diff --git a/julia-0.6.3/LICENSE.md b/julia-0.6.3/LICENSE.md deleted file mode 100644 index 1d812d2..0000000 --- a/julia-0.6.3/LICENSE.md +++ /dev/null @@ -1,94 +0,0 @@ -The Julia language is licensed under the MIT License. The "language" consists -of the compiler (the contents of src/), most of the standard library (base/), -and some utilities (most of the rest of the files in this repository). See below -for exceptions. - -> Copyright (c) 2009-2016: Jeff Bezanson, Stefan Karpinski, Viral B. Shah, -> and other contributors: -> -> https://github.com/JuliaLang/julia/contributors -> -> 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 -> NONINFRINGEMENT. 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. - -Julia includes code from the following projects, which have their own licenses: - -- [crc32c.c](http://stackoverflow.com/questions/17645167/implementing-sse-4-2s-crc32c-in-software) (CRC-32c checksum code by Mark Adler) [[ZLib](https://opensource.org/licenses/Zlib)]. -- [LDC](https://github.com/ldc-developers/ldc/blob/master/LICENSE) (for ccall/cfunction ABI definitions) [BSD-3]. The portion of code that Julia uses from LDC is [BSD-3] licensed. -- [LLVM](http://releases.llvm.org/3.9.0/LICENSE.TXT) (for parts of src/jitlayers.cpp and src/disasm.cpp) [BSD-3, effectively] -- [MUSL](http://git.musl-libc.org/cgit/musl/tree/COPYRIGHT) (for getopt implementation on Windows) [MIT] -- [MINGW](https://sourceforge.net/p/mingw/mingw-org-wsl/ci/legacy/tree/mingwrt/mingwex/dirname.c) (for dirname implementation on Windows) [MIT] -- [NetBSD](http://www.netbsd.org/about/redistribution.html) (for setjmp, longjmp, and strptime implementations on Windows) [BSD-3] -- [Python](https://docs.python.org/2/license.html) (for strtod implementation on Windows) [BSD-3, effectively] -- [randmtzig.c](https://github.com/JuliaLang/julia/blob/master/test/perf/micro/randmtzig.c) for Gaussian random number generation (for C benchmarks only) [BSD-3] - -The Julia language links to the following external libraries, which have their -own licenses: - -- [FEMTOLISP](https://github.com/JeffBezanson/femtolisp) [BSD-3] -- [LIBUNWIND](http://git.savannah.gnu.org/gitweb/?p=libunwind.git;a=blob_plain;f=LICENSE;hb=master) [MIT] -- [LIBUV](https://github.com/joyent/libuv/blob/master/LICENSE) [MIT] -- [LLVM](http://releases.llvm.org/3.9.0/LICENSE.TXT) [BSD-3, effectively] -- [UTF8PROC](https://github.com/JuliaLang/utf8proc) [MIT] - - -Julia's standard library uses the following external libraries, which have -their own licenses: - -- [ARPACK](http://www.caam.rice.edu/software/ARPACK/RiceBSD.txt#LICENSE) [BSD-3] -- [DSFMT](http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/SFMT/LICENSE.txt) [BSD-3] -- [OPENLIBM](https://github.com/JuliaLang/openlibm/blob/master/LICENSE.md) [MIT, BSD-2, ISC] -- [OPENSPECFUN](https://github.com/JuliaLang/openspecfun) [MIT, public domain] -- [FADDEEVA](http://ab-initio.mit.edu/Faddeeva) [MIT] -- [FFTW](http://fftw.org/doc/License-and-Copyright.html) [GPL2+] -- [GMP](http://gmplib.org/manual/Copying.html#Copying) [LGPL3+ or GPL2+] -- [LIBGIT2](https://github.com/libgit2/libgit2/blob/development/COPYING) [GPL2+ with unlimited linking exception] -- [CURL](https://curl.haxx.se/docs/copyright.html) [MIT/X derivative] -- [LIBSSH2](https://github.com/libssh2/libssh2/blob/master/COPYING) [BSD-3] -- [MBEDTLS](https://tls.mbed.org/how-to-get) [either GPLv2 or Apache 2.0] -- [MPFR](http://www.mpfr.org/mpfr-current/mpfr.html#Copying) [LGPL3+] -- [OPENBLAS](https://raw.github.com/xianyi/OpenBLAS/master/LICENSE) [BSD-3] -- [LAPACK](http://netlib.org/lapack/LICENSE.txt) [BSD-3] -- [PCRE](http://www.pcre.org/licence.txt) [BSD-3] -- [SUITESPARSE](http://faculty.cse.tamu.edu/davis/suitesparse.html) [mix of LGPL2+ and GPL2+; see individual module licenses] - - -The following components of Julia's standard library have separate licenses: - -- base/grisu/* (see [double-conversion](https://github.com/google/double-conversion/blob/master/LICENSE)) -- base/sparse/umfpack.jl (see [SUITESPARSE](http://faculty.cse.tamu.edu/davis/suitesparse.html)) -- base/sparse/cholmod.jl (see [SUITESPARSE](http://faculty.cse.tamu.edu/davis/suitesparse.html)) -- base/special/exp.jl (see [FREEBSD MSUN](https://github.com/freebsd/freebsd) [FreeBSD/2-clause BSD/Simplified BSD License]) - - -Julia's build process uses the following external tools: - -- [PATCHELF](http://hydra.nixos.org/build/1524660/download/1/README) -- [OBJCONV](http://www.agner.org/optimize/#objconv) - - -Julia bundles the following external programs and libraries on some platforms: - -- [7-Zip](http://www.7-zip.org/license.txt) -- [BUSYBOX](https://github.com/rmyorston/busybox-w32/blob/master/LICENSE) -- [ZLIB](http://zlib.net/zlib_license.html) -- [LIBEXPAT](http://expat.cvs.sourceforge.net/viewvc/expat/expat/README) - -On some platforms, distributions of Julia contain SSL certificate authority certificates, -released under the [Mozilla Public License](https://en.wikipedia.org/wiki/Mozilla_Public_License). diff --git a/julia-0.6.3/bin/julia b/julia-0.6.3/bin/julia deleted file mode 100755 index 49799ea..0000000 Binary files a/julia-0.6.3/bin/julia and /dev/null differ diff --git a/julia-0.6.3/bin/julia-debug b/julia-0.6.3/bin/julia-debug deleted file mode 100755 index 8d56e78..0000000 Binary files a/julia-0.6.3/bin/julia-debug and /dev/null differ diff --git a/julia-0.6.3/etc/julia/juliarc.jl b/julia-0.6.3/etc/julia/juliarc.jl deleted file mode 100644 index 3993e62..0000000 --- a/julia-0.6.3/etc/julia/juliarc.jl +++ /dev/null @@ -1,3 +0,0 @@ -# This file should contain site-specific commands to be executed on Julia startup -# Users may store their own personal commands in the user home directory `homedir()`, in a file named `.juliarc.jl` - diff --git a/julia-0.6.3/include/julia/END.h b/julia-0.6.3/include/julia/END.h deleted file mode 100644 index 3f551ac..0000000 --- a/julia-0.6.3/include/julia/END.h +++ /dev/null @@ -1,55 +0,0 @@ -/*- - * Copyright (c) 1990 The Regents of the University of California. - * All rights reserved. - * - * This code is derived from software contributed to Berkeley by - * William Jolitz. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 4. Neither the name of the University nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS - * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) - * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT - * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY - * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. - * - * from: @(#)DEFS.h 5.1 (Berkeley) 4/23/90 - * $FreeBSD: src/sys/i386/include/asm.h,v 1.14 2007/08/22 04:26:07 jkoshy Exp $ - */ - -#if defined(__linux__) || defined(__FreeBSD__) || defined(__ELF__) -.size CNAME, . - CNAME -#else -#ifndef _MSC_VER -.end -#else -CNAME endp -end -#endif -#endif - -#undef CNAME -#undef HIDENAME -#undef STR -#undef XSTR -#undef _START_ENTRY -#ifndef __APPLE__ -#undef EXT_ -#undef EXT -#endif diff --git a/julia-0.6.3/include/julia/ENTRY.amd64.h b/julia-0.6.3/include/julia/ENTRY.amd64.h deleted file mode 100644 index 4ad13fc..0000000 --- a/julia-0.6.3/include/julia/ENTRY.amd64.h +++ /dev/null @@ -1,75 +0,0 @@ -/*- - * Copyright (c) 1990 The Regents of the University of California. - * All rights reserved. - * - * This code is derived from software contributed to Berkeley by - * William Jolitz. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 4. Neither the name of the University nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS - * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) - * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT - * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY - * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. - * - * from: @(#)DEFS.h 5.1 (Berkeley) 4/23/90 - * $FreeBSD: src/sys/amd64/include/asm.h,v 1.18 2007/08/22 04:26:07 jkoshy Exp $ - */ - -#define _START_ENTRY .p2align 4,0x90 -#define STR(csym) #csym -#define XSTR(csym) STR(csym) -#if defined(__linux__) || defined(__FreeBSD__) || defined(__ELF__) -#ifndef __APPLE__ -#define EXT_(csym) csym -#define EXT(csym) EXT_(csym) -#endif -#define HIDENAME(asmsym) .asmsym -.text -_START_ENTRY -.globl EXT(CNAME) -.type EXT(CNAME),@function -EXT(CNAME): - -#elif defined(_WIN32) -#define EXT_(csym) csym -#define EXT(csym) EXT_(csym) -#define HIDENAME(asmsym) .asmsym - -#ifndef _MSC_VER -.intel_syntax noprefix -.text -_START_ENTRY -.globl EXT(CNAME) -.section .drectve -.ascii " -export:" -.ascii XSTR(CNAME) -.section .text -.def EXT(CNAME) -.scl 2 -.type 32 -.endef -EXT(CNAME): -#else -.code -CNAME proc -#endif - -#endif diff --git a/julia-0.6.3/include/julia/ENTRY.i387.h b/julia-0.6.3/include/julia/ENTRY.i387.h deleted file mode 100644 index d800386..0000000 --- a/julia-0.6.3/include/julia/ENTRY.i387.h +++ /dev/null @@ -1,76 +0,0 @@ -/*- - * Copyright (c) 1990 The Regents of the University of California. - * All rights reserved. - * - * This code is derived from software contributed to Berkeley by - * William Jolitz. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 4. Neither the name of the University nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS - * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) - * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT - * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY - * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. - * - * from: @(#)DEFS.h 5.1 (Berkeley) 4/23/90 - * $FreeBSD: src/sys/i386/include/asm.h,v 1.14 2007/08/22 04:26:07 jkoshy Exp $ - */ - -#define _START_ENTRY .p2align 2,0x90 -#define STR(csym) #csym -#define XSTR(csym) STR(csym) -#if defined(__linux__) || defined(__FreeBSD__) || defined(__ELF__) -#ifndef __APPLE__ -#define EXT_(csym) csym -#define EXT(csym) EXT_(csym) -#endif -#define HIDENAME(asmsym) .asmsym -.text -_START_ENTRY -.globl EXT(CNAME) -.type EXT(CNAME),@function -EXT(CNAME): - -#elif defined(_WIN32) -#define EXT_(csym) _##csym -#define EXT(csym) EXT_(csym) -#define HIDENAME(asmsym) .asmsym - -#ifndef _MSC_VER -.intel_syntax -.text -_START_ENTRY -.globl EXT(CNAME) -.section .drectve -.ascii " -export:", XSTR(CNAME) -.section .text -.def EXT(CNAME) -.scl 2 -.type 32 -.endef -EXT(CNAME): -#else -.586 -.model small,C -.code -CNAME proc -#endif - -#endif diff --git a/julia-0.6.3/include/julia/MurmurHash3.h b/julia-0.6.3/include/julia/MurmurHash3.h deleted file mode 100644 index 7f29e4d..0000000 --- a/julia-0.6.3/include/julia/MurmurHash3.h +++ /dev/null @@ -1,22 +0,0 @@ -//----------------------------------------------------------------------------- -// MurmurHash3 was written by Austin Appleby, and is placed in the public -// domain. The author hereby disclaims copyright to this source code. - -#ifndef MURMURHASH3_H -#define MURMURHASH3_H - -//----------------------------------------------------------------------------- -// Platform-specific functions and macros -#include - -//----------------------------------------------------------------------------- - -void MurmurHash3_x86_32 ( const void * key, int len, uint32_t seed, void * out ); - -void MurmurHash3_x86_128 ( const void * key, int len, uint32_t seed, void * out ); - -void MurmurHash3_x64_128 ( const void * key, int len, uint32_t seed, void * out ); - -//----------------------------------------------------------------------------- - -#endif // MURMURHASH3_H diff --git a/julia-0.6.3/include/julia/arraylist.h b/julia-0.6.3/include/julia/arraylist.h deleted file mode 100644 index 61ffba1..0000000 --- a/julia-0.6.3/include/julia/arraylist.h +++ /dev/null @@ -1,30 +0,0 @@ -// This file is a part of Julia. License is MIT: https://julialang.org/license - -#ifndef ARRAYLIST_H -#define ARRAYLIST_H - -#define AL_N_INLINE 29 - -#ifdef __cplusplus -extern "C" { -#endif - -typedef struct { - size_t len; - size_t max; - void **items; - void *_space[AL_N_INLINE]; -} arraylist_t; - -arraylist_t *arraylist_new(arraylist_t *a, size_t size); -void arraylist_free(arraylist_t *a); - -void arraylist_push(arraylist_t *a, void *elt); -void *arraylist_pop(arraylist_t *a); -void arraylist_grow(arraylist_t *a, size_t n); - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/julia-0.6.3/include/julia/bitvector.h b/julia-0.6.3/include/julia/bitvector.h deleted file mode 100644 index 76c4bde..0000000 --- a/julia-0.6.3/include/julia/bitvector.h +++ /dev/null @@ -1,22 +0,0 @@ -// This file is a part of Julia. License is MIT: https://julialang.org/license - -#ifndef BITVECTOR_H -#define BITVECTOR_H - -#ifdef __cplusplus -extern "C" { -#endif - -JL_DLLEXPORT uint32_t *bitvector_new(uint64_t n, int initzero); -JL_DLLEXPORT -uint32_t *bitvector_resize(uint32_t *b, uint64_t oldsz, uint64_t newsz, - int initzero); -size_t bitvector_nwords(uint64_t nbits); -JL_DLLEXPORT void bitvector_set(uint32_t *b, uint64_t n, uint32_t c); -JL_DLLEXPORT uint32_t bitvector_get(uint32_t *b, uint64_t n); - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/julia-0.6.3/include/julia/crc32c.h b/julia-0.6.3/include/julia/crc32c.h deleted file mode 100644 index 9dbf41c..0000000 --- a/julia-0.6.3/include/julia/crc32c.h +++ /dev/null @@ -1,19 +0,0 @@ -// This file is a part of Julia. License is MIT: https://julialang.org/license - -#ifndef CRC32C_H -#define CRC32C_H 1 - -#include "dtypes.h" - -#ifdef __cplusplus -extern "C" { -#endif - -JL_DLLEXPORT void jl_crc32c_init(int force_sw); -JL_DLLEXPORT uint32_t jl_crc32c(uint32_t crc, const void *buf, size_t len); - -#ifdef __cplusplus -} -#endif - -#endif /* CRC32C_H */ diff --git a/julia-0.6.3/include/julia/dirpath.h b/julia-0.6.3/include/julia/dirpath.h deleted file mode 100644 index ec31dbe..0000000 --- a/julia-0.6.3/include/julia/dirpath.h +++ /dev/null @@ -1,20 +0,0 @@ -// This file is a part of Julia. License is MIT: https://julialang.org/license - -#ifndef DIRPATH_H -#define DIRPATH_H - -#ifdef _OS_WINDOWS_ -#define PATHSEPSTRING "\\" -#define PATHLISTSEPSTRING ";" -#if defined(_MSC_VER) || defined(_COMPILER_CLANG_) -#define PATH_MAX MAX_PATH -#endif -#else -#define PATHSEPSTRING "/" -#define PATHLISTSEPSTRING ":" -#ifndef PATH_MAX // many platforms don't have a max path, we define one anyways -#define PATH_MAX 1024 -#endif -#endif - -#endif diff --git a/julia-0.6.3/include/julia/dtypes.h b/julia-0.6.3/include/julia/dtypes.h deleted file mode 100644 index a3aa489..0000000 --- a/julia-0.6.3/include/julia/dtypes.h +++ /dev/null @@ -1,217 +0,0 @@ -// This file is a part of Julia. License is MIT: https://julialang.org/license - -#ifndef DTYPES_H -#define DTYPES_H - -#include -#include // double include of stddef.h fixes #3421 -#include -#if defined(_COMPILER_INTEL_) -#include -#else -#include -#endif - -#include "platform.h" - -#if !defined(_OS_WINDOWS_) -#include -#endif - -#if defined(_OS_WINDOWS_) - -#include -#include -#include - -#if !defined(_COMPILER_MINGW_) - -#define strtoull _strtoui64 -#define strtoll _strtoi64 -#define strcasecmp _stricmp -#define strncasecmp _strnicmp -#define snprintf _snprintf -#define stat _stat - -#define STDIN_FILENO 0 -#define STDOUT_FILENO 1 -#define STDERR_FILENO 2 - -#endif /* !_COMPILER_MINGW_ */ - -#endif /* _OS_WINDOWS_ */ - - -/* - This file defines sane integer types for our target platforms. This - library only runs on machines with the following characteristics: - - - supports integer word sizes of 8, 16, 32, and 64 bits - - uses unsigned and signed 2's complement representations - - all pointer types are the same size - - there is an integer type with the same size as a pointer - - Some features require: - - IEEE 754 single- and double-precision floating point - - We assume the LP64 convention for 64-bit platforms. -*/ - -#ifdef _OS_WINDOWS_ -#define STDCALL __stdcall -# ifdef LIBRARY_EXPORTS -# define JL_DLLEXPORT __declspec(dllexport) -# else -# define JL_DLLEXPORT __declspec(dllimport) -# endif -#else -#define STDCALL -#define JL_DLLEXPORT __attribute__ ((visibility("default"))) -#endif - -#ifdef _OS_LINUX_ -#include -#define LITTLE_ENDIAN __LITTLE_ENDIAN -#define BIG_ENDIAN __BIG_ENDIAN -#define PDP_ENDIAN __PDP_ENDIAN -#define BYTE_ORDER __BYTE_ORDER -#endif - -#if defined(__APPLE__) || defined(__FreeBSD__) -#include -#define __LITTLE_ENDIAN LITTLE_ENDIAN -#define __BIG_ENDIAN BIG_ENDIAN -#define __PDP_ENDIAN PDP_ENDIAN -#define __BYTE_ORDER BYTE_ORDER -#endif - -#ifdef _OS_WINDOWS_ -#define __LITTLE_ENDIAN 1234 -#define __BIG_ENDIAN 4321 -#define __PDP_ENDIAN 3412 -#define __BYTE_ORDER __LITTLE_ENDIAN -#define __FLOAT_WORD_ORDER __LITTLE_ENDIAN -#define LITTLE_ENDIAN __LITTLE_ENDIAN -#define BIG_ENDIAN __BIG_ENDIAN -#define PDP_ENDIAN __PDP_ENDIAN -#define BYTE_ORDER __BYTE_ORDER -#endif - -#define LLT_ALLOC(n) malloc(n) -#define LLT_REALLOC(p,n) realloc((p),(n)) -#define LLT_FREE(x) free(x) - -#if defined(_OS_WINDOWS_) && defined(_COMPILER_INTEL_) -# define STATIC_INLINE static -# define INLINE -#elif defined(_OS_WINDOWS_) && defined(_COMPILER_MICROSOFT_) -# define STATIC_INLINE static __inline -# define INLINE __inline -#else -# define STATIC_INLINE static inline -# define INLINE inline -#endif - -#if defined(_OS_WINDOWS_) && !defined(_COMPILER_MINGW_) -# define NOINLINE __declspec(noinline) -# define NOINLINE_DECL(f) __declspec(noinline) f -#else -# define NOINLINE __attribute__((noinline)) -# define NOINLINE_DECL(f) f __attribute__((noinline)) -#endif - -#ifdef _COMPILER_MICROSOFT_ -# ifdef _P64 -# define JL_ATTRIBUTE_ALIGN_PTRSIZE(x) __declspec(align(8)) x -# else -# define JL_ATTRIBUTE_ALIGN_PTRSIZE(x) __declspec(align(4)) x -# endif -#elif defined(__GNUC__) -# define JL_ATTRIBUTE_ALIGN_PTRSIZE(x) x __attribute__ ((aligned (sizeof(void*)))) -#else -# define JL_ATTRIBUTE_ALIGN_PTRSIZE(x) -#endif - -typedef int bool_t; -typedef unsigned char byte_t; /* 1 byte */ - -#ifdef _P64 -#define TOP_BIT 0x8000000000000000 -#define NBITS 64 -typedef uint64_t uint_t; // preferred int type on platform -typedef int64_t int_t; -#else -#define TOP_BIT 0x80000000 -#define NBITS 32 -typedef uint32_t uint_t; -typedef int32_t int_t; -#endif - -STATIC_INLINE unsigned int next_power_of_two(unsigned int val) -{ - /* this function taken from libuv src/unix/core.c */ - val -= 1; - val |= val >> 1; - val |= val >> 2; - val |= val >> 4; - val |= val >> 8; - val |= val >> 16; - val += 1; - return val; -} - -#define LLT_ALIGN(x, sz) (((x) + (sz)-1) & -(sz)) - -// branch prediction annotations -#ifdef __GNUC__ -#define __unlikely(x) __builtin_expect(!!(x), 0) -#define __likely(x) __builtin_expect(!!(x), 1) -#else -#define __unlikely(x) (x) -#define __likely(x) (x) -#endif - -#define DBL_MAXINT 9007199254740992LL -#define FLT_MAXINT 16777216 -#define U64_MAX 18446744073709551615ULL -#define S64_MAX 9223372036854775807LL -#define S64_MIN (-S64_MAX - 1LL) -#define BIT63 0x8000000000000000LL -#define U32_MAX 4294967295L -#define S32_MAX 2147483647L -#define S32_MIN (-S32_MAX - 1L) -#define BIT31 0x80000000 - -#define D_PNAN ((double)+NAN) -#define D_NNAN ((double)-NAN) -#define D_PINF ((double)+INFINITY) -#define D_NINF ((double)-INFINITY) -#define F_PNAN ((float)+NAN) -#define F_NNAN ((float)-NAN) -#define F_PINF ((float)+INFINITY) -#define F_NINF ((float)-INFINITY) - -typedef enum { T_INT8, T_UINT8, T_INT16, T_UINT16, T_INT32, T_UINT32, - T_INT64, T_UINT64, T_FLOAT, T_DOUBLE } numerictype_t; - -#define N_NUMTYPES ((int)T_DOUBLE+1) - -#ifdef _P64 -# define T_PTRDIFF T_INT64 -# define T_SIZE T_UINT64 -#else -# define T_PTRDIFF T_INT32 -# define T_SIZE T_UINT32 -#endif - -#if defined(__GNUC__) && __GNUC__ >= 7 -#define JL_FALLTHROUGH __attribute__((fallthrough)) -#elif defined(__cplusplus) && defined(__clang_major__) && \ - defined(__clang_minor__) && (__clang_major__ > 4 || __clang_minor__ >= 5) -// We require at least clang 3.x -#define JL_FALLTHROUGH [[clang::fallthrough]] -#else -#define JL_FALLTHROUGH -#endif - -#endif /* DTYPES_H */ diff --git a/julia-0.6.3/include/julia/hashing.h b/julia-0.6.3/include/julia/hashing.h deleted file mode 100644 index 9532a35..0000000 --- a/julia-0.6.3/include/julia/hashing.h +++ /dev/null @@ -1,44 +0,0 @@ -// This file is a part of Julia. License is MIT: https://julialang.org/license - -#ifndef HASHING_H -#define HASHING_H - -#include "utils.h" -#include "dtypes.h" - -#ifdef __cplusplus -extern "C" { -#endif - -uint_t nextipow2(uint_t i); -JL_DLLEXPORT uint32_t int32hash(uint32_t a); -JL_DLLEXPORT uint64_t int64hash(uint64_t key); -JL_DLLEXPORT uint32_t int64to32hash(uint64_t key); -#ifdef _P64 -#define inthash int64hash -#else -#define inthash int32hash -#endif -JL_DLLEXPORT uint64_t memhash(const char *buf, size_t n); -JL_DLLEXPORT uint64_t memhash_seed(const char *buf, size_t n, uint32_t seed); -JL_DLLEXPORT uint32_t memhash32(const char *buf, size_t n); -JL_DLLEXPORT uint32_t memhash32_seed(const char *buf, size_t n, uint32_t seed); - -#ifdef _P64 -STATIC_INLINE uint64_t bitmix(uint64_t a, uint64_t b) -{ - return int64hash(a^bswap_64(b)); -} -#else -STATIC_INLINE uint32_t bitmix(uint32_t a, uint32_t b) -{ - return int64to32hash((((uint64_t)a) << 32) | (uint64_t)b); -} -#endif -#define bitmix(a, b) (bitmix)((uintptr_t)(a), (uintptr_t)(b)) - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/julia-0.6.3/include/julia/htable.h b/julia-0.6.3/include/julia/htable.h deleted file mode 100644 index 968ffb2..0000000 --- a/julia-0.6.3/include/julia/htable.h +++ /dev/null @@ -1,48 +0,0 @@ -// This file is a part of Julia. License is MIT: https://julialang.org/license - -#ifndef HTABLE_H -#define HTABLE_H - -#define HT_N_INLINE 32 - -#ifdef __cplusplus -extern "C" { -#endif - -typedef struct { - size_t size; - void **table; - void *_space[HT_N_INLINE]; -} htable_t; - -// define this to be an invalid key/value -#define HT_NOTFOUND ((void*)1) - -// initialize and free -htable_t *htable_new(htable_t *h, size_t size); -void htable_free(htable_t *h); - -// clear and (possibly) change size -void htable_reset(htable_t *h, size_t sz); - -#define HTPROT(HTNAME) \ -void *HTNAME##_get(htable_t *h, void *key); \ -void HTNAME##_put(htable_t *h, void *key, void *val); \ -void HTNAME##_adjoin(htable_t *h, void *key, void *val); \ -int HTNAME##_has(htable_t *h, void *key); \ -int HTNAME##_remove(htable_t *h, void *key); \ -void **HTNAME##_bp(htable_t *h, void *key); - -#define HTPROT_R(HTNAME) \ -void *HTNAME##_get_r(htable_t *h, void *key, void *ctx); \ -void HTNAME##_put_r(htable_t *h, void *key, void *val, void *ctx); \ -void HTNAME##_adjoin_r(htable_t *h, void *key, void *val, void *ctx); \ -int HTNAME##_has_r(htable_t *h, void *key, void *ctx); \ -int HTNAME##_remove_r(htable_t *h, void *key, void *ctx); \ -void **HTNAME##_bp_r(htable_t *h, void *key, void *ctx); - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/julia-0.6.3/include/julia/ios.h b/julia-0.6.3/include/julia/ios.h deleted file mode 100644 index be14701..0000000 --- a/julia-0.6.3/include/julia/ios.h +++ /dev/null @@ -1,214 +0,0 @@ -// This file is a part of Julia. License is MIT: https://julialang.org/license - -#ifndef IOS_H -#define IOS_H - -#include -#include "uv.h" - -#ifdef __cplusplus -extern "C" { -#endif - -// this flag controls when data actually moves out to the underlying I/O -// channel. memory streams are a special case of this where the data -// never moves out. - -//make it compatible with UV Handles -typedef enum { bm_none=UV_HANDLE_TYPE_MAX+1, bm_line, bm_block, bm_mem } bufmode_t; -typedef enum { bst_none, bst_rd, bst_wr } bufstate_t; - -#define IOS_INLSIZE 54 -#define IOS_BUFSIZE 131072 - -typedef struct { - // the state only indicates where the underlying file position is relative - // to the buffer. reading: at the end. writing: at the beginning. - // in general, you can do any operation in any state. - char *buf; // start of buffer - - int errcode; - -#ifdef _P64 - int _pad_bm; // put bm at same offset as type field of uv_stream_s -#endif - bufmode_t bm; // - bufstate_t state; - - int64_t maxsize; // space allocated to buffer - int64_t size; // length of valid data in buf, >=ndirty - int64_t bpos; // current position in buffer - int64_t ndirty; // # bytes at &buf[0] that need to be written - - int64_t fpos; // cached file pos - size_t lineno; // current line number - - // pointer-size integer to support platforms where it might have - // to be a pointer - long fd; - - unsigned char readable:1; - unsigned char writable:1; - unsigned char ownbuf:1; - unsigned char ownfd:1; - unsigned char _eof:1; - - // this means you can read, seek back, then read the same data - // again any number of times. usually only true for files and strings. - unsigned char rereadable:1; - - // this enables "stenciled writes". you can alternately write and - // seek without flushing in between. this performs read-before-write - // to populate the buffer, so "rereadable" capability is required. - // this is off by default. - //unsigned char stenciled:1; - - // request durable writes (fsync) - // unsigned char durable:1; - - int64_t userdata; - char local[IOS_INLSIZE]; -} ios_t; - -extern void (*ios_set_io_wait_func)(int); -/* low-level interface functions */ -JL_DLLEXPORT size_t ios_read(ios_t *s, char *dest, size_t n); -JL_DLLEXPORT size_t ios_readall(ios_t *s, char *dest, size_t n); -JL_DLLEXPORT size_t ios_write(ios_t *s, const char *data, size_t n); -JL_DLLEXPORT int64_t ios_seek(ios_t *s, int64_t pos); // absolute seek -JL_DLLEXPORT int64_t ios_seek_end(ios_t *s); -JL_DLLEXPORT int64_t ios_skip(ios_t *s, int64_t offs); // relative seek -JL_DLLEXPORT int64_t ios_pos(ios_t *s); // get current position -JL_DLLEXPORT int ios_trunc(ios_t *s, size_t size); -JL_DLLEXPORT int ios_eof(ios_t *s); -JL_DLLEXPORT int ios_eof_blocking(ios_t *s); -JL_DLLEXPORT int ios_flush(ios_t *s); -JL_DLLEXPORT void ios_close(ios_t *s); -JL_DLLEXPORT int ios_isopen(ios_t *s); -JL_DLLEXPORT char *ios_take_buffer(ios_t *s, size_t *psize); // release buffer to caller -// set buffer space to use -JL_DLLEXPORT int ios_setbuf(ios_t *s, char *buf, size_t size, int own); -JL_DLLEXPORT int ios_bufmode(ios_t *s, bufmode_t mode); -JL_DLLEXPORT int ios_get_readable(ios_t *s); -JL_DLLEXPORT int ios_get_writable(ios_t *s); -JL_DLLEXPORT void ios_set_readonly(ios_t *s); -JL_DLLEXPORT size_t ios_copy(ios_t *to, ios_t *from, size_t nbytes); -JL_DLLEXPORT size_t ios_copyall(ios_t *to, ios_t *from); -JL_DLLEXPORT size_t ios_copyuntil(ios_t *to, ios_t *from, char delim); -JL_DLLEXPORT size_t ios_nchomp(ios_t *from, size_t ntowrite); -// ensure at least n bytes are buffered if possible. returns # available. -JL_DLLEXPORT size_t ios_readprep(ios_t *from, size_t n); - -/* stream creation */ -JL_DLLEXPORT -ios_t *ios_file(ios_t *s, const char *fname, int rd, int wr, int create, int trunc); -JL_DLLEXPORT ios_t *ios_mkstemp(ios_t *f, char *fname); -JL_DLLEXPORT ios_t *ios_mem(ios_t *s, size_t initsize); -ios_t *ios_str(ios_t *s, char *str); -ios_t *ios_static_buffer(ios_t *s, char *buf, size_t sz); -JL_DLLEXPORT ios_t *ios_fd(ios_t *s, long fd, int isfile, int own); -// todo: ios_socket -extern JL_DLLEXPORT ios_t *ios_stdin; -extern JL_DLLEXPORT ios_t *ios_stdout; -extern JL_DLLEXPORT ios_t *ios_stderr; -void ios_init_stdstreams(void); - -/* high-level functions - output */ -JL_DLLEXPORT int ios_pututf8(ios_t *s, uint32_t wc); -JL_DLLEXPORT int ios_printf(ios_t *s, const char *format, ...); -JL_DLLEXPORT int ios_vprintf(ios_t *s, const char *format, va_list args); - -/* high-level stream functions - input */ -JL_DLLEXPORT int ios_getutf8(ios_t *s, uint32_t *pwc); -JL_DLLEXPORT int ios_peekutf8(ios_t *s, uint32_t *pwc); -JL_DLLEXPORT char *ios_readline(ios_t *s); - -// discard data buffered for reading -JL_DLLEXPORT void ios_purge(ios_t *s); - -/* stdio-style functions */ -#define IOS_EOF (-1) -JL_DLLEXPORT int ios_putc(int c, ios_t *s); -//wint_t ios_putwc(ios_t *s, wchar_t wc); -JL_DLLEXPORT int ios_getc(ios_t *s); -JL_DLLEXPORT int ios_peekc(ios_t *s); -//wint_t ios_getwc(ios_t *s); -int ios_ungetc(int c, ios_t *s); -//wint_t ios_ungetwc(ios_t *s, wint_t wc); -#define ios_puts(str, s) ios_write(s, str, strlen(str)) - -/* - With memory streams, mixed reads and writes are equivalent to performing - sequences of *p++, as either an lvalue or rvalue. File streams behave - similarly, but other streams might not support this. Using unbuffered - mode makes this more predictable. - - Note on "unget" functions: - There are two kinds of functions here: those that operate on sized - blocks of bytes and those that operate on logical units like "character" - or "integer". The "unget" functions only work on logical units. There - is no "unget n bytes". You can only do an unget after a matching get. - However, data pushed back by an unget is available to all read operations. - The reason for this is that unget is defined in terms of its effect on - the underlying buffer (namely, it rebuffers data as if it had been - buffered but not read yet). IOS reserves the right to perform large block - operations directly, bypassing the buffer. In such a case data was - never buffered, so "rebuffering" has no meaning (i.e. there is no - correspondence between the buffer and the physical stream). - - Single-bit I/O is able to write partial bytes ONLY IF the stream supports - seeking. Also, line buffering is not well-defined in the context of - single-bit I/O, so it might not do what you expect. - - implementation notes: - in order to know where we are in a file, we must ensure the buffer - is only populated from the underlying stream starting with p==buf. - - to switch from writing to reading: flush, set p=buf, cnt=0 - to switch from reading to writing: seek backwards cnt bytes, p=buf, cnt=0 - - when writing: buf starts at curr. physical stream pos, p - buf is how - many bytes we've written logically. cnt==0 - - dirty == (bitpos>0 && state==iost_wr), EXCEPT right after switching from - reading to writing, where we might be in the middle of a byte without - having changed it. - - to write a bit: if !dirty, read up to maxsize-(p-buf) into buffer, then - seek back by the same amount (undo it). write onto those bits. now set - the dirty bit. in this state, we can bit-read up to the end of the byte, - then formally switch to the read state using flush. - - design points: - - data-source independence, including memory streams - - expose buffer to user, allow user-owned buffers - - allow direct I/O, don't always go through buffer - - buffer-internal seeking. makes seeking back 1-2 bytes very fast, - and makes it possible for sockets where it otherwise wouldn't be - - tries to allow switching between reading and writing - - support 64-bit and large files - - efficient, low-latency buffering - - special support for utf8 - - type-aware functions with byte-order swapping service - - position counter for meaningful data offsets with sockets - - theory of operation: - - the buffer is a view of part of a file/stream. you can seek, read, and - write around in it as much as you like, as if it were just a string. - - we keep track of the part of the buffer that's invalid (written to). - we remember whether the position of the underlying stream is aligned - with the end of the buffer (reading mode) or the beginning (writing mode). - - based on this info, we might have to seek back before doing a flush. - - as optimizations, we do no writing if the buffer isn't "dirty", and we - do no reading if the data will only be overwritten. -*/ - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/julia-0.6.3/include/julia/julia.h b/julia-0.6.3/include/julia/julia.h deleted file mode 100644 index 7b9c2e7..0000000 --- a/julia-0.6.3/include/julia/julia.h +++ /dev/null @@ -1,1844 +0,0 @@ -// This file is a part of Julia. License is MIT: https://julialang.org/license - -#ifndef JULIA_H -#define JULIA_H - -//** Configuration options that affect the Julia ABI **// -// if this is not defined, only individual dimension sizes are -// stored and not total length, to save space. -#define STORE_ARRAY_LEN -//** End Configuration options **// - -#include "libsupport.h" -#include -#include - -#include "htable.h" -#include "arraylist.h" - -#include -#ifndef _OS_WINDOWS_ -# define jl_jmp_buf sigjmp_buf -# if defined(_CPU_ARM_) || defined(_CPU_PPC_) -# define MAX_ALIGN 8 -# elif defined(_CPU_AARCH64_) -// int128 is 16 bytes aligned on aarch64 -# define MAX_ALIGN 16 -# else -# define MAX_ALIGN sizeof(void*) -# endif -#else -# define jl_jmp_buf jmp_buf -# include //for _resetstkoflw -# define MAX_ALIGN 8 -#endif - -#ifdef _P64 -#define NWORDS(sz) (((sz)+7)>>3) -#else -#define NWORDS(sz) (((sz)+3)>>2) -#endif - -#if defined(__GNUC__) -# define JL_NORETURN __attribute__ ((noreturn)) -# define JL_CONST_FUNC __attribute__((const)) -#elif defined(_COMPILER_MICROSOFT_) -# define JL_NORETURN __declspec(noreturn) -// This is the closest I can find for __attribute__((const)) -# define JL_CONST_FUNC __declspec(noalias) -#else -# define JL_NORETURN -# define JL_CONST_FUNC -#endif - -#define container_of(ptr, type, member) \ - ((type *) ((char *)(ptr) - offsetof(type, member))) - -typedef struct _jl_taggedvalue_t jl_taggedvalue_t; - -#include - -#ifdef __cplusplus -extern "C" { -#endif - -// core data types ------------------------------------------------------------ - -// the common fields are hidden before the pointer, but the following macro is -// used to indicate which types below are subtypes of jl_value_t -#define JL_DATA_TYPE - -typedef struct _jl_value_t jl_value_t; - -struct _jl_taggedvalue_bits { - uintptr_t gc:2; -}; - -struct _jl_taggedvalue_t { - union { - uintptr_t header; - jl_taggedvalue_t *next; - jl_value_t *type; // 16-byte aligned - struct _jl_taggedvalue_bits bits; - }; - // jl_value_t value; -}; - -#define jl_astaggedvalue(v) \ - ((jl_taggedvalue_t*)((char*)(v) - sizeof(jl_taggedvalue_t))) -#define jl_valueof(v) \ - ((jl_value_t*)((char*)(v) + sizeof(jl_taggedvalue_t))) -#define jl_typeof(v) \ - ((jl_value_t*)(jl_astaggedvalue(v)->header & ~(uintptr_t)15)) -static inline void jl_set_typeof(void *v, void *t) -{ - // Do not call this on a value that is already initialized. - jl_taggedvalue_t *tag = jl_astaggedvalue(v); - tag->type = (jl_value_t*)t; -} -#define jl_typeis(v,t) (jl_typeof(v)==(jl_value_t*)(t)) - -// Symbols are interned strings (hash-consed) stored as an invasive binary tree. -// The string data is nul-terminated and hangs off the end of the struct. -typedef struct _jl_sym_t { - JL_DATA_TYPE - struct _jl_sym_t *left; - struct _jl_sym_t *right; - uintptr_t hash; // precomputed hash value - // JL_ATTRIBUTE_ALIGN_PTRSIZE(char name[]); -} jl_sym_t; - -// A numbered SSA value, for optimized code analysis and generation -// the `id` is a unique, small number -typedef struct _jl_ssavalue_t { - JL_DATA_TYPE - ssize_t id; -} jl_ssavalue_t; - -// A SimpleVector is an immutable pointer array -// Data is stored at the end of this variable-length struct. -typedef struct { - JL_DATA_TYPE - size_t length; - // pointer size aligned - // jl_value_t *data[]; -} jl_svec_t; - -typedef struct { - /* - how - allocation style - 0 = data is inlined, or a foreign pointer we don't manage - 1 = julia-allocated buffer that needs to be marked - 2 = malloc-allocated pointer this array object manages - 3 = has a pointer to the object that owns the data - */ - uint16_t how:2; - uint16_t ndims:10; - uint16_t pooled:1; - uint16_t ptrarray:1; // representation is pointer array - uint16_t isshared:1; // data is shared by multiple Arrays - uint16_t isaligned:1; // data allocated with memalign -} jl_array_flags_t; - -typedef struct { - JL_DATA_TYPE - void *data; -#ifdef STORE_ARRAY_LEN - size_t length; -#endif - jl_array_flags_t flags; - uint16_t elsize; - uint32_t offset; // for 1-d only. does not need to get big. - size_t nrows; - union { - // 1d - size_t maxsize; - // Nd - size_t ncols; - }; - // other dim sizes go here for ndims > 2 - - // followed by alignment padding and inline data, or owner pointer -} jl_array_t; - -// compute # of extra words needed to store dimensions -STATIC_INLINE int jl_array_ndimwords(uint32_t ndims) -{ - return (ndims < 3 ? 0 : ndims-2); -} - -typedef struct _jl_datatype_t jl_tupletype_t; -struct _jl_method_instance_t; - -// TypeMap is an implicitly defined type -// that can consist of any of the following nodes: -// typedef TypeMap Union{TypeMapLevel, TypeMapEntry, Void} -// it forms a roughly tree-shaped structure, consisting of nodes of TypeMapLevels -// which split the tree when possible, for example based on the key into the tuple type at `offs` -// when key is a leaftype, (but only when the tree has enough entries for this to be -// more efficient than storing them sorted linearly) -// otherwise the leaf entries are stored sorted, linearly -union jl_typemap_t { - struct _jl_typemap_level_t *node; - struct _jl_typemap_entry_t *leaf; - struct _jl_value_t *unknown; // nothing -}; - -// "jlcall" calling convention signatures. -// This defines the default ABI used by compiled julia functions. -typedef jl_value_t *(*jl_fptr_t)(jl_value_t*, jl_value_t**, uint32_t); -typedef jl_value_t *(*jl_fptr_sparam_t)(jl_svec_t*, jl_value_t*, jl_value_t**, uint32_t); -typedef jl_value_t *(*jl_fptr_linfo_t)(struct _jl_method_instance_t*, jl_value_t**, uint32_t, jl_svec_t*); - -typedef struct { - union { - jl_fptr_t fptr; - jl_fptr_t fptr1; - // constant fptr2; - jl_fptr_sparam_t fptr3; - jl_fptr_linfo_t fptr4; - }; - uint8_t jlcall_api; -} jl_generic_fptr_t; - -typedef struct _jl_llvm_functions_t { - void *functionObject; // jlcall llvm Function - void *specFunctionObject; // specialized llvm Function -} jl_llvm_functions_t; - -// This type describes a single function body -typedef struct _jl_code_info_t { - jl_array_t *code; // Any array of statements - jl_value_t *slottypes; // types of variable slots (or `nothing`) - jl_value_t *ssavaluetypes; // types of ssa values (or count of them) - jl_array_t *slotflags; // local var bit flags - jl_array_t *slotnames; // names of local variables - uint8_t inferred; - uint8_t inlineable; - uint8_t propagate_inbounds; - uint8_t pure; -} jl_code_info_t; - -// This type describes a single method definition, and stores data -// shared by the specializations of a function. -typedef struct _jl_method_t { - JL_DATA_TYPE - jl_sym_t *name; // for error reporting - struct _jl_module_t *module; - jl_sym_t *file; - int32_t line; - - // method's type signature. redundant with TypeMapEntry->specTypes - jl_value_t *sig; - size_t min_world; - - // list of potentially-ambiguous methods (nothing = none, Vector{Any} of Methods otherwise) - jl_value_t *ambig; - - // table of all argument types for which we've inferred or compiled this code - union jl_typemap_t specializations; - - jl_svec_t *sparam_syms; // symbols giving static parameter names - jl_value_t *source; // original code template (jl_code_info_t, but may be compressed), null for builtins - struct _jl_method_instance_t *unspecialized; // unspecialized executable method instance, or null - struct _jl_method_instance_t *generator; // executable code-generating function if isstaged - jl_array_t *roots; // pointers in generated code (shared to reduce memory), or null - - // cache of specializations of this method for invoke(), i.e. - // cases where this method was called even though it was not necessarily - // the most specific for the argument types. - union jl_typemap_t invokes; - - int32_t nargs; - int32_t called; // bit flags: whether each of the first 8 arguments is called - uint8_t isva; - uint8_t isstaged; - uint8_t pure; - -// hidden fields: - uint8_t traced; - // lock for modifications to the method - jl_mutex_t writelock; -} jl_method_t; - -// This type caches the data for a specType signature specialization of a Method -typedef struct _jl_method_instance_t { - JL_DATA_TYPE - jl_value_t *specTypes; // argument types this was specialized for - jl_value_t *rettype; // return type for fptr - jl_svec_t *sparam_vals; // static parameter values, indexed by def->sparam_syms - jl_array_t *backedges; - jl_value_t *inferred; // inferred jl_code_info_t, or value of the function if jlcall_api == 2, or null - jl_value_t *inferred_const; // inferred constant return value, or null - jl_method_t *def; // method this is specialized from, null if this is a toplevel thunk - size_t min_world; - size_t max_world; - uint8_t inInference; // flags to tell if inference is running on this function - uint8_t jlcall_api; // the c-abi for fptr; 0 = jl_fptr_t, 1 = jl_fptr_sparam_t, 2 = constval - uint8_t compile_traced; // if set will notify callback if this linfo is compiled - jl_fptr_t fptr; // jlcall entry point with api specified by jlcall_api - jl_fptr_t unspecialized_ducttape; // if template can't be compiled due to intrinsics, an un-inferred fptr may get stored here, jlcall_api = 1 - - // On the old JIT, handles to all Functions generated for this linfo - // For the new JITs, handles to declarations in the shadow module - // with the same name as the generated functions for this linfo, suitable - // for referencing in LLVM IR - jl_llvm_functions_t functionObjectsDecls; -} jl_method_instance_t; - -// all values are callable as Functions -typedef jl_value_t jl_function_t; - -typedef struct { - JL_DATA_TYPE - jl_sym_t *name; - jl_value_t *lb; // lower bound - jl_value_t *ub; // upper bound -} jl_tvar_t; - -// UnionAll type (iterated union over all values of a variable in certain bounds) -// written `body where lb<:var<:ub` -typedef struct { - JL_DATA_TYPE - jl_tvar_t *var; - jl_value_t *body; -} jl_unionall_t; - -// represents the "name" part of a DataType, describing the syntactic structure -// of a type and storing all data common to different instantiations of the type, -// including a cache for hash-consed allocation of DataType objects. -typedef struct { - JL_DATA_TYPE - jl_sym_t *name; - struct _jl_module_t *module; - jl_svec_t *names; // field names - // `wrapper` is either the only instantiation of the type (if no parameters) - // or a UnionAll accepting parameters to make an instantiation. - jl_value_t *wrapper; - jl_svec_t *cache; // sorted array - jl_svec_t *linearcache; // unsorted array - intptr_t hash; - struct _jl_methtable_t *mt; -} jl_typename_t; - -typedef struct { - JL_DATA_TYPE - jl_value_t *a; - jl_value_t *b; -} jl_uniontype_t; - -// in little-endian, isptr is always the first bit, avoiding the need for a branch in computing isptr -typedef struct { - uint8_t isptr:1; - uint8_t size:7; - uint8_t offset; // offset relative to data start, excluding type tag -} jl_fielddesc8_t; - -typedef struct { - uint16_t isptr:1; - uint16_t size:15; - uint16_t offset; // offset relative to data start, excluding type tag -} jl_fielddesc16_t; - -typedef struct { - uint32_t isptr:1; - uint32_t size:31; - uint32_t offset; // offset relative to data start, excluding type tag -} jl_fielddesc32_t; - -typedef struct { - uint32_t nfields; - uint32_t alignment : 9; // strictest alignment over all fields - uint32_t haspadding : 1; // has internal undefined bytes - uint32_t npointers : 20; // number of pointer fields, top 4 bits are exponent (under-approximation) - uint32_t fielddesc_type : 2; // 0 -> 8, 1 -> 16, 2 -> 32 - // union { - // jl_fielddesc8_t field8[]; - // jl_fielddesc16_t field16[]; - // jl_fielddesc32_t field32[]; - // }; -} jl_datatype_layout_t; - -typedef struct _jl_datatype_t { - JL_DATA_TYPE - jl_typename_t *name; - struct _jl_datatype_t *super; - jl_svec_t *parameters; - jl_svec_t *types; - jl_value_t *instance; // for singletons - const jl_datatype_layout_t *layout; - int32_t size; // TODO: move to _jl_datatype_layout_t - int32_t ninitialized; - uint32_t uid; - uint8_t abstract; - uint8_t mutabl; - // memoized properties - void *struct_decl; //llvm::Type* - void *ditype; // llvm::MDNode* to be used as llvm::DIType(ditype) - int32_t depth; - int8_t hasfreetypevars; - int8_t isleaftype; -} jl_datatype_t; - -typedef struct { - JL_DATA_TYPE - jl_value_t *value; -} jl_weakref_t; - -typedef struct { - // not first-class - jl_sym_t *name; - jl_value_t *value; - jl_value_t *globalref; // cached GlobalRef for this binding - struct _jl_module_t *owner; // for individual imported bindings - unsigned constp:1; - unsigned exportp:1; - unsigned imported:1; - unsigned deprecated:1; -} jl_binding_t; - -typedef struct _jl_module_t { - JL_DATA_TYPE - jl_sym_t *name; - struct _jl_module_t *parent; - htable_t bindings; - arraylist_t usings; // modules with all bindings potentially imported - uint8_t istopmod; - uint64_t uuid; - size_t primary_world; - uint32_t counter; -} jl_module_t; - -// one Type-to-Value entry -typedef struct _jl_typemap_entry_t { - JL_DATA_TYPE - struct _jl_typemap_entry_t *next; // invasive linked list - jl_tupletype_t *sig; // the type signature for this entry - jl_tupletype_t *simplesig; // a simple signature for fast rejection - jl_svec_t *guardsigs; - size_t min_world; - size_t max_world; - union { - jl_value_t *value; - jl_method_instance_t *linfo; // [nullable] for guard entries - jl_method_t *method; - } func; - // memoized properties of sig: - int8_t isleafsig; // isleaftype(sig) & !any(isType, sig) : unsorted and very fast - int8_t issimplesig; // all(isleaftype | isAny | isType | isVararg, sig) : sorted and fast - int8_t va; // isVararg(sig) -} jl_typemap_entry_t; - -// one level in a TypeMap tree -// indexed by key if it is a sublevel in an array -struct jl_ordereddict_t { - jl_array_t *indexes; // Array{Int{8,16,32}} - jl_array_t *values; // Array{union jl_typemap_t} -}; -typedef struct _jl_typemap_level_t { - JL_DATA_TYPE - struct jl_ordereddict_t arg1; - struct jl_ordereddict_t targ; - jl_typemap_entry_t *linear; // union jl_typemap_t (but no more levels) - union jl_typemap_t any; // type at offs is Any - jl_value_t *key; // [nullable] -} jl_typemap_level_t; - -// contains the TypeMap for one Type -typedef struct _jl_methtable_t { - JL_DATA_TYPE - jl_sym_t *name; - union jl_typemap_t defs; - union jl_typemap_t cache; - intptr_t max_args; // max # of non-vararg arguments in a signature - jl_value_t *kwsorter; // keyword argument sorter function - jl_module_t *module; // used for incremental serialization to locate original binding - jl_array_t *backedges; - jl_mutex_t writelock; -} jl_methtable_t; - -typedef struct { - JL_DATA_TYPE - jl_sym_t *head; - jl_array_t *args; - jl_value_t *etype; -} jl_expr_t; - -// constants and type objects ------------------------------------------------- - -// kinds -extern JL_DLLEXPORT jl_datatype_t *jl_typeofbottom_type; -extern JL_DLLEXPORT jl_datatype_t *jl_datatype_type; -extern JL_DLLEXPORT jl_datatype_t *jl_uniontype_type; -extern JL_DLLEXPORT jl_datatype_t *jl_unionall_type; -extern JL_DLLEXPORT jl_datatype_t *jl_tvar_type; - -extern JL_DLLEXPORT jl_datatype_t *jl_any_type; -extern JL_DLLEXPORT jl_unionall_t *jl_type_type; -extern JL_DLLEXPORT jl_unionall_t *jl_typetype_type; -extern JL_DLLEXPORT jl_value_t *jl_ANY_flag; -extern JL_DLLEXPORT jl_datatype_t *jl_typename_type; -extern JL_DLLEXPORT jl_typename_t *jl_type_typename; -extern JL_DLLEXPORT jl_datatype_t *jl_sym_type; -extern JL_DLLEXPORT jl_datatype_t *jl_symbol_type; -extern JL_DLLEXPORT jl_datatype_t *jl_ssavalue_type; -extern JL_DLLEXPORT jl_datatype_t *jl_abstractslot_type; -extern JL_DLLEXPORT jl_datatype_t *jl_slotnumber_type; -extern JL_DLLEXPORT jl_datatype_t *jl_typedslot_type; -extern JL_DLLEXPORT jl_datatype_t *jl_simplevector_type; -extern JL_DLLEXPORT jl_typename_t *jl_tuple_typename; -extern JL_DLLEXPORT jl_typename_t *jl_vecelement_typename; -extern JL_DLLEXPORT jl_datatype_t *jl_anytuple_type; -extern JL_DLLEXPORT jl_datatype_t *jl_emptytuple_type; -#define jl_tuple_type jl_anytuple_type -extern JL_DLLEXPORT jl_unionall_t *jl_anytuple_type_type; -extern JL_DLLEXPORT jl_unionall_t *jl_vararg_type; -extern JL_DLLEXPORT jl_typename_t *jl_vararg_typename; -extern JL_DLLEXPORT jl_datatype_t *jl_task_type; -extern JL_DLLEXPORT jl_datatype_t *jl_function_type; -extern JL_DLLEXPORT jl_datatype_t *jl_builtin_type; - -extern JL_DLLEXPORT jl_value_t *jl_bottom_type; -extern JL_DLLEXPORT jl_datatype_t *jl_method_instance_type; -extern JL_DLLEXPORT jl_datatype_t *jl_code_info_type; -extern JL_DLLEXPORT jl_datatype_t *jl_method_type; -extern JL_DLLEXPORT jl_datatype_t *jl_module_type; -extern JL_DLLEXPORT jl_unionall_t *jl_abstractarray_type; -extern JL_DLLEXPORT jl_unionall_t *jl_densearray_type; -extern JL_DLLEXPORT jl_unionall_t *jl_array_type; -extern JL_DLLEXPORT jl_typename_t *jl_array_typename; -extern JL_DLLEXPORT jl_datatype_t *jl_weakref_type; -extern JL_DLLEXPORT jl_datatype_t *jl_abstractstring_type; -extern JL_DLLEXPORT jl_datatype_t *jl_string_type; -extern JL_DLLEXPORT jl_datatype_t *jl_errorexception_type; -extern JL_DLLEXPORT jl_datatype_t *jl_argumenterror_type; -extern JL_DLLEXPORT jl_datatype_t *jl_loaderror_type; -extern JL_DLLEXPORT jl_datatype_t *jl_initerror_type; -extern JL_DLLEXPORT jl_datatype_t *jl_typeerror_type; -extern JL_DLLEXPORT jl_datatype_t *jl_methoderror_type; -extern JL_DLLEXPORT jl_datatype_t *jl_undefvarerror_type; -extern JL_DLLEXPORT jl_value_t *jl_stackovf_exception; -extern JL_DLLEXPORT jl_value_t *jl_memory_exception; -extern JL_DLLEXPORT jl_value_t *jl_readonlymemory_exception; -extern JL_DLLEXPORT jl_value_t *jl_diverror_exception; -extern JL_DLLEXPORT jl_value_t *jl_domain_exception; -extern JL_DLLEXPORT jl_value_t *jl_overflow_exception; -extern JL_DLLEXPORT jl_value_t *jl_inexact_exception; -extern JL_DLLEXPORT jl_value_t *jl_undefref_exception; -extern JL_DLLEXPORT jl_value_t *jl_interrupt_exception; -extern JL_DLLEXPORT jl_datatype_t *jl_boundserror_type; -extern JL_DLLEXPORT jl_value_t *jl_an_empty_vec_any; - -extern JL_DLLEXPORT jl_datatype_t *jl_bool_type; -extern JL_DLLEXPORT jl_datatype_t *jl_char_type; -extern JL_DLLEXPORT jl_datatype_t *jl_int8_type; -extern JL_DLLEXPORT jl_datatype_t *jl_uint8_type; -extern JL_DLLEXPORT jl_datatype_t *jl_int16_type; -extern JL_DLLEXPORT jl_datatype_t *jl_uint16_type; -extern JL_DLLEXPORT jl_datatype_t *jl_int32_type; -extern JL_DLLEXPORT jl_datatype_t *jl_uint32_type; -extern JL_DLLEXPORT jl_datatype_t *jl_int64_type; -extern JL_DLLEXPORT jl_datatype_t *jl_uint64_type; -extern JL_DLLEXPORT jl_datatype_t *jl_float16_type; -extern JL_DLLEXPORT jl_datatype_t *jl_float32_type; -extern JL_DLLEXPORT jl_datatype_t *jl_float64_type; -extern JL_DLLEXPORT jl_datatype_t *jl_floatingpoint_type; -extern JL_DLLEXPORT jl_datatype_t *jl_number_type; -extern JL_DLLEXPORT jl_datatype_t *jl_void_type; -extern JL_DLLEXPORT jl_unionall_t *jl_complex_type; -extern JL_DLLEXPORT jl_datatype_t *jl_signed_type; -extern JL_DLLEXPORT jl_datatype_t *jl_voidpointer_type; -extern JL_DLLEXPORT jl_unionall_t *jl_pointer_type; -extern JL_DLLEXPORT jl_unionall_t *jl_ref_type; -extern JL_DLLEXPORT jl_typename_t *jl_pointer_typename; - -extern JL_DLLEXPORT jl_value_t *jl_array_uint8_type; -extern JL_DLLEXPORT jl_value_t *jl_array_any_type; -extern JL_DLLEXPORT jl_value_t *jl_array_symbol_type; -extern JL_DLLEXPORT jl_datatype_t *jl_expr_type; -extern JL_DLLEXPORT jl_datatype_t *jl_globalref_type; -extern JL_DLLEXPORT jl_datatype_t *jl_linenumbernode_type; -extern JL_DLLEXPORT jl_datatype_t *jl_labelnode_type; -extern JL_DLLEXPORT jl_datatype_t *jl_gotonode_type; -extern JL_DLLEXPORT jl_datatype_t *jl_quotenode_type; -extern JL_DLLEXPORT jl_datatype_t *jl_newvarnode_type; -extern JL_DLLEXPORT jl_datatype_t *jl_intrinsic_type; -extern JL_DLLEXPORT jl_datatype_t *jl_methtable_type; -extern JL_DLLEXPORT jl_datatype_t *jl_typemap_level_type; -extern JL_DLLEXPORT jl_datatype_t *jl_typemap_entry_type; - -extern JL_DLLEXPORT jl_svec_t *jl_emptysvec; -extern JL_DLLEXPORT jl_value_t *jl_emptytuple; -extern JL_DLLEXPORT jl_value_t *jl_true; -extern JL_DLLEXPORT jl_value_t *jl_false; -extern JL_DLLEXPORT jl_value_t *jl_nothing; - -// some important symbols -extern JL_DLLEXPORT jl_sym_t *jl_incomplete_sym; - -// gc ------------------------------------------------------------------------- - -typedef struct _jl_gcframe_t { - size_t nroots; - struct _jl_gcframe_t *prev; - // actual roots go here -} jl_gcframe_t; - -// NOTE: it is the caller's responsibility to make sure arguments are -// rooted such that the gc can see them on the stack. -// `foo(f(), g())` is not safe, -// since the result of `f()` is not rooted during the call to `g()`, -// and the arguments to foo are not gc-protected during the call to foo. -// foo can't do anything about it, so the caller must do: -// jl_value_t *x=NULL, *y=NULL; JL_GC_PUSH2(&x, &y); -// x = f(); y = g(); foo(x, y) - -#define jl_pgcstack (jl_get_ptls_states()->pgcstack) - -#define JL_GC_PUSH1(arg1) \ - void *__gc_stkf[] = {(void*)3, jl_pgcstack, arg1}; \ - jl_pgcstack = (jl_gcframe_t*)__gc_stkf; - -#define JL_GC_PUSH2(arg1, arg2) \ - void *__gc_stkf[] = {(void*)5, jl_pgcstack, arg1, arg2}; \ - jl_pgcstack = (jl_gcframe_t*)__gc_stkf; - -#define JL_GC_PUSH3(arg1, arg2, arg3) \ - void *__gc_stkf[] = {(void*)7, jl_pgcstack, arg1, arg2, arg3}; \ - jl_pgcstack = (jl_gcframe_t*)__gc_stkf; - -#define JL_GC_PUSH4(arg1, arg2, arg3, arg4) \ - void *__gc_stkf[] = {(void*)9, jl_pgcstack, arg1, arg2, arg3, arg4}; \ - jl_pgcstack = (jl_gcframe_t*)__gc_stkf; - -#define JL_GC_PUSH5(arg1, arg2, arg3, arg4, arg5) \ - void *__gc_stkf[] = {(void*)11, jl_pgcstack, arg1, arg2, arg3, arg4, arg5}; \ - jl_pgcstack = (jl_gcframe_t*)__gc_stkf; - -#define JL_GC_PUSH6(arg1, arg2, arg3, arg4, arg5, arg6) \ - void *__gc_stkf[] = {(void*)13, jl_pgcstack, arg1, arg2, arg3, arg4, arg5, arg6}; \ - jl_pgcstack = (jl_gcframe_t*)__gc_stkf; - -#define JL_GC_PUSHARGS(rts_var,n) \ - rts_var = ((jl_value_t**)alloca(((n)+2)*sizeof(jl_value_t*)))+2; \ - ((void**)rts_var)[-2] = (void*)(((size_t)(n))<<1); \ - ((void**)rts_var)[-1] = jl_pgcstack; \ - memset((void*)rts_var, 0, (n)*sizeof(jl_value_t*)); \ - jl_pgcstack = (jl_gcframe_t*)&(((void**)rts_var)[-2]) - -#define JL_GC_POP() (jl_pgcstack = jl_pgcstack->prev) - -JL_DLLEXPORT int jl_gc_enable(int on); -JL_DLLEXPORT int jl_gc_is_enabled(void); -JL_DLLEXPORT int64_t jl_gc_total_bytes(void); -JL_DLLEXPORT uint64_t jl_gc_total_hrtime(void); -JL_DLLEXPORT int64_t jl_gc_diff_total_bytes(void); - -JL_DLLEXPORT void jl_gc_collect(int); - -JL_DLLEXPORT void jl_gc_add_finalizer(jl_value_t *v, jl_function_t *f); -JL_DLLEXPORT void jl_finalize(jl_value_t *o); -JL_DLLEXPORT jl_weakref_t *jl_gc_new_weakref(jl_value_t *value); -JL_DLLEXPORT jl_value_t *jl_gc_alloc_0w(void); -JL_DLLEXPORT jl_value_t *jl_gc_alloc_1w(void); -JL_DLLEXPORT jl_value_t *jl_gc_alloc_2w(void); -JL_DLLEXPORT jl_value_t *jl_gc_alloc_3w(void); -JL_DLLEXPORT jl_value_t *jl_gc_allocobj(size_t sz); - -JL_DLLEXPORT void jl_clear_malloc_data(void); - -// GC write barriers -JL_DLLEXPORT void jl_gc_queue_root(jl_value_t *root); // root isa jl_value_t* - -// Do NOT put a safepoint here -STATIC_INLINE void jl_gc_wb(void *parent, void *ptr) -{ - // parent and ptr isa jl_value_t* - if (__unlikely(jl_astaggedvalue(parent)->bits.gc == 3 && - (jl_astaggedvalue(ptr)->bits.gc & 1) == 0)) - jl_gc_queue_root((jl_value_t*)parent); -} - -STATIC_INLINE void jl_gc_wb_back(void *ptr) // ptr isa jl_value_t* -{ - // if ptr is old - if (__unlikely(jl_astaggedvalue(ptr)->bits.gc == 3)) { - jl_gc_queue_root((jl_value_t*)ptr); - } -} - -JL_DLLEXPORT void *jl_gc_managed_malloc(size_t sz); -JL_DLLEXPORT void *jl_gc_managed_realloc(void *d, size_t sz, size_t oldsz, - int isaligned, jl_value_t *owner); - -// object accessors ----------------------------------------------------------- - -#define jl_svec_len(t) (((jl_svec_t*)(t))->length) -#define jl_svec_set_len_unsafe(t,n) (((jl_svec_t*)(t))->length=(n)) -#define jl_svec_data(t) ((jl_value_t**)((char*)(t) + sizeof(jl_svec_t))) - -STATIC_INLINE jl_value_t *jl_svecref(void *t, size_t i) -{ - assert(jl_typeis(t,jl_simplevector_type)); - assert(i < jl_svec_len(t)); - return jl_svec_data(t)[i]; -} -STATIC_INLINE jl_value_t *jl_svecset(void *t, size_t i, void *x) -{ - assert(jl_typeis(t,jl_simplevector_type)); - assert(i < jl_svec_len(t)); - jl_svec_data(t)[i] = (jl_value_t*)x; - if (x) jl_gc_wb(t, x); - return (jl_value_t*)x; -} - -#ifdef STORE_ARRAY_LEN -#define jl_array_len(a) (((jl_array_t*)(a))->length) -#else -JL_DLLEXPORT size_t jl_array_len_(jl_array_t *a); -#define jl_array_len(a) jl_array_len_((jl_array_t*)(a)) -#endif -#define jl_array_data(a) ((void*)((jl_array_t*)(a))->data) -#define jl_array_dim(a,i) ((&((jl_array_t*)(a))->nrows)[i]) -#define jl_array_dim0(a) (((jl_array_t*)(a))->nrows) -#define jl_array_nrows(a) (((jl_array_t*)(a))->nrows) -#define jl_array_ndims(a) ((int32_t)(((jl_array_t*)a)->flags.ndims)) -#define jl_array_data_owner_offset(ndims) (offsetof(jl_array_t,ncols) + sizeof(size_t)*(1+jl_array_ndimwords(ndims))) // in bytes -#define jl_array_data_owner(a) (*((jl_value_t**)((char*)a + jl_array_data_owner_offset(jl_array_ndims(a))))) - -STATIC_INLINE jl_value_t *jl_array_ptr_ref(void *a, size_t i) -{ - assert(i < jl_array_len(a)); - return ((jl_value_t**)(jl_array_data(a)))[i]; -} -STATIC_INLINE jl_value_t *jl_array_ptr_set(void *a, size_t i, void *x) -{ - assert(i < jl_array_len(a)); - ((jl_value_t**)(jl_array_data(a)))[i] = (jl_value_t*)x; - if (x) { - if (((jl_array_t*)a)->flags.how == 3) { - a = jl_array_data_owner(a); - } - jl_gc_wb(a, x); - } - return (jl_value_t*)x; -} - -STATIC_INLINE uint8_t jl_array_uint8_ref(void *a, size_t i) -{ - assert(i < jl_array_len(a)); - assert(jl_typeis(a, jl_array_uint8_type)); - return ((uint8_t*)(jl_array_data(a)))[i]; -} -STATIC_INLINE void jl_array_uint8_set(void *a, size_t i, uint8_t x) -{ - assert(i < jl_array_len(a)); - assert(jl_typeis(a, jl_array_uint8_type)); - ((uint8_t*)(jl_array_data(a)))[i] = x; -} - -#define jl_exprarg(e,n) (((jl_value_t**)jl_array_data(((jl_expr_t*)(e))->args))[n]) -#define jl_exprargset(e, n, v) jl_array_ptr_set(((jl_expr_t*)(e))->args, n, v) -#define jl_expr_nargs(e) jl_array_len(((jl_expr_t*)(e))->args) - -#define jl_fieldref(s,i) jl_get_nth_field(((jl_value_t*)s),i) -#define jl_nfields(v) jl_datatype_nfields(jl_typeof(v)) - -// Not using jl_fieldref to avoid allocations -#define jl_linenode_line(x) (((intptr_t*)x)[0]) -#define jl_labelnode_label(x) (((intptr_t*)x)[0]) -#define jl_slot_number(x) (((intptr_t*)x)[0]) -#define jl_typedslot_get_type(x) (((jl_value_t**)x)[1]) -#define jl_gotonode_label(x) (((intptr_t*)x)[0]) -#define jl_globalref_mod(s) (*(jl_module_t**)s) -#define jl_globalref_name(s) (((jl_sym_t**)s)[1]) - -#define jl_nparams(t) jl_svec_len(((jl_datatype_t*)(t))->parameters) -#define jl_tparam0(t) jl_svecref(((jl_datatype_t*)(t))->parameters, 0) -#define jl_tparam1(t) jl_svecref(((jl_datatype_t*)(t))->parameters, 1) -#define jl_tparam(t,i) jl_svecref(((jl_datatype_t*)(t))->parameters, i) - -// get a pointer to the data in a datatype -#define jl_data_ptr(v) ((jl_value_t**)v) - -#define jl_array_ptr_data(a) ((jl_value_t**)((jl_array_t*)a)->data) -#define jl_string_data(s) ((char*)s + sizeof(void*)) -#define jl_string_len(s) (*(size_t*)s) - -#define jl_gf_mtable(f) (((jl_datatype_t*)jl_typeof(f))->name->mt) -#define jl_gf_name(f) (jl_gf_mtable(f)->name) - -// struct type info -#define jl_field_name(st,i) (jl_sym_t*)jl_svecref(((jl_datatype_t*)st)->name->names, (i)) -#define jl_field_type(st,i) jl_svecref(((jl_datatype_t*)st)->types, (i)) -#define jl_field_count(st) jl_svec_len(((jl_datatype_t*)st)->types) -#define jl_datatype_size(t) (((jl_datatype_t*)t)->size) -#define jl_datatype_align(t) (((jl_datatype_t*)t)->layout->alignment) -#define jl_datatype_nbits(t) ((((jl_datatype_t*)t)->size)*8) -#define jl_datatype_nfields(t) (((jl_datatype_t*)(t))->layout->nfields) - -// inline version with strong type check to detect typos in a `->name` chain -STATIC_INLINE char *jl_symbol_name_(jl_sym_t *s) -{ - return (char*)s + LLT_ALIGN(sizeof(jl_sym_t), sizeof(void*)); -} -#define jl_symbol_name(s) jl_symbol_name_(s) - -#define jl_dt_layout_fields(d) ((const char*)(d) + sizeof(jl_datatype_layout_t)) - -#define DEFINE_FIELD_ACCESSORS(f) \ - static inline uint32_t jl_field_##f(jl_datatype_t *st, int i) \ - { \ - const jl_datatype_layout_t *ly = st->layout; \ - assert(i >= 0 && (size_t)i < ly->nfields); \ - if (ly->fielddesc_type == 0) { \ - return ((const jl_fielddesc8_t*)jl_dt_layout_fields(ly))[i].f; \ - } \ - else if (ly->fielddesc_type == 1) { \ - return ((const jl_fielddesc16_t*)jl_dt_layout_fields(ly))[i].f; \ - } \ - else { \ - return ((const jl_fielddesc32_t*)jl_dt_layout_fields(ly))[i].f; \ - } \ - } \ - -DEFINE_FIELD_ACCESSORS(offset) -DEFINE_FIELD_ACCESSORS(size) -static inline int jl_field_isptr(jl_datatype_t *st, int i) -{ - const jl_datatype_layout_t *ly = st->layout; - assert(i >= 0 && (size_t)i < ly->nfields); - return ((const jl_fielddesc8_t*)(jl_dt_layout_fields(ly) + (i << (ly->fielddesc_type + 1))))->isptr; -} - -static inline uint32_t jl_fielddesc_size(int8_t fielddesc_type) -{ - if (fielddesc_type == 0) { - return sizeof(jl_fielddesc8_t); - } - else if (fielddesc_type == 1) { - return sizeof(jl_fielddesc16_t); - } - else { - return sizeof(jl_fielddesc32_t); - } -} - -#undef DEFINE_FIELD_ACCESSORS - -// basic predicates ----------------------------------------------------------- -#define jl_is_nothing(v) (((jl_value_t*)(v)) == ((jl_value_t*)jl_nothing)) -#define jl_is_tuple(v) (((jl_datatype_t*)jl_typeof(v))->name == jl_tuple_typename) -#define jl_is_svec(v) jl_typeis(v,jl_simplevector_type) -#define jl_is_simplevector(v) jl_is_svec(v) -#define jl_is_datatype(v) jl_typeis(v,jl_datatype_type) -#define jl_is_mutable(t) (((jl_datatype_t*)t)->mutabl) -#define jl_is_mutable_datatype(t) (jl_is_datatype(t) && (((jl_datatype_t*)t)->mutabl)) -#define jl_is_immutable(t) (!((jl_datatype_t*)t)->mutabl) -#define jl_is_immutable_datatype(t) (jl_is_datatype(t) && (!((jl_datatype_t*)t)->mutabl)) -#define jl_is_uniontype(v) jl_typeis(v,jl_uniontype_type) -#define jl_is_typevar(v) jl_typeis(v,jl_tvar_type) -#define jl_is_unionall(v) jl_typeis(v,jl_unionall_type) -#define jl_is_typename(v) jl_typeis(v,jl_typename_type) -#define jl_is_int8(v) jl_typeis(v,jl_int8_type) -#define jl_is_int16(v) jl_typeis(v,jl_int16_type) -#define jl_is_int32(v) jl_typeis(v,jl_int32_type) -#define jl_is_int64(v) jl_typeis(v,jl_int64_type) -#define jl_is_uint8(v) jl_typeis(v,jl_uint8_type) -#define jl_is_uint16(v) jl_typeis(v,jl_uint16_type) -#define jl_is_uint32(v) jl_typeis(v,jl_uint32_type) -#define jl_is_uint64(v) jl_typeis(v,jl_uint64_type) -#define jl_is_bool(v) jl_typeis(v,jl_bool_type) -#define jl_is_symbol(v) jl_typeis(v,jl_sym_type) -#define jl_is_ssavalue(v) jl_typeis(v,jl_ssavalue_type) -#define jl_is_slot(v) (jl_typeis(v,jl_slotnumber_type) || jl_typeis(v,jl_typedslot_type)) -#define jl_is_expr(v) jl_typeis(v,jl_expr_type) -#define jl_is_globalref(v) jl_typeis(v,jl_globalref_type) -#define jl_is_labelnode(v) jl_typeis(v,jl_labelnode_type) -#define jl_is_gotonode(v) jl_typeis(v,jl_gotonode_type) -#define jl_is_quotenode(v) jl_typeis(v,jl_quotenode_type) -#define jl_is_newvarnode(v) jl_typeis(v,jl_newvarnode_type) -#define jl_is_linenode(v) jl_typeis(v,jl_linenumbernode_type) -#define jl_is_method_instance(v) jl_typeis(v,jl_method_instance_type) -#define jl_is_code_info(v) jl_typeis(v,jl_code_info_type) -#define jl_is_method(v) jl_typeis(v,jl_method_type) -#define jl_is_module(v) jl_typeis(v,jl_module_type) -#define jl_is_mtable(v) jl_typeis(v,jl_methtable_type) -#define jl_is_task(v) jl_typeis(v,jl_task_type) -#define jl_is_string(v) jl_typeis(v,jl_string_type) -#define jl_is_cpointer(v) jl_is_cpointer_type(jl_typeof(v)) -#define jl_is_pointer(v) jl_is_cpointer_type(jl_typeof(v)) -#define jl_is_intrinsic(v) jl_typeis(v,jl_intrinsic_type) - -JL_DLLEXPORT int jl_subtype(jl_value_t *a, jl_value_t *b); - -STATIC_INLINE int jl_is_kind(jl_value_t *v) -{ - return (v==(jl_value_t*)jl_uniontype_type || v==(jl_value_t*)jl_datatype_type || - v==(jl_value_t*)jl_unionall_type || v==(jl_value_t*)jl_typeofbottom_type); -} - -STATIC_INLINE int jl_is_type(jl_value_t *v) -{ - return jl_is_kind(jl_typeof(v)); -} - -STATIC_INLINE int jl_is_primitivetype(void *v) -{ - return (jl_is_datatype(v) && jl_is_immutable(v) && - ((jl_datatype_t*)(v))->layout && - jl_datatype_nfields(v) == 0 && - jl_datatype_size(v) > 0); -} - -STATIC_INLINE int jl_is_structtype(void *v) -{ - return (jl_is_datatype(v) && - (jl_field_count(v) > 0 || - jl_datatype_size(v) == 0) && - !((jl_datatype_t*)(v))->abstract); -} - -STATIC_INLINE int jl_isbits(void *t) // corresponding to isbits() in julia -{ - return (jl_is_datatype(t) && ((jl_datatype_t*)t)->layout && - !((jl_datatype_t*)t)->mutabl && - ((jl_datatype_t*)t)->layout->npointers == 0); -} - -STATIC_INLINE int jl_is_datatype_singleton(jl_datatype_t *d) -{ - return (d->instance != NULL); -} - -STATIC_INLINE int jl_is_datatype_make_singleton(jl_datatype_t *d) -{ - return (!d->abstract && jl_datatype_size(d) == 0 && d != jl_sym_type && d->name != jl_array_typename && - d->uid != 0 && (d->name->names == jl_emptysvec || !d->mutabl)); -} - -STATIC_INLINE int jl_is_abstracttype(void *v) -{ - return (jl_is_datatype(v) && ((jl_datatype_t*)(v))->abstract); -} - -STATIC_INLINE int jl_is_array_type(void *t) -{ - return (jl_is_datatype(t) && - ((jl_datatype_t*)(t))->name == jl_array_typename); -} - -STATIC_INLINE int jl_is_array(void *v) -{ - jl_value_t *t = jl_typeof(v); - return jl_is_array_type(t); -} - -STATIC_INLINE int jl_is_cpointer_type(jl_value_t *t) -{ - return (jl_is_datatype(t) && - ((jl_datatype_t*)(t))->name == ((jl_datatype_t*)jl_pointer_type->body)->name); -} - -STATIC_INLINE int jl_is_abstract_ref_type(jl_value_t *t) -{ - return (jl_is_datatype(t) && - ((jl_datatype_t*)(t))->name == ((jl_datatype_t*)jl_ref_type->body)->name); -} - -STATIC_INLINE int jl_is_tuple_type(void *t) -{ - return (jl_is_datatype(t) && - ((jl_datatype_t*)(t))->name == jl_tuple_typename); -} - -STATIC_INLINE int jl_is_vecelement_type(jl_value_t* t) -{ - return (jl_is_datatype(t) && - ((jl_datatype_t*)(t))->name == jl_vecelement_typename); -} - -STATIC_INLINE int jl_is_type_type(jl_value_t *v) -{ - return (jl_is_datatype(v) && - ((jl_datatype_t*)(v))->name == ((jl_datatype_t*)jl_type_type->body)->name); -} - -// object identity -JL_DLLEXPORT int jl_egal(jl_value_t *a, jl_value_t *b); -JL_DLLEXPORT uintptr_t jl_object_id(jl_value_t *v); - -// type predicates and basic operations -JL_DLLEXPORT int jl_is_leaf_type(jl_value_t *v); -JL_DLLEXPORT int jl_has_free_typevars(jl_value_t *v); -JL_DLLEXPORT int jl_has_typevar(jl_value_t *t, jl_tvar_t *v); -JL_DLLEXPORT int jl_has_typevar_from_unionall(jl_value_t *t, jl_unionall_t *ua); -JL_DLLEXPORT int jl_subtype_env_size(jl_value_t *t); -JL_DLLEXPORT int jl_subtype_env(jl_value_t *x, jl_value_t *y, jl_value_t **env, int envsz); -JL_DLLEXPORT int jl_isa(jl_value_t *a, jl_value_t *t); -JL_DLLEXPORT int jl_types_equal(jl_value_t *a, jl_value_t *b); -JL_DLLEXPORT jl_value_t *jl_type_union(jl_value_t **ts, size_t n); -JL_DLLEXPORT jl_value_t *jl_type_intersection(jl_value_t *a, jl_value_t *b); -JL_DLLEXPORT int jl_has_empty_intersection(jl_value_t *x, jl_value_t *y); -JL_DLLEXPORT jl_value_t *jl_type_unionall(jl_tvar_t *v, jl_value_t *body); -JL_DLLEXPORT const char *jl_typename_str(jl_value_t *v); -JL_DLLEXPORT const char *jl_typeof_str(jl_value_t *v); -JL_DLLEXPORT int jl_type_morespecific(jl_value_t *a, jl_value_t *b); -jl_value_t *jl_unwrap_unionall(jl_value_t *v); -jl_value_t *jl_rewrap_unionall(jl_value_t *t, jl_value_t *u); - -#if defined(NDEBUG) && defined(JL_NDEBUG) -STATIC_INLINE int jl_is_leaf_type_(jl_value_t *v) -{ - return jl_is_datatype(v) && ((jl_datatype_t*)v)->isleaftype; -} -#define jl_is_leaf_type(v) jl_is_leaf_type_(v) -#endif - -// type constructors -JL_DLLEXPORT jl_typename_t *jl_new_typename(jl_sym_t *name); -JL_DLLEXPORT jl_tvar_t *jl_new_typevar(jl_sym_t *name, jl_value_t *lb, jl_value_t *ub); -JL_DLLEXPORT jl_value_t *jl_instantiate_unionall(jl_unionall_t *u, jl_value_t *p); -JL_DLLEXPORT jl_value_t *jl_apply_type(jl_value_t *tc, jl_value_t **params, size_t n); -JL_DLLEXPORT jl_value_t *jl_apply_type1(jl_value_t *tc, jl_value_t *p1); -JL_DLLEXPORT jl_value_t *jl_apply_type2(jl_value_t *tc, jl_value_t *p1, jl_value_t *p2); -JL_DLLEXPORT jl_tupletype_t *jl_apply_tuple_type(jl_svec_t *params); -JL_DLLEXPORT jl_tupletype_t *jl_apply_tuple_type_v(jl_value_t **p, size_t np); -JL_DLLEXPORT jl_datatype_t *jl_new_datatype(jl_sym_t *name, jl_datatype_t *super, - jl_svec_t *parameters, - jl_svec_t *fnames, jl_svec_t *ftypes, - int abstract, int mutabl, - int ninitialized); -JL_DLLEXPORT jl_datatype_t *jl_new_primitivetype(jl_value_t *name, - jl_datatype_t *super, - jl_svec_t *parameters, size_t nbits); - -// constructors -JL_DLLEXPORT jl_value_t *jl_new_bits(jl_value_t *bt, void *data); -JL_DLLEXPORT jl_value_t *jl_new_struct(jl_datatype_t *type, ...); -JL_DLLEXPORT jl_value_t *jl_new_structv(jl_datatype_t *type, jl_value_t **args, - uint32_t na); -JL_DLLEXPORT jl_value_t *jl_new_struct_uninit(jl_datatype_t *type); -JL_DLLEXPORT jl_method_instance_t *jl_new_method_instance_uninit(void); -JL_DLLEXPORT jl_svec_t *jl_svec(size_t n, ...); -JL_DLLEXPORT jl_svec_t *jl_svec1(void *a); -JL_DLLEXPORT jl_svec_t *jl_svec2(void *a, void *b); -JL_DLLEXPORT jl_svec_t *jl_alloc_svec(size_t n); -JL_DLLEXPORT jl_svec_t *jl_alloc_svec_uninit(size_t n); -JL_DLLEXPORT jl_svec_t *jl_svec_copy(jl_svec_t *a); -JL_DLLEXPORT jl_svec_t *jl_svec_fill(size_t n, jl_value_t *x); -JL_DLLEXPORT jl_value_t *jl_tupletype_fill(size_t n, jl_value_t *v); -JL_DLLEXPORT jl_sym_t *jl_symbol(const char *str); -JL_DLLEXPORT jl_sym_t *jl_symbol_lookup(const char *str); -JL_DLLEXPORT jl_sym_t *jl_symbol_n(const char *str, size_t len); -JL_DLLEXPORT jl_sym_t *jl_gensym(void); -JL_DLLEXPORT jl_sym_t *jl_tagged_gensym(const char *str, int32_t len); -JL_DLLEXPORT jl_sym_t *jl_get_root_symbol(void); -JL_DLLEXPORT jl_value_t *jl_generic_function_def(jl_sym_t *name, jl_value_t **bp, - jl_value_t *bp_owner, - jl_binding_t *bnd); -JL_DLLEXPORT void jl_method_def(jl_svec_t *argdata, jl_code_info_t *f, jl_value_t *isstaged); -JL_DLLEXPORT jl_code_info_t *jl_code_for_staged(jl_method_instance_t *linfo); -JL_DLLEXPORT jl_code_info_t *jl_copy_code_info(jl_code_info_t *src); -JL_DLLEXPORT size_t jl_get_world_counter(void); -JL_DLLEXPORT jl_function_t *jl_get_kwsorter(jl_value_t *ty); -JL_DLLEXPORT jl_value_t *jl_box_bool(int8_t x); -JL_DLLEXPORT jl_value_t *jl_box_int8(int8_t x); -JL_DLLEXPORT jl_value_t *jl_box_uint8(uint8_t x); -JL_DLLEXPORT jl_value_t *jl_box_int16(int16_t x); -JL_DLLEXPORT jl_value_t *jl_box_uint16(uint16_t x); -JL_DLLEXPORT jl_value_t *jl_box_int32(int32_t x); -JL_DLLEXPORT jl_value_t *jl_box_uint32(uint32_t x); -JL_DLLEXPORT jl_value_t *jl_box_char(uint32_t x); -JL_DLLEXPORT jl_value_t *jl_box_int64(int64_t x); -JL_DLLEXPORT jl_value_t *jl_box_uint64(uint64_t x); -JL_DLLEXPORT jl_value_t *jl_box_float32(float x); -JL_DLLEXPORT jl_value_t *jl_box_float64(double x); -JL_DLLEXPORT jl_value_t *jl_box_voidpointer(void *x); -JL_DLLEXPORT jl_value_t *jl_box_ssavalue(size_t x); -JL_DLLEXPORT jl_value_t *jl_box_slotnumber(size_t x); -JL_DLLEXPORT jl_value_t *jl_box8 (jl_datatype_t *t, int8_t x); -JL_DLLEXPORT jl_value_t *jl_box16(jl_datatype_t *t, int16_t x); -JL_DLLEXPORT jl_value_t *jl_box32(jl_datatype_t *t, int32_t x); -JL_DLLEXPORT jl_value_t *jl_box64(jl_datatype_t *t, int64_t x); -JL_DLLEXPORT int8_t jl_unbox_bool(jl_value_t *v); -JL_DLLEXPORT int8_t jl_unbox_int8(jl_value_t *v); -JL_DLLEXPORT uint8_t jl_unbox_uint8(jl_value_t *v); -JL_DLLEXPORT int16_t jl_unbox_int16(jl_value_t *v); -JL_DLLEXPORT uint16_t jl_unbox_uint16(jl_value_t *v); -JL_DLLEXPORT int32_t jl_unbox_int32(jl_value_t *v); -JL_DLLEXPORT uint32_t jl_unbox_uint32(jl_value_t *v); -JL_DLLEXPORT int64_t jl_unbox_int64(jl_value_t *v); -JL_DLLEXPORT uint64_t jl_unbox_uint64(jl_value_t *v); -JL_DLLEXPORT float jl_unbox_float32(jl_value_t *v); -JL_DLLEXPORT double jl_unbox_float64(jl_value_t *v); -JL_DLLEXPORT void *jl_unbox_voidpointer(jl_value_t *v); - -JL_DLLEXPORT int jl_get_size(jl_value_t *val, size_t *pnt); - -#ifdef _P64 -#define jl_box_long(x) jl_box_int64(x) -#define jl_box_ulong(x) jl_box_uint64(x) -#define jl_unbox_long(x) jl_unbox_int64(x) -#define jl_is_long(x) jl_is_int64(x) -#define jl_long_type jl_int64_type -#define jl_ulong_type jl_uint64_type -#else -#define jl_box_long(x) jl_box_int32(x) -#define jl_box_ulong(x) jl_box_uint32(x) -#define jl_unbox_long(x) jl_unbox_int32(x) -#define jl_is_long(x) jl_is_int32(x) -#define jl_long_type jl_int32_type -#define jl_ulong_type jl_uint32_type -#endif - -// Each tuple can exist in one of 4 Vararg states: -// NONE: no vararg Tuple{Int,Float32} -// INT: vararg with integer length Tuple{Int,Vararg{Float32,2}} -// BOUND: vararg with bound TypeVar length Tuple{Int,Vararg{Float32,N}} -// UNBOUND: vararg with unbound length Tuple{Int,Vararg{Float32}} -typedef enum { - JL_VARARG_NONE = 0, - JL_VARARG_INT = 1, - JL_VARARG_BOUND = 2, - JL_VARARG_UNBOUND = 3 -} jl_vararg_kind_t; - -STATIC_INLINE int jl_is_vararg_type(jl_value_t *v) -{ - v = jl_unwrap_unionall(v); - return (jl_is_datatype(v) && - ((jl_datatype_t*)(v))->name == jl_vararg_typename); -} - -STATIC_INLINE jl_value_t *jl_unwrap_vararg(jl_value_t *v) -{ - return jl_tparam0(jl_unwrap_unionall(v)); -} - -STATIC_INLINE jl_vararg_kind_t jl_vararg_kind(jl_value_t *v) -{ - if (!jl_is_vararg_type(v)) - return JL_VARARG_NONE; - jl_tvar_t *v1=NULL, *v2=NULL; - if (jl_is_unionall(v)) { - v1 = ((jl_unionall_t*)v)->var; - v = ((jl_unionall_t*)v)->body; - if (jl_is_unionall(v)) { - v2 = ((jl_unionall_t*)v)->var; - v = ((jl_unionall_t*)v)->body; - } - } - assert(jl_is_datatype(v)); - jl_value_t *lenv = jl_tparam1(v); - if (jl_is_long(lenv)) - return JL_VARARG_INT; - if (jl_is_typevar(lenv) && lenv != (jl_value_t*)v1 && lenv != (jl_value_t*)v2) - return JL_VARARG_BOUND; - return JL_VARARG_UNBOUND; -} - -STATIC_INLINE int jl_is_va_tuple(jl_datatype_t *t) -{ - assert(jl_is_tuple_type(t)); - size_t l = jl_svec_len(t->parameters); - return (l>0 && jl_is_vararg_type(jl_tparam(t,l-1))); -} - -STATIC_INLINE jl_vararg_kind_t jl_va_tuple_kind(jl_datatype_t *t) -{ - t = (jl_datatype_t*)jl_unwrap_unionall((jl_value_t*)t); - assert(jl_is_tuple_type(t)); - size_t l = jl_svec_len(t->parameters); - if (l == 0) - return JL_VARARG_NONE; - return jl_vararg_kind(jl_tparam(t,l-1)); -} - -// structs -JL_DLLEXPORT int jl_field_index(jl_datatype_t *t, jl_sym_t *fld, int err); -JL_DLLEXPORT jl_value_t *jl_get_nth_field(jl_value_t *v, size_t i); -JL_DLLEXPORT jl_value_t *jl_get_nth_field_checked(jl_value_t *v, size_t i); -JL_DLLEXPORT void jl_set_nth_field(jl_value_t *v, size_t i, - jl_value_t *rhs); -JL_DLLEXPORT int jl_field_isdefined(jl_value_t *v, size_t i); -JL_DLLEXPORT jl_value_t *jl_get_field(jl_value_t *o, const char *fld); -JL_DLLEXPORT jl_value_t *jl_value_ptr(jl_value_t *a); - -// arrays -JL_DLLEXPORT jl_array_t *jl_new_array(jl_value_t *atype, jl_value_t *dims); -JL_DLLEXPORT jl_array_t *jl_reshape_array(jl_value_t *atype, jl_array_t *data, - jl_value_t *dims); -JL_DLLEXPORT jl_array_t *jl_ptr_to_array_1d(jl_value_t *atype, void *data, - size_t nel, int own_buffer); -JL_DLLEXPORT jl_array_t *jl_ptr_to_array(jl_value_t *atype, void *data, - jl_value_t *dims, int own_buffer); - -JL_DLLEXPORT jl_array_t *jl_alloc_array_1d(jl_value_t *atype, size_t nr); -JL_DLLEXPORT jl_array_t *jl_alloc_array_2d(jl_value_t *atype, size_t nr, - size_t nc); -JL_DLLEXPORT jl_array_t *jl_alloc_array_3d(jl_value_t *atype, size_t nr, - size_t nc, size_t z); -JL_DLLEXPORT jl_array_t *jl_pchar_to_array(const char *str, size_t len); -JL_DLLEXPORT jl_value_t *jl_pchar_to_string(const char *str, size_t len); -JL_DLLEXPORT jl_value_t *jl_cstr_to_string(const char *str); -JL_DLLEXPORT jl_value_t *jl_alloc_string(size_t len); -JL_DLLEXPORT jl_value_t *jl_array_to_string(jl_array_t *a); -JL_DLLEXPORT jl_array_t *jl_alloc_vec_any(size_t n); -JL_DLLEXPORT jl_value_t *jl_arrayref(jl_array_t *a, size_t i); // 0-indexed -JL_DLLEXPORT void jl_arrayset(jl_array_t *a, jl_value_t *v, size_t i); // 0-indexed -JL_DLLEXPORT void jl_arrayunset(jl_array_t *a, size_t i); // 0-indexed -JL_DLLEXPORT void jl_array_grow_end(jl_array_t *a, size_t inc); -JL_DLLEXPORT void jl_array_del_end(jl_array_t *a, size_t dec); -JL_DLLEXPORT void jl_array_grow_beg(jl_array_t *a, size_t inc); -JL_DLLEXPORT void jl_array_del_beg(jl_array_t *a, size_t dec); -JL_DLLEXPORT void jl_array_sizehint(jl_array_t *a, size_t sz); -JL_DLLEXPORT void jl_array_ptr_1d_push(jl_array_t *a, jl_value_t *item); -JL_DLLEXPORT void jl_array_ptr_1d_push2(jl_array_t *a, jl_value_t *b, jl_value_t *c); -JL_DLLEXPORT void jl_array_ptr_1d_append(jl_array_t *a, jl_array_t *a2); -JL_DLLEXPORT jl_value_t *jl_apply_array_type(jl_value_t *type, size_t dim); -// property access -JL_DLLEXPORT void *jl_array_ptr(jl_array_t *a); -JL_DLLEXPORT void *jl_array_eltype(jl_value_t *a); -JL_DLLEXPORT int jl_array_rank(jl_value_t *a); -JL_DLLEXPORT size_t jl_array_size(jl_value_t *a, int d); - -// strings -JL_DLLEXPORT const char *jl_string_ptr(jl_value_t *s); - -// modules and global variables -extern JL_DLLEXPORT jl_module_t *jl_main_module; -extern JL_DLLEXPORT jl_module_t *jl_internal_main_module; -extern JL_DLLEXPORT jl_module_t *jl_core_module; -extern JL_DLLEXPORT jl_module_t *jl_base_module; -extern JL_DLLEXPORT jl_module_t *jl_top_module; -JL_DLLEXPORT jl_module_t *jl_new_module(jl_sym_t *name); -// get binding for reading -JL_DLLEXPORT jl_binding_t *jl_get_binding(jl_module_t *m, jl_sym_t *var); -JL_DLLEXPORT jl_binding_t *jl_get_binding_or_error(jl_module_t *m, jl_sym_t *var); -JL_DLLEXPORT jl_value_t *jl_module_globalref(jl_module_t *m, jl_sym_t *var); -// get binding for assignment -JL_DLLEXPORT jl_binding_t *jl_get_binding_wr(jl_module_t *m, jl_sym_t *var); -JL_DLLEXPORT jl_binding_t *jl_get_binding_for_method_def(jl_module_t *m, - jl_sym_t *var); -JL_DLLEXPORT int jl_boundp(jl_module_t *m, jl_sym_t *var); -JL_DLLEXPORT int jl_defines_or_exports_p(jl_module_t *m, jl_sym_t *var); -JL_DLLEXPORT int jl_binding_resolved_p(jl_module_t *m, jl_sym_t *var); -JL_DLLEXPORT int jl_is_const(jl_module_t *m, jl_sym_t *var); -JL_DLLEXPORT jl_value_t *jl_get_global(jl_module_t *m, jl_sym_t *var); -JL_DLLEXPORT void jl_set_global(jl_module_t *m, jl_sym_t *var, jl_value_t *val); -JL_DLLEXPORT void jl_set_const(jl_module_t *m, jl_sym_t *var, jl_value_t *val); -JL_DLLEXPORT void jl_checked_assignment(jl_binding_t *b, jl_value_t *rhs); -JL_DLLEXPORT void jl_declare_constant(jl_binding_t *b); -JL_DLLEXPORT void jl_module_using(jl_module_t *to, jl_module_t *from); -JL_DLLEXPORT void jl_module_use(jl_module_t *to, jl_module_t *from, jl_sym_t *s); -JL_DLLEXPORT void jl_module_import(jl_module_t *to, jl_module_t *from, - jl_sym_t *s); -JL_DLLEXPORT void jl_module_importall(jl_module_t *to, jl_module_t *from); -JL_DLLEXPORT void jl_module_export(jl_module_t *from, jl_sym_t *s); -JL_DLLEXPORT int jl_is_imported(jl_module_t *m, jl_sym_t *s); -JL_DLLEXPORT int jl_module_exports_p(jl_module_t *m, jl_sym_t *var); -JL_DLLEXPORT jl_module_t *jl_new_main_module(void); -JL_DLLEXPORT void jl_add_standard_imports(jl_module_t *m); -STATIC_INLINE jl_function_t *jl_get_function(jl_module_t *m, const char *name) -{ - return (jl_function_t*)jl_get_global(m, jl_symbol(name)); -} -int jl_is_submodule(jl_module_t *child, jl_module_t *parent); - -// eq hash tables -JL_DLLEXPORT jl_array_t *jl_eqtable_put(jl_array_t *h, void *key, void *val); -JL_DLLEXPORT jl_value_t *jl_eqtable_get(jl_array_t *h, void *key, - jl_value_t *deflt); - -// system information -JL_DLLEXPORT int jl_errno(void); -JL_DLLEXPORT void jl_set_errno(int e); -JL_DLLEXPORT int32_t jl_stat(const char *path, char *statbuf); -JL_DLLEXPORT int jl_cpu_cores(void); -JL_DLLEXPORT long jl_getpagesize(void); -JL_DLLEXPORT long jl_getallocationgranularity(void); -JL_DLLEXPORT int jl_is_debugbuild(void); -JL_DLLEXPORT jl_sym_t *jl_get_UNAME(void); -JL_DLLEXPORT jl_sym_t *jl_get_ARCH(void); -JL_DLLEXPORT uint64_t jl_cpuid_tag(void); -JL_DLLEXPORT int jl_uses_cpuid_tag(void); - -// environment entries -JL_DLLEXPORT jl_value_t *jl_environ(int i); - -// throwing common exceptions -JL_DLLEXPORT void JL_NORETURN jl_error(const char *str); -JL_DLLEXPORT void JL_NORETURN jl_errorf(const char *fmt, ...); -JL_DLLEXPORT void JL_NORETURN jl_exceptionf(jl_datatype_t *ty, - const char *fmt, ...); -JL_DLLEXPORT void JL_NORETURN jl_too_few_args(const char *fname, int min); -JL_DLLEXPORT void JL_NORETURN jl_too_many_args(const char *fname, int max); -JL_DLLEXPORT void JL_NORETURN jl_type_error(const char *fname, - jl_value_t *expected, - jl_value_t *got); -JL_DLLEXPORT void JL_NORETURN jl_type_error_rt(const char *fname, - const char *context, - jl_value_t *ty, jl_value_t *got); -JL_DLLEXPORT void JL_NORETURN jl_undefined_var_error(jl_sym_t *var); -JL_DLLEXPORT void JL_NORETURN jl_bounds_error(jl_value_t *v, jl_value_t *t); -JL_DLLEXPORT void JL_NORETURN jl_bounds_error_v(jl_value_t *v, - jl_value_t **idxs, size_t nidxs); -JL_DLLEXPORT void JL_NORETURN jl_bounds_error_int(jl_value_t *v, size_t i); -JL_DLLEXPORT void JL_NORETURN jl_bounds_error_tuple_int(jl_value_t **v, - size_t nv, size_t i); -JL_DLLEXPORT void JL_NORETURN jl_bounds_error_unboxed_int(void *v, jl_value_t *vt, size_t i); -JL_DLLEXPORT void JL_NORETURN jl_bounds_error_ints(jl_value_t *v, size_t *idxs, size_t nidxs); -JL_DLLEXPORT void JL_NORETURN jl_eof_error(void); -JL_DLLEXPORT jl_value_t *jl_exception_occurred(void); -JL_DLLEXPORT void jl_exception_clear(void); - -#define JL_NARGS(fname, min, max) \ - if (nargs < min) jl_too_few_args(#fname, min); \ - else if (nargs > max) jl_too_many_args(#fname, max); - -#define JL_NARGSV(fname, min) \ - if (nargs < min) jl_too_few_args(#fname, min); - -#define JL_TYPECHK(fname, type, v) \ - if (!jl_is_##type(v)) { \ - jl_type_error(#fname, (jl_value_t*)jl_##type##_type, (v)); \ - } -#define JL_TYPECHKS(fname, type, v) \ - if (!jl_is_##type(v)) { \ - jl_type_error(fname, (jl_value_t*)jl_##type##_type, (v)); \ - } - -// initialization functions -typedef enum { - JL_IMAGE_CWD = 0, - JL_IMAGE_JULIA_HOME = 1, - //JL_IMAGE_LIBJULIA = 2, -} JL_IMAGE_SEARCH; -JL_DLLEXPORT void julia_init(JL_IMAGE_SEARCH rel); -JL_DLLEXPORT void jl_init(void); -JL_DLLEXPORT void jl_init_with_image(const char *julia_home_dir, - const char *image_relative_path); -JL_DLLEXPORT const char *jl_get_default_sysimg_path(void); -JL_DLLEXPORT int jl_is_initialized(void); -JL_DLLEXPORT void jl_atexit_hook(int status); -JL_DLLEXPORT void JL_NORETURN jl_exit(int status); -JL_DLLEXPORT const char *jl_pathname_for_handle(void *handle); - -JL_DLLEXPORT int jl_deserialize_verify_header(ios_t *s); -JL_DLLEXPORT void jl_preload_sysimg_so(const char *fname); -JL_DLLEXPORT void jl_set_sysimg_so(void *handle); -JL_DLLEXPORT ios_t *jl_create_system_image(void); -JL_DLLEXPORT void jl_save_system_image(const char *fname); -JL_DLLEXPORT void jl_restore_system_image(const char *fname); -JL_DLLEXPORT void jl_restore_system_image_data(const char *buf, size_t len); -JL_DLLEXPORT int jl_save_incremental(const char *fname, jl_array_t *worklist); -JL_DLLEXPORT jl_value_t *jl_restore_incremental(const char *fname); -JL_DLLEXPORT jl_value_t *jl_restore_incremental_from_buf(const char *buf, size_t sz); - -// front end interface -JL_DLLEXPORT jl_value_t *jl_parse_input_line(const char *str, size_t len, - const char *filename, size_t filename_len); -JL_DLLEXPORT jl_value_t *jl_parse_string(const char *str, size_t len, - int pos0, int greedy); -JL_DLLEXPORT int jl_parse_depwarn(int warn); -JL_DLLEXPORT jl_value_t *jl_load_file_string(const char *text, size_t len, - char *filename); -JL_DLLEXPORT jl_value_t *jl_expand(jl_value_t *expr); -JL_DLLEXPORT jl_value_t *jl_eval_string(const char *str); - -// external libraries -enum JL_RTLD_CONSTANT { - JL_RTLD_LOCAL=1U, - JL_RTLD_GLOBAL=2U, - JL_RTLD_LAZY=4U, - JL_RTLD_NOW=8U, - /* Linux/glibc and MacOS X: */ - JL_RTLD_NODELETE=16U, - JL_RTLD_NOLOAD=32U, - /* Linux/glibc: */ - JL_RTLD_DEEPBIND=64U, - /* MacOS X 10.5+: */ - JL_RTLD_FIRST=128U -}; -#define JL_RTLD_DEFAULT (JL_RTLD_LAZY | JL_RTLD_DEEPBIND) - -typedef void *jl_uv_libhandle; // compatible with dlopen (void*) / LoadLibrary (HMODULE) -JL_DLLEXPORT jl_uv_libhandle jl_load_dynamic_library(const char *fname, unsigned flags); -JL_DLLEXPORT jl_uv_libhandle jl_load_dynamic_library_e(const char *fname, unsigned flags); -JL_DLLEXPORT jl_uv_libhandle jl_dlopen(const char *filename, unsigned flags); -JL_DLLEXPORT int jl_dlclose(jl_uv_libhandle handle); -JL_DLLEXPORT void *jl_dlsym_e(jl_uv_libhandle handle, const char *symbol); -JL_DLLEXPORT void *jl_dlsym(jl_uv_libhandle handle, const char *symbol); - -#if defined(__linux__) || defined(__FreeBSD__) -JL_DLLEXPORT const char *jl_lookup_soname(const char *pfx, size_t n); -#endif - -// compiler -JL_DLLEXPORT jl_value_t *jl_toplevel_eval(jl_value_t *v); -JL_DLLEXPORT jl_value_t *jl_toplevel_eval_in(jl_module_t *m, jl_value_t *ex); -JL_DLLEXPORT jl_value_t *jl_load(const char *fname); -JL_DLLEXPORT jl_module_t *jl_base_relative_to(jl_module_t *m); - -// tracing -JL_DLLEXPORT void jl_trace_method(jl_method_t *m); -JL_DLLEXPORT void jl_untrace_method(jl_method_t *m); -JL_DLLEXPORT void jl_trace_linfo(jl_method_instance_t *linfo); -JL_DLLEXPORT void jl_untrace_linfo(jl_method_instance_t *linfo); -JL_DLLEXPORT void jl_register_linfo_tracer(void (*callback)(jl_method_instance_t *tracee)); -JL_DLLEXPORT void jl_register_method_tracer(void (*callback)(jl_method_instance_t *tracee)); -JL_DLLEXPORT void jl_register_newmeth_tracer(void (*callback)(jl_method_t *tracee)); - -// AST access -JL_DLLEXPORT jl_value_t *jl_copy_ast(jl_value_t *expr); - -JL_DLLEXPORT jl_array_t *jl_compress_ast(jl_method_t *m, jl_code_info_t *code); -JL_DLLEXPORT jl_code_info_t *jl_uncompress_ast(jl_method_t *m, jl_array_t *data); -JL_DLLEXPORT uint8_t jl_ast_flag_inferred(jl_array_t *data); -JL_DLLEXPORT uint8_t jl_ast_flag_inlineable(jl_array_t *data); -JL_DLLEXPORT uint8_t jl_ast_flag_pure(jl_array_t *data); -JL_DLLEXPORT void jl_fill_argnames(jl_array_t *data, jl_array_t *names); - -JL_DLLEXPORT int jl_is_operator(char *sym); -JL_DLLEXPORT int jl_operator_precedence(char *sym); - -STATIC_INLINE int jl_vinfo_sa(uint8_t vi) -{ - return (vi&16)!=0; -} - -STATIC_INLINE int jl_vinfo_usedundef(uint8_t vi) -{ - return (vi&32)!=0; -} - -// calling into julia --------------------------------------------------------- - -JL_DLLEXPORT jl_value_t *jl_apply_generic(jl_value_t **args, uint32_t nargs); -JL_DLLEXPORT jl_value_t *jl_invoke(jl_method_instance_t *meth, jl_value_t **args, uint32_t nargs); - -STATIC_INLINE -jl_value_t *jl_apply(jl_value_t **args, uint32_t nargs) -{ - return jl_apply_generic(args, nargs); -} - -JL_DLLEXPORT jl_value_t *jl_call(jl_function_t *f, jl_value_t **args, int32_t nargs); -JL_DLLEXPORT jl_value_t *jl_call0(jl_function_t *f); -JL_DLLEXPORT jl_value_t *jl_call1(jl_function_t *f, jl_value_t *a); -JL_DLLEXPORT jl_value_t *jl_call2(jl_function_t *f, jl_value_t *a, jl_value_t *b); -JL_DLLEXPORT jl_value_t *jl_call3(jl_function_t *f, jl_value_t *a, - jl_value_t *b, jl_value_t *c); - -// interfacing with Task runtime -JL_DLLEXPORT void jl_yield(void); - -// async signal handling ------------------------------------------------------ - -JL_DLLEXPORT void jl_install_sigint_handler(void); -JL_DLLEXPORT void jl_sigatomic_begin(void); -JL_DLLEXPORT void jl_sigatomic_end(void); - -// tasks and exceptions ------------------------------------------------------- - -typedef struct _jl_timing_block_t jl_timing_block_t; -// info describing an exception handler -typedef struct _jl_handler_t { - jl_jmp_buf eh_ctx; - jl_gcframe_t *gcstack; - struct _jl_handler_t *prev; - int8_t gc_state; -#ifdef JULIA_ENABLE_THREADING - size_t locks_len; -#endif - sig_atomic_t defer_signal; - int finalizers_inhibited; - jl_timing_block_t *timing_stack; - size_t world_age; -} jl_handler_t; - -typedef struct _jl_task_t { - JL_DATA_TYPE - struct _jl_task_t *parent; - jl_value_t *tls; - jl_sym_t *state; - jl_value_t *consumers; - jl_value_t *donenotify; - jl_value_t *result; - jl_value_t *exception; - jl_value_t *backtrace; - jl_function_t *start; - jl_jmp_buf ctx; - size_t bufsz; - void *stkbuf; - -// hidden fields: - size_t ssize; - size_t started:1; - - // current exception handler - jl_handler_t *eh; - // saved gc stack top for context switches - jl_gcframe_t *gcstack; - // current module, or NULL if this task has not set one - jl_module_t *current_module; - // current world age - size_t world_age; - - // id of owning thread - // does not need to be defined until the task runs - int16_t tid; -#ifdef JULIA_ENABLE_THREADING - // This is statically initialized when the task is not holding any locks - arraylist_t locks; -#endif - jl_timing_block_t *timing_stack; -} jl_task_t; - -JL_DLLEXPORT jl_task_t *jl_new_task(jl_function_t *start, size_t ssize); -JL_DLLEXPORT void jl_switchto(jl_task_t *t); -JL_DLLEXPORT void JL_NORETURN jl_throw(jl_value_t *e); -JL_DLLEXPORT void JL_NORETURN jl_rethrow(void); -JL_DLLEXPORT void JL_NORETURN jl_rethrow_other(jl_value_t *e); -JL_DLLEXPORT void JL_NORETURN jl_no_exc_handler(jl_value_t *e); - -#ifdef JULIA_ENABLE_THREADING -static inline void jl_lock_frame_push(jl_mutex_t *lock) -{ - jl_ptls_t ptls = jl_get_ptls_states(); - // For early bootstrap - if (__unlikely(!ptls->current_task)) - return; - arraylist_t *locks = &ptls->current_task->locks; - size_t len = locks->len; - if (__unlikely(len >= locks->max)) { - arraylist_grow(locks, 1); - } - else { - locks->len = len + 1; - } - locks->items[len] = (void*)lock; -} -static inline void jl_lock_frame_pop(void) -{ - jl_ptls_t ptls = jl_get_ptls_states(); - if (__likely(ptls->current_task)) { - ptls->current_task->locks.len--; - } -} -#else -static inline void jl_lock_frame_push(jl_mutex_t *lock) -{ - (void)lock; -} -static inline void jl_lock_frame_pop(void) -{ -} -#endif // ifndef JULIA_ENABLE_THREADING - -STATIC_INLINE void jl_eh_restore_state(jl_handler_t *eh) -{ - jl_ptls_t ptls = jl_get_ptls_states(); - jl_task_t *current_task = ptls->current_task; - // `eh` may not be `ptls->current_task->eh`. See `jl_pop_handler` - // This function should **NOT** have any safepoint before the ones at the - // end. - sig_atomic_t old_defer_signal = ptls->defer_signal; - int8_t old_gc_state = ptls->gc_state; - current_task->eh = eh->prev; - ptls->pgcstack = eh->gcstack; -#ifdef JULIA_ENABLE_THREADING - arraylist_t *locks = ¤t_task->locks; - if (locks->len > eh->locks_len) { - for (size_t i = locks->len;i > eh->locks_len;i--) - jl_mutex_unlock_nogc((jl_mutex_t*)locks->items[i - 1]); - locks->len = eh->locks_len; - } -#endif - ptls->world_age = eh->world_age; - ptls->defer_signal = eh->defer_signal; - ptls->gc_state = eh->gc_state; - ptls->finalizers_inhibited = eh->finalizers_inhibited; - if (old_gc_state && !eh->gc_state) { - jl_gc_safepoint_(ptls); - } - if (old_defer_signal && !eh->defer_signal) { - jl_sigint_safepoint(ptls); - } -} - -JL_DLLEXPORT void jl_enter_handler(jl_handler_t *eh); -JL_DLLEXPORT void jl_pop_handler(int n); - -#if defined(_OS_WINDOWS_) -#if defined(_COMPILER_MINGW_) -int __attribute__ ((__nothrow__,__returns_twice__)) (jl_setjmp)(jmp_buf _Buf); -__declspec(noreturn) __attribute__ ((__nothrow__)) void (jl_longjmp)(jmp_buf _Buf, int _Value); -#else -int (jl_setjmp)(jmp_buf _Buf); -void (jl_longjmp)(jmp_buf _Buf, int _Value); -#endif -#define jl_setjmp_f jl_setjmp -#define jl_setjmp_name "jl_setjmp" -#define jl_setjmp(a,b) jl_setjmp(a) -#define jl_longjmp(a,b) jl_longjmp(a,b) -#else -// determine actual entry point name -#if defined(sigsetjmp) -#define jl_setjmp_f __sigsetjmp -#define jl_setjmp_name "__sigsetjmp" -#else -#define jl_setjmp_f sigsetjmp -#define jl_setjmp_name "sigsetjmp" -#endif -#define jl_setjmp(a,b) sigsetjmp(a,b) -#define jl_longjmp(a,b) siglongjmp(a,b) -#endif - -#define JL_TRY \ - int i__tr, i__ca; jl_handler_t __eh; \ - jl_enter_handler(&__eh); \ - if (!jl_setjmp(__eh.eh_ctx,0)) \ - for (i__tr=1; i__tr; i__tr=0, jl_eh_restore_state(&__eh)) - -#define JL_EH_POP() jl_eh_restore_state(&__eh) - -#ifdef _OS_WINDOWS_ -#define JL_CATCH \ - else \ - for (i__ca=1, jl_eh_restore_state(&__eh); i__ca; i__ca=0) \ - if (((jl_get_ptls_states()->exception_in_transit==jl_stackovf_exception) && _resetstkoflw()) || 1) -#else -#define JL_CATCH \ - else \ - for (i__ca=1, jl_eh_restore_state(&__eh); i__ca; i__ca=0) -#endif - -// I/O system ----------------------------------------------------------------- - -#define JL_STREAM uv_stream_t -#define JL_STDOUT jl_uv_stdout -#define JL_STDERR jl_uv_stderr -#define JL_STDIN jl_uv_stdin - -JL_DLLEXPORT void jl_run_event_loop(uv_loop_t *loop); -JL_DLLEXPORT int jl_run_once(uv_loop_t *loop); -JL_DLLEXPORT int jl_process_events(uv_loop_t *loop); - -JL_DLLEXPORT uv_loop_t *jl_global_event_loop(void); - -JL_DLLEXPORT void jl_close_uv(uv_handle_t *handle); - -JL_DLLEXPORT int jl_tcp_bind(uv_tcp_t *handle, uint16_t port, uint32_t host, - unsigned int flags); - -JL_DLLEXPORT int jl_sizeof_ios_t(void); - -JL_DLLEXPORT jl_array_t *jl_take_buffer(ios_t *s); - -typedef struct { - void *data; - uv_loop_t *loop; - uv_handle_type type; - uv_file file; -} jl_uv_file_t; - -#ifdef __GNUC__ -#define _JL_FORMAT_ATTR(type, str, arg) \ - __attribute__((format(type, str, arg))) -#else -#define _JL_FORMAT_ATTR(type, str, arg) -#endif - -JL_DLLEXPORT void jl_uv_puts(uv_stream_t *stream, const char *str, size_t n); -JL_DLLEXPORT int jl_printf(uv_stream_t *s, const char *format, ...) - _JL_FORMAT_ATTR(printf, 2, 3); -JL_DLLEXPORT int jl_vprintf(uv_stream_t *s, const char *format, va_list args) - _JL_FORMAT_ATTR(printf, 2, 0); -JL_DLLEXPORT void jl_safe_printf(const char *str, ...) - _JL_FORMAT_ATTR(printf, 1, 2); - -extern JL_DLLEXPORT JL_STREAM *JL_STDIN; -extern JL_DLLEXPORT JL_STREAM *JL_STDOUT; -extern JL_DLLEXPORT JL_STREAM *JL_STDERR; - -JL_DLLEXPORT JL_STREAM *jl_stdout_stream(void); -JL_DLLEXPORT JL_STREAM *jl_stdin_stream(void); -JL_DLLEXPORT JL_STREAM *jl_stderr_stream(void); - -// showing and std streams -JL_DLLEXPORT void jl_flush_cstdio(void); -JL_DLLEXPORT jl_value_t *jl_stdout_obj(void); -JL_DLLEXPORT jl_value_t *jl_stderr_obj(void); -JL_DLLEXPORT size_t jl_static_show(JL_STREAM *out, jl_value_t *v); -JL_DLLEXPORT size_t jl_static_show_func_sig(JL_STREAM *s, jl_value_t *type); -JL_DLLEXPORT void jlbacktrace(void); -// Mainly for debugging, use `void*` so that no type cast is needed in C++. -JL_DLLEXPORT void jl_(void *jl_value); - -// julia options ----------------------------------------------------------- -// NOTE: This struct needs to be kept in sync with JLOptions type in base/options.jl -typedef struct { - int8_t quiet; - const char *julia_home; - const char *julia_bin; - const char *eval; - const char *print; - const char *load; - const char *image_file; - const char *cpu_target; - int32_t nprocs; - const char *machinefile; - int8_t isinteractive; - int8_t color; - int8_t historyfile; - int8_t startupfile; - int8_t compile_enabled; - int8_t code_coverage; - int8_t malloc_log; - int8_t opt_level; - int8_t debug_level; - int8_t check_bounds; - int8_t depwarn; - int8_t can_inline; - int8_t polly; - int8_t fast_math; - const char *worker; - int8_t handle_signals; - int8_t use_precompiled; - int8_t use_compilecache; - const char *bindto; - const char *outputbc; - const char *outputo; - const char *outputji; - int8_t incremental; - int8_t image_file_specified; -} jl_options_t; - -extern JL_DLLEXPORT jl_options_t jl_options; - -// Parse an argc/argv pair to extract general julia options, passing back out -// any arguments that should be passed on to the script. -JL_DLLEXPORT void jl_parse_opts(int *argcp, char ***argvp); - -// Set julia-level ARGS array according to the arguments provided in -// argc/argv -JL_DLLEXPORT void jl_set_ARGS(int argc, char **argv); - -JL_DLLEXPORT int jl_generating_output(void); - -// Settings for code_coverage and malloc_log -// NOTE: if these numbers change, test/cmdlineargs.jl will have to be updated -#define JL_LOG_NONE 0 -#define JL_LOG_USER 1 -#define JL_LOG_ALL 2 - -#define JL_OPTIONS_CHECK_BOUNDS_DEFAULT 0 -#define JL_OPTIONS_CHECK_BOUNDS_ON 1 -#define JL_OPTIONS_CHECK_BOUNDS_OFF 2 - -#define JL_OPTIONS_COMPILE_DEFAULT 1 -#define JL_OPTIONS_COMPILE_OFF 0 -#define JL_OPTIONS_COMPILE_ON 1 -#define JL_OPTIONS_COMPILE_ALL 2 -#define JL_OPTIONS_COMPILE_MIN 3 - -#define JL_OPTIONS_COLOR_ON 1 -#define JL_OPTIONS_COLOR_OFF 2 - -#define JL_OPTIONS_HISTORYFILE_ON 1 -#define JL_OPTIONS_HISTORYFILE_OFF 0 - -#define JL_OPTIONS_STARTUPFILE_ON 1 -#define JL_OPTIONS_STARTUPFILE_OFF 2 - -#define JL_OPTIONS_DEPWARN_OFF 0 -#define JL_OPTIONS_DEPWARN_ON 1 -#define JL_OPTIONS_DEPWARN_ERROR 2 - -#define JL_OPTIONS_POLLY_ON 1 -#define JL_OPTIONS_POLLY_OFF 0 - -#define JL_OPTIONS_FAST_MATH_ON 1 -#define JL_OPTIONS_FAST_MATH_OFF 2 -#define JL_OPTIONS_FAST_MATH_DEFAULT 0 - -#define JL_OPTIONS_HANDLE_SIGNALS_ON 1 -#define JL_OPTIONS_HANDLE_SIGNALS_OFF 0 - -#define JL_OPTIONS_USE_PRECOMPILED_YES 1 -#define JL_OPTIONS_USE_PRECOMPILED_NO 0 - -#define JL_OPTIONS_USE_COMPILECACHE_YES 1 -#define JL_OPTIONS_USE_COMPILECACHE_NO 0 - -// Version information -#include - -JL_DLLEXPORT extern int jl_ver_major(void); -JL_DLLEXPORT extern int jl_ver_minor(void); -JL_DLLEXPORT extern int jl_ver_patch(void); -JL_DLLEXPORT extern int jl_ver_is_release(void); -JL_DLLEXPORT extern const char *jl_ver_string(void); -JL_DLLEXPORT const char *jl_git_branch(void); -JL_DLLEXPORT const char *jl_git_commit(void); - -// nullable struct representations -typedef struct { - uint8_t hasvalue; - double value; -} jl_nullable_float64_t; - -typedef struct { - uint8_t hasvalue; - float value; -} jl_nullable_float32_t; - -#define jl_current_module (jl_get_ptls_states()->current_module) -#define jl_current_task (jl_get_ptls_states()->current_task) -#define jl_root_task (jl_get_ptls_states()->root_task) -#define jl_exception_in_transit (jl_get_ptls_states()->exception_in_transit) - - -// codegen interface ---------------------------------------------------------- - -typedef struct { - // to disable a hook: set to NULL or nothing - - // module setup: prepare a module for code emission (data layout, DWARF version, ...) - // parameters: LLVMModuleRef as Ptr{Void} - // return value: none - jl_value_t *module_setup; - - // module activation: registers debug info, adds module to JIT - // parameters: LLVMModuleRef as Ptr{Void} - // return value: none - jl_value_t *module_activation; - - // exception raising: emit LLVM instructions to raise an exception - // parameters: LLVMBasicBlockRef as Ptr{Void}, LLVMValueRef as Ptr{Void} - // return value: none - jl_value_t *raise_exception; -} jl_cghooks_t; - -typedef struct { - int cached; // can the compiler use/populate the compilation cache? - - // language features (C-style integer booleans) - int runtime; // can we call into the runtime? - int exceptions; // are exceptions supported (requires runtime)? - int track_allocations; // can we track allocations (don't if disallowed)? - int code_coverage; // can we measure coverage (don't if disallowed)? - int static_alloc; // is the compiler allowed to allocate statically? - int dynamic_alloc; // is the compiler allowed to allocate dynamically (requires runtime)? - - jl_cghooks_t hooks; -} jl_cgparams_t; -extern JL_DLLEXPORT jl_cgparams_t jl_default_cgparams; - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/julia-0.6.3/include/julia/julia_threads.h b/julia-0.6.3/include/julia/julia_threads.h deleted file mode 100644 index bbb11d3..0000000 --- a/julia-0.6.3/include/julia/julia_threads.h +++ /dev/null @@ -1,637 +0,0 @@ -// This file is a part of Julia. License is MIT: https://julialang.org/license - -// Meant to be included in -#ifndef JULIA_THREADS_H -#define JULIA_THREADS_H - -// threading ------------------------------------------------------------------ - -// WARNING: Threading support is incomplete and experimental -// Nonetheless, we define JL_THREAD and use it to give advanced notice to -// maintainers of what eventual threading support will change. - -// JULIA_ENABLE_THREADING is switched on in Make.inc if JULIA_THREADS is -// set (in Make.user) - -#if defined(__i386__) && defined(__GNUC__) && !defined(__SSE2__) -# error Julia can only be built for architectures above Pentium 4. Pass -march=pentium4, or set MARCH=pentium4 and ensure that -march is not passed separately with an older architecture. -#endif -#ifdef _COMPILER_MICROSOFT_ -# include -# include -#endif -#if defined(_CPU_X86_64_) || defined(_CPU_X86_) -# include -#endif -#ifndef _OS_WINDOWS_ -# include -#endif -#include - -typedef struct { - jl_taggedvalue_t *freelist; // root of list of free objects - jl_taggedvalue_t *newpages; // root of list of chunks of free objects - uint16_t osize; // size of objects in this pool -} jl_gc_pool_t; - -typedef struct { - // variable for tracking weak references - arraylist_t weak_refs; - - // variables for tracking malloc'd arrays - struct _mallocarray_t *mallocarrays; - struct _mallocarray_t *mafreelist; - - // variables for tracking big objects - struct _bigval_t *big_objects; - - // variables for tracking "remembered set" - arraylist_t rem_bindings; - arraylist_t _remset[2]; // contains jl_value_t* - // lower bound of the number of pointers inside remembered values - int remset_nptr; - arraylist_t *remset; - arraylist_t *last_remset; - - // variables for allocating objects from pools -#ifdef _P64 -# define JL_GC_N_POOLS 41 -#elif defined(_CPU_ARM_) || defined(_CPU_PPC_) || defined(_CPU_X86_) -# define JL_GC_N_POOLS 42 -#else -# define JL_GC_N_POOLS 43 -#endif - jl_gc_pool_t norm_pools[JL_GC_N_POOLS]; -} jl_thread_heap_t; - -// Cache of thread local change to global metadata during GC -// This is sync'd after marking. -typedef struct { - // thread local increment of `perm_scanned_bytes` - size_t perm_scanned_bytes; - // thread local increment of `scanned_bytes` - size_t scanned_bytes; - // Number of queued big objects (<= 1024) - size_t nbig_obj; - // Array of queued big objects to be moved between the young list - // and the old list. - // A set low bit means that the object should be moved from the old list - // to the young list (`mark_reset_age`). - // Objects can only be put into this list when the mark bit is flipped to - // `1` (atomically). Combining with the sync after marking, - // this makes sure that a single objects can only appear once in - // the lists (the mark bit cannot be flipped to `0` without sweeping) - void *big_obj[1024]; -} jl_gc_mark_cache_t; - -// This includes all the thread local states we care about for a thread. -#define JL_MAX_BT_SIZE 80000 -typedef struct _jl_tls_states_t { - struct _jl_gcframe_t *pgcstack; - size_t world_age; - struct _jl_value_t *exception_in_transit; - volatile size_t *safepoint; - // Whether it is safe to execute GC at the same time. -#define JL_GC_STATE_WAITING 1 - // gc_state = 1 means the thread is doing GC or is waiting for the GC to - // finish. -#define JL_GC_STATE_SAFE 2 - // gc_state = 2 means the thread is running unmanaged code that can be - // execute at the same time with the GC. - volatile int8_t gc_state; - volatile int8_t in_finalizer; - int8_t disable_gc; - volatile sig_atomic_t defer_signal; - struct _jl_module_t *current_module; - struct _jl_task_t *volatile current_task; - struct _jl_task_t *root_task; - void *stackbase; - char *stack_lo; - char *stack_hi; - jl_jmp_buf *volatile jmp_target; - jl_jmp_buf base_ctx; // base context of stack - jl_jmp_buf *safe_restore; - int16_t tid; - size_t bt_size; - // JL_MAX_BT_SIZE + 1 elements long - uintptr_t *bt_data; - // Atomically set by the sender, reset by the handler. - volatile sig_atomic_t signal_request; - // Allow the sigint to be raised asynchronously - // this is limited to the few places we do synchronous IO - // we can make this more general (similar to defer_signal) if necessary - volatile sig_atomic_t io_wait; - jl_thread_heap_t heap; -#ifndef _OS_WINDOWS_ - // These are only used on unix now - pthread_t system_id; - void *signal_stack; -#endif - // execution of certain certain impure - // statements is prohibited from certain - // callbacks (such as generated functions) - // as it may make compilation undecidable - int in_pure_callback; - // Counter to disable finalizer **on the current thread** - int finalizers_inhibited; - arraylist_t finalizers; - jl_gc_mark_cache_t gc_cache; -} jl_tls_states_t; -typedef jl_tls_states_t *jl_ptls_t; - -// Update codegen version in `ccall.cpp` after changing either `pause` or `wake` -#ifdef __MIC__ -# define jl_cpu_pause() _mm_delay_64(100) -# define jl_cpu_wake() ((void)0) -# define JL_CPU_WAKE_NOOP 1 -#elif defined(_CPU_X86_64_) || defined(_CPU_X86_) /* !__MIC__ */ -# define jl_cpu_pause() _mm_pause() -# define jl_cpu_wake() ((void)0) -# define JL_CPU_WAKE_NOOP 1 -#elif defined(_CPU_AARCH64_) || (defined(_CPU_ARM_) && __ARM_ARCH >= 7) -# define jl_cpu_pause() __asm__ volatile ("wfe" ::: "memory") -# define jl_cpu_wake() __asm__ volatile ("sev" ::: "memory") -# define JL_CPU_WAKE_NOOP 0 -#else -# define jl_cpu_pause() ((void)0) -# define jl_cpu_wake() ((void)0) -# define JL_CPU_WAKE_NOOP 1 -#endif - -// Copied from libuv. Add `JL_CONST_FUNC` so that the compiler -// can optimize this better. -static inline unsigned long JL_CONST_FUNC jl_thread_self(void) -{ -#ifdef _OS_WINDOWS_ - return (unsigned long)GetCurrentThreadId(); -#else - return (unsigned long)pthread_self(); -#endif -} - -/** - * Thread synchronization primitives: - * - * These roughly follows the c11/c++11 memory model and the act as memory - * barriers at both the compiler level and the hardware level. - * The only exception is the GC safepoint and GC state transitions for which - * we use only a compiler (signal) barrier and use the signal handler to do the - * synchronization in order to lower the mutator overhead as much as possible. - * - * We use the compiler intrinsics to implement a similar API to the c11/c++11 - * one instead of using it directly because, - * - * 1. We support GCC 4.7 and GCC add support for c11 atomics in 4.9. - * Luckily, the __atomic intrinsics were added in GCC 4.7. - * 2. (most importantly) we need interoperability between code written - * in different languages. - * The current c++ standard (c++14) does not allow using c11 atomic - * functions or types and there's currently no guarantee that the two - * types are compatible (although most of them probably are). - * We also need to access these atomic variables from the LLVM JIT code - * which is very hard unless the layout of the object is fully - * specified. - */ -#if defined(__GNUC__) -# define jl_signal_fence() __atomic_signal_fence(__ATOMIC_SEQ_CST) -# define jl_atomic_fetch_add_relaxed(obj, arg) \ - __atomic_fetch_add(obj, arg, __ATOMIC_RELAXED) -# define jl_atomic_fetch_add(obj, arg) \ - __atomic_fetch_add(obj, arg, __ATOMIC_SEQ_CST) -# define jl_atomic_fetch_and_relaxed(obj, arg) \ - __atomic_fetch_and(obj, arg, __ATOMIC_RELAXED) -# define jl_atomic_fetch_and(obj, arg) \ - __atomic_fetch_and(obj, arg, __ATOMIC_SEQ_CST) -# define jl_atomic_fetch_or_relaxed(obj, arg) \ - __atomic_fetch_or(obj, arg, __ATOMIC_RELAXED) -# define jl_atomic_fetch_or(obj, arg) \ - __atomic_fetch_or(obj, arg, __ATOMIC_SEQ_CST) -// Returns the original value of `obj` -// Use the legacy __sync builtins for now, this can also be written using -// the __atomic builtins or c11 atomics with GNU extension or c11 _Generic -# define jl_atomic_compare_exchange(obj, expected, desired) \ - __sync_val_compare_and_swap(obj, expected, desired) -# define jl_atomic_exchange(obj, desired) \ - __atomic_exchange_n(obj, desired, __ATOMIC_SEQ_CST) -# define jl_atomic_exchange_relaxed(obj, desired) \ - __atomic_exchange_n(obj, desired, __ATOMIC_RELAXED) -// TODO: Maybe add jl_atomic_compare_exchange_weak for spin lock -# define jl_atomic_store(obj, val) \ - __atomic_store_n(obj, val, __ATOMIC_SEQ_CST) -# if defined(__clang__) || defined(__ICC) || defined(__INTEL_COMPILER) || \ - !(defined(_CPU_X86_) || defined(_CPU_X86_64_)) -// ICC and Clang doesn't have this bug... -# define jl_atomic_store_release(obj, val) \ - __atomic_store_n(obj, val, __ATOMIC_RELEASE) -# else -// Workaround a GCC bug when using store with release order by using the -// stronger version instead. -// https://gcc.gnu.org/bugzilla/show_bug.cgi?id=67458 -# define jl_atomic_store_release(obj, val) do { \ - jl_signal_fence(); \ - __atomic_store_n(obj, val, __ATOMIC_RELEASE); \ - } while (0) -# endif -# define jl_atomic_load(obj) \ - __atomic_load_n(obj, __ATOMIC_SEQ_CST) -# define jl_atomic_load_acquire(obj) \ - __atomic_load_n(obj, __ATOMIC_ACQUIRE) -#elif defined(_COMPILER_MICROSOFT_) -# define jl_signal_fence() _ReadWriteBarrier() - -// add -template -static inline typename std::enable_if::type -jl_atomic_fetch_add(T *obj, T2 arg) -{ - return (T)_InterlockedExchangeAdd8((volatile char*)obj, (char)arg); -} -template -static inline typename std::enable_if::type -jl_atomic_fetch_add(T *obj, T2 arg) -{ - return (T)_InterlockedExchangeAdd16((volatile short*)obj, (short)arg); -} -template -static inline typename std::enable_if::type -jl_atomic_fetch_add(T *obj, T2 arg) -{ - return (T)_InterlockedExchangeAdd((volatile LONG*)obj, (LONG)arg); -} -template -static inline typename std::enable_if::type -jl_atomic_fetch_add(T *obj, T2 arg) -{ - return (T)_InterlockedExchangeAdd64((volatile __int64*)obj, (__int64)arg); -} -#define jl_atomic_fetch_add_relaxed(obj, arg) jl_atomic_fetch_add(obj, arg) - -// and -template -static inline typename std::enable_if::type -jl_atomic_fetch_and(T *obj, T2 arg) -{ - return (T)_InterlockedAnd8((volatile char*)obj, (char)arg); -} -template -static inline typename std::enable_if::type -jl_atomic_fetch_and(T *obj, T2 arg) -{ - return (T)_InterlockedAnd16((volatile short*)obj, (short)arg); -} -template -static inline typename std::enable_if::type -jl_atomic_fetch_and(T *obj, T2 arg) -{ - return (T)_InterlockedAnd((volatile LONG*)obj, (LONG)arg); -} -template -static inline typename std::enable_if::type -jl_atomic_fetch_and(T *obj, T2 arg) -{ - return (T)_InterlockedAnd64((volatile __int64*)obj, (__int64)arg); -} -#define jl_atomic_fetch_and_relaxed(obj, arg) jl_atomic_fetch_and(obj, arg) - -// or -template -static inline typename std::enable_if::type -jl_atomic_fetch_or(T *obj, T2 arg) -{ - return (T)_InterlockedOr8((volatile char*)obj, (char)arg); -} -template -static inline typename std::enable_if::type -jl_atomic_fetch_or(T *obj, T2 arg) -{ - return (T)_InterlockedOr16((volatile short*)obj, (short)arg); -} -template -static inline typename std::enable_if::type -jl_atomic_fetch_or(T *obj, T2 arg) -{ - return (T)_InterlockedOr((volatile LONG*)obj, (LONG)arg); -} -template -static inline typename std::enable_if::type -jl_atomic_fetch_or(T *obj, T2 arg) -{ - return (T)_InterlockedOr64((volatile __int64*)obj, (__int64)arg); -} -#define jl_atomic_fetch_or_relaxed(obj, arg) jl_atomic_fetch_or(obj, arg) - -// Returns the original value of `obj` -template -static inline typename std::enable_if::type -jl_atomic_compare_exchange(volatile T *obj, T2 expected, T3 desired) -{ - return (T)_InterlockedCompareExchange8((volatile char*)obj, - (char)desired, (char)expected); -} -template -static inline typename std::enable_if::type -jl_atomic_compare_exchange(volatile T *obj, T2 expected, T3 desired) -{ - return (T)_InterlockedCompareExchange16((volatile short*)obj, - (short)desired, (short)expected); -} -template -static inline typename std::enable_if::type -jl_atomic_compare_exchange(volatile T *obj, T2 expected, T3 desired) -{ - return (T)_InterlockedCompareExchange((volatile LONG*)obj, - (LONG)desired, (LONG)expected); -} -template -static inline typename std::enable_if::type -jl_atomic_compare_exchange(volatile T *obj, T2 expected, T3 desired) -{ - return (T)_InterlockedCompareExchange64((volatile __int64*)obj, - (__int64)desired, (__int64)expected); -} -// atomic exchange -template -static inline typename std::enable_if::type -jl_atomic_exchange(volatile T *obj, T2 val) -{ - return _InterlockedExchange8((volatile char*)obj, (char)val); -} -template -static inline typename std::enable_if::type -jl_atomic_exchange(volatile T *obj, T2 val) -{ - return _InterlockedExchange16((volatile short*)obj, (short)val); -} -template -static inline typename std::enable_if::type -jl_atomic_exchange(volatile T *obj, T2 val) -{ - return _InterlockedExchange((volatile LONG*)obj, (LONG)val); -} -template -static inline typename std::enable_if::type -jl_atomic_exchange(volatile T *obj, T2 val) -{ - return _InterlockedExchange64((volatile __int64*)obj, (__int64)val); -} -#define jl_atomic_exchange_relaxed(obj, val) jl_atomic_exchange(obj, val) -// atomic stores -template -static inline typename std::enable_if::type -jl_atomic_store(volatile T *obj, T2 val) -{ - _InterlockedExchange8((volatile char*)obj, (char)val); -} -template -static inline typename std::enable_if::type -jl_atomic_store(volatile T *obj, T2 val) -{ - _InterlockedExchange16((volatile short*)obj, (short)val); -} -template -static inline typename std::enable_if::type -jl_atomic_store(volatile T *obj, T2 val) -{ - _InterlockedExchange((volatile LONG*)obj, (LONG)val); -} -template -static inline typename std::enable_if::type -jl_atomic_store(volatile T *obj, T2 val) -{ - _InterlockedExchange64((volatile __int64*)obj, (__int64)val); -} -template -static inline void jl_atomic_store_release(volatile T *obj, T2 val) -{ - jl_signal_fence(); - *obj = (T)val; -} -// atomic loads -template -static inline T jl_atomic_load(volatile T *obj) -{ - // Trick to generate cheaper instructions compare to `_InterlockedOr` - // Note that we don't care whether the exchange succeeded or not... - return jl_atomic_compare_exchange(obj, T(0), T(0)); -} -template -static inline T jl_atomic_load_acquire(volatile T *obj) -{ - T val = *obj; - jl_signal_fence(); - return val; -} -#else -# error "No atomic operations supported." -#endif - -#ifdef __cplusplus -extern "C" { -#endif - -JL_DLLEXPORT int16_t jl_threadid(void); -JL_DLLEXPORT void *jl_threadgroup(void); -JL_DLLEXPORT void jl_threading_profile(void); -JL_DLLEXPORT void (jl_cpu_pause)(void); -JL_DLLEXPORT void (jl_cpu_wake)(void); - -// Accessing the tls variables, gc safepoint and gc states -JL_DLLEXPORT JL_CONST_FUNC jl_ptls_t (jl_get_ptls_states)(void); -// This triggers a SegFault when we are in GC -// Assign it to a variable to make sure the compiler emit the load -// and to avoid Clang warning for -Wunused-volatile-lvalue -#define jl_gc_safepoint_(ptls) do { \ - jl_signal_fence(); \ - size_t safepoint_load = *ptls->safepoint; \ - jl_signal_fence(); \ - (void)safepoint_load; \ - } while (0) -#define jl_sigint_safepoint(ptls) do { \ - jl_signal_fence(); \ - size_t safepoint_load = ptls->safepoint[-1]; \ - jl_signal_fence(); \ - (void)safepoint_load; \ - } while (0) -#ifndef JULIA_ENABLE_THREADING -extern JL_DLLEXPORT jl_tls_states_t jl_tls_states; -#define jl_get_ptls_states() (&jl_tls_states) -#define jl_gc_state(ptls) ((int8_t)0) -STATIC_INLINE int8_t jl_gc_state_set(jl_ptls_t ptls, int8_t state, - int8_t old_state) -{ - (void)ptls; - (void)state; - return old_state; -} -#else // ifndef JULIA_ENABLE_THREADING -typedef jl_ptls_t (*jl_get_ptls_states_func)(void); -#if !defined(_OS_DARWIN_) && !defined(_OS_WINDOWS_) -JL_DLLEXPORT void jl_set_ptls_states_getter(jl_get_ptls_states_func f); -#endif -// Make sure jl_gc_state() is always a rvalue -#define jl_gc_state(ptls) ((int8_t)ptls->gc_state) -STATIC_INLINE int8_t jl_gc_state_set(jl_ptls_t ptls, int8_t state, - int8_t old_state) -{ - ptls->gc_state = state; - // A safe point is required if we transition from GC-safe region to - // non GC-safe region. - if (old_state && !state) - jl_gc_safepoint_(ptls); - return old_state; -} -#endif // ifndef JULIA_ENABLE_THREADING -STATIC_INLINE int8_t jl_gc_state_save_and_set(jl_ptls_t ptls, - int8_t state) -{ - return jl_gc_state_set(ptls, state, jl_gc_state(ptls)); -} -#define jl_gc_unsafe_enter(ptls) jl_gc_state_save_and_set(ptls, 0) -#define jl_gc_unsafe_leave(ptls, state) ((void)jl_gc_state_set(ptls, (state), 0)) -#define jl_gc_safe_enter(ptls) jl_gc_state_save_and_set(ptls, JL_GC_STATE_SAFE) -#define jl_gc_safe_leave(ptls, state) ((void)jl_gc_state_set(ptls, (state), JL_GC_STATE_SAFE)) -JL_DLLEXPORT void (jl_gc_safepoint)(void); - -#define JL_SIGATOMIC_BEGIN() do { \ - jl_get_ptls_states()->defer_signal++; \ - jl_signal_fence(); \ - } while (0) -#define JL_SIGATOMIC_END() do { \ - jl_signal_fence(); \ - if (--jl_get_ptls_states()->defer_signal == 0) { \ - jl_sigint_safepoint(jl_get_ptls_states()); \ - } \ - } while (0) - -// Recursive spin lock -typedef struct { - volatile unsigned long owner; - uint32_t count; -} jl_mutex_t; - -JL_DLLEXPORT void jl_gc_enable_finalizers(jl_ptls_t ptls, int on); -static inline void jl_lock_frame_push(jl_mutex_t *lock); -static inline void jl_lock_frame_pop(void); - -// JL_LOCK and jl_mutex_lock are GC safe points while JL_LOCK_NOGC -// and jl_mutex_lock_nogc are not. -// Always use JL_LOCK unless no one holding the lock can trigger a GC or GC -// safepoint. JL_LOCK_NOGC should only be needed for GC internal locks. -// The JL_LOCK* and JL_UNLOCK* macros are no-op for non-threading build -// while the jl_mutex_* functions are always locking and unlocking the locks. - -static inline void jl_mutex_wait(jl_mutex_t *lock, int safepoint) -{ - unsigned long self = jl_thread_self(); - unsigned long owner = jl_atomic_load_acquire(&lock->owner); - if (owner == self) { - lock->count++; - return; - } - while (1) { - if (owner == 0 && - jl_atomic_compare_exchange(&lock->owner, 0, self) == 0) { - lock->count = 1; - return; - } - if (safepoint) { - jl_ptls_t ptls = jl_get_ptls_states(); - jl_gc_safepoint_(ptls); - } - jl_cpu_pause(); - owner = lock->owner; - } -} - -static inline void jl_mutex_lock_nogc(jl_mutex_t *lock) -{ - jl_mutex_wait(lock, 0); -} - -static inline void jl_mutex_lock(jl_mutex_t *lock) -{ - jl_ptls_t ptls = jl_get_ptls_states(); - JL_SIGATOMIC_BEGIN(); - jl_mutex_wait(lock, 1); - jl_lock_frame_push(lock); - jl_gc_enable_finalizers(ptls, 0); -} - -/* Call this function for code that could be called from either a managed - or an unmanaged thread */ -static inline void jl_mutex_lock_maybe_nogc(jl_mutex_t *lock) -{ - jl_ptls_t ptls = jl_get_ptls_states(); - if (ptls->safepoint) { - jl_mutex_lock(lock); - } else { - jl_mutex_lock_nogc(lock); - } -} - -static inline void jl_mutex_unlock_nogc(jl_mutex_t *lock) -{ - assert(lock->owner == jl_thread_self() && - "Unlocking a lock in a different thread."); - if (--lock->count == 0) { - jl_atomic_store_release(&lock->owner, 0); - jl_cpu_wake(); - } -} - -static inline void jl_mutex_unlock(jl_mutex_t *lock) -{ - jl_ptls_t ptls = jl_get_ptls_states(); - jl_mutex_unlock_nogc(lock); - jl_gc_enable_finalizers(ptls, 1); - jl_lock_frame_pop(); - JL_SIGATOMIC_END(); -} - -static inline void jl_mutex_unlock_maybe_nogc(jl_mutex_t *lock) { - jl_ptls_t ptls = jl_get_ptls_states(); - if (ptls->safepoint) { - jl_mutex_unlock(lock); - } else { - jl_mutex_unlock_nogc(lock); - } -} - -static inline void jl_mutex_init(jl_mutex_t *lock) -{ - lock->owner = 0; - lock->count = 0; -} - -// Locks -#ifdef JULIA_ENABLE_THREADING -#define JL_MUTEX_INIT(m) jl_mutex_init(m) -#define JL_LOCK(m) jl_mutex_lock(m) -#define JL_UNLOCK(m) jl_mutex_unlock(m) -#define JL_LOCK_NOGC(m) jl_mutex_lock_nogc(m) -#define JL_UNLOCK_NOGC(m) jl_mutex_unlock_nogc(m) -#else // JULIA_ENABLE_THREADING -static inline void jl_mutex_check_type(jl_mutex_t *m) -{ - (void)m; -} -#define JL_MUTEX_INIT(m) jl_mutex_check_type(m) -#define JL_LOCK(m) do { \ - JL_SIGATOMIC_BEGIN(); \ - jl_gc_enable_finalizers(jl_get_ptls_states(), 0); \ - jl_mutex_check_type(m); \ - } while (0) -#define JL_UNLOCK(m) do { \ - jl_gc_enable_finalizers(jl_get_ptls_states(), 1); \ - jl_mutex_check_type(m); \ - JL_SIGATOMIC_END(); \ - } while (0) -#define JL_LOCK_NOGC(m) jl_mutex_check_type(m) -#define JL_UNLOCK_NOGC(m) jl_mutex_check_type(m) -#endif // JULIA_ENABLE_THREADING - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/julia-0.6.3/include/julia/julia_version.h b/julia-0.6.3/include/julia/julia_version.h deleted file mode 100644 index 7ba25d9..0000000 --- a/julia-0.6.3/include/julia/julia_version.h +++ /dev/null @@ -1,9 +0,0 @@ -// This is an autogenerated header file -#ifndef JULIA_VERSION_H -#define JULIA_VERSION_H -#define JULIA_VERSION_STRING "0.6.3" -#define JULIA_VERSION_MAJOR 0 -#define JULIA_VERSION_MINOR 6 -#define JULIA_VERSION_PATCH 3 -#define JULIA_VERSION_IS_RELEASE 1 -#endif diff --git a/julia-0.6.3/include/julia/libsupport.h b/julia-0.6.3/include/julia/libsupport.h deleted file mode 100644 index c93527a..0000000 --- a/julia-0.6.3/include/julia/libsupport.h +++ /dev/null @@ -1,33 +0,0 @@ -// This file is a part of Julia. License is MIT: https://julialang.org/license - -#ifndef LIBSUPPORT_H -#define LIBSUPPORT_H - -#include "platform.h" - -#include -#include -#include -#include "dtypes.h" -#include "utils.h" -#include "utf8.h" -#include "ios.h" -#include "timefuncs.h" -#include "hashing.h" -#include "ptrhash.h" -#include "bitvector.h" -#include "dirpath.h" -#include "strtod.h" -#include "crc32c.h" - -#ifdef __cplusplus -extern "C" { -#endif - -JL_DLLEXPORT void libsupport_init(void); - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/julia-0.6.3/include/julia/platform.h b/julia-0.6.3/include/julia/platform.h deleted file mode 100644 index 3a4751a..0000000 --- a/julia-0.6.3/include/julia/platform.h +++ /dev/null @@ -1,113 +0,0 @@ -// This file is a part of Julia. License is MIT: https://julialang.org/license - -#ifndef PLATFORM_H -#define PLATFORM_H - -/* - * This file provides convenient macros to be used to identify the platform - * based of compiler-specific pre-defined macros. It is based on the - * information that can be found at the following address: - * - * http://sourceforge.net/p/predef/wiki/Home/ - * - * Possible values include: - * Compiler: - * _COMPILER_CLANG_ - * _COMPILER_GCC_ - * _COMPILER_INTEL_ - * _COMPILER_MICROSOFT_ - * _COMPILER_MINGW_ - * OS: - * _OS_FREEBSD_ - * _OS_LINUX_ - * _OS_WINDOWS_ - * _OS_DARWIN_ - * - * CPU/Architecture: - * _CPU_X86_ - * _CPU_X86_64_ - * _CPU_ARM_ - */ - -/******************************************************************************* -* Compiler * -*******************************************************************************/ - -/* - * Notes: - * - * 1. Checking for Intel's compiler should be done before checking for - * Microsoft's. On Windows Intel's compiler also defines _MSC_VER as the - * acknoledgement of the fact that it is integrated with Visual Studio. - * - * 2. Checking for MinGW should be done before checking for GCC as MinGW - * pretends to be GCC. - */ -#if defined(__clang__) -#define _COMPILER_CLANG_ -// Clang can also be used as a MinGW compiler -#if defined(__MINGW32__) -#define _COMPILER_MINGW_ -#endif -#elif defined(__INTEL_COMPILER) || defined(__ICC) -#define _COMPILER_INTEL_ -#elif defined(__MINGW32__) -#define _COMPILER_MINGW_ -#elif defined(_MSC_VER) -#define _COMPILER_MICROSOFT_ -#elif defined(__GNUC__) -#define _COMPILER_GCC_ -#endif - -/******************************************************************************* -* OS * -*******************************************************************************/ - -#if defined(__FreeBSD__) -#define _OS_FREEBSD_ -#elif defined(__linux__) -#define _OS_LINUX_ -#elif defined(_WIN32) || defined(_WIN64) -#define _OS_WINDOWS_ -#elif defined(__APPLE__) && defined(__MACH__) -#define _OS_DARWIN_ -#endif - -/******************************************************************************* -* Architecture * -*******************************************************************************/ - -#if defined(__amd64__) || defined(__amd64) || defined(__x86_64__) || defined(__x86_64) || defined(_M_X64) || defined(_M_AMD64) -#define _CPU_X86_64_ -#elif defined(i386) || defined(__i386) || defined(__i386__) || defined(_M_IX86) || defined(_X86_) -#define _CPU_X86_ -#elif defined(__aarch64__) -#define _CPU_AARCH64_ -#elif defined(__arm__) || defined(_M_ARM) -#define _CPU_ARM_ -#elif defined(__PPC64__) -#define _CPU_PPC64_ -#elif defined(_ARCH_PPC) -#define _CPU_PPC_ -#endif - -#if defined(_CPU_X86_64_) -# define _P64 -#elif defined(_CPU_X86_) -# define _P32 -#elif defined(_OS_WINDOWS_) -/* Not sure how to determine pointer size on Windows running ARM. */ -# if _WIN64 -# define _P64 -# else -# define _P32 -# endif -#elif __SIZEOF_POINTER__ == 8 -# define _P64 -#elif __SIZEOF_POINTER__ == 4 -# define _P32 -#else -# error pointer size not known for your platform / compiler -#endif - -#endif /* !PLATFORM_H */ diff --git a/julia-0.6.3/include/julia/ptrhash.h b/julia-0.6.3/include/julia/ptrhash.h deleted file mode 100644 index 062287e..0000000 --- a/julia-0.6.3/include/julia/ptrhash.h +++ /dev/null @@ -1,18 +0,0 @@ -// This file is a part of Julia. License is MIT: https://julialang.org/license - -#ifndef PTRHASH_H -#define PTRHASH_H - -#include "htable.h" - -#ifdef __cplusplus -extern "C" { -#endif - -HTPROT(ptrhash) - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/julia-0.6.3/include/julia/strtod.h b/julia-0.6.3/include/julia/strtod.h deleted file mode 100644 index 1d4f08d..0000000 --- a/julia-0.6.3/include/julia/strtod.h +++ /dev/null @@ -1,17 +0,0 @@ -// This file is a part of Julia. License is MIT: https://julialang.org/license - -#ifndef STRTOD_H -#define STRTOD_H - -#ifdef __cplusplus -extern "C" { -#endif - -JL_DLLEXPORT double jl_strtod_c(const char *nptr, char **endptr); -JL_DLLEXPORT float jl_strtof_c(const char *nptr, char **endptr); - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/julia-0.6.3/include/julia/timefuncs.h b/julia-0.6.3/include/julia/timefuncs.h deleted file mode 100644 index 12533e3..0000000 --- a/julia-0.6.3/include/julia/timefuncs.h +++ /dev/null @@ -1,23 +0,0 @@ -// This file is a part of Julia. License is MIT: https://julialang.org/license - -#ifndef TIMEFUNCS_H -#define TIMEFUNCS_H - -#ifdef __cplusplus -extern "C" { -#endif - -struct jl_timeval { - int64_t sec; /* seconds */ - int64_t usec; /* microseconds */ -}; - -JL_DLLEXPORT int jl_gettimeofday(struct jl_timeval *jtv); -JL_DLLEXPORT double jl_clock_now(void); -void sleep_ms(int ms); - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/julia-0.6.3/include/julia/tzfile.h b/julia-0.6.3/include/julia/tzfile.h deleted file mode 100644 index b19046c..0000000 --- a/julia-0.6.3/include/julia/tzfile.h +++ /dev/null @@ -1,170 +0,0 @@ -/* $NetBSD: tzfile.h,v 1.8 2015/07/11 16:40:53 christos Exp $ */ - -#ifndef _TZFILE_H_ -#define _TZFILE_H_ - -/* -** This file is in the public domain, so clarified as of -** 1996-06-05 by Arthur David Olson. -*/ - -/* -** This header is for use ONLY with the time conversion code. -** There is no guarantee that it will remain unchanged, -** or that it will remain at all. -** Do NOT copy it to any system include directory. -** Thank you! -*/ - -/* -** Information about time zone files. -*/ - -#ifndef TZDIR /* Time zone object file directory */ -#define TZDIR "/usr/share/zoneinfo" -#endif /* !defined TZDIR */ - -#ifndef TZDEFAULT -#define TZDEFAULT "/etc/localtime" -#endif /* !defined TZDEFAULT */ - -#ifndef TZDEFRULES -#define TZDEFRULES "posixrules" -#endif /* !defined TZDEFRULES */ - -/* -** Each file begins with. . . -*/ - -#define TZ_MAGIC "TZif" - -struct tzhead { - char tzh_magic[4]; /* TZ_MAGIC */ - char tzh_version[1]; /* '\0' or '2' or '3' as of 2013 */ - char tzh_reserved[15]; /* reserved; must be zero */ - char tzh_ttisgmtcnt[4]; /* coded number of trans. time flags */ - char tzh_ttisstdcnt[4]; /* coded number of trans. time flags */ - char tzh_leapcnt[4]; /* coded number of leap seconds */ - char tzh_timecnt[4]; /* coded number of transition times */ - char tzh_typecnt[4]; /* coded number of local time types */ - char tzh_charcnt[4]; /* coded number of abbr. chars */ -}; - -/* -** . . .followed by. . . -** -** tzh_timecnt (char [4])s coded transition times a la time(2) -** tzh_timecnt (unsigned char)s types of local time starting at above -** tzh_typecnt repetitions of -** one (char [4]) coded UT offset in seconds -** one (unsigned char) used to set tm_isdst -** one (unsigned char) that's an abbreviation list index -** tzh_charcnt (char)s '\0'-terminated zone abbreviations -** tzh_leapcnt repetitions of -** one (char [4]) coded leap second transition times -** one (char [4]) total correction after above -** tzh_ttisstdcnt (char)s indexed by type; if 1, transition -** time is standard time, if 0, -** transition time is wall clock time -** if absent, transition times are -** assumed to be wall clock time -** tzh_ttisgmtcnt (char)s indexed by type; if 1, transition -** time is UT, if 0, -** transition time is local time -** if absent, transition times are -** assumed to be local time -*/ - -/* -** If tzh_version is '2' or greater, the above is followed by a second instance -** of tzhead and a second instance of the data in which each coded transition -** time uses 8 rather than 4 chars, -** then a POSIX-TZ-environment-variable-style string for use in handling -** instants after the last transition time stored in the file -** (with nothing between the newlines if there is no POSIX representation for -** such instants). -** -** If tz_version is '3' or greater, the above is extended as follows. -** First, the POSIX TZ string's hour offset may range from -167 -** through 167 as compared to the POSIX-required 0 through 24. -** Second, its DST start time may be January 1 at 00:00 and its stop -** time December 31 at 24:00 plus the difference between DST and -** standard time, indicating DST all year. -*/ - -/* -** In the current implementation, "tzset()" refuses to deal with files that -** exceed any of the limits below. -*/ - -#ifndef TZ_MAX_TIMES -#define TZ_MAX_TIMES 2000 -#endif /* !defined TZ_MAX_TIMES */ - -#ifndef TZ_MAX_TYPES -/* This must be at least 17 for Europe/Samara and Europe/Vilnius. */ -#define TZ_MAX_TYPES 256 /* Limited by what (unsigned char)'s can hold */ -#endif /* !defined TZ_MAX_TYPES */ - -#ifndef TZ_MAX_CHARS -#define TZ_MAX_CHARS 50 /* Maximum number of abbreviation characters */ - /* (limited by what unsigned chars can hold) */ -#endif /* !defined TZ_MAX_CHARS */ - -#ifndef TZ_MAX_LEAPS -#define TZ_MAX_LEAPS 50 /* Maximum number of leap second corrections */ -#endif /* !defined TZ_MAX_LEAPS */ - -#define SECSPERMIN 60 -#define MINSPERHOUR 60 -#define HOURSPERDAY 24 -#define DAYSPERWEEK 7 -#define DAYSPERNYEAR 365 -#define DAYSPERLYEAR 366 -#define SECSPERHOUR (SECSPERMIN * MINSPERHOUR) -#define SECSPERDAY ((int_fast32_t) SECSPERHOUR * HOURSPERDAY) -#define MONSPERYEAR 12 - -#define TM_SUNDAY 0 -#define TM_MONDAY 1 -#define TM_TUESDAY 2 -#define TM_WEDNESDAY 3 -#define TM_THURSDAY 4 -#define TM_FRIDAY 5 -#define TM_SATURDAY 6 - -#define TM_JANUARY 0 -#define TM_FEBRUARY 1 -#define TM_MARCH 2 -#define TM_APRIL 3 -#define TM_MAY 4 -#define TM_JUNE 5 -#define TM_JULY 6 -#define TM_AUGUST 7 -#define TM_SEPTEMBER 8 -#define TM_OCTOBER 9 -#define TM_NOVEMBER 10 -#define TM_DECEMBER 11 - -#define TM_YEAR_BASE 1900 - -#define EPOCH_YEAR 1970 -#define EPOCH_WDAY TM_THURSDAY - -#define isleap(y) (((y) % 4) == 0 && (((y) % 100) != 0 || ((y) % 400) == 0)) - -/* -** Since everything in isleap is modulo 400 (or a factor of 400), we know that -** isleap(y) == isleap(y % 400) -** and so -** isleap(a + b) == isleap((a + b) % 400) -** or -** isleap(a + b) == isleap(a % 400 + b % 400) -** This is true even if % means modulo rather than Fortran remainder -** (which is allowed by C89 but not C99). -** We use this to avoid addition overflow problems. -*/ - -#define isleap_sum(a, b) isleap((a) % 400 + (b) % 400) - -#endif /* !defined _TZFILE_H_ */ diff --git a/julia-0.6.3/include/julia/utf8.h b/julia-0.6.3/include/julia/utf8.h deleted file mode 100644 index 486243b..0000000 --- a/julia-0.6.3/include/julia/utf8.h +++ /dev/null @@ -1,104 +0,0 @@ -// This file is a part of Julia. License is MIT: https://julialang.org/license - -#ifndef UTF8_H -#define UTF8_H - -#ifdef __cplusplus -extern "C" { -#endif - -/* is c the start of a utf8 sequence? */ -#define isutf(c) (((c)&0xC0)!=0x80) - -#define UEOF ((uint32_t)-1) - -/* convert UTF-8 data to wide character */ -size_t u8_toucs(uint32_t *dest, size_t sz, const char *src, size_t srcsz); - -/* the opposite conversion */ -size_t u8_toutf8(char *dest, size_t sz, const uint32_t *src, size_t srcsz); - -/* single character to UTF-8, returns # bytes written */ -size_t u8_wc_toutf8(char *dest, uint32_t ch); - -/* character number to byte offset */ -JL_DLLEXPORT size_t u8_offset(const char *str, size_t charnum); - -/* byte offset to character number */ -JL_DLLEXPORT size_t u8_charnum(const char *str, size_t offset); - -/* return next character, updating an index variable */ -uint32_t u8_nextchar(const char *s, size_t *i); - -/* next character without NUL character terminator */ -uint32_t u8_nextmemchar(const char *s, size_t *i); - -/* move to next character */ -void u8_inc(const char *s, size_t *i); - -/* move to previous character */ -void u8_dec(const char *s, size_t *i); - -/* returns length of next utf-8 sequence */ -size_t u8_seqlen(const char *s); - -/* returns the # of bytes needed to encode a certain character */ -size_t u8_charlen(uint32_t ch); - -char read_escape_control_char(char c); - -/* assuming src points to the character after a backslash, read an - escape sequence, storing the result in dest and returning the number of - input characters processed */ -size_t u8_read_escape_sequence(const char *src, size_t ssz, uint32_t *dest); - -/* given a wide character, convert it to an ASCII escape sequence stored in - buf, where buf is "sz" bytes. returns the number of characters output. - sz must be at least 3. */ -int u8_escape_wchar(char *buf, size_t sz, uint32_t ch); - -/* convert UTF-8 "src" to escape sequences. - - sz is buf size in bytes. must be at least 12. - - if escape_quotes is nonzero, quote characters will be escaped. - - if ascii is nonzero, the output is 7-bit ASCII, no UTF-8 survives. - - starts at src[*pi], updates *pi to point to the first unprocessed - byte of the input. - - end is one more than the last allowable value of *pi. - - returns number of bytes placed in buf, including a NUL terminator. -*/ -size_t u8_escape(char *buf, size_t sz, const char *src, size_t *pi, size_t end, - int escape_quotes, int ascii); - -/* utility predicates used by the above */ -int octal_digit(char c); -int hex_digit(char c); - -/* same as the above, but searches a buffer of a given size instead of - a NUL-terminated string. */ -char *u8_memchr(const char *s, uint32_t ch, size_t sz, size_t *charn); - -char *u8_memrchr(const char *s, uint32_t ch, size_t sz); - -/* number of columns occupied by a string */ -JL_DLLEXPORT size_t u8_strwidth(const char *s); - -/* printf where the format string and arguments may be in UTF-8. - you can avoid this function and just use ordinary printf() if the current - locale is UTF-8. */ -size_t u8_vprintf(const char *fmt, va_list ap); -size_t u8_printf(const char *fmt, ...); - -/* determine whether a sequence of bytes is valid UTF-8. length is in bytes */ -JL_DLLEXPORT int u8_isvalid(const char *str, size_t length); - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/julia-0.6.3/include/julia/utils.h b/julia-0.6.3/include/julia/utils.h deleted file mode 100644 index 930f54f..0000000 --- a/julia-0.6.3/include/julia/utils.h +++ /dev/null @@ -1,63 +0,0 @@ -// This file is a part of Julia. License is MIT: https://julialang.org/license - -#ifndef UTILS_H -#define UTILS_H - -#ifdef __cplusplus -extern "C" { -#endif - -JL_DLLEXPORT char *uint2str(char *dest, size_t len, uint64_t num, uint32_t base); -int str2int(char *str, size_t len, int64_t *res, uint32_t base); -int isdigit_base(char c, int base); - -double conv_to_double(void *data, numerictype_t tag); -int64_t conv_to_int64(void *data, numerictype_t tag); -uint64_t conv_to_uint64(void *data, numerictype_t tag); -int32_t conv_to_int32(void *data, numerictype_t tag); -uint32_t conv_to_uint32(void *data, numerictype_t tag); -#ifdef _P64 -#define conv_to_ptrdiff conv_to_int64 -#define conv_to_size conv_to_uint64 -#else -#define conv_to_ptrdiff conv_to_int32 -#define conv_to_size conv_to_uint32 -#endif -int cmp_same_lt(void *a, void *b, numerictype_t tag); -int cmp_same_eq(void *a, void *b, numerictype_t tag); -int cmp_lt(void *a, numerictype_t atag, void *b, numerictype_t btag); -int cmp_eq(void *a, numerictype_t atag, void *b, numerictype_t btag, - int equalnans); - -#if defined(__clang__) || (defined(__GNUC__) && (__GNUC__ > 4 || __GNUC_MINOR__ >= 8)) -#define bswap_16(x) __builtin_bswap16(x) -#define bswap_32(x) __builtin_bswap32(x) -#define bswap_64(x) __builtin_bswap64(x) -#elif defined(_MSC_VER) -#define bswap_16(x) _byteswap_ushort(x) -#define bswap_32(x) _byteswap_ulong(x) -#define bswap_64(x) _byteswap_uint64(x) -#elif defined(__INTEL_COMPILER) -#define bswap_16(x) _bswap16(x) -#define bswap_32(x) _bswap(x) -#define bswap_64(x) _bswap64(x) -#else -#define bswap_16(x) (((x) & 0x00ff) << 8 | ((x) & 0xff00) >> 8) -#define bswap_32(x) \ - ((((x) & 0xff000000) >> 24) | (((x) & 0x00ff0000) >> 8) | \ - (((x) & 0x0000ff00) << 8) | (((x) & 0x000000ff) << 24)) -STATIC_INLINE uint64_t ByteSwap64(uint64_t x) -{ - uint32_t high = (uint32_t) (x >> 32); - uint32_t low = (uint32_t) x; - return ((uint64_t) bswap_32 (high)) | - (((uint64_t) bswap_32 (low)) << 32); -} -#define bswap_64(x) ByteSwap64(x) -#endif - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/julia-0.6.3/include/julia/uv-errno.h b/julia-0.6.3/include/julia/uv-errno.h deleted file mode 100644 index 53f3029..0000000 --- a/julia-0.6.3/include/julia/uv-errno.h +++ /dev/null @@ -1,418 +0,0 @@ -/* Copyright Joyent, Inc. and other Node contributors. All rights reserved. - * - * 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 NONINFRINGEMENT. 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. - */ - -#ifndef UV_ERRNO_H_ -#define UV_ERRNO_H_ - -#include - -#define UV__EOF (-4095) -#define UV__UNKNOWN (-4094) - -#define UV__EAI_ADDRFAMILY (-3000) -#define UV__EAI_AGAIN (-3001) -#define UV__EAI_BADFLAGS (-3002) -#define UV__EAI_CANCELED (-3003) -#define UV__EAI_FAIL (-3004) -#define UV__EAI_FAMILY (-3005) -#define UV__EAI_MEMORY (-3006) -#define UV__EAI_NODATA (-3007) -#define UV__EAI_NONAME (-3008) -#define UV__EAI_OVERFLOW (-3009) -#define UV__EAI_SERVICE (-3010) -#define UV__EAI_SOCKTYPE (-3011) -#define UV__EAI_BADHINTS (-3013) -#define UV__EAI_PROTOCOL (-3014) - -/* Only map to the system errno on non-Windows platforms. It's apparently - * a fairly common practice for Windows programmers to redefine errno codes. - */ -#if defined(E2BIG) && !defined(_WIN32) -# define UV__E2BIG (-E2BIG) -#else -# define UV__E2BIG (-4093) -#endif - -#if defined(EACCES) && !defined(_WIN32) -# define UV__EACCES (-EACCES) -#else -# define UV__EACCES (-4092) -#endif - -#if defined(EADDRINUSE) && !defined(_WIN32) -# define UV__EADDRINUSE (-EADDRINUSE) -#else -# define UV__EADDRINUSE (-4091) -#endif - -#if defined(EADDRNOTAVAIL) && !defined(_WIN32) -# define UV__EADDRNOTAVAIL (-EADDRNOTAVAIL) -#else -# define UV__EADDRNOTAVAIL (-4090) -#endif - -#if defined(EAFNOSUPPORT) && !defined(_WIN32) -# define UV__EAFNOSUPPORT (-EAFNOSUPPORT) -#else -# define UV__EAFNOSUPPORT (-4089) -#endif - -#if defined(EAGAIN) && !defined(_WIN32) -# define UV__EAGAIN (-EAGAIN) -#else -# define UV__EAGAIN (-4088) -#endif - -#if defined(EALREADY) && !defined(_WIN32) -# define UV__EALREADY (-EALREADY) -#else -# define UV__EALREADY (-4084) -#endif - -#if defined(EBADF) && !defined(_WIN32) -# define UV__EBADF (-EBADF) -#else -# define UV__EBADF (-4083) -#endif - -#if defined(EBUSY) && !defined(_WIN32) -# define UV__EBUSY (-EBUSY) -#else -# define UV__EBUSY (-4082) -#endif - -#if defined(ECANCELED) && !defined(_WIN32) -# define UV__ECANCELED (-ECANCELED) -#else -# define UV__ECANCELED (-4081) -#endif - -#if defined(ECHARSET) && !defined(_WIN32) -# define UV__ECHARSET (-ECHARSET) -#else -# define UV__ECHARSET (-4080) -#endif - -#if defined(ECONNABORTED) && !defined(_WIN32) -# define UV__ECONNABORTED (-ECONNABORTED) -#else -# define UV__ECONNABORTED (-4079) -#endif - -#if defined(ECONNREFUSED) && !defined(_WIN32) -# define UV__ECONNREFUSED (-ECONNREFUSED) -#else -# define UV__ECONNREFUSED (-4078) -#endif - -#if defined(ECONNRESET) && !defined(_WIN32) -# define UV__ECONNRESET (-ECONNRESET) -#else -# define UV__ECONNRESET (-4077) -#endif - -#if defined(EDESTADDRREQ) && !defined(_WIN32) -# define UV__EDESTADDRREQ (-EDESTADDRREQ) -#else -# define UV__EDESTADDRREQ (-4076) -#endif - -#if defined(EEXIST) && !defined(_WIN32) -# define UV__EEXIST (-EEXIST) -#else -# define UV__EEXIST (-4075) -#endif - -#if defined(EFAULT) && !defined(_WIN32) -# define UV__EFAULT (-EFAULT) -#else -# define UV__EFAULT (-4074) -#endif - -#if defined(EHOSTUNREACH) && !defined(_WIN32) -# define UV__EHOSTUNREACH (-EHOSTUNREACH) -#else -# define UV__EHOSTUNREACH (-4073) -#endif - -#if defined(EINTR) && !defined(_WIN32) -# define UV__EINTR (-EINTR) -#else -# define UV__EINTR (-4072) -#endif - -#if defined(EINVAL) && !defined(_WIN32) -# define UV__EINVAL (-EINVAL) -#else -# define UV__EINVAL (-4071) -#endif - -#if defined(EIO) && !defined(_WIN32) -# define UV__EIO (-EIO) -#else -# define UV__EIO (-4070) -#endif - -#if defined(EISCONN) && !defined(_WIN32) -# define UV__EISCONN (-EISCONN) -#else -# define UV__EISCONN (-4069) -#endif - -#if defined(EISDIR) && !defined(_WIN32) -# define UV__EISDIR (-EISDIR) -#else -# define UV__EISDIR (-4068) -#endif - -#if defined(ELOOP) && !defined(_WIN32) -# define UV__ELOOP (-ELOOP) -#else -# define UV__ELOOP (-4067) -#endif - -#if defined(EMFILE) && !defined(_WIN32) -# define UV__EMFILE (-EMFILE) -#else -# define UV__EMFILE (-4066) -#endif - -#if defined(EMSGSIZE) && !defined(_WIN32) -# define UV__EMSGSIZE (-EMSGSIZE) -#else -# define UV__EMSGSIZE (-4065) -#endif - -#if defined(ENAMETOOLONG) && !defined(_WIN32) -# define UV__ENAMETOOLONG (-ENAMETOOLONG) -#else -# define UV__ENAMETOOLONG (-4064) -#endif - -#if defined(ENETDOWN) && !defined(_WIN32) -# define UV__ENETDOWN (-ENETDOWN) -#else -# define UV__ENETDOWN (-4063) -#endif - -#if defined(ENETUNREACH) && !defined(_WIN32) -# define UV__ENETUNREACH (-ENETUNREACH) -#else -# define UV__ENETUNREACH (-4062) -#endif - -#if defined(ENFILE) && !defined(_WIN32) -# define UV__ENFILE (-ENFILE) -#else -# define UV__ENFILE (-4061) -#endif - -#if defined(ENOBUFS) && !defined(_WIN32) -# define UV__ENOBUFS (-ENOBUFS) -#else -# define UV__ENOBUFS (-4060) -#endif - -#if defined(ENODEV) && !defined(_WIN32) -# define UV__ENODEV (-ENODEV) -#else -# define UV__ENODEV (-4059) -#endif - -#if defined(ENOENT) && !defined(_WIN32) -# define UV__ENOENT (-ENOENT) -#else -# define UV__ENOENT (-4058) -#endif - -#if defined(ENOMEM) && !defined(_WIN32) -# define UV__ENOMEM (-ENOMEM) -#else -# define UV__ENOMEM (-4057) -#endif - -#if defined(ENONET) && !defined(_WIN32) -# define UV__ENONET (-ENONET) -#else -# define UV__ENONET (-4056) -#endif - -#if defined(ENOSPC) && !defined(_WIN32) -# define UV__ENOSPC (-ENOSPC) -#else -# define UV__ENOSPC (-4055) -#endif - -#if defined(ENOSYS) && !defined(_WIN32) -# define UV__ENOSYS (-ENOSYS) -#else -# define UV__ENOSYS (-4054) -#endif - -#if defined(ENOTCONN) && !defined(_WIN32) -# define UV__ENOTCONN (-ENOTCONN) -#else -# define UV__ENOTCONN (-4053) -#endif - -#if defined(ENOTDIR) && !defined(_WIN32) -# define UV__ENOTDIR (-ENOTDIR) -#else -# define UV__ENOTDIR (-4052) -#endif - -#if defined(ENOTEMPTY) && !defined(_WIN32) -# define UV__ENOTEMPTY (-ENOTEMPTY) -#else -# define UV__ENOTEMPTY (-4051) -#endif - -#if defined(ENOTSOCK) && !defined(_WIN32) -# define UV__ENOTSOCK (-ENOTSOCK) -#else -# define UV__ENOTSOCK (-4050) -#endif - -#if defined(ENOTSUP) && !defined(_WIN32) -# define UV__ENOTSUP (-ENOTSUP) -#else -# define UV__ENOTSUP (-4049) -#endif - -#if defined(EPERM) && !defined(_WIN32) -# define UV__EPERM (-EPERM) -#else -# define UV__EPERM (-4048) -#endif - -#if defined(EPIPE) && !defined(_WIN32) -# define UV__EPIPE (-EPIPE) -#else -# define UV__EPIPE (-4047) -#endif - -#if defined(EPROTO) && !defined(_WIN32) -# define UV__EPROTO (-EPROTO) -#else -# define UV__EPROTO (-4046) -#endif - -#if defined(EPROTONOSUPPORT) && !defined(_WIN32) -# define UV__EPROTONOSUPPORT (-EPROTONOSUPPORT) -#else -# define UV__EPROTONOSUPPORT (-4045) -#endif - -#if defined(EPROTOTYPE) && !defined(_WIN32) -# define UV__EPROTOTYPE (-EPROTOTYPE) -#else -# define UV__EPROTOTYPE (-4044) -#endif - -#if defined(EROFS) && !defined(_WIN32) -# define UV__EROFS (-EROFS) -#else -# define UV__EROFS (-4043) -#endif - -#if defined(ESHUTDOWN) && !defined(_WIN32) -# define UV__ESHUTDOWN (-ESHUTDOWN) -#else -# define UV__ESHUTDOWN (-4042) -#endif - -#if defined(ESPIPE) && !defined(_WIN32) -# define UV__ESPIPE (-ESPIPE) -#else -# define UV__ESPIPE (-4041) -#endif - -#if defined(ESRCH) && !defined(_WIN32) -# define UV__ESRCH (-ESRCH) -#else -# define UV__ESRCH (-4040) -#endif - -#if defined(ETIMEDOUT) && !defined(_WIN32) -# define UV__ETIMEDOUT (-ETIMEDOUT) -#else -# define UV__ETIMEDOUT (-4039) -#endif - -#if defined(ETXTBSY) && !defined(_WIN32) -# define UV__ETXTBSY (-ETXTBSY) -#else -# define UV__ETXTBSY (-4038) -#endif - -#if defined(EXDEV) && !defined(_WIN32) -# define UV__EXDEV (-EXDEV) -#else -# define UV__EXDEV (-4037) -#endif - -#if defined(EFBIG) && !defined(_WIN32) -# define UV__EFBIG (-EFBIG) -#else -# define UV__EFBIG (-4036) -#endif - -#if defined(ENOPROTOOPT) && !defined(_WIN32) -# define UV__ENOPROTOOPT (-ENOPROTOOPT) -#else -# define UV__ENOPROTOOPT (-4035) -#endif - -#if defined(ERANGE) && !defined(_WIN32) -# define UV__ERANGE (-ERANGE) -#else -# define UV__ERANGE (-4034) -#endif - -#if defined(ENXIO) && !defined(_WIN32) -# define UV__ENXIO (-ENXIO) -#else -# define UV__ENXIO (-4033) -#endif - -#if defined(EMLINK) && !defined(_WIN32) -# define UV__EMLINK (-EMLINK) -#else -# define UV__EMLINK (-4032) -#endif - -/* EHOSTDOWN is not visible on BSD-like systems when _POSIX_C_SOURCE is - * defined. Fortunately, its value is always 64 so it's possible albeit - * icky to hard-code it. - */ -#if defined(EHOSTDOWN) && !defined(_WIN32) -# define UV__EHOSTDOWN (-EHOSTDOWN) -#elif defined(__APPLE__) || \ - defined(__DragonFly__) || \ - defined(__FreeBSD__) || \ - defined(__NetBSD__) || \ - defined(__OpenBSD__) -# define UV__EHOSTDOWN (-64) -#else -# define UV__EHOSTDOWN (-4031) -#endif - -#endif /* UV_ERRNO_H_ */ diff --git a/julia-0.6.3/include/julia/uv-linux.h b/julia-0.6.3/include/julia/uv-linux.h deleted file mode 100644 index 9b38405..0000000 --- a/julia-0.6.3/include/julia/uv-linux.h +++ /dev/null @@ -1,34 +0,0 @@ -/* Copyright Joyent, Inc. and other Node contributors. All rights reserved. - * - * 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 NONINFRINGEMENT. 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. - */ - -#ifndef UV_LINUX_H -#define UV_LINUX_H - -#define UV_PLATFORM_LOOP_FIELDS \ - uv__io_t inotify_read_watcher; \ - void* inotify_watchers; \ - int inotify_fd; \ - -#define UV_PLATFORM_FS_EVENT_FIELDS \ - void* watchers[2]; \ - int wd; \ - -#endif /* UV_LINUX_H */ diff --git a/julia-0.6.3/include/julia/uv-threadpool.h b/julia-0.6.3/include/julia/uv-threadpool.h deleted file mode 100644 index 9708ebd..0000000 --- a/julia-0.6.3/include/julia/uv-threadpool.h +++ /dev/null @@ -1,37 +0,0 @@ -/* Copyright Joyent, Inc. and other Node contributors. All rights reserved. - * - * 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 NONINFRINGEMENT. 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. - */ - -/* - * This file is private to libuv. It provides common functionality to both - * Windows and Unix backends. - */ - -#ifndef UV_THREADPOOL_H_ -#define UV_THREADPOOL_H_ - -struct uv__work { - void (*work)(struct uv__work *w); - void (*done)(struct uv__work *w, int status); - struct uv_loop_s* loop; - void* wq[2]; -}; - -#endif /* UV_THREADPOOL_H_ */ diff --git a/julia-0.6.3/include/julia/uv-unix.h b/julia-0.6.3/include/julia/uv-unix.h deleted file mode 100644 index 99e8664..0000000 --- a/julia-0.6.3/include/julia/uv-unix.h +++ /dev/null @@ -1,384 +0,0 @@ -/* Copyright Joyent, Inc. and other Node contributors. All rights reserved. - * - * 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 NONINFRINGEMENT. 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. - */ - -#ifndef UV_UNIX_H -#define UV_UNIX_H - -#include -#include -#include -#include - -#include -#include -#include -#include -#include - -#include -#include - -#include -#include -#include -#ifdef __ANDROID__ -#include "pthread-fixes.h" -#endif -#include - -#include "uv-threadpool.h" - -#if defined(__linux__) -# include "uv-linux.h" -#elif defined(_AIX) -# include "uv-aix.h" -#elif defined(__sun) -# include "uv-sunos.h" -#elif defined(__APPLE__) -# include "uv-darwin.h" -#elif defined(__DragonFly__) || \ - defined(__FreeBSD__) || \ - defined(__OpenBSD__) || \ - defined(__NetBSD__) -# include "uv-bsd.h" -#endif - -#ifndef NI_MAXHOST -# define NI_MAXHOST 1025 -#endif - -#ifndef NI_MAXSERV -# define NI_MAXSERV 32 -#endif - -#ifndef UV_IO_PRIVATE_PLATFORM_FIELDS -# define UV_IO_PRIVATE_PLATFORM_FIELDS /* empty */ -#endif - -struct uv__io_s; -struct uv__async; -struct uv_loop_s; - -typedef void (*uv__io_cb)(struct uv_loop_s* loop, - struct uv__io_s* w, - unsigned int events); -typedef struct uv__io_s uv__io_t; - -struct uv__io_s { - uv__io_cb cb; - void* pending_queue[2]; - void* watcher_queue[2]; - unsigned int pevents; /* Pending event mask i.e. mask at next tick. */ - unsigned int events; /* Current event mask. */ - int fd; - UV_IO_PRIVATE_PLATFORM_FIELDS -}; - -typedef void (*uv__async_cb)(struct uv_loop_s* loop, - struct uv__async* w, - unsigned int nevents); - -struct uv__async { - uv__async_cb cb; - uv__io_t io_watcher; - int wfd; -}; - -#ifndef UV_PLATFORM_SEM_T -# define UV_PLATFORM_SEM_T sem_t -#endif - -#ifndef UV_PLATFORM_LOOP_FIELDS -# define UV_PLATFORM_LOOP_FIELDS /* empty */ -#endif - -#ifndef UV_PLATFORM_FS_EVENT_FIELDS -# define UV_PLATFORM_FS_EVENT_FIELDS /* empty */ -#endif - -#ifndef UV_STREAM_PRIVATE_PLATFORM_FIELDS -# define UV_STREAM_PRIVATE_PLATFORM_FIELDS /* empty */ -#endif - -/* Note: May be cast to struct iovec. See writev(2). */ -typedef struct uv_buf_t { - char* base; - size_t len; -} uv_buf_t; - -typedef int uv_file; -typedef int uv_os_sock_t; -typedef int uv_os_fd_t; - -#define UV_ONCE_INIT PTHREAD_ONCE_INIT - -typedef pthread_once_t uv_once_t; -typedef pthread_t uv_thread_t; -typedef pthread_mutex_t uv_mutex_t; -typedef pthread_rwlock_t uv_rwlock_t; -typedef UV_PLATFORM_SEM_T uv_sem_t; -typedef pthread_cond_t uv_cond_t; -typedef pthread_key_t uv_key_t; - -#if defined(__APPLE__) && defined(__MACH__) - -typedef struct { - unsigned int n; - unsigned int count; - uv_mutex_t mutex; - uv_sem_t turnstile1; - uv_sem_t turnstile2; -} uv_barrier_t; - -#else /* defined(__APPLE__) && defined(__MACH__) */ - -typedef pthread_barrier_t uv_barrier_t; - -#endif /* defined(__APPLE__) && defined(__MACH__) */ - -/* Platform-specific definitions for uv_spawn support. */ -typedef gid_t uv_gid_t; -typedef uid_t uv_uid_t; - -typedef struct dirent uv__dirent_t; - -#if defined(DT_UNKNOWN) -# define HAVE_DIRENT_TYPES -# if defined(DT_REG) -# define UV__DT_FILE DT_REG -# else -# define UV__DT_FILE -1 -# endif -# if defined(DT_DIR) -# define UV__DT_DIR DT_DIR -# else -# define UV__DT_DIR -2 -# endif -# if defined(DT_LNK) -# define UV__DT_LINK DT_LNK -# else -# define UV__DT_LINK -3 -# endif -# if defined(DT_FIFO) -# define UV__DT_FIFO DT_FIFO -# else -# define UV__DT_FIFO -4 -# endif -# if defined(DT_SOCK) -# define UV__DT_SOCKET DT_SOCK -# else -# define UV__DT_SOCKET -5 -# endif -# if defined(DT_CHR) -# define UV__DT_CHAR DT_CHR -# else -# define UV__DT_CHAR -6 -# endif -# if defined(DT_BLK) -# define UV__DT_BLOCK DT_BLK -# else -# define UV__DT_BLOCK -7 -# endif -#endif - -/* Platform-specific definitions for uv_dlopen support. */ -#define UV_DYNAMIC /* empty */ - -typedef struct { - void* handle; - char* errmsg; -} uv_lib_t; - -#define UV_LOOP_PRIVATE_FIELDS \ - unsigned long flags; \ - int backend_fd; \ - void* pending_queue[2]; \ - void* watcher_queue[2]; \ - uv__io_t** watchers; \ - unsigned int nwatchers; \ - unsigned int nfds; \ - void* wq[2]; \ - uv_mutex_t wq_mutex; \ - uv_async_t wq_async; \ - uv_rwlock_t cloexec_lock; \ - uv_handle_t* closing_handles; \ - void* process_handles[2]; \ - void* prepare_handles[2]; \ - void* check_handles[2]; \ - void* idle_handles[2]; \ - void* async_handles[2]; \ - struct uv__async async_watcher; \ - struct { \ - void* min; \ - unsigned int nelts; \ - } timer_heap; \ - uint64_t timer_counter; \ - uint64_t time; \ - int signal_pipefd[2]; \ - uv__io_t signal_io_watcher; \ - uv_signal_t child_watcher; \ - int emfile_fd; \ - UV_PLATFORM_LOOP_FIELDS \ - -#define UV_REQ_TYPE_PRIVATE /* empty */ - -#define UV_REQ_PRIVATE_FIELDS /* empty */ - -#define UV_PRIVATE_REQ_TYPES /* empty */ - -#define UV_WRITE_PRIVATE_FIELDS \ - void* queue[2]; \ - unsigned int write_index; \ - uv_buf_t* bufs; \ - unsigned int nbufs; \ - int error; \ - uv_buf_t bufsml[4]; \ - -#define UV_CONNECT_PRIVATE_FIELDS \ - void* queue[2]; \ - -#define UV_SHUTDOWN_PRIVATE_FIELDS /* empty */ - -#define UV_UDP_SEND_PRIVATE_FIELDS \ - void* queue[2]; \ - struct sockaddr_storage addr; \ - unsigned int nbufs; \ - uv_buf_t* bufs; \ - ssize_t status; \ - uv_udp_send_cb send_cb; \ - uv_buf_t bufsml[4]; \ - -#define UV_HANDLE_PRIVATE_FIELDS \ - uv_handle_t* next_closing; \ - unsigned int flags; \ - -#define UV_STREAM_PRIVATE_FIELDS \ - uv_connect_t *connect_req; \ - uv_shutdown_t *shutdown_req; \ - uv__io_t io_watcher; \ - void* write_queue[2]; \ - void* write_completed_queue[2]; \ - uv_connection_cb connection_cb; \ - int delayed_error; \ - int accepted_fd; \ - void* queued_fds; \ - UV_STREAM_PRIVATE_PLATFORM_FIELDS \ - -#define UV_TCP_PRIVATE_FIELDS /* empty */ - -#define UV_UDP_PRIVATE_FIELDS \ - uv_alloc_cb alloc_cb; \ - uv_udp_recv_cb recv_cb; \ - uv__io_t io_watcher; \ - void* write_queue[2]; \ - void* write_completed_queue[2]; \ - -#define UV_PIPE_PRIVATE_FIELDS \ - const char* pipe_fname; /* strdup'ed */ - -#define UV_POLL_PRIVATE_FIELDS \ - uv__io_t io_watcher; - -#define UV_PREPARE_PRIVATE_FIELDS \ - uv_prepare_cb prepare_cb; \ - void* queue[2]; \ - -#define UV_CHECK_PRIVATE_FIELDS \ - uv_check_cb check_cb; \ - void* queue[2]; \ - -#define UV_IDLE_PRIVATE_FIELDS \ - uv_idle_cb idle_cb; \ - void* queue[2]; \ - -#define UV_ASYNC_PRIVATE_FIELDS \ - uv_async_cb async_cb; \ - void* queue[2]; \ - int pending; \ - -#define UV_TIMER_PRIVATE_FIELDS \ - uv_timer_cb timer_cb; \ - void* heap_node[3]; \ - uint64_t timeout; \ - uint64_t repeat; \ - uint64_t start_id; - -#define UV_GETADDRINFO_PRIVATE_FIELDS \ - struct uv__work work_req; \ - uv_getaddrinfo_cb cb; \ - struct addrinfo* hints; \ - char* hostname; \ - char* service; \ - struct addrinfo* addrinfo; \ - int retcode; - -#define UV_GETNAMEINFO_PRIVATE_FIELDS \ - struct uv__work work_req; \ - uv_getnameinfo_cb getnameinfo_cb; \ - struct sockaddr_storage storage; \ - int flags; \ - char host[NI_MAXHOST]; \ - char service[NI_MAXSERV]; \ - int retcode; - -#define UV_PROCESS_PRIVATE_FIELDS \ - void* queue[2]; \ - int status; \ - -#define UV_FS_PRIVATE_FIELDS \ - const char *new_path; \ - uv_file file; \ - int flags; \ - mode_t mode; \ - unsigned int nbufs; \ - uv_buf_t* bufs; \ - off_t off; \ - uv_uid_t uid; \ - uv_gid_t gid; \ - double atime; \ - double mtime; \ - struct uv__work work_req; \ - uv_buf_t bufsml[4]; \ - -#define UV_WORK_PRIVATE_FIELDS \ - struct uv__work work_req; - -#define UV_TTY_PRIVATE_FIELDS \ - struct termios orig_termios; \ - int mode; - -#define UV_SIGNAL_PRIVATE_FIELDS \ - /* RB_ENTRY(uv_signal_s) tree_entry; */ \ - struct { \ - struct uv_signal_s* rbe_left; \ - struct uv_signal_s* rbe_right; \ - struct uv_signal_s* rbe_parent; \ - int rbe_color; \ - } tree_entry; \ - /* Use two counters here so we don have to fiddle with atomics. */ \ - unsigned int caught_signals; \ - unsigned int dispatched_signals; - -#define UV_FS_EVENT_PRIVATE_FIELDS \ - uv_fs_event_cb cb; \ - UV_PLATFORM_FS_EVENT_FIELDS \ - -#endif /* UV_UNIX_H */ diff --git a/julia-0.6.3/include/julia/uv-version.h b/julia-0.6.3/include/julia/uv-version.h deleted file mode 100644 index cb66618..0000000 --- a/julia-0.6.3/include/julia/uv-version.h +++ /dev/null @@ -1,43 +0,0 @@ -/* Copyright Joyent, Inc. and other Node contributors. All rights reserved. - * - * 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 NONINFRINGEMENT. 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. - */ - -#ifndef UV_VERSION_H -#define UV_VERSION_H - - /* - * Versions with the same major number are ABI stable. API is allowed to - * evolve between minor releases, but only in a backwards compatible way. - * Make sure you update the -soname directives in configure.ac - * and uv.gyp whenever you bump UV_VERSION_MAJOR or UV_VERSION_MINOR (but - * not UV_VERSION_PATCH.) - */ - -#define UV_VERSION_MAJOR 1 -#define UV_VERSION_MINOR 9 -#define UV_VERSION_PATCH 0 -#define UV_VERSION_IS_RELEASE 1 -#define UV_VERSION_SUFFIX "" - -#define UV_VERSION_HEX ((UV_VERSION_MAJOR << 16) | \ - (UV_VERSION_MINOR << 8) | \ - (UV_VERSION_PATCH)) - -#endif /* UV_VERSION_H */ diff --git a/julia-0.6.3/include/julia/uv.h b/julia-0.6.3/include/julia/uv.h deleted file mode 100644 index 3bda090..0000000 --- a/julia-0.6.3/include/julia/uv.h +++ /dev/null @@ -1,1546 +0,0 @@ -/* Copyright Joyent, Inc. and other Node contributors. All rights reserved. - * - * 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 NONINFRINGEMENT. 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. - */ - -/* See https://github.com/libuv/libuv#documentation for documentation. */ - -#ifndef UV_H -#define UV_H -#ifdef __cplusplus -extern "C" { -#endif - -#ifdef _WIN32 - /* Windows - set up dll import/export decorators. */ -# if defined(BUILDING_UV_SHARED) - /* Building shared library. */ -# define UV_EXTERN __declspec(dllexport) -# elif defined(USING_UV_SHARED) - /* Using shared library. */ -# define UV_EXTERN __declspec(dllimport) -# else - /* Building static library. */ -# define UV_EXTERN /* nothing */ -# endif -#elif __GNUC__ >= 4 -# define UV_EXTERN __attribute__((visibility("default"))) -# ifndef _GNU_SOURCE -# define _GNU_SOURCE -# endif -#else -# define UV_EXTERN /* nothing */ -#endif - -#include "uv-errno.h" -#include "uv-version.h" -#include -#include - -#if defined(_MSC_VER) && _MSC_VER < 1600 -# include "stdint-msvc2008.h" -#else -# include -#endif - -#if defined(_WIN32) -# include "uv-win.h" -#else -# include "uv-unix.h" -#endif - -/* Expand this list if necessary. */ -#define UV_ERRNO_MAP(XX) \ - XX(E2BIG, "argument list too long") \ - XX(EACCES, "permission denied") \ - XX(EADDRINUSE, "address already in use") \ - XX(EADDRNOTAVAIL, "address not available") \ - XX(EAFNOSUPPORT, "address family not supported") \ - XX(EAGAIN, "resource temporarily unavailable") \ - XX(EAI_ADDRFAMILY, "address family not supported") \ - XX(EAI_AGAIN, "temporary failure") \ - XX(EAI_BADFLAGS, "bad ai_flags value") \ - XX(EAI_BADHINTS, "invalid value for hints") \ - XX(EAI_CANCELED, "request canceled") \ - XX(EAI_FAIL, "permanent failure") \ - XX(EAI_FAMILY, "ai_family not supported") \ - XX(EAI_MEMORY, "out of memory") \ - XX(EAI_NODATA, "no address") \ - XX(EAI_NONAME, "unknown node or service") \ - XX(EAI_OVERFLOW, "argument buffer overflow") \ - XX(EAI_PROTOCOL, "resolved protocol is unknown") \ - XX(EAI_SERVICE, "service not available for socket type") \ - XX(EAI_SOCKTYPE, "socket type not supported") \ - XX(EALREADY, "connection already in progress") \ - XX(EBADF, "bad file descriptor") \ - XX(EBUSY, "resource busy or locked") \ - XX(ECANCELED, "operation canceled") \ - XX(ECHARSET, "invalid Unicode character") \ - XX(ECONNABORTED, "software caused connection abort") \ - XX(ECONNREFUSED, "connection refused") \ - XX(ECONNRESET, "connection reset by peer") \ - XX(EDESTADDRREQ, "destination address required") \ - XX(EEXIST, "file already exists") \ - XX(EFAULT, "bad address in system call argument") \ - XX(EFBIG, "file too large") \ - XX(EHOSTUNREACH, "host is unreachable") \ - XX(EINTR, "interrupted system call") \ - XX(EINVAL, "invalid argument") \ - XX(EIO, "i/o error") \ - XX(EISCONN, "socket is already connected") \ - XX(EISDIR, "illegal operation on a directory") \ - XX(ELOOP, "too many symbolic links encountered") \ - XX(EMFILE, "too many open files") \ - XX(EMSGSIZE, "message too long") \ - XX(ENAMETOOLONG, "name too long") \ - XX(ENETDOWN, "network is down") \ - XX(ENETUNREACH, "network is unreachable") \ - XX(ENFILE, "file table overflow") \ - XX(ENOBUFS, "no buffer space available") \ - XX(ENODEV, "no such device") \ - XX(ENOENT, "no such file or directory") \ - XX(ENOMEM, "not enough memory") \ - XX(ENONET, "machine is not on the network") \ - XX(ENOPROTOOPT, "protocol not available") \ - XX(ENOSPC, "no space left on device") \ - XX(ENOSYS, "function not implemented") \ - XX(ENOTCONN, "socket is not connected") \ - XX(ENOTDIR, "not a directory") \ - XX(ENOTEMPTY, "directory not empty") \ - XX(ENOTSOCK, "socket operation on non-socket") \ - XX(ENOTSUP, "operation not supported on socket") \ - XX(EPERM, "operation not permitted") \ - XX(EPIPE, "broken pipe") \ - XX(EPROTO, "protocol error") \ - XX(EPROTONOSUPPORT, "protocol not supported") \ - XX(EPROTOTYPE, "protocol wrong type for socket") \ - XX(ERANGE, "result too large") \ - XX(EROFS, "read-only file system") \ - XX(ESHUTDOWN, "cannot send after transport endpoint shutdown") \ - XX(ESPIPE, "invalid seek") \ - XX(ESRCH, "no such process") \ - XX(ETIMEDOUT, "connection timed out") \ - XX(ETXTBSY, "text file is busy") \ - XX(EXDEV, "cross-device link not permitted") \ - XX(UNKNOWN, "unknown error") \ - XX(EOF, "end of file") \ - XX(ENXIO, "no such device or address") \ - XX(EMLINK, "too many links") \ - XX(EHOSTDOWN, "host is down") \ - -#define UV_HANDLE_TYPE_MAP(XX) \ - XX(ASYNC, async) \ - XX(CHECK, check) \ - XX(FS_EVENT, fs_event) \ - XX(FS_POLL, fs_poll) \ - XX(HANDLE, handle) \ - XX(IDLE, idle) \ - XX(NAMED_PIPE, pipe) \ - XX(POLL, poll) \ - XX(PREPARE, prepare) \ - XX(PROCESS, process) \ - XX(STREAM, stream) \ - XX(TCP, tcp) \ - XX(TIMER, timer) \ - XX(TTY, tty) \ - XX(UDP, udp) \ - XX(SIGNAL, signal) \ - -#define UV_REQ_TYPE_MAP(XX) \ - XX(REQ, req) \ - XX(CONNECT, connect) \ - XX(WRITE, write) \ - XX(SHUTDOWN, shutdown) \ - XX(UDP_SEND, udp_send) \ - XX(FS, fs) \ - XX(WORK, work) \ - XX(GETADDRINFO, getaddrinfo) \ - XX(GETNAMEINFO, getnameinfo) \ - -typedef enum { -#define XX(code, _) UV_ ## code = UV__ ## code, - UV_ERRNO_MAP(XX) -#undef XX - UV_ERRNO_MAX = UV__EOF - 1 -} uv_errno_t; - -typedef enum { - UV_UNKNOWN_HANDLE = 0, -#define XX(uc, lc) UV_##uc, - UV_HANDLE_TYPE_MAP(XX) -#undef XX - UV_FILE, - UV_HANDLE_TYPE_MAX, - UV_RAW_FD, /* fd for both unix and windows */ - UV_RAW_HANDLE /* HANDLE on windows, same as UV_RAW_FD on unix */ -} uv_handle_type; - -typedef enum { - UV_UNKNOWN_REQ = 0, -#define XX(uc, lc) UV_##uc, - UV_REQ_TYPE_MAP(XX) -#undef XX - UV_REQ_TYPE_PRIVATE - UV_REQ_TYPE_MAX -} uv_req_type; - - -/* Handle types. */ -typedef struct uv_loop_s uv_loop_t; -typedef struct uv_handle_s uv_handle_t; -typedef struct uv_stream_s uv_stream_t; -typedef struct uv_tcp_s uv_tcp_t; -typedef struct uv_udp_s uv_udp_t; -typedef struct uv_pipe_s uv_pipe_t; -typedef struct uv_tty_s uv_tty_t; -typedef struct uv_poll_s uv_poll_t; -typedef struct uv_timer_s uv_timer_t; -typedef struct uv_prepare_s uv_prepare_t; -typedef struct uv_check_s uv_check_t; -typedef struct uv_idle_s uv_idle_t; -typedef struct uv_async_s uv_async_t; -typedef struct uv_process_s uv_process_t; -typedef struct uv_fs_event_s uv_fs_event_t; -typedef struct uv_fs_poll_s uv_fs_poll_t; -typedef struct uv_signal_s uv_signal_t; - -/* Request types. */ -typedef struct uv_req_s uv_req_t; -typedef struct uv_getaddrinfo_s uv_getaddrinfo_t; -typedef struct uv_getnameinfo_s uv_getnameinfo_t; -typedef struct uv_shutdown_s uv_shutdown_t; -typedef struct uv_write_s uv_write_t; -typedef struct uv_connect_s uv_connect_t; -typedef struct uv_udp_send_s uv_udp_send_t; -typedef struct uv_fs_s uv_fs_t; -typedef struct uv_work_s uv_work_t; - -/* None of the above. */ -typedef struct uv_cpu_info_s uv_cpu_info_t; -typedef struct uv_interface_address_s uv_interface_address_t; -typedef struct uv_dirent_s uv_dirent_t; -typedef struct uv_passwd_s uv_passwd_t; - -typedef enum { - UV_LOOP_BLOCK_SIGNAL -} uv_loop_option; - -typedef enum { - UV_RUN_DEFAULT = 0, - UV_RUN_ONCE, - UV_RUN_NOWAIT -} uv_run_mode; - - -UV_EXTERN unsigned int uv_version(void); -UV_EXTERN const char* uv_version_string(void); - -typedef void* (*uv_malloc_func)(size_t size); -typedef void* (*uv_realloc_func)(void* ptr, size_t size); -typedef void* (*uv_calloc_func)(size_t count, size_t size); -typedef void (*uv_free_func)(void* ptr); - -UV_EXTERN int uv_replace_allocator(uv_malloc_func malloc_func, - uv_realloc_func realloc_func, - uv_calloc_func calloc_func, - uv_free_func free_func); - -UV_EXTERN uv_loop_t* uv_default_loop(void); -UV_EXTERN int uv_loop_init(uv_loop_t* loop); -UV_EXTERN int uv_loop_close(uv_loop_t* loop); -/* - * NOTE: - * This function is DEPRECATED (to be removed after 0.12), users should - * allocate the loop manually and use uv_loop_init instead. - */ -UV_EXTERN uv_loop_t* uv_loop_new(void); -/* - * NOTE: - * This function is DEPRECATED (to be removed after 0.12). Users should use - * uv_loop_close and free the memory manually instead. - */ -UV_EXTERN void uv_loop_delete(uv_loop_t*); -UV_EXTERN size_t uv_loop_size(void); -UV_EXTERN int uv_loop_alive(const uv_loop_t* loop); -UV_EXTERN int uv_loop_configure(uv_loop_t* loop, uv_loop_option option, ...); - -UV_EXTERN int uv_run(uv_loop_t*, uv_run_mode mode); -UV_EXTERN void uv_stop(uv_loop_t*); - -UV_EXTERN void uv_ref(uv_handle_t*); -UV_EXTERN void uv_unref(uv_handle_t*); -UV_EXTERN int uv_has_ref(const uv_handle_t*); - -UV_EXTERN void uv_update_time(uv_loop_t*); -UV_EXTERN uint64_t uv_now(const uv_loop_t*); - -UV_EXTERN int uv_backend_fd(const uv_loop_t*); -UV_EXTERN int uv_backend_timeout(const uv_loop_t*); - -typedef void (*uv_alloc_cb)(uv_handle_t* handle, - size_t suggested_size, - uv_buf_t* buf); -typedef void (*uv_read_cb)(uv_stream_t* stream, - ssize_t nread, - const uv_buf_t* buf); -typedef void (*uv_write_cb)(uv_write_t* req, int status); -typedef void (*uv_connect_cb)(uv_connect_t* req, int status); -typedef void (*uv_shutdown_cb)(uv_shutdown_t* req, int status); -typedef void (*uv_connection_cb)(uv_stream_t* server, int status); -typedef void (*uv_close_cb)(uv_handle_t* handle); -typedef void (*uv_poll_cb)(uv_poll_t* handle, int status, int events); -typedef void (*uv_timer_cb)(uv_timer_t* handle); -typedef void (*uv_async_cb)(uv_async_t* handle); -typedef void (*uv_prepare_cb)(uv_prepare_t* handle); -typedef void (*uv_check_cb)(uv_check_t* handle); -typedef void (*uv_idle_cb)(uv_idle_t* handle); -typedef void (*uv_exit_cb)(uv_process_t*, int64_t exit_status, int term_signal); -typedef void (*uv_walk_cb)(uv_handle_t* handle, void* arg); -typedef void (*uv_fs_cb)(uv_fs_t* req); -typedef void (*uv_work_cb)(uv_work_t* req); -typedef void (*uv_after_work_cb)(uv_work_t* req, int status); -typedef void (*uv_getaddrinfo_cb)(uv_getaddrinfo_t* req, - int status, - struct addrinfo* res); -typedef void (*uv_getnameinfo_cb)(uv_getnameinfo_t* req, - int status, - const char* hostname, - const char* service); - -typedef struct { - long tv_sec; - long tv_nsec; -} uv_timespec_t; - - -typedef struct { - uint64_t st_dev; - uint64_t st_mode; - uint64_t st_nlink; - uint64_t st_uid; - uint64_t st_gid; - uint64_t st_rdev; - uint64_t st_ino; - uint64_t st_size; - uint64_t st_blksize; - uint64_t st_blocks; - uint64_t st_flags; - uint64_t st_gen; - uv_timespec_t st_atim; - uv_timespec_t st_mtim; - uv_timespec_t st_ctim; - uv_timespec_t st_birthtim; -} uv_stat_t; - - -typedef void (*uv_fs_event_cb)(uv_fs_event_t* handle, - const char* filename, - int events, - int status); - -typedef void (*uv_fs_poll_cb)(uv_fs_poll_t* handle, - int status, - const uv_stat_t* prev, - const uv_stat_t* curr); - -typedef void (*uv_signal_cb)(uv_signal_t* handle, int signum); - - -typedef enum { - UV_LEAVE_GROUP = 0, - UV_JOIN_GROUP -} uv_membership; - - -UV_EXTERN const char* uv_strerror(int err); -UV_EXTERN const char* uv_err_name(int err); - - -#define UV_REQ_FIELDS \ - /* public */ \ - void* data; \ - /* read-only */ \ - uv_req_type type; \ - /* private */ \ - void* active_queue[2]; \ - void* reserved[4]; \ - UV_REQ_PRIVATE_FIELDS \ - -/* Abstract base class of all requests. */ -struct uv_req_s { - UV_REQ_FIELDS -}; - - -/* Platform-specific request types. */ -UV_PRIVATE_REQ_TYPES - - -UV_EXTERN int uv_shutdown(uv_shutdown_t* req, - uv_stream_t* handle, - uv_shutdown_cb cb); - -struct uv_shutdown_s { - UV_REQ_FIELDS - uv_stream_t* handle; - uv_shutdown_cb cb; - UV_SHUTDOWN_PRIVATE_FIELDS -}; - - -#define UV_HANDLE_FIELDS \ - /* public */ \ - void* data; \ - /* read-only */ \ - uv_loop_t* loop; \ - uv_handle_type type; \ - /* private */ \ - uv_close_cb close_cb; \ - void* handle_queue[2]; \ - union { \ - int fd; \ - void* reserved[4]; \ - } u; \ - UV_HANDLE_PRIVATE_FIELDS \ - -/* The abstract base class of all handles. */ -struct uv_handle_s { - UV_HANDLE_FIELDS -}; - -UV_EXTERN size_t uv_handle_size(uv_handle_type type); -UV_EXTERN size_t uv_req_size(uv_req_type type); - -UV_EXTERN int uv_is_active(const uv_handle_t* handle); - -UV_EXTERN void uv_walk(uv_loop_t* loop, uv_walk_cb walk_cb, void* arg); - -/* Helpers for ad hoc debugging, no API/ABI stability guaranteed. */ -UV_EXTERN void uv_print_all_handles(uv_loop_t* loop, FILE* stream); -UV_EXTERN void uv_print_active_handles(uv_loop_t* loop, FILE* stream); - -UV_EXTERN void uv_close(uv_handle_t* handle, uv_close_cb close_cb); - -UV_EXTERN int uv_send_buffer_size(uv_handle_t* handle, int* value); -UV_EXTERN int uv_recv_buffer_size(uv_handle_t* handle, int* value); - -UV_EXTERN int uv_fileno(const uv_handle_t* handle, uv_os_fd_t* fd); - -UV_EXTERN uv_buf_t uv_buf_init(char* base, unsigned int len); - - -#define UV_STREAM_FIELDS \ - /* number of bytes queued for writing */ \ - size_t write_queue_size; \ - uv_alloc_cb alloc_cb; \ - uv_read_cb read_cb; \ - /* private */ \ - UV_STREAM_PRIVATE_FIELDS - -/* - * uv_stream_t is a subclass of uv_handle_t. - * - * uv_stream is an abstract class. - * - * uv_stream_t is the parent class of uv_tcp_t, uv_pipe_t and uv_tty_t. - */ -struct uv_stream_s { - UV_HANDLE_FIELDS - UV_STREAM_FIELDS -}; - -UV_EXTERN int uv_listen(uv_stream_t* stream, int backlog, uv_connection_cb cb); -UV_EXTERN int uv_accept(uv_stream_t* server, uv_stream_t* client); - -UV_EXTERN int uv_read_start(uv_stream_t*, - uv_alloc_cb alloc_cb, - uv_read_cb read_cb); -UV_EXTERN int uv_read_stop(uv_stream_t*); - -UV_EXTERN int uv_write(uv_write_t* req, - uv_stream_t* handle, - const uv_buf_t bufs[], - unsigned int nbufs, - uv_write_cb cb); -UV_EXTERN int uv_write2(uv_write_t* req, - uv_stream_t* handle, - const uv_buf_t bufs[], - unsigned int nbufs, - uv_stream_t* send_handle, - uv_write_cb cb); -UV_EXTERN int uv_try_write(uv_stream_t* handle, - const uv_buf_t bufs[], - unsigned int nbufs); - -/* uv_write_t is a subclass of uv_req_t. */ -struct uv_write_s { - UV_REQ_FIELDS - uv_write_cb cb; - uv_stream_t* send_handle; - uv_stream_t* handle; - UV_WRITE_PRIVATE_FIELDS -}; - - -UV_EXTERN int uv_is_readable(const uv_stream_t* handle); -UV_EXTERN int uv_is_writable(const uv_stream_t* handle); - -UV_EXTERN int uv_stream_set_blocking(uv_stream_t* handle, int blocking); - -UV_EXTERN int uv_is_closing(const uv_handle_t* handle); - - -/* - * uv_tcp_t is a subclass of uv_stream_t. - * - * Represents a TCP stream or TCP server. - */ -struct uv_tcp_s { - UV_HANDLE_FIELDS - UV_STREAM_FIELDS - UV_TCP_PRIVATE_FIELDS -}; - -UV_EXTERN int uv_tcp_init(uv_loop_t*, uv_tcp_t* handle); -UV_EXTERN int uv_tcp_init_ex(uv_loop_t*, uv_tcp_t* handle, unsigned int flags); -UV_EXTERN int uv_tcp_open(uv_tcp_t* handle, uv_os_sock_t sock); -UV_EXTERN int uv_tcp_nodelay(uv_tcp_t* handle, int enable); -UV_EXTERN int uv_tcp_keepalive(uv_tcp_t* handle, - int enable, - unsigned int delay); -UV_EXTERN int uv_tcp_simultaneous_accepts(uv_tcp_t* handle, int enable); - -enum uv_tcp_flags { - /* Used with uv_tcp_bind, when an IPv6 address is used. */ - UV_TCP_IPV6ONLY = 1 -}; - -UV_EXTERN int uv_tcp_bind(uv_tcp_t* handle, - const struct sockaddr* addr, - unsigned int flags); -UV_EXTERN int uv_tcp_getsockname(const uv_tcp_t* handle, - struct sockaddr* name, - int* namelen); -UV_EXTERN int uv_tcp_getpeername(const uv_tcp_t* handle, - struct sockaddr* name, - int* namelen); -UV_EXTERN int uv_tcp_connect(uv_connect_t* req, - uv_tcp_t* handle, - const struct sockaddr* addr, - uv_connect_cb cb); - -/* uv_connect_t is a subclass of uv_req_t. */ -struct uv_connect_s { - UV_REQ_FIELDS - uv_connect_cb cb; - uv_stream_t* handle; - UV_CONNECT_PRIVATE_FIELDS -}; - - -/* - * UDP support. - */ - -enum uv_udp_flags { - /* Disables dual stack mode. */ - UV_UDP_IPV6ONLY = 1, - /* - * Indicates message was truncated because read buffer was too small. The - * remainder was discarded by the OS. Used in uv_udp_recv_cb. - */ - UV_UDP_PARTIAL = 2, - /* - * Indicates if SO_REUSEADDR will be set when binding the handle. - * This sets the SO_REUSEPORT socket flag on the BSDs and OS X. On other - * Unix platforms, it sets the SO_REUSEADDR flag. What that means is that - * multiple threads or processes can bind to the same address without error - * (provided they all set the flag) but only the last one to bind will receive - * any traffic, in effect "stealing" the port from the previous listener. - */ - UV_UDP_REUSEADDR = 4 -}; - -typedef void (*uv_udp_send_cb)(uv_udp_send_t* req, int status); -typedef void (*uv_udp_recv_cb)(uv_udp_t* handle, - ssize_t nread, - const uv_buf_t* buf, - const struct sockaddr* addr, - unsigned flags); - -/* uv_udp_t is a subclass of uv_handle_t. */ -struct uv_udp_s { - UV_HANDLE_FIELDS - /* read-only */ - /* - * Number of bytes queued for sending. This field strictly shows how much - * information is currently queued. - */ - size_t send_queue_size; - /* - * Number of send requests currently in the queue awaiting to be processed. - */ - size_t send_queue_count; - UV_UDP_PRIVATE_FIELDS -}; - -/* uv_udp_send_t is a subclass of uv_req_t. */ -struct uv_udp_send_s { - UV_REQ_FIELDS - uv_udp_t* handle; - uv_udp_send_cb cb; - UV_UDP_SEND_PRIVATE_FIELDS -}; - -UV_EXTERN int uv_udp_init(uv_loop_t*, uv_udp_t* handle); -UV_EXTERN int uv_udp_init_ex(uv_loop_t*, uv_udp_t* handle, unsigned int flags); -UV_EXTERN int uv_udp_open(uv_udp_t* handle, uv_os_sock_t sock); -UV_EXTERN int uv_udp_bind(uv_udp_t* handle, - const struct sockaddr* addr, - unsigned int flags); - -UV_EXTERN int uv_udp_getsockname(const uv_udp_t* handle, - struct sockaddr* name, - int* namelen); -UV_EXTERN int uv_udp_set_membership(uv_udp_t* handle, - const char* multicast_addr, - const char* interface_addr, - uv_membership membership); -UV_EXTERN int uv_udp_set_multicast_loop(uv_udp_t* handle, int on); -UV_EXTERN int uv_udp_set_multicast_ttl(uv_udp_t* handle, int ttl); -UV_EXTERN int uv_udp_set_multicast_interface(uv_udp_t* handle, - const char* interface_addr); -UV_EXTERN int uv_udp_set_broadcast(uv_udp_t* handle, int on); -UV_EXTERN int uv_udp_set_ttl(uv_udp_t* handle, int ttl); -UV_EXTERN int uv_udp_send(uv_udp_send_t* req, - uv_udp_t* handle, - const uv_buf_t bufs[], - unsigned int nbufs, - const struct sockaddr* addr, - uv_udp_send_cb send_cb); -UV_EXTERN int uv_udp_try_send(uv_udp_t* handle, - const uv_buf_t bufs[], - unsigned int nbufs, - const struct sockaddr* addr); -UV_EXTERN int uv_udp_recv_start(uv_udp_t* handle, - uv_alloc_cb alloc_cb, - uv_udp_recv_cb recv_cb); -UV_EXTERN int uv_udp_recv_stop(uv_udp_t* handle); - - -/* - * uv_tty_t is a subclass of uv_stream_t. - * - * Representing a stream for the console. - */ -struct uv_tty_s { - UV_HANDLE_FIELDS - UV_STREAM_FIELDS - UV_TTY_PRIVATE_FIELDS -}; - -typedef enum { - /* Initial/normal terminal mode */ - UV_TTY_MODE_NORMAL, - /* Raw input mode (On Windows, ENABLE_WINDOW_INPUT is also enabled) */ - UV_TTY_MODE_RAW, - /* Binary-safe I/O mode for IPC (Unix-only) */ - UV_TTY_MODE_IO -} uv_tty_mode_t; - -UV_EXTERN int uv_tty_init(uv_loop_t*, uv_tty_t*, uv_file fd, int readable); -UV_EXTERN int uv_tty_set_mode(uv_tty_t*, uv_tty_mode_t mode); -UV_EXTERN int uv_tty_reset_mode(void); -UV_EXTERN int uv_tty_get_winsize(uv_tty_t*, int* width, int* height); - -#ifdef __cplusplus -extern "C++" { - -inline int uv_tty_set_mode(uv_tty_t* handle, int mode) { - return uv_tty_set_mode(handle, static_cast(mode)); -} - -} -#endif - -UV_EXTERN uv_handle_type uv_guess_handle(uv_file file); - -/* - * uv_pipe_t is a subclass of uv_stream_t. - * - * Representing a pipe stream or pipe server. On Windows this is a Named - * Pipe. On Unix this is a Unix domain socket. - * - * A single uv_pipe_t always represents one end of a pipe. You can use - * uv_pipe_link to create a pair of connected pipe ends. - */ -struct uv_pipe_s { - UV_HANDLE_FIELDS - UV_STREAM_FIELDS - UV_PIPE_PRIVATE_FIELDS -}; - -enum uv_pipe_flags { - UV_PIPE_IPC = 0x01, - UV_PIPE_SPAWN_SAFE = 0x02, - UV_PIPE_READABLE = 0x04, - UV_PIPE_WRITABLE = 0x08 -}; -/* - * Initialize a pipe. The last argument is a boolean to indicate if - * this pipe will be used for handle passing between processes. - */ -UV_EXTERN int uv_pipe_init(uv_loop_t*, uv_pipe_t* handle, int flags); - -/* - * Creates a pipe and assigns the two pipe ends to the given uv_pipe_t's - */ -UV_EXTERN int uv_pipe_link(uv_pipe_t *read, uv_pipe_t *write); - -/* - * Attempt to synchronously close the given pipe. This will only work if the pipe is - * inactive (i.e. not reading, writing listening, connecting, etc. Otherwise this function - * will abort() - */ -UV_EXTERN void uv_pipe_close_sync(uv_pipe_t *pipe); - -/* - * Opens an existing file descriptor or HANDLE as a pipe. - */ -UV_EXTERN int uv_pipe_open(uv_pipe_t*, uv_file file); -UV_EXTERN int uv_pipe_bind(uv_pipe_t* handle, const char* name); -UV_EXTERN void uv_pipe_connect(uv_connect_t* req, - uv_pipe_t* handle, - const char* name, - uv_connect_cb cb); -UV_EXTERN int uv_pipe_getsockname(const uv_pipe_t* handle, - char* buffer, - size_t* size); -UV_EXTERN int uv_pipe_getpeername(const uv_pipe_t* handle, - char* buffer, - size_t* size); -UV_EXTERN void uv_pipe_pending_instances(uv_pipe_t* handle, int count); -UV_EXTERN int uv_pipe_pending_count(uv_pipe_t* handle); -UV_EXTERN uv_handle_type uv_pipe_pending_type(uv_pipe_t* handle); - - -struct uv_poll_s { - UV_HANDLE_FIELDS - uv_poll_cb poll_cb; - UV_POLL_PRIVATE_FIELDS -}; - -enum uv_poll_event { - UV_READABLE = 1, - UV_WRITABLE = 2, - UV_DISCONNECT = 4 -}; - -UV_EXTERN int uv_poll_init(uv_loop_t* loop, uv_poll_t* handle, int fd); -UV_EXTERN int uv_poll_init_socket(uv_loop_t* loop, - uv_poll_t* handle, - uv_os_sock_t socket); -UV_EXTERN int uv_poll_start(uv_poll_t* handle, int events, uv_poll_cb cb); -UV_EXTERN int uv_poll_stop(uv_poll_t* handle); - - -struct uv_prepare_s { - UV_HANDLE_FIELDS - UV_PREPARE_PRIVATE_FIELDS -}; - -UV_EXTERN int uv_prepare_init(uv_loop_t*, uv_prepare_t* prepare); -UV_EXTERN int uv_prepare_start(uv_prepare_t* prepare, uv_prepare_cb cb); -UV_EXTERN int uv_prepare_stop(uv_prepare_t* prepare); - - -struct uv_check_s { - UV_HANDLE_FIELDS - UV_CHECK_PRIVATE_FIELDS -}; - -UV_EXTERN int uv_check_init(uv_loop_t*, uv_check_t* check); -UV_EXTERN int uv_check_start(uv_check_t* check, uv_check_cb cb); -UV_EXTERN int uv_check_stop(uv_check_t* check); - - -struct uv_idle_s { - UV_HANDLE_FIELDS - UV_IDLE_PRIVATE_FIELDS -}; - -UV_EXTERN int uv_idle_init(uv_loop_t*, uv_idle_t* idle); -UV_EXTERN int uv_idle_start(uv_idle_t* idle, uv_idle_cb cb); -UV_EXTERN int uv_idle_stop(uv_idle_t* idle); - - -struct uv_async_s { - UV_HANDLE_FIELDS - UV_ASYNC_PRIVATE_FIELDS -}; - -UV_EXTERN int uv_async_init(uv_loop_t*, - uv_async_t* async, - uv_async_cb async_cb); -UV_EXTERN int uv_async_send(uv_async_t* async); - - -/* - * uv_timer_t is a subclass of uv_handle_t. - * - * Used to get woken up at a specified time in the future. - */ -struct uv_timer_s { - UV_HANDLE_FIELDS - UV_TIMER_PRIVATE_FIELDS -}; - -UV_EXTERN int uv_timer_init(uv_loop_t*, uv_timer_t* handle); -UV_EXTERN int uv_timer_start(uv_timer_t* handle, - uv_timer_cb cb, - uint64_t timeout, - uint64_t repeat); -UV_EXTERN int uv_timer_stop(uv_timer_t* handle); -UV_EXTERN int uv_timer_again(uv_timer_t* handle); -UV_EXTERN void uv_timer_set_repeat(uv_timer_t* handle, uint64_t repeat); -UV_EXTERN uint64_t uv_timer_get_repeat(const uv_timer_t* handle); - - -/* - * uv_getaddrinfo_t is a subclass of uv_req_t. - * - * Request object for uv_getaddrinfo. - */ -struct uv_getaddrinfo_s { - UV_REQ_FIELDS - /* read-only */ - uv_loop_t* loop; - /* struct addrinfo* addrinfo is marked as private, but it really isn't. */ - UV_GETADDRINFO_PRIVATE_FIELDS -}; - - -UV_EXTERN int uv_getaddrinfo(uv_loop_t* loop, - uv_getaddrinfo_t* req, - uv_getaddrinfo_cb getaddrinfo_cb, - const char* node, - const char* service, - const struct addrinfo* hints); -UV_EXTERN void uv_freeaddrinfo(struct addrinfo* ai); - -/* -* uv_getnameinfo_t is a subclass of uv_req_t. -* -* Request object for uv_getnameinfo. -*/ -struct uv_getnameinfo_s { - UV_REQ_FIELDS - /* read-only */ - uv_loop_t* loop; - /* host and service are marked as private, but they really aren't. */ - UV_GETNAMEINFO_PRIVATE_FIELDS -}; - -UV_EXTERN int uv_getnameinfo(uv_loop_t* loop, - uv_getnameinfo_t* req, - uv_getnameinfo_cb getnameinfo_cb, - const struct sockaddr* addr, - int flags); - -typedef struct uv_stdio_container_s { - uv_handle_type type; - union { - uv_stream_t *stream; - uv_file fd; - uv_os_fd_t os_handle; - } data; -} uv_stdio_container_t; - -/* uv_spawn() options */ -typedef struct uv_process_options_s { - uv_exit_cb exit_cb; /* Called after the process exits. */ - const char* file; /* Path to program to execute. */ - /* - * Command line arguments. args[0] should be the path to the program. On - * Windows this uses CreateProcess which concatenates the arguments into a - * string this can cause some strange errors. See the note at - * windows_verbatim_arguments. - */ - char** args; - /* - * This will be set as the environ variable in the subprocess. If this is - * NULL then the parents environ will be used. - */ - char** env; - /* - * If non-null this represents a directory the subprocess should execute - * in. Stands for current working directory. - */ - const char* cwd; - /* - * Various flags that control how uv_spawn() behaves. See the definition of - * `enum uv_process_flags` below. - */ - unsigned int flags; - /* - * The `stdio` field points to an array of uv_stdio_container_t structs that - * describe the file descriptors that will be made available to the child - * process. The convention is that stdio[0] points to stdin, fd 1 is used for - * stdout, and fd 2 is stderr. - * - * Note that on windows file descriptors greater than 2 are available to the - * child process only if the child processes uses the MSVCRT runtime. - */ - int stdio_count; - uv_stdio_container_t* stdio; - /* - * Libuv can change the child process' user/group id. This happens only when - * the appropriate bits are set in the flags fields. This is not supported on - * windows; uv_spawn() will fail and set the error to UV_ENOTSUP. - */ - uv_uid_t uid; - uv_gid_t gid; -} uv_process_options_t; - -/* - * These are the flags that can be used for the uv_process_options.flags field. - */ -enum uv_process_flags { - /* - * Set the child process' user id. The user id is supplied in the `uid` field - * of the options struct. This does not work on windows; setting this flag - * will cause uv_spawn() to fail. - */ - UV_PROCESS_SETUID = (1 << 0), - /* - * Set the child process' group id. The user id is supplied in the `gid` - * field of the options struct. This does not work on windows; setting this - * flag will cause uv_spawn() to fail. - */ - UV_PROCESS_SETGID = (1 << 1), - /* - * Do not wrap any arguments in quotes, or perform any other escaping, when - * converting the argument list into a command line string. This option is - * only meaningful on Windows systems. On Unix it is silently ignored. - */ - UV_PROCESS_WINDOWS_VERBATIM_ARGUMENTS = (1 << 2), - /* - * Spawn the child process in a detached state - this will make it a process - * group leader, and will effectively enable the child to keep running after - * the parent exits. Note that the child process will still keep the - * parent's event loop alive unless the parent process calls uv_unref() on - * the child's process handle. - */ - UV_PROCESS_DETACHED = (1 << 3), - /* - * Hide the subprocess console window that would normally be created. This - * option is only meaningful on Windows systems. On Unix it is silently - * ignored. - */ - UV_PROCESS_WINDOWS_HIDE = (1 << 4), - /* - * Reset SIGPIPE to the default handler. Useful for parent processes that ignore - * SIGPIPE, but don't want to make the same assumption for child processes - */ - UV_PROCESS_RESET_SIGPIPE = (1 << 5) -}; - -/* - * uv_process_t is a subclass of uv_handle_t. - */ -struct uv_process_s { - UV_HANDLE_FIELDS - uv_exit_cb exit_cb; - int pid; - UV_PROCESS_PRIVATE_FIELDS -}; - -UV_EXTERN int uv_spawn(uv_loop_t* loop, - uv_process_t* handle, - const uv_process_options_t* options); -UV_EXTERN int uv_process_kill(uv_process_t*, int signum); -UV_EXTERN int uv_kill(int pid, int signum); - - -/* - * uv_work_t is a subclass of uv_req_t. - */ -struct uv_work_s { - UV_REQ_FIELDS - uv_loop_t* loop; - uv_work_cb work_cb; - uv_after_work_cb after_work_cb; - UV_WORK_PRIVATE_FIELDS -}; - -UV_EXTERN int uv_queue_work(uv_loop_t* loop, - uv_work_t* req, - uv_work_cb work_cb, - uv_after_work_cb after_work_cb); - -UV_EXTERN int uv_cancel(uv_req_t* req); - - -struct uv_cpu_info_s { - char* model; - int speed; - struct uv_cpu_times_s { - uint64_t user; - uint64_t nice; - uint64_t sys; - uint64_t idle; - uint64_t irq; - } cpu_times; -}; - -struct uv_interface_address_s { - char* name; - char phys_addr[6]; - int is_internal; - union { - struct sockaddr_in address4; - struct sockaddr_in6 address6; - } address; - union { - struct sockaddr_in netmask4; - struct sockaddr_in6 netmask6; - } netmask; -}; - -struct uv_passwd_s { - char* username; - long uid; - long gid; - char* shell; - char* homedir; -}; - -typedef enum { - UV_DIRENT_UNKNOWN, - UV_DIRENT_FILE, - UV_DIRENT_DIR, - UV_DIRENT_LINK, - UV_DIRENT_FIFO, - UV_DIRENT_SOCKET, - UV_DIRENT_CHAR, - UV_DIRENT_BLOCK -} uv_dirent_type_t; - -struct uv_dirent_s { - const char* name; - uv_dirent_type_t type; -}; - -UV_EXTERN char** uv_setup_args(int argc, char** argv); -UV_EXTERN int uv_get_process_title(char* buffer, size_t size); -UV_EXTERN int uv_set_process_title(const char* title); -UV_EXTERN int uv_resident_set_memory(size_t* rss); -UV_EXTERN int uv_uptime(double* uptime); - -typedef struct { - long tv_sec; - long tv_usec; -} uv_timeval_t; - -typedef struct { - uv_timeval_t ru_utime; /* user CPU time used */ - uv_timeval_t ru_stime; /* system CPU time used */ - uint64_t ru_maxrss; /* maximum resident set size */ - uint64_t ru_ixrss; /* integral shared memory size */ - uint64_t ru_idrss; /* integral unshared data size */ - uint64_t ru_isrss; /* integral unshared stack size */ - uint64_t ru_minflt; /* page reclaims (soft page faults) */ - uint64_t ru_majflt; /* page faults (hard page faults) */ - uint64_t ru_nswap; /* swaps */ - uint64_t ru_inblock; /* block input operations */ - uint64_t ru_oublock; /* block output operations */ - uint64_t ru_msgsnd; /* IPC messages sent */ - uint64_t ru_msgrcv; /* IPC messages received */ - uint64_t ru_nsignals; /* signals received */ - uint64_t ru_nvcsw; /* voluntary context switches */ - uint64_t ru_nivcsw; /* involuntary context switches */ -} uv_rusage_t; - -UV_EXTERN int uv_getrusage(uv_rusage_t* rusage); - -UV_EXTERN int uv_os_homedir(char* buffer, size_t* size); -UV_EXTERN int uv_os_tmpdir(char* buffer, size_t* size); -UV_EXTERN int uv_os_get_passwd(uv_passwd_t* pwd); -UV_EXTERN void uv_os_free_passwd(uv_passwd_t* pwd); - -UV_EXTERN int uv_cpu_info(uv_cpu_info_t** cpu_infos, int* count); -UV_EXTERN void uv_free_cpu_info(uv_cpu_info_t* cpu_infos, int count); - -UV_EXTERN int uv_interface_addresses(uv_interface_address_t** addresses, - int* count); -UV_EXTERN void uv_free_interface_addresses(uv_interface_address_t* addresses, - int count); - - -typedef enum { - UV_FS_UNKNOWN = -1, - UV_FS_CUSTOM, - UV_FS_OPEN, - UV_FS_CLOSE, - UV_FS_READ, - UV_FS_WRITE, - UV_FS_SENDFILE, - UV_FS_STAT, - UV_FS_LSTAT, - UV_FS_FSTAT, - UV_FS_FTRUNCATE, - UV_FS_UTIME, - UV_FS_FUTIME, - UV_FS_ACCESS, - UV_FS_CHMOD, - UV_FS_FCHMOD, - UV_FS_FSYNC, - UV_FS_FDATASYNC, - UV_FS_UNLINK, - UV_FS_RMDIR, - UV_FS_MKDIR, - UV_FS_MKDTEMP, - UV_FS_RENAME, - UV_FS_SCANDIR, - UV_FS_LINK, - UV_FS_SYMLINK, - UV_FS_READLINK, - UV_FS_CHOWN, - UV_FS_FCHOWN, - UV_FS_REALPATH -} uv_fs_type; - -/* uv_fs_t is a subclass of uv_req_t. */ -struct uv_fs_s { - UV_REQ_FIELDS - uv_fs_type fs_type; - uv_loop_t* loop; - uv_fs_cb cb; - ssize_t result; - void* ptr; - const char* path; - uv_stat_t statbuf; /* Stores the result of uv_fs_stat() and uv_fs_fstat(). */ - UV_FS_PRIVATE_FIELDS -}; - -UV_EXTERN void uv_fs_req_cleanup(uv_fs_t* req); -UV_EXTERN int uv_fs_close(uv_loop_t* loop, - uv_fs_t* req, - uv_file file, - uv_fs_cb cb); -UV_EXTERN int uv_fs_open(uv_loop_t* loop, - uv_fs_t* req, - const char* path, - int flags, - int mode, - uv_fs_cb cb); -UV_EXTERN int uv_fs_read(uv_loop_t* loop, - uv_fs_t* req, - uv_file file, - const uv_buf_t bufs[], - unsigned int nbufs, - int64_t offset, - uv_fs_cb cb); -UV_EXTERN int uv_fs_unlink(uv_loop_t* loop, - uv_fs_t* req, - const char* path, - uv_fs_cb cb); -UV_EXTERN int uv_fs_write(uv_loop_t* loop, - uv_fs_t* req, - uv_file file, - const uv_buf_t bufs[], - unsigned int nbufs, - int64_t offset, - uv_fs_cb cb); -UV_EXTERN int uv_fs_mkdir(uv_loop_t* loop, - uv_fs_t* req, - const char* path, - int mode, - uv_fs_cb cb); -UV_EXTERN int uv_fs_mkdtemp(uv_loop_t* loop, - uv_fs_t* req, - const char* tpl, - uv_fs_cb cb); -UV_EXTERN int uv_fs_rmdir(uv_loop_t* loop, - uv_fs_t* req, - const char* path, - uv_fs_cb cb); -UV_EXTERN int uv_fs_scandir(uv_loop_t* loop, - uv_fs_t* req, - const char* path, - int flags, - uv_fs_cb cb); -UV_EXTERN int uv_fs_scandir_next(uv_fs_t* req, - uv_dirent_t* ent); -UV_EXTERN int uv_fs_stat(uv_loop_t* loop, - uv_fs_t* req, - const char* path, - uv_fs_cb cb); -UV_EXTERN int uv_fs_fstat(uv_loop_t* loop, - uv_fs_t* req, - uv_file file, - uv_fs_cb cb); -UV_EXTERN int uv_fs_rename(uv_loop_t* loop, - uv_fs_t* req, - const char* path, - const char* new_path, - uv_fs_cb cb); -UV_EXTERN int uv_fs_fsync(uv_loop_t* loop, - uv_fs_t* req, - uv_file file, - uv_fs_cb cb); -UV_EXTERN int uv_fs_fdatasync(uv_loop_t* loop, - uv_fs_t* req, - uv_file file, - uv_fs_cb cb); -UV_EXTERN int uv_fs_ftruncate(uv_loop_t* loop, - uv_fs_t* req, - uv_file file, - int64_t offset, - uv_fs_cb cb); -UV_EXTERN int uv_fs_sendfile(uv_loop_t* loop, - uv_fs_t* req, - uv_file out_fd, - uv_file in_fd, - int64_t in_offset, - size_t length, - uv_fs_cb cb); -UV_EXTERN int uv_fs_access(uv_loop_t* loop, - uv_fs_t* req, - const char* path, - int mode, - uv_fs_cb cb); -UV_EXTERN int uv_fs_chmod(uv_loop_t* loop, - uv_fs_t* req, - const char* path, - int mode, - uv_fs_cb cb); -UV_EXTERN int uv_fs_utime(uv_loop_t* loop, - uv_fs_t* req, - const char* path, - double atime, - double mtime, - uv_fs_cb cb); -UV_EXTERN int uv_fs_futime(uv_loop_t* loop, - uv_fs_t* req, - uv_file file, - double atime, - double mtime, - uv_fs_cb cb); -UV_EXTERN int uv_fs_lstat(uv_loop_t* loop, - uv_fs_t* req, - const char* path, - uv_fs_cb cb); -UV_EXTERN int uv_fs_link(uv_loop_t* loop, - uv_fs_t* req, - const char* path, - const char* new_path, - uv_fs_cb cb); - -/* - * This flag can be used with uv_fs_symlink() on Windows to specify whether - * path argument points to a directory. - */ -#define UV_FS_SYMLINK_DIR 0x0001 - -/* - * This flag can be used with uv_fs_symlink() on Windows to specify whether - * the symlink is to be created using junction points. - */ -#define UV_FS_SYMLINK_JUNCTION 0x0002 - -UV_EXTERN int uv_fs_symlink(uv_loop_t* loop, - uv_fs_t* req, - const char* path, - const char* new_path, - int flags, - uv_fs_cb cb); -UV_EXTERN int uv_fs_readlink(uv_loop_t* loop, - uv_fs_t* req, - const char* path, - uv_fs_cb cb); -UV_EXTERN int uv_fs_realpath(uv_loop_t* loop, - uv_fs_t* req, - const char* path, - uv_fs_cb cb); -UV_EXTERN int uv_fs_fchmod(uv_loop_t* loop, - uv_fs_t* req, - uv_file file, - int mode, - uv_fs_cb cb); -UV_EXTERN int uv_fs_chown(uv_loop_t* loop, - uv_fs_t* req, - const char* path, - uv_uid_t uid, - uv_gid_t gid, - uv_fs_cb cb); -UV_EXTERN int uv_fs_fchown(uv_loop_t* loop, - uv_fs_t* req, - uv_file file, - uv_uid_t uid, - uv_gid_t gid, - uv_fs_cb cb); - - -enum uv_fs_event { - UV_RENAME = 1, - UV_CHANGE = 2 -}; - - -struct uv_fs_event_s { - UV_HANDLE_FIELDS - /* private */ - char* path; - UV_FS_EVENT_PRIVATE_FIELDS -}; - - -/* - * uv_fs_stat() based polling file watcher. - */ -struct uv_fs_poll_s { - UV_HANDLE_FIELDS - /* Private, don't touch. */ - void* poll_ctx; -}; - -UV_EXTERN int uv_fs_poll_init(uv_loop_t* loop, uv_fs_poll_t* handle); -UV_EXTERN int uv_fs_poll_start(uv_fs_poll_t* handle, - uv_fs_poll_cb poll_cb, - const char* path, - unsigned int interval); -UV_EXTERN int uv_fs_poll_stop(uv_fs_poll_t* handle); -UV_EXTERN int uv_fs_poll_getpath(uv_fs_poll_t* handle, - char* buffer, - size_t* size); - - -struct uv_signal_s { - UV_HANDLE_FIELDS - uv_signal_cb signal_cb; - int signum; - UV_SIGNAL_PRIVATE_FIELDS -}; - -UV_EXTERN int uv_signal_init(uv_loop_t* loop, uv_signal_t* handle); -UV_EXTERN int uv_signal_start(uv_signal_t* handle, - uv_signal_cb signal_cb, - int signum); -UV_EXTERN int uv_signal_stop(uv_signal_t* handle); - -UV_EXTERN void uv_loadavg(double avg[3]); - - -/* - * Flags to be passed to uv_fs_event_start(). - */ -enum uv_fs_event_flags { - /* - * By default, if the fs event watcher is given a directory name, we will - * watch for all events in that directory. This flags overrides this behavior - * and makes fs_event report only changes to the directory entry itself. This - * flag does not affect individual files watched. - * This flag is currently not implemented yet on any backend. - */ - UV_FS_EVENT_WATCH_ENTRY = 1, - - /* - * By default uv_fs_event will try to use a kernel interface such as inotify - * or kqueue to detect events. This may not work on remote filesystems such - * as NFS mounts. This flag makes fs_event fall back to calling stat() on a - * regular interval. - * This flag is currently not implemented yet on any backend. - */ - UV_FS_EVENT_STAT = 2, - - /* - * By default, event watcher, when watching directory, is not registering - * (is ignoring) changes in it's subdirectories. - * This flag will override this behaviour on platforms that support it. - */ - UV_FS_EVENT_RECURSIVE = 4 -}; - - -UV_EXTERN int uv_fs_event_init(uv_loop_t* loop, uv_fs_event_t* handle); -UV_EXTERN int uv_fs_event_start(uv_fs_event_t* handle, - uv_fs_event_cb cb, - const char* path, - unsigned int flags); -UV_EXTERN int uv_fs_event_stop(uv_fs_event_t* handle); -UV_EXTERN int uv_fs_event_getpath(uv_fs_event_t* handle, - char* buffer, - size_t* size); - -UV_EXTERN int uv_ip4_addr(const char* ip, int port, struct sockaddr_in* addr); -UV_EXTERN int uv_ip6_addr(const char* ip, int port, struct sockaddr_in6* addr); - -UV_EXTERN int uv_ip4_name(const struct sockaddr_in* src, char* dst, size_t size); -UV_EXTERN int uv_ip6_name(const struct sockaddr_in6* src, char* dst, size_t size); - -UV_EXTERN int uv_inet_ntop(int af, const void* src, char* dst, size_t size); -UV_EXTERN int uv_inet_pton(int af, const char* src, void* dst); - -UV_EXTERN int uv_exepath(char* buffer, size_t* size); - -UV_EXTERN int uv_cwd(char* buffer, size_t* size); - -UV_EXTERN int uv_chdir(const char* dir); - -UV_EXTERN uint64_t uv_get_free_memory(void); -UV_EXTERN uint64_t uv_get_total_memory(void); - -UV_EXTERN uint64_t uv_hrtime(void); - -UV_EXTERN void uv_disable_stdio_inheritance(void); - -UV_EXTERN int uv_dlopen(const char* filename, uv_lib_t* lib); -UV_EXTERN void uv_dlclose(uv_lib_t* lib); -UV_EXTERN int uv_dlsym(uv_lib_t* lib, const char* name, void** ptr); -UV_EXTERN const char* uv_dlerror(const uv_lib_t* lib); - -UV_EXTERN int uv_mutex_init(uv_mutex_t* handle); -UV_EXTERN void uv_mutex_destroy(uv_mutex_t* handle); -UV_EXTERN void uv_mutex_lock(uv_mutex_t* handle); -UV_EXTERN int uv_mutex_trylock(uv_mutex_t* handle); -UV_EXTERN void uv_mutex_unlock(uv_mutex_t* handle); - -UV_EXTERN int uv_rwlock_init(uv_rwlock_t* rwlock); -UV_EXTERN void uv_rwlock_destroy(uv_rwlock_t* rwlock); -UV_EXTERN void uv_rwlock_rdlock(uv_rwlock_t* rwlock); -UV_EXTERN int uv_rwlock_tryrdlock(uv_rwlock_t* rwlock); -UV_EXTERN void uv_rwlock_rdunlock(uv_rwlock_t* rwlock); -UV_EXTERN void uv_rwlock_wrlock(uv_rwlock_t* rwlock); -UV_EXTERN int uv_rwlock_trywrlock(uv_rwlock_t* rwlock); -UV_EXTERN void uv_rwlock_wrunlock(uv_rwlock_t* rwlock); - -UV_EXTERN int uv_sem_init(uv_sem_t* sem, unsigned int value); -UV_EXTERN void uv_sem_destroy(uv_sem_t* sem); -UV_EXTERN void uv_sem_post(uv_sem_t* sem); -UV_EXTERN void uv_sem_wait(uv_sem_t* sem); -UV_EXTERN int uv_sem_trywait(uv_sem_t* sem); - -UV_EXTERN int uv_cond_init(uv_cond_t* cond); -UV_EXTERN void uv_cond_destroy(uv_cond_t* cond); -UV_EXTERN void uv_cond_signal(uv_cond_t* cond); -UV_EXTERN void uv_cond_broadcast(uv_cond_t* cond); - -UV_EXTERN int uv_barrier_init(uv_barrier_t* barrier, unsigned int count); -UV_EXTERN void uv_barrier_destroy(uv_barrier_t* barrier); -UV_EXTERN int uv_barrier_wait(uv_barrier_t* barrier); - -UV_EXTERN void uv_cond_wait(uv_cond_t* cond, uv_mutex_t* mutex); -UV_EXTERN int uv_cond_timedwait(uv_cond_t* cond, - uv_mutex_t* mutex, - uint64_t timeout); - -UV_EXTERN void uv_once(uv_once_t* guard, void (*callback)(void)); - -UV_EXTERN int uv_key_create(uv_key_t* key); -UV_EXTERN void uv_key_delete(uv_key_t* key); -UV_EXTERN void* uv_key_get(uv_key_t* key); -UV_EXTERN void uv_key_set(uv_key_t* key, void* value); - -/* - * CPU masks for thread affinity must be at least UV_CPU_SETSIZE bytes long. - */ -#if defined(_WIN32) -# if defined(_WIN64) -# define UV_CPU_SETSIZE 64 -# else -# define UV_CPU_SETSIZE 32 -# endif -#else -# if defined(__APPLE__) || defined(_AIX) -# define UV_CPU_SETSIZE 8 -# else -# define UV_CPU_SETSIZE CPU_SETSIZE -# endif -#endif - -/* - * Callback that is invoked to initialize thread execution. - * - * `arg` is the same value that was passed to uv_thread_create(). - */ -typedef void (*uv_thread_cb)(void* arg); - -UV_EXTERN int uv_thread_create(uv_thread_t* tid, uv_thread_cb entry, void* arg); -UV_EXTERN int uv_thread_setaffinity(uv_thread_t* tid, - char *cpumask, - char *oldmask, - size_t mask_size); -UV_EXTERN int uv_thread_getaffinity(uv_thread_t* tid, - char *cpumask, - size_t mask_size); -UV_EXTERN int uv_thread_detach(uv_thread_t* tid); -UV_EXTERN uv_thread_t uv_thread_self(void); -UV_EXTERN int uv_thread_join(uv_thread_t *tid); -UV_EXTERN int uv_thread_equal(const uv_thread_t* t1, const uv_thread_t* t2); - -/* The presence of these unions force similar struct layout. */ -#define XX(_, name) uv_ ## name ## _t name; -union uv_any_handle { - UV_HANDLE_TYPE_MAP(XX) -}; - -union uv_any_req { - UV_REQ_TYPE_MAP(XX) -}; -#undef XX - - -struct uv_loop_s { - /* User data - use this for whatever. */ - void* data; - /* Loop reference counting. */ - unsigned int active_handles; - void* handle_queue[2]; - void* active_reqs[2]; - /* Internal flag to signal loop stop. */ - unsigned int stop_flag; - UV_LOOP_PRIVATE_FIELDS -}; - - -/* Don't export the private CPP symbols. */ -#undef UV_HANDLE_TYPE_PRIVATE -#undef UV_REQ_TYPE_PRIVATE -#undef UV_REQ_PRIVATE_FIELDS -#undef UV_STREAM_PRIVATE_FIELDS -#undef UV_TCP_PRIVATE_FIELDS -#undef UV_PREPARE_PRIVATE_FIELDS -#undef UV_CHECK_PRIVATE_FIELDS -#undef UV_IDLE_PRIVATE_FIELDS -#undef UV_ASYNC_PRIVATE_FIELDS -#undef UV_TIMER_PRIVATE_FIELDS -#undef UV_GETADDRINFO_PRIVATE_FIELDS -#undef UV_GETNAMEINFO_PRIVATE_FIELDS -#undef UV_FS_REQ_PRIVATE_FIELDS -#undef UV_WORK_PRIVATE_FIELDS -#undef UV_FS_EVENT_PRIVATE_FIELDS -#undef UV_SIGNAL_PRIVATE_FIELDS -#undef UV_LOOP_PRIVATE_FIELDS -#undef UV_LOOP_PRIVATE_PLATFORM_FIELDS - -#ifdef __cplusplus -} -#endif -#endif /* UV_H */ diff --git a/julia-0.6.3/lib/julia/libLLVM-3.9.1.so b/julia-0.6.3/lib/julia/libLLVM-3.9.1.so deleted file mode 120000 index 093992f..0000000 --- a/julia-0.6.3/lib/julia/libLLVM-3.9.1.so +++ /dev/null @@ -1 +0,0 @@ -libLLVM-3.9.so \ No newline at end of file diff --git a/julia-0.6.3/lib/julia/libLLVM-3.9.so.REMOVED.git-id b/julia-0.6.3/lib/julia/libLLVM-3.9.so.REMOVED.git-id deleted file mode 100644 index 46846e8..0000000 --- a/julia-0.6.3/lib/julia/libLLVM-3.9.so.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -c6d518857297010b78acaf70101db1dc2deca407 \ No newline at end of file diff --git a/julia-0.6.3/lib/julia/libLLVM.so b/julia-0.6.3/lib/julia/libLLVM.so deleted file mode 120000 index 093992f..0000000 --- a/julia-0.6.3/lib/julia/libLLVM.so +++ /dev/null @@ -1 +0,0 @@ -libLLVM-3.9.so \ No newline at end of file diff --git a/julia-0.6.3/lib/julia/libamd.so b/julia-0.6.3/lib/julia/libamd.so deleted file mode 100755 index c289713..0000000 Binary files a/julia-0.6.3/lib/julia/libamd.so and /dev/null differ diff --git a/julia-0.6.3/lib/julia/libarpack.so b/julia-0.6.3/lib/julia/libarpack.so deleted file mode 120000 index 6160734..0000000 --- a/julia-0.6.3/lib/julia/libarpack.so +++ /dev/null @@ -1 +0,0 @@ -libarpack.so.2.0.0 \ No newline at end of file diff --git a/julia-0.6.3/lib/julia/libarpack.so.2 b/julia-0.6.3/lib/julia/libarpack.so.2 deleted file mode 120000 index 6160734..0000000 --- a/julia-0.6.3/lib/julia/libarpack.so.2 +++ /dev/null @@ -1 +0,0 @@ -libarpack.so.2.0.0 \ No newline at end of file diff --git a/julia-0.6.3/lib/julia/libarpack.so.2.0.0 b/julia-0.6.3/lib/julia/libarpack.so.2.0.0 deleted file mode 100755 index 1c1ecf2..0000000 Binary files a/julia-0.6.3/lib/julia/libarpack.so.2.0.0 and /dev/null differ diff --git a/julia-0.6.3/lib/julia/libcamd.so b/julia-0.6.3/lib/julia/libcamd.so deleted file mode 100755 index cf59d18..0000000 Binary files a/julia-0.6.3/lib/julia/libcamd.so and /dev/null differ diff --git a/julia-0.6.3/lib/julia/libccalltest.so b/julia-0.6.3/lib/julia/libccalltest.so deleted file mode 100755 index b36469c..0000000 Binary files a/julia-0.6.3/lib/julia/libccalltest.so and /dev/null differ diff --git a/julia-0.6.3/lib/julia/libccalltest.so.debug b/julia-0.6.3/lib/julia/libccalltest.so.debug deleted file mode 100755 index 71a92da..0000000 Binary files a/julia-0.6.3/lib/julia/libccalltest.so.debug and /dev/null differ diff --git a/julia-0.6.3/lib/julia/libccolamd.so b/julia-0.6.3/lib/julia/libccolamd.so deleted file mode 100755 index f906a19..0000000 Binary files a/julia-0.6.3/lib/julia/libccolamd.so and /dev/null differ diff --git a/julia-0.6.3/lib/julia/libcholmod.so b/julia-0.6.3/lib/julia/libcholmod.so deleted file mode 100755 index d7ad1b1..0000000 Binary files a/julia-0.6.3/lib/julia/libcholmod.so and /dev/null differ diff --git a/julia-0.6.3/lib/julia/libcolamd.so b/julia-0.6.3/lib/julia/libcolamd.so deleted file mode 100755 index 7e23bdf..0000000 Binary files a/julia-0.6.3/lib/julia/libcolamd.so and /dev/null differ diff --git a/julia-0.6.3/lib/julia/libcurl.so b/julia-0.6.3/lib/julia/libcurl.so deleted file mode 120000 index a5e8ad8..0000000 --- a/julia-0.6.3/lib/julia/libcurl.so +++ /dev/null @@ -1 +0,0 @@ -libcurl.so.4.5.0 \ No newline at end of file diff --git a/julia-0.6.3/lib/julia/libcurl.so.4 b/julia-0.6.3/lib/julia/libcurl.so.4 deleted file mode 120000 index a5e8ad8..0000000 --- a/julia-0.6.3/lib/julia/libcurl.so.4 +++ /dev/null @@ -1 +0,0 @@ -libcurl.so.4.5.0 \ No newline at end of file diff --git a/julia-0.6.3/lib/julia/libcurl.so.4.5.0 b/julia-0.6.3/lib/julia/libcurl.so.4.5.0 deleted file mode 100755 index aae669a..0000000 Binary files a/julia-0.6.3/lib/julia/libcurl.so.4.5.0 and /dev/null differ diff --git a/julia-0.6.3/lib/julia/libdSFMT.so b/julia-0.6.3/lib/julia/libdSFMT.so deleted file mode 100755 index 2bff9da..0000000 Binary files a/julia-0.6.3/lib/julia/libdSFMT.so and /dev/null differ diff --git a/julia-0.6.3/lib/julia/libfftw3.so b/julia-0.6.3/lib/julia/libfftw3.so deleted file mode 120000 index 2add15e..0000000 --- a/julia-0.6.3/lib/julia/libfftw3.so +++ /dev/null @@ -1 +0,0 @@ -libfftw3.so.3.5.6 \ No newline at end of file diff --git a/julia-0.6.3/lib/julia/libfftw3.so.3 b/julia-0.6.3/lib/julia/libfftw3.so.3 deleted file mode 120000 index 2add15e..0000000 --- a/julia-0.6.3/lib/julia/libfftw3.so.3 +++ /dev/null @@ -1 +0,0 @@ -libfftw3.so.3.5.6 \ No newline at end of file diff --git a/julia-0.6.3/lib/julia/libfftw3.so.3.5.6 b/julia-0.6.3/lib/julia/libfftw3.so.3.5.6 deleted file mode 100755 index 8eb7e0b..0000000 Binary files a/julia-0.6.3/lib/julia/libfftw3.so.3.5.6 and /dev/null differ diff --git a/julia-0.6.3/lib/julia/libfftw3_threads.so b/julia-0.6.3/lib/julia/libfftw3_threads.so deleted file mode 120000 index 77d321f..0000000 --- a/julia-0.6.3/lib/julia/libfftw3_threads.so +++ /dev/null @@ -1 +0,0 @@ -libfftw3_threads.so.3.5.6 \ No newline at end of file diff --git a/julia-0.6.3/lib/julia/libfftw3_threads.so.3 b/julia-0.6.3/lib/julia/libfftw3_threads.so.3 deleted file mode 120000 index 77d321f..0000000 --- a/julia-0.6.3/lib/julia/libfftw3_threads.so.3 +++ /dev/null @@ -1 +0,0 @@ -libfftw3_threads.so.3.5.6 \ No newline at end of file diff --git a/julia-0.6.3/lib/julia/libfftw3_threads.so.3.5.6 b/julia-0.6.3/lib/julia/libfftw3_threads.so.3.5.6 deleted file mode 100755 index 91c669d..0000000 Binary files a/julia-0.6.3/lib/julia/libfftw3_threads.so.3.5.6 and /dev/null differ diff --git a/julia-0.6.3/lib/julia/libfftw3f.so b/julia-0.6.3/lib/julia/libfftw3f.so deleted file mode 120000 index bb22b57..0000000 --- a/julia-0.6.3/lib/julia/libfftw3f.so +++ /dev/null @@ -1 +0,0 @@ -libfftw3f.so.3.5.6 \ No newline at end of file diff --git a/julia-0.6.3/lib/julia/libfftw3f.so.3 b/julia-0.6.3/lib/julia/libfftw3f.so.3 deleted file mode 120000 index bb22b57..0000000 --- a/julia-0.6.3/lib/julia/libfftw3f.so.3 +++ /dev/null @@ -1 +0,0 @@ -libfftw3f.so.3.5.6 \ No newline at end of file diff --git a/julia-0.6.3/lib/julia/libfftw3f.so.3.5.6 b/julia-0.6.3/lib/julia/libfftw3f.so.3.5.6 deleted file mode 100755 index 3dc8a07..0000000 Binary files a/julia-0.6.3/lib/julia/libfftw3f.so.3.5.6 and /dev/null differ diff --git a/julia-0.6.3/lib/julia/libfftw3f_threads.so b/julia-0.6.3/lib/julia/libfftw3f_threads.so deleted file mode 120000 index 37727ca..0000000 --- a/julia-0.6.3/lib/julia/libfftw3f_threads.so +++ /dev/null @@ -1 +0,0 @@ -libfftw3f_threads.so.3.5.6 \ No newline at end of file diff --git a/julia-0.6.3/lib/julia/libfftw3f_threads.so.3 b/julia-0.6.3/lib/julia/libfftw3f_threads.so.3 deleted file mode 120000 index 37727ca..0000000 --- a/julia-0.6.3/lib/julia/libfftw3f_threads.so.3 +++ /dev/null @@ -1 +0,0 @@ -libfftw3f_threads.so.3.5.6 \ No newline at end of file diff --git a/julia-0.6.3/lib/julia/libfftw3f_threads.so.3.5.6 b/julia-0.6.3/lib/julia/libfftw3f_threads.so.3.5.6 deleted file mode 100755 index 40203c6..0000000 Binary files a/julia-0.6.3/lib/julia/libfftw3f_threads.so.3.5.6 and /dev/null differ diff --git a/julia-0.6.3/lib/julia/libgcc_s.so.1 b/julia-0.6.3/lib/julia/libgcc_s.so.1 deleted file mode 100755 index 1416a58..0000000 Binary files a/julia-0.6.3/lib/julia/libgcc_s.so.1 and /dev/null differ diff --git a/julia-0.6.3/lib/julia/libgfortran.so.4 b/julia-0.6.3/lib/julia/libgfortran.so.4 deleted file mode 100755 index 058d30d..0000000 Binary files a/julia-0.6.3/lib/julia/libgfortran.so.4 and /dev/null differ diff --git a/julia-0.6.3/lib/julia/libgit2.so b/julia-0.6.3/lib/julia/libgit2.so deleted file mode 120000 index 94950dd..0000000 --- a/julia-0.6.3/lib/julia/libgit2.so +++ /dev/null @@ -1 +0,0 @@ -libgit2.so.25 \ No newline at end of file diff --git a/julia-0.6.3/lib/julia/libgit2.so.0.25.1 b/julia-0.6.3/lib/julia/libgit2.so.0.25.1 deleted file mode 100755 index c8d06e2..0000000 Binary files a/julia-0.6.3/lib/julia/libgit2.so.0.25.1 and /dev/null differ diff --git a/julia-0.6.3/lib/julia/libgit2.so.25 b/julia-0.6.3/lib/julia/libgit2.so.25 deleted file mode 120000 index dba2ed0..0000000 --- a/julia-0.6.3/lib/julia/libgit2.so.25 +++ /dev/null @@ -1 +0,0 @@ -libgit2.so.0.25.1 \ No newline at end of file diff --git a/julia-0.6.3/lib/julia/libgmp.so b/julia-0.6.3/lib/julia/libgmp.so deleted file mode 120000 index db67e23..0000000 --- a/julia-0.6.3/lib/julia/libgmp.so +++ /dev/null @@ -1 +0,0 @@ -libgmp.so.10.3.2 \ No newline at end of file diff --git a/julia-0.6.3/lib/julia/libgmp.so.10 b/julia-0.6.3/lib/julia/libgmp.so.10 deleted file mode 120000 index db67e23..0000000 --- a/julia-0.6.3/lib/julia/libgmp.so.10 +++ /dev/null @@ -1 +0,0 @@ -libgmp.so.10.3.2 \ No newline at end of file diff --git a/julia-0.6.3/lib/julia/libgmp.so.10.3.2 b/julia-0.6.3/lib/julia/libgmp.so.10.3.2 deleted file mode 100755 index d717c2d..0000000 Binary files a/julia-0.6.3/lib/julia/libgmp.so.10.3.2 and /dev/null differ diff --git a/julia-0.6.3/lib/julia/libmbedcrypto.so b/julia-0.6.3/lib/julia/libmbedcrypto.so deleted file mode 120000 index 32a2e29..0000000 --- a/julia-0.6.3/lib/julia/libmbedcrypto.so +++ /dev/null @@ -1 +0,0 @@ -libmbedcrypto.so.0 \ No newline at end of file diff --git a/julia-0.6.3/lib/julia/libmbedcrypto.so.0 b/julia-0.6.3/lib/julia/libmbedcrypto.so.0 deleted file mode 120000 index d29d3f5..0000000 --- a/julia-0.6.3/lib/julia/libmbedcrypto.so.0 +++ /dev/null @@ -1 +0,0 @@ -libmbedcrypto.so.2.3.0 \ No newline at end of file diff --git a/julia-0.6.3/lib/julia/libmbedcrypto.so.2.3.0 b/julia-0.6.3/lib/julia/libmbedcrypto.so.2.3.0 deleted file mode 100755 index c468ab9..0000000 Binary files a/julia-0.6.3/lib/julia/libmbedcrypto.so.2.3.0 and /dev/null differ diff --git a/julia-0.6.3/lib/julia/libmbedtls.so b/julia-0.6.3/lib/julia/libmbedtls.so deleted file mode 120000 index 3e26c40..0000000 --- a/julia-0.6.3/lib/julia/libmbedtls.so +++ /dev/null @@ -1 +0,0 @@ -libmbedtls.so.10 \ No newline at end of file diff --git a/julia-0.6.3/lib/julia/libmbedtls.so.10 b/julia-0.6.3/lib/julia/libmbedtls.so.10 deleted file mode 120000 index ac298b0..0000000 --- a/julia-0.6.3/lib/julia/libmbedtls.so.10 +++ /dev/null @@ -1 +0,0 @@ -libmbedtls.so.2.3.0 \ No newline at end of file diff --git a/julia-0.6.3/lib/julia/libmbedtls.so.2.3.0 b/julia-0.6.3/lib/julia/libmbedtls.so.2.3.0 deleted file mode 100755 index 0d7bfd2..0000000 Binary files a/julia-0.6.3/lib/julia/libmbedtls.so.2.3.0 and /dev/null differ diff --git a/julia-0.6.3/lib/julia/libmbedx509.so b/julia-0.6.3/lib/julia/libmbedx509.so deleted file mode 120000 index 44fc081..0000000 --- a/julia-0.6.3/lib/julia/libmbedx509.so +++ /dev/null @@ -1 +0,0 @@ -libmbedx509.so.0 \ No newline at end of file diff --git a/julia-0.6.3/lib/julia/libmbedx509.so.0 b/julia-0.6.3/lib/julia/libmbedx509.so.0 deleted file mode 120000 index 431ddce..0000000 --- a/julia-0.6.3/lib/julia/libmbedx509.so.0 +++ /dev/null @@ -1 +0,0 @@ -libmbedx509.so.2.3.0 \ No newline at end of file diff --git a/julia-0.6.3/lib/julia/libmbedx509.so.2.3.0 b/julia-0.6.3/lib/julia/libmbedx509.so.2.3.0 deleted file mode 100755 index cbad9ed..0000000 Binary files a/julia-0.6.3/lib/julia/libmbedx509.so.2.3.0 and /dev/null differ diff --git a/julia-0.6.3/lib/julia/libmpfr.so b/julia-0.6.3/lib/julia/libmpfr.so deleted file mode 120000 index d77f027..0000000 --- a/julia-0.6.3/lib/julia/libmpfr.so +++ /dev/null @@ -1 +0,0 @@ -libmpfr.so.4.1.5 \ No newline at end of file diff --git a/julia-0.6.3/lib/julia/libmpfr.so.4 b/julia-0.6.3/lib/julia/libmpfr.so.4 deleted file mode 120000 index d77f027..0000000 --- a/julia-0.6.3/lib/julia/libmpfr.so.4 +++ /dev/null @@ -1 +0,0 @@ -libmpfr.so.4.1.5 \ No newline at end of file diff --git a/julia-0.6.3/lib/julia/libmpfr.so.4.1.5 b/julia-0.6.3/lib/julia/libmpfr.so.4.1.5 deleted file mode 100755 index b4e297c..0000000 Binary files a/julia-0.6.3/lib/julia/libmpfr.so.4.1.5 and /dev/null differ diff --git a/julia-0.6.3/lib/julia/libopenblas64_.so.0 b/julia-0.6.3/lib/julia/libopenblas64_.so.0 deleted file mode 120000 index f04083e..0000000 --- a/julia-0.6.3/lib/julia/libopenblas64_.so.0 +++ /dev/null @@ -1 +0,0 @@ -libopenblas64_.so \ No newline at end of file diff --git a/julia-0.6.3/lib/julia/libopenblas64_.so.REMOVED.git-id b/julia-0.6.3/lib/julia/libopenblas64_.so.REMOVED.git-id deleted file mode 100644 index 5759348..0000000 --- a/julia-0.6.3/lib/julia/libopenblas64_.so.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -1b86a8fc7d437c5994edc48e05c9fbd966a8362a \ No newline at end of file diff --git a/julia-0.6.3/lib/julia/libopenlibm.so b/julia-0.6.3/lib/julia/libopenlibm.so deleted file mode 120000 index 85a8721..0000000 --- a/julia-0.6.3/lib/julia/libopenlibm.so +++ /dev/null @@ -1 +0,0 @@ -libopenlibm.so.2.3 \ No newline at end of file diff --git a/julia-0.6.3/lib/julia/libopenlibm.so.2 b/julia-0.6.3/lib/julia/libopenlibm.so.2 deleted file mode 120000 index 85a8721..0000000 --- a/julia-0.6.3/lib/julia/libopenlibm.so.2 +++ /dev/null @@ -1 +0,0 @@ -libopenlibm.so.2.3 \ No newline at end of file diff --git a/julia-0.6.3/lib/julia/libopenlibm.so.2.3 b/julia-0.6.3/lib/julia/libopenlibm.so.2.3 deleted file mode 100755 index da67013..0000000 Binary files a/julia-0.6.3/lib/julia/libopenlibm.so.2.3 and /dev/null differ diff --git a/julia-0.6.3/lib/julia/libopenspecfun.so b/julia-0.6.3/lib/julia/libopenspecfun.so deleted file mode 120000 index d84c8a5..0000000 --- a/julia-0.6.3/lib/julia/libopenspecfun.so +++ /dev/null @@ -1 +0,0 @@ -libopenspecfun.so.1.3 \ No newline at end of file diff --git a/julia-0.6.3/lib/julia/libopenspecfun.so.1 b/julia-0.6.3/lib/julia/libopenspecfun.so.1 deleted file mode 120000 index d84c8a5..0000000 --- a/julia-0.6.3/lib/julia/libopenspecfun.so.1 +++ /dev/null @@ -1 +0,0 @@ -libopenspecfun.so.1.3 \ No newline at end of file diff --git a/julia-0.6.3/lib/julia/libopenspecfun.so.1.3 b/julia-0.6.3/lib/julia/libopenspecfun.so.1.3 deleted file mode 100755 index 6170914..0000000 Binary files a/julia-0.6.3/lib/julia/libopenspecfun.so.1.3 and /dev/null differ diff --git a/julia-0.6.3/lib/julia/libpcre2-8.so b/julia-0.6.3/lib/julia/libpcre2-8.so deleted file mode 120000 index 58db0cb..0000000 --- a/julia-0.6.3/lib/julia/libpcre2-8.so +++ /dev/null @@ -1 +0,0 @@ -libpcre2-8.so.0.5.0 \ No newline at end of file diff --git a/julia-0.6.3/lib/julia/libpcre2-8.so.0 b/julia-0.6.3/lib/julia/libpcre2-8.so.0 deleted file mode 120000 index 58db0cb..0000000 --- a/julia-0.6.3/lib/julia/libpcre2-8.so.0 +++ /dev/null @@ -1 +0,0 @@ -libpcre2-8.so.0.5.0 \ No newline at end of file diff --git a/julia-0.6.3/lib/julia/libpcre2-8.so.0.5.0 b/julia-0.6.3/lib/julia/libpcre2-8.so.0.5.0 deleted file mode 100755 index 4d0958c..0000000 Binary files a/julia-0.6.3/lib/julia/libpcre2-8.so.0.5.0 and /dev/null differ diff --git a/julia-0.6.3/lib/julia/libpcre2-posix.so b/julia-0.6.3/lib/julia/libpcre2-posix.so deleted file mode 120000 index ec084bf..0000000 --- a/julia-0.6.3/lib/julia/libpcre2-posix.so +++ /dev/null @@ -1 +0,0 @@ -libpcre2-posix.so.1.0.1 \ No newline at end of file diff --git a/julia-0.6.3/lib/julia/libpcre2-posix.so.1 b/julia-0.6.3/lib/julia/libpcre2-posix.so.1 deleted file mode 120000 index ec084bf..0000000 --- a/julia-0.6.3/lib/julia/libpcre2-posix.so.1 +++ /dev/null @@ -1 +0,0 @@ -libpcre2-posix.so.1.0.1 \ No newline at end of file diff --git a/julia-0.6.3/lib/julia/libpcre2-posix.so.1.0.1 b/julia-0.6.3/lib/julia/libpcre2-posix.so.1.0.1 deleted file mode 100755 index 04760df..0000000 Binary files a/julia-0.6.3/lib/julia/libpcre2-posix.so.1.0.1 and /dev/null differ diff --git a/julia-0.6.3/lib/julia/libquadmath.so.0 b/julia-0.6.3/lib/julia/libquadmath.so.0 deleted file mode 100755 index a4ebd4c..0000000 Binary files a/julia-0.6.3/lib/julia/libquadmath.so.0 and /dev/null differ diff --git a/julia-0.6.3/lib/julia/libspqr.so b/julia-0.6.3/lib/julia/libspqr.so deleted file mode 100755 index f61d33e..0000000 Binary files a/julia-0.6.3/lib/julia/libspqr.so and /dev/null differ diff --git a/julia-0.6.3/lib/julia/libssh2.so b/julia-0.6.3/lib/julia/libssh2.so deleted file mode 120000 index b4441c3..0000000 --- a/julia-0.6.3/lib/julia/libssh2.so +++ /dev/null @@ -1 +0,0 @@ -libssh2.so.1 \ No newline at end of file diff --git a/julia-0.6.3/lib/julia/libssh2.so.1 b/julia-0.6.3/lib/julia/libssh2.so.1 deleted file mode 120000 index 8a7d69e..0000000 --- a/julia-0.6.3/lib/julia/libssh2.so.1 +++ /dev/null @@ -1 +0,0 @@ -libssh2.so.1.0.1 \ No newline at end of file diff --git a/julia-0.6.3/lib/julia/libssh2.so.1.0.1 b/julia-0.6.3/lib/julia/libssh2.so.1.0.1 deleted file mode 100755 index 2b2958f..0000000 Binary files a/julia-0.6.3/lib/julia/libssh2.so.1.0.1 and /dev/null differ diff --git a/julia-0.6.3/lib/julia/libstdc++.so.6.REMOVED.git-id b/julia-0.6.3/lib/julia/libstdc++.so.6.REMOVED.git-id deleted file mode 100644 index 5dbb470..0000000 --- a/julia-0.6.3/lib/julia/libstdc++.so.6.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -c915b8f40bcb6e2e2dadf3bceb787519d811106f \ No newline at end of file diff --git a/julia-0.6.3/lib/julia/libsuitesparse_wrapper.so b/julia-0.6.3/lib/julia/libsuitesparse_wrapper.so deleted file mode 100755 index 9ed728a..0000000 Binary files a/julia-0.6.3/lib/julia/libsuitesparse_wrapper.so and /dev/null differ diff --git a/julia-0.6.3/lib/julia/libsuitesparseconfig.so b/julia-0.6.3/lib/julia/libsuitesparseconfig.so deleted file mode 100755 index 1153e68..0000000 Binary files a/julia-0.6.3/lib/julia/libsuitesparseconfig.so and /dev/null differ diff --git a/julia-0.6.3/lib/julia/libumfpack.so b/julia-0.6.3/lib/julia/libumfpack.so deleted file mode 100755 index 122636b..0000000 Binary files a/julia-0.6.3/lib/julia/libumfpack.so and /dev/null differ diff --git a/julia-0.6.3/lib/julia/sys-debug.so.REMOVED.git-id b/julia-0.6.3/lib/julia/sys-debug.so.REMOVED.git-id deleted file mode 100644 index 3efeb9a..0000000 --- a/julia-0.6.3/lib/julia/sys-debug.so.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -f21d789ebcf70ff90c497523bcdbef37b50f378e \ No newline at end of file diff --git a/julia-0.6.3/lib/julia/sys.so.REMOVED.git-id b/julia-0.6.3/lib/julia/sys.so.REMOVED.git-id deleted file mode 100644 index 0d55e8e..0000000 --- a/julia-0.6.3/lib/julia/sys.so.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -5181d9fe28669e840e765eceab560d0bab56ae59 \ No newline at end of file diff --git a/julia-0.6.3/lib/libjulia-debug.so b/julia-0.6.3/lib/libjulia-debug.so deleted file mode 120000 index 97df690..0000000 --- a/julia-0.6.3/lib/libjulia-debug.so +++ /dev/null @@ -1 +0,0 @@ -libjulia-debug.so.0.6.3 \ No newline at end of file diff --git a/julia-0.6.3/lib/libjulia-debug.so.0.6 b/julia-0.6.3/lib/libjulia-debug.so.0.6 deleted file mode 120000 index 97df690..0000000 --- a/julia-0.6.3/lib/libjulia-debug.so.0.6 +++ /dev/null @@ -1 +0,0 @@ -libjulia-debug.so.0.6.3 \ No newline at end of file diff --git a/julia-0.6.3/lib/libjulia-debug.so.0.6.3.REMOVED.git-id b/julia-0.6.3/lib/libjulia-debug.so.0.6.3.REMOVED.git-id deleted file mode 100644 index 89796f3..0000000 --- a/julia-0.6.3/lib/libjulia-debug.so.0.6.3.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -cf14bb7960ad98f673470e9e2fe31f487db2bee0 \ No newline at end of file diff --git a/julia-0.6.3/lib/libjulia.so b/julia-0.6.3/lib/libjulia.so deleted file mode 120000 index f536a49..0000000 --- a/julia-0.6.3/lib/libjulia.so +++ /dev/null @@ -1 +0,0 @@ -libjulia.so.0.6.3 \ No newline at end of file diff --git a/julia-0.6.3/lib/libjulia.so.0.6 b/julia-0.6.3/lib/libjulia.so.0.6 deleted file mode 120000 index f536a49..0000000 --- a/julia-0.6.3/lib/libjulia.so.0.6 +++ /dev/null @@ -1 +0,0 @@ -libjulia.so.0.6.3 \ No newline at end of file diff --git a/julia-0.6.3/lib/libjulia.so.0.6.3.REMOVED.git-id b/julia-0.6.3/lib/libjulia.so.0.6.3.REMOVED.git-id deleted file mode 100644 index 397a67a..0000000 --- a/julia-0.6.3/lib/libjulia.so.0.6.3.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -f5992a45a406af8d847f75ed637138112c04bce1 \ No newline at end of file diff --git a/julia-0.6.3/share/appdata/julia.appdata.xml b/julia-0.6.3/share/appdata/julia.appdata.xml deleted file mode 100644 index 576d883..0000000 --- a/julia-0.6.3/share/appdata/julia.appdata.xml +++ /dev/null @@ -1,28 +0,0 @@ - - - - julia.desktop - CC-BY-SA-3.0 - MIT and LGPL-2.1+ and GPL-2.0+ - -

- Julia is a high-level, high-performance dynamic programming language for - technical computing, with syntax that is familiar to users of other - technical computing environments. It provides a sophisticated compiler, - distributed parallel execution, numerical accuracy, and an extensive - mathematical function library. -

-

- The library, largely written in Julia itself, - also integrates mature, best-of-breed C and Fortran libraries for linear - algebra, random number generation, signal processing, and string processing. - In addition, the Julia developer community is contributing a number of - external packages through Julia’s built-in package manager at a rapid pace. -

-
- - https://julialang.org/images/julia-gnome.png - - https://julialang.org/ - julia-dev@googlegroups.com -
diff --git a/julia-0.6.3/share/applications/julia.desktop b/julia-0.6.3/share/applications/julia.desktop deleted file mode 100644 index 6b41981..0000000 --- a/julia-0.6.3/share/applications/julia.desktop +++ /dev/null @@ -1,8 +0,0 @@ -[Desktop Entry] -Name=Julia -Comment=High-level, high-performance dynamic language for technical computing -Exec=julia -Icon=julia -Terminal=true -Type=Application -Categories=Development;ComputerScience;Building;Science;Math;NumericalAnalysis;ParallelComputing;DataVisualization;ConsoleOnly; diff --git a/julia-0.6.3/share/doc/julia/examples/ModInts.jl b/julia-0.6.3/share/doc/julia/examples/ModInts.jl deleted file mode 100644 index a6894cd..0000000 --- a/julia-0.6.3/share/doc/julia/examples/ModInts.jl +++ /dev/null @@ -1,27 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -module ModInts -export ModInt - -import Base: +, -, *, /, inv - -struct ModInt{n} <: Integer - k::Int - ModInt{n}(k) where n = new(mod(k,n)) -end - -Base.show{n}(io::IO, k::ModInt{n}) = - print(io, get(io, :compact, false) ? k.k : "$(k.k) mod $n") - -+{n}(a::ModInt{n}, b::ModInt{n}) = ModInt{n}(a.k+b.k) --{n}(a::ModInt{n}, b::ModInt{n}) = ModInt{n}(a.k-b.k) -*{n}(a::ModInt{n}, b::ModInt{n}) = ModInt{n}(a.k*b.k) --{n}(a::ModInt{n}) = ModInt{n}(-a.k) - -inv{n}(a::ModInt{n}) = ModInt{n}(invmod(a.k, n)) -/{n}(a::ModInt{n}, b::ModInt{n}) = a*inv(b) # broaden for non-coprime? - -Base.promote_rule{n}(::Type{ModInt{n}}, ::Type{Int}) = ModInt{n} -Base.convert{n}(::Type{ModInt{n}}, i::Int) = ModInt{n}(i) - -end # module diff --git a/julia-0.6.3/share/doc/julia/examples/bubblesort.jl b/julia-0.6.3/share/doc/julia/examples/bubblesort.jl deleted file mode 100644 index 6b7c244..0000000 --- a/julia-0.6.3/share/doc/julia/examples/bubblesort.jl +++ /dev/null @@ -1,19 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -import Base.Sort -struct BubbleSortAlg <: Sort.Algorithm end -const BubbleSort = BubbleSortAlg() - -function Base.sort!(v::AbstractVector, lo::Int, hi::Int, ::BubbleSortAlg, o::Sort.Ordering) - while true - clean = true - for i = lo:hi-1 - if Sort.lt(o, v[i+1], v[i]) - v[i+1], v[i] = v[i], v[i+1] - clean = false - end - end - clean && break - end - return v -end diff --git a/julia-0.6.3/share/doc/julia/examples/clustermanager/0mq/README b/julia-0.6.3/share/doc/julia/examples/clustermanager/0mq/README deleted file mode 100644 index c6bb2cf..0000000 --- a/julia-0.6.3/share/doc/julia/examples/clustermanager/0mq/README +++ /dev/null @@ -1,27 +0,0 @@ -This is a proof-of-concept that uses ZeroMQ as transport. -It uses a star topology as opposed to the native mesh network. - -Package ZMQ must be installed. All workers only run on localhost. - -All Julia nodes only connect to a "broker" process that listens on known ports -8100 and 8101 via ZMQ sockets. - - -All commands must be run from `examples/clustermanager/0mq` directory - -First, start the broker. In a new console type: - julia broker.jl - -This does not return. - -Next, start a Julia REPL and type: - include("ZMQCM.jl") - ZMQCM.start_master(4) # start with four workers - - -Alternatively, head.jl, a test script could be run. It just launches the requested number of workers, -executes a simple command on all of them and exits. - julia head.jl 4 - -NOTE: As stated this is a proof-of-concept. A real Julia cluster using ZMQ will probably use -different ZMQ socket types and optimize the transport. diff --git a/julia-0.6.3/share/doc/julia/examples/clustermanager/0mq/ZMQCM.jl b/julia-0.6.3/share/doc/julia/examples/clustermanager/0mq/ZMQCM.jl deleted file mode 100644 index d18e7b6..0000000 --- a/julia-0.6.3/share/doc/julia/examples/clustermanager/0mq/ZMQCM.jl +++ /dev/null @@ -1,277 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -using ZMQ - -import Base: launch, manage, connect, kill - -const BROKER_SUB_PORT = 8100 -const BROKER_PUB_PORT = 8101 - -const SELF_INITIATED = 0 -const REMOTE_INITIATED = 1 - -const PAYLOAD_MSG = "J" -const CONTROL_MSG = "Z" - -const REQUEST_ACK = "R" -const ACK_MSG = "A" -const KILL_MSG = "K" - -mutable struct ZMQCMan <: ClusterManager - map_zmq_julia::Dict{Int, Tuple} - c::Condition - isfree::Bool - ctx - pub - sub - zid_self - ZMQCMan() = new(Dict{Int, Tuple}(), Condition(), true) -end - -const manager = ZMQCMan() - -function lock_for_send() - if manager.isfree == true - manager.isfree = false - else - while manager.isfree == false - wait(manager.c) - if manager.isfree == true - manager.isfree = false - return - end - end - end -end - -function release_lock_for_send() - manager.isfree = true - notify(manager.c, all=true) -end - -function init_node(zid=0) - manager.ctx = Context(1) - pub=Socket(manager.ctx, PUB) # Outbound - connect(pub, "tcp://127.0.0.1:$BROKER_SUB_PORT") - - sub=Socket(manager.ctx, SUB) # In bound - connect(sub, "tcp://127.0.0.1:$BROKER_PUB_PORT") - ZMQ.set_subscribe(sub, string(zid)) - - manager.pub = pub - manager.sub = sub - manager.zid_self = zid - - (pub, sub) -end - -function send_data(zid, mtype, data) - lock_for_send() - ZMQ.send(manager.pub, Message(string(zid)), SNDMORE) - ZMQ.send(manager.pub, Message(string(manager.zid_self)), SNDMORE) - #println("Sending message of type $mtype to $zid") - ZMQ.send(manager.pub, Message(mtype), SNDMORE) - ZMQ.send(manager.pub, Message(data)) - release_lock_for_send() -end - -function setup_connection(zid, initiated_by) - try - read_stream=BufferStream() - write_stream=BufferStream() - - if initiated_by == REMOTE_INITIATED - test_remote = false - else - test_remote = true - end - - manager.map_zmq_julia[zid] = (read_stream, write_stream, test_remote) - - @schedule begin - while true - (r_s, w_s, do_test_remote) = manager.map_zmq_julia[zid] - if do_test_remote - send_data(zid, CONTROL_MSG, REQUEST_ACK) - sleep(0.5) - else - break - end - end - (r_s, w_s, do_test_remote) = manager.map_zmq_julia[zid] - - while true - data = readavailable(w_s) - send_data(zid, PAYLOAD_MSG, data) - end - end - (read_stream, write_stream) - catch e - Base.show_backtrace(STDOUT,catch_backtrace()) - println(e) - rethrow(e) - end -end - -# BROKER -function start_broker() - ctx=Context(1) - xpub=Socket(ctx, XPUB) - xsub=Socket(ctx, XSUB) - - ZMQ.bind(xsub, "tcp://127.0.0.1:$(BROKER_SUB_PORT)") - ZMQ.bind(xpub, "tcp://127.0.0.1:$(BROKER_PUB_PORT)") - - ccall((:zmq_proxy, :libzmq), Cint, (Ptr{Void}, Ptr{Void}, Ptr{Void}), xsub.data, xpub.data, C_NULL) -# proxy(xsub, xpub) - - # control never comes here - ZMQ.close(xpub) - ZMQ.close(xsub) - ZMQ.close(ctx) -end - -function recv_data() - try - #println("On $(manager.zid_self) waiting to recv message") - zid = parse(Int,String(ZMQ.recv(manager.sub))) - assert(zid == manager.zid_self) - - from_zid = parse(Int,String(ZMQ.recv(manager.sub))) - mtype = String(ZMQ.recv(manager.sub)) - - #println("$zid received message of type $mtype from $from_zid") - - data = ZMQ.recv(manager.sub) - if mtype == CONTROL_MSG - cmsg = String(data) - if cmsg == REQUEST_ACK - #println("$from_zid REQUESTED_ACK from $zid") - # send back a control_msg - send_data(from_zid, CONTROL_MSG, ACK_MSG) - elseif cmsg == ACK_MSG - #println("$zid got ACK_MSG from $from_zid") - (r_s, w_s, test_remote) = manager.map_zmq_julia[from_zid] - manager.map_zmq_julia[from_zid] = (r_s, w_s, false) - elseif cmsg == KILL_MSG - exit(0) - else - error("Unknown control message : ", cmsg) - end - data = "" - end - - (from_zid, data) - catch e - Base.show_backtrace(STDOUT,catch_backtrace()) - println(e) - rethrow(e) - end - -end - -# MASTER -function start_master(np) - init_node() - @schedule begin - try - while true - (from_zid, data) = recv_data() - - #println("master recv data from $from_zid") - - (r_s, w_s, t_r) = manager.map_zmq_julia[from_zid] - unsafe_write(r_s, pointer(data), length(data)) - end - catch e - Base.show_backtrace(STDOUT,catch_backtrace()) - println(e) - rethrow(e) - end - end - - addprocs(manager; np=np) -end - - -function launch(manager::ZMQCMan, params::Dict, launched::Array, c::Condition) - #println("launch $(params[:np])") - for i in 1:params[:np] - io, pobj = open(`$(params[:exename]) worker.jl $i $(Base.cluster_cookie())`, "r") - - wconfig = WorkerConfig() - wconfig.userdata = Dict(:zid=>i, :io=>io) - push!(launched, wconfig) - notify(c) - end -end - -function connect(manager::ZMQCMan, pid::Int, config::WorkerConfig) - #println("connect_m2w") - if myid() == 1 - zid = get(config.userdata)[:zid] - config.connect_at = zid # This will be useful in the worker-to-worker connection setup. - - print_worker_stdout(get(config.userdata)[:io], pid) - else - #println("connect_w2w") - zid = get(config.connect_at) - config.userdata = Dict{Symbol, Any}(:zid=>zid) - end - - streams = setup_connection(zid, SELF_INITIATED) - - udata = get(config.userdata) - udata[:streams] = streams - - streams -end - -# WORKER -function start_worker(zid, cookie) - #println("start_worker") - Base.init_worker(cookie, ZMQCMan()) - init_node(zid) - - while true - (from_zid, data) = recv_data() - - #println("worker recv data from $from_zid") - - streams = get(manager.map_zmq_julia, from_zid, nothing) - if streams === nothing - # First time.. - (r_s, w_s) = setup_connection(from_zid, REMOTE_INITIATED) - Base.process_messages(r_s, w_s) - else - (r_s, w_s, t_r) = streams - end - - unsafe_write(r_s, pointer(data), length(data)) - end -end - -function manage(manager::ZMQCMan, id::Int, config::WorkerConfig, op) - nothing -end - -function kill(manager::ZMQCMan, pid::Int, config::WorkerConfig) - send_data(get(config.userdata)[:zid], CONTROL_MSG, KILL_MSG) - (r_s, w_s) = get(config.userdata)[:streams] - close(r_s) - close(w_s) - - # remove from our map - delete!(manager.map_zmq_julia, get(config.userdata)[:zid]) - - nothing -end - - -function print_worker_stdout(io, pid) - @schedule while !eof(io) - line = readline(io) - println("\tFrom worker $(pid):\t$line") - end -end - diff --git a/julia-0.6.3/share/doc/julia/examples/clustermanager/0mq/broker.jl b/julia-0.6.3/share/doc/julia/examples/clustermanager/0mq/broker.jl deleted file mode 100644 index 87d2849..0000000 --- a/julia-0.6.3/share/doc/julia/examples/clustermanager/0mq/broker.jl +++ /dev/null @@ -1,4 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -include("ZMQCM.jl") -start_broker() diff --git a/julia-0.6.3/share/doc/julia/examples/clustermanager/0mq/head.jl b/julia-0.6.3/share/doc/julia/examples/clustermanager/0mq/head.jl deleted file mode 100644 index ff0f718..0000000 --- a/julia-0.6.3/share/doc/julia/examples/clustermanager/0mq/head.jl +++ /dev/null @@ -1,11 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -include("ZMQCM.jl") - -# @spawn run(`julia broker.jl`) - -start_master(parse(Int,ARGS[1])) - -resp = pmap(x -> myid() *2, [1:nworkers()]) - -println(resp) diff --git a/julia-0.6.3/share/doc/julia/examples/clustermanager/0mq/worker.jl b/julia-0.6.3/share/doc/julia/examples/clustermanager/0mq/worker.jl deleted file mode 100644 index bbb2ebc..0000000 --- a/julia-0.6.3/share/doc/julia/examples/clustermanager/0mq/worker.jl +++ /dev/null @@ -1,5 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -include("ZMQCM.jl") - -start_worker(parse(Int,ARGS[1]), ARGS[2]) diff --git a/julia-0.6.3/share/doc/julia/examples/clustermanager/simple/README b/julia-0.6.3/share/doc/julia/examples/clustermanager/simple/README deleted file mode 100644 index b14d069..0000000 --- a/julia-0.6.3/share/doc/julia/examples/clustermanager/simple/README +++ /dev/null @@ -1,12 +0,0 @@ -This is a simple proof-of-concept that uses UNIX domain sockets as transport. - -All commands must be run from `examples/clustermanager/simple` directory - -Start a Julia REPL and type: - include("UnixDomainCM.jl") - addprocs(UnixDomainCM(4)) # start with four workers - -Alternatively, head.jl, a test script could be run. It just launches the requested number of workers, -executes a simple command on all of them and exits. - julia head.jl 4 - diff --git a/julia-0.6.3/share/doc/julia/examples/clustermanager/simple/UnixDomainCM.jl b/julia-0.6.3/share/doc/julia/examples/clustermanager/simple/UnixDomainCM.jl deleted file mode 100644 index d1e27e2..0000000 --- a/julia-0.6.3/share/doc/julia/examples/clustermanager/simple/UnixDomainCM.jl +++ /dev/null @@ -1,92 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -import Base: launch, manage, connect, exit - -mutable struct UnixDomainCM <: ClusterManager - np::Integer -end - -function launch(manager::UnixDomainCM, params::Dict, launched::Array, c::Condition) -# println("launch $(manager.np)") - cookie = Base.cluster_cookie() - for i in 1:manager.np - sockname = tempname() - try - cmd = `$(params[:exename]) --startup-file=no $(@__FILE__) udwrkr $sockname $cookie` - io, pobj = open(cmd, "r") - - wconfig = WorkerConfig() - wconfig.userdata = Dict(:sockname=>sockname, :io=>io, :process=>pobj) - push!(launched, wconfig) - notify(c) - catch e - println(e) - end - end -end - -function connect(manager::UnixDomainCM, pid::Int, config::WorkerConfig) - if myid() == 1 -# println("connect_m2w") - config.connect_at = get(config.userdata)[:sockname] # This will be useful in the worker-to-worker connection setup. - - print_worker_stdout(get(config.userdata)[:io], pid) - else -# println("connect_w2w") - sockname = get(config.connect_at) - config.userdata = Dict{Symbol, Any}(:sockname=>sockname) - end - - t = time() - while true - try - address = get(config.userdata)[:sockname] - if isa(address, Tuple) - sock = connect(address...) - else - sock = connect(address) - end - return (sock, sock) - catch e - if (time() - t) > 30.0 - rethrow(e) - else - sleep(0.1) - end - end - end - -end - -# WORKER -function start_worker(sockname, cookie) - Base.init_worker(cookie, UnixDomainCM(0)) - - srvr = listen(sockname) - while true - sock = accept(srvr) - Base.process_messages(sock, sock) - end -end - -function manage(manager::UnixDomainCM, id::Int, config::WorkerConfig, op) - # Does not seem to be required, filesystem entry cleanup is happening automatically on process exit -# if op == :deregister -# try -# rm(get(config.userdata)[:sockname]) -# end -# end - nothing -end - -function print_worker_stdout(io, pid) - @schedule while !eof(io) - line = readline(io) - println("\tFrom worker $(pid):\t$line") - end -end - -if (length(ARGS) > 0) && (ARGS[1] == "udwrkr") - # script has been launched as a worker - start_worker(ARGS[2], ARGS[3]) -end diff --git a/julia-0.6.3/share/doc/julia/examples/clustermanager/simple/head.jl b/julia-0.6.3/share/doc/julia/examples/clustermanager/simple/head.jl deleted file mode 100644 index cb16b8e..0000000 --- a/julia-0.6.3/share/doc/julia/examples/clustermanager/simple/head.jl +++ /dev/null @@ -1,7 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -include("UnixDomainCM.jl") - -addprocs(UnixDomainCM(parse(Int,ARGS[1]))) -resp = pmap(x -> myid() *2, [1:nworkers()]) -println(resp) diff --git a/julia-0.6.3/share/doc/julia/examples/clustermanager/simple/test_simple.jl b/julia-0.6.3/share/doc/julia/examples/clustermanager/simple/test_simple.jl deleted file mode 100644 index 57e8a8a..0000000 --- a/julia-0.6.3/share/doc/julia/examples/clustermanager/simple/test_simple.jl +++ /dev/null @@ -1,12 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -cmanpath = joinpath(dirname(@__FILE__), "UnixDomainCM.jl") -include(cmanpath) - -npids = addprocs(UnixDomainCM(2)) -assert(length(npids) == 2) -test_pids = [remotecall_fetch(myid, x) for x in npids] -assert(npids == test_pids) -rmprocs(npids; waitfor=1.0) - -exit(0) diff --git a/julia-0.6.3/share/doc/julia/examples/dictchannel.jl b/julia-0.6.3/share/doc/julia/examples/dictchannel.jl deleted file mode 100644 index f1b9bfd..0000000 --- a/julia-0.6.3/share/doc/julia/examples/dictchannel.jl +++ /dev/null @@ -1,34 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -import Base: put!, wait, isready, take!, fetch - -mutable struct DictChannel <: AbstractChannel - d::Dict - cond_take::Condition # waiting for data to become available - DictChannel() = new(Dict(), Condition()) -end - -function put!(D::DictChannel, k, v) - D.d[k] = v - notify(D.cond_take) - D -end - -function take!(D::DictChannel, k) - v=fetch(D,k) - delete!(D.d, k) - v -end - -isready(D::DictChannel) = length(D.d) > 1 -isready(D::DictChannel, k) = haskey(D.d,k) -function fetch(D::DictChannel, k) - wait(D,k) - D.d[k] -end - -function wait(D::DictChannel, k) - while !isready(D, k) - wait(D.cond_take) - end -end diff --git a/julia-0.6.3/share/doc/julia/examples/embedding/.gitignore b/julia-0.6.3/share/doc/julia/examples/embedding/.gitignore deleted file mode 100644 index 4ce246e..0000000 --- a/julia-0.6.3/share/doc/julia/examples/embedding/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -/embedding -/embedding-debug diff --git a/julia-0.6.3/share/doc/julia/examples/embedding/Makefile b/julia-0.6.3/share/doc/julia/examples/embedding/Makefile deleted file mode 100644 index 38e9bc3..0000000 --- a/julia-0.6.3/share/doc/julia/examples/embedding/Makefile +++ /dev/null @@ -1,53 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -# This Makefile template requires the following variables to be set -# in the environment or on the command-line: -# JULIA: path to julia[.exe] executable -# BIN: binary build directory - -ifndef JULIA - $(error "Please pass JULIA=[path of target julia binary], or set as environment variable!") -endif -ifndef BIN - $(error "Please pass BIN=[path of build directory], or set as environment variable!") -endif - -#============================================================================= -# this source directory where embedding.c is located -SRCDIR := $(abspath $(dir $(lastword $(MAKEFILE_LIST)))) - -# get the executable suffix, if any -EXE := $(suffix $(abspath $(JULIA))) - -# get compiler and linker flags. (see: `contrib/julia-config.jl`) -JULIA_CONFIG := $(JULIA) -e 'include(joinpath(JULIA_HOME, Base.DATAROOTDIR, "julia", "julia-config.jl"))' -- -CPPFLAGS_ADD := -CFLAGS_ADD = $(shell $(JULIA_CONFIG) --cflags) -LDFLAGS_ADD = -lm $(shell $(JULIA_CONFIG) --ldflags --ldlibs) - -DEBUGFLAGS += -g - -#============================================================================= - -release: $(BIN)/embedding$(EXE) -debug: $(BIN)/embedding-debug$(EXE) - -$(BIN)/embedding$(EXE): $(SRCDIR)/embedding.c - $(CC) $^ -o $@ $(CPPFLAGS_ADD) $(CPPFLAGS) $(CFLAGS_ADD) $(CFLAGS) $(LDFLAGS_ADD) $(LDFLAGS) - -$(BIN)/embedding-debug$(EXE): $(SRCDIR)/embedding.c - $(CC) $^ -o $@ $(CPPFLAGS_ADD) $(CPPFLAGS) $(CFLAGS_ADD) $(CFLAGS) $(LDFLAGS_ADD) $(LDFLAGS) $(DEBUGFLAGS) - -check: $(BIN)/embedding$(EXE) - $(JULIA) $(SRCDIR)/embedding-test.jl $< - @echo SUCCESS - -clean: - -rm -f $(BIN)/embedding-debug$(EXE) $(BIN)/embedding$(EXE) - -.PHONY: release debug clean check - -# Makefile debugging trick: -# call print-VARIABLE to see the runtime value of any variable -print-%: - @echo '$*=$($*)' diff --git a/julia-0.6.3/share/doc/julia/examples/embedding/embedding-test.jl b/julia-0.6.3/share/doc/julia/examples/embedding/embedding-test.jl deleted file mode 100644 index 8081bdc..0000000 --- a/julia-0.6.3/share/doc/julia/examples/embedding/embedding-test.jl +++ /dev/null @@ -1,22 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -# tests the output of the embedding example is correct -using Base.Test - -@test length(ARGS) == 1 -@testset "embedding example" begin - stdout = Pipe() - stderr = Pipe() - p = spawn(pipeline(Cmd(ARGS), stdin=DevNull, stdout=stdout, stderr=stderr)) - close(stdout.in) - close(stderr.in) - stdout_task = @async readlines(stdout) - stderr = readstring(stderr) - @test stderr == "MethodError: no method matching this_function_has_no_methods()\n" - @test success(p) - lines = wait(stdout_task) - @test length(lines) == 9 - @test parse(Float64, lines[1]) ≈ sqrt(2) - @test lines[8] == "called bar" - @test lines[9] == "calling new bar" -end diff --git a/julia-0.6.3/share/doc/julia/examples/embedding/embedding.c b/julia-0.6.3/share/doc/julia/examples/embedding/embedding.c deleted file mode 100644 index a4172a1..0000000 --- a/julia-0.6.3/share/doc/julia/examples/embedding/embedding.c +++ /dev/null @@ -1,153 +0,0 @@ -// This file is a part of Julia. License is MIT: https://julialang.org/license - -#include -#include -#include - -#ifdef _OS_WINDOWS_ -__declspec(dllexport) __cdecl -#endif -double my_c_sqrt(double x) -{ - return sqrt(x); -} - -jl_value_t *checked_eval_string(const char* code) -{ - jl_value_t *result = jl_eval_string(code); - if (jl_exception_occurred()) { - // none of these allocate, so a gc-root (JL_GC_PUSH) is not necessary - jl_call2(jl_get_function(jl_base_module, "showerror"), - jl_stderr_obj(), - jl_exception_occurred()); - jl_printf(jl_stderr_stream(), "\n"); - jl_atexit_hook(1); - exit(1); - } - assert(result && "Missing return value but no exception occurred!"); - return result; -} - -int main() -{ - jl_init(); - - { - // Simple running of Julia code - - checked_eval_string("println(sqrt(2.0))"); - } - - { - // Accessing the return value - - jl_value_t *ret = checked_eval_string("sqrt(2.0)"); - double retDouble = jl_unbox_float64(ret); - printf("sqrt(2.0) in C: %e\n", retDouble); - fflush(stdout); - } - - { - // Same as above but with function handle (more flexible) - - jl_function_t *func = jl_get_function(jl_base_module, "sqrt"); - jl_value_t* argument = jl_box_float64(2.0); - jl_value_t* ret = jl_call1(func, argument); - double retDouble = jl_unbox_float64(ret); - printf("sqrt(2.0) in C: %e\n", retDouble); - fflush(stdout); - } - - { - // 1D arrays - - jl_value_t* array_type = jl_apply_array_type((jl_value_t*)jl_float64_type, 1); - jl_array_t* x = jl_alloc_array_1d(array_type, 10); - // JL_GC_PUSH* is required here to ensure that `x` is not deleted before - // (aka, is gc-rooted until) the program reaches the corresponding JL_GC_POP() - JL_GC_PUSH1(&x); - - double* xData = jl_array_data(x); - - size_t i; - for (i = 0; i < jl_array_len(x); i++) - xData[i] = i; - - jl_function_t *func = jl_get_function(jl_base_module, "reverse!"); - jl_call1(func, (jl_value_t*) x); - - printf("x = ["); - for (i = 0; i < jl_array_len(x); i++) - printf("%e ", xData[i]); - printf("]\n"); - fflush(stdout); - - JL_GC_POP(); - } - - { - // Defining a Julia function and calling it - - checked_eval_string("my_func(x) = 2 * x"); - - jl_function_t *func = jl_get_function(jl_current_module, "my_func"); - jl_value_t* arg = jl_box_float64(5.0); - double ret = jl_unbox_float64(jl_call1(func, arg)); - - printf("my_func(5.0) = %f\n", ret); - fflush(stdout); - } - - { - // Calling a C function from Julia (from C) - - // in a shared library (exported, by name) - checked_eval_string("println( ccall(:my_c_sqrt, Float64, (Float64,), 2.0) )"); - - // or via a pointer - jl_value_t *call_by_ptr = checked_eval_string( - "my_c_sqrt -> println( ccall(my_c_sqrt, Float64, (Float64,), 2.0) )"); - jl_call1(call_by_ptr, jl_box_voidpointer(my_c_sqrt)); - } - - { - // Handling exceptions gracefully - - jl_value_t *f = checked_eval_string("function this_function_has_no_methods end"); - jl_call0(f); - - if (jl_exception_occurred()) { - jl_call2(jl_get_function(jl_base_module, "showerror"), - jl_stderr_obj(), - jl_exception_occurred()); - jl_printf(jl_stderr_stream(), "\n"); - } - - } - - { - // Creating and using a native C function handle - // to a Julia function signature - - checked_eval_string( - "function bar()\n" - " println(\"called bar\")\n" - " random_return_value = 42\n" - "end"); - checked_eval_string( - "function bar_from_c()\n" - " bar()\n" - " nothing\n" - "end"); - typedef void (*Func_VOID__VOID)(void); - jl_value_t *pbar = jl_eval_string("cfunction(bar_from_c, Void, ())"); - Func_VOID__VOID bar = (Func_VOID__VOID)jl_unbox_voidpointer(pbar); - bar(); - checked_eval_string("bar() = println(\"calling new bar\")"); - bar(); - } - - int ret = 0; - jl_atexit_hook(ret); - return ret; -} diff --git a/julia-0.6.3/share/doc/julia/examples/juliatypes.jl b/julia-0.6.3/share/doc/julia/examples/juliatypes.jl deleted file mode 100644 index 09f6fc5..0000000 --- a/julia-0.6.3/share/doc/julia/examples/juliatypes.jl +++ /dev/null @@ -1,1037 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -import Base: convert, show - -abstract type Ty end - -mutable struct TypeName - name::Symbol - abs::Bool - super::Ty # actually TagT - # arity - # representation - # mutable - TypeName(name, abs, super) = new(name, abs, super) - TypeName(name, abs) = new(name, abs) -end - -show(io::IO, x::TypeName) = print(io, x.name) - -mutable struct TagT <: Ty - name::TypeName - params - vararg::Bool - TagT(n, p, v=false) = new(n, p, v) -end - -function show(io::IO, t::TagT) - print(io, t.name.name) - isempty(t.params) && return - print(io, '{') - l = length(t.params) - for i=1:l - show(io, t.params[i]) - if i == l && t.vararg - print(io, "...") - elseif i < l - print(io, ",") - end - end - print(io, '}') -end - -mutable struct BottomTy <: Ty -end - -show(io::IO, ::BottomTy) = print(io, "BottomT") - -mutable struct UnionT <: Ty - a - b - UnionT() = BottomT - UnionT(a) = a - UnionT(a, b) = new(a, b) - UnionT(a, ts...) = new(a, UnionT(ts...)) -end - -function show(io::IO, t::UnionT) - print(io, "UnionT(") - while true - show(io, t.a) - print(io, ",") - if isa(t.b, UnionT) - t = t.b - else - show(io, t.b) - break - end - end - print(io, ')') -end - -mutable struct Var - name::Symbol - lb - ub - Var(n, lb=BottomT, ub=AnyT) = new(n, lb, ub) -end - -function show_var_bounds(io::IO, v::Var) - if v.lb !== BottomT - if v.ub === AnyT - print(io, v.name) - print(io, ">:") - show(io, v.lb) - return - end - show(io, v.lb) - print(io, "<:") - end - print(io, v.name) - if v.ub !== AnyT - print(io, "<:") - show(io, v.ub) - end -end - -show(io::IO, v::Var) = print(io, v.name) - -mutable struct UnionAllT <: Ty - var::Var - T - UnionAllT(v::Var, t) = new(v, t) - UnionAllT(v::Var, t::Union{Type,Tuple}) = new(v, convert(Ty, t)) -end - -function show(io::IO, x::UnionAllT) - print(io, "(@UnionAll ") - show_var_bounds(io, x.var) - print(io, " ") - show(io, x.T) - print(io, ")") -end - - -# Any, Bottom, and Tuple - -const AnyT = TagT(TypeName(:Any,true), ()) -AnyT.name.super = AnyT - -const BottomT = BottomTy() - -const TupleName = TypeName(:Tuple,false,AnyT) -const TupleT = TagT(TupleName, (AnyT,), true) -tupletype(xs...) = inst(TupleName, xs...) -vatype(xs...) = (t = inst(TupleName, xs...); t.vararg = true; t) - - -# type application - -inst(typename::TypeName, params...) = TagT(typename, params) - -inst(t::TagT) = t - -inst(t::UnionAllT, param) = subst(t.T, Dict{Any,Any}(t.var => param)) -inst(t::UnionAllT, param, rest...) = inst(inst(t,param), rest...) - -supertype(t::TagT) = t.name===TupleName ? AnyT : inst(t.name.super, t.params...) - -extend(d::Dict, k, v) = (x = copy(d); x[k]=v; x) - -subst(t::TagT, env) = t===AnyT ? t : TagT(t.name, map(x->subst(x,env), t.params), t.vararg) -subst(t::UnionT, env) = UnionT(subst(t.a,env), subst(t.b,env)) -subst(t::Var, env) = get(env, t, t) -subst(t::UnionAllT, env) = (assert(!haskey(env, t.var)); - newVar = Var(t.var.name, subst(t.var.lb, env), subst(t.var.ub, env)); - UnionAllT(newVar, subst(t.T, extend(env, t.var, newVar)))) -subst(t, env) = t - - -# subtype - -isequal_type(x, y) = issub(x, y) && issub(y, x) - -mutable struct Bounds - # record current lower and upper bounds of a Var - # right: whether this Var is on the right-hand side of A <: B - lb - ub - right::Bool -end - -mutable struct UnionState - depth::Int # number of union decision points we're inside - more::Bool # new union found; need to grow stack - stack::Vector{Bool} # stack of decisions - UnionState() = new(1,0,Bool[]) -end - -mutable struct Env - vars::Dict{Var,Bounds} - Lunions::UnionState - Runions::UnionState - outer::Bool - Env() = new(Dict{Var,Bounds}(), UnionState(), UnionState(), true) -end - -function issub_env(x, y) - e = Env() - ans = forall_exists_issub(x, y, e) - ans, e.vars -end -issub(x, y) = issub_env(x, y)[1] -issub(x, y, env) = (x === y) -issub(x::Ty, y::Ty, env) = (x === y) || x === BottomT - -function forall_exists_issub(x, y, env) - # for all combinations of elements from Unions on the left, there must - # exist a combination of elements from Unions on the right that makes - # issub() true. Unions in invariant position are on both the left and - # the right in this formula. - sub = exists_issub(x, y, env) - - if sub && env.Lunions.more - push!(env.Lunions.stack, false) - sub = forall_exists_issub(x, y, env) - if sub - env.Lunions.stack[end] = true - sub = forall_exists_issub(x, y, env) - end - pop!(env.Lunions.stack) - end - return sub -end - -function exists_issub(x, y, env) - env.Lunions.depth = env.Runions.depth = 1 - env.Lunions.more = env.Runions.more = false - - found = issub(x, y, env) - - if env.Lunions.more - # return up to forall_exists_issub. the recursion must have this shape: - # ∀₁ ∀₁ - # ∃₁ => ∀₂ - # ... - # ∃₁ - # ∃₂ - return true - end - if env.Runions.more - push!(env.Runions.stack, false) - found = exists_issub(x, y, env) - if !found - env.Runions.stack[end] = true - found = exists_issub(x, y, env) - end - pop!(env.Runions.stack) - end - return found -end - -function issub_union(t, u::UnionT, env, R, state::UnionState) - env.outer = false - if state.depth > length(state.stack) - # indicate that stack needs to grow - state.more = true - return true - end - ui = state.stack[state.depth]; state.depth += 1 - choice = getfield(u, 1+ui) - return R ? issub(t, choice, env) : issub(choice, t, env) -end - -issub(a::UnionT, b::UnionT, env) = a === b || issub_union(a, b, env, true, env.Runions) -issub(a::UnionT, b::Ty, env) = b===AnyT || issub_union(b, a, env, false, env.Lunions) -issub(a::Ty, b::UnionT, env) = - a===BottomT || a===b.a || a===b.b || issub_union(a, b, env, true, env.Runions) - -# handle vars before unions -issub(a::UnionT, b::Var, env) = var_gt(b, a, env) -issub(a::Var, b::UnionT, env) = var_lt(a, b, env) - -function issub(a::TagT, b::TagT, env) - env.outer = false - a === b && return true - b === AnyT && return true - a === AnyT && return false - if a.name !== b.name - return issub(supertype(a), b, env) - end - if a.name === TupleName - va, vb = a.vararg, b.vararg - la, lb = length(a.params), length(b.params) - ai = bi = 1 - while ai <= la - bi > lb && return false - !issub(a.params[ai], b.params[bi], env) && return false - ai += 1 - if bi < lb || !vb - bi += 1 - end - end - return (la==lb && va==vb) || (vb && (la >= (va ? lb : lb-1))) - end - for i = 1:length(a.params) - ai, bi = a.params[i], b.params[i] - # use issub in both directions to test equality - if !(ai===bi || (issub(ai, bi, env) && issub(bi, ai, env))) - return false - end - end - return true -end - -function join(a,b) - (a===BottomT || b===AnyT || a === b) && return b - (b===BottomT || a===AnyT) && return a - UnionT(a,b) -end - -issub(a::Ty, b::Var, env) = var_gt(b, a, env) -issub(a::Var, b::Ty, env) = var_lt(a, b, env) -function issub(a::Var, b::Var, env) - env.outer = false - a === b && return true - aa = env.vars[a]; bb = env.vars[b] - if aa.right - # this is a bit odd, but seems necessary to make this case work: - # (@UnionAll x<:T<:x RefT{RefT{T}}) == RefT{@UnionAll x<:T<:x RefT{T}} - bb.right && return issub(bb.ub, bb.lb, env) - return var_lt(a, b, env) - else - if !bb.right # check ∀a,b . a<:b - # the bounds of left-side variables never change, and can only lead - # to other left-side variables, so using || here is safe. - return issub(aa.ub, b, env) || issub(a, bb.lb, env) - end - return var_gt(b, a, env) - end -end - -# issub, but taking apart unions before handling vars -issub_ufirst(a::UnionT, b::Var, env) = issub_union(b, a, env, false, env.Lunions) -issub_ufirst(a::Var, b::UnionT, env) = a===b.a || a===b.b || issub_union(a, b, env, true, env.Runions) -issub_ufirst(a, b, env) = issub(a, b, env) - -function var_lt(b::Var, a::Union{Ty,Var}, env) - env.outer = false - bb = env.vars[b] - #println("$b($(bb.lb),$(bb.ub)) <: $a") - !bb.right && return issub_ufirst(bb.ub, a, env) # check ∀b . b<:a - !issub_ufirst(bb.lb, a, env) && return false - # for contravariance we would need to compute a meet here, but - # because of invariance bb.ub ⊓ a == a here always. however for this - # to work we need to compute issub(left,right) before issub(right,left), - # since otherwise the issub(a, bb.ub) check in var_gt becomes vacuous. - bb.ub = a # meet(bb.ub, a) - return true -end - -function var_gt(b::Var, a::Union{Ty,Var}, env) - env.outer = false - bb = env.vars[b] - #println("$b($(bb.lb),$(bb.ub)) >: $a") - !bb.right && return issub_ufirst(a, bb.lb, env) # check ∀b . b>:a - !issub_ufirst(a, bb.ub, env) && return false - bb.lb = join(bb.lb, a) - return true -end - -function rename(t::UnionAllT) - v = Var(t.var.name, t.var.lb, t.var.ub) - UnionAllT(v, inst(t,v)) -end - -function issub_unionall(t::Ty, u::UnionAllT, env, R) - outer = env.outer - haskey(env.vars, u.var) && (u = rename(u)) - env.vars[u.var] = Bounds(u.var.lb, u.var.ub, R) - ans = R ? issub(t, u.T, env) : issub(u.T, t, env) - !outer && delete!(env.vars, u.var) - return ans -end - -issub(a::UnionAllT, b::UnionAllT, env) = a === b || issub_unionall(a, b, env, true) -issub(a::UnionT, b::UnionAllT, env) = issub_unionall(a, b, env, true) -issub(a::UnionAllT, b::UnionT, env) = issub_unionall(b, a, env, false) -issub(a::Ty, b::UnionAllT, env) = a === BottomT || issub_unionall(a, b, env, true) -issub(a::UnionAllT, b::Ty, env) = b === AnyT || issub_unionall(b, a, env, false) - - -# convenient syntax - -macro UnionAll(var, expr) - lb = :BottomT - ub = :AnyT - if isa(var,Expr) && var.head === :comparison - if length(var.args) == 3 - v = var.args[1] - if var.args[2] == :(<:) - ub = esc(var.args[3]) - elseif var.args[2] == :(>:) - lb = esc(var.args[3]) - else - error("invalid bounds in UnionAll") - end - elseif length(var.args) == 5 - v = var.args[3] - if var.args[2] == var.args[4] == :(<:) - lb = esc(var.args[1]) - ub = esc(var.args[5]) - else - error("invalid bounds in UnionAll") - end - else - error("invalid bounds in UnionAll") - end - elseif isa(var,Expr) && var.head === :(<:) - v = var.args[1] - ub = esc(var.args[2]) - elseif isa(var,Expr) && var.head === :(>:) - v = var.args[1] - lb = esc(var.args[2]) - elseif !isa(var,Symbol) - error("invalid variable in UnionAll") - else - v = var - end - quote - let $(esc(v)) = Var($(Expr(:quote,v)), $lb, $ub) - UnionAllT($(esc(v)), $(esc(expr))) - end - end -end - - -# translating from existing julia types - -const tndict = ObjectIdDict() - -xlate(t) = xlate(t, ObjectIdDict()) - -xlate(t, env) = t - -function xlate(t::Union, env) - if t === Union{} - return BottomT - end - UnionT(map(x->xlate(x,env), t.types)...) -end - -function xlate(t::Tuple, env) - if length(t) == 0 - return inst(TupleName) - end - va = Base.isvarargtype(t[end]) - ts = map(x->(Base.isvarargtype(x) ? xlate(x.parameters[1],env) : xlate(x,env)), t) - tnew = inst(TupleName, ts...) - tnew.vararg = va - tnew -end - -function xlate(t::TypeVar, env) - if haskey(env, t) - return env[t] - end - v = Var(t.name, xlate(t.lb,env), xlate(t.ub,env)) - env[t] = v - v -end - -function xlate(t::DataType, env) - if t === Any - return AnyT - elseif t <: Tuple - return xlate((t.parameters...,), env) - elseif !haskey(tndict,t.name) - para = map(x->xlate(x,env), t.name.primary.parameters) # adds tvars to env - sup = xlate(t.name.primary.super, env) - for i = length(para):-1:1 - sup = UnionAllT(para[i], sup) - end - tn = TypeName(t.name.name, t.abstract, sup) - tndict[t.name] = tn - else - tn = tndict[t.name] - end - inst(tn, map(x->xlate(x,env), t.parameters)...) -end - -convert(::Type{Ty}, t::Union{Type,Tuple}) = xlate(t) -convert(::Type{Ty}, t::TypeVar) = xlate(t) - -issub(a::Union{Type,Tuple}, b::Union{Type,Tuple}) = issub(xlate(a), xlate(b)) -issub(a::Ty , b::Union{Type,Tuple}) = issub(a , xlate(b)) -issub(a::Union{Type,Tuple}, b::Ty ) = issub(xlate(a), b) -issub_env(a::Union{Type,Tuple}, b::Union{Type,Tuple}) = issub_env(xlate(a), xlate(b)) -issub_env(a::Ty , b::Union{Type,Tuple}) = issub_env(a , xlate(b)) -issub_env(a::Union{Type,Tuple}, b::Ty ) = issub_env(xlate(a), b) - -tt(ts...) = Tuple{ts...} -vt(ts...) = Tuple{ts[1:end-1]..., Vararg{ts[end]}} - -# tests - -AbstractArrayT = - let AbstractArrayName = TypeName(:AbstractArray, true, @UnionAll T @UnionAll N AnyT) - @UnionAll T @UnionAll N inst(AbstractArrayName, T, N) - end - -ArrayT = - let ArrayName = TypeName(:Array, false, @UnionAll T @UnionAll N inst(AbstractArrayT, T, N)) - @UnionAll T @UnionAll N inst(ArrayName, T, N) - end - -PairT = let PairName = TypeName(:Pair, false, @UnionAll A @UnionAll B AnyT) - @UnionAll A @UnionAll B inst(PairName, A, B) -end - -RefT = let RefName = TypeName(:Ref, false, @UnionAll T AnyT) - @UnionAll T inst(RefName, T) -end - -tndict[AbstractArray.name] = AbstractArrayT.T.T.name -tndict[Array.name] = ArrayT.T.T.name -tndict[Pair.name] = PairT.T.T.name - -using Base.Test - -issub_strict(x,y) = issub(x,y) && !issub(y,x) - -# level 1: no varags, union, UnionAll -function test_1() - @test issub_strict(Int, Integer) - @test issub_strict(Array{Int,1}, AbstractArray{Int,1}) - - @test isequal_type(Int, Int) - @test isequal_type(Integer, Integer) - @test isequal_type(Array{Int,1}, Array{Int,1}) - @test isequal_type(AbstractArray{Int,1}, AbstractArray{Int,1}) - - @test issub_strict((Int,Int), (Integer,Integer)) - @test issub_strict((Array{Int,1},), (AbstractArray{Int,1},)) - - @test isequal_type((Integer,Integer), (Integer,Integer)) - - @test !issub((Int,Int), (Int,)) - @test !issub((Int,), (Integer,Integer)) -end - -# level 2: varargs -function test_2() - @test issub_strict((Int,Int), vt(Int,)) - @test issub_strict((Int,Int), vt(Int,Int,)) - @test issub_strict((Int,Int), vt(Int,Integer,)) - @test issub_strict((Int,Int), vt(Int,Int,Integer,)) - @test issub_strict(vt(Int,Int), vt(Int,)) - @test issub_strict(vt(Int,Int,Int), vt(Int,)) - @test issub_strict(vt(Int,Int,Int), vt(Integer,Int,)) - @test issub_strict(vt(Int,), vt(Any,)) - @test issub_strict((), vt(Any,)) - - @test isequal_type(vt(Int,), vt(Int,)) - @test isequal_type(vt(Integer,), vt(Integer,)) - - @test !issub((), vt(Int, Int)) - @test !issub((Int,), vt(Int, Int, Int)) - - @test !issub((Int, (Real, Integer)), vt(Int)) -end - -function test_no_diagonal() - # from test_3 - @test issub((@UnionAll T @UnionAll S tupletype(T,S)), (@UnionAll T tupletype(T,T))) - - @test isequal_type((@UnionAll T tupletype(T,T)), (@UnionAll T @UnionAll S tupletype(T,S))) - - @test issub(tupletype(inst(ArrayT,Ty(Integer),1), Ty(Int)), - (@UnionAll T<:Ty(Integer) tupletype(inst(ArrayT,T,1),T))) - - @test issub(Ty((Int,AbstractString,Vector{Any})), - @UnionAll T tupletype(T, T, inst(ArrayT,T,1))) - - @test isequal_type(Ty(Array{Tuple{Integer,Integer},1}), - inst(ArrayT, (@UnionAll T<:Ty(Integer) tupletype(T,T)), 1)) - - @test issub(Ty((Float32,Array{Real,1})), - @UnionAll T<:Ty(Real) @UnionAll S<:inst(AbstractArrayT,T,1) tupletype(T,S)) - - @test isequal_type((@UnionAll T tupletype(inst(RefT,T), T)), - (@UnionAll T @UnionAll S<:T tupletype(inst(RefT,T),S))) - @test isequal_type((@UnionAll T tupletype(inst(RefT,T), T)), - (@UnionAll T @UnionAll S<:T @UnionAll R<:S tupletype(inst(RefT,T),R))) - - @test issub((@UnionAll S<:Ty(Int) (@UnionAll R<:Ty(AbstractString) tupletype(S,R,Ty(Vector{Any})))), - (@UnionAll T tupletype(T, T, inst(ArrayT,T,1)))) -end - -# level 3: UnionAll -function test_3() - @test issub_strict(Ty(Array{Int,1}), @UnionAll T inst(ArrayT, T, 1)) - @test issub_strict((@UnionAll T inst(PairT,T,T)), (@UnionAll T @UnionAll S inst(PairT,T,S))) - @test issub(inst(PairT,Ty(Int),Ty(Int8)), (@UnionAll T @UnionAll S inst(PairT,T,S))) - @test issub(inst(PairT,Ty(Int),Ty(Int8)), (@UnionAll S inst(PairT,Ty(Int),S))) - - @test !issub((@UnionAll T<:Ty(Real) T), (@UnionAll T<:Ty(Integer) T)) - - # diagonal - #@test issub_strict((@UnionAll T tupletype(T,T)), (@UnionAll T @UnionAll S tupletype(T,S))) - @test issub((@UnionAll T tupletype(T,T)), (@UnionAll T @UnionAll S tupletype(T,S))) - @test isequal_type((@UnionAll T tupletype(T,T)), (@UnionAll R tupletype(R,R))) - # diagonal - #@test !issub(tupletype(Ty(Real),Ty(Real)), @UnionAll T<:Ty(Real) tupletype(T,T)) - - @test !issub((@UnionAll T<:Ty(Integer) @UnionAll S<:Ty(Number) (T,S)), - (@UnionAll T<:Ty(Integer) @UnionAll S<:Ty(Number) (S,T))) - - AUA = inst(ArrayT, (@UnionAll T inst(ArrayT,T,1)), 1) - UAA = (@UnionAll T inst(ArrayT, inst(ArrayT,T,1), 1)) - - @test !issub(AUA, UAA) - @test !issub(UAA, AUA) - @test !isequal_type(AUA, UAA) - - @test issub_strict((@UnionAll T Int), (@UnionAll T<:Ty(Integer) Integer)) - - @test isequal_type((@UnionAll T @UnionAll S tupletype(T, tupletype(S))), - (@UnionAll T tupletype(T, @UnionAll S tupletype(S)))) - - @test !issub((@UnionAll T inst(PairT,T,T)), inst(PairT,Ty(Int),Ty(Int8))) - @test !issub((@UnionAll T inst(PairT,T,T)), inst(PairT,Ty(Int),Ty(Int))) - - @test isequal_type((@UnionAll T tupletype(T)), tupletype(AnyT)) - @test isequal_type((@UnionAll T<:Ty(Real) tupletype(T)), tupletype(Ty(Real))) - - #@test !issub(tupletype(inst(ArrayT,Ty(Integer),1), Ty(Int)), - # (@UnionAll T<:Ty(Integer) tupletype(inst(ArrayT,T,1),T))) - @test issub(tupletype(inst(ArrayT,Ty(Integer),1), Ty(Int)), - (@UnionAll T<:Ty(Integer) @UnionAll S<:T tupletype(inst(ArrayT,T,1),S))) - - @test !issub(tupletype(inst(ArrayT,Ty(Integer),1), Ty(Real)), - (@UnionAll T<:Ty(Integer) tupletype(inst(ArrayT,T,1),T))) - - @test !issub(Ty((Int,AbstractString,Vector{Integer})), - @UnionAll T tupletype(T, T, inst(ArrayT,T,1))) - @test !issub(Ty((AbstractString,Int,Vector{Integer})), - @UnionAll T tupletype(T, T, inst(ArrayT,T,1))) - @test !issub(Ty((Int,AbstractString,Vector{Tuple{Integer}})), - @UnionAll T tupletype(T,T,inst(ArrayT,tupletype(T),1))) - - #@test !issub(Ty((Int,AbstractString,Vector{Any})), - # @UnionAll T tupletype(T, T, inst(ArrayT,T,1))) - - @test isequal_type(Ty(Array{Int,1}), inst(ArrayT, (@UnionAll T<:Ty(Int) T), 1)) - @test isequal_type(Ty(Array{Tuple{Any},1}), inst(ArrayT, (@UnionAll T tupletype(T)), 1)) - - @test isequal_type(Ty(Array{Tuple{Int,Int},1}), - inst(ArrayT, (@UnionAll T<:Ty(Int) tupletype(T,T)), 1)) - @test !issub(Ty(Array{Tuple{Int,Integer},1}), - inst(ArrayT, (@UnionAll T<:Ty(Integer) tupletype(T,T)), 1)) - - - @test !issub(inst(PairT,Ty(Int),Ty(Int8)), (@UnionAll T inst(PairT,T,T))) - - @test !issub(tupletype(inst(ArrayT,Ty(Int),1), Ty(Integer)), - (@UnionAll T<:Ty(Integer) tupletype(inst(ArrayT,T,1),T))) - - @test !issub(tupletype(Ty(Integer), inst(ArrayT,Ty(Int),1)), - (@UnionAll T<:Ty(Integer) tupletype(T, inst(ArrayT,T,1)))) - - @test !issub(Ty(Array{Array{Int,1},Integer}), - (@UnionAll T inst(ArrayT,inst(ArrayT,T,1),T))) - - @test issub(Ty(Array{Array{Int,1},Int}), - (@UnionAll T inst(ArrayT,inst(ArrayT,T,1),T))) - - @test issub(Ty((Integer,Int)), @UnionAll T<:Ty(Integer) @UnionAll S<:T tupletype(T,S)) - @test !issub(Ty((Integer,Int)), @UnionAll T<:Ty(Int) @UnionAll S<:T tupletype(T,S)) - @test !issub(Ty((Integer,Int)), @UnionAll T<:Ty(AbstractString) @UnionAll S<:T tupletype(T,S)) - - @test issub(Ty((Float32,Array{Float32,1})), - @UnionAll T<:Ty(Real) @UnionAll S<:inst(AbstractArrayT,T,1) tupletype(T,S)) - - @test !issub(Ty((Float32,Array{Float64,1})), - @UnionAll T<:Ty(Real) @UnionAll S<:inst(AbstractArrayT,T,1) tupletype(T,S)) - - #@test !issub(Ty((Float32,Array{Real,1})), - # @UnionAll T<:Ty(Real) @UnionAll S<:inst(AbstractArrayT,T,1) tupletype(T,S)) - - @test !issub(Ty((Number,Array{Real,1})), - @UnionAll T<:Ty(Real) @UnionAll S<:inst(AbstractArrayT,T,1) tupletype(T,S)) - - @test issub((@UnionAll Ty(Int)<:T<:Ty(Integer) T), @UnionAll T<:Ty(Real) T) - @test issub((@UnionAll Ty(Int)<:T<:Ty(Integer) inst(ArrayT,T,1)), - (@UnionAll T<:Ty(Real) inst(ArrayT,T,1))) - - @test issub((@UnionAll Ty(Int)<:T<:Ty(Integer) T), - (@UnionAll Ty(Integer)<:T<:Ty(Real) T)) - @test !issub((@UnionAll Ty(Int)<:T<:Ty(Integer) inst(ArrayT,T,1)), - (@UnionAll Ty(Integer)<:T<:Ty(Real) inst(ArrayT,T,1))) - - X = (@UnionAll T<:Ty(Real) @UnionAll S<:inst(AbstractArrayT,T,1) tupletype(T,S)) - Y = (@UnionAll A<:Ty(Real) @UnionAll B<:inst(AbstractArrayT,A,1) tupletype(A,B)) - @test isequal_type(X,Y) - Z = (@UnionAll A<:Ty(Real) @UnionAll B<:inst(AbstractArrayT,A,1) tupletype(Ty(Real),B)) - @test issub_strict(X,Z) - - @test issub_strict((@UnionAll T @UnionAll S<:T inst(PairT,T,S)), - (@UnionAll T @UnionAll S inst(PairT,T,S))) - @test issub_strict((@UnionAll T @UnionAll S>:T inst(PairT,T,S)), - (@UnionAll T @UnionAll S inst(PairT,T,S))) - - #@test issub_strict((@UnionAll T tupletype(inst(RefT,T), T)), - # (@UnionAll T @UnionAll S<:T tupletype(inst(RefT,T),S))) - #@test issub_strict((@UnionAll T tupletype(inst(RefT,T), T)), - # (@UnionAll T @UnionAll S<:T @UnionAll R<:S tupletype(inst(RefT,T),R))) - @test isequal_type((@UnionAll T tupletype(inst(RefT,T), T)), - (@UnionAll T @UnionAll T<:S<:T tupletype(inst(RefT,T),S))) - @test issub_strict((@UnionAll T tupletype(inst(RefT,T), T)), - (@UnionAll T @UnionAll S>:T tupletype(inst(RefT,T),S))) -end - -# level 4: Union -function test_4() - @test isequal_type(UnionT(BottomT,BottomT), BottomT) - - @test issub_strict(Int, Union{Int,AbstractString}) - @test issub_strict(Union{Int,Int8}, Integer) - - @test isequal_type(Union{Int,Int8}, Union{Int,Int8}) - - @test isequal_type(UnionT(Ty(Int),Ty(Integer)), Ty(Integer)) - - @test isequal_type(tt(Union{Int,Int8},Int16), Union{tt(Int,Int16),tt(Int8,Int16)}) - - @test issub_strict((Int,Int8,Int), vt(Union{Int,Int8},)) - @test issub_strict((Int,Int8,Int), vt(Union{Int,Int8,Int16},)) - - # nested unions - @test !issub(UnionT(Ty(Int),inst(RefT,UnionT(Ty(Int),Ty(Int8)))), - UnionT(Ty(Int),inst(RefT,UnionT(Ty(Int8),Ty(Int16))))) - - A = Ty(Int); B = Ty(Int8) - C = Ty(Int16); D = Ty(Int32) - @test issub(UnionT(UnionT(A,UnionT(A,UnionT(B,C))), UnionT(D,BottomT)), - UnionT(UnionT(A,B),UnionT(C,UnionT(B,D)))) - @test !issub(UnionT(UnionT(A,UnionT(A,UnionT(B,C))), UnionT(D,BottomT)), - UnionT(UnionT(A,B),UnionT(C,UnionT(B,A)))) - - @test isequal_type(UnionT(UnionT(A,B,C), UnionT(D)), UnionT(A,B,C,D)) - @test isequal_type(UnionT(UnionT(A,B,C), UnionT(D)), UnionT(A,UnionT(B,C),D)) - @test isequal_type(UnionT(UnionT(UnionT(UnionT(A)),B,C), UnionT(D)), - UnionT(A,UnionT(B,C),D)) - - @test issub_strict(UnionT(UnionT(A,C), UnionT(D)), UnionT(A,B,C,D)) - - @test !issub(UnionT(UnionT(A,B,C), UnionT(D)), UnionT(A,C,D)) - - # obviously these unions can be simplified, but when they aren't there's trouble - X = UnionT(UnionT(A,B,C),UnionT(A,B,C),UnionT(A,B,C),UnionT(A,B,C), - UnionT(A,B,C),UnionT(A,B,C),UnionT(A,B,C),UnionT(A,B,C)) - Y = UnionT(UnionT(D,B,C),UnionT(D,B,C),UnionT(D,B,C),UnionT(D,B,C), - UnionT(D,B,C),UnionT(D,B,C),UnionT(D,B,C),UnionT(A,B,C)) - @test issub_strict(X,Y) -end - -# level 5: union and UnionAll -function test_5() - u = Ty(Union{Int8,Int}) - - @test issub(Ty((AbstractString,Array{Int,1})), - (@UnionAll T UnionT(tupletype(T,inst(ArrayT,T,1)), - tupletype(T,inst(ArrayT,Ty(Int),1))))) - - @test issub(Ty((Union{Vector{Int},Vector{Int8}},)), - @UnionAll T tupletype(inst(ArrayT,T,1),)) - - @test !issub(Ty((Union{Vector{Int},Vector{Int8}},Vector{Int})), - @UnionAll T tupletype(inst(ArrayT,T,1), inst(ArrayT,T,1))) - - @test !issub(Ty((Union{Vector{Int},Vector{Int8}},Vector{Int8})), - @UnionAll T tupletype(inst(ArrayT,T,1), inst(ArrayT,T,1))) - - @test !issub(Ty(Vector{Int}), @UnionAll T>:u inst(ArrayT,T,1)) - @test issub(Ty(Vector{Integer}), @UnionAll T>:u inst(ArrayT,T,1)) - @test issub(Ty(Vector{Union{Int,Int8}}), @UnionAll T>:u inst(ArrayT,T,1)) - - @test issub((@UnionAll Ty(Int)<:T<:u inst(ArrayT,T,1)), - (@UnionAll Ty(Int)<:T<:u inst(ArrayT,T,1))) - - # with varargs - @test !issub(inst(ArrayT,tupletype(inst(ArrayT,Ty(Int)),inst(ArrayT,Ty(Vector{Int16})),inst(ArrayT,Ty(Vector{Int})),inst(ArrayT,Ty(Int)))), - @UnionAll T<:(@UnionAll S vatype(UnionT(inst(ArrayT,S),inst(ArrayT,inst(ArrayT,S,1))))) inst(ArrayT,T)) - - @test issub(inst(ArrayT,tupletype(inst(ArrayT,Ty(Int)),inst(ArrayT,Ty(Vector{Int})),inst(ArrayT,Ty(Vector{Int})),inst(ArrayT,Ty(Int)))), - @UnionAll T<:(@UnionAll S vatype(UnionT(inst(ArrayT,S),inst(ArrayT,inst(ArrayT,S,1))))) inst(ArrayT,T)) - - @test !issub(tupletype(inst(ArrayT,Ty(Int)),inst(ArrayT,Ty(Vector{Int16})),inst(ArrayT,Ty(Vector{Int})),inst(ArrayT,Ty(Int))), - @UnionAll S vatype(UnionT(inst(ArrayT,S),inst(ArrayT,inst(ArrayT,S,1))))) - - @test issub(tupletype(inst(ArrayT,Ty(Int)),inst(ArrayT,Ty(Vector{Int})),inst(ArrayT,Ty(Vector{Int})),inst(ArrayT,Ty(Int))), - @UnionAll S vatype(UnionT(inst(ArrayT,S),inst(ArrayT,inst(ArrayT,S,1))))) - - B = @UnionAll S<:u tupletype(S, tupletype(AnyT,AnyT,AnyT), inst(RefT,S)) - # these tests require renaming in issub_unionall - @test issub((@UnionAll T<:B tupletype(Ty(Int8), T, inst(RefT,Ty(Int8)))), B) - @test !issub((@UnionAll T<:B tupletype(Ty(Int8), T, inst(RefT,T))), B) - - # the `convert(Type{T},T)` pattern, where T is a Union - # required changing priority of unions and vars - @test issub(tupletype(inst(ArrayT,u,1),Ty(Int)), - @UnionAll T tupletype(inst(ArrayT,T,1), T)) - @test issub(tupletype(inst(ArrayT,u,1),Ty(Int)), - @UnionAll T @UnionAll S<:T tupletype(inst(ArrayT,T,1), S)) -end - -# tricky type variable lower bounds -function test_6() - # diagonal - #@test !issub((@UnionAll S<:Ty(Int) (@UnionAll R<:Ty(AbstractString) tupletype(S,R,Ty(Vector{Any})))), - # (@UnionAll T tupletype(T, T, inst(ArrayT,T,1)))) - @test issub((@UnionAll S<:Ty(Int) (@UnionAll R<:Ty(AbstractString) tupletype(S,R,Ty(Vector{Any})))), - (@UnionAll T tupletype(T, T, inst(ArrayT,T,1)))) - - @test !issub((@UnionAll S<:Ty(Int) (@UnionAll R<:Ty(AbstractString) tupletype(S,R,Ty(Vector{Integer})))), - (@UnionAll T tupletype(T, T, inst(ArrayT,T,1)))) - - t = @UnionAll T tupletype(T,T,inst(RefT,T)) - @test isequal_type(t, rename(t)) - - @test !issub((@UnionAll T tupletype(T,Ty(AbstractString),inst(RefT,T))), - (@UnionAll T tupletype(T,T,inst(RefT,T)))) - - @test !issub((@UnionAll T tupletype(T,inst(RefT,T),Ty(AbstractString))), - (@UnionAll T tupletype(T,inst(RefT,T),T))) - - i = Ty(Int); ai = Ty(Integer) - @test isequal_type((@UnionAll i<:T<:i inst(RefT,T)), inst(RefT,i)) - @test isequal_type((@UnionAll ai<:T<:ai inst(RefT,T)), inst(RefT,ai)) - - # Pair{T,S} <: Pair{T,T} can be true with certain bounds - @test issub_strict((@UnionAll i<:T<:i @UnionAll i<:S<:i inst(PairT,T,S)), - @UnionAll T inst(PairT,T,T)) - - @test issub_strict(tupletype(i, inst(RefT,i)), - (@UnionAll T @UnionAll S<:T tupletype(S,inst(RefT,T)))) - - @test !issub(tupletype(Ty(Real), inst(RefT,i)), - (@UnionAll T @UnionAll S<:T tupletype(S,inst(RefT,T)))) - - # S >: T - @test issub_strict(tupletype(Ty(Real), inst(RefT,i)), - (@UnionAll T @UnionAll S>:T tupletype(S,inst(RefT,T)))) - - @test !issub(tupletype(inst(RefT,i), inst(RefT,ai)), - (@UnionAll T @UnionAll S>:T tupletype(inst(RefT,S),inst(RefT,T)))) - - @test issub_strict(tupletype(inst(RefT,Ty(Real)), inst(RefT,ai)), - (@UnionAll T @UnionAll S>:T tupletype(inst(RefT,S),inst(RefT,T)))) - - - @test issub_strict(tupletype(Ty(Real), inst(RefT,tupletype(i))), - (@UnionAll T @UnionAll S>:T tupletype(S,inst(RefT,tupletype(T))))) - - @test !issub(tupletype(inst(RefT,tupletype(i)), inst(RefT,tupletype(ai))), - (@UnionAll T @UnionAll S>:T tupletype(inst(RefT,tupletype(S)),inst(RefT,tupletype(T))))) - - @test issub_strict(tupletype(inst(RefT,tupletype(Ty(Real))), inst(RefT,tupletype(ai))), - (@UnionAll T @UnionAll S>:T tupletype(inst(RefT,tupletype(S)),inst(RefT,tupletype(T))))) - - # (@UnionAll x<:T<:x Q{T}) == Q{x} - @test isequal_type(inst(RefT,inst(RefT,i)), - inst(RefT,@UnionAll i<:T<:i inst(RefT,T))) - @test isequal_type((@UnionAll i<:T<:i inst(RefT,inst(RefT,T))), - inst(RefT,@UnionAll i<:T<:i inst(RefT,T))) - @test !issub((@UnionAll i<:T<:i inst(RefT,inst(RefT,T))), - inst(RefT,@UnionAll T<:i inst(RefT,T))) - - u = Ty(Union{Int8,Int64}) - A = inst(RefT,BottomT) - B = @UnionAll S<:u inst(RefT,S) - @test issub(inst(RefT,B), @UnionAll A<:T<:B inst(RefT,T)) - - C = @UnionAll S<:u S - @test issub(inst(RefT,C), @UnionAll u<:T<:u inst(RefT,T)) - - BB = @UnionAll S<:BottomT S - @test issub(inst(RefT,B), @UnionAll BB<:U<:B inst(RefT,U)) -end - -# tests that don't pass yet -function test_failing() - # TODO: S <: Array{T} cases -end - -function test_all() - test_1() - test_2() - test_no_diagonal() - test_3() - test_4() - test_5() - test_6() - test_failing() -end - -const menagerie = - Any[BottomT, AnyT, Ty(Int), Ty(Int8), Ty(Integer), Ty(Real), - Ty(Array{Int,1}), Ty(AbstractArray{Int,1}), - Ty(vt(Int,Integer,)), Ty(vt(Integer,Int,)), Ty(()), - Ty(Union{Int,Int8}), - (@UnionAll T inst(ArrayT, T, 1)), - (@UnionAll T inst(PairT,T,T)), - (@UnionAll T @UnionAll S inst(PairT,T,S)), - inst(PairT,Ty(Int),Ty(Int8)), - (@UnionAll S inst(PairT,Ty(Int),S)), - (@UnionAll T tupletype(T,T)), - (@UnionAll T<:Ty(Integer) tupletype(T,T)), - (@UnionAll T @UnionAll S tupletype(T,S)), - (@UnionAll T<:Ty(Integer) @UnionAll S<:Ty(Number) (T,S)), - (@UnionAll T<:Ty(Integer) @UnionAll S<:Ty(Number) (S,T)), - inst(ArrayT, (@UnionAll T inst(ArrayT,T,1)), 1), - (@UnionAll T inst(ArrayT, inst(ArrayT,T,1), 1)), - inst(ArrayT, (@UnionAll T<:Ty(Int) T), 1), - (@UnionAll T<:Ty(Real) @UnionAll S<:inst(AbstractArrayT,T,1) tupletype(T,S)), - UnionT(Ty(Int),inst(RefT,UnionT(Ty(Int),Ty(Int8)))), - (@UnionAll T UnionT(tupletype(T,inst(ArrayT,T,1)), - tupletype(T,inst(ArrayT,Ty(Int),1)))), - ] - -let new = Any[] - # add variants of each type - for T in menagerie - push!(new, inst(RefT, T)) - push!(new, tupletype(T)) - push!(new, tupletype(T,T)) - push!(new, vatype(T)) - push!(new, @UnionAll S<:T S) - push!(new, @UnionAll S<:T inst(RefT,S)) - end - append!(menagerie, new) -end - -function test_properties() - x→y = !x || y - ¬T = @UnionAll X>:T inst(RefT,X) - - for T in menagerie - # top and bottom identities - @test issub(BottomT, T) - @test issub(T, AnyT) - @test issub(T, BottomT) → isequal_type(T, BottomT) - @test issub(AnyT, T) → isequal_type(T, AnyT) - - # unionall identity - @test isequal_type(T, @UnionAll S<:T S) - @test isequal_type(inst(RefT,T), @UnionAll T<:U<:T inst(RefT,U)) - - # equality under renaming - if isa(T, UnionAllT) - @test isequal_type(T, rename(T)) - end - - # inequality under wrapping - @test !isequal_type(T, inst(RefT,T)) - - for S in menagerie - issubTS = issub(T, S) - # transitivity - if issubTS - for R in menagerie - if issub(S, R) - if !issub(T, R) - @show T - @show S - @show R - end - @test issub(T, R) # issub(S, R) → issub(T, R) - @test issub(inst(RefT,S), @UnionAll T<:U<:R inst(RefT,U)) - end - end - end - - # union subsumption - @test isequal_type(T, UnionT(T,S)) → issub(S, T) - - # invariance - @test isequal_type(T, S) == isequal_type(inst(RefT,T), inst(RefT,S)) - - # covariance - @test issubTS == issub(tupletype(T), tupletype(S)) - @test issubTS == issub(vatype(T), vatype(S)) - @test issubTS == issub(tupletype(T), vatype(S)) - - # contravariance - @test issubTS == issub(¬S, ¬T) - end - end -end - -# function non_terminating_F() -# # undecidable F_<: instance -# ¬T = @ForAll α<:T α -# θ = @ForAll α ¬(@ForAll β<:α ¬β) -# a₀ = Var(:a₀, BottomT, θ) -# issub(a₀, (@ForAll a₁<:a₀ ¬a₁)) -# end - -# attempt to implement non-terminating example from -# "On the Decidability of Subtyping with Bounded Existential Types" -function non_terminating_2() - C = let CName = TypeName(:C, false, @UnionAll T AnyT) - @UnionAll T inst(CName, T) - end - D = let DName = TypeName(:D, false, @UnionAll T AnyT) - @UnionAll T inst(DName, T) - end - ¬T = @UnionAll X>:T inst(D,X) - U = AnyT - X = Var(:X, BottomT, ¬U) - e = Env() - e.vars[X] = Bounds(BottomT, ¬U, false) - issub(X, ¬inst(C,X), e) -end - -#= -Replacing type S with a union over var T(ᶜ)<:S can affect the subtype -relation in all possible ways: - - (C{Real},C{Real}) < @U T<:Real (C{T},C{T}) - (Real,Real) = @U T<:Real (T,T) - - (C{Real},C{Real}) ! @U Tᶜ<:Real (C{T},C{T}) (*) # neither <= nor >= - (Real,Real) > @U Tᶜ<:Real (T,T) - - (C{Real},) < @U T<:Real (C{T},) - (Real,) = @U T<:Real (T,) - (C{Real},) ! @U Tᶜ<:Real (C{T},) (*) - (Real,) = @U Tᶜ<:Real (T,) - -cases (*) are probably not needed in practice. - - -transform all covariant occurrences of non-concrete types to -vars: (Real,Real) => @U T<:Real @U S<:Real (T,S) -and then treat all vars as invariant. -this can maybe even be done on the fly without actually making the -UnionAll types up-front. -in fact this may only need to be done on the left. -which implies right away that the algorithm works as-is if the left -side is a concrete type. - -possible explanation: - -1. match all tvars with invariant rule -2. imagine left side is concrete -3. therefore all (right-) vars will have to equal concrete types - (this completes the base case) -4. inductive hypothesis: tvars match concrete types -5. "build up" an abstract type on the left over the initial concrete type -6. handle all abstract types T in covariant position on the left by treating - them as variables V<:T instead -7. by the inductive hypothesis tvars continue to match concrete types - -it seems you need to plug in the isconcrete predicate in step 6. - -=# diff --git a/julia-0.6.3/share/doc/julia/examples/lru.jl b/julia-0.6.3/share/doc/julia/examples/lru.jl deleted file mode 100644 index 7fa54ff..0000000 --- a/julia-0.6.3/share/doc/julia/examples/lru.jl +++ /dev/null @@ -1,130 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -module LRUExample -# An LRU (Least Recently Used) cache is an associative data structure which -# maintains its contents in an order such that the most recently used item -# is at the beginning of the structure, and the least recently used at the end. -# -# This file specifies two types of LRU caches, both with and without a size -# limit. BoundedLRU has a limit and evicts the LRU item if a new item is added -# after that bound is reached. UnboundedLRU does not have a maximum size, but -# can be used as a basis for more complex LRUs. -# -# LRUs should follow the interfaces for general collections, indexable -# collections, and associative collections. - -# The standard implementation of an LRU backs a hash table with a doubly-linked -# list for O(1) operations when reordering on access and eviction. The Julia -# implementation instead backs the table with a Vector. For moderately-sized -# collections, the difference in performance is small, and this implmentation -# is simpler and easier to understand. - -import Base.isempty, Base.length, Base.sizeof -import Base.start, Base.next, Base.done -import Base.haskey, Base.get -import Base.setindex!, Base.getindex, Base.delete!, Base.empty! -import Base.show - -abstract type LRU{K,V} <: Associative{K,V} end - -# Default cache size -const __MAXCACHE = 1024 - -mutable struct CacheItem{K,V} - k::K - v::V -end - -mutable struct UnboundedLRU{K,V} <: LRU{K,V} - ht::Dict - q::Vector{CacheItem} - - UnboundedLRU{K,V}() where {K,V} = new(Dict(), similar(Array{CacheItem}(1), 0)) -end -UnboundedLRU() = UnboundedLRU{Any, Any}() - -mutable struct BoundedLRU{K,V} <: LRU{K,V} - ht::Dict - q::Vector{CacheItem} - maxsize::Int - - BoundedLRU{K,V}(m) where {K,V} = new(Dict(), similar(Array{CacheItem}(1), 0), m) - BoundedLRU{K,V}() where {K,V} = BoundedLRU(__MAXCACHE) -end -BoundedLRU(m) = BoundedLRU{Any, Any}(m) -BoundedLRU() = BoundedLRU{Any, Any}() - -## collections ## - -isempty(lru::LRU) = isempty(lru.q) -length(lru::LRU) = length(lru.q) - -## associative ## - -# Should this check count as an access? -haskey(lru::LRU, key) = haskey(lru.ht, key) - -get(lru::LRU, key, default) = haskey(lru, key) ? lru[key] : default - -function empty!(lru::LRU) - empty!(lru.ht) - empty!(lru.q) -end - - -show(io::IO, lru::UnboundedLRU) = print(io,"UnboundedLRU()") -show(io::IO, lru::BoundedLRU) = print(io,"BoundedLRU($(lru.maxsize))") - -## indexable ## - -# Method to do the second, slow lookup in the list with early return. -function locate(q, x) - for i = 1:length(q) - if q[i] == x - return i - end - end - error("Item not found.") -end - -function getindex(lru::LRU, key) - item = lru.ht[key] - idx = locate(lru.q, item) - splice!(lru.q, idx) - unshift!(lru.q, item) - item.v -end - -function setindex!(lru::LRU, v, key) - if haskey(lru, key) - item = lru.ht[key] - idx = locate(lru.q, item) - item.v = v - splice!(lru.q, idx) - else - item = CacheItem(key, v) - lru.ht[key] = item - end - unshift!(lru.q, item) -end - -# Eviction -function setindex!{V,K}(lru::BoundedLRU, v::V, key::K) - invoke(setindex!, Tuple{LRU,V,K}, lru, v, key) - nrm = length(lru) - lru.maxsize - for i in 1:nrm - rm = pop!(lru.q) - delete!(lru.ht, rm.k) - end -end - -## associative ## - -function delete!(lru::LRU, key) - item = lru.ht[key] - idx = locate(lru.q, item) - delete!(lru.ht, key) - delete!(lru.q, idx) -end - -end # module diff --git a/julia-0.6.3/share/doc/julia/examples/lru_test.jl b/julia-0.6.3/share/doc/julia/examples/lru_test.jl deleted file mode 100644 index 3370220..0000000 --- a/julia-0.6.3/share/doc/julia/examples/lru_test.jl +++ /dev/null @@ -1,47 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -using .LRUExample - -TestLRU = LRUExample.UnboundedLRU{String, String}() -TestBLRU = LRUExample.BoundedLRU{String, String}(1000) - -get_str(i) = String(vcat(map(x->[x>>4; x&0x0F], reinterpret(UInt8, [Int32(i)]))...)) - -isbounded{L<:LRUExample.LRU}(::Type{L}) = any(map(n->n==:maxsize, fieldnames(L))) -isbounded{L<:LRUExample.LRU}(l::L) = isbounded(L) - -nmax = round.(Int, logspace(2, 5, 4)) - -function lrutest() - #println("LRU consistency tests") - for lru in (TestLRU,TestBLRU) - for n in nmax - empty!(lru) - #@printf(" %s, %d items\n", lru, n) - #print(" Simple eviction: ") - for i in 1:n - str = get_str(i) - lru[str] = str - @assert lru.q[1].v == str - if isbounded(lru) && length(lru) >= lru.maxsize - tailstr = get_str(i-lru.maxsize+1) - @assert lru.q[end].v == tailstr - end - end - #println("pass") - - #print(" Lookup, random access: ") - for i in 1:n - str = get_str(rand(1:n)) - if haskey(lru, str) # the bounded LRUs can have cache misses - blah = lru[str] - @assert lru.q[1].v == blah - end - end - #println("pass") - end - empty!(lru) - end -end - -lrutest() diff --git a/julia-0.6.3/share/doc/julia/examples/ndgrid.jl b/julia-0.6.3/share/doc/julia/examples/ndgrid.jl deleted file mode 100644 index 3bce2fc..0000000 --- a/julia-0.6.3/share/doc/julia/examples/ndgrid.jl +++ /dev/null @@ -1,52 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -ndgrid(v::AbstractVector) = copy(v) - -function ndgrid{T}(v1::AbstractVector{T}, v2::AbstractVector{T}) - m, n = length(v1), length(v2) - v1 = reshape(v1, m, 1) - v2 = reshape(v2, 1, n) - (repmat(v1, 1, n), repmat(v2, m, 1)) -end - -function ndgrid_fill(a, v, s, snext) - for j = 1:length(a) - a[j] = v[div(rem(j-1, snext), s)+1] - end -end - -function ndgrid{T}(vs::AbstractVector{T}...) - n = length(vs) - sz = map(length, vs) - out = ntuple(i->Array{T}(sz), n) - s = 1 - for i=1:n - a = out[i]::Array - v = vs[i] - snext = s*size(a,i) - ndgrid_fill(a, v, s, snext) - s = snext - end - out -end - -meshgrid(v::AbstractVector) = meshgrid(v, v) - -function meshgrid{T}(vx::AbstractVector{T}, vy::AbstractVector{T}) - m, n = length(vy), length(vx) - vx = reshape(vx, 1, n) - vy = reshape(vy, m, 1) - (repmat(vx, m, 1), repmat(vy, 1, n)) -end - -function meshgrid{T}(vx::AbstractVector{T}, vy::AbstractVector{T}, - vz::AbstractVector{T}) - m, n, o = length(vy), length(vx), length(vz) - vx = reshape(vx, 1, n, 1) - vy = reshape(vy, m, 1, 1) - vz = reshape(vz, 1, 1, o) - om = ones(Int, m) - on = ones(Int, n) - oo = ones(Int, o) - (vx[om, :, oo], vy[:, on, oo], vz[om, on, :]) -end diff --git a/julia-0.6.3/share/doc/julia/examples/queens.jl b/julia-0.6.3/share/doc/julia/examples/queens.jl deleted file mode 100644 index e44e2fd..0000000 --- a/julia-0.6.3/share/doc/julia/examples/queens.jl +++ /dev/null @@ -1,28 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -# n-queens (nqueens) solver, for nsquaresx-by-nsquaresy board - -struct Queen - x::Int - y::Int -end -hitshorz(queena, queenb) = queena.x == queenb.x -hitsvert(queena, queenb) = queena.y == queenb.y -hitsdiag(queena, queenb) = abs(queena.x - queenb.x) == abs(queena.y - queenb.y) -hitshvd(qa, qb) = hitshorz(qa, qb) || hitsvert(qa, qb) || hitsdiag(qa, qb) -hitsany(testqueen, queens) = any(q -> hitshvd(testqueen, q), queens) - -function trysolve(nsquaresx, nsquaresy, nqueens, presqueens = ()) - nqueens == 0 && return presqueens - for xsquare in 1:nsquaresx - for ysquare in 1:nsquaresy - testqueen = Queen(xsquare, ysquare) - if !hitsany(testqueen, presqueens) - tryqueens = (presqueens..., testqueen) - maybesol = trysolve(nsquaresx, nsquaresy, nqueens - 1, tryqueens) - maybesol !== nothing && return maybesol - end - end - end - return nothing -end diff --git a/julia-0.6.3/share/doc/julia/examples/quine.jl b/julia-0.6.3/share/doc/julia/examples/quine.jl deleted file mode 100644 index aae47e3..0000000 --- a/julia-0.6.3/share/doc/julia/examples/quine.jl +++ /dev/null @@ -1,4 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -x="println(\"# This file is a part of Julia. License is MIT: https://julialang.org/license\\n\\nx=\$(repr(x))\\n\$x\")" -println("# This file is a part of Julia. License is MIT: https://julialang.org/license\n\nx=$(repr(x))\n$x") diff --git a/julia-0.6.3/share/doc/julia/examples/staged.jl b/julia-0.6.3/share/doc/julia/examples/staged.jl deleted file mode 100644 index 5b14f1d..0000000 --- a/julia-0.6.3/share/doc/julia/examples/staged.jl +++ /dev/null @@ -1,61 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -function add_method(gf, an, at, body) - argexs = [Expr(Symbol("::"), an[i], at[i]) for i=1:length(an)] - def = quote - let __F__=($gf) - function __F__($(argexs...)) - $body - end - end - end - eval(def) -end - -macro staged(fdef) - if !isa(fdef,Expr) || fdef.head !== :function - error("@staged: expected method definition") - end - fname = fdef.args[1].args[1] - argspec = fdef.args[1].args[2:end] - argnames = map(x->(isa(x,Expr) ? x.args[1] : x), argspec) - qargnames = map(x->Expr(:quote,x), argnames) - fbody = fdef.args[2] - @gensym gengf argtypes expander genbody - quote - let ($gengf) - global ($fname) # should be "outer" - local ($expander) - function ($expander)($(argnames...)) - $fbody - end - ($gengf)() = 0 # should be initially empty GF - function ($fname)($(argspec...)) - ($argtypes) = typeof(tuple($(argnames...))) - if !method_exists($gengf, $argtypes) - ($genbody) = apply(($expander), ($argtypes)) - add_method($gengf, Any[$(qargnames...)], - $argtypes, $genbody) - end - return ($gengf)($(argnames...)) - end - end - end -end - -# example - -@staged function nloops(dims::Tuple) - names = map(x->gensym(), dims) - ex = quote - println([$(names...)]) - end - for i = 1:length(dims) - ex = quote - for $(names[i]) in dims[$i] - $ex - end - end - end - ex -end diff --git a/julia-0.6.3/share/doc/julia/examples/time.jl b/julia-0.6.3/share/doc/julia/examples/time.jl deleted file mode 100644 index 45bd30f..0000000 --- a/julia-0.6.3/share/doc/julia/examples/time.jl +++ /dev/null @@ -1,45 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -module Time -export TimeDelta - -import Base.show, Base.+, Base.-, Base.convert, Base.promote_rule - -struct TimeDelta{p} - v::Int64 -end - -const PREFIXES = [ - "yocto", "zepto", "atto", "femto", "pico", "nano", "micro", "milli", - "", "kilo", "mega", "giga", "tera", "peta", "exa", "zetta", "yotta", -] -const ZERO_INDEX = 9 -const MAX_INDEX = 17 - -function show{p}(io::IO, x::TimeDelta{p}) - k = max(1,min(MAX_INDEX,fld(p,3)+ZERO_INDEX)) - r = p-3(k-ZERO_INDEX) - prefix = PREFIXES[k] - if r == 0 - s = x.v == 1 ? "" : "s" - print(io, "$(x.v) $(prefix)second$s") - elseif r > 0 - print(io, "$(x.v*10^r) $(prefix)seconds") - else - print(io, "$(x.v/10^-r) $(prefix)seconds") - end -end - -convert{p,q}(::Type{TimeDelta{p}}, x::TimeDelta{q}) = - TimeDelta{p}(p <= q ? x.v*10^(q-p) : div(x.v,10^(p-q))) - -promote_rule{p,q}(::Type{TimeDelta{p}}, ::Type{TimeDelta{q}}) = TimeDelta{min(p,q)} - --{p}(x::TimeDelta{p}) = TimeDelta{p}(-x.v) -+{p}(x::TimeDelta{p}, y::TimeDelta{p}) = TimeDelta{p}(x.v+y.v) --{p}(x::TimeDelta{p}, y::TimeDelta{p}) = TimeDelta{p}(x.v-y.v) - -+(x::TimeDelta, y::TimeDelta) = +(promote(x,y)...) --(x::TimeDelta, y::TimeDelta) = -(promote(x,y)...) - -end # module diff --git a/julia-0.6.3/share/doc/julia/examples/typetree.jl b/julia-0.6.3/share/doc/julia/examples/typetree.jl deleted file mode 100644 index 1ca8714..0000000 --- a/julia-0.6.3/share/doc/julia/examples/typetree.jl +++ /dev/null @@ -1,154 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -module TypeTrees -## -# Generate a text graphic of Julia modules type tree -## - -struct Binding - mod::Module - sym::Symbol -end -Binding(tn::TypeName) = Binding(tn.module, tn.name) -Base.isless(a::Binding, b::Binding) = isless(a.sym, b.sym) - -# The node type holds the type of the current node and a dict of subtypes -struct TTNode - typ # ::Type - subtypes::Dict{Binding, TTNode} - - TTNode(t::ANY) = new(t, Dict{Binding, TTNode}()) -end - -# Add a node to a dict if not added -function add_ttnode(subtypes::Dict{Binding, TTNode}, sname::Binding, tnode::TTNode) - return get!(subtypes, sname, tnode) -end - -function add_ttnode(subtypes::Dict{Binding, TTNode}, sname::Binding, t::Type) - return get!(subtypes, sname, TTNode(t)) -end - -# Store a type and its type hierarchy chain -# Recurse till we reach the top level type -function store_type(sname::Binding, t::Union) - suptype = Union - tnode = TTNode(t) - - # store unions under Union type - subtypes = store_type(Binding(suptype.name), suptype) - add_ttnode(subtypes, sname, tnode) - store_union(sname, tnode, t) - - # unions are also in a sense related to the types of their components - - return tnode.subtypes -end -function store_union(sname::Binding, tnode::TTNode, t::ANY) - t = Base.unwrap_unionall(t) - if isa(t, Union) - store_union(sname, tnode, t.a) - store_union(sname, tnode, t.b) - elseif isa(t, DataType) - binding = Binding(t.name) - subtypes = store_type(binding, t) - add_ttnode(subtypes, sname, tnode) - end - nothing -end - -function store_type(sname::Binding, t::UnionAll) - suptype = Base.unwrap_unionall(t) - binding = isa(suptype, DataType) ? Binding(suptype.name) : Binding(Main, string(suptype::Union)) - subtypes = store_type(binding, suptype) - tnode = add_ttnode(subtypes, sname, t) - return tnode.subtypes -end - -function store_type(sname::Binding, t::DataType) - suptype = supertype(t) - subtypes = (suptype != t) ? store_type(Binding(suptype.name), suptype) : types_tree - tnode = add_ttnode(subtypes, sname, t) - return tnode.subtypes -end - -# examine all symbols in module and store those that are types -function store_all_from(m::Module) - for s in names(m, true) - if isdefined(m, s) && !Base.isdeprecated(m, s) - t = getfield(m, s) - if isa(t, Type) && t !== Union{} - store_type(Binding(m, s), t) - elseif isa(t, Module) && module_name(t) === s && module_parent(t) === m && t !== m - store_all_from(t) - end - end - end -end - -type_props(typ) = "" -type_props(typ::DataType) = string("<<", - typ.abstract ? " abstract" : " concrete", - typ.mutable ? " mutable" : " immutable", - typ.layout != C_NULL ? string( - Base.datatype_pointerfree(typ) ? " pointerfree" : "", - Base.datatype_haspadding(typ) ? " haspadding" : "", - " nfields:", Core.nfields(typ), - " size:", typ.size, - ", align:", Base.datatype_alignment(typ)) : "", - " >>") - -function print_tree(subtypes::Dict{Binding, TTNode}, pfx::String="") - for b in sort!(collect(keys(subtypes))) - v = subtypes[b] - ishidden = unsafe_load(Base.unsafe_convert(Ptr{UInt8}, b.sym)) == UInt8('#') - if ishidden && supertype(v.typ) === Function - continue - end - if b.mod === Main - n = string(b.sym) - elseif !isa(v.typ, DataType) || v.typ.name.module != b.mod || v.typ.name.name != b.sym - n_io = IOBuffer() - print(n_io, b.mod, '.', b.sym) - ua = v.typ - if isa(ua, UnionAll) - print(n_io, "{") - while true - print(n_io, ua.var) - ua = ua.body - if isa(ua, UnionAll) - print(n_io, ", ") - else - break - end - end - print(n_io, "}") - end - n = String(take!(n_io)) - else - n = string(v.typ) - end - if n == string(v.typ) - println(pfx, "+- ", n, " ", type_props(v.typ)) - else - println(pfx, "+- ", n, " = ", v.typ, " ", type_props(v.typ)) - end - v.typ === Function && println(pfx, ". ## hiding implicit Function subtypes ##") - print_tree(v.subtypes, pfx * ". ") - end -end - - -# TODO: optionally take module names in command line -# TODO: option to list subtrees of type tree, or other symbol types -const types_tree = Dict{Binding, TTNode}() - -store_all_from(Main) - -# print_tree(types_tree) - -end # module - -if !isinteractive() - TypeTrees.print_tree(TypeTrees.types_tree) -end diff --git a/julia-0.6.3/share/doc/julia/examples/wordcount.jl b/julia-0.6.3/share/doc/julia/examples/wordcount.jl deleted file mode 100644 index 2011c88..0000000 --- a/julia-0.6.3/share/doc/julia/examples/wordcount.jl +++ /dev/null @@ -1,86 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -# wordcount.jl -# -# Implementation of parallelized "word-count" of a text, inspired by the -# Hadoop WordCount example. Uses @spawn and fetch() to parallelize -# the "map" task. Reduce is currently done single-threaded. -# -# To run in parallel on a string stored in variable `text`: -# julia -p -# julia> require("/examples/wordcount.jl") -# julia> ...(define text)... -# julia> counts=parallel_wordcount(text) -# -# Or to run on a group of files, writing results to an output file: -# julia -p -# julia> require("/examples/wordcount.jl") -# julia> wordcount_files("/tmp/output.txt", "/tmp/input1.txt","/tmp/input2.txt",...) - -# "Map" function. -# Takes a string. Returns a Dict with the number of times each word -# appears in that string. -function wordcount(text) - words=split(text,[' ','\n','\t','-','.',',',':',';'];keep=false) - counts=Dict() - for w = words - counts[w]=get(counts,w,0)+1 - end - return counts -end - -# "Reduce" function. -# Takes a collection of Dicts in the format returned by wordcount() -# Returns a Dict in which words that appear in multiple inputs -# have their totals added together. -function wcreduce(wcs) - counts=Dict() - for c in wcs, (k,v) in c - counts[k] = get(counts,k,0)+v - end - return counts -end - -# Splits input string into nprocs() equal-sized chunks (last one rounds up), -# and @spawns wordcount() for each chunk to run in parallel. Then fetch()s -# results and performs wcreduce(). -function parallel_wordcount(text) - lines=split(text,'\n';keep=false) - np=nprocs() - unitsize=ceil(length(lines)/np) - wcounts=[] - rrefs=[] - # spawn procs - for i=1:np - first=unitsize*(i-1)+1 - last=unitsize*i - if last>length(lines) - last=length(lines) - end - subtext=join(lines[Int(first):Int(last)],"\n") - push!(rrefs, @spawn wordcount( subtext ) ) - end - # fetch results - while length(rrefs)>0 - push!(wcounts,fetch(pop!(rrefs))) - end - # reduce - count=wcreduce(wcounts) - return count -end - -# Takes the name of a result file, and a list of input file names. -# Combines the contents of all files, then performs a parallel_wordcount -# on the resulting string. Writes the results to result_file. -function wordcount_files(result_file,inputs...) - text = "" - for file in inputs - text *= readstring(file) - end - wc = parallel_wordcount(text) - open(result_file,"w") do f - for (k,v) in wc - println(f, k,"=",v) - end - end -end diff --git a/julia-0.6.3/share/doc/julia/html/en/assets/arrow.svg b/julia-0.6.3/share/doc/julia/html/en/assets/arrow.svg deleted file mode 100644 index ee2798d..0000000 --- a/julia-0.6.3/share/doc/julia/html/en/assets/arrow.svg +++ /dev/null @@ -1,63 +0,0 @@ - - - - - - - - - - image/svg+xml - - - - - - - - - diff --git a/julia-0.6.3/share/doc/julia/html/en/assets/documenter.css b/julia-0.6.3/share/doc/julia/html/en/assets/documenter.css deleted file mode 100644 index 26c8166..0000000 --- a/julia-0.6.3/share/doc/julia/html/en/assets/documenter.css +++ /dev/null @@ -1,573 +0,0 @@ -/* - * The default CSS style for Documenter.jl generated sites - * - * Heavily inspired by the Julia Sphinx theme - * https://github.com/JuliaLang/JuliaDoc - * which extends the sphinx_rtd_theme - * https://github.com/snide/sphinx_rtd_theme - * - * Part of Documenter.jl - * https://github.com/JuliaDocs/Documenter.jl - * - * License: MIT - */ - -/* fonts */ -body, input { - font-family: 'Lato', 'Helvetica Neue', Arial, sans-serif; - font-size: 16px; - color: #222; - text-rendering: optimizeLegibility; -} - -pre, code, kbd { - font-family: 'Roboto Mono', Monaco, courier, monospace; - font-size: 0.90em; -} - -pre code { - font-size: 1em; -} - -a { - color: #2980b9; - text-decoration: none; -} - -a:hover { - color: #3091d1; -} - -a:visited { - color: #9b59b6; -} - -body { - line-height: 1.5; -} - -h1 { - font-size: 1.75em; -} - -/* Unless the

the is very first thing on the page (i.e. the second element - * in the
, * after the
, we add some additional styling to it - * to make it stand out a bit more. This way we get a reasonable fallback if CSS3 - * selectors are not supported in the browser. - */ -article > h1:not(:nth-child(2)) { - margin: 2.5em 0 0; - padding-bottom: 0.30em; - border-bottom: 1px solid #e5e5e5; -} -h2 { - font-size: 1.50em; - margin: 2.3em 0 0; - padding-bottom: 0.25em; - border-bottom: 1px solid #e5e5e5; -} -h3 { - font-size: 1.25em; - margin: 2.0em 0 0; -} -h4 { font-size: 1.15em; } -h5 { font-size: 1.10em; } -h6 { font-size: 1em; } - -h4, h5, h6 { - margin-top: 1.5em; - margin-bottom: 1em; -} - -img { - max-width: 100%; -} - -table { - border-collapse: collapse; - margin: 1em 0; -} - -th, td { - border: 1px solid #e1e4e5; - padding: 0.5em 1em; -} - -th { - border-bottom-width: 2px; -} - -tr:nth-child(even) { - background-color: #f3f6f6; -} - -hr { - border: 0; - border-top: 1px solid #e5e5e5; -} - -/* Inline code and code blocks */ - -code { - padding: 0.1em; - background-color: rgba(0,0,0,.04); - border-radius: 3px; -} - -pre { - background-color: #f5f5f5; - border: 1px solid #dddddd; - border-radius: 3px; - padding: 0.5em; - overflow: auto; -} - -pre code { - padding: 0; - background-color: initial; -} - -kbd { - font-size: 0.70em; - display: inline-block; - padding: 0.1em 0.5em 0.4em 0.5em; - line-height: 1.0em; - color: #444d56; - vertical-align: middle; - background-color: #fafbfc; - border: solid 1px #c6cbd1; - border-bottom-color: #959da5; - border-radius: 3px; - box-shadow: inset 0 -1px 0 #959da5; -} - -/* Headers in admonitions and docstrings */ -.admonition h1, -article section.docstring h1 { - font-size: 1.25em; -} - -.admonition h2, -article section.docstring h2 { - font-size: 1.10em; -} - -.admonition h3, -.admonition h4, -.admonition h5, -.admonition h6, -article section.docstring h3, -article section.docstring h4, -article section.docstring h5, -article section.docstring h6 { - font-size: 1em; -} - -/* Navigation */ -nav.toc { - position: fixed; - top: 0; - left: 0; - bottom: 0; - width: 20em; - overflow-y: auto; - padding: 1em 0; - background-color: #fcfcfc; - box-shadow: inset -14px 0px 5px -12px rgb(210,210,210); -} - -nav.toc .logo { - margin: 0 auto; - display: block; - max-height: 6em; - max-width: 18em; -} - -nav.toc h1 { - text-align: center; - margin-top: .57em; - margin-bottom: 0; -} - -nav.toc select { - display: block; - height: 2em; - padding: 0 1.6em 0 1em; - min-width: 7em; - max-width: 90%; - max-width: calc(100% - 5em); - margin: 0 auto; - font-size: .83em; - border: 1px solid #c9c9c9; - border-radius: 1em; - - /* TODO: doesn't seem to be centered on Safari */ - text-align: center; - text-align-last: center; - - appearance: none; - -moz-appearance: none; - -webkit-appearance: none; - - background: white url("arrow.svg"); - background-size: 1.155em; - background-repeat: no-repeat; - background-position: right; -} - -nav.toc select:hover { - border: 1px solid #a0a0a0; -} - -nav.toc select option { - text-align: center; -} - -nav.toc input { - display: block; - height: 2em; - width: 90%; - width: calc(100% - 5em); - margin: 1.2em auto; - padding: 0 1em; - border: 1px solid #c9c9c9; - border-radius: 1em; - font-size: .83em; -} - -nav.toc > ul * { - margin: 0; -} - -nav.toc ul { - color: #404040; - padding: 0; - list-style: none; -} - -nav.toc ul .toctext { - color: inherit; - display: block; -} - -nav.toc ul a:hover { - color: #fcfcfc; - background-color: #4e4a4a; -} - -nav.toc ul.internal a { - color: inherit; - display: block; -} - -nav.toc ul.internal a:hover { - background-color: #d6d6d6; -} - -nav.toc ul.internal { - background-color: #e3e3e3; - box-shadow: inset -14px 0px 5px -12px rgb(210,210,210); - list-style: none; -} - -nav.toc ul.internal li.toplevel { - border-top: 1px solid #909090; - font-weight: bold; -} - -nav.toc ul.internal li.toplevel:first-child { - border-top: none; -} - -nav.toc .toctext { - padding-top: 0.3em; - padding-bottom: 0.3em; - padding-right: 1em; -} - -nav.toc ul .toctext { - padding-left: 1em; -} - -nav.toc ul ul .toctext { - padding-left: 2em; -} - -nav.toc ul ul ul .toctext { - padding-left: 3em; -} - -nav.toc li.current > .toctext { - border-top: 1px solid #c9c9c9; - border-bottom: 1px solid #c9c9c9; - color: #404040; - font-weight: bold; - background-color: white; -} - -article { - margin-left: 20em; - min-width: 20em; - max-width: 48em; - padding: 2em; -} - -article > header {} - -article > header div#topbar { - display: none; -} - -article > header nav ul { - display: inline-block; - list-style: none; - margin: 0; - padding: 0; -} - -article > header nav li { - display: inline-block; - padding-right: 0.2em; -} - -article > header nav li:before { - content: "»"; - padding-right: 0.2em; -} - -article > header .edit-page { - float: right; -} - -article > footer {} - -article > footer a.prev { - float: left; -} -article > footer a.next { - float: right; -} - -article > footer a .direction:after { - content: ": "; -} - -article hr { - margin: 1em 0; -} - -article section.docstring { - border: 1px solid #ddd; - margin: 0.5em 0; - padding: 0.5em; - border-radius: 3px; -} - -article section.docstring .docstring-header { - margin-bottom: 1em; -} - -article section.docstring .docstring-binding { - color: #333; - font-weight: bold; -} - -article section.docstring .docstring-category { - font-style: italic; -} - -article section.docstring a.source-link { - display: block; - font-weight: bold; -} - -.nav-anchor, -.nav-anchor:hover, -.nav-anchor:visited { - color: #333; -} - -/* - * Admonitions - * - * Colors (title, body) - * warning: #f0b37e #ffedcc (orange) - * note: #6ab0de #e7f2fa (blue) - * tip: #1abc9c #dbfaf4 (green) -*/ -.admonition { - border-radius: 3px; - background-color: #eeeeee; -} - -.admonition-title { - border-radius: 3px 3px 0 0; - background-color: #9b9b9b; - padding: 0.15em 0.5em; -} - -.admonition-text { - padding: 0.5em; -} - -.admonition-text > :first-child { - margin-top: 0; -} - -.admonition-text > :last-child { - margin-bottom: 0; -} - -.admonition > .admonition-title:before { - font-family: "FontAwesome"; - margin-right: 5px; - content: "\f06a"; -} - -.admonition.warning > .admonition-title { - background-color: #f0b37e; -} - -.admonition.warning { - background-color: #ffedcc; -} - -.admonition.note > .admonition-title { - background-color: #6ab0de; -} - -.admonition.note { - background-color: #e7f2fa; -} - -.admonition.tip > .admonition-title { - background-color: #1abc9c; -} - -.admonition.tip { - background-color: #dbfaf4; -} - - -/* footnotes */ -.footnote { - padding-left: 0.8em; - border-left: 2px solid #ccc; -} - -/* Search page */ -#search-results .category { - font-size: smaller; -} - -/* Overriding the block style of highligh.js. - * We have to override the padding and the background-color, since we style this - * part ourselves. Specifically, we style the
 surrounding the , while
- * highlight.js applies the .hljs style directly to the  tag.
- */
-.hljs {
-    background-color: transparent;
-    padding: 0;
-}
-
-@media only screen and (max-width: 768px) {
-    nav.toc {
-        position: fixed;
-        overflow-y: scroll;
-        width: 16em;
-        left: -16em;
-        -webkit-overflow-scrolling: touch;
-        -webkit-transition-property: left; /* Safari */
-        -webkit-transition-duration: 0.3s; /* Safari */
-        transition-property: left;
-        transition-duration: 0.3s;
-        -webkit-transition-timing-function: ease-out; /* Safari */
-        transition-timing-function: ease-out;
-        z-index: 2;
-    }
-
-    nav.toc.show {
-        left: 0;
-    }
-
-    article {
-        margin-left: 0;
-        padding: 3em 0.9em 0 0.9em; /* top right bottom left */
-        overflow-wrap: break-word;
-    }
-
-    article > header {
-        position: fixed;
-        left: 0;
-        z-index: 1;
-    }
-
-    article > header nav, hr {
-        display: none;
-    }
-
-    article > header div#topbar {
-        display: block; /* is mobile */
-        position: fixed;
-        width: 100%;
-        height: 1.5em;
-        padding-top: 1em;
-        padding-bottom: 1em;
-        background-color: #fcfcfc;
-        box-shadow: 0 1px 3px rgba(0,0,0,.26);
-        top: 0;
-        -webkit-transition-property: top; /* Safari */
-        -webkit-transition-duration: 0.3s; /* Safari */
-        transition-property: top;
-        transition-duration: 0.3s;
-    }
-
-    article > header div#topbar.headroom--unpinned.headroom--not-top.headroom--not-bottom {
-        top: -4em;
-        -webkit-transition-property: top; /* Safari */
-        -webkit-transition-duration: 0.7s; /* Safari */
-        transition-property: top;
-        transition-duration: 0.7s;
-    }
-
-    article > header div#topbar span {
-        position: fixed;
-        width: 80%;
-        height: 1.5em;
-        margin-top: -0.1em;
-        margin-left: 0.9em;
-        font-size: 1.2em;
-        overflow: hidden;
-    }
-
-    article > header div#topbar a.fa-bars {
-        float: right;
-        padding: 0.6em;
-        margin-top: -0.6em;
-        margin-right: 0.3em;
-        font-size: 1.5em;
-    }
-
-    article > header div#topbar a.fa-bars:visited {
-        color: #3091d1;
-    }
-
-    article table {
-        overflow-x: auto;
-        display: block;
-    }
-
-    article div.MathJax_Display {
-        overflow: scroll;
-    }
-
-    article span.MathJax {
-        overflow: hidden;
-    }
-}
-
-@media only screen and (max-width: 320px) {
-    body {
-        font-size: 15px;
-    }
-}
diff --git a/julia-0.6.3/share/doc/julia/html/en/assets/documenter.js b/julia-0.6.3/share/doc/julia/html/en/assets/documenter.js
deleted file mode 100644
index 5d31622..0000000
--- a/julia-0.6.3/share/doc/julia/html/en/assets/documenter.js
+++ /dev/null
@@ -1,129 +0,0 @@
-/*
- * Part of Documenter.jl
- *     https://github.com/JuliaDocs/Documenter.jl
- *
- * License: MIT
- */
-
-requirejs.config({
-    paths: {
-        'jquery': 'https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min',
-        'jqueryui': 'https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.0/jquery-ui.min',
-        'headroom': 'https://cdnjs.cloudflare.com/ajax/libs/headroom/0.9.3/headroom.min',
-        'mathjax': 'https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/MathJax.js?config=TeX-AMS_HTML',
-        'highlight': 'https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/highlight.min',
-        'highlight-julia': 'https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/languages/julia.min',
-        'highlight-julia-repl': 'https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/languages/julia-repl.min',
-    },
-    shim: {
-        'mathjax' : {
-            exports: "MathJax"
-        },
-        'highlight-julia': ['highlight'],
-        'highlight-julia-repl': ['highlight'],
-    }
-});
-
-// Load MathJax
-require(['mathjax'], function(MathJax) {
-    MathJax.Hub.Config({
-      "tex2jax": {
-        inlineMath: [['$','$'], ['\\(','\\)']],
-        processEscapes: true
-      }
-    });
-    MathJax.Hub.Config({
-      config: ["MMLorHTML.js"],
-      jax: [
-        "input/TeX",
-        "output/HTML-CSS",
-        "output/NativeMML"
-      ],
-      extensions: [
-        "MathMenu.js",
-        "MathZoom.js",
-        "TeX/AMSmath.js",
-        "TeX/AMSsymbols.js",
-        "TeX/autobold.js",
-        "TeX/autoload-all.js"
-      ]
-    });
-    MathJax.Hub.Config({
-      TeX: { equationNumbers: { autoNumber: "AMS" } }
-    });
-})
-
-require(['jquery', 'highlight', 'highlight-julia', 'highlight-julia-repl'], function($, hljs) {
-    $(document).ready(function() {
-        hljs.initHighlighting();
-    })
-
-})
-
-// update the version selector with info from the siteinfo.js and ../versions.js files
-require(['jquery'], function($) {
-    $(document).ready(function() {
-        var version_selector = $("#version-selector");
-
-        // add the current version to the selector based on siteinfo.js, but only if the selector is empty
-        if (typeof DOCUMENTER_CURRENT_VERSION !== 'undefined' && $('#version-selector > option').length == 0) {
-            var option = $("");
-            version_selector.append(option);
-        }
-
-        if (typeof DOC_VERSIONS !== 'undefined') {
-            var existing_versions = $('#version-selector > option');
-            var existing_versions_texts = existing_versions.map(function(i,x){return x.text});
-            DOC_VERSIONS.forEach(function(each) {
-                var version_url = documenterBaseURL + "/../" + each;
-                var existing_id = $.inArray(each, existing_versions_texts);
-                // if not already in the version selector, add it as a new option,
-                // otherwise update the old option with the URL and enable it
-                if (existing_id == -1) {
-                    var option = $("");
-                    version_selector.append(option);
-                } else {
-                    var option = existing_versions[existing_id];
-                    option.value = version_url;
-                    option.disabled = false;
-                }
-            });
-        }
-
-        // only show the version selector if the selector has been populated
-        if ($('#version-selector > option').length > 0) {
-            version_selector.css("visibility", "visible");
-        }
-    })
-
-})
-
-// mobile
-require(['jquery', 'headroom'], function($, Headroom) {
-    $(document).ready(function() {
-        var navtoc = $("nav.toc");
-        $("nav.toc li.current a.toctext").click(function() {
-            navtoc.toggleClass('show');
-        });
-        $("article > header div#topbar a.fa-bars").click(function(ev) {
-            ev.preventDefault();
-            navtoc.toggleClass('show');
-            if (navtoc.hasClass('show')) {
-                var title = $("article > header div#topbar span").text();
-                $("nav.toc ul li a:contains('" + title + "')").focus();
-            }
-        });
-        $("article#docs").bind('click', function(ev) {
-            if ($(ev.target).is('div#topbar a.fa-bars')) {
-                return;
-            }
-            if (navtoc.hasClass('show')) {
-                navtoc.removeClass('show');
-            }
-        });
-        if ($("article > header div#topbar").css('display') == 'block') {
-            var headroom = new Headroom(document.querySelector("article > header div#topbar"), {"tolerance": {"up": 10, "down": 10}});
-            headroom.init();
-        }
-    })
-})
diff --git a/julia-0.6.3/share/doc/julia/html/en/assets/julia-manual.css b/julia-0.6.3/share/doc/julia/html/en/assets/julia-manual.css
deleted file mode 100644
index 00772f3..0000000
--- a/julia-0.6.3/share/doc/julia/html/en/assets/julia-manual.css
+++ /dev/null
@@ -1,3 +0,0 @@
-nav.toc h1 {
-    display: none;
-}
diff --git a/julia-0.6.3/share/doc/julia/html/en/assets/logo.png b/julia-0.6.3/share/doc/julia/html/en/assets/logo.png
deleted file mode 100644
index 7e80e73..0000000
Binary files a/julia-0.6.3/share/doc/julia/html/en/assets/logo.png and /dev/null differ
diff --git a/julia-0.6.3/share/doc/julia/html/en/assets/search.js b/julia-0.6.3/share/doc/julia/html/en/assets/search.js
deleted file mode 100644
index 4dfee82..0000000
--- a/julia-0.6.3/share/doc/julia/html/en/assets/search.js
+++ /dev/null
@@ -1,243 +0,0 @@
-/*
- * Part of Documenter.jl
- *     https://github.com/JuliaDocs/Documenter.jl
- *
- * License: MIT
- */
-
-// parseUri 1.2.2
-// (c) Steven Levithan 
-// MIT License
-function parseUri (str) {
-	var	o   = parseUri.options,
-		m   = o.parser[o.strictMode ? "strict" : "loose"].exec(str),
-		uri = {},
-		i   = 14;
-
-	while (i--) uri[o.key[i]] = m[i] || "";
-
-	uri[o.q.name] = {};
-	uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) {
-		if ($1) uri[o.q.name][$1] = $2;
-	});
-
-	return uri;
-};
-parseUri.options = {
-	strictMode: false,
-	key: ["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],
-	q:   {
-		name:   "queryKey",
-		parser: /(?:^|&)([^&=]*)=?([^&]*)/g
-	},
-	parser: {
-		strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
-		loose:  /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/
-	}
-};
-
-requirejs.config({
-    paths: {
-        'jquery': 'https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min',
-        'lunr': 'https://cdnjs.cloudflare.com/ajax/libs/lunr.js/2.1.3/lunr.min',
-        'lodash': 'https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min',
-    }
-});
-
-var currentScript = document.currentScript;
-
-require(["jquery", "lunr", "lodash"], function($, lunr, _) {
-    $("#search-form").submit(function(e) {
-        e.preventDefault()
-    })
-
-    // list below is the lunr 2.1.3 list minus the intersect with names(Base)
-    // (all, any, get, in, is, which) and (do, else, for, let, where, while, with)
-    // ideally we'd just filter the original list but it's not available as a variable
-    lunr.stopWordFilter = lunr.generateStopWordFilter([
-        'a',
-        'able',
-        'about',
-        'across',
-        'after',
-        'almost',
-        'also',
-        'am',
-        'among',
-        'an',
-        'and',
-        'are',
-        'as',
-        'at',
-        'be',
-        'because',
-        'been',
-        'but',
-        'by',
-        'can',
-        'cannot',
-        'could',
-        'dear',
-        'did',
-        'does',
-        'either',
-        'ever',
-        'every',
-        'from',
-        'got',
-        'had',
-        'has',
-        'have',
-        'he',
-        'her',
-        'hers',
-        'him',
-        'his',
-        'how',
-        'however',
-        'i',
-        'if',
-        'into',
-        'it',
-        'its',
-        'just',
-        'least',
-        'like',
-        'likely',
-        'may',
-        'me',
-        'might',
-        'most',
-        'must',
-        'my',
-        'neither',
-        'no',
-        'nor',
-        'not',
-        'of',
-        'off',
-        'often',
-        'on',
-        'only',
-        'or',
-        'other',
-        'our',
-        'own',
-        'rather',
-        'said',
-        'say',
-        'says',
-        'she',
-        'should',
-        'since',
-        'so',
-        'some',
-        'than',
-        'that',
-        'the',
-        'their',
-        'them',
-        'then',
-        'there',
-        'these',
-        'they',
-        'this',
-        'tis',
-        'to',
-        'too',
-        'twas',
-        'us',
-        'wants',
-        'was',
-        'we',
-        'were',
-        'what',
-        'when',
-        'who',
-        'whom',
-        'why',
-        'will',
-        'would',
-        'yet',
-        'you',
-        'your'
-        ])
-
-    // add . as a separator, because otherwise "title": "Documenter.Anchors.add!"
-    // would not find anything if searching for "add!", only for the entire qualification
-    lunr.tokenizer.separator = /[\s\-\.]+/
-
-    // custom trimmer that doesn't strip @ and !, which are used in julia macro and function names
-    lunr.trimmer = function (token) {
-        return token.update(function (s) {
-            return s.replace(/^[^a-zA-Z0-9@!]+/, '').replace(/[^a-zA-Z0-9@!]+$/, '')
-        })
-    }
-
-    lunr.Pipeline.registerFunction(lunr.stopWordFilter, 'juliaStopWordFilter')
-    lunr.Pipeline.registerFunction(lunr.trimmer, 'juliaTrimmer')
-
-    var index = lunr(function () {
-        this.ref('location')
-        this.field('title')
-        this.field('text')
-        documenterSearchIndex['docs'].forEach(function(e) {
-            this.add(e)
-        }, this)
-    })
-    var store = {}
-
-    documenterSearchIndex['docs'].forEach(function(e) {
-        store[e.location] = {title: e.title, category: e.category}
-    })
-
-    $(function(){
-        function update_search(querystring) {
-            tokens = lunr.tokenizer(querystring)
-            results = index.query(function (q) {
-                tokens.forEach(function (t) {
-                    q.term(t.toString(), {
-                        fields: ["title"],
-                        boost: 10,
-                        usePipeline: false,
-                        editDistance: 2,
-                        wildcard: lunr.Query.wildcard.NONE
-                    })
-                    q.term(t.toString(), {
-                        fields: ["text"],
-                        boost: 1,
-                        usePipeline: true,
-                        editDistance: 2,
-                        wildcard: lunr.Query.wildcard.NONE
-                    })
-                })
-            })
-            $('#search-info').text("Number of results: " + results.length)
-            $('#search-results').empty()
-            results.forEach(function(result) {
-                data = store[result.ref]
-                link = $('')
-                link.text(data.title)
-                link.attr('href', documenterBaseURL+'/'+result.ref)
-                cat = $('('+data.category+')')
-                li = $('
  • ').append(link).append(" ").append(cat) - $('#search-results').append(li) - }) - } - - function update_search_box() { - querystring = $('#search-query').val() - update_search(querystring) - } - - $('#search-query').keyup(_.debounce(update_search_box, 250)) - $('#search-query').change(update_search_box) - - search_query_uri = parseUri(window.location).queryKey["q"] - if(search_query_uri !== undefined) { - search_query = decodeURIComponent(search_query_uri.replace(/\+/g, '%20')) - $("#search-query").val(search_query) - } - update_search_box(); - }) -}) diff --git a/julia-0.6.3/share/doc/julia/html/en/devdocs/ast.html b/julia-0.6.3/share/doc/julia/html/en/devdocs/ast.html deleted file mode 100644 index 98cbe05..0000000 --- a/julia-0.6.3/share/doc/julia/html/en/devdocs/ast.html +++ /dev/null @@ -1,27 +0,0 @@ - -Julia ASTs · The Julia Language

    Julia ASTs

    Julia ASTs

    Julia has two representations of code. First there is a surface syntax AST returned by the parser (e.g. the parse() function), and manipulated by macros. It is a structured representation of code as it is written, constructed by julia-parser.scm from a character stream. Next there is a lowered form, or IR (intermediate representation), which is used by type inference and code generation. In the lowered form there are fewer types of nodes, all macros are expanded, and all control flow is converted to explicit branches and sequences of statements. The lowered form is constructed by julia-syntax.scm.

    First we will focus on the lowered form, since it is more important to the compiler. It is also less obvious to the human, since it results from a significant rearrangement of the input syntax.

    Lowered form

    The following data types exist in lowered form:

    • Expr

      Has a node type indicated by the head field, and an args field which is a Vector{Any} of subexpressions.

    • Slot

      Identifies arguments and local variables by consecutive numbering. Slot is an abstract type with subtypes SlotNumber and TypedSlot. Both types have an integer-valued id field giving the slot index. Most slots have the same type at all uses, and so are represented with SlotNumber. The types of these slots are found in the slottypes field of their MethodInstance object. Slots that require per-use type annotations are represented with TypedSlot, which has a typ field.

    • CodeInfo

      Wraps the IR of a method.

    • LineNumberNode

      Contains a single number, specifying the line number the next statement came from.

    • LabelNode

      Branch target, a consecutively-numbered integer starting at 0.

    • GotoNode

      Unconditional branch.

    • QuoteNode

      Wraps an arbitrary value to reference as data. For example, the function f() = :a contains a QuoteNode whose value field is the symbol a, in order to return the symbol itself instead of evaluating it.

    • GlobalRef

      Refers to global variable name in module mod.

    • SSAValue

      Refers to a consecutively-numbered (starting at 0) static single assignment (SSA) variable inserted by the compiler.

    • NewvarNode

      Marks a point where a variable is created. This has the effect of resetting a variable to undefined.

    Expr types

    These symbols appear in the head field of Exprs in lowered form.

    • call

      Function call (dynamic dispatch). args[1] is the function to call, args[2:end] are the arguments.

    • invoke

      Function call (static dispatch). args[1] is the MethodInstance to call, args[2:end] are the arguments (including the function that is being called, at args[2]).

    • static_parameter

      Reference a static parameter by index.

    • line

      Line number and file name metadata. Unlike a LineNumberNode, can also contain a file name.

    • gotoifnot

      Conditional branch. If args[1] is false, goes to label identified in args[2].

    • =

      Assignment.

    • method

      Adds a method to a generic function and assigns the result if necessary.

      Has a 1-argument form and a 4-argument form. The 1-argument form arises from the syntax function foo end. In the 1-argument form, the argument is a symbol. If this symbol already names a function in the current scope, nothing happens. If the symbol is undefined, a new function is created and assigned to the identifier specified by the symbol. If the symbol is defined but names a non-function, an error is raised. The definition of "names a function" is that the binding is constant, and refers to an object of singleton type. The rationale for this is that an instance of a singleton type uniquely identifies the type to add the method to. When the type has fields, it wouldn't be clear whether the method was being added to the instance or its type.

      The 4-argument form has the following arguments:

      • args[1]

        A function name, or false if unknown. If a symbol, then the expression first behaves like the 1-argument form above. This argument is ignored from then on. When this is false, it means a method is being added strictly by type, (::T)(x) = x.

      • args[2]

        A SimpleVector of argument type data. args[2][1] is a SimpleVector of the argument types, and args[2][2] is a SimpleVector of type variables corresponding to the method's static parameters.

      • args[3]

        A CodeInfo of the method itself. For "out of scope" method definitions (adding a method to a function that also has methods defined in different scopes) this is an expression that evaluates to a :lambda expression.

      • args[4]

        true or false, identifying whether the method is staged (@generated function).

    • const

      Declares a (global) variable as constant.

    • null

      Has no arguments; simply yields the value nothing.

    • new

      Allocates a new struct-like object. First argument is the type. The new pseudo-function is lowered to this, and the type is always inserted by the compiler. This is very much an internal-only feature, and does no checking. Evaluating arbitrary new expressions can easily segfault.

    • return

      Returns its argument as the value of the enclosing function.

    • the_exception

      Yields the caught exception inside a catch block. This is the value of the run time system variable jl_exception_in_transit.

    • enter

      Enters an exception handler (setjmp). args[1] is the label of the catch block to jump to on error.

    • leave

      Pop exception handlers. args[1] is the number of handlers to pop.

    • inbounds

      Controls turning bounds checks on or off. A stack is maintained; if the first argument of this expression is true or false (true means bounds checks are disabled), it is pushed onto the stack. If the first argument is :pop, the stack is popped.

    • boundscheck

      Indicates the beginning or end of a section of code that performs a bounds check. Like inbounds, a stack is maintained, and the second argument can be one of: true, false, or :pop.

    • copyast

      Part of the implementation of quasi-quote. The argument is a surface syntax AST that is simply copied recursively and returned at run time.

    • meta

      Metadata. args[1] is typically a symbol specifying the kind of metadata, and the rest of the arguments are free-form. The following kinds of metadata are commonly used:

      • :inline and :noinline: Inlining hints.

      • :push_loc: enters a sequence of statements from a specified source location.

        • args[2] specifies a filename, as a symbol.

        • args[3] optionally specifies the name of an (inlined) function that originally contained the code.

      • :pop_loc: returns to the source location before the matching :push_loc.

    Method

    A unique'd container describing the shared metadata for a single method.

    • name, module, file, line, sig

      Metadata to uniquely identify the method for the computer and the human.

    • ambig

      Cache of other methods that may be ambiguous with this one.

    • specializations

      Cache of all MethodInstance ever created for this Method, used to ensure uniqueness. Uniqueness is required for efficiency, especially for incremental precompile and tracking of method invalidation.

    • source

      The original source code (usually compressed).

    • roots

      Pointers to non-AST things that have been interpolated into the AST, required by compression of the AST, type-inference, or the generation of native code.

    • nargs, isva, called, isstaged, pure

      Descriptive bit-fields for the source code of this Method.

    • min_world / max_world

      The range of world ages for which this method is visible to dispatch.

    MethodInstance

    A unique'd container describing a single callable signature for a Method. See especially Proper maintenance and care of multi-threading locks for important details on how to modify these fields safely.

    • specTypes

      The primary key for this MethodInstance. Uniqueness is guaranteed through a def.specializations lookup.

    • def

      The Method that this function describes a specialization of. Or #undef, if this is a top-level Lambda that is not part of a Method.

    • sparam_vals

      The values of the static parameters in specTypes indexed by def.sparam_syms. For the MethodInstance at Method.unspecialized, this is the empty SimpleVector. But for a runtime MethodInstance from the MethodTable cache, this will always be defined and indexable.

    • rettype

      The inferred return type for the specFunctionObject field, which (in most cases) is also the computed return type for the function in general.

    • inferred

      May contain a cache of the inferred source for this function, or other information about the inference result such as a constant return value may be put here (if jlcall_api == 2), or it could be set to nothing to just indicate rettype is inferred.

    • ftpr

      The generic jlcall entry point.

    • jlcall_api

      The ABI to use when calling fptr. Some significant ones include:

      • 0 - Not compiled yet

      • 1 - JL_CALLABLE jl_value_t *(*)(jl_function_t *f, jl_value_t *args[nargs], uint32_t nargs)

      • 2 - Constant (value stored in inferred)

      • 3 - With Static-parameters forwarded jl_value_t *(*)(jl_svec_t *sparams, jl_function_t *f, jl_value_t *args[nargs], uint32_t nargs)

      • 4 - Run in interpreter jl_value_t *(*)(jl_method_instance_t *meth, jl_function_t *f, jl_value_t *args[nargs], uint32_t nargs)

    • min_world / max_world

      The range of world ages for which this method instance is valid to be called.

    CodeInfo

    A temporary container for holding lowered source code.

    • code

      An Any array of statements

    • slotnames

      An array of symbols giving the name of each slot (argument or local variable).

    • slottypes

      An array of types for the slots.

    • slotflags

      A UInt8 array of slot properties, represented as bit flags:

      • 2 - assigned (only false if there are no assignment statements with this var on the left)

      • 8 - const (currently unused for local variables)

      • 16 - statically assigned once

      • 32 - might be used before assigned. This flag is only valid after type inference.

    • ssavaluetypes

      Either an array or an Int.

      If an Int, it gives the number of compiler-inserted temporary locations in the function. If an array, specifies a type for each location.

    Boolean properties:

    • inferred

      Whether this has been produced by type inference.

    • inlineable

      Whether this should be inlined.

    • propagate_inbounds

      Whether this should should propagate @inbounds when inlined for the purpose of eliding @boundscheck blocks.

    • pure

      Whether this is known to be a pure function of its arguments, without respect to the state of the method caches or other mutable global state.

    Surface syntax AST

    Front end ASTs consist entirely of Exprs and atoms (e.g. symbols, numbers). There is generally a different expression head for each visually distinct syntactic form. Examples will be given in s-expression syntax. Each parenthesized list corresponds to an Expr, where the first element is the head. For example (call f x) corresponds to Expr(:call, :f, :x) in Julia.

    Calls

    InputAST
    f(x)(call f x)
    f(x, y=1, z=2)(call f x (kw y 1) (kw z 2))
    f(x; y=1)(call f (parameters (kw y 1)) x)
    f(x...)(call f (... x))

    do syntax:

    f(x) do a,b
    -    body
    -end

    parses as (call f (-> (tuple a b) (block body)) x).

    Operators

    Most uses of operators are just function calls, so they are parsed with the head call. However some operators are special forms (not necessarily function calls), and in those cases the operator itself is the expression head. In julia-parser.scm these are referred to as "syntactic operators". Some operators (+ and *) use N-ary parsing; chained calls are parsed as a single N-argument call. Finally, chains of comparisons have their own special expression structure.

    InputAST
    x+y(call + x y)
    a+b+c+d(call + a b c d)
    2x(call * 2 x)
    a&&b(&& a b)
    x += 1(+= x 1)
    a ? 1 : 2(if a 1 2)
    a:b(: a b)
    a:b:c(: a b c)
    a,b(tuple a b)
    a==b(call == a b)
    1<i<=n(comparison 1 < i <= n)
    a.b(. a (quote b))
    a.(b)(. a b)

    Bracketed forms

    InputAST
    a[i](ref a i)
    t[i;j](typed_vcat t i j)
    t[i j](typed_hcat t i j)
    t[a b; c d](typed_vcat t (row a b) (row c d))
    a{b}(curly a b)
    a{b;c}(curly a (parameters c) b)
    [x](vect x)
    [x,y](vect x y)
    [x;y](vcat x y)
    [x y](hcat x y)
    [x y; z t](vcat (row x y) (row z t))
    [x for y in z, a in b](comprehension x (= y z) (= a b))
    T[x for y in z](typed_comprehension T x (= y z))
    (a, b, c)(tuple a b c)
    (a; b; c)(block a (block b c))

    Macros

    InputAST
    @m x y(macrocall @m x y)
    Base.@m x y(macrocall (. Base (quote @m)) x y)
    @Base.m x y(macrocall (. Base (quote @m)) x y)

    Strings

    InputAST
    "a""a"
    x"y"(macrocall @x_str "y")
    x"y"z(macrocall @x_str "y" "z")
    "x = $x"(string "x = " x)
    `a b c`(macrocall @cmd "a b c")

    Doc string syntax:

    "some docs"
    -f(x) = x

    parses as (macrocall (|.| Core '@doc) "some docs" (= (call f x) (block x))).

    Imports and such

    InputAST
    import a(import a)
    import a.b.c(import a b c)
    import ...a(import . . . a)
    import a.b, c.d(toplevel (import a b) (import c d))
    import Base: x(import Base x)
    import Base: x, y(toplevel (import Base x) (import Base y))
    export a, b(export a b)

    Numbers

    Julia supports more number types than many scheme implementations, so not all numbers are represented directly as scheme numbers in the AST.

    InputAST
    11111111111111111111(macrocall @int128_str "11111111111111111111")
    0xfffffffffffffffff(macrocall @uint128_str "0xfffffffffffffffff")
    1111...many digits...(macrocall @big_str "1111....")

    Block forms

    A block of statements is parsed as (block stmt1 stmt2 ...).

    If statement:

    if a
    -    b
    -elseif c
    -    d
    -else e
    -    f
    -end

    parses as:

    (if a (block (line 2) b)
    -    (block (line 3) (if c (block (line 4) d)
    -                        (block (line 5) e (line 6) f))))

    A while loop parses as (while condition body).

    A for loop parses as (for (= var iter) body). If there is more than one iteration specification, they are parsed as a block: (for (block (= v1 iter1) (= v2 iter2)) body).

    break and continue are parsed as 0-argument expressions (break) and (continue).

    let is parsed as (let body (= var1 val1) (= var2 val2) ...).

    A basic function definition is parsed as (function (call f x) body). A more complex example:

    function f{T}(x::T; k = 1)
    -    return x+1
    -end

    parses as:

    (function (call (curly f T) (parameters (kw k 1))
    -                (:: x T))
    -          (block (line 2 file.jl) (return (call + x 1))))

    Type definition:

    mutable struct Foo{T<:S}
    -    x::T
    -end

    parses as:

    (type #t (curly Foo (<: T S))
    -      (block (line 2 none) (:: x T)))

    The first argument is a boolean telling whether the type is mutable.

    try blocks parse as (try try_block var catch_block finally_block). If no variable is present after catch, var is #f. If there is no finally clause, then the last argument is not present.

    diff --git a/julia-0.6.3/share/doc/julia/html/en/devdocs/backtraces.html b/julia-0.6.3/share/doc/julia/html/en/devdocs/backtraces.html deleted file mode 100644 index 3b70d2e..0000000 --- a/julia-0.6.3/share/doc/julia/html/en/devdocs/backtraces.html +++ /dev/null @@ -1,27 +0,0 @@ - -Reporting and analyzing crashes (segfaults) · The Julia Language

    Reporting and analyzing crashes (segfaults)

    Reporting and analyzing crashes (segfaults)

    So you managed to break Julia. Congratulations! Collected here are some general procedures you can undergo for common symptoms encountered when something goes awry. Including the information from these debugging steps can greatly help the maintainers when tracking down a segfault or trying to figure out why your script is running slower than expected.

    If you've been directed to this page, find the symptom that best matches what you're experiencing and follow the instructions to generate the debugging information requested. Table of symptoms:

    Version/Environment info

    No matter the error, we will always need to know what version of Julia you are running. When Julia first starts up, a header is printed out with a version number and date. If your version is 0.2.0 or higher, please include the output of versioninfo() in any report you create:

    julia> versioninfo()
    -Julia Version 0.6.3
    -Commit d55cadc350 (2018-05-28 20:20 UTC)
    -Platform Info:
    -  OS: Linux (x86_64-pc-linux-gnu)
    -  CPU: Intel(R) Xeon(R) CPU E3-1241 v3 @ 3.50GHz
    -  WORD_SIZE: 64
    -  BLAS: libopenblas (USE64BITINT DYNAMIC_ARCH NO_AFFINITY Haswell)
    -  LAPACK: libopenblas64_
    -  LIBM: libopenlibm
    -  LLVM: libLLVM-3.9.1 (ORCJIT, haswell)

    Segfaults during bootstrap (sysimg.jl)

    Segfaults toward the end of the make process of building Julia are a common symptom of something going wrong while Julia is preparsing the corpus of code in the base/ folder. Many factors can contribute toward this process dying unexpectedly, however it is as often as not due to an error in the C-code portion of Julia, and as such must typically be debugged with a debug build inside of gdb. Explicitly:

    Create a debug build of Julia:

    $ cd <julia_root>
    -$ make debug

    Note that this process will likely fail with the same error as a normal make incantation, however this will create a debug executable that will offer gdb the debugging symbols needed to get accurate backtraces. Next, manually run the bootstrap process inside of gdb:

    $ cd base/
    -$ gdb -x ../contrib/debug_bootstrap.gdb

    This will start gdb, attempt to run the bootstrap process using the debug build of Julia, and print out a backtrace if (when) it segfaults. You may need to hit <enter> a few times to get the full backtrace. Create a gist with the backtrace, the version info, and any other pertinent information you can think of and open a new issue on Github with a link to the gist.

    Segfaults when running a script

    The procedure is very similar to Segfaults during bootstrap (sysimg.jl). Create a debug build of Julia, and run your script inside of a debugged Julia process:

    $ cd <julia_root>
    -$ make debug
    -$ gdb --args usr/bin/julia-debug <path_to_your_script>

    Note that gdb will sit there, waiting for instructions. Type r to run the process, and bt to generate a backtrace once it segfaults:

    (gdb) r
    -Starting program: /home/sabae/src/julia/usr/bin/julia-debug ./test.jl
    -...
    -(gdb) bt

    Create a gist with the backtrace, the version info, and any other pertinent information you can think of and open a new issue on Github with a link to the gist.

    Errors during Julia startup

    Occasionally errors occur during Julia's startup process (especially when using binary distributions, as opposed to compiling from source) such as the following:

    $ julia
    -exec: error -5

    These errors typically indicate something is not getting loaded properly very early on in the bootup phase, and our best bet in determining what's going wrong is to use external tools to audit the disk activity of the julia process:

    • On Linux, use strace:

      $ strace julia
    • On OSX, use dtruss:

      $ dtruss -f julia

    Create a gist with the strace/ dtruss ouput, the version info, and any other pertinent information and open a new issue on Github with a link to the gist.

    Glossary

    A few terms have been used as shorthand in this guide:

    • <julia_root> refers to the root directory of the Julia source tree; e.g. it should contain folders such as base, deps, src, test, etc.....

    diff --git a/julia-0.6.3/share/doc/julia/html/en/devdocs/boundscheck.html b/julia-0.6.3/share/doc/julia/html/en/devdocs/boundscheck.html deleted file mode 100644 index 428252c..0000000 --- a/julia-0.6.3/share/doc/julia/html/en/devdocs/boundscheck.html +++ /dev/null @@ -1,16 +0,0 @@ - -Bounds checking · The Julia Language

    Bounds checking

    Bounds checking

    Like many modern programming languages, Julia uses bounds checking to ensure program safety when accessing arrays. In tight inner loops or other performance critical situations, you may wish to skip these bounds checks to improve runtime performance. For instance, in order to emit vectorized (SIMD) instructions, your loop body cannot contain branches, and thus cannot contain bounds checks. Consequently, Julia includes an @inbounds(...) macro to tell the compiler to skip such bounds checks within the given block. For the built-in Array type, the magic happens inside the arrayref and arrayset intrinsics. User-defined array types instead use the @boundscheck(...) macro to achieve context-sensitive code selection.

    Eliding bounds checks

    The @boundscheck(...) macro marks blocks of code that perform bounds checking. When such blocks appear inside of an @inbounds(...) block, the compiler removes these blocks. When the @boundscheck(...) is nested inside of a calling function containing an @inbounds(...), the compiler will remove the @boundscheck block only if it is inlined into the calling function. For example, you might write the method sum as:

    function sum(A::AbstractArray)
    -    r = zero(eltype(A))
    -    for i = 1:length(A)
    -        @inbounds r += A[i]
    -    end
    -    return r
    -end

    With a custom array-like type MyArray having:

    @inline getindex(A::MyArray, i::Real) = (@boundscheck checkbounds(A,i); A.data[to_index(i)])

    Then when getindex is inlined into sum, the call to checkbounds(A,i) will be elided. If your function contains multiple layers of inlining, only @boundscheck blocks at most one level of inlining deeper are eliminated. The rule prevents unintended changes in program behavior from code further up the stack.

    Propagating inbounds

    There may be certain scenarios where for code-organization reasons you want more than one layer between the @inbounds and @boundscheck declarations. For instance, the default getindex methods have the chain getindex(A::AbstractArray, i::Real) calls getindex(IndexStyle(A), A, i) calls _getindex(::IndexLinear, A, i).

    To override the "one layer of inlining" rule, a function may be marked with @propagate_inbounds to propagate an inbounds context (or out of bounds context) through one additional layer of inlining.

    The bounds checking call hierarchy

    The overall hierarchy is:

    • checkbounds(A, I...) which calls

      • checkbounds(Bool, A, I...) which calls

        • checkbounds_indices(Bool, indices(A), I) which recursively calls

          • checkindex for each dimension

    Here A is the array, and I contains the "requested" indices. indices(A) returns a tuple of "permitted" indices of A.

    checkbounds(A, I...) throws an error if the indices are invalid, whereas checkbounds(Bool, A, I...) returns false in that circumstance. checkbounds_indices discards any information about the array other than its indices tuple, and performs a pure indices-vs-indices comparison: this allows relatively few compiled methods to serve a huge variety of array types. Indices are specified as tuples, and are usually compared in a 1-1 fashion with individual dimensions handled by calling another important function, checkindex: typically,

    checkbounds_indices(Bool, (IA1, IA...), (I1, I...)) = checkindex(Bool, IA1, I1) &
    -                                                      checkbounds_indices(Bool, IA, I)

    so checkindex checks a single dimension. All of these functions, including the unexported checkbounds_indices have docstrings accessible with ? .

    If you have to customize bounds checking for a specific array type, you should specialize checkbounds(Bool, A, I...). However, in most cases you should be able to rely on checkbounds_indices as long as you supply useful indices for your array type.

    If you have novel index types, first consider specializing checkindex, which handles a single index for a particular dimension of an array. If you have a custom multidimensional index type (similar to CartesianIndex), then you may have to consider specializing checkbounds_indices.

    Note this hierarchy has been designed to reduce the likelihood of method ambiguities. We try to make checkbounds the place to specialize on array type, and try to avoid specializations on index types; conversely, checkindex is intended to be specialized only on index type (especially, the last argument).

    diff --git a/julia-0.6.3/share/doc/julia/html/en/devdocs/callconv.html b/julia-0.6.3/share/doc/julia/html/en/devdocs/callconv.html deleted file mode 100644 index 077dbd0..0000000 --- a/julia-0.6.3/share/doc/julia/html/en/devdocs/callconv.html +++ /dev/null @@ -1,9 +0,0 @@ - -Calling Conventions · The Julia Language

    Calling Conventions

    Calling Conventions

    Julia uses three calling conventions for four distinct purposes:

    NamePrefixPurpose
    Nativejulia_Speed via specialized signatures
    JL Calljlcall_Wrapper for generic calls
    JL Calljl_Builtins
    C ABIjlcapi_Wrapper callable from C

    Julia Native Calling Convention

    The native calling convention is designed for fast non-generic calls. It usually uses a specialized signature.

    • LLVM ghosts (zero-length types) are omitted.

    • LLVM scalars and vectors are passed by value.

    • LLVM aggregates (arrays and structs) are passed by reference.

    A small return values is returned as LLVM return values. A large return values is returned via the "structure return" (sret) convention, where the caller provides a pointer to a return slot.

    An argument or return values thta is a homogeneous tuple is sometimes represented as an LLVM vector instead of an LLVM array.

    JL Call Convention

    The JL Call convention is for builtins and generic dispatch. Hand-written functions using this convention are declared via the macro JL_CALLABLE. The convention uses exactly 3 parameters:

    • F - Julia representation of function that is being applied

    • args - pointer to array of pointers to boxes

    • nargs - length of the array

    The return value is a pointer to a box.

    C ABI

    C ABI wrappers enable calling Julia from C. The wrapper calls a function using the native calling convention.

    Tuples are always represented as C arrays.

    diff --git a/julia-0.6.3/share/doc/julia/html/en/devdocs/cartesian.html b/julia-0.6.3/share/doc/julia/html/en/devdocs/cartesian.html deleted file mode 100644 index 0a22742..0000000 --- a/julia-0.6.3/share/doc/julia/html/en/devdocs/cartesian.html +++ /dev/null @@ -1,58 +0,0 @@ - -Base.Cartesian · The Julia Language

    Base.Cartesian

    Base.Cartesian

    The (non-exported) Cartesian module provides macros that facilitate writing multidimensional algorithms. It is hoped that Cartesian will not, in the long term, be necessary; however, at present it is one of the few ways to write compact and performant multidimensional code.

    Principles of usage

    A simple example of usage is:

    @nloops 3 i A begin
    -    s += @nref 3 A i
    -end

    which generates the following code:

    for i_3 = 1:size(A,3)
    -    for i_2 = 1:size(A,2)
    -        for i_1 = 1:size(A,1)
    -            s += A[i_1,i_2,i_3]
    -        end
    -    end
    -end

    In general, Cartesian allows you to write generic code that contains repetitive elements, like the nested loops in this example. Other applications include repeated expressions (e.g., loop unwinding) or creating function calls with variable numbers of arguments without using the "splat" construct (i...).

    Basic syntax

    The (basic) syntax of @nloops is as follows:

    • The first argument must be an integer (not a variable) specifying the number of loops.

    • The second argument is the symbol-prefix used for the iterator variable. Here we used i, and variables i_1, i_2, i_3 were generated.

    • The third argument specifies the range for each iterator variable. If you use a variable (symbol) here, it's taken as 1:size(A,dim). More flexibly, you can use the anonymous-function expression syntax described below.

    • The last argument is the body of the loop. Here, that's what appears between the begin...end.

    There are some additional features of @nloops described in the reference section.

    @nref follows a similar pattern, generating A[i_1,i_2,i_3] from @nref 3 A i. The general practice is to read from left to right, which is why @nloops is @nloops 3 i A expr (as in for i_2 = 1:size(A,2), where i_2 is to the left and the range is to the right) whereas @nref is @nref 3 A i (as in A[i_1,i_2,i_3], where the array comes first).

    If you're developing code with Cartesian, you may find that debugging is easier when you examine the generated code, using macroexpand:

    julia> macroexpand(:(@nref 2 A i))
    -:(A[i_1, i_2])

    Supplying the number of expressions

    The first argument to both of these macros is the number of expressions, which must be an integer. When you're writing a function that you intend to work in multiple dimensions, this may not be something you want to hard-code. If you're writing code that you need to work with older Julia versions, currently you should use the @ngenerate macro described in an older version of this documentation.

    Starting in Julia 0.4-pre, the recommended approach is to use a @generated function. Here's an example:

    @generated function mysum(A::Array{T,N}) where {T,N}
    -    quote
    -        s = zero(T)
    -        @nloops $N i A begin
    -            s += @nref $N A i
    -        end
    -        s
    -    end
    -end

    Naturally, you can also prepare expressions or perform calculations before the quote block.

    Anonymous-function expressions as macro arguments

    Perhaps the single most powerful feature in Cartesian is the ability to supply anonymous-function expressions that get evaluated at parsing time. Let's consider a simple example:

    @nexprs 2 j->(i_j = 1)

    @nexprs generates n expressions that follow a pattern. This code would generate the following statements:

    i_1 = 1
    -i_2 = 1

    In each generated statement, an "isolated" j (the variable of the anonymous function) gets replaced by values in the range 1:2. Generally speaking, Cartesian employs a LaTeX-like syntax. This allows you to do math on the index j. Here's an example computing the strides of an array:

    s_1 = 1
    -@nexprs 3 j->(s_{j+1} = s_j * size(A, j))

    would generate expressions

    s_1 = 1
    -s_2 = s_1 * size(A, 1)
    -s_3 = s_2 * size(A, 2)
    -s_4 = s_3 * size(A, 3)

    Anonymous-function expressions have many uses in practice.

    Macro reference

    @nloops N itersym rangeexpr bodyexpr
    -@nloops N itersym rangeexpr preexpr bodyexpr
    -@nloops N itersym rangeexpr preexpr postexpr bodyexpr

    Generate N nested loops, using itersym as the prefix for the iteration variables. rangeexpr may be an anonymous-function expression, or a simple symbol var in which case the range is indices(var, d) for dimension d.

    Optionally, you can provide "pre" and "post" expressions. These get executed first and last, respectively, in the body of each loop. For example:

    @nloops 2 i A d -> j_d = min(i_d, 5) begin
    -    s += @nref 2 A j
    -end

    would generate:

    for i_2 = indices(A, 2)
    -    j_2 = min(i_2, 5)
    -    for i_1 = indices(A, 1)
    -        j_1 = min(i_1, 5)
    -        s += A[j_1, j_2]
    -    end
    -end

    If you want just a post-expression, supply nothing for the pre-expression. Using parentheses and semicolons, you can supply multi-statement expressions.

    source
    @nref N A indexexpr

    Generate expressions like A[i_1, i_2, ...]. indexexpr can either be an iteration-symbol prefix, or an anonymous-function expression.

    julia> @macroexpand Base.Cartesian.@nref 3 A i
    -:(A[i_1, i_2, i_3])
    source
    @nextract N esym isym

    Generate N variables esym_1, esym_2, ..., esym_N to extract values from isym. isym can be either a Symbol or anonymous-function expression.

    @nextract 2 x y would generate

    x_1 = y[1]
    -x_2 = y[2]

    while @nextract 3 x d->y[2d-1] yields

    x_1 = y[1]
    -x_2 = y[3]
    -x_3 = y[5]
    source
    @nexprs N expr

    Generate N expressions. expr should be an anonymous-function expression.

    julia> @macroexpand Base.Cartesian.@nexprs 4 i -> y[i] = A[i+j]
    -quote
    -    y[1] = A[1 + j]
    -    y[2] = A[2 + j]
    -    y[3] = A[3 + j]
    -    y[4] = A[4 + j]
    -end
    source
    @ncall N f sym...

    Generate a function call expression. sym represents any number of function arguments, the last of which may be an anonymous-function expression and is expanded into N arguments.

    For example @ncall 3 func a generates

    func(a_1, a_2, a_3)

    while @ncall 2 func a b i->c[i] yields

    func(a, b, c[1], c[2])
    source
    @ntuple N expr

    Generates an N-tuple. @ntuple 2 i would generate (i_1, i_2), and @ntuple 2 k->k+1 would generate (2,3).

    source
    @nall N expr

    Check whether all of the expressions generated by the anonymous-function expression expr evaluate to true.

    @nall 3 d->(i_d > 1) would generate the expression (i_1 > 1 && i_2 > 1 && i_3 > 1). This can be convenient for bounds-checking.

    source
    @nany N expr

    Check whether any of the expressions generated by the anonymous-function expression expr evaluate to true.

    @nany 3 d->(i_d > 1) would generate the expression (i_1 > 1 || i_2 > 1 || i_3 > 1).

    source
    @nif N conditionexpr expr
    -@nif N conditionexpr expr elseexpr

    Generates a sequence of if ... elseif ... else ... end statements. For example:

    @nif 3 d->(i_d >= size(A,d)) d->(error("Dimension ", d, " too big")) d->println("All OK")

    would generate:

    if i_1 > size(A, 1)
    -    error("Dimension ", 1, " too big")
    -elseif i_2 > size(A, 2)
    -    error("Dimension ", 2, " too big")
    -else
    -    println("All OK")
    -end
    source
    diff --git a/julia-0.6.3/share/doc/julia/html/en/devdocs/compiler.html b/julia-0.6.3/share/doc/julia/html/en/devdocs/compiler.html deleted file mode 100644 index f63b583..0000000 --- a/julia-0.6.3/share/doc/julia/html/en/devdocs/compiler.html +++ /dev/null @@ -1,9 +0,0 @@ - -High-level Overview of the Native-Code Generation Process · The Julia Language

    High-level Overview of the Native-Code Generation Process

    High-level Overview of the Native-Code Generation Process

    Representation of Pointers

    When emitting code to an object file, pointers will be emitted as relocations. The deserialization code will ensure any object that pointed to one of these constants gets recreated and contains the right runtime pointer.

    Otherwise, they will be emitted as literal constants.

    To emit one of these objects, call literal_pointer_val. It'll handle tracking the Julia value and the LLVM global, ensuring they are valid both for the current runtime and after deserialization.

    When emitted into the object file, these globals are stored as references in a large gvals table. This allows the deserializer to reference them by index, and implement a custom manual mechanism similar to a Global Offset Table (GOT) to restore them.

    Function pointers are handled similarly. They are stored as values in a large fvals table. Like globals, this allows the deserializer to reference them by index.

    Note that extern functions are handled separately, with names, via the usual symbol resolution mechanism in the linker.

    Note too that ccall functions are also handled separately, via a manual GOT and Procedure Linkage Table (PLT).

    Representation of Intermediate Values

    Values are passed around in a jl_cgval_t struct. This represents an R-value, and includes enough information to determine how to assign or pass it somewhere.

    They are created via one of the helper constructors, usually: mark_julia_type (for immediate values) and mark_julia_slot (for pointers to values).

    The function convert_julia_type can transform between any two types. It returns an R-value with cgval.typ set to typ. It'll cast the object to the requested representation, making heap boxes, allocating stack copies, and computing tagged unions as needed to change the representation.

    By contrast update_julia_type will change cgval.typ to typ, only if it can be done at zero-cost (i.e. without emitting any code).

    Union representation

    Inferred union types may be stack allocated via a tagged type representation.

    The primitive routines that need to be able to handle tagged unions are:

    • mark-type

    • load-local

    • store-local

    • isa

    • is

    • emit_typeof

    • emit_sizeof

    • boxed

    • unbox

    • specialized cc-ret

    Everything else should be possible to handle in inference by using these primitives to implement union-splitting.

    The representation of the tagged-union is as a pair of < void* union, byte selector >. The selector is fixed-size as byte & 0x7f, and will union-tag the first 126 isbits. It records the one-based depth-first count into the type-union of the isbits objects inside. An index of zero indicates that the union* is actually a tagged heap-allocated jl_value_t*, and needs to be treated as normal for a boxed object rather than as a tagged union.

    The high bit of the selector (byte & 0x80) can be tested to determine if the void* is actually a heap-allocated (jl_value_t*) box, thus avoiding the cost of re-allocating a box, while maintaining the ability to efficiently handle union-splitting based on the low bits.

    It is guaranteed that byte & 0x7f is an exact test for the type, if the value can be represented by a tag – it will never be marked byte = 0x80. It is not necessary to also test the type-tag when testing isa.

    The union* memory region may be allocated at any size. The only constraint is that it is big enough to contain the data currently specified by selector. It might not be big enough to contain the union of all types that could be stored there according to the associated Union type field. Use appropriate care when copying.

    Specialized Calling Convention Signature Representation

    A jl_returninfo_t object describes the calling convention details of any callable.

    If any of the arguments or return type of a method can be represented unboxed, and the method is not varargs, it'll be given an optimized calling convention signature based on its specTypes and rettype fields.

    The general principles are that:

    • Primitive types get passed in int/float registers.

    • Tuples of VecElement types get passed in vector registers.

    • Structs get passed on the stack.

    • Return values are handle similarly to arguments, with a size-cutoff at which they will instead be returned via a hidden sret argument.

    The total logic for this is implemented by get_specsig_function and deserves_sret.

    Additionally, if the return type is a union, it may be returned as a pair of values (a pointer and a tag). If the union values can be stack-allocated, then sufficient space to store them will also be passed as a hidden first argument. It is up to the callee whether the returned pointer will point to this space, a boxed object, or even other constant memory.

    diff --git a/julia-0.6.3/share/doc/julia/html/en/devdocs/debuggingtips.html b/julia-0.6.3/share/doc/julia/html/en/devdocs/debuggingtips.html deleted file mode 100644 index 99f7ed7..0000000 --- a/julia-0.6.3/share/doc/julia/html/en/devdocs/debuggingtips.html +++ /dev/null @@ -1,35 +0,0 @@ - -gdb debugging tips · The Julia Language

    gdb debugging tips

    gdb debugging tips

    Displaying Julia variables

    Within gdb, any jl_value_t* object obj can be displayed using

    (gdb) call jl_(obj)

    The object will be displayed in the julia session, not in the gdb session. This is a useful way to discover the types and values of objects being manipulated by Julia's C code.

    Similarly, if you're debugging some of Julia's internals (e.g., inference.jl), you can print obj using

    ccall(:jl_, Void, (Any,), obj)

    This is a good way to circumvent problems that arise from the order in which julia's output streams are initialized.

    Julia's flisp interpreter uses value_t objects; these can be displayed with call fl_print(fl_ctx, ios_stdout, obj).

    Useful Julia variables for Inspecting

    While the addresses of many variables, like singletons, can be be useful to print for many failures, there are a number of additional variables (see julia.h for a complete list) that are even more useful.

    • (when in jl_apply_generic) mfunc and jl_uncompress_ast(mfunc->def, mfunc->code) :: for figuring out a bit about the call-stack

    • jl_lineno and jl_filename :: for figuring out what line in a test to go start debugging from (or figure out how far into a file has been parsed)

    • $1 :: not really a variable, but still a useful shorthand for referring to the result of the last gdb command (such as print)

    • jl_options :: sometimes useful, since it lists all of the command line options that were successfully parsed

    • jl_uv_stderr :: because who doesn't like to be able to interact with stdio

    Useful Julia functions for Inspecting those variables

    • jl_gdblookup($rip) :: For looking up the current function and line. (use $eip on i686 platforms)

    • jlbacktrace() :: For dumping the current Julia backtrace stack to stderr. Only usable after record_backtrace() has been called.

    • jl_dump_llvm_value(Value*) :: For invoking Value->dump() in gdb, where it doesn't work natively. For example, f->linfo->functionObject, f->linfo->specFunctionObject, and to_function(f->linfo).

    • Type->dump() :: only works in lldb. Note: add something like ;1 to prevent lldb from printing its prompt over the output

    • jl_eval_string("expr") :: for invoking side-effects to modify the current state or to lookup symbols

    • jl_typeof(jl_value_t*) :: for extracting the type tag of a Julia value (in gdb, call macro define jl_typeof jl_typeof first, or pick something short like ty for the first arg to define a shorthand)

    Inserting breakpoints for inspection from gdb

    In your gdb session, set a breakpoint in jl_breakpoint like so:

    (gdb) break jl_breakpoint

    Then within your Julia code, insert a call to jl_breakpoint by adding

    ccall(:jl_breakpoint, Void, (Any,), obj)

    where obj can be any variable or tuple you want to be accessible in the breakpoint.

    It's particularly helpful to back up to the jl_apply frame, from which you can display the arguments to a function using, e.g.,

    (gdb) call jl_(args[0])

    Another useful frame is to_function(jl_method_instance_t *li, bool cstyle). The jl_method_instance_t* argument is a struct with a reference to the final AST sent into the compiler. However, the AST at this point will usually be compressed; to view the AST, call jl_uncompress_ast and then pass the result to jl_:

    #2  0x00007ffff7928bf7 in to_function (li=0x2812060, cstyle=false) at codegen.cpp:584
    -584          abort();
    -(gdb) p jl_(jl_uncompress_ast(li, li->ast))

    Inserting breakpoints upon certain conditions

    Loading a particular file

    Let's say the file is sysimg.jl:

    (gdb) break jl_load if strcmp(fname, "sysimg.jl")==0

    Calling a particular method

    (gdb) break jl_apply_generic if strcmp((char*)(jl_symbol_name)(jl_gf_mtable(F)->name), "method_to_break")==0

    Since this function is used for every call, you will make everything 1000x slower if you do this.

    Dealing with signals

    Julia requires a few signal to function property. The profiler uses SIGUSR2 for sampling and the garbage collector uses SIGSEGV for threads synchronization. If you are debugging some code that uses the profiler or multiple threads, you may want to let the debugger ignore these signals since they can be triggered very often during normal operations. The command to do this in GDB is (replace SIGSEGV with SIGUSRS or other signals you want to ignore):

    (gdb) handle SIGSEGV noprint nostop pass

    The corresponding LLDB command is (after the process is started):

    (lldb) pro hand -p true -s false -n false SIGSEGV

    If you are debugging a segfault with threaded code, you can set a breakpoint on jl_critical_error (sigdie_handler should also work on Linux and BSD) in order to only catch the actual segfault rather than the GC synchronization points.

    Debugging during Julia's build process (bootstrap)

    Errors that occur during make need special handling. Julia is built in two stages, constructing sys0 and sys.ji. To see what commands are running at the time of failure, use make VERBOSE=1.

    At the time of this writing, you can debug build errors during the sys0 phase from the base directory using:

    julia/base$ gdb --args ../usr/bin/julia-debug -C native --build ../usr/lib/julia/sys0 sysimg.jl

    You might need to delete all the files in usr/lib/julia/ to get this to work.

    You can debug the sys.ji phase using:

    julia/base$ gdb --args ../usr/bin/julia-debug -C native --build ../usr/lib/julia/sys -J ../usr/lib/julia/sys0.ji sysimg.jl

    By default, any errors will cause Julia to exit, even under gdb. To catch an error "in the act", set a breakpoint in jl_error (there are several other useful spots, for specific kinds of failures, including: jl_too_few_args, jl_too_many_args, and jl_throw).

    Once an error is caught, a useful technique is to walk up the stack and examine the function by inspecting the related call to jl_apply. To take a real-world example:

    Breakpoint 1, jl_throw (e=0x7ffdf42de400) at task.c:802
    -802 {
    -(gdb) p jl_(e)
    -ErrorException("auto_unbox: unable to determine argument type")
    -$2 = void
    -(gdb) bt 10
    -#0  jl_throw (e=0x7ffdf42de400) at task.c:802
    -#1  0x00007ffff65412fe in jl_error (str=0x7ffde56be000 <_j_str267> "auto_unbox:
    -   unable to determine argument type")
    -   at builtins.c:39
    -#2  0x00007ffde56bd01a in julia_convert_16886 ()
    -#3  0x00007ffff6541154 in jl_apply (f=0x7ffdf367f630, args=0x7fffffffc2b0, nargs=2) at julia.h:1281
    -...

    The most recent jl_apply is at frame #3, so we can go back there and look at the AST for the function julia_convert_16886. This is the uniqued name for some method of convert. f in this frame is a jl_function_t*, so we can look at the type signature, if any, from the specTypes field:

    (gdb) f 3
    -#3  0x00007ffff6541154 in jl_apply (f=0x7ffdf367f630, args=0x7fffffffc2b0, nargs=2) at julia.h:1281
    -1281            return f->fptr((jl_value_t*)f, args, nargs);
    -(gdb) p f->linfo->specTypes
    -$4 = (jl_tupletype_t *) 0x7ffdf39b1030
    -(gdb) p jl_( f->linfo->specTypes )
    -Tuple{Type{Float32}, Float64}           # <-- type signature for julia_convert_16886

    Then, we can look at the AST for this function:

    (gdb) p jl_( jl_uncompress_ast(f->linfo, f->linfo->ast) )
    -Expr(:lambda, Array{Any, 1}[:#s29, :x], Array{Any, 1}[Array{Any, 1}[], Array{Any, 1}[Array{Any, 1}[:#s29, :Any, 0], Array{Any, 1}[:x, :Any, 0]], Array{Any, 1}[], 0], Expr(:body,
    -Expr(:line, 90, :float.jl)::Any,
    -Expr(:return, Expr(:call, :box, :Float32, Expr(:call, :fptrunc, :Float32, :x)::Any)::Any)::Any)::Any)::Any

    Finally, and perhaps most usefully, we can force the function to be recompiled in order to step through the codegen process. To do this, clear the cached functionObject from the jl_lamdbda_info_t*:

    (gdb) p f->linfo->functionObject
    -$8 = (void *) 0x1289d070
    -(gdb) set f->linfo->functionObject = NULL

    Then, set a breakpoint somewhere useful (e.g. emit_function, emit_expr, emit_call, etc.), and run codegen:

    (gdb) p jl_compile(f)
    -... # your breakpoint here

    Debugging precompilation errors

    Module precompilation spawns a separate Julia process to precompile each module. Setting a breakpoint or catching failures in a precompile worker requires attaching a debugger to the worker. The easiest approach is to set the debugger watch for new process launches matching a given name. For example:

    (gdb) attach -w -n julia-debug

    or:

    (lldb) process attach -w -n julia-debug

    Then run a script/command to start precompilation. As described earlier, use conditional breakpoints in the parent process to catch specific file-loading events and narrow the debugging window. (some operating systems may require alternative approaches, such as following each fork from the parent process)

    Mozilla's Record and Replay Framework (rr)

    Julia now works out of the box with rr, the lightweight recording and deterministic debugging framework from Mozilla. This allows you to replay the trace of an execution deterministically. The replayed execution's address spaces, register contents, syscall data etc are exactly the same in every run.

    A recent version of rr (3.1.0 or higher) is required.

    diff --git a/julia-0.6.3/share/doc/julia/html/en/devdocs/eval.html b/julia-0.6.3/share/doc/julia/html/en/devdocs/eval.html deleted file mode 100644 index 2f2b179..0000000 --- a/julia-0.6.3/share/doc/julia/html/en/devdocs/eval.html +++ /dev/null @@ -1,9 +0,0 @@ - -Eval of Julia code · The Julia Language

    Eval of Julia code

    Eval of Julia code

    One of the hardest parts about learning how the Julia Language runs code is learning how all of the pieces work together to execute a block of code.

    Each chunk of code typically makes a trip through many steps with potentially unfamiliar names, such as (in no particular order): flisp, AST, C++, LLVM, eval, typeinf, macroexpand, sysimg (or system image), bootstrapping, compile, parse, execute, JIT, interpret, box, unbox, intrinsic function, and primitive function, before turning into the desired result (hopefully).

    Julia Execution

    The 10,000 foot view of the whole process is as follows:

    1. The user starts julia.

    2. The C function main() from ui/repl.c gets called. This function processes the command line arguments, filling in the jl_options struct and setting the variable ARGS. It then initializes Julia (by calling julia_init in task.c, which may load a previously compiled sysimg). Finally, it passes off control to Julia by calling Base._start().

    3. When _start() takes over control, the subsequent sequence of commands depends on the command line arguments given. For example, if a filename was supplied, it will proceed to execute that file. Otherwise, it will start an interactive REPL.

    4. Skipping the details about how the REPL interacts with the user, let's just say the program ends up with a block of code that it wants to run.

    5. If the block of code to run is in a file, jl_load(char *filename) gets invoked to load the file and parse it. Each fragment of code is then passed to eval to execute.

    6. Each fragment of code (or AST), is handed off to eval() to turn into results.

    7. eval() takes each code fragment and tries to run it in jl_toplevel_eval_flex().

    8. jl_toplevel_eval_flex() decides whether the code is a "toplevel" action (such as using or module), which would be invalid inside a function. If so, it passes off the code to the toplevel interpreter.

    9. jl_toplevel_eval_flex() then expands the code to eliminate any macros and to "lower" the AST to make it simpler to execute.

    10. jl_toplevel_eval_flex() then uses some simple heuristics to decide whether to JIT compiler the AST or to interpret it directly.

    11. The bulk of the work to interpret code is handled by eval in interpreter.c.

    12. If instead, the code is compiled, the bulk of the work is handled by codegen.cpp. Whenever a Julia function is called for the first time with a given set of argument types, type inference will be run on that function. This information is used by the codegen step to generate faster code.

    13. Eventually, the user quits the REPL, or the end of the program is reached, and the _start() method returns.

    14. Just before exiting, main() calls jl_atexit_hook(exit_code). This calls Base._atexit() (which calls any functions registered to atexit() inside Julia). Then it calls jl_gc_run_all_finalizers(). Finally, it gracefully cleans up all libuv handles and waits for them to flush and close.

    Parsing

    The Julia parser is a small lisp program written in femtolisp, the source-code for which is distributed inside Julia in src/flisp.

    The interface functions for this are primarily defined in jlfrontend.scm. The code in ast.c handles this handoff on the Julia side.

    The other relevant files at this stage are julia-parser.scm, which handles tokenizing Julia code and turning it into an AST, and julia-syntax.scm, which handles transforming complex AST representations into simpler, "lowered" AST representations which are more suitable for analysis and execution.

    Macro Expansion

    When eval() encounters a macro, it expands that AST node before attempting to evaluate the expression. Macro expansion involves a handoff from eval() (in Julia), to the parser function jl_macroexpand() (written in flisp) to the Julia macro itself (written in - what else - Julia) via fl_invoke_julia_macro(), and back.

    Typically, macro expansion is invoked as a first step during a call to expand()/jl_expand(), although it can also be invoked directly by a call to macroexpand()/jl_macroexpand().

    Type Inference

    Type inference is implemented in Julia by typeinf() in inference.jl. Type inference is the process of examining a Julia function and determining bounds for the types of each of its variables, as well as bounds on the type of the return value from the function. This enables many future optimizations, such as unboxing of known immutable values, and compile-time hoisting of various run-time operations such as computing field offsets and function pointers. Type inference may also include other steps such as constant propagation and inlining.

    JIT Code Generation

    Codegen is the process of turning a Julia AST into native machine code.

    The JIT environment is initialized by an early call to jl_init_codegen in codegen.cpp.

    On demand, a Julia method is converted into a native function by the function emit_function(jl_method_instance_t*). (note, when using the MCJIT (in LLVM v3.4+), each function must be JIT into a new module.) This function recursively calls emit_expr() until the entire function has been emitted.

    Much of the remaining bulk of this file is devoted to various manual optimizations of specific code patterns. For example, emit_known_call() knows how to inline many of the primitive functions (defined in builtins.c) for various combinations of argument types.

    Other parts of codegen are handled by various helper files:

    • debuginfo.cpp

      Handles backtraces for JIT functions

    • ccall.cpp

      Handles the ccall and llvmcall FFI, along with various abi_*.cpp files

    • intrinsics.cpp

      Handles the emission of various low-level intrinsic functions

    System Image

    The system image is a precompiled archive of a set of Julia files. The sys.ji file distributed with Julia is one such system image, generated by executing the file sysimg.jl, and serializing the resulting environment (including Types, Functions, Modules, and all other defined values) into a file. Therefore, it contains a frozen version of the Main, Core, and Base modules (and whatever else was in the environment at the end of bootstrapping). This serializer/deserializer is implemented by jl_save_system_image/jl_restore_system_image in dump.c.

    If there is no sysimg file (jl_options.image_file == NULL), this also implies that --build was given on the command line, so the final result should be a new sysimg file. During Julia initialization, minimal Core and Main modules are created. Then a file named boot.jl is evaluated from the current directory. Julia then evaluates any file given as a command line argument until it reaches the end. Finally, it saves the resulting environment to a "sysimg" file for use as a starting point for a future Julia run.

    diff --git a/julia-0.6.3/share/doc/julia/html/en/devdocs/functions.html b/julia-0.6.3/share/doc/julia/html/en/devdocs/functions.html deleted file mode 100644 index 92706d8..0000000 --- a/julia-0.6.3/share/doc/julia/html/en/devdocs/functions.html +++ /dev/null @@ -1,56 +0,0 @@ - -Julia Functions · The Julia Language

    Julia Functions

    Julia Functions

    This document will explain how functions, method definitions, and method tables work.

    Method Tables

    Every function in Julia is a generic function. A generic function is conceptually a single function, but consists of many definitions, or methods. The methods of a generic function are stored in a method table. Method tables (type MethodTable) are associated with TypeNames. A TypeName describes a family of parameterized types. For example Complex{Float32} and Complex{Float64} share the same Complex type name object.

    All objects in Julia are potentially callable, because every object has a type, which in turn has a TypeName.

    Function calls

    Given the call f(x,y), the following steps are performed: first, the method table to use is accessed as typeof(f).name.mt. Second, an argument tuple type is formed, Tuple{typeof(f), typeof(x), typeof(y)}. Note that the type of the function itself is the first element. This is because the type might have parameters, and so needs to take part in dispatch. This tuple type is looked up in the method table.

    This dispatch process is performed by jl_apply_generic, which takes two arguments: a pointer to an array of the values f, x, and y, and the number of values (in this case 3).

    Throughout the system, there are two kinds of APIs that handle functions and argument lists: those that accept the function and arguments separately, and those that accept a single argument structure. In the first kind of API, the "arguments" part does not contain information about the function, since that is passed separately. In the second kind of API, the function is the first element of the argument structure.

    For example, the following function for performing a call accepts just an args pointer, so the first element of the args array will be the function to call:

    jl_value_t *jl_apply(jl_value_t **args, uint32_t nargs)

    This entry point for the same functionality accepts the function separately, so the args array does not contain the function:

    jl_value_t *jl_call(jl_function_t *f, jl_value_t **args, int32_t nargs);

    Adding methods

    Given the above dispatch process, conceptually all that is needed to add a new method is (1) a tuple type, and (2) code for the body of the method. jl_method_def implements this operation. jl_first_argument_datatype is called to extract the relevant method table from what would be the type of the first argument. This is much more complicated than the corresponding procedure during dispatch, since the argument tuple type might be abstract. For example, we can define:

    (::Union{Foo{Int},Foo{Int8}})(x) = 0

    which works since all possible matching methods would belong to the same method table.

    Creating generic functions

    Since every object is callable, nothing special is needed to create a generic function. Therefore jl_new_generic_function simply creates a new singleton (0 size) subtype of Function and returns its instance. A function can have a mnemonic "display name" which is used in debug info and when printing objects. For example the name of Base.sin is sin. By convention, the name of the created type is the same as the function name, with a # prepended. So typeof(sin) is Base.#sin.

    Closures

    A closure is simply a callable object with field names corresponding to captured variables. For example, the following code:

    function adder(x)
    -    return y->x+y
    -end

    is lowered to (roughly):

    struct ##1{T}
    -    x::T
    -end
    -
    -(_::##1)(y) = _.x + y
    -
    -function adder(x)
    -    return ##1(x)
    -end

    Constructors

    A constructor call is just a call to a type. The type of most types is DataType, so the method table for DataType contains most constructor definitions. One wrinkle is the fallback definition that makes all types callable via convert:

    (::Type{T}){T}(args...) = convert(T, args...)::T

    In this definition the function type is abstract, which is not normally supported. To make this work, all subtypes of Type (Type, UnionAll, Union, and DataType) currently share a method table via special arrangement.

    Builtins

    The "builtin" functions, defined in the Core module, are:

    === typeof sizeof issubtype isa typeassert throw tuple getfield setfield! fieldtype
    -nfields isdefined arrayref arrayset arraysize applicable invoke apply_type _apply
    -_expr svec

    These are all singleton objects whose types are subtypes of Builtin, which is a subtype of Function. Their purpose is to expose entry points in the run time that use the "jlcall" calling convention:

    jl_value_t *(jl_value_t*, jl_value_t**, uint32_t)

    The method tables of builtins are empty. Instead, they have a single catch-all method cache entry (Tuple{Vararg{Any}}) whose jlcall fptr points to the correct function. This is kind of a hack but works reasonably well.

    Keyword arguments

    Keyword arguments work by associating a special, hidden function object with each method table that has definitions with keyword arguments. This function is called the "keyword argument sorter" or "keyword sorter", or "kwsorter", and is stored in the kwsorter field of MethodTable objects. Every definition in the kwsorter function has the same arguments as some definition in the normal method table, except with a single Array argument prepended. This array contains alternating symbols and values that represent the passed keyword arguments. The kwsorter's job is to move keyword arguments into their canonical positions based on name, plus evaluate and substite any needed default value expressions. The result is a normal positional argument list, which is then passed to yet another function.

    The easiest way to understand the process is to look at how a keyword argument method definition is lowered. The code:

    function circle(center, radius; color = black, fill::Bool = true, options...)
    -    # draw
    -end

    actually produces three method definitions. The first is a function that accepts all arguments (including keywords) as positional arguments, and includes the code for the method body. It has an auto-generated name:

    function #circle#1(color, fill::Bool, options, circle, center, radius)
    -    # draw
    -end

    The second method is an ordinary definition for the original circle function, which handles the case where no keyword arguments are passed:

    function circle(center, radius)
    -    #circle#1(black, true, Any[], circle, center, radius)
    -end

    This simply dispatches to the first method, passing along default values. Finally there is the kwsorter definition:

    function (::Core.kwftype(typeof(circle)))(kw::Array, circle, center, radius)
    -    options = Any[]
    -    color = arg associated with :color, or black if not found
    -    fill = arg associated with :fill, or true if not found
    -    # push remaining elements of kw into options array
    -    #circle#1(color, fill, options, circle, center, radius)
    -end

    The front end generates code to loop over the kw array and pick out arguments in the right order, evaluating default expressions when an argument is not found.

    The function Core.kwftype(t) fetches (and creates, if necessary) the field t.name.mt.kwsorter.

    This design has the feature that call sites that don't use keyword arguments require no special handling; everything works as if they were not part of the language at all. Call sites that do use keyword arguments are dispatched directly to the called function's kwsorter. For example the call:

    circle((0,0), 1.0, color = red; other...)

    is lowered to:

    kwfunc(circle)(Any[:color,red,other...], circle, (0,0), 1.0)

    The unpacking procedure represented here as other... actually further unpacks each element of other, expecting each one to contain two values (a symbol and a value). kwfunc (also in Core) fetches the kwsorter for the called function. Notice that the original circle function is passed through, to handle closures.

    Compiler efficiency issues

    Generating a new type for every function has potentially serious consequences for compiler resource use when combined with Julia's "specialize on all arguments by default" design. Indeed, the initial implementation of this design suffered from much longer build and test times, higher memory use, and a system image nearly 2x larger than the baseline. In a naive implementation, the problem is bad enough to make the system nearly unusable. Several significant optimizations were needed to make the design practical.

    The first issue is excessive specialization of functions for different values of function-valued arguments. Many functions simply "pass through" an argument to somewhere else, e.g. to another function or to a storage location. Such functions do not need to be specialized for every closure that might be passed in. Fortunately this case is easy to distinguish by simply considering whether a function calls one of its arguments (i.e. the argument appears in "head position" somewhere). Performance-critical higher-order functions like map certainly call their argument function and so will still be specialized as expected. This optimization is implemented by recording which arguments are called during the analyze-variables pass in the front end. When cache_method sees an argument in the Function type hierarchy passed to a slot declared as Any or Function, it pretends the slot was declared as ANY (the "don't specialize" hint). This heuristic seems to be extremely effective in practice.

    The next issue concerns the structure of method cache hash tables. Empirical studies show that the vast majority of dynamically-dispatched calls involve one or two arguments. In turn, many of these cases can be resolved by considering only the first argument. (Aside: proponents of single dispatch would not be surprised by this at all. However, this argument means "multiple dispatch is easy to optimize in practice", and that we should therefore use it, not "we should use single dispatch"!) So the method cache uses the type of the first argument as its primary key. Note, however, that this corresponds to the second element of the tuple type for a function call (the first element being the type of the function itself). Typically, type variation in head position is extremely low – indeed, the majority of functions belong to singleton types with no parameters. However, this is not the case for constructors, where a single method table holds constructors for every type. Therefore the Type method table is special-cased to use the first tuple type element instead of the second.

    The front end generates type declarations for all closures. Initially, this was implemented by generating normal type declarations. However, this produced an extremely large number of constructors, all of which were trivial (simply passing all arguments through to new). Since methods are partially ordered, inserting all of these methods is O(n^2), plus there are just too many of them to keep around. This was optimized by generating composite_type expressions directly (bypassing default constructor generation), and using new directly to create closure instances. Not the prettiest thing ever, but you do what you gotta do.

    The next problem was the @test macro, which generated a 0-argument closure for each test case. This is not really necessary, since each test case is simply run once in place. Therefore I modified @test to expand to a try-catch block that records the test result (true, false, or exception raised) and calls the test suite handler on it.

    However this caused a new problem. When many tests are grouped together in a single function, e.g. a single top level expression, or some other test grouping function, that function could have a very large number of exception handlers. This triggered a kind of dataflow analysis worst case, where type inference spun around for minutes enumerating possible paths through the forest of handlers. This was fixed by simply bailing out of type inference when it encounters more than some number of handlers (currently 25). Presumably no performance-critical function will have more than 25 exception handlers. If one ever does, I'm willing to raise the limit to 26.

    A minor issue occurs during the bootstrap process due to storing all constructors in a single method table. In the second bootstrap step, where inference.ji is compiled using inference0.ji, constructors for inference0's types remain in the table, so there are still references to the old inference module and inference.ji is 2x the size it should be. This was fixed in dump.c by filtering definitions from "replaced modules" out of method tables and caches before saving a system image. A "replaced module" is one that satisfies the condition m != jl_get_global(m->parent, m->name) – in other words, some newer module has taken its name and place.

    Another type inference worst case was triggered by the following code from the QuadGK.jl package, formerly part of Base:

    function do_quadgk(f, s, n, ::Type{Tw}, abstol, reltol, maxevals, nrm) where Tw
    -    if eltype(s) <: Real # check for infinite or semi-infinite intervals
    -        s1 = s[1]; s2 = s[end]; inf1 = isinf(s1); inf2 = isinf(s2)
    -        if inf1 || inf2
    -            if inf1 && inf2 # x = t/(1-t^2) coordinate transformation
    -                return do_quadgk(t -> begin t2 = t*t; den = 1 / (1 - t2);
    -                                            f(t*den) * (1+t2)*den*den; end,
    -                                 map(x -> isinf(x) ? copysign(one(x), x) : 2x / (1+hypot(1,2x)), s),
    -                                 n, Tw, abstol, reltol, maxevals, nrm)
    -            end
    -            s0,si = inf1 ? (s2,s1) : (s1,s2)
    -            if si < 0 # x = s0 - t/(1-t)
    -                return do_quadgk(t -> begin den = 1 / (1 - t);
    -                                            f(s0 - t*den) * den*den; end,
    -                                 reverse!(map(x -> 1 / (1 + 1 / (s0 - x)), s)),
    -                                 n, Tw, abstol, reltol, maxevals, nrm)
    -            else # x = s0 + t/(1-t)
    -                return do_quadgk(t -> begin den = 1 / (1 - t);
    -                                            f(s0 + t*den) * den*den; end,
    -                                 map(x -> 1 / (1 + 1 / (x - s0)), s),
    -                                 n, Tw, abstol, reltol, maxevals, nrm)
    -            end
    -        end
    -    end

    This code has a 3-way tail recursion, where each call wraps the current function argument f in a different new closure. Inference must consider 3^n (where n is the call depth) possible signatures. This blows up way too quickly, so logic was added to typeinf_uncached to immediately widen any argument that is a subtype of Function and that grows in depth down the stack.

    diff --git a/julia-0.6.3/share/doc/julia/html/en/devdocs/init.html b/julia-0.6.3/share/doc/julia/html/en/devdocs/init.html deleted file mode 100644 index 947a491..0000000 --- a/julia-0.6.3/share/doc/julia/html/en/devdocs/init.html +++ /dev/null @@ -1,18 +0,0 @@ - -Initialization of the Julia runtime · The Julia Language

    Initialization of the Julia runtime

    Initialization of the Julia runtime

    How does the Julia runtime execute julia -e 'println("Hello World!")' ?

    main()

    Execution starts at main() in ui/repl.c.

    main() calls libsupport_init() to set the C library locale and to initialize the "ios" library (see ios_init_stdstreams() and Legacy ios.c library).

    Next parse_opts() is called to process command line options. Note that parse_opts() only deals with options that affect code generation or early initialization. Other options are handled later by process_options() in base/client.jl.

    parse_opts() stores command line options in the global jl_options struct.

    julia_init()

    julia_init() in task.c is called by main() and calls _julia_init() in init.c.

    _julia_init() begins by calling libsupport_init() again (it does nothing the second time).

    restore_signals() is called to zero the signal handler mask.

    jl_resolve_sysimg_location() searches configured paths for the base system image. See Building the Julia system image.

    jl_gc_init() sets up allocation pools and lists for weak refs, preserved values and finalization.

    jl_init_frontend() loads and initializes a pre-compiled femtolisp image containing the scanner/parser.

    jl_init_types() creates jl_datatype_t type description objects for the built-in types defined in julia.h. e.g.

    jl_any_type = jl_new_abstracttype(jl_symbol("Any"), NULL, jl_null);
    -jl_any_type->super = jl_any_type;
    -
    -jl_type_type = jl_new_abstracttype(jl_symbol("Type"), jl_any_type, jl_null);
    -
    -jl_int32_type = jl_new_bitstype(jl_symbol("Int32"),
    -                                jl_any_type, jl_null, 32);

    jl_init_tasks() creates the jl_datatype_t* jl_task_type object; initializes the global jl_root_task struct; and sets jl_current_task to the root task.

    jl_init_codegen() initializes the LLVM library.

    jl_init_serializer() initializes 8-bit serialization tags for 256 frequently used jl_value_t values. The serialization mechanism uses these tags as shorthand (in lieu of storing whole objects) to save storage space.

    If there is no sysimg file (!jl_options.image_file) then the Core and Main modules are created and boot.jl is evaluated:

    jl_core_module = jl_new_module(jl_symbol("Core")) creates the Julia Core module.

    jl_init_intrinsic_functions() creates a new Julia module Intrinsics containing constant jl_intrinsic_type symbols. These define an integer code for each intrinsic function. emit_intrinsic() translates these symbols into LLVM instructions during code generation.

    jl_init_primitives() hooks C functions up to Julia function symbols. e.g. the symbol Base.is() is bound to C function pointer jl_f_is() by calling add_builtin_func("eval", jl_f_top_eval).

    jl_new_main_module() creates the global "Main" module and sets jl_current_task->current_module = jl_main_module.

    Note: _julia_init() then sets jl_root_task->current_module = jl_core_module. jl_root_task is an alias of jl_current_task at this point, so the current_module set by jl_new_main_module() above is overwritten.

    jl_load("boot.jl", sizeof("boot.jl")) calls jl_parse_eval_all which repeatedly calls jl_toplevel_eval_flex() to execute boot.jl. <!– TODO – drill down into eval? –>

    jl_get_builtin_hooks() initializes global C pointers to Julia globals defined in boot.jl.

    jl_init_box_caches() pre-allocates global boxed integer value objects for values up to 1024. This speeds up allocation of boxed ints later on. e.g.:

    jl_value_t *jl_box_uint8(uint32_t x)
    -{
    -    return boxed_uint8_cache[(uint8_t)x];
    -}

    _julia_init() iterates over the jl_core_module->bindings.table looking for jl_datatype_t values and sets the type name's module prefix to jl_core_module.

    jl_add_standard_imports(jl_main_module) does "using Base" in the "Main" module.

    Note: _julia_init() now reverts to jl_root_task->current_module = jl_main_module as it was before being set to jl_core_module above.

    Platform specific signal handlers are initialized for SIGSEGV (OSX, Linux), and SIGFPE (Windows).

    Other signals (SIGINFO, SIGBUS, SIGILL, SIGTERM, SIGABRT, SIGQUIT, SIGSYS and SIGPIPE) are hooked up to sigdie_handler() which prints a backtrace.

    jl_init_restored_modules() calls jl_module_run_initializer() for each deserialized module to run the __init__() function.

    Finally sigint_handler() is hooked up to SIGINT and calls jl_throw(jl_interrupt_exception).

    _julia_init() then returns back to main() in ui/repl.c and main() calls true_main(argc, (char**)argv).

    true_main()

    true_main() loads the contents of argv[] into Base.ARGS.

    If a .jl "program" file was supplied on the command line, then exec_program() calls jl_load(program,len) which calls jl_parse_eval_all which repeatedly calls jl_toplevel_eval_flex() to execute the program.

    However, in our example (julia -e 'println("Hello World!")'), jl_get_global(jl_base_module, jl_symbol("_start")) looks up Base._start and jl_apply() executes it.

    Base._start

    Base._start calls Base.process_options which calls jl_parse_input_line("println("Hello World!")") to create an expression object and Base.eval() to execute it.

    Base.eval

    Base.eval() was mapped to jl_f_top_eval by jl_init_primitives().

    jl_f_top_eval() calls jl_toplevel_eval_in(jl_main_module, ex), where ex is the parsed expression println("Hello World!").

    jl_toplevel_eval_in() calls jl_toplevel_eval_flex() which calls eval() in interpreter.c.

    The stack dump below shows how the interpreter works its way through various methods of Base.println() and Base.print() before arriving at write(s::IO, a::Array{T}) where T which does ccall(jl_uv_write()).

    jl_uv_write() calls uv_write() to write "Hello World!" to JL_STDOUT. See Libuv wrappers for stdio.:

    Hello World!
    Stack frameSource codeNotes
    jl_uv_write()jl_uv.ccalled though ccall
    julia_write_282942stream.jlfunction write!(s::IO, a::Array{T}) where T
    julia_print_284639ascii.jlprint(io::IO, s::String) = (write(io, s); nothing)
    jlcall_print_284639  
    jl_apply()julia.h 
    jl_trampoline()builtins.c 
    jl_apply()julia.h 
    jl_apply_generic()gf.cBase.print(Base.TTY, String)
    jl_apply()julia.h 
    jl_trampoline()builtins.c 
    jl_apply()julia.h 
    jl_apply_generic()gf.cBase.print(Base.TTY, String, Char, Char...)
    jl_apply()julia.h 
    jl_f_apply()builtins.c 
    jl_apply()julia.h 
    jl_trampoline()builtins.c 
    jl_apply()julia.h 
    jl_apply_generic()gf.cBase.println(Base.TTY, String, String...)
    jl_apply()julia.h 
    jl_trampoline()builtins.c 
    jl_apply()julia.h 
    jl_apply_generic()gf.cBase.println(String,)
    jl_apply()julia.h 
    do_call()interpreter.c 
    eval()interpreter.c 
    jl_interpret_toplevel_expr()interpreter.c 
    jl_toplevel_eval_flex()toplevel.c 
    jl_toplevel_eval()toplevel.c 
    jl_toplevel_eval_in()builtins.c 
    jl_f_top_eval()builtins.c 

    Since our example has just one function call, which has done its job of printing "Hello World!", the stack now rapidly unwinds back to main().

    jl_atexit_hook()

    main() calls jl_atexit_hook(). This calls _atexit for each module, then calls jl_gc_run_all_finalizers() and cleans up libuv handles.

    julia_save()

    Finally, main() calls julia_save(), which if requested on the command line, saves the runtime state to a new system image. See jl_compile_all() and jl_save_system_image().

    diff --git a/julia-0.6.3/share/doc/julia/html/en/devdocs/libgit2.html b/julia-0.6.3/share/doc/julia/html/en/devdocs/libgit2.html deleted file mode 100644 index 8a92c2b..0000000 --- a/julia-0.6.3/share/doc/julia/html/en/devdocs/libgit2.html +++ /dev/null @@ -1,151 +0,0 @@ - -Base.LibGit2 · The Julia Language

    Base.LibGit2

    Base.LibGit2

    The LibGit2 module provides bindings to libgit2, a portable C library that implements core functionality for the Git version control system. These bindings are currently used to power Julia's package manager. It is expected that this module will eventually be moved into a separate package.

    Functionality

    Some of this documentation assumes some prior knowledge of the libgit2 API. For more information on some of the objects and methods referenced here, consult the upstream libgit2 API reference.

    Abstract credentials payload

    source
    LibGit2.Buffer

    A data buffer for exporting data from libgit2. Matches the git_buf struct.

    When fetching data from LibGit2, a typical usage would look like:

    buf_ref = Ref(Buffer())
    -@check ccall(..., (Ptr{Buffer},), buf_ref)
    -# operation on buf_ref
    -free(buf_ref)

    In particular, note that LibGit2.free should be called afterward on the Ref object.

    source

    Credentials that support caching

    source
    LibGit2.CheckoutOptions

    Matches the git_checkout_options struct.

    source
    LibGit2.CloneOptions

    Matches the git_clone_options struct.

    source
    LibGit2.DiffDelta

    Description of changes to one entry. Matches the git_diff_delta struct.

    The fields represent:

    • status: One of Consts.DELTA_STATUS, indicating whether the file has been added/modified/deleted.

    • flags: Flags for the delta and the objects on each side. Determines whether to treat the file(s) as binary/text, whether they exist on each side of the diff, and whether the object ids are known to be correct.

    • similarity: Used to indicate if a file has been renamed or copied.

    • nfiles: The number of files in the delta (for instance, if the delta was run on a submodule commit id, it may contain more than one file).

    • old_file: A DiffFile containing information about the file(s) before the changes.

    • new_file: A DiffFile containing information about the file(s) after the changes.

    source
    LibGit2.DiffFile

    Description of one side of a delta. Matches the git_diff_file struct.

    source
    LibGit2.DiffOptionsStruct

    Matches the git_diff_options struct.

    source
    LibGit2.FetchHead

    Contains the information about HEAD during a fetch, including the name and URL of the branch fetched from, the oid of the HEAD, and whether the fetched HEAD has been merged locally.

    source
    LibGit2.FetchOptions

    Matches the git_fetch_options struct.

    source
    GitBlob(repo::GitRepo, hash::AbstractGitHash)
    -GitBlob(repo::GitRepo, spec::AbstractString)

    Return a GitBlob object from repo specified by hash/spec.

    • hash is a full (GitHash) or partial (GitShortHash) hash.

    • spec is a textual specification: see the git docs for a full list.

    source
    GitCommit(repo::GitRepo, hash::AbstractGitHash)
    -GitCommit(repo::GitRepo, spec::AbstractString)

    Return a GitCommit object from repo specified by hash/spec.

    • hash is a full (GitHash) or partial (GitShortHash) hash.

    • spec is a textual specification: see the git docs for a full list.

    source
    GitHash

    A git object identifier, based on the sha-1 hash. It is a 20 byte string (40 hex digits) used to identify a GitObject in a repository.

    source
    GitObject(repo::GitRepo, hash::AbstractGitHash)
    -GitObject(repo::GitRepo, spec::AbstractString)

    Return the specified object (GitCommit, GitBlob, GitTree or GitTag) from repo specified by hash/spec.

    • hash is a full (GitHash) or partial (GitShortHash) hash.

    • spec is a textual specification: see the git docs for a full list.

    source
    GitRemote(repo::GitRepo, rmt_name::AbstractString, rmt_url::AbstractString) -> GitRemote

    Look up a remote git repository using its name and URL. Uses the default fetch refspec.

    Example

    repo = LibGit2.init(repo_path)
    -remote = LibGit2.GitRemote(repo, "upstream", repo_url)
    source
    GitRemote(repo::GitRepo, rmt_name::AbstractString, rmt_url::AbstractString, fetch_spec::AbstractString) -> GitRemote

    Look up a remote git repository using the repository's name and URL, as well as specifications for how to fetch from the remote (e.g. which remote branch to fetch from).

    Example

    repo = LibGit2.init(repo_path)
    -refspec = "+refs/heads/mybranch:refs/remotes/origin/mybranch"
    -remote = LibGit2.GitRemote(repo, "upstream", repo_url, refspec)
    source
    GitRemoteAnon(repo::GitRepo, url::AbstractString) -> GitRemote

    Look up a remote git repository using only its URL, not its name.

    Example

    repo = LibGit2.init(repo_path)
    -remote = LibGit2.GitRemoteAnon(repo, repo_url)
    source
    LibGit2.GitRepo(path::AbstractString)

    Opens a git repository at path.

    source
    LibGit2.GitRepoExt(path::AbstractString, flags::Cuint = Cuint(Consts.REPOSITORY_OPEN_DEFAULT))

    Opens a git repository at path with extended controls (for instance, if the current user must be a member of a special access group to read path).

    source
    GitShortHash

    This is a shortened form of GitHash, which can be used to identify a git object when it is unique.

    Internally it is stored as two fields: a full-size GitHash (hash) and a length (len). Only the initial len hex digits of hash are used.

    source
    LibGit2.GitSignature

    This is a Julia wrapper around a pointer to a git_signature object.

    source
    LibGit2.GitStatus(repo::GitRepo; status_opts=StatusOptions())

    Collect information about the status of each file in the git repository repo (e.g. is the file modified, staged, etc.). status_opts can be used to set various options, for instance whether or not to look at untracked files or whether to include submodules or not.

    source
    GitTag(repo::GitRepo, hash::AbstractGitHash)
    -GitTag(repo::GitRepo, spec::AbstractString)

    Return a GitTag object from repo specified by hash/spec.

    • hash is a full (GitHash) or partial (GitShortHash) hash.

    • spec is a textual specification: see the git docs for a full list.

    source
    GitTree(repo::GitRepo, hash::AbstractGitHash)
    -GitTree(repo::GitRepo, spec::AbstractString)

    Return a GitTree object from repo specified by hash/spec.

    • hash is a full (GitHash) or partial (GitShortHash) hash.

    • spec is a textual specification: see the git docs for a full list.

    source
    LibGit2.IndexEntry

    In-memory representation of a file entry in the index. Matches the git_index_entry struct.

    source
    LibGit2.IndexTime

    Matches the git_index_time struct.

    source
    LibGit2.MergeOptions

    Matches the git_merge_options struct.

    source
    LibGit2.ProxyOptions

    Options for connecting through a proxy.

    Matches the git_proxy_options struct.

    source
    LibGit2.PushOptions

    Matches the git_push_options struct.

    source
    LibGit2.RebaseOperation

    Describes a single instruction/operation to be performed during the rebase. Matches the git_rebase_operation struct.

    source
    LibGit2.RebaseOptions

    Matches the git_rebase_options struct.

    source
    LibGit2.RemoteCallbacks

    Callback settings. Matches the git_remote_callbacks struct.

    source

    SSH credentials type

    source
    LibGit2.SignatureStruct

    An action signature (e.g. for committers, taggers, etc). Matches the git_signature struct.

    source
    LibGit2.StatusEntry

    Providing the differences between the file as it exists in HEAD and the index, and providing the differences between the index and the working directory. Matches the git_status_entry struct.

    source
    LibGit2.StatusOptions

    Options to control how git_status_foreach_ext() will issue callbacks. Matches the git_status_opt_t struct.

    source
    LibGit2.StrArrayStruct

    A LibGit2 representation of an array of strings. Matches the git_strarray struct.

    When fetching data from LibGit2, a typical usage would look like:

    sa_ref = Ref(StrArrayStruct())
    -@check ccall(..., (Ptr{StrArrayStruct},), sa_ref)
    -res = convert(Vector{String}, sa_ref[])
    -free(sa_ref)

    In particular, note that LibGit2.free should be called afterward on the Ref object.

    Conversely, when passing a vector of strings to LibGit2, it is generally simplest to rely on implicit conversion:

    strs = String[...]
    -@check ccall(..., (Ptr{StrArrayStruct},), strs)

    Note that no call to free is required as the data is allocated by Julia.

    source
    LibGit2.TimeStruct

    Time in a signature. Matches the git_time struct.

    source

    Credentials that support only user and password parameters

    source
    add_fetch!(repo::GitRepo, rmt::GitRemote, fetch_spec::String)

    Add a fetch refspec for the specified rmt. This refspec will contain information about which branch(es) to fetch from.

    Example

    julia> LibGit2.add_fetch!(repo, remote, "upstream");
    -
    -julia> LibGit2.fetch_refspecs(remote)
    -String["+refs/heads/*:refs/remotes/upstream/*"]
    source
    add_push!(repo::GitRepo, rmt::GitRemote, push_spec::String)

    Add a push refspec for the specified rmt. This refspec will contain information about which branch(es) to push to.

    Example

    julia> LibGit2.add_push!(repo, remote, "refs/heads/master");
    -
    -julia> remote = LibGit2.get(LibGit2.GitRemote, repo, branch);
    -
    -julia> LibGit2.push_refspecs(remote)
    -String["refs/heads/master"]
    Note

    You may need to close and reopen the GitRemote in question after updating its push refspecs in order for the change to take effect and for calls to push to work.

    source
    Base.LibGit2.addblob!Function.
    LibGit2.addblob!(repo::GitRepo, path::AbstractString)

    Reads the file at path and adds it to the object database of repo as a loose blob. Returns the GitHash of the resulting blob.

    Example

    hash_str = hex(commit_oid)
    -blob_file = joinpath(repo_path, ".git", "objects", hash_str[1:2], hash_str[3:end])
    -id = LibGit2.addblob!(repo, blob_file)
    source
    Base.LibGit2.authorsFunction.
    authors(repo::GitRepo) -> Vector{Signature}

    Returns all authors of commits to the repo repository.

    Example

    repo = LibGit2.GitRepo(repo_path)
    -repo_file = open(joinpath(repo_path, test_file), "a")
    -
    -println(repo_file, commit_msg)
    -flush(repo_file)
    -LibGit2.add!(repo, test_file)
    -sig = LibGit2.Signature("TEST", "TEST@TEST.COM", round(time(), 0), 0)
    -commit_oid1 = LibGit2.commit(repo, "commit1"; author=sig, committer=sig)
    -println(repo_file, randstring(10))
    -flush(repo_file)
    -LibGit2.add!(repo, test_file)
    -commit_oid2 = LibGit2.commit(repo, "commit2"; author=sig, committer=sig)
    -
    -# will be a Vector of [sig, sig]
    -auths = LibGit2.authors(repo)
    source
    Base.LibGit2.branchFunction.
    branch(repo::GitRepo)

    Equivalent to git branch. Create a new branch from the current HEAD.

    source
    Base.LibGit2.branch!Function.
    branch!(repo::GitRepo, branch_name::AbstractString, commit::AbstractString=""; kwargs...)

    Checkout a new git branch in the repo repository. commit is the GitHash, in string form, which will be the start of the new branch. If commit is an empty string, the current HEAD will be used.

    The keyword arguments are:

    • track::AbstractString="": the name of the remote branch this new branch should track, if any. If empty (the default), no remote branch will be tracked.

    • force::Bool=false: if true, branch creation will be forced.

    • set_head::Bool=true: if true, after the branch creation finishes the branch head will be set as the HEAD of repo.

    Equivalent to git checkout [-b|-B] <branch_name> [<commit>] [--track <track>].

    Example

    repo = LibGit2.GitRepo(repo_path)
    -LibGit2.branch!(repo, "new_branch", set_head=false)
    source
    checkout!(repo::GitRepo, commit::AbstractString=""; force::Bool=true)

    Equivalent to git checkout [-f] --detach <commit>. Checkout the git commit commit (a GitHash in string form) in repo. If force is true, force the checkout and discard any current changes. Note that this detaches the current HEAD.

    Example

    repo = LibGit2.init(repo_path)
    -open(joinpath(LibGit2.path(repo), "file1"), "w") do f
    -    write(f, "111
    -")
    -end
    -LibGit2.add!(repo, "file1")
    -commit_oid = LibGit2.commit(repo, "add file1")
    -open(joinpath(LibGit2.path(repo), "file1"), "w") do f
    -    write(f, "112
    -")
    -end
    -# would fail without the force=true
    -# since there are modifications to the file
    -LibGit2.checkout!(repo, string(commit_oid), force=true)
    source

    Checks if credentials were used

    source

    Checks if credentials were used or failed authentication, see LibGit2.credentials_callback

    source
    Base.LibGit2.cloneFunction.
    clone(repo_url::AbstractString, repo_path::AbstractString; kwargs...)

    Clone a remote repository located at repo_url to the local filesystem location repo_path.

    The keyword arguments are:

    • branch::AbstractString="": which branch of the remote to clone, if not the default repository branch (usually master).

    • isbare::Bool=false: if true, clone the remote as a bare repository, which will make repo_path itself the git directory instead of repo_path/.git. This means that a working tree cannot be checked out. Plays the role of the git CLI argument --bare.

    • remote_cb::Ptr{Void}=C_NULL: a callback which will be used to create the remote before it is cloned. If C_NULL (the default), no attempt will be made to create the remote - it will be assumed to already exist.

    • payload::Nullable{P<:AbstractCredentials}=Nullable{AbstractCredentials}(): provides credentials if necessary, for instance if the remote is a private repository.

    Equivalent to git clone [-b <branch>] [--bare] <repo_url> <repo_path>.

    Examples

    repo_url = "https://github.com/JuliaLang/Example.jl"
    -repo1 = LibGit2.clone(repo_url, "test_path")
    -repo2 = LibGit2.clone(repo_url, "test_path", isbare=true)
    -julia_url = "https://github.com/JuliaLang/julia"
    -julia_repo = LibGit2.clone(julia_url, "julia_path", branch="release-0.6")
    source
    Base.LibGit2.commitFunction.

    Wrapper around git_commit_create

    source

    Commit changes to repository

    source
    LibGit2.commit(rb::GitRebase, sig::GitSignature)

    Commits the current patch to the rebase rb, using sig as the committer. Is silent if the commit has already been applied.

    source
    LibGit2.create_branch(repo::GitRepo, bname::AbstractString, commit_obj::GitCommit; force::Bool=false)

    Create a new branch in the repository repo with name bname, which points to commit commit_obj (which has to be part of repo). If force is true, overwrite an existing branch named bname if it exists. If force is false and a branch already exists named bname, this function will throw an error.

    source

    Credentials callback function

    Function provides different credential acquisition functionality w.r.t. a connection protocol. If a payload is provided then payload_ptr should contain a LibGit2.AbstractCredentials object.

    For LibGit2.Consts.CREDTYPE_USERPASS_PLAINTEXT type, if the payload contains fields: user & pass, they are used to create authentication credentials. Empty user name and password trigger an authentication error.

    For LibGit2.Consts.CREDTYPE_SSH_KEY type, if the payload contains fields: user, prvkey, pubkey & pass, they are used to create authentication credentials. Empty user name triggers an authentication error.

    Credentials are checked in the following order (if supported):

    • ssh key pair (ssh-agent if specified in payload's usesshagent field)

    • plain text

    Note: Due to the specifics of the libgit2 authentication procedure, when authentication fails, this function is called again without any indication whether authentication was successful or not. To avoid an infinite loop from repeatedly using the same faulty credentials, the checkused! function can be called. This function returns true if the credentials were used. Using credentials triggers a user prompt for (re)entering required information. UserPasswordCredentials and CachedCredentials are implemented using a call counting strategy that prevents repeated usage of faulty credentials.

    source

    C function pointer for credentials_callback

    source

    Return signature object. Free it after use.

    source
    LibGit2.delete_branch(branch::GitReference)

    Delete the branch pointed to by branch.

    source
    diff_files(repo::GitRepo, branch1::AbstractString, branch2::AbstractString; kwarg...) -> Vector{AbstractString}

    Show which files have changed in the git repository repo between branches branch1 and branch2.

    The keyword argument is:

    • filter::Set{Consts.DELTA_STATUS}=Set([Consts.DELTA_ADDED, Consts.DELTA_MODIFIED, Consts.DELTA_DELETED])), and it sets options for the diff. The default is to show files added, modified, or deleted.

    Returns only the names of the files which have changed, not their contents.

    Example

    LibGit2.branch!(repo, "branch/a")
    -LibGit2.branch!(repo, "branch/b")
    -# add a file to repo
    -open(joinpath(LibGit2.path(repo),"file"),"w") do f
    -    write(f, "hello repo
    -")
    -end
    -LibGit2.add!(repo, "file")
    -LibGit2.commit(repo, "add file")
    -# returns ["file"]
    -filt = Set([LibGit2.Consts.DELTA_ADDED])
    -files = LibGit2.diff_files(repo, "branch/a", "branch/b", filter=filt)
    -# returns [] because existing files weren't modified
    -filt = Set([LibGit2.Consts.DELTA_MODIFIED])
    -files = LibGit2.diff_files(repo, "branch/a", "branch/b", filter=filt)

    Equivalent to git diff --name-only --diff-filter=<filter> <branch1> <branch2>.

    source
    Base.LibGit2.fetchFunction.
    fetch(rmt::GitRemote, refspecs; options::FetchOptions=FetchOptions(), msg="")

    Fetch from the specified rmt remote git repository, using refspecs to determine which remote branch(es) to fetch. The keyword arguments are:

    • options: determines the options for the fetch, e.g. whether to prune afterwards.

    • msg: a message to insert into the reflogs.

    source
    fetch(repo::GitRepo; kwargs...)

    Fetches updates from an upstream of the repository repo.

    The keyword arguments are:

    • remote::AbstractString="origin": which remote, specified by name, of repo to fetch from. If this is empty, the URL will be used to construct an anonymous remote.

    • remoteurl::AbstractString="": the URL of remote. If not specified, will be assumed based on the given name of remote.

    • refspecs=AbstractString[]: determines properties of the fetch.

    • payload=Nullable{AbstractCredentials}(): provides credentials, if necessary, for instance if remote is a private repository.

    Equivalent to git fetch [<remoteurl>|<repo>] [<refspecs>].

    source
    fetch_refspecs(rmt::GitRemote) -> Vector{String}

    Get the fetch refspecs for the specified rmt. These refspecs contain information about which branch(es) to fetch from.

    source

    C function pointer for fetchhead_foreach_callback

    source
    Base.LibGit2.ffmerge!Function.

    Fastforward merge changes into current head

    source
    Base.LibGit2.fullnameFunction.
    LibGit2.fullname(ref::GitReference)

    Return the name of the reference pointed to by the symbolic reference ref. If ref is not a symbolic reference, returns an empty string.

    source

    Obtain the cached credentials for the given host+protocol (credid), or return and store the default if not found

    source
    Base.LibGit2.gitdirFunction.
    LibGit2.gitdir(repo::GitRepo)

    Returns the location of the "git" files of repo:

    • for normal repositories, this is the location of the .git folder.

    • for bare repositories, this is the location of the repository itself.

    See also workdir, path.

    source
    Base.LibGit2.headFunction.
    LibGit2.head(repo::GitRepo) -> GitReference

    Returns a GitReference to the current HEAD of repo.

    source
    head(pkg::AbstractString) -> String

    Return current HEAD GitHash of the pkg repo as a string.

    source
    Base.LibGit2.head!Function.
    LibGit2.head!(repo::GitRepo, ref::GitReference) -> GitReference

    Set the HEAD of repo to the object pointed to by ref.

    source
    Base.LibGit2.head_oidFunction.
    LibGit2.head_oid(repo::GitRepo) -> GitHash

    Lookup the object id of the current HEAD of git repository repo.

    source
    Base.LibGit2.headnameFunction.
    LibGit2.headname(repo::GitRepo)

    Lookup the name of the current HEAD of git repository repo. If repo is currently detached, returns the name of the HEAD it's detached from.

    source
    Base.LibGit2.initFunction.
    LibGit2.init(path::AbstractString, bare::Bool=false) -> GitRepo

    Opens a new git repository at path. If bare is false, the working tree will be created in path/.git. If bare is true, no working directory will be created.

    source
    is_ancestor_of(a::AbstractString, b::AbstractString, repo::GitRepo) -> Bool

    Returns true if a, a GitHash in string form, is an ancestor of b, a GitHash in string form.

    Example

    julia> repo = LibGit2.GitRepo(repo_path);
    -
    -julia> LibGit2.add!(repo, test_file1);
    -
    -julia> commit_oid1 = LibGit2.commit(repo, "commit1");
    -
    -julia> LibGit2.add!(repo, test_file2);
    -
    -julia> commit_oid2 = LibGit2.commit(repo, "commit2");
    -
    -julia> LibGit2.is_ancestor_of(string(commit_oid1), string(commit_oid2), repo)
    -true
    source
    Base.LibGit2.isbinaryFunction.

    Use a heuristic to guess if a file is binary: searching for NULL bytes and looking for a reasonable ratio of printable to non-printable characters among the first 8000 bytes.

    source
    Base.LibGit2.iscommitFunction.
    iscommit(id::AbstractString, repo::GitRepo) -> Bool

    Checks if commit id (which is a GitHash in string form) is in the repository.

    Example

    julia> repo = LibGit2.GitRepo(repo_path);
    -
    -julia> LibGit2.add!(repo, test_file);
    -
    -julia> commit_oid = LibGit2.commit(repo, "add test_file");
    -
    -julia> LibGit2.iscommit(string(commit_oid), repo)
    -true
    source
    Base.LibGit2.isdiffFunction.
    LibGit2.isdiff(repo::GitRepo, treeish::AbstractString, pathspecs::AbstractString=""; cached::Bool=false)

    Checks if there are any differences between the tree specified by treeish and the tracked files in the working tree (if cached=false) or the index (if cached=true). pathspecs are the specifications for options for the diff.

    Example

    repo = LibGit2.GitRepo(repo_path)
    -LibGit2.isdiff(repo, "HEAD") # should be false
    -open(joinpath(repo_path, new_file), "a") do f
    -    println(f, "here's my cool new file")
    -end
    -LibGit2.isdiff(repo, "HEAD") # now true

    Equivalent to git diff-index <treeish> [-- <pathspecs>].

    source
    Base.LibGit2.isdirtyFunction.
    LibGit2.isdirty(repo::GitRepo, pathspecs::AbstractString=""; cached::Bool=false) -> Bool

    Checks if there have been any changes to tracked files in the working tree (if cached=false) or the index (if cached=true). pathspecs are the specifications for options for the diff.

    Example

    repo = LibGit2.GitRepo(repo_path)
    -LibGit2.isdirty(repo) # should be false
    -open(joinpath(repo_path, new_file), "a") do f
    -    println(f, "here's my cool new file")
    -end
    -LibGit2.isdirty(repo) # now true
    -LibGit2.isdirty(repo, new_file) # now true

    Equivalent to git diff-index HEAD [-- <pathspecs>].

    source
    Base.LibGit2.isorphanFunction.
    LibGit2.isorphan(repo::GitRepo)

    Checks if the current branch is an "orphan" branch, i.e. has no commits. The first commit to this branch will have no parents.

    source
    lookup_branch(repo::GitRepo, branch_name::AbstractString, remote::Bool=false) -> Nullable{GitReference}

    Determine if the branch specified by branch_name exists in the repository repo. If remote is true, repo is assumed to be a remote git repository. Otherwise, it is part of the local filesystem.

    lookup_branch returns a Nullable, which will be null if the requested branch does not exist yet. If the branch does exist, the Nullable contains a GitReference to the branch.

    source

    Mirror callback function

    Function sets +refs/*:refs/* refspecs and mirror flag for remote reference.

    source

    C function pointer for mirror_callback

    source
    Base.LibGit2.nameFunction.
    LibGit2.name(ref::GitReference)

    Return the full name of ref.

    source
    name(rmt::GitRemote)

    Get the name of a remote repository, for instance "origin". If the remote is anonymous (see GitRemoteAnon) the name will be an empty string "".

    Example

    julia> repo_url = "https://github.com/JuliaLang/Example.jl";
    -
    -julia> repo = LibGit2.clone(cache_repo, "test_directory");
    -
    -julia> remote = LibGit2.GitRemote(repo, "origin", repo_url);
    -
    -julia> name(remote)
    -"origin"
    source
    LibGit2.name(tag::GitTag)

    The name of tag (e.g. "v0.5").

    source
    need_update(repo::GitRepo)

    Equivalent to git update-index. Returns true if repo needs updating.

    source
    Base.LibGit2.objtypeFunction.
    objtype(obj_type::Consts.OBJECT)

    Returns the type corresponding to the enum value.

    source
    Base.LibGit2.pathFunction.
    LibGit2.path(repo::GitRepo)

    The base file path of the repository repo.

    • for normal repositories, this will typically be the parent directory of the ".git" directory (note: this may be different than the working directory, see workdir for more details).

    • for bare repositories, this is the location of the "git" files.

    See also gitdir, workdir.

    source
    Base.LibGit2.peelFunction.
    peel([T,] ref::GitReference)

    Recursively peel ref until an object of type T is obtained. If no T is provided, then ref will be peeled until an object other than a GitTag is obtained.

    • A GitTag will be peeled to the object it references.

    • A GitCommit will be peeled to a GitTree.

    Note

    Only annotated tags can be peeled to GitTag objects. Lightweight tags (the default) are references under refs/tags/ which point directly to GitCommit objects.

    source
    peel([T,] obj::GitObject)

    Recursively peel obj until an object of type T is obtained. If no T is provided, then obj will be peeled until the type changes.

    • A GitTag will be peeled to the object it references.

    • A GitCommit will be peeled to a GitTree.

    source
    LibGit2.posixpath(path)

    Standardise the path string path to use POSIX separators.

    source
    Base.LibGit2.pushFunction.
    push(rmt::GitRemote, refspecs; force::Bool=false, options::PushOptions=PushOptions())

    Push to the specified rmt remote git repository, using refspecs to determine which remote branch(es) to push to. The keyword arguments are:

    • force: if true, a force-push will occur, disregarding conflicts.

    • options: determines the options for the push, e.g. which proxy headers to use.

    Note

    You can add information about the push refspecs in two other ways: by setting an option in the repository's GitConfig (with push.default as the key) or by calling add_push!. Otherwise you will need to explicitly specify a push refspec in the call to push for it to have any effect, like so: LibGit2.push(repo, refspecs=["refs/heads/master"]).

    source
    push(repo::GitRepo; kwargs...)

    Pushes updates to an upstream of repo.

    The keyword arguments are:

    • remote::AbstractString="origin": the name of the upstream remote to push to.

    • remoteurl::AbstractString="": the URL of remote.

    • refspecs=AbstractString[]: determines properties of the push.

    • force::Bool=false: determines if the push will be a force push, overwriting the remote branch.

    • payload=Nullable{AbstractCredentials}(): provides credentials, if necessary, for instance if remote is a private repository.

    Equivalent to git push [<remoteurl>|<repo>] [<refspecs>].

    source
    push_refspecs(rmt::GitRemote) -> Vector{String}

    Get the push refspecs for the specified rmt. These refspecs contain information about which branch(es) to push to.

    source
    LibGit2.read_tree!(idx::GitIndex, tree::GitTree)
    -LibGit2.read_tree!(idx::GitIndex, treehash::AbstractGitHash)

    Read the tree tree (or the tree pointed to by treehash in the repository owned by idx) into the index idx. The current index contents will be replaced.

    source
    Base.LibGit2.rebase!Function.
    LibGit2.rebase!(repo::GitRepo, upstream::AbstractString="", newbase::AbstractString="")

    Attempt an automatic merge rebase of the current branch, from upstream if provided, or otherwise from the upstream tracking branch. newbase is the branch to rebase onto. By default this is upstream.

    If any conflicts arise which cannot be automatically resolved, the rebase will abort, leaving the repository and working tree in its original state, and the function will throw a GitError. This is roughly equivalent to the following command line statement:

    git rebase --merge [<upstream>]
    -if [ -d ".git/rebase-merge" ]; then
    -    git rebase --abort
    -fi
    source
    Base.LibGit2.ref_listFunction.
    LibGit2.ref_list(repo::GitRepo) -> Vector{String}

    Get a list of all reference names in the repo repository.

    source
    Base.LibGit2.reftypeFunction.
    LibGit2.reftype(ref::GitReference) -> Cint

    Returns a Cint corresponding to the type of ref:

    • 0 if the reference is invalid

    • 1 if the reference is an object id

    • 2 if the reference is symbolic

    source
    Base.LibGit2.remotesFunction.
    LibGit2.remotes(repo::GitRepo)

    Returns a vector of the names of the remotes of repo.

    source
    Base.LibGit2.reset!Function.

    Resets credentials for another use

    source

    Updates some entries, determined by the pathspecs, in the index from the target commit tree.

    source

    Sets the current head to the specified commit oid and optionally resets the index and working tree to match.

    source

    git reset [<committish>] [–] <pathspecs>...

    source
    reset!(repo::GitRepo, id::GitHash, mode::Cint = Consts.RESET_MIXED)

    Reset the repository repo to its state at id, using one of three modes set by mode:

    1. Consts.RESET_SOFT - move HEAD to id.

    2. Consts.RESET_MIXED - default, move HEAD to id and reset the index to id.

    3. Consts.RESET_HARD - move HEAD to id, reset the index to id, and discard all working changes.

    Equivalent to git reset [--soft | --mixed | --hard] <id>.

    Example

    repo = LibGit2.GitRepo(repo_path)
    -head_oid = LibGit2.head_oid(repo)
    -open(joinpath(repo_path, "file1"), "w") do f
    -    write(f, "111
    -")
    -end
    -LibGit2.add!(repo, "file1")
    -mode = LibGit2.Consts.RESET_HARD
    -# will discard the changes to file1
    -# and unstage it
    -new_head = LibGit2.reset!(repo, head_oid, mode)
    source
    Base.LibGit2.restoreFunction.
    restore(s::State, repo::GitRepo)

    Return a repository repo to a previous State s, for example the HEAD of a branch before a merge attempt. s can be generated using the snapshot function.

    source
    Base.LibGit2.revcountFunction.
    LibGit2.revcount(repo::GitRepo, commit1::AbstractString, commit2::AbstractString)

    List the number of revisions between commit1 and commit2 (committish OIDs in string form). Since commit1 and commit2 may be on different branches, revcount performs a "left-right" revision list (and count), returning a tuple of Ints - the number of left and right commits, respectively. A left (or right) commit refers to which side of a symmetric difference in a tree the commit is reachable from.

    Equivalent to git rev-list --left-right --count <commit1> <commit2>.

    source
    set_remote_url(repo::GitRepo, url::AbstractString; remote::AbstractString="origin")

    Set the url for remote for the git repository repo. The default name of the remote is "origin".

    Examples

    repo_path = joinpath("test_directory", "Example")
    -repo = LibGit2.init(repo_path)
    -url1 = "https://github.com/JuliaLang/Example.jl"
    -LibGit2.set_remote_url(repo, url1, remote="upstream")
    -url2 = "https://github.com/JuliaLang/Example2.jl"
    -LibGit2.set_remote_url(repo_path, url2, remote="upstream2")
    source
    set_remote_url(path::AbstractString, url::AbstractString; remote::AbstractString="origin")

    Set the url for remote for the git repository located at path. The default name of the remote is "origin".

    source
    LibGit2.shortname(ref::GitReference)

    Returns a shortened version of the name of ref that's "human-readable".

    julia> repo = LibGit2.GitRepo(path_to_repo);
    -
    -julia> branch_ref = LibGit2.head(repo);
    -
    -julia> LibGit2.name(branch_ref)
    -"refs/heads/master"
    -
    -julia> LibGit2.shortname(branch_ref)
    -"master"
    source
    Base.LibGit2.snapshotFunction.
    snapshot(repo::GitRepo) -> State

    Take a snapshot of the current state of the repository repo, storing the current HEAD, index, and any uncommitted work. The output State can be used later during a call to restore to return the repository to the snapshotted state.

    source
    Base.LibGit2.statusFunction.
    LibGit2.status(repo::GitRepo, path::String)

    Lookup the status of the file at path in the git repository repo. For instance, this can be used to check if the file at path has been modified and needs to be staged and committed.

    source
    LibGit2.tag_create(repo::GitRepo, tag::AbstractString, commit; kwargs...)

    Create a new git tag tag (e.g. "v0.5") in the repository repo, at the commit commit.

    The keyword arguments are:

    • msg::AbstractString="": the message for the tag.

    • force::Bool=false: if true, existing references will be overwritten.

    • sig::Signature=Signature(repo): the tagger's signature.

    source
    LibGit2.tag_delete(repo::GitRepo, tag::AbstractString)

    Remove the git tag tag from the repository repo.

    source
    Base.LibGit2.tag_listFunction.
    LibGit2.tag_list(repo::GitRepo) -> Vector{String}

    Get a list of all tags in the git repository repo.

    source
    Base.LibGit2.targetFunction.
    LibGit2.target(tag::GitTag)

    The GitHash of the target object of tag.

    source
    Base.LibGit2.treewalkFunction.

    Traverse the entries in a tree and its subtrees in post or pre order.

    Function parameter should have following signature:

    (Cstring, Ptr{Void}, Ptr{Void}) -> Cint
    source
    Base.LibGit2.upstreamFunction.
    upstream(ref::GitReference) -> Nullable{GitReference}

    Determine if the branch containing ref has a specified upstream branch.

    upstream returns a Nullable, which will be null if the requested branch does not have an upstream counterpart. If the upstream branch does exist, the Nullable contains a GitReference to the upstream branch.

    source
    Base.LibGit2.urlFunction.
    url(rmt::GitRemote)

    Get the fetch URL of a remote git repository.

    Example

    julia> repo_url = "https://github.com/JuliaLang/Example.jl";
    -
    -julia> repo = LibGit2.init(mktempdir());
    -
    -julia> remote = LibGit2.GitRemote(repo, "origin", repo_url);
    -
    -julia> LibGit2.url(remote)
    -"https://github.com/JuliaLang/Example.jl"
    source
    Base.LibGit2.withFunction.

    Resource management helper function

    source
    Base.LibGit2.workdirFunction.
    LibGit2.workdir(repo::GitRepo)

    The location of the working directory of repo. This will throw an error for bare repositories.

    Note

    This will typically be the parent directory of gitdir(repo), but can be different in some cases: e.g. if either the core.worktree configuration variable or the GIT_WORK_TREE environment variable is set.

    See also gitdir, path.

    source
    diff --git a/julia-0.6.3/share/doc/julia/html/en/devdocs/llvm.html b/julia-0.6.3/share/doc/julia/html/en/devdocs/llvm.html deleted file mode 100644 index 9c0bbdd..0000000 --- a/julia-0.6.3/share/doc/julia/html/en/devdocs/llvm.html +++ /dev/null @@ -1,9 +0,0 @@ - -Working with LLVM · The Julia Language

    Working with LLVM

    Working with LLVM

    This is not a replacement for the LLVM documentation, but a collection of tips for working on LLVM for Julia.

    Overview of Julia to LLVM Interface

    Julia statically links in LLVM by default. Build with USE_LLVM_SHLIB=1 to link dynamically.

    The code for lowering Julia AST to LLVM IR or interpreting it directly is in directory src/.

    FileDescription
    builtins.cBuiltin functions
    ccall.cppLowering ccall
    cgutils.cppLowering utilities, notably for array and tuple accesses
    codegen.cppTop-level of code generation, pass list, lowering builtins
    debuginfo.cppTracks debug information for JIT code
    disasm.cppHandles native object file and JIT code diassembly
    gf.cGeneric functions
    intrinsics.cppLowering intrinsics
    llvm-simdloop.cppCustom LLVM pass for @simd
    sys.cI/O and operating system utility functions

    Some of the .cpp files form a group that compile to a single object.

    The difference between an intrinsic and a builtin is that a builtin is a first class function that can be used like any other Julia function. An intrinsic can operate only on unboxed data, and therefore its arguments must be statically typed.

    Alias Analysis

    Julia currently uses LLVM's Type Based Alias Analysis. To find the comments that document the inclusion relationships, look for static MDNode* in src/codegen.cpp.

    The -O option enables LLVM's Basic Alias Analysis.

    Building Julia with a different version of LLVM

    The default version of LLVM is specified in deps/Versions.make. You can override it by creating a file called Make.user in the top-level directory and adding a line to it such as:

    LLVM_VER = 3.5.0

    Besides the LLVM release numerals, you can also use LLVM_VER = svn to bulid against the latest development version of LLVM.

    Passing options to LLVM

    You can pass options to LLVM using debug builds of Julia. To create a debug build, run make debug. The resulting executable is usr/bin/julia-debug. You can pass LLVM options to this executable via the environment variable JULIA_LLVM_ARGS. Here are example settings using bash syntax:

    • export JULIA_LLVM_ARGS = -print-after-all dumps IR after each pass.

    • export JULIA_LLVM_ARGS = -debug-only=loop-vectorize dumps LLVM DEBUG(...) diagnostics for loop vectorizer if you built Julia with LLVM_ASSERTIONS=1. Otherwise you will get warnings about "Unknown command line argument". Counter-intuitively, building Julia with LLVM_DEBUG=1 is not enough to dump DEBUG diagnostics from a pass.

    Improving LLVM optimizations for Julia

    Improving LLVM code generation usually involves either changing Julia lowering to be more friendly to LLVM's passes, or improving a pass.

    If you are planning to improve a pass, be sure to read the LLVM developer policy. The best strategy is to create a code example in a form where you can use LLVM's opt tool to study it and the pass of interest in isolation.

    1. Create an example Julia code of interest.

    2. Use JULIA_LLVM_ARGS = -print-after-all to dump the IR.

    3. Pick out the IR at the point just before the pass of interest runs.

    4. Strip the debug metadata and fix up the TBAA metadata by hand.

    The last step is labor intensive. Suggestions on a better way would be appreciated.

    diff --git a/julia-0.6.3/share/doc/julia/html/en/devdocs/locks.html b/julia-0.6.3/share/doc/julia/html/en/devdocs/locks.html deleted file mode 100644 index ccab792..0000000 --- a/julia-0.6.3/share/doc/julia/html/en/devdocs/locks.html +++ /dev/null @@ -1,9 +0,0 @@ - -Proper maintenance and care of multi-threading locks · The Julia Language

    Proper maintenance and care of multi-threading locks

    Proper maintenance and care of multi-threading locks

    The following strategies are used to ensure that the code is dead-lock free (generally by addressing the 4th Coffman condition: circular wait).

    1. structure code such that only one lock will need to be acquired at a time

    2. always acquire shared locks in the same order, as given by the table below

    3. avoid constructs that expect to need unrestricted recursion

    Locks

    Below are all of the locks that exist in the system and the mechanisms for using them that avoid the potential for deadlocks (no Ostrich algorithm allowed here):

    The following are definitely leaf locks (level 1), and must not try to acquire any other lock:

    • safepoint

      Note that this lock is acquired implicitly by JL_LOCK and JL_UNLOCK. use the _NOGC variants to avoid that for level 1 locks.

      While holding this lock, the code must not do any allocation or hit any safepoints. Note that there are safepoints when doing allocation, enabling / disabling GC, entering / restoring exception frames, and taking / releasing locks.

    • shared_map

    • finalizers

    • pagealloc

    • gc_perm_lock

    • flisp

      flisp itself is already threadsafe, this lock only protects the jl_ast_context_list_t pool

    The following is a leaf lock (level 2), and only acquires level 1 locks (safepoint) internally:

    • typecache

    The following is a level 3 lock, which can only acquire level 1 or level 2 locks internally:

    • Method->writelock

    The following is a level 4 lock, which can only recurse to acquire level 1, 2, or 3 locks:

    • MethodTable->writelock

    No Julia code may be called while holding a lock above this point.

    The following is a level 6 lock, which can only recurse to acquire locks at lower levels:

    • codegen

    The following is an almost root lock (level end-1), meaning only the root look may be held when trying to acquire it:

    • typeinf

      this one is perhaps one of the most tricky ones, since type-inference can be invoked from many points

      currently the lock is merged with the codegen lock, since they call each other recursively

    The following is the root lock, meaning no other lock shall be held when trying to acquire it:

    • toplevel

      this should be held while attempting a top-level action (such as making a new type or defining a new method): trying to obtain this lock inside a staged function will cause a deadlock condition!

      additionally, it's unclear if any code can safely run in parallel with an arbitrary toplevel expression, so it may require all threads to get to a safepoint first

    Broken Locks

    The following locks are broken:

    • toplevel

      doesn't exist right now

      fix: create it

    Shared Global Data Structures

    These data structures each need locks due to being shared mutable global state. It is the inverse list for the above lock priority list. This list does not include level 1 leaf resources due to their simplicity.

    MethodTable modifications (def, cache, kwsorter type) : MethodTable->writelock

    Type declarations : toplevel lock

    Type application : typecache lock

    Module serializer : toplevel lock

    JIT & type-inference : codegen lock

    MethodInstance updates : codegen lock

    • These fields are generally lazy initialized, using the test-and-test-and-set pattern.

    • These are set at construction and immutable:

      • specTypes

      • sparam_vals

      • def

    • These are set by jl_type_infer (while holding codegen lock):

      • rettype

      • inferred

      • these can also be reset, see jl_set_lambda_rettype for that logic as it needs to keep functionObjectsDecls in sync

    • inInference flag:

      • optimization to quickly avoid recurring into jl_type_infer while it is already running

      • actual state (of setting inferred, then fptr) is protected by codegen lock

    • Function pointers (jlcall_api and fptr, unspecialized_ducttape):

      • these transition once, from NULL to a value, while the codegen lock is held

    • Code-generator cache (the contents of functionObjectsDecls):

      • these can transition multiple times, but only while the codegen lock is held

      • it is valid to use old version of this, or block for new versions of this, so races are benign, as long as the code is careful not to reference other data in the method instance (such as rettype) and assume it is coordinated, unless also holding the codegen lock

    • compile_traced flag:

      • unknown

    LLVMContext : codegen lock

    Method : Method->writelock

    • roots array (serializer and codegen)

    • invoke / specializations / tfunc modifications

    diff --git a/julia-0.6.3/share/doc/julia/html/en/devdocs/meta.html b/julia-0.6.3/share/doc/julia/html/en/devdocs/meta.html deleted file mode 100644 index 815c012..0000000 --- a/julia-0.6.3/share/doc/julia/html/en/devdocs/meta.html +++ /dev/null @@ -1,18 +0,0 @@ - -Talking to the compiler (the :meta mechanism) · The Julia Language

    Talking to the compiler (the :meta mechanism)

    Talking to the compiler (the :meta mechanism)

    In some circumstances, one might wish to provide hints or instructions that a given block of code has special properties: you might always want to inline it, or you might want to turn on special compiler optimization passes. Starting with version 0.4, Julia has a convention that these instructions can be placed inside a :meta expression, which is typically (but not necessarily) the first expression in the body of a function.

    :meta expressions are created with macros. As an example, consider the implementation of the @inline macro:

    macro inline(ex)
    -    esc(isa(ex, Expr) ? pushmeta!(ex, :inline) : ex)
    -end

    Here, ex is expected to be an expression defining a function. A statement like this:

    @inline function myfunction(x)
    -    x*(x+3)
    -end

    gets turned into an expression like this:

    quote
    -    function myfunction(x)
    -        Expr(:meta, :inline)
    -        x*(x+3)
    -    end
    -end

    Base.pushmeta!(ex, :symbol, args...) appends :symbol to the end of the :meta expression, creating a new :meta expression if necessary. If args is specified, a nested expression containing :symbol and these arguments is appended instead, which can be used to specify additional information.

    To use the metadata, you have to parse these :meta expressions. If your implementation can be performed within Julia, Base.popmeta! is very handy: Base.popmeta!(body, :symbol) will scan a function body expression (one without the function signature) for the first :meta expression containing :symbol, extract any arguments, and return a tuple (found::Bool, args::Array{Any}). If the metadata did not have any arguments, or :symbol was not found, the args array will be empty.

    Not yet provided is a convenient infrastructure for parsing :meta expressions from C++.

    diff --git a/julia-0.6.3/share/doc/julia/html/en/devdocs/object.html b/julia-0.6.3/share/doc/julia/html/en/devdocs/object.html deleted file mode 100644 index eb7098d..0000000 --- a/julia-0.6.3/share/doc/julia/html/en/devdocs/object.html +++ /dev/null @@ -1,34 +0,0 @@ - -Memory layout of Julia Objects · The Julia Language

    Memory layout of Julia Objects

    Memory layout of Julia Objects

    Object layout (jl_value_t)

    The jl_value_t struct is the name for a block of memory owned by the Julia Garbage Collector, representing the data associated with a Julia object in memory. Absent any type information, it is simply an opaque pointer:

    typedef struct jl_value_t* jl_pvalue_t;

    Each jl_value_t struct is contained in a jl_typetag_t struct that contains metadata information about the Julia object, such as its type and garbage collector (gc) reachability:

    typedef struct {
    -    opaque metadata;
    -    jl_value_t value;
    -} jl_typetag_t;

    The type of any Julia object is an instance of a leaf jl_datatype_t object. The jl_typeof() function can be used to query for it:

    jl_value_t *jl_typeof(jl_value_t *v);

    The layout of the object depends on its type. Reflection methods can be used to inspect that layout. A field can be accessed by calling one of the get-field methods:

    jl_value_t *jl_get_nth_field_checked(jl_value_t *v, size_t i);
    -jl_value_t *jl_get_field(jl_value_t *o, char *fld);

    If the field types are known, a priori, to be all pointers, the values can also be extracted directly as an array access:

    jl_value_t *v = value->fieldptr[n];

    As an example, a "boxed" uint16_t is stored as follows:

    struct {
    -    opaque metadata;
    -    struct {
    -        uint16_t data;        // -- 2 bytes
    -    } jl_value_t;
    -};

    This object is created by jl_box_uint16(). Note that the jl_value_t pointer references the data portion, not the metadata at the top of the struct.

    A value may be stored "unboxed" in many circumstances (just the data, without the metadata, and possibly not even stored but just kept in registers), so it is unsafe to assume that the address of a box is a unique identifier. The "egal" test (corresponding to the === function in Julia), should instead be used to compare two unknown objects for equivalence:

    int jl_egal(jl_value_t *a, jl_value_t *b);

    This optimization should be relatively transparent to the API, since the object will be "boxed" on-demand, whenever a jl_value_t pointer is needed.

    Note that modification of a jl_value_t pointer in memory is permitted only if the object is mutable. Otherwise, modification of the value may corrupt the program and the result will be undefined. The mutability property of a value can be queried for with:

    int jl_is_mutable(jl_value_t *v);

    If the object being stored is a jl_value_t, the Julia garbage collector must be notified also:

    void jl_gc_wb(jl_value_t *parent, jl_value_t *ptr);

    However, the Embedding Julia section of the manual is also required reading at this point, for covering other details of boxing and unboxing various types, and understanding the gc interactions.

    Mirror structs for some of the built-in types are defined in julia.h. The corresponding global jl_datatype_t objects are created by jl_init_types in jltypes.c.

    Garbage collector mark bits

    The garbage collector uses several bits from the metadata portion of the jl_typetag_t to track each object in the system. Further details about this algorithm can be found in the comments of the garbage collector implementation in gc.c.

    Object allocation

    Most new objects are allocated by jl_new_structv():

    jl_value_t *jl_new_struct(jl_datatype_t *type, ...);
    -jl_value_t *jl_new_structv(jl_datatype_t *type, jl_value_t **args, uint32_t na);

    Although, isbits objects can be also constructed directly from memory:

    jl_value_t *jl_new_bits(jl_value_t *bt, void *data)

    And some objects have special constructors that must be used instead of the above functions:

    Types:

    jl_datatype_t *jl_apply_type(jl_datatype_t *tc, jl_tuple_t *params);
    -jl_datatype_t *jl_apply_array_type(jl_datatype_t *type, size_t dim);
    -jl_uniontype_t *jl_new_uniontype(jl_tuple_t *types);

    While these are the most commonly used options, there are more low-level constructors too, which you can find declared in julia.h. These are used in jl_init_types() to create the initial types needed to bootstrap the creation of the Julia system image.

    Tuples:

    jl_tuple_t *jl_tuple(size_t n, ...);
    -jl_tuple_t *jl_tuplev(size_t n, jl_value_t **v);
    -jl_tuple_t *jl_alloc_tuple(size_t n);

    The representation of tuples is highly unique in the Julia object representation ecosystem. In some cases, a Base.tuple() object may be an array of pointers to the objects contained by the tuple equivalent to:

    typedef struct {
    -    size_t length;
    -    jl_value_t *data[length];
    -} jl_tuple_t;

    However, in other cases, the tuple may be converted to an anonymous isbits type and stored unboxed, or it may not stored at all (if it is not being used in a generic context as a jl_value_t*).

    Symbols:

    jl_sym_t *jl_symbol(const char *str);

    Functions and MethodInstance:

    jl_function_t *jl_new_generic_function(jl_sym_t *name);
    -jl_method_instance_t *jl_new_method_instance(jl_value_t *ast, jl_tuple_t *sparams);

    Arrays:

    jl_array_t *jl_new_array(jl_value_t *atype, jl_tuple_t *dims);
    -jl_array_t *jl_new_arrayv(jl_value_t *atype, ...);
    -jl_array_t *jl_alloc_array_1d(jl_value_t *atype, size_t nr);
    -jl_array_t *jl_alloc_array_2d(jl_value_t *atype, size_t nr, size_t nc);
    -jl_array_t *jl_alloc_array_3d(jl_value_t *atype, size_t nr, size_t nc, size_t z);
    -jl_array_t *jl_alloc_vec_any(size_t n);

    Note that many of these have alternative allocation functions for various special-purposes. The list here reflects the more common usages, but a more complete list can be found by reading the julia.h header file.

    Internal to Julia, storage is typically allocated by newstruct() (or newobj() for the special types):

    jl_value_t *newstruct(jl_value_t *type);
    -jl_value_t *newobj(jl_value_t *type, size_t nfields);

    And at the lowest level, memory is getting allocated by a call to the garbage collector (in gc.c), then tagged with its type:

    jl_value_t *jl_gc_allocobj(size_t nbytes);
    -void jl_set_typeof(jl_value_t *v, jl_datatype_t *type);

    Note that all objects are allocated in multiples of 4 bytes and aligned to the platform pointer size. Memory is allocated from a pool for smaller objects, or directly with malloc() for large objects.

    diff --git a/julia-0.6.3/share/doc/julia/html/en/devdocs/offset-arrays.html b/julia-0.6.3/share/doc/julia/html/en/devdocs/offset-arrays.html deleted file mode 100644 index f7db562..0000000 --- a/julia-0.6.3/share/doc/julia/html/en/devdocs/offset-arrays.html +++ /dev/null @@ -1,30 +0,0 @@ - -Arrays with custom indices · The Julia Language

    Arrays with custom indices

    Arrays with custom indices

    Julia 0.5 adds experimental support for arrays with arbitrary indices. Conventionally, Julia's arrays are indexed starting at 1, whereas some other languages start numbering at 0, and yet others (e.g., Fortran) allow you to specify arbitrary starting indices. While there is much merit in picking a standard (i.e., 1 for Julia), there are some algorithms which simplify considerably if you can index outside the range 1:size(A,d) (and not just 0:size(A,d)-1, either). Such array types are expected to be supplied through packages.

    The purpose of this page is to address the question, "what do I have to do to support such arrays in my own code?" First, let's address the simplest case: if you know that your code will never need to handle arrays with unconventional indexing, hopefully the answer is "nothing." Old code, on conventional arrays, should function essentially without alteration as long as it was using the exported interfaces of Julia.

    Generalizing existing code

    As an overview, the steps are:

    • replace many uses of size with indices

    • replace 1:length(A) with linearindices(A), and length(A) with length(linearindices(A))

    • replace explicit allocations like Array{Int}(size(B)) with similar(Array{Int}, indices(B))

    These are described in more detail below.

    Background

    Because unconventional indexing breaks deeply-held assumptions throughout the Julia ecosystem, early adopters running code that has not been updated are likely to experience errors. The most frustrating bugs would be incorrect results or segfaults (total crashes of Julia). For example, consider the following function:

    function mycopy!(dest::AbstractVector, src::AbstractVector)
    -    length(dest) == length(src) || throw(DimensionMismatch("vectors must match"))
    -    # OK, now we're safe to use @inbounds, right? (not anymore!)
    -    for i = 1:length(src)
    -        @inbounds dest[i] = src[i]
    -    end
    -    dest
    -end

    This code implicitly assumes that vectors are indexed from 1. Previously that was a safe assumption, so this code was fine, but (depending on what types the user passes to this function) it may no longer be safe. If this code continued to work when passed a vector with non-1 indices, it would either produce an incorrect answer or it would segfault. (If you do get segfaults, to help locate the cause try running julia with the option --check-bounds=yes.)

    To ensure that such errors are caught, in Julia 0.5 both length and sizeshould throw an error when passed an array with non-1 indexing. This is designed to force users of such arrays to check the code, and inspect it for whether it needs to be generalized.

    Using indices for bounds checks and loop iteration

    indices(A) (reminiscent of size(A)) returns a tuple of AbstractUnitRange objects, specifying the range of valid indices along each dimension of A. When A has unconventional indexing, the ranges may not start at 1. If you just want the range for a particular dimension d, there is indices(A, d).

    Base implements a custom range type, OneTo, where OneTo(n) means the same thing as 1:n but in a form that guarantees (via the type system) that the lower index is 1. For any new AbstractArray type, this is the default returned by indices, and it indicates that this array type uses "conventional" 1-based indexing. Note that if you don't want to be bothered supporting arrays with non-1 indexing, you can add the following line:

    @assert all(x->isa(x, Base.OneTo), indices(A))

    at the top of any function.

    For bounds checking, note that there are dedicated functions checkbounds and checkindex which can sometimes simplify such tests.

    Linear indexing (linearindices)

    Some algorithms are most conveniently (or efficiently) written in terms of a single linear index, A[i] even if A is multi-dimensional. In "true" linear indexing, the indices always range from 1:length(A). However, this raises an ambiguity for one-dimensional arrays (a.k.a., AbstractVector): does v[i] mean linear indexing, or Cartesian indexing with the array's native indices?

    For this reason, if you want to use linear indexing in an algorithm, your best option is to get the index range by calling linearindices(A). This will return indices(A, 1) if A is an AbstractVector, and the equivalent of 1:length(A) otherwise.

    In a sense, one can say that 1-dimensional arrays always use Cartesian indexing. To help enforce this, it's worth noting that sub2ind(shape, i...) and ind2sub(shape, ind) will throw an error if shape indicates a 1-dimensional array with unconventional indexing (i.e., is a Tuple{UnitRange} rather than a tuple of OneTo). For arrays with conventional indexing, these functions continue to work the same as always.

    Using indices and linearindices, here is one way you could rewrite mycopy!:

    function mycopy!(dest::AbstractVector, src::AbstractVector)
    -    indices(dest) == indices(src) || throw(DimensionMismatch("vectors must match"))
    -    for i in linearindices(src)
    -        @inbounds dest[i] = src[i]
    -    end
    -    dest
    -end

    Allocating storage using generalizations of similar

    Storage is often allocated with Array{Int}(dims) or similar(A, args...). When the result needs to match the indices of some other array, this may not always suffice. The generic replacement for such patterns is to use similar(storagetype, shape). storagetype indicates the kind of underlying "conventional" behavior you'd like, e.g., Array{Int} or BitArray or even dims->zeros(Float32, dims) (which would allocate an all-zeros array). shape is a tuple of Integer or AbstractUnitRange values, specifying the indices that you want the result to use.

    Let's walk through a couple of explicit examples. First, if A has conventional indices, then similar(Array{Int}, indices(A)) would end up calling Array{Int}(size(A)), and thus return an array. If A is an AbstractArray type with unconventional indexing, then similar(Array{Int}, indices(A)) should return something that "behaves like" an Array{Int} but with a shape (including indices) that matches A. (The most obvious implementation is to allocate an Array{Int}(size(A)) and then "wrap" it in a type that shifts the indices.)

    Note also that similar(Array{Int}, (indices(A, 2),)) would allocate an AbstractVector{Int} (i.e., 1-dimensional array) that matches the indices of the columns of A.

    Deprecations

    In generalizing Julia's code base, at least one deprecation was unavoidable: earlier versions of Julia defined first(::Colon) = 1, meaning that the first index along a dimension indexed by : is 1. This definition can no longer be justified, so it was deprecated. There is no provided replacement, because the proper replacement depends on what you are doing and might need to know more about the array. However, it appears that many uses of first(::Colon) are really about computing an index offset; when that is the case, a candidate replacement is:

    indexoffset(r::AbstractVector) = first(r) - 1
    -indexoffset(::Colon) = 0

    In other words, while first(:) does not itself make sense, in general you can say that the offset associated with a colon-index is zero.

    Writing custom array types with non-1 indexing

    Most of the methods you'll need to define are standard for any AbstractArray type, see Abstract Arrays. This page focuses on the steps needed to define unconventional indexing.

    Do not implement size or length

    Perhaps the majority of pre-existing code that uses size will not work properly for arrays with non-1 indices. For that reason, it is much better to avoid implementing these methods, and use the resulting MethodError to identify code that needs to be audited and perhaps generalized.

    Do not annotate bounds checks

    Julia 0.5 includes @boundscheck to annotate code that can be removed for callers that exploit @inbounds. Initially, it seems far preferable to run with bounds checking always enabled (i.e., omit the @boundscheck annotation so the check always runs).

    Custom AbstractUnitRange types

    If you're writing a non-1 indexed array type, you will want to specialize indices so it returns a UnitRange, or (perhaps better) a custom AbstractUnitRange. The advantage of a custom type is that it "signals" the allocation type for functions like similar. If we're writing an array type for which indexing will start at 0, we likely want to begin by creating a new AbstractUnitRange, ZeroRange, where ZeroRange(n) is equivalent to 0:n-1.

    In general, you should probably not export ZeroRange from your package: there may be other packages that implement their own ZeroRange, and having multiple distinct ZeroRange types is (perhaps counterintuitively) an advantage: ModuleA.ZeroRange indicates that similar should create a ModuleA.ZeroArray, whereas ModuleB.ZeroRange indicates a ModuleB.ZeroArray type. This design allows peaceful coexistence among many different custom array types.

    Note that the Julia package CustomUnitRanges.jl can sometimes be used to avoid the need to write your own ZeroRange type.

    Specializing indices

    Once you have your AbstractUnitRange type, then specialize indices:

    Base.indices(A::ZeroArray) = map(n->ZeroRange(n), A.size)

    where here we imagine that ZeroArray has a field called size (there would be other ways to implement this).

    In some cases, the fallback definition for indices(A, d):

    indices(A::AbstractArray{T,N}, d) where {T,N} = d <= N ? indices(A)[d] : OneTo(1)

    may not be what you want: you may need to specialize it to return something other than OneTo(1) when d > ndims(A). Likewise, in Base there is a dedicated function indices1 which is equivalent to indices(A, 1) but which avoids checking (at runtime) whether ndims(A) > 0. (This is purely a performance optimization.) It is defined as:

    indices1(A::AbstractArray{T,0}) where {T} = OneTo(1)
    -indices1(A::AbstractArray) = indices(A)[1]

    If the first of these (the zero-dimensional case) is problematic for your custom array type, be sure to specialize it appropriately.

    Specializing similar

    Given your custom ZeroRange type, then you should also add the following two specializations for similar:

    function Base.similar(A::AbstractArray, T::Type, shape::Tuple{ZeroRange,Vararg{ZeroRange}})
    -    # body
    -end
    -
    -function Base.similar(f::Union{Function,DataType}, shape::Tuple{ZeroRange,Vararg{ZeroRange}})
    -    # body
    -end

    Both of these should allocate your custom array type.

    Specializing reshape

    Optionally, define a method

    Base.reshape(A::AbstractArray, shape::Tuple{ZeroRange,Vararg{ZeroRange}}) = ...

    and you can reshape an array so that the result has custom indices.

    Summary

    Writing code that doesn't make assumptions about indexing requires a few extra abstractions, but hopefully the necessary changes are relatively straightforward.

    As a reminder, this support is still experimental. While much of Julia's base code has been updated to support unconventional indexing, without a doubt there are many omissions that will be discovered only through usage. Moreover, at the time of this writing, most packages do not support unconventional indexing. As a consequence, early adopters should be prepared to identify and/or fix bugs. On the other hand, only through practical usage will it become clear whether this experimental feature should be retained in future versions of Julia; consequently, interested parties are encouraged to accept some ownership for putting it through its paces.

    diff --git a/julia-0.6.3/share/doc/julia/html/en/devdocs/reflection.html b/julia-0.6.3/share/doc/julia/html/en/devdocs/reflection.html deleted file mode 100644 index 64ac153..0000000 --- a/julia-0.6.3/share/doc/julia/html/en/devdocs/reflection.html +++ /dev/null @@ -1,39 +0,0 @@ - -Reflection and introspection · The Julia Language

    Reflection and introspection

    Reflection and introspection

    Julia provides a variety of runtime reflection capabilities.

    Module bindings

    The exported names for a Module are available using names(m::Module), which will return an array of Symbol elements representing the exported bindings. names(m::Module, true) returns symbols for all bindings in m, regardless of export status.

    DataType fields

    The names of DataType fields may be interrogated using fieldnames(). For example, given the following type, fieldnames(Point) returns an arrays of Symbol elements representing the field names:

    julia> struct Point
    -           x::Int
    -           y
    -       end
    -
    -julia> fieldnames(Point)
    -2-element Array{Symbol,1}:
    - :x
    - :y

    The type of each field in a Point object is stored in the types field of the Point variable itself:

    julia> Point.types
    -svec(Int64, Any)

    While x is annotated as an Int, y was unannotated in the type definition, therefore y defaults to the Any type.

    Types are themselves represented as a structure called DataType:

    julia> typeof(Point)
    -DataType

    Note that fieldnames(DataType) gives the names for each field of DataType itself, and one of these fields is the types field observed in the example above.

    Subtypes

    The direct subtypes of any DataType may be listed using subtypes(). For example, the abstract DataType AbstractFloat has four (concrete) subtypes:

    julia> subtypes(AbstractFloat)
    -4-element Array{Union{DataType, UnionAll},1}:
    - BigFloat
    - Float16
    - Float32
    - Float64

    Any abstract subtype will also be included in this list, but further subtypes thereof will not; recursive application of subtypes() may be used to inspect the full type tree.

    DataType layout

    The internal representation of a DataType is critically important when interfacing with C code and several functions are available to inspect these details. isbits(T::DataType) returns true if T is stored with C-compatible alignment. fieldoffset(T::DataType, i::Integer) returns the (byte) offset for field i relative to the start of the type.

    Function methods

    The methods of any generic function may be listed using methods(). The method dispatch table may be searched for methods accepting a given type using methodswith().

    Expansion and lowering

    As discussed in the Metaprogramming section, the macroexpand() function gives the unquoted and interpolated expression (Expr) form for a given macro. To use macroexpand, quote the expression block itself (otherwise, the macro will be evaluated and the result will be passed instead!). For example:

    julia> macroexpand( :(@edit println("")) )
    -:((Base.edit)(println, (Base.typesof)("")))

    The functions Base.Meta.show_sexpr() and dump() are used to display S-expr style views and depth-nested detail views for any expression.

    Finally, the expand() function gives the lowered form of any expression and is of particular interest for understanding both macros and top-level statements such as function declarations and variable assignments:

    julia> expand( :(f() = 1) )
    -:(begin
    -        $(Expr(:method, :f))
    -        $(Expr(:method, :f, :((Core.svec)((Core.svec)((Core.Typeof)(f)), (Core.svec)())), CodeInfo(:(begin  # none, line 1:
    -        return 1
    -    end)), false))
    -        return f
    -    end)

    Intermediate and compiled representations

    Inspecting the lowered form for functions requires selection of the specific method to display, because generic functions may have many methods with different type signatures. For this purpose, method-specific code-lowering is available using code_lowered(f::Function, (Argtypes...)), and the type-inferred form is available using code_typed(f::Function, (Argtypes...)). code_warntype(f::Function, (Argtypes...)) adds highlighting to the output of code_typed() (see @code_warntype).

    Closer to the machine, the LLVM intermediate representation of a function may be printed using by code_llvm(f::Function, (Argtypes...)), and finally the compiled machine code is available using code_native(f::Function, (Argtypes...)) (this will trigger JIT compilation/code generation for any function which has not previously been called).

    For convenience, there are macro versions of the above functions which take standard function calls and expand argument types automatically:

    julia> @code_llvm +(1,1)
    -
    -; Function Attrs: sspreq
    -define i64 @"julia_+_130862"(i64, i64) #0 {
    -top:
    -    %2 = add i64 %1, %0, !dbg !8
    -    ret i64 %2, !dbg !8
    -}

    (likewise @code_typed, @code_warntype, @code_lowered, and @code_native)

    diff --git a/julia-0.6.3/share/doc/julia/html/en/devdocs/require.html b/julia-0.6.3/share/doc/julia/html/en/devdocs/require.html deleted file mode 100644 index 5e506cd..0000000 --- a/julia-0.6.3/share/doc/julia/html/en/devdocs/require.html +++ /dev/null @@ -1,22 +0,0 @@ - -Module loading · The Julia Language

    Module loading

    Module loading

    Base.require[@ref] is responsible for loading modules and it also manages the precompilation cache. It is the implementation of the import statement.

    Experimental features

    The features below are experimental and not part of the stable Julia API. Before building upon them inform yourself about the current thinking and whether they might change soon.

    Module loading callbacks

    It is possible to listen to the modules loaded by Base.require, by registering a callback.

    loaded_packages = Channel{Symbol}()
    -callback = (mod::Symbol) -> put!(loaded_packages, mod)
    -push!(Base.package_callbacks, callback)

    Please note that the symbol given to the callback is a non-unique identifier and it is the responsibility of the callback provider to walk the module chain to determine the fully qualified name of the loaded binding.

    The callback below is an example of how to do that:

    # Get the fully-qualified name of a module.
    -function module_fqn(name::Symbol)
    -    fqn = Symbol[name]
    -    mod = getfield(Main, name)
    -    parent = Base.module_parent(mod)
    -    while parent !== Main
    -        push!(fqn, Base.module_name(parent))
    -        parent = Base.module_parent(parent)
    -    end
    -    fqn = reverse!(fqn)
    -    return join(fqn, '.')
    -end
    diff --git a/julia-0.6.3/share/doc/julia/html/en/devdocs/sanitizers.html b/julia-0.6.3/share/doc/julia/html/en/devdocs/sanitizers.html deleted file mode 100644 index f02881d..0000000 --- a/julia-0.6.3/share/doc/julia/html/en/devdocs/sanitizers.html +++ /dev/null @@ -1,9 +0,0 @@ - -Sanitizer support · The Julia Language

    Sanitizer support

    Sanitizer support

    General considerations

    Using Clang's sanitizers obviously require you to use Clang (USECLANG=1), but there's another catch: most sanitizers require a run-time library, provided by the host compiler, while the instrumented code generated by Julia's JIT relies on functionality from that library. This implies that the LLVM version of your host compiler matches that of the LLVM library used within Julia.

    An easy solution is to have an dedicated build folder for providing a matching toolchain, by building with BUILD_LLVM_CLANG=1 and overriding LLVM_USE_CMAKE=1 (Autotool-based builds are incompatible with ASAN). You can then refer to this toolchain from another build folder by specifying USECLANG=1 while overriding the CC and CXX variables.

    Address Sanitizer (ASAN)

    For detecting or debugging memory bugs, you can use Clang's address sanitizer (ASAN). By compiling with SANITIZE=1 you enable ASAN for the Julia compiler and its generated code. In addition, you can specify LLVM_SANITIZE=1 to sanitize the LLVM library as well. Note that these options incur a high performance and memory cost. For example, using ASAN for Julia and LLVM makes testall1 takes 8-10 times as long while using 20 times as much memory (this can be reduced to respectively a factor of 3 and 4 by using the options described below).

    By default, Julia sets the allow_user_segv_handler=1 ASAN flag, which is required for signal delivery to work properly. You can define other options using the ASAN_OPTIONS environment flag, in which case you'll need to repeat the default option mentioned before. For example, memory usage can be reduced by specifying fast_unwind_on_malloc=0 and malloc_context_size=2, at the cost of backtrace accuracy. For now, Julia also sets detect_leaks=0, but this should be removed in the future.

    Memory Sanitizer (MSAN)

    For detecting use of uninitialized memory, you can use Clang's memory sanitizer (MSAN) by compiling with SANITIZE_MEMORY=1.

    diff --git a/julia-0.6.3/share/doc/julia/html/en/devdocs/stdio.html b/julia-0.6.3/share/doc/julia/html/en/devdocs/stdio.html deleted file mode 100644 index ea8b7d5..0000000 --- a/julia-0.6.3/share/doc/julia/html/en/devdocs/stdio.html +++ /dev/null @@ -1,24 +0,0 @@ - -printf() and stdio in the Julia runtime · The Julia Language

    printf() and stdio in the Julia runtime

    printf() and stdio in the Julia runtime

    Libuv wrappers for stdio

    julia.h defines libuv wrappers for the stdio.h streams:

    uv_stream_t *JL_STDIN;
    -uv_stream_t *JL_STDOUT;
    -uv_stream_t *JL_STDERR;

    ... and corresponding output functions:

    int jl_printf(uv_stream_t *s, const char *format, ...);
    -int jl_vprintf(uv_stream_t *s, const char *format, va_list args);

    These printf functions are used by the .c files in the src/ and ui/ directories wherever stdio is needed to ensure that output buffering is handled in a unified way.

    In special cases, like signal handlers, where the full libuv infrastructure is too heavy, jl_safe_printf() can be used to write(2) directly to STDERR_FILENO:

    void jl_safe_printf(const char *str, ...);

    Interface between JL_STD* and Julia code

    Base.STDIN, Base.STDOUT and Base.STDERR are bound to the JL_STD* libuv streams defined in the runtime.

    Julia's __init__() function (in base/sysimg.jl) calls reinit_stdio() (in base/stream.jl) to create Julia objects for Base.STDIN, Base.STDOUT and Base.STDERR.

    reinit_stdio() uses ccall to retrieve pointers to JL_STD* and calls jl_uv_handle_type() to inspect the type of each stream. It then creates a Julia Base.IOStream, Base.TTY or Base.PipeEndpoint object to represent each stream, e.g.:

    $ julia -e 'println(typeof((STDIN, STDOUT, STDERR)))'
    -Tuple{Base.TTY,Base.TTY,Base.TTY}
    -
    -$ julia -e 'println(typeof((STDIN, STDOUT, STDERR)))' < /dev/null 2>/dev/null
    -Tuple{IOStream,Base.TTY,IOStream}
    -
    -$ echo hello | julia -e 'println(typeof((STDIN, STDOUT, STDERR)))' | cat
    -Tuple{Base.PipeEndpoint,Base.PipeEndpoint,Base.TTY}

    The Base.read() and Base.write() methods for these streams use ccall to call libuv wrappers in src/jl_uv.c, e.g.:

    stream.jl: function write(s::IO, p::Ptr, nb::Integer)
    -               -> ccall(:jl_uv_write, ...)
    -  jl_uv.c:          -> int jl_uv_write(uv_stream_t *stream, ...)
    -                        -> uv_write(uvw, stream, buf, ...)

    printf() during initialization

    The libuv streams relied upon by jl_printf() etc., are not available until midway through initialization of the runtime (see init.c, init_stdio()). Error messages or warnings that need to be printed before this are routed to the standard C library fwrite() function by the following mechanism:

    In sys.c, the JL_STD* stream pointers are statically initialized to integer constants: STD*_FILENO (0, 1 and 2). In jl_uv.c the jl_uv_puts() function checks its uv_stream_t* stream argument and calls fwrite() if stream is set to STDOUT_FILENO or STDERR_FILENO.

    This allows for uniform use of jl_printf() throughout the runtime regardless of whether or not any particular piece of code is reachable before initialization is complete.

    Legacy ios.c library

    The src/support/ios.c library is inherited from femtolisp. It provides cross-platform buffered file IO and in-memory temporary buffers.

    ios.c is still used by:

    • src/flisp/*.c

    • src/dump.c – for serialization file IO and for memory buffers.

    • base/iostream.jl – for file IO (see base/fs.jl for libuv equivalent).

    Use of ios.c in these modules is mostly self-contained and separated from the libuv I/O system. However, there is one place where femtolisp calls through to jl_printf() with a legacy ios_t stream.

    There is a hack in ios.h that makes the ios_t.bm field line up with the uv_stream_t.type and ensures that the values used for ios_t.bm to not overlap with valid UV_HANDLE_TYPE values. This allows uv_stream_t pointers to point to ios_t streams.

    This is needed because jl_printf() caller jl_static_show() is passed an ios_t stream by femtolisp's fl_print() function. Julia's jl_uv_puts() function has special handling for this:

    if (stream->type > UV_HANDLE_TYPE_MAX) {
    -    return ios_write((ios_t*)stream, str, n);
    -}
    diff --git a/julia-0.6.3/share/doc/julia/html/en/devdocs/subarrays.html b/julia-0.6.3/share/doc/julia/html/en/devdocs/subarrays.html deleted file mode 100644 index c41db89..0000000 --- a/julia-0.6.3/share/doc/julia/html/en/devdocs/subarrays.html +++ /dev/null @@ -1,62 +0,0 @@ - -SubArrays · The Julia Language

    SubArrays

    SubArrays

    Julia's SubArray type is a container encoding a "view" of a parent AbstractArray. This page documents some of the design principles and implementation of SubArrays.

    Indexing: cartesian vs. linear indexing

    Broadly speaking, there are two main ways to access data in an array. The first, often called cartesian indexing, uses N indexes for an N -dimensional AbstractArray. For example, a matrix A (2-dimensional) can be indexed in cartesian style as A[i,j]. The second indexing method, referred to as linear indexing, uses a single index even for higher-dimensional objects. For example, if A = reshape(1:12, 3, 4), then the expression A[5] returns the value 5. Julia allows you to combine these styles of indexing: for example, a 3d array A3 can be indexed as A3[i,j], in which case i is interpreted as a cartesian index for the first dimension, and j is a linear index over dimensions 2 and 3.

    For Arrays, linear indexing appeals to the underlying storage format: an array is laid out as a contiguous block of memory, and hence the linear index is just the offset (+1) of the corresponding entry relative to the beginning of the array. However, this is not true for many other AbstractArray types: examples include SparseMatrixCSC, arrays that require some kind of computation (such as interpolation), and the type under discussion here, SubArray. For these types, the underlying information is more naturally described in terms of cartesian indexes.

    You can manually convert from a cartesian index to a linear index with sub2ind, and vice versa using ind2sub. getindex and setindex! functions for AbstractArray types may include similar operations.

    While converting from a cartesian index to a linear index is fast (it's just multiplication and addition), converting from a linear index to a cartesian index is very slow: it relies on the div operation, which is one of the slowest low-level operations you can perform with a CPU. For this reason, any code that deals with AbstractArray types is best designed in terms of cartesian, rather than linear, indexing.

    Index replacement

    Consider making 2d slices of a 3d array:

    S1 = view(A, :, 5, 2:6)
    -S2 = view(A, 5, :, 2:6)

    view drops "singleton" dimensions (ones that are specified by an Int), so both S1 and S2 are two-dimensional SubArrays. Consequently, the natural way to index these is with S1[i,j]. To extract the value from the parent array A, the natural approach is to replace S1[i,j] with A[i,5,(2:6)[j]] and S2[i,j] with A[5,i,(2:6)[j]].

    The key feature of the design of SubArrays is that this index replacement can be performed without any runtime overhead.

    SubArray design

    Type parameters and fields

    The strategy adopted is first and foremost expressed in the definition of the type:

    struct SubArray{T,N,P,I,L} <: AbstractArray{T,N}
    -    parent::P
    -    indexes::I
    -    offset1::Int       # for linear indexing and pointer, only valid when L==true
    -    stride1::Int       # used only for linear indexing
    -    ...
    -end

    SubArray has 5 type parameters. The first two are the standard element type and dimensionality. The next is the type of the parent AbstractArray. The most heavily-used is the fourth parameter, a Tuple of the types of the indices for each dimension. The final one, L, is only provided as a convenience for dispatch; it's a boolean that represents whether the index types support fast linear indexing. More on that later.

    If in our example above A is a Array{Float64, 3}, our S1 case above would be a SubArray{Int64,2,Array{Int64,3},Tuple{Colon,Int64,UnitRange{Int64}},false}. Note in particular the tuple parameter, which stores the types of the indices used to create S1. Likewise,

    julia> S1.indexes
    -(Colon(),5,2:6)

    Storing these values allows index replacement, and having the types encoded as parameters allows one to dispatch to efficient algorithms.

    Index translation

    Performing index translation requires that you do different things for different concrete SubArray types. For example, for S1, one needs to apply the i,j indices to the first and third dimensions of the parent array, whereas for S2 one needs to apply them to the second and third. The simplest approach to indexing would be to do the type-analysis at runtime:

    parentindexes = Array{Any}(0)
    -for thisindex in S.indexes
    -    ...
    -    if isa(thisindex, Int)
    -        # Don't consume one of the input indexes
    -        push!(parentindexes, thisindex)
    -    elseif isa(thisindex, AbstractVector)
    -        # Consume an input index
    -        push!(parentindexes, thisindex[inputindex[j]])
    -        j += 1
    -    elseif isa(thisindex, AbstractMatrix)
    -        # Consume two input indices
    -        push!(parentindexes, thisindex[inputindex[j], inputindex[j+1]])
    -        j += 2
    -    elseif ...
    -end
    -S.parent[parentindexes...]

    Unfortunately, this would be disastrous in terms of performance: each element access would allocate memory, and involves the running of a lot of poorly-typed code.

    The better approach is to dispatch to specific methods to handle each type of stored index. That's what reindex does: it dispatches on the type of the first stored index and consumes the appropriate number of input indices, and then it recurses on the remaining indices. In the case of S1, this expands to

    Base.reindex(S1, S1.indexes, (i, j)) == (i, S1.indexes[2], S1.indexes[3][j])

    for any pair of indices (i,j) (except CartesianIndexs and arrays thereof, see below).

    This is the core of a SubArray; indexing methods depend upon reindex to do this index translation. Sometimes, though, we can avoid the indirection and make it even faster.

    Linear indexing

    Linear indexing can be implemented efficiently when the entire array has a single stride that separates successive elements, starting from some offset. This means that we can pre-compute these values and represent linear indexing simply as an addition and multiplication, avoiding the indirection of reindex and (more importantly) the slow computation of the cartesian coordinates entirely.

    For SubArray types, the availability of efficient linear indexing is based purely on the types of the indices, and does not depend on values like the size of the parent array. You can ask whether a given set of indices supports fast linear indexing with the internal Base.viewindexing function:

    julia> Base.viewindexing(S1.indexes)
    -IndexCartesian()
    -
    -julia> Base.viewindexing(S2.indexes)
    -IndexLinear()

    This is computed during construction of the SubArray and stored in the L type parameter as a boolean that encodes fast linear indexing support. While not strictly necessary, it means that we can define dispatch directly on SubArray{T,N,A,I,true} without any intermediaries.

    Since this computation doesn't depend on runtime values, it can miss some cases in which the stride happens to be uniform:

    julia> A = reshape(1:4*2, 4, 2)
    -4×2 Base.ReshapedArray{Int64,2,UnitRange{Int64},Tuple{}}:
    - 1  5
    - 2  6
    - 3  7
    - 4  8
    -
    -julia> diff(A[2:2:4,:][:])
    -3-element Array{Int64,1}:
    - 2
    - 2
    - 2

    A view constructed as view(A, 2:2:4, :) happens to have uniform stride, and therefore linear indexing indeed could be performed efficiently. However, success in this case depends on the size of the array: if the first dimension instead were odd,

    julia> A = reshape(1:5*2, 5, 2)
    -5×2 Base.ReshapedArray{Int64,2,UnitRange{Int64},Tuple{}}:
    - 1   6
    - 2   7
    - 3   8
    - 4   9
    - 5  10
    -
    -julia> diff(A[2:2:4,:][:])
    -3-element Array{Int64,1}:
    - 2
    - 3
    - 2

    then A[2:2:4,:] does not have uniform stride, so we cannot guarantee efficient linear indexing. Since we have to base this decision based purely on types encoded in the parameters of the SubArray, S = view(A, 2:2:4, :) cannot implement efficient linear indexing.

    A few details

    • Note that the Base.reindex function is agnostic to the types of the input indices; it simply determines how and where the stored indices should be reindexed. It not only supports integer indices, but it supports non-scalar indexing, too. This means that views of views don't need two levels of indirection; they can simply re-compute the indices into the original parent array!

    • Hopefully by now it's fairly clear that supporting slices means that the dimensionality, given by the parameter N, is not necessarily equal to the dimensionality of the parent array or the length of the indexes tuple. Neither do user-supplied indices necessarily line up with entries in the indexes tuple (e.g., the second user-supplied index might correspond to the third dimension of the parent array, and the third element in the indexes tuple).

      What might be less obvious is that the dimensionality of the stored parent array must be equal to the number of effective indices in the indexes tuple. Some examples:

      A = reshape(1:35, 5, 7) # A 2d parent Array
      -S = view(A, 2:7)         # A 1d view created by linear indexing
      -S = view(A, :, :, 1:1)   # Appending extra indices is supported

      Naively, you'd think you could just set S.parent = A and S.indexes = (:,:,1:1), but supporting this dramatically complicates the reindexing process, especially for views of views. Not only do you need to dispatch on the types of the stored indices, but you need to examine whether a given index is the final one and "merge" any remaining stored indices together. This is not an easy task, and even worse: it's slow since it implicitly depends upon linear indexing.

      Fortunately, this is precisely the computation that ReshapedArray performs, and it does so linearly if possible. Consequently, view ensures that the parent array is the appropriate dimensionality for the given indices by reshaping it if needed. The inner SubArray constructor ensures that this invariant is satisfied.

    • CartesianIndex and arrays thereof throw a nasty wrench into the reindex scheme. Recall that reindex simply dispatches on the type of the stored indices in order to determine how many passed indices should be used and where they should go. But with CartesianIndex, there's no longer a one-to-one correspondence between the number of passed arguments and the number of dimensions that they index into. If we return to the above example of Base.reindex(S1, S1.indexes, (i, j)), you can see that the expansion is incorrect for i, j = CartesianIndex(), CartesianIndex(2,1). It should skip the CartesianIndex() entirely and return:

      (CartesianIndex(2,1)[1], S1.indexes[2], S1.indexes[3][CartesianIndex(2,1)[2]])

      Instead, though, we get:

      (CartesianIndex(), S1.indexes[2], S1.indexes[3][CartesianIndex(2,1)])

      Doing this correctly would require combined dispatch on both the stored and passed indices across all combinations of dimensionalities in an intractable manner. As such, reindex must never be called with CartesianIndex indices. Fortunately, the scalar case is easily handled by first flattening the CartesianIndex arguments to plain integers. Arrays of CartesianIndex, however, cannot be split apart into orthogonal pieces so easily. Before attempting to use reindex, view must ensure that there are no arrays of CartesianIndex in the argument list. If there are, it can simply "punt" by avoiding the reindex calculation entirely, constructing a nested SubArray with two levels of indirection instead.

    diff --git a/julia-0.6.3/share/doc/julia/html/en/devdocs/sysimg.html b/julia-0.6.3/share/doc/julia/html/en/devdocs/sysimg.html deleted file mode 100644 index 7d2ede1..0000000 --- a/julia-0.6.3/share/doc/julia/html/en/devdocs/sysimg.html +++ /dev/null @@ -1,9 +0,0 @@ - -System Image Building · The Julia Language

    System Image Building

    System Image Building

    Building the Julia system image

    Julia ships with a preparsed system image containing the contents of the Base module, named sys.ji. This file is also precompiled into a shared library called sys.{so,dll,dylib} on as many platforms as possible, so as to give vastly improved startup times. On systems that do not ship with a precompiled system image file, one can be generated from the source files shipped in Julia's DATAROOTDIR/julia/base folder.

    This operation is useful for multiple reasons. A user may:

    • Build a precompiled shared library system image on a platform that did not ship with one, thereby improving startup times.

    • Modify Base, rebuild the system image and use the new Base next time Julia is started.

    • Include a userimg.jl file that includes packages into the system image, thereby creating a system image that has packages embedded into the startup environment.

    Julia now ships with a script that automates the tasks of building the system image, wittingly named build_sysimg.jl that lives in DATAROOTDIR/julia/. That is, to include it into a current Julia session, type:

    include(joinpath(JULIA_HOME, Base.DATAROOTDIR, "julia", "build_sysimg.jl"))

    This will include a build_sysimg() function:

    build_sysimg(sysimg_path=default_sysimg_path(), cpu_target="native", userimg_path=nothing; force=false)

    Rebuild the system image. Store it in sysimg_path, which defaults to a file named sys.ji that sits in the same folder as libjulia.{so,dylib}, except on Windows where it defaults to JULIA_HOME/../lib/julia/sys.ji. Use the cpu instruction set given by cpu_target. Valid CPU targets are the same as for the -C option to julia, or the -march option to gcc. Defaults to native, which means to use all CPU instructions available on the current processor. Include the user image file given by userimg_path, which should contain directives such as using MyPackage to include that package in the new system image. New system image will not replace an older image unless force is set to true.

    source

    Note that this file can also be run as a script itself, with command line arguments taking the place of arguments passed to the build_sysimg function. For example, to build a system image in /tmp/sys.{so,dll,dylib}, with the core2 CPU instruction set, a user image of ~/userimg.jl and force set to true, one would execute:

    julia build_sysimg.jl /tmp/sys core2 ~/userimg.jl --force
    diff --git a/julia-0.6.3/share/doc/julia/html/en/devdocs/types.html b/julia-0.6.3/share/doc/julia/html/en/devdocs/types.html deleted file mode 100644 index 42c1e1f..0000000 --- a/julia-0.6.3/share/doc/julia/html/en/devdocs/types.html +++ /dev/null @@ -1,145 +0,0 @@ - -More about types · The Julia Language

    More about types

    More about types

    If you've used Julia for a while, you understand the fundamental role that types play. Here we try to get under the hood, focusing particularly on Parametric Types.

    Types and sets (and Any and Union{}/Bottom)

    It's perhaps easiest to conceive of Julia's type system in terms of sets. While programs manipulate individual values, a type refers to a set of values. This is not the same thing as a collection; for example a Set of values is itself a single Set value. Rather, a type describes a set of possible values, expressing uncertainty about which value we have.

    A concrete type T describes the set of values whose direct tag, as returned by the typeof function, is T. An abstract type describes some possibly-larger set of values.

    Any describes the entire universe of possible values. Integer is a subset of Any that includes Int, Int8, and other concrete types. Internally, Julia also makes heavy use of another type known as Bottom, which can also be written as Union{}. This corresponds to the empty set.

    Julia's types support the standard operations of set theory: you can ask whether T1 is a "subset" (subtype) of T2 with T1 <: T2. Likewise, you intersect two types using typeintersect, take their union with Union, and compute a type that contains their union with typejoin:

    julia> typeintersect(Int, Float64)
    -Union{}
    -
    -julia> Union{Int, Float64}
    -Union{Float64, Int64}
    -
    -julia> typejoin(Int, Float64)
    -Real
    -
    -julia> typeintersect(Signed, Union{UInt8, Int8})
    -Int8
    -
    -julia> Union{Signed, Union{UInt8, Int8}}
    -Union{Signed, UInt8}
    -
    -julia> typejoin(Signed, Union{UInt8, Int8})
    -Integer
    -
    -julia> typeintersect(Tuple{Integer,Float64}, Tuple{Int,Real})
    -Tuple{Int64,Float64}
    -
    -julia> Union{Tuple{Integer,Float64}, Tuple{Int,Real}}
    -Union{Tuple{Int64,Real}, Tuple{Integer,Float64}}
    -
    -julia> typejoin(Tuple{Integer,Float64}, Tuple{Int,Real})
    -Tuple{Integer,Real}

    While these operations may seem abstract, they lie at the heart of Julia. For example, method dispatch is implemented by stepping through the items in a method list until reaching one for which the type of the argument tuple is a subtype of the method signature. For this algorithm to work, it's important that methods be sorted by their specificity, and that the search begins with the most specific methods. Consequently, Julia also implements a partial order on types; this is achieved by functionality that is similar to <:, but with differences that will be discussed below.

    UnionAll types

    Julia's type system can also express an iterated union of types: a union of types over all values of some variable. This is needed to describe parametric types where the values of some parameters are not known.

    For example, :obj:Array has two parameters as in Array{Int,2}. If we did not know the element type, we could write Array{T,2} where T, which is the union of Array{T,2} for all values of T: Union{Array{Int8,2}, Array{Int16,2}, ...}.

    Such a type is represented by a UnionAll object, which contains a variable (T in this example, of type TypeVar), and a wrapped type (Array{T,2} in this example).

    Consider the following methods:

    f1(A::Array) = 1
    -f2(A::Array{Int}) = 2
    -f3(A::Array{T}) where {T<:Any} = 3
    -f4(A::Array{Any}) = 4

    The signature of f3 is a UnionAll type wrapping a tuple type. All but f4 can be called with a = [1,2]; all but f2 can be called with b = Any[1,2].

    Let's look at these types a little more closely:

    julia> dump(Array)
    -UnionAll
    -  var: TypeVar
    -    name: Symbol T
    -    lb: Core.TypeofBottom Union{}
    -    ub: Any
    -  body: UnionAll
    -    var: TypeVar
    -      name: Symbol N
    -      lb: Core.TypeofBottom Union{}
    -      ub: Any
    -    body: Array{T,N} <: DenseArray{T,N}

    This indicates that Array actually names a UnionAll type. There is one UnionAll type for each parameter, nested. The syntax Array{Int,2} is equivalent to Array{Int}{2}; internally each UnionAll is instantiated with a particular variable value, one at a time, outermost-first. This gives a natural meaning to the omission of trailing type parameters; Array{Int} gives a type equivalent to Array{Int,N} where N.

    A TypeVar is not itself a type, but rather should be considered part of the structure of a UnionAll type. Type variables have lower and upper bounds on their values (in the fields lb and ub). The symbol name is purely cosmetic. Internally, TypeVars are compared by address, so they are defined as mutable types to ensure that "different" type variables can be distinguished. However, by convention they should not be mutated.

    One can construct TypeVars manually:

    julia> TypeVar(:V, Signed, Real)
    -Signed<:V<:Real

    There are convenience versions that allow you to omit any of these arguments except the name symbol.

    The syntax Array{T} where T<:Integer is lowered to

    let T = TypeVar(:T,Integer)
    -    UnionAll(T, Array{T})
    -end

    so it is seldom necessary to construct a TypeVar manually (indeed, this is to be avoided).

    Free variables

    The concept of a free type variable is extremely important in the type system. We say that a variable V is free in type T if T does not contain the UnionAll that introduces variable V. For example, the type Array{Array{V} where V<:Integer} has no free variables, but the Array{V} part inside of it does have a free variable, V.

    A type with free variables is, in some sense, not really a type at all. Consider the type Array{Array{T}} where T, which refers to all homogeneous arrays of arrays. The inner type Array{T}, seen by itself, might seem to refer to any kind of array. However, every element of the outer array must have the same array type, so Array{T} cannot refer to just any old array. One could say that Array{T} effectively "occurs" multiple times, and T must have the same value each "time".

    For this reason, the function jl_has_free_typevars in the C API is very important. Types for which it returns true will not give meaningful answers in subtyping and other type functions.

    TypeNames

    The following two Array types are functionally equivalent, yet print differently:

    julia> TV, NV = TypeVar(:T), TypeVar(:N)
    -(T, N)
    -
    -julia> Array
    -Array
    -
    -julia> Array{TV,NV}
    -Array{T,N}

    These can be distinguished by examining the name field of the type, which is an object of type TypeName:

    julia> dump(Array{Int,1}.name)
    -TypeName
    -  name: Symbol Array
    -  module: Module Core
    -  names: empty SimpleVector
    -  wrapper: UnionAll
    -    var: TypeVar
    -      name: Symbol T
    -      lb: Core.TypeofBottom Union{}
    -      ub: Any
    -    body: UnionAll
    -      var: TypeVar
    -        name: Symbol N
    -        lb: Core.TypeofBottom Union{}
    -        ub: Any
    -      body: Array{T,N} <: DenseArray{T,N}
    -  cache: SimpleVector
    -    ...
    -
    -  linearcache: SimpleVector
    -    ...
    -
    -  hash: Int64 -7900426068641098781
    -  mt: MethodTable
    -    name: Symbol Array
    -    defs: Void nothing
    -    cache: Void nothing
    -    max_args: Int64 0
    -    kwsorter: #undef
    -    module: Module Core
    -    : Int64 0
    -    : Int64 0

    In this case, the relevant field is wrapper, which holds a reference to the top-level type used to make new Array types.

    julia> pointer_from_objref(Array)
    -Ptr{Void} @0x00007fcc7de64850
    -
    -julia> pointer_from_objref(Array.body.body.name.wrapper)
    -Ptr{Void} @0x00007fcc7de64850
    -
    -julia> pointer_from_objref(Array{TV,NV})
    -Ptr{Void} @0x00007fcc80c4d930
    -
    -julia> pointer_from_objref(Array{TV,NV}.name.wrapper)
    -Ptr{Void} @0x00007fcc7de64850

    The wrapper field of Array points to itself, but for Array{TV,NV} it points back to the original definition of the type.

    What about the other fields? hash assigns an integer to each type. To examine the cache field, it's helpful to pick a type that is less heavily used than Array. Let's first create our own type:

    julia> struct MyType{T,N} end
    -
    -julia> MyType{Int,2}
    -MyType{Int64,2}
    -
    -julia> MyType{Float32, 5}
    -MyType{Float32,5}
    -
    -julia> MyType.body.body.name.cache
    -svec(MyType{Float32,5}, MyType{Int64,2}, #undef, #undef, #undef, #undef, #undef, #undef)

    (The cache is pre-allocated to have length 8, but only the first two entries are populated.) Consequently, when you instantiate a parametric type, each concrete type gets saved in a type cache. However, instances containing free type variables are not cached.

    Tuple types

    Tuple types constitute an interesting special case. For dispatch to work on declarations like x::Tuple, the type has to be able to accommodate any tuple. Let's check the parameters:

    julia> Tuple
    -Tuple
    -
    -julia> Tuple.parameters
    -svec(Vararg{Any,N} where N)

    Unlike other types, tuple types are covariant in their parameters, so this definition permits Tuple to match any type of tuple:

    julia> typeintersect(Tuple, Tuple{Int,Float64})
    -Tuple{Int64,Float64}
    -
    -julia> typeintersect(Tuple{Vararg{Any}}, Tuple{Int,Float64})
    -Tuple{Int64,Float64}

    However, if a variadic (Vararg) tuple type has free variables it can describe different kinds of tuples:

    julia> typeintersect(Tuple{Vararg{T} where T}, Tuple{Int,Float64})
    -Tuple{Int64,Float64}
    -
    -julia> typeintersect(Tuple{Vararg{T}} where T, Tuple{Int,Float64})
    -Union{}

    Notice that when T is free with respect to the Tuple type (i.e. its binding UnionAll type is outside the Tuple type), only one T value must work over the whole type. Therefore a heterogeneous tuple does not match.

    Finally, it's worth noting that Tuple{} is distinct:

    julia> Tuple{}
    -Tuple{}
    -
    -julia> Tuple{}.parameters
    -svec()
    -
    -julia> typeintersect(Tuple{}, Tuple{Int})
    -Union{}

    What is the "primary" tuple-type?

    julia> pointer_from_objref(Tuple)
    -Ptr{Void} @0x00007f5998a04370
    -
    -julia> pointer_from_objref(Tuple{})
    -Ptr{Void} @0x00007f5998a570d0
    -
    -julia> pointer_from_objref(Tuple.name.wrapper)
    -Ptr{Void} @0x00007f5998a04370
    -
    -julia> pointer_from_objref(Tuple{}.name.wrapper)
    -Ptr{Void} @0x00007f5998a04370

    so Tuple == Tuple{Vararg{Any}} is indeed the primary type.

    Diagonal types

    Consider the type Tuple{T,T} where T. A method with this signature would look like:

    f(x::T, y::T) where {T} = ...

    According to the usual interpretation of a UnionAll type, this T ranges over all types, including Any, so this type should be equivalent to Tuple{Any,Any}. However, this interpretation causes some practical problems.

    First, a value of T needs to be available inside the method definition. For a call like f(1, 1.0), it's not clear what T should be. It could be Union{Int,Float64}, or perhaps Real. Intuitively, we expect the declaration x::T to mean T === typeof(x). To make sure that invariant holds, we need typeof(x) === typeof(y) === T in this method. That implies the method should only be called for arguments of the exact same type.

    It turns out that being able to dispatch on whether two values have the same type is very useful (this is used by the promotion system for example), so we have multiple reasons to want a different interpretation of Tuple{T,T} where T. To make this work we add the following rule to subtyping: if a variable occurs more than once in covariant position, it is restricted to ranging over only concrete types. ("Covariant position" means that only Tuple and Union types occur between an occurrence of a variable and the UnionAll type that introduces it.) Such variables are called "diagonal variables" or "concrete variables".

    So for example, Tuple{T,T} where T can be seen as Union{Tuple{Int8,Int8}, Tuple{Int16,Int16}, ...}, where T ranges over all concrete types. This gives rise to some interesting subtyping results. For example Tuple{Real,Real} is not a subtype of Tuple{T,T} where T, because it includes some types like Tuple{Int8,Int16} where the two elements have different types. Tuple{Real,Real} and Tuple{T,T} where T have the non-trivial intersection Tuple{T,T} where T<:Real. However, Tuple{Real} is a subtype of Tuple{T} where T, because in that case T occurs only once and so is not diagonal.

    Next consider a signature like the following:

    f(a::Array{T}, x::T, y::T) where {T} = ...

    In this case, T occurs in invariant position inside Array{T}. That means whatever type of array is passed unambiguously determines the value of T –- we say T has an equality constraint on it. Therefore in this case the diagonal rule is not really necessary, since the array determines T and we can then allow x and y to be of any subtypes of T. So variables that occur in invariant position are never considered diagonal. This choice of behavior is slightly controversial –- some feel this definition should be written as

    f(a::Array{T}, x::S, y::S) where {T, S<:T} = ...

    to clarify whether x and y need to have the same type. In this version of the signature they would, or we could introduce a third variable for the type of y if x and y can have different types.

    The next complication is the interaction of unions and diagonal variables, e.g.

    f(x::Union{Void,T}, y::T) where {T} = ...

    Consider what this declaration means. y has type T. x then can have either the same type T, or else be of type Void. So all of the following calls should match:

    f(1, 1)
    -f("", "")
    -f(2.0, 2.0)
    -f(nothing, 1)
    -f(nothing, "")
    -f(nothing, 2.0)

    These examples are telling us something: when x is nothing::Void, there are no extra constraints on y. It is as if the method signature had y::Any. This means that whether a variable is diagonal is not a static property based on where it appears in a type. Rather, it depends on where a variable appears when the subtyping algorithm uses it. When x has type Void, we don't need to use the T in Union{Void,T}, so T does not "occur". Indeed, we have the following type equivalence:

    (Tuple{Union{Void,T},T} where T) == Union{Tuple{Void,Any}, Tuple{T,T} where T}

    Subtyping diagonal variables

    The subtyping algorithm for diagonal variables has two components: (1) identifying variable occurrences, and (2) ensuring that diagonal variables range over concrete types only.

    The first task is accomplished by keeping counters occurs_inv and occurs_cov (in src/subtype.c) for each variable in the environment, tracking the number of invariant and covariant occurrences, respectively. A variable is diagonal when occurs_inv == 0 && occurs_cov > 1.

    The second task is accomplished by imposing a condition on a variable's lower bound. As the subtyping algorithm runs, it narrows the bounds of each variable (raising lower bounds and lowering upper bounds) to keep track of the range of variable values for which the subtype relation would hold. When we are done evaluating the body of a UnionAll type whose variable is diagonal, we look at the final values of the bounds. Since the variable must be concrete, a contradiction occurs if its lower bound could not be a subtype of a concrete type. For example, an abstract type like AbstractArray cannot be a subtype of a concrete type, but a concrete type like Int can be, and the empty type Bottom can be as well. If a lower bound fails this test the algorithm stops with the answer false.

    For example, in the problem Tuple{Int,String} <: Tuple{T,T} where T, we derive that this would be true if T were a supertype of Union{Int,String}. However, Union{Int,String} is an abstract type, so the relation does not hold.

    This concreteness test is done by the function is_leaf_bound. Note that this test is slightly different from jl_is_leaf_type, since it also returns true for Bottom. Currently this function is heuristic, and does not catch all possible concrete types. The difficulty is that whether a lower bound is concrete might depend on the values of other type variable bounds. For example, Vector{T} is equivalent to the concrete type Vector{Int} only if both the upper and lower bounds of T equal Int. We have not yet worked out a complete algorithm for this.

    Introduction to the internal machinery

    Most operations for dealing with types are found in the files jltypes.c and subtype.c. A good way to start is to watch subtyping in action. Build Julia with make debug and fire up Julia within a debugger. gdb debugging tips has some tips which may be useful.

    Because the subtyping code is used heavily in the REPL itself–and hence breakpoints in this code get triggered often–it will be easiest if you make the following definition:

    julia> function mysubtype(a,b)
    -           ccall(:jl_breakpoint, Void, (Any,), nothing)
    -           issubtype(a, b)
    -       end

    and then set a breakpoint in jl_breakpoint. Once this breakpoint gets triggered, you can set breakpoints in other functions.

    As a warm-up, try the following:

    mysubtype(Tuple{Int,Float64}, Tuple{Integer,Real})

    We can make it more interesting by trying a more complex case:

    mysubtype(Tuple{Array{Int,2}, Int8}, Tuple{Array{T}, T} where T)

    Subtyping and method sorting

    The type_morespecific functions are used for imposing a partial order on functions in method tables (from most-to-least specific). Specificity is strict; if a is more specific than b, then a does not equal b and b is not more specific than a.

    If a is a strict subtype of b, then it is automatically considered more specific. From there, type_morespecific employs some less formal rules. For example, subtype is sensitive to the number of arguments, but type_morespecific may not be. In particular, Tuple{Int,AbstractFloat} is more specific than Tuple{Integer}, even though it is not a subtype. (Of Tuple{Int,AbstractFloat} and Tuple{Integer,Float64}, neither is more specific than the other.) Likewise, Tuple{Int,Vararg{Int}} is not a subtype of Tuple{Integer}, but it is considered more specific. However, morespecific does get a bonus for length: in particular, Tuple{Int,Int} is more specific than Tuple{Int,Vararg{Int}}.

    If you're debugging how methods get sorted, it can be convenient to define the function:

    type_morespecific(a, b) = ccall(:jl_type_morespecific, Cint, (Any,Any), a, b)

    which allows you to test whether tuple type a is more specific than tuple type b.

    diff --git a/julia-0.6.3/share/doc/julia/html/en/devdocs/valgrind.html b/julia-0.6.3/share/doc/julia/html/en/devdocs/valgrind.html deleted file mode 100644 index 9ba8128..0000000 --- a/julia-0.6.3/share/doc/julia/html/en/devdocs/valgrind.html +++ /dev/null @@ -1,9 +0,0 @@ - -Using Valgrind with Julia · The Julia Language

    Using Valgrind with Julia

    Using Valgrind with Julia

    Valgrind is a tool for memory debugging, memory leak detection, and profiling. This section describes things to keep in mind when using Valgrind to debug memory issues with Julia.

    General considerations

    By default, Valgrind assumes that there is no self modifying code in the programs it runs. This assumption works fine in most instances but fails miserably for a just-in-time compiler like julia. For this reason it is crucial to pass --smc-check=all-non-file to valgrind, else code may crash or behave unexpectedly (often in subtle ways).

    In some cases, to better detect memory errors using Valgrind it can help to compile julia with memory pools disabled. The compile-time flag MEMDEBUG disables memory pools in Julia, and MEMDEBUG2 disables memory pools in FemtoLisp. To build julia with both flags, add the following line to Make.user:

    CFLAGS = -DMEMDEBUG -DMEMDEBUG2

    Another thing to note: if your program uses multiple workers processes, it is likely that you want all such worker processes to run under Valgrind, not just the parent process. To do this, pass --trace-children=yes to valgrind.

    Suppressions

    Valgrind will typically display spurious warnings as it runs. To reduce the number of such warnings, it helps to provide a suppressions file to Valgrind. A sample suppressions file is included in the Julia source distribution at contrib/valgrind-julia.supp.

    The suppressions file can be used from the julia/ source directory as follows:

    $ valgrind --smc-check=all-non-file --suppressions=contrib/valgrind-julia.supp ./julia progname.jl

    Any memory errors that are displayed should either be reported as bugs or contributed as additional suppressions. Note that some versions of Valgrind are shipped with insufficient default suppressions, so that may be one thing to consider before submitting any bugs.

    Running the Julia test suite under Valgrind

    It is possible to run the entire Julia test suite under Valgrind, but it does take quite some time (typically several hours). To do so, run the following command from the julia/test/ directory:

    valgrind --smc-check=all-non-file --trace-children=yes --suppressions=$PWD/../contrib/valgrind-julia.supp ../julia runtests.jl all

    If you would like to see a report of "definite" memory leaks, pass the flags --leak-check=full --show-leak-kinds=definite to valgrind as well.

    Caveats

    Valgrind currently does not support multiple rounding modes, so code that adjusts the rounding mode will behave differently when run under Valgrind.

    In general, if after setting --smc-check=all-non-file you find that your program behaves differently when run under Valgrind, it may help to pass --tool=none to valgrind as you investigate further. This will enable the minimal Valgrind machinery but will also run much faster than when the full memory checker is enabled.

    diff --git a/julia-0.6.3/share/doc/julia/html/en/index.html b/julia-0.6.3/share/doc/julia/html/en/index.html deleted file mode 100644 index b1656f4..0000000 --- a/julia-0.6.3/share/doc/julia/html/en/index.html +++ /dev/null @@ -1,9 +0,0 @@ - -Home · The Julia Language

    Home

    Julia Documentation

    Manual

    Standard Library

    Developer Documentation

    diff --git a/julia-0.6.3/share/doc/julia/html/en/manual/arrays.html b/julia-0.6.3/share/doc/julia/html/en/manual/arrays.html deleted file mode 100644 index bfa47b0..0000000 --- a/julia-0.6.3/share/doc/julia/html/en/manual/arrays.html +++ /dev/null @@ -1,283 +0,0 @@ - -Multi-dimensional Arrays · The Julia Language

    Multi-dimensional Arrays

    Multi-dimensional Arrays

    Julia, like most technical computing languages, provides a first-class array implementation. Most technical computing languages pay a lot of attention to their array implementation at the expense of other containers. Julia does not treat arrays in any special way. The array library is implemented almost completely in Julia itself, and derives its performance from the compiler, just like any other code written in Julia. As such, it's also possible to define custom array types by inheriting from AbstractArray. See the manual section on the AbstractArray interface for more details on implementing a custom array type.

    An array is a collection of objects stored in a multi-dimensional grid. In the most general case, an array may contain objects of type Any. For most computational purposes, arrays should contain objects of a more specific type, such as Float64 or Int32.

    In general, unlike many other technical computing languages, Julia does not expect programs to be written in a vectorized style for performance. Julia's compiler uses type inference and generates optimized code for scalar array indexing, allowing programs to be written in a style that is convenient and readable, without sacrificing performance, and using less memory at times.

    In Julia, all arguments to functions are passed by reference. Some technical computing languages pass arrays by value, and this is convenient in many cases. In Julia, modifications made to input arrays within a function will be visible in the parent function. The entire Julia array library ensures that inputs are not modified by library functions. User code, if it needs to exhibit similar behavior, should take care to create a copy of inputs that it may modify.

    Arrays

    Basic Functions

    FunctionDescription
    eltype(A)the type of the elements contained in A
    length(A)the number of elements in A
    ndims(A)the number of dimensions of A
    size(A)a tuple containing the dimensions of A
    size(A,n)the size of A along dimension n
    indices(A)a tuple containing the valid indices of A
    indices(A,n)a range expressing the valid indices along dimension n
    eachindex(A)an efficient iterator for visiting each position in A
    stride(A,k)the stride (linear index distance between adjacent elements) along dimension k
    strides(A)a tuple of the strides in each dimension

    Construction and Initialization

    Many functions for constructing and initializing arrays are provided. In the following list of such functions, calls with a dims... argument can either take a single tuple of dimension sizes or a series of dimension sizes passed as a variable number of arguments. Most of these functions also accept a first input T, which is the element type of the array. If the type T is omitted it will default to Float64.

    FunctionDescription
    Array{T}(dims...)an uninitialized dense Array
    zeros(T, dims...)an Array of all zeros
    zeros(A)an array of all zeros with the same type, element type and shape as A
    ones(T, dims...)an Array of all ones
    ones(A)an array of all ones with the same type, element type and shape as A
    trues(dims...)a BitArray with all values true
    trues(A)a BitArray with all values true and the same shape as A
    falses(dims...)a BitArray with all values false
    falses(A)a BitArray with all values false and the same shape as A
    reshape(A, dims...)an array containing the same data as A, but with different dimensions
    copy(A)copy A
    deepcopy(A)copy A, recursively copying its elements
    similar(A, T, dims...)an uninitialized array of the same type as A (dense, sparse, etc.), but with the specified element type and dimensions. The second and third arguments are both optional, defaulting to the element type and dimensions of A if omitted.
    reinterpret(T, A)an array with the same binary data as A, but with element type T
    rand(T, dims...)an Array with random, iid [1] and uniformly distributed values in the half-open interval $[0, 1)$
    randn(T, dims...)an Array with random, iid and standard normally distributed values
    eye(T, n)n-by-n identity matrix
    eye(T, m, n)m-by-n identity matrix
    linspace(start, stop, n)range of n linearly spaced elements from start to stop
    fill!(A, x)fill the array A with the value x
    fill(x, dims...)an Array filled with the value x
    [1]

    iid, independently and identically distributed.

    The syntax [A, B, C, ...] constructs a 1-d array (vector) of its arguments. If all arguments have a common promotion type then they get converted to that type using convert().

    Concatenation

    Arrays can be constructed and also concatenated using the following functions:

    FunctionDescription
    cat(k, A...)concatenate input n-d arrays along the dimension k
    vcat(A...)shorthand for cat(1, A...)
    hcat(A...)shorthand for cat(2, A...)

    Scalar values passed to these functions are treated as 1-element arrays.

    The concatenation functions are used so often that they have special syntax:

    ExpressionCalls
    [A; B; C; ...]vcat()
    [A B C ...]hcat()
    [A B; C D; ...]hvcat()

    hvcat() concatenates in both dimension 1 (with semicolons) and dimension 2 (with spaces).

    Typed array initializers

    An array with a specific element type can be constructed using the syntax T[A, B, C, ...]. This will construct a 1-d array with element type T, initialized to contain elements A, B, C, etc. For example Any[x, y, z] constructs a heterogeneous array that can contain any values.

    Concatenation syntax can similarly be prefixed with a type to specify the element type of the result.

    julia> [[1 2] [3 4]]
    -1×4 Array{Int64,2}:
    - 1  2  3  4
    -
    -julia> Int8[[1 2] [3 4]]
    -1×4 Array{Int8,2}:
    - 1  2  3  4

    Comprehensions

    Comprehensions provide a general and powerful way to construct arrays. Comprehension syntax is similar to set construction notation in mathematics:

    A = [ F(x,y,...) for x=rx, y=ry, ... ]

    The meaning of this form is that F(x,y,...) is evaluated with the variables x, y, etc. taking on each value in their given list of values. Values can be specified as any iterable object, but will commonly be ranges like 1:n or 2:(n-1), or explicit arrays of values like [1.2, 3.4, 5.7]. The result is an N-d dense array with dimensions that are the concatenation of the dimensions of the variable ranges rx, ry, etc. and each F(x,y,...) evaluation returns a scalar.

    The following example computes a weighted average of the current element and its left and right neighbor along a 1-d grid. :

    julia> x = rand(8)
    -8-element Array{Float64,1}:
    - 0.843025
    - 0.869052
    - 0.365105
    - 0.699456
    - 0.977653
    - 0.994953
    - 0.41084
    - 0.809411
    -
    -julia> [ 0.25*x[i-1] + 0.5*x[i] + 0.25*x[i+1] for i=2:length(x)-1 ]
    -6-element Array{Float64,1}:
    - 0.736559
    - 0.57468
    - 0.685417
    - 0.912429
    - 0.8446
    - 0.656511

    The resulting array type depends on the types of the computed elements. In order to control the type explicitly, a type can be prepended to the comprehension. For example, we could have requested the result in single precision by writing:

    Float32[ 0.25*x[i-1] + 0.5*x[i] + 0.25*x[i+1] for i=2:length(x)-1 ]

    Generator Expressions

    Comprehensions can also be written without the enclosing square brackets, producing an object known as a generator. This object can be iterated to produce values on demand, instead of allocating an array and storing them in advance (see Iteration). For example, the following expression sums a series without allocating memory:

    julia> sum(1/n^2 for n=1:1000)
    -1.6439345666815615

    When writing a generator expression with multiple dimensions inside an argument list, parentheses are needed to separate the generator from subsequent arguments:

    julia> map(tuple, 1/(i+j) for i=1:2, j=1:2, [1:4;])
    -ERROR: syntax: invalid iteration specification

    All comma-separated expressions after for are interpreted as ranges. Adding parentheses lets us add a third argument to map:

    julia> map(tuple, (1/(i+j) for i=1:2, j=1:2), [1 3; 2 4])
    -2×2 Array{Tuple{Float64,Int64},2}:
    - (0.5, 1)       (0.333333, 3)
    - (0.333333, 2)  (0.25, 4)

    Ranges in generators and comprehensions can depend on previous ranges by writing multiple for keywords:

    julia> [(i,j) for i=1:3 for j=1:i]
    -6-element Array{Tuple{Int64,Int64},1}:
    - (1, 1)
    - (2, 1)
    - (2, 2)
    - (3, 1)
    - (3, 2)
    - (3, 3)

    In such cases, the result is always 1-d.

    Generated values can be filtered using the if keyword:

    julia> [(i,j) for i=1:3 for j=1:i if i+j == 4]
    -2-element Array{Tuple{Int64,Int64},1}:
    - (2, 2)
    - (3, 1)

    Indexing

    The general syntax for indexing into an n-dimensional array A is:

    X = A[I_1, I_2, ..., I_n]

    where each I_k may be a scalar integer, an array of integers, or any other supported index. This includes Colon (:) to select all indices within the entire dimension, ranges of the form a:c or a:b:c to select contiguous or strided subsections, and arrays of booleans to select elements at their true indices.

    If all the indices are scalars, then the result X is a single element from the array A. Otherwise, X is an array with the same number of dimensions as the sum of the dimensionalities of all the indices.

    If all indices are vectors, for example, then the shape of X would be (length(I_1), length(I_2), ..., length(I_n)), with location (i_1, i_2, ..., i_n) of X containing the value A[I_1[i_1], I_2[i_2], ..., I_n[i_n]]. If I_1 is changed to a two-dimensional matrix, then X becomes an n+1-dimensional array of shape (size(I_1, 1), size(I_1, 2), length(I_2), ..., length(I_n)). The matrix adds a dimension. The location (i_1, i_2, i_3, ..., i_{n+1}) contains the value at A[I_1[i_1, i_2], I_2[i_3], ..., I_n[i_{n+1}]]. All dimensions indexed with scalars are dropped. For example, the result of A[2, I, 3] is an array with size size(I). Its ith element is populated by A[2, I[i], 3].

    As a special part of this syntax, the end keyword may be used to represent the last index of each dimension within the indexing brackets, as determined by the size of the innermost array being indexed. Indexing syntax without the end keyword is equivalent to a call to getindex:

    X = getindex(A, I_1, I_2, ..., I_n)

    Example:

    julia> x = reshape(1:16, 4, 4)
    -4×4 Base.ReshapedArray{Int64,2,UnitRange{Int64},Tuple{}}:
    - 1  5   9  13
    - 2  6  10  14
    - 3  7  11  15
    - 4  8  12  16
    -
    -julia> x[2:3, 2:end-1]
    -2×2 Array{Int64,2}:
    - 6  10
    - 7  11
    -
    -julia> x[1, [2 3; 4 1]]
    -2×2 Array{Int64,2}:
    -  5  9
    - 13  1

    Empty ranges of the form n:n-1 are sometimes used to indicate the inter-index location between n-1 and n. For example, the searchsorted() function uses this convention to indicate the insertion point of a value not found in a sorted array:

    julia> a = [1,2,5,6,7];
    -
    -julia> searchsorted(a, 3)
    -3:2

    Assignment

    The general syntax for assigning values in an n-dimensional array A is:

    A[I_1, I_2, ..., I_n] = X

    where each I_k may be a scalar integer, an array of integers, or any other supported index. This includes Colon (:) to select all indices within the entire dimension, ranges of the form a:c or a:b:c to select contiguous or strided subsections, and arrays of booleans to select elements at their true indices.

    If X is an array, it must have the same number of elements as the product of the lengths of the indices: prod(length(I_1), length(I_2), ..., length(I_n)). The value in location I_1[i_1], I_2[i_2], ..., I_n[i_n] of A is overwritten with the value X[i_1, i_2, ..., i_n]. If X is not an array, its value is written to all referenced locations of A.

    Just as in Indexing, the end keyword may be used to represent the last index of each dimension within the indexing brackets, as determined by the size of the array being assigned into. Indexed assignment syntax without the end keyword is equivalent to a call to setindex!():

    setindex!(A, X, I_1, I_2, ..., I_n)

    Example:

    julia> x = collect(reshape(1:9, 3, 3))
    -3×3 Array{Int64,2}:
    - 1  4  7
    - 2  5  8
    - 3  6  9
    -
    -julia> x[1:2, 2:3] = -1
    --1
    -
    -julia> x
    -3×3 Array{Int64,2}:
    - 1  -1  -1
    - 2  -1  -1
    - 3   6   9

    Supported index types

    In the expression A[I_1, I_2, ..., I_n], each I_k may be a scalar index, an array of scalar indices, or an object that represents an array of scalar indices and can be converted to such by to_indices:

    1. A scalar index. By default this includes:

      • Non-boolean integers

      • CartesianIndex{N}s, which behave like an N-tuple of integers spanning multiple dimensions (see below for more details)

    2. An array of scalar indices. This includes:

      • Vectors and multidimensional arrays of integers

      • Empty arrays like [], which select no elements

      • Ranges of the form a:c or a:b:c, which select contiguous or strided subsections from a to c (inclusive)

      • Any custom array of scalar indices that is a subtype of AbstractArray

      • Arrays of CartesianIndex{N} (see below for more details)

    3. An object that represents an array of scalar indices and can be converted to such by to_indices. By default this includes:

      • Colon() (:), which represents all indices within an entire dimension or across the entire array

      • Arrays of booleans, which select elements at their true indices (see below for more details)

    Cartesian indices

    The special CartesianIndex{N} object represents a scalar index that behaves like an N-tuple of integers spanning multiple dimensions. For example:

    julia> A = reshape(1:32, 4, 4, 2);
    -
    -julia> A[3, 2, 1]
    -7
    -
    -julia> A[CartesianIndex(3, 2, 1)] == A[3, 2, 1] == 7
    -true

    Considered alone, this may seem relatively trivial; CartesianIndex simply gathers multiple integers together into one object that represents a single multidimensional index. When combined with other indexing forms and iterators that yield CartesianIndexes, however, this can lead directly to very elegant and efficient code. See Iteration below, and for some more advanced examples, see this blog post on multidimensional algorithms and iteration.

    Arrays of CartesianIndex{N} are also supported. They represent a collection of scalar indices that each span N dimensions, enabling a form of indexing that is sometimes referred to as pointwise indexing. For example, it enables accessing the diagonal elements from the first "page" of A from above:

    julia> page = A[:,:,1]
    -4×4 Array{Int64,2}:
    - 1  5   9  13
    - 2  6  10  14
    - 3  7  11  15
    - 4  8  12  16
    -
    -julia> page[[CartesianIndex(1,1),
    -             CartesianIndex(2,2),
    -             CartesianIndex(3,3),
    -             CartesianIndex(4,4)]]
    -4-element Array{Int64,1}:
    -  1
    -  6
    - 11
    - 16

    This can be expressed much more simply with dot broadcasting and by combining it with a normal integer index (instead of extracting the first page from A as a separate step). It can even be combined with a : to extract both diagonals from the two pages at the same time:

    julia> A[CartesianIndex.(indices(A, 1), indices(A, 2)), 1]
    -4-element Array{Int64,1}:
    -  1
    -  6
    - 11
    - 16
    -
    -julia> A[CartesianIndex.(indices(A, 1), indices(A, 2)), :]
    -4×2 Array{Int64,2}:
    -  1  17
    -  6  22
    - 11  27
    - 16  32
    Warning

    CartesianIndex and arrays of CartesianIndex are not compatible with the end keyword to represent the last index of a dimension. Do not use end in indexing expressions that may contain either CartesianIndex or arrays thereof.

    Logical indexing

    Often referred to as logical indexing or indexing with a logical mask, indexing by a boolean array selects elements at the indices where its values are true. Indexing by a boolean vector B is effectively the same as indexing by the vector of integers that is returned by find(B). Similarly, indexing by a N-dimensional boolean array is effectively the same as indexing by the vector of CartesianIndex{N}s where its values are true. A logical index must be a vector of the same length as the dimension it indexes into, or it must be the only index provided and match the size and dimensionality of the array it indexes into. It is generally more efficient to use boolean arrays as indices directly instead of first calling find().

    julia> x = reshape(1:16, 4, 4)
    -4×4 Base.ReshapedArray{Int64,2,UnitRange{Int64},Tuple{}}:
    - 1  5   9  13
    - 2  6  10  14
    - 3  7  11  15
    - 4  8  12  16
    -
    -julia> x[[false, true, true, false], :]
    -2×4 Array{Int64,2}:
    - 2  6  10  14
    - 3  7  11  15
    -
    -julia> mask = map(ispow2, x)
    -4×4 Array{Bool,2}:
    -  true  false  false  false
    -  true  false  false  false
    - false  false  false  false
    -  true   true  false   true
    -
    -julia> x[mask]
    -5-element Array{Int64,1}:
    -  1
    -  2
    -  4
    -  8
    - 16

    Iteration

    The recommended ways to iterate over a whole array are

    for a in A
    -    # Do something with the element a
    -end
    -
    -for i in eachindex(A)
    -    # Do something with i and/or A[i]
    -end

    The first construct is used when you need the value, but not index, of each element. In the second construct, i will be an Int if A is an array type with fast linear indexing; otherwise, it will be a CartesianIndex:

    julia> A = rand(4,3);
    -
    -julia> B = view(A, 1:3, 2:3);
    -
    -julia> for i in eachindex(B)
    -           @show i
    -       end
    -i = CartesianIndex{2}((1, 1))
    -i = CartesianIndex{2}((2, 1))
    -i = CartesianIndex{2}((3, 1))
    -i = CartesianIndex{2}((1, 2))
    -i = CartesianIndex{2}((2, 2))
    -i = CartesianIndex{2}((3, 2))

    In contrast with for i = 1:length(A), iterating with eachindex provides an efficient way to iterate over any array type.

    Array traits

    If you write a custom AbstractArray type, you can specify that it has fast linear indexing using

    Base.IndexStyle(::Type{<:MyArray}) = IndexLinear()

    This setting will cause eachindex iteration over a MyArray to use integers. If you don't specify this trait, the default value IndexCartesian() is used.

    Array and Vectorized Operators and Functions

    The following operators are supported for arrays:

    1. Unary arithmetic – -, +

    2. Binary arithmetic – -, +, *, /, \, ^

    3. Comparison – ==, !=, (isapprox),

    Most of the binary arithmetic operators listed above also operate elementwise when one argument is scalar: -, +, and * when either argument is scalar, and / and \ when the denominator is scalar. For example, [1, 2] + 3 == [4, 5] and [6, 4] / 2 == [3, 2].

    Additionally, to enable convenient vectorization of mathematical and other operations, Julia provides the dot syntax f.(args...), e.g. sin.(x) or min.(x,y), for elementwise operations over arrays or mixtures of arrays and scalars (a Broadcasting operation); these have the additional advantage of "fusing" into a single loop when combined with other dot calls, e.g. sin.(cos.(x)).

    Also, every binary operator supports a dot version that can be applied to arrays (and combinations of arrays and scalars) in such fused broadcasting operations, e.g. z .== sin.(x .* y).

    Note that comparisons such as == operate on whole arrays, giving a single boolean answer. Use dot operators like .== for elementwise comparisons. (For comparison operations like <, only the elementwise .< version is applicable to arrays.)

    Also notice the difference between max.(a,b), which broadcasts max() elementwise over a and b, and maximum(a), which finds the largest value within a. The same relationship holds for min.(a,b) and minimum(a).

    Broadcasting

    It is sometimes useful to perform element-by-element binary operations on arrays of different sizes, such as adding a vector to each column of a matrix. An inefficient way to do this would be to replicate the vector to the size of the matrix:

    julia> a = rand(2,1); A = rand(2,3);
    -
    -julia> repmat(a,1,3)+A
    -2×3 Array{Float64,2}:
    - 1.20813  1.82068  1.25387
    - 1.56851  1.86401  1.67846

    This is wasteful when dimensions get large, so Julia offers broadcast(), which expands singleton dimensions in array arguments to match the corresponding dimension in the other array without using extra memory, and applies the given function elementwise:

    julia> broadcast(+, a, A)
    -2×3 Array{Float64,2}:
    - 1.20813  1.82068  1.25387
    - 1.56851  1.86401  1.67846
    -
    -julia> b = rand(1,2)
    -1×2 Array{Float64,2}:
    - 0.867535  0.00457906
    -
    -julia> broadcast(+, a, b)
    -2×2 Array{Float64,2}:
    - 1.71056  0.847604
    - 1.73659  0.873631

    Dotted operators such as .+ and .* are equivalent to broadcast calls (except that they fuse, as described below). There is also a broadcast!() function to specify an explicit destination (which can also be accessed in a fusing fashion by .= assignment), and functions broadcast_getindex() and broadcast_setindex!() that broadcast the indices before indexing. Moreover, f.(args...) is equivalent to broadcast(f, args...), providing a convenient syntax to broadcast any function (dot syntax). Nested "dot calls" f.(...) (including calls to .+ etcetera) automatically fuse into a single broadcast call.

    Additionally, broadcast() is not limited to arrays (see the function documentation), it also handles tuples and treats any argument that is not an array, tuple or Ref (except for Ptr) as a "scalar".

    julia> convert.(Float32, [1, 2])
    -2-element Array{Float32,1}:
    - 1.0
    - 2.0
    -
    -julia> ceil.((UInt8,), [1.2 3.4; 5.6 6.7])
    -2×2 Array{UInt8,2}:
    - 0x02  0x04
    - 0x06  0x07
    -
    -julia> string.(1:3, ". ", ["First", "Second", "Third"])
    -3-element Array{String,1}:
    - "1. First"
    - "2. Second"
    - "3. Third"

    Implementation

    The base array type in Julia is the abstract type AbstractArray{T,N}. It is parametrized by the number of dimensions N and the element type T. AbstractVector and AbstractMatrix are aliases for the 1-d and 2-d cases. Operations on AbstractArray objects are defined using higher level operators and functions, in a way that is independent of the underlying storage. These operations generally work correctly as a fallback for any specific array implementation.

    The AbstractArray type includes anything vaguely array-like, and implementations of it might be quite different from conventional arrays. For example, elements might be computed on request rather than stored. However, any concrete AbstractArray{T,N} type should generally implement at least size(A) (returning an Int tuple), getindex(A,i) and getindex(A,i1,...,iN); mutable arrays should also implement setindex!(). It is recommended that these operations have nearly constant time complexity, or technically Õ(1) complexity, as otherwise some array functions may be unexpectedly slow. Concrete types should also typically provide a similar(A,T=eltype(A),dims=size(A)) method, which is used to allocate a similar array for copy() and other out-of-place operations. No matter how an AbstractArray{T,N} is represented internally, T is the type of object returned by integer indexing (A[1, ..., 1], when A is not empty) and N should be the length of the tuple returned by size().

    DenseArray is an abstract subtype of AbstractArray intended to include all arrays that are laid out at regular offsets in memory, and which can therefore be passed to external C and Fortran functions expecting this memory layout. Subtypes should provide a method stride(A,k) that returns the "stride" of dimension k: increasing the index of dimension k by 1 should increase the index i of getindex(A,i) by stride(A,k). If a pointer conversion method Base.unsafe_convert(Ptr{T}, A) is provided, the memory layout should correspond in the same way to these strides.

    The Array type is a specific instance of DenseArray where elements are stored in column-major order (see additional notes in Performance Tips). Vector and Matrix are aliases for the 1-d and 2-d cases. Specific operations such as scalar indexing, assignment, and a few other basic storage-specific operations are all that have to be implemented for Array, so that the rest of the array library can be implemented in a generic manner.

    SubArray is a specialization of AbstractArray that performs indexing by reference rather than by copying. A SubArray is created with the view() function, which is called the same way as getindex() (with an array and a series of index arguments). The result of view() looks the same as the result of getindex(), except the data is left in place. view() stores the input index vectors in a SubArray object, which can later be used to index the original array indirectly. By putting the @views macro in front of an expression or block of code, any array[...] slice in that expression will be converted to create a SubArray view instead.

    StridedVector and StridedMatrix are convenient aliases defined to make it possible for Julia to call a wider range of BLAS and LAPACK functions by passing them either Array or SubArray objects, and thus saving inefficiencies from memory allocation and copying.

    The following example computes the QR decomposition of a small section of a larger array, without creating any temporaries, and by calling the appropriate LAPACK function with the right leading dimension size and stride parameters.

    julia> a = rand(10,10)
    -10×10 Array{Float64,2}:
    - 0.561255   0.226678   0.203391  0.308912   …  0.750307  0.235023   0.217964
    - 0.718915   0.537192   0.556946  0.996234      0.666232  0.509423   0.660788
    - 0.493501   0.0565622  0.118392  0.493498      0.262048  0.940693   0.252965
    - 0.0470779  0.736979   0.264822  0.228787      0.161441  0.897023   0.567641
    - 0.343935   0.32327    0.795673  0.452242      0.468819  0.628507   0.511528
    - 0.935597   0.991511   0.571297  0.74485    …  0.84589   0.178834   0.284413
    - 0.160706   0.672252   0.133158  0.65554       0.371826  0.770628   0.0531208
    - 0.306617   0.836126   0.301198  0.0224702     0.39344   0.0370205  0.536062
    - 0.890947   0.168877   0.32002   0.486136      0.096078  0.172048   0.77672
    - 0.507762   0.573567   0.220124  0.165816      0.211049  0.433277   0.539476
    -
    -julia> b = view(a, 2:2:8,2:2:4)
    -4×2 SubArray{Float64,2,Array{Float64,2},Tuple{StepRange{Int64,Int64},StepRange{Int64,Int64}},false}:
    - 0.537192  0.996234
    - 0.736979  0.228787
    - 0.991511  0.74485
    - 0.836126  0.0224702
    -
    -julia> (q,r) = qr(b);
    -
    -julia> q
    -4×2 Array{Float64,2}:
    - -0.338809   0.78934
    - -0.464815  -0.230274
    - -0.625349   0.194538
    - -0.527347  -0.534856
    -
    -julia> r
    -2×2 Array{Float64,2}:
    - -1.58553  -0.921517
    -  0.0       0.866567

    Sparse Vectors and Matrices

    Julia has built-in support for sparse vectors and sparse matrices. Sparse arrays are arrays that contain enough zeros that storing them in a special data structure leads to savings in space and execution time, compared to dense arrays.

    Compressed Sparse Column (CSC) Sparse Matrix Storage

    In Julia, sparse matrices are stored in the Compressed Sparse Column (CSC) format. Julia sparse matrices have the type SparseMatrixCSC{Tv,Ti}, where Tv is the type of the stored values, and Ti is the integer type for storing column pointers and row indices. The internal representation of SparseMatrixCSC is as follows:

    struct SparseMatrixCSC{Tv,Ti<:Integer} <: AbstractSparseMatrix{Tv,Ti}
    -    m::Int                  # Number of rows
    -    n::Int                  # Number of columns
    -    colptr::Vector{Ti}      # Column i is in colptr[i]:(colptr[i+1]-1)
    -    rowval::Vector{Ti}      # Row indices of stored values
    -    nzval::Vector{Tv}       # Stored values, typically nonzeros
    -end

    The compressed sparse column storage makes it easy and quick to access the elements in the column of a sparse matrix, whereas accessing the sparse matrix by rows is considerably slower. Operations such as insertion of previously unstored entries one at a time in the CSC structure tend to be slow. This is because all elements of the sparse matrix that are beyond the point of insertion have to be moved one place over.

    All operations on sparse matrices are carefully implemented to exploit the CSC data structure for performance, and to avoid expensive operations.

    If you have data in CSC format from a different application or library, and wish to import it in Julia, make sure that you use 1-based indexing. The row indices in every column need to be sorted. If your SparseMatrixCSC object contains unsorted row indices, one quick way to sort them is by doing a double transpose.

    In some applications, it is convenient to store explicit zero values in a SparseMatrixCSC. These are accepted by functions in Base (but there is no guarantee that they will be preserved in mutating operations). Such explicitly stored zeros are treated as structural nonzeros by many routines. The nnz() function returns the number of elements explicitly stored in the sparse data structure, including structural nonzeros. In order to count the exact number of numerical nonzeros, use countnz(), which inspects every stored element of a sparse matrix. dropzeros(), and the in-place dropzeros!(), can be used to remove stored zeros from the sparse matrix.

    julia> A = sparse([1, 2, 3], [1, 2, 3], [0, 2, 0])
    -3×3 SparseMatrixCSC{Int64,Int64} with 3 stored entries:
    -  [1, 1]  =  0
    -  [2, 2]  =  2
    -  [3, 3]  =  0
    -
    -julia> dropzeros(A)
    -3×3 SparseMatrixCSC{Int64,Int64} with 1 stored entry:
    -  [2, 2]  =  2

    Sparse Vector Storage

    Sparse vectors are stored in a close analog to compressed sparse column format for sparse matrices. In Julia, sparse vectors have the type SparseVector{Tv,Ti} where Tv is the type of the stored values and Ti the integer type for the indices. The internal representation is as follows:

    struct SparseVector{Tv,Ti<:Integer} <: AbstractSparseVector{Tv,Ti}
    -    n::Int              # Length of the sparse vector
    -    nzind::Vector{Ti}   # Indices of stored values
    -    nzval::Vector{Tv}   # Stored values, typically nonzeros
    -end

    As for SparseMatrixCSC, the SparseVector type can also contain explicitly stored zeros. (See Sparse Matrix Storage.).

    Sparse Vector and Matrix Constructors

    The simplest way to create sparse arrays is to use functions equivalent to the zeros() and eye() functions that Julia provides for working with dense arrays. To produce sparse arrays instead, you can use the same names with an sp prefix:

    julia> spzeros(3)
    -3-element SparseVector{Float64,Int64} with 0 stored entries
    -
    -julia> speye(3,5)
    -3×5 SparseMatrixCSC{Float64,Int64} with 3 stored entries:
    -  [1, 1]  =  1.0
    -  [2, 2]  =  1.0
    -  [3, 3]  =  1.0

    The sparse() function is often a handy way to construct sparse arrays. For example, to construct a sparse matrix we can input a vector I of row indices, a vector J of column indices, and a vector V of stored values (this is also known as the COO (coordinate) format). sparse(I,J,V) then constructs a sparse matrix such that S[I[k], J[k]] = V[k]. The equivalent sparse vector constructor is sparsevec, which takes the (row) index vector I and the vector V with the stored values and constructs a sparse vector R such that R[I[k]] = V[k].

    julia> I = [1, 4, 3, 5]; J = [4, 7, 18, 9]; V = [1, 2, -5, 3];
    -
    -julia> S = sparse(I,J,V)
    -5×18 SparseMatrixCSC{Int64,Int64} with 4 stored entries:
    -  [1 ,  4]  =  1
    -  [4 ,  7]  =  2
    -  [5 ,  9]  =  3
    -  [3 , 18]  =  -5
    -
    -julia> R = sparsevec(I,V)
    -5-element SparseVector{Int64,Int64} with 4 stored entries:
    -  [1]  =  1
    -  [3]  =  -5
    -  [4]  =  2
    -  [5]  =  3

    The inverse of the sparse() and sparsevec functions is findnz(), which retrieves the inputs used to create the sparse array. There is also a findn function which only returns the index vectors.

    julia> findnz(S)
    -([1, 4, 5, 3], [4, 7, 9, 18], [1, 2, 3, -5])
    -
    -julia> findn(S)
    -([1, 4, 5, 3], [4, 7, 9, 18])
    -
    -julia> findnz(R)
    -([1, 3, 4, 5], [1, -5, 2, 3])
    -
    -julia> findn(R)
    -4-element Array{Int64,1}:
    - 1
    - 3
    - 4
    - 5

    Another way to create a sparse array is to convert a dense array into a sparse array using the sparse() function:

    julia> sparse(eye(5))
    -5×5 SparseMatrixCSC{Float64,Int64} with 5 stored entries:
    -  [1, 1]  =  1.0
    -  [2, 2]  =  1.0
    -  [3, 3]  =  1.0
    -  [4, 4]  =  1.0
    -  [5, 5]  =  1.0
    -
    -julia> sparse([1.0, 0.0, 1.0])
    -3-element SparseVector{Float64,Int64} with 2 stored entries:
    -  [1]  =  1.0
    -  [3]  =  1.0

    You can go in the other direction using the Array constructor. The issparse() function can be used to query if a matrix is sparse.

    julia> issparse(speye(5))
    -true

    Sparse matrix operations

    Arithmetic operations on sparse matrices also work as they do on dense matrices. Indexing of, assignment into, and concatenation of sparse matrices work in the same way as dense matrices. Indexing operations, especially assignment, are expensive, when carried out one element at a time. In many cases it may be better to convert the sparse matrix into (I,J,V) format using findnz(), manipulate the values or the structure in the dense vectors (I,J,V), and then reconstruct the sparse matrix.

    Correspondence of dense and sparse methods

    The following table gives a correspondence between built-in methods on sparse matrices and their corresponding methods on dense matrix types. In general, methods that generate sparse matrices differ from their dense counterparts in that the resulting matrix follows the same sparsity pattern as a given sparse matrix S, or that the resulting sparse matrix has density d, i.e. each matrix element has a probability d of being non-zero.

    Details can be found in the Sparse Vectors and Matrices section of the standard library reference.

    SparseDenseDescription
    spzeros(m,n)zeros(m,n)Creates a m-by-n matrix of zeros. (spzeros(m,n) is empty.)
    spones(S)ones(m,n)Creates a matrix filled with ones. Unlike the dense version, spones() has the same sparsity pattern as S.
    speye(n)eye(n)Creates a n-by-n identity matrix.
    full(S)sparse(A)Interconverts between dense and sparse formats.
    sprand(m,n,d)rand(m,n)Creates a m-by-n random matrix (of density d) with iid non-zero elements distributed uniformly on the half-open interval $[0, 1)$.
    sprandn(m,n,d)randn(m,n)Creates a m-by-n random matrix (of density d) with iid non-zero elements distributed according to the standard normal (Gaussian) distribution.
    sprandn(m,n,d,X)randn(m,n,X)Creates a m-by-n random matrix (of density d) with iid non-zero elements distributed according to the X distribution. (Requires the Distributions package.)
    diff --git a/julia-0.6.3/share/doc/julia/html/en/manual/calling-c-and-fortran-code.html b/julia-0.6.3/share/doc/julia/html/en/manual/calling-c-and-fortran-code.html deleted file mode 100644 index 61001d3..0000000 --- a/julia-0.6.3/share/doc/julia/html/en/manual/calling-c-and-fortran-code.html +++ /dev/null @@ -1,166 +0,0 @@ - -Calling C and Fortran Code · The Julia Language

    Calling C and Fortran Code

    Calling C and Fortran Code

    Though most code can be written in Julia, there are many high-quality, mature libraries for numerical computing already written in C and Fortran. To allow easy use of this existing code, Julia makes it simple and efficient to call C and Fortran functions. Julia has a "no boilerplate" philosophy: functions can be called directly from Julia without any "glue" code, code generation, or compilation – even from the interactive prompt. This is accomplished just by making an appropriate call with ccall syntax, which looks like an ordinary function call.

    The code to be called must be available as a shared library. Most C and Fortran libraries ship compiled as shared libraries already, but if you are compiling the code yourself using GCC (or Clang), you will need to use the -shared and -fPIC options. The machine instructions generated by Julia's JIT are the same as a native C call would be, so the resulting overhead is the same as calling a library function from C code. (Non-library function calls in both C and Julia can be inlined and thus may have even less overhead than calls to shared library functions. When both libraries and executables are generated by LLVM, it is possible to perform whole-program optimizations that can even optimize across this boundary, but Julia does not yet support that. In the future, however, it may do so, yielding even greater performance gains.)

    Shared libraries and functions are referenced by a tuple of the form (:function, "library") or ("function", "library") where function is the C-exported function name. library refers to the shared library name: shared libraries available in the (platform-specific) load path will be resolved by name, and if necessary a direct path may be specified.

    A function name may be used alone in place of the tuple (just :function or "function"). In this case the name is resolved within the current process. This form can be used to call C library functions, functions in the Julia runtime, or functions in an application linked to Julia.

    By default, Fortran compilers generate mangled names (for example, converting function names to lowercase or uppercase, often appending an underscore), and so to call a Fortran function via ccall you must pass the mangled identifier corresponding to the rule followed by your Fortran compiler. Also, when calling a Fortran function, all inputs must be passed by reference.

    Finally, you can use ccall to actually generate a call to the library function. Arguments to ccall are as follows:

    1. A (:function, "library") pair, which must be written as a literal constant,

      OR

      a function pointer (for example, from dlsym).

    2. Return type (see below for mapping the declared C type to Julia)

      • This argument will be evaluated at compile-time, when the containing method is defined.

    3. A tuple of input types. The input types must be written as a literal tuple, not a tuple-valued variable or expression.

      • This argument will be evaluated at compile-time, when the containing method is defined.

    4. The following arguments, if any, are the actual argument values passed to the function.

    As a complete but simple example, the following calls the clock function from the standard C library:

    julia> t = ccall((:clock, "libc"), Int32, ())
    -2292761
    -
    -julia> t
    -2292761
    -
    -julia> typeof(ans)
    -Int32

    clock takes no arguments and returns an Int32. One common gotcha is that a 1-tuple must be written with a trailing comma. For example, to call the getenv function to get a pointer to the value of an environment variable, one makes a call like this:

    julia> path = ccall((:getenv, "libc"), Cstring, (Cstring,), "SHELL")
    -Cstring(@0x00007fff5fbffc45)
    -
    -julia> unsafe_string(path)
    -"/bin/bash"

    Note that the argument type tuple must be written as (Cstring,), rather than (Cstring). This is because (Cstring) is just the expression Cstring surrounded by parentheses, rather than a 1-tuple containing Cstring:

    julia> (Cstring)
    -Cstring
    -
    -julia> (Cstring,)
    -(Cstring,)

    In practice, especially when providing reusable functionality, one generally wraps ccall uses in Julia functions that set up arguments and then check for errors in whatever manner the C or Fortran function indicates them, propagating to the Julia caller as exceptions. This is especially important since C and Fortran APIs are notoriously inconsistent about how they indicate error conditions. For example, the getenv C library function is wrapped in the following Julia function, which is a simplified version of the actual definition from env.jl:

    function getenv(var::AbstractString)
    -    val = ccall((:getenv, "libc"),
    -                Cstring, (Cstring,), var)
    -    if val == C_NULL
    -        error("getenv: undefined variable: ", var)
    -    end
    -    unsafe_string(val)
    -end

    The C getenv function indicates an error by returning NULL, but other standard C functions indicate errors in various different ways, including by returning -1, 0, 1 and other special values. This wrapper throws an exception clearly indicating the problem if the caller tries to get a non-existent environment variable:

    julia> getenv("SHELL")
    -"/bin/bash"
    -
    -julia> getenv("FOOBAR")
    -getenv: undefined variable: FOOBAR

    Here is a slightly more complex example that discovers the local machine's hostname:

    function gethostname()
    -    hostname = Vector{UInt8}(128)
    -    ccall((:gethostname, "libc"), Int32,
    -          (Ptr{UInt8}, Csize_t),
    -          hostname, sizeof(hostname))
    -    hostname[end] = 0; # ensure null-termination
    -    return unsafe_string(pointer(hostname))
    -end

    This example first allocates an array of bytes, then calls the C library function gethostname to fill the array in with the hostname, takes a pointer to the hostname buffer, and converts the pointer to a Julia string, assuming that it is a NUL-terminated C string. It is common for C libraries to use this pattern of requiring the caller to allocate memory to be passed to the callee and filled in. Allocation of memory from Julia like this is generally accomplished by creating an uninitialized array and passing a pointer to its data to the C function. This is why we don't use the Cstring type here: as the array is uninitialized, it could contain NUL bytes. Converting to a Cstring as part of the ccall checks for contained NUL bytes and could therefore throw a conversion error.

    Creating C-Compatible Julia Function Pointers

    It is possible to pass Julia functions to native C functions that accept function pointer arguments. For example, to match C prototypes of the form:

    typedef returntype (*functiontype)(argumenttype,...)

    The function cfunction() generates the C-compatible function pointer for a call to a Julia library function. Arguments to cfunction() are as follows:

    1. A Julia Function

    2. Return type

    3. A tuple of input types

    A classic example is the standard C library qsort function, declared as:

    void qsort(void *base, size_t nmemb, size_t size,
    -           int(*compare)(const void *a, const void *b));

    The base argument is a pointer to an array of length nmemb, with elements of size bytes each. compare is a callback function which takes pointers to two elements a and b and returns an integer less/greater than zero if a should appear before/after b (or zero if any order is permitted). Now, suppose that we have a 1d array A of values in Julia that we want to sort using the qsort function (rather than Julia's built-in sort function). Before we worry about calling qsort and passing arguments, we need to write a comparison function that works for some arbitrary type T:

    julia> function mycompare(a::T, b::T) where T
    -           return convert(Cint, a < b ? -1 : a > b ? +1 : 0)::Cint
    -       end
    -mycompare (generic function with 1 method)

    Notice that we have to be careful about the return type: qsort expects a function returning a C int, so we must be sure to return Cint via a call to convert and a typeassert.

    In order to pass this function to C, we obtain its address using the function cfunction:

    julia> const mycompare_c = cfunction(mycompare, Cint, (Ref{Cdouble}, Ref{Cdouble}));

    cfunction() accepts three arguments: the Julia function (mycompare), the return type (Cint), and a tuple of the argument types, in this case to sort an array of Cdouble (Float64) elements.

    The final call to qsort looks like this:

    julia> A = [1.3, -2.7, 4.4, 3.1]
    -4-element Array{Float64,1}:
    -  1.3
    - -2.7
    -  4.4
    -  3.1
    -
    -julia> ccall(:qsort, Void, (Ptr{Cdouble}, Csize_t, Csize_t, Ptr{Void}),
    -             A, length(A), sizeof(eltype(A)), mycompare_c)
    -
    -julia> A
    -4-element Array{Float64,1}:
    - -2.7
    -  1.3
    -  3.1
    -  4.4

    As can be seen, A is changed to the sorted array [-2.7, 1.3, 3.1, 4.4]. Note that Julia knows how to convert an array into a Ptr{Cdouble}, how to compute the size of a type in bytes (identical to C's sizeof operator), and so on. For fun, try inserting a println("mycompare($a,$b)") line into mycompare, which will allow you to see the comparisons that qsort is performing (and to verify that it is really calling the Julia function that you passed to it).

    Mapping C Types to Julia

    It is critical to exactly match the declared C type with its declaration in Julia. Inconsistencies can cause code that works correctly on one system to fail or produce indeterminate results on a different system.

    Note that no C header files are used anywhere in the process of calling C functions: you are responsible for making sure that your Julia types and call signatures accurately reflect those in the C header file. (The Clang package can be used to auto-generate Julia code from a C header file.)

    Auto-conversion:

    Julia automatically inserts calls to the Base.cconvert() function to convert each argument to the specified type. For example, the following call:

    ccall((:foo, "libfoo"), Void, (Int32, Float64), x, y)

    will behave as if the following were written:

    ccall((:foo, "libfoo"), Void, (Int32, Float64),
    -      Base.unsafe_convert(Int32, Base.cconvert(Int32, x)),
    -      Base.unsafe_convert(Float64, Base.cconvert(Float64, y)))

    Base.cconvert() normally just calls convert(), but can be defined to return an arbitrary new object more appropriate for passing to C. For example, this is used to convert an Array of objects (e.g. strings) to an array of pointers.

    Base.unsafe_convert() handles conversion to Ptr types. It is considered unsafe because converting an object to a native pointer can hide the object from the garbage collector, causing it to be freed prematurely.

    Type Correspondences:

    First, a review of some relevant Julia type terminology:

    Syntax / KeywordExampleDescription
    mutable structString"Leaf Type" :: A group of related data that includes a type-tag, is managed by the Julia GC, and is defined by object-identity. The type parameters of a leaf type must be fully defined (no TypeVars are allowed) in order for the instance to be constructed.
    abstract typeAny, AbstractArray{T, N}, Complex{T}"Super Type" :: A super-type (not a leaf-type) that cannot be instantiated, but can be used to describe a group of types.
    T{A}Vector{Int}"Type Parameter" :: A specialization of a type (typically used for dispatch or storage optimization).
    "TypeVar" :: The T in the type parameter declaration is referred to as a TypeVar (short for type variable).
    primitive typeInt, Float64"Primitive Type" :: A type with no fields, but a size. It is stored and defined by-value.
    structPair{Int, Int}"Struct" :: A type with all fields defined to be constant. It is defined by-value, and may be stored with a type-tag.
    Complex128 (isbits)"Is-Bits" :: A primitive type, or a struct type where all fields are other isbits types. It is defined by-value, and is stored without a type-tag.
    struct ...; endnothing"Singleton" :: a Leaf Type or Struct with no fields.
    (...) or tuple(...)(1, 2, 3)"Tuple" :: an immutable data-structure similar to an anonymous struct type, or a constant array. Represented as either an array or a struct.

    Bits Types:

    There are several special types to be aware of, as no other type can be defined to behave the same:

    • Float32

      Exactly corresponds to the float type in C (or REAL*4 in Fortran).

    • Float64

      Exactly corresponds to the double type in C (or REAL*8 in Fortran).

    • Complex64

      Exactly corresponds to the complex float type in C (or COMPLEX*8 in Fortran).

    • Complex128

      Exactly corresponds to the complex double type in C (or COMPLEX*16 in Fortran).

    • Signed

      Exactly corresponds to the signed type annotation in C (or any INTEGER type in Fortran). Any Julia type that is not a subtype of Signed is assumed to be unsigned.

    • Ref{T}

      Behaves like a Ptr{T} that can manage its memory via the Julia GC.

    • Array{T,N}

      When an array is passed to C as a Ptr{T} argument, it is not reinterpret-cast: Julia requires that the element type of the array matches T, and the address of the first element is passed.

      Therefore, if an Array contains data in the wrong format, it will have to be explicitly converted using a call such as trunc(Int32, a).

      To pass an array A as a pointer of a different type without converting the data beforehand (for example, to pass a Float64 array to a function that operates on uninterpreted bytes), you can declare the argument as Ptr{Void}.

      If an array of eltype Ptr{T} is passed as a Ptr{Ptr{T}} argument, Base.cconvert() will attempt to first make a null-terminated copy of the array with each element replaced by its Base.cconvert() version. This allows, for example, passing an argv pointer array of type Vector{String} to an argument of type Ptr{Ptr{Cchar}}.

    On all systems we currently support, basic C/C++ value types may be translated to Julia types as follows. Every C type also has a corresponding Julia type with the same name, prefixed by C. This can help for writing portable code (and remembering that an int in C is not the same as an Int in Julia).

    System Independent:

    C nameFortran nameStandard Julia AliasJulia Base Type
    unsigned charCHARACTERCucharUInt8
    bool (only in C++)CucharUInt8
    shortINTEGER*2, LOGICAL*2CshortInt16
    unsigned short CushortUInt16
    int, BOOL (C, typical)INTEGER*4, LOGICAL*4CintInt32
    unsigned int CuintUInt32
    long longINTEGER*8, LOGICAL*8ClonglongInt64
    unsigned long long CulonglongUInt64
    intmax_t Cintmax_tInt64
    uintmax_t Cuintmax_tUInt64
    floatREAL*4iCfloatFloat32
    doubleREAL*8CdoubleFloat64
    complex floatCOMPLEX*8Complex64Complex{Float32}
    complex doubleCOMPLEX*16Complex128Complex{Float64}
    ptrdiff_t Cptrdiff_tInt
    ssize_t Cssize_tInt
    size_t Csize_tUInt
    void  Void
    void and [[noreturn]] or _Noreturn  Union{}
    void*  Ptr{Void}
    T* (where T represents an appropriately defined type)  Ref{T}
    char* (or char[], e.g. a string)CHARACTER*N Cstring if NUL-terminated, or Ptr{UInt8} if not
    char** (or *char[])  Ptr{Ptr{UInt8}}
    jl_value_t* (any Julia Type)  Any
    jl_value_t** (a reference to a Julia Type)  Ref{Any}
    va_arg  Not supported
    ... (variadic function specification)  T... (where T is one of the above types, variadic functions of different argument types are not supported)

    The Cstring type is essentially a synonym for Ptr{UInt8}, except the conversion to Cstring throws an error if the Julia string contains any embedded NUL characters (which would cause the string to be silently truncated if the C routine treats NUL as the terminator). If you are passing a char* to a C routine that does not assume NUL termination (e.g. because you pass an explicit string length), or if you know for certain that your Julia string does not contain NUL and want to skip the check, you can use Ptr{UInt8} as the argument type. Cstring can also be used as the ccall return type, but in that case it obviously does not introduce any extra checks and is only meant to improve readability of the call.

    System-dependent:

    C nameStandard Julia AliasJulia Base Type
    charCcharInt8 (x86, x86_64), UInt8 (powerpc, arm)
    longClongInt (UNIX), Int32 (Windows)
    unsigned longCulongUInt (UNIX), UInt32 (Windows)
    wchar_tCwchar_tInt32 (UNIX), UInt16 (Windows)
    Note

    When calling a Fortran function, all inputs must be passed by reference, so all type correspondences above should contain an additional Ptr{..} or Ref{..} wrapper around their type specification.

    Warning

    For string arguments (char*) the Julia type should be Cstring (if NUL- terminated data is expected) or either Ptr{Cchar} or Ptr{UInt8} otherwise (these two pointer types have the same effect), as described above, not String. Similarly, for array arguments (T[] or T*), the Julia type should again be Ptr{T}, not Vector{T}.

    Warning

    Julia's Char type is 32 bits, which is not the same as the wide character type (wchar_t or wint_t) on all platforms.

    Warning

    A return type of Union{} means the function will not return i.e. C++11 [[noreturn]] or C11 _Noreturn (e.g. jl_throw or longjmp). Do not use this for functions that return no value (void) but do return, use Void instead.

    Note

    For wchar_t* arguments, the Julia type should be Cwstring (if the C routine expects a NUL-terminated string) or Ptr{Cwchar_t} otherwise. Note also that UTF-8 string data in Julia is internally NUL-terminated, so it can be passed to C functions expecting NUL-terminated data without making a copy (but using the Cwstring type will cause an error to be thrown if the string itself contains NUL characters).

    Note

    C functions that take an argument of the type char** can be called by using a Ptr{Ptr{UInt8}} type within Julia. For example, C functions of the form:

    int main(int argc, char **argv);

    can be called via the following Julia code:

    argv = [ "a.out", "arg1", "arg2" ]
    -ccall(:main, Int32, (Int32, Ptr{Ptr{UInt8}}), length(argv), argv)
    Note

    A C function declared to return Void will return the value nothing in Julia.

    Struct Type correspondences

    Composite types, aka struct in C or TYPE in Fortran90 (or STRUCTURE / RECORD in some variants of F77), can be mirrored in Julia by creating a struct definition with the same field layout.

    When used recursively, isbits types are stored inline. All other types are stored as a pointer to the data. When mirroring a struct used by-value inside another struct in C, it is imperative that you do not attempt to manually copy the fields over, as this will not preserve the correct field alignment. Instead, declare an isbits struct type and use that instead. Unnamed structs are not possible in the translation to Julia.

    Packed structs and union declarations are not supported by Julia.

    You can get a near approximation of a union if you know, a priori, the field that will have the greatest size (potentially including padding). When translating your fields to Julia, declare the Julia field to be only of that type.

    Arrays of parameters can be expressed with NTuple:

    in C:
    -struct B {
    -    int A[3];
    -};
    -b_a_2 = B.A[2];
    -
    -in Julia:
    -struct B
    -    A::NTuple{3, CInt}
    -end
    -b_a_2 = B.A[3]  # note the difference in indexing (1-based in Julia, 0-based in C)

    Arrays of unknown size (C99-compliant variable length structs specified by [] or [0]) are not directly supported. Often the best way to deal with these is to deal with the byte offsets directly. For example, if a C library declared a proper string type and returned a pointer to it:

    struct String {
    -    int strlen;
    -    char data[];
    -};

    In Julia, we can access the parts independently to make a copy of that string:

    str = from_c::Ptr{Void}
    -len = unsafe_load(Ptr{Cint}(str))
    -unsafe_string(str + Core.sizeof(Cint), len)

    Type Parameters

    The type arguments to ccall are evaluated statically, when the method containing the ccall is defined. They therefore must take the form of a literal tuple, not a variable, and cannot reference local variables.

    This may sound like a strange restriction, but remember that since C is not a dynamic language like Julia, its functions can only accept argument types with a statically-known, fixed signature.

    However, while the type layout must be known statically to compute the ccall ABI, the static parameters of the function are considered to be part of this static environment. The static parameters of the function may be used as type parameters in the ccall signature, as long as they don't affect the layout of the type. For example, f(x::T) where {T} = ccall(:valid, Ptr{T}, (Ptr{T},), x) is valid, since Ptr is always a word-size primitive type. But, g(x::T) where {T} = ccall(:notvalid, T, (T,), x) is not valid, since the type layout of T is not known statically.

    SIMD Values

    Note: This feature is currently implemented on 64-bit x86 and AArch64 platforms only.

    If a C/C++ routine has an argument or return value that is a native SIMD type, the corresponding Julia type is a homogeneous tuple of VecElement that naturally maps to the SIMD type. Specifically:

    • The tuple must be the same size as the SIMD type. For example, a tuple representing an __m128 on x86 must have a size of 16 bytes.

    • The element type of the tuple must be an instance of VecElement{T} where T is a primitive type that is 1, 2, 4 or 8 bytes.

    For instance, consider this C routine that uses AVX intrinsics:

    #include <immintrin.h>
    -
    -__m256 dist( __m256 a, __m256 b ) {
    -    return _mm256_sqrt_ps(_mm256_add_ps(_mm256_mul_ps(a, a),
    -                                        _mm256_mul_ps(b, b)));
    -}

    The following Julia code calls dist using ccall:

    const m256 = NTuple{8, VecElement{Float32}}
    -
    -a = m256(ntuple(i -> VecElement(sin(Float32(i))), 8))
    -b = m256(ntuple(i -> VecElement(cos(Float32(i))), 8))
    -
    -function call_dist(a::m256, b::m256)
    -    ccall((:dist, "libdist"), m256, (m256, m256), a, b)
    -end
    -
    -println(call_dist(a,b))

    The host machine must have the requisite SIMD registers. For example, the code above will not work on hosts without AVX support.

    Memory Ownership

    malloc/free

    Memory allocation and deallocation of such objects must be handled by calls to the appropriate cleanup routines in the libraries being used, just like in any C program. Do not try to free an object received from a C library with Libc.free in Julia, as this may result in the free function being called via the wrong libc library and cause Julia to crash. The reverse (passing an object allocated in Julia to be freed by an external library) is equally invalid.

    When to use T, Ptr{T} and Ref{T}

    In Julia code wrapping calls to external C routines, ordinary (non-pointer) data should be declared to be of type T inside the ccall, as they are passed by value. For C code accepting pointers, Ref{T} should generally be used for the types of input arguments, allowing the use of pointers to memory managed by either Julia or C through the implicit call to Base.cconvert(). In contrast, pointers returned by the C function called should be declared to be of output type Ptr{T}, reflecting that the memory pointed to is managed by C only. Pointers contained in C structs should be represented as fields of type Ptr{T} within the corresponding Julia struct types designed to mimic the internal structure of corresponding C structs.

    In Julia code wrapping calls to external Fortran routines, all input arguments should be declared as of type Ref{T}, as Fortran passes all variables by reference. The return type should either be Void for Fortran subroutines, or a T for Fortran functions returning the type T.

    Mapping C Functions to Julia

    ccall/cfunction argument translation guide

    For translating a C argument list to Julia:

    • T, where T is one of the primitive types: char, int, long, short, float, double, complex, enum or any of their typedef equivalents

      • T, where T is an equivalent Julia Bits Type (per the table above)

      • if T is an enum, the argument type should be equivalent to Cint or Cuint

      • argument value will be copied (passed by value)

    • struct T (including typedef to a struct)

      • T, where T is a Julia leaf type

      • argument value will be copied (passed by value)

    • void*

      • depends on how this parameter is used, first translate this to the intended pointer type, then determine the Julia equivalent using the remaining rules in this list

      • this argument may be declared as Ptr{Void}, if it really is just an unknown pointer

    • jl_value_t*

      • Any

      • argument value must be a valid Julia object

      • currently unsupported by cfunction()

    • jl_value_t**

      • Ref{Any}

      • argument value must be a valid Julia object (or C_NULL)

      • currently unsupported by cfunction()

    • T*

      • Ref{T}, where T is the Julia type corresponding to T

      • argument value will be copied if it is an isbits type otherwise, the value must be a valid Julia object

    • (T*)(...) (e.g. a pointer to a function)

      • Ptr{Void} (you may need to use cfunction() explicitly to create this pointer)

    • ... (e.g. a vararg)

      • T..., where T is the Julia type

    • va_arg

      • not supported

    ccall/cfunction return type translation guide

    For translating a C return type to Julia:

    • void

      • Void (this will return the singleton instance nothing::Void)

    • T, where T is one of the primitive types: char, int, long, short, float, double, complex, enum or any of their typedef equivalents

      • T, where T is an equivalent Julia Bits Type (per the table above)

      • if T is an enum, the argument type should be equivalent to Cint or Cuint

      • argument value will be copied (returned by-value)

    • struct T (including typedef to a struct)

      • T, where T is a Julia Leaf Type

      • argument value will be copied (returned by-value)

    • void*

      • depends on how this parameter is used, first translate this to the intended pointer type, then determine the Julia equivalent using the remaining rules in this list

      • this argument may be declared as Ptr{Void}, if it really is just an unknown pointer

    • jl_value_t*

      • Any

      • argument value must be a valid Julia object

    • jl_value_t**

      • Ref{Any}

      • argument value must be a valid Julia object (or C_NULL)

    • T*

      • If the memory is already owned by Julia, or is an isbits type, and is known to be non-null:

        • Ref{T}, where T is the Julia type corresponding to T

        • a return type of Ref{Any} is invalid, it should either be Any (corresponding to jl_value_t*) or Ptr{Any} (corresponding to Ptr{Any})

        • C MUST NOT modify the memory returned via Ref{T} if T is an isbits type

      • If the memory is owned by C:

        • Ptr{T}, where T is the Julia type corresponding to T

    • (T*)(...) (e.g. a pointer to a function)

      • Ptr{Void} (you may need to use cfunction() explicitly to create this pointer)

    Passing Pointers for Modifying Inputs

    Because C doesn't support multiple return values, often C functions will take pointers to data that the function will modify. To accomplish this within a ccall, you need to first encapsulate the value inside an Ref{T} of the appropriate type. When you pass this Ref object as an argument, Julia will automatically pass a C pointer to the encapsulated data:

    width = Ref{Cint}(0)
    -range = Ref{Cfloat}(0)
    -ccall(:foo, Void, (Ref{Cint}, Ref{Cfloat}), width, range)

    Upon return, the contents of width and range can be retrieved (if they were changed by foo) by width[] and range[]; that is, they act like zero-dimensional arrays.

    Special Reference Syntax for ccall (deprecated):

    The & syntax is deprecated, use the Ref{T} argument type instead.

    A prefix & is used on an argument to ccall to indicate that a pointer to a scalar argument should be passed instead of the scalar value itself (required for all Fortran function arguments, as noted above). The following example computes a dot product using a BLAS function.

    function compute_dot(DX::Vector{Float64}, DY::Vector{Float64})
    -    @assert length(DX) == length(DY)
    -    n = length(DX)
    -    incx = incy = 1
    -    product = ccall((:ddot_, "libLAPACK"),
    -                    Float64,
    -                    (Ptr{Int32}, Ptr{Float64}, Ptr{Int32}, Ptr{Float64}, Ptr{Int32}),
    -                    &n, DX, &incx, DY, &incy)
    -    return product
    -end

    The meaning of prefix & is not quite the same as in C. In particular, any changes to the referenced variables will not be visible in Julia unless the type is mutable (declared via type). However, even for immutable structs it will not cause any harm for called functions to attempt such modifications (that is, writing through the passed pointers). Moreover, & may be used with any expression, such as &0 or &f(x).

    When a scalar value is passed with & as an argument of type Ptr{T}, the value will first be converted to type T.

    Some Examples of C Wrappers

    Here is a simple example of a C wrapper that returns a Ptr type:

    mutable struct gsl_permutation
    -end
    -
    -# The corresponding C signature is
    -#     gsl_permutation * gsl_permutation_alloc (size_t n);
    -function permutation_alloc(n::Integer)
    -    output_ptr = ccall(
    -        (:gsl_permutation_alloc, :libgsl), # name of C function and library
    -        Ptr{gsl_permutation},              # output type
    -        (Csize_t,),                        # tuple of input types
    -        n                                  # name of Julia variable to pass in
    -    )
    -    if output_ptr == C_NULL # Could not allocate memory
    -        throw(OutOfMemoryError())
    -    end
    -    return output_ptr
    -end

    The GNU Scientific Library (here assumed to be accessible through :libgsl) defines an opaque pointer, gsl_permutation *, as the return type of the C function gsl_permutation_alloc(). As user code never has to look inside the gsl_permutation struct, the corresponding Julia wrapper simply needs a new type declaration, gsl_permutation, that has no internal fields and whose sole purpose is to be placed in the type parameter of a Ptr type. The return type of the ccall is declared as Ptr{gsl_permutation}, since the memory allocated and pointed to by output_ptr is controlled by C (and not Julia).

    The input n is passed by value, and so the function's input signature is simply declared as (Csize_t,) without any Ref or Ptr necessary. (If the wrapper was calling a Fortran function instead, the corresponding function input signature should instead be (Ref{Csize_t},), since Fortran variables are passed by reference.) Furthermore, n can be any type that is convertable to a Csize_t integer; the ccall implicitly calls Base.cconvert(Csize_t, n).

    Here is a second example wrapping the corresponding destructor:

    # The corresponding C signature is
    -#     void gsl_permutation_free (gsl_permutation * p);
    -function permutation_free(p::Ref{gsl_permutation})
    -    ccall(
    -        (:gsl_permutation_free, :libgsl), # name of C function and library
    -        Void,                             # output type
    -        (Ref{gsl_permutation},),          # tuple of input types
    -        p                                 # name of Julia variable to pass in
    -    )
    -end

    Here, the input p is declared to be of type Ref{gsl_permutation}, meaning that the memory that p points to may be managed by Julia or by C. A pointer to memory allocated by C should be of type Ptr{gsl_permutation}, but it is convertable using Base.cconvert() and therefore can be used in the same (covariant) context of the input argument to a ccall. A pointer to memory allocated by Julia must be of type Ref{gsl_permutation}, to ensure that the memory address pointed to is valid and that Julia's garbage collector manages the chunk of memory pointed to correctly. Therefore, the Ref{gsl_permutation} declaration allows pointers managed by C or Julia to be used.

    If the C wrapper never expects the user to pass pointers to memory managed by Julia, then using p::Ptr{gsl_permutation} for the method signature of the wrapper and similarly in the ccall is also acceptable.

    Here is a third example passing Julia arrays:

    # The corresponding C signature is
    -#    int gsl_sf_bessel_Jn_array (int nmin, int nmax, double x,
    -#                                double result_array[])
    -function sf_bessel_Jn_array(nmin::Integer, nmax::Integer, x::Real)
    -    if nmax < nmin
    -        throw(DomainError())
    -    end
    -    result_array = Vector{Cdouble}(nmax - nmin + 1)
    -    errorcode = ccall(
    -        (:gsl_sf_bessel_Jn_array, :libgsl), # name of C function and library
    -        Cint,                               # output type
    -        (Cint, Cint, Cdouble, Ref{Cdouble}),# tuple of input types
    -        nmin, nmax, x, result_array         # names of Julia variables to pass in
    -    )
    -    if errorcode != 0
    -        error("GSL error code $errorcode")
    -    end
    -    return result_array
    -end

    The C function wrapped returns an integer error code; the results of the actual evaluation of the Bessel J function populate the Julia array result_array. This variable can only be used with corresponding input type declaration Ref{Cdouble}, since its memory is allocated and managed by Julia, not C. The implicit call to Base.cconvert(Ref{Cdouble}, result_array) unpacks the Julia pointer to a Julia array data structure into a form understandable by C.

    Note that for this code to work correctly, result_array must be declared to be of type Ref{Cdouble} and not Ptr{Cdouble}. The memory is managed by Julia and the Ref signature alerts Julia's garbage collector to keep managing the memory for result_array while the ccall executes. If Ptr{Cdouble} were used instead, the ccall may still work, but Julia's garbage collector would not be aware that the memory declared for result_array is being used by the external C function. As a result, the code may produce a memory leak if result_array never gets freed by the garbage collector, or if the garbage collector prematurely frees result_array, the C function may end up throwing an invalid memory access exception.

    Garbage Collection Safety

    When passing data to a ccall, it is best to avoid using the pointer() function. Instead define a convert method and pass the variables directly to the ccall. ccall automatically arranges that all of its arguments will be preserved from garbage collection until the call returns. If a C API will store a reference to memory allocated by Julia, after the ccall returns, you must arrange that the object remains visible to the garbage collector. The suggested way to handle this is to make a global variable of type Array{Ref,1} to hold these values, until the C library notifies you that it is finished with them.

    Whenever you have created a pointer to Julia data, you must ensure the original data exists until you are done with using the pointer. Many methods in Julia such as unsafe_load() and String() make copies of data instead of taking ownership of the buffer, so that it is safe to free (or alter) the original data without affecting Julia. A notable exception is unsafe_wrap() which, for performance reasons, shares (or can be told to take ownership of) the underlying buffer.

    The garbage collector does not guarantee any order of finalization. That is, if a contained a reference to b and both a and b are due for garbage collection, there is no guarantee that b would be finalized after a. If proper finalization of a depends on b being valid, it must be handled in other ways.

    Non-constant Function Specifications

    A (name, library) function specification must be a constant expression. However, it is possible to use computed values as function names by staging through eval as follows:

    @eval ccall(($(string("a", "b")), "lib"), ...

    This expression constructs a name using string, then substitutes this name into a new ccall expression, which is then evaluated. Keep in mind that eval only operates at the top level, so within this expression local variables will not be available (unless their values are substituted with $). For this reason, eval is typically only used to form top-level definitions, for example when wrapping libraries that contain many similar functions.

    If your usage is more dynamic, use indirect calls as described in the next section.

    Indirect Calls

    The first argument to ccall can also be an expression evaluated at run time. In this case, the expression must evaluate to a Ptr, which will be used as the address of the native function to call. This behavior occurs when the first ccall argument contains references to non-constants, such as local variables, function arguments, or non-constant globals.

    For example, you might look up the function via dlsym, then cache it in a global variable for that session. For example:

    macro dlsym(func, lib)
    -    z, zlocal = gensym(string(func)), gensym()
    -    eval(current_module(), :(global $z = C_NULL))
    -    z = esc(z)
    -    quote
    -        let $zlocal::Ptr{Void} = $z::Ptr{Void}
    -            if $zlocal == C_NULL
    -                $zlocal = dlsym($(esc(lib))::Ptr{Void}, $(esc(func)))
    -                global $z = $zlocal
    -            end
    -            $zlocal
    -        end
    -    end
    -end
    -
    -mylibvar = Libdl.dlopen("mylib")
    -ccall(@dlsym("myfunc", mylibvar), Void, ())

    Calling Convention

    The second argument to ccall can optionally be a calling convention specifier (immediately preceding return type). Without any specifier, the platform-default C calling convention is used. Other supported conventions are: stdcall, cdecl, fastcall, and thiscall. For example (from base/libc.jl) we see the same gethostnameccall as above, but with the correct signature for Windows:

    hn = Vector{UInt8}(256)
    -err = ccall(:gethostname, stdcall, Int32, (Ptr{UInt8}, UInt32), hn, length(hn))

    For more information, please see the LLVM Language Reference.

    There is one additional special calling convention llvmcall, which allows inserting calls to LLVM intrinsics directly. This can be especially useful when targeting unusual platforms such as GPGPUs. For example, for CUDA, we need to be able to read the thread index:

    ccall("llvm.nvvm.read.ptx.sreg.tid.x", llvmcall, Int32, ())

    As with any ccall, it is essential to get the argument signature exactly correct. Also, note that there is no compatibility layer that ensures the intrinsic makes sense and works on the current target, unlike the equivalent Julia functions exposed by Core.Intrinsics.

    Accessing Global Variables

    Global variables exported by native libraries can be accessed by name using the cglobal() function. The arguments to cglobal() are a symbol specification identical to that used by ccall, and a type describing the value stored in the variable:

    julia> cglobal((:errno, :libc), Int32)
    -Ptr{Int32} @0x00007f418d0816b8

    The result is a pointer giving the address of the value. The value can be manipulated through this pointer using unsafe_load() and unsafe_store!().

    Accessing Data through a Pointer

    The following methods are described as "unsafe" because a bad pointer or type declaration can cause Julia to terminate abruptly.

    Given a Ptr{T}, the contents of type T can generally be copied from the referenced memory into a Julia object using unsafe_load(ptr, [index]). The index argument is optional (default is 1), and follows the Julia-convention of 1-based indexing. This function is intentionally similar to the behavior of getindex() and setindex!() (e.g. [] access syntax).

    The return value will be a new object initialized to contain a copy of the contents of the referenced memory. The referenced memory can safely be freed or released.

    If T is Any, then the memory is assumed to contain a reference to a Julia object (a jl_value_t*), the result will be a reference to this object, and the object will not be copied. You must be careful in this case to ensure that the object was always visible to the garbage collector (pointers do not count, but the new reference does) to ensure the memory is not prematurely freed. Note that if the object was not originally allocated by Julia, the new object will never be finalized by Julia's garbage collector. If the Ptr itself is actually a jl_value_t*, it can be converted back to a Julia object reference by unsafe_pointer_to_objref(ptr). (Julia values v can be converted to jl_value_t* pointers, as Ptr{Void}, by calling pointer_from_objref(v).)

    The reverse operation (writing data to a Ptr{T}), can be performed using unsafe_store!(ptr, value, [index]). Currently, this is only supported for primitive types or other pointer-free (isbits) immutable struct types.

    Any operation that throws an error is probably currently unimplemented and should be posted as a bug so that it can be resolved.

    If the pointer of interest is a plain-data array (primitive type or immutable struct), the function unsafe_wrap(Array, ptr,dims,[own]) may be more useful. The final parameter should be true if Julia should "take ownership" of the underlying buffer and call free(ptr) when the returned Array object is finalized. If the own parameter is omitted or false, the caller must ensure the buffer remains in existence until all access is complete.

    Arithmetic on the Ptr type in Julia (e.g. using +) does not behave the same as C's pointer arithmetic. Adding an integer to a Ptr in Julia always moves the pointer by some number of bytes, not elements. This way, the address values obtained from pointer arithmetic do not depend on the element types of pointers.

    Thread-safety

    Some C libraries execute their callbacks from a different thread, and since Julia isn't thread-safe you'll need to take some extra precautions. In particular, you'll need to set up a two-layered system: the C callback should only schedule (via Julia's event loop) the execution of your "real" callback. To do this, create a AsyncCondition object and wait on it:

    cond = Base.AsyncCondition()
    -wait(cond)

    The callback you pass to C should only execute a ccall to :uv_async_send, passing cond.handle as the argument, taking care to avoid any allocations or other interactions with the Julia runtime.

    Note that events may be coalesced, so multiple calls to uv_async_send may result in a single wakeup notification to the condition.

    More About Callbacks

    For more details on how to pass callbacks to C libraries, see this blog post.

    C++

    For direct C++ interfacing, see the Cxx package. For tools to create C++ bindings, see the CxxWrap package.

    diff --git a/julia-0.6.3/share/doc/julia/html/en/manual/complex-and-rational-numbers.html b/julia-0.6.3/share/doc/julia/html/en/manual/complex-and-rational-numbers.html deleted file mode 100644 index bc5c889..0000000 --- a/julia-0.6.3/share/doc/julia/html/en/manual/complex-and-rational-numbers.html +++ /dev/null @@ -1,191 +0,0 @@ - -Complex and Rational Numbers · The Julia Language

    Complex and Rational Numbers

    Complex and Rational Numbers

    Julia ships with predefined types representing both complex and rational numbers, and supports all standard Mathematical Operations and Elementary Functions on them. Conversion and Promotion are defined so that operations on any combination of predefined numeric types, whether primitive or composite, behave as expected.

    Complex Numbers

    The global constant im is bound to the complex number i, representing the principal square root of -1. It was deemed harmful to co-opt the name i for a global constant, since it is such a popular index variable name. Since Julia allows numeric literals to be juxtaposed with identifiers as coefficients, this binding suffices to provide convenient syntax for complex numbers, similar to the traditional mathematical notation:

    julia> 1 + 2im
    -1 + 2im

    You can perform all the standard arithmetic operations with complex numbers:

    julia> (1 + 2im)*(2 - 3im)
    -8 + 1im
    -
    -julia> (1 + 2im)/(1 - 2im)
    --0.6 + 0.8im
    -
    -julia> (1 + 2im) + (1 - 2im)
    -2 + 0im
    -
    -julia> (-3 + 2im) - (5 - 1im)
    --8 + 3im
    -
    -julia> (-1 + 2im)^2
    --3 - 4im
    -
    -julia> (-1 + 2im)^2.5
    -2.7296244647840084 - 6.960664459571898im
    -
    -julia> (-1 + 2im)^(1 + 1im)
    --0.27910381075826657 + 0.08708053414102428im
    -
    -julia> 3(2 - 5im)
    -6 - 15im
    -
    -julia> 3(2 - 5im)^2
    --63 - 60im
    -
    -julia> 3(2 - 5im)^-1.0
    -0.20689655172413796 + 0.5172413793103449im

    The promotion mechanism ensures that combinations of operands of different types just work:

    julia> 2(1 - 1im)
    -2 - 2im
    -
    -julia> (2 + 3im) - 1
    -1 + 3im
    -
    -julia> (1 + 2im) + 0.5
    -1.5 + 2.0im
    -
    -julia> (2 + 3im) - 0.5im
    -2.0 + 2.5im
    -
    -julia> 0.75(1 + 2im)
    -0.75 + 1.5im
    -
    -julia> (2 + 3im) / 2
    -1.0 + 1.5im
    -
    -julia> (1 - 3im) / (2 + 2im)
    --0.5 - 1.0im
    -
    -julia> 2im^2
    --2 + 0im
    -
    -julia> 1 + 3/4im
    -1.0 - 0.75im

    Note that 3/4im == 3/(4*im) == -(3/4*im), since a literal coefficient binds more tightly than division.

    Standard functions to manipulate complex values are provided:

    julia> z = 1 + 2im
    -1 + 2im
    -
    -julia> real(1 + 2im) # real part of z
    -1
    -
    -julia> imag(1 + 2im) # imaginary part of z
    -2
    -
    -julia> conj(1 + 2im) # complex conjugate of z
    -1 - 2im
    -
    -julia> abs(1 + 2im) # absolute value of z
    -2.23606797749979
    -
    -julia> abs2(1 + 2im) # squared absolute value
    -5
    -
    -julia> angle(1 + 2im) # phase angle in radians
    -1.1071487177940904

    As usual, the absolute value (abs()) of a complex number is its distance from zero. abs2() gives the square of the absolute value, and is of particular use for complex numbers where it avoids taking a square root. angle() returns the phase angle in radians (also known as the argument or arg function). The full gamut of other Elementary Functions is also defined for complex numbers:

    julia> sqrt(1im)
    -0.7071067811865476 + 0.7071067811865475im
    -
    -julia> sqrt(1 + 2im)
    -1.272019649514069 + 0.7861513777574233im
    -
    -julia> cos(1 + 2im)
    -2.0327230070196656 - 3.0518977991518im
    -
    -julia> exp(1 + 2im)
    --1.1312043837568135 + 2.4717266720048188im
    -
    -julia> sinh(1 + 2im)
    --0.4890562590412937 + 1.4031192506220405im

    Note that mathematical functions typically return real values when applied to real numbers and complex values when applied to complex numbers. For example, sqrt() behaves differently when applied to -1 versus -1 + 0im even though -1 == -1 + 0im:

    julia> sqrt(-1)
    -ERROR: DomainError:
    -sqrt will only return a complex result if called with a complex argument. Try sqrt(complex(x)).
    -Stacktrace:
    - [1] sqrt(::Int64) at ./math.jl:434
    -
    -julia> sqrt(-1 + 0im)
    -0.0 + 1.0im

    The literal numeric coefficient notation does not work when constructing a complex number from variables. Instead, the multiplication must be explicitly written out:

    julia> a = 1; b = 2; a + b*im
    -1 + 2im

    However, this is not recommended; Use the complex() function instead to construct a complex value directly from its real and imaginary parts:

    julia> a = 1; b = 2; complex(a, b)
    -1 + 2im

    This construction avoids the multiplication and addition operations.

    Inf and NaN propagate through complex numbers in the real and imaginary parts of a complex number as described in the Special floating-point values section:

    julia> 1 + Inf*im
    -1.0 + Inf*im
    -
    -julia> 1 + NaN*im
    -1.0 + NaN*im

    Rational Numbers

    Julia has a rational number type to represent exact ratios of integers. Rationals are constructed using the // operator:

    julia> 2//3
    -2//3

    If the numerator and denominator of a rational have common factors, they are reduced to lowest terms such that the denominator is non-negative:

    julia> 6//9
    -2//3
    -
    -julia> -4//8
    --1//2
    -
    -julia> 5//-15
    --1//3
    -
    -julia> -4//-12
    -1//3

    This normalized form for a ratio of integers is unique, so equality of rational values can be tested by checking for equality of the numerator and denominator. The standardized numerator and denominator of a rational value can be extracted using the numerator() and denominator() functions:

    julia> numerator(2//3)
    -2
    -
    -julia> denominator(2//3)
    -3

    Direct comparison of the numerator and denominator is generally not necessary, since the standard arithmetic and comparison operations are defined for rational values:

    julia> 2//3 == 6//9
    -true
    -
    -julia> 2//3 == 9//27
    -false
    -
    -julia> 3//7 < 1//2
    -true
    -
    -julia> 3//4 > 2//3
    -true
    -
    -julia> 2//4 + 1//6
    -2//3
    -
    -julia> 5//12 - 1//4
    -1//6
    -
    -julia> 5//8 * 3//12
    -5//32
    -
    -julia> 6//5 / 10//7
    -21//25

    Rationals can be easily converted to floating-point numbers:

    julia> float(3//4)
    -0.75

    Conversion from rational to floating-point respects the following identity for any integral values of a and b, with the exception of the case a == 0 and b == 0:

    julia> a = 1; b = 2;
    -
    -julia> isequal(float(a//b), a/b)
    -true

    Constructing infinite rational values is acceptable:

    julia> 5//0
    -1//0
    -
    -julia> -3//0
    --1//0
    -
    -julia> typeof(ans)
    -Rational{Int64}

    Trying to construct a NaN rational value, however, is not:

    julia> 0//0
    -ERROR: ArgumentError: invalid rational: zero(Int64)//zero(Int64)
    -Stacktrace:
    - [1] Rational{Int64}(::Int64, ::Int64) at ./rational.jl:13
    - [2] //(::Int64, ::Int64) at ./rational.jl:40

    As usual, the promotion system makes interactions with other numeric types effortless:

    julia> 3//5 + 1
    -8//5
    -
    -julia> 3//5 - 0.5
    -0.09999999999999998
    -
    -julia> 2//7 * (1 + 2im)
    -2//7 + 4//7*im
    -
    -julia> 2//7 * (1.5 + 2im)
    -0.42857142857142855 + 0.5714285714285714im
    -
    -julia> 3//2 / (1 + 2im)
    -3//10 - 3//5*im
    -
    -julia> 1//2 + 2im
    -1//2 + 2//1*im
    -
    -julia> 1 + 2//3im
    -1//1 - 2//3*im
    -
    -julia> 0.5 == 1//2
    -true
    -
    -julia> 0.33 == 1//3
    -false
    -
    -julia> 0.33 < 1//3
    -true
    -
    -julia> 1//3 - 0.33
    -0.0033333333333332993
    diff --git a/julia-0.6.3/share/doc/julia/html/en/manual/constructors.html b/julia-0.6.3/share/doc/julia/html/en/manual/constructors.html deleted file mode 100644 index 613a612..0000000 --- a/julia-0.6.3/share/doc/julia/html/en/manual/constructors.html +++ /dev/null @@ -1,211 +0,0 @@ - -Constructors · The Julia Language

    Constructors

    Constructors

    Constructors [1] are functions that create new objects – specifically, instances of Composite Types. In Julia, type objects also serve as constructor functions: they create new instances of themselves when applied to an argument tuple as a function. This much was already mentioned briefly when composite types were introduced. For example:

    julia> struct Foo
    -           bar
    -           baz
    -       end
    -
    -julia> foo = Foo(1, 2)
    -Foo(1, 2)
    -
    -julia> foo.bar
    -1
    -
    -julia> foo.baz
    -2

    For many types, forming new objects by binding their field values together is all that is ever needed to create instances. There are, however, cases where more functionality is required when creating composite objects. Sometimes invariants must be enforced, either by checking arguments or by transforming them. Recursive data structures, especially those that may be self-referential, often cannot be constructed cleanly without first being created in an incomplete state and then altered programmatically to be made whole, as a separate step from object creation. Sometimes, it's just convenient to be able to construct objects with fewer or different types of parameters than they have fields. Julia's system for object construction addresses all of these cases and more.

    [1]

    Nomenclature: while the term "constructor" generally refers to the entire function which constructs objects of a type, it is common to abuse terminology slightly and refer to specific constructor methods as "constructors". In such situations, it is generally clear from context that the term is used to mean "constructor method" rather than "constructor function", especially as it is often used in the sense of singling out a particular method of the constructor from all of the others.

    Outer Constructor Methods

    A constructor is just like any other function in Julia in that its overall behavior is defined by the combined behavior of its methods. Accordingly, you can add functionality to a constructor by simply defining new methods. For example, let's say you want to add a constructor method for Foo objects that takes only one argument and uses the given value for both the bar and baz fields. This is simple:

    julia> Foo(x) = Foo(x,x)
    -Foo
    -
    -julia> Foo(1)
    -Foo(1, 1)

    You could also add a zero-argument Foo constructor method that supplies default values for both of the bar and baz fields:

    julia> Foo() = Foo(0)
    -Foo
    -
    -julia> Foo()
    -Foo(0, 0)

    Here the zero-argument constructor method calls the single-argument constructor method, which in turn calls the automatically provided two-argument constructor method. For reasons that will become clear very shortly, additional constructor methods declared as normal methods like this are called outer constructor methods. Outer constructor methods can only ever create a new instance by calling another constructor method, such as the automatically provided default ones.

    Inner Constructor Methods

    While outer constructor methods succeed in addressing the problem of providing additional convenience methods for constructing objects, they fail to address the other two use cases mentioned in the introduction of this chapter: enforcing invariants, and allowing construction of self-referential objects. For these problems, one needs inner constructor methods. An inner constructor method is much like an outer constructor method, with two differences:

    1. It is declared inside the block of a type declaration, rather than outside of it like normal methods.

    2. It has access to a special locally existent function called new that creates objects of the block's type.

    For example, suppose one wants to declare a type that holds a pair of real numbers, subject to the constraint that the first number is not greater than the second one. One could declare it like this:

    julia> struct OrderedPair
    -           x::Real
    -           y::Real
    -           OrderedPair(x,y) = x > y ? error("out of order") : new(x,y)
    -       end
    -

    Now OrderedPair objects can only be constructed such that x <= y:

    julia> OrderedPair(1, 2)
    -OrderedPair(1, 2)
    -
    -julia> OrderedPair(2,1)
    -ERROR: out of order
    -Stacktrace:
    - [1] OrderedPair(::Int64, ::Int64) at ./none:4

    If the type were declared mutable, you could reach in and directly change the field values to violate this invariant, but messing around with an object's internals uninvited is considered poor form. You (or someone else) can also provide additional outer constructor methods at any later point, but once a type is declared, there is no way to add more inner constructor methods. Since outer constructor methods can only create objects by calling other constructor methods, ultimately, some inner constructor must be called to create an object. This guarantees that all objects of the declared type must come into existence by a call to one of the inner constructor methods provided with the type, thereby giving some degree of enforcement of a type's invariants.

    If any inner constructor method is defined, no default constructor method is provided: it is presumed that you have supplied yourself with all the inner constructors you need. The default constructor is equivalent to writing your own inner constructor method that takes all of the object's fields as parameters (constrained to be of the correct type, if the corresponding field has a type), and passes them to new, returning the resulting object:

    julia> struct Foo
    -           bar
    -           baz
    -           Foo(bar,baz) = new(bar,baz)
    -       end
    -

    This declaration has the same effect as the earlier definition of the Foo type without an explicit inner constructor method. The following two types are equivalent – one with a default constructor, the other with an explicit constructor:

    julia> struct T1
    -           x::Int64
    -       end
    -
    -julia> struct T2
    -           x::Int64
    -           T2(x) = new(x)
    -       end
    -
    -julia> T1(1)
    -T1(1)
    -
    -julia> T2(1)
    -T2(1)
    -
    -julia> T1(1.0)
    -T1(1)
    -
    -julia> T2(1.0)
    -T2(1)

    It is considered good form to provide as few inner constructor methods as possible: only those taking all arguments explicitly and enforcing essential error checking and transformation. Additional convenience constructor methods, supplying default values or auxiliary transformations, should be provided as outer constructors that call the inner constructors to do the heavy lifting. This separation is typically quite natural.

    Incomplete Initialization

    The final problem which has still not been addressed is construction of self-referential objects, or more generally, recursive data structures. Since the fundamental difficulty may not be immediately obvious, let us briefly explain it. Consider the following recursive type declaration:

    julia> mutable struct SelfReferential
    -           obj::SelfReferential
    -       end
    -

    This type may appear innocuous enough, until one considers how to construct an instance of it. If a is an instance of SelfReferential, then a second instance can be created by the call:

    julia> b = SelfReferential(a)

    But how does one construct the first instance when no instance exists to provide as a valid value for its obj field? The only solution is to allow creating an incompletely initialized instance of SelfReferential with an unassigned obj field, and using that incomplete instance as a valid value for the obj field of another instance, such as, for example, itself.

    To allow for the creation of incompletely initialized objects, Julia allows the new function to be called with fewer than the number of fields that the type has, returning an object with the unspecified fields uninitialized. The inner constructor method can then use the incomplete object, finishing its initialization before returning it. Here, for example, we take another crack at defining the SelfReferential type, with a zero-argument inner constructor returning instances having obj fields pointing to themselves:

    julia> mutable struct SelfReferential
    -           obj::SelfReferential
    -           SelfReferential() = (x = new(); x.obj = x)
    -       end
    -

    We can verify that this constructor works and constructs objects that are, in fact, self-referential:

    julia> x = SelfReferential();
    -
    -julia> x === x
    -true
    -
    -julia> x === x.obj
    -true
    -
    -julia> x === x.obj.obj
    -true

    Although it is generally a good idea to return a fully initialized object from an inner constructor, incompletely initialized objects can be returned:

    julia> mutable struct Incomplete
    -           xx
    -           Incomplete() = new()
    -       end
    -
    -julia> z = Incomplete();

    While you are allowed to create objects with uninitialized fields, any access to an uninitialized reference is an immediate error:

    julia> z.xx
    -ERROR: UndefRefError: access to undefined reference

    This avoids the need to continually check for null values. However, not all object fields are references. Julia considers some types to be "plain data", meaning all of their data is self-contained and does not reference other objects. The plain data types consist of primitive types (e.g. Int) and immutable structs of other plain data types. The initial contents of a plain data type is undefined:

    julia> struct HasPlain
    -           n::Int
    -           HasPlain() = new()
    -       end
    -
    -julia> HasPlain()
    -HasPlain(438103441441)

    Arrays of plain data types exhibit the same behavior.

    You can pass incomplete objects to other functions from inner constructors to delegate their completion:

    julia> mutable struct Lazy
    -           xx
    -           Lazy(v) = complete_me(new(), v)
    -       end

    As with incomplete objects returned from constructors, if complete_me or any of its callees try to access the xx field of the Lazy object before it has been initialized, an error will be thrown immediately.

    Parametric Constructors

    Parametric types add a few wrinkles to the constructor story. Recall from Parametric Types that, by default, instances of parametric composite types can be constructed either with explicitly given type parameters or with type parameters implied by the types of the arguments given to the constructor. Here are some examples:

    julia> struct Point{T<:Real}
    -           x::T
    -           y::T
    -       end
    -
    -julia> Point(1,2) ## implicit T ##
    -Point{Int64}(1, 2)
    -
    -julia> Point(1.0,2.5) ## implicit T ##
    -Point{Float64}(1.0, 2.5)
    -
    -julia> Point(1,2.5) ## implicit T ##
    -ERROR: MethodError: no method matching Point(::Int64, ::Float64)
    -Closest candidates are:
    -  Point(::T<:Real, !Matched::T<:Real) where T<:Real at none:2
    -
    -julia> Point{Int64}(1, 2) ## explicit T ##
    -Point{Int64}(1, 2)
    -
    -julia> Point{Int64}(1.0,2.5) ## explicit T ##
    -ERROR: InexactError()
    -Stacktrace:
    - [1] convert(::Type{Int64}, ::Float64) at ./float.jl:679
    - [2] Point{Int64}(::Float64, ::Float64) at ./none:2
    -
    -julia> Point{Float64}(1.0, 2.5) ## explicit T ##
    -Point{Float64}(1.0, 2.5)
    -
    -julia> Point{Float64}(1,2) ## explicit T ##
    -Point{Float64}(1.0, 2.0)

    As you can see, for constructor calls with explicit type parameters, the arguments are converted to the implied field types: Point{Int64}(1,2) works, but Point{Int64}(1.0,2.5) raises an InexactError when converting 2.5 to Int64. When the type is implied by the arguments to the constructor call, as in Point(1,2), then the types of the arguments must agree – otherwise the T cannot be determined – but any pair of real arguments with matching type may be given to the generic Point constructor.

    What's really going on here is that Point, Point{Float64} and Point{Int64} are all different constructor functions. In fact, Point{T} is a distinct constructor function for each type T. Without any explicitly provided inner constructors, the declaration of the composite type Point{T<:Real} automatically provides an inner constructor, Point{T}, for each possible type T<:Real, that behaves just like non-parametric default inner constructors do. It also provides a single general outer Point constructor that takes pairs of real arguments, which must be of the same type. This automatic provision of constructors is equivalent to the following explicit declaration:

    julia> struct Point{T<:Real}
    -           x::T
    -           y::T
    -           Point{T}(x,y) where {T<:Real} = new(x,y)
    -       end
    -
    -julia> Point(x::T, y::T) where {T<:Real} = Point{T}(x,y);

    Notice that each definition looks like the form of constructor call that it handles. The call Point{Int64}(1,2) will invoke the definition Point{T}(x,y) inside the type block. The outer constructor declaration, on the other hand, defines a method for the general Point constructor which only applies to pairs of values of the same real type. This declaration makes constructor calls without explicit type parameters, like Point(1,2) and Point(1.0,2.5), work. Since the method declaration restricts the arguments to being of the same type, calls like Point(1,2.5), with arguments of different types, result in "no method" errors.

    Suppose we wanted to make the constructor call Point(1,2.5) work by "promoting" the integer value 1 to the floating-point value 1.0. The simplest way to achieve this is to define the following additional outer constructor method:

    julia> Point(x::Int64, y::Float64) = Point(convert(Float64,x),y);

    This method uses the convert() function to explicitly convert x to Float64 and then delegates construction to the general constructor for the case where both arguments are Float64. With this method definition what was previously a MethodError now successfully creates a point of type Point{Float64}:

    julia> Point(1,2.5)
    -Point{Float64}(1.0, 2.5)
    -
    -julia> typeof(ans)
    -Point{Float64}

    However, other similar calls still don't work:

    julia> Point(1.5,2)
    -ERROR: MethodError: no method matching Point(::Float64, ::Int64)
    -Closest candidates are:
    -  Point(::T<:Real, !Matched::T<:Real) where T<:Real at none:1

    For a more general way to make all such calls work sensibly, see Conversion and Promotion. At the risk of spoiling the suspense, we can reveal here that all it takes is the following outer method definition to make all calls to the general Point constructor work as one would expect:

    julia> Point(x::Real, y::Real) = Point(promote(x,y)...);

    The promote function converts all its arguments to a common type – in this case Float64. With this method definition, the Point constructor promotes its arguments the same way that numeric operators like + do, and works for all kinds of real numbers:

    julia> Point(1.5,2)
    -Point{Float64}(1.5, 2.0)
    -
    -julia> Point(1,1//2)
    -Point{Rational{Int64}}(1//1, 1//2)
    -
    -julia> Point(1.0,1//2)
    -Point{Float64}(1.0, 0.5)

    Thus, while the implicit type parameter constructors provided by default in Julia are fairly strict, it is possible to make them behave in a more relaxed but sensible manner quite easily. Moreover, since constructors can leverage all of the power of the type system, methods, and multiple dispatch, defining sophisticated behavior is typically quite simple.

    Case Study: Rational

    Perhaps the best way to tie all these pieces together is to present a real world example of a parametric composite type and its constructor methods. To that end, here is the (slightly modified) beginning of rational.jl, which implements Julia's Rational Numbers:

    julia> struct OurRational{T<:Integer} <: Real
    -           num::T
    -           den::T
    -           function OurRational{T}(num::T, den::T) where T<:Integer
    -               if num == 0 && den == 0
    -                    error("invalid rational: 0//0")
    -               end
    -               g = gcd(den, num)
    -               num = div(num, g)
    -               den = div(den, g)
    -               new(num, den)
    -           end
    -       end
    -
    -julia> OurRational(n::T, d::T) where {T<:Integer} = OurRational{T}(n,d)
    -OurRational
    -
    -julia> OurRational(n::Integer, d::Integer) = OurRational(promote(n,d)...)
    -OurRational
    -
    -julia> OurRational(n::Integer) = OurRational(n,one(n))
    -OurRational
    -
    -julia> //(n::Integer, d::Integer) = OurRational(n,d)
    -// (generic function with 1 method)
    -
    -julia> //(x::OurRational, y::Integer) = x.num // (x.den*y)
    -// (generic function with 2 methods)
    -
    -julia> //(x::Integer, y::OurRational) = (x*y.den) // y.num
    -// (generic function with 3 methods)
    -
    -julia> //(x::Complex, y::Real) = complex(real(x)//y, imag(x)//y)
    -// (generic function with 4 methods)
    -
    -julia> //(x::Real, y::Complex) = x*y'//real(y*y')
    -// (generic function with 5 methods)
    -
    -julia> function //(x::Complex, y::Complex)
    -           xy = x*y'
    -           yy = real(y*y')
    -           complex(real(xy)//yy, imag(xy)//yy)
    -       end
    -// (generic function with 6 methods)

    The first line – struct OurRational{T<:Integer} <: Real – declares that OurRational takes one type parameter of an integer type, and is itself a real type. The field declarations num::T and den::T indicate that the data held in a OurRational{T} object are a pair of integers of type T, one representing the rational value's numerator and the other representing its denominator.

    Now things get interesting. OurRational has a single inner constructor method which checks that both of num and den aren't zero and ensures that every rational is constructed in "lowest terms" with a non-negative denominator. This is accomplished by dividing the given numerator and denominator values by their greatest common divisor, computed using the gcd function. Since gcd returns the greatest common divisor of its arguments with sign matching the first argument (den here), after this division the new value of den is guaranteed to be non-negative. Because this is the only inner constructor for OurRational, we can be certain that OurRational objects are always constructed in this normalized form.

    OurRational also provides several outer constructor methods for convenience. The first is the "standard" general constructor that infers the type parameter T from the type of the numerator and denominator when they have the same type. The second applies when the given numerator and denominator values have different types: it promotes them to a common type and then delegates construction to the outer constructor for arguments of matching type. The third outer constructor turns integer values into rationals by supplying a value of 1 as the denominator.

    Following the outer constructor definitions, we have a number of methods for the // operator, which provides a syntax for writing rationals. Before these definitions, // is a completely undefined operator with only syntax and no meaning. Afterwards, it behaves just as described in Rational Numbers – its entire behavior is defined in these few lines. The first and most basic definition just makes a//b construct a OurRational by applying the OurRational constructor to a and b when they are integers. When one of the operands of // is already a rational number, we construct a new rational for the resulting ratio slightly differently; this behavior is actually identical to division of a rational with an integer. Finally, applying // to complex integral values creates an instance of Complex{OurRational} – a complex number whose real and imaginary parts are rationals:

    julia> ans = (1 + 2im)//(1 - 2im);
    -
    -julia> typeof(ans)
    -Complex{OurRational{Int64}}
    -
    -julia> ans <: Complex{OurRational}
    -false

    Thus, although the // operator usually returns an instance of OurRational, if either of its arguments are complex integers, it will return an instance of Complex{OurRational} instead. The interested reader should consider perusing the rest of rational.jl: it is short, self-contained, and implements an entire basic Julia type.

    Constructors and Conversion

    Constructors T(args...) in Julia are implemented like other callable objects: methods are added to their types. The type of a type is Type, so all constructor methods are stored in the method table for the Type type. This means that you can declare more flexible constructors, e.g. constructors for abstract types, by explicitly defining methods for the appropriate types.

    However, in some cases you could consider adding methods to Base.convert instead of defining a constructor, because Julia falls back to calling convert() if no matching constructor is found. For example, if no constructor T(args...) = ... exists Base.convert(::Type{T}, args...) = ... is called.

    convert is used extensively throughout Julia whenever one type needs to be converted to another (e.g. in assignment, ccall, etcetera), and should generally only be defined (or successful) if the conversion is lossless. For example, convert(Int, 3.0) produces 3, but convert(Int, 3.2) throws an InexactError. If you want to define a constructor for a lossless conversion from one type to another, you should probably define a convert method instead.

    On the other hand, if your constructor does not represent a lossless conversion, or doesn't represent "conversion" at all, it is better to leave it as a constructor rather than a convert method. For example, the Array{Int}() constructor creates a zero-dimensional Array of the type Int, but is not really a "conversion" from Int to an Array.

    Outer-only constructors

    As we have seen, a typical parametric type has inner constructors that are called when type parameters are known; e.g. they apply to Point{Int} but not to Point. Optionally, outer constructors that determine type parameters automatically can be added, for example constructing a Point{Int} from the call Point(1,2). Outer constructors call inner constructors to do the core work of making an instance. However, in some cases one would rather not provide inner constructors, so that specific type parameters cannot be requested manually.

    For example, say we define a type that stores a vector along with an accurate representation of its sum:

    julia> struct SummedArray{T<:Number,S<:Number}
    -           data::Vector{T}
    -           sum::S
    -       end
    -
    -julia> SummedArray(Int32[1; 2; 3], Int32(6))
    -SummedArray{Int32,Int32}(Int32[1, 2, 3], 6)

    The problem is that we want S to be a larger type than T, so that we can sum many elements with less information loss. For example, when T is Int32, we would like S to be Int64. Therefore we want to avoid an interface that allows the user to construct instances of the type SummedArray{Int32,Int32}. One way to do this is to provide a constructor only for SummedArray, but inside the type definition block to suppress generation of default constructors:

    julia> struct SummedArray{T<:Number,S<:Number}
    -           data::Vector{T}
    -           sum::S
    -           function SummedArray(a::Vector{T}) where T
    -               S = widen(T)
    -               new{T,S}(a, sum(S, a))
    -           end
    -       end
    -
    -julia> SummedArray(Int32[1; 2; 3], Int32(6))
    -ERROR: MethodError: no method matching SummedArray(::Array{Int32,1}, ::Int32)
    -Closest candidates are:
    -  SummedArray(::Array{T,1}) where T at none:5

    This constructor will be invoked by the syntax SummedArray(a). The syntax new{T,S} allows specifying parameters for the type to be constructed, i.e. this call will return a SummedArray{T,S}. new{T,S} can be used in any constructor definition, but for convenience the parameters to new{} are automatically derived from the type being constructed when possible.

    diff --git a/julia-0.6.3/share/doc/julia/html/en/manual/control-flow.html b/julia-0.6.3/share/doc/julia/html/en/manual/control-flow.html deleted file mode 100644 index 735e04a..0000000 --- a/julia-0.6.3/share/doc/julia/html/en/manual/control-flow.html +++ /dev/null @@ -1,404 +0,0 @@ - -Control Flow · The Julia Language

    Control Flow

    Control Flow

    Julia provides a variety of control flow constructs:

    The first five control flow mechanisms are standard to high-level programming languages. Tasks are not so standard: they provide non-local control flow, making it possible to switch between temporarily-suspended computations. This is a powerful construct: both exception handling and cooperative multitasking are implemented in Julia using tasks. Everyday programming requires no direct usage of tasks, but certain problems can be solved much more easily by using tasks.

    Compound Expressions

    Sometimes it is convenient to have a single expression which evaluates several subexpressions in order, returning the value of the last subexpression as its value. There are two Julia constructs that accomplish this: begin blocks and (;) chains. The value of both compound expression constructs is that of the last subexpression. Here's an example of a begin block:

    julia> z = begin
    -           x = 1
    -           y = 2
    -           x + y
    -       end
    -3

    Since these are fairly small, simple expressions, they could easily be placed onto a single line, which is where the (;) chain syntax comes in handy:

    julia> z = (x = 1; y = 2; x + y)
    -3

    This syntax is particularly useful with the terse single-line function definition form introduced in Functions. Although it is typical, there is no requirement that begin blocks be multiline or that (;) chains be single-line:

    julia> begin x = 1; y = 2; x + y end
    -3
    -
    -julia> (x = 1;
    -        y = 2;
    -        x + y)
    -3

    Conditional Evaluation

    Conditional evaluation allows portions of code to be evaluated or not evaluated depending on the value of a boolean expression. Here is the anatomy of the if-elseif-else conditional syntax:

    if x < y
    -    println("x is less than y")
    -elseif x > y
    -    println("x is greater than y")
    -else
    -    println("x is equal to y")
    -end

    If the condition expression x < y is true, then the corresponding block is evaluated; otherwise the condition expression x > y is evaluated, and if it is true, the corresponding block is evaluated; if neither expression is true, the else block is evaluated. Here it is in action:

    julia> function test(x, y)
    -           if x < y
    -               println("x is less than y")
    -           elseif x > y
    -               println("x is greater than y")
    -           else
    -               println("x is equal to y")
    -           end
    -       end
    -test (generic function with 1 method)
    -
    -julia> test(1, 2)
    -x is less than y
    -
    -julia> test(2, 1)
    -x is greater than y
    -
    -julia> test(1, 1)
    -x is equal to y

    The elseif and else blocks are optional, and as many elseif blocks as desired can be used. The condition expressions in the if-elseif-else construct are evaluated until the first one evaluates to true, after which the associated block is evaluated, and no further condition expressions or blocks are evaluated.

    if blocks are "leaky", i.e. they do not introduce a local scope. This means that new variables defined inside the if clauses can be used after the if block, even if they weren't defined before. So, we could have defined the test function above as

    julia> function test(x,y)
    -           if x < y
    -               relation = "less than"
    -           elseif x == y
    -               relation = "equal to"
    -           else
    -               relation = "greater than"
    -           end
    -           println("x is ", relation, " y.")
    -       end
    -test (generic function with 1 method)
    -
    -julia> test(2, 1)
    -x is greater than y.

    The variable relation is declared inside the if block, but used outside. However, when depending on this behavior, make sure all possible code paths define a value for the variable. The following change to the above function results in a runtime error

    julia> function test(x,y)
    -           if x < y
    -               relation = "less than"
    -           elseif x == y
    -               relation = "equal to"
    -           end
    -           println("x is ", relation, " y.")
    -       end
    -test (generic function with 1 method)
    -
    -julia> test(1,2)
    -x is less than y.
    -
    -julia> test(2,1)
    -ERROR: UndefVarError: relation not defined
    -Stacktrace:
    - [1] test(::Int64, ::Int64) at ./none:7

    if blocks also return a value, which may seem unintuitive to users coming from many other languages. This value is simply the return value of the last executed statement in the branch that was chosen, so

    julia> x = 3
    -3
    -
    -julia> if x > 0
    -           "positive!"
    -       else
    -           "negative..."
    -       end
    -"positive!"

    Note that very short conditional statements (one-liners) are frequently expressed using Short-Circuit Evaluation in Julia, as outlined in the next section.

    Unlike C, MATLAB, Perl, Python, and Ruby – but like Java, and a few other stricter, typed languages – it is an error if the value of a conditional expression is anything but true or false:

    julia> if 1
    -           println("true")
    -       end
    -ERROR: TypeError: non-boolean (Int64) used in boolean context

    This error indicates that the conditional was of the wrong type: Int64 rather than the required Bool.

    The so-called "ternary operator", ?:, is closely related to the if-elseif-else syntax, but is used where a conditional choice between single expression values is required, as opposed to conditional execution of longer blocks of code. It gets its name from being the only operator in most languages taking three operands:

    a ? b : c

    The expression a, before the ?, is a condition expression, and the ternary operation evaluates the expression b, before the :, if the condition a is true or the expression c, after the :, if it is false.

    The easiest way to understand this behavior is to see an example. In the previous example, the println call is shared by all three branches: the only real choice is which literal string to print. This could be written more concisely using the ternary operator. For the sake of clarity, let's try a two-way version first:

    julia> x = 1; y = 2;
    -
    -julia> println(x < y ? "less than" : "not less than")
    -less than
    -
    -julia> x = 1; y = 0;
    -
    -julia> println(x < y ? "less than" : "not less than")
    -not less than

    If the expression x < y is true, the entire ternary operator expression evaluates to the string "less than" and otherwise it evaluates to the string "not less than". The original three-way example requires chaining multiple uses of the ternary operator together:

    julia> test(x, y) = println(x < y ? "x is less than y"    :
    -                            x > y ? "x is greater than y" : "x is equal to y")
    -test (generic function with 1 method)
    -
    -julia> test(1, 2)
    -x is less than y
    -
    -julia> test(2, 1)
    -x is greater than y
    -
    -julia> test(1, 1)
    -x is equal to y

    To facilitate chaining, the operator associates from right to left.

    It is significant that like if-elseif-else, the expressions before and after the : are only evaluated if the condition expression evaluates to true or false, respectively:

    julia> v(x) = (println(x); x)
    -v (generic function with 1 method)
    -
    -julia> 1 < 2 ? v("yes") : v("no")
    -yes
    -"yes"
    -
    -julia> 1 > 2 ? v("yes") : v("no")
    -no
    -"no"

    Short-Circuit Evaluation

    Short-circuit evaluation is quite similar to conditional evaluation. The behavior is found in most imperative programming languages having the && and || boolean operators: in a series of boolean expressions connected by these operators, only the minimum number of expressions are evaluated as are necessary to determine the final boolean value of the entire chain. Explicitly, this means that:

    • In the expression a && b, the subexpression b is only evaluated if a evaluates to true.

    • In the expression a || b, the subexpression b is only evaluated if a evaluates to false.

    The reasoning is that a && b must be false if a is false, regardless of the value of b, and likewise, the value of a || b must be true if a is true, regardless of the value of b. Both && and || associate to the right, but && has higher precedence than || does. It's easy to experiment with this behavior:

    julia> t(x) = (println(x); true)
    -t (generic function with 1 method)
    -
    -julia> f(x) = (println(x); false)
    -f (generic function with 1 method)
    -
    -julia> t(1) && t(2)
    -1
    -2
    -true
    -
    -julia> t(1) && f(2)
    -1
    -2
    -false
    -
    -julia> f(1) && t(2)
    -1
    -false
    -
    -julia> f(1) && f(2)
    -1
    -false
    -
    -julia> t(1) || t(2)
    -1
    -true
    -
    -julia> t(1) || f(2)
    -1
    -true
    -
    -julia> f(1) || t(2)
    -1
    -2
    -true
    -
    -julia> f(1) || f(2)
    -1
    -2
    -false

    You can easily experiment in the same way with the associativity and precedence of various combinations of && and || operators.

    This behavior is frequently used in Julia to form an alternative to very short if statements. Instead of if <cond> <statement> end, one can write <cond> && <statement> (which could be read as: <cond> and then <statement>). Similarly, instead of if ! <cond> <statement> end, one can write <cond> || <statement> (which could be read as: <cond> or else <statement>).

    For example, a recursive factorial routine could be defined like this:

    julia> function fact(n::Int)
    -           n >= 0 || error("n must be non-negative")
    -           n == 0 && return 1
    -           n * fact(n-1)
    -       end
    -fact (generic function with 1 method)
    -
    -julia> fact(5)
    -120
    -
    -julia> fact(0)
    -1
    -
    -julia> fact(-1)
    -ERROR: n must be non-negative
    -Stacktrace:
    - [1] fact(::Int64) at ./none:2

    Boolean operations without short-circuit evaluation can be done with the bitwise boolean operators introduced in Mathematical Operations and Elementary Functions: & and |. These are normal functions, which happen to support infix operator syntax, but always evaluate their arguments:

    julia> f(1) & t(2)
    -1
    -2
    -false
    -
    -julia> t(1) | t(2)
    -1
    -2
    -true

    Just like condition expressions used in if, elseif or the ternary operator, the operands of && or || must be boolean values (true or false). Using a non-boolean value anywhere except for the last entry in a conditional chain is an error:

    julia> 1 && true
    -ERROR: TypeError: non-boolean (Int64) used in boolean context

    On the other hand, any type of expression can be used at the end of a conditional chain. It will be evaluated and returned depending on the preceding conditionals:

    julia> true && (x = (1, 2, 3))
    -(1, 2, 3)
    -
    -julia> false && (x = (1, 2, 3))
    -false

    Repeated Evaluation: Loops

    There are two constructs for repeated evaluation of expressions: the while loop and the for loop. Here is an example of a while loop:

    julia> i = 1;
    -
    -julia> while i <= 5
    -           println(i)
    -           i += 1
    -       end
    -1
    -2
    -3
    -4
    -5

    The while loop evaluates the condition expression (i <= 5 in this case), and as long it remains true, keeps also evaluating the body of the while loop. If the condition expression is false when the while loop is first reached, the body is never evaluated.

    The for loop makes common repeated evaluation idioms easier to write. Since counting up and down like the above while loop does is so common, it can be expressed more concisely with a for loop:

    julia> for i = 1:5
    -           println(i)
    -       end
    -1
    -2
    -3
    -4
    -5

    Here the 1:5 is a Range object, representing the sequence of numbers 1, 2, 3, 4, 5. The for loop iterates through these values, assigning each one in turn to the variable i. One rather important distinction between the previous while loop form and the for loop form is the scope during which the variable is visible. If the variable i has not been introduced in an other scope, in the for loop form, it is visible only inside of the for loop, and not afterwards. You'll either need a new interactive session instance or a different variable name to test this:

    julia> for j = 1:5
    -           println(j)
    -       end
    -1
    -2
    -3
    -4
    -5
    -
    -julia> j
    -ERROR: UndefVarError: j not defined

    See Scope of Variables for a detailed explanation of variable scope and how it works in Julia.

    In general, the for loop construct can iterate over any container. In these cases, the alternative (but fully equivalent) keyword in or is typically used instead of =, since it makes the code read more clearly:

    julia> for i in [1,4,0]
    -           println(i)
    -       end
    -1
    -4
    -0
    -
    -julia> for s ∈ ["foo","bar","baz"]
    -           println(s)
    -       end
    -foo
    -bar
    -baz

    Various types of iterable containers will be introduced and discussed in later sections of the manual (see, e.g., Multi-dimensional Arrays).

    It is sometimes convenient to terminate the repetition of a while before the test condition is falsified or stop iterating in a for loop before the end of the iterable object is reached. This can be accomplished with the break keyword:

    julia> i = 1;
    -
    -julia> while true
    -           println(i)
    -           if i >= 5
    -               break
    -           end
    -           i += 1
    -       end
    -1
    -2
    -3
    -4
    -5
    -
    -julia> for i = 1:1000
    -           println(i)
    -           if i >= 5
    -               break
    -           end
    -       end
    -1
    -2
    -3
    -4
    -5

    Without the break keyword, the above while loop would never terminate on its own, and the for loop would iterate up to 1000. These loops are both exited early by using break.

    In other circumstances, it is handy to be able to stop an iteration and move on to the next one immediately. The continue keyword accomplishes this:

    julia> for i = 1:10
    -           if i % 3 != 0
    -               continue
    -           end
    -           println(i)
    -       end
    -3
    -6
    -9

    This is a somewhat contrived example since we could produce the same behavior more clearly by negating the condition and placing the println call inside the if block. In realistic usage there is more code to be evaluated after the continue, and often there are multiple points from which one calls continue.

    Multiple nested for loops can be combined into a single outer loop, forming the cartesian product of its iterables:

    julia> for i = 1:2, j = 3:4
    -           println((i, j))
    -       end
    -(1, 3)
    -(1, 4)
    -(2, 3)
    -(2, 4)

    A break statement inside such a loop exits the entire nest of loops, not just the inner one.

    Exception Handling

    When an unexpected condition occurs, a function may be unable to return a reasonable value to its caller. In such cases, it may be best for the exceptional condition to either terminate the program, printing a diagnostic error message, or if the programmer has provided code to handle such exceptional circumstances, allow that code to take the appropriate action.

    Built-in Exceptions

    Exceptions are thrown when an unexpected condition has occurred. The built-in Exceptions listed below all interrupt the normal flow of control.

    Exception
    ArgumentError
    BoundsError
    CompositeException
    DivideError
    DomainError
    EOFError
    ErrorException
    InexactError
    InitError
    InterruptException
    InvalidStateException
    KeyError
    LoadError
    OutOfMemoryError
    ReadOnlyMemoryError
    RemoteException
    MethodError
    OverflowError
    ParseError
    SystemError
    TypeError
    UndefRefError
    UndefVarError
    UnicodeError

    For example, the sqrt() function throws a DomainError if applied to a negative real value:

    julia> sqrt(-1)
    -ERROR: DomainError:
    -sqrt will only return a complex result if called with a complex argument. Try sqrt(complex(x)).
    -Stacktrace:
    - [1] sqrt(::Int64) at ./math.jl:434

    You may define your own exceptions in the following way:

    julia> struct MyCustomException <: Exception end

    The throw() function

    Exceptions can be created explicitly with throw(). For example, a function defined only for nonnegative numbers could be written to throw() a DomainError if the argument is negative:

    julia> f(x) = x>=0 ? exp(-x) : throw(DomainError())
    -f (generic function with 1 method)
    -
    -julia> f(1)
    -0.36787944117144233
    -
    -julia> f(-1)
    -ERROR: DomainError:
    -Stacktrace:
    - [1] f(::Int64) at ./none:1

    Note that DomainError without parentheses is not an exception, but a type of exception. It needs to be called to obtain an Exception object:

    julia> typeof(DomainError()) <: Exception
    -true
    -
    -julia> typeof(DomainError) <: Exception
    -false

    Additionally, some exception types take one or more arguments that are used for error reporting:

    julia> throw(UndefVarError(:x))
    -ERROR: UndefVarError: x not defined

    This mechanism can be implemented easily by custom exception types following the way UndefVarError is written:

    julia> struct MyUndefVarError <: Exception
    -           var::Symbol
    -       end
    -
    -julia> Base.showerror(io::IO, e::MyUndefVarError) = print(io, e.var, " not defined")
    Note

    When writing an error message, it is preferred to make the first word lowercase. For example, size(A) == size(B) || throw(DimensionMismatch("size of A not equal to size of B"))

    is preferred over

    size(A) == size(B) || throw(DimensionMismatch("Size of A not equal to size of B")).

    However, sometimes it makes sense to keep the uppercase first letter, for instance if an argument to a function is a capital letter: size(A,1) == size(B,2) || throw(DimensionMismatch("A has first dimension...")).

    Errors

    The error() function is used to produce an ErrorException that interrupts the normal flow of control.

    Suppose we want to stop execution immediately if the square root of a negative number is taken. To do this, we can define a fussy version of the sqrt() function that raises an error if its argument is negative:

    julia> fussy_sqrt(x) = x >= 0 ? sqrt(x) : error("negative x not allowed")
    -fussy_sqrt (generic function with 1 method)
    -
    -julia> fussy_sqrt(2)
    -1.4142135623730951
    -
    -julia> fussy_sqrt(-1)
    -ERROR: negative x not allowed
    -Stacktrace:
    - [1] fussy_sqrt(::Int64) at ./none:1

    If fussy_sqrt is called with a negative value from another function, instead of trying to continue execution of the calling function, it returns immediately, displaying the error message in the interactive session:

    julia> function verbose_fussy_sqrt(x)
    -           println("before fussy_sqrt")
    -           r = fussy_sqrt(x)
    -           println("after fussy_sqrt")
    -           return r
    -       end
    -verbose_fussy_sqrt (generic function with 1 method)
    -
    -julia> verbose_fussy_sqrt(2)
    -before fussy_sqrt
    -after fussy_sqrt
    -1.4142135623730951
    -
    -julia> verbose_fussy_sqrt(-1)
    -before fussy_sqrt
    -ERROR: negative x not allowed
    -Stacktrace:
    - [1] fussy_sqrt at ./none:1 [inlined]
    - [2] verbose_fussy_sqrt(::Int64) at ./none:3

    Warnings and informational messages

    Julia also provides other functions that write messages to the standard error I/O, but do not throw any Exceptions and hence do not interrupt execution:

    julia> info("Hi"); 1+1
    -INFO: Hi
    -2
    -
    -julia> warn("Hi"); 1+1
    -WARNING: Hi
    -2
    -
    -julia> error("Hi"); 1+1
    -ERROR: Hi
    -Stacktrace:
    - [1] error(::String) at ./error.jl:21

    The try/catch statement

    The try/catch statement allows for Exceptions to be tested for. For example, a customized square root function can be written to automatically call either the real or complex square root method on demand using Exceptions :

    julia> f(x) = try
    -           sqrt(x)
    -       catch
    -           sqrt(complex(x, 0))
    -       end
    -f (generic function with 1 method)
    -
    -julia> f(1)
    -1.0
    -
    -julia> f(-1)
    -0.0 + 1.0im

    It is important to note that in real code computing this function, one would compare x to zero instead of catching an exception. The exception is much slower than simply comparing and branching.

    try/catch statements also allow the Exception to be saved in a variable. In this contrived example, the following example calculates the square root of the second element of x if x is indexable, otherwise assumes x is a real number and returns its square root:

    julia> sqrt_second(x) = try
    -           sqrt(x[2])
    -       catch y
    -           if isa(y, DomainError)
    -               sqrt(complex(x[2], 0))
    -           elseif isa(y, BoundsError)
    -               sqrt(x)
    -           end
    -       end
    -sqrt_second (generic function with 1 method)
    -
    -julia> sqrt_second([1 4])
    -2.0
    -
    -julia> sqrt_second([1 -4])
    -0.0 + 2.0im
    -
    -julia> sqrt_second(9)
    -3.0
    -
    -julia> sqrt_second(-9)
    -ERROR: DomainError:
    -Stacktrace:
    - [1] sqrt_second(::Int64) at ./none:7

    Note that the symbol following catch will always be interpreted as a name for the exception, so care is needed when writing try/catch expressions on a single line. The following code will not work to return the value of x in case of an error:

    try bad() catch x end

    Instead, use a semicolon or insert a line break after catch:

    try bad() catch; x end
    -
    -try bad()
    -catch
    -    x
    -end

    The catch clause is not strictly necessary; when omitted, the default return value is nothing.

    julia> try error() end # Returns nothing

    The power of the try/catch construct lies in the ability to unwind a deeply nested computation immediately to a much higher level in the stack of calling functions. There are situations where no error has occurred, but the ability to unwind the stack and pass a value to a higher level is desirable. Julia provides the rethrow(), backtrace() and catch_backtrace() functions for more advanced error handling.

    finally Clauses

    In code that performs state changes or uses resources like files, there is typically clean-up work (such as closing files) that needs to be done when the code is finished. Exceptions potentially complicate this task, since they can cause a block of code to exit before reaching its normal end. The finally keyword provides a way to run some code when a given block of code exits, regardless of how it exits.

    For example, here is how we can guarantee that an opened file is closed:

    f = open("file")
    -try
    -    # operate on file f
    -finally
    -    close(f)
    -end

    When control leaves the try block (for example due to a return, or just finishing normally), close(f) will be executed. If the try block exits due to an exception, the exception will continue propagating. A catch block may be combined with try and finally as well. In this case the finally block will run after catch has handled the error.

    Tasks (aka Coroutines)

    Tasks are a control flow feature that allows computations to be suspended and resumed in a flexible manner. This feature is sometimes called by other names, such as symmetric coroutines, lightweight threads, cooperative multitasking, or one-shot continuations.

    When a piece of computing work (in practice, executing a particular function) is designated as a Task, it becomes possible to interrupt it by switching to another Task. The original Task can later be resumed, at which point it will pick up right where it left off. At first, this may seem similar to a function call. However there are two key differences. First, switching tasks does not use any space, so any number of task switches can occur without consuming the call stack. Second, switching among tasks can occur in any order, unlike function calls, where the called function must finish executing before control returns to the calling function.

    This kind of control flow can make it much easier to solve certain problems. In some problems, the various pieces of required work are not naturally related by function calls; there is no obvious "caller" or "callee" among the jobs that need to be done. An example is the producer-consumer problem, where one complex procedure is generating values and another complex procedure is consuming them. The consumer cannot simply call a producer function to get a value, because the producer may have more values to generate and so might not yet be ready to return. With tasks, the producer and consumer can both run as long as they need to, passing values back and forth as necessary.

    Julia provides a Channel mechanism for solving this problem. A Channel is a waitable first-in first-out queue which can have multiple tasks reading from and writing to it.

    Let's define a producer task, which produces values via the put! call. To consume values, we need to schedule the producer to run in a new task. A special Channel constructor which accepts a 1-arg function as an argument can be used to run a task bound to a channel. We can then take!() values repeatedly from the channel object:

    julia> function producer(c::Channel)
    -           put!(c, "start")
    -           for n=1:4
    -               put!(c, 2n)
    -           end
    -           put!(c, "stop")
    -       end;
    -
    -julia> chnl = Channel(producer);
    -
    -julia> take!(chnl)
    -"start"
    -
    -julia> take!(chnl)
    -2
    -
    -julia> take!(chnl)
    -4
    -
    -julia> take!(chnl)
    -6
    -
    -julia> take!(chnl)
    -8
    -
    -julia> take!(chnl)
    -"stop"

    One way to think of this behavior is that producer was able to return multiple times. Between calls to put!(), the producer's execution is suspended and the consumer has control.

    The returned Channel can be used as an iterable object in a for loop, in which case the loop variable takes on all the produced values. The loop is terminated when the channel is closed.

    julia> for x in Channel(producer)
    -           println(x)
    -       end
    -start
    -2
    -4
    -6
    -8
    -stop

    Note that we did not have to explicitly close the channel in the producer. This is because the act of binding a Channel to a Task() associates the open lifetime of a channel with that of the bound task. The channel object is closed automatically when the task terminates. Multiple channels can be bound to a task, and vice-versa.

    While the Task() constructor expects a 0-argument function, the Channel() method which creates a channel bound task expects a function that accepts a single argument of type Channel. A common pattern is for the producer to be parameterized, in which case a partial function application is needed to create a 0 or 1 argument anonymous function.

    For Task() objects this can be done either directly or by use of a convenience macro:

    function mytask(myarg)
    -    ...
    -end
    -
    -taskHdl = Task(() -> mytask(7))
    -# or, equivalently
    -taskHdl = @task mytask(7)

    To orchestrate more advanced work distribution patterns, bind() and schedule() can be used in conjunction with Task() and Channel() constructors to explicitly link a set of channels with a set of producer/consumer tasks.

    Note that currently Julia tasks are not scheduled to run on separate CPU cores. True kernel threads are discussed under the topic of Parallel Computing.

    Core task operations

    Let us explore the low level construct yieldto() to underestand how task switching works. yieldto(task,value) suspends the current task, switches to the specified task, and causes that task's last yieldto() call to return the specified value. Notice that yieldto() is the only operation required to use task-style control flow; instead of calling and returning we are always just switching to a different task. This is why this feature is also called "symmetric coroutines"; each task is switched to and from using the same mechanism.

    yieldto() is powerful, but most uses of tasks do not invoke it directly. Consider why this might be. If you switch away from the current task, you will probably want to switch back to it at some point, but knowing when to switch back, and knowing which task has the responsibility of switching back, can require considerable coordination. For example, put!() and take!() are blocking operations, which, when used in the context of channels maintain state to remember who the consumers are. Not needing to manually keep track of the consuming task is what makes put!() easier to use than the low-level yieldto().

    In addition to yieldto(), a few other basic functions are needed to use tasks effectively.

    Tasks and events

    Most task switches occur as a result of waiting for events such as I/O requests, and are performed by a scheduler included in the standard library. The scheduler maintains a queue of runnable tasks, and executes an event loop that restarts tasks based on external events such as message arrival.

    The basic function for waiting for an event is wait(). Several objects implement wait(); for example, given a Process object, wait() will wait for it to exit. wait() is often implicit; for example, a wait() can happen inside a call to read() to wait for data to be available.

    In all of these cases, wait() ultimately operates on a Condition object, which is in charge of queueing and restarting tasks. When a task calls wait() on a Condition, the task is marked as non-runnable, added to the condition's queue, and switches to the scheduler. The scheduler will then pick another task to run, or block waiting for external events. If all goes well, eventually an event handler will call notify() on the condition, which causes tasks waiting for that condition to become runnable again.

    A task created explicitly by calling Task is initially not known to the scheduler. This allows you to manage tasks manually using yieldto() if you wish. However, when such a task waits for an event, it still gets restarted automatically when the event happens, as you would expect. It is also possible to make the scheduler run a task whenever it can, without necessarily waiting for any events. This is done by calling schedule(), or using the @schedule or @async macros (see Parallel Computing for more details).

    Task states

    Tasks have a state field that describes their execution status. A Task state is one of the following symbols:

    SymbolMeaning
    :runnableCurrently running, or available to be switched to
    :waitingBlocked waiting for a specific event
    :queuedIn the scheduler's run queue about to be restarted
    :doneSuccessfully finished executing
    :failedFinished with an uncaught exception
    diff --git a/julia-0.6.3/share/doc/julia/html/en/manual/conversion-and-promotion.html b/julia-0.6.3/share/doc/julia/html/en/manual/conversion-and-promotion.html deleted file mode 100644 index 3094b0f..0000000 --- a/julia-0.6.3/share/doc/julia/html/en/manual/conversion-and-promotion.html +++ /dev/null @@ -1,99 +0,0 @@ - -Conversion and Promotion · The Julia Language

    Conversion and Promotion

    Conversion and Promotion

    Julia has a system for promoting arguments of mathematical operators to a common type, which has been mentioned in various other sections, including Integers and Floating-Point Numbers, Mathematical Operations and Elementary Functions, Types, and Methods. In this section, we explain how this promotion system works, as well as how to extend it to new types and apply it to functions besides built-in mathematical operators. Traditionally, programming languages fall into two camps with respect to promotion of arithmetic arguments:

    • Automatic promotion for built-in arithmetic types and operators. In most languages, built-in numeric types, when used as operands to arithmetic operators with infix syntax, such as +, -, *, and /, are automatically promoted to a common type to produce the expected results. C, Java, Perl, and Python, to name a few, all correctly compute the sum 1 + 1.5 as the floating-point value 2.5, even though one of the operands to + is an integer. These systems are convenient and designed carefully enough that they are generally all-but-invisible to the programmer: hardly anyone consciously thinks of this promotion taking place when writing such an expression, but compilers and interpreters must perform conversion before addition since integers and floating-point values cannot be added as-is. Complex rules for such automatic conversions are thus inevitably part of specifications and implementations for such languages.

    • No automatic promotion. This camp includes Ada and ML – very "strict" statically typed languages. In these languages, every conversion must be explicitly specified by the programmer. Thus, the example expression 1 + 1.5 would be a compilation error in both Ada and ML. Instead one must write real(1) + 1.5, explicitly converting the integer 1 to a floating-point value before performing addition. Explicit conversion everywhere is so inconvenient, however, that even Ada has some degree of automatic conversion: integer literals are promoted to the expected integer type automatically, and floating-point literals are similarly promoted to appropriate floating-point types.

    In a sense, Julia falls into the "no automatic promotion" category: mathematical operators are just functions with special syntax, and the arguments of functions are never automatically converted. However, one may observe that applying mathematical operations to a wide variety of mixed argument types is just an extreme case of polymorphic multiple dispatch – something which Julia's dispatch and type systems are particularly well-suited to handle. "Automatic" promotion of mathematical operands simply emerges as a special application: Julia comes with pre-defined catch-all dispatch rules for mathematical operators, invoked when no specific implementation exists for some combination of operand types. These catch-all rules first promote all operands to a common type using user-definable promotion rules, and then invoke a specialized implementation of the operator in question for the resulting values, now of the same type. User-defined types can easily participate in this promotion system by defining methods for conversion to and from other types, and providing a handful of promotion rules defining what types they should promote to when mixed with other types.

    Conversion

    Conversion of values to various types is performed by the convert function. The convert function generally takes two arguments: the first is a type object while the second is a value to convert to that type; the returned value is the value converted to an instance of given type. The simplest way to understand this function is to see it in action:

    julia> x = 12
    -12
    -
    -julia> typeof(x)
    -Int64
    -
    -julia> convert(UInt8, x)
    -0x0c
    -
    -julia> typeof(ans)
    -UInt8
    -
    -julia> convert(AbstractFloat, x)
    -12.0
    -
    -julia> typeof(ans)
    -Float64
    -
    -julia> a = Any[1 2 3; 4 5 6]
    -2×3 Array{Any,2}:
    - 1  2  3
    - 4  5  6
    -
    -julia> convert(Array{Float64}, a)
    -2×3 Array{Float64,2}:
    - 1.0  2.0  3.0
    - 4.0  5.0  6.0

    Conversion isn't always possible, in which case a no method error is thrown indicating that convert doesn't know how to perform the requested conversion:

    julia> convert(AbstractFloat, "foo")
    -ERROR: MethodError: Cannot `convert` an object of type String to an object of type AbstractFloat
    -This may have arisen from a call to the constructor AbstractFloat(...),
    -since type constructors fall back to convert methods.

    Some languages consider parsing strings as numbers or formatting numbers as strings to be conversions (many dynamic languages will even perform conversion for you automatically), however Julia does not: even though some strings can be parsed as numbers, most strings are not valid representations of numbers, and only a very limited subset of them are. Therefore in Julia the dedicated parse() function must be used to perform this operation, making it more explicit.

    Defining New Conversions

    To define a new conversion, simply provide a new method for convert(). That's really all there is to it. For example, the method to convert a real number to a boolean is this:

    convert(::Type{Bool}, x::Real) = x==0 ? false : x==1 ? true : throw(InexactError())

    The type of the first argument of this method is a singleton type, Type{Bool}, the only instance of which is Bool. Thus, this method is only invoked when the first argument is the type value Bool. Notice the syntax used for the first argument: the argument name is omitted prior to the :: symbol, and only the type is given. This is the syntax in Julia for a function argument whose type is specified but whose value is never used in the function body. In this example, since the type is a singleton, there would never be any reason to use its value within the body. When invoked, the method determines whether a numeric value is true or false as a boolean, by comparing it to one and zero:

    julia> convert(Bool, 1)
    -true
    -
    -julia> convert(Bool, 0)
    -false
    -
    -julia> convert(Bool, 1im)
    -ERROR: InexactError()
    -Stacktrace:
    - [1] convert(::Type{Bool}, ::Complex{Int64}) at ./complex.jl:31
    -
    -julia> convert(Bool, 0im)
    -false

    The method signatures for conversion methods are often quite a bit more involved than this example, especially for parametric types. The example above is meant to be pedagogical, and is not the actual Julia behaviour. This is the actual implementation in Julia:

    convert(::Type{T}, z::Complex) where {T<:Real} =
    -    (imag(z) == 0 ? convert(T, real(z)) : throw(InexactError()))

    Case Study: Rational Conversions

    To continue our case study of Julia's Rational type, here are the conversions declared in rational.jl, right after the declaration of the type and its constructors:

    convert(::Type{Rational{T}}, x::Rational) where {T<:Integer} = Rational(convert(T,x.num),convert(T,x.den))
    -convert(::Type{Rational{T}}, x::Integer) where {T<:Integer} = Rational(convert(T,x), convert(T,1))
    -
    -function convert(::Type{Rational{T}}, x::AbstractFloat, tol::Real) where T<:Integer
    -    if isnan(x); return zero(T)//zero(T); end
    -    if isinf(x); return sign(x)//zero(T); end
    -    y = x
    -    a = d = one(T)
    -    b = c = zero(T)
    -    while true
    -        f = convert(T,round(y)); y -= f
    -        a, b, c, d = f*a+c, f*b+d, a, b
    -        if y == 0 || abs(a/b-x) <= tol
    -            return a//b
    -        end
    -        y = 1/y
    -    end
    -end
    -convert(rt::Type{Rational{T}}, x::AbstractFloat) where {T<:Integer} = convert(rt,x,eps(x))
    -
    -convert(::Type{T}, x::Rational) where {T<:AbstractFloat} = convert(T,x.num)/convert(T,x.den)
    -convert(::Type{T}, x::Rational) where {T<:Integer} = div(convert(T,x.num),convert(T,x.den))

    The initial four convert methods provide conversions to rational types. The first method converts one type of rational to another type of rational by converting the numerator and denominator to the appropriate integer type. The second method does the same conversion for integers by taking the denominator to be 1. The third method implements a standard algorithm for approximating a floating-point number by a ratio of integers to within a given tolerance, and the fourth method applies it, using machine epsilon at the given value as the threshold. In general, one should have a//b == convert(Rational{Int64}, a/b).

    The last two convert methods provide conversions from rational types to floating-point and integer types. To convert to floating point, one simply converts both numerator and denominator to that floating point type and then divides. To convert to integer, one can use the div operator for truncated integer division (rounded towards zero).

    Promotion

    Promotion refers to converting values of mixed types to a single common type. Although it is not strictly necessary, it is generally implied that the common type to which the values are converted can faithfully represent all of the original values. In this sense, the term "promotion" is appropriate since the values are converted to a "greater" type – i.e. one which can represent all of the input values in a single common type. It is important, however, not to confuse this with object-oriented (structural) super-typing, or Julia's notion of abstract super-types: promotion has nothing to do with the type hierarchy, and everything to do with converting between alternate representations. For instance, although every Int32 value can also be represented as a Float64 value, Int32 is not a subtype of Float64.

    Promotion to a common "greater" type is performed in Julia by the promote function, which takes any number of arguments, and returns a tuple of the same number of values, converted to a common type, or throws an exception if promotion is not possible. The most common use case for promotion is to convert numeric arguments to a common type:

    julia> promote(1, 2.5)
    -(1.0, 2.5)
    -
    -julia> promote(1, 2.5, 3)
    -(1.0, 2.5, 3.0)
    -
    -julia> promote(2, 3//4)
    -(2//1, 3//4)
    -
    -julia> promote(1, 2.5, 3, 3//4)
    -(1.0, 2.5, 3.0, 0.75)
    -
    -julia> promote(1.5, im)
    -(1.5 + 0.0im, 0.0 + 1.0im)
    -
    -julia> promote(1 + 2im, 3//4)
    -(1//1 + 2//1*im, 3//4 + 0//1*im)

    Floating-point values are promoted to the largest of the floating-point argument types. Integer values are promoted to the larger of either the native machine word size or the largest integer argument type. Mixtures of integers and floating-point values are promoted to a floating-point type big enough to hold all the values. Integers mixed with rationals are promoted to rationals. Rationals mixed with floats are promoted to floats. Complex values mixed with real values are promoted to the appropriate kind of complex value.

    That is really all there is to using promotions. The rest is just a matter of clever application, the most typical "clever" application being the definition of catch-all methods for numeric operations like the arithmetic operators +, -, * and /. Here are some of the catch-all method definitions given in promotion.jl:

    +(x::Number, y::Number) = +(promote(x,y)...)
    --(x::Number, y::Number) = -(promote(x,y)...)
    -*(x::Number, y::Number) = *(promote(x,y)...)
    -/(x::Number, y::Number) = /(promote(x,y)...)

    These method definitions say that in the absence of more specific rules for adding, subtracting, multiplying and dividing pairs of numeric values, promote the values to a common type and then try again. That's all there is to it: nowhere else does one ever need to worry about promotion to a common numeric type for arithmetic operations – it just happens automatically. There are definitions of catch-all promotion methods for a number of other arithmetic and mathematical functions in promotion.jl, but beyond that, there are hardly any calls to promote required in the Julia standard library. The most common usages of promote occur in outer constructors methods, provided for convenience, to allow constructor calls with mixed types to delegate to an inner type with fields promoted to an appropriate common type. For example, recall that rational.jl provides the following outer constructor method:

    Rational(n::Integer, d::Integer) = Rational(promote(n,d)...)

    This allows calls like the following to work:

    julia> Rational(Int8(15),Int32(-5))
    --3//1
    -
    -julia> typeof(ans)
    -Rational{Int32}

    For most user-defined types, it is better practice to require programmers to supply the expected types to constructor functions explicitly, but sometimes, especially for numeric problems, it can be convenient to do promotion automatically.

    Defining Promotion Rules

    Although one could, in principle, define methods for the promote function directly, this would require many redundant definitions for all possible permutations of argument types. Instead, the behavior of promote is defined in terms of an auxiliary function called promote_rule, which one can provide methods for. The promote_rule function takes a pair of type objects and returns another type object, such that instances of the argument types will be promoted to the returned type. Thus, by defining the rule:

    promote_rule(::Type{Float64}, ::Type{Float32}) = Float64

    one declares that when 64-bit and 32-bit floating-point values are promoted together, they should be promoted to 64-bit floating-point. The promotion type does not need to be one of the argument types, however; the following promotion rules both occur in Julia's standard library:

    promote_rule(::Type{UInt8}, ::Type{Int8}) = Int
    -promote_rule(::Type{BigInt}, ::Type{Int8}) = BigInt

    In the latter case, the result type is BigInt since BigInt is the only type large enough to hold integers for arbitrary-precision integer arithmetic. Also note that one does not need to define both promote_rule(::Type{A}, ::Type{B}) and promote_rule(::Type{B}, ::Type{A}) – the symmetry is implied by the way promote_rule is used in the promotion process.

    The promote_rule function is used as a building block to define a second function called promote_type, which, given any number of type objects, returns the common type to which those values, as arguments to promote should be promoted. Thus, if one wants to know, in absence of actual values, what type a collection of values of certain types would promote to, one can use promote_type:

    julia> promote_type(Int8, UInt16)
    -Int64

    Internally, promote_type is used inside of promote to determine what type argument values should be converted to for promotion. It can, however, be useful in its own right. The curious reader can read the code in promotion.jl, which defines the complete promotion mechanism in about 35 lines.

    Case Study: Rational Promotions

    Finally, we finish off our ongoing case study of Julia's rational number type, which makes relatively sophisticated use of the promotion mechanism with the following promotion rules:

    promote_rule(::Type{Rational{T}}, ::Type{S}) where {T<:Integer,S<:Integer} = Rational{promote_type(T,S)}
    -promote_rule(::Type{Rational{T}}, ::Type{Rational{S}}) where {T<:Integer,S<:Integer} = Rational{promote_type(T,S)}
    -promote_rule(::Type{Rational{T}}, ::Type{S}) where {T<:Integer,S<:AbstractFloat} = promote_type(T,S)

    The first rule says that promoting a rational number with any other integer type promotes to a rational type whose numerator/denominator type is the result of promotion of its numerator/denominator type with the other integer type. The second rule applies the same logic to two different types of rational numbers, resulting in a rational of the promotion of their respective numerator/denominator types. The third and final rule dictates that promoting a rational with a float results in the same type as promoting the numerator/denominator type with the float.

    This small handful of promotion rules, together with the conversion methods discussed above, are sufficient to make rational numbers interoperate completely naturally with all of Julia's other numeric types – integers, floating-point numbers, and complex numbers. By providing appropriate conversion methods and promotion rules in the same manner, any user-defined numeric type can interoperate just as naturally with Julia's predefined numerics.

    diff --git a/julia-0.6.3/share/doc/julia/html/en/manual/dates.html b/julia-0.6.3/share/doc/julia/html/en/manual/dates.html deleted file mode 100644 index 5df142f..0000000 --- a/julia-0.6.3/share/doc/julia/html/en/manual/dates.html +++ /dev/null @@ -1,280 +0,0 @@ - -Date and DateTime · The Julia Language

    Date and DateTime

    Date and DateTime

    The Dates module provides two types for working with dates: Date and DateTime, representing day and millisecond precision, respectively; both are subtypes of the abstract TimeType. The motivation for distinct types is simple: some operations are much simpler, both in terms of code and mental reasoning, when the complexities of greater precision don't have to be dealt with. For example, since the Date type only resolves to the precision of a single date (i.e. no hours, minutes, or seconds), normal considerations for time zones, daylight savings/summer time, and leap seconds are unnecessary and avoided.

    Both Date and DateTime are basically immutable Int64 wrappers. The single instant field of either type is actually a UTInstant{P} type, which represents a continuously increasing machine timeline based on the UT second [1]. The DateTime type is not aware of time zones (naive, in Python parlance), analogous to a LocalDateTime in Java 8. Additional time zone functionality can be added through the TimeZones.jl package, which compiles the IANA time zone database. Both Date and DateTime are based on the ISO 8601 standard, which follows the proleptic Gregorian calendar. One note is that the ISO 8601 standard is particular about BC/BCE dates. In general, the last day of the BC/BCE era, 1-12-31 BC/BCE, was followed by 1-1-1 AD/CE, thus no year zero exists. The ISO standard, however, states that 1 BC/BCE is year zero, so 0000-12-31 is the day before 0001-01-01, and year -0001 (yes, negative one for the year) is 2 BC/BCE, year -0002 is 3 BC/BCE, etc.

    [1]

    The notion of the UT second is actually quite fundamental. There are basically two different notions of time generally accepted, one based on the physical rotation of the earth (one full rotation = 1 day), the other based on the SI second (a fixed, constant value). These are radically different! Think about it, a "UT second", as defined relative to the rotation of the earth, may have a different absolute length depending on the day! Anyway, the fact that Date and DateTime are based on UT seconds is a simplifying, yet honest assumption so that things like leap seconds and all their complexity can be avoided. This basis of time is formally called UT or UT1. Basing types on the UT second basically means that every minute has 60 seconds and every day has 24 hours and leads to more natural calculations when working with calendar dates.

    Constructors

    Date and DateTime types can be constructed by integer or Period types, by parsing, or through adjusters (more on those later):

    julia> DateTime(2013)
    -2013-01-01T00:00:00
    -
    -julia> DateTime(2013,7)
    -2013-07-01T00:00:00
    -
    -julia> DateTime(2013,7,1)
    -2013-07-01T00:00:00
    -
    -julia> DateTime(2013,7,1,12)
    -2013-07-01T12:00:00
    -
    -julia> DateTime(2013,7,1,12,30)
    -2013-07-01T12:30:00
    -
    -julia> DateTime(2013,7,1,12,30,59)
    -2013-07-01T12:30:59
    -
    -julia> DateTime(2013,7,1,12,30,59,1)
    -2013-07-01T12:30:59.001
    -
    -julia> Date(2013)
    -2013-01-01
    -
    -julia> Date(2013,7)
    -2013-07-01
    -
    -julia> Date(2013,7,1)
    -2013-07-01
    -
    -julia> Date(Dates.Year(2013),Dates.Month(7),Dates.Day(1))
    -2013-07-01
    -
    -julia> Date(Dates.Month(7),Dates.Year(2013))
    -2013-07-01

    Date or DateTime parsing is accomplished by the use of format strings. Format strings work by the notion of defining delimited or fixed-width "slots" that contain a period to parse and passing the text to parse and format string to a Date or DateTime constructor, of the form Date("2015-01-01","y-m-d") or DateTime("20150101","yyyymmdd").

    Delimited slots are marked by specifying the delimiter the parser should expect between two subsequent periods; so "y-m-d" lets the parser know that between the first and second slots in a date string like "2014-07-16", it should find the - character. The y, m, and d characters let the parser know which periods to parse in each slot.

    Fixed-width slots are specified by repeating the period character the number of times corresponding to the width with no delimiter between characters. So "yyyymmdd" would correspond to a date string like "20140716". The parser distinguishes a fixed-width slot by the absence of a delimiter, noting the transition "yyyymm" from one period character to the next.

    Support for text-form month parsing is also supported through the u and U characters, for abbreviated and full-length month names, respectively. By default, only English month names are supported, so u corresponds to "Jan", "Feb", "Mar", etc. And U corresponds to "January", "February", "March", etc. Similar to other name=>value mapping functions dayname() and monthname(), custom locales can be loaded by passing in the locale=>Dict{String,Int} mapping to the MONTHTOVALUEABBR and MONTHTOVALUE dicts for abbreviated and full-name month names, respectively.

    One note on parsing performance: using the Date(date_string,format_string) function is fine if only called a few times. If there are many similarly formatted date strings to parse however, it is much more efficient to first create a Dates.DateFormat, and pass it instead of a raw format string.

    julia> df = DateFormat("y-m-d");
    -
    -julia> dt = Date("2015-01-01",df)
    -2015-01-01
    -
    -julia> dt2 = Date("2015-01-02",df)
    -2015-01-02

    You can also use the dateformat"" string macro. This macro creates the DateFormat object once when the macro is expanded and uses the same DateFormat object even if a code snippet is run multiple times.

    julia> for i = 1:10^5
    -           Date("2015-01-01", dateformat"y-m-d")
    -       end

    A full suite of parsing and formatting tests and examples is available in tests/dates/io.jl.

    Durations/Comparisons

    Finding the length of time between two Date or DateTime is straightforward given their underlying representation as UTInstant{Day} and UTInstant{Millisecond}, respectively. The difference between Date is returned in the number of Day, and DateTime in the number of Millisecond. Similarly, comparing TimeType is a simple matter of comparing the underlying machine instants (which in turn compares the internal Int64 values).

    julia> dt = Date(2012,2,29)
    -2012-02-29
    -
    -julia> dt2 = Date(2000,2,1)
    -2000-02-01
    -
    -julia> dump(dt)
    -Date
    -  instant: Base.Dates.UTInstant{Base.Dates.Day}
    -    periods: Base.Dates.Day
    -      value: Int64 734562
    -
    -julia> dump(dt2)
    -Date
    -  instant: Base.Dates.UTInstant{Base.Dates.Day}
    -    periods: Base.Dates.Day
    -      value: Int64 730151
    -
    -julia> dt > dt2
    -true
    -
    -julia> dt != dt2
    -true
    -
    -julia> dt + dt2
    -ERROR: MethodError: no method matching +(::Date, ::Date)
    -[...]
    -
    -julia> dt * dt2
    -ERROR: MethodError: no method matching *(::Date, ::Date)
    -[...]
    -
    -julia> dt / dt2
    -ERROR: MethodError: no method matching /(::Date, ::Date)
    -[...]
    -
    -julia> dt - dt2
    -4411 days
    -
    -julia> dt2 - dt
    --4411 days
    -
    -julia> dt = DateTime(2012,2,29)
    -2012-02-29T00:00:00
    -
    -julia> dt2 = DateTime(2000,2,1)
    -2000-02-01T00:00:00
    -
    -julia> dt - dt2
    -381110400000 milliseconds

    Accessor Functions

    Because the Date and DateTime types are stored as single Int64 values, date parts or fields can be retrieved through accessor functions. The lowercase accessors return the field as an integer:

    julia> t = Date(2014, 1, 31)
    -2014-01-31
    -
    -julia> Dates.year(t)
    -2014
    -
    -julia> Dates.month(t)
    -1
    -
    -julia> Dates.week(t)
    -5
    -
    -julia> Dates.day(t)
    -31

    While propercase return the same value in the corresponding Period type:

    julia> Dates.Year(t)
    -2014 years
    -
    -julia> Dates.Day(t)
    -31 days

    Compound methods are provided, as they provide a measure of efficiency if multiple fields are needed at the same time:

    julia> Dates.yearmonth(t)
    -(2014, 1)
    -
    -julia> Dates.monthday(t)
    -(1, 31)
    -
    -julia> Dates.yearmonthday(t)
    -(2014, 1, 31)

    One may also access the underlying UTInstant or integer value:

    julia> dump(t)
    -Date
    -  instant: Base.Dates.UTInstant{Base.Dates.Day}
    -    periods: Base.Dates.Day
    -      value: Int64 735264
    -
    -julia> t.instant
    -Base.Dates.UTInstant{Base.Dates.Day}(735264 days)
    -
    -julia> Dates.value(t)
    -735264

    Query Functions

    Query functions provide calendrical information about a TimeType. They include information about the day of the week:

    julia> t = Date(2014, 1, 31)
    -2014-01-31
    -
    -julia> Dates.dayofweek(t)
    -5
    -
    -julia> Dates.dayname(t)
    -"Friday"
    -
    -julia> Dates.dayofweekofmonth(t) # 5th Friday of January
    -5

    Month of the year:

    julia> Dates.monthname(t)
    -"January"
    -
    -julia> Dates.daysinmonth(t)
    -31

    As well as information about the TimeType's year and quarter:

    julia> Dates.isleapyear(t)
    -false
    -
    -julia> Dates.dayofyear(t)
    -31
    -
    -julia> Dates.quarterofyear(t)
    -1
    -
    -julia> Dates.dayofquarter(t)
    -31

    The dayname() and monthname() methods can also take an optional locale keyword that can be used to return the name of the day or month of the year for other languages/locales. There are also versions of these functions returning the abbreviated names, namely dayabbr() and monthabbr(). First the mapping is loaded into the LOCALES variable:

    julia> french_months = ["janvier", "février", "mars", "avril", "mai", "juin",
    -                        "juillet", "août", "septembre", "octobre", "novembre", "décembre"];
    -
    -julia> french_monts_abbrev = ["janv","févr","mars","avril","mai","juin",
    -                              "juil","août","sept","oct","nov","déc"];
    -
    -julia> french_days = ["lundi","mardi","mercredi","jeudi","vendredi","samedi","dimanche"];
    -
    -julia> Dates.LOCALES["french"] = Dates.DateLocale(french_months, french_monts_abbrev, french_days, [""]);

    The above mentioned functions can then be used to perform the queries:

    julia> Dates.dayname(t;locale="french")
    -"vendredi"
    -
    -julia> Dates.monthname(t;locale="french")
    -"janvier"
    -
    -julia> Dates.monthabbr(t;locale="french")
    -"janv"

    Since the abbreviated versions of the days are not loaded, trying to use the function dayabbr() will error.

    julia> Dates.dayabbr(t;locale="french")
    -ERROR: BoundsError: attempt to access 1-element Array{String,1} at index [5]
    -Stacktrace:
    - [1] #dayabbr#6(::String, ::Function, ::Int64) at ./dates/query.jl:114
    - [2] (::Base.Dates.#kw##dayabbr)(::Array{Any,1}, ::Base.Dates.#dayabbr, ::Int64) at ./<missing>:0 (repeats 2 times)

    TimeType-Period Arithmetic

    It's good practice when using any language/date framework to be familiar with how date-period arithmetic is handled as there are some tricky issues to deal with (though much less so for day-precision types).

    The Dates module approach tries to follow the simple principle of trying to change as little as possible when doing Period arithmetic. This approach is also often known as calendrical arithmetic or what you would probably guess if someone were to ask you the same calculation in a conversation. Why all the fuss about this? Let's take a classic example: add 1 month to January 31st, 2014. What's the answer? Javascript will say March 3 (assumes 31 days). PHP says March 2 (assumes 30 days). The fact is, there is no right answer. In the Dates module, it gives the result of February 28th. How does it figure that out? I like to think of the classic 7-7-7 gambling game in casinos.

    Now just imagine that instead of 7-7-7, the slots are Year-Month-Day, or in our example, 2014-01-31. When you ask to add 1 month to this date, the month slot is incremented, so now we have 2014-02-31. Then the day number is checked if it is greater than the last valid day of the new month; if it is (as in the case above), the day number is adjusted down to the last valid day (28). What are the ramifications with this approach? Go ahead and add another month to our date, 2014-02-28 + Month(1) == 2014-03-28. What? Were you expecting the last day of March? Nope, sorry, remember the 7-7-7 slots. As few slots as possible are going to change, so we first increment the month slot by 1, 2014-03-28, and boom, we're done because that's a valid date. On the other hand, if we were to add 2 months to our original date, 2014-01-31, then we end up with 2014-03-31, as expected. The other ramification of this approach is a loss in associativity when a specific ordering is forced (i.e. adding things in different orders results in different outcomes). For example:

    julia> (Date(2014,1,29)+Dates.Day(1)) + Dates.Month(1)
    -2014-02-28
    -
    -julia> (Date(2014,1,29)+Dates.Month(1)) + Dates.Day(1)
    -2014-03-01

    What's going on there? In the first line, we're adding 1 day to January 29th, which results in 2014-01-30; then we add 1 month, so we get 2014-02-30, which then adjusts down to 2014-02-28. In the second example, we add 1 month first, where we get 2014-02-29, which adjusts down to 2014-02-28, and then add 1 day, which results in 2014-03-01. One design principle that helps in this case is that, in the presence of multiple Periods, the operations will be ordered by the Periods' types, not their value or positional order; this means Year will always be added first, then Month, then Week, etc. Hence the following does result in associativity and Just Works:

    julia> Date(2014,1,29) + Dates.Day(1) + Dates.Month(1)
    -2014-03-01
    -
    -julia> Date(2014,1,29) + Dates.Month(1) + Dates.Day(1)
    -2014-03-01

    Tricky? Perhaps. What is an innocent Dates user to do? The bottom line is to be aware that explicitly forcing a certain associativity, when dealing with months, may lead to some unexpected results, but otherwise, everything should work as expected. Thankfully, that's pretty much the extent of the odd cases in date-period arithmetic when dealing with time in UT (avoiding the "joys" of dealing with daylight savings, leap seconds, etc.).

    As a bonus, all period arithmetic objects work directly with ranges:

    julia> dr = Date(2014,1,29):Date(2014,2,3)
    -2014-01-29:1 day:2014-02-03
    -
    -julia> collect(dr)
    -6-element Array{Date,1}:
    - 2014-01-29
    - 2014-01-30
    - 2014-01-31
    - 2014-02-01
    - 2014-02-02
    - 2014-02-03
    -
    -julia> dr = Date(2014,1,29):Dates.Month(1):Date(2014,07,29)
    -2014-01-29:1 month:2014-07-29
    -
    -julia> collect(dr)
    -7-element Array{Date,1}:
    - 2014-01-29
    - 2014-02-28
    - 2014-03-29
    - 2014-04-29
    - 2014-05-29
    - 2014-06-29
    - 2014-07-29

    Adjuster Functions

    As convenient as date-period arithmetics are, often the kinds of calculations needed on dates take on a calendrical or temporal nature rather than a fixed number of periods. Holidays are a perfect example; most follow rules such as "Memorial Day = Last Monday of May", or "Thanksgiving = 4th Thursday of November". These kinds of temporal expressions deal with rules relative to the calendar, like first or last of the month, next Tuesday, or the first and third Wednesdays, etc.

    The Dates module provides the adjuster API through several convenient methods that aid in simply and succinctly expressing temporal rules. The first group of adjuster methods deal with the first and last of weeks, months, quarters, and years. They each take a single TimeType as input and return or adjust to the first or last of the desired period relative to the input.

    julia> Dates.firstdayofweek(Date(2014,7,16)) # Adjusts the input to the Monday of the input's week
    -2014-07-14
    -
    -julia> Dates.lastdayofmonth(Date(2014,7,16)) # Adjusts to the last day of the input's month
    -2014-07-31
    -
    -julia> Dates.lastdayofquarter(Date(2014,7,16)) # Adjusts to the last day of the input's quarter
    -2014-09-30

    The next two higher-order methods, tonext(), and toprev(), generalize working with temporal expressions by taking a DateFunction as first argument, along with a starting TimeType. A DateFunction is just a function, usually anonymous, that takes a single TimeType as input and returns a Bool, true indicating a satisfied adjustment criterion. For example:

    julia> istuesday = x->Dates.dayofweek(x) == Dates.Tuesday # Returns true if the day of the week of x is Tuesday
    -(::#1) (generic function with 1 method)
    -
    -julia> Dates.tonext(istuesday, Date(2014,7,13)) # 2014-07-13 is a Sunday
    -2014-07-15
    -
    -julia> Dates.tonext(Date(2014,7,13), Dates.Tuesday) # Convenience method provided for day of the week adjustments
    -2014-07-15

    This is useful with the do-block syntax for more complex temporal expressions:

    julia> Dates.tonext(Date(2014,7,13)) do x
    -           # Return true on the 4th Thursday of November (Thanksgiving)
    -           Dates.dayofweek(x) == Dates.Thursday &&
    -           Dates.dayofweekofmonth(x) == 4 &&
    -           Dates.month(x) == Dates.November
    -       end
    -2014-11-27

    The Base.filter() method can be used to obtain all valid dates/moments in a specified range:

    # Pittsburgh street cleaning; Every 2nd Tuesday from April to November
    -# Date range from January 1st, 2014 to January 1st, 2015
    -julia> dr = Dates.Date(2014):Dates.Date(2015);
    -
    -julia> filter(dr) do x
    -           Dates.dayofweek(x) == Dates.Tue &&
    -           Dates.April <= Dates.month(x) <= Dates.Nov &&
    -           Dates.dayofweekofmonth(x) == 2
    -       end
    -8-element Array{Date,1}:
    - 2014-04-08
    - 2014-05-13
    - 2014-06-10
    - 2014-07-08
    - 2014-08-12
    - 2014-09-09
    - 2014-10-14
    - 2014-11-11

    Additional examples and tests are available in test/dates/adjusters.jl.

    Period Types

    Periods are a human view of discrete, sometimes irregular durations of time. Consider 1 month; it could represent, in days, a value of 28, 29, 30, or 31 depending on the year and month context. Or a year could represent 365 or 366 days in the case of a leap year. Period types are simple Int64 wrappers and are constructed by wrapping any Int64 convertible type, i.e. Year(1) or Month(3.0). Arithmetic between Period of the same type behave like integers, and limited Period-Real arithmetic is available.

    julia> y1 = Dates.Year(1)
    -1 year
    -
    -julia> y2 = Dates.Year(2)
    -2 years
    -
    -julia> y3 = Dates.Year(10)
    -10 years
    -
    -julia> y1 + y2
    -3 years
    -
    -julia> div(y3,y2)
    -5
    -
    -julia> y3 - y2
    -8 years
    -
    -julia> y3 % y2
    -0 years
    -
    -julia> div(y3,3) # mirrors integer division
    -3 years

    Rounding

    Date and DateTime values can be rounded to a specified resolution (e.g., 1 month or 15 minutes) with floor(), ceil(), or round():

    julia> floor(Date(1985, 8, 16), Dates.Month)
    -1985-08-01
    -
    -julia> ceil(DateTime(2013, 2, 13, 0, 31, 20), Dates.Minute(15))
    -2013-02-13T00:45:00
    -
    -julia> round(DateTime(2016, 8, 6, 20, 15), Dates.Day)
    -2016-08-07T00:00:00

    Unlike the numeric round() method, which breaks ties toward the even number by default, the TimeTyperound() method uses the RoundNearestTiesUp rounding mode. (It's difficult to guess what breaking ties to nearest "even" TimeType would entail.) Further details on the available RoundingMode s can be found in the API reference.

    Rounding should generally behave as expected, but there are a few cases in which the expected behaviour is not obvious.

    Rounding Epoch

    In many cases, the resolution specified for rounding (e.g., Dates.Second(30)) divides evenly into the next largest period (in this case, Dates.Minute(1)). But rounding behaviour in cases in which this is not true may lead to confusion. What is the expected result of rounding a DateTime to the nearest 10 hours?

    julia> round(DateTime(2016, 7, 17, 11, 55), Dates.Hour(10))
    -2016-07-17T12:00:00

    That may seem confusing, given that the hour (12) is not divisible by 10. The reason that 2016-07-17T12:00:00 was chosen is that it is 17,676,660 hours after 0000-01-01T00:00:00, and 17,676,660 is divisible by 10.

    As Julia Date and DateTime values are represented according to the ISO 8601 standard, 0000-01-01T00:00:00 was chosen as base (or "rounding epoch") from which to begin the count of days (and milliseconds) used in rounding calculations. (Note that this differs slightly from Julia's internal representation of Date s using Rata Die notation; but since the ISO 8601 standard is most visible to the end user, 0000-01-01T00:00:00 was chosen as the rounding epoch instead of the 0000-12-31T00:00:00 used internally to minimize confusion.)

    The only exception to the use of 0000-01-01T00:00:00 as the rounding epoch is when rounding to weeks. Rounding to the nearest week will always return a Monday (the first day of the week as specified by ISO 8601). For this reason, we use 0000-01-03T00:00:00 (the first day of the first week of year 0000, as defined by ISO 8601) as the base when rounding to a number of weeks.

    Here is a related case in which the expected behaviour is not necessarily obvious: What happens when we round to the nearest P(2), where P is a Period type? In some cases (specifically, when P <: Dates.TimePeriod) the answer is clear:

    julia> round(DateTime(2016, 7, 17, 8, 55, 30), Dates.Hour(2))
    -2016-07-17T08:00:00
    -
    -julia> round(DateTime(2016, 7, 17, 8, 55, 30), Dates.Minute(2))
    -2016-07-17T08:56:00

    This seems obvious, because two of each of these periods still divides evenly into the next larger order period. But in the case of two months (which still divides evenly into one year), the answer may be surprising:

    julia> round(DateTime(2016, 7, 17, 8, 55, 30), Dates.Month(2))
    -2016-07-01T00:00:00

    Why round to the first day in July, even though it is month 7 (an odd number)? The key is that months are 1-indexed (the first month is assigned 1), unlike hours, minutes, seconds, and milliseconds (the first of which are assigned 0).

    This means that rounding a DateTime to an even multiple of seconds, minutes, hours, or years (because the ISO 8601 specification includes a year zero) will result in a DateTime with an even value in that field, while rounding a DateTime to an even multiple of months will result in the months field having an odd value. Because both months and years may contain an irregular number of days, whether rounding to an even number of days will result in an even value in the days field is uncertain.

    See the API reference for additional information on methods exported from the Dates module.

    diff --git a/julia-0.6.3/share/doc/julia/html/en/manual/documentation.html b/julia-0.6.3/share/doc/julia/html/en/manual/documentation.html deleted file mode 100644 index e106c35..0000000 --- a/julia-0.6.3/share/doc/julia/html/en/manual/documentation.html +++ /dev/null @@ -1,274 +0,0 @@ - -Documentation · The Julia Language

    Documentation

    Documentation

    Julia enables package developers and users to document functions, types and other objects easily via a built-in documentation system since Julia 0.4.

    The basic syntax is very simple: any string appearing at the top-level right before an object (function, macro, type or instance) will be interpreted as documenting it (these are called docstrings). Here is a very simple example:

    "Tell whether there are too foo items in the array."
    -foo(xs::Array) = ...

    Documentation is interpreted as Markdown, so you can use indentation and code fences to delimit code examples from text. Technically, any object can be associated with any other as metadata; Markdown happens to be the default, but one can construct other string macros and pass them to the @doc macro just as well.

    Here is a more complex example, still using Markdown:

    """
    -    bar(x[, y])
    -
    -Compute the Bar index between `x` and `y`. If `y` is missing, compute
    -the Bar index between all pairs of columns of `x`.
    -
    -# Examples
    -```julia-repl
    -julia> bar([1, 2], [1, 2])
    -1
    -```
    -"""
    -function bar(x, y) ...

    As in the example above, we recommend following some simple conventions when writing documentation:

    1. Always show the signature of a function at the top of the documentation, with a four-space indent so that it is printed as Julia code.

      This can be identical to the signature present in the Julia code (like mean(x::AbstractArray)), or a simplified form. Optional arguments should be represented with their default values (i.e. f(x, y=1)) when possible, following the actual Julia syntax. Optional arguments which do not have a default value should be put in brackets (i.e. f(x[, y]) and f(x[, y[, z]])). An alternative solution is to use several lines: one without optional arguments, the other(s) with them. This solution can also be used to document several related methods of a given function. When a function accepts many keyword arguments, only include a <keyword arguments> placeholder in the signature (i.e. f(x; <keyword arguments>)), and give the complete list under an # Arguments section (see point 4 below).

    2. Include a single one-line sentence describing what the function does or what the object represents after the simplified signature block. If needed, provide more details in a second paragraph, after a blank line.

      The one-line sentence should use the imperative form ("Do this", "Return that") instead of the third person (do not write "Returns the length...") when documenting functions. It should end with a period. If the meaning of a function cannot be summarized easily, splitting it into separate composable parts could be beneficial (this should not be taken as an absolute requirement for every single case though).

    3. Do not repeat yourself.

      Since the function name is given by the signature, there is no need to start the documentation with "The function bar...": go straight to the point. Similarly, if the signature specifies the types of the arguments, mentioning them in the description is redundant.

    4. Only provide an argument list when really necessary.

      For simple functions, it is often clearer to mention the role of the arguments directly in the description of the function's purpose. An argument list would only repeat information already provided elsewhere. However, providing an argument list can be a good idea for complex functions with many arguments (in particular keyword arguments). In that case, insert it after the general description of the function, under an # Arguments header, with one - bullet for each argument. The list should mention the types and default values (if any) of the arguments:

      """
      -...
      -# Arguments
      -- `n::Integer`: the number of elements to compute.
      -- `dim::Integer=1`: the dimensions along which to perform the computation.
      -...
      -"""
    5. Include any code examples in an # Examples section.

      Examples should, whenever possible, be written as doctests. A doctest is a fenced code block (see Code blocks) starting with ```jldoctest and contains any number of julia> prompts together with inputs and expected outputs that mimic the Julia REPL.

      For example in the following docstring a variable a is defined and the expected result, as printed in a Julia REPL, appears afterwards:

      """
      -Some nice documentation here.
      -
      -# Examples
      -
      -```jldoctest
      -julia> a = [1 2; 3 4]
      -2×2 Array{Int64,2}:
      - 1  2
      - 3  4
      -```
      -"""
      Warning

      Calling rand and other RNG-related functions should be avoided in doctests since they will not produce consistent outputs during different Julia sessions.

      Operating system word size (Int32 or Int64) as well as path separator differences (/ or \) will also affect the reproducibility of some doctests.

      Note that whitespace in your doctest is significant! The doctest will fail if you misalign the output of pretty-printing an array, for example.

      You can then run make -C doc doctest to run all the doctests in the Julia Manual, which will ensure that your example works.

      Examples that are untestable should be written within fenced code blocks starting with ```julia so that they are highlighted correctly in the generated documentation.

      Tip

      Wherever possible examples should be self-contained and runnable so that readers are able to try them out without having to include any dependencies.

    6. Use backticks to identify code and equations.

      Julia identifiers and code excerpts should always appear between backticks ` to enable highlighting. Equations in the LaTeX syntax can be inserted between double backticks ``. Use Unicode characters rather than their LaTeX escape sequence, i.e. ``α = 1`` rather than ``\\alpha = 1``.

    7. Place the starting and ending """ characters on lines by themselves.

      That is, write:

      """
      -...
      -
      -...
      -"""
      -f(x, y) = ...

      rather than:

      """...
      -
      -..."""
      -f(x, y) = ...

      This makes it more clear where docstrings start and end.

    8. Respect the line length limit used in the surrounding code.

      Docstrings are edited using the same tools as code. Therefore, the same conventions should apply. It it advised to add line breaks after 92 characters.

    Accessing Documentation

    Documentation can be accessed at the REPL or in IJulia by typing ? followed by the name of a function or macro, and pressing Enter. For example,

    ?fft
    -?@time
    -?r""

    will bring up docs for the relevant function, macro or string macro respectively. In Juno using Ctrl-J, Ctrl-D will bring up documentation for the object under the cursor.

    Functions & Methods

    Functions in Julia may have multiple implementations, known as methods. While it's good practice for generic functions to have a single purpose, Julia allows methods to be documented individually if necessary. In general, only the most generic method should be documented, or even the function itself (i.e. the object created without any methods by function bar end). Specific methods should only be documented if their behaviour differs from the more generic ones. In any case, they should not repeat the information provided elsewhere. For example:

    """
    -    *(x, y, z...)
    -
    -Multiplication operator. `x * y * z *...` calls this function with multiple
    -arguments, i.e. `*(x, y, z...)`.
    -"""
    -function *(x, y, z...)
    -    # ... [implementation sold separately] ...
    -end
    -
    -"""
    -    *(x::AbstractString, y::AbstractString, z::AbstractString...)
    -
    -When applied to strings, concatenates them.
    -"""
    -function *(x::AbstractString, y::AbstractString, z::AbstractString...)
    -    # ... [insert secret sauce here] ...
    -end
    -
    -help?> *
    -search: * .*
    -
    -  *(x, y, z...)
    -
    -  Multiplication operator. x * y * z *... calls this function with multiple
    -  arguments, i.e. *(x,y,z...).
    -
    -  *(x::AbstractString, y::AbstractString, z::AbstractString...)
    -
    -  When applied to strings, concatenates them.

    When retrieving documentation for a generic function, the metadata for each method is concatenated with the catdoc function, which can of course be overridden for custom types.

    Advanced Usage

    The @doc macro associates its first argument with its second in a per-module dictionary called META. By default, documentation is expected to be written in Markdown, and the doc"" string macro simply creates an object representing the Markdown content. In the future it is likely to do more advanced things such as allowing for relative image or link paths.

    When used for retrieving documentation, the @doc macro (or equally, the doc function) will search all META dictionaries for metadata relevant to the given object and return it. The returned object (some Markdown content, for example) will by default display itself intelligently. This design also makes it easy to use the doc system in a programmatic way; for example, to re-use documentation between different versions of a function:

    @doc "..." foo!
    -@doc (@doc foo!) foo

    Or for use with Julia's metaprogramming functionality:

    for (f, op) in ((:add, :+), (:subtract, :-), (:multiply, :*), (:divide, :/))
    -    @eval begin
    -        $f(a,b) = $op(a,b)
    -    end
    -end
    -@doc "`add(a,b)` adds `a` and `b` together" add
    -@doc "`subtract(a,b)` subtracts `b` from `a`" subtract

    Documentation written in non-toplevel blocks, such as begin, if, for, and let, is added to the documentation system as blocks are evaluated. For example:

    if VERSION > v"0.5"
    -    "..."
    -    f(x) = x
    -end

    will add documentation to f(x) when the condition is true. Note that even if f(x) goes out of scope at the end of the block, its documentation will remain.

    Dynamic documentation

    Sometimes the appropriate documentation for an instance of a type depends on the field values of that instance, rather than just on the type itself. In these cases, you can add a method to Docs.getdoc for your custom type that returns the documentation on a per-instance basis. For instance,

    struct MyType
    -    value::String
    -end
    -
    -Docs.getdoc(t::MyType) = "Documentation for MyType with value $(t.value)"
    -
    -x = MyType("x")
    -y = MyType("y")

    ?x will display "Documentation for MyType with value x" while ?y will display "Documentation for MyType with value y".

    Syntax Guide

    A comprehensive overview of all documentable Julia syntax.

    In the following examples "..." is used to illustrate an arbitrary docstring which may be one of the follow four variants and contain arbitrary text:

    "..."
    -
    -doc"..."
    -
    -"""
    -...
    -"""
    -
    -doc"""
    -...
    -"""

    @doc_str should only be used when the docstring contains $ or \ characters that should not be parsed by Julia such as LaTeX syntax or Julia source code examples containing interpolation.

    Functions and Methods

    "..."
    -function f end
    -
    -"..."
    -f

    Adds docstring "..." to Functionf. The first version is the preferred syntax, however both are equivalent.

    "..."
    -f(x) = x
    -
    -"..."
    -function f(x)
    -    x
    -end
    -
    -"..."
    -f(x)

    Adds docstring "..." to Methodf(::Any).

    "..."
    -f(x, y = 1) = x + y

    Adds docstring "..." to two Methods, namely f(::Any) and f(::Any, ::Any).

    Macros

    "..."
    -macro m(x) end

    Adds docstring "..." to the @m(::Any) macro definition.

    "..."
    -:(@m)

    Adds docstring "..." to the macro named @m.

    Types

    "..."
    -abstract type T1 end
    -
    -"..."
    -mutable struct T2
    -    ...
    -end
    -
    -"..."
    -struct T3
    -    ...
    -end

    Adds the docstring "..." to types T1, T2, and T3.

    "..."
    -struct T
    -    "x"
    -    x
    -    "y"
    -    y
    -end

    Adds docstring "..." to type T, "x" to field T.x and "y" to field T.y. Also applicable to mutable struct types.

    Modules

    "..."
    -module M end
    -
    -module M
    -
    -"..."
    -M
    -
    -end

    Adds docstring "..." to the ModuleM. Adding the docstring above the Module is the preferred syntax, however both are equivalent.

    "..."
    -baremodule M
    -# ...
    -end
    -
    -baremodule M
    -
    -import Base: @doc
    -
    -"..."
    -f(x) = x
    -
    -end

    Documenting a baremodule by placing a docstring above the expression automatically imports @doc into the module. These imports must be done manually when the module expression is not documented. Empty baremodules cannot be documented.

    Global Variables

    "..."
    -const a = 1
    -
    -"..."
    -b = 2
    -
    -"..."
    -global c = 3

    Adds docstring "..." to the Bindings a, b, and c.

    Bindings are used to store a reference to a particular Symbol in a Module without storing the referenced value itself.

    Note

    When a const definition is only used to define an alias of another definition, such as is the case with the function div and its alias ÷ in Base, do not document the alias and instead document the actual function.

    If the alias is documented and not the real definition then the docsystem (? mode) will not return the docstring attached to the alias when the real definition is searched for.

    For example you should write

    "..."
    -f(x) = x + 1
    -const alias = f

    rather than

    f(x) = x + 1
    -"..."
    -const alias = f
    "..."
    -sym

    Adds docstring "..." to the value associated with sym. Users should prefer documenting sym at it's definition.

    Multiple Objects

    "..."
    -a, b

    Adds docstring "..." to a and b each of which should be a documentable expression. This syntax is equivalent to

    "..."
    -a
    -
    -"..."
    -b

    Any number of expressions many be documented together in this way. This syntax can be useful when two functions are related, such as non-mutating and mutating versions f and f!.

    Macro-generated code

    "..."
    -@m expression

    Adds docstring "..." to expression generated by expanding @m expression. This allows for expressions decorated with @inline, @noinline, @generated, or any other macro to be documented in the same way as undecorated expressions.

    Macro authors should take note that only macros that generate a single expression will automatically support docstrings. If a macro returns a block containing multiple subexpressions then the subexpression that should be documented must be marked using the @__doc__ macro.

    The @enum macro makes use of @__doc__ to allow for documenting Enums. Examining it's definition should serve as an example of how to use @__doc__ correctly.

    Core.@__doc__Macro.
    @__doc__(ex)

    Low-level macro used to mark expressions returned by a macro that should be documented. If more than one expression is marked then the same docstring is applied to each expression.

    macro example(f)
    -    quote
    -        $(f)() = 0
    -        @__doc__ $(f)(x) = 1
    -        $(f)(x, y) = 2
    -    end |> esc
    -end

    @__doc__ has no effect when a macro that uses it is not documented.

    source

    Markdown syntax

    The following markdown syntax is supported in Julia.

    Inline elements

    Here "inline" refers to elements that can be found within blocks of text, i.e. paragraphs. These include the following elements.

    Bold

    Surround words with two asterisks, **, to display the enclosed text in boldface.

    A paragraph containing a **bold** word.

    Italics

    Surround words with one asterisk, *, to display the enclosed text in italics.

    A paragraph containing an *emphasised* word.

    Literals

    Surround text that should be displayed exactly as written with single backticks, ` .

    A paragraph containing a `literal` word.

    Literals should be used when writing text that refers to names of variables, functions, or other parts of a Julia program.

    Tip

    To include a backtick character within literal text use three backticks rather than one to enclose the text.

    A paragraph containing a ``` `backtick` character ```.

    By extension any odd number of backticks may be used to enclose a lesser number of backticks.

    $\LaTeX$

    Surround text that should be displayed as mathematics using $\LaTeX$ syntax with double backticks, `` .

    A paragraph containing some ``\LaTeX`` markup.
    Tip

    As with literals in the previous section, if literal backticks need to be written within double backticks use an even number greater than two. Note that if a single literal backtick needs to be included within $\LaTeX$ markup then two enclosing backticks is sufficient.

    Links

    Links to either external or internal addresses can be written using the following syntax, where the text enclosed in square brackets, [ ], is the name of the link and the text enclosed in parentheses, ( ), is the URL.

    A paragraph containing a link to [Julia](http://www.julialang.org).

    It's also possible to add cross-references to other documented functions/methods/variables within the Julia documentation itself. For example:

    """
    -    eigvals!(A,[irange,][vl,][vu]) -> values
    -
    -Same as [`eigvals`](@ref), but saves space by overwriting the input `A`, instead of creating a copy.
    -"""

    This will create a link in the generated docs to the eigvals documentation (which has more information about what this function actually does). It's good to include cross references to mutating/non-mutating versions of a function, or to highlight a difference between two similar-seeming functions.

    Note

    The above cross referencing is not a Markdown feature, and relies on Documenter.jl, which is used to build base Julia's documentation.

    Footnote references

    Named and numbered footnote references can be written using the following syntax. A footnote name must be a single alphanumeric word containing no punctuation.

    A paragraph containing a numbered footnote [^1] and a named one [^named].
    Note

    The text associated with a footnote can be written anywhere within the same page as the footnote reference. The syntax used to define the footnote text is discussed in the Footnotes section below.

    Toplevel elements

    The following elements can be written either at the "toplevel" of a document or within another "toplevel" element.

    Paragraphs

    A paragraph is a block of plain text, possibly containing any number of inline elements defined in the Inline elements section above, with one or more blank lines above and below it.

    This is a paragraph.
    -
    -And this is *another* one containing some emphasised text.
    -A new line, but still part of the same paragraph.

    Headers

    A document can be split up into different sections using headers. Headers use the following syntax:

    # Level One
    -## Level Two
    -### Level Three
    -#### Level Four
    -##### Level Five
    -###### Level Six

    A header line can contain any inline syntax in the same way as a paragraph can.

    Tip

    Try to avoid using too many levels of header within a single document. A heavily nested document may be indicative of a need to restructure it or split it into several pages covering separate topics.

    Code blocks

    Source code can be displayed as a literal block using an indent of four spaces as shown in the following example.

    This is a paragraph.
    -
    -    function func(x)
    -        # ...
    -    end
    -
    -Another paragraph.

    Additionally, code blocks can be enclosed using triple backticks with an optional "language" to specify how a block of code should be highlighted.

    A code block without a "language":
    -
    -```
    -function func(x)
    -    # ...
    -end
    -```
    -
    -and another one with the "language" specified as `julia`:
    -
    -```julia
    -function func(x)
    -    # ...
    -end
    -```
    Note

    "Fenced" code blocks, as shown in the last example, should be prefered over indented code blocks since there is no way to specify what language an indented code block is written in.

    Block quotes

    Text from external sources, such as quotations from books or websites, can be quoted using > characters prepended to each line of the quote as follows.

    Here's a quote:
    -
    -> Julia is a high-level, high-performance dynamic programming language for
    -> technical computing, with syntax that is familiar to users of other
    -> technical computing environments.

    Note that a single space must appear after the > character on each line. Quoted blocks may themselves contain other toplevel or inline elements.

    Images

    The syntax for images is similar to the link syntax mentioned above. Prepending a ! character to a link will display an image from the specified URL rather than a link to it.

    ![alternative text](link/to/image.png)

    Lists

    Unordered lists can be written by prepending each item in a list with either *, +, or -.

    A list of items:
    -
    -  * item one
    -  * item two
    -  * item three

    Note the two spaces before each * and the single space after each one.

    Lists can contain other nested toplevel elements such as lists, code blocks, or quoteblocks. A blank line should be left between each list item when including any toplevel elements within a list.

    Another list:
    -
    -  * item one
    -
    -  * item two
    -
    -    ```
    -    f(x) = x
    -    ```
    -
    -  * And a sublist:
    -
    -      + sub-item one
    -      + sub-item two
    Note

    The contents of each item in the list must line up with the first line of the item. In the above example the fenced code block must be indented by four spaces to align with the i in item two.

    Ordered lists are written by replacing the "bullet" character, either *, +, or -, with a positive integer followed by either . or ).

    Two ordered lists:
    -
    - 1. item one
    - 2. item two
    - 3. item three
    -
    - 5) item five
    - 6) item six
    - 7) item seven

    An ordered list may start from a number other than one, as in the second list of the above example, where it is numbered from five. As with unordered lists, ordered lists can contain nested toplevel elements.

    Display equations

    Large $\LaTeX$ equations that do not fit inline within a paragraph may be written as display equations using a fenced code block with the "language" math as in the example below.

    ```math
    -f(a) = \frac{1}{2\pi}\int_{0}^{2\pi} (\alpha+R\cos(\theta))d\theta
    -```

    Footnotes

    This syntax is paired with the inline syntax for Footnote references. Make sure to read that section as well.

    Footnote text is defined using the following syntax, which is similar to footnote reference syntax, aside from the : character that is appended to the footnote label.

    [^1]: Numbered footnote text.
    -
    -[^note]:
    -
    -    Named footnote text containing several toplevel elements.
    -
    -      * item one
    -      * item two
    -      * item three
    -
    -    ```julia
    -    function func(x)
    -        # ...
    -    end
    -    ```
    Note

    No checks are done during parsing to make sure that all footnote references have matching footnotes.

    Horizontal rules

    The equivalent of an <hr> HTML tag can be written using the following syntax:

    Text above the line.
    -
    ----
    -
    -And text below the line.

    Tables

    Basic tables can be written using the syntax described below. Note that markdown tables have limited features and cannot contain nested toplevel elements unlike other elements discussed above – only inline elements are allowed. Tables must always contain a header row with column names. Cells cannot span multiple rows or columns of the table.

    | Column One | Column Two | Column Three |
    -|:---------- | ---------- |:------------:|
    -| Row `1`    | Column `2` |              |
    -| *Row* 2    | **Row** 2  | Column ``3`` |
    Note

    As illustrated in the above example each column of | characters must be aligned vertically.

    A : character on either end of a column's header separator (the row containing - characters) specifies whether the row is left-aligned, right-aligned, or (when : appears on both ends) center-aligned. Providing no : characters will default to right-aligning the column.

    Admonitions

    Specially formatted blocks with titles such as "Notes", "Warning", or "Tips" are known as admonitions and are used when some part of a document needs special attention. They can be defined using the following !!! syntax:

    !!! note
    -
    -    This is the content of the note.
    -
    -!!! warning "Beware!"
    -
    -    And this is another one.
    -
    -    This warning admonition has a custom title: `"Beware!"`.

    Admonitions, like most other toplevel elements, can contain other toplevel elements. When no title text, specified after the admonition type in double quotes, is included then the title used will be the type of the block, i.e. "Note" in the case of the note admonition.

    Markdown Syntax Extensions

    Julia's markdown supports interpolation in a very similar way to basic string literals, with the difference that it will store the object itself in the Markdown tree (as opposed to converting it to a string). When the Markdown content is rendered the usual show methods will be called, and these can be overridden as usual. This design allows the Markdown to be extended with arbitrarily complex features (such as references) without cluttering the basic syntax.

    In principle, the Markdown parser itself can also be arbitrarily extended by packages, or an entirely custom flavour of Markdown can be used, but this should generally be unnecessary.

    diff --git a/julia-0.6.3/share/doc/julia/html/en/manual/embedding.html b/julia-0.6.3/share/doc/julia/html/en/manual/embedding.html deleted file mode 100644 index e682311..0000000 --- a/julia-0.6.3/share/doc/julia/html/en/manual/embedding.html +++ /dev/null @@ -1,94 +0,0 @@ - -Embedding Julia · The Julia Language

    Embedding Julia

    Embedding Julia

    As we have seen in Calling C and Fortran Code, Julia has a simple and efficient way to call functions written in C. But there are situations where the opposite is needed: calling Julia function from C code. This can be used to integrate Julia code into a larger C/C++ project, without the need to rewrite everything in C/C++. Julia has a C API to make this possible. As almost all programming languages have some way to call C functions, the Julia C API can also be used to build further language bridges (e.g. calling Julia from Python or C#).

    High-Level Embedding

    We start with a simple C program that initializes Julia and calls some Julia code:

    #include <julia.h>
    -
    -int main(int argc, char *argv[])
    -{
    -    /* required: setup the Julia context */
    -    jl_init();
    -
    -    /* run Julia commands */
    -    jl_eval_string("print(sqrt(2.0))");
    -
    -    /* strongly recommended: notify Julia that the
    -         program is about to terminate. this allows
    -         Julia time to cleanup pending write requests
    -         and run all finalizers
    -    */
    -    jl_atexit_hook(0);
    -    return 0;
    -}

    In order to build this program you have to put the path to the Julia header into the include path and link against libjulia. For instance, when Julia is installed to $JULIA_DIR, one can compile the above test program test.c with gcc using:

    gcc -o test -fPIC -I$JULIA_DIR/include/julia -L$JULIA_DIR/lib test.c -ljulia $JULIA_DIR/lib/julia/libstdc++.so.6

    Then if the environment variable JULIA_HOME is set to $JULIA_DIR/bin, the output test program can be executed.

    Alternatively, look at the embedding.c program in the Julia source tree in the examples/ folder. The file ui/repl.c program is another simple example of how to set jl_options options while linking against libjulia.

    The first thing that has to be done before calling any other Julia C function is to initialize Julia. This is done by calling jl_init, which tries to automatically determine Julia's install location. If you need to specify a custom location, or specify which system image to load, use jl_init_with_image instead.

    The second statement in the test program evaluates a Julia statement using a call to jl_eval_string.

    Before the program terminates, it is strongly recommended to call jl_atexit_hook. The above example program calls this before returning from main.

    Note

    Currently, dynamically linking with the libjulia shared library requires passing the RTLD_GLOBAL option. In Python, this looks like:

    >>> julia=CDLL('./libjulia.dylib',RTLD_GLOBAL)
    ->>> julia.jl_init.argtypes = []
    ->>> julia.jl_init()
    -250593296
    Note

    If the julia program needs to access symbols from the main executable, it may be necessary to add -Wl,--export-dynamic linker flag at compile time on Linux in addition to the ones generated by julia-config.jl described below. This is not necessary when compiling a shared library.

    Using julia-config to automatically determine build parameters

    The script julia-config.jl was created to aid in determining what build parameters are required by a program that uses embedded Julia. This script uses the build parameters and system configuration of the particular Julia distribution it is invoked by to export the necessary compiler flags for an embedding program to interact with that distribution. This script is located in the Julia shared data directory.

    Example

    #include <julia.h>
    -
    -int main(int argc, char *argv[])
    -{
    -    jl_init();
    -    (void)jl_eval_string("println(sqrt(2.0))");
    -    jl_atexit_hook(0);
    -    return 0;
    -}

    On the command line

    A simple use of this script is from the command line. Assuming that julia-config.jl is located in /usr/local/julia/share/julia, it can be invoked on the command line directly and takes any combination of 3 flags:

    /usr/local/julia/share/julia/julia-config.jl
    -Usage: julia-config [--cflags|--ldflags|--ldlibs]

    If the above example source is saved in the file embed_example.c, then the following command will compile it into a running program on Linux and Windows (MSYS2 environment), or if on OS/X, then substitute clang for gcc.:

    /usr/local/julia/share/julia/julia-config.jl --cflags --ldflags --ldlibs | xargs gcc embed_example.c

    Use in Makefiles

    But in general, embedding projects will be more complicated than the above, and so the following allows general makefile support as well – assuming GNU make because of the use of the shell macro expansions. Additionally, though many times julia-config.jl may be found in the directory /usr/local, this is not necessarily the case, but Julia can be used to locate julia-config.jl too, and the makefile can be used to take advantage of that. The above example is extended to use a Makefile:

    JL_SHARE = $(shell julia -e 'print(joinpath(JULIA_HOME,Base.DATAROOTDIR,"julia"))')
    -CFLAGS   += $(shell $(JL_SHARE)/julia-config.jl --cflags)
    -CXXFLAGS += $(shell $(JL_SHARE)/julia-config.jl --cflags)
    -LDFLAGS  += $(shell $(JL_SHARE)/julia-config.jl --ldflags)
    -LDLIBS   += $(shell $(JL_SHARE)/julia-config.jl --ldlibs)
    -
    -all: embed_example

    Now the build command is simply make.

    Converting Types

    Real applications will not just need to execute expressions, but also return their values to the host program. jl_eval_string returns a jl_value_t*, which is a pointer to a heap-allocated Julia object. Storing simple data types like Float64 in this way is called boxing, and extracting the stored primitive data is called unboxing. Our improved sample program that calculates the square root of 2 in Julia and reads back the result in C looks as follows:

    jl_value_t *ret = jl_eval_string("sqrt(2.0)");
    -
    -if (jl_typeis(ret, jl_float64_type)) {
    -    double ret_unboxed = jl_unbox_float64(ret);
    -    printf("sqrt(2.0) in C: %e \n", ret_unboxed);
    -}
    -else {
    -    printf("ERROR: unexpected return type from sqrt(::Float64)\n");
    -}

    In order to check whether ret is of a specific Julia type, we can use the jl_isa, jl_typeis, or jl_is_... functions. By typing typeof(sqrt(2.0)) into the Julia shell we can see that the return type is Float64 (double in C). To convert the boxed Julia value into a C double the jl_unbox_float64 function is used in the above code snippet.

    Corresponding jl_box_... functions are used to convert the other way:

    jl_value_t *a = jl_box_float64(3.0);
    -jl_value_t *b = jl_box_float32(3.0f);
    -jl_value_t *c = jl_box_int32(3);

    As we will see next, boxing is required to call Julia functions with specific arguments.

    Calling Julia Functions

    While jl_eval_string allows C to obtain the result of a Julia expression, it does not allow passing arguments computed in C to Julia. For this you will need to invoke Julia functions directly, using jl_call:

    jl_function_t *func = jl_get_function(jl_base_module, "sqrt");
    -jl_value_t *argument = jl_box_float64(2.0);
    -jl_value_t *ret = jl_call1(func, argument);

    In the first step, a handle to the Julia function sqrt is retrieved by calling jl_get_function. The first argument passed to jl_get_function is a pointer to the Base module in which sqrt is defined. Then, the double value is boxed using jl_box_float64. Finally, in the last step, the function is called using jl_call1. jl_call0, jl_call2, and jl_call3 functions also exist, to conveniently handle different numbers of arguments. To pass more arguments, use jl_call:

    jl_value_t *jl_call(jl_function_t *f, jl_value_t **args, int32_t nargs)

    Its second argument args is an array of jl_value_t* arguments and nargs is the number of arguments.

    Memory Management

    As we have seen, Julia objects are represented in C as pointers. This raises the question of who is responsible for freeing these objects.

    Typically, Julia objects are freed by a garbage collector (GC), but the GC does not automatically know that we are holding a reference to a Julia value from C. This means the GC can free objects out from under you, rendering pointers invalid.

    The GC can only run when Julia objects are allocated. Calls like jl_box_float64 perform allocation, and allocation might also happen at any point in running Julia code. However, it is generally safe to use pointers in between jl_... calls. But in order to make sure that values can survive jl_... calls, we have to tell Julia that we hold a reference to a Julia value. This can be done using the JL_GC_PUSH macros:

    jl_value_t *ret = jl_eval_string("sqrt(2.0)");
    -JL_GC_PUSH1(&ret);
    -// Do something with ret
    -JL_GC_POP();

    The JL_GC_POP call releases the references established by the previous JL_GC_PUSH. Note that JL_GC_PUSH is working on the stack, so it must be exactly paired with a JL_GC_POP before the stack frame is destroyed.

    Several Julia values can be pushed at once using the JL_GC_PUSH2 , JL_GC_PUSH3 , and JL_GC_PUSH4 macros. To push an array of Julia values one can use the JL_GC_PUSHARGS macro, which can be used as follows:

    jl_value_t **args;
    -JL_GC_PUSHARGS(args, 2); // args can now hold 2 `jl_value_t*` objects
    -args[0] = some_value;
    -args[1] = some_other_value;
    -// Do something with args (e.g. call jl_... functions)
    -JL_GC_POP();

    The garbage collector also operates under the assumption that it is aware of every old-generation object pointing to a young-generation one. Any time a pointer is updated breaking that assumption, it must be signaled to the collector with the jl_gc_wb (write barrier) function like so:

    jl_value_t *parent = some_old_value, *child = some_young_value;
    -((some_specific_type*)parent)->field = child;
    -jl_gc_wb(parent, child);

    It is in general impossible to predict which values will be old at runtime, so the write barrier must be inserted after all explicit stores. One notable exception is if the parent object was just allocated and garbage collection was not run since then. Remember that most jl_... functions can sometimes invoke garbage collection.

    The write barrier is also necessary for arrays of pointers when updating their data directly. For example:

    jl_array_t *some_array = ...; // e.g. a Vector{Any}
    -void **data = (void**)jl_array_data(some_array);
    -jl_value_t *some_value = ...;
    -data[0] = some_value;
    -jl_gc_wb(some_array, some_value);

    Manipulating the Garbage Collector

    There are some functions to control the GC. In normal use cases, these should not be necessary.

    FunctionDescription
    jl_gc_collect()Force a GC run
    jl_gc_enable(0)Disable the GC, return previous state as int
    jl_gc_enable(1)Enable the GC, return previous state as int
    jl_gc_is_enabled()Return current state as int

    Working with Arrays

    Julia and C can share array data without copying. The next example will show how this works.

    Julia arrays are represented in C by the datatype jl_array_t*. Basically, jl_array_t is a struct that contains:

    • Information about the datatype

    • A pointer to the data block

    • Information about the sizes of the array

    To keep things simple, we start with a 1D array. Creating an array containing Float64 elements of length 10 is done by:

    jl_value_t* array_type = jl_apply_array_type(jl_float64_type, 1);
    -jl_array_t* x          = jl_alloc_array_1d(array_type, 10);

    Alternatively, if you have already allocated the array you can generate a thin wrapper around its data:

    double *existingArray = (double*)malloc(sizeof(double)*10);
    -jl_array_t *x = jl_ptr_to_array_1d(array_type, existingArray, 10, 0);

    The last argument is a boolean indicating whether Julia should take ownership of the data. If this argument is non-zero, the GC will call free on the data pointer when the array is no longer referenced.

    In order to access the data of x, we can use jl_array_data:

    double *xData = (double*)jl_array_data(x);

    Now we can fill the array:

    for(size_t i=0; i<jl_array_len(x); i++)
    -    xData[i] = i;

    Now let us call a Julia function that performs an in-place operation on x:

    jl_function_t *func = jl_get_function(jl_base_module, "reverse!");
    -jl_call1(func, (jl_value_t*)x);

    By printing the array, one can verify that the elements of x are now reversed.

    Accessing Returned Arrays

    If a Julia function returns an array, the return value of jl_eval_string and jl_call can be cast to a jl_array_t*:

    jl_function_t *func  = jl_get_function(jl_base_module, "reverse");
    -jl_array_t *y = (jl_array_t*)jl_call1(func, (jl_value_t*)x);

    Now the content of y can be accessed as before using jl_array_data. As always, be sure to keep a reference to the array while it is in use.

    Multidimensional Arrays

    Julia's multidimensional arrays are stored in memory in column-major order. Here is some code that creates a 2D array and accesses its properties:

    // Create 2D array of float64 type
    -jl_value_t *array_type = jl_apply_array_type(jl_float64_type, 2);
    -jl_array_t *x  = jl_alloc_array_2d(array_type, 10, 5);
    -
    -// Get array pointer
    -double *p = (double*)jl_array_data(x);
    -// Get number of dimensions
    -int ndims = jl_array_ndims(x);
    -// Get the size of the i-th dim
    -size_t size0 = jl_array_dim(x,0);
    -size_t size1 = jl_array_dim(x,1);
    -
    -// Fill array with data
    -for(size_t i=0; i<size1; i++)
    -    for(size_t j=0; j<size0; j++)
    -        p[j + size0*i] = i + j;

    Notice that while Julia arrays use 1-based indexing, the C API uses 0-based indexing (for example in calling jl_array_dim) in order to read as idiomatic C code.

    Exceptions

    Julia code can throw exceptions. For example, consider:

    jl_eval_string("this_function_does_not_exist()");

    This call will appear to do nothing. However, it is possible to check whether an exception was thrown:

    if (jl_exception_occurred())
    -    printf("%s \n", jl_typeof_str(jl_exception_occurred()));

    If you are using the Julia C API from a language that supports exceptions (e.g. Python, C#, C++), it makes sense to wrap each call into libjulia with a function that checks whether an exception was thrown, and then rethrows the exception in the host language.

    Throwing Julia Exceptions

    When writing Julia callable functions, it might be necessary to validate arguments and throw exceptions to indicate errors. A typical type check looks like:

    if (!jl_typeis(val, jl_float64_type)) {
    -    jl_type_error(function_name, (jl_value_t*)jl_float64_type, val);
    -}

    General exceptions can be raised using the functions:

    void jl_error(const char *str);
    -void jl_errorf(const char *fmt, ...);

    jl_error takes a C string, and jl_errorf is called like printf:

    jl_errorf("argument x = %d is too large", x);

    where in this example x is assumed to be an integer.

    diff --git a/julia-0.6.3/share/doc/julia/html/en/manual/environment-variables.html b/julia-0.6.3/share/doc/julia/html/en/manual/environment-variables.html deleted file mode 100644 index 33ab11a..0000000 --- a/julia-0.6.3/share/doc/julia/html/en/manual/environment-variables.html +++ /dev/null @@ -1,13 +0,0 @@ - -Environment Variables · The Julia Language

    Environment Variables

    Environment Variables

    Julia may be configured with a number of environment variables, either in the usual way of the operating system, or in a portable way from within Julia. Suppose you want to set the environment variable JULIA_EDITOR to vim, then either type ENV["JULIA_EDITOR"] = "vim" for instance in the REPL to make this change on a case by case basis, or add the same to the user configuration file .juliarc.jl in the user's home directory to have a permanent effect. The current value of the same environment variable is determined by evaluating ENV["JULIA_EDITOR"].

    The environment variables that Julia uses generally start with JULIA. If Base.versioninfo is called with verbose equal to true, then the output will list defined environment variables relevant for Julia, including those for which JULIA appears in the name.

    File locations

    JULIA_HOME

    The absolute path of the directory containing the Julia executable, which sets the global variable Base.JULIA_HOME. If $JULIA_HOME is not set, then Julia determines the value Base.JULIA_HOME at run-time.

    The executable itself is one of

    $JULIA_HOME/julia
    -$JULIA_HOME/julia-debug

    by default.

    The global variable Base.DATAROOTDIR determines a relative path from Base.JULIA_HOME to the data directory associated with Julia. Then the path

    $JULIA_HOME/$DATAROOTDIR/julia/base

    determines the directory in which Julia initially searches for source files (via Base.find_source_file()).

    Likewise, the global variable Base.SYSCONFDIR determines a relative path to the configuration file directory. Then Julia searches for a juliarc.jl file at

    $JULIA_HOME/$SYSCONFDIR/julia/juliarc.jl
    -$JULIA_HOME/../etc/julia/juliarc.jl

    by default (via Base.load_juliarc()).

    For example, a Linux installation with a Julia executable located at /bin/julia, a DATAROOTDIR of ../share, and a SYSCONFDIR of ../etc will have JULIA_HOME set to /bin, a source-file search path of

    /share/julia/base

    and a global configuration search path of

    /etc/julia/juliarc.jl

    JULIA_LOAD_PATH

    A separated list of absolute paths that are to be appended to the variable LOAD_PATH. (In Unix-like systems, the path separator is :; in Windows systems, the path separator is ;.) The LOAD_PATH variable is where Base.require and Base.load_in_path() look for code; it defaults to the absolute paths

    $JULIA_HOME/../local/share/julia/site/v$(VERSION.major).$(VERSION.minor)
    -$JULIA_HOME/../share/julia/site/v$(VERSION.major).$(VERSION.minor)

    so that, e.g., version 0.6 of Julia on a Linux system with a Julia executable at /bin/julia will have a default LOAD_PATH of

    /local/share/julia/site/v0.6
    -/share/julia/site/v0.6

    JULIA_PKGDIR

    The path of the parent directory Pkg.Dir._pkgroot() for the version-specific Julia package repositories. If the path is relative, then it is taken with respect to the working directory. If $JULIA_PKGDIR is not set, then Pkg.Dir._pkgroot() defaults to

    $HOME/.julia

    Then the repository location Pkg.dir for a given Julia version is

    $JULIA_PKGDIR/v$(VERSION.major).$(VERSION.minor)

    For example, for a Linux user whose home directory is /home/alice, the directory containing the package repositories would by default be

    /home/alice/.julia

    and the package repository for version 0.6 of Julia would be

    /home/alice/.julia/v0.6

    JULIA_HISTORY

    The absolute path Base.REPL.find_hist_file() of the REPL's history file. If $JULIA_HISTORY is not set, then Base.REPL.find_hist_file() defaults to

    $HOME/.julia_history

    JULIA_PKGRESOLVE_ACCURACY

    A positive Int that determines how much time the max-sum subroutine MaxSum.maxsum() of the package dependency resolver Base.Pkg.resolve will devote to attempting satisfying constraints before giving up: this value is by default 1, and larger values correspond to larger amounts of time.

    Suppose the value of $JULIA_PKGRESOLVE_ACCURACY is n. Then

    • the number of pre-decimation iterations is 20*n,

    • the number of iterations between decimation steps is 10*n, and

    • at decimation steps, at most one in every 20*n packages is decimated.

    External applications

    JULIA_SHELL

    The absolute path of the shell with which Julia should execute external commands (via Base.repl_cmd()). Defaults to the environment variable $SHELL, and falls back to /bin/sh if $SHELL is unset.

    Note

    On Windows, this environment variable is ignored, and external commands are executed directly.

    JULIA_EDITOR

    The editor returned by Base.editor() and used in, e.g., Base.edit, referring to the command of the preferred editor, for instance vim.

    $JULIA_EDITOR takes precedence over $VISUAL, which in turn takes precedence over $EDITOR. If none of these environment variables is set, then the editor is taken to be open on Windows and OS X, or /etc/alternatives/editor if it exists, or emacs otherwise.

    Note

    $JULIA_EDITOR is not used in the determination of the editor for Base.Pkg.edit: this function checks $VISUAL and $EDITOR alone.

    Parallelization

    JULIA_CPU_CORES

    Overrides the global variable Base.Sys.CPU_CORES, the number of logical CPU cores available.

    JULIA_WORKER_TIMEOUT

    A Float64 that sets the value of Base.worker_timeout() (default: 60.0). This function gives the number of seconds a worker process will wait for a master process to establish a connection before dying.

    JULIA_NUM_THREADS

    An unsigned 64-bit integer (uint64_t) that sets the maximum number of threads available to Julia. If $JULIA_NUM_THREADS exceeds the number of available physical CPU cores, then the number of threads is set to the number of cores. If $JULIA_NUM_THREADS is not positive or is not set, or if the number of CPU cores cannot be determined through system calls, then the number of threads is set to 1.

    JULIA_THREAD_SLEEP_THRESHOLD

    If set to a string that starts with the case-insensitive substring "infinite", then spinning threads never sleep. Otherwise, $JULIA_THREAD_SLEEP_THRESHOLD is interpreted as an unsigned 64-bit integer (uint64_t) and gives, in nanoseconds, the amount of time after which spinning threads should sleep.

    JULIA_EXCLUSIVE

    If set to anything besides 0, then Julia's thread policy is consistent with running on a dedicated machine: the master thread is on proc 0, and threads are affinitized. Otherwise, Julia lets the operating system handle thread policy.

    REPL formatting

    Environment variables that determine how REPL output should be formatted at the terminal. Generally, these variables should be set to ANSI terminal escape sequences. Julia provides a high-level interface with much of the same functionality: see the section on Interacting With Julia.

    JULIA_ERROR_COLOR

    The formatting Base.error_color() (default: light red, "\033[91m") that errors should have at the terminal.

    JULIA_WARN_COLOR

    The formatting Base.warn_color() (default: yellow, "\033[93m") that warnings should have at the terminal.

    JULIA_INFO_COLOR

    The formatting Base.info_color() (default: cyan, "\033[36m") that info should have at the terminal.

    JULIA_INPUT_COLOR

    The formatting Base.input_color() (default: normal, "\033[0m") that input should have at the terminal.

    JULIA_ANSWER_COLOR

    The formatting Base.answer_color() (default: normal, "\033[0m") that output should have at the terminal.

    JULIA_STACKFRAME_LINEINFO_COLOR

    The formatting Base.stackframe_lineinfo_color() (default: bold, "\033[1m") that line info should have during a stack trace at the terminal.

    JULIA_STACKFRAME_FUNCTION_COLOR

    The formatting Base.stackframe_function_color() (default: bold, "\033[1m") that function calls should have during a stack trace at the terminal.

    Debugging and profiling

    JULIA_GC_ALLOC_POOL, JULIA_GC_ALLOC_OTHER, JULIA_GC_ALLOC_PRINT

    If set, these environment variables take strings that optionally start with the character 'r', followed by a string interpolation of a colon-separated list of three signed 64-bit integers (int64_t). This triple of integers a:b:c represents the arithmetic sequence a, a + b, a + 2*b, ... c.

    • If it's the nth time that jl_gc_pool_alloc() has been called, and n belongs to the arithmetic sequence represented by $JULIA_GC_ALLOC_POOL, then garbage collection is forced.

    • If it's the nth time that maybe_collect() has been called, and n belongs to the arithmetic sequence represented by $JULIA_GC_ALLOC_OTHER, then garbage collection is forced.

    • If it's the nth time that jl_gc_collect() has been called, and n belongs to the arithmetic sequence represented by $JULIA_GC_ALLOC_PRINT, then counts for the number of calls to jl_gc_pool_alloc() and maybe_collect() are printed.

    If the value of the environment variable begins with the character 'r', then the interval between garbage collection events is randomized.

    Note

    These environment variables only have an effect if Julia was compiled with garbage-collection debugging (that is, if WITH_GC_DEBUG_ENV is set to 1 in the build configuration).

    JULIA_GC_NO_GENERATIONAL

    If set to anything besides 0, then the Julia garbage collector never performs "quick sweeps" of memory.

    Note

    This environment variable only has an effect if Julia was compiled with garbage-collection debugging (that is, if WITH_GC_DEBUG_ENV is set to 1 in the build configuration).

    JULIA_GC_WAIT_FOR_DEBUGGER

    If set to anything besides 0, then the Julia garbage collector will wait for a debugger to attach instead of aborting whenever there's a critical error.

    Note

    This environment variable only has an effect if Julia was compiled with garbage-collection debugging (that is, if WITH_GC_DEBUG_ENV is set to 1 in the build configuration).

    ENABLE_JITPROFILING

    If set to anything besides 0, then the compiler will create and register an event listener for just-in-time (JIT) profiling.

    Note

    This environment variable only has an effect if Julia was compiled with JIT profiling support, using either

    • Intel's VTune™ Amplifier (USE_INTEL_JITEVENTS set to 1 in the build configuration), or

    • OProfile (USE_OPROFILE_JITEVENTS set to 1 in the build configuration).

    JULIA_LLVM_ARGS

    Arguments to be passed to the LLVM backend.

    Note

    This environment variable has an effect only if Julia was compiled with JL_DEBUG_BUILD set — in particular, the julia-debug executable is always compiled with this build variable.

    JULIA_DEBUG_LOADING

    If set, then Julia prints detailed information about the cache in the loading process of Base.require.

    diff --git a/julia-0.6.3/share/doc/julia/html/en/manual/faq.html b/julia-0.6.3/share/doc/julia/html/en/manual/faq.html deleted file mode 100644 index 41588fc..0000000 --- a/julia-0.6.3/share/doc/julia/html/en/manual/faq.html +++ /dev/null @@ -1,279 +0,0 @@ - -Frequently Asked Questions · The Julia Language

    Frequently Asked Questions

    Frequently Asked Questions

    Sessions and the REPL

    How do I delete an object in memory?

    Julia does not have an analog of MATLAB's clear function; once a name is defined in a Julia session (technically, in module Main), it is always present.

    If memory usage is your concern, you can always replace objects with ones that consume less memory. For example, if A is a gigabyte-sized array that you no longer need, you can free the memory with A = 0. The memory will be released the next time the garbage collector runs; you can force this to happen with gc().

    How can I modify the declaration of a type in my session?

    Perhaps you've defined a type and then realize you need to add a new field. If you try this at the REPL, you get the error:

    ERROR: invalid redefinition of constant MyType

    Types in module Main cannot be redefined.

    While this can be inconvenient when you are developing new code, there's an excellent workaround. Modules can be replaced by redefining them, and so if you wrap all your new code inside a module you can redefine types and constants. You can't import the type names into Main and then expect to be able to redefine them there, but you can use the module name to resolve the scope. In other words, while developing you might use a workflow something like this:

    include("mynewcode.jl")              # this defines a module MyModule
    -obj1 = MyModule.ObjConstructor(a, b)
    -obj2 = MyModule.somefunction(obj1)
    -# Got an error. Change something in "mynewcode.jl"
    -include("mynewcode.jl")              # reload the module
    -obj1 = MyModule.ObjConstructor(a, b) # old objects are no longer valid, must reconstruct
    -obj2 = MyModule.somefunction(obj1)   # this time it worked!
    -obj3 = MyModule.someotherfunction(obj2, c)
    -...

    Functions

    I passed an argument x to a function, modified it inside that function, but on the outside,

    the variable x is still unchanged. Why?

    Suppose you call a function like this:

    julia> x = 10
    -10
    -
    -julia> function change_value!(y)
    -           y = 17
    -       end
    -change_value! (generic function with 1 method)
    -
    -julia> change_value!(x)
    -17
    -
    -julia> x # x is unchanged!
    -10

    In Julia, the binding of a variable x cannot be changed by passing x as an argument to a function. When calling change_value!(x) in the above example, y is a newly created variable, bound initially to the value of x, i.e. 10; then y is rebound to the constant 17, while the variable x of the outer scope is left untouched.

    But here is a thing you should pay attention to: suppose x is bound to an object of type Array (or any other mutable type). From within the function, you cannot "unbind" x from this Array, but you can change its content. For example:

    julia> x = [1,2,3]
    -3-element Array{Int64,1}:
    - 1
    - 2
    - 3
    -
    -julia> function change_array!(A)
    -           A[1] = 5
    -       end
    -change_array! (generic function with 1 method)
    -
    -julia> change_array!(x)
    -5
    -
    -julia> x
    -3-element Array{Int64,1}:
    - 5
    - 2
    - 3

    Here we created a function change_array!(), that assigns 5 to the first element of the passed array (bound to x at the call site, and bound to A within the function). Notice that, after the function call, x is still bound to the same array, but the content of that array changed: the variables A and x were distinct bindings refering to the same mutable Array object.

    Can I use using or import inside a function?

    No, you are not allowed to have a using or import statement inside a function. If you want to import a module but only use its symbols inside a specific function or set of functions, you have two options:

    1. Use import:

      import Foo
      -function bar(...)
      -    # ... refer to Foo symbols via Foo.baz ...
      -end

      This loads the module Foo and defines a variable Foo that refers to the module, but does not import any of the other symbols from the module into the current namespace. You refer to the Foo symbols by their qualified names Foo.bar etc.

    2. Wrap your function in a module:

      module Bar
      -export bar
      -using Foo
      -function bar(...)
      -    # ... refer to Foo.baz as simply baz ....
      -end
      -end
      -using Bar

      This imports all the symbols from Foo, but only inside the module Bar.

    What does the ... operator do?

    The two uses of the ... operator: slurping and splatting

    Many newcomers to Julia find the use of ... operator confusing. Part of what makes the ... operator confusing is that it means two different things depending on context.

    ... combines many arguments into one argument in function definitions

    In the context of function definitions, the ... operator is used to combine many different arguments into a single argument. This use of ... for combining many different arguments into a single argument is called slurping:

    julia> function printargs(args...)
    -           @printf("%s\n", typeof(args))
    -           for (i, arg) in enumerate(args)
    -               @printf("Arg %d = %s\n", i, arg)
    -           end
    -       end
    -printargs (generic function with 1 method)
    -
    -julia> printargs(1, 2, 3)
    -Tuple{Int64,Int64,Int64}
    -Arg 1 = 1
    -Arg 2 = 2
    -Arg 3 = 3

    If Julia were a language that made more liberal use of ASCII characters, the slurping operator might have been written as <-... instead of ....

    ... splits one argument into many different arguments in function calls

    In contrast to the use of the ... operator to denote slurping many different arguments into one argument when defining a function, the ... operator is also used to cause a single function argument to be split apart into many different arguments when used in the context of a function call. This use of ... is called splatting:

    julia> function threeargs(a, b, c)
    -           @printf("a = %s::%s\n", a, typeof(a))
    -           @printf("b = %s::%s\n", b, typeof(b))
    -           @printf("c = %s::%s\n", c, typeof(c))
    -       end
    -threeargs (generic function with 1 method)
    -
    -julia> vec = [1, 2, 3]
    -3-element Array{Int64,1}:
    - 1
    - 2
    - 3
    -
    -julia> threeargs(vec...)
    -a = 1::Int64
    -b = 2::Int64
    -c = 3::Int64

    If Julia were a language that made more liberal use of ASCII characters, the splatting operator might have been written as ...-> instead of ....

    Types, type declarations, and constructors

    What does "type-stable" mean?

    It means that the type of the output is predictable from the types of the inputs. In particular, it means that the type of the output cannot vary depending on the values of the inputs. The following code is not type-stable:

    julia> function unstable(flag::Bool)
    -           if flag
    -               return 1
    -           else
    -               return 1.0
    -           end
    -       end
    -unstable (generic function with 1 method)

    It returns either an Int or a Float64 depending on the value of its argument. Since Julia can't predict the return type of this function at compile-time, any computation that uses it will have to guard against both types possibly occurring, making generation of fast machine code difficult.

    Why does Julia give a DomainError for certain seemingly-sensible operations?

    Certain operations make mathematical sense but result in errors:

    julia> sqrt(-2.0)
    -ERROR: DomainError:
    -sqrt will only return a complex result if called with a complex argument. Try sqrt(complex(x)).
    -Stacktrace:
    - [1] sqrt(::Float64) at ./math.jl:425
    -
    -julia> 2^-5
    -ERROR: DomainError:
    -Cannot raise an integer x to a negative power -n.
    -Make x a float by adding a zero decimal (e.g. 2.0^-n instead of 2^-n), or write 1/x^n, float(x)^-n, or (x//1)^-n.
    -Stacktrace:
    - [1] power_by_squaring(::Int64, ::Int64) at ./intfuncs.jl:173
    - [2] literal_pow(::Base.#^, ::Int64, ::Type{Val{-5}}) at ./intfuncs.jl:208

    This behavior is an inconvenient consequence of the requirement for type-stability. In the case of sqrt(), most users want sqrt(2.0) to give a real number, and would be unhappy if it produced the complex number 1.4142135623730951 + 0.0im. One could write the sqrt() function to switch to a complex-valued output only when passed a negative number (which is what sqrt() does in some other languages), but then the result would not be type-stable and the sqrt() function would have poor performance.

    In these and other cases, you can get the result you want by choosing an input type that conveys your willingness to accept an output type in which the result can be represented:

    julia> sqrt(-2.0+0im)
    -0.0 + 1.4142135623730951im
    -
    -julia> 2.0^-5
    -0.03125

    Why does Julia use native machine integer arithmetic?

    Julia uses machine arithmetic for integer computations. This means that the range of Int values is bounded and wraps around at either end so that adding, subtracting and multiplying integers can overflow or underflow, leading to some results that can be unsettling at first:

    julia> typemax(Int)
    -9223372036854775807
    -
    -julia> ans+1
    --9223372036854775808
    -
    -julia> -ans
    --9223372036854775808
    -
    -julia> 2*ans
    -0

    Clearly, this is far from the way mathematical integers behave, and you might think it less than ideal for a high-level programming language to expose this to the user. For numerical work where efficiency and transparency are at a premium, however, the alternatives are worse.

    One alternative to consider would be to check each integer operation for overflow and promote results to bigger integer types such as Int128 or BigInt in the case of overflow. Unfortunately, this introduces major overhead on every integer operation (think incrementing a loop counter) – it requires emitting code to perform run-time overflow checks after arithmetic instructions and branches to handle potential overflows. Worse still, this would cause every computation involving integers to be type-unstable. As we mentioned above, type-stability is crucial for effective generation of efficient code. If you can't count on the results of integer operations being integers, it's impossible to generate fast, simple code the way C and Fortran compilers do.

    A variation on this approach, which avoids the appearance of type instability is to merge the Int and BigInt types into a single hybrid integer type, that internally changes representation when a result no longer fits into the size of a machine integer. While this superficially avoids type-instability at the level of Julia code, it just sweeps the problem under the rug by foisting all of the same difficulties onto the C code implementing this hybrid integer type. This approach can be made to work and can even be made quite fast in many cases, but has several drawbacks. One problem is that the in-memory representation of integers and arrays of integers no longer match the natural representation used by C, Fortran and other languages with native machine integers. Thus, to interoperate with those languages, we would ultimately need to introduce native integer types anyway. Any unbounded representation of integers cannot have a fixed number of bits, and thus cannot be stored inline in an array with fixed-size slots – large integer values will always require separate heap-allocated storage. And of course, no matter how clever a hybrid integer implementation one uses, there are always performance traps – situations where performance degrades unexpectedly. Complex representation, lack of interoperability with C and Fortran, the inability to represent integer arrays without additional heap storage, and unpredictable performance characteristics make even the cleverest hybrid integer implementations a poor choice for high-performance numerical work.

    An alternative to using hybrid integers or promoting to BigInts is to use saturating integer arithmetic, where adding to the largest integer value leaves it unchanged and likewise for subtracting from the smallest integer value. This is precisely what Matlab™ does:

    >> int64(9223372036854775807)
    -
    -ans =
    -
    -  9223372036854775807
    -
    ->> int64(9223372036854775807) + 1
    -
    -ans =
    -
    -  9223372036854775807
    -
    ->> int64(-9223372036854775808)
    -
    -ans =
    -
    - -9223372036854775808
    -
    ->> int64(-9223372036854775808) - 1
    -
    -ans =
    -
    - -9223372036854775808

    At first blush, this seems reasonable enough since 9223372036854775807 is much closer to 9223372036854775808 than -9223372036854775808 is and integers are still represented with a fixed size in a natural way that is compatible with C and Fortran. Saturated integer arithmetic, however, is deeply problematic. The first and most obvious issue is that this is not the way machine integer arithmetic works, so implementing saturated operations requires emitting instructions after each machine integer operation to check for underflow or overflow and replace the result with typemin(Int) or typemax(Int) as appropriate. This alone expands each integer operation from a single, fast instruction into half a dozen instructions, probably including branches. Ouch. But it gets worse – saturating integer arithmetic isn't associative. Consider this Matlab computation:

    >> n = int64(2)^62
    -4611686018427387904
    -
    ->> n + (n - 1)
    -9223372036854775807
    -
    ->> (n + n) - 1
    -9223372036854775806

    This makes it hard to write many basic integer algorithms since a lot of common techniques depend on the fact that machine addition with overflow is associative. Consider finding the midpoint between integer values lo and hi in Julia using the expression (lo + hi) >>> 1:

    julia> n = 2^62
    -4611686018427387904
    -
    -julia> (n + 2n) >>> 1
    -6917529027641081856

    See? No problem. That's the correct midpoint between 2^62 and 2^63, despite the fact that n + 2n is -4611686018427387904. Now try it in Matlab:

    >> (n + 2*n)/2
    -
    -ans =
    -
    -  4611686018427387904

    Oops. Adding a >>> operator to Matlab wouldn't help, because saturation that occurs when adding n and 2n has already destroyed the information necessary to compute the correct midpoint.

    Not only is lack of associativity unfortunate for programmers who cannot rely it for techniques like this, but it also defeats almost anything compilers might want to do to optimize integer arithmetic. For example, since Julia integers use normal machine integer arithmetic, LLVM is free to aggressively optimize simple little functions like f(k) = 5k-1. The machine code for this function is just this:

    julia> code_native(f, Tuple{Int})
    -  .text
    -Filename: none
    -  pushq %rbp
    -  movq  %rsp, %rbp
    -Source line: 1
    -  leaq  -1(%rdi,%rdi,4), %rax
    -  popq  %rbp
    -  retq
    -  nopl  (%rax,%rax)

    The actual body of the function is a single leaq instruction, which computes the integer multiply and add at once. This is even more beneficial when f gets inlined into another function:

    julia> function g(k, n)
    -           for i = 1:n
    -               k = f(k)
    -           end
    -           return k
    -       end
    -g (generic function with 1 methods)
    -
    -julia> code_native(g, Tuple{Int,Int})
    -  .text
    -Filename: none
    -  pushq %rbp
    -  movq  %rsp, %rbp
    -Source line: 2
    -  testq %rsi, %rsi
    -  jle L26
    -  nopl  (%rax)
    -Source line: 3
    -L16:
    -  leaq  -1(%rdi,%rdi,4), %rdi
    -Source line: 2
    -  decq  %rsi
    -  jne L16
    -Source line: 5
    -L26:
    -  movq  %rdi, %rax
    -  popq  %rbp
    -  retq
    -  nop

    Since the call to f gets inlined, the loop body ends up being just a single leaq instruction. Next, consider what happens if we make the number of loop iterations fixed:

    julia> function g(k)
    -           for i = 1:10
    -               k = f(k)
    -           end
    -           return k
    -       end
    -g (generic function with 2 methods)
    -
    -julia> code_native(g,(Int,))
    -  .text
    -Filename: none
    -  pushq %rbp
    -  movq  %rsp, %rbp
    -Source line: 3
    -  imulq $9765625, %rdi, %rax    # imm = 0x9502F9
    -  addq  $-2441406, %rax         # imm = 0xFFDABF42
    -Source line: 5
    -  popq  %rbp
    -  retq
    -  nopw  %cs:(%rax,%rax)

    Because the compiler knows that integer addition and multiplication are associative and that multiplication distributes over addition – neither of which is true of saturating arithmetic – it can optimize the entire loop down to just a multiply and an add. Saturated arithmetic completely defeats this kind of optimization since associativity and distributivity can fail at each loop iteration, causing different outcomes depending on which iteration the failure occurs in. The compiler can unroll the loop, but it cannot algebraically reduce multiple operations into fewer equivalent operations.

    The most reasonable alternative to having integer arithmetic silently overflow is to do checked arithmetic everywhere, raising errors when adds, subtracts, and multiplies overflow, producing values that are not value-correct. In this blog post, Dan Luu analyzes this and finds that rather than the trivial cost that this approach should in theory have, it ends up having a substantial cost due to compilers (LLVM and GCC) not gracefully optimizing around the added overflow checks. If this improves in the future, we could consider defaulting to checked integer arithmetic in Julia, but for now, we have to live with the possibility of overflow.

    What are the possible causes of an UndefVarError during remote execution?

    As the error states, an immediate cause of an UndefVarError on a remote node is that a binding by that name does not exist. Let us explore some of the possible causes.

    julia> module Foo
    -           foo() = remotecall_fetch(x->x, 2, "Hello")
    -       end
    -
    -julia> Foo.foo()
    -ERROR: On worker 2:
    -UndefVarError: Foo not defined
    -[...]

    The closure x->x carries a reference to Foo, and since Foo is unavailable on node 2, an UndefVarError is thrown.

    Globals under modules other than Main are not serialized by value to the remote node. Only a reference is sent. Functions which create global bindings (except under Main) may cause an UndefVarError to be thrown later.

    julia> @everywhere module Foo
    -           function foo()
    -               global gvar = "Hello"
    -               remotecall_fetch(()->gvar, 2)
    -           end
    -       end
    -
    -julia> Foo.foo()
    -ERROR: On worker 2:
    -UndefVarError: gvar not defined
    -[...]

    In the above example, @everywhere module Foo defined Foo on all nodes. However the call to Foo.foo() created a new global binding gvar on the local node, but this was not found on node 2 resulting in an UndefVarError error.

    Note that this does not apply to globals created under module Main. Globals under module Main are serialized and new bindings created under Main on the remote node.

    julia> gvar_self = "Node1"
    -"Node1"
    -
    -julia> remotecall_fetch(()->gvar_self, 2)
    -"Node1"
    -
    -julia> remotecall_fetch(whos, 2)
    -	From worker 2:	                          Base  41762 KB     Module
    -	From worker 2:	                          Core  27337 KB     Module
    -	From worker 2:	                           Foo   2477 bytes  Module
    -	From worker 2:	                          Main  46191 KB     Module
    -	From worker 2:	                     gvar_self     13 bytes  String

    This does not apply to function or type declarations. However, anonymous functions bound to global variables are serialized as can be seen below.

    julia> bar() = 1
    -bar (generic function with 1 method)
    -
    -julia> remotecall_fetch(bar, 2)
    -ERROR: On worker 2:
    -UndefVarError: #bar not defined
    -[...]
    -
    -julia> anon_bar  = ()->1
    -(::#21) (generic function with 1 method)
    -
    -julia> remotecall_fetch(anon_bar, 2)
    -1

    Packages and Modules

    What is the difference between "using" and "importall"?

    There is only one difference, and on the surface (syntax-wise) it may seem very minor. The difference between using and importall is that with using you need to say function Foo.bar(.. to extend module Foo's function bar with a new method, but with importall or import Foo.bar, you only need to say function bar(... and it automatically extends module Foo's function bar.

    If you use importall, then function Foo.bar(... and function bar(... become equivalent. If you use using, then they are different.

    The reason this is important enough to have been given separate syntax is that you don't want to accidentally extend a function that you didn't know existed, because that could easily cause a bug. This is most likely to happen with a method that takes a common type like a string or integer, because both you and the other module could define a method to handle such a common type. If you use importall, then you'll replace the other module's implementation of bar(s::AbstractString) with your new implementation, which could easily do something completely different (and break all/many future usages of the other functions in module Foo that depend on calling bar).

    Nothingness and missing values

    How does "null" or "nothingness" work in Julia?

    Unlike many languages (for example, C and Java), Julia does not have a "null" value. When a reference (variable, object field, or array element) is uninitialized, accessing it will immediately throw an error. This situation can be detected using the isdefined function.

    Some functions are used only for their side effects, and do not need to return a value. In these cases, the convention is to return the value nothing, which is just a singleton object of type Void. This is an ordinary type with no fields; there is nothing special about it except for this convention, and that the REPL does not print anything for it. Some language constructs that would not otherwise have a value also yield nothing, for example if false; end.

    For situations where a value exists only sometimes (for example, missing statistical data), it is best to use the Nullable{T} type, which allows specifying the type of a missing value.

    The empty tuple (()) is another form of nothingness. But, it should not really be thought of as nothing but rather a tuple of zero values.

    In code written for Julia prior to version 0.4 you may occasionally see None, which is quite different. It is the empty (or "bottom") type, a type with no values and no subtypes (except itself). This is now written as Union{} (an empty union type). You will generally not need to use this type.

    Memory

    Why does x += y allocate memory when x and y are arrays?

    In Julia, x += y gets replaced during parsing by x = x + y. For arrays, this has the consequence that, rather than storing the result in the same location in memory as x, it allocates a new array to store the result.

    While this behavior might surprise some, the choice is deliberate. The main reason is the presence of immutable objects within Julia, which cannot change their value once created. Indeed, a number is an immutable object; the statements x = 5; x += 1 do not modify the meaning of 5, they modify the value bound to x. For an immutable, the only way to change the value is to reassign it.

    To amplify a bit further, consider the following function:

    function power_by_squaring(x, n::Int)
    -    ispow2(n) || error("This implementation only works for powers of 2")
    -    while n >= 2
    -        x *= x
    -        n >>= 1
    -    end
    -    x
    -end

    After a call like x = 5; y = power_by_squaring(x, 4), you would get the expected result: x == 5 && y == 625. However, now suppose that *=, when used with matrices, instead mutated the left hand side. There would be two problems:

    • For general square matrices, A = A*B cannot be implemented without temporary storage: A[1,1] gets computed and stored on the left hand side before you're done using it on the right hand side.

    • Suppose you were willing to allocate a temporary for the computation (which would eliminate most of the point of making *= work in-place); if you took advantage of the mutability of x, then this function would behave differently for mutable vs. immutable inputs. In particular, for immutable x, after the call you'd have (in general) y != x, but for mutable x you'd have y == x.

    Because supporting generic programming is deemed more important than potential performance optimizations that can be achieved by other means (e.g., using explicit loops), operators like += and *= work by rebinding new values.

    Asynchronous IO and concurrent synchronous writes

    Why do concurrent writes to the same stream result in inter-mixed output?

    While the streaming I/O API is synchronous, the underlying implementation is fully asynchronous.

    Consider the printed output from the following:

    julia> @sync for i in 1:3
    -           @async write(STDOUT, string(i), " Foo ", " Bar ")
    -       end
    -123 Foo  Foo  Foo  Bar  Bar  Bar

    This is happening because, while the write call is synchronous, the writing of each argument yields to other tasks while waiting for that part of the I/O to complete.

    print and println "lock" the stream during a call. Consequently changing write to println in the above example results in:

    julia> @sync for i in 1:3
    -           @async println(STDOUT, string(i), " Foo ", " Bar ")
    -       end
    -1 Foo  Bar
    -2 Foo  Bar
    -3 Foo  Bar

    You can lock your writes with a ReentrantLock like this:

    julia> l = ReentrantLock()
    -ReentrantLock(Nullable{Task}(), Condition(Any[]), 0)
    -
    -julia> @sync for i in 1:3
    -           @async begin
    -               lock(l)
    -               try
    -                   write(STDOUT, string(i), " Foo ", " Bar ")
    -               finally
    -                   unlock(l)
    -               end
    -           end
    -       end
    -1 Foo  Bar 2 Foo  Bar 3 Foo  Bar

    Julia Releases

    Do I want to use a release, beta, or nightly version of Julia?

    You may prefer the release version of Julia if you are looking for a stable code base. Releases generally occur every 6 months, giving you a stable platform for writing code.

    You may prefer the beta version of Julia if you don't mind being slightly behind the latest bugfixes and changes, but find the slightly faster rate of changes more appealing. Additionally, these binaries are tested before they are published to ensure they are fully functional.

    You may prefer the nightly version of Julia if you want to take advantage of the latest updates to the language, and don't mind if the version available today occasionally doesn't actually work.

    Finally, you may also consider building Julia from source for yourself. This option is mainly for those individuals who are comfortable at the command line, or interested in learning. If this describes you, you may also be interested in reading our guidelines for contributing.

    Links to each of these download types can be found on the download page at https://julialang.org/downloads/. Note that not all versions of Julia are available for all platforms.

    When are deprecated functions removed?

    Deprecated functions are removed after the subsequent release. For example, functions marked as deprecated in the 0.1 release will not be available starting with the 0.2 release.

    diff --git a/julia-0.6.3/share/doc/julia/html/en/manual/functions.html b/julia-0.6.3/share/doc/julia/html/en/manual/functions.html deleted file mode 100644 index 9c98664..0000000 --- a/julia-0.6.3/share/doc/julia/html/en/manual/functions.html +++ /dev/null @@ -1,225 +0,0 @@ - -Functions · The Julia Language

    Functions

    Functions

    In Julia, a function is an object that maps a tuple of argument values to a return value. Julia functions are not pure mathematical functions, in the sense that functions can alter and be affected by the global state of the program. The basic syntax for defining functions in Julia is:

    julia> function f(x,y)
    -           x + y
    -       end
    -f (generic function with 1 method)

    There is a second, more terse syntax for defining a function in Julia. The traditional function declaration syntax demonstrated above is equivalent to the following compact "assignment form":

    julia> f(x,y) = x + y
    -f (generic function with 1 method)

    In the assignment form, the body of the function must be a single expression, although it can be a compound expression (see Compound Expressions). Short, simple function definitions are common in Julia. The short function syntax is accordingly quite idiomatic, considerably reducing both typing and visual noise.

    A function is called using the traditional parenthesis syntax:

    julia> f(2,3)
    -5

    Without parentheses, the expression f refers to the function object, and can be passed around like any value:

    julia> g = f;
    -
    -julia> g(2,3)
    -5

    As with variables, Unicode can also be used for function names:

    julia> ∑(x,y) = x + y
    -∑ (generic function with 1 method)
    -
    -julia> ∑(2, 3)
    -5

    Argument Passing Behavior

    Julia function arguments follow a convention sometimes called "pass-by-sharing", which means that values are not copied when they are passed to functions. Function arguments themselves act as new variable bindings (new locations that can refer to values), but the values they refer to are identical to the passed values. Modifications to mutable values (such as Arrays) made within a function will be visible to the caller. This is the same behavior found in Scheme, most Lisps, Python, Ruby and Perl, among other dynamic languages.

    The return Keyword

    The value returned by a function is the value of the last expression evaluated, which, by default, is the last expression in the body of the function definition. In the example function, f, from the previous section this is the value of the expression x + y. As in C and most other imperative or functional languages, the return keyword causes a function to return immediately, providing an expression whose value is returned:

    function g(x,y)
    -    return x * y
    -    x + y
    -end

    Since function definitions can be entered into interactive sessions, it is easy to compare these definitions:

    julia> f(x,y) = x + y
    -f (generic function with 1 method)
    -
    -julia> function g(x,y)
    -           return x * y
    -           x + y
    -       end
    -g (generic function with 1 method)
    -
    -julia> f(2,3)
    -5
    -
    -julia> g(2,3)
    -6

    Of course, in a purely linear function body like g, the usage of return is pointless since the expression x + y is never evaluated and we could simply make x * y the last expression in the function and omit the return. In conjunction with other control flow, however, return is of real use. Here, for example, is a function that computes the hypotenuse length of a right triangle with sides of length x and y, avoiding overflow:

    julia> function hypot(x,y)
    -           x = abs(x)
    -           y = abs(y)
    -           if x > y
    -               r = y/x
    -               return x*sqrt(1+r*r)
    -           end
    -           if y == 0
    -               return zero(x)
    -           end
    -           r = x/y
    -           return y*sqrt(1+r*r)
    -       end
    -hypot (generic function with 1 method)
    -
    -julia> hypot(3, 4)
    -5.0

    There are three possible points of return from this function, returning the values of three different expressions, depending on the values of x and y. The return on the last line could be omitted since it is the last expression.

    Operators Are Functions

    In Julia, most operators are just functions with support for special syntax. (The exceptions are operators with special evaluation semantics like && and ||. These operators cannot be functions since Short-Circuit Evaluation requires that their operands are not evaluated before evaluation of the operator.) Accordingly, you can also apply them using parenthesized argument lists, just as you would any other function:

    julia> 1 + 2 + 3
    -6
    -
    -julia> +(1,2,3)
    -6

    The infix form is exactly equivalent to the function application form – in fact the former is parsed to produce the function call internally. This also means that you can assign and pass around operators such as +() and *() just like you would with other function values:

    julia> f = +;
    -
    -julia> f(1,2,3)
    -6

    Under the name f, the function does not support infix notation, however.

    Operators With Special Names

    A few special expressions correspond to calls to functions with non-obvious names. These are:

    ExpressionCalls
    [A B C ...]hcat()
    [A; B; C; ...]vcat()
    [A B; C D; ...]hvcat()
    A'ctranspose()
    A.'transpose()
    1:ncolon()
    A[i]getindex()
    A[i]=xsetindex!()

    These functions are included in the Base.Operators module even though they do not have operator-like names.

    Anonymous Functions

    Functions in Julia are first-class objects: they can be assigned to variables, and called using the standard function call syntax from the variable they have been assigned to. They can be used as arguments, and they can be returned as values. They can also be created anonymously, without being given a name, using either of these syntaxes:

    julia> x -> x^2 + 2x - 1
    -(::#1) (generic function with 1 method)
    -
    -julia> function (x)
    -           x^2 + 2x - 1
    -       end
    -(::#3) (generic function with 1 method)

    This creates a function taking one argument x and returning the value of the polynomial x^2 + 2x - 1 at that value. Notice that the result is a generic function, but with a compiler-generated name based on consecutive numbering.

    The primary use for anonymous functions is passing them to functions which take other functions as arguments. A classic example is map(), which applies a function to each value of an array and returns a new array containing the resulting values:

    julia> map(round, [1.2,3.5,1.7])
    -3-element Array{Float64,1}:
    - 1.0
    - 4.0
    - 2.0

    This is fine if a named function effecting the transform one wants already exists to pass as the first argument to map(). Often, however, a ready-to-use, named function does not exist. In these situations, the anonymous function construct allows easy creation of a single-use function object without needing a name:

    julia> map(x -> x^2 + 2x - 1, [1,3,-1])
    -3-element Array{Int64,1}:
    -  2
    - 14
    - -2

    An anonymous function accepting multiple arguments can be written using the syntax (x,y,z)->2x+y-z. A zero-argument anonymous function is written as ()->3. The idea of a function with no arguments may seem strange, but is useful for "delaying" a computation. In this usage, a block of code is wrapped in a zero-argument function, which is later invoked by calling it as f().

    Multiple Return Values

    In Julia, one returns a tuple of values to simulate returning multiple values. However, tuples can be created and destructured without needing parentheses, thereby providing an illusion that multiple values are being returned, rather than a single tuple value. For example, the following function returns a pair of values:

    julia> function foo(a,b)
    -           a+b, a*b
    -       end
    -foo (generic function with 1 method)

    If you call it in an interactive session without assigning the return value anywhere, you will see the tuple returned:

    julia> foo(2,3)
    -(5, 6)

    A typical usage of such a pair of return values, however, extracts each value into a variable. Julia supports simple tuple "destructuring" that facilitates this:

    julia> x, y = foo(2,3)
    -(5, 6)
    -
    -julia> x
    -5
    -
    -julia> y
    -6

    You can also return multiple values via an explicit usage of the return keyword:

    function foo(a,b)
    -    return a+b, a*b
    -end

    This has the exact same effect as the previous definition of foo.

    Varargs Functions

    It is often convenient to be able to write functions taking an arbitrary number of arguments. Such functions are traditionally known as "varargs" functions, which is short for "variable number of arguments". You can define a varargs function by following the last argument with an ellipsis:

    julia> bar(a,b,x...) = (a,b,x)
    -bar (generic function with 1 method)

    The variables a and b are bound to the first two argument values as usual, and the variable x is bound to an iterable collection of the zero or more values passed to bar after its first two arguments:

    julia> bar(1,2)
    -(1, 2, ())
    -
    -julia> bar(1,2,3)
    -(1, 2, (3,))
    -
    -julia> bar(1, 2, 3, 4)
    -(1, 2, (3, 4))
    -
    -julia> bar(1,2,3,4,5,6)
    -(1, 2, (3, 4, 5, 6))

    In all these cases, x is bound to a tuple of the trailing values passed to bar.

    It is possible to constrain the number of values passed as a variable argument; this will be discussed later in Parametrically-constrained Varargs methods.

    On the flip side, it is often handy to "splice" the values contained in an iterable collection into a function call as individual arguments. To do this, one also uses ... but in the function call instead:

    julia> x = (3, 4)
    -(3, 4)
    -
    -julia> bar(1,2,x...)
    -(1, 2, (3, 4))

    In this case a tuple of values is spliced into a varargs call precisely where the variable number of arguments go. This need not be the case, however:

    julia> x = (2, 3, 4)
    -(2, 3, 4)
    -
    -julia> bar(1,x...)
    -(1, 2, (3, 4))
    -
    -julia> x = (1, 2, 3, 4)
    -(1, 2, 3, 4)
    -
    -julia> bar(x...)
    -(1, 2, (3, 4))

    Furthermore, the iterable object spliced into a function call need not be a tuple:

    julia> x = [3,4]
    -2-element Array{Int64,1}:
    - 3
    - 4
    -
    -julia> bar(1,2,x...)
    -(1, 2, (3, 4))
    -
    -julia> x = [1,2,3,4]
    -4-element Array{Int64,1}:
    - 1
    - 2
    - 3
    - 4
    -
    -julia> bar(x...)
    -(1, 2, (3, 4))

    Also, the function that arguments are spliced into need not be a varargs function (although it often is):

    julia> baz(a,b) = a + b;
    -
    -julia> args = [1,2]
    -2-element Array{Int64,1}:
    - 1
    - 2
    -
    -julia> baz(args...)
    -3
    -
    -julia> args = [1,2,3]
    -3-element Array{Int64,1}:
    - 1
    - 2
    - 3
    -
    -julia> baz(args...)
    -ERROR: MethodError: no method matching baz(::Int64, ::Int64, ::Int64)
    -Closest candidates are:
    -  baz(::Any, ::Any) at none:1

    As you can see, if the wrong number of elements are in the spliced container, then the function call will fail, just as it would if too many arguments were given explicitly.

    Optional Arguments

    In many cases, function arguments have sensible default values and therefore might not need to be passed explicitly in every call. For example, the library function parse(T, num, base) interprets a string as a number in some base. The base argument defaults to 10. This behavior can be expressed concisely as:

    function parse(T, num, base=10)
    -    ###
    -end

    With this definition, the function can be called with either two or three arguments, and 10 is automatically passed when a third argument is not specified:

    julia> parse(Int,"12",10)
    -12
    -
    -julia> parse(Int,"12",3)
    -5
    -
    -julia> parse(Int,"12")
    -12

    Optional arguments are actually just a convenient syntax for writing multiple method definitions with different numbers of arguments (see Note on Optional and keyword Arguments).

    Keyword Arguments

    Some functions need a large number of arguments, or have a large number of behaviors. Remembering how to call such functions can be difficult. Keyword arguments can make these complex interfaces easier to use and extend by allowing arguments to be identified by name instead of only by position.

    For example, consider a function plot that plots a line. This function might have many options, for controlling line style, width, color, and so on. If it accepts keyword arguments, a possible call might look like plot(x, y, width=2), where we have chosen to specify only line width. Notice that this serves two purposes. The call is easier to read, since we can label an argument with its meaning. It also becomes possible to pass any subset of a large number of arguments, in any order.

    Functions with keyword arguments are defined using a semicolon in the signature:

    function plot(x, y; style="solid", width=1, color="black")
    -    ###
    -end

    When the function is called, the semicolon is optional: one can either call plot(x, y, width=2) or plot(x, y; width=2), but the former style is more common. An explicit semicolon is required only for passing varargs or computed keywords as described below.

    Keyword argument default values are evaluated only when necessary (when a corresponding keyword argument is not passed), and in left-to-right order. Therefore default expressions may refer to prior keyword arguments.

    The types of keyword arguments can be made explicit as follows:

    function f(;x::Int64=1)
    -    ###
    -end

    Extra keyword arguments can be collected using ..., as in varargs functions:

    function f(x; y=0, kwargs...)
    -    ###
    -end

    Inside f, kwargs will be a collection of (key,value) tuples, where each key is a symbol. Such collections can be passed as keyword arguments using a semicolon in a call, e.g. f(x, z=1; kwargs...). Dictionaries can also be used for this purpose.

    One can also pass (key,value) tuples, or any iterable expression (such as a => pair) that can be assigned to such a tuple, explicitly after a semicolon. For example, plot(x, y; (:width,2)) and plot(x, y; :width => 2) are equivalent to plot(x, y, width=2). This is useful in situations where the keyword name is computed at runtime.

    The nature of keyword arguments makes it possible to specify the same argument more than once. For example, in the call plot(x, y; options..., width=2) it is possible that the options structure also contains a value for width. In such a case the rightmost occurrence takes precedence; in this example, width is certain to have the value 2.

    Evaluation Scope of Default Values

    Optional and keyword arguments differ slightly in how their default values are evaluated. When optional argument default expressions are evaluated, only previous arguments are in scope. In contrast, all the arguments are in scope when keyword arguments default expressions are evaluated. For example, given this definition:

    function f(x, a=b, b=1)
    -    ###
    -end

    the b in a=b refers to a b in an outer scope, not the subsequent argument b. However, if a and b were keyword arguments instead, then both would be created in the same scope and the b in a=b would refer to the subsequent argument b (shadowing any b in an outer scope), which would result in an undefined variable error (since the default expressions are evaluated left-to-right, and b has not been assigned yet).

    Do-Block Syntax for Function Arguments

    Passing functions as arguments to other functions is a powerful technique, but the syntax for it is not always convenient. Such calls are especially awkward to write when the function argument requires multiple lines. As an example, consider calling map() on a function with several cases:

    map(x->begin
    -           if x < 0 && iseven(x)
    -               return 0
    -           elseif x == 0
    -               return 1
    -           else
    -               return x
    -           end
    -       end,
    -    [A, B, C])

    Julia provides a reserved word do for rewriting this code more clearly:

    map([A, B, C]) do x
    -    if x < 0 && iseven(x)
    -        return 0
    -    elseif x == 0
    -        return 1
    -    else
    -        return x
    -    end
    -end

    The do x syntax creates an anonymous function with argument x and passes it as the first argument to map(). Similarly, do a,b would create a two-argument anonymous function, and a plain do would declare that what follows is an anonymous function of the form () -> ....

    How these arguments are initialized depends on the "outer" function; here, map() will sequentially set x to A, B, C, calling the anonymous function on each, just as would happen in the syntax map(func, [A, B, C]).

    This syntax makes it easier to use functions to effectively extend the language, since calls look like normal code blocks. There are many possible uses quite different from map(), such as managing system state. For example, there is a version of open() that runs code ensuring that the opened file is eventually closed:

    open("outfile", "w") do io
    -    write(io, data)
    -end

    This is accomplished by the following definition:

    function open(f::Function, args...)
    -    io = open(args...)
    -    try
    -        f(io)
    -    finally
    -        close(io)
    -    end
    -end

    Here, open() first opens the file for writing and then passes the resulting output stream to the anonymous function you defined in the do ... end block. After your function exits, open() will make sure that the stream is properly closed, regardless of whether your function exited normally or threw an exception. (The try/finally construct will be described in Control Flow.)

    With the do block syntax, it helps to check the documentation or implementation to know how the arguments of the user function are initialized.

    Dot Syntax for Vectorizing Functions

    In technical-computing languages, it is common to have "vectorized" versions of functions, which simply apply a given function f(x) to each element of an array A to yield a new array via f(A). This kind of syntax is convenient for data processing, but in other languages vectorization is also often required for performance: if loops are slow, the "vectorized" version of a function can call fast library code written in a low-level language. In Julia, vectorized functions are not required for performance, and indeed it is often beneficial to write your own loops (see Performance Tips), but they can still be convenient. Therefore, any Julia function f can be applied elementwise to any array (or other collection) with the syntax f.(A). For example sin can be applied to all elements in the vector A, like so:

    julia> A = [1.0, 2.0, 3.0]
    -3-element Array{Float64,1}:
    - 1.0
    - 2.0
    - 3.0
    -
    -julia> sin.(A)
    -3-element Array{Float64,1}:
    - 0.841471
    - 0.909297
    - 0.14112

    Of course, you can omit the dot if you write a specialized "vector" method of f, e.g. via f(A::AbstractArray) = map(f, A), and this is just as efficient as f.(A). But that approach requires you to decide in advance which functions you want to vectorize.

    More generally, f.(args...) is actually equivalent to broadcast(f, args...), which allows you to operate on multiple arrays (even of different shapes), or a mix of arrays and scalars (see Broadcasting). For example, if you have f(x,y) = 3x + 4y, then f.(pi,A) will return a new array consisting of f(pi,a) for each a in A, and f.(vector1,vector2) will return a new vector consisting of f(vector1[i],vector2[i]) for each index i (throwing an exception if the vectors have different length).

    julia> f(x,y) = 3x + 4y;
    -
    -julia> A = [1.0, 2.0, 3.0];
    -
    -julia> B = [4.0, 5.0, 6.0];
    -
    -julia> f.(pi, A)
    -3-element Array{Float64,1}:
    - 13.4248
    - 17.4248
    - 21.4248
    -
    -julia> f.(A, B)
    -3-element Array{Float64,1}:
    - 19.0
    - 26.0
    - 33.0

    Moreover, nested f.(args...) calls are fused into a single broadcast loop. For example, sin.(cos.(X)) is equivalent to broadcast(x -> sin(cos(x)), X), similar to [sin(cos(x)) for x in X]: there is only a single loop over X, and a single array is allocated for the result. [In contrast, sin(cos(X)) in a typical "vectorized" language would first allocate one temporary array for tmp=cos(X), and then compute sin(tmp) in a separate loop, allocating a second array.] This loop fusion is not a compiler optimization that may or may not occur, it is a syntactic guarantee whenever nested f.(args...) calls are encountered. Technically, the fusion stops as soon as a "non-dot" function call is encountered; for example, in sin.(sort(cos.(X))) the sin and cos loops cannot be merged because of the intervening sort function.

    Finally, the maximum efficiency is typically achieved when the output array of a vectorized operation is pre-allocated, so that repeated calls do not allocate new arrays over and over again for the results (Pre-allocating outputs:). A convenient syntax for this is X .= ..., which is equivalent to broadcast!(identity, X, ...) except that, as above, the broadcast! loop is fused with any nested "dot" calls. For example, X .= sin.(Y) is equivalent to broadcast!(sin, X, Y), overwriting X with sin.(Y) in-place. If the left-hand side is an array-indexing expression, e.g. X[2:end] .= sin.(Y), then it translates to broadcast! on a view, e.g. broadcast!(sin, view(X, 2:endof(X)), Y), so that the left-hand side is updated in-place.

    Since adding dots to many operations and function calls in an expression can be tedious and lead to code that is difficult to read, the macro @. is provided to convert every function call, operation, and assignment in an expression into the "dotted" version.

    julia> Y = [1.0, 2.0, 3.0, 4.0];
    -
    -julia> X = similar(Y); # pre-allocate output array
    -
    -julia> @. X = sin(cos(Y)) # equivalent to X .= sin.(cos.(Y))
    -4-element Array{Float64,1}:
    -  0.514395
    - -0.404239
    - -0.836022
    - -0.608083

    Binary (or unary) operators like .+ are handled with the same mechanism: they are equivalent to broadcast calls and are fused with other nested "dot" calls. X .+= Y etcetera is equivalent to X .= X .+ Y and results in a fused in-place assignment; see also dot operators.

    Further Reading

    We should mention here that this is far from a complete picture of defining functions. Julia has a sophisticated type system and allows multiple dispatch on argument types. None of the examples given here provide any type annotations on their arguments, meaning that they are applicable to all types of arguments. The type system is described in Types and defining a function in terms of methods chosen by multiple dispatch on run-time argument types is described in Methods.

    diff --git a/julia-0.6.3/share/doc/julia/html/en/manual/getting-started.html b/julia-0.6.3/share/doc/julia/html/en/manual/getting-started.html deleted file mode 100644 index 52f7b94..0000000 --- a/julia-0.6.3/share/doc/julia/html/en/manual/getting-started.html +++ /dev/null @@ -1,76 +0,0 @@ - -Getting Started · The Julia Language

    Getting Started

    Getting Started

    Julia installation is straightforward, whether using precompiled binaries or compiling from source. Download and install Julia by following the instructions at https://julialang.org/downloads/.

    The easiest way to learn and experiment with Julia is by starting an interactive session (also known as a read-eval-print loop or "repl") by double-clicking the Julia executable or running julia from the command line:

    $ julia
    -               _
    -   _       _ _(_)_     |  A fresh approach to technical computing
    -  (_)     | (_) (_)    |  Documentation: https://docs.julialang.org
    -   _ _   _| |_  __ _   |  Type "?help" for help.
    -  | | | | | | |/ _` |  |
    -  | | |_| | | | (_| |  |  Version 0.5.0-dev+2440 (2016-02-01 02:22 UTC)
    - _/ |\__'_|_|_|\__'_|  |  Commit 2bb94d6 (11 days old master)
    -|__/                   |  x86_64-apple-darwin13.1.0
    -
    -julia> 1 + 2
    -3
    -
    -julia> ans
    -3

    To exit the interactive session, type ^D – the control key together with the d key or type quit(). When run in interactive mode, julia displays a banner and prompts the user for input. Once the user has entered a complete expression, such as 1 + 2, and hits enter, the interactive session evaluates the expression and shows its value. If an expression is entered into an interactive session with a trailing semicolon, its value is not shown. The variable ans is bound to the value of the last evaluated expression whether it is shown or not. The ans variable is only bound in interactive sessions, not when Julia code is run in other ways.

    To evaluate expressions written in a source file file.jl, write include("file.jl").

    To run code in a file non-interactively, you can give it as the first argument to the julia command:

    $ julia script.jl arg1 arg2...

    As the example implies, the following command-line arguments to julia are taken as command-line arguments to the program script.jl, passed in the global constant ARGS. The name of the script itself is passed in as the global PROGRAM_FILE. Note that ARGS is also set when script code is given using the -e option on the command line (see the julia help output below) but PROGRAM_FILE will be empty. For example, to just print the arguments given to a script, you could do this:

    $ julia -e 'println(PROGRAM_FILE); for x in ARGS; println(x); end' foo bar
    -
    -foo
    -bar

    Or you could put that code into a script and run it:

    $ echo 'println(PROGRAM_FILE); for x in ARGS; println(x); end' > script.jl
    -$ julia script.jl foo bar
    -script.jl
    -foo
    -bar

    The -- delimiter can be used to separate command-line args to the scriptfile from args to Julia:

    $ julia --color=yes -O -- foo.jl arg1 arg2..

    Julia can be started in parallel mode with either the -p or the --machinefile options. -p n will launch an additional n worker processes, while --machinefile file will launch a worker for each line in file file. The machines defined in file must be accessible via a passwordless ssh login, with Julia installed at the same location as the current host. Each machine definition takes the form [count*][user@]host[:port] [bind_addr[:port]] . user defaults to current user, port to the standard ssh port. count is the number of workers to spawn on the node, and defaults to 1. The optional bind-to bind_addr[:port] specifies the ip-address and port that other workers should use to connect to this worker.

    If you have code that you want executed whenever Julia is run, you can put it in ~/.juliarc.jl:

    $ echo 'println("Greetings! 你好! 안녕하세요?")' > ~/.juliarc.jl
    -$ julia
    -Greetings! 你好! 안녕하세요?
    -
    -...

    There are various ways to run Julia code and provide options, similar to those available for the perl and ruby programs:

    julia [switches] -- [programfile] [args...]
    - -v, --version             Display version information
    - -h, --help                Print this message
    -
    - -J, --sysimage <file>     Start up with the given system image file
    - --precompiled={yes|no}    Use precompiled code from system image if available
    - --compilecache={yes|no}   Enable/disable incremental precompilation of modules
    - -H, --home <dir>          Set location of `julia` executable
    - --startup-file={yes|no}   Load ~/.juliarc.jl
    - --handle-signals={yes|no} Enable or disable Julia's default signal handlers
    -
    - -e, --eval <expr>         Evaluate <expr>
    - -E, --print <expr>        Evaluate and show <expr>
    - -L, --load <file>         Load <file> immediately on all processors
    -
    - -p, --procs {N|auto}      Integer value N launches N additional local worker processes
    -                           "auto" launches as many workers as the number of local cores
    - --machinefile <file>      Run processes on hosts listed in <file>
    -
    - -i                        Interactive mode; REPL runs and isinteractive() is true
    - -q, --quiet               Quiet startup (no banner)
    - --color={yes|no}          Enable or disable color text
    - --history-file={yes|no}   Load or save history
    -
    - --compile={yes|no|all|min}Enable or disable JIT compiler, or request exhaustive compilation
    - -C, --cpu-target <target> Limit usage of cpu features up to <target>
    - -O, --optimize={0,1,2,3}  Set the optimization level (default is 2 if unspecified or 3 if specified as -O)
    - -g, -g <level>            Enable / Set the level of debug info generation (default is 1 if unspecified or 2 if specified as -g)
    - --inline={yes|no}         Control whether inlining is permitted (overrides functions declared as @inline)
    - --check-bounds={yes|no}   Emit bounds checks always or never (ignoring declarations)
    - --math-mode={ieee,fast}   Disallow or enable unsafe floating point optimizations (overrides @fastmath declaration)
    -
    - --depwarn={yes|no|error}  Enable or disable syntax and method deprecation warnings ("error" turns warnings into errors)
    -
    - --output-o name           Generate an object file (including system image data)
    - --output-ji name          Generate a system image data file (.ji)
    - --output-bc name          Generate LLVM bitcode (.bc)
    - --output-incremental=no   Generate an incremental output file (rather than complete)
    -
    - --code-coverage={none|user|all}, --code-coverage
    -                           Count executions of source lines (omitting setting is equivalent to "user")
    - --track-allocation={none|user|all}, --track-allocation
    -                           Count bytes allocated by each source line

    Resources

    In addition to this manual, there are various other resources that may help new users get started with Julia:

    diff --git a/julia-0.6.3/share/doc/julia/html/en/manual/handling-operating-system-variation.html b/julia-0.6.3/share/doc/julia/html/en/manual/handling-operating-system-variation.html deleted file mode 100644 index 98dc84b..0000000 --- a/julia-0.6.3/share/doc/julia/html/en/manual/handling-operating-system-variation.html +++ /dev/null @@ -1,15 +0,0 @@ - -Handling Operating System Variation · The Julia Language

    Handling Operating System Variation

    Handling Operating System Variation

    When dealing with platform libraries, it is often necessary to provide special cases for various platforms. The variable Sys.KERNEL can be used to write these special cases. There are several functions intended to make this easier: is_unix, is_linux, is_apple, is_bsd, and is_windows. These may be used as follows:

    if is_windows()
    -    some_complicated_thing(a)
    -end

    Note that is_linux and is_apple are mutually exclusive subsets of is_unix. Additionally, there is a macro @static which makes it possible to use these functions to conditionally hide invalid code, as demonstrated in the following examples.

    Simple blocks:

    ccall( (@static is_windows() ? :_fopen : :fopen), ...)

    Complex blocks:

    @static if is_linux()
    -    some_complicated_thing(a)
    -else
    -    some_different_thing(a)
    -end

    When chaining conditionals (including if/elseif/end), the @static must be repeated for each level (parentheses optional, but recommended for readability):

    @static is_windows() ? :a : (@static is_apple() ? :b : :c)
    diff --git a/julia-0.6.3/share/doc/julia/html/en/manual/integers-and-floating-point-numbers.html b/julia-0.6.3/share/doc/julia/html/en/manual/integers-and-floating-point-numbers.html deleted file mode 100644 index b5d716e..0000000 --- a/julia-0.6.3/share/doc/julia/html/en/manual/integers-and-floating-point-numbers.html +++ /dev/null @@ -1,291 +0,0 @@ - -Integers and Floating-Point Numbers · The Julia Language

    Integers and Floating-Point Numbers

    Integers and Floating-Point Numbers

    Integers and floating-point values are the basic building blocks of arithmetic and computation. Built-in representations of such values are called numeric primitives, while representations of integers and floating-point numbers as immediate values in code are known as numeric literals. For example, 1 is an integer literal, while 1.0 is a floating-point literal; their binary in-memory representations as objects are numeric primitives.

    Julia provides a broad range of primitive numeric types, and a full complement of arithmetic and bitwise operators as well as standard mathematical functions are defined over them. These map directly onto numeric types and operations that are natively supported on modern computers, thus allowing Julia to take full advantage of computational resources. Additionally, Julia provides software support for Arbitrary Precision Arithmetic, which can handle operations on numeric values that cannot be represented effectively in native hardware representations, but at the cost of relatively slower performance.

    The following are Julia's primitive numeric types:

    • Integer types:

    TypeSigned?Number of bitsSmallest valueLargest value
    Int88-2^72^7 - 1
    UInt8 802^8 - 1
    Int1616-2^152^15 - 1
    UInt16 1602^16 - 1
    Int3232-2^312^31 - 1
    UInt32 3202^32 - 1
    Int6464-2^632^63 - 1
    UInt64 6402^64 - 1
    Int128128-2^1272^127 - 1
    UInt128 12802^128 - 1
    BoolN/A8false (0)true (1)
    • Floating-point types:

    TypePrecisionNumber of bits
    Float16half16
    Float32single32
    Float64double64

    Additionally, full support for Complex and Rational Numbers is built on top of these primitive numeric types. All numeric types interoperate naturally without explicit casting, thanks to a flexible, user-extensible type promotion system.

    Integers

    Literal integers are represented in the standard manner:

    julia> 1
    -1
    -
    -julia> 1234
    -1234

    The default type for an integer literal depends on whether the target system has a 32-bit architecture or a 64-bit architecture:

    # 32-bit system:
    -julia> typeof(1)
    -Int32
    -
    -# 64-bit system:
    -julia> typeof(1)
    -Int64

    The Julia internal variable Sys.WORD_SIZE indicates whether the target system is 32-bit or 64-bit:

    # 32-bit system:
    -julia> Sys.WORD_SIZE
    -32
    -
    -# 64-bit system:
    -julia> Sys.WORD_SIZE
    -64

    Julia also defines the types Int and UInt, which are aliases for the system's signed and unsigned native integer types respectively:

    # 32-bit system:
    -julia> Int
    -Int32
    -julia> UInt
    -UInt32
    -
    -# 64-bit system:
    -julia> Int
    -Int64
    -julia> UInt
    -UInt64

    Larger integer literals that cannot be represented using only 32 bits but can be represented in 64 bits always create 64-bit integers, regardless of the system type:

    # 32-bit or 64-bit system:
    -julia> typeof(3000000000)
    -Int64

    Unsigned integers are input and output using the 0x prefix and hexadecimal (base 16) digits 0-9a-f (the capitalized digits A-F also work for input). The size of the unsigned value is determined by the number of hex digits used:

    julia> 0x1
    -0x01
    -
    -julia> typeof(ans)
    -UInt8
    -
    -julia> 0x123
    -0x0123
    -
    -julia> typeof(ans)
    -UInt16
    -
    -julia> 0x1234567
    -0x01234567
    -
    -julia> typeof(ans)
    -UInt32
    -
    -julia> 0x123456789abcdef
    -0x0123456789abcdef
    -
    -julia> typeof(ans)
    -UInt64

    This behavior is based on the observation that when one uses unsigned hex literals for integer values, one typically is using them to represent a fixed numeric byte sequence, rather than just an integer value.

    Recall that the variable ans is set to the value of the last expression evaluated in an interactive session. This does not occur when Julia code is run in other ways.

    Binary and octal literals are also supported:

    julia> 0b10
    -0x02
    -
    -julia> typeof(ans)
    -UInt8
    -
    -julia> 0o10
    -0x08
    -
    -julia> typeof(ans)
    -UInt8

    The minimum and maximum representable values of primitive numeric types such as integers are given by the typemin() and typemax() functions:

    julia> (typemin(Int32), typemax(Int32))
    -(-2147483648, 2147483647)
    -
    -julia> for T in [Int8,Int16,Int32,Int64,Int128,UInt8,UInt16,UInt32,UInt64,UInt128]
    -           println("$(lpad(T,7)): [$(typemin(T)),$(typemax(T))]")
    -       end
    -   Int8: [-128,127]
    -  Int16: [-32768,32767]
    -  Int32: [-2147483648,2147483647]
    -  Int64: [-9223372036854775808,9223372036854775807]
    - Int128: [-170141183460469231731687303715884105728,170141183460469231731687303715884105727]
    -  UInt8: [0,255]
    - UInt16: [0,65535]
    - UInt32: [0,4294967295]
    - UInt64: [0,18446744073709551615]
    -UInt128: [0,340282366920938463463374607431768211455]

    The values returned by typemin() and typemax() are always of the given argument type. (The above expression uses several features we have yet to introduce, including for loops, Strings, and Interpolation, but should be easy enough to understand for users with some existing programming experience.)

    Overflow behavior

    In Julia, exceeding the maximum representable value of a given type results in a wraparound behavior:

    julia> x = typemax(Int64)
    -9223372036854775807
    -
    -julia> x + 1
    --9223372036854775808
    -
    -julia> x + 1 == typemin(Int64)
    -true

    Thus, arithmetic with Julia integers is actually a form of modular arithmetic. This reflects the characteristics of the underlying arithmetic of integers as implemented on modern computers. In applications where overflow is possible, explicit checking for wraparound produced by overflow is essential; otherwise, the BigInt type in Arbitrary Precision Arithmetic is recommended instead.

    Division errors

    Integer division (the div function) has two exceptional cases: dividing by zero, and dividing the lowest negative number (typemin()) by -1. Both of these cases throw a DivideError. The remainder and modulus functions (rem and mod) throw a DivideError when their second argument is zero.

    Floating-Point Numbers

    Literal floating-point numbers are represented in the standard formats:

    julia> 1.0
    -1.0
    -
    -julia> 1.
    -1.0
    -
    -julia> 0.5
    -0.5
    -
    -julia> .5
    -0.5
    -
    -julia> -1.23
    --1.23
    -
    -julia> 1e10
    -1.0e10
    -
    -julia> 2.5e-4
    -0.00025

    The above results are all Float64 values. Literal Float32 values can be entered by writing an f in place of e:

    julia> 0.5f0
    -0.5f0
    -
    -julia> typeof(ans)
    -Float32
    -
    -julia> 2.5f-4
    -0.00025f0

    Values can be converted to Float32 easily:

    julia> Float32(-1.5)
    --1.5f0
    -
    -julia> typeof(ans)
    -Float32

    Hexadecimal floating-point literals are also valid, but only as Float64 values:

    julia> 0x1p0
    -1.0
    -
    -julia> 0x1.8p3
    -12.0
    -
    -julia> 0x.4p-1
    -0.125
    -
    -julia> typeof(ans)
    -Float64

    Half-precision floating-point numbers are also supported (Float16), but they are implemented in software and use Float32 for calculations.

    julia> sizeof(Float16(4.))
    -2
    -
    -julia> 2*Float16(4.)
    -Float16(8.0)

    The underscore _ can be used as digit separator:

    julia> 10_000, 0.000_000_005, 0xdead_beef, 0b1011_0010
    -(10000, 5.0e-9, 0xdeadbeef, 0xb2)

    Floating-point zero

    Floating-point numbers have two zeros, positive zero and negative zero. They are equal to each other but have different binary representations, as can be seen using the bits function: :

    julia> 0.0 == -0.0
    -true
    -
    -julia> bits(0.0)
    -"0000000000000000000000000000000000000000000000000000000000000000"
    -
    -julia> bits(-0.0)
    -"1000000000000000000000000000000000000000000000000000000000000000"

    Special floating-point values

    There are three specified standard floating-point values that do not correspond to any point on the real number line:

    Float16Float32Float64NameDescription
    Inf16Inf32Infpositive infinitya value greater than all finite floating-point values
    -Inf16-Inf32-Infnegative infinitya value less than all finite floating-point values
    NaN16NaN32NaNnot a numbera value not == to any floating-point value (including itself)

    For further discussion of how these non-finite floating-point values are ordered with respect to each other and other floats, see Numeric Comparisons. By the IEEE 754 standard, these floating-point values are the results of certain arithmetic operations:

    julia> 1/Inf
    -0.0
    -
    -julia> 1/0
    -Inf
    -
    -julia> -5/0
    --Inf
    -
    -julia> 0.000001/0
    -Inf
    -
    -julia> 0/0
    -NaN
    -
    -julia> 500 + Inf
    -Inf
    -
    -julia> 500 - Inf
    --Inf
    -
    -julia> Inf + Inf
    -Inf
    -
    -julia> Inf - Inf
    -NaN
    -
    -julia> Inf * Inf
    -Inf
    -
    -julia> Inf / Inf
    -NaN
    -
    -julia> 0 * Inf
    -NaN

    The typemin() and typemax() functions also apply to floating-point types:

    julia> (typemin(Float16),typemax(Float16))
    -(-Inf16, Inf16)
    -
    -julia> (typemin(Float32),typemax(Float32))
    -(-Inf32, Inf32)
    -
    -julia> (typemin(Float64),typemax(Float64))
    -(-Inf, Inf)

    Machine epsilon

    Most real numbers cannot be represented exactly with floating-point numbers, and so for many purposes it is important to know the distance between two adjacent representable floating-point numbers, which is often known as machine epsilon.

    Julia provides eps(), which gives the distance between 1.0 and the next larger representable floating-point value:

    julia> eps(Float32)
    -1.1920929f-7
    -
    -julia> eps(Float64)
    -2.220446049250313e-16
    -
    -julia> eps() # same as eps(Float64)
    -2.220446049250313e-16

    These values are 2.0^-23 and 2.0^-52 as Float32 and Float64 values, respectively. The eps() function can also take a floating-point value as an argument, and gives the absolute difference between that value and the next representable floating point value. That is, eps(x) yields a value of the same type as x such that x + eps(x) is the next representable floating-point value larger than x:

    julia> eps(1.0)
    -2.220446049250313e-16
    -
    -julia> eps(1000.)
    -1.1368683772161603e-13
    -
    -julia> eps(1e-27)
    -1.793662034335766e-43
    -
    -julia> eps(0.0)
    -5.0e-324

    The distance between two adjacent representable floating-point numbers is not constant, but is smaller for smaller values and larger for larger values. In other words, the representable floating-point numbers are densest in the real number line near zero, and grow sparser exponentially as one moves farther away from zero. By definition, eps(1.0) is the same as eps(Float64) since 1.0 is a 64-bit floating-point value.

    Julia also provides the nextfloat() and prevfloat() functions which return the next largest or smallest representable floating-point number to the argument respectively:

    julia> x = 1.25f0
    -1.25f0
    -
    -julia> nextfloat(x)
    -1.2500001f0
    -
    -julia> prevfloat(x)
    -1.2499999f0
    -
    -julia> bits(prevfloat(x))
    -"00111111100111111111111111111111"
    -
    -julia> bits(x)
    -"00111111101000000000000000000000"
    -
    -julia> bits(nextfloat(x))
    -"00111111101000000000000000000001"

    This example highlights the general principle that the adjacent representable floating-point numbers also have adjacent binary integer representations.

    Rounding modes

    If a number doesn't have an exact floating-point representation, it must be rounded to an appropriate representable value, however, if wanted, the manner in which this rounding is done can be changed according to the rounding modes presented in the IEEE 754 standard.

    julia> x = 1.1; y = 0.1;
    -
    -julia> x + y
    -1.2000000000000002
    -
    -julia> setrounding(Float64,RoundDown) do
    -           x + y
    -       end
    -1.2

    The default mode used is always RoundNearest, which rounds to the nearest representable value, with ties rounded towards the nearest value with an even least significant bit.

    Warning

    Rounding is generally only correct for basic arithmetic functions (+(), -(), *(), /() and sqrt()) and type conversion operations. Many other functions assume the default RoundNearest mode is set, and can give erroneous results when operating under other rounding modes.

    Background and References

    Floating-point arithmetic entails many subtleties which can be surprising to users who are unfamiliar with the low-level implementation details. However, these subtleties are described in detail in most books on scientific computation, and also in the following references:

    Arbitrary Precision Arithmetic

    To allow computations with arbitrary-precision integers and floating point numbers, Julia wraps the GNU Multiple Precision Arithmetic Library (GMP) and the GNU MPFR Library, respectively. The BigInt and BigFloat types are available in Julia for arbitrary precision integer and floating point numbers respectively.

    Constructors exist to create these types from primitive numerical types, and parse() can be used to construct them from AbstractStrings. Once created, they participate in arithmetic with all other numeric types thanks to Julia's type promotion and conversion mechanism:

    julia> BigInt(typemax(Int64)) + 1
    -9223372036854775808
    -
    -julia> parse(BigInt, "123456789012345678901234567890") + 1
    -123456789012345678901234567891
    -
    -julia> parse(BigFloat, "1.23456789012345678901")
    -1.234567890123456789010000000000000000000000000000000000000000000000000000000004
    -
    -julia> BigFloat(2.0^66) / 3
    -2.459565876494606882133333333333333333333333333333333333333333333333333333333344e+19
    -
    -julia> factorial(BigInt(40))
    -815915283247897734345611269596115894272000000000

    However, type promotion between the primitive types above and BigInt/BigFloat is not automatic and must be explicitly stated.

    julia> x = typemin(Int64)
    --9223372036854775808
    -
    -julia> x = x - 1
    -9223372036854775807
    -
    -julia> typeof(x)
    -Int64
    -
    -julia> y = BigInt(typemin(Int64))
    --9223372036854775808
    -
    -julia> y = y - 1
    --9223372036854775809
    -
    -julia> typeof(y)
    -BigInt

    The default precision (in number of bits of the significand) and rounding mode of BigFloat operations can be changed globally by calling setprecision() and setrounding(), and all further calculations will take these changes in account. Alternatively, the precision or the rounding can be changed only within the execution of a particular block of code by using the same functions with a do block:

    julia> setrounding(BigFloat, RoundUp) do
    -           BigFloat(1) + parse(BigFloat, "0.1")
    -       end
    -1.100000000000000000000000000000000000000000000000000000000000000000000000000003
    -
    -julia> setrounding(BigFloat, RoundDown) do
    -           BigFloat(1) + parse(BigFloat, "0.1")
    -       end
    -1.099999999999999999999999999999999999999999999999999999999999999999999999999986
    -
    -julia> setprecision(40) do
    -           BigFloat(1) + parse(BigFloat, "0.1")
    -       end
    -1.1000000000004

    Numeric Literal Coefficients

    To make common numeric formulas and expressions clearer, Julia allows variables to be immediately preceded by a numeric literal, implying multiplication. This makes writing polynomial expressions much cleaner:

    julia> x = 3
    -3
    -
    -julia> 2x^2 - 3x + 1
    -10
    -
    -julia> 1.5x^2 - .5x + 1
    -13.0

    It also makes writing exponential functions more elegant:

    julia> 2^2x
    -64

    The precedence of numeric literal coefficients is the same as that of unary operators such as negation. So 2^3x is parsed as 2^(3x), and 2x^3 is parsed as 2*(x^3).

    Numeric literals also work as coefficients to parenthesized expressions:

    julia> 2(x-1)^2 - 3(x-1) + 1
    -3
    Note

    The precedence of numeric literal coefficients used for implicit multiplication is higher than other binary operators such as multiplication (*), and division (/, \, and //). This means, for example, that 1 / 2im equals -0.5im and 6 // 2(2 + 1) equals 1 // 1.

    Additionally, parenthesized expressions can be used as coefficients to variables, implying multiplication of the expression by the variable:

    julia> (x-1)x
    -6

    Neither juxtaposition of two parenthesized expressions, nor placing a variable before a parenthesized expression, however, can be used to imply multiplication:

    julia> (x-1)(x+1)
    -ERROR: MethodError: objects of type Int64 are not callable
    -
    -julia> x(x+1)
    -ERROR: MethodError: objects of type Int64 are not callable

    Both expressions are interpreted as function application: any expression that is not a numeric literal, when immediately followed by a parenthetical, is interpreted as a function applied to the values in parentheses (see Functions for more about functions). Thus, in both of these cases, an error occurs since the left-hand value is not a function.

    The above syntactic enhancements significantly reduce the visual noise incurred when writing common mathematical formulae. Note that no whitespace may come between a numeric literal coefficient and the identifier or parenthesized expression which it multiplies.

    Syntax Conflicts

    Juxtaposed literal coefficient syntax may conflict with two numeric literal syntaxes: hexadecimal integer literals and engineering notation for floating-point literals. Here are some situations where syntactic conflicts arise:

    • The hexadecimal integer literal expression 0xff could be interpreted as the numeric literal 0 multiplied by the variable xff.

    • The floating-point literal expression 1e10 could be interpreted as the numeric literal 1 multiplied by the variable e10, and similarly with the equivalent E form.

    In both cases, we resolve the ambiguity in favor of interpretation as a numeric literals:

    • Expressions starting with 0x are always hexadecimal literals.

    • Expressions starting with a numeric literal followed by e or E are always floating-point literals.

    Literal zero and one

    Julia provides functions which return literal 0 and 1 corresponding to a specified type or the type of a given variable.

    FunctionDescription
    zero(x)Literal zero of type x or type of variable x
    one(x)Literal one of type x or type of variable x

    These functions are useful in Numeric Comparisons to avoid overhead from unnecessary type conversion.

    Examples:

    julia> zero(Float32)
    -0.0f0
    -
    -julia> zero(1.0)
    -0.0
    -
    -julia> one(Int32)
    -1
    -
    -julia> one(BigFloat)
    -1.000000000000000000000000000000000000000000000000000000000000000000000000000000
    diff --git a/julia-0.6.3/share/doc/julia/html/en/manual/interacting-with-julia.html b/julia-0.6.3/share/doc/julia/html/en/manual/interacting-with-julia.html deleted file mode 100644 index 2e2f696..0000000 --- a/julia-0.6.3/share/doc/julia/html/en/manual/interacting-with-julia.html +++ /dev/null @@ -1,130 +0,0 @@ - -Interacting With Julia · The Julia Language

    Interacting With Julia

    Interacting With Julia

    Julia comes with a full-featured interactive command-line REPL (read-eval-print loop) built into the julia executable. In addition to allowing quick and easy evaluation of Julia statements, it has a searchable history, tab-completion, many helpful keybindings, and dedicated help and shell modes. The REPL can be started by simply calling julia with no arguments or double-clicking on the executable:

    $ julia
    -               _
    -   _       _ _(_)_     |  A fresh approach to technical computing
    -  (_)     | (_) (_)    |  Documentation: https://docs.julialang.org
    -   _ _   _| |_  __ _   |  Type "?help" for help.
    -  | | | | | | |/ _` |  |
    -  | | |_| | | | (_| |  |  Version 0.6.0-dev.2493 (2017-01-31 18:53 UTC)
    - _/ |\__'_|_|_|\__'_|  |  Commit c99e12c* (0 days old master)
    -|__/                   |  x86_64-linux-gnu
    -
    -julia>

    To exit the interactive session, type ^D – the control key together with the d key on a blank line – or type quit() followed by the return or enter key. The REPL greets you with a banner and a julia> prompt.

    The different prompt modes

    The Julian mode

    The REPL has four main modes of operation. The first and most common is the Julian prompt. It is the default mode of operation; each new line initially starts with julia>. It is here that you can enter Julia expressions. Hitting return or enter after a complete expression has been entered will evaluate the entry and show the result of the last expression.

    julia> string(1 + 2)
    -"3"

    There are a number useful features unique to interactive work. In addition to showing the result, the REPL also binds the result to the variable ans. A trailing semicolon on the line can be used as a flag to suppress showing the result.

    julia> string(3 * 4);
    -
    -julia> ans
    -"12"

    In Julia mode, the REPL supports something called prompt pasting. This activates when pasting text that starts with julia>  into the REPL. In that case, only expressions starting with julia>  are parsed, others are removed. This makes it is possible to paste a chunk of code that has been copied from a REPL session without having to scrub away prompts and outputs. This feature is enabled by default but can be disabled or enabled at will with Base.REPL.enable_promptpaste(::Bool). If it is enabled, you can try it out by pasting the code block above this paragraph straight into the REPL. This feature does not work on the standard Windows command prompt due to its limitation at detecting when a paste occurs.

    Help mode

    When the cursor is at the beginning of the line, the prompt can be changed to a help mode by typing ?. Julia will attempt to print help or documentation for anything entered in help mode:

    julia> ? # upon typing ?, the prompt changes (in place) to: help?>
    -
    -help?> string
    -search: string String stringmime Cstring Cwstring RevString readstring randstring bytestring SubString
    -
    -  string(xs...)
    -
    -  Create a string from any values using the print function.

    Macros, types and variables can also be queried:

    help?> @time
    -  @time
    -
    -  A macro to execute an expression, printing the time it took to execute, the number of allocations,
    -  and the total number of bytes its execution caused to be allocated, before returning the value of the
    -  expression.
    -
    -  See also @timev, @timed, @elapsed, and @allocated.
    -
    -help?> AbstractString
    -search: AbstractString AbstractSparseMatrix AbstractSparseVector AbstractSet
    -
    -  No documentation found.
    -
    -  Summary:
    -
    -  abstract AbstractString <: Any
    -
    -  Subtypes:
    -
    -  Base.Test.GenericString
    -  DirectIndexString
    -  String

    Help mode can be exited by pressing backspace at the beginning of the line.

    Shell mode

    Just as help mode is useful for quick access to documentation, another common task is to use the system shell to execute system commands. Just as ? entered help mode when at the beginning of the line, a semicolon (;) will enter the shell mode. And it can be exited by pressing backspace at the beginning of the line.

    julia> ; # upon typing ;, the prompt changes (in place) to: shell>
    -
    -shell> echo hello
    -hello

    Search modes

    In all of the above modes, the executed lines get saved to a history file, which can be searched. To initiate an incremental search through the previous history, type ^R – the control key together with the r key. The prompt will change to (reverse-i-search)`':, and as you type the search query will appear in the quotes. The most recent result that matches the query will dynamically update to the right of the colon as more is typed. To find an older result using the same query, simply type ^R again.

    Just as ^R is a reverse search, ^S is a forward search, with the prompt (i-search)`':. The two may be used in conjunction with each other to move through the previous or next matching results, respectively.

    Key bindings

    The Julia REPL makes great use of key bindings. Several control-key bindings were already introduced above (^D to exit, ^R and ^S for searching), but there are many more. In addition to the control-key, there are also meta-key bindings. These vary more by platform, but most terminals default to using alt- or option- held down with a key to send the meta-key (or can be configured to do so).

    KeybindingDescription
    Program control 
    ^DExit (when buffer is empty)
    ^CInterrupt or cancel
    ^LClear console screen
    Return/Enter, ^JNew line, executing if it is complete
    meta-Return/EnterInsert new line without executing it
    ? or ;Enter help or shell mode (when at start of a line)
    ^R, ^SIncremental history search, described above
    Cursor movement 
    Right arrow, ^FMove right one character
    Left arrow, ^BMove left one character
    Home, ^AMove to beginning of line
    End, ^EMove to end of line
    ^PChange to the previous or next history entry
    ^NChange to the next history entry
    Up arrowMove up one line (or to the previous history entry)
    Down arrowMove down one line (or to the next history entry)
    Page-upChange to the previous history entry that matches the text before the cursor
    Page-downChange to the next history entry that matches the text before the cursor
    meta-FMove right one word
    meta-BMove left one word
    Editing 
    Backspace, ^HDelete the previous character
    Delete, ^DForward delete one character (when buffer has text)
    meta-BackspaceDelete the previous word
    meta-DForward delete the next word
    ^WDelete previous text up to the nearest whitespace
    ^K"Kill" to end of line, placing the text in a buffer
    ^Y"Yank" insert the text from the kill buffer
    ^TTranspose the characters about the cursor
    ^QWrite a number in REPL and press ^Q to open editor at corresponding stackframe

    Customizing keybindings

    Julia's REPL keybindings may be fully customized to a user's preferences by passing a dictionary to REPL.setup_interface(). The keys of this dictionary may be characters or strings. The key '*' refers to the default action. Control plus character x bindings are indicated with "^x". Meta plus x can be written "\\Mx". The values of the custom keymap must be nothing (indicating that the input should be ignored) or functions that accept the signature (PromptState, AbstractREPL, Char). The REPL.setup_interface() function must be called before the REPL is initialized, by registering the operation with atreplinit(). For example, to bind the up and down arrow keys to move through history without prefix search, one could put the following code in .juliarc.jl:

    import Base: LineEdit, REPL
    -
    -const mykeys = Dict{Any,Any}(
    -    # Up Arrow
    -    "\e[A" => (s,o...)->(LineEdit.edit_move_up(s) || LineEdit.history_prev(s, LineEdit.mode(s).hist)),
    -    # Down Arrow
    -    "\e[B" => (s,o...)->(LineEdit.edit_move_up(s) || LineEdit.history_next(s, LineEdit.mode(s).hist))
    -)
    -
    -function customize_keys(repl)
    -    repl.interface = REPL.setup_interface(repl; extra_repl_keymap = mykeys)
    -end
    -
    -atreplinit(customize_keys)

    Users should refer to base/LineEdit.jl to discover the available actions on key input.

    Tab completion

    In both the Julian and help modes of the REPL, one can enter the first few characters of a function or type and then press the tab key to get a list all matches:

    julia> stri[TAB]
    -stride     strides     string      stringmime  strip
    -
    -julia> Stri[TAB]
    -StridedArray    StridedMatrix    StridedVecOrMat  StridedVector    String

    The tab key can also be used to substitute LaTeX math symbols with their Unicode equivalents, and get a list of LaTeX matches as well:

    julia> \pi[TAB]
    -julia> π
    -π = 3.1415926535897...
    -
    -julia> e\_1[TAB] = [1,0]
    -julia> e₁ = [1,0]
    -2-element Array{Int64,1}:
    - 1
    - 0
    -
    -julia> e\^1[TAB] = [1 0]
    -julia> e¹ = [1 0]
    -1×2 Array{Int64,2}:
    - 1  0
    -
    -julia> \sqrt[TAB]2     # √ is equivalent to the sqrt() function
    -julia> √2
    -1.4142135623730951
    -
    -julia> \hbar[TAB](h) = h / 2\pi[TAB]
    -julia> ħ(h) = h / 2π
    -ħ (generic function with 1 method)
    -
    -julia> \h[TAB]
    -\hat              \hermitconjmatrix  \hkswarow          \hrectangle
    -\hatapprox        \hexagon           \hookleftarrow     \hrectangleblack
    -\hbar             \hexagonblack      \hookrightarrow    \hslash
    -\heartsuit        \hksearow          \house             \hspace
    -
    -julia> α="\alpha[TAB]"   # LaTeX completion also works in strings
    -julia> α="α"

    A full list of tab-completions can be found in the Unicode Input section of the manual.

    Completion of paths works for strings and julia's shell mode:

    julia> path="/[TAB]"
    -.dockerenv  .juliabox/   boot/        etc/         lib/         media/       opt/         root/        sbin/        sys/         usr/
    -.dockerinit bin/         dev/         home/        lib64/       mnt/         proc/        run/         srv/         tmp/         var/
    -shell> /[TAB]
    -.dockerenv  .juliabox/   boot/        etc/         lib/         media/       opt/         root/        sbin/        sys/         usr/
    -.dockerinit bin/         dev/         home/        lib64/       mnt/         proc/        run/         srv/         tmp/         var/

    Tab completion can help with investigation of the available methods matching the input arguments:

    julia> max([TAB] # All methods are displayed, not shown here due to size of the list
    -
    -julia> max([1, 2], [TAB] # All methods where `Vector{Int}` matches as first argument
    -max(x, y) in Base at operators.jl:215
    -max(a, b, c, xs...) in Base at operators.jl:281
    -
    -julia> max([1, 2], max(1, 2), [TAB] # All methods matching the arguments.
    -max(x, y) in Base at operators.jl:215
    -max(a, b, c, xs...) in Base at operators.jl:281

    Keywords are also displayed in the suggested methods, see second line after ; where limit and keep are keyword arguments:

    julia> split("1 1 1", [TAB]
    -split(str::AbstractString) in Base at strings/util.jl:278
    -split{T<:AbstractString}(str::T, splitter; limit, keep) in Base at strings/util.jl:254

    The completion of the methods uses type inference and can therefore see if the arguments match even if the arguments are output from functions. The function needs to be type stable for the completion to be able to remove non-matching methods.

    Tab completion can also help completing fields:

    julia> Pkg.a[TAB]
    -add       available

    Fields for output from functions can also be completed:

    julia> split("","")[1].[TAB]
    -endof  offset  string

    The completion of fields for output from functions uses type inference, and it can only suggest fields if the function is type stable.

    Customizing Colors

    The colors used by Julia and the REPL can be customized, as well. To change the color of the Julia prompt you can add something like the following to your .juliarc.jl file, which is to be placed inside your home directory:

    function customize_colors(repl)
    -    repl.prompt_color = Base.text_colors[:cyan]
    -end
    -
    -atreplinit(customize_colors)

    The available color keys can be seen by typing Base.text_colors in the help mode of the REPL. In addition, the integers 0 to 255 can be used as color keys for terminals with 256 color support.

    You can also change the colors for the help and shell prompts and input and answer text by setting the appropriate field of repl in the customize_colors function above (respectively, help_color, shell_color, input_color, and answer_color). For the latter two, be sure that the envcolors field is also set to false.

    It is also possible to apply boldface formatting by using Base.text_colors[:bold] as a color. For instance, to print answers in boldface font, one can use the following as a .juliarc.jl:

    function customize_colors(repl)
    -    repl.envcolors = false
    -    repl.answer_color = Base.text_colors[:bold]
    -end
    -
    -atreplinit(customize_colors)

    You can also customize the color used to render warning and informational messages by setting the appropriate environment variables. For instance, to render error, warning, and informational messages respectively in magenta, yellow, and cyan you can add the following to your .juliarc.jl file:

    ENV["JULIA_ERROR_COLOR"] = :magenta
    -ENV["JULIA_WARN_COLOR"] = :yellow
    -ENV["JULIA_INFO_COLOR"] = :cyan
    diff --git a/julia-0.6.3/share/doc/julia/html/en/manual/interfaces.html b/julia-0.6.3/share/doc/julia/html/en/manual/interfaces.html deleted file mode 100644 index 757d474..0000000 --- a/julia-0.6.3/share/doc/julia/html/en/manual/interfaces.html +++ /dev/null @@ -1,139 +0,0 @@ - -Interfaces · The Julia Language

    Interfaces

    Interfaces

    A lot of the power and extensibility in Julia comes from a collection of informal interfaces. By extending a few specific methods to work for a custom type, objects of that type not only receive those functionalities, but they are also able to be used in other methods that are written to generically build upon those behaviors.

    Iteration

    Required methods Brief description
    start(iter) Returns the initial iteration state
    next(iter, state) Returns the current item and the next state
    done(iter, state) Tests if there are any items remaining
    Important optional methodsDefault definitionBrief description
    iteratorsize(IterType)HasLength()One of HasLength(), HasShape(), IsInfinite(), or SizeUnknown() as appropriate
    iteratoreltype(IterType)HasEltype()Either EltypeUnknown() or HasEltype() as appropriate
    eltype(IterType)AnyThe type the items returned by next()
    length(iter)(undefined)The number of items, if known
    size(iter, [dim...])(undefined)The number of items in each dimension, if known
    Value returned by iteratorsize(IterType)Required Methods
    HasLength()length(iter)
    HasShape()length(iter) and size(iter, [dim...])
    IsInfinite()(none)
    SizeUnknown()(none)
    Value returned by iteratoreltype(IterType)Required Methods
    HasEltype()eltype(IterType)
    EltypeUnknown()(none)

    Sequential iteration is implemented by the methods start(), done(), and next(). Instead of mutating objects as they are iterated over, Julia provides these three methods to keep track of the iteration state externally from the object. The start(iter) method returns the initial state for the iterable object iter. That state gets passed along to done(iter, state), which tests if there are any elements remaining, and next(iter, state), which returns a tuple containing the current element and an updated state. The state object can be anything, and is generally considered to be an implementation detail private to the iterable object.

    Any object defines these three methods is iterable and can be used in the many functions that rely upon iteration. It can also be used directly in a for loop since the syntax:

    for i in iter   # or  "for i = iter"
    -    # body
    -end

    is translated into:

    state = start(iter)
    -while !done(iter, state)
    -    (i, state) = next(iter, state)
    -    # body
    -end

    A simple example is an iterable sequence of square numbers with a defined length:

    julia> struct Squares
    -           count::Int
    -       end
    -
    -julia> Base.start(::Squares) = 1
    -
    -julia> Base.next(S::Squares, state) = (state*state, state+1)
    -
    -julia> Base.done(S::Squares, state) = state > S.count
    -
    -julia> Base.eltype(::Type{Squares}) = Int # Note that this is defined for the type
    -
    -julia> Base.length(S::Squares) = S.count

    With only start, next, and done definitions, the Squares type is already pretty powerful. We can iterate over all the elements:

    julia> for i in Squares(7)
    -           println(i)
    -       end
    -1
    -4
    -9
    -16
    -25
    -36
    -49

    We can use many of the builtin methods that work with iterables, like in(), mean() and std():

    julia> 25 in Squares(10)
    -true
    -
    -julia> mean(Squares(100))
    -3383.5
    -
    -julia> std(Squares(100))
    -3024.355854282583

    There are a few more methods we can extend to give Julia more information about this iterable collection. We know that the elements in a Squares sequence will always be Int. By extending the eltype() method, we can give that information to Julia and help it make more specialized code in the more complicated methods. We also know the number of elements in our sequence, so we can extend length(), too.

    Now, when we ask Julia to collect() all the elements into an array it can preallocate a Vector{Int} of the right size instead of blindly push!ing each element into a Vector{Any}:

    julia> collect(Squares(10))' # transposed to save space
    -1×10 RowVector{Int64,Array{Int64,1}}:
    - 1  4  9  16  25  36  49  64  81  100

    While we can rely upon generic implementations, we can also extend specific methods where we know there is a simpler algorithm. For example, there's a formula to compute the sum of squares, so we can override the generic iterative version with a more performant solution:

    julia> Base.sum(S::Squares) = (n = S.count; return n*(n+1)*(2n+1)÷6)
    -
    -julia> sum(Squares(1803))
    -1955361914

    This is a very common pattern throughout the Julia standard library: a small set of required methods define an informal interface that enable many fancier behaviors. In some cases, types will want to additionally specialize those extra behaviors when they know a more efficient algorithm can be used in their specific case.

    Indexing

    Methods to implementBrief description
    getindex(X, i)X[i], indexed element access
    setindex!(X, v, i)X[i] = v, indexed assignment
    endof(X)The last index, used in X[end]

    For the Squares iterable above, we can easily compute the ith element of the sequence by squaring it. We can expose this as an indexing expression S[i]. To opt into this behavior, Squares simply needs to define getindex():

    julia> function Base.getindex(S::Squares, i::Int)
    -           1 <= i <= S.count || throw(BoundsError(S, i))
    -           return i*i
    -       end
    -
    -julia> Squares(100)[23]
    -529

    Additionally, to support the syntax S[end], we must define endof() to specify the last valid index:

    julia> Base.endof(S::Squares) = length(S)
    -
    -julia> Squares(23)[end]
    -529

    Note, though, that the above only defines getindex() with one integer index. Indexing with anything other than an Int will throw a MethodError saying that there was no matching method. In order to support indexing with ranges or vectors of Ints, separate methods must be written:

    julia> Base.getindex(S::Squares, i::Number) = S[convert(Int, i)]
    -
    -julia> Base.getindex(S::Squares, I) = [S[i] for i in I]
    -
    -julia> Squares(10)[[3,4.,5]]
    -3-element Array{Int64,1}:
    -  9
    - 16
    - 25

    While this is starting to support more of the indexing operations supported by some of the builtin types, there's still quite a number of behaviors missing. This Squares sequence is starting to look more and more like a vector as we've added behaviors to it. Instead of defining all these behaviors ourselves, we can officially define it as a subtype of an AbstractArray.

    Abstract Arrays

    Methods to implement Brief description
    size(A) Returns a tuple containing the dimensions of A
    getindex(A, i::Int) (if IndexLinear) Linear scalar indexing
    getindex(A, I::Vararg{Int, N}) (if IndexCartesian, where N = ndims(A)) N-dimensional scalar indexing
    setindex!(A, v, i::Int) (if IndexLinear) Scalar indexed assignment
    setindex!(A, v, I::Vararg{Int, N}) (if IndexCartesian, where N = ndims(A)) N-dimensional scalar indexed assignment
    Optional methodsDefault definitionBrief description
    IndexStyle(::Type)IndexCartesian()Returns either IndexLinear() or IndexCartesian(). See the description below.
    getindex(A, I...)defined in terms of scalar getindex()Multidimensional and nonscalar indexing
    setindex!(A, I...)defined in terms of scalar setindex!()Multidimensional and nonscalar indexed assignment
    start()/next()/done()defined in terms of scalar getindex()Iteration
    length(A)prod(size(A))Number of elements
    similar(A)similar(A, eltype(A), size(A))Return a mutable array with the same shape and element type
    similar(A, ::Type{S})similar(A, S, size(A))Return a mutable array with the same shape and the specified element type
    similar(A, dims::NTuple{Int})similar(A, eltype(A), dims)Return a mutable array with the same element type and size dims
    similar(A, ::Type{S}, dims::NTuple{Int})Array{S}(dims)Return a mutable array with the specified element type and size
    Non-traditional indicesDefault definitionBrief description
    indices(A)map(OneTo, size(A))Return the AbstractUnitRange of valid indices
    Base.similar(A, ::Type{S}, inds::NTuple{Ind})similar(A, S, Base.to_shape(inds))Return a mutable array with the specified indices inds (see below)
    Base.similar(T::Union{Type,Function}, inds)T(Base.to_shape(inds))Return an array similar to T with the specified indices inds (see below)

    If a type is defined as a subtype of AbstractArray, it inherits a very large set of rich behaviors including iteration and multidimensional indexing built on top of single-element access. See the arrays manual page and standard library section for more supported methods.

    A key part in defining an AbstractArray subtype is IndexStyle. Since indexing is such an important part of an array and often occurs in hot loops, it's important to make both indexing and indexed assignment as efficient as possible. Array data structures are typically defined in one of two ways: either it most efficiently accesses its elements using just one index (linear indexing) or it intrinsically accesses the elements with indices specified for every dimension. These two modalities are identified by Julia as IndexLinear() and IndexCartesian(). Converting a linear index to multiple indexing subscripts is typically very expensive, so this provides a traits-based mechanism to enable efficient generic code for all array types.

    This distinction determines which scalar indexing methods the type must define. IndexLinear() arrays are simple: just define getindex(A::ArrayType, i::Int). When the array is subsequently indexed with a multidimensional set of indices, the fallback getindex(A::AbstractArray, I...)() efficiently converts the indices into one linear index and then calls the above method. IndexCartesian() arrays, on the other hand, require methods to be defined for each supported dimensionality with ndims(A) Int indices. For example, the built-in SparseMatrixCSC type only supports two dimensions, so it just defines getindex(A::SparseMatrixCSC, i::Int, j::Int). The same holds for setindex!().

    Returning to the sequence of squares from above, we could instead define it as a subtype of an AbstractArray{Int, 1}:

    julia> struct SquaresVector <: AbstractArray{Int, 1}
    -           count::Int
    -       end
    -
    -julia> Base.size(S::SquaresVector) = (S.count,)
    -
    -julia> Base.IndexStyle(::Type{<:SquaresVector}) = IndexLinear()
    -
    -julia> Base.getindex(S::SquaresVector, i::Int) = i*i

    Note that it's very important to specify the two parameters of the AbstractArray; the first defines the eltype(), and the second defines the ndims(). That supertype and those three methods are all it takes for SquaresVector to be an iterable, indexable, and completely functional array:

    julia> s = SquaresVector(7)
    -7-element SquaresVector:
    -  1
    -  4
    -  9
    - 16
    - 25
    - 36
    - 49
    -
    -julia> s[s .> 20]
    -3-element Array{Int64,1}:
    - 25
    - 36
    - 49
    -
    -julia> s \ [1 2; 3 4; 5 6; 7 8; 9 10; 11 12; 13 14]
    -1×2 Array{Float64,2}:
    - 0.305389  0.335329
    -
    -julia> s ⋅ s # dot(s, s)
    -4676

    As a more complicated example, let's define our own toy N-dimensional sparse-like array type built on top of Dict:

    julia> struct SparseArray{T,N} <: AbstractArray{T,N}
    -           data::Dict{NTuple{N,Int}, T}
    -           dims::NTuple{N,Int}
    -       end
    -
    -julia> SparseArray{T}(::Type{T}, dims::Int...) = SparseArray(T, dims);
    -
    -julia> SparseArray{T,N}(::Type{T}, dims::NTuple{N,Int}) = SparseArray{T,N}(Dict{NTuple{N,Int}, T}(), dims);
    -
    -julia> Base.size(A::SparseArray) = A.dims
    -
    -julia> Base.similar(A::SparseArray, ::Type{T}, dims::Dims) where {T} = SparseArray(T, dims)
    -
    -julia> Base.getindex(A::SparseArray{T,N}, I::Vararg{Int,N}) where {T,N} = get(A.data, I, zero(T))
    -
    -julia> Base.setindex!(A::SparseArray{T,N}, v, I::Vararg{Int,N}) where {T,N} = (A.data[I] = v)

    Notice that this is an IndexCartesian array, so we must manually define getindex() and setindex!() at the dimensionality of the array. Unlike the SquaresVector, we are able to define setindex!(), and so we can mutate the array:

    julia> A = SparseArray(Float64, 3, 3)
    -3×3 SparseArray{Float64,2}:
    - 0.0  0.0  0.0
    - 0.0  0.0  0.0
    - 0.0  0.0  0.0
    -
    -julia> fill!(A, 2)
    -3×3 SparseArray{Float64,2}:
    - 2.0  2.0  2.0
    - 2.0  2.0  2.0
    - 2.0  2.0  2.0
    -
    -julia> A[:] = 1:length(A); A
    -3×3 SparseArray{Float64,2}:
    - 1.0  4.0  7.0
    - 2.0  5.0  8.0
    - 3.0  6.0  9.0

    The result of indexing an AbstractArray can itself be an array (for instance when indexing by a Range). The AbstractArray fallback methods use similar() to allocate an Array of the appropriate size and element type, which is filled in using the basic indexing method described above. However, when implementing an array wrapper you often want the result to be wrapped as well:

    julia> A[1:2,:]
    -2×3 SparseArray{Float64,2}:
    - 1.0  4.0  7.0
    - 2.0  5.0  8.0

    In this example it is accomplished by defining Base.similar{T}(A::SparseArray, ::Type{T}, dims::Dims) to create the appropriate wrapped array. (Note that while similar supports 1- and 2-argument forms, in most case you only need to specialize the 3-argument form.) For this to work it's important that SparseArray is mutable (supports setindex!). Defining similar(), getindex() and setindex!() for SparseArray also makes it possible to copy() the array:

    julia> copy(A)
    -3×3 SparseArray{Float64,2}:
    - 1.0  4.0  7.0
    - 2.0  5.0  8.0
    - 3.0  6.0  9.0

    In addition to all the iterable and indexable methods from above, these types can also interact with each other and use most of the methods defined in the standard library for AbstractArrays:

    julia> A[SquaresVector(3)]
    -3-element SparseArray{Float64,1}:
    - 1.0
    - 4.0
    - 9.0
    -
    -julia> dot(A[:,1],A[:,2])
    -32.0

    If you are defining an array type that allows non-traditional indexing (indices that start at something other than 1), you should specialize indices. You should also specialize similar so that the dims argument (ordinarily a Dims size-tuple) can accept AbstractUnitRange objects, perhaps range-types Ind of your own design. For more information, see Arrays with custom indices.

    diff --git a/julia-0.6.3/share/doc/julia/html/en/manual/introduction.html b/julia-0.6.3/share/doc/julia/html/en/manual/introduction.html deleted file mode 100644 index 43c81b5..0000000 --- a/julia-0.6.3/share/doc/julia/html/en/manual/introduction.html +++ /dev/null @@ -1,9 +0,0 @@ - -Introduction · The Julia Language

    Introduction

    Introduction

    Scientific computing has traditionally required the highest performance, yet domain experts have largely moved to slower dynamic languages for daily work. We believe there are many good reasons to prefer dynamic languages for these applications, and we do not expect their use to diminish. Fortunately, modern language design and compiler techniques make it possible to mostly eliminate the performance trade-off and provide a single environment productive enough for prototyping and efficient enough for deploying performance-intensive applications. The Julia programming language fills this role: it is a flexible dynamic language, appropriate for scientific and numerical computing, with performance comparable to traditional statically-typed languages.

    Because Julia's compiler is different from the interpreters used for languages like Python or R, you may find that Julia's performance is unintuitive at first. If you find that something is slow, we highly recommend reading through the Performance Tips section before trying anything else. Once you understand how Julia works, it's easy to write code that's nearly as fast as C.

    Julia features optional typing, multiple dispatch, and good performance, achieved using type inference and just-in-time (JIT) compilation, implemented using LLVM. It is multi-paradigm, combining features of imperative, functional, and object-oriented programming. Julia provides ease and expressiveness for high-level numerical computing, in the same way as languages such as R, MATLAB, and Python, but also supports general programming. To achieve this, Julia builds upon the lineage of mathematical programming languages, but also borrows much from popular dynamic languages, including Lisp, Perl, Python, Lua, and Ruby.

    The most significant departures of Julia from typical dynamic languages are:

    • The core language imposes very little; the standard library is written in Julia itself, including primitive operations like integer arithmetic

    • A rich language of types for constructing and describing objects, that can also optionally be used to make type declarations

    • The ability to define function behavior across many combinations of argument types via multiple dispatch

    • Automatic generation of efficient, specialized code for different argument types

    • Good performance, approaching that of statically-compiled languages like C

    Although one sometimes speaks of dynamic languages as being "typeless", they are definitely not: every object, whether primitive or user-defined, has a type. The lack of type declarations in most dynamic languages, however, means that one cannot instruct the compiler about the types of values, and often cannot explicitly talk about types at all. In static languages, on the other hand, while one can – and usually must – annotate types for the compiler, types exist only at compile time and cannot be manipulated or expressed at run time. In Julia, types are themselves run-time objects, and can also be used to convey information to the compiler.

    While the casual programmer need not explicitly use types or multiple dispatch, they are the core unifying features of Julia: functions are defined on different combinations of argument types, and applied by dispatching to the most specific matching definition. This model is a good fit for mathematical programming, where it is unnatural for the first argument to "own" an operation as in traditional object-oriented dispatch. Operators are just functions with special notation – to extend addition to new user-defined data types, you define new methods for the + function. Existing code then seamlessly applies to the new data types.

    Partly because of run-time type inference (augmented by optional type annotations), and partly because of a strong focus on performance from the inception of the project, Julia's computational efficiency exceeds that of other dynamic languages, and even rivals that of statically-compiled languages. For large scale numerical problems, speed always has been, continues to be, and probably always will be crucial: the amount of data being processed has easily kept pace with Moore's Law over the past decades.

    Julia aims to create an unprecedented combination of ease-of-use, power, and efficiency in a single language. In addition to the above, some advantages of Julia over comparable systems include:

    • Free and open source (MIT licensed)

    • User-defined types are as fast and compact as built-ins

    • No need to vectorize code for performance; devectorized code is fast

    • Designed for parallelism and distributed computation

    • Lightweight "green" threading (coroutines)

    • Unobtrusive yet powerful type system

    • Elegant and extensible conversions and promotions for numeric and other types

    • Efficient support for Unicode, including but not limited to UTF-8

    • Call C functions directly (no wrappers or special APIs needed)

    • Powerful shell-like capabilities for managing other processes

    • Lisp-like macros and other metaprogramming facilities

    diff --git a/julia-0.6.3/share/doc/julia/html/en/manual/linear-algebra.html b/julia-0.6.3/share/doc/julia/html/en/manual/linear-algebra.html deleted file mode 100644 index 68382fb..0000000 --- a/julia-0.6.3/share/doc/julia/html/en/manual/linear-algebra.html +++ /dev/null @@ -1,89 +0,0 @@ - -Linear algebra · The Julia Language

    Linear algebra

    Linear algebra

    In addition to (and as part of) its support for multi-dimensional arrays, Julia provides native implementations of many common and useful linear algebra operations. Basic operations, such as trace, det, and inv are all supported:

    julia> A = [1 2 3; 4 1 6; 7 8 1]
    -3×3 Array{Int64,2}:
    - 1  2  3
    - 4  1  6
    - 7  8  1
    -
    -julia> trace(A)
    -3
    -
    -julia> det(A)
    -104.0
    -
    -julia> inv(A)
    -3×3 Array{Float64,2}:
    - -0.451923   0.211538    0.0865385
    -  0.365385  -0.192308    0.0576923
    -  0.240385   0.0576923  -0.0673077

    As well as other useful operations, such as finding eigenvalues or eigenvectors:

    julia> A = [1.5 2 -4; 3 -1 -6; -10 2.3 4]
    -3×3 Array{Float64,2}:
    -   1.5   2.0  -4.0
    -   3.0  -1.0  -6.0
    - -10.0   2.3   4.0
    -
    -julia> eigvals(A)
    -3-element Array{Complex{Float64},1}:
    -  9.31908+0.0im
    - -2.40954+2.72095im
    - -2.40954-2.72095im
    -
    -julia> eigvecs(A)
    -3×3 Array{Complex{Float64},2}:
    - -0.488645+0.0im  0.182546-0.39813im   0.182546+0.39813im
    - -0.540358+0.0im  0.692926+0.0im       0.692926-0.0im
    -   0.68501+0.0im  0.254058-0.513301im  0.254058+0.513301im

    In addition, Julia provides many factorizations which can be used to speed up problems such as linear solve or matrix exponentiation by pre-factorizing a matrix into a form more amenable (for performance or memory reasons) to the problem. See the documentation on factorize for more information. As an example:

    julia> A = [1.5 2 -4; 3 -1 -6; -10 2.3 4]
    -3×3 Array{Float64,2}:
    -   1.5   2.0  -4.0
    -   3.0  -1.0  -6.0
    - -10.0   2.3   4.0
    -
    -julia> factorize(A)
    -Base.LinAlg.LU{Float64,Array{Float64,2}} with factors L and U:
    -[1.0 0.0 0.0; -0.15 1.0 0.0; -0.3 -0.132196 1.0]
    -[-10.0 2.3 4.0; 0.0 2.345 -3.4; 0.0 0.0 -5.24947]

    Since A is not Hermitian, symmetric, triangular, tridiagonal, or bidiagonal, an LU factorization may be the best we can do. Compare with:

    julia> B = [1.5 2 -4; 2 -1 -3; -4 -3 5]
    -3×3 Array{Float64,2}:
    -  1.5   2.0  -4.0
    -  2.0  -1.0  -3.0
    - -4.0  -3.0   5.0
    -
    -julia> factorize(B)
    -Base.LinAlg.BunchKaufman{Float64,Array{Float64,2}}([-1.64286 0.142857 -0.8; 2.0 -2.8 -0.6; -4.0 -3.0 5.0], [1, 2, 3], 'U', true, false, 0)

    Here, Julia was able to detect that B is in fact symmetric, and used a more appropriate factorization. Often it's possible to write more efficient code for a matrix that is known to have certain properties e.g. it is symmetric, or tridiagonal. Julia provides some special types so that you can "tag" matrices as having these properties. For instance:

    julia> B = [1.5 2 -4; 2 -1 -3; -4 -3 5]
    -3×3 Array{Float64,2}:
    -  1.5   2.0  -4.0
    -  2.0  -1.0  -3.0
    - -4.0  -3.0   5.0
    -
    -julia> sB = Symmetric(B)
    -3×3 Symmetric{Float64,Array{Float64,2}}:
    -  1.5   2.0  -4.0
    -  2.0  -1.0  -3.0
    - -4.0  -3.0   5.0

    sB has been tagged as a matrix that's (real) symmetric, so for later operations we might perform on it, such as eigenfactorization or computing matrix-vector products, efficiencies can be found by only referencing half of it. For example:

    julia> B = [1.5 2 -4; 2 -1 -3; -4 -3 5]
    -3×3 Array{Float64,2}:
    -  1.5   2.0  -4.0
    -  2.0  -1.0  -3.0
    - -4.0  -3.0   5.0
    -
    -julia> sB = Symmetric(B)
    -3×3 Symmetric{Float64,Array{Float64,2}}:
    -  1.5   2.0  -4.0
    -  2.0  -1.0  -3.0
    - -4.0  -3.0   5.0
    -
    -julia> x = [1; 2; 3]
    -3-element Array{Int64,1}:
    - 1
    - 2
    - 3
    -
    -julia> sB\x
    -3-element Array{Float64,1}:
    - -1.73913
    - -1.1087
    - -1.45652

    The \ operation here performs the linear solution. Julia's parser provides convenient dispatch to specialized methods for the transpose of a matrix left-divided by a vector, or for the various combinations of transpose operations in matrix-matrix solutions. Many of these are further specialized for certain special matrix types. For example, A\B will end up calling Base.LinAlg.A_ldiv_B! while A'\B will end up calling Base.LinAlg.Ac_ldiv_B, even though we used the same left-division operator. This works for matrices too: A.'\B.' would call Base.LinAlg.At_ldiv_Bt. The left-division operator is pretty powerful and it's easy to write compact, readable code that is flexible enough to solve all sorts of systems of linear equations.

    Special matrices

    Matrices with special symmetries and structures arise often in linear algebra and are frequently associated with various matrix factorizations. Julia features a rich collection of special matrix types, which allow for fast computation with specialized routines that are specially developed for particular matrix types.

    The following tables summarize the types of special matrices that have been implemented in Julia, as well as whether hooks to various optimized methods for them in LAPACK are available.

    TypeDescription
    HermitianHermitian matrix
    UpperTriangularUpper triangular matrix
    LowerTriangularLower triangular matrix
    TridiagonalTridiagonal matrix
    SymTridiagonalSymmetric tridiagonal matrix
    BidiagonalUpper/lower bidiagonal matrix
    DiagonalDiagonal matrix
    UniformScalingUniform scaling operator

    Elementary operations

    Matrix type+-*\Other functions with optimized methods
    Hermitian   MVinv(), sqrtm(), expm()
    UpperTriangular  MVMVinv(), det()
    LowerTriangular  MVMVinv(), det()
    SymTridiagonalMMMSMVeigmax(), eigmin()
    TridiagonalMMMSMV 
    BidiagonalMMMSMV 
    DiagonalMMMVMVinv(), det(), logdet(), /()
    UniformScalingMMMVSMVS/()

    Legend:

    KeyDescription
    M (matrix)An optimized method for matrix-matrix operations is available
    V (vector)An optimized method for matrix-vector operations is available
    S (scalar)An optimized method for matrix-scalar operations is available

    Matrix factorizations

    Matrix typeLAPACKeig()eigvals()eigvecs()svd()svdvals()
    HermitianHE ARI   
    UpperTriangularTRAAA  
    LowerTriangularTRAAA  
    SymTridiagonalSTAARIAV  
    TridiagonalGT     
    BidiagonalBD   AA
    DiagonalDI A   

    Legend:

    KeyDescriptionExample
    A (all)An optimized method to find all the characteristic values and/or vectors is availablee.g. eigvals(M)
    R (range)An optimized method to find the ilth through the ihth characteristic values are availableeigvals(M, il, ih)
    I (interval)An optimized method to find the characteristic values in the interval [vl, vh] is availableeigvals(M, vl, vh)
    V (vectors)An optimized method to find the characteristic vectors corresponding to the characteristic values x=[x1, x2,...] is availableeigvecs(M, x)

    The uniform scaling operator

    A UniformScaling operator represents a scalar times the identity operator, λ*I. The identity operator I is defined as a constant and is an instance of UniformScaling. The size of these operators are generic and match the other matrix in the binary operations +, -, * and \. For A+I and A-I this means that A must be square. Multiplication with the identity operator I is a noop (except for checking that the scaling factor is one) and therefore almost without overhead.

    Matrix factorizations

    Matrix factorizations (a.k.a. matrix decompositions) compute the factorization of a matrix into a product of matrices, and are one of the central concepts in linear algebra.

    The following table summarizes the types of matrix factorizations that have been implemented in Julia. Details of their associated methods can be found in the Linear Algebra section of the standard library documentation.

    TypeDescription
    CholeskyCholesky factorization
    CholeskyPivotedPivoted Cholesky factorization
    LULU factorization
    LUTridiagonalLU factorization for Tridiagonal matrices
    UmfpackLULU factorization for sparse matrices (computed by UMFPack)
    QRQR factorization
    QRCompactWYCompact WY form of the QR factorization
    QRPivotedPivoted QR factorization
    HessenbergHessenberg decomposition
    EigenSpectral decomposition
    SVDSingular value decomposition
    GeneralizedSVDGeneralized SVD
    diff --git a/julia-0.6.3/share/doc/julia/html/en/manual/mathematical-operations.html b/julia-0.6.3/share/doc/julia/html/en/manual/mathematical-operations.html deleted file mode 100644 index db1fdd0..0000000 --- a/julia-0.6.3/share/doc/julia/html/en/manual/mathematical-operations.html +++ /dev/null @@ -1,164 +0,0 @@ - -Mathematical Operations and Elementary Functions · The Julia Language

    Mathematical Operations and Elementary Functions

    Mathematical Operations and Elementary Functions

    Julia provides a complete collection of basic arithmetic and bitwise operators across all of its numeric primitive types, as well as providing portable, efficient implementations of a comprehensive collection of standard mathematical functions.

    Arithmetic Operators

    The following arithmetic operators are supported on all primitive numeric types:

    ExpressionNameDescription
    +xunary plusthe identity operation
    -xunary minusmaps values to their additive inverses
    x + ybinary plusperforms addition
    x - ybinary minusperforms subtraction
    x * ytimesperforms multiplication
    x / ydivideperforms division
    x \ yinverse divideequivalent to y / x
    x ^ ypowerraises x to the yth power
    x % yremainderequivalent to rem(x,y)

    as well as the negation on Bool types:

    ExpressionNameDescription
    !xnegationchanges true to false and vice versa

    Julia's promotion system makes arithmetic operations on mixtures of argument types "just work" naturally and automatically. See Conversion and Promotion for details of the promotion system.

    Here are some simple examples using arithmetic operators:

    julia> 1 + 2 + 3
    -6
    -
    -julia> 1 - 2
    --1
    -
    -julia> 3*2/12
    -0.5

    (By convention, we tend to space operators more tightly if they get applied before other nearby operators. For instance, we would generally write -x + 2 to reflect that first x gets negated, and then 2 is added to that result.)

    Bitwise Operators

    The following bitwise operators are supported on all primitive integer types:

    ExpressionName
    ~xbitwise not
    x & ybitwise and
    x | ybitwise or
    x ⊻ ybitwise xor (exclusive or)
    x >>> ylogical shift right
    x >> yarithmetic shift right
    x << ylogical/arithmetic shift left

    Here are some examples with bitwise operators:

    julia> ~123
    --124
    -
    -julia> 123 & 234
    -106
    -
    -julia> 123 | 234
    -251
    -
    -julia> 123 ⊻ 234
    -145
    -
    -julia> xor(123, 234)
    -145
    -
    -julia> ~UInt32(123)
    -0xffffff84
    -
    -julia> ~UInt8(123)
    -0x84

    Updating operators

    Every binary arithmetic and bitwise operator also has an updating version that assigns the result of the operation back into its left operand. The updating version of the binary operator is formed by placing a = immediately after the operator. For example, writing x += 3 is equivalent to writing x = x + 3:

    julia> x = 1
    -1
    -
    -julia> x += 3
    -4
    -
    -julia> x
    -4

    The updating versions of all the binary arithmetic and bitwise operators are:

    +=  -=  *=  /=  \=  ÷=  %=  ^=  &=  |=  ⊻=  >>>=  >>=  <<=
    Note

    An updating operator rebinds the variable on the left-hand side. As a result, the type of the variable may change.

    julia> x = 0x01; typeof(x)
    -UInt8
    -
    -julia> x *= 2 # Same as x = x * 2
    -2
    -
    -julia> typeof(x)
    -Int64

    Vectorized "dot" operators

    For every binary operation like ^, there is a corresponding "dot" operation .^ that is automatically defined to perform ^ element-by-element on arrays. For example, [1,2,3] ^ 3 is not defined, since there is no standard mathematical meaning to "cubing" an array, but [1,2,3] .^ 3 is defined as computing the elementwise (or "vectorized") result [1^3, 2^3, 3^3]. Similarly for unary operators like ! or , there is a corresponding .√ that applies the operator elementwise.

    julia> [1,2,3] .^ 3
    -3-element Array{Int64,1}:
    -  1
    -  8
    - 27

    More specifically, a .^ b is parsed as the "dot" call (^).(a,b), which performs a broadcast operation: it can combine arrays and scalars, arrays of the same size (performing the operation elementwise), and even arrays of different shapes (e.g. combining row and column vectors to produce a matrix). Moreover, like all vectorized "dot calls," these "dot operators" are fusing. For example, if you compute 2 .* A.^2 .+ sin.(A) (or equivalently @. 2A^2 + sin(A), using the @. macro) for an array A, it performs a single loop over A, computing 2a^2 + sin(a) for each element of A. In particular, nested dot calls like f.(g.(x)) are fused, and "adjacent" binary operators like x .+ 3 .* x.^2 are equivalent to nested dot calls (+).(x, (*).(3, (^).(x, 2))).

    Furthermore, "dotted" updating operators like a .+= b (or @. a += b) are parsed as a .= a .+ b, where .= is a fused in-place assignment operation (see the dot syntax documentation).

    Note the dot syntax is also applicable to user-defined operators. For example, if you define ⊗(A,B) = kron(A,B) to give a convenient infix syntax A ⊗ B for Kronecker products (kron), then [A,B] .⊗ [C,D] will compute [A⊗C, B⊗D] with no additional coding.

    Numeric Comparisons

    Standard comparison operations are defined for all the primitive numeric types:

    OperatorName
    ==equality
    !=, inequality
    <less than
    <=, less than or equal to
    >greater than
    >=, greater than or equal to

    Here are some simple examples:

    julia> 1 == 1
    -true
    -
    -julia> 1 == 2
    -false
    -
    -julia> 1 != 2
    -true
    -
    -julia> 1 == 1.0
    -true
    -
    -julia> 1 < 2
    -true
    -
    -julia> 1.0 > 3
    -false
    -
    -julia> 1 >= 1.0
    -true
    -
    -julia> -1 <= 1
    -true
    -
    -julia> -1 <= -1
    -true
    -
    -julia> -1 <= -2
    -false
    -
    -julia> 3 < -0.5
    -false

    Integers are compared in the standard manner – by comparison of bits. Floating-point numbers are compared according to the IEEE 754 standard:

    • Finite numbers are ordered in the usual manner.

    • Positive zero is equal but not greater than negative zero.

    • Inf is equal to itself and greater than everything else except NaN.

    • -Inf is equal to itself and less then everything else except NaN.

    • NaN is not equal to, not less than, and not greater than anything, including itself.

    The last point is potentially surprising and thus worth noting:

    julia> NaN == NaN
    -false
    -
    -julia> NaN != NaN
    -true
    -
    -julia> NaN < NaN
    -false
    -
    -julia> NaN > NaN
    -false

    and can cause especial headaches with Arrays:

    julia> [1 NaN] == [1 NaN]
    -false

    Julia provides additional functions to test numbers for special values, which can be useful in situations like hash key comparisons:

    FunctionTests if
    isequal(x, y)x and y are identical
    isfinite(x)x is a finite number
    isinf(x)x is infinite
    isnan(x)x is not a number

    isequal() considers NaNs equal to each other:

    julia> isequal(NaN, NaN)
    -true
    -
    -julia> isequal([1 NaN], [1 NaN])
    -true
    -
    -julia> isequal(NaN, NaN32)
    -true

    isequal() can also be used to distinguish signed zeros:

    julia> -0.0 == 0.0
    -true
    -
    -julia> isequal(-0.0, 0.0)
    -false

    Mixed-type comparisons between signed integers, unsigned integers, and floats can be tricky. A great deal of care has been taken to ensure that Julia does them correctly.

    For other types, isequal() defaults to calling ==(), so if you want to define equality for your own types then you only need to add a ==() method. If you define your own equality function, you should probably define a corresponding hash() method to ensure that isequal(x,y) implies hash(x) == hash(y).

    Chaining comparisons

    Unlike most languages, with the notable exception of Python, comparisons can be arbitrarily chained:

    julia> 1 < 2 <= 2 < 3 == 3 > 2 >= 1 == 1 < 3 != 5
    -true

    Chaining comparisons is often quite convenient in numerical code. Chained comparisons use the && operator for scalar comparisons, and the & operator for elementwise comparisons, which allows them to work on arrays. For example, 0 .< A .< 1 gives a boolean array whose entries are true where the corresponding elements of A are between 0 and 1.

    Note the evaluation behavior of chained comparisons:

    julia> v(x) = (println(x); x)
    -v (generic function with 1 method)
    -
    -julia> v(1) < v(2) <= v(3)
    -2
    -1
    -3
    -true
    -
    -julia> v(1) > v(2) <= v(3)
    -2
    -1
    -false

    The middle expression is only evaluated once, rather than twice as it would be if the expression were written as v(1) < v(2) && v(2) <= v(3). However, the order of evaluations in a chained comparison is undefined. It is strongly recommended not to use expressions with side effects (such as printing) in chained comparisons. If side effects are required, the short-circuit && operator should be used explicitly (see Short-Circuit Evaluation).

    Elementary Functions

    Julia provides a comprehensive collection of mathematical functions and operators. These mathematical operations are defined over as broad a class of numerical values as permit sensible definitions, including integers, floating-point numbers, rationals, and complex numbers, wherever such definitions make sense.

    Moreover, these functions (like any Julia function) can be applied in "vectorized" fashion to arrays and other collections with the dot syntax f.(A), e.g. sin.(A) will compute the sine of each element of an array A.

    Operator Precedence

    Julia applies the following order of operations, from highest precedence to lowest:

    CategoryOperators
    Syntax. followed by ::
    Exponentiation^
    Fractions//
    Multiplication* / % & \
    Bitshifts<< >> >>>
    Addition+ - | ⊻
    Syntax: .. followed by |>
    Comparisons> < >= <= == === != !== <:
    Control flow&& followed by || followed by ?
    Assignments= += -= *= /= //= \= ^= ÷= %= |= &= ⊻= <<= >>= >>>=

    For a complete list of every Julia operator's precedence, see the top of this file: src/julia-parser.scm

    You can also find the numerical precedence for any given operator via the built-in function Base.operator_precedence, where higher numbers take precedence:

    julia> Base.operator_precedence(:+), Base.operator_precedence(:*), Base.operator_precedence(:.)
    -(9, 11, 15)
    -
    -julia> Base.operator_precedence(:+=), Base.operator_precedence(:(=))  # (Note the necessary parens on `:(=)`)
    -(1, 1)

    Numerical Conversions

    Julia supports three forms of numerical conversion, which differ in their handling of inexact conversions.

    • The notation T(x) or convert(T,x) converts x to a value of type T.

      • If T is a floating-point type, the result is the nearest representable value, which could be positive or negative infinity.

      • If T is an integer type, an InexactError is raised if x is not representable by T.

    • x % T converts an integer x to a value of integer type T congruent to x modulo 2^n, where n is the number of bits in T. In other words, the binary representation is truncated to fit.

    • The Rounding functions take a type T as an optional argument. For example, round(Int,x) is a shorthand for Int(round(x)).

    The following examples show the different forms.

    julia> Int8(127)
    -127
    -
    -julia> Int8(128)
    -ERROR: InexactError()
    -Stacktrace:
    - [1] Int8(::Int64) at ./sysimg.jl:77
    -
    -julia> Int8(127.0)
    -127
    -
    -julia> Int8(3.14)
    -ERROR: InexactError()
    -Stacktrace:
    - [1] convert(::Type{Int8}, ::Float64) at ./float.jl:658
    - [2] Int8(::Float64) at ./sysimg.jl:77
    -
    -julia> Int8(128.0)
    -ERROR: InexactError()
    -Stacktrace:
    - [1] convert(::Type{Int8}, ::Float64) at ./float.jl:658
    - [2] Int8(::Float64) at ./sysimg.jl:77
    -
    -julia> 127 % Int8
    -127
    -
    -julia> 128 % Int8
    --128
    -
    -julia> round(Int8,127.4)
    -127
    -
    -julia> round(Int8,127.6)
    -ERROR: InexactError()
    -Stacktrace:
    - [1] trunc(::Type{Int8}, ::Float64) at ./float.jl:651
    - [2] round(::Type{Int8}, ::Float64) at ./float.jl:337

    See Conversion and Promotion for how to define your own conversions and promotions.

    Rounding functions

    FunctionDescriptionReturn type
    round(x)round x to the nearest integertypeof(x)
    round(T, x)round x to the nearest integerT
    floor(x)round x towards -Inftypeof(x)
    floor(T, x)round x towards -InfT
    ceil(x)round x towards +Inftypeof(x)
    ceil(T, x)round x towards +InfT
    trunc(x)round x towards zerotypeof(x)
    trunc(T, x)round x towards zeroT

    Division functions

    FunctionDescription
    div(x,y)truncated division; quotient rounded towards zero
    fld(x,y)floored division; quotient rounded towards -Inf
    cld(x,y)ceiling division; quotient rounded towards +Inf
    rem(x,y)remainder; satisfies x == div(x,y)*y + rem(x,y); sign matches x
    mod(x,y)modulus; satisfies x == fld(x,y)*y + mod(x,y); sign matches y
    mod1(x,y)mod() with offset 1; returns r∈(0,y] for y>0 or r∈[y,0) for y<0, where mod(r, y) == mod(x, y)
    mod2pi(x)modulus with respect to 2pi; 0 <= mod2pi(x)   < 2pi
    divrem(x,y)returns (div(x,y),rem(x,y))
    fldmod(x,y)returns (fld(x,y),mod(x,y))
    gcd(x,y...)greatest positive common divisor of x, y,...
    lcm(x,y...)least positive common multiple of x, y,...

    Sign and absolute value functions

    FunctionDescription
    abs(x)a positive value with the magnitude of x
    abs2(x)the squared magnitude of x
    sign(x)indicates the sign of x, returning -1, 0, or +1
    signbit(x)indicates whether the sign bit is on (true) or off (false)
    copysign(x,y)a value with the magnitude of x and the sign of y
    flipsign(x,y)a value with the magnitude of x and the sign of x*y

    Powers, logs and roots

    FunctionDescription
    sqrt(x), √xsquare root of x
    cbrt(x), ∛xcube root of x
    hypot(x,y)hypotenuse of right-angled triangle with other sides of length x and y
    exp(x)natural exponential function at x
    expm1(x)accurate exp(x)-1 for x near zero
    ldexp(x,n)x*2^n computed efficiently for integer values of n
    log(x)natural logarithm of x
    log(b,x)base b logarithm of x
    log2(x)base 2 logarithm of x
    log10(x)base 10 logarithm of x
    log1p(x)accurate log(1+x) for x near zero
    exponent(x)binary exponent of x
    significand(x)binary significand (a.k.a. mantissa) of a floating-point number x

    For an overview of why functions like hypot(), expm1(), and log1p() are necessary and useful, see John D. Cook's excellent pair of blog posts on the subject: expm1, log1p, erfc, and hypot.

    Trigonometric and hyperbolic functions

    All the standard trigonometric and hyperbolic functions are also defined:

    sin    cos    tan    cot    sec    csc
    -sinh   cosh   tanh   coth   sech   csch
    -asin   acos   atan   acot   asec   acsc
    -asinh  acosh  atanh  acoth  asech  acsch
    -sinc   cosc   atan2

    These are all single-argument functions, with the exception of atan2, which gives the angle in radians between the x-axis and the point specified by its arguments, interpreted as x and y coordinates.

    Additionally, sinpi(x) and cospi(x) are provided for more accurate computations of sin(pi*x) and cos(pi*x) respectively.

    In order to compute trigonometric functions with degrees instead of radians, suffix the function with d. For example, sind(x) computes the sine of x where x is specified in degrees. The complete list of trigonometric functions with degree variants is:

    sind   cosd   tand   cotd   secd   cscd
    -asind  acosd  atand  acotd  asecd  acscd

    Special functions

    FunctionDescription
    gamma(x)gamma function at x
    lgamma(x)accurate log(gamma(x)) for large x
    lfact(x)accurate log(factorial(x)) for large x; same as lgamma(x+1) for x > 1, zero otherwise
    beta(x,y)beta function at x,y
    lbeta(x,y)accurate log(beta(x,y)) for large x or y
    diff --git a/julia-0.6.3/share/doc/julia/html/en/manual/metaprogramming.html b/julia-0.6.3/share/doc/julia/html/en/manual/metaprogramming.html deleted file mode 100644 index 27195c4..0000000 --- a/julia-0.6.3/share/doc/julia/html/en/manual/metaprogramming.html +++ /dev/null @@ -1,369 +0,0 @@ - -Metaprogramming · The Julia Language

    Metaprogramming

    Metaprogramming

    The strongest legacy of Lisp in the Julia language is its metaprogramming support. Like Lisp, Julia represents its own code as a data structure of the language itself. Since code is represented by objects that can be created and manipulated from within the language, it is possible for a program to transform and generate its own code. This allows sophisticated code generation without extra build steps, and also allows true Lisp-style macros operating at the level of abstract syntax trees. In contrast, preprocessor "macro" systems, like that of C and C++, perform textual manipulation and substitution before any actual parsing or interpretation occurs. Because all data types and code in Julia are represented by Julia data structures, powerful reflection capabilities are available to explore the internals of a program and its types just like any other data.

    Program representation

    Every Julia program starts life as a string:

    julia> prog = "1 + 1"
    -"1 + 1"

    What happens next?

    The next step is to parse each string into an object called an expression, represented by the Julia type Expr:

    julia> ex1 = parse(prog)
    -:(1 + 1)
    -
    -julia> typeof(ex1)
    -Expr

    Expr objects contain two parts:

    • a Symbol identifying the kind of expression. A symbol is an interned string identifier (more discussion below).

    julia> ex1.head
    -:call
    • the expression arguments, which may be symbols, other expressions, or literal values:

    julia> ex1.args
    -3-element Array{Any,1}:
    -  :+
    - 1
    - 1

    Expressions may also be constructed directly in prefix notation:

    julia> ex2 = Expr(:call, :+, 1, 1)
    -:(1 + 1)

    The two expressions constructed above – by parsing and by direct construction – are equivalent:

    julia> ex1 == ex2
    -true

    The key point here is that Julia code is internally represented as a data structure that is accessible from the language itself.

    The dump() function provides indented and annotated display of Expr objects:

    julia> dump(ex2)
    -Expr
    -  head: Symbol call
    -  args: Array{Any}((3,))
    -    1: Symbol +
    -    2: Int64 1
    -    3: Int64 1
    -  typ: Any

    Expr objects may also be nested:

    julia> ex3 = parse("(4 + 4) / 2")
    -:((4 + 4) / 2)

    Another way to view expressions is with Meta.show_sexpr, which displays the S-expression form of a given Expr, which may look very familiar to users of Lisp. Here's an example illustrating the display on a nested Expr:

    julia> Meta.show_sexpr(ex3)
    -(:call, :/, (:call, :+, 4, 4), 2)

    Symbols

    The : character has two syntactic purposes in Julia. The first form creates a Symbol, an interned string used as one building-block of expressions:

    julia> :foo
    -:foo
    -
    -julia> typeof(ans)
    -Symbol

    The Symbol constructor takes any number of arguments and creates a new symbol by concatenating their string representations together:

    julia> :foo == Symbol("foo")
    -true
    -
    -julia> Symbol("func",10)
    -:func10
    -
    -julia> Symbol(:var,'_',"sym")
    -:var_sym

    In the context of an expression, symbols are used to indicate access to variables; when an expression is evaluated, a symbol is replaced with the value bound to that symbol in the appropriate scope.

    Sometimes extra parentheses around the argument to : are needed to avoid ambiguity in parsing.:

    julia> :(:)
    -:(:)
    -
    -julia> :(::)
    -:(::)

    Expressions and evaluation

    Quoting

    The second syntactic purpose of the : character is to create expression objects without using the explicit Expr constructor. This is referred to as quoting. The : character, followed by paired parentheses around a single statement of Julia code, produces an Expr object based on the enclosed code. Here is example of the short form used to quote an arithmetic expression:

    julia> ex = :(a+b*c+1)
    -:(a + b * c + 1)
    -
    -julia> typeof(ex)
    -Expr

    (to view the structure of this expression, try ex.head and ex.args, or use dump() as above)

    Note that equivalent expressions may be constructed using parse() or the direct Expr form:

    julia>      :(a + b*c + 1)  ==
    -       parse("a + b*c + 1") ==
    -       Expr(:call, :+, :a, Expr(:call, :*, :b, :c), 1)
    -true

    Expressions provided by the parser generally only have symbols, other expressions, and literal values as their args, whereas expressions constructed by Julia code can have arbitrary run-time values without literal forms as args. In this specific example, + and a are symbols, *(b,c) is a subexpression, and 1 is a literal 64-bit signed integer.

    There is a second syntactic form of quoting for multiple expressions: blocks of code enclosed in quote ... end. Note that this form introduces QuoteNode elements to the expression tree, which must be considered when directly manipulating an expression tree generated from quote blocks. For other purposes, :( ... ) and quote .. end blocks are treated identically.

    julia> ex = quote
    -           x = 1
    -           y = 2
    -           x + y
    -       end
    -quote  # none, line 2:
    -    x = 1 # none, line 3:
    -    y = 2 # none, line 4:
    -    x + y
    -end
    -
    -julia> typeof(ex)
    -Expr

    Interpolation

    Direct construction of Expr objects with value arguments is powerful, but Expr constructors can be tedious compared to "normal" Julia syntax. As an alternative, Julia allows "splicing" or interpolation of literals or expressions into quoted expressions. Interpolation is indicated by the $ prefix.

    In this example, the literal value of a is interpolated:

    julia> a = 1;
    -
    -julia> ex = :($a + b)
    -:(1 + b)

    Interpolating into an unquoted expression is not supported and will cause a compile-time error:

    julia> $a + b
    -ERROR: unsupported or misplaced expression $
    - ...

    In this example, the tuple (1,2,3) is interpolated as an expression into a conditional test:

    julia> ex = :(a in $:((1,2,3)) )
    -:(a in (1, 2, 3))

    Interpolating symbols into a nested expression requires enclosing each symbol in an enclosing quote block:

    julia> :( :a in $( :(:a + :b) ) )
    -                   ^^^^^^^^^^
    -                   quoted inner expression

    The use of $ for expression interpolation is intentionally reminiscent of string interpolation and command interpolation. Expression interpolation allows convenient, readable programmatic construction of complex Julia expressions.

    eval() and effects

    Given an expression object, one can cause Julia to evaluate (execute) it at global scope using eval():

    julia> :(1 + 2)
    -:(1 + 2)
    -
    -julia> eval(ans)
    -3
    -
    -julia> ex = :(a + b)
    -:(a + b)
    -
    -julia> eval(ex)
    -ERROR: UndefVarError: b not defined
    -[...]
    -
    -julia> a = 1; b = 2;
    -
    -julia> eval(ex)
    -3

    Every module has its own eval() function that evaluates expressions in its global scope. Expressions passed to eval() are not limited to returning values – they can also have side-effects that alter the state of the enclosing module's environment:

    julia> ex = :(x = 1)
    -:(x = 1)
    -
    -julia> x
    -ERROR: UndefVarError: x not defined
    -
    -julia> eval(ex)
    -1
    -
    -julia> x
    -1

    Here, the evaluation of an expression object causes a value to be assigned to the global variable x.

    Since expressions are just Expr objects which can be constructed programmatically and then evaluated, it is possible to dynamically generate arbitrary code which can then be run using eval(). Here is a simple example:

    julia> a = 1;
    -
    -julia> ex = Expr(:call, :+, a, :b)
    -:(1 + b)
    -
    -julia> a = 0; b = 2;
    -
    -julia> eval(ex)
    -3

    The value of a is used to construct the expression ex which applies the + function to the value 1 and the variable b. Note the important distinction between the way a and b are used:

    • The value of the variablea at expression construction time is used as an immediate value in the expression. Thus, the value of a when the expression is evaluated no longer matters: the value in the expression is already 1, independent of whatever the value of a might be.

    • On the other hand, the symbol:b is used in the expression construction, so the value of the variable b at that time is irrelevant – :b is just a symbol and the variable b need not even be defined. At expression evaluation time, however, the value of the symbol :b is resolved by looking up the value of the variable b.

    Functions on Expressions

    As hinted above, one extremely useful feature of Julia is the capability to generate and manipulate Julia code within Julia itself. We have already seen one example of a function returning Expr objects: the parse() function, which takes a string of Julia code and returns the corresponding Expr. A function can also take one or more Expr objects as arguments, and return another Expr. Here is a simple, motivating example:

    julia> function math_expr(op, op1, op2)
    -           expr = Expr(:call, op, op1, op2)
    -           return expr
    -       end
    -math_expr (generic function with 1 method)
    -
    -julia>  ex = math_expr(:+, 1, Expr(:call, :*, 4, 5))
    -:(1 + 4 * 5)
    -
    -julia> eval(ex)
    -21

    As another example, here is a function that doubles any numeric argument, but leaves expressions alone:

    julia> function make_expr2(op, opr1, opr2)
    -           opr1f, opr2f = map(x -> isa(x, Number) ? 2*x : x, (opr1, opr2))
    -           retexpr = Expr(:call, op, opr1f, opr2f)
    -           return retexpr
    -       end
    -make_expr2 (generic function with 1 method)
    -
    -julia> make_expr2(:+, 1, 2)
    -:(2 + 4)
    -
    -julia> ex = make_expr2(:+, 1, Expr(:call, :*, 5, 8))
    -:(2 + 5 * 8)
    -
    -julia> eval(ex)
    -42

    Macros

    Macros provide a method to include generated code in the final body of a program. A macro maps a tuple of arguments to a returned expression, and the resulting expression is compiled directly rather than requiring a runtime eval() call. Macro arguments may include expressions, literal values, and symbols.

    Basics

    Here is an extraordinarily simple macro:

    julia> macro sayhello()
    -           return :( println("Hello, world!") )
    -       end
    -@sayhello (macro with 1 method)

    Macros have a dedicated character in Julia's syntax: the @ (at-sign), followed by the unique name declared in a macro NAME ... end block. In this example, the compiler will replace all instances of @sayhello with:

    :( println("Hello, world!") )

    When @sayhello is entered in the REPL, the expression executes immediately, thus we only see the evaluation result:

    julia> @sayhello()
    -Hello, world!

    Now, consider a slightly more complex macro:

    julia> macro sayhello(name)
    -           return :( println("Hello, ", $name) )
    -       end
    -@sayhello (macro with 1 method)

    This macro takes one argument: name. When @sayhello is encountered, the quoted expression is expanded to interpolate the value of the argument into the final expression:

    julia> @sayhello("human")
    -Hello, human

    We can view the quoted return expression using the function macroexpand() (important note: this is an extremely useful tool for debugging macros):

    julia> ex = macroexpand( :(@sayhello("human")) )
    -:((println)("Hello, ", "human"))
    -
    -julia> typeof(ex)
    -Expr

    We can see that the "human" literal has been interpolated into the expression.

    There also exists a macro @macroexpand that is perhaps a bit more convenient than the macroexpand function:

    julia> @macroexpand @sayhello "human"
    -:((println)("Hello, ", "human"))

    Hold up: why macros?

    We have already seen a function f(::Expr...) -> Expr in a previous section. In fact, macroexpand() is also such a function. So, why do macros exist?

    Macros are necessary because they execute when code is parsed, therefore, macros allow the programmer to generate and include fragments of customized code before the full program is run. To illustrate the difference, consider the following example:

    julia> macro twostep(arg)
    -           println("I execute at parse time. The argument is: ", arg)
    -           return :(println("I execute at runtime. The argument is: ", $arg))
    -       end
    -@twostep (macro with 1 method)
    -
    -julia> ex = macroexpand( :(@twostep :(1, 2, 3)) );
    -I execute at parse time. The argument is: $(Expr(:quote, :((1, 2, 3))))

    The first call to println() is executed when macroexpand() is called. The resulting expression contains only the second println:

    julia> typeof(ex)
    -Expr
    -
    -julia> ex
    -:((println)("I execute at runtime. The argument is: ", $(Expr(:copyast, :($(QuoteNode(:((1, 2, 3)))))))))
    -
    -julia> eval(ex)
    -I execute at runtime. The argument is: (1, 2, 3)

    Macro invocation

    Macros are invoked with the following general syntax:

    @name expr1 expr2 ...
    -@name(expr1, expr2, ...)

    Note the distinguishing @ before the macro name and the lack of commas between the argument expressions in the first form, and the lack of whitespace after @name in the second form. The two styles should not be mixed. For example, the following syntax is different from the examples above; it passes the tuple (expr1, expr2, ...) as one argument to the macro:

    @name (expr1, expr2, ...)

    It is important to emphasize that macros receive their arguments as expressions, literals, or symbols. One way to explore macro arguments is to call the show() function within the macro body:

    julia> macro showarg(x)
    -           show(x)
    -           # ... remainder of macro, returning an expression
    -       end
    -@showarg (macro with 1 method)
    -
    -julia> @showarg(a)
    -:a
    -
    -julia> @showarg(1+1)
    -:(1 + 1)
    -
    -julia> @showarg(println("Yo!"))
    -:(println("Yo!"))

    Building an advanced macro

    Here is a simplified definition of Julia's @assert macro:

    julia> macro assert(ex)
    -           return :( $ex ? nothing : throw(AssertionError($(string(ex)))) )
    -       end
    -@assert (macro with 1 method)

    This macro can be used like this:

    julia> @assert 1 == 1.0
    -
    -julia> @assert 1 == 0
    -ERROR: AssertionError: 1 == 0

    In place of the written syntax, the macro call is expanded at parse time to its returned result. This is equivalent to writing:

    1 == 1.0 ? nothing : throw(AssertionError("1 == 1.0"))
    -1 == 0 ? nothing : throw(AssertionError("1 == 0"))

    That is, in the first call, the expression :(1 == 1.0) is spliced into the test condition slot, while the value of string(:(1 == 1.0)) is spliced into the assertion message slot. The entire expression, thus constructed, is placed into the syntax tree where the @assert macro call occurs. Then at execution time, if the test expression evaluates to true, then nothing is returned, whereas if the test is false, an error is raised indicating the asserted expression that was false. Notice that it would not be possible to write this as a function, since only the value of the condition is available and it would be impossible to display the expression that computed it in the error message.

    The actual definition of @assert in the standard library is more complicated. It allows the user to optionally specify their own error message, instead of just printing the failed expression. Just like in functions with a variable number of arguments, this is specified with an ellipses following the last argument:

    julia> macro assert(ex, msgs...)
    -           msg_body = isempty(msgs) ? ex : msgs[1]
    -           msg = string(msg_body)
    -           return :($ex ? nothing : throw(AssertionError($msg)))
    -       end
    -@assert (macro with 1 method)

    Now @assert has two modes of operation, depending upon the number of arguments it receives! If there's only one argument, the tuple of expressions captured by msgs will be empty and it will behave the same as the simpler definition above. But now if the user specifies a second argument, it is printed in the message body instead of the failing expression. You can inspect the result of a macro expansion with the aptly named macroexpand() function:

    julia> macroexpand(:(@assert a == b))
    -:(if a == b
    -        nothing
    -    else
    -        (throw)((AssertionError)("a == b"))
    -    end)
    -
    -julia> macroexpand(:(@assert a==b "a should equal b!"))
    -:(if a == b
    -        nothing
    -    else
    -        (throw)((AssertionError)("a should equal b!"))
    -    end)

    There is yet another case that the actual @assert macro handles: what if, in addition to printing "a should equal b," we wanted to print their values? One might naively try to use string interpolation in the custom message, e.g., @assert a==b "a ($a) should equal b ($b)!", but this won't work as expected with the above macro. Can you see why? Recall from string interpolation that an interpolated string is rewritten to a call to string(). Compare:

    julia> typeof(:("a should equal b"))
    -String
    -
    -julia> typeof(:("a ($a) should equal b ($b)!"))
    -Expr
    -
    -julia> dump(:("a ($a) should equal b ($b)!"))
    -Expr
    -  head: Symbol string
    -  args: Array{Any}((5,))
    -    1: String "a ("
    -    2: Symbol a
    -    3: String ") should equal b ("
    -    4: Symbol b
    -    5: String ")!"
    -  typ: Any

    So now instead of getting a plain string in msg_body, the macro is receiving a full expression that will need to be evaluated in order to display as expected. This can be spliced directly into the returned expression as an argument to the string() call; see error.jl for the complete implementation.

    The @assert macro makes great use of splicing into quoted expressions to simplify the manipulation of expressions inside the macro body.

    Hygiene

    An issue that arises in more complex macros is that of hygiene. In short, macros must ensure that the variables they introduce in their returned expressions do not accidentally clash with existing variables in the surrounding code they expand into. Conversely, the expressions that are passed into a macro as arguments are often expected to evaluate in the context of the surrounding code, interacting with and modifying the existing variables. Another concern arises from the fact that a macro may be called in a different module from where it was defined. In this case we need to ensure that all global variables are resolved to the correct module. Julia already has a major advantage over languages with textual macro expansion (like C) in that it only needs to consider the returned expression. All the other variables (such as msg in @assert above) follow the normal scoping block behavior.

    To demonstrate these issues, let us consider writing a @time macro that takes an expression as its argument, records the time, evaluates the expression, records the time again, prints the difference between the before and after times, and then has the value of the expression as its final value. The macro might look like this:

    macro time(ex)
    -    return quote
    -        local t0 = time()
    -        local val = $ex
    -        local t1 = time()
    -        println("elapsed time: ", t1-t0, " seconds")
    -        val
    -    end
    -end

    Here, we want t0, t1, and val to be private temporary variables, and we want time to refer to the time() function in the standard library, not to any time variable the user might have (the same applies to println). Imagine the problems that could occur if the user expression ex also contained assignments to a variable called t0, or defined its own time variable. We might get errors, or mysteriously incorrect behavior.

    Julia's macro expander solves these problems in the following way. First, variables within a macro result are classified as either local or global. A variable is considered local if it is assigned to (and not declared global), declared local, or used as a function argument name. Otherwise, it is considered global. Local variables are then renamed to be unique (using the gensym() function, which generates new symbols), and global variables are resolved within the macro definition environment. Therefore both of the above concerns are handled; the macro's locals will not conflict with any user variables, and time and println will refer to the standard library definitions.

    One problem remains however. Consider the following use of this macro:

    module MyModule
    -import Base.@time
    -
    -time() = ... # compute something
    -
    -@time time()
    -end

    Here the user expression ex is a call to time, but not the same time function that the macro uses. It clearly refers to MyModule.time. Therefore we must arrange for the code in ex to be resolved in the macro call environment. This is done by "escaping" the expression with esc():

    macro time(ex)
    -    ...
    -    local val = $(esc(ex))
    -    ...
    -end

    An expression wrapped in this manner is left alone by the macro expander and simply pasted into the output verbatim. Therefore it will be resolved in the macro call environment.

    This escaping mechanism can be used to "violate" hygiene when necessary, in order to introduce or manipulate user variables. For example, the following macro sets x to zero in the call environment:

    julia> macro zerox()
    -           return esc(:(x = 0))
    -       end
    -@zerox (macro with 1 method)
    -
    -julia> function foo()
    -           x = 1
    -           @zerox
    -           return x # is zero
    -       end
    -foo (generic function with 1 method)
    -
    -julia> foo()
    -0

    This kind of manipulation of variables should be used judiciously, but is occasionally quite handy.

    Code Generation

    When a significant amount of repetitive boilerplate code is required, it is common to generate it programmatically to avoid redundancy. In most languages, this requires an extra build step, and a separate program to generate the repetitive code. In Julia, expression interpolation and eval() allow such code generation to take place in the normal course of program execution. For example, the following code defines a series of operators on three arguments in terms of their 2-argument forms:

    for op = (:+, :*, :&, :|, :$)
    -    eval(quote
    -        ($op)(a,b,c) = ($op)(($op)(a,b),c)
    -    end)
    -end

    In this manner, Julia acts as its own preprocessor, and allows code generation from inside the language. The above code could be written slightly more tersely using the : prefix quoting form:

    for op = (:+, :*, :&, :|, :$)
    -    eval(:(($op)(a,b,c) = ($op)(($op)(a,b),c)))
    -end

    This sort of in-language code generation, however, using the eval(quote(...)) pattern, is common enough that Julia comes with a macro to abbreviate this pattern:

    for op = (:+, :*, :&, :|, :$)
    -    @eval ($op)(a,b,c) = ($op)(($op)(a,b),c)
    -end

    The @eval macro rewrites this call to be precisely equivalent to the above longer versions. For longer blocks of generated code, the expression argument given to @eval can be a block:

    @eval begin
    -    # multiple lines
    -end

    Non-Standard String Literals

    Recall from Strings that string literals prefixed by an identifier are called non-standard string literals, and can have different semantics than un-prefixed string literals. For example:

    • r"^\s*(?:#|$)" produces a regular expression object rather than a string

    • b"DATA\xff\u2200" is a byte array literal for [68,65,84,65,255,226,136,128].

    Perhaps surprisingly, these behaviors are not hard-coded into the Julia parser or compiler. Instead, they are custom behaviors provided by a general mechanism that anyone can use: prefixed string literals are parsed as calls to specially-named macros. For example, the regular expression macro is just the following:

    macro r_str(p)
    -    Regex(p)
    -end

    That's all. This macro says that the literal contents of the string literal r"^\s*(?:#|$)" should be passed to the @r_str macro and the result of that expansion should be placed in the syntax tree where the string literal occurs. In other words, the expression r"^\s*(?:#|$)" is equivalent to placing the following object directly into the syntax tree:

    Regex("^\\s*(?:#|\$)")

    Not only is the string literal form shorter and far more convenient, but it is also more efficient: since the regular expression is compiled and the Regex object is actually created when the code is compiled, the compilation occurs only once, rather than every time the code is executed. Consider if the regular expression occurs in a loop:

    for line = lines
    -    m = match(r"^\s*(?:#|$)", line)
    -    if m === nothing
    -        # non-comment
    -    else
    -        # comment
    -    end
    -end

    Since the regular expression r"^\s*(?:#|$)" is compiled and inserted into the syntax tree when this code is parsed, the expression is only compiled once instead of each time the loop is executed. In order to accomplish this without macros, one would have to write this loop like this:

    re = Regex("^\\s*(?:#|\$)")
    -for line = lines
    -    m = match(re, line)
    -    if m === nothing
    -        # non-comment
    -    else
    -        # comment
    -    end
    -end

    Moreover, if the compiler could not determine that the regex object was constant over all loops, certain optimizations might not be possible, making this version still less efficient than the more convenient literal form above. Of course, there are still situations where the non-literal form is more convenient: if one needs to interpolate a variable into the regular expression, one must take this more verbose approach; in cases where the regular expression pattern itself is dynamic, potentially changing upon each loop iteration, a new regular expression object must be constructed on each iteration. In the vast majority of use cases, however, regular expressions are not constructed based on run-time data. In this majority of cases, the ability to write regular expressions as compile-time values is invaluable.

    Like non-standard string literals, non-standard command literals exist using a prefixed variant of the command literal syntax. The command literal custom`literal` is parsed as @custom_cmd "literal". Julia itself does not contain any non-standard command literals, but packages can make use of this syntax. Aside from the different syntax and the _cmd suffix instead of the _str suffix, non-standard command literals behave exactly like non-standard string literals.

    In the event that two modules provide non-standard string or command literals with the same name, it is possible to qualify the string or command literal with a module name. For instance, if both Foo and Bar provide non-standard string literal @x_str, then one can write Foo.x"literal" or Bar.x"literal" to disambiguate between the two.

    The mechanism for user-defined string literals is deeply, profoundly powerful. Not only are Julia's non-standard literals implemented using it, but also the command literal syntax (`echo "Hello, $person"`) is implemented with the following innocuous-looking macro:

    macro cmd(str)
    -    :(cmd_gen($(shell_parse(str)[1])))
    -end

    Of course, a large amount of complexity is hidden in the functions used in this macro definition, but they are just functions, written entirely in Julia. You can read their source and see precisely what they do – and all they do is construct expression objects to be inserted into your program's syntax tree.

    Generated functions

    A very special macro is @generated, which allows you to define so-called generated functions. These have the capability to generate specialized code depending on the types of their arguments with more flexibility and/or less code than what can be achieved with multiple dispatch. While macros work with expressions at parsing-time and cannot access the types of their inputs, a generated function gets expanded at a time when the types of the arguments are known, but the function is not yet compiled.

    Instead of performing some calculation or action, a generated function declaration returns a quoted expression which then forms the body for the method corresponding to the types of the arguments. When called, the body expression is first evaluated and compiled, then the returned expression is compiled and run. To make this efficient, the result is often cached. And to make this inferable, only a limited subset of the language is usable. Thus, generated functions provide a flexible framework to move work from run-time to compile-time, at the expense of greater restrictions on the allowable constructs.

    When defining generated functions, there are four main differences to ordinary functions:

    1. You annotate the function declaration with the @generated macro. This adds some information to the AST that lets the compiler know that this is a generated function.

    2. In the body of the generated function you only have access to the types of the arguments – not their values – and any function that was defined before the definition of the generated function.

    3. Instead of calculating something or performing some action, you return a quoted expression which, when evaluated, does what you want.

    4. Generated functions must not mutate or observe any non-constant global state (including, for example, IO, locks, non-local dictionaries, or using method_exists). This means they can only read global constants, and cannot have any side effects. In other words, they must be completely pure. Due to an implementation limitation, this also means that they currently cannot define a closure or untyped generator.

    It's easiest to illustrate this with an example. We can declare a generated function foo as

    julia> @generated function foo(x)
    -           Core.println(x)
    -           return :(x * x)
    -       end
    -foo (generic function with 1 method)

    Note that the body returns a quoted expression, namely :(x * x), rather than just the value of x * x.

    From the caller's perspective, they are very similar to regular functions; in fact, you don't have to know if you're calling a regular or generated function - the syntax and result of the call is just the same. Let's see how foo behaves:

    julia> x = foo(2); # note: output is from println() statement in the body
    -Int64
    -
    -julia> x           # now we print x
    -4
    -
    -julia> y = foo("bar");
    -String
    -
    -julia> y
    -"barbar"

    So, we see that in the body of the generated function, x is the type of the passed argument, and the value returned by the generated function, is the result of evaluating the quoted expression we returned from the definition, now with the value of x.

    What happens if we evaluate foo again with a type that we have already used?

    julia> foo(4)
    -16

    Note that there is no printout of Int64. We can see that the body of the generated function was only executed once here, for the specific set of argument types, and the result was cached. After that, for this example, the expression returned from the generated function on the first invocation was re-used as the method body. However, the actual caching behavior is an implementation-defined performance optimization, so it is invalid to depend too closely on this behavior.

    The number of times a generated function is generated might be only once, but it might also be more often, or appear to not happen at all. As a consequence, you should never write a generated function with side effects - when, and how often, the side effects occur is undefined. (This is true for macros too - and just like for macros, the use of eval() in a generated function is a sign that you're doing something the wrong way.) However, unlike macros, the runtime system cannot correctly handle a call to eval(), so it is disallowed.

    It is also important to see how @generated functions interact with method redefinition. Following the principle that a correct @generated function must not observe any mutable state or cause any mutation of global state, we see the following behavior. Observe that the generated function cannot call any method that was not defined prior to the definition of the generated function itself.

    Initially f(x) has one definition

    julia> f(x) = "original definition";

    Define other operations that use f(x):

    julia> g(x) = f(x);
    -
    -julia> @generated gen1(x) = f(x);
    -
    -julia> @generated gen2(x) = :(f(x));

    We now add some new definitions for f(x):

    julia> f(x::Int) = "definition for Int";
    -
    -julia> f(x::Type{Int}) = "definition for Type{Int}";

    and compare how these results differ:

    julia> f(1)
    -"definition for Int"
    -
    -julia> g(1)
    -"definition for Int"
    -
    -julia> gen1(1)
    -"original definition"
    -
    -julia> gen2(1)
    -"definition for Int"

    Each method of a generated function has its own view of defined functions:

    julia> @generated gen1(x::Real) = f(x);
    -
    -julia> gen1(1)
    -"definition for Type{Int}"

    The example generated function foo above did not do anything a normal function foo(x) = x * x could not do (except printing the type on the first invocation, and incurring higher overhead). However, the power of a generated function lies in its ability to compute different quoted expressions depending on the types passed to it:

    julia> @generated function bar(x)
    -           if x <: Integer
    -               return :(x ^ 2)
    -           else
    -               return :(x)
    -           end
    -       end
    -bar (generic function with 1 method)
    -
    -julia> bar(4)
    -16
    -
    -julia> bar("baz")
    -"baz"

    (although of course this contrived example would be more easily implemented using multiple dispatch...)

    Abusing this will corrupt the runtime system and cause undefined behavior:

    julia> @generated function baz(x)
    -           if rand() < .9
    -               return :(x^2)
    -           else
    -               return :("boo!")
    -           end
    -       end
    -baz (generic function with 1 method)

    Since the body of the generated function is non-deterministic, its behavior, and the behavior of all subsequent code is undefined.

    Don't copy these examples!

    These examples are hopefully helpful to illustrate how generated functions work, both in the definition end and at the call site; however, don't copy them, for the following reasons:

    • the foo function has side-effects (the call to Core.println), and it is undefined exactly when, how often or how many times these side-effects will occur

    • the bar function solves a problem that is better solved with multiple dispatch - defining bar(x) = x and bar(x::Integer) = x ^ 2 will do the same thing, but it is both simpler and faster.

    • the baz function is pathologically insane

    Note that the set of operations that should not be attempted in a generated function is unbounded, and the runtime system can currently only detect a subset of the invalid operations. There are many other operations that will simply corrupt the runtime system without notification, usually in subtle ways not obviously connected to the bad definition. Because the function generator is run during inference, it must respect all of the limitations of that code.

    Some operations that should not be attempted include:

    1. Caching of native pointers.

    2. Interacting with the contents or methods of Core.Inference in any way.

    3. Observing any mutable state.

      • Inference on the generated function may be run at any time, including while your code is attempting to observe or mutate this state.

    4. Taking any locks: C code you call out to may use locks internally, (for example, it is not problematic to call malloc, even though most implementations require locks internally) but don't attempt to hold or acquire any while executing Julia code.

    5. Calling any function that is defined after the body of the generated function. This condition is relaxed for incrementally-loaded precompiled modules to allow calling any function in the module.

    Alright, now that we have a better understanding of how generated functions work, let's use them to build some more advanced (and valid) functionality...

    An advanced example

    Julia's base library has a sub2ind() function to calculate a linear index into an n-dimensional array, based on a set of n multilinear indices - in other words, to calculate the index i that can be used to index into an array A using A[i], instead of A[x,y,z,...]. One possible implementation is the following:

    julia> function sub2ind_loop(dims::NTuple{N}, I::Integer...) where N
    -           ind = I[N] - 1
    -           for i = N-1:-1:1
    -               ind = I[i]-1 + dims[i]*ind
    -           end
    -           return ind + 1
    -       end
    -sub2ind_loop (generic function with 1 method)
    -
    -julia> sub2ind_loop((3, 5), 1, 2)
    -4

    The same thing can be done using recursion:

    julia> sub2ind_rec(dims::Tuple{}) = 1;
    -
    -julia> sub2ind_rec(dims::Tuple{}, i1::Integer, I::Integer...) =
    -           i1 == 1 ? sub2ind_rec(dims, I...) : throw(BoundsError());
    -
    -julia> sub2ind_rec(dims::Tuple{Integer, Vararg{Integer}}, i1::Integer) = i1;
    -
    -julia> sub2ind_rec(dims::Tuple{Integer, Vararg{Integer}}, i1::Integer, I::Integer...) =
    -           i1 + dims[1] * (sub2ind_rec(Base.tail(dims), I...) - 1);
    -
    -julia> sub2ind_rec((3, 5), 1, 2)
    -4

    Both these implementations, although different, do essentially the same thing: a runtime loop over the dimensions of the array, collecting the offset in each dimension into the final index.

    However, all the information we need for the loop is embedded in the type information of the arguments. Thus, we can utilize generated functions to move the iteration to compile-time; in compiler parlance, we use generated functions to manually unroll the loop. The body becomes almost identical, but instead of calculating the linear index, we build up an expression that calculates the index:

    julia> @generated function sub2ind_gen(dims::NTuple{N}, I::Integer...) where N
    -           ex = :(I[$N] - 1)
    -           for i = (N - 1):-1:1
    -               ex = :(I[$i] - 1 + dims[$i] * $ex)
    -           end
    -           return :($ex + 1)
    -       end
    -sub2ind_gen (generic function with 1 method)
    -
    -julia> sub2ind_gen((3, 5), 1, 2)
    -4

    What code will this generate?

    An easy way to find out is to extract the body into another (regular) function:

    julia> @generated function sub2ind_gen(dims::NTuple{N}, I::Integer...) where N
    -           return sub2ind_gen_impl(dims, I...)
    -       end
    -sub2ind_gen (generic function with 1 method)
    -
    -julia> function sub2ind_gen_impl(dims::Type{T}, I...) where T <: NTuple{N,Any} where N
    -           length(I) == N || return :(error("partial indexing is unsupported"))
    -           ex = :(I[$N] - 1)
    -           for i = (N - 1):-1:1
    -               ex = :(I[$i] - 1 + dims[$i] * $ex)
    -           end
    -           return :($ex + 1)
    -       end
    -sub2ind_gen_impl (generic function with 1 method)

    We can now execute sub2ind_gen_impl and examine the expression it returns:

    julia> sub2ind_gen_impl(Tuple{Int,Int}, Int, Int)
    -:(((I[1] - 1) + dims[1] * (I[2] - 1)) + 1)

    So, the method body that will be used here doesn't include a loop at all - just indexing into the two tuples, multiplication and addition/subtraction. All the looping is performed compile-time, and we avoid looping during execution entirely. Thus, we only loop once per type, in this case once per N (except in edge cases where the function is generated more than once - see disclaimer above).

    diff --git a/julia-0.6.3/share/doc/julia/html/en/manual/methods.html b/julia-0.6.3/share/doc/julia/html/en/manual/methods.html deleted file mode 100644 index 9279866..0000000 --- a/julia-0.6.3/share/doc/julia/html/en/manual/methods.html +++ /dev/null @@ -1,277 +0,0 @@ - -Methods · The Julia Language

    Methods

    Methods

    Recall from Functions that a function is an object that maps a tuple of arguments to a return value, or throws an exception if no appropriate value can be returned. It is common for the same conceptual function or operation to be implemented quite differently for different types of arguments: adding two integers is very different from adding two floating-point numbers, both of which are distinct from adding an integer to a floating-point number. Despite their implementation differences, these operations all fall under the general concept of "addition". Accordingly, in Julia, these behaviors all belong to a single object: the + function.

    To facilitate using many different implementations of the same concept smoothly, functions need not be defined all at once, but can rather be defined piecewise by providing specific behaviors for certain combinations of argument types and counts. A definition of one possible behavior for a function is called a method. Thus far, we have presented only examples of functions defined with a single method, applicable to all types of arguments. However, the signatures of method definitions can be annotated to indicate the types of arguments in addition to their number, and more than a single method definition may be provided. When a function is applied to a particular tuple of arguments, the most specific method applicable to those arguments is applied. Thus, the overall behavior of a function is a patchwork of the behaviors of its various method definitions. If the patchwork is well designed, even though the implementations of the methods may be quite different, the outward behavior of the function will appear seamless and consistent.

    The choice of which method to execute when a function is applied is called dispatch. Julia allows the dispatch process to choose which of a function's methods to call based on the number of arguments given, and on the types of all of the function's arguments. This is different than traditional object-oriented languages, where dispatch occurs based only on the first argument, which often has a special argument syntax, and is sometimes implied rather than explicitly written as an argument. [1] Using all of a function's arguments to choose which method should be invoked, rather than just the first, is known as multiple dispatch. Multiple dispatch is particularly useful for mathematical code, where it makes little sense to artificially deem the operations to "belong" to one argument more than any of the others: does the addition operation in x + y belong to x any more than it does to y? The implementation of a mathematical operator generally depends on the types of all of its arguments. Even beyond mathematical operations, however, multiple dispatch ends up being a powerful and convenient paradigm for structuring and organizing programs.

    [1]

    In C++ or Java, for example, in a method call like obj.meth(arg1,arg2), the object obj "receives" the method call and is implicitly passed to the method via the this keyword, rather than as an explicit method argument. When the current this object is the receiver of a method call, it can be omitted altogether, writing just meth(arg1,arg2), with this implied as the receiving object.

    Defining Methods

    Until now, we have, in our examples, defined only functions with a single method having unconstrained argument types. Such functions behave just like they would in traditional dynamically typed languages. Nevertheless, we have used multiple dispatch and methods almost continually without being aware of it: all of Julia's standard functions and operators, like the aforementioned + function, have many methods defining their behavior over various possible combinations of argument type and count.

    When defining a function, one can optionally constrain the types of parameters it is applicable to, using the :: type-assertion operator, introduced in the section on Composite Types:

    julia> f(x::Float64, y::Float64) = 2x + y
    -f (generic function with 1 method)

    This function definition applies only to calls where x and y are both values of type Float64:

    julia> f(2.0, 3.0)
    -7.0

    Applying it to any other types of arguments will result in a MethodError:

    julia> f(2.0, 3)
    -ERROR: MethodError: no method matching f(::Float64, ::Int64)
    -Closest candidates are:
    -  f(::Float64, !Matched::Float64) at none:1
    -
    -julia> f(Float32(2.0), 3.0)
    -ERROR: MethodError: no method matching f(::Float32, ::Float64)
    -Closest candidates are:
    -  f(!Matched::Float64, ::Float64) at none:1
    -
    -julia> f(2.0, "3.0")
    -ERROR: MethodError: no method matching f(::Float64, ::String)
    -Closest candidates are:
    -  f(::Float64, !Matched::Float64) at none:1
    -
    -julia> f("2.0", "3.0")
    -ERROR: MethodError: no method matching f(::String, ::String)

    As you can see, the arguments must be precisely of type Float64. Other numeric types, such as integers or 32-bit floating-point values, are not automatically converted to 64-bit floating-point, nor are strings parsed as numbers. Because Float64 is a concrete type and concrete types cannot be subclassed in Julia, such a definition can only be applied to arguments that are exactly of type Float64. It may often be useful, however, to write more general methods where the declared parameter types are abstract:

    julia> f(x::Number, y::Number) = 2x - y
    -f (generic function with 2 methods)
    -
    -julia> f(2.0, 3)
    -1.0

    This method definition applies to any pair of arguments that are instances of Number. They need not be of the same type, so long as they are each numeric values. The problem of handling disparate numeric types is delegated to the arithmetic operations in the expression 2x - y.

    To define a function with multiple methods, one simply defines the function multiple times, with different numbers and types of arguments. The first method definition for a function creates the function object, and subsequent method definitions add new methods to the existing function object. The most specific method definition matching the number and types of the arguments will be executed when the function is applied. Thus, the two method definitions above, taken together, define the behavior for f over all pairs of instances of the abstract type Number – but with a different behavior specific to pairs of Float64 values. If one of the arguments is a 64-bit float but the other one is not, then the f(Float64,Float64) method cannot be called and the more general f(Number,Number) method must be used:

    julia> f(2.0, 3.0)
    -7.0
    -
    -julia> f(2, 3.0)
    -1.0
    -
    -julia> f(2.0, 3)
    -1.0
    -
    -julia> f(2, 3)
    -1

    The 2x + y definition is only used in the first case, while the 2x - y definition is used in the others. No automatic casting or conversion of function arguments is ever performed: all conversion in Julia is non-magical and completely explicit. Conversion and Promotion, however, shows how clever application of sufficiently advanced technology can be indistinguishable from magic. [Clarke61]

    For non-numeric values, and for fewer or more than two arguments, the function f remains undefined, and applying it will still result in a MethodError:

    julia> f("foo", 3)
    -ERROR: MethodError: no method matching f(::String, ::Int64)
    -Closest candidates are:
    -  f(!Matched::Number, ::Number) at none:1
    -
    -julia> f()
    -ERROR: MethodError: no method matching f()
    -Closest candidates are:
    -  f(!Matched::Float64, !Matched::Float64) at none:1
    -  f(!Matched::Number, !Matched::Number) at none:1

    You can easily see which methods exist for a function by entering the function object itself in an interactive session:

    julia> f
    -f (generic function with 2 methods)

    This output tells us that f is a function object with two methods. To find out what the signatures of those methods are, use the methods() function:

    julia> methods(f)
    -# 2 methods for generic function "f":
    -f(x::Float64, y::Float64) in Main at none:1
    -f(x::Number, y::Number) in Main at none:1

    which shows that f has two methods, one taking two Float64 arguments and one taking arguments of type Number. It also indicates the file and line number where the methods were defined: because these methods were defined at the REPL, we get the apparent line number none:1.

    In the absence of a type declaration with ::, the type of a method parameter is Any by default, meaning that it is unconstrained since all values in Julia are instances of the abstract type Any. Thus, we can define a catch-all method for f like so:

    julia> f(x,y) = println("Whoa there, Nelly.")
    -f (generic function with 3 methods)
    -
    -julia> f("foo", 1)
    -Whoa there, Nelly.

    This catch-all is less specific than any other possible method definition for a pair of parameter values, so it will only be called on pairs of arguments to which no other method definition applies.

    Although it seems a simple concept, multiple dispatch on the types of values is perhaps the single most powerful and central feature of the Julia language. Core operations typically have dozens of methods:

    julia> methods(+)
    -# 180 methods for generic function "+":
    -+(x::Bool, z::Complex{Bool}) in Base at complex.jl:224
    -+(x::Bool, y::Bool) in Base at bool.jl:89
    -+(x::Bool) in Base at bool.jl:86
    -+(x::Bool, y::T) where T<:AbstractFloat in Base at bool.jl:96
    -+(x::Bool, z::Complex) in Base at complex.jl:231
    -+(a::Float16, b::Float16) in Base at float.jl:372
    -+(x::Float32, y::Float32) in Base at float.jl:374
    -+(x::Float64, y::Float64) in Base at float.jl:375
    -+(z::Complex{Bool}, x::Bool) in Base at complex.jl:225
    -+(z::Complex{Bool}, x::Real) in Base at complex.jl:239
    -+(x::Char, y::Integer) in Base at char.jl:40
    -+(c::BigInt, x::BigFloat) in Base.MPFR at mpfr.jl:303
    -+(a::BigInt, b::BigInt, c::BigInt, d::BigInt, e::BigInt) in Base.GMP at gmp.jl:303
    -+(a::BigInt, b::BigInt, c::BigInt, d::BigInt) in Base.GMP at gmp.jl:296
    -+(a::BigInt, b::BigInt, c::BigInt) in Base.GMP at gmp.jl:290
    -+(x::BigInt, y::BigInt) in Base.GMP at gmp.jl:258
    -+(x::BigInt, c::Union{UInt16, UInt32, UInt64, UInt8}) in Base.GMP at gmp.jl:315
    -...
    -+(a, b, c, xs...) at operators.jl:119

    Multiple dispatch together with the flexible parametric type system give Julia its ability to abstractly express high-level algorithms decoupled from implementation details, yet generate efficient, specialized code to handle each case at run time.

    Method Ambiguities

    It is possible to define a set of function methods such that there is no unique most specific method applicable to some combinations of arguments:

    julia> g(x::Float64, y) = 2x + y
    -g (generic function with 1 method)
    -
    -julia> g(x, y::Float64) = x + 2y
    -g (generic function with 2 methods)
    -
    -julia> g(2.0, 3)
    -7.0
    -
    -julia> g(2, 3.0)
    -8.0
    -
    -julia> g(2.0, 3.0)
    -ERROR: MethodError: g(::Float64, ::Float64) is ambiguous.
    -[...]

    Here the call g(2.0, 3.0) could be handled by either the g(Float64, Any) or the g(Any, Float64) method, and neither is more specific than the other. In such cases, Julia raises a MethodError rather than arbitrarily picking a method. You can avoid method ambiguities by specifying an appropriate method for the intersection case:

    julia> g(x::Float64, y::Float64) = 2x + 2y
    -g (generic function with 3 methods)
    -
    -julia> g(2.0, 3)
    -7.0
    -
    -julia> g(2, 3.0)
    -8.0
    -
    -julia> g(2.0, 3.0)
    -10.0

    It is recommended that the disambiguating method be defined first, since otherwise the ambiguity exists, if transiently, until the more specific method is defined.

    In more complex cases, resolving method ambiguities involves a certain element of design; this topic is explored further below.

    Parametric Methods

    Method definitions can optionally have type parameters qualifying the signature:

    julia> same_type(x::T, y::T) where {T} = true
    -same_type (generic function with 1 method)
    -
    -julia> same_type(x,y) = false
    -same_type (generic function with 2 methods)

    The first method applies whenever both arguments are of the same concrete type, regardless of what type that is, while the second method acts as a catch-all, covering all other cases. Thus, overall, this defines a boolean function that checks whether its two arguments are of the same type:

    julia> same_type(1, 2)
    -true
    -
    -julia> same_type(1, 2.0)
    -false
    -
    -julia> same_type(1.0, 2.0)
    -true
    -
    -julia> same_type("foo", 2.0)
    -false
    -
    -julia> same_type("foo", "bar")
    -true
    -
    -julia> same_type(Int32(1), Int64(2))
    -false

    Such definitions correspond to methods whose type signatures are UnionAll types (see UnionAll Types).

    This kind of definition of function behavior by dispatch is quite common – idiomatic, even – in Julia. Method type parameters are not restricted to being used as the types of arguments: they can be used anywhere a value would be in the signature of the function or body of the function. Here's an example where the method type parameter T is used as the type parameter to the parametric type Vector{T} in the method signature:

    julia> myappend(v::Vector{T}, x::T) where {T} = [v..., x]
    -myappend (generic function with 1 method)
    -
    -julia> myappend([1,2,3],4)
    -4-element Array{Int64,1}:
    - 1
    - 2
    - 3
    - 4
    -
    -julia> myappend([1,2,3],2.5)
    -ERROR: MethodError: no method matching myappend(::Array{Int64,1}, ::Float64)
    -Closest candidates are:
    -  myappend(::Array{T,1}, !Matched::T) where T at none:1
    -
    -julia> myappend([1.0,2.0,3.0],4.0)
    -4-element Array{Float64,1}:
    - 1.0
    - 2.0
    - 3.0
    - 4.0
    -
    -julia> myappend([1.0,2.0,3.0],4)
    -ERROR: MethodError: no method matching myappend(::Array{Float64,1}, ::Int64)
    -Closest candidates are:
    -  myappend(::Array{T,1}, !Matched::T) where T at none:1

    As you can see, the type of the appended element must match the element type of the vector it is appended to, or else a MethodError is raised. In the following example, the method type parameter T is used as the return value:

    julia> mytypeof(x::T) where {T} = T
    -mytypeof (generic function with 1 method)
    -
    -julia> mytypeof(1)
    -Int64
    -
    -julia> mytypeof(1.0)
    -Float64

    Just as you can put subtype constraints on type parameters in type declarations (see Parametric Types), you can also constrain type parameters of methods:

    julia> same_type_numeric(x::T, y::T) where {T<:Number} = true
    -same_type_numeric (generic function with 1 method)
    -
    -julia> same_type_numeric(x::Number, y::Number) = false
    -same_type_numeric (generic function with 2 methods)
    -
    -julia> same_type_numeric(1, 2)
    -true
    -
    -julia> same_type_numeric(1, 2.0)
    -false
    -
    -julia> same_type_numeric(1.0, 2.0)
    -true
    -
    -julia> same_type_numeric("foo", 2.0)
    -ERROR: MethodError: no method matching same_type_numeric(::String, ::Float64)
    -Closest candidates are:
    -  same_type_numeric(!Matched::T<:Number, ::T<:Number) where T<:Number at none:1
    -  same_type_numeric(!Matched::Number, ::Number) at none:1
    -
    -julia> same_type_numeric("foo", "bar")
    -ERROR: MethodError: no method matching same_type_numeric(::String, ::String)
    -
    -julia> same_type_numeric(Int32(1), Int64(2))
    -false

    The same_type_numeric function behaves much like the same_type function defined above, but is only defined for pairs of numbers.

    Parametric methods allow the same syntax as where expressions used to write types (see UnionAll Types). If there is only a single parameter, the enclosing curly braces (in where {T}) can be omitted, but are often preferred for clarity. Multiple parameters can be separated with commas, e.g. where {T, S<:Real}, or written using nested where, e.g. where S<:Real where T.

    Redefining Methods

    When redefining a method or adding new methods, it is important to realize that these changes don't take effect immediately. This is key to Julia's ability to statically infer and compile code to run fast, without the usual JIT tricks and overhead. Indeed, any new method definition won't be visible to the current runtime environment, including Tasks and Threads (and any previously defined @generated functions). Let's start with an example to see what this means:

    julia> function tryeval()
    -           @eval newfun() = 1
    -           newfun()
    -       end
    -tryeval (generic function with 1 method)
    -
    -julia> tryeval()
    -ERROR: MethodError: no method matching newfun()
    -The applicable method may be too new: running in world age xxxx1, while current world is xxxx2.
    -Closest candidates are:
    -  newfun() at none:1 (method too new to be called from this world context.)
    - in tryeval() at none:1
    - ...
    -
    -julia> newfun()
    -1

    In this example, observe that the new definition for newfun has been created, but can't be immediately called. The new global is immediately visible to the tryeval function, so you could write return newfun (without parentheses). But neither you, nor any of your callers, nor the functions they call, or etc. can call this new method definition!

    But there's an exception: future calls to newfun from the REPL work as expected, being able to both see and call the new definition of newfun.

    However, future calls to tryeval will continue to see the definition of newfun as it was at the previous statement at the REPL, and thus before that call to tryeval.

    You may want to try this for yourself to see how it works.

    The implementation of this behavior is a "world age counter". This monotonically increasing value tracks each method definition operation. This allows describing "the set of method definitions visible to a given runtime environment" as a single number, or "world age". It also allows comparing the methods available in two worlds just by comparing their ordinal value. In the example above, we see that the "current world" (in which the method newfun() exists), is one greater than the task-local "runtime world" that was fixed when the execution of tryeval started.

    Sometimes it is necessary to get around this (for example, if you are implementing the above REPL). Fortunately, there is an easy solution: call the function using Base.invokelatest:

    julia> function tryeval2()
    -           @eval newfun2() = 2
    -           Base.invokelatest(newfun2)
    -       end
    -tryeval2 (generic function with 1 method)
    -
    -julia> tryeval2()
    -2

    Finally, let's take a look at some more complex examples where this rule comes into play. Define a function f(x), which initially has one method:

    julia> f(x) = "original definition"
    -f (generic function with 1 method)

    Start some other operations that use f(x):

    julia> g(x) = f(x)
    -g (generic function with 1 method)
    -
    -julia> t = @async f(wait()); yield();

    Now we add some new methods to f(x):

    julia> f(x::Int) = "definition for Int"
    -f (generic function with 2 methods)
    -
    -julia> f(x::Type{Int}) = "definition for Type{Int}"
    -f (generic function with 3 methods)

    Compare how these results differ:

    julia> f(1)
    -"definition for Int"
    -
    -julia> g(1)
    -"definition for Int"
    -
    -julia> wait(schedule(t, 1))
    -"original definition"
    -
    -julia> t = @async f(wait()); yield();
    -
    -julia> wait(schedule(t, 1))
    -"definition for Int"

    Parametrically-constrained Varargs methods

    Function parameters can also be used to constrain the number of arguments that may be supplied to a "varargs" function (Varargs Functions). The notation Vararg{T,N} is used to indicate such a constraint. For example:

    julia> bar(a,b,x::Vararg{Any,2}) = (a,b,x)
    -bar (generic function with 1 method)
    -
    -julia> bar(1,2,3)
    -ERROR: MethodError: no method matching bar(::Int64, ::Int64, ::Int64)
    -Closest candidates are:
    -  bar(::Any, ::Any, ::Any, !Matched::Any) at none:1
    -
    -julia> bar(1,2,3,4)
    -(1, 2, (3, 4))
    -
    -julia> bar(1,2,3,4,5)
    -ERROR: MethodError: no method matching bar(::Int64, ::Int64, ::Int64, ::Int64, ::Int64)
    -Closest candidates are:
    -  bar(::Any, ::Any, ::Any, ::Any) at none:1

    More usefully, it is possible to constrain varargs methods by a parameter. For example:

    function getindex(A::AbstractArray{T,N}, indexes::Vararg{Number,N}) where {T,N}

    would be called only when the number of indexes matches the dimensionality of the array.

    Note on Optional and keyword Arguments

    As mentioned briefly in Functions, optional arguments are implemented as syntax for multiple method definitions. For example, this definition:

    f(a=1,b=2) = a+2b

    translates to the following three methods:

    f(a,b) = a+2b
    -f(a) = f(a,2)
    -f() = f(1,2)

    This means that calling f() is equivalent to calling f(1,2). In this case the result is 5, because f(1,2) invokes the first method of f above. However, this need not always be the case. If you define a fourth method that is more specialized for integers:

    f(a::Int,b::Int) = a-2b

    then the result of both f() and f(1,2) is -3. In other words, optional arguments are tied to a function, not to any specific method of that function. It depends on the types of the optional arguments which method is invoked. When optional arguments are defined in terms of a global variable, the type of the optional argument may even change at run-time.

    Keyword arguments behave quite differently from ordinary positional arguments. In particular, they do not participate in method dispatch. Methods are dispatched based only on positional arguments, with keyword arguments processed after the matching method is identified.

    Function-like objects

    Methods are associated with types, so it is possible to make any arbitrary Julia object "callable" by adding methods to its type. (Such "callable" objects are sometimes called "functors.")

    For example, you can define a type that stores the coefficients of a polynomial, but behaves like a function evaluating the polynomial:

    julia> struct Polynomial{R}
    -           coeffs::Vector{R}
    -       end
    -
    -julia> function (p::Polynomial)(x)
    -           v = p.coeffs[end]
    -           for i = (length(p.coeffs)-1):-1:1
    -               v = v*x + p.coeffs[i]
    -           end
    -           return v
    -       end

    Notice that the function is specified by type instead of by name. In the function body, p will refer to the object that was called. A Polynomial can be used as follows:

    julia> p = Polynomial([1,10,100])
    -Polynomial{Int64}([1, 10, 100])
    -
    -julia> p(3)
    -931

    This mechanism is also the key to how type constructors and closures (inner functions that refer to their surrounding environment) work in Julia, discussed later in the manual.

    Empty generic functions

    Occasionally it is useful to introduce a generic function without yet adding methods. This can be used to separate interface definitions from implementations. It might also be done for the purpose of documentation or code readability. The syntax for this is an empty function block without a tuple of arguments:

    function emptyfunc
    -end

    Method design and the avoidance of ambiguities

    Julia's method polymorphism is one of its most powerful features, yet exploiting this power can pose design challenges. In particular, in more complex method hierarchies it is not uncommon for ambiguities to arise.

    Above, it was pointed out that one can resolve ambiguities like

    f(x, y::Int) = 1
    -f(x::Int, y) = 2

    by defining a method

    f(x::Int, y::Int) = 3

    This is often the right strategy; however, there are circumstances where following this advice blindly can be counterproductive. In particular, the more methods a generic function has, the more possibilities there are for ambiguities. When your method hierarchies get more complicated than this simple example, it can be worth your while to think carefully about alternative strategies.

    Below we discuss particular challenges and some alternative ways to resolve such issues.

    Tuple and NTuple arguments

    Tuple (and NTuple) arguments present special challenges. For example,

    f(x::NTuple{N,Int}) where {N} = 1
    -f(x::NTuple{N,Float64}) where {N} = 2

    are ambiguous because of the possibility that N == 0: there are no elements to determine whether the Int or Float64 variant should be called. To resolve the ambiguity, one approach is define a method for the empty tuple:

    f(x::Tuple{}) = 3

    Alternatively, for all methods but one you can insist that there is at least one element in the tuple:

    f(x::NTuple{N,Int}) where {N} = 1           # this is the fallback
    -f(x::Tuple{Float64, Vararg{Float64}}) = 2   # this requires at least one Float64

    Orthogonalize your design

    When you might be tempted to dispatch on two or more arguments, consider whether a "wrapper" function might make for a simpler design. For example, instead of writing multiple variants:

    f(x::A, y::A) = ...
    -f(x::A, y::B) = ...
    -f(x::B, y::A) = ...
    -f(x::B, y::B) = ...

    you might consider defining

    f(x::A, y::A) = ...
    -f(x, y) = f(g(x), g(y))

    where g converts the argument to type A. This is a very specific example of the more general principle of orthogonal design, in which separate concepts are assigned to separate methods. Here, g will most likely need a fallback definition

    g(x::A) = x

    A related strategy exploits promote to bring x and y to a common type:

    f(x::T, y::T) where {T} = ...
    -f(x, y) = f(promote(x, y)...)

    One risk with this design is the possibility that if there is no suitable promotion method converting x and y to the same type, the second method will recurse on itself infinitely and trigger a stack overflow. The non-exported function Base.promote_noncircular can be used as an alternative; when promotion fails it will still throw an error, but one that fails faster with a more specific error message.

    Dispatch on one argument at a time

    If you need to dispatch on multiple arguments, and there are many fallbacks with too many combinations to make it practical to define all possible variants, then consider introducing a "name cascade" where (for example) you dispatch on the first argument and then call an internal method:

    f(x::A, y) = _fA(x, y)
    -f(x::B, y) = _fB(x, y)

    Then the internal methods _fA and _fB can dispatch on y without concern about ambiguities with each other with respect to x.

    Be aware that this strategy has at least one major disadvantage: in many cases, it is not possible for users to further customize the behavior of f by defining further specializations of your exported function f. Instead, they have to define specializations for your internal methods _fA and _fB, and this blurs the lines between exported and internal methods.

    Abstract containers and element types

    Where possible, try to avoid defining methods that dispatch on specific element types of abstract containers. For example,

    -(A::AbstractArray{T}, b::Date) where {T<:Date}

    generates ambiguities for anyone who defines a method

    -(A::MyArrayType{T}, b::T) where {T}

    The best approach is to avoid defining either of these methods: instead, rely on a generic method -(A::AbstractArray, b) and make sure this method is implemented with generic calls (like similar and -) that do the right thing for each container type and element type separately. This is just a more complex variant of the advice to orthogonalize your methods.

    When this approach is not possible, it may be worth starting a discussion with other developers about resolving the ambiguity; just because one method was defined first does not necessarily mean that it can't be modified or eliminated. As a last resort, one developer can define the "band-aid" method

    -(A::MyArrayType{T}, b::Date) where {T<:Date} = ...

    that resolves the ambiguity by brute force.

    Complex method "cascades" with default arguments

    If you are defining a method "cascade" that supplies defaults, be careful about dropping any arguments that correspond to potential defaults. For example, suppose you're writing a digital filtering algorithm and you have a method that handles the edges of the signal by applying padding:

    function myfilter(A, kernel, ::Replicate)
    -    Apadded = replicate_edges(A, size(kernel))
    -    myfilter(Apadded, kernel)  # now perform the "real" computation
    -end

    This will run afoul of a method that supplies default padding:

    myfilter(A, kernel) = myfilter(A, kernel, Replicate()) # replicate the edge by default

    Together, these two methods generate an infinite recursion with A constantly growing bigger.

    The better design would be to define your call hierarchy like this:

    struct NoPad end  # indicate that no padding is desired, or that it's already applied
    -
    -myfilter(A, kernel) = myfilter(A, kernel, Replicate())  # default boundary conditions
    -
    -function myfilter(A, kernel, ::Replicate)
    -    Apadded = replicate_edges(A, size(kernel))
    -    myfilter(Apadded, kernel, NoPad())  # indicate the new boundary conditions
    -end
    -
    -# other padding methods go here
    -
    -function myfilter(A, kernel, ::NoPad)
    -    # Here's the "real" implementation of the core computation
    -end

    NoPad is supplied in the same argument position as any other kind of padding, so it keeps the dispatch hierarchy well organized and with reduced likelihood of ambiguities. Moreover, it extends the "public" myfilter interface: a user who wants to control the padding explicitly can call the NoPad variant directly.

    [Clarke61]

    Arthur C. Clarke, Profiles of the Future (1961): Clarke's Third Law.

    diff --git a/julia-0.6.3/share/doc/julia/html/en/manual/modules.html b/julia-0.6.3/share/doc/julia/html/en/manual/modules.html deleted file mode 100644 index 4c8c117..0000000 --- a/julia-0.6.3/share/doc/julia/html/en/manual/modules.html +++ /dev/null @@ -1,79 +0,0 @@ - -Modules · The Julia Language

    Modules

    Modules

    Modules in Julia are separate variable workspaces, i.e. they introduce a new global scope. They are delimited syntactically, inside module Name ... end. Modules allow you to create top-level definitions (aka global variables) without worrying about name conflicts when your code is used together with somebody else's. Within a module, you can control which names from other modules are visible (via importing), and specify which of your names are intended to be public (via exporting).

    The following example demonstrates the major features of modules. It is not meant to be run, but is shown for illustrative purposes:

    module MyModule
    -using Lib
    -
    -using BigLib: thing1, thing2
    -
    -import Base.show
    -
    -importall OtherLib
    -
    -export MyType, foo
    -
    -struct MyType
    -    x
    -end
    -
    -bar(x) = 2x
    -foo(a::MyType) = bar(a.x) + 1
    -
    -show(io::IO, a::MyType) = print(io, "MyType $(a.x)")
    -end

    Note that the style is not to indent the body of the module, since that would typically lead to whole files being indented.

    This module defines a type MyType, and two functions. Function foo and type MyType are exported, and so will be available for importing into other modules. Function bar is private to MyModule.

    The statement using Lib means that a module called Lib will be available for resolving names as needed. When a global variable is encountered that has no definition in the current module, the system will search for it among variables exported by Lib and import it if it is found there. This means that all uses of that global within the current module will resolve to the definition of that variable in Lib.

    The statement using BigLib: thing1, thing2 is a syntactic shortcut for using BigLib.thing1, BigLib.thing2.

    The import keyword supports all the same syntax as using, but only operates on a single name at a time. It does not add modules to be searched the way using does. import also differs from using in that functions must be imported using import to be extended with new methods.

    In MyModule above we wanted to add a method to the standard show function, so we had to write import Base.show. Functions whose names are only visible via using cannot be extended.

    The keyword importall explicitly imports all names exported by the specified module, as if import were individually used on all of them.

    Once a variable is made visible via using or import, a module may not create its own variable with the same name. Imported variables are read-only; assigning to a global variable always affects a variable owned by the current module, or else raises an error.

    Summary of module usage

    To load a module, two main keywords can be used: using and import. To understand their differences, consider the following example:

    module MyModule
    -
    -export x, y
    -
    -x() = "x"
    -y() = "y"
    -p() = "p"
    -
    -end

    In this module we export the x and y functions (with the keyword export), and also have the non-exported function p. There are several different ways to load the Module and its inner functions into the current workspace:

    Import CommandWhat is brought into scopeAvailable for method extension
    using MyModuleAll exported names (x and y), MyModule.x, MyModule.y and MyModule.pMyModule.x, MyModule.y and MyModule.p
    using MyModule.x, MyModule.px and p 
    using MyModule: x, px and p 
    import MyModuleMyModule.x, MyModule.y and MyModule.pMyModule.x, MyModule.y and MyModule.p
    import MyModule.x, MyModule.px and px and p
    import MyModule: x, px and px and p
    importall MyModuleAll exported names (x and y)x and y

    Modules and files

    Files and file names are mostly unrelated to modules; modules are associated only with module expressions. One can have multiple files per module, and multiple modules per file:

    module Foo
    -
    -include("file1.jl")
    -include("file2.jl")
    -
    -end

    Including the same code in different modules provides mixin-like behavior. One could use this to run the same code with different base definitions, for example testing code by running it with "safe" versions of some operators:

    module Normal
    -include("mycode.jl")
    -end
    -
    -module Testing
    -include("safe_operators.jl")
    -include("mycode.jl")
    -end

    Standard modules

    There are three important standard modules: Main, Core, and Base.

    Main is the top-level module, and Julia starts with Main set as the current module. Variables defined at the prompt go in Main, and whos() lists variables in Main.

    Core contains all identifiers considered "built in" to the language, i.e. part of the core language and not libraries. Every module implicitly specifies using Core, since you can't do anything without those definitions.

    Base is the standard library (the contents of base/). All modules implicitly contain using Base, since this is needed in the vast majority of cases.

    Default top-level definitions and bare modules

    In addition to using Base, modules also automatically contain a definition of the eval function, which evaluates expressions within the context of that module.

    If these default definitions are not wanted, modules can be defined using the keyword baremodule instead (note: Core is still imported, as per above). In terms of baremodule, a standard module looks like this:

    baremodule Mod
    -
    -using Base
    -
    -eval(x) = Core.eval(Mod, x)
    -eval(m,x) = Core.eval(m, x)
    -
    -...
    -
    -end

    Relative and absolute module paths

    Given the statement using Foo, the system looks for Foo within Main. If the module does not exist, the system attempts to require("Foo"), which typically results in loading code from an installed package.

    However, some modules contain submodules, which means you sometimes need to access a module that is not directly available in Main. There are two ways to do this. The first is to use an absolute path, for example using Base.Sort. The second is to use a relative path, which makes it easier to import submodules of the current module or any of its enclosing modules:

    module Parent
    -
    -module Utils
    -...
    -end
    -
    -using .Utils
    -
    -...
    -end

    Here module Parent contains a submodule Utils, and code in Parent wants the contents of Utils to be visible. This is done by starting the using path with a period. Adding more leading periods moves up additional levels in the module hierarchy. For example using ..Utils would look for Utils in Parent's enclosing module rather than in Parent itself.

    Note that relative-import qualifiers are only valid in using and import statements.

    Module file paths

    The global variable LOAD_PATH contains the directories Julia searches for modules when calling require. It can be extended using push!:

    push!(LOAD_PATH, "/Path/To/My/Module/")

    Putting this statement in the file ~/.juliarc.jl will extend LOAD_PATH on every Julia startup. Alternatively, the module load path can be extended by defining the environment variable JULIA_LOAD_PATH.

    Namespace miscellanea

    If a name is qualified (e.g. Base.sin), then it can be accessed even if it is not exported. This is often useful when debugging. It can also have methods added to it by using the qualified name as the function name. However, due to syntactic ambiguities that arise, if you wish to add methods to a function in a different module whose name contains only symbols, such as an operator, Base.+ for example, you must use Base.:+ to refer to it. If the operator is more than one character in length you must surround it in brackets, such as: Base.:(==).

    Macro names are written with @ in import and export statements, e.g. import Mod.@mac. Macros in other modules can be invoked as Mod.@mac or @Mod.mac.

    The syntax M.x = y does not work to assign a global in another module; global assignment is always module-local.

    A variable can be "reserved" for the current module without assigning to it by declaring it as global x at the top level. This can be used to prevent name conflicts for globals initialized after load time.

    Module initialization and precompilation

    Large modules can take several seconds to load because executing all of the statements in a module often involves compiling a large amount of code. Julia provides the ability to create precompiled versions of modules to reduce this time.

    To create an incremental precompiled module file, add __precompile__() at the top of your module file (before the module starts). This will cause it to be automatically compiled the first time it is imported. Alternatively, you can manually call Base.compilecache(modulename). The resulting cache files will be stored in Base.LOAD_CACHE_PATH[1]. Subsequently, the module is automatically recompiled upon import whenever any of its dependencies change; dependencies are modules it imports, the Julia build, files it includes, or explicit dependencies declared by include_dependency(path) in the module file(s).

    For file dependencies, a change is determined by examining whether the modification time (mtime) of each file loaded by include or added explicitly by include_dependency is unchanged, or equal to the modification time truncated to the nearest second (to accommodate systems that can't copy mtime with sub-second accuracy). It also takes into account whether the path to the file chosen by the search logic in require matches the path that had created the precompile file.

    It also takes into account the set of dependencies already loaded into the current process and won't recompile those modules, even if their files change or disappear, in order to avoid creating incompatibilities between the running system and the precompile cache. If you want to have changes to the source reflected in the running system, you should call reload("Module") on the module you changed, and any module that depended on it in which you want to see the change reflected.

    Precompiling a module also recursively precompiles any modules that are imported therein. If you know that it is not safe to precompile your module (for the reasons described below), you should put __precompile__(false) in the module file to cause Base.compilecache to throw an error (and thereby prevent the module from being imported by any other precompiled module).

    __precompile__() should not be used in a module unless all of its dependencies are also using __precompile__(). Failure to do so can result in a runtime error when loading the module.

    In order to make your module work with precompilation, however, you may need to change your module to explicitly separate any initialization steps that must occur at runtime from steps that can occur at compile time. For this purpose, Julia allows you to define an __init__() function in your module that executes any initialization steps that must occur at runtime. This function will not be called during compilation (--output-* or __precompile__()). You may, of course, call it manually if necessary, but the default is to assume this function deals with computing state for the local machine, which does not need to be – or even should not be – captured in the compiled image. It will be called after the module is loaded into a process, including if it is being loaded into an incremental compile (--output-incremental=yes), but not if it is being loaded into a full-compilation process.

    In particular, if you define a function __init__() in a module, then Julia will call __init__() immediately after the module is loaded (e.g., by import, using, or require) at runtime for the first time (i.e., __init__ is only called once, and only after all statements in the module have been executed). Because it is called after the module is fully imported, any submodules or other imported modules have their __init__ functions called before the __init__ of the enclosing module.

    Two typical uses of __init__ are calling runtime initialization functions of external C libraries and initializing global constants that involve pointers returned by external libraries. For example, suppose that we are calling a C library libfoo that requires us to call a foo_init() initialization function at runtime. Suppose that we also want to define a global constant foo_data_ptr that holds the return value of a void *foo_data() function defined by libfoo – this constant must be initialized at runtime (not at compile time) because the pointer address will change from run to run. You could accomplish this by defining the following __init__ function in your module:

    const foo_data_ptr = Ref{Ptr{Void}}(0)
    -function __init__()
    -    ccall((:foo_init, :libfoo), Void, ())
    -    foo_data_ptr[] = ccall((:foo_data, :libfoo), Ptr{Void}, ())
    -end

    Notice that it is perfectly possible to define a global inside a function like __init__; this is one of the advantages of using a dynamic language. But by making it a constant at global scope, we can ensure that the type is known to the compiler and allow it to generate better optimized code. Obviously, any other globals in your module that depends on foo_data_ptr would also have to be initialized in __init__.

    Constants involving most Julia objects that are not produced by ccall do not need to be placed in __init__: their definitions can be precompiled and loaded from the cached module image. This includes complicated heap-allocated objects like arrays. However, any routine that returns a raw pointer value must be called at runtime for precompilation to work (Ptr objects will turn into null pointers unless they are hidden inside an isbits object). This includes the return values of the Julia functions cfunction and pointer.

    Dictionary and set types, or in general anything that depends on the output of a hash(key) method, are a trickier case. In the common case where the keys are numbers, strings, symbols, ranges, Expr, or compositions of these types (via arrays, tuples, sets, pairs, etc.) they are safe to precompile. However, for a few other key types, such as Function or DataType and generic user-defined types where you haven't defined a hash method, the fallback hash method depends on the memory address of the object (via its object_id) and hence may change from run to run. If you have one of these key types, or if you aren't sure, to be safe you can initialize this dictionary from within your __init__ function. Alternatively, you can use the ObjectIdDict dictionary type, which is specially handled by precompilation so that it is safe to initialize at compile-time.

    When using precompilation, it is important to keep a clear sense of the distinction between the compilation phase and the execution phase. In this mode, it will often be much more clearly apparent that Julia is a compiler which allows execution of arbitrary Julia code, not a standalone interpreter that also generates compiled code.

    Other known potential failure scenarios include:

    1. Global counters (for example, for attempting to uniquely identify objects) Consider the following code snippet:

      mutable struct UniquedById
      -    myid::Int
      -    let counter = 0
      -        UniquedById() = new(counter += 1)
      -    end
      -end

      while the intent of this code was to give every instance a unique id, the counter value is recorded at the end of compilation. All subsequent usages of this incrementally compiled module will start from that same counter value.

      Note that object_id (which works by hashing the memory pointer) has similar issues (see notes on Dict usage below).

      One alternative is to store both current_module() and the current counter value, however, it may be better to redesign the code to not depend on this global state.

    2. Associative collections (such as Dict and Set) need to be re-hashed in __init__. (In the future, a mechanism may be provided to register an initializer function.)

    3. Depending on compile-time side-effects persisting through load-time. Example include: modifying arrays or other variables in other Julia modules; maintaining handles to open files or devices; storing pointers to other system resources (including memory);

    4. Creating accidental "copies" of global state from another module, by referencing it directly instead of via its lookup path. For example, (in global scope):

      #mystdout = Base.STDOUT #= will not work correctly, since this will copy Base.STDOUT into this module =#
      -# instead use accessor functions:
      -getstdout() = Base.STDOUT #= best option =#
      -# or move the assignment into the runtime:
      -__init__() = global mystdout = Base.STDOUT #= also works =#

    Several additional restrictions are placed on the operations that can be done while precompiling code to help the user avoid other wrong-behavior situations:

    1. Calling eval to cause a side-effect in another module. This will also cause a warning to be emitted when the incremental precompile flag is set.

    2. global const statements from local scope after __init__() has been started (see issue #12010 for plans to add an error for this)

    3. Replacing a module (or calling workspace()) is a runtime error while doing an incremental precompile.

    A few other points to be aware of:

    1. No code reload / cache invalidation is performed after changes are made to the source files themselves, (including by Pkg.update), and no cleanup is done after Pkg.rm

    2. The memory sharing behavior of a reshaped array is disregarded by precompilation (each view gets its own copy)

    3. Expecting the filesystem to be unchanged between compile-time and runtime e.g. @__FILE__/source_path() to find resources at runtime, or the BinDeps @checked_lib macro. Sometimes this is unavoidable. However, when possible, it can be good practice to copy resources into the module at compile-time so they won't need to be found at runtime.

    4. WeakRef objects and finalizers are not currently handled properly by the serializer (this will be fixed in an upcoming release).

    5. It is usually best to avoid capturing references to instances of internal metadata objects such as Method, MethodInstance, MethodTable, TypeMapLevel, TypeMapEntry and fields of those objects, as this can confuse the serializer and may not lead to the outcome you desire. It is not necessarily an error to do this, but you simply need to be prepared that the system will try to copy some of these and to create a single unique instance of others.

    It is sometimes helpful during module development to turn off incremental precompilation. The command line flag --compilecache={yes|no} enables you to toggle module precompilation on and off. When Julia is started with --compilecache=no the serialized modules in the compile cache are ignored when loading modules and module dependencies. Base.compilecache() can still be called manually and it will respect __precompile__() directives for the module. The state of this command line flag is passed to Pkg.build() to disable automatic precompilation triggering when installing, updating, and explicitly building packages.

    diff --git a/julia-0.6.3/share/doc/julia/html/en/manual/networking-and-streams.html b/julia-0.6.3/share/doc/julia/html/en/manual/networking-and-streams.html deleted file mode 100644 index 2c3945b..0000000 --- a/julia-0.6.3/share/doc/julia/html/en/manual/networking-and-streams.html +++ /dev/null @@ -1,104 +0,0 @@ - -Networking and Streams · The Julia Language

    Networking and Streams

    Networking and Streams

    Julia provides a rich interface to deal with streaming I/O objects such as terminals, pipes and TCP sockets. This interface, though asynchronous at the system level, is presented in a synchronous manner to the programmer and it is usually unnecessary to think about the underlying asynchronous operation. This is achieved by making heavy use of Julia cooperative threading (coroutine) functionality.

    Basic Stream I/O

    All Julia streams expose at least a read() and a write() method, taking the stream as their first argument, e.g.:

    julia> write(STDOUT,"Hello World");  # suppress return value 11 with ;
    -Hello World
    -julia> read(STDIN,Char)
    -
    -'\n': ASCII/Unicode U+000a (category Cc: Other, control)

    Note that write() returns 11, the number of bytes (in "Hello World") written to STDOUT, but this return value is suppressed with the ;.

    Here Enter was pressed again so that Julia would read the newline. Now, as you can see from this example, write() takes the data to write as its second argument, while read() takes the type of the data to be read as the second argument.

    For example, to read a simple byte array, we could do:

    julia> x = zeros(UInt8, 4)
    -4-element Array{UInt8,1}:
    - 0x00
    - 0x00
    - 0x00
    - 0x00
    -
    -julia> read!(STDIN, x)
    -abcd
    -4-element Array{UInt8,1}:
    - 0x61
    - 0x62
    - 0x63
    - 0x64

    However, since this is slightly cumbersome, there are several convenience methods provided. For example, we could have written the above as:

    julia> read(STDIN,4)
    -abcd
    -4-element Array{UInt8,1}:
    - 0x61
    - 0x62
    - 0x63
    - 0x64

    or if we had wanted to read the entire line instead:

    julia> readline(STDIN)
    -abcd
    -"abcd"

    Note that depending on your terminal settings, your TTY may be line buffered and might thus require an additional enter before the data is sent to Julia.

    To read every line from STDIN you can use eachline():

    for line in eachline(STDIN)
    -    print("Found $line")
    -end

    or read() if you wanted to read by character instead:

    while !eof(STDIN)
    -    x = read(STDIN, Char)
    -    println("Found: $x")
    -end

    Text I/O

    Note that the write() method mentioned above operates on binary streams. In particular, values do not get converted to any canonical text representation but are written out as is:

    julia> write(STDOUT,0x61);  # suppress return value 1 with ;
    -a

    Note that a is written to STDOUT by the write() function and that the returned value is 1 (since 0x61 is one byte).

    For text I/O, use the print() or show() methods, depending on your needs (see the standard library reference for a detailed discussion of the difference between the two):

    julia> print(STDOUT, 0x61)
    -97

    IO Output Contextual Properties

    Sometimes IO output can benefit from the ability to pass contextual information into show methods. The IOContext object provides this framework for associating arbitrary metadata with an IO object. For example, showcompact adds a hinting parameter to the IO object that the invoked show method should print a shorter output (if applicable).

    Working with Files

    Like many other environments, Julia has an open() function, which takes a filename and returns an IOStream object that you can use to read and write things from the file. For example if we have a file, hello.txt, whose contents are Hello, World!:

    julia> f = open("hello.txt")
    -IOStream(<file hello.txt>)
    -
    -julia> readlines(f)
    -1-element Array{String,1}:
    - "Hello, World!"

    If you want to write to a file, you can open it with the write ("w") flag:

    julia> f = open("hello.txt","w")
    -IOStream(<file hello.txt>)
    -
    -julia> write(f,"Hello again.")
    -12

    If you examine the contents of hello.txt at this point, you will notice that it is empty; nothing has actually been written to disk yet. This is because the IOStream must be closed before the write is actually flushed to disk:

    julia> close(f)

    Examining hello.txt again will show its contents have been changed.

    Opening a file, doing something to its contents, and closing it again is a very common pattern. To make this easier, there exists another invocation of open() which takes a function as its first argument and filename as its second, opens the file, calls the function with the file as an argument, and then closes it again. For example, given a function:

    function read_and_capitalize(f::IOStream)
    -    return uppercase(readstring(f))
    -end

    You can call:

    julia> open(read_and_capitalize, "hello.txt")
    -"HELLO AGAIN."

    to open hello.txt, call read_and_capitalize on it, close hello.txt and return the capitalized contents.

    To avoid even having to define a named function, you can use the do syntax, which creates an anonymous function on the fly:

    julia> open("hello.txt") do f
    -           uppercase(readstring(f))
    -       end
    -"HELLO AGAIN."

    A simple TCP example

    Let's jump right in with a simple example involving TCP sockets. Let's first create a simple server:

    julia> @async begin
    -           server = listen(2000)
    -           while true
    -               sock = accept(server)
    -               println("Hello World\n")
    -           end
    -       end
    -Task (runnable) @0x00007fd31dc11ae0

    To those familiar with the Unix socket API, the method names will feel familiar, though their usage is somewhat simpler than the raw Unix socket API. The first call to listen() will create a server waiting for incoming connections on the specified port (2000) in this case. The same function may also be used to create various other kinds of servers:

    julia> listen(2000) # Listens on localhost:2000 (IPv4)
    -TCPServer(active)
    -
    -julia> listen(ip"127.0.0.1",2000) # Equivalent to the first
    -TCPServer(active)
    -
    -julia> listen(ip"::1",2000) # Listens on localhost:2000 (IPv6)
    -TCPServer(active)
    -
    -julia> listen(IPv4(0),2001) # Listens on port 2001 on all IPv4 interfaces
    -TCPServer(active)
    -
    -julia> listen(IPv6(0),2001) # Listens on port 2001 on all IPv6 interfaces
    -TCPServer(active)
    -
    -julia> listen("testsocket") # Listens on a UNIX domain socket/named pipe
    -PipeServer(active)

    Note that the return type of the last invocation is different. This is because this server does not listen on TCP, but rather on a named pipe (Windows) or UNIX domain socket. The difference is subtle and has to do with the accept() and connect() methods. The accept() method retrieves a connection to the client that is connecting on the server we just created, while the connect() function connects to a server using the specified method. The connect() function takes the same arguments as listen(), so, assuming the environment (i.e. host, cwd, etc.) is the same you should be able to pass the same arguments to connect() as you did to listen to establish the connection. So let's try that out (after having created the server above):

    julia> connect(2000)
    -TCPSocket(open, 0 bytes waiting)
    -
    -julia> Hello World

    As expected we saw "Hello World" printed. So, let's actually analyze what happened behind the scenes. When we called connect(), we connect to the server we had just created. Meanwhile, the accept function returns a server-side connection to the newly created socket and prints "Hello World" to indicate that the connection was successful.

    A great strength of Julia is that since the API is exposed synchronously even though the I/O is actually happening asynchronously, we didn't have to worry callbacks or even making sure that the server gets to run. When we called connect() the current task waited for the connection to be established and only continued executing after that was done. In this pause, the server task resumed execution (because a connection request was now available), accepted the connection, printed the message and waited for the next client. Reading and writing works in the same way. To see this, consider the following simple echo server:

    julia> @async begin
    -           server = listen(2001)
    -           while true
    -               sock = accept(server)
    -               @async while isopen(sock)
    -                   write(sock,readline(sock))
    -               end
    -           end
    -       end
    -Task (runnable) @0x00007fd31dc12e60
    -
    -julia> clientside = connect(2001)
    -TCPSocket(RawFD(28) open, 0 bytes waiting)
    -
    -julia> @async while true
    -           write(STDOUT,readline(clientside))
    -       end
    -Task (runnable) @0x00007fd31dc11870
    -
    -julia> println(clientside,"Hello World from the Echo Server")
    -Hello World from the Echo Server

    As with other streams, use close() to disconnect the socket:

    julia> close(clientside)

    Resolving IP Addresses

    One of the connect() methods that does not follow the listen() methods is connect(host::String,port), which will attempt to connect to the host given by the host parameter on the port given by the port parameter. It allows you to do things like:

    julia> connect("google.com",80)
    -TCPSocket(RawFD(30) open, 0 bytes waiting)

    At the base of this functionality is getaddrinfo(), which will do the appropriate address resolution:

    julia> getaddrinfo("google.com")
    -ip"74.125.226.225"
    diff --git a/julia-0.6.3/share/doc/julia/html/en/manual/noteworthy-differences.html b/julia-0.6.3/share/doc/julia/html/en/manual/noteworthy-differences.html deleted file mode 100644 index f413f80..0000000 --- a/julia-0.6.3/share/doc/julia/html/en/manual/noteworthy-differences.html +++ /dev/null @@ -1,9 +0,0 @@ - -Noteworthy Differences from other Languages · The Julia Language

    Noteworthy Differences from other Languages

    Noteworthy Differences from other Languages

    Noteworthy differences from MATLAB

    Although MATLAB users may find Julia's syntax familiar, Julia is not a MATLAB clone. There are major syntactic and functional differences. The following are some noteworthy differences that may trip up Julia users accustomed to MATLAB:

    • Julia arrays are indexed with square brackets, A[i,j].

    • Julia arrays are assigned by reference. After A=B, changing elements of B will modify A as well.

    • Julia values are passed and assigned by reference. If a function modifies an array, the changes will be visible in the caller.

    • Julia does not automatically grow arrays in an assignment statement. Whereas in MATLAB a(4) = 3.2 can create the array a = [0 0 0 3.2] and a(5) = 7 can grow it into a = [0 0 0 3.2 7], the corresponding Julia statement a[5] = 7 throws an error if the length of a is less than 5 or if this statement is the first use of the identifier a. Julia has push!() and append!(), which grow Vectors much more efficiently than MATLAB's a(end+1) = val.

    • The imaginary unit sqrt(-1) is represented in Julia as im, not i or j as in MATLAB.

    • In Julia, literal numbers without a decimal point (such as 42) create integers instead of floating point numbers. Arbitrarily large integer literals are supported. As a result, some operations such as 2^-1 will throw a domain error as the result is not an integer (see the FAQ entry on domain errors for details).

    • In Julia, multiple values are returned and assigned as tuples, e.g. (a, b) = (1, 2) or a, b = 1, 2. MATLAB's nargout, which is often used in MATLAB to do optional work based on the number of returned values, does not exist in Julia. Instead, users can use optional and keyword arguments to achieve similar capabilities.

    • Julia has true one-dimensional arrays. Column vectors are of size N, not Nx1. For example, rand(N) makes a 1-dimensional array.

    • In Julia, [x,y,z] will always construct a 3-element array containing x, y and z.

      • To concatenate in the first ("vertical") dimension use either vcat(x,y,z) or separate with semicolons ([x; y; z]).

      • To concatenate in the second ("horizontal") dimension use either hcat(x,y,z) or separate with spaces ([x y z]).

      • To construct block matrices (concatenating in the first two dimensions), use either hvcat() or combine spaces and semicolons ([a b; c d]).

    • In Julia, a:b and a:b:c construct Range objects. To construct a full vector like in MATLAB, use collect(a:b). Generally, there is no need to call collect though. Range will act like a normal array in most cases but is more efficient because it lazily computes its values. This pattern of creating specialized objects instead of full arrays is used frequently, and is also seen in functions such as linspace, or with iterators such as enumerate, and zip. The special objects can mostly be used as if they were normal arrays.

    • Functions in Julia return values from their last expression or the return keyword instead of listing the names of variables to return in the function definition (see The return Keyword for details).

    • A Julia script may contain any number of functions, and all definitions will be externally visible when the file is loaded. Function definitions can be loaded from files outside the current working directory.

    • In Julia, reductions such as sum(), prod(), and max() are performed over every element of an array when called with a single argument, as in sum(A), even if A has more than one dimension.

    • In Julia, functions such as sort() that operate column-wise by default (sort(A) is equivalent to sort(A,1)) do not have special behavior for 1xN arrays; the argument is returned unmodified since it still performs sort(A,1). To sort a 1xN matrix like a vector, use sort(A,2).

    • In Julia, if A is a 2-dimensional array, fft(A) computes a 2D FFT. In particular, it is not equivalent to fft(A,1), which computes a 1D FFT acting column-wise.

    • In Julia, parentheses must be used to call a function with zero arguments, like in tic() and toc().

    • Julia discourages the used of semicolons to end statements. The results of statements are not automatically printed (except at the interactive prompt), and lines of code do not need to end with semicolons. println() or @printf() can be used to print specific output.

    • In Julia, if A and B are arrays, logical comparison operations like A == B do not return an array of booleans. Instead, use A .== B, and similarly for the other boolean operators like <, > and =.

    • In Julia, the operators &, |, and (xor) perform the bitwise operations equivalent to and, or, and xor respectively in MATLAB, and have precedence similar to Python's bitwise operators (unlike C). They can operate on scalars or element-wise across arrays and can be used to combine logical arrays, but note the difference in order of operations: parentheses may be required (e.g., to select elements of A equal to 1 or 2 use (A .== 1) | (A .== 2)).

    • In Julia, the elements of a collection can be passed as arguments to a function using the splat operator ..., as in xs=[1,2]; f(xs...).

    • Julia's svd() returns singular values as a vector instead of as a dense diagonal matrix.

    • In Julia, ... is not used to continue lines of code. Instead, incomplete expressions automatically continue onto the next line.

    • In both Julia and MATLAB, the variable ans is set to the value of the last expression issued in an interactive session. In Julia, unlike MATLAB, ans is not set when Julia code is run in non-interactive mode.

    • Julia's types do not support dynamically adding fields at runtime, unlike MATLAB's classes. Instead, use a Dict.

    • In Julia each module has its own global scope/namespace, whereas in MATLAB there is just one global scope.

    • In MATLAB, an idiomatic way to remove unwanted values is to use logical indexing, like in the expression x(x>3) or in the statement x(x>3) = [] to modify x in-place. In contrast, Julia provides the higher order functions filter() and filter!(), allowing users to write filter(z->z>3, x) and filter!(z->z>3, x) as alternatives to the corresponding transliterations x[x.>3] and x = x[x.>3]. Using filter!() reduces the use of temporary arrays.

    • The analogue of extracting (or "dereferencing") all elements of a cell array, e.g. in vertcat(A{:}) in MATLAB, is written using the splat operator in Julia, e.g. as vcat(A...).

    Noteworthy differences from R

    One of Julia's goals is to provide an effective language for data analysis and statistical programming. For users coming to Julia from R, these are some noteworthy differences:

    • Julia's single quotes enclose characters, not strings.

    • Julia can create substrings by indexing into strings. In R, strings must be converted into character vectors before creating substrings.

    • In Julia, like Python but unlike R, strings can be created with triple quotes """ ... """. This syntax is convenient for constructing strings that contain line breaks.

    • In Julia, varargs are specified using the splat operator ..., which always follows the name of a specific variable, unlike R, for which ... can occur in isolation.

    • In Julia, modulus is mod(a, b), not a %% b. % in Julia is the remainder operator.

    • In Julia, not all data structures support logical indexing. Furthermore, logical indexing in Julia is supported only with vectors of length equal to the object being indexed. For example:

      • In R, c(1, 2, 3, 4)[c(TRUE, FALSE)] is equivalent to c(1, 3).

      • In R, c(1, 2, 3, 4)[c(TRUE, FALSE, TRUE, FALSE)] is equivalent to c(1, 3).

      • In Julia, [1, 2, 3, 4][[true, false]] throws a BoundsError.

      • In Julia, [1, 2, 3, 4][[true, false, true, false]] produces [1, 3].

    • Like many languages, Julia does not always allow operations on vectors of different lengths, unlike R where the vectors only need to share a common index range. For example, c(1, 2, 3, 4) + c(1, 2) is valid R but the equivalent [1, 2, 3, 4] + [1, 2] will throw an error in Julia.

    • Julia's map() takes the function first, then its arguments, unlike lapply(<structure>, function, ...) in R. Similarly Julia's equivalent of apply(X, MARGIN, FUN, ...) in R is mapslices() where the function is the first argument.

    • Multivariate apply in R, e.g. mapply(choose, 11:13, 1:3), can be written as broadcast(binomial, 11:13, 1:3) in Julia. Equivalently Julia offers a shorter dot syntax for vectorizing functions binomial.(11:13, 1:3).

    • Julia uses end to denote the end of conditional blocks, like if, loop blocks, like while/ for, and functions. In lieu of the one-line if ( cond ) statement, Julia allows statements of the form if cond; statement; end, cond && statement and !cond || statement. Assignment statements in the latter two syntaxes must be explicitly wrapped in parentheses, e.g. cond && (x = value).

    • In Julia, <-, <<- and -> are not assignment operators.

    • Julia's -> creates an anonymous function, like Python.

    • Julia constructs vectors using brackets. Julia's [1, 2, 3] is the equivalent of R's c(1, 2, 3).

    • Julia's * operator can perform matrix multiplication, unlike in R. If A and B are matrices, then A * B denotes a matrix multiplication in Julia, equivalent to R's A %*% B. In R, this same notation would perform an element-wise (Hadamard) product. To get the element-wise multiplication operation, you need to write A .* B in Julia.

    • Julia performs matrix transposition using the .' operator and conjugated transposition using the ' operator. Julia's A.' is therefore equivalent to R's t(A).

    • Julia does not require parentheses when writing if statements or for/while loops: use for i in [1, 2, 3] instead of for (i in c(1, 2, 3)) and if i == 1 instead of if (i == 1).

    • Julia does not treat the numbers 0 and 1 as Booleans. You cannot write if (1) in Julia, because if statements accept only booleans. Instead, you can write if true, if Bool(1), or if 1==1.

    • Julia does not provide nrow and ncol. Instead, use size(M, 1) for nrow(M) and size(M, 2) for ncol(M).

    • Julia is careful to distinguish scalars, vectors and matrices. In R, 1 and c(1) are the same. In Julia, they cannot be used interchangeably.

    • Julia's diag and diagm are not like R's.

    • Julia cannot assign to the results of function calls on the left hand side of an assignment operation: you cannot write diag(M) = ones(n).

    • Julia discourages populating the main namespace with functions. Most statistical functionality for Julia is found in packages under the JuliaStats organization. For example:

    • Julia provides tuples and real hash tables, but not R-style lists. When returning multiple items, you should typically use a tuple: instead of list(a = 1, b = 2), use (1, 2).

    • Julia encourages users to write their own types, which are easier to use than S3 or S4 objects in R. Julia's multiple dispatch system means that table(x::TypeA) and table(x::TypeB) act like R's table.TypeA(x) and table.TypeB(x).

    • In Julia, values are passed and assigned by reference. If a function modifies an array, the changes will be visible in the caller. This is very different from R and allows new functions to operate on large data structures much more efficiently.

    • In Julia, vectors and matrices are concatenated using hcat(), vcat() and hvcat(), not c, rbind and cbind like in R.

    • In Julia, a range like a:b is not shorthand for a vector like in R, but is a specialized Range that is used for iteration without high memory overhead. To convert a range into a vector, use collect(a:b).

    • Julia's max() and min() are the equivalent of pmax and pmin respectively in R, but both arguments need to have the same dimensions. While maximum() and minimum() replace max and min in R, there are important differences.

    • Julia's sum(), prod(), maximum(), and minimum() are different from their counterparts in R. They all accept one or two arguments. The first argument is an iterable collection such as an array. If there is a second argument, then this argument indicates the dimensions, over which the operation is carried out. For instance, let A=[[1 2],[3 4]] in Julia and B=rbind(c(1,2),c(3,4)) be the same matrix in R. Then sum(A) gives the same result as sum(B), but sum(A, 1) is a row vector containing the sum over each column and sum(A, 2) is a column vector containing the sum over each row. This contrasts to the behavior of R, where sum(B,1)=11 and sum(B,2)=12. If the second argument is a vector, then it specifies all the dimensions over which the sum is performed, e.g., sum(A,[1,2])=10. It should be noted that there is no error checking regarding the second argument.

    • Julia has several functions that can mutate their arguments. For example, it has both sort() and sort!().

    • In R, performance requires vectorization. In Julia, almost the opposite is true: the best performing code is often achieved by using devectorized loops.

    • Julia is eagerly evaluated and does not support R-style lazy evaluation. For most users, this means that there are very few unquoted expressions or column names.

    • Julia does not support the NULL type.

    • Julia lacks the equivalent of R's assign or get.

    • In Julia, return does not require parentheses.

    • In R, an idiomatic way to remove unwanted values is to use logical indexing, like in the expression x[x>3] or in the statement x = x[x>3] to modify x in-place. In contrast, Julia provides the higher order functions filter() and filter!(), allowing users to write filter(z->z>3, x) and filter!(z->z>3, x) as alternatives to the corresponding transliterations x[x.>3] and x = x[x.>3]. Using filter!() reduces the use of temporary arrays.

    Noteworthy differences from Python

    • Julia requires end to end a block. Unlike Python, Julia has no pass keyword.

    • In Julia, indexing of arrays, strings, etc. is 1-based not 0-based.

    • Julia's slice indexing includes the last element, unlike in Python. a[2:3] in Julia is a[1:3] in Python.

    • Julia does not support negative indexes. In particular, the last element of a list or array is indexed with end in Julia, not -1 as in Python.

    • Julia's for, if, while, etc. blocks are terminated by the end keyword. Indentation level is not significant as it is in Python.

    • Julia has no line continuation syntax: if, at the end of a line, the input so far is a complete expression, it is considered done; otherwise the input continues. One way to force an expression to continue is to wrap it in parentheses.

    • Julia arrays are column major (Fortran ordered) whereas NumPy arrays are row major (C-ordered) by default. To get optimal performance when looping over arrays, the order of the loops should be reversed in Julia relative to NumPy (see relevant section of Performance Tips).

    • Julia's updating operators (e.g. +=, -=, ...) are not in-place whereas NumPy's are. This means A = ones(4); B = A; B += 3 doesn't change values in A, it rather rebinds the name B to the result of the right- hand side B = B + 3, which is a new array. Use B[:] += 3, explicit loops, or InplaceOps.jl.

    • Julia evaluates default values of function arguments every time the method is invoked, unlike in Python where the default values are evaluated only once when the function is defined. For example, the function f(x=rand()) = x returns a new random number every time it is invoked without argument. On the other hand, the function g(x=[1,2]) = push!(x,3) returns [1,2,3] every time it is called as g().

    • In Julia % is the remainder operator, whereas in Python it is the modulus.

    Noteworthy differences from C/C++

    • Julia arrays are indexed with square brackets, and can have more than one dimension A[i,j]. This syntax is not just syntactic sugar for a reference to a pointer or address as in C/C++. See the Julia documentation for the syntax for array construction (it has changed between versions).

    • In Julia, indexing of arrays, strings, etc. is 1-based not 0-based.

    • Julia arrays are assigned by reference. After A=B, changing elements of B will modify A as well. Updating operators like += do not operate in-place, they are equivalent to A = A + B which rebinds the left-hand side to the result of the right-hand side expression.

    • Julia arrays are column major (Fortran ordered) whereas C/C++ arrays are row major ordered by default. To get optimal performance when looping over arrays, the order of the loops should be reversed in Julia relative to C/C++ (see relevant section of Performance Tips).

    • Julia values are passed and assigned by reference. If a function modifies an array, the changes will be visible in the caller.

    • In Julia, whitespace is significant, unlike C/C++, so care must be taken when adding/removing whitespace from a Julia program.

    • In Julia, literal numbers without a decimal point (such as 42) create signed integers, of type Int, but literals too large to fit in the machine word size will automatically be promoted to a larger size type, such as Int64 (if Int is Int32), Int128, or the arbitrarily large BigInt type. There are no numeric literal suffixes, such as L, LL, U, UL, ULL to indicate unsigned and/or signed vs. unsigned. Decimal literals are always signed, and hexadecimal literals (which start with 0x like C/C++), are unsigned. Hexadecimal literals also, unlike C/C++/Java and unlike decimal literals in Julia, have a type based on the length of the literal, including leading 0s. For example, 0x0 and 0x00 have type UInt8, 0x000 and 0x0000 have type UInt16, then literals with 5 to 8 hex digits have type UInt32, 9 to 16 hex digits type UInt64 and 17 to 32 hex digits type UInt128. This needs to be taken into account when defining hexadecimal masks, for example ~0xf == 0xf0 is very different from ~0x000f == 0xfff0. 64 bit Float64 and 32 bit Float32 bit literals are expressed as 1.0 and 1.0f0 respectively. Floating point literals are rounded (and not promoted to the BigFloat type) if they can not be exactly represented. Floating point literals are closer in behavior to C/C++. Octal (prefixed with 0o) and binary (prefixed with 0b) literals are also treated as unsigned.

    • String literals can be delimited with either " or """, """ delimited literals can contain " characters without quoting it like "\"" String literals can have values of other variables or expressions interpolated into them, indicated by $variablename or $(expression), which evaluates the variable name or the expression in the context of the function.

    • // indicates a Rational number, and not a single-line comment (which is # in Julia)

    • #= indicates the start of a multiline comment, and =# ends it.

    • Functions in Julia return values from their last expression(s) or the return keyword. Multiple values can be returned from functions and assigned as tuples, e.g. (a, b) = myfunction() or a, b = myfunction(), instead of having to pass pointers to values as one would have to do in C/C++ (i.e. a = myfunction(&b).

    • Julia does not require the use of semicolons to end statements. The results of expressions are not automatically printed (except at the interactive prompt, i.e. the REPL), and lines of code do not need to end with semicolons. println() or @printf() can be used to print specific output. In the REPL, ; can be used to suppress output. ; also has a different meaning within [ ], something to watch out for. ; can be used to separate expressions on a single line, but are not strictly necessary in many cases, and are more an aid to readability.

    • In Julia, the operator (xor) performs the bitwise XOR operation, i.e. ^ in C/C++. Also, the bitwise operators do not have the same precedence as C/++, so parenthesis may be required.

    • Julia's ^ is exponentiation (pow), not bitwise XOR as in C/C++ (use , or xor, in Julia)

    • Julia has two right-shift operators, >> and >>>. >>> performs an arithmetic shift, >> always performs a logical shift, unlike C/C++, where the meaning of >> depends on the type of the value being shifted.

    • Julia's -> creates an anonymous function, it does not access a member via a pointer.

    • Julia does not require parentheses when writing if statements or for/while loops: use for i in [1, 2, 3] instead of for (int i=1; i <= 3; i++) and if i == 1 instead of if (i == 1).

    • Julia does not treat the numbers 0 and 1 as Booleans. You cannot write if (1) in Julia, because if statements accept only booleans. Instead, you can write if true, if Bool(1), or if 1==1.

    • Julia uses end to denote the end of conditional blocks, like if, loop blocks, like while/ for, and functions. In lieu of the one-line if ( cond ) statement, Julia allows statements of the form if cond; statement; end, cond && statement and !cond || statement. Assignment statements in the latter two syntaxes must be explicitly wrapped in parentheses, e.g. cond && (x = value), because of the operator precedence.

    • Julia has no line continuation syntax: if, at the end of a line, the input so far is a complete expression, it is considered done; otherwise the input continues. One way to force an expression to continue is to wrap it in parentheses.

    • Julia macros operate on parsed expressions, rather than the text of the program, which allows them to perform sophisticated transformations of Julia code. Macro names start with the @ character, and have both a function-like syntax, @mymacro(arg1, arg2, arg3), and a statement-like syntax, @mymacro arg1 arg2 arg3. The forms are interchangable; the function-like form is particularly useful if the macro appears within another expression, and is often clearest. The statement-like form is often used to annotate blocks, as in the parallel for construct: @parallel for i in 1:n; #= body =#; end. Where the end of the macro construct may be unclear, use the function-like form.

    • Julia now has an enumeration type, expressed using the macro @enum(name, value1, value2, ...) For example: @enum(Fruit, banana=1, apple, pear)

    • By convention, functions that modify their arguments have a ! at the end of the name, for example push!.

    • In C++, by default, you have static dispatch, i.e. you need to annotate a function as virtual, in order to have dynamic dispatch. On the other hand, in Julia every method is "virtual" (although it's more general than that since methods are dispatched on every argument type, not only this, using the most-specific-declaration rule).

    diff --git a/julia-0.6.3/share/doc/julia/html/en/manual/packages.html b/julia-0.6.3/share/doc/julia/html/en/manual/packages.html deleted file mode 100644 index e4f1f52..0000000 --- a/julia-0.6.3/share/doc/julia/html/en/manual/packages.html +++ /dev/null @@ -1,252 +0,0 @@ - -Packages · The Julia Language

    Packages

    Packages

    Julia has a built-in package manager for installing add-on functionality written in Julia. It can also install external libraries using your operating system's standard system for doing so, or by compiling from source. The list of registered Julia packages can be found at http://pkg.julialang.org. All package manager commands are found in the Pkg module, included in Julia's Base install.

    First we'll go over the mechanics of the Pkg family of commands and then we'll provide some guidance on how to get your package registered. Be sure to read the section below on package naming conventions, tagging versions and the importance of a REQUIRE file for when you're ready to add your code to the curated METADATA repository.

    Package Status

    The Pkg.status() function prints out a summary of the state of packages you have installed. Initially, you'll have no packages installed:

    julia> Pkg.status()
    -INFO: Initializing package repository /Users/stefan/.julia/v0.6
    -INFO: Cloning METADATA from git://github.com/JuliaLang/METADATA.jl
    -No packages installed.

    Your package directory is automatically initialized the first time you run a Pkg command that expects it to exist – which includes Pkg.status(). Here's an example non-trivial set of required and additional packages:

    julia> Pkg.status()
    -Required packages:
    - - Distributions                 0.2.8
    - - SHA                           0.3.2
    -Additional packages:
    - - NumericExtensions             0.2.17
    - - Stats                         0.2.6

    These packages are all on registered versions, managed by Pkg. Packages can be in more complicated states, indicated by annotations to the right of the installed package version; we will explain these states and annotations as we encounter them. For programmatic usage, Pkg.installed() returns a dictionary, mapping installed package names to the version of that package which is installed:

    julia> Pkg.installed()
    -Dict{String,VersionNumber} with 4 entries:
    -"Distributions"     => v"0.2.8"
    -"Stats"             => v"0.2.6"
    -"SHA"               => v"0.3.2"
    -"NumericExtensions" => v"0.2.17"

    Adding and Removing Packages

    Julia's package manager is a little unusual in that it is declarative rather than imperative. This means that you tell it what you want and it figures out what versions to install (or remove) to satisfy those requirements optimally – and minimally. So rather than installing a package, you just add it to the list of requirements and then "resolve" what needs to be installed. In particular, this means that if some package had been installed because it was needed by a previous version of something you wanted, and a newer version doesn't have that requirement anymore, updating will actually remove that package.

    Your package requirements are in the file ~/.julia/v0.6/REQUIRE. You can edit this file by hand and then call Pkg.resolve() to install, upgrade or remove packages to optimally satisfy the requirements, or you can do Pkg.edit(), which will open REQUIRE in your editor (configured via the EDITOR or VISUAL environment variables), and then automatically call Pkg.resolve() afterwards if necessary. If you only want to add or remove the requirement for a single package, you can also use the non-interactive Pkg.add() and Pkg.rm() commands, which add or remove a single requirement to REQUIRE and then call Pkg.resolve().

    You can add a package to the list of requirements with the Pkg.add() function, and the package and all the packages that it depends on will be installed:

    julia> Pkg.status()
    -No packages installed.
    -
    -julia> Pkg.add("Distributions")
    -INFO: Cloning cache of Distributions from git://github.com/JuliaStats/Distributions.jl.git
    -INFO: Cloning cache of NumericExtensions from git://github.com/lindahua/NumericExtensions.jl.git
    -INFO: Cloning cache of Stats from git://github.com/JuliaStats/Stats.jl.git
    -INFO: Installing Distributions v0.2.7
    -INFO: Installing NumericExtensions v0.2.17
    -INFO: Installing Stats v0.2.6
    -INFO: REQUIRE updated.
    -
    -julia> Pkg.status()
    -Required packages:
    - - Distributions                 0.2.7
    -Additional packages:
    - - NumericExtensions             0.2.17
    - - Stats                         0.2.6

    What this is doing is first adding Distributions to your ~/.julia/v0.6/REQUIRE file:

    $ cat ~/.julia/v0.6/REQUIRE
    -Distributions

    It then runs Pkg.resolve() using these new requirements, which leads to the conclusion that the Distributions package should be installed since it is required but not installed. As stated before, you can accomplish the same thing by editing your ~/.julia/v0.6/REQUIRE file by hand and then running Pkg.resolve() yourself:

    $ echo SHA >> ~/.julia/v0.6/REQUIRE
    -
    -julia> Pkg.resolve()
    -INFO: Cloning cache of SHA from git://github.com/staticfloat/SHA.jl.git
    -INFO: Installing SHA v0.3.2
    -
    -julia> Pkg.status()
    -Required packages:
    - - Distributions                 0.2.7
    - - SHA                           0.3.2
    -Additional packages:
    - - NumericExtensions             0.2.17
    - - Stats                         0.2.6

    This is functionally equivalent to calling Pkg.add("SHA"), except that Pkg.add() doesn't change REQUIRE until after installation has completed, so if there are problems, REQUIRE will be left as it was before calling Pkg.add(). The format of the REQUIRE file is described in Requirements Specification; it allows, among other things, requiring specific ranges of versions of packages.

    When you decide that you don't want to have a package around any more, you can use Pkg.rm() to remove the requirement for it from the REQUIRE file:

    julia> Pkg.rm("Distributions")
    -INFO: Removing Distributions v0.2.7
    -INFO: Removing Stats v0.2.6
    -INFO: Removing NumericExtensions v0.2.17
    -INFO: REQUIRE updated.
    -
    -julia> Pkg.status()
    -Required packages:
    - - SHA                           0.3.2
    -
    -julia> Pkg.rm("SHA")
    -INFO: Removing SHA v0.3.2
    -INFO: REQUIRE updated.
    -
    -julia> Pkg.status()
    -No packages installed.

    Once again, this is equivalent to editing the REQUIRE file to remove the line with each package name on it then running Pkg.resolve() to update the set of installed packages to match. While Pkg.add() and Pkg.rm() are convenient for adding and removing requirements for a single package, when you want to add or remove multiple packages, you can call Pkg.edit() to manually change the contents of REQUIRE and then update your packages accordingly. Pkg.edit() does not roll back the contents of REQUIRE if Pkg.resolve() fails – rather, you have to run Pkg.edit() again to fix the files contents yourself.

    Because the package manager uses libgit2 internally to manage the package git repositories, users may run into protocol issues (if behind a firewall, for example), when running Pkg.add(). By default, all GitHub-hosted packages wil be accessed via 'https'; this default can be modified by calling Pkg.setprotocol!(). The following command can be run from the command line in order to tell git to use 'https' instead of the 'git' protocol when cloning all repositories, wherever they are hosted:

    git config --global url."https://".insteadOf git://

    However, this change will be system-wide and thus the use of Pkg.setprotocol!() is preferable.

    Note

    The package manager functions also accept the .jl suffix on package names, though the suffix is stripped internally. For example:

    Pkg.add("Distributions.jl")
    -Pkg.rm("Distributions.jl")

    Offline Installation of Packages

    For machines with no Internet connection, packages may be installed by copying the package root directory (given by Pkg.dir()) from a machine with the same operating system and environment.

    Pkg.add() does the following within the package root directory:

    1. Adds the name of the package to REQUIRE.

    2. Downloads the package to .cache, then copies the package to the package root directory.

    3. Recursively performs step 2 against all the packages listed in the package's REQUIRE file.

    4. Runs Pkg.build()

    Warning

    Copying installed packages from a different machine is brittle for packages requiring binary external dependencies. Such packages may break due to differences in operating system versions, build environments, and/or absolute path dependencies.

    Installing Unregistered Packages

    Julia packages are simply git repositories, clonable via any of the protocols that git supports, and containing Julia code that follows certain layout conventions. Official Julia packages are registered in the METADATA.jl repository, available at a well-known location [1]. The Pkg.add() and Pkg.rm() commands in the previous section interact with registered packages, but the package manager can install and work with unregistered packages too. To install an unregistered package, use Pkg.clone(url), where url is a git URL from which the package can be cloned:

    julia> Pkg.clone("git://example.com/path/to/Package.jl.git")
    -INFO: Cloning Package from git://example.com/path/to/Package.jl.git
    -Cloning into 'Package'...
    -remote: Counting objects: 22, done.
    -remote: Compressing objects: 100% (10/10), done.
    -remote: Total 22 (delta 8), reused 22 (delta 8)
    -Receiving objects: 100% (22/22), 2.64 KiB, done.
    -Resolving deltas: 100% (8/8), done.

    By convention, Julia repository names end with .jl (the additional .git indicates a "bare" git repository), which keeps them from colliding with repositories for other languages, and also makes Julia packages easy to find in search engines. When packages are installed in your .julia/v0.6 directory, however, the extension is redundant so we leave it off.

    If unregistered packages contain a REQUIRE file at the top of their source tree, that file will be used to determine which registered packages the unregistered package depends on, and they will automatically be installed. Unregistered packages participate in the same version resolution logic as registered packages, so installed package versions will be adjusted as necessary to satisfy the requirements of both registered and unregistered packages.

    [1]

    The official set of packages is at https://github.com/JuliaLang/METADATA.jl, but individuals and organizations can easily use a different metadata repository. This allows control which packages are available for automatic installation. One can allow only audited and approved package versions, and make private packages or forks available. See Custom METADATA Repository for details.

    Updating Packages

    When package developers publish new registered versions of packages that you're using, you will, of course, want the new shiny versions. To get the latest and greatest versions of all your packages, just do Pkg.update():

    julia> Pkg.update()
    -INFO: Updating METADATA...
    -INFO: Computing changes...
    -INFO: Upgrading Distributions: v0.2.8 => v0.2.10
    -INFO: Upgrading Stats: v0.2.7 => v0.2.8

    The first step of updating packages is to pull new changes to ~/.julia/v0.6/METADATA and see if any new registered package versions have been published. After this, Pkg.update() attempts to update packages that are checked out on a branch and not dirty (i.e. no changes have been made to files tracked by git) by pulling changes from the package's upstream repository. Upstream changes will only be applied if no merging or rebasing is necessary – i.e. if the branch can be "fast-forwarded". If the branch cannot be fast-forwarded, it is assumed that you're working on it and will update the repository yourself.

    Finally, the update process recomputes an optimal set of package versions to have installed to satisfy your top-level requirements and the requirements of "fixed" packages. A package is considered fixed if it is one of the following:

    1. Unregistered: the package is not in METADATA – you installed it with Pkg.clone().

    2. Checked out: the package repo is on a development branch.

    3. Dirty: changes have been made to files in the repo.

    If any of these are the case, the package manager cannot freely change the installed version of the package, so its requirements must be satisfied by whatever other package versions it picks. The combination of top-level requirements in ~/.julia/v0.6/REQUIRE and the requirement of fixed packages are used to determine what should be installed.

    You can also update only a subset of the installed packages, by providing arguments to the Pkg.update function. In that case, only the packages provided as arguments and their dependencies will be updated:

    julia> Pkg.update("Example")
    -INFO: Updating METADATA...
    -INFO: Computing changes...
    -INFO: Upgrading Example: v0.4.0 => 0.4.1

    This partial update process still computes the new set of package versions according to top-level requirements and "fixed" packages, but it additionally considers all other packages except those explicitly provided, and their dependencies, as fixed.

    Checkout, Pin and Free

    You may want to use the master version of a package rather than one of its registered versions. There might be fixes or functionality on master that you need that aren't yet published in any registered versions, or you may be a developer of the package and need to make changes on master or some other development branch. In such cases, you can do Pkg.checkout(pkg) to checkout the master branch of pkg or Pkg.checkout(pkg,branch) to checkout some other branch:

    julia> Pkg.add("Distributions")
    -INFO: Installing Distributions v0.2.9
    -INFO: Installing NumericExtensions v0.2.17
    -INFO: Installing Stats v0.2.7
    -INFO: REQUIRE updated.
    -
    -julia> Pkg.status()
    -Required packages:
    - - Distributions                 0.2.9
    -Additional packages:
    - - NumericExtensions             0.2.17
    - - Stats                         0.2.7
    -
    -julia> Pkg.checkout("Distributions")
    -INFO: Checking out Distributions master...
    -INFO: No packages to install, update or remove.
    -
    -julia> Pkg.status()
    -Required packages:
    - - Distributions                 0.2.9+             master
    -Additional packages:
    - - NumericExtensions             0.2.17
    - - Stats                         0.2.7

    Immediately after installing Distributions with Pkg.add() it is on the current most recent registered version – 0.2.9 at the time of writing this. Then after running Pkg.checkout("Distributions"), you can see from the output of Pkg.status() that Distributions is on an unregistered version greater than 0.2.9, indicated by the "pseudo-version" number 0.2.9+.

    When you checkout an unregistered version of a package, the copy of the REQUIRE file in the package repo takes precedence over any requirements registered in METADATA, so it is important that developers keep this file accurate and up-to-date, reflecting the actual requirements of the current version of the package. If the REQUIRE file in the package repo is incorrect or missing, dependencies may be removed when the package is checked out. This file is also used to populate newly published versions of the package if you use the API that Pkg provides for this (described below).

    When you decide that you no longer want to have a package checked out on a branch, you can "free" it back to the control of the package manager with Pkg.free(pkg):

    julia> Pkg.free("Distributions")
    -INFO: Freeing Distributions...
    -INFO: No packages to install, update or remove.
    -
    -julia> Pkg.status()
    -Required packages:
    - - Distributions                 0.2.9
    -Additional packages:
    - - NumericExtensions             0.2.17
    - - Stats                         0.2.7

    After this, since the package is on a registered version and not on a branch, its version will be updated as new registered versions of the package are published.

    If you want to pin a package at a specific version so that calling Pkg.update() won't change the version the package is on, you can use the Pkg.pin() function:

    julia> Pkg.pin("Stats")
    -INFO: Creating Stats branch pinned.47c198b1.tmp
    -
    -julia> Pkg.status()
    -Required packages:
    - - Distributions                 0.2.9
    -Additional packages:
    - - NumericExtensions             0.2.17
    - - Stats                         0.2.7              pinned.47c198b1.tmp

    After this, the Stats package will remain pinned at version 0.2.7 – or more specifically, at commit 47c198b1, but since versions are permanently associated a given git hash, this is the same thing. Pkg.pin() works by creating a throw-away branch for the commit you want to pin the package at and then checking that branch out. By default, it pins a package at the current commit, but you can choose a different version by passing a second argument:

    julia> Pkg.pin("Stats",v"0.2.5")
    -INFO: Creating Stats branch pinned.1fd0983b.tmp
    -INFO: No packages to install, update or remove.
    -
    -julia> Pkg.status()
    -Required packages:
    - - Distributions                 0.2.9
    -Additional packages:
    - - NumericExtensions             0.2.17
    - - Stats                         0.2.5              pinned.1fd0983b.tmp

    Now the Stats package is pinned at commit 1fd0983b, which corresponds to version 0.2.5. When you decide to "unpin" a package and let the package manager update it again, you can use Pkg.free() like you would to move off of any branch:

    julia> Pkg.free("Stats")
    -INFO: Freeing Stats...
    -INFO: No packages to install, update or remove.
    -
    -julia> Pkg.status()
    -Required packages:
    - - Distributions                 0.2.9
    -Additional packages:
    - - NumericExtensions             0.2.17
    - - Stats                         0.2.7

    After this, the Stats package is managed by the package manager again, and future calls to Pkg.update() will upgrade it to newer versions when they are published. The throw-away pinned.1fd0983b.tmp branch remains in your local Stats repo, but since git branches are extremely lightweight, this doesn't really matter; if you feel like cleaning them up, you can go into the repo and delete those branches [2].

    [2]

    Packages that aren't on branches will also be marked as dirty if you make changes in the repo, but that's a less common thing to do.

    Custom METADATA Repository

    By default, Julia assumes you will be using the official METADATA.jl repository for downloading and installing packages. You can also provide a different metadata repository location. A common approach is to keep your metadata-v2 branch up to date with the Julia official branch and add another branch with your custom packages. You can initialize your local metadata repository using that custom location and branch and then periodically rebase your custom branch with the official metadata-v2 branch. In order to use a custom repository and branch, issue the following command:

    julia> Pkg.init("https://me.example.com/METADATA.jl.git", "branch")

    The branch argument is optional and defaults to metadata-v2. Once initialized, a file named META_BRANCH in your ~/.julia/vX.Y/ path will track the branch that your METADATA repository was initialized with. If you want to change branches, you will need to either modify the META_BRANCH file directly (be careful!) or remove the vX.Y directory and re-initialize your METADATA repository using the Pkg.init command.

    Package Development

    Julia's package manager is designed so that when you have a package installed, you are already in a position to look at its source code and full development history. You are also able to make changes to packages, commit them using git, and easily contribute fixes and enhancements upstream. Similarly, the system is designed so that if you want to create a new package, the simplest way to do so is within the infrastructure provided by the package manager.

    Initial Setup

    Since packages are git repositories, before doing any package development you should setup the following standard global git configuration settings:

    $ git config --global user.name "FULL NAME"
    -$ git config --global user.email "EMAIL"

    where FULL NAME is your actual full name (spaces are allowed between the double quotes) and EMAIL is your actual email address. Although it isn't necessary to use GitHub to create or publish Julia packages, most Julia packages as of writing this are hosted on GitHub and the package manager knows how to format origin URLs correctly and otherwise work with the service smoothly. We recommend that you create a free account on GitHub and then do:

    $ git config --global github.user "USERNAME"

    where USERNAME is your actual GitHub user name. Once you do this, the package manager knows your GitHub user name and can configure things accordingly. You should also upload your public SSH key to GitHub and set up an SSH agent on your development machine so that you can push changes with minimal hassle. In the future, we will make this system extensible and support other common git hosting options like BitBucket and allow developers to choose their favorite. Since the package development functions has been moved to the PkgDev package, you need to run Pkg.add("PkgDev"); import PkgDev to access the functions starting with PkgDev. in the document below.

    Making changes to an existing package

    Documentation changes

    If you want to improve the online documentation of a package, the easiest approach (at least for small changes) is to use GitHub's online editing functionality. First, navigate to the repository's GitHub "home page," find the file (e.g., README.md) within the repository's folder structure, and click on it. You'll see the contents displayed, along with a small "pencil" icon in the upper right hand corner. Clicking that icon opens the file in edit mode. Make your changes, write a brief summary describing the changes you want to make (this is your commit message), and then hit "Propose file change." Your changes will be submitted for consideration by the package owner(s) and collaborators.

    For larger documentation changes–and especially ones that you expect to have to update in response to feedback–you might find it easier to use the procedure for code changes described below.

    Code changes

    Executive summary

    Here we assume you've already set up git on your local machine and have a GitHub account (see above). Let's imagine you're fixing a bug in the Images package:

    Pkg.checkout("Images")           # check out the master branch
    -<here, make sure your bug is still a bug and hasn't been fixed already>
    -cd(Pkg.dir("Images"))
    -;git checkout -b myfixes         # create a branch for your changes
    -<edit code>                      # be sure to add a test for your bug
    -Pkg.test("Images")               # make sure everything works now
    -;git commit -a -m "Fix foo by calling bar"   # write a descriptive message
    -using PkgDev
    -PkgDev.submit("Images")

    The last line will present you with a link to submit a pull request to incorporate your changes.

    Detailed description

    If you want to fix a bug or add new functionality, you want to be able to test your changes before you submit them for consideration. You also need to have an easy way to update your proposal in response to the package owner's feedback. Consequently, in this case the strategy is to work locally on your own machine; once you are satisfied with your changes, you submit them for consideration. This process is called a pull request because you are asking to "pull" your changes into the project's main repository. Because the online repository can't see the code on your private machine, you first push your changes to a publicly-visible location, your own online fork of the package (hosted on your own personal GitHub account).

    Let's assume you already have the Foo package installed. In the description below, anything starting with Pkg. or PkgDev. is meant to be typed at the Julia prompt; anything starting with git is meant to be typed in julia's shell mode (or using the shell that comes with your operating system). Within Julia, you can combine these two modes:

    julia> cd(Pkg.dir("Foo"))          # go to Foo's folder
    -
    -shell> git command arguments...    # command will apply to Foo

    Now suppose you're ready to make some changes to Foo. While there are several possible approaches, here is one that is widely used:

    • From the Julia prompt, type Pkg.checkout("Foo"). This ensures you're running the latest code (the master branch), rather than just whatever "official release" version you have installed. (If you're planning to fix a bug, at this point it's a good idea to check again whether the bug has already been fixed by someone else. If it has, you can request that a new official release be tagged so that the fix gets distributed to the rest of the community.) If you receive an error Foo is dirty, bailing, see Dirty packages below.

    • Create a branch for your changes: navigate to the package folder (the one that Julia reports from Pkg.dir("Foo")) and (in shell mode) create a new branch using git checkout -b <newbranch>, where <newbranch> might be some descriptive name (e.g., fixbar). By creating a branch, you ensure that you can easily go back and forth between your new work and the current master branch (see https://git-scm.com/book/en/v2/Git-Branching-Branches-in-a-Nutshell).

      If you forget to do this step until after you've already made some changes, don't worry: see more detail about branching below.

    • Make your changes. Whether it's fixing a bug or adding new functionality, in most cases your change should include updates to both the src/ and test/ folders. If you're fixing a bug, add your minimal example demonstrating the bug (on the current code) to the test suite; by contributing a test for the bug, you ensure that the bug won't accidentally reappear at some later time due to other changes. If you're adding new functionality, creating tests demonstrates to the package owner that you've made sure your code works as intended.

    • Run the package's tests and make sure they pass. There are several ways to run the tests:

      • From Julia, run Pkg.test("Foo"): this will run your tests in a separate (new) julia process.

      • From Julia, include("runtests.jl") from the package's test/ folder (it's possible the file has a different name, look for one that runs all the tests): this allows you to run the tests repeatedly in the same session without reloading all the package code; for packages that take a while to load, this can be much faster. With this approach, you do have to do some extra work to make changes in the package code.

      • From the shell, run julia ../test/runtests.jl from within the package's src/ folder.

    • Commit your changes: see https://git-scm.com/book/en/v2/Git-Basics-Recording-Changes-to-the-Repository.

    • Submit your changes: From the Julia prompt, type PkgDev.submit("Foo"). This will push your changes to your GitHub fork, creating it if it doesn't already exist. (If you encounter an error, make sure you've set up your SSH keys.) Julia will then give you a hyperlink; open that link, edit the message, and then click "submit." At that point, the package owner will be notified of your changes and may initiate discussion. (If you are comfortable with git, you can also do these steps manually from the shell.)

    • The package owner may suggest additional improvements. To respond to those suggestions, you can easily update the pull request (this only works for changes that have not already been merged; for merged pull requests, make new changes by starting a new branch):

      • If you've changed branches in the meantime, make sure you go back to the same branch with git checkout fixbar (from shell mode) or Pkg.checkout("Foo", "fixbar") (from the Julia prompt).

      • As above, make your changes, run the tests, and commit your changes.

      • From the shell, type git push. This will add your new commit(s) to the same pull request; you should see them appear automatically on the page holding the discussion of your pull request.

      One potential type of change the owner may request is that you squash your commits. See Squashing below.

    Dirty packages

    If you can't change branches because the package manager complains that your package is dirty, it means you have some changes that have not been committed. From the shell, use git diff to see what these changes are; you can either discard them (git checkout changedfile.jl) or commit them before switching branches. If you can't easily resolve the problems manually, as a last resort you can delete the entire "Foo" folder and reinstall a fresh copy with Pkg.add("Foo"). Naturally, this deletes any changes you've made.

    Making a branch post hoc

    Especially for newcomers to git, one often forgets to create a new branch until after some changes have already been made. If you haven't yet staged or committed your changes, you can create a new branch with git checkout -b <newbranch> just as usual–git will kindly show you that some files have been modified and create the new branch for you. Your changes have not yet been committed to this new branch, so the normal work rules still apply.

    However, if you've already made a commit to master but wish to go back to the official master (called origin/master), use the following procedure:

    • Create a new branch. This branch will hold your changes.

    • Make sure everything is committed to this branch.

    • git checkout master. If this fails, do not proceed further until you have resolved the problems, or you may lose your changes.

    • Resetmaster (your current branch) back to an earlier state with git reset --hard origin/master (see https://git-scm.com/blog/2011/07/11/reset.html).

    This requires a bit more familiarity with git, so it's much better to get in the habit of creating a branch at the outset.

    Squashing and rebasing

    Depending on the tastes of the package owner (s)he may ask you to "squash" your commits. This is especially likely if your change is quite simple but your commit history looks like this:

    WIP: add new 1-line whizbang function (currently breaks package)
    -Finish whizbang function
    -Fix typo in variable name
    -Oops, don't forget to supply default argument
    -Split into two 1-line functions
    -Rats, forgot to export the second function
    -...

    This gets into the territory of more advanced git usage, and you're encouraged to do some reading (https://git-scm.com/book/en/v2/Git-Branching-Rebasing). However, a brief summary of the procedure is as follows:

    • To protect yourself from error, start from your fixbar branch and create a new branch with git checkout -b fixbar_backup. Since you started from fixbar, this will be a copy. Now go back to the one you intend to modify with git checkout fixbar.

    • From the shell, type git rebase -i origin/master.

    • To combine commits, change pick to squash (for additional options, consult other sources). Save the file and close the editor window.

    • Edit the combined commit message.

    If the rebase goes badly, you can go back to the beginning to try again like this:

    git checkout fixbar
    -git reset --hard fixbar_backup

    Now let's assume you've rebased successfully. Since your fixbar repository has now diverged from the one in your GitHub fork, you're going to have to do a force push:

    • To make it easy to refer to your GitHub fork, create a "handle" for it with git remote add myfork https://github.com/myaccount/Foo.jl.git, where the URL comes from the "clone URL" on your GitHub fork's page.

    • Force-push to your fork with git push myfork +fixbar. The + indicates that this should replace the fixbar branch found at myfork.

    Creating a new Package

    REQUIRE speaks for itself

    You should have a REQUIRE file in your package repository, with a bare minimum directive of what Julia version you expect your users to be running for the package to work. Putting a floor on what Julia version your package supports is done by simply adding julia 0.x in this file. While this line is partly informational, it also has the consequence of whether Pkg.update() will update code found in .julia version directories. It will not update code found in version directories beneath the floor of what's specified in your REQUIRE.

    As the development version 0.y matures, you may find yourself using it more frequently, and wanting your package to support it. Be warned, the development branch of Julia is the land of breakage, and you can expect things to break. When you go about fixing whatever broke your package in the development 0.y branch, you will likely find that you just broke your package on the stable version.

    There is a mechanism found in the Compat package that will enable you to support both the stable version and breaking changes found in the development version. Should you decide to use this solution, you will need to add Compat to your REQUIRE file. In this case, you will still have julia 0.x in your REQUIRE. The x is the floor version of what your package supports.

    You might also have no interest in supporting the development version of Julia. Just as you can add a floor to the version you expect your users to be on, you can set an upper bound. In this case, you would put julia 0.x 0.y- in your REQUIRE file. The - at the end of the version number means pre-release versions of that specific version from the very first commit. By setting it as the ceiling, you mean the code supports everything up to but not including the ceiling version.

    Another scenario is that you are writing the bulk of the code for your package with Julia 0.y and do not want to support the current stable version of Julia. If you choose to do this, simply add julia 0.y- to your REQUIRE. Just remember to change the julia 0.y- to julia 0.y in your REQUIRE file once 0.y is officially released. If you don't edit the dash cruft you are suggesting that you support both the development and stable versions of the same version number! That would be madness. See the Requirements Specification for the full format of REQUIRE.

    Lastly, in many cases you may need extra packages for testing. Additional packages which are only required for tests should be specified in the test/REQUIRE file. This REQUIRE file has the same specification as the standard REQUIRE file.

    Guidelines for naming a package

    Package names should be sensible to most Julia users, even to those who are not domain experts. When you submit your package to METADATA, you can expect a little back and forth about the package name with collaborators, especially if it's ambiguous or can be confused with something other than what it is. During this bike-shedding, it's not uncommon to get a range of different name suggestions. These are only suggestions though, with the intent being to keep a tidy namespace in the curated METADATA repository. Since this repository belongs to the entire community, there will likely be a few collaborators who care about your package name. Here are some guidelines to follow in naming your package:

    1. Avoid jargon. In particular, avoid acronyms unless there is minimal possibility of confusion.

      • It's ok to say USA if you're talking about the USA.

      • It's not ok to say PMA, even if you're talking about positive mental attitude.

    2. Avoid using Julia in your package name.

      • It is usually clear from context and to your users that the package is a Julia package.

      • Having Julia in the name can imply that the package is connected to, or endorsed by, contributors to the Julia language itself.

    3. Packages that provide most of their functionality in association with a new type should have pluralized names.

      • DataFrames provides the DataFrame type.

      • BloomFilters provides the BloomFilter type.

      • In contrast, JuliaParser provides no new type, but instead new functionality in the JuliaParser.parse() function.

    4. Err on the side of clarity, even if clarity seems long-winded to you.

      • RandomMatrices is a less ambiguous name than RndMat or RMT, even though the latter are shorter.

    5. A less systematic name may suit a package that implements one of several possible approaches to its domain.

      • Julia does not have a single comprehensive plotting package. Instead, Gadfly, PyPlot, Winston and other packages each implement a unique approach based on a particular design philosophy.

      • In contrast, SortingAlgorithms provides a consistent interface to use many well-established sorting algorithms.

    6. Packages that wrap external libraries or programs should be named after those libraries or programs.

      • CPLEX.jl wraps the CPLEX library, which can be identified easily in a web search.

      • MATLAB.jl provides an interface to call the MATLAB engine from within Julia.

    Generating the package

    Suppose you want to create a new Julia package called FooBar. To get started, do PkgDev.generate(pkg,license) where pkg is the new package name and license is the name of a license that the package generator knows about:

    julia> PkgDev.generate("FooBar","MIT")
    -INFO: Initializing FooBar repo: /Users/stefan/.julia/v0.6/FooBar
    -INFO: Origin: git://github.com/StefanKarpinski/FooBar.jl.git
    -INFO: Generating LICENSE.md
    -INFO: Generating README.md
    -INFO: Generating src/FooBar.jl
    -INFO: Generating test/runtests.jl
    -INFO: Generating REQUIRE
    -INFO: Generating .travis.yml
    -INFO: Generating appveyor.yml
    -INFO: Generating .gitignore
    -INFO: Committing FooBar generated files

    This creates the directory ~/.julia/v0.6/FooBar, initializes it as a git repository, generates a bunch of files that all packages should have, and commits them to the repository:

    $ cd ~/.julia/v0.6/FooBar && git show --stat
    -
    -commit 84b8e266dae6de30ab9703150b3bf771ec7b6285
    -Author: Stefan Karpinski <stefan@karpinski.org>
    -Date:   Wed Oct 16 17:57:58 2013 -0400
    -
    -    FooBar.jl generated files.
    -
    -        license: MIT
    -        authors: Stefan Karpinski
    -        years:   2013
    -        user:    StefanKarpinski
    -
    -    Julia Version 0.3.0-prerelease+3217 [5fcfb13*]
    -
    - .gitignore       |  2 ++
    - .travis.yml      | 13 +++++++++++++
    - LICENSE.md       | 22 +++++++++++++++++++++++
    - README.md        |  3 +++
    - REQUIRE          |  1 +
    - appveyor.yml     | 34 ++++++++++++++++++++++++++++++++++
    - src/FooBar.jl    |  5 +++++
    - test/runtests.jl |  5 +++++
    - 8 files changed, 85 insertions(+)

    At the moment, the package manager knows about the MIT "Expat" License, indicated by "MIT", the Simplified BSD License, indicated by "BSD", and version 2.0 of the Apache Software License, indicated by "ASL". If you want to use a different license, you can ask us to add it to the package generator, or just pick one of these three and then modify the ~/.julia/v0.6/PACKAGE/LICENSE.md file after it has been generated.

    If you created a GitHub account and configured git to know about it, PkgDev.generate() will set an appropriate origin URL for you. It will also automatically generate a .travis.yml file for using the Travis automated testing service, and an appveyor.yml file for using AppVeyor. You will have to enable testing on the Travis and AppVeyor websites for your package repository, but once you've done that, it will already have working tests. Of course, all the default testing does is verify that using FooBar in Julia works.

    Loading Static Non-Julia Files

    If your package code needs to load static files which are not Julia code, e.g. an external library or data files, and are located within the package directory, use the @__DIR__ macro to determine the directory of the current source file. For example if FooBar/src/FooBar.jl needs to load FooBar/data/foo.csv, use the following code:

    datapath = joinpath(@__DIR__, "..", "data")
    -foo = readcsv(joinpath(datapath, "foo.csv"))

    Making Your Package Available

    Once you've made some commits and you're happy with how FooBar is working, you may want to get some other people to try it out. First you'll need to create the remote repository and push your code to it; we don't yet automatically do this for you, but we will in the future and it's not too hard to figure out [3]. Once you've done this, letting people try out your code is as simple as sending them the URL of the published repo – in this case:

    git://github.com/StefanKarpinski/FooBar.jl.git

    For your package, it will be your GitHub user name and the name of your package, but you get the idea. People you send this URL to can use Pkg.clone() to install the package and try it out:

    julia> Pkg.clone("git://github.com/StefanKarpinski/FooBar.jl.git")
    -INFO: Cloning FooBar from git@github.com:StefanKarpinski/FooBar.jl.git
    [3]

    Installing and using GitHub's "hub" tool is highly recommended. It allows you to do things like run hub create in the package repo and have it automatically created via GitHub's API.

    Tagging and Publishing Your Package

    Tip

    If you are hosting your package on GitHub, you can use the attobot integration to handle package registration, tagging and publishing.

    Once you've decided that FooBar is ready to be registered as an official package, you can add it to your local copy of METADATA using PkgDev.register():

    julia> PkgDev.register("FooBar")
    -INFO: Registering FooBar at git://github.com/StefanKarpinski/FooBar.jl.git
    -INFO: Committing METADATA for FooBar

    This creates a commit in the ~/.julia/v0.6/METADATA repo:

    $ cd ~/.julia/v0.6/METADATA && git show
    -
    -commit 9f71f4becb05cadacb983c54a72eed744e5c019d
    -Author: Stefan Karpinski <stefan@karpinski.org>
    -Date:   Wed Oct 16 18:46:02 2013 -0400
    -
    -    Register FooBar
    -
    -diff --git a/FooBar/url b/FooBar/url
    -new file mode 100644
    -index 0000000..30e525e
    ---- /dev/null
    -+++ b/FooBar/url
    -@@ -0,0 +1 @@
    -+git://github.com/StefanKarpinski/FooBar.jl.git

    This commit is only locally visible, however. To make it visible to the Julia community, you need to merge your local METADATA upstream into the official repo. The PkgDev.publish() command will fork the METADATA repository on GitHub, push your changes to your fork, and open a pull request:

    julia> PkgDev.publish()
    -INFO: Validating METADATA
    -INFO: No new package versions to publish
    -INFO: Submitting METADATA changes
    -INFO: Forking JuliaLang/METADATA.jl to StefanKarpinski
    -INFO: Pushing changes as branch pull-request/ef45f54b
    -INFO: To create a pull-request open:
    -
    -  https://github.com/StefanKarpinski/METADATA.jl/compare/pull-request/ef45f54b
    Tip

    If PkgDev.publish() fails with error:

    ERROR: key not found: "token"

    then you may have encountered an issue from using the GitHub API on multiple systems. The solution is to delete the "Julia Package Manager" personal access token from your Github account and try again.

    Other failures may require you to circumvent PkgDev.publish() by creating a pull request on GitHub. See: Publishing METADATA manually below.

    Once the package URL for FooBar is registered in the official METADATA repo, people know where to clone the package from, but there still aren't any registered versions available. You can tag and register it with the PkgDev.tag() command:

    julia> PkgDev.tag("FooBar")
    -INFO: Tagging FooBar v0.0.1
    -INFO: Committing METADATA for FooBar

    This tags v0.0.1 in the FooBar repo:

    $ cd ~/.julia/v0.6/FooBar && git tag
    -v0.0.1

    It also creates a new version entry in your local METADATA repo for FooBar:

    $ cd ~/.julia/v0.6/FooBar && git show
    -commit de77ee4dc0689b12c5e8b574aef7f70e8b311b0e
    -Author: Stefan Karpinski <stefan@karpinski.org>
    -Date:   Wed Oct 16 23:06:18 2013 -0400
    -
    -    Tag FooBar v0.0.1
    -
    -diff --git a/FooBar/versions/0.0.1/sha1 b/FooBar/versions/0.0.1/sha1
    -new file mode 100644
    -index 0000000..c1cb1c1
    ---- /dev/null
    -+++ b/FooBar/versions/0.0.1/sha1
    -@@ -0,0 +1 @@
    -+84b8e266dae6de30ab9703150b3bf771ec7b6285

    The PkgDev.tag() command takes an optional second argument that is either an explicit version number object like v"0.0.1" or one of the symbols :patch, :minor or :major. These increment the patch, minor or major version number of your package intelligently.

    Adding a tagged version of your package will expedite the official registration into METADATA.jl by collaborators. It is strongly recommended that you complete this process, regardless if your package is completely ready for an official release.

    As a general rule, packages should be tagged 0.0.1 first. Since Julia itself hasn't achieved 1.0 status, it's best to be conservative in your package's tagged versions.

    As with PkgDev.register(), these changes to METADATA aren't available to anyone else until they've been included upstream. Again, use the PkgDev.publish() command, which first makes sure that individual package repos have been tagged, pushes them if they haven't already been, and then opens a pull request to METADATA:

    julia> PkgDev.publish()
    -INFO: Validating METADATA
    -INFO: Pushing FooBar permanent tags: v0.0.1
    -INFO: Submitting METADATA changes
    -INFO: Forking JuliaLang/METADATA.jl to StefanKarpinski
    -INFO: Pushing changes as branch pull-request/3ef4f5c4
    -INFO: To create a pull-request open:
    -
    -  https://github.com/StefanKarpinski/METADATA.jl/compare/pull-request/3ef4f5c4

    Publishing METADATA manually

    If PkgDev.publish() fails you can follow these instructions to manually publish your package.

    By "forking" the main METADATA repository, you can create a personal copy (of METADATA.jl) under your GitHub account. Once that copy exists, you can push your local changes to your copy (just like any other GitHub project).

    1. Create a fork of METADATA.jl.

    2. Add your fork as a remote repository for the METADATA repository on your local computer (in the terminal where USERNAME is your github username):

      cd ~/.julia/v0.6/METADATA
      -git remote add USERNAME https://github.com/USERNAME/METADATA.jl.git
    3. Push your changes to your fork:

      git push USERNAME metadata-v2
    4. If all of that works, then go back to the GitHub page for your fork, and click the "pull request" link.

    Fixing Package Requirements

    If you need to fix the registered requirements of an already-published package version, you can do so just by editing the metadata for that version, which will still have the same commit hash – the hash associated with a version is permanent:

    $ cd ~/.julia/v0.6/METADATA/FooBar/versions/0.0.1 && cat requires
    -julia 0.3-
    -$ vi requires

    Since the commit hash stays the same, the contents of the REQUIRE file that will be checked out in the repo will not match the requirements in METADATA after such a change; this is unavoidable. When you fix the requirements in METADATA for a previous version of a package, however, you should also fix the REQUIRE file in the current version of the package.

    Requirements Specification

    The ~/.julia/v0.6/REQUIRE file, the REQUIRE file inside packages, and the METADATA package requires files use a simple line-based format to express the ranges of package versions which need to be installed. Package REQUIRE and METADATA requires files should also include the range of versions of julia the package is expected to work with. Additionally, packages can include a test/REQUIRE file to specify additional packages which are only required for testing.

    Here's how these files are parsed and interpreted.

    • Everything after a # mark is stripped from each line as a comment.

    • If nothing but whitespace is left, the line is ignored.

    • If there are non-whitespace characters remaining, the line is a requirement and the is split on whitespace into words.

    The simplest possible requirement is just the name of a package name on a line by itself:

    Distributions

    This requirement is satisfied by any version of the Distributions package. The package name can be followed by zero or more version numbers in ascending order, indicating acceptable intervals of versions of that package. One version opens an interval, while the next closes it, and the next opens a new interval, and so on; if an odd number of version numbers are given, then arbitrarily large versions will satisfy; if an even number of version numbers are given, the last one is an upper limit on acceptable version numbers. For example, the line:

    Distributions 0.1

    is satisfied by any version of Distributions greater than or equal to 0.1.0. Suffixing a version with - allows any pre-release versions as well. For example:

    Distributions 0.1-

    is satisfied by pre-release versions such as 0.1-dev or 0.1-rc1, or by any version greater than or equal to 0.1.0.

    This requirement entry:

    Distributions 0.1 0.2.5

    is satisfied by versions from 0.1.0 up to, but not including 0.2.5. If you want to indicate that any 0.1.x version will do, you will want to write:

    Distributions 0.1 0.2-

    If you want to start accepting versions after 0.2.7, you can write:

    Distributions 0.1 0.2- 0.2.7

    If a requirement line has leading words that begin with @, it is a system-dependent requirement. If your system matches these system conditionals, the requirement is included, if not, the requirement is ignored. For example:

    @osx Homebrew

    will require the Homebrew package only on systems where the operating system is OS X. The system conditions that are currently supported are (hierarchically):

    • @unix

      • @linux

      • @bsd

        • @osx

    • @windows

    The @unix condition is satisfied on all UNIX systems, including Linux and BSD. Negated system conditionals are also supported by adding a ! after the leading @. Examples:

    @!windows
    -@unix @!osx

    The first condition applies to any system but Windows and the second condition applies to any UNIX system besides OS X.

    Runtime checks for the current version of Julia can be made using the built-in VERSION variable, which is of type VersionNumber. Such code is occasionally necessary to keep track of new or deprecated functionality between various releases of Julia. Examples of runtime checks:

    VERSION < v"0.3-" #exclude all pre-release versions of 0.3
    -
    -v"0.2-" <= VERSION < v"0.3-" #get all 0.2 versions, including pre-releases, up to the above
    -
    -v"0.2" <= VERSION < v"0.3-" #To get only stable 0.2 versions (Note v"0.2" == v"0.2.0")
    -
    -VERSION >= v"0.2.1" #get at least version 0.2.1

    See the section on version number literals for a more complete description.

    diff --git a/julia-0.6.3/share/doc/julia/html/en/manual/parallel-computing.html b/julia-0.6.3/share/doc/julia/html/en/manual/parallel-computing.html deleted file mode 100644 index 2be5f3a..0000000 --- a/julia-0.6.3/share/doc/julia/html/en/manual/parallel-computing.html +++ /dev/null @@ -1,424 +0,0 @@ - -Parallel Computing · The Julia Language

    Parallel Computing

    Parallel Computing

    Most modern computers possess more than one CPU, and several computers can be combined together in a cluster. Harnessing the power of these multiple CPUs allows many computations to be completed more quickly. There are two major factors that influence performance: the speed of the CPUs themselves, and the speed of their access to memory. In a cluster, it's fairly obvious that a given CPU will have fastest access to the RAM within the same computer (node). Perhaps more surprisingly, similar issues are relevant on a typical multicore laptop, due to differences in the speed of main memory and the cache. Consequently, a good multiprocessing environment should allow control over the "ownership" of a chunk of memory by a particular CPU. Julia provides a multiprocessing environment based on message passing to allow programs to run on multiple processes in separate memory domains at once.

    Julia's implementation of message passing is different from other environments such as MPI [1]. Communication in Julia is generally "one-sided", meaning that the programmer needs to explicitly manage only one process in a two-process operation. Furthermore, these operations typically do not look like "message send" and "message receive" but rather resemble higher-level operations like calls to user functions.

    Parallel programming in Julia is built on two primitives: remote references and remote calls. A remote reference is an object that can be used from any process to refer to an object stored on a particular process. A remote call is a request by one process to call a certain function on certain arguments on another (possibly the same) process.

    Remote references come in two flavors: Future and RemoteChannel.

    A remote call returns a Future to its result. Remote calls return immediately; the process that made the call proceeds to its next operation while the remote call happens somewhere else. You can wait for a remote call to finish by calling wait() on the returned Future, and you can obtain the full value of the result using fetch().

    On the other hand, RemoteChannel s are rewritable. For example, multiple processes can co-ordinate their processing by referencing the same remote Channel.

    Each process has an associated identifier. The process providing the interactive Julia prompt always has an id equal to 1. The processes used by default for parallel operations are referred to as "workers". When there is only one process, process 1 is considered a worker. Otherwise, workers are considered to be all processes other than process 1.

    Let's try this out. Starting with julia -p n provides n worker processes on the local machine. Generally it makes sense for n to equal the number of CPU cores on the machine.

    $ ./julia -p 2
    -
    -julia> r = remotecall(rand, 2, 2, 2)
    -Future(2, 1, 4, Nullable{Any}())
    -
    -julia> s = @spawnat 2 1 .+ fetch(r)
    -Future(2, 1, 5, Nullable{Any}())
    -
    -julia> fetch(s)
    -2×2 Array{Float64,2}:
    - 1.18526  1.50912
    - 1.16296  1.60607

    The first argument to remotecall() is the function to call. Most parallel programming in Julia does not reference specific processes or the number of processes available, but remotecall() is considered a low-level interface providing finer control. The second argument to remotecall() is the id of the process that will do the work, and the remaining arguments will be passed to the function being called.

    As you can see, in the first line we asked process 2 to construct a 2-by-2 random matrix, and in the second line we asked it to add 1 to it. The result of both calculations is available in the two futures, r and s. The @spawnat macro evaluates the expression in the second argument on the process specified by the first argument.

    Occasionally you might want a remotely-computed value immediately. This typically happens when you read from a remote object to obtain data needed by the next local operation. The function remotecall_fetch() exists for this purpose. It is equivalent to fetch(remotecall(...)) but is more efficient.

    julia> remotecall_fetch(getindex, 2, r, 1, 1)
    -0.18526337335308085

    Remember that getindex(r,1,1) is equivalent to r[1,1], so this call fetches the first element of the future r.

    The syntax of remotecall() is not especially convenient. The macro @spawn makes things easier. It operates on an expression rather than a function, and picks where to do the operation for you:

    julia> r = @spawn rand(2,2)
    -Future(2, 1, 4, Nullable{Any}())
    -
    -julia> s = @spawn 1 .+ fetch(r)
    -Future(3, 1, 5, Nullable{Any}())
    -
    -julia> fetch(s)
    -2×2 Array{Float64,2}:
    - 1.38854  1.9098
    - 1.20939  1.57158

    Note that we used 1 .+ fetch(r) instead of 1 .+ r. This is because we do not know where the code will run, so in general a fetch() might be required to move r to the process doing the addition. In this case, @spawn is smart enough to perform the computation on the process that owns r, so the fetch() will be a no-op (no work is done).

    (It is worth noting that @spawn is not built-in but defined in Julia as a macro. It is possible to define your own such constructs.)

    An important thing to remember is that, once fetched, a Future will cache its value locally. Further fetch() calls do not entail a network hop. Once all referencing Futures have fetched, the remote stored value is deleted.

    Code Availability and Loading Packages

    Your code must be available on any process that runs it. For example, type the following into the Julia prompt:

    julia> function rand2(dims...)
    -           return 2*rand(dims...)
    -       end
    -
    -julia> rand2(2,2)
    -2×2 Array{Float64,2}:
    - 0.153756  0.368514
    - 1.15119   0.918912
    -
    -julia> fetch(@spawn rand2(2,2))
    -ERROR: RemoteException(2, CapturedException(UndefVarError(Symbol("#rand2"))
    -[...]

    Process 1 knew about the function rand2, but process 2 did not.

    Most commonly you'll be loading code from files or packages, and you have a considerable amount of flexibility in controlling which processes load code. Consider a file, DummyModule.jl, containing the following code:

    module DummyModule
    -
    -export MyType, f
    -
    -mutable struct MyType
    -    a::Int
    -end
    -
    -f(x) = x^2+1
    -
    -println("loaded")
    -
    -end

    Starting Julia with julia -p 2, you can use this to verify the following:

    • include("DummyModule.jl") loads the file on just a single process (whichever one executes the statement).

    • using DummyModule causes the module to be loaded on all processes; however, the module is brought into scope only on the one executing the statement.

    • As long as DummyModule is loaded on process 2, commands like

      rr = RemoteChannel(2)
      -put!(rr, MyType(7))

      allow you to store an object of type MyType on process 2 even if DummyModule is not in scope on process 2.

    You can force a command to run on all processes using the @everywhere macro. For example, @everywhere can also be used to directly define a function on all processes:

    julia> @everywhere id = myid()
    -
    -julia> remotecall_fetch(()->id, 2)
    -2

    A file can also be preloaded on multiple processes at startup, and a driver script can be used to drive the computation:

    julia -p <n> -L file1.jl -L file2.jl driver.jl

    The Julia process running the driver script in the example above has an id equal to 1, just like a process providing an interactive prompt.

    The base Julia installation has in-built support for two types of clusters:

    • A local cluster specified with the -p option as shown above.

    • A cluster spanning machines using the --machinefile option. This uses a passwordless ssh login to start Julia worker processes (from the same path as the current host) on the specified machines.

    Functions addprocs(), rmprocs(), workers(), and others are available as a programmatic means of adding, removing and querying the processes in a cluster.

    Note that workers do not run a .juliarc.jl startup script, nor do they synchronize their global state (such as global variables, new method definitions, and loaded modules) with any of the other running processes.

    Other types of clusters can be supported by writing your own custom ClusterManager, as described below in the ClusterManagers section.

    Data Movement

    Sending messages and moving data constitute most of the overhead in a parallel program. Reducing the number of messages and the amount of data sent is critical to achieving performance and scalability. To this end, it is important to understand the data movement performed by Julia's various parallel programming constructs.

    fetch() can be considered an explicit data movement operation, since it directly asks that an object be moved to the local machine. @spawn (and a few related constructs) also moves data, but this is not as obvious, hence it can be called an implicit data movement operation. Consider these two approaches to constructing and squaring a random matrix:

    Method 1:

    julia> A = rand(1000,1000);
    -
    -julia> Bref = @spawn A^2;
    -
    -[...]
    -
    -julia> fetch(Bref);

    Method 2:

    julia> Bref = @spawn rand(1000,1000)^2;
    -
    -[...]
    -
    -julia> fetch(Bref);

    The difference seems trivial, but in fact is quite significant due to the behavior of @spawn. In the first method, a random matrix is constructed locally, then sent to another process where it is squared. In the second method, a random matrix is both constructed and squared on another process. Therefore the second method sends much less data than the first.

    In this toy example, the two methods are easy to distinguish and choose from. However, in a real program designing data movement might require more thought and likely some measurement. For example, if the first process needs matrix A then the first method might be better. Or, if computing A is expensive and only the current process has it, then moving it to another process might be unavoidable. Or, if the current process has very little to do between the @spawn and fetch(Bref), it might be better to eliminate the parallelism altogether. Or imagine rand(1000,1000) is replaced with a more expensive operation. Then it might make sense to add another @spawn statement just for this step.

    Global variables

    Expressions executed remotely via @spawn, or closures specified for remote execution using remotecall may refer to global variables. Global bindings under module Main are treated a little differently compared to global bindings in other modules. Consider the following code snippet:

    A = rand(10,10)
    -remotecall_fetch(()->foo(A), 2)

    Note that A is a global variable defined in the local workspace. Worker 2 does not have a variable called A under Main. The act of shipping the closure ()->foo(A) to worker 2 results in Main.A being defined on 2. Main.A continues to exist on worker 2 even after the call remotecall_fetch returns. Remote calls with embedded global references (under Main module only) manage globals as follows:

    • New global bindings are created on destination workers if they are referenced as part of a remote call.

    • Global constants are declared as constants on remote nodes too.

    • Globals are re-sent to a destination worker only in the context of a remote call, and then only if its value has changed. Also, the cluster does not synchronize global bindings across nodes. For example:

      A = rand(10,10)
      -remotecall_fetch(()->foo(A), 2) # worker 2
      -A = rand(10,10)
      -remotecall_fetch(()->foo(A), 3) # worker 3
      -A = nothing

      Executing the above snippet results in Main.A on worker 2 having a different value from Main.A on worker 3, while the value of Main.A on node 1 is set to nothing.

    As you may have realized, while memory associated with globals may be collected when they are reassigned on the master, no such action is taken on the workers as the bindings continue to be valid. clear! can be used to manually reassign specific globals on remote nodes to nothing once they are no longer required. This will release any memory associated with them as part of a regular garbage collection cycle.

    Thus programs should be careful referencing globals in remote calls. In fact, it is preferable to avoid them altogether if possible. If you must reference globals, consider using let blocks to localize global variables.

    For example:

    julia> A = rand(10,10);
    -
    -julia> remotecall_fetch(()->A, 2);
    -
    -julia> B = rand(10,10);
    -
    -julia> let B = B
    -           remotecall_fetch(()->B, 2)
    -       end;
    -
    -julia> @spawnat 2 whos();
    -
    -julia>  From worker 2:                               A    800 bytes  10×10 Array{Float64,2}
    -        From worker 2:                            Base               Module
    -        From worker 2:                            Core               Module
    -        From worker 2:                            Main               Module

    As can be seen, global variable A is defined on worker 2, but B is captured as a local variable and hence a binding for B does not exist on worker 2.

    Parallel Map and Loops

    Fortunately, many useful parallel computations do not require data movement. A common example is a Monte Carlo simulation, where multiple processes can handle independent simulation trials simultaneously. We can use @spawn to flip coins on two processes. First, write the following function in count_heads.jl:

    function count_heads(n)
    -    c::Int = 0
    -    for i = 1:n
    -        c += rand(Bool)
    -    end
    -    c
    -end

    The function count_heads simply adds together n random bits. Here is how we can perform some trials on two machines, and add together the results:

    julia> @everywhere include("count_heads.jl")
    -
    -julia> a = @spawn count_heads(100000000)
    -Future(2, 1, 6, Nullable{Any}())
    -
    -julia> b = @spawn count_heads(100000000)
    -Future(3, 1, 7, Nullable{Any}())
    -
    -julia> fetch(a)+fetch(b)
    -100001564

    This example demonstrates a powerful and often-used parallel programming pattern. Many iterations run independently over several processes, and then their results are combined using some function. The combination process is called a reduction, since it is generally tensor-rank-reducing: a vector of numbers is reduced to a single number, or a matrix is reduced to a single row or column, etc. In code, this typically looks like the pattern x = f(x,v[i]), where x is the accumulator, f is the reduction function, and the v[i] are the elements being reduced. It is desirable for f to be associative, so that it does not matter what order the operations are performed in.

    Notice that our use of this pattern with count_heads can be generalized. We used two explicit @spawn statements, which limits the parallelism to two processes. To run on any number of processes, we can use a parallel for loop, which can be written in Julia using @parallel like this:

    nheads = @parallel (+) for i = 1:200000000
    -    Int(rand(Bool))
    -end

    This construct implements the pattern of assigning iterations to multiple processes, and combining them with a specified reduction (in this case (+)). The result of each iteration is taken as the value of the last expression inside the loop. The whole parallel loop expression itself evaluates to the final answer.

    Note that although parallel for loops look like serial for loops, their behavior is dramatically different. In particular, the iterations do not happen in a specified order, and writes to variables or arrays will not be globally visible since iterations run on different processes. Any variables used inside the parallel loop will be copied and broadcast to each process.

    For example, the following code will not work as intended:

    a = zeros(100000)
    -@parallel for i = 1:100000
    -    a[i] = i
    -end

    This code will not initialize all of a, since each process will have a separate copy of it. Parallel for loops like these must be avoided. Fortunately, Shared Arrays can be used to get around this limitation:

    a = SharedArray{Float64}(10)
    -@parallel for i = 1:10
    -    a[i] = i
    -end

    Using "outside" variables in parallel loops is perfectly reasonable if the variables are read-only:

    a = randn(1000)
    -@parallel (+) for i = 1:100000
    -    f(a[rand(1:end)])
    -end

    Here each iteration applies f to a randomly-chosen sample from a vector a shared by all processes.

    As you could see, the reduction operator can be omitted if it is not needed. In that case, the loop executes asynchronously, i.e. it spawns independent tasks on all available workers and returns an array of Future immediately without waiting for completion. The caller can wait for the Future completions at a later point by calling fetch() on them, or wait for completion at the end of the loop by prefixing it with @sync, like @sync @parallel for.

    In some cases no reduction operator is needed, and we merely wish to apply a function to all integers in some range (or, more generally, to all elements in some collection). This is another useful operation called parallel map, implemented in Julia as the pmap() function. For example, we could compute the singular values of several large random matrices in parallel as follows:

    julia> M = Matrix{Float64}[rand(1000,1000) for i = 1:10];
    -
    -julia> pmap(svd, M);

    Julia's pmap() is designed for the case where each function call does a large amount of work. In contrast, @parallel for can handle situations where each iteration is tiny, perhaps merely summing two numbers. Only worker processes are used by both pmap() and @parallel for for the parallel computation. In case of @parallel for, the final reduction is done on the calling process.

    Synchronization With Remote References

    Scheduling

    Julia's parallel programming platform uses Tasks (aka Coroutines) to switch among multiple computations. Whenever code performs a communication operation like fetch() or wait(), the current task is suspended and a scheduler picks another task to run. A task is restarted when the event it is waiting for completes.

    For many problems, it is not necessary to think about tasks directly. However, they can be used to wait for multiple events at the same time, which provides for dynamic scheduling. In dynamic scheduling, a program decides what to compute or where to compute it based on when other jobs finish. This is needed for unpredictable or unbalanced workloads, where we want to assign more work to processes only when they finish their current tasks.

    As an example, consider computing the singular values of matrices of different sizes:

    julia> M = Matrix{Float64}[rand(800,800), rand(600,600), rand(800,800), rand(600,600)];
    -
    -julia> pmap(svd, M);

    If one process handles both 800×800 matrices and another handles both 600×600 matrices, we will not get as much scalability as we could. The solution is to make a local task to "feed" work to each process when it completes its current task. For example, consider a simple pmap() implementation:

    function pmap(f, lst)
    -    np = nprocs()  # determine the number of processes available
    -    n = length(lst)
    -    results = Vector{Any}(n)
    -    i = 1
    -    # function to produce the next work item from the queue.
    -    # in this case it's just an index.
    -    nextidx() = (idx=i; i+=1; idx)
    -    @sync begin
    -        for p=1:np
    -            if p != myid() || np == 1
    -                @async begin
    -                    while true
    -                        idx = nextidx()
    -                        if idx > n
    -                            break
    -                        end
    -                        results[idx] = remotecall_fetch(f, p, lst[idx])
    -                    end
    -                end
    -            end
    -        end
    -    end
    -    results
    -end

    @async is similar to @spawn, but only runs tasks on the local process. We use it to create a "feeder" task for each process. Each task picks the next index that needs to be computed, then waits for its process to finish, then repeats until we run out of indexes. Note that the feeder tasks do not begin to execute until the main task reaches the end of the @sync block, at which point it surrenders control and waits for all the local tasks to complete before returning from the function. The feeder tasks are able to share state via nextidx() because they all run on the same process. No locking is required, since the threads are scheduled cooperatively and not preemptively. This means context switches only occur at well-defined points: in this case, when remotecall_fetch() is called.

    Channels

    The section on Tasks in Control Flow discussed the execution of multiple functions in a co-operative manner. Channels can be quite useful to pass data between running tasks, particularly those involving I/O operations.

    Examples of operations involving I/O include reading/writing to files, accessing web services, executing external programs, etc. In all these cases, overall execution time can be improved if other tasks can be run while a file is being read, or while waiting for an external service/program to complete.

    A channel can be visualized as a pipe, i.e., it has a write end and read end.

    • Multiple writers in different tasks can write to the same channel concurrently via put!() calls.

    • Multiple readers in different tasks can read data concurrently via take!() calls.

    • As an example:

      # Given Channels c1 and c2,
      -c1 = Channel(32)
      -c2 = Channel(32)
      -
      -# and a function `foo()` which reads items from from c1, processes the item read
      -# and writes a result to c2,
      -function foo()
      -    while true
      -        data = take!(c1)
      -        [...]               # process data
      -        put!(c2, result)    # write out result
      -    end
      -end
      -
      -# we can schedule `n` instances of `foo()` to be active concurrently.
      -for _ in 1:n
      -    @schedule foo()
      -end
    • Channels are created via the Channel{T}(sz) constructor. The channel will only hold objects of type T. If the type is not specified, the channel can hold objects of any type. sz refers to the maximum number of elements that can be held in the channel at any time. For example, Channel(32) creates a channel that can hold a maximum of 32 objects of any type. A Channel{MyType}(64) can hold up to 64 objects of MyType at any time.

    • If a Channel is empty, readers (on a take!() call) will block until data is available.

    • If a Channel is full, writers (on a put!() call) will block until space becomes available.

    • isready() tests for the presence of any object in the channel, while wait() waits for an object to become available.

    • A Channel is in an open state initially. This means that it can be read from and written to freely via take!() and put!() calls. close() closes a Channel. On a closed Channel, put!() will fail. For example:

    julia> c = Channel(2);
    -
    -julia> put!(c, 1) # `put!` on an open channel succeeds
    -1
    -
    -julia> close(c);
    -
    -julia> put!(c, 2) # `put!` on a closed channel throws an exception.
    -ERROR: InvalidStateException("Channel is closed.",:closed)
    -[...]
    • take!() and fetch() (which retrieves but does not remove the value) on a closed channel successfully return any existing values until it is emptied. Continuing the above example:

    julia> fetch(c) # Any number of `fetch` calls succeed.
    -1
    -
    -julia> fetch(c)
    -1
    -
    -julia> take!(c) # The first `take!` removes the value.
    -1
    -
    -julia> take!(c) # No more data available on a closed channel.
    -ERROR: InvalidStateException("Channel is closed.",:closed)
    -[...]

    A Channel can be used as an iterable object in a for loop, in which case the loop runs as long as the Channel has data or is open. The loop variable takes on all values added to the Channel. The for loop is terminated once the Channel is closed and emptied.

    For example, the following would cause the for loop to wait for more data:

    julia> c = Channel{Int}(10);
    -
    -julia> foreach(i->put!(c, i), 1:3) # add a few entries
    -
    -julia> data = [i for i in c]

    while this will return after reading all data:

    julia> c = Channel{Int}(10);
    -
    -julia> foreach(i->put!(c, i), 1:3); # add a few entries
    -
    -julia> close(c);                    # `for` loops can exit
    -
    -julia> data = [i for i in c]
    -3-element Array{Int64,1}:
    - 1
    - 2
    - 3

    Consider a simple example using channels for inter-task communication. We start 4 tasks to process data from a single jobs channel. Jobs, identified by an id (job_id), are written to the channel. Each task in this simulation reads a job_id, waits for a random amout of time and writes back a tuple of job_id and the simulated time to the results channel. Finally all the results are printed out.

    julia> const jobs = Channel{Int}(32);
    -
    -julia> const results = Channel{Tuple}(32);
    -
    -julia> function do_work()
    -           for job_id in jobs
    -               exec_time = rand()
    -               sleep(exec_time)                # simulates elapsed time doing actual work
    -                                               # typically performed externally.
    -               put!(results, (job_id, exec_time))
    -           end
    -       end;
    -
    -julia> function make_jobs(n)
    -           for i in 1:n
    -               put!(jobs, i)
    -           end
    -       end;
    -
    -julia> n = 12;
    -
    -julia> @schedule make_jobs(n); # feed the jobs channel with "n" jobs
    -
    -julia> for i in 1:4 # start 4 tasks to process requests in parallel
    -           @schedule do_work()
    -       end
    -
    -julia> @elapsed while n > 0 # print out results
    -           job_id, exec_time = take!(results)
    -           println("$job_id finished in $(round(exec_time,2)) seconds")
    -           n = n - 1
    -       end
    -4 finished in 0.22 seconds
    -3 finished in 0.45 seconds
    -1 finished in 0.5 seconds
    -7 finished in 0.14 seconds
    -2 finished in 0.78 seconds
    -5 finished in 0.9 seconds
    -9 finished in 0.36 seconds
    -6 finished in 0.87 seconds
    -8 finished in 0.79 seconds
    -10 finished in 0.64 seconds
    -12 finished in 0.5 seconds
    -11 finished in 0.97 seconds
    -0.029772311

    The current version of Julia multiplexes all tasks onto a single OS thread. Thus, while tasks involving I/O operations benefit from parallel execution, compute bound tasks are effectively executed sequentially on a single OS thread. Future versions of Julia may support scheduling of tasks on multiple threads, in which case compute bound tasks will see benefits of parallel execution too.

    Remote References and AbstractChannels

    Remote references always refer to an implementation of an AbstractChannel.

    A concrete implementation of an AbstractChannel (like Channel), is required to implement put!(), take!(), fetch(), isready() and wait(). The remote object referred to by a Future is stored in a Channel{Any}(1), i.e., a Channel of size 1 capable of holding objects of Any type.

    RemoteChannel, which is rewritable, can point to any type and size of channels, or any other implementation of an AbstractChannel.

    The constructor RemoteChannel(f::Function, pid)() allows us to construct references to channels holding more than one value of a specific type. f() is a function executed on pid and it must return an AbstractChannel.

    For example, RemoteChannel(()->Channel{Int}(10), pid), will return a reference to a channel of type Int and size 10. The channel exists on worker pid.

    Methods put!(), take!(), fetch(), isready() and wait() on a RemoteChannel are proxied onto the backing store on the remote process.

    RemoteChannel can thus be used to refer to user implemented AbstractChannel objects. A simple example of this is provided in examples/dictchannel.jl which uses a dictionary as its remote store.

    Channels and RemoteChannels

    • A Channel is local to a process. Worker 2 cannot directly refer to a Channel on worker 3 and vice-versa. A RemoteChannel, however, can put and take values across workers.

    • A RemoteChannel can be thought of as a handle to a Channel.

    • The process id, pid, associated with a RemoteChannel identifies the process where the backing store, i.e., the backing Channel exists.

    • Any process with a reference to a RemoteChannel can put and take items from the channel. Data is automatically sent to (or retrieved from) the process a RemoteChannel is associated with.

    • Serializing a Channel also serializes any data present in the channel. Deserializing it therefore effectively makes a copy of the original object.

    • On the other hand, serializing a RemoteChannel only involves the serialization of an identifier that identifies the location and instance of Channel referred to by the handle. A deserialized RemoteChannel object (on any worker), therefore also points to the same backing store as the original.

    The channels example from above can be modified for interprocess communication, as shown below.

    We start 4 workers to process a single jobs remote channel. Jobs, identified by an id (job_id), are written to the channel. Each remotely executing task in this simulation reads a job_id, waits for a random amount of time and writes back a tuple of job_id, time taken and its own pid to the results channel. Finally all the results are printed out on the master process.

    julia> addprocs(4); # add worker processes
    -
    -julia> const jobs = RemoteChannel(()->Channel{Int}(32));
    -
    -julia> const results = RemoteChannel(()->Channel{Tuple}(32));
    -
    -julia> @everywhere function do_work(jobs, results) # define work function everywhere
    -           while true
    -               job_id = take!(jobs)
    -               exec_time = rand()
    -               sleep(exec_time) # simulates elapsed time doing actual work
    -               put!(results, (job_id, exec_time, myid()))
    -           end
    -       end
    -
    -julia> function make_jobs(n)
    -           for i in 1:n
    -               put!(jobs, i)
    -           end
    -       end;
    -
    -julia> n = 12;
    -
    -julia> @schedule make_jobs(n); # feed the jobs channel with "n" jobs
    -
    -julia> for p in workers() # start tasks on the workers to process requests in parallel
    -           @async remote_do(do_work, p, jobs, results)
    -       end
    -
    -julia> @elapsed while n > 0 # print out results
    -           job_id, exec_time, where = take!(results)
    -           println("$job_id finished in $(round(exec_time,2)) seconds on worker $where")
    -           n = n - 1
    -       end
    -1 finished in 0.18 seconds on worker 4
    -2 finished in 0.26 seconds on worker 5
    -6 finished in 0.12 seconds on worker 4
    -7 finished in 0.18 seconds on worker 4
    -5 finished in 0.35 seconds on worker 5
    -4 finished in 0.68 seconds on worker 2
    -3 finished in 0.73 seconds on worker 3
    -11 finished in 0.01 seconds on worker 3
    -12 finished in 0.02 seconds on worker 3
    -9 finished in 0.26 seconds on worker 5
    -8 finished in 0.57 seconds on worker 4
    -10 finished in 0.58 seconds on worker 2
    -0.055971741

    Remote References and Distributed Garbage Collection

    Objects referred to by remote references can be freed only when all held references in the cluster are deleted.

    The node where the value is stored keeps track of which of the workers have a reference to it. Every time a RemoteChannel or a (unfetched) Future is serialized to a worker, the node pointed to by the reference is notified. And every time a RemoteChannel or a (unfetched) Future is garbage collected locally, the node owning the value is again notified.

    The notifications are done via sending of "tracking" messages–an "add reference" message when a reference is serialized to a different process and a "delete reference" message when a reference is locally garbage collected.

    Since Futures are write-once and cached locally, the act of fetch()ing a Future also updates reference tracking information on the node owning the value.

    The node which owns the value frees it once all references to it are cleared.

    With Futures, serializing an already fetched Future to a different node also sends the value since the original remote store may have collected the value by this time.

    It is important to note that when an object is locally garbage collected depends on the size of the object and the current memory pressure in the system.

    In case of remote references, the size of the local reference object is quite small, while the value stored on the remote node may be quite large. Since the local object may not be collected immediately, it is a good practice to explicitly call finalize() on local instances of a RemoteChannel, or on unfetched Futures. Since calling fetch() on a Future also removes its reference from the remote store, this is not required on fetched Futures. Explicitly calling finalize() results in an immediate message sent to the remote node to go ahead and remove its reference to the value.

    Once finalized, a reference becomes invalid and cannot be used in any further calls.

    Shared Arrays

    Shared Arrays use system shared memory to map the same array across many processes. While there are some similarities to a DArray, the behavior of a SharedArray is quite different. In a DArray, each process has local access to just a chunk of the data, and no two processes share the same chunk; in contrast, in a SharedArray each "participating" process has access to the entire array. A SharedArray is a good choice when you want to have a large amount of data jointly accessible to two or more processes on the same machine.

    SharedArray indexing (assignment and accessing values) works just as with regular arrays, and is efficient because the underlying memory is available to the local process. Therefore, most algorithms work naturally on SharedArrays, albeit in single-process mode. In cases where an algorithm insists on an Array input, the underlying array can be retrieved from a SharedArray by calling sdata(). For other AbstractArray types, sdata() just returns the object itself, so it's safe to use sdata() on any Array-type object.

    The constructor for a shared array is of the form:

    SharedArray{T,N}(dims::NTuple; init=false, pids=Int[])

    which creates an N-dimensional shared array of a bits type T and size dims across the processes specified by pids. Unlike distributed arrays, a shared array is accessible only from those participating workers specified by the pids named argument (and the creating process too, if it is on the same host).

    If an init function, of signature initfn(S::SharedArray), is specified, it is called on all the participating workers. You can specify that each worker runs the init function on a distinct portion of the array, thereby parallelizing initialization.

    Here's a brief example:

    julia> addprocs(3)
    -3-element Array{Int64,1}:
    - 2
    - 3
    - 4
    -
    -julia> S = SharedArray{Int,2}((3,4), init = S -> S[Base.localindexes(S)] = myid())
    -3×4 SharedArray{Int64,2}:
    - 2  2  3  4
    - 2  3  3  4
    - 2  3  4  4
    -
    -julia> S[3,2] = 7
    -7
    -
    -julia> S
    -3×4 SharedArray{Int64,2}:
    - 2  2  3  4
    - 2  3  3  4
    - 2  7  4  4

    Base.localindexes() provides disjoint one-dimensional ranges of indexes, and is sometimes convenient for splitting up tasks among processes. You can, of course, divide the work any way you wish:

    julia> S = SharedArray{Int,2}((3,4), init = S -> S[indexpids(S):length(procs(S)):length(S)] = myid())
    -3×4 SharedArray{Int64,2}:
    - 2  2  2  2
    - 3  3  3  3
    - 4  4  4  4

    Since all processes have access to the underlying data, you do have to be careful not to set up conflicts. For example:

    @sync begin
    -    for p in procs(S)
    -        @async begin
    -            remotecall_wait(fill!, p, S, p)
    -        end
    -    end
    -end

    would result in undefined behavior. Because each process fills the entire array with its own pid, whichever process is the last to execute (for any particular element of S) will have its pid retained.

    As a more extended and complex example, consider running the following "kernel" in parallel:

    q[i,j,t+1] = q[i,j,t] + u[i,j,t]

    In this case, if we try to split up the work using a one-dimensional index, we are likely to run into trouble: if q[i,j,t] is near the end of the block assigned to one worker and q[i,j,t+1] is near the beginning of the block assigned to another, it's very likely that q[i,j,t] will not be ready at the time it's needed for computing q[i,j,t+1]. In such cases, one is better off chunking the array manually. Let's split along the second dimension. Define a function that returns the (irange, jrange) indexes assigned to this worker:

    julia> @everywhere function myrange(q::SharedArray)
    -           idx = indexpids(q)
    -           if idx == 0 # This worker is not assigned a piece
    -               return 1:0, 1:0
    -           end
    -           nchunks = length(procs(q))
    -           splits = [round(Int, s) for s in linspace(0,size(q,2),nchunks+1)]
    -           1:size(q,1), splits[idx]+1:splits[idx+1]
    -       end

    Next, define the kernel:

    julia> @everywhere function advection_chunk!(q, u, irange, jrange, trange)
    -           @show (irange, jrange, trange)  # display so we can see what's happening
    -           for t in trange, j in jrange, i in irange
    -               q[i,j,t+1] = q[i,j,t] + u[i,j,t]
    -           end
    -           q
    -       end

    We also define a convenience wrapper for a SharedArray implementation

    julia> @everywhere advection_shared_chunk!(q, u) =
    -           advection_chunk!(q, u, myrange(q)..., 1:size(q,3)-1)

    Now let's compare three different versions, one that runs in a single process:

    julia> advection_serial!(q, u) = advection_chunk!(q, u, 1:size(q,1), 1:size(q,2), 1:size(q,3)-1);

    one that uses @parallel:

    julia> function advection_parallel!(q, u)
    -           for t = 1:size(q,3)-1
    -               @sync @parallel for j = 1:size(q,2)
    -                   for i = 1:size(q,1)
    -                       q[i,j,t+1]= q[i,j,t] + u[i,j,t]
    -                   end
    -               end
    -           end
    -           q
    -       end;

    and one that delegates in chunks:

    julia> function advection_shared!(q, u)
    -           @sync begin
    -               for p in procs(q)
    -                   @async remotecall_wait(advection_shared_chunk!, p, q, u)
    -               end
    -           end
    -           q
    -       end;

    If we create SharedArrays and time these functions, we get the following results (with julia -p 4):

    julia> q = SharedArray{Float64,3}((500,500,500));
    -
    -julia> u = SharedArray{Float64,3}((500,500,500));

    Run the functions once to JIT-compile and @time them on the second run:

    julia> @time advection_serial!(q, u);
    -(irange,jrange,trange) = (1:500,1:500,1:499)
    - 830.220 milliseconds (216 allocations: 13820 bytes)
    -
    -julia> @time advection_parallel!(q, u);
    -   2.495 seconds      (3999 k allocations: 289 MB, 2.09% gc time)
    -
    -julia> @time advection_shared!(q,u);
    -        From worker 2:       (irange,jrange,trange) = (1:500,1:125,1:499)
    -        From worker 4:       (irange,jrange,trange) = (1:500,251:375,1:499)
    -        From worker 3:       (irange,jrange,trange) = (1:500,126:250,1:499)
    -        From worker 5:       (irange,jrange,trange) = (1:500,376:500,1:499)
    - 238.119 milliseconds (2264 allocations: 169 KB)

    The biggest advantage of advection_shared! is that it minimizes traffic among the workers, allowing each to compute for an extended time on the assigned piece.

    Shared Arrays and Distributed Garbage Collection

    Like remote references, shared arrays are also dependent on garbage collection on the creating node to release references from all participating workers. Code which creates many short lived shared array objects would benefit from explicitly finalizing these objects as soon as possible. This results in both memory and file handles mapping the shared segment being released sooner.

    ClusterManagers

    The launching, management and networking of Julia processes into a logical cluster is done via cluster managers. A ClusterManager is responsible for

    • launching worker processes in a cluster environment

    • managing events during the lifetime of each worker

    • optionally, providing data transport

    A Julia cluster has the following characteristics:

    • The initial Julia process, also called the master, is special and has an id of 1.

    • Only the master process can add or remove worker processes.

    • All processes can directly communicate with each other.

    Connections between workers (using the in-built TCP/IP transport) is established in the following manner:

    • addprocs() is called on the master process with a ClusterManager object.

    • addprocs() calls the appropriate launch() method which spawns required number of worker processes on appropriate machines.

    • Each worker starts listening on a free port and writes out its host and port information to STDOUT.

    • The cluster manager captures the STDOUT of each worker and makes it available to the master process.

    • The master process parses this information and sets up TCP/IP connections to each worker.

    • Every worker is also notified of other workers in the cluster.

    • Each worker connects to all workers whose id is less than the worker's own id.

    • In this way a mesh network is established, wherein every worker is directly connected with every other worker.

    While the default transport layer uses plain TCPSocket, it is possible for a Julia cluster to provide its own transport.

    Julia provides two in-built cluster managers:

    LocalManager is used to launch additional workers on the same host, thereby leveraging multi-core and multi-processor hardware.

    Thus, a minimal cluster manager would need to:

    • be a subtype of the abstract ClusterManager

    • implement launch(), a method responsible for launching new workers

    • implement manage(), which is called at various events during a worker's lifetime (for example, sending an interrupt signal)

    addprocs(manager::FooManager) requires FooManager to implement:

    function launch(manager::FooManager, params::Dict, launched::Array, c::Condition)
    -    [...]
    -end
    -
    -function manage(manager::FooManager, id::Integer, config::WorkerConfig, op::Symbol)
    -    [...]
    -end

    As an example let us see how the LocalManager, the manager responsible for starting workers on the same host, is implemented:

    struct LocalManager <: ClusterManager
    -    np::Integer
    -end
    -
    -function launch(manager::LocalManager, params::Dict, launched::Array, c::Condition)
    -    [...]
    -end
    -
    -function manage(manager::LocalManager, id::Integer, config::WorkerConfig, op::Symbol)
    -    [...]
    -end

    The launch() method takes the following arguments:

    • manager::ClusterManager: the cluster manager that addprocs() is called with

    • params::Dict: all the keyword arguments passed to addprocs()

    • launched::Array: the array to append one or more WorkerConfig objects to

    • c::Condition: the condition variable to be notified as and when workers are launched

    The launch() method is called asynchronously in a separate task. The termination of this task signals that all requested workers have been launched. Hence the launch() function MUST exit as soon as all the requested workers have been launched.

    Newly launched workers are connected to each other, and the master process, in an all-to-all manner. Specifying the command argument --worker <cookie> results in the launched processes initializing themselves as workers and connections being set up via TCP/IP sockets. Optionally, --bind-to bind_addr[:port] may also be specified to enable other workers to connect to it at the specified bind_addr and port. This is useful for multi-homed hosts.

    As an example of a non-TCP/IP transport, an implementation may choose to use MPI, in which case --worker must NOT be specified. Instead, newly launched workers should call init_worker(cookie) before using any of the parallel constructs.

    For every worker launched, the launch() method must add a WorkerConfig object (with appropriate fields initialized) to launched

    mutable struct WorkerConfig
    -    # Common fields relevant to all cluster managers
    -    io::Nullable{IO}
    -    host::Nullable{AbstractString}
    -    port::Nullable{Integer}
    -
    -    # Used when launching additional workers at a host
    -    count::Nullable{Union{Int, Symbol}}
    -    exename::Nullable{AbstractString}
    -    exeflags::Nullable{Cmd}
    -
    -    # External cluster managers can use this to store information at a per-worker level
    -    # Can be a dict if multiple fields need to be stored.
    -    userdata::Nullable{Any}
    -
    -    # SSHManager / SSH tunnel connections to workers
    -    tunnel::Nullable{Bool}
    -    bind_addr::Nullable{AbstractString}
    -    sshflags::Nullable{Cmd}
    -    max_parallel::Nullable{Integer}
    -
    -    connect_at::Nullable{Any}
    -
    -    [...]
    -end

    Most of the fields in WorkerConfig are used by the inbuilt managers. Custom cluster managers would typically specify only io or host / port:

    • If io is specified, it is used to read host/port information. A Julia worker prints out its bind address and port at startup. This allows Julia workers to listen on any free port available instead of requiring worker ports to be configured manually.

    • If io is not specified, host and port are used to connect.

    • count, exename and exeflags are relevant for launching additional workers from a worker. For example, a cluster manager may launch a single worker per node, and use that to launch additional workers.

      • count with an integer value n will launch a total of n workers.

      • count with a value of :auto will launch as many workers as the number of cores on that machine.

      • exename is the name of the julia executable including the full path.

      • exeflags should be set to the required command line arguments for new workers.

    • tunnel, bind_addr, sshflags and max_parallel are used when a ssh tunnel is required to connect to the workers from the master process.

    • userdata is provided for custom cluster managers to store their own worker-specific information.

    manage(manager::FooManager, id::Integer, config::WorkerConfig, op::Symbol) is called at different times during the worker's lifetime with appropriate op values:

    • with :register/:deregister when a worker is added / removed from the Julia worker pool.

    • with :interrupt when interrupt(workers) is called. The ClusterManager should signal the appropriate worker with an interrupt signal.

    • with :finalize for cleanup purposes.

    Cluster Managers with Custom Transports

    Replacing the default TCP/IP all-to-all socket connections with a custom transport layer is a little more involved. Each Julia process has as many communication tasks as the workers it is connected to. For example, consider a Julia cluster of 32 processes in an all-to-all mesh network:

    • Each Julia process thus has 31 communication tasks.

    • Each task handles all incoming messages from a single remote worker in a message-processing loop.

    • The message-processing loop waits on an IO object (for example, a TCPSocket in the default implementation), reads an entire message, processes it and waits for the next one.

    • Sending messages to a process is done directly from any Julia task–not just communication tasks–again, via the appropriate IO object.

    Replacing the default transport requires the new implementation to set up connections to remote workers and to provide appropriate IO objects that the message-processing loops can wait on. The manager-specific callbacks to be implemented are:

    connect(manager::FooManager, pid::Integer, config::WorkerConfig)
    -kill(manager::FooManager, pid::Int, config::WorkerConfig)

    The default implementation (which uses TCP/IP sockets) is implemented as connect(manager::ClusterManager, pid::Integer, config::WorkerConfig).

    connect should return a pair of IO objects, one for reading data sent from worker pid, and the other to write data that needs to be sent to worker pid. Custom cluster managers can use an in-memory BufferStream as the plumbing to proxy data between the custom, possibly non-IO transport and Julia's in-built parallel infrastructure.

    A BufferStream is an in-memory IOBuffer which behaves like an IO–it is a stream which can be handled asynchronously.

    Folder examples/clustermanager/0mq contains an example of using ZeroMQ to connect Julia workers in a star topology with a 0MQ broker in the middle. Note: The Julia processes are still all logically connected to each other–any worker can message any other worker directly without any awareness of 0MQ being used as the transport layer.

    When using custom transports:

    • Julia workers must NOT be started with --worker. Starting with --worker will result in the newly launched workers defaulting to the TCP/IP socket transport implementation.

    • For every incoming logical connection with a worker, Base.process_messages(rd::IO, wr::IO)() must be called. This launches a new task that handles reading and writing of messages from/to the worker represented by the IO objects.

    • init_worker(cookie, manager::FooManager) MUST be called as part of worker process initialization.

    • Field connect_at::Any in WorkerConfig can be set by the cluster manager when launch() is called. The value of this field is passed in in all connect() callbacks. Typically, it carries information on how to connect to a worker. For example, the TCP/IP socket transport uses this field to specify the (host, port) tuple at which to connect to a worker.

    kill(manager, pid, config) is called to remove a worker from the cluster. On the master process, the corresponding IO objects must be closed by the implementation to ensure proper cleanup. The default implementation simply executes an exit() call on the specified remote worker.

    examples/clustermanager/simple is an example that shows a simple implementation using UNIX domain sockets for cluster setup.

    Network Requirements for LocalManager and SSHManager

    Julia clusters are designed to be executed on already secured environments on infrastructure such as local laptops, departmental clusters, or even the cloud. This section covers network security requirements for the inbuilt LocalManager and SSHManager:

    • The master process does not listen on any port. It only connects out to the workers.

    • Each worker binds to only one of the local interfaces and listens on the first free port starting from 9009.

    • LocalManager, used by addprocs(N), by default binds only to the loopback interface. This means that workers started later on remote hosts (or by anyone with malicious intentions) are unable to connect to the cluster. An addprocs(4) followed by an addprocs(["remote_host"]) will fail. Some users may need to create a cluster comprising their local system and a few remote systems. This can be done by explicitly requesting LocalManager to bind to an external network interface via the restrict keyword argument: addprocs(4; restrict=false).

    • SSHManager, used by addprocs(list_of_remote_hosts), launches workers on remote hosts via SSH. By default SSH is only used to launch Julia workers. Subsequent master-worker and worker-worker connections use plain, unencrypted TCP/IP sockets. The remote hosts must have passwordless login enabled. Additional SSH flags or credentials may be specified via keyword argument sshflags.

    • addprocs(list_of_remote_hosts; tunnel=true, sshflags=<ssh keys and other flags>) is useful when we wish to use SSH connections for master-worker too. A typical scenario for this is a local laptop running the Julia REPL (i.e., the master) with the rest of the cluster on the cloud, say on Amazon EC2. In this case only port 22 needs to be opened at the remote cluster coupled with SSH client authenticated via public key infrastructure (PKI). Authentication credentials can be supplied via sshflags, for example sshflags=`-e <keyfile>`.

      Note that worker-worker connections are still plain TCP and the local security policy on the remote cluster must allow for free connections between worker nodes, at least for ports 9009 and above.

      Securing and encrypting all worker-worker traffic (via SSH) or encrypting individual messages can be done via a custom ClusterManager.

    Cluster Cookie

    All processes in a cluster share the same cookie which, by default, is a randomly generated string on the master process:

    • Base.cluster_cookie() returns the cookie, while Base.cluster_cookie(cookie)() sets it and returns the new cookie.

    • All connections are authenticated on both sides to ensure that only workers started by the master are allowed to connect to each other.

    • The cookie must be passed to the workers at startup via argument --worker <cookie>. Custom ClusterManagers can retrieve the cookie on the master by calling Base.cluster_cookie(). Cluster managers not using the default TCP/IP transport (and hence not specifying --worker) must call init_worker(cookie, manager) with the same cookie as on the master.

    Note that environments requiring higher levels of security can implement this via a custom ClusterManager. For example, cookies can be pre-shared and hence not specified as a startup argument.

    Specifying Network Topology (Experimental)

    The keyword argument topology passed to addprocs is used to specify how the workers must be connected to each other:

    • :all_to_all, the default: all workers are connected to each other.

    • :master_slave: only the driver process, i.e. pid 1, has connections to the workers.

    • :custom: the launch method of the cluster manager specifies the connection topology via the fields ident and connect_idents in WorkerConfig. A worker with a cluster-manager-provided identity ident will connect to all workers specified in connect_idents.

    Currently, sending a message between unconnected workers results in an error. This behaviour, as with the functionality and interface, should be considered experimental in nature and may change in future releases.

    Multi-Threading (Experimental)

    In addition to tasks, remote calls, and remote references, Julia from v0.5 forwards will natively support multi-threading. Note that this section is experimental and the interfaces may change in the future.

    Setup

    By default, Julia starts up with a single thread of execution. This can be verified by using the command Threads.nthreads():

    julia> Threads.nthreads()
    -1

    The number of threads Julia starts up with is controlled by an environment variable called JULIA_NUM_THREADS. Now, let's start up Julia with 4 threads:

    export JULIA_NUM_THREADS=4

    (The above command works on bourne shells on Linux and OSX. Note that if you're using a C shell on these platforms, you should use the keyword set instead of export. If you're on Windows, start up the command line in the location of julia.exe and use set instead of export.)

    Let's verify there are 4 threads at our disposal.

    julia> Threads.nthreads()
    -4

    But we are currently on the master thread. To check, we use the command Threads.threadid()

    julia> Threads.threadid()
    -1

    The @threads Macro

    Let's work a simple example using our native threads. Let us create an array of zeros:

    julia> a = zeros(10)
    -10-element Array{Float64,1}:
    - 0.0
    - 0.0
    - 0.0
    - 0.0
    - 0.0
    - 0.0
    - 0.0
    - 0.0
    - 0.0
    - 0.0

    Let us operate on this array simultaneously using 4 threads. We'll have each thread write its thread ID into each location.

    Julia supports parallel loops using the Threads.@threads macro. This macro is affixed in front of a for loop to indicate to Julia that the loop is a multi-threaded region:

    julia> Threads.@threads for i = 1:10
    -           a[i] = Threads.threadid()
    -       end

    The iteration space is split amongst the threads, after which each thread writes its thread ID to its assigned locations:

    julia> a
    -10-element Array{Float64,1}:
    - 1.0
    - 1.0
    - 1.0
    - 2.0
    - 2.0
    - 2.0
    - 3.0
    - 3.0
    - 4.0
    - 4.0

    Note that Threads.@threads does not have an optional reduction parameter like @parallel.

    @threadcall (Experimental)

    All I/O tasks, timers, REPL commands, etc are multiplexed onto a single OS thread via an event loop. A patched version of libuv (http://docs.libuv.org/en/v1.x/) provides this functionality. Yield points provide for co-operatively scheduling multiple tasks onto the same OS thread. I/O tasks and timers yield implicitly while waiting for the event to occur. Calling yield() explicitly allows for other tasks to be scheduled.

    Thus, a task executing a ccall effectively prevents the Julia scheduler from executing any other tasks till the call returns. This is true for all calls into external libraries. Exceptions are calls into custom C code that call back into Julia (which may then yield) or C code that calls jl_yield() (C equivalent of yield()).

    Note that while Julia code runs on a single thread (by default), libraries used by Julia may launch their own internal threads. For example, the BLAS library may start as many threads as there are cores on a machine.

    The @threadcall macro addresses scenarios where we do not want a ccall to block the main Julia event loop. It schedules a C function for execution in a separate thread. A threadpool with a default size of 4 is used for this. The size of the threadpool is controlled via environment variable UV_THREADPOOL_SIZE. While waiting for a free thread, and during function execution once a thread is available, the requesting task (on the main Julia event loop) yields to other tasks. Note that @threadcall does not return till the execution is complete. From a user point of view, it is therefore a blocking call like other Julia APIs.

    It is very important that the called function does not call back into Julia.

    @threadcall may be removed/changed in future versions of Julia.

    [1]

    In this context, MPI refers to the MPI-1 standard. Beginning with MPI-2, the MPI standards committee introduced a new set of communication mechanisms, collectively referred to as Remote Memory Access (RMA). The motivation for adding RMA to the MPI standard was to facilitate one-sided communication patterns. For additional information on the latest MPI standard, see http://mpi-forum.org/docs.

    diff --git a/julia-0.6.3/share/doc/julia/html/en/manual/performance-tips.html b/julia-0.6.3/share/doc/julia/html/en/manual/performance-tips.html deleted file mode 100644 index 676ee1d..0000000 --- a/julia-0.6.3/share/doc/julia/html/en/manual/performance-tips.html +++ /dev/null @@ -1,527 +0,0 @@ - -Performance Tips · The Julia Language

    Performance Tips

    Performance Tips

    In the following sections, we briefly go through a few techniques that can help make your Julia code run as fast as possible.

    Avoid global variables

    A global variable might have its value, and therefore its type, change at any point. This makes it difficult for the compiler to optimize code using global variables. Variables should be local, or passed as arguments to functions, whenever possible.

    Any code that is performance critical or being benchmarked should be inside a function.

    We find that global names are frequently constants, and declaring them as such greatly improves performance:

    const DEFAULT_VAL = 0

    Uses of non-constant globals can be optimized by annotating their types at the point of use:

    global x
    -y = f(x::Int + 1)

    Writing functions is better style. It leads to more reusable code and clarifies what steps are being done, and what their inputs and outputs are.

    Note

    All code in the REPL is evaluated in global scope, so a variable defined and assigned at toplevel will be a global variable.

    In the following REPL session:

    julia> x = 1.0

    is equivalent to:

    julia> global x = 1.0

    so all the performance issues discussed previously apply.

    Measure performance with @time and pay attention to memory allocation

    A useful tool for measuring performance is the @time macro. The following example illustrates good working style:

    julia> function f(n)
    -           s = 0
    -           for i = 1:n
    -               s += i/2
    -           end
    -           s
    -       end
    -f (generic function with 1 method)
    -
    -julia> @time f(1)
    -  0.012686 seconds (2.09 k allocations: 103.421 KiB)
    -0.5
    -
    -julia> @time f(10^6)
    -  0.021061 seconds (3.00 M allocations: 45.777 MiB, 11.69% gc time)
    -2.5000025e11

    On the first call (@time f(1)), f gets compiled. (If you've not yet used @time in this session, it will also compile functions needed for timing.) You should not take the results of this run seriously. For the second run, note that in addition to reporting the time, it also indicated that a large amount of memory was allocated. This is the single biggest advantage of @time vs. functions like tic() and toc(), which only report time.

    Unexpected memory allocation is almost always a sign of some problem with your code, usually a problem with type-stability. Consequently, in addition to the allocation itself, it's very likely that the code generated for your function is far from optimal. Take such indications seriously and follow the advice below.

    For more serious benchmarking, consider the BenchmarkTools.jl package which evaluates the function multiple times in order to reduce noise.

    As a teaser, an improved version of this function allocates no memory (the allocation reported below is due to running the @time macro in global scope) and has an order of magnitude faster execution after the first call:

    julia> @time f_improved(1)
    -  0.007008 seconds (1.32 k allocations: 63.640 KiB)
    -0.5
    -
    -julia> @time f_improved(10^6)
    -  0.002997 seconds (6 allocations: 192 bytes)
    -2.5000025e11

    Below you'll learn how to spot the problem with f and how to fix it.

    In some situations, your function may need to allocate memory as part of its operation, and this can complicate the simple picture above. In such cases, consider using one of the tools below to diagnose problems, or write a version of your function that separates allocation from its algorithmic aspects (see Pre-allocating outputs).

    Tools

    Julia and its package ecosystem includes tools that may help you diagnose problems and improve the performance of your code:

    • Profiling allows you to measure the performance of your running code and identify lines that serve as bottlenecks. For complex projects, the ProfileView package can help you visualize your profiling results.

    • Unexpectedly-large memory allocations–as reported by @time, @allocated, or the profiler (through calls to the garbage-collection routines)–hint that there might be issues with your code. If you don't see another reason for the allocations, suspect a type problem. You can also start Julia with the --track-allocation=user option and examine the resulting *.mem files to see information about where those allocations occur. See Memory allocation analysis.

    • @code_warntype generates a representation of your code that can be helpful in finding expressions that result in type uncertainty. See @code_warntype below.

    • The Lint package can also warn you of certain types of programming errors.

    Avoid containers with abstract type parameters

    When working with parameterized types, including arrays, it is best to avoid parameterizing with abstract types where possible.

    Consider the following:

    a = Real[]    # typeof(a) = Array{Real,1}
    -if (f = rand()) < .8
    -    push!(a, f)
    -end

    Because a is a an array of abstract type Real, it must be able to hold any Real value. Since Real objects can be of arbitrary size and structure, a must be represented as an array of pointers to individually allocated Real objects. Because f will always be a Float64, we should instead, use:

    a = Float64[] # typeof(a) = Array{Float64,1}

    which will create a contiguous block of 64-bit floating-point values that can be manipulated efficiently.

    See also the discussion under Parametric Types.

    Type declarations

    In many languages with optional type declarations, adding declarations is the principal way to make code run faster. This is not the case in Julia. In Julia, the compiler generally knows the types of all function arguments, local variables, and expressions. However, there are a few specific instances where declarations are helpful.

    Avoid fields with abstract type

    Types can be declared without specifying the types of their fields:

    julia> struct MyAmbiguousType
    -           a
    -       end

    This allows a to be of any type. This can often be useful, but it does have a downside: for objects of type MyAmbiguousType, the compiler will not be able to generate high-performance code. The reason is that the compiler uses the types of objects, not their values, to determine how to build code. Unfortunately, very little can be inferred about an object of type MyAmbiguousType:

    julia> b = MyAmbiguousType("Hello")
    -MyAmbiguousType("Hello")
    -
    -julia> c = MyAmbiguousType(17)
    -MyAmbiguousType(17)
    -
    -julia> typeof(b)
    -MyAmbiguousType
    -
    -julia> typeof(c)
    -MyAmbiguousType

    b and c have the same type, yet their underlying representation of data in memory is very different. Even if you stored just numeric values in field a, the fact that the memory representation of a UInt8 differs from a Float64 also means that the CPU needs to handle them using two different kinds of instructions. Since the required information is not available in the type, such decisions have to be made at run-time. This slows performance.

    You can do better by declaring the type of a. Here, we are focused on the case where a might be any one of several types, in which case the natural solution is to use parameters. For example:

    julia> mutable struct MyType{T<:AbstractFloat}
    -           a::T
    -       end

    This is a better choice than

    julia> mutable struct MyStillAmbiguousType
    -           a::AbstractFloat
    -       end

    because the first version specifies the type of a from the type of the wrapper object. For example:

    julia> m = MyType(3.2)
    -MyType{Float64}(3.2)
    -
    -julia> t = MyStillAmbiguousType(3.2)
    -MyStillAmbiguousType(3.2)
    -
    -julia> typeof(m)
    -MyType{Float64}
    -
    -julia> typeof(t)
    -MyStillAmbiguousType

    The type of field a can be readily determined from the type of m, but not from the type of t. Indeed, in t it's possible to change the type of field a:

    julia> typeof(t.a)
    -Float64
    -
    -julia> t.a = 4.5f0
    -4.5f0
    -
    -julia> typeof(t.a)
    -Float32

    In contrast, once m is constructed, the type of m.a cannot change:

    julia> m.a = 4.5f0
    -4.5f0
    -
    -julia> typeof(m.a)
    -Float64

    The fact that the type of m.a is known from m's type–coupled with the fact that its type cannot change mid-function–allows the compiler to generate highly-optimized code for objects like m but not for objects like t.

    Of course, all of this is true only if we construct m with a concrete type. We can break this by explicitly constructing it with an abstract type:

    julia> m = MyType{AbstractFloat}(3.2)
    -MyType{AbstractFloat}(3.2)
    -
    -julia> typeof(m.a)
    -Float64
    -
    -julia> m.a = 4.5f0
    -4.5f0
    -
    -julia> typeof(m.a)
    -Float32

    For all practical purposes, such objects behave identically to those of MyStillAmbiguousType.

    It's quite instructive to compare the sheer amount code generated for a simple function

    func(m::MyType) = m.a+1

    using

    code_llvm(func,Tuple{MyType{Float64}})
    -code_llvm(func,Tuple{MyType{AbstractFloat}})
    -code_llvm(func,Tuple{MyType})

    For reasons of length the results are not shown here, but you may wish to try this yourself. Because the type is fully-specified in the first case, the compiler doesn't need to generate any code to resolve the type at run-time. This results in shorter and faster code.

    Avoid fields with abstract containers

    The same best practices also work for container types:

    julia> mutable struct MySimpleContainer{A<:AbstractVector}
    -           a::A
    -       end
    -
    -julia> mutable struct MyAmbiguousContainer{T}
    -           a::AbstractVector{T}
    -       end

    For example:

    julia> c = MySimpleContainer(1:3);
    -
    -julia> typeof(c)
    -MySimpleContainer{UnitRange{Int64}}
    -
    -julia> c = MySimpleContainer([1:3;]);
    -
    -julia> typeof(c)
    -MySimpleContainer{Array{Int64,1}}
    -
    -julia> b = MyAmbiguousContainer(1:3);
    -
    -julia> typeof(b)
    -MyAmbiguousContainer{Int64}
    -
    -julia> b = MyAmbiguousContainer([1:3;]);
    -
    -julia> typeof(b)
    -MyAmbiguousContainer{Int64}

    For MySimpleContainer, the object is fully-specified by its type and parameters, so the compiler can generate optimized functions. In most instances, this will probably suffice.

    While the compiler can now do its job perfectly well, there are cases where you might wish that your code could do different things depending on the element type of a. Usually the best way to achieve this is to wrap your specific operation (here, foo) in a separate function:

    julia> function sumfoo(c::MySimpleContainer)
    -           s = 0
    -           for x in c.a
    -               s += foo(x)
    -           end
    -           s
    -       end
    -sumfoo (generic function with 1 method)
    -
    -julia> foo(x::Integer) = x
    -foo (generic function with 1 method)
    -
    -julia> foo(x::AbstractFloat) = round(x)
    -foo (generic function with 2 methods)

    This keeps things simple, while allowing the compiler to generate optimized code in all cases.

    However, there are cases where you may need to declare different versions of the outer function for different element types of a. You could do it like this:

    function myfun(c::MySimpleContainer{Vector{T}}) where T<:AbstractFloat
    -    ...
    -end
    -function myfun(c::MySimpleContainer{Vector{T}}) where T<:Integer
    -    ...
    -end

    This works fine for Vector{T}, but we'd also have to write explicit versions for UnitRange{T} or other abstract types. To prevent such tedium, you can use two parameters in the declaration of MyContainer:

    julia> mutable struct MyContainer{T, A<:AbstractVector}
    -           a::A
    -       end
    -
    -julia> MyContainer(v::AbstractVector) = MyContainer{eltype(v), typeof(v)}(v)
    -MyContainer
    -
    -julia> b = MyContainer(1:5);
    -
    -julia> typeof(b)
    -MyContainer{Int64,UnitRange{Int64}}

    Note the somewhat surprising fact that T doesn't appear in the declaration of field a, a point that we'll return to in a moment. With this approach, one can write functions such as:

    julia> function myfunc(c::MyContainer{<:Integer, <:AbstractArray})
    -           return c.a[1]+1
    -       end
    -myfunc (generic function with 1 method)
    -
    -julia> function myfunc(c::MyContainer{<:AbstractFloat})
    -           return c.a[1]+2
    -       end
    -myfunc (generic function with 2 methods)
    -
    -julia> function myfunc(c::MyContainer{T,Vector{T}}) where T<:Integer
    -           return c.a[1]+3
    -       end
    -myfunc (generic function with 3 methods)
    Note

    Because we can only define MyContainer for A<:AbstractArray, and any unspecified parameters are arbitrary, the first function above could have been written more succinctly as function myfunc{T<:Integer}(c::MyContainer{T})

    julia> myfunc(MyContainer(1:3))
    -2
    -
    -julia> myfunc(MyContainer(1.0:3))
    -3.0
    -
    -julia> myfunc(MyContainer([1:3;]))
    -4

    As you can see, with this approach it's possible to specialize on both the element type T and the array type A.

    However, there's one remaining hole: we haven't enforced that A has element type T, so it's perfectly possible to construct an object like this:

    julia> b = MyContainer{Int64, UnitRange{Float64}}(UnitRange(1.3, 5.0));
    -
    -julia> typeof(b)
    -MyContainer{Int64,UnitRange{Float64}}

    To prevent this, we can add an inner constructor:

    julia> mutable struct MyBetterContainer{T<:Real, A<:AbstractVector}
    -           a::A
    -           MyBetterContainer{T,A}(v::AbstractVector{T}) where {T,A} = new(v)
    -       end
    -
    -julia> MyBetterContainer(v::AbstractVector) = MyBetterContainer{eltype(v),typeof(v)}(v)
    -MyBetterContainer
    -
    -julia> b = MyBetterContainer(UnitRange(1.3, 5.0));
    -
    -julia> typeof(b)
    -MyBetterContainer{Float64,UnitRange{Float64}}
    -
    -julia> b = MyBetterContainer{Int64, UnitRange{Float64}}(UnitRange(1.3, 5.0));
    -ERROR: MethodError: Cannot `convert` an object of type UnitRange{Float64} to an object of type MyBetterContainer{Int64,UnitRange{Float64}}
    -[...]

    The inner constructor requires that the element type of A be T.

    Annotate values taken from untyped locations

    It is often convenient to work with data structures that may contain values of any type (arrays of type Array{Any}). But, if you're using one of these structures and happen to know the type of an element, it helps to share this knowledge with the compiler:

    function foo(a::Array{Any,1})
    -    x = a[1]::Int32
    -    b = x+1
    -    ...
    -end

    Here, we happened to know that the first element of a would be an Int32. Making an annotation like this has the added benefit that it will raise a run-time error if the value is not of the expected type, potentially catching certain bugs earlier.

    Declare types of keyword arguments

    Keyword arguments can have declared types:

    function with_keyword(x; name::Int = 1)
    -    ...
    -end

    Functions are specialized on the types of keyword arguments, so these declarations will not affect performance of code inside the function. However, they will reduce the overhead of calls to the function that include keyword arguments.

    Functions with keyword arguments have near-zero overhead for call sites that pass only positional arguments.

    Passing dynamic lists of keyword arguments, as in f(x; keywords...), can be slow and should be avoided in performance-sensitive code.

    Break functions into multiple definitions

    Writing a function as many small definitions allows the compiler to directly call the most applicable code, or even inline it.

    Here is an example of a "compound function" that should really be written as multiple definitions:

    function norm(A)
    -    if isa(A, Vector)
    -        return sqrt(real(dot(A,A)))
    -    elseif isa(A, Matrix)
    -        return maximum(svd(A)[2])
    -    else
    -        error("norm: invalid argument")
    -    end
    -end

    This can be written more concisely and efficiently as:

    norm(x::Vector) = sqrt(real(dot(x,x)))
    -norm(A::Matrix) = maximum(svd(A)[2])

    Write "type-stable" functions

    When possible, it helps to ensure that a function always returns a value of the same type. Consider the following definition:

    pos(x) = x < 0 ? 0 : x

    Although this seems innocent enough, the problem is that 0 is an integer (of type Int) and x might be of any type. Thus, depending on the value of x, this function might return a value of either of two types. This behavior is allowed, and may be desirable in some cases. But it can easily be fixed as follows:

    pos(x) = x < 0 ? zero(x) : x

    There is also a one() function, and a more general oftype(x, y) function, which returns y converted to the type of x.

    Avoid changing the type of a variable

    An analogous "type-stability" problem exists for variables used repeatedly within a function:

    function foo()
    -    x = 1
    -    for i = 1:10
    -        x = x/bar()
    -    end
    -    return x
    -end

    Local variable x starts as an integer, and after one loop iteration becomes a floating-point number (the result of / operator). This makes it more difficult for the compiler to optimize the body of the loop. There are several possible fixes:

    • Initialize x with x = 1.0

    • Declare the type of x: x::Float64 = 1

    • Use an explicit conversion: x = oneunit(T)

    • Initialize with the first loop iteration, to x = 1/bar(), then loop for i = 2:10

    Separate kernel functions (aka, function barriers)

    Many functions follow a pattern of performing some set-up work, and then running many iterations to perform a core computation. Where possible, it is a good idea to put these core computations in separate functions. For example, the following contrived function returns an array of a randomly-chosen type:

    julia> function strange_twos(n)
    -           a = Vector{rand(Bool) ? Int64 : Float64}(n)
    -           for i = 1:n
    -               a[i] = 2
    -           end
    -           return a
    -       end
    -strange_twos (generic function with 1 method)
    -
    -julia> strange_twos(3)
    -3-element Array{Float64,1}:
    - 2.0
    - 2.0
    - 2.0

    This should be written as:

    julia> function fill_twos!(a)
    -           for i=1:length(a)
    -               a[i] = 2
    -           end
    -       end
    -fill_twos! (generic function with 1 method)
    -
    -julia> function strange_twos(n)
    -           a = Array{rand(Bool) ? Int64 : Float64}(n)
    -           fill_twos!(a)
    -           return a
    -       end
    -strange_twos (generic function with 1 method)
    -
    -julia> strange_twos(3)
    -3-element Array{Float64,1}:
    - 2.0
    - 2.0
    - 2.0

    Julia's compiler specializes code for argument types at function boundaries, so in the original implementation it does not know the type of a during the loop (since it is chosen randomly). Therefore the second version is generally faster since the inner loop can be recompiled as part of fill_twos! for different types of a.

    The second form is also often better style and can lead to more code reuse.

    This pattern is used in several places in the standard library. For example, see hvcat_fill in abstractarray.jl, or the fill! function, which we could have used instead of writing our own fill_twos!.

    Functions like strange_twos occur when dealing with data of uncertain type, for example data loaded from an input file that might contain either integers, floats, strings, or something else.

    Types with values-as-parameters

    Let's say you want to create an N-dimensional array that has size 3 along each axis. Such arrays can be created like this:

    julia> A = fill(5.0, (3, 3))
    -3×3 Array{Float64,2}:
    - 5.0  5.0  5.0
    - 5.0  5.0  5.0
    - 5.0  5.0  5.0

    This approach works very well: the compiler can figure out that A is an Array{Float64,2} because it knows the type of the fill value (5.0::Float64) and the dimensionality ((3, 3)::NTuple{2,Int}). This implies that the compiler can generate very efficient code for any future usage of A in the same function.

    But now let's say you want to write a function that creates a 3×3×... array in arbitrary dimensions; you might be tempted to write a function

    julia> function array3(fillval, N)
    -           fill(fillval, ntuple(d->3, N))
    -       end
    -array3 (generic function with 1 method)
    -
    -julia> array3(5.0, 2)
    -3×3 Array{Float64,2}:
    - 5.0  5.0  5.0
    - 5.0  5.0  5.0
    - 5.0  5.0  5.0

    This works, but (as you can verify for yourself using @code_warntype array3(5.0, 2)) the problem is that the output type cannot be inferred: the argument N is a value of type Int, and type-inference does not (and cannot) predict its value in advance. This means that code using the output of this function has to be conservative, checking the type on each access of A; such code will be very slow.

    Now, one very good way to solve such problems is by using the function-barrier technique. However, in some cases you might want to eliminate the type-instability altogether. In such cases, one approach is to pass the dimensionality as a parameter, for example through Val{T} (see "Value types"):

    julia> function array3(fillval, ::Type{Val{N}}) where N
    -           fill(fillval, ntuple(d->3, Val{N}))
    -       end
    -array3 (generic function with 1 method)
    -
    -julia> array3(5.0, Val{2})
    -3×3 Array{Float64,2}:
    - 5.0  5.0  5.0
    - 5.0  5.0  5.0
    - 5.0  5.0  5.0

    Julia has a specialized version of ntuple that accepts a Val{::Int} as the second parameter; by passing N as a type-parameter, you make its "value" known to the compiler. Consequently, this version of array3 allows the compiler to predict the return type.

    However, making use of such techniques can be surprisingly subtle. For example, it would be of no help if you called array3 from a function like this:

    function call_array3(fillval, n)
    -    A = array3(fillval, Val{n})
    -end

    Here, you've created the same problem all over again: the compiler can't guess the type of n, so it doesn't know the type of Val{n}. Attempting to use Val, but doing so incorrectly, can easily make performance worse in many situations. (Only in situations where you're effectively combining Val with the function-barrier trick, to make the kernel function more efficient, should code like the above be used.)

    An example of correct usage of Val would be:

    function filter3(A::AbstractArray{T,N}) where {T,N}
    -    kernel = array3(1, Val{N})
    -    filter(A, kernel)
    -end

    In this example, N is passed as a parameter, so its "value" is known to the compiler. Essentially, Val{T} works only when T is either hard-coded (Val{3}) or already specified in the type-domain.

    The dangers of abusing multiple dispatch (aka, more on types with values-as-parameters)

    Once one learns to appreciate multiple dispatch, there's an understandable tendency to go crazy and try to use it for everything. For example, you might imagine using it to store information, e.g.

    struct Car{Make,Model}
    -    year::Int
    -    ...more fields...
    -end

    and then dispatch on objects like Car{:Honda,:Accord}(year, args...).

    This might be worthwhile when the following are true:

    • You require CPU-intensive processing on each Car, and it becomes vastly more efficient if you know the Make and Model at compile time.

    • You have homogenous lists of the same type of Car to process, so that you can store them all in an Array{Car{:Honda,:Accord},N}.

    When the latter holds, a function processing such a homogenous array can be productively specialized: Julia knows the type of each element in advance (all objects in the container have the same concrete type), so Julia can "look up" the correct method calls when the function is being compiled (obviating the need to check at run-time) and thereby emit efficient code for processing the whole list.

    When these do not hold, then it's likely that you'll get no benefit; worse, the resulting "combinatorial explosion of types" will be counterproductive. If items[i+1] has a different type than item[i], Julia has to look up the type at run-time, search for the appropriate method in method tables, decide (via type intersection) which one matches, determine whether it has been JIT-compiled yet (and do so if not), and then make the call. In essence, you're asking the full type- system and JIT-compilation machinery to basically execute the equivalent of a switch statement or dictionary lookup in your own code.

    Some run-time benchmarks comparing (1) type dispatch, (2) dictionary lookup, and (3) a "switch" statement can be found on the mailing list.

    Perhaps even worse than the run-time impact is the compile-time impact: Julia will compile specialized functions for each different Car{Make, Model}; if you have hundreds or thousands of such types, then every function that accepts such an object as a parameter (from a custom get_year function you might write yourself, to the generic push! function in the standard library) will have hundreds or thousands of variants compiled for it. Each of these increases the size of the cache of compiled code, the length of internal lists of methods, etc. Excess enthusiasm for values-as-parameters can easily waste enormous resources.

    Access arrays in memory order, along columns

    Multidimensional arrays in Julia are stored in column-major order. This means that arrays are stacked one column at a time. This can be verified using the vec function or the syntax [:] as shown below (notice that the array is ordered [1 3 2 4], not [1 2 3 4]):

    julia> x = [1 2; 3 4]
    -2×2 Array{Int64,2}:
    - 1  2
    - 3  4
    -
    -julia> x[:]
    -4-element Array{Int64,1}:
    - 1
    - 3
    - 2
    - 4

    This convention for ordering arrays is common in many languages like Fortran, Matlab, and R (to name a few). The alternative to column-major ordering is row-major ordering, which is the convention adopted by C and Python (numpy) among other languages. Remembering the ordering of arrays can have significant performance effects when looping over arrays. A rule of thumb to keep in mind is that with column-major arrays, the first index changes most rapidly. Essentially this means that looping will be faster if the inner-most loop index is the first to appear in a slice expression.

    Consider the following contrived example. Imagine we wanted to write a function that accepts a Vector and returns a square Matrix with either the rows or the columns filled with copies of the input vector. Assume that it is not important whether rows or columns are filled with these copies (perhaps the rest of the code can be easily adapted accordingly). We could conceivably do this in at least four ways (in addition to the recommended call to the built-in repmat()):

    function copy_cols(x::Vector{T}) where T
    -    n = size(x, 1)
    -    out = Array{T}(n, n)
    -    for i = 1:n
    -        out[:, i] = x
    -    end
    -    out
    -end
    -
    -function copy_rows(x::Vector{T}) where T
    -    n = size(x, 1)
    -    out = Array{T}(n, n)
    -    for i = 1:n
    -        out[i, :] = x
    -    end
    -    out
    -end
    -
    -function copy_col_row(x::Vector{T}) where T
    -    n = size(x, 1)
    -    out = Array{T}(n, n)
    -    for col = 1:n, row = 1:n
    -        out[row, col] = x[row]
    -    end
    -    out
    -end
    -
    -function copy_row_col(x::Vector{T}) where T
    -    n = size(x, 1)
    -    out = Array{T}(n, n)
    -    for row = 1:n, col = 1:n
    -        out[row, col] = x[col]
    -    end
    -    out
    -end

    Now we will time each of these functions using the same random 10000 by 1 input vector:

    julia> x = randn(10000);
    -
    -julia> fmt(f) = println(rpad(string(f)*": ", 14, ' '), @elapsed f(x))
    -
    -julia> map(fmt, Any[copy_cols, copy_rows, copy_col_row, copy_row_col]);
    -copy_cols:    0.331706323
    -copy_rows:    1.799009911
    -copy_col_row: 0.415630047
    -copy_row_col: 1.721531501

    Notice that copy_cols is much faster than copy_rows. This is expected because copy_cols respects the column-based memory layout of the Matrix and fills it one column at a time. Additionally, copy_col_row is much faster than copy_row_col because it follows our rule of thumb that the first element to appear in a slice expression should be coupled with the inner-most loop.

    Pre-allocating outputs

    If your function returns an Array or some other complex type, it may have to allocate memory. Unfortunately, oftentimes allocation and its converse, garbage collection, are substantial bottlenecks.

    Sometimes you can circumvent the need to allocate memory on each function call by preallocating the output. As a trivial example, compare

    function xinc(x)
    -    return [x, x+1, x+2]
    -end
    -
    -function loopinc()
    -    y = 0
    -    for i = 1:10^7
    -        ret = xinc(i)
    -        y += ret[2]
    -    end
    -    y
    -end

    with

    function xinc!(ret::AbstractVector{T}, x::T) where T
    -    ret[1] = x
    -    ret[2] = x+1
    -    ret[3] = x+2
    -    nothing
    -end
    -
    -function loopinc_prealloc()
    -    ret = Array{Int}(3)
    -    y = 0
    -    for i = 1:10^7
    -        xinc!(ret, i)
    -        y += ret[2]
    -    end
    -    y
    -end

    Timing results:

    julia> @time loopinc()
    -  0.529894 seconds (40.00 M allocations: 1.490 GiB, 12.14% gc time)
    -50000015000000
    -
    -julia> @time loopinc_prealloc()
    -  0.030850 seconds (6 allocations: 288 bytes)
    -50000015000000

    Preallocation has other advantages, for example by allowing the caller to control the "output" type from an algorithm. In the example above, we could have passed a SubArray rather than an Array, had we so desired.

    Taken to its extreme, pre-allocation can make your code uglier, so performance measurements and some judgment may be required. However, for "vectorized" (element-wise) functions, the convenient syntax x .= f.(y) can be used for in-place operations with fused loops and no temporary arrays (see the dot syntax for vectorizing functions).

    More dots: Fuse vectorized operations

    Julia has a special dot syntax that converts any scalar function into a "vectorized" function call, and any operator into a "vectorized" operator, with the special property that nested "dot calls" are fusing: they are combined at the syntax level into a single loop, without allocating temporary arrays. If you use .= and similar assignment operators, the result can also be stored in-place in a pre-allocated array (see above).

    In a linear-algebra context, this means that even though operations like vector + vector and vector * scalar are defined, it can be advantageous to instead use vector .+ vector and vector .* scalar because the resulting loops can be fused with surrounding computations. For example, consider the two functions:

    f(x) = 3x.^2 + 4x + 7x.^3
    -
    -fdot(x) = @. 3x^2 + 4x + 7x^3 # equivalent to 3 .* x.^2 .+ 4 .* x .+ 7 .* x.^3

    Both f and fdot compute the same thing. However, fdot (defined with the help of the @. macro) is significantly faster when applied to an array:

    julia> x = rand(10^6);
    -
    -julia> @time f(x);
    -  0.010986 seconds (18 allocations: 53.406 MiB, 11.45% gc time)
    -
    -julia> @time fdot(x);
    -  0.003470 seconds (6 allocations: 7.630 MiB)
    -
    -julia> @time f.(x);
    -  0.003297 seconds (30 allocations: 7.631 MiB)

    That is, fdot(x) is three times faster and allocates 1/7 the memory of f(x), because each * and + operation in f(x) allocates a new temporary array and executes in a separate loop. (Of course, if you just do f.(x) then it is as fast as fdot(x) in this example, but in many contexts it is more convenient to just sprinkle some dots in your expressions rather than defining a separate function for each vectorized operation.)

    Consider using views for slices

    In Julia, an array "slice" expression like array[1:5, :] creates a copy of that data (except on the left-hand side of an assignment, where array[1:5, :] = ... assigns in-place to that portion of array). If you are doing many operations on the slice, this can be good for performance because it is more efficient to work with a smaller contiguous copy than it would be to index into the original array. On the other hand, if you are just doing a few simple operations on the slice, the cost of the allocation and copy operations can be substantial.

    An alternative is to create a "view" of the array, which is an array object (a SubArray) that actually references the data of the original array in-place, without making a copy. (If you write to a view, it modifies the original array's data as well.) This can be done for individual slices by calling view(), or more simply for a whole expression or block of code by putting @views in front of that expression. For example:

    julia> fcopy(x) = sum(x[2:end-1])
    -
    -julia> @views fview(x) = sum(x[2:end-1])
    -
    -julia> x = rand(10^6);
    -
    -julia> @time fcopy(x);
    -  0.003051 seconds (7 allocations: 7.630 MB)
    -
    -julia> @time fview(x);
    -  0.001020 seconds (6 allocations: 224 bytes)

    Notice both the 3× speedup and the decreased memory allocation of the fview version of the function.

    Avoid string interpolation for I/O

    When writing data to a file (or other I/O device), forming extra intermediate strings is a source of overhead. Instead of:

    println(file, "$a $b")

    use:

    println(file, a, " ", b)

    The first version of the code forms a string, then writes it to the file, while the second version writes values directly to the file. Also notice that in some cases string interpolation can be harder to read. Consider:

    println(file, "$(f(a))$(f(b))")

    versus:

    println(file, f(a), f(b))

    Optimize network I/O during parallel execution

    When executing a remote function in parallel:

    responses = Vector{Any}(nworkers())
    -@sync begin
    -    for (idx, pid) in enumerate(workers())
    -        @async responses[idx] = remotecall_fetch(pid, foo, args...)
    -    end
    -end

    is faster than:

    refs = Vector{Any}(nworkers())
    -for (idx, pid) in enumerate(workers())
    -    refs[idx] = @spawnat pid foo(args...)
    -end
    -responses = [fetch(r) for r in refs]

    The former results in a single network round-trip to every worker, while the latter results in two network calls - first by the @spawnat and the second due to the fetch (or even a wait). The fetch/wait is also being executed serially resulting in an overall poorer performance.

    Fix deprecation warnings

    A deprecated function internally performs a lookup in order to print a relevant warning only once. This extra lookup can cause a significant slowdown, so all uses of deprecated functions should be modified as suggested by the warnings.

    Tweaks

    These are some minor points that might help in tight inner loops.

    Performance Annotations

    Sometimes you can enable better optimization by promising certain program properties.

    • Use @inbounds to eliminate array bounds checking within expressions. Be certain before doing this. If the subscripts are ever out of bounds, you may suffer crashes or silent corruption.

    • Use @fastmath to allow floating point optimizations that are correct for real numbers, but lead to differences for IEEE numbers. Be careful when doing this, as this may change numerical results. This corresponds to the -ffast-math option of clang.

    • Write @simd in front of for loops that are amenable to vectorization. This feature is experimental and could change or disappear in future versions of Julia.

    Note: While @simd needs to be placed directly in front of a loop, both @inbounds and @fastmath can be applied to several statements at once, e.g. using begin ... end, or even to a whole function.

    Here is an example with both @inbounds and @simd markup:

    function inner(x, y)
    -    s = zero(eltype(x))
    -    for i=1:length(x)
    -        @inbounds s += x[i]*y[i]
    -    end
    -    s
    -end
    -
    -function innersimd(x, y)
    -    s = zero(eltype(x))
    -    @simd for i=1:length(x)
    -        @inbounds s += x[i]*y[i]
    -    end
    -    s
    -end
    -
    -function timeit(n, reps)
    -    x = rand(Float32,n)
    -    y = rand(Float32,n)
    -    s = zero(Float64)
    -    time = @elapsed for j in 1:reps
    -        s+=inner(x,y)
    -    end
    -    println("GFlop/sec        = ",2.0*n*reps/time*1E-9)
    -    time = @elapsed for j in 1:reps
    -        s+=innersimd(x,y)
    -    end
    -    println("GFlop/sec (SIMD) = ",2.0*n*reps/time*1E-9)
    -end
    -
    -timeit(1000,1000)

    On a computer with a 2.4GHz Intel Core i5 processor, this produces:

    GFlop/sec        = 1.9467069505224963
    -GFlop/sec (SIMD) = 17.578554163920018

    (GFlop/sec measures the performance, and larger numbers are better.) The range for a @simd for loop should be a one-dimensional range. A variable used for accumulating, such as s in the example, is called a reduction variable. By using @simd, you are asserting several properties of the loop:

    • It is safe to execute iterations in arbitrary or overlapping order, with special consideration for reduction variables.

    • Floating-point operations on reduction variables can be reordered, possibly causing different results than without @simd.

    • No iteration ever waits on another iteration to make forward progress.

    A loop containing break, continue, or @goto will cause a compile-time error.

    Using @simd merely gives the compiler license to vectorize. Whether it actually does so depends on the compiler. To actually benefit from the current implementation, your loop should have the following additional properties:

    • The loop must be an innermost loop.

    • The loop body must be straight-line code. This is why @inbounds is currently needed for all array accesses. The compiler can sometimes turn short &&, ||, and ?: expressions into straight-line code, if it is safe to evaluate all operands unconditionally. Consider using ifelse() instead of ?: in the loop if it is safe to do so.

    • Accesses must have a stride pattern and cannot be "gathers" (random-index reads) or "scatters" (random-index writes).

    • The stride should be unit stride.

    • In some simple cases, for example with 2-3 arrays accessed in a loop, the LLVM auto-vectorization may kick in automatically, leading to no further speedup with @simd.

    Here is an example with all three kinds of markup. This program first calculates the finite difference of a one-dimensional array, and then evaluates the L2-norm of the result:

    function init!(u)
    -    n = length(u)
    -    dx = 1.0 / (n-1)
    -    @fastmath @inbounds @simd for i in 1:n
    -        u[i] = sin(2pi*dx*i)
    -    end
    -end
    -
    -function deriv!(u, du)
    -    n = length(u)
    -    dx = 1.0 / (n-1)
    -    @fastmath @inbounds du[1] = (u[2] - u[1]) / dx
    -    @fastmath @inbounds @simd for i in 2:n-1
    -        du[i] = (u[i+1] - u[i-1]) / (2*dx)
    -    end
    -    @fastmath @inbounds du[n] = (u[n] - u[n-1]) / dx
    -end
    -
    -function norm(u)
    -    n = length(u)
    -    T = eltype(u)
    -    s = zero(T)
    -    @fastmath @inbounds @simd for i in 1:n
    -        s += u[i]^2
    -    end
    -    @fastmath @inbounds return sqrt(s/n)
    -end
    -
    -function main()
    -    n = 2000
    -    u = Array{Float64}(n)
    -    init!(u)
    -    du = similar(u)
    -
    -    deriv!(u, du)
    -    nu = norm(du)
    -
    -    @time for i in 1:10^6
    -        deriv!(u, du)
    -        nu = norm(du)
    -    end
    -
    -    println(nu)
    -end
    -
    -main()

    On a computer with a 2.7 GHz Intel Core i7 processor, this produces:

    $ julia wave.jl;
    -elapsed time: 1.207814709 seconds (0 bytes allocated)
    -
    -$ julia --math-mode=ieee wave.jl;
    -elapsed time: 4.487083643 seconds (0 bytes allocated)

    Here, the option --math-mode=ieee disables the @fastmath macro, so that we can compare results.

    In this case, the speedup due to @fastmath is a factor of about 3.7. This is unusually large – in general, the speedup will be smaller. (In this particular example, the working set of the benchmark is small enough to fit into the L1 cache of the processor, so that memory access latency does not play a role, and computing time is dominated by CPU usage. In many real world programs this is not the case.) Also, in this case this optimization does not change the result – in general, the result will be slightly different. In some cases, especially for numerically unstable algorithms, the result can be very different.

    The annotation @fastmath re-arranges floating point expressions, e.g. changing the order of evaluation, or assuming that certain special cases (inf, nan) cannot occur. In this case (and on this particular computer), the main difference is that the expression 1 / (2*dx) in the function deriv is hoisted out of the loop (i.e. calculated outside the loop), as if one had written idx = 1 / (2*dx). In the loop, the expression ... / (2*dx) then becomes ... * idx, which is much faster to evaluate. Of course, both the actual optimization that is applied by the compiler as well as the resulting speedup depend very much on the hardware. You can examine the change in generated code by using Julia's code_native() function.

    Treat Subnormal Numbers as Zeros

    Subnormal numbers, formerly called denormal numbers, are useful in many contexts, but incur a performance penalty on some hardware. A call set_zero_subnormals(true) grants permission for floating-point operations to treat subnormal inputs or outputs as zeros, which may improve performance on some hardware. A call set_zero_subnormals(false) enforces strict IEEE behavior for subnormal numbers.

    Below is an example where subnormals noticeably impact performance on some hardware:

    function timestep(b::Vector{T}, a::Vector{T}, Δt::T) where T
    -    @assert length(a)==length(b)
    -    n = length(b)
    -    b[1] = 1                            # Boundary condition
    -    for i=2:n-1
    -        b[i] = a[i] + (a[i-1] - T(2)*a[i] + a[i+1]) * Δt
    -    end
    -    b[n] = 0                            # Boundary condition
    -end
    -
    -function heatflow(a::Vector{T}, nstep::Integer) where T
    -    b = similar(a)
    -    for t=1:div(nstep,2)                # Assume nstep is even
    -        timestep(b,a,T(0.1))
    -        timestep(a,b,T(0.1))
    -    end
    -end
    -
    -heatflow(zeros(Float32,10),2)           # Force compilation
    -for trial=1:6
    -    a = zeros(Float32,1000)
    -    set_zero_subnormals(iseven(trial))  # Odd trials use strict IEEE arithmetic
    -    @time heatflow(a,1000)
    -end

    This example generates many subnormal numbers because the values in a become an exponentially decreasing curve, which slowly flattens out over time.

    Treating subnormals as zeros should be used with caution, because doing so breaks some identities, such as x-y == 0 implies x == y:

    julia> x = 3f-38; y = 2f-38;
    -
    -julia> set_zero_subnormals(true); (x - y, x == y)
    -(0.0f0, false)
    -
    -julia> set_zero_subnormals(false); (x - y, x == y)
    -(1.0000001f-38, false)

    In some applications, an alternative to zeroing subnormal numbers is to inject a tiny bit of noise. For example, instead of initializing a with zeros, initialize it with:

    a = rand(Float32,1000) * 1.f-9

    @code_warntype

    The macro @code_warntype (or its function variant code_warntype()) can sometimes be helpful in diagnosing type-related problems. Here's an example:

    pos(x) = x < 0 ? 0 : x
    -
    -function f(x)
    -    y = pos(x)
    -    sin(y*x+1)
    -end
    -
    -julia> @code_warntype f(3.2)
    -Variables:
    -  #self#::#f
    -  x::Float64
    -  y::UNION{FLOAT64,INT64}
    -  fy::Float64
    -  #temp#@_5::UNION{FLOAT64,INT64}
    -  #temp#@_6::Core.MethodInstance
    -  #temp#@_7::Float64
    -
    -Body:
    -  begin
    -      $(Expr(:inbounds, false))
    -      # meta: location REPL[1] pos 1
    -      # meta: location float.jl < 487
    -      fy::Float64 = (Core.typeassert)((Base.sitofp)(Float64,0)::Float64,Float64)::Float64
    -      # meta: pop location
    -      unless (Base.or_int)((Base.lt_float)(x::Float64,fy::Float64)::Bool,(Base.and_int)((Base.and_int)((Base.eq_float)(x::Float64,fy::Float64)::Bool,(Base.lt_float)(fy::Float64,9.223372036854776e18)::Bool)::Bool,(Base.slt_int)((Base.fptosi)(Int64,fy::Float64)::Int64,0)::Bool)::Bool)::Bool goto 9
    -      #temp#@_5::UNION{FLOAT64,INT64} = 0
    -      goto 11
    -      9:
    -      #temp#@_5::UNION{FLOAT64,INT64} = x::Float64
    -      11:
    -      # meta: pop location
    -      $(Expr(:inbounds, :pop))
    -      y::UNION{FLOAT64,INT64} = #temp#@_5::UNION{FLOAT64,INT64} # line 3:
    -      unless (y::UNION{FLOAT64,INT64} isa Int64)::ANY goto 19
    -      #temp#@_6::Core.MethodInstance = MethodInstance for *(::Int64, ::Float64)
    -      goto 28
    -      19:
    -      unless (y::UNION{FLOAT64,INT64} isa Float64)::ANY goto 23
    -      #temp#@_6::Core.MethodInstance = MethodInstance for *(::Float64, ::Float64)
    -      goto 28
    -      23:
    -      goto 25
    -      25:
    -      #temp#@_7::Float64 = (y::UNION{FLOAT64,INT64} * x::Float64)::Float64
    -      goto 30
    -      28:
    -      #temp#@_7::Float64 = $(Expr(:invoke, :(#temp#@_6), :(Main.*), :(y), :(x)))
    -      30:
    -      return $(Expr(:invoke, MethodInstance for sin(::Float64), :(Main.sin), :((Base.add_float)(#temp#@_7,(Base.sitofp)(Float64,1)::Float64)::Float64)))
    -  end::Float64

    Interpreting the output of @code_warntype, like that of its cousins @code_lowered, @code_typed, @code_llvm, and @code_native, takes a little practice. Your code is being presented in form that has been partially digested on its way to generating compiled machine code. Most of the expressions are annotated by a type, indicated by the ::T (where T might be Float64, for example). The most important characteristic of @code_warntype is that non-concrete types are displayed in red; in the above example, such output is shown in all-caps.

    The top part of the output summarizes the type information for the different variables internal to the function. You can see that y, one of the variables you created, is a Union{Int64,Float64}, due to the type-instability of pos. There is another variable, _var4, which you can see also has the same type.

    The next lines represent the body of f. The lines starting with a number followed by a colon (1:, 2:) are labels, and represent targets for jumps (via goto) in your code. Looking at the body, you can see that pos has been inlined into f–everything before 2: comes from code defined in pos.

    Starting at 2:, the variable y is defined, and again annotated as a Union type. Next, we see that the compiler created the temporary variable _var1 to hold the result of y*x. Because a Float64 times either an Int64 or Float64 yields a Float64, all type-instability ends here. The net result is that f(x::Float64) will not be type-unstable in its output, even if some of the intermediate computations are type-unstable.

    How you use this information is up to you. Obviously, it would be far and away best to fix pos to be type-stable: if you did so, all of the variables in f would be concrete, and its performance would be optimal. However, there are circumstances where this kind of ephemeral type instability might not matter too much: for example, if pos is never used in isolation, the fact that f's output is type-stable (for Float64 inputs) will shield later code from the propagating effects of type instability. This is particularly relevant in cases where fixing the type instability is difficult or impossible: for example, currently it's not possible to infer the return type of an anonymous function. In such cases, the tips above (e.g., adding type annotations and/or breaking up functions) are your best tools to contain the "damage" from type instability.

    The following examples may help you interpret expressions marked as containing non-leaf types:

    • Function body ending in end::Union{T1,T2})

      • Interpretation: function with unstable return type

      • Suggestion: make the return value type-stable, even if you have to annotate it

    • f(x::T)::Union{T1,T2}

      • Interpretation: call to a type-unstable function

      • Suggestion: fix the function, or if necessary annotate the return value

    • (top(arrayref))(A::Array{Any,1},1)::Any

      • Interpretation: accessing elements of poorly-typed arrays

      • Suggestion: use arrays with better-defined types, or if necessary annotate the type of individual element accesses

    • (top(getfield))(A::ArrayContainer{Float64},:data)::Array{Float64,N}

      • Interpretation: getting a field that is of non-leaf type. In this case, ArrayContainer had a field data::Array{T}. But Array needs the dimension N, too, to be a concrete type.

      • Suggestion: use concrete types like Array{T,3} or Array{T,N}, where N is now a parameter of ArrayContainer

    diff --git a/julia-0.6.3/share/doc/julia/html/en/manual/profile.html b/julia-0.6.3/share/doc/julia/html/en/manual/profile.html deleted file mode 100644 index f3dd683..0000000 --- a/julia-0.6.3/share/doc/julia/html/en/manual/profile.html +++ /dev/null @@ -1,71 +0,0 @@ - -Profiling · The Julia Language

    Profiling

    Profiling

    The Profile module provides tools to help developers improve the performance of their code. When used, it takes measurements on running code, and produces output that helps you understand how much time is spent on individual line(s). The most common usage is to identify "bottlenecks" as targets for optimization.

    Profile implements what is known as a "sampling" or statistical profiler. It works by periodically taking a backtrace during the execution of any task. Each backtrace captures the currently-running function and line number, plus the complete chain of function calls that led to this line, and hence is a "snapshot" of the current state of execution.

    If much of your run time is spent executing a particular line of code, this line will show up frequently in the set of all backtraces. In other words, the "cost" of a given line–or really, the cost of the sequence of function calls up to and including this line–is proportional to how often it appears in the set of all backtraces.

    A sampling profiler does not provide complete line-by-line coverage, because the backtraces occur at intervals (by default, 1 ms on Unix systems and 10 ms on Windows, although the actual scheduling is subject to operating system load). Moreover, as discussed further below, because samples are collected at a sparse subset of all execution points, the data collected by a sampling profiler is subject to statistical noise.

    Despite these limitations, sampling profilers have substantial strengths:

    • You do not have to make any modifications to your code to take timing measurements (in contrast to the alternative instrumenting profiler).

    • It can profile into Julia's core code and even (optionally) into C and Fortran libraries.

    • By running "infrequently" there is very little performance overhead; while profiling, your code can run at nearly native speed.

    For these reasons, it's recommended that you try using the built-in sampling profiler before considering any alternatives.

    Basic usage

    Let's work with a simple test case:

    julia> function myfunc()
    -           A = rand(200, 200, 400)
    -           maximum(A)
    -       end

    It's a good idea to first run the code you intend to profile at least once (unless you want to profile Julia's JIT-compiler):

    julia> myfunc() # run once to force compilation

    Now we're ready to profile this function:

    julia> @profile myfunc()

    To see the profiling results, there is a graphical browser available, but here we'll use the text-based display that comes with the standard library:

    julia> Profile.print()
    -80 ./event.jl:73; (::Base.REPL.##1#2{Base.REPL.REPLBackend})()
    - 80 ./REPL.jl:97; macro expansion
    -  80 ./REPL.jl:66; eval_user_input(::Any, ::Base.REPL.REPLBackend)
    -   80 ./boot.jl:235; eval(::Module, ::Any)
    -    80 ./<missing>:?; anonymous
    -     80 ./profile.jl:23; macro expansion
    -      52 ./REPL[1]:2; myfunc()
    -       38 ./random.jl:431; rand!(::MersenneTwister, ::Array{Float64,3}, ::Int64, ::Type{B...
    -        38 ./dSFMT.jl:84; dsfmt_fill_array_close_open!(::Base.dSFMT.DSFMT_state, ::Ptr{F...
    -       14 ./random.jl:278; rand
    -        14 ./random.jl:277; rand
    -         14 ./random.jl:366; rand
    -          14 ./random.jl:369; rand
    -      28 ./REPL[1]:3; myfunc()
    -       28 ./reduce.jl:270; _mapreduce(::Base.#identity, ::Base.#scalarmax, ::IndexLinear,...
    -        3  ./reduce.jl:426; mapreduce_impl(::Base.#identity, ::Base.#scalarmax, ::Array{F...
    -        25 ./reduce.jl:428; mapreduce_impl(::Base.#identity, ::Base.#scalarmax, ::Array{F...

    Each line of this display represents a particular spot (line number) in the code. Indentation is used to indicate the nested sequence of function calls, with more-indented lines being deeper in the sequence of calls. In each line, the first "field" is the number of backtraces (samples) taken at this line or in any functions executed by this line. The second field is the file name and line number and the third field is the function name. Note that the specific line numbers may change as Julia's code changes; if you want to follow along, it's best to run this example yourself.

    In this example, we can see that the top level function called is in the file event.jl. This is the function that runs the REPL when you launch Julia. If you examine line 97 of REPL.jl, you'll see this is where the function eval_user_input() is called. This is the function that evaluates what you type at the REPL, and since we're working interactively these functions were invoked when we entered @profile myfunc(). The next line reflects actions taken in the @profile macro.

    The first line shows that 80 backtraces were taken at line 73 of event.jl, but it's not that this line was "expensive" on its own: the third line reveals that all 80 of these backtraces were actually triggered inside its call to eval_user_input, and so on. To find out which operations are actually taking the time, we need to look deeper in the call chain.

    The first "important" line in this output is this one:

    52 ./REPL[1]:2; myfunc()

    REPL refers to the fact that we defined myfunc in the REPL, rather than putting it in a file; if we had used a file, this would show the file name. The [1] shows that the function myfunc was the first expression evaluated in this REPL session. Line 2 of myfunc() contains the call to rand, and there were 52 (out of 80) backtraces that occurred at this line. Below that, you can see a call to dsfmt_fill_array_close_open! inside dSFMT.jl.

    A little further down, you see:

    28 ./REPL[1]:3; myfunc()

    Line 3 of myfunc contains the call to maximum, and there were 28 (out of 80) backtraces taken here. Below that, you can see the specific places in base/reduce.jl that carry out the time-consuming operations in the maximum function for this type of input data.

    Overall, we can tentatively conclude that generating the random numbers is approximately twice as expensive as finding the maximum element. We could increase our confidence in this result by collecting more samples:

    julia> @profile (for i = 1:100; myfunc(); end)
    -
    -julia> Profile.print()
    -[....]
    - 3821 ./REPL[1]:2; myfunc()
    -  3511 ./random.jl:431; rand!(::MersenneTwister, ::Array{Float64,3}, ::Int64, ::Type...
    -   3511 ./dSFMT.jl:84; dsfmt_fill_array_close_open!(::Base.dSFMT.DSFMT_state, ::Ptr...
    -  310  ./random.jl:278; rand
    -   [....]
    - 2893 ./REPL[1]:3; myfunc()
    -  2893 ./reduce.jl:270; _mapreduce(::Base.#identity, ::Base.#scalarmax, ::IndexLinea...
    -   [....]

    In general, if you have N samples collected at a line, you can expect an uncertainty on the order of sqrt(N) (barring other sources of noise, like how busy the computer is with other tasks). The major exception to this rule is garbage collection, which runs infrequently but tends to be quite expensive. (Since Julia's garbage collector is written in C, such events can be detected using the C=true output mode described below, or by using ProfileView.jl.)

    This illustrates the default "tree" dump; an alternative is the "flat" dump, which accumulates counts independent of their nesting:

    julia> Profile.print(format=:flat)
    - Count File          Line Function
    -  6714 ./<missing>     -1 anonymous
    -  6714 ./REPL.jl       66 eval_user_input(::Any, ::Base.REPL.REPLBackend)
    -  6714 ./REPL.jl       97 macro expansion
    -  3821 ./REPL[1]        2 myfunc()
    -  2893 ./REPL[1]        3 myfunc()
    -  6714 ./REPL[7]        1 macro expansion
    -  6714 ./boot.jl      235 eval(::Module, ::Any)
    -  3511 ./dSFMT.jl      84 dsfmt_fill_array_close_open!(::Base.dSFMT.DSFMT_s...
    -  6714 ./event.jl      73 (::Base.REPL.##1#2{Base.REPL.REPLBackend})()
    -  6714 ./profile.jl    23 macro expansion
    -  3511 ./random.jl    431 rand!(::MersenneTwister, ::Array{Float64,3}, ::In...
    -   310 ./random.jl    277 rand
    -   310 ./random.jl    278 rand
    -   310 ./random.jl    366 rand
    -   310 ./random.jl    369 rand
    -  2893 ./reduce.jl    270 _mapreduce(::Base.#identity, ::Base.#scalarmax, :...
    -     5 ./reduce.jl    420 mapreduce_impl(::Base.#identity, ::Base.#scalarma...
    -   253 ./reduce.jl    426 mapreduce_impl(::Base.#identity, ::Base.#scalarma...
    -  2592 ./reduce.jl    428 mapreduce_impl(::Base.#identity, ::Base.#scalarma...
    -    43 ./reduce.jl    429 mapreduce_impl(::Base.#identity, ::Base.#scalarma...

    If your code has recursion, one potentially-confusing point is that a line in a "child" function can accumulate more counts than there are total backtraces. Consider the following function definitions:

    dumbsum(n::Integer) = n == 1 ? 1 : 1 + dumbsum(n-1)
    -dumbsum3() = dumbsum(3)

    If you were to profile dumbsum3, and a backtrace was taken while it was executing dumbsum(1), the backtrace would look like this:

    dumbsum3
    -    dumbsum(3)
    -        dumbsum(2)
    -            dumbsum(1)

    Consequently, this child function gets 3 counts, even though the parent only gets one. The "tree" representation makes this much clearer, and for this reason (among others) is probably the most useful way to view the results.

    Accumulation and clearing

    Results from @profile accumulate in a buffer; if you run multiple pieces of code under @profile, then Profile.print() will show you the combined results. This can be very useful, but sometimes you want to start fresh; you can do so with Profile.clear().

    Options for controlling the display of profile results

    Profile.print() has more options than we've described so far. Let's see the full declaration:

    function print(io::IO = STDOUT, data = fetch(); kwargs...)

    Let's first discuss the two positional arguments, and later the keyword arguments:

    • io – Allows you to save the results to a buffer, e.g. a file, but the default is to print to STDOUT (the console).

    • data – Contains the data you want to analyze; by default that is obtained from Profile.fetch(), which pulls out the backtraces from a pre-allocated buffer. For example, if you want to profile the profiler, you could say:

      data = copy(Profile.fetch())
      -Profile.clear()
      -@profile Profile.print(STDOUT, data) # Prints the previous results
      -Profile.print()                      # Prints results from Profile.print()

    The keyword arguments can be any combination of:

    • format – Introduced above, determines whether backtraces are printed with (default, :tree) or without (:flat) indentation indicating tree structure.

    • C – If true, backtraces from C and Fortran code are shown (normally they are excluded). Try running the introductory example with Profile.print(C = true). This can be extremely helpful in deciding whether it's Julia code or C code that is causing a bottleneck; setting C = true also improves the interpretability of the nesting, at the cost of longer profile dumps.

    • combine – Some lines of code contain multiple operations; for example, s += A[i] contains both an array reference (A[i]) and a sum operation. These correspond to different lines in the generated machine code, and hence there may be two or more different addresses captured during backtraces on this line. combine = true lumps them together, and is probably what you typically want, but you can generate an output separately for each unique instruction pointer with combine = false.

    • maxdepth – Limits frames at a depth higher than maxdepth in the :tree format.

    • sortedby – Controls the order in :flat format. :filefuncline (default) sorts by the source line, whereas :count sorts in order of number of collected samples.

    • noisefloor – Limits frames that are below the heuristic noise floor of the sample (only applies to format :tree). A suggested value to try for this is 2.0 (the default is 0). This parameter hides samples for which n <= noisefloor * √N, where n is the number of samples on this line, and N is the number of samples for the callee.

    • mincount – Limits frames with less than mincount occurrences.

    File/function names are sometimes truncated (with ...), and indentation is truncated with a +n at the beginning, where n is the number of extra spaces that would have been inserted, had there been room. If you want a complete profile of deeply-nested code, often a good idea is to save to a file using a wide displaysize in an IOContext:

    open("/tmp/prof.txt", "w") do s
    -    Profile.print(IOContext(s, :displaysize => (24, 500)))
    -end

    Configuration

    @profile just accumulates backtraces, and the analysis happens when you call Profile.print(). For a long-running computation, it's entirely possible that the pre-allocated buffer for storing backtraces will be filled. If that happens, the backtraces stop but your computation continues. As a consequence, you may miss some important profiling data (you will get a warning when that happens).

    You can obtain and configure the relevant parameters this way:

    Profile.init() # returns the current settings
    -Profile.init(n = 10^7, delay = 0.01)

    n is the total number of instruction pointers you can store, with a default value of 10^6. If your typical backtrace is 20 instruction pointers, then you can collect 50000 backtraces, which suggests a statistical uncertainty of less than 1%. This may be good enough for most applications.

    Consequently, you are more likely to need to modify delay, expressed in seconds, which sets the amount of time that Julia gets between snapshots to perform the requested computations. A very long-running job might not need frequent backtraces. The default setting is delay = 0.001. Of course, you can decrease the delay as well as increase it; however, the overhead of profiling grows once the delay becomes similar to the amount of time needed to take a backtrace (~30 microseconds on the author's laptop).

    Memory allocation analysis

    One of the most common techniques to improve performance is to reduce memory allocation. The total amount of allocation can be measured with @time and @allocated, and specific lines triggering allocation can often be inferred from profiling via the cost of garbage collection that these lines incur. However, sometimes it is more efficient to directly measure the amount of memory allocated by each line of code.

    To measure allocation line-by-line, start Julia with the --track-allocation=<setting> command-line option, for which you can choose none (the default, do not measure allocation), user (measure memory allocation everywhere except Julia's core code), or all (measure memory allocation at each line of Julia code). Allocation gets measured for each line of compiled code. When you quit Julia, the cumulative results are written to text files with .mem appended after the file name, residing in the same directory as the source file. Each line lists the total number of bytes allocated. The Coverage package contains some elementary analysis tools, for example to sort the lines in order of number of bytes allocated.

    In interpreting the results, there are a few important details. Under the user setting, the first line of any function directly called from the REPL will exhibit allocation due to events that happen in the REPL code itself. More significantly, JIT-compilation also adds to allocation counts, because much of Julia's compiler is written in Julia (and compilation usually requires memory allocation). The recommended procedure is to force compilation by executing all the commands you want to analyze, then call Profile.clear_malloc_data() to reset all allocation counters. Finally, execute the desired commands and quit Julia to trigger the generation of the .mem files.

    diff --git a/julia-0.6.3/share/doc/julia/html/en/manual/running-external-programs.html b/julia-0.6.3/share/doc/julia/html/en/manual/running-external-programs.html deleted file mode 100644 index 1648c4e..0000000 --- a/julia-0.6.3/share/doc/julia/html/en/manual/running-external-programs.html +++ /dev/null @@ -1,137 +0,0 @@ - -Running External Programs · The Julia Language

    Running External Programs

    Running External Programs

    Julia borrows backtick notation for commands from the shell, Perl, and Ruby. However, in Julia, writing

    julia> `echo hello`
    -`echo hello`

    differs in several aspects from the behavior in various shells, Perl, or Ruby:

    • Instead of immediately running the command, backticks create a Cmd object to represent the command. You can use this object to connect the command to others via pipes, run it, and read or write to it.

    • When the command is run, Julia does not capture its output unless you specifically arrange for it to. Instead, the output of the command by default goes to STDOUT as it would using libc's system call.

    • The command is never run with a shell. Instead, Julia parses the command syntax directly, appropriately interpolating variables and splitting on words as the shell would, respecting shell quoting syntax. The command is run as julia's immediate child process, using fork and exec calls.

    Here's a simple example of running an external program:

    julia> mycommand = `echo hello`
    -`echo hello`
    -
    -julia> typeof(mycommand)
    -Cmd
    -
    -julia> run(mycommand)
    -hello

    The hello is the output of the echo command, sent to STDOUT. The run method itself returns nothing, and throws an ErrorException if the external command fails to run successfully.

    If you want to read the output of the external command, readstring() can be used instead:

    julia> a = readstring(`echo hello`)
    -"hello\n"
    -
    -julia> chomp(a) == "hello"
    -true

    More generally, you can use open() to read from or write to an external command.

    julia> open(`less`, "w", STDOUT) do io
    -           for i = 1:3
    -               println(io, i)
    -           end
    -       end
    -1
    -2
    -3

    Interpolation

    Suppose you want to do something a bit more complicated and use the name of a file in the variable file as an argument to a command. You can use $ for interpolation much as you would in a string literal (see Strings):

    julia> file = "/etc/passwd"
    -"/etc/passwd"
    -
    -julia> `sort $file`
    -`sort /etc/passwd`

    A common pitfall when running external programs via a shell is that if a file name contains characters that are special to the shell, they may cause undesirable behavior. Suppose, for example, rather than /etc/passwd, we wanted to sort the contents of the file /Volumes/External HD/data.csv. Let's try it:

    julia> file = "/Volumes/External HD/data.csv"
    -"/Volumes/External HD/data.csv"
    -
    -julia> `sort $file`
    -`sort '/Volumes/External HD/data.csv'`

    How did the file name get quoted? Julia knows that file is meant to be interpolated as a single argument, so it quotes the word for you. Actually, that is not quite accurate: the value of file is never interpreted by a shell, so there's no need for actual quoting; the quotes are inserted only for presentation to the user. This will even work if you interpolate a value as part of a shell word:

    julia> path = "/Volumes/External HD"
    -"/Volumes/External HD"
    -
    -julia> name = "data"
    -"data"
    -
    -julia> ext = "csv"
    -"csv"
    -
    -julia> `sort $path/$name.$ext`
    -`sort '/Volumes/External HD/data.csv'`

    As you can see, the space in the path variable is appropriately escaped. But what if you want to interpolate multiple words? In that case, just use an array (or any other iterable container):

    julia> files = ["/etc/passwd","/Volumes/External HD/data.csv"]
    -2-element Array{String,1}:
    - "/etc/passwd"
    - "/Volumes/External HD/data.csv"
    -
    -julia> `grep foo $files`
    -`grep foo /etc/passwd '/Volumes/External HD/data.csv'`

    If you interpolate an array as part of a shell word, Julia emulates the shell's {a,b,c} argument generation:

    julia> names = ["foo","bar","baz"]
    -3-element Array{String,1}:
    - "foo"
    - "bar"
    - "baz"
    -
    -julia> `grep xylophone $names.txt`
    -`grep xylophone foo.txt bar.txt baz.txt`

    Moreover, if you interpolate multiple arrays into the same word, the shell's Cartesian product generation behavior is emulated:

    julia> names = ["foo","bar","baz"]
    -3-element Array{String,1}:
    - "foo"
    - "bar"
    - "baz"
    -
    -julia> exts = ["aux","log"]
    -2-element Array{String,1}:
    - "aux"
    - "log"
    -
    -julia> `rm -f $names.$exts`
    -`rm -f foo.aux foo.log bar.aux bar.log baz.aux baz.log`

    Since you can interpolate literal arrays, you can use this generative functionality without needing to create temporary array objects first:

    julia> `rm -rf $["foo","bar","baz","qux"].$["aux","log","pdf"]`
    -`rm -rf foo.aux foo.log foo.pdf bar.aux bar.log bar.pdf baz.aux baz.log baz.pdf qux.aux qux.log qux.pdf`

    Quoting

    Inevitably, one wants to write commands that aren't quite so simple, and it becomes necessary to use quotes. Here's a simple example of a Perl one-liner at a shell prompt:

    sh$ perl -le '$|=1; for (0..3) { print }'
    -0
    -1
    -2
    -3

    The Perl expression needs to be in single quotes for two reasons: so that spaces don't break the expression into multiple shell words, and so that uses of Perl variables like $| (yes, that's the name of a variable in Perl), don't cause interpolation. In other instances, you may want to use double quotes so that interpolation does occur:

    sh$ first="A"
    -sh$ second="B"
    -sh$ perl -le '$|=1; print for @ARGV' "1: $first" "2: $second"
    -1: A
    -2: B

    In general, the Julia backtick syntax is carefully designed so that you can just cut-and-paste shell commands as is into backticks and they will work: the escaping, quoting, and interpolation behaviors are the same as the shell's. The only difference is that the interpolation is integrated and aware of Julia's notion of what is a single string value, and what is a container for multiple values. Let's try the above two examples in Julia:

    julia> A = `perl -le '$|=1; for (0..3) { print }'`
    -`perl -le '$|=1; for (0..3) { print }'`
    -
    -julia> run(A)
    -0
    -1
    -2
    -3
    -
    -julia> first = "A"; second = "B";
    -
    -julia> B = `perl -le 'print for @ARGV' "1: $first" "2: $second"`
    -`perl -le 'print for @ARGV' '1: A' '2: B'`
    -
    -julia> run(B)
    -1: A
    -2: B

    The results are identical, and Julia's interpolation behavior mimics the shell's with some improvements due to the fact that Julia supports first-class iterable objects while most shells use strings split on spaces for this, which introduces ambiguities. When trying to port shell commands to Julia, try cut and pasting first. Since Julia shows commands to you before running them, you can easily and safely just examine its interpretation without doing any damage.

    Pipelines

    Shell metacharacters, such as |, &, and >, need to be quoted (or escaped) inside of Julia's backticks:

    julia> run(`echo hello '|' sort`)
    -hello | sort
    -
    -julia> run(`echo hello \| sort`)
    -hello | sort

    This expression invokes the echo command with three words as arguments: hello, |, and sort. The result is that a single line is printed: hello | sort. How, then, does one construct a pipeline? Instead of using '|' inside of backticks, one uses pipeline():

    julia> run(pipeline(`echo hello`, `sort`))
    -hello

    This pipes the output of the echo command to the sort command. Of course, this isn't terribly interesting since there's only one line to sort, but we can certainly do much more interesting things:

    julia> run(pipeline(`cut -d: -f3 /etc/passwd`, `sort -n`, `tail -n5`))
    -210
    -211
    -212
    -213
    -214

    This prints the highest five user IDs on a UNIX system. The cut, sort and tail commands are all spawned as immediate children of the current julia process, with no intervening shell process. Julia itself does the work to setup pipes and connect file descriptors that is normally done by the shell. Since Julia does this itself, it retains better control and can do some things that shells cannot.

    Julia can run multiple commands in parallel:

    julia> run(`echo hello` & `echo world`)
    -world
    -hello

    The order of the output here is non-deterministic because the two echo processes are started nearly simultaneously, and race to make the first write to the STDOUT descriptor they share with each other and the julia parent process. Julia lets you pipe the output from both of these processes to another program:

    julia> run(pipeline(`echo world` & `echo hello`, `sort`))
    -hello
    -world

    In terms of UNIX plumbing, what's happening here is that a single UNIX pipe object is created and written to by both echo processes, and the other end of the pipe is read from by the sort command.

    IO redirection can be accomplished by passing keyword arguments stdin, stdout, and stderr to the pipeline function:

    pipeline(`do_work`, stdout=pipeline(`sort`, "out.txt"), stderr="errs.txt")

    Avoiding Deadlock in Pipelines

    When reading and writing to both ends of a pipeline from a single process, it is important to avoid forcing the kernel to buffer all of the data.

    For example, when reading all of the output from a command, call readstring(out), not wait(process), since the former will actively consume all of the data written by the process, whereas the latter will attempt to store the data in the kernel's buffers while waiting for a reader to be connected.

    Another common solution is to separate the reader and writer of the pipeline into separate Tasks:

    writer = @async writeall(process, "data")
    -reader = @async do_compute(readstring(process))
    -wait(process)
    -fetch(reader)

    Complex Example

    The combination of a high-level programming language, a first-class command abstraction, and automatic setup of pipes between processes is a powerful one. To give some sense of the complex pipelines that can be created easily, here are some more sophisticated examples, with apologies for the excessive use of Perl one-liners:

    julia> prefixer(prefix, sleep) = `perl -nle '$|=1; print "'$prefix' ", $_; sleep '$sleep';'`;
    -
    -julia> run(pipeline(`perl -le '$|=1; for(0..9){ print; sleep 1 }'`, prefixer("A",2) & prefixer("B",2)))
    -A 0
    -B 1
    -A 2
    -B 3
    -A 4
    -B 5
    -A 6
    -B 7
    -A 8
    -B 9

    This is a classic example of a single producer feeding two concurrent consumers: one perl process generates lines with the numbers 0 through 9 on them, while two parallel processes consume that output, one prefixing lines with the letter "A", the other with the letter "B". Which consumer gets the first line is non-deterministic, but once that race has been won, the lines are consumed alternately by one process and then the other. (Setting $|=1 in Perl causes each print statement to flush the STDOUT handle, which is necessary for this example to work. Otherwise all the output is buffered and printed to the pipe at once, to be read by just one consumer process.)

    Here is an even more complex multi-stage producer-consumer example:

    julia> run(pipeline(`perl -le '$|=1; for(0..9){ print; sleep 1 }'`,
    -           prefixer("X",3) & prefixer("Y",3) & prefixer("Z",3),
    -           prefixer("A",2) & prefixer("B",2)))
    -A X 0
    -B Y 1
    -A Z 2
    -B X 3
    -A Y 4
    -B Z 5
    -A X 6
    -B Y 7
    -A Z 8
    -B X 9

    This example is similar to the previous one, except there are two stages of consumers, and the stages have different latency so they use a different number of parallel workers, to maintain saturated throughput.

    We strongly encourage you to try all these examples to see how they work.

    diff --git a/julia-0.6.3/share/doc/julia/html/en/manual/stacktraces.html b/julia-0.6.3/share/doc/julia/html/en/manual/stacktraces.html deleted file mode 100644 index cd58f53..0000000 --- a/julia-0.6.3/share/doc/julia/html/en/manual/stacktraces.html +++ /dev/null @@ -1,181 +0,0 @@ - -Stack Traces · The Julia Language

    Stack Traces

    Stack Traces

    The StackTraces module provides simple stack traces that are both human readable and easy to use programmatically.

    Viewing a stack trace

    The primary function used to obtain a stack trace is stacktrace():

    julia> stacktrace()
    -4-element Array{StackFrame,1}:
    - eval(::Module, ::Any) at boot.jl:236
    - eval_user_input(::Any, ::Base.REPL.REPLBackend) at REPL.jl:66
    - macro expansion at REPL.jl:97 [inlined]
    - (::Base.REPL.##1#2{Base.REPL.REPLBackend})() at event.jl:73

    Calling stacktrace() returns a vector of StackFrame s. For ease of use, the alias StackTrace can be used in place of Vector{StackFrame}. (Examples with [...] indicate that output may vary depending on how the code is run.)

    julia> example() = stacktrace()
    -example (generic function with 1 method)
    -
    -julia> example()
    -5-element Array{StackFrame,1}:
    - example() at REPL[1]:1
    - eval(::Module, ::Any) at boot.jl:236
    -[...]
    -
    -julia> @noinline child() = stacktrace()
    -child (generic function with 1 method)
    -
    -julia> @noinline parent() = child()
    -parent (generic function with 1 method)
    -
    -julia> grandparent() = parent()
    -grandparent (generic function with 1 method)
    -
    -julia> grandparent()
    -7-element Array{StackFrame,1}:
    - child() at REPL[3]:1
    - parent() at REPL[4]:1
    - grandparent() at REPL[5]:1
    -[...]

    Note that when calling stacktrace() you'll typically see a frame with eval(...) at boot.jl. When calling stacktrace() from the REPL you'll also have a few extra frames in the stack from REPL.jl, usually looking something like this:

    julia> example() = stacktrace()
    -example (generic function with 1 method)
    -
    -julia> example()
    -5-element Array{StackFrame,1}:
    - example() at REPL[1]:1
    - eval(::Module, ::Any) at boot.jl:236
    - eval_user_input(::Any, ::Base.REPL.REPLBackend) at REPL.jl:66
    - macro expansion at REPL.jl:97 [inlined]
    - (::Base.REPL.##1#2{Base.REPL.REPLBackend})() at event.jl:73

    Extracting useful information

    Each StackFrame contains the function name, file name, line number, lambda info, a flag indicating whether the frame has been inlined, a flag indicating whether it is a C function (by default C functions do not appear in the stack trace), and an integer representation of the pointer returned by backtrace():

    julia> top_frame = stacktrace()[1]
    -eval(::Module, ::Any) at boot.jl:236
    -
    -julia> top_frame.func
    -:eval
    -
    -julia> top_frame.file
    -Symbol("./boot.jl")
    -
    -julia> top_frame.line
    -236
    -
    -julia> top_frame.linfo
    -Nullable{Core.MethodInstance}(MethodInstance for eval(::Module, ::Any))
    -
    -julia> top_frame.inlined
    -false
    -
    -julia> top_frame.from_c
    -false
    julia> top_frame.pointer
    -0x00007f390d152a59

    This makes stack trace information available programmatically for logging, error handling, and more.

    Error handling

    While having easy access to information about the current state of the callstack can be helpful in many places, the most obvious application is in error handling and debugging.

    julia> @noinline bad_function() = undeclared_variable
    -bad_function (generic function with 1 method)
    -
    -julia> @noinline example() = try
    -           bad_function()
    -       catch
    -           stacktrace()
    -       end
    -example (generic function with 1 method)
    -
    -julia> example()
    -5-element Array{StackFrame,1}:
    - example() at REPL[2]:4
    - eval(::Module, ::Any) at boot.jl:236
    -[...]

    You may notice that in the example above the first stack frame points points at line 4, where stacktrace() is called, rather than line 2, where bad_function is called, and bad_function's frame is missing entirely. This is understandable, given that stacktrace() is called from the context of the catch. While in this example it's fairly easy to find the actual source of the error, in complex cases tracking down the source of the error becomes nontrivial.

    This can be remedied by calling catch_stacktrace() instead of stacktrace(). Instead of returning callstack information for the current context, catch_stacktrace() returns stack information for the context of the most recent exception:

    julia> @noinline bad_function() = undeclared_variable
    -bad_function (generic function with 1 method)
    -
    -julia> @noinline example() = try
    -           bad_function()
    -       catch
    -           catch_stacktrace()
    -       end
    -example (generic function with 1 method)
    -
    -julia> example()
    -6-element Array{StackFrame,1}:
    - bad_function() at REPL[1]:1
    - example() at REPL[2]:2
    -[...]

    Notice that the stack trace now indicates the appropriate line number and the missing frame.

    julia> @noinline child() = error("Whoops!")
    -child (generic function with 1 method)
    -
    -julia> @noinline parent() = child()
    -parent (generic function with 1 method)
    -
    -julia> @noinline function grandparent()
    -           try
    -               parent()
    -           catch err
    -               println("ERROR: ", err.msg)
    -               catch_stacktrace()
    -           end
    -       end
    -grandparent (generic function with 1 method)
    -
    -julia> grandparent()
    -ERROR: Whoops!
    -7-element Array{StackFrame,1}:
    - child() at REPL[1]:1
    - parent() at REPL[2]:1
    - grandparent() at REPL[3]:3
    -[...]

    Comparison with backtrace()

    A call to backtrace() returns a vector of Ptr{Void}, which may then be passed into stacktrace() for translation:

    julia> trace = backtrace()
    -21-element Array{Ptr{Void},1}:
    - Ptr{Void} @0x00007f10049d5b2f
    - Ptr{Void} @0x00007f0ffeb4d29c
    - Ptr{Void} @0x00007f0ffeb4d2a9
    - Ptr{Void} @0x00007f1004993fe7
    - Ptr{Void} @0x00007f10049a92be
    - Ptr{Void} @0x00007f10049a823a
    - Ptr{Void} @0x00007f10049a9fb0
    - Ptr{Void} @0x00007f10049aa718
    - Ptr{Void} @0x00007f10049c0d5e
    - Ptr{Void} @0x00007f10049a3286
    - Ptr{Void} @0x00007f0ffe9ba3ba
    - Ptr{Void} @0x00007f0ffe9ba3d0
    - Ptr{Void} @0x00007f1004993fe7
    - Ptr{Void} @0x00007f0ded34583d
    - Ptr{Void} @0x00007f0ded345a87
    - Ptr{Void} @0x00007f1004993fe7
    - Ptr{Void} @0x00007f0ded34308f
    - Ptr{Void} @0x00007f0ded343320
    - Ptr{Void} @0x00007f1004993fe7
    - Ptr{Void} @0x00007f10049aeb67
    - Ptr{Void} @0x0000000000000000
    -
    -julia> stacktrace(trace)
    -5-element Array{StackFrame,1}:
    - backtrace() at error.jl:46
    - eval(::Module, ::Any) at boot.jl:236
    - eval_user_input(::Any, ::Base.REPL.REPLBackend) at REPL.jl:66
    - macro expansion at REPL.jl:97 [inlined]
    - (::Base.REPL.##1#2{Base.REPL.REPLBackend})() at event.jl:73

    Notice that the vector returned by backtrace() had 21 pointers, while the vector returned by stacktrace() only has 5. This is because, by default, stacktrace() removes any lower-level C functions from the stack. If you want to include stack frames from C calls, you can do it like this:

    julia> stacktrace(trace, true)
    -27-element Array{StackFrame,1}:
    - jl_backtrace_from_here at stackwalk.c:103
    - backtrace() at error.jl:46
    - backtrace() at sys.so:?
    - jl_call_method_internal at julia_internal.h:248 [inlined]
    - jl_apply_generic at gf.c:2215
    - do_call at interpreter.c:75
    - eval at interpreter.c:215
    - eval_body at interpreter.c:519
    - jl_interpret_toplevel_thunk at interpreter.c:664
    - jl_toplevel_eval_flex at toplevel.c:592
    - jl_toplevel_eval_in at builtins.c:614
    - eval(::Module, ::Any) at boot.jl:236
    - eval(::Module, ::Any) at sys.so:?
    - jl_call_method_internal at julia_internal.h:248 [inlined]
    - jl_apply_generic at gf.c:2215
    - eval_user_input(::Any, ::Base.REPL.REPLBackend) at REPL.jl:66
    - ip:0x7f1c707f1846
    - jl_call_method_internal at julia_internal.h:248 [inlined]
    - jl_apply_generic at gf.c:2215
    - macro expansion at REPL.jl:97 [inlined]
    - (::Base.REPL.##1#2{Base.REPL.REPLBackend})() at event.jl:73
    - ip:0x7f1c707ea1ef
    - jl_call_method_internal at julia_internal.h:248 [inlined]
    - jl_apply_generic at gf.c:2215
    - jl_apply at julia.h:1411 [inlined]
    - start_task at task.c:261
    - ip:0xffffffffffffffff

    Individual pointers returned by backtrace() can be translated into StackFrame s by passing them into StackTraces.lookup():

    julia> pointer = backtrace()[1];
    -
    -julia> frame = StackTraces.lookup(pointer)
    -1-element Array{StackFrame,1}:
    - jl_backtrace_from_here at stackwalk.c:103
    -
    -julia> println("The top frame is from $(frame[1].func)!")
    -The top frame is from jl_backtrace_from_here!
    diff --git a/julia-0.6.3/share/doc/julia/html/en/manual/strings.html b/julia-0.6.3/share/doc/julia/html/en/manual/strings.html deleted file mode 100644 index a9720a5..0000000 --- a/julia-0.6.3/share/doc/julia/html/en/manual/strings.html +++ /dev/null @@ -1,320 +0,0 @@ - -Strings · The Julia Language

    Strings

    Strings

    Strings are finite sequences of characters. Of course, the real trouble comes when one asks what a character is. The characters that English speakers are familiar with are the letters A, B, C, etc., together with numerals and common punctuation symbols. These characters are standardized together with a mapping to integer values between 0 and 127 by the ASCII standard. There are, of course, many other characters used in non-English languages, including variants of the ASCII characters with accents and other modifications, related scripts such as Cyrillic and Greek, and scripts completely unrelated to ASCII and English, including Arabic, Chinese, Hebrew, Hindi, Japanese, and Korean. The Unicode standard tackles the complexities of what exactly a character is, and is generally accepted as the definitive standard addressing this problem. Depending on your needs, you can either ignore these complexities entirely and just pretend that only ASCII characters exist, or you can write code that can handle any of the characters or encodings that one may encounter when handling non-ASCII text. Julia makes dealing with plain ASCII text simple and efficient, and handling Unicode is as simple and efficient as possible. In particular, you can write C-style string code to process ASCII strings, and they will work as expected, both in terms of performance and semantics. If such code encounters non-ASCII text, it will gracefully fail with a clear error message, rather than silently introducing corrupt results. When this happens, modifying the code to handle non-ASCII data is straightforward.

    There are a few noteworthy high-level features about Julia's strings:

    • The built-in concrete type used for strings (and string literals) in Julia is String. This supports the full range of Unicode characters via the UTF-8 encoding. (A transcode() function is provided to convert to/from other Unicode encodings.)

    • All string types are subtypes of the abstract type AbstractString, and external packages define additional AbstractString subtypes (e.g. for other encodings). If you define a function expecting a string argument, you should declare the type as AbstractString in order to accept any string type.

    • Like C and Java, but unlike most dynamic languages, Julia has a first-class type representing a single character, called Char. This is just a special kind of 32-bit primitive type whose numeric value represents a Unicode code point.

    • As in Java, strings are immutable: the value of an AbstractString object cannot be changed. To construct a different string value, you construct a new string from parts of other strings.

    • Conceptually, a string is a partial function from indices to characters: for some index values, no character value is returned, and instead an exception is thrown. This allows for efficient indexing into strings by the byte index of an encoded representation rather than by a character index, which cannot be implemented both efficiently and simply for variable-width encodings of Unicode strings.

    Characters

    A Char value represents a single character: it is just a 32-bit primitive type with a special literal representation and appropriate arithmetic behaviors, whose numeric value is interpreted as a Unicode code point. Here is how Char values are input and shown:

    julia> 'x'
    -'x': ASCII/Unicode U+0078 (category Ll: Letter, lowercase)
    -
    -julia> typeof(ans)
    -Char

    You can convert a Char to its integer value, i.e. code point, easily:

    julia> Int('x')
    -120
    -
    -julia> typeof(ans)
    -Int64

    On 32-bit architectures, typeof(ans) will be Int32. You can convert an integer value back to a Char just as easily:

    julia> Char(120)
    -'x': ASCII/Unicode U+0078 (category Ll: Letter, lowercase)

    Not all integer values are valid Unicode code points, but for performance, the Char() conversion does not check that every character value is valid. If you want to check that each converted value is a valid code point, use the isvalid() function:

    julia> Char(0x110000)
    -'\U110000': Unicode U+110000 (category Cn: Other, not assigned)
    -
    -julia> isvalid(Char, 0x110000)
    -false

    As of this writing, the valid Unicode code points are U+00 through U+d7ff and U+e000 through U+10ffff. These have not all been assigned intelligible meanings yet, nor are they necessarily interpretable by applications, but all of these values are considered to be valid Unicode characters.

    You can input any Unicode character in single quotes using \u followed by up to four hexadecimal digits or \U followed by up to eight hexadecimal digits (the longest valid value only requires six):

    julia> '\u0'
    -'\0': ASCII/Unicode U+0000 (category Cc: Other, control)
    -
    -julia> '\u78'
    -'x': ASCII/Unicode U+0078 (category Ll: Letter, lowercase)
    -
    -julia> '\u2200'
    -'∀': Unicode U+2200 (category Sm: Symbol, math)
    -
    -julia> '\U10ffff'
    -'\U10ffff': Unicode U+10ffff (category Cn: Other, not assigned)

    Julia uses your system's locale and language settings to determine which characters can be printed as-is and which must be output using the generic, escaped \u or \U input forms. In addition to these Unicode escape forms, all of C's traditional escaped input forms can also be used:

    julia> Int('\0')
    -0
    -
    -julia> Int('\t')
    -9
    -
    -julia> Int('\n')
    -10
    -
    -julia> Int('\e')
    -27
    -
    -julia> Int('\x7f')
    -127
    -
    -julia> Int('\177')
    -127
    -
    -julia> Int('\xff')
    -255

    You can do comparisons and a limited amount of arithmetic with Char values:

    julia> 'A' < 'a'
    -true
    -
    -julia> 'A' <= 'a' <= 'Z'
    -false
    -
    -julia> 'A' <= 'X' <= 'Z'
    -true
    -
    -julia> 'x' - 'a'
    -23
    -
    -julia> 'A' + 1
    -'B': ASCII/Unicode U+0042 (category Lu: Letter, uppercase)

    String Basics

    String literals are delimited by double quotes or triple double quotes:

    julia> str = "Hello, world.\n"
    -"Hello, world.\n"
    -
    -julia> """Contains "quote" characters"""
    -"Contains \"quote\" characters"

    If you want to extract a character from a string, you index into it:

    julia> str[1]
    -'H': ASCII/Unicode U+0048 (category Lu: Letter, uppercase)
    -
    -julia> str[6]
    -',': ASCII/Unicode U+002c (category Po: Punctuation, other)
    -
    -julia> str[end]
    -'\n': ASCII/Unicode U+000a (category Cc: Other, control)

    All indexing in Julia is 1-based: the first element of any integer-indexed object is found at index 1. (As we will see below, this does not necessarily mean that the last element is found at index n, where n is the length of the string.)

    In any indexing expression, the keyword end can be used as a shorthand for the last index (computed by endof(str)). You can perform arithmetic and other operations with end, just like a normal value:

    julia> str[end-1]
    -'.': ASCII/Unicode U+002e (category Po: Punctuation, other)
    -
    -julia> str[end÷2]
    -' ': ASCII/Unicode U+0020 (category Zs: Separator, space)

    Using an index less than 1 or greater than end raises an error:

    julia> str[0]
    -ERROR: BoundsError: attempt to access "Hello, world.\n"
    -  at index [0]
    -[...]
    -
    -julia> str[end+1]
    -ERROR: BoundsError: attempt to access "Hello, world.\n"
    -  at index [15]
    -[...]

    You can also extract a substring using range indexing:

    julia> str[4:9]
    -"lo, wo"

    Notice that the expressions str[k] and str[k:k] do not give the same result:

    julia> str[6]
    -',': ASCII/Unicode U+002c (category Po: Punctuation, other)
    -
    -julia> str[6:6]
    -","

    The former is a single character value of type Char, while the latter is a string value that happens to contain only a single character. In Julia these are very different things.

    Unicode and UTF-8

    Julia fully supports Unicode characters and strings. As discussed above, in character literals, Unicode code points can be represented using Unicode \u and \U escape sequences, as well as all the standard C escape sequences. These can likewise be used to write string literals:

    julia> s = "\u2200 x \u2203 y"
    -"∀ x ∃ y"

    Whether these Unicode characters are displayed as escapes or shown as special characters depends on your terminal's locale settings and its support for Unicode. String literals are encoded using the UTF-8 encoding. UTF-8 is a variable-width encoding, meaning that not all characters are encoded in the same number of bytes. In UTF-8, ASCII characters – i.e. those with code points less than 0x80 (128) – are encoded as they are in ASCII, using a single byte, while code points 0x80 and above are encoded using multiple bytes – up to four per character. This means that not every byte index into a UTF-8 string is necessarily a valid index for a character. If you index into a string at such an invalid byte index, an error is thrown:

    julia> s[1]
    -'∀': Unicode U+2200 (category Sm: Symbol, math)
    -
    -julia> s[2]
    -ERROR: UnicodeError: invalid character index
    -[...]
    -
    -julia> s[3]
    -ERROR: UnicodeError: invalid character index
    -[...]
    -
    -julia> s[4]
    -' ': ASCII/Unicode U+0020 (category Zs: Separator, space)

    In this case, the character is a three-byte character, so the indices 2 and 3 are invalid and the next character's index is 4; this next valid index can be computed by nextind(s,1), and the next index after that by nextind(s,4) and so on.

    Because of variable-length encodings, the number of characters in a string (given by length(s)) is not always the same as the last index. If you iterate through the indices 1 through endof(s) and index into s, the sequence of characters returned when errors aren't thrown is the sequence of characters comprising the string s. Thus we have the identity that length(s) <= endof(s), since each character in a string must have its own index. The following is an inefficient and verbose way to iterate through the characters of s:

    julia> for i = 1:endof(s)
    -           try
    -               println(s[i])
    -           catch
    -               # ignore the index error
    -           end
    -       end
    -∀
    -
    -x
    -
    -∃
    -
    -y

    The blank lines actually have spaces on them. Fortunately, the above awkward idiom is unnecessary for iterating through the characters in a string, since you can just use the string as an iterable object, no exception handling required:

    julia> for c in s
    -           println(c)
    -       end
    -∀
    -
    -x
    -
    -∃
    -
    -y

    Julia uses the UTF-8 encoding by default, and support for new encodings can be added by packages. For example, the LegacyStrings.jl package implements UTF16String and UTF32String types. Additional discussion of other encodings and how to implement support for them is beyond the scope of this document for the time being. For further discussion of UTF-8 encoding issues, see the section below on byte array literals. The transcode() function is provided to convert data between the various UTF-xx encodings, primarily for working with external data and libraries.

    Concatenation

    One of the most common and useful string operations is concatenation:

    julia> greet = "Hello"
    -"Hello"
    -
    -julia> whom = "world"
    -"world"
    -
    -julia> string(greet, ", ", whom, ".\n")
    -"Hello, world.\n"

    Julia also provides * for string concatenation:

    julia> greet * ", " * whom * ".\n"
    -"Hello, world.\n"

    While * may seem like a surprising choice to users of languages that provide + for string concatenation, this use of * has precedent in mathematics, particularly in abstract algebra.

    In mathematics, + usually denotes a commutative operation, where the order of the operands does not matter. An example of this is matrix addition, where A + B == B + A for any matrices A and B that have the same shape. In contrast, * typically denotes a noncommutative operation, where the order of the operands does matter. An example of this is matrix multiplication, where in general A * B != B * A. As with matrix multiplication, string concatenation is noncommutative: greet * whom != whom * greet. As such, * is a more natural choice for an infix string concatenation operator, consistent with common mathematical use.

    More precisely, the set of all finite-length strings S together with the string concatenation operator * forms a free monoid (S, *). The identity element of this set is the empty string, "". Whenever a free monoid is not commutative, the operation is typically represented as \cdot, *, or a similar symbol, rather than +, which as stated usually implies commutativity.

    Interpolation

    Constructing strings using concatenation can become a bit cumbersome, however. To reduce the need for these verbose calls to string() or repeated multiplications, Julia allows interpolation into string literals using $, as in Perl:

    julia> "$greet, $whom.\n"
    -"Hello, world.\n"

    This is more readable and convenient and equivalent to the above string concatenation – the system rewrites this apparent single string literal into a concatenation of string literals with variables.

    The shortest complete expression after the $ is taken as the expression whose value is to be interpolated into the string. Thus, you can interpolate any expression into a string using parentheses:

    julia> "1 + 2 = $(1 + 2)"
    -"1 + 2 = 3"

    Both concatenation and string interpolation call string() to convert objects into string form. Most non-AbstractString objects are converted to strings closely corresponding to how they are entered as literal expressions:

    julia> v = [1,2,3]
    -3-element Array{Int64,1}:
    - 1
    - 2
    - 3
    -
    -julia> "v: $v"
    -"v: [1, 2, 3]"

    string() is the identity for AbstractString and Char values, so these are interpolated into strings as themselves, unquoted and unescaped:

    julia> c = 'x'
    -'x': ASCII/Unicode U+0078 (category Ll: Letter, lowercase)
    -
    -julia> "hi, $c"
    -"hi, x"

    To include a literal $ in a string literal, escape it with a backslash:

    julia> print("I have \$100 in my account.\n")
    -I have $100 in my account.

    Triple-Quoted String Literals

    When strings are created using triple-quotes ("""...""") they have some special behavior that can be useful for creating longer blocks of text. First, if the opening """ is followed by a newline, the newline is stripped from the resulting string.

    """hello"""

    is equivalent to

    """
    -hello"""

    but

    """
    -
    -hello"""

    will contain a literal newline at the beginning. Trailing whitespace is left unaltered. They can contain " symbols without escaping. Triple-quoted strings are also dedented to the level of the least-indented line. This is useful for defining strings within code that is indented. For example:

    julia> str = """
    -           Hello,
    -           world.
    -         """
    -"  Hello,\n  world.\n"

    In this case the final (empty) line before the closing """ sets the indentation level.

    Note that line breaks in literal strings, whether single- or triple-quoted, result in a newline (LF) character \n in the string, even if your editor uses a carriage return \r (CR) or CRLF combination to end lines. To include a CR in a string, use an explicit escape \r; for example, you can enter the literal string "a CRLF line ending\r\n".

    Common Operations

    You can lexicographically compare strings using the standard comparison operators:

    julia> "abracadabra" < "xylophone"
    -true
    -
    -julia> "abracadabra" == "xylophone"
    -false
    -
    -julia> "Hello, world." != "Goodbye, world."
    -true
    -
    -julia> "1 + 2 = 3" == "1 + 2 = $(1 + 2)"
    -true

    You can search for the index of a particular character using the search() function:

    julia> search("xylophone", 'x')
    -1
    -
    -julia> search("xylophone", 'p')
    -5
    -
    -julia> search("xylophone", 'z')
    -0

    You can start the search for a character at a given offset by providing a third argument:

    julia> search("xylophone", 'o')
    -4
    -
    -julia> search("xylophone", 'o', 5)
    -7
    -
    -julia> search("xylophone", 'o', 8)
    -0

    You can use the contains() function to check if a substring is contained in a string:

    julia> contains("Hello, world.", "world")
    -true
    -
    -julia> contains("Xylophon", "o")
    -true
    -
    -julia> contains("Xylophon", "a")
    -false
    -
    -julia> contains("Xylophon", 'o')
    -ERROR: MethodError: no method matching contains(::String, ::Char)
    -Closest candidates are:
    -  contains(!Matched::Function, ::Any, !Matched::Any) at reduce.jl:664
    -  contains(::AbstractString, !Matched::AbstractString) at strings/search.jl:378

    The last error is because 'o' is a character literal, and contains() is a generic function that looks for subsequences. To look for an element in a sequence, you must use in() instead.

    Two other handy string functions are repeat() and join():

    julia> repeat(".:Z:.", 10)
    -".:Z:..:Z:..:Z:..:Z:..:Z:..:Z:..:Z:..:Z:..:Z:..:Z:."
    -
    -julia> join(["apples", "bananas", "pineapples"], ", ", " and ")
    -"apples, bananas and pineapples"

    Some other useful functions include:

    • endof(str) gives the maximal (byte) index that can be used to index into str.

    • length(str) the number of characters in str.

    • i = start(str) gives the first valid index at which a character can be found in str (typically 1).

    • c, j = next(str,i) returns next character at or after the index i and the next valid character index following that. With start() and endof(), can be used to iterate through the characters in str.

    • ind2chr(str,i) gives the number of characters in str up to and including any at index i.

    • chr2ind(str,j) gives the index at which the jth character in str occurs.

    Non-Standard String Literals

    There are situations when you want to construct a string or use string semantics, but the behavior of the standard string construct is not quite what is needed. For these kinds of situations, Julia provides non-standard string literals. A non-standard string literal looks like a regular double-quoted string literal, but is immediately prefixed by an identifier, and doesn't behave quite like a normal string literal. Regular expressions, byte array literals and version number literals, as described below, are some examples of non-standard string literals. Other examples are given in the Metaprogramming section.

    Regular Expressions

    Julia has Perl-compatible regular expressions (regexes), as provided by the PCRE library. Regular expressions are related to strings in two ways: the obvious connection is that regular expressions are used to find regular patterns in strings; the other connection is that regular expressions are themselves input as strings, which are parsed into a state machine that can be used to efficiently search for patterns in strings. In Julia, regular expressions are input using non-standard string literals prefixed with various identifiers beginning with r. The most basic regular expression literal without any options turned on just uses r"...":

    julia> r"^\s*(?:#|$)"
    -r"^\s*(?:#|$)"
    -
    -julia> typeof(ans)
    -Regex

    To check if a regex matches a string, use ismatch():

    julia> ismatch(r"^\s*(?:#|$)", "not a comment")
    -false
    -
    -julia> ismatch(r"^\s*(?:#|$)", "# a comment")
    -true

    As one can see here, ismatch() simply returns true or false, indicating whether the given regex matches the string or not. Commonly, however, one wants to know not just whether a string matched, but also how it matched. To capture this information about a match, use the match() function instead:

    julia> match(r"^\s*(?:#|$)", "not a comment")
    -
    -julia> match(r"^\s*(?:#|$)", "# a comment")
    -RegexMatch("#")

    If the regular expression does not match the given string, match() returns nothing – a special value that does not print anything at the interactive prompt. Other than not printing, it is a completely normal value and you can test for it programmatically:

    m = match(r"^\s*(?:#|$)", line)
    -if m === nothing
    -    println("not a comment")
    -else
    -    println("blank or comment")
    -end

    If a regular expression does match, the value returned by match() is a RegexMatch object. These objects record how the expression matches, including the substring that the pattern matches and any captured substrings, if there are any. This example only captures the portion of the substring that matches, but perhaps we want to capture any non-blank text after the comment character. We could do the following:

    julia> m = match(r"^\s*(?:#\s*(.*?)\s*$|$)", "# a comment ")
    -RegexMatch("# a comment ", 1="a comment")

    When calling match(), you have the option to specify an index at which to start the search. For example:

    julia> m = match(r"[0-9]","aaaa1aaaa2aaaa3",1)
    -RegexMatch("1")
    -
    -julia> m = match(r"[0-9]","aaaa1aaaa2aaaa3",6)
    -RegexMatch("2")
    -
    -julia> m = match(r"[0-9]","aaaa1aaaa2aaaa3",11)
    -RegexMatch("3")

    You can extract the following info from a RegexMatch object:

    • the entire substring matched: m.match

    • the captured substrings as an array of strings: m.captures

    • the offset at which the whole match begins: m.offset

    • the offsets of the captured substrings as a vector: m.offsets

    For when a capture doesn't match, instead of a substring, m.captures contains nothing in that position, and m.offsets has a zero offset (recall that indices in Julia are 1-based, so a zero offset into a string is invalid). Here is a pair of somewhat contrived examples:

    julia> m = match(r"(a|b)(c)?(d)", "acd")
    -RegexMatch("acd", 1="a", 2="c", 3="d")
    -
    -julia> m.match
    -"acd"
    -
    -julia> m.captures
    -3-element Array{Union{SubString{String}, Void},1}:
    - "a"
    - "c"
    - "d"
    -
    -julia> m.offset
    -1
    -
    -julia> m.offsets
    -3-element Array{Int64,1}:
    - 1
    - 2
    - 3
    -
    -julia> m = match(r"(a|b)(c)?(d)", "ad")
    -RegexMatch("ad", 1="a", 2=nothing, 3="d")
    -
    -julia> m.match
    -"ad"
    -
    -julia> m.captures
    -3-element Array{Union{SubString{String}, Void},1}:
    - "a"
    - nothing
    - "d"
    -
    -julia> m.offset
    -1
    -
    -julia> m.offsets
    -3-element Array{Int64,1}:
    - 1
    - 0
    - 2

    It is convenient to have captures returned as an array so that one can use destructuring syntax to bind them to local variables:

    julia> first, second, third = m.captures; first
    -"a"

    Captures can also be accessed by indexing the RegexMatch object with the number or name of the capture group:

    julia> m=match(r"(?<hour>\d+):(?<minute>\d+)","12:45")
    -RegexMatch("12:45", hour="12", minute="45")
    -
    -julia> m[:minute]
    -"45"
    -
    -julia> m[2]
    -"45"

    Captures can be referenced in a substitution string when using replace() by using \n to refer to the nth capture group and prefixing the substitution string with s. Capture group 0 refers to the entire match object. Named capture groups can be referenced in the substitution with g<groupname>. For example:

    julia> replace("first second", r"(\w+) (?<agroup>\w+)", s"\g<agroup> \1")
    -"second first"

    Numbered capture groups can also be referenced as \g<n> for disambiguation, as in:

    julia> replace("a", r".", s"\g<0>1")
    -"a1"

    You can modify the behavior of regular expressions by some combination of the flags i, m, s, and x after the closing double quote mark. These flags have the same meaning as they do in Perl, as explained in this excerpt from the perlre manpage:

    i   Do case-insensitive pattern matching.
    -
    -    If locale matching rules are in effect, the case map is taken
    -    from the current locale for code points less than 255, and
    -    from Unicode rules for larger code points. However, matches
    -    that would cross the Unicode rules/non-Unicode rules boundary
    -    (ords 255/256) will not succeed.
    -
    -m   Treat string as multiple lines.  That is, change "^" and "$"
    -    from matching the start or end of the string to matching the
    -    start or end of any line anywhere within the string.
    -
    -s   Treat string as single line.  That is, change "." to match any
    -    character whatsoever, even a newline, which normally it would
    -    not match.
    -
    -    Used together, as r""ms, they let the "." match any character
    -    whatsoever, while still allowing "^" and "$" to match,
    -    respectively, just after and just before newlines within the
    -    string.
    -
    -x   Tells the regular expression parser to ignore most whitespace
    -    that is neither backslashed nor within a character class. You
    -    can use this to break up your regular expression into
    -    (slightly) more readable parts. The '#' character is also
    -    treated as a metacharacter introducing a comment, just as in
    -    ordinary code.

    For example, the following regex has all three flags turned on:

    julia> r"a+.*b+.*?d$"ism
    -r"a+.*b+.*?d$"ims
    -
    -julia> match(r"a+.*b+.*?d$"ism, "Goodbye,\nOh, angry,\nBad world\n")
    -RegexMatch("angry,\nBad world")

    Triple-quoted regex strings, of the form r"""...""", are also supported (and may be convenient for regular expressions containing quotation marks or newlines).

    Byte Array Literals

    Another useful non-standard string literal is the byte-array string literal: b"...". This form lets you use string notation to express literal byte arrays – i.e. arrays of UInt8 values. The rules for byte array literals are the following:

    • ASCII characters and ASCII escapes produce a single byte.

    • \x and octal escape sequences produce the byte corresponding to the escape value.

    • Unicode escape sequences produce a sequence of bytes encoding that code point in UTF-8.

    There is some overlap between these rules since the behavior of \x and octal escapes less than 0x80 (128) are covered by both of the first two rules, but here these rules agree. Together, these rules allow one to easily use ASCII characters, arbitrary byte values, and UTF-8 sequences to produce arrays of bytes. Here is an example using all three:

    julia> b"DATA\xff\u2200"
    -8-element Array{UInt8,1}:
    - 0x44
    - 0x41
    - 0x54
    - 0x41
    - 0xff
    - 0xe2
    - 0x88
    - 0x80

    The ASCII string "DATA" corresponds to the bytes 68, 65, 84, 65. \xff produces the single byte 255. The Unicode escape \u2200 is encoded in UTF-8 as the three bytes 226, 136, 128. Note that the resulting byte array does not correspond to a valid UTF-8 string – if you try to use this as a regular string literal, you will get a syntax error:

    julia> "DATA\xff\u2200"
    -ERROR: syntax: invalid UTF-8 sequence

    Also observe the significant distinction between \xff and \uff: the former escape sequence encodes the byte 255, whereas the latter escape sequence represents the code point 255, which is encoded as two bytes in UTF-8:

    julia> b"\xff"
    -1-element Array{UInt8,1}:
    - 0xff
    -
    -julia> b"\uff"
    -2-element Array{UInt8,1}:
    - 0xc3
    - 0xbf

    In character literals, this distinction is glossed over and \xff is allowed to represent the code point 255, because characters always represent code points. In strings, however, \x escapes always represent bytes, not code points, whereas \u and \U escapes always represent code points, which are encoded in one or more bytes. For code points less than \u80, it happens that the UTF-8 encoding of each code point is just the single byte produced by the corresponding \x escape, so the distinction can safely be ignored. For the escapes \x80 through \xff as compared to \u80 through \uff, however, there is a major difference: the former escapes all encode single bytes, which – unless followed by very specific continuation bytes – do not form valid UTF-8 data, whereas the latter escapes all represent Unicode code points with two-byte encodings.

    If this is all extremely confusing, try reading "The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets". It's an excellent introduction to Unicode and UTF-8, and may help alleviate some confusion regarding the matter.

    Version Number Literals

    Version numbers can easily be expressed with non-standard string literals of the form v"...". Version number literals create VersionNumber objects which follow the specifications of semantic versioning, and therefore are composed of major, minor and patch numeric values, followed by pre-release and build alpha-numeric annotations. For example, v"0.2.1-rc1+win64" is broken into major version 0, minor version 2, patch version 1, pre-release rc1 and build win64. When entering a version literal, everything except the major version number is optional, therefore e.g. v"0.2" is equivalent to v"0.2.0" (with empty pre-release/build annotations), v"2" is equivalent to v"2.0.0", and so on.

    VersionNumber objects are mostly useful to easily and correctly compare two (or more) versions. For example, the constant VERSION holds Julia version number as a VersionNumber object, and therefore one can define some version-specific behavior using simple statements as:

    if v"0.2" <= VERSION < v"0.3-"
    -    # do something specific to 0.2 release series
    -end

    Note that in the above example the non-standard version number v"0.3-" is used, with a trailing -: this notation is a Julia extension of the standard, and it's used to indicate a version which is lower than any 0.3 release, including all of its pre-releases. So in the above example the code would only run with stable 0.2 versions, and exclude such versions as v"0.3.0-rc1". In order to also allow for unstable (i.e. pre-release) 0.2 versions, the lower bound check should be modified like this: v"0.2-" <= VERSION.

    Another non-standard version specification extension allows one to use a trailing + to express an upper limit on build versions, e.g. VERSION > v"0.2-rc1+" can be used to mean any version above 0.2-rc1 and any of its builds: it will return false for version v"0.2-rc1+win64" and true for v"0.2-rc2".

    It is good practice to use such special versions in comparisons (particularly, the trailing - should always be used on upper bounds unless there's a good reason not to), but they must not be used as the actual version number of anything, as they are invalid in the semantic versioning scheme.

    Besides being used for the VERSION constant, VersionNumber objects are widely used in the Pkg module, to specify packages versions and their dependencies.

    Raw String Literals

    Raw strings without interpolation or unescaping can be expressed with non-standard string literals of the form raw"...". Raw string literals create ordinary String objects which contain the enclosed contents exactly as entered with no interpolation or unescaping. This is useful for strings which contain code or markup in other languages which use $ or \ as special characters. The exception is quotation marks that still must be escaped, e.g. raw"\"" is equivalent to "\"".

    diff --git a/julia-0.6.3/share/doc/julia/html/en/manual/style-guide.html b/julia-0.6.3/share/doc/julia/html/en/manual/style-guide.html deleted file mode 100644 index 8de1d78..0000000 --- a/julia-0.6.3/share/doc/julia/html/en/manual/style-guide.html +++ /dev/null @@ -1,69 +0,0 @@ - -Style Guide · The Julia Language

    Style Guide

    Style Guide

    The following sections explain a few aspects of idiomatic Julia coding style. None of these rules are absolute; they are only suggestions to help familiarize you with the language and to help you choose among alternative designs.

    Write functions, not just scripts

    Writing code as a series of steps at the top level is a quick way to get started solving a problem, but you should try to divide a program into functions as soon as possible. Functions are more reusable and testable, and clarify what steps are being done and what their inputs and outputs are. Furthermore, code inside functions tends to run much faster than top level code, due to how Julia's compiler works.

    It is also worth emphasizing that functions should take arguments, instead of operating directly on global variables (aside from constants like pi).

    Avoid writing overly-specific types

    Code should be as generic as possible. Instead of writing:

    convert(Complex{Float64}, x)

    it's better to use available generic functions:

    complex(float(x))

    The second version will convert x to an appropriate type, instead of always the same type.

    This style point is especially relevant to function arguments. For example, don't declare an argument to be of type Int or Int32 if it really could be any integer, expressed with the abstract type Integer. In fact, in many cases you can omit the argument type altogether, unless it is needed to disambiguate from other method definitions, since a MethodError will be thrown anyway if a type is passed that does not support any of the requisite operations. (This is known as duck typing.)

    For example, consider the following definitions of a function addone that returns one plus its argument:

    addone(x::Int) = x + 1                 # works only for Int
    -addone(x::Integer) = x + oneunit(x)    # any integer type
    -addone(x::Number) = x + oneunit(x)     # any numeric type
    -addone(x) = x + oneunit(x)             # any type supporting + and oneunit

    The last definition of addone handles any type supporting oneunit (which returns 1 in the same type as x, which avoids unwanted type promotion) and the + function with those arguments. The key thing to realize is that there is no performance penalty to defining only the general addone(x) = x + oneunit(x), because Julia will automatically compile specialized versions as needed. For example, the first time you call addone(12), Julia will automatically compile a specialized addone function for x::Int arguments, with the call to oneunit replaced by its inlined value 1. Therefore, the first three definitions of addone above are completely redundant with the fourth definition.

    Handle excess argument diversity in the caller

    Instead of:

    function foo(x, y)
    -    x = Int(x); y = Int(y)
    -    ...
    -end
    -foo(x, y)

    use:

    function foo(x::Int, y::Int)
    -    ...
    -end
    -foo(Int(x), Int(y))

    This is better style because foo does not really accept numbers of all types; it really needs Int s.

    One issue here is that if a function inherently requires integers, it might be better to force the caller to decide how non-integers should be converted (e.g. floor or ceiling). Another issue is that declaring more specific types leaves more "space" for future method definitions.

    Append ! to names of functions that modify their arguments

    Instead of:

    function double(a::AbstractArray{<:Number})
    -    for i = 1:endof(a)
    -        a[i] *= 2
    -    end
    -    return a
    -end

    use:

    function double!(a::AbstractArray{<:Number})
    -    for i = 1:endof(a)
    -        a[i] *= 2
    -    end
    -    return a
    -end

    The Julia standard library uses this convention throughout and contains examples of functions with both copying and modifying forms (e.g., sort() and sort!()), and others which are just modifying (e.g., push!(), pop!(), splice!()). It is typical for such functions to also return the modified array for convenience.

    Avoid strange type Unions

    Types such as Union{Function,AbstractString} are often a sign that some design could be cleaner.

    Avoid type Unions in fields

    When creating a type such as:

    mutable struct MyType
    -    ...
    -    x::Union{Void,T}
    -end

    ask whether the option for x to be nothing (of type Void) is really necessary. Here are some alternatives to consider:

    • Find a safe default value to initialize x with

    • Introduce another type that lacks x

    • If there are many fields like x, store them in a dictionary

    • Determine whether there is a simple rule for when x is nothing. For example, often the field will start as nothing but get initialized at some well-defined point. In that case, consider leaving it undefined at first.

    • If x really needs to hold no value at some times, define it as ::Nullable{T} instead, as this guarantees type-stability in the code accessing this field (see Nullable types).

    Avoid elaborate container types

    It is usually not much help to construct arrays like the following:

    a = Array{Union{Int,AbstractString,Tuple,Array}}(n)

    In this case Array{Any}(n) is better. It is also more helpful to the compiler to annotate specific uses (e.g. a[i]::Int) than to try to pack many alternatives into one type.

    Use naming conventions consistent with Julia's base/

    • modules and type names use capitalization and camel case: module SparseArrays, struct UnitRange.

    • functions are lowercase (maximum(), convert()) and, when readable, with multiple words squashed together (isequal(), haskey()). When necessary, use underscores as word separators. Underscores are also used to indicate a combination of concepts (remotecall_fetch() as a more efficient implementation of fetch(remotecall(...))) or as modifiers (sum_kbn()).

    • conciseness is valued, but avoid abbreviation (indexin() rather than indxin()) as it becomes difficult to remember whether and how particular words are abbreviated.

    If a function name requires multiple words, consider whether it might represent more than one concept and might be better split into pieces.

    Don't overuse try-catch

    It is better to avoid errors than to rely on catching them.

    Don't parenthesize conditions

    Julia doesn't require parens around conditions in if and while. Write:

    if a == b

    instead of:

    if (a == b)

    Don't overuse ...

    Splicing function arguments can be addictive. Instead of [a..., b...], use simply [a; b], which already concatenates arrays. collect(a) is better than [a...], but since a is already iterable it is often even better to leave it alone, and not convert it to an array.

    Don't use unnecessary static parameters

    A function signature:

    foo(x::T) where {T<:Real} = ...

    should be written as:

    foo(x::Real) = ...

    instead, especially if T is not used in the function body. Even if T is used, it can be replaced with typeof(x) if convenient. There is no performance difference. Note that this is not a general caution against static parameters, just against uses where they are not needed.

    Note also that container types, specifically may need type parameters in function calls. See the FAQ Avoid fields with abstract containers for more information.

    Avoid confusion about whether something is an instance or a type

    Sets of definitions like the following are confusing:

    foo(::Type{MyType}) = ...
    -foo(::MyType) = foo(MyType)

    Decide whether the concept in question will be written as MyType or MyType(), and stick to it.

    The preferred style is to use instances by default, and only add methods involving Type{MyType} later if they become necessary to solve some problem.

    If a type is effectively an enumeration, it should be defined as a single (ideally immutable struct or primitive) type, with the enumeration values being instances of it. Constructors and conversions can check whether values are valid. This design is preferred over making the enumeration an abstract type, with the "values" as subtypes.

    Don't overuse macros

    Be aware of when a macro could really be a function instead.

    Calling eval() inside a macro is a particularly dangerous warning sign; it means the macro will only work when called at the top level. If such a macro is written as a function instead, it will naturally have access to the run-time values it needs.

    Don't expose unsafe operations at the interface level

    If you have a type that uses a native pointer:

    mutable struct NativeType
    -    p::Ptr{UInt8}
    -    ...
    -end

    don't write definitions like the following:

    getindex(x::NativeType, i) = unsafe_load(x.p, i)

    The problem is that users of this type can write x[i] without realizing that the operation is unsafe, and then be susceptible to memory bugs.

    Such a function should either check the operation to ensure it is safe, or have unsafe somewhere in its name to alert callers.

    Don't overload methods of base container types

    It is possible to write definitions like the following:

    show(io::IO, v::Vector{MyType}) = ...

    This would provide custom showing of vectors with a specific new element type. While tempting, this should be avoided. The trouble is that users will expect a well-known type like Vector() to behave in a certain way, and overly customizing its behavior can make it harder to work with.

    Avoid type piracy

    "Type piracy" refers to the practice of extending or redefining methods in Base or other packages on types that you have not defined. In some cases, you can get away with type piracy with little ill effect. In extreme cases, however, you can even crash Julia (e.g. if your method extension or redefinition causes invalid input to be passed to a ccall). Type piracy can complicate reasoning about code, and may introduce incompatibilities that are hard to predict and diagnose.

    As an example, suppose you wanted to define multiplication on symbols in a module:

    module A
    -import Base.*
    -*(x::Symbol, y::Symbol) = Symbol(x,y)
    -end

    The problem is that now any other module that uses Base.* will also see this definition. Since Symbol is defined in Base and is used by other modules, this can change the behavior of unrelated code unexpectedly. There are several alternatives here, including using a different function name, or wrapping the Symbols in another type that you define.

    Sometimes, coupled packages may engage in type piracy to separate features from definitions, especially when the packages were designed by collaborating authors, and when the definitions are reusable. For example, one package might provide some types useful for working with colors; another package could define methods for those types that enable conversions between color spaces. Another example might be a package that acts as a thin wrapper for some C code, which another package might then pirate to implement a higher-level, Julia-friendly API.

    Be careful with type equality

    You generally want to use isa() and <: (issubtype()) for testing types, not ==. Checking types for exact equality typically only makes sense when comparing to a known concrete type (e.g. T == Float64), or if you really, really know what you're doing.

    Do not write x->f(x)

    Since higher-order functions are often called with anonymous functions, it is easy to conclude that this is desirable or even necessary. But any function can be passed directly, without being "wrapped" in an anonymous function. Instead of writing map(x->f(x), a), write map(f, a).

    Avoid using floats for numeric literals in generic code when possible

    If you write generic code which handles numbers, and which can be expected to run with many different numeric type arguments, try using literals of a numeric type that will affect the arguments as little as possible through promotion.

    For example,

    julia> f(x) = 2.0 * x
    -f (generic function with 1 method)
    -
    -julia> f(1//2)
    -1.0
    -
    -julia> f(1/2)
    -1.0
    -
    -julia> f(1)
    -2.0

    while

    julia> g(x) = 2 * x
    -g (generic function with 1 method)
    -
    -julia> g(1//2)
    -1//1
    -
    -julia> g(1/2)
    -1.0
    -
    -julia> g(1)
    -2

    As you can see, the second version, where we used an Int literal, preserved the type of the input argument, while the first didn't. This is because e.g. promote_type(Int, Float64) == Float64, and promotion happens with the multiplication. Similarly, Rational literals are less type disruptive than Float64 literals, but more disruptive than Ints:

    julia> h(x) = 2//1 * x
    -h (generic function with 1 method)
    -
    -julia> h(1//2)
    -1//1
    -
    -julia> h(1/2)
    -1.0
    -
    -julia> h(1)
    -2//1

    Thus, use Int literals when possible, with Rational{Int} for literal non-integer numbers, in order to make it easier to use your code.

    diff --git a/julia-0.6.3/share/doc/julia/html/en/manual/types.html b/julia-0.6.3/share/doc/julia/html/en/manual/types.html deleted file mode 100644 index 82584a8..0000000 --- a/julia-0.6.3/share/doc/julia/html/en/manual/types.html +++ /dev/null @@ -1,366 +0,0 @@ - -Types · The Julia Language

    Types

    Types

    Type systems have traditionally fallen into two quite different camps: static type systems, where every program expression must have a type computable before the execution of the program, and dynamic type systems, where nothing is known about types until run time, when the actual values manipulated by the program are available. Object orientation allows some flexibility in statically typed languages by letting code be written without the precise types of values being known at compile time. The ability to write code that can operate on different types is called polymorphism. All code in classic dynamically typed languages is polymorphic: only by explicitly checking types, or when objects fail to support operations at run-time, are the types of any values ever restricted.

    Julia's type system is dynamic, but gains some of the advantages of static type systems by making it possible to indicate that certain values are of specific types. This can be of great assistance in generating efficient code, but even more significantly, it allows method dispatch on the types of function arguments to be deeply integrated with the language. Method dispatch is explored in detail in Methods, but is rooted in the type system presented here.

    The default behavior in Julia when types are omitted is to allow values to be of any type. Thus, one can write many useful Julia programs without ever explicitly using types. When additional expressiveness is needed, however, it is easy to gradually introduce explicit type annotations into previously "untyped" code. Doing so will typically increase both the performance and robustness of these systems, and perhaps somewhat counterintuitively, often significantly simplify them.

    Describing Julia in the lingo of type systems, it is: dynamic, nominative and parametric. Generic types can be parameterized, and the hierarchical relationships between types are explicitly declared, rather than implied by compatible structure. One particularly distinctive feature of Julia's type system is that concrete types may not subtype each other: all concrete types are final and may only have abstract types as their supertypes. While this might at first seem unduly restrictive, it has many beneficial consequences with surprisingly few drawbacks. It turns out that being able to inherit behavior is much more important than being able to inherit structure, and inheriting both causes significant difficulties in traditional object-oriented languages. Other high-level aspects of Julia's type system that should be mentioned up front are:

    • There is no division between object and non-object values: all values in Julia are true objects having a type that belongs to a single, fully connected type graph, all nodes of which are equally first-class as types.

    • There is no meaningful concept of a "compile-time type": the only type a value has is its actual type when the program is running. This is called a "run-time type" in object-oriented languages where the combination of static compilation with polymorphism makes this distinction significant.

    • Only values, not variables, have types – variables are simply names bound to values.

    • Both abstract and concrete types can be parameterized by other types. They can also be parameterized by symbols, by values of any type for which isbits() returns true (essentially, things like numbers and bools that are stored like C types or structs with no pointers to other objects), and also by tuples thereof. Type parameters may be omitted when they do not need to be referenced or restricted.

    Julia's type system is designed to be powerful and expressive, yet clear, intuitive and unobtrusive. Many Julia programmers may never feel the need to write code that explicitly uses types. Some kinds of programming, however, become clearer, simpler, faster and more robust with declared types.

    Type Declarations

    The :: operator can be used to attach type annotations to expressions and variables in programs. There are two primary reasons to do this:

    1. As an assertion to help confirm that your program works the way you expect,

    2. To provide extra type information to the compiler, which can then improve performance in some cases

    When appended to an expression computing a value, the :: operator is read as "is an instance of". It can be used anywhere to assert that the value of the expression on the left is an instance of the type on the right. When the type on the right is concrete, the value on the left must have that type as its implementation – recall that all concrete types are final, so no implementation is a subtype of any other. When the type is abstract, it suffices for the value to be implemented by a concrete type that is a subtype of the abstract type. If the type assertion is not true, an exception is thrown, otherwise, the left-hand value is returned:

    julia> (1+2)::AbstractFloat
    -ERROR: TypeError: typeassert: expected AbstractFloat, got Int64
    -
    -julia> (1+2)::Int
    -3

    This allows a type assertion to be attached to any expression in-place.

    When appended to a variable on the left-hand side of an assignment, or as part of a local declaration, the :: operator means something a bit different: it declares the variable to always have the specified type, like a type declaration in a statically-typed language such as C. Every value assigned to the variable will be converted to the declared type using convert():

    julia> function foo()
    -           x::Int8 = 100
    -           x
    -       end
    -foo (generic function with 1 method)
    -
    -julia> foo()
    -100
    -
    -julia> typeof(ans)
    -Int8

    This feature is useful for avoiding performance "gotchas" that could occur if one of the assignments to a variable changed its type unexpectedly.

    This "declaration" behavior only occurs in specific contexts:

    local x::Int8  # in a local declaration
    -x::Int8 = 10   # as the left-hand side of an assignment

    and applies to the whole current scope, even before the declaration. Currently, type declarations cannot be used in global scope, e.g. in the REPL, since Julia does not yet have constant-type globals.

    Declarations can also be attached to function definitions:

    function sinc(x)::Float64
    -    if x == 0
    -        return 1
    -    end
    -    return sin(pi*x)/(pi*x)
    -end

    Returning from this function behaves just like an assignment to a variable with a declared type: the value is always converted to Float64.

    Abstract Types

    Abstract types cannot be instantiated, and serve only as nodes in the type graph, thereby describing sets of related concrete types: those concrete types which are their descendants. We begin with abstract types even though they have no instantiation because they are the backbone of the type system: they form the conceptual hierarchy which makes Julia's type system more than just a collection of object implementations.

    Recall that in Integers and Floating-Point Numbers, we introduced a variety of concrete types of numeric values: Int8, UInt8, Int16, UInt16, Int32, UInt32, Int64, UInt64, Int128, UInt128, Float16, Float32, and Float64. Although they have different representation sizes, Int8, Int16, Int32, Int64 and Int128 all have in common that they are signed integer types. Likewise UInt8, UInt16, UInt32, UInt64 and UInt128 are all unsigned integer types, while Float16, Float32 and Float64 are distinct in being floating-point types rather than integers. It is common for a piece of code to make sense, for example, only if its arguments are some kind of integer, but not really depend on what particular kind of integer. For example, the greatest common denominator algorithm works for all kinds of integers, but will not work for floating-point numbers. Abstract types allow the construction of a hierarchy of types, providing a context into which concrete types can fit. This allows you, for example, to easily program to any type that is an integer, without restricting an algorithm to a specific type of integer.

    Abstract types are declared using the abstract type keyword. The general syntaxes for declaring an abstract type are:

    abstract type «name» end
    -abstract type «name» <: «supertype» end

    The abstract type keyword introduces a new abstract type, whose name is given by «name». This name can be optionally followed by <: and an already-existing type, indicating that the newly declared abstract type is a subtype of this "parent" type.

    When no supertype is given, the default supertype is Any – a predefined abstract type that all objects are instances of and all types are subtypes of. In type theory, Any is commonly called "top" because it is at the apex of the type graph. Julia also has a predefined abstract "bottom" type, at the nadir of the type graph, which is written as Union{}. It is the exact opposite of Any: no object is an instance of Union{} and all types are supertypes of Union{}.

    Let's consider some of the abstract types that make up Julia's numerical hierarchy:

    abstract type Number end
    -abstract type Real     <: Number end
    -abstract type AbstractFloat <: Real end
    -abstract type Integer  <: Real end
    -abstract type Signed   <: Integer end
    -abstract type Unsigned <: Integer end

    The Number type is a direct child type of Any, and Real is its child. In turn, Real has two children (it has more, but only two are shown here; we'll get to the others later): Integer and AbstractFloat, separating the world into representations of integers and representations of real numbers. Representations of real numbers include, of course, floating-point types, but also include other types, such as rationals. Hence, AbstractFloat is a proper subtype of Real, including only floating-point representations of real numbers. Integers are further subdivided into Signed and Unsigned varieties.

    The <: operator in general means "is a subtype of", and, used in declarations like this, declares the right-hand type to be an immediate supertype of the newly declared type. It can also be used in expressions as a subtype operator which returns true when its left operand is a subtype of its right operand:

    julia> Integer <: Number
    -true
    -
    -julia> Integer <: AbstractFloat
    -false

    An important use of abstract types is to provide default implementations for concrete types. To give a simple example, consider:

    function myplus(x,y)
    -    x+y
    -end

    The first thing to note is that the above argument declarations are equivalent to x::Any and y::Any. When this function is invoked, say as myplus(2,5), the dispatcher chooses the most specific method named myplus that matches the given arguments. (See Methods for more information on multiple dispatch.)

    Assuming no method more specific than the above is found, Julia next internally defines and compiles a method called myplus specifically for two Int arguments based on the generic function given above, i.e., it implicitly defines and compiles:

    function myplus(x::Int,y::Int)
    -    x+y
    -end

    and finally, it invokes this specific method.

    Thus, abstract types allow programmers to write generic functions that can later be used as the default method by many combinations of concrete types. Thanks to multiple dispatch, the programmer has full control over whether the default or more specific method is used.

    An important point to note is that there is no loss in performance if the programmer relies on a function whose arguments are abstract types, because it is recompiled for each tuple of argument concrete types with which it is invoked. (There may be a performance issue, however, in the case of function arguments that are containers of abstract types; see Performance Tips.)

    Primitive Types

    A primitive type is a concrete type whose data consists of plain old bits. Classic examples of primitive types are integers and floating-point values. Unlike most languages, Julia lets you declare your own primitive types, rather than providing only a fixed set of built-in ones. In fact, the standard primitive types are all defined in the language itself:

    primitive type Float16 <: AbstractFloat 16 end
    -primitive type Float32 <: AbstractFloat 32 end
    -primitive type Float64 <: AbstractFloat 64 end
    -
    -primitive type Bool <: Integer 8 end
    -primitive type Char 32 end
    -
    -primitive type Int8    <: Signed   8 end
    -primitive type UInt8   <: Unsigned 8 end
    -primitive type Int16   <: Signed   16 end
    -primitive type UInt16  <: Unsigned 16 end
    -primitive type Int32   <: Signed   32 end
    -primitive type UInt32  <: Unsigned 32 end
    -primitive type Int64   <: Signed   64 end
    -primitive type UInt64  <: Unsigned 64 end
    -primitive type Int128  <: Signed   128 end
    -primitive type UInt128 <: Unsigned 128 end

    The general syntaxes for declaring a primitive type are:

    primitive type «name» «bits» end
    -primitive type «name» <: «supertype» «bits» end

    The number of bits indicates how much storage the type requires and the name gives the new type a name. A primitive type can optionally be declared to be a subtype of some supertype. If a supertype is omitted, then the type defaults to having Any as its immediate supertype. The declaration of Bool above therefore means that a boolean value takes eight bits to store, and has Integer as its immediate supertype. Currently, only sizes that are multiples of 8 bits are supported. Therefore, boolean values, although they really need just a single bit, cannot be declared to be any smaller than eight bits.

    The types Bool, Int8 and UInt8 all have identical representations: they are eight-bit chunks of memory. Since Julia's type system is nominative, however, they are not interchangeable despite having identical structure. A fundamental difference between them is that they have different supertypes: Bool's direct supertype is Integer, Int8's is Signed, and UInt8's is Unsigned. All other differences between Bool, Int8, and UInt8 are matters of behavior – the way functions are defined to act when given objects of these types as arguments. This is why a nominative type system is necessary: if structure determined type, which in turn dictates behavior, then it would be impossible to make Bool behave any differently than Int8 or UInt8.

    Composite Types

    Composite types are called records, structs, or objects in various languages. A composite type is a collection of named fields, an instance of which can be treated as a single value. In many languages, composite types are the only kind of user-definable type, and they are by far the most commonly used user-defined type in Julia as well.

    In mainstream object oriented languages, such as C++, Java, Python and Ruby, composite types also have named functions associated with them, and the combination is called an "object". In purer object-oriented languages, such as Ruby or Smalltalk, all values are objects whether they are composites or not. In less pure object oriented languages, including C++ and Java, some values, such as integers and floating-point values, are not objects, while instances of user-defined composite types are true objects with associated methods. In Julia, all values are objects, but functions are not bundled with the objects they operate on. This is necessary since Julia chooses which method of a function to use by multiple dispatch, meaning that the types of all of a function's arguments are considered when selecting a method, rather than just the first one (see Methods for more information on methods and dispatch). Thus, it would be inappropriate for functions to "belong" to only their first argument. Organizing methods into function objects rather than having named bags of methods "inside" each object ends up being a highly beneficial aspect of the language design.

    Composite types are introduced with the struct keyword followed by a block of field names, optionally annotated with types using the :: operator:

    julia> struct Foo
    -           bar
    -           baz::Int
    -           qux::Float64
    -       end

    Fields with no type annotation default to Any, and can accordingly hold any type of value.

    New objects of type Foo are created by applying the Foo type object like a function to values for its fields:

    julia> foo = Foo("Hello, world.", 23, 1.5)
    -Foo("Hello, world.", 23, 1.5)
    -
    -julia> typeof(foo)
    -Foo

    When a type is applied like a function it is called a constructor. Two constructors are generated automatically (these are called default constructors). One accepts any arguments and calls convert() to convert them to the types of the fields, and the other accepts arguments that match the field types exactly. The reason both of these are generated is that this makes it easier to add new definitions without inadvertently replacing a default constructor.

    Since the bar field is unconstrained in type, any value will do. However, the value for baz must be convertible to Int:

    julia> Foo((), 23.5, 1)
    -ERROR: InexactError()
    -Stacktrace:
    - [1] convert(::Type{Int64}, ::Float64) at ./float.jl:679
    - [2] Foo(::Tuple{}, ::Float64, ::Int64) at ./none:2

    You may find a list of field names using the fieldnames function.

    julia> fieldnames(foo)
    -3-element Array{Symbol,1}:
    - :bar
    - :baz
    - :qux

    You can access the field values of a composite object using the traditional foo.bar notation:

    julia> foo.bar
    -"Hello, world."
    -
    -julia> foo.baz
    -23
    -
    -julia> foo.qux
    -1.5

    Composite objects declared with struct are immutable; they cannot be modified after construction. This may seem odd at first, but it has several advantages:

    • It can be more efficient. Some structs can be packed efficiently into arrays, and in some cases the compiler is able to avoid allocating immutable objects entirely.

    • It is not possible to violate the invariants provided by the type's constructors.

    • Code using immutable objects can be easier to reason about.

    An immutable object might contain mutable objects, such as arrays, as fields. Those contained objects will remain mutable; only the fields of the immutable object itself cannot be changed to point to different objects.

    Where required, mutable composite objects can be declared with the keyword mutable struct, to be discussed in the next section.

    Composite types with no fields are singletons; there can be only one instance of such types:

    julia> struct NoFields
    -       end
    -
    -julia> NoFields() === NoFields()
    -true

    The === function confirms that the "two" constructed instances of NoFields are actually one and the same. Singleton types are described in further detail below.

    There is much more to say about how instances of composite types are created, but that discussion depends on both Parametric Types and on Methods, and is sufficiently important to be addressed in its own section: Constructors.

    Mutable Composite Types

    If a composite type is declared with mutable struct instead of struct, then instances of it can be modified:

    julia> mutable struct Bar
    -           baz
    -           qux::Float64
    -       end
    -
    -julia> bar = Bar("Hello", 1.5);
    -
    -julia> bar.qux = 2.0
    -2.0
    -
    -julia> bar.baz = 1//2
    -1//2

    In order to support mutation, such objects are generally allocated on the heap, and have stable memory addresses. A mutable object is like a little container that might hold different values over time, and so can only be reliably identified with its address. In contrast, an instance of an immutable type is associated with specific field values –- the field values alone tell you everything about the object. In deciding whether to make a type mutable, ask whether two instances with the same field values would be considered identical, or if they might need to change independently over time. If they would be considered identical, the type should probably be immutable.

    To recap, two essential properties define immutability in Julia:

    • An object with an immutable type is passed around (both in assignment statements and in function calls) by copying, whereas a mutable type is passed around by reference.

    • It is not permitted to modify the fields of a composite immutable type.

    It is instructive, particularly for readers whose background is C/C++, to consider why these two properties go hand in hand. If they were separated, i.e., if the fields of objects passed around by copying could be modified, then it would become more difficult to reason about certain instances of generic code. For example, suppose x is a function argument of an abstract type, and suppose that the function changes a field: x.isprocessed = true. Depending on whether x is passed by copying or by reference, this statement may or may not alter the actual argument in the calling routine. Julia sidesteps the possibility of creating functions with unknown effects in this scenario by forbidding modification of fields of objects passed around by copying.

    Declared Types

    The three kinds of types discussed in the previous three sections are actually all closely related. They share the same key properties:

    • They are explicitly declared.

    • They have names.

    • They have explicitly declared supertypes.

    • They may have parameters.

    Because of these shared properties, these types are internally represented as instances of the same concept, DataType, which is the type of any of these types:

    julia> typeof(Real)
    -DataType
    -
    -julia> typeof(Int)
    -DataType

    A DataType may be abstract or concrete. If it is concrete, it has a specified size, storage layout, and (optionally) field names. Thus a bits type is a DataType with nonzero size, but no field names. A composite type is a DataType that has field names or is empty (zero size).

    Every concrete value in the system is an instance of some DataType.

    Type Unions

    A type union is a special abstract type which includes as objects all instances of any of its argument types, constructed using the special Union function:

    julia> IntOrString = Union{Int,AbstractString}
    -Union{AbstractString, Int64}
    -
    -julia> 1 :: IntOrString
    -1
    -
    -julia> "Hello!" :: IntOrString
    -"Hello!"
    -
    -julia> 1.0 :: IntOrString
    -ERROR: TypeError: typeassert: expected Union{AbstractString, Int64}, got Float64

    The compilers for many languages have an internal union construct for reasoning about types; Julia simply exposes it to the programmer.

    Parametric Types

    An important and powerful feature of Julia's type system is that it is parametric: types can take parameters, so that type declarations actually introduce a whole family of new types – one for each possible combination of parameter values. There are many languages that support some version of generic programming, wherein data structures and algorithms to manipulate them may be specified without specifying the exact types involved. For example, some form of generic programming exists in ML, Haskell, Ada, Eiffel, C++, Java, C#, F#, and Scala, just to name a few. Some of these languages support true parametric polymorphism (e.g. ML, Haskell, Scala), while others support ad-hoc, template-based styles of generic programming (e.g. C++, Java). With so many different varieties of generic programming and parametric types in various languages, we won't even attempt to compare Julia's parametric types to other languages, but will instead focus on explaining Julia's system in its own right. We will note, however, that because Julia is a dynamically typed language and doesn't need to make all type decisions at compile time, many traditional difficulties encountered in static parametric type systems can be relatively easily handled.

    All declared types (the DataType variety) can be parameterized, with the same syntax in each case. We will discuss them in the following order: first, parametric composite types, then parametric abstract types, and finally parametric bits types.

    Parametric Composite Types

    Type parameters are introduced immediately after the type name, surrounded by curly braces:

    julia> struct Point{T}
    -           x::T
    -           y::T
    -       end

    This declaration defines a new parametric type, Point{T}, holding two "coordinates" of type T. What, one may ask, is T? Well, that's precisely the point of parametric types: it can be any type at all (or a value of any bits type, actually, although here it's clearly used as a type). Point{Float64} is a concrete type equivalent to the type defined by replacing T in the definition of Point with Float64. Thus, this single declaration actually declares an unlimited number of types: Point{Float64}, Point{AbstractString}, Point{Int64}, etc. Each of these is now a usable concrete type:

    julia> Point{Float64}
    -Point{Float64}
    -
    -julia> Point{AbstractString}
    -Point{AbstractString}

    The type Point{Float64} is a point whose coordinates are 64-bit floating-point values, while the type Point{AbstractString} is a "point" whose "coordinates" are string objects (see Strings).

    Point itself is also a valid type object, containing all instances Point{Float64}, Point{AbstractString}, etc. as subtypes:

    julia> Point{Float64} <: Point
    -true
    -
    -julia> Point{AbstractString} <: Point
    -true

    Other types, of course, are not subtypes of it:

    julia> Float64 <: Point
    -false
    -
    -julia> AbstractString <: Point
    -false

    Concrete Point types with different values of T are never subtypes of each other:

    julia> Point{Float64} <: Point{Int64}
    -false
    -
    -julia> Point{Float64} <: Point{Real}
    -false
    Warning

    This last point is very important: even though Float64 <: Real we DO NOT have Point{Float64} <: Point{Real}.

    In other words, in the parlance of type theory, Julia's type parameters are invariant, rather than being covariant (or even contravariant). This is for practical reasons: while any instance of Point{Float64} may conceptually be like an instance of Point{Real} as well, the two types have different representations in memory:

    • An instance of Point{Float64} can be represented compactly and efficiently as an immediate pair of 64-bit values;

    • An instance of Point{Real} must be able to hold any pair of instances of Real. Since objects that are instances of Real can be of arbitrary size and structure, in practice an instance of Point{Real} must be represented as a pair of pointers to individually allocated Real objects.

    The efficiency gained by being able to store Point{Float64} objects with immediate values is magnified enormously in the case of arrays: an Array{Float64} can be stored as a contiguous memory block of 64-bit floating-point values, whereas an Array{Real} must be an array of pointers to individually allocated Real objects – which may well be boxed 64-bit floating-point values, but also might be arbitrarily large, complex objects, which are declared to be implementations of the Real abstract type.

    Since Point{Float64} is not a subtype of Point{Real}, the following method can't be applied to arguments of type Point{Float64}:

    function norm(p::Point{Real})
    -    sqrt(p.x^2 + p.y^2)
    -end

    A correct way to define a method that accepts all arguments of type Point{T} where T is a subtype of Real is:

    function norm(p::Point{<:Real})
    -    sqrt(p.x^2 + p.y^2)
    -end

    (Equivalently, one could define function norm{T<:Real}(p::Point{T}) or function norm(p::Point{T} where T<:Real); see UnionAll Types.)

    More examples will be discussed later in Methods.

    How does one construct a Point object? It is possible to define custom constructors for composite types, which will be discussed in detail in Constructors, but in the absence of any special constructor declarations, there are two default ways of creating new composite objects, one in which the type parameters are explicitly given and the other in which they are implied by the arguments to the object constructor.

    Since the type Point{Float64} is a concrete type equivalent to Point declared with Float64 in place of T, it can be applied as a constructor accordingly:

    julia> Point{Float64}(1.0, 2.0)
    -Point{Float64}(1.0, 2.0)
    -
    -julia> typeof(ans)
    -Point{Float64}

    For the default constructor, exactly one argument must be supplied for each field:

    julia> Point{Float64}(1.0)
    -ERROR: MethodError: Cannot `convert` an object of type Float64 to an object of type Point{Float64}
    -This may have arisen from a call to the constructor Point{Float64}(...),
    -since type constructors fall back to convert methods.
    -Stacktrace:
    - [1] Point{Float64}(::Float64) at ./sysimg.jl:77
    -
    -julia> Point{Float64}(1.0,2.0,3.0)
    -ERROR: MethodError: no method matching Point{Float64}(::Float64, ::Float64, ::Float64)

    Only one default constructor is generated for parametric types, since overriding it is not possible. This constructor accepts any arguments and converts them to the field types.

    In many cases, it is redundant to provide the type of Point object one wants to construct, since the types of arguments to the constructor call already implicitly provide type information. For that reason, you can also apply Point itself as a constructor, provided that the implied value of the parameter type T is unambiguous:

    julia> Point(1.0,2.0)
    -Point{Float64}(1.0, 2.0)
    -
    -julia> typeof(ans)
    -Point{Float64}
    -
    -julia> Point(1,2)
    -Point{Int64}(1, 2)
    -
    -julia> typeof(ans)
    -Point{Int64}

    In the case of Point, the type of T is unambiguously implied if and only if the two arguments to Point have the same type. When this isn't the case, the constructor will fail with a MethodError:

    julia> Point(1,2.5)
    -ERROR: MethodError: no method matching Point(::Int64, ::Float64)
    -Closest candidates are:
    -  Point(::T, !Matched::T) where T at none:2

    Constructor methods to appropriately handle such mixed cases can be defined, but that will not be discussed until later on in Constructors.

    Parametric Abstract Types

    Parametric abstract type declarations declare a collection of abstract types, in much the same way:

    julia> abstract type Pointy{T} end

    With this declaration, Pointy{T} is a distinct abstract type for each type or integer value of T. As with parametric composite types, each such instance is a subtype of Pointy:

    julia> Pointy{Int64} <: Pointy
    -true
    -
    -julia> Pointy{1} <: Pointy
    -true

    Parametric abstract types are invariant, much as parametric composite types are:

    julia> Pointy{Float64} <: Pointy{Real}
    -false
    -
    -julia> Pointy{Real} <: Pointy{Float64}
    -false

    The notation Pointy{<:Real} can be used to express the Julia analogue of a covariant type, while Pointy{>:Int} the analogue of a contravariant type, but technically these represent sets of types (see UnionAll Types).

    julia> Pointy{Float64} <: Pointy{<:Real}
    -true
    -
    -julia> Pointy{Real} <: Pointy{>:Int}
    -true

    Much as plain old abstract types serve to create a useful hierarchy of types over concrete types, parametric abstract types serve the same purpose with respect to parametric composite types. We could, for example, have declared Point{T} to be a subtype of Pointy{T} as follows:

    julia> struct Point{T} <: Pointy{T}
    -           x::T
    -           y::T
    -       end

    Given such a declaration, for each choice of T, we have Point{T} as a subtype of Pointy{T}:

    julia> Point{Float64} <: Pointy{Float64}
    -true
    -
    -julia> Point{Real} <: Pointy{Real}
    -true
    -
    -julia> Point{AbstractString} <: Pointy{AbstractString}
    -true

    This relationship is also invariant:

    julia> Point{Float64} <: Pointy{Real}
    -false
    -
    -julia> Point{Float64} <: Pointy{<:Real}
    -true

    What purpose do parametric abstract types like Pointy serve? Consider if we create a point-like implementation that only requires a single coordinate because the point is on the diagonal line x = y:

    julia> struct DiagPoint{T} <: Pointy{T}
    -           x::T
    -       end

    Now both Point{Float64} and DiagPoint{Float64} are implementations of the Pointy{Float64} abstraction, and similarly for every other possible choice of type T. This allows programming to a common interface shared by all Pointy objects, implemented for both Point and DiagPoint. This cannot be fully demonstrated, however, until we have introduced methods and dispatch in the next section, Methods.

    There are situations where it may not make sense for type parameters to range freely over all possible types. In such situations, one can constrain the range of T like so:

    julia> abstract type Pointy{T<:Real} end

    With such a declaration, it is acceptable to use any type that is a subtype of Real in place of T, but not types that are not subtypes of Real:

    julia> Pointy{Float64}
    -Pointy{Float64}
    -
    -julia> Pointy{Real}
    -Pointy{Real}
    -
    -julia> Pointy{AbstractString}
    -ERROR: TypeError: Pointy: in T, expected T<:Real, got Type{AbstractString}
    -
    -julia> Pointy{1}
    -ERROR: TypeError: Pointy: in T, expected T<:Real, got Int64

    Type parameters for parametric composite types can be restricted in the same manner:

    struct Point{T<:Real} <: Pointy{T}
    -    x::T
    -    y::T
    -end

    To give a real-world example of how all this parametric type machinery can be useful, here is the actual definition of Julia's Rational immutable type (except that we omit the constructor here for simplicity), representing an exact ratio of integers:

    struct Rational{T<:Integer} <: Real
    -    num::T
    -    den::T
    -end

    It only makes sense to take ratios of integer values, so the parameter type T is restricted to being a subtype of Integer, and a ratio of integers represents a value on the real number line, so any Rational is an instance of the Real abstraction.

    Tuple Types

    Tuples are an abstraction of the arguments of a function – without the function itself. The salient aspects of a function's arguments are their order and their types. Therefore a tuple type is similar to a parameterized immutable type where each parameter is the type of one field. For example, a 2-element tuple type resembles the following immutable type:

    struct Tuple2{A,B}
    -    a::A
    -    b::B
    -end

    However, there are three key differences:

    • Tuple types may have any number of parameters.

    • Tuple types are covariant in their parameters: Tuple{Int} is a subtype of Tuple{Any}. Therefore Tuple{Any} is considered an abstract type, and tuple types are only concrete if their parameters are.

    • Tuples do not have field names; fields are only accessed by index.

    Tuple values are written with parentheses and commas. When a tuple is constructed, an appropriate tuple type is generated on demand:

    julia> typeof((1,"foo",2.5))
    -Tuple{Int64,String,Float64}

    Note the implications of covariance:

    julia> Tuple{Int,AbstractString} <: Tuple{Real,Any}
    -true
    -
    -julia> Tuple{Int,AbstractString} <: Tuple{Real,Real}
    -false
    -
    -julia> Tuple{Int,AbstractString} <: Tuple{Real,}
    -false

    Intuitively, this corresponds to the type of a function's arguments being a subtype of the function's signature (when the signature matches).

    Vararg Tuple Types

    The last parameter of a tuple type can be the special type Vararg, which denotes any number of trailing elements:

    julia> mytupletype = Tuple{AbstractString,Vararg{Int}}
    -Tuple{AbstractString,Vararg{Int64,N} where N}
    -
    -julia> isa(("1",), mytupletype)
    -true
    -
    -julia> isa(("1",1), mytupletype)
    -true
    -
    -julia> isa(("1",1,2), mytupletype)
    -true
    -
    -julia> isa(("1",1,2,3.0), mytupletype)
    -false

    Notice that Vararg{T} corresponds to zero or more elements of type T. Vararg tuple types are used to represent the arguments accepted by varargs methods (see Varargs Functions).

    The type Vararg{T,N} corresponds to exactly N elements of type T. NTuple{N,T} is a convenient alias for Tuple{Vararg{T,N}}, i.e. a tuple type containing exactly N elements of type T.

    Singleton Types

    There is a special kind of abstract parametric type that must be mentioned here: singleton types. For each type, T, the "singleton type" Type{T} is an abstract type whose only instance is the object T. Since the definition is a little difficult to parse, let's look at some examples:

    julia> isa(Float64, Type{Float64})
    -true
    -
    -julia> isa(Real, Type{Float64})
    -false
    -
    -julia> isa(Real, Type{Real})
    -true
    -
    -julia> isa(Float64, Type{Real})
    -false

    In other words, isa(A,Type{B}) is true if and only if A and B are the same object and that object is a type. Without the parameter, Type is simply an abstract type which has all type objects as its instances, including, of course, singleton types:

    julia> isa(Type{Float64}, Type)
    -true
    -
    -julia> isa(Float64, Type)
    -true
    -
    -julia> isa(Real, Type)
    -true

    Any object that is not a type is not an instance of Type:

    julia> isa(1, Type)
    -false
    -
    -julia> isa("foo", Type)
    -false

    Until we discuss Parametric Methods and conversions, it is difficult to explain the utility of the singleton type construct, but in short, it allows one to specialize function behavior on specific type values. This is useful for writing methods (especially parametric ones) whose behavior depends on a type that is given as an explicit argument rather than implied by the type of one of its arguments.

    A few popular languages have singleton types, including Haskell, Scala and Ruby. In general usage, the term "singleton type" refers to a type whose only instance is a single value. This meaning applies to Julia's singleton types, but with that caveat that only type objects have singleton types.

    Parametric Primitive Types

    Primitive types can also be declared parametrically. For example, pointers are represented as primitive types which would be declared in Julia like this:

    # 32-bit system:
    -primitive type Ptr{T} 32 end
    -
    -# 64-bit system:
    -primitive type Ptr{T} 64 end

    The slightly odd feature of these declarations as compared to typical parametric composite types, is that the type parameter T is not used in the definition of the type itself – it is just an abstract tag, essentially defining an entire family of types with identical structure, differentiated only by their type parameter. Thus, Ptr{Float64} and Ptr{Int64} are distinct types, even though they have identical representations. And of course, all specific pointer types are subtypes of the umbrella Ptr type:

    julia> Ptr{Float64} <: Ptr
    -true
    -
    -julia> Ptr{Int64} <: Ptr
    -true

    UnionAll Types

    We have said that a parametric type like Ptr acts as a supertype of all its instances (Ptr{Int64} etc.). How does this work? Ptr itself cannot be a normal data type, since without knowing the type of the referenced data the type clearly cannot be used for memory operations. The answer is that Ptr (or other parametric types like Array) is a different kind of type called a UnionAll type. Such a type expresses the iterated union of types for all values of some parameter.

    UnionAll types are usually written using the keyword where. For example Ptr could be more accurately written as Ptr{T} where T, meaning all values whose type is Ptr{T} for some value of T. In this context, the parameter T is also often called a "type variable" since it is like a variable that ranges over types. Each where introduces a single type variable, so these expressions are nested for types with multiple parameters, for example Array{T,N} where N where T.

    The type application syntax A{B,C} requires A to be a UnionAll type, and first substitutes B for the outermost type variable in A. The result is expected to be another UnionAll type, into which C is then substituted. So A{B,C} is equivalent to A{B}{C}. This explains why it is possible to partially instantiate a type, as in Array{Float64}: the first parameter value has been fixed, but the second still ranges over all possible values. Using explicit where syntax, any subset of parameters can be fixed. For example, the type of all 1-dimensional arrays can be written as Array{T,1} where T.

    Type variables can be restricted with subtype relations. Array{T} where T<:Integer refers to all arrays whose element type is some kind of Integer. The syntax Array{<:Integer} is a convenient shorthand for Array{T} where T<:Integer. Type variables can have both lower and upper bounds. Array{T} where Int<:T<:Number refers to all arrays of Numbers that are able to contain Ints (since T must be at least as big as Int). The syntax where T>:Int also works to specify only the lower bound of a type variable, and Array{>:Int} is equivalent to Array{T} where T>:Int.

    Since where expressions nest, type variable bounds can refer to outer type variables. For example Tuple{T,Array{S}} where S<:AbstractArray{T} where T<:Real refers to 2-tuples whose first element is some Real, and whose second element is an Array of any kind of array whose element type contains the type of the first tuple element.

    The where keyword itself can be nested inside a more complex declaration. For example, consider the two types created by the following declarations:

    julia> const T1 = Array{Array{T,1} where T, 1}
    -Array{Array{T,1} where T,1}
    -
    -julia> const T2 = Array{Array{T,1}, 1} where T
    -Array{Array{T,1},1} where T

    Type T1 defines a 1-dimensional array of 1-dimensional arrays; each of the inner arrays consists of objects of the same type, but this type may vary from one inner array to the next. On the other hand, type T2 defines a 1-dimensional array of 1-dimensional arrays all of whose inner arrays must have the same type. Note that T2 is an abstract type, e.g., Array{Array{Int,1},1} <: T2, whereas T1 is a concrete type. As a consequence, T1 can be constructed with a zero-argument constructor a=T1() but T2 cannot.

    There is a convenient syntax for naming such types, similar to the short form of function definition syntax:

    Vector{T} = Array{T,1}

    This is equivalent to const Vector = Array{T,1} where T. Writing Vector{Float64} is equivalent to writing Array{Float64,1}, and the umbrella type Vector has as instances all Array objects where the second parameter – the number of array dimensions – is 1, regardless of what the element type is. In languages where parametric types must always be specified in full, this is not especially helpful, but in Julia, this allows one to write just Vector for the abstract type including all one-dimensional dense arrays of any element type.

    Type Aliases

    Sometimes it is convenient to introduce a new name for an already expressible type. This can be done with a simple assignment statement. For example, UInt is aliased to either UInt32 or UInt64 as is appropriate for the size of pointers on the system:

    # 32-bit system:
    -julia> UInt
    -UInt32
    -
    -# 64-bit system:
    -julia> UInt
    -UInt64

    This is accomplished via the following code in base/boot.jl:

    if Int === Int64
    -    const UInt = UInt64
    -else
    -    const UInt = UInt32
    -end

    Of course, this depends on what Int is aliased to – but that is predefined to be the correct type – either Int32 or Int64.

    (Note that unlike Int, Float does not exist as a type alias for a specific sized AbstractFloat. Unlike with integer registers, the floating point register sizes are specified by the IEEE-754 standard. Whereas the size of Int reflects the size of a native pointer on that machine.)

    Operations on Types

    Since types in Julia are themselves objects, ordinary functions can operate on them. Some functions that are particularly useful for working with or exploring types have already been introduced, such as the <: operator, which indicates whether its left hand operand is a subtype of its right hand operand.

    The isa function tests if an object is of a given type and returns true or false:

    julia> isa(1, Int)
    -true
    -
    -julia> isa(1, AbstractFloat)
    -false

    The typeof() function, already used throughout the manual in examples, returns the type of its argument. Since, as noted above, types are objects, they also have types, and we can ask what their types are:

    julia> typeof(Rational{Int})
    -DataType
    -
    -julia> typeof(Union{Real,Float64,Rational})
    -DataType
    -
    -julia> typeof(Union{Real,String})
    -Union

    What if we repeat the process? What is the type of a type of a type? As it happens, types are all composite values and thus all have a type of DataType:

    julia> typeof(DataType)
    -DataType
    -
    -julia> typeof(Union)
    -DataType

    DataType is its own type.

    Another operation that applies to some types is supertype(), which reveals a type's supertype. Only declared types (DataType) have unambiguous supertypes:

    julia> supertype(Float64)
    -AbstractFloat
    -
    -julia> supertype(Number)
    -Any
    -
    -julia> supertype(AbstractString)
    -Any
    -
    -julia> supertype(Any)
    -Any

    If you apply supertype() to other type objects (or non-type objects), a MethodError is raised:

    julia> supertype(Union{Float64,Int64})
    -ERROR: MethodError: no method matching supertype(::Type{Union{Float64, Int64}})
    -Closest candidates are:
    -  supertype(!Matched::DataType) at operators.jl:41
    -  supertype(!Matched::UnionAll) at operators.jl:46

    Custom pretty-printing

    Often, one wants to customize how instances of a type are displayed. This is accomplished by overloading the show() function. For example, suppose we define a type to represent complex numbers in polar form:

    julia> struct Polar{T<:Real} <: Number
    -           r::T
    -           Θ::T
    -       end
    -
    -julia> Polar(r::Real,Θ::Real) = Polar(promote(r,Θ)...)
    -Polar

    Here, we've added a custom constructor function so that it can take arguments of different Real types and promote them to a common type (see Constructors and Conversion and Promotion). (Of course, we would have to define lots of other methods, too, to make it act like a Number, e.g. +, *, one, zero, promotion rules and so on.) By default, instances of this type display rather simply, with information about the type name and the field values, as e.g. Polar{Float64}(3.0,4.0).

    If we want it to display instead as 3.0 * exp(4.0im), we would define the following method to print the object to a given output object io (representing a file, terminal, buffer, etcetera; see Networking and Streams):

    julia> Base.show(io::IO, z::Polar) = print(io, z.r, " * exp(", z.Θ, "im)")

    More fine-grained control over display of Polar objects is possible. In particular, sometimes one wants both a verbose multi-line printing format, used for displaying a single object in the REPL and other interactive environments, and also a more compact single-line format used for print() or for displaying the object as part of another object (e.g. in an array). Although by default the show(io, z) function is called in both cases, you can define a different multi-line format for displaying an object by overloading a three-argument form of show that takes the text/plain MIME type as its second argument (see Multimedia I/O), for example:

    julia> Base.show{T}(io::IO, ::MIME"text/plain", z::Polar{T}) =
    -           print(io, "Polar{$T} complex number:\n   ", z)

    (Note that print(..., z) here will call the 2-argument show(io, z) method.) This results in:

    julia> Polar(3, 4.0)
    -Polar{Float64} complex number:
    -   3.0 * exp(4.0im)
    -
    -julia> [Polar(3, 4.0), Polar(4.0,5.3)]
    -2-element Array{Polar{Float64},1}:
    - 3.0 * exp(4.0im)
    - 4.0 * exp(5.3im)

    where the single-line show(io, z) form is still used for an array of Polar values. Technically, the REPL calls display(z) to display the result of executing a line, which defaults to show(STDOUT, MIME("text/plain"), z), which in turn defaults to show(STDOUT, z), but you should not define new display() methods unless you are defining a new multimedia display handler (see Multimedia I/O).

    Moreover, you can also define show methods for other MIME types in order to enable richer display (HTML, images, etcetera) of objects in environments that support this (e.g. IJulia). For example, we can define formatted HTML display of Polar objects, with superscripts and italics, via:

    julia> Base.show{T}(io::IO, ::MIME"text/html", z::Polar{T}) =
    -           println(io, "<code>Polar{$T}</code> complex number: ",
    -                   z.r, " <i>e</i><sup>", z.Θ, " <i>i</i></sup>")

    A Polar object will then display automatically using HTML in an environment that supports HTML display, but you can call show manually to get HTML output if you want:

    julia> show(STDOUT, "text/html", Polar(3.0,4.0))
    -<code>Polar{Float64}</code> complex number: 3.0 <i>e</i><sup>4.0 <i>i</i></sup>

    An HTML renderer would display this as: Polar{Float64} complex number: 3.0 e4.0 i

    "Value types"

    In Julia, you can't dispatch on a value such as true or false. However, you can dispatch on parametric types, and Julia allows you to include "plain bits" values (Types, Symbols, Integers, floating-point numbers, tuples, etc.) as type parameters. A common example is the dimensionality parameter in Array{T,N}, where T is a type (e.g., Float64) but N is just an Int.

    You can create your own custom types that take values as parameters, and use them to control dispatch of custom types. By way of illustration of this idea, let's introduce a parametric type, Val{T}, which serves as a customary way to exploit this technique for cases where you don't need a more elaborate hierarchy.

    Val is defined as:

    julia> struct Val{T}
    -       end

    There is no more to the implementation of Val than this. Some functions in Julia's standard library accept Val types as arguments, and you can also use it to write your own functions. For example:

    julia> firstlast(::Type{Val{true}}) = "First"
    -firstlast (generic function with 1 method)
    -
    -julia> firstlast(::Type{Val{false}}) = "Last"
    -firstlast (generic function with 2 methods)
    -
    -julia> firstlast(Val{true})
    -"First"
    -
    -julia> firstlast(Val{false})
    -"Last"

    For consistency across Julia, the call site should always pass a Valtype rather than creating an instance, i.e., use foo(Val{:bar}) rather than foo(Val{:bar}()).

    It's worth noting that it's extremely easy to mis-use parametric "value" types, including Val; in unfavorable cases, you can easily end up making the performance of your code much worse. In particular, you would never want to write actual code as illustrated above. For more information about the proper (and improper) uses of Val, please read the more extensive discussion in the performance tips.

    Nullable Types: Representing Missing Values

    In many settings, you need to interact with a value of type T that may or may not exist. To handle these settings, Julia provides a parametric type called Nullable{T}, which can be thought of as a specialized container type that can contain either zero or one values. Nullable{T} provides a minimal interface designed to ensure that interactions with missing values are safe. At present, the interface consists of several possible interactions:

    • Construct a Nullable object.

    • Check if a Nullable object has a missing value.

    • Access the value of a Nullable object with a guarantee that a NullException will be thrown if the object's value is missing.

    • Access the value of a Nullable object with a guarantee that a default value of type T will be returned if the object's value is missing.

    • Perform an operation on the value (if it exists) of a Nullable object, getting a Nullable result. The result will be missing if the original value was missing.

    • Performing a test on the value (if it exists) of a Nullable object, getting a result that is missing if either the Nullable itself was missing, or the test failed.

    • Perform general operations on single Nullable objects, propagating the missing data.

    Constructing Nullable objects

    To construct an object representing a missing value of type T, use the Nullable{T}() function:

    julia> x1 = Nullable{Int64}()
    -Nullable{Int64}()
    -
    -julia> x2 = Nullable{Float64}()
    -Nullable{Float64}()
    -
    -julia> x3 = Nullable{Vector{Int64}}()
    -Nullable{Array{Int64,1}}()

    To construct an object representing a non-missing value of type T, use the Nullable(x::T) function:

    julia> x1 = Nullable(1)
    -Nullable{Int64}(1)
    -
    -julia> x2 = Nullable(1.0)
    -Nullable{Float64}(1.0)
    -
    -julia> x3 = Nullable([1, 2, 3])
    -Nullable{Array{Int64,1}}([1, 2, 3])

    Note the core distinction between these two ways of constructing a Nullable object: in one style, you provide a type, T, as a function parameter; in the other style, you provide a single value of type T as an argument.

    Checking if a Nullable object has a value

    You can check if a Nullable object has any value using isnull():

    julia> isnull(Nullable{Float64}())
    -true
    -
    -julia> isnull(Nullable(0.0))
    -false

    Safely accessing the value of a Nullable object

    You can safely access the value of a Nullable object using get():

    julia> get(Nullable{Float64}())
    -ERROR: NullException()
    -Stacktrace:
    - [1] get(::Nullable{Float64}) at ./nullable.jl:92
    -
    -julia> get(Nullable(1.0))
    -1.0

    If the value is not present, as it would be for Nullable{Float64}, a NullException error will be thrown. The error-throwing nature of the get() function ensures that any attempt to access a missing value immediately fails.

    In cases for which a reasonable default value exists that could be used when a Nullable object's value turns out to be missing, you can provide this default value as a second argument to get():

    julia> get(Nullable{Float64}(), 0.0)
    -0.0
    -
    -julia> get(Nullable(1.0), 0.0)
    -1.0
    Tip

    Make sure the type of the default value passed to get() and that of the Nullable object match to avoid type instability, which could hurt performance. Use convert() manually if needed.

    Performing operations on Nullable objects

    Nullable objects represent values that are possibly missing, and it is possible to write all code using these objects by first testing to see if the value is missing with isnull(), and then doing an appropriate action. However, there are some common use cases where the code could be more concise or clear by using a higher-order function.

    The map function takes as arguments a function f and a Nullable value x. It produces a Nullable:

    • If x is a missing value, then it produces a missing value;

    • If x has a value, then it produces a Nullable containing f(get(x)) as value.

    This is useful for performing simple operations on values that might be missing if the desired behaviour is to simply propagate the missing values forward.

    The filter function takes as arguments a predicate function p (that is, a function returning a boolean) and a Nullable value x. It produces a Nullable value:

    • If x is a missing value, then it produces a missing value;

    • If p(get(x)) is true, then it produces the original value x;

    • If p(get(x)) is false, then it produces a missing value.

    In this way, filter can be thought of as selecting only allowable values, and converting non-allowable values to missing values.

    While map and filter are useful in specific cases, by far the most useful higher-order function is broadcast, which can handle a wide variety of cases, including making existing operations work and propagate Nullables. An example will motivate the need for broadcast. Suppose we have a function that computes the greater of two real roots of a quadratic equation, using the quadratic formula:

    julia> root(a::Real, b::Real, c::Real) = (-b + √(b^2 - 4a*c)) / 2a
    -root (generic function with 1 method)

    We may verify that the result of root(1, -9, 20) is 5.0, as we expect, since 5.0 is the greater of two real roots of the quadratic equation.

    Suppose now that we want to find the greatest real root of a quadratic equations where the coefficients might be missing values. Having missing values in datasets is a common occurrence in real-world data, and so it is important to be able to deal with them. But we cannot find the roots of an equation if we do not know all the coefficients. The best solution to this will depend on the particular use case; perhaps we should throw an error. However, for this example, we will assume that the best solution is to propagate the missing values forward; that is, if any input is missing, we simply produce a missing output.

    The broadcast() function makes this task easy; we can simply pass the root function we wrote to broadcast:

    julia> broadcast(root, Nullable(1), Nullable(-9), Nullable(20))
    -Nullable{Float64}(5.0)
    -
    -julia> broadcast(root, Nullable(1), Nullable{Int}(), Nullable{Int}())
    -Nullable{Float64}()
    -
    -julia> broadcast(root, Nullable{Int}(), Nullable(-9), Nullable(20))
    -Nullable{Float64}()

    If one or more of the inputs is missing, then the output of broadcast() will be missing.

    There exists special syntactic sugar for the broadcast() function using a dot notation:

    julia> root.(Nullable(1), Nullable(-9), Nullable(20))
    -Nullable{Float64}(5.0)

    In particular, the regular arithmetic operators can be broadcast() conveniently using .-prefixed operators:

    julia> Nullable(2) ./ Nullable(3) .+ Nullable(1.0)
    -Nullable{Float64}(1.66667)
    diff --git a/julia-0.6.3/share/doc/julia/html/en/manual/unicode-input.html b/julia-0.6.3/share/doc/julia/html/en/manual/unicode-input.html deleted file mode 100644 index 0c49b3d..0000000 --- a/julia-0.6.3/share/doc/julia/html/en/manual/unicode-input.html +++ /dev/null @@ -1,9 +0,0 @@ - -Unicode Input · The Julia Language

    Unicode Input

    Unicode Input

    The following table lists Unicode characters that can be entered via tab completion of LaTeX-like abbreviations in the Julia REPL (and in various other editing environments). You can also get information on how to type a symbol by entering it in the REPL help, i.e. by typing ? and then entering the symbol in the REPL (e.g., by copy-paste from somewhere you saw the symbol).

    Warning

    This table may appear to contain missing characters in the second column, or even show characters that are inconsistent with the characters as they are rendered in the Julia REPL. In these cases, users are strongly advised to check their choice of fonts in their browser and REPL environment, as there are known issues with glyphs in many fonts.

    Code point(s)Character(s)Tab completion sequence(s)Unicode name(s)
    U+000A1¡\textexclamdownInverted Exclamation Mark
    U+000A3£\sterlingPound Sign
    U+000A5¥\yenYen Sign
    U+000A6¦\textbrokenbarBroken Bar / Broken Vertical Bar
    U+000A7§\SSection Sign
    U+000A8¨\textasciidieresisDiaeresis / Spacing Diaeresis
    U+000A9©\copyright, \:copyright:Copyright Sign
    U+000AAª\textordfeminineFeminine Ordinal Indicator
    U+000AC¬\negNot Sign
    U+000AE®\circledR, \:registered:Registered Sign / Registered Trade Mark Sign
    U+000AF¯\textasciimacronMacron / Spacing Macron
    U+000B0°\degreeDegree Sign
    U+000B1±\pmPlus-minus Sign / Plus-or-minus Sign
    U+000B2²\^2Superscript Two / Superscript Digit Two
    U+000B3³\^3Superscript Three / Superscript Digit Three
    U+000B4´\textasciiacuteAcute Accent / Spacing Acute
    U+000B6\PPilcrow Sign / Paragraph Sign
    U+000B7·\cdotpMiddle Dot
    U+000B9¹\^1Superscript One / Superscript Digit One
    U+000BAº\textordmasculineMasculine Ordinal Indicator
    U+000BC¼\textonequarterVulgar Fraction One Quarter / Fraction One Quarter
    U+000BD½\textonehalfVulgar Fraction One Half / Fraction One Half
    U+000BE¾\textthreequartersVulgar Fraction Three Quarters / Fraction Three Quarters
    U+000BF¿\textquestiondownInverted Question Mark
    U+000C5Å\AALatin Capital Letter A With Ring Above / Latin Capital Letter A Ring
    U+000C6Æ\AELatin Capital Letter Ae / Latin Capital Letter A E
    U+000D0Ð\DHLatin Capital Letter Eth
    U+000D7×\timesMultiplication Sign
    U+000D8Ø\OLatin Capital Letter O With Stroke / Latin Capital Letter O Slash
    U+000DEÞ\THLatin Capital Letter Thorn
    U+000DFß\ssLatin Small Letter Sharp S
    U+000E5å\aaLatin Small Letter A With Ring Above / Latin Small Letter A Ring
    U+000E6æ\aeLatin Small Letter Ae / Latin Small Letter A E
    U+000F0ð\ethLatin Small Letter Eth
    U+000F7÷\divDivision Sign
    U+000F8ø\oLatin Small Letter O With Stroke / Latin Small Letter O Slash
    U+000FEþ\thLatin Small Letter Thorn
    U+00110Đ\DJLatin Capital Letter D With Stroke / Latin Capital Letter D Bar
    U+00111đ\djLatin Small Letter D With Stroke / Latin Small Letter D Bar
    U+00127ħ\Elzxh, \hbarLatin Small Letter H With Stroke / Latin Small Letter H Bar
    U+00141Ł\LLatin Capital Letter L With Stroke / Latin Capital Letter L Slash
    U+00142ł\lLatin Small Letter L With Stroke / Latin Small Letter L Slash
    U+0014AŊ\NGLatin Capital Letter Eng
    U+0014Bŋ\ngLatin Small Letter Eng
    U+00152Œ\OELatin Capital Ligature Oe / Latin Capital Letter O E
    U+00153œ\oeLatin Small Ligature Oe / Latin Small Letter O E
    U+00195ƕ\texthvligLatin Small Letter Hv / Latin Small Letter H V
    U+0019Eƞ\textnrlegLatin Small Letter N With Long Right Leg
    U+001B5Ƶ\ZbarLatin Capital Letter Z With Stroke / Latin Capital Letter Z Bar
    U+001C2ǂ\textdoublepipeLatin Letter Alveolar Click / Latin Letter Pipe Double Bar
    U+00250ɐ\ElztrnaLatin Small Letter Turned A
    U+00252ɒ\ElztrnsaLatin Small Letter Turned Alpha / Latin Small Letter Turned Script A
    U+00254ɔ\ElzopenoLatin Small Letter Open O
    U+00256ɖ\ElzrtldLatin Small Letter D With Tail / Latin Small Letter D Retroflex Hook
    U+00259ə\ElzschwaLatin Small Letter Schwa
    U+00263ɣ\ElzpgammaLatin Small Letter Gamma
    U+00264ɤ\ElzpbgamLatin Small Letter Rams Horn / Latin Small Letter Baby Gamma
    U+00265ɥ\ElztrnhLatin Small Letter Turned H
    U+0026Cɬ\ElzbtdlLatin Small Letter L With Belt / Latin Small Letter L Belt
    U+0026Dɭ\ElzrtllLatin Small Letter L With Retroflex Hook / Latin Small Letter L Retroflex Hook
    U+0026Fɯ\ElztrnmLatin Small Letter Turned M
    U+00270ɰ\ElztrnmlrLatin Small Letter Turned M With Long Leg
    U+00271ɱ\ElzltlmrLatin Small Letter M With Hook / Latin Small Letter M Hook
    U+00272ɲ\ElzltlnLatin Small Letter N With Left Hook / Latin Small Letter N Hook
    U+00273ɳ\ElzrtlnLatin Small Letter N With Retroflex Hook / Latin Small Letter N Retroflex Hook
    U+00277ɷ\ElzclomegLatin Small Letter Closed Omega
    U+00278ɸ\textphiLatin Small Letter Phi
    U+00279ɹ\ElztrnrLatin Small Letter Turned R
    U+0027Aɺ\ElztrnrlLatin Small Letter Turned R With Long Leg
    U+0027Bɻ\ElzrttrnrLatin Small Letter Turned R With Hook / Latin Small Letter Turned R Hook
    U+0027Cɼ\ElzrlLatin Small Letter R With Long Leg
    U+0027Dɽ\ElzrtlrLatin Small Letter R With Tail / Latin Small Letter R Hook
    U+0027Eɾ\ElzfhrLatin Small Letter R With Fishhook / Latin Small Letter Fishhook R
    U+00282ʂ\ElzrtlsLatin Small Letter S With Hook / Latin Small Letter S Hook
    U+00283ʃ\ElzeshLatin Small Letter Esh
    U+00287ʇ\ElztrntLatin Small Letter Turned T
    U+00288ʈ\ElzrtltLatin Small Letter T With Retroflex Hook / Latin Small Letter T Retroflex Hook
    U+0028Aʊ\ElzpupsilLatin Small Letter Upsilon
    U+0028Bʋ\ElzpscrvLatin Small Letter V With Hook / Latin Small Letter Script V
    U+0028Cʌ\ElzinvvLatin Small Letter Turned V
    U+0028Dʍ\ElzinvwLatin Small Letter Turned W
    U+0028Eʎ\ElztrnyLatin Small Letter Turned Y
    U+00290ʐ\ElzrtlzLatin Small Letter Z With Retroflex Hook / Latin Small Letter Z Retroflex Hook
    U+00292ʒ\ElzyoghLatin Small Letter Ezh / Latin Small Letter Yogh
    U+00294ʔ\ElzglstLatin Letter Glottal Stop
    U+00295ʕ\ElzreglstLatin Letter Pharyngeal Voiced Fricative / Latin Letter Reversed Glottal Stop
    U+00296ʖ\ElzinglstLatin Letter Inverted Glottal Stop
    U+0029Eʞ\textturnkLatin Small Letter Turned K
    U+002A4ʤ\ElzdyoghLatin Small Letter Dezh Digraph / Latin Small Letter D Yogh
    U+002A7ʧ\ElzteshLatin Small Letter Tesh Digraph / Latin Small Letter T Esh
    U+002B0ʰ\^hModifier Letter Small H
    U+002B2ʲ\^jModifier Letter Small J
    U+002B3ʳ\^rModifier Letter Small R
    U+002B7ʷ\^wModifier Letter Small W
    U+002B8ʸ\^yModifier Letter Small Y
    U+002BCʼ\raspModifier Letter Apostrophe
    U+002C7ˇ\textasciicaronCaron / Modifier Letter Hacek
    U+002C8ˈ\ElzvertsModifier Letter Vertical Line
    U+002CCˌ\ElzvertiModifier Letter Low Vertical Line
    U+002D0ː\ElzlmrkModifier Letter Triangular Colon
    U+002D1ˑ\ElzhlmrkModifier Letter Half Triangular Colon
    U+002D2˒\ElzsbrhrModifier Letter Centred Right Half Ring / Modifier Letter Centered Right Half Ring
    U+002D3˓\ElzsblhrModifier Letter Centred Left Half Ring / Modifier Letter Centered Left Half Ring
    U+002D4˔\ElzraisModifier Letter Up Tack
    U+002D5˕\ElzlowModifier Letter Down Tack
    U+002D8˘\uBreve / Spacing Breve
    U+002DC˜\texttildelowSmall Tilde / Spacing Tilde
    U+002E1ˡ\^lModifier Letter Small L
    U+002E2ˢ\^sModifier Letter Small S
    U+002E3ˣ\^xModifier Letter Small X
    U+00300◌̀\graveCombining Grave Accent / Non-spacing Grave
    U+00301◌́\acuteCombining Acute Accent / Non-spacing Acute
    U+00302◌̂\hatCombining Circumflex Accent / Non-spacing Circumflex
    U+00303◌̃\tildeCombining Tilde / Non-spacing Tilde
    U+00304◌̄\barCombining Macron / Non-spacing Macron
    U+00305◌̅\overbarCombining Overline / Non-spacing Overscore
    U+00306◌̆\breveCombining Breve / Non-spacing Breve
    U+00307◌̇\dotCombining Dot Above / Non-spacing Dot Above
    U+00308◌̈\ddotCombining Diaeresis / Non-spacing Diaeresis
    U+00309◌̉\ovhookCombining Hook Above / Non-spacing Hook Above
    U+0030A◌̊\ocircCombining Ring Above / Non-spacing Ring Above
    U+0030B◌̋\HCombining Double Acute Accent / Non-spacing Double Acute
    U+0030C◌̌\checkCombining Caron / Non-spacing Hacek
    U+00310◌̐\candraCombining Candrabindu / Non-spacing Candrabindu
    U+00312◌̒\oturnedcommaCombining Turned Comma Above / Non-spacing Turned Comma Above
    U+00315◌̕\ocommatoprightCombining Comma Above Right / Non-spacing Comma Above Right
    U+0031A◌̚\droangCombining Left Angle Above / Non-spacing Left Angle Above
    U+00321◌̡\ElzpalhCombining Palatalized Hook Below / Non-spacing Palatalized Hook Below
    U+00322◌̢\ElzrhCombining Retroflex Hook Below / Non-spacing Retroflex Hook Below
    U+00327◌̧\cCombining Cedilla / Non-spacing Cedilla
    U+00328◌̨\kCombining Ogonek / Non-spacing Ogonek
    U+0032A◌̪\ElzsbbrgCombining Bridge Below / Non-spacing Bridge Below
    U+00330◌̰\wideutildeCombining Tilde Below / Non-spacing Tilde Below
    U+00332◌̲\underbarCombining Low Line / Non-spacing Underscore
    U+00335◌̵\ElzxlCombining Short Stroke Overlay / Non-spacing Short Bar Overlay
    U+00336◌̶\Elzbar, \soutCombining Long Stroke Overlay / Non-spacing Long Bar Overlay
    U+00338◌̸\notCombining Long Solidus Overlay / Non-spacing Long Slash Overlay
    U+0034D◌͍\underleftrightarrowCombining Left Right Arrow Below
    U+00391Α\AlphaGreek Capital Letter Alpha
    U+00392Β\BetaGreek Capital Letter Beta
    U+00393Γ\GammaGreek Capital Letter Gamma
    U+00394Δ\DeltaGreek Capital Letter Delta
    U+00395Ε\EpsilonGreek Capital Letter Epsilon
    U+00396Ζ\ZetaGreek Capital Letter Zeta
    U+00397Η\EtaGreek Capital Letter Eta
    U+00398Θ\ThetaGreek Capital Letter Theta
    U+00399Ι\IotaGreek Capital Letter Iota
    U+0039AΚ\KappaGreek Capital Letter Kappa
    U+0039BΛ\LambdaGreek Capital Letter Lamda / Greek Capital Letter Lambda
    U+0039CΜ\upMuGreek Capital Letter Mu
    U+0039DΝ\upNuGreek Capital Letter Nu
    U+0039EΞ\XiGreek Capital Letter Xi
    U+0039FΟ\upOmicronGreek Capital Letter Omicron
    U+003A0Π\PiGreek Capital Letter Pi
    U+003A1Ρ\RhoGreek Capital Letter Rho
    U+003A3Σ\SigmaGreek Capital Letter Sigma
    U+003A4Τ\TauGreek Capital Letter Tau
    U+003A5Υ\UpsilonGreek Capital Letter Upsilon
    U+003A6Φ\PhiGreek Capital Letter Phi
    U+003A7Χ\ChiGreek Capital Letter Chi
    U+003A8Ψ\PsiGreek Capital Letter Psi
    U+003A9Ω\OmegaGreek Capital Letter Omega
    U+003B1α\alphaGreek Small Letter Alpha
    U+003B2β\betaGreek Small Letter Beta
    U+003B3γ\gammaGreek Small Letter Gamma
    U+003B4δ\deltaGreek Small Letter Delta
    U+003B5ε\upepsilon, \varepsilonGreek Small Letter Epsilon
    U+003B6ζ\zetaGreek Small Letter Zeta
    U+003B7η\etaGreek Small Letter Eta
    U+003B8θ\thetaGreek Small Letter Theta
    U+003B9ι\iotaGreek Small Letter Iota
    U+003BAκ\kappaGreek Small Letter Kappa
    U+003BBλ\lambdaGreek Small Letter Lamda / Greek Small Letter Lambda
    U+003BCμ\muGreek Small Letter Mu
    U+003BDν\nuGreek Small Letter Nu
    U+003BEξ\xiGreek Small Letter Xi
    U+003BFο\upomicronGreek Small Letter Omicron
    U+003C0π\piGreek Small Letter Pi
    U+003C1ρ\rhoGreek Small Letter Rho
    U+003C2ς\varsigmaGreek Small Letter Final Sigma
    U+003C3σ\sigmaGreek Small Letter Sigma
    U+003C4τ\tauGreek Small Letter Tau
    U+003C5υ\upsilonGreek Small Letter Upsilon
    U+003C6φ\varphiGreek Small Letter Phi
    U+003C7χ\chiGreek Small Letter Chi
    U+003C8ψ\psiGreek Small Letter Psi
    U+003C9ω\omegaGreek Small Letter Omega
    U+003D0ϐ\upvarbetaGreek Beta Symbol / Greek Small Letter Curled Beta
    U+003D1ϑ\varthetaGreek Theta Symbol / Greek Small Letter Script Theta
    U+003D5ϕ\phiGreek Phi Symbol / Greek Small Letter Script Phi
    U+003D6ϖ\varpiGreek Pi Symbol / Greek Small Letter Omega Pi
    U+003D8Ϙ\upoldKoppaGreek Letter Archaic Koppa
    U+003D9ϙ\upoldkoppaGreek Small Letter Archaic Koppa
    U+003DAϚ\StigmaGreek Letter Stigma / Greek Capital Letter Stigma
    U+003DBϛ\upstigmaGreek Small Letter Stigma
    U+003DCϜ\DigammaGreek Letter Digamma / Greek Capital Letter Digamma
    U+003DDϝ\digammaGreek Small Letter Digamma
    U+003DEϞ\KoppaGreek Letter Koppa / Greek Capital Letter Koppa
    U+003DFϟ\upkoppaGreek Small Letter Koppa
    U+003E0Ϡ\SampiGreek Letter Sampi / Greek Capital Letter Sampi
    U+003E1ϡ\upsampiGreek Small Letter Sampi
    U+003F0ϰ\varkappaGreek Kappa Symbol / Greek Small Letter Script Kappa
    U+003F1ϱ\varrhoGreek Rho Symbol / Greek Small Letter Tailed Rho
    U+003F4ϴ\textThetaGreek Capital Theta Symbol
    U+003F5ϵ\epsilonGreek Lunate Epsilon Symbol
    U+003F6϶\backepsilonGreek Reversed Lunate Epsilon Symbol
    U+01D2C\^AModifier Letter Capital A
    U+01D2E\^BModifier Letter Capital B
    U+01D30\^DModifier Letter Capital D
    U+01D31\^EModifier Letter Capital E
    U+01D33\^GModifier Letter Capital G
    U+01D34\^HModifier Letter Capital H
    U+01D35\^IModifier Letter Capital I
    U+01D36\^JModifier Letter Capital J
    U+01D37\^KModifier Letter Capital K
    U+01D38\^LModifier Letter Capital L
    U+01D39\^MModifier Letter Capital M
    U+01D3A\^NModifier Letter Capital N
    U+01D3C\^OModifier Letter Capital O
    U+01D3E\^PModifier Letter Capital P
    U+01D3Fᴿ\^RModifier Letter Capital R
    U+01D40\^TModifier Letter Capital T
    U+01D41\^UModifier Letter Capital U
    U+01D42\^WModifier Letter Capital W
    U+01D43\^aModifier Letter Small A
    U+01D45\^alphaModifier Letter Small Alpha
    U+01D47\^bModifier Letter Small B
    U+01D48\^dModifier Letter Small D
    U+01D49\^eModifier Letter Small E
    U+01D4B\^epsilonModifier Letter Small Open E
    U+01D4D\^gModifier Letter Small G
    U+01D4F\^kModifier Letter Small K
    U+01D50\^mModifier Letter Small M
    U+01D52\^oModifier Letter Small O
    U+01D56\^pModifier Letter Small P
    U+01D57\^tModifier Letter Small T
    U+01D58\^uModifier Letter Small U
    U+01D5B\^vModifier Letter Small V
    U+01D5D\^betaModifier Letter Small Beta
    U+01D5E\^gammaModifier Letter Small Greek Gamma
    U+01D5F\^deltaModifier Letter Small Delta
    U+01D60\^phiModifier Letter Small Greek Phi
    U+01D61\^chiModifier Letter Small Chi
    U+01D62\_iLatin Subscript Small Letter I
    U+01D63\_rLatin Subscript Small Letter R
    U+01D64\_uLatin Subscript Small Letter U
    U+01D65\_vLatin Subscript Small Letter V
    U+01D66\_betaGreek Subscript Small Letter Beta
    U+01D67\_gammaGreek Subscript Small Letter Gamma
    U+01D68\_rhoGreek Subscript Small Letter Rho
    U+01D69\_phiGreek Subscript Small Letter Phi
    U+01D6A\_chiGreek Subscript Small Letter Chi
    U+01D9C\^cModifier Letter Small C
    U+01DA0\^fModifier Letter Small F
    U+01DA5\^iotaModifier Letter Small Iota
    U+01DB2\^PhiModifier Letter Small Phi
    U+01DBB\^zModifier Letter Small Z
    U+01DBFᶿ\^thetaModifier Letter Small Theta
    U+02002\enspaceEn Space
    U+02003\quadEm Space
    U+02005\thickspaceFour-per-em Space
    U+02009\thinspaceThin Space
    U+0200A\hspaceHair Space
    U+02013\endashEn Dash
    U+02014\emdashEm Dash
    U+02016\VertDouble Vertical Line / Double Vertical Bar
    U+02018\lqLeft Single Quotation Mark / Single Turned Comma Quotation Mark
    U+02019\rqRight Single Quotation Mark / Single Comma Quotation Mark
    U+0201B\ElzreaposSingle High-reversed-9 Quotation Mark / Single Reversed Comma Quotation Mark
    U+0201C\textquotedblleftLeft Double Quotation Mark / Double Turned Comma Quotation Mark
    U+0201D\textquotedblrightRight Double Quotation Mark / Double Comma Quotation Mark
    U+02020\daggerDagger
    U+02021\ddaggerDouble Dagger
    U+02022\bulletBullet
    U+02026\dots, \ldotsHorizontal Ellipsis
    U+02030\textperthousandPer Mille Sign
    U+02031\textpertenthousandPer Ten Thousand Sign
    U+02032\primePrime
    U+02033\pprimeDouble Prime
    U+02034\ppprimeTriple Prime
    U+02035\backprimeReversed Prime
    U+02036\backpprimeReversed Double Prime
    U+02037\backppprimeReversed Triple Prime
    U+02039\guilsinglleftSingle Left-pointing Angle Quotation Mark / Left Pointing Single Guillemet
    U+0203A\guilsinglrightSingle Right-pointing Angle Quotation Mark / Right Pointing Single Guillemet
    U+0203C\:bangbang:Double Exclamation Mark
    U+02040\tieconcatCharacter Tie
    U+02049\:interrobang:Exclamation Question Mark
    U+02057\pppprimeQuadruple Prime
    U+02060\nolinebreakWord Joiner
    U+02070\^0Superscript Zero / Superscript Digit Zero
    U+02071\^iSuperscript Latin Small Letter I
    U+02074\^4Superscript Four / Superscript Digit Four
    U+02075\^5Superscript Five / Superscript Digit Five
    U+02076\^6Superscript Six / Superscript Digit Six
    U+02077\^7Superscript Seven / Superscript Digit Seven
    U+02078\^8Superscript Eight / Superscript Digit Eight
    U+02079\^9Superscript Nine / Superscript Digit Nine
    U+0207A\^+Superscript Plus Sign
    U+0207B\^-Superscript Minus / Superscript Hyphen-minus
    U+0207C\^=Superscript Equals Sign
    U+0207D\^(Superscript Left Parenthesis / Superscript Opening Parenthesis
    U+0207E\^)Superscript Right Parenthesis / Superscript Closing Parenthesis
    U+0207F\^nSuperscript Latin Small Letter N
    U+02080\_0Subscript Zero / Subscript Digit Zero
    U+02081\_1Subscript One / Subscript Digit One
    U+02082\_2Subscript Two / Subscript Digit Two
    U+02083\_3Subscript Three / Subscript Digit Three
    U+02084\_4Subscript Four / Subscript Digit Four
    U+02085\_5Subscript Five / Subscript Digit Five
    U+02086\_6Subscript Six / Subscript Digit Six
    U+02087\_7Subscript Seven / Subscript Digit Seven
    U+02088\_8Subscript Eight / Subscript Digit Eight
    U+02089\_9Subscript Nine / Subscript Digit Nine
    U+0208A\_+Subscript Plus Sign
    U+0208B\_-Subscript Minus / Subscript Hyphen-minus
    U+0208C\_=Subscript Equals Sign
    U+0208D\_(Subscript Left Parenthesis / Subscript Opening Parenthesis
    U+0208E\_)Subscript Right Parenthesis / Subscript Closing Parenthesis
    U+02090\_aLatin Subscript Small Letter A
    U+02091\_eLatin Subscript Small Letter E
    U+02092\_oLatin Subscript Small Letter O
    U+02093\_xLatin Subscript Small Letter X
    U+02094\_schwaLatin Subscript Small Letter Schwa
    U+02095\_hLatin Subscript Small Letter H
    U+02096\_kLatin Subscript Small Letter K
    U+02097\_lLatin Subscript Small Letter L
    U+02098\_mLatin Subscript Small Letter M
    U+02099\_nLatin Subscript Small Letter N
    U+0209A\_pLatin Subscript Small Letter P
    U+0209B\_sLatin Subscript Small Letter S
    U+0209C\_tLatin Subscript Small Letter T
    U+020A7\ElzpesPeseta Sign
    U+020AC\euroEuro Sign
    U+020D0◌⃐\leftharpoonaccentCombining Left Harpoon Above / Non-spacing Left Harpoon Above
    U+020D1◌⃑\rightharpoonaccentCombining Right Harpoon Above / Non-spacing Right Harpoon Above
    U+020D2◌⃒\vertoverlayCombining Long Vertical Line Overlay / Non-spacing Long Vertical Bar Overlay
    U+020D6◌⃖\overleftarrowCombining Left Arrow Above / Non-spacing Left Arrow Above
    U+020D7◌⃗\vecCombining Right Arrow Above / Non-spacing Right Arrow Above
    U+020DB◌⃛\dddotCombining Three Dots Above / Non-spacing Three Dots Above
    U+020DC◌⃜\ddddotCombining Four Dots Above / Non-spacing Four Dots Above
    U+020DD◌⃝\enclosecircleCombining Enclosing Circle / Enclosing Circle
    U+020DE◌⃞\enclosesquareCombining Enclosing Square / Enclosing Square
    U+020DF◌⃟\enclosediamondCombining Enclosing Diamond / Enclosing Diamond
    U+020E1◌⃡\overleftrightarrowCombining Left Right Arrow Above / Non-spacing Left Right Arrow Above
    U+020E4◌⃤\enclosetriangleCombining Enclosing Upward Pointing Triangle
    U+020E7◌⃧\annuityCombining Annuity Symbol
    U+020E8◌⃨\threeunderdotCombining Triple Underdot
    U+020E9◌⃩\widebridgeaboveCombining Wide Bridge Above
    U+020EC◌⃬\underrightharpoondownCombining Rightwards Harpoon With Barb Downwards
    U+020ED◌⃭\underleftharpoondownCombining Leftwards Harpoon With Barb Downwards
    U+020EE◌⃮\underleftarrowCombining Left Arrow Below
    U+020EF◌⃯\underrightarrowCombining Right Arrow Below
    U+020F0◌⃰\asteraccentCombining Asterisk Above
    U+02102\BbbCDouble-struck Capital C / Double-struck C
    U+02107\EulerconstEuler Constant / Eulers
    U+0210A\mscrgScript Small G
    U+0210B\mscrHScript Capital H / Script H
    U+0210C\mfrakHBlack-letter Capital H / Black-letter H
    U+0210D\BbbHDouble-struck Capital H / Double-struck H
    U+0210E\PlanckconstPlanck Constant
    U+0210F\hslashPlanck Constant Over Two Pi / Planck Constant Over 2 Pi
    U+02110\mscrIScript Capital I / Script I
    U+02111\ImBlack-letter Capital I / Black-letter I
    U+02112\mscrLScript Capital L / Script L
    U+02113\ellScript Small L
    U+02115\BbbNDouble-struck Capital N / Double-struck N
    U+02116\textnumeroNumero Sign / Numero
    U+02118\wpScript Capital P / Script P
    U+02119\BbbPDouble-struck Capital P / Double-struck P
    U+0211A\BbbQDouble-struck Capital Q / Double-struck Q
    U+0211B\mscrRScript Capital R / Script R
    U+0211C\ReBlack-letter Capital R / Black-letter R
    U+0211D\BbbRDouble-struck Capital R / Double-struck R
    U+0211E\ElzxratPrescription Take
    U+02122\texttrademark, \:tm:Trade Mark Sign / Trademark
    U+02124\BbbZDouble-struck Capital Z / Double-struck Z
    U+02127\mhoInverted Ohm Sign / Mho
    U+02128\mfrakZBlack-letter Capital Z / Black-letter Z
    U+02129\turnediotaTurned Greek Small Letter Iota
    U+0212B\AngstromAngstrom Sign / Angstrom Unit
    U+0212C\mscrBScript Capital B / Script B
    U+0212D\mfrakCBlack-letter Capital C / Black-letter C
    U+0212F\mscreScript Small E
    U+02130\mscrEScript Capital E / Script E
    U+02131\mscrFScript Capital F / Script F
    U+02132\FinvTurned Capital F / Turned F
    U+02133\mscrMScript Capital M / Script M
    U+02134\mscroScript Small O
    U+02135\alephAlef Symbol / First Transfinite Cardinal
    U+02136\bethBet Symbol / Second Transfinite Cardinal
    U+02137\gimelGimel Symbol / Third Transfinite Cardinal
    U+02138\dalethDalet Symbol / Fourth Transfinite Cardinal
    U+02139\:information_source:Information Source
    U+0213C\BbbpiDouble-struck Small Pi
    U+0213D\BbbgammaDouble-struck Small Gamma
    U+0213E\BbbGammaDouble-struck Capital Gamma
    U+0213F\BbbPiDouble-struck Capital Pi
    U+02140\bbsumDouble-struck N-ary Summation
    U+02141\GameTurned Sans-serif Capital G
    U+02142\sansLturnedTurned Sans-serif Capital L
    U+02143\sansLmirroredReversed Sans-serif Capital L
    U+02144\YupTurned Sans-serif Capital Y
    U+02145\mitBbbDDouble-struck Italic Capital D
    U+02146\mitBbbdDouble-struck Italic Small D
    U+02147\mitBbbeDouble-struck Italic Small E
    U+02148\mitBbbiDouble-struck Italic Small I
    U+02149\mitBbbjDouble-struck Italic Small J
    U+0214A\PropertyLineProperty Line
    U+0214B\upandTurned Ampersand
    U+02190\leftarrowLeftwards Arrow / Left Arrow
    U+02191\uparrowUpwards Arrow / Up Arrow
    U+02192\to, \rightarrowRightwards Arrow / Right Arrow
    U+02193\downarrowDownwards Arrow / Down Arrow
    U+02194\leftrightarrow, \:left_right_arrow:Left Right Arrow
    U+02195\updownarrow, \:arrow_up_down:Up Down Arrow
    U+02196\nwarrow, \:arrow_upper_left:North West Arrow / Upper Left Arrow
    U+02197\nearrow, \:arrow_upper_right:North East Arrow / Upper Right Arrow
    U+02198\searrow, \:arrow_lower_right:South East Arrow / Lower Right Arrow
    U+02199\swarrow, \:arrow_lower_left:South West Arrow / Lower Left Arrow
    U+0219A\nleftarrowLeftwards Arrow With Stroke / Left Arrow With Stroke
    U+0219B\nrightarrowRightwards Arrow With Stroke / Right Arrow With Stroke
    U+0219C\leftwavearrowLeftwards Wave Arrow / Left Wave Arrow
    U+0219D\rightwavearrowRightwards Wave Arrow / Right Wave Arrow
    U+0219E\twoheadleftarrowLeftwards Two Headed Arrow / Left Two Headed Arrow
    U+0219F\twoheaduparrowUpwards Two Headed Arrow / Up Two Headed Arrow
    U+021A0\twoheadrightarrowRightwards Two Headed Arrow / Right Two Headed Arrow
    U+021A1\twoheaddownarrowDownwards Two Headed Arrow / Down Two Headed Arrow
    U+021A2\leftarrowtailLeftwards Arrow With Tail / Left Arrow With Tail
    U+021A3\rightarrowtailRightwards Arrow With Tail / Right Arrow With Tail
    U+021A4\mapsfromLeftwards Arrow From Bar / Left Arrow From Bar
    U+021A5\mapsupUpwards Arrow From Bar / Up Arrow From Bar
    U+021A6\mapstoRightwards Arrow From Bar / Right Arrow From Bar
    U+021A7\mapsdownDownwards Arrow From Bar / Down Arrow From Bar
    U+021A8\updownarrowbarUp Down Arrow With Base
    U+021A9\hookleftarrow, \:leftwards_arrow_with_hook:Leftwards Arrow With Hook / Left Arrow With Hook
    U+021AA\hookrightarrow, \:arrow_right_hook:Rightwards Arrow With Hook / Right Arrow With Hook
    U+021AB\looparrowleftLeftwards Arrow With Loop / Left Arrow With Loop
    U+021AC\looparrowrightRightwards Arrow With Loop / Right Arrow With Loop
    U+021AD\leftrightsquigarrowLeft Right Wave Arrow
    U+021AE\nleftrightarrowLeft Right Arrow With Stroke
    U+021AF\downzigzagarrowDownwards Zigzag Arrow / Down Zigzag Arrow
    U+021B0\LshUpwards Arrow With Tip Leftwards / Up Arrow With Tip Left
    U+021B1\RshUpwards Arrow With Tip Rightwards / Up Arrow With Tip Right
    U+021B2\LdshDownwards Arrow With Tip Leftwards / Down Arrow With Tip Left
    U+021B3\RdshDownwards Arrow With Tip Rightwards / Down Arrow With Tip Right
    U+021B4\linefeedRightwards Arrow With Corner Downwards / Right Arrow With Corner Down
    U+021B5\carriagereturnDownwards Arrow With Corner Leftwards / Down Arrow With Corner Left
    U+021B6\curvearrowleftAnticlockwise Top Semicircle Arrow
    U+021B7\curvearrowrightClockwise Top Semicircle Arrow
    U+021B8\barovernorthwestarrowNorth West Arrow To Long Bar / Upper Left Arrow To Long Bar
    U+021B9\barleftarrowrightarrowbarLeftwards Arrow To Bar Over Rightwards Arrow To Bar / Left Arrow To Bar Over Right Arrow To Bar
    U+021BA\circlearrowleftAnticlockwise Open Circle Arrow
    U+021BB\circlearrowrightClockwise Open Circle Arrow
    U+021BC\leftharpoonupLeftwards Harpoon With Barb Upwards / Left Harpoon With Barb Up
    U+021BD\leftharpoondownLeftwards Harpoon With Barb Downwards / Left Harpoon With Barb Down
    U+021BE\upharpoonleftUpwards Harpoon With Barb Rightwards / Up Harpoon With Barb Right
    U+021BF\upharpoonrightUpwards Harpoon With Barb Leftwards / Up Harpoon With Barb Left
    U+021C0\rightharpoonupRightwards Harpoon With Barb Upwards / Right Harpoon With Barb Up
    U+021C1\rightharpoondownRightwards Harpoon With Barb Downwards / Right Harpoon With Barb Down
    U+021C2\downharpoonrightDownwards Harpoon With Barb Rightwards / Down Harpoon With Barb Right
    U+021C3\downharpoonleftDownwards Harpoon With Barb Leftwards / Down Harpoon With Barb Left
    U+021C4\rightleftarrowsRightwards Arrow Over Leftwards Arrow / Right Arrow Over Left Arrow
    U+021C5\dblarrowupdownUpwards Arrow Leftwards Of Downwards Arrow / Up Arrow Left Of Down Arrow
    U+021C6\leftrightarrowsLeftwards Arrow Over Rightwards Arrow / Left Arrow Over Right Arrow
    U+021C7\leftleftarrowsLeftwards Paired Arrows / Left Paired Arrows
    U+021C8\upuparrowsUpwards Paired Arrows / Up Paired Arrows
    U+021C9\rightrightarrowsRightwards Paired Arrows / Right Paired Arrows
    U+021CA\downdownarrowsDownwards Paired Arrows / Down Paired Arrows
    U+021CB\leftrightharpoonsLeftwards Harpoon Over Rightwards Harpoon / Left Harpoon Over Right Harpoon
    U+021CC\rightleftharpoonsRightwards Harpoon Over Leftwards Harpoon / Right Harpoon Over Left Harpoon
    U+021CD\nLeftarrowLeftwards Double Arrow With Stroke / Left Double Arrow With Stroke
    U+021CE\nLeftrightarrowLeft Right Double Arrow With Stroke
    U+021CF\nRightarrowRightwards Double Arrow With Stroke / Right Double Arrow With Stroke
    U+021D0\LeftarrowLeftwards Double Arrow / Left Double Arrow
    U+021D1\UparrowUpwards Double Arrow / Up Double Arrow
    U+021D2\RightarrowRightwards Double Arrow / Right Double Arrow
    U+021D3\DownarrowDownwards Double Arrow / Down Double Arrow
    U+021D4\LeftrightarrowLeft Right Double Arrow
    U+021D5\UpdownarrowUp Down Double Arrow
    U+021D6\NwarrowNorth West Double Arrow / Upper Left Double Arrow
    U+021D7\NearrowNorth East Double Arrow / Upper Right Double Arrow
    U+021D8\SearrowSouth East Double Arrow / Lower Right Double Arrow
    U+021D9\SwarrowSouth West Double Arrow / Lower Left Double Arrow
    U+021DA\LleftarrowLeftwards Triple Arrow / Left Triple Arrow
    U+021DB\RrightarrowRightwards Triple Arrow / Right Triple Arrow
    U+021DC\leftsquigarrowLeftwards Squiggle Arrow / Left Squiggle Arrow
    U+021DD\rightsquigarrowRightwards Squiggle Arrow / Right Squiggle Arrow
    U+021DE\nHuparrowUpwards Arrow With Double Stroke / Up Arrow With Double Stroke
    U+021DF\nHdownarrowDownwards Arrow With Double Stroke / Down Arrow With Double Stroke
    U+021E0\leftdasharrowLeftwards Dashed Arrow / Left Dashed Arrow
    U+021E1\updasharrowUpwards Dashed Arrow / Up Dashed Arrow
    U+021E2\rightdasharrowRightwards Dashed Arrow / Right Dashed Arrow
    U+021E3\downdasharrowDownwards Dashed Arrow / Down Dashed Arrow
    U+021E4\barleftarrowLeftwards Arrow To Bar / Left Arrow To Bar
    U+021E5\rightarrowbarRightwards Arrow To Bar / Right Arrow To Bar
    U+021E6\leftwhitearrowLeftwards White Arrow / White Left Arrow
    U+021E7\upwhitearrowUpwards White Arrow / White Up Arrow
    U+021E8\rightwhitearrowRightwards White Arrow / White Right Arrow
    U+021E9\downwhitearrowDownwards White Arrow / White Down Arrow
    U+021EA\whitearrowupfrombarUpwards White Arrow From Bar / White Up Arrow From Bar
    U+021F4\circleonrightarrowRight Arrow With Small Circle
    U+021F5\DownArrowUpArrowDownwards Arrow Leftwards Of Upwards Arrow
    U+021F6\rightthreearrowsThree Rightwards Arrows
    U+021F7\nvleftarrowLeftwards Arrow With Vertical Stroke
    U+021F8\nvrightarrowRightwards Arrow With Vertical Stroke
    U+021F9\nvleftrightarrowLeft Right Arrow With Vertical Stroke
    U+021FA\nVleftarrowLeftwards Arrow With Double Vertical Stroke
    U+021FB\nVrightarrowRightwards Arrow With Double Vertical Stroke
    U+021FC\nVleftrightarrowLeft Right Arrow With Double Vertical Stroke
    U+021FD\leftarrowtriangleLeftwards Open-headed Arrow
    U+021FE\rightarrowtriangleRightwards Open-headed Arrow
    U+021FF\leftrightarrowtriangleLeft Right Open-headed Arrow
    U+02200\forallFor All
    U+02201\complementComplement
    U+02202\partialPartial Differential
    U+02203\existsThere Exists
    U+02204\nexistsThere Does Not Exist
    U+02205\varnothing, \emptysetEmpty Set
    U+02206\incrementIncrement
    U+02207\del, \nablaNabla
    U+02208\inElement Of
    U+02209\notinNot An Element Of
    U+0220A\smallinSmall Element Of
    U+0220B\niContains As Member
    U+0220C\nniDoes Not Contain As Member
    U+0220D\smallniSmall Contains As Member
    U+0220E\QEDEnd Of Proof
    U+0220F\prodN-ary Product
    U+02210\coprodN-ary Coproduct
    U+02211\sumN-ary Summation
    U+02212\minusMinus Sign
    U+02213\mpMinus-or-plus Sign
    U+02214\dotplusDot Plus
    U+02216\setminusSet Minus
    U+02217\astAsterisk Operator
    U+02218\circRing Operator
    U+02219\vysmblkcircleBullet Operator
    U+0221A\surd, \sqrtSquare Root
    U+0221B\cbrtCube Root
    U+0221C\fourthrootFourth Root
    U+0221D\proptoProportional To
    U+0221E\inftyInfinity
    U+0221F\rightangleRight Angle
    U+02220\angleAngle
    U+02221\measuredangleMeasured Angle
    U+02222\sphericalangleSpherical Angle
    U+02223\midDivides
    U+02224\nmidDoes Not Divide
    U+02225\parallelParallel To
    U+02226\nparallelNot Parallel To
    U+02227\wedgeLogical And
    U+02228\veeLogical Or
    U+02229\capIntersection
    U+0222A\cupUnion
    U+0222B\intIntegral
    U+0222C\iintDouble Integral
    U+0222D\iiintTriple Integral
    U+0222E\ointContour Integral
    U+0222F\oiintSurface Integral
    U+02230\oiiintVolume Integral
    U+02231\clwintegralClockwise Integral
    U+02232\varointclockwiseClockwise Contour Integral
    U+02233\ointctrclockwiseAnticlockwise Contour Integral
    U+02234\thereforeTherefore
    U+02235\becauseBecause
    U+02237\ColonProportion
    U+02238\dotminusDot Minus
    U+0223A\dotsminusdotsGeometric Proportion
    U+0223B\kernelcontractionHomothetic
    U+0223C\simTilde Operator
    U+0223D\backsimReversed Tilde
    U+0223E\lazysinvInverted Lazy S
    U+0223F\sinewaveSine Wave
    U+02240\wrWreath Product
    U+02241\nsimNot Tilde
    U+02242\eqsimMinus Tilde
    U+02242 + U+00338≂̸\neqsimMinus Tilde + Combining Long Solidus Overlay / Non-spacing Long Slash Overlay
    U+02243\simeqAsymptotically Equal To
    U+02244\nsimeNot Asymptotically Equal To
    U+02245\congApproximately Equal To
    U+02246\approxnotequalApproximately But Not Actually Equal To
    U+02247\ncongNeither Approximately Nor Actually Equal To
    U+02248\approxAlmost Equal To
    U+02249\napproxNot Almost Equal To
    U+0224A\approxeqAlmost Equal Or Equal To
    U+0224B\tildetrplTriple Tilde
    U+0224C\allequalAll Equal To
    U+0224D\asympEquivalent To
    U+0224E\BumpeqGeometrically Equivalent To
    U+0224E + U+00338≎̸\nBumpeqGeometrically Equivalent To + Combining Long Solidus Overlay / Non-spacing Long Slash Overlay
    U+0224F\bumpeqDifference Between
    U+0224F + U+00338≏̸\nbumpeqDifference Between + Combining Long Solidus Overlay / Non-spacing Long Slash Overlay
    U+02250\doteqApproaches The Limit
    U+02251\DoteqGeometrically Equal To
    U+02252\fallingdotseqApproximately Equal To Or The Image Of
    U+02253\risingdotseqImage Of Or Approximately Equal To
    U+02254\coloneqColon Equals / Colon Equal
    U+02255\eqcolonEquals Colon / Equal Colon
    U+02256\eqcircRing In Equal To
    U+02257\circeqRing Equal To
    U+02258\arceqCorresponds To
    U+02259\wedgeqEstimates
    U+0225A\veeeqEquiangular To
    U+0225B\starequalStar Equals
    U+0225C\triangleqDelta Equal To
    U+0225D\eqdefEqual To By Definition
    U+0225E\measeqMeasured By
    U+0225F\questeqQuestioned Equal To
    U+02260\neNot Equal To
    U+02261\equivIdentical To
    U+02262\nequivNot Identical To
    U+02263\EquivStrictly Equivalent To
    U+02264\leLess-than Or Equal To / Less Than Or Equal To
    U+02265\geGreater-than Or Equal To / Greater Than Or Equal To
    U+02266\leqqLess-than Over Equal To / Less Than Over Equal To
    U+02267\geqqGreater-than Over Equal To / Greater Than Over Equal To
    U+02268\lneqqLess-than But Not Equal To / Less Than But Not Equal To
    U+02268 + U+0FE00≨︀\lvertneqqLess-than But Not Equal To / Less Than But Not Equal To + Variation Selector-1
    U+02269\gneqqGreater-than But Not Equal To / Greater Than But Not Equal To
    U+02269 + U+0FE00≩︀\gvertneqqGreater-than But Not Equal To / Greater Than But Not Equal To + Variation Selector-1
    U+0226A\llMuch Less-than / Much Less Than
    U+0226A + U+00338≪̸\NotLessLessMuch Less-than / Much Less Than + Combining Long Solidus Overlay / Non-spacing Long Slash Overlay
    U+0226B\ggMuch Greater-than / Much Greater Than
    U+0226B + U+00338≫̸\NotGreaterGreaterMuch Greater-than / Much Greater Than + Combining Long Solidus Overlay / Non-spacing Long Slash Overlay
    U+0226C\betweenBetween
    U+0226D\nasympNot Equivalent To
    U+0226E\nlessNot Less-than / Not Less Than
    U+0226F\ngtrNot Greater-than / Not Greater Than
    U+02270\nleqNeither Less-than Nor Equal To / Neither Less Than Nor Equal To
    U+02271\ngeqNeither Greater-than Nor Equal To / Neither Greater Than Nor Equal To
    U+02272\lesssimLess-than Or Equivalent To / Less Than Or Equivalent To
    U+02273\gtrsimGreater-than Or Equivalent To / Greater Than Or Equivalent To
    U+02274\nlesssimNeither Less-than Nor Equivalent To / Neither Less Than Nor Equivalent To
    U+02275\ngtrsimNeither Greater-than Nor Equivalent To / Neither Greater Than Nor Equivalent To
    U+02276\lessgtrLess-than Or Greater-than / Less Than Or Greater Than
    U+02277\gtrlessGreater-than Or Less-than / Greater Than Or Less Than
    U+02278\notlessgreaterNeither Less-than Nor Greater-than / Neither Less Than Nor Greater Than
    U+02279\notgreaterlessNeither Greater-than Nor Less-than / Neither Greater Than Nor Less Than
    U+0227A\precPrecedes
    U+0227B\succSucceeds
    U+0227C\preccurlyeqPrecedes Or Equal To
    U+0227D\succcurlyeqSucceeds Or Equal To
    U+0227E\precsimPrecedes Or Equivalent To
    U+0227E + U+00338≾̸\nprecsimPrecedes Or Equivalent To + Combining Long Solidus Overlay / Non-spacing Long Slash Overlay
    U+0227F\succsimSucceeds Or Equivalent To
    U+0227F + U+00338≿̸\nsuccsimSucceeds Or Equivalent To + Combining Long Solidus Overlay / Non-spacing Long Slash Overlay
    U+02280\nprecDoes Not Precede
    U+02281\nsuccDoes Not Succeed
    U+02282\subsetSubset Of
    U+02283\supsetSuperset Of
    U+02284\nsubsetNot A Subset Of
    U+02285\nsupsetNot A Superset Of
    U+02286\subseteqSubset Of Or Equal To
    U+02287\supseteqSuperset Of Or Equal To
    U+02288\nsubseteqNeither A Subset Of Nor Equal To
    U+02289\nsupseteqNeither A Superset Of Nor Equal To
    U+0228A\subsetneqSubset Of With Not Equal To / Subset Of Or Not Equal To
    U+0228A + U+0FE00⊊︀\varsubsetneqqSubset Of With Not Equal To / Subset Of Or Not Equal To + Variation Selector-1
    U+0228B\supsetneqSuperset Of With Not Equal To / Superset Of Or Not Equal To
    U+0228B + U+0FE00⊋︀\varsupsetneqSuperset Of With Not Equal To / Superset Of Or Not Equal To + Variation Selector-1
    U+0228D\cupdotMultiset Multiplication
    U+0228E\uplusMultiset Union
    U+0228F\sqsubsetSquare Image Of
    U+0228F + U+00338⊏̸\NotSquareSubsetSquare Image Of + Combining Long Solidus Overlay / Non-spacing Long Slash Overlay
    U+02290\sqsupsetSquare Original Of
    U+02290 + U+00338⊐̸\NotSquareSupersetSquare Original Of + Combining Long Solidus Overlay / Non-spacing Long Slash Overlay
    U+02291\sqsubseteqSquare Image Of Or Equal To
    U+02292\sqsupseteqSquare Original Of Or Equal To
    U+02293\sqcapSquare Cap
    U+02294\sqcupSquare Cup
    U+02295\oplusCircled Plus
    U+02296\ominusCircled Minus
    U+02297\otimesCircled Times
    U+02298\oslashCircled Division Slash
    U+02299\odotCircled Dot Operator
    U+0229A\circledcircCircled Ring Operator
    U+0229B\circledastCircled Asterisk Operator
    U+0229C\circledequalCircled Equals
    U+0229D\circleddashCircled Dash
    U+0229E\boxplusSquared Plus
    U+0229F\boxminusSquared Minus
    U+022A0\boxtimesSquared Times
    U+022A1\boxdotSquared Dot Operator
    U+022A2\vdashRight Tack
    U+022A3\dashvLeft Tack
    U+022A4\topDown Tack
    U+022A5\botUp Tack
    U+022A7\modelsModels
    U+022A8\vDashTrue
    U+022A9\VdashForces
    U+022AA\VvdashTriple Vertical Bar Right Turnstile
    U+022AB\VDashDouble Vertical Bar Double Right Turnstile
    U+022AC\nvdashDoes Not Prove
    U+022AD\nvDashNot True
    U+022AE\nVdashDoes Not Force
    U+022AF\nVDashNegated Double Vertical Bar Double Right Turnstile
    U+022B0\prurelPrecedes Under Relation
    U+022B1\scurelSucceeds Under Relation
    U+022B2\vartriangleleftNormal Subgroup Of
    U+022B3\vartrianglerightContains As Normal Subgroup
    U+022B4\trianglelefteqNormal Subgroup Of Or Equal To
    U+022B5\trianglerighteqContains As Normal Subgroup Or Equal To
    U+022B6\originalOriginal Of
    U+022B7\imageImage Of
    U+022B8\multimapMultimap
    U+022B9\hermitconjmatrixHermitian Conjugate Matrix
    U+022BA\intercalIntercalate
    U+022BB\veebar, \xorXor
    U+022BC\barwedgeNand
    U+022BD\barveeNor
    U+022BE\rightanglearcRight Angle With Arc
    U+022BF\varlrtriangleRight Triangle
    U+022C0\bigwedgeN-ary Logical And
    U+022C1\bigveeN-ary Logical Or
    U+022C2\bigcapN-ary Intersection
    U+022C3\bigcupN-ary Union
    U+022C4\diamondDiamond Operator
    U+022C5\cdotDot Operator
    U+022C6\starStar Operator
    U+022C7\divideontimesDivision Times
    U+022C8\bowtieBowtie
    U+022C9\ltimesLeft Normal Factor Semidirect Product
    U+022CA\rtimesRight Normal Factor Semidirect Product
    U+022CB\leftthreetimesLeft Semidirect Product
    U+022CC\rightthreetimesRight Semidirect Product
    U+022CD\backsimeqReversed Tilde Equals
    U+022CE\curlyveeCurly Logical Or
    U+022CF\curlywedgeCurly Logical And
    U+022D0\SubsetDouble Subset
    U+022D1\SupsetDouble Superset
    U+022D2\CapDouble Intersection
    U+022D3\CupDouble Union
    U+022D4\pitchforkPitchfork
    U+022D5\equalparallelEqual And Parallel To
    U+022D6\lessdotLess-than With Dot / Less Than With Dot
    U+022D7\gtrdotGreater-than With Dot / Greater Than With Dot
    U+022D8\verymuchlessVery Much Less-than / Very Much Less Than
    U+022D9\gggVery Much Greater-than / Very Much Greater Than
    U+022DA\lesseqgtrLess-than Equal To Or Greater-than / Less Than Equal To Or Greater Than
    U+022DB\gtreqlessGreater-than Equal To Or Less-than / Greater Than Equal To Or Less Than
    U+022DC\eqlessEqual To Or Less-than / Equal To Or Less Than
    U+022DD\eqgtrEqual To Or Greater-than / Equal To Or Greater Than
    U+022DE\curlyeqprecEqual To Or Precedes
    U+022DF\curlyeqsuccEqual To Or Succeeds
    U+022E0\npreccurlyeqDoes Not Precede Or Equal
    U+022E1\nsucccurlyeqDoes Not Succeed Or Equal
    U+022E2\nsqsubseteqNot Square Image Of Or Equal To
    U+022E3\nsqsupseteqNot Square Original Of Or Equal To
    U+022E4\sqsubsetneqSquare Image Of Or Not Equal To
    U+022E5\ElzsqspneSquare Original Of Or Not Equal To
    U+022E6\lnsimLess-than But Not Equivalent To / Less Than But Not Equivalent To
    U+022E7\gnsimGreater-than But Not Equivalent To / Greater Than But Not Equivalent To
    U+022E8\precnsimPrecedes But Not Equivalent To
    U+022E9\succnsimSucceeds But Not Equivalent To
    U+022EA\ntriangleleftNot Normal Subgroup Of
    U+022EB\ntrianglerightDoes Not Contain As Normal Subgroup
    U+022EC\ntrianglelefteqNot Normal Subgroup Of Or Equal To
    U+022ED\ntrianglerighteqDoes Not Contain As Normal Subgroup Or Equal
    U+022EE\vdotsVertical Ellipsis
    U+022EF\cdotsMidline Horizontal Ellipsis
    U+022F0\adotsUp Right Diagonal Ellipsis
    U+022F1\ddotsDown Right Diagonal Ellipsis
    U+022F2\disinElement Of With Long Horizontal Stroke
    U+022F3\varisinsElement Of With Vertical Bar At End Of Horizontal Stroke
    U+022F4\isinsSmall Element Of With Vertical Bar At End Of Horizontal Stroke
    U+022F5\isindotElement Of With Dot Above
    U+022F6\varisinobarElement Of With Overbar
    U+022F7\isinobarSmall Element Of With Overbar
    U+022F8\isinvbElement Of With Underbar
    U+022F9\isinEElement Of With Two Horizontal Strokes
    U+022FA\nisdContains With Long Horizontal Stroke
    U+022FB\varnisContains With Vertical Bar At End Of Horizontal Stroke
    U+022FC\nisSmall Contains With Vertical Bar At End Of Horizontal Stroke
    U+022FD\varniobarContains With Overbar
    U+022FE\niobarSmall Contains With Overbar
    U+022FF\bagmemberZ Notation Bag Membership
    U+02300\diameterDiameter Sign
    U+02302\houseHouse
    U+02305\varbarwedgeProjective
    U+02306\vardoublebarwedgePerspective
    U+02308\lceilLeft Ceiling
    U+02309\rceilRight Ceiling
    U+0230A\lfloorLeft Floor
    U+0230B\rfloorRight Floor
    U+02310\invnotReversed Not Sign
    U+02311\sqlozengeSquare Lozenge
    U+02312\proflineArc
    U+02313\profsurfSegment
    U+02315\recorderTelephone Recorder
    U+02317\viewdataViewdata Square
    U+02319\turnednotTurned Not Sign
    U+0231A\:watch:Watch
    U+0231B\:hourglass:Hourglass
    U+0231C\ulcornerTop Left Corner
    U+0231D\urcornerTop Right Corner
    U+0231E\llcornerBottom Left Corner
    U+0231F\lrcornerBottom Right Corner
    U+02322\frownFrown
    U+02323\smileSmile
    U+0232C\varhexagonlrbondsBenzene Ring
    U+02332\conictaperConical Taper
    U+02336\topbotApl Functional Symbol I-beam
    U+0233D\obarApl Functional Symbol Circle Stile
    U+0233F\APLnotslashApl Functional Symbol Slash Bar
    U+02340\APLnotbackslashApl Functional Symbol Backslash Bar
    U+02353\APLboxupcaretApl Functional Symbol Quad Up Caret
    U+02370\APLboxquestionApl Functional Symbol Quad Question
    U+02394\hexagonSoftware-function Symbol
    U+023A3\ElzdlcornLeft Square Bracket Lower Corner
    U+023B0\lmoustacheUpper Left Or Lower Right Curly Bracket Section
    U+023B1\rmoustacheUpper Right Or Lower Left Curly Bracket Section
    U+023B4\overbracketTop Square Bracket
    U+023B5\underbracketBottom Square Bracket
    U+023B6\bbrktbrkBottom Square Bracket Over Top Square Bracket
    U+023B7\sqrtbottomRadical Symbol Bottom
    U+023B8\lvboxlineLeft Vertical Box Line
    U+023B9\rvboxlineRight Vertical Box Line
    U+023CE\varcarriagereturnReturn Symbol
    U+023DE\overbraceTop Curly Bracket
    U+023DF\underbraceBottom Curly Bracket
    U+023E2\trapeziumWhite Trapezium
    U+023E3\benzenrBenzene Ring With Circle
    U+023E4\strnsStraightness
    U+023E5\fltnsFlatness
    U+023E6\accurrentAc Current
    U+023E7\elintersElectrical Intersection
    U+023E9\:fast_forward:Black Right-pointing Double Triangle
    U+023EA\:rewind:Black Left-pointing Double Triangle
    U+023EB\:arrow_double_up:Black Up-pointing Double Triangle
    U+023EC\:arrow_double_down:Black Down-pointing Double Triangle
    U+023F0\:alarm_clock:Alarm Clock
    U+023F3\:hourglass_flowing_sand:Hourglass With Flowing Sand
    U+02422\blanksymbolBlank Symbol / Blank
    U+02423\textvisiblespaceOpen Box
    U+024C2\:m:Circled Latin Capital Letter M
    U+024C8\circledSCircled Latin Capital Letter S
    U+02506\ElzdshfncBox Drawings Light Triple Dash Vertical / Forms Light Triple Dash Vertical
    U+02519\ElzsqfnwBox Drawings Up Light And Left Heavy / Forms Up Light And Left Heavy
    U+02571\diagupBox Drawings Light Diagonal Upper Right To Lower Left / Forms Light Diagonal Upper Right To Lower Left
    U+02572\diagdownBox Drawings Light Diagonal Upper Left To Lower Right / Forms Light Diagonal Upper Left To Lower Right
    U+02580\blockuphalfUpper Half Block
    U+02584\blocklowhalfLower Half Block
    U+02588\blockfullFull Block
    U+0258C\blocklefthalfLeft Half Block
    U+02590\blockrighthalfRight Half Block
    U+02591\blockqtrshadedLight Shade
    U+02592\blockhalfshadedMedium Shade
    U+02593\blockthreeqtrshadedDark Shade
    U+025A0\blacksquareBlack Square
    U+025A1\squareWhite Square
    U+025A2\squovalWhite Square With Rounded Corners
    U+025A3\blackinwhitesquareWhite Square Containing Black Small Square
    U+025A4\squarehfillSquare With Horizontal Fill
    U+025A5\squarevfillSquare With Vertical Fill
    U+025A6\squarehvfillSquare With Orthogonal Crosshatch Fill
    U+025A7\squarenwsefillSquare With Upper Left To Lower Right Fill
    U+025A8\squareneswfillSquare With Upper Right To Lower Left Fill
    U+025A9\squarecrossfillSquare With Diagonal Crosshatch Fill
    U+025AA\smblksquare, \:black_small_square:Black Small Square
    U+025AB\smwhtsquare, \:white_small_square:White Small Square
    U+025AC\hrectangleblackBlack Rectangle
    U+025AD\hrectangleWhite Rectangle
    U+025AE\vrectangleblackBlack Vertical Rectangle
    U+025AF\ElzvrectoWhite Vertical Rectangle
    U+025B0\parallelogramblackBlack Parallelogram
    U+025B1\parallelogramWhite Parallelogram
    U+025B2\bigblacktriangleupBlack Up-pointing Triangle / Black Up Pointing Triangle
    U+025B3\bigtriangleupWhite Up-pointing Triangle / White Up Pointing Triangle
    U+025B4\blacktriangleBlack Up-pointing Small Triangle / Black Up Pointing Small Triangle
    U+025B5\vartriangleWhite Up-pointing Small Triangle / White Up Pointing Small Triangle
    U+025B6\blacktriangleright, \:arrow_forward:Black Right-pointing Triangle / Black Right Pointing Triangle
    U+025B7\trianglerightWhite Right-pointing Triangle / White Right Pointing Triangle
    U+025B8\smallblacktrianglerightBlack Right-pointing Small Triangle / Black Right Pointing Small Triangle
    U+025B9\smalltrianglerightWhite Right-pointing Small Triangle / White Right Pointing Small Triangle
    U+025BA\blackpointerrightBlack Right-pointing Pointer / Black Right Pointing Pointer
    U+025BB\whitepointerrightWhite Right-pointing Pointer / White Right Pointing Pointer
    U+025BC\bigblacktriangledownBlack Down-pointing Triangle / Black Down Pointing Triangle
    U+025BD\bigtriangledownWhite Down-pointing Triangle / White Down Pointing Triangle
    U+025BE\blacktriangledownBlack Down-pointing Small Triangle / Black Down Pointing Small Triangle
    U+025BF\triangledownWhite Down-pointing Small Triangle / White Down Pointing Small Triangle
    U+025C0\blacktriangleleft, \:arrow_backward:Black Left-pointing Triangle / Black Left Pointing Triangle
    U+025C1\triangleleftWhite Left-pointing Triangle / White Left Pointing Triangle
    U+025C2\smallblacktriangleleftBlack Left-pointing Small Triangle / Black Left Pointing Small Triangle
    U+025C3\smalltriangleleftWhite Left-pointing Small Triangle / White Left Pointing Small Triangle
    U+025C4\blackpointerleftBlack Left-pointing Pointer / Black Left Pointing Pointer
    U+025C5\whitepointerleftWhite Left-pointing Pointer / White Left Pointing Pointer
    U+025C6\mdlgblkdiamondBlack Diamond
    U+025C7\mdlgwhtdiamondWhite Diamond
    U+025C8\blackinwhitediamondWhite Diamond Containing Black Small Diamond
    U+025C9\fisheyeFisheye
    U+025CA\lozengeLozenge
    U+025CB\bigcircWhite Circle
    U+025CC\dottedcircleDotted Circle
    U+025CD\circlevertfillCircle With Vertical Fill
    U+025CE\bullseyeBullseye
    U+025CF\mdlgblkcircleBlack Circle
    U+025D0\ElzcirflCircle With Left Half Black
    U+025D1\ElzcirfrCircle With Right Half Black
    U+025D2\ElzcirfbCircle With Lower Half Black
    U+025D3\circletophalfblackCircle With Upper Half Black
    U+025D4\circleurquadblackCircle With Upper Right Quadrant Black
    U+025D5\blackcircleulquadwhiteCircle With All But Upper Left Quadrant Black
    U+025D6\blacklefthalfcircleLeft Half Black Circle
    U+025D7\blackrighthalfcircleRight Half Black Circle
    U+025D8\ElzrvbullInverse Bullet
    U+025D9\inversewhitecircleInverse White Circle
    U+025DA\invwhiteupperhalfcircleUpper Half Inverse White Circle
    U+025DB\invwhitelowerhalfcircleLower Half Inverse White Circle
    U+025DC\ularcUpper Left Quadrant Circular Arc
    U+025DD\urarcUpper Right Quadrant Circular Arc
    U+025DE\lrarcLower Right Quadrant Circular Arc
    U+025DF\llarcLower Left Quadrant Circular Arc
    U+025E0\topsemicircleUpper Half Circle
    U+025E1\botsemicircleLower Half Circle
    U+025E2\lrblacktriangleBlack Lower Right Triangle
    U+025E3\llblacktriangleBlack Lower Left Triangle
    U+025E4\ulblacktriangleBlack Upper Left Triangle
    U+025E5\urblacktriangleBlack Upper Right Triangle
    U+025E6\smwhtcircleWhite Bullet
    U+025E7\ElzsqflSquare With Left Half Black
    U+025E8\ElzsqfrSquare With Right Half Black
    U+025E9\squareulblackSquare With Upper Left Diagonal Half Black
    U+025EA\ElzsqfseSquare With Lower Right Diagonal Half Black
    U+025EB\boxbarWhite Square With Vertical Bisecting Line
    U+025EC\trianglecdotWhite Up-pointing Triangle With Dot / White Up Pointing Triangle With Dot
    U+025ED\triangleleftblackUp-pointing Triangle With Left Half Black / Up Pointing Triangle With Left Half Black
    U+025EE\trianglerightblackUp-pointing Triangle With Right Half Black / Up Pointing Triangle With Right Half Black
    U+025EF\lgwhtcircleLarge Circle
    U+025F0\squareulquadWhite Square With Upper Left Quadrant
    U+025F1\squarellquadWhite Square With Lower Left Quadrant
    U+025F2\squarelrquadWhite Square With Lower Right Quadrant
    U+025F3\squareurquadWhite Square With Upper Right Quadrant
    U+025F4\circleulquadWhite Circle With Upper Left Quadrant
    U+025F5\circlellquadWhite Circle With Lower Left Quadrant
    U+025F6\circlelrquadWhite Circle With Lower Right Quadrant
    U+025F7\circleurquadWhite Circle With Upper Right Quadrant
    U+025F8\ultriangleUpper Left Triangle
    U+025F9\urtriangleUpper Right Triangle
    U+025FA\lltriangleLower Left Triangle
    U+025FB\mdwhtsquare, \:white_medium_square:White Medium Square
    U+025FC\mdblksquare, \:black_medium_square:Black Medium Square
    U+025FD\mdsmwhtsquare, \:white_medium_small_square:White Medium Small Square
    U+025FE\mdsmblksquare, \:black_medium_small_square:Black Medium Small Square
    U+025FF\lrtriangleLower Right Triangle
    U+02600\:sunny:Black Sun With Rays
    U+02601\:cloud:Cloud
    U+02605\bigstarBlack Star
    U+02606\bigwhitestarWhite Star
    U+02609\astrosunSun
    U+0260E\:phone:Black Telephone
    U+02611\:ballot_box_with_check:Ballot Box With Check
    U+02614\:umbrella:Umbrella With Rain Drops
    U+02615\:coffee:Hot Beverage
    U+0261D\:point_up:White Up Pointing Index
    U+02621\dangerCaution Sign
    U+0263A\:relaxed:White Smiling Face
    U+0263B\blacksmileyBlack Smiling Face
    U+0263C\sunWhite Sun With Rays
    U+0263D\rightmoonFirst Quarter Moon
    U+0263E\leftmoonLast Quarter Moon
    U+0263F\mercuryMercury
    U+02640\venus, \femaleFemale Sign
    U+02642\male, \marsMale Sign
    U+02643\jupiterJupiter
    U+02644\saturnSaturn
    U+02645\uranusUranus
    U+02646\neptuneNeptune
    U+02647\plutoPluto
    U+02648\aries, \:aries:Aries
    U+02649\taurus, \:taurus:Taurus
    U+0264A\gemini, \:gemini:Gemini
    U+0264B\cancer, \:cancer:Cancer
    U+0264C\leo, \:leo:Leo
    U+0264D\virgo, \:virgo:Virgo
    U+0264E\libra, \:libra:Libra
    U+0264F\scorpio, \:scorpius:Scorpius
    U+02650\sagittarius, \:sagittarius:Sagittarius
    U+02651\capricornus, \:capricorn:Capricorn
    U+02652\aquarius, \:aquarius:Aquarius
    U+02653\pisces, \:pisces:Pisces
    U+02660\spadesuit, \:spades:Black Spade Suit
    U+02661\heartsuitWhite Heart Suit
    U+02662\diamondsuitWhite Diamond Suit
    U+02663\clubsuit, \:clubs:Black Club Suit
    U+02664\varspadesuitWhite Spade Suit
    U+02665\varheartsuit, \:hearts:Black Heart Suit
    U+02666\vardiamondsuit, \:diamonds:Black Diamond Suit
    U+02667\varclubsuitWhite Club Suit
    U+02668\:hotsprings:Hot Springs
    U+02669\quarternoteQuarter Note
    U+0266A\eighthnoteEighth Note
    U+0266B\twonotesBeamed Eighth Notes / Barred Eighth Notes
    U+0266D\flatMusic Flat Sign / Flat
    U+0266E\naturalMusic Natural Sign / Natural
    U+0266F\sharpMusic Sharp Sign / Sharp
    U+0267B\:recycle:Black Universal Recycling Symbol
    U+0267E\acidfreePermanent Paper Sign
    U+0267F\:wheelchair:Wheelchair Symbol
    U+02680\diceiDie Face-1
    U+02681\diceiiDie Face-2
    U+02682\diceiiiDie Face-3
    U+02683\diceivDie Face-4
    U+02684\dicevDie Face-5
    U+02685\diceviDie Face-6
    U+02686\circledrightdotWhite Circle With Dot Right
    U+02687\circledtwodotsWhite Circle With Two Dots
    U+02688\blackcircledrightdotBlack Circle With White Dot Right
    U+02689\blackcircledtwodotsBlack Circle With Two White Dots
    U+02693\:anchor:Anchor
    U+026A0\:warning:Warning Sign
    U+026A1\:zap:High Voltage Sign
    U+026A5\HermaphroditeMale And Female Sign
    U+026AA\mdwhtcircle, \:white_circle:Medium White Circle
    U+026AB\mdblkcircle, \:black_circle:Medium Black Circle
    U+026AC\mdsmwhtcircleMedium Small White Circle
    U+026B2\neuterNeuter
    U+026BD\:soccer:Soccer Ball
    U+026BE\:baseball:Baseball
    U+026C4\:snowman:Snowman Without Snow
    U+026C5\:partly_sunny:Sun Behind Cloud
    U+026CE\:ophiuchus:Ophiuchus
    U+026D4\:no_entry:No Entry
    U+026EA\:church:Church
    U+026F2\:fountain:Fountain
    U+026F3\:golf:Flag In Hole
    U+026F5\:boat:Sailboat
    U+026FA\:tent:Tent
    U+026FD\:fuelpump:Fuel Pump
    U+02702\:scissors:Black Scissors
    U+02705\:white_check_mark:White Heavy Check Mark
    U+02708\:airplane:Airplane
    U+02709\:email:Envelope
    U+0270A\:fist:Raised Fist
    U+0270B\:hand:Raised Hand
    U+0270C\:v:Victory Hand
    U+0270F\:pencil2:Pencil
    U+02712\:black_nib:Black Nib
    U+02713\checkmarkCheck Mark
    U+02714\:heavy_check_mark:Heavy Check Mark
    U+02716\:heavy_multiplication_x:Heavy Multiplication X
    U+02720\malteseMaltese Cross
    U+02728\:sparkles:Sparkles
    U+0272A\circledstarCircled White Star
    U+02733\:eight_spoked_asterisk:Eight Spoked Asterisk
    U+02734\:eight_pointed_black_star:Eight Pointed Black Star
    U+02736\varstarSix Pointed Black Star
    U+0273D\dingasteriskHeavy Teardrop-spoked Asterisk
    U+02744\:snowflake:Snowflake
    U+02747\:sparkle:Sparkle
    U+0274C\:x:Cross Mark
    U+0274E\:negative_squared_cross_mark:Negative Squared Cross Mark
    U+02753\:question:Black Question Mark Ornament
    U+02754\:grey_question:White Question Mark Ornament
    U+02755\:grey_exclamation:White Exclamation Mark Ornament
    U+02757\:exclamation:Heavy Exclamation Mark Symbol
    U+02764\:heart:Heavy Black Heart
    U+02795\:heavy_plus_sign:Heavy Plus Sign
    U+02796\:heavy_minus_sign:Heavy Minus Sign
    U+02797\:heavy_division_sign:Heavy Division Sign
    U+0279B\draftingarrowDrafting Point Rightwards Arrow / Drafting Point Right Arrow
    U+027A1\:arrow_right:Black Rightwards Arrow / Black Right Arrow
    U+027B0\:curly_loop:Curly Loop
    U+027BF\:loop:Double Curly Loop
    U+027C0\threedangleThree Dimensional Angle
    U+027C1\whiteinwhitetriangleWhite Triangle Containing Small White Triangle
    U+027C2\perpPerpendicular
    U+027C8\bsolhsubReverse Solidus Preceding Subset
    U+027C9\suphsolSuperset Preceding Solidus
    U+027D1\wedgedotAnd With Dot
    U+027D2\upinElement Of Opening Upwards
    U+027D5\leftouterjoinLeft Outer Join
    U+027D6\rightouterjoinRight Outer Join
    U+027D7\fullouterjoinFull Outer Join
    U+027D8\bigbotLarge Up Tack
    U+027D9\bigtopLarge Down Tack
    U+027E6\llbracket, \openbracketleftMathematical Left White Square Bracket
    U+027E7\openbracketright, \rrbracketMathematical Right White Square Bracket
    U+027E8\langleMathematical Left Angle Bracket
    U+027E9\rangleMathematical Right Angle Bracket
    U+027F0\UUparrowUpwards Quadruple Arrow
    U+027F1\DDownarrowDownwards Quadruple Arrow
    U+027F5\longleftarrowLong Leftwards Arrow
    U+027F6\longrightarrowLong Rightwards Arrow
    U+027F7\longleftrightarrowLong Left Right Arrow
    U+027F8\impliedby, \LongleftarrowLong Leftwards Double Arrow
    U+027F9\implies, \LongrightarrowLong Rightwards Double Arrow
    U+027FA\Longleftrightarrow, \iffLong Left Right Double Arrow
    U+027FB\longmapsfromLong Leftwards Arrow From Bar
    U+027FC\longmapstoLong Rightwards Arrow From Bar
    U+027FD\LongmapsfromLong Leftwards Double Arrow From Bar
    U+027FE\LongmapstoLong Rightwards Double Arrow From Bar
    U+027FF\longrightsquigarrowLong Rightwards Squiggle Arrow
    U+02900\nvtwoheadrightarrowRightwards Two-headed Arrow With Vertical Stroke
    U+02901\nVtwoheadrightarrowRightwards Two-headed Arrow With Double Vertical Stroke
    U+02902\nvLeftarrowLeftwards Double Arrow With Vertical Stroke
    U+02903\nvRightarrowRightwards Double Arrow With Vertical Stroke
    U+02904\nvLeftrightarrowLeft Right Double Arrow With Vertical Stroke
    U+02905\twoheadmapstoRightwards Two-headed Arrow From Bar
    U+02906\MapsfromLeftwards Double Arrow From Bar
    U+02907\MapstoRightwards Double Arrow From Bar
    U+02908\downarrowbarredDownwards Arrow With Horizontal Stroke
    U+02909\uparrowbarredUpwards Arrow With Horizontal Stroke
    U+0290A\UuparrowUpwards Triple Arrow
    U+0290B\DdownarrowDownwards Triple Arrow
    U+0290C\leftbkarrowLeftwards Double Dash Arrow
    U+0290D\bkarowRightwards Double Dash Arrow
    U+0290E\leftdbkarrowLeftwards Triple Dash Arrow
    U+0290F\dbkarowRightwards Triple Dash Arrow
    U+02910\drbkarrowRightwards Two-headed Triple Dash Arrow
    U+02911\rightdotarrowRightwards Arrow With Dotted Stem
    U+02912\UpArrowBarUpwards Arrow To Bar
    U+02913\DownArrowBarDownwards Arrow To Bar
    U+02914\nvrightarrowtailRightwards Arrow With Tail With Vertical Stroke
    U+02915\nVrightarrowtailRightwards Arrow With Tail With Double Vertical Stroke
    U+02916\twoheadrightarrowtailRightwards Two-headed Arrow With Tail
    U+02917\nvtwoheadrightarrowtailRightwards Two-headed Arrow With Tail With Vertical Stroke
    U+02918\nVtwoheadrightarrowtailRightwards Two-headed Arrow With Tail With Double Vertical Stroke
    U+0291D\diamondleftarrowLeftwards Arrow To Black Diamond
    U+0291E\rightarrowdiamondRightwards Arrow To Black Diamond
    U+0291F\diamondleftarrowbarLeftwards Arrow From Bar To Black Diamond
    U+02920\barrightarrowdiamondRightwards Arrow From Bar To Black Diamond
    U+02925\hksearowSouth East Arrow With Hook
    U+02926\hkswarowSouth West Arrow With Hook
    U+02927\tonaNorth West Arrow And North East Arrow
    U+02928\toeaNorth East Arrow And South East Arrow
    U+02929\tosaSouth East Arrow And South West Arrow
    U+0292A\towaSouth West Arrow And North West Arrow
    U+0292B\rdiagovfdiagRising Diagonal Crossing Falling Diagonal
    U+0292C\fdiagovrdiagFalling Diagonal Crossing Rising Diagonal
    U+0292D\seovnearrowSouth East Arrow Crossing North East Arrow
    U+0292E\neovsearrowNorth East Arrow Crossing South East Arrow
    U+0292F\fdiagovnearrowFalling Diagonal Crossing North East Arrow
    U+02930\rdiagovsearrowRising Diagonal Crossing South East Arrow
    U+02931\neovnwarrowNorth East Arrow Crossing North West Arrow
    U+02932\nwovnearrowNorth West Arrow Crossing North East Arrow
    U+02934\:arrow_heading_up:Arrow Pointing Rightwards Then Curving Upwards
    U+02935\:arrow_heading_down:Arrow Pointing Rightwards Then Curving Downwards
    U+02942\ElzRlarrRightwards Arrow Above Short Leftwards Arrow
    U+02944\ElzrLarrShort Rightwards Arrow Above Leftwards Arrow
    U+02945\rightarrowplusRightwards Arrow With Plus Below
    U+02946\leftarrowplusLeftwards Arrow With Plus Below
    U+02947\ElzrarrxRightwards Arrow Through X
    U+02948\leftrightarrowcircleLeft Right Arrow Through Small Circle
    U+02949\twoheaduparrowcircleUpwards Two-headed Arrow From Small Circle
    U+0294A\leftrightharpoonupdownLeft Barb Up Right Barb Down Harpoon
    U+0294B\leftrightharpoondownupLeft Barb Down Right Barb Up Harpoon
    U+0294C\updownharpoonrightleftUp Barb Right Down Barb Left Harpoon
    U+0294D\updownharpoonleftrightUp Barb Left Down Barb Right Harpoon
    U+0294E\LeftRightVectorLeft Barb Up Right Barb Up Harpoon
    U+0294F\RightUpDownVectorUp Barb Right Down Barb Right Harpoon
    U+02950\DownLeftRightVectorLeft Barb Down Right Barb Down Harpoon
    U+02951\LeftUpDownVectorUp Barb Left Down Barb Left Harpoon
    U+02952\LeftVectorBarLeftwards Harpoon With Barb Up To Bar
    U+02953\RightVectorBarRightwards Harpoon With Barb Up To Bar
    U+02954\RightUpVectorBarUpwards Harpoon With Barb Right To Bar
    U+02955\RightDownVectorBarDownwards Harpoon With Barb Right To Bar
    U+02956\DownLeftVectorBarLeftwards Harpoon With Barb Down To Bar
    U+02957\DownRightVectorBarRightwards Harpoon With Barb Down To Bar
    U+02958\LeftUpVectorBarUpwards Harpoon With Barb Left To Bar
    U+02959\LeftDownVectorBarDownwards Harpoon With Barb Left To Bar
    U+0295A\LeftTeeVectorLeftwards Harpoon With Barb Up From Bar
    U+0295B\RightTeeVectorRightwards Harpoon With Barb Up From Bar
    U+0295C\RightUpTeeVectorUpwards Harpoon With Barb Right From Bar
    U+0295D\RightDownTeeVectorDownwards Harpoon With Barb Right From Bar
    U+0295E\DownLeftTeeVectorLeftwards Harpoon With Barb Down From Bar
    U+0295F\DownRightTeeVectorRightwards Harpoon With Barb Down From Bar
    U+02960\LeftUpTeeVectorUpwards Harpoon With Barb Left From Bar
    U+02961\LeftDownTeeVectorDownwards Harpoon With Barb Left From Bar
    U+02962\leftharpoonsupdownLeftwards Harpoon With Barb Up Above Leftwards Harpoon With Barb Down
    U+02963\upharpoonsleftrightUpwards Harpoon With Barb Left Beside Upwards Harpoon With Barb Right
    U+02964\rightharpoonsupdownRightwards Harpoon With Barb Up Above Rightwards Harpoon With Barb Down
    U+02965\downharpoonsleftrightDownwards Harpoon With Barb Left Beside Downwards Harpoon With Barb Right
    U+02966\leftrightharpoonsupLeftwards Harpoon With Barb Up Above Rightwards Harpoon With Barb Up
    U+02967\leftrightharpoonsdownLeftwards Harpoon With Barb Down Above Rightwards Harpoon With Barb Down
    U+02968\rightleftharpoonsupRightwards Harpoon With Barb Up Above Leftwards Harpoon With Barb Up
    U+02969\rightleftharpoonsdownRightwards Harpoon With Barb Down Above Leftwards Harpoon With Barb Down
    U+0296A\leftharpoonupdashLeftwards Harpoon With Barb Up Above Long Dash
    U+0296B\dashleftharpoondownLeftwards Harpoon With Barb Down Below Long Dash
    U+0296C\rightharpoonupdashRightwards Harpoon With Barb Up Above Long Dash
    U+0296D\dashrightharpoondownRightwards Harpoon With Barb Down Below Long Dash
    U+0296E\UpEquilibriumUpwards Harpoon With Barb Left Beside Downwards Harpoon With Barb Right
    U+0296F\ReverseUpEquilibriumDownwards Harpoon With Barb Left Beside Upwards Harpoon With Barb Right
    U+02970\RoundImpliesRight Double Arrow With Rounded Head
    U+02980\VvertTriple Vertical Bar Delimiter
    U+02986\ElroangRight White Parenthesis
    U+02999\ElzddfncDotted Fence
    U+0299B\measuredangleleftMeasured Angle Opening Left
    U+0299C\AngleRight Angle Variant With Square
    U+0299D\rightanglemdotMeasured Right Angle With Dot
    U+0299E\anglesAngle With S Inside
    U+0299F\angdnrAcute Angle
    U+029A0\ElzlpargtSpherical Angle Opening Left
    U+029A1\sphericalangleupSpherical Angle Opening Up
    U+029A2\turnangleTurned Angle
    U+029A3\revangleReversed Angle
    U+029A4\angleubarAngle With Underbar
    U+029A5\revangleubarReversed Angle With Underbar
    U+029A6\wideangledownOblique Angle Opening Up
    U+029A7\wideangleupOblique Angle Opening Down
    U+029A8\measanglerutoneMeasured Angle With Open Arm Ending In Arrow Pointing Up And Right
    U+029A9\measanglelutonwMeasured Angle With Open Arm Ending In Arrow Pointing Up And Left
    U+029AA\measanglerdtoseMeasured Angle With Open Arm Ending In Arrow Pointing Down And Right
    U+029AB\measangleldtoswMeasured Angle With Open Arm Ending In Arrow Pointing Down And Left
    U+029AC\measangleurtoneMeasured Angle With Open Arm Ending In Arrow Pointing Right And Up
    U+029AD\measangleultonwMeasured Angle With Open Arm Ending In Arrow Pointing Left And Up
    U+029AE\measangledrtoseMeasured Angle With Open Arm Ending In Arrow Pointing Right And Down
    U+029AF\measangledltoswMeasured Angle With Open Arm Ending In Arrow Pointing Left And Down
    U+029B0\revemptysetReversed Empty Set
    U+029B1\emptysetobarEmpty Set With Overbar
    U+029B2\emptysetocircEmpty Set With Small Circle Above
    U+029B3\emptysetoarrEmpty Set With Right Arrow Above
    U+029B4\emptysetoarrlEmpty Set With Left Arrow Above
    U+029B7\circledparallelCircled Parallel
    U+029B8\obslashCircled Reverse Solidus
    U+029BC\odotslashdotCircled Anticlockwise-rotated Division Sign
    U+029BE\circledwhitebulletCircled White Bullet
    U+029BF⦿\circledbulletCircled Bullet
    U+029C0\olessthanCircled Less-than
    U+029C1\ogreaterthanCircled Greater-than
    U+029C4\boxdiagSquared Rising Diagonal Slash
    U+029C5\boxbslashSquared Falling Diagonal Slash
    U+029C6\boxastSquared Asterisk
    U+029C7\boxcircleSquared Small Circle
    U+029CA\ElzLapTriangle With Dot Above
    U+029CB\ElzdefasTriangle With Underbar
    U+029CF\LeftTriangleBarLeft Triangle Beside Vertical Bar
    U+029CF + U+00338⧏̸\NotLeftTriangleBarLeft Triangle Beside Vertical Bar + Combining Long Solidus Overlay / Non-spacing Long Slash Overlay
    U+029D0\RightTriangleBarVertical Bar Beside Right Triangle
    U+029D0 + U+00338⧐̸\NotRightTriangleBarVertical Bar Beside Right Triangle + Combining Long Solidus Overlay / Non-spacing Long Slash Overlay
    U+029DF\dualmapDouble-ended Multimap
    U+029E1\lrtriangleeqIncreases As
    U+029E2\shuffleShuffle Product
    U+029E3\eparslEquals Sign And Slanted Parallel
    U+029E4\smeparslEquals Sign And Slanted Parallel With Tilde Above
    U+029E5\eqvparslIdentical To And Slanted Parallel
    U+029EB\blacklozengeBlack Lozenge
    U+029F4\RuleDelayedRule-delayed
    U+029F6\dsolSolidus With Overbar
    U+029F7\rsolbarReverse Solidus With Horizontal Stroke
    U+029FA\doubleplusDouble Plus
    U+029FB\tripleplusTriple Plus
    U+02A00\bigodotN-ary Circled Dot Operator
    U+02A01\bigoplusN-ary Circled Plus Operator
    U+02A02\bigotimesN-ary Circled Times Operator
    U+02A03\bigcupdotN-ary Union Operator With Dot
    U+02A04\biguplusN-ary Union Operator With Plus
    U+02A05\bigsqcapN-ary Square Intersection Operator
    U+02A06\bigsqcupN-ary Square Union Operator
    U+02A07\conjquantTwo Logical And Operator
    U+02A08\disjquantTwo Logical Or Operator
    U+02A09\bigtimesN-ary Times Operator
    U+02A0A\modtwosumModulo Two Sum
    U+02A0B\sumintSummation With Integral
    U+02A0C\iiiintQuadruple Integral Operator
    U+02A0D\intbarFinite Part Integral
    U+02A0E\intBarIntegral With Double Stroke
    U+02A0F\clockointIntegral Average With Slash
    U+02A10\cirfnintCirculation Function
    U+02A11\awintAnticlockwise Integration
    U+02A12\rppolintLine Integration With Rectangular Path Around Pole
    U+02A13\scpolintLine Integration With Semicircular Path Around Pole
    U+02A14\npolintLine Integration Not Including The Pole
    U+02A15\pointintIntegral Around A Point Operator
    U+02A16\sqrintQuaternion Integral Operator
    U+02A18\intxIntegral With Times Sign
    U+02A19\intcapIntegral With Intersection
    U+02A1A\intcupIntegral With Union
    U+02A1B\upintIntegral With Overbar
    U+02A1C\lowintIntegral With Underbar
    U+02A1D\JoinJoin
    U+02A22\ringplusPlus Sign With Small Circle Above
    U+02A23\plushatPlus Sign With Circumflex Accent Above
    U+02A24\simplusPlus Sign With Tilde Above
    U+02A25\plusdotPlus Sign With Dot Below
    U+02A26\plussimPlus Sign With Tilde Below
    U+02A27\plussubtwoPlus Sign With Subscript Two
    U+02A28\plustrifPlus Sign With Black Triangle
    U+02A29\commaminusMinus Sign With Comma Above
    U+02A2A\minusdotMinus Sign With Dot Below
    U+02A2B\minusfdotsMinus Sign With Falling Dots
    U+02A2C\minusrdotsMinus Sign With Rising Dots
    U+02A2D\opluslhrimPlus Sign In Left Half Circle
    U+02A2E\oplusrhrimPlus Sign In Right Half Circle
    U+02A2F\ElzTimesVector Or Cross Product
    U+02A30\dottimesMultiplication Sign With Dot Above
    U+02A31\timesbarMultiplication Sign With Underbar
    U+02A32\btimesSemidirect Product With Bottom Closed
    U+02A33\smashtimesSmash Product
    U+02A34\otimeslhrimMultiplication Sign In Left Half Circle
    U+02A35\otimesrhrimMultiplication Sign In Right Half Circle
    U+02A36\otimeshatCircled Multiplication Sign With Circumflex Accent
    U+02A37\OtimesMultiplication Sign In Double Circle
    U+02A38\odivCircled Division Sign
    U+02A39\triangleplusPlus Sign In Triangle
    U+02A3A\triangleminusMinus Sign In Triangle
    U+02A3B\triangletimesMultiplication Sign In Triangle
    U+02A3C\intprodInterior Product
    U+02A3D\intprodrRighthand Interior Product
    U+02A3F⨿\amalgAmalgamation Or Coproduct
    U+02A40\capdotIntersection With Dot
    U+02A41\uminusUnion With Minus Sign
    U+02A42\barcupUnion With Overbar
    U+02A43\barcapIntersection With Overbar
    U+02A44\capwedgeIntersection With Logical And
    U+02A45\cupveeUnion With Logical Or
    U+02A4A\twocupsUnion Beside And Joined With Union
    U+02A4B\twocapsIntersection Beside And Joined With Intersection
    U+02A4C\closedvarcupClosed Union With Serifs
    U+02A4D\closedvarcapClosed Intersection With Serifs
    U+02A4E\SqcapDouble Square Intersection
    U+02A4F\SqcupDouble Square Union
    U+02A50\closedvarcupsmashprodClosed Union With Serifs And Smash Product
    U+02A51\wedgeodotLogical And With Dot Above
    U+02A52\veeodotLogical Or With Dot Above
    U+02A53\ElzAndDouble Logical And
    U+02A54\ElzOrDouble Logical Or
    U+02A55\wedgeonwedgeTwo Intersecting Logical And
    U+02A56\ElOrTwo Intersecting Logical Or
    U+02A57\bigslopedveeSloping Large Or
    U+02A58\bigslopedwedgeSloping Large And
    U+02A5A\wedgemidvertLogical And With Middle Stem
    U+02A5B\veemidvertLogical Or With Middle Stem
    U+02A5C\midbarwedgeLogical And With Horizontal Dash
    U+02A5D\midbarveeLogical Or With Horizontal Dash
    U+02A5E\perspcorrespondLogical And With Double Overbar
    U+02A5F\ElzminhatLogical And With Underbar
    U+02A60\wedgedoublebarLogical And With Double Underbar
    U+02A61\varveebarSmall Vee With Underbar
    U+02A62\doublebarveeLogical Or With Double Overbar
    U+02A63\veedoublebarLogical Or With Double Underbar
    U+02A66\eqdotEquals Sign With Dot Below
    U+02A67\dotequivIdentical With Dot Above
    U+02A6A\dotsimTilde Operator With Dot Above
    U+02A6B\simrdotsTilde Operator With Rising Dots
    U+02A6C\simminussimSimilar Minus Similar
    U+02A6D\congdotCongruent With Dot Above
    U+02A6E\asteqEquals With Asterisk
    U+02A6F\hatapproxAlmost Equal To With Circumflex Accent
    U+02A70\approxeqqApproximately Equal Or Equal To
    U+02A71\eqqplusEquals Sign Above Plus Sign
    U+02A72\pluseqqPlus Sign Above Equals Sign
    U+02A73\eqqsimEquals Sign Above Tilde Operator
    U+02A74\ColoneqDouble Colon Equal
    U+02A75\EqualTwo Consecutive Equals Signs
    U+02A76\eqeqeqThree Consecutive Equals Signs
    U+02A77\ddotseqEquals Sign With Two Dots Above And Two Dots Below
    U+02A78\equivDDEquivalent With Four Dots Above
    U+02A79\ltcirLess-than With Circle Inside
    U+02A7A\gtcirGreater-than With Circle Inside
    U+02A7B\ltquestLess-than With Question Mark Above
    U+02A7C\gtquestGreater-than With Question Mark Above
    U+02A7D\leqslantLess-than Or Slanted Equal To
    U+02A7D + U+00338⩽̸\nleqslantLess-than Or Slanted Equal To + Combining Long Solidus Overlay / Non-spacing Long Slash Overlay
    U+02A7E\geqslantGreater-than Or Slanted Equal To
    U+02A7E + U+00338⩾̸\ngeqslantGreater-than Or Slanted Equal To + Combining Long Solidus Overlay / Non-spacing Long Slash Overlay
    U+02A7F⩿\lesdotLess-than Or Slanted Equal To With Dot Inside
    U+02A80\gesdotGreater-than Or Slanted Equal To With Dot Inside
    U+02A81\lesdotoLess-than Or Slanted Equal To With Dot Above
    U+02A82\gesdotoGreater-than Or Slanted Equal To With Dot Above
    U+02A83\lesdotorLess-than Or Slanted Equal To With Dot Above Right
    U+02A84\gesdotolGreater-than Or Slanted Equal To With Dot Above Left
    U+02A85\lessapproxLess-than Or Approximate
    U+02A86\gtrapproxGreater-than Or Approximate
    U+02A87\lneqLess-than And Single-line Not Equal To
    U+02A88\gneqGreater-than And Single-line Not Equal To
    U+02A89\lnapproxLess-than And Not Approximate
    U+02A8A\gnapproxGreater-than And Not Approximate
    U+02A8B\lesseqqgtrLess-than Above Double-line Equal Above Greater-than
    U+02A8C\gtreqqlessGreater-than Above Double-line Equal Above Less-than
    U+02A8D\lsimeLess-than Above Similar Or Equal
    U+02A8E\gsimeGreater-than Above Similar Or Equal
    U+02A8F\lsimgLess-than Above Similar Above Greater-than
    U+02A90\gsimlGreater-than Above Similar Above Less-than
    U+02A91\lgELess-than Above Greater-than Above Double-line Equal
    U+02A92\glEGreater-than Above Less-than Above Double-line Equal
    U+02A93\lesgesLess-than Above Slanted Equal Above Greater-than Above Slanted Equal
    U+02A94\geslesGreater-than Above Slanted Equal Above Less-than Above Slanted Equal
    U+02A95\eqslantlessSlanted Equal To Or Less-than
    U+02A96\eqslantgtrSlanted Equal To Or Greater-than
    U+02A97\elsdotSlanted Equal To Or Less-than With Dot Inside
    U+02A98\egsdotSlanted Equal To Or Greater-than With Dot Inside
    U+02A99\eqqlessDouble-line Equal To Or Less-than
    U+02A9A\eqqgtrDouble-line Equal To Or Greater-than
    U+02A9B\eqqslantlessDouble-line Slanted Equal To Or Less-than
    U+02A9C\eqqslantgtrDouble-line Slanted Equal To Or Greater-than
    U+02A9D\simlessSimilar Or Less-than
    U+02A9E\simgtrSimilar Or Greater-than
    U+02A9F\simlESimilar Above Less-than Above Equals Sign
    U+02AA0\simgESimilar Above Greater-than Above Equals Sign
    U+02AA1\NestedLessLessDouble Nested Less-than
    U+02AA1 + U+00338⪡̸\NotNestedLessLessDouble Nested Less-than + Combining Long Solidus Overlay / Non-spacing Long Slash Overlay
    U+02AA2\NestedGreaterGreaterDouble Nested Greater-than
    U+02AA2 + U+00338⪢̸\NotNestedGreaterGreaterDouble Nested Greater-than + Combining Long Solidus Overlay / Non-spacing Long Slash Overlay
    U+02AA3\partialmeetcontractionDouble Nested Less-than With Underbar
    U+02AA4\gljGreater-than Overlapping Less-than
    U+02AA5\glaGreater-than Beside Less-than
    U+02AA6\ltccLess-than Closed By Curve
    U+02AA7\gtccGreater-than Closed By Curve
    U+02AA8\lesccLess-than Closed By Curve Above Slanted Equal
    U+02AA9\gesccGreater-than Closed By Curve Above Slanted Equal
    U+02AAA\smtSmaller Than
    U+02AAB\latLarger Than
    U+02AAC\smteSmaller Than Or Equal To
    U+02AAD\lateLarger Than Or Equal To
    U+02AAE\bumpeqqEquals Sign With Bumpy Above
    U+02AAF\preceqPrecedes Above Single-line Equals Sign
    U+02AAF + U+00338⪯̸\npreceqPrecedes Above Single-line Equals Sign + Combining Long Solidus Overlay / Non-spacing Long Slash Overlay
    U+02AB0\succeqSucceeds Above Single-line Equals Sign
    U+02AB0 + U+00338⪰̸\nsucceqSucceeds Above Single-line Equals Sign + Combining Long Solidus Overlay / Non-spacing Long Slash Overlay
    U+02AB1\precneqPrecedes Above Single-line Not Equal To
    U+02AB2\succneqSucceeds Above Single-line Not Equal To
    U+02AB3\preceqqPrecedes Above Equals Sign
    U+02AB4\succeqqSucceeds Above Equals Sign
    U+02AB5\precneqqPrecedes Above Not Equal To
    U+02AB6\succneqqSucceeds Above Not Equal To
    U+02AB7\precapproxPrecedes Above Almost Equal To
    U+02AB8\succapproxSucceeds Above Almost Equal To
    U+02AB9\precnapproxPrecedes Above Not Almost Equal To
    U+02ABA\succnapproxSucceeds Above Not Almost Equal To
    U+02ABB\PrecDouble Precedes
    U+02ABC\SuccDouble Succeeds
    U+02ABD\subsetdotSubset With Dot
    U+02ABE\supsetdotSuperset With Dot
    U+02ABF⪿\subsetplusSubset With Plus Sign Below
    U+02AC0\supsetplusSuperset With Plus Sign Below
    U+02AC1\submultSubset With Multiplication Sign Below
    U+02AC2\supmultSuperset With Multiplication Sign Below
    U+02AC3\subedotSubset Of Or Equal To With Dot Above
    U+02AC4\supedotSuperset Of Or Equal To With Dot Above
    U+02AC5\subseteqqSubset Of Above Equals Sign
    U+02AC5 + U+00338⫅̸\nsubseteqqSubset Of Above Equals Sign + Combining Long Solidus Overlay / Non-spacing Long Slash Overlay
    U+02AC6\supseteqqSuperset Of Above Equals Sign
    U+02AC6 + U+00338⫆̸\nsupseteqqSuperset Of Above Equals Sign + Combining Long Solidus Overlay / Non-spacing Long Slash Overlay
    U+02AC7\subsimSubset Of Above Tilde Operator
    U+02AC8\supsimSuperset Of Above Tilde Operator
    U+02AC9\subsetapproxSubset Of Above Almost Equal To
    U+02ACA\supsetapproxSuperset Of Above Almost Equal To
    U+02ACB\subsetneqqSubset Of Above Not Equal To
    U+02ACC\supsetneqqSuperset Of Above Not Equal To
    U+02ACD\lsqhookSquare Left Open Box Operator
    U+02ACE\rsqhookSquare Right Open Box Operator
    U+02ACF\csubClosed Subset
    U+02AD0\csupClosed Superset
    U+02AD1\csubeClosed Subset Or Equal To
    U+02AD2\csupeClosed Superset Or Equal To
    U+02AD3\subsupSubset Above Superset
    U+02AD4\supsubSuperset Above Subset
    U+02AD5\subsubSubset Above Subset
    U+02AD6\supsupSuperset Above Superset
    U+02AD7\suphsubSuperset Beside Subset
    U+02AD8\supdsubSuperset Beside And Joined By Dash With Subset
    U+02AD9\forkvElement Of Opening Downwards
    U+02ADB\mlcpTransversal Intersection
    U+02ADC\forksForking
    U+02ADD\forksnotNonforking
    U+02AE3\dashVDouble Vertical Bar Left Turnstile
    U+02AE4\DashvVertical Bar Double Left Turnstile
    U+02AF4\interleaveTriple Vertical Bar Binary Relation
    U+02AF6\ElztdcolTriple Colon Operator
    U+02AF7\lllnestTriple Nested Less-than
    U+02AF8\gggnestTriple Nested Greater-than
    U+02AF9\leqqslantDouble-line Slanted Less-than Or Equal To
    U+02AFA\geqqslantDouble-line Slanted Greater-than Or Equal To
    U+02B05\:arrow_left:Leftwards Black Arrow
    U+02B06\:arrow_up:Upwards Black Arrow
    U+02B07\:arrow_down:Downwards Black Arrow
    U+02B12\squaretopblackSquare With Top Half Black
    U+02B13\squarebotblackSquare With Bottom Half Black
    U+02B14\squareurblackSquare With Upper Right Diagonal Half Black
    U+02B15\squarellblackSquare With Lower Left Diagonal Half Black
    U+02B16\diamondleftblackDiamond With Left Half Black
    U+02B17\diamondrightblackDiamond With Right Half Black
    U+02B18\diamondtopblackDiamond With Top Half Black
    U+02B19\diamondbotblackDiamond With Bottom Half Black
    U+02B1A\dottedsquareDotted Square
    U+02B1B\lgblksquare, \:black_large_square:Black Large Square
    U+02B1C\lgwhtsquare, \:white_large_square:White Large Square
    U+02B1D\vysmblksquareBlack Very Small Square
    U+02B1E\vysmwhtsquareWhite Very Small Square
    U+02B1F\pentagonblackBlack Pentagon
    U+02B20\pentagonWhite Pentagon
    U+02B21\varhexagonWhite Hexagon
    U+02B22\varhexagonblackBlack Hexagon
    U+02B23\hexagonblackHorizontal Black Hexagon
    U+02B24\lgblkcircleBlack Large Circle
    U+02B25\mdblkdiamondBlack Medium Diamond
    U+02B26\mdwhtdiamondWhite Medium Diamond
    U+02B27\mdblklozengeBlack Medium Lozenge
    U+02B28\mdwhtlozengeWhite Medium Lozenge
    U+02B29\smblkdiamondBlack Small Diamond
    U+02B2A\smblklozengeBlack Small Lozenge
    U+02B2B\smwhtlozengeWhite Small Lozenge
    U+02B2C\blkhorzovalBlack Horizontal Ellipse
    U+02B2D\whthorzovalWhite Horizontal Ellipse
    U+02B2E\blkvertovalBlack Vertical Ellipse
    U+02B2F\whtvertovalWhite Vertical Ellipse
    U+02B30\circleonleftarrowLeft Arrow With Small Circle
    U+02B31\leftthreearrowsThree Leftwards Arrows
    U+02B32\leftarrowonoplusLeft Arrow With Circled Plus
    U+02B33\longleftsquigarrowLong Leftwards Squiggle Arrow
    U+02B34\nvtwoheadleftarrowLeftwards Two-headed Arrow With Vertical Stroke
    U+02B35\nVtwoheadleftarrowLeftwards Two-headed Arrow With Double Vertical Stroke
    U+02B36\twoheadmapsfromLeftwards Two-headed Arrow From Bar
    U+02B37\twoheadleftdbkarrowLeftwards Two-headed Triple Dash Arrow
    U+02B38\leftdotarrowLeftwards Arrow With Dotted Stem
    U+02B39\nvleftarrowtailLeftwards Arrow With Tail With Vertical Stroke
    U+02B3A\nVleftarrowtailLeftwards Arrow With Tail With Double Vertical Stroke
    U+02B3B\twoheadleftarrowtailLeftwards Two-headed Arrow With Tail
    U+02B3C\nvtwoheadleftarrowtailLeftwards Two-headed Arrow With Tail With Vertical Stroke
    U+02B3D\nVtwoheadleftarrowtailLeftwards Two-headed Arrow With Tail With Double Vertical Stroke
    U+02B3E\leftarrowxLeftwards Arrow Through X
    U+02B3F⬿\leftcurvedarrowWave Arrow Pointing Directly Left
    U+02B40\equalleftarrowEquals Sign Above Leftwards Arrow
    U+02B41\bsimilarleftarrowReverse Tilde Operator Above Leftwards Arrow
    U+02B42\leftarrowbackapproxLeftwards Arrow Above Reverse Almost Equal To
    U+02B43\rightarrowgtrRightwards Arrow Through Greater-than
    U+02B44\rightarrowsupsetRightwards Arrow Through Superset
    U+02B45\LLeftarrowLeftwards Quadruple Arrow
    U+02B46\RRightarrowRightwards Quadruple Arrow
    U+02B47\bsimilarrightarrowReverse Tilde Operator Above Rightwards Arrow
    U+02B48\rightarrowbackapproxRightwards Arrow Above Reverse Almost Equal To
    U+02B49\similarleftarrowTilde Operator Above Leftwards Arrow
    U+02B4A\leftarrowapproxLeftwards Arrow Above Almost Equal To
    U+02B4B\leftarrowbsimilarLeftwards Arrow Above Reverse Tilde Operator
    U+02B4C\rightarrowbsimilarRightwards Arrow Above Reverse Tilde Operator
    U+02B50\medwhitestar, \:star:White Medium Star
    U+02B51\medblackstarBlack Small Star
    U+02B52\smwhitestarWhite Small Star
    U+02B53\rightpentagonblackBlack Right-pointing Pentagon
    U+02B54\rightpentagonWhite Right-pointing Pentagon
    U+02B55\:o:Heavy Large Circle
    U+02C7C\_jLatin Subscript Small Letter J
    U+02C7D\^VModifier Letter Capital V
    U+03012\postalmarkPostal Mark
    U+03030\:wavy_dash:Wavy Dash
    U+0303D\:part_alternation_mark:Part Alternation Mark
    U+03297\:congratulations:Circled Ideograph Congratulation
    U+03299\:secret:Circled Ideograph Secret
    U+1D400𝐀\mbfAMathematical Bold Capital A
    U+1D401𝐁\mbfBMathematical Bold Capital B
    U+1D402𝐂\mbfCMathematical Bold Capital C
    U+1D403𝐃\mbfDMathematical Bold Capital D
    U+1D404𝐄\mbfEMathematical Bold Capital E
    U+1D405𝐅\mbfFMathematical Bold Capital F
    U+1D406𝐆\mbfGMathematical Bold Capital G
    U+1D407𝐇\mbfHMathematical Bold Capital H
    U+1D408𝐈\mbfIMathematical Bold Capital I
    U+1D409𝐉\mbfJMathematical Bold Capital J
    U+1D40A𝐊\mbfKMathematical Bold Capital K
    U+1D40B𝐋\mbfLMathematical Bold Capital L
    U+1D40C𝐌\mbfMMathematical Bold Capital M
    U+1D40D𝐍\mbfNMathematical Bold Capital N
    U+1D40E𝐎\mbfOMathematical Bold Capital O
    U+1D40F𝐏\mbfPMathematical Bold Capital P
    U+1D410𝐐\mbfQMathematical Bold Capital Q
    U+1D411𝐑\mbfRMathematical Bold Capital R
    U+1D412𝐒\mbfSMathematical Bold Capital S
    U+1D413𝐓\mbfTMathematical Bold Capital T
    U+1D414𝐔\mbfUMathematical Bold Capital U
    U+1D415𝐕\mbfVMathematical Bold Capital V
    U+1D416𝐖\mbfWMathematical Bold Capital W
    U+1D417𝐗\mbfXMathematical Bold Capital X
    U+1D418𝐘\mbfYMathematical Bold Capital Y
    U+1D419𝐙\mbfZMathematical Bold Capital Z
    U+1D41A𝐚\mbfaMathematical Bold Small A
    U+1D41B𝐛\mbfbMathematical Bold Small B
    U+1D41C𝐜\mbfcMathematical Bold Small C
    U+1D41D𝐝\mbfdMathematical Bold Small D
    U+1D41E𝐞\mbfeMathematical Bold Small E
    U+1D41F𝐟\mbffMathematical Bold Small F
    U+1D420𝐠\mbfgMathematical Bold Small G
    U+1D421𝐡\mbfhMathematical Bold Small H
    U+1D422𝐢\mbfiMathematical Bold Small I
    U+1D423𝐣\mbfjMathematical Bold Small J
    U+1D424𝐤\mbfkMathematical Bold Small K
    U+1D425𝐥\mbflMathematical Bold Small L
    U+1D426𝐦\mbfmMathematical Bold Small M
    U+1D427𝐧\mbfnMathematical Bold Small N
    U+1D428𝐨\mbfoMathematical Bold Small O
    U+1D429𝐩\mbfpMathematical Bold Small P
    U+1D42A𝐪\mbfqMathematical Bold Small Q
    U+1D42B𝐫\mbfrMathematical Bold Small R
    U+1D42C𝐬\mbfsMathematical Bold Small S
    U+1D42D𝐭\mbftMathematical Bold Small T
    U+1D42E𝐮\mbfuMathematical Bold Small U
    U+1D42F𝐯\mbfvMathematical Bold Small V
    U+1D430𝐰\mbfwMathematical Bold Small W
    U+1D431𝐱\mbfxMathematical Bold Small X
    U+1D432𝐲\mbfyMathematical Bold Small Y
    U+1D433𝐳\mbfzMathematical Bold Small Z
    U+1D434𝐴\mitAMathematical Italic Capital A
    U+1D435𝐵\mitBMathematical Italic Capital B
    U+1D436𝐶\mitCMathematical Italic Capital C
    U+1D437𝐷\mitDMathematical Italic Capital D
    U+1D438𝐸\mitEMathematical Italic Capital E
    U+1D439𝐹\mitFMathematical Italic Capital F
    U+1D43A𝐺\mitGMathematical Italic Capital G
    U+1D43B𝐻\mitHMathematical Italic Capital H
    U+1D43C𝐼\mitIMathematical Italic Capital I
    U+1D43D𝐽\mitJMathematical Italic Capital J
    U+1D43E𝐾\mitKMathematical Italic Capital K
    U+1D43F𝐿\mitLMathematical Italic Capital L
    U+1D440𝑀\mitMMathematical Italic Capital M
    U+1D441𝑁\mitNMathematical Italic Capital N
    U+1D442𝑂\mitOMathematical Italic Capital O
    U+1D443𝑃\mitPMathematical Italic Capital P
    U+1D444𝑄\mitQMathematical Italic Capital Q
    U+1D445𝑅\mitRMathematical Italic Capital R
    U+1D446𝑆\mitSMathematical Italic Capital S
    U+1D447𝑇\mitTMathematical Italic Capital T
    U+1D448𝑈\mitUMathematical Italic Capital U
    U+1D449𝑉\mitVMathematical Italic Capital V
    U+1D44A𝑊\mitWMathematical Italic Capital W
    U+1D44B𝑋\mitXMathematical Italic Capital X
    U+1D44C𝑌\mitYMathematical Italic Capital Y
    U+1D44D𝑍\mitZMathematical Italic Capital Z
    U+1D44E𝑎\mitaMathematical Italic Small A
    U+1D44F𝑏\mitbMathematical Italic Small B
    U+1D450𝑐\mitcMathematical Italic Small C
    U+1D451𝑑\mitdMathematical Italic Small D
    U+1D452𝑒\miteMathematical Italic Small E
    U+1D453𝑓\mitfMathematical Italic Small F
    U+1D454𝑔\mitgMathematical Italic Small G
    U+1D456𝑖\mitiMathematical Italic Small I
    U+1D457𝑗\mitjMathematical Italic Small J
    U+1D458𝑘\mitkMathematical Italic Small K
    U+1D459𝑙\mitlMathematical Italic Small L
    U+1D45A𝑚\mitmMathematical Italic Small M
    U+1D45B𝑛\mitnMathematical Italic Small N
    U+1D45C𝑜\mitoMathematical Italic Small O
    U+1D45D𝑝\mitpMathematical Italic Small P
    U+1D45E𝑞\mitqMathematical Italic Small Q
    U+1D45F𝑟\mitrMathematical Italic Small R
    U+1D460𝑠\mitsMathematical Italic Small S
    U+1D461𝑡\mittMathematical Italic Small T
    U+1D462𝑢\mituMathematical Italic Small U
    U+1D463𝑣\mitvMathematical Italic Small V
    U+1D464𝑤\mitwMathematical Italic Small W
    U+1D465𝑥\mitxMathematical Italic Small X
    U+1D466𝑦\mityMathematical Italic Small Y
    U+1D467𝑧\mitzMathematical Italic Small Z
    U+1D468𝑨\mbfitAMathematical Bold Italic Capital A
    U+1D469𝑩\mbfitBMathematical Bold Italic Capital B
    U+1D46A𝑪\mbfitCMathematical Bold Italic Capital C
    U+1D46B𝑫\mbfitDMathematical Bold Italic Capital D
    U+1D46C𝑬\mbfitEMathematical Bold Italic Capital E
    U+1D46D𝑭\mbfitFMathematical Bold Italic Capital F
    U+1D46E𝑮\mbfitGMathematical Bold Italic Capital G
    U+1D46F𝑯\mbfitHMathematical Bold Italic Capital H
    U+1D470𝑰\mbfitIMathematical Bold Italic Capital I
    U+1D471𝑱\mbfitJMathematical Bold Italic Capital J
    U+1D472𝑲\mbfitKMathematical Bold Italic Capital K
    U+1D473𝑳\mbfitLMathematical Bold Italic Capital L
    U+1D474𝑴\mbfitMMathematical Bold Italic Capital M
    U+1D475𝑵\mbfitNMathematical Bold Italic Capital N
    U+1D476𝑶\mbfitOMathematical Bold Italic Capital O
    U+1D477𝑷\mbfitPMathematical Bold Italic Capital P
    U+1D478𝑸\mbfitQMathematical Bold Italic Capital Q
    U+1D479𝑹\mbfitRMathematical Bold Italic Capital R
    U+1D47A𝑺\mbfitSMathematical Bold Italic Capital S
    U+1D47B𝑻\mbfitTMathematical Bold Italic Capital T
    U+1D47C𝑼\mbfitUMathematical Bold Italic Capital U
    U+1D47D𝑽\mbfitVMathematical Bold Italic Capital V
    U+1D47E𝑾\mbfitWMathematical Bold Italic Capital W
    U+1D47F𝑿\mbfitXMathematical Bold Italic Capital X
    U+1D480𝒀\mbfitYMathematical Bold Italic Capital Y
    U+1D481𝒁\mbfitZMathematical Bold Italic Capital Z
    U+1D482𝒂\mbfitaMathematical Bold Italic Small A
    U+1D483𝒃\mbfitbMathematical Bold Italic Small B
    U+1D484𝒄\mbfitcMathematical Bold Italic Small C
    U+1D485𝒅\mbfitdMathematical Bold Italic Small D
    U+1D486𝒆\mbfiteMathematical Bold Italic Small E
    U+1D487𝒇\mbfitfMathematical Bold Italic Small F
    U+1D488𝒈\mbfitgMathematical Bold Italic Small G
    U+1D489𝒉\mbfithMathematical Bold Italic Small H
    U+1D48A𝒊\mbfitiMathematical Bold Italic Small I
    U+1D48B𝒋\mbfitjMathematical Bold Italic Small J
    U+1D48C𝒌\mbfitkMathematical Bold Italic Small K
    U+1D48D𝒍\mbfitlMathematical Bold Italic Small L
    U+1D48E𝒎\mbfitmMathematical Bold Italic Small M
    U+1D48F𝒏\mbfitnMathematical Bold Italic Small N
    U+1D490𝒐\mbfitoMathematical Bold Italic Small O
    U+1D491𝒑\mbfitpMathematical Bold Italic Small P
    U+1D492𝒒\mbfitqMathematical Bold Italic Small Q
    U+1D493𝒓\mbfitrMathematical Bold Italic Small R
    U+1D494𝒔\mbfitsMathematical Bold Italic Small S
    U+1D495𝒕\mbfittMathematical Bold Italic Small T
    U+1D496𝒖\mbfituMathematical Bold Italic Small U
    U+1D497𝒗\mbfitvMathematical Bold Italic Small V
    U+1D498𝒘\mbfitwMathematical Bold Italic Small W
    U+1D499𝒙\mbfitxMathematical Bold Italic Small X
    U+1D49A𝒚\mbfityMathematical Bold Italic Small Y
    U+1D49B𝒛\mbfitzMathematical Bold Italic Small Z
    U+1D49C𝒜\mscrAMathematical Script Capital A
    U+1D49E𝒞\mscrCMathematical Script Capital C
    U+1D49F𝒟\mscrDMathematical Script Capital D
    U+1D4A2𝒢\mscrGMathematical Script Capital G
    U+1D4A5𝒥\mscrJMathematical Script Capital J
    U+1D4A6𝒦\mscrKMathematical Script Capital K
    U+1D4A9𝒩\mscrNMathematical Script Capital N
    U+1D4AA𝒪\mscrOMathematical Script Capital O
    U+1D4AB𝒫\mscrPMathematical Script Capital P
    U+1D4AC𝒬\mscrQMathematical Script Capital Q
    U+1D4AE𝒮\mscrSMathematical Script Capital S
    U+1D4AF𝒯\mscrTMathematical Script Capital T
    U+1D4B0𝒰\mscrUMathematical Script Capital U
    U+1D4B1𝒱\mscrVMathematical Script Capital V
    U+1D4B2𝒲\mscrWMathematical Script Capital W
    U+1D4B3𝒳\mscrXMathematical Script Capital X
    U+1D4B4𝒴\mscrYMathematical Script Capital Y
    U+1D4B5𝒵\mscrZMathematical Script Capital Z
    U+1D4B6𝒶\mscraMathematical Script Small A
    U+1D4B7𝒷\mscrbMathematical Script Small B
    U+1D4B8𝒸\mscrcMathematical Script Small C
    U+1D4B9𝒹\mscrdMathematical Script Small D
    U+1D4BB𝒻\mscrfMathematical Script Small F
    U+1D4BD𝒽\mscrhMathematical Script Small H
    U+1D4BE𝒾\mscriMathematical Script Small I
    U+1D4BF𝒿\mscrjMathematical Script Small J
    U+1D4C0𝓀\mscrkMathematical Script Small K
    U+1D4C1𝓁\mscrlMathematical Script Small L
    U+1D4C2𝓂\mscrmMathematical Script Small M
    U+1D4C3𝓃\mscrnMathematical Script Small N
    U+1D4C5𝓅\mscrpMathematical Script Small P
    U+1D4C6𝓆\mscrqMathematical Script Small Q
    U+1D4C7𝓇\mscrrMathematical Script Small R
    U+1D4C8𝓈\mscrsMathematical Script Small S
    U+1D4C9𝓉\mscrtMathematical Script Small T
    U+1D4CA𝓊\mscruMathematical Script Small U
    U+1D4CB𝓋\mscrvMathematical Script Small V
    U+1D4CC𝓌\mscrwMathematical Script Small W
    U+1D4CD𝓍\mscrxMathematical Script Small X
    U+1D4CE𝓎\mscryMathematical Script Small Y
    U+1D4CF𝓏\mscrzMathematical Script Small Z
    U+1D4D0𝓐\mbfscrAMathematical Bold Script Capital A
    U+1D4D1𝓑\mbfscrBMathematical Bold Script Capital B
    U+1D4D2𝓒\mbfscrCMathematical Bold Script Capital C
    U+1D4D3𝓓\mbfscrDMathematical Bold Script Capital D
    U+1D4D4𝓔\mbfscrEMathematical Bold Script Capital E
    U+1D4D5𝓕\mbfscrFMathematical Bold Script Capital F
    U+1D4D6𝓖\mbfscrGMathematical Bold Script Capital G
    U+1D4D7𝓗\mbfscrHMathematical Bold Script Capital H
    U+1D4D8𝓘\mbfscrIMathematical Bold Script Capital I
    U+1D4D9𝓙\mbfscrJMathematical Bold Script Capital J
    U+1D4DA𝓚\mbfscrKMathematical Bold Script Capital K
    U+1D4DB𝓛\mbfscrLMathematical Bold Script Capital L
    U+1D4DC𝓜\mbfscrMMathematical Bold Script Capital M
    U+1D4DD𝓝\mbfscrNMathematical Bold Script Capital N
    U+1D4DE𝓞\mbfscrOMathematical Bold Script Capital O
    U+1D4DF𝓟\mbfscrPMathematical Bold Script Capital P
    U+1D4E0𝓠\mbfscrQMathematical Bold Script Capital Q
    U+1D4E1𝓡\mbfscrRMathematical Bold Script Capital R
    U+1D4E2𝓢\mbfscrSMathematical Bold Script Capital S
    U+1D4E3𝓣\mbfscrTMathematical Bold Script Capital T
    U+1D4E4𝓤\mbfscrUMathematical Bold Script Capital U
    U+1D4E5𝓥\mbfscrVMathematical Bold Script Capital V
    U+1D4E6𝓦\mbfscrWMathematical Bold Script Capital W
    U+1D4E7𝓧\mbfscrXMathematical Bold Script Capital X
    U+1D4E8𝓨\mbfscrYMathematical Bold Script Capital Y
    U+1D4E9𝓩\mbfscrZMathematical Bold Script Capital Z
    U+1D4EA𝓪\mbfscraMathematical Bold Script Small A
    U+1D4EB𝓫\mbfscrbMathematical Bold Script Small B
    U+1D4EC𝓬\mbfscrcMathematical Bold Script Small C
    U+1D4ED𝓭\mbfscrdMathematical Bold Script Small D
    U+1D4EE𝓮\mbfscreMathematical Bold Script Small E
    U+1D4EF𝓯\mbfscrfMathematical Bold Script Small F
    U+1D4F0𝓰\mbfscrgMathematical Bold Script Small G
    U+1D4F1𝓱\mbfscrhMathematical Bold Script Small H
    U+1D4F2𝓲\mbfscriMathematical Bold Script Small I
    U+1D4F3𝓳\mbfscrjMathematical Bold Script Small J
    U+1D4F4𝓴\mbfscrkMathematical Bold Script Small K
    U+1D4F5𝓵\mbfscrlMathematical Bold Script Small L
    U+1D4F6𝓶\mbfscrmMathematical Bold Script Small M
    U+1D4F7𝓷\mbfscrnMathematical Bold Script Small N
    U+1D4F8𝓸\mbfscroMathematical Bold Script Small O
    U+1D4F9𝓹\mbfscrpMathematical Bold Script Small P
    U+1D4FA𝓺\mbfscrqMathematical Bold Script Small Q
    U+1D4FB𝓻\mbfscrrMathematical Bold Script Small R
    U+1D4FC𝓼\mbfscrsMathematical Bold Script Small S
    U+1D4FD𝓽\mbfscrtMathematical Bold Script Small T
    U+1D4FE𝓾\mbfscruMathematical Bold Script Small U
    U+1D4FF𝓿\mbfscrvMathematical Bold Script Small V
    U+1D500𝔀\mbfscrwMathematical Bold Script Small W
    U+1D501𝔁\mbfscrxMathematical Bold Script Small X
    U+1D502𝔂\mbfscryMathematical Bold Script Small Y
    U+1D503𝔃\mbfscrzMathematical Bold Script Small Z
    U+1D504𝔄\mfrakAMathematical Fraktur Capital A
    U+1D505𝔅\mfrakBMathematical Fraktur Capital B
    U+1D507𝔇\mfrakDMathematical Fraktur Capital D
    U+1D508𝔈\mfrakEMathematical Fraktur Capital E
    U+1D509𝔉\mfrakFMathematical Fraktur Capital F
    U+1D50A𝔊\mfrakGMathematical Fraktur Capital G
    U+1D50D𝔍\mfrakJMathematical Fraktur Capital J
    U+1D50E𝔎\mfrakKMathematical Fraktur Capital K
    U+1D50F𝔏\mfrakLMathematical Fraktur Capital L
    U+1D510𝔐\mfrakMMathematical Fraktur Capital M
    U+1D511𝔑\mfrakNMathematical Fraktur Capital N
    U+1D512𝔒\mfrakOMathematical Fraktur Capital O
    U+1D513𝔓\mfrakPMathematical Fraktur Capital P
    U+1D514𝔔\mfrakQMathematical Fraktur Capital Q
    U+1D516𝔖\mfrakSMathematical Fraktur Capital S
    U+1D517𝔗\mfrakTMathematical Fraktur Capital T
    U+1D518𝔘\mfrakUMathematical Fraktur Capital U
    U+1D519𝔙\mfrakVMathematical Fraktur Capital V
    U+1D51A𝔚\mfrakWMathematical Fraktur Capital W
    U+1D51B𝔛\mfrakXMathematical Fraktur Capital X
    U+1D51C𝔜\mfrakYMathematical Fraktur Capital Y
    U+1D51E𝔞\mfrakaMathematical Fraktur Small A
    U+1D51F𝔟\mfrakbMathematical Fraktur Small B
    U+1D520𝔠\mfrakcMathematical Fraktur Small C
    U+1D521𝔡\mfrakdMathematical Fraktur Small D
    U+1D522𝔢\mfrakeMathematical Fraktur Small E
    U+1D523𝔣\mfrakfMathematical Fraktur Small F
    U+1D524𝔤\mfrakgMathematical Fraktur Small G
    U+1D525𝔥\mfrakhMathematical Fraktur Small H
    U+1D526𝔦\mfrakiMathematical Fraktur Small I
    U+1D527𝔧\mfrakjMathematical Fraktur Small J
    U+1D528𝔨\mfrakkMathematical Fraktur Small K
    U+1D529𝔩\mfraklMathematical Fraktur Small L
    U+1D52A𝔪\mfrakmMathematical Fraktur Small M
    U+1D52B𝔫\mfraknMathematical Fraktur Small N
    U+1D52C𝔬\mfrakoMathematical Fraktur Small O
    U+1D52D𝔭\mfrakpMathematical Fraktur Small P
    U+1D52E𝔮\mfrakqMathematical Fraktur Small Q
    U+1D52F𝔯\mfrakrMathematical Fraktur Small R
    U+1D530𝔰\mfraksMathematical Fraktur Small S
    U+1D531𝔱\mfraktMathematical Fraktur Small T
    U+1D532𝔲\mfrakuMathematical Fraktur Small U
    U+1D533𝔳\mfrakvMathematical Fraktur Small V
    U+1D534𝔴\mfrakwMathematical Fraktur Small W
    U+1D535𝔵\mfrakxMathematical Fraktur Small X
    U+1D536𝔶\mfrakyMathematical Fraktur Small Y
    U+1D537𝔷\mfrakzMathematical Fraktur Small Z
    U+1D538𝔸\BbbAMathematical Double-struck Capital A
    U+1D539𝔹\BbbBMathematical Double-struck Capital B
    U+1D53B𝔻\BbbDMathematical Double-struck Capital D
    U+1D53C𝔼\BbbEMathematical Double-struck Capital E
    U+1D53D𝔽\BbbFMathematical Double-struck Capital F
    U+1D53E𝔾\BbbGMathematical Double-struck Capital G
    U+1D540𝕀\BbbIMathematical Double-struck Capital I
    U+1D541𝕁\BbbJMathematical Double-struck Capital J
    U+1D542𝕂\BbbKMathematical Double-struck Capital K
    U+1D543𝕃\BbbLMathematical Double-struck Capital L
    U+1D544𝕄\BbbMMathematical Double-struck Capital M
    U+1D546𝕆\BbbOMathematical Double-struck Capital O
    U+1D54A𝕊\BbbSMathematical Double-struck Capital S
    U+1D54B𝕋\BbbTMathematical Double-struck Capital T
    U+1D54C𝕌\BbbUMathematical Double-struck Capital U
    U+1D54D𝕍\BbbVMathematical Double-struck Capital V
    U+1D54E𝕎\BbbWMathematical Double-struck Capital W
    U+1D54F𝕏\BbbXMathematical Double-struck Capital X
    U+1D550𝕐\BbbYMathematical Double-struck Capital Y
    U+1D552𝕒\BbbaMathematical Double-struck Small A
    U+1D553𝕓\BbbbMathematical Double-struck Small B
    U+1D554𝕔\BbbcMathematical Double-struck Small C
    U+1D555𝕕\BbbdMathematical Double-struck Small D
    U+1D556𝕖\BbbeMathematical Double-struck Small E
    U+1D557𝕗\BbbfMathematical Double-struck Small F
    U+1D558𝕘\BbbgMathematical Double-struck Small G
    U+1D559𝕙\BbbhMathematical Double-struck Small H
    U+1D55A𝕚\BbbiMathematical Double-struck Small I
    U+1D55B𝕛\BbbjMathematical Double-struck Small J
    U+1D55C𝕜\BbbkMathematical Double-struck Small K
    U+1D55D𝕝\BbblMathematical Double-struck Small L
    U+1D55E𝕞\BbbmMathematical Double-struck Small M
    U+1D55F𝕟\BbbnMathematical Double-struck Small N
    U+1D560𝕠\BbboMathematical Double-struck Small O
    U+1D561𝕡\BbbpMathematical Double-struck Small P
    U+1D562𝕢\BbbqMathematical Double-struck Small Q
    U+1D563𝕣\BbbrMathematical Double-struck Small R
    U+1D564𝕤\BbbsMathematical Double-struck Small S
    U+1D565𝕥\BbbtMathematical Double-struck Small T
    U+1D566𝕦\BbbuMathematical Double-struck Small U
    U+1D567𝕧\BbbvMathematical Double-struck Small V
    U+1D568𝕨\BbbwMathematical Double-struck Small W
    U+1D569𝕩\BbbxMathematical Double-struck Small X
    U+1D56A𝕪\BbbyMathematical Double-struck Small Y
    U+1D56B𝕫\BbbzMathematical Double-struck Small Z
    U+1D56C𝕬\mbffrakAMathematical Bold Fraktur Capital A
    U+1D56D𝕭\mbffrakBMathematical Bold Fraktur Capital B
    U+1D56E𝕮\mbffrakCMathematical Bold Fraktur Capital C
    U+1D56F𝕯\mbffrakDMathematical Bold Fraktur Capital D
    U+1D570𝕰\mbffrakEMathematical Bold Fraktur Capital E
    U+1D571𝕱\mbffrakFMathematical Bold Fraktur Capital F
    U+1D572𝕲\mbffrakGMathematical Bold Fraktur Capital G
    U+1D573𝕳\mbffrakHMathematical Bold Fraktur Capital H
    U+1D574𝕴\mbffrakIMathematical Bold Fraktur Capital I
    U+1D575𝕵\mbffrakJMathematical Bold Fraktur Capital J
    U+1D576𝕶\mbffrakKMathematical Bold Fraktur Capital K
    U+1D577𝕷\mbffrakLMathematical Bold Fraktur Capital L
    U+1D578𝕸\mbffrakMMathematical Bold Fraktur Capital M
    U+1D579𝕹\mbffrakNMathematical Bold Fraktur Capital N
    U+1D57A𝕺\mbffrakOMathematical Bold Fraktur Capital O
    U+1D57B𝕻\mbffrakPMathematical Bold Fraktur Capital P
    U+1D57C𝕼\mbffrakQMathematical Bold Fraktur Capital Q
    U+1D57D𝕽\mbffrakRMathematical Bold Fraktur Capital R
    U+1D57E𝕾\mbffrakSMathematical Bold Fraktur Capital S
    U+1D57F𝕿\mbffrakTMathematical Bold Fraktur Capital T
    U+1D580𝖀\mbffrakUMathematical Bold Fraktur Capital U
    U+1D581𝖁\mbffrakVMathematical Bold Fraktur Capital V
    U+1D582𝖂\mbffrakWMathematical Bold Fraktur Capital W
    U+1D583𝖃\mbffrakXMathematical Bold Fraktur Capital X
    U+1D584𝖄\mbffrakYMathematical Bold Fraktur Capital Y
    U+1D585𝖅\mbffrakZMathematical Bold Fraktur Capital Z
    U+1D586𝖆\mbffrakaMathematical Bold Fraktur Small A
    U+1D587𝖇\mbffrakbMathematical Bold Fraktur Small B
    U+1D588𝖈\mbffrakcMathematical Bold Fraktur Small C
    U+1D589𝖉\mbffrakdMathematical Bold Fraktur Small D
    U+1D58A𝖊\mbffrakeMathematical Bold Fraktur Small E
    U+1D58B𝖋\mbffrakfMathematical Bold Fraktur Small F
    U+1D58C𝖌\mbffrakgMathematical Bold Fraktur Small G
    U+1D58D𝖍\mbffrakhMathematical Bold Fraktur Small H
    U+1D58E𝖎\mbffrakiMathematical Bold Fraktur Small I
    U+1D58F𝖏\mbffrakjMathematical Bold Fraktur Small J
    U+1D590𝖐\mbffrakkMathematical Bold Fraktur Small K
    U+1D591𝖑\mbffraklMathematical Bold Fraktur Small L
    U+1D592𝖒\mbffrakmMathematical Bold Fraktur Small M
    U+1D593𝖓\mbffraknMathematical Bold Fraktur Small N
    U+1D594𝖔\mbffrakoMathematical Bold Fraktur Small O
    U+1D595𝖕\mbffrakpMathematical Bold Fraktur Small P
    U+1D596𝖖\mbffrakqMathematical Bold Fraktur Small Q
    U+1D597𝖗\mbffrakrMathematical Bold Fraktur Small R
    U+1D598𝖘\mbffraksMathematical Bold Fraktur Small S
    U+1D599𝖙\mbffraktMathematical Bold Fraktur Small T
    U+1D59A𝖚\mbffrakuMathematical Bold Fraktur Small U
    U+1D59B𝖛\mbffrakvMathematical Bold Fraktur Small V
    U+1D59C𝖜\mbffrakwMathematical Bold Fraktur Small W
    U+1D59D𝖝\mbffrakxMathematical Bold Fraktur Small X
    U+1D59E𝖞\mbffrakyMathematical Bold Fraktur Small Y
    U+1D59F𝖟\mbffrakzMathematical Bold Fraktur Small Z
    U+1D5A0𝖠\msansAMathematical Sans-serif Capital A
    U+1D5A1𝖡\msansBMathematical Sans-serif Capital B
    U+1D5A2𝖢\msansCMathematical Sans-serif Capital C
    U+1D5A3𝖣\msansDMathematical Sans-serif Capital D
    U+1D5A4𝖤\msansEMathematical Sans-serif Capital E
    U+1D5A5𝖥\msansFMathematical Sans-serif Capital F
    U+1D5A6𝖦\msansGMathematical Sans-serif Capital G
    U+1D5A7𝖧\msansHMathematical Sans-serif Capital H
    U+1D5A8𝖨\msansIMathematical Sans-serif Capital I
    U+1D5A9𝖩\msansJMathematical Sans-serif Capital J
    U+1D5AA𝖪\msansKMathematical Sans-serif Capital K
    U+1D5AB𝖫\msansLMathematical Sans-serif Capital L
    U+1D5AC𝖬\msansMMathematical Sans-serif Capital M
    U+1D5AD𝖭\msansNMathematical Sans-serif Capital N
    U+1D5AE𝖮\msansOMathematical Sans-serif Capital O
    U+1D5AF𝖯\msansPMathematical Sans-serif Capital P
    U+1D5B0𝖰\msansQMathematical Sans-serif Capital Q
    U+1D5B1𝖱\msansRMathematical Sans-serif Capital R
    U+1D5B2𝖲\msansSMathematical Sans-serif Capital S
    U+1D5B3𝖳\msansTMathematical Sans-serif Capital T
    U+1D5B4𝖴\msansUMathematical Sans-serif Capital U
    U+1D5B5𝖵\msansVMathematical Sans-serif Capital V
    U+1D5B6𝖶\msansWMathematical Sans-serif Capital W
    U+1D5B7𝖷\msansXMathematical Sans-serif Capital X
    U+1D5B8𝖸\msansYMathematical Sans-serif Capital Y
    U+1D5B9𝖹\msansZMathematical Sans-serif Capital Z
    U+1D5BA𝖺\msansaMathematical Sans-serif Small A
    U+1D5BB𝖻\msansbMathematical Sans-serif Small B
    U+1D5BC𝖼\msanscMathematical Sans-serif Small C
    U+1D5BD𝖽\msansdMathematical Sans-serif Small D
    U+1D5BE𝖾\msanseMathematical Sans-serif Small E
    U+1D5BF𝖿\msansfMathematical Sans-serif Small F
    U+1D5C0𝗀\msansgMathematical Sans-serif Small G
    U+1D5C1𝗁\msanshMathematical Sans-serif Small H
    U+1D5C2𝗂\msansiMathematical Sans-serif Small I
    U+1D5C3𝗃\msansjMathematical Sans-serif Small J
    U+1D5C4𝗄\msanskMathematical Sans-serif Small K
    U+1D5C5𝗅\msanslMathematical Sans-serif Small L
    U+1D5C6𝗆\msansmMathematical Sans-serif Small M
    U+1D5C7𝗇\msansnMathematical Sans-serif Small N
    U+1D5C8𝗈\msansoMathematical Sans-serif Small O
    U+1D5C9𝗉\msanspMathematical Sans-serif Small P
    U+1D5CA𝗊\msansqMathematical Sans-serif Small Q
    U+1D5CB𝗋\msansrMathematical Sans-serif Small R
    U+1D5CC𝗌\msanssMathematical Sans-serif Small S
    U+1D5CD𝗍\msanstMathematical Sans-serif Small T
    U+1D5CE𝗎\msansuMathematical Sans-serif Small U
    U+1D5CF𝗏\msansvMathematical Sans-serif Small V
    U+1D5D0𝗐\msanswMathematical Sans-serif Small W
    U+1D5D1𝗑\msansxMathematical Sans-serif Small X
    U+1D5D2𝗒\msansyMathematical Sans-serif Small Y
    U+1D5D3𝗓\msanszMathematical Sans-serif Small Z
    U+1D5D4𝗔\mbfsansAMathematical Sans-serif Bold Capital A
    U+1D5D5𝗕\mbfsansBMathematical Sans-serif Bold Capital B
    U+1D5D6𝗖\mbfsansCMathematical Sans-serif Bold Capital C
    U+1D5D7𝗗\mbfsansDMathematical Sans-serif Bold Capital D
    U+1D5D8𝗘\mbfsansEMathematical Sans-serif Bold Capital E
    U+1D5D9𝗙\mbfsansFMathematical Sans-serif Bold Capital F
    U+1D5DA𝗚\mbfsansGMathematical Sans-serif Bold Capital G
    U+1D5DB𝗛\mbfsansHMathematical Sans-serif Bold Capital H
    U+1D5DC𝗜\mbfsansIMathematical Sans-serif Bold Capital I
    U+1D5DD𝗝\mbfsansJMathematical Sans-serif Bold Capital J
    U+1D5DE𝗞\mbfsansKMathematical Sans-serif Bold Capital K
    U+1D5DF𝗟\mbfsansLMathematical Sans-serif Bold Capital L
    U+1D5E0𝗠\mbfsansMMathematical Sans-serif Bold Capital M
    U+1D5E1𝗡\mbfsansNMathematical Sans-serif Bold Capital N
    U+1D5E2𝗢\mbfsansOMathematical Sans-serif Bold Capital O
    U+1D5E3𝗣\mbfsansPMathematical Sans-serif Bold Capital P
    U+1D5E4𝗤\mbfsansQMathematical Sans-serif Bold Capital Q
    U+1D5E5𝗥\mbfsansRMathematical Sans-serif Bold Capital R
    U+1D5E6𝗦\mbfsansSMathematical Sans-serif Bold Capital S
    U+1D5E7𝗧\mbfsansTMathematical Sans-serif Bold Capital T
    U+1D5E8𝗨\mbfsansUMathematical Sans-serif Bold Capital U
    U+1D5E9𝗩\mbfsansVMathematical Sans-serif Bold Capital V
    U+1D5EA𝗪\mbfsansWMathematical Sans-serif Bold Capital W
    U+1D5EB𝗫\mbfsansXMathematical Sans-serif Bold Capital X
    U+1D5EC𝗬\mbfsansYMathematical Sans-serif Bold Capital Y
    U+1D5ED𝗭\mbfsansZMathematical Sans-serif Bold Capital Z
    U+1D5EE𝗮\mbfsansaMathematical Sans-serif Bold Small A
    U+1D5EF𝗯\mbfsansbMathematical Sans-serif Bold Small B
    U+1D5F0𝗰\mbfsanscMathematical Sans-serif Bold Small C
    U+1D5F1𝗱\mbfsansdMathematical Sans-serif Bold Small D
    U+1D5F2𝗲\mbfsanseMathematical Sans-serif Bold Small E
    U+1D5F3𝗳\mbfsansfMathematical Sans-serif Bold Small F
    U+1D5F4𝗴\mbfsansgMathematical Sans-serif Bold Small G
    U+1D5F5𝗵\mbfsanshMathematical Sans-serif Bold Small H
    U+1D5F6𝗶\mbfsansiMathematical Sans-serif Bold Small I
    U+1D5F7𝗷\mbfsansjMathematical Sans-serif Bold Small J
    U+1D5F8𝗸\mbfsanskMathematical Sans-serif Bold Small K
    U+1D5F9𝗹\mbfsanslMathematical Sans-serif Bold Small L
    U+1D5FA𝗺\mbfsansmMathematical Sans-serif Bold Small M
    U+1D5FB𝗻\mbfsansnMathematical Sans-serif Bold Small N
    U+1D5FC𝗼\mbfsansoMathematical Sans-serif Bold Small O
    U+1D5FD𝗽\mbfsanspMathematical Sans-serif Bold Small P
    U+1D5FE𝗾\mbfsansqMathematical Sans-serif Bold Small Q
    U+1D5FF𝗿\mbfsansrMathematical Sans-serif Bold Small R
    U+1D600𝘀\mbfsanssMathematical Sans-serif Bold Small S
    U+1D601𝘁\mbfsanstMathematical Sans-serif Bold Small T
    U+1D602𝘂\mbfsansuMathematical Sans-serif Bold Small U
    U+1D603𝘃\mbfsansvMathematical Sans-serif Bold Small V
    U+1D604𝘄\mbfsanswMathematical Sans-serif Bold Small W
    U+1D605𝘅\mbfsansxMathematical Sans-serif Bold Small X
    U+1D606𝘆\mbfsansyMathematical Sans-serif Bold Small Y
    U+1D607𝘇\mbfsanszMathematical Sans-serif Bold Small Z
    U+1D608𝘈\mitsansAMathematical Sans-serif Italic Capital A
    U+1D609𝘉\mitsansBMathematical Sans-serif Italic Capital B
    U+1D60A𝘊\mitsansCMathematical Sans-serif Italic Capital C
    U+1D60B𝘋\mitsansDMathematical Sans-serif Italic Capital D
    U+1D60C𝘌\mitsansEMathematical Sans-serif Italic Capital E
    U+1D60D𝘍\mitsansFMathematical Sans-serif Italic Capital F
    U+1D60E𝘎\mitsansGMathematical Sans-serif Italic Capital G
    U+1D60F𝘏\mitsansHMathematical Sans-serif Italic Capital H
    U+1D610𝘐\mitsansIMathematical Sans-serif Italic Capital I
    U+1D611𝘑\mitsansJMathematical Sans-serif Italic Capital J
    U+1D612𝘒\mitsansKMathematical Sans-serif Italic Capital K
    U+1D613𝘓\mitsansLMathematical Sans-serif Italic Capital L
    U+1D614𝘔\mitsansMMathematical Sans-serif Italic Capital M
    U+1D615𝘕\mitsansNMathematical Sans-serif Italic Capital N
    U+1D616𝘖\mitsansOMathematical Sans-serif Italic Capital O
    U+1D617𝘗\mitsansPMathematical Sans-serif Italic Capital P
    U+1D618𝘘\mitsansQMathematical Sans-serif Italic Capital Q
    U+1D619𝘙\mitsansRMathematical Sans-serif Italic Capital R
    U+1D61A𝘚\mitsansSMathematical Sans-serif Italic Capital S
    U+1D61B𝘛\mitsansTMathematical Sans-serif Italic Capital T
    U+1D61C𝘜\mitsansUMathematical Sans-serif Italic Capital U
    U+1D61D𝘝\mitsansVMathematical Sans-serif Italic Capital V
    U+1D61E𝘞\mitsansWMathematical Sans-serif Italic Capital W
    U+1D61F𝘟\mitsansXMathematical Sans-serif Italic Capital X
    U+1D620𝘠\mitsansYMathematical Sans-serif Italic Capital Y
    U+1D621𝘡\mitsansZMathematical Sans-serif Italic Capital Z
    U+1D622𝘢\mitsansaMathematical Sans-serif Italic Small A
    U+1D623𝘣\mitsansbMathematical Sans-serif Italic Small B
    U+1D624𝘤\mitsanscMathematical Sans-serif Italic Small C
    U+1D625𝘥\mitsansdMathematical Sans-serif Italic Small D
    U+1D626𝘦\mitsanseMathematical Sans-serif Italic Small E
    U+1D627𝘧\mitsansfMathematical Sans-serif Italic Small F
    U+1D628𝘨\mitsansgMathematical Sans-serif Italic Small G
    U+1D629𝘩\mitsanshMathematical Sans-serif Italic Small H
    U+1D62A𝘪\mitsansiMathematical Sans-serif Italic Small I
    U+1D62B𝘫\mitsansjMathematical Sans-serif Italic Small J
    U+1D62C𝘬\mitsanskMathematical Sans-serif Italic Small K
    U+1D62D𝘭\mitsanslMathematical Sans-serif Italic Small L
    U+1D62E𝘮\mitsansmMathematical Sans-serif Italic Small M
    U+1D62F𝘯\mitsansnMathematical Sans-serif Italic Small N
    U+1D630𝘰\mitsansoMathematical Sans-serif Italic Small O
    U+1D631𝘱\mitsanspMathematical Sans-serif Italic Small P
    U+1D632𝘲\mitsansqMathematical Sans-serif Italic Small Q
    U+1D633𝘳\mitsansrMathematical Sans-serif Italic Small R
    U+1D634𝘴\mitsanssMathematical Sans-serif Italic Small S
    U+1D635𝘵\mitsanstMathematical Sans-serif Italic Small T
    U+1D636𝘶\mitsansuMathematical Sans-serif Italic Small U
    U+1D637𝘷\mitsansvMathematical Sans-serif Italic Small V
    U+1D638𝘸\mitsanswMathematical Sans-serif Italic Small W
    U+1D639𝘹\mitsansxMathematical Sans-serif Italic Small X
    U+1D63A𝘺\mitsansyMathematical Sans-serif Italic Small Y
    U+1D63B𝘻\mitsanszMathematical Sans-serif Italic Small Z
    U+1D63C𝘼\mbfitsansAMathematical Sans-serif Bold Italic Capital A
    U+1D63D𝘽\mbfitsansBMathematical Sans-serif Bold Italic Capital B
    U+1D63E𝘾\mbfitsansCMathematical Sans-serif Bold Italic Capital C
    U+1D63F𝘿\mbfitsansDMathematical Sans-serif Bold Italic Capital D
    U+1D640𝙀\mbfitsansEMathematical Sans-serif Bold Italic Capital E
    U+1D641𝙁\mbfitsansFMathematical Sans-serif Bold Italic Capital F
    U+1D642𝙂\mbfitsansGMathematical Sans-serif Bold Italic Capital G
    U+1D643𝙃\mbfitsansHMathematical Sans-serif Bold Italic Capital H
    U+1D644𝙄\mbfitsansIMathematical Sans-serif Bold Italic Capital I
    U+1D645𝙅\mbfitsansJMathematical Sans-serif Bold Italic Capital J
    U+1D646𝙆\mbfitsansKMathematical Sans-serif Bold Italic Capital K
    U+1D647𝙇\mbfitsansLMathematical Sans-serif Bold Italic Capital L
    U+1D648𝙈\mbfitsansMMathematical Sans-serif Bold Italic Capital M
    U+1D649𝙉\mbfitsansNMathematical Sans-serif Bold Italic Capital N
    U+1D64A𝙊\mbfitsansOMathematical Sans-serif Bold Italic Capital O
    U+1D64B𝙋\mbfitsansPMathematical Sans-serif Bold Italic Capital P
    U+1D64C𝙌\mbfitsansQMathematical Sans-serif Bold Italic Capital Q
    U+1D64D𝙍\mbfitsansRMathematical Sans-serif Bold Italic Capital R
    U+1D64E𝙎\mbfitsansSMathematical Sans-serif Bold Italic Capital S
    U+1D64F𝙏\mbfitsansTMathematical Sans-serif Bold Italic Capital T
    U+1D650𝙐\mbfitsansUMathematical Sans-serif Bold Italic Capital U
    U+1D651𝙑\mbfitsansVMathematical Sans-serif Bold Italic Capital V
    U+1D652𝙒\mbfitsansWMathematical Sans-serif Bold Italic Capital W
    U+1D653𝙓\mbfitsansXMathematical Sans-serif Bold Italic Capital X
    U+1D654𝙔\mbfitsansYMathematical Sans-serif Bold Italic Capital Y
    U+1D655𝙕\mbfitsansZMathematical Sans-serif Bold Italic Capital Z
    U+1D656𝙖\mbfitsansaMathematical Sans-serif Bold Italic Small A
    U+1D657𝙗\mbfitsansbMathematical Sans-serif Bold Italic Small B
    U+1D658𝙘\mbfitsanscMathematical Sans-serif Bold Italic Small C
    U+1D659𝙙\mbfitsansdMathematical Sans-serif Bold Italic Small D
    U+1D65A𝙚\mbfitsanseMathematical Sans-serif Bold Italic Small E
    U+1D65B𝙛\mbfitsansfMathematical Sans-serif Bold Italic Small F
    U+1D65C𝙜\mbfitsansgMathematical Sans-serif Bold Italic Small G
    U+1D65D𝙝\mbfitsanshMathematical Sans-serif Bold Italic Small H
    U+1D65E𝙞\mbfitsansiMathematical Sans-serif Bold Italic Small I
    U+1D65F𝙟\mbfitsansjMathematical Sans-serif Bold Italic Small J
    U+1D660𝙠\mbfitsanskMathematical Sans-serif Bold Italic Small K
    U+1D661𝙡\mbfitsanslMathematical Sans-serif Bold Italic Small L
    U+1D662𝙢\mbfitsansmMathematical Sans-serif Bold Italic Small M
    U+1D663𝙣\mbfitsansnMathematical Sans-serif Bold Italic Small N
    U+1D664𝙤\mbfitsansoMathematical Sans-serif Bold Italic Small O
    U+1D665𝙥\mbfitsanspMathematical Sans-serif Bold Italic Small P
    U+1D666𝙦\mbfitsansqMathematical Sans-serif Bold Italic Small Q
    U+1D667𝙧\mbfitsansrMathematical Sans-serif Bold Italic Small R
    U+1D668𝙨\mbfitsanssMathematical Sans-serif Bold Italic Small S
    U+1D669𝙩\mbfitsanstMathematical Sans-serif Bold Italic Small T
    U+1D66A𝙪\mbfitsansuMathematical Sans-serif Bold Italic Small U
    U+1D66B𝙫\mbfitsansvMathematical Sans-serif Bold Italic Small V
    U+1D66C𝙬\mbfitsanswMathematical Sans-serif Bold Italic Small W
    U+1D66D𝙭\mbfitsansxMathematical Sans-serif Bold Italic Small X
    U+1D66E𝙮\mbfitsansyMathematical Sans-serif Bold Italic Small Y
    U+1D66F𝙯\mbfitsanszMathematical Sans-serif Bold Italic Small Z
    U+1D670𝙰\mttAMathematical Monospace Capital A
    U+1D671𝙱\mttBMathematical Monospace Capital B
    U+1D672𝙲\mttCMathematical Monospace Capital C
    U+1D673𝙳\mttDMathematical Monospace Capital D
    U+1D674𝙴\mttEMathematical Monospace Capital E
    U+1D675𝙵\mttFMathematical Monospace Capital F
    U+1D676𝙶\mttGMathematical Monospace Capital G
    U+1D677𝙷\mttHMathematical Monospace Capital H
    U+1D678𝙸\mttIMathematical Monospace Capital I
    U+1D679𝙹\mttJMathematical Monospace Capital J
    U+1D67A𝙺\mttKMathematical Monospace Capital K
    U+1D67B𝙻\mttLMathematical Monospace Capital L
    U+1D67C𝙼\mttMMathematical Monospace Capital M
    U+1D67D𝙽\mttNMathematical Monospace Capital N
    U+1D67E𝙾\mttOMathematical Monospace Capital O
    U+1D67F𝙿\mttPMathematical Monospace Capital P
    U+1D680𝚀\mttQMathematical Monospace Capital Q
    U+1D681𝚁\mttRMathematical Monospace Capital R
    U+1D682𝚂\mttSMathematical Monospace Capital S
    U+1D683𝚃\mttTMathematical Monospace Capital T
    U+1D684𝚄\mttUMathematical Monospace Capital U
    U+1D685𝚅\mttVMathematical Monospace Capital V
    U+1D686𝚆\mttWMathematical Monospace Capital W
    U+1D687𝚇\mttXMathematical Monospace Capital X
    U+1D688𝚈\mttYMathematical Monospace Capital Y
    U+1D689𝚉\mttZMathematical Monospace Capital Z
    U+1D68A𝚊\mttaMathematical Monospace Small A
    U+1D68B𝚋\mttbMathematical Monospace Small B
    U+1D68C𝚌\mttcMathematical Monospace Small C
    U+1D68D𝚍\mttdMathematical Monospace Small D
    U+1D68E𝚎\mtteMathematical Monospace Small E
    U+1D68F𝚏\mttfMathematical Monospace Small F
    U+1D690𝚐\mttgMathematical Monospace Small G
    U+1D691𝚑\mtthMathematical Monospace Small H
    U+1D692𝚒\mttiMathematical Monospace Small I
    U+1D693𝚓\mttjMathematical Monospace Small J
    U+1D694𝚔\mttkMathematical Monospace Small K
    U+1D695𝚕\mttlMathematical Monospace Small L
    U+1D696𝚖\mttmMathematical Monospace Small M
    U+1D697𝚗\mttnMathematical Monospace Small N
    U+1D698𝚘\mttoMathematical Monospace Small O
    U+1D699𝚙\mttpMathematical Monospace Small P
    U+1D69A𝚚\mttqMathematical Monospace Small Q
    U+1D69B𝚛\mttrMathematical Monospace Small R
    U+1D69C𝚜\mttsMathematical Monospace Small S
    U+1D69D𝚝\mtttMathematical Monospace Small T
    U+1D69E𝚞\mttuMathematical Monospace Small U
    U+1D69F𝚟\mttvMathematical Monospace Small V
    U+1D6A0𝚠\mttwMathematical Monospace Small W
    U+1D6A1𝚡\mttxMathematical Monospace Small X
    U+1D6A2𝚢\mttyMathematical Monospace Small Y
    U+1D6A3𝚣\mttzMathematical Monospace Small Z
    U+1D6A4𝚤\imathMathematical Italic Small Dotless I
    U+1D6A5𝚥\jmathMathematical Italic Small Dotless J
    U+1D6A8𝚨\mbfAlphaMathematical Bold Capital Alpha
    U+1D6A9𝚩\mbfBetaMathematical Bold Capital Beta
    U+1D6AA𝚪\mbfGammaMathematical Bold Capital Gamma
    U+1D6AB𝚫\mbfDeltaMathematical Bold Capital Delta
    U+1D6AC𝚬\mbfEpsilonMathematical Bold Capital Epsilon
    U+1D6AD𝚭\mbfZetaMathematical Bold Capital Zeta
    U+1D6AE𝚮\mbfEtaMathematical Bold Capital Eta
    U+1D6AF𝚯\mbfThetaMathematical Bold Capital Theta
    U+1D6B0𝚰\mbfIotaMathematical Bold Capital Iota
    U+1D6B1𝚱\mbfKappaMathematical Bold Capital Kappa
    U+1D6B2𝚲\mbfLambdaMathematical Bold Capital Lamda
    U+1D6B3𝚳\mbfMuMathematical Bold Capital Mu
    U+1D6B4𝚴\mbfNuMathematical Bold Capital Nu
    U+1D6B5𝚵\mbfXiMathematical Bold Capital Xi
    U+1D6B6𝚶\mbfOmicronMathematical Bold Capital Omicron
    U+1D6B7𝚷\mbfPiMathematical Bold Capital Pi
    U+1D6B8𝚸\mbfRhoMathematical Bold Capital Rho
    U+1D6B9𝚹\mbfvarThetaMathematical Bold Capital Theta Symbol
    U+1D6BA𝚺\mbfSigmaMathematical Bold Capital Sigma
    U+1D6BB𝚻\mbfTauMathematical Bold Capital Tau
    U+1D6BC𝚼\mbfUpsilonMathematical Bold Capital Upsilon
    U+1D6BD𝚽\mbfPhiMathematical Bold Capital Phi
    U+1D6BE𝚾\mbfChiMathematical Bold Capital Chi
    U+1D6BF𝚿\mbfPsiMathematical Bold Capital Psi
    U+1D6C0𝛀\mbfOmegaMathematical Bold Capital Omega
    U+1D6C1𝛁\mbfnablaMathematical Bold Nabla
    U+1D6C2𝛂\mbfalphaMathematical Bold Small Alpha
    U+1D6C3𝛃\mbfbetaMathematical Bold Small Beta
    U+1D6C4𝛄\mbfgammaMathematical Bold Small Gamma
    U+1D6C5𝛅\mbfdeltaMathematical Bold Small Delta
    U+1D6C6𝛆\mbfepsilonMathematical Bold Small Epsilon
    U+1D6C7𝛇\mbfzetaMathematical Bold Small Zeta
    U+1D6C8𝛈\mbfetaMathematical Bold Small Eta
    U+1D6C9𝛉\mbfthetaMathematical Bold Small Theta
    U+1D6CA𝛊\mbfiotaMathematical Bold Small Iota
    U+1D6CB𝛋\mbfkappaMathematical Bold Small Kappa
    U+1D6CC𝛌\mbflambdaMathematical Bold Small Lamda
    U+1D6CD𝛍\mbfmuMathematical Bold Small Mu
    U+1D6CE𝛎\mbfnuMathematical Bold Small Nu
    U+1D6CF𝛏\mbfxiMathematical Bold Small Xi
    U+1D6D0𝛐\mbfomicronMathematical Bold Small Omicron
    U+1D6D1𝛑\mbfpiMathematical Bold Small Pi
    U+1D6D2𝛒\mbfrhoMathematical Bold Small Rho
    U+1D6D3𝛓\mbfvarsigmaMathematical Bold Small Final Sigma
    U+1D6D4𝛔\mbfsigmaMathematical Bold Small Sigma
    U+1D6D5𝛕\mbftauMathematical Bold Small Tau
    U+1D6D6𝛖\mbfupsilonMathematical Bold Small Upsilon
    U+1D6D7𝛗\mbfvarphiMathematical Bold Small Phi
    U+1D6D8𝛘\mbfchiMathematical Bold Small Chi
    U+1D6D9𝛙\mbfpsiMathematical Bold Small Psi
    U+1D6DA𝛚\mbfomegaMathematical Bold Small Omega
    U+1D6DB𝛛\mbfpartialMathematical Bold Partial Differential
    U+1D6DC𝛜\mbfvarepsilonMathematical Bold Epsilon Symbol
    U+1D6DD𝛝\mbfvarthetaMathematical Bold Theta Symbol
    U+1D6DE𝛞\mbfvarkappaMathematical Bold Kappa Symbol
    U+1D6DF𝛟\mbfphiMathematical Bold Phi Symbol
    U+1D6E0𝛠\mbfvarrhoMathematical Bold Rho Symbol
    U+1D6E1𝛡\mbfvarpiMathematical Bold Pi Symbol
    U+1D6E2𝛢\mitAlphaMathematical Italic Capital Alpha
    U+1D6E3𝛣\mitBetaMathematical Italic Capital Beta
    U+1D6E4𝛤\mitGammaMathematical Italic Capital Gamma
    U+1D6E5𝛥\mitDeltaMathematical Italic Capital Delta
    U+1D6E6𝛦\mitEpsilonMathematical Italic Capital Epsilon
    U+1D6E7𝛧\mitZetaMathematical Italic Capital Zeta
    U+1D6E8𝛨\mitEtaMathematical Italic Capital Eta
    U+1D6E9𝛩\mitThetaMathematical Italic Capital Theta
    U+1D6EA𝛪\mitIotaMathematical Italic Capital Iota
    U+1D6EB𝛫\mitKappaMathematical Italic Capital Kappa
    U+1D6EC𝛬\mitLambdaMathematical Italic Capital Lamda
    U+1D6ED𝛭\mitMuMathematical Italic Capital Mu
    U+1D6EE𝛮\mitNuMathematical Italic Capital Nu
    U+1D6EF𝛯\mitXiMathematical Italic Capital Xi
    U+1D6F0𝛰\mitOmicronMathematical Italic Capital Omicron
    U+1D6F1𝛱\mitPiMathematical Italic Capital Pi
    U+1D6F2𝛲\mitRhoMathematical Italic Capital Rho
    U+1D6F3𝛳\mitvarThetaMathematical Italic Capital Theta Symbol
    U+1D6F4𝛴\mitSigmaMathematical Italic Capital Sigma
    U+1D6F5𝛵\mitTauMathematical Italic Capital Tau
    U+1D6F6𝛶\mitUpsilonMathematical Italic Capital Upsilon
    U+1D6F7𝛷\mitPhiMathematical Italic Capital Phi
    U+1D6F8𝛸\mitChiMathematical Italic Capital Chi
    U+1D6F9𝛹\mitPsiMathematical Italic Capital Psi
    U+1D6FA𝛺\mitOmegaMathematical Italic Capital Omega
    U+1D6FB𝛻\mitnablaMathematical Italic Nabla
    U+1D6FC𝛼\mitalphaMathematical Italic Small Alpha
    U+1D6FD𝛽\mitbetaMathematical Italic Small Beta
    U+1D6FE𝛾\mitgammaMathematical Italic Small Gamma
    U+1D6FF𝛿\mitdeltaMathematical Italic Small Delta
    U+1D700𝜀\mitepsilonMathematical Italic Small Epsilon
    U+1D701𝜁\mitzetaMathematical Italic Small Zeta
    U+1D702𝜂\mitetaMathematical Italic Small Eta
    U+1D703𝜃\mitthetaMathematical Italic Small Theta
    U+1D704𝜄\mitiotaMathematical Italic Small Iota
    U+1D705𝜅\mitkappaMathematical Italic Small Kappa
    U+1D706𝜆\mitlambdaMathematical Italic Small Lamda
    U+1D707𝜇\mitmuMathematical Italic Small Mu
    U+1D708𝜈\mitnuMathematical Italic Small Nu
    U+1D709𝜉\mitxiMathematical Italic Small Xi
    U+1D70A𝜊\mitomicronMathematical Italic Small Omicron
    U+1D70B𝜋\mitpiMathematical Italic Small Pi
    U+1D70C𝜌\mitrhoMathematical Italic Small Rho
    U+1D70D𝜍\mitvarsigmaMathematical Italic Small Final Sigma
    U+1D70E𝜎\mitsigmaMathematical Italic Small Sigma
    U+1D70F𝜏\mittauMathematical Italic Small Tau
    U+1D710𝜐\mitupsilonMathematical Italic Small Upsilon
    U+1D711𝜑\mitphiMathematical Italic Small Phi
    U+1D712𝜒\mitchiMathematical Italic Small Chi
    U+1D713𝜓\mitpsiMathematical Italic Small Psi
    U+1D714𝜔\mitomegaMathematical Italic Small Omega
    U+1D715𝜕\mitpartialMathematical Italic Partial Differential
    U+1D716𝜖\mitvarepsilonMathematical Italic Epsilon Symbol
    U+1D717𝜗\mitvarthetaMathematical Italic Theta Symbol
    U+1D718𝜘\mitvarkappaMathematical Italic Kappa Symbol
    U+1D719𝜙\mitvarphiMathematical Italic Phi Symbol
    U+1D71A𝜚\mitvarrhoMathematical Italic Rho Symbol
    U+1D71B𝜛\mitvarpiMathematical Italic Pi Symbol
    U+1D71C𝜜\mbfitAlphaMathematical Bold Italic Capital Alpha
    U+1D71D𝜝\mbfitBetaMathematical Bold Italic Capital Beta
    U+1D71E𝜞\mbfitGammaMathematical Bold Italic Capital Gamma
    U+1D71F𝜟\mbfitDeltaMathematical Bold Italic Capital Delta
    U+1D720𝜠\mbfitEpsilonMathematical Bold Italic Capital Epsilon
    U+1D721𝜡\mbfitZetaMathematical Bold Italic Capital Zeta
    U+1D722𝜢\mbfitEtaMathematical Bold Italic Capital Eta
    U+1D723𝜣\mbfitThetaMathematical Bold Italic Capital Theta
    U+1D724𝜤\mbfitIotaMathematical Bold Italic Capital Iota
    U+1D725𝜥\mbfitKappaMathematical Bold Italic Capital Kappa
    U+1D726𝜦\mbfitLambdaMathematical Bold Italic Capital Lamda
    U+1D727𝜧\mbfitMuMathematical Bold Italic Capital Mu
    U+1D728𝜨\mbfitNuMathematical Bold Italic Capital Nu
    U+1D729𝜩\mbfitXiMathematical Bold Italic Capital Xi
    U+1D72A𝜪\mbfitOmicronMathematical Bold Italic Capital Omicron
    U+1D72B𝜫\mbfitPiMathematical Bold Italic Capital Pi
    U+1D72C𝜬\mbfitRhoMathematical Bold Italic Capital Rho
    U+1D72D𝜭\mbfitvarThetaMathematical Bold Italic Capital Theta Symbol
    U+1D72E𝜮\mbfitSigmaMathematical Bold Italic Capital Sigma
    U+1D72F𝜯\mbfitTauMathematical Bold Italic Capital Tau
    U+1D730𝜰\mbfitUpsilonMathematical Bold Italic Capital Upsilon
    U+1D731𝜱\mbfitPhiMathematical Bold Italic Capital Phi
    U+1D732𝜲\mbfitChiMathematical Bold Italic Capital Chi
    U+1D733𝜳\mbfitPsiMathematical Bold Italic Capital Psi
    U+1D734𝜴\mbfitOmegaMathematical Bold Italic Capital Omega
    U+1D735𝜵\mbfitnablaMathematical Bold Italic Nabla
    U+1D736𝜶\mbfitalphaMathematical Bold Italic Small Alpha
    U+1D737𝜷\mbfitbetaMathematical Bold Italic Small Beta
    U+1D738𝜸\mbfitgammaMathematical Bold Italic Small Gamma
    U+1D739𝜹\mbfitdeltaMathematical Bold Italic Small Delta
    U+1D73A𝜺\mbfitepsilonMathematical Bold Italic Small Epsilon
    U+1D73B𝜻\mbfitzetaMathematical Bold Italic Small Zeta
    U+1D73C𝜼\mbfitetaMathematical Bold Italic Small Eta
    U+1D73D𝜽\mbfitthetaMathematical Bold Italic Small Theta
    U+1D73E𝜾\mbfitiotaMathematical Bold Italic Small Iota
    U+1D73F𝜿\mbfitkappaMathematical Bold Italic Small Kappa
    U+1D740𝝀\mbfitlambdaMathematical Bold Italic Small Lamda
    U+1D741𝝁\mbfitmuMathematical Bold Italic Small Mu
    U+1D742𝝂\mbfitnuMathematical Bold Italic Small Nu
    U+1D743𝝃\mbfitxiMathematical Bold Italic Small Xi
    U+1D744𝝄\mbfitomicronMathematical Bold Italic Small Omicron
    U+1D745𝝅\mbfitpiMathematical Bold Italic Small Pi
    U+1D746𝝆\mbfitrhoMathematical Bold Italic Small Rho
    U+1D747𝝇\mbfitvarsigmaMathematical Bold Italic Small Final Sigma
    U+1D748𝝈\mbfitsigmaMathematical Bold Italic Small Sigma
    U+1D749𝝉\mbfittauMathematical Bold Italic Small Tau
    U+1D74A𝝊\mbfitupsilonMathematical Bold Italic Small Upsilon
    U+1D74B𝝋\mbfitphiMathematical Bold Italic Small Phi
    U+1D74C𝝌\mbfitchiMathematical Bold Italic Small Chi
    U+1D74D𝝍\mbfitpsiMathematical Bold Italic Small Psi
    U+1D74E𝝎\mbfitomegaMathematical Bold Italic Small Omega
    U+1D74F𝝏\mbfitpartialMathematical Bold Italic Partial Differential
    U+1D750𝝐\mbfitvarepsilonMathematical Bold Italic Epsilon Symbol
    U+1D751𝝑\mbfitvarthetaMathematical Bold Italic Theta Symbol
    U+1D752𝝒\mbfitvarkappaMathematical Bold Italic Kappa Symbol
    U+1D753𝝓\mbfitvarphiMathematical Bold Italic Phi Symbol
    U+1D754𝝔\mbfitvarrhoMathematical Bold Italic Rho Symbol
    U+1D755𝝕\mbfitvarpiMathematical Bold Italic Pi Symbol
    U+1D756𝝖\mbfsansAlphaMathematical Sans-serif Bold Capital Alpha
    U+1D757𝝗\mbfsansBetaMathematical Sans-serif Bold Capital Beta
    U+1D758𝝘\mbfsansGammaMathematical Sans-serif Bold Capital Gamma
    U+1D759𝝙\mbfsansDeltaMathematical Sans-serif Bold Capital Delta
    U+1D75A𝝚\mbfsansEpsilonMathematical Sans-serif Bold Capital Epsilon
    U+1D75B𝝛\mbfsansZetaMathematical Sans-serif Bold Capital Zeta
    U+1D75C𝝜\mbfsansEtaMathematical Sans-serif Bold Capital Eta
    U+1D75D𝝝\mbfsansThetaMathematical Sans-serif Bold Capital Theta
    U+1D75E𝝞\mbfsansIotaMathematical Sans-serif Bold Capital Iota
    U+1D75F𝝟\mbfsansKappaMathematical Sans-serif Bold Capital Kappa
    U+1D760𝝠\mbfsansLambdaMathematical Sans-serif Bold Capital Lamda
    U+1D761𝝡\mbfsansMuMathematical Sans-serif Bold Capital Mu
    U+1D762𝝢\mbfsansNuMathematical Sans-serif Bold Capital Nu
    U+1D763𝝣\mbfsansXiMathematical Sans-serif Bold Capital Xi
    U+1D764𝝤\mbfsansOmicronMathematical Sans-serif Bold Capital Omicron
    U+1D765𝝥\mbfsansPiMathematical Sans-serif Bold Capital Pi
    U+1D766𝝦\mbfsansRhoMathematical Sans-serif Bold Capital Rho
    U+1D767𝝧\mbfsansvarThetaMathematical Sans-serif Bold Capital Theta Symbol
    U+1D768𝝨\mbfsansSigmaMathematical Sans-serif Bold Capital Sigma
    U+1D769𝝩\mbfsansTauMathematical Sans-serif Bold Capital Tau
    U+1D76A𝝪\mbfsansUpsilonMathematical Sans-serif Bold Capital Upsilon
    U+1D76B𝝫\mbfsansPhiMathematical Sans-serif Bold Capital Phi
    U+1D76C𝝬\mbfsansChiMathematical Sans-serif Bold Capital Chi
    U+1D76D𝝭\mbfsansPsiMathematical Sans-serif Bold Capital Psi
    U+1D76E𝝮\mbfsansOmegaMathematical Sans-serif Bold Capital Omega
    U+1D76F𝝯\mbfsansnablaMathematical Sans-serif Bold Nabla
    U+1D770𝝰\mbfsansalphaMathematical Sans-serif Bold Small Alpha
    U+1D771𝝱\mbfsansbetaMathematical Sans-serif Bold Small Beta
    U+1D772𝝲\mbfsansgammaMathematical Sans-serif Bold Small Gamma
    U+1D773𝝳\mbfsansdeltaMathematical Sans-serif Bold Small Delta
    U+1D774𝝴\mbfsansepsilonMathematical Sans-serif Bold Small Epsilon
    U+1D775𝝵\mbfsanszetaMathematical Sans-serif Bold Small Zeta
    U+1D776𝝶\mbfsansetaMathematical Sans-serif Bold Small Eta
    U+1D777𝝷\mbfsansthetaMathematical Sans-serif Bold Small Theta
    U+1D778𝝸\mbfsansiotaMathematical Sans-serif Bold Small Iota
    U+1D779𝝹\mbfsanskappaMathematical Sans-serif Bold Small Kappa
    U+1D77A𝝺\mbfsanslambdaMathematical Sans-serif Bold Small Lamda
    U+1D77B𝝻\mbfsansmuMathematical Sans-serif Bold Small Mu
    U+1D77C𝝼\mbfsansnuMathematical Sans-serif Bold Small Nu
    U+1D77D𝝽\mbfsansxiMathematical Sans-serif Bold Small Xi
    U+1D77E𝝾\mbfsansomicronMathematical Sans-serif Bold Small Omicron
    U+1D77F𝝿\mbfsanspiMathematical Sans-serif Bold Small Pi
    U+1D780𝞀\mbfsansrhoMathematical Sans-serif Bold Small Rho
    U+1D781𝞁\mbfsansvarsigmaMathematical Sans-serif Bold Small Final Sigma
    U+1D782𝞂\mbfsanssigmaMathematical Sans-serif Bold Small Sigma
    U+1D783𝞃\mbfsanstauMathematical Sans-serif Bold Small Tau
    U+1D784𝞄\mbfsansupsilonMathematical Sans-serif Bold Small Upsilon
    U+1D785𝞅\mbfsansphiMathematical Sans-serif Bold Small Phi
    U+1D786𝞆\mbfsanschiMathematical Sans-serif Bold Small Chi
    U+1D787𝞇\mbfsanspsiMathematical Sans-serif Bold Small Psi
    U+1D788𝞈\mbfsansomegaMathematical Sans-serif Bold Small Omega
    U+1D789𝞉\mbfsanspartialMathematical Sans-serif Bold Partial Differential
    U+1D78A𝞊\mbfsansvarepsilonMathematical Sans-serif Bold Epsilon Symbol
    U+1D78B𝞋\mbfsansvarthetaMathematical Sans-serif Bold Theta Symbol
    U+1D78C𝞌\mbfsansvarkappaMathematical Sans-serif Bold Kappa Symbol
    U+1D78D𝞍\mbfsansvarphiMathematical Sans-serif Bold Phi Symbol
    U+1D78E𝞎\mbfsansvarrhoMathematical Sans-serif Bold Rho Symbol
    U+1D78F𝞏\mbfsansvarpiMathematical Sans-serif Bold Pi Symbol
    U+1D790𝞐\mbfitsansAlphaMathematical Sans-serif Bold Italic Capital Alpha
    U+1D791𝞑\mbfitsansBetaMathematical Sans-serif Bold Italic Capital Beta
    U+1D792𝞒\mbfitsansGammaMathematical Sans-serif Bold Italic Capital Gamma
    U+1D793𝞓\mbfitsansDeltaMathematical Sans-serif Bold Italic Capital Delta
    U+1D794𝞔\mbfitsansEpsilonMathematical Sans-serif Bold Italic Capital Epsilon
    U+1D795𝞕\mbfitsansZetaMathematical Sans-serif Bold Italic Capital Zeta
    U+1D796𝞖\mbfitsansEtaMathematical Sans-serif Bold Italic Capital Eta
    U+1D797𝞗\mbfitsansThetaMathematical Sans-serif Bold Italic Capital Theta
    U+1D798𝞘\mbfitsansIotaMathematical Sans-serif Bold Italic Capital Iota
    U+1D799𝞙\mbfitsansKappaMathematical Sans-serif Bold Italic Capital Kappa
    U+1D79A𝞚\mbfitsansLambdaMathematical Sans-serif Bold Italic Capital Lamda
    U+1D79B𝞛\mbfitsansMuMathematical Sans-serif Bold Italic Capital Mu
    U+1D79C𝞜\mbfitsansNuMathematical Sans-serif Bold Italic Capital Nu
    U+1D79D𝞝\mbfitsansXiMathematical Sans-serif Bold Italic Capital Xi
    U+1D79E𝞞\mbfitsansOmicronMathematical Sans-serif Bold Italic Capital Omicron
    U+1D79F𝞟\mbfitsansPiMathematical Sans-serif Bold Italic Capital Pi
    U+1D7A0𝞠\mbfitsansRhoMathematical Sans-serif Bold Italic Capital Rho
    U+1D7A1𝞡\mbfitsansvarThetaMathematical Sans-serif Bold Italic Capital Theta Symbol
    U+1D7A2𝞢\mbfitsansSigmaMathematical Sans-serif Bold Italic Capital Sigma
    U+1D7A3𝞣\mbfitsansTauMathematical Sans-serif Bold Italic Capital Tau
    U+1D7A4𝞤\mbfitsansUpsilonMathematical Sans-serif Bold Italic Capital Upsilon
    U+1D7A5𝞥\mbfitsansPhiMathematical Sans-serif Bold Italic Capital Phi
    U+1D7A6𝞦\mbfitsansChiMathematical Sans-serif Bold Italic Capital Chi
    U+1D7A7𝞧\mbfitsansPsiMathematical Sans-serif Bold Italic Capital Psi
    U+1D7A8𝞨\mbfitsansOmegaMathematical Sans-serif Bold Italic Capital Omega
    U+1D7A9𝞩\mbfitsansnablaMathematical Sans-serif Bold Italic Nabla
    U+1D7AA𝞪\mbfitsansalphaMathematical Sans-serif Bold Italic Small Alpha
    U+1D7AB𝞫\mbfitsansbetaMathematical Sans-serif Bold Italic Small Beta
    U+1D7AC𝞬\mbfitsansgammaMathematical Sans-serif Bold Italic Small Gamma
    U+1D7AD𝞭\mbfitsansdeltaMathematical Sans-serif Bold Italic Small Delta
    U+1D7AE𝞮\mbfitsansepsilonMathematical Sans-serif Bold Italic Small Epsilon
    U+1D7AF𝞯\mbfitsanszetaMathematical Sans-serif Bold Italic Small Zeta
    U+1D7B0𝞰\mbfitsansetaMathematical Sans-serif Bold Italic Small Eta
    U+1D7B1𝞱\mbfitsansthetaMathematical Sans-serif Bold Italic Small Theta
    U+1D7B2𝞲\mbfitsansiotaMathematical Sans-serif Bold Italic Small Iota
    U+1D7B3𝞳\mbfitsanskappaMathematical Sans-serif Bold Italic Small Kappa
    U+1D7B4𝞴\mbfitsanslambdaMathematical Sans-serif Bold Italic Small Lamda
    U+1D7B5𝞵\mbfitsansmuMathematical Sans-serif Bold Italic Small Mu
    U+1D7B6𝞶\mbfitsansnuMathematical Sans-serif Bold Italic Small Nu
    U+1D7B7𝞷\mbfitsansxiMathematical Sans-serif Bold Italic Small Xi
    U+1D7B8𝞸\mbfitsansomicronMathematical Sans-serif Bold Italic Small Omicron
    U+1D7B9𝞹\mbfitsanspiMathematical Sans-serif Bold Italic Small Pi
    U+1D7BA𝞺\mbfitsansrhoMathematical Sans-serif Bold Italic Small Rho
    U+1D7BB𝞻\mbfitsansvarsigmaMathematical Sans-serif Bold Italic Small Final Sigma
    U+1D7BC𝞼\mbfitsanssigmaMathematical Sans-serif Bold Italic Small Sigma
    U+1D7BD𝞽\mbfitsanstauMathematical Sans-serif Bold Italic Small Tau
    U+1D7BE𝞾\mbfitsansupsilonMathematical Sans-serif Bold Italic Small Upsilon
    U+1D7BF𝞿\mbfitsansphiMathematical Sans-serif Bold Italic Small Phi
    U+1D7C0𝟀\mbfitsanschiMathematical Sans-serif Bold Italic Small Chi
    U+1D7C1𝟁\mbfitsanspsiMathematical Sans-serif Bold Italic Small Psi
    U+1D7C2𝟂\mbfitsansomegaMathematical Sans-serif Bold Italic Small Omega
    U+1D7C3𝟃\mbfitsanspartialMathematical Sans-serif Bold Italic Partial Differential
    U+1D7C4𝟄\mbfitsansvarepsilonMathematical Sans-serif Bold Italic Epsilon Symbol
    U+1D7C5𝟅\mbfitsansvarthetaMathematical Sans-serif Bold Italic Theta Symbol
    U+1D7C6𝟆\mbfitsansvarkappaMathematical Sans-serif Bold Italic Kappa Symbol
    U+1D7C7𝟇\mbfitsansvarphiMathematical Sans-serif Bold Italic Phi Symbol
    U+1D7C8𝟈\mbfitsansvarrhoMathematical Sans-serif Bold Italic Rho Symbol
    U+1D7C9𝟉\mbfitsansvarpiMathematical Sans-serif Bold Italic Pi Symbol
    U+1D7CA𝟊\mbfDigammaMathematical Bold Capital Digamma
    U+1D7CB𝟋\mbfdigammaMathematical Bold Small Digamma
    U+1D7CE𝟎\mbfzeroMathematical Bold Digit Zero
    U+1D7CF𝟏\mbfoneMathematical Bold Digit One
    U+1D7D0𝟐\mbftwoMathematical Bold Digit Two
    U+1D7D1𝟑\mbfthreeMathematical Bold Digit Three
    U+1D7D2𝟒\mbffourMathematical Bold Digit Four
    U+1D7D3𝟓\mbffiveMathematical Bold Digit Five
    U+1D7D4𝟔\mbfsixMathematical Bold Digit Six
    U+1D7D5𝟕\mbfsevenMathematical Bold Digit Seven
    U+1D7D6𝟖\mbfeightMathematical Bold Digit Eight
    U+1D7D7𝟗\mbfnineMathematical Bold Digit Nine
    U+1D7D8𝟘\BbbzeroMathematical Double-struck Digit Zero
    U+1D7D9𝟙\BbboneMathematical Double-struck Digit One
    U+1D7DA𝟚\BbbtwoMathematical Double-struck Digit Two
    U+1D7DB𝟛\BbbthreeMathematical Double-struck Digit Three
    U+1D7DC𝟜\BbbfourMathematical Double-struck Digit Four
    U+1D7DD𝟝\BbbfiveMathematical Double-struck Digit Five
    U+1D7DE𝟞\BbbsixMathematical Double-struck Digit Six
    U+1D7DF𝟟\BbbsevenMathematical Double-struck Digit Seven
    U+1D7E0𝟠\BbbeightMathematical Double-struck Digit Eight
    U+1D7E1𝟡\BbbnineMathematical Double-struck Digit Nine
    U+1D7E2𝟢\msanszeroMathematical Sans-serif Digit Zero
    U+1D7E3𝟣\msansoneMathematical Sans-serif Digit One
    U+1D7E4𝟤\msanstwoMathematical Sans-serif Digit Two
    U+1D7E5𝟥\msansthreeMathematical Sans-serif Digit Three
    U+1D7E6𝟦\msansfourMathematical Sans-serif Digit Four
    U+1D7E7𝟧\msansfiveMathematical Sans-serif Digit Five
    U+1D7E8𝟨\msanssixMathematical Sans-serif Digit Six
    U+1D7E9𝟩\msanssevenMathematical Sans-serif Digit Seven
    U+1D7EA𝟪\msanseightMathematical Sans-serif Digit Eight
    U+1D7EB𝟫\msansnineMathematical Sans-serif Digit Nine
    U+1D7EC𝟬\mbfsanszeroMathematical Sans-serif Bold Digit Zero
    U+1D7ED𝟭\mbfsansoneMathematical Sans-serif Bold Digit One
    U+1D7EE𝟮\mbfsanstwoMathematical Sans-serif Bold Digit Two
    U+1D7EF𝟯\mbfsansthreeMathematical Sans-serif Bold Digit Three
    U+1D7F0𝟰\mbfsansfourMathematical Sans-serif Bold Digit Four
    U+1D7F1𝟱\mbfsansfiveMathematical Sans-serif Bold Digit Five
    U+1D7F2𝟲\mbfsanssixMathematical Sans-serif Bold Digit Six
    U+1D7F3𝟳\mbfsanssevenMathematical Sans-serif Bold Digit Seven
    U+1D7F4𝟴\mbfsanseightMathematical Sans-serif Bold Digit Eight
    U+1D7F5𝟵\mbfsansnineMathematical Sans-serif Bold Digit Nine
    U+1D7F6𝟶\mttzeroMathematical Monospace Digit Zero
    U+1D7F7𝟷\mttoneMathematical Monospace Digit One
    U+1D7F8𝟸\mtttwoMathematical Monospace Digit Two
    U+1D7F9𝟹\mttthreeMathematical Monospace Digit Three
    U+1D7FA𝟺\mttfourMathematical Monospace Digit Four
    U+1D7FB𝟻\mttfiveMathematical Monospace Digit Five
    U+1D7FC𝟼\mttsixMathematical Monospace Digit Six
    U+1D7FD𝟽\mttsevenMathematical Monospace Digit Seven
    U+1D7FE𝟾\mtteightMathematical Monospace Digit Eight
    U+1D7FF𝟿\mttnineMathematical Monospace Digit Nine
    U+1F004🀄\:mahjong:Mahjong Tile Red Dragon
    U+1F0CF🃏\:black_joker:Playing Card Black Joker
    U+1F170🅰\:a:Negative Squared Latin Capital Letter A
    U+1F171🅱\:b:Negative Squared Latin Capital Letter B
    U+1F17E🅾\:o2:Negative Squared Latin Capital Letter O
    U+1F17F🅿\:parking:Negative Squared Latin Capital Letter P
    U+1F18E🆎\:ab:Negative Squared Ab
    U+1F191🆑\:cl:Squared Cl
    U+1F192🆒\:cool:Squared Cool
    U+1F193🆓\:free:Squared Free
    U+1F194🆔\:id:Squared Id
    U+1F195🆕\:new:Squared New
    U+1F196🆖\:ng:Squared Ng
    U+1F197🆗\:ok:Squared Ok
    U+1F198🆘\:sos:Squared Sos
    U+1F199🆙\:up:Squared Up With Exclamation Mark
    U+1F19A🆚\:vs:Squared Vs
    U+1F201🈁\:koko:Squared Katakana Koko
    U+1F202🈂\:sa:Squared Katakana Sa
    U+1F21A🈚\:u7121:Squared Cjk Unified Ideograph-7121
    U+1F22F🈯\:u6307:Squared Cjk Unified Ideograph-6307
    U+1F232🈲\:u7981:Squared Cjk Unified Ideograph-7981
    U+1F233🈳\:u7a7a:Squared Cjk Unified Ideograph-7a7a
    U+1F234🈴\:u5408:Squared Cjk Unified Ideograph-5408
    U+1F235🈵\:u6e80:Squared Cjk Unified Ideograph-6e80
    U+1F236🈶\:u6709:Squared Cjk Unified Ideograph-6709
    U+1F237🈷\:u6708:Squared Cjk Unified Ideograph-6708
    U+1F238🈸\:u7533:Squared Cjk Unified Ideograph-7533
    U+1F239🈹\:u5272:Squared Cjk Unified Ideograph-5272
    U+1F23A🈺\:u55b6:Squared Cjk Unified Ideograph-55b6
    U+1F250🉐\:ideograph_advantage:Circled Ideograph Advantage
    U+1F251🉑\:accept:Circled Ideograph Accept
    U+1F300🌀\:cyclone:Cyclone
    U+1F301🌁\:foggy:Foggy
    U+1F302🌂\:closed_umbrella:Closed Umbrella
    U+1F303🌃\:night_with_stars:Night With Stars
    U+1F304🌄\:sunrise_over_mountains:Sunrise Over Mountains
    U+1F305🌅\:sunrise:Sunrise
    U+1F306🌆\:city_sunset:Cityscape At Dusk
    U+1F307🌇\:city_sunrise:Sunset Over Buildings
    U+1F308🌈\:rainbow:Rainbow
    U+1F309🌉\:bridge_at_night:Bridge At Night
    U+1F30A🌊\:ocean:Water Wave
    U+1F30B🌋\:volcano:Volcano
    U+1F30C🌌\:milky_way:Milky Way
    U+1F30D🌍\:earth_africa:Earth Globe Europe-africa
    U+1F30E🌎\:earth_americas:Earth Globe Americas
    U+1F30F🌏\:earth_asia:Earth Globe Asia-australia
    U+1F310🌐\:globe_with_meridians:Globe With Meridians
    U+1F311🌑\:new_moon:New Moon Symbol
    U+1F312🌒\:waxing_crescent_moon:Waxing Crescent Moon Symbol
    U+1F313🌓\:first_quarter_moon:First Quarter Moon Symbol
    U+1F314🌔\:moon:Waxing Gibbous Moon Symbol
    U+1F315🌕\:full_moon:Full Moon Symbol
    U+1F316🌖\:waning_gibbous_moon:Waning Gibbous Moon Symbol
    U+1F317🌗\:last_quarter_moon:Last Quarter Moon Symbol
    U+1F318🌘\:waning_crescent_moon:Waning Crescent Moon Symbol
    U+1F319🌙\:crescent_moon:Crescent Moon
    U+1F31A🌚\:new_moon_with_face:New Moon With Face
    U+1F31B🌛\:first_quarter_moon_with_face:First Quarter Moon With Face
    U+1F31C🌜\:last_quarter_moon_with_face:Last Quarter Moon With Face
    U+1F31D🌝\:full_moon_with_face:Full Moon With Face
    U+1F31E🌞\:sun_with_face:Sun With Face
    U+1F31F🌟\:star2:Glowing Star
    U+1F320🌠\:stars:Shooting Star
    U+1F330🌰\:chestnut:Chestnut
    U+1F331🌱\:seedling:Seedling
    U+1F332🌲\:evergreen_tree:Evergreen Tree
    U+1F333🌳\:deciduous_tree:Deciduous Tree
    U+1F334🌴\:palm_tree:Palm Tree
    U+1F335🌵\:cactus:Cactus
    U+1F337🌷\:tulip:Tulip
    U+1F338🌸\:cherry_blossom:Cherry Blossom
    U+1F339🌹\:rose:Rose
    U+1F33A🌺\:hibiscus:Hibiscus
    U+1F33B🌻\:sunflower:Sunflower
    U+1F33C🌼\:blossom:Blossom
    U+1F33D🌽\:corn:Ear Of Maize
    U+1F33E🌾\:ear_of_rice:Ear Of Rice
    U+1F33F🌿\:herb:Herb
    U+1F340🍀\:four_leaf_clover:Four Leaf Clover
    U+1F341🍁\:maple_leaf:Maple Leaf
    U+1F342🍂\:fallen_leaf:Fallen Leaf
    U+1F343🍃\:leaves:Leaf Fluttering In Wind
    U+1F344🍄\:mushroom:Mushroom
    U+1F345🍅\:tomato:Tomato
    U+1F346🍆\:eggplant:Aubergine
    U+1F347🍇\:grapes:Grapes
    U+1F348🍈\:melon:Melon
    U+1F349🍉\:watermelon:Watermelon
    U+1F34A🍊\:tangerine:Tangerine
    U+1F34B🍋\:lemon:Lemon
    U+1F34C🍌\:banana:Banana
    U+1F34D🍍\:pineapple:Pineapple
    U+1F34E🍎\:apple:Red Apple
    U+1F34F🍏\:green_apple:Green Apple
    U+1F350🍐\:pear:Pear
    U+1F351🍑\:peach:Peach
    U+1F352🍒\:cherries:Cherries
    U+1F353🍓\:strawberry:Strawberry
    U+1F354🍔\:hamburger:Hamburger
    U+1F355🍕\:pizza:Slice Of Pizza
    U+1F356🍖\:meat_on_bone:Meat On Bone
    U+1F357🍗\:poultry_leg:Poultry Leg
    U+1F358🍘\:rice_cracker:Rice Cracker
    U+1F359🍙\:rice_ball:Rice Ball
    U+1F35A🍚\:rice:Cooked Rice
    U+1F35B🍛\:curry:Curry And Rice
    U+1F35C🍜\:ramen:Steaming Bowl
    U+1F35D🍝\:spaghetti:Spaghetti
    U+1F35E🍞\:bread:Bread
    U+1F35F🍟\:fries:French Fries
    U+1F360🍠\:sweet_potato:Roasted Sweet Potato
    U+1F361🍡\:dango:Dango
    U+1F362🍢\:oden:Oden
    U+1F363🍣\:sushi:Sushi
    U+1F364🍤\:fried_shrimp:Fried Shrimp
    U+1F365🍥\:fish_cake:Fish Cake With Swirl Design
    U+1F366🍦\:icecream:Soft Ice Cream
    U+1F367🍧\:shaved_ice:Shaved Ice
    U+1F368🍨\:ice_cream:Ice Cream
    U+1F369🍩\:doughnut:Doughnut
    U+1F36A🍪\:cookie:Cookie
    U+1F36B🍫\:chocolate_bar:Chocolate Bar
    U+1F36C🍬\:candy:Candy
    U+1F36D🍭\:lollipop:Lollipop
    U+1F36E🍮\:custard:Custard
    U+1F36F🍯\:honey_pot:Honey Pot
    U+1F370🍰\:cake:Shortcake
    U+1F371🍱\:bento:Bento Box
    U+1F372🍲\:stew:Pot Of Food
    U+1F373🍳\:egg:Cooking
    U+1F374🍴\:fork_and_knife:Fork And Knife
    U+1F375🍵\:tea:Teacup Without Handle
    U+1F376🍶\:sake:Sake Bottle And Cup
    U+1F377🍷\:wine_glass:Wine Glass
    U+1F378🍸\:cocktail:Cocktail Glass
    U+1F379🍹\:tropical_drink:Tropical Drink
    U+1F37A🍺\:beer:Beer Mug
    U+1F37B🍻\:beers:Clinking Beer Mugs
    U+1F37C🍼\:baby_bottle:Baby Bottle
    U+1F380🎀\:ribbon:Ribbon
    U+1F381🎁\:gift:Wrapped Present
    U+1F382🎂\:birthday:Birthday Cake
    U+1F383🎃\:jack_o_lantern:Jack-o-lantern
    U+1F384🎄\:christmas_tree:Christmas Tree
    U+1F385🎅\:santa:Father Christmas
    U+1F386🎆\:fireworks:Fireworks
    U+1F387🎇\:sparkler:Firework Sparkler
    U+1F388🎈\:balloon:Balloon
    U+1F389🎉\:tada:Party Popper
    U+1F38A🎊\:confetti_ball:Confetti Ball
    U+1F38B🎋\:tanabata_tree:Tanabata Tree
    U+1F38C🎌\:crossed_flags:Crossed Flags
    U+1F38D🎍\:bamboo:Pine Decoration
    U+1F38E🎎\:dolls:Japanese Dolls
    U+1F38F🎏\:flags:Carp Streamer
    U+1F390🎐\:wind_chime:Wind Chime
    U+1F391🎑\:rice_scene:Moon Viewing Ceremony
    U+1F392🎒\:school_satchel:School Satchel
    U+1F393🎓\:mortar_board:Graduation Cap
    U+1F3A0🎠\:carousel_horse:Carousel Horse
    U+1F3A1🎡\:ferris_wheel:Ferris Wheel
    U+1F3A2🎢\:roller_coaster:Roller Coaster
    U+1F3A3🎣\:fishing_pole_and_fish:Fishing Pole And Fish
    U+1F3A4🎤\:microphone:Microphone
    U+1F3A5🎥\:movie_camera:Movie Camera
    U+1F3A6🎦\:cinema:Cinema
    U+1F3A7🎧\:headphones:Headphone
    U+1F3A8🎨\:art:Artist Palette
    U+1F3A9🎩\:tophat:Top Hat
    U+1F3AA🎪\:circus_tent:Circus Tent
    U+1F3AB🎫\:ticket:Ticket
    U+1F3AC🎬\:clapper:Clapper Board
    U+1F3AD🎭\:performing_arts:Performing Arts
    U+1F3AE🎮\:video_game:Video Game
    U+1F3AF🎯\:dart:Direct Hit
    U+1F3B0🎰\:slot_machine:Slot Machine
    U+1F3B1🎱\:8ball:Billiards
    U+1F3B2🎲\:game_die:Game Die
    U+1F3B3🎳\:bowling:Bowling
    U+1F3B4🎴\:flower_playing_cards:Flower Playing Cards
    U+1F3B5🎵\:musical_note:Musical Note
    U+1F3B6🎶\:notes:Multiple Musical Notes
    U+1F3B7🎷\:saxophone:Saxophone
    U+1F3B8🎸\:guitar:Guitar
    U+1F3B9🎹\:musical_keyboard:Musical Keyboard
    U+1F3BA🎺\:trumpet:Trumpet
    U+1F3BB🎻\:violin:Violin
    U+1F3BC🎼\:musical_score:Musical Score
    U+1F3BD🎽\:running_shirt_with_sash:Running Shirt With Sash
    U+1F3BE🎾\:tennis:Tennis Racquet And Ball
    U+1F3BF🎿\:ski:Ski And Ski Boot
    U+1F3C0🏀\:basketball:Basketball And Hoop
    U+1F3C1🏁\:checkered_flag:Chequered Flag
    U+1F3C2🏂\:snowboarder:Snowboarder
    U+1F3C3🏃\:runner:Runner
    U+1F3C4🏄\:surfer:Surfer
    U+1F3C6🏆\:trophy:Trophy
    U+1F3C7🏇\:horse_racing:Horse Racing
    U+1F3C8🏈\:football:American Football
    U+1F3C9🏉\:rugby_football:Rugby Football
    U+1F3CA🏊\:swimmer:Swimmer
    U+1F3E0🏠\:house:House Building
    U+1F3E1🏡\:house_with_garden:House With Garden
    U+1F3E2🏢\:office:Office Building
    U+1F3E3🏣\:post_office:Japanese Post Office
    U+1F3E4🏤\:european_post_office:European Post Office
    U+1F3E5🏥\:hospital:Hospital
    U+1F3E6🏦\:bank:Bank
    U+1F3E7🏧\:atm:Automated Teller Machine
    U+1F3E8🏨\:hotel:Hotel
    U+1F3E9🏩\:love_hotel:Love Hotel
    U+1F3EA🏪\:convenience_store:Convenience Store
    U+1F3EB🏫\:school:School
    U+1F3EC🏬\:department_store:Department Store
    U+1F3ED🏭\:factory:Factory
    U+1F3EE🏮\:izakaya_lantern:Izakaya Lantern
    U+1F3EF🏯\:japanese_castle:Japanese Castle
    U+1F3F0🏰\:european_castle:European Castle
    U+1F3FB🏻\:skin-tone-2:Emoji Modifier Fitzpatrick Type-1-2
    U+1F3FC🏼\:skin-tone-3:Emoji Modifier Fitzpatrick Type-3
    U+1F3FD🏽\:skin-tone-4:Emoji Modifier Fitzpatrick Type-4
    U+1F3FE🏾\:skin-tone-5:Emoji Modifier Fitzpatrick Type-5
    U+1F3FF🏿\:skin-tone-6:Emoji Modifier Fitzpatrick Type-6
    U+1F400🐀\:rat:Rat
    U+1F401🐁\:mouse2:Mouse
    U+1F402🐂\:ox:Ox
    U+1F403🐃\:water_buffalo:Water Buffalo
    U+1F404🐄\:cow2:Cow
    U+1F405🐅\:tiger2:Tiger
    U+1F406🐆\:leopard:Leopard
    U+1F407🐇\:rabbit2:Rabbit
    U+1F408🐈\:cat2:Cat
    U+1F409🐉\:dragon:Dragon
    U+1F40A🐊\:crocodile:Crocodile
    U+1F40B🐋\:whale2:Whale
    U+1F40C🐌\:snail:Snail
    U+1F40D🐍\:snake:Snake
    U+1F40E🐎\:racehorse:Horse
    U+1F40F🐏\:ram:Ram
    U+1F410🐐\:goat:Goat
    U+1F411🐑\:sheep:Sheep
    U+1F412🐒\:monkey:Monkey
    U+1F413🐓\:rooster:Rooster
    U+1F414🐔\:chicken:Chicken
    U+1F415🐕\:dog2:Dog
    U+1F416🐖\:pig2:Pig
    U+1F417🐗\:boar:Boar
    U+1F418🐘\:elephant:Elephant
    U+1F419🐙\:octopus:Octopus
    U+1F41A🐚\:shell:Spiral Shell
    U+1F41B🐛\:bug:Bug
    U+1F41C🐜\:ant:Ant
    U+1F41D🐝\:bee:Honeybee
    U+1F41E🐞\:beetle:Lady Beetle
    U+1F41F🐟\:fish:Fish
    U+1F420🐠\:tropical_fish:Tropical Fish
    U+1F421🐡\:blowfish:Blowfish
    U+1F422🐢\:turtle:Turtle
    U+1F423🐣\:hatching_chick:Hatching Chick
    U+1F424🐤\:baby_chick:Baby Chick
    U+1F425🐥\:hatched_chick:Front-facing Baby Chick
    U+1F426🐦\:bird:Bird
    U+1F427🐧\:penguin:Penguin
    U+1F428🐨\:koala:Koala
    U+1F429🐩\:poodle:Poodle
    U+1F42A🐪\:dromedary_camel:Dromedary Camel
    U+1F42B🐫\:camel:Bactrian Camel
    U+1F42C🐬\:dolphin:Dolphin
    U+1F42D🐭\:mouse:Mouse Face
    U+1F42E🐮\:cow:Cow Face
    U+1F42F🐯\:tiger:Tiger Face
    U+1F430🐰\:rabbit:Rabbit Face
    U+1F431🐱\:cat:Cat Face
    U+1F432🐲\:dragon_face:Dragon Face
    U+1F433🐳\:whale:Spouting Whale
    U+1F434🐴\:horse:Horse Face
    U+1F435🐵\:monkey_face:Monkey Face
    U+1F436🐶\:dog:Dog Face
    U+1F437🐷\:pig:Pig Face
    U+1F438🐸\:frog:Frog Face
    U+1F439🐹\:hamster:Hamster Face
    U+1F43A🐺\:wolf:Wolf Face
    U+1F43B🐻\:bear:Bear Face
    U+1F43C🐼\:panda_face:Panda Face
    U+1F43D🐽\:pig_nose:Pig Nose
    U+1F43E🐾\:feet:Paw Prints
    U+1F440👀\:eyes:Eyes
    U+1F442👂\:ear:Ear
    U+1F443👃\:nose:Nose
    U+1F444👄\:lips:Mouth
    U+1F445👅\:tongue:Tongue
    U+1F446👆\:point_up_2:White Up Pointing Backhand Index
    U+1F447👇\:point_down:White Down Pointing Backhand Index
    U+1F448👈\:point_left:White Left Pointing Backhand Index
    U+1F449👉\:point_right:White Right Pointing Backhand Index
    U+1F44A👊\:facepunch:Fisted Hand Sign
    U+1F44B👋\:wave:Waving Hand Sign
    U+1F44C👌\:ok_hand:Ok Hand Sign
    U+1F44D👍\:+1:Thumbs Up Sign
    U+1F44E👎\:-1:Thumbs Down Sign
    U+1F44F👏\:clap:Clapping Hands Sign
    U+1F450👐\:open_hands:Open Hands Sign
    U+1F451👑\:crown:Crown
    U+1F452👒\:womans_hat:Womans Hat
    U+1F453👓\:eyeglasses:Eyeglasses
    U+1F454👔\:necktie:Necktie
    U+1F455👕\:shirt:T-shirt
    U+1F456👖\:jeans:Jeans
    U+1F457👗\:dress:Dress
    U+1F458👘\:kimono:Kimono
    U+1F459👙\:bikini:Bikini
    U+1F45A👚\:womans_clothes:Womans Clothes
    U+1F45B👛\:purse:Purse
    U+1F45C👜\:handbag:Handbag
    U+1F45D👝\:pouch:Pouch
    U+1F45E👞\:mans_shoe:Mans Shoe
    U+1F45F👟\:athletic_shoe:Athletic Shoe
    U+1F460👠\:high_heel:High-heeled Shoe
    U+1F461👡\:sandal:Womans Sandal
    U+1F462👢\:boot:Womans Boots
    U+1F463👣\:footprints:Footprints
    U+1F464👤\:bust_in_silhouette:Bust In Silhouette
    U+1F465👥\:busts_in_silhouette:Busts In Silhouette
    U+1F466👦\:boy:Boy
    U+1F467👧\:girl:Girl
    U+1F468👨\:man:Man
    U+1F469👩\:woman:Woman
    U+1F46A👪\:family:Family
    U+1F46B👫\:couple:Man And Woman Holding Hands
    U+1F46C👬\:two_men_holding_hands:Two Men Holding Hands
    U+1F46D👭\:two_women_holding_hands:Two Women Holding Hands
    U+1F46E👮\:cop:Police Officer
    U+1F46F👯\:dancers:Woman With Bunny Ears
    U+1F470👰\:bride_with_veil:Bride With Veil
    U+1F471👱\:person_with_blond_hair:Person With Blond Hair
    U+1F472👲\:man_with_gua_pi_mao:Man With Gua Pi Mao
    U+1F473👳\:man_with_turban:Man With Turban
    U+1F474👴\:older_man:Older Man
    U+1F475👵\:older_woman:Older Woman
    U+1F476👶\:baby:Baby
    U+1F477👷\:construction_worker:Construction Worker
    U+1F478👸\:princess:Princess
    U+1F479👹\:japanese_ogre:Japanese Ogre
    U+1F47A👺\:japanese_goblin:Japanese Goblin
    U+1F47B👻\:ghost:Ghost
    U+1F47C👼\:angel:Baby Angel
    U+1F47D👽\:alien:Extraterrestrial Alien
    U+1F47E👾\:space_invader:Alien Monster
    U+1F47F👿\:imp:Imp
    U+1F480💀\:skull:Skull
    U+1F481💁\:information_desk_person:Information Desk Person
    U+1F482💂\:guardsman:Guardsman
    U+1F483💃\:dancer:Dancer
    U+1F484💄\:lipstick:Lipstick
    U+1F485💅\:nail_care:Nail Polish
    U+1F486💆\:massage:Face Massage
    U+1F487💇\:haircut:Haircut
    U+1F488💈\:barber:Barber Pole
    U+1F489💉\:syringe:Syringe
    U+1F48A💊\:pill:Pill
    U+1F48B💋\:kiss:Kiss Mark
    U+1F48C💌\:love_letter:Love Letter
    U+1F48D💍\:ring:Ring
    U+1F48E💎\:gem:Gem Stone
    U+1F48F💏\:couplekiss:Kiss
    U+1F490💐\:bouquet:Bouquet
    U+1F491💑\:couple_with_heart:Couple With Heart
    U+1F492💒\:wedding:Wedding
    U+1F493💓\:heartbeat:Beating Heart
    U+1F494💔\:broken_heart:Broken Heart
    U+1F495💕\:two_hearts:Two Hearts
    U+1F496💖\:sparkling_heart:Sparkling Heart
    U+1F497💗\:heartpulse:Growing Heart
    U+1F498💘\:cupid:Heart With Arrow
    U+1F499💙\:blue_heart:Blue Heart
    U+1F49A💚\:green_heart:Green Heart
    U+1F49B💛\:yellow_heart:Yellow Heart
    U+1F49C💜\:purple_heart:Purple Heart
    U+1F49D💝\:gift_heart:Heart With Ribbon
    U+1F49E💞\:revolving_hearts:Revolving Hearts
    U+1F49F💟\:heart_decoration:Heart Decoration
    U+1F4A0💠\:diamond_shape_with_a_dot_inside:Diamond Shape With A Dot Inside
    U+1F4A1💡\:bulb:Electric Light Bulb
    U+1F4A2💢\:anger:Anger Symbol
    U+1F4A3💣\:bomb:Bomb
    U+1F4A4💤\:zzz:Sleeping Symbol
    U+1F4A5💥\:boom:Collision Symbol
    U+1F4A6💦\:sweat_drops:Splashing Sweat Symbol
    U+1F4A7💧\:droplet:Droplet
    U+1F4A8💨\:dash:Dash Symbol
    U+1F4A9💩\:hankey:Pile Of Poo
    U+1F4AA💪\:muscle:Flexed Biceps
    U+1F4AB💫\:dizzy:Dizzy Symbol
    U+1F4AC💬\:speech_balloon:Speech Balloon
    U+1F4AD💭\:thought_balloon:Thought Balloon
    U+1F4AE💮\:white_flower:White Flower
    U+1F4AF💯\:100:Hundred Points Symbol
    U+1F4B0💰\:moneybag:Money Bag
    U+1F4B1💱\:currency_exchange:Currency Exchange
    U+1F4B2💲\:heavy_dollar_sign:Heavy Dollar Sign
    U+1F4B3💳\:credit_card:Credit Card
    U+1F4B4💴\:yen:Banknote With Yen Sign
    U+1F4B5💵\:dollar:Banknote With Dollar Sign
    U+1F4B6💶\:euro:Banknote With Euro Sign
    U+1F4B7💷\:pound:Banknote With Pound Sign
    U+1F4B8💸\:money_with_wings:Money With Wings
    U+1F4B9💹\:chart:Chart With Upwards Trend And Yen Sign
    U+1F4BA💺\:seat:Seat
    U+1F4BB💻\:computer:Personal Computer
    U+1F4BC💼\:briefcase:Briefcase
    U+1F4BD💽\:minidisc:Minidisc
    U+1F4BE💾\:floppy_disk:Floppy Disk
    U+1F4BF💿\:cd:Optical Disc
    U+1F4C0📀\:dvd:Dvd
    U+1F4C1📁\:file_folder:File Folder
    U+1F4C2📂\:open_file_folder:Open File Folder
    U+1F4C3📃\:page_with_curl:Page With Curl
    U+1F4C4📄\:page_facing_up:Page Facing Up
    U+1F4C5📅\:date:Calendar
    U+1F4C6📆\:calendar:Tear-off Calendar
    U+1F4C7📇\:card_index:Card Index
    U+1F4C8📈\:chart_with_upwards_trend:Chart With Upwards Trend
    U+1F4C9📉\:chart_with_downwards_trend:Chart With Downwards Trend
    U+1F4CA📊\:bar_chart:Bar Chart
    U+1F4CB📋\:clipboard:Clipboard
    U+1F4CC📌\:pushpin:Pushpin
    U+1F4CD📍\:round_pushpin:Round Pushpin
    U+1F4CE📎\:paperclip:Paperclip
    U+1F4CF📏\:straight_ruler:Straight Ruler
    U+1F4D0📐\:triangular_ruler:Triangular Ruler
    U+1F4D1📑\:bookmark_tabs:Bookmark Tabs
    U+1F4D2📒\:ledger:Ledger
    U+1F4D3📓\:notebook:Notebook
    U+1F4D4📔\:notebook_with_decorative_cover:Notebook With Decorative Cover
    U+1F4D5📕\:closed_book:Closed Book
    U+1F4D6📖\:book:Open Book
    U+1F4D7📗\:green_book:Green Book
    U+1F4D8📘\:blue_book:Blue Book
    U+1F4D9📙\:orange_book:Orange Book
    U+1F4DA📚\:books:Books
    U+1F4DB📛\:name_badge:Name Badge
    U+1F4DC📜\:scroll:Scroll
    U+1F4DD📝\:memo:Memo
    U+1F4DE📞\:telephone_receiver:Telephone Receiver
    U+1F4DF📟\:pager:Pager
    U+1F4E0📠\:fax:Fax Machine
    U+1F4E1📡\:satellite:Satellite Antenna
    U+1F4E2📢\:loudspeaker:Public Address Loudspeaker
    U+1F4E3📣\:mega:Cheering Megaphone
    U+1F4E4📤\:outbox_tray:Outbox Tray
    U+1F4E5📥\:inbox_tray:Inbox Tray
    U+1F4E6📦\:package:Package
    U+1F4E7📧\:e-mail:E-mail Symbol
    U+1F4E8📨\:incoming_envelope:Incoming Envelope
    U+1F4E9📩\:envelope_with_arrow:Envelope With Downwards Arrow Above
    U+1F4EA📪\:mailbox_closed:Closed Mailbox With Lowered Flag
    U+1F4EB📫\:mailbox:Closed Mailbox With Raised Flag
    U+1F4EC📬\:mailbox_with_mail:Open Mailbox With Raised Flag
    U+1F4ED📭\:mailbox_with_no_mail:Open Mailbox With Lowered Flag
    U+1F4EE📮\:postbox:Postbox
    U+1F4EF📯\:postal_horn:Postal Horn
    U+1F4F0📰\:newspaper:Newspaper
    U+1F4F1📱\:iphone:Mobile Phone
    U+1F4F2📲\:calling:Mobile Phone With Rightwards Arrow At Left
    U+1F4F3📳\:vibration_mode:Vibration Mode
    U+1F4F4📴\:mobile_phone_off:Mobile Phone Off
    U+1F4F5📵\:no_mobile_phones:No Mobile Phones
    U+1F4F6📶\:signal_strength:Antenna With Bars
    U+1F4F7📷\:camera:Camera
    U+1F4F9📹\:video_camera:Video Camera
    U+1F4FA📺\:tv:Television
    U+1F4FB📻\:radio:Radio
    U+1F4FC📼\:vhs:Videocassette
    U+1F500🔀\:twisted_rightwards_arrows:Twisted Rightwards Arrows
    U+1F501🔁\:repeat:Clockwise Rightwards And Leftwards Open Circle Arrows
    U+1F502🔂\:repeat_one:Clockwise Rightwards And Leftwards Open Circle Arrows With Circled One Overlay
    U+1F503🔃\:arrows_clockwise:Clockwise Downwards And Upwards Open Circle Arrows
    U+1F504🔄\:arrows_counterclockwise:Anticlockwise Downwards And Upwards Open Circle Arrows
    U+1F505🔅\:low_brightness:Low Brightness Symbol
    U+1F506🔆\:high_brightness:High Brightness Symbol
    U+1F507🔇\:mute:Speaker With Cancellation Stroke
    U+1F508🔈\:speaker:Speaker
    U+1F509🔉\:sound:Speaker With One Sound Wave
    U+1F50A🔊\:loud_sound:Speaker With Three Sound Waves
    U+1F50B🔋\:battery:Battery
    U+1F50C🔌\:electric_plug:Electric Plug
    U+1F50D🔍\:mag:Left-pointing Magnifying Glass
    U+1F50E🔎\:mag_right:Right-pointing Magnifying Glass
    U+1F50F🔏\:lock_with_ink_pen:Lock With Ink Pen
    U+1F510🔐\:closed_lock_with_key:Closed Lock With Key
    U+1F511🔑\:key:Key
    U+1F512🔒\:lock:Lock
    U+1F513🔓\:unlock:Open Lock
    U+1F514🔔\:bell:Bell
    U+1F515🔕\:no_bell:Bell With Cancellation Stroke
    U+1F516🔖\:bookmark:Bookmark
    U+1F517🔗\:link:Link Symbol
    U+1F518🔘\:radio_button:Radio Button
    U+1F519🔙\:back:Back With Leftwards Arrow Above
    U+1F51A🔚\:end:End With Leftwards Arrow Above
    U+1F51B🔛\:on:On With Exclamation Mark With Left Right Arrow Above
    U+1F51C🔜\:soon:Soon With Rightwards Arrow Above
    U+1F51D🔝\:top:Top With Upwards Arrow Above
    U+1F51E🔞\:underage:No One Under Eighteen Symbol
    U+1F51F🔟\:keycap_ten:Keycap Ten
    U+1F520🔠\:capital_abcd:Input Symbol For Latin Capital Letters
    U+1F521🔡\:abcd:Input Symbol For Latin Small Letters
    U+1F522🔢\:1234:Input Symbol For Numbers
    U+1F523🔣\:symbols:Input Symbol For Symbols
    U+1F524🔤\:abc:Input Symbol For Latin Letters
    U+1F525🔥\:fire:Fire
    U+1F526🔦\:flashlight:Electric Torch
    U+1F527🔧\:wrench:Wrench
    U+1F528🔨\:hammer:Hammer
    U+1F529🔩\:nut_and_bolt:Nut And Bolt
    U+1F52A🔪\:hocho:Hocho
    U+1F52B🔫\:gun:Pistol
    U+1F52C🔬\:microscope:Microscope
    U+1F52D🔭\:telescope:Telescope
    U+1F52E🔮\:crystal_ball:Crystal Ball
    U+1F52F🔯\:six_pointed_star:Six Pointed Star With Middle Dot
    U+1F530🔰\:beginner:Japanese Symbol For Beginner
    U+1F531🔱\:trident:Trident Emblem
    U+1F532🔲\:black_square_button:Black Square Button
    U+1F533🔳\:white_square_button:White Square Button
    U+1F534🔴\:red_circle:Large Red Circle
    U+1F535🔵\:large_blue_circle:Large Blue Circle
    U+1F536🔶\:large_orange_diamond:Large Orange Diamond
    U+1F537🔷\:large_blue_diamond:Large Blue Diamond
    U+1F538🔸\:small_orange_diamond:Small Orange Diamond
    U+1F539🔹\:small_blue_diamond:Small Blue Diamond
    U+1F53A🔺\:small_red_triangle:Up-pointing Red Triangle
    U+1F53B🔻\:small_red_triangle_down:Down-pointing Red Triangle
    U+1F53C🔼\:arrow_up_small:Up-pointing Small Red Triangle
    U+1F53D🔽\:arrow_down_small:Down-pointing Small Red Triangle
    U+1F550🕐\:clock1:Clock Face One Oclock
    U+1F551🕑\:clock2:Clock Face Two Oclock
    U+1F552🕒\:clock3:Clock Face Three Oclock
    U+1F553🕓\:clock4:Clock Face Four Oclock
    U+1F554🕔\:clock5:Clock Face Five Oclock
    U+1F555🕕\:clock6:Clock Face Six Oclock
    U+1F556🕖\:clock7:Clock Face Seven Oclock
    U+1F557🕗\:clock8:Clock Face Eight Oclock
    U+1F558🕘\:clock9:Clock Face Nine Oclock
    U+1F559🕙\:clock10:Clock Face Ten Oclock
    U+1F55A🕚\:clock11:Clock Face Eleven Oclock
    U+1F55B🕛\:clock12:Clock Face Twelve Oclock
    U+1F55C🕜\:clock130:Clock Face One-thirty
    U+1F55D🕝\:clock230:Clock Face Two-thirty
    U+1F55E🕞\:clock330:Clock Face Three-thirty
    U+1F55F🕟\:clock430:Clock Face Four-thirty
    U+1F560🕠\:clock530:Clock Face Five-thirty
    U+1F561🕡\:clock630:Clock Face Six-thirty
    U+1F562🕢\:clock730:Clock Face Seven-thirty
    U+1F563🕣\:clock830:Clock Face Eight-thirty
    U+1F564🕤\:clock930:Clock Face Nine-thirty
    U+1F565🕥\:clock1030:Clock Face Ten-thirty
    U+1F566🕦\:clock1130:Clock Face Eleven-thirty
    U+1F567🕧\:clock1230:Clock Face Twelve-thirty
    U+1F5FB🗻\:mount_fuji:Mount Fuji
    U+1F5FC🗼\:tokyo_tower:Tokyo Tower
    U+1F5FD🗽\:statue_of_liberty:Statue Of Liberty
    U+1F5FE🗾\:japan:Silhouette Of Japan
    U+1F5FF🗿\:moyai:Moyai
    U+1F600😀\:grinning:Grinning Face
    U+1F601😁\:grin:Grinning Face With Smiling Eyes
    U+1F602😂\:joy:Face With Tears Of Joy
    U+1F603😃\:smiley:Smiling Face With Open Mouth
    U+1F604😄\:smile:Smiling Face With Open Mouth And Smiling Eyes
    U+1F605😅\:sweat_smile:Smiling Face With Open Mouth And Cold Sweat
    U+1F606😆\:laughing:Smiling Face With Open Mouth And Tightly-closed Eyes
    U+1F607😇\:innocent:Smiling Face With Halo
    U+1F608😈\:smiling_imp:Smiling Face With Horns
    U+1F609😉\:wink:Winking Face
    U+1F60A😊\:blush:Smiling Face With Smiling Eyes
    U+1F60B😋\:yum:Face Savouring Delicious Food
    U+1F60C😌\:relieved:Relieved Face
    U+1F60D😍\:heart_eyes:Smiling Face With Heart-shaped Eyes
    U+1F60E😎\:sunglasses:Smiling Face With Sunglasses
    U+1F60F😏\:smirk:Smirking Face
    U+1F610😐\:neutral_face:Neutral Face
    U+1F611😑\:expressionless:Expressionless Face
    U+1F612😒\:unamused:Unamused Face
    U+1F613😓\:sweat:Face With Cold Sweat
    U+1F614😔\:pensive:Pensive Face
    U+1F615😕\:confused:Confused Face
    U+1F616😖\:confounded:Confounded Face
    U+1F617😗\:kissing:Kissing Face
    U+1F618😘\:kissing_heart:Face Throwing A Kiss
    U+1F619😙\:kissing_smiling_eyes:Kissing Face With Smiling Eyes
    U+1F61A😚\:kissing_closed_eyes:Kissing Face With Closed Eyes
    U+1F61B😛\:stuck_out_tongue:Face With Stuck-out Tongue
    U+1F61C😜\:stuck_out_tongue_winking_eye:Face With Stuck-out Tongue And Winking Eye
    U+1F61D😝\:stuck_out_tongue_closed_eyes:Face With Stuck-out Tongue And Tightly-closed Eyes
    U+1F61E😞\:disappointed:Disappointed Face
    U+1F61F😟\:worried:Worried Face
    U+1F620😠\:angry:Angry Face
    U+1F621😡\:rage:Pouting Face
    U+1F622😢\:cry:Crying Face
    U+1F623😣\:persevere:Persevering Face
    U+1F624😤\:triumph:Face With Look Of Triumph
    U+1F625😥\:disappointed_relieved:Disappointed But Relieved Face
    U+1F626😦\:frowning:Frowning Face With Open Mouth
    U+1F627😧\:anguished:Anguished Face
    U+1F628😨\:fearful:Fearful Face
    U+1F629😩\:weary:Weary Face
    U+1F62A😪\:sleepy:Sleepy Face
    U+1F62B😫\:tired_face:Tired Face
    U+1F62C😬\:grimacing:Grimacing Face
    U+1F62D😭\:sob:Loudly Crying Face
    U+1F62E😮\:open_mouth:Face With Open Mouth
    U+1F62F😯\:hushed:Hushed Face
    U+1F630😰\:cold_sweat:Face With Open Mouth And Cold Sweat
    U+1F631😱\:scream:Face Screaming In Fear
    U+1F632😲\:astonished:Astonished Face
    U+1F633😳\:flushed:Flushed Face
    U+1F634😴\:sleeping:Sleeping Face
    U+1F635😵\:dizzy_face:Dizzy Face
    U+1F636😶\:no_mouth:Face Without Mouth
    U+1F637😷\:mask:Face With Medical Mask
    U+1F638😸\:smile_cat:Grinning Cat Face With Smiling Eyes
    U+1F639😹\:joy_cat:Cat Face With Tears Of Joy
    U+1F63A😺\:smiley_cat:Smiling Cat Face With Open Mouth
    U+1F63B😻\:heart_eyes_cat:Smiling Cat Face With Heart-shaped Eyes
    U+1F63C😼\:smirk_cat:Cat Face With Wry Smile
    U+1F63D😽\:kissing_cat:Kissing Cat Face With Closed Eyes
    U+1F63E😾\:pouting_cat:Pouting Cat Face
    U+1F63F😿\:crying_cat_face:Crying Cat Face
    U+1F640🙀\:scream_cat:Weary Cat Face
    U+1F645🙅\:no_good:Face With No Good Gesture
    U+1F646🙆\:ok_woman:Face With Ok Gesture
    U+1F647🙇\:bow:Person Bowing Deeply
    U+1F648🙈\:see_no_evil:See-no-evil Monkey
    U+1F649🙉\:hear_no_evil:Hear-no-evil Monkey
    U+1F64A🙊\:speak_no_evil:Speak-no-evil Monkey
    U+1F64B🙋\:raising_hand:Happy Person Raising One Hand
    U+1F64C🙌\:raised_hands:Person Raising Both Hands In Celebration
    U+1F64D🙍\:person_frowning:Person Frowning
    U+1F64E🙎\:person_with_pouting_face:Person With Pouting Face
    U+1F64F🙏\:pray:Person With Folded Hands
    U+1F680🚀\:rocket:Rocket
    U+1F681🚁\:helicopter:Helicopter
    U+1F682🚂\:steam_locomotive:Steam Locomotive
    U+1F683🚃\:railway_car:Railway Car
    U+1F684🚄\:bullettrain_side:High-speed Train
    U+1F685🚅\:bullettrain_front:High-speed Train With Bullet Nose
    U+1F686🚆\:train2:Train
    U+1F687🚇\:metro:Metro
    U+1F688🚈\:light_rail:Light Rail
    U+1F689🚉\:station:Station
    U+1F68A🚊\:tram:Tram
    U+1F68B🚋\:train:Tram Car
    U+1F68C🚌\:bus:Bus
    U+1F68D🚍\:oncoming_bus:Oncoming Bus
    U+1F68E🚎\:trolleybus:Trolleybus
    U+1F68F🚏\:busstop:Bus Stop
    U+1F690🚐\:minibus:Minibus
    U+1F691🚑\:ambulance:Ambulance
    U+1F692🚒\:fire_engine:Fire Engine
    U+1F693🚓\:police_car:Police Car
    U+1F694🚔\:oncoming_police_car:Oncoming Police Car
    U+1F695🚕\:taxi:Taxi
    U+1F696🚖\:oncoming_taxi:Oncoming Taxi
    U+1F697🚗\:car:Automobile
    U+1F698🚘\:oncoming_automobile:Oncoming Automobile
    U+1F699🚙\:blue_car:Recreational Vehicle
    U+1F69A🚚\:truck:Delivery Truck
    U+1F69B🚛\:articulated_lorry:Articulated Lorry
    U+1F69C🚜\:tractor:Tractor
    U+1F69D🚝\:monorail:Monorail
    U+1F69E🚞\:mountain_railway:Mountain Railway
    U+1F69F🚟\:suspension_railway:Suspension Railway
    U+1F6A0🚠\:mountain_cableway:Mountain Cableway
    U+1F6A1🚡\:aerial_tramway:Aerial Tramway
    U+1F6A2🚢\:ship:Ship
    U+1F6A3🚣\:rowboat:Rowboat
    U+1F6A4🚤\:speedboat:Speedboat
    U+1F6A5🚥\:traffic_light:Horizontal Traffic Light
    U+1F6A6🚦\:vertical_traffic_light:Vertical Traffic Light
    U+1F6A7🚧\:construction:Construction Sign
    U+1F6A8🚨\:rotating_light:Police Cars Revolving Light
    U+1F6A9🚩\:triangular_flag_on_post:Triangular Flag On Post
    U+1F6AA🚪\:door:Door
    U+1F6AB🚫\:no_entry_sign:No Entry Sign
    U+1F6AC🚬\:smoking:Smoking Symbol
    U+1F6AD🚭\:no_smoking:No Smoking Symbol
    U+1F6AE🚮\:put_litter_in_its_place:Put Litter In Its Place Symbol
    U+1F6AF🚯\:do_not_litter:Do Not Litter Symbol
    U+1F6B0🚰\:potable_water:Potable Water Symbol
    U+1F6B1🚱\:non-potable_water:Non-potable Water Symbol
    U+1F6B2🚲\:bike:Bicycle
    U+1F6B3🚳\:no_bicycles:No Bicycles
    U+1F6B4🚴\:bicyclist:Bicyclist
    U+1F6B5🚵\:mountain_bicyclist:Mountain Bicyclist
    U+1F6B6🚶\:walking:Pedestrian
    U+1F6B7🚷\:no_pedestrians:No Pedestrians
    U+1F6B8🚸\:children_crossing:Children Crossing
    U+1F6B9🚹\:mens:Mens Symbol
    U+1F6BA🚺\:womens:Womens Symbol
    U+1F6BB🚻\:restroom:Restroom
    U+1F6BC🚼\:baby_symbol:Baby Symbol
    U+1F6BD🚽\:toilet:Toilet
    U+1F6BE🚾\:wc:Water Closet
    U+1F6BF🚿\:shower:Shower
    U+1F6C0🛀\:bath:Bath
    U+1F6C1🛁\:bathtub:Bathtub
    U+1F6C2🛂\:passport_control:Passport Control
    U+1F6C3🛃\:customs:Customs
    U+1F6C4🛄\:baggage_claim:Baggage Claim
    U+1F6C5🛅\:left_luggage:Left Luggage
    diff --git a/julia-0.6.3/share/doc/julia/html/en/manual/variables-and-scoping.html b/julia-0.6.3/share/doc/julia/html/en/manual/variables-and-scoping.html deleted file mode 100644 index 1f63705..0000000 --- a/julia-0.6.3/share/doc/julia/html/en/manual/variables-and-scoping.html +++ /dev/null @@ -1,220 +0,0 @@ - -Scope of Variables · The Julia Language

    Scope of Variables

    Scope of Variables

    The scope of a variable is the region of code within which a variable is visible. Variable scoping helps avoid variable naming conflicts. The concept is intuitive: two functions can both have arguments called x without the two x's referring to the same thing. Similarly there are many other cases where different blocks of code can use the same name without referring to the same thing. The rules for when the same variable name does or doesn't refer to the same thing are called scope rules; this section spells them out in detail.

    Certain constructs in the language introduce scope blocks, which are regions of code that are eligible to be the scope of some set of variables. The scope of a variable cannot be an arbitrary set of source lines; instead, it will always line up with one of these blocks. There are two main types of scopes in Julia, global scope and local scope, the latter can be nested. The constructs introducing scope blocks are:

    Scope nameblock/construct introducing this kind of scope
    Global Scopemodule, baremodule, at interactive prompt (REPL)
    Local ScopeSoft Local Scope: for, while, comprehensions, try-catch-finally, let
    Local ScopeHard Local Scope: functions (either syntax, anonymous & do-blocks), struct, macro

    Notably missing from this table are begin blocks and if blocks, which do not introduce new scope blocks. All three types of scopes follow somewhat different rules which will be explained below as well as some extra rules for certain blocks.

    Julia uses lexical scoping, meaning that a function's scope does not inherit from its caller's scope, but from the scope in which the function was defined. For example, in the following code the x inside foo refers to the x in the global scope of its module Bar:

    julia> module Bar
    -           x = 1
    -           foo() = x
    -       end;

    and not a x in the scope where foo is used:

    julia> import .Bar
    -
    -julia> x = -1;
    -
    -julia> Bar.foo()
    -1

    Thus lexical scope means that the scope of variables can be inferred from the source code alone.

    Global Scope

    Each module introduces a new global scope, separate from the global scope of all other modules; there is no all-encompassing global scope. Modules can introduce variables of other modules into their scope through the using or import statements or through qualified access using the dot-notation, i.e. each module is a so-called namespace. Note that variable bindings can only be changed within their global scope and not from an outside module.

    julia> module A
    -           a = 1 # a global in A's scope
    -       end;
    -
    -julia> module B
    -           module C
    -               c = 2
    -           end
    -           b = C.c    # can access the namespace of a nested global scope
    -                      # through a qualified access
    -           import ..A # makes module A available
    -           d = A.a
    -       end;
    -
    -julia> module D
    -           b = a # errors as D's global scope is separate from A's
    -       end;
    -ERROR: UndefVarError: a not defined
    -
    -julia> module E
    -           import ..A # make module A available
    -           A.a = 2    # throws below error
    -       end;
    -ERROR: cannot assign variables in other modules

    Note that the interactive prompt (aka REPL) is in the global scope of the module Main.

    Local Scope

    A new local scope is introduced by most code-blocks, see above table for a complete list. A local scope usually inherits all the variables from its parent scope, both for reading and writing. There are two subtypes of local scopes, hard and soft, with slightly different rules concerning what variables are inherited. Unlike global scopes, local scopes are not namespaces, thus variables in an inner scope cannot be retrieved from the parent scope through some sort of qualified access.

    The following rules and examples pertain to both hard and soft local scopes. A newly introduced variable in a local scope does not back-propagate to its parent scope. For example, here the z is not introduced into the top-level scope:

    julia> for i = 1:10
    -           z = i
    -       end
    -
    -julia> z
    -ERROR: UndefVarError: z not defined

    (Note, in this and all following examples it is assumed that their top-level is a global scope with a clean workspace, for instance a newly started REPL.)

    Inside a local scope a variable can be forced to be a local variable using the local keyword:

    julia> x = 0;
    -
    -julia> for i = 1:10
    -           local x
    -           x = i + 1
    -       end
    -
    -julia> x
    -0

    Inside a local scope a new global variable can be defined using the keyword global:

    julia> for i = 1:10
    -           global z
    -           z = i
    -       end
    -
    -julia> z
    -10

    The location of both the local and global keywords within the scope block is irrelevant. The following is equivalent to the last example (although stylistically worse):

    julia> for i = 1:10
    -           z = i
    -           global z
    -       end
    -
    -julia> z
    -10

    Soft Local Scope

    In a soft local scope, all variables are inherited from its parent scope unless a variable is specifically marked with the keyword local.

    Soft local scopes are introduced by for-loops, while-loops, comprehensions, try-catch-finally-blocks, and let-blocks. There are some extra rules for Let Blocks and for For Loops and Comprehensions.

    In the following example the x and y refer always to the same variables as the soft local scope inherits both read and write variables:

    julia> x, y = 0, 1;
    -
    -julia> for i = 1:10
    -           x = i + y + 1
    -       end
    -
    -julia> x
    -12

    Within soft scopes, the global keyword is never necessary, although allowed. The only case when it would change the semantics is (currently) a syntax error:

    julia> let
    -           local j = 2
    -           let
    -               global j = 3
    -           end
    -       end
    -ERROR: syntax: `global j`: j is local variable in the enclosing scope

    Hard Local Scope

    Hard local scopes are introduced by function definitions (in all their forms), struct type definition blocks, and macro-definitions.

    In a hard local scope, all variables are inherited from its parent scope unless:

    • an assignment would result in a modified global variable, or

    • a variable is specifically marked with the keyword local.

    Thus global variables are only inherited for reading but not for writing:

    julia> x, y = 1, 2;
    -
    -julia> function foo()
    -           x = 2        # assignment introduces a new local
    -           return x + y # y refers to the global
    -       end;
    -
    -julia> foo()
    -4
    -
    -julia> x
    -1

    An explicit global is needed to assign to a global variable:

    julia> x = 1;
    -
    -julia> function foobar()
    -           global x = 2
    -       end;
    -
    -julia> foobar();
    -
    -julia> x
    -2

    Note that nested functions can behave differently to functions defined in the global scope as they can modify their parent scope's local variables:

    julia> x, y = 1, 2;
    -
    -julia> function baz()
    -           x = 2 # introduces a new local
    -           function bar()
    -               x = 10       # modifies the parent's x
    -               return x + y # y is global
    -           end
    -           return bar() + x # 12 + 10 (x is modified in call of bar())
    -       end;
    -
    -julia> baz()
    -22
    -
    -julia> x, y
    -(1, 2)

    The distinction between inheriting global and local variables for assignment can lead to some slight differences between functions defined in local vs. global scopes. Consider the modification of the last example by moving bar to the global scope:

    julia> x, y = 1, 2;
    -
    -julia> function bar()
    -           x = 10 # local
    -           return x + y
    -       end;
    -
    -julia> function quz()
    -           x = 2 # local
    -           return bar() + x # 12 + 2 (x is not modified)
    -       end;
    -
    -julia> quz()
    -14
    -
    -julia> x, y
    -(1, 2)

    Note that above subtlety does not pertain to type and macro definitions as they can only appear at the global scope. There are special scoping rules concerning the evaluation of default and keyword function arguments which are described in the Function section.

    An assignment introducing a variable used inside a function, type or macro definition need not come before its inner usage:

    julia> f = y -> y + a
    -(::#1) (generic function with 1 method)
    -
    -julia> f(3)
    -ERROR: UndefVarError: a not defined
    -Stacktrace:
    - [1] (::##1#2)(::Int64) at ./none:1
    -
    -julia> a = 1
    -1
    -
    -julia> f(3)
    -4

    This behavior may seem slightly odd for a normal variable, but allows for named functions – which are just normal variables holding function objects – to be used before they are defined. This allows functions to be defined in whatever order is intuitive and convenient, rather than forcing bottom up ordering or requiring forward declarations, as long as they are defined by the time they are actually called. As an example, here is an inefficient, mutually recursive way to test if positive integers are even or odd:

    julia> even(n) = n == 0 ? true : odd(n-1);
    -
    -julia> odd(n) = n == 0 ? false : even(n-1);
    -
    -julia> even(3)
    -false
    -
    -julia> odd(3)
    -true

    Julia provides built-in, efficient functions to test for oddness and evenness called iseven() and isodd() so the above definitions should only be taken as examples.

    Hard vs. Soft Local Scope

    Blocks which introduce a soft local scope, such as loops, are generally used to manipulate the variables in their parent scope. Thus their default is to fully access all variables in their parent scope.

    Conversely, the code inside blocks which introduce a hard local scope (function, type, and macro definitions) can be executed at any place in a program. Remotely changing the state of global variables in other modules should be done with care and thus this is an opt-in feature requiring the global keyword.

    The reason to allow modifying local variables of parent scopes in nested functions is to allow constructing closures which have a private state, for instance the state variable in the following example:

    julia> let
    -           state = 0
    -           global counter
    -           counter() = state += 1
    -       end;
    -
    -julia> counter()
    -1
    -
    -julia> counter()
    -2

    See also the closures in the examples in the next two sections.

    Let Blocks

    Unlike assignments to local variables, let statements allocate new variable bindings each time they run. An assignment modifies an existing value location, and let creates new locations. This difference is usually not important, and is only detectable in the case of variables that outlive their scope via closures. The let syntax accepts a comma-separated series of assignments and variable names:

    julia> x, y, z = -1, -1, -1;
    -
    -julia> let x = 1, z
    -           println("x: $x, y: $y") # x is local variable, y the global
    -           println("z: $z") # errors as z has not been assigned yet but is local
    -       end
    -x: 1, y: -1
    -ERROR: UndefVarError: z not defined

    The assignments are evaluated in order, with each right-hand side evaluated in the scope before the new variable on the left-hand side has been introduced. Therefore it makes sense to write something like let x = x since the two x variables are distinct and have separate storage. Here is an example where the behavior of let is needed:

    julia> Fs = Array{Any}(2); i = 1;
    -
    -julia> while i <= 2
    -           Fs[i] = ()->i
    -           i += 1
    -       end
    -
    -julia> Fs[1]()
    -3
    -
    -julia> Fs[2]()
    -3

    Here we create and store two closures that return variable i. However, it is always the same variable i, so the two closures behave identically. We can use let to create a new binding for i:

    julia> Fs = Array{Any}(2); i = 1;
    -
    -julia> while i <= 2
    -           let i = i
    -               Fs[i] = ()->i
    -           end
    -           i += 1
    -       end
    -
    -julia> Fs[1]()
    -1
    -
    -julia> Fs[2]()
    -2

    Since the begin construct does not introduce a new scope, it can be useful to use a zero-argument let to just introduce a new scope block without creating any new bindings:

    julia> let
    -           local x = 1
    -           let
    -               local x = 2
    -           end
    -           x
    -       end
    -1

    Since let introduces a new scope block, the inner local x is a different variable than the outer local x.

    For Loops and Comprehensions

    for loops and Comprehensions have the following behavior: any new variables introduced in their body scopes are freshly allocated for each loop iteration. This is in contrast to while loops which reuse the variables for all iterations. Therefore these constructs are similar to while loops with let blocks inside:

    julia> Fs = Array{Any}(2);
    -
    -julia> for j = 1:2
    -           Fs[j] = ()->j
    -       end
    -
    -julia> Fs[1]()
    -1
    -
    -julia> Fs[2]()
    -2

    for loops will reuse existing variables for its iteration variable:

    julia> i = 0;
    -
    -julia> for i = 1:3
    -       end
    -
    -julia> i
    -3

    However, comprehensions do not do this, and always freshly allocate their iteration variables:

    julia> x = 0;
    -
    -julia> [ x for x = 1:3 ];
    -
    -julia> x
    -0

    Constants

    A common use of variables is giving names to specific, unchanging values. Such variables are only assigned once. This intent can be conveyed to the compiler using the const keyword:

    julia> const e  = 2.71828182845904523536;
    -
    -julia> const pi = 3.14159265358979323846;

    The const declaration is allowed on both global and local variables, but is especially useful for globals. It is difficult for the compiler to optimize code involving global variables, since their values (or even their types) might change at almost any time. If a global variable will not change, adding a const declaration solves this performance problem.

    Local constants are quite different. The compiler is able to determine automatically when a local variable is constant, so local constant declarations are not necessary for performance purposes.

    Special top-level assignments, such as those performed by the function and struct keywords, are constant by default.

    Note that const only affects the variable binding; the variable may be bound to a mutable object (such as an array), and that object may still be modified.

    diff --git a/julia-0.6.3/share/doc/julia/html/en/manual/variables.html b/julia-0.6.3/share/doc/julia/html/en/manual/variables.html deleted file mode 100644 index 995805e..0000000 --- a/julia-0.6.3/share/doc/julia/html/en/manual/variables.html +++ /dev/null @@ -1,59 +0,0 @@ - -Variables · The Julia Language

    Variables

    Variables

    A variable, in Julia, is a name associated (or bound) to a value. It's useful when you want to store a value (that you obtained after some math, for example) for later use. For example:

    # Assign the value 10 to the variable x
    -julia> x = 10
    -10
    -
    -# Doing math with x's value
    -julia> x + 1
    -11
    -
    -# Reassign x's value
    -julia> x = 1 + 1
    -2
    -
    -# You can assign values of other types, like strings of text
    -julia> x = "Hello World!"
    -"Hello World!"

    Julia provides an extremely flexible system for naming variables. Variable names are case-sensitive, and have no semantic meaning (that is, the language will not treat variables differently based on their names).

    julia> x = 1.0
    -1.0
    -
    -julia> y = -3
    --3
    -
    -julia> Z = "My string"
    -"My string"
    -
    -julia> customary_phrase = "Hello world!"
    -"Hello world!"
    -
    -julia> UniversalDeclarationOfHumanRightsStart = "人人生而自由,在尊严和权利上一律平等。"
    -"人人生而自由,在尊严和权利上一律平等。"

    Unicode names (in UTF-8 encoding) are allowed:

    julia> δ = 0.00001
    -1.0e-5
    -
    -julia> 안녕하세요 = "Hello"
    -"Hello"

    In the Julia REPL and several other Julia editing environments, you can type many Unicode math symbols by typing the backslashed LaTeX symbol name followed by tab. For example, the variable name δ can be entered by typing \delta-tab, or even α̂₂ by \alpha-tab-\hat- tab-\_2-tab. (If you find a symbol somewhere, e.g. in someone else's code, that you don't know how to type, the REPL help will tell you: just type ? and then paste the symbol.)

    Julia will even let you redefine built-in constants and functions if needed:

    julia> pi
    -π = 3.1415926535897...
    -
    -julia> pi = 3
    -WARNING: imported binding for pi overwritten in module Main
    -3
    -
    -julia> pi
    -3
    -
    -julia> sqrt(100)
    -10.0
    -
    -julia> sqrt = 4
    -WARNING: imported binding for sqrt overwritten in module Main
    -4

    However, this is obviously not recommended to avoid potential confusion.

    Allowed Variable Names

    Variable names must begin with a letter (A-Z or a-z), underscore, or a subset of Unicode code points greater than 00A0; in particular, Unicode character categories Lu/Ll/Lt/Lm/Lo/Nl (letters), Sc/So (currency and other symbols), and a few other letter-like characters (e.g. a subset of the Sm math symbols) are allowed. Subsequent characters may also include ! and digits (0-9 and other characters in categories Nd/No), as well as other Unicode code points: diacritics and other modifying marks (categories Mn/Mc/Me/Sk), some punctuation connectors (category Pc), primes, and a few other characters.

    Operators like + are also valid identifiers, but are parsed specially. In some contexts, operators can be used just like variables; for example (+) refers to the addition function, and (+) = f will reassign it. Most of the Unicode infix operators (in category Sm), such as , are parsed as infix operators and are available for user-defined methods (e.g. you can use const ⊗ = kron to define as an infix Kronecker product).

    The only explicitly disallowed names for variables are the names of built-in statements:

    julia> else = false
    -ERROR: syntax: unexpected "else"
    -
    -julia> try = "No"
    -ERROR: syntax: unexpected "="

    Some Unicode characters are considered to be equivalent in identifiers. Different ways of entering Unicode combining characters (e.g., accents) are treated as equivalent (specifically, Julia identifiers are NFC-normalized). The Unicode characters ɛ (U+025B: Latin small letter open e) and µ (U+00B5: micro sign) are treated as equivalent to the corresponding Greek letters, because the former are easily accessible via some input methods.

    Stylistic Conventions

    While Julia imposes few restrictions on valid names, it has become useful to adopt the following conventions:

    • Names of variables are in lower case.

    • Word separation can be indicated by underscores ('_'), but use of underscores is discouraged unless the name would be hard to read otherwise.

    • Names of Types and Modules begin with a capital letter and word separation is shown with upper camel case instead of underscores.

    • Names of functions and macros are in lower case, without underscores.

    • Functions that write to their arguments have names that end in !. These are sometimes called "mutating" or "in-place" functions because they are intended to produce changes in their arguments after the function is called, not just return a value.

    For more information about stylistic conventions, see the Style Guide.

    diff --git a/julia-0.6.3/share/doc/julia/html/en/manual/workflow-tips.html b/julia-0.6.3/share/doc/julia/html/en/manual/workflow-tips.html deleted file mode 100644 index 9f013c3..0000000 --- a/julia-0.6.3/share/doc/julia/html/en/manual/workflow-tips.html +++ /dev/null @@ -1,19 +0,0 @@ - -Workflow Tips · The Julia Language

    Workflow Tips

    Workflow Tips

    Here are some tips for working with Julia efficiently.

    REPL-based workflow

    As already elaborated in Interacting With Julia, Julia's REPL provides rich functionality that facilitates an efficient interactive workflow. Here are some tips that might further enhance your experience at the command line.

    A basic editor/REPL workflow

    The most basic Julia workflows involve using a text editor in conjunction with the julia command line. A common pattern includes the following elements:

    • Put code under development in a temporary module. Create a file, say Tmp.jl, and include within it

      module Tmp
      -
      -<your definitions here>
      -
      -end
    • Put your test code in another file. Create another file, say tst.jl, which begins with

      import Tmp

      and includes tests for the contents of Tmp. The value of using import versus using is that you can call reload("Tmp") instead of having to restart the REPL when your definitions change. Of course, the cost is the need to prepend Tmp. to uses of names defined in your module. (You can lower that cost by keeping your module name short.)

      Alternatively, you can wrap the contents of your test file in a module, as

      module Tst
      -    using Tmp
      -
      -    <scratch work>
      -
      -end

      The advantage is that you can now do using Tmp in your test code and can therefore avoid prepending Tmp. everywhere. The disadvantage is that code can no longer be selectively copied to the REPL without some tweaking.

    • Lather. Rinse. Repeat. Explore ideas at the julia command prompt. Save good ideas in tst.jl. Occasionally restart the REPL, issuing

      reload("Tmp")
      -include("tst.jl")

    Simplify initialization

    To simplify restarting the REPL, put project-specific initialization code in a file, say _init.jl, which you can run on startup by issuing the command:

    julia -L _init.jl

    If you further add the following to your .juliarc.jl file

    isfile("_init.jl") && include(joinpath(pwd(), "_init.jl"))

    then calling julia from that directory will run the initialization code without the additional command line argument.

    Browser-based workflow

    It is also possible to interact with a Julia REPL in the browser via IJulia. See the package home for details.

    diff --git a/julia-0.6.3/share/doc/julia/html/en/search.html b/julia-0.6.3/share/doc/julia/html/en/search.html deleted file mode 100644 index 73a3aab..0000000 --- a/julia-0.6.3/share/doc/julia/html/en/search.html +++ /dev/null @@ -1,9 +0,0 @@ - -Search · The Julia Language

    Search

    Search

    Number of results: loading...

      diff --git a/julia-0.6.3/share/doc/julia/html/en/search_index.js b/julia-0.6.3/share/doc/julia/html/en/search_index.js deleted file mode 100644 index 5aac7a8..0000000 --- a/julia-0.6.3/share/doc/julia/html/en/search_index.js +++ /dev/null @@ -1,20931 +0,0 @@ -var documenterSearchIndex = {"docs": [ - -{ - "location": "index.html#", - "page": "Home", - "title": "Home", - "category": "page", - "text": "" -}, - -{ - "location": "index.html#Julia-Documentation-1", - "page": "Home", - "title": "Julia Documentation", - "category": "section", - "text": "" -}, - -{ - "location": "index.html#Manual-1", - "page": "Home", - "title": "Manual", - "category": "section", - "text": "Introduction\nGetting Started\nVariables\nIntegers and Floating-Point Numbers\nMathematical Operations and Elementary Functions\nComplex and Rational Numbers\nStrings\nFunctions\nControl Flow\nScope of Variables\nTypes\nMethods\nConstructors\nConversion and Promotion\nInterfaces\nModules\nDocumentation\nMetaprogramming\nMulti-dimensional Arrays\nLinear Algebra\nNetworking and Streams\nParallel Computing\nDate and DateTime\nRunning External Programs\nCalling C and Fortran Code\nHandling Operating System Variation\nEnvironment Variables\nInteracting With Julia\nEmbedding Julia\nPackages\nProfiling\nStack Traces\nPerformance Tips\nWorkflow Tips\nStyle Guide\nFrequently Asked Questions\nNoteworthy Differences from other Languages\nUnicode Input" -}, - -{ - "location": "index.html#Standard-Library-1", - "page": "Home", - "title": "Standard Library", - "category": "section", - "text": "Essentials\nCollections and Data Structures\nMathematics\nNumbers\nStrings\nArrays\nTasks and Parallel Computing\nLinear Algebra\nConstants\nFilesystem\nI/O and Network\nPunctuation\nSorting and Related Functions\nPackage Manager Functions\nDates and Time\nIteration utilities\nUnit Testing\nC Interface\nC Standard Library\nDynamic Linker\nProfiling\nStackTraces\nSIMD Support" -}, - -{ - "location": "index.html#Developer-Documentation-1", - "page": "Home", - "title": "Developer Documentation", - "category": "section", - "text": "Reflection and introspection\nDocumentation of Julia\'s Internals\nInitialization of the Julia runtime\nJulia ASTs\nMore about types\nMemory layout of Julia Objects\nEval of Julia code\nCalling Conventions\nHigh-level Overview of the Native-Code Generation Process\nJulia Functions\nBase.Cartesian\nTalking to the compiler (the :meta mechanism)\nSubArrays\nSystem Image Building\nWorking with LLVM\nprintf() and stdio in the Julia runtime\nBounds checking\nProper maintenance and care of multi-threading locks\nArrays with custom indices\nBase.LibGit2\nModule loading\nDeveloping/debugging Julia\'s C code\nReporting and analyzing crashes (segfaults)\ngdb debugging tips\nUsing Valgrind with Julia\nSanitizer support" -}, - -{ - "location": "manual/introduction.html#", - "page": "Introduction", - "title": "Introduction", - "category": "page", - "text": "" -}, - -{ - "location": "manual/introduction.html#man-introduction-1", - "page": "Introduction", - "title": "Introduction", - "category": "section", - "text": "Scientific computing has traditionally required the highest performance, yet domain experts have largely moved to slower dynamic languages for daily work. We believe there are many good reasons to prefer dynamic languages for these applications, and we do not expect their use to diminish. Fortunately, modern language design and compiler techniques make it possible to mostly eliminate the performance trade-off and provide a single environment productive enough for prototyping and efficient enough for deploying performance-intensive applications. The Julia programming language fills this role: it is a flexible dynamic language, appropriate for scientific and numerical computing, with performance comparable to traditional statically-typed languages.Because Julia\'s compiler is different from the interpreters used for languages like Python or R, you may find that Julia\'s performance is unintuitive at first. If you find that something is slow, we highly recommend reading through the Performance Tips section before trying anything else. Once you understand how Julia works, it\'s easy to write code that\'s nearly as fast as C.Julia features optional typing, multiple dispatch, and good performance, achieved using type inference and just-in-time (JIT) compilation, implemented using LLVM. It is multi-paradigm, combining features of imperative, functional, and object-oriented programming. Julia provides ease and expressiveness for high-level numerical computing, in the same way as languages such as R, MATLAB, and Python, but also supports general programming. To achieve this, Julia builds upon the lineage of mathematical programming languages, but also borrows much from popular dynamic languages, including Lisp, Perl, Python, Lua, and Ruby.The most significant departures of Julia from typical dynamic languages are:The core language imposes very little; the standard library is written in Julia itself, including primitive operations like integer arithmetic\nA rich language of types for constructing and describing objects, that can also optionally be used to make type declarations\nThe ability to define function behavior across many combinations of argument types via multiple dispatch\nAutomatic generation of efficient, specialized code for different argument types\nGood performance, approaching that of statically-compiled languages like CAlthough one sometimes speaks of dynamic languages as being \"typeless\", they are definitely not: every object, whether primitive or user-defined, has a type. The lack of type declarations in most dynamic languages, however, means that one cannot instruct the compiler about the types of values, and often cannot explicitly talk about types at all. In static languages, on the other hand, while one can – and usually must – annotate types for the compiler, types exist only at compile time and cannot be manipulated or expressed at run time. In Julia, types are themselves run-time objects, and can also be used to convey information to the compiler.While the casual programmer need not explicitly use types or multiple dispatch, they are the core unifying features of Julia: functions are defined on different combinations of argument types, and applied by dispatching to the most specific matching definition. This model is a good fit for mathematical programming, where it is unnatural for the first argument to \"own\" an operation as in traditional object-oriented dispatch. Operators are just functions with special notation – to extend addition to new user-defined data types, you define new methods for the + function. Existing code then seamlessly applies to the new data types.Partly because of run-time type inference (augmented by optional type annotations), and partly because of a strong focus on performance from the inception of the project, Julia\'s computational efficiency exceeds that of other dynamic languages, and even rivals that of statically-compiled languages. For large scale numerical problems, speed always has been, continues to be, and probably always will be crucial: the amount of data being processed has easily kept pace with Moore\'s Law over the past decades.Julia aims to create an unprecedented combination of ease-of-use, power, and efficiency in a single language. In addition to the above, some advantages of Julia over comparable systems include:Free and open source (MIT licensed)\nUser-defined types are as fast and compact as built-ins\nNo need to vectorize code for performance; devectorized code is fast\nDesigned for parallelism and distributed computation\nLightweight \"green\" threading (coroutines)\nUnobtrusive yet powerful type system\nElegant and extensible conversions and promotions for numeric and other types\nEfficient support for Unicode, including but not limited to UTF-8\nCall C functions directly (no wrappers or special APIs needed)\nPowerful shell-like capabilities for managing other processes\nLisp-like macros and other metaprogramming facilities" -}, - -{ - "location": "manual/getting-started.html#", - "page": "Getting Started", - "title": "Getting Started", - "category": "page", - "text": "" -}, - -{ - "location": "manual/getting-started.html#Getting-Started-1", - "page": "Getting Started", - "title": "Getting Started", - "category": "section", - "text": "Julia installation is straightforward, whether using precompiled binaries or compiling from source. Download and install Julia by following the instructions at https://julialang.org/downloads/.The easiest way to learn and experiment with Julia is by starting an interactive session (also known as a read-eval-print loop or \"repl\") by double-clicking the Julia executable or running julia from the command line:$ julia\n _\n _ _ _(_)_ | A fresh approach to technical computing\n (_) | (_) (_) | Documentation: https://docs.julialang.org\n _ _ _| |_ __ _ | Type \"?help\" for help.\n | | | | | | |/ _` | |\n | | |_| | | | (_| | | Version 0.5.0-dev+2440 (2016-02-01 02:22 UTC)\n _/ |\\__\'_|_|_|\\__\'_| | Commit 2bb94d6 (11 days old master)\n|__/ | x86_64-apple-darwin13.1.0\n\njulia> 1 + 2\n3\n\njulia> ans\n3To exit the interactive session, type ^D – the control key together with the d key or type quit(). When run in interactive mode, julia displays a banner and prompts the user for input. Once the user has entered a complete expression, such as 1 + 2, and hits enter, the interactive session evaluates the expression and shows its value. If an expression is entered into an interactive session with a trailing semicolon, its value is not shown. The variable ans is bound to the value of the last evaluated expression whether it is shown or not. The ans variable is only bound in interactive sessions, not when Julia code is run in other ways.To evaluate expressions written in a source file file.jl, write include(\"file.jl\").To run code in a file non-interactively, you can give it as the first argument to the julia command:$ julia script.jl arg1 arg2...As the example implies, the following command-line arguments to julia are taken as command-line arguments to the program script.jl, passed in the global constant ARGS. The name of the script itself is passed in as the global PROGRAM_FILE. Note that ARGS is also set when script code is given using the -e option on the command line (see the julia help output below) but PROGRAM_FILE will be empty. For example, to just print the arguments given to a script, you could do this:$ julia -e \'println(PROGRAM_FILE); for x in ARGS; println(x); end\' foo bar\n\nfoo\nbarOr you could put that code into a script and run it:$ echo \'println(PROGRAM_FILE); for x in ARGS; println(x); end\' > script.jl\n$ julia script.jl foo bar\nscript.jl\nfoo\nbarThe -- delimiter can be used to separate command-line args to the scriptfile from args to Julia:$ julia --color=yes -O -- foo.jl arg1 arg2..Julia can be started in parallel mode with either the -p or the --machinefile options. -p n will launch an additional n worker processes, while --machinefile file will launch a worker for each line in file file. The machines defined in file must be accessible via a passwordless ssh login, with Julia installed at the same location as the current host. Each machine definition takes the form [count*][user@]host[:port] [bind_addr[:port]] . user defaults to current user, port to the standard ssh port. count is the number of workers to spawn on the node, and defaults to 1. The optional bind-to bind_addr[:port] specifies the ip-address and port that other workers should use to connect to this worker.If you have code that you want executed whenever Julia is run, you can put it in ~/.juliarc.jl:$ echo \'println(\"Greetings! 你好! 안녕하세요?\")\' > ~/.juliarc.jl\n$ julia\nGreetings! 你好! 안녕하세요?\n\n...There are various ways to run Julia code and provide options, similar to those available for the perl and ruby programs:julia [switches] -- [programfile] [args...]\n -v, --version Display version information\n -h, --help Print this message\n\n -J, --sysimage Start up with the given system image file\n --precompiled={yes|no} Use precompiled code from system image if available\n --compilecache={yes|no} Enable/disable incremental precompilation of modules\n -H, --home Set location of `julia` executable\n --startup-file={yes|no} Load ~/.juliarc.jl\n --handle-signals={yes|no} Enable or disable Julia\'s default signal handlers\n\n -e, --eval Evaluate \n -E, --print Evaluate and show \n -L, --load Load immediately on all processors\n\n -p, --procs {N|auto} Integer value N launches N additional local worker processes\n \"auto\" launches as many workers as the number of local cores\n --machinefile Run processes on hosts listed in \n\n -i Interactive mode; REPL runs and isinteractive() is true\n -q, --quiet Quiet startup (no banner)\n --color={yes|no} Enable or disable color text\n --history-file={yes|no} Load or save history\n\n --compile={yes|no|all|min}Enable or disable JIT compiler, or request exhaustive compilation\n -C, --cpu-target Limit usage of cpu features up to \n -O, --optimize={0,1,2,3} Set the optimization level (default is 2 if unspecified or 3 if specified as -O)\n -g, -g Enable / Set the level of debug info generation (default is 1 if unspecified or 2 if specified as -g)\n --inline={yes|no} Control whether inlining is permitted (overrides functions declared as @inline)\n --check-bounds={yes|no} Emit bounds checks always or never (ignoring declarations)\n --math-mode={ieee,fast} Disallow or enable unsafe floating point optimizations (overrides @fastmath declaration)\n\n --depwarn={yes|no|error} Enable or disable syntax and method deprecation warnings (\"error\" turns warnings into errors)\n\n --output-o name Generate an object file (including system image data)\n --output-ji name Generate a system image data file (.ji)\n --output-bc name Generate LLVM bitcode (.bc)\n --output-incremental=no Generate an incremental output file (rather than complete)\n\n --code-coverage={none|user|all}, --code-coverage\n Count executions of source lines (omitting setting is equivalent to \"user\")\n --track-allocation={none|user|all}, --track-allocation\n Count bytes allocated by each source line" -}, - -{ - "location": "manual/getting-started.html#Resources-1", - "page": "Getting Started", - "title": "Resources", - "category": "section", - "text": "In addition to this manual, there are various other resources that may help new users get started with Julia:Julia and IJulia cheatsheet\nLearn Julia in a few minutes\nLearn Julia the Hard Way\nJulia by Example\nHands-on Julia\nTutorial for Homer Reid\'s numerical analysis class\nAn introductory presentation\nVideos from the Julia tutorial at MIT\nYouTube videos from the JuliaCons" -}, - -{ - "location": "manual/variables.html#", - "page": "Variables", - "title": "Variables", - "category": "page", - "text": "" -}, - -{ - "location": "manual/variables.html#Variables-1", - "page": "Variables", - "title": "Variables", - "category": "section", - "text": "A variable, in Julia, is a name associated (or bound) to a value. It\'s useful when you want to store a value (that you obtained after some math, for example) for later use. For example:# Assign the value 10 to the variable x\njulia> x = 10\n10\n\n# Doing math with x\'s value\njulia> x + 1\n11\n\n# Reassign x\'s value\njulia> x = 1 + 1\n2\n\n# You can assign values of other types, like strings of text\njulia> x = \"Hello World!\"\n\"Hello World!\"Julia provides an extremely flexible system for naming variables. Variable names are case-sensitive, and have no semantic meaning (that is, the language will not treat variables differently based on their names).julia> x = 1.0\n1.0\n\njulia> y = -3\n-3\n\njulia> Z = \"My string\"\n\"My string\"\n\njulia> customary_phrase = \"Hello world!\"\n\"Hello world!\"\n\njulia> UniversalDeclarationOfHumanRightsStart = \"人人生而自由,在尊严和权利上一律平等。\"\n\"人人生而自由,在尊严和权利上一律平等。\"Unicode names (in UTF-8 encoding) are allowed:julia> δ = 0.00001\n1.0e-5\n\njulia> 안녕하세요 = \"Hello\"\n\"Hello\"In the Julia REPL and several other Julia editing environments, you can type many Unicode math symbols by typing the backslashed LaTeX symbol name followed by tab. For example, the variable name δ can be entered by typing \\delta-tab, or even α̂₂ by \\alpha-tab-\\hat- tab-\\_2-tab. (If you find a symbol somewhere, e.g. in someone else\'s code, that you don\'t know how to type, the REPL help will tell you: just type ? and then paste the symbol.)Julia will even let you redefine built-in constants and functions if needed:julia> pi\nπ = 3.1415926535897...\n\njulia> pi = 3\nWARNING: imported binding for pi overwritten in module Main\n3\n\njulia> pi\n3\n\njulia> sqrt(100)\n10.0\n\njulia> sqrt = 4\nWARNING: imported binding for sqrt overwritten in module Main\n4However, this is obviously not recommended to avoid potential confusion." -}, - -{ - "location": "manual/variables.html#Allowed-Variable-Names-1", - "page": "Variables", - "title": "Allowed Variable Names", - "category": "section", - "text": "Variable names must begin with a letter (A-Z or a-z), underscore, or a subset of Unicode code points greater than 00A0; in particular, Unicode character categories Lu/Ll/Lt/Lm/Lo/Nl (letters), Sc/So (currency and other symbols), and a few other letter-like characters (e.g. a subset of the Sm math symbols) are allowed. Subsequent characters may also include ! and digits (0-9 and other characters in categories Nd/No), as well as other Unicode code points: diacritics and other modifying marks (categories Mn/Mc/Me/Sk), some punctuation connectors (category Pc), primes, and a few other characters.Operators like + are also valid identifiers, but are parsed specially. In some contexts, operators can be used just like variables; for example (+) refers to the addition function, and (+) = f will reassign it. Most of the Unicode infix operators (in category Sm), such as ⊕, are parsed as infix operators and are available for user-defined methods (e.g. you can use const ⊗ = kron to define ⊗ as an infix Kronecker product).The only explicitly disallowed names for variables are the names of built-in statements:julia> else = false\nERROR: syntax: unexpected \"else\"\n\njulia> try = \"No\"\nERROR: syntax: unexpected \"=\"Some Unicode characters are considered to be equivalent in identifiers. Different ways of entering Unicode combining characters (e.g., accents) are treated as equivalent (specifically, Julia identifiers are NFC-normalized). The Unicode characters ɛ (U+025B: Latin small letter open e) and µ (U+00B5: micro sign) are treated as equivalent to the corresponding Greek letters, because the former are easily accessible via some input methods." -}, - -{ - "location": "manual/variables.html#Stylistic-Conventions-1", - "page": "Variables", - "title": "Stylistic Conventions", - "category": "section", - "text": "While Julia imposes few restrictions on valid names, it has become useful to adopt the following conventions:Names of variables are in lower case.\nWord separation can be indicated by underscores (\'_\'), but use of underscores is discouraged unless the name would be hard to read otherwise.\nNames of Types and Modules begin with a capital letter and word separation is shown with upper camel case instead of underscores.\nNames of functions and macros are in lower case, without underscores.\nFunctions that write to their arguments have names that end in !. These are sometimes called \"mutating\" or \"in-place\" functions because they are intended to produce changes in their arguments after the function is called, not just return a value.For more information about stylistic conventions, see the Style Guide." -}, - -{ - "location": "manual/integers-and-floating-point-numbers.html#", - "page": "Integers and Floating-Point Numbers", - "title": "Integers and Floating-Point Numbers", - "category": "page", - "text": "" -}, - -{ - "location": "manual/integers-and-floating-point-numbers.html#Integers-and-Floating-Point-Numbers-1", - "page": "Integers and Floating-Point Numbers", - "title": "Integers and Floating-Point Numbers", - "category": "section", - "text": "Integers and floating-point values are the basic building blocks of arithmetic and computation. Built-in representations of such values are called numeric primitives, while representations of integers and floating-point numbers as immediate values in code are known as numeric literals. For example, 1 is an integer literal, while 1.0 is a floating-point literal; their binary in-memory representations as objects are numeric primitives.Julia provides a broad range of primitive numeric types, and a full complement of arithmetic and bitwise operators as well as standard mathematical functions are defined over them. These map directly onto numeric types and operations that are natively supported on modern computers, thus allowing Julia to take full advantage of computational resources. Additionally, Julia provides software support for Arbitrary Precision Arithmetic, which can handle operations on numeric values that cannot be represented effectively in native hardware representations, but at the cost of relatively slower performance.The following are Julia\'s primitive numeric types:Integer types:Type Signed? Number of bits Smallest value Largest value\nInt8 ✓ 8 -2^7 2^7 - 1\nUInt8   8 0 2^8 - 1\nInt16 ✓ 16 -2^15 2^15 - 1\nUInt16   16 0 2^16 - 1\nInt32 ✓ 32 -2^31 2^31 - 1\nUInt32   32 0 2^32 - 1\nInt64 ✓ 64 -2^63 2^63 - 1\nUInt64   64 0 2^64 - 1\nInt128 ✓ 128 -2^127 2^127 - 1\nUInt128   128 0 2^128 - 1\nBool N/A 8 false (0) true (1)Floating-point types:Type Precision Number of bits\nFloat16 half 16\nFloat32 single 32\nFloat64 double 64Additionally, full support for Complex and Rational Numbers is built on top of these primitive numeric types. All numeric types interoperate naturally without explicit casting, thanks to a flexible, user-extensible type promotion system." -}, - -{ - "location": "manual/integers-and-floating-point-numbers.html#Integers-1", - "page": "Integers and Floating-Point Numbers", - "title": "Integers", - "category": "section", - "text": "Literal integers are represented in the standard manner:julia> 1\n1\n\njulia> 1234\n1234The default type for an integer literal depends on whether the target system has a 32-bit architecture or a 64-bit architecture:# 32-bit system:\njulia> typeof(1)\nInt32\n\n# 64-bit system:\njulia> typeof(1)\nInt64The Julia internal variable Sys.WORD_SIZE indicates whether the target system is 32-bit or 64-bit:# 32-bit system:\njulia> Sys.WORD_SIZE\n32\n\n# 64-bit system:\njulia> Sys.WORD_SIZE\n64Julia also defines the types Int and UInt, which are aliases for the system\'s signed and unsigned native integer types respectively:# 32-bit system:\njulia> Int\nInt32\njulia> UInt\nUInt32\n\n# 64-bit system:\njulia> Int\nInt64\njulia> UInt\nUInt64Larger integer literals that cannot be represented using only 32 bits but can be represented in 64 bits always create 64-bit integers, regardless of the system type:# 32-bit or 64-bit system:\njulia> typeof(3000000000)\nInt64Unsigned integers are input and output using the 0x prefix and hexadecimal (base 16) digits 0-9a-f (the capitalized digits A-F also work for input). The size of the unsigned value is determined by the number of hex digits used:julia> 0x1\n0x01\n\njulia> typeof(ans)\nUInt8\n\njulia> 0x123\n0x0123\n\njulia> typeof(ans)\nUInt16\n\njulia> 0x1234567\n0x01234567\n\njulia> typeof(ans)\nUInt32\n\njulia> 0x123456789abcdef\n0x0123456789abcdef\n\njulia> typeof(ans)\nUInt64This behavior is based on the observation that when one uses unsigned hex literals for integer values, one typically is using them to represent a fixed numeric byte sequence, rather than just an integer value.Recall that the variable ans is set to the value of the last expression evaluated in an interactive session. This does not occur when Julia code is run in other ways.Binary and octal literals are also supported:julia> 0b10\n0x02\n\njulia> typeof(ans)\nUInt8\n\njulia> 0o10\n0x08\n\njulia> typeof(ans)\nUInt8The minimum and maximum representable values of primitive numeric types such as integers are given by the typemin() and typemax() functions:julia> (typemin(Int32), typemax(Int32))\n(-2147483648, 2147483647)\n\njulia> for T in [Int8,Int16,Int32,Int64,Int128,UInt8,UInt16,UInt32,UInt64,UInt128]\n println(\"$(lpad(T,7)): [$(typemin(T)),$(typemax(T))]\")\n end\n Int8: [-128,127]\n Int16: [-32768,32767]\n Int32: [-2147483648,2147483647]\n Int64: [-9223372036854775808,9223372036854775807]\n Int128: [-170141183460469231731687303715884105728,170141183460469231731687303715884105727]\n UInt8: [0,255]\n UInt16: [0,65535]\n UInt32: [0,4294967295]\n UInt64: [0,18446744073709551615]\nUInt128: [0,340282366920938463463374607431768211455]The values returned by typemin() and typemax() are always of the given argument type. (The above expression uses several features we have yet to introduce, including for loops, Strings, and Interpolation, but should be easy enough to understand for users with some existing programming experience.)" -}, - -{ - "location": "manual/integers-and-floating-point-numbers.html#Overflow-behavior-1", - "page": "Integers and Floating-Point Numbers", - "title": "Overflow behavior", - "category": "section", - "text": "In Julia, exceeding the maximum representable value of a given type results in a wraparound behavior:julia> x = typemax(Int64)\n9223372036854775807\n\njulia> x + 1\n-9223372036854775808\n\njulia> x + 1 == typemin(Int64)\ntrueThus, arithmetic with Julia integers is actually a form of modular arithmetic. This reflects the characteristics of the underlying arithmetic of integers as implemented on modern computers. In applications where overflow is possible, explicit checking for wraparound produced by overflow is essential; otherwise, the BigInt type in Arbitrary Precision Arithmetic is recommended instead." -}, - -{ - "location": "manual/integers-and-floating-point-numbers.html#Division-errors-1", - "page": "Integers and Floating-Point Numbers", - "title": "Division errors", - "category": "section", - "text": "Integer division (the div function) has two exceptional cases: dividing by zero, and dividing the lowest negative number (typemin()) by -1. Both of these cases throw a DivideError. The remainder and modulus functions (rem and mod) throw a DivideError when their second argument is zero." -}, - -{ - "location": "manual/integers-and-floating-point-numbers.html#Floating-Point-Numbers-1", - "page": "Integers and Floating-Point Numbers", - "title": "Floating-Point Numbers", - "category": "section", - "text": "Literal floating-point numbers are represented in the standard formats:julia> 1.0\n1.0\n\njulia> 1.\n1.0\n\njulia> 0.5\n0.5\n\njulia> .5\n0.5\n\njulia> -1.23\n-1.23\n\njulia> 1e10\n1.0e10\n\njulia> 2.5e-4\n0.00025The above results are all Float64 values. Literal Float32 values can be entered by writing an f in place of e:julia> 0.5f0\n0.5f0\n\njulia> typeof(ans)\nFloat32\n\njulia> 2.5f-4\n0.00025f0Values can be converted to Float32 easily:julia> Float32(-1.5)\n-1.5f0\n\njulia> typeof(ans)\nFloat32Hexadecimal floating-point literals are also valid, but only as Float64 values:julia> 0x1p0\n1.0\n\njulia> 0x1.8p3\n12.0\n\njulia> 0x.4p-1\n0.125\n\njulia> typeof(ans)\nFloat64Half-precision floating-point numbers are also supported (Float16), but they are implemented in software and use Float32 for calculations.julia> sizeof(Float16(4.))\n2\n\njulia> 2*Float16(4.)\nFloat16(8.0)The underscore _ can be used as digit separator:julia> 10_000, 0.000_000_005, 0xdead_beef, 0b1011_0010\n(10000, 5.0e-9, 0xdeadbeef, 0xb2)" -}, - -{ - "location": "manual/integers-and-floating-point-numbers.html#Floating-point-zero-1", - "page": "Integers and Floating-Point Numbers", - "title": "Floating-point zero", - "category": "section", - "text": "Floating-point numbers have two zeros, positive zero and negative zero. They are equal to each other but have different binary representations, as can be seen using the bits function: :julia> 0.0 == -0.0\ntrue\n\njulia> bits(0.0)\n\"0000000000000000000000000000000000000000000000000000000000000000\"\n\njulia> bits(-0.0)\n\"1000000000000000000000000000000000000000000000000000000000000000\"" -}, - -{ - "location": "manual/integers-and-floating-point-numbers.html#Special-floating-point-values-1", - "page": "Integers and Floating-Point Numbers", - "title": "Special floating-point values", - "category": "section", - "text": "There are three specified standard floating-point values that do not correspond to any point on the real number line:Float16 Float32 Float64 Name Description\nInf16 Inf32 Inf positive infinity a value greater than all finite floating-point values\n-Inf16 -Inf32 -Inf negative infinity a value less than all finite floating-point values\nNaN16 NaN32 NaN not a number a value not == to any floating-point value (including itself)For further discussion of how these non-finite floating-point values are ordered with respect to each other and other floats, see Numeric Comparisons. By the IEEE 754 standard, these floating-point values are the results of certain arithmetic operations:julia> 1/Inf\n0.0\n\njulia> 1/0\nInf\n\njulia> -5/0\n-Inf\n\njulia> 0.000001/0\nInf\n\njulia> 0/0\nNaN\n\njulia> 500 + Inf\nInf\n\njulia> 500 - Inf\n-Inf\n\njulia> Inf + Inf\nInf\n\njulia> Inf - Inf\nNaN\n\njulia> Inf * Inf\nInf\n\njulia> Inf / Inf\nNaN\n\njulia> 0 * Inf\nNaNThe typemin() and typemax() functions also apply to floating-point types:julia> (typemin(Float16),typemax(Float16))\n(-Inf16, Inf16)\n\njulia> (typemin(Float32),typemax(Float32))\n(-Inf32, Inf32)\n\njulia> (typemin(Float64),typemax(Float64))\n(-Inf, Inf)" -}, - -{ - "location": "manual/integers-and-floating-point-numbers.html#Machine-epsilon-1", - "page": "Integers and Floating-Point Numbers", - "title": "Machine epsilon", - "category": "section", - "text": "Most real numbers cannot be represented exactly with floating-point numbers, and so for many purposes it is important to know the distance between two adjacent representable floating-point numbers, which is often known as machine epsilon.Julia provides eps(), which gives the distance between 1.0 and the next larger representable floating-point value:julia> eps(Float32)\n1.1920929f-7\n\njulia> eps(Float64)\n2.220446049250313e-16\n\njulia> eps() # same as eps(Float64)\n2.220446049250313e-16These values are 2.0^-23 and 2.0^-52 as Float32 and Float64 values, respectively. The eps() function can also take a floating-point value as an argument, and gives the absolute difference between that value and the next representable floating point value. That is, eps(x) yields a value of the same type as x such that x + eps(x) is the next representable floating-point value larger than x:julia> eps(1.0)\n2.220446049250313e-16\n\njulia> eps(1000.)\n1.1368683772161603e-13\n\njulia> eps(1e-27)\n1.793662034335766e-43\n\njulia> eps(0.0)\n5.0e-324The distance between two adjacent representable floating-point numbers is not constant, but is smaller for smaller values and larger for larger values. In other words, the representable floating-point numbers are densest in the real number line near zero, and grow sparser exponentially as one moves farther away from zero. By definition, eps(1.0) is the same as eps(Float64) since 1.0 is a 64-bit floating-point value.Julia also provides the nextfloat() and prevfloat() functions which return the next largest or smallest representable floating-point number to the argument respectively:julia> x = 1.25f0\n1.25f0\n\njulia> nextfloat(x)\n1.2500001f0\n\njulia> prevfloat(x)\n1.2499999f0\n\njulia> bits(prevfloat(x))\n\"00111111100111111111111111111111\"\n\njulia> bits(x)\n\"00111111101000000000000000000000\"\n\njulia> bits(nextfloat(x))\n\"00111111101000000000000000000001\"This example highlights the general principle that the adjacent representable floating-point numbers also have adjacent binary integer representations." -}, - -{ - "location": "manual/integers-and-floating-point-numbers.html#Rounding-modes-1", - "page": "Integers and Floating-Point Numbers", - "title": "Rounding modes", - "category": "section", - "text": "If a number doesn\'t have an exact floating-point representation, it must be rounded to an appropriate representable value, however, if wanted, the manner in which this rounding is done can be changed according to the rounding modes presented in the IEEE 754 standard.julia> x = 1.1; y = 0.1;\n\njulia> x + y\n1.2000000000000002\n\njulia> setrounding(Float64,RoundDown) do\n x + y\n end\n1.2The default mode used is always RoundNearest, which rounds to the nearest representable value, with ties rounded towards the nearest value with an even least significant bit.warning: Warning\nRounding is generally only correct for basic arithmetic functions (+(), -(), *(), /() and sqrt()) and type conversion operations. Many other functions assume the default RoundNearest mode is set, and can give erroneous results when operating under other rounding modes." -}, - -{ - "location": "manual/integers-and-floating-point-numbers.html#Background-and-References-1", - "page": "Integers and Floating-Point Numbers", - "title": "Background and References", - "category": "section", - "text": "Floating-point arithmetic entails many subtleties which can be surprising to users who are unfamiliar with the low-level implementation details. However, these subtleties are described in detail in most books on scientific computation, and also in the following references:The definitive guide to floating point arithmetic is the IEEE 754-2008 Standard; however, it is not available for free online.\nFor a brief but lucid presentation of how floating-point numbers are represented, see John D. Cook\'s article on the subject as well as his introduction to some of the issues arising from how this representation differs in behavior from the idealized abstraction of real numbers.\nAlso recommended is Bruce Dawson\'s series of blog posts on floating-point numbers.\nFor an excellent, in-depth discussion of floating-point numbers and issues of numerical accuracy encountered when computing with them, see David Goldberg\'s paper What Every Computer Scientist Should Know About Floating-Point Arithmetic.\nFor even more extensive documentation of the history of, rationale for, and issues with floating-point numbers, as well as discussion of many other topics in numerical computing, see the collected writings of William Kahan, commonly known as the \"Father of Floating-Point\". Of particular interest may be An Interview with the Old Man of Floating-Point." -}, - -{ - "location": "manual/integers-and-floating-point-numbers.html#Arbitrary-Precision-Arithmetic-1", - "page": "Integers and Floating-Point Numbers", - "title": "Arbitrary Precision Arithmetic", - "category": "section", - "text": "To allow computations with arbitrary-precision integers and floating point numbers, Julia wraps the GNU Multiple Precision Arithmetic Library (GMP) and the GNU MPFR Library, respectively. The BigInt and BigFloat types are available in Julia for arbitrary precision integer and floating point numbers respectively.Constructors exist to create these types from primitive numerical types, and parse() can be used to construct them from AbstractStrings. Once created, they participate in arithmetic with all other numeric types thanks to Julia\'s type promotion and conversion mechanism:julia> BigInt(typemax(Int64)) + 1\n9223372036854775808\n\njulia> parse(BigInt, \"123456789012345678901234567890\") + 1\n123456789012345678901234567891\n\njulia> parse(BigFloat, \"1.23456789012345678901\")\n1.234567890123456789010000000000000000000000000000000000000000000000000000000004\n\njulia> BigFloat(2.0^66) / 3\n2.459565876494606882133333333333333333333333333333333333333333333333333333333344e+19\n\njulia> factorial(BigInt(40))\n815915283247897734345611269596115894272000000000However, type promotion between the primitive types above and BigInt/BigFloat is not automatic and must be explicitly stated.julia> x = typemin(Int64)\n-9223372036854775808\n\njulia> x = x - 1\n9223372036854775807\n\njulia> typeof(x)\nInt64\n\njulia> y = BigInt(typemin(Int64))\n-9223372036854775808\n\njulia> y = y - 1\n-9223372036854775809\n\njulia> typeof(y)\nBigIntThe default precision (in number of bits of the significand) and rounding mode of BigFloat operations can be changed globally by calling setprecision() and setrounding(), and all further calculations will take these changes in account. Alternatively, the precision or the rounding can be changed only within the execution of a particular block of code by using the same functions with a do block:julia> setrounding(BigFloat, RoundUp) do\n BigFloat(1) + parse(BigFloat, \"0.1\")\n end\n1.100000000000000000000000000000000000000000000000000000000000000000000000000003\n\njulia> setrounding(BigFloat, RoundDown) do\n BigFloat(1) + parse(BigFloat, \"0.1\")\n end\n1.099999999999999999999999999999999999999999999999999999999999999999999999999986\n\njulia> setprecision(40) do\n BigFloat(1) + parse(BigFloat, \"0.1\")\n end\n1.1000000000004" -}, - -{ - "location": "manual/integers-and-floating-point-numbers.html#man-numeric-literal-coefficients-1", - "page": "Integers and Floating-Point Numbers", - "title": "Numeric Literal Coefficients", - "category": "section", - "text": "To make common numeric formulas and expressions clearer, Julia allows variables to be immediately preceded by a numeric literal, implying multiplication. This makes writing polynomial expressions much cleaner:julia> x = 3\n3\n\njulia> 2x^2 - 3x + 1\n10\n\njulia> 1.5x^2 - .5x + 1\n13.0It also makes writing exponential functions more elegant:julia> 2^2x\n64The precedence of numeric literal coefficients is the same as that of unary operators such as negation. So 2^3x is parsed as 2^(3x), and 2x^3 is parsed as 2*(x^3).Numeric literals also work as coefficients to parenthesized expressions:julia> 2(x-1)^2 - 3(x-1) + 1\n3note: Note\nThe precedence of numeric literal coefficients used for implicit multiplication is higher than other binary operators such as multiplication (*), and division (/, \\, and //). This means, for example, that 1 / 2im equals -0.5im and 6 // 2(2 + 1) equals 1 // 1.Additionally, parenthesized expressions can be used as coefficients to variables, implying multiplication of the expression by the variable:julia> (x-1)x\n6Neither juxtaposition of two parenthesized expressions, nor placing a variable before a parenthesized expression, however, can be used to imply multiplication:julia> (x-1)(x+1)\nERROR: MethodError: objects of type Int64 are not callable\n\njulia> x(x+1)\nERROR: MethodError: objects of type Int64 are not callableBoth expressions are interpreted as function application: any expression that is not a numeric literal, when immediately followed by a parenthetical, is interpreted as a function applied to the values in parentheses (see Functions for more about functions). Thus, in both of these cases, an error occurs since the left-hand value is not a function.The above syntactic enhancements significantly reduce the visual noise incurred when writing common mathematical formulae. Note that no whitespace may come between a numeric literal coefficient and the identifier or parenthesized expression which it multiplies." -}, - -{ - "location": "manual/integers-and-floating-point-numbers.html#Syntax-Conflicts-1", - "page": "Integers and Floating-Point Numbers", - "title": "Syntax Conflicts", - "category": "section", - "text": "Juxtaposed literal coefficient syntax may conflict with two numeric literal syntaxes: hexadecimal integer literals and engineering notation for floating-point literals. Here are some situations where syntactic conflicts arise:The hexadecimal integer literal expression 0xff could be interpreted as the numeric literal 0 multiplied by the variable xff.\nThe floating-point literal expression 1e10 could be interpreted as the numeric literal 1 multiplied by the variable e10, and similarly with the equivalent E form.In both cases, we resolve the ambiguity in favor of interpretation as a numeric literals:Expressions starting with 0x are always hexadecimal literals.\nExpressions starting with a numeric literal followed by e or E are always floating-point literals." -}, - -{ - "location": "manual/integers-and-floating-point-numbers.html#Literal-zero-and-one-1", - "page": "Integers and Floating-Point Numbers", - "title": "Literal zero and one", - "category": "section", - "text": "Julia provides functions which return literal 0 and 1 corresponding to a specified type or the type of a given variable.Function Description\nzero(x) Literal zero of type x or type of variable x\none(x) Literal one of type x or type of variable xThese functions are useful in Numeric Comparisons to avoid overhead from unnecessary type conversion.Examples:julia> zero(Float32)\n0.0f0\n\njulia> zero(1.0)\n0.0\n\njulia> one(Int32)\n1\n\njulia> one(BigFloat)\n1.000000000000000000000000000000000000000000000000000000000000000000000000000000" -}, - -{ - "location": "manual/mathematical-operations.html#", - "page": "Mathematical Operations and Elementary Functions", - "title": "Mathematical Operations and Elementary Functions", - "category": "page", - "text": "" -}, - -{ - "location": "manual/mathematical-operations.html#Mathematical-Operations-and-Elementary-Functions-1", - "page": "Mathematical Operations and Elementary Functions", - "title": "Mathematical Operations and Elementary Functions", - "category": "section", - "text": "Julia provides a complete collection of basic arithmetic and bitwise operators across all of its numeric primitive types, as well as providing portable, efficient implementations of a comprehensive collection of standard mathematical functions." -}, - -{ - "location": "manual/mathematical-operations.html#Arithmetic-Operators-1", - "page": "Mathematical Operations and Elementary Functions", - "title": "Arithmetic Operators", - "category": "section", - "text": "The following arithmetic operators are supported on all primitive numeric types:Expression Name Description\n+x unary plus the identity operation\n-x unary minus maps values to their additive inverses\nx + y binary plus performs addition\nx - y binary minus performs subtraction\nx * y times performs multiplication\nx / y divide performs division\nx \\ y inverse divide equivalent to y / x\nx ^ y power raises x to the yth power\nx % y remainder equivalent to rem(x,y)as well as the negation on Bool types:Expression Name Description\n!x negation changes true to false and vice versaJulia\'s promotion system makes arithmetic operations on mixtures of argument types \"just work\" naturally and automatically. See Conversion and Promotion for details of the promotion system.Here are some simple examples using arithmetic operators:julia> 1 + 2 + 3\n6\n\njulia> 1 - 2\n-1\n\njulia> 3*2/12\n0.5(By convention, we tend to space operators more tightly if they get applied before other nearby operators. For instance, we would generally write -x + 2 to reflect that first x gets negated, and then 2 is added to that result.)" -}, - -{ - "location": "manual/mathematical-operations.html#Bitwise-Operators-1", - "page": "Mathematical Operations and Elementary Functions", - "title": "Bitwise Operators", - "category": "section", - "text": "The following bitwise operators are supported on all primitive integer types:Expression Name\n~x bitwise not\nx & y bitwise and\nx | y bitwise or\nx ⊻ y bitwise xor (exclusive or)\nx >>> y logical shift right\nx >> y arithmetic shift right\nx << y logical/arithmetic shift leftHere are some examples with bitwise operators:julia> ~123\n-124\n\njulia> 123 & 234\n106\n\njulia> 123 | 234\n251\n\njulia> 123 ⊻ 234\n145\n\njulia> xor(123, 234)\n145\n\njulia> ~UInt32(123)\n0xffffff84\n\njulia> ~UInt8(123)\n0x84" -}, - -{ - "location": "manual/mathematical-operations.html#Updating-operators-1", - "page": "Mathematical Operations and Elementary Functions", - "title": "Updating operators", - "category": "section", - "text": "Every binary arithmetic and bitwise operator also has an updating version that assigns the result of the operation back into its left operand. The updating version of the binary operator is formed by placing a = immediately after the operator. For example, writing x += 3 is equivalent to writing x = x + 3:julia> x = 1\n1\n\njulia> x += 3\n4\n\njulia> x\n4The updating versions of all the binary arithmetic and bitwise operators are:+= -= *= /= \\= ÷= %= ^= &= |= ⊻= >>>= >>= <<=note: Note\nAn updating operator rebinds the variable on the left-hand side. As a result, the type of the variable may change.julia> x = 0x01; typeof(x)\nUInt8\n\njulia> x *= 2 # Same as x = x * 2\n2\n\njulia> typeof(x)\nInt64" -}, - -{ - "location": "manual/mathematical-operations.html#man-dot-operators-1", - "page": "Mathematical Operations and Elementary Functions", - "title": "Vectorized \"dot\" operators", - "category": "section", - "text": "For every binary operation like ^, there is a corresponding \"dot\" operation .^ that is automatically defined to perform ^ element-by-element on arrays. For example, [1,2,3] ^ 3 is not defined, since there is no standard mathematical meaning to \"cubing\" an array, but [1,2,3] .^ 3 is defined as computing the elementwise (or \"vectorized\") result [1^3, 2^3, 3^3]. Similarly for unary operators like ! or √, there is a corresponding .√ that applies the operator elementwise.julia> [1,2,3] .^ 3\n3-element Array{Int64,1}:\n 1\n 8\n 27More specifically, a .^ b is parsed as the \"dot\" call (^).(a,b), which performs a broadcast operation: it can combine arrays and scalars, arrays of the same size (performing the operation elementwise), and even arrays of different shapes (e.g. combining row and column vectors to produce a matrix). Moreover, like all vectorized \"dot calls,\" these \"dot operators\" are fusing. For example, if you compute 2 .* A.^2 .+ sin.(A) (or equivalently @. 2A^2 + sin(A), using the @. macro) for an array A, it performs a single loop over A, computing 2a^2 + sin(a) for each element of A. In particular, nested dot calls like f.(g.(x)) are fused, and \"adjacent\" binary operators like x .+ 3 .* x.^2 are equivalent to nested dot calls (+).(x, (*).(3, (^).(x, 2))).Furthermore, \"dotted\" updating operators like a .+= b (or @. a += b) are parsed as a .= a .+ b, where .= is a fused in-place assignment operation (see the dot syntax documentation).Note the dot syntax is also applicable to user-defined operators. For example, if you define ⊗(A,B) = kron(A,B) to give a convenient infix syntax A ⊗ B for Kronecker products (kron), then [A,B] .⊗ [C,D] will compute [A⊗C, B⊗D] with no additional coding." -}, - -{ - "location": "manual/mathematical-operations.html#Numeric-Comparisons-1", - "page": "Mathematical Operations and Elementary Functions", - "title": "Numeric Comparisons", - "category": "section", - "text": "Standard comparison operations are defined for all the primitive numeric types:Operator Name\n== equality\n!=, ≠ inequality\n< less than\n<=, ≤ less than or equal to\n> greater than\n>=, ≥ greater than or equal toHere are some simple examples:julia> 1 == 1\ntrue\n\njulia> 1 == 2\nfalse\n\njulia> 1 != 2\ntrue\n\njulia> 1 == 1.0\ntrue\n\njulia> 1 < 2\ntrue\n\njulia> 1.0 > 3\nfalse\n\njulia> 1 >= 1.0\ntrue\n\njulia> -1 <= 1\ntrue\n\njulia> -1 <= -1\ntrue\n\njulia> -1 <= -2\nfalse\n\njulia> 3 < -0.5\nfalseIntegers are compared in the standard manner – by comparison of bits. Floating-point numbers are compared according to the IEEE 754 standard:Finite numbers are ordered in the usual manner.\nPositive zero is equal but not greater than negative zero.\nInf is equal to itself and greater than everything else except NaN.\n-Inf is equal to itself and less then everything else except NaN.\nNaN is not equal to, not less than, and not greater than anything, including itself.The last point is potentially surprising and thus worth noting:julia> NaN == NaN\nfalse\n\njulia> NaN != NaN\ntrue\n\njulia> NaN < NaN\nfalse\n\njulia> NaN > NaN\nfalseand can cause especial headaches with Arrays:julia> [1 NaN] == [1 NaN]\nfalseJulia provides additional functions to test numbers for special values, which can be useful in situations like hash key comparisons:Function Tests if\nisequal(x, y) x and y are identical\nisfinite(x) x is a finite number\nisinf(x) x is infinite\nisnan(x) x is not a numberisequal() considers NaNs equal to each other:julia> isequal(NaN, NaN)\ntrue\n\njulia> isequal([1 NaN], [1 NaN])\ntrue\n\njulia> isequal(NaN, NaN32)\ntrueisequal() can also be used to distinguish signed zeros:julia> -0.0 == 0.0\ntrue\n\njulia> isequal(-0.0, 0.0)\nfalseMixed-type comparisons between signed integers, unsigned integers, and floats can be tricky. A great deal of care has been taken to ensure that Julia does them correctly.For other types, isequal() defaults to calling ==(), so if you want to define equality for your own types then you only need to add a ==() method. If you define your own equality function, you should probably define a corresponding hash() method to ensure that isequal(x,y) implies hash(x) == hash(y)." -}, - -{ - "location": "manual/mathematical-operations.html#Chaining-comparisons-1", - "page": "Mathematical Operations and Elementary Functions", - "title": "Chaining comparisons", - "category": "section", - "text": "Unlike most languages, with the notable exception of Python, comparisons can be arbitrarily chained:julia> 1 < 2 <= 2 < 3 == 3 > 2 >= 1 == 1 < 3 != 5\ntrueChaining comparisons is often quite convenient in numerical code. Chained comparisons use the && operator for scalar comparisons, and the & operator for elementwise comparisons, which allows them to work on arrays. For example, 0 .< A .< 1 gives a boolean array whose entries are true where the corresponding elements of A are between 0 and 1.Note the evaluation behavior of chained comparisons:julia> v(x) = (println(x); x)\nv (generic function with 1 method)\n\njulia> v(1) < v(2) <= v(3)\n2\n1\n3\ntrue\n\njulia> v(1) > v(2) <= v(3)\n2\n1\nfalseThe middle expression is only evaluated once, rather than twice as it would be if the expression were written as v(1) < v(2) && v(2) <= v(3). However, the order of evaluations in a chained comparison is undefined. It is strongly recommended not to use expressions with side effects (such as printing) in chained comparisons. If side effects are required, the short-circuit && operator should be used explicitly (see Short-Circuit Evaluation)." -}, - -{ - "location": "manual/mathematical-operations.html#Elementary-Functions-1", - "page": "Mathematical Operations and Elementary Functions", - "title": "Elementary Functions", - "category": "section", - "text": "Julia provides a comprehensive collection of mathematical functions and operators. These mathematical operations are defined over as broad a class of numerical values as permit sensible definitions, including integers, floating-point numbers, rationals, and complex numbers, wherever such definitions make sense.Moreover, these functions (like any Julia function) can be applied in \"vectorized\" fashion to arrays and other collections with the dot syntax f.(A), e.g. sin.(A) will compute the sine of each element of an array A." -}, - -{ - "location": "manual/mathematical-operations.html#Operator-Precedence-1", - "page": "Mathematical Operations and Elementary Functions", - "title": "Operator Precedence", - "category": "section", - "text": "Julia applies the following order of operations, from highest precedence to lowest:Category Operators\nSyntax . followed by ::\nExponentiation ^\nFractions //\nMultiplication * / % & \\\nBitshifts << >> >>>\nAddition + - | ⊻\nSyntax : .. followed by |>\nComparisons > < >= <= == === != !== <:\nControl flow && followed by || followed by ?\nAssignments = += -= *= /= //= \\= ^= ÷= %= |= &= ⊻= <<= >>= >>>=For a complete list of every Julia operator\'s precedence, see the top of this file: src/julia-parser.scmYou can also find the numerical precedence for any given operator via the built-in function Base.operator_precedence, where higher numbers take precedence:julia> Base.operator_precedence(:+), Base.operator_precedence(:*), Base.operator_precedence(:.)\n(9, 11, 15)\n\njulia> Base.operator_precedence(:+=), Base.operator_precedence(:(=)) # (Note the necessary parens on `:(=)`)\n(1, 1)" -}, - -{ - "location": "manual/mathematical-operations.html#Numerical-Conversions-1", - "page": "Mathematical Operations and Elementary Functions", - "title": "Numerical Conversions", - "category": "section", - "text": "Julia supports three forms of numerical conversion, which differ in their handling of inexact conversions.The notation T(x) or convert(T,x) converts x to a value of type T.\nIf T is a floating-point type, the result is the nearest representable value, which could be positive or negative infinity.\nIf T is an integer type, an InexactError is raised if x is not representable by T.\nx % T converts an integer x to a value of integer type T congruent to x modulo 2^n, where n is the number of bits in T. In other words, the binary representation is truncated to fit.\nThe Rounding functions take a type T as an optional argument. For example, round(Int,x) is a shorthand for Int(round(x)).The following examples show the different forms.julia> Int8(127)\n127\n\njulia> Int8(128)\nERROR: InexactError()\nStacktrace:\n [1] Int8(::Int64) at ./sysimg.jl:77\n\njulia> Int8(127.0)\n127\n\njulia> Int8(3.14)\nERROR: InexactError()\nStacktrace:\n [1] convert(::Type{Int8}, ::Float64) at ./float.jl:658\n [2] Int8(::Float64) at ./sysimg.jl:77\n\njulia> Int8(128.0)\nERROR: InexactError()\nStacktrace:\n [1] convert(::Type{Int8}, ::Float64) at ./float.jl:658\n [2] Int8(::Float64) at ./sysimg.jl:77\n\njulia> 127 % Int8\n127\n\njulia> 128 % Int8\n-128\n\njulia> round(Int8,127.4)\n127\n\njulia> round(Int8,127.6)\nERROR: InexactError()\nStacktrace:\n [1] trunc(::Type{Int8}, ::Float64) at ./float.jl:651\n [2] round(::Type{Int8}, ::Float64) at ./float.jl:337See Conversion and Promotion for how to define your own conversions and promotions." -}, - -{ - "location": "manual/mathematical-operations.html#Rounding-functions-1", - "page": "Mathematical Operations and Elementary Functions", - "title": "Rounding functions", - "category": "section", - "text": "Function Description Return type\nround(x) round x to the nearest integer typeof(x)\nround(T, x) round x to the nearest integer T\nfloor(x) round x towards -Inf typeof(x)\nfloor(T, x) round x towards -Inf T\nceil(x) round x towards +Inf typeof(x)\nceil(T, x) round x towards +Inf T\ntrunc(x) round x towards zero typeof(x)\ntrunc(T, x) round x towards zero T" -}, - -{ - "location": "manual/mathematical-operations.html#Division-functions-1", - "page": "Mathematical Operations and Elementary Functions", - "title": "Division functions", - "category": "section", - "text": "Function Description\ndiv(x,y) truncated division; quotient rounded towards zero\nfld(x,y) floored division; quotient rounded towards -Inf\ncld(x,y) ceiling division; quotient rounded towards +Inf\nrem(x,y) remainder; satisfies x == div(x,y)*y + rem(x,y); sign matches x\nmod(x,y) modulus; satisfies x == fld(x,y)*y + mod(x,y); sign matches y\nmod1(x,y) mod() with offset 1; returns r∈(0,y] for y>0 or r∈[y,0) for y<0, where mod(r, y) == mod(x, y)\nmod2pi(x) modulus with respect to 2pi; 0 <= mod2pi(x)   < 2pi\ndivrem(x,y) returns (div(x,y),rem(x,y))\nfldmod(x,y) returns (fld(x,y),mod(x,y))\ngcd(x,y...) greatest positive common divisor of x, y,...\nlcm(x,y...) least positive common multiple of x, y,..." -}, - -{ - "location": "manual/mathematical-operations.html#Sign-and-absolute-value-functions-1", - "page": "Mathematical Operations and Elementary Functions", - "title": "Sign and absolute value functions", - "category": "section", - "text": "Function Description\nabs(x) a positive value with the magnitude of x\nabs2(x) the squared magnitude of x\nsign(x) indicates the sign of x, returning -1, 0, or +1\nsignbit(x) indicates whether the sign bit is on (true) or off (false)\ncopysign(x,y) a value with the magnitude of x and the sign of y\nflipsign(x,y) a value with the magnitude of x and the sign of x*y" -}, - -{ - "location": "manual/mathematical-operations.html#Powers,-logs-and-roots-1", - "page": "Mathematical Operations and Elementary Functions", - "title": "Powers, logs and roots", - "category": "section", - "text": "Function Description\nsqrt(x), √x square root of x\ncbrt(x), ∛x cube root of x\nhypot(x,y) hypotenuse of right-angled triangle with other sides of length x and y\nexp(x) natural exponential function at x\nexpm1(x) accurate exp(x)-1 for x near zero\nldexp(x,n) x*2^n computed efficiently for integer values of n\nlog(x) natural logarithm of x\nlog(b,x) base b logarithm of x\nlog2(x) base 2 logarithm of x\nlog10(x) base 10 logarithm of x\nlog1p(x) accurate log(1+x) for x near zero\nexponent(x) binary exponent of x\nsignificand(x) binary significand (a.k.a. mantissa) of a floating-point number xFor an overview of why functions like hypot(), expm1(), and log1p() are necessary and useful, see John D. Cook\'s excellent pair of blog posts on the subject: expm1, log1p, erfc, and hypot." -}, - -{ - "location": "manual/mathematical-operations.html#Trigonometric-and-hyperbolic-functions-1", - "page": "Mathematical Operations and Elementary Functions", - "title": "Trigonometric and hyperbolic functions", - "category": "section", - "text": "All the standard trigonometric and hyperbolic functions are also defined:sin cos tan cot sec csc\nsinh cosh tanh coth sech csch\nasin acos atan acot asec acsc\nasinh acosh atanh acoth asech acsch\nsinc cosc atan2These are all single-argument functions, with the exception of atan2, which gives the angle in radians between the x-axis and the point specified by its arguments, interpreted as x and y coordinates.Additionally, sinpi(x) and cospi(x) are provided for more accurate computations of sin(pi*x) and cos(pi*x) respectively.In order to compute trigonometric functions with degrees instead of radians, suffix the function with d. For example, sind(x) computes the sine of x where x is specified in degrees. The complete list of trigonometric functions with degree variants is:sind cosd tand cotd secd cscd\nasind acosd atand acotd asecd acscd" -}, - -{ - "location": "manual/mathematical-operations.html#Special-functions-1", - "page": "Mathematical Operations and Elementary Functions", - "title": "Special functions", - "category": "section", - "text": "Function Description\ngamma(x) gamma function at x\nlgamma(x) accurate log(gamma(x)) for large x\nlfact(x) accurate log(factorial(x)) for large x; same as lgamma(x+1) for x > 1, zero otherwise\nbeta(x,y) beta function at x,y\nlbeta(x,y) accurate log(beta(x,y)) for large x or y" -}, - -{ - "location": "manual/complex-and-rational-numbers.html#", - "page": "Complex and Rational Numbers", - "title": "Complex and Rational Numbers", - "category": "page", - "text": "" -}, - -{ - "location": "manual/complex-and-rational-numbers.html#Complex-and-Rational-Numbers-1", - "page": "Complex and Rational Numbers", - "title": "Complex and Rational Numbers", - "category": "section", - "text": "Julia ships with predefined types representing both complex and rational numbers, and supports all standard Mathematical Operations and Elementary Functions on them. Conversion and Promotion are defined so that operations on any combination of predefined numeric types, whether primitive or composite, behave as expected." -}, - -{ - "location": "manual/complex-and-rational-numbers.html#Complex-Numbers-1", - "page": "Complex and Rational Numbers", - "title": "Complex Numbers", - "category": "section", - "text": "The global constant im is bound to the complex number i, representing the principal square root of -1. It was deemed harmful to co-opt the name i for a global constant, since it is such a popular index variable name. Since Julia allows numeric literals to be juxtaposed with identifiers as coefficients, this binding suffices to provide convenient syntax for complex numbers, similar to the traditional mathematical notation:julia> 1 + 2im\n1 + 2imYou can perform all the standard arithmetic operations with complex numbers:julia> (1 + 2im)*(2 - 3im)\n8 + 1im\n\njulia> (1 + 2im)/(1 - 2im)\n-0.6 + 0.8im\n\njulia> (1 + 2im) + (1 - 2im)\n2 + 0im\n\njulia> (-3 + 2im) - (5 - 1im)\n-8 + 3im\n\njulia> (-1 + 2im)^2\n-3 - 4im\n\njulia> (-1 + 2im)^2.5\n2.7296244647840084 - 6.960664459571898im\n\njulia> (-1 + 2im)^(1 + 1im)\n-0.27910381075826657 + 0.08708053414102428im\n\njulia> 3(2 - 5im)\n6 - 15im\n\njulia> 3(2 - 5im)^2\n-63 - 60im\n\njulia> 3(2 - 5im)^-1.0\n0.20689655172413796 + 0.5172413793103449imThe promotion mechanism ensures that combinations of operands of different types just work:julia> 2(1 - 1im)\n2 - 2im\n\njulia> (2 + 3im) - 1\n1 + 3im\n\njulia> (1 + 2im) + 0.5\n1.5 + 2.0im\n\njulia> (2 + 3im) - 0.5im\n2.0 + 2.5im\n\njulia> 0.75(1 + 2im)\n0.75 + 1.5im\n\njulia> (2 + 3im) / 2\n1.0 + 1.5im\n\njulia> (1 - 3im) / (2 + 2im)\n-0.5 - 1.0im\n\njulia> 2im^2\n-2 + 0im\n\njulia> 1 + 3/4im\n1.0 - 0.75imNote that 3/4im == 3/(4*im) == -(3/4*im), since a literal coefficient binds more tightly than division.Standard functions to manipulate complex values are provided:julia> z = 1 + 2im\n1 + 2im\n\njulia> real(1 + 2im) # real part of z\n1\n\njulia> imag(1 + 2im) # imaginary part of z\n2\n\njulia> conj(1 + 2im) # complex conjugate of z\n1 - 2im\n\njulia> abs(1 + 2im) # absolute value of z\n2.23606797749979\n\njulia> abs2(1 + 2im) # squared absolute value\n5\n\njulia> angle(1 + 2im) # phase angle in radians\n1.1071487177940904As usual, the absolute value (abs()) of a complex number is its distance from zero. abs2() gives the square of the absolute value, and is of particular use for complex numbers where it avoids taking a square root. angle() returns the phase angle in radians (also known as the argument or arg function). The full gamut of other Elementary Functions is also defined for complex numbers:julia> sqrt(1im)\n0.7071067811865476 + 0.7071067811865475im\n\njulia> sqrt(1 + 2im)\n1.272019649514069 + 0.7861513777574233im\n\njulia> cos(1 + 2im)\n2.0327230070196656 - 3.0518977991518im\n\njulia> exp(1 + 2im)\n-1.1312043837568135 + 2.4717266720048188im\n\njulia> sinh(1 + 2im)\n-0.4890562590412937 + 1.4031192506220405imNote that mathematical functions typically return real values when applied to real numbers and complex values when applied to complex numbers. For example, sqrt() behaves differently when applied to -1 versus -1 + 0im even though -1 == -1 + 0im:julia> sqrt(-1)\nERROR: DomainError:\nsqrt will only return a complex result if called with a complex argument. Try sqrt(complex(x)).\nStacktrace:\n [1] sqrt(::Int64) at ./math.jl:434\n\njulia> sqrt(-1 + 0im)\n0.0 + 1.0imThe literal numeric coefficient notation does not work when constructing a complex number from variables. Instead, the multiplication must be explicitly written out:julia> a = 1; b = 2; a + b*im\n1 + 2imHowever, this is not recommended; Use the complex() function instead to construct a complex value directly from its real and imaginary parts:julia> a = 1; b = 2; complex(a, b)\n1 + 2imThis construction avoids the multiplication and addition operations.Inf and NaN propagate through complex numbers in the real and imaginary parts of a complex number as described in the Special floating-point values section:julia> 1 + Inf*im\n1.0 + Inf*im\n\njulia> 1 + NaN*im\n1.0 + NaN*im" -}, - -{ - "location": "manual/complex-and-rational-numbers.html#Rational-Numbers-1", - "page": "Complex and Rational Numbers", - "title": "Rational Numbers", - "category": "section", - "text": "Julia has a rational number type to represent exact ratios of integers. Rationals are constructed using the // operator:julia> 2//3\n2//3If the numerator and denominator of a rational have common factors, they are reduced to lowest terms such that the denominator is non-negative:julia> 6//9\n2//3\n\njulia> -4//8\n-1//2\n\njulia> 5//-15\n-1//3\n\njulia> -4//-12\n1//3This normalized form for a ratio of integers is unique, so equality of rational values can be tested by checking for equality of the numerator and denominator. The standardized numerator and denominator of a rational value can be extracted using the numerator() and denominator() functions:julia> numerator(2//3)\n2\n\njulia> denominator(2//3)\n3Direct comparison of the numerator and denominator is generally not necessary, since the standard arithmetic and comparison operations are defined for rational values:julia> 2//3 == 6//9\ntrue\n\njulia> 2//3 == 9//27\nfalse\n\njulia> 3//7 < 1//2\ntrue\n\njulia> 3//4 > 2//3\ntrue\n\njulia> 2//4 + 1//6\n2//3\n\njulia> 5//12 - 1//4\n1//6\n\njulia> 5//8 * 3//12\n5//32\n\njulia> 6//5 / 10//7\n21//25Rationals can be easily converted to floating-point numbers:julia> float(3//4)\n0.75Conversion from rational to floating-point respects the following identity for any integral values of a and b, with the exception of the case a == 0 and b == 0:julia> a = 1; b = 2;\n\njulia> isequal(float(a//b), a/b)\ntrueConstructing infinite rational values is acceptable:julia> 5//0\n1//0\n\njulia> -3//0\n-1//0\n\njulia> typeof(ans)\nRational{Int64}Trying to construct a NaN rational value, however, is not:julia> 0//0\nERROR: ArgumentError: invalid rational: zero(Int64)//zero(Int64)\nStacktrace:\n [1] Rational{Int64}(::Int64, ::Int64) at ./rational.jl:13\n [2] //(::Int64, ::Int64) at ./rational.jl:40As usual, the promotion system makes interactions with other numeric types effortless:julia> 3//5 + 1\n8//5\n\njulia> 3//5 - 0.5\n0.09999999999999998\n\njulia> 2//7 * (1 + 2im)\n2//7 + 4//7*im\n\njulia> 2//7 * (1.5 + 2im)\n0.42857142857142855 + 0.5714285714285714im\n\njulia> 3//2 / (1 + 2im)\n3//10 - 3//5*im\n\njulia> 1//2 + 2im\n1//2 + 2//1*im\n\njulia> 1 + 2//3im\n1//1 - 2//3*im\n\njulia> 0.5 == 1//2\ntrue\n\njulia> 0.33 == 1//3\nfalse\n\njulia> 0.33 < 1//3\ntrue\n\njulia> 1//3 - 0.33\n0.0033333333333332993" -}, - -{ - "location": "manual/strings.html#", - "page": "Strings", - "title": "Strings", - "category": "page", - "text": "" -}, - -{ - "location": "manual/strings.html#man-strings-1", - "page": "Strings", - "title": "Strings", - "category": "section", - "text": "Strings are finite sequences of characters. Of course, the real trouble comes when one asks what a character is. The characters that English speakers are familiar with are the letters A, B, C, etc., together with numerals and common punctuation symbols. These characters are standardized together with a mapping to integer values between 0 and 127 by the ASCII standard. There are, of course, many other characters used in non-English languages, including variants of the ASCII characters with accents and other modifications, related scripts such as Cyrillic and Greek, and scripts completely unrelated to ASCII and English, including Arabic, Chinese, Hebrew, Hindi, Japanese, and Korean. The Unicode standard tackles the complexities of what exactly a character is, and is generally accepted as the definitive standard addressing this problem. Depending on your needs, you can either ignore these complexities entirely and just pretend that only ASCII characters exist, or you can write code that can handle any of the characters or encodings that one may encounter when handling non-ASCII text. Julia makes dealing with plain ASCII text simple and efficient, and handling Unicode is as simple and efficient as possible. In particular, you can write C-style string code to process ASCII strings, and they will work as expected, both in terms of performance and semantics. If such code encounters non-ASCII text, it will gracefully fail with a clear error message, rather than silently introducing corrupt results. When this happens, modifying the code to handle non-ASCII data is straightforward.There are a few noteworthy high-level features about Julia\'s strings:The built-in concrete type used for strings (and string literals) in Julia is String. This supports the full range of Unicode characters via the UTF-8 encoding. (A transcode() function is provided to convert to/from other Unicode encodings.)\nAll string types are subtypes of the abstract type AbstractString, and external packages define additional AbstractString subtypes (e.g. for other encodings). If you define a function expecting a string argument, you should declare the type as AbstractString in order to accept any string type.\nLike C and Java, but unlike most dynamic languages, Julia has a first-class type representing a single character, called Char. This is just a special kind of 32-bit primitive type whose numeric value represents a Unicode code point.\nAs in Java, strings are immutable: the value of an AbstractString object cannot be changed. To construct a different string value, you construct a new string from parts of other strings.\nConceptually, a string is a partial function from indices to characters: for some index values, no character value is returned, and instead an exception is thrown. This allows for efficient indexing into strings by the byte index of an encoded representation rather than by a character index, which cannot be implemented both efficiently and simply for variable-width encodings of Unicode strings." -}, - -{ - "location": "manual/strings.html#man-characters-1", - "page": "Strings", - "title": "Characters", - "category": "section", - "text": "A Char value represents a single character: it is just a 32-bit primitive type with a special literal representation and appropriate arithmetic behaviors, whose numeric value is interpreted as a Unicode code point. Here is how Char values are input and shown:julia> \'x\'\n\'x\': ASCII/Unicode U+0078 (category Ll: Letter, lowercase)\n\njulia> typeof(ans)\nCharYou can convert a Char to its integer value, i.e. code point, easily:julia> Int(\'x\')\n120\n\njulia> typeof(ans)\nInt64On 32-bit architectures, typeof(ans) will be Int32. You can convert an integer value back to a Char just as easily:julia> Char(120)\n\'x\': ASCII/Unicode U+0078 (category Ll: Letter, lowercase)Not all integer values are valid Unicode code points, but for performance, the Char() conversion does not check that every character value is valid. If you want to check that each converted value is a valid code point, use the isvalid() function:julia> Char(0x110000)\n\'\\U110000\': Unicode U+110000 (category Cn: Other, not assigned)\n\njulia> isvalid(Char, 0x110000)\nfalseAs of this writing, the valid Unicode code points are U+00 through U+d7ff and U+e000 through U+10ffff. These have not all been assigned intelligible meanings yet, nor are they necessarily interpretable by applications, but all of these values are considered to be valid Unicode characters.You can input any Unicode character in single quotes using \\u followed by up to four hexadecimal digits or \\U followed by up to eight hexadecimal digits (the longest valid value only requires six):julia> \'\\u0\'\n\'\\0\': ASCII/Unicode U+0000 (category Cc: Other, control)\n\njulia> \'\\u78\'\n\'x\': ASCII/Unicode U+0078 (category Ll: Letter, lowercase)\n\njulia> \'\\u2200\'\n\'∀\': Unicode U+2200 (category Sm: Symbol, math)\n\njulia> \'\\U10ffff\'\n\'\\U10ffff\': Unicode U+10ffff (category Cn: Other, not assigned)Julia uses your system\'s locale and language settings to determine which characters can be printed as-is and which must be output using the generic, escaped \\u or \\U input forms. In addition to these Unicode escape forms, all of C\'s traditional escaped input forms can also be used:julia> Int(\'\\0\')\n0\n\njulia> Int(\'\\t\')\n9\n\njulia> Int(\'\\n\')\n10\n\njulia> Int(\'\\e\')\n27\n\njulia> Int(\'\\x7f\')\n127\n\njulia> Int(\'\\177\')\n127\n\njulia> Int(\'\\xff\')\n255You can do comparisons and a limited amount of arithmetic with Char values:julia> \'A\' < \'a\'\ntrue\n\njulia> \'A\' <= \'a\' <= \'Z\'\nfalse\n\njulia> \'A\' <= \'X\' <= \'Z\'\ntrue\n\njulia> \'x\' - \'a\'\n23\n\njulia> \'A\' + 1\n\'B\': ASCII/Unicode U+0042 (category Lu: Letter, uppercase)" -}, - -{ - "location": "manual/strings.html#String-Basics-1", - "page": "Strings", - "title": "String Basics", - "category": "section", - "text": "String literals are delimited by double quotes or triple double quotes:julia> str = \"Hello, world.\\n\"\n\"Hello, world.\\n\"\n\njulia> \"\"\"Contains \"quote\" characters\"\"\"\n\"Contains \\\"quote\\\" characters\"If you want to extract a character from a string, you index into it:julia> str[1]\n\'H\': ASCII/Unicode U+0048 (category Lu: Letter, uppercase)\n\njulia> str[6]\n\',\': ASCII/Unicode U+002c (category Po: Punctuation, other)\n\njulia> str[end]\n\'\\n\': ASCII/Unicode U+000a (category Cc: Other, control)All indexing in Julia is 1-based: the first element of any integer-indexed object is found at index 1. (As we will see below, this does not necessarily mean that the last element is found at index n, where n is the length of the string.)In any indexing expression, the keyword end can be used as a shorthand for the last index (computed by endof(str)). You can perform arithmetic and other operations with end, just like a normal value:julia> str[end-1]\n\'.\': ASCII/Unicode U+002e (category Po: Punctuation, other)\n\njulia> str[end÷2]\n\' \': ASCII/Unicode U+0020 (category Zs: Separator, space)Using an index less than 1 or greater than end raises an error:julia> str[0]\nERROR: BoundsError: attempt to access \"Hello, world.\\n\"\n at index [0]\n[...]\n\njulia> str[end+1]\nERROR: BoundsError: attempt to access \"Hello, world.\\n\"\n at index [15]\n[...]You can also extract a substring using range indexing:julia> str[4:9]\n\"lo, wo\"Notice that the expressions str[k] and str[k:k] do not give the same result:julia> str[6]\n\',\': ASCII/Unicode U+002c (category Po: Punctuation, other)\n\njulia> str[6:6]\n\",\"The former is a single character value of type Char, while the latter is a string value that happens to contain only a single character. In Julia these are very different things." -}, - -{ - "location": "manual/strings.html#Unicode-and-UTF-8-1", - "page": "Strings", - "title": "Unicode and UTF-8", - "category": "section", - "text": "Julia fully supports Unicode characters and strings. As discussed above, in character literals, Unicode code points can be represented using Unicode \\u and \\U escape sequences, as well as all the standard C escape sequences. These can likewise be used to write string literals:julia> s = \"\\u2200 x \\u2203 y\"\n\"∀ x ∃ y\"Whether these Unicode characters are displayed as escapes or shown as special characters depends on your terminal\'s locale settings and its support for Unicode. String literals are encoded using the UTF-8 encoding. UTF-8 is a variable-width encoding, meaning that not all characters are encoded in the same number of bytes. In UTF-8, ASCII characters – i.e. those with code points less than 0x80 (128) – are encoded as they are in ASCII, using a single byte, while code points 0x80 and above are encoded using multiple bytes – up to four per character. This means that not every byte index into a UTF-8 string is necessarily a valid index for a character. If you index into a string at such an invalid byte index, an error is thrown:julia> s[1]\n\'∀\': Unicode U+2200 (category Sm: Symbol, math)\n\njulia> s[2]\nERROR: UnicodeError: invalid character index\n[...]\n\njulia> s[3]\nERROR: UnicodeError: invalid character index\n[...]\n\njulia> s[4]\n\' \': ASCII/Unicode U+0020 (category Zs: Separator, space)In this case, the character ∀ is a three-byte character, so the indices 2 and 3 are invalid and the next character\'s index is 4; this next valid index can be computed by nextind(s,1), and the next index after that by nextind(s,4) and so on.Because of variable-length encodings, the number of characters in a string (given by length(s)) is not always the same as the last index. If you iterate through the indices 1 through endof(s) and index into s, the sequence of characters returned when errors aren\'t thrown is the sequence of characters comprising the string s. Thus we have the identity that length(s) <= endof(s), since each character in a string must have its own index. The following is an inefficient and verbose way to iterate through the characters of s:julia> for i = 1:endof(s)\n try\n println(s[i])\n catch\n # ignore the index error\n end\n end\n∀\n\nx\n\n∃\n\nyThe blank lines actually have spaces on them. Fortunately, the above awkward idiom is unnecessary for iterating through the characters in a string, since you can just use the string as an iterable object, no exception handling required:julia> for c in s\n println(c)\n end\n∀\n\nx\n\n∃\n\nyJulia uses the UTF-8 encoding by default, and support for new encodings can be added by packages. For example, the LegacyStrings.jl package implements UTF16String and UTF32String types. Additional discussion of other encodings and how to implement support for them is beyond the scope of this document for the time being. For further discussion of UTF-8 encoding issues, see the section below on byte array literals. The transcode() function is provided to convert data between the various UTF-xx encodings, primarily for working with external data and libraries." -}, - -{ - "location": "manual/strings.html#Concatenation-1", - "page": "Strings", - "title": "Concatenation", - "category": "section", - "text": "One of the most common and useful string operations is concatenation:julia> greet = \"Hello\"\n\"Hello\"\n\njulia> whom = \"world\"\n\"world\"\n\njulia> string(greet, \", \", whom, \".\\n\")\n\"Hello, world.\\n\"Julia also provides * for string concatenation:julia> greet * \", \" * whom * \".\\n\"\n\"Hello, world.\\n\"While * may seem like a surprising choice to users of languages that provide + for string concatenation, this use of * has precedent in mathematics, particularly in abstract algebra.In mathematics, + usually denotes a commutative operation, where the order of the operands does not matter. An example of this is matrix addition, where A + B == B + A for any matrices A and B that have the same shape. In contrast, * typically denotes a noncommutative operation, where the order of the operands does matter. An example of this is matrix multiplication, where in general A * B != B * A. As with matrix multiplication, string concatenation is noncommutative: greet * whom != whom * greet. As such, * is a more natural choice for an infix string concatenation operator, consistent with common mathematical use.More precisely, the set of all finite-length strings S together with the string concatenation operator * forms a free monoid (S, *). The identity element of this set is the empty string, \"\". Whenever a free monoid is not commutative, the operation is typically represented as \\cdot, *, or a similar symbol, rather than +, which as stated usually implies commutativity." -}, - -{ - "location": "manual/strings.html#string-interpolation-1", - "page": "Strings", - "title": "Interpolation", - "category": "section", - "text": "Constructing strings using concatenation can become a bit cumbersome, however. To reduce the need for these verbose calls to string() or repeated multiplications, Julia allows interpolation into string literals using $, as in Perl:julia> \"$greet, $whom.\\n\"\n\"Hello, world.\\n\"This is more readable and convenient and equivalent to the above string concatenation – the system rewrites this apparent single string literal into a concatenation of string literals with variables.The shortest complete expression after the $ is taken as the expression whose value is to be interpolated into the string. Thus, you can interpolate any expression into a string using parentheses:julia> \"1 + 2 = $(1 + 2)\"\n\"1 + 2 = 3\"Both concatenation and string interpolation call string() to convert objects into string form. Most non-AbstractString objects are converted to strings closely corresponding to how they are entered as literal expressions:julia> v = [1,2,3]\n3-element Array{Int64,1}:\n 1\n 2\n 3\n\njulia> \"v: $v\"\n\"v: [1, 2, 3]\"string() is the identity for AbstractString and Char values, so these are interpolated into strings as themselves, unquoted and unescaped:julia> c = \'x\'\n\'x\': ASCII/Unicode U+0078 (category Ll: Letter, lowercase)\n\njulia> \"hi, $c\"\n\"hi, x\"To include a literal $ in a string literal, escape it with a backslash:julia> print(\"I have \\$100 in my account.\\n\")\nI have $100 in my account." -}, - -{ - "location": "manual/strings.html#Triple-Quoted-String-Literals-1", - "page": "Strings", - "title": "Triple-Quoted String Literals", - "category": "section", - "text": "When strings are created using triple-quotes (\"\"\"...\"\"\") they have some special behavior that can be useful for creating longer blocks of text. First, if the opening \"\"\" is followed by a newline, the newline is stripped from the resulting string.\"\"\"hello\"\"\"is equivalent to\"\"\"\nhello\"\"\"but\"\"\"\n\nhello\"\"\"will contain a literal newline at the beginning. Trailing whitespace is left unaltered. They can contain \" symbols without escaping. Triple-quoted strings are also dedented to the level of the least-indented line. This is useful for defining strings within code that is indented. For example:julia> str = \"\"\"\n Hello,\n world.\n \"\"\"\n\" Hello,\\n world.\\n\"In this case the final (empty) line before the closing \"\"\" sets the indentation level.Note that line breaks in literal strings, whether single- or triple-quoted, result in a newline (LF) character \\n in the string, even if your editor uses a carriage return \\r (CR) or CRLF combination to end lines. To include a CR in a string, use an explicit escape \\r; for example, you can enter the literal string \"a CRLF line ending\\r\\n\"." -}, - -{ - "location": "manual/strings.html#Common-Operations-1", - "page": "Strings", - "title": "Common Operations", - "category": "section", - "text": "You can lexicographically compare strings using the standard comparison operators:julia> \"abracadabra\" < \"xylophone\"\ntrue\n\njulia> \"abracadabra\" == \"xylophone\"\nfalse\n\njulia> \"Hello, world.\" != \"Goodbye, world.\"\ntrue\n\njulia> \"1 + 2 = 3\" == \"1 + 2 = $(1 + 2)\"\ntrueYou can search for the index of a particular character using the search() function:julia> search(\"xylophone\", \'x\')\n1\n\njulia> search(\"xylophone\", \'p\')\n5\n\njulia> search(\"xylophone\", \'z\')\n0You can start the search for a character at a given offset by providing a third argument:julia> search(\"xylophone\", \'o\')\n4\n\njulia> search(\"xylophone\", \'o\', 5)\n7\n\njulia> search(\"xylophone\", \'o\', 8)\n0You can use the contains() function to check if a substring is contained in a string:julia> contains(\"Hello, world.\", \"world\")\ntrue\n\njulia> contains(\"Xylophon\", \"o\")\ntrue\n\njulia> contains(\"Xylophon\", \"a\")\nfalse\n\njulia> contains(\"Xylophon\", \'o\')\nERROR: MethodError: no method matching contains(::String, ::Char)\nClosest candidates are:\n contains(!Matched::Function, ::Any, !Matched::Any) at reduce.jl:664\n contains(::AbstractString, !Matched::AbstractString) at strings/search.jl:378The last error is because \'o\' is a character literal, and contains() is a generic function that looks for subsequences. To look for an element in a sequence, you must use in() instead.Two other handy string functions are repeat() and join():julia> repeat(\".:Z:.\", 10)\n\".:Z:..:Z:..:Z:..:Z:..:Z:..:Z:..:Z:..:Z:..:Z:..:Z:.\"\n\njulia> join([\"apples\", \"bananas\", \"pineapples\"], \", \", \" and \")\n\"apples, bananas and pineapples\"Some other useful functions include:endof(str) gives the maximal (byte) index that can be used to index into str.\nlength(str) the number of characters in str.\ni = start(str) gives the first valid index at which a character can be found in str (typically 1).\nc, j = next(str,i) returns next character at or after the index i and the next valid character index following that. With start() and endof(), can be used to iterate through the characters in str.\nind2chr(str,i) gives the number of characters in str up to and including any at index i.\nchr2ind(str,j) gives the index at which the jth character in str occurs." -}, - -{ - "location": "manual/strings.html#non-standard-string-literals-1", - "page": "Strings", - "title": "Non-Standard String Literals", - "category": "section", - "text": "There are situations when you want to construct a string or use string semantics, but the behavior of the standard string construct is not quite what is needed. For these kinds of situations, Julia provides non-standard string literals. A non-standard string literal looks like a regular double-quoted string literal, but is immediately prefixed by an identifier, and doesn\'t behave quite like a normal string literal. Regular expressions, byte array literals and version number literals, as described below, are some examples of non-standard string literals. Other examples are given in the Metaprogramming section." -}, - -{ - "location": "manual/strings.html#Regular-Expressions-1", - "page": "Strings", - "title": "Regular Expressions", - "category": "section", - "text": "Julia has Perl-compatible regular expressions (regexes), as provided by the PCRE library. Regular expressions are related to strings in two ways: the obvious connection is that regular expressions are used to find regular patterns in strings; the other connection is that regular expressions are themselves input as strings, which are parsed into a state machine that can be used to efficiently search for patterns in strings. In Julia, regular expressions are input using non-standard string literals prefixed with various identifiers beginning with r. The most basic regular expression literal without any options turned on just uses r\"...\":julia> r\"^\\s*(?:#|$)\"\nr\"^\\s*(?:#|$)\"\n\njulia> typeof(ans)\nRegexTo check if a regex matches a string, use ismatch():julia> ismatch(r\"^\\s*(?:#|$)\", \"not a comment\")\nfalse\n\njulia> ismatch(r\"^\\s*(?:#|$)\", \"# a comment\")\ntrueAs one can see here, ismatch() simply returns true or false, indicating whether the given regex matches the string or not. Commonly, however, one wants to know not just whether a string matched, but also how it matched. To capture this information about a match, use the match() function instead:julia> match(r\"^\\s*(?:#|$)\", \"not a comment\")\n\njulia> match(r\"^\\s*(?:#|$)\", \"# a comment\")\nRegexMatch(\"#\")If the regular expression does not match the given string, match() returns nothing – a special value that does not print anything at the interactive prompt. Other than not printing, it is a completely normal value and you can test for it programmatically:m = match(r\"^\\s*(?:#|$)\", line)\nif m === nothing\n println(\"not a comment\")\nelse\n println(\"blank or comment\")\nendIf a regular expression does match, the value returned by match() is a RegexMatch object. These objects record how the expression matches, including the substring that the pattern matches and any captured substrings, if there are any. This example only captures the portion of the substring that matches, but perhaps we want to capture any non-blank text after the comment character. We could do the following:julia> m = match(r\"^\\s*(?:#\\s*(.*?)\\s*$|$)\", \"# a comment \")\nRegexMatch(\"# a comment \", 1=\"a comment\")When calling match(), you have the option to specify an index at which to start the search. For example:julia> m = match(r\"[0-9]\",\"aaaa1aaaa2aaaa3\",1)\nRegexMatch(\"1\")\n\njulia> m = match(r\"[0-9]\",\"aaaa1aaaa2aaaa3\",6)\nRegexMatch(\"2\")\n\njulia> m = match(r\"[0-9]\",\"aaaa1aaaa2aaaa3\",11)\nRegexMatch(\"3\")You can extract the following info from a RegexMatch object:the entire substring matched: m.match\nthe captured substrings as an array of strings: m.captures\nthe offset at which the whole match begins: m.offset\nthe offsets of the captured substrings as a vector: m.offsetsFor when a capture doesn\'t match, instead of a substring, m.captures contains nothing in that position, and m.offsets has a zero offset (recall that indices in Julia are 1-based, so a zero offset into a string is invalid). Here is a pair of somewhat contrived examples:julia> m = match(r\"(a|b)(c)?(d)\", \"acd\")\nRegexMatch(\"acd\", 1=\"a\", 2=\"c\", 3=\"d\")\n\njulia> m.match\n\"acd\"\n\njulia> m.captures\n3-element Array{Union{SubString{String}, Void},1}:\n \"a\"\n \"c\"\n \"d\"\n\njulia> m.offset\n1\n\njulia> m.offsets\n3-element Array{Int64,1}:\n 1\n 2\n 3\n\njulia> m = match(r\"(a|b)(c)?(d)\", \"ad\")\nRegexMatch(\"ad\", 1=\"a\", 2=nothing, 3=\"d\")\n\njulia> m.match\n\"ad\"\n\njulia> m.captures\n3-element Array{Union{SubString{String}, Void},1}:\n \"a\"\n nothing\n \"d\"\n\njulia> m.offset\n1\n\njulia> m.offsets\n3-element Array{Int64,1}:\n 1\n 0\n 2It is convenient to have captures returned as an array so that one can use destructuring syntax to bind them to local variables:julia> first, second, third = m.captures; first\n\"a\"Captures can also be accessed by indexing the RegexMatch object with the number or name of the capture group:julia> m=match(r\"(?\\d+):(?\\d+)\",\"12:45\")\nRegexMatch(\"12:45\", hour=\"12\", minute=\"45\")\n\njulia> m[:minute]\n\"45\"\n\njulia> m[2]\n\"45\"Captures can be referenced in a substitution string when using replace() by using \\n to refer to the nth capture group and prefixing the substitution string with s. Capture group 0 refers to the entire match object. Named capture groups can be referenced in the substitution with g. For example:julia> replace(\"first second\", r\"(\\w+) (?\\w+)\", s\"\\g \\1\")\n\"second first\"Numbered capture groups can also be referenced as \\g for disambiguation, as in:julia> replace(\"a\", r\".\", s\"\\g<0>1\")\n\"a1\"You can modify the behavior of regular expressions by some combination of the flags i, m, s, and x after the closing double quote mark. These flags have the same meaning as they do in Perl, as explained in this excerpt from the perlre manpage:i Do case-insensitive pattern matching.\n\n If locale matching rules are in effect, the case map is taken\n from the current locale for code points less than 255, and\n from Unicode rules for larger code points. However, matches\n that would cross the Unicode rules/non-Unicode rules boundary\n (ords 255/256) will not succeed.\n\nm Treat string as multiple lines. That is, change \"^\" and \"$\"\n from matching the start or end of the string to matching the\n start or end of any line anywhere within the string.\n\ns Treat string as single line. That is, change \".\" to match any\n character whatsoever, even a newline, which normally it would\n not match.\n\n Used together, as r\"\"ms, they let the \".\" match any character\n whatsoever, while still allowing \"^\" and \"$\" to match,\n respectively, just after and just before newlines within the\n string.\n\nx Tells the regular expression parser to ignore most whitespace\n that is neither backslashed nor within a character class. You\n can use this to break up your regular expression into\n (slightly) more readable parts. The \'#\' character is also\n treated as a metacharacter introducing a comment, just as in\n ordinary code.For example, the following regex has all three flags turned on:julia> r\"a+.*b+.*?d$\"ism\nr\"a+.*b+.*?d$\"ims\n\njulia> match(r\"a+.*b+.*?d$\"ism, \"Goodbye,\\nOh, angry,\\nBad world\\n\")\nRegexMatch(\"angry,\\nBad world\")Triple-quoted regex strings, of the form r\"\"\"...\"\"\", are also supported (and may be convenient for regular expressions containing quotation marks or newlines)." -}, - -{ - "location": "manual/strings.html#man-byte-array-literals-1", - "page": "Strings", - "title": "Byte Array Literals", - "category": "section", - "text": "Another useful non-standard string literal is the byte-array string literal: b\"...\". This form lets you use string notation to express literal byte arrays – i.e. arrays of UInt8 values. The rules for byte array literals are the following:ASCII characters and ASCII escapes produce a single byte.\n\\x and octal escape sequences produce the byte corresponding to the escape value.\nUnicode escape sequences produce a sequence of bytes encoding that code point in UTF-8.There is some overlap between these rules since the behavior of \\x and octal escapes less than 0x80 (128) are covered by both of the first two rules, but here these rules agree. Together, these rules allow one to easily use ASCII characters, arbitrary byte values, and UTF-8 sequences to produce arrays of bytes. Here is an example using all three:julia> b\"DATA\\xff\\u2200\"\n8-element Array{UInt8,1}:\n 0x44\n 0x41\n 0x54\n 0x41\n 0xff\n 0xe2\n 0x88\n 0x80The ASCII string \"DATA\" corresponds to the bytes 68, 65, 84, 65. \\xff produces the single byte 255. The Unicode escape \\u2200 is encoded in UTF-8 as the three bytes 226, 136, 128. Note that the resulting byte array does not correspond to a valid UTF-8 string – if you try to use this as a regular string literal, you will get a syntax error:julia> \"DATA\\xff\\u2200\"\nERROR: syntax: invalid UTF-8 sequenceAlso observe the significant distinction between \\xff and \\uff: the former escape sequence encodes the byte 255, whereas the latter escape sequence represents the code point 255, which is encoded as two bytes in UTF-8:julia> b\"\\xff\"\n1-element Array{UInt8,1}:\n 0xff\n\njulia> b\"\\uff\"\n2-element Array{UInt8,1}:\n 0xc3\n 0xbfIn character literals, this distinction is glossed over and \\xff is allowed to represent the code point 255, because characters always represent code points. In strings, however, \\x escapes always represent bytes, not code points, whereas \\u and \\U escapes always represent code points, which are encoded in one or more bytes. For code points less than \\u80, it happens that the UTF-8 encoding of each code point is just the single byte produced by the corresponding \\x escape, so the distinction can safely be ignored. For the escapes \\x80 through \\xff as compared to \\u80 through \\uff, however, there is a major difference: the former escapes all encode single bytes, which – unless followed by very specific continuation bytes – do not form valid UTF-8 data, whereas the latter escapes all represent Unicode code points with two-byte encodings.If this is all extremely confusing, try reading \"The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets\". It\'s an excellent introduction to Unicode and UTF-8, and may help alleviate some confusion regarding the matter." -}, - -{ - "location": "manual/strings.html#man-version-number-literals-1", - "page": "Strings", - "title": "Version Number Literals", - "category": "section", - "text": "Version numbers can easily be expressed with non-standard string literals of the form v\"...\". Version number literals create VersionNumber objects which follow the specifications of semantic versioning, and therefore are composed of major, minor and patch numeric values, followed by pre-release and build alpha-numeric annotations. For example, v\"0.2.1-rc1+win64\" is broken into major version 0, minor version 2, patch version 1, pre-release rc1 and build win64. When entering a version literal, everything except the major version number is optional, therefore e.g. v\"0.2\" is equivalent to v\"0.2.0\" (with empty pre-release/build annotations), v\"2\" is equivalent to v\"2.0.0\", and so on.VersionNumber objects are mostly useful to easily and correctly compare two (or more) versions. For example, the constant VERSION holds Julia version number as a VersionNumber object, and therefore one can define some version-specific behavior using simple statements as:if v\"0.2\" <= VERSION < v\"0.3-\"\n # do something specific to 0.2 release series\nendNote that in the above example the non-standard version number v\"0.3-\" is used, with a trailing -: this notation is a Julia extension of the standard, and it\'s used to indicate a version which is lower than any 0.3 release, including all of its pre-releases. So in the above example the code would only run with stable 0.2 versions, and exclude such versions as v\"0.3.0-rc1\". In order to also allow for unstable (i.e. pre-release) 0.2 versions, the lower bound check should be modified like this: v\"0.2-\" <= VERSION.Another non-standard version specification extension allows one to use a trailing + to express an upper limit on build versions, e.g. VERSION > v\"0.2-rc1+\" can be used to mean any version above 0.2-rc1 and any of its builds: it will return false for version v\"0.2-rc1+win64\" and true for v\"0.2-rc2\".It is good practice to use such special versions in comparisons (particularly, the trailing - should always be used on upper bounds unless there\'s a good reason not to), but they must not be used as the actual version number of anything, as they are invalid in the semantic versioning scheme.Besides being used for the VERSION constant, VersionNumber objects are widely used in the Pkg module, to specify packages versions and their dependencies." -}, - -{ - "location": "manual/strings.html#man-raw-string-literals-1", - "page": "Strings", - "title": "Raw String Literals", - "category": "section", - "text": "Raw strings without interpolation or unescaping can be expressed with non-standard string literals of the form raw\"...\". Raw string literals create ordinary String objects which contain the enclosed contents exactly as entered with no interpolation or unescaping. This is useful for strings which contain code or markup in other languages which use $ or \\ as special characters. The exception is quotation marks that still must be escaped, e.g. raw\"\\\"\" is equivalent to \"\\\"\"." -}, - -{ - "location": "manual/functions.html#", - "page": "Functions", - "title": "Functions", - "category": "page", - "text": "" -}, - -{ - "location": "manual/functions.html#man-functions-1", - "page": "Functions", - "title": "Functions", - "category": "section", - "text": "In Julia, a function is an object that maps a tuple of argument values to a return value. Julia functions are not pure mathematical functions, in the sense that functions can alter and be affected by the global state of the program. The basic syntax for defining functions in Julia is:julia> function f(x,y)\n x + y\n end\nf (generic function with 1 method)There is a second, more terse syntax for defining a function in Julia. The traditional function declaration syntax demonstrated above is equivalent to the following compact \"assignment form\":julia> f(x,y) = x + y\nf (generic function with 1 method)In the assignment form, the body of the function must be a single expression, although it can be a compound expression (see Compound Expressions). Short, simple function definitions are common in Julia. The short function syntax is accordingly quite idiomatic, considerably reducing both typing and visual noise.A function is called using the traditional parenthesis syntax:julia> f(2,3)\n5Without parentheses, the expression f refers to the function object, and can be passed around like any value:julia> g = f;\n\njulia> g(2,3)\n5As with variables, Unicode can also be used for function names:julia> ∑(x,y) = x + y\n∑ (generic function with 1 method)\n\njulia> ∑(2, 3)\n5" -}, - -{ - "location": "manual/functions.html#Argument-Passing-Behavior-1", - "page": "Functions", - "title": "Argument Passing Behavior", - "category": "section", - "text": "Julia function arguments follow a convention sometimes called \"pass-by-sharing\", which means that values are not copied when they are passed to functions. Function arguments themselves act as new variable bindings (new locations that can refer to values), but the values they refer to are identical to the passed values. Modifications to mutable values (such as Arrays) made within a function will be visible to the caller. This is the same behavior found in Scheme, most Lisps, Python, Ruby and Perl, among other dynamic languages." -}, - -{ - "location": "manual/functions.html#The-return-Keyword-1", - "page": "Functions", - "title": "The return Keyword", - "category": "section", - "text": "The value returned by a function is the value of the last expression evaluated, which, by default, is the last expression in the body of the function definition. In the example function, f, from the previous section this is the value of the expression x + y. As in C and most other imperative or functional languages, the return keyword causes a function to return immediately, providing an expression whose value is returned:function g(x,y)\n return x * y\n x + y\nendSince function definitions can be entered into interactive sessions, it is easy to compare these definitions:julia> f(x,y) = x + y\nf (generic function with 1 method)\n\njulia> function g(x,y)\n return x * y\n x + y\n end\ng (generic function with 1 method)\n\njulia> f(2,3)\n5\n\njulia> g(2,3)\n6Of course, in a purely linear function body like g, the usage of return is pointless since the expression x + y is never evaluated and we could simply make x * y the last expression in the function and omit the return. In conjunction with other control flow, however, return is of real use. Here, for example, is a function that computes the hypotenuse length of a right triangle with sides of length x and y, avoiding overflow:julia> function hypot(x,y)\n x = abs(x)\n y = abs(y)\n if x > y\n r = y/x\n return x*sqrt(1+r*r)\n end\n if y == 0\n return zero(x)\n end\n r = x/y\n return y*sqrt(1+r*r)\n end\nhypot (generic function with 1 method)\n\njulia> hypot(3, 4)\n5.0There are three possible points of return from this function, returning the values of three different expressions, depending on the values of x and y. The return on the last line could be omitted since it is the last expression." -}, - -{ - "location": "manual/functions.html#Operators-Are-Functions-1", - "page": "Functions", - "title": "Operators Are Functions", - "category": "section", - "text": "In Julia, most operators are just functions with support for special syntax. (The exceptions are operators with special evaluation semantics like && and ||. These operators cannot be functions since Short-Circuit Evaluation requires that their operands are not evaluated before evaluation of the operator.) Accordingly, you can also apply them using parenthesized argument lists, just as you would any other function:julia> 1 + 2 + 3\n6\n\njulia> +(1,2,3)\n6The infix form is exactly equivalent to the function application form – in fact the former is parsed to produce the function call internally. This also means that you can assign and pass around operators such as +() and *() just like you would with other function values:julia> f = +;\n\njulia> f(1,2,3)\n6Under the name f, the function does not support infix notation, however." -}, - -{ - "location": "manual/functions.html#Operators-With-Special-Names-1", - "page": "Functions", - "title": "Operators With Special Names", - "category": "section", - "text": "A few special expressions correspond to calls to functions with non-obvious names. These are:Expression Calls\n[A B C ...] hcat()\n[A; B; C; ...] vcat()\n[A B; C D; ...] hvcat()\nA\' ctranspose()\nA.\' transpose()\n1:n colon()\nA[i] getindex()\nA[i]=x setindex!()These functions are included in the Base.Operators module even though they do not have operator-like names." -}, - -{ - "location": "manual/functions.html#man-anonymous-functions-1", - "page": "Functions", - "title": "Anonymous Functions", - "category": "section", - "text": "Functions in Julia are first-class objects: they can be assigned to variables, and called using the standard function call syntax from the variable they have been assigned to. They can be used as arguments, and they can be returned as values. They can also be created anonymously, without being given a name, using either of these syntaxes:julia> x -> x^2 + 2x - 1\n(::#1) (generic function with 1 method)\n\njulia> function (x)\n x^2 + 2x - 1\n end\n(::#3) (generic function with 1 method)This creates a function taking one argument x and returning the value of the polynomial x^2 + 2x - 1 at that value. Notice that the result is a generic function, but with a compiler-generated name based on consecutive numbering.The primary use for anonymous functions is passing them to functions which take other functions as arguments. A classic example is map(), which applies a function to each value of an array and returns a new array containing the resulting values:julia> map(round, [1.2,3.5,1.7])\n3-element Array{Float64,1}:\n 1.0\n 4.0\n 2.0This is fine if a named function effecting the transform one wants already exists to pass as the first argument to map(). Often, however, a ready-to-use, named function does not exist. In these situations, the anonymous function construct allows easy creation of a single-use function object without needing a name:julia> map(x -> x^2 + 2x - 1, [1,3,-1])\n3-element Array{Int64,1}:\n 2\n 14\n -2An anonymous function accepting multiple arguments can be written using the syntax (x,y,z)->2x+y-z. A zero-argument anonymous function is written as ()->3. The idea of a function with no arguments may seem strange, but is useful for \"delaying\" a computation. In this usage, a block of code is wrapped in a zero-argument function, which is later invoked by calling it as f()." -}, - -{ - "location": "manual/functions.html#Multiple-Return-Values-1", - "page": "Functions", - "title": "Multiple Return Values", - "category": "section", - "text": "In Julia, one returns a tuple of values to simulate returning multiple values. However, tuples can be created and destructured without needing parentheses, thereby providing an illusion that multiple values are being returned, rather than a single tuple value. For example, the following function returns a pair of values:julia> function foo(a,b)\n a+b, a*b\n end\nfoo (generic function with 1 method)If you call it in an interactive session without assigning the return value anywhere, you will see the tuple returned:julia> foo(2,3)\n(5, 6)A typical usage of such a pair of return values, however, extracts each value into a variable. Julia supports simple tuple \"destructuring\" that facilitates this:julia> x, y = foo(2,3)\n(5, 6)\n\njulia> x\n5\n\njulia> y\n6You can also return multiple values via an explicit usage of the return keyword:function foo(a,b)\n return a+b, a*b\nendThis has the exact same effect as the previous definition of foo." -}, - -{ - "location": "manual/functions.html#Varargs-Functions-1", - "page": "Functions", - "title": "Varargs Functions", - "category": "section", - "text": "It is often convenient to be able to write functions taking an arbitrary number of arguments. Such functions are traditionally known as \"varargs\" functions, which is short for \"variable number of arguments\". You can define a varargs function by following the last argument with an ellipsis:julia> bar(a,b,x...) = (a,b,x)\nbar (generic function with 1 method)The variables a and b are bound to the first two argument values as usual, and the variable x is bound to an iterable collection of the zero or more values passed to bar after its first two arguments:julia> bar(1,2)\n(1, 2, ())\n\njulia> bar(1,2,3)\n(1, 2, (3,))\n\njulia> bar(1, 2, 3, 4)\n(1, 2, (3, 4))\n\njulia> bar(1,2,3,4,5,6)\n(1, 2, (3, 4, 5, 6))In all these cases, x is bound to a tuple of the trailing values passed to bar.It is possible to constrain the number of values passed as a variable argument; this will be discussed later in Parametrically-constrained Varargs methods.On the flip side, it is often handy to \"splice\" the values contained in an iterable collection into a function call as individual arguments. To do this, one also uses ... but in the function call instead:julia> x = (3, 4)\n(3, 4)\n\njulia> bar(1,2,x...)\n(1, 2, (3, 4))In this case a tuple of values is spliced into a varargs call precisely where the variable number of arguments go. This need not be the case, however:julia> x = (2, 3, 4)\n(2, 3, 4)\n\njulia> bar(1,x...)\n(1, 2, (3, 4))\n\njulia> x = (1, 2, 3, 4)\n(1, 2, 3, 4)\n\njulia> bar(x...)\n(1, 2, (3, 4))Furthermore, the iterable object spliced into a function call need not be a tuple:julia> x = [3,4]\n2-element Array{Int64,1}:\n 3\n 4\n\njulia> bar(1,2,x...)\n(1, 2, (3, 4))\n\njulia> x = [1,2,3,4]\n4-element Array{Int64,1}:\n 1\n 2\n 3\n 4\n\njulia> bar(x...)\n(1, 2, (3, 4))Also, the function that arguments are spliced into need not be a varargs function (although it often is):julia> baz(a,b) = a + b;\n\njulia> args = [1,2]\n2-element Array{Int64,1}:\n 1\n 2\n\njulia> baz(args...)\n3\n\njulia> args = [1,2,3]\n3-element Array{Int64,1}:\n 1\n 2\n 3\n\njulia> baz(args...)\nERROR: MethodError: no method matching baz(::Int64, ::Int64, ::Int64)\nClosest candidates are:\n baz(::Any, ::Any) at none:1As you can see, if the wrong number of elements are in the spliced container, then the function call will fail, just as it would if too many arguments were given explicitly." -}, - -{ - "location": "manual/functions.html#Optional-Arguments-1", - "page": "Functions", - "title": "Optional Arguments", - "category": "section", - "text": "In many cases, function arguments have sensible default values and therefore might not need to be passed explicitly in every call. For example, the library function parse(T, num, base) interprets a string as a number in some base. The base argument defaults to 10. This behavior can be expressed concisely as:function parse(T, num, base=10)\n ###\nendWith this definition, the function can be called with either two or three arguments, and 10 is automatically passed when a third argument is not specified:julia> parse(Int,\"12\",10)\n12\n\njulia> parse(Int,\"12\",3)\n5\n\njulia> parse(Int,\"12\")\n12Optional arguments are actually just a convenient syntax for writing multiple method definitions with different numbers of arguments (see Note on Optional and keyword Arguments)." -}, - -{ - "location": "manual/functions.html#Keyword-Arguments-1", - "page": "Functions", - "title": "Keyword Arguments", - "category": "section", - "text": "Some functions need a large number of arguments, or have a large number of behaviors. Remembering how to call such functions can be difficult. Keyword arguments can make these complex interfaces easier to use and extend by allowing arguments to be identified by name instead of only by position.For example, consider a function plot that plots a line. This function might have many options, for controlling line style, width, color, and so on. If it accepts keyword arguments, a possible call might look like plot(x, y, width=2), where we have chosen to specify only line width. Notice that this serves two purposes. The call is easier to read, since we can label an argument with its meaning. It also becomes possible to pass any subset of a large number of arguments, in any order.Functions with keyword arguments are defined using a semicolon in the signature:function plot(x, y; style=\"solid\", width=1, color=\"black\")\n ###\nendWhen the function is called, the semicolon is optional: one can either call plot(x, y, width=2) or plot(x, y; width=2), but the former style is more common. An explicit semicolon is required only for passing varargs or computed keywords as described below.Keyword argument default values are evaluated only when necessary (when a corresponding keyword argument is not passed), and in left-to-right order. Therefore default expressions may refer to prior keyword arguments.The types of keyword arguments can be made explicit as follows:function f(;x::Int64=1)\n ###\nendExtra keyword arguments can be collected using ..., as in varargs functions:function f(x; y=0, kwargs...)\n ###\nendInside f, kwargs will be a collection of (key,value) tuples, where each key is a symbol. Such collections can be passed as keyword arguments using a semicolon in a call, e.g. f(x, z=1; kwargs...). Dictionaries can also be used for this purpose.One can also pass (key,value) tuples, or any iterable expression (such as a => pair) that can be assigned to such a tuple, explicitly after a semicolon. For example, plot(x, y; (:width,2)) and plot(x, y; :width => 2) are equivalent to plot(x, y, width=2). This is useful in situations where the keyword name is computed at runtime.The nature of keyword arguments makes it possible to specify the same argument more than once. For example, in the call plot(x, y; options..., width=2) it is possible that the options structure also contains a value for width. In such a case the rightmost occurrence takes precedence; in this example, width is certain to have the value 2." -}, - -{ - "location": "manual/functions.html#Evaluation-Scope-of-Default-Values-1", - "page": "Functions", - "title": "Evaluation Scope of Default Values", - "category": "section", - "text": "Optional and keyword arguments differ slightly in how their default values are evaluated. When optional argument default expressions are evaluated, only previous arguments are in scope. In contrast, all the arguments are in scope when keyword arguments default expressions are evaluated. For example, given this definition:function f(x, a=b, b=1)\n ###\nendthe b in a=b refers to a b in an outer scope, not the subsequent argument b. However, if a and b were keyword arguments instead, then both would be created in the same scope and the b in a=b would refer to the subsequent argument b (shadowing any b in an outer scope), which would result in an undefined variable error (since the default expressions are evaluated left-to-right, and b has not been assigned yet)." -}, - -{ - "location": "manual/functions.html#Do-Block-Syntax-for-Function-Arguments-1", - "page": "Functions", - "title": "Do-Block Syntax for Function Arguments", - "category": "section", - "text": "Passing functions as arguments to other functions is a powerful technique, but the syntax for it is not always convenient. Such calls are especially awkward to write when the function argument requires multiple lines. As an example, consider calling map() on a function with several cases:map(x->begin\n if x < 0 && iseven(x)\n return 0\n elseif x == 0\n return 1\n else\n return x\n end\n end,\n [A, B, C])Julia provides a reserved word do for rewriting this code more clearly:map([A, B, C]) do x\n if x < 0 && iseven(x)\n return 0\n elseif x == 0\n return 1\n else\n return x\n end\nendThe do x syntax creates an anonymous function with argument x and passes it as the first argument to map(). Similarly, do a,b would create a two-argument anonymous function, and a plain do would declare that what follows is an anonymous function of the form () -> ....How these arguments are initialized depends on the \"outer\" function; here, map() will sequentially set x to A, B, C, calling the anonymous function on each, just as would happen in the syntax map(func, [A, B, C]).This syntax makes it easier to use functions to effectively extend the language, since calls look like normal code blocks. There are many possible uses quite different from map(), such as managing system state. For example, there is a version of open() that runs code ensuring that the opened file is eventually closed:open(\"outfile\", \"w\") do io\n write(io, data)\nendThis is accomplished by the following definition:function open(f::Function, args...)\n io = open(args...)\n try\n f(io)\n finally\n close(io)\n end\nendHere, open() first opens the file for writing and then passes the resulting output stream to the anonymous function you defined in the do ... end block. After your function exits, open() will make sure that the stream is properly closed, regardless of whether your function exited normally or threw an exception. (The try/finally construct will be described in Control Flow.)With the do block syntax, it helps to check the documentation or implementation to know how the arguments of the user function are initialized." -}, - -{ - "location": "manual/functions.html#man-vectorized-1", - "page": "Functions", - "title": "Dot Syntax for Vectorizing Functions", - "category": "section", - "text": "In technical-computing languages, it is common to have \"vectorized\" versions of functions, which simply apply a given function f(x) to each element of an array A to yield a new array via f(A). This kind of syntax is convenient for data processing, but in other languages vectorization is also often required for performance: if loops are slow, the \"vectorized\" version of a function can call fast library code written in a low-level language. In Julia, vectorized functions are not required for performance, and indeed it is often beneficial to write your own loops (see Performance Tips), but they can still be convenient. Therefore, any Julia function f can be applied elementwise to any array (or other collection) with the syntax f.(A). For example sin can be applied to all elements in the vector A, like so:julia> A = [1.0, 2.0, 3.0]\n3-element Array{Float64,1}:\n 1.0\n 2.0\n 3.0\n\njulia> sin.(A)\n3-element Array{Float64,1}:\n 0.841471\n 0.909297\n 0.14112Of course, you can omit the dot if you write a specialized \"vector\" method of f, e.g. via f(A::AbstractArray) = map(f, A), and this is just as efficient as f.(A). But that approach requires you to decide in advance which functions you want to vectorize.More generally, f.(args...) is actually equivalent to broadcast(f, args...), which allows you to operate on multiple arrays (even of different shapes), or a mix of arrays and scalars (see Broadcasting). For example, if you have f(x,y) = 3x + 4y, then f.(pi,A) will return a new array consisting of f(pi,a) for each a in A, and f.(vector1,vector2) will return a new vector consisting of f(vector1[i],vector2[i]) for each index i (throwing an exception if the vectors have different length).julia> f(x,y) = 3x + 4y;\n\njulia> A = [1.0, 2.0, 3.0];\n\njulia> B = [4.0, 5.0, 6.0];\n\njulia> f.(pi, A)\n3-element Array{Float64,1}:\n 13.4248\n 17.4248\n 21.4248\n\njulia> f.(A, B)\n3-element Array{Float64,1}:\n 19.0\n 26.0\n 33.0Moreover, nested f.(args...) calls are fused into a single broadcast loop. For example, sin.(cos.(X)) is equivalent to broadcast(x -> sin(cos(x)), X), similar to [sin(cos(x)) for x in X]: there is only a single loop over X, and a single array is allocated for the result. [In contrast, sin(cos(X)) in a typical \"vectorized\" language would first allocate one temporary array for tmp=cos(X), and then compute sin(tmp) in a separate loop, allocating a second array.] This loop fusion is not a compiler optimization that may or may not occur, it is a syntactic guarantee whenever nested f.(args...) calls are encountered. Technically, the fusion stops as soon as a \"non-dot\" function call is encountered; for example, in sin.(sort(cos.(X))) the sin and cos loops cannot be merged because of the intervening sort function.Finally, the maximum efficiency is typically achieved when the output array of a vectorized operation is pre-allocated, so that repeated calls do not allocate new arrays over and over again for the results (Pre-allocating outputs:). A convenient syntax for this is X .= ..., which is equivalent to broadcast!(identity, X, ...) except that, as above, the broadcast! loop is fused with any nested \"dot\" calls. For example, X .= sin.(Y) is equivalent to broadcast!(sin, X, Y), overwriting X with sin.(Y) in-place. If the left-hand side is an array-indexing expression, e.g. X[2:end] .= sin.(Y), then it translates to broadcast! on a view, e.g. broadcast!(sin, view(X, 2:endof(X)), Y), so that the left-hand side is updated in-place.Since adding dots to many operations and function calls in an expression can be tedious and lead to code that is difficult to read, the macro @. is provided to convert every function call, operation, and assignment in an expression into the \"dotted\" version.julia> Y = [1.0, 2.0, 3.0, 4.0];\n\njulia> X = similar(Y); # pre-allocate output array\n\njulia> @. X = sin(cos(Y)) # equivalent to X .= sin.(cos.(Y))\n4-element Array{Float64,1}:\n 0.514395\n -0.404239\n -0.836022\n -0.608083Binary (or unary) operators like .+ are handled with the same mechanism: they are equivalent to broadcast calls and are fused with other nested \"dot\" calls. X .+= Y etcetera is equivalent to X .= X .+ Y and results in a fused in-place assignment; see also dot operators." -}, - -{ - "location": "manual/functions.html#Further-Reading-1", - "page": "Functions", - "title": "Further Reading", - "category": "section", - "text": "We should mention here that this is far from a complete picture of defining functions. Julia has a sophisticated type system and allows multiple dispatch on argument types. None of the examples given here provide any type annotations on their arguments, meaning that they are applicable to all types of arguments. The type system is described in Types and defining a function in terms of methods chosen by multiple dispatch on run-time argument types is described in Methods." -}, - -{ - "location": "manual/control-flow.html#", - "page": "Control Flow", - "title": "Control Flow", - "category": "page", - "text": "" -}, - -{ - "location": "manual/control-flow.html#Control-Flow-1", - "page": "Control Flow", - "title": "Control Flow", - "category": "section", - "text": "Julia provides a variety of control flow constructs:Compound Expressions: begin and (;).\nConditional Evaluation: if-elseif-else and ?: (ternary operator).\nShort-Circuit Evaluation: &&, || and chained comparisons.\nRepeated Evaluation: Loops: while and for.\nException Handling: try-catch, error() and throw().\nTasks (aka Coroutines): yieldto().The first five control flow mechanisms are standard to high-level programming languages. Tasks are not so standard: they provide non-local control flow, making it possible to switch between temporarily-suspended computations. This is a powerful construct: both exception handling and cooperative multitasking are implemented in Julia using tasks. Everyday programming requires no direct usage of tasks, but certain problems can be solved much more easily by using tasks." -}, - -{ - "location": "manual/control-flow.html#man-compound-expressions-1", - "page": "Control Flow", - "title": "Compound Expressions", - "category": "section", - "text": "Sometimes it is convenient to have a single expression which evaluates several subexpressions in order, returning the value of the last subexpression as its value. There are two Julia constructs that accomplish this: begin blocks and (;) chains. The value of both compound expression constructs is that of the last subexpression. Here\'s an example of a begin block:julia> z = begin\n x = 1\n y = 2\n x + y\n end\n3Since these are fairly small, simple expressions, they could easily be placed onto a single line, which is where the (;) chain syntax comes in handy:julia> z = (x = 1; y = 2; x + y)\n3This syntax is particularly useful with the terse single-line function definition form introduced in Functions. Although it is typical, there is no requirement that begin blocks be multiline or that (;) chains be single-line:julia> begin x = 1; y = 2; x + y end\n3\n\njulia> (x = 1;\n y = 2;\n x + y)\n3" -}, - -{ - "location": "manual/control-flow.html#man-conditional-evaluation-1", - "page": "Control Flow", - "title": "Conditional Evaluation", - "category": "section", - "text": "Conditional evaluation allows portions of code to be evaluated or not evaluated depending on the value of a boolean expression. Here is the anatomy of the if-elseif-else conditional syntax:if x < y\n println(\"x is less than y\")\nelseif x > y\n println(\"x is greater than y\")\nelse\n println(\"x is equal to y\")\nendIf the condition expression x < y is true, then the corresponding block is evaluated; otherwise the condition expression x > y is evaluated, and if it is true, the corresponding block is evaluated; if neither expression is true, the else block is evaluated. Here it is in action:julia> function test(x, y)\n if x < y\n println(\"x is less than y\")\n elseif x > y\n println(\"x is greater than y\")\n else\n println(\"x is equal to y\")\n end\n end\ntest (generic function with 1 method)\n\njulia> test(1, 2)\nx is less than y\n\njulia> test(2, 1)\nx is greater than y\n\njulia> test(1, 1)\nx is equal to yThe elseif and else blocks are optional, and as many elseif blocks as desired can be used. The condition expressions in the if-elseif-else construct are evaluated until the first one evaluates to true, after which the associated block is evaluated, and no further condition expressions or blocks are evaluated.if blocks are \"leaky\", i.e. they do not introduce a local scope. This means that new variables defined inside the if clauses can be used after the if block, even if they weren\'t defined before. So, we could have defined the test function above asjulia> function test(x,y)\n if x < y\n relation = \"less than\"\n elseif x == y\n relation = \"equal to\"\n else\n relation = \"greater than\"\n end\n println(\"x is \", relation, \" y.\")\n end\ntest (generic function with 1 method)\n\njulia> test(2, 1)\nx is greater than y.The variable relation is declared inside the if block, but used outside. However, when depending on this behavior, make sure all possible code paths define a value for the variable. The following change to the above function results in a runtime errorjulia> function test(x,y)\n if x < y\n relation = \"less than\"\n elseif x == y\n relation = \"equal to\"\n end\n println(\"x is \", relation, \" y.\")\n end\ntest (generic function with 1 method)\n\njulia> test(1,2)\nx is less than y.\n\njulia> test(2,1)\nERROR: UndefVarError: relation not defined\nStacktrace:\n [1] test(::Int64, ::Int64) at ./none:7if blocks also return a value, which may seem unintuitive to users coming from many other languages. This value is simply the return value of the last executed statement in the branch that was chosen, sojulia> x = 3\n3\n\njulia> if x > 0\n \"positive!\"\n else\n \"negative...\"\n end\n\"positive!\"Note that very short conditional statements (one-liners) are frequently expressed using Short-Circuit Evaluation in Julia, as outlined in the next section.Unlike C, MATLAB, Perl, Python, and Ruby – but like Java, and a few other stricter, typed languages – it is an error if the value of a conditional expression is anything but true or false:julia> if 1\n println(\"true\")\n end\nERROR: TypeError: non-boolean (Int64) used in boolean contextThis error indicates that the conditional was of the wrong type: Int64 rather than the required Bool.The so-called \"ternary operator\", ?:, is closely related to the if-elseif-else syntax, but is used where a conditional choice between single expression values is required, as opposed to conditional execution of longer blocks of code. It gets its name from being the only operator in most languages taking three operands:a ? b : cThe expression a, before the ?, is a condition expression, and the ternary operation evaluates the expression b, before the :, if the condition a is true or the expression c, after the :, if it is false.The easiest way to understand this behavior is to see an example. In the previous example, the println call is shared by all three branches: the only real choice is which literal string to print. This could be written more concisely using the ternary operator. For the sake of clarity, let\'s try a two-way version first:julia> x = 1; y = 2;\n\njulia> println(x < y ? \"less than\" : \"not less than\")\nless than\n\njulia> x = 1; y = 0;\n\njulia> println(x < y ? \"less than\" : \"not less than\")\nnot less thanIf the expression x < y is true, the entire ternary operator expression evaluates to the string \"less than\" and otherwise it evaluates to the string \"not less than\". The original three-way example requires chaining multiple uses of the ternary operator together:julia> test(x, y) = println(x < y ? \"x is less than y\" :\n x > y ? \"x is greater than y\" : \"x is equal to y\")\ntest (generic function with 1 method)\n\njulia> test(1, 2)\nx is less than y\n\njulia> test(2, 1)\nx is greater than y\n\njulia> test(1, 1)\nx is equal to yTo facilitate chaining, the operator associates from right to left.It is significant that like if-elseif-else, the expressions before and after the : are only evaluated if the condition expression evaluates to true or false, respectively:julia> v(x) = (println(x); x)\nv (generic function with 1 method)\n\njulia> 1 < 2 ? v(\"yes\") : v(\"no\")\nyes\n\"yes\"\n\njulia> 1 > 2 ? v(\"yes\") : v(\"no\")\nno\n\"no\"" -}, - -{ - "location": "manual/control-flow.html#Short-Circuit-Evaluation-1", - "page": "Control Flow", - "title": "Short-Circuit Evaluation", - "category": "section", - "text": "Short-circuit evaluation is quite similar to conditional evaluation. The behavior is found in most imperative programming languages having the && and || boolean operators: in a series of boolean expressions connected by these operators, only the minimum number of expressions are evaluated as are necessary to determine the final boolean value of the entire chain. Explicitly, this means that:In the expression a && b, the subexpression b is only evaluated if a evaluates to true.\nIn the expression a || b, the subexpression b is only evaluated if a evaluates to false.The reasoning is that a && b must be false if a is false, regardless of the value of b, and likewise, the value of a || b must be true if a is true, regardless of the value of b. Both && and || associate to the right, but && has higher precedence than || does. It\'s easy to experiment with this behavior:julia> t(x) = (println(x); true)\nt (generic function with 1 method)\n\njulia> f(x) = (println(x); false)\nf (generic function with 1 method)\n\njulia> t(1) && t(2)\n1\n2\ntrue\n\njulia> t(1) && f(2)\n1\n2\nfalse\n\njulia> f(1) && t(2)\n1\nfalse\n\njulia> f(1) && f(2)\n1\nfalse\n\njulia> t(1) || t(2)\n1\ntrue\n\njulia> t(1) || f(2)\n1\ntrue\n\njulia> f(1) || t(2)\n1\n2\ntrue\n\njulia> f(1) || f(2)\n1\n2\nfalseYou can easily experiment in the same way with the associativity and precedence of various combinations of && and || operators.This behavior is frequently used in Julia to form an alternative to very short if statements. Instead of if end, one can write && (which could be read as: and then ). Similarly, instead of if ! end, one can write || (which could be read as: or else ).For example, a recursive factorial routine could be defined like this:julia> function fact(n::Int)\n n >= 0 || error(\"n must be non-negative\")\n n == 0 && return 1\n n * fact(n-1)\n end\nfact (generic function with 1 method)\n\njulia> fact(5)\n120\n\njulia> fact(0)\n1\n\njulia> fact(-1)\nERROR: n must be non-negative\nStacktrace:\n [1] fact(::Int64) at ./none:2Boolean operations without short-circuit evaluation can be done with the bitwise boolean operators introduced in Mathematical Operations and Elementary Functions: & and |. These are normal functions, which happen to support infix operator syntax, but always evaluate their arguments:julia> f(1) & t(2)\n1\n2\nfalse\n\njulia> t(1) | t(2)\n1\n2\ntrueJust like condition expressions used in if, elseif or the ternary operator, the operands of && or || must be boolean values (true or false). Using a non-boolean value anywhere except for the last entry in a conditional chain is an error:julia> 1 && true\nERROR: TypeError: non-boolean (Int64) used in boolean contextOn the other hand, any type of expression can be used at the end of a conditional chain. It will be evaluated and returned depending on the preceding conditionals:julia> true && (x = (1, 2, 3))\n(1, 2, 3)\n\njulia> false && (x = (1, 2, 3))\nfalse" -}, - -{ - "location": "manual/control-flow.html#man-loops-1", - "page": "Control Flow", - "title": "Repeated Evaluation: Loops", - "category": "section", - "text": "There are two constructs for repeated evaluation of expressions: the while loop and the for loop. Here is an example of a while loop:julia> i = 1;\n\njulia> while i <= 5\n println(i)\n i += 1\n end\n1\n2\n3\n4\n5The while loop evaluates the condition expression (i <= 5 in this case), and as long it remains true, keeps also evaluating the body of the while loop. If the condition expression is false when the while loop is first reached, the body is never evaluated.The for loop makes common repeated evaluation idioms easier to write. Since counting up and down like the above while loop does is so common, it can be expressed more concisely with a for loop:julia> for i = 1:5\n println(i)\n end\n1\n2\n3\n4\n5Here the 1:5 is a Range object, representing the sequence of numbers 1, 2, 3, 4, 5. The for loop iterates through these values, assigning each one in turn to the variable i. One rather important distinction between the previous while loop form and the for loop form is the scope during which the variable is visible. If the variable i has not been introduced in an other scope, in the for loop form, it is visible only inside of the for loop, and not afterwards. You\'ll either need a new interactive session instance or a different variable name to test this:julia> for j = 1:5\n println(j)\n end\n1\n2\n3\n4\n5\n\njulia> j\nERROR: UndefVarError: j not definedSee Scope of Variables for a detailed explanation of variable scope and how it works in Julia.In general, the for loop construct can iterate over any container. In these cases, the alternative (but fully equivalent) keyword in or ∈ is typically used instead of =, since it makes the code read more clearly:julia> for i in [1,4,0]\n println(i)\n end\n1\n4\n0\n\njulia> for s ∈ [\"foo\",\"bar\",\"baz\"]\n println(s)\n end\nfoo\nbar\nbazVarious types of iterable containers will be introduced and discussed in later sections of the manual (see, e.g., Multi-dimensional Arrays).It is sometimes convenient to terminate the repetition of a while before the test condition is falsified or stop iterating in a for loop before the end of the iterable object is reached. This can be accomplished with the break keyword:julia> i = 1;\n\njulia> while true\n println(i)\n if i >= 5\n break\n end\n i += 1\n end\n1\n2\n3\n4\n5\n\njulia> for i = 1:1000\n println(i)\n if i >= 5\n break\n end\n end\n1\n2\n3\n4\n5Without the break keyword, the above while loop would never terminate on its own, and the for loop would iterate up to 1000. These loops are both exited early by using break.In other circumstances, it is handy to be able to stop an iteration and move on to the next one immediately. The continue keyword accomplishes this:julia> for i = 1:10\n if i % 3 != 0\n continue\n end\n println(i)\n end\n3\n6\n9This is a somewhat contrived example since we could produce the same behavior more clearly by negating the condition and placing the println call inside the if block. In realistic usage there is more code to be evaluated after the continue, and often there are multiple points from which one calls continue.Multiple nested for loops can be combined into a single outer loop, forming the cartesian product of its iterables:julia> for i = 1:2, j = 3:4\n println((i, j))\n end\n(1, 3)\n(1, 4)\n(2, 3)\n(2, 4)A break statement inside such a loop exits the entire nest of loops, not just the inner one." -}, - -{ - "location": "manual/control-flow.html#Exception-Handling-1", - "page": "Control Flow", - "title": "Exception Handling", - "category": "section", - "text": "When an unexpected condition occurs, a function may be unable to return a reasonable value to its caller. In such cases, it may be best for the exceptional condition to either terminate the program, printing a diagnostic error message, or if the programmer has provided code to handle such exceptional circumstances, allow that code to take the appropriate action." -}, - -{ - "location": "manual/control-flow.html#Built-in-Exceptions-1", - "page": "Control Flow", - "title": "Built-in Exceptions", - "category": "section", - "text": "Exceptions are thrown when an unexpected condition has occurred. The built-in Exceptions listed below all interrupt the normal flow of control.Exception\nArgumentError\nBoundsError\nCompositeException\nDivideError\nDomainError\nEOFError\nErrorException\nInexactError\nInitError\nInterruptException\nInvalidStateException\nKeyError\nLoadError\nOutOfMemoryError\nReadOnlyMemoryError\nRemoteException\nMethodError\nOverflowError\nParseError\nSystemError\nTypeError\nUndefRefError\nUndefVarError\nUnicodeErrorFor example, the sqrt() function throws a DomainError if applied to a negative real value:julia> sqrt(-1)\nERROR: DomainError:\nsqrt will only return a complex result if called with a complex argument. Try sqrt(complex(x)).\nStacktrace:\n [1] sqrt(::Int64) at ./math.jl:434You may define your own exceptions in the following way:julia> struct MyCustomException <: Exception end" -}, - -{ - "location": "manual/control-flow.html#The-[throw()](@ref)-function-1", - "page": "Control Flow", - "title": "The throw() function", - "category": "section", - "text": "Exceptions can be created explicitly with throw(). For example, a function defined only for nonnegative numbers could be written to throw() a DomainError if the argument is negative:julia> f(x) = x>=0 ? exp(-x) : throw(DomainError())\nf (generic function with 1 method)\n\njulia> f(1)\n0.36787944117144233\n\njulia> f(-1)\nERROR: DomainError:\nStacktrace:\n [1] f(::Int64) at ./none:1Note that DomainError without parentheses is not an exception, but a type of exception. It needs to be called to obtain an Exception object:julia> typeof(DomainError()) <: Exception\ntrue\n\njulia> typeof(DomainError) <: Exception\nfalseAdditionally, some exception types take one or more arguments that are used for error reporting:julia> throw(UndefVarError(:x))\nERROR: UndefVarError: x not definedThis mechanism can be implemented easily by custom exception types following the way UndefVarError is written:julia> struct MyUndefVarError <: Exception\n var::Symbol\n end\n\njulia> Base.showerror(io::IO, e::MyUndefVarError) = print(io, e.var, \" not defined\")note: Note\nWhen writing an error message, it is preferred to make the first word lowercase. For example, size(A) == size(B) || throw(DimensionMismatch(\"size of A not equal to size of B\"))is preferred oversize(A) == size(B) || throw(DimensionMismatch(\"Size of A not equal to size of B\")).However, sometimes it makes sense to keep the uppercase first letter, for instance if an argument to a function is a capital letter: size(A,1) == size(B,2) || throw(DimensionMismatch(\"A has first dimension...\"))." -}, - -{ - "location": "manual/control-flow.html#Errors-1", - "page": "Control Flow", - "title": "Errors", - "category": "section", - "text": "The error() function is used to produce an ErrorException that interrupts the normal flow of control.Suppose we want to stop execution immediately if the square root of a negative number is taken. To do this, we can define a fussy version of the sqrt() function that raises an error if its argument is negative:julia> fussy_sqrt(x) = x >= 0 ? sqrt(x) : error(\"negative x not allowed\")\nfussy_sqrt (generic function with 1 method)\n\njulia> fussy_sqrt(2)\n1.4142135623730951\n\njulia> fussy_sqrt(-1)\nERROR: negative x not allowed\nStacktrace:\n [1] fussy_sqrt(::Int64) at ./none:1If fussy_sqrt is called with a negative value from another function, instead of trying to continue execution of the calling function, it returns immediately, displaying the error message in the interactive session:julia> function verbose_fussy_sqrt(x)\n println(\"before fussy_sqrt\")\n r = fussy_sqrt(x)\n println(\"after fussy_sqrt\")\n return r\n end\nverbose_fussy_sqrt (generic function with 1 method)\n\njulia> verbose_fussy_sqrt(2)\nbefore fussy_sqrt\nafter fussy_sqrt\n1.4142135623730951\n\njulia> verbose_fussy_sqrt(-1)\nbefore fussy_sqrt\nERROR: negative x not allowed\nStacktrace:\n [1] fussy_sqrt at ./none:1 [inlined]\n [2] verbose_fussy_sqrt(::Int64) at ./none:3" -}, - -{ - "location": "manual/control-flow.html#Warnings-and-informational-messages-1", - "page": "Control Flow", - "title": "Warnings and informational messages", - "category": "section", - "text": "Julia also provides other functions that write messages to the standard error I/O, but do not throw any Exceptions and hence do not interrupt execution:julia> info(\"Hi\"); 1+1\nINFO: Hi\n2\n\njulia> warn(\"Hi\"); 1+1\nWARNING: Hi\n2\n\njulia> error(\"Hi\"); 1+1\nERROR: Hi\nStacktrace:\n [1] error(::String) at ./error.jl:21" -}, - -{ - "location": "manual/control-flow.html#The-try/catch-statement-1", - "page": "Control Flow", - "title": "The try/catch statement", - "category": "section", - "text": "The try/catch statement allows for Exceptions to be tested for. For example, a customized square root function can be written to automatically call either the real or complex square root method on demand using Exceptions :julia> f(x) = try\n sqrt(x)\n catch\n sqrt(complex(x, 0))\n end\nf (generic function with 1 method)\n\njulia> f(1)\n1.0\n\njulia> f(-1)\n0.0 + 1.0imIt is important to note that in real code computing this function, one would compare x to zero instead of catching an exception. The exception is much slower than simply comparing and branching.try/catch statements also allow the Exception to be saved in a variable. In this contrived example, the following example calculates the square root of the second element of x if x is indexable, otherwise assumes x is a real number and returns its square root:julia> sqrt_second(x) = try\n sqrt(x[2])\n catch y\n if isa(y, DomainError)\n sqrt(complex(x[2], 0))\n elseif isa(y, BoundsError)\n sqrt(x)\n end\n end\nsqrt_second (generic function with 1 method)\n\njulia> sqrt_second([1 4])\n2.0\n\njulia> sqrt_second([1 -4])\n0.0 + 2.0im\n\njulia> sqrt_second(9)\n3.0\n\njulia> sqrt_second(-9)\nERROR: DomainError:\nStacktrace:\n [1] sqrt_second(::Int64) at ./none:7Note that the symbol following catch will always be interpreted as a name for the exception, so care is needed when writing try/catch expressions on a single line. The following code will not work to return the value of x in case of an error:try bad() catch x endInstead, use a semicolon or insert a line break after catch:try bad() catch; x end\n\ntry bad()\ncatch\n x\nendThe catch clause is not strictly necessary; when omitted, the default return value is nothing.julia> try error() end # Returns nothingThe power of the try/catch construct lies in the ability to unwind a deeply nested computation immediately to a much higher level in the stack of calling functions. There are situations where no error has occurred, but the ability to unwind the stack and pass a value to a higher level is desirable. Julia provides the rethrow(), backtrace() and catch_backtrace() functions for more advanced error handling." -}, - -{ - "location": "manual/control-flow.html#finally-Clauses-1", - "page": "Control Flow", - "title": "finally Clauses", - "category": "section", - "text": "In code that performs state changes or uses resources like files, there is typically clean-up work (such as closing files) that needs to be done when the code is finished. Exceptions potentially complicate this task, since they can cause a block of code to exit before reaching its normal end. The finally keyword provides a way to run some code when a given block of code exits, regardless of how it exits.For example, here is how we can guarantee that an opened file is closed:f = open(\"file\")\ntry\n # operate on file f\nfinally\n close(f)\nendWhen control leaves the try block (for example due to a return, or just finishing normally), close(f) will be executed. If the try block exits due to an exception, the exception will continue propagating. A catch block may be combined with try and finally as well. In this case the finally block will run after catch has handled the error." -}, - -{ - "location": "manual/control-flow.html#man-tasks-1", - "page": "Control Flow", - "title": "Tasks (aka Coroutines)", - "category": "section", - "text": "Tasks are a control flow feature that allows computations to be suspended and resumed in a flexible manner. This feature is sometimes called by other names, such as symmetric coroutines, lightweight threads, cooperative multitasking, or one-shot continuations.When a piece of computing work (in practice, executing a particular function) is designated as a Task, it becomes possible to interrupt it by switching to another Task. The original Task can later be resumed, at which point it will pick up right where it left off. At first, this may seem similar to a function call. However there are two key differences. First, switching tasks does not use any space, so any number of task switches can occur without consuming the call stack. Second, switching among tasks can occur in any order, unlike function calls, where the called function must finish executing before control returns to the calling function.This kind of control flow can make it much easier to solve certain problems. In some problems, the various pieces of required work are not naturally related by function calls; there is no obvious \"caller\" or \"callee\" among the jobs that need to be done. An example is the producer-consumer problem, where one complex procedure is generating values and another complex procedure is consuming them. The consumer cannot simply call a producer function to get a value, because the producer may have more values to generate and so might not yet be ready to return. With tasks, the producer and consumer can both run as long as they need to, passing values back and forth as necessary.Julia provides a Channel mechanism for solving this problem. A Channel is a waitable first-in first-out queue which can have multiple tasks reading from and writing to it.Let\'s define a producer task, which produces values via the put! call. To consume values, we need to schedule the producer to run in a new task. A special Channel constructor which accepts a 1-arg function as an argument can be used to run a task bound to a channel. We can then take!() values repeatedly from the channel object:julia> function producer(c::Channel)\n put!(c, \"start\")\n for n=1:4\n put!(c, 2n)\n end\n put!(c, \"stop\")\n end;\n\njulia> chnl = Channel(producer);\n\njulia> take!(chnl)\n\"start\"\n\njulia> take!(chnl)\n2\n\njulia> take!(chnl)\n4\n\njulia> take!(chnl)\n6\n\njulia> take!(chnl)\n8\n\njulia> take!(chnl)\n\"stop\"One way to think of this behavior is that producer was able to return multiple times. Between calls to put!(), the producer\'s execution is suspended and the consumer has control.The returned Channel can be used as an iterable object in a for loop, in which case the loop variable takes on all the produced values. The loop is terminated when the channel is closed.julia> for x in Channel(producer)\n println(x)\n end\nstart\n2\n4\n6\n8\nstopNote that we did not have to explicitly close the channel in the producer. This is because the act of binding a Channel to a Task() associates the open lifetime of a channel with that of the bound task. The channel object is closed automatically when the task terminates. Multiple channels can be bound to a task, and vice-versa.While the Task() constructor expects a 0-argument function, the Channel() method which creates a channel bound task expects a function that accepts a single argument of type Channel. A common pattern is for the producer to be parameterized, in which case a partial function application is needed to create a 0 or 1 argument anonymous function.For Task() objects this can be done either directly or by use of a convenience macro:function mytask(myarg)\n ...\nend\n\ntaskHdl = Task(() -> mytask(7))\n# or, equivalently\ntaskHdl = @task mytask(7)To orchestrate more advanced work distribution patterns, bind() and schedule() can be used in conjunction with Task() and Channel() constructors to explicitly link a set of channels with a set of producer/consumer tasks.Note that currently Julia tasks are not scheduled to run on separate CPU cores. True kernel threads are discussed under the topic of Parallel Computing." -}, - -{ - "location": "manual/control-flow.html#Core-task-operations-1", - "page": "Control Flow", - "title": "Core task operations", - "category": "section", - "text": "Let us explore the low level construct yieldto() to underestand how task switching works. yieldto(task,value) suspends the current task, switches to the specified task, and causes that task\'s last yieldto() call to return the specified value. Notice that yieldto() is the only operation required to use task-style control flow; instead of calling and returning we are always just switching to a different task. This is why this feature is also called \"symmetric coroutines\"; each task is switched to and from using the same mechanism.yieldto() is powerful, but most uses of tasks do not invoke it directly. Consider why this might be. If you switch away from the current task, you will probably want to switch back to it at some point, but knowing when to switch back, and knowing which task has the responsibility of switching back, can require considerable coordination. For example, put!() and take!() are blocking operations, which, when used in the context of channels maintain state to remember who the consumers are. Not needing to manually keep track of the consuming task is what makes put!() easier to use than the low-level yieldto().In addition to yieldto(), a few other basic functions are needed to use tasks effectively.current_task() gets a reference to the currently-running task.\nistaskdone() queries whether a task has exited.\nistaskstarted() queries whether a task has run yet.\ntask_local_storage() manipulates a key-value store specific to the current task." -}, - -{ - "location": "manual/control-flow.html#Tasks-and-events-1", - "page": "Control Flow", - "title": "Tasks and events", - "category": "section", - "text": "Most task switches occur as a result of waiting for events such as I/O requests, and are performed by a scheduler included in the standard library. The scheduler maintains a queue of runnable tasks, and executes an event loop that restarts tasks based on external events such as message arrival.The basic function for waiting for an event is wait(). Several objects implement wait(); for example, given a Process object, wait() will wait for it to exit. wait() is often implicit; for example, a wait() can happen inside a call to read() to wait for data to be available.In all of these cases, wait() ultimately operates on a Condition object, which is in charge of queueing and restarting tasks. When a task calls wait() on a Condition, the task is marked as non-runnable, added to the condition\'s queue, and switches to the scheduler. The scheduler will then pick another task to run, or block waiting for external events. If all goes well, eventually an event handler will call notify() on the condition, which causes tasks waiting for that condition to become runnable again.A task created explicitly by calling Task is initially not known to the scheduler. This allows you to manage tasks manually using yieldto() if you wish. However, when such a task waits for an event, it still gets restarted automatically when the event happens, as you would expect. It is also possible to make the scheduler run a task whenever it can, without necessarily waiting for any events. This is done by calling schedule(), or using the @schedule or @async macros (see Parallel Computing for more details)." -}, - -{ - "location": "manual/control-flow.html#Task-states-1", - "page": "Control Flow", - "title": "Task states", - "category": "section", - "text": "Tasks have a state field that describes their execution status. A Task state is one of the following symbols:Symbol Meaning\n:runnable Currently running, or available to be switched to\n:waiting Blocked waiting for a specific event\n:queued In the scheduler\'s run queue about to be restarted\n:done Successfully finished executing\n:failed Finished with an uncaught exception" -}, - -{ - "location": "manual/variables-and-scoping.html#", - "page": "Scope of Variables", - "title": "Scope of Variables", - "category": "page", - "text": "" -}, - -{ - "location": "manual/variables-and-scoping.html#scope-of-variables-1", - "page": "Scope of Variables", - "title": "Scope of Variables", - "category": "section", - "text": "The scope of a variable is the region of code within which a variable is visible. Variable scoping helps avoid variable naming conflicts. The concept is intuitive: two functions can both have arguments called x without the two x\'s referring to the same thing. Similarly there are many other cases where different blocks of code can use the same name without referring to the same thing. The rules for when the same variable name does or doesn\'t refer to the same thing are called scope rules; this section spells them out in detail.Certain constructs in the language introduce scope blocks, which are regions of code that are eligible to be the scope of some set of variables. The scope of a variable cannot be an arbitrary set of source lines; instead, it will always line up with one of these blocks. There are two main types of scopes in Julia, global scope and local scope, the latter can be nested. The constructs introducing scope blocks are:Scope name block/construct introducing this kind of scope\nGlobal Scope module, baremodule, at interactive prompt (REPL)\nLocal Scope Soft Local Scope: for, while, comprehensions, try-catch-finally, let\nLocal Scope Hard Local Scope: functions (either syntax, anonymous & do-blocks), struct, macroNotably missing from this table are begin blocks and if blocks, which do not introduce new scope blocks. All three types of scopes follow somewhat different rules which will be explained below as well as some extra rules for certain blocks.Julia uses lexical scoping, meaning that a function\'s scope does not inherit from its caller\'s scope, but from the scope in which the function was defined. For example, in the following code the x inside foo refers to the x in the global scope of its module Bar:julia> module Bar\n x = 1\n foo() = x\n end;and not a x in the scope where foo is used:julia> import .Bar\n\njulia> x = -1;\n\njulia> Bar.foo()\n1Thus lexical scope means that the scope of variables can be inferred from the source code alone." -}, - -{ - "location": "manual/variables-and-scoping.html#Global-Scope-1", - "page": "Scope of Variables", - "title": "Global Scope", - "category": "section", - "text": "Each module introduces a new global scope, separate from the global scope of all other modules; there is no all-encompassing global scope. Modules can introduce variables of other modules into their scope through the using or import statements or through qualified access using the dot-notation, i.e. each module is a so-called namespace. Note that variable bindings can only be changed within their global scope and not from an outside module.julia> module A\n a = 1 # a global in A\'s scope\n end;\n\njulia> module B\n module C\n c = 2\n end\n b = C.c # can access the namespace of a nested global scope\n # through a qualified access\n import ..A # makes module A available\n d = A.a\n end;\n\njulia> module D\n b = a # errors as D\'s global scope is separate from A\'s\n end;\nERROR: UndefVarError: a not defined\n\njulia> module E\n import ..A # make module A available\n A.a = 2 # throws below error\n end;\nERROR: cannot assign variables in other modulesNote that the interactive prompt (aka REPL) is in the global scope of the module Main." -}, - -{ - "location": "manual/variables-and-scoping.html#Local-Scope-1", - "page": "Scope of Variables", - "title": "Local Scope", - "category": "section", - "text": "A new local scope is introduced by most code-blocks, see above table for a complete list. A local scope usually inherits all the variables from its parent scope, both for reading and writing. There are two subtypes of local scopes, hard and soft, with slightly different rules concerning what variables are inherited. Unlike global scopes, local scopes are not namespaces, thus variables in an inner scope cannot be retrieved from the parent scope through some sort of qualified access.The following rules and examples pertain to both hard and soft local scopes. A newly introduced variable in a local scope does not back-propagate to its parent scope. For example, here the z is not introduced into the top-level scope:julia> for i = 1:10\n z = i\n end\n\njulia> z\nERROR: UndefVarError: z not defined(Note, in this and all following examples it is assumed that their top-level is a global scope with a clean workspace, for instance a newly started REPL.)Inside a local scope a variable can be forced to be a local variable using the local keyword:julia> x = 0;\n\njulia> for i = 1:10\n local x\n x = i + 1\n end\n\njulia> x\n0Inside a local scope a new global variable can be defined using the keyword global:julia> for i = 1:10\n global z\n z = i\n end\n\njulia> z\n10The location of both the local and global keywords within the scope block is irrelevant. The following is equivalent to the last example (although stylistically worse):julia> for i = 1:10\n z = i\n global z\n end\n\njulia> z\n10" -}, - -{ - "location": "manual/variables-and-scoping.html#Soft-Local-Scope-1", - "page": "Scope of Variables", - "title": "Soft Local Scope", - "category": "section", - "text": "In a soft local scope, all variables are inherited from its parent scope unless a variable is specifically marked with the keyword local.Soft local scopes are introduced by for-loops, while-loops, comprehensions, try-catch-finally-blocks, and let-blocks. There are some extra rules for Let Blocks and for For Loops and Comprehensions.In the following example the x and y refer always to the same variables as the soft local scope inherits both read and write variables:julia> x, y = 0, 1;\n\njulia> for i = 1:10\n x = i + y + 1\n end\n\njulia> x\n12Within soft scopes, the global keyword is never necessary, although allowed. The only case when it would change the semantics is (currently) a syntax error:julia> let\n local j = 2\n let\n global j = 3\n end\n end\nERROR: syntax: `global j`: j is local variable in the enclosing scope" -}, - -{ - "location": "manual/variables-and-scoping.html#Hard-Local-Scope-1", - "page": "Scope of Variables", - "title": "Hard Local Scope", - "category": "section", - "text": "Hard local scopes are introduced by function definitions (in all their forms), struct type definition blocks, and macro-definitions.In a hard local scope, all variables are inherited from its parent scope unless:an assignment would result in a modified global variable, or\na variable is specifically marked with the keyword local.Thus global variables are only inherited for reading but not for writing:julia> x, y = 1, 2;\n\njulia> function foo()\n x = 2 # assignment introduces a new local\n return x + y # y refers to the global\n end;\n\njulia> foo()\n4\n\njulia> x\n1An explicit global is needed to assign to a global variable:julia> x = 1;\n\njulia> function foobar()\n global x = 2\n end;\n\njulia> foobar();\n\njulia> x\n2Note that nested functions can behave differently to functions defined in the global scope as they can modify their parent scope\'s local variables:julia> x, y = 1, 2;\n\njulia> function baz()\n x = 2 # introduces a new local\n function bar()\n x = 10 # modifies the parent\'s x\n return x + y # y is global\n end\n return bar() + x # 12 + 10 (x is modified in call of bar())\n end;\n\njulia> baz()\n22\n\njulia> x, y\n(1, 2)The distinction between inheriting global and local variables for assignment can lead to some slight differences between functions defined in local vs. global scopes. Consider the modification of the last example by moving bar to the global scope:julia> x, y = 1, 2;\n\njulia> function bar()\n x = 10 # local\n return x + y\n end;\n\njulia> function quz()\n x = 2 # local\n return bar() + x # 12 + 2 (x is not modified)\n end;\n\njulia> quz()\n14\n\njulia> x, y\n(1, 2)Note that above subtlety does not pertain to type and macro definitions as they can only appear at the global scope. There are special scoping rules concerning the evaluation of default and keyword function arguments which are described in the Function section.An assignment introducing a variable used inside a function, type or macro definition need not come before its inner usage:julia> f = y -> y + a\n(::#1) (generic function with 1 method)\n\njulia> f(3)\nERROR: UndefVarError: a not defined\nStacktrace:\n [1] (::##1#2)(::Int64) at ./none:1\n\njulia> a = 1\n1\n\njulia> f(3)\n4This behavior may seem slightly odd for a normal variable, but allows for named functions – which are just normal variables holding function objects – to be used before they are defined. This allows functions to be defined in whatever order is intuitive and convenient, rather than forcing bottom up ordering or requiring forward declarations, as long as they are defined by the time they are actually called. As an example, here is an inefficient, mutually recursive way to test if positive integers are even or odd:julia> even(n) = n == 0 ? true : odd(n-1);\n\njulia> odd(n) = n == 0 ? false : even(n-1);\n\njulia> even(3)\nfalse\n\njulia> odd(3)\ntrueJulia provides built-in, efficient functions to test for oddness and evenness called iseven() and isodd() so the above definitions should only be taken as examples." -}, - -{ - "location": "manual/variables-and-scoping.html#Hard-vs.-Soft-Local-Scope-1", - "page": "Scope of Variables", - "title": "Hard vs. Soft Local Scope", - "category": "section", - "text": "Blocks which introduce a soft local scope, such as loops, are generally used to manipulate the variables in their parent scope. Thus their default is to fully access all variables in their parent scope.Conversely, the code inside blocks which introduce a hard local scope (function, type, and macro definitions) can be executed at any place in a program. Remotely changing the state of global variables in other modules should be done with care and thus this is an opt-in feature requiring the global keyword.The reason to allow modifying local variables of parent scopes in nested functions is to allow constructing closures which have a private state, for instance the state variable in the following example:julia> let\n state = 0\n global counter\n counter() = state += 1\n end;\n\njulia> counter()\n1\n\njulia> counter()\n2See also the closures in the examples in the next two sections." -}, - -{ - "location": "manual/variables-and-scoping.html#Let-Blocks-1", - "page": "Scope of Variables", - "title": "Let Blocks", - "category": "section", - "text": "Unlike assignments to local variables, let statements allocate new variable bindings each time they run. An assignment modifies an existing value location, and let creates new locations. This difference is usually not important, and is only detectable in the case of variables that outlive their scope via closures. The let syntax accepts a comma-separated series of assignments and variable names:julia> x, y, z = -1, -1, -1;\n\njulia> let x = 1, z\n println(\"x: $x, y: $y\") # x is local variable, y the global\n println(\"z: $z\") # errors as z has not been assigned yet but is local\n end\nx: 1, y: -1\nERROR: UndefVarError: z not definedThe assignments are evaluated in order, with each right-hand side evaluated in the scope before the new variable on the left-hand side has been introduced. Therefore it makes sense to write something like let x = x since the two x variables are distinct and have separate storage. Here is an example where the behavior of let is needed:julia> Fs = Array{Any}(2); i = 1;\n\njulia> while i <= 2\n Fs[i] = ()->i\n i += 1\n end\n\njulia> Fs[1]()\n3\n\njulia> Fs[2]()\n3Here we create and store two closures that return variable i. However, it is always the same variable i, so the two closures behave identically. We can use let to create a new binding for i:julia> Fs = Array{Any}(2); i = 1;\n\njulia> while i <= 2\n let i = i\n Fs[i] = ()->i\n end\n i += 1\n end\n\njulia> Fs[1]()\n1\n\njulia> Fs[2]()\n2Since the begin construct does not introduce a new scope, it can be useful to use a zero-argument let to just introduce a new scope block without creating any new bindings:julia> let\n local x = 1\n let\n local x = 2\n end\n x\n end\n1Since let introduces a new scope block, the inner local x is a different variable than the outer local x." -}, - -{ - "location": "manual/variables-and-scoping.html#For-Loops-and-Comprehensions-1", - "page": "Scope of Variables", - "title": "For Loops and Comprehensions", - "category": "section", - "text": "for loops and Comprehensions have the following behavior: any new variables introduced in their body scopes are freshly allocated for each loop iteration. This is in contrast to while loops which reuse the variables for all iterations. Therefore these constructs are similar to while loops with let blocks inside:julia> Fs = Array{Any}(2);\n\njulia> for j = 1:2\n Fs[j] = ()->j\n end\n\njulia> Fs[1]()\n1\n\njulia> Fs[2]()\n2for loops will reuse existing variables for its iteration variable:julia> i = 0;\n\njulia> for i = 1:3\n end\n\njulia> i\n3However, comprehensions do not do this, and always freshly allocate their iteration variables:julia> x = 0;\n\njulia> [ x for x = 1:3 ];\n\njulia> x\n0" -}, - -{ - "location": "manual/variables-and-scoping.html#Constants-1", - "page": "Scope of Variables", - "title": "Constants", - "category": "section", - "text": "A common use of variables is giving names to specific, unchanging values. Such variables are only assigned once. This intent can be conveyed to the compiler using the const keyword:julia> const e = 2.71828182845904523536;\n\njulia> const pi = 3.14159265358979323846;The const declaration is allowed on both global and local variables, but is especially useful for globals. It is difficult for the compiler to optimize code involving global variables, since their values (or even their types) might change at almost any time. If a global variable will not change, adding a const declaration solves this performance problem.Local constants are quite different. The compiler is able to determine automatically when a local variable is constant, so local constant declarations are not necessary for performance purposes.Special top-level assignments, such as those performed by the function and struct keywords, are constant by default.Note that const only affects the variable binding; the variable may be bound to a mutable object (such as an array), and that object may still be modified." -}, - -{ - "location": "manual/types.html#", - "page": "Types", - "title": "Types", - "category": "page", - "text": "" -}, - -{ - "location": "manual/types.html#man-types-1", - "page": "Types", - "title": "Types", - "category": "section", - "text": "Type systems have traditionally fallen into two quite different camps: static type systems, where every program expression must have a type computable before the execution of the program, and dynamic type systems, where nothing is known about types until run time, when the actual values manipulated by the program are available. Object orientation allows some flexibility in statically typed languages by letting code be written without the precise types of values being known at compile time. The ability to write code that can operate on different types is called polymorphism. All code in classic dynamically typed languages is polymorphic: only by explicitly checking types, or when objects fail to support operations at run-time, are the types of any values ever restricted.Julia\'s type system is dynamic, but gains some of the advantages of static type systems by making it possible to indicate that certain values are of specific types. This can be of great assistance in generating efficient code, but even more significantly, it allows method dispatch on the types of function arguments to be deeply integrated with the language. Method dispatch is explored in detail in Methods, but is rooted in the type system presented here.The default behavior in Julia when types are omitted is to allow values to be of any type. Thus, one can write many useful Julia programs without ever explicitly using types. When additional expressiveness is needed, however, it is easy to gradually introduce explicit type annotations into previously \"untyped\" code. Doing so will typically increase both the performance and robustness of these systems, and perhaps somewhat counterintuitively, often significantly simplify them.Describing Julia in the lingo of type systems, it is: dynamic, nominative and parametric. Generic types can be parameterized, and the hierarchical relationships between types are explicitly declared, rather than implied by compatible structure. One particularly distinctive feature of Julia\'s type system is that concrete types may not subtype each other: all concrete types are final and may only have abstract types as their supertypes. While this might at first seem unduly restrictive, it has many beneficial consequences with surprisingly few drawbacks. It turns out that being able to inherit behavior is much more important than being able to inherit structure, and inheriting both causes significant difficulties in traditional object-oriented languages. Other high-level aspects of Julia\'s type system that should be mentioned up front are:There is no division between object and non-object values: all values in Julia are true objects having a type that belongs to a single, fully connected type graph, all nodes of which are equally first-class as types.\nThere is no meaningful concept of a \"compile-time type\": the only type a value has is its actual type when the program is running. This is called a \"run-time type\" in object-oriented languages where the combination of static compilation with polymorphism makes this distinction significant.\nOnly values, not variables, have types – variables are simply names bound to values.\nBoth abstract and concrete types can be parameterized by other types. They can also be parameterized by symbols, by values of any type for which isbits() returns true (essentially, things like numbers and bools that are stored like C types or structs with no pointers to other objects), and also by tuples thereof. Type parameters may be omitted when they do not need to be referenced or restricted.Julia\'s type system is designed to be powerful and expressive, yet clear, intuitive and unobtrusive. Many Julia programmers may never feel the need to write code that explicitly uses types. Some kinds of programming, however, become clearer, simpler, faster and more robust with declared types." -}, - -{ - "location": "manual/types.html#Type-Declarations-1", - "page": "Types", - "title": "Type Declarations", - "category": "section", - "text": "The :: operator can be used to attach type annotations to expressions and variables in programs. There are two primary reasons to do this:As an assertion to help confirm that your program works the way you expect,\nTo provide extra type information to the compiler, which can then improve performance in some casesWhen appended to an expression computing a value, the :: operator is read as \"is an instance of\". It can be used anywhere to assert that the value of the expression on the left is an instance of the type on the right. When the type on the right is concrete, the value on the left must have that type as its implementation – recall that all concrete types are final, so no implementation is a subtype of any other. When the type is abstract, it suffices for the value to be implemented by a concrete type that is a subtype of the abstract type. If the type assertion is not true, an exception is thrown, otherwise, the left-hand value is returned:julia> (1+2)::AbstractFloat\nERROR: TypeError: typeassert: expected AbstractFloat, got Int64\n\njulia> (1+2)::Int\n3This allows a type assertion to be attached to any expression in-place.When appended to a variable on the left-hand side of an assignment, or as part of a local declaration, the :: operator means something a bit different: it declares the variable to always have the specified type, like a type declaration in a statically-typed language such as C. Every value assigned to the variable will be converted to the declared type using convert():julia> function foo()\n x::Int8 = 100\n x\n end\nfoo (generic function with 1 method)\n\njulia> foo()\n100\n\njulia> typeof(ans)\nInt8This feature is useful for avoiding performance \"gotchas\" that could occur if one of the assignments to a variable changed its type unexpectedly.This \"declaration\" behavior only occurs in specific contexts:local x::Int8 # in a local declaration\nx::Int8 = 10 # as the left-hand side of an assignmentand applies to the whole current scope, even before the declaration. Currently, type declarations cannot be used in global scope, e.g. in the REPL, since Julia does not yet have constant-type globals.Declarations can also be attached to function definitions:function sinc(x)::Float64\n if x == 0\n return 1\n end\n return sin(pi*x)/(pi*x)\nendReturning from this function behaves just like an assignment to a variable with a declared type: the value is always converted to Float64." -}, - -{ - "location": "manual/types.html#Abstract-Types-1", - "page": "Types", - "title": "Abstract Types", - "category": "section", - "text": "Abstract types cannot be instantiated, and serve only as nodes in the type graph, thereby describing sets of related concrete types: those concrete types which are their descendants. We begin with abstract types even though they have no instantiation because they are the backbone of the type system: they form the conceptual hierarchy which makes Julia\'s type system more than just a collection of object implementations.Recall that in Integers and Floating-Point Numbers, we introduced a variety of concrete types of numeric values: Int8, UInt8, Int16, UInt16, Int32, UInt32, Int64, UInt64, Int128, UInt128, Float16, Float32, and Float64. Although they have different representation sizes, Int8, Int16, Int32, Int64 and Int128 all have in common that they are signed integer types. Likewise UInt8, UInt16, UInt32, UInt64 and UInt128 are all unsigned integer types, while Float16, Float32 and Float64 are distinct in being floating-point types rather than integers. It is common for a piece of code to make sense, for example, only if its arguments are some kind of integer, but not really depend on what particular kind of integer. For example, the greatest common denominator algorithm works for all kinds of integers, but will not work for floating-point numbers. Abstract types allow the construction of a hierarchy of types, providing a context into which concrete types can fit. This allows you, for example, to easily program to any type that is an integer, without restricting an algorithm to a specific type of integer.Abstract types are declared using the abstract type keyword. The general syntaxes for declaring an abstract type are:abstract type «name» end\nabstract type «name» <: «supertype» endThe abstract type keyword introduces a new abstract type, whose name is given by «name». This name can be optionally followed by <: and an already-existing type, indicating that the newly declared abstract type is a subtype of this \"parent\" type.When no supertype is given, the default supertype is Any – a predefined abstract type that all objects are instances of and all types are subtypes of. In type theory, Any is commonly called \"top\" because it is at the apex of the type graph. Julia also has a predefined abstract \"bottom\" type, at the nadir of the type graph, which is written as Union{}. It is the exact opposite of Any: no object is an instance of Union{} and all types are supertypes of Union{}.Let\'s consider some of the abstract types that make up Julia\'s numerical hierarchy:abstract type Number end\nabstract type Real <: Number end\nabstract type AbstractFloat <: Real end\nabstract type Integer <: Real end\nabstract type Signed <: Integer end\nabstract type Unsigned <: Integer endThe Number type is a direct child type of Any, and Real is its child. In turn, Real has two children (it has more, but only two are shown here; we\'ll get to the others later): Integer and AbstractFloat, separating the world into representations of integers and representations of real numbers. Representations of real numbers include, of course, floating-point types, but also include other types, such as rationals. Hence, AbstractFloat is a proper subtype of Real, including only floating-point representations of real numbers. Integers are further subdivided into Signed and Unsigned varieties.The <: operator in general means \"is a subtype of\", and, used in declarations like this, declares the right-hand type to be an immediate supertype of the newly declared type. It can also be used in expressions as a subtype operator which returns true when its left operand is a subtype of its right operand:julia> Integer <: Number\ntrue\n\njulia> Integer <: AbstractFloat\nfalseAn important use of abstract types is to provide default implementations for concrete types. To give a simple example, consider:function myplus(x,y)\n x+y\nendThe first thing to note is that the above argument declarations are equivalent to x::Any and y::Any. When this function is invoked, say as myplus(2,5), the dispatcher chooses the most specific method named myplus that matches the given arguments. (See Methods for more information on multiple dispatch.)Assuming no method more specific than the above is found, Julia next internally defines and compiles a method called myplus specifically for two Int arguments based on the generic function given above, i.e., it implicitly defines and compiles:function myplus(x::Int,y::Int)\n x+y\nendand finally, it invokes this specific method.Thus, abstract types allow programmers to write generic functions that can later be used as the default method by many combinations of concrete types. Thanks to multiple dispatch, the programmer has full control over whether the default or more specific method is used.An important point to note is that there is no loss in performance if the programmer relies on a function whose arguments are abstract types, because it is recompiled for each tuple of argument concrete types with which it is invoked. (There may be a performance issue, however, in the case of function arguments that are containers of abstract types; see Performance Tips.)" -}, - -{ - "location": "manual/types.html#Primitive-Types-1", - "page": "Types", - "title": "Primitive Types", - "category": "section", - "text": "A primitive type is a concrete type whose data consists of plain old bits. Classic examples of primitive types are integers and floating-point values. Unlike most languages, Julia lets you declare your own primitive types, rather than providing only a fixed set of built-in ones. In fact, the standard primitive types are all defined in the language itself:primitive type Float16 <: AbstractFloat 16 end\nprimitive type Float32 <: AbstractFloat 32 end\nprimitive type Float64 <: AbstractFloat 64 end\n\nprimitive type Bool <: Integer 8 end\nprimitive type Char 32 end\n\nprimitive type Int8 <: Signed 8 end\nprimitive type UInt8 <: Unsigned 8 end\nprimitive type Int16 <: Signed 16 end\nprimitive type UInt16 <: Unsigned 16 end\nprimitive type Int32 <: Signed 32 end\nprimitive type UInt32 <: Unsigned 32 end\nprimitive type Int64 <: Signed 64 end\nprimitive type UInt64 <: Unsigned 64 end\nprimitive type Int128 <: Signed 128 end\nprimitive type UInt128 <: Unsigned 128 endThe general syntaxes for declaring a primitive type are:primitive type «name» «bits» end\nprimitive type «name» <: «supertype» «bits» endThe number of bits indicates how much storage the type requires and the name gives the new type a name. A primitive type can optionally be declared to be a subtype of some supertype. If a supertype is omitted, then the type defaults to having Any as its immediate supertype. The declaration of Bool above therefore means that a boolean value takes eight bits to store, and has Integer as its immediate supertype. Currently, only sizes that are multiples of 8 bits are supported. Therefore, boolean values, although they really need just a single bit, cannot be declared to be any smaller than eight bits.The types Bool, Int8 and UInt8 all have identical representations: they are eight-bit chunks of memory. Since Julia\'s type system is nominative, however, they are not interchangeable despite having identical structure. A fundamental difference between them is that they have different supertypes: Bool\'s direct supertype is Integer, Int8\'s is Signed, and UInt8\'s is Unsigned. All other differences between Bool, Int8, and UInt8 are matters of behavior – the way functions are defined to act when given objects of these types as arguments. This is why a nominative type system is necessary: if structure determined type, which in turn dictates behavior, then it would be impossible to make Bool behave any differently than Int8 or UInt8." -}, - -{ - "location": "manual/types.html#Composite-Types-1", - "page": "Types", - "title": "Composite Types", - "category": "section", - "text": "Composite types are called records, structs, or objects in various languages. A composite type is a collection of named fields, an instance of which can be treated as a single value. In many languages, composite types are the only kind of user-definable type, and they are by far the most commonly used user-defined type in Julia as well.In mainstream object oriented languages, such as C++, Java, Python and Ruby, composite types also have named functions associated with them, and the combination is called an \"object\". In purer object-oriented languages, such as Ruby or Smalltalk, all values are objects whether they are composites or not. In less pure object oriented languages, including C++ and Java, some values, such as integers and floating-point values, are not objects, while instances of user-defined composite types are true objects with associated methods. In Julia, all values are objects, but functions are not bundled with the objects they operate on. This is necessary since Julia chooses which method of a function to use by multiple dispatch, meaning that the types of all of a function\'s arguments are considered when selecting a method, rather than just the first one (see Methods for more information on methods and dispatch). Thus, it would be inappropriate for functions to \"belong\" to only their first argument. Organizing methods into function objects rather than having named bags of methods \"inside\" each object ends up being a highly beneficial aspect of the language design.Composite types are introduced with the struct keyword followed by a block of field names, optionally annotated with types using the :: operator:julia> struct Foo\n bar\n baz::Int\n qux::Float64\n endFields with no type annotation default to Any, and can accordingly hold any type of value.New objects of type Foo are created by applying the Foo type object like a function to values for its fields:julia> foo = Foo(\"Hello, world.\", 23, 1.5)\nFoo(\"Hello, world.\", 23, 1.5)\n\njulia> typeof(foo)\nFooWhen a type is applied like a function it is called a constructor. Two constructors are generated automatically (these are called default constructors). One accepts any arguments and calls convert() to convert them to the types of the fields, and the other accepts arguments that match the field types exactly. The reason both of these are generated is that this makes it easier to add new definitions without inadvertently replacing a default constructor.Since the bar field is unconstrained in type, any value will do. However, the value for baz must be convertible to Int:julia> Foo((), 23.5, 1)\nERROR: InexactError()\nStacktrace:\n [1] convert(::Type{Int64}, ::Float64) at ./float.jl:679\n [2] Foo(::Tuple{}, ::Float64, ::Int64) at ./none:2You may find a list of field names using the fieldnames function.julia> fieldnames(foo)\n3-element Array{Symbol,1}:\n :bar\n :baz\n :quxYou can access the field values of a composite object using the traditional foo.bar notation:julia> foo.bar\n\"Hello, world.\"\n\njulia> foo.baz\n23\n\njulia> foo.qux\n1.5Composite objects declared with struct are immutable; they cannot be modified after construction. This may seem odd at first, but it has several advantages:It can be more efficient. Some structs can be packed efficiently into arrays, and in some cases the compiler is able to avoid allocating immutable objects entirely.\nIt is not possible to violate the invariants provided by the type\'s constructors.\nCode using immutable objects can be easier to reason about.An immutable object might contain mutable objects, such as arrays, as fields. Those contained objects will remain mutable; only the fields of the immutable object itself cannot be changed to point to different objects.Where required, mutable composite objects can be declared with the keyword mutable struct, to be discussed in the next section.Composite types with no fields are singletons; there can be only one instance of such types:julia> struct NoFields\n end\n\njulia> NoFields() === NoFields()\ntrueThe === function confirms that the \"two\" constructed instances of NoFields are actually one and the same. Singleton types are described in further detail below.There is much more to say about how instances of composite types are created, but that discussion depends on both Parametric Types and on Methods, and is sufficiently important to be addressed in its own section: Constructors." -}, - -{ - "location": "manual/types.html#Mutable-Composite-Types-1", - "page": "Types", - "title": "Mutable Composite Types", - "category": "section", - "text": "If a composite type is declared with mutable struct instead of struct, then instances of it can be modified:julia> mutable struct Bar\n baz\n qux::Float64\n end\n\njulia> bar = Bar(\"Hello\", 1.5);\n\njulia> bar.qux = 2.0\n2.0\n\njulia> bar.baz = 1//2\n1//2In order to support mutation, such objects are generally allocated on the heap, and have stable memory addresses. A mutable object is like a little container that might hold different values over time, and so can only be reliably identified with its address. In contrast, an instance of an immutable type is associated with specific field values –- the field values alone tell you everything about the object. In deciding whether to make a type mutable, ask whether two instances with the same field values would be considered identical, or if they might need to change independently over time. If they would be considered identical, the type should probably be immutable.To recap, two essential properties define immutability in Julia:An object with an immutable type is passed around (both in assignment statements and in function calls) by copying, whereas a mutable type is passed around by reference.\nIt is not permitted to modify the fields of a composite immutable type.It is instructive, particularly for readers whose background is C/C++, to consider why these two properties go hand in hand. If they were separated, i.e., if the fields of objects passed around by copying could be modified, then it would become more difficult to reason about certain instances of generic code. For example, suppose x is a function argument of an abstract type, and suppose that the function changes a field: x.isprocessed = true. Depending on whether x is passed by copying or by reference, this statement may or may not alter the actual argument in the calling routine. Julia sidesteps the possibility of creating functions with unknown effects in this scenario by forbidding modification of fields of objects passed around by copying." -}, - -{ - "location": "manual/types.html#Declared-Types-1", - "page": "Types", - "title": "Declared Types", - "category": "section", - "text": "The three kinds of types discussed in the previous three sections are actually all closely related. They share the same key properties:They are explicitly declared.\nThey have names.\nThey have explicitly declared supertypes.\nThey may have parameters.Because of these shared properties, these types are internally represented as instances of the same concept, DataType, which is the type of any of these types:julia> typeof(Real)\nDataType\n\njulia> typeof(Int)\nDataTypeA DataType may be abstract or concrete. If it is concrete, it has a specified size, storage layout, and (optionally) field names. Thus a bits type is a DataType with nonzero size, but no field names. A composite type is a DataType that has field names or is empty (zero size).Every concrete value in the system is an instance of some DataType." -}, - -{ - "location": "manual/types.html#Type-Unions-1", - "page": "Types", - "title": "Type Unions", - "category": "section", - "text": "A type union is a special abstract type which includes as objects all instances of any of its argument types, constructed using the special Union function:julia> IntOrString = Union{Int,AbstractString}\nUnion{AbstractString, Int64}\n\njulia> 1 :: IntOrString\n1\n\njulia> \"Hello!\" :: IntOrString\n\"Hello!\"\n\njulia> 1.0 :: IntOrString\nERROR: TypeError: typeassert: expected Union{AbstractString, Int64}, got Float64The compilers for many languages have an internal union construct for reasoning about types; Julia simply exposes it to the programmer." -}, - -{ - "location": "manual/types.html#Parametric-Types-1", - "page": "Types", - "title": "Parametric Types", - "category": "section", - "text": "An important and powerful feature of Julia\'s type system is that it is parametric: types can take parameters, so that type declarations actually introduce a whole family of new types – one for each possible combination of parameter values. There are many languages that support some version of generic programming, wherein data structures and algorithms to manipulate them may be specified without specifying the exact types involved. For example, some form of generic programming exists in ML, Haskell, Ada, Eiffel, C++, Java, C#, F#, and Scala, just to name a few. Some of these languages support true parametric polymorphism (e.g. ML, Haskell, Scala), while others support ad-hoc, template-based styles of generic programming (e.g. C++, Java). With so many different varieties of generic programming and parametric types in various languages, we won\'t even attempt to compare Julia\'s parametric types to other languages, but will instead focus on explaining Julia\'s system in its own right. We will note, however, that because Julia is a dynamically typed language and doesn\'t need to make all type decisions at compile time, many traditional difficulties encountered in static parametric type systems can be relatively easily handled.All declared types (the DataType variety) can be parameterized, with the same syntax in each case. We will discuss them in the following order: first, parametric composite types, then parametric abstract types, and finally parametric bits types." -}, - -{ - "location": "manual/types.html#Parametric-Composite-Types-1", - "page": "Types", - "title": "Parametric Composite Types", - "category": "section", - "text": "Type parameters are introduced immediately after the type name, surrounded by curly braces:julia> struct Point{T}\n x::T\n y::T\n endThis declaration defines a new parametric type, Point{T}, holding two \"coordinates\" of type T. What, one may ask, is T? Well, that\'s precisely the point of parametric types: it can be any type at all (or a value of any bits type, actually, although here it\'s clearly used as a type). Point{Float64} is a concrete type equivalent to the type defined by replacing T in the definition of Point with Float64. Thus, this single declaration actually declares an unlimited number of types: Point{Float64}, Point{AbstractString}, Point{Int64}, etc. Each of these is now a usable concrete type:julia> Point{Float64}\nPoint{Float64}\n\njulia> Point{AbstractString}\nPoint{AbstractString}The type Point{Float64} is a point whose coordinates are 64-bit floating-point values, while the type Point{AbstractString} is a \"point\" whose \"coordinates\" are string objects (see Strings).Point itself is also a valid type object, containing all instances Point{Float64}, Point{AbstractString}, etc. as subtypes:julia> Point{Float64} <: Point\ntrue\n\njulia> Point{AbstractString} <: Point\ntrueOther types, of course, are not subtypes of it:julia> Float64 <: Point\nfalse\n\njulia> AbstractString <: Point\nfalseConcrete Point types with different values of T are never subtypes of each other:julia> Point{Float64} <: Point{Int64}\nfalse\n\njulia> Point{Float64} <: Point{Real}\nfalsewarning: Warning\nThis last point is very important: even though Float64 <: Real we DO NOT have Point{Float64} <: Point{Real}.In other words, in the parlance of type theory, Julia\'s type parameters are invariant, rather than being covariant (or even contravariant). This is for practical reasons: while any instance of Point{Float64} may conceptually be like an instance of Point{Real} as well, the two types have different representations in memory:An instance of Point{Float64} can be represented compactly and efficiently as an immediate pair of 64-bit values;\nAn instance of Point{Real} must be able to hold any pair of instances of Real. Since objects that are instances of Real can be of arbitrary size and structure, in practice an instance of Point{Real} must be represented as a pair of pointers to individually allocated Real objects.The efficiency gained by being able to store Point{Float64} objects with immediate values is magnified enormously in the case of arrays: an Array{Float64} can be stored as a contiguous memory block of 64-bit floating-point values, whereas an Array{Real} must be an array of pointers to individually allocated Real objects – which may well be boxed 64-bit floating-point values, but also might be arbitrarily large, complex objects, which are declared to be implementations of the Real abstract type.Since Point{Float64} is not a subtype of Point{Real}, the following method can\'t be applied to arguments of type Point{Float64}:function norm(p::Point{Real})\n sqrt(p.x^2 + p.y^2)\nendA correct way to define a method that accepts all arguments of type Point{T} where T is a subtype of Real is:function norm(p::Point{<:Real})\n sqrt(p.x^2 + p.y^2)\nend(Equivalently, one could define function norm{T<:Real}(p::Point{T}) or function norm(p::Point{T} where T<:Real); see UnionAll Types.)More examples will be discussed later in Methods.How does one construct a Point object? It is possible to define custom constructors for composite types, which will be discussed in detail in Constructors, but in the absence of any special constructor declarations, there are two default ways of creating new composite objects, one in which the type parameters are explicitly given and the other in which they are implied by the arguments to the object constructor.Since the type Point{Float64} is a concrete type equivalent to Point declared with Float64 in place of T, it can be applied as a constructor accordingly:julia> Point{Float64}(1.0, 2.0)\nPoint{Float64}(1.0, 2.0)\n\njulia> typeof(ans)\nPoint{Float64}For the default constructor, exactly one argument must be supplied for each field:julia> Point{Float64}(1.0)\nERROR: MethodError: Cannot `convert` an object of type Float64 to an object of type Point{Float64}\nThis may have arisen from a call to the constructor Point{Float64}(...),\nsince type constructors fall back to convert methods.\nStacktrace:\n [1] Point{Float64}(::Float64) at ./sysimg.jl:77\n\njulia> Point{Float64}(1.0,2.0,3.0)\nERROR: MethodError: no method matching Point{Float64}(::Float64, ::Float64, ::Float64)Only one default constructor is generated for parametric types, since overriding it is not possible. This constructor accepts any arguments and converts them to the field types.In many cases, it is redundant to provide the type of Point object one wants to construct, since the types of arguments to the constructor call already implicitly provide type information. For that reason, you can also apply Point itself as a constructor, provided that the implied value of the parameter type T is unambiguous:julia> Point(1.0,2.0)\nPoint{Float64}(1.0, 2.0)\n\njulia> typeof(ans)\nPoint{Float64}\n\njulia> Point(1,2)\nPoint{Int64}(1, 2)\n\njulia> typeof(ans)\nPoint{Int64}In the case of Point, the type of T is unambiguously implied if and only if the two arguments to Point have the same type. When this isn\'t the case, the constructor will fail with a MethodError:julia> Point(1,2.5)\nERROR: MethodError: no method matching Point(::Int64, ::Float64)\nClosest candidates are:\n Point(::T, !Matched::T) where T at none:2Constructor methods to appropriately handle such mixed cases can be defined, but that will not be discussed until later on in Constructors." -}, - -{ - "location": "manual/types.html#Parametric-Abstract-Types-1", - "page": "Types", - "title": "Parametric Abstract Types", - "category": "section", - "text": "Parametric abstract type declarations declare a collection of abstract types, in much the same way:julia> abstract type Pointy{T} endWith this declaration, Pointy{T} is a distinct abstract type for each type or integer value of T. As with parametric composite types, each such instance is a subtype of Pointy:julia> Pointy{Int64} <: Pointy\ntrue\n\njulia> Pointy{1} <: Pointy\ntrueParametric abstract types are invariant, much as parametric composite types are:julia> Pointy{Float64} <: Pointy{Real}\nfalse\n\njulia> Pointy{Real} <: Pointy{Float64}\nfalseThe notation Pointy{<:Real} can be used to express the Julia analogue of a covariant type, while Pointy{>:Int} the analogue of a contravariant type, but technically these represent sets of types (see UnionAll Types).julia> Pointy{Float64} <: Pointy{<:Real}\ntrue\n\njulia> Pointy{Real} <: Pointy{>:Int}\ntrueMuch as plain old abstract types serve to create a useful hierarchy of types over concrete types, parametric abstract types serve the same purpose with respect to parametric composite types. We could, for example, have declared Point{T} to be a subtype of Pointy{T} as follows:julia> struct Point{T} <: Pointy{T}\n x::T\n y::T\n endGiven such a declaration, for each choice of T, we have Point{T} as a subtype of Pointy{T}:julia> Point{Float64} <: Pointy{Float64}\ntrue\n\njulia> Point{Real} <: Pointy{Real}\ntrue\n\njulia> Point{AbstractString} <: Pointy{AbstractString}\ntrueThis relationship is also invariant:julia> Point{Float64} <: Pointy{Real}\nfalse\n\njulia> Point{Float64} <: Pointy{<:Real}\ntrueWhat purpose do parametric abstract types like Pointy serve? Consider if we create a point-like implementation that only requires a single coordinate because the point is on the diagonal line x = y:julia> struct DiagPoint{T} <: Pointy{T}\n x::T\n endNow both Point{Float64} and DiagPoint{Float64} are implementations of the Pointy{Float64} abstraction, and similarly for every other possible choice of type T. This allows programming to a common interface shared by all Pointy objects, implemented for both Point and DiagPoint. This cannot be fully demonstrated, however, until we have introduced methods and dispatch in the next section, Methods.There are situations where it may not make sense for type parameters to range freely over all possible types. In such situations, one can constrain the range of T like so:julia> abstract type Pointy{T<:Real} endWith such a declaration, it is acceptable to use any type that is a subtype of Real in place of T, but not types that are not subtypes of Real:julia> Pointy{Float64}\nPointy{Float64}\n\njulia> Pointy{Real}\nPointy{Real}\n\njulia> Pointy{AbstractString}\nERROR: TypeError: Pointy: in T, expected T<:Real, got Type{AbstractString}\n\njulia> Pointy{1}\nERROR: TypeError: Pointy: in T, expected T<:Real, got Int64Type parameters for parametric composite types can be restricted in the same manner:struct Point{T<:Real} <: Pointy{T}\n x::T\n y::T\nendTo give a real-world example of how all this parametric type machinery can be useful, here is the actual definition of Julia\'s Rational immutable type (except that we omit the constructor here for simplicity), representing an exact ratio of integers:struct Rational{T<:Integer} <: Real\n num::T\n den::T\nendIt only makes sense to take ratios of integer values, so the parameter type T is restricted to being a subtype of Integer, and a ratio of integers represents a value on the real number line, so any Rational is an instance of the Real abstraction." -}, - -{ - "location": "manual/types.html#Tuple-Types-1", - "page": "Types", - "title": "Tuple Types", - "category": "section", - "text": "Tuples are an abstraction of the arguments of a function – without the function itself. The salient aspects of a function\'s arguments are their order and their types. Therefore a tuple type is similar to a parameterized immutable type where each parameter is the type of one field. For example, a 2-element tuple type resembles the following immutable type:struct Tuple2{A,B}\n a::A\n b::B\nendHowever, there are three key differences:Tuple types may have any number of parameters.\nTuple types are covariant in their parameters: Tuple{Int} is a subtype of Tuple{Any}. Therefore Tuple{Any} is considered an abstract type, and tuple types are only concrete if their parameters are.\nTuples do not have field names; fields are only accessed by index.Tuple values are written with parentheses and commas. When a tuple is constructed, an appropriate tuple type is generated on demand:julia> typeof((1,\"foo\",2.5))\nTuple{Int64,String,Float64}Note the implications of covariance:julia> Tuple{Int,AbstractString} <: Tuple{Real,Any}\ntrue\n\njulia> Tuple{Int,AbstractString} <: Tuple{Real,Real}\nfalse\n\njulia> Tuple{Int,AbstractString} <: Tuple{Real,}\nfalseIntuitively, this corresponds to the type of a function\'s arguments being a subtype of the function\'s signature (when the signature matches)." -}, - -{ - "location": "manual/types.html#Vararg-Tuple-Types-1", - "page": "Types", - "title": "Vararg Tuple Types", - "category": "section", - "text": "The last parameter of a tuple type can be the special type Vararg, which denotes any number of trailing elements:julia> mytupletype = Tuple{AbstractString,Vararg{Int}}\nTuple{AbstractString,Vararg{Int64,N} where N}\n\njulia> isa((\"1\",), mytupletype)\ntrue\n\njulia> isa((\"1\",1), mytupletype)\ntrue\n\njulia> isa((\"1\",1,2), mytupletype)\ntrue\n\njulia> isa((\"1\",1,2,3.0), mytupletype)\nfalseNotice that Vararg{T} corresponds to zero or more elements of type T. Vararg tuple types are used to represent the arguments accepted by varargs methods (see Varargs Functions).The type Vararg{T,N} corresponds to exactly N elements of type T. NTuple{N,T} is a convenient alias for Tuple{Vararg{T,N}}, i.e. a tuple type containing exactly N elements of type T." -}, - -{ - "location": "manual/types.html#man-singleton-types-1", - "page": "Types", - "title": "Singleton Types", - "category": "section", - "text": "There is a special kind of abstract parametric type that must be mentioned here: singleton types. For each type, T, the \"singleton type\" Type{T} is an abstract type whose only instance is the object T. Since the definition is a little difficult to parse, let\'s look at some examples:julia> isa(Float64, Type{Float64})\ntrue\n\njulia> isa(Real, Type{Float64})\nfalse\n\njulia> isa(Real, Type{Real})\ntrue\n\njulia> isa(Float64, Type{Real})\nfalseIn other words, isa(A,Type{B}) is true if and only if A and B are the same object and that object is a type. Without the parameter, Type is simply an abstract type which has all type objects as its instances, including, of course, singleton types:julia> isa(Type{Float64}, Type)\ntrue\n\njulia> isa(Float64, Type)\ntrue\n\njulia> isa(Real, Type)\ntrueAny object that is not a type is not an instance of Type:julia> isa(1, Type)\nfalse\n\njulia> isa(\"foo\", Type)\nfalseUntil we discuss Parametric Methods and conversions, it is difficult to explain the utility of the singleton type construct, but in short, it allows one to specialize function behavior on specific type values. This is useful for writing methods (especially parametric ones) whose behavior depends on a type that is given as an explicit argument rather than implied by the type of one of its arguments.A few popular languages have singleton types, including Haskell, Scala and Ruby. In general usage, the term \"singleton type\" refers to a type whose only instance is a single value. This meaning applies to Julia\'s singleton types, but with that caveat that only type objects have singleton types." -}, - -{ - "location": "manual/types.html#Parametric-Primitive-Types-1", - "page": "Types", - "title": "Parametric Primitive Types", - "category": "section", - "text": "Primitive types can also be declared parametrically. For example, pointers are represented as primitive types which would be declared in Julia like this:# 32-bit system:\nprimitive type Ptr{T} 32 end\n\n# 64-bit system:\nprimitive type Ptr{T} 64 endThe slightly odd feature of these declarations as compared to typical parametric composite types, is that the type parameter T is not used in the definition of the type itself – it is just an abstract tag, essentially defining an entire family of types with identical structure, differentiated only by their type parameter. Thus, Ptr{Float64} and Ptr{Int64} are distinct types, even though they have identical representations. And of course, all specific pointer types are subtypes of the umbrella Ptr type:julia> Ptr{Float64} <: Ptr\ntrue\n\njulia> Ptr{Int64} <: Ptr\ntrue" -}, - -{ - "location": "manual/types.html#UnionAll-Types-1", - "page": "Types", - "title": "UnionAll Types", - "category": "section", - "text": "We have said that a parametric type like Ptr acts as a supertype of all its instances (Ptr{Int64} etc.). How does this work? Ptr itself cannot be a normal data type, since without knowing the type of the referenced data the type clearly cannot be used for memory operations. The answer is that Ptr (or other parametric types like Array) is a different kind of type called a UnionAll type. Such a type expresses the iterated union of types for all values of some parameter.UnionAll types are usually written using the keyword where. For example Ptr could be more accurately written as Ptr{T} where T, meaning all values whose type is Ptr{T} for some value of T. In this context, the parameter T is also often called a \"type variable\" since it is like a variable that ranges over types. Each where introduces a single type variable, so these expressions are nested for types with multiple parameters, for example Array{T,N} where N where T.The type application syntax A{B,C} requires A to be a UnionAll type, and first substitutes B for the outermost type variable in A. The result is expected to be another UnionAll type, into which C is then substituted. So A{B,C} is equivalent to A{B}{C}. This explains why it is possible to partially instantiate a type, as in Array{Float64}: the first parameter value has been fixed, but the second still ranges over all possible values. Using explicit where syntax, any subset of parameters can be fixed. For example, the type of all 1-dimensional arrays can be written as Array{T,1} where T.Type variables can be restricted with subtype relations. Array{T} where T<:Integer refers to all arrays whose element type is some kind of Integer. The syntax Array{<:Integer} is a convenient shorthand for Array{T} where T<:Integer. Type variables can have both lower and upper bounds. Array{T} where Int<:T<:Number refers to all arrays of Numbers that are able to contain Ints (since T must be at least as big as Int). The syntax where T>:Int also works to specify only the lower bound of a type variable, and Array{>:Int} is equivalent to Array{T} where T>:Int.Since where expressions nest, type variable bounds can refer to outer type variables. For example Tuple{T,Array{S}} where S<:AbstractArray{T} where T<:Real refers to 2-tuples whose first element is some Real, and whose second element is an Array of any kind of array whose element type contains the type of the first tuple element.The where keyword itself can be nested inside a more complex declaration. For example, consider the two types created by the following declarations:julia> const T1 = Array{Array{T,1} where T, 1}\nArray{Array{T,1} where T,1}\n\njulia> const T2 = Array{Array{T,1}, 1} where T\nArray{Array{T,1},1} where TType T1 defines a 1-dimensional array of 1-dimensional arrays; each of the inner arrays consists of objects of the same type, but this type may vary from one inner array to the next. On the other hand, type T2 defines a 1-dimensional array of 1-dimensional arrays all of whose inner arrays must have the same type. Note that T2 is an abstract type, e.g., Array{Array{Int,1},1} <: T2, whereas T1 is a concrete type. As a consequence, T1 can be constructed with a zero-argument constructor a=T1() but T2 cannot.There is a convenient syntax for naming such types, similar to the short form of function definition syntax:Vector{T} = Array{T,1}This is equivalent to const Vector = Array{T,1} where T. Writing Vector{Float64} is equivalent to writing Array{Float64,1}, and the umbrella type Vector has as instances all Array objects where the second parameter – the number of array dimensions – is 1, regardless of what the element type is. In languages where parametric types must always be specified in full, this is not especially helpful, but in Julia, this allows one to write just Vector for the abstract type including all one-dimensional dense arrays of any element type." -}, - -{ - "location": "manual/types.html#Type-Aliases-1", - "page": "Types", - "title": "Type Aliases", - "category": "section", - "text": "Sometimes it is convenient to introduce a new name for an already expressible type. This can be done with a simple assignment statement. For example, UInt is aliased to either UInt32 or UInt64 as is appropriate for the size of pointers on the system:# 32-bit system:\njulia> UInt\nUInt32\n\n# 64-bit system:\njulia> UInt\nUInt64This is accomplished via the following code in base/boot.jl:if Int === Int64\n const UInt = UInt64\nelse\n const UInt = UInt32\nendOf course, this depends on what Int is aliased to – but that is predefined to be the correct type – either Int32 or Int64.(Note that unlike Int, Float does not exist as a type alias for a specific sized AbstractFloat. Unlike with integer registers, the floating point register sizes are specified by the IEEE-754 standard. Whereas the size of Int reflects the size of a native pointer on that machine.)" -}, - -{ - "location": "manual/types.html#Operations-on-Types-1", - "page": "Types", - "title": "Operations on Types", - "category": "section", - "text": "Since types in Julia are themselves objects, ordinary functions can operate on them. Some functions that are particularly useful for working with or exploring types have already been introduced, such as the <: operator, which indicates whether its left hand operand is a subtype of its right hand operand.The isa function tests if an object is of a given type and returns true or false:julia> isa(1, Int)\ntrue\n\njulia> isa(1, AbstractFloat)\nfalseThe typeof() function, already used throughout the manual in examples, returns the type of its argument. Since, as noted above, types are objects, they also have types, and we can ask what their types are:julia> typeof(Rational{Int})\nDataType\n\njulia> typeof(Union{Real,Float64,Rational})\nDataType\n\njulia> typeof(Union{Real,String})\nUnionWhat if we repeat the process? What is the type of a type of a type? As it happens, types are all composite values and thus all have a type of DataType:julia> typeof(DataType)\nDataType\n\njulia> typeof(Union)\nDataTypeDataType is its own type.Another operation that applies to some types is supertype(), which reveals a type\'s supertype. Only declared types (DataType) have unambiguous supertypes:julia> supertype(Float64)\nAbstractFloat\n\njulia> supertype(Number)\nAny\n\njulia> supertype(AbstractString)\nAny\n\njulia> supertype(Any)\nAnyIf you apply supertype() to other type objects (or non-type objects), a MethodError is raised:julia> supertype(Union{Float64,Int64})\nERROR: MethodError: no method matching supertype(::Type{Union{Float64, Int64}})\nClosest candidates are:\n supertype(!Matched::DataType) at operators.jl:41\n supertype(!Matched::UnionAll) at operators.jl:46" -}, - -{ - "location": "manual/types.html#Custom-pretty-printing-1", - "page": "Types", - "title": "Custom pretty-printing", - "category": "section", - "text": "Often, one wants to customize how instances of a type are displayed. This is accomplished by overloading the show() function. For example, suppose we define a type to represent complex numbers in polar form:julia> struct Polar{T<:Real} <: Number\n r::T\n Θ::T\n end\n\njulia> Polar(r::Real,Θ::Real) = Polar(promote(r,Θ)...)\nPolarHere, we\'ve added a custom constructor function so that it can take arguments of different Real types and promote them to a common type (see Constructors and Conversion and Promotion). (Of course, we would have to define lots of other methods, too, to make it act like a Number, e.g. +, *, one, zero, promotion rules and so on.) By default, instances of this type display rather simply, with information about the type name and the field values, as e.g. Polar{Float64}(3.0,4.0).If we want it to display instead as 3.0 * exp(4.0im), we would define the following method to print the object to a given output object io (representing a file, terminal, buffer, etcetera; see Networking and Streams):julia> Base.show(io::IO, z::Polar) = print(io, z.r, \" * exp(\", z.Θ, \"im)\")More fine-grained control over display of Polar objects is possible. In particular, sometimes one wants both a verbose multi-line printing format, used for displaying a single object in the REPL and other interactive environments, and also a more compact single-line format used for print() or for displaying the object as part of another object (e.g. in an array). Although by default the show(io, z) function is called in both cases, you can define a different multi-line format for displaying an object by overloading a three-argument form of show that takes the text/plain MIME type as its second argument (see Multimedia I/O), for example:julia> Base.show{T}(io::IO, ::MIME\"text/plain\", z::Polar{T}) =\n print(io, \"Polar{$T} complex number:\\n \", z)(Note that print(..., z) here will call the 2-argument show(io, z) method.) This results in:julia> Polar(3, 4.0)\nPolar{Float64} complex number:\n 3.0 * exp(4.0im)\n\njulia> [Polar(3, 4.0), Polar(4.0,5.3)]\n2-element Array{Polar{Float64},1}:\n 3.0 * exp(4.0im)\n 4.0 * exp(5.3im)where the single-line show(io, z) form is still used for an array of Polar values. Technically, the REPL calls display(z) to display the result of executing a line, which defaults to show(STDOUT, MIME(\"text/plain\"), z), which in turn defaults to show(STDOUT, z), but you should not define new display() methods unless you are defining a new multimedia display handler (see Multimedia I/O).Moreover, you can also define show methods for other MIME types in order to enable richer display (HTML, images, etcetera) of objects in environments that support this (e.g. IJulia). For example, we can define formatted HTML display of Polar objects, with superscripts and italics, via:julia> Base.show{T}(io::IO, ::MIME\"text/html\", z::Polar{T}) =\n println(io, \"Polar{$T} complex number: \",\n z.r, \" e\", z.Θ, \" i\")A Polar object will then display automatically using HTML in an environment that supports HTML display, but you can call show manually to get HTML output if you want:julia> show(STDOUT, \"text/html\", Polar(3.0,4.0))\nPolar{Float64} complex number: 3.0 e4.0 i

      An HTML renderer would display this as: Polar{Float64} complex number: 3.0 e4.0 i

      " -}, - -{ - "location": "manual/types.html#\"Value-types\"-1", - "page": "Types", - "title": "\"Value types\"", - "category": "section", - "text": "In Julia, you can\'t dispatch on a value such as true or false. However, you can dispatch on parametric types, and Julia allows you to include \"plain bits\" values (Types, Symbols, Integers, floating-point numbers, tuples, etc.) as type parameters. A common example is the dimensionality parameter in Array{T,N}, where T is a type (e.g., Float64) but N is just an Int.You can create your own custom types that take values as parameters, and use them to control dispatch of custom types. By way of illustration of this idea, let\'s introduce a parametric type, Val{T}, which serves as a customary way to exploit this technique for cases where you don\'t need a more elaborate hierarchy.Val is defined as:julia> struct Val{T}\n endThere is no more to the implementation of Val than this. Some functions in Julia\'s standard library accept Val types as arguments, and you can also use it to write your own functions. For example:julia> firstlast(::Type{Val{true}}) = \"First\"\nfirstlast (generic function with 1 method)\n\njulia> firstlast(::Type{Val{false}}) = \"Last\"\nfirstlast (generic function with 2 methods)\n\njulia> firstlast(Val{true})\n\"First\"\n\njulia> firstlast(Val{false})\n\"Last\"For consistency across Julia, the call site should always pass a Valtype rather than creating an instance, i.e., use foo(Val{:bar}) rather than foo(Val{:bar}()).It\'s worth noting that it\'s extremely easy to mis-use parametric \"value\" types, including Val; in unfavorable cases, you can easily end up making the performance of your code much worse. In particular, you would never want to write actual code as illustrated above. For more information about the proper (and improper) uses of Val, please read the more extensive discussion in the performance tips." -}, - -{ - "location": "manual/types.html#man-nullable-types-1", - "page": "Types", - "title": "Nullable Types: Representing Missing Values", - "category": "section", - "text": "In many settings, you need to interact with a value of type T that may or may not exist. To handle these settings, Julia provides a parametric type called Nullable{T}, which can be thought of as a specialized container type that can contain either zero or one values. Nullable{T} provides a minimal interface designed to ensure that interactions with missing values are safe. At present, the interface consists of several possible interactions:Construct a Nullable object.\nCheck if a Nullable object has a missing value.\nAccess the value of a Nullable object with a guarantee that a NullException will be thrown if the object\'s value is missing.\nAccess the value of a Nullable object with a guarantee that a default value of type T will be returned if the object\'s value is missing.\nPerform an operation on the value (if it exists) of a Nullable object, getting a Nullable result. The result will be missing if the original value was missing.\nPerforming a test on the value (if it exists) of a Nullable object, getting a result that is missing if either the Nullable itself was missing, or the test failed.\nPerform general operations on single Nullable objects, propagating the missing data." -}, - -{ - "location": "manual/types.html#Constructing-[Nullable](@ref)-objects-1", - "page": "Types", - "title": "Constructing Nullable objects", - "category": "section", - "text": "To construct an object representing a missing value of type T, use the Nullable{T}() function:julia> x1 = Nullable{Int64}()\nNullable{Int64}()\n\njulia> x2 = Nullable{Float64}()\nNullable{Float64}()\n\njulia> x3 = Nullable{Vector{Int64}}()\nNullable{Array{Int64,1}}()To construct an object representing a non-missing value of type T, use the Nullable(x::T) function:julia> x1 = Nullable(1)\nNullable{Int64}(1)\n\njulia> x2 = Nullable(1.0)\nNullable{Float64}(1.0)\n\njulia> x3 = Nullable([1, 2, 3])\nNullable{Array{Int64,1}}([1, 2, 3])Note the core distinction between these two ways of constructing a Nullable object: in one style, you provide a type, T, as a function parameter; in the other style, you provide a single value of type T as an argument." -}, - -{ - "location": "manual/types.html#Checking-if-a-Nullable-object-has-a-value-1", - "page": "Types", - "title": "Checking if a Nullable object has a value", - "category": "section", - "text": "You can check if a Nullable object has any value using isnull():julia> isnull(Nullable{Float64}())\ntrue\n\njulia> isnull(Nullable(0.0))\nfalse" -}, - -{ - "location": "manual/types.html#Safely-accessing-the-value-of-a-Nullable-object-1", - "page": "Types", - "title": "Safely accessing the value of a Nullable object", - "category": "section", - "text": "You can safely access the value of a Nullable object using get():julia> get(Nullable{Float64}())\nERROR: NullException()\nStacktrace:\n [1] get(::Nullable{Float64}) at ./nullable.jl:92\n\njulia> get(Nullable(1.0))\n1.0If the value is not present, as it would be for Nullable{Float64}, a NullException error will be thrown. The error-throwing nature of the get() function ensures that any attempt to access a missing value immediately fails.In cases for which a reasonable default value exists that could be used when a Nullable object\'s value turns out to be missing, you can provide this default value as a second argument to get():julia> get(Nullable{Float64}(), 0.0)\n0.0\n\njulia> get(Nullable(1.0), 0.0)\n1.0tip: Tip\nMake sure the type of the default value passed to get() and that of the Nullable object match to avoid type instability, which could hurt performance. Use convert() manually if needed." -}, - -{ - "location": "manual/types.html#Performing-operations-on-Nullable-objects-1", - "page": "Types", - "title": "Performing operations on Nullable objects", - "category": "section", - "text": "Nullable objects represent values that are possibly missing, and it is possible to write all code using these objects by first testing to see if the value is missing with isnull(), and then doing an appropriate action. However, there are some common use cases where the code could be more concise or clear by using a higher-order function.The map function takes as arguments a function f and a Nullable value x. It produces a Nullable:If x is a missing value, then it produces a missing value;\nIf x has a value, then it produces a Nullable containing f(get(x)) as value.This is useful for performing simple operations on values that might be missing if the desired behaviour is to simply propagate the missing values forward.The filter function takes as arguments a predicate function p (that is, a function returning a boolean) and a Nullable value x. It produces a Nullable value:If x is a missing value, then it produces a missing value;\nIf p(get(x)) is true, then it produces the original value x;\nIf p(get(x)) is false, then it produces a missing value.In this way, filter can be thought of as selecting only allowable values, and converting non-allowable values to missing values.While map and filter are useful in specific cases, by far the most useful higher-order function is broadcast, which can handle a wide variety of cases, including making existing operations work and propagate Nullables. An example will motivate the need for broadcast. Suppose we have a function that computes the greater of two real roots of a quadratic equation, using the quadratic formula:julia> root(a::Real, b::Real, c::Real) = (-b + √(b^2 - 4a*c)) / 2a\nroot (generic function with 1 method)We may verify that the result of root(1, -9, 20) is 5.0, as we expect, since 5.0 is the greater of two real roots of the quadratic equation.Suppose now that we want to find the greatest real root of a quadratic equations where the coefficients might be missing values. Having missing values in datasets is a common occurrence in real-world data, and so it is important to be able to deal with them. But we cannot find the roots of an equation if we do not know all the coefficients. The best solution to this will depend on the particular use case; perhaps we should throw an error. However, for this example, we will assume that the best solution is to propagate the missing values forward; that is, if any input is missing, we simply produce a missing output.The broadcast() function makes this task easy; we can simply pass the root function we wrote to broadcast:julia> broadcast(root, Nullable(1), Nullable(-9), Nullable(20))\nNullable{Float64}(5.0)\n\njulia> broadcast(root, Nullable(1), Nullable{Int}(), Nullable{Int}())\nNullable{Float64}()\n\njulia> broadcast(root, Nullable{Int}(), Nullable(-9), Nullable(20))\nNullable{Float64}()If one or more of the inputs is missing, then the output of broadcast() will be missing.There exists special syntactic sugar for the broadcast() function using a dot notation:julia> root.(Nullable(1), Nullable(-9), Nullable(20))\nNullable{Float64}(5.0)In particular, the regular arithmetic operators can be broadcast() conveniently using .-prefixed operators:julia> Nullable(2) ./ Nullable(3) .+ Nullable(1.0)\nNullable{Float64}(1.66667)" -}, - -{ - "location": "manual/methods.html#", - "page": "Methods", - "title": "Methods", - "category": "page", - "text": "" -}, - -{ - "location": "manual/methods.html#Methods-1", - "page": "Methods", - "title": "Methods", - "category": "section", - "text": "Recall from Functions that a function is an object that maps a tuple of arguments to a return value, or throws an exception if no appropriate value can be returned. It is common for the same conceptual function or operation to be implemented quite differently for different types of arguments: adding two integers is very different from adding two floating-point numbers, both of which are distinct from adding an integer to a floating-point number. Despite their implementation differences, these operations all fall under the general concept of \"addition\". Accordingly, in Julia, these behaviors all belong to a single object: the + function.To facilitate using many different implementations of the same concept smoothly, functions need not be defined all at once, but can rather be defined piecewise by providing specific behaviors for certain combinations of argument types and counts. A definition of one possible behavior for a function is called a method. Thus far, we have presented only examples of functions defined with a single method, applicable to all types of arguments. However, the signatures of method definitions can be annotated to indicate the types of arguments in addition to their number, and more than a single method definition may be provided. When a function is applied to a particular tuple of arguments, the most specific method applicable to those arguments is applied. Thus, the overall behavior of a function is a patchwork of the behaviors of its various method definitions. If the patchwork is well designed, even though the implementations of the methods may be quite different, the outward behavior of the function will appear seamless and consistent.The choice of which method to execute when a function is applied is called dispatch. Julia allows the dispatch process to choose which of a function\'s methods to call based on the number of arguments given, and on the types of all of the function\'s arguments. This is different than traditional object-oriented languages, where dispatch occurs based only on the first argument, which often has a special argument syntax, and is sometimes implied rather than explicitly written as an argument. [1] Using all of a function\'s arguments to choose which method should be invoked, rather than just the first, is known as multiple dispatch. Multiple dispatch is particularly useful for mathematical code, where it makes little sense to artificially deem the operations to \"belong\" to one argument more than any of the others: does the addition operation in x + y belong to x any more than it does to y? The implementation of a mathematical operator generally depends on the types of all of its arguments. Even beyond mathematical operations, however, multiple dispatch ends up being a powerful and convenient paradigm for structuring and organizing programs.[1]: In C++ or Java, for example, in a method call like obj.meth(arg1,arg2), the object obj \"receives\" the method call and is implicitly passed to the method via the this keyword, rather than as an explicit method argument. When the current this object is the receiver of a method call, it can be omitted altogether, writing just meth(arg1,arg2), with this implied as the receiving object." -}, - -{ - "location": "manual/methods.html#Defining-Methods-1", - "page": "Methods", - "title": "Defining Methods", - "category": "section", - "text": "Until now, we have, in our examples, defined only functions with a single method having unconstrained argument types. Such functions behave just like they would in traditional dynamically typed languages. Nevertheless, we have used multiple dispatch and methods almost continually without being aware of it: all of Julia\'s standard functions and operators, like the aforementioned + function, have many methods defining their behavior over various possible combinations of argument type and count.When defining a function, one can optionally constrain the types of parameters it is applicable to, using the :: type-assertion operator, introduced in the section on Composite Types:julia> f(x::Float64, y::Float64) = 2x + y\nf (generic function with 1 method)This function definition applies only to calls where x and y are both values of type Float64:julia> f(2.0, 3.0)\n7.0Applying it to any other types of arguments will result in a MethodError:julia> f(2.0, 3)\nERROR: MethodError: no method matching f(::Float64, ::Int64)\nClosest candidates are:\n f(::Float64, !Matched::Float64) at none:1\n\njulia> f(Float32(2.0), 3.0)\nERROR: MethodError: no method matching f(::Float32, ::Float64)\nClosest candidates are:\n f(!Matched::Float64, ::Float64) at none:1\n\njulia> f(2.0, \"3.0\")\nERROR: MethodError: no method matching f(::Float64, ::String)\nClosest candidates are:\n f(::Float64, !Matched::Float64) at none:1\n\njulia> f(\"2.0\", \"3.0\")\nERROR: MethodError: no method matching f(::String, ::String)As you can see, the arguments must be precisely of type Float64. Other numeric types, such as integers or 32-bit floating-point values, are not automatically converted to 64-bit floating-point, nor are strings parsed as numbers. Because Float64 is a concrete type and concrete types cannot be subclassed in Julia, such a definition can only be applied to arguments that are exactly of type Float64. It may often be useful, however, to write more general methods where the declared parameter types are abstract:julia> f(x::Number, y::Number) = 2x - y\nf (generic function with 2 methods)\n\njulia> f(2.0, 3)\n1.0This method definition applies to any pair of arguments that are instances of Number. They need not be of the same type, so long as they are each numeric values. The problem of handling disparate numeric types is delegated to the arithmetic operations in the expression 2x - y.To define a function with multiple methods, one simply defines the function multiple times, with different numbers and types of arguments. The first method definition for a function creates the function object, and subsequent method definitions add new methods to the existing function object. The most specific method definition matching the number and types of the arguments will be executed when the function is applied. Thus, the two method definitions above, taken together, define the behavior for f over all pairs of instances of the abstract type Number – but with a different behavior specific to pairs of Float64 values. If one of the arguments is a 64-bit float but the other one is not, then the f(Float64,Float64) method cannot be called and the more general f(Number,Number) method must be used:julia> f(2.0, 3.0)\n7.0\n\njulia> f(2, 3.0)\n1.0\n\njulia> f(2.0, 3)\n1.0\n\njulia> f(2, 3)\n1The 2x + y definition is only used in the first case, while the 2x - y definition is used in the others. No automatic casting or conversion of function arguments is ever performed: all conversion in Julia is non-magical and completely explicit. Conversion and Promotion, however, shows how clever application of sufficiently advanced technology can be indistinguishable from magic. [Clarke61]For non-numeric values, and for fewer or more than two arguments, the function f remains undefined, and applying it will still result in a MethodError:julia> f(\"foo\", 3)\nERROR: MethodError: no method matching f(::String, ::Int64)\nClosest candidates are:\n f(!Matched::Number, ::Number) at none:1\n\njulia> f()\nERROR: MethodError: no method matching f()\nClosest candidates are:\n f(!Matched::Float64, !Matched::Float64) at none:1\n f(!Matched::Number, !Matched::Number) at none:1You can easily see which methods exist for a function by entering the function object itself in an interactive session:julia> f\nf (generic function with 2 methods)This output tells us that f is a function object with two methods. To find out what the signatures of those methods are, use the methods() function:julia> methods(f)\n# 2 methods for generic function \"f\":\nf(x::Float64, y::Float64) in Main at none:1\nf(x::Number, y::Number) in Main at none:1which shows that f has two methods, one taking two Float64 arguments and one taking arguments of type Number. It also indicates the file and line number where the methods were defined: because these methods were defined at the REPL, we get the apparent line number none:1.In the absence of a type declaration with ::, the type of a method parameter is Any by default, meaning that it is unconstrained since all values in Julia are instances of the abstract type Any. Thus, we can define a catch-all method for f like so:julia> f(x,y) = println(\"Whoa there, Nelly.\")\nf (generic function with 3 methods)\n\njulia> f(\"foo\", 1)\nWhoa there, Nelly.This catch-all is less specific than any other possible method definition for a pair of parameter values, so it will only be called on pairs of arguments to which no other method definition applies.Although it seems a simple concept, multiple dispatch on the types of values is perhaps the single most powerful and central feature of the Julia language. Core operations typically have dozens of methods:julia> methods(+)\n# 180 methods for generic function \"+\":\n+(x::Bool, z::Complex{Bool}) in Base at complex.jl:224\n+(x::Bool, y::Bool) in Base at bool.jl:89\n+(x::Bool) in Base at bool.jl:86\n+(x::Bool, y::T) where T<:AbstractFloat in Base at bool.jl:96\n+(x::Bool, z::Complex) in Base at complex.jl:231\n+(a::Float16, b::Float16) in Base at float.jl:372\n+(x::Float32, y::Float32) in Base at float.jl:374\n+(x::Float64, y::Float64) in Base at float.jl:375\n+(z::Complex{Bool}, x::Bool) in Base at complex.jl:225\n+(z::Complex{Bool}, x::Real) in Base at complex.jl:239\n+(x::Char, y::Integer) in Base at char.jl:40\n+(c::BigInt, x::BigFloat) in Base.MPFR at mpfr.jl:303\n+(a::BigInt, b::BigInt, c::BigInt, d::BigInt, e::BigInt) in Base.GMP at gmp.jl:303\n+(a::BigInt, b::BigInt, c::BigInt, d::BigInt) in Base.GMP at gmp.jl:296\n+(a::BigInt, b::BigInt, c::BigInt) in Base.GMP at gmp.jl:290\n+(x::BigInt, y::BigInt) in Base.GMP at gmp.jl:258\n+(x::BigInt, c::Union{UInt16, UInt32, UInt64, UInt8}) in Base.GMP at gmp.jl:315\n...\n+(a, b, c, xs...) at operators.jl:119Multiple dispatch together with the flexible parametric type system give Julia its ability to abstractly express high-level algorithms decoupled from implementation details, yet generate efficient, specialized code to handle each case at run time." -}, - -{ - "location": "manual/methods.html#man-ambiguities-1", - "page": "Methods", - "title": "Method Ambiguities", - "category": "section", - "text": "It is possible to define a set of function methods such that there is no unique most specific method applicable to some combinations of arguments:julia> g(x::Float64, y) = 2x + y\ng (generic function with 1 method)\n\njulia> g(x, y::Float64) = x + 2y\ng (generic function with 2 methods)\n\njulia> g(2.0, 3)\n7.0\n\njulia> g(2, 3.0)\n8.0\n\njulia> g(2.0, 3.0)\nERROR: MethodError: g(::Float64, ::Float64) is ambiguous.\n[...]Here the call g(2.0, 3.0) could be handled by either the g(Float64, Any) or the g(Any, Float64) method, and neither is more specific than the other. In such cases, Julia raises a MethodError rather than arbitrarily picking a method. You can avoid method ambiguities by specifying an appropriate method for the intersection case:julia> g(x::Float64, y::Float64) = 2x + 2y\ng (generic function with 3 methods)\n\njulia> g(2.0, 3)\n7.0\n\njulia> g(2, 3.0)\n8.0\n\njulia> g(2.0, 3.0)\n10.0It is recommended that the disambiguating method be defined first, since otherwise the ambiguity exists, if transiently, until the more specific method is defined.In more complex cases, resolving method ambiguities involves a certain element of design; this topic is explored further below." -}, - -{ - "location": "manual/methods.html#Parametric-Methods-1", - "page": "Methods", - "title": "Parametric Methods", - "category": "section", - "text": "Method definitions can optionally have type parameters qualifying the signature:julia> same_type(x::T, y::T) where {T} = true\nsame_type (generic function with 1 method)\n\njulia> same_type(x,y) = false\nsame_type (generic function with 2 methods)The first method applies whenever both arguments are of the same concrete type, regardless of what type that is, while the second method acts as a catch-all, covering all other cases. Thus, overall, this defines a boolean function that checks whether its two arguments are of the same type:julia> same_type(1, 2)\ntrue\n\njulia> same_type(1, 2.0)\nfalse\n\njulia> same_type(1.0, 2.0)\ntrue\n\njulia> same_type(\"foo\", 2.0)\nfalse\n\njulia> same_type(\"foo\", \"bar\")\ntrue\n\njulia> same_type(Int32(1), Int64(2))\nfalseSuch definitions correspond to methods whose type signatures are UnionAll types (see UnionAll Types).This kind of definition of function behavior by dispatch is quite common – idiomatic, even – in Julia. Method type parameters are not restricted to being used as the types of arguments: they can be used anywhere a value would be in the signature of the function or body of the function. Here\'s an example where the method type parameter T is used as the type parameter to the parametric type Vector{T} in the method signature:julia> myappend(v::Vector{T}, x::T) where {T} = [v..., x]\nmyappend (generic function with 1 method)\n\njulia> myappend([1,2,3],4)\n4-element Array{Int64,1}:\n 1\n 2\n 3\n 4\n\njulia> myappend([1,2,3],2.5)\nERROR: MethodError: no method matching myappend(::Array{Int64,1}, ::Float64)\nClosest candidates are:\n myappend(::Array{T,1}, !Matched::T) where T at none:1\n\njulia> myappend([1.0,2.0,3.0],4.0)\n4-element Array{Float64,1}:\n 1.0\n 2.0\n 3.0\n 4.0\n\njulia> myappend([1.0,2.0,3.0],4)\nERROR: MethodError: no method matching myappend(::Array{Float64,1}, ::Int64)\nClosest candidates are:\n myappend(::Array{T,1}, !Matched::T) where T at none:1As you can see, the type of the appended element must match the element type of the vector it is appended to, or else a MethodError is raised. In the following example, the method type parameter T is used as the return value:julia> mytypeof(x::T) where {T} = T\nmytypeof (generic function with 1 method)\n\njulia> mytypeof(1)\nInt64\n\njulia> mytypeof(1.0)\nFloat64Just as you can put subtype constraints on type parameters in type declarations (see Parametric Types), you can also constrain type parameters of methods:julia> same_type_numeric(x::T, y::T) where {T<:Number} = true\nsame_type_numeric (generic function with 1 method)\n\njulia> same_type_numeric(x::Number, y::Number) = false\nsame_type_numeric (generic function with 2 methods)\n\njulia> same_type_numeric(1, 2)\ntrue\n\njulia> same_type_numeric(1, 2.0)\nfalse\n\njulia> same_type_numeric(1.0, 2.0)\ntrue\n\njulia> same_type_numeric(\"foo\", 2.0)\nERROR: MethodError: no method matching same_type_numeric(::String, ::Float64)\nClosest candidates are:\n same_type_numeric(!Matched::T<:Number, ::T<:Number) where T<:Number at none:1\n same_type_numeric(!Matched::Number, ::Number) at none:1\n\njulia> same_type_numeric(\"foo\", \"bar\")\nERROR: MethodError: no method matching same_type_numeric(::String, ::String)\n\njulia> same_type_numeric(Int32(1), Int64(2))\nfalseThe same_type_numeric function behaves much like the same_type function defined above, but is only defined for pairs of numbers.Parametric methods allow the same syntax as where expressions used to write types (see UnionAll Types). If there is only a single parameter, the enclosing curly braces (in where {T}) can be omitted, but are often preferred for clarity. Multiple parameters can be separated with commas, e.g. where {T, S<:Real}, or written using nested where, e.g. where S<:Real where T." -}, - -{ - "location": "manual/methods.html#Redefining-Methods-1", - "page": "Methods", - "title": "Redefining Methods", - "category": "section", - "text": "When redefining a method or adding new methods, it is important to realize that these changes don\'t take effect immediately. This is key to Julia\'s ability to statically infer and compile code to run fast, without the usual JIT tricks and overhead. Indeed, any new method definition won\'t be visible to the current runtime environment, including Tasks and Threads (and any previously defined @generated functions). Let\'s start with an example to see what this means:julia> function tryeval()\n @eval newfun() = 1\n newfun()\n end\ntryeval (generic function with 1 method)\n\njulia> tryeval()\nERROR: MethodError: no method matching newfun()\nThe applicable method may be too new: running in world age xxxx1, while current world is xxxx2.\nClosest candidates are:\n newfun() at none:1 (method too new to be called from this world context.)\n in tryeval() at none:1\n ...\n\njulia> newfun()\n1In this example, observe that the new definition for newfun has been created, but can\'t be immediately called. The new global is immediately visible to the tryeval function, so you could write return newfun (without parentheses). But neither you, nor any of your callers, nor the functions they call, or etc. can call this new method definition!But there\'s an exception: future calls to newfun from the REPL work as expected, being able to both see and call the new definition of newfun.However, future calls to tryeval will continue to see the definition of newfun as it was at the previous statement at the REPL, and thus before that call to tryeval.You may want to try this for yourself to see how it works.The implementation of this behavior is a \"world age counter\". This monotonically increasing value tracks each method definition operation. This allows describing \"the set of method definitions visible to a given runtime environment\" as a single number, or \"world age\". It also allows comparing the methods available in two worlds just by comparing their ordinal value. In the example above, we see that the \"current world\" (in which the method newfun() exists), is one greater than the task-local \"runtime world\" that was fixed when the execution of tryeval started.Sometimes it is necessary to get around this (for example, if you are implementing the above REPL). Fortunately, there is an easy solution: call the function using Base.invokelatest:julia> function tryeval2()\n @eval newfun2() = 2\n Base.invokelatest(newfun2)\n end\ntryeval2 (generic function with 1 method)\n\njulia> tryeval2()\n2Finally, let\'s take a look at some more complex examples where this rule comes into play. Define a function f(x), which initially has one method:julia> f(x) = \"original definition\"\nf (generic function with 1 method)Start some other operations that use f(x):julia> g(x) = f(x)\ng (generic function with 1 method)\n\njulia> t = @async f(wait()); yield();Now we add some new methods to f(x):julia> f(x::Int) = \"definition for Int\"\nf (generic function with 2 methods)\n\njulia> f(x::Type{Int}) = \"definition for Type{Int}\"\nf (generic function with 3 methods)Compare how these results differ:julia> f(1)\n\"definition for Int\"\n\njulia> g(1)\n\"definition for Int\"\n\njulia> wait(schedule(t, 1))\n\"original definition\"\n\njulia> t = @async f(wait()); yield();\n\njulia> wait(schedule(t, 1))\n\"definition for Int\"" -}, - -{ - "location": "manual/methods.html#Parametrically-constrained-Varargs-methods-1", - "page": "Methods", - "title": "Parametrically-constrained Varargs methods", - "category": "section", - "text": "Function parameters can also be used to constrain the number of arguments that may be supplied to a \"varargs\" function (Varargs Functions). The notation Vararg{T,N} is used to indicate such a constraint. For example:julia> bar(a,b,x::Vararg{Any,2}) = (a,b,x)\nbar (generic function with 1 method)\n\njulia> bar(1,2,3)\nERROR: MethodError: no method matching bar(::Int64, ::Int64, ::Int64)\nClosest candidates are:\n bar(::Any, ::Any, ::Any, !Matched::Any) at none:1\n\njulia> bar(1,2,3,4)\n(1, 2, (3, 4))\n\njulia> bar(1,2,3,4,5)\nERROR: MethodError: no method matching bar(::Int64, ::Int64, ::Int64, ::Int64, ::Int64)\nClosest candidates are:\n bar(::Any, ::Any, ::Any, ::Any) at none:1More usefully, it is possible to constrain varargs methods by a parameter. For example:function getindex(A::AbstractArray{T,N}, indexes::Vararg{Number,N}) where {T,N}would be called only when the number of indexes matches the dimensionality of the array." -}, - -{ - "location": "manual/methods.html#Note-on-Optional-and-keyword-Arguments-1", - "page": "Methods", - "title": "Note on Optional and keyword Arguments", - "category": "section", - "text": "As mentioned briefly in Functions, optional arguments are implemented as syntax for multiple method definitions. For example, this definition:f(a=1,b=2) = a+2btranslates to the following three methods:f(a,b) = a+2b\nf(a) = f(a,2)\nf() = f(1,2)This means that calling f() is equivalent to calling f(1,2). In this case the result is 5, because f(1,2) invokes the first method of f above. However, this need not always be the case. If you define a fourth method that is more specialized for integers:f(a::Int,b::Int) = a-2bthen the result of both f() and f(1,2) is -3. In other words, optional arguments are tied to a function, not to any specific method of that function. It depends on the types of the optional arguments which method is invoked. When optional arguments are defined in terms of a global variable, the type of the optional argument may even change at run-time.Keyword arguments behave quite differently from ordinary positional arguments. In particular, they do not participate in method dispatch. Methods are dispatched based only on positional arguments, with keyword arguments processed after the matching method is identified." -}, - -{ - "location": "manual/methods.html#Function-like-objects-1", - "page": "Methods", - "title": "Function-like objects", - "category": "section", - "text": "Methods are associated with types, so it is possible to make any arbitrary Julia object \"callable\" by adding methods to its type. (Such \"callable\" objects are sometimes called \"functors.\")For example, you can define a type that stores the coefficients of a polynomial, but behaves like a function evaluating the polynomial:julia> struct Polynomial{R}\n coeffs::Vector{R}\n end\n\njulia> function (p::Polynomial)(x)\n v = p.coeffs[end]\n for i = (length(p.coeffs)-1):-1:1\n v = v*x + p.coeffs[i]\n end\n return v\n endNotice that the function is specified by type instead of by name. In the function body, p will refer to the object that was called. A Polynomial can be used as follows:julia> p = Polynomial([1,10,100])\nPolynomial{Int64}([1, 10, 100])\n\njulia> p(3)\n931This mechanism is also the key to how type constructors and closures (inner functions that refer to their surrounding environment) work in Julia, discussed later in the manual." -}, - -{ - "location": "manual/methods.html#Empty-generic-functions-1", - "page": "Methods", - "title": "Empty generic functions", - "category": "section", - "text": "Occasionally it is useful to introduce a generic function without yet adding methods. This can be used to separate interface definitions from implementations. It might also be done for the purpose of documentation or code readability. The syntax for this is an empty function block without a tuple of arguments:function emptyfunc\nend" -}, - -{ - "location": "manual/methods.html#man-method-design-ambiguities-1", - "page": "Methods", - "title": "Method design and the avoidance of ambiguities", - "category": "section", - "text": "Julia\'s method polymorphism is one of its most powerful features, yet exploiting this power can pose design challenges. In particular, in more complex method hierarchies it is not uncommon for ambiguities to arise.Above, it was pointed out that one can resolve ambiguities likef(x, y::Int) = 1\nf(x::Int, y) = 2by defining a methodf(x::Int, y::Int) = 3This is often the right strategy; however, there are circumstances where following this advice blindly can be counterproductive. In particular, the more methods a generic function has, the more possibilities there are for ambiguities. When your method hierarchies get more complicated than this simple example, it can be worth your while to think carefully about alternative strategies.Below we discuss particular challenges and some alternative ways to resolve such issues." -}, - -{ - "location": "manual/methods.html#Tuple-and-NTuple-arguments-1", - "page": "Methods", - "title": "Tuple and NTuple arguments", - "category": "section", - "text": "Tuple (and NTuple) arguments present special challenges. For example,f(x::NTuple{N,Int}) where {N} = 1\nf(x::NTuple{N,Float64}) where {N} = 2are ambiguous because of the possibility that N == 0: there are no elements to determine whether the Int or Float64 variant should be called. To resolve the ambiguity, one approach is define a method for the empty tuple:f(x::Tuple{}) = 3Alternatively, for all methods but one you can insist that there is at least one element in the tuple:f(x::NTuple{N,Int}) where {N} = 1 # this is the fallback\nf(x::Tuple{Float64, Vararg{Float64}}) = 2 # this requires at least one Float64" -}, - -{ - "location": "manual/methods.html#man-methods-orthogonalize-1", - "page": "Methods", - "title": "Orthogonalize your design", - "category": "section", - "text": "When you might be tempted to dispatch on two or more arguments, consider whether a \"wrapper\" function might make for a simpler design. For example, instead of writing multiple variants:f(x::A, y::A) = ...\nf(x::A, y::B) = ...\nf(x::B, y::A) = ...\nf(x::B, y::B) = ...you might consider definingf(x::A, y::A) = ...\nf(x, y) = f(g(x), g(y))where g converts the argument to type A. This is a very specific example of the more general principle of orthogonal design, in which separate concepts are assigned to separate methods. Here, g will most likely need a fallback definitiong(x::A) = xA related strategy exploits promote to bring x and y to a common type:f(x::T, y::T) where {T} = ...\nf(x, y) = f(promote(x, y)...)One risk with this design is the possibility that if there is no suitable promotion method converting x and y to the same type, the second method will recurse on itself infinitely and trigger a stack overflow. The non-exported function Base.promote_noncircular can be used as an alternative; when promotion fails it will still throw an error, but one that fails faster with a more specific error message." -}, - -{ - "location": "manual/methods.html#Dispatch-on-one-argument-at-a-time-1", - "page": "Methods", - "title": "Dispatch on one argument at a time", - "category": "section", - "text": "If you need to dispatch on multiple arguments, and there are many fallbacks with too many combinations to make it practical to define all possible variants, then consider introducing a \"name cascade\" where (for example) you dispatch on the first argument and then call an internal method:f(x::A, y) = _fA(x, y)\nf(x::B, y) = _fB(x, y)Then the internal methods _fA and _fB can dispatch on y without concern about ambiguities with each other with respect to x.Be aware that this strategy has at least one major disadvantage: in many cases, it is not possible for users to further customize the behavior of f by defining further specializations of your exported function f. Instead, they have to define specializations for your internal methods _fA and _fB, and this blurs the lines between exported and internal methods." -}, - -{ - "location": "manual/methods.html#Abstract-containers-and-element-types-1", - "page": "Methods", - "title": "Abstract containers and element types", - "category": "section", - "text": "Where possible, try to avoid defining methods that dispatch on specific element types of abstract containers. For example,-(A::AbstractArray{T}, b::Date) where {T<:Date}generates ambiguities for anyone who defines a method-(A::MyArrayType{T}, b::T) where {T}The best approach is to avoid defining either of these methods: instead, rely on a generic method -(A::AbstractArray, b) and make sure this method is implemented with generic calls (like similar and -) that do the right thing for each container type and element type separately. This is just a more complex variant of the advice to orthogonalize your methods.When this approach is not possible, it may be worth starting a discussion with other developers about resolving the ambiguity; just because one method was defined first does not necessarily mean that it can\'t be modified or eliminated. As a last resort, one developer can define the \"band-aid\" method-(A::MyArrayType{T}, b::Date) where {T<:Date} = ...that resolves the ambiguity by brute force." -}, - -{ - "location": "manual/methods.html#Complex-method-\"cascades\"-with-default-arguments-1", - "page": "Methods", - "title": "Complex method \"cascades\" with default arguments", - "category": "section", - "text": "If you are defining a method \"cascade\" that supplies defaults, be careful about dropping any arguments that correspond to potential defaults. For example, suppose you\'re writing a digital filtering algorithm and you have a method that handles the edges of the signal by applying padding:function myfilter(A, kernel, ::Replicate)\n Apadded = replicate_edges(A, size(kernel))\n myfilter(Apadded, kernel) # now perform the \"real\" computation\nendThis will run afoul of a method that supplies default padding:myfilter(A, kernel) = myfilter(A, kernel, Replicate()) # replicate the edge by defaultTogether, these two methods generate an infinite recursion with A constantly growing bigger.The better design would be to define your call hierarchy like this:struct NoPad end # indicate that no padding is desired, or that it\'s already applied\n\nmyfilter(A, kernel) = myfilter(A, kernel, Replicate()) # default boundary conditions\n\nfunction myfilter(A, kernel, ::Replicate)\n Apadded = replicate_edges(A, size(kernel))\n myfilter(Apadded, kernel, NoPad()) # indicate the new boundary conditions\nend\n\n# other padding methods go here\n\nfunction myfilter(A, kernel, ::NoPad)\n # Here\'s the \"real\" implementation of the core computation\nendNoPad is supplied in the same argument position as any other kind of padding, so it keeps the dispatch hierarchy well organized and with reduced likelihood of ambiguities. Moreover, it extends the \"public\" myfilter interface: a user who wants to control the padding explicitly can call the NoPad variant directly.[Clarke61]: Arthur C. Clarke, Profiles of the Future (1961): Clarke\'s Third Law." -}, - -{ - "location": "manual/constructors.html#", - "page": "Constructors", - "title": "Constructors", - "category": "page", - "text": "" -}, - -{ - "location": "manual/constructors.html#man-constructors-1", - "page": "Constructors", - "title": "Constructors", - "category": "section", - "text": "Constructors [1] are functions that create new objects – specifically, instances of Composite Types. In Julia, type objects also serve as constructor functions: they create new instances of themselves when applied to an argument tuple as a function. This much was already mentioned briefly when composite types were introduced. For example:julia> struct Foo\n bar\n baz\n end\n\njulia> foo = Foo(1, 2)\nFoo(1, 2)\n\njulia> foo.bar\n1\n\njulia> foo.baz\n2For many types, forming new objects by binding their field values together is all that is ever needed to create instances. There are, however, cases where more functionality is required when creating composite objects. Sometimes invariants must be enforced, either by checking arguments or by transforming them. Recursive data structures, especially those that may be self-referential, often cannot be constructed cleanly without first being created in an incomplete state and then altered programmatically to be made whole, as a separate step from object creation. Sometimes, it\'s just convenient to be able to construct objects with fewer or different types of parameters than they have fields. Julia\'s system for object construction addresses all of these cases and more.[1]: Nomenclature: while the term \"constructor\" generally refers to the entire function which constructs objects of a type, it is common to abuse terminology slightly and refer to specific constructor methods as \"constructors\". In such situations, it is generally clear from context that the term is used to mean \"constructor method\" rather than \"constructor function\", especially as it is often used in the sense of singling out a particular method of the constructor from all of the others." -}, - -{ - "location": "manual/constructors.html#Outer-Constructor-Methods-1", - "page": "Constructors", - "title": "Outer Constructor Methods", - "category": "section", - "text": "A constructor is just like any other function in Julia in that its overall behavior is defined by the combined behavior of its methods. Accordingly, you can add functionality to a constructor by simply defining new methods. For example, let\'s say you want to add a constructor method for Foo objects that takes only one argument and uses the given value for both the bar and baz fields. This is simple:julia> Foo(x) = Foo(x,x)\nFoo\n\njulia> Foo(1)\nFoo(1, 1)You could also add a zero-argument Foo constructor method that supplies default values for both of the bar and baz fields:julia> Foo() = Foo(0)\nFoo\n\njulia> Foo()\nFoo(0, 0)Here the zero-argument constructor method calls the single-argument constructor method, which in turn calls the automatically provided two-argument constructor method. For reasons that will become clear very shortly, additional constructor methods declared as normal methods like this are called outer constructor methods. Outer constructor methods can only ever create a new instance by calling another constructor method, such as the automatically provided default ones." -}, - -{ - "location": "manual/constructors.html#Inner-Constructor-Methods-1", - "page": "Constructors", - "title": "Inner Constructor Methods", - "category": "section", - "text": "While outer constructor methods succeed in addressing the problem of providing additional convenience methods for constructing objects, they fail to address the other two use cases mentioned in the introduction of this chapter: enforcing invariants, and allowing construction of self-referential objects. For these problems, one needs inner constructor methods. An inner constructor method is much like an outer constructor method, with two differences:It is declared inside the block of a type declaration, rather than outside of it like normal methods.\nIt has access to a special locally existent function called new that creates objects of the block\'s type.For example, suppose one wants to declare a type that holds a pair of real numbers, subject to the constraint that the first number is not greater than the second one. One could declare it like this:julia> struct OrderedPair\n x::Real\n y::Real\n OrderedPair(x,y) = x > y ? error(\"out of order\") : new(x,y)\n end\nNow OrderedPair objects can only be constructed such that x <= y:julia> OrderedPair(1, 2)\nOrderedPair(1, 2)\n\njulia> OrderedPair(2,1)\nERROR: out of order\nStacktrace:\n [1] OrderedPair(::Int64, ::Int64) at ./none:4If the type were declared mutable, you could reach in and directly change the field values to violate this invariant, but messing around with an object\'s internals uninvited is considered poor form. You (or someone else) can also provide additional outer constructor methods at any later point, but once a type is declared, there is no way to add more inner constructor methods. Since outer constructor methods can only create objects by calling other constructor methods, ultimately, some inner constructor must be called to create an object. This guarantees that all objects of the declared type must come into existence by a call to one of the inner constructor methods provided with the type, thereby giving some degree of enforcement of a type\'s invariants.If any inner constructor method is defined, no default constructor method is provided: it is presumed that you have supplied yourself with all the inner constructors you need. The default constructor is equivalent to writing your own inner constructor method that takes all of the object\'s fields as parameters (constrained to be of the correct type, if the corresponding field has a type), and passes them to new, returning the resulting object:julia> struct Foo\n bar\n baz\n Foo(bar,baz) = new(bar,baz)\n end\nThis declaration has the same effect as the earlier definition of the Foo type without an explicit inner constructor method. The following two types are equivalent – one with a default constructor, the other with an explicit constructor:julia> struct T1\n x::Int64\n end\n\njulia> struct T2\n x::Int64\n T2(x) = new(x)\n end\n\njulia> T1(1)\nT1(1)\n\njulia> T2(1)\nT2(1)\n\njulia> T1(1.0)\nT1(1)\n\njulia> T2(1.0)\nT2(1)It is considered good form to provide as few inner constructor methods as possible: only those taking all arguments explicitly and enforcing essential error checking and transformation. Additional convenience constructor methods, supplying default values or auxiliary transformations, should be provided as outer constructors that call the inner constructors to do the heavy lifting. This separation is typically quite natural." -}, - -{ - "location": "manual/constructors.html#Incomplete-Initialization-1", - "page": "Constructors", - "title": "Incomplete Initialization", - "category": "section", - "text": "The final problem which has still not been addressed is construction of self-referential objects, or more generally, recursive data structures. Since the fundamental difficulty may not be immediately obvious, let us briefly explain it. Consider the following recursive type declaration:julia> mutable struct SelfReferential\n obj::SelfReferential\n end\nThis type may appear innocuous enough, until one considers how to construct an instance of it. If a is an instance of SelfReferential, then a second instance can be created by the call:julia> b = SelfReferential(a)But how does one construct the first instance when no instance exists to provide as a valid value for its obj field? The only solution is to allow creating an incompletely initialized instance of SelfReferential with an unassigned obj field, and using that incomplete instance as a valid value for the obj field of another instance, such as, for example, itself.To allow for the creation of incompletely initialized objects, Julia allows the new function to be called with fewer than the number of fields that the type has, returning an object with the unspecified fields uninitialized. The inner constructor method can then use the incomplete object, finishing its initialization before returning it. Here, for example, we take another crack at defining the SelfReferential type, with a zero-argument inner constructor returning instances having obj fields pointing to themselves:julia> mutable struct SelfReferential\n obj::SelfReferential\n SelfReferential() = (x = new(); x.obj = x)\n end\nWe can verify that this constructor works and constructs objects that are, in fact, self-referential:julia> x = SelfReferential();\n\njulia> x === x\ntrue\n\njulia> x === x.obj\ntrue\n\njulia> x === x.obj.obj\ntrueAlthough it is generally a good idea to return a fully initialized object from an inner constructor, incompletely initialized objects can be returned:julia> mutable struct Incomplete\n xx\n Incomplete() = new()\n end\n\njulia> z = Incomplete();While you are allowed to create objects with uninitialized fields, any access to an uninitialized reference is an immediate error:julia> z.xx\nERROR: UndefRefError: access to undefined referenceThis avoids the need to continually check for null values. However, not all object fields are references. Julia considers some types to be \"plain data\", meaning all of their data is self-contained and does not reference other objects. The plain data types consist of primitive types (e.g. Int) and immutable structs of other plain data types. The initial contents of a plain data type is undefined:julia> struct HasPlain\n n::Int\n HasPlain() = new()\n end\n\njulia> HasPlain()\nHasPlain(438103441441)Arrays of plain data types exhibit the same behavior.You can pass incomplete objects to other functions from inner constructors to delegate their completion:julia> mutable struct Lazy\n xx\n Lazy(v) = complete_me(new(), v)\n endAs with incomplete objects returned from constructors, if complete_me or any of its callees try to access the xx field of the Lazy object before it has been initialized, an error will be thrown immediately." -}, - -{ - "location": "manual/constructors.html#Parametric-Constructors-1", - "page": "Constructors", - "title": "Parametric Constructors", - "category": "section", - "text": "Parametric types add a few wrinkles to the constructor story. Recall from Parametric Types that, by default, instances of parametric composite types can be constructed either with explicitly given type parameters or with type parameters implied by the types of the arguments given to the constructor. Here are some examples:julia> struct Point{T<:Real}\n x::T\n y::T\n end\n\njulia> Point(1,2) ## implicit T ##\nPoint{Int64}(1, 2)\n\njulia> Point(1.0,2.5) ## implicit T ##\nPoint{Float64}(1.0, 2.5)\n\njulia> Point(1,2.5) ## implicit T ##\nERROR: MethodError: no method matching Point(::Int64, ::Float64)\nClosest candidates are:\n Point(::T<:Real, !Matched::T<:Real) where T<:Real at none:2\n\njulia> Point{Int64}(1, 2) ## explicit T ##\nPoint{Int64}(1, 2)\n\njulia> Point{Int64}(1.0,2.5) ## explicit T ##\nERROR: InexactError()\nStacktrace:\n [1] convert(::Type{Int64}, ::Float64) at ./float.jl:679\n [2] Point{Int64}(::Float64, ::Float64) at ./none:2\n\njulia> Point{Float64}(1.0, 2.5) ## explicit T ##\nPoint{Float64}(1.0, 2.5)\n\njulia> Point{Float64}(1,2) ## explicit T ##\nPoint{Float64}(1.0, 2.0)As you can see, for constructor calls with explicit type parameters, the arguments are converted to the implied field types: Point{Int64}(1,2) works, but Point{Int64}(1.0,2.5) raises an InexactError when converting 2.5 to Int64. When the type is implied by the arguments to the constructor call, as in Point(1,2), then the types of the arguments must agree – otherwise the T cannot be determined – but any pair of real arguments with matching type may be given to the generic Point constructor.What\'s really going on here is that Point, Point{Float64} and Point{Int64} are all different constructor functions. In fact, Point{T} is a distinct constructor function for each type T. Without any explicitly provided inner constructors, the declaration of the composite type Point{T<:Real} automatically provides an inner constructor, Point{T}, for each possible type T<:Real, that behaves just like non-parametric default inner constructors do. It also provides a single general outer Point constructor that takes pairs of real arguments, which must be of the same type. This automatic provision of constructors is equivalent to the following explicit declaration:julia> struct Point{T<:Real}\n x::T\n y::T\n Point{T}(x,y) where {T<:Real} = new(x,y)\n end\n\njulia> Point(x::T, y::T) where {T<:Real} = Point{T}(x,y);Notice that each definition looks like the form of constructor call that it handles. The call Point{Int64}(1,2) will invoke the definition Point{T}(x,y) inside the type block. The outer constructor declaration, on the other hand, defines a method for the general Point constructor which only applies to pairs of values of the same real type. This declaration makes constructor calls without explicit type parameters, like Point(1,2) and Point(1.0,2.5), work. Since the method declaration restricts the arguments to being of the same type, calls like Point(1,2.5), with arguments of different types, result in \"no method\" errors.Suppose we wanted to make the constructor call Point(1,2.5) work by \"promoting\" the integer value 1 to the floating-point value 1.0. The simplest way to achieve this is to define the following additional outer constructor method:julia> Point(x::Int64, y::Float64) = Point(convert(Float64,x),y);This method uses the convert() function to explicitly convert x to Float64 and then delegates construction to the general constructor for the case where both arguments are Float64. With this method definition what was previously a MethodError now successfully creates a point of type Point{Float64}:julia> Point(1,2.5)\nPoint{Float64}(1.0, 2.5)\n\njulia> typeof(ans)\nPoint{Float64}However, other similar calls still don\'t work:julia> Point(1.5,2)\nERROR: MethodError: no method matching Point(::Float64, ::Int64)\nClosest candidates are:\n Point(::T<:Real, !Matched::T<:Real) where T<:Real at none:1For a more general way to make all such calls work sensibly, see Conversion and Promotion. At the risk of spoiling the suspense, we can reveal here that all it takes is the following outer method definition to make all calls to the general Point constructor work as one would expect:julia> Point(x::Real, y::Real) = Point(promote(x,y)...);The promote function converts all its arguments to a common type – in this case Float64. With this method definition, the Point constructor promotes its arguments the same way that numeric operators like + do, and works for all kinds of real numbers:julia> Point(1.5,2)\nPoint{Float64}(1.5, 2.0)\n\njulia> Point(1,1//2)\nPoint{Rational{Int64}}(1//1, 1//2)\n\njulia> Point(1.0,1//2)\nPoint{Float64}(1.0, 0.5)Thus, while the implicit type parameter constructors provided by default in Julia are fairly strict, it is possible to make them behave in a more relaxed but sensible manner quite easily. Moreover, since constructors can leverage all of the power of the type system, methods, and multiple dispatch, defining sophisticated behavior is typically quite simple." -}, - -{ - "location": "manual/constructors.html#Case-Study:-Rational-1", - "page": "Constructors", - "title": "Case Study: Rational", - "category": "section", - "text": "Perhaps the best way to tie all these pieces together is to present a real world example of a parametric composite type and its constructor methods. To that end, here is the (slightly modified) beginning of rational.jl, which implements Julia\'s Rational Numbers:julia> struct OurRational{T<:Integer} <: Real\n num::T\n den::T\n function OurRational{T}(num::T, den::T) where T<:Integer\n if num == 0 && den == 0\n error(\"invalid rational: 0//0\")\n end\n g = gcd(den, num)\n num = div(num, g)\n den = div(den, g)\n new(num, den)\n end\n end\n\njulia> OurRational(n::T, d::T) where {T<:Integer} = OurRational{T}(n,d)\nOurRational\n\njulia> OurRational(n::Integer, d::Integer) = OurRational(promote(n,d)...)\nOurRational\n\njulia> OurRational(n::Integer) = OurRational(n,one(n))\nOurRational\n\njulia> //(n::Integer, d::Integer) = OurRational(n,d)\n// (generic function with 1 method)\n\njulia> //(x::OurRational, y::Integer) = x.num // (x.den*y)\n// (generic function with 2 methods)\n\njulia> //(x::Integer, y::OurRational) = (x*y.den) // y.num\n// (generic function with 3 methods)\n\njulia> //(x::Complex, y::Real) = complex(real(x)//y, imag(x)//y)\n// (generic function with 4 methods)\n\njulia> //(x::Real, y::Complex) = x*y\'//real(y*y\')\n// (generic function with 5 methods)\n\njulia> function //(x::Complex, y::Complex)\n xy = x*y\'\n yy = real(y*y\')\n complex(real(xy)//yy, imag(xy)//yy)\n end\n// (generic function with 6 methods)The first line – struct OurRational{T<:Integer} <: Real – declares that OurRational takes one type parameter of an integer type, and is itself a real type. The field declarations num::T and den::T indicate that the data held in a OurRational{T} object are a pair of integers of type T, one representing the rational value\'s numerator and the other representing its denominator.Now things get interesting. OurRational has a single inner constructor method which checks that both of num and den aren\'t zero and ensures that every rational is constructed in \"lowest terms\" with a non-negative denominator. This is accomplished by dividing the given numerator and denominator values by their greatest common divisor, computed using the gcd function. Since gcd returns the greatest common divisor of its arguments with sign matching the first argument (den here), after this division the new value of den is guaranteed to be non-negative. Because this is the only inner constructor for OurRational, we can be certain that OurRational objects are always constructed in this normalized form.OurRational also provides several outer constructor methods for convenience. The first is the \"standard\" general constructor that infers the type parameter T from the type of the numerator and denominator when they have the same type. The second applies when the given numerator and denominator values have different types: it promotes them to a common type and then delegates construction to the outer constructor for arguments of matching type. The third outer constructor turns integer values into rationals by supplying a value of 1 as the denominator.Following the outer constructor definitions, we have a number of methods for the // operator, which provides a syntax for writing rationals. Before these definitions, // is a completely undefined operator with only syntax and no meaning. Afterwards, it behaves just as described in Rational Numbers – its entire behavior is defined in these few lines. The first and most basic definition just makes a//b construct a OurRational by applying the OurRational constructor to a and b when they are integers. When one of the operands of // is already a rational number, we construct a new rational for the resulting ratio slightly differently; this behavior is actually identical to division of a rational with an integer. Finally, applying // to complex integral values creates an instance of Complex{OurRational} – a complex number whose real and imaginary parts are rationals:julia> ans = (1 + 2im)//(1 - 2im);\n\njulia> typeof(ans)\nComplex{OurRational{Int64}}\n\njulia> ans <: Complex{OurRational}\nfalseThus, although the // operator usually returns an instance of OurRational, if either of its arguments are complex integers, it will return an instance of Complex{OurRational} instead. The interested reader should consider perusing the rest of rational.jl: it is short, self-contained, and implements an entire basic Julia type." -}, - -{ - "location": "manual/constructors.html#constructors-and-conversion-1", - "page": "Constructors", - "title": "Constructors and Conversion", - "category": "section", - "text": "Constructors T(args...) in Julia are implemented like other callable objects: methods are added to their types. The type of a type is Type, so all constructor methods are stored in the method table for the Type type. This means that you can declare more flexible constructors, e.g. constructors for abstract types, by explicitly defining methods for the appropriate types.However, in some cases you could consider adding methods to Base.convert instead of defining a constructor, because Julia falls back to calling convert() if no matching constructor is found. For example, if no constructor T(args...) = ... exists Base.convert(::Type{T}, args...) = ... is called.convert is used extensively throughout Julia whenever one type needs to be converted to another (e.g. in assignment, ccall, etcetera), and should generally only be defined (or successful) if the conversion is lossless. For example, convert(Int, 3.0) produces 3, but convert(Int, 3.2) throws an InexactError. If you want to define a constructor for a lossless conversion from one type to another, you should probably define a convert method instead.On the other hand, if your constructor does not represent a lossless conversion, or doesn\'t represent \"conversion\" at all, it is better to leave it as a constructor rather than a convert method. For example, the Array{Int}() constructor creates a zero-dimensional Array of the type Int, but is not really a \"conversion\" from Int to an Array." -}, - -{ - "location": "manual/constructors.html#Outer-only-constructors-1", - "page": "Constructors", - "title": "Outer-only constructors", - "category": "section", - "text": "As we have seen, a typical parametric type has inner constructors that are called when type parameters are known; e.g. they apply to Point{Int} but not to Point. Optionally, outer constructors that determine type parameters automatically can be added, for example constructing a Point{Int} from the call Point(1,2). Outer constructors call inner constructors to do the core work of making an instance. However, in some cases one would rather not provide inner constructors, so that specific type parameters cannot be requested manually.For example, say we define a type that stores a vector along with an accurate representation of its sum:julia> struct SummedArray{T<:Number,S<:Number}\n data::Vector{T}\n sum::S\n end\n\njulia> SummedArray(Int32[1; 2; 3], Int32(6))\nSummedArray{Int32,Int32}(Int32[1, 2, 3], 6)The problem is that we want S to be a larger type than T, so that we can sum many elements with less information loss. For example, when T is Int32, we would like S to be Int64. Therefore we want to avoid an interface that allows the user to construct instances of the type SummedArray{Int32,Int32}. One way to do this is to provide a constructor only for SummedArray, but inside the type definition block to suppress generation of default constructors:julia> struct SummedArray{T<:Number,S<:Number}\n data::Vector{T}\n sum::S\n function SummedArray(a::Vector{T}) where T\n S = widen(T)\n new{T,S}(a, sum(S, a))\n end\n end\n\njulia> SummedArray(Int32[1; 2; 3], Int32(6))\nERROR: MethodError: no method matching SummedArray(::Array{Int32,1}, ::Int32)\nClosest candidates are:\n SummedArray(::Array{T,1}) where T at none:5This constructor will be invoked by the syntax SummedArray(a). The syntax new{T,S} allows specifying parameters for the type to be constructed, i.e. this call will return a SummedArray{T,S}. new{T,S} can be used in any constructor definition, but for convenience the parameters to new{} are automatically derived from the type being constructed when possible." -}, - -{ - "location": "manual/conversion-and-promotion.html#", - "page": "Conversion and Promotion", - "title": "Conversion and Promotion", - "category": "page", - "text": "" -}, - -{ - "location": "manual/conversion-and-promotion.html#conversion-and-promotion-1", - "page": "Conversion and Promotion", - "title": "Conversion and Promotion", - "category": "section", - "text": "Julia has a system for promoting arguments of mathematical operators to a common type, which has been mentioned in various other sections, including Integers and Floating-Point Numbers, Mathematical Operations and Elementary Functions, Types, and Methods. In this section, we explain how this promotion system works, as well as how to extend it to new types and apply it to functions besides built-in mathematical operators. Traditionally, programming languages fall into two camps with respect to promotion of arithmetic arguments:Automatic promotion for built-in arithmetic types and operators. In most languages, built-in numeric types, when used as operands to arithmetic operators with infix syntax, such as +, -, *, and /, are automatically promoted to a common type to produce the expected results. C, Java, Perl, and Python, to name a few, all correctly compute the sum 1 + 1.5 as the floating-point value 2.5, even though one of the operands to + is an integer. These systems are convenient and designed carefully enough that they are generally all-but-invisible to the programmer: hardly anyone consciously thinks of this promotion taking place when writing such an expression, but compilers and interpreters must perform conversion before addition since integers and floating-point values cannot be added as-is. Complex rules for such automatic conversions are thus inevitably part of specifications and implementations for such languages.\nNo automatic promotion. This camp includes Ada and ML – very \"strict\" statically typed languages. In these languages, every conversion must be explicitly specified by the programmer. Thus, the example expression 1 + 1.5 would be a compilation error in both Ada and ML. Instead one must write real(1) + 1.5, explicitly converting the integer 1 to a floating-point value before performing addition. Explicit conversion everywhere is so inconvenient, however, that even Ada has some degree of automatic conversion: integer literals are promoted to the expected integer type automatically, and floating-point literals are similarly promoted to appropriate floating-point types.In a sense, Julia falls into the \"no automatic promotion\" category: mathematical operators are just functions with special syntax, and the arguments of functions are never automatically converted. However, one may observe that applying mathematical operations to a wide variety of mixed argument types is just an extreme case of polymorphic multiple dispatch – something which Julia\'s dispatch and type systems are particularly well-suited to handle. \"Automatic\" promotion of mathematical operands simply emerges as a special application: Julia comes with pre-defined catch-all dispatch rules for mathematical operators, invoked when no specific implementation exists for some combination of operand types. These catch-all rules first promote all operands to a common type using user-definable promotion rules, and then invoke a specialized implementation of the operator in question for the resulting values, now of the same type. User-defined types can easily participate in this promotion system by defining methods for conversion to and from other types, and providing a handful of promotion rules defining what types they should promote to when mixed with other types." -}, - -{ - "location": "manual/conversion-and-promotion.html#Conversion-1", - "page": "Conversion and Promotion", - "title": "Conversion", - "category": "section", - "text": "Conversion of values to various types is performed by the convert function. The convert function generally takes two arguments: the first is a type object while the second is a value to convert to that type; the returned value is the value converted to an instance of given type. The simplest way to understand this function is to see it in action:julia> x = 12\n12\n\njulia> typeof(x)\nInt64\n\njulia> convert(UInt8, x)\n0x0c\n\njulia> typeof(ans)\nUInt8\n\njulia> convert(AbstractFloat, x)\n12.0\n\njulia> typeof(ans)\nFloat64\n\njulia> a = Any[1 2 3; 4 5 6]\n2×3 Array{Any,2}:\n 1 2 3\n 4 5 6\n\njulia> convert(Array{Float64}, a)\n2×3 Array{Float64,2}:\n 1.0 2.0 3.0\n 4.0 5.0 6.0Conversion isn\'t always possible, in which case a no method error is thrown indicating that convert doesn\'t know how to perform the requested conversion:julia> convert(AbstractFloat, \"foo\")\nERROR: MethodError: Cannot `convert` an object of type String to an object of type AbstractFloat\nThis may have arisen from a call to the constructor AbstractFloat(...),\nsince type constructors fall back to convert methods.Some languages consider parsing strings as numbers or formatting numbers as strings to be conversions (many dynamic languages will even perform conversion for you automatically), however Julia does not: even though some strings can be parsed as numbers, most strings are not valid representations of numbers, and only a very limited subset of them are. Therefore in Julia the dedicated parse() function must be used to perform this operation, making it more explicit." -}, - -{ - "location": "manual/conversion-and-promotion.html#Defining-New-Conversions-1", - "page": "Conversion and Promotion", - "title": "Defining New Conversions", - "category": "section", - "text": "To define a new conversion, simply provide a new method for convert(). That\'s really all there is to it. For example, the method to convert a real number to a boolean is this:convert(::Type{Bool}, x::Real) = x==0 ? false : x==1 ? true : throw(InexactError())The type of the first argument of this method is a singleton type, Type{Bool}, the only instance of which is Bool. Thus, this method is only invoked when the first argument is the type value Bool. Notice the syntax used for the first argument: the argument name is omitted prior to the :: symbol, and only the type is given. This is the syntax in Julia for a function argument whose type is specified but whose value is never used in the function body. In this example, since the type is a singleton, there would never be any reason to use its value within the body. When invoked, the method determines whether a numeric value is true or false as a boolean, by comparing it to one and zero:julia> convert(Bool, 1)\ntrue\n\njulia> convert(Bool, 0)\nfalse\n\njulia> convert(Bool, 1im)\nERROR: InexactError()\nStacktrace:\n [1] convert(::Type{Bool}, ::Complex{Int64}) at ./complex.jl:31\n\njulia> convert(Bool, 0im)\nfalseThe method signatures for conversion methods are often quite a bit more involved than this example, especially for parametric types. The example above is meant to be pedagogical, and is not the actual Julia behaviour. This is the actual implementation in Julia:convert(::Type{T}, z::Complex) where {T<:Real} =\n (imag(z) == 0 ? convert(T, real(z)) : throw(InexactError()))" -}, - -{ - "location": "manual/conversion-and-promotion.html#man-rational-conversion-1", - "page": "Conversion and Promotion", - "title": "Case Study: Rational Conversions", - "category": "section", - "text": "To continue our case study of Julia\'s Rational type, here are the conversions declared in rational.jl, right after the declaration of the type and its constructors:convert(::Type{Rational{T}}, x::Rational) where {T<:Integer} = Rational(convert(T,x.num),convert(T,x.den))\nconvert(::Type{Rational{T}}, x::Integer) where {T<:Integer} = Rational(convert(T,x), convert(T,1))\n\nfunction convert(::Type{Rational{T}}, x::AbstractFloat, tol::Real) where T<:Integer\n if isnan(x); return zero(T)//zero(T); end\n if isinf(x); return sign(x)//zero(T); end\n y = x\n a = d = one(T)\n b = c = zero(T)\n while true\n f = convert(T,round(y)); y -= f\n a, b, c, d = f*a+c, f*b+d, a, b\n if y == 0 || abs(a/b-x) <= tol\n return a//b\n end\n y = 1/y\n end\nend\nconvert(rt::Type{Rational{T}}, x::AbstractFloat) where {T<:Integer} = convert(rt,x,eps(x))\n\nconvert(::Type{T}, x::Rational) where {T<:AbstractFloat} = convert(T,x.num)/convert(T,x.den)\nconvert(::Type{T}, x::Rational) where {T<:Integer} = div(convert(T,x.num),convert(T,x.den))The initial four convert methods provide conversions to rational types. The first method converts one type of rational to another type of rational by converting the numerator and denominator to the appropriate integer type. The second method does the same conversion for integers by taking the denominator to be 1. The third method implements a standard algorithm for approximating a floating-point number by a ratio of integers to within a given tolerance, and the fourth method applies it, using machine epsilon at the given value as the threshold. In general, one should have a//b == convert(Rational{Int64}, a/b).The last two convert methods provide conversions from rational types to floating-point and integer types. To convert to floating point, one simply converts both numerator and denominator to that floating point type and then divides. To convert to integer, one can use the div operator for truncated integer division (rounded towards zero)." -}, - -{ - "location": "manual/conversion-and-promotion.html#Promotion-1", - "page": "Conversion and Promotion", - "title": "Promotion", - "category": "section", - "text": "Promotion refers to converting values of mixed types to a single common type. Although it is not strictly necessary, it is generally implied that the common type to which the values are converted can faithfully represent all of the original values. In this sense, the term \"promotion\" is appropriate since the values are converted to a \"greater\" type – i.e. one which can represent all of the input values in a single common type. It is important, however, not to confuse this with object-oriented (structural) super-typing, or Julia\'s notion of abstract super-types: promotion has nothing to do with the type hierarchy, and everything to do with converting between alternate representations. For instance, although every Int32 value can also be represented as a Float64 value, Int32 is not a subtype of Float64.Promotion to a common \"greater\" type is performed in Julia by the promote function, which takes any number of arguments, and returns a tuple of the same number of values, converted to a common type, or throws an exception if promotion is not possible. The most common use case for promotion is to convert numeric arguments to a common type:julia> promote(1, 2.5)\n(1.0, 2.5)\n\njulia> promote(1, 2.5, 3)\n(1.0, 2.5, 3.0)\n\njulia> promote(2, 3//4)\n(2//1, 3//4)\n\njulia> promote(1, 2.5, 3, 3//4)\n(1.0, 2.5, 3.0, 0.75)\n\njulia> promote(1.5, im)\n(1.5 + 0.0im, 0.0 + 1.0im)\n\njulia> promote(1 + 2im, 3//4)\n(1//1 + 2//1*im, 3//4 + 0//1*im)Floating-point values are promoted to the largest of the floating-point argument types. Integer values are promoted to the larger of either the native machine word size or the largest integer argument type. Mixtures of integers and floating-point values are promoted to a floating-point type big enough to hold all the values. Integers mixed with rationals are promoted to rationals. Rationals mixed with floats are promoted to floats. Complex values mixed with real values are promoted to the appropriate kind of complex value.That is really all there is to using promotions. The rest is just a matter of clever application, the most typical \"clever\" application being the definition of catch-all methods for numeric operations like the arithmetic operators +, -, * and /. Here are some of the catch-all method definitions given in promotion.jl:+(x::Number, y::Number) = +(promote(x,y)...)\n-(x::Number, y::Number) = -(promote(x,y)...)\n*(x::Number, y::Number) = *(promote(x,y)...)\n/(x::Number, y::Number) = /(promote(x,y)...)These method definitions say that in the absence of more specific rules for adding, subtracting, multiplying and dividing pairs of numeric values, promote the values to a common type and then try again. That\'s all there is to it: nowhere else does one ever need to worry about promotion to a common numeric type for arithmetic operations – it just happens automatically. There are definitions of catch-all promotion methods for a number of other arithmetic and mathematical functions in promotion.jl, but beyond that, there are hardly any calls to promote required in the Julia standard library. The most common usages of promote occur in outer constructors methods, provided for convenience, to allow constructor calls with mixed types to delegate to an inner type with fields promoted to an appropriate common type. For example, recall that rational.jl provides the following outer constructor method:Rational(n::Integer, d::Integer) = Rational(promote(n,d)...)This allows calls like the following to work:julia> Rational(Int8(15),Int32(-5))\n-3//1\n\njulia> typeof(ans)\nRational{Int32}For most user-defined types, it is better practice to require programmers to supply the expected types to constructor functions explicitly, but sometimes, especially for numeric problems, it can be convenient to do promotion automatically." -}, - -{ - "location": "manual/conversion-and-promotion.html#Defining-Promotion-Rules-1", - "page": "Conversion and Promotion", - "title": "Defining Promotion Rules", - "category": "section", - "text": "Although one could, in principle, define methods for the promote function directly, this would require many redundant definitions for all possible permutations of argument types. Instead, the behavior of promote is defined in terms of an auxiliary function called promote_rule, which one can provide methods for. The promote_rule function takes a pair of type objects and returns another type object, such that instances of the argument types will be promoted to the returned type. Thus, by defining the rule:promote_rule(::Type{Float64}, ::Type{Float32}) = Float64one declares that when 64-bit and 32-bit floating-point values are promoted together, they should be promoted to 64-bit floating-point. The promotion type does not need to be one of the argument types, however; the following promotion rules both occur in Julia\'s standard library:promote_rule(::Type{UInt8}, ::Type{Int8}) = Int\npromote_rule(::Type{BigInt}, ::Type{Int8}) = BigIntIn the latter case, the result type is BigInt since BigInt is the only type large enough to hold integers for arbitrary-precision integer arithmetic. Also note that one does not need to define both promote_rule(::Type{A}, ::Type{B}) and promote_rule(::Type{B}, ::Type{A}) – the symmetry is implied by the way promote_rule is used in the promotion process.The promote_rule function is used as a building block to define a second function called promote_type, which, given any number of type objects, returns the common type to which those values, as arguments to promote should be promoted. Thus, if one wants to know, in absence of actual values, what type a collection of values of certain types would promote to, one can use promote_type:julia> promote_type(Int8, UInt16)\nInt64Internally, promote_type is used inside of promote to determine what type argument values should be converted to for promotion. It can, however, be useful in its own right. The curious reader can read the code in promotion.jl, which defines the complete promotion mechanism in about 35 lines." -}, - -{ - "location": "manual/conversion-and-promotion.html#Case-Study:-Rational-Promotions-1", - "page": "Conversion and Promotion", - "title": "Case Study: Rational Promotions", - "category": "section", - "text": "Finally, we finish off our ongoing case study of Julia\'s rational number type, which makes relatively sophisticated use of the promotion mechanism with the following promotion rules:promote_rule(::Type{Rational{T}}, ::Type{S}) where {T<:Integer,S<:Integer} = Rational{promote_type(T,S)}\npromote_rule(::Type{Rational{T}}, ::Type{Rational{S}}) where {T<:Integer,S<:Integer} = Rational{promote_type(T,S)}\npromote_rule(::Type{Rational{T}}, ::Type{S}) where {T<:Integer,S<:AbstractFloat} = promote_type(T,S)The first rule says that promoting a rational number with any other integer type promotes to a rational type whose numerator/denominator type is the result of promotion of its numerator/denominator type with the other integer type. The second rule applies the same logic to two different types of rational numbers, resulting in a rational of the promotion of their respective numerator/denominator types. The third and final rule dictates that promoting a rational with a float results in the same type as promoting the numerator/denominator type with the float.This small handful of promotion rules, together with the conversion methods discussed above, are sufficient to make rational numbers interoperate completely naturally with all of Julia\'s other numeric types – integers, floating-point numbers, and complex numbers. By providing appropriate conversion methods and promotion rules in the same manner, any user-defined numeric type can interoperate just as naturally with Julia\'s predefined numerics." -}, - -{ - "location": "manual/interfaces.html#", - "page": "Interfaces", - "title": "Interfaces", - "category": "page", - "text": "" -}, - -{ - "location": "manual/interfaces.html#Interfaces-1", - "page": "Interfaces", - "title": "Interfaces", - "category": "section", - "text": "A lot of the power and extensibility in Julia comes from a collection of informal interfaces. By extending a few specific methods to work for a custom type, objects of that type not only receive those functionalities, but they are also able to be used in other methods that are written to generically build upon those behaviors." -}, - -{ - "location": "manual/interfaces.html#man-interface-iteration-1", - "page": "Interfaces", - "title": "Iteration", - "category": "section", - "text": "Required methods   Brief description\nstart(iter)   Returns the initial iteration state\nnext(iter, state)   Returns the current item and the next state\ndone(iter, state)   Tests if there are any items remaining\nImportant optional methods Default definition Brief description\niteratorsize(IterType) HasLength() One of HasLength(), HasShape(), IsInfinite(), or SizeUnknown() as appropriate\niteratoreltype(IterType) HasEltype() Either EltypeUnknown() or HasEltype() as appropriate\neltype(IterType) Any The type the items returned by next()\nlength(iter) (undefined) The number of items, if known\nsize(iter, [dim...]) (undefined) The number of items in each dimension, if knownValue returned by iteratorsize(IterType) Required Methods\nHasLength() length(iter)\nHasShape() length(iter) and size(iter, [dim...])\nIsInfinite() (none)\nSizeUnknown() (none)Value returned by iteratoreltype(IterType) Required Methods\nHasEltype() eltype(IterType)\nEltypeUnknown() (none)Sequential iteration is implemented by the methods start(), done(), and next(). Instead of mutating objects as they are iterated over, Julia provides these three methods to keep track of the iteration state externally from the object. The start(iter) method returns the initial state for the iterable object iter. That state gets passed along to done(iter, state), which tests if there are any elements remaining, and next(iter, state), which returns a tuple containing the current element and an updated state. The state object can be anything, and is generally considered to be an implementation detail private to the iterable object.Any object defines these three methods is iterable and can be used in the many functions that rely upon iteration. It can also be used directly in a for loop since the syntax:for i in iter # or \"for i = iter\"\n # body\nendis translated into:state = start(iter)\nwhile !done(iter, state)\n (i, state) = next(iter, state)\n # body\nendA simple example is an iterable sequence of square numbers with a defined length:julia> struct Squares\n count::Int\n end\n\njulia> Base.start(::Squares) = 1\n\njulia> Base.next(S::Squares, state) = (state*state, state+1)\n\njulia> Base.done(S::Squares, state) = state > S.count\n\njulia> Base.eltype(::Type{Squares}) = Int # Note that this is defined for the type\n\njulia> Base.length(S::Squares) = S.countWith only start, next, and done definitions, the Squares type is already pretty powerful. We can iterate over all the elements:julia> for i in Squares(7)\n println(i)\n end\n1\n4\n9\n16\n25\n36\n49We can use many of the builtin methods that work with iterables, like in(), mean() and std():julia> 25 in Squares(10)\ntrue\n\njulia> mean(Squares(100))\n3383.5\n\njulia> std(Squares(100))\n3024.355854282583There are a few more methods we can extend to give Julia more information about this iterable collection. We know that the elements in a Squares sequence will always be Int. By extending the eltype() method, we can give that information to Julia and help it make more specialized code in the more complicated methods. We also know the number of elements in our sequence, so we can extend length(), too.Now, when we ask Julia to collect() all the elements into an array it can preallocate a Vector{Int} of the right size instead of blindly push!ing each element into a Vector{Any}:julia> collect(Squares(10))\' # transposed to save space\n1×10 RowVector{Int64,Array{Int64,1}}:\n 1 4 9 16 25 36 49 64 81 100While we can rely upon generic implementations, we can also extend specific methods where we know there is a simpler algorithm. For example, there\'s a formula to compute the sum of squares, so we can override the generic iterative version with a more performant solution:julia> Base.sum(S::Squares) = (n = S.count; return n*(n+1)*(2n+1)÷6)\n\njulia> sum(Squares(1803))\n1955361914This is a very common pattern throughout the Julia standard library: a small set of required methods define an informal interface that enable many fancier behaviors. In some cases, types will want to additionally specialize those extra behaviors when they know a more efficient algorithm can be used in their specific case." -}, - -{ - "location": "manual/interfaces.html#Indexing-1", - "page": "Interfaces", - "title": "Indexing", - "category": "section", - "text": "Methods to implement Brief description\ngetindex(X, i) X[i], indexed element access\nsetindex!(X, v, i) X[i] = v, indexed assignment\nendof(X) The last index, used in X[end]For the Squares iterable above, we can easily compute the ith element of the sequence by squaring it. We can expose this as an indexing expression S[i]. To opt into this behavior, Squares simply needs to define getindex():julia> function Base.getindex(S::Squares, i::Int)\n 1 <= i <= S.count || throw(BoundsError(S, i))\n return i*i\n end\n\njulia> Squares(100)[23]\n529Additionally, to support the syntax S[end], we must define endof() to specify the last valid index:julia> Base.endof(S::Squares) = length(S)\n\njulia> Squares(23)[end]\n529Note, though, that the above only defines getindex() with one integer index. Indexing with anything other than an Int will throw a MethodError saying that there was no matching method. In order to support indexing with ranges or vectors of Ints, separate methods must be written:julia> Base.getindex(S::Squares, i::Number) = S[convert(Int, i)]\n\njulia> Base.getindex(S::Squares, I) = [S[i] for i in I]\n\njulia> Squares(10)[[3,4.,5]]\n3-element Array{Int64,1}:\n 9\n 16\n 25While this is starting to support more of the indexing operations supported by some of the builtin types, there\'s still quite a number of behaviors missing. This Squares sequence is starting to look more and more like a vector as we\'ve added behaviors to it. Instead of defining all these behaviors ourselves, we can officially define it as a subtype of an AbstractArray." -}, - -{ - "location": "manual/interfaces.html#man-interface-array-1", - "page": "Interfaces", - "title": "Abstract Arrays", - "category": "section", - "text": "Methods to implement   Brief description\nsize(A)   Returns a tuple containing the dimensions of A\ngetindex(A, i::Int)   (if IndexLinear) Linear scalar indexing\ngetindex(A, I::Vararg{Int, N})   (if IndexCartesian, where N = ndims(A)) N-dimensional scalar indexing\nsetindex!(A, v, i::Int)   (if IndexLinear) Scalar indexed assignment\nsetindex!(A, v, I::Vararg{Int, N})   (if IndexCartesian, where N = ndims(A)) N-dimensional scalar indexed assignment\nOptional methods Default definition Brief description\nIndexStyle(::Type) IndexCartesian() Returns either IndexLinear() or IndexCartesian(). See the description below.\ngetindex(A, I...) defined in terms of scalar getindex() Multidimensional and nonscalar indexing\nsetindex!(A, I...) defined in terms of scalar setindex!() Multidimensional and nonscalar indexed assignment\nstart()/next()/done() defined in terms of scalar getindex() Iteration\nlength(A) prod(size(A)) Number of elements\nsimilar(A) similar(A, eltype(A), size(A)) Return a mutable array with the same shape and element type\nsimilar(A, ::Type{S}) similar(A, S, size(A)) Return a mutable array with the same shape and the specified element type\nsimilar(A, dims::NTuple{Int}) similar(A, eltype(A), dims) Return a mutable array with the same element type and size dims\nsimilar(A, ::Type{S}, dims::NTuple{Int}) Array{S}(dims) Return a mutable array with the specified element type and size\nNon-traditional indices Default definition Brief description\nindices(A) map(OneTo, size(A)) Return the AbstractUnitRange of valid indices\nBase.similar(A, ::Type{S}, inds::NTuple{Ind}) similar(A, S, Base.to_shape(inds)) Return a mutable array with the specified indices inds (see below)\nBase.similar(T::Union{Type,Function}, inds) T(Base.to_shape(inds)) Return an array similar to T with the specified indices inds (see below)If a type is defined as a subtype of AbstractArray, it inherits a very large set of rich behaviors including iteration and multidimensional indexing built on top of single-element access. See the arrays manual page and standard library section for more supported methods.A key part in defining an AbstractArray subtype is IndexStyle. Since indexing is such an important part of an array and often occurs in hot loops, it\'s important to make both indexing and indexed assignment as efficient as possible. Array data structures are typically defined in one of two ways: either it most efficiently accesses its elements using just one index (linear indexing) or it intrinsically accesses the elements with indices specified for every dimension. These two modalities are identified by Julia as IndexLinear() and IndexCartesian(). Converting a linear index to multiple indexing subscripts is typically very expensive, so this provides a traits-based mechanism to enable efficient generic code for all array types.This distinction determines which scalar indexing methods the type must define. IndexLinear() arrays are simple: just define getindex(A::ArrayType, i::Int). When the array is subsequently indexed with a multidimensional set of indices, the fallback getindex(A::AbstractArray, I...)() efficiently converts the indices into one linear index and then calls the above method. IndexCartesian() arrays, on the other hand, require methods to be defined for each supported dimensionality with ndims(A) Int indices. For example, the built-in SparseMatrixCSC type only supports two dimensions, so it just defines getindex(A::SparseMatrixCSC, i::Int, j::Int). The same holds for setindex!().Returning to the sequence of squares from above, we could instead define it as a subtype of an AbstractArray{Int, 1}:julia> struct SquaresVector <: AbstractArray{Int, 1}\n count::Int\n end\n\njulia> Base.size(S::SquaresVector) = (S.count,)\n\njulia> Base.IndexStyle(::Type{<:SquaresVector}) = IndexLinear()\n\njulia> Base.getindex(S::SquaresVector, i::Int) = i*iNote that it\'s very important to specify the two parameters of the AbstractArray; the first defines the eltype(), and the second defines the ndims(). That supertype and those three methods are all it takes for SquaresVector to be an iterable, indexable, and completely functional array:julia> s = SquaresVector(7)\n7-element SquaresVector:\n 1\n 4\n 9\n 16\n 25\n 36\n 49\n\njulia> s[s .> 20]\n3-element Array{Int64,1}:\n 25\n 36\n 49\n\njulia> s \\ [1 2; 3 4; 5 6; 7 8; 9 10; 11 12; 13 14]\n1×2 Array{Float64,2}:\n 0.305389 0.335329\n\njulia> s ⋅ s # dot(s, s)\n4676As a more complicated example, let\'s define our own toy N-dimensional sparse-like array type built on top of Dict:julia> struct SparseArray{T,N} <: AbstractArray{T,N}\n data::Dict{NTuple{N,Int}, T}\n dims::NTuple{N,Int}\n end\n\njulia> SparseArray{T}(::Type{T}, dims::Int...) = SparseArray(T, dims);\n\njulia> SparseArray{T,N}(::Type{T}, dims::NTuple{N,Int}) = SparseArray{T,N}(Dict{NTuple{N,Int}, T}(), dims);\n\njulia> Base.size(A::SparseArray) = A.dims\n\njulia> Base.similar(A::SparseArray, ::Type{T}, dims::Dims) where {T} = SparseArray(T, dims)\n\njulia> Base.getindex(A::SparseArray{T,N}, I::Vararg{Int,N}) where {T,N} = get(A.data, I, zero(T))\n\njulia> Base.setindex!(A::SparseArray{T,N}, v, I::Vararg{Int,N}) where {T,N} = (A.data[I] = v)Notice that this is an IndexCartesian array, so we must manually define getindex() and setindex!() at the dimensionality of the array. Unlike the SquaresVector, we are able to define setindex!(), and so we can mutate the array:julia> A = SparseArray(Float64, 3, 3)\n3×3 SparseArray{Float64,2}:\n 0.0 0.0 0.0\n 0.0 0.0 0.0\n 0.0 0.0 0.0\n\njulia> fill!(A, 2)\n3×3 SparseArray{Float64,2}:\n 2.0 2.0 2.0\n 2.0 2.0 2.0\n 2.0 2.0 2.0\n\njulia> A[:] = 1:length(A); A\n3×3 SparseArray{Float64,2}:\n 1.0 4.0 7.0\n 2.0 5.0 8.0\n 3.0 6.0 9.0The result of indexing an AbstractArray can itself be an array (for instance when indexing by a Range). The AbstractArray fallback methods use similar() to allocate an Array of the appropriate size and element type, which is filled in using the basic indexing method described above. However, when implementing an array wrapper you often want the result to be wrapped as well:julia> A[1:2,:]\n2×3 SparseArray{Float64,2}:\n 1.0 4.0 7.0\n 2.0 5.0 8.0In this example it is accomplished by defining Base.similar{T}(A::SparseArray, ::Type{T}, dims::Dims) to create the appropriate wrapped array. (Note that while similar supports 1- and 2-argument forms, in most case you only need to specialize the 3-argument form.) For this to work it\'s important that SparseArray is mutable (supports setindex!). Defining similar(), getindex() and setindex!() for SparseArray also makes it possible to copy() the array:julia> copy(A)\n3×3 SparseArray{Float64,2}:\n 1.0 4.0 7.0\n 2.0 5.0 8.0\n 3.0 6.0 9.0In addition to all the iterable and indexable methods from above, these types can also interact with each other and use most of the methods defined in the standard library for AbstractArrays:julia> A[SquaresVector(3)]\n3-element SparseArray{Float64,1}:\n 1.0\n 4.0\n 9.0\n\njulia> dot(A[:,1],A[:,2])\n32.0If you are defining an array type that allows non-traditional indexing (indices that start at something other than 1), you should specialize indices. You should also specialize similar so that the dims argument (ordinarily a Dims size-tuple) can accept AbstractUnitRange objects, perhaps range-types Ind of your own design. For more information, see Arrays with custom indices." -}, - -{ - "location": "manual/modules.html#", - "page": "Modules", - "title": "Modules", - "category": "page", - "text": "" -}, - -{ - "location": "manual/modules.html#modules-1", - "page": "Modules", - "title": "Modules", - "category": "section", - "text": "Modules in Julia are separate variable workspaces, i.e. they introduce a new global scope. They are delimited syntactically, inside module Name ... end. Modules allow you to create top-level definitions (aka global variables) without worrying about name conflicts when your code is used together with somebody else\'s. Within a module, you can control which names from other modules are visible (via importing), and specify which of your names are intended to be public (via exporting).The following example demonstrates the major features of modules. It is not meant to be run, but is shown for illustrative purposes:module MyModule\nusing Lib\n\nusing BigLib: thing1, thing2\n\nimport Base.show\n\nimportall OtherLib\n\nexport MyType, foo\n\nstruct MyType\n x\nend\n\nbar(x) = 2x\nfoo(a::MyType) = bar(a.x) + 1\n\nshow(io::IO, a::MyType) = print(io, \"MyType $(a.x)\")\nendNote that the style is not to indent the body of the module, since that would typically lead to whole files being indented.This module defines a type MyType, and two functions. Function foo and type MyType are exported, and so will be available for importing into other modules. Function bar is private to MyModule.The statement using Lib means that a module called Lib will be available for resolving names as needed. When a global variable is encountered that has no definition in the current module, the system will search for it among variables exported by Lib and import it if it is found there. This means that all uses of that global within the current module will resolve to the definition of that variable in Lib.The statement using BigLib: thing1, thing2 is a syntactic shortcut for using BigLib.thing1, BigLib.thing2.The import keyword supports all the same syntax as using, but only operates on a single name at a time. It does not add modules to be searched the way using does. import also differs from using in that functions must be imported using import to be extended with new methods.In MyModule above we wanted to add a method to the standard show function, so we had to write import Base.show. Functions whose names are only visible via using cannot be extended.The keyword importall explicitly imports all names exported by the specified module, as if import were individually used on all of them.Once a variable is made visible via using or import, a module may not create its own variable with the same name. Imported variables are read-only; assigning to a global variable always affects a variable owned by the current module, or else raises an error." -}, - -{ - "location": "manual/modules.html#Summary-of-module-usage-1", - "page": "Modules", - "title": "Summary of module usage", - "category": "section", - "text": "To load a module, two main keywords can be used: using and import. To understand their differences, consider the following example:module MyModule\n\nexport x, y\n\nx() = \"x\"\ny() = \"y\"\np() = \"p\"\n\nendIn this module we export the x and y functions (with the keyword export), and also have the non-exported function p. There are several different ways to load the Module and its inner functions into the current workspace:Import Command What is brought into scope Available for method extension\nusing MyModule All exported names (x and y), MyModule.x, MyModule.y and MyModule.p MyModule.x, MyModule.y and MyModule.p\nusing MyModule.x, MyModule.p x and p  \nusing MyModule: x, p x and p  \nimport MyModule MyModule.x, MyModule.y and MyModule.p MyModule.x, MyModule.y and MyModule.p\nimport MyModule.x, MyModule.p x and p x and p\nimport MyModule: x, p x and p x and p\nimportall MyModule All exported names (x and y) x and y" -}, - -{ - "location": "manual/modules.html#Modules-and-files-1", - "page": "Modules", - "title": "Modules and files", - "category": "section", - "text": "Files and file names are mostly unrelated to modules; modules are associated only with module expressions. One can have multiple files per module, and multiple modules per file:module Foo\n\ninclude(\"file1.jl\")\ninclude(\"file2.jl\")\n\nendIncluding the same code in different modules provides mixin-like behavior. One could use this to run the same code with different base definitions, for example testing code by running it with \"safe\" versions of some operators:module Normal\ninclude(\"mycode.jl\")\nend\n\nmodule Testing\ninclude(\"safe_operators.jl\")\ninclude(\"mycode.jl\")\nend" -}, - -{ - "location": "manual/modules.html#Standard-modules-1", - "page": "Modules", - "title": "Standard modules", - "category": "section", - "text": "There are three important standard modules: Main, Core, and Base.Main is the top-level module, and Julia starts with Main set as the current module. Variables defined at the prompt go in Main, and whos() lists variables in Main.Core contains all identifiers considered \"built in\" to the language, i.e. part of the core language and not libraries. Every module implicitly specifies using Core, since you can\'t do anything without those definitions.Base is the standard library (the contents of base/). All modules implicitly contain using Base, since this is needed in the vast majority of cases." -}, - -{ - "location": "manual/modules.html#Default-top-level-definitions-and-bare-modules-1", - "page": "Modules", - "title": "Default top-level definitions and bare modules", - "category": "section", - "text": "In addition to using Base, modules also automatically contain a definition of the eval function, which evaluates expressions within the context of that module.If these default definitions are not wanted, modules can be defined using the keyword baremodule instead (note: Core is still imported, as per above). In terms of baremodule, a standard module looks like this:baremodule Mod\n\nusing Base\n\neval(x) = Core.eval(Mod, x)\neval(m,x) = Core.eval(m, x)\n\n...\n\nend" -}, - -{ - "location": "manual/modules.html#Relative-and-absolute-module-paths-1", - "page": "Modules", - "title": "Relative and absolute module paths", - "category": "section", - "text": "Given the statement using Foo, the system looks for Foo within Main. If the module does not exist, the system attempts to require(\"Foo\"), which typically results in loading code from an installed package.However, some modules contain submodules, which means you sometimes need to access a module that is not directly available in Main. There are two ways to do this. The first is to use an absolute path, for example using Base.Sort. The second is to use a relative path, which makes it easier to import submodules of the current module or any of its enclosing modules:module Parent\n\nmodule Utils\n...\nend\n\nusing .Utils\n\n...\nendHere module Parent contains a submodule Utils, and code in Parent wants the contents of Utils to be visible. This is done by starting the using path with a period. Adding more leading periods moves up additional levels in the module hierarchy. For example using ..Utils would look for Utils in Parent\'s enclosing module rather than in Parent itself.Note that relative-import qualifiers are only valid in using and import statements." -}, - -{ - "location": "manual/modules.html#Module-file-paths-1", - "page": "Modules", - "title": "Module file paths", - "category": "section", - "text": "The global variable LOAD_PATH contains the directories Julia searches for modules when calling require. It can be extended using push!:push!(LOAD_PATH, \"/Path/To/My/Module/\")Putting this statement in the file ~/.juliarc.jl will extend LOAD_PATH on every Julia startup. Alternatively, the module load path can be extended by defining the environment variable JULIA_LOAD_PATH." -}, - -{ - "location": "manual/modules.html#Namespace-miscellanea-1", - "page": "Modules", - "title": "Namespace miscellanea", - "category": "section", - "text": "If a name is qualified (e.g. Base.sin), then it can be accessed even if it is not exported. This is often useful when debugging. It can also have methods added to it by using the qualified name as the function name. However, due to syntactic ambiguities that arise, if you wish to add methods to a function in a different module whose name contains only symbols, such as an operator, Base.+ for example, you must use Base.:+ to refer to it. If the operator is more than one character in length you must surround it in brackets, such as: Base.:(==).Macro names are written with @ in import and export statements, e.g. import Mod.@mac. Macros in other modules can be invoked as Mod.@mac or @Mod.mac.The syntax M.x = y does not work to assign a global in another module; global assignment is always module-local.A variable can be \"reserved\" for the current module without assigning to it by declaring it as global x at the top level. This can be used to prevent name conflicts for globals initialized after load time." -}, - -{ - "location": "manual/modules.html#Module-initialization-and-precompilation-1", - "page": "Modules", - "title": "Module initialization and precompilation", - "category": "section", - "text": "Large modules can take several seconds to load because executing all of the statements in a module often involves compiling a large amount of code. Julia provides the ability to create precompiled versions of modules to reduce this time.To create an incremental precompiled module file, add __precompile__() at the top of your module file (before the module starts). This will cause it to be automatically compiled the first time it is imported. Alternatively, you can manually call Base.compilecache(modulename). The resulting cache files will be stored in Base.LOAD_CACHE_PATH[1]. Subsequently, the module is automatically recompiled upon import whenever any of its dependencies change; dependencies are modules it imports, the Julia build, files it includes, or explicit dependencies declared by include_dependency(path) in the module file(s).For file dependencies, a change is determined by examining whether the modification time (mtime) of each file loaded by include or added explicitly by include_dependency is unchanged, or equal to the modification time truncated to the nearest second (to accommodate systems that can\'t copy mtime with sub-second accuracy). It also takes into account whether the path to the file chosen by the search logic in require matches the path that had created the precompile file.It also takes into account the set of dependencies already loaded into the current process and won\'t recompile those modules, even if their files change or disappear, in order to avoid creating incompatibilities between the running system and the precompile cache. If you want to have changes to the source reflected in the running system, you should call reload(\"Module\") on the module you changed, and any module that depended on it in which you want to see the change reflected.Precompiling a module also recursively precompiles any modules that are imported therein. If you know that it is not safe to precompile your module (for the reasons described below), you should put __precompile__(false) in the module file to cause Base.compilecache to throw an error (and thereby prevent the module from being imported by any other precompiled module).__precompile__() should not be used in a module unless all of its dependencies are also using __precompile__(). Failure to do so can result in a runtime error when loading the module.In order to make your module work with precompilation, however, you may need to change your module to explicitly separate any initialization steps that must occur at runtime from steps that can occur at compile time. For this purpose, Julia allows you to define an __init__() function in your module that executes any initialization steps that must occur at runtime. This function will not be called during compilation (--output-* or __precompile__()). You may, of course, call it manually if necessary, but the default is to assume this function deals with computing state for the local machine, which does not need to be – or even should not be – captured in the compiled image. It will be called after the module is loaded into a process, including if it is being loaded into an incremental compile (--output-incremental=yes), but not if it is being loaded into a full-compilation process.In particular, if you define a function __init__() in a module, then Julia will call __init__() immediately after the module is loaded (e.g., by import, using, or require) at runtime for the first time (i.e., __init__ is only called once, and only after all statements in the module have been executed). Because it is called after the module is fully imported, any submodules or other imported modules have their __init__ functions called before the __init__ of the enclosing module.Two typical uses of __init__ are calling runtime initialization functions of external C libraries and initializing global constants that involve pointers returned by external libraries. For example, suppose that we are calling a C library libfoo that requires us to call a foo_init() initialization function at runtime. Suppose that we also want to define a global constant foo_data_ptr that holds the return value of a void *foo_data() function defined by libfoo – this constant must be initialized at runtime (not at compile time) because the pointer address will change from run to run. You could accomplish this by defining the following __init__ function in your module:const foo_data_ptr = Ref{Ptr{Void}}(0)\nfunction __init__()\n ccall((:foo_init, :libfoo), Void, ())\n foo_data_ptr[] = ccall((:foo_data, :libfoo), Ptr{Void}, ())\nendNotice that it is perfectly possible to define a global inside a function like __init__; this is one of the advantages of using a dynamic language. But by making it a constant at global scope, we can ensure that the type is known to the compiler and allow it to generate better optimized code. Obviously, any other globals in your module that depends on foo_data_ptr would also have to be initialized in __init__.Constants involving most Julia objects that are not produced by ccall do not need to be placed in __init__: their definitions can be precompiled and loaded from the cached module image. This includes complicated heap-allocated objects like arrays. However, any routine that returns a raw pointer value must be called at runtime for precompilation to work (Ptr objects will turn into null pointers unless they are hidden inside an isbits object). This includes the return values of the Julia functions cfunction and pointer.Dictionary and set types, or in general anything that depends on the output of a hash(key) method, are a trickier case. In the common case where the keys are numbers, strings, symbols, ranges, Expr, or compositions of these types (via arrays, tuples, sets, pairs, etc.) they are safe to precompile. However, for a few other key types, such as Function or DataType and generic user-defined types where you haven\'t defined a hash method, the fallback hash method depends on the memory address of the object (via its object_id) and hence may change from run to run. If you have one of these key types, or if you aren\'t sure, to be safe you can initialize this dictionary from within your __init__ function. Alternatively, you can use the ObjectIdDict dictionary type, which is specially handled by precompilation so that it is safe to initialize at compile-time.When using precompilation, it is important to keep a clear sense of the distinction between the compilation phase and the execution phase. In this mode, it will often be much more clearly apparent that Julia is a compiler which allows execution of arbitrary Julia code, not a standalone interpreter that also generates compiled code.Other known potential failure scenarios include:Global counters (for example, for attempting to uniquely identify objects) Consider the following code snippet:\nmutable struct UniquedById\n myid::Int\n let counter = 0\n UniquedById() = new(counter += 1)\n end\nend\nwhile the intent of this code was to give every instance a unique id, the counter value is recorded at the end of compilation. All subsequent usages of this incrementally compiled module will start from that same counter value.\nNote that object_id (which works by hashing the memory pointer) has similar issues (see notes on Dict usage below).\nOne alternative is to store both current_module() and the current counter value, however, it may be better to redesign the code to not depend on this global state.\nAssociative collections (such as Dict and Set) need to be re-hashed in __init__. (In the future, a mechanism may be provided to register an initializer function.)\nDepending on compile-time side-effects persisting through load-time. Example include: modifying arrays or other variables in other Julia modules; maintaining handles to open files or devices; storing pointers to other system resources (including memory);\nCreating accidental \"copies\" of global state from another module, by referencing it directly instead of via its lookup path. For example, (in global scope):\n#mystdout = Base.STDOUT #= will not work correctly, since this will copy Base.STDOUT into this module =#\n# instead use accessor functions:\ngetstdout() = Base.STDOUT #= best option =#\n# or move the assignment into the runtime:\n__init__() = global mystdout = Base.STDOUT #= also works =#Several additional restrictions are placed on the operations that can be done while precompiling code to help the user avoid other wrong-behavior situations:Calling eval to cause a side-effect in another module. This will also cause a warning to be emitted when the incremental precompile flag is set.\nglobal const statements from local scope after __init__() has been started (see issue #12010 for plans to add an error for this)\nReplacing a module (or calling workspace()) is a runtime error while doing an incremental precompile.A few other points to be aware of:No code reload / cache invalidation is performed after changes are made to the source files themselves, (including by Pkg.update), and no cleanup is done after Pkg.rm\nThe memory sharing behavior of a reshaped array is disregarded by precompilation (each view gets its own copy)\nExpecting the filesystem to be unchanged between compile-time and runtime e.g. @__FILE__/source_path() to find resources at runtime, or the BinDeps @checked_lib macro. Sometimes this is unavoidable. However, when possible, it can be good practice to copy resources into the module at compile-time so they won\'t need to be found at runtime.\nWeakRef objects and finalizers are not currently handled properly by the serializer (this will be fixed in an upcoming release).\nIt is usually best to avoid capturing references to instances of internal metadata objects such as Method, MethodInstance, MethodTable, TypeMapLevel, TypeMapEntry and fields of those objects, as this can confuse the serializer and may not lead to the outcome you desire. It is not necessarily an error to do this, but you simply need to be prepared that the system will try to copy some of these and to create a single unique instance of others.It is sometimes helpful during module development to turn off incremental precompilation. The command line flag --compilecache={yes|no} enables you to toggle module precompilation on and off. When Julia is started with --compilecache=no the serialized modules in the compile cache are ignored when loading modules and module dependencies. Base.compilecache() can still be called manually and it will respect __precompile__() directives for the module. The state of this command line flag is passed to Pkg.build() to disable automatic precompilation triggering when installing, updating, and explicitly building packages." -}, - -{ - "location": "manual/documentation.html#", - "page": "Documentation", - "title": "Documentation", - "category": "page", - "text": "" -}, - -{ - "location": "manual/documentation.html#Documentation-1", - "page": "Documentation", - "title": "Documentation", - "category": "section", - "text": "Julia enables package developers and users to document functions, types and other objects easily via a built-in documentation system since Julia 0.4.The basic syntax is very simple: any string appearing at the top-level right before an object (function, macro, type or instance) will be interpreted as documenting it (these are called docstrings). Here is a very simple example:\"Tell whether there are too foo items in the array.\"\nfoo(xs::Array) = ...Documentation is interpreted as Markdown, so you can use indentation and code fences to delimit code examples from text. Technically, any object can be associated with any other as metadata; Markdown happens to be the default, but one can construct other string macros and pass them to the @doc macro just as well.Here is a more complex example, still using Markdown:\"\"\"\n bar(x[, y])\n\nCompute the Bar index between `x` and `y`. If `y` is missing, compute\nthe Bar index between all pairs of columns of `x`.\n\n# Examples\n```julia-repl\njulia> bar([1, 2], [1, 2])\n1\n```\n\"\"\"\nfunction bar(x, y) ...As in the example above, we recommend following some simple conventions when writing documentation:Always show the signature of a function at the top of the documentation, with a four-space indent so that it is printed as Julia code.\nThis can be identical to the signature present in the Julia code (like mean(x::AbstractArray)), or a simplified form. Optional arguments should be represented with their default values (i.e. f(x, y=1)) when possible, following the actual Julia syntax. Optional arguments which do not have a default value should be put in brackets (i.e. f(x[, y]) and f(x[, y[, z]])). An alternative solution is to use several lines: one without optional arguments, the other(s) with them. This solution can also be used to document several related methods of a given function. When a function accepts many keyword arguments, only include a placeholder in the signature (i.e. f(x; )), and give the complete list under an # Arguments section (see point 4 below).\nInclude a single one-line sentence describing what the function does or what the object represents after the simplified signature block. If needed, provide more details in a second paragraph, after a blank line.\nThe one-line sentence should use the imperative form (\"Do this\", \"Return that\") instead of the third person (do not write \"Returns the length...\") when documenting functions. It should end with a period. If the meaning of a function cannot be summarized easily, splitting it into separate composable parts could be beneficial (this should not be taken as an absolute requirement for every single case though).\nDo not repeat yourself.\nSince the function name is given by the signature, there is no need to start the documentation with \"The function bar...\": go straight to the point. Similarly, if the signature specifies the types of the arguments, mentioning them in the description is redundant.\nOnly provide an argument list when really necessary.\nFor simple functions, it is often clearer to mention the role of the arguments directly in the description of the function\'s purpose. An argument list would only repeat information already provided elsewhere. However, providing an argument list can be a good idea for complex functions with many arguments (in particular keyword arguments). In that case, insert it after the general description of the function, under an # Arguments header, with one - bullet for each argument. The list should mention the types and default values (if any) of the arguments:\n\"\"\"\n...\n# Arguments\n- `n::Integer`: the number of elements to compute.\n- `dim::Integer=1`: the dimensions along which to perform the computation.\n...\n\"\"\"\nInclude any code examples in an # Examples section.\nExamples should, whenever possible, be written as doctests. A doctest is a fenced code block (see Code blocks) starting with ```jldoctest and contains any number of julia> prompts together with inputs and expected outputs that mimic the Julia REPL.\nFor example in the following docstring a variable a is defined and the expected result, as printed in a Julia REPL, appears afterwards:\n\"\"\"\nSome nice documentation here.\n\n# Examples\n\n```jldoctest\njulia> a = [1 2; 3 4]\n2×2 Array{Int64,2}:\n 1 2\n 3 4\n```\n\"\"\"\nwarning: Warning\nCalling rand and other RNG-related functions should be avoided in doctests since they will not produce consistent outputs during different Julia sessions.Operating system word size (Int32 or Int64) as well as path separator differences (/ or \\) will also affect the reproducibility of some doctests.Note that whitespace in your doctest is significant! The doctest will fail if you misalign the output of pretty-printing an array, for example.\nYou can then run make -C doc doctest to run all the doctests in the Julia Manual, which will ensure that your example works.\nExamples that are untestable should be written within fenced code blocks starting with ```julia so that they are highlighted correctly in the generated documentation.\ntip: Tip\nWherever possible examples should be self-contained and runnable so that readers are able to try them out without having to include any dependencies.\nUse backticks to identify code and equations.\nJulia identifiers and code excerpts should always appear between backticks ` to enable highlighting. Equations in the LaTeX syntax can be inserted between double backticks ``. Use Unicode characters rather than their LaTeX escape sequence, i.e. ``α = 1`` rather than ``\\\\alpha = 1``.\nPlace the starting and ending \"\"\" characters on lines by themselves.\nThat is, write:\n\"\"\"\n...\n\n...\n\"\"\"\nf(x, y) = ...\nrather than:\n\"\"\"...\n\n...\"\"\"\nf(x, y) = ...\nThis makes it more clear where docstrings start and end.\nRespect the line length limit used in the surrounding code.\nDocstrings are edited using the same tools as code. Therefore, the same conventions should apply. It it advised to add line breaks after 92 characters." -}, - -{ - "location": "manual/documentation.html#Accessing-Documentation-1", - "page": "Documentation", - "title": "Accessing Documentation", - "category": "section", - "text": "Documentation can be accessed at the REPL or in IJulia by typing ? followed by the name of a function or macro, and pressing Enter. For example,?fft\n?@time\n?r\"\"will bring up docs for the relevant function, macro or string macro respectively. In Juno using Ctrl-J, Ctrl-D will bring up documentation for the object under the cursor." -}, - -{ - "location": "manual/documentation.html#Functions-and-Methods-1", - "page": "Documentation", - "title": "Functions & Methods", - "category": "section", - "text": "Functions in Julia may have multiple implementations, known as methods. While it\'s good practice for generic functions to have a single purpose, Julia allows methods to be documented individually if necessary. In general, only the most generic method should be documented, or even the function itself (i.e. the object created without any methods by function bar end). Specific methods should only be documented if their behaviour differs from the more generic ones. In any case, they should not repeat the information provided elsewhere. For example:\"\"\"\n *(x, y, z...)\n\nMultiplication operator. `x * y * z *...` calls this function with multiple\narguments, i.e. `*(x, y, z...)`.\n\"\"\"\nfunction *(x, y, z...)\n # ... [implementation sold separately] ...\nend\n\n\"\"\"\n *(x::AbstractString, y::AbstractString, z::AbstractString...)\n\nWhen applied to strings, concatenates them.\n\"\"\"\nfunction *(x::AbstractString, y::AbstractString, z::AbstractString...)\n # ... [insert secret sauce here] ...\nend\n\nhelp?> *\nsearch: * .*\n\n *(x, y, z...)\n\n Multiplication operator. x * y * z *... calls this function with multiple\n arguments, i.e. *(x,y,z...).\n\n *(x::AbstractString, y::AbstractString, z::AbstractString...)\n\n When applied to strings, concatenates them.When retrieving documentation for a generic function, the metadata for each method is concatenated with the catdoc function, which can of course be overridden for custom types." -}, - -{ - "location": "manual/documentation.html#Advanced-Usage-1", - "page": "Documentation", - "title": "Advanced Usage", - "category": "section", - "text": "The @doc macro associates its first argument with its second in a per-module dictionary called META. By default, documentation is expected to be written in Markdown, and the doc\"\" string macro simply creates an object representing the Markdown content. In the future it is likely to do more advanced things such as allowing for relative image or link paths.When used for retrieving documentation, the @doc macro (or equally, the doc function) will search all META dictionaries for metadata relevant to the given object and return it. The returned object (some Markdown content, for example) will by default display itself intelligently. This design also makes it easy to use the doc system in a programmatic way; for example, to re-use documentation between different versions of a function:@doc \"...\" foo!\n@doc (@doc foo!) fooOr for use with Julia\'s metaprogramming functionality:for (f, op) in ((:add, :+), (:subtract, :-), (:multiply, :*), (:divide, :/))\n @eval begin\n $f(a,b) = $op(a,b)\n end\nend\n@doc \"`add(a,b)` adds `a` and `b` together\" add\n@doc \"`subtract(a,b)` subtracts `b` from `a`\" subtractDocumentation written in non-toplevel blocks, such as begin, if, for, and let, is added to the documentation system as blocks are evaluated. For example:if VERSION > v\"0.5\"\n \"...\"\n f(x) = x\nendwill add documentation to f(x) when the condition is true. Note that even if f(x) goes out of scope at the end of the block, its documentation will remain." -}, - -{ - "location": "manual/documentation.html#Dynamic-documentation-1", - "page": "Documentation", - "title": "Dynamic documentation", - "category": "section", - "text": "Sometimes the appropriate documentation for an instance of a type depends on the field values of that instance, rather than just on the type itself. In these cases, you can add a method to Docs.getdoc for your custom type that returns the documentation on a per-instance basis. For instance,struct MyType\n value::String\nend\n\nDocs.getdoc(t::MyType) = \"Documentation for MyType with value $(t.value)\"\n\nx = MyType(\"x\")\ny = MyType(\"y\")?x will display \"Documentation for MyType with value x\" while ?y will display \"Documentation for MyType with value y\"." -}, - -{ - "location": "manual/documentation.html#Syntax-Guide-1", - "page": "Documentation", - "title": "Syntax Guide", - "category": "section", - "text": "A comprehensive overview of all documentable Julia syntax.In the following examples \"...\" is used to illustrate an arbitrary docstring which may be one of the follow four variants and contain arbitrary text:\"...\"\n\ndoc\"...\"\n\n\"\"\"\n...\n\"\"\"\n\ndoc\"\"\"\n...\n\"\"\"@doc_str should only be used when the docstring contains $ or \\ characters that should not be parsed by Julia such as LaTeX syntax or Julia source code examples containing interpolation." -}, - -{ - "location": "manual/documentation.html#Functions-and-Methods-2", - "page": "Documentation", - "title": "Functions and Methods", - "category": "section", - "text": "\"...\"\nfunction f end\n\n\"...\"\nfAdds docstring \"...\" to Functionf. The first version is the preferred syntax, however both are equivalent.\"...\"\nf(x) = x\n\n\"...\"\nfunction f(x)\n x\nend\n\n\"...\"\nf(x)Adds docstring \"...\" to Methodf(::Any).\"...\"\nf(x, y = 1) = x + yAdds docstring \"...\" to two Methods, namely f(::Any) and f(::Any, ::Any)." -}, - -{ - "location": "manual/documentation.html#Macros-1", - "page": "Documentation", - "title": "Macros", - "category": "section", - "text": "\"...\"\nmacro m(x) endAdds docstring \"...\" to the @m(::Any) macro definition.\"...\"\n:(@m)Adds docstring \"...\" to the macro named @m." -}, - -{ - "location": "manual/documentation.html#Types-1", - "page": "Documentation", - "title": "Types", - "category": "section", - "text": "\"...\"\nabstract type T1 end\n\n\"...\"\nmutable struct T2\n ...\nend\n\n\"...\"\nstruct T3\n ...\nendAdds the docstring \"...\" to types T1, T2, and T3.\"...\"\nstruct T\n \"x\"\n x\n \"y\"\n y\nendAdds docstring \"...\" to type T, \"x\" to field T.x and \"y\" to field T.y. Also applicable to mutable struct types." -}, - -{ - "location": "manual/documentation.html#Modules-1", - "page": "Documentation", - "title": "Modules", - "category": "section", - "text": "\"...\"\nmodule M end\n\nmodule M\n\n\"...\"\nM\n\nendAdds docstring \"...\" to the ModuleM. Adding the docstring above the Module is the preferred syntax, however both are equivalent.\"...\"\nbaremodule M\n# ...\nend\n\nbaremodule M\n\nimport Base: @doc\n\n\"...\"\nf(x) = x\n\nendDocumenting a baremodule by placing a docstring above the expression automatically imports @doc into the module. These imports must be done manually when the module expression is not documented. Empty baremodules cannot be documented." -}, - -{ - "location": "manual/documentation.html#Global-Variables-1", - "page": "Documentation", - "title": "Global Variables", - "category": "section", - "text": "\"...\"\nconst a = 1\n\n\"...\"\nb = 2\n\n\"...\"\nglobal c = 3Adds docstring \"...\" to the Bindings a, b, and c.Bindings are used to store a reference to a particular Symbol in a Module without storing the referenced value itself.note: Note\nWhen a const definition is only used to define an alias of another definition, such as is the case with the function div and its alias ÷ in Base, do not document the alias and instead document the actual function.If the alias is documented and not the real definition then the docsystem (? mode) will not return the docstring attached to the alias when the real definition is searched for.For example you should write\"...\"\nf(x) = x + 1\nconst alias = frather thanf(x) = x + 1\n\"...\"\nconst alias = f\"...\"\nsymAdds docstring \"...\" to the value associated with sym. Users should prefer documenting sym at it\'s definition." -}, - -{ - "location": "manual/documentation.html#Multiple-Objects-1", - "page": "Documentation", - "title": "Multiple Objects", - "category": "section", - "text": "\"...\"\na, bAdds docstring \"...\" to a and b each of which should be a documentable expression. This syntax is equivalent to\"...\"\na\n\n\"...\"\nbAny number of expressions many be documented together in this way. This syntax can be useful when two functions are related, such as non-mutating and mutating versions f and f!." -}, - -{ - "location": "manual/documentation.html#Core.@__doc__", - "page": "Documentation", - "title": "Core.@__doc__", - "category": "macro", - "text": "@__doc__(ex)\n\nLow-level macro used to mark expressions returned by a macro that should be documented. If more than one expression is marked then the same docstring is applied to each expression.\n\nmacro example(f)\n quote\n $(f)() = 0\n @__doc__ $(f)(x) = 1\n $(f)(x, y) = 2\n end |> esc\nend\n\n@__doc__ has no effect when a macro that uses it is not documented.\n\n\n\n" -}, - -{ - "location": "manual/documentation.html#Macro-generated-code-1", - "page": "Documentation", - "title": "Macro-generated code", - "category": "section", - "text": "\"...\"\n@m expressionAdds docstring \"...\" to expression generated by expanding @m expression. This allows for expressions decorated with @inline, @noinline, @generated, or any other macro to be documented in the same way as undecorated expressions.Macro authors should take note that only macros that generate a single expression will automatically support docstrings. If a macro returns a block containing multiple subexpressions then the subexpression that should be documented must be marked using the @__doc__ macro.The @enum macro makes use of @__doc__ to allow for documenting Enums. Examining it\'s definition should serve as an example of how to use @__doc__ correctly.Core.@__doc__" -}, - -{ - "location": "manual/documentation.html#Markdown-syntax-1", - "page": "Documentation", - "title": "Markdown syntax", - "category": "section", - "text": "The following markdown syntax is supported in Julia." -}, - -{ - "location": "manual/documentation.html#Inline-elements-1", - "page": "Documentation", - "title": "Inline elements", - "category": "section", - "text": "Here \"inline\" refers to elements that can be found within blocks of text, i.e. paragraphs. These include the following elements." -}, - -{ - "location": "manual/documentation.html#Bold-1", - "page": "Documentation", - "title": "Bold", - "category": "section", - "text": "Surround words with two asterisks, **, to display the enclosed text in boldface.A paragraph containing a **bold** word." -}, - -{ - "location": "manual/documentation.html#Italics-1", - "page": "Documentation", - "title": "Italics", - "category": "section", - "text": "Surround words with one asterisk, *, to display the enclosed text in italics.A paragraph containing an *emphasised* word." -}, - -{ - "location": "manual/documentation.html#Literals-1", - "page": "Documentation", - "title": "Literals", - "category": "section", - "text": "Surround text that should be displayed exactly as written with single backticks, ` .A paragraph containing a `literal` word.Literals should be used when writing text that refers to names of variables, functions, or other parts of a Julia program.tip: Tip\nTo include a backtick character within literal text use three backticks rather than one to enclose the text.A paragraph containing a ``` `backtick` character ```.By extension any odd number of backticks may be used to enclose a lesser number of backticks." -}, - -{ - "location": "manual/documentation.html#\\LaTeX-1", - "page": "Documentation", - "title": "LaTeX", - "category": "section", - "text": "Surround text that should be displayed as mathematics using LaTeX syntax with double backticks, `` .A paragraph containing some ``\\LaTeX`` markup.tip: Tip\nAs with literals in the previous section, if literal backticks need to be written within double backticks use an even number greater than two. Note that if a single literal backtick needs to be included within LaTeX markup then two enclosing backticks is sufficient." -}, - -{ - "location": "manual/documentation.html#Links-1", - "page": "Documentation", - "title": "Links", - "category": "section", - "text": "Links to either external or internal addresses can be written using the following syntax, where the text enclosed in square brackets, [ ], is the name of the link and the text enclosed in parentheses, ( ), is the URL.A paragraph containing a link to [Julia](http://www.julialang.org).It\'s also possible to add cross-references to other documented functions/methods/variables within the Julia documentation itself. For example:\"\"\"\n eigvals!(A,[irange,][vl,][vu]) -> values\n\nSame as [`eigvals`](@ref), but saves space by overwriting the input `A`, instead of creating a copy.\n\"\"\"This will create a link in the generated docs to the eigvals documentation (which has more information about what this function actually does). It\'s good to include cross references to mutating/non-mutating versions of a function, or to highlight a difference between two similar-seeming functions.note: Note\nThe above cross referencing is not a Markdown feature, and relies on Documenter.jl, which is used to build base Julia\'s documentation." -}, - -{ - "location": "manual/documentation.html#Footnote-references-1", - "page": "Documentation", - "title": "Footnote references", - "category": "section", - "text": "Named and numbered footnote references can be written using the following syntax. A footnote name must be a single alphanumeric word containing no punctuation.A paragraph containing a numbered footnote [^1] and a named one [^named].note: Note\nThe text associated with a footnote can be written anywhere within the same page as the footnote reference. The syntax used to define the footnote text is discussed in the Footnotes section below." -}, - -{ - "location": "manual/documentation.html#Toplevel-elements-1", - "page": "Documentation", - "title": "Toplevel elements", - "category": "section", - "text": "The following elements can be written either at the \"toplevel\" of a document or within another \"toplevel\" element." -}, - -{ - "location": "manual/documentation.html#Paragraphs-1", - "page": "Documentation", - "title": "Paragraphs", - "category": "section", - "text": "A paragraph is a block of plain text, possibly containing any number of inline elements defined in the Inline elements section above, with one or more blank lines above and below it.This is a paragraph.\n\nAnd this is *another* one containing some emphasised text.\nA new line, but still part of the same paragraph." -}, - -{ - "location": "manual/documentation.html#Headers-1", - "page": "Documentation", - "title": "Headers", - "category": "section", - "text": "A document can be split up into different sections using headers. Headers use the following syntax:# Level One\n## Level Two\n### Level Three\n#### Level Four\n##### Level Five\n###### Level SixA header line can contain any inline syntax in the same way as a paragraph can.tip: Tip\nTry to avoid using too many levels of header within a single document. A heavily nested document may be indicative of a need to restructure it or split it into several pages covering separate topics." -}, - -{ - "location": "manual/documentation.html#Code-blocks-1", - "page": "Documentation", - "title": "Code blocks", - "category": "section", - "text": "Source code can be displayed as a literal block using an indent of four spaces as shown in the following example.This is a paragraph.\n\n function func(x)\n # ...\n end\n\nAnother paragraph.Additionally, code blocks can be enclosed using triple backticks with an optional \"language\" to specify how a block of code should be highlighted.A code block without a \"language\":\n\n```\nfunction func(x)\n # ...\nend\n```\n\nand another one with the \"language\" specified as `julia`:\n\n```julia\nfunction func(x)\n # ...\nend\n```note: Note\n\"Fenced\" code blocks, as shown in the last example, should be prefered over indented code blocks since there is no way to specify what language an indented code block is written in." -}, - -{ - "location": "manual/documentation.html#Block-quotes-1", - "page": "Documentation", - "title": "Block quotes", - "category": "section", - "text": "Text from external sources, such as quotations from books or websites, can be quoted using > characters prepended to each line of the quote as follows.Here\'s a quote:\n\n> Julia is a high-level, high-performance dynamic programming language for\n> technical computing, with syntax that is familiar to users of other\n> technical computing environments.Note that a single space must appear after the > character on each line. Quoted blocks may themselves contain other toplevel or inline elements." -}, - -{ - "location": "manual/documentation.html#Images-1", - "page": "Documentation", - "title": "Images", - "category": "section", - "text": "The syntax for images is similar to the link syntax mentioned above. Prepending a ! character to a link will display an image from the specified URL rather than a link to it.![alternative text](link/to/image.png)" -}, - -{ - "location": "manual/documentation.html#Lists-1", - "page": "Documentation", - "title": "Lists", - "category": "section", - "text": "Unordered lists can be written by prepending each item in a list with either *, +, or -.A list of items:\n\n * item one\n * item two\n * item threeNote the two spaces before each * and the single space after each one.Lists can contain other nested toplevel elements such as lists, code blocks, or quoteblocks. A blank line should be left between each list item when including any toplevel elements within a list.Another list:\n\n * item one\n\n * item two\n\n ```\n f(x) = x\n ```\n\n * And a sublist:\n\n + sub-item one\n + sub-item twonote: Note\nThe contents of each item in the list must line up with the first line of the item. In the above example the fenced code block must be indented by four spaces to align with the i in item two.Ordered lists are written by replacing the \"bullet\" character, either *, +, or -, with a positive integer followed by either . or ).Two ordered lists:\n\n 1. item one\n 2. item two\n 3. item three\n\n 5) item five\n 6) item six\n 7) item sevenAn ordered list may start from a number other than one, as in the second list of the above example, where it is numbered from five. As with unordered lists, ordered lists can contain nested toplevel elements." -}, - -{ - "location": "manual/documentation.html#Display-equations-1", - "page": "Documentation", - "title": "Display equations", - "category": "section", - "text": "Large LaTeX equations that do not fit inline within a paragraph may be written as display equations using a fenced code block with the \"language\" math as in the example below.```math\nf(a) = \\frac{1}{2\\pi}\\int_{0}^{2\\pi} (\\alpha+R\\cos(\\theta))d\\theta\n```" -}, - -{ - "location": "manual/documentation.html#Footnotes-1", - "page": "Documentation", - "title": "Footnotes", - "category": "section", - "text": "This syntax is paired with the inline syntax for Footnote references. Make sure to read that section as well.Footnote text is defined using the following syntax, which is similar to footnote reference syntax, aside from the : character that is appended to the footnote label.[^1]: Numbered footnote text.\n\n[^note]:\n\n Named footnote text containing several toplevel elements.\n\n * item one\n * item two\n * item three\n\n ```julia\n function func(x)\n # ...\n end\n ```note: Note\nNo checks are done during parsing to make sure that all footnote references have matching footnotes." -}, - -{ - "location": "manual/documentation.html#Horizontal-rules-1", - "page": "Documentation", - "title": "Horizontal rules", - "category": "section", - "text": "The equivalent of an
      HTML tag can be written using the following syntax:Text above the line.\n\n---\n\nAnd text below the line." -}, - -{ - "location": "manual/documentation.html#Tables-1", - "page": "Documentation", - "title": "Tables", - "category": "section", - "text": "Basic tables can be written using the syntax described below. Note that markdown tables have limited features and cannot contain nested toplevel elements unlike other elements discussed above – only inline elements are allowed. Tables must always contain a header row with column names. Cells cannot span multiple rows or columns of the table.| Column One | Column Two | Column Three |\n|:---------- | ---------- |:------------:|\n| Row `1` | Column `2` | |\n| *Row* 2 | **Row** 2 | Column ``3`` |note: Note\nAs illustrated in the above example each column of | characters must be aligned vertically.A : character on either end of a column\'s header separator (the row containing - characters) specifies whether the row is left-aligned, right-aligned, or (when : appears on both ends) center-aligned. Providing no : characters will default to right-aligning the column." -}, - -{ - "location": "manual/documentation.html#Admonitions-1", - "page": "Documentation", - "title": "Admonitions", - "category": "section", - "text": "Specially formatted blocks with titles such as \"Notes\", \"Warning\", or \"Tips\" are known as admonitions and are used when some part of a document needs special attention. They can be defined using the following !!! syntax:!!! note\n\n This is the content of the note.\n\n!!! warning \"Beware!\"\n\n And this is another one.\n\n This warning admonition has a custom title: `\"Beware!\"`.Admonitions, like most other toplevel elements, can contain other toplevel elements. When no title text, specified after the admonition type in double quotes, is included then the title used will be the type of the block, i.e. \"Note\" in the case of the note admonition." -}, - -{ - "location": "manual/documentation.html#Markdown-Syntax-Extensions-1", - "page": "Documentation", - "title": "Markdown Syntax Extensions", - "category": "section", - "text": "Julia\'s markdown supports interpolation in a very similar way to basic string literals, with the difference that it will store the object itself in the Markdown tree (as opposed to converting it to a string). When the Markdown content is rendered the usual show methods will be called, and these can be overridden as usual. This design allows the Markdown to be extended with arbitrarily complex features (such as references) without cluttering the basic syntax.In principle, the Markdown parser itself can also be arbitrarily extended by packages, or an entirely custom flavour of Markdown can be used, but this should generally be unnecessary." -}, - -{ - "location": "manual/metaprogramming.html#", - "page": "Metaprogramming", - "title": "Metaprogramming", - "category": "page", - "text": "" -}, - -{ - "location": "manual/metaprogramming.html#Metaprogramming-1", - "page": "Metaprogramming", - "title": "Metaprogramming", - "category": "section", - "text": "The strongest legacy of Lisp in the Julia language is its metaprogramming support. Like Lisp, Julia represents its own code as a data structure of the language itself. Since code is represented by objects that can be created and manipulated from within the language, it is possible for a program to transform and generate its own code. This allows sophisticated code generation without extra build steps, and also allows true Lisp-style macros operating at the level of abstract syntax trees. In contrast, preprocessor \"macro\" systems, like that of C and C++, perform textual manipulation and substitution before any actual parsing or interpretation occurs. Because all data types and code in Julia are represented by Julia data structures, powerful reflection capabilities are available to explore the internals of a program and its types just like any other data." -}, - -{ - "location": "manual/metaprogramming.html#Program-representation-1", - "page": "Metaprogramming", - "title": "Program representation", - "category": "section", - "text": "Every Julia program starts life as a string:julia> prog = \"1 + 1\"\n\"1 + 1\"What happens next?The next step is to parse each string into an object called an expression, represented by the Julia type Expr:julia> ex1 = parse(prog)\n:(1 + 1)\n\njulia> typeof(ex1)\nExprExpr objects contain two parts:a Symbol identifying the kind of expression. A symbol is an interned string identifier (more discussion below).julia> ex1.head\n:callthe expression arguments, which may be symbols, other expressions, or literal values:julia> ex1.args\n3-element Array{Any,1}:\n :+\n 1\n 1Expressions may also be constructed directly in prefix notation:julia> ex2 = Expr(:call, :+, 1, 1)\n:(1 + 1)The two expressions constructed above – by parsing and by direct construction – are equivalent:julia> ex1 == ex2\ntrueThe key point here is that Julia code is internally represented as a data structure that is accessible from the language itself.The dump() function provides indented and annotated display of Expr objects:julia> dump(ex2)\nExpr\n head: Symbol call\n args: Array{Any}((3,))\n 1: Symbol +\n 2: Int64 1\n 3: Int64 1\n typ: AnyExpr objects may also be nested:julia> ex3 = parse(\"(4 + 4) / 2\")\n:((4 + 4) / 2)Another way to view expressions is with Meta.show_sexpr, which displays the S-expression form of a given Expr, which may look very familiar to users of Lisp. Here\'s an example illustrating the display on a nested Expr:julia> Meta.show_sexpr(ex3)\n(:call, :/, (:call, :+, 4, 4), 2)" -}, - -{ - "location": "manual/metaprogramming.html#Symbols-1", - "page": "Metaprogramming", - "title": "Symbols", - "category": "section", - "text": "The : character has two syntactic purposes in Julia. The first form creates a Symbol, an interned string used as one building-block of expressions:julia> :foo\n:foo\n\njulia> typeof(ans)\nSymbolThe Symbol constructor takes any number of arguments and creates a new symbol by concatenating their string representations together:julia> :foo == Symbol(\"foo\")\ntrue\n\njulia> Symbol(\"func\",10)\n:func10\n\njulia> Symbol(:var,\'_\',\"sym\")\n:var_symIn the context of an expression, symbols are used to indicate access to variables; when an expression is evaluated, a symbol is replaced with the value bound to that symbol in the appropriate scope.Sometimes extra parentheses around the argument to : are needed to avoid ambiguity in parsing.:julia> :(:)\n:(:)\n\njulia> :(::)\n:(::)" -}, - -{ - "location": "manual/metaprogramming.html#Expressions-and-evaluation-1", - "page": "Metaprogramming", - "title": "Expressions and evaluation", - "category": "section", - "text": "" -}, - -{ - "location": "manual/metaprogramming.html#Quoting-1", - "page": "Metaprogramming", - "title": "Quoting", - "category": "section", - "text": "The second syntactic purpose of the : character is to create expression objects without using the explicit Expr constructor. This is referred to as quoting. The : character, followed by paired parentheses around a single statement of Julia code, produces an Expr object based on the enclosed code. Here is example of the short form used to quote an arithmetic expression:julia> ex = :(a+b*c+1)\n:(a + b * c + 1)\n\njulia> typeof(ex)\nExpr(to view the structure of this expression, try ex.head and ex.args, or use dump() as above)Note that equivalent expressions may be constructed using parse() or the direct Expr form:julia> :(a + b*c + 1) ==\n parse(\"a + b*c + 1\") ==\n Expr(:call, :+, :a, Expr(:call, :*, :b, :c), 1)\ntrueExpressions provided by the parser generally only have symbols, other expressions, and literal values as their args, whereas expressions constructed by Julia code can have arbitrary run-time values without literal forms as args. In this specific example, + and a are symbols, *(b,c) is a subexpression, and 1 is a literal 64-bit signed integer.There is a second syntactic form of quoting for multiple expressions: blocks of code enclosed in quote ... end. Note that this form introduces QuoteNode elements to the expression tree, which must be considered when directly manipulating an expression tree generated from quote blocks. For other purposes, :( ... ) and quote .. end blocks are treated identically.julia> ex = quote\n x = 1\n y = 2\n x + y\n end\nquote # none, line 2:\n x = 1 # none, line 3:\n y = 2 # none, line 4:\n x + y\nend\n\njulia> typeof(ex)\nExpr" -}, - -{ - "location": "manual/metaprogramming.html#Interpolation-1", - "page": "Metaprogramming", - "title": "Interpolation", - "category": "section", - "text": "Direct construction of Expr objects with value arguments is powerful, but Expr constructors can be tedious compared to \"normal\" Julia syntax. As an alternative, Julia allows \"splicing\" or interpolation of literals or expressions into quoted expressions. Interpolation is indicated by the $ prefix.In this example, the literal value of a is interpolated:julia> a = 1;\n\njulia> ex = :($a + b)\n:(1 + b)Interpolating into an unquoted expression is not supported and will cause a compile-time error:julia> $a + b\nERROR: unsupported or misplaced expression $\n ...In this example, the tuple (1,2,3) is interpolated as an expression into a conditional test:julia> ex = :(a in $:((1,2,3)) )\n:(a in (1, 2, 3))Interpolating symbols into a nested expression requires enclosing each symbol in an enclosing quote block:julia> :( :a in $( :(:a + :b) ) )\n ^^^^^^^^^^\n quoted inner expressionThe use of $ for expression interpolation is intentionally reminiscent of string interpolation and command interpolation. Expression interpolation allows convenient, readable programmatic construction of complex Julia expressions." -}, - -{ - "location": "manual/metaprogramming.html#[eval()](@ref)-and-effects-1", - "page": "Metaprogramming", - "title": "eval() and effects", - "category": "section", - "text": "Given an expression object, one can cause Julia to evaluate (execute) it at global scope using eval():julia> :(1 + 2)\n:(1 + 2)\n\njulia> eval(ans)\n3\n\njulia> ex = :(a + b)\n:(a + b)\n\njulia> eval(ex)\nERROR: UndefVarError: b not defined\n[...]\n\njulia> a = 1; b = 2;\n\njulia> eval(ex)\n3Every module has its own eval() function that evaluates expressions in its global scope. Expressions passed to eval() are not limited to returning values – they can also have side-effects that alter the state of the enclosing module\'s environment:julia> ex = :(x = 1)\n:(x = 1)\n\njulia> x\nERROR: UndefVarError: x not defined\n\njulia> eval(ex)\n1\n\njulia> x\n1Here, the evaluation of an expression object causes a value to be assigned to the global variable x.Since expressions are just Expr objects which can be constructed programmatically and then evaluated, it is possible to dynamically generate arbitrary code which can then be run using eval(). Here is a simple example:julia> a = 1;\n\njulia> ex = Expr(:call, :+, a, :b)\n:(1 + b)\n\njulia> a = 0; b = 2;\n\njulia> eval(ex)\n3The value of a is used to construct the expression ex which applies the + function to the value 1 and the variable b. Note the important distinction between the way a and b are used:The value of the variablea at expression construction time is used as an immediate value in the expression. Thus, the value of a when the expression is evaluated no longer matters: the value in the expression is already 1, independent of whatever the value of a might be.\nOn the other hand, the symbol:b is used in the expression construction, so the value of the variable b at that time is irrelevant – :b is just a symbol and the variable b need not even be defined. At expression evaluation time, however, the value of the symbol :b is resolved by looking up the value of the variable b." -}, - -{ - "location": "manual/metaprogramming.html#Functions-on-Expressions-1", - "page": "Metaprogramming", - "title": "Functions on Expressions", - "category": "section", - "text": "As hinted above, one extremely useful feature of Julia is the capability to generate and manipulate Julia code within Julia itself. We have already seen one example of a function returning Expr objects: the parse() function, which takes a string of Julia code and returns the corresponding Expr. A function can also take one or more Expr objects as arguments, and return another Expr. Here is a simple, motivating example:julia> function math_expr(op, op1, op2)\n expr = Expr(:call, op, op1, op2)\n return expr\n end\nmath_expr (generic function with 1 method)\n\njulia> ex = math_expr(:+, 1, Expr(:call, :*, 4, 5))\n:(1 + 4 * 5)\n\njulia> eval(ex)\n21As another example, here is a function that doubles any numeric argument, but leaves expressions alone:julia> function make_expr2(op, opr1, opr2)\n opr1f, opr2f = map(x -> isa(x, Number) ? 2*x : x, (opr1, opr2))\n retexpr = Expr(:call, op, opr1f, opr2f)\n return retexpr\n end\nmake_expr2 (generic function with 1 method)\n\njulia> make_expr2(:+, 1, 2)\n:(2 + 4)\n\njulia> ex = make_expr2(:+, 1, Expr(:call, :*, 5, 8))\n:(2 + 5 * 8)\n\njulia> eval(ex)\n42" -}, - -{ - "location": "manual/metaprogramming.html#man-macros-1", - "page": "Metaprogramming", - "title": "Macros", - "category": "section", - "text": "Macros provide a method to include generated code in the final body of a program. A macro maps a tuple of arguments to a returned expression, and the resulting expression is compiled directly rather than requiring a runtime eval() call. Macro arguments may include expressions, literal values, and symbols." -}, - -{ - "location": "manual/metaprogramming.html#Basics-1", - "page": "Metaprogramming", - "title": "Basics", - "category": "section", - "text": "Here is an extraordinarily simple macro:julia> macro sayhello()\n return :( println(\"Hello, world!\") )\n end\n@sayhello (macro with 1 method)Macros have a dedicated character in Julia\'s syntax: the @ (at-sign), followed by the unique name declared in a macro NAME ... end block. In this example, the compiler will replace all instances of @sayhello with::( println(\"Hello, world!\") )When @sayhello is entered in the REPL, the expression executes immediately, thus we only see the evaluation result:julia> @sayhello()\nHello, world!Now, consider a slightly more complex macro:julia> macro sayhello(name)\n return :( println(\"Hello, \", $name) )\n end\n@sayhello (macro with 1 method)This macro takes one argument: name. When @sayhello is encountered, the quoted expression is expanded to interpolate the value of the argument into the final expression:julia> @sayhello(\"human\")\nHello, humanWe can view the quoted return expression using the function macroexpand() (important note: this is an extremely useful tool for debugging macros):julia> ex = macroexpand( :(@sayhello(\"human\")) )\n:((println)(\"Hello, \", \"human\"))\n\njulia> typeof(ex)\nExprWe can see that the \"human\" literal has been interpolated into the expression.There also exists a macro @macroexpand that is perhaps a bit more convenient than the macroexpand function:julia> @macroexpand @sayhello \"human\"\n:((println)(\"Hello, \", \"human\"))" -}, - -{ - "location": "manual/metaprogramming.html#Hold-up:-why-macros?-1", - "page": "Metaprogramming", - "title": "Hold up: why macros?", - "category": "section", - "text": "We have already seen a function f(::Expr...) -> Expr in a previous section. In fact, macroexpand() is also such a function. So, why do macros exist?Macros are necessary because they execute when code is parsed, therefore, macros allow the programmer to generate and include fragments of customized code before the full program is run. To illustrate the difference, consider the following example:julia> macro twostep(arg)\n println(\"I execute at parse time. The argument is: \", arg)\n return :(println(\"I execute at runtime. The argument is: \", $arg))\n end\n@twostep (macro with 1 method)\n\njulia> ex = macroexpand( :(@twostep :(1, 2, 3)) );\nI execute at parse time. The argument is: $(Expr(:quote, :((1, 2, 3))))The first call to println() is executed when macroexpand() is called. The resulting expression contains only the second println:julia> typeof(ex)\nExpr\n\njulia> ex\n:((println)(\"I execute at runtime. The argument is: \", $(Expr(:copyast, :($(QuoteNode(:((1, 2, 3)))))))))\n\njulia> eval(ex)\nI execute at runtime. The argument is: (1, 2, 3)" -}, - -{ - "location": "manual/metaprogramming.html#Macro-invocation-1", - "page": "Metaprogramming", - "title": "Macro invocation", - "category": "section", - "text": "Macros are invoked with the following general syntax:@name expr1 expr2 ...\n@name(expr1, expr2, ...)Note the distinguishing @ before the macro name and the lack of commas between the argument expressions in the first form, and the lack of whitespace after @name in the second form. The two styles should not be mixed. For example, the following syntax is different from the examples above; it passes the tuple (expr1, expr2, ...) as one argument to the macro:@name (expr1, expr2, ...)It is important to emphasize that macros receive their arguments as expressions, literals, or symbols. One way to explore macro arguments is to call the show() function within the macro body:julia> macro showarg(x)\n show(x)\n # ... remainder of macro, returning an expression\n end\n@showarg (macro with 1 method)\n\njulia> @showarg(a)\n:a\n\njulia> @showarg(1+1)\n:(1 + 1)\n\njulia> @showarg(println(\"Yo!\"))\n:(println(\"Yo!\"))" -}, - -{ - "location": "manual/metaprogramming.html#Building-an-advanced-macro-1", - "page": "Metaprogramming", - "title": "Building an advanced macro", - "category": "section", - "text": "Here is a simplified definition of Julia\'s @assert macro:julia> macro assert(ex)\n return :( $ex ? nothing : throw(AssertionError($(string(ex)))) )\n end\n@assert (macro with 1 method)This macro can be used like this:julia> @assert 1 == 1.0\n\njulia> @assert 1 == 0\nERROR: AssertionError: 1 == 0In place of the written syntax, the macro call is expanded at parse time to its returned result. This is equivalent to writing:1 == 1.0 ? nothing : throw(AssertionError(\"1 == 1.0\"))\n1 == 0 ? nothing : throw(AssertionError(\"1 == 0\"))That is, in the first call, the expression :(1 == 1.0) is spliced into the test condition slot, while the value of string(:(1 == 1.0)) is spliced into the assertion message slot. The entire expression, thus constructed, is placed into the syntax tree where the @assert macro call occurs. Then at execution time, if the test expression evaluates to true, then nothing is returned, whereas if the test is false, an error is raised indicating the asserted expression that was false. Notice that it would not be possible to write this as a function, since only the value of the condition is available and it would be impossible to display the expression that computed it in the error message.The actual definition of @assert in the standard library is more complicated. It allows the user to optionally specify their own error message, instead of just printing the failed expression. Just like in functions with a variable number of arguments, this is specified with an ellipses following the last argument:julia> macro assert(ex, msgs...)\n msg_body = isempty(msgs) ? ex : msgs[1]\n msg = string(msg_body)\n return :($ex ? nothing : throw(AssertionError($msg)))\n end\n@assert (macro with 1 method)Now @assert has two modes of operation, depending upon the number of arguments it receives! If there\'s only one argument, the tuple of expressions captured by msgs will be empty and it will behave the same as the simpler definition above. But now if the user specifies a second argument, it is printed in the message body instead of the failing expression. You can inspect the result of a macro expansion with the aptly named macroexpand() function:julia> macroexpand(:(@assert a == b))\n:(if a == b\n nothing\n else\n (throw)((AssertionError)(\"a == b\"))\n end)\n\njulia> macroexpand(:(@assert a==b \"a should equal b!\"))\n:(if a == b\n nothing\n else\n (throw)((AssertionError)(\"a should equal b!\"))\n end)There is yet another case that the actual @assert macro handles: what if, in addition to printing \"a should equal b,\" we wanted to print their values? One might naively try to use string interpolation in the custom message, e.g., @assert a==b \"a ($a) should equal b ($b)!\", but this won\'t work as expected with the above macro. Can you see why? Recall from string interpolation that an interpolated string is rewritten to a call to string(). Compare:julia> typeof(:(\"a should equal b\"))\nString\n\njulia> typeof(:(\"a ($a) should equal b ($b)!\"))\nExpr\n\njulia> dump(:(\"a ($a) should equal b ($b)!\"))\nExpr\n head: Symbol string\n args: Array{Any}((5,))\n 1: String \"a (\"\n 2: Symbol a\n 3: String \") should equal b (\"\n 4: Symbol b\n 5: String \")!\"\n typ: AnySo now instead of getting a plain string in msg_body, the macro is receiving a full expression that will need to be evaluated in order to display as expected. This can be spliced directly into the returned expression as an argument to the string() call; see error.jl for the complete implementation.The @assert macro makes great use of splicing into quoted expressions to simplify the manipulation of expressions inside the macro body." -}, - -{ - "location": "manual/metaprogramming.html#Hygiene-1", - "page": "Metaprogramming", - "title": "Hygiene", - "category": "section", - "text": "An issue that arises in more complex macros is that of hygiene. In short, macros must ensure that the variables they introduce in their returned expressions do not accidentally clash with existing variables in the surrounding code they expand into. Conversely, the expressions that are passed into a macro as arguments are often expected to evaluate in the context of the surrounding code, interacting with and modifying the existing variables. Another concern arises from the fact that a macro may be called in a different module from where it was defined. In this case we need to ensure that all global variables are resolved to the correct module. Julia already has a major advantage over languages with textual macro expansion (like C) in that it only needs to consider the returned expression. All the other variables (such as msg in @assert above) follow the normal scoping block behavior.To demonstrate these issues, let us consider writing a @time macro that takes an expression as its argument, records the time, evaluates the expression, records the time again, prints the difference between the before and after times, and then has the value of the expression as its final value. The macro might look like this:macro time(ex)\n return quote\n local t0 = time()\n local val = $ex\n local t1 = time()\n println(\"elapsed time: \", t1-t0, \" seconds\")\n val\n end\nendHere, we want t0, t1, and val to be private temporary variables, and we want time to refer to the time() function in the standard library, not to any time variable the user might have (the same applies to println). Imagine the problems that could occur if the user expression ex also contained assignments to a variable called t0, or defined its own time variable. We might get errors, or mysteriously incorrect behavior.Julia\'s macro expander solves these problems in the following way. First, variables within a macro result are classified as either local or global. A variable is considered local if it is assigned to (and not declared global), declared local, or used as a function argument name. Otherwise, it is considered global. Local variables are then renamed to be unique (using the gensym() function, which generates new symbols), and global variables are resolved within the macro definition environment. Therefore both of the above concerns are handled; the macro\'s locals will not conflict with any user variables, and time and println will refer to the standard library definitions.One problem remains however. Consider the following use of this macro:module MyModule\nimport Base.@time\n\ntime() = ... # compute something\n\n@time time()\nendHere the user expression ex is a call to time, but not the same time function that the macro uses. It clearly refers to MyModule.time. Therefore we must arrange for the code in ex to be resolved in the macro call environment. This is done by \"escaping\" the expression with esc():macro time(ex)\n ...\n local val = $(esc(ex))\n ...\nendAn expression wrapped in this manner is left alone by the macro expander and simply pasted into the output verbatim. Therefore it will be resolved in the macro call environment.This escaping mechanism can be used to \"violate\" hygiene when necessary, in order to introduce or manipulate user variables. For example, the following macro sets x to zero in the call environment:julia> macro zerox()\n return esc(:(x = 0))\n end\n@zerox (macro with 1 method)\n\njulia> function foo()\n x = 1\n @zerox\n return x # is zero\n end\nfoo (generic function with 1 method)\n\njulia> foo()\n0This kind of manipulation of variables should be used judiciously, but is occasionally quite handy." -}, - -{ - "location": "manual/metaprogramming.html#Code-Generation-1", - "page": "Metaprogramming", - "title": "Code Generation", - "category": "section", - "text": "When a significant amount of repetitive boilerplate code is required, it is common to generate it programmatically to avoid redundancy. In most languages, this requires an extra build step, and a separate program to generate the repetitive code. In Julia, expression interpolation and eval() allow such code generation to take place in the normal course of program execution. For example, the following code defines a series of operators on three arguments in terms of their 2-argument forms:for op = (:+, :*, :&, :|, :$)\n eval(quote\n ($op)(a,b,c) = ($op)(($op)(a,b),c)\n end)\nendIn this manner, Julia acts as its own preprocessor, and allows code generation from inside the language. The above code could be written slightly more tersely using the : prefix quoting form:for op = (:+, :*, :&, :|, :$)\n eval(:(($op)(a,b,c) = ($op)(($op)(a,b),c)))\nendThis sort of in-language code generation, however, using the eval(quote(...)) pattern, is common enough that Julia comes with a macro to abbreviate this pattern:for op = (:+, :*, :&, :|, :$)\n @eval ($op)(a,b,c) = ($op)(($op)(a,b),c)\nendThe @eval macro rewrites this call to be precisely equivalent to the above longer versions. For longer blocks of generated code, the expression argument given to @eval can be a block:@eval begin\n # multiple lines\nend" -}, - -{ - "location": "manual/metaprogramming.html#Non-Standard-String-Literals-1", - "page": "Metaprogramming", - "title": "Non-Standard String Literals", - "category": "section", - "text": "Recall from Strings that string literals prefixed by an identifier are called non-standard string literals, and can have different semantics than un-prefixed string literals. For example:r\"^\\s*(?:#|$)\" produces a regular expression object rather than a string\nb\"DATA\\xff\\u2200\" is a byte array literal for [68,65,84,65,255,226,136,128].Perhaps surprisingly, these behaviors are not hard-coded into the Julia parser or compiler. Instead, they are custom behaviors provided by a general mechanism that anyone can use: prefixed string literals are parsed as calls to specially-named macros. For example, the regular expression macro is just the following:macro r_str(p)\n Regex(p)\nendThat\'s all. This macro says that the literal contents of the string literal r\"^\\s*(?:#|$)\" should be passed to the @r_str macro and the result of that expansion should be placed in the syntax tree where the string literal occurs. In other words, the expression r\"^\\s*(?:#|$)\" is equivalent to placing the following object directly into the syntax tree:Regex(\"^\\\\s*(?:#|\\$)\")Not only is the string literal form shorter and far more convenient, but it is also more efficient: since the regular expression is compiled and the Regex object is actually created when the code is compiled, the compilation occurs only once, rather than every time the code is executed. Consider if the regular expression occurs in a loop:for line = lines\n m = match(r\"^\\s*(?:#|$)\", line)\n if m === nothing\n # non-comment\n else\n # comment\n end\nendSince the regular expression r\"^\\s*(?:#|$)\" is compiled and inserted into the syntax tree when this code is parsed, the expression is only compiled once instead of each time the loop is executed. In order to accomplish this without macros, one would have to write this loop like this:re = Regex(\"^\\\\s*(?:#|\\$)\")\nfor line = lines\n m = match(re, line)\n if m === nothing\n # non-comment\n else\n # comment\n end\nendMoreover, if the compiler could not determine that the regex object was constant over all loops, certain optimizations might not be possible, making this version still less efficient than the more convenient literal form above. Of course, there are still situations where the non-literal form is more convenient: if one needs to interpolate a variable into the regular expression, one must take this more verbose approach; in cases where the regular expression pattern itself is dynamic, potentially changing upon each loop iteration, a new regular expression object must be constructed on each iteration. In the vast majority of use cases, however, regular expressions are not constructed based on run-time data. In this majority of cases, the ability to write regular expressions as compile-time values is invaluable.Like non-standard string literals, non-standard command literals exist using a prefixed variant of the command literal syntax. The command literal custom`literal` is parsed as @custom_cmd \"literal\". Julia itself does not contain any non-standard command literals, but packages can make use of this syntax. Aside from the different syntax and the _cmd suffix instead of the _str suffix, non-standard command literals behave exactly like non-standard string literals.In the event that two modules provide non-standard string or command literals with the same name, it is possible to qualify the string or command literal with a module name. For instance, if both Foo and Bar provide non-standard string literal @x_str, then one can write Foo.x\"literal\" or Bar.x\"literal\" to disambiguate between the two.The mechanism for user-defined string literals is deeply, profoundly powerful. Not only are Julia\'s non-standard literals implemented using it, but also the command literal syntax (`echo \"Hello, $person\"`) is implemented with the following innocuous-looking macro:macro cmd(str)\n :(cmd_gen($(shell_parse(str)[1])))\nendOf course, a large amount of complexity is hidden in the functions used in this macro definition, but they are just functions, written entirely in Julia. You can read their source and see precisely what they do – and all they do is construct expression objects to be inserted into your program\'s syntax tree." -}, - -{ - "location": "manual/metaprogramming.html#Generated-functions-1", - "page": "Metaprogramming", - "title": "Generated functions", - "category": "section", - "text": "A very special macro is @generated, which allows you to define so-called generated functions. These have the capability to generate specialized code depending on the types of their arguments with more flexibility and/or less code than what can be achieved with multiple dispatch. While macros work with expressions at parsing-time and cannot access the types of their inputs, a generated function gets expanded at a time when the types of the arguments are known, but the function is not yet compiled.Instead of performing some calculation or action, a generated function declaration returns a quoted expression which then forms the body for the method corresponding to the types of the arguments. When called, the body expression is first evaluated and compiled, then the returned expression is compiled and run. To make this efficient, the result is often cached. And to make this inferable, only a limited subset of the language is usable. Thus, generated functions provide a flexible framework to move work from run-time to compile-time, at the expense of greater restrictions on the allowable constructs.When defining generated functions, there are four main differences to ordinary functions:You annotate the function declaration with the @generated macro. This adds some information to the AST that lets the compiler know that this is a generated function.\nIn the body of the generated function you only have access to the types of the arguments – not their values – and any function that was defined before the definition of the generated function.\nInstead of calculating something or performing some action, you return a quoted expression which, when evaluated, does what you want.\nGenerated functions must not mutate or observe any non-constant global state (including, for example, IO, locks, non-local dictionaries, or using method_exists). This means they can only read global constants, and cannot have any side effects. In other words, they must be completely pure. Due to an implementation limitation, this also means that they currently cannot define a closure or untyped generator.It\'s easiest to illustrate this with an example. We can declare a generated function foo asjulia> @generated function foo(x)\n Core.println(x)\n return :(x * x)\n end\nfoo (generic function with 1 method)Note that the body returns a quoted expression, namely :(x * x), rather than just the value of x * x.From the caller\'s perspective, they are very similar to regular functions; in fact, you don\'t have to know if you\'re calling a regular or generated function - the syntax and result of the call is just the same. Let\'s see how foo behaves:julia> x = foo(2); # note: output is from println() statement in the body\nInt64\n\njulia> x # now we print x\n4\n\njulia> y = foo(\"bar\");\nString\n\njulia> y\n\"barbar\"So, we see that in the body of the generated function, x is the type of the passed argument, and the value returned by the generated function, is the result of evaluating the quoted expression we returned from the definition, now with the value of x.What happens if we evaluate foo again with a type that we have already used?julia> foo(4)\n16Note that there is no printout of Int64. We can see that the body of the generated function was only executed once here, for the specific set of argument types, and the result was cached. After that, for this example, the expression returned from the generated function on the first invocation was re-used as the method body. However, the actual caching behavior is an implementation-defined performance optimization, so it is invalid to depend too closely on this behavior.The number of times a generated function is generated might be only once, but it might also be more often, or appear to not happen at all. As a consequence, you should never write a generated function with side effects - when, and how often, the side effects occur is undefined. (This is true for macros too - and just like for macros, the use of eval() in a generated function is a sign that you\'re doing something the wrong way.) However, unlike macros, the runtime system cannot correctly handle a call to eval(), so it is disallowed.It is also important to see how @generated functions interact with method redefinition. Following the principle that a correct @generated function must not observe any mutable state or cause any mutation of global state, we see the following behavior. Observe that the generated function cannot call any method that was not defined prior to the definition of the generated function itself.Initially f(x) has one definitionjulia> f(x) = \"original definition\";Define other operations that use f(x):julia> g(x) = f(x);\n\njulia> @generated gen1(x) = f(x);\n\njulia> @generated gen2(x) = :(f(x));We now add some new definitions for f(x):julia> f(x::Int) = \"definition for Int\";\n\njulia> f(x::Type{Int}) = \"definition for Type{Int}\";and compare how these results differ:julia> f(1)\n\"definition for Int\"\n\njulia> g(1)\n\"definition for Int\"\n\njulia> gen1(1)\n\"original definition\"\n\njulia> gen2(1)\n\"definition for Int\"Each method of a generated function has its own view of defined functions:julia> @generated gen1(x::Real) = f(x);\n\njulia> gen1(1)\n\"definition for Type{Int}\"The example generated function foo above did not do anything a normal function foo(x) = x * x could not do (except printing the type on the first invocation, and incurring higher overhead). However, the power of a generated function lies in its ability to compute different quoted expressions depending on the types passed to it:julia> @generated function bar(x)\n if x <: Integer\n return :(x ^ 2)\n else\n return :(x)\n end\n end\nbar (generic function with 1 method)\n\njulia> bar(4)\n16\n\njulia> bar(\"baz\")\n\"baz\"(although of course this contrived example would be more easily implemented using multiple dispatch...)Abusing this will corrupt the runtime system and cause undefined behavior:julia> @generated function baz(x)\n if rand() < .9\n return :(x^2)\n else\n return :(\"boo!\")\n end\n end\nbaz (generic function with 1 method)Since the body of the generated function is non-deterministic, its behavior, and the behavior of all subsequent code is undefined.Don\'t copy these examples!These examples are hopefully helpful to illustrate how generated functions work, both in the definition end and at the call site; however, don\'t copy them, for the following reasons:the foo function has side-effects (the call to Core.println), and it is undefined exactly when, how often or how many times these side-effects will occur\nthe bar function solves a problem that is better solved with multiple dispatch - defining bar(x) = x and bar(x::Integer) = x ^ 2 will do the same thing, but it is both simpler and faster.\nthe baz function is pathologically insaneNote that the set of operations that should not be attempted in a generated function is unbounded, and the runtime system can currently only detect a subset of the invalid operations. There are many other operations that will simply corrupt the runtime system without notification, usually in subtle ways not obviously connected to the bad definition. Because the function generator is run during inference, it must respect all of the limitations of that code.Some operations that should not be attempted include:Caching of native pointers.\nInteracting with the contents or methods of Core.Inference in any way.\nObserving any mutable state.\nInference on the generated function may be run at any time, including while your code is attempting to observe or mutate this state.\nTaking any locks: C code you call out to may use locks internally, (for example, it is not problematic to call malloc, even though most implementations require locks internally) but don\'t attempt to hold or acquire any while executing Julia code.\nCalling any function that is defined after the body of the generated function. This condition is relaxed for incrementally-loaded precompiled modules to allow calling any function in the module.Alright, now that we have a better understanding of how generated functions work, let\'s use them to build some more advanced (and valid) functionality..." -}, - -{ - "location": "manual/metaprogramming.html#An-advanced-example-1", - "page": "Metaprogramming", - "title": "An advanced example", - "category": "section", - "text": "Julia\'s base library has a sub2ind() function to calculate a linear index into an n-dimensional array, based on a set of n multilinear indices - in other words, to calculate the index i that can be used to index into an array A using A[i], instead of A[x,y,z,...]. One possible implementation is the following:julia> function sub2ind_loop(dims::NTuple{N}, I::Integer...) where N\n ind = I[N] - 1\n for i = N-1:-1:1\n ind = I[i]-1 + dims[i]*ind\n end\n return ind + 1\n end\nsub2ind_loop (generic function with 1 method)\n\njulia> sub2ind_loop((3, 5), 1, 2)\n4The same thing can be done using recursion:julia> sub2ind_rec(dims::Tuple{}) = 1;\n\njulia> sub2ind_rec(dims::Tuple{}, i1::Integer, I::Integer...) =\n i1 == 1 ? sub2ind_rec(dims, I...) : throw(BoundsError());\n\njulia> sub2ind_rec(dims::Tuple{Integer, Vararg{Integer}}, i1::Integer) = i1;\n\njulia> sub2ind_rec(dims::Tuple{Integer, Vararg{Integer}}, i1::Integer, I::Integer...) =\n i1 + dims[1] * (sub2ind_rec(Base.tail(dims), I...) - 1);\n\njulia> sub2ind_rec((3, 5), 1, 2)\n4Both these implementations, although different, do essentially the same thing: a runtime loop over the dimensions of the array, collecting the offset in each dimension into the final index.However, all the information we need for the loop is embedded in the type information of the arguments. Thus, we can utilize generated functions to move the iteration to compile-time; in compiler parlance, we use generated functions to manually unroll the loop. The body becomes almost identical, but instead of calculating the linear index, we build up an expression that calculates the index:julia> @generated function sub2ind_gen(dims::NTuple{N}, I::Integer...) where N\n ex = :(I[$N] - 1)\n for i = (N - 1):-1:1\n ex = :(I[$i] - 1 + dims[$i] * $ex)\n end\n return :($ex + 1)\n end\nsub2ind_gen (generic function with 1 method)\n\njulia> sub2ind_gen((3, 5), 1, 2)\n4What code will this generate?An easy way to find out is to extract the body into another (regular) function:julia> @generated function sub2ind_gen(dims::NTuple{N}, I::Integer...) where N\n return sub2ind_gen_impl(dims, I...)\n end\nsub2ind_gen (generic function with 1 method)\n\njulia> function sub2ind_gen_impl(dims::Type{T}, I...) where T <: NTuple{N,Any} where N\n length(I) == N || return :(error(\"partial indexing is unsupported\"))\n ex = :(I[$N] - 1)\n for i = (N - 1):-1:1\n ex = :(I[$i] - 1 + dims[$i] * $ex)\n end\n return :($ex + 1)\n end\nsub2ind_gen_impl (generic function with 1 method)We can now execute sub2ind_gen_impl and examine the expression it returns:julia> sub2ind_gen_impl(Tuple{Int,Int}, Int, Int)\n:(((I[1] - 1) + dims[1] * (I[2] - 1)) + 1)So, the method body that will be used here doesn\'t include a loop at all - just indexing into the two tuples, multiplication and addition/subtraction. All the looping is performed compile-time, and we avoid looping during execution entirely. Thus, we only loop once per type, in this case once per N (except in edge cases where the function is generated more than once - see disclaimer above)." -}, - -{ - "location": "manual/arrays.html#", - "page": "Multi-dimensional Arrays", - "title": "Multi-dimensional Arrays", - "category": "page", - "text": "" -}, - -{ - "location": "manual/arrays.html#man-multi-dim-arrays-1", - "page": "Multi-dimensional Arrays", - "title": "Multi-dimensional Arrays", - "category": "section", - "text": "Julia, like most technical computing languages, provides a first-class array implementation. Most technical computing languages pay a lot of attention to their array implementation at the expense of other containers. Julia does not treat arrays in any special way. The array library is implemented almost completely in Julia itself, and derives its performance from the compiler, just like any other code written in Julia. As such, it\'s also possible to define custom array types by inheriting from AbstractArray. See the manual section on the AbstractArray interface for more details on implementing a custom array type.An array is a collection of objects stored in a multi-dimensional grid. In the most general case, an array may contain objects of type Any. For most computational purposes, arrays should contain objects of a more specific type, such as Float64 or Int32.In general, unlike many other technical computing languages, Julia does not expect programs to be written in a vectorized style for performance. Julia\'s compiler uses type inference and generates optimized code for scalar array indexing, allowing programs to be written in a style that is convenient and readable, without sacrificing performance, and using less memory at times.In Julia, all arguments to functions are passed by reference. Some technical computing languages pass arrays by value, and this is convenient in many cases. In Julia, modifications made to input arrays within a function will be visible in the parent function. The entire Julia array library ensures that inputs are not modified by library functions. User code, if it needs to exhibit similar behavior, should take care to create a copy of inputs that it may modify." -}, - -{ - "location": "manual/arrays.html#Arrays-1", - "page": "Multi-dimensional Arrays", - "title": "Arrays", - "category": "section", - "text": "" -}, - -{ - "location": "manual/arrays.html#Basic-Functions-1", - "page": "Multi-dimensional Arrays", - "title": "Basic Functions", - "category": "section", - "text": "Function Description\neltype(A) the type of the elements contained in A\nlength(A) the number of elements in A\nndims(A) the number of dimensions of A\nsize(A) a tuple containing the dimensions of A\nsize(A,n) the size of A along dimension n\nindices(A) a tuple containing the valid indices of A\nindices(A,n) a range expressing the valid indices along dimension n\neachindex(A) an efficient iterator for visiting each position in A\nstride(A,k) the stride (linear index distance between adjacent elements) along dimension k\nstrides(A) a tuple of the strides in each dimension" -}, - -{ - "location": "manual/arrays.html#Construction-and-Initialization-1", - "page": "Multi-dimensional Arrays", - "title": "Construction and Initialization", - "category": "section", - "text": "Many functions for constructing and initializing arrays are provided. In the following list of such functions, calls with a dims... argument can either take a single tuple of dimension sizes or a series of dimension sizes passed as a variable number of arguments. Most of these functions also accept a first input T, which is the element type of the array. If the type T is omitted it will default to Float64.Function Description\nArray{T}(dims...) an uninitialized dense Array\nzeros(T, dims...) an Array of all zeros\nzeros(A) an array of all zeros with the same type, element type and shape as A\nones(T, dims...) an Array of all ones\nones(A) an array of all ones with the same type, element type and shape as A\ntrues(dims...) a BitArray with all values true\ntrues(A) a BitArray with all values true and the same shape as A\nfalses(dims...) a BitArray with all values false\nfalses(A) a BitArray with all values false and the same shape as A\nreshape(A, dims...) an array containing the same data as A, but with different dimensions\ncopy(A) copy A\ndeepcopy(A) copy A, recursively copying its elements\nsimilar(A, T, dims...) an uninitialized array of the same type as A (dense, sparse, etc.), but with the specified element type and dimensions. The second and third arguments are both optional, defaulting to the element type and dimensions of A if omitted.\nreinterpret(T, A) an array with the same binary data as A, but with element type T\nrand(T, dims...) an Array with random, iid [1] and uniformly distributed values in the half-open interval 0 1)\nrandn(T, dims...) an Array with random, iid and standard normally distributed values\neye(T, n) n-by-n identity matrix\neye(T, m, n) m-by-n identity matrix\nlinspace(start, stop, n) range of n linearly spaced elements from start to stop\nfill!(A, x) fill the array A with the value x\nfill(x, dims...) an Array filled with the value x[1]: iid, independently and identically distributed.The syntax [A, B, C, ...] constructs a 1-d array (vector) of its arguments. If all arguments have a common promotion type then they get converted to that type using convert()." -}, - -{ - "location": "manual/arrays.html#Concatenation-1", - "page": "Multi-dimensional Arrays", - "title": "Concatenation", - "category": "section", - "text": "Arrays can be constructed and also concatenated using the following functions:Function Description\ncat(k, A...) concatenate input n-d arrays along the dimension k\nvcat(A...) shorthand for cat(1, A...)\nhcat(A...) shorthand for cat(2, A...)Scalar values passed to these functions are treated as 1-element arrays.The concatenation functions are used so often that they have special syntax:Expression Calls\n[A; B; C; ...] vcat()\n[A B C ...] hcat()\n[A B; C D; ...] hvcat()hvcat() concatenates in both dimension 1 (with semicolons) and dimension 2 (with spaces)." -}, - -{ - "location": "manual/arrays.html#Typed-array-initializers-1", - "page": "Multi-dimensional Arrays", - "title": "Typed array initializers", - "category": "section", - "text": "An array with a specific element type can be constructed using the syntax T[A, B, C, ...]. This will construct a 1-d array with element type T, initialized to contain elements A, B, C, etc. For example Any[x, y, z] constructs a heterogeneous array that can contain any values.Concatenation syntax can similarly be prefixed with a type to specify the element type of the result.julia> [[1 2] [3 4]]\n1×4 Array{Int64,2}:\n 1 2 3 4\n\njulia> Int8[[1 2] [3 4]]\n1×4 Array{Int8,2}:\n 1 2 3 4" -}, - -{ - "location": "manual/arrays.html#Comprehensions-1", - "page": "Multi-dimensional Arrays", - "title": "Comprehensions", - "category": "section", - "text": "Comprehensions provide a general and powerful way to construct arrays. Comprehension syntax is similar to set construction notation in mathematics:A = [ F(x,y,...) for x=rx, y=ry, ... ]The meaning of this form is that F(x,y,...) is evaluated with the variables x, y, etc. taking on each value in their given list of values. Values can be specified as any iterable object, but will commonly be ranges like 1:n or 2:(n-1), or explicit arrays of values like [1.2, 3.4, 5.7]. The result is an N-d dense array with dimensions that are the concatenation of the dimensions of the variable ranges rx, ry, etc. and each F(x,y,...) evaluation returns a scalar.The following example computes a weighted average of the current element and its left and right neighbor along a 1-d grid. :julia> x = rand(8)\n8-element Array{Float64,1}:\n 0.843025\n 0.869052\n 0.365105\n 0.699456\n 0.977653\n 0.994953\n 0.41084\n 0.809411\n\njulia> [ 0.25*x[i-1] + 0.5*x[i] + 0.25*x[i+1] for i=2:length(x)-1 ]\n6-element Array{Float64,1}:\n 0.736559\n 0.57468\n 0.685417\n 0.912429\n 0.8446\n 0.656511The resulting array type depends on the types of the computed elements. In order to control the type explicitly, a type can be prepended to the comprehension. For example, we could have requested the result in single precision by writing:Float32[ 0.25*x[i-1] + 0.5*x[i] + 0.25*x[i+1] for i=2:length(x)-1 ]" -}, - -{ - "location": "manual/arrays.html#Generator-Expressions-1", - "page": "Multi-dimensional Arrays", - "title": "Generator Expressions", - "category": "section", - "text": "Comprehensions can also be written without the enclosing square brackets, producing an object known as a generator. This object can be iterated to produce values on demand, instead of allocating an array and storing them in advance (see Iteration). For example, the following expression sums a series without allocating memory:julia> sum(1/n^2 for n=1:1000)\n1.6439345666815615When writing a generator expression with multiple dimensions inside an argument list, parentheses are needed to separate the generator from subsequent arguments:julia> map(tuple, 1/(i+j) for i=1:2, j=1:2, [1:4;])\nERROR: syntax: invalid iteration specificationAll comma-separated expressions after for are interpreted as ranges. Adding parentheses lets us add a third argument to map:julia> map(tuple, (1/(i+j) for i=1:2, j=1:2), [1 3; 2 4])\n2×2 Array{Tuple{Float64,Int64},2}:\n (0.5, 1) (0.333333, 3)\n (0.333333, 2) (0.25, 4)Ranges in generators and comprehensions can depend on previous ranges by writing multiple for keywords:julia> [(i,j) for i=1:3 for j=1:i]\n6-element Array{Tuple{Int64,Int64},1}:\n (1, 1)\n (2, 1)\n (2, 2)\n (3, 1)\n (3, 2)\n (3, 3)In such cases, the result is always 1-d.Generated values can be filtered using the if keyword:julia> [(i,j) for i=1:3 for j=1:i if i+j == 4]\n2-element Array{Tuple{Int64,Int64},1}:\n (2, 2)\n (3, 1)" -}, - -{ - "location": "manual/arrays.html#man-array-indexing-1", - "page": "Multi-dimensional Arrays", - "title": "Indexing", - "category": "section", - "text": "The general syntax for indexing into an n-dimensional array A is:X = A[I_1, I_2, ..., I_n]where each I_k may be a scalar integer, an array of integers, or any other supported index. This includes Colon (:) to select all indices within the entire dimension, ranges of the form a:c or a:b:c to select contiguous or strided subsections, and arrays of booleans to select elements at their true indices.If all the indices are scalars, then the result X is a single element from the array A. Otherwise, X is an array with the same number of dimensions as the sum of the dimensionalities of all the indices.If all indices are vectors, for example, then the shape of X would be (length(I_1), length(I_2), ..., length(I_n)), with location (i_1, i_2, ..., i_n) of X containing the value A[I_1[i_1], I_2[i_2], ..., I_n[i_n]]. If I_1 is changed to a two-dimensional matrix, then X becomes an n+1-dimensional array of shape (size(I_1, 1), size(I_1, 2), length(I_2), ..., length(I_n)). The matrix adds a dimension. The location (i_1, i_2, i_3, ..., i_{n+1}) contains the value at A[I_1[i_1, i_2], I_2[i_3], ..., I_n[i_{n+1}]]. All dimensions indexed with scalars are dropped. For example, the result of A[2, I, 3] is an array with size size(I). Its ith element is populated by A[2, I[i], 3].As a special part of this syntax, the end keyword may be used to represent the last index of each dimension within the indexing brackets, as determined by the size of the innermost array being indexed. Indexing syntax without the end keyword is equivalent to a call to getindex:X = getindex(A, I_1, I_2, ..., I_n)Example:julia> x = reshape(1:16, 4, 4)\n4×4 Base.ReshapedArray{Int64,2,UnitRange{Int64},Tuple{}}:\n 1 5 9 13\n 2 6 10 14\n 3 7 11 15\n 4 8 12 16\n\njulia> x[2:3, 2:end-1]\n2×2 Array{Int64,2}:\n 6 10\n 7 11\n\njulia> x[1, [2 3; 4 1]]\n2×2 Array{Int64,2}:\n 5 9\n 13 1Empty ranges of the form n:n-1 are sometimes used to indicate the inter-index location between n-1 and n. For example, the searchsorted() function uses this convention to indicate the insertion point of a value not found in a sorted array:julia> a = [1,2,5,6,7];\n\njulia> searchsorted(a, 3)\n3:2" -}, - -{ - "location": "manual/arrays.html#Assignment-1", - "page": "Multi-dimensional Arrays", - "title": "Assignment", - "category": "section", - "text": "The general syntax for assigning values in an n-dimensional array A is:A[I_1, I_2, ..., I_n] = Xwhere each I_k may be a scalar integer, an array of integers, or any other supported index. This includes Colon (:) to select all indices within the entire dimension, ranges of the form a:c or a:b:c to select contiguous or strided subsections, and arrays of booleans to select elements at their true indices.If X is an array, it must have the same number of elements as the product of the lengths of the indices: prod(length(I_1), length(I_2), ..., length(I_n)). The value in location I_1[i_1], I_2[i_2], ..., I_n[i_n] of A is overwritten with the value X[i_1, i_2, ..., i_n]. If X is not an array, its value is written to all referenced locations of A.Just as in Indexing, the end keyword may be used to represent the last index of each dimension within the indexing brackets, as determined by the size of the array being assigned into. Indexed assignment syntax without the end keyword is equivalent to a call to setindex!():setindex!(A, X, I_1, I_2, ..., I_n)Example:julia> x = collect(reshape(1:9, 3, 3))\n3×3 Array{Int64,2}:\n 1 4 7\n 2 5 8\n 3 6 9\n\njulia> x[1:2, 2:3] = -1\n-1\n\njulia> x\n3×3 Array{Int64,2}:\n 1 -1 -1\n 2 -1 -1\n 3 6 9" -}, - -{ - "location": "manual/arrays.html#man-supported-index-types-1", - "page": "Multi-dimensional Arrays", - "title": "Supported index types", - "category": "section", - "text": "In the expression A[I_1, I_2, ..., I_n], each I_k may be a scalar index, an array of scalar indices, or an object that represents an array of scalar indices and can be converted to such by to_indices:A scalar index. By default this includes:\nNon-boolean integers\nCartesianIndex{N}s, which behave like an N-tuple of integers spanning multiple dimensions (see below for more details)\nAn array of scalar indices. This includes:\nVectors and multidimensional arrays of integers\nEmpty arrays like [], which select no elements\nRanges of the form a:c or a:b:c, which select contiguous or strided subsections from a to c (inclusive)\nAny custom array of scalar indices that is a subtype of AbstractArray\nArrays of CartesianIndex{N} (see below for more details)\nAn object that represents an array of scalar indices and can be converted to such by to_indices. By default this includes:\nColon() (:), which represents all indices within an entire dimension or across the entire array\nArrays of booleans, which select elements at their true indices (see below for more details)" -}, - -{ - "location": "manual/arrays.html#Cartesian-indices-1", - "page": "Multi-dimensional Arrays", - "title": "Cartesian indices", - "category": "section", - "text": "The special CartesianIndex{N} object represents a scalar index that behaves like an N-tuple of integers spanning multiple dimensions. For example:julia> A = reshape(1:32, 4, 4, 2);\n\njulia> A[3, 2, 1]\n7\n\njulia> A[CartesianIndex(3, 2, 1)] == A[3, 2, 1] == 7\ntrueConsidered alone, this may seem relatively trivial; CartesianIndex simply gathers multiple integers together into one object that represents a single multidimensional index. When combined with other indexing forms and iterators that yield CartesianIndexes, however, this can lead directly to very elegant and efficient code. See Iteration below, and for some more advanced examples, see this blog post on multidimensional algorithms and iteration.Arrays of CartesianIndex{N} are also supported. They represent a collection of scalar indices that each span N dimensions, enabling a form of indexing that is sometimes referred to as pointwise indexing. For example, it enables accessing the diagonal elements from the first \"page\" of A from above:julia> page = A[:,:,1]\n4×4 Array{Int64,2}:\n 1 5 9 13\n 2 6 10 14\n 3 7 11 15\n 4 8 12 16\n\njulia> page[[CartesianIndex(1,1),\n CartesianIndex(2,2),\n CartesianIndex(3,3),\n CartesianIndex(4,4)]]\n4-element Array{Int64,1}:\n 1\n 6\n 11\n 16This can be expressed much more simply with dot broadcasting and by combining it with a normal integer index (instead of extracting the first page from A as a separate step). It can even be combined with a : to extract both diagonals from the two pages at the same time:julia> A[CartesianIndex.(indices(A, 1), indices(A, 2)), 1]\n4-element Array{Int64,1}:\n 1\n 6\n 11\n 16\n\njulia> A[CartesianIndex.(indices(A, 1), indices(A, 2)), :]\n4×2 Array{Int64,2}:\n 1 17\n 6 22\n 11 27\n 16 32warning: Warning\nCartesianIndex and arrays of CartesianIndex are not compatible with the end keyword to represent the last index of a dimension. Do not use end in indexing expressions that may contain either CartesianIndex or arrays thereof." -}, - -{ - "location": "manual/arrays.html#Logical-indexing-1", - "page": "Multi-dimensional Arrays", - "title": "Logical indexing", - "category": "section", - "text": "Often referred to as logical indexing or indexing with a logical mask, indexing by a boolean array selects elements at the indices where its values are true. Indexing by a boolean vector B is effectively the same as indexing by the vector of integers that is returned by find(B). Similarly, indexing by a N-dimensional boolean array is effectively the same as indexing by the vector of CartesianIndex{N}s where its values are true. A logical index must be a vector of the same length as the dimension it indexes into, or it must be the only index provided and match the size and dimensionality of the array it indexes into. It is generally more efficient to use boolean arrays as indices directly instead of first calling find().julia> x = reshape(1:16, 4, 4)\n4×4 Base.ReshapedArray{Int64,2,UnitRange{Int64},Tuple{}}:\n 1 5 9 13\n 2 6 10 14\n 3 7 11 15\n 4 8 12 16\n\njulia> x[[false, true, true, false], :]\n2×4 Array{Int64,2}:\n 2 6 10 14\n 3 7 11 15\n\njulia> mask = map(ispow2, x)\n4×4 Array{Bool,2}:\n true false false false\n true false false false\n false false false false\n true true false true\n\njulia> x[mask]\n5-element Array{Int64,1}:\n 1\n 2\n 4\n 8\n 16" -}, - -{ - "location": "manual/arrays.html#Iteration-1", - "page": "Multi-dimensional Arrays", - "title": "Iteration", - "category": "section", - "text": "The recommended ways to iterate over a whole array arefor a in A\n # Do something with the element a\nend\n\nfor i in eachindex(A)\n # Do something with i and/or A[i]\nendThe first construct is used when you need the value, but not index, of each element. In the second construct, i will be an Int if A is an array type with fast linear indexing; otherwise, it will be a CartesianIndex:julia> A = rand(4,3);\n\njulia> B = view(A, 1:3, 2:3);\n\njulia> for i in eachindex(B)\n @show i\n end\ni = CartesianIndex{2}((1, 1))\ni = CartesianIndex{2}((2, 1))\ni = CartesianIndex{2}((3, 1))\ni = CartesianIndex{2}((1, 2))\ni = CartesianIndex{2}((2, 2))\ni = CartesianIndex{2}((3, 2))In contrast with for i = 1:length(A), iterating with eachindex provides an efficient way to iterate over any array type." -}, - -{ - "location": "manual/arrays.html#Array-traits-1", - "page": "Multi-dimensional Arrays", - "title": "Array traits", - "category": "section", - "text": "If you write a custom AbstractArray type, you can specify that it has fast linear indexing usingBase.IndexStyle(::Type{<:MyArray}) = IndexLinear()This setting will cause eachindex iteration over a MyArray to use integers. If you don\'t specify this trait, the default value IndexCartesian() is used." -}, - -{ - "location": "manual/arrays.html#Array-and-Vectorized-Operators-and-Functions-1", - "page": "Multi-dimensional Arrays", - "title": "Array and Vectorized Operators and Functions", - "category": "section", - "text": "The following operators are supported for arrays:Unary arithmetic – -, +\nBinary arithmetic – -, +, *, /, \\, ^\nComparison – ==, !=, ≈ (isapprox), ≉Most of the binary arithmetic operators listed above also operate elementwise when one argument is scalar: -, +, and * when either argument is scalar, and / and \\ when the denominator is scalar. For example, [1, 2] + 3 == [4, 5] and [6, 4] / 2 == [3, 2].Additionally, to enable convenient vectorization of mathematical and other operations, Julia provides the dot syntax f.(args...), e.g. sin.(x) or min.(x,y), for elementwise operations over arrays or mixtures of arrays and scalars (a Broadcasting operation); these have the additional advantage of \"fusing\" into a single loop when combined with other dot calls, e.g. sin.(cos.(x)).Also, every binary operator supports a dot version that can be applied to arrays (and combinations of arrays and scalars) in such fused broadcasting operations, e.g. z .== sin.(x .* y).Note that comparisons such as == operate on whole arrays, giving a single boolean answer. Use dot operators like .== for elementwise comparisons. (For comparison operations like <, only the elementwise .< version is applicable to arrays.)Also notice the difference between max.(a,b), which broadcasts max() elementwise over a and b, and maximum(a), which finds the largest value within a. The same relationship holds for min.(a,b) and minimum(a)." -}, - -{ - "location": "manual/arrays.html#Broadcasting-1", - "page": "Multi-dimensional Arrays", - "title": "Broadcasting", - "category": "section", - "text": "It is sometimes useful to perform element-by-element binary operations on arrays of different sizes, such as adding a vector to each column of a matrix. An inefficient way to do this would be to replicate the vector to the size of the matrix:julia> a = rand(2,1); A = rand(2,3);\n\njulia> repmat(a,1,3)+A\n2×3 Array{Float64,2}:\n 1.20813 1.82068 1.25387\n 1.56851 1.86401 1.67846This is wasteful when dimensions get large, so Julia offers broadcast(), which expands singleton dimensions in array arguments to match the corresponding dimension in the other array without using extra memory, and applies the given function elementwise:julia> broadcast(+, a, A)\n2×3 Array{Float64,2}:\n 1.20813 1.82068 1.25387\n 1.56851 1.86401 1.67846\n\njulia> b = rand(1,2)\n1×2 Array{Float64,2}:\n 0.867535 0.00457906\n\njulia> broadcast(+, a, b)\n2×2 Array{Float64,2}:\n 1.71056 0.847604\n 1.73659 0.873631Dotted operators such as .+ and .* are equivalent to broadcast calls (except that they fuse, as described below). There is also a broadcast!() function to specify an explicit destination (which can also be accessed in a fusing fashion by .= assignment), and functions broadcast_getindex() and broadcast_setindex!() that broadcast the indices before indexing. Moreover, f.(args...) is equivalent to broadcast(f, args...), providing a convenient syntax to broadcast any function (dot syntax). Nested \"dot calls\" f.(...) (including calls to .+ etcetera) automatically fuse into a single broadcast call.Additionally, broadcast() is not limited to arrays (see the function documentation), it also handles tuples and treats any argument that is not an array, tuple or Ref (except for Ptr) as a \"scalar\".julia> convert.(Float32, [1, 2])\n2-element Array{Float32,1}:\n 1.0\n 2.0\n\njulia> ceil.((UInt8,), [1.2 3.4; 5.6 6.7])\n2×2 Array{UInt8,2}:\n 0x02 0x04\n 0x06 0x07\n\njulia> string.(1:3, \". \", [\"First\", \"Second\", \"Third\"])\n3-element Array{String,1}:\n \"1. First\"\n \"2. Second\"\n \"3. Third\"" -}, - -{ - "location": "manual/arrays.html#Implementation-1", - "page": "Multi-dimensional Arrays", - "title": "Implementation", - "category": "section", - "text": "The base array type in Julia is the abstract type AbstractArray{T,N}. It is parametrized by the number of dimensions N and the element type T. AbstractVector and AbstractMatrix are aliases for the 1-d and 2-d cases. Operations on AbstractArray objects are defined using higher level operators and functions, in a way that is independent of the underlying storage. These operations generally work correctly as a fallback for any specific array implementation.The AbstractArray type includes anything vaguely array-like, and implementations of it might be quite different from conventional arrays. For example, elements might be computed on request rather than stored. However, any concrete AbstractArray{T,N} type should generally implement at least size(A) (returning an Int tuple), getindex(A,i) and getindex(A,i1,...,iN); mutable arrays should also implement setindex!(). It is recommended that these operations have nearly constant time complexity, or technically Õ(1) complexity, as otherwise some array functions may be unexpectedly slow. Concrete types should also typically provide a similar(A,T=eltype(A),dims=size(A)) method, which is used to allocate a similar array for copy() and other out-of-place operations. No matter how an AbstractArray{T,N} is represented internally, T is the type of object returned by integer indexing (A[1, ..., 1], when A is not empty) and N should be the length of the tuple returned by size().DenseArray is an abstract subtype of AbstractArray intended to include all arrays that are laid out at regular offsets in memory, and which can therefore be passed to external C and Fortran functions expecting this memory layout. Subtypes should provide a method stride(A,k) that returns the \"stride\" of dimension k: increasing the index of dimension k by 1 should increase the index i of getindex(A,i) by stride(A,k). If a pointer conversion method Base.unsafe_convert(Ptr{T}, A) is provided, the memory layout should correspond in the same way to these strides.The Array type is a specific instance of DenseArray where elements are stored in column-major order (see additional notes in Performance Tips). Vector and Matrix are aliases for the 1-d and 2-d cases. Specific operations such as scalar indexing, assignment, and a few other basic storage-specific operations are all that have to be implemented for Array, so that the rest of the array library can be implemented in a generic manner.SubArray is a specialization of AbstractArray that performs indexing by reference rather than by copying. A SubArray is created with the view() function, which is called the same way as getindex() (with an array and a series of index arguments). The result of view() looks the same as the result of getindex(), except the data is left in place. view() stores the input index vectors in a SubArray object, which can later be used to index the original array indirectly. By putting the @views macro in front of an expression or block of code, any array[...] slice in that expression will be converted to create a SubArray view instead.StridedVector and StridedMatrix are convenient aliases defined to make it possible for Julia to call a wider range of BLAS and LAPACK functions by passing them either Array or SubArray objects, and thus saving inefficiencies from memory allocation and copying.The following example computes the QR decomposition of a small section of a larger array, without creating any temporaries, and by calling the appropriate LAPACK function with the right leading dimension size and stride parameters.julia> a = rand(10,10)\n10×10 Array{Float64,2}:\n 0.561255 0.226678 0.203391 0.308912 … 0.750307 0.235023 0.217964\n 0.718915 0.537192 0.556946 0.996234 0.666232 0.509423 0.660788\n 0.493501 0.0565622 0.118392 0.493498 0.262048 0.940693 0.252965\n 0.0470779 0.736979 0.264822 0.228787 0.161441 0.897023 0.567641\n 0.343935 0.32327 0.795673 0.452242 0.468819 0.628507 0.511528\n 0.935597 0.991511 0.571297 0.74485 … 0.84589 0.178834 0.284413\n 0.160706 0.672252 0.133158 0.65554 0.371826 0.770628 0.0531208\n 0.306617 0.836126 0.301198 0.0224702 0.39344 0.0370205 0.536062\n 0.890947 0.168877 0.32002 0.486136 0.096078 0.172048 0.77672\n 0.507762 0.573567 0.220124 0.165816 0.211049 0.433277 0.539476\n\njulia> b = view(a, 2:2:8,2:2:4)\n4×2 SubArray{Float64,2,Array{Float64,2},Tuple{StepRange{Int64,Int64},StepRange{Int64,Int64}},false}:\n 0.537192 0.996234\n 0.736979 0.228787\n 0.991511 0.74485\n 0.836126 0.0224702\n\njulia> (q,r) = qr(b);\n\njulia> q\n4×2 Array{Float64,2}:\n -0.338809 0.78934\n -0.464815 -0.230274\n -0.625349 0.194538\n -0.527347 -0.534856\n\njulia> r\n2×2 Array{Float64,2}:\n -1.58553 -0.921517\n 0.0 0.866567" -}, - -{ - "location": "manual/arrays.html#Sparse-Vectors-and-Matrices-1", - "page": "Multi-dimensional Arrays", - "title": "Sparse Vectors and Matrices", - "category": "section", - "text": "Julia has built-in support for sparse vectors and sparse matrices. Sparse arrays are arrays that contain enough zeros that storing them in a special data structure leads to savings in space and execution time, compared to dense arrays." -}, - -{ - "location": "manual/arrays.html#man-csc-1", - "page": "Multi-dimensional Arrays", - "title": "Compressed Sparse Column (CSC) Sparse Matrix Storage", - "category": "section", - "text": "In Julia, sparse matrices are stored in the Compressed Sparse Column (CSC) format. Julia sparse matrices have the type SparseMatrixCSC{Tv,Ti}, where Tv is the type of the stored values, and Ti is the integer type for storing column pointers and row indices. The internal representation of SparseMatrixCSC is as follows:struct SparseMatrixCSC{Tv,Ti<:Integer} <: AbstractSparseMatrix{Tv,Ti}\n m::Int # Number of rows\n n::Int # Number of columns\n colptr::Vector{Ti} # Column i is in colptr[i]:(colptr[i+1]-1)\n rowval::Vector{Ti} # Row indices of stored values\n nzval::Vector{Tv} # Stored values, typically nonzeros\nendThe compressed sparse column storage makes it easy and quick to access the elements in the column of a sparse matrix, whereas accessing the sparse matrix by rows is considerably slower. Operations such as insertion of previously unstored entries one at a time in the CSC structure tend to be slow. This is because all elements of the sparse matrix that are beyond the point of insertion have to be moved one place over.All operations on sparse matrices are carefully implemented to exploit the CSC data structure for performance, and to avoid expensive operations.If you have data in CSC format from a different application or library, and wish to import it in Julia, make sure that you use 1-based indexing. The row indices in every column need to be sorted. If your SparseMatrixCSC object contains unsorted row indices, one quick way to sort them is by doing a double transpose.In some applications, it is convenient to store explicit zero values in a SparseMatrixCSC. These are accepted by functions in Base (but there is no guarantee that they will be preserved in mutating operations). Such explicitly stored zeros are treated as structural nonzeros by many routines. The nnz() function returns the number of elements explicitly stored in the sparse data structure, including structural nonzeros. In order to count the exact number of numerical nonzeros, use countnz(), which inspects every stored element of a sparse matrix. dropzeros(), and the in-place dropzeros!(), can be used to remove stored zeros from the sparse matrix.julia> A = sparse([1, 2, 3], [1, 2, 3], [0, 2, 0])\n3×3 SparseMatrixCSC{Int64,Int64} with 3 stored entries:\n [1, 1] = 0\n [2, 2] = 2\n [3, 3] = 0\n\njulia> dropzeros(A)\n3×3 SparseMatrixCSC{Int64,Int64} with 1 stored entry:\n [2, 2] = 2" -}, - -{ - "location": "manual/arrays.html#Sparse-Vector-Storage-1", - "page": "Multi-dimensional Arrays", - "title": "Sparse Vector Storage", - "category": "section", - "text": "Sparse vectors are stored in a close analog to compressed sparse column format for sparse matrices. In Julia, sparse vectors have the type SparseVector{Tv,Ti} where Tv is the type of the stored values and Ti the integer type for the indices. The internal representation is as follows:struct SparseVector{Tv,Ti<:Integer} <: AbstractSparseVector{Tv,Ti}\n n::Int # Length of the sparse vector\n nzind::Vector{Ti} # Indices of stored values\n nzval::Vector{Tv} # Stored values, typically nonzeros\nendAs for SparseMatrixCSC, the SparseVector type can also contain explicitly stored zeros. (See Sparse Matrix Storage.)." -}, - -{ - "location": "manual/arrays.html#Sparse-Vector-and-Matrix-Constructors-1", - "page": "Multi-dimensional Arrays", - "title": "Sparse Vector and Matrix Constructors", - "category": "section", - "text": "The simplest way to create sparse arrays is to use functions equivalent to the zeros() and eye() functions that Julia provides for working with dense arrays. To produce sparse arrays instead, you can use the same names with an sp prefix:julia> spzeros(3)\n3-element SparseVector{Float64,Int64} with 0 stored entries\n\njulia> speye(3,5)\n3×5 SparseMatrixCSC{Float64,Int64} with 3 stored entries:\n [1, 1] = 1.0\n [2, 2] = 1.0\n [3, 3] = 1.0The sparse() function is often a handy way to construct sparse arrays. For example, to construct a sparse matrix we can input a vector I of row indices, a vector J of column indices, and a vector V of stored values (this is also known as the COO (coordinate) format). sparse(I,J,V) then constructs a sparse matrix such that S[I[k], J[k]] = V[k]. The equivalent sparse vector constructor is sparsevec, which takes the (row) index vector I and the vector V with the stored values and constructs a sparse vector R such that R[I[k]] = V[k].julia> I = [1, 4, 3, 5]; J = [4, 7, 18, 9]; V = [1, 2, -5, 3];\n\njulia> S = sparse(I,J,V)\n5×18 SparseMatrixCSC{Int64,Int64} with 4 stored entries:\n [1 , 4] = 1\n [4 , 7] = 2\n [5 , 9] = 3\n [3 , 18] = -5\n\njulia> R = sparsevec(I,V)\n5-element SparseVector{Int64,Int64} with 4 stored entries:\n [1] = 1\n [3] = -5\n [4] = 2\n [5] = 3The inverse of the sparse() and sparsevec functions is findnz(), which retrieves the inputs used to create the sparse array. There is also a findn function which only returns the index vectors.julia> findnz(S)\n([1, 4, 5, 3], [4, 7, 9, 18], [1, 2, 3, -5])\n\njulia> findn(S)\n([1, 4, 5, 3], [4, 7, 9, 18])\n\njulia> findnz(R)\n([1, 3, 4, 5], [1, -5, 2, 3])\n\njulia> findn(R)\n4-element Array{Int64,1}:\n 1\n 3\n 4\n 5Another way to create a sparse array is to convert a dense array into a sparse array using the sparse() function:julia> sparse(eye(5))\n5×5 SparseMatrixCSC{Float64,Int64} with 5 stored entries:\n [1, 1] = 1.0\n [2, 2] = 1.0\n [3, 3] = 1.0\n [4, 4] = 1.0\n [5, 5] = 1.0\n\njulia> sparse([1.0, 0.0, 1.0])\n3-element SparseVector{Float64,Int64} with 2 stored entries:\n [1] = 1.0\n [3] = 1.0You can go in the other direction using the Array constructor. The issparse() function can be used to query if a matrix is sparse.julia> issparse(speye(5))\ntrue" -}, - -{ - "location": "manual/arrays.html#Sparse-matrix-operations-1", - "page": "Multi-dimensional Arrays", - "title": "Sparse matrix operations", - "category": "section", - "text": "Arithmetic operations on sparse matrices also work as they do on dense matrices. Indexing of, assignment into, and concatenation of sparse matrices work in the same way as dense matrices. Indexing operations, especially assignment, are expensive, when carried out one element at a time. In many cases it may be better to convert the sparse matrix into (I,J,V) format using findnz(), manipulate the values or the structure in the dense vectors (I,J,V), and then reconstruct the sparse matrix." -}, - -{ - "location": "manual/arrays.html#Correspondence-of-dense-and-sparse-methods-1", - "page": "Multi-dimensional Arrays", - "title": "Correspondence of dense and sparse methods", - "category": "section", - "text": "The following table gives a correspondence between built-in methods on sparse matrices and their corresponding methods on dense matrix types. In general, methods that generate sparse matrices differ from their dense counterparts in that the resulting matrix follows the same sparsity pattern as a given sparse matrix S, or that the resulting sparse matrix has density d, i.e. each matrix element has a probability d of being non-zero.Details can be found in the Sparse Vectors and Matrices section of the standard library reference.Sparse Dense Description\nspzeros(m,n) zeros(m,n) Creates a m-by-n matrix of zeros. (spzeros(m,n) is empty.)\nspones(S) ones(m,n) Creates a matrix filled with ones. Unlike the dense version, spones() has the same sparsity pattern as S.\nspeye(n) eye(n) Creates a n-by-n identity matrix.\nfull(S) sparse(A) Interconverts between dense and sparse formats.\nsprand(m,n,d) rand(m,n) Creates a m-by-n random matrix (of density d) with iid non-zero elements distributed uniformly on the half-open interval 0 1).\nsprandn(m,n,d) randn(m,n) Creates a m-by-n random matrix (of density d) with iid non-zero elements distributed according to the standard normal (Gaussian) distribution.\nsprandn(m,n,d,X) randn(m,n,X) Creates a m-by-n random matrix (of density d) with iid non-zero elements distributed according to the X distribution. (Requires the Distributions package.)" -}, - -{ - "location": "manual/linear-algebra.html#", - "page": "Linear algebra", - "title": "Linear algebra", - "category": "page", - "text": "" -}, - -{ - "location": "manual/linear-algebra.html#Linear-algebra-1", - "page": "Linear algebra", - "title": "Linear algebra", - "category": "section", - "text": "In addition to (and as part of) its support for multi-dimensional arrays, Julia provides native implementations of many common and useful linear algebra operations. Basic operations, such as trace, det, and inv are all supported:julia> A = [1 2 3; 4 1 6; 7 8 1]\n3×3 Array{Int64,2}:\n 1 2 3\n 4 1 6\n 7 8 1\n\njulia> trace(A)\n3\n\njulia> det(A)\n104.0\n\njulia> inv(A)\n3×3 Array{Float64,2}:\n -0.451923 0.211538 0.0865385\n 0.365385 -0.192308 0.0576923\n 0.240385 0.0576923 -0.0673077As well as other useful operations, such as finding eigenvalues or eigenvectors:julia> A = [1.5 2 -4; 3 -1 -6; -10 2.3 4]\n3×3 Array{Float64,2}:\n 1.5 2.0 -4.0\n 3.0 -1.0 -6.0\n -10.0 2.3 4.0\n\njulia> eigvals(A)\n3-element Array{Complex{Float64},1}:\n 9.31908+0.0im\n -2.40954+2.72095im\n -2.40954-2.72095im\n\njulia> eigvecs(A)\n3×3 Array{Complex{Float64},2}:\n -0.488645+0.0im 0.182546-0.39813im 0.182546+0.39813im\n -0.540358+0.0im 0.692926+0.0im 0.692926-0.0im\n 0.68501+0.0im 0.254058-0.513301im 0.254058+0.513301imIn addition, Julia provides many factorizations which can be used to speed up problems such as linear solve or matrix exponentiation by pre-factorizing a matrix into a form more amenable (for performance or memory reasons) to the problem. See the documentation on factorize for more information. As an example:julia> A = [1.5 2 -4; 3 -1 -6; -10 2.3 4]\n3×3 Array{Float64,2}:\n 1.5 2.0 -4.0\n 3.0 -1.0 -6.0\n -10.0 2.3 4.0\n\njulia> factorize(A)\nBase.LinAlg.LU{Float64,Array{Float64,2}} with factors L and U:\n[1.0 0.0 0.0; -0.15 1.0 0.0; -0.3 -0.132196 1.0]\n[-10.0 2.3 4.0; 0.0 2.345 -3.4; 0.0 0.0 -5.24947]Since A is not Hermitian, symmetric, triangular, tridiagonal, or bidiagonal, an LU factorization may be the best we can do. Compare with:julia> B = [1.5 2 -4; 2 -1 -3; -4 -3 5]\n3×3 Array{Float64,2}:\n 1.5 2.0 -4.0\n 2.0 -1.0 -3.0\n -4.0 -3.0 5.0\n\njulia> factorize(B)\nBase.LinAlg.BunchKaufman{Float64,Array{Float64,2}}([-1.64286 0.142857 -0.8; 2.0 -2.8 -0.6; -4.0 -3.0 5.0], [1, 2, 3], \'U\', true, false, 0)Here, Julia was able to detect that B is in fact symmetric, and used a more appropriate factorization. Often it\'s possible to write more efficient code for a matrix that is known to have certain properties e.g. it is symmetric, or tridiagonal. Julia provides some special types so that you can \"tag\" matrices as having these properties. For instance:julia> B = [1.5 2 -4; 2 -1 -3; -4 -3 5]\n3×3 Array{Float64,2}:\n 1.5 2.0 -4.0\n 2.0 -1.0 -3.0\n -4.0 -3.0 5.0\n\njulia> sB = Symmetric(B)\n3×3 Symmetric{Float64,Array{Float64,2}}:\n 1.5 2.0 -4.0\n 2.0 -1.0 -3.0\n -4.0 -3.0 5.0sB has been tagged as a matrix that\'s (real) symmetric, so for later operations we might perform on it, such as eigenfactorization or computing matrix-vector products, efficiencies can be found by only referencing half of it. For example:julia> B = [1.5 2 -4; 2 -1 -3; -4 -3 5]\n3×3 Array{Float64,2}:\n 1.5 2.0 -4.0\n 2.0 -1.0 -3.0\n -4.0 -3.0 5.0\n\njulia> sB = Symmetric(B)\n3×3 Symmetric{Float64,Array{Float64,2}}:\n 1.5 2.0 -4.0\n 2.0 -1.0 -3.0\n -4.0 -3.0 5.0\n\njulia> x = [1; 2; 3]\n3-element Array{Int64,1}:\n 1\n 2\n 3\n\njulia> sB\\x\n3-element Array{Float64,1}:\n -1.73913\n -1.1087\n -1.45652The \\ operation here performs the linear solution. Julia\'s parser provides convenient dispatch to specialized methods for the transpose of a matrix left-divided by a vector, or for the various combinations of transpose operations in matrix-matrix solutions. Many of these are further specialized for certain special matrix types. For example, A\\B will end up calling Base.LinAlg.A_ldiv_B! while A\'\\B will end up calling Base.LinAlg.Ac_ldiv_B, even though we used the same left-division operator. This works for matrices too: A.\'\\B.\' would call Base.LinAlg.At_ldiv_Bt. The left-division operator is pretty powerful and it\'s easy to write compact, readable code that is flexible enough to solve all sorts of systems of linear equations." -}, - -{ - "location": "manual/linear-algebra.html#Special-matrices-1", - "page": "Linear algebra", - "title": "Special matrices", - "category": "section", - "text": "Matrices with special symmetries and structures arise often in linear algebra and are frequently associated with various matrix factorizations. Julia features a rich collection of special matrix types, which allow for fast computation with specialized routines that are specially developed for particular matrix types.The following tables summarize the types of special matrices that have been implemented in Julia, as well as whether hooks to various optimized methods for them in LAPACK are available.Type Description\nHermitian Hermitian matrix\nUpperTriangular Upper triangular matrix\nLowerTriangular Lower triangular matrix\nTridiagonal Tridiagonal matrix\nSymTridiagonal Symmetric tridiagonal matrix\nBidiagonal Upper/lower bidiagonal matrix\nDiagonal Diagonal matrix\nUniformScaling Uniform scaling operator" -}, - -{ - "location": "manual/linear-algebra.html#Elementary-operations-1", - "page": "Linear algebra", - "title": "Elementary operations", - "category": "section", - "text": "Matrix type + - * \\ Other functions with optimized methods\nHermitian       MV inv(), sqrtm(), expm()\nUpperTriangular     MV MV inv(), det()\nLowerTriangular     MV MV inv(), det()\nSymTridiagonal M M MS MV eigmax(), eigmin()\nTridiagonal M M MS MV  \nBidiagonal M M MS MV  \nDiagonal M M MV MV inv(), det(), logdet(), /()\nUniformScaling M M MVS MVS /()Legend:Key Description\nM (matrix) An optimized method for matrix-matrix operations is available\nV (vector) An optimized method for matrix-vector operations is available\nS (scalar) An optimized method for matrix-scalar operations is available" -}, - -{ - "location": "manual/linear-algebra.html#Matrix-factorizations-1", - "page": "Linear algebra", - "title": "Matrix factorizations", - "category": "section", - "text": "Matrix type LAPACK eig() eigvals() eigvecs() svd() svdvals()\nHermitian HE   ARI      \nUpperTriangular TR A A A    \nLowerTriangular TR A A A    \nSymTridiagonal ST A ARI AV    \nTridiagonal GT          \nBidiagonal BD       A A\nDiagonal DI   A      Legend:Key Description Example\nA (all) An optimized method to find all the characteristic values and/or vectors is available e.g. eigvals(M)\nR (range) An optimized method to find the ilth through the ihth characteristic values are available eigvals(M, il, ih)\nI (interval) An optimized method to find the characteristic values in the interval [vl, vh] is available eigvals(M, vl, vh)\nV (vectors) An optimized method to find the characteristic vectors corresponding to the characteristic values x=[x1, x2,...] is available eigvecs(M, x)" -}, - -{ - "location": "manual/linear-algebra.html#The-uniform-scaling-operator-1", - "page": "Linear algebra", - "title": "The uniform scaling operator", - "category": "section", - "text": "A UniformScaling operator represents a scalar times the identity operator, λ*I. The identity operator I is defined as a constant and is an instance of UniformScaling. The size of these operators are generic and match the other matrix in the binary operations +, -, * and \\. For A+I and A-I this means that A must be square. Multiplication with the identity operator I is a noop (except for checking that the scaling factor is one) and therefore almost without overhead." -}, - -{ - "location": "manual/linear-algebra.html#man-linalg-factorizations-1", - "page": "Linear algebra", - "title": "Matrix factorizations", - "category": "section", - "text": "Matrix factorizations (a.k.a. matrix decompositions) compute the factorization of a matrix into a product of matrices, and are one of the central concepts in linear algebra.The following table summarizes the types of matrix factorizations that have been implemented in Julia. Details of their associated methods can be found in the Linear Algebra section of the standard library documentation.Type Description\nCholesky Cholesky factorization\nCholeskyPivoted Pivoted Cholesky factorization\nLU LU factorization\nLUTridiagonal LU factorization for Tridiagonal matrices\nUmfpackLU LU factorization for sparse matrices (computed by UMFPack)\nQR QR factorization\nQRCompactWY Compact WY form of the QR factorization\nQRPivoted Pivoted QR factorization\nHessenberg Hessenberg decomposition\nEigen Spectral decomposition\nSVD Singular value decomposition\nGeneralizedSVD Generalized SVD" -}, - -{ - "location": "manual/networking-and-streams.html#", - "page": "Networking and Streams", - "title": "Networking and Streams", - "category": "page", - "text": "" -}, - -{ - "location": "manual/networking-and-streams.html#Networking-and-Streams-1", - "page": "Networking and Streams", - "title": "Networking and Streams", - "category": "section", - "text": "Julia provides a rich interface to deal with streaming I/O objects such as terminals, pipes and TCP sockets. This interface, though asynchronous at the system level, is presented in a synchronous manner to the programmer and it is usually unnecessary to think about the underlying asynchronous operation. This is achieved by making heavy use of Julia cooperative threading (coroutine) functionality." -}, - -{ - "location": "manual/networking-and-streams.html#Basic-Stream-I/O-1", - "page": "Networking and Streams", - "title": "Basic Stream I/O", - "category": "section", - "text": "All Julia streams expose at least a read() and a write() method, taking the stream as their first argument, e.g.:julia> write(STDOUT,\"Hello World\"); # suppress return value 11 with ;\nHello World\njulia> read(STDIN,Char)\n\n\'\\n\': ASCII/Unicode U+000a (category Cc: Other, control)Note that write() returns 11, the number of bytes (in \"Hello World\") written to STDOUT, but this return value is suppressed with the ;.Here Enter was pressed again so that Julia would read the newline. Now, as you can see from this example, write() takes the data to write as its second argument, while read() takes the type of the data to be read as the second argument.For example, to read a simple byte array, we could do:julia> x = zeros(UInt8, 4)\n4-element Array{UInt8,1}:\n 0x00\n 0x00\n 0x00\n 0x00\n\njulia> read!(STDIN, x)\nabcd\n4-element Array{UInt8,1}:\n 0x61\n 0x62\n 0x63\n 0x64However, since this is slightly cumbersome, there are several convenience methods provided. For example, we could have written the above as:julia> read(STDIN,4)\nabcd\n4-element Array{UInt8,1}:\n 0x61\n 0x62\n 0x63\n 0x64or if we had wanted to read the entire line instead:julia> readline(STDIN)\nabcd\n\"abcd\"Note that depending on your terminal settings, your TTY may be line buffered and might thus require an additional enter before the data is sent to Julia.To read every line from STDIN you can use eachline():for line in eachline(STDIN)\n print(\"Found $line\")\nendor read() if you wanted to read by character instead:while !eof(STDIN)\n x = read(STDIN, Char)\n println(\"Found: $x\")\nend" -}, - -{ - "location": "manual/networking-and-streams.html#Text-I/O-1", - "page": "Networking and Streams", - "title": "Text I/O", - "category": "section", - "text": "Note that the write() method mentioned above operates on binary streams. In particular, values do not get converted to any canonical text representation but are written out as is:julia> write(STDOUT,0x61); # suppress return value 1 with ;\naNote that a is written to STDOUT by the write() function and that the returned value is 1 (since 0x61 is one byte).For text I/O, use the print() or show() methods, depending on your needs (see the standard library reference for a detailed discussion of the difference between the two):julia> print(STDOUT, 0x61)\n97" -}, - -{ - "location": "manual/networking-and-streams.html#IO-Output-Contextual-Properties-1", - "page": "Networking and Streams", - "title": "IO Output Contextual Properties", - "category": "section", - "text": "Sometimes IO output can benefit from the ability to pass contextual information into show methods. The IOContext object provides this framework for associating arbitrary metadata with an IO object. For example, showcompact adds a hinting parameter to the IO object that the invoked show method should print a shorter output (if applicable)." -}, - -{ - "location": "manual/networking-and-streams.html#Working-with-Files-1", - "page": "Networking and Streams", - "title": "Working with Files", - "category": "section", - "text": "Like many other environments, Julia has an open() function, which takes a filename and returns an IOStream object that you can use to read and write things from the file. For example if we have a file, hello.txt, whose contents are Hello, World!:julia> f = open(\"hello.txt\")\nIOStream()\n\njulia> readlines(f)\n1-element Array{String,1}:\n \"Hello, World!\"If you want to write to a file, you can open it with the write (\"w\") flag:julia> f = open(\"hello.txt\",\"w\")\nIOStream()\n\njulia> write(f,\"Hello again.\")\n12If you examine the contents of hello.txt at this point, you will notice that it is empty; nothing has actually been written to disk yet. This is because the IOStream must be closed before the write is actually flushed to disk:julia> close(f)Examining hello.txt again will show its contents have been changed.Opening a file, doing something to its contents, and closing it again is a very common pattern. To make this easier, there exists another invocation of open() which takes a function as its first argument and filename as its second, opens the file, calls the function with the file as an argument, and then closes it again. For example, given a function:function read_and_capitalize(f::IOStream)\n return uppercase(readstring(f))\nendYou can call:julia> open(read_and_capitalize, \"hello.txt\")\n\"HELLO AGAIN.\"to open hello.txt, call read_and_capitalize on it, close hello.txt and return the capitalized contents.To avoid even having to define a named function, you can use the do syntax, which creates an anonymous function on the fly:julia> open(\"hello.txt\") do f\n uppercase(readstring(f))\n end\n\"HELLO AGAIN.\"" -}, - -{ - "location": "manual/networking-and-streams.html#A-simple-TCP-example-1", - "page": "Networking and Streams", - "title": "A simple TCP example", - "category": "section", - "text": "Let\'s jump right in with a simple example involving TCP sockets. Let\'s first create a simple server:julia> @async begin\n server = listen(2000)\n while true\n sock = accept(server)\n println(\"Hello World\\n\")\n end\n end\nTask (runnable) @0x00007fd31dc11ae0To those familiar with the Unix socket API, the method names will feel familiar, though their usage is somewhat simpler than the raw Unix socket API. The first call to listen() will create a server waiting for incoming connections on the specified port (2000) in this case. The same function may also be used to create various other kinds of servers:julia> listen(2000) # Listens on localhost:2000 (IPv4)\nTCPServer(active)\n\njulia> listen(ip\"127.0.0.1\",2000) # Equivalent to the first\nTCPServer(active)\n\njulia> listen(ip\"::1\",2000) # Listens on localhost:2000 (IPv6)\nTCPServer(active)\n\njulia> listen(IPv4(0),2001) # Listens on port 2001 on all IPv4 interfaces\nTCPServer(active)\n\njulia> listen(IPv6(0),2001) # Listens on port 2001 on all IPv6 interfaces\nTCPServer(active)\n\njulia> listen(\"testsocket\") # Listens on a UNIX domain socket/named pipe\nPipeServer(active)Note that the return type of the last invocation is different. This is because this server does not listen on TCP, but rather on a named pipe (Windows) or UNIX domain socket. The difference is subtle and has to do with the accept() and connect() methods. The accept() method retrieves a connection to the client that is connecting on the server we just created, while the connect() function connects to a server using the specified method. The connect() function takes the same arguments as listen(), so, assuming the environment (i.e. host, cwd, etc.) is the same you should be able to pass the same arguments to connect() as you did to listen to establish the connection. So let\'s try that out (after having created the server above):julia> connect(2000)\nTCPSocket(open, 0 bytes waiting)\n\njulia> Hello WorldAs expected we saw \"Hello World\" printed. So, let\'s actually analyze what happened behind the scenes. When we called connect(), we connect to the server we had just created. Meanwhile, the accept function returns a server-side connection to the newly created socket and prints \"Hello World\" to indicate that the connection was successful.A great strength of Julia is that since the API is exposed synchronously even though the I/O is actually happening asynchronously, we didn\'t have to worry callbacks or even making sure that the server gets to run. When we called connect() the current task waited for the connection to be established and only continued executing after that was done. In this pause, the server task resumed execution (because a connection request was now available), accepted the connection, printed the message and waited for the next client. Reading and writing works in the same way. To see this, consider the following simple echo server:julia> @async begin\n server = listen(2001)\n while true\n sock = accept(server)\n @async while isopen(sock)\n write(sock,readline(sock))\n end\n end\n end\nTask (runnable) @0x00007fd31dc12e60\n\njulia> clientside = connect(2001)\nTCPSocket(RawFD(28) open, 0 bytes waiting)\n\njulia> @async while true\n write(STDOUT,readline(clientside))\n end\nTask (runnable) @0x00007fd31dc11870\n\njulia> println(clientside,\"Hello World from the Echo Server\")\nHello World from the Echo ServerAs with other streams, use close() to disconnect the socket:julia> close(clientside)" -}, - -{ - "location": "manual/networking-and-streams.html#Resolving-IP-Addresses-1", - "page": "Networking and Streams", - "title": "Resolving IP Addresses", - "category": "section", - "text": "One of the connect() methods that does not follow the listen() methods is connect(host::String,port), which will attempt to connect to the host given by the host parameter on the port given by the port parameter. It allows you to do things like:julia> connect(\"google.com\",80)\nTCPSocket(RawFD(30) open, 0 bytes waiting)At the base of this functionality is getaddrinfo(), which will do the appropriate address resolution:julia> getaddrinfo(\"google.com\")\nip\"74.125.226.225\"" -}, - -{ - "location": "manual/parallel-computing.html#", - "page": "Parallel Computing", - "title": "Parallel Computing", - "category": "page", - "text": "" -}, - -{ - "location": "manual/parallel-computing.html#Parallel-Computing-1", - "page": "Parallel Computing", - "title": "Parallel Computing", - "category": "section", - "text": "Most modern computers possess more than one CPU, and several computers can be combined together in a cluster. Harnessing the power of these multiple CPUs allows many computations to be completed more quickly. There are two major factors that influence performance: the speed of the CPUs themselves, and the speed of their access to memory. In a cluster, it\'s fairly obvious that a given CPU will have fastest access to the RAM within the same computer (node). Perhaps more surprisingly, similar issues are relevant on a typical multicore laptop, due to differences in the speed of main memory and the cache. Consequently, a good multiprocessing environment should allow control over the \"ownership\" of a chunk of memory by a particular CPU. Julia provides a multiprocessing environment based on message passing to allow programs to run on multiple processes in separate memory domains at once.Julia\'s implementation of message passing is different from other environments such as MPI [1]. Communication in Julia is generally \"one-sided\", meaning that the programmer needs to explicitly manage only one process in a two-process operation. Furthermore, these operations typically do not look like \"message send\" and \"message receive\" but rather resemble higher-level operations like calls to user functions.Parallel programming in Julia is built on two primitives: remote references and remote calls. A remote reference is an object that can be used from any process to refer to an object stored on a particular process. A remote call is a request by one process to call a certain function on certain arguments on another (possibly the same) process.Remote references come in two flavors: Future and RemoteChannel.A remote call returns a Future to its result. Remote calls return immediately; the process that made the call proceeds to its next operation while the remote call happens somewhere else. You can wait for a remote call to finish by calling wait() on the returned Future, and you can obtain the full value of the result using fetch().On the other hand, RemoteChannel s are rewritable. For example, multiple processes can co-ordinate their processing by referencing the same remote Channel.Each process has an associated identifier. The process providing the interactive Julia prompt always has an id equal to 1. The processes used by default for parallel operations are referred to as \"workers\". When there is only one process, process 1 is considered a worker. Otherwise, workers are considered to be all processes other than process 1.Let\'s try this out. Starting with julia -p n provides n worker processes on the local machine. Generally it makes sense for n to equal the number of CPU cores on the machine.$ ./julia -p 2\n\njulia> r = remotecall(rand, 2, 2, 2)\nFuture(2, 1, 4, Nullable{Any}())\n\njulia> s = @spawnat 2 1 .+ fetch(r)\nFuture(2, 1, 5, Nullable{Any}())\n\njulia> fetch(s)\n2×2 Array{Float64,2}:\n 1.18526 1.50912\n 1.16296 1.60607The first argument to remotecall() is the function to call. Most parallel programming in Julia does not reference specific processes or the number of processes available, but remotecall() is considered a low-level interface providing finer control. The second argument to remotecall() is the id of the process that will do the work, and the remaining arguments will be passed to the function being called.As you can see, in the first line we asked process 2 to construct a 2-by-2 random matrix, and in the second line we asked it to add 1 to it. The result of both calculations is available in the two futures, r and s. The @spawnat macro evaluates the expression in the second argument on the process specified by the first argument.Occasionally you might want a remotely-computed value immediately. This typically happens when you read from a remote object to obtain data needed by the next local operation. The function remotecall_fetch() exists for this purpose. It is equivalent to fetch(remotecall(...)) but is more efficient.julia> remotecall_fetch(getindex, 2, r, 1, 1)\n0.18526337335308085Remember that getindex(r,1,1) is equivalent to r[1,1], so this call fetches the first element of the future r.The syntax of remotecall() is not especially convenient. The macro @spawn makes things easier. It operates on an expression rather than a function, and picks where to do the operation for you:julia> r = @spawn rand(2,2)\nFuture(2, 1, 4, Nullable{Any}())\n\njulia> s = @spawn 1 .+ fetch(r)\nFuture(3, 1, 5, Nullable{Any}())\n\njulia> fetch(s)\n2×2 Array{Float64,2}:\n 1.38854 1.9098\n 1.20939 1.57158Note that we used 1 .+ fetch(r) instead of 1 .+ r. This is because we do not know where the code will run, so in general a fetch() might be required to move r to the process doing the addition. In this case, @spawn is smart enough to perform the computation on the process that owns r, so the fetch() will be a no-op (no work is done).(It is worth noting that @spawn is not built-in but defined in Julia as a macro. It is possible to define your own such constructs.)An important thing to remember is that, once fetched, a Future will cache its value locally. Further fetch() calls do not entail a network hop. Once all referencing Futures have fetched, the remote stored value is deleted." -}, - -{ - "location": "manual/parallel-computing.html#Code-Availability-and-Loading-Packages-1", - "page": "Parallel Computing", - "title": "Code Availability and Loading Packages", - "category": "section", - "text": "Your code must be available on any process that runs it. For example, type the following into the Julia prompt:julia> function rand2(dims...)\n return 2*rand(dims...)\n end\n\njulia> rand2(2,2)\n2×2 Array{Float64,2}:\n 0.153756 0.368514\n 1.15119 0.918912\n\njulia> fetch(@spawn rand2(2,2))\nERROR: RemoteException(2, CapturedException(UndefVarError(Symbol(\"#rand2\"))\n[...]Process 1 knew about the function rand2, but process 2 did not.Most commonly you\'ll be loading code from files or packages, and you have a considerable amount of flexibility in controlling which processes load code. Consider a file, DummyModule.jl, containing the following code:module DummyModule\n\nexport MyType, f\n\nmutable struct MyType\n a::Int\nend\n\nf(x) = x^2+1\n\nprintln(\"loaded\")\n\nendStarting Julia with julia -p 2, you can use this to verify the following:include(\"DummyModule.jl\") loads the file on just a single process (whichever one executes the statement).\nusing DummyModule causes the module to be loaded on all processes; however, the module is brought into scope only on the one executing the statement.\nAs long as DummyModule is loaded on process 2, commands like\nrr = RemoteChannel(2)\nput!(rr, MyType(7))\nallow you to store an object of type MyType on process 2 even if DummyModule is not in scope on process 2.You can force a command to run on all processes using the @everywhere macro. For example, @everywhere can also be used to directly define a function on all processes:julia> @everywhere id = myid()\n\njulia> remotecall_fetch(()->id, 2)\n2A file can also be preloaded on multiple processes at startup, and a driver script can be used to drive the computation:julia -p -L file1.jl -L file2.jl driver.jlThe Julia process running the driver script in the example above has an id equal to 1, just like a process providing an interactive prompt.The base Julia installation has in-built support for two types of clusters:A local cluster specified with the -p option as shown above.\nA cluster spanning machines using the --machinefile option. This uses a passwordless ssh login to start Julia worker processes (from the same path as the current host) on the specified machines.Functions addprocs(), rmprocs(), workers(), and others are available as a programmatic means of adding, removing and querying the processes in a cluster.Note that workers do not run a .juliarc.jl startup script, nor do they synchronize their global state (such as global variables, new method definitions, and loaded modules) with any of the other running processes.Other types of clusters can be supported by writing your own custom ClusterManager, as described below in the ClusterManagers section." -}, - -{ - "location": "manual/parallel-computing.html#Data-Movement-1", - "page": "Parallel Computing", - "title": "Data Movement", - "category": "section", - "text": "Sending messages and moving data constitute most of the overhead in a parallel program. Reducing the number of messages and the amount of data sent is critical to achieving performance and scalability. To this end, it is important to understand the data movement performed by Julia\'s various parallel programming constructs.fetch() can be considered an explicit data movement operation, since it directly asks that an object be moved to the local machine. @spawn (and a few related constructs) also moves data, but this is not as obvious, hence it can be called an implicit data movement operation. Consider these two approaches to constructing and squaring a random matrix:Method 1:julia> A = rand(1000,1000);\n\njulia> Bref = @spawn A^2;\n\n[...]\n\njulia> fetch(Bref);Method 2:julia> Bref = @spawn rand(1000,1000)^2;\n\n[...]\n\njulia> fetch(Bref);The difference seems trivial, but in fact is quite significant due to the behavior of @spawn. In the first method, a random matrix is constructed locally, then sent to another process where it is squared. In the second method, a random matrix is both constructed and squared on another process. Therefore the second method sends much less data than the first.In this toy example, the two methods are easy to distinguish and choose from. However, in a real program designing data movement might require more thought and likely some measurement. For example, if the first process needs matrix A then the first method might be better. Or, if computing A is expensive and only the current process has it, then moving it to another process might be unavoidable. Or, if the current process has very little to do between the @spawn and fetch(Bref), it might be better to eliminate the parallelism altogether. Or imagine rand(1000,1000) is replaced with a more expensive operation. Then it might make sense to add another @spawn statement just for this step." -}, - -{ - "location": "manual/parallel-computing.html#Global-variables-1", - "page": "Parallel Computing", - "title": "Global variables", - "category": "section", - "text": "Expressions executed remotely via @spawn, or closures specified for remote execution using remotecall may refer to global variables. Global bindings under module Main are treated a little differently compared to global bindings in other modules. Consider the following code snippet:A = rand(10,10)\nremotecall_fetch(()->foo(A), 2)Note that A is a global variable defined in the local workspace. Worker 2 does not have a variable called A under Main. The act of shipping the closure ()->foo(A) to worker 2 results in Main.A being defined on 2. Main.A continues to exist on worker 2 even after the call remotecall_fetch returns. Remote calls with embedded global references (under Main module only) manage globals as follows:New global bindings are created on destination workers if they are referenced as part of a remote call.\nGlobal constants are declared as constants on remote nodes too.\nGlobals are re-sent to a destination worker only in the context of a remote call, and then only if its value has changed. Also, the cluster does not synchronize global bindings across nodes. For example:\nA = rand(10,10)\nremotecall_fetch(()->foo(A), 2) # worker 2\nA = rand(10,10)\nremotecall_fetch(()->foo(A), 3) # worker 3\nA = nothing\nExecuting the above snippet results in Main.A on worker 2 having a different value from Main.A on worker 3, while the value of Main.A on node 1 is set to nothing.As you may have realized, while memory associated with globals may be collected when they are reassigned on the master, no such action is taken on the workers as the bindings continue to be valid. clear! can be used to manually reassign specific globals on remote nodes to nothing once they are no longer required. This will release any memory associated with them as part of a regular garbage collection cycle.Thus programs should be careful referencing globals in remote calls. In fact, it is preferable to avoid them altogether if possible. If you must reference globals, consider using let blocks to localize global variables.For example:julia> A = rand(10,10);\n\njulia> remotecall_fetch(()->A, 2);\n\njulia> B = rand(10,10);\n\njulia> let B = B\n remotecall_fetch(()->B, 2)\n end;\n\njulia> @spawnat 2 whos();\n\njulia> From worker 2: A 800 bytes 10×10 Array{Float64,2}\n From worker 2: Base Module\n From worker 2: Core Module\n From worker 2: Main ModuleAs can be seen, global variable A is defined on worker 2, but B is captured as a local variable and hence a binding for B does not exist on worker 2." -}, - -{ - "location": "manual/parallel-computing.html#Parallel-Map-and-Loops-1", - "page": "Parallel Computing", - "title": "Parallel Map and Loops", - "category": "section", - "text": "Fortunately, many useful parallel computations do not require data movement. A common example is a Monte Carlo simulation, where multiple processes can handle independent simulation trials simultaneously. We can use @spawn to flip coins on two processes. First, write the following function in count_heads.jl:function count_heads(n)\n c::Int = 0\n for i = 1:n\n c += rand(Bool)\n end\n c\nendThe function count_heads simply adds together n random bits. Here is how we can perform some trials on two machines, and add together the results:julia> @everywhere include(\"count_heads.jl\")\n\njulia> a = @spawn count_heads(100000000)\nFuture(2, 1, 6, Nullable{Any}())\n\njulia> b = @spawn count_heads(100000000)\nFuture(3, 1, 7, Nullable{Any}())\n\njulia> fetch(a)+fetch(b)\n100001564This example demonstrates a powerful and often-used parallel programming pattern. Many iterations run independently over several processes, and then their results are combined using some function. The combination process is called a reduction, since it is generally tensor-rank-reducing: a vector of numbers is reduced to a single number, or a matrix is reduced to a single row or column, etc. In code, this typically looks like the pattern x = f(x,v[i]), where x is the accumulator, f is the reduction function, and the v[i] are the elements being reduced. It is desirable for f to be associative, so that it does not matter what order the operations are performed in.Notice that our use of this pattern with count_heads can be generalized. We used two explicit @spawn statements, which limits the parallelism to two processes. To run on any number of processes, we can use a parallel for loop, which can be written in Julia using @parallel like this:nheads = @parallel (+) for i = 1:200000000\n Int(rand(Bool))\nendThis construct implements the pattern of assigning iterations to multiple processes, and combining them with a specified reduction (in this case (+)). The result of each iteration is taken as the value of the last expression inside the loop. The whole parallel loop expression itself evaluates to the final answer.Note that although parallel for loops look like serial for loops, their behavior is dramatically different. In particular, the iterations do not happen in a specified order, and writes to variables or arrays will not be globally visible since iterations run on different processes. Any variables used inside the parallel loop will be copied and broadcast to each process.For example, the following code will not work as intended:a = zeros(100000)\n@parallel for i = 1:100000\n a[i] = i\nendThis code will not initialize all of a, since each process will have a separate copy of it. Parallel for loops like these must be avoided. Fortunately, Shared Arrays can be used to get around this limitation:a = SharedArray{Float64}(10)\n@parallel for i = 1:10\n a[i] = i\nendUsing \"outside\" variables in parallel loops is perfectly reasonable if the variables are read-only:a = randn(1000)\n@parallel (+) for i = 1:100000\n f(a[rand(1:end)])\nendHere each iteration applies f to a randomly-chosen sample from a vector a shared by all processes.As you could see, the reduction operator can be omitted if it is not needed. In that case, the loop executes asynchronously, i.e. it spawns independent tasks on all available workers and returns an array of Future immediately without waiting for completion. The caller can wait for the Future completions at a later point by calling fetch() on them, or wait for completion at the end of the loop by prefixing it with @sync, like @sync @parallel for.In some cases no reduction operator is needed, and we merely wish to apply a function to all integers in some range (or, more generally, to all elements in some collection). This is another useful operation called parallel map, implemented in Julia as the pmap() function. For example, we could compute the singular values of several large random matrices in parallel as follows:julia> M = Matrix{Float64}[rand(1000,1000) for i = 1:10];\n\njulia> pmap(svd, M);Julia\'s pmap() is designed for the case where each function call does a large amount of work. In contrast, @parallel for can handle situations where each iteration is tiny, perhaps merely summing two numbers. Only worker processes are used by both pmap() and @parallel for for the parallel computation. In case of @parallel for, the final reduction is done on the calling process." -}, - -{ - "location": "manual/parallel-computing.html#Synchronization-With-Remote-References-1", - "page": "Parallel Computing", - "title": "Synchronization With Remote References", - "category": "section", - "text": "" -}, - -{ - "location": "manual/parallel-computing.html#Scheduling-1", - "page": "Parallel Computing", - "title": "Scheduling", - "category": "section", - "text": "Julia\'s parallel programming platform uses Tasks (aka Coroutines) to switch among multiple computations. Whenever code performs a communication operation like fetch() or wait(), the current task is suspended and a scheduler picks another task to run. A task is restarted when the event it is waiting for completes.For many problems, it is not necessary to think about tasks directly. However, they can be used to wait for multiple events at the same time, which provides for dynamic scheduling. In dynamic scheduling, a program decides what to compute or where to compute it based on when other jobs finish. This is needed for unpredictable or unbalanced workloads, where we want to assign more work to processes only when they finish their current tasks.As an example, consider computing the singular values of matrices of different sizes:julia> M = Matrix{Float64}[rand(800,800), rand(600,600), rand(800,800), rand(600,600)];\n\njulia> pmap(svd, M);If one process handles both 800×800 matrices and another handles both 600×600 matrices, we will not get as much scalability as we could. The solution is to make a local task to \"feed\" work to each process when it completes its current task. For example, consider a simple pmap() implementation:function pmap(f, lst)\n np = nprocs() # determine the number of processes available\n n = length(lst)\n results = Vector{Any}(n)\n i = 1\n # function to produce the next work item from the queue.\n # in this case it\'s just an index.\n nextidx() = (idx=i; i+=1; idx)\n @sync begin\n for p=1:np\n if p != myid() || np == 1\n @async begin\n while true\n idx = nextidx()\n if idx > n\n break\n end\n results[idx] = remotecall_fetch(f, p, lst[idx])\n end\n end\n end\n end\n end\n results\nend@async is similar to @spawn, but only runs tasks on the local process. We use it to create a \"feeder\" task for each process. Each task picks the next index that needs to be computed, then waits for its process to finish, then repeats until we run out of indexes. Note that the feeder tasks do not begin to execute until the main task reaches the end of the @sync block, at which point it surrenders control and waits for all the local tasks to complete before returning from the function. The feeder tasks are able to share state via nextidx() because they all run on the same process. No locking is required, since the threads are scheduled cooperatively and not preemptively. This means context switches only occur at well-defined points: in this case, when remotecall_fetch() is called." -}, - -{ - "location": "manual/parallel-computing.html#Channels-1", - "page": "Parallel Computing", - "title": "Channels", - "category": "section", - "text": "The section on Tasks in Control Flow discussed the execution of multiple functions in a co-operative manner. Channels can be quite useful to pass data between running tasks, particularly those involving I/O operations.Examples of operations involving I/O include reading/writing to files, accessing web services, executing external programs, etc. In all these cases, overall execution time can be improved if other tasks can be run while a file is being read, or while waiting for an external service/program to complete.A channel can be visualized as a pipe, i.e., it has a write end and read end.Multiple writers in different tasks can write to the same channel concurrently via put!() calls.\nMultiple readers in different tasks can read data concurrently via take!() calls.\nAs an example:\n# Given Channels c1 and c2,\nc1 = Channel(32)\nc2 = Channel(32)\n\n# and a function `foo()` which reads items from from c1, processes the item read\n# and writes a result to c2,\nfunction foo()\n while true\n data = take!(c1)\n [...] # process data\n put!(c2, result) # write out result\n end\nend\n\n# we can schedule `n` instances of `foo()` to be active concurrently.\nfor _ in 1:n\n @schedule foo()\nend\nChannels are created via the Channel{T}(sz) constructor. The channel will only hold objects of type T. If the type is not specified, the channel can hold objects of any type. sz refers to the maximum number of elements that can be held in the channel at any time. For example, Channel(32) creates a channel that can hold a maximum of 32 objects of any type. A Channel{MyType}(64) can hold up to 64 objects of MyType at any time.\nIf a Channel is empty, readers (on a take!() call) will block until data is available.\nIf a Channel is full, writers (on a put!() call) will block until space becomes available.\nisready() tests for the presence of any object in the channel, while wait() waits for an object to become available.\nA Channel is in an open state initially. This means that it can be read from and written to freely via take!() and put!() calls. close() closes a Channel. On a closed Channel, put!() will fail. For example:julia> c = Channel(2);\n\njulia> put!(c, 1) # `put!` on an open channel succeeds\n1\n\njulia> close(c);\n\njulia> put!(c, 2) # `put!` on a closed channel throws an exception.\nERROR: InvalidStateException(\"Channel is closed.\",:closed)\n[...]take!() and fetch() (which retrieves but does not remove the value) on a closed channel successfully return any existing values until it is emptied. Continuing the above example:julia> fetch(c) # Any number of `fetch` calls succeed.\n1\n\njulia> fetch(c)\n1\n\njulia> take!(c) # The first `take!` removes the value.\n1\n\njulia> take!(c) # No more data available on a closed channel.\nERROR: InvalidStateException(\"Channel is closed.\",:closed)\n[...]A Channel can be used as an iterable object in a for loop, in which case the loop runs as long as the Channel has data or is open. The loop variable takes on all values added to the Channel. The for loop is terminated once the Channel is closed and emptied.For example, the following would cause the for loop to wait for more data:julia> c = Channel{Int}(10);\n\njulia> foreach(i->put!(c, i), 1:3) # add a few entries\n\njulia> data = [i for i in c]while this will return after reading all data:julia> c = Channel{Int}(10);\n\njulia> foreach(i->put!(c, i), 1:3); # add a few entries\n\njulia> close(c); # `for` loops can exit\n\njulia> data = [i for i in c]\n3-element Array{Int64,1}:\n 1\n 2\n 3Consider a simple example using channels for inter-task communication. We start 4 tasks to process data from a single jobs channel. Jobs, identified by an id (job_id), are written to the channel. Each task in this simulation reads a job_id, waits for a random amout of time and writes back a tuple of job_id and the simulated time to the results channel. Finally all the results are printed out.julia> const jobs = Channel{Int}(32);\n\njulia> const results = Channel{Tuple}(32);\n\njulia> function do_work()\n for job_id in jobs\n exec_time = rand()\n sleep(exec_time) # simulates elapsed time doing actual work\n # typically performed externally.\n put!(results, (job_id, exec_time))\n end\n end;\n\njulia> function make_jobs(n)\n for i in 1:n\n put!(jobs, i)\n end\n end;\n\njulia> n = 12;\n\njulia> @schedule make_jobs(n); # feed the jobs channel with \"n\" jobs\n\njulia> for i in 1:4 # start 4 tasks to process requests in parallel\n @schedule do_work()\n end\n\njulia> @elapsed while n > 0 # print out results\n job_id, exec_time = take!(results)\n println(\"$job_id finished in $(round(exec_time,2)) seconds\")\n n = n - 1\n end\n4 finished in 0.22 seconds\n3 finished in 0.45 seconds\n1 finished in 0.5 seconds\n7 finished in 0.14 seconds\n2 finished in 0.78 seconds\n5 finished in 0.9 seconds\n9 finished in 0.36 seconds\n6 finished in 0.87 seconds\n8 finished in 0.79 seconds\n10 finished in 0.64 seconds\n12 finished in 0.5 seconds\n11 finished in 0.97 seconds\n0.029772311The current version of Julia multiplexes all tasks onto a single OS thread. Thus, while tasks involving I/O operations benefit from parallel execution, compute bound tasks are effectively executed sequentially on a single OS thread. Future versions of Julia may support scheduling of tasks on multiple threads, in which case compute bound tasks will see benefits of parallel execution too." -}, - -{ - "location": "manual/parallel-computing.html#Remote-References-and-AbstractChannels-1", - "page": "Parallel Computing", - "title": "Remote References and AbstractChannels", - "category": "section", - "text": "Remote references always refer to an implementation of an AbstractChannel.A concrete implementation of an AbstractChannel (like Channel), is required to implement put!(), take!(), fetch(), isready() and wait(). The remote object referred to by a Future is stored in a Channel{Any}(1), i.e., a Channel of size 1 capable of holding objects of Any type.RemoteChannel, which is rewritable, can point to any type and size of channels, or any other implementation of an AbstractChannel.The constructor RemoteChannel(f::Function, pid)() allows us to construct references to channels holding more than one value of a specific type. f() is a function executed on pid and it must return an AbstractChannel.For example, RemoteChannel(()->Channel{Int}(10), pid), will return a reference to a channel of type Int and size 10. The channel exists on worker pid.Methods put!(), take!(), fetch(), isready() and wait() on a RemoteChannel are proxied onto the backing store on the remote process.RemoteChannel can thus be used to refer to user implemented AbstractChannel objects. A simple example of this is provided in examples/dictchannel.jl which uses a dictionary as its remote store." -}, - -{ - "location": "manual/parallel-computing.html#Channels-and-RemoteChannels-1", - "page": "Parallel Computing", - "title": "Channels and RemoteChannels", - "category": "section", - "text": "A Channel is local to a process. Worker 2 cannot directly refer to a Channel on worker 3 and vice-versa. A RemoteChannel, however, can put and take values across workers.\nA RemoteChannel can be thought of as a handle to a Channel.\nThe process id, pid, associated with a RemoteChannel identifies the process where the backing store, i.e., the backing Channel exists.\nAny process with a reference to a RemoteChannel can put and take items from the channel. Data is automatically sent to (or retrieved from) the process a RemoteChannel is associated with.\nSerializing a Channel also serializes any data present in the channel. Deserializing it therefore effectively makes a copy of the original object.\nOn the other hand, serializing a RemoteChannel only involves the serialization of an identifier that identifies the location and instance of Channel referred to by the handle. A deserialized RemoteChannel object (on any worker), therefore also points to the same backing store as the original.The channels example from above can be modified for interprocess communication, as shown below.We start 4 workers to process a single jobs remote channel. Jobs, identified by an id (job_id), are written to the channel. Each remotely executing task in this simulation reads a job_id, waits for a random amount of time and writes back a tuple of job_id, time taken and its own pid to the results channel. Finally all the results are printed out on the master process.julia> addprocs(4); # add worker processes\n\njulia> const jobs = RemoteChannel(()->Channel{Int}(32));\n\njulia> const results = RemoteChannel(()->Channel{Tuple}(32));\n\njulia> @everywhere function do_work(jobs, results) # define work function everywhere\n while true\n job_id = take!(jobs)\n exec_time = rand()\n sleep(exec_time) # simulates elapsed time doing actual work\n put!(results, (job_id, exec_time, myid()))\n end\n end\n\njulia> function make_jobs(n)\n for i in 1:n\n put!(jobs, i)\n end\n end;\n\njulia> n = 12;\n\njulia> @schedule make_jobs(n); # feed the jobs channel with \"n\" jobs\n\njulia> for p in workers() # start tasks on the workers to process requests in parallel\n @async remote_do(do_work, p, jobs, results)\n end\n\njulia> @elapsed while n > 0 # print out results\n job_id, exec_time, where = take!(results)\n println(\"$job_id finished in $(round(exec_time,2)) seconds on worker $where\")\n n = n - 1\n end\n1 finished in 0.18 seconds on worker 4\n2 finished in 0.26 seconds on worker 5\n6 finished in 0.12 seconds on worker 4\n7 finished in 0.18 seconds on worker 4\n5 finished in 0.35 seconds on worker 5\n4 finished in 0.68 seconds on worker 2\n3 finished in 0.73 seconds on worker 3\n11 finished in 0.01 seconds on worker 3\n12 finished in 0.02 seconds on worker 3\n9 finished in 0.26 seconds on worker 5\n8 finished in 0.57 seconds on worker 4\n10 finished in 0.58 seconds on worker 2\n0.055971741" -}, - -{ - "location": "manual/parallel-computing.html#Remote-References-and-Distributed-Garbage-Collection-1", - "page": "Parallel Computing", - "title": "Remote References and Distributed Garbage Collection", - "category": "section", - "text": "Objects referred to by remote references can be freed only when all held references in the cluster are deleted.The node where the value is stored keeps track of which of the workers have a reference to it. Every time a RemoteChannel or a (unfetched) Future is serialized to a worker, the node pointed to by the reference is notified. And every time a RemoteChannel or a (unfetched) Future is garbage collected locally, the node owning the value is again notified.The notifications are done via sending of \"tracking\" messages–an \"add reference\" message when a reference is serialized to a different process and a \"delete reference\" message when a reference is locally garbage collected.Since Futures are write-once and cached locally, the act of fetch()ing a Future also updates reference tracking information on the node owning the value.The node which owns the value frees it once all references to it are cleared.With Futures, serializing an already fetched Future to a different node also sends the value since the original remote store may have collected the value by this time.It is important to note that when an object is locally garbage collected depends on the size of the object and the current memory pressure in the system.In case of remote references, the size of the local reference object is quite small, while the value stored on the remote node may be quite large. Since the local object may not be collected immediately, it is a good practice to explicitly call finalize() on local instances of a RemoteChannel, or on unfetched Futures. Since calling fetch() on a Future also removes its reference from the remote store, this is not required on fetched Futures. Explicitly calling finalize() results in an immediate message sent to the remote node to go ahead and remove its reference to the value.Once finalized, a reference becomes invalid and cannot be used in any further calls." -}, - -{ - "location": "manual/parallel-computing.html#man-shared-arrays-1", - "page": "Parallel Computing", - "title": "Shared Arrays", - "category": "section", - "text": "Shared Arrays use system shared memory to map the same array across many processes. While there are some similarities to a DArray, the behavior of a SharedArray is quite different. In a DArray, each process has local access to just a chunk of the data, and no two processes share the same chunk; in contrast, in a SharedArray each \"participating\" process has access to the entire array. A SharedArray is a good choice when you want to have a large amount of data jointly accessible to two or more processes on the same machine.SharedArray indexing (assignment and accessing values) works just as with regular arrays, and is efficient because the underlying memory is available to the local process. Therefore, most algorithms work naturally on SharedArrays, albeit in single-process mode. In cases where an algorithm insists on an Array input, the underlying array can be retrieved from a SharedArray by calling sdata(). For other AbstractArray types, sdata() just returns the object itself, so it\'s safe to use sdata() on any Array-type object.The constructor for a shared array is of the form:SharedArray{T,N}(dims::NTuple; init=false, pids=Int[])which creates an N-dimensional shared array of a bits type T and size dims across the processes specified by pids. Unlike distributed arrays, a shared array is accessible only from those participating workers specified by the pids named argument (and the creating process too, if it is on the same host).If an init function, of signature initfn(S::SharedArray), is specified, it is called on all the participating workers. You can specify that each worker runs the init function on a distinct portion of the array, thereby parallelizing initialization.Here\'s a brief example:julia> addprocs(3)\n3-element Array{Int64,1}:\n 2\n 3\n 4\n\njulia> S = SharedArray{Int,2}((3,4), init = S -> S[Base.localindexes(S)] = myid())\n3×4 SharedArray{Int64,2}:\n 2 2 3 4\n 2 3 3 4\n 2 3 4 4\n\njulia> S[3,2] = 7\n7\n\njulia> S\n3×4 SharedArray{Int64,2}:\n 2 2 3 4\n 2 3 3 4\n 2 7 4 4Base.localindexes() provides disjoint one-dimensional ranges of indexes, and is sometimes convenient for splitting up tasks among processes. You can, of course, divide the work any way you wish:julia> S = SharedArray{Int,2}((3,4), init = S -> S[indexpids(S):length(procs(S)):length(S)] = myid())\n3×4 SharedArray{Int64,2}:\n 2 2 2 2\n 3 3 3 3\n 4 4 4 4Since all processes have access to the underlying data, you do have to be careful not to set up conflicts. For example:@sync begin\n for p in procs(S)\n @async begin\n remotecall_wait(fill!, p, S, p)\n end\n end\nendwould result in undefined behavior. Because each process fills the entire array with its own pid, whichever process is the last to execute (for any particular element of S) will have its pid retained.As a more extended and complex example, consider running the following \"kernel\" in parallel:q[i,j,t+1] = q[i,j,t] + u[i,j,t]In this case, if we try to split up the work using a one-dimensional index, we are likely to run into trouble: if q[i,j,t] is near the end of the block assigned to one worker and q[i,j,t+1] is near the beginning of the block assigned to another, it\'s very likely that q[i,j,t] will not be ready at the time it\'s needed for computing q[i,j,t+1]. In such cases, one is better off chunking the array manually. Let\'s split along the second dimension. Define a function that returns the (irange, jrange) indexes assigned to this worker:julia> @everywhere function myrange(q::SharedArray)\n idx = indexpids(q)\n if idx == 0 # This worker is not assigned a piece\n return 1:0, 1:0\n end\n nchunks = length(procs(q))\n splits = [round(Int, s) for s in linspace(0,size(q,2),nchunks+1)]\n 1:size(q,1), splits[idx]+1:splits[idx+1]\n endNext, define the kernel:julia> @everywhere function advection_chunk!(q, u, irange, jrange, trange)\n @show (irange, jrange, trange) # display so we can see what\'s happening\n for t in trange, j in jrange, i in irange\n q[i,j,t+1] = q[i,j,t] + u[i,j,t]\n end\n q\n endWe also define a convenience wrapper for a SharedArray implementationjulia> @everywhere advection_shared_chunk!(q, u) =\n advection_chunk!(q, u, myrange(q)..., 1:size(q,3)-1)Now let\'s compare three different versions, one that runs in a single process:julia> advection_serial!(q, u) = advection_chunk!(q, u, 1:size(q,1), 1:size(q,2), 1:size(q,3)-1);one that uses @parallel:julia> function advection_parallel!(q, u)\n for t = 1:size(q,3)-1\n @sync @parallel for j = 1:size(q,2)\n for i = 1:size(q,1)\n q[i,j,t+1]= q[i,j,t] + u[i,j,t]\n end\n end\n end\n q\n end;and one that delegates in chunks:julia> function advection_shared!(q, u)\n @sync begin\n for p in procs(q)\n @async remotecall_wait(advection_shared_chunk!, p, q, u)\n end\n end\n q\n end;If we create SharedArrays and time these functions, we get the following results (with julia -p 4):julia> q = SharedArray{Float64,3}((500,500,500));\n\njulia> u = SharedArray{Float64,3}((500,500,500));Run the functions once to JIT-compile and @time them on the second run:julia> @time advection_serial!(q, u);\n(irange,jrange,trange) = (1:500,1:500,1:499)\n 830.220 milliseconds (216 allocations: 13820 bytes)\n\njulia> @time advection_parallel!(q, u);\n 2.495 seconds (3999 k allocations: 289 MB, 2.09% gc time)\n\njulia> @time advection_shared!(q,u);\n From worker 2: (irange,jrange,trange) = (1:500,1:125,1:499)\n From worker 4: (irange,jrange,trange) = (1:500,251:375,1:499)\n From worker 3: (irange,jrange,trange) = (1:500,126:250,1:499)\n From worker 5: (irange,jrange,trange) = (1:500,376:500,1:499)\n 238.119 milliseconds (2264 allocations: 169 KB)The biggest advantage of advection_shared! is that it minimizes traffic among the workers, allowing each to compute for an extended time on the assigned piece." -}, - -{ - "location": "manual/parallel-computing.html#Shared-Arrays-and-Distributed-Garbage-Collection-1", - "page": "Parallel Computing", - "title": "Shared Arrays and Distributed Garbage Collection", - "category": "section", - "text": "Like remote references, shared arrays are also dependent on garbage collection on the creating node to release references from all participating workers. Code which creates many short lived shared array objects would benefit from explicitly finalizing these objects as soon as possible. This results in both memory and file handles mapping the shared segment being released sooner." -}, - -{ - "location": "manual/parallel-computing.html#ClusterManagers-1", - "page": "Parallel Computing", - "title": "ClusterManagers", - "category": "section", - "text": "The launching, management and networking of Julia processes into a logical cluster is done via cluster managers. A ClusterManager is responsible forlaunching worker processes in a cluster environment\nmanaging events during the lifetime of each worker\noptionally, providing data transportA Julia cluster has the following characteristics:The initial Julia process, also called the master, is special and has an id of 1.\nOnly the master process can add or remove worker processes.\nAll processes can directly communicate with each other.Connections between workers (using the in-built TCP/IP transport) is established in the following manner:addprocs() is called on the master process with a ClusterManager object.\naddprocs() calls the appropriate launch() method which spawns required number of worker processes on appropriate machines.\nEach worker starts listening on a free port and writes out its host and port information to STDOUT.\nThe cluster manager captures the STDOUT of each worker and makes it available to the master process.\nThe master process parses this information and sets up TCP/IP connections to each worker.\nEvery worker is also notified of other workers in the cluster.\nEach worker connects to all workers whose id is less than the worker\'s own id.\nIn this way a mesh network is established, wherein every worker is directly connected with every other worker.While the default transport layer uses plain TCPSocket, it is possible for a Julia cluster to provide its own transport.Julia provides two in-built cluster managers:LocalManager, used when addprocs() or addprocs(np::Integer) are called\nSSHManager, used when addprocs(hostnames::Array) is called with a list of hostnamesLocalManager is used to launch additional workers on the same host, thereby leveraging multi-core and multi-processor hardware.Thus, a minimal cluster manager would need to:be a subtype of the abstract ClusterManager\nimplement launch(), a method responsible for launching new workers\nimplement manage(), which is called at various events during a worker\'s lifetime (for example, sending an interrupt signal)addprocs(manager::FooManager) requires FooManager to implement:function launch(manager::FooManager, params::Dict, launched::Array, c::Condition)\n [...]\nend\n\nfunction manage(manager::FooManager, id::Integer, config::WorkerConfig, op::Symbol)\n [...]\nendAs an example let us see how the LocalManager, the manager responsible for starting workers on the same host, is implemented:struct LocalManager <: ClusterManager\n np::Integer\nend\n\nfunction launch(manager::LocalManager, params::Dict, launched::Array, c::Condition)\n [...]\nend\n\nfunction manage(manager::LocalManager, id::Integer, config::WorkerConfig, op::Symbol)\n [...]\nendThe launch() method takes the following arguments:manager::ClusterManager: the cluster manager that addprocs() is called with\nparams::Dict: all the keyword arguments passed to addprocs()\nlaunched::Array: the array to append one or more WorkerConfig objects to\nc::Condition: the condition variable to be notified as and when workers are launchedThe launch() method is called asynchronously in a separate task. The termination of this task signals that all requested workers have been launched. Hence the launch() function MUST exit as soon as all the requested workers have been launched.Newly launched workers are connected to each other, and the master process, in an all-to-all manner. Specifying the command argument --worker results in the launched processes initializing themselves as workers and connections being set up via TCP/IP sockets. Optionally, --bind-to bind_addr[:port] may also be specified to enable other workers to connect to it at the specified bind_addr and port. This is useful for multi-homed hosts.As an example of a non-TCP/IP transport, an implementation may choose to use MPI, in which case --worker must NOT be specified. Instead, newly launched workers should call init_worker(cookie) before using any of the parallel constructs.For every worker launched, the launch() method must add a WorkerConfig object (with appropriate fields initialized) to launchedmutable struct WorkerConfig\n # Common fields relevant to all cluster managers\n io::Nullable{IO}\n host::Nullable{AbstractString}\n port::Nullable{Integer}\n\n # Used when launching additional workers at a host\n count::Nullable{Union{Int, Symbol}}\n exename::Nullable{AbstractString}\n exeflags::Nullable{Cmd}\n\n # External cluster managers can use this to store information at a per-worker level\n # Can be a dict if multiple fields need to be stored.\n userdata::Nullable{Any}\n\n # SSHManager / SSH tunnel connections to workers\n tunnel::Nullable{Bool}\n bind_addr::Nullable{AbstractString}\n sshflags::Nullable{Cmd}\n max_parallel::Nullable{Integer}\n\n connect_at::Nullable{Any}\n\n [...]\nendMost of the fields in WorkerConfig are used by the inbuilt managers. Custom cluster managers would typically specify only io or host / port:If io is specified, it is used to read host/port information. A Julia worker prints out its bind address and port at startup. This allows Julia workers to listen on any free port available instead of requiring worker ports to be configured manually.\nIf io is not specified, host and port are used to connect.\ncount, exename and exeflags are relevant for launching additional workers from a worker. For example, a cluster manager may launch a single worker per node, and use that to launch additional workers.\ncount with an integer value n will launch a total of n workers.\ncount with a value of :auto will launch as many workers as the number of cores on that machine.\nexename is the name of the julia executable including the full path.\nexeflags should be set to the required command line arguments for new workers.\ntunnel, bind_addr, sshflags and max_parallel are used when a ssh tunnel is required to connect to the workers from the master process.\nuserdata is provided for custom cluster managers to store their own worker-specific information.manage(manager::FooManager, id::Integer, config::WorkerConfig, op::Symbol) is called at different times during the worker\'s lifetime with appropriate op values:with :register/:deregister when a worker is added / removed from the Julia worker pool.\nwith :interrupt when interrupt(workers) is called. The ClusterManager should signal the appropriate worker with an interrupt signal.\nwith :finalize for cleanup purposes." -}, - -{ - "location": "manual/parallel-computing.html#Cluster-Managers-with-Custom-Transports-1", - "page": "Parallel Computing", - "title": "Cluster Managers with Custom Transports", - "category": "section", - "text": "Replacing the default TCP/IP all-to-all socket connections with a custom transport layer is a little more involved. Each Julia process has as many communication tasks as the workers it is connected to. For example, consider a Julia cluster of 32 processes in an all-to-all mesh network:Each Julia process thus has 31 communication tasks.\nEach task handles all incoming messages from a single remote worker in a message-processing loop.\nThe message-processing loop waits on an IO object (for example, a TCPSocket in the default implementation), reads an entire message, processes it and waits for the next one.\nSending messages to a process is done directly from any Julia task–not just communication tasks–again, via the appropriate IO object.Replacing the default transport requires the new implementation to set up connections to remote workers and to provide appropriate IO objects that the message-processing loops can wait on. The manager-specific callbacks to be implemented are:connect(manager::FooManager, pid::Integer, config::WorkerConfig)\nkill(manager::FooManager, pid::Int, config::WorkerConfig)The default implementation (which uses TCP/IP sockets) is implemented as connect(manager::ClusterManager, pid::Integer, config::WorkerConfig).connect should return a pair of IO objects, one for reading data sent from worker pid, and the other to write data that needs to be sent to worker pid. Custom cluster managers can use an in-memory BufferStream as the plumbing to proxy data between the custom, possibly non-IO transport and Julia\'s in-built parallel infrastructure.A BufferStream is an in-memory IOBuffer which behaves like an IO–it is a stream which can be handled asynchronously.Folder examples/clustermanager/0mq contains an example of using ZeroMQ to connect Julia workers in a star topology with a 0MQ broker in the middle. Note: The Julia processes are still all logically connected to each other–any worker can message any other worker directly without any awareness of 0MQ being used as the transport layer.When using custom transports:Julia workers must NOT be started with --worker. Starting with --worker will result in the newly launched workers defaulting to the TCP/IP socket transport implementation.\nFor every incoming logical connection with a worker, Base.process_messages(rd::IO, wr::IO)() must be called. This launches a new task that handles reading and writing of messages from/to the worker represented by the IO objects.\ninit_worker(cookie, manager::FooManager) MUST be called as part of worker process initialization.\nField connect_at::Any in WorkerConfig can be set by the cluster manager when launch() is called. The value of this field is passed in in all connect() callbacks. Typically, it carries information on how to connect to a worker. For example, the TCP/IP socket transport uses this field to specify the (host, port) tuple at which to connect to a worker.kill(manager, pid, config) is called to remove a worker from the cluster. On the master process, the corresponding IO objects must be closed by the implementation to ensure proper cleanup. The default implementation simply executes an exit() call on the specified remote worker.examples/clustermanager/simple is an example that shows a simple implementation using UNIX domain sockets for cluster setup." -}, - -{ - "location": "manual/parallel-computing.html#Network-Requirements-for-LocalManager-and-SSHManager-1", - "page": "Parallel Computing", - "title": "Network Requirements for LocalManager and SSHManager", - "category": "section", - "text": "Julia clusters are designed to be executed on already secured environments on infrastructure such as local laptops, departmental clusters, or even the cloud. This section covers network security requirements for the inbuilt LocalManager and SSHManager:The master process does not listen on any port. It only connects out to the workers.\nEach worker binds to only one of the local interfaces and listens on the first free port starting from 9009.\nLocalManager, used by addprocs(N), by default binds only to the loopback interface. This means that workers started later on remote hosts (or by anyone with malicious intentions) are unable to connect to the cluster. An addprocs(4) followed by an addprocs([\"remote_host\"]) will fail. Some users may need to create a cluster comprising their local system and a few remote systems. This can be done by explicitly requesting LocalManager to bind to an external network interface via the restrict keyword argument: addprocs(4; restrict=false).\nSSHManager, used by addprocs(list_of_remote_hosts), launches workers on remote hosts via SSH. By default SSH is only used to launch Julia workers. Subsequent master-worker and worker-worker connections use plain, unencrypted TCP/IP sockets. The remote hosts must have passwordless login enabled. Additional SSH flags or credentials may be specified via keyword argument sshflags.\naddprocs(list_of_remote_hosts; tunnel=true, sshflags=) is useful when we wish to use SSH connections for master-worker too. A typical scenario for this is a local laptop running the Julia REPL (i.e., the master) with the rest of the cluster on the cloud, say on Amazon EC2. In this case only port 22 needs to be opened at the remote cluster coupled with SSH client authenticated via public key infrastructure (PKI). Authentication credentials can be supplied via sshflags, for example sshflags=`-e `.\nNote that worker-worker connections are still plain TCP and the local security policy on the remote cluster must allow for free connections between worker nodes, at least for ports 9009 and above.\nSecuring and encrypting all worker-worker traffic (via SSH) or encrypting individual messages can be done via a custom ClusterManager." -}, - -{ - "location": "manual/parallel-computing.html#Cluster-Cookie-1", - "page": "Parallel Computing", - "title": "Cluster Cookie", - "category": "section", - "text": "All processes in a cluster share the same cookie which, by default, is a randomly generated string on the master process:Base.cluster_cookie() returns the cookie, while Base.cluster_cookie(cookie)() sets it and returns the new cookie.\nAll connections are authenticated on both sides to ensure that only workers started by the master are allowed to connect to each other.\nThe cookie must be passed to the workers at startup via argument --worker . Custom ClusterManagers can retrieve the cookie on the master by calling Base.cluster_cookie(). Cluster managers not using the default TCP/IP transport (and hence not specifying --worker) must call init_worker(cookie, manager) with the same cookie as on the master.Note that environments requiring higher levels of security can implement this via a custom ClusterManager. For example, cookies can be pre-shared and hence not specified as a startup argument." -}, - -{ - "location": "manual/parallel-computing.html#Specifying-Network-Topology-(Experimental)-1", - "page": "Parallel Computing", - "title": "Specifying Network Topology (Experimental)", - "category": "section", - "text": "The keyword argument topology passed to addprocs is used to specify how the workers must be connected to each other::all_to_all, the default: all workers are connected to each other.\n:master_slave: only the driver process, i.e. pid 1, has connections to the workers.\n:custom: the launch method of the cluster manager specifies the connection topology via the fields ident and connect_idents in WorkerConfig. A worker with a cluster-manager-provided identity ident will connect to all workers specified in connect_idents.Currently, sending a message between unconnected workers results in an error. This behaviour, as with the functionality and interface, should be considered experimental in nature and may change in future releases." -}, - -{ - "location": "manual/parallel-computing.html#Multi-Threading-(Experimental)-1", - "page": "Parallel Computing", - "title": "Multi-Threading (Experimental)", - "category": "section", - "text": "In addition to tasks, remote calls, and remote references, Julia from v0.5 forwards will natively support multi-threading. Note that this section is experimental and the interfaces may change in the future." -}, - -{ - "location": "manual/parallel-computing.html#Setup-1", - "page": "Parallel Computing", - "title": "Setup", - "category": "section", - "text": "By default, Julia starts up with a single thread of execution. This can be verified by using the command Threads.nthreads():julia> Threads.nthreads()\n1The number of threads Julia starts up with is controlled by an environment variable called JULIA_NUM_THREADS. Now, let\'s start up Julia with 4 threads:export JULIA_NUM_THREADS=4(The above command works on bourne shells on Linux and OSX. Note that if you\'re using a C shell on these platforms, you should use the keyword set instead of export. If you\'re on Windows, start up the command line in the location of julia.exe and use set instead of export.)Let\'s verify there are 4 threads at our disposal.julia> Threads.nthreads()\n4But we are currently on the master thread. To check, we use the command Threads.threadid()julia> Threads.threadid()\n1" -}, - -{ - "location": "manual/parallel-computing.html#The-@threads-Macro-1", - "page": "Parallel Computing", - "title": "The @threads Macro", - "category": "section", - "text": "Let\'s work a simple example using our native threads. Let us create an array of zeros:julia> a = zeros(10)\n10-element Array{Float64,1}:\n 0.0\n 0.0\n 0.0\n 0.0\n 0.0\n 0.0\n 0.0\n 0.0\n 0.0\n 0.0Let us operate on this array simultaneously using 4 threads. We\'ll have each thread write its thread ID into each location.Julia supports parallel loops using the Threads.@threads macro. This macro is affixed in front of a for loop to indicate to Julia that the loop is a multi-threaded region:julia> Threads.@threads for i = 1:10\n a[i] = Threads.threadid()\n endThe iteration space is split amongst the threads, after which each thread writes its thread ID to its assigned locations:julia> a\n10-element Array{Float64,1}:\n 1.0\n 1.0\n 1.0\n 2.0\n 2.0\n 2.0\n 3.0\n 3.0\n 4.0\n 4.0Note that Threads.@threads does not have an optional reduction parameter like @parallel." -}, - -{ - "location": "manual/parallel-computing.html#@threadcall-(Experimental)-1", - "page": "Parallel Computing", - "title": "@threadcall (Experimental)", - "category": "section", - "text": "All I/O tasks, timers, REPL commands, etc are multiplexed onto a single OS thread via an event loop. A patched version of libuv (http://docs.libuv.org/en/v1.x/) provides this functionality. Yield points provide for co-operatively scheduling multiple tasks onto the same OS thread. I/O tasks and timers yield implicitly while waiting for the event to occur. Calling yield() explicitly allows for other tasks to be scheduled.Thus, a task executing a ccall effectively prevents the Julia scheduler from executing any other tasks till the call returns. This is true for all calls into external libraries. Exceptions are calls into custom C code that call back into Julia (which may then yield) or C code that calls jl_yield() (C equivalent of yield()).Note that while Julia code runs on a single thread (by default), libraries used by Julia may launch their own internal threads. For example, the BLAS library may start as many threads as there are cores on a machine.The @threadcall macro addresses scenarios where we do not want a ccall to block the main Julia event loop. It schedules a C function for execution in a separate thread. A threadpool with a default size of 4 is used for this. The size of the threadpool is controlled via environment variable UV_THREADPOOL_SIZE. While waiting for a free thread, and during function execution once a thread is available, the requesting task (on the main Julia event loop) yields to other tasks. Note that @threadcall does not return till the execution is complete. From a user point of view, it is therefore a blocking call like other Julia APIs.It is very important that the called function does not call back into Julia.@threadcall may be removed/changed in future versions of Julia.[1]: In this context, MPI refers to the MPI-1 standard. Beginning with MPI-2, the MPI standards committee introduced a new set of communication mechanisms, collectively referred to as Remote Memory Access (RMA). The motivation for adding RMA to the MPI standard was to facilitate one-sided communication patterns. For additional information on the latest MPI standard, see http://mpi-forum.org/docs." -}, - -{ - "location": "manual/dates.html#", - "page": "Date and DateTime", - "title": "Date and DateTime", - "category": "page", - "text": "" -}, - -{ - "location": "manual/dates.html#Date-and-DateTime-1", - "page": "Date and DateTime", - "title": "Date and DateTime", - "category": "section", - "text": "CurrentModule = Base.DatesThe Dates module provides two types for working with dates: Date and DateTime, representing day and millisecond precision, respectively; both are subtypes of the abstract TimeType. The motivation for distinct types is simple: some operations are much simpler, both in terms of code and mental reasoning, when the complexities of greater precision don\'t have to be dealt with. For example, since the Date type only resolves to the precision of a single date (i.e. no hours, minutes, or seconds), normal considerations for time zones, daylight savings/summer time, and leap seconds are unnecessary and avoided.Both Date and DateTime are basically immutable Int64 wrappers. The single instant field of either type is actually a UTInstant{P} type, which represents a continuously increasing machine timeline based on the UT second [1]. The DateTime type is not aware of time zones (naive, in Python parlance), analogous to a LocalDateTime in Java 8. Additional time zone functionality can be added through the TimeZones.jl package, which compiles the IANA time zone database. Both Date and DateTime are based on the ISO 8601 standard, which follows the proleptic Gregorian calendar. One note is that the ISO 8601 standard is particular about BC/BCE dates. In general, the last day of the BC/BCE era, 1-12-31 BC/BCE, was followed by 1-1-1 AD/CE, thus no year zero exists. The ISO standard, however, states that 1 BC/BCE is year zero, so 0000-12-31 is the day before 0001-01-01, and year -0001 (yes, negative one for the year) is 2 BC/BCE, year -0002 is 3 BC/BCE, etc.[1]: The notion of the UT second is actually quite fundamental. There are basically two different notions of time generally accepted, one based on the physical rotation of the earth (one full rotation = 1 day), the other based on the SI second (a fixed, constant value). These are radically different! Think about it, a \"UT second\", as defined relative to the rotation of the earth, may have a different absolute length depending on the day! Anyway, the fact that Date and DateTime are based on UT seconds is a simplifying, yet honest assumption so that things like leap seconds and all their complexity can be avoided. This basis of time is formally called UT or UT1. Basing types on the UT second basically means that every minute has 60 seconds and every day has 24 hours and leads to more natural calculations when working with calendar dates." -}, - -{ - "location": "manual/dates.html#Constructors-1", - "page": "Date and DateTime", - "title": "Constructors", - "category": "section", - "text": "Date and DateTime types can be constructed by integer or Period types, by parsing, or through adjusters (more on those later):julia> DateTime(2013)\n2013-01-01T00:00:00\n\njulia> DateTime(2013,7)\n2013-07-01T00:00:00\n\njulia> DateTime(2013,7,1)\n2013-07-01T00:00:00\n\njulia> DateTime(2013,7,1,12)\n2013-07-01T12:00:00\n\njulia> DateTime(2013,7,1,12,30)\n2013-07-01T12:30:00\n\njulia> DateTime(2013,7,1,12,30,59)\n2013-07-01T12:30:59\n\njulia> DateTime(2013,7,1,12,30,59,1)\n2013-07-01T12:30:59.001\n\njulia> Date(2013)\n2013-01-01\n\njulia> Date(2013,7)\n2013-07-01\n\njulia> Date(2013,7,1)\n2013-07-01\n\njulia> Date(Dates.Year(2013),Dates.Month(7),Dates.Day(1))\n2013-07-01\n\njulia> Date(Dates.Month(7),Dates.Year(2013))\n2013-07-01Date or DateTime parsing is accomplished by the use of format strings. Format strings work by the notion of defining delimited or fixed-width \"slots\" that contain a period to parse and passing the text to parse and format string to a Date or DateTime constructor, of the form Date(\"2015-01-01\",\"y-m-d\") or DateTime(\"20150101\",\"yyyymmdd\").Delimited slots are marked by specifying the delimiter the parser should expect between two subsequent periods; so \"y-m-d\" lets the parser know that between the first and second slots in a date string like \"2014-07-16\", it should find the - character. The y, m, and d characters let the parser know which periods to parse in each slot.Fixed-width slots are specified by repeating the period character the number of times corresponding to the width with no delimiter between characters. So \"yyyymmdd\" would correspond to a date string like \"20140716\". The parser distinguishes a fixed-width slot by the absence of a delimiter, noting the transition \"yyyymm\" from one period character to the next.Support for text-form month parsing is also supported through the u and U characters, for abbreviated and full-length month names, respectively. By default, only English month names are supported, so u corresponds to \"Jan\", \"Feb\", \"Mar\", etc. And U corresponds to \"January\", \"February\", \"March\", etc. Similar to other name=>value mapping functions dayname() and monthname(), custom locales can be loaded by passing in the locale=>Dict{String,Int} mapping to the MONTHTOVALUEABBR and MONTHTOVALUE dicts for abbreviated and full-name month names, respectively.One note on parsing performance: using the Date(date_string,format_string) function is fine if only called a few times. If there are many similarly formatted date strings to parse however, it is much more efficient to first create a Dates.DateFormat, and pass it instead of a raw format string.julia> df = DateFormat(\"y-m-d\");\n\njulia> dt = Date(\"2015-01-01\",df)\n2015-01-01\n\njulia> dt2 = Date(\"2015-01-02\",df)\n2015-01-02You can also use the dateformat\"\" string macro. This macro creates the DateFormat object once when the macro is expanded and uses the same DateFormat object even if a code snippet is run multiple times.julia> for i = 1:10^5\n Date(\"2015-01-01\", dateformat\"y-m-d\")\n endA full suite of parsing and formatting tests and examples is available in tests/dates/io.jl." -}, - -{ - "location": "manual/dates.html#Durations/Comparisons-1", - "page": "Date and DateTime", - "title": "Durations/Comparisons", - "category": "section", - "text": "Finding the length of time between two Date or DateTime is straightforward given their underlying representation as UTInstant{Day} and UTInstant{Millisecond}, respectively. The difference between Date is returned in the number of Day, and DateTime in the number of Millisecond. Similarly, comparing TimeType is a simple matter of comparing the underlying machine instants (which in turn compares the internal Int64 values).julia> dt = Date(2012,2,29)\n2012-02-29\n\njulia> dt2 = Date(2000,2,1)\n2000-02-01\n\njulia> dump(dt)\nDate\n instant: Base.Dates.UTInstant{Base.Dates.Day}\n periods: Base.Dates.Day\n value: Int64 734562\n\njulia> dump(dt2)\nDate\n instant: Base.Dates.UTInstant{Base.Dates.Day}\n periods: Base.Dates.Day\n value: Int64 730151\n\njulia> dt > dt2\ntrue\n\njulia> dt != dt2\ntrue\n\njulia> dt + dt2\nERROR: MethodError: no method matching +(::Date, ::Date)\n[...]\n\njulia> dt * dt2\nERROR: MethodError: no method matching *(::Date, ::Date)\n[...]\n\njulia> dt / dt2\nERROR: MethodError: no method matching /(::Date, ::Date)\n[...]\n\njulia> dt - dt2\n4411 days\n\njulia> dt2 - dt\n-4411 days\n\njulia> dt = DateTime(2012,2,29)\n2012-02-29T00:00:00\n\njulia> dt2 = DateTime(2000,2,1)\n2000-02-01T00:00:00\n\njulia> dt - dt2\n381110400000 milliseconds" -}, - -{ - "location": "manual/dates.html#Accessor-Functions-1", - "page": "Date and DateTime", - "title": "Accessor Functions", - "category": "section", - "text": "Because the Date and DateTime types are stored as single Int64 values, date parts or fields can be retrieved through accessor functions. The lowercase accessors return the field as an integer:julia> t = Date(2014, 1, 31)\n2014-01-31\n\njulia> Dates.year(t)\n2014\n\njulia> Dates.month(t)\n1\n\njulia> Dates.week(t)\n5\n\njulia> Dates.day(t)\n31While propercase return the same value in the corresponding Period type:julia> Dates.Year(t)\n2014 years\n\njulia> Dates.Day(t)\n31 daysCompound methods are provided, as they provide a measure of efficiency if multiple fields are needed at the same time:julia> Dates.yearmonth(t)\n(2014, 1)\n\njulia> Dates.monthday(t)\n(1, 31)\n\njulia> Dates.yearmonthday(t)\n(2014, 1, 31)One may also access the underlying UTInstant or integer value:julia> dump(t)\nDate\n instant: Base.Dates.UTInstant{Base.Dates.Day}\n periods: Base.Dates.Day\n value: Int64 735264\n\njulia> t.instant\nBase.Dates.UTInstant{Base.Dates.Day}(735264 days)\n\njulia> Dates.value(t)\n735264" -}, - -{ - "location": "manual/dates.html#Query-Functions-1", - "page": "Date and DateTime", - "title": "Query Functions", - "category": "section", - "text": "Query functions provide calendrical information about a TimeType. They include information about the day of the week:julia> t = Date(2014, 1, 31)\n2014-01-31\n\njulia> Dates.dayofweek(t)\n5\n\njulia> Dates.dayname(t)\n\"Friday\"\n\njulia> Dates.dayofweekofmonth(t) # 5th Friday of January\n5Month of the year:julia> Dates.monthname(t)\n\"January\"\n\njulia> Dates.daysinmonth(t)\n31As well as information about the TimeType\'s year and quarter:julia> Dates.isleapyear(t)\nfalse\n\njulia> Dates.dayofyear(t)\n31\n\njulia> Dates.quarterofyear(t)\n1\n\njulia> Dates.dayofquarter(t)\n31The dayname() and monthname() methods can also take an optional locale keyword that can be used to return the name of the day or month of the year for other languages/locales. There are also versions of these functions returning the abbreviated names, namely dayabbr() and monthabbr(). First the mapping is loaded into the LOCALES variable:julia> french_months = [\"janvier\", \"février\", \"mars\", \"avril\", \"mai\", \"juin\",\n \"juillet\", \"août\", \"septembre\", \"octobre\", \"novembre\", \"décembre\"];\n\njulia> french_monts_abbrev = [\"janv\",\"févr\",\"mars\",\"avril\",\"mai\",\"juin\",\n \"juil\",\"août\",\"sept\",\"oct\",\"nov\",\"déc\"];\n\njulia> french_days = [\"lundi\",\"mardi\",\"mercredi\",\"jeudi\",\"vendredi\",\"samedi\",\"dimanche\"];\n\njulia> Dates.LOCALES[\"french\"] = Dates.DateLocale(french_months, french_monts_abbrev, french_days, [\"\"]);The above mentioned functions can then be used to perform the queries:julia> Dates.dayname(t;locale=\"french\")\n\"vendredi\"\n\njulia> Dates.monthname(t;locale=\"french\")\n\"janvier\"\n\njulia> Dates.monthabbr(t;locale=\"french\")\n\"janv\"Since the abbreviated versions of the days are not loaded, trying to use the function dayabbr() will error.julia> Dates.dayabbr(t;locale=\"french\")\nERROR: BoundsError: attempt to access 1-element Array{String,1} at index [5]\nStacktrace:\n [1] #dayabbr#6(::String, ::Function, ::Int64) at ./dates/query.jl:114\n [2] (::Base.Dates.#kw##dayabbr)(::Array{Any,1}, ::Base.Dates.#dayabbr, ::Int64) at ./:0 (repeats 2 times)" -}, - -{ - "location": "manual/dates.html#TimeType-Period-Arithmetic-1", - "page": "Date and DateTime", - "title": "TimeType-Period Arithmetic", - "category": "section", - "text": "It\'s good practice when using any language/date framework to be familiar with how date-period arithmetic is handled as there are some tricky issues to deal with (though much less so for day-precision types).The Dates module approach tries to follow the simple principle of trying to change as little as possible when doing Period arithmetic. This approach is also often known as calendrical arithmetic or what you would probably guess if someone were to ask you the same calculation in a conversation. Why all the fuss about this? Let\'s take a classic example: add 1 month to January 31st, 2014. What\'s the answer? Javascript will say March 3 (assumes 31 days). PHP says March 2 (assumes 30 days). The fact is, there is no right answer. In the Dates module, it gives the result of February 28th. How does it figure that out? I like to think of the classic 7-7-7 gambling game in casinos.Now just imagine that instead of 7-7-7, the slots are Year-Month-Day, or in our example, 2014-01-31. When you ask to add 1 month to this date, the month slot is incremented, so now we have 2014-02-31. Then the day number is checked if it is greater than the last valid day of the new month; if it is (as in the case above), the day number is adjusted down to the last valid day (28). What are the ramifications with this approach? Go ahead and add another month to our date, 2014-02-28 + Month(1) == 2014-03-28. What? Were you expecting the last day of March? Nope, sorry, remember the 7-7-7 slots. As few slots as possible are going to change, so we first increment the month slot by 1, 2014-03-28, and boom, we\'re done because that\'s a valid date. On the other hand, if we were to add 2 months to our original date, 2014-01-31, then we end up with 2014-03-31, as expected. The other ramification of this approach is a loss in associativity when a specific ordering is forced (i.e. adding things in different orders results in different outcomes). For example:julia> (Date(2014,1,29)+Dates.Day(1)) + Dates.Month(1)\n2014-02-28\n\njulia> (Date(2014,1,29)+Dates.Month(1)) + Dates.Day(1)\n2014-03-01What\'s going on there? In the first line, we\'re adding 1 day to January 29th, which results in 2014-01-30; then we add 1 month, so we get 2014-02-30, which then adjusts down to 2014-02-28. In the second example, we add 1 month first, where we get 2014-02-29, which adjusts down to 2014-02-28, and then add 1 day, which results in 2014-03-01. One design principle that helps in this case is that, in the presence of multiple Periods, the operations will be ordered by the Periods\' types, not their value or positional order; this means Year will always be added first, then Month, then Week, etc. Hence the following does result in associativity and Just Works:julia> Date(2014,1,29) + Dates.Day(1) + Dates.Month(1)\n2014-03-01\n\njulia> Date(2014,1,29) + Dates.Month(1) + Dates.Day(1)\n2014-03-01Tricky? Perhaps. What is an innocent Dates user to do? The bottom line is to be aware that explicitly forcing a certain associativity, when dealing with months, may lead to some unexpected results, but otherwise, everything should work as expected. Thankfully, that\'s pretty much the extent of the odd cases in date-period arithmetic when dealing with time in UT (avoiding the \"joys\" of dealing with daylight savings, leap seconds, etc.).As a bonus, all period arithmetic objects work directly with ranges:julia> dr = Date(2014,1,29):Date(2014,2,3)\n2014-01-29:1 day:2014-02-03\n\njulia> collect(dr)\n6-element Array{Date,1}:\n 2014-01-29\n 2014-01-30\n 2014-01-31\n 2014-02-01\n 2014-02-02\n 2014-02-03\n\njulia> dr = Date(2014,1,29):Dates.Month(1):Date(2014,07,29)\n2014-01-29:1 month:2014-07-29\n\njulia> collect(dr)\n7-element Array{Date,1}:\n 2014-01-29\n 2014-02-28\n 2014-03-29\n 2014-04-29\n 2014-05-29\n 2014-06-29\n 2014-07-29" -}, - -{ - "location": "manual/dates.html#Adjuster-Functions-1", - "page": "Date and DateTime", - "title": "Adjuster Functions", - "category": "section", - "text": "As convenient as date-period arithmetics are, often the kinds of calculations needed on dates take on a calendrical or temporal nature rather than a fixed number of periods. Holidays are a perfect example; most follow rules such as \"Memorial Day = Last Monday of May\", or \"Thanksgiving = 4th Thursday of November\". These kinds of temporal expressions deal with rules relative to the calendar, like first or last of the month, next Tuesday, or the first and third Wednesdays, etc.The Dates module provides the adjuster API through several convenient methods that aid in simply and succinctly expressing temporal rules. The first group of adjuster methods deal with the first and last of weeks, months, quarters, and years. They each take a single TimeType as input and return or adjust to the first or last of the desired period relative to the input.julia> Dates.firstdayofweek(Date(2014,7,16)) # Adjusts the input to the Monday of the input\'s week\n2014-07-14\n\njulia> Dates.lastdayofmonth(Date(2014,7,16)) # Adjusts to the last day of the input\'s month\n2014-07-31\n\njulia> Dates.lastdayofquarter(Date(2014,7,16)) # Adjusts to the last day of the input\'s quarter\n2014-09-30The next two higher-order methods, tonext(), and toprev(), generalize working with temporal expressions by taking a DateFunction as first argument, along with a starting TimeType. A DateFunction is just a function, usually anonymous, that takes a single TimeType as input and returns a Bool, true indicating a satisfied adjustment criterion. For example:julia> istuesday = x->Dates.dayofweek(x) == Dates.Tuesday # Returns true if the day of the week of x is Tuesday\n(::#1) (generic function with 1 method)\n\njulia> Dates.tonext(istuesday, Date(2014,7,13)) # 2014-07-13 is a Sunday\n2014-07-15\n\njulia> Dates.tonext(Date(2014,7,13), Dates.Tuesday) # Convenience method provided for day of the week adjustments\n2014-07-15This is useful with the do-block syntax for more complex temporal expressions:julia> Dates.tonext(Date(2014,7,13)) do x\n # Return true on the 4th Thursday of November (Thanksgiving)\n Dates.dayofweek(x) == Dates.Thursday &&\n Dates.dayofweekofmonth(x) == 4 &&\n Dates.month(x) == Dates.November\n end\n2014-11-27The Base.filter() method can be used to obtain all valid dates/moments in a specified range:# Pittsburgh street cleaning; Every 2nd Tuesday from April to November\n# Date range from January 1st, 2014 to January 1st, 2015\njulia> dr = Dates.Date(2014):Dates.Date(2015);\n\njulia> filter(dr) do x\n Dates.dayofweek(x) == Dates.Tue &&\n Dates.April <= Dates.month(x) <= Dates.Nov &&\n Dates.dayofweekofmonth(x) == 2\n end\n8-element Array{Date,1}:\n 2014-04-08\n 2014-05-13\n 2014-06-10\n 2014-07-08\n 2014-08-12\n 2014-09-09\n 2014-10-14\n 2014-11-11Additional examples and tests are available in test/dates/adjusters.jl." -}, - -{ - "location": "manual/dates.html#Period-Types-1", - "page": "Date and DateTime", - "title": "Period Types", - "category": "section", - "text": "Periods are a human view of discrete, sometimes irregular durations of time. Consider 1 month; it could represent, in days, a value of 28, 29, 30, or 31 depending on the year and month context. Or a year could represent 365 or 366 days in the case of a leap year. Period types are simple Int64 wrappers and are constructed by wrapping any Int64 convertible type, i.e. Year(1) or Month(3.0). Arithmetic between Period of the same type behave like integers, and limited Period-Real arithmetic is available.julia> y1 = Dates.Year(1)\n1 year\n\njulia> y2 = Dates.Year(2)\n2 years\n\njulia> y3 = Dates.Year(10)\n10 years\n\njulia> y1 + y2\n3 years\n\njulia> div(y3,y2)\n5\n\njulia> y3 - y2\n8 years\n\njulia> y3 % y2\n0 years\n\njulia> div(y3,3) # mirrors integer division\n3 years" -}, - -{ - "location": "manual/dates.html#Rounding-1", - "page": "Date and DateTime", - "title": "Rounding", - "category": "section", - "text": "Date and DateTime values can be rounded to a specified resolution (e.g., 1 month or 15 minutes) with floor(), ceil(), or round():julia> floor(Date(1985, 8, 16), Dates.Month)\n1985-08-01\n\njulia> ceil(DateTime(2013, 2, 13, 0, 31, 20), Dates.Minute(15))\n2013-02-13T00:45:00\n\njulia> round(DateTime(2016, 8, 6, 20, 15), Dates.Day)\n2016-08-07T00:00:00Unlike the numeric round() method, which breaks ties toward the even number by default, the TimeTyperound() method uses the RoundNearestTiesUp rounding mode. (It\'s difficult to guess what breaking ties to nearest \"even\" TimeType would entail.) Further details on the available RoundingMode s can be found in the API reference.Rounding should generally behave as expected, but there are a few cases in which the expected behaviour is not obvious." -}, - -{ - "location": "manual/dates.html#Rounding-Epoch-1", - "page": "Date and DateTime", - "title": "Rounding Epoch", - "category": "section", - "text": "In many cases, the resolution specified for rounding (e.g., Dates.Second(30)) divides evenly into the next largest period (in this case, Dates.Minute(1)). But rounding behaviour in cases in which this is not true may lead to confusion. What is the expected result of rounding a DateTime to the nearest 10 hours?julia> round(DateTime(2016, 7, 17, 11, 55), Dates.Hour(10))\n2016-07-17T12:00:00That may seem confusing, given that the hour (12) is not divisible by 10. The reason that 2016-07-17T12:00:00 was chosen is that it is 17,676,660 hours after 0000-01-01T00:00:00, and 17,676,660 is divisible by 10.As Julia Date and DateTime values are represented according to the ISO 8601 standard, 0000-01-01T00:00:00 was chosen as base (or \"rounding epoch\") from which to begin the count of days (and milliseconds) used in rounding calculations. (Note that this differs slightly from Julia\'s internal representation of Date s using Rata Die notation; but since the ISO 8601 standard is most visible to the end user, 0000-01-01T00:00:00 was chosen as the rounding epoch instead of the 0000-12-31T00:00:00 used internally to minimize confusion.)The only exception to the use of 0000-01-01T00:00:00 as the rounding epoch is when rounding to weeks. Rounding to the nearest week will always return a Monday (the first day of the week as specified by ISO 8601). For this reason, we use 0000-01-03T00:00:00 (the first day of the first week of year 0000, as defined by ISO 8601) as the base when rounding to a number of weeks.Here is a related case in which the expected behaviour is not necessarily obvious: What happens when we round to the nearest P(2), where P is a Period type? In some cases (specifically, when P <: Dates.TimePeriod) the answer is clear:julia> round(DateTime(2016, 7, 17, 8, 55, 30), Dates.Hour(2))\n2016-07-17T08:00:00\n\njulia> round(DateTime(2016, 7, 17, 8, 55, 30), Dates.Minute(2))\n2016-07-17T08:56:00This seems obvious, because two of each of these periods still divides evenly into the next larger order period. But in the case of two months (which still divides evenly into one year), the answer may be surprising:julia> round(DateTime(2016, 7, 17, 8, 55, 30), Dates.Month(2))\n2016-07-01T00:00:00Why round to the first day in July, even though it is month 7 (an odd number)? The key is that months are 1-indexed (the first month is assigned 1), unlike hours, minutes, seconds, and milliseconds (the first of which are assigned 0).This means that rounding a DateTime to an even multiple of seconds, minutes, hours, or years (because the ISO 8601 specification includes a year zero) will result in a DateTime with an even value in that field, while rounding a DateTime to an even multiple of months will result in the months field having an odd value. Because both months and years may contain an irregular number of days, whether rounding to an even number of days will result in an even value in the days field is uncertain.See the API reference for additional information on methods exported from the Dates module." -}, - -{ - "location": "manual/interacting-with-julia.html#", - "page": "Interacting With Julia", - "title": "Interacting With Julia", - "category": "page", - "text": "" -}, - -{ - "location": "manual/interacting-with-julia.html#Interacting-With-Julia-1", - "page": "Interacting With Julia", - "title": "Interacting With Julia", - "category": "section", - "text": "Julia comes with a full-featured interactive command-line REPL (read-eval-print loop) built into the julia executable. In addition to allowing quick and easy evaluation of Julia statements, it has a searchable history, tab-completion, many helpful keybindings, and dedicated help and shell modes. The REPL can be started by simply calling julia with no arguments or double-clicking on the executable:$ julia\n _\n _ _ _(_)_ | A fresh approach to technical computing\n (_) | (_) (_) | Documentation: https://docs.julialang.org\n _ _ _| |_ __ _ | Type \"?help\" for help.\n | | | | | | |/ _` | |\n | | |_| | | | (_| | | Version 0.6.0-dev.2493 (2017-01-31 18:53 UTC)\n _/ |\\__\'_|_|_|\\__\'_| | Commit c99e12c* (0 days old master)\n|__/ | x86_64-linux-gnu\n\njulia>To exit the interactive session, type ^D – the control key together with the d key on a blank line – or type quit() followed by the return or enter key. The REPL greets you with a banner and a julia> prompt." -}, - -{ - "location": "manual/interacting-with-julia.html#The-different-prompt-modes-1", - "page": "Interacting With Julia", - "title": "The different prompt modes", - "category": "section", - "text": "" -}, - -{ - "location": "manual/interacting-with-julia.html#The-Julian-mode-1", - "page": "Interacting With Julia", - "title": "The Julian mode", - "category": "section", - "text": "The REPL has four main modes of operation. The first and most common is the Julian prompt. It is the default mode of operation; each new line initially starts with julia>. It is here that you can enter Julia expressions. Hitting return or enter after a complete expression has been entered will evaluate the entry and show the result of the last expression.julia> string(1 + 2)\n\"3\"There are a number useful features unique to interactive work. In addition to showing the result, the REPL also binds the result to the variable ans. A trailing semicolon on the line can be used as a flag to suppress showing the result.julia> string(3 * 4);\n\njulia> ans\n\"12\"In Julia mode, the REPL supports something called prompt pasting. This activates when pasting text that starts with julia>  into the REPL. In that case, only expressions starting with julia>  are parsed, others are removed. This makes it is possible to paste a chunk of code that has been copied from a REPL session without having to scrub away prompts and outputs. This feature is enabled by default but can be disabled or enabled at will with Base.REPL.enable_promptpaste(::Bool). If it is enabled, you can try it out by pasting the code block above this paragraph straight into the REPL. This feature does not work on the standard Windows command prompt due to its limitation at detecting when a paste occurs." -}, - -{ - "location": "manual/interacting-with-julia.html#Help-mode-1", - "page": "Interacting With Julia", - "title": "Help mode", - "category": "section", - "text": "When the cursor is at the beginning of the line, the prompt can be changed to a help mode by typing ?. Julia will attempt to print help or documentation for anything entered in help mode:julia> ? # upon typing ?, the prompt changes (in place) to: help?>\n\nhelp?> string\nsearch: string String stringmime Cstring Cwstring RevString readstring randstring bytestring SubString\n\n string(xs...)\n\n Create a string from any values using the print function.Macros, types and variables can also be queried:help?> @time\n @time\n\n A macro to execute an expression, printing the time it took to execute, the number of allocations,\n and the total number of bytes its execution caused to be allocated, before returning the value of the\n expression.\n\n See also @timev, @timed, @elapsed, and @allocated.\n\nhelp?> AbstractString\nsearch: AbstractString AbstractSparseMatrix AbstractSparseVector AbstractSet\n\n No documentation found.\n\n Summary:\n\n abstract AbstractString <: Any\n\n Subtypes:\n\n Base.Test.GenericString\n DirectIndexString\n StringHelp mode can be exited by pressing backspace at the beginning of the line." -}, - -{ - "location": "manual/interacting-with-julia.html#man-shell-mode-1", - "page": "Interacting With Julia", - "title": "Shell mode", - "category": "section", - "text": "Just as help mode is useful for quick access to documentation, another common task is to use the system shell to execute system commands. Just as ? entered help mode when at the beginning of the line, a semicolon (;) will enter the shell mode. And it can be exited by pressing backspace at the beginning of the line.julia> ; # upon typing ;, the prompt changes (in place) to: shell>\n\nshell> echo hello\nhello" -}, - -{ - "location": "manual/interacting-with-julia.html#Search-modes-1", - "page": "Interacting With Julia", - "title": "Search modes", - "category": "section", - "text": "In all of the above modes, the executed lines get saved to a history file, which can be searched. To initiate an incremental search through the previous history, type ^R – the control key together with the r key. The prompt will change to (reverse-i-search)`\':, and as you type the search query will appear in the quotes. The most recent result that matches the query will dynamically update to the right of the colon as more is typed. To find an older result using the same query, simply type ^R again.Just as ^R is a reverse search, ^S is a forward search, with the prompt (i-search)`\':. The two may be used in conjunction with each other to move through the previous or next matching results, respectively." -}, - -{ - "location": "manual/interacting-with-julia.html#Key-bindings-1", - "page": "Interacting With Julia", - "title": "Key bindings", - "category": "section", - "text": "The Julia REPL makes great use of key bindings. Several control-key bindings were already introduced above (^D to exit, ^R and ^S for searching), but there are many more. In addition to the control-key, there are also meta-key bindings. These vary more by platform, but most terminals default to using alt- or option- held down with a key to send the meta-key (or can be configured to do so).Keybinding Description\nProgram control  \n^D Exit (when buffer is empty)\n^C Interrupt or cancel\n^L Clear console screen\nReturn/Enter, ^J New line, executing if it is complete\nmeta-Return/Enter Insert new line without executing it\n? or ; Enter help or shell mode (when at start of a line)\n^R, ^S Incremental history search, described above\nCursor movement  \nRight arrow, ^F Move right one character\nLeft arrow, ^B Move left one character\nHome, ^A Move to beginning of line\nEnd, ^E Move to end of line\n^P Change to the previous or next history entry\n^N Change to the next history entry\nUp arrow Move up one line (or to the previous history entry)\nDown arrow Move down one line (or to the next history entry)\nPage-up Change to the previous history entry that matches the text before the cursor\nPage-down Change to the next history entry that matches the text before the cursor\nmeta-F Move right one word\nmeta-B Move left one word\nEditing  \nBackspace, ^H Delete the previous character\nDelete, ^D Forward delete one character (when buffer has text)\nmeta-Backspace Delete the previous word\nmeta-D Forward delete the next word\n^W Delete previous text up to the nearest whitespace\n^K \"Kill\" to end of line, placing the text in a buffer\n^Y \"Yank\" insert the text from the kill buffer\n^T Transpose the characters about the cursor\n^Q Write a number in REPL and press ^Q to open editor at corresponding stackframe" -}, - -{ - "location": "manual/interacting-with-julia.html#Customizing-keybindings-1", - "page": "Interacting With Julia", - "title": "Customizing keybindings", - "category": "section", - "text": "Julia\'s REPL keybindings may be fully customized to a user\'s preferences by passing a dictionary to REPL.setup_interface(). The keys of this dictionary may be characters or strings. The key \'*\' refers to the default action. Control plus character x bindings are indicated with \"^x\". Meta plus x can be written \"\\\\Mx\". The values of the custom keymap must be nothing (indicating that the input should be ignored) or functions that accept the signature (PromptState, AbstractREPL, Char). The REPL.setup_interface() function must be called before the REPL is initialized, by registering the operation with atreplinit(). For example, to bind the up and down arrow keys to move through history without prefix search, one could put the following code in .juliarc.jl:import Base: LineEdit, REPL\n\nconst mykeys = Dict{Any,Any}(\n # Up Arrow\n \"\\e[A\" => (s,o...)->(LineEdit.edit_move_up(s) || LineEdit.history_prev(s, LineEdit.mode(s).hist)),\n # Down Arrow\n \"\\e[B\" => (s,o...)->(LineEdit.edit_move_up(s) || LineEdit.history_next(s, LineEdit.mode(s).hist))\n)\n\nfunction customize_keys(repl)\n repl.interface = REPL.setup_interface(repl; extra_repl_keymap = mykeys)\nend\n\natreplinit(customize_keys)Users should refer to base/LineEdit.jl to discover the available actions on key input." -}, - -{ - "location": "manual/interacting-with-julia.html#Tab-completion-1", - "page": "Interacting With Julia", - "title": "Tab completion", - "category": "section", - "text": "In both the Julian and help modes of the REPL, one can enter the first few characters of a function or type and then press the tab key to get a list all matches:julia> stri[TAB]\nstride strides string stringmime strip\n\njulia> Stri[TAB]\nStridedArray StridedMatrix StridedVecOrMat StridedVector StringThe tab key can also be used to substitute LaTeX math symbols with their Unicode equivalents, and get a list of LaTeX matches as well:julia> \\pi[TAB]\njulia> π\nπ = 3.1415926535897...\n\njulia> e\\_1[TAB] = [1,0]\njulia> e₁ = [1,0]\n2-element Array{Int64,1}:\n 1\n 0\n\njulia> e\\^1[TAB] = [1 0]\njulia> e¹ = [1 0]\n1×2 Array{Int64,2}:\n 1 0\n\njulia> \\sqrt[TAB]2 # √ is equivalent to the sqrt() function\njulia> √2\n1.4142135623730951\n\njulia> \\hbar[TAB](h) = h / 2\\pi[TAB]\njulia> ħ(h) = h / 2π\nħ (generic function with 1 method)\n\njulia> \\h[TAB]\n\\hat \\hermitconjmatrix \\hkswarow \\hrectangle\n\\hatapprox \\hexagon \\hookleftarrow \\hrectangleblack\n\\hbar \\hexagonblack \\hookrightarrow \\hslash\n\\heartsuit \\hksearow \\house \\hspace\n\njulia> α=\"\\alpha[TAB]\" # LaTeX completion also works in strings\njulia> α=\"α\"A full list of tab-completions can be found in the Unicode Input section of the manual.Completion of paths works for strings and julia\'s shell mode:julia> path=\"/[TAB]\"\n.dockerenv .juliabox/ boot/ etc/ lib/ media/ opt/ root/ sbin/ sys/ usr/\n.dockerinit bin/ dev/ home/ lib64/ mnt/ proc/ run/ srv/ tmp/ var/\nshell> /[TAB]\n.dockerenv .juliabox/ boot/ etc/ lib/ media/ opt/ root/ sbin/ sys/ usr/\n.dockerinit bin/ dev/ home/ lib64/ mnt/ proc/ run/ srv/ tmp/ var/Tab completion can help with investigation of the available methods matching the input arguments:julia> max([TAB] # All methods are displayed, not shown here due to size of the list\n\njulia> max([1, 2], [TAB] # All methods where `Vector{Int}` matches as first argument\nmax(x, y) in Base at operators.jl:215\nmax(a, b, c, xs...) in Base at operators.jl:281\n\njulia> max([1, 2], max(1, 2), [TAB] # All methods matching the arguments.\nmax(x, y) in Base at operators.jl:215\nmax(a, b, c, xs...) in Base at operators.jl:281Keywords are also displayed in the suggested methods, see second line after ; where limit and keep are keyword arguments:julia> split(\"1 1 1\", [TAB]\nsplit(str::AbstractString) in Base at strings/util.jl:278\nsplit{T<:AbstractString}(str::T, splitter; limit, keep) in Base at strings/util.jl:254The completion of the methods uses type inference and can therefore see if the arguments match even if the arguments are output from functions. The function needs to be type stable for the completion to be able to remove non-matching methods.Tab completion can also help completing fields:julia> Pkg.a[TAB]\nadd availableFields for output from functions can also be completed:julia> split(\"\",\"\")[1].[TAB]\nendof offset stringThe completion of fields for output from functions uses type inference, and it can only suggest fields if the function is type stable." -}, - -{ - "location": "manual/interacting-with-julia.html#Customizing-Colors-1", - "page": "Interacting With Julia", - "title": "Customizing Colors", - "category": "section", - "text": "The colors used by Julia and the REPL can be customized, as well. To change the color of the Julia prompt you can add something like the following to your .juliarc.jl file, which is to be placed inside your home directory:function customize_colors(repl)\n repl.prompt_color = Base.text_colors[:cyan]\nend\n\natreplinit(customize_colors)The available color keys can be seen by typing Base.text_colors in the help mode of the REPL. In addition, the integers 0 to 255 can be used as color keys for terminals with 256 color support.You can also change the colors for the help and shell prompts and input and answer text by setting the appropriate field of repl in the customize_colors function above (respectively, help_color, shell_color, input_color, and answer_color). For the latter two, be sure that the envcolors field is also set to false.It is also possible to apply boldface formatting by using Base.text_colors[:bold] as a color. For instance, to print answers in boldface font, one can use the following as a .juliarc.jl:function customize_colors(repl)\n repl.envcolors = false\n repl.answer_color = Base.text_colors[:bold]\nend\n\natreplinit(customize_colors)You can also customize the color used to render warning and informational messages by setting the appropriate environment variables. For instance, to render error, warning, and informational messages respectively in magenta, yellow, and cyan you can add the following to your .juliarc.jl file:ENV[\"JULIA_ERROR_COLOR\"] = :magenta\nENV[\"JULIA_WARN_COLOR\"] = :yellow\nENV[\"JULIA_INFO_COLOR\"] = :cyan" -}, - -{ - "location": "manual/running-external-programs.html#", - "page": "Running External Programs", - "title": "Running External Programs", - "category": "page", - "text": "" -}, - -{ - "location": "manual/running-external-programs.html#Running-External-Programs-1", - "page": "Running External Programs", - "title": "Running External Programs", - "category": "section", - "text": "Julia borrows backtick notation for commands from the shell, Perl, and Ruby. However, in Julia, writingjulia> `echo hello`\n`echo hello`differs in several aspects from the behavior in various shells, Perl, or Ruby:Instead of immediately running the command, backticks create a Cmd object to represent the command. You can use this object to connect the command to others via pipes, run it, and read or write to it.\nWhen the command is run, Julia does not capture its output unless you specifically arrange for it to. Instead, the output of the command by default goes to STDOUT as it would using libc\'s system call.\nThe command is never run with a shell. Instead, Julia parses the command syntax directly, appropriately interpolating variables and splitting on words as the shell would, respecting shell quoting syntax. The command is run as julia\'s immediate child process, using fork and exec calls.Here\'s a simple example of running an external program:julia> mycommand = `echo hello`\n`echo hello`\n\njulia> typeof(mycommand)\nCmd\n\njulia> run(mycommand)\nhelloThe hello is the output of the echo command, sent to STDOUT. The run method itself returns nothing, and throws an ErrorException if the external command fails to run successfully.If you want to read the output of the external command, readstring() can be used instead:julia> a = readstring(`echo hello`)\n\"hello\\n\"\n\njulia> chomp(a) == \"hello\"\ntrueMore generally, you can use open() to read from or write to an external command.julia> open(`less`, \"w\", STDOUT) do io\n for i = 1:3\n println(io, i)\n end\n end\n1\n2\n3" -}, - -{ - "location": "manual/running-external-programs.html#command-interpolation-1", - "page": "Running External Programs", - "title": "Interpolation", - "category": "section", - "text": "Suppose you want to do something a bit more complicated and use the name of a file in the variable file as an argument to a command. You can use $ for interpolation much as you would in a string literal (see Strings):julia> file = \"/etc/passwd\"\n\"/etc/passwd\"\n\njulia> `sort $file`\n`sort /etc/passwd`A common pitfall when running external programs via a shell is that if a file name contains characters that are special to the shell, they may cause undesirable behavior. Suppose, for example, rather than /etc/passwd, we wanted to sort the contents of the file /Volumes/External HD/data.csv. Let\'s try it:julia> file = \"/Volumes/External HD/data.csv\"\n\"/Volumes/External HD/data.csv\"\n\njulia> `sort $file`\n`sort \'/Volumes/External HD/data.csv\'`How did the file name get quoted? Julia knows that file is meant to be interpolated as a single argument, so it quotes the word for you. Actually, that is not quite accurate: the value of file is never interpreted by a shell, so there\'s no need for actual quoting; the quotes are inserted only for presentation to the user. This will even work if you interpolate a value as part of a shell word:julia> path = \"/Volumes/External HD\"\n\"/Volumes/External HD\"\n\njulia> name = \"data\"\n\"data\"\n\njulia> ext = \"csv\"\n\"csv\"\n\njulia> `sort $path/$name.$ext`\n`sort \'/Volumes/External HD/data.csv\'`As you can see, the space in the path variable is appropriately escaped. But what if you want to interpolate multiple words? In that case, just use an array (or any other iterable container):julia> files = [\"/etc/passwd\",\"/Volumes/External HD/data.csv\"]\n2-element Array{String,1}:\n \"/etc/passwd\"\n \"/Volumes/External HD/data.csv\"\n\njulia> `grep foo $files`\n`grep foo /etc/passwd \'/Volumes/External HD/data.csv\'`If you interpolate an array as part of a shell word, Julia emulates the shell\'s {a,b,c} argument generation:julia> names = [\"foo\",\"bar\",\"baz\"]\n3-element Array{String,1}:\n \"foo\"\n \"bar\"\n \"baz\"\n\njulia> `grep xylophone $names.txt`\n`grep xylophone foo.txt bar.txt baz.txt`Moreover, if you interpolate multiple arrays into the same word, the shell\'s Cartesian product generation behavior is emulated:julia> names = [\"foo\",\"bar\",\"baz\"]\n3-element Array{String,1}:\n \"foo\"\n \"bar\"\n \"baz\"\n\njulia> exts = [\"aux\",\"log\"]\n2-element Array{String,1}:\n \"aux\"\n \"log\"\n\njulia> `rm -f $names.$exts`\n`rm -f foo.aux foo.log bar.aux bar.log baz.aux baz.log`Since you can interpolate literal arrays, you can use this generative functionality without needing to create temporary array objects first:julia> `rm -rf $[\"foo\",\"bar\",\"baz\",\"qux\"].$[\"aux\",\"log\",\"pdf\"]`\n`rm -rf foo.aux foo.log foo.pdf bar.aux bar.log bar.pdf baz.aux baz.log baz.pdf qux.aux qux.log qux.pdf`" -}, - -{ - "location": "manual/running-external-programs.html#Quoting-1", - "page": "Running External Programs", - "title": "Quoting", - "category": "section", - "text": "Inevitably, one wants to write commands that aren\'t quite so simple, and it becomes necessary to use quotes. Here\'s a simple example of a Perl one-liner at a shell prompt:sh$ perl -le \'$|=1; for (0..3) { print }\'\n0\n1\n2\n3The Perl expression needs to be in single quotes for two reasons: so that spaces don\'t break the expression into multiple shell words, and so that uses of Perl variables like $| (yes, that\'s the name of a variable in Perl), don\'t cause interpolation. In other instances, you may want to use double quotes so that interpolation does occur:sh$ first=\"A\"\nsh$ second=\"B\"\nsh$ perl -le \'$|=1; print for @ARGV\' \"1: $first\" \"2: $second\"\n1: A\n2: BIn general, the Julia backtick syntax is carefully designed so that you can just cut-and-paste shell commands as is into backticks and they will work: the escaping, quoting, and interpolation behaviors are the same as the shell\'s. The only difference is that the interpolation is integrated and aware of Julia\'s notion of what is a single string value, and what is a container for multiple values. Let\'s try the above two examples in Julia:julia> A = `perl -le \'$|=1; for (0..3) { print }\'`\n`perl -le \'$|=1; for (0..3) { print }\'`\n\njulia> run(A)\n0\n1\n2\n3\n\njulia> first = \"A\"; second = \"B\";\n\njulia> B = `perl -le \'print for @ARGV\' \"1: $first\" \"2: $second\"`\n`perl -le \'print for @ARGV\' \'1: A\' \'2: B\'`\n\njulia> run(B)\n1: A\n2: BThe results are identical, and Julia\'s interpolation behavior mimics the shell\'s with some improvements due to the fact that Julia supports first-class iterable objects while most shells use strings split on spaces for this, which introduces ambiguities. When trying to port shell commands to Julia, try cut and pasting first. Since Julia shows commands to you before running them, you can easily and safely just examine its interpretation without doing any damage." -}, - -{ - "location": "manual/running-external-programs.html#Pipelines-1", - "page": "Running External Programs", - "title": "Pipelines", - "category": "section", - "text": "Shell metacharacters, such as |, &, and >, need to be quoted (or escaped) inside of Julia\'s backticks:julia> run(`echo hello \'|\' sort`)\nhello | sort\n\njulia> run(`echo hello \\| sort`)\nhello | sortThis expression invokes the echo command with three words as arguments: hello, |, and sort. The result is that a single line is printed: hello | sort. How, then, does one construct a pipeline? Instead of using \'|\' inside of backticks, one uses pipeline():julia> run(pipeline(`echo hello`, `sort`))\nhelloThis pipes the output of the echo command to the sort command. Of course, this isn\'t terribly interesting since there\'s only one line to sort, but we can certainly do much more interesting things:julia> run(pipeline(`cut -d: -f3 /etc/passwd`, `sort -n`, `tail -n5`))\n210\n211\n212\n213\n214This prints the highest five user IDs on a UNIX system. The cut, sort and tail commands are all spawned as immediate children of the current julia process, with no intervening shell process. Julia itself does the work to setup pipes and connect file descriptors that is normally done by the shell. Since Julia does this itself, it retains better control and can do some things that shells cannot.Julia can run multiple commands in parallel:julia> run(`echo hello` & `echo world`)\nworld\nhelloThe order of the output here is non-deterministic because the two echo processes are started nearly simultaneously, and race to make the first write to the STDOUT descriptor they share with each other and the julia parent process. Julia lets you pipe the output from both of these processes to another program:julia> run(pipeline(`echo world` & `echo hello`, `sort`))\nhello\nworldIn terms of UNIX plumbing, what\'s happening here is that a single UNIX pipe object is created and written to by both echo processes, and the other end of the pipe is read from by the sort command.IO redirection can be accomplished by passing keyword arguments stdin, stdout, and stderr to the pipeline function:pipeline(`do_work`, stdout=pipeline(`sort`, \"out.txt\"), stderr=\"errs.txt\")" -}, - -{ - "location": "manual/running-external-programs.html#Avoiding-Deadlock-in-Pipelines-1", - "page": "Running External Programs", - "title": "Avoiding Deadlock in Pipelines", - "category": "section", - "text": "When reading and writing to both ends of a pipeline from a single process, it is important to avoid forcing the kernel to buffer all of the data.For example, when reading all of the output from a command, call readstring(out), not wait(process), since the former will actively consume all of the data written by the process, whereas the latter will attempt to store the data in the kernel\'s buffers while waiting for a reader to be connected.Another common solution is to separate the reader and writer of the pipeline into separate Tasks:writer = @async writeall(process, \"data\")\nreader = @async do_compute(readstring(process))\nwait(process)\nfetch(reader)" -}, - -{ - "location": "manual/running-external-programs.html#Complex-Example-1", - "page": "Running External Programs", - "title": "Complex Example", - "category": "section", - "text": "The combination of a high-level programming language, a first-class command abstraction, and automatic setup of pipes between processes is a powerful one. To give some sense of the complex pipelines that can be created easily, here are some more sophisticated examples, with apologies for the excessive use of Perl one-liners:julia> prefixer(prefix, sleep) = `perl -nle \'$|=1; print \"\'$prefix\' \", $_; sleep \'$sleep\';\'`;\n\njulia> run(pipeline(`perl -le \'$|=1; for(0..9){ print; sleep 1 }\'`, prefixer(\"A\",2) & prefixer(\"B\",2)))\nA 0\nB 1\nA 2\nB 3\nA 4\nB 5\nA 6\nB 7\nA 8\nB 9This is a classic example of a single producer feeding two concurrent consumers: one perl process generates lines with the numbers 0 through 9 on them, while two parallel processes consume that output, one prefixing lines with the letter \"A\", the other with the letter \"B\". Which consumer gets the first line is non-deterministic, but once that race has been won, the lines are consumed alternately by one process and then the other. (Setting $|=1 in Perl causes each print statement to flush the STDOUT handle, which is necessary for this example to work. Otherwise all the output is buffered and printed to the pipe at once, to be read by just one consumer process.)Here is an even more complex multi-stage producer-consumer example:julia> run(pipeline(`perl -le \'$|=1; for(0..9){ print; sleep 1 }\'`,\n prefixer(\"X\",3) & prefixer(\"Y\",3) & prefixer(\"Z\",3),\n prefixer(\"A\",2) & prefixer(\"B\",2)))\nA X 0\nB Y 1\nA Z 2\nB X 3\nA Y 4\nB Z 5\nA X 6\nB Y 7\nA Z 8\nB X 9This example is similar to the previous one, except there are two stages of consumers, and the stages have different latency so they use a different number of parallel workers, to maintain saturated throughput.We strongly encourage you to try all these examples to see how they work." -}, - -{ - "location": "manual/calling-c-and-fortran-code.html#", - "page": "Calling C and Fortran Code", - "title": "Calling C and Fortran Code", - "category": "page", - "text": "" -}, - -{ - "location": "manual/calling-c-and-fortran-code.html#Calling-C-and-Fortran-Code-1", - "page": "Calling C and Fortran Code", - "title": "Calling C and Fortran Code", - "category": "section", - "text": "Though most code can be written in Julia, there are many high-quality, mature libraries for numerical computing already written in C and Fortran. To allow easy use of this existing code, Julia makes it simple and efficient to call C and Fortran functions. Julia has a \"no boilerplate\" philosophy: functions can be called directly from Julia without any \"glue\" code, code generation, or compilation – even from the interactive prompt. This is accomplished just by making an appropriate call with ccall syntax, which looks like an ordinary function call.The code to be called must be available as a shared library. Most C and Fortran libraries ship compiled as shared libraries already, but if you are compiling the code yourself using GCC (or Clang), you will need to use the -shared and -fPIC options. The machine instructions generated by Julia\'s JIT are the same as a native C call would be, so the resulting overhead is the same as calling a library function from C code. (Non-library function calls in both C and Julia can be inlined and thus may have even less overhead than calls to shared library functions. When both libraries and executables are generated by LLVM, it is possible to perform whole-program optimizations that can even optimize across this boundary, but Julia does not yet support that. In the future, however, it may do so, yielding even greater performance gains.)Shared libraries and functions are referenced by a tuple of the form (:function, \"library\") or (\"function\", \"library\") where function is the C-exported function name. library refers to the shared library name: shared libraries available in the (platform-specific) load path will be resolved by name, and if necessary a direct path may be specified.A function name may be used alone in place of the tuple (just :function or \"function\"). In this case the name is resolved within the current process. This form can be used to call C library functions, functions in the Julia runtime, or functions in an application linked to Julia.By default, Fortran compilers generate mangled names (for example, converting function names to lowercase or uppercase, often appending an underscore), and so to call a Fortran function via ccall you must pass the mangled identifier corresponding to the rule followed by your Fortran compiler. Also, when calling a Fortran function, all inputs must be passed by reference.Finally, you can use ccall to actually generate a call to the library function. Arguments to ccall are as follows:A (:function, \"library\") pair, which must be written as a literal constant,\nOR\na function pointer (for example, from dlsym).\nReturn type (see below for mapping the declared C type to Julia)\nThis argument will be evaluated at compile-time, when the containing method is defined.\nA tuple of input types. The input types must be written as a literal tuple, not a tuple-valued variable or expression.\nThis argument will be evaluated at compile-time, when the containing method is defined.\nThe following arguments, if any, are the actual argument values passed to the function.As a complete but simple example, the following calls the clock function from the standard C library:julia> t = ccall((:clock, \"libc\"), Int32, ())\n2292761\n\njulia> t\n2292761\n\njulia> typeof(ans)\nInt32clock takes no arguments and returns an Int32. One common gotcha is that a 1-tuple must be written with a trailing comma. For example, to call the getenv function to get a pointer to the value of an environment variable, one makes a call like this:julia> path = ccall((:getenv, \"libc\"), Cstring, (Cstring,), \"SHELL\")\nCstring(@0x00007fff5fbffc45)\n\njulia> unsafe_string(path)\n\"/bin/bash\"Note that the argument type tuple must be written as (Cstring,), rather than (Cstring). This is because (Cstring) is just the expression Cstring surrounded by parentheses, rather than a 1-tuple containing Cstring:julia> (Cstring)\nCstring\n\njulia> (Cstring,)\n(Cstring,)In practice, especially when providing reusable functionality, one generally wraps ccall uses in Julia functions that set up arguments and then check for errors in whatever manner the C or Fortran function indicates them, propagating to the Julia caller as exceptions. This is especially important since C and Fortran APIs are notoriously inconsistent about how they indicate error conditions. For example, the getenv C library function is wrapped in the following Julia function, which is a simplified version of the actual definition from env.jl:function getenv(var::AbstractString)\n val = ccall((:getenv, \"libc\"),\n Cstring, (Cstring,), var)\n if val == C_NULL\n error(\"getenv: undefined variable: \", var)\n end\n unsafe_string(val)\nendThe C getenv function indicates an error by returning NULL, but other standard C functions indicate errors in various different ways, including by returning -1, 0, 1 and other special values. This wrapper throws an exception clearly indicating the problem if the caller tries to get a non-existent environment variable:julia> getenv(\"SHELL\")\n\"/bin/bash\"\n\njulia> getenv(\"FOOBAR\")\ngetenv: undefined variable: FOOBARHere is a slightly more complex example that discovers the local machine\'s hostname:function gethostname()\n hostname = Vector{UInt8}(128)\n ccall((:gethostname, \"libc\"), Int32,\n (Ptr{UInt8}, Csize_t),\n hostname, sizeof(hostname))\n hostname[end] = 0; # ensure null-termination\n return unsafe_string(pointer(hostname))\nendThis example first allocates an array of bytes, then calls the C library function gethostname to fill the array in with the hostname, takes a pointer to the hostname buffer, and converts the pointer to a Julia string, assuming that it is a NUL-terminated C string. It is common for C libraries to use this pattern of requiring the caller to allocate memory to be passed to the callee and filled in. Allocation of memory from Julia like this is generally accomplished by creating an uninitialized array and passing a pointer to its data to the C function. This is why we don\'t use the Cstring type here: as the array is uninitialized, it could contain NUL bytes. Converting to a Cstring as part of the ccall checks for contained NUL bytes and could therefore throw a conversion error." -}, - -{ - "location": "manual/calling-c-and-fortran-code.html#Creating-C-Compatible-Julia-Function-Pointers-1", - "page": "Calling C and Fortran Code", - "title": "Creating C-Compatible Julia Function Pointers", - "category": "section", - "text": "It is possible to pass Julia functions to native C functions that accept function pointer arguments. For example, to match C prototypes of the form:typedef returntype (*functiontype)(argumenttype,...)The function cfunction() generates the C-compatible function pointer for a call to a Julia library function. Arguments to cfunction() are as follows:A Julia Function\nReturn type\nA tuple of input typesA classic example is the standard C library qsort function, declared as:void qsort(void *base, size_t nmemb, size_t size,\n int(*compare)(const void *a, const void *b));The base argument is a pointer to an array of length nmemb, with elements of size bytes each. compare is a callback function which takes pointers to two elements a and b and returns an integer less/greater than zero if a should appear before/after b (or zero if any order is permitted). Now, suppose that we have a 1d array A of values in Julia that we want to sort using the qsort function (rather than Julia\'s built-in sort function). Before we worry about calling qsort and passing arguments, we need to write a comparison function that works for some arbitrary type T:julia> function mycompare(a::T, b::T) where T\n return convert(Cint, a < b ? -1 : a > b ? +1 : 0)::Cint\n end\nmycompare (generic function with 1 method)Notice that we have to be careful about the return type: qsort expects a function returning a C int, so we must be sure to return Cint via a call to convert and a typeassert.In order to pass this function to C, we obtain its address using the function cfunction:julia> const mycompare_c = cfunction(mycompare, Cint, (Ref{Cdouble}, Ref{Cdouble}));cfunction() accepts three arguments: the Julia function (mycompare), the return type (Cint), and a tuple of the argument types, in this case to sort an array of Cdouble (Float64) elements.The final call to qsort looks like this:julia> A = [1.3, -2.7, 4.4, 3.1]\n4-element Array{Float64,1}:\n 1.3\n -2.7\n 4.4\n 3.1\n\njulia> ccall(:qsort, Void, (Ptr{Cdouble}, Csize_t, Csize_t, Ptr{Void}),\n A, length(A), sizeof(eltype(A)), mycompare_c)\n\njulia> A\n4-element Array{Float64,1}:\n -2.7\n 1.3\n 3.1\n 4.4As can be seen, A is changed to the sorted array [-2.7, 1.3, 3.1, 4.4]. Note that Julia knows how to convert an array into a Ptr{Cdouble}, how to compute the size of a type in bytes (identical to C\'s sizeof operator), and so on. For fun, try inserting a println(\"mycompare($a,$b)\") line into mycompare, which will allow you to see the comparisons that qsort is performing (and to verify that it is really calling the Julia function that you passed to it)." -}, - -{ - "location": "manual/calling-c-and-fortran-code.html#Mapping-C-Types-to-Julia-1", - "page": "Calling C and Fortran Code", - "title": "Mapping C Types to Julia", - "category": "section", - "text": "It is critical to exactly match the declared C type with its declaration in Julia. Inconsistencies can cause code that works correctly on one system to fail or produce indeterminate results on a different system.Note that no C header files are used anywhere in the process of calling C functions: you are responsible for making sure that your Julia types and call signatures accurately reflect those in the C header file. (The Clang package can be used to auto-generate Julia code from a C header file.)" -}, - -{ - "location": "manual/calling-c-and-fortran-code.html#Auto-conversion:-1", - "page": "Calling C and Fortran Code", - "title": "Auto-conversion:", - "category": "section", - "text": "Julia automatically inserts calls to the Base.cconvert() function to convert each argument to the specified type. For example, the following call:ccall((:foo, \"libfoo\"), Void, (Int32, Float64), x, y)will behave as if the following were written:ccall((:foo, \"libfoo\"), Void, (Int32, Float64),\n Base.unsafe_convert(Int32, Base.cconvert(Int32, x)),\n Base.unsafe_convert(Float64, Base.cconvert(Float64, y)))Base.cconvert() normally just calls convert(), but can be defined to return an arbitrary new object more appropriate for passing to C. For example, this is used to convert an Array of objects (e.g. strings) to an array of pointers.Base.unsafe_convert() handles conversion to Ptr types. It is considered unsafe because converting an object to a native pointer can hide the object from the garbage collector, causing it to be freed prematurely." -}, - -{ - "location": "manual/calling-c-and-fortran-code.html#Type-Correspondences:-1", - "page": "Calling C and Fortran Code", - "title": "Type Correspondences:", - "category": "section", - "text": "First, a review of some relevant Julia type terminology:Syntax / Keyword Example Description\nmutable struct String \"Leaf Type\" :: A group of related data that includes a type-tag, is managed by the Julia GC, and is defined by object-identity. The type parameters of a leaf type must be fully defined (no TypeVars are allowed) in order for the instance to be constructed.\nabstract type Any, AbstractArray{T, N}, Complex{T} \"Super Type\" :: A super-type (not a leaf-type) that cannot be instantiated, but can be used to describe a group of types.\nT{A} Vector{Int} \"Type Parameter\" :: A specialization of a type (typically used for dispatch or storage optimization).\n \"TypeVar\" :: The T in the type parameter declaration is referred to as a TypeVar (short for type variable).\nprimitive type Int, Float64 \"Primitive Type\" :: A type with no fields, but a size. It is stored and defined by-value.\nstruct Pair{Int, Int} \"Struct\" :: A type with all fields defined to be constant. It is defined by-value, and may be stored with a type-tag.\n Complex128 (isbits) \"Is-Bits\" :: A primitive type, or a struct type where all fields are other isbits types. It is defined by-value, and is stored without a type-tag.\nstruct ...; end nothing \"Singleton\" :: a Leaf Type or Struct with no fields.\n(...) or tuple(...) (1, 2, 3) \"Tuple\" :: an immutable data-structure similar to an anonymous struct type, or a constant array. Represented as either an array or a struct." -}, - -{ - "location": "manual/calling-c-and-fortran-code.html#Bits-Types:-1", - "page": "Calling C and Fortran Code", - "title": "Bits Types:", - "category": "section", - "text": "There are several special types to be aware of, as no other type can be defined to behave the same:Float32\nExactly corresponds to the float type in C (or REAL*4 in Fortran).\nFloat64\nExactly corresponds to the double type in C (or REAL*8 in Fortran).\nComplex64\nExactly corresponds to the complex float type in C (or COMPLEX*8 in Fortran).\nComplex128\nExactly corresponds to the complex double type in C (or COMPLEX*16 in Fortran).\nSigned\nExactly corresponds to the signed type annotation in C (or any INTEGER type in Fortran). Any Julia type that is not a subtype of Signed is assumed to be unsigned.Ref{T}\nBehaves like a Ptr{T} that can manage its memory via the Julia GC.Array{T,N}\nWhen an array is passed to C as a Ptr{T} argument, it is not reinterpret-cast: Julia requires that the element type of the array matches T, and the address of the first element is passed.\nTherefore, if an Array contains data in the wrong format, it will have to be explicitly converted using a call such as trunc(Int32, a).\nTo pass an array A as a pointer of a different type without converting the data beforehand (for example, to pass a Float64 array to a function that operates on uninterpreted bytes), you can declare the argument as Ptr{Void}.\nIf an array of eltype Ptr{T} is passed as a Ptr{Ptr{T}} argument, Base.cconvert() will attempt to first make a null-terminated copy of the array with each element replaced by its Base.cconvert() version. This allows, for example, passing an argv pointer array of type Vector{String} to an argument of type Ptr{Ptr{Cchar}}.On all systems we currently support, basic C/C++ value types may be translated to Julia types as follows. Every C type also has a corresponding Julia type with the same name, prefixed by C. This can help for writing portable code (and remembering that an int in C is not the same as an Int in Julia).System Independent:C name Fortran name Standard Julia Alias Julia Base Type\nunsigned char CHARACTER Cuchar UInt8\nbool (only in C++) Cuchar UInt8\nshort INTEGER*2, LOGICAL*2 Cshort Int16\nunsigned short   Cushort UInt16\nint, BOOL (C, typical) INTEGER*4, LOGICAL*4 Cint Int32\nunsigned int   Cuint UInt32\nlong long INTEGER*8, LOGICAL*8 Clonglong Int64\nunsigned long long   Culonglong UInt64\nintmax_t   Cintmax_t Int64\nuintmax_t   Cuintmax_t UInt64\nfloat REAL*4i Cfloat Float32\ndouble REAL*8 Cdouble Float64\ncomplex float COMPLEX*8 Complex64 Complex{Float32}\ncomplex double COMPLEX*16 Complex128 Complex{Float64}\nptrdiff_t   Cptrdiff_t Int\nssize_t   Cssize_t Int\nsize_t   Csize_t UInt\nvoid     Void\nvoid and [[noreturn]] or _Noreturn     Union{}\nvoid*     Ptr{Void}\nT* (where T represents an appropriately defined type)     Ref{T}\nchar* (or char[], e.g. a string) CHARACTER*N   Cstring if NUL-terminated, or Ptr{UInt8} if not\nchar** (or *char[])     Ptr{Ptr{UInt8}}\njl_value_t* (any Julia Type)     Any\njl_value_t** (a reference to a Julia Type)     Ref{Any}\nva_arg     Not supported\n... (variadic function specification)     T... (where T is one of the above types, variadic functions of different argument types are not supported)The Cstring type is essentially a synonym for Ptr{UInt8}, except the conversion to Cstring throws an error if the Julia string contains any embedded NUL characters (which would cause the string to be silently truncated if the C routine treats NUL as the terminator). If you are passing a char* to a C routine that does not assume NUL termination (e.g. because you pass an explicit string length), or if you know for certain that your Julia string does not contain NUL and want to skip the check, you can use Ptr{UInt8} as the argument type. Cstring can also be used as the ccall return type, but in that case it obviously does not introduce any extra checks and is only meant to improve readability of the call.System-dependent:C name Standard Julia Alias Julia Base Type\nchar Cchar Int8 (x86, x86_64), UInt8 (powerpc, arm)\nlong Clong Int (UNIX), Int32 (Windows)\nunsigned long Culong UInt (UNIX), UInt32 (Windows)\nwchar_t Cwchar_t Int32 (UNIX), UInt16 (Windows)note: Note\nWhen calling a Fortran function, all inputs must be passed by reference, so all type correspondences above should contain an additional Ptr{..} or Ref{..} wrapper around their type specification.warning: Warning\nFor string arguments (char*) the Julia type should be Cstring (if NUL- terminated data is expected) or either Ptr{Cchar} or Ptr{UInt8} otherwise (these two pointer types have the same effect), as described above, not String. Similarly, for array arguments (T[] or T*), the Julia type should again be Ptr{T}, not Vector{T}.warning: Warning\nJulia\'s Char type is 32 bits, which is not the same as the wide character type (wchar_t or wint_t) on all platforms.warning: Warning\nA return type of Union{} means the function will not return i.e. C++11 [[noreturn]] or C11 _Noreturn (e.g. jl_throw or longjmp). Do not use this for functions that return no value (void) but do return, use Void instead.note: Note\nFor wchar_t* arguments, the Julia type should be Cwstring (if the C routine expects a NUL-terminated string) or Ptr{Cwchar_t} otherwise. Note also that UTF-8 string data in Julia is internally NUL-terminated, so it can be passed to C functions expecting NUL-terminated data without making a copy (but using the Cwstring type will cause an error to be thrown if the string itself contains NUL characters).note: Note\nC functions that take an argument of the type char** can be called by using a Ptr{Ptr{UInt8}} type within Julia. For example, C functions of the form:int main(int argc, char **argv);can be called via the following Julia code:argv = [ \"a.out\", \"arg1\", \"arg2\" ]\nccall(:main, Int32, (Int32, Ptr{Ptr{UInt8}}), length(argv), argv)note: Note\nA C function declared to return Void will return the value nothing in Julia." -}, - -{ - "location": "manual/calling-c-and-fortran-code.html#Struct-Type-correspondences-1", - "page": "Calling C and Fortran Code", - "title": "Struct Type correspondences", - "category": "section", - "text": "Composite types, aka struct in C or TYPE in Fortran90 (or STRUCTURE / RECORD in some variants of F77), can be mirrored in Julia by creating a struct definition with the same field layout.When used recursively, isbits types are stored inline. All other types are stored as a pointer to the data. When mirroring a struct used by-value inside another struct in C, it is imperative that you do not attempt to manually copy the fields over, as this will not preserve the correct field alignment. Instead, declare an isbits struct type and use that instead. Unnamed structs are not possible in the translation to Julia.Packed structs and union declarations are not supported by Julia.You can get a near approximation of a union if you know, a priori, the field that will have the greatest size (potentially including padding). When translating your fields to Julia, declare the Julia field to be only of that type.Arrays of parameters can be expressed with NTuple:in C:\nstruct B {\n int A[3];\n};\nb_a_2 = B.A[2];\n\nin Julia:\nstruct B\n A::NTuple{3, CInt}\nend\nb_a_2 = B.A[3] # note the difference in indexing (1-based in Julia, 0-based in C)Arrays of unknown size (C99-compliant variable length structs specified by [] or [0]) are not directly supported. Often the best way to deal with these is to deal with the byte offsets directly. For example, if a C library declared a proper string type and returned a pointer to it:struct String {\n int strlen;\n char data[];\n};In Julia, we can access the parts independently to make a copy of that string:str = from_c::Ptr{Void}\nlen = unsafe_load(Ptr{Cint}(str))\nunsafe_string(str + Core.sizeof(Cint), len)" -}, - -{ - "location": "manual/calling-c-and-fortran-code.html#Type-Parameters-1", - "page": "Calling C and Fortran Code", - "title": "Type Parameters", - "category": "section", - "text": "The type arguments to ccall are evaluated statically, when the method containing the ccall is defined. They therefore must take the form of a literal tuple, not a variable, and cannot reference local variables.This may sound like a strange restriction, but remember that since C is not a dynamic language like Julia, its functions can only accept argument types with a statically-known, fixed signature.However, while the type layout must be known statically to compute the ccall ABI, the static parameters of the function are considered to be part of this static environment. The static parameters of the function may be used as type parameters in the ccall signature, as long as they don\'t affect the layout of the type. For example, f(x::T) where {T} = ccall(:valid, Ptr{T}, (Ptr{T},), x) is valid, since Ptr is always a word-size primitive type. But, g(x::T) where {T} = ccall(:notvalid, T, (T,), x) is not valid, since the type layout of T is not known statically." -}, - -{ - "location": "manual/calling-c-and-fortran-code.html#SIMD-Values-1", - "page": "Calling C and Fortran Code", - "title": "SIMD Values", - "category": "section", - "text": "Note: This feature is currently implemented on 64-bit x86 and AArch64 platforms only.If a C/C++ routine has an argument or return value that is a native SIMD type, the corresponding Julia type is a homogeneous tuple of VecElement that naturally maps to the SIMD type. Specifically:The tuple must be the same size as the SIMD type. For example, a tuple representing an __m128 on x86 must have a size of 16 bytes.\nThe element type of the tuple must be an instance of VecElement{T} where T is a primitive type that is 1, 2, 4 or 8 bytes.For instance, consider this C routine that uses AVX intrinsics:#include \n\n__m256 dist( __m256 a, __m256 b ) {\n return _mm256_sqrt_ps(_mm256_add_ps(_mm256_mul_ps(a, a),\n _mm256_mul_ps(b, b)));\n}The following Julia code calls dist using ccall:const m256 = NTuple{8, VecElement{Float32}}\n\na = m256(ntuple(i -> VecElement(sin(Float32(i))), 8))\nb = m256(ntuple(i -> VecElement(cos(Float32(i))), 8))\n\nfunction call_dist(a::m256, b::m256)\n ccall((:dist, \"libdist\"), m256, (m256, m256), a, b)\nend\n\nprintln(call_dist(a,b))The host machine must have the requisite SIMD registers. For example, the code above will not work on hosts without AVX support." -}, - -{ - "location": "manual/calling-c-and-fortran-code.html#Memory-Ownership-1", - "page": "Calling C and Fortran Code", - "title": "Memory Ownership", - "category": "section", - "text": "malloc/freeMemory allocation and deallocation of such objects must be handled by calls to the appropriate cleanup routines in the libraries being used, just like in any C program. Do not try to free an object received from a C library with Libc.free in Julia, as this may result in the free function being called via the wrong libc library and cause Julia to crash. The reverse (passing an object allocated in Julia to be freed by an external library) is equally invalid." -}, - -{ - "location": "manual/calling-c-and-fortran-code.html#When-to-use-T,-Ptr{T}-and-Ref{T}-1", - "page": "Calling C and Fortran Code", - "title": "When to use T, Ptr{T} and Ref{T}", - "category": "section", - "text": "In Julia code wrapping calls to external C routines, ordinary (non-pointer) data should be declared to be of type T inside the ccall, as they are passed by value. For C code accepting pointers, Ref{T} should generally be used for the types of input arguments, allowing the use of pointers to memory managed by either Julia or C through the implicit call to Base.cconvert(). In contrast, pointers returned by the C function called should be declared to be of output type Ptr{T}, reflecting that the memory pointed to is managed by C only. Pointers contained in C structs should be represented as fields of type Ptr{T} within the corresponding Julia struct types designed to mimic the internal structure of corresponding C structs.In Julia code wrapping calls to external Fortran routines, all input arguments should be declared as of type Ref{T}, as Fortran passes all variables by reference. The return type should either be Void for Fortran subroutines, or a T for Fortran functions returning the type T." -}, - -{ - "location": "manual/calling-c-and-fortran-code.html#Mapping-C-Functions-to-Julia-1", - "page": "Calling C and Fortran Code", - "title": "Mapping C Functions to Julia", - "category": "section", - "text": "" -}, - -{ - "location": "manual/calling-c-and-fortran-code.html#ccall/cfunction-argument-translation-guide-1", - "page": "Calling C and Fortran Code", - "title": "ccall/cfunction argument translation guide", - "category": "section", - "text": "For translating a C argument list to Julia:T, where T is one of the primitive types: char, int, long, short, float, double, complex, enum or any of their typedef equivalents\nT, where T is an equivalent Julia Bits Type (per the table above)\nif T is an enum, the argument type should be equivalent to Cint or Cuint\nargument value will be copied (passed by value)\nstruct T (including typedef to a struct)\nT, where T is a Julia leaf type\nargument value will be copied (passed by value)\nvoid*\ndepends on how this parameter is used, first translate this to the intended pointer type, then determine the Julia equivalent using the remaining rules in this list\nthis argument may be declared as Ptr{Void}, if it really is just an unknown pointer\njl_value_t*\nAny\nargument value must be a valid Julia object\ncurrently unsupported by cfunction()\njl_value_t**\nRef{Any}\nargument value must be a valid Julia object (or C_NULL)\ncurrently unsupported by cfunction()\nT*\nRef{T}, where T is the Julia type corresponding to T\nargument value will be copied if it is an isbits type otherwise, the value must be a valid Julia object\n(T*)(...) (e.g. a pointer to a function)\nPtr{Void} (you may need to use cfunction() explicitly to create this pointer)\n... (e.g. a vararg)\nT..., where T is the Julia type\nva_arg\nnot supported" -}, - -{ - "location": "manual/calling-c-and-fortran-code.html#ccall/cfunction-return-type-translation-guide-1", - "page": "Calling C and Fortran Code", - "title": "ccall/cfunction return type translation guide", - "category": "section", - "text": "For translating a C return type to Julia:void\nVoid (this will return the singleton instance nothing::Void)\nT, where T is one of the primitive types: char, int, long, short, float, double, complex, enum or any of their typedef equivalents\nT, where T is an equivalent Julia Bits Type (per the table above)\nif T is an enum, the argument type should be equivalent to Cint or Cuint\nargument value will be copied (returned by-value)\nstruct T (including typedef to a struct)\nT, where T is a Julia Leaf Type\nargument value will be copied (returned by-value)\nvoid*\ndepends on how this parameter is used, first translate this to the intended pointer type, then determine the Julia equivalent using the remaining rules in this list\nthis argument may be declared as Ptr{Void}, if it really is just an unknown pointer\njl_value_t*\nAny\nargument value must be a valid Julia object\njl_value_t**\nRef{Any}\nargument value must be a valid Julia object (or C_NULL)\nT*\nIf the memory is already owned by Julia, or is an isbits type, and is known to be non-null:\nRef{T}, where T is the Julia type corresponding to T\na return type of Ref{Any} is invalid, it should either be Any (corresponding to jl_value_t*) or Ptr{Any} (corresponding to Ptr{Any})\nC MUST NOT modify the memory returned via Ref{T} if T is an isbits type\nIf the memory is owned by C:\nPtr{T}, where T is the Julia type corresponding to T\n(T*)(...) (e.g. a pointer to a function)\nPtr{Void} (you may need to use cfunction() explicitly to create this pointer)" -}, - -{ - "location": "manual/calling-c-and-fortran-code.html#Passing-Pointers-for-Modifying-Inputs-1", - "page": "Calling C and Fortran Code", - "title": "Passing Pointers for Modifying Inputs", - "category": "section", - "text": "Because C doesn\'t support multiple return values, often C functions will take pointers to data that the function will modify. To accomplish this within a ccall, you need to first encapsulate the value inside an Ref{T} of the appropriate type. When you pass this Ref object as an argument, Julia will automatically pass a C pointer to the encapsulated data:width = Ref{Cint}(0)\nrange = Ref{Cfloat}(0)\nccall(:foo, Void, (Ref{Cint}, Ref{Cfloat}), width, range)Upon return, the contents of width and range can be retrieved (if they were changed by foo) by width[] and range[]; that is, they act like zero-dimensional arrays." -}, - -{ - "location": "manual/calling-c-and-fortran-code.html#Special-Reference-Syntax-for-ccall-(deprecated):-1", - "page": "Calling C and Fortran Code", - "title": "Special Reference Syntax for ccall (deprecated):", - "category": "section", - "text": "The & syntax is deprecated, use the Ref{T} argument type instead.A prefix & is used on an argument to ccall to indicate that a pointer to a scalar argument should be passed instead of the scalar value itself (required for all Fortran function arguments, as noted above). The following example computes a dot product using a BLAS function.function compute_dot(DX::Vector{Float64}, DY::Vector{Float64})\n @assert length(DX) == length(DY)\n n = length(DX)\n incx = incy = 1\n product = ccall((:ddot_, \"libLAPACK\"),\n Float64,\n (Ptr{Int32}, Ptr{Float64}, Ptr{Int32}, Ptr{Float64}, Ptr{Int32}),\n &n, DX, &incx, DY, &incy)\n return product\nendThe meaning of prefix & is not quite the same as in C. In particular, any changes to the referenced variables will not be visible in Julia unless the type is mutable (declared via type). However, even for immutable structs it will not cause any harm for called functions to attempt such modifications (that is, writing through the passed pointers). Moreover, & may be used with any expression, such as &0 or &f(x).When a scalar value is passed with & as an argument of type Ptr{T}, the value will first be converted to type T." -}, - -{ - "location": "manual/calling-c-and-fortran-code.html#Some-Examples-of-C-Wrappers-1", - "page": "Calling C and Fortran Code", - "title": "Some Examples of C Wrappers", - "category": "section", - "text": "Here is a simple example of a C wrapper that returns a Ptr type:mutable struct gsl_permutation\nend\n\n# The corresponding C signature is\n# gsl_permutation * gsl_permutation_alloc (size_t n);\nfunction permutation_alloc(n::Integer)\n output_ptr = ccall(\n (:gsl_permutation_alloc, :libgsl), # name of C function and library\n Ptr{gsl_permutation}, # output type\n (Csize_t,), # tuple of input types\n n # name of Julia variable to pass in\n )\n if output_ptr == C_NULL # Could not allocate memory\n throw(OutOfMemoryError())\n end\n return output_ptr\nendThe GNU Scientific Library (here assumed to be accessible through :libgsl) defines an opaque pointer, gsl_permutation *, as the return type of the C function gsl_permutation_alloc(). As user code never has to look inside the gsl_permutation struct, the corresponding Julia wrapper simply needs a new type declaration, gsl_permutation, that has no internal fields and whose sole purpose is to be placed in the type parameter of a Ptr type. The return type of the ccall is declared as Ptr{gsl_permutation}, since the memory allocated and pointed to by output_ptr is controlled by C (and not Julia).The input n is passed by value, and so the function\'s input signature is simply declared as (Csize_t,) without any Ref or Ptr necessary. (If the wrapper was calling a Fortran function instead, the corresponding function input signature should instead be (Ref{Csize_t},), since Fortran variables are passed by reference.) Furthermore, n can be any type that is convertable to a Csize_t integer; the ccall implicitly calls Base.cconvert(Csize_t, n).Here is a second example wrapping the corresponding destructor:# The corresponding C signature is\n# void gsl_permutation_free (gsl_permutation * p);\nfunction permutation_free(p::Ref{gsl_permutation})\n ccall(\n (:gsl_permutation_free, :libgsl), # name of C function and library\n Void, # output type\n (Ref{gsl_permutation},), # tuple of input types\n p # name of Julia variable to pass in\n )\nendHere, the input p is declared to be of type Ref{gsl_permutation}, meaning that the memory that p points to may be managed by Julia or by C. A pointer to memory allocated by C should be of type Ptr{gsl_permutation}, but it is convertable using Base.cconvert() and therefore can be used in the same (covariant) context of the input argument to a ccall. A pointer to memory allocated by Julia must be of type Ref{gsl_permutation}, to ensure that the memory address pointed to is valid and that Julia\'s garbage collector manages the chunk of memory pointed to correctly. Therefore, the Ref{gsl_permutation} declaration allows pointers managed by C or Julia to be used.If the C wrapper never expects the user to pass pointers to memory managed by Julia, then using p::Ptr{gsl_permutation} for the method signature of the wrapper and similarly in the ccall is also acceptable.Here is a third example passing Julia arrays:# The corresponding C signature is\n# int gsl_sf_bessel_Jn_array (int nmin, int nmax, double x,\n# double result_array[])\nfunction sf_bessel_Jn_array(nmin::Integer, nmax::Integer, x::Real)\n if nmax < nmin\n throw(DomainError())\n end\n result_array = Vector{Cdouble}(nmax - nmin + 1)\n errorcode = ccall(\n (:gsl_sf_bessel_Jn_array, :libgsl), # name of C function and library\n Cint, # output type\n (Cint, Cint, Cdouble, Ref{Cdouble}),# tuple of input types\n nmin, nmax, x, result_array # names of Julia variables to pass in\n )\n if errorcode != 0\n error(\"GSL error code $errorcode\")\n end\n return result_array\nendThe C function wrapped returns an integer error code; the results of the actual evaluation of the Bessel J function populate the Julia array result_array. This variable can only be used with corresponding input type declaration Ref{Cdouble}, since its memory is allocated and managed by Julia, not C. The implicit call to Base.cconvert(Ref{Cdouble}, result_array) unpacks the Julia pointer to a Julia array data structure into a form understandable by C.Note that for this code to work correctly, result_array must be declared to be of type Ref{Cdouble} and not Ptr{Cdouble}. The memory is managed by Julia and the Ref signature alerts Julia\'s garbage collector to keep managing the memory for result_array while the ccall executes. If Ptr{Cdouble} were used instead, the ccall may still work, but Julia\'s garbage collector would not be aware that the memory declared for result_array is being used by the external C function. As a result, the code may produce a memory leak if result_array never gets freed by the garbage collector, or if the garbage collector prematurely frees result_array, the C function may end up throwing an invalid memory access exception." -}, - -{ - "location": "manual/calling-c-and-fortran-code.html#Garbage-Collection-Safety-1", - "page": "Calling C and Fortran Code", - "title": "Garbage Collection Safety", - "category": "section", - "text": "When passing data to a ccall, it is best to avoid using the pointer() function. Instead define a convert method and pass the variables directly to the ccall. ccall automatically arranges that all of its arguments will be preserved from garbage collection until the call returns. If a C API will store a reference to memory allocated by Julia, after the ccall returns, you must arrange that the object remains visible to the garbage collector. The suggested way to handle this is to make a global variable of type Array{Ref,1} to hold these values, until the C library notifies you that it is finished with them.Whenever you have created a pointer to Julia data, you must ensure the original data exists until you are done with using the pointer. Many methods in Julia such as unsafe_load() and String() make copies of data instead of taking ownership of the buffer, so that it is safe to free (or alter) the original data without affecting Julia. A notable exception is unsafe_wrap() which, for performance reasons, shares (or can be told to take ownership of) the underlying buffer.The garbage collector does not guarantee any order of finalization. That is, if a contained a reference to b and both a and b are due for garbage collection, there is no guarantee that b would be finalized after a. If proper finalization of a depends on b being valid, it must be handled in other ways." -}, - -{ - "location": "manual/calling-c-and-fortran-code.html#Non-constant-Function-Specifications-1", - "page": "Calling C and Fortran Code", - "title": "Non-constant Function Specifications", - "category": "section", - "text": "A (name, library) function specification must be a constant expression. However, it is possible to use computed values as function names by staging through eval as follows:@eval ccall(($(string(\"a\", \"b\")), \"lib\"), ...This expression constructs a name using string, then substitutes this name into a new ccall expression, which is then evaluated. Keep in mind that eval only operates at the top level, so within this expression local variables will not be available (unless their values are substituted with $). For this reason, eval is typically only used to form top-level definitions, for example when wrapping libraries that contain many similar functions.If your usage is more dynamic, use indirect calls as described in the next section." -}, - -{ - "location": "manual/calling-c-and-fortran-code.html#Indirect-Calls-1", - "page": "Calling C and Fortran Code", - "title": "Indirect Calls", - "category": "section", - "text": "The first argument to ccall can also be an expression evaluated at run time. In this case, the expression must evaluate to a Ptr, which will be used as the address of the native function to call. This behavior occurs when the first ccall argument contains references to non-constants, such as local variables, function arguments, or non-constant globals.For example, you might look up the function via dlsym, then cache it in a global variable for that session. For example:macro dlsym(func, lib)\n z, zlocal = gensym(string(func)), gensym()\n eval(current_module(), :(global $z = C_NULL))\n z = esc(z)\n quote\n let $zlocal::Ptr{Void} = $z::Ptr{Void}\n if $zlocal == C_NULL\n $zlocal = dlsym($(esc(lib))::Ptr{Void}, $(esc(func)))\n global $z = $zlocal\n end\n $zlocal\n end\n end\nend\n\nmylibvar = Libdl.dlopen(\"mylib\")\nccall(@dlsym(\"myfunc\", mylibvar), Void, ())" -}, - -{ - "location": "manual/calling-c-and-fortran-code.html#Calling-Convention-1", - "page": "Calling C and Fortran Code", - "title": "Calling Convention", - "category": "section", - "text": "The second argument to ccall can optionally be a calling convention specifier (immediately preceding return type). Without any specifier, the platform-default C calling convention is used. Other supported conventions are: stdcall, cdecl, fastcall, and thiscall. For example (from base/libc.jl) we see the same gethostnameccall as above, but with the correct signature for Windows:hn = Vector{UInt8}(256)\nerr = ccall(:gethostname, stdcall, Int32, (Ptr{UInt8}, UInt32), hn, length(hn))For more information, please see the LLVM Language Reference.There is one additional special calling convention llvmcall, which allows inserting calls to LLVM intrinsics directly. This can be especially useful when targeting unusual platforms such as GPGPUs. For example, for CUDA, we need to be able to read the thread index:ccall(\"llvm.nvvm.read.ptx.sreg.tid.x\", llvmcall, Int32, ())As with any ccall, it is essential to get the argument signature exactly correct. Also, note that there is no compatibility layer that ensures the intrinsic makes sense and works on the current target, unlike the equivalent Julia functions exposed by Core.Intrinsics." -}, - -{ - "location": "manual/calling-c-and-fortran-code.html#Accessing-Global-Variables-1", - "page": "Calling C and Fortran Code", - "title": "Accessing Global Variables", - "category": "section", - "text": "Global variables exported by native libraries can be accessed by name using the cglobal() function. The arguments to cglobal() are a symbol specification identical to that used by ccall, and a type describing the value stored in the variable:julia> cglobal((:errno, :libc), Int32)\nPtr{Int32} @0x00007f418d0816b8The result is a pointer giving the address of the value. The value can be manipulated through this pointer using unsafe_load() and unsafe_store!()." -}, - -{ - "location": "manual/calling-c-and-fortran-code.html#Accessing-Data-through-a-Pointer-1", - "page": "Calling C and Fortran Code", - "title": "Accessing Data through a Pointer", - "category": "section", - "text": "The following methods are described as \"unsafe\" because a bad pointer or type declaration can cause Julia to terminate abruptly.Given a Ptr{T}, the contents of type T can generally be copied from the referenced memory into a Julia object using unsafe_load(ptr, [index]). The index argument is optional (default is 1), and follows the Julia-convention of 1-based indexing. This function is intentionally similar to the behavior of getindex() and setindex!() (e.g. [] access syntax).The return value will be a new object initialized to contain a copy of the contents of the referenced memory. The referenced memory can safely be freed or released.If T is Any, then the memory is assumed to contain a reference to a Julia object (a jl_value_t*), the result will be a reference to this object, and the object will not be copied. You must be careful in this case to ensure that the object was always visible to the garbage collector (pointers do not count, but the new reference does) to ensure the memory is not prematurely freed. Note that if the object was not originally allocated by Julia, the new object will never be finalized by Julia\'s garbage collector. If the Ptr itself is actually a jl_value_t*, it can be converted back to a Julia object reference by unsafe_pointer_to_objref(ptr). (Julia values v can be converted to jl_value_t* pointers, as Ptr{Void}, by calling pointer_from_objref(v).)The reverse operation (writing data to a Ptr{T}), can be performed using unsafe_store!(ptr, value, [index]). Currently, this is only supported for primitive types or other pointer-free (isbits) immutable struct types.Any operation that throws an error is probably currently unimplemented and should be posted as a bug so that it can be resolved.If the pointer of interest is a plain-data array (primitive type or immutable struct), the function unsafe_wrap(Array, ptr,dims,[own]) may be more useful. The final parameter should be true if Julia should \"take ownership\" of the underlying buffer and call free(ptr) when the returned Array object is finalized. If the own parameter is omitted or false, the caller must ensure the buffer remains in existence until all access is complete.Arithmetic on the Ptr type in Julia (e.g. using +) does not behave the same as C\'s pointer arithmetic. Adding an integer to a Ptr in Julia always moves the pointer by some number of bytes, not elements. This way, the address values obtained from pointer arithmetic do not depend on the element types of pointers." -}, - -{ - "location": "manual/calling-c-and-fortran-code.html#Thread-safety-1", - "page": "Calling C and Fortran Code", - "title": "Thread-safety", - "category": "section", - "text": "Some C libraries execute their callbacks from a different thread, and since Julia isn\'t thread-safe you\'ll need to take some extra precautions. In particular, you\'ll need to set up a two-layered system: the C callback should only schedule (via Julia\'s event loop) the execution of your \"real\" callback. To do this, create a AsyncCondition object and wait on it:cond = Base.AsyncCondition()\nwait(cond)The callback you pass to C should only execute a ccall to :uv_async_send, passing cond.handle as the argument, taking care to avoid any allocations or other interactions with the Julia runtime.Note that events may be coalesced, so multiple calls to uv_async_send may result in a single wakeup notification to the condition." -}, - -{ - "location": "manual/calling-c-and-fortran-code.html#More-About-Callbacks-1", - "page": "Calling C and Fortran Code", - "title": "More About Callbacks", - "category": "section", - "text": "For more details on how to pass callbacks to C libraries, see this blog post." -}, - -{ - "location": "manual/calling-c-and-fortran-code.html#C-1", - "page": "Calling C and Fortran Code", - "title": "C++", - "category": "section", - "text": "For direct C++ interfacing, see the Cxx package. For tools to create C++ bindings, see the CxxWrap package." -}, - -{ - "location": "manual/handling-operating-system-variation.html#", - "page": "Handling Operating System Variation", - "title": "Handling Operating System Variation", - "category": "page", - "text": "" -}, - -{ - "location": "manual/handling-operating-system-variation.html#Handling-Operating-System-Variation-1", - "page": "Handling Operating System Variation", - "title": "Handling Operating System Variation", - "category": "section", - "text": "When dealing with platform libraries, it is often necessary to provide special cases for various platforms. The variable Sys.KERNEL can be used to write these special cases. There are several functions intended to make this easier: is_unix, is_linux, is_apple, is_bsd, and is_windows. These may be used as follows:if is_windows()\n some_complicated_thing(a)\nendNote that is_linux and is_apple are mutually exclusive subsets of is_unix. Additionally, there is a macro @static which makes it possible to use these functions to conditionally hide invalid code, as demonstrated in the following examples.Simple blocks:ccall( (@static is_windows() ? :_fopen : :fopen), ...)Complex blocks:@static if is_linux()\n some_complicated_thing(a)\nelse\n some_different_thing(a)\nendWhen chaining conditionals (including if/elseif/end), the @static must be repeated for each level (parentheses optional, but recommended for readability):@static is_windows() ? :a : (@static is_apple() ? :b : :c)" -}, - -{ - "location": "manual/environment-variables.html#", - "page": "Environment Variables", - "title": "Environment Variables", - "category": "page", - "text": "" -}, - -{ - "location": "manual/environment-variables.html#Environment-Variables-1", - "page": "Environment Variables", - "title": "Environment Variables", - "category": "section", - "text": "Julia may be configured with a number of environment variables, either in the usual way of the operating system, or in a portable way from within Julia. Suppose you want to set the environment variable JULIA_EDITOR to vim, then either type ENV[\"JULIA_EDITOR\"] = \"vim\" for instance in the REPL to make this change on a case by case basis, or add the same to the user configuration file .juliarc.jl in the user\'s home directory to have a permanent effect. The current value of the same environment variable is determined by evaluating ENV[\"JULIA_EDITOR\"].The environment variables that Julia uses generally start with JULIA. If Base.versioninfo is called with verbose equal to true, then the output will list defined environment variables relevant for Julia, including those for which JULIA appears in the name." -}, - -{ - "location": "manual/environment-variables.html#File-locations-1", - "page": "Environment Variables", - "title": "File locations", - "category": "section", - "text": "" -}, - -{ - "location": "manual/environment-variables.html#JULIA_HOME-1", - "page": "Environment Variables", - "title": "JULIA_HOME", - "category": "section", - "text": "The absolute path of the directory containing the Julia executable, which sets the global variable Base.JULIA_HOME. If $JULIA_HOME is not set, then Julia determines the value Base.JULIA_HOME at run-time.The executable itself is one of$JULIA_HOME/julia\n$JULIA_HOME/julia-debugby default.The global variable Base.DATAROOTDIR determines a relative path from Base.JULIA_HOME to the data directory associated with Julia. Then the path$JULIA_HOME/$DATAROOTDIR/julia/basedetermines the directory in which Julia initially searches for source files (via Base.find_source_file()).Likewise, the global variable Base.SYSCONFDIR determines a relative path to the configuration file directory. Then Julia searches for a juliarc.jl file at$JULIA_HOME/$SYSCONFDIR/julia/juliarc.jl\n$JULIA_HOME/../etc/julia/juliarc.jlby default (via Base.load_juliarc()).For example, a Linux installation with a Julia executable located at /bin/julia, a DATAROOTDIR of ../share, and a SYSCONFDIR of ../etc will have JULIA_HOME set to /bin, a source-file search path of/share/julia/baseand a global configuration search path of/etc/julia/juliarc.jl" -}, - -{ - "location": "manual/environment-variables.html#JULIA_LOAD_PATH-1", - "page": "Environment Variables", - "title": "JULIA_LOAD_PATH", - "category": "section", - "text": "A separated list of absolute paths that are to be appended to the variable LOAD_PATH. (In Unix-like systems, the path separator is :; in Windows systems, the path separator is ;.) The LOAD_PATH variable is where Base.require and Base.load_in_path() look for code; it defaults to the absolute paths$JULIA_HOME/../local/share/julia/site/v$(VERSION.major).$(VERSION.minor)\n$JULIA_HOME/../share/julia/site/v$(VERSION.major).$(VERSION.minor)so that, e.g., version 0.6 of Julia on a Linux system with a Julia executable at /bin/julia will have a default LOAD_PATH of/local/share/julia/site/v0.6\n/share/julia/site/v0.6" -}, - -{ - "location": "manual/environment-variables.html#JULIA_PKGDIR-1", - "page": "Environment Variables", - "title": "JULIA_PKGDIR", - "category": "section", - "text": "The path of the parent directory Pkg.Dir._pkgroot() for the version-specific Julia package repositories. If the path is relative, then it is taken with respect to the working directory. If $JULIA_PKGDIR is not set, then Pkg.Dir._pkgroot() defaults to$HOME/.juliaThen the repository location Pkg.dir for a given Julia version is$JULIA_PKGDIR/v$(VERSION.major).$(VERSION.minor)For example, for a Linux user whose home directory is /home/alice, the directory containing the package repositories would by default be/home/alice/.juliaand the package repository for version 0.6 of Julia would be/home/alice/.julia/v0.6" -}, - -{ - "location": "manual/environment-variables.html#JULIA_HISTORY-1", - "page": "Environment Variables", - "title": "JULIA_HISTORY", - "category": "section", - "text": "The absolute path Base.REPL.find_hist_file() of the REPL\'s history file. If $JULIA_HISTORY is not set, then Base.REPL.find_hist_file() defaults to$HOME/.julia_history" -}, - -{ - "location": "manual/environment-variables.html#JULIA_PKGRESOLVE_ACCURACY-1", - "page": "Environment Variables", - "title": "JULIA_PKGRESOLVE_ACCURACY", - "category": "section", - "text": "A positive Int that determines how much time the max-sum subroutine MaxSum.maxsum() of the package dependency resolver Base.Pkg.resolve will devote to attempting satisfying constraints before giving up: this value is by default 1, and larger values correspond to larger amounts of time.Suppose the value of $JULIA_PKGRESOLVE_ACCURACY is n. Thenthe number of pre-decimation iterations is 20*n,\nthe number of iterations between decimation steps is 10*n, and\nat decimation steps, at most one in every 20*n packages is decimated." -}, - -{ - "location": "manual/environment-variables.html#External-applications-1", - "page": "Environment Variables", - "title": "External applications", - "category": "section", - "text": "" -}, - -{ - "location": "manual/environment-variables.html#JULIA_SHELL-1", - "page": "Environment Variables", - "title": "JULIA_SHELL", - "category": "section", - "text": "The absolute path of the shell with which Julia should execute external commands (via Base.repl_cmd()). Defaults to the environment variable $SHELL, and falls back to /bin/sh if $SHELL is unset.note: Note\nOn Windows, this environment variable is ignored, and external commands are executed directly." -}, - -{ - "location": "manual/environment-variables.html#JULIA_EDITOR-1", - "page": "Environment Variables", - "title": "JULIA_EDITOR", - "category": "section", - "text": "The editor returned by Base.editor() and used in, e.g., Base.edit, referring to the command of the preferred editor, for instance vim.$JULIA_EDITOR takes precedence over $VISUAL, which in turn takes precedence over $EDITOR. If none of these environment variables is set, then the editor is taken to be open on Windows and OS X, or /etc/alternatives/editor if it exists, or emacs otherwise.note: Note\n$JULIA_EDITOR is not used in the determination of the editor for Base.Pkg.edit: this function checks $VISUAL and $EDITOR alone." -}, - -{ - "location": "manual/environment-variables.html#Parallelization-1", - "page": "Environment Variables", - "title": "Parallelization", - "category": "section", - "text": "" -}, - -{ - "location": "manual/environment-variables.html#JULIA_CPU_CORES-1", - "page": "Environment Variables", - "title": "JULIA_CPU_CORES", - "category": "section", - "text": "Overrides the global variable Base.Sys.CPU_CORES, the number of logical CPU cores available." -}, - -{ - "location": "manual/environment-variables.html#JULIA_WORKER_TIMEOUT-1", - "page": "Environment Variables", - "title": "JULIA_WORKER_TIMEOUT", - "category": "section", - "text": "A Float64 that sets the value of Base.worker_timeout() (default: 60.0). This function gives the number of seconds a worker process will wait for a master process to establish a connection before dying." -}, - -{ - "location": "manual/environment-variables.html#JULIA_NUM_THREADS-1", - "page": "Environment Variables", - "title": "JULIA_NUM_THREADS", - "category": "section", - "text": "An unsigned 64-bit integer (uint64_t) that sets the maximum number of threads available to Julia. If $JULIA_NUM_THREADS exceeds the number of available physical CPU cores, then the number of threads is set to the number of cores. If $JULIA_NUM_THREADS is not positive or is not set, or if the number of CPU cores cannot be determined through system calls, then the number of threads is set to 1." -}, - -{ - "location": "manual/environment-variables.html#JULIA_THREAD_SLEEP_THRESHOLD-1", - "page": "Environment Variables", - "title": "JULIA_THREAD_SLEEP_THRESHOLD", - "category": "section", - "text": "If set to a string that starts with the case-insensitive substring \"infinite\", then spinning threads never sleep. Otherwise, $JULIA_THREAD_SLEEP_THRESHOLD is interpreted as an unsigned 64-bit integer (uint64_t) and gives, in nanoseconds, the amount of time after which spinning threads should sleep." -}, - -{ - "location": "manual/environment-variables.html#JULIA_EXCLUSIVE-1", - "page": "Environment Variables", - "title": "JULIA_EXCLUSIVE", - "category": "section", - "text": "If set to anything besides 0, then Julia\'s thread policy is consistent with running on a dedicated machine: the master thread is on proc 0, and threads are affinitized. Otherwise, Julia lets the operating system handle thread policy." -}, - -{ - "location": "manual/environment-variables.html#REPL-formatting-1", - "page": "Environment Variables", - "title": "REPL formatting", - "category": "section", - "text": "Environment variables that determine how REPL output should be formatted at the terminal. Generally, these variables should be set to ANSI terminal escape sequences. Julia provides a high-level interface with much of the same functionality: see the section on Interacting With Julia." -}, - -{ - "location": "manual/environment-variables.html#JULIA_ERROR_COLOR-1", - "page": "Environment Variables", - "title": "JULIA_ERROR_COLOR", - "category": "section", - "text": "The formatting Base.error_color() (default: light red, \"\\033[91m\") that errors should have at the terminal." -}, - -{ - "location": "manual/environment-variables.html#JULIA_WARN_COLOR-1", - "page": "Environment Variables", - "title": "JULIA_WARN_COLOR", - "category": "section", - "text": "The formatting Base.warn_color() (default: yellow, \"\\033[93m\") that warnings should have at the terminal." -}, - -{ - "location": "manual/environment-variables.html#JULIA_INFO_COLOR-1", - "page": "Environment Variables", - "title": "JULIA_INFO_COLOR", - "category": "section", - "text": "The formatting Base.info_color() (default: cyan, \"\\033[36m\") that info should have at the terminal." -}, - -{ - "location": "manual/environment-variables.html#JULIA_INPUT_COLOR-1", - "page": "Environment Variables", - "title": "JULIA_INPUT_COLOR", - "category": "section", - "text": "The formatting Base.input_color() (default: normal, \"\\033[0m\") that input should have at the terminal." -}, - -{ - "location": "manual/environment-variables.html#JULIA_ANSWER_COLOR-1", - "page": "Environment Variables", - "title": "JULIA_ANSWER_COLOR", - "category": "section", - "text": "The formatting Base.answer_color() (default: normal, \"\\033[0m\") that output should have at the terminal." -}, - -{ - "location": "manual/environment-variables.html#JULIA_STACKFRAME_LINEINFO_COLOR-1", - "page": "Environment Variables", - "title": "JULIA_STACKFRAME_LINEINFO_COLOR", - "category": "section", - "text": "The formatting Base.stackframe_lineinfo_color() (default: bold, \"\\033[1m\") that line info should have during a stack trace at the terminal." -}, - -{ - "location": "manual/environment-variables.html#JULIA_STACKFRAME_FUNCTION_COLOR-1", - "page": "Environment Variables", - "title": "JULIA_STACKFRAME_FUNCTION_COLOR", - "category": "section", - "text": "The formatting Base.stackframe_function_color() (default: bold, \"\\033[1m\") that function calls should have during a stack trace at the terminal." -}, - -{ - "location": "manual/environment-variables.html#Debugging-and-profiling-1", - "page": "Environment Variables", - "title": "Debugging and profiling", - "category": "section", - "text": "" -}, - -{ - "location": "manual/environment-variables.html#JULIA_GC_ALLOC_POOL,-JULIA_GC_ALLOC_OTHER,-JULIA_GC_ALLOC_PRINT-1", - "page": "Environment Variables", - "title": "JULIA_GC_ALLOC_POOL, JULIA_GC_ALLOC_OTHER, JULIA_GC_ALLOC_PRINT", - "category": "section", - "text": "If set, these environment variables take strings that optionally start with the character \'r\', followed by a string interpolation of a colon-separated list of three signed 64-bit integers (int64_t). This triple of integers a:b:c represents the arithmetic sequence a, a + b, a + 2*b, ... c.If it\'s the nth time that jl_gc_pool_alloc() has been called, and n belongs to the arithmetic sequence represented by $JULIA_GC_ALLOC_POOL, then garbage collection is forced.\nIf it\'s the nth time that maybe_collect() has been called, and n belongs to the arithmetic sequence represented by $JULIA_GC_ALLOC_OTHER, then garbage collection is forced.\nIf it\'s the nth time that jl_gc_collect() has been called, and n belongs to the arithmetic sequence represented by $JULIA_GC_ALLOC_PRINT, then counts for the number of calls to jl_gc_pool_alloc() and maybe_collect() are printed.If the value of the environment variable begins with the character \'r\', then the interval between garbage collection events is randomized.note: Note\nThese environment variables only have an effect if Julia was compiled with garbage-collection debugging (that is, if WITH_GC_DEBUG_ENV is set to 1 in the build configuration)." -}, - -{ - "location": "manual/environment-variables.html#JULIA_GC_NO_GENERATIONAL-1", - "page": "Environment Variables", - "title": "JULIA_GC_NO_GENERATIONAL", - "category": "section", - "text": "If set to anything besides 0, then the Julia garbage collector never performs \"quick sweeps\" of memory.note: Note\nThis environment variable only has an effect if Julia was compiled with garbage-collection debugging (that is, if WITH_GC_DEBUG_ENV is set to 1 in the build configuration)." -}, - -{ - "location": "manual/environment-variables.html#JULIA_GC_WAIT_FOR_DEBUGGER-1", - "page": "Environment Variables", - "title": "JULIA_GC_WAIT_FOR_DEBUGGER", - "category": "section", - "text": "If set to anything besides 0, then the Julia garbage collector will wait for a debugger to attach instead of aborting whenever there\'s a critical error.note: Note\nThis environment variable only has an effect if Julia was compiled with garbage-collection debugging (that is, if WITH_GC_DEBUG_ENV is set to 1 in the build configuration)." -}, - -{ - "location": "manual/environment-variables.html#ENABLE_JITPROFILING-1", - "page": "Environment Variables", - "title": "ENABLE_JITPROFILING", - "category": "section", - "text": "If set to anything besides 0, then the compiler will create and register an event listener for just-in-time (JIT) profiling.note: Note\nThis environment variable only has an effect if Julia was compiled with JIT profiling support, using eitherIntel\'s VTune™ Amplifier (USE_INTEL_JITEVENTS set to 1 in the build configuration), or\nOProfile (USE_OPROFILE_JITEVENTS set to 1 in the build configuration)." -}, - -{ - "location": "manual/environment-variables.html#JULIA_LLVM_ARGS-1", - "page": "Environment Variables", - "title": "JULIA_LLVM_ARGS", - "category": "section", - "text": "Arguments to be passed to the LLVM backend.note: Note\nThis environment variable has an effect only if Julia was compiled with JL_DEBUG_BUILD set — in particular, the julia-debug executable is always compiled with this build variable." -}, - -{ - "location": "manual/environment-variables.html#JULIA_DEBUG_LOADING-1", - "page": "Environment Variables", - "title": "JULIA_DEBUG_LOADING", - "category": "section", - "text": "If set, then Julia prints detailed information about the cache in the loading process of Base.require." -}, - -{ - "location": "manual/embedding.html#", - "page": "Embedding Julia", - "title": "Embedding Julia", - "category": "page", - "text": "" -}, - -{ - "location": "manual/embedding.html#Embedding-Julia-1", - "page": "Embedding Julia", - "title": "Embedding Julia", - "category": "section", - "text": "As we have seen in Calling C and Fortran Code, Julia has a simple and efficient way to call functions written in C. But there are situations where the opposite is needed: calling Julia function from C code. This can be used to integrate Julia code into a larger C/C++ project, without the need to rewrite everything in C/C++. Julia has a C API to make this possible. As almost all programming languages have some way to call C functions, the Julia C API can also be used to build further language bridges (e.g. calling Julia from Python or C#)." -}, - -{ - "location": "manual/embedding.html#High-Level-Embedding-1", - "page": "Embedding Julia", - "title": "High-Level Embedding", - "category": "section", - "text": "We start with a simple C program that initializes Julia and calls some Julia code:#include \n\nint main(int argc, char *argv[])\n{\n /* required: setup the Julia context */\n jl_init();\n\n /* run Julia commands */\n jl_eval_string(\"print(sqrt(2.0))\");\n\n /* strongly recommended: notify Julia that the\n program is about to terminate. this allows\n Julia time to cleanup pending write requests\n and run all finalizers\n */\n jl_atexit_hook(0);\n return 0;\n}In order to build this program you have to put the path to the Julia header into the include path and link against libjulia. For instance, when Julia is installed to $JULIA_DIR, one can compile the above test program test.c with gcc using:gcc -o test -fPIC -I$JULIA_DIR/include/julia -L$JULIA_DIR/lib test.c -ljulia $JULIA_DIR/lib/julia/libstdc++.so.6Then if the environment variable JULIA_HOME is set to $JULIA_DIR/bin, the output test program can be executed.Alternatively, look at the embedding.c program in the Julia source tree in the examples/ folder. The file ui/repl.c program is another simple example of how to set jl_options options while linking against libjulia.The first thing that has to be done before calling any other Julia C function is to initialize Julia. This is done by calling jl_init, which tries to automatically determine Julia\'s install location. If you need to specify a custom location, or specify which system image to load, use jl_init_with_image instead.The second statement in the test program evaluates a Julia statement using a call to jl_eval_string.Before the program terminates, it is strongly recommended to call jl_atexit_hook. The above example program calls this before returning from main.note: Note\nCurrently, dynamically linking with the libjulia shared library requires passing the RTLD_GLOBAL option. In Python, this looks like:>>> julia=CDLL(\'./libjulia.dylib\',RTLD_GLOBAL)\n>>> julia.jl_init.argtypes = []\n>>> julia.jl_init()\n250593296note: Note\nIf the julia program needs to access symbols from the main executable, it may be necessary to add -Wl,--export-dynamic linker flag at compile time on Linux in addition to the ones generated by julia-config.jl described below. This is not necessary when compiling a shared library." -}, - -{ - "location": "manual/embedding.html#Using-julia-config-to-automatically-determine-build-parameters-1", - "page": "Embedding Julia", - "title": "Using julia-config to automatically determine build parameters", - "category": "section", - "text": "The script julia-config.jl was created to aid in determining what build parameters are required by a program that uses embedded Julia. This script uses the build parameters and system configuration of the particular Julia distribution it is invoked by to export the necessary compiler flags for an embedding program to interact with that distribution. This script is located in the Julia shared data directory." -}, - -{ - "location": "manual/embedding.html#Example-1", - "page": "Embedding Julia", - "title": "Example", - "category": "section", - "text": "#include \n\nint main(int argc, char *argv[])\n{\n jl_init();\n (void)jl_eval_string(\"println(sqrt(2.0))\");\n jl_atexit_hook(0);\n return 0;\n}" -}, - -{ - "location": "manual/embedding.html#On-the-command-line-1", - "page": "Embedding Julia", - "title": "On the command line", - "category": "section", - "text": "A simple use of this script is from the command line. Assuming that julia-config.jl is located in /usr/local/julia/share/julia, it can be invoked on the command line directly and takes any combination of 3 flags:/usr/local/julia/share/julia/julia-config.jl\nUsage: julia-config [--cflags|--ldflags|--ldlibs]If the above example source is saved in the file embed_example.c, then the following command will compile it into a running program on Linux and Windows (MSYS2 environment), or if on OS/X, then substitute clang for gcc.:/usr/local/julia/share/julia/julia-config.jl --cflags --ldflags --ldlibs | xargs gcc embed_example.c" -}, - -{ - "location": "manual/embedding.html#Use-in-Makefiles-1", - "page": "Embedding Julia", - "title": "Use in Makefiles", - "category": "section", - "text": "But in general, embedding projects will be more complicated than the above, and so the following allows general makefile support as well – assuming GNU make because of the use of the shell macro expansions. Additionally, though many times julia-config.jl may be found in the directory /usr/local, this is not necessarily the case, but Julia can be used to locate julia-config.jl too, and the makefile can be used to take advantage of that. The above example is extended to use a Makefile:JL_SHARE = $(shell julia -e \'print(joinpath(JULIA_HOME,Base.DATAROOTDIR,\"julia\"))\')\nCFLAGS += $(shell $(JL_SHARE)/julia-config.jl --cflags)\nCXXFLAGS += $(shell $(JL_SHARE)/julia-config.jl --cflags)\nLDFLAGS += $(shell $(JL_SHARE)/julia-config.jl --ldflags)\nLDLIBS += $(shell $(JL_SHARE)/julia-config.jl --ldlibs)\n\nall: embed_exampleNow the build command is simply make." -}, - -{ - "location": "manual/embedding.html#Converting-Types-1", - "page": "Embedding Julia", - "title": "Converting Types", - "category": "section", - "text": "Real applications will not just need to execute expressions, but also return their values to the host program. jl_eval_string returns a jl_value_t*, which is a pointer to a heap-allocated Julia object. Storing simple data types like Float64 in this way is called boxing, and extracting the stored primitive data is called unboxing. Our improved sample program that calculates the square root of 2 in Julia and reads back the result in C looks as follows:jl_value_t *ret = jl_eval_string(\"sqrt(2.0)\");\n\nif (jl_typeis(ret, jl_float64_type)) {\n double ret_unboxed = jl_unbox_float64(ret);\n printf(\"sqrt(2.0) in C: %e \\n\", ret_unboxed);\n}\nelse {\n printf(\"ERROR: unexpected return type from sqrt(::Float64)\\n\");\n}In order to check whether ret is of a specific Julia type, we can use the jl_isa, jl_typeis, or jl_is_... functions. By typing typeof(sqrt(2.0)) into the Julia shell we can see that the return type is Float64 (double in C). To convert the boxed Julia value into a C double the jl_unbox_float64 function is used in the above code snippet.Corresponding jl_box_... functions are used to convert the other way:jl_value_t *a = jl_box_float64(3.0);\njl_value_t *b = jl_box_float32(3.0f);\njl_value_t *c = jl_box_int32(3);As we will see next, boxing is required to call Julia functions with specific arguments." -}, - -{ - "location": "manual/embedding.html#Calling-Julia-Functions-1", - "page": "Embedding Julia", - "title": "Calling Julia Functions", - "category": "section", - "text": "While jl_eval_string allows C to obtain the result of a Julia expression, it does not allow passing arguments computed in C to Julia. For this you will need to invoke Julia functions directly, using jl_call:jl_function_t *func = jl_get_function(jl_base_module, \"sqrt\");\njl_value_t *argument = jl_box_float64(2.0);\njl_value_t *ret = jl_call1(func, argument);In the first step, a handle to the Julia function sqrt is retrieved by calling jl_get_function. The first argument passed to jl_get_function is a pointer to the Base module in which sqrt is defined. Then, the double value is boxed using jl_box_float64. Finally, in the last step, the function is called using jl_call1. jl_call0, jl_call2, and jl_call3 functions also exist, to conveniently handle different numbers of arguments. To pass more arguments, use jl_call:jl_value_t *jl_call(jl_function_t *f, jl_value_t **args, int32_t nargs)Its second argument args is an array of jl_value_t* arguments and nargs is the number of arguments." -}, - -{ - "location": "manual/embedding.html#Memory-Management-1", - "page": "Embedding Julia", - "title": "Memory Management", - "category": "section", - "text": "As we have seen, Julia objects are represented in C as pointers. This raises the question of who is responsible for freeing these objects.Typically, Julia objects are freed by a garbage collector (GC), but the GC does not automatically know that we are holding a reference to a Julia value from C. This means the GC can free objects out from under you, rendering pointers invalid.The GC can only run when Julia objects are allocated. Calls like jl_box_float64 perform allocation, and allocation might also happen at any point in running Julia code. However, it is generally safe to use pointers in between jl_... calls. But in order to make sure that values can survive jl_... calls, we have to tell Julia that we hold a reference to a Julia value. This can be done using the JL_GC_PUSH macros:jl_value_t *ret = jl_eval_string(\"sqrt(2.0)\");\nJL_GC_PUSH1(&ret);\n// Do something with ret\nJL_GC_POP();The JL_GC_POP call releases the references established by the previous JL_GC_PUSH. Note that JL_GC_PUSH is working on the stack, so it must be exactly paired with a JL_GC_POP before the stack frame is destroyed.Several Julia values can be pushed at once using the JL_GC_PUSH2 , JL_GC_PUSH3 , and JL_GC_PUSH4 macros. To push an array of Julia values one can use the JL_GC_PUSHARGS macro, which can be used as follows:jl_value_t **args;\nJL_GC_PUSHARGS(args, 2); // args can now hold 2 `jl_value_t*` objects\nargs[0] = some_value;\nargs[1] = some_other_value;\n// Do something with args (e.g. call jl_... functions)\nJL_GC_POP();The garbage collector also operates under the assumption that it is aware of every old-generation object pointing to a young-generation one. Any time a pointer is updated breaking that assumption, it must be signaled to the collector with the jl_gc_wb (write barrier) function like so:jl_value_t *parent = some_old_value, *child = some_young_value;\n((some_specific_type*)parent)->field = child;\njl_gc_wb(parent, child);It is in general impossible to predict which values will be old at runtime, so the write barrier must be inserted after all explicit stores. One notable exception is if the parent object was just allocated and garbage collection was not run since then. Remember that most jl_... functions can sometimes invoke garbage collection.The write barrier is also necessary for arrays of pointers when updating their data directly. For example:jl_array_t *some_array = ...; // e.g. a Vector{Any}\nvoid **data = (void**)jl_array_data(some_array);\njl_value_t *some_value = ...;\ndata[0] = some_value;\njl_gc_wb(some_array, some_value);" -}, - -{ - "location": "manual/embedding.html#Manipulating-the-Garbage-Collector-1", - "page": "Embedding Julia", - "title": "Manipulating the Garbage Collector", - "category": "section", - "text": "There are some functions to control the GC. In normal use cases, these should not be necessary.Function Description\njl_gc_collect() Force a GC run\njl_gc_enable(0) Disable the GC, return previous state as int\njl_gc_enable(1) Enable the GC, return previous state as int\njl_gc_is_enabled() Return current state as int" -}, - -{ - "location": "manual/embedding.html#Working-with-Arrays-1", - "page": "Embedding Julia", - "title": "Working with Arrays", - "category": "section", - "text": "Julia and C can share array data without copying. The next example will show how this works.Julia arrays are represented in C by the datatype jl_array_t*. Basically, jl_array_t is a struct that contains:Information about the datatype\nA pointer to the data block\nInformation about the sizes of the arrayTo keep things simple, we start with a 1D array. Creating an array containing Float64 elements of length 10 is done by:jl_value_t* array_type = jl_apply_array_type(jl_float64_type, 1);\njl_array_t* x = jl_alloc_array_1d(array_type, 10);Alternatively, if you have already allocated the array you can generate a thin wrapper around its data:double *existingArray = (double*)malloc(sizeof(double)*10);\njl_array_t *x = jl_ptr_to_array_1d(array_type, existingArray, 10, 0);The last argument is a boolean indicating whether Julia should take ownership of the data. If this argument is non-zero, the GC will call free on the data pointer when the array is no longer referenced.In order to access the data of x, we can use jl_array_data:double *xData = (double*)jl_array_data(x);Now we can fill the array:for(size_t i=0; i Pkg.status()\nINFO: Initializing package repository /Users/stefan/.julia/v0.6\nINFO: Cloning METADATA from git://github.com/JuliaLang/METADATA.jl\nNo packages installed.Your package directory is automatically initialized the first time you run a Pkg command that expects it to exist – which includes Pkg.status(). Here\'s an example non-trivial set of required and additional packages:julia> Pkg.status()\nRequired packages:\n - Distributions 0.2.8\n - SHA 0.3.2\nAdditional packages:\n - NumericExtensions 0.2.17\n - Stats 0.2.6These packages are all on registered versions, managed by Pkg. Packages can be in more complicated states, indicated by annotations to the right of the installed package version; we will explain these states and annotations as we encounter them. For programmatic usage, Pkg.installed() returns a dictionary, mapping installed package names to the version of that package which is installed:julia> Pkg.installed()\nDict{String,VersionNumber} with 4 entries:\n\"Distributions\" => v\"0.2.8\"\n\"Stats\" => v\"0.2.6\"\n\"SHA\" => v\"0.3.2\"\n\"NumericExtensions\" => v\"0.2.17\"" -}, - -{ - "location": "manual/packages.html#Adding-and-Removing-Packages-1", - "page": "Packages", - "title": "Adding and Removing Packages", - "category": "section", - "text": "Julia\'s package manager is a little unusual in that it is declarative rather than imperative. This means that you tell it what you want and it figures out what versions to install (or remove) to satisfy those requirements optimally – and minimally. So rather than installing a package, you just add it to the list of requirements and then \"resolve\" what needs to be installed. In particular, this means that if some package had been installed because it was needed by a previous version of something you wanted, and a newer version doesn\'t have that requirement anymore, updating will actually remove that package.Your package requirements are in the file ~/.julia/v0.6/REQUIRE. You can edit this file by hand and then call Pkg.resolve() to install, upgrade or remove packages to optimally satisfy the requirements, or you can do Pkg.edit(), which will open REQUIRE in your editor (configured via the EDITOR or VISUAL environment variables), and then automatically call Pkg.resolve() afterwards if necessary. If you only want to add or remove the requirement for a single package, you can also use the non-interactive Pkg.add() and Pkg.rm() commands, which add or remove a single requirement to REQUIRE and then call Pkg.resolve().You can add a package to the list of requirements with the Pkg.add() function, and the package and all the packages that it depends on will be installed:julia> Pkg.status()\nNo packages installed.\n\njulia> Pkg.add(\"Distributions\")\nINFO: Cloning cache of Distributions from git://github.com/JuliaStats/Distributions.jl.git\nINFO: Cloning cache of NumericExtensions from git://github.com/lindahua/NumericExtensions.jl.git\nINFO: Cloning cache of Stats from git://github.com/JuliaStats/Stats.jl.git\nINFO: Installing Distributions v0.2.7\nINFO: Installing NumericExtensions v0.2.17\nINFO: Installing Stats v0.2.6\nINFO: REQUIRE updated.\n\njulia> Pkg.status()\nRequired packages:\n - Distributions 0.2.7\nAdditional packages:\n - NumericExtensions 0.2.17\n - Stats 0.2.6What this is doing is first adding Distributions to your ~/.julia/v0.6/REQUIRE file:$ cat ~/.julia/v0.6/REQUIRE\nDistributionsIt then runs Pkg.resolve() using these new requirements, which leads to the conclusion that the Distributions package should be installed since it is required but not installed. As stated before, you can accomplish the same thing by editing your ~/.julia/v0.6/REQUIRE file by hand and then running Pkg.resolve() yourself:$ echo SHA >> ~/.julia/v0.6/REQUIRE\n\njulia> Pkg.resolve()\nINFO: Cloning cache of SHA from git://github.com/staticfloat/SHA.jl.git\nINFO: Installing SHA v0.3.2\n\njulia> Pkg.status()\nRequired packages:\n - Distributions 0.2.7\n - SHA 0.3.2\nAdditional packages:\n - NumericExtensions 0.2.17\n - Stats 0.2.6This is functionally equivalent to calling Pkg.add(\"SHA\"), except that Pkg.add() doesn\'t change REQUIRE until after installation has completed, so if there are problems, REQUIRE will be left as it was before calling Pkg.add(). The format of the REQUIRE file is described in Requirements Specification; it allows, among other things, requiring specific ranges of versions of packages.When you decide that you don\'t want to have a package around any more, you can use Pkg.rm() to remove the requirement for it from the REQUIRE file:julia> Pkg.rm(\"Distributions\")\nINFO: Removing Distributions v0.2.7\nINFO: Removing Stats v0.2.6\nINFO: Removing NumericExtensions v0.2.17\nINFO: REQUIRE updated.\n\njulia> Pkg.status()\nRequired packages:\n - SHA 0.3.2\n\njulia> Pkg.rm(\"SHA\")\nINFO: Removing SHA v0.3.2\nINFO: REQUIRE updated.\n\njulia> Pkg.status()\nNo packages installed.Once again, this is equivalent to editing the REQUIRE file to remove the line with each package name on it then running Pkg.resolve() to update the set of installed packages to match. While Pkg.add() and Pkg.rm() are convenient for adding and removing requirements for a single package, when you want to add or remove multiple packages, you can call Pkg.edit() to manually change the contents of REQUIRE and then update your packages accordingly. Pkg.edit() does not roll back the contents of REQUIRE if Pkg.resolve() fails – rather, you have to run Pkg.edit() again to fix the files contents yourself.Because the package manager uses libgit2 internally to manage the package git repositories, users may run into protocol issues (if behind a firewall, for example), when running Pkg.add(). By default, all GitHub-hosted packages wil be accessed via \'https\'; this default can be modified by calling Pkg.setprotocol!(). The following command can be run from the command line in order to tell git to use \'https\' instead of the \'git\' protocol when cloning all repositories, wherever they are hosted:git config --global url.\"https://\".insteadOf git://However, this change will be system-wide and thus the use of Pkg.setprotocol!() is preferable.note: Note\nThe package manager functions also accept the .jl suffix on package names, though the suffix is stripped internally. For example:Pkg.add(\"Distributions.jl\")\nPkg.rm(\"Distributions.jl\")" -}, - -{ - "location": "manual/packages.html#Offline-Installation-of-Packages-1", - "page": "Packages", - "title": "Offline Installation of Packages", - "category": "section", - "text": "For machines with no Internet connection, packages may be installed by copying the package root directory (given by Pkg.dir()) from a machine with the same operating system and environment.Pkg.add() does the following within the package root directory:Adds the name of the package to REQUIRE.\nDownloads the package to .cache, then copies the package to the package root directory.\nRecursively performs step 2 against all the packages listed in the package\'s REQUIRE file.\nRuns Pkg.build()warning: Warning\nCopying installed packages from a different machine is brittle for packages requiring binary external dependencies. Such packages may break due to differences in operating system versions, build environments, and/or absolute path dependencies." -}, - -{ - "location": "manual/packages.html#Installing-Unregistered-Packages-1", - "page": "Packages", - "title": "Installing Unregistered Packages", - "category": "section", - "text": "Julia packages are simply git repositories, clonable via any of the protocols that git supports, and containing Julia code that follows certain layout conventions. Official Julia packages are registered in the METADATA.jl repository, available at a well-known location [1]. The Pkg.add() and Pkg.rm() commands in the previous section interact with registered packages, but the package manager can install and work with unregistered packages too. To install an unregistered package, use Pkg.clone(url), where url is a git URL from which the package can be cloned:julia> Pkg.clone(\"git://example.com/path/to/Package.jl.git\")\nINFO: Cloning Package from git://example.com/path/to/Package.jl.git\nCloning into \'Package\'...\nremote: Counting objects: 22, done.\nremote: Compressing objects: 100% (10/10), done.\nremote: Total 22 (delta 8), reused 22 (delta 8)\nReceiving objects: 100% (22/22), 2.64 KiB, done.\nResolving deltas: 100% (8/8), done.By convention, Julia repository names end with .jl (the additional .git indicates a \"bare\" git repository), which keeps them from colliding with repositories for other languages, and also makes Julia packages easy to find in search engines. When packages are installed in your .julia/v0.6 directory, however, the extension is redundant so we leave it off.If unregistered packages contain a REQUIRE file at the top of their source tree, that file will be used to determine which registered packages the unregistered package depends on, and they will automatically be installed. Unregistered packages participate in the same version resolution logic as registered packages, so installed package versions will be adjusted as necessary to satisfy the requirements of both registered and unregistered packages.[1]: The official set of packages is at https://github.com/JuliaLang/METADATA.jl, but individuals and organizations can easily use a different metadata repository. This allows control which packages are available for automatic installation. One can allow only audited and approved package versions, and make private packages or forks available. See Custom METADATA Repository for details." -}, - -{ - "location": "manual/packages.html#Updating-Packages-1", - "page": "Packages", - "title": "Updating Packages", - "category": "section", - "text": "When package developers publish new registered versions of packages that you\'re using, you will, of course, want the new shiny versions. To get the latest and greatest versions of all your packages, just do Pkg.update():julia> Pkg.update()\nINFO: Updating METADATA...\nINFO: Computing changes...\nINFO: Upgrading Distributions: v0.2.8 => v0.2.10\nINFO: Upgrading Stats: v0.2.7 => v0.2.8The first step of updating packages is to pull new changes to ~/.julia/v0.6/METADATA and see if any new registered package versions have been published. After this, Pkg.update() attempts to update packages that are checked out on a branch and not dirty (i.e. no changes have been made to files tracked by git) by pulling changes from the package\'s upstream repository. Upstream changes will only be applied if no merging or rebasing is necessary – i.e. if the branch can be \"fast-forwarded\". If the branch cannot be fast-forwarded, it is assumed that you\'re working on it and will update the repository yourself.Finally, the update process recomputes an optimal set of package versions to have installed to satisfy your top-level requirements and the requirements of \"fixed\" packages. A package is considered fixed if it is one of the following:Unregistered: the package is not in METADATA – you installed it with Pkg.clone().\nChecked out: the package repo is on a development branch.\nDirty: changes have been made to files in the repo.If any of these are the case, the package manager cannot freely change the installed version of the package, so its requirements must be satisfied by whatever other package versions it picks. The combination of top-level requirements in ~/.julia/v0.6/REQUIRE and the requirement of fixed packages are used to determine what should be installed.You can also update only a subset of the installed packages, by providing arguments to the Pkg.update function. In that case, only the packages provided as arguments and their dependencies will be updated:julia> Pkg.update(\"Example\")\nINFO: Updating METADATA...\nINFO: Computing changes...\nINFO: Upgrading Example: v0.4.0 => 0.4.1This partial update process still computes the new set of package versions according to top-level requirements and \"fixed\" packages, but it additionally considers all other packages except those explicitly provided, and their dependencies, as fixed." -}, - -{ - "location": "manual/packages.html#Checkout,-Pin-and-Free-1", - "page": "Packages", - "title": "Checkout, Pin and Free", - "category": "section", - "text": "You may want to use the master version of a package rather than one of its registered versions. There might be fixes or functionality on master that you need that aren\'t yet published in any registered versions, or you may be a developer of the package and need to make changes on master or some other development branch. In such cases, you can do Pkg.checkout(pkg) to checkout the master branch of pkg or Pkg.checkout(pkg,branch) to checkout some other branch:julia> Pkg.add(\"Distributions\")\nINFO: Installing Distributions v0.2.9\nINFO: Installing NumericExtensions v0.2.17\nINFO: Installing Stats v0.2.7\nINFO: REQUIRE updated.\n\njulia> Pkg.status()\nRequired packages:\n - Distributions 0.2.9\nAdditional packages:\n - NumericExtensions 0.2.17\n - Stats 0.2.7\n\njulia> Pkg.checkout(\"Distributions\")\nINFO: Checking out Distributions master...\nINFO: No packages to install, update or remove.\n\njulia> Pkg.status()\nRequired packages:\n - Distributions 0.2.9+ master\nAdditional packages:\n - NumericExtensions 0.2.17\n - Stats 0.2.7Immediately after installing Distributions with Pkg.add() it is on the current most recent registered version – 0.2.9 at the time of writing this. Then after running Pkg.checkout(\"Distributions\"), you can see from the output of Pkg.status() that Distributions is on an unregistered version greater than 0.2.9, indicated by the \"pseudo-version\" number 0.2.9+.When you checkout an unregistered version of a package, the copy of the REQUIRE file in the package repo takes precedence over any requirements registered in METADATA, so it is important that developers keep this file accurate and up-to-date, reflecting the actual requirements of the current version of the package. If the REQUIRE file in the package repo is incorrect or missing, dependencies may be removed when the package is checked out. This file is also used to populate newly published versions of the package if you use the API that Pkg provides for this (described below).When you decide that you no longer want to have a package checked out on a branch, you can \"free\" it back to the control of the package manager with Pkg.free(pkg):julia> Pkg.free(\"Distributions\")\nINFO: Freeing Distributions...\nINFO: No packages to install, update or remove.\n\njulia> Pkg.status()\nRequired packages:\n - Distributions 0.2.9\nAdditional packages:\n - NumericExtensions 0.2.17\n - Stats 0.2.7After this, since the package is on a registered version and not on a branch, its version will be updated as new registered versions of the package are published.If you want to pin a package at a specific version so that calling Pkg.update() won\'t change the version the package is on, you can use the Pkg.pin() function:julia> Pkg.pin(\"Stats\")\nINFO: Creating Stats branch pinned.47c198b1.tmp\n\njulia> Pkg.status()\nRequired packages:\n - Distributions 0.2.9\nAdditional packages:\n - NumericExtensions 0.2.17\n - Stats 0.2.7 pinned.47c198b1.tmpAfter this, the Stats package will remain pinned at version 0.2.7 – or more specifically, at commit 47c198b1, but since versions are permanently associated a given git hash, this is the same thing. Pkg.pin() works by creating a throw-away branch for the commit you want to pin the package at and then checking that branch out. By default, it pins a package at the current commit, but you can choose a different version by passing a second argument:julia> Pkg.pin(\"Stats\",v\"0.2.5\")\nINFO: Creating Stats branch pinned.1fd0983b.tmp\nINFO: No packages to install, update or remove.\n\njulia> Pkg.status()\nRequired packages:\n - Distributions 0.2.9\nAdditional packages:\n - NumericExtensions 0.2.17\n - Stats 0.2.5 pinned.1fd0983b.tmpNow the Stats package is pinned at commit 1fd0983b, which corresponds to version 0.2.5. When you decide to \"unpin\" a package and let the package manager update it again, you can use Pkg.free() like you would to move off of any branch:julia> Pkg.free(\"Stats\")\nINFO: Freeing Stats...\nINFO: No packages to install, update or remove.\n\njulia> Pkg.status()\nRequired packages:\n - Distributions 0.2.9\nAdditional packages:\n - NumericExtensions 0.2.17\n - Stats 0.2.7After this, the Stats package is managed by the package manager again, and future calls to Pkg.update() will upgrade it to newer versions when they are published. The throw-away pinned.1fd0983b.tmp branch remains in your local Stats repo, but since git branches are extremely lightweight, this doesn\'t really matter; if you feel like cleaning them up, you can go into the repo and delete those branches [2].[2]: Packages that aren\'t on branches will also be marked as dirty if you make changes in the repo, but that\'s a less common thing to do." -}, - -{ - "location": "manual/packages.html#Custom-METADATA-Repository-1", - "page": "Packages", - "title": "Custom METADATA Repository", - "category": "section", - "text": "By default, Julia assumes you will be using the official METADATA.jl repository for downloading and installing packages. You can also provide a different metadata repository location. A common approach is to keep your metadata-v2 branch up to date with the Julia official branch and add another branch with your custom packages. You can initialize your local metadata repository using that custom location and branch and then periodically rebase your custom branch with the official metadata-v2 branch. In order to use a custom repository and branch, issue the following command:julia> Pkg.init(\"https://me.example.com/METADATA.jl.git\", \"branch\")The branch argument is optional and defaults to metadata-v2. Once initialized, a file named META_BRANCH in your ~/.julia/vX.Y/ path will track the branch that your METADATA repository was initialized with. If you want to change branches, you will need to either modify the META_BRANCH file directly (be careful!) or remove the vX.Y directory and re-initialize your METADATA repository using the Pkg.init command." -}, - -{ - "location": "manual/packages.html#Package-Development-1", - "page": "Packages", - "title": "Package Development", - "category": "section", - "text": "Julia\'s package manager is designed so that when you have a package installed, you are already in a position to look at its source code and full development history. You are also able to make changes to packages, commit them using git, and easily contribute fixes and enhancements upstream. Similarly, the system is designed so that if you want to create a new package, the simplest way to do so is within the infrastructure provided by the package manager." -}, - -{ - "location": "manual/packages.html#man-initial-setup-1", - "page": "Packages", - "title": "Initial Setup", - "category": "section", - "text": "Since packages are git repositories, before doing any package development you should setup the following standard global git configuration settings:$ git config --global user.name \"FULL NAME\"\n$ git config --global user.email \"EMAIL\"where FULL NAME is your actual full name (spaces are allowed between the double quotes) and EMAIL is your actual email address. Although it isn\'t necessary to use GitHub to create or publish Julia packages, most Julia packages as of writing this are hosted on GitHub and the package manager knows how to format origin URLs correctly and otherwise work with the service smoothly. We recommend that you create a free account on GitHub and then do:$ git config --global github.user \"USERNAME\"where USERNAME is your actual GitHub user name. Once you do this, the package manager knows your GitHub user name and can configure things accordingly. You should also upload your public SSH key to GitHub and set up an SSH agent on your development machine so that you can push changes with minimal hassle. In the future, we will make this system extensible and support other common git hosting options like BitBucket and allow developers to choose their favorite. Since the package development functions has been moved to the PkgDev package, you need to run Pkg.add(\"PkgDev\"); import PkgDev to access the functions starting with PkgDev. in the document below." -}, - -{ - "location": "manual/packages.html#Making-changes-to-an-existing-package-1", - "page": "Packages", - "title": "Making changes to an existing package", - "category": "section", - "text": "" -}, - -{ - "location": "manual/packages.html#Documentation-changes-1", - "page": "Packages", - "title": "Documentation changes", - "category": "section", - "text": "If you want to improve the online documentation of a package, the easiest approach (at least for small changes) is to use GitHub\'s online editing functionality. First, navigate to the repository\'s GitHub \"home page,\" find the file (e.g., README.md) within the repository\'s folder structure, and click on it. You\'ll see the contents displayed, along with a small \"pencil\" icon in the upper right hand corner. Clicking that icon opens the file in edit mode. Make your changes, write a brief summary describing the changes you want to make (this is your commit message), and then hit \"Propose file change.\" Your changes will be submitted for consideration by the package owner(s) and collaborators.For larger documentation changes–and especially ones that you expect to have to update in response to feedback–you might find it easier to use the procedure for code changes described below." -}, - -{ - "location": "manual/packages.html#Code-changes-1", - "page": "Packages", - "title": "Code changes", - "category": "section", - "text": "" -}, - -{ - "location": "manual/packages.html#Executive-summary-1", - "page": "Packages", - "title": "Executive summary", - "category": "section", - "text": "Here we assume you\'ve already set up git on your local machine and have a GitHub account (see above). Let\'s imagine you\'re fixing a bug in the Images package:Pkg.checkout(\"Images\") # check out the master branch\n\ncd(Pkg.dir(\"Images\"))\n;git checkout -b myfixes # create a branch for your changes\n # be sure to add a test for your bug\nPkg.test(\"Images\") # make sure everything works now\n;git commit -a -m \"Fix foo by calling bar\" # write a descriptive message\nusing PkgDev\nPkgDev.submit(\"Images\")The last line will present you with a link to submit a pull request to incorporate your changes." -}, - -{ - "location": "manual/packages.html#Detailed-description-1", - "page": "Packages", - "title": "Detailed description", - "category": "section", - "text": "If you want to fix a bug or add new functionality, you want to be able to test your changes before you submit them for consideration. You also need to have an easy way to update your proposal in response to the package owner\'s feedback. Consequently, in this case the strategy is to work locally on your own machine; once you are satisfied with your changes, you submit them for consideration. This process is called a pull request because you are asking to \"pull\" your changes into the project\'s main repository. Because the online repository can\'t see the code on your private machine, you first push your changes to a publicly-visible location, your own online fork of the package (hosted on your own personal GitHub account).Let\'s assume you already have the Foo package installed. In the description below, anything starting with Pkg. or PkgDev. is meant to be typed at the Julia prompt; anything starting with git is meant to be typed in julia\'s shell mode (or using the shell that comes with your operating system). Within Julia, you can combine these two modes:julia> cd(Pkg.dir(\"Foo\")) # go to Foo\'s folder\n\nshell> git command arguments... # command will apply to FooNow suppose you\'re ready to make some changes to Foo. While there are several possible approaches, here is one that is widely used:From the Julia prompt, type Pkg.checkout(\"Foo\"). This ensures you\'re running the latest code (the master branch), rather than just whatever \"official release\" version you have installed. (If you\'re planning to fix a bug, at this point it\'s a good idea to check again whether the bug has already been fixed by someone else. If it has, you can request that a new official release be tagged so that the fix gets distributed to the rest of the community.) If you receive an error Foo is dirty, bailing, see Dirty packages below.\nCreate a branch for your changes: navigate to the package folder (the one that Julia reports from Pkg.dir(\"Foo\")) and (in shell mode) create a new branch using git checkout -b , where might be some descriptive name (e.g., fixbar). By creating a branch, you ensure that you can easily go back and forth between your new work and the current master branch (see https://git-scm.com/book/en/v2/Git-Branching-Branches-in-a-Nutshell).\nIf you forget to do this step until after you\'ve already made some changes, don\'t worry: see more detail about branching below.\nMake your changes. Whether it\'s fixing a bug or adding new functionality, in most cases your change should include updates to both the src/ and test/ folders. If you\'re fixing a bug, add your minimal example demonstrating the bug (on the current code) to the test suite; by contributing a test for the bug, you ensure that the bug won\'t accidentally reappear at some later time due to other changes. If you\'re adding new functionality, creating tests demonstrates to the package owner that you\'ve made sure your code works as intended.\nRun the package\'s tests and make sure they pass. There are several ways to run the tests:\nFrom Julia, run Pkg.test(\"Foo\"): this will run your tests in a separate (new) julia process.\nFrom Julia, include(\"runtests.jl\") from the package\'s test/ folder (it\'s possible the file has a different name, look for one that runs all the tests): this allows you to run the tests repeatedly in the same session without reloading all the package code; for packages that take a while to load, this can be much faster. With this approach, you do have to do some extra work to make changes in the package code.\nFrom the shell, run julia ../test/runtests.jl from within the package\'s src/ folder.\nCommit your changes: see https://git-scm.com/book/en/v2/Git-Basics-Recording-Changes-to-the-Repository.\nSubmit your changes: From the Julia prompt, type PkgDev.submit(\"Foo\"). This will push your changes to your GitHub fork, creating it if it doesn\'t already exist. (If you encounter an error, make sure you\'ve set up your SSH keys.) Julia will then give you a hyperlink; open that link, edit the message, and then click \"submit.\" At that point, the package owner will be notified of your changes and may initiate discussion. (If you are comfortable with git, you can also do these steps manually from the shell.)\nThe package owner may suggest additional improvements. To respond to those suggestions, you can easily update the pull request (this only works for changes that have not already been merged; for merged pull requests, make new changes by starting a new branch):\nIf you\'ve changed branches in the meantime, make sure you go back to the same branch with git checkout fixbar (from shell mode) or Pkg.checkout(\"Foo\", \"fixbar\") (from the Julia prompt).\nAs above, make your changes, run the tests, and commit your changes.\nFrom the shell, type git push. This will add your new commit(s) to the same pull request; you should see them appear automatically on the page holding the discussion of your pull request.\nOne potential type of change the owner may request is that you squash your commits. See Squashing below." -}, - -{ - "location": "manual/packages.html#Dirty-packages-1", - "page": "Packages", - "title": "Dirty packages", - "category": "section", - "text": "If you can\'t change branches because the package manager complains that your package is dirty, it means you have some changes that have not been committed. From the shell, use git diff to see what these changes are; you can either discard them (git checkout changedfile.jl) or commit them before switching branches. If you can\'t easily resolve the problems manually, as a last resort you can delete the entire \"Foo\" folder and reinstall a fresh copy with Pkg.add(\"Foo\"). Naturally, this deletes any changes you\'ve made." -}, - -{ - "location": "manual/packages.html#man-branch-post-hoc-1", - "page": "Packages", - "title": "Making a branch post hoc", - "category": "section", - "text": "Especially for newcomers to git, one often forgets to create a new branch until after some changes have already been made. If you haven\'t yet staged or committed your changes, you can create a new branch with git checkout -b just as usual–git will kindly show you that some files have been modified and create the new branch for you. Your changes have not yet been committed to this new branch, so the normal work rules still apply.However, if you\'ve already made a commit to master but wish to go back to the official master (called origin/master), use the following procedure:Create a new branch. This branch will hold your changes.\nMake sure everything is committed to this branch.\ngit checkout master. If this fails, do not proceed further until you have resolved the problems, or you may lose your changes.\nResetmaster (your current branch) back to an earlier state with git reset --hard origin/master (see https://git-scm.com/blog/2011/07/11/reset.html).This requires a bit more familiarity with git, so it\'s much better to get in the habit of creating a branch at the outset." -}, - -{ - "location": "manual/packages.html#man-squashing-and-rebasing-1", - "page": "Packages", - "title": "Squashing and rebasing", - "category": "section", - "text": "Depending on the tastes of the package owner (s)he may ask you to \"squash\" your commits. This is especially likely if your change is quite simple but your commit history looks like this:WIP: add new 1-line whizbang function (currently breaks package)\nFinish whizbang function\nFix typo in variable name\nOops, don\'t forget to supply default argument\nSplit into two 1-line functions\nRats, forgot to export the second function\n...This gets into the territory of more advanced git usage, and you\'re encouraged to do some reading (https://git-scm.com/book/en/v2/Git-Branching-Rebasing). However, a brief summary of the procedure is as follows:To protect yourself from error, start from your fixbar branch and create a new branch with git checkout -b fixbar_backup. Since you started from fixbar, this will be a copy. Now go back to the one you intend to modify with git checkout fixbar.\nFrom the shell, type git rebase -i origin/master.\nTo combine commits, change pick to squash (for additional options, consult other sources). Save the file and close the editor window.\nEdit the combined commit message.If the rebase goes badly, you can go back to the beginning to try again like this:git checkout fixbar\ngit reset --hard fixbar_backupNow let\'s assume you\'ve rebased successfully. Since your fixbar repository has now diverged from the one in your GitHub fork, you\'re going to have to do a force push:To make it easy to refer to your GitHub fork, create a \"handle\" for it with git remote add myfork https://github.com/myaccount/Foo.jl.git, where the URL comes from the \"clone URL\" on your GitHub fork\'s page.\nForce-push to your fork with git push myfork +fixbar. The + indicates that this should replace the fixbar branch found at myfork." -}, - -{ - "location": "manual/packages.html#Creating-a-new-Package-1", - "page": "Packages", - "title": "Creating a new Package", - "category": "section", - "text": "" -}, - -{ - "location": "manual/packages.html#REQUIRE-speaks-for-itself-1", - "page": "Packages", - "title": "REQUIRE speaks for itself", - "category": "section", - "text": "You should have a REQUIRE file in your package repository, with a bare minimum directive of what Julia version you expect your users to be running for the package to work. Putting a floor on what Julia version your package supports is done by simply adding julia 0.x in this file. While this line is partly informational, it also has the consequence of whether Pkg.update() will update code found in .julia version directories. It will not update code found in version directories beneath the floor of what\'s specified in your REQUIRE.As the development version 0.y matures, you may find yourself using it more frequently, and wanting your package to support it. Be warned, the development branch of Julia is the land of breakage, and you can expect things to break. When you go about fixing whatever broke your package in the development 0.y branch, you will likely find that you just broke your package on the stable version.There is a mechanism found in the Compat package that will enable you to support both the stable version and breaking changes found in the development version. Should you decide to use this solution, you will need to add Compat to your REQUIRE file. In this case, you will still have julia 0.x in your REQUIRE. The x is the floor version of what your package supports.You might also have no interest in supporting the development version of Julia. Just as you can add a floor to the version you expect your users to be on, you can set an upper bound. In this case, you would put julia 0.x 0.y- in your REQUIRE file. The - at the end of the version number means pre-release versions of that specific version from the very first commit. By setting it as the ceiling, you mean the code supports everything up to but not including the ceiling version.Another scenario is that you are writing the bulk of the code for your package with Julia 0.y and do not want to support the current stable version of Julia. If you choose to do this, simply add julia 0.y- to your REQUIRE. Just remember to change the julia 0.y- to julia 0.y in your REQUIRE file once 0.y is officially released. If you don\'t edit the dash cruft you are suggesting that you support both the development and stable versions of the same version number! That would be madness. See the Requirements Specification for the full format of REQUIRE.Lastly, in many cases you may need extra packages for testing. Additional packages which are only required for tests should be specified in the test/REQUIRE file. This REQUIRE file has the same specification as the standard REQUIRE file." -}, - -{ - "location": "manual/packages.html#Guidelines-for-naming-a-package-1", - "page": "Packages", - "title": "Guidelines for naming a package", - "category": "section", - "text": "Package names should be sensible to most Julia users, even to those who are not domain experts. When you submit your package to METADATA, you can expect a little back and forth about the package name with collaborators, especially if it\'s ambiguous or can be confused with something other than what it is. During this bike-shedding, it\'s not uncommon to get a range of different name suggestions. These are only suggestions though, with the intent being to keep a tidy namespace in the curated METADATA repository. Since this repository belongs to the entire community, there will likely be a few collaborators who care about your package name. Here are some guidelines to follow in naming your package:Avoid jargon. In particular, avoid acronyms unless there is minimal possibility of confusion.\nIt\'s ok to say USA if you\'re talking about the USA.\nIt\'s not ok to say PMA, even if you\'re talking about positive mental attitude.\nAvoid using Julia in your package name.\nIt is usually clear from context and to your users that the package is a Julia package.\nHaving Julia in the name can imply that the package is connected to, or endorsed by, contributors to the Julia language itself.\nPackages that provide most of their functionality in association with a new type should have pluralized names.\nDataFrames provides the DataFrame type.\nBloomFilters provides the BloomFilter type.\nIn contrast, JuliaParser provides no new type, but instead new functionality in the JuliaParser.parse() function.\nErr on the side of clarity, even if clarity seems long-winded to you.\nRandomMatrices is a less ambiguous name than RndMat or RMT, even though the latter are shorter.\nA less systematic name may suit a package that implements one of several possible approaches to its domain.\nJulia does not have a single comprehensive plotting package. Instead, Gadfly, PyPlot, Winston and other packages each implement a unique approach based on a particular design philosophy.\nIn contrast, SortingAlgorithms provides a consistent interface to use many well-established sorting algorithms.\nPackages that wrap external libraries or programs should be named after those libraries or programs.\nCPLEX.jl wraps the CPLEX library, which can be identified easily in a web search.\nMATLAB.jl provides an interface to call the MATLAB engine from within Julia." -}, - -{ - "location": "manual/packages.html#Generating-the-package-1", - "page": "Packages", - "title": "Generating the package", - "category": "section", - "text": "Suppose you want to create a new Julia package called FooBar. To get started, do PkgDev.generate(pkg,license) where pkg is the new package name and license is the name of a license that the package generator knows about:julia> PkgDev.generate(\"FooBar\",\"MIT\")\nINFO: Initializing FooBar repo: /Users/stefan/.julia/v0.6/FooBar\nINFO: Origin: git://github.com/StefanKarpinski/FooBar.jl.git\nINFO: Generating LICENSE.md\nINFO: Generating README.md\nINFO: Generating src/FooBar.jl\nINFO: Generating test/runtests.jl\nINFO: Generating REQUIRE\nINFO: Generating .travis.yml\nINFO: Generating appveyor.yml\nINFO: Generating .gitignore\nINFO: Committing FooBar generated filesThis creates the directory ~/.julia/v0.6/FooBar, initializes it as a git repository, generates a bunch of files that all packages should have, and commits them to the repository:$ cd ~/.julia/v0.6/FooBar && git show --stat\n\ncommit 84b8e266dae6de30ab9703150b3bf771ec7b6285\nAuthor: Stefan Karpinski \nDate: Wed Oct 16 17:57:58 2013 -0400\n\n FooBar.jl generated files.\n\n license: MIT\n authors: Stefan Karpinski\n years: 2013\n user: StefanKarpinski\n\n Julia Version 0.3.0-prerelease+3217 [5fcfb13*]\n\n .gitignore | 2 ++\n .travis.yml | 13 +++++++++++++\n LICENSE.md | 22 +++++++++++++++++++++++\n README.md | 3 +++\n REQUIRE | 1 +\n appveyor.yml | 34 ++++++++++++++++++++++++++++++++++\n src/FooBar.jl | 5 +++++\n test/runtests.jl | 5 +++++\n 8 files changed, 85 insertions(+)At the moment, the package manager knows about the MIT \"Expat\" License, indicated by \"MIT\", the Simplified BSD License, indicated by \"BSD\", and version 2.0 of the Apache Software License, indicated by \"ASL\". If you want to use a different license, you can ask us to add it to the package generator, or just pick one of these three and then modify the ~/.julia/v0.6/PACKAGE/LICENSE.md file after it has been generated.If you created a GitHub account and configured git to know about it, PkgDev.generate() will set an appropriate origin URL for you. It will also automatically generate a .travis.yml file for using the Travis automated testing service, and an appveyor.yml file for using AppVeyor. You will have to enable testing on the Travis and AppVeyor websites for your package repository, but once you\'ve done that, it will already have working tests. Of course, all the default testing does is verify that using FooBar in Julia works." -}, - -{ - "location": "manual/packages.html#Loading-Static-Non-Julia-Files-1", - "page": "Packages", - "title": "Loading Static Non-Julia Files", - "category": "section", - "text": "If your package code needs to load static files which are not Julia code, e.g. an external library or data files, and are located within the package directory, use the @__DIR__ macro to determine the directory of the current source file. For example if FooBar/src/FooBar.jl needs to load FooBar/data/foo.csv, use the following code:datapath = joinpath(@__DIR__, \"..\", \"data\")\nfoo = readcsv(joinpath(datapath, \"foo.csv\"))" -}, - -{ - "location": "manual/packages.html#Making-Your-Package-Available-1", - "page": "Packages", - "title": "Making Your Package Available", - "category": "section", - "text": "Once you\'ve made some commits and you\'re happy with how FooBar is working, you may want to get some other people to try it out. First you\'ll need to create the remote repository and push your code to it; we don\'t yet automatically do this for you, but we will in the future and it\'s not too hard to figure out [3]. Once you\'ve done this, letting people try out your code is as simple as sending them the URL of the published repo – in this case:git://github.com/StefanKarpinski/FooBar.jl.gitFor your package, it will be your GitHub user name and the name of your package, but you get the idea. People you send this URL to can use Pkg.clone() to install the package and try it out:julia> Pkg.clone(\"git://github.com/StefanKarpinski/FooBar.jl.git\")\nINFO: Cloning FooBar from git@github.com:StefanKarpinski/FooBar.jl.git[3]: Installing and using GitHub\'s \"hub\" tool is highly recommended. It allows you to do things like run hub create in the package repo and have it automatically created via GitHub\'s API." -}, - -{ - "location": "manual/packages.html#Tagging-and-Publishing-Your-Package-1", - "page": "Packages", - "title": "Tagging and Publishing Your Package", - "category": "section", - "text": "tip: Tip\nIf you are hosting your package on GitHub, you can use the attobot integration to handle package registration, tagging and publishing.Once you\'ve decided that FooBar is ready to be registered as an official package, you can add it to your local copy of METADATA using PkgDev.register():julia> PkgDev.register(\"FooBar\")\nINFO: Registering FooBar at git://github.com/StefanKarpinski/FooBar.jl.git\nINFO: Committing METADATA for FooBarThis creates a commit in the ~/.julia/v0.6/METADATA repo:$ cd ~/.julia/v0.6/METADATA && git show\n\ncommit 9f71f4becb05cadacb983c54a72eed744e5c019d\nAuthor: Stefan Karpinski \nDate: Wed Oct 16 18:46:02 2013 -0400\n\n Register FooBar\n\ndiff --git a/FooBar/url b/FooBar/url\nnew file mode 100644\nindex 0000000..30e525e\n--- /dev/null\n+++ b/FooBar/url\n@@ -0,0 +1 @@\n+git://github.com/StefanKarpinski/FooBar.jl.gitThis commit is only locally visible, however. To make it visible to the Julia community, you need to merge your local METADATA upstream into the official repo. The PkgDev.publish() command will fork the METADATA repository on GitHub, push your changes to your fork, and open a pull request:julia> PkgDev.publish()\nINFO: Validating METADATA\nINFO: No new package versions to publish\nINFO: Submitting METADATA changes\nINFO: Forking JuliaLang/METADATA.jl to StefanKarpinski\nINFO: Pushing changes as branch pull-request/ef45f54b\nINFO: To create a pull-request open:\n\n https://github.com/StefanKarpinski/METADATA.jl/compare/pull-request/ef45f54btip: Tip\nIf PkgDev.publish() fails with error:ERROR: key not found: \"token\"then you may have encountered an issue from using the GitHub API on multiple systems. The solution is to delete the \"Julia Package Manager\" personal access token from your Github account and try again.Other failures may require you to circumvent PkgDev.publish() by creating a pull request on GitHub. See: Publishing METADATA manually below.Once the package URL for FooBar is registered in the official METADATA repo, people know where to clone the package from, but there still aren\'t any registered versions available. You can tag and register it with the PkgDev.tag() command:julia> PkgDev.tag(\"FooBar\")\nINFO: Tagging FooBar v0.0.1\nINFO: Committing METADATA for FooBarThis tags v0.0.1 in the FooBar repo:$ cd ~/.julia/v0.6/FooBar && git tag\nv0.0.1It also creates a new version entry in your local METADATA repo for FooBar:$ cd ~/.julia/v0.6/FooBar && git show\ncommit de77ee4dc0689b12c5e8b574aef7f70e8b311b0e\nAuthor: Stefan Karpinski \nDate: Wed Oct 16 23:06:18 2013 -0400\n\n Tag FooBar v0.0.1\n\ndiff --git a/FooBar/versions/0.0.1/sha1 b/FooBar/versions/0.0.1/sha1\nnew file mode 100644\nindex 0000000..c1cb1c1\n--- /dev/null\n+++ b/FooBar/versions/0.0.1/sha1\n@@ -0,0 +1 @@\n+84b8e266dae6de30ab9703150b3bf771ec7b6285The PkgDev.tag() command takes an optional second argument that is either an explicit version number object like v\"0.0.1\" or one of the symbols :patch, :minor or :major. These increment the patch, minor or major version number of your package intelligently.Adding a tagged version of your package will expedite the official registration into METADATA.jl by collaborators. It is strongly recommended that you complete this process, regardless if your package is completely ready for an official release.As a general rule, packages should be tagged 0.0.1 first. Since Julia itself hasn\'t achieved 1.0 status, it\'s best to be conservative in your package\'s tagged versions.As with PkgDev.register(), these changes to METADATA aren\'t available to anyone else until they\'ve been included upstream. Again, use the PkgDev.publish() command, which first makes sure that individual package repos have been tagged, pushes them if they haven\'t already been, and then opens a pull request to METADATA:julia> PkgDev.publish()\nINFO: Validating METADATA\nINFO: Pushing FooBar permanent tags: v0.0.1\nINFO: Submitting METADATA changes\nINFO: Forking JuliaLang/METADATA.jl to StefanKarpinski\nINFO: Pushing changes as branch pull-request/3ef4f5c4\nINFO: To create a pull-request open:\n\n https://github.com/StefanKarpinski/METADATA.jl/compare/pull-request/3ef4f5c4" -}, - -{ - "location": "manual/packages.html#Publishing-METADATA-manually-1", - "page": "Packages", - "title": "Publishing METADATA manually", - "category": "section", - "text": "If PkgDev.publish() fails you can follow these instructions to manually publish your package.By \"forking\" the main METADATA repository, you can create a personal copy (of METADATA.jl) under your GitHub account. Once that copy exists, you can push your local changes to your copy (just like any other GitHub project).Create a fork of METADATA.jl.\nAdd your fork as a remote repository for the METADATA repository on your local computer (in the terminal where USERNAME is your github username):\ncd ~/.julia/v0.6/METADATA\ngit remote add USERNAME https://github.com/USERNAME/METADATA.jl.git\nPush your changes to your fork:\ngit push USERNAME metadata-v2\nIf all of that works, then go back to the GitHub page for your fork, and click the \"pull request\" link." -}, - -{ - "location": "manual/packages.html#Fixing-Package-Requirements-1", - "page": "Packages", - "title": "Fixing Package Requirements", - "category": "section", - "text": "If you need to fix the registered requirements of an already-published package version, you can do so just by editing the metadata for that version, which will still have the same commit hash – the hash associated with a version is permanent:$ cd ~/.julia/v0.6/METADATA/FooBar/versions/0.0.1 && cat requires\njulia 0.3-\n$ vi requiresSince the commit hash stays the same, the contents of the REQUIRE file that will be checked out in the repo will not match the requirements in METADATA after such a change; this is unavoidable. When you fix the requirements in METADATA for a previous version of a package, however, you should also fix the REQUIRE file in the current version of the package." -}, - -{ - "location": "manual/packages.html#Requirements-Specification-1", - "page": "Packages", - "title": "Requirements Specification", - "category": "section", - "text": "The ~/.julia/v0.6/REQUIRE file, the REQUIRE file inside packages, and the METADATA package requires files use a simple line-based format to express the ranges of package versions which need to be installed. Package REQUIRE and METADATA requires files should also include the range of versions of julia the package is expected to work with. Additionally, packages can include a test/REQUIRE file to specify additional packages which are only required for testing.Here\'s how these files are parsed and interpreted.Everything after a # mark is stripped from each line as a comment.\nIf nothing but whitespace is left, the line is ignored.\nIf there are non-whitespace characters remaining, the line is a requirement and the is split on whitespace into words.The simplest possible requirement is just the name of a package name on a line by itself:DistributionsThis requirement is satisfied by any version of the Distributions package. The package name can be followed by zero or more version numbers in ascending order, indicating acceptable intervals of versions of that package. One version opens an interval, while the next closes it, and the next opens a new interval, and so on; if an odd number of version numbers are given, then arbitrarily large versions will satisfy; if an even number of version numbers are given, the last one is an upper limit on acceptable version numbers. For example, the line:Distributions 0.1is satisfied by any version of Distributions greater than or equal to 0.1.0. Suffixing a version with - allows any pre-release versions as well. For example:Distributions 0.1-is satisfied by pre-release versions such as 0.1-dev or 0.1-rc1, or by any version greater than or equal to 0.1.0.This requirement entry:Distributions 0.1 0.2.5is satisfied by versions from 0.1.0 up to, but not including 0.2.5. If you want to indicate that any 0.1.x version will do, you will want to write:Distributions 0.1 0.2-If you want to start accepting versions after 0.2.7, you can write:Distributions 0.1 0.2- 0.2.7If a requirement line has leading words that begin with @, it is a system-dependent requirement. If your system matches these system conditionals, the requirement is included, if not, the requirement is ignored. For example:@osx Homebrewwill require the Homebrew package only on systems where the operating system is OS X. The system conditions that are currently supported are (hierarchically):@unix\n@linux\n@bsd\n@osx\n@windowsThe @unix condition is satisfied on all UNIX systems, including Linux and BSD. Negated system conditionals are also supported by adding a ! after the leading @. Examples:@!windows\n@unix @!osxThe first condition applies to any system but Windows and the second condition applies to any UNIX system besides OS X.Runtime checks for the current version of Julia can be made using the built-in VERSION variable, which is of type VersionNumber. Such code is occasionally necessary to keep track of new or deprecated functionality between various releases of Julia. Examples of runtime checks:VERSION < v\"0.3-\" #exclude all pre-release versions of 0.3\n\nv\"0.2-\" <= VERSION < v\"0.3-\" #get all 0.2 versions, including pre-releases, up to the above\n\nv\"0.2\" <= VERSION < v\"0.3-\" #To get only stable 0.2 versions (Note v\"0.2\" == v\"0.2.0\")\n\nVERSION >= v\"0.2.1\" #get at least version 0.2.1See the section on version number literals for a more complete description." -}, - -{ - "location": "manual/profile.html#", - "page": "Profiling", - "title": "Profiling", - "category": "page", - "text": "" -}, - -{ - "location": "manual/profile.html#Profiling-1", - "page": "Profiling", - "title": "Profiling", - "category": "section", - "text": "The Profile module provides tools to help developers improve the performance of their code. When used, it takes measurements on running code, and produces output that helps you understand how much time is spent on individual line(s). The most common usage is to identify \"bottlenecks\" as targets for optimization.Profile implements what is known as a \"sampling\" or statistical profiler. It works by periodically taking a backtrace during the execution of any task. Each backtrace captures the currently-running function and line number, plus the complete chain of function calls that led to this line, and hence is a \"snapshot\" of the current state of execution.If much of your run time is spent executing a particular line of code, this line will show up frequently in the set of all backtraces. In other words, the \"cost\" of a given line–or really, the cost of the sequence of function calls up to and including this line–is proportional to how often it appears in the set of all backtraces.A sampling profiler does not provide complete line-by-line coverage, because the backtraces occur at intervals (by default, 1 ms on Unix systems and 10 ms on Windows, although the actual scheduling is subject to operating system load). Moreover, as discussed further below, because samples are collected at a sparse subset of all execution points, the data collected by a sampling profiler is subject to statistical noise.Despite these limitations, sampling profilers have substantial strengths:You do not have to make any modifications to your code to take timing measurements (in contrast to the alternative instrumenting profiler).\nIt can profile into Julia\'s core code and even (optionally) into C and Fortran libraries.\nBy running \"infrequently\" there is very little performance overhead; while profiling, your code can run at nearly native speed.For these reasons, it\'s recommended that you try using the built-in sampling profiler before considering any alternatives." -}, - -{ - "location": "manual/profile.html#Basic-usage-1", - "page": "Profiling", - "title": "Basic usage", - "category": "section", - "text": "Let\'s work with a simple test case:julia> function myfunc()\n A = rand(200, 200, 400)\n maximum(A)\n endIt\'s a good idea to first run the code you intend to profile at least once (unless you want to profile Julia\'s JIT-compiler):julia> myfunc() # run once to force compilationNow we\'re ready to profile this function:julia> @profile myfunc()To see the profiling results, there is a graphical browser available, but here we\'ll use the text-based display that comes with the standard library:julia> Profile.print()\n80 ./event.jl:73; (::Base.REPL.##1#2{Base.REPL.REPLBackend})()\n 80 ./REPL.jl:97; macro expansion\n 80 ./REPL.jl:66; eval_user_input(::Any, ::Base.REPL.REPLBackend)\n 80 ./boot.jl:235; eval(::Module, ::Any)\n 80 ./:?; anonymous\n 80 ./profile.jl:23; macro expansion\n 52 ./REPL[1]:2; myfunc()\n 38 ./random.jl:431; rand!(::MersenneTwister, ::Array{Float64,3}, ::Int64, ::Type{B...\n 38 ./dSFMT.jl:84; dsfmt_fill_array_close_open!(::Base.dSFMT.DSFMT_state, ::Ptr{F...\n 14 ./random.jl:278; rand\n 14 ./random.jl:277; rand\n 14 ./random.jl:366; rand\n 14 ./random.jl:369; rand\n 28 ./REPL[1]:3; myfunc()\n 28 ./reduce.jl:270; _mapreduce(::Base.#identity, ::Base.#scalarmax, ::IndexLinear,...\n 3 ./reduce.jl:426; mapreduce_impl(::Base.#identity, ::Base.#scalarmax, ::Array{F...\n 25 ./reduce.jl:428; mapreduce_impl(::Base.#identity, ::Base.#scalarmax, ::Array{F...Each line of this display represents a particular spot (line number) in the code. Indentation is used to indicate the nested sequence of function calls, with more-indented lines being deeper in the sequence of calls. In each line, the first \"field\" is the number of backtraces (samples) taken at this line or in any functions executed by this line. The second field is the file name and line number and the third field is the function name. Note that the specific line numbers may change as Julia\'s code changes; if you want to follow along, it\'s best to run this example yourself.In this example, we can see that the top level function called is in the file event.jl. This is the function that runs the REPL when you launch Julia. If you examine line 97 of REPL.jl, you\'ll see this is where the function eval_user_input() is called. This is the function that evaluates what you type at the REPL, and since we\'re working interactively these functions were invoked when we entered @profile myfunc(). The next line reflects actions taken in the @profile macro.The first line shows that 80 backtraces were taken at line 73 of event.jl, but it\'s not that this line was \"expensive\" on its own: the third line reveals that all 80 of these backtraces were actually triggered inside its call to eval_user_input, and so on. To find out which operations are actually taking the time, we need to look deeper in the call chain.The first \"important\" line in this output is this one:52 ./REPL[1]:2; myfunc()REPL refers to the fact that we defined myfunc in the REPL, rather than putting it in a file; if we had used a file, this would show the file name. The [1] shows that the function myfunc was the first expression evaluated in this REPL session. Line 2 of myfunc() contains the call to rand, and there were 52 (out of 80) backtraces that occurred at this line. Below that, you can see a call to dsfmt_fill_array_close_open! inside dSFMT.jl.A little further down, you see:28 ./REPL[1]:3; myfunc()Line 3 of myfunc contains the call to maximum, and there were 28 (out of 80) backtraces taken here. Below that, you can see the specific places in base/reduce.jl that carry out the time-consuming operations in the maximum function for this type of input data.Overall, we can tentatively conclude that generating the random numbers is approximately twice as expensive as finding the maximum element. We could increase our confidence in this result by collecting more samples:julia> @profile (for i = 1:100; myfunc(); end)\n\njulia> Profile.print()\n[....]\n 3821 ./REPL[1]:2; myfunc()\n 3511 ./random.jl:431; rand!(::MersenneTwister, ::Array{Float64,3}, ::Int64, ::Type...\n 3511 ./dSFMT.jl:84; dsfmt_fill_array_close_open!(::Base.dSFMT.DSFMT_state, ::Ptr...\n 310 ./random.jl:278; rand\n [....]\n 2893 ./REPL[1]:3; myfunc()\n 2893 ./reduce.jl:270; _mapreduce(::Base.#identity, ::Base.#scalarmax, ::IndexLinea...\n [....]In general, if you have N samples collected at a line, you can expect an uncertainty on the order of sqrt(N) (barring other sources of noise, like how busy the computer is with other tasks). The major exception to this rule is garbage collection, which runs infrequently but tends to be quite expensive. (Since Julia\'s garbage collector is written in C, such events can be detected using the C=true output mode described below, or by using ProfileView.jl.)This illustrates the default \"tree\" dump; an alternative is the \"flat\" dump, which accumulates counts independent of their nesting:julia> Profile.print(format=:flat)\n Count File Line Function\n 6714 ./ -1 anonymous\n 6714 ./REPL.jl 66 eval_user_input(::Any, ::Base.REPL.REPLBackend)\n 6714 ./REPL.jl 97 macro expansion\n 3821 ./REPL[1] 2 myfunc()\n 2893 ./REPL[1] 3 myfunc()\n 6714 ./REPL[7] 1 macro expansion\n 6714 ./boot.jl 235 eval(::Module, ::Any)\n 3511 ./dSFMT.jl 84 dsfmt_fill_array_close_open!(::Base.dSFMT.DSFMT_s...\n 6714 ./event.jl 73 (::Base.REPL.##1#2{Base.REPL.REPLBackend})()\n 6714 ./profile.jl 23 macro expansion\n 3511 ./random.jl 431 rand!(::MersenneTwister, ::Array{Float64,3}, ::In...\n 310 ./random.jl 277 rand\n 310 ./random.jl 278 rand\n 310 ./random.jl 366 rand\n 310 ./random.jl 369 rand\n 2893 ./reduce.jl 270 _mapreduce(::Base.#identity, ::Base.#scalarmax, :...\n 5 ./reduce.jl 420 mapreduce_impl(::Base.#identity, ::Base.#scalarma...\n 253 ./reduce.jl 426 mapreduce_impl(::Base.#identity, ::Base.#scalarma...\n 2592 ./reduce.jl 428 mapreduce_impl(::Base.#identity, ::Base.#scalarma...\n 43 ./reduce.jl 429 mapreduce_impl(::Base.#identity, ::Base.#scalarma...If your code has recursion, one potentially-confusing point is that a line in a \"child\" function can accumulate more counts than there are total backtraces. Consider the following function definitions:dumbsum(n::Integer) = n == 1 ? 1 : 1 + dumbsum(n-1)\ndumbsum3() = dumbsum(3)If you were to profile dumbsum3, and a backtrace was taken while it was executing dumbsum(1), the backtrace would look like this:dumbsum3\n dumbsum(3)\n dumbsum(2)\n dumbsum(1)Consequently, this child function gets 3 counts, even though the parent only gets one. The \"tree\" representation makes this much clearer, and for this reason (among others) is probably the most useful way to view the results." -}, - -{ - "location": "manual/profile.html#Accumulation-and-clearing-1", - "page": "Profiling", - "title": "Accumulation and clearing", - "category": "section", - "text": "Results from @profile accumulate in a buffer; if you run multiple pieces of code under @profile, then Profile.print() will show you the combined results. This can be very useful, but sometimes you want to start fresh; you can do so with Profile.clear()." -}, - -{ - "location": "manual/profile.html#Options-for-controlling-the-display-of-profile-results-1", - "page": "Profiling", - "title": "Options for controlling the display of profile results", - "category": "section", - "text": "Profile.print() has more options than we\'ve described so far. Let\'s see the full declaration:function print(io::IO = STDOUT, data = fetch(); kwargs...)Let\'s first discuss the two positional arguments, and later the keyword arguments:io – Allows you to save the results to a buffer, e.g. a file, but the default is to print to STDOUT (the console).\ndata – Contains the data you want to analyze; by default that is obtained from Profile.fetch(), which pulls out the backtraces from a pre-allocated buffer. For example, if you want to profile the profiler, you could say:\ndata = copy(Profile.fetch())\nProfile.clear()\n@profile Profile.print(STDOUT, data) # Prints the previous results\nProfile.print() # Prints results from Profile.print()The keyword arguments can be any combination of:format – Introduced above, determines whether backtraces are printed with (default, :tree) or without (:flat) indentation indicating tree structure.\nC – If true, backtraces from C and Fortran code are shown (normally they are excluded). Try running the introductory example with Profile.print(C = true). This can be extremely helpful in deciding whether it\'s Julia code or C code that is causing a bottleneck; setting C = true also improves the interpretability of the nesting, at the cost of longer profile dumps.\ncombine – Some lines of code contain multiple operations; for example, s += A[i] contains both an array reference (A[i]) and a sum operation. These correspond to different lines in the generated machine code, and hence there may be two or more different addresses captured during backtraces on this line. combine = true lumps them together, and is probably what you typically want, but you can generate an output separately for each unique instruction pointer with combine = false.\nmaxdepth – Limits frames at a depth higher than maxdepth in the :tree format.\nsortedby – Controls the order in :flat format. :filefuncline (default) sorts by the source line, whereas :count sorts in order of number of collected samples.\nnoisefloor – Limits frames that are below the heuristic noise floor of the sample (only applies to format :tree). A suggested value to try for this is 2.0 (the default is 0). This parameter hides samples for which n <= noisefloor * √N, where n is the number of samples on this line, and N is the number of samples for the callee.\nmincount – Limits frames with less than mincount occurrences.File/function names are sometimes truncated (with ...), and indentation is truncated with a +n at the beginning, where n is the number of extra spaces that would have been inserted, had there been room. If you want a complete profile of deeply-nested code, often a good idea is to save to a file using a wide displaysize in an IOContext:open(\"/tmp/prof.txt\", \"w\") do s\n Profile.print(IOContext(s, :displaysize => (24, 500)))\nend" -}, - -{ - "location": "manual/profile.html#Configuration-1", - "page": "Profiling", - "title": "Configuration", - "category": "section", - "text": "@profile just accumulates backtraces, and the analysis happens when you call Profile.print(). For a long-running computation, it\'s entirely possible that the pre-allocated buffer for storing backtraces will be filled. If that happens, the backtraces stop but your computation continues. As a consequence, you may miss some important profiling data (you will get a warning when that happens).You can obtain and configure the relevant parameters this way:Profile.init() # returns the current settings\nProfile.init(n = 10^7, delay = 0.01)n is the total number of instruction pointers you can store, with a default value of 10^6. If your typical backtrace is 20 instruction pointers, then you can collect 50000 backtraces, which suggests a statistical uncertainty of less than 1%. This may be good enough for most applications.Consequently, you are more likely to need to modify delay, expressed in seconds, which sets the amount of time that Julia gets between snapshots to perform the requested computations. A very long-running job might not need frequent backtraces. The default setting is delay = 0.001. Of course, you can decrease the delay as well as increase it; however, the overhead of profiling grows once the delay becomes similar to the amount of time needed to take a backtrace (~30 microseconds on the author\'s laptop)." -}, - -{ - "location": "manual/profile.html#Memory-allocation-analysis-1", - "page": "Profiling", - "title": "Memory allocation analysis", - "category": "section", - "text": "One of the most common techniques to improve performance is to reduce memory allocation. The total amount of allocation can be measured with @time and @allocated, and specific lines triggering allocation can often be inferred from profiling via the cost of garbage collection that these lines incur. However, sometimes it is more efficient to directly measure the amount of memory allocated by each line of code.To measure allocation line-by-line, start Julia with the --track-allocation= command-line option, for which you can choose none (the default, do not measure allocation), user (measure memory allocation everywhere except Julia\'s core code), or all (measure memory allocation at each line of Julia code). Allocation gets measured for each line of compiled code. When you quit Julia, the cumulative results are written to text files with .mem appended after the file name, residing in the same directory as the source file. Each line lists the total number of bytes allocated. The Coverage package contains some elementary analysis tools, for example to sort the lines in order of number of bytes allocated.In interpreting the results, there are a few important details. Under the user setting, the first line of any function directly called from the REPL will exhibit allocation due to events that happen in the REPL code itself. More significantly, JIT-compilation also adds to allocation counts, because much of Julia\'s compiler is written in Julia (and compilation usually requires memory allocation). The recommended procedure is to force compilation by executing all the commands you want to analyze, then call Profile.clear_malloc_data() to reset all allocation counters. Finally, execute the desired commands and quit Julia to trigger the generation of the .mem files." -}, - -{ - "location": "manual/stacktraces.html#", - "page": "Stack Traces", - "title": "Stack Traces", - "category": "page", - "text": "" -}, - -{ - "location": "manual/stacktraces.html#Stack-Traces-1", - "page": "Stack Traces", - "title": "Stack Traces", - "category": "section", - "text": "The StackTraces module provides simple stack traces that are both human readable and easy to use programmatically." -}, - -{ - "location": "manual/stacktraces.html#Viewing-a-stack-trace-1", - "page": "Stack Traces", - "title": "Viewing a stack trace", - "category": "section", - "text": "The primary function used to obtain a stack trace is stacktrace():julia> stacktrace()\n4-element Array{StackFrame,1}:\n eval(::Module, ::Any) at boot.jl:236\n eval_user_input(::Any, ::Base.REPL.REPLBackend) at REPL.jl:66\n macro expansion at REPL.jl:97 [inlined]\n (::Base.REPL.##1#2{Base.REPL.REPLBackend})() at event.jl:73Calling stacktrace() returns a vector of StackFrame s. For ease of use, the alias StackTrace can be used in place of Vector{StackFrame}. (Examples with [...] indicate that output may vary depending on how the code is run.)julia> example() = stacktrace()\nexample (generic function with 1 method)\n\njulia> example()\n5-element Array{StackFrame,1}:\n example() at REPL[1]:1\n eval(::Module, ::Any) at boot.jl:236\n[...]\n\njulia> @noinline child() = stacktrace()\nchild (generic function with 1 method)\n\njulia> @noinline parent() = child()\nparent (generic function with 1 method)\n\njulia> grandparent() = parent()\ngrandparent (generic function with 1 method)\n\njulia> grandparent()\n7-element Array{StackFrame,1}:\n child() at REPL[3]:1\n parent() at REPL[4]:1\n grandparent() at REPL[5]:1\n[...]Note that when calling stacktrace() you\'ll typically see a frame with eval(...) at boot.jl. When calling stacktrace() from the REPL you\'ll also have a few extra frames in the stack from REPL.jl, usually looking something like this:julia> example() = stacktrace()\nexample (generic function with 1 method)\n\njulia> example()\n5-element Array{StackFrame,1}:\n example() at REPL[1]:1\n eval(::Module, ::Any) at boot.jl:236\n eval_user_input(::Any, ::Base.REPL.REPLBackend) at REPL.jl:66\n macro expansion at REPL.jl:97 [inlined]\n (::Base.REPL.##1#2{Base.REPL.REPLBackend})() at event.jl:73" -}, - -{ - "location": "manual/stacktraces.html#Extracting-useful-information-1", - "page": "Stack Traces", - "title": "Extracting useful information", - "category": "section", - "text": "Each StackFrame contains the function name, file name, line number, lambda info, a flag indicating whether the frame has been inlined, a flag indicating whether it is a C function (by default C functions do not appear in the stack trace), and an integer representation of the pointer returned by backtrace():julia> top_frame = stacktrace()[1]\neval(::Module, ::Any) at boot.jl:236\n\njulia> top_frame.func\n:eval\n\njulia> top_frame.file\nSymbol(\"./boot.jl\")\n\njulia> top_frame.line\n236\n\njulia> top_frame.linfo\nNullable{Core.MethodInstance}(MethodInstance for eval(::Module, ::Any))\n\njulia> top_frame.inlined\nfalse\n\njulia> top_frame.from_c\nfalsejulia> top_frame.pointer\n0x00007f390d152a59This makes stack trace information available programmatically for logging, error handling, and more." -}, - -{ - "location": "manual/stacktraces.html#Error-handling-1", - "page": "Stack Traces", - "title": "Error handling", - "category": "section", - "text": "While having easy access to information about the current state of the callstack can be helpful in many places, the most obvious application is in error handling and debugging.julia> @noinline bad_function() = undeclared_variable\nbad_function (generic function with 1 method)\n\njulia> @noinline example() = try\n bad_function()\n catch\n stacktrace()\n end\nexample (generic function with 1 method)\n\njulia> example()\n5-element Array{StackFrame,1}:\n example() at REPL[2]:4\n eval(::Module, ::Any) at boot.jl:236\n[...]You may notice that in the example above the first stack frame points points at line 4, where stacktrace() is called, rather than line 2, where bad_function is called, and bad_function\'s frame is missing entirely. This is understandable, given that stacktrace() is called from the context of the catch. While in this example it\'s fairly easy to find the actual source of the error, in complex cases tracking down the source of the error becomes nontrivial.This can be remedied by calling catch_stacktrace() instead of stacktrace(). Instead of returning callstack information for the current context, catch_stacktrace() returns stack information for the context of the most recent exception:julia> @noinline bad_function() = undeclared_variable\nbad_function (generic function with 1 method)\n\njulia> @noinline example() = try\n bad_function()\n catch\n catch_stacktrace()\n end\nexample (generic function with 1 method)\n\njulia> example()\n6-element Array{StackFrame,1}:\n bad_function() at REPL[1]:1\n example() at REPL[2]:2\n[...]Notice that the stack trace now indicates the appropriate line number and the missing frame.julia> @noinline child() = error(\"Whoops!\")\nchild (generic function with 1 method)\n\njulia> @noinline parent() = child()\nparent (generic function with 1 method)\n\njulia> @noinline function grandparent()\n try\n parent()\n catch err\n println(\"ERROR: \", err.msg)\n catch_stacktrace()\n end\n end\ngrandparent (generic function with 1 method)\n\njulia> grandparent()\nERROR: Whoops!\n7-element Array{StackFrame,1}:\n child() at REPL[1]:1\n parent() at REPL[2]:1\n grandparent() at REPL[3]:3\n[...]" -}, - -{ - "location": "manual/stacktraces.html#Comparison-with-[backtrace()](@ref)-1", - "page": "Stack Traces", - "title": "Comparison with backtrace()", - "category": "section", - "text": "A call to backtrace() returns a vector of Ptr{Void}, which may then be passed into stacktrace() for translation:julia> trace = backtrace()\n21-element Array{Ptr{Void},1}:\n Ptr{Void} @0x00007f10049d5b2f\n Ptr{Void} @0x00007f0ffeb4d29c\n Ptr{Void} @0x00007f0ffeb4d2a9\n Ptr{Void} @0x00007f1004993fe7\n Ptr{Void} @0x00007f10049a92be\n Ptr{Void} @0x00007f10049a823a\n Ptr{Void} @0x00007f10049a9fb0\n Ptr{Void} @0x00007f10049aa718\n Ptr{Void} @0x00007f10049c0d5e\n Ptr{Void} @0x00007f10049a3286\n Ptr{Void} @0x00007f0ffe9ba3ba\n Ptr{Void} @0x00007f0ffe9ba3d0\n Ptr{Void} @0x00007f1004993fe7\n Ptr{Void} @0x00007f0ded34583d\n Ptr{Void} @0x00007f0ded345a87\n Ptr{Void} @0x00007f1004993fe7\n Ptr{Void} @0x00007f0ded34308f\n Ptr{Void} @0x00007f0ded343320\n Ptr{Void} @0x00007f1004993fe7\n Ptr{Void} @0x00007f10049aeb67\n Ptr{Void} @0x0000000000000000\n\njulia> stacktrace(trace)\n5-element Array{StackFrame,1}:\n backtrace() at error.jl:46\n eval(::Module, ::Any) at boot.jl:236\n eval_user_input(::Any, ::Base.REPL.REPLBackend) at REPL.jl:66\n macro expansion at REPL.jl:97 [inlined]\n (::Base.REPL.##1#2{Base.REPL.REPLBackend})() at event.jl:73Notice that the vector returned by backtrace() had 21 pointers, while the vector returned by stacktrace() only has 5. This is because, by default, stacktrace() removes any lower-level C functions from the stack. If you want to include stack frames from C calls, you can do it like this:julia> stacktrace(trace, true)\n27-element Array{StackFrame,1}:\n jl_backtrace_from_here at stackwalk.c:103\n backtrace() at error.jl:46\n backtrace() at sys.so:?\n jl_call_method_internal at julia_internal.h:248 [inlined]\n jl_apply_generic at gf.c:2215\n do_call at interpreter.c:75\n eval at interpreter.c:215\n eval_body at interpreter.c:519\n jl_interpret_toplevel_thunk at interpreter.c:664\n jl_toplevel_eval_flex at toplevel.c:592\n jl_toplevel_eval_in at builtins.c:614\n eval(::Module, ::Any) at boot.jl:236\n eval(::Module, ::Any) at sys.so:?\n jl_call_method_internal at julia_internal.h:248 [inlined]\n jl_apply_generic at gf.c:2215\n eval_user_input(::Any, ::Base.REPL.REPLBackend) at REPL.jl:66\n ip:0x7f1c707f1846\n jl_call_method_internal at julia_internal.h:248 [inlined]\n jl_apply_generic at gf.c:2215\n macro expansion at REPL.jl:97 [inlined]\n (::Base.REPL.##1#2{Base.REPL.REPLBackend})() at event.jl:73\n ip:0x7f1c707ea1ef\n jl_call_method_internal at julia_internal.h:248 [inlined]\n jl_apply_generic at gf.c:2215\n jl_apply at julia.h:1411 [inlined]\n start_task at task.c:261\n ip:0xffffffffffffffffIndividual pointers returned by backtrace() can be translated into StackFrame s by passing them into StackTraces.lookup():julia> pointer = backtrace()[1];\n\njulia> frame = StackTraces.lookup(pointer)\n1-element Array{StackFrame,1}:\n jl_backtrace_from_here at stackwalk.c:103\n\njulia> println(\"The top frame is from $(frame[1].func)!\")\nThe top frame is from jl_backtrace_from_here!" -}, - -{ - "location": "manual/performance-tips.html#", - "page": "Performance Tips", - "title": "Performance Tips", - "category": "page", - "text": "" -}, - -{ - "location": "manual/performance-tips.html#man-performance-tips-1", - "page": "Performance Tips", - "title": "Performance Tips", - "category": "section", - "text": "In the following sections, we briefly go through a few techniques that can help make your Julia code run as fast as possible." -}, - -{ - "location": "manual/performance-tips.html#Avoid-global-variables-1", - "page": "Performance Tips", - "title": "Avoid global variables", - "category": "section", - "text": "A global variable might have its value, and therefore its type, change at any point. This makes it difficult for the compiler to optimize code using global variables. Variables should be local, or passed as arguments to functions, whenever possible.Any code that is performance critical or being benchmarked should be inside a function.We find that global names are frequently constants, and declaring them as such greatly improves performance:const DEFAULT_VAL = 0Uses of non-constant globals can be optimized by annotating their types at the point of use:global x\ny = f(x::Int + 1)Writing functions is better style. It leads to more reusable code and clarifies what steps are being done, and what their inputs and outputs are.note: Note\nAll code in the REPL is evaluated in global scope, so a variable defined and assigned at toplevel will be a global variable.In the following REPL session:julia> x = 1.0is equivalent to:julia> global x = 1.0so all the performance issues discussed previously apply." -}, - -{ - "location": "manual/performance-tips.html#Measure-performance-with-[@time](@ref)-and-pay-attention-to-memory-allocation-1", - "page": "Performance Tips", - "title": "Measure performance with @time and pay attention to memory allocation", - "category": "section", - "text": "A useful tool for measuring performance is the @time macro. The following example illustrates good working style:julia> function f(n)\n s = 0\n for i = 1:n\n s += i/2\n end\n s\n end\nf (generic function with 1 method)\n\njulia> @time f(1)\n 0.012686 seconds (2.09 k allocations: 103.421 KiB)\n0.5\n\njulia> @time f(10^6)\n 0.021061 seconds (3.00 M allocations: 45.777 MiB, 11.69% gc time)\n2.5000025e11On the first call (@time f(1)), f gets compiled. (If you\'ve not yet used @time in this session, it will also compile functions needed for timing.) You should not take the results of this run seriously. For the second run, note that in addition to reporting the time, it also indicated that a large amount of memory was allocated. This is the single biggest advantage of @time vs. functions like tic() and toc(), which only report time.Unexpected memory allocation is almost always a sign of some problem with your code, usually a problem with type-stability. Consequently, in addition to the allocation itself, it\'s very likely that the code generated for your function is far from optimal. Take such indications seriously and follow the advice below.For more serious benchmarking, consider the BenchmarkTools.jl package which evaluates the function multiple times in order to reduce noise.As a teaser, an improved version of this function allocates no memory (the allocation reported below is due to running the @time macro in global scope) and has an order of magnitude faster execution after the first call:julia> @time f_improved(1)\n 0.007008 seconds (1.32 k allocations: 63.640 KiB)\n0.5\n\njulia> @time f_improved(10^6)\n 0.002997 seconds (6 allocations: 192 bytes)\n2.5000025e11Below you\'ll learn how to spot the problem with f and how to fix it.In some situations, your function may need to allocate memory as part of its operation, and this can complicate the simple picture above. In such cases, consider using one of the tools below to diagnose problems, or write a version of your function that separates allocation from its algorithmic aspects (see Pre-allocating outputs)." -}, - -{ - "location": "manual/performance-tips.html#tools-1", - "page": "Performance Tips", - "title": "Tools", - "category": "section", - "text": "Julia and its package ecosystem includes tools that may help you diagnose problems and improve the performance of your code:Profiling allows you to measure the performance of your running code and identify lines that serve as bottlenecks. For complex projects, the ProfileView package can help you visualize your profiling results.\nUnexpectedly-large memory allocations–as reported by @time, @allocated, or the profiler (through calls to the garbage-collection routines)–hint that there might be issues with your code. If you don\'t see another reason for the allocations, suspect a type problem. You can also start Julia with the --track-allocation=user option and examine the resulting *.mem files to see information about where those allocations occur. See Memory allocation analysis.\n@code_warntype generates a representation of your code that can be helpful in finding expressions that result in type uncertainty. See @code_warntype below.\nThe Lint package can also warn you of certain types of programming errors." -}, - -{ - "location": "manual/performance-tips.html#Avoid-containers-with-abstract-type-parameters-1", - "page": "Performance Tips", - "title": "Avoid containers with abstract type parameters", - "category": "section", - "text": "When working with parameterized types, including arrays, it is best to avoid parameterizing with abstract types where possible.Consider the following:a = Real[] # typeof(a) = Array{Real,1}\nif (f = rand()) < .8\n push!(a, f)\nendBecause a is a an array of abstract type Real, it must be able to hold any Real value. Since Real objects can be of arbitrary size and structure, a must be represented as an array of pointers to individually allocated Real objects. Because f will always be a Float64, we should instead, use:a = Float64[] # typeof(a) = Array{Float64,1}which will create a contiguous block of 64-bit floating-point values that can be manipulated efficiently.See also the discussion under Parametric Types." -}, - -{ - "location": "manual/performance-tips.html#Type-declarations-1", - "page": "Performance Tips", - "title": "Type declarations", - "category": "section", - "text": "In many languages with optional type declarations, adding declarations is the principal way to make code run faster. This is not the case in Julia. In Julia, the compiler generally knows the types of all function arguments, local variables, and expressions. However, there are a few specific instances where declarations are helpful." -}, - -{ - "location": "manual/performance-tips.html#Avoid-fields-with-abstract-type-1", - "page": "Performance Tips", - "title": "Avoid fields with abstract type", - "category": "section", - "text": "Types can be declared without specifying the types of their fields:julia> struct MyAmbiguousType\n a\n endThis allows a to be of any type. This can often be useful, but it does have a downside: for objects of type MyAmbiguousType, the compiler will not be able to generate high-performance code. The reason is that the compiler uses the types of objects, not their values, to determine how to build code. Unfortunately, very little can be inferred about an object of type MyAmbiguousType:julia> b = MyAmbiguousType(\"Hello\")\nMyAmbiguousType(\"Hello\")\n\njulia> c = MyAmbiguousType(17)\nMyAmbiguousType(17)\n\njulia> typeof(b)\nMyAmbiguousType\n\njulia> typeof(c)\nMyAmbiguousTypeb and c have the same type, yet their underlying representation of data in memory is very different. Even if you stored just numeric values in field a, the fact that the memory representation of a UInt8 differs from a Float64 also means that the CPU needs to handle them using two different kinds of instructions. Since the required information is not available in the type, such decisions have to be made at run-time. This slows performance.You can do better by declaring the type of a. Here, we are focused on the case where a might be any one of several types, in which case the natural solution is to use parameters. For example:julia> mutable struct MyType{T<:AbstractFloat}\n a::T\n endThis is a better choice thanjulia> mutable struct MyStillAmbiguousType\n a::AbstractFloat\n endbecause the first version specifies the type of a from the type of the wrapper object. For example:julia> m = MyType(3.2)\nMyType{Float64}(3.2)\n\njulia> t = MyStillAmbiguousType(3.2)\nMyStillAmbiguousType(3.2)\n\njulia> typeof(m)\nMyType{Float64}\n\njulia> typeof(t)\nMyStillAmbiguousTypeThe type of field a can be readily determined from the type of m, but not from the type of t. Indeed, in t it\'s possible to change the type of field a:julia> typeof(t.a)\nFloat64\n\njulia> t.a = 4.5f0\n4.5f0\n\njulia> typeof(t.a)\nFloat32In contrast, once m is constructed, the type of m.a cannot change:julia> m.a = 4.5f0\n4.5f0\n\njulia> typeof(m.a)\nFloat64The fact that the type of m.a is known from m\'s type–coupled with the fact that its type cannot change mid-function–allows the compiler to generate highly-optimized code for objects like m but not for objects like t.Of course, all of this is true only if we construct m with a concrete type. We can break this by explicitly constructing it with an abstract type:julia> m = MyType{AbstractFloat}(3.2)\nMyType{AbstractFloat}(3.2)\n\njulia> typeof(m.a)\nFloat64\n\njulia> m.a = 4.5f0\n4.5f0\n\njulia> typeof(m.a)\nFloat32For all practical purposes, such objects behave identically to those of MyStillAmbiguousType.It\'s quite instructive to compare the sheer amount code generated for a simple functionfunc(m::MyType) = m.a+1usingcode_llvm(func,Tuple{MyType{Float64}})\ncode_llvm(func,Tuple{MyType{AbstractFloat}})\ncode_llvm(func,Tuple{MyType})For reasons of length the results are not shown here, but you may wish to try this yourself. Because the type is fully-specified in the first case, the compiler doesn\'t need to generate any code to resolve the type at run-time. This results in shorter and faster code." -}, - -{ - "location": "manual/performance-tips.html#Avoid-fields-with-abstract-containers-1", - "page": "Performance Tips", - "title": "Avoid fields with abstract containers", - "category": "section", - "text": "The same best practices also work for container types:julia> mutable struct MySimpleContainer{A<:AbstractVector}\n a::A\n end\n\njulia> mutable struct MyAmbiguousContainer{T}\n a::AbstractVector{T}\n endFor example:julia> c = MySimpleContainer(1:3);\n\njulia> typeof(c)\nMySimpleContainer{UnitRange{Int64}}\n\njulia> c = MySimpleContainer([1:3;]);\n\njulia> typeof(c)\nMySimpleContainer{Array{Int64,1}}\n\njulia> b = MyAmbiguousContainer(1:3);\n\njulia> typeof(b)\nMyAmbiguousContainer{Int64}\n\njulia> b = MyAmbiguousContainer([1:3;]);\n\njulia> typeof(b)\nMyAmbiguousContainer{Int64}For MySimpleContainer, the object is fully-specified by its type and parameters, so the compiler can generate optimized functions. In most instances, this will probably suffice.While the compiler can now do its job perfectly well, there are cases where you might wish that your code could do different things depending on the element type of a. Usually the best way to achieve this is to wrap your specific operation (here, foo) in a separate function:julia> function sumfoo(c::MySimpleContainer)\n s = 0\n for x in c.a\n s += foo(x)\n end\n s\n end\nsumfoo (generic function with 1 method)\n\njulia> foo(x::Integer) = x\nfoo (generic function with 1 method)\n\njulia> foo(x::AbstractFloat) = round(x)\nfoo (generic function with 2 methods)This keeps things simple, while allowing the compiler to generate optimized code in all cases.However, there are cases where you may need to declare different versions of the outer function for different element types of a. You could do it like this:function myfun(c::MySimpleContainer{Vector{T}}) where T<:AbstractFloat\n ...\nend\nfunction myfun(c::MySimpleContainer{Vector{T}}) where T<:Integer\n ...\nendThis works fine for Vector{T}, but we\'d also have to write explicit versions for UnitRange{T} or other abstract types. To prevent such tedium, you can use two parameters in the declaration of MyContainer:julia> mutable struct MyContainer{T, A<:AbstractVector}\n a::A\n end\n\njulia> MyContainer(v::AbstractVector) = MyContainer{eltype(v), typeof(v)}(v)\nMyContainer\n\njulia> b = MyContainer(1:5);\n\njulia> typeof(b)\nMyContainer{Int64,UnitRange{Int64}}Note the somewhat surprising fact that T doesn\'t appear in the declaration of field a, a point that we\'ll return to in a moment. With this approach, one can write functions such as:julia> function myfunc(c::MyContainer{<:Integer, <:AbstractArray})\n return c.a[1]+1\n end\nmyfunc (generic function with 1 method)\n\njulia> function myfunc(c::MyContainer{<:AbstractFloat})\n return c.a[1]+2\n end\nmyfunc (generic function with 2 methods)\n\njulia> function myfunc(c::MyContainer{T,Vector{T}}) where T<:Integer\n return c.a[1]+3\n end\nmyfunc (generic function with 3 methods)note: Note\nBecause we can only define MyContainer for A<:AbstractArray, and any unspecified parameters are arbitrary, the first function above could have been written more succinctly as function myfunc{T<:Integer}(c::MyContainer{T})julia> myfunc(MyContainer(1:3))\n2\n\njulia> myfunc(MyContainer(1.0:3))\n3.0\n\njulia> myfunc(MyContainer([1:3;]))\n4As you can see, with this approach it\'s possible to specialize on both the element type T and the array type A.However, there\'s one remaining hole: we haven\'t enforced that A has element type T, so it\'s perfectly possible to construct an object like this:julia> b = MyContainer{Int64, UnitRange{Float64}}(UnitRange(1.3, 5.0));\n\njulia> typeof(b)\nMyContainer{Int64,UnitRange{Float64}}To prevent this, we can add an inner constructor:julia> mutable struct MyBetterContainer{T<:Real, A<:AbstractVector}\n a::A\n MyBetterContainer{T,A}(v::AbstractVector{T}) where {T,A} = new(v)\n end\n\njulia> MyBetterContainer(v::AbstractVector) = MyBetterContainer{eltype(v),typeof(v)}(v)\nMyBetterContainer\n\njulia> b = MyBetterContainer(UnitRange(1.3, 5.0));\n\njulia> typeof(b)\nMyBetterContainer{Float64,UnitRange{Float64}}\n\njulia> b = MyBetterContainer{Int64, UnitRange{Float64}}(UnitRange(1.3, 5.0));\nERROR: MethodError: Cannot `convert` an object of type UnitRange{Float64} to an object of type MyBetterContainer{Int64,UnitRange{Float64}}\n[...]The inner constructor requires that the element type of A be T." -}, - -{ - "location": "manual/performance-tips.html#Annotate-values-taken-from-untyped-locations-1", - "page": "Performance Tips", - "title": "Annotate values taken from untyped locations", - "category": "section", - "text": "It is often convenient to work with data structures that may contain values of any type (arrays of type Array{Any}). But, if you\'re using one of these structures and happen to know the type of an element, it helps to share this knowledge with the compiler:function foo(a::Array{Any,1})\n x = a[1]::Int32\n b = x+1\n ...\nendHere, we happened to know that the first element of a would be an Int32. Making an annotation like this has the added benefit that it will raise a run-time error if the value is not of the expected type, potentially catching certain bugs earlier." -}, - -{ - "location": "manual/performance-tips.html#Declare-types-of-keyword-arguments-1", - "page": "Performance Tips", - "title": "Declare types of keyword arguments", - "category": "section", - "text": "Keyword arguments can have declared types:function with_keyword(x; name::Int = 1)\n ...\nendFunctions are specialized on the types of keyword arguments, so these declarations will not affect performance of code inside the function. However, they will reduce the overhead of calls to the function that include keyword arguments.Functions with keyword arguments have near-zero overhead for call sites that pass only positional arguments.Passing dynamic lists of keyword arguments, as in f(x; keywords...), can be slow and should be avoided in performance-sensitive code." -}, - -{ - "location": "manual/performance-tips.html#Break-functions-into-multiple-definitions-1", - "page": "Performance Tips", - "title": "Break functions into multiple definitions", - "category": "section", - "text": "Writing a function as many small definitions allows the compiler to directly call the most applicable code, or even inline it.Here is an example of a \"compound function\" that should really be written as multiple definitions:function norm(A)\n if isa(A, Vector)\n return sqrt(real(dot(A,A)))\n elseif isa(A, Matrix)\n return maximum(svd(A)[2])\n else\n error(\"norm: invalid argument\")\n end\nendThis can be written more concisely and efficiently as:norm(x::Vector) = sqrt(real(dot(x,x)))\nnorm(A::Matrix) = maximum(svd(A)[2])" -}, - -{ - "location": "manual/performance-tips.html#Write-\"type-stable\"-functions-1", - "page": "Performance Tips", - "title": "Write \"type-stable\" functions", - "category": "section", - "text": "When possible, it helps to ensure that a function always returns a value of the same type. Consider the following definition:pos(x) = x < 0 ? 0 : xAlthough this seems innocent enough, the problem is that 0 is an integer (of type Int) and x might be of any type. Thus, depending on the value of x, this function might return a value of either of two types. This behavior is allowed, and may be desirable in some cases. But it can easily be fixed as follows:pos(x) = x < 0 ? zero(x) : xThere is also a one() function, and a more general oftype(x, y) function, which returns y converted to the type of x." -}, - -{ - "location": "manual/performance-tips.html#Avoid-changing-the-type-of-a-variable-1", - "page": "Performance Tips", - "title": "Avoid changing the type of a variable", - "category": "section", - "text": "An analogous \"type-stability\" problem exists for variables used repeatedly within a function:function foo()\n x = 1\n for i = 1:10\n x = x/bar()\n end\n return x\nendLocal variable x starts as an integer, and after one loop iteration becomes a floating-point number (the result of / operator). This makes it more difficult for the compiler to optimize the body of the loop. There are several possible fixes:Initialize x with x = 1.0\nDeclare the type of x: x::Float64 = 1\nUse an explicit conversion: x = oneunit(T)\nInitialize with the first loop iteration, to x = 1/bar(), then loop for i = 2:10" -}, - -{ - "location": "manual/performance-tips.html#kernal-functions-1", - "page": "Performance Tips", - "title": "Separate kernel functions (aka, function barriers)", - "category": "section", - "text": "Many functions follow a pattern of performing some set-up work, and then running many iterations to perform a core computation. Where possible, it is a good idea to put these core computations in separate functions. For example, the following contrived function returns an array of a randomly-chosen type:DocTestSetup = quote\n srand(1234)\nendjulia> function strange_twos(n)\n a = Vector{rand(Bool) ? Int64 : Float64}(n)\n for i = 1:n\n a[i] = 2\n end\n return a\n end\nstrange_twos (generic function with 1 method)\n\njulia> strange_twos(3)\n3-element Array{Float64,1}:\n 2.0\n 2.0\n 2.0This should be written as:julia> function fill_twos!(a)\n for i=1:length(a)\n a[i] = 2\n end\n end\nfill_twos! (generic function with 1 method)\n\njulia> function strange_twos(n)\n a = Array{rand(Bool) ? Int64 : Float64}(n)\n fill_twos!(a)\n return a\n end\nstrange_twos (generic function with 1 method)\n\njulia> strange_twos(3)\n3-element Array{Float64,1}:\n 2.0\n 2.0\n 2.0Julia\'s compiler specializes code for argument types at function boundaries, so in the original implementation it does not know the type of a during the loop (since it is chosen randomly). Therefore the second version is generally faster since the inner loop can be recompiled as part of fill_twos! for different types of a.The second form is also often better style and can lead to more code reuse.This pattern is used in several places in the standard library. For example, see hvcat_fill in abstractarray.jl, or the fill! function, which we could have used instead of writing our own fill_twos!.Functions like strange_twos occur when dealing with data of uncertain type, for example data loaded from an input file that might contain either integers, floats, strings, or something else." -}, - -{ - "location": "manual/performance-tips.html#Types-with-values-as-parameters-1", - "page": "Performance Tips", - "title": "Types with values-as-parameters", - "category": "section", - "text": "Let\'s say you want to create an N-dimensional array that has size 3 along each axis. Such arrays can be created like this:julia> A = fill(5.0, (3, 3))\n3×3 Array{Float64,2}:\n 5.0 5.0 5.0\n 5.0 5.0 5.0\n 5.0 5.0 5.0This approach works very well: the compiler can figure out that A is an Array{Float64,2} because it knows the type of the fill value (5.0::Float64) and the dimensionality ((3, 3)::NTuple{2,Int}). This implies that the compiler can generate very efficient code for any future usage of A in the same function.But now let\'s say you want to write a function that creates a 3×3×... array in arbitrary dimensions; you might be tempted to write a functionjulia> function array3(fillval, N)\n fill(fillval, ntuple(d->3, N))\n end\narray3 (generic function with 1 method)\n\njulia> array3(5.0, 2)\n3×3 Array{Float64,2}:\n 5.0 5.0 5.0\n 5.0 5.0 5.0\n 5.0 5.0 5.0This works, but (as you can verify for yourself using @code_warntype array3(5.0, 2)) the problem is that the output type cannot be inferred: the argument N is a value of type Int, and type-inference does not (and cannot) predict its value in advance. This means that code using the output of this function has to be conservative, checking the type on each access of A; such code will be very slow.Now, one very good way to solve such problems is by using the function-barrier technique. However, in some cases you might want to eliminate the type-instability altogether. In such cases, one approach is to pass the dimensionality as a parameter, for example through Val{T} (see \"Value types\"):julia> function array3(fillval, ::Type{Val{N}}) where N\n fill(fillval, ntuple(d->3, Val{N}))\n end\narray3 (generic function with 1 method)\n\njulia> array3(5.0, Val{2})\n3×3 Array{Float64,2}:\n 5.0 5.0 5.0\n 5.0 5.0 5.0\n 5.0 5.0 5.0Julia has a specialized version of ntuple that accepts a Val{::Int} as the second parameter; by passing N as a type-parameter, you make its \"value\" known to the compiler. Consequently, this version of array3 allows the compiler to predict the return type.However, making use of such techniques can be surprisingly subtle. For example, it would be of no help if you called array3 from a function like this:function call_array3(fillval, n)\n A = array3(fillval, Val{n})\nendHere, you\'ve created the same problem all over again: the compiler can\'t guess the type of n, so it doesn\'t know the type of Val{n}. Attempting to use Val, but doing so incorrectly, can easily make performance worse in many situations. (Only in situations where you\'re effectively combining Val with the function-barrier trick, to make the kernel function more efficient, should code like the above be used.)An example of correct usage of Val would be:function filter3(A::AbstractArray{T,N}) where {T,N}\n kernel = array3(1, Val{N})\n filter(A, kernel)\nendIn this example, N is passed as a parameter, so its \"value\" is known to the compiler. Essentially, Val{T} works only when T is either hard-coded (Val{3}) or already specified in the type-domain." -}, - -{ - "location": "manual/performance-tips.html#The-dangers-of-abusing-multiple-dispatch-(aka,-more-on-types-with-values-as-parameters)-1", - "page": "Performance Tips", - "title": "The dangers of abusing multiple dispatch (aka, more on types with values-as-parameters)", - "category": "section", - "text": "Once one learns to appreciate multiple dispatch, there\'s an understandable tendency to go crazy and try to use it for everything. For example, you might imagine using it to store information, e.g.struct Car{Make,Model}\n year::Int\n ...more fields...\nendand then dispatch on objects like Car{:Honda,:Accord}(year, args...).This might be worthwhile when the following are true:You require CPU-intensive processing on each Car, and it becomes vastly more efficient if you know the Make and Model at compile time.\nYou have homogenous lists of the same type of Car to process, so that you can store them all in an Array{Car{:Honda,:Accord},N}.When the latter holds, a function processing such a homogenous array can be productively specialized: Julia knows the type of each element in advance (all objects in the container have the same concrete type), so Julia can \"look up\" the correct method calls when the function is being compiled (obviating the need to check at run-time) and thereby emit efficient code for processing the whole list.When these do not hold, then it\'s likely that you\'ll get no benefit; worse, the resulting \"combinatorial explosion of types\" will be counterproductive. If items[i+1] has a different type than item[i], Julia has to look up the type at run-time, search for the appropriate method in method tables, decide (via type intersection) which one matches, determine whether it has been JIT-compiled yet (and do so if not), and then make the call. In essence, you\'re asking the full type- system and JIT-compilation machinery to basically execute the equivalent of a switch statement or dictionary lookup in your own code.Some run-time benchmarks comparing (1) type dispatch, (2) dictionary lookup, and (3) a \"switch\" statement can be found on the mailing list.Perhaps even worse than the run-time impact is the compile-time impact: Julia will compile specialized functions for each different Car{Make, Model}; if you have hundreds or thousands of such types, then every function that accepts such an object as a parameter (from a custom get_year function you might write yourself, to the generic push! function in the standard library) will have hundreds or thousands of variants compiled for it. Each of these increases the size of the cache of compiled code, the length of internal lists of methods, etc. Excess enthusiasm for values-as-parameters can easily waste enormous resources." -}, - -{ - "location": "manual/performance-tips.html#Access-arrays-in-memory-order,-along-columns-1", - "page": "Performance Tips", - "title": "Access arrays in memory order, along columns", - "category": "section", - "text": "Multidimensional arrays in Julia are stored in column-major order. This means that arrays are stacked one column at a time. This can be verified using the vec function or the syntax [:] as shown below (notice that the array is ordered [1 3 2 4], not [1 2 3 4]):julia> x = [1 2; 3 4]\n2×2 Array{Int64,2}:\n 1 2\n 3 4\n\njulia> x[:]\n4-element Array{Int64,1}:\n 1\n 3\n 2\n 4This convention for ordering arrays is common in many languages like Fortran, Matlab, and R (to name a few). The alternative to column-major ordering is row-major ordering, which is the convention adopted by C and Python (numpy) among other languages. Remembering the ordering of arrays can have significant performance effects when looping over arrays. A rule of thumb to keep in mind is that with column-major arrays, the first index changes most rapidly. Essentially this means that looping will be faster if the inner-most loop index is the first to appear in a slice expression.Consider the following contrived example. Imagine we wanted to write a function that accepts a Vector and returns a square Matrix with either the rows or the columns filled with copies of the input vector. Assume that it is not important whether rows or columns are filled with these copies (perhaps the rest of the code can be easily adapted accordingly). We could conceivably do this in at least four ways (in addition to the recommended call to the built-in repmat()):function copy_cols(x::Vector{T}) where T\n n = size(x, 1)\n out = Array{T}(n, n)\n for i = 1:n\n out[:, i] = x\n end\n out\nend\n\nfunction copy_rows(x::Vector{T}) where T\n n = size(x, 1)\n out = Array{T}(n, n)\n for i = 1:n\n out[i, :] = x\n end\n out\nend\n\nfunction copy_col_row(x::Vector{T}) where T\n n = size(x, 1)\n out = Array{T}(n, n)\n for col = 1:n, row = 1:n\n out[row, col] = x[row]\n end\n out\nend\n\nfunction copy_row_col(x::Vector{T}) where T\n n = size(x, 1)\n out = Array{T}(n, n)\n for row = 1:n, col = 1:n\n out[row, col] = x[col]\n end\n out\nendNow we will time each of these functions using the same random 10000 by 1 input vector:julia> x = randn(10000);\n\njulia> fmt(f) = println(rpad(string(f)*\": \", 14, \' \'), @elapsed f(x))\n\njulia> map(fmt, Any[copy_cols, copy_rows, copy_col_row, copy_row_col]);\ncopy_cols: 0.331706323\ncopy_rows: 1.799009911\ncopy_col_row: 0.415630047\ncopy_row_col: 1.721531501Notice that copy_cols is much faster than copy_rows. This is expected because copy_cols respects the column-based memory layout of the Matrix and fills it one column at a time. Additionally, copy_col_row is much faster than copy_row_col because it follows our rule of thumb that the first element to appear in a slice expression should be coupled with the inner-most loop." -}, - -{ - "location": "manual/performance-tips.html#Pre-allocating-outputs-1", - "page": "Performance Tips", - "title": "Pre-allocating outputs", - "category": "section", - "text": "If your function returns an Array or some other complex type, it may have to allocate memory. Unfortunately, oftentimes allocation and its converse, garbage collection, are substantial bottlenecks.Sometimes you can circumvent the need to allocate memory on each function call by preallocating the output. As a trivial example, comparefunction xinc(x)\n return [x, x+1, x+2]\nend\n\nfunction loopinc()\n y = 0\n for i = 1:10^7\n ret = xinc(i)\n y += ret[2]\n end\n y\nendwithfunction xinc!(ret::AbstractVector{T}, x::T) where T\n ret[1] = x\n ret[2] = x+1\n ret[3] = x+2\n nothing\nend\n\nfunction loopinc_prealloc()\n ret = Array{Int}(3)\n y = 0\n for i = 1:10^7\n xinc!(ret, i)\n y += ret[2]\n end\n y\nendTiming results:julia> @time loopinc()\n 0.529894 seconds (40.00 M allocations: 1.490 GiB, 12.14% gc time)\n50000015000000\n\njulia> @time loopinc_prealloc()\n 0.030850 seconds (6 allocations: 288 bytes)\n50000015000000Preallocation has other advantages, for example by allowing the caller to control the \"output\" type from an algorithm. In the example above, we could have passed a SubArray rather than an Array, had we so desired.Taken to its extreme, pre-allocation can make your code uglier, so performance measurements and some judgment may be required. However, for \"vectorized\" (element-wise) functions, the convenient syntax x .= f.(y) can be used for in-place operations with fused loops and no temporary arrays (see the dot syntax for vectorizing functions)." -}, - -{ - "location": "manual/performance-tips.html#More-dots:-Fuse-vectorized-operations-1", - "page": "Performance Tips", - "title": "More dots: Fuse vectorized operations", - "category": "section", - "text": "Julia has a special dot syntax that converts any scalar function into a \"vectorized\" function call, and any operator into a \"vectorized\" operator, with the special property that nested \"dot calls\" are fusing: they are combined at the syntax level into a single loop, without allocating temporary arrays. If you use .= and similar assignment operators, the result can also be stored in-place in a pre-allocated array (see above).In a linear-algebra context, this means that even though operations like vector + vector and vector * scalar are defined, it can be advantageous to instead use vector .+ vector and vector .* scalar because the resulting loops can be fused with surrounding computations. For example, consider the two functions:f(x) = 3x.^2 + 4x + 7x.^3\n\nfdot(x) = @. 3x^2 + 4x + 7x^3 # equivalent to 3 .* x.^2 .+ 4 .* x .+ 7 .* x.^3Both f and fdot compute the same thing. However, fdot (defined with the help of the @. macro) is significantly faster when applied to an array:julia> x = rand(10^6);\n\njulia> @time f(x);\n 0.010986 seconds (18 allocations: 53.406 MiB, 11.45% gc time)\n\njulia> @time fdot(x);\n 0.003470 seconds (6 allocations: 7.630 MiB)\n\njulia> @time f.(x);\n 0.003297 seconds (30 allocations: 7.631 MiB)That is, fdot(x) is three times faster and allocates 1/7 the memory of f(x), because each * and + operation in f(x) allocates a new temporary array and executes in a separate loop. (Of course, if you just do f.(x) then it is as fast as fdot(x) in this example, but in many contexts it is more convenient to just sprinkle some dots in your expressions rather than defining a separate function for each vectorized operation.)" -}, - -{ - "location": "manual/performance-tips.html#Consider-using-views-for-slices-1", - "page": "Performance Tips", - "title": "Consider using views for slices", - "category": "section", - "text": "In Julia, an array \"slice\" expression like array[1:5, :] creates a copy of that data (except on the left-hand side of an assignment, where array[1:5, :] = ... assigns in-place to that portion of array). If you are doing many operations on the slice, this can be good for performance because it is more efficient to work with a smaller contiguous copy than it would be to index into the original array. On the other hand, if you are just doing a few simple operations on the slice, the cost of the allocation and copy operations can be substantial.An alternative is to create a \"view\" of the array, which is an array object (a SubArray) that actually references the data of the original array in-place, without making a copy. (If you write to a view, it modifies the original array\'s data as well.) This can be done for individual slices by calling view(), or more simply for a whole expression or block of code by putting @views in front of that expression. For example:julia> fcopy(x) = sum(x[2:end-1])\n\njulia> @views fview(x) = sum(x[2:end-1])\n\njulia> x = rand(10^6);\n\njulia> @time fcopy(x);\n 0.003051 seconds (7 allocations: 7.630 MB)\n\njulia> @time fview(x);\n 0.001020 seconds (6 allocations: 224 bytes)Notice both the 3× speedup and the decreased memory allocation of the fview version of the function." -}, - -{ - "location": "manual/performance-tips.html#Avoid-string-interpolation-for-I/O-1", - "page": "Performance Tips", - "title": "Avoid string interpolation for I/O", - "category": "section", - "text": "When writing data to a file (or other I/O device), forming extra intermediate strings is a source of overhead. Instead of:println(file, \"$a $b\")use:println(file, a, \" \", b)The first version of the code forms a string, then writes it to the file, while the second version writes values directly to the file. Also notice that in some cases string interpolation can be harder to read. Consider:println(file, \"$(f(a))$(f(b))\")versus:println(file, f(a), f(b))" -}, - -{ - "location": "manual/performance-tips.html#Optimize-network-I/O-during-parallel-execution-1", - "page": "Performance Tips", - "title": "Optimize network I/O during parallel execution", - "category": "section", - "text": "When executing a remote function in parallel:responses = Vector{Any}(nworkers())\n@sync begin\n for (idx, pid) in enumerate(workers())\n @async responses[idx] = remotecall_fetch(pid, foo, args...)\n end\nendis faster than:refs = Vector{Any}(nworkers())\nfor (idx, pid) in enumerate(workers())\n refs[idx] = @spawnat pid foo(args...)\nend\nresponses = [fetch(r) for r in refs]The former results in a single network round-trip to every worker, while the latter results in two network calls - first by the @spawnat and the second due to the fetch (or even a wait). The fetch/wait is also being executed serially resulting in an overall poorer performance." -}, - -{ - "location": "manual/performance-tips.html#Fix-deprecation-warnings-1", - "page": "Performance Tips", - "title": "Fix deprecation warnings", - "category": "section", - "text": "A deprecated function internally performs a lookup in order to print a relevant warning only once. This extra lookup can cause a significant slowdown, so all uses of deprecated functions should be modified as suggested by the warnings." -}, - -{ - "location": "manual/performance-tips.html#Tweaks-1", - "page": "Performance Tips", - "title": "Tweaks", - "category": "section", - "text": "These are some minor points that might help in tight inner loops.Avoid unnecessary arrays. For example, instead of sum([x,y,z]) use x+y+z.\nUse abs2(z) instead of abs(z)^2 for complex z. In general, try to rewrite code to use abs2() instead of abs() for complex arguments.\nUse div(x,y) for truncating division of integers instead of trunc(x/y), fld(x,y) instead of floor(x/y), and cld(x,y) instead of ceil(x/y)." -}, - -{ - "location": "manual/performance-tips.html#Performance-Annotations-1", - "page": "Performance Tips", - "title": "Performance Annotations", - "category": "section", - "text": "Sometimes you can enable better optimization by promising certain program properties.Use @inbounds to eliminate array bounds checking within expressions. Be certain before doing this. If the subscripts are ever out of bounds, you may suffer crashes or silent corruption.\nUse @fastmath to allow floating point optimizations that are correct for real numbers, but lead to differences for IEEE numbers. Be careful when doing this, as this may change numerical results. This corresponds to the -ffast-math option of clang.\nWrite @simd in front of for loops that are amenable to vectorization. This feature is experimental and could change or disappear in future versions of Julia.Note: While @simd needs to be placed directly in front of a loop, both @inbounds and @fastmath can be applied to several statements at once, e.g. using begin ... end, or even to a whole function.Here is an example with both @inbounds and @simd markup:function inner(x, y)\n s = zero(eltype(x))\n for i=1:length(x)\n @inbounds s += x[i]*y[i]\n end\n s\nend\n\nfunction innersimd(x, y)\n s = zero(eltype(x))\n @simd for i=1:length(x)\n @inbounds s += x[i]*y[i]\n end\n s\nend\n\nfunction timeit(n, reps)\n x = rand(Float32,n)\n y = rand(Float32,n)\n s = zero(Float64)\n time = @elapsed for j in 1:reps\n s+=inner(x,y)\n end\n println(\"GFlop/sec = \",2.0*n*reps/time*1E-9)\n time = @elapsed for j in 1:reps\n s+=innersimd(x,y)\n end\n println(\"GFlop/sec (SIMD) = \",2.0*n*reps/time*1E-9)\nend\n\ntimeit(1000,1000)On a computer with a 2.4GHz Intel Core i5 processor, this produces:GFlop/sec = 1.9467069505224963\nGFlop/sec (SIMD) = 17.578554163920018(GFlop/sec measures the performance, and larger numbers are better.) The range for a @simd for loop should be a one-dimensional range. A variable used for accumulating, such as s in the example, is called a reduction variable. By using @simd, you are asserting several properties of the loop:It is safe to execute iterations in arbitrary or overlapping order, with special consideration for reduction variables.\nFloating-point operations on reduction variables can be reordered, possibly causing different results than without @simd.\nNo iteration ever waits on another iteration to make forward progress.A loop containing break, continue, or @goto will cause a compile-time error.Using @simd merely gives the compiler license to vectorize. Whether it actually does so depends on the compiler. To actually benefit from the current implementation, your loop should have the following additional properties:The loop must be an innermost loop.\nThe loop body must be straight-line code. This is why @inbounds is currently needed for all array accesses. The compiler can sometimes turn short &&, ||, and ?: expressions into straight-line code, if it is safe to evaluate all operands unconditionally. Consider using ifelse() instead of ?: in the loop if it is safe to do so.\nAccesses must have a stride pattern and cannot be \"gathers\" (random-index reads) or \"scatters\" (random-index writes).\nThe stride should be unit stride.\nIn some simple cases, for example with 2-3 arrays accessed in a loop, the LLVM auto-vectorization may kick in automatically, leading to no further speedup with @simd.Here is an example with all three kinds of markup. This program first calculates the finite difference of a one-dimensional array, and then evaluates the L2-norm of the result:function init!(u)\n n = length(u)\n dx = 1.0 / (n-1)\n @fastmath @inbounds @simd for i in 1:n\n u[i] = sin(2pi*dx*i)\n end\nend\n\nfunction deriv!(u, du)\n n = length(u)\n dx = 1.0 / (n-1)\n @fastmath @inbounds du[1] = (u[2] - u[1]) / dx\n @fastmath @inbounds @simd for i in 2:n-1\n du[i] = (u[i+1] - u[i-1]) / (2*dx)\n end\n @fastmath @inbounds du[n] = (u[n] - u[n-1]) / dx\nend\n\nfunction norm(u)\n n = length(u)\n T = eltype(u)\n s = zero(T)\n @fastmath @inbounds @simd for i in 1:n\n s += u[i]^2\n end\n @fastmath @inbounds return sqrt(s/n)\nend\n\nfunction main()\n n = 2000\n u = Array{Float64}(n)\n init!(u)\n du = similar(u)\n\n deriv!(u, du)\n nu = norm(du)\n\n @time for i in 1:10^6\n deriv!(u, du)\n nu = norm(du)\n end\n\n println(nu)\nend\n\nmain()On a computer with a 2.7 GHz Intel Core i7 processor, this produces:$ julia wave.jl;\nelapsed time: 1.207814709 seconds (0 bytes allocated)\n\n$ julia --math-mode=ieee wave.jl;\nelapsed time: 4.487083643 seconds (0 bytes allocated)Here, the option --math-mode=ieee disables the @fastmath macro, so that we can compare results.In this case, the speedup due to @fastmath is a factor of about 3.7. This is unusually large – in general, the speedup will be smaller. (In this particular example, the working set of the benchmark is small enough to fit into the L1 cache of the processor, so that memory access latency does not play a role, and computing time is dominated by CPU usage. In many real world programs this is not the case.) Also, in this case this optimization does not change the result – in general, the result will be slightly different. In some cases, especially for numerically unstable algorithms, the result can be very different.The annotation @fastmath re-arranges floating point expressions, e.g. changing the order of evaluation, or assuming that certain special cases (inf, nan) cannot occur. In this case (and on this particular computer), the main difference is that the expression 1 / (2*dx) in the function deriv is hoisted out of the loop (i.e. calculated outside the loop), as if one had written idx = 1 / (2*dx). In the loop, the expression ... / (2*dx) then becomes ... * idx, which is much faster to evaluate. Of course, both the actual optimization that is applied by the compiler as well as the resulting speedup depend very much on the hardware. You can examine the change in generated code by using Julia\'s code_native() function." -}, - -{ - "location": "manual/performance-tips.html#Treat-Subnormal-Numbers-as-Zeros-1", - "page": "Performance Tips", - "title": "Treat Subnormal Numbers as Zeros", - "category": "section", - "text": "Subnormal numbers, formerly called denormal numbers, are useful in many contexts, but incur a performance penalty on some hardware. A call set_zero_subnormals(true) grants permission for floating-point operations to treat subnormal inputs or outputs as zeros, which may improve performance on some hardware. A call set_zero_subnormals(false) enforces strict IEEE behavior for subnormal numbers.Below is an example where subnormals noticeably impact performance on some hardware:function timestep(b::Vector{T}, a::Vector{T}, Δt::T) where T\n @assert length(a)==length(b)\n n = length(b)\n b[1] = 1 # Boundary condition\n for i=2:n-1\n b[i] = a[i] + (a[i-1] - T(2)*a[i] + a[i+1]) * Δt\n end\n b[n] = 0 # Boundary condition\nend\n\nfunction heatflow(a::Vector{T}, nstep::Integer) where T\n b = similar(a)\n for t=1:div(nstep,2) # Assume nstep is even\n timestep(b,a,T(0.1))\n timestep(a,b,T(0.1))\n end\nend\n\nheatflow(zeros(Float32,10),2) # Force compilation\nfor trial=1:6\n a = zeros(Float32,1000)\n set_zero_subnormals(iseven(trial)) # Odd trials use strict IEEE arithmetic\n @time heatflow(a,1000)\nendThis example generates many subnormal numbers because the values in a become an exponentially decreasing curve, which slowly flattens out over time.Treating subnormals as zeros should be used with caution, because doing so breaks some identities, such as x-y == 0 implies x == y:julia> x = 3f-38; y = 2f-38;\n\njulia> set_zero_subnormals(true); (x - y, x == y)\n(0.0f0, false)\n\njulia> set_zero_subnormals(false); (x - y, x == y)\n(1.0000001f-38, false)In some applications, an alternative to zeroing subnormal numbers is to inject a tiny bit of noise. For example, instead of initializing a with zeros, initialize it with:a = rand(Float32,1000) * 1.f-9" -}, - -{ - "location": "manual/performance-tips.html#man-code-warntype-1", - "page": "Performance Tips", - "title": "@code_warntype", - "category": "section", - "text": "The macro @code_warntype (or its function variant code_warntype()) can sometimes be helpful in diagnosing type-related problems. Here\'s an example:pos(x) = x < 0 ? 0 : x\n\nfunction f(x)\n y = pos(x)\n sin(y*x+1)\nend\n\njulia> @code_warntype f(3.2)\nVariables:\n #self#::#f\n x::Float64\n y::UNION{FLOAT64,INT64}\n fy::Float64\n #temp#@_5::UNION{FLOAT64,INT64}\n #temp#@_6::Core.MethodInstance\n #temp#@_7::Float64\n\nBody:\n begin\n $(Expr(:inbounds, false))\n # meta: location REPL[1] pos 1\n # meta: location float.jl < 487\n fy::Float64 = (Core.typeassert)((Base.sitofp)(Float64,0)::Float64,Float64)::Float64\n # meta: pop location\n unless (Base.or_int)((Base.lt_float)(x::Float64,fy::Float64)::Bool,(Base.and_int)((Base.and_int)((Base.eq_float)(x::Float64,fy::Float64)::Bool,(Base.lt_float)(fy::Float64,9.223372036854776e18)::Bool)::Bool,(Base.slt_int)((Base.fptosi)(Int64,fy::Float64)::Int64,0)::Bool)::Bool)::Bool goto 9\n #temp#@_5::UNION{FLOAT64,INT64} = 0\n goto 11\n 9:\n #temp#@_5::UNION{FLOAT64,INT64} = x::Float64\n 11:\n # meta: pop location\n $(Expr(:inbounds, :pop))\n y::UNION{FLOAT64,INT64} = #temp#@_5::UNION{FLOAT64,INT64} # line 3:\n unless (y::UNION{FLOAT64,INT64} isa Int64)::ANY goto 19\n #temp#@_6::Core.MethodInstance = MethodInstance for *(::Int64, ::Float64)\n goto 28\n 19:\n unless (y::UNION{FLOAT64,INT64} isa Float64)::ANY goto 23\n #temp#@_6::Core.MethodInstance = MethodInstance for *(::Float64, ::Float64)\n goto 28\n 23:\n goto 25\n 25:\n #temp#@_7::Float64 = (y::UNION{FLOAT64,INT64} * x::Float64)::Float64\n goto 30\n 28:\n #temp#@_7::Float64 = $(Expr(:invoke, :(#temp#@_6), :(Main.*), :(y), :(x)))\n 30:\n return $(Expr(:invoke, MethodInstance for sin(::Float64), :(Main.sin), :((Base.add_float)(#temp#@_7,(Base.sitofp)(Float64,1)::Float64)::Float64)))\n end::Float64Interpreting the output of @code_warntype, like that of its cousins @code_lowered, @code_typed, @code_llvm, and @code_native, takes a little practice. Your code is being presented in form that has been partially digested on its way to generating compiled machine code. Most of the expressions are annotated by a type, indicated by the ::T (where T might be Float64, for example). The most important characteristic of @code_warntype is that non-concrete types are displayed in red; in the above example, such output is shown in all-caps.The top part of the output summarizes the type information for the different variables internal to the function. You can see that y, one of the variables you created, is a Union{Int64,Float64}, due to the type-instability of pos. There is another variable, _var4, which you can see also has the same type.The next lines represent the body of f. The lines starting with a number followed by a colon (1:, 2:) are labels, and represent targets for jumps (via goto) in your code. Looking at the body, you can see that pos has been inlined into f–everything before 2: comes from code defined in pos.Starting at 2:, the variable y is defined, and again annotated as a Union type. Next, we see that the compiler created the temporary variable _var1 to hold the result of y*x. Because a Float64 times either an Int64 or Float64 yields a Float64, all type-instability ends here. The net result is that f(x::Float64) will not be type-unstable in its output, even if some of the intermediate computations are type-unstable.How you use this information is up to you. Obviously, it would be far and away best to fix pos to be type-stable: if you did so, all of the variables in f would be concrete, and its performance would be optimal. However, there are circumstances where this kind of ephemeral type instability might not matter too much: for example, if pos is never used in isolation, the fact that f\'s output is type-stable (for Float64 inputs) will shield later code from the propagating effects of type instability. This is particularly relevant in cases where fixing the type instability is difficult or impossible: for example, currently it\'s not possible to infer the return type of an anonymous function. In such cases, the tips above (e.g., adding type annotations and/or breaking up functions) are your best tools to contain the \"damage\" from type instability.The following examples may help you interpret expressions marked as containing non-leaf types:Function body ending in end::Union{T1,T2})\nInterpretation: function with unstable return type\nSuggestion: make the return value type-stable, even if you have to annotate it\nf(x::T)::Union{T1,T2}\nInterpretation: call to a type-unstable function\nSuggestion: fix the function, or if necessary annotate the return value\n(top(arrayref))(A::Array{Any,1},1)::Any\nInterpretation: accessing elements of poorly-typed arrays\nSuggestion: use arrays with better-defined types, or if necessary annotate the type of individual element accesses\n(top(getfield))(A::ArrayContainer{Float64},:data)::Array{Float64,N}\nInterpretation: getting a field that is of non-leaf type. In this case, ArrayContainer had a field data::Array{T}. But Array needs the dimension N, too, to be a concrete type.\nSuggestion: use concrete types like Array{T,3} or Array{T,N}, where N is now a parameter of ArrayContainer" -}, - -{ - "location": "manual/workflow-tips.html#", - "page": "Workflow Tips", - "title": "Workflow Tips", - "category": "page", - "text": "" -}, - -{ - "location": "manual/workflow-tips.html#man-workflow-tips-1", - "page": "Workflow Tips", - "title": "Workflow Tips", - "category": "section", - "text": "Here are some tips for working with Julia efficiently." -}, - -{ - "location": "manual/workflow-tips.html#REPL-based-workflow-1", - "page": "Workflow Tips", - "title": "REPL-based workflow", - "category": "section", - "text": "As already elaborated in Interacting With Julia, Julia\'s REPL provides rich functionality that facilitates an efficient interactive workflow. Here are some tips that might further enhance your experience at the command line." -}, - -{ - "location": "manual/workflow-tips.html#A-basic-editor/REPL-workflow-1", - "page": "Workflow Tips", - "title": "A basic editor/REPL workflow", - "category": "section", - "text": "The most basic Julia workflows involve using a text editor in conjunction with the julia command line. A common pattern includes the following elements:Put code under development in a temporary module. Create a file, say Tmp.jl, and include within it\nmodule Tmp\n\n\n\nend\nPut your test code in another file. Create another file, say tst.jl, which begins with\nimport Tmp\nand includes tests for the contents of Tmp. The value of using import versus using is that you can call reload(\"Tmp\") instead of having to restart the REPL when your definitions change. Of course, the cost is the need to prepend Tmp. to uses of names defined in your module. (You can lower that cost by keeping your module name short.)\nAlternatively, you can wrap the contents of your test file in a module, as\nmodule Tst\n using Tmp\n\n \n\nend\nThe advantage is that you can now do using Tmp in your test code and can therefore avoid prepending Tmp. everywhere. The disadvantage is that code can no longer be selectively copied to the REPL without some tweaking.\nLather. Rinse. Repeat. Explore ideas at the julia command prompt. Save good ideas in tst.jl. Occasionally restart the REPL, issuing\nreload(\"Tmp\")\ninclude(\"tst.jl\")" -}, - -{ - "location": "manual/workflow-tips.html#Simplify-initialization-1", - "page": "Workflow Tips", - "title": "Simplify initialization", - "category": "section", - "text": "To simplify restarting the REPL, put project-specific initialization code in a file, say _init.jl, which you can run on startup by issuing the command:julia -L _init.jlIf you further add the following to your .juliarc.jl fileisfile(\"_init.jl\") && include(joinpath(pwd(), \"_init.jl\"))then calling julia from that directory will run the initialization code without the additional command line argument." -}, - -{ - "location": "manual/workflow-tips.html#Browser-based-workflow-1", - "page": "Workflow Tips", - "title": "Browser-based workflow", - "category": "section", - "text": "It is also possible to interact with a Julia REPL in the browser via IJulia. See the package home for details." -}, - -{ - "location": "manual/style-guide.html#", - "page": "Style Guide", - "title": "Style Guide", - "category": "page", - "text": "" -}, - -{ - "location": "manual/style-guide.html#Style-Guide-1", - "page": "Style Guide", - "title": "Style Guide", - "category": "section", - "text": "The following sections explain a few aspects of idiomatic Julia coding style. None of these rules are absolute; they are only suggestions to help familiarize you with the language and to help you choose among alternative designs." -}, - -{ - "location": "manual/style-guide.html#Write-functions,-not-just-scripts-1", - "page": "Style Guide", - "title": "Write functions, not just scripts", - "category": "section", - "text": "Writing code as a series of steps at the top level is a quick way to get started solving a problem, but you should try to divide a program into functions as soon as possible. Functions are more reusable and testable, and clarify what steps are being done and what their inputs and outputs are. Furthermore, code inside functions tends to run much faster than top level code, due to how Julia\'s compiler works.It is also worth emphasizing that functions should take arguments, instead of operating directly on global variables (aside from constants like pi)." -}, - -{ - "location": "manual/style-guide.html#Avoid-writing-overly-specific-types-1", - "page": "Style Guide", - "title": "Avoid writing overly-specific types", - "category": "section", - "text": "Code should be as generic as possible. Instead of writing:convert(Complex{Float64}, x)it\'s better to use available generic functions:complex(float(x))The second version will convert x to an appropriate type, instead of always the same type.This style point is especially relevant to function arguments. For example, don\'t declare an argument to be of type Int or Int32 if it really could be any integer, expressed with the abstract type Integer. In fact, in many cases you can omit the argument type altogether, unless it is needed to disambiguate from other method definitions, since a MethodError will be thrown anyway if a type is passed that does not support any of the requisite operations. (This is known as duck typing.)For example, consider the following definitions of a function addone that returns one plus its argument:addone(x::Int) = x + 1 # works only for Int\naddone(x::Integer) = x + oneunit(x) # any integer type\naddone(x::Number) = x + oneunit(x) # any numeric type\naddone(x) = x + oneunit(x) # any type supporting + and oneunitThe last definition of addone handles any type supporting oneunit (which returns 1 in the same type as x, which avoids unwanted type promotion) and the + function with those arguments. The key thing to realize is that there is no performance penalty to defining only the general addone(x) = x + oneunit(x), because Julia will automatically compile specialized versions as needed. For example, the first time you call addone(12), Julia will automatically compile a specialized addone function for x::Int arguments, with the call to oneunit replaced by its inlined value 1. Therefore, the first three definitions of addone above are completely redundant with the fourth definition." -}, - -{ - "location": "manual/style-guide.html#Handle-excess-argument-diversity-in-the-caller-1", - "page": "Style Guide", - "title": "Handle excess argument diversity in the caller", - "category": "section", - "text": "Instead of:function foo(x, y)\n x = Int(x); y = Int(y)\n ...\nend\nfoo(x, y)use:function foo(x::Int, y::Int)\n ...\nend\nfoo(Int(x), Int(y))This is better style because foo does not really accept numbers of all types; it really needs Int s.One issue here is that if a function inherently requires integers, it might be better to force the caller to decide how non-integers should be converted (e.g. floor or ceiling). Another issue is that declaring more specific types leaves more \"space\" for future method definitions." -}, - -{ - "location": "manual/style-guide.html#Append-!-to-names-of-functions-that-modify-their-arguments-1", - "page": "Style Guide", - "title": "Append ! to names of functions that modify their arguments", - "category": "section", - "text": "Instead of:function double(a::AbstractArray{<:Number})\n for i = 1:endof(a)\n a[i] *= 2\n end\n return a\nenduse:function double!(a::AbstractArray{<:Number})\n for i = 1:endof(a)\n a[i] *= 2\n end\n return a\nendThe Julia standard library uses this convention throughout and contains examples of functions with both copying and modifying forms (e.g., sort() and sort!()), and others which are just modifying (e.g., push!(), pop!(), splice!()). It is typical for such functions to also return the modified array for convenience." -}, - -{ - "location": "manual/style-guide.html#Avoid-strange-type-Unions-1", - "page": "Style Guide", - "title": "Avoid strange type Unions", - "category": "section", - "text": "Types such as Union{Function,AbstractString} are often a sign that some design could be cleaner." -}, - -{ - "location": "manual/style-guide.html#Avoid-type-Unions-in-fields-1", - "page": "Style Guide", - "title": "Avoid type Unions in fields", - "category": "section", - "text": "When creating a type such as:mutable struct MyType\n ...\n x::Union{Void,T}\nendask whether the option for x to be nothing (of type Void) is really necessary. Here are some alternatives to consider:Find a safe default value to initialize x with\nIntroduce another type that lacks x\nIf there are many fields like x, store them in a dictionary\nDetermine whether there is a simple rule for when x is nothing. For example, often the field will start as nothing but get initialized at some well-defined point. In that case, consider leaving it undefined at first.\nIf x really needs to hold no value at some times, define it as ::Nullable{T} instead, as this guarantees type-stability in the code accessing this field (see Nullable types)." -}, - -{ - "location": "manual/style-guide.html#Avoid-elaborate-container-types-1", - "page": "Style Guide", - "title": "Avoid elaborate container types", - "category": "section", - "text": "It is usually not much help to construct arrays like the following:a = Array{Union{Int,AbstractString,Tuple,Array}}(n)In this case Array{Any}(n) is better. It is also more helpful to the compiler to annotate specific uses (e.g. a[i]::Int) than to try to pack many alternatives into one type." -}, - -{ - "location": "manual/style-guide.html#Use-naming-conventions-consistent-with-Julia\'s-base/-1", - "page": "Style Guide", - "title": "Use naming conventions consistent with Julia\'s base/", - "category": "section", - "text": "modules and type names use capitalization and camel case: module SparseArrays, struct UnitRange.\nfunctions are lowercase (maximum(), convert()) and, when readable, with multiple words squashed together (isequal(), haskey()). When necessary, use underscores as word separators. Underscores are also used to indicate a combination of concepts (remotecall_fetch() as a more efficient implementation of fetch(remotecall(...))) or as modifiers (sum_kbn()).\nconciseness is valued, but avoid abbreviation (indexin() rather than indxin()) as it becomes difficult to remember whether and how particular words are abbreviated.If a function name requires multiple words, consider whether it might represent more than one concept and might be better split into pieces." -}, - -{ - "location": "manual/style-guide.html#Don\'t-overuse-try-catch-1", - "page": "Style Guide", - "title": "Don\'t overuse try-catch", - "category": "section", - "text": "It is better to avoid errors than to rely on catching them." -}, - -{ - "location": "manual/style-guide.html#Don\'t-parenthesize-conditions-1", - "page": "Style Guide", - "title": "Don\'t parenthesize conditions", - "category": "section", - "text": "Julia doesn\'t require parens around conditions in if and while. Write:if a == binstead of:if (a == b)" -}, - -{ - "location": "manual/style-guide.html#Don\'t-overuse-...-1", - "page": "Style Guide", - "title": "Don\'t overuse ...", - "category": "section", - "text": "Splicing function arguments can be addictive. Instead of [a..., b...], use simply [a; b], which already concatenates arrays. collect(a) is better than [a...], but since a is already iterable it is often even better to leave it alone, and not convert it to an array." -}, - -{ - "location": "manual/style-guide.html#Don\'t-use-unnecessary-static-parameters-1", - "page": "Style Guide", - "title": "Don\'t use unnecessary static parameters", - "category": "section", - "text": "A function signature:foo(x::T) where {T<:Real} = ...should be written as:foo(x::Real) = ...instead, especially if T is not used in the function body. Even if T is used, it can be replaced with typeof(x) if convenient. There is no performance difference. Note that this is not a general caution against static parameters, just against uses where they are not needed.Note also that container types, specifically may need type parameters in function calls. See the FAQ Avoid fields with abstract containers for more information." -}, - -{ - "location": "manual/style-guide.html#Avoid-confusion-about-whether-something-is-an-instance-or-a-type-1", - "page": "Style Guide", - "title": "Avoid confusion about whether something is an instance or a type", - "category": "section", - "text": "Sets of definitions like the following are confusing:foo(::Type{MyType}) = ...\nfoo(::MyType) = foo(MyType)Decide whether the concept in question will be written as MyType or MyType(), and stick to it.The preferred style is to use instances by default, and only add methods involving Type{MyType} later if they become necessary to solve some problem.If a type is effectively an enumeration, it should be defined as a single (ideally immutable struct or primitive) type, with the enumeration values being instances of it. Constructors and conversions can check whether values are valid. This design is preferred over making the enumeration an abstract type, with the \"values\" as subtypes." -}, - -{ - "location": "manual/style-guide.html#Don\'t-overuse-macros-1", - "page": "Style Guide", - "title": "Don\'t overuse macros", - "category": "section", - "text": "Be aware of when a macro could really be a function instead.Calling eval() inside a macro is a particularly dangerous warning sign; it means the macro will only work when called at the top level. If such a macro is written as a function instead, it will naturally have access to the run-time values it needs." -}, - -{ - "location": "manual/style-guide.html#Don\'t-expose-unsafe-operations-at-the-interface-level-1", - "page": "Style Guide", - "title": "Don\'t expose unsafe operations at the interface level", - "category": "section", - "text": "If you have a type that uses a native pointer:mutable struct NativeType\n p::Ptr{UInt8}\n ...\nenddon\'t write definitions like the following:getindex(x::NativeType, i) = unsafe_load(x.p, i)The problem is that users of this type can write x[i] without realizing that the operation is unsafe, and then be susceptible to memory bugs.Such a function should either check the operation to ensure it is safe, or have unsafe somewhere in its name to alert callers." -}, - -{ - "location": "manual/style-guide.html#Don\'t-overload-methods-of-base-container-types-1", - "page": "Style Guide", - "title": "Don\'t overload methods of base container types", - "category": "section", - "text": "It is possible to write definitions like the following:show(io::IO, v::Vector{MyType}) = ...This would provide custom showing of vectors with a specific new element type. While tempting, this should be avoided. The trouble is that users will expect a well-known type like Vector() to behave in a certain way, and overly customizing its behavior can make it harder to work with." -}, - -{ - "location": "manual/style-guide.html#Avoid-type-piracy-1", - "page": "Style Guide", - "title": "Avoid type piracy", - "category": "section", - "text": "\"Type piracy\" refers to the practice of extending or redefining methods in Base or other packages on types that you have not defined. In some cases, you can get away with type piracy with little ill effect. In extreme cases, however, you can even crash Julia (e.g. if your method extension or redefinition causes invalid input to be passed to a ccall). Type piracy can complicate reasoning about code, and may introduce incompatibilities that are hard to predict and diagnose.As an example, suppose you wanted to define multiplication on symbols in a module:module A\nimport Base.*\n*(x::Symbol, y::Symbol) = Symbol(x,y)\nendThe problem is that now any other module that uses Base.* will also see this definition. Since Symbol is defined in Base and is used by other modules, this can change the behavior of unrelated code unexpectedly. There are several alternatives here, including using a different function name, or wrapping the Symbols in another type that you define.Sometimes, coupled packages may engage in type piracy to separate features from definitions, especially when the packages were designed by collaborating authors, and when the definitions are reusable. For example, one package might provide some types useful for working with colors; another package could define methods for those types that enable conversions between color spaces. Another example might be a package that acts as a thin wrapper for some C code, which another package might then pirate to implement a higher-level, Julia-friendly API." -}, - -{ - "location": "manual/style-guide.html#Be-careful-with-type-equality-1", - "page": "Style Guide", - "title": "Be careful with type equality", - "category": "section", - "text": "You generally want to use isa() and <: (issubtype()) for testing types, not ==. Checking types for exact equality typically only makes sense when comparing to a known concrete type (e.g. T == Float64), or if you really, really know what you\'re doing." -}, - -{ - "location": "manual/style-guide.html#Do-not-write-x-f(x)-1", - "page": "Style Guide", - "title": "Do not write x->f(x)", - "category": "section", - "text": "Since higher-order functions are often called with anonymous functions, it is easy to conclude that this is desirable or even necessary. But any function can be passed directly, without being \"wrapped\" in an anonymous function. Instead of writing map(x->f(x), a), write map(f, a)." -}, - -{ - "location": "manual/style-guide.html#Avoid-using-floats-for-numeric-literals-in-generic-code-when-possible-1", - "page": "Style Guide", - "title": "Avoid using floats for numeric literals in generic code when possible", - "category": "section", - "text": "If you write generic code which handles numbers, and which can be expected to run with many different numeric type arguments, try using literals of a numeric type that will affect the arguments as little as possible through promotion.For example,julia> f(x) = 2.0 * x\nf (generic function with 1 method)\n\njulia> f(1//2)\n1.0\n\njulia> f(1/2)\n1.0\n\njulia> f(1)\n2.0whilejulia> g(x) = 2 * x\ng (generic function with 1 method)\n\njulia> g(1//2)\n1//1\n\njulia> g(1/2)\n1.0\n\njulia> g(1)\n2As you can see, the second version, where we used an Int literal, preserved the type of the input argument, while the first didn\'t. This is because e.g. promote_type(Int, Float64) == Float64, and promotion happens with the multiplication. Similarly, Rational literals are less type disruptive than Float64 literals, but more disruptive than Ints:julia> h(x) = 2//1 * x\nh (generic function with 1 method)\n\njulia> h(1//2)\n1//1\n\njulia> h(1/2)\n1.0\n\njulia> h(1)\n2//1Thus, use Int literals when possible, with Rational{Int} for literal non-integer numbers, in order to make it easier to use your code." -}, - -{ - "location": "manual/faq.html#", - "page": "Frequently Asked Questions", - "title": "Frequently Asked Questions", - "category": "page", - "text": "" -}, - -{ - "location": "manual/faq.html#Frequently-Asked-Questions-1", - "page": "Frequently Asked Questions", - "title": "Frequently Asked Questions", - "category": "section", - "text": "" -}, - -{ - "location": "manual/faq.html#Sessions-and-the-REPL-1", - "page": "Frequently Asked Questions", - "title": "Sessions and the REPL", - "category": "section", - "text": "" -}, - -{ - "location": "manual/faq.html#How-do-I-delete-an-object-in-memory?-1", - "page": "Frequently Asked Questions", - "title": "How do I delete an object in memory?", - "category": "section", - "text": "Julia does not have an analog of MATLAB\'s clear function; once a name is defined in a Julia session (technically, in module Main), it is always present.If memory usage is your concern, you can always replace objects with ones that consume less memory. For example, if A is a gigabyte-sized array that you no longer need, you can free the memory with A = 0. The memory will be released the next time the garbage collector runs; you can force this to happen with gc()." -}, - -{ - "location": "manual/faq.html#How-can-I-modify-the-declaration-of-a-type-in-my-session?-1", - "page": "Frequently Asked Questions", - "title": "How can I modify the declaration of a type in my session?", - "category": "section", - "text": "Perhaps you\'ve defined a type and then realize you need to add a new field. If you try this at the REPL, you get the error:ERROR: invalid redefinition of constant MyTypeTypes in module Main cannot be redefined.While this can be inconvenient when you are developing new code, there\'s an excellent workaround. Modules can be replaced by redefining them, and so if you wrap all your new code inside a module you can redefine types and constants. You can\'t import the type names into Main and then expect to be able to redefine them there, but you can use the module name to resolve the scope. In other words, while developing you might use a workflow something like this:include(\"mynewcode.jl\") # this defines a module MyModule\nobj1 = MyModule.ObjConstructor(a, b)\nobj2 = MyModule.somefunction(obj1)\n# Got an error. Change something in \"mynewcode.jl\"\ninclude(\"mynewcode.jl\") # reload the module\nobj1 = MyModule.ObjConstructor(a, b) # old objects are no longer valid, must reconstruct\nobj2 = MyModule.somefunction(obj1) # this time it worked!\nobj3 = MyModule.someotherfunction(obj2, c)\n..." -}, - -{ - "location": "manual/faq.html#Functions-1", - "page": "Frequently Asked Questions", - "title": "Functions", - "category": "section", - "text": "" -}, - -{ - "location": "manual/faq.html#I-passed-an-argument-x-to-a-function,-modified-it-inside-that-function,-but-on-the-outside,-1", - "page": "Frequently Asked Questions", - "title": "I passed an argument x to a function, modified it inside that function, but on the outside,", - "category": "section", - "text": "the variable x is still unchanged. Why?Suppose you call a function like this:julia> x = 10\n10\n\njulia> function change_value!(y)\n y = 17\n end\nchange_value! (generic function with 1 method)\n\njulia> change_value!(x)\n17\n\njulia> x # x is unchanged!\n10In Julia, the binding of a variable x cannot be changed by passing x as an argument to a function. When calling change_value!(x) in the above example, y is a newly created variable, bound initially to the value of x, i.e. 10; then y is rebound to the constant 17, while the variable x of the outer scope is left untouched.But here is a thing you should pay attention to: suppose x is bound to an object of type Array (or any other mutable type). From within the function, you cannot \"unbind\" x from this Array, but you can change its content. For example:julia> x = [1,2,3]\n3-element Array{Int64,1}:\n 1\n 2\n 3\n\njulia> function change_array!(A)\n A[1] = 5\n end\nchange_array! (generic function with 1 method)\n\njulia> change_array!(x)\n5\n\njulia> x\n3-element Array{Int64,1}:\n 5\n 2\n 3Here we created a function change_array!(), that assigns 5 to the first element of the passed array (bound to x at the call site, and bound to A within the function). Notice that, after the function call, x is still bound to the same array, but the content of that array changed: the variables A and x were distinct bindings refering to the same mutable Array object." -}, - -{ - "location": "manual/faq.html#Can-I-use-using-or-import-inside-a-function?-1", - "page": "Frequently Asked Questions", - "title": "Can I use using or import inside a function?", - "category": "section", - "text": "No, you are not allowed to have a using or import statement inside a function. If you want to import a module but only use its symbols inside a specific function or set of functions, you have two options:Use import:\nimport Foo\nfunction bar(...)\n # ... refer to Foo symbols via Foo.baz ...\nend\nThis loads the module Foo and defines a variable Foo that refers to the module, but does not import any of the other symbols from the module into the current namespace. You refer to the Foo symbols by their qualified names Foo.bar etc.\nWrap your function in a module:\nmodule Bar\nexport bar\nusing Foo\nfunction bar(...)\n # ... refer to Foo.baz as simply baz ....\nend\nend\nusing Bar\nThis imports all the symbols from Foo, but only inside the module Bar." -}, - -{ - "location": "manual/faq.html#What-does-the-...-operator-do?-1", - "page": "Frequently Asked Questions", - "title": "What does the ... operator do?", - "category": "section", - "text": "" -}, - -{ - "location": "manual/faq.html#The-two-uses-of-the-...-operator:-slurping-and-splatting-1", - "page": "Frequently Asked Questions", - "title": "The two uses of the ... operator: slurping and splatting", - "category": "section", - "text": "Many newcomers to Julia find the use of ... operator confusing. Part of what makes the ... operator confusing is that it means two different things depending on context." -}, - -{ - "location": "manual/faq.html#...-combines-many-arguments-into-one-argument-in-function-definitions-1", - "page": "Frequently Asked Questions", - "title": "... combines many arguments into one argument in function definitions", - "category": "section", - "text": "In the context of function definitions, the ... operator is used to combine many different arguments into a single argument. This use of ... for combining many different arguments into a single argument is called slurping:julia> function printargs(args...)\n @printf(\"%s\\n\", typeof(args))\n for (i, arg) in enumerate(args)\n @printf(\"Arg %d = %s\\n\", i, arg)\n end\n end\nprintargs (generic function with 1 method)\n\njulia> printargs(1, 2, 3)\nTuple{Int64,Int64,Int64}\nArg 1 = 1\nArg 2 = 2\nArg 3 = 3If Julia were a language that made more liberal use of ASCII characters, the slurping operator might have been written as <-... instead of ...." -}, - -{ - "location": "manual/faq.html#...-splits-one-argument-into-many-different-arguments-in-function-calls-1", - "page": "Frequently Asked Questions", - "title": "... splits one argument into many different arguments in function calls", - "category": "section", - "text": "In contrast to the use of the ... operator to denote slurping many different arguments into one argument when defining a function, the ... operator is also used to cause a single function argument to be split apart into many different arguments when used in the context of a function call. This use of ... is called splatting:julia> function threeargs(a, b, c)\n @printf(\"a = %s::%s\\n\", a, typeof(a))\n @printf(\"b = %s::%s\\n\", b, typeof(b))\n @printf(\"c = %s::%s\\n\", c, typeof(c))\n end\nthreeargs (generic function with 1 method)\n\njulia> vec = [1, 2, 3]\n3-element Array{Int64,1}:\n 1\n 2\n 3\n\njulia> threeargs(vec...)\na = 1::Int64\nb = 2::Int64\nc = 3::Int64If Julia were a language that made more liberal use of ASCII characters, the splatting operator might have been written as ...-> instead of ...." -}, - -{ - "location": "manual/faq.html#Types,-type-declarations,-and-constructors-1", - "page": "Frequently Asked Questions", - "title": "Types, type declarations, and constructors", - "category": "section", - "text": "" -}, - -{ - "location": "manual/faq.html#man-type-stability-1", - "page": "Frequently Asked Questions", - "title": "What does \"type-stable\" mean?", - "category": "section", - "text": "It means that the type of the output is predictable from the types of the inputs. In particular, it means that the type of the output cannot vary depending on the values of the inputs. The following code is not type-stable:julia> function unstable(flag::Bool)\n if flag\n return 1\n else\n return 1.0\n end\n end\nunstable (generic function with 1 method)It returns either an Int or a Float64 depending on the value of its argument. Since Julia can\'t predict the return type of this function at compile-time, any computation that uses it will have to guard against both types possibly occurring, making generation of fast machine code difficult." -}, - -{ - "location": "manual/faq.html#faq-domain-errors-1", - "page": "Frequently Asked Questions", - "title": "Why does Julia give a DomainError for certain seemingly-sensible operations?", - "category": "section", - "text": "Certain operations make mathematical sense but result in errors:julia> sqrt(-2.0)\nERROR: DomainError:\nsqrt will only return a complex result if called with a complex argument. Try sqrt(complex(x)).\nStacktrace:\n [1] sqrt(::Float64) at ./math.jl:425\n\njulia> 2^-5\nERROR: DomainError:\nCannot raise an integer x to a negative power -n.\nMake x a float by adding a zero decimal (e.g. 2.0^-n instead of 2^-n), or write 1/x^n, float(x)^-n, or (x//1)^-n.\nStacktrace:\n [1] power_by_squaring(::Int64, ::Int64) at ./intfuncs.jl:173\n [2] literal_pow(::Base.#^, ::Int64, ::Type{Val{-5}}) at ./intfuncs.jl:208This behavior is an inconvenient consequence of the requirement for type-stability. In the case of sqrt(), most users want sqrt(2.0) to give a real number, and would be unhappy if it produced the complex number 1.4142135623730951 + 0.0im. One could write the sqrt() function to switch to a complex-valued output only when passed a negative number (which is what sqrt() does in some other languages), but then the result would not be type-stable and the sqrt() function would have poor performance.In these and other cases, you can get the result you want by choosing an input type that conveys your willingness to accept an output type in which the result can be represented:julia> sqrt(-2.0+0im)\n0.0 + 1.4142135623730951im\n\njulia> 2.0^-5\n0.03125" -}, - -{ - "location": "manual/faq.html#Why-does-Julia-use-native-machine-integer-arithmetic?-1", - "page": "Frequently Asked Questions", - "title": "Why does Julia use native machine integer arithmetic?", - "category": "section", - "text": "Julia uses machine arithmetic for integer computations. This means that the range of Int values is bounded and wraps around at either end so that adding, subtracting and multiplying integers can overflow or underflow, leading to some results that can be unsettling at first:julia> typemax(Int)\n9223372036854775807\n\njulia> ans+1\n-9223372036854775808\n\njulia> -ans\n-9223372036854775808\n\njulia> 2*ans\n0Clearly, this is far from the way mathematical integers behave, and you might think it less than ideal for a high-level programming language to expose this to the user. For numerical work where efficiency and transparency are at a premium, however, the alternatives are worse.One alternative to consider would be to check each integer operation for overflow and promote results to bigger integer types such as Int128 or BigInt in the case of overflow. Unfortunately, this introduces major overhead on every integer operation (think incrementing a loop counter) – it requires emitting code to perform run-time overflow checks after arithmetic instructions and branches to handle potential overflows. Worse still, this would cause every computation involving integers to be type-unstable. As we mentioned above, type-stability is crucial for effective generation of efficient code. If you can\'t count on the results of integer operations being integers, it\'s impossible to generate fast, simple code the way C and Fortran compilers do.A variation on this approach, which avoids the appearance of type instability is to merge the Int and BigInt types into a single hybrid integer type, that internally changes representation when a result no longer fits into the size of a machine integer. While this superficially avoids type-instability at the level of Julia code, it just sweeps the problem under the rug by foisting all of the same difficulties onto the C code implementing this hybrid integer type. This approach can be made to work and can even be made quite fast in many cases, but has several drawbacks. One problem is that the in-memory representation of integers and arrays of integers no longer match the natural representation used by C, Fortran and other languages with native machine integers. Thus, to interoperate with those languages, we would ultimately need to introduce native integer types anyway. Any unbounded representation of integers cannot have a fixed number of bits, and thus cannot be stored inline in an array with fixed-size slots – large integer values will always require separate heap-allocated storage. And of course, no matter how clever a hybrid integer implementation one uses, there are always performance traps – situations where performance degrades unexpectedly. Complex representation, lack of interoperability with C and Fortran, the inability to represent integer arrays without additional heap storage, and unpredictable performance characteristics make even the cleverest hybrid integer implementations a poor choice for high-performance numerical work.An alternative to using hybrid integers or promoting to BigInts is to use saturating integer arithmetic, where adding to the largest integer value leaves it unchanged and likewise for subtracting from the smallest integer value. This is precisely what Matlab™ does:>> int64(9223372036854775807)\n\nans =\n\n 9223372036854775807\n\n>> int64(9223372036854775807) + 1\n\nans =\n\n 9223372036854775807\n\n>> int64(-9223372036854775808)\n\nans =\n\n -9223372036854775808\n\n>> int64(-9223372036854775808) - 1\n\nans =\n\n -9223372036854775808At first blush, this seems reasonable enough since 9223372036854775807 is much closer to 9223372036854775808 than -9223372036854775808 is and integers are still represented with a fixed size in a natural way that is compatible with C and Fortran. Saturated integer arithmetic, however, is deeply problematic. The first and most obvious issue is that this is not the way machine integer arithmetic works, so implementing saturated operations requires emitting instructions after each machine integer operation to check for underflow or overflow and replace the result with typemin(Int) or typemax(Int) as appropriate. This alone expands each integer operation from a single, fast instruction into half a dozen instructions, probably including branches. Ouch. But it gets worse – saturating integer arithmetic isn\'t associative. Consider this Matlab computation:>> n = int64(2)^62\n4611686018427387904\n\n>> n + (n - 1)\n9223372036854775807\n\n>> (n + n) - 1\n9223372036854775806This makes it hard to write many basic integer algorithms since a lot of common techniques depend on the fact that machine addition with overflow is associative. Consider finding the midpoint between integer values lo and hi in Julia using the expression (lo + hi) >>> 1:julia> n = 2^62\n4611686018427387904\n\njulia> (n + 2n) >>> 1\n6917529027641081856See? No problem. That\'s the correct midpoint between 2^62 and 2^63, despite the fact that n + 2n is -4611686018427387904. Now try it in Matlab:>> (n + 2*n)/2\n\nans =\n\n 4611686018427387904Oops. Adding a >>> operator to Matlab wouldn\'t help, because saturation that occurs when adding n and 2n has already destroyed the information necessary to compute the correct midpoint.Not only is lack of associativity unfortunate for programmers who cannot rely it for techniques like this, but it also defeats almost anything compilers might want to do to optimize integer arithmetic. For example, since Julia integers use normal machine integer arithmetic, LLVM is free to aggressively optimize simple little functions like f(k) = 5k-1. The machine code for this function is just this:julia> code_native(f, Tuple{Int})\n .text\nFilename: none\n pushq %rbp\n movq %rsp, %rbp\nSource line: 1\n leaq -1(%rdi,%rdi,4), %rax\n popq %rbp\n retq\n nopl (%rax,%rax)The actual body of the function is a single leaq instruction, which computes the integer multiply and add at once. This is even more beneficial when f gets inlined into another function:julia> function g(k, n)\n for i = 1:n\n k = f(k)\n end\n return k\n end\ng (generic function with 1 methods)\n\njulia> code_native(g, Tuple{Int,Int})\n .text\nFilename: none\n pushq %rbp\n movq %rsp, %rbp\nSource line: 2\n testq %rsi, %rsi\n jle L26\n nopl (%rax)\nSource line: 3\nL16:\n leaq -1(%rdi,%rdi,4), %rdi\nSource line: 2\n decq %rsi\n jne L16\nSource line: 5\nL26:\n movq %rdi, %rax\n popq %rbp\n retq\n nopSince the call to f gets inlined, the loop body ends up being just a single leaq instruction. Next, consider what happens if we make the number of loop iterations fixed:julia> function g(k)\n for i = 1:10\n k = f(k)\n end\n return k\n end\ng (generic function with 2 methods)\n\njulia> code_native(g,(Int,))\n .text\nFilename: none\n pushq %rbp\n movq %rsp, %rbp\nSource line: 3\n imulq $9765625, %rdi, %rax # imm = 0x9502F9\n addq $-2441406, %rax # imm = 0xFFDABF42\nSource line: 5\n popq %rbp\n retq\n nopw %cs:(%rax,%rax)Because the compiler knows that integer addition and multiplication are associative and that multiplication distributes over addition – neither of which is true of saturating arithmetic – it can optimize the entire loop down to just a multiply and an add. Saturated arithmetic completely defeats this kind of optimization since associativity and distributivity can fail at each loop iteration, causing different outcomes depending on which iteration the failure occurs in. The compiler can unroll the loop, but it cannot algebraically reduce multiple operations into fewer equivalent operations.The most reasonable alternative to having integer arithmetic silently overflow is to do checked arithmetic everywhere, raising errors when adds, subtracts, and multiplies overflow, producing values that are not value-correct. In this blog post, Dan Luu analyzes this and finds that rather than the trivial cost that this approach should in theory have, it ends up having a substantial cost due to compilers (LLVM and GCC) not gracefully optimizing around the added overflow checks. If this improves in the future, we could consider defaulting to checked integer arithmetic in Julia, but for now, we have to live with the possibility of overflow." -}, - -{ - "location": "manual/faq.html#What-are-the-possible-causes-of-an-UndefVarError-during-remote-execution?-1", - "page": "Frequently Asked Questions", - "title": "What are the possible causes of an UndefVarError during remote execution?", - "category": "section", - "text": "As the error states, an immediate cause of an UndefVarError on a remote node is that a binding by that name does not exist. Let us explore some of the possible causes.julia> module Foo\n foo() = remotecall_fetch(x->x, 2, \"Hello\")\n end\n\njulia> Foo.foo()\nERROR: On worker 2:\nUndefVarError: Foo not defined\n[...]The closure x->x carries a reference to Foo, and since Foo is unavailable on node 2, an UndefVarError is thrown.Globals under modules other than Main are not serialized by value to the remote node. Only a reference is sent. Functions which create global bindings (except under Main) may cause an UndefVarError to be thrown later.julia> @everywhere module Foo\n function foo()\n global gvar = \"Hello\"\n remotecall_fetch(()->gvar, 2)\n end\n end\n\njulia> Foo.foo()\nERROR: On worker 2:\nUndefVarError: gvar not defined\n[...]In the above example, @everywhere module Foo defined Foo on all nodes. However the call to Foo.foo() created a new global binding gvar on the local node, but this was not found on node 2 resulting in an UndefVarError error.Note that this does not apply to globals created under module Main. Globals under module Main are serialized and new bindings created under Main on the remote node.julia> gvar_self = \"Node1\"\n\"Node1\"\n\njulia> remotecall_fetch(()->gvar_self, 2)\n\"Node1\"\n\njulia> remotecall_fetch(whos, 2)\n From worker 2: Base 41762 KB Module\n From worker 2: Core 27337 KB Module\n From worker 2: Foo 2477 bytes Module\n From worker 2: Main 46191 KB Module\n From worker 2: gvar_self 13 bytes StringThis does not apply to function or type declarations. However, anonymous functions bound to global variables are serialized as can be seen below.julia> bar() = 1\nbar (generic function with 1 method)\n\njulia> remotecall_fetch(bar, 2)\nERROR: On worker 2:\nUndefVarError: #bar not defined\n[...]\n\njulia> anon_bar = ()->1\n(::#21) (generic function with 1 method)\n\njulia> remotecall_fetch(anon_bar, 2)\n1" -}, - -{ - "location": "manual/faq.html#Packages-and-Modules-1", - "page": "Frequently Asked Questions", - "title": "Packages and Modules", - "category": "section", - "text": "" -}, - -{ - "location": "manual/faq.html#What-is-the-difference-between-\"using\"-and-\"importall\"?-1", - "page": "Frequently Asked Questions", - "title": "What is the difference between \"using\" and \"importall\"?", - "category": "section", - "text": "There is only one difference, and on the surface (syntax-wise) it may seem very minor. The difference between using and importall is that with using you need to say function Foo.bar(.. to extend module Foo\'s function bar with a new method, but with importall or import Foo.bar, you only need to say function bar(... and it automatically extends module Foo\'s function bar.If you use importall, then function Foo.bar(... and function bar(... become equivalent. If you use using, then they are different.The reason this is important enough to have been given separate syntax is that you don\'t want to accidentally extend a function that you didn\'t know existed, because that could easily cause a bug. This is most likely to happen with a method that takes a common type like a string or integer, because both you and the other module could define a method to handle such a common type. If you use importall, then you\'ll replace the other module\'s implementation of bar(s::AbstractString) with your new implementation, which could easily do something completely different (and break all/many future usages of the other functions in module Foo that depend on calling bar)." -}, - -{ - "location": "manual/faq.html#Nothingness-and-missing-values-1", - "page": "Frequently Asked Questions", - "title": "Nothingness and missing values", - "category": "section", - "text": "" -}, - -{ - "location": "manual/faq.html#How-does-\"null\"-or-\"nothingness\"-work-in-Julia?-1", - "page": "Frequently Asked Questions", - "title": "How does \"null\" or \"nothingness\" work in Julia?", - "category": "section", - "text": "Unlike many languages (for example, C and Java), Julia does not have a \"null\" value. When a reference (variable, object field, or array element) is uninitialized, accessing it will immediately throw an error. This situation can be detected using the isdefined function.Some functions are used only for their side effects, and do not need to return a value. In these cases, the convention is to return the value nothing, which is just a singleton object of type Void. This is an ordinary type with no fields; there is nothing special about it except for this convention, and that the REPL does not print anything for it. Some language constructs that would not otherwise have a value also yield nothing, for example if false; end.For situations where a value exists only sometimes (for example, missing statistical data), it is best to use the Nullable{T} type, which allows specifying the type of a missing value.The empty tuple (()) is another form of nothingness. But, it should not really be thought of as nothing but rather a tuple of zero values.In code written for Julia prior to version 0.4 you may occasionally see None, which is quite different. It is the empty (or \"bottom\") type, a type with no values and no subtypes (except itself). This is now written as Union{} (an empty union type). You will generally not need to use this type." -}, - -{ - "location": "manual/faq.html#Memory-1", - "page": "Frequently Asked Questions", - "title": "Memory", - "category": "section", - "text": "" -}, - -{ - "location": "manual/faq.html#Why-does-x-y-allocate-memory-when-x-and-y-are-arrays?-1", - "page": "Frequently Asked Questions", - "title": "Why does x += y allocate memory when x and y are arrays?", - "category": "section", - "text": "In Julia, x += y gets replaced during parsing by x = x + y. For arrays, this has the consequence that, rather than storing the result in the same location in memory as x, it allocates a new array to store the result.While this behavior might surprise some, the choice is deliberate. The main reason is the presence of immutable objects within Julia, which cannot change their value once created. Indeed, a number is an immutable object; the statements x = 5; x += 1 do not modify the meaning of 5, they modify the value bound to x. For an immutable, the only way to change the value is to reassign it.To amplify a bit further, consider the following function:function power_by_squaring(x, n::Int)\n ispow2(n) || error(\"This implementation only works for powers of 2\")\n while n >= 2\n x *= x\n n >>= 1\n end\n x\nendAfter a call like x = 5; y = power_by_squaring(x, 4), you would get the expected result: x == 5 && y == 625. However, now suppose that *=, when used with matrices, instead mutated the left hand side. There would be two problems:For general square matrices, A = A*B cannot be implemented without temporary storage: A[1,1] gets computed and stored on the left hand side before you\'re done using it on the right hand side.\nSuppose you were willing to allocate a temporary for the computation (which would eliminate most of the point of making *= work in-place); if you took advantage of the mutability of x, then this function would behave differently for mutable vs. immutable inputs. In particular, for immutable x, after the call you\'d have (in general) y != x, but for mutable x you\'d have y == x.Because supporting generic programming is deemed more important than potential performance optimizations that can be achieved by other means (e.g., using explicit loops), operators like += and *= work by rebinding new values." -}, - -{ - "location": "manual/faq.html#Asynchronous-IO-and-concurrent-synchronous-writes-1", - "page": "Frequently Asked Questions", - "title": "Asynchronous IO and concurrent synchronous writes", - "category": "section", - "text": "" -}, - -{ - "location": "manual/faq.html#Why-do-concurrent-writes-to-the-same-stream-result-in-inter-mixed-output?-1", - "page": "Frequently Asked Questions", - "title": "Why do concurrent writes to the same stream result in inter-mixed output?", - "category": "section", - "text": "While the streaming I/O API is synchronous, the underlying implementation is fully asynchronous.Consider the printed output from the following:julia> @sync for i in 1:3\n @async write(STDOUT, string(i), \" Foo \", \" Bar \")\n end\n123 Foo Foo Foo Bar Bar BarThis is happening because, while the write call is synchronous, the writing of each argument yields to other tasks while waiting for that part of the I/O to complete.print and println \"lock\" the stream during a call. Consequently changing write to println in the above example results in:julia> @sync for i in 1:3\n @async println(STDOUT, string(i), \" Foo \", \" Bar \")\n end\n1 Foo Bar\n2 Foo Bar\n3 Foo BarYou can lock your writes with a ReentrantLock like this:julia> l = ReentrantLock()\nReentrantLock(Nullable{Task}(), Condition(Any[]), 0)\n\njulia> @sync for i in 1:3\n @async begin\n lock(l)\n try\n write(STDOUT, string(i), \" Foo \", \" Bar \")\n finally\n unlock(l)\n end\n end\n end\n1 Foo Bar 2 Foo Bar 3 Foo Bar" -}, - -{ - "location": "manual/faq.html#Julia-Releases-1", - "page": "Frequently Asked Questions", - "title": "Julia Releases", - "category": "section", - "text": "" -}, - -{ - "location": "manual/faq.html#Do-I-want-to-use-a-release,-beta,-or-nightly-version-of-Julia?-1", - "page": "Frequently Asked Questions", - "title": "Do I want to use a release, beta, or nightly version of Julia?", - "category": "section", - "text": "You may prefer the release version of Julia if you are looking for a stable code base. Releases generally occur every 6 months, giving you a stable platform for writing code.You may prefer the beta version of Julia if you don\'t mind being slightly behind the latest bugfixes and changes, but find the slightly faster rate of changes more appealing. Additionally, these binaries are tested before they are published to ensure they are fully functional.You may prefer the nightly version of Julia if you want to take advantage of the latest updates to the language, and don\'t mind if the version available today occasionally doesn\'t actually work.Finally, you may also consider building Julia from source for yourself. This option is mainly for those individuals who are comfortable at the command line, or interested in learning. If this describes you, you may also be interested in reading our guidelines for contributing.Links to each of these download types can be found on the download page at https://julialang.org/downloads/. Note that not all versions of Julia are available for all platforms." -}, - -{ - "location": "manual/faq.html#When-are-deprecated-functions-removed?-1", - "page": "Frequently Asked Questions", - "title": "When are deprecated functions removed?", - "category": "section", - "text": "Deprecated functions are removed after the subsequent release. For example, functions marked as deprecated in the 0.1 release will not be available starting with the 0.2 release." -}, - -{ - "location": "manual/noteworthy-differences.html#", - "page": "Noteworthy Differences from other Languages", - "title": "Noteworthy Differences from other Languages", - "category": "page", - "text": "" -}, - -{ - "location": "manual/noteworthy-differences.html#Noteworthy-Differences-from-other-Languages-1", - "page": "Noteworthy Differences from other Languages", - "title": "Noteworthy Differences from other Languages", - "category": "section", - "text": "" -}, - -{ - "location": "manual/noteworthy-differences.html#Noteworthy-differences-from-MATLAB-1", - "page": "Noteworthy Differences from other Languages", - "title": "Noteworthy differences from MATLAB", - "category": "section", - "text": "Although MATLAB users may find Julia\'s syntax familiar, Julia is not a MATLAB clone. There are major syntactic and functional differences. The following are some noteworthy differences that may trip up Julia users accustomed to MATLAB:Julia arrays are indexed with square brackets, A[i,j].\nJulia arrays are assigned by reference. After A=B, changing elements of B will modify A as well.\nJulia values are passed and assigned by reference. If a function modifies an array, the changes will be visible in the caller.\nJulia does not automatically grow arrays in an assignment statement. Whereas in MATLAB a(4) = 3.2 can create the array a = [0 0 0 3.2] and a(5) = 7 can grow it into a = [0 0 0 3.2 7], the corresponding Julia statement a[5] = 7 throws an error if the length of a is less than 5 or if this statement is the first use of the identifier a. Julia has push!() and append!(), which grow Vectors much more efficiently than MATLAB\'s a(end+1) = val.\nThe imaginary unit sqrt(-1) is represented in Julia as im, not i or j as in MATLAB.\nIn Julia, literal numbers without a decimal point (such as 42) create integers instead of floating point numbers. Arbitrarily large integer literals are supported. As a result, some operations such as 2^-1 will throw a domain error as the result is not an integer (see the FAQ entry on domain errors for details).\nIn Julia, multiple values are returned and assigned as tuples, e.g. (a, b) = (1, 2) or a, b = 1, 2. MATLAB\'s nargout, which is often used in MATLAB to do optional work based on the number of returned values, does not exist in Julia. Instead, users can use optional and keyword arguments to achieve similar capabilities.\nJulia has true one-dimensional arrays. Column vectors are of size N, not Nx1. For example, rand(N) makes a 1-dimensional array.\nIn Julia, [x,y,z] will always construct a 3-element array containing x, y and z.\nTo concatenate in the first (\"vertical\") dimension use either vcat(x,y,z) or separate with semicolons ([x; y; z]).\nTo concatenate in the second (\"horizontal\") dimension use either hcat(x,y,z) or separate with spaces ([x y z]).\nTo construct block matrices (concatenating in the first two dimensions), use either hvcat() or combine spaces and semicolons ([a b; c d]).\nIn Julia, a:b and a:b:c construct Range objects. To construct a full vector like in MATLAB, use collect(a:b). Generally, there is no need to call collect though. Range will act like a normal array in most cases but is more efficient because it lazily computes its values. This pattern of creating specialized objects instead of full arrays is used frequently, and is also seen in functions such as linspace, or with iterators such as enumerate, and zip. The special objects can mostly be used as if they were normal arrays.\nFunctions in Julia return values from their last expression or the return keyword instead of listing the names of variables to return in the function definition (see The return Keyword for details).\nA Julia script may contain any number of functions, and all definitions will be externally visible when the file is loaded. Function definitions can be loaded from files outside the current working directory.\nIn Julia, reductions such as sum(), prod(), and max() are performed over every element of an array when called with a single argument, as in sum(A), even if A has more than one dimension.\nIn Julia, functions such as sort() that operate column-wise by default (sort(A) is equivalent to sort(A,1)) do not have special behavior for 1xN arrays; the argument is returned unmodified since it still performs sort(A,1). To sort a 1xN matrix like a vector, use sort(A,2).\nIn Julia, if A is a 2-dimensional array, fft(A) computes a 2D FFT. In particular, it is not equivalent to fft(A,1), which computes a 1D FFT acting column-wise.\nIn Julia, parentheses must be used to call a function with zero arguments, like in tic() and toc().\nJulia discourages the used of semicolons to end statements. The results of statements are not automatically printed (except at the interactive prompt), and lines of code do not need to end with semicolons. println() or @printf() can be used to print specific output.\nIn Julia, if A and B are arrays, logical comparison operations like A == B do not return an array of booleans. Instead, use A .== B, and similarly for the other boolean operators like <, > and =.\nIn Julia, the operators &, |, and ⊻ (xor) perform the bitwise operations equivalent to and, or, and xor respectively in MATLAB, and have precedence similar to Python\'s bitwise operators (unlike C). They can operate on scalars or element-wise across arrays and can be used to combine logical arrays, but note the difference in order of operations: parentheses may be required (e.g., to select elements of A equal to 1 or 2 use (A .== 1) | (A .== 2)).\nIn Julia, the elements of a collection can be passed as arguments to a function using the splat operator ..., as in xs=[1,2]; f(xs...).\nJulia\'s svd() returns singular values as a vector instead of as a dense diagonal matrix.\nIn Julia, ... is not used to continue lines of code. Instead, incomplete expressions automatically continue onto the next line.\nIn both Julia and MATLAB, the variable ans is set to the value of the last expression issued in an interactive session. In Julia, unlike MATLAB, ans is not set when Julia code is run in non-interactive mode.\nJulia\'s types do not support dynamically adding fields at runtime, unlike MATLAB\'s classes. Instead, use a Dict.\nIn Julia each module has its own global scope/namespace, whereas in MATLAB there is just one global scope.\nIn MATLAB, an idiomatic way to remove unwanted values is to use logical indexing, like in the expression x(x>3) or in the statement x(x>3) = [] to modify x in-place. In contrast, Julia provides the higher order functions filter() and filter!(), allowing users to write filter(z->z>3, x) and filter!(z->z>3, x) as alternatives to the corresponding transliterations x[x.>3] and x = x[x.>3]. Using filter!() reduces the use of temporary arrays.\nThe analogue of extracting (or \"dereferencing\") all elements of a cell array, e.g. in vertcat(A{:}) in MATLAB, is written using the splat operator in Julia, e.g. as vcat(A...)." -}, - -{ - "location": "manual/noteworthy-differences.html#Noteworthy-differences-from-R-1", - "page": "Noteworthy Differences from other Languages", - "title": "Noteworthy differences from R", - "category": "section", - "text": "One of Julia\'s goals is to provide an effective language for data analysis and statistical programming. For users coming to Julia from R, these are some noteworthy differences:Julia\'s single quotes enclose characters, not strings.\nJulia can create substrings by indexing into strings. In R, strings must be converted into character vectors before creating substrings.\nIn Julia, like Python but unlike R, strings can be created with triple quotes \"\"\" ... \"\"\". This syntax is convenient for constructing strings that contain line breaks.\nIn Julia, varargs are specified using the splat operator ..., which always follows the name of a specific variable, unlike R, for which ... can occur in isolation.\nIn Julia, modulus is mod(a, b), not a %% b. % in Julia is the remainder operator.\nIn Julia, not all data structures support logical indexing. Furthermore, logical indexing in Julia is supported only with vectors of length equal to the object being indexed. For example:\nIn R, c(1, 2, 3, 4)[c(TRUE, FALSE)] is equivalent to c(1, 3).\nIn R, c(1, 2, 3, 4)[c(TRUE, FALSE, TRUE, FALSE)] is equivalent to c(1, 3).\nIn Julia, [1, 2, 3, 4][[true, false]] throws a BoundsError.\nIn Julia, [1, 2, 3, 4][[true, false, true, false]] produces [1, 3].\nLike many languages, Julia does not always allow operations on vectors of different lengths, unlike R where the vectors only need to share a common index range. For example, c(1, 2, 3, 4) + c(1, 2) is valid R but the equivalent [1, 2, 3, 4] + [1, 2] will throw an error in Julia.\nJulia\'s map() takes the function first, then its arguments, unlike lapply(, function, ...) in R. Similarly Julia\'s equivalent of apply(X, MARGIN, FUN, ...) in R is mapslices() where the function is the first argument.\nMultivariate apply in R, e.g. mapply(choose, 11:13, 1:3), can be written as broadcast(binomial, 11:13, 1:3) in Julia. Equivalently Julia offers a shorter dot syntax for vectorizing functions binomial.(11:13, 1:3).\nJulia uses end to denote the end of conditional blocks, like if, loop blocks, like while/ for, and functions. In lieu of the one-line if ( cond ) statement, Julia allows statements of the form if cond; statement; end, cond && statement and !cond || statement. Assignment statements in the latter two syntaxes must be explicitly wrapped in parentheses, e.g. cond && (x = value).\nIn Julia, <-, <<- and -> are not assignment operators.\nJulia\'s -> creates an anonymous function, like Python.\nJulia constructs vectors using brackets. Julia\'s [1, 2, 3] is the equivalent of R\'s c(1, 2, 3).\nJulia\'s * operator can perform matrix multiplication, unlike in R. If A and B are matrices, then A * B denotes a matrix multiplication in Julia, equivalent to R\'s A %*% B. In R, this same notation would perform an element-wise (Hadamard) product. To get the element-wise multiplication operation, you need to write A .* B in Julia.\nJulia performs matrix transposition using the .\' operator and conjugated transposition using the \' operator. Julia\'s A.\' is therefore equivalent to R\'s t(A).\nJulia does not require parentheses when writing if statements or for/while loops: use for i in [1, 2, 3] instead of for (i in c(1, 2, 3)) and if i == 1 instead of if (i == 1).\nJulia does not treat the numbers 0 and 1 as Booleans. You cannot write if (1) in Julia, because if statements accept only booleans. Instead, you can write if true, if Bool(1), or if 1==1.\nJulia does not provide nrow and ncol. Instead, use size(M, 1) for nrow(M) and size(M, 2) for ncol(M).\nJulia is careful to distinguish scalars, vectors and matrices. In R, 1 and c(1) are the same. In Julia, they cannot be used interchangeably.\nJulia\'s diag and diagm are not like R\'s.\nJulia cannot assign to the results of function calls on the left hand side of an assignment operation: you cannot write diag(M) = ones(n).\nJulia discourages populating the main namespace with functions. Most statistical functionality for Julia is found in packages under the JuliaStats organization. For example:\nFunctions pertaining to probability distributions are provided by the Distributions package.\nThe DataFrames package provides data frames.\nGeneralized linear models are provided by the GLM package.\nJulia provides tuples and real hash tables, but not R-style lists. When returning multiple items, you should typically use a tuple: instead of list(a = 1, b = 2), use (1, 2).\nJulia encourages users to write their own types, which are easier to use than S3 or S4 objects in R. Julia\'s multiple dispatch system means that table(x::TypeA) and table(x::TypeB) act like R\'s table.TypeA(x) and table.TypeB(x).\nIn Julia, values are passed and assigned by reference. If a function modifies an array, the changes will be visible in the caller. This is very different from R and allows new functions to operate on large data structures much more efficiently.\nIn Julia, vectors and matrices are concatenated using hcat(), vcat() and hvcat(), not c, rbind and cbind like in R.\nIn Julia, a range like a:b is not shorthand for a vector like in R, but is a specialized Range that is used for iteration without high memory overhead. To convert a range into a vector, use collect(a:b).\nJulia\'s max() and min() are the equivalent of pmax and pmin respectively in R, but both arguments need to have the same dimensions. While maximum() and minimum() replace max and min in R, there are important differences.\nJulia\'s sum(), prod(), maximum(), and minimum() are different from their counterparts in R. They all accept one or two arguments. The first argument is an iterable collection such as an array. If there is a second argument, then this argument indicates the dimensions, over which the operation is carried out. For instance, let A=[[1 2],[3 4]] in Julia and B=rbind(c(1,2),c(3,4)) be the same matrix in R. Then sum(A) gives the same result as sum(B), but sum(A, 1) is a row vector containing the sum over each column and sum(A, 2) is a column vector containing the sum over each row. This contrasts to the behavior of R, where sum(B,1)=11 and sum(B,2)=12. If the second argument is a vector, then it specifies all the dimensions over which the sum is performed, e.g., sum(A,[1,2])=10. It should be noted that there is no error checking regarding the second argument.\nJulia has several functions that can mutate their arguments. For example, it has both sort() and sort!().\nIn R, performance requires vectorization. In Julia, almost the opposite is true: the best performing code is often achieved by using devectorized loops.\nJulia is eagerly evaluated and does not support R-style lazy evaluation. For most users, this means that there are very few unquoted expressions or column names.\nJulia does not support the NULL type.\nJulia lacks the equivalent of R\'s assign or get.\nIn Julia, return does not require parentheses.\nIn R, an idiomatic way to remove unwanted values is to use logical indexing, like in the expression x[x>3] or in the statement x = x[x>3] to modify x in-place. In contrast, Julia provides the higher order functions filter() and filter!(), allowing users to write filter(z->z>3, x) and filter!(z->z>3, x) as alternatives to the corresponding transliterations x[x.>3] and x = x[x.>3]. Using filter!() reduces the use of temporary arrays." -}, - -{ - "location": "manual/noteworthy-differences.html#Noteworthy-differences-from-Python-1", - "page": "Noteworthy Differences from other Languages", - "title": "Noteworthy differences from Python", - "category": "section", - "text": "Julia requires end to end a block. Unlike Python, Julia has no pass keyword.\nIn Julia, indexing of arrays, strings, etc. is 1-based not 0-based.\nJulia\'s slice indexing includes the last element, unlike in Python. a[2:3] in Julia is a[1:3] in Python.\nJulia does not support negative indexes. In particular, the last element of a list or array is indexed with end in Julia, not -1 as in Python.\nJulia\'s for, if, while, etc. blocks are terminated by the end keyword. Indentation level is not significant as it is in Python.\nJulia has no line continuation syntax: if, at the end of a line, the input so far is a complete expression, it is considered done; otherwise the input continues. One way to force an expression to continue is to wrap it in parentheses.\nJulia arrays are column major (Fortran ordered) whereas NumPy arrays are row major (C-ordered) by default. To get optimal performance when looping over arrays, the order of the loops should be reversed in Julia relative to NumPy (see relevant section of Performance Tips).\nJulia\'s updating operators (e.g. +=, -=, ...) are not in-place whereas NumPy\'s are. This means A = ones(4); B = A; B += 3 doesn\'t change values in A, it rather rebinds the name B to the result of the right- hand side B = B + 3, which is a new array. Use B[:] += 3, explicit loops, or InplaceOps.jl.\nJulia evaluates default values of function arguments every time the method is invoked, unlike in Python where the default values are evaluated only once when the function is defined. For example, the function f(x=rand()) = x returns a new random number every time it is invoked without argument. On the other hand, the function g(x=[1,2]) = push!(x,3) returns [1,2,3] every time it is called as g().\nIn Julia % is the remainder operator, whereas in Python it is the modulus." -}, - -{ - "location": "manual/noteworthy-differences.html#Noteworthy-differences-from-C/C-1", - "page": "Noteworthy Differences from other Languages", - "title": "Noteworthy differences from C/C++", - "category": "section", - "text": "Julia arrays are indexed with square brackets, and can have more than one dimension A[i,j]. This syntax is not just syntactic sugar for a reference to a pointer or address as in C/C++. See the Julia documentation for the syntax for array construction (it has changed between versions).\nIn Julia, indexing of arrays, strings, etc. is 1-based not 0-based.\nJulia arrays are assigned by reference. After A=B, changing elements of B will modify A as well. Updating operators like += do not operate in-place, they are equivalent to A = A + B which rebinds the left-hand side to the result of the right-hand side expression.\nJulia arrays are column major (Fortran ordered) whereas C/C++ arrays are row major ordered by default. To get optimal performance when looping over arrays, the order of the loops should be reversed in Julia relative to C/C++ (see relevant section of Performance Tips).\nJulia values are passed and assigned by reference. If a function modifies an array, the changes will be visible in the caller.\nIn Julia, whitespace is significant, unlike C/C++, so care must be taken when adding/removing whitespace from a Julia program.\nIn Julia, literal numbers without a decimal point (such as 42) create signed integers, of type Int, but literals too large to fit in the machine word size will automatically be promoted to a larger size type, such as Int64 (if Int is Int32), Int128, or the arbitrarily large BigInt type. There are no numeric literal suffixes, such as L, LL, U, UL, ULL to indicate unsigned and/or signed vs. unsigned. Decimal literals are always signed, and hexadecimal literals (which start with 0x like C/C++), are unsigned. Hexadecimal literals also, unlike C/C++/Java and unlike decimal literals in Julia, have a type based on the length of the literal, including leading 0s. For example, 0x0 and 0x00 have type UInt8, 0x000 and 0x0000 have type UInt16, then literals with 5 to 8 hex digits have type UInt32, 9 to 16 hex digits type UInt64 and 17 to 32 hex digits type UInt128. This needs to be taken into account when defining hexadecimal masks, for example ~0xf == 0xf0 is very different from ~0x000f == 0xfff0. 64 bit Float64 and 32 bit Float32 bit literals are expressed as 1.0 and 1.0f0 respectively. Floating point literals are rounded (and not promoted to the BigFloat type) if they can not be exactly represented. Floating point literals are closer in behavior to C/C++. Octal (prefixed with 0o) and binary (prefixed with 0b) literals are also treated as unsigned.\nString literals can be delimited with either \" or \"\"\", \"\"\" delimited literals can contain \" characters without quoting it like \"\\\"\" String literals can have values of other variables or expressions interpolated into them, indicated by $variablename or $(expression), which evaluates the variable name or the expression in the context of the function.\n// indicates a Rational number, and not a single-line comment (which is # in Julia)\n#= indicates the start of a multiline comment, and =# ends it.\nFunctions in Julia return values from their last expression(s) or the return keyword. Multiple values can be returned from functions and assigned as tuples, e.g. (a, b) = myfunction() or a, b = myfunction(), instead of having to pass pointers to values as one would have to do in C/C++ (i.e. a = myfunction(&b).\nJulia does not require the use of semicolons to end statements. The results of expressions are not automatically printed (except at the interactive prompt, i.e. the REPL), and lines of code do not need to end with semicolons. println() or @printf() can be used to print specific output. In the REPL, ; can be used to suppress output. ; also has a different meaning within [ ], something to watch out for. ; can be used to separate expressions on a single line, but are not strictly necessary in many cases, and are more an aid to readability.\nIn Julia, the operator ⊻ (xor) performs the bitwise XOR operation, i.e. ^ in C/C++. Also, the bitwise operators do not have the same precedence as C/++, so parenthesis may be required.\nJulia\'s ^ is exponentiation (pow), not bitwise XOR as in C/C++ (use ⊻, or xor, in Julia)\nJulia has two right-shift operators, >> and >>>. >>> performs an arithmetic shift, >> always performs a logical shift, unlike C/C++, where the meaning of >> depends on the type of the value being shifted.\nJulia\'s -> creates an anonymous function, it does not access a member via a pointer.\nJulia does not require parentheses when writing if statements or for/while loops: use for i in [1, 2, 3] instead of for (int i=1; i <= 3; i++) and if i == 1 instead of if (i == 1).\nJulia does not treat the numbers 0 and 1 as Booleans. You cannot write if (1) in Julia, because if statements accept only booleans. Instead, you can write if true, if Bool(1), or if 1==1.\nJulia uses end to denote the end of conditional blocks, like if, loop blocks, like while/ for, and functions. In lieu of the one-line if ( cond ) statement, Julia allows statements of the form if cond; statement; end, cond && statement and !cond || statement. Assignment statements in the latter two syntaxes must be explicitly wrapped in parentheses, e.g. cond && (x = value), because of the operator precedence.\nJulia has no line continuation syntax: if, at the end of a line, the input so far is a complete expression, it is considered done; otherwise the input continues. One way to force an expression to continue is to wrap it in parentheses.\nJulia macros operate on parsed expressions, rather than the text of the program, which allows them to perform sophisticated transformations of Julia code. Macro names start with the @ character, and have both a function-like syntax, @mymacro(arg1, arg2, arg3), and a statement-like syntax, @mymacro arg1 arg2 arg3. The forms are interchangable; the function-like form is particularly useful if the macro appears within another expression, and is often clearest. The statement-like form is often used to annotate blocks, as in the parallel for construct: @parallel for i in 1:n; #= body =#; end. Where the end of the macro construct may be unclear, use the function-like form.\nJulia now has an enumeration type, expressed using the macro @enum(name, value1, value2, ...) For example: @enum(Fruit, banana=1, apple, pear)\nBy convention, functions that modify their arguments have a ! at the end of the name, for example push!.\nIn C++, by default, you have static dispatch, i.e. you need to annotate a function as virtual, in order to have dynamic dispatch. On the other hand, in Julia every method is \"virtual\" (although it\'s more general than that since methods are dispatched on every argument type, not only this, using the most-specific-declaration rule)." -}, - -{ - "location": "manual/unicode-input.html#", - "page": "Unicode Input", - "title": "Unicode Input", - "category": "page", - "text": "" -}, - -{ - "location": "manual/unicode-input.html#Unicode-Input-1", - "page": "Unicode Input", - "title": "Unicode Input", - "category": "section", - "text": "The following table lists Unicode characters that can be entered via tab completion of LaTeX-like abbreviations in the Julia REPL (and in various other editing environments). You can also get information on how to type a symbol by entering it in the REPL help, i.e. by typing ? and then entering the symbol in the REPL (e.g., by copy-paste from somewhere you saw the symbol).warning: Warning\nThis table may appear to contain missing characters in the second column, or even show characters that are inconsistent with the characters as they are rendered in the Julia REPL. In these cases, users are strongly advised to check their choice of fonts in their browser and REPL environment, as there are known issues with glyphs in many fonts.#\n# Generate a table containing all LaTeX and Emoji tab completions available in the REPL.\n#\n\nfunction tab_completions(symbols...)\n completions = Dict{String, Vector{String}}()\n for each in symbols, (k, v) in each\n completions[v] = push!(get!(completions, v, String[]), k)\n end\n return completions\nend\n\nfunction unicode_data()\n file = normpath(JULIA_HOME, \"..\", \"..\", \"doc\", \"UnicodeData.txt\")\n names = Dict{UInt32, String}()\n open(file) do unidata\n for line in readlines(unidata)\n id, name, desc = split(line, \";\")[[1, 2, 11]]\n codepoint = parse(UInt32, \"0x$id\")\n names[codepoint] = titlecase(lowercase(name == \"\" ? desc : desc == \"\" ? name : \"$name / $desc\"))\n end\n end\n return names\nend\n\n# Prepend a dotted circle (\'◌\' i.e. \'\\u25CC\') to combining characters\nfunction fix_combining_chars(char)\n cat = Base.UTF8proc.category_code(char)\n return string(cat == 6 || cat == 8 ? \"◌\" : \"\", char)\nend\n\n\nfunction table_entries(completions, unicode_dict)\n entries = [[\n \"Code point(s)\", \"Character(s)\",\n \"Tab completion sequence(s)\", \"Unicode name(s)\"\n ]]\n for (chars, inputs) in sort!(collect(completions), by = first)\n code_points, unicode_names, characters = String[], String[], String[]\n for char in chars\n push!(code_points, \"U+$(uppercase(hex(char, 5)))\")\n push!(unicode_names, get(unicode_dict, UInt32(char), \"(No Unicode name)\"))\n push!(characters, isempty(characters) ? fix_combining_chars(char) : \"$char\")\n end\n push!(entries, [\n join(code_points, \" + \"), join(characters),\n join(inputs, \", \"), join(unicode_names, \" + \")\n ])\n end\n return Markdown.Table(entries, [:l, :l, :l, :l])\nend\n\ntable_entries(\n tab_completions(\n Base.REPLCompletions.latex_symbols,\n Base.REPLCompletions.emoji_symbols\n ),\n unicode_data()\n)" -}, - -{ - "location": "stdlib/base.html#", - "page": "Essentials", - "title": "Essentials", - "category": "page", - "text": "" -}, - -{ - "location": "stdlib/base.html#Essentials-1", - "page": "Essentials", - "title": "Essentials", - "category": "section", - "text": "" -}, - -{ - "location": "stdlib/base.html#Introduction-1", - "page": "Essentials", - "title": "Introduction", - "category": "section", - "text": "The Julia standard library contains a range of functions and macros appropriate for performing scientific and numerical computing, but is also as broad as those of many general purpose programming languages. Additional functionality is available from a growing collection of available packages. Functions are grouped by topic below.Some general notes:Except for functions in built-in modules (Pkg, Collections, Test and Profile), all functions documented here are directly available for use in programs.\nTo use module functions, use import Module to import the module, and Module.fn(x) to use the functions.\nAlternatively, using Module will import all exported Module functions into the current namespace.\nBy convention, function names ending with an exclamation point (!) modify their arguments. Some functions have both modifying (e.g., sort!) and non-modifying (sort) versions." -}, - -{ - "location": "stdlib/base.html#Base.exit", - "page": "Essentials", - "title": "Base.exit", - "category": "function", - "text": "exit([code])\n\nQuit (or control-D at the prompt). The default exit code is zero, indicating that the processes completed successfully.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.quit", - "page": "Essentials", - "title": "Base.quit", - "category": "function", - "text": "quit()\n\nQuit the program indicating that the processes completed successfully. This function calls exit(0) (see exit).\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.atexit", - "page": "Essentials", - "title": "Base.atexit", - "category": "function", - "text": "atexit(f)\n\nRegister a zero-argument function f() to be called at process exit. atexit() hooks are called in last in first out (LIFO) order and run before object finalizers.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.atreplinit", - "page": "Essentials", - "title": "Base.atreplinit", - "category": "function", - "text": "atreplinit(f)\n\nRegister a one-argument function to be called before the REPL interface is initialized in interactive sessions; this is useful to customize the interface. The argument of f is the REPL object. This function should be called from within the .juliarc.jl initialization file.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.isinteractive", - "page": "Essentials", - "title": "Base.isinteractive", - "category": "function", - "text": "isinteractive() -> Bool\n\nDetermine whether Julia is running an interactive session.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.whos", - "page": "Essentials", - "title": "Base.whos", - "category": "function", - "text": "whos(io::IO=STDOUT, m::Module=current_module(), pattern::Regex=r\"\")\n\nPrint information about exported global variables in a module, optionally restricted to those matching pattern.\n\nThe memory consumption estimate is an approximate lower bound on the size of the internal structure of the object.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.summarysize", - "page": "Essentials", - "title": "Base.summarysize", - "category": "function", - "text": "Base.summarysize(obj; exclude=Union{...}, chargeall=Union{...}) -> Int\n\nCompute the amount of memory used by all unique objects reachable from the argument.\n\nKeyword Arguments\n\nexclude: specifies the types of objects to exclude from the traversal.\nchargeall: specifies the types of objects to always charge the size of all of their fields, even if those fields would normally be excluded.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.edit-Tuple{AbstractString,Integer}", - "page": "Essentials", - "title": "Base.edit", - "category": "method", - "text": "edit(path::AbstractString, line::Integer=0)\n\nEdit a file or directory optionally providing a line number to edit the file at. Returns to the julia prompt when you quit the editor. The editor can be changed by setting JULIA_EDITOR, VISUAL or EDITOR as an environment variable.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.edit-Tuple{Any}", - "page": "Essentials", - "title": "Base.edit", - "category": "method", - "text": "edit(function, [types])\n\nEdit the definition of a function, optionally specifying a tuple of types to indicate which method to edit. The editor can be changed by setting JULIA_EDITOR, VISUAL or EDITOR as an environment variable.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.@edit", - "page": "Essentials", - "title": "Base.@edit", - "category": "macro", - "text": "@edit\n\nEvaluates the arguments to the function or macro call, determines their types, and calls the edit function on the resulting expression.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.less-Tuple{AbstractString}", - "page": "Essentials", - "title": "Base.less", - "category": "method", - "text": "less(file::AbstractString, [line::Integer])\n\nShow a file using the default pager, optionally providing a starting line number. Returns to the julia prompt when you quit the pager.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.less-Tuple{Any}", - "page": "Essentials", - "title": "Base.less", - "category": "method", - "text": "less(function, [types])\n\nShow the definition of a function using the default pager, optionally specifying a tuple of types to indicate which method to see.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.@less", - "page": "Essentials", - "title": "Base.@less", - "category": "macro", - "text": "@less\n\nEvaluates the arguments to the function or macro call, determines their types, and calls the less function on the resulting expression.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.clipboard-Tuple{Any}", - "page": "Essentials", - "title": "Base.clipboard", - "category": "method", - "text": "clipboard(x)\n\nSend a printed form of x to the operating system clipboard (\"copy\").\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.clipboard-Tuple{}", - "page": "Essentials", - "title": "Base.clipboard", - "category": "method", - "text": "clipboard() -> AbstractString\n\nReturn a string with the contents of the operating system clipboard (\"paste\").\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.reload", - "page": "Essentials", - "title": "Base.reload", - "category": "function", - "text": "reload(name::AbstractString)\n\nForce reloading of a package, even if it has been loaded before. This is intended for use during package development as code is modified.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.require", - "page": "Essentials", - "title": "Base.require", - "category": "function", - "text": "require(module::Symbol)\n\nThis function is part of the implementation of using / import, if a module is not already defined in Main. It can also be called directly to force reloading a module, regardless of whether it has been loaded before (for example, when interactively developing libraries).\n\nLoads a source file, in the context of the Main module, on every active node, searching standard locations for files. require is considered a top-level operation, so it sets the current include path but does not use it to search for files (see help for include). This function is typically used to load library code, and is implicitly called by using to load packages.\n\nWhen searching for files, require first looks for package code under Pkg.dir(), then tries paths in the global array LOAD_PATH. require is case-sensitive on all platforms, including those with case-insensitive filesystems like macOS and Windows.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.compilecache", - "page": "Essentials", - "title": "Base.compilecache", - "category": "function", - "text": "Base.compilecache(module::String)\n\nCreates a precompiled cache file for a module and all of its dependencies. This can be used to reduce package load times. Cache files are stored in LOAD_CACHE_PATH[1], which defaults to ~/.julia/lib/VERSION. See Module initialization and precompilation for important notes.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.__precompile__", - "page": "Essentials", - "title": "Base.__precompile__", - "category": "function", - "text": "__precompile__(isprecompilable::Bool=true)\n\nSpecify whether the file calling this function is precompilable. If isprecompilable is true, then __precompile__ throws an exception when the file is loaded by using/import/require unless the file is being precompiled, and in a module file it causes the module to be automatically precompiled when it is imported. Typically, __precompile__() should occur before the module declaration in the file, or better yet VERSION >= v\"0.4\" && __precompile__() in order to be backward-compatible with Julia 0.3.\n\nIf a module or file is not safely precompilable, it should call __precompile__(false) in order to throw an error if Julia attempts to precompile it.\n\n__precompile__() should not be used in a module unless all of its dependencies are also using __precompile__(). Failure to do so can result in a runtime error when loading the module.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.include", - "page": "Essentials", - "title": "Base.include", - "category": "function", - "text": "include(path::AbstractString)\n\nEvaluate the contents of the input source file in the current context. Returns the result of the last evaluated expression of the input file. During including, a task-local include path is set to the directory containing the file. Nested calls to include will search relative to that path. All paths refer to files on node 1 when running in parallel, and files will be fetched from node 1. This function is typically used to load source interactively, or to combine files in packages that are broken into multiple source files.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.include_string", - "page": "Essentials", - "title": "Base.include_string", - "category": "function", - "text": "include_string(code::AbstractString, filename::AbstractString=\"string\")\n\nLike include, except reads code from the given string rather than from a file. Since there is no file path involved, no path processing or fetching from node 1 is done.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.include_dependency", - "page": "Essentials", - "title": "Base.include_dependency", - "category": "function", - "text": "include_dependency(path::AbstractString)\n\nIn a module, declare that the file specified by path (relative or absolute) is a dependency for precompilation; that is, the module will need to be recompiled if this file changes.\n\nThis is only needed if your module depends on a file that is not used via include. It has no effect outside of compilation.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.Docs.apropos", - "page": "Essentials", - "title": "Base.Docs.apropos", - "category": "function", - "text": "apropos(string)\n\nSearch through all documentation for a string, ignoring case.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.which-Tuple{Any,Any}", - "page": "Essentials", - "title": "Base.which", - "category": "method", - "text": "which(f, types)\n\nReturns the method of f (a Method object) that would be called for arguments of the given types.\n\nIf types is an abstract type, then the method that would be called by invoke is returned.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.which-Tuple{Symbol}", - "page": "Essentials", - "title": "Base.which", - "category": "method", - "text": "which(symbol)\n\nReturn the module in which the binding for the variable referenced by symbol was created.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.@which", - "page": "Essentials", - "title": "Base.@which", - "category": "macro", - "text": "@which\n\nApplied to a function or macro call, it evaluates the arguments to the specified call, and returns the Method object for the method that would be called for those arguments. Applied to a variable, it returns the module in which the variable was bound. It calls out to the which function.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.methods", - "page": "Essentials", - "title": "Base.methods", - "category": "function", - "text": "methods(f, [types])\n\nReturns the method table for f.\n\nIf types is specified, returns an array of methods whose types match.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.methodswith", - "page": "Essentials", - "title": "Base.methodswith", - "category": "function", - "text": "methodswith(typ[, module or function][, showparents::Bool=false])\n\nReturn an array of methods with an argument of type typ.\n\nThe optional second argument restricts the search to a particular module or function (the default is all modules, starting from Main).\n\nIf optional showparents is true, also return arguments with a parent type of typ, excluding type Any.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.@show", - "page": "Essentials", - "title": "Base.@show", - "category": "macro", - "text": "@show\n\nShow an expression and result, returning the result.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.versioninfo", - "page": "Essentials", - "title": "Base.versioninfo", - "category": "function", - "text": "versioninfo(io::IO=STDOUT, verbose::Bool=false)\n\nPrint information about the version of Julia in use. If the verbose argument is true, detailed system information is shown as well.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.workspace", - "page": "Essentials", - "title": "Base.workspace", - "category": "function", - "text": "workspace()\n\nReplace the top-level module (Main) with a new one, providing a clean workspace. The previous Main module is made available as LastMain. A previously-loaded package can be accessed using a statement such as using LastMain.Package.\n\nThis function should only be used interactively.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#ans", - "page": "Essentials", - "title": "ans", - "category": "keyword", - "text": "ans\n\nA variable referring to the last computed value, automatically set at the interactive prompt.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Getting-Around-1", - "page": "Essentials", - "title": "Getting Around", - "category": "section", - "text": "Base.exit\nBase.quit\nBase.atexit\nBase.atreplinit\nBase.isinteractive\nBase.whos\nBase.summarysize\nBase.edit(::AbstractString, ::Integer)\nBase.edit(::Any)\nBase.@edit\nBase.less(::AbstractString)\nBase.less(::Any)\nBase.@less\nBase.clipboard(::Any)\nBase.clipboard()\nBase.reload\nBase.require\nBase.compilecache\nBase.__precompile__\nBase.include\nBase.include_string\nBase.include_dependency\nBase.Docs.apropos\nBase.which(::Any, ::Any)\nBase.which(::Symbol)\nBase.@which\nBase.methods\nBase.methodswith\nBase.@show\nBase.versioninfo\nBase.workspace\nans" -}, - -{ - "location": "stdlib/base.html#Core.:===", - "page": "Essentials", - "title": "Core.:===", - "category": "function", - "text": "===(x,y) -> Bool\n≡(x,y) -> Bool\n\nDetermine whether x and y are identical, in the sense that no program could distinguish them. Compares mutable objects by address in memory, and compares immutable objects (such as numbers) by contents at the bit level. This function is sometimes called egal.\n\njulia> a = [1, 2]; b = [1, 2];\n\njulia> a == b\ntrue\n\njulia> a === b\nfalse\n\njulia> a === a\ntrue\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Core.isa", - "page": "Essentials", - "title": "Core.isa", - "category": "function", - "text": "isa(x, type) -> Bool\n\nDetermine whether x is of the given type. Can also be used as an infix operator, e.g. x isa type.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.isequal-Tuple{Any,Any}", - "page": "Essentials", - "title": "Base.isequal", - "category": "method", - "text": "isequal(x, y)\n\nSimilar to ==, except treats all floating-point NaN values as equal to each other, and treats -0.0 as unequal to 0.0. The default implementation of isequal calls ==, so if you have a type that doesn\'t have these floating-point subtleties then you probably only need to define ==.\n\nisequal is the comparison function used by hash tables (Dict). isequal(x,y) must imply that hash(x) == hash(y).\n\nThis typically means that if you define your own == function then you must define a corresponding hash (and vice versa). Collections typically implement isequal by calling isequal recursively on all contents.\n\nScalar types generally do not need to implement isequal separate from ==, unless they represent floating-point numbers amenable to a more efficient implementation than that provided as a generic fallback (based on isnan, signbit, and ==).\n\njulia> isequal([1., NaN], [1., NaN])\ntrue\n\njulia> [1., NaN] == [1., NaN]\nfalse\n\njulia> 0.0 == -0.0\ntrue\n\njulia> isequal(0.0, -0.0)\nfalse\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.isequal-Tuple{Nullable,Nullable}", - "page": "Essentials", - "title": "Base.isequal", - "category": "method", - "text": "isequal(x, y)\n\nSimilar to ==, except treats all floating-point NaN values as equal to each other, and treats -0.0 as unequal to 0.0. The default implementation of isequal calls ==, so if you have a type that doesn\'t have these floating-point subtleties then you probably only need to define ==.\n\nisequal is the comparison function used by hash tables (Dict). isequal(x,y) must imply that hash(x) == hash(y).\n\nThis typically means that if you define your own == function then you must define a corresponding hash (and vice versa). Collections typically implement isequal by calling isequal recursively on all contents.\n\nScalar types generally do not need to implement isequal separate from ==, unless they represent floating-point numbers amenable to a more efficient implementation than that provided as a generic fallback (based on isnan, signbit, and ==).\n\njulia> isequal([1., NaN], [1., NaN])\ntrue\n\njulia> [1., NaN] == [1., NaN]\nfalse\n\njulia> 0.0 == -0.0\ntrue\n\njulia> isequal(0.0, -0.0)\nfalse\n\n\n\nisequal(x::Nullable, y::Nullable)\n\nIf neither x nor y is null, compare them according to their values (i.e. isequal(get(x), get(y))). Else, return true if both arguments are null, and false if one is null but not the other: nulls are considered equal.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.isless", - "page": "Essentials", - "title": "Base.isless", - "category": "function", - "text": "isless(x, y)\n\nTest whether x is less than y, according to a canonical total order. Values that are normally unordered, such as NaN, are ordered in an arbitrary but consistent fashion. This is the default comparison used by sort. Non-numeric types with a canonical total order should implement this function. Numeric types only need to implement it if they have special values such as NaN.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.isless-Tuple{Nullable,Nullable}", - "page": "Essentials", - "title": "Base.isless", - "category": "method", - "text": "isless(x::Nullable, y::Nullable)\n\nIf neither x nor y is null, compare them according to their values (i.e. isless(get(x), get(y))). Else, return true if only y is null, and false otherwise: nulls are always considered greater than non-nulls, but not greater than another null.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.ifelse", - "page": "Essentials", - "title": "Base.ifelse", - "category": "function", - "text": "ifelse(condition::Bool, x, y)\n\nReturn x if condition is true, otherwise return y. This differs from ? or if in that it is an ordinary function, so all the arguments are evaluated first. In some cases, using ifelse instead of an if statement can eliminate the branch in generated code and provide higher performance in tight loops.\n\njulia> ifelse(1 > 2, 1, 2)\n2\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.lexcmp", - "page": "Essentials", - "title": "Base.lexcmp", - "category": "function", - "text": "lexcmp(x, y)\n\nCompare x and y lexicographically and return -1, 0, or 1 depending on whether x is less than, equal to, or greater than y, respectively. This function should be defined for lexicographically comparable types, and lexless will call lexcmp by default.\n\njulia> lexcmp(\"abc\", \"abd\")\n-1\n\njulia> lexcmp(\"abc\", \"abc\")\n0\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.lexless", - "page": "Essentials", - "title": "Base.lexless", - "category": "function", - "text": "lexless(x, y)\n\nDetermine whether x is lexicographically less than y.\n\njulia> lexless(\"abc\", \"abd\")\ntrue\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Core.typeof", - "page": "Essentials", - "title": "Core.typeof", - "category": "function", - "text": "typeof(x)\n\nGet the concrete type of x.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Core.tuple", - "page": "Essentials", - "title": "Core.tuple", - "category": "function", - "text": "tuple(xs...)\n\nConstruct a tuple of the given objects.\n\nExample\n\njulia> tuple(1, \'a\', pi)\n(1, \'a\', π = 3.1415926535897...)\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.ntuple", - "page": "Essentials", - "title": "Base.ntuple", - "category": "function", - "text": "ntuple(f::Function, n::Integer)\n\nCreate a tuple of length n, computing each element as f(i), where i is the index of the element.\n\njulia> ntuple(i -> 2*i, 4)\n(2, 4, 6, 8)\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.object_id", - "page": "Essentials", - "title": "Base.object_id", - "category": "function", - "text": "object_id(x)\n\nGet a hash value for x based on object identity. object_id(x)==object_id(y) if x === y.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.hash", - "page": "Essentials", - "title": "Base.hash", - "category": "function", - "text": "hash(x[, h::UInt])\n\nCompute an integer hash code such that isequal(x,y) implies hash(x)==hash(y). The optional second argument h is a hash code to be mixed with the result.\n\nNew types should implement the 2-argument form, typically by calling the 2-argument hash method recursively in order to mix hashes of the contents with each other (and with h). Typically, any type that implements hash should also implement its own == (hence isequal) to guarantee the property mentioned above.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.finalizer", - "page": "Essentials", - "title": "Base.finalizer", - "category": "function", - "text": "finalizer(x, f)\n\nRegister a function f(x) to be called when there are no program-accessible references to x. The type of x must be a mutable struct, otherwise the behavior of this function is unpredictable.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.finalize", - "page": "Essentials", - "title": "Base.finalize", - "category": "function", - "text": "finalize(x)\n\nImmediately run finalizers registered for object x.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.copy", - "page": "Essentials", - "title": "Base.copy", - "category": "function", - "text": "copy(x)\n\nCreate a shallow copy of x: the outer structure is copied, but not all internal values. For example, copying an array produces a new array with identically-same elements as the original.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.deepcopy", - "page": "Essentials", - "title": "Base.deepcopy", - "category": "function", - "text": "deepcopy(x)\n\nCreate a deep copy of x: everything is copied recursively, resulting in a fully independent object. For example, deep-copying an array produces a new array whose elements are deep copies of the original elements. Calling deepcopy on an object should generally have the same effect as serializing and then deserializing it.\n\nAs a special case, functions can only be actually deep-copied if they are anonymous, otherwise they are just copied. The difference is only relevant in the case of closures, i.e. functions which may contain hidden internal references.\n\nWhile it isn\'t normally necessary, user-defined types can override the default deepcopy behavior by defining a specialized version of the function deepcopy_internal(x::T, dict::ObjectIdDict) (which shouldn\'t otherwise be used), where T is the type to be specialized for, and dict keeps track of objects copied so far within the recursion. Within the definition, deepcopy_internal should be used in place of deepcopy, and the dict variable should be updated as appropriate before returning.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Core.isdefined", - "page": "Essentials", - "title": "Core.isdefined", - "category": "function", - "text": "isdefined([m::Module,] s::Symbol)\nisdefined(object, s::Symbol)\nisdefined(object, index::Int)\n\nTests whether an assignable location is defined. The arguments can be a module and a symbol or a composite object and field name (as a symbol) or index. With a single symbol argument, tests whether a global variable with that name is defined in current_module().\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.convert", - "page": "Essentials", - "title": "Base.convert", - "category": "function", - "text": "convert(T, x)\n\nConvert x to a value of type T.\n\nIf T is an Integer type, an InexactError will be raised if x is not representable by T, for example if x is not integer-valued, or is outside the range supported by T.\n\nExamples\n\njulia> convert(Int, 3.0)\n3\n\njulia> convert(Int, 3.5)\nERROR: InexactError()\nStacktrace:\n [1] convert(::Type{Int64}, ::Float64) at ./float.jl:679\n\nIf T is a AbstractFloat or Rational type, then it will return the closest value to x representable by T.\n\njulia> x = 1/3\n0.3333333333333333\n\njulia> convert(Float32, x)\n0.33333334f0\n\njulia> convert(Rational{Int32}, x)\n1//3\n\njulia> convert(Rational{Int64}, x)\n6004799503160661//18014398509481984\n\nIf T is a collection type and x a collection, the result of convert(T, x) may alias x.\n\njulia> x = Int[1,2,3];\n\njulia> y = convert(Vector{Int}, x);\n\njulia> y === x\ntrue\n\nSimilarly, if T is a composite type and x a related instance, the result of convert(T, x) may alias part or all of x.\n\njulia> x = speye(5);\n\njulia> typeof(x)\nSparseMatrixCSC{Float64,Int64}\n\njulia> y = convert(SparseMatrixCSC{Float64,Int64}, x);\n\njulia> z = convert(SparseMatrixCSC{Float32,Int64}, y);\n\njulia> y === x\ntrue\n\njulia> z === x\nfalse\n\njulia> z.colptr === x.colptr\ntrue\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.promote", - "page": "Essentials", - "title": "Base.promote", - "category": "function", - "text": "promote(xs...)\n\nConvert all arguments to their common promotion type (if any), and return them all (as a tuple).\n\nExample\n\njulia> promote(Int8(1), Float16(4.5), Float32(4.1))\n(1.0f0, 4.5f0, 4.1f0)\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.oftype", - "page": "Essentials", - "title": "Base.oftype", - "category": "function", - "text": "oftype(x, y)\n\nConvert y to the type of x (convert(typeof(x), y)).\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.widen", - "page": "Essentials", - "title": "Base.widen", - "category": "function", - "text": "widen(x)\n\nIf x is a type, return a \"larger\" type (for numeric types, this will be a type with at least as much range and precision as the argument, and usually more). Otherwise x is converted to widen(typeof(x)).\n\nExamples\n\njulia> widen(Int32)\nInt64\n\njulia> widen(1.5f0)\n1.5\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.identity", - "page": "Essentials", - "title": "Base.identity", - "category": "function", - "text": "identity(x)\n\nThe identity function. Returns its argument.\n\njulia> identity(\"Well, what did you expect?\")\n\"Well, what did you expect?\"\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#All-Objects-1", - "page": "Essentials", - "title": "All Objects", - "category": "section", - "text": "Core.:(===)\nCore.isa\nBase.isequal(::Any, ::Any)\nBase.isequal(::Nullable, ::Nullable)\nBase.isless\nBase.isless(::Nullable, ::Nullable)\nBase.ifelse\nBase.lexcmp\nBase.lexless\nCore.typeof\nCore.tuple\nBase.ntuple\nBase.object_id\nBase.hash\nBase.finalizer\nBase.finalize\nBase.copy\nBase.deepcopy\nCore.isdefined\nBase.convert\nBase.promote\nBase.oftype\nBase.widen\nBase.identity" -}, - -{ - "location": "stdlib/base.html#Base.supertype", - "page": "Essentials", - "title": "Base.supertype", - "category": "function", - "text": "supertype(T::DataType)\n\nReturn the supertype of DataType T.\n\njulia> supertype(Int32)\nSigned\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Core.issubtype", - "page": "Essentials", - "title": "Core.issubtype", - "category": "function", - "text": "issubtype(type1, type2)\n\nReturn true if and only if all values of type1 are also of type2. Can also be written using the <: infix operator as type1 <: type2.\n\nExamples\n\njulia> issubtype(Int8, Int32)\nfalse\n\njulia> Int8 <: Integer\ntrue\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.:<:", - "page": "Essentials", - "title": "Base.:<:", - "category": "function", - "text": "<:(T1, T2)\n\nSubtype operator, equivalent to issubtype(T1, T2).\n\njulia> Float64 <: AbstractFloat\ntrue\n\njulia> Vector{Int} <: AbstractArray\ntrue\n\njulia> Matrix{Float64} <: Matrix{AbstractFloat}\nfalse\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.:>:", - "page": "Essentials", - "title": "Base.:>:", - "category": "function", - "text": ">:(T1, T2)\n\nSupertype operator, equivalent to issubtype(T2, T1).\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.subtypes", - "page": "Essentials", - "title": "Base.subtypes", - "category": "function", - "text": "subtypes(T::DataType)\n\nReturn a list of immediate subtypes of DataType T. Note that all currently loaded subtypes are included, including those not visible in the current module.\n\njulia> subtypes(Integer)\n4-element Array{Union{DataType, UnionAll},1}:\n BigInt\n Bool\n Signed\n Unsigned\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.typemin", - "page": "Essentials", - "title": "Base.typemin", - "category": "function", - "text": "typemin(T)\n\nThe lowest value representable by the given (real) numeric DataType T.\n\nExamples\n\njulia> typemin(Float16)\n-Inf16\n\njulia> typemin(Float32)\n-Inf32\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.typemax", - "page": "Essentials", - "title": "Base.typemax", - "category": "function", - "text": "typemax(T)\n\nThe highest value representable by the given (real) numeric DataType.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.realmin", - "page": "Essentials", - "title": "Base.realmin", - "category": "function", - "text": "realmin(T)\n\nThe smallest in absolute value non-subnormal value representable by the given floating-point DataType T.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.realmax", - "page": "Essentials", - "title": "Base.realmax", - "category": "function", - "text": "realmax(T)\n\nThe highest finite value representable by the given floating-point DataType T.\n\nExamples\n\njulia> realmax(Float16)\nFloat16(6.55e4)\n\njulia> realmax(Float32)\n3.4028235f38\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.maxintfloat", - "page": "Essentials", - "title": "Base.maxintfloat", - "category": "function", - "text": "maxintfloat(T)\n\nThe largest integer losslessly representable by the given floating-point DataType T.\n\n\n\nmaxintfloat(T, S)\n\nThe largest integer losslessly representable by the given floating-point DataType T that also does not exceed the maximum integer representable by the integer DataType S.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.sizeof-Tuple{Type}", - "page": "Essentials", - "title": "Base.sizeof", - "category": "method", - "text": "sizeof(T)\n\nSize, in bytes, of the canonical binary representation of the given DataType T, if any.\n\nExamples\n\njulia> sizeof(Float32)\n4\n\njulia> sizeof(Complex128)\n16\n\nIf T does not have a specific size, an error is thrown.\n\njulia> sizeof(Base.LinAlg.LU)\nERROR: argument is an abstract type; size is indeterminate\nStacktrace:\n [1] sizeof(::Type{T} where T) at ./essentials.jl:159\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.eps-Tuple{Type{#s27} where #s27<:AbstractFloat}", - "page": "Essentials", - "title": "Base.eps", - "category": "method", - "text": "eps(::Type{T}) where T<:AbstractFloat\neps()\n\nReturns the machine epsilon of the floating point type T (T = Float64 by default). This is defined as the gap between 1 and the next largest value representable by T, and is equivalent to eps(one(T)).\n\njulia> eps()\n2.220446049250313e-16\n\njulia> eps(Float32)\n1.1920929f-7\n\njulia> 1.0 + eps()\n1.0000000000000002\n\njulia> 1.0 + eps()/2\n1.0\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.eps-Tuple{AbstractFloat}", - "page": "Essentials", - "title": "Base.eps", - "category": "method", - "text": "eps(x::AbstractFloat)\n\nReturns the unit in last place (ulp) of x. This is the distance between consecutive representable floating point values at x. In most cases, if the distance on either side of x is different, then the larger of the two is taken, that is\n\neps(x) == max(x-prevfloat(x), nextfloat(x)-x)\n\nThe exceptions to this rule are the smallest and largest finite values (e.g. nextfloat(-Inf) and prevfloat(Inf) for Float64), which round to the smaller of the values.\n\nThe rationale for this behavior is that eps bounds the floating point rounding error. Under the default RoundNearest rounding mode, if y is a real number and x is the nearest floating point number to y, then\n\ny-x leq operatornameeps(x)2\n\njulia> eps(1.0)\n2.220446049250313e-16\n\njulia> eps(prevfloat(2.0))\n2.220446049250313e-16\n\njulia> eps(2.0)\n4.440892098500626e-16\n\njulia> x = prevfloat(Inf) # largest finite Float64\n1.7976931348623157e308\n\njulia> x + eps(x)/2 # rounds up\nInf\n\njulia> x + prevfloat(eps(x)/2) # rounds down\n1.7976931348623157e308\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.promote_type", - "page": "Essentials", - "title": "Base.promote_type", - "category": "function", - "text": "promote_type(type1, type2)\n\nDetermine a type big enough to hold values of each argument type without loss, whenever possible. In some cases, where no type exists to which both types can be promoted losslessly, some loss is tolerated; for example, promote_type(Int64, Float64) returns Float64 even though strictly, not all Int64 values can be represented exactly as Float64 values.\n\njulia> promote_type(Int64, Float64)\nFloat64\n\njulia> promote_type(Int32, Int64)\nInt64\n\njulia> promote_type(Float32, BigInt)\nBigFloat\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.promote_rule", - "page": "Essentials", - "title": "Base.promote_rule", - "category": "function", - "text": "promote_rule(type1, type2)\n\nSpecifies what type should be used by promote when given values of types type1 and type2. This function should not be called directly, but should have definitions added to it for new types as appropriate.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Core.getfield", - "page": "Essentials", - "title": "Core.getfield", - "category": "function", - "text": "getfield(value, name::Symbol)\n\nExtract a named field from a value of composite type. The syntax a.b calls getfield(a, :b).\n\nExample\n\njulia> a = 1//2\n1//2\n\njulia> getfield(a, :num)\n1\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Core.setfield!", - "page": "Essentials", - "title": "Core.setfield!", - "category": "function", - "text": "setfield!(value, name::Symbol, x)\n\nAssign x to a named field in value of composite type. The syntax a.b = c calls setfield!(a, :b, c).\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.fieldoffset", - "page": "Essentials", - "title": "Base.fieldoffset", - "category": "function", - "text": "fieldoffset(type, i)\n\nThe byte offset of field i of a type relative to the data start. For example, we could use it in the following manner to summarize information about a struct:\n\njulia> structinfo(T) = [(fieldoffset(T,i), fieldname(T,i), fieldtype(T,i)) for i = 1:nfields(T)];\n\njulia> structinfo(Base.Filesystem.StatStruct)\n12-element Array{Tuple{UInt64,Symbol,DataType},1}:\n (0x0000000000000000, :device, UInt64)\n (0x0000000000000008, :inode, UInt64)\n (0x0000000000000010, :mode, UInt64)\n (0x0000000000000018, :nlink, Int64)\n (0x0000000000000020, :uid, UInt64)\n (0x0000000000000028, :gid, UInt64)\n (0x0000000000000030, :rdev, UInt64)\n (0x0000000000000038, :size, Int64)\n (0x0000000000000040, :blksize, Int64)\n (0x0000000000000048, :blocks, Int64)\n (0x0000000000000050, :mtime, Float64)\n (0x0000000000000058, :ctime, Float64)\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Core.fieldtype", - "page": "Essentials", - "title": "Core.fieldtype", - "category": "function", - "text": "fieldtype(T, name::Symbol | index::Int)\n\nDetermine the declared type of a field (specified by name or index) in a composite DataType T.\n\njulia> struct Foo\n x::Int64\n y::String\n end\n\njulia> fieldtype(Foo, :x)\nInt64\n\njulia> fieldtype(Foo, 2)\nString\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.isimmutable", - "page": "Essentials", - "title": "Base.isimmutable", - "category": "function", - "text": "isimmutable(v)\n\nReturn true iff value v is immutable. See Mutable Composite Types for a discussion of immutability. Note that this function works on values, so if you give it a type, it will tell you that a value of DataType is mutable.\n\njulia> isimmutable(1)\ntrue\n\njulia> isimmutable([1,2])\nfalse\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.isbits", - "page": "Essentials", - "title": "Base.isbits", - "category": "function", - "text": "isbits(T)\n\nReturn true if T is a \"plain data\" type, meaning it is immutable and contains no references to other values. Typical examples are numeric types such as UInt8, Float64, and Complex{Float64}.\n\njulia> isbits(Complex{Float64})\ntrue\n\njulia> isbits(Complex)\nfalse\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.isleaftype", - "page": "Essentials", - "title": "Base.isleaftype", - "category": "function", - "text": "isleaftype(T)\n\nDetermine whether T\'s only subtypes are itself and Union{}. This means T is a concrete type that can have instances.\n\njulia> isleaftype(Complex)\nfalse\n\njulia> isleaftype(Complex{Float32})\ntrue\n\njulia> isleaftype(Vector{Complex})\ntrue\n\njulia> isleaftype(Vector{Complex{Float32}})\ntrue\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.typejoin", - "page": "Essentials", - "title": "Base.typejoin", - "category": "function", - "text": "typejoin(T, S)\n\nCompute a type that contains both T and S.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.typeintersect", - "page": "Essentials", - "title": "Base.typeintersect", - "category": "function", - "text": "typeintersect(T, S)\n\nCompute a type that contains the intersection of T and S. Usually this will be the smallest such type or one close to it.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.Val", - "page": "Essentials", - "title": "Base.Val", - "category": "type", - "text": "Val{c}\n\nCreate a \"value type\" out of c, which must be an isbits value. The intent of this construct is to be able to dispatch on constants, e.g., f(Val{false}) allows you to dispatch directly (at compile-time) to an implementation f(::Type{Val{false}}), without having to test the boolean value at runtime.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.Enums.@enum", - "page": "Essentials", - "title": "Base.Enums.@enum", - "category": "macro", - "text": "@enum EnumName[::BaseType] value1[=x] value2[=y]\n\nCreate an Enum{BaseType} subtype with name EnumName and enum member values of value1 and value2 with optional assigned values of x and y, respectively. EnumName can be used just like other types and enum member values as regular values, such as\n\njulia> @enum Fruit apple=1 orange=2 kiwi=3\n\njulia> f(x::Fruit) = \"I\'m a Fruit with value: $(Int(x))\"\nf (generic function with 1 method)\n\njulia> f(apple)\n\"I\'m a Fruit with value: 1\"\n\nBaseType, which defaults to Int32, must be a primitive subtype of Integer. Member values can be converted between the enum type and BaseType. read and write perform these conversions automatically.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.instances", - "page": "Essentials", - "title": "Base.instances", - "category": "function", - "text": "instances(T::Type)\n\nReturn a collection of all instances of the given type, if applicable. Mostly used for enumerated types (see @enum).\n\njulia> @enum Color red blue green\n\njulia> instances(Color)\n(red::Color = 0, blue::Color = 1, green::Color = 2)\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Types-1", - "page": "Essentials", - "title": "Types", - "category": "section", - "text": "Base.supertype\nCore.issubtype\nBase.:(<:)\nBase.:(>:)\nBase.subtypes\nBase.typemin\nBase.typemax\nBase.realmin\nBase.realmax\nBase.maxintfloat\nBase.sizeof(::Type)\nBase.eps(::Type{<:AbstractFloat})\nBase.eps(::AbstractFloat)\nBase.promote_type\nBase.promote_rule\nCore.getfield\nCore.setfield!\nBase.fieldoffset\nCore.fieldtype\nBase.isimmutable\nBase.isbits\nBase.isleaftype\nBase.typejoin\nBase.typeintersect\nBase.Val\nBase.Enums.@enum\nBase.instances" -}, - -{ - "location": "stdlib/base.html#Core.Function", - "page": "Essentials", - "title": "Core.Function", - "category": "type", - "text": "Function\n\nAbstract type of all functions.\n\njulia> isa(+, Function)\ntrue\n\njulia> typeof(sin)\nBase.#sin\n\njulia> ans <: Function\ntrue\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.method_exists", - "page": "Essentials", - "title": "Base.method_exists", - "category": "function", - "text": "method_exists(f, Tuple type, world=typemax(UInt)) -> Bool\n\nDetermine whether the given generic function has a method matching the given Tuple of argument types with the upper bound of world age given by world.\n\njulia> method_exists(length, Tuple{Array})\ntrue\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Core.applicable", - "page": "Essentials", - "title": "Core.applicable", - "category": "function", - "text": "applicable(f, args...) -> Bool\n\nDetermine whether the given generic function has a method applicable to the given arguments.\n\nExamples\n\njulia> function f(x, y)\n x + y\n end;\n\njulia> applicable(f, 1)\nfalse\n\njulia> applicable(f, 1, 2)\ntrue\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Core.invoke", - "page": "Essentials", - "title": "Core.invoke", - "category": "function", - "text": "invoke(f, types <: Tuple, args...)\n\nInvoke a method for the given generic function matching the specified types, on the specified arguments. The arguments must be compatible with the specified types. This allows invoking a method other than the most specific matching method, which is useful when the behavior of a more general definition is explicitly needed (often as part of the implementation of a more specific method of the same function).\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.invokelatest", - "page": "Essentials", - "title": "Base.invokelatest", - "category": "function", - "text": "invokelatest(f, args...)\n\nCalls f(args...), but guarantees that the most recent method of f will be executed. This is useful in specialized circumstances, e.g. long-running event loops or callback functions that may call obsolete versions of a function f. (The drawback is that invokelatest is somewhat slower than calling f directly, and the type of the result cannot be inferred by the compiler.)\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.:|>", - "page": "Essentials", - "title": "Base.:|>", - "category": "function", - "text": "|>(x, f)\n\nApplies a function to the preceding argument. This allows for easy function chaining.\n\njulia> [1:5;] |> x->x.^2 |> sum |> inv\n0.01818181818181818\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.:∘", - "page": "Essentials", - "title": "Base.:∘", - "category": "function", - "text": "f ∘ g\n\nCompose functions: i.e. (f ∘ g)(args...) means f(g(args...)). The ∘ symbol can be entered in the Julia REPL (and most editors, appropriately configured) by typing \\circ. Example:\n\njulia> map(uppercase∘hex, 250:255)\n6-element Array{String,1}:\n \"FA\"\n \"FB\"\n \"FC\"\n \"FD\"\n \"FE\"\n \"FF\"\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Generic-Functions-1", - "page": "Essentials", - "title": "Generic Functions", - "category": "section", - "text": "Core.Function\nBase.method_exists\nCore.applicable\nCore.invoke\nBase.invokelatest\nBase.:(|>)\nBase.:(∘)" -}, - -{ - "location": "stdlib/base.html#Core.eval", - "page": "Essentials", - "title": "Core.eval", - "category": "function", - "text": "eval([m::Module], expr::Expr)\n\nEvaluate an expression in the given module and return the result. Every Module (except those defined with baremodule) has its own 1-argument definition of eval, which evaluates expressions in that module.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.@eval", - "page": "Essentials", - "title": "Base.@eval", - "category": "macro", - "text": "@eval [mod,] ex\n\nEvaluate an expression with values interpolated into it using eval. If two arguments are provided, the first is the module to evaluate in.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.evalfile", - "page": "Essentials", - "title": "Base.evalfile", - "category": "function", - "text": "evalfile(path::AbstractString, args::Vector{String}=String[])\n\nLoad the file using include, evaluate all expressions, and return the value of the last one.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.esc", - "page": "Essentials", - "title": "Base.esc", - "category": "function", - "text": "esc(e::ANY)\n\nOnly valid in the context of an Expr returned from a macro. Prevents the macro hygiene pass from turning embedded variables into gensym variables. See the Macros section of the Metaprogramming chapter of the manual for more details and examples.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.@inbounds", - "page": "Essentials", - "title": "Base.@inbounds", - "category": "macro", - "text": "@inbounds(blk)\n\nEliminates array bounds checking within expressions.\n\nIn the example below the bound check of array A is skipped to improve performance.\n\nfunction sum(A::AbstractArray)\n r = zero(eltype(A))\n for i = 1:length(A)\n @inbounds r += A[i]\n end\n return r\nend\n\nwarning: Warning\nUsing @inbounds may return incorrect results/crashes/corruption for out-of-bounds indices. The user is responsible for checking it manually.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.@inline", - "page": "Essentials", - "title": "Base.@inline", - "category": "macro", - "text": "@inline\n\nGive a hint to the compiler that this function is worth inlining.\n\nSmall functions typically do not need the @inline annotation, as the compiler does it automatically. By using @inline on bigger functions, an extra nudge can be given to the compiler to inline it. This is shown in the following example:\n\n@inline function bigfunction(x)\n #=\n Function Definition\n =#\nend\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.@noinline", - "page": "Essentials", - "title": "Base.@noinline", - "category": "macro", - "text": "@noinline\n\nPrevents the compiler from inlining a function.\n\nSmall functions are typically inlined automatically. By using @noinline on small functions, auto-inlining can be prevented. This is shown in the following example:\n\n@noinline function smallfunction(x)\n #=\n Function Definition\n =#\nend\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.gensym", - "page": "Essentials", - "title": "Base.gensym", - "category": "function", - "text": "gensym([tag])\n\nGenerates a symbol which will not conflict with other variable names.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.@gensym", - "page": "Essentials", - "title": "Base.@gensym", - "category": "macro", - "text": "@gensym\n\nGenerates a gensym symbol for a variable. For example, @gensym x y is transformed into x = gensym(\"x\"); y = gensym(\"y\").\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.@polly", - "page": "Essentials", - "title": "Base.@polly", - "category": "macro", - "text": "@polly\n\nTells the compiler to apply the polyhedral optimizer Polly to a function.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.parse-Tuple{Any,Any}", - "page": "Essentials", - "title": "Base.parse", - "category": "method", - "text": "parse(str, start; greedy=true, raise=true)\n\nParse the expression string and return an expression (which could later be passed to eval for execution). start is the index of the first character to start parsing. If greedy is true (default), parse will try to consume as much input as it can; otherwise, it will stop as soon as it has parsed a valid expression. Incomplete but otherwise syntactically valid expressions will return Expr(:incomplete, \"(error message)\"). If raise is true (default), syntax errors other than incomplete expressions will raise an error. If raise is false, parse will return an expression that will raise an error upon evaluation.\n\njulia> parse(\"x = 3, y = 5\", 7)\n(:(y = 5), 13)\n\njulia> parse(\"x = 3, y = 5\", 5)\n(:((3, y) = 5), 13)\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.parse-Tuple{Any}", - "page": "Essentials", - "title": "Base.parse", - "category": "method", - "text": "parse(str; raise=true)\n\nParse the expression string greedily, returning a single expression. An error is thrown if there are additional characters after the first expression. If raise is true (default), syntax errors will raise an error; otherwise, parse will return an expression that will raise an error upon evaluation.\n\njulia> parse(\"x = 3\")\n:(x = 3)\n\njulia> parse(\"x = \")\n:($(Expr(:incomplete, \"incomplete: premature end of input\")))\n\njulia> parse(\"1.0.2\")\nERROR: ParseError(\"invalid numeric constant \\\"1.0.\\\"\")\nStacktrace:\n[...]\n\njulia> parse(\"1.0.2\"; raise = false)\n:($(Expr(:error, \"invalid numeric constant \\\"1.0.\\\"\")))\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Syntax-1", - "page": "Essentials", - "title": "Syntax", - "category": "section", - "text": "Core.eval\nBase.@eval\nBase.evalfile\nBase.esc\nBase.@inbounds\nBase.@inline\nBase.@noinline\nBase.gensym\nBase.@gensym\nBase.@polly\nBase.parse(::Any, ::Any)\nBase.parse(::Any)" -}, - -{ - "location": "stdlib/base.html#Base.Nullable", - "page": "Essentials", - "title": "Base.Nullable", - "category": "type", - "text": "Nullable(x, hasvalue::Bool=true)\n\nWrap value x in an object of type Nullable, which indicates whether a value is present. Nullable(x) yields a non-empty wrapper and Nullable{T}() yields an empty instance of a wrapper that might contain a value of type T.\n\nNullable(x, false) yields Nullable{typeof(x)}() with x stored in the result\'s value field.\n\nExamples\n\njulia> Nullable(1)\nNullable{Int64}(1)\n\njulia> Nullable{Int64}()\nNullable{Int64}()\n\njulia> Nullable(1, false)\nNullable{Int64}()\n\njulia> dump(Nullable(1, false))\nNullable{Int64}\n hasvalue: Bool false\n value: Int64 1\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.get-Tuple{Nullable,Any}", - "page": "Essentials", - "title": "Base.get", - "category": "method", - "text": "get(x::Nullable[, y])\n\nAttempt to access the value of x. Returns the value if it is present; otherwise, returns y if provided, or throws a NullException if not.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.isnull", - "page": "Essentials", - "title": "Base.isnull", - "category": "function", - "text": "isnull(x)\n\nReturn whether or not x is null for Nullable x; return false for all other x.\n\nExamples\n\njulia> x = Nullable(1, false)\nNullable{Int64}()\n\njulia> isnull(x)\ntrue\n\njulia> x = Nullable(1, true)\nNullable{Int64}(1)\n\njulia> isnull(x)\nfalse\n\njulia> x = 1\n1\n\njulia> isnull(x)\nfalse\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.unsafe_get", - "page": "Essentials", - "title": "Base.unsafe_get", - "category": "function", - "text": "unsafe_get(x)\n\nReturn the value of x for Nullable x; return x for all other x.\n\nThis method does not check whether or not x is null before attempting to access the value of x for x::Nullable (hence \"unsafe\").\n\njulia> x = Nullable(1)\nNullable{Int64}(1)\n\njulia> unsafe_get(x)\n1\n\njulia> x = Nullable{String}()\nNullable{String}()\n\njulia> unsafe_get(x)\nERROR: UndefRefError: access to undefined reference\nStacktrace:\n [1] unsafe_get(::Nullable{String}) at ./nullable.jl:125\n\njulia> x = 1\n1\n\njulia> unsafe_get(x)\n1\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Nullables-1", - "page": "Essentials", - "title": "Nullables", - "category": "section", - "text": "Base.Nullable\nBase.get(::Nullable, ::Any)\nBase.isnull\nBase.unsafe_get" -}, - -{ - "location": "stdlib/base.html#Base.run", - "page": "Essentials", - "title": "Base.run", - "category": "function", - "text": "run(command, args...)\n\nRun a command object, constructed with backticks. Throws an error if anything goes wrong, including the process exiting with a non-zero status.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.spawn", - "page": "Essentials", - "title": "Base.spawn", - "category": "function", - "text": "spawn(command)\n\nRun a command object asynchronously, returning the resulting Process object.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.DevNull", - "page": "Essentials", - "title": "Base.DevNull", - "category": "constant", - "text": "DevNull\n\nUsed in a stream redirect to discard all data written to it. Essentially equivalent to /dev/null on Unix or NUL on Windows. Usage:\n\nrun(pipeline(`cat test.txt`, DevNull))\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.success", - "page": "Essentials", - "title": "Base.success", - "category": "function", - "text": "success(command)\n\nRun a command object, constructed with backticks, and tell whether it was successful (exited with a code of 0). An exception is raised if the process cannot be started.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.process_running", - "page": "Essentials", - "title": "Base.process_running", - "category": "function", - "text": "process_running(p::Process)\n\nDetermine whether a process is currently running.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.process_exited", - "page": "Essentials", - "title": "Base.process_exited", - "category": "function", - "text": "process_exited(p::Process)\n\nDetermine whether a process has exited.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.kill-Tuple{Base.Process,Integer}", - "page": "Essentials", - "title": "Base.kill", - "category": "method", - "text": "kill(p::Process, signum=SIGTERM)\n\nSend a signal to a process. The default is to terminate the process.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.Sys.set_process_title", - "page": "Essentials", - "title": "Base.Sys.set_process_title", - "category": "function", - "text": "Sys.set_process_title(title::AbstractString)\n\nSet the process title. No-op on some operating systems.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.Sys.get_process_title", - "page": "Essentials", - "title": "Base.Sys.get_process_title", - "category": "function", - "text": "Sys.get_process_title()\n\nGet the process title. On some systems, will always return an empty string.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.readandwrite", - "page": "Essentials", - "title": "Base.readandwrite", - "category": "function", - "text": "readandwrite(command)\n\nStarts running a command asynchronously, and returns a tuple (stdout,stdin,process) of the output stream and input stream of the process, and the process object itself.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.ignorestatus", - "page": "Essentials", - "title": "Base.ignorestatus", - "category": "function", - "text": "ignorestatus(command)\n\nMark a command object so that running it will not throw an error if the result code is non-zero.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.detach", - "page": "Essentials", - "title": "Base.detach", - "category": "function", - "text": "detach(command)\n\nMark a command object so that it will be run in a new process group, allowing it to outlive the julia process, and not have Ctrl-C interrupts passed to it.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.Cmd", - "page": "Essentials", - "title": "Base.Cmd", - "category": "type", - "text": "Cmd(cmd::Cmd; ignorestatus, detach, windows_verbatim, windows_hide, env, dir)\n\nConstruct a new Cmd object, representing an external program and arguments, from cmd, while changing the settings of the optional keyword arguments:\n\nignorestatus::Bool: If true (defaults to false), then the Cmd will not throw an error if the return code is nonzero.\ndetach::Bool: If true (defaults to false), then the Cmd will be run in a new process group, allowing it to outlive the julia process and not have Ctrl-C passed to it.\nwindows_verbatim::Bool: If true (defaults to false), then on Windows the Cmd will send a command-line string to the process with no quoting or escaping of arguments, even arguments containing spaces. (On Windows, arguments are sent to a program as a single \"command-line\" string, and programs are responsible for parsing it into arguments. By default, empty arguments and arguments with spaces or tabs are quoted with double quotes \" in the command line, and \\ or \" are preceded by backslashes. windows_verbatim=true is useful for launching programs that parse their command line in nonstandard ways.) Has no effect on non-Windows systems.\nwindows_hide::Bool: If true (defaults to false), then on Windows no new console window is displayed when the Cmd is executed. This has no effect if a console is already open or on non-Windows systems.\nenv: Set environment variables to use when running the Cmd. env is either a dictionary mapping strings to strings, an array of strings of the form \"var=val\", an array or tuple of \"var\"=>val pairs, or nothing. In order to modify (rather than replace) the existing environment, create env by copy(ENV) and then set env[\"var\"]=val as desired.\ndir::AbstractString: Specify a working directory for the command (instead of the current directory).\n\nFor any keywords that are not specified, the current settings from cmd are used. Normally, to create a Cmd object in the first place, one uses backticks, e.g.\n\nCmd(`echo \"Hello world\"`, ignorestatus=true, detach=false)\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.setenv", - "page": "Essentials", - "title": "Base.setenv", - "category": "function", - "text": "setenv(command::Cmd, env; dir=\"\")\n\nSet environment variables to use when running the given command. env is either a dictionary mapping strings to strings, an array of strings of the form \"var=val\", or zero or more \"var\"=>val pair arguments. In order to modify (rather than replace) the existing environment, create env by copy(ENV) and then setting env[\"var\"]=val as desired, or use withenv.\n\nThe dir keyword argument can be used to specify a working directory for the command.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.withenv", - "page": "Essentials", - "title": "Base.withenv", - "category": "function", - "text": "withenv(f::Function, kv::Pair...)\n\nExecute f() in an environment that is temporarily modified (not replaced as in setenv) by zero or more \"var\"=>val arguments kv. withenv is generally used via the withenv(kv...) do ... end syntax. A value of nothing can be used to temporarily unset an environment variable (if it is set). When withenv returns, the original environment has been restored.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.pipeline-Tuple{Any,Any,Any,Vararg{Any,N} where N}", - "page": "Essentials", - "title": "Base.pipeline", - "category": "method", - "text": "pipeline(from, to, ...)\n\nCreate a pipeline from a data source to a destination. The source and destination can be commands, I/O streams, strings, or results of other pipeline calls. At least one argument must be a command. Strings refer to filenames. When called with more than two arguments, they are chained together from left to right. For example pipeline(a,b,c) is equivalent to pipeline(pipeline(a,b),c). This provides a more concise way to specify multi-stage pipelines.\n\nExamples:\n\nrun(pipeline(`ls`, `grep xyz`))\nrun(pipeline(`ls`, \"out.txt\"))\nrun(pipeline(\"out.txt\", `grep xyz`))\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.pipeline-Tuple{Base.AbstractCmd}", - "page": "Essentials", - "title": "Base.pipeline", - "category": "method", - "text": "pipeline(command; stdin, stdout, stderr, append=false)\n\nRedirect I/O to or from the given command. Keyword arguments specify which of the command\'s streams should be redirected. append controls whether file output appends to the file. This is a more general version of the 2-argument pipeline function. pipeline(from, to) is equivalent to pipeline(from, stdout=to) when from is a command, and to pipeline(to, stdin=from) when from is another kind of data source.\n\nExamples:\n\nrun(pipeline(`dothings`, stdout=\"out.txt\", stderr=\"errs.txt\"))\nrun(pipeline(`update`, stdout=\"log.txt\", append=true))\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.Libc.gethostname", - "page": "Essentials", - "title": "Base.Libc.gethostname", - "category": "function", - "text": "gethostname() -> AbstractString\n\nGet the local machine\'s host name.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.getipaddr", - "page": "Essentials", - "title": "Base.getipaddr", - "category": "function", - "text": "getipaddr() -> IPAddr\n\nGet the IP address of the local machine.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.Libc.getpid", - "page": "Essentials", - "title": "Base.Libc.getpid", - "category": "function", - "text": "getpid() -> Int32\n\nGet Julia\'s process ID.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.Libc.time-Tuple{}", - "page": "Essentials", - "title": "Base.Libc.time", - "category": "method", - "text": "time()\n\nGet the system time in seconds since the epoch, with fairly high (typically, microsecond) resolution.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.time_ns", - "page": "Essentials", - "title": "Base.time_ns", - "category": "function", - "text": "time_ns()\n\nGet the time in nanoseconds. The time corresponding to 0 is undefined, and wraps every 5.8 years.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.tic", - "page": "Essentials", - "title": "Base.tic", - "category": "function", - "text": "tic()\n\nSet a timer to be read by the next call to toc or toq. The macro call @time expr can also be used to time evaluation.\n\njulia> tic()\n0x0000c45bc7abac95\n\njulia> sleep(0.3)\n\njulia> toc()\nelapsed time: 0.302745944 seconds\n0.302745944\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.toc", - "page": "Essentials", - "title": "Base.toc", - "category": "function", - "text": "toc()\n\nPrint and return the time elapsed since the last tic. The macro call @time expr can also be used to time evaluation.\n\njulia> tic()\n0x0000c45bc7abac95\n\njulia> sleep(0.3)\n\njulia> toc()\nelapsed time: 0.302745944 seconds\n0.302745944\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.toq", - "page": "Essentials", - "title": "Base.toq", - "category": "function", - "text": "toq()\n\nReturn, but do not print, the time elapsed since the last tic. The macro calls @timed expr and @elapsed expr also return evaluation time.\n\njulia> tic()\n0x0000c46477a9675d\n\njulia> sleep(0.3)\n\njulia> toq()\n0.302251004\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.@time", - "page": "Essentials", - "title": "Base.@time", - "category": "macro", - "text": "@time\n\nA macro to execute an expression, printing the time it took to execute, the number of allocations, and the total number of bytes its execution caused to be allocated, before returning the value of the expression.\n\nSee also @timev, @timed, @elapsed, and @allocated.\n\njulia> @time rand(10^6);\n 0.001525 seconds (7 allocations: 7.630 MiB)\n\njulia> @time begin\n sleep(0.3)\n 1+1\n end\n 0.301395 seconds (8 allocations: 336 bytes)\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.@timev", - "page": "Essentials", - "title": "Base.@timev", - "category": "macro", - "text": "@timev\n\nThis is a verbose version of the @time macro. It first prints the same information as @time, then any non-zero memory allocation counters, and then returns the value of the expression.\n\nSee also @time, @timed, @elapsed, and @allocated.\n\njulia> @timev rand(10^6);\n 0.001006 seconds (7 allocations: 7.630 MiB)\nelapsed time (ns): 1005567\nbytes allocated: 8000256\npool allocs: 6\nmalloc() calls: 1\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.@timed", - "page": "Essentials", - "title": "Base.@timed", - "category": "macro", - "text": "@timed\n\nA macro to execute an expression, and return the value of the expression, elapsed time, total bytes allocated, garbage collection time, and an object with various memory allocation counters.\n\nSee also @time, @timev, @elapsed, and @allocated.\n\njulia> val, t, bytes, gctime, memallocs = @timed rand(10^6);\n\njulia> t\n0.006634834\n\njulia> bytes\n8000256\n\njulia> gctime\n0.0055765\n\njulia> fieldnames(typeof(memallocs))\n9-element Array{Symbol,1}:\n :allocd\n :malloc\n :realloc\n :poolalloc\n :bigalloc\n :freecall\n :total_time\n :pause\n :full_sweep\n\njulia> memallocs.total_time\n5576500\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.@elapsed", - "page": "Essentials", - "title": "Base.@elapsed", - "category": "macro", - "text": "@elapsed\n\nA macro to evaluate an expression, discarding the resulting value, instead returning the number of seconds it took to execute as a floating-point number.\n\nSee also @time, @timev, @timed, and @allocated.\n\njulia> @elapsed sleep(0.3)\n0.301391426\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.@allocated", - "page": "Essentials", - "title": "Base.@allocated", - "category": "macro", - "text": "@allocated\n\nA macro to evaluate an expression, discarding the resulting value, instead returning the total number of bytes allocated during evaluation of the expression. Note: the expression is evaluated inside a local function, instead of the current context, in order to eliminate the effects of compilation, however, there still may be some allocations due to JIT compilation. This also makes the results inconsistent with the @time macros, which do not try to adjust for the effects of compilation.\n\nSee also @time, @timev, @timed, and @elapsed.\n\njulia> @allocated rand(10^6)\n8000080\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.EnvHash", - "page": "Essentials", - "title": "Base.EnvHash", - "category": "type", - "text": "EnvHash() -> EnvHash\n\nA singleton of this type provides a hash table interface to environment variables.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.ENV", - "page": "Essentials", - "title": "Base.ENV", - "category": "constant", - "text": "ENV\n\nReference to the singleton EnvHash, providing a dictionary interface to system environment variables.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.is_unix", - "page": "Essentials", - "title": "Base.is_unix", - "category": "function", - "text": "is_unix([os])\n\nPredicate for testing if the OS provides a Unix-like interface. See documentation in Handling Operating System Variation.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.is_apple", - "page": "Essentials", - "title": "Base.is_apple", - "category": "function", - "text": "is_apple([os])\n\nPredicate for testing if the OS is a derivative of Apple Macintosh OS X or Darwin. See documentation in Handling Operating System Variation.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.is_linux", - "page": "Essentials", - "title": "Base.is_linux", - "category": "function", - "text": "is_linux([os])\n\nPredicate for testing if the OS is a derivative of Linux. See documentation in Handling Operating System Variation.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.is_bsd", - "page": "Essentials", - "title": "Base.is_bsd", - "category": "function", - "text": "is_bsd([os])\n\nPredicate for testing if the OS is a derivative of BSD. See documentation in Handling Operating System Variation.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.is_windows", - "page": "Essentials", - "title": "Base.is_windows", - "category": "function", - "text": "is_windows([os])\n\nPredicate for testing if the OS is a derivative of Microsoft Windows NT. See documentation in Handling Operating System Variation.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.Sys.windows_version", - "page": "Essentials", - "title": "Base.Sys.windows_version", - "category": "function", - "text": "Sys.windows_version()\n\nReturns the version number for the Windows NT Kernel as a (major, minor) pair, or (0, 0) if this is not running on Windows.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.@static", - "page": "Essentials", - "title": "Base.@static", - "category": "macro", - "text": "@static\n\nPartially evaluates an expression at parse time.\n\nFor example, @static is_windows() ? foo : bar will evaluate is_windows() and insert either foo or bar into the expression. This is useful in cases where a construct would be invalid on other platforms, such as a ccall to a non-existent function. @static if is_apple() foo end and @static foo <&&,||> bar are also valid syntax.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#System-1", - "page": "Essentials", - "title": "System", - "category": "section", - "text": "Base.run\nBase.spawn\nBase.DevNull\nBase.success\nBase.process_running\nBase.process_exited\nBase.kill(::Base.Process, ::Integer)\nBase.Sys.set_process_title\nBase.Sys.get_process_title\nBase.readandwrite\nBase.ignorestatus\nBase.detach\nBase.Cmd\nBase.setenv\nBase.withenv\nBase.pipeline(::Any, ::Any, ::Any, ::Any...)\nBase.pipeline(::Base.AbstractCmd)\nBase.Libc.gethostname\nBase.getipaddr\nBase.Libc.getpid\nBase.Libc.time()\nBase.time_ns\nBase.tic\nBase.toc\nBase.toq\nBase.@time\nBase.@timev\nBase.@timed\nBase.@elapsed\nBase.@allocated\nBase.EnvHash\nBase.ENV\nBase.is_unix\nBase.is_apple\nBase.is_linux\nBase.is_bsd\nBase.is_windows\nBase.Sys.windows_version\nBase.@static" -}, - -{ - "location": "stdlib/base.html#Base.error", - "page": "Essentials", - "title": "Base.error", - "category": "function", - "text": "error(message::AbstractString)\n\nRaise an ErrorException with the given message.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Core.throw", - "page": "Essentials", - "title": "Core.throw", - "category": "function", - "text": "throw(e)\n\nThrow an object as an exception.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.rethrow", - "page": "Essentials", - "title": "Base.rethrow", - "category": "function", - "text": "rethrow([e])\n\nThrow an object without changing the current exception backtrace. The default argument is the current exception (if called within a catch block).\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.backtrace", - "page": "Essentials", - "title": "Base.backtrace", - "category": "function", - "text": "backtrace()\n\nGet a backtrace object for the current program point.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.catch_backtrace", - "page": "Essentials", - "title": "Base.catch_backtrace", - "category": "function", - "text": "catch_backtrace()\n\nGet the backtrace of the current exception, for use within catch blocks.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.assert", - "page": "Essentials", - "title": "Base.assert", - "category": "function", - "text": "assert(cond)\n\nThrow an AssertionError if cond is false. Also available as the macro @assert expr.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.@assert", - "page": "Essentials", - "title": "Base.@assert", - "category": "macro", - "text": "@assert cond [text]\n\nThrow an AssertionError if cond is false. Preferred syntax for writing assertions. Message text is optionally displayed upon assertion failure.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.ArgumentError", - "page": "Essentials", - "title": "Base.ArgumentError", - "category": "type", - "text": "ArgumentError(msg)\n\nThe parameters to a function call do not match a valid signature. Argument msg is a descriptive error string.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.AssertionError", - "page": "Essentials", - "title": "Base.AssertionError", - "category": "type", - "text": "AssertionError([msg])\n\nThe asserted condition did not evaluate to true. Optional argument msg is a descriptive error string.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Core.BoundsError", - "page": "Essentials", - "title": "Core.BoundsError", - "category": "type", - "text": "BoundsError([a],[i])\n\nAn indexing operation into an array, a, tried to access an out-of-bounds element, i.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.DimensionMismatch", - "page": "Essentials", - "title": "Base.DimensionMismatch", - "category": "type", - "text": "DimensionMismatch([msg])\n\nThe objects called do not have matching dimensionality. Optional argument msg is a descriptive error string.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Core.DivideError", - "page": "Essentials", - "title": "Core.DivideError", - "category": "type", - "text": "DivideError()\n\nInteger division was attempted with a denominator value of 0.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Core.DomainError", - "page": "Essentials", - "title": "Core.DomainError", - "category": "type", - "text": "DomainError()\n\nThe arguments to a function or constructor are outside the valid domain.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.EOFError", - "page": "Essentials", - "title": "Base.EOFError", - "category": "type", - "text": "EOFError()\n\nNo more data was available to read from a file or stream.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Core.ErrorException", - "page": "Essentials", - "title": "Core.ErrorException", - "category": "type", - "text": "ErrorException(msg)\n\nGeneric error type. The error message, in the .msg field, may provide more specific details.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Core.InexactError", - "page": "Essentials", - "title": "Core.InexactError", - "category": "type", - "text": "InexactError()\n\nType conversion cannot be done exactly.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Core.InterruptException", - "page": "Essentials", - "title": "Core.InterruptException", - "category": "type", - "text": "InterruptException()\n\nThe process was stopped by a terminal interrupt (CTRL+C).\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.KeyError", - "page": "Essentials", - "title": "Base.KeyError", - "category": "type", - "text": "KeyError(key)\n\nAn indexing operation into an Associative (Dict) or Set like object tried to access or delete a non-existent element.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.LoadError", - "page": "Essentials", - "title": "Base.LoadError", - "category": "type", - "text": "LoadError(file::AbstractString, line::Int, error)\n\nAn error occurred while includeing, requireing, or using a file. The error specifics should be available in the .error field.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.MethodError", - "page": "Essentials", - "title": "Base.MethodError", - "category": "type", - "text": "MethodError(f, args)\n\nA method with the required type signature does not exist in the given generic function. Alternatively, there is no unique most-specific method.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.NullException", - "page": "Essentials", - "title": "Base.NullException", - "category": "type", - "text": "NullException()\n\nAn attempted access to a Nullable with no defined value.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Core.OutOfMemoryError", - "page": "Essentials", - "title": "Core.OutOfMemoryError", - "category": "type", - "text": "OutOfMemoryError()\n\nAn operation allocated too much memory for either the system or the garbage collector to handle properly.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Core.ReadOnlyMemoryError", - "page": "Essentials", - "title": "Core.ReadOnlyMemoryError", - "category": "type", - "text": "ReadOnlyMemoryError()\n\nAn operation tried to write to memory that is read-only.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Core.OverflowError", - "page": "Essentials", - "title": "Core.OverflowError", - "category": "type", - "text": "OverflowError()\n\nThe result of an expression is too large for the specified type and will cause a wraparound.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.ParseError", - "page": "Essentials", - "title": "Base.ParseError", - "category": "type", - "text": "ParseError(msg)\n\nThe expression passed to the parse function could not be interpreted as a valid Julia expression.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.Distributed.ProcessExitedException", - "page": "Essentials", - "title": "Base.Distributed.ProcessExitedException", - "category": "type", - "text": "ProcessExitedException()\n\nAfter a client Julia process has exited, further attempts to reference the dead child will throw this exception.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Core.StackOverflowError", - "page": "Essentials", - "title": "Core.StackOverflowError", - "category": "type", - "text": "StackOverflowError()\n\nThe function call grew beyond the size of the call stack. This usually happens when a call recurses infinitely.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.SystemError", - "page": "Essentials", - "title": "Base.SystemError", - "category": "type", - "text": "SystemError(prefix::AbstractString, [errno::Int32])\n\nA system call failed with an error code (in the errno global variable).\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Core.TypeError", - "page": "Essentials", - "title": "Core.TypeError", - "category": "type", - "text": "TypeError(func::Symbol, context::AbstractString, expected::Type, got)\n\nA type assertion failure, or calling an intrinsic function with an incorrect argument type.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Core.UndefRefError", - "page": "Essentials", - "title": "Core.UndefRefError", - "category": "type", - "text": "UndefRefError()\n\nThe item or field is not defined for the given object.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Core.UndefVarError", - "page": "Essentials", - "title": "Core.UndefVarError", - "category": "type", - "text": "UndefVarError(var::Symbol)\n\nA symbol in the current scope is not defined.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.InitError", - "page": "Essentials", - "title": "Base.InitError", - "category": "type", - "text": "InitError(mod::Symbol, error)\n\nAn error occurred when running a module\'s __init__ function. The actual error thrown is available in the .error field.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.retry", - "page": "Essentials", - "title": "Base.retry", - "category": "function", - "text": "retry(f::Function; delays=ExponentialBackOff(), check=nothing) -> Function\n\nReturns an anonymous function that calls function f. If an exception arises, f is repeatedly called again, each time check returns true, after waiting the number of seconds specified in delays. check should input delays\'s current state and the Exception.\n\nExamples\n\nretry(f, delays=fill(5.0, 3))\nretry(f, delays=rand(5:10, 2))\nretry(f, delays=Base.ExponentialBackOff(n=3, first_delay=5, max_delay=1000))\nretry(http_get, check=(s,e)->e.status == \"503\")(url)\nretry(read, check=(s,e)->isa(e, UVError))(io, 128; all=false)\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.ExponentialBackOff", - "page": "Essentials", - "title": "Base.ExponentialBackOff", - "category": "type", - "text": "ExponentialBackOff(; n=1, first_delay=0.05, max_delay=10.0, factor=5.0, jitter=0.1)\n\nA Float64 iterator of length n whose elements exponentially increase at a rate in the interval factor * (1 ± jitter). The first element is first_delay and all elements are clamped to max_delay.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Errors-1", - "page": "Essentials", - "title": "Errors", - "category": "section", - "text": "Base.error\nCore.throw\nBase.rethrow\nBase.backtrace\nBase.catch_backtrace\nBase.assert\nBase.@assert\nBase.ArgumentError\nBase.AssertionError\nCore.BoundsError\nBase.DimensionMismatch\nCore.DivideError\nCore.DomainError\nBase.EOFError\nCore.ErrorException\nCore.InexactError\nCore.InterruptException\nBase.KeyError\nBase.LoadError\nBase.MethodError\nBase.NullException\nCore.OutOfMemoryError\nCore.ReadOnlyMemoryError\nCore.OverflowError\nBase.ParseError\nBase.ProcessExitedException\nCore.StackOverflowError\nBase.SystemError\nCore.TypeError\nCore.UndefRefError\nCore.UndefVarError\nBase.InitError\nBase.retry\nBase.ExponentialBackOff" -}, - -{ - "location": "stdlib/base.html#Base.Timer-Tuple{Function,Real,Real}", - "page": "Essentials", - "title": "Base.Timer", - "category": "method", - "text": "Timer(callback::Function, delay, repeat=0)\n\nCreate a timer to call the given callback function. The callback is passed one argument, the timer object itself. The callback will be invoked after the specified initial delay, and then repeating with the given repeat interval. If repeat is 0, the timer is only triggered once. Times are in seconds. A timer is stopped and has its resources freed by calling close on it.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.Timer", - "page": "Essentials", - "title": "Base.Timer", - "category": "type", - "text": "Timer(delay, repeat=0)\n\nCreate a timer that wakes up tasks waiting for it (by calling wait on the timer object) at a specified interval. Times are in seconds. Waiting tasks are woken with an error when the timer is closed (by close. Use isopen to check whether a timer is still active.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.AsyncCondition", - "page": "Essentials", - "title": "Base.AsyncCondition", - "category": "type", - "text": "AsyncCondition()\n\nCreate a async condition that wakes up tasks waiting for it (by calling wait on the object) when notified from C by a call to uv_async_send. Waiting tasks are woken with an error when the object is closed (by close. Use isopen to check whether it is still active.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.AsyncCondition-Tuple{Function}", - "page": "Essentials", - "title": "Base.AsyncCondition", - "category": "method", - "text": "AsyncCondition(callback::Function)\n\nCreate a async condition that calls the given callback function. The callback is passed one argument, the async condition object itself.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Events-1", - "page": "Essentials", - "title": "Events", - "category": "section", - "text": "Base.Timer(::Function, ::Real, ::Real)\nBase.Timer\nBase.AsyncCondition\nBase.AsyncCondition(::Function)" -}, - -{ - "location": "stdlib/base.html#Base.module_name", - "page": "Essentials", - "title": "Base.module_name", - "category": "function", - "text": "module_name(m::Module) -> Symbol\n\nGet the name of a Module as a Symbol.\n\njulia> module_name(Base.LinAlg)\n:LinAlg\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.module_parent", - "page": "Essentials", - "title": "Base.module_parent", - "category": "function", - "text": "module_parent(m::Module) -> Module\n\nGet a module\'s enclosing Module. Main is its own parent, as is LastMain after workspace().\n\njulia> module_parent(Main)\nMain\n\njulia> module_parent(Base.LinAlg.BLAS)\nBase.LinAlg\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.current_module", - "page": "Essentials", - "title": "Base.current_module", - "category": "function", - "text": "current_module() -> Module\n\nGet the dynamically current Module, which is the Module code is currently being read from. In general, this is not the same as the module containing the call to this function.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.fullname", - "page": "Essentials", - "title": "Base.fullname", - "category": "function", - "text": "fullname(m::Module)\n\nGet the fully-qualified name of a module as a tuple of symbols. For example,\n\njulia> fullname(Base.Pkg)\n(:Base, :Pkg)\n\njulia> fullname(Main)\n()\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.names", - "page": "Essentials", - "title": "Base.names", - "category": "function", - "text": "names(x::Module, all::Bool=false, imported::Bool=false)\n\nGet an array of the names exported by a Module, excluding deprecated names. If all is true, then the list also includes non-exported names defined in the module, deprecated names, and compiler-generated names. If imported is true, then names explicitly imported from other modules are also included.\n\nAs a special case, all names defined in Main are considered \"exported\", since it is not idiomatic to explicitly export names from Main.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Core.nfields", - "page": "Essentials", - "title": "Core.nfields", - "category": "function", - "text": "nfields(x::DataType) -> Int\n\nGet the number of fields of a DataType.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.fieldnames", - "page": "Essentials", - "title": "Base.fieldnames", - "category": "function", - "text": "fieldnames(x::DataType)\n\nGet an array of the fields of a DataType.\n\njulia> fieldnames(Hermitian)\n2-element Array{Symbol,1}:\n :data\n :uplo\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.fieldname", - "page": "Essentials", - "title": "Base.fieldname", - "category": "function", - "text": "fieldname(x::DataType, i::Integer)\n\nGet the name of field i of a DataType.\n\njulia> fieldname(SparseMatrixCSC,1)\n:m\n\njulia> fieldname(SparseMatrixCSC,5)\n:nzval\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.datatype_module", - "page": "Essentials", - "title": "Base.datatype_module", - "category": "function", - "text": "Base.datatype_module(t::DataType) -> Module\n\nDetermine the module containing the definition of a DataType.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.datatype_name", - "page": "Essentials", - "title": "Base.datatype_name", - "category": "function", - "text": "Base.datatype_name(t) -> Symbol\n\nGet the name of a (potentially UnionAll-wrapped) DataType (without its parent module) as a symbol.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.isconst", - "page": "Essentials", - "title": "Base.isconst", - "category": "function", - "text": "isconst([m::Module], s::Symbol) -> Bool\n\nDetermine whether a global is declared const in a given Module. The default Module argument is current_module().\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.function_name", - "page": "Essentials", - "title": "Base.function_name", - "category": "function", - "text": "Base.function_name(f::Function) -> Symbol\n\nGet the name of a generic Function as a symbol, or :anonymous.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.function_module-Tuple{Function}", - "page": "Essentials", - "title": "Base.function_module", - "category": "method", - "text": "Base.function_module(f::Function) -> Module\n\nDetermine the module containing the (first) definition of a generic function.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.function_module-Tuple{Any,Any}", - "page": "Essentials", - "title": "Base.function_module", - "category": "method", - "text": "Base.function_module(f::Function, types) -> Module\n\nDetermine the module containing a given definition of a generic function.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.functionloc-Tuple{Any,Any}", - "page": "Essentials", - "title": "Base.functionloc", - "category": "method", - "text": "functionloc(f::Function, types)\n\nReturns a tuple (filename,line) giving the location of a generic Function definition.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.functionloc-Tuple{Method}", - "page": "Essentials", - "title": "Base.functionloc", - "category": "method", - "text": "functionloc(m::Method)\n\nReturns a tuple (filename,line) giving the location of a Method definition.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.@functionloc", - "page": "Essentials", - "title": "Base.@functionloc", - "category": "macro", - "text": "@functionloc\n\nApplied to a function or macro call, it evaluates the arguments to the specified call, and returns a tuple (filename,line) giving the location for the method that would be called for those arguments. It calls out to the functionloc function.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Reflection-1", - "page": "Essentials", - "title": "Reflection", - "category": "section", - "text": "Base.module_name\nBase.module_parent\nBase.current_module\nBase.fullname\nBase.names\nCore.nfields\nBase.fieldnames\nBase.fieldname\nBase.datatype_module\nBase.datatype_name\nBase.isconst\nBase.function_name\nBase.function_module(::Function)\nBase.function_module(::Any, ::Any)\nBase.functionloc(::Any, ::Any)\nBase.functionloc(::Method)\nBase.@functionloc" -}, - -{ - "location": "stdlib/base.html#Base.gc", - "page": "Essentials", - "title": "Base.gc", - "category": "function", - "text": "gc()\n\nPerform garbage collection. This should not generally be used.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.gc_enable", - "page": "Essentials", - "title": "Base.gc_enable", - "category": "function", - "text": "gc_enable(on::Bool)\n\nControl whether garbage collection is enabled using a boolean argument (true for enabled, false for disabled). Returns previous GC state. Disabling garbage collection should be used only with extreme caution, as it can cause memory use to grow without bound.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.macroexpand", - "page": "Essentials", - "title": "Base.macroexpand", - "category": "function", - "text": "macroexpand(x)\n\nTakes the expression x and returns an equivalent expression with all macros removed (expanded).\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.@macroexpand", - "page": "Essentials", - "title": "Base.@macroexpand", - "category": "macro", - "text": "@macroexpand\n\nReturn equivalent expression with all macros removed (expanded).\n\nThere is a subtle difference between @macroexpand and macroexpand in that expansion takes place in different contexts. This is best seen in the following example:\n\njulia> module M\n macro m()\n 1\n end\n function f()\n (@macroexpand(@m), macroexpand(:(@m)))\n end\n end\nM\n\njulia> macro m()\n 2\n end\n@m (macro with 1 method)\n\njulia> M.f()\n(1, 2)\n\nWith @macroexpand the expression expands where @macroexpand appears in the code (module M in the example). With macroexpand the expression expands in the current module where the code was finally called (REPL in the example). Note that when calling macroexpand or @macroexpand directly from the REPL, both of these contexts coincide, hence there is no difference.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.expand", - "page": "Essentials", - "title": "Base.expand", - "category": "function", - "text": "expand(x)\n\nTakes the expression x and returns an equivalent expression in lowered form. See also code_lowered.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.code_lowered", - "page": "Essentials", - "title": "Base.code_lowered", - "category": "function", - "text": "code_lowered(f, types)\n\nReturns an array of lowered ASTs for the methods matching the given generic function and type signature.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.@code_lowered", - "page": "Essentials", - "title": "Base.@code_lowered", - "category": "macro", - "text": "@code_lowered\n\nEvaluates the arguments to the function or macro call, determines their types, and calls code_lowered on the resulting expression.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.code_typed", - "page": "Essentials", - "title": "Base.code_typed", - "category": "function", - "text": "code_typed(f, types; optimize=true)\n\nReturns an array of lowered and type-inferred ASTs for the methods matching the given generic function and type signature. The keyword argument optimize controls whether additional optimizations, such as inlining, are also applied.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.@code_typed", - "page": "Essentials", - "title": "Base.@code_typed", - "category": "macro", - "text": "@code_typed\n\nEvaluates the arguments to the function or macro call, determines their types, and calls code_typed on the resulting expression.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.code_warntype", - "page": "Essentials", - "title": "Base.code_warntype", - "category": "function", - "text": "code_warntype([io::IO], f, types)\n\nPrints lowered and type-inferred ASTs for the methods matching the given generic function and type signature to io which defaults to STDOUT. The ASTs are annotated in such a way as to cause \"non-leaf\" types to be emphasized (if color is available, displayed in red). This serves as a warning of potential type instability. Not all non-leaf types are particularly problematic for performance, so the results need to be used judiciously. See @code_warntype for more information.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.@code_warntype", - "page": "Essentials", - "title": "Base.@code_warntype", - "category": "macro", - "text": "@code_warntype\n\nEvaluates the arguments to the function or macro call, determines their types, and calls code_warntype on the resulting expression.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.code_llvm", - "page": "Essentials", - "title": "Base.code_llvm", - "category": "function", - "text": "code_llvm([io], f, types)\n\nPrints the LLVM bitcodes generated for running the method matching the given generic function and type signature to io which defaults to STDOUT.\n\nAll metadata and dbg.* calls are removed from the printed bitcode. Use code_llvm_raw for the full IR.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.@code_llvm", - "page": "Essentials", - "title": "Base.@code_llvm", - "category": "macro", - "text": "@code_llvm\n\nEvaluates the arguments to the function or macro call, determines their types, and calls code_llvm on the resulting expression.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.code_native", - "page": "Essentials", - "title": "Base.code_native", - "category": "function", - "text": "code_native([io], f, types, [syntax])\n\nPrints the native assembly instructions generated for running the method matching the given generic function and type signature to io which defaults to STDOUT. Switch assembly syntax using syntax symbol parameter set to :att for AT&T syntax or :intel for Intel syntax. Output is AT&T syntax by default.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.@code_native", - "page": "Essentials", - "title": "Base.@code_native", - "category": "macro", - "text": "@code_native\n\nEvaluates the arguments to the function or macro call, determines their types, and calls code_native on the resulting expression.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Base.precompile", - "page": "Essentials", - "title": "Base.precompile", - "category": "function", - "text": "precompile(f,args::Tuple{Vararg{Any}})\n\nCompile the given function f for the argument tuple (of types) args, but do not execute it.\n\n\n\n" -}, - -{ - "location": "stdlib/base.html#Internals-1", - "page": "Essentials", - "title": "Internals", - "category": "section", - "text": "Base.gc\nBase.gc_enable\nBase.macroexpand\nBase.@macroexpand\nBase.expand\nBase.code_lowered\nBase.@code_lowered\nBase.code_typed\nBase.@code_typed\nBase.code_warntype\nBase.@code_warntype\nBase.code_llvm\nBase.@code_llvm\nBase.code_native\nBase.@code_native\nBase.precompile" -}, - -{ - "location": "stdlib/collections.html#", - "page": "Collections and Data Structures", - "title": "Collections and Data Structures", - "category": "page", - "text": "" -}, - -{ - "location": "stdlib/collections.html#Collections-and-Data-Structures-1", - "page": "Collections and Data Structures", - "title": "Collections and Data Structures", - "category": "section", - "text": "" -}, - -{ - "location": "stdlib/collections.html#Base.start", - "page": "Collections and Data Structures", - "title": "Base.start", - "category": "function", - "text": "start(iter) -> state\n\nGet initial iteration state for an iterable object.\n\nExamples\n\njulia> start(1:5)\n1\n\njulia> start([1;2;3])\n1\n\njulia> start([4;2;3])\n1\n\n\n\n" -}, - -{ - "location": "stdlib/collections.html#Base.done", - "page": "Collections and Data Structures", - "title": "Base.done", - "category": "function", - "text": "done(iter, state) -> Bool\n\nTest whether we are done iterating.\n\nExamples\n\njulia> done(1:5, 3)\nfalse\n\njulia> done(1:5, 5)\nfalse\n\njulia> done(1:5, 6)\ntrue\n\n\n\n" -}, - -{ - "location": "stdlib/collections.html#Base.next", - "page": "Collections and Data Structures", - "title": "Base.next", - "category": "function", - "text": "next(iter, state) -> item, state\n\nFor a given iterable object and iteration state, return the current item and the next iteration state.\n\nExamples\n\njulia> next(1:5, 3)\n(3, 4)\n\njulia> next(1:5, 5)\n(5, 6)\n\n\n\n" -}, - -{ - "location": "stdlib/collections.html#Base.iteratorsize", - "page": "Collections and Data Structures", - "title": "Base.iteratorsize", - "category": "function", - "text": "iteratorsize(itertype::Type) -> IteratorSize\n\nGiven the type of an iterator, returns one of the following values:\n\nSizeUnknown() if the length (number of elements) cannot be determined in advance.\nHasLength() if there is a fixed, finite length.\nHasShape() if there is a known length plus a notion of multidimensional shape (as for an array). In this case the size function is valid for the iterator.\nIsInfinite() if the iterator yields values forever.\n\nThe default value (for iterators that do not define this function) is HasLength(). This means that most iterators are assumed to implement length.\n\nThis trait is generally used to select between algorithms that pre-allocate space for their result, and algorithms that resize their result incrementally.\n\njulia> Base.iteratorsize(1:5)\nBase.HasShape()\n\njulia> Base.iteratorsize((2,3))\nBase.HasLength()\n\n\n\n" -}, - -{ - "location": "stdlib/collections.html#Base.iteratoreltype", - "page": "Collections and Data Structures", - "title": "Base.iteratoreltype", - "category": "function", - "text": "iteratoreltype(itertype::Type) -> IteratorEltype\n\nGiven the type of an iterator, returns one of the following values:\n\nEltypeUnknown() if the type of elements yielded by the iterator is not known in advance.\nHasEltype() if the element type is known, and eltype would return a meaningful value.\n\nHasEltype() is the default, since iterators are assumed to implement eltype.\n\nThis trait is generally used to select between algorithms that pre-allocate a specific type of result, and algorithms that pick a result type based on the types of yielded values.\n\njulia> Base.iteratoreltype(1:5)\nBase.HasEltype()\n\n\n\n" -}, - -{ - "location": "stdlib/collections.html#lib-collections-iteration-1", - "page": "Collections and Data Structures", - "title": "Iteration", - "category": "section", - "text": "Sequential iteration is implemented by the methods start(), done(), and next(). The general for loop:for i = I # or \"for i in I\"\n # body\nendis translated into:state = start(I)\nwhile !done(I, state)\n (i, state) = next(I, state)\n # body\nendThe state object may be anything, and should be chosen appropriately for each iterable type. See the manual section on the iteration interface for more details about defining a custom iterable type.Base.start\nBase.done\nBase.next\nBase.iteratorsize\nBase.iteratoreltypeFully implemented by:Range\nUnitRange\nTuple\nNumber\nAbstractArray\nIntSet\nObjectIdDict\nDict\nWeakKeyDict\nEachLine\nAbstractString\nSet" -}, - -{ - "location": "stdlib/collections.html#Base.isempty", - "page": "Collections and Data Structures", - "title": "Base.isempty", - "category": "function", - "text": "isempty(collection) -> Bool\n\nDetermine whether a collection is empty (has no elements).\n\nExamples\n\njulia> isempty([])\ntrue\n\njulia> isempty([1 2 3])\nfalse\n\n\n\n" -}, - -{ - "location": "stdlib/collections.html#Base.empty!", - "page": "Collections and Data Structures", - "title": "Base.empty!", - "category": "function", - "text": "empty!(collection) -> collection\n\nRemove all elements from a collection.\n\njulia> A = Dict(\"a\" => 1, \"b\" => 2)\nDict{String,Int64} with 2 entries:\n \"b\" => 2\n \"a\" => 1\n\njulia> empty!(A);\n\njulia> A\nDict{String,Int64} with 0 entries\n\n\n\n" -}, - -{ - "location": "stdlib/collections.html#Base.length-Tuple{Any}", - "page": "Collections and Data Structures", - "title": "Base.length", - "category": "method", - "text": "length(collection) -> Integer\n\nFor ordered, indexable collections, returns the maximum index i for which getindex(collection, i) is valid. For unordered collections, returns the number of elements.\n\nExamples\n\njulia> length(1:5)\n5\n\njulia> length([1; 2; 3; 4])\n4\n\n\n\n" -}, - -{ - "location": "stdlib/collections.html#Base.endof", - "page": "Collections and Data Structures", - "title": "Base.endof", - "category": "function", - "text": "endof(collection) -> Integer\n\nReturns the last index of the collection.\n\nExample\n\njulia> endof([1,2,4])\n3\n\n\n\n" -}, - -{ - "location": "stdlib/collections.html#General-Collections-1", - "page": "Collections and Data Structures", - "title": "General Collections", - "category": "section", - "text": "Base.isempty\nBase.empty!\nBase.length(::Any)\nBase.endofFully implemented by:Range\nUnitRange\nTuple\nNumber\nAbstractArray\nIntSet\nObjectIdDict\nDict\nWeakKeyDict\nAbstractString\nSet" -}, - -{ - "location": "stdlib/collections.html#Base.in", - "page": "Collections and Data Structures", - "title": "Base.in", - "category": "function", - "text": "in(item, collection) -> Bool\n∈(item,collection) -> Bool\n∋(collection,item) -> Bool\n∉(item,collection) -> Bool\n∌(collection,item) -> Bool\n\nDetermine whether an item is in the given collection, in the sense that it is == to one of the values generated by iterating over the collection. Some collections need a slightly different definition; for example Sets check whether the item isequal to one of the elements. Dicts look for (key,value) pairs, and the key is compared using isequal. To test for the presence of a key in a dictionary, use haskey or k in keys(dict).\n\njulia> a = 1:3:20\n1:3:19\n\njulia> 4 in a\ntrue\n\njulia> 5 in a\nfalse\n\n\n\n" -}, - -{ - "location": "stdlib/collections.html#Base.eltype", - "page": "Collections and Data Structures", - "title": "Base.eltype", - "category": "function", - "text": "eltype(type)\n\nDetermine the type of the elements generated by iterating a collection of the given type. For associative collection types, this will be a Pair{KeyType,ValType}. The definition eltype(x) = eltype(typeof(x)) is provided for convenience so that instances can be passed instead of types. However the form that accepts a type argument should be defined for new types.\n\njulia> eltype(ones(Float32,2,2))\nFloat32\n\njulia> eltype(ones(Int8,2,2))\nInt8\n\n\n\n" -}, - -{ - "location": "stdlib/collections.html#Base.indexin", - "page": "Collections and Data Structures", - "title": "Base.indexin", - "category": "function", - "text": "indexin(a, b)\n\nReturns a vector containing the highest index in b for each value in a that is a member of b . The output vector contains 0 wherever a is not a member of b.\n\nExamples\n\njulia> a = [\'a\', \'b\', \'c\', \'b\', \'d\', \'a\'];\n\njulia> b = [\'a\',\'b\',\'c\'];\n\njulia> indexin(a,b)\n6-element Array{Int64,1}:\n 1\n 2\n 3\n 2\n 0\n 1\n\njulia> indexin(b,a)\n3-element Array{Int64,1}:\n 6\n 4\n 3\n\n\n\n" -}, - -{ - "location": "stdlib/collections.html#Base.findin", - "page": "Collections and Data Structures", - "title": "Base.findin", - "category": "function", - "text": "findin(a, b)\n\nReturns the indices of elements in collection a that appear in collection b.\n\nExamples\n\njulia> a = collect(1:3:15)\n5-element Array{Int64,1}:\n 1\n 4\n 7\n 10\n 13\n\njulia> b = collect(2:4:10)\n3-element Array{Int64,1}:\n 2\n 6\n 10\n\njulia> findin(a,b) # 10 is the only common element\n1-element Array{Int64,1}:\n 4\n\n\n\n" -}, - -{ - "location": "stdlib/collections.html#Base.unique", - "page": "Collections and Data Structures", - "title": "Base.unique", - "category": "function", - "text": "unique(itr)\n\nReturns an array containing one value from itr for each unique value, as determined by isequal.\n\njulia> unique([1; 2; 2; 6])\n3-element Array{Int64,1}:\n 1\n 2\n 6\n\n\n\nunique(f, itr)\n\nReturns an array containing one value from itr for each unique value produced by f applied to elements of itr.\n\njulia> unique(isodd, [1; 2; 2; 6])\n2-element Array{Int64,1}:\n 1\n 2\n\n\n\nunique(itr[, dim])\n\nReturns an array containing only the unique elements of the iterable itr, in the order that the first of each set of equivalent elements originally appears. If dim is specified, returns unique regions of the array itr along dim.\n\njulia> A = map(isodd, reshape(collect(1:8), (2,2,2)))\n2×2×2 Array{Bool,3}:\n[:, :, 1] =\n true true\n false false\n\n[:, :, 2] =\n true true\n false false\n\njulia> unique(A)\n2-element Array{Bool,1}:\n true\n false\n\njulia> unique(A, 2)\n2×1×2 Array{Bool,3}:\n[:, :, 1] =\n true\n false\n\n[:, :, 2] =\n true\n false\n\njulia> unique(A, 3)\n2×2×1 Array{Bool,3}:\n[:, :, 1] =\n true true\n false false\n\n\n\n" -}, - -{ - "location": "stdlib/collections.html#Base.allunique", - "page": "Collections and Data Structures", - "title": "Base.allunique", - "category": "function", - "text": "allunique(itr) -> Bool\n\nReturn true if all values from itr are distinct when compared with isequal.\n\njulia> a = [1; 2; 3]\n3-element Array{Int64,1}:\n 1\n 2\n 3\n\njulia> allunique([a, a])\nfalse\n\n\n\n" -}, - -{ - "location": "stdlib/collections.html#Base.reduce-Tuple{Any,Any,Any}", - "page": "Collections and Data Structures", - "title": "Base.reduce", - "category": "method", - "text": "reduce(op, v0, itr)\n\nReduce the given collection ìtr with the given binary operator op. v0 must be a neutral element for op that will be returned for empty collections. It is unspecified whether v0 is used for non-empty collections.\n\nReductions for certain commonly-used operators have special implementations which should be used instead: maximum(itr), minimum(itr), sum(itr), prod(itr), any(itr), all(itr).\n\nThe associativity of the reduction is implementation dependent. This means that you can\'t use non-associative operations like - because it is undefined whether reduce(-,[1,2,3]) should be evaluated as (1-2)-3 or 1-(2-3). Use foldl or foldr instead for guaranteed left or right associativity.\n\nSome operations accumulate error, and parallelism will also be easier if the reduction can be executed in groups. Future versions of Julia might change the algorithm. Note that the elements are not reordered if you use an ordered collection.\n\nExamples\n\njulia> reduce(*, 1, [2; 3; 4])\n24\n\n\n\n" -}, - -{ - "location": "stdlib/collections.html#Base.reduce-Tuple{Any,Any}", - "page": "Collections and Data Structures", - "title": "Base.reduce", - "category": "method", - "text": "reduce(op, itr)\n\nLike reduce(op, v0, itr). This cannot be used with empty collections, except for some special cases (e.g. when op is one of +, *, max, min, &, |) when Julia can determine the neutral element of op.\n\njulia> reduce(*, [2; 3; 4])\n24\n\n\n\n" -}, - -{ - "location": "stdlib/collections.html#Base.foldl-Tuple{Any,Any,Any}", - "page": "Collections and Data Structures", - "title": "Base.foldl", - "category": "method", - "text": "foldl(op, v0, itr)\n\nLike reduce, but with guaranteed left associativity. v0 will be used exactly once.\n\njulia> foldl(-, 1, 2:5)\n-13\n\n\n\n" -}, - -{ - "location": "stdlib/collections.html#Base.foldl-Tuple{Any,Any}", - "page": "Collections and Data Structures", - "title": "Base.foldl", - "category": "method", - "text": "foldl(op, itr)\n\nLike foldl(op, v0, itr), but using the first element of itr as v0. In general, this cannot be used with empty collections (see reduce(op, itr)).\n\njulia> foldl(-, 2:5)\n-10\n\n\n\n" -}, - -{ - "location": "stdlib/collections.html#Base.foldr-Tuple{Any,Any,Any}", - "page": "Collections and Data Structures", - "title": "Base.foldr", - "category": "method", - "text": "foldr(op, v0, itr)\n\nLike reduce, but with guaranteed right associativity. v0 will be used exactly once.\n\njulia> foldr(-, 1, 2:5)\n-1\n\n\n\n" -}, - -{ - "location": "stdlib/collections.html#Base.foldr-Tuple{Any,Any}", - "page": "Collections and Data Structures", - "title": "Base.foldr", - "category": "method", - "text": "foldr(op, itr)\n\nLike foldr(op, v0, itr), but using the last element of itr as v0. In general, this cannot be used with empty collections (see reduce(op, itr)).\n\njulia> foldr(-, 2:5)\n-2\n\n\n\n" -}, - -{ - "location": "stdlib/collections.html#Base.maximum-Tuple{Any}", - "page": "Collections and Data Structures", - "title": "Base.maximum", - "category": "method", - "text": "maximum(itr)\n\nReturns the largest element in a collection.\n\njulia> maximum(-20.5:10)\n9.5\n\njulia> maximum([1,2,3])\n3\n\n\n\n" -}, - -{ - "location": "stdlib/collections.html#Base.maximum-Tuple{Any,Any}", - "page": "Collections and Data Structures", - "title": "Base.maximum", - "category": "method", - "text": "maximum(A, dims)\n\nCompute the maximum value of an array over the given dimensions. See also the max(a,b) function to take the maximum of two or more arguments, which can be applied elementwise to arrays via max.(a,b).\n\njulia> A = [1 2; 3 4]\n2×2 Array{Int64,2}:\n 1 2\n 3 4\n\njulia> maximum(A, 1)\n1×2 Array{Int64,2}:\n 3 4\n\njulia> maximum(A, 2)\n2×1 Array{Int64,2}:\n 2\n 4\n\n\n\n" -}, - -{ - "location": "stdlib/collections.html#Base.maximum!", - "page": "Collections and Data Structures", - "title": "Base.maximum!", - "category": "function", - "text": "maximum!(r, A)\n\nCompute the maximum value of A over the singleton dimensions of r, and write results to r.\n\nExamples\n\njulia> A = [1 2; 3 4]\n2×2 Array{Int64,2}:\n 1 2\n 3 4\n\njulia> maximum!([1; 1], A)\n2-element Array{Int64,1}:\n 2\n 4\n\njulia> maximum!([1 1], A)\n1×2 Array{Int64,2}:\n 3 4\n\n\n\n" -}, - -{ - "location": "stdlib/collections.html#Base.minimum-Tuple{Any}", - "page": "Collections and Data Structures", - "title": "Base.minimum", - "category": "method", - "text": "minimum(itr)\n\nReturns the smallest element in a collection.\n\njulia> minimum(-20.5:10)\n-20.5\n\njulia> minimum([1,2,3])\n1\n\n\n\n" -}, - -{ - "location": "stdlib/collections.html#Base.minimum-Tuple{Any,Any}", - "page": "Collections and Data Structures", - "title": "Base.minimum", - "category": "method", - "text": "minimum(A, dims)\n\nCompute the minimum value of an array over the given dimensions. See also the min(a,b) function to take the minimum of two or more arguments, which can be applied elementwise to arrays via min.(a,b).\n\nExamples\n\njulia> A = [1 2; 3 4]\n2×2 Array{Int64,2}:\n 1 2\n 3 4\n\njulia> minimum(A, 1)\n1×2 Array{Int64,2}:\n 1 2\n\njulia> minimum(A, 2)\n2×1 Array{Int64,2}:\n 1\n 3\n\n\n\n" -}, - -{ - "location": "stdlib/collections.html#Base.minimum!", - "page": "Collections and Data Structures", - "title": "Base.minimum!", - "category": "function", - "text": "minimum!(r, A)\n\nCompute the minimum value of A over the singleton dimensions of r, and write results to r.\n\nExamples\n\njulia> A = [1 2; 3 4]\n2×2 Array{Int64,2}:\n 1 2\n 3 4\n\njulia> minimum!([1; 1], A)\n2-element Array{Int64,1}:\n 1\n 3\n\njulia> minimum!([1 1], A)\n1×2 Array{Int64,2}:\n 1 2\n\n\n\n" -}, - -{ - "location": "stdlib/collections.html#Base.extrema-Tuple{Any}", - "page": "Collections and Data Structures", - "title": "Base.extrema", - "category": "method", - "text": "extrema(itr) -> Tuple\n\nCompute both the minimum and maximum element in a single pass, and return them as a 2-tuple.\n\njulia> extrema(2:10)\n(2, 10)\n\njulia> extrema([9,pi,4.5])\n(3.141592653589793, 9.0)\n\n\n\n" -}, - -{ - "location": "stdlib/collections.html#Base.extrema-Tuple{AbstractArray,Any}", - "page": "Collections and Data Structures", - "title": "Base.extrema", - "category": "method", - "text": "extrema(A, dims) -> Array{Tuple}\n\nCompute the minimum and maximum elements of an array over the given dimensions.\n\nExample\n\njulia> A = reshape(collect(1:2:16), (2,2,2))\n2×2×2 Array{Int64,3}:\n[:, :, 1] =\n 1 5\n 3 7\n\n[:, :, 2] =\n 9 13\n 11 15\n\njulia> extrema(A, (1,2))\n1×1×2 Array{Tuple{Int64,Int64},3}:\n[:, :, 1] =\n (1, 7)\n\n[:, :, 2] =\n (9, 15)\n\n\n\n" -}, - -{ - "location": "stdlib/collections.html#Base.indmax", - "page": "Collections and Data Structures", - "title": "Base.indmax", - "category": "function", - "text": "indmax(itr) -> Integer\n\nReturns the index of the maximum element in a collection. If there are multiple maximal elements, then the first one will be returned. NaN values are ignored, unless all elements are NaN.\n\nThe collection must not be empty.\n\nExamples\n\njulia> indmax([8,0.1,-9,pi])\n1\n\njulia> indmax([1,7,7,6])\n2\n\njulia> indmax([1,7,7,NaN])\n2\n\n\n\n" -}, - -{ - "location": "stdlib/collections.html#Base.indmin", - "page": "Collections and Data Structures", - "title": "Base.indmin", - "category": "function", - "text": "indmin(itr) -> Integer\n\nReturns the index of the minimum element in a collection. If there are multiple minimal elements, then the first one will be returned. NaN values are ignored, unless all elements are NaN.\n\nThe collection must not be empty.\n\nExamples\n\njulia> indmin([8,0.1,-9,pi])\n3\n\njulia> indmin([7,1,1,6])\n2\n\njulia> indmin([7,1,1,NaN])\n2\n\n\n\n" -}, - -{ - "location": "stdlib/collections.html#Base.findmax-Tuple{Any}", - "page": "Collections and Data Structures", - "title": "Base.findmax", - "category": "method", - "text": "findmax(itr) -> (x, index)\n\nReturns the maximum element of the collection itr and its index. If there are multiple maximal elements, then the first one will be returned. NaN values are ignored, unless all elements are NaN.\n\nThe collection must not be empty.\n\nExamples\n\njulia> findmax([8,0.1,-9,pi])\n(8.0, 1)\n\njulia> findmax([1,7,7,6])\n(7, 2)\n\njulia> findmax([1,7,7,NaN])\n(7.0, 2)\n\n\n\n" -}, - -{ - "location": "stdlib/collections.html#Base.findmax-Tuple{AbstractArray,Any}", - "page": "Collections and Data Structures", - "title": "Base.findmax", - "category": "method", - "text": "findmax(A, region) -> (maxval, index)\n\nFor an array input, returns the value and index of the maximum over the given region.\n\nExamples\n\njulia> A = [1 2; 3 4]\n2×2 Array{Int64,2}:\n 1 2\n 3 4\n\njulia> findmax(A,1)\n([3 4], [2 4])\n\njulia> findmax(A,2)\n([2; 4], [3; 4])\n\n\n\n" -}, - -{ - "location": "stdlib/collections.html#Base.findmin-Tuple{Any}", - "page": "Collections and Data Structures", - "title": "Base.findmin", - "category": "method", - "text": "findmin(itr) -> (x, index)\n\nReturns the minimum element of the collection itr and its index. If there are multiple minimal elements, then the first one will be returned. NaN values are ignored, unless all elements are NaN.\n\nThe collection must not be empty.\n\nExamples\n\njulia> findmin([8,0.1,-9,pi])\n(-9.0, 3)\n\njulia> findmin([7,1,1,6])\n(1, 2)\n\njulia> findmin([7,1,1,NaN])\n(1.0, 2)\n\n\n\n" -}, - -{ - "location": "stdlib/collections.html#Base.findmin-Tuple{AbstractArray,Any}", - "page": "Collections and Data Structures", - "title": "Base.findmin", - "category": "method", - "text": "findmin(A, region) -> (minval, index)\n\nFor an array input, returns the value and index of the minimum over the given region.\n\nExamples\n\njulia> A = [1 2; 3 4]\n2×2 Array{Int64,2}:\n 1 2\n 3 4\n\njulia> findmin(A, 1)\n([1 2], [1 3])\n\njulia> findmin(A, 2)\n([1; 3], [1; 2])\n\n\n\n" -}, - -{ - "location": "stdlib/collections.html#Base.findmax!", - "page": "Collections and Data Structures", - "title": "Base.findmax!", - "category": "function", - "text": "findmax!(rval, rind, A, [init=true]) -> (maxval, index)\n\nFind the maximum of A and the corresponding linear index along singleton dimensions of rval and rind, and store the results in rval and rind.\n\n\n\n" -}, - -{ - "location": "stdlib/collections.html#Base.findmin!", - "page": "Collections and Data Structures", - "title": "Base.findmin!", - "category": "function", - "text": "findmin!(rval, rind, A, [init=true]) -> (minval, index)\n\nFind the minimum of A and the corresponding linear index along singleton dimensions of rval and rind, and store the results in rval and rind.\n\n\n\n" -}, - -{ - "location": "stdlib/collections.html#Base.sum", - "page": "Collections and Data Structures", - "title": "Base.sum", - "category": "function", - "text": "sum(f, itr)\n\nSum the results of calling function f on each element of itr.\n\njulia> sum(abs2, [2; 3; 4])\n29\n\n\n\nsum(itr)\n\nReturns the sum of all elements in a collection.\n\njulia> sum(1:20)\n210\n\n\n\nsum(A, dims)\n\nSum elements of an array over the given dimensions.\n\nExamples\n\njulia> A = [1 2; 3 4]\n2×2 Array{Int64,2}:\n 1 2\n 3 4\n\njulia> sum(A, 1)\n1×2 Array{Int64,2}:\n 4 6\n\njulia> sum(A, 2)\n2×1 Array{Int64,2}:\n 3\n 7\n\n\n\n" -}, - -{ - "location": "stdlib/collections.html#Base.sum!", - "page": "Collections and Data Structures", - "title": "Base.sum!", - "category": "function", - "text": "sum!(r, A)\n\nSum elements of A over the singleton dimensions of r, and write results to r.\n\nExamples\n\njulia> A = [1 2; 3 4]\n2×2 Array{Int64,2}:\n 1 2\n 3 4\n\njulia> sum!([1; 1], A)\n2-element Array{Int64,1}:\n 3\n 7\n\njulia> sum!([1 1], A)\n1×2 Array{Int64,2}:\n 4 6\n\n\n\n" -}, - -{ - "location": "stdlib/collections.html#Base.prod", - "page": "Collections and Data Structures", - "title": "Base.prod", - "category": "function", - "text": "prod(f, itr)\n\nReturns the product of f applied to each element of itr.\n\njulia> prod(abs2, [2; 3; 4])\n576\n\n\n\nprod(itr)\n\nReturns the product of all elements of a collection.\n\njulia> prod(1:20)\n2432902008176640000\n\n\n\nprod(A, dims)\n\nMultiply elements of an array over the given dimensions.\n\nExamples\n\njulia> A = [1 2; 3 4]\n2×2 Array{Int64,2}:\n 1 2\n 3 4\n\njulia> prod(A, 1)\n1×2 Array{Int64,2}:\n 3 8\n\njulia> prod(A, 2)\n2×1 Array{Int64,2}:\n 2\n 12\n\n\n\n" -}, - -{ - "location": "stdlib/collections.html#Base.prod!", - "page": "Collections and Data Structures", - "title": "Base.prod!", - "category": "function", - "text": "prod!(r, A)\n\nMultiply elements of A over the singleton dimensions of r, and write results to r.\n\nExamples\n\njulia> A = [1 2; 3 4]\n2×2 Array{Int64,2}:\n 1 2\n 3 4\n\njulia> prod!([1; 1], A)\n2-element Array{Int64,1}:\n 2\n 12\n\njulia> prod!([1 1], A)\n1×2 Array{Int64,2}:\n 3 8\n\n\n\n" -}, - -{ - "location": "stdlib/collections.html#Base.any-Tuple{Any}", - "page": "Collections and Data Structures", - "title": "Base.any", - "category": "method", - "text": "any(itr) -> Bool\n\nTest whether any elements of a boolean collection are true, returning true as soon as the first true value in itr is encountered (short-circuiting).\n\njulia> a = [true,false,false,true]\n4-element Array{Bool,1}:\n true\n false\n false\n true\n\njulia> any(a)\ntrue\n\njulia> any((println(i); v) for (i, v) in enumerate(a))\n1\ntrue\n\n\n\n" -}, - -{ - "location": "stdlib/collections.html#Base.any-Tuple{AbstractArray,Any}", - "page": "Collections and Data Structures", - "title": "Base.any", - "category": "method", - "text": "any(A, dims)\n\nTest whether any values along the given dimensions of an array are true.\n\nExamples\n\njulia> A = [true false; true false]\n2×2 Array{Bool,2}:\n true false\n true false\n\njulia> any(A, 1)\n1×2 Array{Bool,2}:\n true false\n\njulia> any(A, 2)\n2×1 Array{Bool,2}:\n true\n true\n\n\n\n" -}, - -{ - "location": "stdlib/collections.html#Base.any!", - "page": "Collections and Data Structures", - "title": "Base.any!", - "category": "function", - "text": "any!(r, A)\n\nTest whether any values in A along the singleton dimensions of r are true, and write results to r.\n\nExamples\n\njulia> A = [true false; true false]\n2×2 Array{Bool,2}:\n true false\n true false\n\njulia> any!([1; 1], A)\n2-element Array{Int64,1}:\n 1\n 1\n\njulia> any!([1 1], A)\n1×2 Array{Int64,2}:\n 1 0\n\n\n\n" -}, - -{ - "location": "stdlib/collections.html#Base.all-Tuple{Any}", - "page": "Collections and Data Structures", - "title": "Base.all", - "category": "method", - "text": "all(itr) -> Bool\n\nTest whether all elements of a boolean collection are true, returning false as soon as the first false value in itr is encountered (short-circuiting).\n\njulia> a = [true,false,false,true]\n4-element Array{Bool,1}:\n true\n false\n false\n true\n\njulia> all(a)\nfalse\n\njulia> all((println(i); v) for (i, v) in enumerate(a))\n1\n2\nfalse\n\n\n\n" -}, - -{ - "location": "stdlib/collections.html#Base.all-Tuple{AbstractArray,Any}", - "page": "Collections and Data Structures", - "title": "Base.all", - "category": "method", - "text": "all(A, dims)\n\nTest whether all values along the given dimensions of an array are true.\n\nExamples\n\njulia> A = [true false; true true]\n2×2 Array{Bool,2}:\n true false\n true true\n\njulia> all(A, 1)\n1×2 Array{Bool,2}:\n true false\n\njulia> all(A, 2)\n2×1 Array{Bool,2}:\n false\n true\n\n\n\n" -}, - -{ - "location": "stdlib/collections.html#Base.all!", - "page": "Collections and Data Structures", - "title": "Base.all!", - "category": "function", - "text": "all!(r, A)\n\nTest whether all values in A along the singleton dimensions of r are true, and write results to r.\n\nExamples\n\njulia> A = [true false; true false]\n2×2 Array{Bool,2}:\n true false\n true false\n\njulia> all!([1; 1], A)\n2-element Array{Int64,1}:\n 0\n 0\n\njulia> all!([1 1], A)\n1×2 Array{Int64,2}:\n 1 0\n\n\n\n" -}, - -{ - "location": "stdlib/collections.html#Base.count", - "page": "Collections and Data Structures", - "title": "Base.count", - "category": "function", - "text": "count(p, itr) -> Integer\ncount(itr) -> Integer\n\nCount the number of elements in itr for which predicate p returns true. If p is omitted, counts the number of true elements in itr (which should be a collection of boolean values).\n\njulia> count(i->(4<=i<=6), [2,3,4,5,6])\n3\n\njulia> count([true, false, true, true])\n3\n\n\n\n" -}, - -{ - "location": "stdlib/collections.html#Base.any-Tuple{Any,Any}", - "page": "Collections and Data Structures", - "title": "Base.any", - "category": "method", - "text": "any(p, itr) -> Bool\n\nDetermine whether predicate p returns true for any elements of itr, returning true as soon as the first item in itr for which p returns true is encountered (short-circuiting).\n\njulia> any(i->(4<=i<=6), [3,5,7])\ntrue\n\njulia> any(i -> (println(i); i > 3), 1:10)\n1\n2\n3\n4\ntrue\n\n\n\n" -}, - -{ - "location": "stdlib/collections.html#Base.all-Tuple{Any,Any}", - "page": "Collections and Data Structures", - "title": "Base.all", - "category": "method", - "text": "all(p, itr) -> Bool\n\nDetermine whether predicate p returns true for all elements of itr, returning false as soon as the first item in itr for which p returns false is encountered (short-circuiting).\n\njulia> all(i->(4<=i<=6), [4,5,6])\ntrue\n\njulia> all(i -> (println(i); i < 3), 1:10)\n1\n2\n3\nfalse\n\n\n\n" -}, - -{ - "location": "stdlib/collections.html#Base.foreach", - "page": "Collections and Data Structures", - "title": "Base.foreach", - "category": "function", - "text": "foreach(f, c...) -> Void\n\nCall function f on each element of iterable c. For multiple iterable arguments, f is called elementwise. foreach should be used instead of map when the results of f are not needed, for example in foreach(println, array).\n\nExample\n\njulia> a = 1:3:7;\n\njulia> foreach(x -> println(x^2), a)\n1\n16\n49\n\n\n\n" -}, - -{ - "location": "stdlib/collections.html#Base.map", - "page": "Collections and Data Structures", - "title": "Base.map", - "category": "function", - "text": "map(f, c...) -> collection\n\nTransform collection c by applying f to each element. For multiple collection arguments, apply f elementwise.\n\nExamples\n\njulia> map(x -> x * 2, [1, 2, 3])\n3-element Array{Int64,1}:\n 2\n 4\n 6\n\njulia> map(+, [1, 2, 3], [10, 20, 30])\n3-element Array{Int64,1}:\n 11\n 22\n 33\n\n\n\nmap(f, x::Nullable)\n\nReturn f applied to the value of x if it has one, as a Nullable. If x is null, then return a null value of type Nullable{S}. S is guaranteed to be either Union{} or a concrete type. Whichever of these is chosen is an implementation detail, but typically the choice that maximizes performance would be used. If x has a value, then the return type is guaranteed to be of type Nullable{typeof(f(x))}.\n\n\n\n" -}, - -{ - "location": "stdlib/collections.html#Base.map!", - "page": "Collections and Data Structures", - "title": "Base.map!", - "category": "function", - "text": "map!(function, destination, collection...)\n\nLike map, but stores the result in destination rather than a new collection. destination must be at least as large as the first collection.\n\nExample\n\njulia> x = zeros(3);\n\njulia> map!(x -> x * 2, x, [1, 2, 3]);\n\njulia> x\n3-element Array{Float64,1}:\n 2.0\n 4.0\n 6.0\n\n\n\n" -}, - -{ - "location": "stdlib/collections.html#Base.mapreduce-NTuple{4,Any}", - "page": "Collections and Data Structures", - "title": "Base.mapreduce", - "category": "method", - "text": "mapreduce(f, op, v0, itr)\n\nApply function f to each element in itr, and then reduce the result using the binary function op. v0 must be a neutral element for op that will be returned for empty collections. It is unspecified whether v0 is used for non-empty collections.\n\nmapreduce is functionally equivalent to calling reduce(op, v0, map(f, itr)), but will in general execute faster since no intermediate collection needs to be created. See documentation for reduce and map.\n\njulia> mapreduce(x->x^2, +, [1:3;]) # == 1 + 4 + 9\n14\n\nThe associativity of the reduction is implementation-dependent. Additionally, some implementations may reuse the return value of f for elements that appear multiple times in itr. Use mapfoldl or mapfoldr instead for guaranteed left or right associativity and invocation of f for every value.\n\n\n\n" -}, - -{ - "location": "stdlib/collections.html#Base.mapreduce-Tuple{Any,Any,Any}", - "page": "Collections and Data Structures", - "title": "Base.mapreduce", - "category": "method", - "text": "mapreduce(f, op, itr)\n\nLike mapreduce(f, op, v0, itr). In general, this cannot be used with empty collections (see reduce(op, itr)).\n\n\n\n" -}, - -{ - "location": "stdlib/collections.html#Base.mapfoldl-NTuple{4,Any}", - "page": "Collections and Data Structures", - "title": "Base.mapfoldl", - "category": "method", - "text": "mapfoldl(f, op, v0, itr)\n\nLike mapreduce, but with guaranteed left associativity, as in foldl. v0 will be used exactly once.\n\n\n\n" -}, - -{ - "location": "stdlib/collections.html#Base.mapfoldl-Tuple{Any,Any,Any}", - "page": "Collections and Data Structures", - "title": "Base.mapfoldl", - "category": "method", - "text": "mapfoldl(f, op, itr)\n\nLike mapfoldl(f, op, v0, itr), but using the first element of itr as v0. In general, this cannot be used with empty collections (see reduce(op, itr)).\n\n\n\n" -}, - -{ - "location": "stdlib/collections.html#Base.mapfoldr-NTuple{4,Any}", - "page": "Collections and Data Structures", - "title": "Base.mapfoldr", - "category": "method", - "text": "mapfoldr(f, op, v0, itr)\n\nLike mapreduce, but with guaranteed right associativity, as in foldr. v0 will be used exactly once.\n\n\n\n" -}, - -{ - "location": "stdlib/collections.html#Base.mapfoldr-Tuple{Any,Any,Any}", - "page": "Collections and Data Structures", - "title": "Base.mapfoldr", - "category": "method", - "text": "mapfoldr(f, op, itr)\n\nLike mapfoldr(f, op, v0, itr), but using the first element of itr as v0. In general, this cannot be used with empty collections (see reduce(op, itr)).\n\n\n\n" -}, - -{ - "location": "stdlib/collections.html#Base.first", - "page": "Collections and Data Structures", - "title": "Base.first", - "category": "function", - "text": "first(coll)\n\nGet the first element of an iterable collection. Returns the start point of a Range even if it is empty.\n\njulia> first(2:2:10)\n2\n\njulia> first([1; 2; 3; 4])\n1\n\n\n\n" -}, - -{ - "location": "stdlib/collections.html#Base.last", - "page": "Collections and Data Structures", - "title": "Base.last", - "category": "function", - "text": "last(coll)\n\nGet the last element of an ordered collection, if it can be computed in O(1) time. This is accomplished by calling endof to get the last index. Returns the end point of a Range even if it is empty.\n\njulia> last(1:2:10)\n9\n\njulia> last([1; 2; 3; 4])\n4\n\n\n\n" -}, - -{ - "location": "stdlib/collections.html#Base.step", - "page": "Collections and Data Structures", - "title": "Base.step", - "category": "function", - "text": "step(r)\n\nGet the step size of a Range object.\n\njulia> step(1:10)\n1\n\njulia> step(1:2:10)\n2\n\njulia> step(2.5:0.3:10.9)\n0.3\n\njulia> step(linspace(2.5,10.9,85))\n0.1\n\n\n\n" -}, - -{ - "location": "stdlib/collections.html#Base.collect-Tuple{Any}", - "page": "Collections and Data Structures", - "title": "Base.collect", - "category": "method", - "text": "collect(collection)\n\nReturn an Array of all items in a collection or iterator. For associative collections, returns Pair{KeyType, ValType}. If the argument is array-like or is an iterator with the HasShape() trait, the result will have the same shape and number of dimensions as the argument.\n\nExample\n\njulia> collect(1:2:13)\n7-element Array{Int64,1}:\n 1\n 3\n 5\n 7\n 9\n 11\n 13\n\n\n\n" -}, - -{ - "location": "stdlib/collections.html#Base.collect-Tuple{Type,Any}", - "page": "Collections and Data Structures", - "title": "Base.collect", - "category": "method", - "text": "collect(element_type, collection)\n\nReturn an Array with the given element type of all items in a collection or iterable. The result has the same shape and number of dimensions as collection.\n\njulia> collect(Float64, 1:2:5)\n3-element Array{Float64,1}:\n 1.0\n 3.0\n 5.0\n\n\n\n" -}, - -{ - "location": "stdlib/collections.html#Base.issubset-Tuple{Any,Any}", - "page": "Collections and Data Structures", - "title": "Base.issubset", - "category": "method", - "text": "issubset(a, b)\n⊆(a,b) -> Bool\n⊈(a,b) -> Bool\n⊊(a,b) -> Bool\n\nDetermine whether every element of a is also in b, using in.\n\nExamples\n\njulia> issubset([1, 2], [1, 2, 3])\ntrue\n\njulia> issubset([1, 2, 3], [1, 2])\nfalse\n\n\n\n" -}, - -{ - "location": "stdlib/collections.html#Base.filter", - "page": "Collections and Data Structures", - "title": "Base.filter", - "category": "function", - "text": "filter(function, collection)\n\nReturn a copy of collection, removing elements for which function is false. For associative collections, the function is passed two arguments (key and value).\n\nExamples\n\njulia> a = 1:10\n1:10\n\njulia> filter(isodd, a)\n5-element Array{Int64,1}:\n 1\n 3\n 5\n 7\n 9\n\njulia> d = Dict(1=>\"a\", 2=>\"b\")\nDict{Int64,String} with 2 entries:\n 2 => \"b\"\n 1 => \"a\"\n\njulia> filter((x,y)->isodd(x), d)\nDict{Int64,String} with 1 entry:\n 1 => \"a\"\n\n\n\nfilter(p, x::Nullable)\n\nReturn null if either x is null or p(get(x)) is false, and x otherwise.\n\n\n\n" -}, - -{ - "location": "stdlib/collections.html#Base.filter!", - "page": "Collections and Data Structures", - "title": "Base.filter!", - "category": "function", - "text": "filter!(function, collection)\n\nUpdate collection, removing elements for which function is false. For associative collections, the function is passed two arguments (key and value).\n\nExample\n\njulia> filter!(isodd, collect(1:10))\n5-element Array{Int64,1}:\n 1\n 3\n 5\n 7\n 9\n\n\n\n" -}, - -{ - "location": "stdlib/collections.html#Iterable-Collections-1", - "page": "Collections and Data Structures", - "title": "Iterable Collections", - "category": "section", - "text": "Base.in\nBase.eltype\nBase.indexin\nBase.findin\nBase.unique\nBase.allunique\nBase.reduce(::Any, ::Any, ::Any)\nBase.reduce(::Any, ::Any)\nBase.foldl(::Any, ::Any, ::Any)\nBase.foldl(::Any, ::Any)\nBase.foldr(::Any, ::Any, ::Any)\nBase.foldr(::Any, ::Any)\nBase.maximum(::Any)\nBase.maximum(::Any, ::Any)\nBase.maximum!\nBase.minimum(::Any)\nBase.minimum(::Any, ::Any)\nBase.minimum!\nBase.extrema(::Any)\nBase.extrema(::AbstractArray, ::Any)\nBase.indmax\nBase.indmin\nBase.findmax(::Any)\nBase.findmax(::AbstractArray, ::Any)\nBase.findmin(::Any)\nBase.findmin(::AbstractArray, ::Any)\nBase.findmax!\nBase.findmin!\nBase.sum\nBase.sum!\nBase.prod\nBase.prod!\nBase.any(::Any)\nBase.any(::AbstractArray, ::Any)\nBase.any!\nBase.all(::Any)\nBase.all(::AbstractArray, ::Any)\nBase.all!\nBase.count\nBase.any(::Any, ::Any)\nBase.all(::Any, ::Any)\nBase.foreach\nBase.map\nBase.map!\nBase.mapreduce(::Any, ::Any, ::Any, ::Any)\nBase.mapreduce(::Any, ::Any, ::Any)\nBase.mapfoldl(::Any, ::Any, ::Any, ::Any)\nBase.mapfoldl(::Any, ::Any, ::Any)\nBase.mapfoldr(::Any, ::Any, ::Any, ::Any)\nBase.mapfoldr(::Any, ::Any, ::Any)\nBase.first\nBase.last\nBase.step\nBase.collect(::Any)\nBase.collect(::Type, ::Any)\nBase.issubset(::Any, ::Any)\nBase.filter\nBase.filter!" -}, - -{ - "location": "stdlib/collections.html#Base.getindex-Tuple{Any,Vararg{Any,N} where N}", - "page": "Collections and Data Structures", - "title": "Base.getindex", - "category": "method", - "text": "getindex(collection, key...)\n\nRetrieve the value(s) stored at the given key or index within a collection. The syntax a[i,j,...] is converted by the compiler to getindex(a, i, j, ...).\n\nExample\n\njulia> A = Dict(\"a\" => 1, \"b\" => 2)\nDict{String,Int64} with 2 entries:\n \"b\" => 2\n \"a\" => 1\n\njulia> getindex(A, \"a\")\n1\n\n\n\n" -}, - -{ - "location": "stdlib/collections.html#Base.setindex!-Tuple{Any,Any,Vararg{Any,N} where N}", - "page": "Collections and Data Structures", - "title": "Base.setindex!", - "category": "method", - "text": "setindex!(collection, value, key...)\n\nStore the given value at the given key or index within a collection. The syntax a[i,j,...] = x is converted by the compiler to (setindex!(a, x, i, j, ...); x).\n\n\n\n" -}, - -{ - "location": "stdlib/collections.html#Indexable-Collections-1", - "page": "Collections and Data Structures", - "title": "Indexable Collections", - "category": "section", - "text": "Base.getindex(::Any, ::Any...)\nBase.setindex!(::Any, ::Any, ::Any...)Fully implemented by:Array\nBitArray\nAbstractArray\nSubArray\nObjectIdDict\nDict\nWeakKeyDict\nAbstractStringPartially implemented by:Range\nUnitRange\nTuple" -}, - -{ - "location": "stdlib/collections.html#Base.Dict", - "page": "Collections and Data Structures", - "title": "Base.Dict", - "category": "type", - "text": "Dict([itr])\n\nDict{K,V}() constructs a hash table with keys of type K and values of type V.\n\nGiven a single iterable argument, constructs a Dict whose key-value pairs are taken from 2-tuples (key,value) generated by the argument.\n\njulia> Dict([(\"A\", 1), (\"B\", 2)])\nDict{String,Int64} with 2 entries:\n \"B\" => 2\n \"A\" => 1\n\nAlternatively, a sequence of pair arguments may be passed.\n\njulia> Dict(\"A\"=>1, \"B\"=>2)\nDict{String,Int64} with 2 entries:\n \"B\" => 2\n \"A\" => 1\n\n\n\n" -}, - -{ - "location": "stdlib/collections.html#Base.ObjectIdDict", - "page": "Collections and Data Structures", - "title": "Base.ObjectIdDict", - "category": "type", - "text": "ObjectIdDict([itr])\n\nObjectIdDict() constructs a hash table where the keys are (always) object identities. Unlike Dict it is not parameterized on its key and value type and thus its eltype is always Pair{Any,Any}.\n\nSee Dict for further help.\n\n\n\n" -}, - -{ - "location": "stdlib/collections.html#Base.WeakKeyDict", - "page": "Collections and Data Structures", - "title": "Base.WeakKeyDict", - "category": "type", - "text": "WeakKeyDict([itr])\n\nWeakKeyDict() constructs a hash table where the keys are weak references to objects, and thus may be garbage collected even when referenced in a hash table.\n\nSee Dict for further help.\n\n\n\n" -}, - -{ - "location": "stdlib/collections.html#Base.haskey", - "page": "Collections and Data Structures", - "title": "Base.haskey", - "category": "function", - "text": "haskey(collection, key) -> Bool\n\nDetermine whether a collection has a mapping for a given key.\n\njulia> a = Dict(\'a\'=>2, \'b\'=>3)\nDict{Char,Int64} with 2 entries:\n \'b\' => 3\n \'a\' => 2\n\njulia> haskey(a,\'a\')\ntrue\n\njulia> haskey(a,\'c\')\nfalse\n\n\n\n" -}, - -{ - "location": "stdlib/collections.html#Base.get-Tuple{Any,Any,Any}", - "page": "Collections and Data Structures", - "title": "Base.get", - "category": "method", - "text": "get(collection, key, default)\n\nReturn the value stored for the given key, or the given default value if no mapping for the key is present.\n\nExamples\n\njulia> d = Dict(\"a\"=>1, \"b\"=>2);\n\njulia> get(d, \"a\", 3)\n1\n\njulia> get(d, \"c\", 3)\n3\n\n\n\n" -}, - -{ - "location": "stdlib/collections.html#Base.get", - "page": "Collections and Data Structures", - "title": "Base.get", - "category": "function", - "text": "get(f::Function, collection, key)\n\nReturn the value stored for the given key, or if no mapping for the key is present, return f(). Use get! to also store the default value in the dictionary.\n\nThis is intended to be called using do block syntax\n\nget(dict, key) do\n # default value calculated here\n time()\nend\n\n\n\n" -}, - -{ - "location": "stdlib/collections.html#Base.get!-Tuple{Any,Any,Any}", - "page": "Collections and Data Structures", - "title": "Base.get!", - "category": "method", - "text": "get!(collection, key, default)\n\nReturn the value stored for the given key, or if no mapping for the key is present, store key => default, and return default.\n\nExamples\n\njulia> d = Dict(\"a\"=>1, \"b\"=>2, \"c\"=>3);\n\njulia> get!(d, \"a\", 5)\n1\n\njulia> get!(d, \"d\", 4)\n4\n\njulia> d\nDict{String,Int64} with 4 entries:\n \"c\" => 3\n \"b\" => 2\n \"a\" => 1\n \"d\" => 4\n\n\n\n" -}, - -{ - "location": "stdlib/collections.html#Base.get!-Tuple{Function,Any,Any}", - "page": "Collections and Data Structures", - "title": "Base.get!", - "category": "method", - "text": "get!(f::Function, collection, key)\n\nReturn the value stored for the given key, or if no mapping for the key is present, store key => f(), and return f().\n\nThis is intended to be called using do block syntax:\n\nget!(dict, key) do\n # default value calculated here\n time()\nend\n\n\n\n" -}, - -{ - "location": "stdlib/collections.html#Base.getkey", - "page": "Collections and Data Structures", - "title": "Base.getkey", - "category": "function", - "text": "getkey(collection, key, default)\n\nReturn the key matching argument key if one exists in collection, otherwise return default.\n\njulia> a = Dict(\'a\'=>2, \'b\'=>3)\nDict{Char,Int64} with 2 entries:\n \'b\' => 3\n \'a\' => 2\n\njulia> getkey(a,\'a\',1)\n\'a\': ASCII/Unicode U+0061 (category Ll: Letter, lowercase)\n\njulia> getkey(a,\'d\',\'a\')\n\'a\': ASCII/Unicode U+0061 (category Ll: Letter, lowercase)\n\n\n\n" -}, - -{ - "location": "stdlib/collections.html#Base.delete!", - "page": "Collections and Data Structures", - "title": "Base.delete!", - "category": "function", - "text": "delete!(collection, key)\n\nDelete the mapping for the given key in a collection, and return the collection.\n\nExample\n\njulia> d = Dict(\"a\"=>1, \"b\"=>2)\nDict{String,Int64} with 2 entries:\n \"b\" => 2\n \"a\" => 1\n\njulia> delete!(d, \"b\")\nDict{String,Int64} with 1 entry:\n \"a\" => 1\n\n\n\n" -}, - -{ - "location": "stdlib/collections.html#Base.pop!-Tuple{Any,Any,Any}", - "page": "Collections and Data Structures", - "title": "Base.pop!", - "category": "method", - "text": "pop!(collection, key[, default])\n\nDelete and return the mapping for key if it exists in collection, otherwise return default, or throw an error if default is not specified.\n\nExamples\n\njulia> d = Dict(\"a\"=>1, \"b\"=>2, \"c\"=>3);\n\njulia> pop!(d, \"a\")\n1\n\njulia> pop!(d, \"d\")\nERROR: KeyError: key \"d\" not found\nStacktrace:\n [1] pop!(::Dict{String,Int64}, ::String) at ./dict.jl:539\n\njulia> pop!(d, \"e\", 4)\n4\n\n\n\n" -}, - -{ - "location": "stdlib/collections.html#Base.keys", - "page": "Collections and Data Structures", - "title": "Base.keys", - "category": "function", - "text": "keys(a::Associative)\n\nReturn an iterator over all keys in a collection. collect(keys(a)) returns an array of keys. Since the keys are stored internally in a hash table, the order in which they are returned may vary. But keys(a) and values(a) both iterate a and return the elements in the same order.\n\njulia> a = Dict(\'a\'=>2, \'b\'=>3)\nDict{Char,Int64} with 2 entries:\n \'b\' => 3\n \'a\' => 2\n\njulia> collect(keys(a))\n2-element Array{Char,1}:\n \'b\'\n \'a\'\n\n\n\n" -}, - -{ - "location": "stdlib/collections.html#Base.values", - "page": "Collections and Data Structures", - "title": "Base.values", - "category": "function", - "text": "values(a::Associative)\n\nReturn an iterator over all values in a collection. collect(values(a)) returns an array of values. Since the values are stored internally in a hash table, the order in which they are returned may vary. But keys(a) and values(a) both iterate a and return the elements in the same order.\n\njulia> a = Dict(\'a\'=>2, \'b\'=>3)\nDict{Char,Int64} with 2 entries:\n \'b\' => 3\n \'a\' => 2\n\njulia> collect(values(a))\n2-element Array{Int64,1}:\n 3\n 2\n\n\n\n" -}, - -{ - "location": "stdlib/collections.html#Base.merge", - "page": "Collections and Data Structures", - "title": "Base.merge", - "category": "function", - "text": "merge(d::Associative, others::Associative...)\n\nConstruct a merged collection from the given collections. If necessary, the types of the resulting collection will be promoted to accommodate the types of the merged collections. If the same key is present in another collection, the value for that key will be the value it has in the last collection listed.\n\njulia> a = Dict(\"foo\" => 0.0, \"bar\" => 42.0)\nDict{String,Float64} with 2 entries:\n \"bar\" => 42.0\n \"foo\" => 0.0\n\njulia> b = Dict(\"baz\" => 17, \"bar\" => 4711)\nDict{String,Int64} with 2 entries:\n \"bar\" => 4711\n \"baz\" => 17\n\njulia> merge(a, b)\nDict{String,Float64} with 3 entries:\n \"bar\" => 4711.0\n \"baz\" => 17.0\n \"foo\" => 0.0\n\njulia> merge(b, a)\nDict{String,Float64} with 3 entries:\n \"bar\" => 42.0\n \"baz\" => 17.0\n \"foo\" => 0.0\n\n\n\nmerge(combine, d::Associative, others::Associative...)\n\nConstruct a merged collection from the given collections. If necessary, the types of the resulting collection will be promoted to accommodate the types of the merged collections. Values with the same key will be combined using the combiner function.\n\njulia> a = Dict(\"foo\" => 0.0, \"bar\" => 42.0)\nDict{String,Float64} with 2 entries:\n \"bar\" => 42.0\n \"foo\" => 0.0\n\njulia> b = Dict(\"baz\" => 17, \"bar\" => 4711)\nDict{String,Int64} with 2 entries:\n \"bar\" => 4711\n \"baz\" => 17\n\njulia> merge(+, a, b)\nDict{String,Float64} with 3 entries:\n \"bar\" => 4753.0\n \"baz\" => 17.0\n \"foo\" => 0.0\n\n\n\n" -}, - -{ - "location": "stdlib/collections.html#Base.merge!", - "page": "Collections and Data Structures", - "title": "Base.merge!", - "category": "function", - "text": "Merge changes into current head \n\n\n\nInternal implementation of merge. Returns true if merge was successful, otherwise false\n\n\n\nmerge!(repo::GitRepo; kwargs...) -> Bool\n\nPerform a git merge on the repository repo, merging commits with diverging history into the current branch. Returns true if the merge succeeded, false if not.\n\nThe keyword arguments are:\n\ncommittish::AbstractString=\"\": Merge the named commit(s) in committish.\nbranch::AbstractString=\"\": Merge the branch branch and all its commits since it diverged from the current branch.\nfastforward::Bool=false: If fastforward is true, only merge if the merge is a fast-forward (the current branch head is an ancestor of the commits to be merged), otherwise refuse to merge and return false. This is equivalent to the git CLI option --ff-only.\nmerge_opts::MergeOptions=MergeOptions(): merge_opts specifies options for the merge, such as merge strategy in case of conflicts.\ncheckout_opts::CheckoutOptions=CheckoutOptions(): checkout_opts specifies options for the checkout step.\n\nEquivalent to git merge [--ff-only] [ | ].\n\nnote: Note\nIf you specify a branch, this must be done in reference format, since the string will be turned into a GitReference. For example, if you wanted to merge branch branch_a, you would call merge!(repo, branch=\"refs/heads/branch_a\").\n\n\n\nmerge!(d::Associative, others::Associative...)\n\nUpdate collection with pairs from the other collections. See also merge.\n\njulia> d1 = Dict(1 => 2, 3 => 4);\n\njulia> d2 = Dict(1 => 4, 4 => 5);\n\njulia> merge!(d1, d2);\n\njulia> d1\nDict{Int64,Int64} with 3 entries:\n 4 => 5\n 3 => 4\n 1 => 4\n\n\n\nmerge!(combine, d::Associative, others::Associative...)\n\nUpdate collection with pairs from the other collections. Values with the same key will be combined using the combiner function.\n\njulia> d1 = Dict(1 => 2, 3 => 4);\n\njulia> d2 = Dict(1 => 4, 4 => 5);\n\njulia> merge!(+, d1, d2);\n\njulia> d1\nDict{Int64,Int64} with 3 entries:\n 4 => 5\n 3 => 4\n 1 => 6\n\njulia> merge!(-, d1, d1);\n\njulia> d1\nDict{Int64,Int64} with 3 entries:\n 4 => 0\n 3 => 0\n 1 => 0\n\n\n\n" -}, - -{ - "location": "stdlib/collections.html#Base.sizehint!", - "page": "Collections and Data Structures", - "title": "Base.sizehint!", - "category": "function", - "text": "sizehint!(s, n)\n\nSuggest that collection s reserve capacity for at least n elements. This can improve performance.\n\n\n\n" -}, - -{ - "location": "stdlib/collections.html#Base.keytype", - "page": "Collections and Data Structures", - "title": "Base.keytype", - "category": "function", - "text": "keytype(type)\n\nGet the key type of an associative collection type. Behaves similarly to eltype.\n\njulia> keytype(Dict(Int32(1) => \"foo\"))\nInt32\n\n\n\n" -}, - -{ - "location": "stdlib/collections.html#Base.valtype", - "page": "Collections and Data Structures", - "title": "Base.valtype", - "category": "function", - "text": "valtype(type)\n\nGet the value type of an associative collection type. Behaves similarly to eltype.\n\njulia> valtype(Dict(Int32(1) => \"foo\"))\nString\n\n\n\n" -}, - -{ - "location": "stdlib/collections.html#Associative-Collections-1", - "page": "Collections and Data Structures", - "title": "Associative Collections", - "category": "section", - "text": "Dict is the standard associative collection. Its implementation uses hash() as the hashing function for the key, and isequal() to determine equality. Define these two functions for custom types to override how they are stored in a hash table.ObjectIdDict is a special hash table where the keys are always object identities.WeakKeyDict is a hash table implementation where the keys are weak references to objects, and thus may be garbage collected even when referenced in a hash table.Dicts can be created by passing pair objects constructed with =>() to a Dict constructor: Dict(\"A\"=>1, \"B\"=>2). This call will attempt to infer type information from the keys and values (i.e. this example creates a Dict{String, Int64}). To explicitly specify types use the syntax Dict{KeyType,ValueType}(...). For example, Dict{String,Int32}(\"A\"=>1, \"B\"=>2).Associative collections may also be created with generators. For example, Dict(i => f(i) for i = 1:10).Given a dictionary D, the syntax D[x] returns the value of key x (if it exists) or throws an error, and D[x] = y stores the key-value pair x => y in D (replacing any existing value for the key x). Multiple arguments to D[...] are converted to tuples; for example, the syntax D[x,y] is equivalent to D[(x,y)], i.e. it refers to the value keyed by the tuple (x,y).Base.Dict\nBase.ObjectIdDict\nBase.WeakKeyDict\nBase.haskey\nBase.get(::Any, ::Any, ::Any)\nBase.get\nBase.get!(::Any, ::Any, ::Any)\nBase.get!(::Function, ::Any, ::Any)\nBase.getkey\nBase.delete!\nBase.pop!(::Any, ::Any, ::Any)\nBase.keys\nBase.values\nBase.merge\nBase.merge!\nBase.sizehint!\nBase.keytype\nBase.valtypeFully implemented by:ObjectIdDict\nDict\nWeakKeyDictPartially implemented by:IntSet\nSet\nEnvHash\nArray\nBitArray" -}, - -{ - "location": "stdlib/collections.html#Base.Set", - "page": "Collections and Data Structures", - "title": "Base.Set", - "category": "type", - "text": "Set([itr])\n\nConstruct a Set of the values generated by the given iterable object, or an empty set. Should be used instead of IntSet for sparse integer sets, or for sets of arbitrary objects.\n\n\n\n" -}, - -{ - "location": "stdlib/collections.html#Base.IntSet", - "page": "Collections and Data Structures", - "title": "Base.IntSet", - "category": "type", - "text": "IntSet([itr])\n\nConstruct a sorted set of positive Ints generated by the given iterable object, or an empty set. Implemented as a bit string, and therefore designed for dense integer sets. Only Ints greater than 0 can be stored. If the set will be sparse (for example holding a few very large integers), use Set instead.\n\n\n\n" -}, - -{ - "location": "stdlib/collections.html#Base.union", - "page": "Collections and Data Structures", - "title": "Base.union", - "category": "function", - "text": "union(s1,s2...)\n∪(s1,s2...)\n\nConstruct the union of two or more sets. Maintains order with arrays.\n\nExamples\n\njulia> union([1, 2], [3, 4])\n4-element Array{Int64,1}:\n 1\n 2\n 3\n 4\n\njulia> union([1, 2], [2, 4])\n3-element Array{Int64,1}:\n 1\n 2\n 4\n\njulia> union([4, 2], [1, 2])\n3-element Array{Int64,1}:\n 4\n 2\n 1\n\n\n\n" -}, - -{ - "location": "stdlib/collections.html#Base.union!", - "page": "Collections and Data Structures", - "title": "Base.union!", - "category": "function", - "text": "union!(s, iterable)\n\nUnion each element of iterable into set s in-place.\n\n\n\n" -}, - -{ - "location": "stdlib/collections.html#Base.intersect", - "page": "Collections and Data Structures", - "title": "Base.intersect", - "category": "function", - "text": "intersect(s1,s2...)\n∩(s1,s2)\n\nConstruct the intersection of two or more sets. Maintains order and multiplicity of the first argument for arrays and ranges.\n\n\n\n" -}, - -{ - "location": "stdlib/collections.html#Base.setdiff", - "page": "Collections and Data Structures", - "title": "Base.setdiff", - "category": "function", - "text": "setdiff(a, b)\n\nConstruct the set of elements in a but not b. Maintains order with arrays. Note that both arguments must be collections, and both will be iterated over. In particular, setdiff(set,element) where element is a potential member of set, will not work in general.\n\nExample\n\njulia> setdiff([1,2,3],[3,4,5])\n2-element Array{Int64,1}:\n 1\n 2\n\n\n\n" -}, - -{ - "location": "stdlib/collections.html#Base.setdiff!", - "page": "Collections and Data Structures", - "title": "Base.setdiff!", - "category": "function", - "text": "setdiff!(s, iterable)\n\nRemove each element of iterable from set s in-place.\n\n\n\n" -}, - -{ - "location": "stdlib/collections.html#Base.symdiff", - "page": "Collections and Data Structures", - "title": "Base.symdiff", - "category": "function", - "text": "symdiff(a, b, rest...)\n\nConstruct the symmetric difference of elements in the passed in sets or arrays. Maintains order with arrays.\n\nExample\n\njulia> symdiff([1,2,3],[3,4,5],[4,5,6])\n3-element Array{Int64,1}:\n 1\n 2\n 6\n\n\n\n" -}, - -{ - "location": "stdlib/collections.html#Base.symdiff!-Tuple{IntSet,Integer}", - "page": "Collections and Data Structures", - "title": "Base.symdiff!", - "category": "method", - "text": "symdiff!(s, n)\n\nThe set s is destructively modified to toggle the inclusion of integer n.\n\n\n\n" -}, - -{ - "location": "stdlib/collections.html#Base.symdiff!-Tuple{IntSet,Any}", - "page": "Collections and Data Structures", - "title": "Base.symdiff!", - "category": "method", - "text": "symdiff!(s, itr)\n\nFor each element in itr, destructively toggle its inclusion in set s.\n\n\n\n" -}, - -{ - "location": "stdlib/collections.html#Base.symdiff!-Tuple{IntSet,IntSet}", - "page": "Collections and Data Structures", - "title": "Base.symdiff!", - "category": "method", - "text": "symdiff!(s, itr)\n\nFor each element in itr, destructively toggle its inclusion in set s.\n\n\n\n" -}, - -{ - "location": "stdlib/collections.html#Base.intersect!", - "page": "Collections and Data Structures", - "title": "Base.intersect!", - "category": "function", - "text": "intersect!(s1::IntSet, s2::IntSet)\n\nIntersects sets s1 and s2 and overwrites the set s1 with the result. If needed, s1 will be expanded to the size of s2.\n\n\n\n" -}, - -{ - "location": "stdlib/collections.html#Base.issubset", - "page": "Collections and Data Structures", - "title": "Base.issubset", - "category": "function", - "text": "issubset(A, S) -> Bool\n⊆(A,S) -> Bool\n\nReturn true if A is a subset of or equal to S.\n\n\n\n" -}, - -{ - "location": "stdlib/collections.html#Set-Like-Collections-1", - "page": "Collections and Data Structures", - "title": "Set-Like Collections", - "category": "section", - "text": "Base.Set\nBase.IntSet\nBase.union\nBase.union!\nBase.intersect\nBase.setdiff\nBase.setdiff!\nBase.symdiff\nBase.symdiff!(::IntSet, ::Integer)\nBase.symdiff!(::IntSet, ::Any)\nBase.symdiff!(::IntSet, ::IntSet)\nBase.intersect!\nBase.issubsetFully implemented by:IntSet\nSetPartially implemented by:Array" -}, - -{ - "location": "stdlib/collections.html#Base.push!", - "page": "Collections and Data Structures", - "title": "Base.push!", - "category": "function", - "text": "push!(collection, items...) -> collection\n\nInsert one or more items at the end of collection.\n\nExample\n\njulia> push!([1, 2, 3], 4, 5, 6)\n6-element Array{Int64,1}:\n 1\n 2\n 3\n 4\n 5\n 6\n\nUse append! to add all the elements of another collection to collection. The result of the preceding example is equivalent to append!([1, 2, 3], [4, 5, 6]).\n\n\n\n" -}, - -{ - "location": "stdlib/collections.html#Base.pop!-Tuple{Any}", - "page": "Collections and Data Structures", - "title": "Base.pop!", - "category": "method", - "text": "pop!(collection) -> item\n\nRemove the last item in collection and return it.\n\nExamples\n\njulia> A=[1, 2, 3, 4, 5, 6]\n6-element Array{Int64,1}:\n 1\n 2\n 3\n 4\n 5\n 6\n\njulia> pop!(A)\n6\n\njulia> A\n5-element Array{Int64,1}:\n 1\n 2\n 3\n 4\n 5\n\n\n\n" -}, - -{ - "location": "stdlib/collections.html#Base.unshift!", - "page": "Collections and Data Structures", - "title": "Base.unshift!", - "category": "function", - "text": "unshift!(collection, items...) -> collection\n\nInsert one or more items at the beginning of collection.\n\nExample\n\njulia> unshift!([1, 2, 3, 4], 5, 6)\n6-element Array{Int64,1}:\n 5\n 6\n 1\n 2\n 3\n 4\n\n\n\n" -}, - -{ - "location": "stdlib/collections.html#Base.shift!", - "page": "Collections and Data Structures", - "title": "Base.shift!", - "category": "function", - "text": "shift!(collection) -> item\n\nRemove the first item from collection.\n\nExample\n\njulia> A = [1, 2, 3, 4, 5, 6]\n6-element Array{Int64,1}:\n 1\n 2\n 3\n 4\n 5\n 6\n\njulia> shift!(A)\n1\n\njulia> A\n5-element Array{Int64,1}:\n 2\n 3\n 4\n 5\n 6\n\n\n\n" -}, - -{ - "location": "stdlib/collections.html#Base.insert!", - "page": "Collections and Data Structures", - "title": "Base.insert!", - "category": "function", - "text": "insert!(a::Vector, index::Integer, item)\n\nInsert an item into a at the given index. index is the index of item in the resulting a.\n\nExample\n\njulia> insert!([6, 5, 4, 2, 1], 4, 3)\n6-element Array{Int64,1}:\n 6\n 5\n 4\n 3\n 2\n 1\n\n\n\n" -}, - -{ - "location": "stdlib/collections.html#Base.deleteat!", - "page": "Collections and Data Structures", - "title": "Base.deleteat!", - "category": "function", - "text": "deleteat!(a::Vector, i::Integer)\n\nRemove the item at the given i and return the modified a. Subsequent items are shifted to fill the resulting gap.\n\nExample\n\njulia> deleteat!([6, 5, 4, 3, 2, 1], 2)\n5-element Array{Int64,1}:\n 6\n 4\n 3\n 2\n 1\n\n\n\ndeleteat!(a::Vector, inds)\n\nRemove the items at the indices given by inds, and return the modified a. Subsequent items are shifted to fill the resulting gap.\n\ninds can be either an iterator or a collection of sorted and unique integer indices, or a boolean vector of the same length as a with true indicating entries to delete.\n\nExamples\n\njulia> deleteat!([6, 5, 4, 3, 2, 1], 1:2:5)\n3-element Array{Int64,1}:\n 5\n 3\n 1\n\njulia> deleteat!([6, 5, 4, 3, 2, 1], [true, false, true, false, true, false])\n3-element Array{Int64,1}:\n 5\n 3\n 1\n\njulia> deleteat!([6, 5, 4, 3, 2, 1], (2, 2))\nERROR: ArgumentError: indices must be unique and sorted\nStacktrace:\n [1] _deleteat!(::Array{Int64,1}, ::Tuple{Int64,Int64}) at ./array.jl:921\n [2] deleteat!(::Array{Int64,1}, ::Tuple{Int64,Int64}) at ./array.jl:908\n\n\n\n" -}, - -{ - "location": "stdlib/collections.html#Base.splice!", - "page": "Collections and Data Structures", - "title": "Base.splice!", - "category": "function", - "text": "splice!(a::Vector, index::Integer, [replacement]) -> item\n\nRemove the item at the given index, and return the removed item. Subsequent items are shifted left to fill the resulting gap. If specified, replacement values from an ordered collection will be spliced in place of the removed item.\n\nExamples\n\njulia> A = [6, 5, 4, 3, 2, 1]; splice!(A, 5)\n2\n\njulia> A\n5-element Array{Int64,1}:\n 6\n 5\n 4\n 3\n 1\n\njulia> splice!(A, 5, -1)\n1\n\njulia> A\n5-element Array{Int64,1}:\n 6\n 5\n 4\n 3\n -1\n\njulia> splice!(A, 1, [-1, -2, -3])\n6\n\njulia> A\n7-element Array{Int64,1}:\n -1\n -2\n -3\n 5\n 4\n 3\n -1\n\nTo insert replacement before an index n without removing any items, use splice!(collection, n:n-1, replacement).\n\n\n\nsplice!(a::Vector, range, [replacement]) -> items\n\nRemove items in the specified index range, and return a collection containing the removed items. Subsequent items are shifted left to fill the resulting gap. If specified, replacement values from an ordered collection will be spliced in place of the removed items.\n\nTo insert replacement before an index n without removing any items, use splice!(collection, n:n-1, replacement).\n\nExample\n\njulia> splice!(A, 4:3, 2)\n0-element Array{Int64,1}\n\njulia> A\n8-element Array{Int64,1}:\n -1\n -2\n -3\n 2\n 5\n 4\n 3\n -1\n\n\n\n" -}, - -{ - "location": "stdlib/collections.html#Base.resize!", - "page": "Collections and Data Structures", - "title": "Base.resize!", - "category": "function", - "text": "resize!(a::Vector, n::Integer) -> Vector\n\nResize a to contain n elements. If n is smaller than the current collection length, the first n elements will be retained. If n is larger, the new elements are not guaranteed to be initialized.\n\nExamples\n\njulia> resize!([6, 5, 4, 3, 2, 1], 3)\n3-element Array{Int64,1}:\n 6\n 5\n 4\n\njulia> a = resize!([6, 5, 4, 3, 2, 1], 8);\n\njulia> length(a)\n8\n\njulia> a[1:6]\n6-element Array{Int64,1}:\n 6\n 5\n 4\n 3\n 2\n 1\n\n\n\n" -}, - -{ - "location": "stdlib/collections.html#Base.append!", - "page": "Collections and Data Structures", - "title": "Base.append!", - "category": "function", - "text": "append!(collection, collection2) -> collection.\n\nAdd the elements of collection2 to the end of collection.\n\nExamples\n\njulia> append!([1],[2,3])\n3-element Array{Int64,1}:\n 1\n 2\n 3\n\njulia> append!([1, 2, 3], [4, 5, 6])\n6-element Array{Int64,1}:\n 1\n 2\n 3\n 4\n 5\n 6\n\nUse push! to add individual items to collection which are not already themselves in another collection. The result is of the preceding example is equivalent to push!([1, 2, 3], 4, 5, 6).\n\n\n\n" -}, - -{ - "location": "stdlib/collections.html#Base.prepend!", - "page": "Collections and Data Structures", - "title": "Base.prepend!", - "category": "function", - "text": "prepend!(a::Vector, items) -> collection\n\nInsert the elements of items to the beginning of a.\n\nExample\n\njulia> prepend!([3],[1,2])\n3-element Array{Int64,1}:\n 1\n 2\n 3\n\n\n\n" -}, - -{ - "location": "stdlib/collections.html#Dequeues-1", - "page": "Collections and Data Structures", - "title": "Dequeues", - "category": "section", - "text": "Base.push!\nBase.pop!(::Any)\nBase.unshift!\nBase.shift!\nBase.insert!\nBase.deleteat!\nBase.splice!\nBase.resize!\nBase.append!\nBase.prepend!Fully implemented by:Vector (a.k.a. 1-dimensional Array)\nBitVector (a.k.a. 1-dimensional BitArray)" -}, - -{ - "location": "stdlib/math.html#", - "page": "Mathematics", - "title": "Mathematics", - "category": "page", - "text": "" -}, - -{ - "location": "stdlib/math.html#Mathematics-1", - "page": "Mathematics", - "title": "Mathematics", - "category": "section", - "text": "" -}, - -{ - "location": "stdlib/math.html#Base.:--Tuple{Any}", - "page": "Mathematics", - "title": "Base.:-", - "category": "method", - "text": "-(x)\n\nUnary minus operator.\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.:+", - "page": "Mathematics", - "title": "Base.:+", - "category": "function", - "text": "+(x, y...)\n\nAddition operator. x+y+z+... calls this function with all arguments, i.e. +(x, y, z, ...).\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.:--Tuple{Any,Any}", - "page": "Mathematics", - "title": "Base.:-", - "category": "method", - "text": "-(x, y)\n\nSubtraction operator.\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.:*-Tuple{Any,Vararg{Any,N} where N}", - "page": "Mathematics", - "title": "Base.:*", - "category": "method", - "text": "*(x, y...)\n\nMultiplication operator. x*y*z*... calls this function with all arguments, i.e. *(x, y, z, ...).\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.:/", - "page": "Mathematics", - "title": "Base.:/", - "category": "function", - "text": "/(x, y)\n\nRight division operator: multiplication of x by the inverse of y on the right. Gives floating-point results for integer arguments.\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.:\\-Tuple{Any,Any}", - "page": "Mathematics", - "title": "Base.:\\", - "category": "method", - "text": "\\(x, y)\n\nLeft division operator: multiplication of y by the inverse of x on the left. Gives floating-point results for integer arguments.\n\njulia> 3 \\ 6\n2.0\n\njulia> inv(3) * 6\n2.0\n\njulia> A = [1 2; 3 4]; x = [5, 6];\n\njulia> A \\ x\n2-element Array{Float64,1}:\n -4.0\n 4.5\n\njulia> inv(A) * x\n2-element Array{Float64,1}:\n -4.0\n 4.5\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.:^-Tuple{Number,Number}", - "page": "Mathematics", - "title": "Base.:^", - "category": "method", - "text": "^(x, y)\n\nExponentiation operator. If x is a matrix, computes matrix exponentiation.\n\nIf y is an Int literal (e.g. 2 in x^2 or -3 in x^-3), the Julia code x^y is transformed by the compiler to Base.literal_pow(^, x, Val{y}), to enable compile-time specialization on the value of the exponent. (As a default fallback we have Base.literal_pow(^, x, Val{y}) = ^(x,y), where usually ^ == Base.^ unless ^ has been defined in the calling namespace.)\n\njulia> 3^5\n243\n\njulia> A = [1 2; 3 4]\n2×2 Array{Int64,2}:\n 1 2\n 3 4\n\njulia> A^3\n2×2 Array{Int64,2}:\n 37 54\n 81 118\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.fma", - "page": "Mathematics", - "title": "Base.fma", - "category": "function", - "text": "fma(x, y, z)\n\nComputes x*y+z without rounding the intermediate result x*y. On some systems this is significantly more expensive than x*y+z. fma is used to improve accuracy in certain algorithms. See muladd.\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.muladd", - "page": "Mathematics", - "title": "Base.muladd", - "category": "function", - "text": "muladd(x, y, z)\n\nCombined multiply-add, computes x*y+z in an efficient manner. This may on some systems be equivalent to x*y+z, or to fma(x,y,z). muladd is used to improve performance. See fma.\n\nExample\n\njulia> muladd(3, 2, 1)\n7\n\njulia> 3 * 2 + 1\n7\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.div", - "page": "Mathematics", - "title": "Base.div", - "category": "function", - "text": "div(x, y)\n÷(x, y)\n\nThe quotient from Euclidean division. Computes x/y, truncated to an integer.\n\njulia> 9 ÷ 4\n2\n\njulia> -5 ÷ 3\n-1\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.fld", - "page": "Mathematics", - "title": "Base.fld", - "category": "function", - "text": "fld(x, y)\n\nLargest integer less than or equal to x/y.\n\njulia> fld(7.3,5.5)\n1.0\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.cld", - "page": "Mathematics", - "title": "Base.cld", - "category": "function", - "text": "cld(x, y)\n\nSmallest integer larger than or equal to x/y.\n\njulia> cld(5.5,2.2)\n3.0\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.mod", - "page": "Mathematics", - "title": "Base.mod", - "category": "function", - "text": "mod(x, y)\nrem(x, y, RoundDown)\n\nThe reduction of x modulo y, or equivalently, the remainder of x after floored division by y, i.e.\n\nx - y*fld(x,y)\n\nif computed without intermediate rounding.\n\nThe result will have the same sign as y, and magnitude less than abs(y) (with some exceptions, see note below).\n\nnote: Note\nWhen used with floating point values, the exact result may not be representable by the type, and so rounding error may occur. In particular, if the exact result is very close to y, then it may be rounded to y.\n\njulia> mod(8, 3)\n2\n\njulia> mod(9, 3)\n0\n\njulia> mod(8.9, 3)\n2.9000000000000004\n\njulia> mod(eps(), 3)\n2.220446049250313e-16\n\njulia> mod(-eps(), 3)\n3.0\n\n\n\nrem(x::Integer, T::Type{<:Integer}) -> T\nmod(x::Integer, T::Type{<:Integer}) -> T\n%(x::Integer, T::Type{<:Integer}) -> T\n\nFind y::T such that x ≡ y (mod n), where n is the number of integers representable in T, and y is an integer in [typemin(T),typemax(T)]. If T can represent any integer (e.g. T == BigInt), then this operation corresponds to a conversion to T.\n\njulia> 129 % Int8\n-127\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.rem", - "page": "Mathematics", - "title": "Base.rem", - "category": "function", - "text": "rem(x, y)\n%(x, y)\n\nRemainder from Euclidean division, returning a value of the same sign as x, and smaller in magnitude than y. This value is always exact.\n\njulia> x = 15; y = 4;\n\njulia> x % y\n3\n\njulia> x == div(x, y) * y + rem(x, y)\ntrue\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.Math.rem2pi", - "page": "Mathematics", - "title": "Base.Math.rem2pi", - "category": "function", - "text": "rem2pi(x, r::RoundingMode)\n\nCompute the remainder of x after integer division by 2π, with the quotient rounded according to the rounding mode r. In other words, the quantity\n\nx - 2π*round(x/(2π),r)\n\nwithout any intermediate rounding. This internally uses a high precision approximation of 2π, and so will give a more accurate result than rem(x,2π,r)\n\nif r == RoundNearest, then the result is in the interval - . This will generally be the most accurate result.\nif r == RoundToZero, then the result is in the interval 0 2 if x is positive,. or -2 0 otherwise.\nif r == RoundDown, then the result is in the interval 0 2.\nif r == RoundUp, then the result is in the interval -2 0.\n\nExample\n\njulia> rem2pi(7pi/4, RoundNearest)\n-0.7853981633974485\n\njulia> rem2pi(7pi/4, RoundDown)\n5.497787143782138\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.Math.mod2pi", - "page": "Mathematics", - "title": "Base.Math.mod2pi", - "category": "function", - "text": "mod2pi(x)\n\nModulus after division by 2π, returning in the range 02).\n\nThis function computes a floating point representation of the modulus after division by numerically exact 2π, and is therefore not exactly the same as mod(x,2π), which would compute the modulus of x relative to division by the floating-point number 2π.\n\nExample\n\njulia> mod2pi(9*pi/4)\n0.7853981633974481\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.divrem", - "page": "Mathematics", - "title": "Base.divrem", - "category": "function", - "text": "divrem(x, y)\n\nThe quotient and remainder from Euclidean division. Equivalent to (div(x,y), rem(x,y)) or (x÷y, x%y).\n\njulia> divrem(3,7)\n(0, 3)\n\njulia> divrem(7,3)\n(2, 1)\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.fldmod", - "page": "Mathematics", - "title": "Base.fldmod", - "category": "function", - "text": "fldmod(x, y)\n\nThe floored quotient and modulus after division. Equivalent to (fld(x,y), mod(x,y)).\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.fld1", - "page": "Mathematics", - "title": "Base.fld1", - "category": "function", - "text": "fld1(x, y)\n\nFlooring division, returning a value consistent with mod1(x,y)\n\nSee also: mod1.\n\njulia> x = 15; y = 4;\n\njulia> fld1(x, y)\n4\n\njulia> x == fld(x, y) * y + mod(x, y)\ntrue\n\njulia> x == (fld1(x, y) - 1) * y + mod1(x, y)\ntrue\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.mod1", - "page": "Mathematics", - "title": "Base.mod1", - "category": "function", - "text": "mod1(x, y)\n\nModulus after flooring division, returning a value r such that mod(r, y) == mod(x, y) in the range (0 y for positive y and in the range y0) for negative y.\n\njulia> mod1(4, 2)\n2\n\njulia> mod1(4, 3)\n1\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.fldmod1", - "page": "Mathematics", - "title": "Base.fldmod1", - "category": "function", - "text": "fldmod1(x, y)\n\nReturn (fld1(x,y), mod1(x,y)).\n\nSee also: fld1, mod1.\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.://", - "page": "Mathematics", - "title": "Base.://", - "category": "function", - "text": "//(num, den)\n\nDivide two integers or rational numbers, giving a Rational result.\n\njulia> 3 // 5\n3//5\n\njulia> (3 // 5) // (2 // 1)\n3//10\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.rationalize", - "page": "Mathematics", - "title": "Base.rationalize", - "category": "function", - "text": "rationalize([T<:Integer=Int,] x; tol::Real=eps(x))\n\nApproximate floating point number x as a Rational number with components of the given integer type. The result will differ from x by no more than tol. If T is not provided, it defaults to Int.\n\njulia> rationalize(5.6)\n28//5\n\njulia> a = rationalize(BigInt, 10.3)\n103//10\n\njulia> typeof(numerator(a))\nBigInt\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.numerator", - "page": "Mathematics", - "title": "Base.numerator", - "category": "function", - "text": "numerator(x)\n\nNumerator of the rational representation of x.\n\njulia> numerator(2//3)\n2\n\njulia> numerator(4)\n4\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.denominator", - "page": "Mathematics", - "title": "Base.denominator", - "category": "function", - "text": "denominator(x)\n\nDenominator of the rational representation of x.\n\njulia> denominator(2//3)\n3\n\njulia> denominator(4)\n1\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.:<<", - "page": "Mathematics", - "title": "Base.:<<", - "category": "function", - "text": "<<(x, n)\n\nLeft bit shift operator, x << n. For n >= 0, the result is x shifted left by n bits, filling with 0s. This is equivalent to x * 2^n. For n < 0, this is equivalent to x >> -n.\n\njulia> Int8(3) << 2\n12\n\njulia> bits(Int8(3))\n\"00000011\"\n\njulia> bits(Int8(12))\n\"00001100\"\n\nSee also >>, >>>.\n\n\n\n<<(B::BitVector, n) -> BitVector\n\nLeft bit shift operator, B << n. For n >= 0, the result is B with elements shifted n positions backwards, filling with false values. If n < 0, elements are shifted forwards. Equivalent to B >> -n.\n\nExamples\n\njulia> B = BitVector([true, false, true, false, false])\n5-element BitArray{1}:\n true\n false\n true\n false\n false\n\njulia> B << 1\n5-element BitArray{1}:\n false\n true\n false\n false\n false\n\njulia> B << -1\n5-element BitArray{1}:\n false\n true\n false\n true\n false\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.:>>", - "page": "Mathematics", - "title": "Base.:>>", - "category": "function", - "text": ">>(x, n)\n\nRight bit shift operator, x >> n. For n >= 0, the result is x shifted right by n bits, where n >= 0, filling with 0s if x >= 0, 1s if x < 0, preserving the sign of x. This is equivalent to fld(x, 2^n). For n < 0, this is equivalent to x << -n.\n\njulia> Int8(13) >> 2\n3\n\njulia> bits(Int8(13))\n\"00001101\"\n\njulia> bits(Int8(3))\n\"00000011\"\n\njulia> Int8(-14) >> 2\n-4\n\njulia> bits(Int8(-14))\n\"11110010\"\n\njulia> bits(Int8(-4))\n\"11111100\"\n\nSee also >>>, <<.\n\n\n\n>>(B::BitVector, n) -> BitVector\n\nRight bit shift operator, B >> n. For n >= 0, the result is B with elements shifted n positions forward, filling with false values. If n < 0, elements are shifted backwards. Equivalent to B << -n.\n\nExample\n\njulia> B = BitVector([true, false, true, false, false])\n5-element BitArray{1}:\n true\n false\n true\n false\n false\n\njulia> B >> 1\n5-element BitArray{1}:\n false\n true\n false\n true\n false\n\njulia> B >> -1\n5-element BitArray{1}:\n false\n true\n false\n false\n false\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.:>>>", - "page": "Mathematics", - "title": "Base.:>>>", - "category": "function", - "text": ">>>(x, n)\n\nUnsigned right bit shift operator, x >>> n. For n >= 0, the result is x shifted right by n bits, where n >= 0, filling with 0s. For n < 0, this is equivalent to x << -n.\n\nFor Unsigned integer types, this is equivalent to >>. For Signed integer types, this is equivalent to signed(unsigned(x) >> n).\n\njulia> Int8(-14) >>> 2\n60\n\njulia> bits(Int8(-14))\n\"11110010\"\n\njulia> bits(Int8(60))\n\"00111100\"\n\nBigInts are treated as if having infinite size, so no filling is required and this is equivalent to >>.\n\nSee also >>, <<.\n\n\n\n>>>(B::BitVector, n) -> BitVector\n\nUnsigned right bitshift operator, B >>> n. Equivalent to B >> n. See >> for details and examples.\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.colon", - "page": "Mathematics", - "title": "Base.colon", - "category": "function", - "text": "colon(start, [step], stop)\n\nCalled by : syntax for constructing ranges.\n\njulia> colon(1, 2, 5)\n1:2:5\n\n\n\n:(start, [step], stop)\n\nRange operator. a:b constructs a range from a to b with a step size of 1, and a:s:b is similar but uses a step size of s. These syntaxes call the function colon. The colon is also used in indexing to select whole dimensions.\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.range", - "page": "Mathematics", - "title": "Base.range", - "category": "function", - "text": "range(start, [step], length)\n\nConstruct a range by length, given a starting value and optional step (defaults to 1).\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.OneTo", - "page": "Mathematics", - "title": "Base.OneTo", - "category": "type", - "text": "Base.OneTo(n)\n\nDefine an AbstractUnitRange that behaves like 1:n, with the added distinction that the lower limit is guaranteed (by the type system) to be 1.\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.StepRangeLen", - "page": "Mathematics", - "title": "Base.StepRangeLen", - "category": "type", - "text": "StepRangeLen{T,R,S}(ref::R, step::S, len, [offset=1])\n\nA range r where r[i] produces values of type T, parametrized by a reference value, a step, and the length. By default ref is the starting value r[1], but alternatively you can supply it as the value of r[offset] for some other index 1 <= offset <= len. In conjunction with TwicePrecision this can be used to implement ranges that are free of roundoff error.\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.:==", - "page": "Mathematics", - "title": "Base.:==", - "category": "function", - "text": "==(x, y)\n\nGeneric equality operator, giving a single Bool result. Falls back to ===. Should be implemented for all types with a notion of equality, based on the abstract value that an instance represents. For example, all numeric types are compared by numeric value, ignoring type. Strings are compared as sequences of characters, ignoring encoding.\n\nFollows IEEE semantics for floating-point numbers.\n\nCollections should generally implement == by calling == recursively on all contents.\n\nNew numeric types should implement this function for two arguments of the new type, and handle comparison to other types via promotion rules where possible.\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.:!=", - "page": "Mathematics", - "title": "Base.:!=", - "category": "function", - "text": "!=(x, y)\n≠(x,y)\n\nNot-equals comparison operator. Always gives the opposite answer as ==. New types should generally not implement this, and rely on the fallback definition !=(x,y) = !(x==y) instead.\n\njulia> 3 != 2\ntrue\n\njulia> \"foo\" ≠ \"foo\"\nfalse\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.:!==", - "page": "Mathematics", - "title": "Base.:!==", - "category": "function", - "text": "!==(x, y)\n≢(x,y)\n\nEquivalent to !(x === y).\n\njulia> a = [1, 2]; b = [1, 2];\n\njulia> a ≢ b\ntrue\n\njulia> a ≢ a\nfalse\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.:<", - "page": "Mathematics", - "title": "Base.:<", - "category": "function", - "text": "<(x, y)\n\nLess-than comparison operator. New numeric types should implement this function for two arguments of the new type. Because of the behavior of floating-point NaN values, < implements a partial order. Types with a canonical partial order should implement <, and types with a canonical total order should implement isless.\n\njulia> \'a\' < \'b\'\ntrue\n\njulia> \"abc\" < \"abd\"\ntrue\n\njulia> 5 < 3\nfalse\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.:<=", - "page": "Mathematics", - "title": "Base.:<=", - "category": "function", - "text": "<=(x, y)\n≤(x,y)\n\nLess-than-or-equals comparison operator.\n\njulia> \'a\' <= \'b\'\ntrue\n\njulia> 7 ≤ 7 ≤ 9\ntrue\n\njulia> \"abc\" ≤ \"abc\"\ntrue\n\njulia> 5 <= 3\nfalse\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.:>", - "page": "Mathematics", - "title": "Base.:>", - "category": "function", - "text": ">(x, y)\n\nGreater-than comparison operator. Generally, new types should implement < instead of this function, and rely on the fallback definition >(x, y) = y < x.\n\njulia> \'a\' > \'b\'\nfalse\n\njulia> 7 > 3 > 1\ntrue\n\njulia> \"abc\" > \"abd\"\nfalse\n\njulia> 5 > 3\ntrue\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.:>=", - "page": "Mathematics", - "title": "Base.:>=", - "category": "function", - "text": ">=(x, y)\n≥(x,y)\n\nGreater-than-or-equals comparison operator.\n\njulia> \'a\' >= \'b\'\nfalse\n\njulia> 7 ≥ 7 ≥ 3\ntrue\n\njulia> \"abc\" ≥ \"abc\"\ntrue\n\njulia> 5 >= 3\ntrue\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.cmp", - "page": "Mathematics", - "title": "Base.cmp", - "category": "function", - "text": "cmp(x,y)\n\nReturn -1, 0, or 1 depending on whether x is less than, equal to, or greater than y, respectively. Uses the total order implemented by isless. For floating-point numbers, uses < but throws an error for unordered arguments.\n\njulia> cmp(1, 2)\n-1\n\njulia> cmp(2, 1)\n1\n\njulia> cmp(2+im, 3-im)\nERROR: MethodError: no method matching isless(::Complex{Int64}, ::Complex{Int64})\n[...]\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.:~", - "page": "Mathematics", - "title": "Base.:~", - "category": "function", - "text": "~(x)\n\nBitwise not.\n\nExamples\n\njulia> ~4\n-5\n\njulia> ~10\n-11\n\njulia> ~true\nfalse\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.:&", - "page": "Mathematics", - "title": "Base.:&", - "category": "function", - "text": "&(x, y)\n\nBitwise and.\n\nExamples\n\njulia> 4 & 10\n0\n\njulia> 4 & 12\n4\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.:|", - "page": "Mathematics", - "title": "Base.:|", - "category": "function", - "text": "|(x, y)\n\nBitwise or.\n\nExamples\n\njulia> 4 | 10\n14\n\njulia> 4 | 1\n5\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.xor", - "page": "Mathematics", - "title": "Base.xor", - "category": "function", - "text": "xor(x, y)\n⊻(x, y)\n\nBitwise exclusive or of x and y. The infix operation a ⊻ b is a synonym for xor(a,b), and ⊻ can be typed by tab-completing \\xor or \\veebar in the Julia REPL.\n\njulia> [true; true; false] .⊻ [true; false; false]\n3-element BitArray{1}:\n false\n true\n false\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.:!", - "page": "Mathematics", - "title": "Base.:!", - "category": "function", - "text": "!(x)\n\nBoolean not.\n\njulia> !true\nfalse\n\njulia> !false\ntrue\n\njulia> .![true false true]\n1×3 BitArray{2}:\n false true false\n\n\n\n!f::Function\n\nPredicate function negation: when the argument of ! is a function, it returns a function which computes the boolean negation of f. Example:\n\njulia> str = \"∀ ε > 0, ∃ δ > 0: |x-y| < δ ⇒ |f(x)-f(y)| < ε\"\n\"∀ ε > 0, ∃ δ > 0: |x-y| < δ ⇒ |f(x)-f(y)| < ε\"\n\njulia> filter(isalpha, str)\n\"εδxyδfxfyε\"\n\njulia> filter(!isalpha, str)\n\"∀ > 0, ∃ > 0: |-| < ⇒ |()-()| < \"\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#&&", - "page": "Mathematics", - "title": "&&", - "category": "keyword", - "text": "x && y\n\nShort-circuiting boolean AND.\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#||", - "page": "Mathematics", - "title": "||", - "category": "keyword", - "text": "x || y\n\nShort-circuiting boolean OR.\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#math-ops-1", - "page": "Mathematics", - "title": "Mathematical Operators", - "category": "section", - "text": "Base.:-(::Any)\nBase.:(+)\nBase.:-(::Any, ::Any)\nBase.:*(::Any, ::Any...)\nBase.:(/)\nBase.:\\(::Any, ::Any)\nBase.:^(::Number, ::Number)\nBase.fma\nBase.muladd\nBase.div\nBase.fld\nBase.cld\nBase.mod\nBase.rem\nBase.rem2pi\nBase.Math.mod2pi\nBase.divrem\nBase.fldmod\nBase.fld1\nBase.mod1\nBase.fldmod1\nBase.:(//)\nBase.rationalize\nBase.numerator\nBase.denominator\nBase.:(<<)\nBase.:(>>)\nBase.:(>>>)\nBase.colon\nBase.range\nBase.OneTo\nBase.StepRangeLen\nBase.:(==)\nBase.:(!=)\nBase.:(!==)\nBase.:(<)\nBase.:(<=)\nBase.:(>)\nBase.:(>=)\nBase.cmp\nBase.:(~)\nBase.:(&)\nBase.:(|)\nBase.xor\nBase.:(!)\n&&\n||" -}, - -{ - "location": "stdlib/math.html#Base.isapprox", - "page": "Mathematics", - "title": "Base.isapprox", - "category": "function", - "text": "isapprox(x, y; rtol::Real=sqrt(eps), atol::Real=0, nans::Bool=false, norm::Function)\n\nInexact equality comparison: true if norm(x-y) <= atol + rtol*max(norm(x), norm(y)). The default atol is zero and the default rtol depends on the types of x and y. The keyword argument nans determines whether or not NaN values are considered equal (defaults to false).\n\nFor real or complex floating-point values, rtol defaults to sqrt(eps(typeof(real(x-y)))). This corresponds to requiring equality of about half of the significand digits. For other types, rtol defaults to zero.\n\nx and y may also be arrays of numbers, in which case norm defaults to vecnorm but may be changed by passing a norm::Function keyword argument. (For numbers, norm is the same thing as abs.) When x and y are arrays, if norm(x-y) is not finite (i.e. ±Inf or NaN), the comparison falls back to checking whether all elements of x and y are approximately equal component-wise.\n\nThe binary operator ≈ is equivalent to isapprox with the default arguments, and x ≉ y is equivalent to !isapprox(x,y).\n\njulia> 0.1 ≈ (0.1 - 1e-10)\ntrue\n\njulia> isapprox(10, 11; atol = 2)\ntrue\n\njulia> isapprox([10.0^9, 1.0], [10.0^9, 2.0])\ntrue\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.sin", - "page": "Mathematics", - "title": "Base.sin", - "category": "function", - "text": "sin(x)\n\nCompute sine of x, where x is in radians.\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.cos", - "page": "Mathematics", - "title": "Base.cos", - "category": "function", - "text": "cos(x)\n\nCompute cosine of x, where x is in radians.\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.tan", - "page": "Mathematics", - "title": "Base.tan", - "category": "function", - "text": "tan(x)\n\nCompute tangent of x, where x is in radians.\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.Math.sind", - "page": "Mathematics", - "title": "Base.Math.sind", - "category": "function", - "text": "sind(x)\n\nCompute sine of x, where x is in degrees. \n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.Math.cosd", - "page": "Mathematics", - "title": "Base.Math.cosd", - "category": "function", - "text": "cosd(x)\n\nCompute cosine of x, where x is in degrees. \n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.Math.tand", - "page": "Mathematics", - "title": "Base.Math.tand", - "category": "function", - "text": "tand(x)\n\nCompute tangent of x, where x is in degrees. \n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.Math.sinpi", - "page": "Mathematics", - "title": "Base.Math.sinpi", - "category": "function", - "text": "sinpi(x)\n\nCompute sin(pi x) more accurately than sin(pi*x), especially for large x.\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.Math.cospi", - "page": "Mathematics", - "title": "Base.Math.cospi", - "category": "function", - "text": "cospi(x)\n\nCompute cos(pi x) more accurately than cos(pi*x), especially for large x.\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.sinh", - "page": "Mathematics", - "title": "Base.sinh", - "category": "function", - "text": "sinh(x)\n\nCompute hyperbolic sine of x.\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.cosh", - "page": "Mathematics", - "title": "Base.cosh", - "category": "function", - "text": "cosh(x)\n\nCompute hyperbolic cosine of x.\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.tanh", - "page": "Mathematics", - "title": "Base.tanh", - "category": "function", - "text": "tanh(x)\n\nCompute hyperbolic tangent of x.\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.asin", - "page": "Mathematics", - "title": "Base.asin", - "category": "function", - "text": "asin(x)\n\nCompute the inverse sine of x, where the output is in radians.\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.acos", - "page": "Mathematics", - "title": "Base.acos", - "category": "function", - "text": "acos(x)\n\nCompute the inverse cosine of x, where the output is in radians\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.atan", - "page": "Mathematics", - "title": "Base.atan", - "category": "function", - "text": "atan(x)\n\nCompute the inverse tangent of x, where the output is in radians.\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.Math.atan2", - "page": "Mathematics", - "title": "Base.Math.atan2", - "category": "function", - "text": "atan2(y, x)\n\nCompute the inverse tangent of y/x, using the signs of both x and y to determine the quadrant of the return value.\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.Math.asind", - "page": "Mathematics", - "title": "Base.Math.asind", - "category": "function", - "text": "asind(x)\n\nCompute the inverse sine of x, where the output is in degrees. \n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.Math.acosd", - "page": "Mathematics", - "title": "Base.Math.acosd", - "category": "function", - "text": "acosd(x)\n\nCompute the inverse cosine of x, where the output is in degrees. \n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.Math.atand", - "page": "Mathematics", - "title": "Base.Math.atand", - "category": "function", - "text": "atand(x)\n\nCompute the inverse tangent of x, where the output is in degrees. \n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.Math.sec", - "page": "Mathematics", - "title": "Base.Math.sec", - "category": "function", - "text": "sec(x)\n\nCompute the secant of x, where x is in radians.\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.Math.csc", - "page": "Mathematics", - "title": "Base.Math.csc", - "category": "function", - "text": "csc(x)\n\nCompute the cosecant of x, where x is in radians.\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.Math.cot", - "page": "Mathematics", - "title": "Base.Math.cot", - "category": "function", - "text": "cot(x)\n\nCompute the cotangent of x, where x is in radians.\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.Math.secd", - "page": "Mathematics", - "title": "Base.Math.secd", - "category": "function", - "text": "secd(x)\n\nCompute the secant of x, where x is in degrees.\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.Math.cscd", - "page": "Mathematics", - "title": "Base.Math.cscd", - "category": "function", - "text": "cscd(x)\n\nCompute the cosecant of x, where x is in degrees.\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.Math.cotd", - "page": "Mathematics", - "title": "Base.Math.cotd", - "category": "function", - "text": "cotd(x)\n\nCompute the cotangent of x, where x is in degrees.\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.Math.asec", - "page": "Mathematics", - "title": "Base.Math.asec", - "category": "function", - "text": "asec(x)\n\nCompute the inverse secant of x, where the output is in radians. \n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.Math.acsc", - "page": "Mathematics", - "title": "Base.Math.acsc", - "category": "function", - "text": "acsc(x)\n\nCompute the inverse cosecant of x, where the output is in radians. \n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.Math.acot", - "page": "Mathematics", - "title": "Base.Math.acot", - "category": "function", - "text": "acot(x)\n\nCompute the inverse cotangent of x, where the output is in radians. \n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.Math.asecd", - "page": "Mathematics", - "title": "Base.Math.asecd", - "category": "function", - "text": "asecd(x)\n\nCompute the inverse secant of x, where the output is in degrees. \n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.Math.acscd", - "page": "Mathematics", - "title": "Base.Math.acscd", - "category": "function", - "text": "acscd(x)\n\nCompute the inverse cosecant of x, where the output is in degrees. \n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.Math.acotd", - "page": "Mathematics", - "title": "Base.Math.acotd", - "category": "function", - "text": "acotd(x)\n\nCompute the inverse cotangent of x, where the output is in degrees. \n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.Math.sech", - "page": "Mathematics", - "title": "Base.Math.sech", - "category": "function", - "text": "sech(x)\n\nCompute the hyperbolic secant of x\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.Math.csch", - "page": "Mathematics", - "title": "Base.Math.csch", - "category": "function", - "text": "csch(x)\n\nCompute the hyperbolic cosecant of x.\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.Math.coth", - "page": "Mathematics", - "title": "Base.Math.coth", - "category": "function", - "text": "coth(x)\n\nCompute the hyperbolic cotangent of x.\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.asinh", - "page": "Mathematics", - "title": "Base.asinh", - "category": "function", - "text": "asinh(x)\n\nCompute the inverse hyperbolic sine of x.\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.acosh", - "page": "Mathematics", - "title": "Base.acosh", - "category": "function", - "text": "acosh(x)\n\nCompute the inverse hyperbolic cosine of x.\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.atanh", - "page": "Mathematics", - "title": "Base.atanh", - "category": "function", - "text": "atanh(x)\n\nCompute the inverse hyperbolic tangent of x.\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.Math.asech", - "page": "Mathematics", - "title": "Base.Math.asech", - "category": "function", - "text": "asech(x)\n\nCompute the inverse hyperbolic secant of x. \n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.Math.acsch", - "page": "Mathematics", - "title": "Base.Math.acsch", - "category": "function", - "text": "acsch(x)\n\nCompute the inverse hyperbolic cosecant of x. \n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.Math.acoth", - "page": "Mathematics", - "title": "Base.Math.acoth", - "category": "function", - "text": "acoth(x)\n\nCompute the inverse hyperbolic cotangent of x. \n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.Math.sinc", - "page": "Mathematics", - "title": "Base.Math.sinc", - "category": "function", - "text": "sinc(x)\n\nCompute sin(pi x) (pi x) if x neq 0, and 1 if x = 0.\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.Math.cosc", - "page": "Mathematics", - "title": "Base.Math.cosc", - "category": "function", - "text": "cosc(x)\n\nCompute cos(pi x) x - sin(pi x) (pi x^2) if x neq 0, and 0 if x = 0. This is the derivative of sinc(x).\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.Math.deg2rad", - "page": "Mathematics", - "title": "Base.Math.deg2rad", - "category": "function", - "text": "deg2rad(x)\n\nConvert x from degrees to radians.\n\njulia> deg2rad(90)\n1.5707963267948966\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.Math.rad2deg", - "page": "Mathematics", - "title": "Base.Math.rad2deg", - "category": "function", - "text": "rad2deg(x)\n\nConvert x from radians to degrees.\n\njulia> rad2deg(pi)\n180.0\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.Math.hypot", - "page": "Mathematics", - "title": "Base.Math.hypot", - "category": "function", - "text": "hypot(x, y)\n\nCompute the hypotenuse sqrtx^2+y^2 avoiding overflow and underflow.\n\nExamples\n\njulia> a = 10^10;\n\njulia> hypot(a, a)\n1.4142135623730951e10\n\njulia> √(a^2 + a^2) # a^2 overflows\nERROR: DomainError:\nsqrt will only return a complex result if called with a complex argument. Try sqrt(complex(x)).\nStacktrace:\n [1] sqrt(::Int64) at ./math.jl:434\n\n\n\nhypot(x...)\n\nCompute the hypotenuse sqrtsum x_i^2 avoiding overflow and underflow.\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.log-Tuple{Any}", - "page": "Mathematics", - "title": "Base.log", - "category": "method", - "text": "log(x)\n\nCompute the natural logarithm of x. Throws DomainError for negative Real arguments. Use complex negative arguments to obtain complex results.\n\nThere is an experimental variant in the Base.Math.JuliaLibm module, which is typically faster and more accurate.\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.log-Tuple{Number,Number}", - "page": "Mathematics", - "title": "Base.log", - "category": "method", - "text": "log(b,x)\n\nCompute the base b logarithm of x. Throws DomainError for negative Real arguments.\n\njulia> log(4,8)\n1.5\n\njulia> log(4,2)\n0.5\n\nnote: Note\nIf b is a power of 2 or 10, log2 or log10 should be used, as these will typically be faster and more accurate. For example,julia> log(100,1000000)\n2.9999999999999996\n\njulia> log10(1000000)/2\n3.0\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.log2", - "page": "Mathematics", - "title": "Base.log2", - "category": "function", - "text": "log2(x)\n\nCompute the logarithm of x to base 2. Throws DomainError for negative Real arguments.\n\nExample\n\njulia> log2(4)\n2.0\n\njulia> log2(10)\n3.321928094887362\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.log10", - "page": "Mathematics", - "title": "Base.log10", - "category": "function", - "text": "log10(x)\n\nCompute the logarithm of x to base 10. Throws DomainError for negative Real arguments.\n\nExample\n\njulia> log10(100)\n2.0\n\njulia> log10(2)\n0.3010299956639812\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.log1p", - "page": "Mathematics", - "title": "Base.log1p", - "category": "function", - "text": "log1p(x)\n\nAccurate natural logarithm of 1+x. Throws DomainError for Real arguments less than -1.\n\nThere is an experimental variant in the Base.Math.JuliaLibm module, which is typically faster and more accurate.\n\nExamples\n\njulia> log1p(-0.5)\n-0.6931471805599453\n\njulia> log1p(0)\n0.0\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.Math.frexp", - "page": "Mathematics", - "title": "Base.Math.frexp", - "category": "function", - "text": "frexp(val)\n\nReturn (x,exp) such that x has a magnitude in the interval 12 1) or 0, and val is equal to x times 2^exp.\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.exp", - "page": "Mathematics", - "title": "Base.exp", - "category": "function", - "text": "exp(x)\n\nCompute the natural base exponential of x, in other words e^x.\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.exp2", - "page": "Mathematics", - "title": "Base.exp2", - "category": "function", - "text": "exp2(x)\n\nCompute 2^x.\n\njulia> exp2(5)\n32.0\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.exp10", - "page": "Mathematics", - "title": "Base.exp10", - "category": "function", - "text": "exp10(x)\n\nCompute 10^x.\n\nExamples\n\njulia> exp10(2)\n100.0\n\njulia> exp10(0.2)\n1.5848931924611136\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.Math.ldexp", - "page": "Mathematics", - "title": "Base.Math.ldexp", - "category": "function", - "text": "ldexp(x, n)\n\nCompute x times 2^n.\n\nExample\n\njulia> ldexp(5., 2)\n20.0\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.Math.modf", - "page": "Mathematics", - "title": "Base.Math.modf", - "category": "function", - "text": "modf(x)\n\nReturn a tuple (fpart,ipart) of the fractional and integral parts of a number. Both parts have the same sign as the argument.\n\nExample\n\njulia> modf(3.5)\n(0.5, 3.0)\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.expm1", - "page": "Mathematics", - "title": "Base.expm1", - "category": "function", - "text": "expm1(x)\n\nAccurately compute e^x-1.\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.round-Tuple{Type,Any}", - "page": "Mathematics", - "title": "Base.round", - "category": "method", - "text": "round([T,] x, [digits, [base]], [r::RoundingMode])\n\nRounds x to an integer value according to the provided RoundingMode, returning a value of the same type as x. When not specifying a rounding mode the global mode will be used (see rounding), which by default is round to the nearest integer (RoundNearest mode), with ties (fractional values of 0.5) being rounded to the nearest even integer.\n\njulia> round(1.7)\n2.0\n\njulia> round(1.5)\n2.0\n\njulia> round(2.5)\n2.0\n\nThe optional RoundingMode argument will change how the number gets rounded.\n\nround(T, x, [r::RoundingMode]) converts the result to type T, throwing an InexactError if the value is not representable.\n\nround(x, digits) rounds to the specified number of digits after the decimal place (or before if negative). round(x, digits, base) rounds using a base other than 10.\n\njulia> round(pi, 2)\n3.14\n\njulia> round(pi, 3, 2)\n3.125\n\nnote: Note\nRounding to specified digits in bases other than 2 can be inexact when operating on binary floating point numbers. For example, the Float64 value represented by 1.15 is actually less than 1.15, yet will be rounded to 1.2.julia> x = 1.15\n1.15\n\njulia> @sprintf \"%.20f\" x\n\"1.14999999999999991118\"\n\njulia> x < 115//100\ntrue\n\njulia> round(x, 1)\n1.2\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.Rounding.RoundingMode", - "page": "Mathematics", - "title": "Base.Rounding.RoundingMode", - "category": "type", - "text": "RoundingMode\n\nA type used for controlling the rounding mode of floating point operations (via rounding/setrounding functions), or as optional arguments for rounding to the nearest integer (via the round function).\n\nCurrently supported rounding modes are:\n\nRoundNearest (default)\nRoundNearestTiesAway\nRoundNearestTiesUp\nRoundToZero\nRoundFromZero (BigFloat only)\nRoundUp\nRoundDown\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.Rounding.RoundNearest", - "page": "Mathematics", - "title": "Base.Rounding.RoundNearest", - "category": "constant", - "text": "RoundNearest\n\nThe default rounding mode. Rounds to the nearest integer, with ties (fractional values of 0.5) being rounded to the nearest even integer.\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.Rounding.RoundNearestTiesAway", - "page": "Mathematics", - "title": "Base.Rounding.RoundNearestTiesAway", - "category": "constant", - "text": "RoundNearestTiesAway\n\nRounds to nearest integer, with ties rounded away from zero (C/C++ round behaviour).\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.Rounding.RoundNearestTiesUp", - "page": "Mathematics", - "title": "Base.Rounding.RoundNearestTiesUp", - "category": "constant", - "text": "RoundNearestTiesUp\n\nRounds to nearest integer, with ties rounded toward positive infinity (Java/JavaScript round behaviour).\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.Rounding.RoundToZero", - "page": "Mathematics", - "title": "Base.Rounding.RoundToZero", - "category": "constant", - "text": "RoundToZero\n\nround using this rounding mode is an alias for trunc.\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.Rounding.RoundUp", - "page": "Mathematics", - "title": "Base.Rounding.RoundUp", - "category": "constant", - "text": "RoundUp\n\nround using this rounding mode is an alias for ceil.\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.Rounding.RoundDown", - "page": "Mathematics", - "title": "Base.Rounding.RoundDown", - "category": "constant", - "text": "RoundDown\n\nround using this rounding mode is an alias for floor.\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.round-Union{Tuple{Complex{T},RoundingMode{MR},RoundingMode{MI}}, Tuple{MI}, Tuple{MR}, Tuple{T}} where MI where MR where T<:AbstractFloat", - "page": "Mathematics", - "title": "Base.round", - "category": "method", - "text": "round(z, RoundingModeReal, RoundingModeImaginary)\n\nReturns the nearest integral value of the same type as the complex-valued z to z, breaking ties using the specified RoundingModes. The first RoundingMode is used for rounding the real components while the second is used for rounding the imaginary components.\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.ceil", - "page": "Mathematics", - "title": "Base.ceil", - "category": "function", - "text": "ceil([T,] x, [digits, [base]])\n\nceil(x) returns the nearest integral value of the same type as x that is greater than or equal to x.\n\nceil(T, x) converts the result to type T, throwing an InexactError if the value is not representable.\n\ndigits and base work as for round.\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.floor", - "page": "Mathematics", - "title": "Base.floor", - "category": "function", - "text": "floor([T,] x, [digits, [base]])\n\nfloor(x) returns the nearest integral value of the same type as x that is less than or equal to x.\n\nfloor(T, x) converts the result to type T, throwing an InexactError if the value is not representable.\n\ndigits and base work as for round.\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.trunc", - "page": "Mathematics", - "title": "Base.trunc", - "category": "function", - "text": "trunc([T,] x, [digits, [base]])\n\ntrunc(x) returns the nearest integral value of the same type as x whose absolute value is less than or equal to x.\n\ntrunc(T, x) converts the result to type T, throwing an InexactError if the value is not representable.\n\ndigits and base work as for round.\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.unsafe_trunc", - "page": "Mathematics", - "title": "Base.unsafe_trunc", - "category": "function", - "text": "unsafe_trunc(T, x)\n\nunsafe_trunc(T, x) returns the nearest integral value of type T whose absolute value is less than or equal to x. If the value is not representable by T, an arbitrary value will be returned.\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.signif", - "page": "Mathematics", - "title": "Base.signif", - "category": "function", - "text": "signif(x, digits, [base])\n\nRounds (in the sense of round) x so that there are digits significant digits, under a base base representation, default 10. E.g., signif(123.456, 2) is 120.0, and signif(357.913, 4, 2) is 352.0.\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.min", - "page": "Mathematics", - "title": "Base.min", - "category": "function", - "text": "min(x, y, ...)\n\nReturn the minimum of the arguments. See also the minimum function to take the minimum element from a collection.\n\njulia> min(2, 5, 1)\n1\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.max", - "page": "Mathematics", - "title": "Base.max", - "category": "function", - "text": "max(x, y, ...)\n\nReturn the maximum of the arguments. See also the maximum function to take the maximum element from a collection.\n\njulia> max(2, 5, 1)\n5\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.minmax", - "page": "Mathematics", - "title": "Base.minmax", - "category": "function", - "text": "minmax(x, y)\n\nReturn (min(x,y), max(x,y)). See also: extrema that returns (minimum(x), maximum(x)).\n\njulia> minmax(\'c\',\'b\')\n(\'b\', \'c\')\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.Math.clamp", - "page": "Mathematics", - "title": "Base.Math.clamp", - "category": "function", - "text": "clamp(x, lo, hi)\n\nReturn x if lo <= x <= hi. If x < lo, return lo. If x > hi, return hi. Arguments are promoted to a common type.\n\njulia> clamp.([pi, 1.0, big(10.)], 2., 9.)\n3-element Array{BigFloat,1}:\n 3.141592653589793238462643383279502884197169399375105820974944592307816406286198\n 2.000000000000000000000000000000000000000000000000000000000000000000000000000000\n 9.000000000000000000000000000000000000000000000000000000000000000000000000000000\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.Math.clamp!", - "page": "Mathematics", - "title": "Base.Math.clamp!", - "category": "function", - "text": "clamp!(array::AbstractArray, lo, hi)\n\nRestrict values in array to the specified range, in-place. See also clamp.\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.abs", - "page": "Mathematics", - "title": "Base.abs", - "category": "function", - "text": "abs(x)\n\nThe absolute value of x.\n\nWhen abs is applied to signed integers, overflow may occur, resulting in the return of a negative value. This overflow occurs only when abs is applied to the minimum representable value of a signed integer. That is, when x == typemin(typeof(x)), abs(x) == x < 0, not -x as might be expected.\n\njulia> abs(-3)\n3\n\njulia> abs(1 + im)\n1.4142135623730951\n\njulia> abs(typemin(Int64))\n-9223372036854775808\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.Checked.checked_abs", - "page": "Mathematics", - "title": "Base.Checked.checked_abs", - "category": "function", - "text": "Base.checked_abs(x)\n\nCalculates abs(x), checking for overflow errors where applicable. For example, standard two\'s complement signed integers (e.g. Int) cannot represent abs(typemin(Int)), thus leading to an overflow.\n\nThe overflow protection may impose a perceptible performance penalty.\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.Checked.checked_neg", - "page": "Mathematics", - "title": "Base.Checked.checked_neg", - "category": "function", - "text": "Base.checked_neg(x)\n\nCalculates -x, checking for overflow errors where applicable. For example, standard two\'s complement signed integers (e.g. Int) cannot represent -typemin(Int), thus leading to an overflow.\n\nThe overflow protection may impose a perceptible performance penalty.\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.Checked.checked_add", - "page": "Mathematics", - "title": "Base.Checked.checked_add", - "category": "function", - "text": "Base.checked_add(x, y)\n\nCalculates x+y, checking for overflow errors where applicable.\n\nThe overflow protection may impose a perceptible performance penalty.\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.Checked.checked_sub", - "page": "Mathematics", - "title": "Base.Checked.checked_sub", - "category": "function", - "text": "Base.checked_sub(x, y)\n\nCalculates x-y, checking for overflow errors where applicable.\n\nThe overflow protection may impose a perceptible performance penalty.\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.Checked.checked_mul", - "page": "Mathematics", - "title": "Base.Checked.checked_mul", - "category": "function", - "text": "Base.checked_mul(x, y)\n\nCalculates x*y, checking for overflow errors where applicable.\n\nThe overflow protection may impose a perceptible performance penalty.\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.Checked.checked_div", - "page": "Mathematics", - "title": "Base.Checked.checked_div", - "category": "function", - "text": "Base.checked_div(x, y)\n\nCalculates div(x,y), checking for overflow errors where applicable.\n\nThe overflow protection may impose a perceptible performance penalty.\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.Checked.checked_rem", - "page": "Mathematics", - "title": "Base.Checked.checked_rem", - "category": "function", - "text": "Base.checked_rem(x, y)\n\nCalculates x%y, checking for overflow errors where applicable.\n\nThe overflow protection may impose a perceptible performance penalty.\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.Checked.checked_fld", - "page": "Mathematics", - "title": "Base.Checked.checked_fld", - "category": "function", - "text": "Base.checked_fld(x, y)\n\nCalculates fld(x,y), checking for overflow errors where applicable.\n\nThe overflow protection may impose a perceptible performance penalty.\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.Checked.checked_mod", - "page": "Mathematics", - "title": "Base.Checked.checked_mod", - "category": "function", - "text": "Base.checked_mod(x, y)\n\nCalculates mod(x,y), checking for overflow errors where applicable.\n\nThe overflow protection may impose a perceptible performance penalty.\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.Checked.checked_cld", - "page": "Mathematics", - "title": "Base.Checked.checked_cld", - "category": "function", - "text": "Base.checked_cld(x, y)\n\nCalculates cld(x,y), checking for overflow errors where applicable.\n\nThe overflow protection may impose a perceptible performance penalty.\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.Checked.add_with_overflow", - "page": "Mathematics", - "title": "Base.Checked.add_with_overflow", - "category": "function", - "text": "Base.add_with_overflow(x, y) -> (r, f)\n\nCalculates r = x+y, with the flag f indicating whether overflow has occurred.\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.Checked.sub_with_overflow", - "page": "Mathematics", - "title": "Base.Checked.sub_with_overflow", - "category": "function", - "text": "Base.sub_with_overflow(x, y) -> (r, f)\n\nCalculates r = x-y, with the flag f indicating whether overflow has occurred.\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.Checked.mul_with_overflow", - "page": "Mathematics", - "title": "Base.Checked.mul_with_overflow", - "category": "function", - "text": "Base.mul_with_overflow(x, y) -> (r, f)\n\nCalculates r = x*y, with the flag f indicating whether overflow has occurred.\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.abs2", - "page": "Mathematics", - "title": "Base.abs2", - "category": "function", - "text": "abs2(x)\n\nSquared absolute value of x.\n\njulia> abs2(-3)\n9\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.copysign", - "page": "Mathematics", - "title": "Base.copysign", - "category": "function", - "text": "copysign(x, y) -> z\n\nReturn z which has the magnitude of x and the same sign as y.\n\nExamples\n\njulia> copysign(1, -2)\n-1\n\njulia> copysign(-1, 2)\n1\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.sign", - "page": "Mathematics", - "title": "Base.sign", - "category": "function", - "text": "sign(x)\n\nReturn zero if x==0 and xx otherwise (i.e., ±1 for real x).\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.signbit", - "page": "Mathematics", - "title": "Base.signbit", - "category": "function", - "text": "signbit(x)\n\nReturns true if the value of the sign of x is negative, otherwise false.\n\nExamples\n\njulia> signbit(-4)\ntrue\n\njulia> signbit(5)\nfalse\n\njulia> signbit(5.5)\nfalse\n\njulia> signbit(-4.1)\ntrue\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.flipsign", - "page": "Mathematics", - "title": "Base.flipsign", - "category": "function", - "text": "flipsign(x, y)\n\nReturn x with its sign flipped if y is negative. For example abs(x) = flipsign(x,x).\n\njulia> flipsign(5, 3)\n5\n\njulia> flipsign(5, -3)\n-5\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.sqrt", - "page": "Mathematics", - "title": "Base.sqrt", - "category": "function", - "text": "sqrt(x)\n\nReturn sqrtx. Throws DomainError for negative Real arguments. Use complex negative arguments instead. The prefix operator √ is equivalent to sqrt.\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.isqrt", - "page": "Mathematics", - "title": "Base.isqrt", - "category": "function", - "text": "isqrt(n::Integer)\n\nInteger square root: the largest integer m such that m*m <= n.\n\njulia> isqrt(5)\n2\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.Math.cbrt", - "page": "Mathematics", - "title": "Base.Math.cbrt", - "category": "function", - "text": "cbrt(x::Real)\n\nReturn the cube root of x, i.e. x^13. Negative values are accepted (returning the negative real root when x 0).\n\nThe prefix operator ∛ is equivalent to cbrt.\n\njulia> cbrt(big(27))\n3.000000000000000000000000000000000000000000000000000000000000000000000000000000\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.real-Tuple{Complex}", - "page": "Mathematics", - "title": "Base.real", - "category": "method", - "text": "real(z)\n\nReturn the real part of the complex number z.\n\njulia> real(1 + 3im)\n1\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.imag", - "page": "Mathematics", - "title": "Base.imag", - "category": "function", - "text": "imag(z)\n\nReturn the imaginary part of the complex number z.\n\njulia> imag(1 + 3im)\n3\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.reim", - "page": "Mathematics", - "title": "Base.reim", - "category": "function", - "text": "reim(z)\n\nReturn both the real and imaginary parts of the complex number z.\n\njulia> reim(1 + 3im)\n(1, 3)\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.conj", - "page": "Mathematics", - "title": "Base.conj", - "category": "function", - "text": "conj(v::RowVector)\n\nReturns a ConjArray lazy view of the input, where each element is conjugated.\n\nExample\n\njulia> v = [1+im, 1-im].\'\n1×2 RowVector{Complex{Int64},Array{Complex{Int64},1}}:\n 1+1im 1-1im\n\njulia> conj(v)\n1×2 RowVector{Complex{Int64},ConjArray{Complex{Int64},1,Array{Complex{Int64},1}}}:\n 1-1im 1+1im\n\n\n\nconj(z)\n\nCompute the complex conjugate of a complex number z.\n\njulia> conj(1 + 3im)\n1 - 3im\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.angle", - "page": "Mathematics", - "title": "Base.angle", - "category": "function", - "text": "angle(z)\n\nCompute the phase angle in radians of a complex number z.\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.cis", - "page": "Mathematics", - "title": "Base.cis", - "category": "function", - "text": "cis(z)\n\nReturn exp(iz).\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.binomial", - "page": "Mathematics", - "title": "Base.binomial", - "category": "function", - "text": "binomial(n, k)\n\nNumber of ways to choose k out of n items.\n\nExample\n\njulia> binomial(5, 3)\n10\n\njulia> factorial(5) ÷ (factorial(5-3) * factorial(3))\n10\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.factorial", - "page": "Mathematics", - "title": "Base.factorial", - "category": "function", - "text": "factorial(n)\n\nFactorial of n. If n is an Integer, the factorial is computed as an integer (promoted to at least 64 bits). Note that this may overflow if n is not small, but you can use factorial(big(n)) to compute the result exactly in arbitrary precision. If n is not an Integer, factorial(n) is equivalent to gamma(n+1).\n\njulia> factorial(6)\n720\n\njulia> factorial(21)\nERROR: OverflowError()\n[...]\n\njulia> factorial(21.0)\n5.109094217170944e19\n\njulia> factorial(big(21))\n51090942171709440000\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.gcd", - "page": "Mathematics", - "title": "Base.gcd", - "category": "function", - "text": "gcd(x,y)\n\nGreatest common (positive) divisor (or zero if x and y are both zero).\n\nExamples\n\njulia> gcd(6,9)\n3\n\njulia> gcd(6,-9)\n3\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.lcm", - "page": "Mathematics", - "title": "Base.lcm", - "category": "function", - "text": "lcm(x,y)\n\nLeast common (non-negative) multiple.\n\nExamples\n\njulia> lcm(2,3)\n6\n\njulia> lcm(-2,3)\n6\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.gcdx", - "page": "Mathematics", - "title": "Base.gcdx", - "category": "function", - "text": "gcdx(x,y)\n\nComputes the greatest common (positive) divisor of x and y and their Bézout coefficients, i.e. the integer coefficients u and v that satisfy ux+vy = d = gcd(xy). gcdx(xy) returns (duv).\n\nExamples\n\njulia> gcdx(12, 42)\n(6, -3, 1)\n\njulia> gcdx(240, 46)\n(2, -9, 47)\n\nnote: Note\nBézout coefficients are not uniquely defined. gcdx returns the minimal Bézout coefficients that are computed by the extended Euclidean algorithm. (Ref: D. Knuth, TAoCP, 2/e, p. 325, Algorithm X.) For signed integers, these coefficients u and v are minimal in the sense that u yd and v xd. Furthermore, the signs of u and v are chosen so that d is positive. For unsigned integers, the coefficients u and v might be near their typemax, and the identity then holds only via the unsigned integers\' modulo arithmetic.\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.ispow2", - "page": "Mathematics", - "title": "Base.ispow2", - "category": "function", - "text": "ispow2(n::Integer) -> Bool\n\nTest whether n is a power of two.\n\nExamples\n\njulia> ispow2(4)\ntrue\n\njulia> ispow2(5)\nfalse\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.nextpow2", - "page": "Mathematics", - "title": "Base.nextpow2", - "category": "function", - "text": "nextpow2(n::Integer)\n\nThe smallest power of two not less than n. Returns 0 for n==0, and returns -nextpow2(-n) for negative arguments.\n\nExamples\n\njulia> nextpow2(16)\n16\n\njulia> nextpow2(17)\n32\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.prevpow2", - "page": "Mathematics", - "title": "Base.prevpow2", - "category": "function", - "text": "prevpow2(n::Integer)\n\nThe largest power of two not greater than n. Returns 0 for n==0, and returns -prevpow2(-n) for negative arguments.\n\nExamples\n\njulia> prevpow2(5)\n4\n\njulia> prevpow2(0)\n0\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.nextpow", - "page": "Mathematics", - "title": "Base.nextpow", - "category": "function", - "text": "nextpow(a, x)\n\nThe smallest a^n not less than x, where n is a non-negative integer. a must be greater than 1, and x must be greater than 0.\n\nExamples\n\njulia> nextpow(2, 7)\n8\n\njulia> nextpow(2, 9)\n16\n\njulia> nextpow(5, 20)\n25\n\njulia> nextpow(4, 16)\n16\n\nSee also prevpow.\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.prevpow", - "page": "Mathematics", - "title": "Base.prevpow", - "category": "function", - "text": "prevpow(a, x)\n\nThe largest a^n not greater than x, where n is a non-negative integer. a must be greater than 1, and x must not be less than 1.\n\nExamples\n\njulia> prevpow(2, 7)\n4\n\njulia> prevpow(2, 9)\n8\n\njulia> prevpow(5, 20)\n5\n\njulia> prevpow(4, 16)\n16\n\nSee also nextpow.\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.nextprod", - "page": "Mathematics", - "title": "Base.nextprod", - "category": "function", - "text": "nextprod([k_1, k_2,...], n)\n\nNext integer greater than or equal to n that can be written as prod k_i^p_i for integers p_1, p_2, etc.\n\nExample\n\njulia> nextprod([2, 3], 105)\n108\n\njulia> 2^2 * 3^3\n108\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.invmod", - "page": "Mathematics", - "title": "Base.invmod", - "category": "function", - "text": "invmod(x,m)\n\nTake the inverse of x modulo m: y such that x y = 1 pmod m, with div(xy) = 0. This is undefined for m = 0, or if gcd(xm) neq 1.\n\nExamples\n\njulia> invmod(2,5)\n3\n\njulia> invmod(2,3)\n2\n\njulia> invmod(5,6)\n5\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.powermod", - "page": "Mathematics", - "title": "Base.powermod", - "category": "function", - "text": "powermod(x::Integer, p::Integer, m)\n\nCompute x^p pmod m.\n\nExamples\n\njulia> powermod(2, 6, 5)\n4\n\njulia> mod(2^6, 5)\n4\n\njulia> powermod(5, 2, 20)\n5\n\njulia> powermod(5, 2, 19)\n6\n\njulia> powermod(5, 3, 19)\n11\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.Math.gamma", - "page": "Mathematics", - "title": "Base.Math.gamma", - "category": "function", - "text": "gamma(x)\n\nCompute the gamma function of x.\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.Math.lgamma", - "page": "Mathematics", - "title": "Base.Math.lgamma", - "category": "function", - "text": "lgamma(x)\n\nCompute the logarithm of the absolute value of gamma for Real x, while for Complex x compute the principal branch cut of the logarithm of gamma(x) (defined for negative real(x) by analytic continuation from positive real(x)).\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.Math.lfact", - "page": "Mathematics", - "title": "Base.Math.lfact", - "category": "function", - "text": "lfact(x)\n\nCompute the logarithmic factorial of a nonnegative integer x. Equivalent to lgamma of x + 1, but lgamma extends this function to non-integer x.\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.Math.beta", - "page": "Mathematics", - "title": "Base.Math.beta", - "category": "function", - "text": "beta(x, y)\n\nEuler integral of the first kind operatornameB(xy) = Gamma(x)Gamma(y)Gamma(x+y).\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.Math.lbeta", - "page": "Mathematics", - "title": "Base.Math.lbeta", - "category": "function", - "text": "lbeta(x, y)\n\nNatural logarithm of the absolute value of the beta function log(operatornameB(xy)).\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.ndigits", - "page": "Mathematics", - "title": "Base.ndigits", - "category": "function", - "text": "ndigits(n::Integer, b::Integer=10)\n\nCompute the number of digits in integer n written in base b. The base b must not be in [-1, 0, 1].\n\nExamples\n\njulia> ndigits(12345)\n5\n\njulia> ndigits(1022, 16)\n3\n\njulia> base(16, 1022)\n\"3fe\"\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.widemul", - "page": "Mathematics", - "title": "Base.widemul", - "category": "function", - "text": "widemul(x, y)\n\nMultiply x and y, giving the result as a larger type.\n\njulia> widemul(Float32(3.), 4.)\n1.200000000000000000000000000000000000000000000000000000000000000000000000000000e+01\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.Math.@evalpoly", - "page": "Mathematics", - "title": "Base.Math.@evalpoly", - "category": "macro", - "text": "@evalpoly(z, c...)\n\nEvaluate the polynomial sum_k ck z^k-1 for the coefficients c[1], c[2], ...; that is, the coefficients are given in ascending order by power of z. This macro expands to efficient inline code that uses either Horner\'s method or, for complex z, a more efficient Goertzel-like algorithm.\n\njulia> @evalpoly(3, 1, 0, 1)\n10\n\njulia> @evalpoly(2, 1, 0, 1)\n5\n\njulia> @evalpoly(2, 1, 1, 1)\n7\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Mathematical-Functions-1", - "page": "Mathematics", - "title": "Mathematical Functions", - "category": "section", - "text": "Base.isapprox\nBase.sin\nBase.cos\nBase.tan\nBase.Math.sind\nBase.Math.cosd\nBase.Math.tand\nBase.Math.sinpi\nBase.Math.cospi\nBase.sinh\nBase.cosh\nBase.tanh\nBase.asin\nBase.acos\nBase.atan\nBase.Math.atan2\nBase.Math.asind\nBase.Math.acosd\nBase.Math.atand\nBase.Math.sec\nBase.Math.csc\nBase.Math.cot\nBase.Math.secd\nBase.Math.cscd\nBase.Math.cotd\nBase.Math.asec\nBase.Math.acsc\nBase.Math.acot\nBase.Math.asecd\nBase.Math.acscd\nBase.Math.acotd\nBase.Math.sech\nBase.Math.csch\nBase.Math.coth\nBase.asinh\nBase.acosh\nBase.atanh\nBase.Math.asech\nBase.Math.acsch\nBase.Math.acoth\nBase.Math.sinc\nBase.Math.cosc\nBase.Math.deg2rad\nBase.Math.rad2deg\nBase.Math.hypot\nBase.log(::Any)\nBase.log(::Number, ::Number)\nBase.log2\nBase.log10\nBase.log1p\nBase.Math.frexp\nBase.exp\nBase.exp2\nBase.exp10\nBase.Math.ldexp\nBase.Math.modf\nBase.expm1\nBase.round(::Type, ::Any)\nBase.Rounding.RoundingMode\nBase.Rounding.RoundNearest\nBase.Rounding.RoundNearestTiesAway\nBase.Rounding.RoundNearestTiesUp\nBase.Rounding.RoundToZero\nBase.Rounding.RoundUp\nBase.Rounding.RoundDown\nBase.round{T <: AbstractFloat, MR, MI}(::Complex{T}, ::RoundingMode{MR}, ::RoundingMode{MI})\nBase.ceil\nBase.floor\nBase.trunc\nBase.unsafe_trunc\nBase.signif\nBase.min\nBase.max\nBase.minmax\nBase.Math.clamp\nBase.Math.clamp!\nBase.abs\nBase.Checked.checked_abs\nBase.Checked.checked_neg\nBase.Checked.checked_add\nBase.Checked.checked_sub\nBase.Checked.checked_mul\nBase.Checked.checked_div\nBase.Checked.checked_rem\nBase.Checked.checked_fld\nBase.Checked.checked_mod\nBase.Checked.checked_cld\nBase.Checked.add_with_overflow\nBase.Checked.sub_with_overflow\nBase.Checked.mul_with_overflow\nBase.abs2\nBase.copysign\nBase.sign\nBase.signbit\nBase.flipsign\nBase.sqrt\nBase.isqrt\nBase.Math.cbrt\nBase.real(::Complex)\nBase.imag\nBase.reim\nBase.conj\nBase.angle\nBase.cis\nBase.binomial\nBase.factorial\nBase.gcd\nBase.lcm\nBase.gcdx\nBase.ispow2\nBase.nextpow2\nBase.prevpow2\nBase.nextpow\nBase.prevpow\nBase.nextprod\nBase.invmod\nBase.powermod\nBase.Math.gamma\nBase.Math.lgamma\nBase.Math.lfact\nBase.Math.beta\nBase.Math.lbeta\nBase.ndigits\nBase.widemul\nBase.Math.@evalpoly" -}, - -{ - "location": "stdlib/math.html#Base.mean", - "page": "Mathematics", - "title": "Base.mean", - "category": "function", - "text": "mean(f::Function, v)\n\nApply the function f to each element of v and take the mean.\n\njulia> mean(√, [1, 2, 3])\n1.3820881233139908\n\njulia> mean([√1, √2, √3])\n1.3820881233139908\n\n\n\nmean(v[, region])\n\nCompute the mean of whole array v, or optionally along the dimensions in region.\n\nnote: Note\nJulia does not ignore NaN values in the computation. For applications requiring the handling of missing data, the DataArrays.jl package is recommended.\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.mean!", - "page": "Mathematics", - "title": "Base.mean!", - "category": "function", - "text": "mean!(r, v)\n\nCompute the mean of v over the singleton dimensions of r, and write results to r.\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.std", - "page": "Mathematics", - "title": "Base.std", - "category": "function", - "text": "std(v[, region]; corrected::Bool=true, mean=nothing)\n\nCompute the sample standard deviation of a vector or array v, optionally along dimensions in region. The algorithm returns an estimator of the generative distribution\'s standard deviation under the assumption that each entry of v is an IID drawn from that generative distribution. This computation is equivalent to calculating sqrt(sum((v - mean(v)).^2) / (length(v) - 1)). A pre-computed mean may be provided. If corrected is true, then the sum is scaled with n-1, whereas the sum is scaled with n if corrected is false where n = length(x).\n\nnote: Note\nJulia does not ignore NaN values in the computation. For applications requiring the handling of missing data, the DataArrays.jl package is recommended.\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.stdm", - "page": "Mathematics", - "title": "Base.stdm", - "category": "function", - "text": "stdm(v, m::Number; corrected::Bool=true)\n\nCompute the sample standard deviation of a vector v with known mean m. If corrected is true, then the sum is scaled with n-1, whereas the sum is scaled with n if corrected is false where n = length(x).\n\nnote: Note\nJulia does not ignore NaN values in the computation. For applications requiring the handling of missing data, the DataArrays.jl package is recommended.\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.var", - "page": "Mathematics", - "title": "Base.var", - "category": "function", - "text": "var(v[, region]; corrected::Bool=true, mean=nothing)\n\nCompute the sample variance of a vector or array v, optionally along dimensions in region. The algorithm will return an estimator of the generative distribution\'s variance under the assumption that each entry of v is an IID drawn from that generative distribution. This computation is equivalent to calculating sum(abs2, v - mean(v)) / (length(v) - 1). If corrected is true, then the sum is scaled with n-1, whereas the sum is scaled with n if corrected is false where n = length(x). The mean mean over the region may be provided.\n\nnote: Note\nJulia does not ignore NaN values in the computation. For applications requiring the handling of missing data, the DataArrays.jl package is recommended.\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.varm", - "page": "Mathematics", - "title": "Base.varm", - "category": "function", - "text": "varm(v, m[, region]; corrected::Bool=true)\n\nCompute the sample variance of a collection v with known mean(s) m, optionally over region. m may contain means for each dimension of v. If corrected is true, then the sum is scaled with n-1, whereas the sum is scaled with n if corrected is false where n = length(x).\n\nnote: Note\nJulia does not ignore NaN values in the computation. For applications requiring the handling of missing data, the DataArrays.jl package is recommended.\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.middle", - "page": "Mathematics", - "title": "Base.middle", - "category": "function", - "text": "middle(x)\n\nCompute the middle of a scalar value, which is equivalent to x itself, but of the type of middle(x, x) for consistency.\n\n\n\nmiddle(x, y)\n\nCompute the middle of two reals x and y, which is equivalent in both value and type to computing their mean ((x + y) / 2).\n\n\n\nmiddle(range)\n\nCompute the middle of a range, which consists of computing the mean of its extrema. Since a range is sorted, the mean is performed with the first and last element.\n\njulia> middle(1:10)\n5.5\n\n\n\nmiddle(a)\n\nCompute the middle of an array a, which consists of finding its extrema and then computing their mean.\n\njulia> a = [1,2,3.6,10.9]\n4-element Array{Float64,1}:\n 1.0\n 2.0\n 3.6\n 10.9\n\njulia> middle(a)\n5.95\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.median", - "page": "Mathematics", - "title": "Base.median", - "category": "function", - "text": "median(v[, region])\n\nCompute the median of an entire array v, or, optionally, along the dimensions in region. For an even number of elements no exact median element exists, so the result is equivalent to calculating mean of two median elements.\n\nnote: Note\nJulia does not ignore NaN values in the computation. For applications requiring the handling of missing data, the DataArrays.jl package is recommended.\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.median!", - "page": "Mathematics", - "title": "Base.median!", - "category": "function", - "text": "median!(v)\n\nLike median, but may overwrite the input vector.\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.quantile", - "page": "Mathematics", - "title": "Base.quantile", - "category": "function", - "text": "quantile(v, p; sorted=false)\n\nCompute the quantile(s) of a vector v at a specified probability or vector p. The keyword argument sorted indicates whether v can be assumed to be sorted.\n\nThe p should be on the interval [0,1], and v should not have any NaN values.\n\nQuantiles are computed via linear interpolation between the points ((k-1)/(n-1), v[k]), for k = 1:n where n = length(v). This corresponds to Definition 7 of Hyndman and Fan (1996), and is the same as the R default.\n\nnote: Note\nJulia does not ignore NaN values in the computation. For applications requiring the handling of missing data, the DataArrays.jl package is recommended. quantile will throw an ArgumentError in the presence of NaN values in the data array.\n\nHyndman, R.J and Fan, Y. (1996) \"Sample Quantiles in Statistical Packages\", The American Statistician, Vol. 50, No. 4, pp. 361-365\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.quantile!", - "page": "Mathematics", - "title": "Base.quantile!", - "category": "function", - "text": "quantile!([q, ] v, p; sorted=false)\n\nCompute the quantile(s) of a vector v at the probabilities p, with optional output into array q (if not provided, a new output array is created). The keyword argument sorted indicates whether v can be assumed to be sorted; if false (the default), then the elements of v may be partially sorted.\n\nThe elements of p should be on the interval [0,1], and v should not have any NaN values.\n\nQuantiles are computed via linear interpolation between the points ((k-1)/(n-1), v[k]), for k = 1:n where n = length(v). This corresponds to Definition 7 of Hyndman and Fan (1996), and is the same as the R default.\n\nnote: Note\nJulia does not ignore NaN values in the computation. For applications requiring the handling of missing data, the DataArrays.jl package is recommended. quantile! will throw an ArgumentError in the presence of NaN values in the data array.\n\nHyndman, R.J and Fan, Y. (1996) \"Sample Quantiles in Statistical Packages\", The American Statistician, Vol. 50, No. 4, pp. 361-365\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.cov", - "page": "Mathematics", - "title": "Base.cov", - "category": "function", - "text": "cov(x[, corrected=true])\n\nCompute the variance of the vector x. If corrected is true (the default) then the sum is scaled with n-1, whereas the sum is scaled with n if corrected is false where n = length(x).\n\n\n\ncov(X[, vardim=1, corrected=true])\n\nCompute the covariance matrix of the matrix X along the dimension vardim. If corrected is true (the default) then the sum is scaled with n-1, whereas the sum is scaled with n if corrected is false where n = size(X, vardim).\n\n\n\ncov(x, y[, corrected=true])\n\nCompute the covariance between the vectors x and y. If corrected is true (the default), computes frac1n-1sum_i=1^n (x_i-bar x) (y_i-bar y)^* where * denotes the complex conjugate and n = length(x) = length(y). If corrected is false, computes rac1nsum_i=1^n (x_i-bar x) (y_i-bar y)^*.\n\n\n\ncov(X, Y[, vardim=1, corrected=true])\n\nCompute the covariance between the vectors or matrices X and Y along the dimension vardim. If corrected is true (the default) then the sum is scaled with n-1, whereas the sum is scaled with n if corrected is false where n = size(X, vardim) = size(Y, vardim).\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.cor", - "page": "Mathematics", - "title": "Base.cor", - "category": "function", - "text": "cor(x)\n\nReturn the number one.\n\n\n\ncor(X[, vardim=1])\n\nCompute the Pearson correlation matrix of the matrix X along the dimension vardim.\n\n\n\ncor(x, y)\n\nCompute the Pearson correlation between the vectors x and y.\n\n\n\ncor(X, Y[, vardim=1])\n\nCompute the Pearson correlation between the vectors or matrices X and Y along the dimension vardim.\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Statistics-1", - "page": "Mathematics", - "title": "Statistics", - "category": "section", - "text": "Base.mean\nBase.mean!\nBase.std\nBase.stdm\nBase.var\nBase.varm\nBase.middle\nBase.median\nBase.median!\nBase.quantile\nBase.quantile!\nBase.cov\nBase.cor" -}, - -{ - "location": "stdlib/math.html#Base.DFT.fft", - "page": "Mathematics", - "title": "Base.DFT.fft", - "category": "function", - "text": "fft(A [, dims])\n\nPerforms a multidimensional FFT of the array A. The optional dims argument specifies an iterable subset of dimensions (e.g. an integer, range, tuple, or array) to transform along. Most efficient if the size of A along the transformed dimensions is a product of small primes; see nextprod(). See also plan_fft() for even greater efficiency.\n\nA one-dimensional FFT computes the one-dimensional discrete Fourier transform (DFT) as defined by\n\noperatornameDFT(A)k =\n sum_n=1^operatornamelength(A)\n expleft(-ifrac2pi\n (n-1)(k-1)operatornamelength(A) right) An\n\nA multidimensional FFT simply performs this operation along each transformed dimension of A.\n\nnote: Note\nJulia starts FFTW up with 1 thread by default. Higher performance is usually possible by increasing number of threads. Use FFTW.set_num_threads(Sys.CPU_CORES) to use as many threads as cores on your system.\nThis performs a multidimensional FFT by default. FFT libraries in other languages such as Python and Octave perform a one-dimensional FFT along the first non-singleton dimension of the array. This is worth noting while performing comparisons. For more details, refer to the Noteworthy Differences from other Languages section of the manual.\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.DFT.fft!", - "page": "Mathematics", - "title": "Base.DFT.fft!", - "category": "function", - "text": "fft!(A [, dims])\n\nSame as fft, but operates in-place on A, which must be an array of complex floating-point numbers.\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.DFT.ifft", - "page": "Mathematics", - "title": "Base.DFT.ifft", - "category": "function", - "text": "ifft(A [, dims])\n\nMultidimensional inverse FFT.\n\nA one-dimensional inverse FFT computes\n\noperatornameIDFT(A)k = frac1operatornamelength(A)\nsum_n=1^operatornamelength(A) expleft(+ifrac2pi (n-1)(k-1)\noperatornamelength(A) right) An\n\nA multidimensional inverse FFT simply performs this operation along each transformed dimension of A.\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.DFT.ifft!", - "page": "Mathematics", - "title": "Base.DFT.ifft!", - "category": "function", - "text": "ifft!(A [, dims])\n\nSame as ifft, but operates in-place on A.\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.DFT.bfft", - "page": "Mathematics", - "title": "Base.DFT.bfft", - "category": "function", - "text": "bfft(A [, dims])\n\nSimilar to ifft, but computes an unnormalized inverse (backward) transform, which must be divided by the product of the sizes of the transformed dimensions in order to obtain the inverse. (This is slightly more efficient than ifft because it omits a scaling step, which in some applications can be combined with other computational steps elsewhere.)\n\noperatornameBDFT(A)k = operatornamelength(A) operatornameIDFT(A)k\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.DFT.bfft!", - "page": "Mathematics", - "title": "Base.DFT.bfft!", - "category": "function", - "text": "bfft!(A [, dims])\n\nSame as bfft, but operates in-place on A.\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.DFT.plan_fft", - "page": "Mathematics", - "title": "Base.DFT.plan_fft", - "category": "function", - "text": "plan_fft(A [, dims]; flags=FFTW.ESTIMATE; timelimit=Inf)\n\nPre-plan an optimized FFT along given dimensions (dims) of arrays matching the shape and type of A. (The first two arguments have the same meaning as for fft.) Returns an object P which represents the linear operator computed by the FFT, and which contains all of the information needed to compute fft(A, dims) quickly.\n\nTo apply P to an array A, use P * A; in general, the syntax for applying plans is much like that of matrices. (A plan can only be applied to arrays of the same size as the A for which the plan was created.) You can also apply a plan with a preallocated output array  by calling A_mul_B!(Â, plan, A). (For A_mul_B!, however, the input array A must be a complex floating-point array like the output Â.) You can compute the inverse-transform plan by inv(P) and apply the inverse plan with P \\  (the inverse plan is cached and reused for subsequent calls to inv or \\), and apply the inverse plan to a pre-allocated output array A with A_ldiv_B!(A, P, Â).\n\nThe flags argument is a bitwise-or of FFTW planner flags, defaulting to FFTW.ESTIMATE. e.g. passing FFTW.MEASURE or FFTW.PATIENT will instead spend several seconds (or more) benchmarking different possible FFT algorithms and picking the fastest one; see the FFTW manual for more information on planner flags. The optional timelimit argument specifies a rough upper bound on the allowed planning time, in seconds. Passing FFTW.MEASURE or FFTW.PATIENT may cause the input array A to be overwritten with zeros during plan creation.\n\nplan_fft! is the same as plan_fft but creates a plan that operates in-place on its argument (which must be an array of complex floating-point numbers). plan_ifft and so on are similar but produce plans that perform the equivalent of the inverse transforms ifft and so on.\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.DFT.plan_ifft", - "page": "Mathematics", - "title": "Base.DFT.plan_ifft", - "category": "function", - "text": "plan_ifft(A [, dims]; flags=FFTW.ESTIMATE; timelimit=Inf)\n\nSame as plan_fft, but produces a plan that performs inverse transforms ifft.\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.DFT.plan_bfft", - "page": "Mathematics", - "title": "Base.DFT.plan_bfft", - "category": "function", - "text": "plan_bfft(A [, dims]; flags=FFTW.ESTIMATE; timelimit=Inf)\n\nSame as plan_fft, but produces a plan that performs an unnormalized backwards transform bfft.\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.DFT.plan_fft!", - "page": "Mathematics", - "title": "Base.DFT.plan_fft!", - "category": "function", - "text": "plan_fft!(A [, dims]; flags=FFTW.ESTIMATE; timelimit=Inf)\n\nSame as plan_fft, but operates in-place on A.\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.DFT.plan_ifft!", - "page": "Mathematics", - "title": "Base.DFT.plan_ifft!", - "category": "function", - "text": "plan_ifft!(A [, dims]; flags=FFTW.ESTIMATE; timelimit=Inf)\n\nSame as plan_ifft, but operates in-place on A.\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.DFT.plan_bfft!", - "page": "Mathematics", - "title": "Base.DFT.plan_bfft!", - "category": "function", - "text": "plan_bfft!(A [, dims]; flags=FFTW.ESTIMATE; timelimit=Inf)\n\nSame as plan_bfft, but operates in-place on A.\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.DFT.rfft", - "page": "Mathematics", - "title": "Base.DFT.rfft", - "category": "function", - "text": "rfft(A [, dims])\n\nMultidimensional FFT of a real array A, exploiting the fact that the transform has conjugate symmetry in order to save roughly half the computational time and storage costs compared with fft. If A has size (n_1, ..., n_d), the result has size (div(n_1,2)+1, ..., n_d).\n\nThe optional dims argument specifies an iterable subset of one or more dimensions of A to transform, similar to fft. Instead of (roughly) halving the first dimension of A in the result, the dims[1] dimension is (roughly) halved in the same way.\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.DFT.irfft", - "page": "Mathematics", - "title": "Base.DFT.irfft", - "category": "function", - "text": "irfft(A, d [, dims])\n\nInverse of rfft: for a complex array A, gives the corresponding real array whose FFT yields A in the first half. As for rfft, dims is an optional subset of dimensions to transform, defaulting to 1:ndims(A).\n\nd is the length of the transformed real array along the dims[1] dimension, which must satisfy div(d,2)+1 == size(A,dims[1]). (This parameter cannot be inferred from size(A) since both 2*size(A,dims[1])-2 as well as 2*size(A,dims[1])-1 are valid sizes for the transformed real array.)\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.DFT.brfft", - "page": "Mathematics", - "title": "Base.DFT.brfft", - "category": "function", - "text": "brfft(A, d [, dims])\n\nSimilar to irfft but computes an unnormalized inverse transform (similar to bfft), which must be divided by the product of the sizes of the transformed dimensions (of the real output array) in order to obtain the inverse transform.\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.DFT.plan_rfft", - "page": "Mathematics", - "title": "Base.DFT.plan_rfft", - "category": "function", - "text": "plan_rfft(A [, dims]; flags=FFTW.ESTIMATE; timelimit=Inf)\n\nPre-plan an optimized real-input FFT, similar to plan_fft except for rfft instead of fft. The first two arguments, and the size of the transformed result, are the same as for rfft.\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.DFT.plan_brfft", - "page": "Mathematics", - "title": "Base.DFT.plan_brfft", - "category": "function", - "text": "plan_brfft(A, d [, dims]; flags=FFTW.ESTIMATE; timelimit=Inf)\n\nPre-plan an optimized real-input unnormalized transform, similar to plan_rfft except for brfft instead of rfft. The first two arguments and the size of the transformed result, are the same as for brfft.\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.DFT.plan_irfft", - "page": "Mathematics", - "title": "Base.DFT.plan_irfft", - "category": "function", - "text": "plan_irfft(A, d [, dims]; flags=FFTW.ESTIMATE; timelimit=Inf)\n\nPre-plan an optimized inverse real-input FFT, similar to plan_rfft except for irfft and brfft, respectively. The first three arguments have the same meaning as for irfft.\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.DFT.FFTW.dct", - "page": "Mathematics", - "title": "Base.DFT.FFTW.dct", - "category": "function", - "text": "dct(A [, dims])\n\nPerforms a multidimensional type-II discrete cosine transform (DCT) of the array A, using the unitary normalization of the DCT. The optional dims argument specifies an iterable subset of dimensions (e.g. an integer, range, tuple, or array) to transform along. Most efficient if the size of A along the transformed dimensions is a product of small primes; see nextprod. See also plan_dct for even greater efficiency.\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.DFT.FFTW.dct!", - "page": "Mathematics", - "title": "Base.DFT.FFTW.dct!", - "category": "function", - "text": "dct!(A [, dims])\n\nSame as dct!, except that it operates in-place on A, which must be an array of real or complex floating-point values.\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.DFT.FFTW.idct", - "page": "Mathematics", - "title": "Base.DFT.FFTW.idct", - "category": "function", - "text": "idct(A [, dims])\n\nComputes the multidimensional inverse discrete cosine transform (DCT) of the array A (technically, a type-III DCT with the unitary normalization). The optional dims argument specifies an iterable subset of dimensions (e.g. an integer, range, tuple, or array) to transform along. Most efficient if the size of A along the transformed dimensions is a product of small primes; see nextprod. See also plan_idct for even greater efficiency.\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.DFT.FFTW.idct!", - "page": "Mathematics", - "title": "Base.DFT.FFTW.idct!", - "category": "function", - "text": "idct!(A [, dims])\n\nSame as idct!, but operates in-place on A.\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.DFT.FFTW.plan_dct", - "page": "Mathematics", - "title": "Base.DFT.FFTW.plan_dct", - "category": "function", - "text": "plan_dct(A [, dims [, flags [, timelimit]]])\n\nPre-plan an optimized discrete cosine transform (DCT), similar to plan_fft except producing a function that computes dct. The first two arguments have the same meaning as for dct.\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.DFT.FFTW.plan_dct!", - "page": "Mathematics", - "title": "Base.DFT.FFTW.plan_dct!", - "category": "function", - "text": "plan_dct!(A [, dims [, flags [, timelimit]]])\n\nSame as plan_dct, but operates in-place on A.\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.DFT.FFTW.plan_idct", - "page": "Mathematics", - "title": "Base.DFT.FFTW.plan_idct", - "category": "function", - "text": "plan_idct(A [, dims [, flags [, timelimit]]])\n\nPre-plan an optimized inverse discrete cosine transform (DCT), similar to plan_fft except producing a function that computes idct. The first two arguments have the same meaning as for idct.\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.DFT.FFTW.plan_idct!", - "page": "Mathematics", - "title": "Base.DFT.FFTW.plan_idct!", - "category": "function", - "text": "plan_idct!(A [, dims [, flags [, timelimit]]])\n\nSame as plan_idct, but operates in-place on A.\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.DFT.fftshift-Tuple{Any}", - "page": "Mathematics", - "title": "Base.DFT.fftshift", - "category": "method", - "text": "fftshift(x)\n\nSwap the first and second halves of each dimension of x.\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.DFT.fftshift-Tuple{Any,Any}", - "page": "Mathematics", - "title": "Base.DFT.fftshift", - "category": "method", - "text": "fftshift(x,dim)\n\nSwap the first and second halves of the given dimension or iterable of dimensions of array x.\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.DFT.ifftshift", - "page": "Mathematics", - "title": "Base.DFT.ifftshift", - "category": "function", - "text": "ifftshift(x, [dim])\n\nUndoes the effect of fftshift.\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.DSP.filt", - "page": "Mathematics", - "title": "Base.DSP.filt", - "category": "function", - "text": "filt(b, a, x, [si])\n\nApply filter described by vectors a and b to vector x, with an optional initial filter state vector si (defaults to zeros).\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.DSP.filt!", - "page": "Mathematics", - "title": "Base.DSP.filt!", - "category": "function", - "text": "filt!(out, b, a, x, [si])\n\nSame as filt but writes the result into the out argument, which may alias the input x to modify it in-place.\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.DSP.deconv", - "page": "Mathematics", - "title": "Base.DSP.deconv", - "category": "function", - "text": "deconv(b,a) -> c\n\nConstruct vector c such that b = conv(a,c) + r. Equivalent to polynomial division.\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.DSP.conv", - "page": "Mathematics", - "title": "Base.DSP.conv", - "category": "function", - "text": "conv(u,v)\n\nConvolution of two vectors. Uses FFT algorithm.\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.DSP.conv2", - "page": "Mathematics", - "title": "Base.DSP.conv2", - "category": "function", - "text": "conv2(u,v,A)\n\n2-D convolution of the matrix A with the 2-D separable kernel generated by the vectors u and v. Uses 2-D FFT algorithm.\n\n\n\nconv2(B,A)\n\n2-D convolution of the matrix B with the matrix A. Uses 2-D FFT algorithm.\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.DSP.xcorr", - "page": "Mathematics", - "title": "Base.DSP.xcorr", - "category": "function", - "text": "xcorr(u,v)\n\nCompute the cross-correlation of two vectors.\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.DFT.FFTW.r2r", - "page": "Mathematics", - "title": "Base.DFT.FFTW.r2r", - "category": "function", - "text": "r2r(A, kind [, dims])\n\nPerforms a multidimensional real-input/real-output (r2r) transform of type kind of the array A, as defined in the FFTW manual. kind specifies either a discrete cosine transform of various types (FFTW.REDFT00, FFTW.REDFT01, FFTW.REDFT10, or FFTW.REDFT11), a discrete sine transform of various types (FFTW.RODFT00, FFTW.RODFT01, FFTW.RODFT10, or FFTW.RODFT11), a real-input DFT with halfcomplex-format output (FFTW.R2HC and its inverse FFTW.HC2R), or a discrete Hartley transform (FFTW.DHT). The kind argument may be an array or tuple in order to specify different transform types along the different dimensions of A; kind[end] is used for any unspecified dimensions. See the FFTW manual for precise definitions of these transform types, at http://www.fftw.org/doc.\n\nThe optional dims argument specifies an iterable subset of dimensions (e.g. an integer, range, tuple, or array) to transform along. kind[i] is then the transform type for dims[i], with kind[end] being used for i > length(kind).\n\nSee also plan_r2r to pre-plan optimized r2r transforms.\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.DFT.FFTW.r2r!", - "page": "Mathematics", - "title": "Base.DFT.FFTW.r2r!", - "category": "function", - "text": "r2r!(A, kind [, dims])\n\nSame as r2r, but operates in-place on A, which must be an array of real or complex floating-point numbers.\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.DFT.FFTW.plan_r2r", - "page": "Mathematics", - "title": "Base.DFT.FFTW.plan_r2r", - "category": "function", - "text": "plan_r2r(A, kind [, dims [, flags [, timelimit]]])\n\nPre-plan an optimized r2r transform, similar to plan_fft except that the transforms (and the first three arguments) correspond to r2r and r2r!, respectively.\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Base.DFT.FFTW.plan_r2r!", - "page": "Mathematics", - "title": "Base.DFT.FFTW.plan_r2r!", - "category": "function", - "text": "plan_r2r!(A, kind [, dims [, flags [, timelimit]]])\n\nSimilar to plan_fft, but corresponds to r2r!.\n\n\n\n" -}, - -{ - "location": "stdlib/math.html#Signal-Processing-1", - "page": "Mathematics", - "title": "Signal Processing", - "category": "section", - "text": "Fast Fourier transform (FFT) functions in Julia are implemented by calling functions from FFTW.Base.DFT.fft\nBase.DFT.fft!\nBase.DFT.ifft\nBase.DFT.ifft!\nBase.DFT.bfft\nBase.DFT.bfft!\nBase.DFT.plan_fft\nBase.DFT.plan_ifft\nBase.DFT.plan_bfft\nBase.DFT.plan_fft!\nBase.DFT.plan_ifft!\nBase.DFT.plan_bfft!\nBase.DFT.rfft\nBase.DFT.irfft\nBase.DFT.brfft\nBase.DFT.plan_rfft\nBase.DFT.plan_brfft\nBase.DFT.plan_irfft\nBase.DFT.FFTW.dct\nBase.DFT.FFTW.dct!\nBase.DFT.FFTW.idct\nBase.DFT.FFTW.idct!\nBase.DFT.FFTW.plan_dct\nBase.DFT.FFTW.plan_dct!\nBase.DFT.FFTW.plan_idct\nBase.DFT.FFTW.plan_idct!\nBase.DFT.fftshift(::Any)\nBase.DFT.fftshift(::Any, ::Any)\nBase.DFT.ifftshift\nBase.DSP.filt\nBase.DSP.filt!\nBase.DSP.deconv\nBase.DSP.conv\nBase.DSP.conv2\nBase.DSP.xcorrThe following functions are defined within the Base.FFTW module.Base.DFT.FFTW.r2r\nBase.DFT.FFTW.r2r!\nBase.DFT.FFTW.plan_r2r\nBase.DFT.FFTW.plan_r2r!" -}, - -{ - "location": "stdlib/numbers.html#", - "page": "Numbers", - "title": "Numbers", - "category": "page", - "text": "" -}, - -{ - "location": "stdlib/numbers.html#lib-numbers-1", - "page": "Numbers", - "title": "Numbers", - "category": "section", - "text": "" -}, - -{ - "location": "stdlib/numbers.html#Standard-Numeric-Types-1", - "page": "Numbers", - "title": "Standard Numeric Types", - "category": "section", - "text": "" -}, - -{ - "location": "stdlib/numbers.html#Core.Number", - "page": "Numbers", - "title": "Core.Number", - "category": "type", - "text": "Number\n\nAbstract supertype for all number types.\n\n\n\n" -}, - -{ - "location": "stdlib/numbers.html#Core.Real", - "page": "Numbers", - "title": "Core.Real", - "category": "type", - "text": "Real <: Number\n\nAbstract supertype for all real numbers.\n\n\n\n" -}, - -{ - "location": "stdlib/numbers.html#Core.AbstractFloat", - "page": "Numbers", - "title": "Core.AbstractFloat", - "category": "type", - "text": "AbstractFloat <: Real\n\nAbstract supertype for all floating point numbers.\n\n\n\n" -}, - -{ - "location": "stdlib/numbers.html#Core.Integer", - "page": "Numbers", - "title": "Core.Integer", - "category": "type", - "text": "Integer <: Real\n\nAbstract supertype for all integers.\n\n\n\n" -}, - -{ - "location": "stdlib/numbers.html#Core.Signed", - "page": "Numbers", - "title": "Core.Signed", - "category": "type", - "text": "Signed <: Integer\n\nAbstract supertype for all signed integers.\n\n\n\n" -}, - -{ - "location": "stdlib/numbers.html#Core.Unsigned", - "page": "Numbers", - "title": "Core.Unsigned", - "category": "type", - "text": "Unsigned <: Integer\n\nAbstract supertype for all unsigned integers.\n\n\n\n" -}, - -{ - "location": "stdlib/numbers.html#Abstract-number-types-1", - "page": "Numbers", - "title": "Abstract number types", - "category": "section", - "text": "Core.Number\nCore.Real\nCore.AbstractFloat\nCore.Integer\nCore.Signed\nCore.Unsigned" -}, - -{ - "location": "stdlib/numbers.html#Core.Float16", - "page": "Numbers", - "title": "Core.Float16", - "category": "type", - "text": "Float16 <: AbstractFloat\n\n16-bit floating point number type.\n\n\n\n" -}, - -{ - "location": "stdlib/numbers.html#Core.Float32", - "page": "Numbers", - "title": "Core.Float32", - "category": "type", - "text": "Float32 <: AbstractFloat\n\n32-bit floating point number type.\n\n\n\n" -}, - -{ - "location": "stdlib/numbers.html#Core.Float64", - "page": "Numbers", - "title": "Core.Float64", - "category": "type", - "text": "Float64 <: AbstractFloat\n\n64-bit floating point number type.\n\n\n\n" -}, - -{ - "location": "stdlib/numbers.html#Base.MPFR.BigFloat", - "page": "Numbers", - "title": "Base.MPFR.BigFloat", - "category": "type", - "text": "BigFloat <: AbstractFloat\n\nArbitrary precision floating point number type.\n\n\n\n" -}, - -{ - "location": "stdlib/numbers.html#Core.Bool", - "page": "Numbers", - "title": "Core.Bool", - "category": "type", - "text": "Bool <: Integer\n\nBoolean type.\n\n\n\n" -}, - -{ - "location": "stdlib/numbers.html#Core.Int8", - "page": "Numbers", - "title": "Core.Int8", - "category": "type", - "text": "Int8 <: Signed\n\n8-bit signed integer type.\n\n\n\n" -}, - -{ - "location": "stdlib/numbers.html#Core.UInt8", - "page": "Numbers", - "title": "Core.UInt8", - "category": "type", - "text": "UInt8 <: Unsigned\n\n8-bit unsigned integer type.\n\n\n\n" -}, - -{ - "location": "stdlib/numbers.html#Core.Int16", - "page": "Numbers", - "title": "Core.Int16", - "category": "type", - "text": "Int16 <: Signed\n\n16-bit signed integer type.\n\n\n\n" -}, - -{ - "location": "stdlib/numbers.html#Core.UInt16", - "page": "Numbers", - "title": "Core.UInt16", - "category": "type", - "text": "UInt16 <: Unsigned\n\n16-bit unsigned integer type.\n\n\n\n" -}, - -{ - "location": "stdlib/numbers.html#Core.Int32", - "page": "Numbers", - "title": "Core.Int32", - "category": "type", - "text": "Int32 <: Signed\n\n32-bit signed integer type.\n\n\n\n" -}, - -{ - "location": "stdlib/numbers.html#Core.UInt32", - "page": "Numbers", - "title": "Core.UInt32", - "category": "type", - "text": "UInt32 <: Unsigned\n\n32-bit unsigned integer type.\n\n\n\n" -}, - -{ - "location": "stdlib/numbers.html#Core.Int64", - "page": "Numbers", - "title": "Core.Int64", - "category": "type", - "text": "Int64 <: Signed\n\n64-bit signed integer type.\n\n\n\n" -}, - -{ - "location": "stdlib/numbers.html#Core.UInt64", - "page": "Numbers", - "title": "Core.UInt64", - "category": "type", - "text": "UInt64 <: Unsigned\n\n64-bit unsigned integer type.\n\n\n\n" -}, - -{ - "location": "stdlib/numbers.html#Core.Int128", - "page": "Numbers", - "title": "Core.Int128", - "category": "type", - "text": "Int128 <: Signed\n\n128-bit signed integer type.\n\n\n\n" -}, - -{ - "location": "stdlib/numbers.html#Core.UInt128", - "page": "Numbers", - "title": "Core.UInt128", - "category": "type", - "text": "UInt128 <: Unsigned\n\n128-bit unsigned integer type.\n\n\n\n" -}, - -{ - "location": "stdlib/numbers.html#Base.GMP.BigInt", - "page": "Numbers", - "title": "Base.GMP.BigInt", - "category": "type", - "text": "BigInt <: Integer\n\nArbitrary precision integer type.\n\n\n\n" -}, - -{ - "location": "stdlib/numbers.html#Base.Complex", - "page": "Numbers", - "title": "Base.Complex", - "category": "type", - "text": "Complex{T<:Real} <: Number\n\nComplex number type with real and imaginary part of type T.\n\nComplex32, Complex64 and Complex128 are aliases for Complex{Float16}, Complex{Float32} and Complex{Float64} respectively.\n\n\n\n" -}, - -{ - "location": "stdlib/numbers.html#Base.Rational", - "page": "Numbers", - "title": "Base.Rational", - "category": "type", - "text": "Rational{T<:Integer} <: Real\n\nRational number type, with numerator and denominator of type T.\n\n\n\n" -}, - -{ - "location": "stdlib/numbers.html#Base.Irrational", - "page": "Numbers", - "title": "Base.Irrational", - "category": "type", - "text": "Irrational <: Real\n\nIrrational number type.\n\n\n\n" -}, - -{ - "location": "stdlib/numbers.html#Concrete-number-types-1", - "page": "Numbers", - "title": "Concrete number types", - "category": "section", - "text": "Core.Float16\nCore.Float32\nCore.Float64\nBase.BigFloat\nCore.Bool\nCore.Int8\nCore.UInt8\nCore.Int16\nCore.UInt16\nCore.Int32\nCore.UInt32\nCore.Int64\nCore.UInt64\nCore.Int128\nCore.UInt128\nBase.BigInt\nBase.Complex\nBase.Rational\nBase.Irrational" -}, - -{ - "location": "stdlib/numbers.html#Base.bin", - "page": "Numbers", - "title": "Base.bin", - "category": "function", - "text": "bin(n, pad::Int=1)\n\nConvert an integer to a binary string, optionally specifying a number of digits to pad to.\n\njulia> bin(10,2)\n\"1010\"\n\njulia> bin(10,8)\n\"00001010\"\n\n\n\n" -}, - -{ - "location": "stdlib/numbers.html#Base.hex", - "page": "Numbers", - "title": "Base.hex", - "category": "function", - "text": "hex(n, pad::Int=1)\n\nConvert an integer to a hexadecimal string, optionally specifying a number of digits to pad to.\n\njulia> hex(20)\n\"14\"\n\njulia> hex(20, 3)\n\"014\"\n\n\n\n" -}, - -{ - "location": "stdlib/numbers.html#Base.dec", - "page": "Numbers", - "title": "Base.dec", - "category": "function", - "text": "dec(n, pad::Int=1)\n\nConvert an integer to a decimal string, optionally specifying a number of digits to pad to.\n\nExamples\n\njulia> dec(20)\n\"20\"\n\njulia> dec(20, 3)\n\"020\"\n\n\n\n" -}, - -{ - "location": "stdlib/numbers.html#Base.oct", - "page": "Numbers", - "title": "Base.oct", - "category": "function", - "text": "oct(n, pad::Int=1)\n\nConvert an integer to an octal string, optionally specifying a number of digits to pad to.\n\njulia> oct(20)\n\"24\"\n\njulia> oct(20, 3)\n\"024\"\n\n\n\n" -}, - -{ - "location": "stdlib/numbers.html#Base.base", - "page": "Numbers", - "title": "Base.base", - "category": "function", - "text": "base(base::Integer, n::Integer, pad::Integer=1)\n\nConvert an integer n to a string in the given base, optionally specifying a number of digits to pad to.\n\njulia> base(13,5,4)\n\"0005\"\n\njulia> base(5,13,4)\n\"0023\"\n\n\n\n" -}, - -{ - "location": "stdlib/numbers.html#Base.digits", - "page": "Numbers", - "title": "Base.digits", - "category": "function", - "text": "digits([T<:Integer], n::Integer, base::T=10, pad::Integer=1)\n\nReturns an array with element type T (default Int) of the digits of n in the given base, optionally padded with zeros to a specified size. More significant digits are at higher indexes, such that n == sum([digits[k]*base^(k-1) for k=1:length(digits)]).\n\nExamples\n\njulia> digits(10, 10)\n2-element Array{Int64,1}:\n 0\n 1\n\njulia> digits(10, 2)\n4-element Array{Int64,1}:\n 0\n 1\n 0\n 1\n\njulia> digits(10, 2, 6)\n6-element Array{Int64,1}:\n 0\n 1\n 0\n 1\n 0\n 0\n\n\n\n" -}, - -{ - "location": "stdlib/numbers.html#Base.digits!", - "page": "Numbers", - "title": "Base.digits!", - "category": "function", - "text": "digits!(array, n::Integer, base::Integer=10)\n\nFills an array of the digits of n in the given base. More significant digits are at higher indexes. If the array length is insufficient, the least significant digits are filled up to the array length. If the array length is excessive, the excess portion is filled with zeros.\n\nExamples\n\njulia> digits!([2,2,2,2], 10, 2)\n4-element Array{Int64,1}:\n 0\n 1\n 0\n 1\n\njulia> digits!([2,2,2,2,2,2], 10, 2)\n6-element Array{Int64,1}:\n 0\n 1\n 0\n 1\n 0\n 0\n\n\n\n" -}, - -{ - "location": "stdlib/numbers.html#Base.bits", - "page": "Numbers", - "title": "Base.bits", - "category": "function", - "text": "bits(n)\n\nA string giving the literal bit representation of a number.\n\nExample\n\njulia> bits(4)\n\"0000000000000000000000000000000000000000000000000000000000000100\"\n\njulia> bits(2.2)\n\"0100000000000001100110011001100110011001100110011001100110011010\"\n\n\n\n" -}, - -{ - "location": "stdlib/numbers.html#Base.parse-Tuple{Type,Any,Any}", - "page": "Numbers", - "title": "Base.parse", - "category": "method", - "text": "parse(type, str, [base])\n\nParse a string as a number. If the type is an integer type, then a base can be specified (the default is 10). If the type is a floating point type, the string is parsed as a decimal floating point number. If the string does not contain a valid number, an error is raised.\n\njulia> parse(Int, \"1234\")\n1234\n\njulia> parse(Int, \"1234\", 5)\n194\n\njulia> parse(Int, \"afc\", 16)\n2812\n\njulia> parse(Float64, \"1.2e-3\")\n0.0012\n\n\n\n" -}, - -{ - "location": "stdlib/numbers.html#Base.tryparse", - "page": "Numbers", - "title": "Base.tryparse", - "category": "function", - "text": "tryparse(type, str, [base])\n\nLike parse, but returns a Nullable of the requested type. The result will be null if the string does not contain a valid number.\n\n\n\n" -}, - -{ - "location": "stdlib/numbers.html#Base.big", - "page": "Numbers", - "title": "Base.big", - "category": "function", - "text": "big(x)\n\nConvert a number to a maximum precision representation (typically BigInt or BigFloat). See BigFloat for information about some pitfalls with floating-point numbers.\n\n\n\n" -}, - -{ - "location": "stdlib/numbers.html#Base.signed", - "page": "Numbers", - "title": "Base.signed", - "category": "function", - "text": "signed(x)\n\nConvert a number to a signed integer. If the argument is unsigned, it is reinterpreted as signed without checking for overflow.\n\n\n\n" -}, - -{ - "location": "stdlib/numbers.html#Base.unsigned", - "page": "Numbers", - "title": "Base.unsigned", - "category": "function", - "text": "unsigned(x) -> Unsigned\n\nConvert a number to an unsigned integer. If the argument is signed, it is reinterpreted as unsigned without checking for negative values.\n\nExamples\n\njulia> unsigned(-2)\n0xfffffffffffffffe\n\njulia> unsigned(2)\n0x0000000000000002\n\njulia> signed(unsigned(-2))\n-2\n\n\n\n" -}, - -{ - "location": "stdlib/numbers.html#Base.float-Tuple{Any}", - "page": "Numbers", - "title": "Base.float", - "category": "method", - "text": "float(x)\n\nConvert a number or array to a floating point data type. When passed a string, this function is equivalent to parse(Float64, x).\n\n\n\n" -}, - -{ - "location": "stdlib/numbers.html#Base.Math.significand", - "page": "Numbers", - "title": "Base.Math.significand", - "category": "function", - "text": "significand(x)\n\nExtract the significand(s) (a.k.a. mantissa), in binary representation, of a floating-point number. If x is a non-zero finite number, then the result will be a number of the same type on the interval 12). Otherwise x is returned.\n\nExamples\n\njulia> significand(15.2)/15.2\n0.125\n\njulia> significand(15.2)*8\n15.2\n\n\n\n" -}, - -{ - "location": "stdlib/numbers.html#Base.Math.exponent", - "page": "Numbers", - "title": "Base.Math.exponent", - "category": "function", - "text": "exponent(x) -> Int\n\nGet the exponent of a normalized floating-point number.\n\n\n\n" -}, - -{ - "location": "stdlib/numbers.html#Base.complex-Tuple{Complex}", - "page": "Numbers", - "title": "Base.complex", - "category": "method", - "text": "complex(r, [i])\n\nConvert real numbers or arrays to complex. i defaults to zero.\n\n\n\n" -}, - -{ - "location": "stdlib/numbers.html#Base.bswap", - "page": "Numbers", - "title": "Base.bswap", - "category": "function", - "text": "bswap(n)\n\nByte-swap an integer. Flip the bits of its binary representation.\n\nExamples\n\njulia> a = bswap(4)\n288230376151711744\n\njulia> bswap(a)\n4\n\njulia> bin(1)\n\"1\"\n\njulia> bin(bswap(1))\n\"100000000000000000000000000000000000000000000000000000000\"\n\n\n\n" -}, - -{ - "location": "stdlib/numbers.html#Base.num2hex", - "page": "Numbers", - "title": "Base.num2hex", - "category": "function", - "text": "num2hex(f)\n\nGet a hexadecimal string of the binary representation of a floating point number.\n\nExample\n\njulia> num2hex(2.2)\n\"400199999999999a\"\n\n\n\n" -}, - -{ - "location": "stdlib/numbers.html#Base.hex2num", - "page": "Numbers", - "title": "Base.hex2num", - "category": "function", - "text": "hex2num(str)\n\nConvert a hexadecimal string to the floating point number it represents.\n\n\n\n" -}, - -{ - "location": "stdlib/numbers.html#Base.hex2bytes", - "page": "Numbers", - "title": "Base.hex2bytes", - "category": "function", - "text": "hex2bytes(s::AbstractString)\n\nConvert an arbitrarily long hexadecimal string to its binary representation. Returns an Array{UInt8,1}, i.e. an array of bytes.\n\njulia> a = hex(12345)\n\"3039\"\n\njulia> hex2bytes(a)\n2-element Array{UInt8,1}:\n 0x30\n 0x39\n\n\n\n" -}, - -{ - "location": "stdlib/numbers.html#Base.bytes2hex", - "page": "Numbers", - "title": "Base.bytes2hex", - "category": "function", - "text": "bytes2hex(bin_arr::Array{UInt8, 1}) -> String\n\nConvert an array of bytes to its hexadecimal representation. All characters are in lower-case.\n\njulia> a = hex(12345)\n\"3039\"\n\njulia> b = hex2bytes(a)\n2-element Array{UInt8,1}:\n 0x30\n 0x39\n\njulia> bytes2hex(b)\n\"3039\"\n\n\n\n" -}, - -{ - "location": "stdlib/numbers.html#Data-Formats-1", - "page": "Numbers", - "title": "Data Formats", - "category": "section", - "text": "Base.bin\nBase.hex\nBase.dec\nBase.oct\nBase.base\nBase.digits\nBase.digits!\nBase.bits\nBase.parse(::Type, ::Any, ::Any)\nBase.tryparse\nBase.big\nBase.signed\nBase.unsigned\nBase.float(::Any)\nBase.Math.significand\nBase.Math.exponent\nBase.complex(::Complex)\nBase.bswap\nBase.num2hex\nBase.hex2num\nBase.hex2bytes\nBase.bytes2hex" -}, - -{ - "location": "stdlib/numbers.html#Base.one", - "page": "Numbers", - "title": "Base.one", - "category": "function", - "text": "one(x)\none(T::type)\n\nReturn a multiplicative identity for x: a value such that one(x)*x == x*one(x) == x. Alternatively one(T) can take a type T, in which case one returns a multiplicative identity for any x of type T.\n\nIf possible, one(x) returns a value of the same type as x, and one(T) returns a value of type T. However, this may not be the case for types representing dimensionful quantities (e.g. time in days), since the multiplicative identity must be dimensionless. In that case, one(x) should return an identity value of the same precision (and shape, for matrices) as x.\n\nIf you want a quantity that is of the same type as x, or of type T, even if x is dimensionful, use oneunit instead.\n\njulia> one(3.7)\n1.0\n\njulia> one(Int)\n1\n\njulia> one(Dates.Day(1))\n1\n\n\n\n" -}, - -{ - "location": "stdlib/numbers.html#Base.oneunit", - "page": "Numbers", - "title": "Base.oneunit", - "category": "function", - "text": "oneunit(x::T)\noneunit(T::Type)\n\nReturns T(one(x)), where T is either the type of the argument or (if a type is passed) the argument. This differs from one for dimensionful quantities: one is dimensionless (a multiplicative identity) while oneunit is dimensionful (of the same type as x, or of type T).\n\njulia> oneunit(3.7)\n1.0\n\njulia> oneunit(Dates.Day)\n1 day\n\n\n\n" -}, - -{ - "location": "stdlib/numbers.html#Base.zero", - "page": "Numbers", - "title": "Base.zero", - "category": "function", - "text": "zero(x)\n\nGet the additive identity element for the type of x (x can also specify the type itself).\n\njulia> zero(1)\n0\n\njulia> zero(big\"2.0\")\n0.000000000000000000000000000000000000000000000000000000000000000000000000000000\n\njulia> zero(rand(2,2))\n2×2 Array{Float64,2}:\n 0.0 0.0\n 0.0 0.0\n\n\n\n" -}, - -{ - "location": "stdlib/numbers.html#Base.pi", - "page": "Numbers", - "title": "Base.pi", - "category": "constant", - "text": "pi\nπ\n\nThe constant pi.\n\njulia> pi\nπ = 3.1415926535897...\n\n\n\n" -}, - -{ - "location": "stdlib/numbers.html#Base.im", - "page": "Numbers", - "title": "Base.im", - "category": "constant", - "text": "im\n\nThe imaginary unit.\n\n\n\n" -}, - -{ - "location": "stdlib/numbers.html#Base.eu", - "page": "Numbers", - "title": "Base.eu", - "category": "constant", - "text": "e\neu\n\nThe constant e.\n\njulia> e\ne = 2.7182818284590...\n\n\n\n" -}, - -{ - "location": "stdlib/numbers.html#Base.catalan", - "page": "Numbers", - "title": "Base.catalan", - "category": "constant", - "text": "catalan\n\nCatalan\'s constant.\n\njulia> catalan\ncatalan = 0.9159655941772...\n\n\n\n" -}, - -{ - "location": "stdlib/numbers.html#Base.eulergamma", - "page": "Numbers", - "title": "Base.eulergamma", - "category": "constant", - "text": "γ\neulergamma\n\nEuler\'s constant.\n\njulia> eulergamma\nγ = 0.5772156649015...\n\n\n\n" -}, - -{ - "location": "stdlib/numbers.html#Base.golden", - "page": "Numbers", - "title": "Base.golden", - "category": "constant", - "text": "φ\ngolden\n\nThe golden ratio.\n\njulia> golden\nφ = 1.6180339887498...\n\n\n\n" -}, - -{ - "location": "stdlib/numbers.html#Base.Inf", - "page": "Numbers", - "title": "Base.Inf", - "category": "constant", - "text": "Inf\n\nPositive infinity of type Float64.\n\n\n\n" -}, - -{ - "location": "stdlib/numbers.html#Base.Inf32", - "page": "Numbers", - "title": "Base.Inf32", - "category": "constant", - "text": "Inf32\n\nPositive infinity of type Float32.\n\n\n\n" -}, - -{ - "location": "stdlib/numbers.html#Base.Inf16", - "page": "Numbers", - "title": "Base.Inf16", - "category": "constant", - "text": "Inf16\n\nPositive infinity of type Float16.\n\n\n\n" -}, - -{ - "location": "stdlib/numbers.html#Base.NaN", - "page": "Numbers", - "title": "Base.NaN", - "category": "constant", - "text": "NaN\n\nA not-a-number value of type Float64.\n\n\n\n" -}, - -{ - "location": "stdlib/numbers.html#Base.NaN32", - "page": "Numbers", - "title": "Base.NaN32", - "category": "constant", - "text": "NaN32\n\nA not-a-number value of type Float32.\n\n\n\n" -}, - -{ - "location": "stdlib/numbers.html#Base.NaN16", - "page": "Numbers", - "title": "Base.NaN16", - "category": "constant", - "text": "NaN16\n\nA not-a-number value of type Float16.\n\n\n\n" -}, - -{ - "location": "stdlib/numbers.html#Base.issubnormal", - "page": "Numbers", - "title": "Base.issubnormal", - "category": "function", - "text": "issubnormal(f) -> Bool\n\nTest whether a floating point number is subnormal.\n\n\n\n" -}, - -{ - "location": "stdlib/numbers.html#Base.isfinite", - "page": "Numbers", - "title": "Base.isfinite", - "category": "function", - "text": "isfinite(f) -> Bool\n\nTest whether a number is finite.\n\njulia> isfinite(5)\ntrue\n\njulia> isfinite(NaN32)\nfalse\n\n\n\n" -}, - -{ - "location": "stdlib/numbers.html#Base.isinf", - "page": "Numbers", - "title": "Base.isinf", - "category": "function", - "text": "isinf(f) -> Bool\n\nTest whether a number is infinite.\n\n\n\n" -}, - -{ - "location": "stdlib/numbers.html#Base.isnan", - "page": "Numbers", - "title": "Base.isnan", - "category": "function", - "text": "isnan(f) -> Bool\n\nTest whether a floating point number is not a number (NaN).\n\n\n\n" -}, - -{ - "location": "stdlib/numbers.html#Base.iszero", - "page": "Numbers", - "title": "Base.iszero", - "category": "function", - "text": "iszero(x)\n\nReturn true if x == zero(x); if x is an array, this checks whether all of the elements of x are zero.\n\n\n\n" -}, - -{ - "location": "stdlib/numbers.html#Base.nextfloat", - "page": "Numbers", - "title": "Base.nextfloat", - "category": "function", - "text": "nextfloat(x::AbstractFloat, n::Integer)\n\nThe result of n iterative applications of nextfloat to x if n >= 0, or -n applications of prevfloat if n < 0.\n\n\n\nnextfloat(x::AbstractFloat)\n\nReturns the smallest floating point number y of the same type as x such x < y. If no such y exists (e.g. if x is Inf or NaN), then returns x.\n\n\n\n" -}, - -{ - "location": "stdlib/numbers.html#Base.prevfloat", - "page": "Numbers", - "title": "Base.prevfloat", - "category": "function", - "text": "prevfloat(x::AbstractFloat)\n\nReturns the largest floating point number y of the same type as x such y < x. If no such y exists (e.g. if x is -Inf or NaN), then returns x.\n\n\n\n" -}, - -{ - "location": "stdlib/numbers.html#Base.isinteger", - "page": "Numbers", - "title": "Base.isinteger", - "category": "function", - "text": "isinteger(x) -> Bool\n\nTest whether x is numerically equal to some integer.\n\njulia> isinteger(4.0)\ntrue\n\n\n\n" -}, - -{ - "location": "stdlib/numbers.html#Base.isreal", - "page": "Numbers", - "title": "Base.isreal", - "category": "function", - "text": "isreal(x) -> Bool\n\nTest whether x or all its elements are numerically equal to some real number.\n\njulia> isreal(5.)\ntrue\n\njulia> isreal([4.; complex(0,1)])\nfalse\n\n\n\n" -}, - -{ - "location": "stdlib/numbers.html#Core.Float32-Tuple{Any}", - "page": "Numbers", - "title": "Core.Float32", - "category": "method", - "text": "Float32(x [, mode::RoundingMode])\n\nCreate a Float32 from x. If x is not exactly representable then mode determines how x is rounded.\n\nExamples\n\njulia> Float32(1/3, RoundDown)\n0.3333333f0\n\njulia> Float32(1/3, RoundUp)\n0.33333334f0\n\nSee RoundingMode for available rounding modes.\n\n\n\n" -}, - -{ - "location": "stdlib/numbers.html#Core.Float64-Tuple{Any}", - "page": "Numbers", - "title": "Core.Float64", - "category": "method", - "text": "Float64(x [, mode::RoundingMode])\n\nCreate a Float64 from x. If x is not exactly representable then mode determines how x is rounded.\n\nExamples\n\njulia> Float64(pi, RoundDown)\n3.141592653589793\n\njulia> Float64(pi, RoundUp)\n3.1415926535897936\n\nSee RoundingMode for available rounding modes.\n\n\n\n" -}, - -{ - "location": "stdlib/numbers.html#Base.GMP.BigInt-Tuple{Any}", - "page": "Numbers", - "title": "Base.GMP.BigInt", - "category": "method", - "text": "BigInt(x)\n\nCreate an arbitrary precision integer. x may be an Int (or anything that can be converted to an Int). The usual mathematical operators are defined for this type, and results are promoted to a BigInt.\n\nInstances can be constructed from strings via parse, or using the big string literal.\n\njulia> parse(BigInt, \"42\")\n42\n\njulia> big\"313\"\n313\n\n\n\n" -}, - -{ - "location": "stdlib/numbers.html#Base.MPFR.BigFloat-Tuple{Any}", - "page": "Numbers", - "title": "Base.MPFR.BigFloat", - "category": "method", - "text": "BigFloat(x)\n\nCreate an arbitrary precision floating point number. x may be an Integer, a Float64 or a BigInt. The usual mathematical operators are defined for this type, and results are promoted to a BigFloat.\n\nNote that because decimal literals are converted to floating point numbers when parsed, BigFloat(2.1) may not yield what you expect. You may instead prefer to initialize constants from strings via parse, or using the big string literal.\n\njulia> BigFloat(2.1)\n2.100000000000000088817841970012523233890533447265625000000000000000000000000000\n\njulia> big\"2.1\"\n2.099999999999999999999999999999999999999999999999999999999999999999999999999986\n\n\n\n" -}, - -{ - "location": "stdlib/numbers.html#Base.Rounding.rounding", - "page": "Numbers", - "title": "Base.Rounding.rounding", - "category": "function", - "text": "rounding(T)\n\nGet the current floating point rounding mode for type T, controlling the rounding of basic arithmetic functions (+, -, *, / and sqrt) and type conversion.\n\nSee RoundingMode for available modes.\n\n\n\n" -}, - -{ - "location": "stdlib/numbers.html#Base.Rounding.setrounding-Tuple{Type,Any}", - "page": "Numbers", - "title": "Base.Rounding.setrounding", - "category": "method", - "text": "setrounding(T, mode)\n\nSet the rounding mode of floating point type T, controlling the rounding of basic arithmetic functions (+, -, *, / and sqrt) and type conversion. Other numerical functions may give incorrect or invalid values when using rounding modes other than the default RoundNearest.\n\nNote that this may affect other types, for instance changing the rounding mode of Float64 will change the rounding mode of Float32. See RoundingMode for available modes.\n\nwarning: Warning\nThis feature is still experimental, and may give unexpected or incorrect values.\n\n\n\n" -}, - -{ - "location": "stdlib/numbers.html#Base.Rounding.setrounding-Tuple{Function,Type,RoundingMode}", - "page": "Numbers", - "title": "Base.Rounding.setrounding", - "category": "method", - "text": "setrounding(f::Function, T, mode)\n\nChange the rounding mode of floating point type T for the duration of f. It is logically equivalent to:\n\nold = rounding(T)\nsetrounding(T, mode)\nf()\nsetrounding(T, old)\n\nSee RoundingMode for available rounding modes.\n\nwarning: Warning\nThis feature is still experimental, and may give unexpected or incorrect values. A known problem is the interaction with compiler optimisations, e.g.julia> setrounding(Float64,RoundDown) do\n 1.1 + 0.1\n end\n1.2000000000000002Here the compiler is constant folding, that is evaluating a known constant expression at compile time, however the rounding mode is only changed at runtime, so this is not reflected in the function result. This can be avoided by moving constants outside the expression, e.g.julia> x = 1.1; y = 0.1;\n\njulia> setrounding(Float64,RoundDown) do\n x + y\n end\n1.2\n\n\n\n" -}, - -{ - "location": "stdlib/numbers.html#Base.Rounding.get_zero_subnormals", - "page": "Numbers", - "title": "Base.Rounding.get_zero_subnormals", - "category": "function", - "text": "get_zero_subnormals() -> Bool\n\nReturns false if operations on subnormal floating-point values (\"denormals\") obey rules for IEEE arithmetic, and true if they might be converted to zeros.\n\n\n\n" -}, - -{ - "location": "stdlib/numbers.html#Base.Rounding.set_zero_subnormals", - "page": "Numbers", - "title": "Base.Rounding.set_zero_subnormals", - "category": "function", - "text": "set_zero_subnormals(yes::Bool) -> Bool\n\nIf yes is false, subsequent floating-point operations follow rules for IEEE arithmetic on subnormal values (\"denormals\"). Otherwise, floating-point operations are permitted (but not required) to convert subnormal inputs or outputs to zero. Returns true unless yes==true but the hardware does not support zeroing of subnormal numbers.\n\nset_zero_subnormals(true) can speed up some computations on some hardware. However, it can break identities such as (x-y==0) == (x==y).\n\n\n\n" -}, - -{ - "location": "stdlib/numbers.html#General-Number-Functions-and-Constants-1", - "page": "Numbers", - "title": "General Number Functions and Constants", - "category": "section", - "text": "Base.one\nBase.oneunit\nBase.zero\nBase.pi\nBase.im\nBase.eu\nBase.catalan\nBase.eulergamma\nBase.golden\nBase.Inf\nBase.Inf32\nBase.Inf16\nBase.NaN\nBase.NaN32\nBase.NaN16\nBase.issubnormal\nBase.isfinite\nBase.isinf\nBase.isnan\nBase.iszero\nBase.nextfloat\nBase.prevfloat\nBase.isinteger\nBase.isreal\nCore.Float32(::Any)\nCore.Float64(::Any)\nBase.GMP.BigInt(::Any)\nBase.MPFR.BigFloat(::Any)\nBase.Rounding.rounding\nBase.Rounding.setrounding(::Type, ::Any)\nBase.Rounding.setrounding(::Function, ::Type, ::RoundingMode)\nBase.Rounding.get_zero_subnormals\nBase.Rounding.set_zero_subnormals" -}, - -{ - "location": "stdlib/numbers.html#Base.count_ones", - "page": "Numbers", - "title": "Base.count_ones", - "category": "function", - "text": "count_ones(x::Integer) -> Integer\n\nNumber of ones in the binary representation of x.\n\njulia> count_ones(7)\n3\n\n\n\n" -}, - -{ - "location": "stdlib/numbers.html#Base.count_zeros", - "page": "Numbers", - "title": "Base.count_zeros", - "category": "function", - "text": "count_zeros(x::Integer) -> Integer\n\nNumber of zeros in the binary representation of x.\n\njulia> count_zeros(Int32(2 ^ 16 - 1))\n16\n\n\n\n" -}, - -{ - "location": "stdlib/numbers.html#Base.leading_zeros", - "page": "Numbers", - "title": "Base.leading_zeros", - "category": "function", - "text": "leading_zeros(x::Integer) -> Integer\n\nNumber of zeros leading the binary representation of x.\n\njulia> leading_zeros(Int32(1))\n31\n\n\n\n" -}, - -{ - "location": "stdlib/numbers.html#Base.leading_ones", - "page": "Numbers", - "title": "Base.leading_ones", - "category": "function", - "text": "leading_ones(x::Integer) -> Integer\n\nNumber of ones leading the binary representation of x.\n\njulia> leading_ones(UInt32(2 ^ 32 - 2))\n31\n\n\n\n" -}, - -{ - "location": "stdlib/numbers.html#Base.trailing_zeros", - "page": "Numbers", - "title": "Base.trailing_zeros", - "category": "function", - "text": "trailing_zeros(x::Integer) -> Integer\n\nNumber of zeros trailing the binary representation of x.\n\njulia> trailing_zeros(2)\n1\n\n\n\n" -}, - -{ - "location": "stdlib/numbers.html#Base.trailing_ones", - "page": "Numbers", - "title": "Base.trailing_ones", - "category": "function", - "text": "trailing_ones(x::Integer) -> Integer\n\nNumber of ones trailing the binary representation of x.\n\njulia> trailing_ones(3)\n2\n\n\n\n" -}, - -{ - "location": "stdlib/numbers.html#Base.isodd", - "page": "Numbers", - "title": "Base.isodd", - "category": "function", - "text": "isodd(x::Integer) -> Bool\n\nReturns true if x is odd (that is, not divisible by 2), and false otherwise.\n\njulia> isodd(9)\ntrue\n\njulia> isodd(10)\nfalse\n\n\n\n" -}, - -{ - "location": "stdlib/numbers.html#Base.iseven", - "page": "Numbers", - "title": "Base.iseven", - "category": "function", - "text": "iseven(x::Integer) -> Bool\n\nReturns true is x is even (that is, divisible by 2), and false otherwise.\n\njulia> iseven(9)\nfalse\n\njulia> iseven(10)\ntrue\n\n\n\n" -}, - -{ - "location": "stdlib/numbers.html#Integers-1", - "page": "Numbers", - "title": "Integers", - "category": "section", - "text": "Base.count_ones\nBase.count_zeros\nBase.leading_zeros\nBase.leading_ones\nBase.trailing_zeros\nBase.trailing_ones\nBase.isodd\nBase.iseven" -}, - -{ - "location": "stdlib/numbers.html#Base.precision", - "page": "Numbers", - "title": "Base.precision", - "category": "function", - "text": "precision(num::AbstractFloat)\n\nGet the precision of a floating point number, as defined by the effective number of bits in the mantissa.\n\n\n\n" -}, - -{ - "location": "stdlib/numbers.html#Base.precision-Tuple{Type{BigFloat}}", - "page": "Numbers", - "title": "Base.precision", - "category": "method", - "text": "precision(BigFloat)\n\nGet the precision (in bits) currently used for BigFloat arithmetic.\n\n\n\n" -}, - -{ - "location": "stdlib/numbers.html#Base.MPFR.setprecision", - "page": "Numbers", - "title": "Base.MPFR.setprecision", - "category": "function", - "text": "setprecision([T=BigFloat,] precision::Int)\n\nSet the precision (in bits) to be used for T arithmetic.\n\n\n\nsetprecision(f::Function, [T=BigFloat,] precision::Integer)\n\nChange the T arithmetic precision (in bits) for the duration of f. It is logically equivalent to:\n\nold = precision(BigFloat)\nsetprecision(BigFloat, precision)\nf()\nsetprecision(BigFloat, old)\n\nOften used as setprecision(T, precision) do ... end\n\n\n\n" -}, - -{ - "location": "stdlib/numbers.html#Base.MPFR.BigFloat-Tuple{Any,Int64}", - "page": "Numbers", - "title": "Base.MPFR.BigFloat", - "category": "method", - "text": "BigFloat(x, prec::Int)\n\nCreate a representation of x as a BigFloat with precision prec.\n\n\n\n" -}, - -{ - "location": "stdlib/numbers.html#Base.MPFR.BigFloat-Tuple{Union{AbstractFloat, Integer, String},RoundingMode}", - "page": "Numbers", - "title": "Base.MPFR.BigFloat", - "category": "method", - "text": "BigFloat(x, rounding::RoundingMode)\n\nCreate a representation of x as a BigFloat with the current global precision and rounding mode rounding.\n\n\n\n" -}, - -{ - "location": "stdlib/numbers.html#Base.MPFR.BigFloat-Tuple{Any,Int64,RoundingMode}", - "page": "Numbers", - "title": "Base.MPFR.BigFloat", - "category": "method", - "text": "BigFloat(x, prec::Int, rounding::RoundingMode)\n\nCreate a representation of x as a BigFloat with precision prec and rounding mode rounding.\n\n\n\n" -}, - -{ - "location": "stdlib/numbers.html#Base.MPFR.BigFloat-Tuple{String}", - "page": "Numbers", - "title": "Base.MPFR.BigFloat", - "category": "method", - "text": "BigFloat(x::String)\n\nCreate a representation of the string x as a BigFloat.\n\n\n\n" -}, - -{ - "location": "stdlib/numbers.html#BigFloats-1", - "page": "Numbers", - "title": "BigFloats", - "category": "section", - "text": "The BigFloat type implements arbitrary-precision floating-point arithmetic using the GNU MPFR library.Base.precision\nBase.MPFR.precision(::Type{BigFloat})\nBase.MPFR.setprecision\nBase.MPFR.BigFloat(x, prec::Int)\nBigFloat(x::Union{Integer, AbstractFloat, String}, rounding::RoundingMode)\nBase.MPFR.BigFloat(x, prec::Int, rounding::RoundingMode)\nBase.MPFR.BigFloat(x::String)" -}, - -{ - "location": "stdlib/numbers.html#Base.Random.srand", - "page": "Numbers", - "title": "Base.Random.srand", - "category": "function", - "text": "srand([rng=GLOBAL_RNG], [seed]) -> rng\nsrand([rng=GLOBAL_RNG], filename, n=4) -> rng\n\nReseed the random number generator. If a seed is provided, the RNG will give a reproducible sequence of numbers, otherwise Julia will get entropy from the system. For MersenneTwister, the seed may be a non-negative integer, a vector of UInt32 integers or a filename, in which case the seed is read from a file (4n bytes are read from the file, where n is an optional argument). RandomDevice does not support seeding.\n\n\n\n" -}, - -{ - "location": "stdlib/numbers.html#Base.Random.MersenneTwister", - "page": "Numbers", - "title": "Base.Random.MersenneTwister", - "category": "type", - "text": "MersenneTwister(seed)\n\nCreate a MersenneTwister RNG object. Different RNG objects can have their own seeds, which may be useful for generating different streams of random numbers.\n\nExample\n\njulia> rng = MersenneTwister(1234);\n\n\n\n" -}, - -{ - "location": "stdlib/numbers.html#Base.Random.RandomDevice", - "page": "Numbers", - "title": "Base.Random.RandomDevice", - "category": "type", - "text": "RandomDevice()\n\nCreate a RandomDevice RNG object. Two such objects will always generate different streams of random numbers.\n\n\n\n" -}, - -{ - "location": "stdlib/numbers.html#Base.Random.rand", - "page": "Numbers", - "title": "Base.Random.rand", - "category": "function", - "text": "rand([rng=GLOBAL_RNG], [S], [dims...])\n\nPick a random element or array of random elements from the set of values specified by S; S can be\n\nan indexable collection (for example 1:n or [\'x\',\'y\',\'z\']), or\na type: the set of values to pick from is then equivalent to typemin(S):typemax(S) for integers (this is not applicable to BigInt), and to 0 1) for floating point numbers;\n\nS defaults to Float64.\n\n\n\n" -}, - -{ - "location": "stdlib/numbers.html#Base.Random.rand!", - "page": "Numbers", - "title": "Base.Random.rand!", - "category": "function", - "text": "rand!([rng=GLOBAL_RNG], A, [coll])\n\nPopulate the array A with random values. If the indexable collection coll is specified, the values are picked randomly from coll. This is equivalent to copy!(A, rand(rng, coll, size(A))) or copy!(A, rand(rng, eltype(A), size(A))) but without allocating a new array.\n\nExample\n\njulia> rng = MersenneTwister(1234);\n\njulia> rand!(rng, zeros(5))\n5-element Array{Float64,1}:\n 0.590845\n 0.766797\n 0.566237\n 0.460085\n 0.794026\n\n\n\n" -}, - -{ - "location": "stdlib/numbers.html#Base.Random.bitrand", - "page": "Numbers", - "title": "Base.Random.bitrand", - "category": "function", - "text": "bitrand([rng=GLOBAL_RNG], [dims...])\n\nGenerate a BitArray of random boolean values.\n\nExample\n\njulia> rng = MersenneTwister(1234);\n\njulia> bitrand(rng, 10)\n10-element BitArray{1}:\n true\n true\n true\n false\n true\n false\n false\n true\n false\n true\n\n\n\n" -}, - -{ - "location": "stdlib/numbers.html#Base.Random.randn", - "page": "Numbers", - "title": "Base.Random.randn", - "category": "function", - "text": "randn([rng=GLOBAL_RNG], [T=Float64], [dims...])\n\nGenerate a normally-distributed random number of type T with mean 0 and standard deviation 1. Optionally generate an array of normally-distributed random numbers. The Base module currently provides an implementation for the types Float16, Float32, and Float64 (the default).\n\nExamples\n\njulia> rng = MersenneTwister(1234);\n\njulia> randn(rng, Float64)\n0.8673472019512456\n\njulia> randn(rng, Float32, (2, 4))\n2×4 Array{Float32,2}:\n -0.901744 -0.902914 2.21188 -0.271735\n -0.494479 0.864401 0.532813 0.502334\n\n\n\n" -}, - -{ - "location": "stdlib/numbers.html#Base.Random.randn!", - "page": "Numbers", - "title": "Base.Random.randn!", - "category": "function", - "text": "randn!([rng=GLOBAL_RNG], A::AbstractArray) -> A\n\nFill the array A with normally-distributed (mean 0, standard deviation 1) random numbers. Also see the rand function.\n\nExample\n\njulia> rng = MersenneTwister(1234);\n\njulia> randn!(rng, zeros(5))\n5-element Array{Float64,1}:\n 0.867347\n -0.901744\n -0.494479\n -0.902914\n 0.864401\n\n\n\n" -}, - -{ - "location": "stdlib/numbers.html#Base.Random.randexp", - "page": "Numbers", - "title": "Base.Random.randexp", - "category": "function", - "text": "randexp([rng=GLOBAL_RNG], [T=Float64], [dims...])\n\nGenerate a random number of type T according to the exponential distribution with scale 1. Optionally generate an array of such random numbers. The Base module currently provides an implementation for the types Float16, Float32, and Float64 (the default).\n\nExamples\n\njulia> rng = MersenneTwister(1234);\n\njulia> randexp(rng, Float32)\n2.4835055f0\n\njulia> randexp(rng, 3, 3)\n3×3 Array{Float64,2}:\n 1.5167 1.30652 0.344435\n 0.604436 2.78029 0.418516\n 0.695867 0.693292 0.643644\n\n\n\n" -}, - -{ - "location": "stdlib/numbers.html#Base.Random.randexp!", - "page": "Numbers", - "title": "Base.Random.randexp!", - "category": "function", - "text": "randexp!([rng=GLOBAL_RNG], A::AbstractArray) -> A\n\nFill the array A with random numbers following the exponential distribution (with scale 1).\n\nExample\n\njulia> rng = MersenneTwister(1234);\n\njulia> randexp!(rng, zeros(5))\n5-element Array{Float64,1}:\n 2.48351\n 1.5167\n 0.604436\n 0.695867\n 1.30652\n\n\n\n" -}, - -{ - "location": "stdlib/numbers.html#Base.Random.randjump", - "page": "Numbers", - "title": "Base.Random.randjump", - "category": "function", - "text": "randjump(r::MersenneTwister, jumps::Integer, [jumppoly::AbstractString=dSFMT.JPOLY1e21]) -> Vector{MersenneTwister}\n\nCreate an array of the size jumps of initialized MersenneTwister RNG objects. The first RNG object given as a parameter and following MersenneTwister RNGs in the array are initialized such that a state of the RNG object in the array would be moved forward (without generating numbers) from a previous RNG object array element on a particular number of steps encoded by the jump polynomial jumppoly.\n\nDefault jump polynomial moves forward MersenneTwister RNG state by 10^20 steps.\n\n\n\n" -}, - -{ - "location": "stdlib/numbers.html#Random-Numbers-1", - "page": "Numbers", - "title": "Random Numbers", - "category": "section", - "text": "Random number generation in Julia uses the Mersenne Twister library via MersenneTwister objects. Julia has a global RNG, which is used by default. Other RNG types can be plugged in by inheriting the AbstractRNG type; they can then be used to have multiple streams of random numbers. Besides MersenneTwister, Julia also provides the RandomDevice RNG type, which is a wrapper over the OS provided entropy.Most functions related to random generation accept an optional AbstractRNG as the first argument, rng , which defaults to the global one if not provided. Morever, some of them accept optionally dimension specifications dims... (which can be given as a tuple) to generate arrays of random values.A MersenneTwister or RandomDevice RNG can generate random numbers of the following types: Float16, Float32, Float64, Bool, Int8, UInt8, Int16, UInt16, Int32, UInt32, Int64, UInt64, Int128, UInt128, BigInt (or complex numbers of those types). Random floating point numbers are generated uniformly in 0 1). As BigInt represents unbounded integers, the interval must be specified (e.g. rand(big(1:6))).Base.Random.srand\nBase.Random.MersenneTwister\nBase.Random.RandomDevice\nBase.Random.rand\nBase.Random.rand!\nBase.Random.bitrand\nBase.Random.randn\nBase.Random.randn!\nBase.Random.randexp\nBase.Random.randexp!\nBase.Random.randjump" -}, - -{ - "location": "stdlib/strings.html#", - "page": "Strings", - "title": "Strings", - "category": "page", - "text": "" -}, - -{ - "location": "stdlib/strings.html#Base.length-Tuple{AbstractString}", - "page": "Strings", - "title": "Base.length", - "category": "method", - "text": "length(s::AbstractString)\n\nThe number of characters in string s.\n\nExample\n\njulia> length(\"jμΛIα\")\n5\n\n\n\n" -}, - -{ - "location": "stdlib/strings.html#Base.sizeof-Tuple{AbstractString}", - "page": "Strings", - "title": "Base.sizeof", - "category": "method", - "text": "sizeof(s::AbstractString)\n\nThe number of bytes in string s.\n\nExample\n\njulia> sizeof(\"❤\")\n3\n\n\n\n" -}, - -{ - "location": "stdlib/strings.html#Base.:*-Tuple{AbstractString,Vararg{Any,N} where N}", - "page": "Strings", - "title": "Base.:*", - "category": "method", - "text": "*(x, y...)\n\nMultiplication operator. x*y*z*... calls this function with all arguments, i.e. *(x, y, z, ...).\n\n\n\n" -}, - -{ - "location": "stdlib/strings.html#Base.:^-Tuple{AbstractString,Integer}", - "page": "Strings", - "title": "Base.:^", - "category": "method", - "text": "^(s::AbstractString, n::Integer)\n\nRepeat n times the string s. The repeat function is an alias to this operator.\n\njulia> \"Test \"^3\n\"Test Test Test \"\n\n\n\n" -}, - -{ - "location": "stdlib/strings.html#Base.string", - "page": "Strings", - "title": "Base.string", - "category": "function", - "text": "string(xs...)\n\nCreate a string from any values using the print function.\n\njulia> string(\"a\", 1, true)\n\"a1true\"\n\n\n\n" -}, - -{ - "location": "stdlib/strings.html#Base.repr", - "page": "Strings", - "title": "Base.repr", - "category": "function", - "text": "repr(x)\n\nCreate a string from any value using the showall function.\n\n\n\n" -}, - -{ - "location": "stdlib/strings.html#Core.String-Tuple{AbstractString}", - "page": "Strings", - "title": "Core.String", - "category": "method", - "text": "String(s::AbstractString)\n\nConvert a string to a contiguous byte array representation encoded as UTF-8 bytes. This representation is often appropriate for passing strings to C.\n\n\n\n" -}, - -{ - "location": "stdlib/strings.html#Base.transcode", - "page": "Strings", - "title": "Base.transcode", - "category": "function", - "text": "transcode(T, src)\n\nConvert string data between Unicode encodings. src is either a String or a Vector{UIntXX} of UTF-XX code units, where XX is 8, 16, or 32. T indicates the encoding of the return value: String to return a (UTF-8 encoded) String or UIntXX to return a Vector{UIntXX} of UTF-XX data. (The alias Cwchar_t can also be used as the integer type, for converting wchar_t* strings used by external C libraries.)\n\nThe transcode function succeeds as long as the input data can be reasonably represented in the target encoding; it always succeeds for conversions between UTF-XX encodings, even for invalid Unicode data.\n\nOnly conversion to/from UTF-8 is currently supported.\n\n\n\n" -}, - -{ - "location": "stdlib/strings.html#Base.unsafe_string", - "page": "Strings", - "title": "Base.unsafe_string", - "category": "function", - "text": "unsafe_string(p::Ptr{UInt8}, [length::Integer])\n\nCopy a string from the address of a C-style (NUL-terminated) string encoded as UTF-8. (The pointer can be safely freed afterwards.) If length is specified (the length of the data in bytes), the string does not have to be NUL-terminated.\n\nThis function is labelled \"unsafe\" because it will crash if p is not a valid memory address to data of the requested length.\n\n\n\n" -}, - -{ - "location": "stdlib/strings.html#Base.codeunit-Tuple{AbstractString,Integer}", - "page": "Strings", - "title": "Base.codeunit", - "category": "method", - "text": "codeunit(s::AbstractString, i::Integer)\n\nGet the ith code unit of an encoded string. For example, returns the ith byte of the representation of a UTF-8 string.\n\n\n\n" -}, - -{ - "location": "stdlib/strings.html#Base.ascii", - "page": "Strings", - "title": "Base.ascii", - "category": "function", - "text": "ascii(s::AbstractString)\n\nConvert a string to String type and check that it contains only ASCII data, otherwise throwing an ArgumentError indicating the position of the first non-ASCII byte.\n\njulia> ascii(\"abcdeγfgh\")\nERROR: ArgumentError: invalid ASCII at index 6 in \"abcdeγfgh\"\nStacktrace:\n [1] ascii(::String) at ./strings/util.jl:479\n\njulia> ascii(\"abcdefgh\")\n\"abcdefgh\"\n\n\n\n" -}, - -{ - "location": "stdlib/strings.html#Base.@r_str", - "page": "Strings", - "title": "Base.@r_str", - "category": "macro", - "text": "@r_str -> Regex\n\nConstruct a regex, such as r\"^[a-z]*$\". The regex also accepts one or more flags, listed after the ending quote, to change its behaviour:\n\ni enables case-insensitive matching\nm treats the ^ and $ tokens as matching the start and end of individual lines, as opposed to the whole string.\ns allows the . modifier to match newlines.\nx enables \"comment mode\": whitespace is enabled except when escaped with \\, and # is treated as starting a comment.\n\nFor example, this regex has all three flags enabled:\n\njulia> match(r\"a+.*b+.*?d$\"ism, \"Goodbye,\\nOh, angry,\\nBad world\\n\")\nRegexMatch(\"angry,\\nBad world\")\n\n\n\n" -}, - -{ - "location": "stdlib/strings.html#Base.Docs.@html_str", - "page": "Strings", - "title": "Base.Docs.@html_str", - "category": "macro", - "text": "@html_str -> Docs.HTML\n\nCreate an HTML object from a literal string.\n\n\n\n" -}, - -{ - "location": "stdlib/strings.html#Base.Docs.@text_str", - "page": "Strings", - "title": "Base.Docs.@text_str", - "category": "macro", - "text": "@text_str -> Docs.Text\n\nCreate a Text object from a literal string.\n\n\n\n" -}, - -{ - "location": "stdlib/strings.html#Base.UTF8proc.normalize_string", - "page": "Strings", - "title": "Base.UTF8proc.normalize_string", - "category": "function", - "text": "normalize_string(s::AbstractString, normalform::Symbol)\n\nNormalize the string s according to one of the four \"normal forms\" of the Unicode standard: normalform can be :NFC, :NFD, :NFKC, or :NFKD. Normal forms C (canonical composition) and D (canonical decomposition) convert different visually identical representations of the same abstract string into a single canonical form, with form C being more compact. Normal forms KC and KD additionally canonicalize \"compatibility equivalents\": they convert characters that are abstractly similar but visually distinct into a single canonical choice (e.g. they expand ligatures into the individual characters), with form KC being more compact.\n\nAlternatively, finer control and additional transformations may be be obtained by calling normalize_string(s; keywords...), where any number of the following boolean keywords options (which all default to false except for compose) are specified:\n\ncompose=false: do not perform canonical composition\ndecompose=true: do canonical decomposition instead of canonical composition (compose=true is ignored if present)\ncompat=true: compatibility equivalents are canonicalized\ncasefold=true: perform Unicode case folding, e.g. for case-insensitive string comparison\nnewline2lf=true, newline2ls=true, or newline2ps=true: convert various newline sequences (LF, CRLF, CR, NEL) into a linefeed (LF), line-separation (LS), or paragraph-separation (PS) character, respectively\nstripmark=true: strip diacritical marks (e.g. accents)\nstripignore=true: strip Unicode\'s \"default ignorable\" characters (e.g. the soft hyphen or the left-to-right marker)\nstripcc=true: strip control characters; horizontal tabs and form feeds are converted to spaces; newlines are also converted to spaces unless a newline-conversion flag was specified\nrejectna=true: throw an error if unassigned code points are found\nstable=true: enforce Unicode Versioning Stability\n\nFor example, NFKC corresponds to the options compose=true, compat=true, stable=true.\n\n\n\n" -}, - -{ - "location": "stdlib/strings.html#Base.UTF8proc.graphemes", - "page": "Strings", - "title": "Base.UTF8proc.graphemes", - "category": "function", - "text": "graphemes(s::AbstractString) -> GraphemeIterator\n\nReturns an iterator over substrings of s that correspond to the extended graphemes in the string, as defined by Unicode UAX #29. (Roughly, these are what users would perceive as single characters, even though they may contain more than one codepoint; for example a letter combined with an accent mark is a single grapheme.)\n\n\n\n" -}, - -{ - "location": "stdlib/strings.html#Base.isvalid-Tuple{Any}", - "page": "Strings", - "title": "Base.isvalid", - "category": "method", - "text": "isvalid(value) -> Bool\n\nReturns true if the given value is valid for its type, which currently can be either Char or String.\n\n\n\n" -}, - -{ - "location": "stdlib/strings.html#Base.isvalid-Tuple{Any,Any}", - "page": "Strings", - "title": "Base.isvalid", - "category": "method", - "text": "isvalid(T, value) -> Bool\n\nReturns true if the given value is valid for that type. Types currently can be either Char or String. Values for Char can be of type Char or UInt32. Values for String can be of that type, or Vector{UInt8}.\n\n\n\n" -}, - -{ - "location": "stdlib/strings.html#Base.isvalid-Tuple{AbstractString,Integer}", - "page": "Strings", - "title": "Base.isvalid", - "category": "method", - "text": "isvalid(str::AbstractString, i::Integer)\n\nTells whether index i is valid for the given string.\n\nExamples\n\njulia> str = \"αβγdef\";\n\njulia> isvalid(str, 1)\ntrue\n\njulia> str[1]\n\'α\': Unicode U+03b1 (category Ll: Letter, lowercase)\n\njulia> isvalid(str, 2)\nfalse\n\njulia> str[2]\nERROR: UnicodeError: invalid character index\n[...]\n\n\n\n" -}, - -{ - "location": "stdlib/strings.html#Base.UTF8proc.is_assigned_char", - "page": "Strings", - "title": "Base.UTF8proc.is_assigned_char", - "category": "function", - "text": "is_assigned_char(c) -> Bool\n\nReturns true if the given char or integer is an assigned Unicode code point.\n\n\n\n" -}, - -{ - "location": "stdlib/strings.html#Base.ismatch", - "page": "Strings", - "title": "Base.ismatch", - "category": "function", - "text": "ismatch(r::Regex, s::AbstractString) -> Bool\n\nTest whether a string contains a match of the given regular expression.\n\n\n\n" -}, - -{ - "location": "stdlib/strings.html#Base.match", - "page": "Strings", - "title": "Base.match", - "category": "function", - "text": "match(r::Regex, s::AbstractString[, idx::Integer[, addopts]])\n\nSearch for the first match of the regular expression r in s and return a RegexMatch object containing the match, or nothing if the match failed. The matching substring can be retrieved by accessing m.match and the captured sequences can be retrieved by accessing m.captures The optional idx argument specifies an index at which to start the search.\n\n\n\n" -}, - -{ - "location": "stdlib/strings.html#Base.eachmatch", - "page": "Strings", - "title": "Base.eachmatch", - "category": "function", - "text": "eachmatch(r::Regex, s::AbstractString[, overlap::Bool=false])\n\nSearch for all matches of a the regular expression r in s and return a iterator over the matches. If overlap is true, the matching sequences are allowed to overlap indices in the original string, otherwise they must be from distinct character ranges.\n\n\n\n" -}, - -{ - "location": "stdlib/strings.html#Base.matchall", - "page": "Strings", - "title": "Base.matchall", - "category": "function", - "text": "matchall(r::Regex, s::AbstractString[, overlap::Bool=false]) -> Vector{AbstractString}\n\nReturn a vector of the matching substrings from eachmatch.\n\n\n\n" -}, - -{ - "location": "stdlib/strings.html#Base.lpad", - "page": "Strings", - "title": "Base.lpad", - "category": "function", - "text": "lpad(s, n::Integer, p::AbstractString=\" \")\n\nMake a string at least n columns wide when printed by padding s on the left with copies of p.\n\njulia> lpad(\"March\",10)\n\" March\"\n\n\n\n" -}, - -{ - "location": "stdlib/strings.html#Base.rpad", - "page": "Strings", - "title": "Base.rpad", - "category": "function", - "text": "rpad(s, n::Integer, p::AbstractString=\" \")\n\nMake a string at least n columns wide when printed by padding s on the right with copies of p.\n\njulia> rpad(\"March\",20)\n\"March \"\n\n\n\n" -}, - -{ - "location": "stdlib/strings.html#Base.search", - "page": "Strings", - "title": "Base.search", - "category": "function", - "text": "search(string::AbstractString, chars::Chars, [start::Integer])\n\nSearch for the first occurrence of the given characters within the given string. The second argument may be a single character, a vector or a set of characters, a string, or a regular expression (though regular expressions are only allowed on contiguous strings, such as ASCII or UTF-8 strings). The third argument optionally specifies a starting index. The return value is a range of indexes where the matching sequence is found, such that s[search(s,x)] == x:\n\nsearch(string, \"substring\") = start:end such that string[start:end] == \"substring\", or 0:-1 if unmatched.\n\nsearch(string, \'c\') = index such that string[index] == \'c\', or 0 if unmatched.\n\njulia> search(\"Hello to the world\", \"z\")\n0:-1\n\njulia> search(\"JuliaLang\",\"Julia\")\n1:5\n\n\n\n" -}, - -{ - "location": "stdlib/strings.html#Base.rsearch", - "page": "Strings", - "title": "Base.rsearch", - "category": "function", - "text": "rsearch(s::AbstractString, chars::Chars, [start::Integer])\n\nSimilar to search, but returning the last occurrence of the given characters within the given string, searching in reverse from start.\n\njulia> rsearch(\"aaabbb\",\"b\")\n6:6\n\n\n\n" -}, - -{ - "location": "stdlib/strings.html#Base.searchindex", - "page": "Strings", - "title": "Base.searchindex", - "category": "function", - "text": "searchindex(s::AbstractString, substring, [start::Integer])\n\nSimilar to search, but return only the start index at which the substring is found, or 0 if it is not.\n\njulia> searchindex(\"Hello to the world\", \"z\")\n0\n\njulia> searchindex(\"JuliaLang\",\"Julia\")\n1\n\njulia> searchindex(\"JuliaLang\",\"Lang\")\n6\n\n\n\n" -}, - -{ - "location": "stdlib/strings.html#Base.rsearchindex", - "page": "Strings", - "title": "Base.rsearchindex", - "category": "function", - "text": "rsearchindex(s::AbstractString, substring, [start::Integer])\n\nSimilar to rsearch, but return only the start index at which the substring is found, or 0 if it is not.\n\njulia> rsearchindex(\"aaabbb\",\"b\")\n6\n\njulia> rsearchindex(\"aaabbb\",\"a\")\n3\n\n\n\n" -}, - -{ - "location": "stdlib/strings.html#Base.contains-Tuple{AbstractString,AbstractString}", - "page": "Strings", - "title": "Base.contains", - "category": "method", - "text": "contains(haystack::AbstractString, needle::AbstractString)\n\nDetermine whether the second argument is a substring of the first.\n\njulia> contains(\"JuliaLang is pretty cool!\", \"Julia\")\ntrue\n\n\n\n" -}, - -{ - "location": "stdlib/strings.html#Base.reverse-Tuple{AbstractString}", - "page": "Strings", - "title": "Base.reverse", - "category": "method", - "text": "reverse(s::AbstractString) -> AbstractString\n\nReverses a string.\n\njulia> reverse(\"JuliaLang\")\n\"gnaLailuJ\"\n\n\n\n" -}, - -{ - "location": "stdlib/strings.html#Base.replace", - "page": "Strings", - "title": "Base.replace", - "category": "function", - "text": "replace(string::AbstractString, pat, r[, n::Integer=0])\n\nSearch for the given pattern pat, and replace each occurrence with r. If n is provided, replace at most n occurrences. As with search, the second argument may be a single character, a vector or a set of characters, a string, or a regular expression. If r is a function, each occurrence is replaced with r(s) where s is the matched substring. If pat is a regular expression and r is a SubstitutionString, then capture group references in r are replaced with the corresponding matched text.\n\n\n\n" -}, - -{ - "location": "stdlib/strings.html#Base.split", - "page": "Strings", - "title": "Base.split", - "category": "function", - "text": "split(s::AbstractString, [chars]; limit::Integer=0, keep::Bool=true)\n\nReturn an array of substrings by splitting the given string on occurrences of the given character delimiters, which may be specified in any of the formats allowed by search\'s second argument (i.e. a single character, collection of characters, string, or regular expression). If chars is omitted, it defaults to the set of all space characters, and keep is taken to be false. The two keyword arguments are optional: they are a maximum size for the result and a flag determining whether empty fields should be kept in the result.\n\njulia> a = \"Ma.rch\"\n\"Ma.rch\"\n\njulia> split(a,\".\")\n2-element Array{SubString{String},1}:\n \"Ma\"\n \"rch\"\n\n\n\n" -}, - -{ - "location": "stdlib/strings.html#Base.rsplit", - "page": "Strings", - "title": "Base.rsplit", - "category": "function", - "text": "rsplit(s::AbstractString, [chars]; limit::Integer=0, keep::Bool=true)\n\nSimilar to split, but starting from the end of the string.\n\njulia> a = \"M.a.r.c.h\"\n\"M.a.r.c.h\"\n\njulia> rsplit(a,\".\")\n5-element Array{SubString{String},1}:\n \"M\"\n \"a\"\n \"r\"\n \"c\"\n \"h\"\n\njulia> rsplit(a,\".\";limit=1)\n1-element Array{SubString{String},1}:\n \"M.a.r.c.h\"\n\njulia> rsplit(a,\".\";limit=2)\n2-element Array{SubString{String},1}:\n \"M.a.r.c\"\n \"h\"\n\n\n\n" -}, - -{ - "location": "stdlib/strings.html#Base.strip", - "page": "Strings", - "title": "Base.strip", - "category": "function", - "text": "strip(s::AbstractString, [chars::Chars])\n\nReturn s with any leading and trailing whitespace removed. If chars (a character, or vector or set of characters) is provided, instead remove characters contained in it.\n\njulia> strip(\"{3, 5}\\n\", [\'{\', \'}\', \'\\n\'])\n\"3, 5\"\n\n\n\n" -}, - -{ - "location": "stdlib/strings.html#Base.lstrip", - "page": "Strings", - "title": "Base.lstrip", - "category": "function", - "text": "lstrip(s::AbstractString[, chars::Chars])\n\nReturn s with any leading whitespace and delimiters removed. The default delimiters to remove are \' \', \\t, \\n, \\v, \\f, and \\r. If chars (a character, or vector or set of characters) is provided, instead remove characters contained in it.\n\njulia> a = lpad(\"March\", 20)\n\" March\"\n\njulia> lstrip(a)\n\"March\"\n\n\n\n" -}, - -{ - "location": "stdlib/strings.html#Base.rstrip", - "page": "Strings", - "title": "Base.rstrip", - "category": "function", - "text": "rstrip(s::AbstractString[, chars::Chars])\n\nReturn s with any trailing whitespace and delimiters removed. The default delimiters to remove are \' \', \\t, \\n, \\v, \\f, and \\r. If chars (a character, or vector or set of characters) is provided, instead remove characters contained in it.\n\njulia> a = rpad(\"March\", 20)\n\"March \"\n\njulia> rstrip(a)\n\"March\"\n\n\n\n" -}, - -{ - "location": "stdlib/strings.html#Base.startswith", - "page": "Strings", - "title": "Base.startswith", - "category": "function", - "text": "startswith(s::AbstractString, prefix::AbstractString)\n\nReturns true if s starts with prefix. If prefix is a vector or set of characters, tests whether the first character of s belongs to that set.\n\nSee also endswith.\n\njulia> startswith(\"JuliaLang\", \"Julia\")\ntrue\n\n\n\n" -}, - -{ - "location": "stdlib/strings.html#Base.endswith", - "page": "Strings", - "title": "Base.endswith", - "category": "function", - "text": "endswith(s::AbstractString, suffix::AbstractString)\n\nReturns true if s ends with suffix. If suffix is a vector or set of characters, tests whether the last character of s belongs to that set.\n\nSee also startswith.\n\njulia> endswith(\"Sunday\", \"day\")\ntrue\n\n\n\n" -}, - -{ - "location": "stdlib/strings.html#Base.uppercase", - "page": "Strings", - "title": "Base.uppercase", - "category": "function", - "text": "uppercase(s::AbstractString)\n\nReturns s with all characters converted to uppercase.\n\nExample\n\njulia> uppercase(\"Julia\")\n\"JULIA\"\n\n\n\n" -}, - -{ - "location": "stdlib/strings.html#Base.lowercase", - "page": "Strings", - "title": "Base.lowercase", - "category": "function", - "text": "lowercase(s::AbstractString)\n\nReturns s with all characters converted to lowercase.\n\nExample\n\njulia> lowercase(\"STRINGS AND THINGS\")\n\"strings and things\"\n\n\n\n" -}, - -{ - "location": "stdlib/strings.html#Base.titlecase", - "page": "Strings", - "title": "Base.titlecase", - "category": "function", - "text": "titlecase(s::AbstractString)\n\nCapitalizes the first character of each word in s.\n\nExample\n\njulia> titlecase(\"the julia programming language\")\n\"The Julia Programming Language\"\n\n\n\n" -}, - -{ - "location": "stdlib/strings.html#Base.ucfirst", - "page": "Strings", - "title": "Base.ucfirst", - "category": "function", - "text": "ucfirst(s::AbstractString)\n\nReturns string with the first character converted to uppercase.\n\nExample\n\njulia> ucfirst(\"python\")\n\"Python\"\n\n\n\n" -}, - -{ - "location": "stdlib/strings.html#Base.lcfirst", - "page": "Strings", - "title": "Base.lcfirst", - "category": "function", - "text": "lcfirst(s::AbstractString)\n\nReturns string with the first character converted to lowercase.\n\nExample\n\njulia> lcfirst(\"Julia\")\n\"julia\"\n\n\n\n" -}, - -{ - "location": "stdlib/strings.html#Base.join", - "page": "Strings", - "title": "Base.join", - "category": "function", - "text": "join(io::IO, strings, delim, [last])\n\nJoin an array of strings into a single string, inserting the given delimiter between adjacent strings. If last is given, it will be used instead of delim between the last two strings. For example,\n\njulia> join([\"apples\", \"bananas\", \"pineapples\"], \", \", \" and \")\n\"apples, bananas and pineapples\"\n\nstrings can be any iterable over elements x which are convertible to strings via print(io::IOBuffer, x). strings will be printed to io.\n\n\n\n" -}, - -{ - "location": "stdlib/strings.html#Base.chop", - "page": "Strings", - "title": "Base.chop", - "category": "function", - "text": "chop(s::AbstractString)\n\nRemove the last character from s.\n\njulia> a = \"March\"\n\"March\"\n\njulia> chop(a)\n\"Marc\"\n\n\n\n" -}, - -{ - "location": "stdlib/strings.html#Base.chomp", - "page": "Strings", - "title": "Base.chomp", - "category": "function", - "text": "chomp(s::AbstractString)\n\nRemove a single trailing newline from a string.\n\njulia> chomp(\"Hello\\n\")\n\"Hello\"\n\n\n\n" -}, - -{ - "location": "stdlib/strings.html#Base.ind2chr", - "page": "Strings", - "title": "Base.ind2chr", - "category": "function", - "text": "ind2chr(s::AbstractString, i::Integer)\n\nConvert a byte index i to a character index with respect to string s.\n\nSee also chr2ind.\n\nExample\n\njulia> str = \"αβγdef\";\n\njulia> ind2chr(str, 3)\n2\n\njulia> chr2ind(str, 2)\n3\n\n\n\n" -}, - -{ - "location": "stdlib/strings.html#Base.chr2ind", - "page": "Strings", - "title": "Base.chr2ind", - "category": "function", - "text": "chr2ind(s::AbstractString, i::Integer)\n\nConvert a character index i to a byte index.\n\nSee also ind2chr.\n\nExample\n\njulia> str = \"αβγdef\";\n\njulia> chr2ind(str, 2)\n3\n\njulia> ind2chr(str, 3)\n2\n\n\n\n" -}, - -{ - "location": "stdlib/strings.html#Base.nextind", - "page": "Strings", - "title": "Base.nextind", - "category": "function", - "text": "nextind(str::AbstractString, i::Integer)\n\nGet the next valid string index after i. Returns a value greater than endof(str) at or after the end of the string.\n\nExamples\n\njulia> str = \"αβγdef\";\n\njulia> nextind(str, 1)\n3\n\njulia> endof(str)\n9\n\njulia> nextind(str, 9)\n10\n\n\n\n" -}, - -{ - "location": "stdlib/strings.html#Base.prevind", - "page": "Strings", - "title": "Base.prevind", - "category": "function", - "text": "prevind(str::AbstractString, i::Integer)\n\nGet the previous valid string index before i. Returns a value less than 1 at the beginning of the string.\n\nExamples\n\njulia> prevind(\"αβγdef\", 3)\n1\n\njulia> prevind(\"αβγdef\", 1)\n0\n\n\n\n" -}, - -{ - "location": "stdlib/strings.html#Base.Random.randstring", - "page": "Strings", - "title": "Base.Random.randstring", - "category": "function", - "text": "randstring([rng,] len=8)\n\nCreate a random ASCII string of length len, consisting of upper- and lower-case letters and the digits 0-9. The optional rng argument specifies a random number generator, see Random Numbers.\n\nExample\n\njulia> rng = MersenneTwister(1234);\n\njulia> randstring(rng, 4)\n\"mbDd\"\n\n\n\n" -}, - -{ - "location": "stdlib/strings.html#Base.UTF8proc.charwidth", - "page": "Strings", - "title": "Base.UTF8proc.charwidth", - "category": "function", - "text": "charwidth(c)\n\nGives the number of columns needed to print a character.\n\n\n\n" -}, - -{ - "location": "stdlib/strings.html#Base.strwidth", - "page": "Strings", - "title": "Base.strwidth", - "category": "function", - "text": "strwidth(s::AbstractString)\n\nGives the number of columns needed to print a string.\n\nExample\n\njulia> strwidth(\"March\")\n5\n\n\n\n" -}, - -{ - "location": "stdlib/strings.html#Base.UTF8proc.isalnum", - "page": "Strings", - "title": "Base.UTF8proc.isalnum", - "category": "function", - "text": "isalnum(c::Char) -> Bool\n\nTests whether a character is alphanumeric. A character is classified as alphabetic if it belongs to the Unicode general category Letter or Number, i.e. a character whose category code begins with \'L\' or \'N\'.\n\n\n\n" -}, - -{ - "location": "stdlib/strings.html#Base.UTF8proc.isalpha", - "page": "Strings", - "title": "Base.UTF8proc.isalpha", - "category": "function", - "text": "isalpha(c::Char) -> Bool\n\nTests whether a character is alphabetic. A character is classified as alphabetic if it belongs to the Unicode general category Letter, i.e. a character whose category code begins with \'L\'.\n\n\n\n" -}, - -{ - "location": "stdlib/strings.html#Base.isascii", - "page": "Strings", - "title": "Base.isascii", - "category": "function", - "text": "isascii(c::Union{Char,AbstractString}) -> Bool\n\nTests whether a character belongs to the ASCII character set, or whether this is true for all elements of a string.\n\n\n\n" -}, - -{ - "location": "stdlib/strings.html#Base.UTF8proc.iscntrl", - "page": "Strings", - "title": "Base.UTF8proc.iscntrl", - "category": "function", - "text": "iscntrl(c::Char) -> Bool\n\nTests whether a character is a control character. Control characters are the non-printing characters of the Latin-1 subset of Unicode.\n\n\n\n" -}, - -{ - "location": "stdlib/strings.html#Base.UTF8proc.isdigit", - "page": "Strings", - "title": "Base.UTF8proc.isdigit", - "category": "function", - "text": "isdigit(c::Char) -> Bool\n\nTests whether a character is a numeric digit (0-9).\n\n\n\n" -}, - -{ - "location": "stdlib/strings.html#Base.UTF8proc.isgraph", - "page": "Strings", - "title": "Base.UTF8proc.isgraph", - "category": "function", - "text": "isgraph(c::Char) -> Bool\n\nTests whether a character is printable, and not a space. Any character that would cause a printer to use ink should be classified with isgraph(c)==true.\n\n\n\n" -}, - -{ - "location": "stdlib/strings.html#Base.UTF8proc.islower", - "page": "Strings", - "title": "Base.UTF8proc.islower", - "category": "function", - "text": "islower(c::Char) -> Bool\n\nTests whether a character is a lowercase letter. A character is classified as lowercase if it belongs to Unicode category Ll, Letter: Lowercase.\n\n\n\n" -}, - -{ - "location": "stdlib/strings.html#Base.UTF8proc.isnumber", - "page": "Strings", - "title": "Base.UTF8proc.isnumber", - "category": "function", - "text": "isnumber(c::Char) -> Bool\n\nTests whether a character is numeric. A character is classified as numeric if it belongs to the Unicode general category Number, i.e. a character whose category code begins with \'N\'.\n\n\n\n" -}, - -{ - "location": "stdlib/strings.html#Base.UTF8proc.isprint", - "page": "Strings", - "title": "Base.UTF8proc.isprint", - "category": "function", - "text": "isprint(c::Char) -> Bool\n\nTests whether a character is printable, including spaces, but not a control character.\n\n\n\n" -}, - -{ - "location": "stdlib/strings.html#Base.UTF8proc.ispunct", - "page": "Strings", - "title": "Base.UTF8proc.ispunct", - "category": "function", - "text": "ispunct(c::Char) -> Bool\n\nTests whether a character belongs to the Unicode general category Punctuation, i.e. a character whose category code begins with \'P\'.\n\n\n\n" -}, - -{ - "location": "stdlib/strings.html#Base.UTF8proc.isspace", - "page": "Strings", - "title": "Base.UTF8proc.isspace", - "category": "function", - "text": "isspace(c::Char) -> Bool\n\nTests whether a character is any whitespace character. Includes ASCII characters \'\\t\', \'\\n\', \'\\v\', \'\\f\', \'\\r\', and \' \', Latin-1 character U+0085, and characters in Unicode category Zs.\n\n\n\n" -}, - -{ - "location": "stdlib/strings.html#Base.UTF8proc.isupper", - "page": "Strings", - "title": "Base.UTF8proc.isupper", - "category": "function", - "text": "isupper(c::Char) -> Bool\n\nTests whether a character is an uppercase letter. A character is classified as uppercase if it belongs to Unicode category Lu, Letter: Uppercase, or Lt, Letter: Titlecase.\n\n\n\n" -}, - -{ - "location": "stdlib/strings.html#Base.isxdigit", - "page": "Strings", - "title": "Base.isxdigit", - "category": "function", - "text": "isxdigit(c::Char) -> Bool\n\nTests whether a character is a valid hexadecimal digit. Note that this does not include x (as in the standard 0x prefix).\n\nExample\n\njulia> isxdigit(\'a\')\ntrue\n\njulia> isxdigit(\'x\')\nfalse\n\n\n\n" -}, - -{ - "location": "stdlib/strings.html#Core.Symbol", - "page": "Strings", - "title": "Core.Symbol", - "category": "type", - "text": "Symbol(x...) -> Symbol\n\nCreate a Symbol by concatenating the string representations of the arguments together.\n\n\n\n" -}, - -{ - "location": "stdlib/strings.html#Base.escape_string", - "page": "Strings", - "title": "Base.escape_string", - "category": "function", - "text": "escape_string([io,] str::AbstractString[, esc::AbstractString]) -> AbstractString\n\nGeneral escaping of traditional C and Unicode escape sequences. Any characters in esc are also escaped (with a backslash). See also unescape_string.\n\n\n\n" -}, - -{ - "location": "stdlib/strings.html#Base.unescape_string", - "page": "Strings", - "title": "Base.unescape_string", - "category": "function", - "text": "unescape_string([io,] s::AbstractString) -> AbstractString\n\nGeneral unescaping of traditional C and Unicode escape sequences. Reverse of escape_string.\n\n\n\n" -}, - -{ - "location": "stdlib/strings.html#lib-strings-1", - "page": "Strings", - "title": "Strings", - "category": "section", - "text": "Base.length(::AbstractString)\nBase.sizeof(::AbstractString)\nBase.:*(::AbstractString, ::Any...)\nBase.:^(::AbstractString, ::Integer)\nBase.string\nBase.repr\nCore.String(::AbstractString)\nBase.transcode\nBase.unsafe_string\nBase.codeunit(::AbstractString, ::Integer)\nBase.ascii\nBase.@r_str\nBase.Docs.@html_str\nBase.Docs.@text_str\nBase.UTF8proc.normalize_string\nBase.UTF8proc.graphemes\nBase.isvalid(::Any)\nBase.isvalid(::Any, ::Any)\nBase.isvalid(::AbstractString, ::Integer)\nBase.UTF8proc.is_assigned_char\nBase.ismatch\nBase.match\nBase.eachmatch\nBase.matchall\nBase.lpad\nBase.rpad\nBase.search\nBase.rsearch\nBase.searchindex\nBase.rsearchindex\nBase.contains(::AbstractString, ::AbstractString)\nBase.reverse(::AbstractString)\nBase.replace\nBase.split\nBase.rsplit\nBase.strip\nBase.lstrip\nBase.rstrip\nBase.startswith\nBase.endswith\nBase.uppercase\nBase.lowercase\nBase.titlecase\nBase.ucfirst\nBase.lcfirst\nBase.join\nBase.chop\nBase.chomp\nBase.ind2chr\nBase.chr2ind\nBase.nextind\nBase.prevind\nBase.Random.randstring\nBase.UTF8proc.charwidth\nBase.strwidth\nBase.UTF8proc.isalnum\nBase.UTF8proc.isalpha\nBase.isascii\nBase.UTF8proc.iscntrl\nBase.UTF8proc.isdigit\nBase.UTF8proc.isgraph\nBase.UTF8proc.islower\nBase.UTF8proc.isnumber\nBase.UTF8proc.isprint\nBase.UTF8proc.ispunct\nBase.UTF8proc.isspace\nBase.UTF8proc.isupper\nBase.isxdigit\nCore.Symbol\nBase.escape_string\nBase.unescape_string" -}, - -{ - "location": "stdlib/arrays.html#", - "page": "Arrays", - "title": "Arrays", - "category": "page", - "text": "" -}, - -{ - "location": "stdlib/arrays.html#lib-arrays-1", - "page": "Arrays", - "title": "Arrays", - "category": "section", - "text": "" -}, - -{ - "location": "stdlib/arrays.html#Core.AbstractArray", - "page": "Arrays", - "title": "Core.AbstractArray", - "category": "type", - "text": "AbstractArray{T, N}\n\nAbstract array supertype which arrays inherit from.\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Core.Array", - "page": "Arrays", - "title": "Core.Array", - "category": "type", - "text": "Array{T}(dims)\nArray{T,N}(dims)\n\nConstruct an uninitialized N-dimensional dense array with element type T, where N is determined from the length or number of dims. dims may be a tuple or a series of integer arguments corresponding to the lengths in each dimension. If the rank N is supplied explicitly as in Array{T,N}(dims), then it must match the length or number of dims.\n\nExample\n\njulia> A = Array{Float64, 2}(2, 2);\n\njulia> ndims(A)\n2\n\njulia> eltype(A)\nFloat64\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Base.getindex-Tuple{Type,Vararg{Any,N} where N}", - "page": "Arrays", - "title": "Base.getindex", - "category": "method", - "text": "getindex(type[, elements...])\n\nConstruct a 1-d array of the specified type. This is usually called with the syntax Type[]. Element values can be specified using Type[a,b,c,...].\n\nExample\n\njulia> Int8[1, 2, 3]\n3-element Array{Int8,1}:\n 1\n 2\n 3\n\njulia> getindex(Int8, 1, 2, 3)\n3-element Array{Int8,1}:\n 1\n 2\n 3\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Base.zeros", - "page": "Arrays", - "title": "Base.zeros", - "category": "function", - "text": "zeros([A::AbstractArray,] [T=eltype(A)::Type,] [dims=size(A)::Tuple])\n\nCreate an array of all zeros with the same layout as A, element type T and size dims. The A argument can be skipped, which behaves like Array{Float64,0}() was passed. For convenience dims may also be passed in variadic form.\n\nExamples\n\njulia> zeros(1)\n1-element Array{Float64,1}:\n 0.0\n\njulia> zeros(Int8, 2, 3)\n2×3 Array{Int8,2}:\n 0 0 0\n 0 0 0\n\njulia> A = [1 2; 3 4]\n2×2 Array{Int64,2}:\n 1 2\n 3 4\n\njulia> zeros(A)\n2×2 Array{Int64,2}:\n 0 0\n 0 0\n\njulia> zeros(A, Float64)\n2×2 Array{Float64,2}:\n 0.0 0.0\n 0.0 0.0\n\njulia> zeros(A, Bool, (3,))\n3-element Array{Bool,1}:\n false\n false\n false\n\nSee also ones, similar.\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Base.ones", - "page": "Arrays", - "title": "Base.ones", - "category": "function", - "text": "ones([A::AbstractArray,] [T=eltype(A)::Type,] [dims=size(A)::Tuple])\n\nCreate an array of all ones with the same layout as A, element type T and size dims. The A argument can be skipped, which behaves like Array{Float64,0}() was passed. For convenience dims may also be passed in variadic form.\n\nExamples\n\njulia> ones(Complex128, 2, 3)\n2×3 Array{Complex{Float64},2}:\n 1.0+0.0im 1.0+0.0im 1.0+0.0im\n 1.0+0.0im 1.0+0.0im 1.0+0.0im\n\njulia> ones(1,2)\n1×2 Array{Float64,2}:\n 1.0 1.0\n\njulia> A = [1 2; 3 4]\n2×2 Array{Int64,2}:\n 1 2\n 3 4\n\njulia> ones(A)\n2×2 Array{Int64,2}:\n 1 1\n 1 1\n\njulia> ones(A, Float64)\n2×2 Array{Float64,2}:\n 1.0 1.0\n 1.0 1.0\n\njulia> ones(A, Bool, (3,))\n3-element Array{Bool,1}:\n true\n true\n true\n\nSee also zeros, similar.\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Base.BitArray", - "page": "Arrays", - "title": "Base.BitArray", - "category": "type", - "text": "BitArray(dims::Integer...)\nBitArray{N}(dims::NTuple{N,Int})\n\nConstruct an uninitialized BitArray with the given dimensions. Behaves identically to the Array constructor.\n\njulia> BitArray(2, 2)\n2×2 BitArray{2}:\n false false\n false true\n\njulia> BitArray((3, 1))\n3×1 BitArray{2}:\n false\n true\n false\n\n\n\nBitArray(itr)\n\nConstruct a BitArray generated by the given iterable object. The shape is inferred from the itr object.\n\njulia> BitArray([1 0; 0 1])\n2×2 BitArray{2}:\n true false\n false true\n\njulia> BitArray(x+y == 3 for x = 1:2, y = 1:3)\n2×3 BitArray{2}:\n false true false\n true false false\n\njulia> BitArray(x+y == 3 for x = 1:2 for y = 1:3)\n6-element BitArray{1}:\n false\n true\n false\n true\n false\n false\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Base.trues", - "page": "Arrays", - "title": "Base.trues", - "category": "function", - "text": "trues(dims)\n\nCreate a BitArray with all values set to true.\n\njulia> trues(2,3)\n2×3 BitArray{2}:\n true true true\n true true true\n\n\n\ntrues(A)\n\nCreate a BitArray with all values set to true of the same shape as A.\n\njulia> A = [1 2; 3 4]\n2×2 Array{Int64,2}:\n 1 2\n 3 4\n\njulia> trues(A)\n2×2 BitArray{2}:\n true true\n true true\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Base.falses", - "page": "Arrays", - "title": "Base.falses", - "category": "function", - "text": "falses(dims)\n\nCreate a BitArray with all values set to false.\n\njulia> falses(2,3)\n2×3 BitArray{2}:\n false false false\n false false false\n\n\n\nfalses(A)\n\nCreate a BitArray with all values set to false of the same shape as A.\n\njulia> A = [1 2; 3 4]\n2×2 Array{Int64,2}:\n 1 2\n 3 4\n\njulia> falses(A)\n2×2 BitArray{2}:\n false false\n false false\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Base.fill", - "page": "Arrays", - "title": "Base.fill", - "category": "function", - "text": "fill(x, dims)\n\nCreate an array filled with the value x. For example, fill(1.0, (5,5)) returns a 5×5 array of floats, with each element initialized to 1.0.\n\njulia> fill(1.0, (5,5))\n5×5 Array{Float64,2}:\n 1.0 1.0 1.0 1.0 1.0\n 1.0 1.0 1.0 1.0 1.0\n 1.0 1.0 1.0 1.0 1.0\n 1.0 1.0 1.0 1.0 1.0\n 1.0 1.0 1.0 1.0 1.0\n\nIf x is an object reference, all elements will refer to the same object. fill(Foo(), dims) will return an array filled with the result of evaluating Foo() once.\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Base.fill!", - "page": "Arrays", - "title": "Base.fill!", - "category": "function", - "text": "fill!(A, x)\n\nFill array A with the value x. If x is an object reference, all elements will refer to the same object. fill!(A, Foo()) will return A filled with the result of evaluating Foo() once.\n\nExamples\n\njulia> A = zeros(2,3)\n2×3 Array{Float64,2}:\n 0.0 0.0 0.0\n 0.0 0.0 0.0\n\njulia> fill!(A, 2.)\n2×3 Array{Float64,2}:\n 2.0 2.0 2.0\n 2.0 2.0 2.0\n\njulia> a = [1, 1, 1]; A = fill!(Vector{Vector{Int}}(3), a); a[1] = 2; A\n3-element Array{Array{Int64,1},1}:\n [2, 1, 1]\n [2, 1, 1]\n [2, 1, 1]\n\njulia> x = 0; f() = (global x += 1; x); fill!(Vector{Int}(3), f())\n3-element Array{Int64,1}:\n 1\n 1\n 1\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Base.similar-Tuple{AbstractArray}", - "page": "Arrays", - "title": "Base.similar", - "category": "method", - "text": "similar(array, [element_type=eltype(array)], [dims=size(array)])\n\nCreate an uninitialized mutable array with the given element type and size, based upon the given source array. The second and third arguments are both optional, defaulting to the given array\'s eltype and size. The dimensions may be specified either as a single tuple argument or as a series of integer arguments.\n\nCustom AbstractArray subtypes may choose which specific array type is best-suited to return for the given element type and dimensionality. If they do not specialize this method, the default is an Array{element_type}(dims...).\n\nFor example, similar(1:10, 1, 4) returns an uninitialized Array{Int,2} since ranges are neither mutable nor support 2 dimensions:\n\njulia> similar(1:10, 1, 4)\n1×4 Array{Int64,2}:\n 4419743872 4374413872 4419743888 0\n\nConversely, similar(trues(10,10), 2) returns an uninitialized BitVector with two elements since BitArrays are both mutable and can support 1-dimensional arrays:\n\njulia> similar(trues(10,10), 2)\n2-element BitArray{1}:\n false\n false\n\nSince BitArrays can only store elements of type Bool, however, if you request a different element type it will create a regular Array instead:\n\njulia> similar(falses(10), Float64, 2, 4)\n2×4 Array{Float64,2}:\n 2.18425e-314 2.18425e-314 2.18425e-314 2.18425e-314\n 2.18425e-314 2.18425e-314 2.18425e-314 2.18425e-314\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Base.similar-Tuple{Any,Tuple}", - "page": "Arrays", - "title": "Base.similar", - "category": "method", - "text": "similar(storagetype, indices)\n\nCreate an uninitialized mutable array analogous to that specified by storagetype, but with indices specified by the last argument. storagetype might be a type or a function.\n\nExamples:\n\nsimilar(Array{Int}, indices(A))\n\ncreates an array that \"acts like\" an Array{Int} (and might indeed be backed by one), but which is indexed identically to A. If A has conventional indexing, this will be identical to Array{Int}(size(A)), but if A has unconventional indexing then the indices of the result will match A.\n\nsimilar(BitArray, (indices(A, 2),))\n\nwould create a 1-dimensional logical array whose indices match those of the columns of A.\n\nsimilar(dims->zeros(Int, dims), indices(A))\n\nwould create an array of Int, initialized to zero, matching the indices of A.\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Base.eye", - "page": "Arrays", - "title": "Base.eye", - "category": "function", - "text": "eye([T::Type=Float64,] m::Integer, n::Integer)\n\nm-by-n identity matrix. The default element type is Float64.\n\nExamples\n\njulia> eye(3, 4)\n3×4 Array{Float64,2}:\n 1.0 0.0 0.0 0.0\n 0.0 1.0 0.0 0.0\n 0.0 0.0 1.0 0.0\n\njulia> eye(2, 2)\n2×2 Array{Float64,2}:\n 1.0 0.0\n 0.0 1.0\n\njulia> eye(Int, 2, 2)\n2×2 Array{Int64,2}:\n 1 0\n 0 1\n\n\n\neye(m, n)\n\nm-by-n identity matrix.\n\n\n\neye([T::Type=Float64,] n::Integer)\n\nn-by-n identity matrix. The default element type is Float64.\n\nExamples\n\njulia> eye(Int, 2)\n2×2 Array{Int64,2}:\n 1 0\n 0 1\n\njulia> eye(2)\n2×2 Array{Float64,2}:\n 1.0 0.0\n 0.0 1.0\n\n\n\neye(A)\n\nConstructs an identity matrix of the same dimensions and type as A.\n\njulia> A = [1 2 3; 4 5 6; 7 8 9]\n3×3 Array{Int64,2}:\n 1 2 3\n 4 5 6\n 7 8 9\n\njulia> eye(A)\n3×3 Array{Int64,2}:\n 1 0 0\n 0 1 0\n 0 0 1\n\nNote the difference from ones.\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Base.linspace", - "page": "Arrays", - "title": "Base.linspace", - "category": "function", - "text": "linspace(start, stop, n=50)\n\nConstruct a range of n linearly spaced elements from start to stop.\n\njulia> linspace(1.3,2.9,9)\n1.3:0.2:2.9\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Base.logspace", - "page": "Arrays", - "title": "Base.logspace", - "category": "function", - "text": "logspace(start::Real, stop::Real, n::Integer=50)\n\nConstruct a vector of n logarithmically spaced numbers from 10^start to 10^stop.\n\njulia> logspace(1.,10.,5)\n5-element Array{Float64,1}:\n 10.0\n 1778.28\n 3.16228e5\n 5.62341e7\n 1.0e10\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Base.Random.randsubseq", - "page": "Arrays", - "title": "Base.Random.randsubseq", - "category": "function", - "text": "randsubseq(A, p) -> Vector\n\nReturn a vector consisting of a random subsequence of the given array A, where each element of A is included (in order) with independent probability p. (Complexity is linear in p*length(A), so this function is efficient even if p is small and A is large.) Technically, this process is known as \"Bernoulli sampling\" of A.\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Base.Random.randsubseq!", - "page": "Arrays", - "title": "Base.Random.randsubseq!", - "category": "function", - "text": "randsubseq!(S, A, p)\n\nLike randsubseq, but the results are stored in S (which is resized as needed).\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Constructors-and-Types-1", - "page": "Arrays", - "title": "Constructors and Types", - "category": "section", - "text": "Core.AbstractArray\nCore.Array\nBase.getindex(::Type, ::Any...)\nBase.zeros\nBase.ones\nBase.BitArray\nBase.trues\nBase.falses\nBase.fill\nBase.fill!\nBase.similar(::AbstractArray)\nBase.similar(::Any, ::Tuple)\nBase.eye\nBase.linspace\nBase.logspace\nBase.Random.randsubseq\nBase.Random.randsubseq!" -}, - -{ - "location": "stdlib/arrays.html#Base.ndims", - "page": "Arrays", - "title": "Base.ndims", - "category": "function", - "text": "ndims(A::AbstractArray) -> Integer\n\nReturns the number of dimensions of A.\n\njulia> A = ones(3,4,5);\n\njulia> ndims(A)\n3\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Base.size", - "page": "Arrays", - "title": "Base.size", - "category": "function", - "text": "size(A::AbstractArray, [dim...])\n\nReturns a tuple containing the dimensions of A. Optionally you can specify the dimension(s) you want the length of, and get the length of that dimension, or a tuple of the lengths of dimensions you asked for.\n\njulia> A = ones(2,3,4);\n\njulia> size(A, 2)\n3\n\njulia> size(A,3,2)\n(4, 3)\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Base.indices-Tuple{Any}", - "page": "Arrays", - "title": "Base.indices", - "category": "method", - "text": "indices(A)\n\nReturns the tuple of valid indices for array A.\n\njulia> A = ones(5,6,7);\n\njulia> indices(A)\n(Base.OneTo(5), Base.OneTo(6), Base.OneTo(7))\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Base.indices-Tuple{AbstractArray,Any}", - "page": "Arrays", - "title": "Base.indices", - "category": "method", - "text": "indices(A, d)\n\nReturns the valid range of indices for array A along dimension d.\n\njulia> A = ones(5,6,7);\n\njulia> indices(A,2)\nBase.OneTo(6)\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Base.length-Tuple{AbstractArray}", - "page": "Arrays", - "title": "Base.length", - "category": "method", - "text": "length(A::AbstractArray) -> Integer\n\nReturns the number of elements in A.\n\njulia> A = ones(3,4,5);\n\njulia> length(A)\n60\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Base.eachindex", - "page": "Arrays", - "title": "Base.eachindex", - "category": "function", - "text": "eachindex(A...)\n\nCreates an iterable object for visiting each index of an AbstractArray A in an efficient manner. For array types that have opted into fast linear indexing (like Array), this is simply the range 1:length(A). For other array types, this returns a specialized Cartesian range to efficiently index into the array with indices specified for every dimension. For other iterables, including strings and dictionaries, this returns an iterator object supporting arbitrary index types (e.g. unevenly spaced or non-integer indices).\n\nExample for a sparse 2-d array:\n\njulia> A = sparse([1, 1, 2], [1, 3, 1], [1, 2, -5])\n2×3 SparseMatrixCSC{Int64,Int64} with 3 stored entries:\n [1, 1] = 1\n [2, 1] = -5\n [1, 3] = 2\n\njulia> for iter in eachindex(A)\n @show iter.I[1], iter.I[2]\n @show A[iter]\n end\n(iter.I[1], iter.I[2]) = (1, 1)\nA[iter] = 1\n(iter.I[1], iter.I[2]) = (2, 1)\nA[iter] = -5\n(iter.I[1], iter.I[2]) = (1, 2)\nA[iter] = 0\n(iter.I[1], iter.I[2]) = (2, 2)\nA[iter] = 0\n(iter.I[1], iter.I[2]) = (1, 3)\nA[iter] = 2\n(iter.I[1], iter.I[2]) = (2, 3)\nA[iter] = 0\n\nIf you supply more than one AbstractArray argument, eachindex will create an iterable object that is fast for all arguments (a UnitRange if all inputs have fast linear indexing, a CartesianRange otherwise). If the arrays have different sizes and/or dimensionalities, eachindex returns an iterable that spans the largest range along each dimension.\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Base.linearindices", - "page": "Arrays", - "title": "Base.linearindices", - "category": "function", - "text": "linearindices(A)\n\nReturns a UnitRange specifying the valid range of indices for A[i] where i is an Int. For arrays with conventional indexing (indices start at 1), or any multidimensional array, this is 1:length(A); however, for one-dimensional arrays with unconventional indices, this is indices(A, 1).\n\nCalling this function is the \"safe\" way to write algorithms that exploit linear indexing.\n\njulia> A = ones(5,6,7);\n\njulia> b = linearindices(A);\n\njulia> extrema(b)\n(1, 210)\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Base.IndexStyle", - "page": "Arrays", - "title": "Base.IndexStyle", - "category": "type", - "text": "IndexStyle(A)\nIndexStyle(typeof(A))\n\nIndexStyle specifies the \"native indexing style\" for array A. When you define a new AbstractArray type, you can choose to implement either linear indexing or cartesian indexing. If you decide to implement linear indexing, then you must set this trait for your array type:\n\nBase.IndexStyle(::Type{<:MyArray}) = IndexLinear()\n\nThe default is IndexCartesian().\n\nJulia\'s internal indexing machinery will automatically (and invisibly) convert all indexing operations into the preferred style using sub2ind or ind2sub. This allows users to access elements of your array using any indexing style, even when explicit methods have not been provided.\n\nIf you define both styles of indexing for your AbstractArray, this trait can be used to select the most performant indexing style. Some methods check this trait on their inputs, and dispatch to different algorithms depending on the most efficient access pattern. In particular, eachindex creates an iterator whose type depends on the setting of this trait.\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Base.countnz", - "page": "Arrays", - "title": "Base.countnz", - "category": "function", - "text": "countnz(A) -> Integer\n\nCounts the number of nonzero values in array A (dense or sparse). Note that this is not a constant-time operation. For sparse matrices, one should usually use nnz, which returns the number of stored values.\n\njulia> A = [1 2 4; 0 0 1; 1 1 0]\n3×3 Array{Int64,2}:\n 1 2 4\n 0 0 1\n 1 1 0\n\njulia> countnz(A)\n6\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Base.conj!", - "page": "Arrays", - "title": "Base.conj!", - "category": "function", - "text": "conj!(A)\n\nTransform an array to its complex conjugate in-place.\n\nSee also conj.\n\nExample\n\njulia> A = [1+im 2-im; 2+2im 3+im]\n2×2 Array{Complex{Int64},2}:\n 1+1im 2-1im\n 2+2im 3+1im\n\njulia> conj!(A);\n\njulia> A\n2×2 Array{Complex{Int64},2}:\n 1-1im 2+1im\n 2-2im 3-1im\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Base.stride", - "page": "Arrays", - "title": "Base.stride", - "category": "function", - "text": "stride(A, k::Integer)\n\nReturns the distance in memory (in number of elements) between adjacent elements in dimension k.\n\njulia> A = ones(3,4,5);\n\njulia> stride(A,2)\n3\n\njulia> stride(A,3)\n12\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Base.strides", - "page": "Arrays", - "title": "Base.strides", - "category": "function", - "text": "strides(A)\n\nReturns a tuple of the memory strides in each dimension.\n\njulia> A = ones(3,4,5);\n\njulia> strides(A)\n(1, 3, 12)\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Base.ind2sub", - "page": "Arrays", - "title": "Base.ind2sub", - "category": "function", - "text": "ind2sub(a, index) -> subscripts\n\nReturns a tuple of subscripts into array a corresponding to the linear index index.\n\njulia> A = ones(5,6,7);\n\njulia> ind2sub(A,35)\n(5, 1, 2)\n\njulia> ind2sub(A,70)\n(5, 2, 3)\n\n\n\nind2sub(dims, index) -> subscripts\n\nReturns a tuple of subscripts into an array with dimensions dims, corresponding to the linear index index.\n\nExample:\n\ni, j, ... = ind2sub(size(A), indmax(A))\n\nprovides the indices of the maximum element.\n\njulia> ind2sub((3,4),2)\n(2, 1)\n\njulia> ind2sub((3,4),3)\n(3, 1)\n\njulia> ind2sub((3,4),4)\n(1, 2)\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Base.sub2ind", - "page": "Arrays", - "title": "Base.sub2ind", - "category": "function", - "text": "sub2ind(dims, i, j, k...) -> index\n\nThe inverse of ind2sub, returns the linear index corresponding to the provided subscripts.\n\njulia> sub2ind((5,6,7),1,2,3)\n66\n\njulia> sub2ind((5,6,7),1,6,3)\n86\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Base.LinAlg.checksquare", - "page": "Arrays", - "title": "Base.LinAlg.checksquare", - "category": "function", - "text": "LinAlg.checksquare(A)\n\nCheck that a matrix is square, then return its common dimension. For multiple arguments, return a vector.\n\nExample\n\njulia> A = ones(4,4); B = zeros(5,5);\n\njulia> LinAlg.checksquare(A, B)\n2-element Array{Int64,1}:\n 4\n 5\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Basic-functions-1", - "page": "Arrays", - "title": "Basic functions", - "category": "section", - "text": "Base.ndims\nBase.size\nBase.indices(::Any)\nBase.indices(::AbstractArray, ::Any)\nBase.length(::AbstractArray)\nBase.eachindex\nBase.linearindices\nBase.IndexStyle\nBase.countnz\nBase.conj!\nBase.stride\nBase.strides\nBase.ind2sub\nBase.sub2ind\nBase.LinAlg.checksquare" -}, - -{ - "location": "stdlib/arrays.html#Base.broadcast", - "page": "Arrays", - "title": "Base.broadcast", - "category": "function", - "text": "broadcast(f, As...)\n\nBroadcasts the arrays, tuples, Refs, nullables, and/or scalars As to a container of the appropriate type and dimensions. In this context, anything that is not a subtype of AbstractArray, Ref (except for Ptrs), Tuple, or Nullable is considered a scalar. The resulting container is established by the following rules:\n\nIf all the arguments are scalars, it returns a scalar.\nIf the arguments are tuples and zero or more scalars, it returns a tuple.\nIf the arguments contain at least one array or Ref, it returns an array (expanding singleton dimensions), and treats Refs as 0-dimensional arrays, and tuples as 1-dimensional arrays.\n\nThe following additional rule applies to Nullable arguments: If there is at least one Nullable, and all the arguments are scalars or Nullable, it returns a Nullable treating Nullables as \"containers\".\n\nA special syntax exists for broadcasting: f.(args...) is equivalent to broadcast(f, args...), and nested f.(g.(args...)) calls are fused into a single broadcast loop.\n\njulia> A = [1, 2, 3, 4, 5]\n5-element Array{Int64,1}:\n 1\n 2\n 3\n 4\n 5\n\njulia> B = [1 2; 3 4; 5 6; 7 8; 9 10]\n5×2 Array{Int64,2}:\n 1 2\n 3 4\n 5 6\n 7 8\n 9 10\n\njulia> broadcast(+, A, B)\n5×2 Array{Int64,2}:\n 2 3\n 5 6\n 8 9\n 11 12\n 14 15\n\njulia> parse.(Int, [\"1\", \"2\"])\n2-element Array{Int64,1}:\n 1\n 2\n\njulia> abs.((1, -2))\n(1, 2)\n\njulia> broadcast(+, 1.0, (0, -2.0))\n(1.0, -1.0)\n\njulia> broadcast(+, 1.0, (0, -2.0), Ref(1))\n2-element Array{Float64,1}:\n 2.0\n 0.0\n\njulia> (+).([[0,2], [1,3]], Ref{Vector{Int}}([1,-1]))\n2-element Array{Array{Int64,1},1}:\n [1, 1]\n [2, 2]\n\njulia> string.((\"one\",\"two\",\"three\",\"four\"), \": \", 1:4)\n4-element Array{String,1}:\n \"one: 1\"\n \"two: 2\"\n \"three: 3\"\n \"four: 4\"\n\njulia> Nullable(\"X\") .* \"Y\"\nNullable{String}(\"XY\")\n\njulia> broadcast(/, 1.0, Nullable(2.0))\nNullable{Float64}(0.5)\n\njulia> (1 + im) ./ Nullable{Int}()\nNullable{Complex{Float64}}()\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Base.broadcast!", - "page": "Arrays", - "title": "Base.broadcast!", - "category": "function", - "text": "broadcast!(f, dest, As...)\n\nLike broadcast, but store the result of broadcast(f, As...) in the dest array. Note that dest is only used to store the result, and does not supply arguments to f unless it is also listed in the As, as in broadcast!(f, A, A, B) to perform A[:] = broadcast(f, A, B).\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Base.Broadcast.@__dot__", - "page": "Arrays", - "title": "Base.Broadcast.@__dot__", - "category": "macro", - "text": "@. expr\n\nConvert every function call or operator in expr into a \"dot call\" (e.g. convert f(x) to f.(x)), and convert every assignment in expr to a \"dot assignment\" (e.g. convert += to .+=).\n\nIf you want to avoid adding dots for selected function calls in expr, splice those function calls in with $. For example, @. sqrt(abs($sort(x))) is equivalent to sqrt.(abs.(sort(x))) (no dot for sort).\n\n(@. is equivalent to a call to @__dot__.)\n\njulia> x = 1.0:3.0; y = similar(x);\n\njulia> @. y = x + 3 * sin(x)\n3-element Array{Float64,1}:\n 3.52441\n 4.72789\n 3.42336\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Base.Broadcast.broadcast_getindex", - "page": "Arrays", - "title": "Base.Broadcast.broadcast_getindex", - "category": "function", - "text": "broadcast_getindex(A, inds...)\n\nBroadcasts the inds arrays to a common size like broadcast and returns an array of the results A[ks...], where ks goes over the positions in the broadcast result A.\n\njulia> A = [1, 2, 3, 4, 5]\n5-element Array{Int64,1}:\n 1\n 2\n 3\n 4\n 5\n\njulia> B = [1 2; 3 4; 5 6; 7 8; 9 10]\n5×2 Array{Int64,2}:\n 1 2\n 3 4\n 5 6\n 7 8\n 9 10\n\njulia> C = broadcast(+,A,B)\n5×2 Array{Int64,2}:\n 2 3\n 5 6\n 8 9\n 11 12\n 14 15\n\njulia> broadcast_getindex(C,[1,2,10])\n3-element Array{Int64,1}:\n 2\n 5\n 15\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Base.Broadcast.broadcast_setindex!", - "page": "Arrays", - "title": "Base.Broadcast.broadcast_setindex!", - "category": "function", - "text": "broadcast_setindex!(A, X, inds...)\n\nBroadcasts the X and inds arrays to a common size and stores the value from each position in X at the indices in A given by the same positions in inds.\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Broadcast-and-vectorization-1", - "page": "Arrays", - "title": "Broadcast and vectorization", - "category": "section", - "text": "See also the dot syntax for vectorizing functions; for example, f.(args...) implicitly calls broadcast(f, args...). Rather than relying on \"vectorized\" methods of functions like sin to operate on arrays, you should use sin.(a) to vectorize via broadcast.Base.broadcast\nBase.Broadcast.broadcast!\nBase.@__dot__\nBase.Broadcast.broadcast_getindex\nBase.Broadcast.broadcast_setindex!" -}, - -{ - "location": "stdlib/arrays.html#Base.getindex-Tuple{AbstractArray,Vararg{Any,N} where N}", - "page": "Arrays", - "title": "Base.getindex", - "category": "method", - "text": "getindex(A, inds...)\n\nReturns a subset of array A as specified by inds, where each ind may be an Int, a Range, or a Vector. See the manual section on array indexing for details.\n\nExamples\n\njulia> A = [1 2; 3 4]\n2×2 Array{Int64,2}:\n 1 2\n 3 4\n\njulia> getindex(A, 1)\n1\n\njulia> getindex(A, [2, 1])\n2-element Array{Int64,1}:\n 3\n 1\n\njulia> getindex(A, 2:4)\n3-element Array{Int64,1}:\n 3\n 2\n 4\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Base.setindex!-Tuple{AbstractArray,Any,Vararg{Any,N} where N}", - "page": "Arrays", - "title": "Base.setindex!", - "category": "method", - "text": "setindex!(A, X, inds...)\n\nStore values from array X within some subset of A as specified by inds.\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Base.copy!-Tuple{AbstractArray,CartesianRange,AbstractArray,CartesianRange}", - "page": "Arrays", - "title": "Base.copy!", - "category": "method", - "text": "copy!(dest, Rdest::CartesianRange, src, Rsrc::CartesianRange) -> dest\n\nCopy the block of src in the range of Rsrc to the block of dest in the range of Rdest. The sizes of the two regions must match.\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Base.isassigned", - "page": "Arrays", - "title": "Base.isassigned", - "category": "function", - "text": "isassigned(array, i) -> Bool\n\nTests whether the given array has a value associated with index i. Returns false if the index is out of bounds, or has an undefined reference.\n\njulia> isassigned(rand(3, 3), 5)\ntrue\n\njulia> isassigned(rand(3, 3), 3 * 3 + 1)\nfalse\n\njulia> mutable struct Foo end\n\njulia> v = similar(rand(3), Foo)\n3-element Array{Foo,1}:\n #undef\n #undef\n #undef\n\njulia> isassigned(v, 1)\nfalse\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Base.Colon", - "page": "Arrays", - "title": "Base.Colon", - "category": "type", - "text": "Colon()\n\nColons (:) are used to signify indexing entire objects or dimensions at once.\n\nVery few operations are defined on Colons directly; instead they are converted by to_indices to an internal vector type (Base.Slice) to represent the collection of indices they span before being used.\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Base.IteratorsMD.CartesianIndex", - "page": "Arrays", - "title": "Base.IteratorsMD.CartesianIndex", - "category": "type", - "text": "CartesianIndex(i, j, k...) -> I\nCartesianIndex((i, j, k...)) -> I\n\nCreate a multidimensional index I, which can be used for indexing a multidimensional array A. In particular, A[I] is equivalent to A[i,j,k...]. One can freely mix integer and CartesianIndex indices; for example, A[Ipre, i, Ipost] (where Ipre and Ipost are CartesianIndex indices and i is an Int) can be a useful expression when writing algorithms that work along a single dimension of an array of arbitrary dimensionality.\n\nA CartesianIndex is sometimes produced by eachindex, and always when iterating with an explicit CartesianRange.\n\nExample\n\njulia> A = reshape(collect(1:16), (2, 2, 2, 2))\n2×2×2×2 Array{Int64,4}:\n[:, :, 1, 1] =\n 1 3\n 2 4\n\n[:, :, 2, 1] =\n 5 7\n 6 8\n\n[:, :, 1, 2] =\n 9 11\n 10 12\n\n[:, :, 2, 2] =\n 13 15\n 14 16\n\njulia> A[CartesianIndex((1, 1, 1, 1))]\n1\n\njulia> A[CartesianIndex((1, 1, 1, 2))]\n9\n\njulia> A[CartesianIndex((1, 1, 2, 1))]\n5\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Base.IteratorsMD.CartesianRange", - "page": "Arrays", - "title": "Base.IteratorsMD.CartesianRange", - "category": "type", - "text": "CartesianRange(Istart::CartesianIndex, Istop::CartesianIndex) -> R\nCartesianRange(sz::Dims) -> R\nCartesianRange(istart:istop, jstart:jstop, ...) -> R\n\nDefine a region R spanning a multidimensional rectangular range of integer indices. These are most commonly encountered in the context of iteration, where for I in R ... end will return CartesianIndex indices I equivalent to the nested loops\n\nfor j = jstart:jstop\n for i = istart:istop\n ...\n end\nend\n\nConsequently these can be useful for writing algorithms that work in arbitrary dimensions.\n\njulia> foreach(println, CartesianRange((2, 2, 2)))\nCartesianIndex{3}((1, 1, 1))\nCartesianIndex{3}((2, 1, 1))\nCartesianIndex{3}((1, 2, 1))\nCartesianIndex{3}((2, 2, 1))\nCartesianIndex{3}((1, 1, 2))\nCartesianIndex{3}((2, 1, 2))\nCartesianIndex{3}((1, 2, 2))\nCartesianIndex{3}((2, 2, 2))\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Base.to_indices", - "page": "Arrays", - "title": "Base.to_indices", - "category": "function", - "text": "to_indices(A, I::Tuple)\n\nConvert the tuple I to a tuple of indices for use in indexing into array A.\n\nThe returned tuple must only contain either Ints or AbstractArrays of scalar indices that are supported by array A. It will error upon encountering a novel index type that it does not know how to process.\n\nFor simple index types, it defers to the unexported Base.to_index(A, i) to process each index i. While this internal function is not intended to be called directly, Base.to_index may be extended by custom array or index types to provide custom indexing behaviors.\n\nMore complicated index types may require more context about the dimension into which they index. To support those cases, to_indices(A, I) calls to_indices(A, indices(A), I), which then recursively walks through both the given tuple of indices and the dimensional indices of A in tandem. As such, not all index types are guaranteed to propagate to Base.to_index.\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Base.checkbounds", - "page": "Arrays", - "title": "Base.checkbounds", - "category": "function", - "text": "checkbounds(Bool, A, I...)\n\nReturn true if the specified indices I are in bounds for the given array A. Subtypes of AbstractArray should specialize this method if they need to provide custom bounds checking behaviors; however, in many cases one can rely on A\'s indices and checkindex.\n\nSee also checkindex.\n\njulia> A = rand(3, 3);\n\njulia> checkbounds(Bool, A, 2)\ntrue\n\njulia> checkbounds(Bool, A, 3, 4)\nfalse\n\njulia> checkbounds(Bool, A, 1:3)\ntrue\n\njulia> checkbounds(Bool, A, 1:3, 2:4)\nfalse\n\n\n\ncheckbounds(A, I...)\n\nThrow an error if the specified indices I are not in bounds for the given array A.\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Base.checkindex", - "page": "Arrays", - "title": "Base.checkindex", - "category": "function", - "text": "checkindex(Bool, inds::AbstractUnitRange, index)\n\nReturn true if the given index is within the bounds of inds. Custom types that would like to behave as indices for all arrays can extend this method in order to provide a specialized bounds checking implementation.\n\njulia> checkindex(Bool,1:20,8)\ntrue\n\njulia> checkindex(Bool,1:20,21)\nfalse\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Indexing-and-assignment-1", - "page": "Arrays", - "title": "Indexing and assignment", - "category": "section", - "text": "Base.getindex(::AbstractArray, ::Any...)\nBase.setindex!(::AbstractArray, ::Any, ::Any...)\nBase.copy!(::AbstractArray, ::CartesianRange, ::AbstractArray, ::CartesianRange)\nBase.isassigned\nBase.Colon\nBase.CartesianIndex\nBase.CartesianRange\nBase.to_indices\nBase.checkbounds\nBase.checkindex" -}, - -{ - "location": "stdlib/arrays.html#Base.view", - "page": "Arrays", - "title": "Base.view", - "category": "function", - "text": "view(A, inds...)\n\nLike getindex, but returns a view into the parent array A with the given indices instead of making a copy. Calling getindex or setindex! on the returned SubArray computes the indices to the parent array on the fly without checking bounds.\n\njulia> A = [1 2; 3 4]\n2×2 Array{Int64,2}:\n 1 2\n 3 4\n\njulia> b = view(A, :, 1)\n2-element SubArray{Int64,1,Array{Int64,2},Tuple{Base.Slice{Base.OneTo{Int64}},Int64},true}:\n 1\n 3\n\njulia> fill!(b, 0)\n2-element SubArray{Int64,1,Array{Int64,2},Tuple{Base.Slice{Base.OneTo{Int64}},Int64},true}:\n 0\n 0\n\njulia> A # Note A has changed even though we modified b\n2×2 Array{Int64,2}:\n 0 2\n 0 4\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Base.@view", - "page": "Arrays", - "title": "Base.@view", - "category": "macro", - "text": "@view A[inds...]\n\nCreates a SubArray from an indexing expression. This can only be applied directly to a reference expression (e.g. @view A[1,2:end]), and should not be used as the target of an assignment (e.g. @view(A[1,2:end]) = ...). See also @views to switch an entire block of code to use views for slicing.\n\njulia> A = [1 2; 3 4]\n2×2 Array{Int64,2}:\n 1 2\n 3 4\n\njulia> b = @view A[:, 1]\n2-element SubArray{Int64,1,Array{Int64,2},Tuple{Base.Slice{Base.OneTo{Int64}},Int64},true}:\n 1\n 3\n\njulia> fill!(b, 0)\n2-element SubArray{Int64,1,Array{Int64,2},Tuple{Base.Slice{Base.OneTo{Int64}},Int64},true}:\n 0\n 0\n\njulia> A\n2×2 Array{Int64,2}:\n 0 2\n 0 4\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Base.@views", - "page": "Arrays", - "title": "Base.@views", - "category": "macro", - "text": "@views expression\n\nConvert every array-slicing operation in the given expression (which may be a begin/end block, loop, function, etc.) to return a view. Scalar indices, non-array types, and explicit getindex calls (as opposed to array[...]) are unaffected.\n\nNote that the @views macro only affects array[...] expressions that appear explicitly in the given expression, not array slicing that occurs in functions called by that code.\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Base.parent", - "page": "Arrays", - "title": "Base.parent", - "category": "function", - "text": "parent(A)\n\nReturns the \"parent array\" of an array view type (e.g., SubArray), or the array itself if it is not a view.\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Base.parentindexes", - "page": "Arrays", - "title": "Base.parentindexes", - "category": "function", - "text": "parentindexes(A)\n\nFrom an array view A, returns the corresponding indexes in the parent.\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Base.slicedim", - "page": "Arrays", - "title": "Base.slicedim", - "category": "function", - "text": "slicedim(A, d::Integer, i)\n\nReturn all the data of A where the index for dimension d equals i. Equivalent to A[:,:,...,i,:,:,...] where i is in position d.\n\nExample\n\njulia> A = [1 2 3 4; 5 6 7 8]\n2×4 Array{Int64,2}:\n 1 2 3 4\n 5 6 7 8\n\njulia> slicedim(A,2,3)\n2-element Array{Int64,1}:\n 3\n 7\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Base.reinterpret", - "page": "Arrays", - "title": "Base.reinterpret", - "category": "function", - "text": "reinterpret(type, A)\n\nChange the type-interpretation of a block of memory. For arrays, this constructs an array with the same binary data as the given array, but with the specified element type. For example, reinterpret(Float32, UInt32(7)) interprets the 4 bytes corresponding to UInt32(7) as a Float32.\n\nwarning: Warning\nIt is not allowed to reinterpret an array to an element type with a larger alignment then the alignment of the array. For a normal Array, this is the alignment of its element type. For a reinterpreted array, this is the alignment of the Array it was reinterpreted from. For example, reinterpret(UInt32, UInt8[0, 0, 0, 0]) is not allowed but reinterpret(UInt32, reinterpret(UInt8, Float32[1.0])) is allowed.\n\nExamples\n\njulia> reinterpret(Float32, UInt32(7))\n1.0f-44\n\njulia> reinterpret(Float32, UInt32[1 2 3 4 5])\n1×5 Array{Float32,2}:\n 1.4013f-45 2.8026f-45 4.2039f-45 5.60519f-45 7.00649f-45\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Base.reshape", - "page": "Arrays", - "title": "Base.reshape", - "category": "function", - "text": "reshape(A, dims...) -> R\nreshape(A, dims) -> R\n\nReturn an array R with the same data as A, but with different dimension sizes or number of dimensions. The two arrays share the same underlying data, so that setting elements of R alters the values of A and vice versa.\n\nThe new dimensions may be specified either as a list of arguments or as a shape tuple. At most one dimension may be specified with a :, in which case its length is computed such that its product with all the specified dimensions is equal to the length of the original array A. The total number of elements must not change.\n\njulia> A = collect(1:16)\n16-element Array{Int64,1}:\n 1\n 2\n 3\n 4\n 5\n 6\n 7\n 8\n 9\n 10\n 11\n 12\n 13\n 14\n 15\n 16\n\njulia> reshape(A, (4, 4))\n4×4 Array{Int64,2}:\n 1 5 9 13\n 2 6 10 14\n 3 7 11 15\n 4 8 12 16\n\njulia> reshape(A, 2, :)\n2×8 Array{Int64,2}:\n 1 3 5 7 9 11 13 15\n 2 4 6 8 10 12 14 16\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Base.squeeze", - "page": "Arrays", - "title": "Base.squeeze", - "category": "function", - "text": "squeeze(A, dims)\n\nRemove the dimensions specified by dims from array A. Elements of dims must be unique and within the range 1:ndims(A). size(A,i) must equal 1 for all i in dims.\n\nExample\n\njulia> a = reshape(collect(1:4),(2,2,1,1))\n2×2×1×1 Array{Int64,4}:\n[:, :, 1, 1] =\n 1 3\n 2 4\n\njulia> squeeze(a,3)\n2×2×1 Array{Int64,3}:\n[:, :, 1] =\n 1 3\n 2 4\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Base.vec", - "page": "Arrays", - "title": "Base.vec", - "category": "function", - "text": "vec(a::AbstractArray) -> Vector\n\nReshape the array a as a one-dimensional column vector. The resulting array shares the same underlying data as a, so modifying one will also modify the other.\n\nExample\n\njulia> a = [1 2 3; 4 5 6]\n2×3 Array{Int64,2}:\n 1 2 3\n 4 5 6\n\njulia> vec(a)\n6-element Array{Int64,1}:\n 1\n 4\n 2\n 5\n 3\n 6\n\nSee also reshape.\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Views-(SubArrays-and-other-view-types)-1", - "page": "Arrays", - "title": "Views (SubArrays and other view types)", - "category": "section", - "text": "Base.view\nBase.@view\nBase.@views\nBase.parent\nBase.parentindexes\nBase.slicedim\nBase.reinterpret\nBase.reshape\nBase.squeeze\nBase.vec" -}, - -{ - "location": "stdlib/arrays.html#Base.cat", - "page": "Arrays", - "title": "Base.cat", - "category": "function", - "text": "cat(dims, A...)\n\nConcatenate the input arrays along the specified dimensions in the iterable dims. For dimensions not in dims, all input arrays should have the same size, which will also be the size of the output array along that dimension. For dimensions in dims, the size of the output array is the sum of the sizes of the input arrays along that dimension. If dims is a single number, the different arrays are tightly stacked along that dimension. If dims is an iterable containing several dimensions, this allows one to construct block diagonal matrices and their higher-dimensional analogues by simultaneously increasing several dimensions for every new input array and putting zero blocks elsewhere. For example, cat([1,2], matrices...) builds a block diagonal matrix, i.e. a block matrix with matrices[1], matrices[2], ... as diagonal blocks and matching zero blocks away from the diagonal.\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Base.vcat", - "page": "Arrays", - "title": "Base.vcat", - "category": "function", - "text": "vcat(A...)\n\nConcatenate along dimension 1.\n\njulia> a = [1 2 3 4 5]\n1×5 Array{Int64,2}:\n 1 2 3 4 5\n\njulia> b = [6 7 8 9 10; 11 12 13 14 15]\n2×5 Array{Int64,2}:\n 6 7 8 9 10\n 11 12 13 14 15\n\njulia> vcat(a,b)\n3×5 Array{Int64,2}:\n 1 2 3 4 5\n 6 7 8 9 10\n 11 12 13 14 15\n\njulia> c = ([1 2 3], [4 5 6])\n([1 2 3], [4 5 6])\n\njulia> vcat(c...)\n2×3 Array{Int64,2}:\n 1 2 3\n 4 5 6\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Base.hcat", - "page": "Arrays", - "title": "Base.hcat", - "category": "function", - "text": "hcat(A...)\n\nConcatenate along dimension 2.\n\njulia> a = [1; 2; 3; 4; 5]\n5-element Array{Int64,1}:\n 1\n 2\n 3\n 4\n 5\n\njulia> b = [6 7; 8 9; 10 11; 12 13; 14 15]\n5×2 Array{Int64,2}:\n 6 7\n 8 9\n 10 11\n 12 13\n 14 15\n\njulia> hcat(a,b)\n5×3 Array{Int64,2}:\n 1 6 7\n 2 8 9\n 3 10 11\n 4 12 13\n 5 14 15\n\njulia> c = ([1; 2; 3], [4; 5; 6])\n([1, 2, 3], [4, 5, 6])\n\njulia> hcat(c...)\n3×2 Array{Int64,2}:\n 1 4\n 2 5\n 3 6\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Base.hvcat", - "page": "Arrays", - "title": "Base.hvcat", - "category": "function", - "text": "hvcat(rows::Tuple{Vararg{Int}}, values...)\n\nHorizontal and vertical concatenation in one call. This function is called for block matrix syntax. The first argument specifies the number of arguments to concatenate in each block row.\n\njulia> a, b, c, d, e, f = 1, 2, 3, 4, 5, 6\n(1, 2, 3, 4, 5, 6)\n\njulia> [a b c; d e f]\n2×3 Array{Int64,2}:\n 1 2 3\n 4 5 6\n\njulia> hvcat((3,3), a,b,c,d,e,f)\n2×3 Array{Int64,2}:\n 1 2 3\n 4 5 6\n\njulia> [a b;c d; e f]\n3×2 Array{Int64,2}:\n 1 2\n 3 4\n 5 6\n\njulia> hvcat((2,2,2), a,b,c,d,e,f)\n3×2 Array{Int64,2}:\n 1 2\n 3 4\n 5 6\n\nIf the first argument is a single integer n, then all block rows are assumed to have n block columns.\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Base.flipdim", - "page": "Arrays", - "title": "Base.flipdim", - "category": "function", - "text": "flipdim(A, d::Integer)\n\nReverse A in dimension d.\n\nExample\n\njulia> b = [1 2; 3 4]\n2×2 Array{Int64,2}:\n 1 2\n 3 4\n\njulia> flipdim(b,2)\n2×2 Array{Int64,2}:\n 2 1\n 4 3\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Base.circshift", - "page": "Arrays", - "title": "Base.circshift", - "category": "function", - "text": "circshift(A, shifts)\n\nCircularly shift the data in an array. The second argument is a vector giving the amount to shift in each dimension.\n\nExample\n\njulia> b = reshape(collect(1:16), (4,4))\n4×4 Array{Int64,2}:\n 1 5 9 13\n 2 6 10 14\n 3 7 11 15\n 4 8 12 16\n\njulia> circshift(b, (0,2))\n4×4 Array{Int64,2}:\n 9 13 1 5\n 10 14 2 6\n 11 15 3 7\n 12 16 4 8\n\njulia> circshift(b, (-1,0))\n4×4 Array{Int64,2}:\n 2 6 10 14\n 3 7 11 15\n 4 8 12 16\n 1 5 9 13\n\nSee also circshift!.\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Base.circshift!", - "page": "Arrays", - "title": "Base.circshift!", - "category": "function", - "text": "circshift!(dest, src, shifts)\n\nCircularly shift the data in src, storing the result in dest. shifts specifies the amount to shift in each dimension.\n\nThe dest array must be distinct from the src array (they cannot alias each other).\n\nSee also circshift.\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Base.circcopy!", - "page": "Arrays", - "title": "Base.circcopy!", - "category": "function", - "text": "circcopy!(dest, src)\n\nCopy src to dest, indexing each dimension modulo its length. src and dest must have the same size, but can be offset in their indices; any offset results in a (circular) wraparound. If the arrays have overlapping indices, then on the domain of the overlap dest agrees with src.\n\nExample\n\njulia> src = reshape(collect(1:16), (4,4))\n4×4 Array{Int64,2}:\n 1 5 9 13\n 2 6 10 14\n 3 7 11 15\n 4 8 12 16\n\njulia> dest = OffsetArray{Int}((0:3,2:5))\n\njulia> circcopy!(dest, src)\nOffsetArrays.OffsetArray{Int64,2,Array{Int64,2}} with indices 0:3×2:5:\n 8 12 16 4\n 5 9 13 1\n 6 10 14 2\n 7 11 15 3\n\njulia> dest[1:3,2:4] == src[1:3,2:4]\ntrue\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Base.contains-Tuple{Function,Any,Any}", - "page": "Arrays", - "title": "Base.contains", - "category": "method", - "text": "contains(fun, itr, x) -> Bool\n\nReturns true if there is at least one element y in itr such that fun(y,x) is true.\n\njulia> vec = [10, 100, 200]\n3-element Array{Int64,1}:\n 10\n 100\n 200\n\njulia> contains(==, vec, 200)\ntrue\n\njulia> contains(==, vec, 300)\nfalse\n\njulia> contains(>, vec, 100)\ntrue\n\njulia> contains(>, vec, 200)\nfalse\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Base.find-Tuple{Any}", - "page": "Arrays", - "title": "Base.find", - "category": "method", - "text": "find(A)\n\nReturn a vector of the linear indexes of the non-zeros in A (determined by A[i]!=0). A common use of this is to convert a boolean array to an array of indexes of the true elements. If there are no non-zero elements of A, find returns an empty array.\n\nExamples\n\njulia> A = [true false; false true]\n2×2 Array{Bool,2}:\n true false\n false true\n\njulia> find(A)\n2-element Array{Int64,1}:\n 1\n 4\n\njulia> find(zeros(3))\n0-element Array{Int64,1}\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Base.find-Tuple{Function,Any}", - "page": "Arrays", - "title": "Base.find", - "category": "method", - "text": "find(f::Function, A)\n\nReturn a vector I of the linear indexes of A where f(A[I]) returns true. If there are no such elements of A, find returns an empty array.\n\nExamples\n\njulia> A = [1 2; 3 4]\n2×2 Array{Int64,2}:\n 1 2\n 3 4\n\njulia> find(isodd,A)\n2-element Array{Int64,1}:\n 1\n 2\n\njulia> find(isodd, [2, 4])\n0-element Array{Int64,1}\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Base.findn", - "page": "Arrays", - "title": "Base.findn", - "category": "function", - "text": "findn(A)\n\nReturn a vector of indexes for each dimension giving the locations of the non-zeros in A (determined by A[i]!=0). If there are no non-zero elements of A, findn returns a 2-tuple of empty arrays.\n\nExamples\n\njulia> A = [1 2 0; 0 0 3; 0 4 0]\n3×3 Array{Int64,2}:\n 1 2 0\n 0 0 3\n 0 4 0\n\njulia> findn(A)\n([1, 1, 3, 2], [1, 2, 2, 3])\n\njulia> A = zeros(2,2)\n2×2 Array{Float64,2}:\n 0.0 0.0\n 0.0 0.0\n\njulia> findn(A)\n(Int64[], Int64[])\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Base.findnz", - "page": "Arrays", - "title": "Base.findnz", - "category": "function", - "text": "findnz(A)\n\nReturn a tuple (I, J, V) where I and J are the row and column indexes of the non-zero values in matrix A, and V is a vector of the non-zero values.\n\nExample\n\njulia> A = [1 2 0; 0 0 3; 0 4 0]\n3×3 Array{Int64,2}:\n 1 2 0\n 0 0 3\n 0 4 0\n\njulia> findnz(A)\n([1, 1, 3, 2], [1, 2, 2, 3], [1, 2, 4, 3])\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Base.findfirst-Tuple{Any}", - "page": "Arrays", - "title": "Base.findfirst", - "category": "method", - "text": "findfirst(A)\n\nReturn the linear index of the first non-zero value in A (determined by A[i]!=0). Returns 0 if no such value is found.\n\nExamples\n\njulia> A = [0 0; 1 0]\n2×2 Array{Int64,2}:\n 0 0\n 1 0\n\njulia> findfirst(A)\n2\n\njulia> findfirst(zeros(3))\n0\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Base.findfirst-Tuple{Any,Any}", - "page": "Arrays", - "title": "Base.findfirst", - "category": "method", - "text": "findfirst(A, v)\n\nReturn the linear index of the first element equal to v in A. Returns 0 if v is not found.\n\nExamples\n\njulia> A = [4 6; 2 2]\n2×2 Array{Int64,2}:\n 4 6\n 2 2\n\njulia> findfirst(A,2)\n2\n\njulia> findfirst(A,3)\n0\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Base.findfirst-Tuple{Function,Any}", - "page": "Arrays", - "title": "Base.findfirst", - "category": "method", - "text": "findfirst(predicate::Function, A)\n\nReturn the linear index of the first element of A for which predicate returns true. Returns 0 if there is no such element.\n\nExamples\n\njulia> A = [1 4; 2 2]\n2×2 Array{Int64,2}:\n 1 4\n 2 2\n\njulia> findfirst(iseven, A)\n2\n\njulia> findfirst(x -> x>10, A)\n0\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Base.findlast-Tuple{Any}", - "page": "Arrays", - "title": "Base.findlast", - "category": "method", - "text": "findlast(A)\n\nReturn the linear index of the last non-zero value in A (determined by A[i]!=0). Returns 0 if there is no non-zero value in A.\n\nExamples\n\njulia> A = [1 0; 1 0]\n2×2 Array{Int64,2}:\n 1 0\n 1 0\n\njulia> findlast(A)\n2\n\njulia> A = zeros(2,2)\n2×2 Array{Float64,2}:\n 0.0 0.0\n 0.0 0.0\n\njulia> findlast(A)\n0\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Base.findlast-Tuple{Any,Any}", - "page": "Arrays", - "title": "Base.findlast", - "category": "method", - "text": "findlast(A, v)\n\nReturn the linear index of the last element equal to v in A. Returns 0 if there is no element of A equal to v.\n\nExamples\n\njulia> A = [1 2; 2 1]\n2×2 Array{Int64,2}:\n 1 2\n 2 1\n\njulia> findlast(A,1)\n4\n\njulia> findlast(A,2)\n3\n\njulia> findlast(A,3)\n0\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Base.findlast-Tuple{Function,Any}", - "page": "Arrays", - "title": "Base.findlast", - "category": "method", - "text": "findlast(predicate::Function, A)\n\nReturn the linear index of the last element of A for which predicate returns true. Returns 0 if there is no such element.\n\nExamples\n\njulia> A = [1 2; 3 4]\n2×2 Array{Int64,2}:\n 1 2\n 3 4\n\njulia> findlast(isodd, A)\n2\n\njulia> findlast(x -> x > 5, A)\n0\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Base.findnext-Tuple{Any,Integer}", - "page": "Arrays", - "title": "Base.findnext", - "category": "method", - "text": "findnext(A, i::Integer)\n\nFind the next linear index >= i of a non-zero element of A, or 0 if not found.\n\nExamples\n\njulia> A = [0 0; 1 0]\n2×2 Array{Int64,2}:\n 0 0\n 1 0\n\njulia> findnext(A,1)\n2\n\njulia> findnext(A,3)\n0\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Base.findnext-Tuple{Function,Any,Integer}", - "page": "Arrays", - "title": "Base.findnext", - "category": "method", - "text": "findnext(predicate::Function, A, i::Integer)\n\nFind the next linear index >= i of an element of A for which predicate returns true, or 0 if not found.\n\nExamples\n\njulia> A = [1 4; 2 2]\n2×2 Array{Int64,2}:\n 1 4\n 2 2\n\njulia> findnext(isodd, A, 1)\n1\n\njulia> findnext(isodd, A, 2)\n0\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Base.findnext-Tuple{Any,Any,Integer}", - "page": "Arrays", - "title": "Base.findnext", - "category": "method", - "text": "findnext(A, v, i::Integer)\n\nFind the next linear index >= i of an element of A equal to v (using ==), or 0 if not found.\n\nExamples\n\njulia> A = [1 4; 2 2]\n2×2 Array{Int64,2}:\n 1 4\n 2 2\n\njulia> findnext(A,4,4)\n0\n\njulia> findnext(A,4,3)\n3\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Base.findprev-Tuple{Any,Integer}", - "page": "Arrays", - "title": "Base.findprev", - "category": "method", - "text": "findprev(A, i::Integer)\n\nFind the previous linear index <= i of a non-zero element of A, or 0 if not found.\n\nExamples\n\njulia> A = [0 0; 1 2]\n2×2 Array{Int64,2}:\n 0 0\n 1 2\n\njulia> findprev(A,2)\n2\n\njulia> findprev(A,1)\n0\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Base.findprev-Tuple{Function,Any,Integer}", - "page": "Arrays", - "title": "Base.findprev", - "category": "method", - "text": "findprev(predicate::Function, A, i::Integer)\n\nFind the previous linear index <= i of an element of A for which predicate returns true, or 0 if not found.\n\nExamples\n\njulia> A = [4 6; 1 2]\n2×2 Array{Int64,2}:\n 4 6\n 1 2\n\njulia> findprev(isodd, A, 1)\n0\n\njulia> findprev(isodd, A, 3)\n2\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Base.findprev-Tuple{Any,Any,Integer}", - "page": "Arrays", - "title": "Base.findprev", - "category": "method", - "text": "findprev(A, v, i::Integer)\n\nFind the previous linear index <= i of an element of A equal to v (using ==), or 0 if not found.\n\nExamples\n\njulia> A = [0 0; 1 2]\n2×2 Array{Int64,2}:\n 0 0\n 1 2\n\njulia> findprev(A, 1, 4)\n2\n\njulia> findprev(A, 1, 1)\n0\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Base.permutedims", - "page": "Arrays", - "title": "Base.permutedims", - "category": "function", - "text": "permutedims(A, perm)\n\nPermute the dimensions of array A. perm is a vector specifying a permutation of length ndims(A). This is a generalization of transpose for multi-dimensional arrays. Transpose is equivalent to permutedims(A, [2,1]).\n\nSee also: PermutedDimsArray.\n\nExample\n\njulia> A = reshape(collect(1:8), (2,2,2))\n2×2×2 Array{Int64,3}:\n[:, :, 1] =\n 1 3\n 2 4\n\n[:, :, 2] =\n 5 7\n 6 8\n\njulia> permutedims(A, [3, 2, 1])\n2×2×2 Array{Int64,3}:\n[:, :, 1] =\n 1 3\n 5 7\n\n[:, :, 2] =\n 2 4\n 6 8\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Base.permutedims!", - "page": "Arrays", - "title": "Base.permutedims!", - "category": "function", - "text": "permutedims!(dest, src, perm)\n\nPermute the dimensions of array src and store the result in the array dest. perm is a vector specifying a permutation of length ndims(src). The preallocated array dest should have size(dest) == size(src)[perm] and is completely overwritten. No in-place permutation is supported and unexpected results will happen if src and dest have overlapping memory regions.\n\nSee also permutedims.\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Base.PermutedDimsArrays.PermutedDimsArray", - "page": "Arrays", - "title": "Base.PermutedDimsArrays.PermutedDimsArray", - "category": "type", - "text": "PermutedDimsArray(A, perm) -> B\n\nGiven an AbstractArray A, create a view B such that the dimensions appear to be permuted. Similar to permutedims, except that no copying occurs (B shares storage with A).\n\nSee also: permutedims.\n\nExample\n\njulia> A = rand(3,5,4);\n\njulia> B = PermutedDimsArray(A, (3,1,2));\n\njulia> size(B)\n(4, 3, 5)\n\njulia> B[3,1,2] == A[1,2,3]\ntrue\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Base.promote_shape", - "page": "Arrays", - "title": "Base.promote_shape", - "category": "function", - "text": "promote_shape(s1, s2)\n\nCheck two array shapes for compatibility, allowing trailing singleton dimensions, and return whichever shape has more dimensions.\n\njulia> a = ones(3,4,1,1,1);\n\njulia> b = ones(3,4);\n\njulia> promote_shape(a,b)\n(Base.OneTo(3), Base.OneTo(4), Base.OneTo(1), Base.OneTo(1), Base.OneTo(1))\n\njulia> promote_shape((2,3,1,4), (2, 3, 1, 4, 1))\n(2, 3, 1, 4, 1)\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Concatenation-and-permutation-1", - "page": "Arrays", - "title": "Concatenation and permutation", - "category": "section", - "text": "Base.cat\nBase.vcat\nBase.hcat\nBase.hvcat\nBase.flipdim\nBase.circshift\nBase.circshift!\nBase.circcopy!\nBase.contains(::Function, ::Any, ::Any)\nBase.find(::Any)\nBase.find(::Function, ::Any)\nBase.findn\nBase.findnz\nBase.findfirst(::Any)\nBase.findfirst(::Any, ::Any)\nBase.findfirst(::Function, ::Any)\nBase.findlast(::Any)\nBase.findlast(::Any, ::Any)\nBase.findlast(::Function, ::Any)\nBase.findnext(::Any, ::Integer)\nBase.findnext(::Function, ::Any, ::Integer)\nBase.findnext(::Any, ::Any, ::Integer)\nBase.findprev(::Any, ::Integer)\nBase.findprev(::Function, ::Any, ::Integer)\nBase.findprev(::Any, ::Any, ::Integer)\nBase.permutedims\nBase.permutedims!\nBase.PermutedDimsArray\nBase.promote_shape" -}, - -{ - "location": "stdlib/arrays.html#Base.accumulate-Tuple{Any,Any,Integer}", - "page": "Arrays", - "title": "Base.accumulate", - "category": "method", - "text": "accumulate(op, A, dim=1)\n\nCumulative operation op along a dimension dim (defaults to 1). See also accumulate! to use a preallocated output array, both for performance and to control the precision of the output (e.g. to avoid overflow). For common operations there are specialized variants of accumulate, see: cumsum, cumprod\n\njulia> accumulate(+, [1,2,3])\n3-element Array{Int64,1}:\n 1\n 3\n 6\n\njulia> accumulate(*, [1,2,3])\n3-element Array{Int64,1}:\n 1\n 2\n 6\n\n\n\naccumulate(op, v0, A)\n\nLike accumulate, but using a starting element v0. The first entry of the result will be op(v0, first(A)). For example:\n\njulia> accumulate(+, 100, [1,2,3])\n3-element Array{Int64,1}:\n 101\n 103\n 106\n\njulia> accumulate(min, 0, [1,2,-1])\n3-element Array{Int64,1}:\n 0\n 0\n -1\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Base.accumulate!", - "page": "Arrays", - "title": "Base.accumulate!", - "category": "function", - "text": "accumulate!(op, B, A, dim=1)\n\nCumulative operation op on A along a dimension, storing the result in B. The dimension defaults to 1. See also accumulate.\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Base.cumprod", - "page": "Arrays", - "title": "Base.cumprod", - "category": "function", - "text": "cumprod(A, dim=1)\n\nCumulative product along a dimension dim (defaults to 1). See also cumprod! to use a preallocated output array, both for performance and to control the precision of the output (e.g. to avoid overflow).\n\njulia> a = [1 2 3; 4 5 6]\n2×3 Array{Int64,2}:\n 1 2 3\n 4 5 6\n\njulia> cumprod(a,1)\n2×3 Array{Int64,2}:\n 1 2 3\n 4 10 18\n\njulia> cumprod(a,2)\n2×3 Array{Int64,2}:\n 1 2 6\n 4 20 120\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Base.cumprod!", - "page": "Arrays", - "title": "Base.cumprod!", - "category": "function", - "text": "cumprod!(B, A, dim::Integer=1)\n\nCumulative product of A along a dimension, storing the result in B. The dimension defaults to 1. See also cumprod.\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Base.cumsum", - "page": "Arrays", - "title": "Base.cumsum", - "category": "function", - "text": "cumsum(A, dim=1)\n\nCumulative sum along a dimension dim (defaults to 1). See also cumsum! to use a preallocated output array, both for performance and to control the precision of the output (e.g. to avoid overflow).\n\njulia> a = [1 2 3; 4 5 6]\n2×3 Array{Int64,2}:\n 1 2 3\n 4 5 6\n\njulia> cumsum(a,1)\n2×3 Array{Int64,2}:\n 1 2 3\n 5 7 9\n\njulia> cumsum(a,2)\n2×3 Array{Int64,2}:\n 1 3 6\n 4 9 15\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Base.cumsum!", - "page": "Arrays", - "title": "Base.cumsum!", - "category": "function", - "text": "cumsum!(B, A, dim::Integer=1)\n\nCumulative sum of A along a dimension, storing the result in B. The dimension defaults to 1. See also cumsum.\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Base.cumsum_kbn", - "page": "Arrays", - "title": "Base.cumsum_kbn", - "category": "function", - "text": "cumsum_kbn(A, [dim::Integer=1])\n\nCumulative sum along a dimension, using the Kahan-Babuska-Neumaier compensated summation algorithm for additional accuracy. The dimension defaults to 1.\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Base.LinAlg.diff", - "page": "Arrays", - "title": "Base.LinAlg.diff", - "category": "function", - "text": "diff(A, [dim::Integer=1])\n\nFinite difference operator of matrix or vector A. If A is a matrix, compute the finite difference over a dimension dim (default 1).\n\nExample\n\njulia> a = [2 4; 6 16]\n2×2 Array{Int64,2}:\n 2 4\n 6 16\n\njulia> diff(a,2)\n2×1 Array{Int64,2}:\n 2\n 10\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Base.LinAlg.gradient", - "page": "Arrays", - "title": "Base.LinAlg.gradient", - "category": "function", - "text": "gradient(F::AbstractVector, [h::Real])\n\nCompute differences along vector F, using h as the spacing between points. The default spacing is one.\n\nExample\n\njulia> a = [2,4,6,8];\n\njulia> gradient(a)\n4-element Array{Float64,1}:\n 2.0\n 2.0\n 2.0\n 2.0\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Base.rot180", - "page": "Arrays", - "title": "Base.rot180", - "category": "function", - "text": "rot180(A)\n\nRotate matrix A 180 degrees.\n\nExample\n\njulia> a = [1 2; 3 4]\n2×2 Array{Int64,2}:\n 1 2\n 3 4\n\njulia> rot180(a)\n2×2 Array{Int64,2}:\n 4 3\n 2 1\n\n\n\nrot180(A, k)\n\nRotate matrix A 180 degrees an integer k number of times. If k is even, this is equivalent to a copy.\n\nExamples\n\njulia> a = [1 2; 3 4]\n2×2 Array{Int64,2}:\n 1 2\n 3 4\n\njulia> rot180(a,1)\n2×2 Array{Int64,2}:\n 4 3\n 2 1\n\njulia> rot180(a,2)\n2×2 Array{Int64,2}:\n 1 2\n 3 4\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Base.rotl90", - "page": "Arrays", - "title": "Base.rotl90", - "category": "function", - "text": "rotl90(A)\n\nRotate matrix A left 90 degrees.\n\nExample\n\njulia> a = [1 2; 3 4]\n2×2 Array{Int64,2}:\n 1 2\n 3 4\n\njulia> rotl90(a)\n2×2 Array{Int64,2}:\n 2 4\n 1 3\n\n\n\nrotl90(A, k)\n\nRotate matrix A left 90 degrees an integer k number of times. If k is zero or a multiple of four, this is equivalent to a copy.\n\nExamples\n\njulia> a = [1 2; 3 4]\n2×2 Array{Int64,2}:\n 1 2\n 3 4\n\njulia> rotl90(a,1)\n2×2 Array{Int64,2}:\n 2 4\n 1 3\n\njulia> rotl90(a,2)\n2×2 Array{Int64,2}:\n 4 3\n 2 1\n\njulia> rotl90(a,3)\n2×2 Array{Int64,2}:\n 3 1\n 4 2\n\njulia> rotl90(a,4)\n2×2 Array{Int64,2}:\n 1 2\n 3 4\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Base.rotr90", - "page": "Arrays", - "title": "Base.rotr90", - "category": "function", - "text": "rotr90(A)\n\nRotate matrix A right 90 degrees.\n\nExample\n\njulia> a = [1 2; 3 4]\n2×2 Array{Int64,2}:\n 1 2\n 3 4\n\njulia> rotr90(a)\n2×2 Array{Int64,2}:\n 3 1\n 4 2\n\n\n\nrotr90(A, k)\n\nRotate matrix A right 90 degrees an integer k number of times. If k is zero or a multiple of four, this is equivalent to a copy.\n\nExamples\n\njulia> a = [1 2; 3 4]\n2×2 Array{Int64,2}:\n 1 2\n 3 4\n\njulia> rotr90(a,1)\n2×2 Array{Int64,2}:\n 3 1\n 4 2\n\njulia> rotr90(a,2)\n2×2 Array{Int64,2}:\n 4 3\n 2 1\n\njulia> rotr90(a,3)\n2×2 Array{Int64,2}:\n 2 4\n 1 3\n\njulia> rotr90(a,4)\n2×2 Array{Int64,2}:\n 1 2\n 3 4\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Base.reducedim", - "page": "Arrays", - "title": "Base.reducedim", - "category": "function", - "text": "reducedim(f, A, region[, v0])\n\nReduce 2-argument function f along dimensions of A. region is a vector specifying the dimensions to reduce, and v0 is the initial value to use in the reductions. For +, *, max and min the v0 argument is optional.\n\nThe associativity of the reduction is implementation-dependent; if you need a particular associativity, e.g. left-to-right, you should write your own loop. See documentation for reduce.\n\nExamples\n\njulia> a = reshape(collect(1:16), (4,4))\n4×4 Array{Int64,2}:\n 1 5 9 13\n 2 6 10 14\n 3 7 11 15\n 4 8 12 16\n\njulia> reducedim(max, a, 2)\n4×1 Array{Int64,2}:\n 13\n 14\n 15\n 16\n\njulia> reducedim(max, a, 1)\n1×4 Array{Int64,2}:\n 4 8 12 16\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Base.mapreducedim", - "page": "Arrays", - "title": "Base.mapreducedim", - "category": "function", - "text": "mapreducedim(f, op, A, region[, v0])\n\nEvaluates to the same as reducedim(op, map(f, A), region, f(v0)), but is generally faster because the intermediate array is avoided.\n\nExamples\n\njulia> a = reshape(collect(1:16), (4,4))\n4×4 Array{Int64,2}:\n 1 5 9 13\n 2 6 10 14\n 3 7 11 15\n 4 8 12 16\n\njulia> mapreducedim(isodd, *, a, 1)\n1×4 Array{Bool,2}:\n false false false false\n\njulia> mapreducedim(isodd, |, a, 1, true)\n1×4 Array{Bool,2}:\n true true true true\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Base.mapslices", - "page": "Arrays", - "title": "Base.mapslices", - "category": "function", - "text": "mapslices(f, A, dims)\n\nTransform the given dimensions of array A using function f. f is called on each slice of A of the form A[...,:,...,:,...]. dims is an integer vector specifying where the colons go in this expression. The results are concatenated along the remaining dimensions. For example, if dims is [1,2] and A is 4-dimensional, f is called on A[:,:,i,j] for all i and j.\n\nExamples\n\njulia> a = reshape(collect(1:16),(2,2,2,2))\n2×2×2×2 Array{Int64,4}:\n[:, :, 1, 1] =\n 1 3\n 2 4\n\n[:, :, 2, 1] =\n 5 7\n 6 8\n\n[:, :, 1, 2] =\n 9 11\n 10 12\n\n[:, :, 2, 2] =\n 13 15\n 14 16\n\njulia> mapslices(sum, a, [1,2])\n1×1×2×2 Array{Int64,4}:\n[:, :, 1, 1] =\n 10\n\n[:, :, 2, 1] =\n 26\n\n[:, :, 1, 2] =\n 42\n\n[:, :, 2, 2] =\n 58\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Base.sum_kbn", - "page": "Arrays", - "title": "Base.sum_kbn", - "category": "function", - "text": "sum_kbn(A)\n\nReturns the sum of all elements of A, using the Kahan-Babuska-Neumaier compensated summation algorithm for additional accuracy.\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Array-functions-1", - "page": "Arrays", - "title": "Array functions", - "category": "section", - "text": "Base.accumulate(::Any, ::Any, ::Integer)\nBase.accumulate!\nBase.cumprod\nBase.cumprod!\nBase.cumsum\nBase.cumsum!\nBase.cumsum_kbn\nBase.LinAlg.diff\nBase.LinAlg.gradient\nBase.rot180\nBase.rotl90\nBase.rotr90\nBase.reducedim\nBase.mapreducedim\nBase.mapslices\nBase.sum_kbn" -}, - -{ - "location": "stdlib/arrays.html#Base.Random.randperm", - "page": "Arrays", - "title": "Base.Random.randperm", - "category": "function", - "text": "randperm([rng=GLOBAL_RNG,] n::Integer)\n\nConstruct a random permutation of length n. The optional rng argument specifies a random number generator (see Random Numbers). To randomly permute a arbitrary vector, see shuffle or shuffle!.\n\nExample\n\njulia> rng = MersenneTwister(1234);\n\njulia> randperm(rng, 4)\n4-element Array{Int64,1}:\n 2\n 1\n 4\n 3\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Base.invperm", - "page": "Arrays", - "title": "Base.invperm", - "category": "function", - "text": "invperm(v)\n\nReturn the inverse permutation of v. If B = A[v], then A == B[invperm(v)].\n\nExample\n\njulia> v = [2; 4; 3; 1];\n\njulia> invperm(v)\n4-element Array{Int64,1}:\n 4\n 1\n 3\n 2\n\njulia> A = [\'a\',\'b\',\'c\',\'d\'];\n\njulia> B = A[v]\n4-element Array{Char,1}:\n \'b\'\n \'d\'\n \'c\'\n \'a\'\n\njulia> B[invperm(v)]\n4-element Array{Char,1}:\n \'a\'\n \'b\'\n \'c\'\n \'d\'\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Base.isperm", - "page": "Arrays", - "title": "Base.isperm", - "category": "function", - "text": "isperm(v) -> Bool\n\nReturns true if v is a valid permutation.\n\nExamples\n\njulia> isperm([1; 2])\ntrue\n\njulia> isperm([1; 3])\nfalse\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Base.permute!-Tuple{Any,AbstractArray{T,1} where T}", - "page": "Arrays", - "title": "Base.permute!", - "category": "method", - "text": "permute!(v, p)\n\nPermute vector v in-place, according to permutation p. No checking is done to verify that p is a permutation.\n\nTo return a new permutation, use v[p]. Note that this is generally faster than permute!(v,p) for large vectors.\n\nSee also ipermute!.\n\nExample\n\njulia> A = [1, 1, 3, 4];\n\njulia> perm = [2, 4, 3, 1];\n\njulia> permute!(A, perm);\n\njulia> A\n4-element Array{Int64,1}:\n 1\n 4\n 3\n 1\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Base.ipermute!", - "page": "Arrays", - "title": "Base.ipermute!", - "category": "function", - "text": "ipermute!(v, p)\n\nLike permute!, but the inverse of the given permutation is applied.\n\nExample\n\njulia> A = [1, 1, 3, 4];\n\njulia> perm = [2, 4, 3, 1];\n\njulia> ipermute!(A, perm);\n\njulia> A\n4-element Array{Int64,1}:\n 4\n 1\n 3\n 1\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Base.Random.randcycle", - "page": "Arrays", - "title": "Base.Random.randcycle", - "category": "function", - "text": "randcycle([rng=GLOBAL_RNG,] n::Integer)\n\nConstruct a random cyclic permutation of length n. The optional rng argument specifies a random number generator, see Random Numbers.\n\nExample\n\njulia> rng = MersenneTwister(1234);\n\njulia> randcycle(rng, 6)\n6-element Array{Int64,1}:\n 3\n 5\n 4\n 6\n 1\n 2\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Base.Random.shuffle", - "page": "Arrays", - "title": "Base.Random.shuffle", - "category": "function", - "text": "shuffle([rng=GLOBAL_RNG,] v)\n\nReturn a randomly permuted copy of v. The optional rng argument specifies a random number generator (see Random Numbers). To permute v in-place, see shuffle!. To obtain randomly permuted indices, see randperm.\n\nExample\n\njulia> rng = MersenneTwister(1234);\n\njulia> shuffle(rng, collect(1:10))\n10-element Array{Int64,1}:\n 6\n 1\n 10\n 2\n 3\n 9\n 5\n 7\n 4\n 8\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Base.Random.shuffle!", - "page": "Arrays", - "title": "Base.Random.shuffle!", - "category": "function", - "text": "shuffle!([rng=GLOBAL_RNG,] v)\n\nIn-place version of shuffle: randomly permute the array v in-place, optionally supplying the random-number generator rng.\n\nExample\n\njulia> rng = MersenneTwister(1234);\n\njulia> shuffle!(rng, collect(1:16))\n16-element Array{Int64,1}:\n 2\n 15\n 5\n 14\n 1\n 9\n 10\n 6\n 11\n 3\n 16\n 7\n 4\n 12\n 8\n 13\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Base.reverse", - "page": "Arrays", - "title": "Base.reverse", - "category": "function", - "text": "reverse(v [, start=1 [, stop=length(v) ]] )\n\nReturn a copy of v reversed from start to stop.\n\nExamples\n\njulia> A = collect(1:5)\n5-element Array{Int64,1}:\n 1\n 2\n 3\n 4\n 5\n\njulia> reverse(A)\n5-element Array{Int64,1}:\n 5\n 4\n 3\n 2\n 1\n\njulia> reverse(A, 1, 4)\n5-element Array{Int64,1}:\n 4\n 3\n 2\n 1\n 5\n\njulia> reverse(A, 3, 5)\n5-element Array{Int64,1}:\n 1\n 2\n 5\n 4\n 3\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Base.reverseind", - "page": "Arrays", - "title": "Base.reverseind", - "category": "function", - "text": "reverseind(v, i)\n\nGiven an index i in reverse(v), return the corresponding index in v so that v[reverseind(v,i)] == reverse(v)[i]. (This can be nontrivial in the case where v is a Unicode string.)\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Base.reverse!", - "page": "Arrays", - "title": "Base.reverse!", - "category": "function", - "text": "reverse!(v [, start=1 [, stop=length(v) ]]) -> v\n\nIn-place version of reverse.\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Combinatorics-1", - "page": "Arrays", - "title": "Combinatorics", - "category": "section", - "text": "Base.Random.randperm\nBase.invperm\nBase.isperm\nBase.permute!(::Any, ::AbstractVector)\nBase.ipermute!\nBase.Random.randcycle\nBase.Random.shuffle\nBase.Random.shuffle!\nBase.reverse\nBase.reverseind\nBase.reverse!" -}, - -{ - "location": "stdlib/arrays.html#Base.flipbits!", - "page": "Arrays", - "title": "Base.flipbits!", - "category": "function", - "text": "flipbits!(B::BitArray{N}) -> BitArray{N}\n\nPerforms a bitwise not operation on B. See ~.\n\nExample\n\njulia> A = trues(2,2)\n2×2 BitArray{2}:\n true true\n true true\n\njulia> flipbits!(A)\n2×2 BitArray{2}:\n false false\n false false\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Base.rol!", - "page": "Arrays", - "title": "Base.rol!", - "category": "function", - "text": "rol!(dest::BitVector, src::BitVector, i::Integer) -> BitVector\n\nPerforms a left rotation operation on src and puts the result into dest. i controls how far to rotate the bits.\n\n\n\nrol!(B::BitVector, i::Integer) -> BitVector\n\nPerforms a left rotation operation in-place on B. i controls how far to rotate the bits.\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Base.rol", - "page": "Arrays", - "title": "Base.rol", - "category": "function", - "text": "rol(B::BitVector, i::Integer) -> BitVector\n\nPerforms a left rotation operation, returning a new BitVector. i controls how far to rotate the bits. See also rol!.\n\nExamples\n\njulia> A = BitArray([true, true, false, false, true])\n5-element BitArray{1}:\n true\n true\n false\n false\n true\n\njulia> rol(A,1)\n5-element BitArray{1}:\n true\n false\n false\n true\n true\n\njulia> rol(A,2)\n5-element BitArray{1}:\n false\n false\n true\n true\n true\n\njulia> rol(A,5)\n5-element BitArray{1}:\n true\n true\n false\n false\n true\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Base.ror!", - "page": "Arrays", - "title": "Base.ror!", - "category": "function", - "text": "ror!(dest::BitVector, src::BitVector, i::Integer) -> BitVector\n\nPerforms a right rotation operation on src and puts the result into dest. i controls how far to rotate the bits.\n\n\n\nror!(B::BitVector, i::Integer) -> BitVector\n\nPerforms a right rotation operation in-place on B. i controls how far to rotate the bits.\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Base.ror", - "page": "Arrays", - "title": "Base.ror", - "category": "function", - "text": "ror(B::BitVector, i::Integer) -> BitVector\n\nPerforms a right rotation operation on B, returning a new BitVector. i controls how far to rotate the bits. See also ror!.\n\nExamples\n\njulia> A = BitArray([true, true, false, false, true])\n5-element BitArray{1}:\n true\n true\n false\n false\n true\n\njulia> ror(A,1)\n5-element BitArray{1}:\n true\n true\n true\n false\n false\n\njulia> ror(A,2)\n5-element BitArray{1}:\n false\n true\n true\n true\n false\n\njulia> ror(A,5)\n5-element BitArray{1}:\n true\n true\n false\n false\n true\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#BitArrays-1", - "page": "Arrays", - "title": "BitArrays", - "category": "section", - "text": "BitArrays are space-efficient \"packed\" boolean arrays, which store one bit per boolean value. They can be used similarly to Array{Bool} arrays (which store one byte per boolean value), and can be converted to/from the latter via Array(bitarray) and BitArray(array), respectively.Base.flipbits!\nBase.rol!\nBase.rol\nBase.ror!\nBase.ror" -}, - -{ - "location": "stdlib/arrays.html#Base.SparseArrays.SparseVector", - "page": "Arrays", - "title": "Base.SparseArrays.SparseVector", - "category": "type", - "text": "SparseVector{Tv,Ti<:Integer} <: AbstractSparseVector{Tv,Ti}\n\nVector type for storing sparse vectors.\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Base.SparseArrays.SparseMatrixCSC", - "page": "Arrays", - "title": "Base.SparseArrays.SparseMatrixCSC", - "category": "type", - "text": "SparseMatrixCSC{Tv,Ti<:Integer} <: AbstractSparseMatrix{Tv,Ti}\n\nMatrix type for storing sparse matrices in the Compressed Sparse Column format.\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Base.SparseArrays.sparse", - "page": "Arrays", - "title": "Base.SparseArrays.sparse", - "category": "function", - "text": "sparse(A)\n\nConvert an AbstractMatrix A into a sparse matrix.\n\nExample\n\njulia> A = eye(3)\n3×3 Array{Float64,2}:\n 1.0 0.0 0.0\n 0.0 1.0 0.0\n 0.0 0.0 1.0\n\njulia> sparse(A)\n3×3 SparseMatrixCSC{Float64,Int64} with 3 stored entries:\n [1, 1] = 1.0\n [2, 2] = 1.0\n [3, 3] = 1.0\n\n\n\nsparse(I, J, V,[ m, n, combine])\n\nCreate a sparse matrix S of dimensions m x n such that S[I[k], J[k]] = V[k]. The combine function is used to combine duplicates. If m and n are not specified, they are set to maximum(I) and maximum(J) respectively. If the combine function is not supplied, combine defaults to + unless the elements of V are Booleans in which case combine defaults to |. All elements of I must satisfy 1 <= I[k] <= m, and all elements of J must satisfy 1 <= J[k] <= n. Numerical zeros in (I, J, V) are retained as structural nonzeros; to drop numerical zeros, use dropzeros!.\n\nFor additional documentation and an expert driver, see Base.SparseArrays.sparse!.\n\nExample\n\njulia> Is = [1; 2; 3];\n\njulia> Js = [1; 2; 3];\n\njulia> Vs = [1; 2; 3];\n\njulia> sparse(Is, Js, Vs)\n3×3 SparseMatrixCSC{Int64,Int64} with 3 stored entries:\n [1, 1] = 1\n [2, 2] = 2\n [3, 3] = 3\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Base.SparseArrays.sparsevec", - "page": "Arrays", - "title": "Base.SparseArrays.sparsevec", - "category": "function", - "text": "sparsevec(I, V, [m, combine])\n\nCreate a sparse vector S of length m such that S[I[k]] = V[k]. Duplicates are combined using the combine function, which defaults to + if no combine argument is provided, unless the elements of V are Booleans in which case combine defaults to |.\n\njulia> II = [1, 3, 3, 5]; V = [0.1, 0.2, 0.3, 0.2];\n\njulia> sparsevec(II, V)\n5-element SparseVector{Float64,Int64} with 3 stored entries:\n [1] = 0.1\n [3] = 0.5\n [5] = 0.2\n\njulia> sparsevec(II, V, 8, -)\n8-element SparseVector{Float64,Int64} with 3 stored entries:\n [1] = 0.1\n [3] = -0.1\n [5] = 0.2\n\njulia> sparsevec([1, 3, 1, 2, 2], [true, true, false, false, false])\n3-element SparseVector{Bool,Int64} with 3 stored entries:\n [1] = true\n [2] = false\n [3] = true\n\n\n\nsparsevec(d::Dict, [m])\n\nCreate a sparse vector of length m where the nonzero indices are keys from the dictionary, and the nonzero values are the values from the dictionary.\n\njulia> sparsevec(Dict(1 => 3, 2 => 2))\n2-element SparseVector{Int64,Int64} with 2 stored entries:\n [1] = 3\n [2] = 2\n\n\n\nsparsevec(A)\n\nConvert a vector A into a sparse vector of length m.\n\nExample\n\njulia> sparsevec([1.0, 2.0, 0.0, 0.0, 3.0, 0.0])\n6-element SparseVector{Float64,Int64} with 3 stored entries:\n [1] = 1.0\n [2] = 2.0\n [5] = 3.0\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Base.SparseArrays.issparse", - "page": "Arrays", - "title": "Base.SparseArrays.issparse", - "category": "function", - "text": "issparse(S)\n\nReturns true if S is sparse, and false otherwise.\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Base.full", - "page": "Arrays", - "title": "Base.full", - "category": "function", - "text": "full(S)\n\nConvert a sparse matrix or vector S into a dense matrix or vector.\n\nExample\n\njulia> A = speye(3)\n3×3 SparseMatrixCSC{Float64,Int64} with 3 stored entries:\n [1, 1] = 1.0\n [2, 2] = 1.0\n [3, 3] = 1.0\n\njulia> full(A)\n3×3 Array{Float64,2}:\n 1.0 0.0 0.0\n 0.0 1.0 0.0\n 0.0 0.0 1.0\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Base.SparseArrays.nnz", - "page": "Arrays", - "title": "Base.SparseArrays.nnz", - "category": "function", - "text": "nnz(A)\n\nReturns the number of stored (filled) elements in a sparse array.\n\nExample\n\njulia> A = speye(3)\n3×3 SparseMatrixCSC{Float64,Int64} with 3 stored entries:\n [1, 1] = 1.0\n [2, 2] = 1.0\n [3, 3] = 1.0\n\njulia> nnz(A)\n3\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Base.SparseArrays.spzeros", - "page": "Arrays", - "title": "Base.SparseArrays.spzeros", - "category": "function", - "text": "spzeros([type,]m[,n])\n\nCreate a sparse vector of length m or sparse matrix of size m x n. This sparse array will not contain any nonzero values. No storage will be allocated for nonzero values during construction. The type defaults to Float64 if not specified.\n\nExamples\n\njulia> spzeros(3, 3)\n3×3 SparseMatrixCSC{Float64,Int64} with 0 stored entries\n\njulia> spzeros(Float32, 4)\n4-element SparseVector{Float32,Int64} with 0 stored entries\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Base.SparseArrays.spones", - "page": "Arrays", - "title": "Base.SparseArrays.spones", - "category": "function", - "text": "spones(S)\n\nCreate a sparse array with the same structure as that of S, but with every nonzero element having the value 1.0.\n\nExample\n\njulia> A = sparse([1,2,3,4],[2,4,3,1],[5.,4.,3.,2.])\n4×4 SparseMatrixCSC{Float64,Int64} with 4 stored entries:\n [4, 1] = 2.0\n [1, 2] = 5.0\n [3, 3] = 3.0\n [2, 4] = 4.0\n\njulia> spones(A)\n4×4 SparseMatrixCSC{Float64,Int64} with 4 stored entries:\n [4, 1] = 1.0\n [1, 2] = 1.0\n [3, 3] = 1.0\n [2, 4] = 1.0\n\nNote the difference from speye.\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Base.SparseArrays.speye-Tuple{Type,Integer,Integer}", - "page": "Arrays", - "title": "Base.SparseArrays.speye", - "category": "method", - "text": "speye([type,]m[,n])\n\nCreate a sparse identity matrix of size m x m. When n is supplied, create a sparse identity matrix of size m x n. The type defaults to Float64 if not specified.\n\nsparse(I, m, n) is equivalent to speye(Int, m, n), and sparse(α*I, m, n) can be used to efficiently create a sparse multiple α of the identity matrix.\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Base.SparseArrays.speye-Tuple{SparseMatrixCSC}", - "page": "Arrays", - "title": "Base.SparseArrays.speye", - "category": "method", - "text": "speye(S)\n\nCreate a sparse identity matrix with the same size as S.\n\nExample\n\njulia> A = sparse([1,2,3,4],[2,4,3,1],[5.,4.,3.,2.])\n4×4 SparseMatrixCSC{Float64,Int64} with 4 stored entries:\n [4, 1] = 2.0\n [1, 2] = 5.0\n [3, 3] = 3.0\n [2, 4] = 4.0\n\njulia> speye(A)\n4×4 SparseMatrixCSC{Float64,Int64} with 4 stored entries:\n [1, 1] = 1.0\n [2, 2] = 1.0\n [3, 3] = 1.0\n [4, 4] = 1.0\n\nNote the difference from spones.\n\n\n\nspeye([type,]m[,n])\n\nCreate a sparse identity matrix of size m x m. When n is supplied, create a sparse identity matrix of size m x n. The type defaults to Float64 if not specified.\n\nsparse(I, m, n) is equivalent to speye(Int, m, n), and sparse(α*I, m, n) can be used to efficiently create a sparse multiple α of the identity matrix.\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Base.SparseArrays.spdiagm", - "page": "Arrays", - "title": "Base.SparseArrays.spdiagm", - "category": "function", - "text": "spdiagm(B, d[, m, n])\n\nConstruct a sparse diagonal matrix. B is a tuple of vectors containing the diagonals and d is a tuple containing the positions of the diagonals. In the case the input contains only one diagonal, B can be a vector (instead of a tuple) and d can be the diagonal position (instead of a tuple), defaulting to 0 (diagonal). Optionally, m and n specify the size of the resulting sparse matrix.\n\nExample\n\njulia> spdiagm(([1,2,3,4],[4,3,2,1]),(-1,1))\n5×5 SparseMatrixCSC{Int64,Int64} with 8 stored entries:\n [2, 1] = 1\n [1, 2] = 4\n [3, 2] = 2\n [2, 3] = 3\n [4, 3] = 3\n [3, 4] = 2\n [5, 4] = 4\n [4, 5] = 1\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Base.SparseArrays.sprand", - "page": "Arrays", - "title": "Base.SparseArrays.sprand", - "category": "function", - "text": "sprand([rng],[type],m,[n],p::AbstractFloat,[rfn])\n\nCreate a random length m sparse vector or m by n sparse matrix, in which the probability of any element being nonzero is independently given by p (and hence the mean density of nonzeros is also exactly p). Nonzero values are sampled from the distribution specified by rfn and have the type type. The uniform distribution is used in case rfn is not specified. The optional rng argument specifies a random number generator, see Random Numbers.\n\nExample\n\njulia> rng = MersenneTwister(1234);\n\njulia> sprand(rng, Bool, 2, 2, 0.5)\n2×2 SparseMatrixCSC{Bool,Int64} with 2 stored entries:\n [1, 1] = true\n [2, 1] = true\n\njulia> sprand(rng, Float64, 3, 0.75)\n3-element SparseVector{Float64,Int64} with 1 stored entry:\n [3] = 0.298614\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Base.SparseArrays.sprandn", - "page": "Arrays", - "title": "Base.SparseArrays.sprandn", - "category": "function", - "text": "sprandn([rng], m[,n],p::AbstractFloat)\n\nCreate a random sparse vector of length m or sparse matrix of size m by n with the specified (independent) probability p of any entry being nonzero, where nonzero values are sampled from the normal distribution. The optional rng argument specifies a random number generator, see Random Numbers.\n\nExample\n\njulia> rng = MersenneTwister(1234);\n\njulia> sprandn(rng, 2, 2, 0.75)\n2×2 SparseMatrixCSC{Float64,Int64} with 3 stored entries:\n [1, 1] = 0.532813\n [2, 1] = -0.271735\n [2, 2] = 0.502334\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Base.SparseArrays.nonzeros", - "page": "Arrays", - "title": "Base.SparseArrays.nonzeros", - "category": "function", - "text": "nonzeros(A)\n\nReturn a vector of the structural nonzero values in sparse array A. This includes zeros that are explicitly stored in the sparse array. The returned vector points directly to the internal nonzero storage of A, and any modifications to the returned vector will mutate A as well. See rowvals and nzrange.\n\nExample\n\njulia> A = speye(3)\n3×3 SparseMatrixCSC{Float64,Int64} with 3 stored entries:\n [1, 1] = 1.0\n [2, 2] = 1.0\n [3, 3] = 1.0\n\njulia> nonzeros(A)\n3-element Array{Float64,1}:\n 1.0\n 1.0\n 1.0\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Base.SparseArrays.rowvals", - "page": "Arrays", - "title": "Base.SparseArrays.rowvals", - "category": "function", - "text": "rowvals(A::SparseMatrixCSC)\n\nReturn a vector of the row indices of A. Any modifications to the returned vector will mutate A as well. Providing access to how the row indices are stored internally can be useful in conjunction with iterating over structural nonzero values. See also nonzeros and nzrange.\n\nExample\n\njulia> A = speye(3)\n3×3 SparseMatrixCSC{Float64,Int64} with 3 stored entries:\n [1, 1] = 1.0\n [2, 2] = 1.0\n [3, 3] = 1.0\n\njulia> rowvals(A)\n3-element Array{Int64,1}:\n 1\n 2\n 3\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Base.SparseArrays.nzrange", - "page": "Arrays", - "title": "Base.SparseArrays.nzrange", - "category": "function", - "text": "nzrange(A::SparseMatrixCSC, col::Integer)\n\nReturn the range of indices to the structural nonzero values of a sparse matrix column. In conjunction with nonzeros and rowvals, this allows for convenient iterating over a sparse matrix :\n\nA = sparse(I,J,V)\nrows = rowvals(A)\nvals = nonzeros(A)\nm, n = size(A)\nfor i = 1:n\n for j in nzrange(A, i)\n row = rows[j]\n val = vals[j]\n # perform sparse wizardry...\n end\nend\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Base.SparseArrays.dropzeros!-Tuple{SparseMatrixCSC,Bool}", - "page": "Arrays", - "title": "Base.SparseArrays.dropzeros!", - "category": "method", - "text": "dropzeros!(A::SparseMatrixCSC, trim::Bool = true)\n\nRemoves stored numerical zeros from A, optionally trimming resulting excess space from A.rowval and A.nzval when trim is true.\n\nFor an out-of-place version, see dropzeros. For algorithmic information, see fkeep!.\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Base.SparseArrays.dropzeros-Tuple{SparseMatrixCSC,Bool}", - "page": "Arrays", - "title": "Base.SparseArrays.dropzeros", - "category": "method", - "text": "dropzeros(A::SparseMatrixCSC, trim::Bool = true)\n\nGenerates a copy of A and removes stored numerical zeros from that copy, optionally trimming excess space from the result\'s rowval and nzval arrays when trim is true.\n\nFor an in-place version and algorithmic information, see dropzeros!.\n\nExample\n\njulia> A = sparse([1, 2, 3], [1, 2, 3], [1.0, 0.0, 1.0])\n3×3 SparseMatrixCSC{Float64,Int64} with 3 stored entries:\n [1, 1] = 1.0\n [2, 2] = 0.0\n [3, 3] = 1.0\n\njulia> dropzeros(A)\n3×3 SparseMatrixCSC{Float64,Int64} with 2 stored entries:\n [1, 1] = 1.0\n [3, 3] = 1.0\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Base.SparseArrays.dropzeros!-Tuple{SparseVector,Bool}", - "page": "Arrays", - "title": "Base.SparseArrays.dropzeros!", - "category": "method", - "text": "dropzeros!(x::SparseVector, trim::Bool = true)\n\nRemoves stored numerical zeros from x, optionally trimming resulting excess space from x.nzind and x.nzval when trim is true.\n\nFor an out-of-place version, see dropzeros. For algorithmic information, see fkeep!.\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Base.SparseArrays.dropzeros-Tuple{SparseVector,Bool}", - "page": "Arrays", - "title": "Base.SparseArrays.dropzeros", - "category": "method", - "text": "dropzeros(x::SparseVector, trim::Bool = true)\n\nGenerates a copy of x and removes numerical zeros from that copy, optionally trimming excess space from the result\'s nzind and nzval arrays when trim is true.\n\nFor an in-place version and algorithmic information, see dropzeros!.\n\nExample\n\njulia> A = sparsevec([1, 2, 3], [1.0, 0.0, 1.0])\n3-element SparseVector{Float64,Int64} with 3 stored entries:\n [1] = 1.0\n [2] = 0.0\n [3] = 1.0\n\njulia> dropzeros(A)\n3-element SparseVector{Float64,Int64} with 2 stored entries:\n [1] = 1.0\n [3] = 1.0\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Base.SparseArrays.permute", - "page": "Arrays", - "title": "Base.SparseArrays.permute", - "category": "function", - "text": "permute{Tv,Ti}(A::SparseMatrixCSC{Tv,Ti}, p::AbstractVector{<:Integer},\n q::AbstractVector{<:Integer})\n\nBilaterally permute A, returning PAQ (A[p,q]). Column-permutation q\'s length must match A\'s column count (length(q) == A.n). Row-permutation p\'s length must match A\'s row count (length(p) == A.m).\n\nFor expert drivers and additional information, see permute!.\n\nExample\n\njulia> A = spdiagm([1, 2, 3, 4], 0, 4, 4) + spdiagm([5, 6, 7], 1, 4, 4)\n4×4 SparseMatrixCSC{Int64,Int64} with 7 stored entries:\n [1, 1] = 1\n [1, 2] = 5\n [2, 2] = 2\n [2, 3] = 6\n [3, 3] = 3\n [3, 4] = 7\n [4, 4] = 4\n\njulia> permute(A, [4, 3, 2, 1], [1, 2, 3, 4])\n4×4 SparseMatrixCSC{Int64,Int64} with 7 stored entries:\n [4, 1] = 1\n [3, 2] = 2\n [4, 2] = 5\n [2, 3] = 3\n [3, 3] = 6\n [1, 4] = 4\n [2, 4] = 7\n\njulia> permute(A, [1, 2, 3, 4], [4, 3, 2, 1])\n4×4 SparseMatrixCSC{Int64,Int64} with 7 stored entries:\n [3, 1] = 7\n [4, 1] = 4\n [2, 2] = 6\n [3, 2] = 3\n [1, 3] = 5\n [2, 3] = 2\n [1, 4] = 1\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#Base.permute!-Union{Tuple{SparseMatrixCSC{Tv,Ti},SparseMatrixCSC{Tv,Ti},AbstractArray{Tp,1},AbstractArray{Tq,1}}, Tuple{Ti}, Tuple{Tp}, Tuple{Tq}, Tuple{Tv}} where Tq<:Integer where Tp<:Integer where Ti where Tv", - "page": "Arrays", - "title": "Base.permute!", - "category": "method", - "text": "permute!{Tv,Ti}(X::SparseMatrixCSC{Tv,Ti}, A::SparseMatrixCSC{Tv,Ti},\n p::AbstractVector{<:Integer}, q::AbstractVector{<:Integer}[, C::SparseMatrixCSC{Tv,Ti}])\n\nBilaterally permute A, storing result PAQ (A[p,q]) in X. Stores intermediate result (AQ)^T (transpose(A[:,q])) in optional argument C if present. Requires that none of X, A, and, if present, C alias each other; to store result PAQ back into A, use the following method lacking X:\n\npermute!{Tv,Ti}(A::SparseMatrixCSC{Tv,Ti}, p::AbstractVector{<:Integer},\n q::AbstractVector{<:Integer}[, C::SparseMatrixCSC{Tv,Ti}[, workcolptr::Vector{Ti}]])\n\nX\'s dimensions must match those of A (X.m == A.m and X.n == A.n), and X must have enough storage to accommodate all allocated entries in A (length(X.rowval) >= nnz(A) and length(X.nzval) >= nnz(A)). Column-permutation q\'s length must match A\'s column count (length(q) == A.n). Row-permutation p\'s length must match A\'s row count (length(p) == A.m).\n\nC\'s dimensions must match those of transpose(A) (C.m == A.n and C.n == A.m), and C must have enough storage to accommodate all allocated entries in A (length(C.rowval) >= nnz(A) and length(C.nzval) >= nnz(A)).\n\nFor additional (algorithmic) information, and for versions of these methods that forgo argument checking, see (unexported) parent methods unchecked_noalias_permute! and unchecked_aliasing_permute!.\n\nSee also: permute.\n\n\n\n" -}, - -{ - "location": "stdlib/arrays.html#stdlib-sparse-arrays-1", - "page": "Arrays", - "title": "Sparse Vectors and Matrices", - "category": "section", - "text": "Sparse vectors and matrices largely support the same set of operations as their dense counterparts. The following functions are specific to sparse arrays.Base.SparseArrays.SparseVector\nBase.SparseArrays.SparseMatrixCSC\nBase.SparseArrays.sparse\nBase.SparseArrays.sparsevec\nBase.SparseArrays.issparse\nBase.full\nBase.SparseArrays.nnz\nBase.SparseArrays.spzeros\nBase.SparseArrays.spones\nBase.SparseArrays.speye(::Type, ::Integer, ::Integer)\nBase.SparseArrays.speye(::SparseMatrixCSC)\nBase.SparseArrays.spdiagm\nBase.SparseArrays.sprand\nBase.SparseArrays.sprandn\nBase.SparseArrays.nonzeros\nBase.SparseArrays.rowvals\nBase.SparseArrays.nzrange\nBase.SparseArrays.dropzeros!(::SparseMatrixCSC, ::Bool)\nBase.SparseArrays.dropzeros(::SparseMatrixCSC, ::Bool)\nBase.SparseArrays.dropzeros!(::SparseVector, ::Bool)\nBase.SparseArrays.dropzeros(::SparseVector, ::Bool)\nBase.SparseArrays.permute\nBase.permute!{Tv, Ti, Tp <: Integer, Tq <: Integer}(::SparseMatrixCSC{Tv,Ti}, ::SparseMatrixCSC{Tv,Ti}, ::AbstractArray{Tp,1}, ::AbstractArray{Tq,1})" -}, - -{ - "location": "stdlib/parallel.html#", - "page": "Tasks and Parallel Computing", - "title": "Tasks and Parallel Computing", - "category": "page", - "text": "" -}, - -{ - "location": "stdlib/parallel.html#Tasks-and-Parallel-Computing-1", - "page": "Tasks and Parallel Computing", - "title": "Tasks and Parallel Computing", - "category": "section", - "text": "" -}, - -{ - "location": "stdlib/parallel.html#Core.Task", - "page": "Tasks and Parallel Computing", - "title": "Core.Task", - "category": "type", - "text": "Task(func)\n\nCreate a Task (i.e. coroutine) to execute the given function (which must be callable with no arguments). The task exits when this function returns.\n\nExample\n\njulia> a() = det(rand(1000, 1000));\n\njulia> b = Task(a);\n\nIn this example, b is a runnable Task that hasn\'t started yet.\n\n\n\n" -}, - -{ - "location": "stdlib/parallel.html#Base.current_task", - "page": "Tasks and Parallel Computing", - "title": "Base.current_task", - "category": "function", - "text": "current_task()\n\nGet the currently running Task.\n\n\n\n" -}, - -{ - "location": "stdlib/parallel.html#Base.istaskdone", - "page": "Tasks and Parallel Computing", - "title": "Base.istaskdone", - "category": "function", - "text": "istaskdone(t::Task) -> Bool\n\nDetermine whether a task has exited.\n\njulia> a2() = det(rand(1000, 1000));\n\njulia> b = Task(a2);\n\njulia> istaskdone(b)\nfalse\n\njulia> schedule(b);\n\njulia> yield();\n\njulia> istaskdone(b)\ntrue\n\n\n\n" -}, - -{ - "location": "stdlib/parallel.html#Base.istaskstarted", - "page": "Tasks and Parallel Computing", - "title": "Base.istaskstarted", - "category": "function", - "text": "istaskstarted(t::Task) -> Bool\n\nDetermine whether a task has started executing.\n\njulia> a3() = det(rand(1000, 1000));\n\njulia> b = Task(a3);\n\njulia> istaskstarted(b)\nfalse\n\n\n\n" -}, - -{ - "location": "stdlib/parallel.html#Base.yield", - "page": "Tasks and Parallel Computing", - "title": "Base.yield", - "category": "function", - "text": "yield()\n\nSwitch to the scheduler to allow another scheduled task to run. A task that calls this function is still runnable, and will be restarted immediately if there are no other runnable tasks.\n\n\n\nyield(t::Task, arg = nothing)\n\nA fast, unfair-scheduling version of schedule(t, arg); yield() which immediately yields to t before calling the scheduler.\n\n\n\n" -}, - -{ - "location": "stdlib/parallel.html#Base.yieldto", - "page": "Tasks and Parallel Computing", - "title": "Base.yieldto", - "category": "function", - "text": "yieldto(t::Task, arg = nothing)\n\nSwitch to the given task. The first time a task is switched to, the task\'s function is called with no arguments. On subsequent switches, arg is returned from the task\'s last call to yieldto. This is a low-level call that only switches tasks, not considering states or scheduling in any way. Its use is discouraged.\n\n\n\n" -}, - -{ - "location": "stdlib/parallel.html#Base.task_local_storage-Tuple{Any}", - "page": "Tasks and Parallel Computing", - "title": "Base.task_local_storage", - "category": "method", - "text": "task_local_storage(key)\n\nLook up the value of a key in the current task\'s task-local storage.\n\n\n\n" -}, - -{ - "location": "stdlib/parallel.html#Base.task_local_storage-Tuple{Any,Any}", - "page": "Tasks and Parallel Computing", - "title": "Base.task_local_storage", - "category": "method", - "text": "task_local_storage(key, value)\n\nAssign a value to a key in the current task\'s task-local storage.\n\n\n\n" -}, - -{ - "location": "stdlib/parallel.html#Base.task_local_storage-Tuple{Function,Any,Any}", - "page": "Tasks and Parallel Computing", - "title": "Base.task_local_storage", - "category": "method", - "text": "task_local_storage(body, key, value)\n\nCall the function body with a modified task-local storage, in which value is assigned to key; the previous value of key, or lack thereof, is restored afterwards. Useful for emulating dynamic scoping.\n\n\n\n" -}, - -{ - "location": "stdlib/parallel.html#Base.Condition", - "page": "Tasks and Parallel Computing", - "title": "Base.Condition", - "category": "type", - "text": "Condition()\n\nCreate an edge-triggered event source that tasks can wait for. Tasks that call wait on a Condition are suspended and queued. Tasks are woken up when notify is later called on the Condition. Edge triggering means that only tasks waiting at the time notify is called can be woken up. For level-triggered notifications, you must keep extra state to keep track of whether a notification has happened. The Channel type does this, and so can be used for level-triggered events.\n\n\n\n" -}, - -{ - "location": "stdlib/parallel.html#Base.notify", - "page": "Tasks and Parallel Computing", - "title": "Base.notify", - "category": "function", - "text": "notify(condition, val=nothing; all=true, error=false)\n\nWake up tasks waiting for a condition, passing them val. If all is true (the default), all waiting tasks are woken, otherwise only one is. If error is true, the passed value is raised as an exception in the woken tasks.\n\nReturns the count of tasks woken up. Returns 0 if no tasks are waiting on condition.\n\n\n\n" -}, - -{ - "location": "stdlib/parallel.html#Base.schedule", - "page": "Tasks and Parallel Computing", - "title": "Base.schedule", - "category": "function", - "text": "schedule(t::Task, [val]; error=false)\n\nAdd a Task to the scheduler\'s queue. This causes the task to run constantly when the system is otherwise idle, unless the task performs a blocking operation such as wait.\n\nIf a second argument val is provided, it will be passed to the task (via the return value of yieldto) when it runs again. If error is true, the value is raised as an exception in the woken task.\n\njulia> a5() = det(rand(1000, 1000));\n\njulia> b = Task(a5);\n\njulia> istaskstarted(b)\nfalse\n\njulia> schedule(b);\n\njulia> yield();\n\njulia> istaskstarted(b)\ntrue\n\njulia> istaskdone(b)\ntrue\n\n\n\n" -}, - -{ - "location": "stdlib/parallel.html#Base.@schedule", - "page": "Tasks and Parallel Computing", - "title": "Base.@schedule", - "category": "macro", - "text": "@schedule\n\nWrap an expression in a Task and add it to the local machine\'s scheduler queue. Similar to @async except that an enclosing @sync does NOT wait for tasks started with an @schedule.\n\n\n\n" -}, - -{ - "location": "stdlib/parallel.html#Base.@task", - "page": "Tasks and Parallel Computing", - "title": "Base.@task", - "category": "macro", - "text": "@task\n\nWrap an expression in a Task without executing it, and return the Task. This only creates a task, and does not run it.\n\njulia> a1() = det(rand(1000, 1000));\n\njulia> b = @task a1();\n\njulia> istaskstarted(b)\nfalse\n\njulia> schedule(b);\n\njulia> yield();\n\njulia> istaskdone(b)\ntrue\n\n\n\n" -}, - -{ - "location": "stdlib/parallel.html#Base.sleep", - "page": "Tasks and Parallel Computing", - "title": "Base.sleep", - "category": "function", - "text": "sleep(seconds)\n\nBlock the current task for a specified number of seconds. The minimum sleep time is 1 millisecond or input of 0.001.\n\n\n\n" -}, - -{ - "location": "stdlib/parallel.html#Base.Channel", - "page": "Tasks and Parallel Computing", - "title": "Base.Channel", - "category": "type", - "text": "Channel{T}(sz::Int)\n\nConstructs a Channel with an internal buffer that can hold a maximum of sz objects of type T. put! calls on a full channel block until an object is removed with take!.\n\nChannel(0) constructs an unbuffered channel. put! blocks until a matching take! is called. And vice-versa.\n\nOther constructors:\n\nChannel(Inf): equivalent to Channel{Any}(typemax(Int))\nChannel(sz): equivalent to Channel{Any}(sz)\n\n\n\n" -}, - -{ - "location": "stdlib/parallel.html#Base.put!-Tuple{Channel,Any}", - "page": "Tasks and Parallel Computing", - "title": "Base.put!", - "category": "method", - "text": "put!(c::Channel, v)\n\nAppends an item v to the channel c. Blocks if the channel is full.\n\nFor unbuffered channels, blocks until a take! is performed by a different task.\n\n\n\n" -}, - -{ - "location": "stdlib/parallel.html#Base.take!-Tuple{Channel}", - "page": "Tasks and Parallel Computing", - "title": "Base.take!", - "category": "method", - "text": "take!(c::Channel)\n\nRemoves and returns a value from a Channel. Blocks until data is available.\n\nFor unbuffered channels, blocks until a put! is performed by a different task.\n\n\n\n" -}, - -{ - "location": "stdlib/parallel.html#Base.isready-Tuple{Channel}", - "page": "Tasks and Parallel Computing", - "title": "Base.isready", - "category": "method", - "text": "isready(c::Channel)\n\nDetermine whether a Channel has a value stored to it. Returns immediately, does not block.\n\nFor unbuffered channels returns true if there are tasks waiting on a put!.\n\n\n\n" -}, - -{ - "location": "stdlib/parallel.html#Base.fetch-Tuple{Channel}", - "page": "Tasks and Parallel Computing", - "title": "Base.fetch", - "category": "method", - "text": "fetch(c::Channel)\n\nWaits for and gets the first available item from the channel. Does not remove the item. fetch is unsupported on an unbuffered (0-size) channel.\n\n\n\n" -}, - -{ - "location": "stdlib/parallel.html#Base.close-Tuple{Channel}", - "page": "Tasks and Parallel Computing", - "title": "Base.close", - "category": "method", - "text": "close(c::Channel)\n\nCloses a channel. An exception is thrown by:\n\nput! on a closed channel.\ntake! and fetch on an empty, closed channel.\n\n\n\n" -}, - -{ - "location": "stdlib/parallel.html#Base.bind-Tuple{Channel,Task}", - "page": "Tasks and Parallel Computing", - "title": "Base.bind", - "category": "method", - "text": "bind(chnl::Channel, task::Task)\n\nAssociates the lifetime of chnl with a task. Channel chnl is automatically closed when the task terminates. Any uncaught exception in the task is propagated to all waiters on chnl.\n\nThe chnl object can be explicitly closed independent of task termination. Terminating tasks have no effect on already closed Channel objects.\n\nWhen a channel is bound to multiple tasks, the first task to terminate will close the channel. When multiple channels are bound to the same task, termination of the task will close all of the bound channels.\n\njulia> c = Channel(0);\n\njulia> task = @schedule foreach(i->put!(c, i), 1:4);\n\njulia> bind(c,task);\n\njulia> for i in c\n @show i\n end;\ni = 1\ni = 2\ni = 3\ni = 4\n\njulia> isopen(c)\nfalse\n\njulia> c = Channel(0);\n\njulia> task = @schedule (put!(c,1);error(\"foo\"));\n\njulia> bind(c,task);\n\njulia> take!(c)\n1\n\njulia> put!(c,1);\nERROR: foo\nStacktrace:\n [1] check_channel_state(::Channel{Any}) at ./channels.jl:131\n [2] put!(::Channel{Any}, ::Int64) at ./channels.jl:261\n\n\n\n" -}, - -{ - "location": "stdlib/parallel.html#Base.asyncmap", - "page": "Tasks and Parallel Computing", - "title": "Base.asyncmap", - "category": "function", - "text": "asyncmap(f, c...; ntasks=0, batch_size=nothing)\n\nUses multiple concurrent tasks to map f over a collection (or multiple equal length collections). For multiple collection arguments, f is applied elementwise.\n\nntasks specifies the number of tasks to run concurrently. Depending on the length of the collections, if ntasks is unspecified, up to 100 tasks will be used for concurrent mapping.\n\nntasks can also be specified as a zero-arg function. In this case, the number of tasks to run in parallel is checked before processing every element and a new task started if the value of ntasks_func() is less than the current number of tasks.\n\nIf batch_size is specified, the collection is processed in batch mode. f must then be a function that must accept a Vector of argument tuples and must return a vector of results. The input vector will have a length of batch_size or less.\n\nThe following examples highlight execution in different tasks by returning the object_id of the tasks in which the mapping function is executed.\n\nFirst, with ntasks undefined, each element is processed in a different task.\n\njulia> tskoid() = object_id(current_task());\n\njulia> asyncmap(x->tskoid(), 1:5)\n5-element Array{UInt64,1}:\n 0x6e15e66c75c75853\n 0x440f8819a1baa682\n 0x9fb3eeadd0c83985\n 0xebd3e35fe90d4050\n 0x29efc93edce2b961\n\njulia> length(unique(asyncmap(x->tskoid(), 1:5)))\n5\n\nWith ntasks=2 all elements are processed in 2 tasks.\n\njulia> asyncmap(x->tskoid(), 1:5; ntasks=2)\n5-element Array{UInt64,1}:\n 0x027ab1680df7ae94\n 0xa23d2f80cd7cf157\n 0x027ab1680df7ae94\n 0xa23d2f80cd7cf157\n 0x027ab1680df7ae94\n\njulia> length(unique(asyncmap(x->tskoid(), 1:5; ntasks=2)))\n2\n\nWith batch_size defined, the mapping function needs to be changed to accept an array of argument tuples and return an array of results. map is used in the modified mapping function to achieve this.\n\njulia> batch_func(input) = map(x->string(\"args_tuple: \", x, \", element_val: \", x[1], \", task: \", tskoid()), input)\nbatch_func (generic function with 1 method)\n\njulia> asyncmap(batch_func, 1:5; ntasks=2, batch_size=2)\n5-element Array{String,1}:\n \"args_tuple: (1,), element_val: 1, task: 9118321258196414413\"\n \"args_tuple: (2,), element_val: 2, task: 4904288162898683522\"\n \"args_tuple: (3,), element_val: 3, task: 9118321258196414413\"\n \"args_tuple: (4,), element_val: 4, task: 4904288162898683522\"\n \"args_tuple: (5,), element_val: 5, task: 9118321258196414413\"\n\nnote: Note\nCurrently, all tasks in Julia are executed in a single OS thread co-operatively. Consequently, ayncmap is beneficial only when the mapping function involves any I/O - disk, network, remote worker invocation, etc.\n\n\n\n" -}, - -{ - "location": "stdlib/parallel.html#Base.asyncmap!", - "page": "Tasks and Parallel Computing", - "title": "Base.asyncmap!", - "category": "function", - "text": "asyncmap!(f, results, c...; ntasks=0, batch_size=nothing)\n\nLike asyncmap(), but stores output in results rather than returning a collection.\n\n\n\n" -}, - -{ - "location": "stdlib/parallel.html#Tasks-1", - "page": "Tasks and Parallel Computing", - "title": "Tasks", - "category": "section", - "text": "Core.Task\nBase.current_task\nBase.istaskdone\nBase.istaskstarted\nBase.yield\nBase.yieldto\nBase.task_local_storage(::Any)\nBase.task_local_storage(::Any, ::Any)\nBase.task_local_storage(::Function, ::Any, ::Any)\nBase.Condition\nBase.notify\nBase.schedule\nBase.@schedule\nBase.@task\nBase.sleep\nBase.Channel\nBase.put!(::Channel, ::Any)\nBase.take!(::Channel)\nBase.isready(::Channel)\nBase.fetch(::Channel)\nBase.close(::Channel)\nBase.bind(c::Channel, task::Task)\nBase.asyncmap\nBase.asyncmap!" -}, - -{ - "location": "stdlib/parallel.html#Base.Distributed.addprocs", - "page": "Tasks and Parallel Computing", - "title": "Base.Distributed.addprocs", - "category": "function", - "text": "addprocs(manager::ClusterManager; kwargs...) -> List of process identifiers\n\nLaunches worker processes via the specified cluster manager.\n\nFor example, Beowulf clusters are supported via a custom cluster manager implemented in the package ClusterManagers.jl.\n\nThe number of seconds a newly launched worker waits for connection establishment from the master can be specified via variable JULIA_WORKER_TIMEOUT in the worker process\'s environment. Relevant only when using TCP/IP as transport.\n\n\n\naddprocs(machines; tunnel=false, sshflags=``, max_parallel=10, kwargs...) -> List of process identifiers\n\nAdd processes on remote machines via SSH. Requires julia to be installed in the same location on each node, or to be available via a shared file system.\n\nmachines is a vector of machine specifications. Workers are started for each specification.\n\nA machine specification is either a string machine_spec or a tuple - (machine_spec, count).\n\nmachine_spec is a string of the form [user@]host[:port] [bind_addr[:port]]. user defaults to current user, port to the standard ssh port. If [bind_addr[:port]] is specified, other workers will connect to this worker at the specified bind_addr and port.\n\ncount is the number of workers to be launched on the specified host. If specified as :auto it will launch as many workers as the number of cores on the specific host.\n\nKeyword arguments:\n\ntunnel: if true then SSH tunneling will be used to connect to the worker from the master process. Default is false.\nsshflags: specifies additional ssh options, e.g. sshflags=`-i /home/foo/bar.pem`\nmax_parallel: specifies the maximum number of workers connected to in parallel at a host. Defaults to 10.\ndir: specifies the working directory on the workers. Defaults to the host\'s current directory (as found by pwd())\nenable_threaded_blas: if true then BLAS will run on multiple threads in added processes. Default is false.\nexename: name of the julia executable. Defaults to \"$JULIA_HOME/julia\" or \"$JULIA_HOME/julia-debug\" as the case may be.\nexeflags: additional flags passed to the worker processes.\ntopology: Specifies how the workers connect to each other. Sending a message between unconnected workers results in an error.\ntopology=:all_to_all: All processes are connected to each other. The default.\ntopology=:master_slave: Only the driver process, i.e. pid 1 connects to the workers. The workers do not connect to each other.\ntopology=:custom: The launch method of the cluster manager specifies the connection topology via fields ident and connect_idents in WorkerConfig. A worker with a cluster manager identity ident will connect to all workers specified in connect_idents.\n\nEnvironment variables :\n\nIf the master process fails to establish a connection with a newly launched worker within 60.0 seconds, the worker treats it as a fatal situation and terminates. This timeout can be controlled via environment variable JULIA_WORKER_TIMEOUT. The value of JULIA_WORKER_TIMEOUT on the master process specifies the number of seconds a newly launched worker waits for connection establishment.\n\n\n\naddprocs(; kwargs...) -> List of process identifiers\n\nEquivalent to addprocs(Sys.CPU_CORES; kwargs...)\n\nNote that workers do not run a .juliarc.jl startup script, nor do they synchronize their global state (such as global variables, new method definitions, and loaded modules) with any of the other running processes.\n\n\n\naddprocs(np::Integer; restrict=true, kwargs...) -> List of process identifiers\n\nLaunches workers using the in-built LocalManager which only launches workers on the local host. This can be used to take advantage of multiple cores. addprocs(4) will add 4 processes on the local machine. If restrict is true, binding is restricted to 127.0.0.1. Keyword args dir, exename, exeflags, topology, and enable_threaded_blas have the same effect as documented for addprocs(machines).\n\n\n\n" -}, - -{ - "location": "stdlib/parallel.html#Base.Distributed.nprocs", - "page": "Tasks and Parallel Computing", - "title": "Base.Distributed.nprocs", - "category": "function", - "text": "nprocs()\n\nGet the number of available processes.\n\n\n\n" -}, - -{ - "location": "stdlib/parallel.html#Base.Distributed.nworkers", - "page": "Tasks and Parallel Computing", - "title": "Base.Distributed.nworkers", - "category": "function", - "text": "nworkers()\n\nGet the number of available worker processes. This is one less than nprocs(). Equal to nprocs() if nprocs() == 1.\n\n\n\n" -}, - -{ - "location": "stdlib/parallel.html#Base.Distributed.procs-Tuple{}", - "page": "Tasks and Parallel Computing", - "title": "Base.Distributed.procs", - "category": "method", - "text": "procs()\n\nReturns a list of all process identifiers.\n\n\n\n" -}, - -{ - "location": "stdlib/parallel.html#Base.Distributed.procs-Tuple{Integer}", - "page": "Tasks and Parallel Computing", - "title": "Base.Distributed.procs", - "category": "method", - "text": "procs(pid::Integer)\n\nReturns a list of all process identifiers on the same physical node. Specifically all workers bound to the same ip-address as pid are returned.\n\n\n\n" -}, - -{ - "location": "stdlib/parallel.html#Base.Distributed.workers", - "page": "Tasks and Parallel Computing", - "title": "Base.Distributed.workers", - "category": "function", - "text": "workers()\n\nReturns a list of all worker process identifiers.\n\n\n\n" -}, - -{ - "location": "stdlib/parallel.html#Base.Distributed.rmprocs", - "page": "Tasks and Parallel Computing", - "title": "Base.Distributed.rmprocs", - "category": "function", - "text": "rmprocs(pids...; waitfor=typemax(Int))\n\nRemoves the specified workers. Note that only process 1 can add or remove workers.\n\nArgument waitfor specifies how long to wait for the workers to shut down: - If unspecified, rmprocs will wait until all requested pids are removed. - An ErrorException is raised if all workers cannot be terminated before the requested waitfor seconds. - With a waitfor value of 0, the call returns immediately with the workers scheduled for removal in a different task. The scheduled Task object is returned. The user should call wait on the task before invoking any other parallel calls.\n\n\n\n" -}, - -{ - "location": "stdlib/parallel.html#Base.Distributed.interrupt", - "page": "Tasks and Parallel Computing", - "title": "Base.Distributed.interrupt", - "category": "function", - "text": "interrupt(pids::Integer...)\n\nInterrupt the current executing task on the specified workers. This is equivalent to pressing Ctrl-C on the local machine. If no arguments are given, all workers are interrupted.\n\n\n\ninterrupt(pids::AbstractVector=workers())\n\nInterrupt the current executing task on the specified workers. This is equivalent to pressing Ctrl-C on the local machine. If no arguments are given, all workers are interrupted.\n\n\n\n" -}, - -{ - "location": "stdlib/parallel.html#Base.Distributed.myid", - "page": "Tasks and Parallel Computing", - "title": "Base.Distributed.myid", - "category": "function", - "text": "myid()\n\nGet the id of the current process.\n\n\n\n" -}, - -{ - "location": "stdlib/parallel.html#Base.Distributed.pmap", - "page": "Tasks and Parallel Computing", - "title": "Base.Distributed.pmap", - "category": "function", - "text": "pmap([::AbstractWorkerPool], f, c...; distributed=true, batch_size=1, on_error=nothing, retry_delays=[]), retry_check=nothing) -> collection\n\nTransform collection c by applying f to each element using available workers and tasks.\n\nFor multiple collection arguments, apply f elementwise.\n\nNote that f must be made available to all worker processes; see Code Availability and Loading Packages for details.\n\nIf a worker pool is not specified, all available workers, i.e., the default worker pool is used.\n\nBy default, pmap distributes the computation over all specified workers. To use only the local process and distribute over tasks, specify distributed=false. This is equivalent to using asyncmap. For example, pmap(f, c; distributed=false) is equivalent to asyncmap(f,c; ntasks=()->nworkers())\n\npmap can also use a mix of processes and tasks via the batch_size argument. For batch sizes greater than 1, the collection is processed in multiple batches, each of length batch_size or less. A batch is sent as a single request to a free worker, where a local asyncmap processes elements from the batch using multiple concurrent tasks.\n\nAny error stops pmap from processing the remainder of the collection. To override this behavior you can specify an error handling function via argument on_error which takes in a single argument, i.e., the exception. The function can stop the processing by rethrowing the error, or, to continue, return any value which is then returned inline with the results to the caller.\n\nConsider the following two examples. The first one returns the exception object inline, the second a 0 in place of any exception:\n\njulia> pmap(x->iseven(x) ? error(\"foo\") : x, 1:4; on_error=identity)\n4-element Array{Any,1}:\n 1\n ErrorException(\"foo\")\n 3\n ErrorException(\"foo\")\n\njulia> pmap(x->iseven(x) ? error(\"foo\") : x, 1:4; on_error=ex->0)\n4-element Array{Int64,1}:\n 1\n 0\n 3\n 0\n\nErrors can also be handled by retrying failed computations. Keyword arguments retry_delays and retry_check are passed through to retry as keyword arguments delays and check respectively. If batching is specified, and an entire batch fails, all items in the batch are retried.\n\nNote that if both on_error and retry_delays are specified, the on_error hook is called before retrying. If on_error does not throw (or rethrow) an exception, the element will not be retried.\n\nExample: On errors, retry f on an element a maximum of 3 times without any delay between retries.\n\npmap(f, c; retry_delays = zeros(3))\n\nExample: Retry f only if the exception is not of type InexactError, with exponentially increasing delays up to 3 times. Return a NaN in place for all InexactError occurrences.\n\npmap(f, c; on_error = e->(isa(e, InexactError) ? NaN : rethrow(e)), retry_delays = ExponentialBackOff(n = 3))\n\n\n\n" -}, - -{ - "location": "stdlib/parallel.html#Base.Distributed.RemoteException", - "page": "Tasks and Parallel Computing", - "title": "Base.Distributed.RemoteException", - "category": "type", - "text": "RemoteException(captured)\n\nExceptions on remote computations are captured and rethrown locally. A RemoteException wraps the pid of the worker and a captured exception. A CapturedException captures the remote exception and a serializable form of the call stack when the exception was raised.\n\n\n\n" -}, - -{ - "location": "stdlib/parallel.html#Base.Distributed.Future", - "page": "Tasks and Parallel Computing", - "title": "Base.Distributed.Future", - "category": "type", - "text": "Future(pid::Integer=myid())\n\nCreate a Future on process pid. The default pid is the current process.\n\n\n\n" -}, - -{ - "location": "stdlib/parallel.html#Base.Distributed.RemoteChannel-Tuple{Integer}", - "page": "Tasks and Parallel Computing", - "title": "Base.Distributed.RemoteChannel", - "category": "method", - "text": "RemoteChannel(pid::Integer=myid())\n\nMake a reference to a Channel{Any}(1) on process pid. The default pid is the current process.\n\n\n\n" -}, - -{ - "location": "stdlib/parallel.html#Base.Distributed.RemoteChannel-Tuple{Function,Integer}", - "page": "Tasks and Parallel Computing", - "title": "Base.Distributed.RemoteChannel", - "category": "method", - "text": "RemoteChannel(f::Function, pid::Integer=myid())\n\nCreate references to remote channels of a specific size and type. f() is a function that when executed on pid must return an implementation of an AbstractChannel.\n\nFor example, RemoteChannel(()->Channel{Int}(10), pid), will return a reference to a channel of type Int and size 10 on pid.\n\nThe default pid is the current process.\n\n\n\n" -}, - -{ - "location": "stdlib/parallel.html#Base.wait", - "page": "Tasks and Parallel Computing", - "title": "Base.wait", - "category": "function", - "text": "wait([x])\n\nBlock the current task until some event occurs, depending on the type of the argument:\n\nRemoteChannel : Wait for a value to become available on the specified remote channel.\nFuture : Wait for a value to become available for the specified future.\nChannel: Wait for a value to be appended to the channel.\nCondition: Wait for notify on a condition.\nProcess: Wait for a process or process chain to exit. The exitcode field of a process can be used to determine success or failure.\nTask: Wait for a Task to finish, returning its result value. If the task fails with an exception, the exception is propagated (re-thrown in the task that called wait).\nRawFD: Wait for changes on a file descriptor (see poll_fd for keyword arguments and return code)\n\nIf no argument is passed, the task blocks for an undefined period. A task can only be restarted by an explicit call to schedule or yieldto.\n\nOften wait is called within a while loop to ensure a waited-for condition is met before proceeding.\n\n\n\n" -}, - -{ - "location": "stdlib/parallel.html#Base.fetch-Tuple{Any}", - "page": "Tasks and Parallel Computing", - "title": "Base.fetch", - "category": "method", - "text": "fetch(x)\n\nWaits and fetches a value from x depending on the type of x:\n\nFuture: Wait for and get the value of a Future. The fetched value is cached locally. Further calls to fetch on the same reference return the cached value. If the remote value is an exception, throws a RemoteException which captures the remote exception and backtrace.\nRemoteChannel: Wait for and get the value of a remote reference. Exceptions raised are same as for a Future .\n\nDoes not remove the item fetched.\n\n\n\n" -}, - -{ - "location": "stdlib/parallel.html#Base.Distributed.remotecall-Tuple{Any,Integer,Vararg{Any,N} where N}", - "page": "Tasks and Parallel Computing", - "title": "Base.Distributed.remotecall", - "category": "method", - "text": "remotecall(f, id::Integer, args...; kwargs...) -> Future\n\nCall a function f asynchronously on the given arguments on the specified process. Returns a Future. Keyword arguments, if any, are passed through to f.\n\n\n\n" -}, - -{ - "location": "stdlib/parallel.html#Base.Distributed.remotecall_wait-Tuple{Any,Integer,Vararg{Any,N} where N}", - "page": "Tasks and Parallel Computing", - "title": "Base.Distributed.remotecall_wait", - "category": "method", - "text": "remotecall_wait(f, id::Integer, args...; kwargs...)\n\nPerform a faster wait(remotecall(...)) in one message on the Worker specified by worker id id. Keyword arguments, if any, are passed through to f.\n\nSee also wait and remotecall.\n\n\n\n" -}, - -{ - "location": "stdlib/parallel.html#Base.Distributed.remotecall_fetch-Tuple{Any,Integer,Vararg{Any,N} where N}", - "page": "Tasks and Parallel Computing", - "title": "Base.Distributed.remotecall_fetch", - "category": "method", - "text": "remotecall_fetch(f, id::Integer, args...; kwargs...)\n\nPerform fetch(remotecall(...)) in one message. Keyword arguments, if any, are passed through to f. Any remote exceptions are captured in a RemoteException and thrown.\n\nSee also fetch and remotecall.\n\n\n\n" -}, - -{ - "location": "stdlib/parallel.html#Base.Distributed.remote_do-Tuple{Any,Integer,Vararg{Any,N} where N}", - "page": "Tasks and Parallel Computing", - "title": "Base.Distributed.remote_do", - "category": "method", - "text": "remote_do(f, id::Integer, args...; kwargs...) -> nothing\n\nExecutes f on worker id asynchronously. Unlike remotecall, it does not store the result of computation, nor is there a way to wait for its completion.\n\nA successful invocation indicates that the request has been accepted for execution on the remote node.\n\nWhile consecutive remotecalls to the same worker are serialized in the order they are invoked, the order of executions on the remote worker is undetermined. For example, remote_do(f1, 2); remotecall(f2, 2); remote_do(f3, 2) will serialize the call to f1, followed by f2 and f3 in that order. However, it is not guaranteed that f1 is executed before f3 on worker 2.\n\nAny exceptions thrown by f are printed to STDERR on the remote worker.\n\nKeyword arguments, if any, are passed through to f.\n\n\n\n" -}, - -{ - "location": "stdlib/parallel.html#Base.put!-Tuple{RemoteChannel,Vararg{Any,N} where N}", - "page": "Tasks and Parallel Computing", - "title": "Base.put!", - "category": "method", - "text": "put!(rr::RemoteChannel, args...)\n\nStore a set of values to the RemoteChannel. If the channel is full, blocks until space is available. Returns its first argument.\n\n\n\n" -}, - -{ - "location": "stdlib/parallel.html#Base.put!-Tuple{Future,Any}", - "page": "Tasks and Parallel Computing", - "title": "Base.put!", - "category": "method", - "text": "put!(rr::Future, v)\n\nStore a value to a Future rr. Futures are write-once remote references. A put! on an already set Future throws an Exception. All asynchronous remote calls return Futures and set the value to the return value of the call upon completion.\n\n\n\n" -}, - -{ - "location": "stdlib/parallel.html#Base.take!-Tuple{RemoteChannel,Vararg{Any,N} where N}", - "page": "Tasks and Parallel Computing", - "title": "Base.take!", - "category": "method", - "text": "take!(rr::RemoteChannel, args...)\n\nFetch value(s) from a RemoteChannel rr, removing the value(s) in the processs.\n\n\n\n" -}, - -{ - "location": "stdlib/parallel.html#Base.isready-Tuple{RemoteChannel,Vararg{Any,N} where N}", - "page": "Tasks and Parallel Computing", - "title": "Base.isready", - "category": "method", - "text": "isready(rr::RemoteChannel, args...)\n\nDetermine whether a RemoteChannel has a value stored to it. Note that this function can cause race conditions, since by the time you receive its result it may no longer be true. However, it can be safely used on a Future since they are assigned only once.\n\n\n\n" -}, - -{ - "location": "stdlib/parallel.html#Base.isready-Tuple{Future}", - "page": "Tasks and Parallel Computing", - "title": "Base.isready", - "category": "method", - "text": "isready(rr::Future)\n\nDetermine whether a Future has a value stored to it.\n\nIf the argument Future is owned by a different node, this call will block to wait for the answer. It is recommended to wait for rr in a separate task instead or to use a local Channel as a proxy:\n\nc = Channel(1)\n@async put!(c, remotecall_fetch(long_computation, p))\nisready(c) # will not block\n\n\n\n" -}, - -{ - "location": "stdlib/parallel.html#Base.Distributed.WorkerPool", - "page": "Tasks and Parallel Computing", - "title": "Base.Distributed.WorkerPool", - "category": "type", - "text": "WorkerPool(workers::Vector{Int})\n\nCreate a WorkerPool from a vector of worker ids.\n\n\n\n" -}, - -{ - "location": "stdlib/parallel.html#Base.Distributed.CachingPool", - "page": "Tasks and Parallel Computing", - "title": "Base.Distributed.CachingPool", - "category": "type", - "text": "CachingPool(workers::Vector{Int})\n\nAn implementation of an AbstractWorkerPool. remote, remotecall_fetch, pmap (and other remote calls which execute functions remotely) benefit from caching the serialized/deserialized functions on the worker nodes, especially closures (which may capture large amounts of data).\n\nThe remote cache is maintained for the lifetime of the returned CachingPool object. To clear the cache earlier, use clear!(pool).\n\nFor global variables, only the bindings are captured in a closure, not the data. let blocks can be used to capture global data.\n\nFor example:\n\nconst foo=rand(10^8);\nwp=CachingPool(workers())\nlet foo=foo\n pmap(wp, i->sum(foo)+i, 1:100);\nend\n\nThe above would transfer foo only once to each worker.\n\n\n\n" -}, - -{ - "location": "stdlib/parallel.html#Base.Distributed.default_worker_pool", - "page": "Tasks and Parallel Computing", - "title": "Base.Distributed.default_worker_pool", - "category": "function", - "text": "default_worker_pool()\n\nWorkerPool containing idle workers() - used by remote(f) and pmap (by default).\n\n\n\n" -}, - -{ - "location": "stdlib/parallel.html#Base.Distributed.clear!-Tuple{CachingPool}", - "page": "Tasks and Parallel Computing", - "title": "Base.Distributed.clear!", - "category": "method", - "text": "clear!(pool::CachingPool) -> pool\n\nRemoves all cached functions from all participating workers.\n\n\n\n" -}, - -{ - "location": "stdlib/parallel.html#Base.Distributed.remote", - "page": "Tasks and Parallel Computing", - "title": "Base.Distributed.remote", - "category": "function", - "text": "remote([::AbstractWorkerPool], f) -> Function\n\nReturns an anonymous function that executes function f on an available worker using remotecall_fetch.\n\n\n\n" -}, - -{ - "location": "stdlib/parallel.html#Base.Distributed.remotecall-Tuple{Any,Base.Distributed.AbstractWorkerPool,Vararg{Any,N} where N}", - "page": "Tasks and Parallel Computing", - "title": "Base.Distributed.remotecall", - "category": "method", - "text": "remotecall(f, pool::AbstractWorkerPool, args...; kwargs...) -> Future\n\nWorkerPool variant of remotecall(f, pid, ....). Waits for and takes a free worker from pool and performs a remotecall on it.\n\n\n\n" -}, - -{ - "location": "stdlib/parallel.html#Base.Distributed.remotecall_wait-Tuple{Any,Base.Distributed.AbstractWorkerPool,Vararg{Any,N} where N}", - "page": "Tasks and Parallel Computing", - "title": "Base.Distributed.remotecall_wait", - "category": "method", - "text": "remotecall_wait(f, pool::AbstractWorkerPool, args...; kwargs...) -> Future\n\nWorkerPool variant of remotecall_wait(f, pid, ....). Waits for and takes a free worker from pool and performs a remotecall_wait on it.\n\n\n\n" -}, - -{ - "location": "stdlib/parallel.html#Base.Distributed.remotecall_fetch-Tuple{Any,Base.Distributed.AbstractWorkerPool,Vararg{Any,N} where N}", - "page": "Tasks and Parallel Computing", - "title": "Base.Distributed.remotecall_fetch", - "category": "method", - "text": "remotecall_fetch(f, pool::AbstractWorkerPool, args...; kwargs...) -> result\n\nWorkerPool variant of remotecall_fetch(f, pid, ....). Waits for and takes a free worker from pool and performs a remotecall_fetch on it.\n\n\n\n" -}, - -{ - "location": "stdlib/parallel.html#Base.Distributed.remote_do-Tuple{Any,Base.Distributed.AbstractWorkerPool,Vararg{Any,N} where N}", - "page": "Tasks and Parallel Computing", - "title": "Base.Distributed.remote_do", - "category": "method", - "text": "remote_do(f, pool::AbstractWorkerPool, args...; kwargs...) -> nothing\n\nWorkerPool variant of remote_do(f, pid, ....). Waits for and takes a free worker from pool and performs a remote_do on it.\n\n\n\n" -}, - -{ - "location": "stdlib/parallel.html#Base.timedwait", - "page": "Tasks and Parallel Computing", - "title": "Base.timedwait", - "category": "function", - "text": "timedwait(testcb::Function, secs::Float64; pollint::Float64=0.1)\n\nWaits until testcb returns true or for secs seconds, whichever is earlier. testcb is polled every pollint seconds.\n\n\n\n" -}, - -{ - "location": "stdlib/parallel.html#Base.Distributed.@spawn", - "page": "Tasks and Parallel Computing", - "title": "Base.Distributed.@spawn", - "category": "macro", - "text": "@spawn\n\nCreates a closure around an expression and runs it on an automatically-chosen process, returning a Future to the result.\n\n\n\n" -}, - -{ - "location": "stdlib/parallel.html#Base.Distributed.@spawnat", - "page": "Tasks and Parallel Computing", - "title": "Base.Distributed.@spawnat", - "category": "macro", - "text": "@spawnat\n\nAccepts two arguments, p and an expression. A closure is created around the expression and run asynchronously on process p. Returns a Future to the result.\n\n\n\n" -}, - -{ - "location": "stdlib/parallel.html#Base.Distributed.@fetch", - "page": "Tasks and Parallel Computing", - "title": "Base.Distributed.@fetch", - "category": "macro", - "text": "@fetch\n\nEquivalent to fetch(@spawn expr). See fetch and @spawn.\n\n\n\n" -}, - -{ - "location": "stdlib/parallel.html#Base.Distributed.@fetchfrom", - "page": "Tasks and Parallel Computing", - "title": "Base.Distributed.@fetchfrom", - "category": "macro", - "text": "@fetchfrom\n\nEquivalent to fetch(@spawnat p expr). See fetch and @spawnat.\n\n\n\n" -}, - -{ - "location": "stdlib/parallel.html#Base.@async", - "page": "Tasks and Parallel Computing", - "title": "Base.@async", - "category": "macro", - "text": "@async\n\nLike @schedule, @async wraps an expression in a Task and adds it to the local machine\'s scheduler queue. Additionally it adds the task to the set of items that the nearest enclosing @sync waits for.\n\n\n\n" -}, - -{ - "location": "stdlib/parallel.html#Base.@sync", - "page": "Tasks and Parallel Computing", - "title": "Base.@sync", - "category": "macro", - "text": "@sync\n\nWait until all dynamically-enclosed uses of @async, @spawn, @spawnat and @parallel are complete. All exceptions thrown by enclosed async operations are collected and thrown as a CompositeException.\n\n\n\n" -}, - -{ - "location": "stdlib/parallel.html#Base.Distributed.@parallel", - "page": "Tasks and Parallel Computing", - "title": "Base.Distributed.@parallel", - "category": "macro", - "text": "@parallel\n\nA parallel for loop of the form :\n\n@parallel [reducer] for var = range\n body\nend\n\nThe specified range is partitioned and locally executed across all workers. In case an optional reducer function is specified, @parallel performs local reductions on each worker with a final reduction on the calling process.\n\nNote that without a reducer function, @parallel executes asynchronously, i.e. it spawns independent tasks on all available workers and returns immediately without waiting for completion. To wait for completion, prefix the call with @sync, like :\n\n@sync @parallel for var = range\n body\nend\n\n\n\n" -}, - -{ - "location": "stdlib/parallel.html#Base.Distributed.@everywhere", - "page": "Tasks and Parallel Computing", - "title": "Base.Distributed.@everywhere", - "category": "macro", - "text": "@everywhere expr\n\nExecute an expression under Main everywhere. Equivalent to calling eval(Main, expr) on all processes. Errors on any of the processes are collected into a CompositeException and thrown. For example :\n\n@everywhere bar=1\n\nwill define Main.bar on all processes.\n\nUnlike @spawn and @spawnat, @everywhere does not capture any local variables. Prefixing @everywhere with @eval allows us to broadcast local variables using interpolation :\n\nfoo = 1\n@eval @everywhere bar=$foo\n\nThe expression is evaluated under Main irrespective of where @everywhere is called from. For example :\n\nmodule FooBar\n foo() = @everywhere bar()=myid()\nend\nFooBar.foo()\n\nwill result in Main.bar being defined on all processes and not FooBar.bar.\n\n\n\n" -}, - -{ - "location": "stdlib/parallel.html#Base.Distributed.clear!-Tuple{Any,Any}", - "page": "Tasks and Parallel Computing", - "title": "Base.Distributed.clear!", - "category": "method", - "text": "clear!(syms, pids=workers(); mod=Main)\n\nClears global bindings in modules by initializing them to nothing. syms should be of type Symbol or a collection of Symbols . pids and mod identify the processes and the module in which global variables are to be reinitialized. Only those names found to be defined under mod are cleared.\n\nAn exception is raised if a global constant is requested to be cleared.\n\n\n\n" -}, - -{ - "location": "stdlib/parallel.html#Base.Distributed.remoteref_id", - "page": "Tasks and Parallel Computing", - "title": "Base.Distributed.remoteref_id", - "category": "function", - "text": "Base.remoteref_id(r::AbstractRemoteRef) -> RRID\n\nFutures and RemoteChannels are identified by fields:\n\nwhere - refers to the node where the underlying object/storage referred to by the reference actually exists.\nwhence - refers to the node the remote reference was created from. Note that this is different from the node where the underlying object referred to actually exists. For example calling RemoteChannel(2) from the master process would result in a where value of 2 and a whence value of 1.\nid is unique across all references created from the worker specified by whence.\n\nTaken together, whence and id uniquely identify a reference across all workers.\n\nBase.remoteref_id is a low-level API which returns a Base.RRID object that wraps whence and id values of a remote reference.\n\n\n\n" -}, - -{ - "location": "stdlib/parallel.html#Base.Distributed.channel_from_id", - "page": "Tasks and Parallel Computing", - "title": "Base.Distributed.channel_from_id", - "category": "function", - "text": "Base.channel_from_id(id) -> c\n\nA low-level API which returns the backing AbstractChannel for an id returned by remoteref_id. The call is valid only on the node where the backing channel exists.\n\n\n\n" -}, - -{ - "location": "stdlib/parallel.html#Base.Distributed.worker_id_from_socket", - "page": "Tasks and Parallel Computing", - "title": "Base.Distributed.worker_id_from_socket", - "category": "function", - "text": "Base.worker_id_from_socket(s) -> pid\n\nA low-level API which given a IO connection or a Worker, returns the pid of the worker it is connected to. This is useful when writing custom serialize methods for a type, which optimizes the data written out depending on the receiving process id.\n\n\n\n" -}, - -{ - "location": "stdlib/parallel.html#Base.Distributed.cluster_cookie-Tuple{}", - "page": "Tasks and Parallel Computing", - "title": "Base.Distributed.cluster_cookie", - "category": "method", - "text": "Base.cluster_cookie() -> cookie\n\nReturns the cluster cookie.\n\n\n\n" -}, - -{ - "location": "stdlib/parallel.html#Base.Distributed.cluster_cookie-Tuple{Any}", - "page": "Tasks and Parallel Computing", - "title": "Base.Distributed.cluster_cookie", - "category": "method", - "text": "Base.cluster_cookie(cookie) -> cookie\n\nSets the passed cookie as the cluster cookie, then returns it.\n\n\n\n" -}, - -{ - "location": "stdlib/parallel.html#General-Parallel-Computing-Support-1", - "page": "Tasks and Parallel Computing", - "title": "General Parallel Computing Support", - "category": "section", - "text": "Base.addprocs\nBase.nprocs\nBase.nworkers\nBase.procs()\nBase.procs(::Integer)\nBase.workers\nBase.rmprocs\nBase.interrupt\nBase.myid\nBase.pmap\nBase.RemoteException\nBase.Future\nBase.RemoteChannel(::Integer)\nBase.RemoteChannel(::Function, ::Integer)\nBase.wait\nBase.fetch(::Any)\nBase.remotecall(::Any, ::Integer, ::Any...)\nBase.remotecall_wait(::Any, ::Integer, ::Any...)\nBase.remotecall_fetch(::Any, ::Integer, ::Any...)\nBase.remote_do(::Any, ::Integer, ::Any...)\nBase.put!(::RemoteChannel, ::Any...)\nBase.put!(::Future, ::Any)\nBase.take!(::RemoteChannel, ::Any...)\nBase.isready(::RemoteChannel, ::Any...)\nBase.isready(::Future)\nBase.WorkerPool\nBase.CachingPool\nBase.default_worker_pool\nBase.clear!(::CachingPool)\nBase.remote\nBase.remotecall(::Any, ::Base.Distributed.AbstractWorkerPool, ::Any...)\nBase.remotecall_wait(::Any, ::Base.Distributed.AbstractWorkerPool, ::Any...)\nBase.remotecall_fetch(::Any, ::Base.Distributed.AbstractWorkerPool, ::Any...)\nBase.remote_do(::Any, ::Base.Distributed.AbstractWorkerPool, ::Any...)\nBase.timedwait\nBase.@spawn\nBase.@spawnat\nBase.@fetch\nBase.@fetchfrom\nBase.@async\nBase.@sync\nBase.@parallel\nBase.@everywhere\nBase.clear!(::Any, ::Any; ::Any)\nBase.remoteref_id\nBase.channel_from_id\nBase.worker_id_from_socket\nBase.cluster_cookie()\nBase.cluster_cookie(::Any)" -}, - -{ - "location": "stdlib/parallel.html#Base.SharedArray", - "page": "Tasks and Parallel Computing", - "title": "Base.SharedArray", - "category": "type", - "text": "SharedArray{T}(dims::NTuple; init=false, pids=Int[])\nSharedArray{T,N}(...)\n\nConstruct a SharedArray of a bits type T and size dims across the processes specified by pids - all of which have to be on the same host. If N is specified by calling SharedArray{T,N}(dims), then N must match the length of dims.\n\nIf pids is left unspecified, the shared array will be mapped across all processes on the current host, including the master. But, localindexes and indexpids will only refer to worker processes. This facilitates work distribution code to use workers for actual computation with the master process acting as a driver.\n\nIf an init function of the type initfn(S::SharedArray) is specified, it is called on all the participating workers.\n\nThe shared array is valid as long as a reference to the SharedArray object exists on the node which created the mapping.\n\nSharedArray{T}(filename::AbstractString, dims::NTuple, [offset=0]; mode=nothing, init=false, pids=Int[])\nSharedArray{T,N}(...)\n\nConstruct a SharedArray backed by the file filename, with element type T (must be a bits type) and size dims, across the processes specified by pids - all of which have to be on the same host. This file is mmapped into the host memory, with the following consequences:\n\nThe array data must be represented in binary format (e.g., an ASCII format like CSV cannot be supported)\nAny changes you make to the array values (e.g., A[3] = 0) will also change the values on disk\n\nIf pids is left unspecified, the shared array will be mapped across all processes on the current host, including the master. But, localindexes and indexpids will only refer to worker processes. This facilitates work distribution code to use workers for actual computation with the master process acting as a driver.\n\nmode must be one of \"r\", \"r+\", \"w+\", or \"a+\", and defaults to \"r+\" if the file specified by filename already exists, or \"w+\" if not. If an init function of the type initfn(S::SharedArray) is specified, it is called on all the participating workers. You cannot specify an init function if the file is not writable.\n\noffset allows you to skip the specified number of bytes at the beginning of the file.\n\n\n\n" -}, - -{ - "location": "stdlib/parallel.html#Base.Distributed.procs-Tuple{SharedArray}", - "page": "Tasks and Parallel Computing", - "title": "Base.Distributed.procs", - "category": "method", - "text": "procs(S::SharedArray)\n\nGet the vector of processes mapping the shared array.\n\n\n\n" -}, - -{ - "location": "stdlib/parallel.html#Base.sdata", - "page": "Tasks and Parallel Computing", - "title": "Base.sdata", - "category": "function", - "text": "sdata(S::SharedArray)\n\nReturns the actual Array object backing S.\n\n\n\n" -}, - -{ - "location": "stdlib/parallel.html#Base.indexpids", - "page": "Tasks and Parallel Computing", - "title": "Base.indexpids", - "category": "function", - "text": "indexpids(S::SharedArray)\n\nReturns the current worker\'s index in the list of workers mapping the SharedArray (i.e. in the same list returned by procs(S)), or 0 if the SharedArray is not mapped locally.\n\n\n\n" -}, - -{ - "location": "stdlib/parallel.html#Base.localindexes", - "page": "Tasks and Parallel Computing", - "title": "Base.localindexes", - "category": "function", - "text": "localindexes(S::SharedArray)\n\nReturns a range describing the \"default\" indexes to be handled by the current process. This range should be interpreted in the sense of linear indexing, i.e., as a sub-range of 1:length(S). In multi-process contexts, returns an empty range in the parent process (or any process for which indexpids returns 0).\n\nIt\'s worth emphasizing that localindexes exists purely as a convenience, and you can partition work on the array among workers any way you wish. For a SharedArray, all indexes should be equally fast for each worker process.\n\n\n\n" -}, - -{ - "location": "stdlib/parallel.html#Shared-Arrays-1", - "page": "Tasks and Parallel Computing", - "title": "Shared Arrays", - "category": "section", - "text": "Base.SharedArray\nBase.procs(::SharedArray)\nBase.sdata\nBase.indexpids\nBase.localindexes" -}, - -{ - "location": "stdlib/parallel.html#Base.Threads.threadid", - "page": "Tasks and Parallel Computing", - "title": "Base.Threads.threadid", - "category": "function", - "text": "Threads.threadid()\n\nGet the ID number of the current thread of execution. The master thread has ID 1.\n\n\n\n" -}, - -{ - "location": "stdlib/parallel.html#Base.Threads.nthreads", - "page": "Tasks and Parallel Computing", - "title": "Base.Threads.nthreads", - "category": "function", - "text": "Threads.nthreads()\n\nGet the number of threads available to the Julia process. This is the inclusive upper bound on threadid().\n\n\n\n" -}, - -{ - "location": "stdlib/parallel.html#Base.Threads.@threads", - "page": "Tasks and Parallel Computing", - "title": "Base.Threads.@threads", - "category": "macro", - "text": "Threads.@threads\n\nA macro to parallelize a for-loop to run with multiple threads. This spawns nthreads() number of threads, splits the iteration space amongst them, and iterates in parallel. A barrier is placed at the end of the loop which waits for all the threads to finish execution, and the loop returns.\n\n\n\n" -}, - -{ - "location": "stdlib/parallel.html#Base.Threads.Atomic", - "page": "Tasks and Parallel Computing", - "title": "Base.Threads.Atomic", - "category": "type", - "text": "Threads.Atomic{T}\n\nHolds a reference to an object of type T, ensuring that it is only accessed atomically, i.e. in a thread-safe manner.\n\nOnly certain \"simple\" types can be used atomically, namely the primitive integer and float-point types. These are Int8...Int128, UInt8...UInt128, and Float16...Float64.\n\nNew atomic objects can be created from a non-atomic values; if none is specified, the atomic object is initialized with zero.\n\nAtomic objects can be accessed using the [] notation:\n\njulia> x = Threads.Atomic{Int}(3)\nBase.Threads.Atomic{Int64}(3)\n\njulia> x[] = 1\n1\n\njulia> x[]\n1\n\nAtomic operations use an atomic_ prefix, such as atomic_add!, atomic_xchg!, etc.\n\n\n\n" -}, - -{ - "location": "stdlib/parallel.html#Base.Threads.atomic_cas!", - "page": "Tasks and Parallel Computing", - "title": "Base.Threads.atomic_cas!", - "category": "function", - "text": "Threads.atomic_cas!{T}(x::Atomic{T}, cmp::T, newval::T)\n\nAtomically compare-and-set x\n\nAtomically compares the value in x with cmp. If equal, write newval to x. Otherwise, leaves x unmodified. Returns the old value in x. By comparing the returned value to cmp (via ===) one knows whether x was modified and now holds the new value newval.\n\nFor further details, see LLVM\'s cmpxchg instruction.\n\nThis function can be used to implement transactional semantics. Before the transaction, one records the value in x. After the transaction, the new value is stored only if x has not been modified in the mean time.\n\njulia> x = Threads.Atomic{Int}(3)\nBase.Threads.Atomic{Int64}(3)\n\njulia> Threads.atomic_cas!(x, 4, 2);\n\njulia> x\nBase.Threads.Atomic{Int64}(3)\n\njulia> Threads.atomic_cas!(x, 3, 2);\n\njulia> x\nBase.Threads.Atomic{Int64}(2)\n\n\n\n" -}, - -{ - "location": "stdlib/parallel.html#Base.Threads.atomic_xchg!", - "page": "Tasks and Parallel Computing", - "title": "Base.Threads.atomic_xchg!", - "category": "function", - "text": "Threads.atomic_xchg!{T}(x::Atomic{T}, newval::T)\n\nAtomically exchange the value in x\n\nAtomically exchanges the value in x with newval. Returns the old value.\n\nFor further details, see LLVM\'s atomicrmw xchg instruction.\n\njulia> x = Threads.Atomic{Int}(3)\nBase.Threads.Atomic{Int64}(3)\n\njulia> Threads.atomic_xchg!(x, 2)\n3\n\njulia> x[]\n2\n\n\n\n" -}, - -{ - "location": "stdlib/parallel.html#Base.Threads.atomic_add!", - "page": "Tasks and Parallel Computing", - "title": "Base.Threads.atomic_add!", - "category": "function", - "text": "Threads.atomic_add!{T}(x::Atomic{T}, val::T)\n\nAtomically add val to x\n\nPerforms x[] += val atomically. Returns the old value.\n\nFor further details, see LLVM\'s atomicrmw add instruction.\n\njulia> x = Threads.Atomic{Int}(3)\nBase.Threads.Atomic{Int64}(3)\n\njulia> Threads.atomic_add!(x, 2)\n3\n\njulia> x[]\n5\n\n\n\n" -}, - -{ - "location": "stdlib/parallel.html#Base.Threads.atomic_sub!", - "page": "Tasks and Parallel Computing", - "title": "Base.Threads.atomic_sub!", - "category": "function", - "text": "Threads.atomic_sub!{T}(x::Atomic{T}, val::T)\n\nAtomically subtract val from x\n\nPerforms x[] -= val atomically. Returns the old value.\n\nFor further details, see LLVM\'s atomicrmw sub instruction.\n\njulia> x = Threads.Atomic{Int}(3)\nBase.Threads.Atomic{Int64}(3)\n\njulia> Threads.atomic_sub!(x, 2)\n3\n\njulia> x[]\n1\n\n\n\n" -}, - -{ - "location": "stdlib/parallel.html#Base.Threads.atomic_and!", - "page": "Tasks and Parallel Computing", - "title": "Base.Threads.atomic_and!", - "category": "function", - "text": "Threads.atomic_and!{T}(x::Atomic{T}, val::T)\n\nAtomically bitwise-and x with val\n\nPerforms x[] &= val atomically. Returns the old value.\n\nFor further details, see LLVM\'s atomicrmw and instruction.\n\njulia> x = Threads.Atomic{Int}(3)\nBase.Threads.Atomic{Int64}(3)\n\njulia> Threads.atomic_and!(x, 2)\n3\n\njulia> x[]\n2\n\n\n\n" -}, - -{ - "location": "stdlib/parallel.html#Base.Threads.atomic_nand!", - "page": "Tasks and Parallel Computing", - "title": "Base.Threads.atomic_nand!", - "category": "function", - "text": "Threads.atomic_nand!{T}(x::Atomic{T}, val::T)\n\nAtomically bitwise-nand (not-and) x with val\n\nPerforms x[] = ~(x[] & val) atomically. Returns the old value.\n\nFor further details, see LLVM\'s atomicrmw nand instruction.\n\njulia> x = Threads.Atomic{Int}(3)\nBase.Threads.Atomic{Int64}(3)\n\njulia> Threads.atomic_nand!(x, 2)\n3\n\njulia> x[]\n-3\n\n\n\n" -}, - -{ - "location": "stdlib/parallel.html#Base.Threads.atomic_or!", - "page": "Tasks and Parallel Computing", - "title": "Base.Threads.atomic_or!", - "category": "function", - "text": "Threads.atomic_or!{T}(x::Atomic{T}, val::T)\n\nAtomically bitwise-or x with val\n\nPerforms x[] |= val atomically. Returns the old value.\n\nFor further details, see LLVM\'s atomicrmw or instruction.\n\njulia> x = Threads.Atomic{Int}(5)\nBase.Threads.Atomic{Int64}(5)\n\njulia> Threads.atomic_or!(x, 7)\n5\n\njulia> x[]\n7\n\n\n\n" -}, - -{ - "location": "stdlib/parallel.html#Base.Threads.atomic_xor!", - "page": "Tasks and Parallel Computing", - "title": "Base.Threads.atomic_xor!", - "category": "function", - "text": "Threads.atomic_xor!{T}(x::Atomic{T}, val::T)\n\nAtomically bitwise-xor (exclusive-or) x with val\n\nPerforms x[] $= val atomically. Returns the old value.\n\nFor further details, see LLVM\'s atomicrmw xor instruction.\n\njulia> x = Threads.Atomic{Int}(5)\nBase.Threads.Atomic{Int64}(5)\n\njulia> Threads.atomic_xor!(x, 7)\n5\n\njulia> x[]\n2\n\n\n\n" -}, - -{ - "location": "stdlib/parallel.html#Base.Threads.atomic_max!", - "page": "Tasks and Parallel Computing", - "title": "Base.Threads.atomic_max!", - "category": "function", - "text": "Threads.atomic_max!{T}(x::Atomic{T}, val::T)\n\nAtomically store the maximum of x and val in x\n\nPerforms x[] = max(x[], val) atomically. Returns the old value.\n\nFor further details, see LLVM\'s atomicrmw max instruction.\n\njulia> x = Threads.Atomic{Int}(5)\nBase.Threads.Atomic{Int64}(5)\n\njulia> Threads.atomic_max!(x, 7)\n5\n\njulia> x[]\n7\n\n\n\n" -}, - -{ - "location": "stdlib/parallel.html#Base.Threads.atomic_min!", - "page": "Tasks and Parallel Computing", - "title": "Base.Threads.atomic_min!", - "category": "function", - "text": "Threads.atomic_min!{T}(x::Atomic{T}, val::T)\n\nAtomically store the minimum of x and val in x\n\nPerforms x[] = min(x[], val) atomically. Returns the old value.\n\nFor further details, see LLVM\'s atomicrmw min instruction.\n\njulia> x = Threads.Atomic{Int}(7)\nBase.Threads.Atomic{Int64}(7)\n\njulia> Threads.atomic_min!(x, 5)\n7\n\njulia> x[]\n5\n\n\n\n" -}, - -{ - "location": "stdlib/parallel.html#Base.Threads.atomic_fence", - "page": "Tasks and Parallel Computing", - "title": "Base.Threads.atomic_fence", - "category": "function", - "text": "Threads.atomic_fence()\n\nInsert a sequential-consistency memory fence\n\nInserts a memory fence with sequentially-consistent ordering semantics. There are algorithms where this is needed, i.e. where an acquire/release ordering is insufficient.\n\nThis is likely a very expensive operation. Given that all other atomic operations in Julia already have acquire/release semantics, explicit fences should not be necessary in most cases.\n\nFor further details, see LLVM\'s fence instruction.\n\n\n\n" -}, - -{ - "location": "stdlib/parallel.html#Multi-Threading-1", - "page": "Tasks and Parallel Computing", - "title": "Multi-Threading", - "category": "section", - "text": "This experimental interface supports Julia\'s multi-threading capabilities. Types and functions described here might (and likely will) change in the future.Base.Threads.threadid\nBase.Threads.nthreads\nBase.Threads.@threads\nBase.Threads.Atomic\nBase.Threads.atomic_cas!\nBase.Threads.atomic_xchg!\nBase.Threads.atomic_add!\nBase.Threads.atomic_sub!\nBase.Threads.atomic_and!\nBase.Threads.atomic_nand!\nBase.Threads.atomic_or!\nBase.Threads.atomic_xor!\nBase.Threads.atomic_max!\nBase.Threads.atomic_min!\nBase.Threads.atomic_fence" -}, - -{ - "location": "stdlib/parallel.html#Base.@threadcall", - "page": "Tasks and Parallel Computing", - "title": "Base.@threadcall", - "category": "macro", - "text": "@threadcall((cfunc, clib), rettype, (argtypes...), argvals...)\n\nThe @threadcall macro is called in the same way as ccall but does the work in a different thread. This is useful when you want to call a blocking C function without causing the main julia thread to become blocked. Concurrency is limited by size of the libuv thread pool, which defaults to 4 threads but can be increased by setting the UV_THREADPOOL_SIZE environment variable and restarting the julia process.\n\nNote that the called function should never call back into Julia.\n\n\n\n" -}, - -{ - "location": "stdlib/parallel.html#ccall-using-a-threadpool-(Experimental)-1", - "page": "Tasks and Parallel Computing", - "title": "ccall using a threadpool (Experimental)", - "category": "section", - "text": "Base.@threadcall" -}, - -{ - "location": "stdlib/parallel.html#Base.Threads.AbstractLock", - "page": "Tasks and Parallel Computing", - "title": "Base.Threads.AbstractLock", - "category": "type", - "text": "AbstractLock\n\nAbstract supertype describing types that implement the thread-safe synchronization primitives: lock, trylock, unlock, and islocked\n\n\n\n" -}, - -{ - "location": "stdlib/parallel.html#Base.lock", - "page": "Tasks and Parallel Computing", - "title": "Base.lock", - "category": "function", - "text": "lock(the_lock)\n\nAcquires the lock when it becomes available. If the lock is already locked by a different task/thread, it waits for it to become available.\n\nEach lock must be matched by an unlock.\n\n\n\n" -}, - -{ - "location": "stdlib/parallel.html#Base.unlock", - "page": "Tasks and Parallel Computing", - "title": "Base.unlock", - "category": "function", - "text": "unlock(the_lock)\n\nReleases ownership of the lock.\n\nIf this is a recursive lock which has been acquired before, it just decrements an internal counter and returns immediately.\n\n\n\n" -}, - -{ - "location": "stdlib/parallel.html#Base.trylock", - "page": "Tasks and Parallel Computing", - "title": "Base.trylock", - "category": "function", - "text": "trylock(the_lock) -> Success (Boolean)\n\nAcquires the lock if it is available, returning true if successful. If the lock is already locked by a different task/thread, returns false.\n\nEach successful trylock must be matched by an unlock.\n\n\n\n" -}, - -{ - "location": "stdlib/parallel.html#Base.islocked", - "page": "Tasks and Parallel Computing", - "title": "Base.islocked", - "category": "function", - "text": "islocked(the_lock) -> Status (Boolean)\n\nCheck whether the lock is held by any task/thread. This should not be used for synchronization (see instead trylock).\n\n\n\n" -}, - -{ - "location": "stdlib/parallel.html#Base.ReentrantLock", - "page": "Tasks and Parallel Computing", - "title": "Base.ReentrantLock", - "category": "type", - "text": "ReentrantLock()\n\nCreates a reentrant lock for synchronizing Tasks. The same task can acquire the lock as many times as required. Each lock must be matched with an unlock.\n\nThis lock is NOT threadsafe. See Threads.Mutex for a threadsafe lock.\n\n\n\n" -}, - -{ - "location": "stdlib/parallel.html#Base.Threads.Mutex", - "page": "Tasks and Parallel Computing", - "title": "Base.Threads.Mutex", - "category": "type", - "text": "Mutex()\n\nThese are standard system mutexes for locking critical sections of logic.\n\nOn Windows, this is a critical section object, on pthreads, this is a pthread_mutex_t.\n\nSee also SpinLock for a lighter-weight lock.\n\n\n\n" -}, - -{ - "location": "stdlib/parallel.html#Base.Threads.SpinLock", - "page": "Tasks and Parallel Computing", - "title": "Base.Threads.SpinLock", - "category": "type", - "text": "SpinLock()\n\nCreates a non-reentrant lock. Recursive use will result in a deadlock. Each lock must be matched with an unlock.\n\nTest-and-test-and-set spin locks are quickest up to about 30ish contending threads. If you have more contention than that, perhaps a lock is the wrong way to synchronize.\n\nSee also RecursiveSpinLock for a version that permits recursion.\n\nSee also Mutex for a more efficient version on one core or if the lock may be held for a considerable length of time.\n\n\n\n" -}, - -{ - "location": "stdlib/parallel.html#Base.Threads.RecursiveSpinLock", - "page": "Tasks and Parallel Computing", - "title": "Base.Threads.RecursiveSpinLock", - "category": "type", - "text": "RecursiveSpinLock()\n\nCreates a reentrant lock. The same thread can acquire the lock as many times as required. Each lock must be matched with an unlock.\n\nSee also SpinLock for a slightly faster version.\n\nSee also Mutex for a more efficient version on one core or if the lock may be held for a considerable length of time.\n\n\n\n" -}, - -{ - "location": "stdlib/parallel.html#Base.Semaphore", - "page": "Tasks and Parallel Computing", - "title": "Base.Semaphore", - "category": "type", - "text": "Semaphore(sem_size)\n\nCreates a counting semaphore that allows at most sem_size acquires to be in use at any time. Each acquire must be mached with a release.\n\nThis construct is NOT threadsafe.\n\n\n\n" -}, - -{ - "location": "stdlib/parallel.html#Base.acquire", - "page": "Tasks and Parallel Computing", - "title": "Base.acquire", - "category": "function", - "text": "acquire(s::Semaphore)\n\nWait for one of the sem_size permits to be available, blocking until one can be acquired.\n\n\n\n" -}, - -{ - "location": "stdlib/parallel.html#Base.release", - "page": "Tasks and Parallel Computing", - "title": "Base.release", - "category": "function", - "text": "release(s::Semaphore)\n\nReturn one permit to the pool, possibly allowing another task to acquire it and resume execution.\n\n\n\n" -}, - -{ - "location": "stdlib/parallel.html#Synchronization-Primitives-1", - "page": "Tasks and Parallel Computing", - "title": "Synchronization Primitives", - "category": "section", - "text": "Base.Threads.AbstractLock\nBase.lock\nBase.unlock\nBase.trylock\nBase.islocked\nBase.ReentrantLock\nBase.Threads.Mutex\nBase.Threads.SpinLock\nBase.Threads.RecursiveSpinLock\nBase.Semaphore\nBase.acquire\nBase.release" -}, - -{ - "location": "stdlib/parallel.html#Base.Distributed.launch", - "page": "Tasks and Parallel Computing", - "title": "Base.Distributed.launch", - "category": "function", - "text": "launch(manager::ClusterManager, params::Dict, launched::Array, launch_ntfy::Condition)\n\nImplemented by cluster managers. For every Julia worker launched by this function, it should append a WorkerConfig entry to launched and notify launch_ntfy. The function MUST exit once all workers, requested by manager have been launched. params is a dictionary of all keyword arguments addprocs was called with.\n\n\n\n" -}, - -{ - "location": "stdlib/parallel.html#Base.Distributed.manage", - "page": "Tasks and Parallel Computing", - "title": "Base.Distributed.manage", - "category": "function", - "text": "manage(manager::ClusterManager, id::Integer, config::WorkerConfig. op::Symbol)\n\nImplemented by cluster managers. It is called on the master process, during a worker\'s lifetime, with appropriate op values:\n\nwith :register/:deregister when a worker is added / removed from the Julia worker pool.\nwith :interrupt when interrupt(workers) is called. The ClusterManager should signal the appropriate worker with an interrupt signal.\nwith :finalize for cleanup purposes.\n\n\n\n" -}, - -{ - "location": "stdlib/parallel.html#Base.kill-Tuple{ClusterManager,Int64,WorkerConfig}", - "page": "Tasks and Parallel Computing", - "title": "Base.kill", - "category": "method", - "text": "kill(manager::ClusterManager, pid::Int, config::WorkerConfig)\n\nImplemented by cluster managers. It is called on the master process, by rmprocs. It should cause the remote worker specified by pid to exit. kill(manager::ClusterManager.....) executes a remote exit() on pid.\n\n\n\n" -}, - -{ - "location": "stdlib/parallel.html#Base.Distributed.init_worker", - "page": "Tasks and Parallel Computing", - "title": "Base.Distributed.init_worker", - "category": "function", - "text": "init_worker(cookie::AbstractString, manager::ClusterManager=DefaultClusterManager())\n\nCalled by cluster managers implementing custom transports. It initializes a newly launched process as a worker. Command line argument --worker has the effect of initializing a process as a worker using TCP/IP sockets for transport. cookie is a cluster_cookie.\n\n\n\n" -}, - -{ - "location": "stdlib/parallel.html#Base.connect-Tuple{ClusterManager,Int64,WorkerConfig}", - "page": "Tasks and Parallel Computing", - "title": "Base.connect", - "category": "method", - "text": "connect(manager::ClusterManager, pid::Int, config::WorkerConfig) -> (instrm::IO, outstrm::IO)\n\nImplemented by cluster managers using custom transports. It should establish a logical connection to worker with id pid, specified by config and return a pair of IO objects. Messages from pid to current process will be read off instrm, while messages to be sent to pid will be written to outstrm. The custom transport implementation must ensure that messages are delivered and received completely and in order. connect(manager::ClusterManager.....) sets up TCP/IP socket connections in-between workers.\n\n\n\n" -}, - -{ - "location": "stdlib/parallel.html#Base.Distributed.process_messages", - "page": "Tasks and Parallel Computing", - "title": "Base.Distributed.process_messages", - "category": "function", - "text": "Base.process_messages(r_stream::IO, w_stream::IO, incoming::Bool=true)\n\nCalled by cluster managers using custom transports. It should be called when the custom transport implementation receives the first message from a remote worker. The custom transport must manage a logical connection to the remote worker and provide two IO objects, one for incoming messages and the other for messages addressed to the remote worker. If incoming is true, the remote peer initiated the connection. Whichever of the pair initiates the connection sends the cluster cookie and its Julia version number to perform the authentication handshake.\n\nSee also cluster_cookie.\n\n\n\n" -}, - -{ - "location": "stdlib/parallel.html#Cluster-Manager-Interface-1", - "page": "Tasks and Parallel Computing", - "title": "Cluster Manager Interface", - "category": "section", - "text": "This interface provides a mechanism to launch and manage Julia workers on different cluster environments. There are two types of managers present in Base: LocalManager, for launching additional workers on the same host, and SSHManager, for launching on remote hosts via ssh. TCP/IP sockets are used to connect and transport messages between processes. It is possible for Cluster Managers to provide a different transport.Base.launch\nBase.manage\nBase.kill(::ClusterManager, ::Int, ::WorkerConfig)\nBase.init_worker\nBase.connect(::ClusterManager, ::Int, ::WorkerConfig)\nBase.process_messages" -}, - -{ - "location": "stdlib/linalg.html#", - "page": "Linear Algebra", - "title": "Linear Algebra", - "category": "page", - "text": "" -}, - -{ - "location": "stdlib/linalg.html#Linear-Algebra-1", - "page": "Linear Algebra", - "title": "Linear Algebra", - "category": "section", - "text": "" -}, - -{ - "location": "stdlib/linalg.html#Base.:*-Tuple{AbstractArray,AbstractArray}", - "page": "Linear Algebra", - "title": "Base.:*", - "category": "method", - "text": "*(x, y...)\n\nMultiplication operator. x*y*z*... calls this function with all arguments, i.e. *(x, y, z, ...).\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.:\\-Tuple{AbstractArray,Any}", - "page": "Linear Algebra", - "title": "Base.:\\", - "category": "method", - "text": "\\(x, y)\n\nLeft division operator: multiplication of y by the inverse of x on the left. Gives floating-point results for integer arguments.\n\njulia> 3 \\ 6\n2.0\n\njulia> inv(3) * 6\n2.0\n\njulia> A = [1 2; 3 4]; x = [5, 6];\n\njulia> A \\ x\n2-element Array{Float64,1}:\n -4.0\n 4.5\n\njulia> inv(A) * x\n2-element Array{Float64,1}:\n -4.0\n 4.5\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.dot", - "page": "Linear Algebra", - "title": "Base.LinAlg.dot", - "category": "function", - "text": "dot(n, X, incx, Y, incy)\n\nDot product of two vectors consisting of n elements of array X with stride incx and n elements of array Y with stride incy.\n\nExample:\n\njulia> dot(10, ones(10), 1, ones(20), 2)\n10.0\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.vecdot", - "page": "Linear Algebra", - "title": "Base.LinAlg.vecdot", - "category": "function", - "text": "vecdot(x, y)\n\nFor any iterable containers x and y (including arrays of any dimension) of numbers (or any element type for which dot is defined), compute the Euclidean dot product (the sum of dot(x[i],y[i])) as if they were vectors.\n\nExamples\n\njulia> vecdot(1:5, 2:6)\n70\n\njulia> x = fill(2., (5,5));\n\njulia> y = fill(3., (5,5));\n\njulia> vecdot(x, y)\n150.0\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.cross", - "page": "Linear Algebra", - "title": "Base.LinAlg.cross", - "category": "function", - "text": "cross(x, y)\n×(x,y)\n\nCompute the cross product of two 3-vectors.\n\nExample\n\njulia> a = [0;1;0]\n3-element Array{Int64,1}:\n 0\n 1\n 0\n\njulia> b = [0;0;1]\n3-element Array{Int64,1}:\n 0\n 0\n 1\n\njulia> cross(a,b)\n3-element Array{Int64,1}:\n 1\n 0\n 0\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.factorize", - "page": "Linear Algebra", - "title": "Base.LinAlg.factorize", - "category": "function", - "text": "factorize(A)\n\nCompute a convenient factorization of A, based upon the type of the input matrix. factorize checks A to see if it is symmetric/triangular/etc. if A is passed as a generic matrix. factorize checks every element of A to verify/rule out each property. It will short-circuit as soon as it can rule out symmetry/triangular structure. The return value can be reused for efficient solving of multiple systems. For example: A=factorize(A); x=A\\b; y=A\\C.\n\nProperties of A type of factorization\nPositive-definite Cholesky (see cholfact)\nDense Symmetric/Hermitian Bunch-Kaufman (see bkfact)\nSparse Symmetric/Hermitian LDLt (see ldltfact)\nTriangular Triangular\nDiagonal Diagonal\nBidiagonal Bidiagonal\nTridiagonal LU (see lufact)\nSymmetric real tridiagonal LDLt (see ldltfact)\nGeneral square LU (see lufact)\nGeneral non-square QR (see qrfact)\n\nIf factorize is called on a Hermitian positive-definite matrix, for instance, then factorize will return a Cholesky factorization.\n\nExample\n\njulia> A = Array(Bidiagonal(ones(5, 5), true))\n5×5 Array{Float64,2}:\n 1.0 1.0 0.0 0.0 0.0\n 0.0 1.0 1.0 0.0 0.0\n 0.0 0.0 1.0 1.0 0.0\n 0.0 0.0 0.0 1.0 1.0\n 0.0 0.0 0.0 0.0 1.0\n\njulia> factorize(A) # factorize will check to see that A is already factorized\n5×5 Bidiagonal{Float64}:\n 1.0 1.0 ⋅ ⋅ ⋅\n ⋅ 1.0 1.0 ⋅ ⋅\n ⋅ ⋅ 1.0 1.0 ⋅\n ⋅ ⋅ ⋅ 1.0 1.0\n ⋅ ⋅ ⋅ ⋅ 1.0\n\nThis returns a 5×5 Bidiagonal{Float64}, which can now be passed to other linear algebra functions (e.g. eigensolvers) which will use specialized methods for Bidiagonal types.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.Diagonal", - "page": "Linear Algebra", - "title": "Base.LinAlg.Diagonal", - "category": "type", - "text": "Diagonal(A::AbstractMatrix)\n\nConstructs a matrix from the diagonal of A.\n\nExample\n\njulia> A = [1 2 3; 4 5 6; 7 8 9]\n3×3 Array{Int64,2}:\n 1 2 3\n 4 5 6\n 7 8 9\n\njulia> Diagonal(A)\n3×3 Diagonal{Int64}:\n 1 ⋅ ⋅\n ⋅ 5 ⋅\n ⋅ ⋅ 9\n\n\n\nDiagonal(V::AbstractVector)\n\nConstructs a matrix with V as its diagonal.\n\nExample\n\njulia> V = [1; 2]\n2-element Array{Int64,1}:\n 1\n 2\n\njulia> Diagonal(V)\n2×2 Diagonal{Int64}:\n 1 ⋅\n ⋅ 2\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.Bidiagonal", - "page": "Linear Algebra", - "title": "Base.LinAlg.Bidiagonal", - "category": "type", - "text": "Bidiagonal(dv, ev, isupper::Bool)\n\nConstructs an upper (isupper=true) or lower (isupper=false) bidiagonal matrix using the given diagonal (dv) and off-diagonal (ev) vectors. The result is of type Bidiagonal and provides efficient specialized linear solvers, but may be converted into a regular matrix with convert(Array, _) (or Array(_) for short). ev\'s length must be one less than the length of dv.\n\nExample\n\njulia> dv = [1; 2; 3; 4]\n4-element Array{Int64,1}:\n 1\n 2\n 3\n 4\n\njulia> ev = [7; 8; 9]\n3-element Array{Int64,1}:\n 7\n 8\n 9\n\njulia> Bu = Bidiagonal(dv, ev, true) # ev is on the first superdiagonal\n4×4 Bidiagonal{Int64}:\n 1 7 ⋅ ⋅\n ⋅ 2 8 ⋅\n ⋅ ⋅ 3 9\n ⋅ ⋅ ⋅ 4\n\njulia> Bl = Bidiagonal(dv, ev, false) # ev is on the first subdiagonal\n4×4 Bidiagonal{Int64}:\n 1 ⋅ ⋅ ⋅\n 7 2 ⋅ ⋅\n ⋅ 8 3 ⋅\n ⋅ ⋅ 9 4\n\n\n\nBidiagonal(dv, ev, uplo::Char)\n\nConstructs an upper (uplo=\'U\') or lower (uplo=\'L\') bidiagonal matrix using the given diagonal (dv) and off-diagonal (ev) vectors. The result is of type Bidiagonal and provides efficient specialized linear solvers, but may be converted into a regular matrix with convert(Array, _) (or Array(_) for short). ev\'s length must be one less than the length of dv.\n\nExample\n\njulia> dv = [1; 2; 3; 4]\n4-element Array{Int64,1}:\n 1\n 2\n 3\n 4\n\njulia> ev = [7; 8; 9]\n3-element Array{Int64,1}:\n 7\n 8\n 9\n\njulia> Bu = Bidiagonal(dv, ev, \'U\') #e is on the first superdiagonal\n4×4 Bidiagonal{Int64}:\n 1 7 ⋅ ⋅\n ⋅ 2 8 ⋅\n ⋅ ⋅ 3 9\n ⋅ ⋅ ⋅ 4\n\njulia> Bl = Bidiagonal(dv, ev, \'L\') #e is on the first subdiagonal\n4×4 Bidiagonal{Int64}:\n 1 ⋅ ⋅ ⋅\n 7 2 ⋅ ⋅\n ⋅ 8 3 ⋅\n ⋅ ⋅ 9 4\n\n\n\nBidiagonal(A, isupper::Bool)\n\nConstruct a Bidiagonal matrix from the main diagonal of A and its first super- (if isupper=true) or sub-diagonal (if isupper=false).\n\nExample\n\njulia> A = [1 1 1 1; 2 2 2 2; 3 3 3 3; 4 4 4 4]\n4×4 Array{Int64,2}:\n 1 1 1 1\n 2 2 2 2\n 3 3 3 3\n 4 4 4 4\n\njulia> Bidiagonal(A, true) #contains the main diagonal and first superdiagonal of A\n4×4 Bidiagonal{Int64}:\n 1 1 ⋅ ⋅\n ⋅ 2 2 ⋅\n ⋅ ⋅ 3 3\n ⋅ ⋅ ⋅ 4\n\njulia> Bidiagonal(A, false) #contains the main diagonal and first subdiagonal of A\n4×4 Bidiagonal{Int64}:\n 1 ⋅ ⋅ ⋅\n 2 2 ⋅ ⋅\n ⋅ 3 3 ⋅\n ⋅ ⋅ 4 4\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.SymTridiagonal", - "page": "Linear Algebra", - "title": "Base.LinAlg.SymTridiagonal", - "category": "type", - "text": "SymTridiagonal(dv, ev)\n\nConstruct a symmetric tridiagonal matrix from the diagonal and first sub/super-diagonal, respectively. The result is of type SymTridiagonal and provides efficient specialized eigensolvers, but may be converted into a regular matrix with convert(Array, _) (or Array(_) for short).\n\nExample\n\njulia> dv = [1; 2; 3; 4]\n4-element Array{Int64,1}:\n 1\n 2\n 3\n 4\n\njulia> ev = [7; 8; 9]\n3-element Array{Int64,1}:\n 7\n 8\n 9\n\njulia> SymTridiagonal(dv, ev)\n4×4 SymTridiagonal{Int64}:\n 1 7 ⋅ ⋅\n 7 2 8 ⋅\n ⋅ 8 3 9\n ⋅ ⋅ 9 4\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.Tridiagonal", - "page": "Linear Algebra", - "title": "Base.LinAlg.Tridiagonal", - "category": "type", - "text": "Tridiagonal(dl, d, du)\n\nConstruct a tridiagonal matrix from the first subdiagonal, diagonal, and first superdiagonal, respectively. The result is of type Tridiagonal and provides efficient specialized linear solvers, but may be converted into a regular matrix with convert(Array, _) (or Array(_) for short). The lengths of dl and du must be one less than the length of d.\n\nExample\n\njulia> dl = [1; 2; 3]\n3-element Array{Int64,1}:\n 1\n 2\n 3\n\njulia> du = [4; 5; 6]\n3-element Array{Int64,1}:\n 4\n 5\n 6\n\njulia> d = [7; 8; 9; 0]\n4-element Array{Int64,1}:\n 7\n 8\n 9\n 0\n\njulia> Tridiagonal(dl, d, du)\n4×4 Tridiagonal{Int64}:\n 7 4 ⋅ ⋅\n 1 8 5 ⋅\n ⋅ 2 9 6\n ⋅ ⋅ 3 0\n\n\n\nTridiagonal(A)\n\nreturns a Tridiagonal array based on (abstract) matrix A, using its first lower diagonal, main diagonal, and first upper diagonal.\n\nExample\n\njulia> A = [1 2 3 4; 1 2 3 4; 1 2 3 4; 1 2 3 4]\n4×4 Array{Int64,2}:\n 1 2 3 4\n 1 2 3 4\n 1 2 3 4\n 1 2 3 4\n\njulia> Tridiagonal(A)\n4×4 Tridiagonal{Int64}:\n 1 2 ⋅ ⋅\n 1 2 3 ⋅\n ⋅ 2 3 4\n ⋅ ⋅ 3 4\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.Symmetric", - "page": "Linear Algebra", - "title": "Base.LinAlg.Symmetric", - "category": "type", - "text": "Symmetric(A, uplo=:U)\n\nConstruct a Symmetric view of the upper (if uplo = :U) or lower (if uplo = :L) triangle of the matrix A.\n\nExample\n\njulia> A = [1 0 2 0 3; 0 4 0 5 0; 6 0 7 0 8; 0 9 0 1 0; 2 0 3 0 4]\n5×5 Array{Int64,2}:\n 1 0 2 0 3\n 0 4 0 5 0\n 6 0 7 0 8\n 0 9 0 1 0\n 2 0 3 0 4\n\njulia> Supper = Symmetric(A)\n5×5 Symmetric{Int64,Array{Int64,2}}:\n 1 0 2 0 3\n 0 4 0 5 0\n 2 0 7 0 8\n 0 5 0 1 0\n 3 0 8 0 4\n\njulia> Slower = Symmetric(A, :L)\n5×5 Symmetric{Int64,Array{Int64,2}}:\n 1 0 6 0 2\n 0 4 0 9 0\n 6 0 7 0 3\n 0 9 0 1 0\n 2 0 3 0 4\n\nNote that Supper will not be equal to Slower unless A is itself symmetric (e.g. if A == A.\').\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.Hermitian", - "page": "Linear Algebra", - "title": "Base.LinAlg.Hermitian", - "category": "type", - "text": "Hermitian(A, uplo=:U)\n\nConstruct a Hermitian view of the upper (if uplo = :U) or lower (if uplo = :L) triangle of the matrix A.\n\nExample\n\njulia> A = [1 0 2+2im 0 3-3im; 0 4 0 5 0; 6-6im 0 7 0 8+8im; 0 9 0 1 0; 2+2im 0 3-3im 0 4];\n\njulia> Hupper = Hermitian(A)\n5×5 Hermitian{Complex{Int64},Array{Complex{Int64},2}}:\n 1+0im 0+0im 2+2im 0+0im 3-3im\n 0+0im 4+0im 0+0im 5+0im 0+0im\n 2-2im 0+0im 7+0im 0+0im 8+8im\n 0+0im 5+0im 0+0im 1+0im 0+0im\n 3+3im 0+0im 8-8im 0+0im 4+0im\n\njulia> Hlower = Hermitian(A, :L)\n5×5 Hermitian{Complex{Int64},Array{Complex{Int64},2}}:\n 1+0im 0+0im 6+6im 0+0im 2-2im\n 0+0im 4+0im 0+0im 9+0im 0+0im\n 6-6im 0+0im 7+0im 0+0im 3+3im\n 0+0im 9+0im 0+0im 1+0im 0+0im\n 2+2im 0+0im 3-3im 0+0im 4+0im\n\nNote that Hupper will not be equal to Hlower unless A is itself Hermitian (e.g. if A == A\').\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.LowerTriangular", - "page": "Linear Algebra", - "title": "Base.LinAlg.LowerTriangular", - "category": "type", - "text": "LowerTriangular(A::AbstractMatrix)\n\nConstruct a LowerTriangular view of the the matrix A.\n\nExample\n\njulia> A = [1.0 2.0 3.0; 4.0 5.0 6.0; 7.0 8.0 9.0]\n3×3 Array{Float64,2}:\n 1.0 2.0 3.0\n 4.0 5.0 6.0\n 7.0 8.0 9.0\n\njulia> LowerTriangular(A)\n3×3 LowerTriangular{Float64,Array{Float64,2}}:\n 1.0 ⋅ ⋅\n 4.0 5.0 ⋅\n 7.0 8.0 9.0\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.UpperTriangular", - "page": "Linear Algebra", - "title": "Base.LinAlg.UpperTriangular", - "category": "type", - "text": "UpperTriangular(A::AbstractMatrix)\n\nConstruct an UpperTriangular view of the the matrix A.\n\nExample\n\njulia> A = [1.0 2.0 3.0; 4.0 5.0 6.0; 7.0 8.0 9.0]\n3×3 Array{Float64,2}:\n 1.0 2.0 3.0\n 4.0 5.0 6.0\n 7.0 8.0 9.0\n\njulia> UpperTriangular(A)\n3×3 UpperTriangular{Float64,Array{Float64,2}}:\n 1.0 2.0 3.0\n ⋅ 5.0 6.0\n ⋅ ⋅ 9.0\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.lu", - "page": "Linear Algebra", - "title": "Base.LinAlg.lu", - "category": "function", - "text": "lu(A, pivot=Val{true}) -> L, U, p\n\nCompute the LU factorization of A, such that A[p,:] = L*U. By default, pivoting is used. This can be overridden by passing Val{false} for the second argument.\n\nSee also lufact.\n\nExample\n\njulia> A = [4. 3.; 6. 3.]\n2×2 Array{Float64,2}:\n 4.0 3.0\n 6.0 3.0\n\njulia> L, U, p = lu(A)\n([1.0 0.0; 0.666667 1.0], [6.0 3.0; 0.0 1.0], [2, 1])\n\njulia> A[p, :] == L * U\ntrue\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.lufact", - "page": "Linear Algebra", - "title": "Base.LinAlg.lufact", - "category": "function", - "text": "lufact(A [,pivot=Val{true}]) -> F::LU\n\nCompute the LU factorization of A.\n\nIn most cases, if A is a subtype S of AbstractMatrix{T} with an element type T supporting +, -, * and /, the return type is LU{T,S{T}}. If pivoting is chosen (default) the element type should also support abs and <.\n\nThe individual components of the factorization F can be accessed by indexing:\n\nComponent Description\nF[:L] L (lower triangular) part of LU\nF[:U] U (upper triangular) part of LU\nF[:p] (right) permutation Vector\nF[:P] (right) permutation Matrix\n\nThe relationship between F and A is\n\nF[:L]*F[:U] == A[F[:p], :]\n\nF further supports the following functions:\n\nSupported function LU LU{T,Tridiagonal{T}}\n/ ✓ \n\\ ✓ ✓\ncond ✓ \ninv ✓ ✓\ndet ✓ ✓\nlogdet ✓ ✓\nlogabsdet ✓ ✓\nsize ✓ ✓\n\nExample\n\njulia> A = [4 3; 6 3]\n2×2 Array{Int64,2}:\n 4 3\n 6 3\n\njulia> F = lufact(A)\nBase.LinAlg.LU{Float64,Array{Float64,2}} with factors L and U:\n[1.0 0.0; 1.5 1.0]\n[4.0 3.0; 0.0 -1.5]\n\njulia> F[:L] * F[:U] == A[F[:p], :]\ntrue\n\n\n\nlufact(A::SparseMatrixCSC) -> F::UmfpackLU\n\nCompute the LU factorization of a sparse matrix A.\n\nFor sparse A with real or complex element type, the return type of F is UmfpackLU{Tv, Ti}, with Tv = Float64 or Complex128 respectively and Ti is an integer type (Int32 or Int64).\n\nThe individual components of the factorization F can be accessed by indexing:\n\nComponent Description\nF[:L] L (lower triangular) part of LU\nF[:U] U (upper triangular) part of LU\nF[:p] right permutation Vector\nF[:q] left permutation Vector\nF[:Rs] Vector of scaling factors\nF[:(:)] (L,U,p,q,Rs) components\n\nThe relation between F and A is\n\nF[:L]*F[:U] == (F[:Rs] .* A)[F[:p], F[:q]]\n\nF further supports the following functions:\n\n\\\ncond\ndet\n\nnote: Note\nlufact(A::SparseMatrixCSC) uses the UMFPACK library that is part of SuiteSparse. As this library only supports sparse matrices with Float64 or Complex128 elements, lufact converts A into a copy that is of type SparseMatrixCSC{Float64} or SparseMatrixCSC{Complex128} as appropriate.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.lufact!", - "page": "Linear Algebra", - "title": "Base.LinAlg.lufact!", - "category": "function", - "text": "lufact!(A, pivot=Val{true}) -> LU\n\nlufact! is the same as lufact, but saves space by overwriting the input A, instead of creating a copy. An InexactError exception is thrown if the factorization produces a number not representable by the element type of A, e.g. for integer types.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.chol", - "page": "Linear Algebra", - "title": "Base.LinAlg.chol", - "category": "function", - "text": "chol(A) -> U\n\nCompute the Cholesky factorization of a positive definite matrix A and return the UpperTriangular matrix U such that A = U\'U.\n\nExample\n\njulia> A = [1. 2.; 2. 50.]\n2×2 Array{Float64,2}:\n 1.0 2.0\n 2.0 50.0\n\njulia> U = chol(A)\n2×2 UpperTriangular{Float64,Array{Float64,2}}:\n 1.0 2.0\n ⋅ 6.78233\n\njulia> U\'U\n2×2 Array{Float64,2}:\n 1.0 2.0\n 2.0 50.0\n\n\n\nchol(x::Number) -> y\n\nCompute the square root of a non-negative number x.\n\nExample\n\njulia> chol(16)\n4.0\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.cholfact", - "page": "Linear Algebra", - "title": "Base.LinAlg.cholfact", - "category": "function", - "text": "cholfact(A, [uplo::Symbol,] Val{false}) -> Cholesky\n\nCompute the Cholesky factorization of a dense symmetric positive definite matrix A and return a Cholesky factorization. The matrix A can either be a Symmetric or Hermitian StridedMatrix or a perfectly symmetric or Hermitian StridedMatrix. In the latter case, the optional argument uplo may be :L for using the lower part or :U for the upper part of A. The default is to use :U. The triangular Cholesky factor can be obtained from the factorization F with: F[:L] and F[:U]. The following functions are available for Cholesky objects: size, \\, inv, and det. A PosDefException exception is thrown in case the matrix is not positive definite.\n\nExample\n\njulia> A = [4. 12. -16.; 12. 37. -43.; -16. -43. 98.]\n3×3 Array{Float64,2}:\n 4.0 12.0 -16.0\n 12.0 37.0 -43.0\n -16.0 -43.0 98.0\n\njulia> C = cholfact(A)\nBase.LinAlg.Cholesky{Float64,Array{Float64,2}} with factor:\n[2.0 6.0 -8.0; 0.0 1.0 5.0; 0.0 0.0 3.0]\n\njulia> C[:U]\n3×3 UpperTriangular{Float64,Array{Float64,2}}:\n 2.0 6.0 -8.0\n ⋅ 1.0 5.0\n ⋅ ⋅ 3.0\n\njulia> C[:L]\n3×3 LowerTriangular{Float64,Array{Float64,2}}:\n 2.0 ⋅ ⋅\n 6.0 1.0 ⋅\n -8.0 5.0 3.0\n\njulia> C[:L] * C[:U] == A\ntrue\n\n\n\ncholfact(A, [uplo::Symbol,] Val{true}; tol = 0.0) -> CholeskyPivoted\n\nCompute the pivoted Cholesky factorization of a dense symmetric positive semi-definite matrix A and return a CholeskyPivoted factorization. The matrix A can either be a Symmetric or Hermitian StridedMatrix or a perfectly symmetric or Hermitian StridedMatrix. In the latter case, the optional argument uplo may be :L for using the lower part or :U for the upper part of A. The default is to use :U. The triangular Cholesky factor can be obtained from the factorization F with: F[:L] and F[:U]. The following functions are available for PivotedCholesky objects: size, \\, inv, det, and rank. The argument tol determines the tolerance for determining the rank. For negative values, the tolerance is the machine precision.\n\n\n\ncholfact(A; shift = 0.0, perm = Int[]) -> CHOLMOD.Factor\n\nCompute the Cholesky factorization of a sparse positive definite matrix A. A must be a SparseMatrixCSC or a Symmetric/Hermitian view of a SparseMatrixCSC. Note that even if A doesn\'t have the type tag, it must still be symmetric or Hermitian. A fill-reducing permutation is used. F = cholfact(A) is most frequently used to solve systems of equations with F\\b, but also the methods diag, det, and logdet are defined for F. You can also extract individual factors from F, using F[:L]. However, since pivoting is on by default, the factorization is internally represented as A == P\'*L*L\'*P with a permutation matrix P; using just L without accounting for P will give incorrect answers. To include the effects of permutation, it\'s typically preferable to extract \"combined\" factors like PtL = F[:PtL] (the equivalent of P\'*L) and LtP = F[:UP] (the equivalent of L\'*P).\n\nSetting the optional shift keyword argument computes the factorization of A+shift*I instead of A. If the perm argument is nonempty, it should be a permutation of 1:size(A,1) giving the ordering to use (instead of CHOLMOD\'s default AMD ordering).\n\nnote: Note\nThis method uses the CHOLMOD library from SuiteSparse, which only supports doubles or complex doubles. Input matrices not of those element types will be converted to SparseMatrixCSC{Float64} or SparseMatrixCSC{Complex128} as appropriate.Many other functions from CHOLMOD are wrapped but not exported from the Base.SparseArrays.CHOLMOD module.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.cholfact!", - "page": "Linear Algebra", - "title": "Base.LinAlg.cholfact!", - "category": "function", - "text": "cholfact!(A, [uplo::Symbol,] Val{false}) -> Cholesky\n\nThe same as cholfact, but saves space by overwriting the input A, instead of creating a copy. An InexactError exception is thrown if the factorization produces a number not representable by the element type of A, e.g. for integer types.\n\nExample\n\njulia> A = [1 2; 2 50]\n2×2 Array{Int64,2}:\n 1 2\n 2 50\n\njulia> cholfact!(A)\nERROR: InexactError()\n\n\n\ncholfact!(A, [uplo::Symbol,] Val{true}; tol = 0.0) -> CholeskyPivoted\n\nThe same as cholfact, but saves space by overwriting the input A, instead of creating a copy. An InexactError exception is thrown if the factorization produces a number not representable by the element type of A, e.g. for integer types.\n\n\n\ncholfact!(F::Factor, A; shift = 0.0) -> CHOLMOD.Factor\n\nCompute the Cholesky (LL) factorization of A, reusing the symbolic factorization F. A must be a SparseMatrixCSC or a Symmetric/ Hermitian view of a SparseMatrixCSC. Note that even if A doesn\'t have the type tag, it must still be symmetric or Hermitian.\n\nSee also cholfact.\n\nnote: Note\nThis method uses the CHOLMOD library from SuiteSparse, which only supports doubles or complex doubles. Input matrices not of those element types will be converted to SparseMatrixCSC{Float64} or SparseMatrixCSC{Complex128} as appropriate.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.lowrankupdate", - "page": "Linear Algebra", - "title": "Base.LinAlg.lowrankupdate", - "category": "function", - "text": "lowrankupdate(C::Cholesky, v::StridedVector) -> CC::Cholesky\n\nUpdate a Cholesky factorization C with the vector v. If A = C[:U]\'C[:U] then CC = cholfact(C[:U]\'C[:U] + v*v\') but the computation of CC only uses O(n^2) operations.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.lowrankdowndate", - "page": "Linear Algebra", - "title": "Base.LinAlg.lowrankdowndate", - "category": "function", - "text": "lowrankdowndate(C::Cholesky, v::StridedVector) -> CC::Cholesky\n\nDowndate a Cholesky factorization C with the vector v. If A = C[:U]\'C[:U] then CC = cholfact(C[:U]\'C[:U] - v*v\') but the computation of CC only uses O(n^2) operations.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.lowrankupdate!", - "page": "Linear Algebra", - "title": "Base.LinAlg.lowrankupdate!", - "category": "function", - "text": "lowrankupdate!(C::Cholesky, v::StridedVector) -> CC::Cholesky\n\nUpdate a Cholesky factorization C with the vector v. If A = C[:U]\'C[:U] then CC = cholfact(C[:U]\'C[:U] + v*v\') but the computation of CC only uses O(n^2) operations. The input factorization C is updated in place such that on exit C == CC. The vector v is destroyed during the computation.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.lowrankdowndate!", - "page": "Linear Algebra", - "title": "Base.LinAlg.lowrankdowndate!", - "category": "function", - "text": "lowrankdowndate!(C::Cholesky, v::StridedVector) -> CC::Cholesky\n\nDowndate a Cholesky factorization C with the vector v. If A = C[:U]\'C[:U] then CC = cholfact(C[:U]\'C[:U] - v*v\') but the computation of CC only uses O(n^2) operations. The input factorization C is updated in place such that on exit C == CC. The vector v is destroyed during the computation.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.ldltfact", - "page": "Linear Algebra", - "title": "Base.LinAlg.ldltfact", - "category": "function", - "text": "ldltfact(S::SymTridiagonal) -> LDLt\n\nCompute an LDLt factorization of a real symmetric tridiagonal matrix such that A = L*Diagonal(d)*L\' where L is a unit lower triangular matrix and d is a vector. The main use of an LDLt factorization F = ldltfact(A) is to solve the linear system of equations Ax = b with F\\b.\n\n\n\nldltfact(A; shift = 0.0, perm=Int[]) -> CHOLMOD.Factor\n\nCompute the LDL factorization of a sparse matrix A. A must be a SparseMatrixCSC or a Symmetric/Hermitian view of a SparseMatrixCSC. Note that even if A doesn\'t have the type tag, it must still be symmetric or Hermitian. A fill-reducing permutation is used. F = ldltfact(A) is most frequently used to solve systems of equations A*x = b with F\\b. The returned factorization object F also supports the methods diag, det, logdet, and inv. You can extract individual factors from F using F[:L]. However, since pivoting is on by default, the factorization is internally represented as A == P\'*L*D*L\'*P with a permutation matrix P; using just L without accounting for P will give incorrect answers. To include the effects of permutation, it is typically preferable to extract \"combined\" factors like PtL = F[:PtL] (the equivalent of P\'*L) and LtP = F[:UP] (the equivalent of L\'*P). The complete list of supported factors is :L, :PtL, :D, :UP, :U, :LD, :DU, :PtLD, :DUP.\n\nSetting the optional shift keyword argument computes the factorization of A+shift*I instead of A. If the perm argument is nonempty, it should be a permutation of 1:size(A,1) giving the ordering to use (instead of CHOLMOD\'s default AMD ordering).\n\nnote: Note\nThis method uses the CHOLMOD library from SuiteSparse, which only supports doubles or complex doubles. Input matrices not of those element types will be converted to SparseMatrixCSC{Float64} or SparseMatrixCSC{Complex128} as appropriate.Many other functions from CHOLMOD are wrapped but not exported from the Base.SparseArrays.CHOLMOD module.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.ldltfact!", - "page": "Linear Algebra", - "title": "Base.LinAlg.ldltfact!", - "category": "function", - "text": "ldltfact!(S::SymTridiagonal) -> LDLt\n\nSame as ldltfact, but saves space by overwriting the input A, instead of creating a copy.\n\n\n\nldltfact!(F::Factor, A; shift = 0.0) -> CHOLMOD.Factor\n\nCompute the LDL factorization of A, reusing the symbolic factorization F. A must be a SparseMatrixCSC or a Symmetric/Hermitian view of a SparseMatrixCSC. Note that even if A doesn\'t have the type tag, it must still be symmetric or Hermitian.\n\nSee also ldltfact.\n\nnote: Note\nThis method uses the CHOLMOD library from SuiteSparse, which only supports doubles or complex doubles. Input matrices not of those element types will be converted to SparseMatrixCSC{Float64} or SparseMatrixCSC{Complex128} as appropriate.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.qr", - "page": "Linear Algebra", - "title": "Base.LinAlg.qr", - "category": "function", - "text": "qr(A, pivot=Val{false}; thin::Bool=true) -> Q, R, [p]\n\nCompute the (pivoted) QR factorization of A such that either A = Q*R or A[:,p] = Q*R. Also see qrfact. The default is to compute a thin factorization. Note that R is not extended with zeros when the full Q is requested.\n\n\n\nqr(v::AbstractVector) -> w, r\n\nComputes the polar decomposition of a vector. Returns w, a unit vector in the direction of v, and r, the norm of v.\n\nSee also normalize, normalize!, and LinAlg.qr!.\n\nExample\n\njulia> v = [1; 2]\n2-element Array{Int64,1}:\n 1\n 2\n\njulia> w, r = qr(v)\n([0.447214, 0.894427], 2.23606797749979)\n\njulia> w*r == v\ntrue\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.qr!", - "page": "Linear Algebra", - "title": "Base.LinAlg.qr!", - "category": "function", - "text": "LinAlg.qr!(v::AbstractVector) -> w, r\n\nComputes the polar decomposition of a vector. Instead of returning a new vector as qr(v::AbstractVector), this function mutates the input vector v in place. Returns w, a unit vector in the direction of v (this is a mutation of v), and r, the norm of v.\n\nSee also normalize, normalize!, and qr.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.qrfact", - "page": "Linear Algebra", - "title": "Base.LinAlg.qrfact", - "category": "function", - "text": "qrfact(A) -> SPQR.Factorization\n\nCompute the QR factorization of a sparse matrix A. A fill-reducing permutation is used. The main application of this type is to solve least squares problems with \\. The function calls the C library SPQR and a few additional functions from the library are wrapped but not exported.\n\n\n\nqrfact(A, pivot=Val{false}) -> F\n\nCompute the QR factorization of the matrix A: an orthogonal (or unitary if A is complex-valued) matrix Q, and an upper triangular matrix R such that\n\nA = Q R\n\nThe returned object F stores the factorization in a packed format:\n\nif pivot == Val{true} then F is a QRPivoted object,\notherwise if the element type of A is a BLAS type (Float32, Float64, Complex64 or Complex128), then F is a QRCompactWY object,\notherwise F is a QR object.\n\nThe individual components of the factorization F can be accessed by indexing with a symbol:\n\nF[:Q]: the orthogonal/unitary matrix Q\nF[:R]: the upper triangular matrix R\nF[:p]: the permutation vector of the pivot (QRPivoted only)\nF[:P]: the permutation matrix of the pivot (QRPivoted only)\n\nThe following functions are available for the QR objects: inv, size, and \\. When A is rectangular, \\ will return a least squares solution and if the solution is not unique, the one with smallest norm is returned.\n\nMultiplication with respect to either thin or full Q is allowed, i.e. both F[:Q]*F[:R] and F[:Q]*A are supported. A Q matrix can be converted into a regular matrix with full which has a named argument thin.\n\nExample\n\njulia> A = [3.0 -6.0; 4.0 -8.0; 0.0 1.0]\n3×2 Array{Float64,2}:\n 3.0 -6.0\n 4.0 -8.0\n 0.0 1.0\n\njulia> F = qrfact(A)\nBase.LinAlg.QRCompactWY{Float64,Array{Float64,2}} with factors Q and R:\n[-0.6 0.0 0.8; -0.8 0.0 -0.6; 0.0 -1.0 0.0]\n[-5.0 10.0; 0.0 -1.0]\n\njulia> F[:Q] * F[:R] == A\ntrue\n\nnote: Note\nqrfact returns multiple types because LAPACK uses several representations that minimize the memory storage requirements of products of Householder elementary reflectors, so that the Q and R matrices can be stored compactly rather as two separate dense matrices.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.qrfact!", - "page": "Linear Algebra", - "title": "Base.LinAlg.qrfact!", - "category": "function", - "text": "qrfact!(A, pivot=Val{false})\n\nqrfact! is the same as qrfact when A is a subtype of StridedMatrix, but saves space by overwriting the input A, instead of creating a copy. An InexactError exception is thrown if the factorization produces a number not representable by the element type of A, e.g. for integer types.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.QR", - "page": "Linear Algebra", - "title": "Base.LinAlg.QR", - "category": "type", - "text": "QR <: Factorization\n\nA QR matrix factorization stored in a packed format, typically obtained from qrfact. If A is an m×n matrix, then\n\nA = Q R\n\nwhere Q is an orthogonal/unitary matrix and R is upper triangular. The matrix Q is stored as a sequence of Householder reflectors v_i and coefficients tau_i where:\n\nQ = prod_i=1^min(mn) (I - tau_i v_i v_i^T)\n\nThe object has two fields:\n\nfactors is an m×n matrix.\nThe upper triangular part contains the elements of R, that is R = triu(F.factors) for a QR object F.\nThe subdiagonal part contains the reflectors v_i stored in a packed format where v_i is the ith column of the matrix V = eye(m,n) + tril(F.factors,-1).\nτ is a vector of length min(m,n) containing the coefficients au_i.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.QRCompactWY", - "page": "Linear Algebra", - "title": "Base.LinAlg.QRCompactWY", - "category": "type", - "text": "QRCompactWY <: Factorization\n\nA QR matrix factorization stored in a compact blocked format, typically obtained from qrfact. If A is an m×n matrix, then\n\nA = Q R\n\nwhere Q is an orthogonal/unitary matrix and R is upper triangular. It is similar to the QR format except that the orthogonal/unitary matrix Q is stored in Compact WY format [Schreiber1989], as a lower trapezoidal matrix V and an upper triangular matrix T where\n\nQ = prod_i=1^min(mn) (I - tau_i v_i v_i^T) = I - V T V^T\n\nsuch that v_i is the ith column of V, and au_i is the ith diagonal element of T.\n\nThe object has two fields:\n\nfactors, as in the QR type, is an m×n matrix.\nThe upper triangular part contains the elements of R, that is R = triu(F.factors) for a QR object F.\nThe subdiagonal part contains the reflectors v_i stored in a packed format such that V = eye(m,n) + tril(F.factors,-1).\nT is a square matrix with min(m,n) columns, whose upper triangular part gives the matrix T above (the subdiagonal elements are ignored).\n\nnote: Note\nThis format should not to be confused with the older WY representation [Bischof1987].\n\n[Bischof1987]: C Bischof and C Van Loan, \"The WY representation for products of Householder matrices\", SIAM J Sci Stat Comput 8 (1987), s2-s13. doi:10.1137/0908009\n\n[Schreiber1989]: R Schreiber and C Van Loan, \"A storage-efficient WY representation for products of Householder transformations\", SIAM J Sci Stat Comput 10 (1989), 53-57. doi:10.1137/0910005\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.QRPivoted", - "page": "Linear Algebra", - "title": "Base.LinAlg.QRPivoted", - "category": "type", - "text": "QRPivoted <: Factorization\n\nA QR matrix factorization with column pivoting in a packed format, typically obtained from qrfact. If A is an m×n matrix, then\n\nA P = Q R\n\nwhere P is a permutation matrix, Q is an orthogonal/unitary matrix and R is upper triangular. The matrix Q is stored as a sequence of Householder reflectors:\n\nQ = prod_i=1^min(mn) (I - tau_i v_i v_i^T)\n\nThe object has three fields:\n\nfactors is an m×n matrix.\nThe upper triangular part contains the elements of R, that is R = triu(F.factors) for a QR object F.\nThe subdiagonal part contains the reflectors v_i stored in a packed format where v_i is the ith column of the matrix V = eye(m,n) + tril(F.factors,-1).\nτ is a vector of length min(m,n) containing the coefficients au_i.\njpvt is an integer vector of length n corresponding to the permutation P.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.lqfact!", - "page": "Linear Algebra", - "title": "Base.LinAlg.lqfact!", - "category": "function", - "text": "lqfact!(A) -> LQ\n\nCompute the LQ factorization of A, using the input matrix as a workspace. See also lq.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.lqfact", - "page": "Linear Algebra", - "title": "Base.LinAlg.lqfact", - "category": "function", - "text": "lqfact(A) -> LQ\n\nCompute the LQ factorization of A. See also lq.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.lq", - "page": "Linear Algebra", - "title": "Base.LinAlg.lq", - "category": "function", - "text": "lq(A; [thin=true]) -> L, Q\n\nPerform an LQ factorization of A such that A = L*Q. The default is to compute a thin factorization. The LQ factorization is the QR factorization of A.\'. L is not extended with zeros if the full Q is requested.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.bkfact", - "page": "Linear Algebra", - "title": "Base.LinAlg.bkfact", - "category": "function", - "text": "bkfact(A, uplo::Symbol=:U, symmetric::Bool=issymmetric(A), rook::Bool=false) -> BunchKaufman\n\nCompute the Bunch-Kaufman [Bunch1977] factorization of a symmetric or Hermitian matrix A and return a BunchKaufman object. uplo indicates which triangle of matrix A to reference. If symmetric is true, A is assumed to be symmetric. If symmetric is false, A is assumed to be Hermitian. If rook is true, rook pivoting is used. If rook is false, rook pivoting is not used. The following functions are available for BunchKaufman objects: size, \\, inv, issymmetric, ishermitian.\n\n[Bunch1977]: J R Bunch and L Kaufman, Some stable methods for calculating inertia and solving symmetric linear systems, Mathematics of Computation 31:137 (1977), 163-179. url.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.bkfact!", - "page": "Linear Algebra", - "title": "Base.LinAlg.bkfact!", - "category": "function", - "text": "bkfact!(A, uplo::Symbol=:U, symmetric::Bool=issymmetric(A), rook::Bool=false) -> BunchKaufman\n\nbkfact! is the same as bkfact, but saves space by overwriting the input A, instead of creating a copy.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.eig", - "page": "Linear Algebra", - "title": "Base.LinAlg.eig", - "category": "function", - "text": "eig(A::Union{SymTridiagonal, Hermitian, Symmetric}, irange::UnitRange) -> D, V\neig(A::Union{SymTridiagonal, Hermitian, Symmetric}, vl::Real, vu::Real) -> D, V\neig(A, permute::Bool=true, scale::Bool=true) -> D, V\n\nComputes eigenvalues (D) and eigenvectors (V) of A. See eigfact for details on the irange, vl, and vu arguments (for SymTridiagonal, Hermitian, and Symmetric matrices) and the permute and scale keyword arguments. The eigenvectors are returned columnwise.\n\nExample\n\njulia> eig([1.0 0.0 0.0; 0.0 3.0 0.0; 0.0 0.0 18.0])\n([1.0, 3.0, 18.0], [1.0 0.0 0.0; 0.0 1.0 0.0; 0.0 0.0 1.0])\n\neig is a wrapper around eigfact, extracting all parts of the factorization to a tuple; where possible, using eigfact is recommended.\n\n\n\neig(A, B) -> D, V\n\nComputes generalized eigenvalues (D) and vectors (V) of A with respect to B.\n\neig is a wrapper around eigfact, extracting all parts of the factorization to a tuple; where possible, using eigfact is recommended.\n\nExample\n\njulia> A = [1 0; 0 -1]\n2×2 Array{Int64,2}:\n 1 0\n 0 -1\n\njulia> B = [0 1; 1 0]\n2×2 Array{Int64,2}:\n 0 1\n 1 0\n\njulia> eig(A, B)\n(Complex{Float64}[0.0+1.0im, 0.0-1.0im], Complex{Float64}[0.0-1.0im 0.0+1.0im; -1.0-0.0im -1.0+0.0im])\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.eigvals", - "page": "Linear Algebra", - "title": "Base.LinAlg.eigvals", - "category": "function", - "text": "eigvals(A; permute::Bool=true, scale::Bool=true) -> values\n\nReturns the eigenvalues of A.\n\nFor general non-symmetric matrices it is possible to specify how the matrix is balanced before the eigenvalue calculation. The option permute=true permutes the matrix to become closer to upper triangular, and scale=true scales the matrix by its diagonal elements to make rows and columns more equal in norm. The default is true for both options.\n\n\n\neigvals(A, B) -> values\n\nComputes the generalized eigenvalues of A and B.\n\nExample\n\njulia> A = [1 0; 0 -1]\n2×2 Array{Int64,2}:\n 1 0\n 0 -1\n\njulia> B = [0 1; 1 0]\n2×2 Array{Int64,2}:\n 0 1\n 1 0\n\njulia> eigvals(A,B)\n2-element Array{Complex{Float64},1}:\n 0.0+1.0im\n 0.0-1.0im\n\n\n\neigvals(A::Union{SymTridiagonal, Hermitian, Symmetric}, irange::UnitRange) -> values\n\nReturns the eigenvalues of A. It is possible to calculate only a subset of the eigenvalues by specifying a UnitRange irange covering indices of the sorted eigenvalues, e.g. the 2nd to 8th eigenvalues.\n\njulia> A = SymTridiagonal([1.; 2.; 1.], [2.; 3.])\n3×3 SymTridiagonal{Float64}:\n 1.0 2.0 ⋅\n 2.0 2.0 3.0\n ⋅ 3.0 1.0\n\njulia> eigvals(A, 2:2)\n1-element Array{Float64,1}:\n 1.0\n\njulia> eigvals(A)\n3-element Array{Float64,1}:\n -2.14005\n 1.0\n 5.14005\n\n\n\neigvals(A::Union{SymTridiagonal, Hermitian, Symmetric}, vl::Real, vu::Real) -> values\n\nReturns the eigenvalues of A. It is possible to calculate only a subset of the eigenvalues by specifying a pair vl and vu for the lower and upper boundaries of the eigenvalues.\n\njulia> A = SymTridiagonal([1.; 2.; 1.], [2.; 3.])\n3×3 SymTridiagonal{Float64}:\n 1.0 2.0 ⋅\n 2.0 2.0 3.0\n ⋅ 3.0 1.0\n\njulia> eigvals(A, -1, 2)\n1-element Array{Float64,1}:\n 1.0\n\njulia> eigvals(A)\n3-element Array{Float64,1}:\n -2.14005\n 1.0\n 5.14005\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.eigvals!", - "page": "Linear Algebra", - "title": "Base.LinAlg.eigvals!", - "category": "function", - "text": "eigvals!(A; permute::Bool=true, scale::Bool=true) -> values\n\nSame as eigvals, but saves space by overwriting the input A, instead of creating a copy. The option permute=true permutes the matrix to become closer to upper triangular, and scale=true scales the matrix by its diagonal elements to make rows and columns more equal in norm.\n\n\n\neigvals!(A, B) -> values\n\nSame as eigvals, but saves space by overwriting the input A (and B), instead of creating copies.\n\n\n\neigvals!(A::Union{SymTridiagonal, Hermitian, Symmetric}, irange::UnitRange) -> values\n\nSame as eigvals, but saves space by overwriting the input A, instead of creating a copy. irange is a range of eigenvalue indices to search for - for instance, the 2nd to 8th eigenvalues.\n\n\n\neigvals!(A::Union{SymTridiagonal, Hermitian, Symmetric}, vl::Real, vu::Real) -> values\n\nSame as eigvals, but saves space by overwriting the input A, instead of creating a copy. vl is the lower bound of the interval to search for eigenvalues, and vu is the upper bound.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.eigmax", - "page": "Linear Algebra", - "title": "Base.LinAlg.eigmax", - "category": "function", - "text": "eigmax(A; permute::Bool=true, scale::Bool=true)\n\nReturns the largest eigenvalue of A. The option permute=true permutes the matrix to become closer to upper triangular, and scale=true scales the matrix by its diagonal elements to make rows and columns more equal in norm. Note that if the eigenvalues of A are complex, this method will fail, since complex numbers cannot be sorted.\n\nExample\n\njulia> A = [0 im; -im 0]\n2×2 Array{Complex{Int64},2}:\n 0+0im 0+1im\n 0-1im 0+0im\n\njulia> eigmax(A)\n1.0\n\njulia> A = [0 im; -1 0]\n2×2 Array{Complex{Int64},2}:\n 0+0im 0+1im\n -1+0im 0+0im\n\njulia> eigmax(A)\nERROR: DomainError:\nStacktrace:\n [1] #eigmax#46(::Bool, ::Bool, ::Function, ::Array{Complex{Int64},2}) at ./linalg/eigen.jl:238\n [2] eigmax(::Array{Complex{Int64},2}) at ./linalg/eigen.jl:236\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.eigmin", - "page": "Linear Algebra", - "title": "Base.LinAlg.eigmin", - "category": "function", - "text": "eigmin(A; permute::Bool=true, scale::Bool=true)\n\nReturns the smallest eigenvalue of A. The option permute=true permutes the matrix to become closer to upper triangular, and scale=true scales the matrix by its diagonal elements to make rows and columns more equal in norm. Note that if the eigenvalues of A are complex, this method will fail, since complex numbers cannot be sorted.\n\nExample\n\njulia> A = [0 im; -im 0]\n2×2 Array{Complex{Int64},2}:\n 0+0im 0+1im\n 0-1im 0+0im\n\njulia> eigmin(A)\n-1.0\n\njulia> A = [0 im; -1 0]\n2×2 Array{Complex{Int64},2}:\n 0+0im 0+1im\n -1+0im 0+0im\n\njulia> eigmin(A)\nERROR: DomainError:\nStacktrace:\n [1] #eigmin#47(::Bool, ::Bool, ::Function, ::Array{Complex{Int64},2}) at ./linalg/eigen.jl:280\n [2] eigmin(::Array{Complex{Int64},2}) at ./linalg/eigen.jl:278\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.eigvecs", - "page": "Linear Algebra", - "title": "Base.LinAlg.eigvecs", - "category": "function", - "text": "eigvecs(A::SymTridiagonal[, eigvals]) -> Matrix\n\nReturns a matrix M whose columns are the eigenvectors of A. (The kth eigenvector can be obtained from the slice M[:, k].)\n\nIf the optional vector of eigenvalues eigvals is specified, eigvecs returns the specific corresponding eigenvectors.\n\nExample\n\njulia> A = SymTridiagonal([1.; 2.; 1.], [2.; 3.])\n3×3 SymTridiagonal{Float64}:\n 1.0 2.0 ⋅\n 2.0 2.0 3.0\n ⋅ 3.0 1.0\n\njulia> eigvals(A)\n3-element Array{Float64,1}:\n -2.14005\n 1.0\n 5.14005\n\njulia> eigvecs(A)\n3×3 Array{Float64,2}:\n 0.418304 -0.83205 0.364299\n -0.656749 -7.39009e-16 0.754109\n 0.627457 0.5547 0.546448\n\njulia> eigvecs(A, [1.])\n3×1 Array{Float64,2}:\n 0.83205\n 4.26351e-17\n -0.5547\n\n\n\neigvecs(A; permute::Bool=true, scale::Bool=true) -> Matrix\n\nReturns a matrix M whose columns are the eigenvectors of A. (The kth eigenvector can be obtained from the slice M[:, k].) The permute and scale keywords are the same as for eigfact.\n\nExample\n\njulia> eigvecs([1.0 0.0 0.0; 0.0 3.0 0.0; 0.0 0.0 18.0])\n3×3 Array{Float64,2}:\n 1.0 0.0 0.0\n 0.0 1.0 0.0\n 0.0 0.0 1.0\n\n\n\neigvecs(A, B) -> Matrix\n\nReturns a matrix M whose columns are the generalized eigenvectors of A and B. (The kth eigenvector can be obtained from the slice M[:, k].)\n\nExample\n\njulia> A = [1 0; 0 -1]\n2×2 Array{Int64,2}:\n 1 0\n 0 -1\n\njulia> B = [0 1; 1 0]\n2×2 Array{Int64,2}:\n 0 1\n 1 0\n\njulia> eigvecs(A, B)\n2×2 Array{Complex{Float64},2}:\n 0.0-1.0im 0.0+1.0im\n -1.0-0.0im -1.0+0.0im\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.eigfact", - "page": "Linear Algebra", - "title": "Base.LinAlg.eigfact", - "category": "function", - "text": "eigfact(A; permute::Bool=true, scale::Bool=true) -> Eigen\n\nComputes the eigenvalue decomposition of A, returning an Eigen factorization object F which contains the eigenvalues in F[:values] and the eigenvectors in the columns of the matrix F[:vectors]. (The kth eigenvector can be obtained from the slice F[:vectors][:, k].)\n\nThe following functions are available for Eigen objects: inv, det, and isposdef.\n\nFor general nonsymmetric matrices it is possible to specify how the matrix is balanced before the eigenvector calculation. The option permute=true permutes the matrix to become closer to upper triangular, and scale=true scales the matrix by its diagonal elements to make rows and columns more equal in norm. The default is true for both options.\n\nExample\n\njulia> F = eigfact([1.0 0.0 0.0; 0.0 3.0 0.0; 0.0 0.0 18.0])\nBase.LinAlg.Eigen{Float64,Float64,Array{Float64,2},Array{Float64,1}}([1.0, 3.0, 18.0], [1.0 0.0 0.0; 0.0 1.0 0.0; 0.0 0.0 1.0])\n\njulia> F[:values]\n3-element Array{Float64,1}:\n 1.0\n 3.0\n 18.0\n\njulia> F[:vectors]\n3×3 Array{Float64,2}:\n 1.0 0.0 0.0\n 0.0 1.0 0.0\n 0.0 0.0 1.0\n\n\n\neigfact(A, B) -> GeneralizedEigen\n\nComputes the generalized eigenvalue decomposition of A and B, returning a GeneralizedEigen factorization object F which contains the generalized eigenvalues in F[:values] and the generalized eigenvectors in the columns of the matrix F[:vectors]. (The kth generalized eigenvector can be obtained from the slice F[:vectors][:, k].)\n\n\n\neigfact(A::Union{SymTridiagonal, Hermitian, Symmetric}, irange::UnitRange) -> Eigen\n\nComputes the eigenvalue decomposition of A, returning an Eigen factorization object F which contains the eigenvalues in F[:values] and the eigenvectors in the columns of the matrix F[:vectors]. (The kth eigenvector can be obtained from the slice F[:vectors][:, k].)\n\nThe following functions are available for Eigen objects: inv, det, and isposdef.\n\nThe UnitRange irange specifies indices of the sorted eigenvalues to search for.\n\nnote: Note\nIf irange is not 1:n, where n is the dimension of A, then the returned factorization will be a truncated factorization.\n\n\n\neigfact(A::Union{SymTridiagonal, Hermitian, Symmetric}, vl::Real, vu::Real) -> Eigen\n\nComputes the eigenvalue decomposition of A, returning an Eigen factorization object F which contains the eigenvalues in F[:values] and the eigenvectors in the columns of the matrix F[:vectors]. (The kth eigenvector can be obtained from the slice F[:vectors][:, k].)\n\nThe following functions are available for Eigen objects: inv, det, and isposdef.\n\nvl is the lower bound of the window of eigenvalues to search for, and vu is the upper bound.\n\nnote: Note\nIf [vl, vu] does not contain all eigenvalues of A, then the returned factorization will be a truncated factorization.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.eigfact!", - "page": "Linear Algebra", - "title": "Base.LinAlg.eigfact!", - "category": "function", - "text": "eigfact!(A, [B])\n\nSame as eigfact, but saves space by overwriting the input A (and B), instead of creating a copy.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.hessfact", - "page": "Linear Algebra", - "title": "Base.LinAlg.hessfact", - "category": "function", - "text": "hessfact(A) -> Hessenberg\n\nCompute the Hessenberg decomposition of A and return a Hessenberg object. If F is the factorization object, the unitary matrix can be accessed with F[:Q] and the Hessenberg matrix with F[:H]. When Q is extracted, the resulting type is the HessenbergQ object, and may be converted to a regular matrix with convert(Array, _) (or Array(_) for short).\n\nExample\n\njulia> A = [4. 9. 7.; 4. 4. 1.; 4. 3. 2.]\n3×3 Array{Float64,2}:\n 4.0 9.0 7.0\n 4.0 4.0 1.0\n 4.0 3.0 2.0\n\njulia> F = hessfact(A);\n\njulia> F[:Q] * F[:H] * F[:Q]\'\n3×3 Array{Float64,2}:\n 4.0 9.0 7.0\n 4.0 4.0 1.0\n 4.0 3.0 2.0\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.hessfact!", - "page": "Linear Algebra", - "title": "Base.LinAlg.hessfact!", - "category": "function", - "text": "hessfact!(A) -> Hessenberg\n\nhessfact! is the same as hessfact, but saves space by overwriting the input A, instead of creating a copy.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.schurfact", - "page": "Linear Algebra", - "title": "Base.LinAlg.schurfact", - "category": "function", - "text": "schurfact(A::StridedMatrix) -> F::Schur\n\nComputes the Schur factorization of the matrix A. The (quasi) triangular Schur factor can be obtained from the Schur object F with either F[:Schur] or F[:T] and the orthogonal/unitary Schur vectors can be obtained with F[:vectors] or F[:Z] such that A = F[:vectors]*F[:Schur]*F[:vectors]\'. The eigenvalues of A can be obtained with F[:values].\n\nExample\n\njulia> A = [-2. 1. 3.; 2. 1. -1.; -7. 2. 7.]\n3×3 Array{Float64,2}:\n -2.0 1.0 3.0\n 2.0 1.0 -1.0\n -7.0 2.0 7.0\n\njulia> F = schurfact(A)\nBase.LinAlg.Schur{Float64,Array{Float64,2}} with factors T and Z:\n[2.0 0.801792 6.63509; -8.55988e-11 2.0 8.08286; 0.0 0.0 1.99999]\n[0.577351 0.154299 -0.801784; 0.577346 -0.77152 0.267262; 0.577354 0.617211 0.534522]\nand values:\nComplex{Float64}[2.0+8.28447e-6im, 2.0-8.28447e-6im, 1.99999+0.0im]\n\njulia> F[:vectors] * F[:Schur] * F[:vectors]\'\n3×3 Array{Float64,2}:\n -2.0 1.0 3.0\n 2.0 1.0 -1.0\n -7.0 2.0 7.0\n\n\n\nschurfact(A::StridedMatrix, B::StridedMatrix) -> F::GeneralizedSchur\n\nComputes the Generalized Schur (or QZ) factorization of the matrices A and B. The (quasi) triangular Schur factors can be obtained from the Schur object F with F[:S] and F[:T], the left unitary/orthogonal Schur vectors can be obtained with F[:left] or F[:Q] and the right unitary/orthogonal Schur vectors can be obtained with F[:right] or F[:Z] such that A=F[:left]*F[:S]*F[:right]\' and B=F[:left]*F[:T]*F[:right]\'. The generalized eigenvalues of A and B can be obtained with F[:alpha]./F[:beta].\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.schurfact!", - "page": "Linear Algebra", - "title": "Base.LinAlg.schurfact!", - "category": "function", - "text": "schurfact!(A::StridedMatrix) -> F::Schur\n\nSame as schurfact but uses the input argument as workspace.\n\n\n\nschurfact!(A::StridedMatrix, B::StridedMatrix) -> F::GeneralizedSchur\n\nSame as schurfact but uses the input matrices A and B as workspace.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.schur", - "page": "Linear Algebra", - "title": "Base.LinAlg.schur", - "category": "function", - "text": "schur(A::StridedMatrix) -> T::Matrix, Z::Matrix, λ::Vector\n\nComputes the Schur factorization of the matrix A. The methods return the (quasi) triangular Schur factor T and the orthogonal/unitary Schur vectors Z such that A = Z*T*Z\'. The eigenvalues of A are returned in the vector λ.\n\nSee schurfact.\n\nExample\n\njulia> A = [-2. 1. 3.; 2. 1. -1.; -7. 2. 7.]\n3×3 Array{Float64,2}:\n -2.0 1.0 3.0\n 2.0 1.0 -1.0\n -7.0 2.0 7.0\n\njulia> T, Z, lambda = schur(A)\n([2.0 0.801792 6.63509; -8.55988e-11 2.0 8.08286; 0.0 0.0 1.99999], [0.577351 0.154299 -0.801784; 0.577346 -0.77152 0.267262; 0.577354 0.617211 0.534522], Complex{Float64}[2.0+8.28447e-6im, 2.0-8.28447e-6im, 1.99999+0.0im])\n\njulia> Z * T * Z\'\n3×3 Array{Float64,2}:\n -2.0 1.0 3.0\n 2.0 1.0 -1.0\n -7.0 2.0 7.0\n\n\n\nschur(A::StridedMatrix, B::StridedMatrix) -> S::StridedMatrix, T::StridedMatrix, Q::StridedMatrix, Z::StridedMatrix, α::Vector, β::Vector\n\nSee schurfact.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.ordschur", - "page": "Linear Algebra", - "title": "Base.LinAlg.ordschur", - "category": "function", - "text": "ordschur(F::Schur, select::Union{Vector{Bool},BitVector}) -> F::Schur\n\nReorders the Schur factorization F of a matrix A = Z*T*Z\' according to the logical array select returning the reordered factorization F object. The selected eigenvalues appear in the leading diagonal of F[:Schur] and the corresponding leading columns of F[:vectors] form an orthogonal/unitary basis of the corresponding right invariant subspace. In the real case, a complex conjugate pair of eigenvalues must be either both included or both excluded via select.\n\n\n\nordschur(T::StridedMatrix, Z::StridedMatrix, select::Union{Vector{Bool},BitVector}) -> T::StridedMatrix, Z::StridedMatrix, λ::Vector\n\nReorders the Schur factorization of a real matrix A = Z*T*Z\' according to the logical array select returning the reordered matrices T and Z as well as the vector of eigenvalues λ. The selected eigenvalues appear in the leading diagonal of T and the corresponding leading columns of Z form an orthogonal/unitary basis of the corresponding right invariant subspace. In the real case, a complex conjugate pair of eigenvalues must be either both included or both excluded via select.\n\n\n\nordschur(F::GeneralizedSchur, select::Union{Vector{Bool},BitVector}) -> F::GeneralizedSchur\n\nReorders the Generalized Schur factorization F of a matrix pair (A, B) = (Q*S*Z\', Q*T*Z\') according to the logical array select and returns a GeneralizedSchur object F. The selected eigenvalues appear in the leading diagonal of both F[:S] and F[:T], and the left and right orthogonal/unitary Schur vectors are also reordered such that (A, B) = F[:Q]*(F[:S], F[:T])*F[:Z]\' still holds and the generalized eigenvalues of A and B can still be obtained with F[:alpha]./F[:beta].\n\n\n\nordschur(S::StridedMatrix, T::StridedMatrix, Q::StridedMatrix, Z::StridedMatrix, select) -> S::StridedMatrix, T::StridedMatrix, Q::StridedMatrix, Z::StridedMatrix, α::Vector, β::Vector\n\nReorders the Generalized Schur factorization of a matrix pair (A, B) = (Q*S*Z\', Q*T*Z\') according to the logical array select and returns the matrices S, T, Q, Z and vectors α and β. The selected eigenvalues appear in the leading diagonal of both S and T, and the left and right unitary/orthogonal Schur vectors are also reordered such that (A, B) = Q*(S, T)*Z\' still holds and the generalized eigenvalues of A and B can still be obtained with α./β.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.ordschur!", - "page": "Linear Algebra", - "title": "Base.LinAlg.ordschur!", - "category": "function", - "text": "ordschur!(F::Schur, select::Union{Vector{Bool},BitVector}) -> F::Schur\n\nSame as ordschur but overwrites the factorization F.\n\n\n\nordschur!(T::StridedMatrix, Z::StridedMatrix, select::Union{Vector{Bool},BitVector}) -> T::StridedMatrix, Z::StridedMatrix, λ::Vector\n\nSame as ordschur but overwrites the input arguments.\n\n\n\nordschur!(F::GeneralizedSchur, select::Union{Vector{Bool},BitVector}) -> F::GeneralizedSchur\n\nSame as ordschur but overwrites the factorization F.\n\n\n\nordschur!(S::StridedMatrix, T::StridedMatrix, Q::StridedMatrix, Z::StridedMatrix, select) -> S::StridedMatrix, T::StridedMatrix, Q::StridedMatrix, Z::StridedMatrix, α::Vector, β::Vector\n\nSame as ordschur but overwrites the factorization the input arguments.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.svdfact", - "page": "Linear Algebra", - "title": "Base.LinAlg.svdfact", - "category": "function", - "text": "svdfact(A; thin::Bool=true) -> SVD\n\nCompute the singular value decomposition (SVD) of A and return an SVD object.\n\nU, S, V and Vt can be obtained from the factorization F with F[:U], F[:S], F[:V] and F[:Vt], such that A = U*diagm(S)*Vt. The algorithm produces Vt and hence Vt is more efficient to extract than V. The singular values in S are sorted in descending order.\n\nIf thin=true (default), a thin SVD is returned. For a M times N matrix A, U is M times M for a full SVD (thin=false) and M times min(M N) for a thin SVD.\n\nExample\n\njulia> A = [1. 0. 0. 0. 2.; 0. 0. 3. 0. 0.; 0. 0. 0. 0. 0.; 0. 2. 0. 0. 0.]\n4×5 Array{Float64,2}:\n 1.0 0.0 0.0 0.0 2.0\n 0.0 0.0 3.0 0.0 0.0\n 0.0 0.0 0.0 0.0 0.0\n 0.0 2.0 0.0 0.0 0.0\n\njulia> F = svdfact(A)\nBase.LinAlg.SVD{Float64,Float64,Array{Float64,2}}([0.0 1.0 0.0 0.0; 1.0 0.0 0.0 0.0; 0.0 0.0 0.0 -1.0; 0.0 0.0 1.0 0.0], [3.0, 2.23607, 2.0, 0.0], [-0.0 0.0 … -0.0 0.0; 0.447214 0.0 … 0.0 0.894427; -0.0 1.0 … -0.0 0.0; 0.0 0.0 … 1.0 0.0])\n\njulia> F[:U] * diagm(F[:S]) * F[:Vt]\n4×5 Array{Float64,2}:\n 1.0 0.0 0.0 0.0 2.0\n 0.0 0.0 3.0 0.0 0.0\n 0.0 0.0 0.0 0.0 0.0\n 0.0 2.0 0.0 0.0 0.0\n\n\n\nsvdfact(A, B) -> GeneralizedSVD\n\nCompute the generalized SVD of A and B, returning a GeneralizedSVD factorization object F, such that A = F[:U]*F[:D1]*F[:R0]*F[:Q]\' and B = F[:V]*F[:D2]*F[:R0]*F[:Q]\'.\n\nFor an M-by-N matrix A and P-by-N matrix B,\n\nF[:U] is a M-by-M orthogonal matrix,\nF[:V] is a P-by-P orthogonal matrix,\nF[:Q] is a N-by-N orthogonal matrix,\nF[:R0] is a (K+L)-by-N matrix whose rightmost (K+L)-by-(K+L) block is nonsingular upper block triangular,\nF[:D1] is a M-by-(K+L) diagonal matrix with 1s in the first K entries,\nF[:D2] is a P-by-(K+L) matrix whose top right L-by-L block is diagonal,\n\nK+L is the effective numerical rank of the matrix [A; B].\n\nThe entries of F[:D1] and F[:D2] are related, as explained in the LAPACK documentation for the generalized SVD and the xGGSVD3 routine which is called underneath (in LAPACK 3.6.0 and newer).\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.svdfact!", - "page": "Linear Algebra", - "title": "Base.LinAlg.svdfact!", - "category": "function", - "text": "svdfact!(A, thin::Bool=true) -> SVD\n\nsvdfact! is the same as svdfact, but saves space by overwriting the input A, instead of creating a copy.\n\n\n\nsvdfact!(A, B) -> GeneralizedSVD\n\nsvdfact! is the same as svdfact, but modifies the arguments A and B in-place, instead of making copies.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.svd", - "page": "Linear Algebra", - "title": "Base.LinAlg.svd", - "category": "function", - "text": "svd(A; thin::Bool=true) -> U, S, V\n\nComputes the SVD of A, returning U, vector S, and V such that A == U*diagm(S)*V\'. The singular values in S are sorted in descending order.\n\nIf thin=true (default), a thin SVD is returned. For a M times N matrix A, U is M times M for a full SVD (thin=false) and M times min(M N) for a thin SVD.\n\nsvd is a wrapper around svdfact, extracting all parts of the SVD factorization to a tuple. Direct use of svdfact is therefore more efficient.\n\nExample\n\njulia> A = [1. 0. 0. 0. 2.; 0. 0. 3. 0. 0.; 0. 0. 0. 0. 0.; 0. 2. 0. 0. 0.]\n4×5 Array{Float64,2}:\n 1.0 0.0 0.0 0.0 2.0\n 0.0 0.0 3.0 0.0 0.0\n 0.0 0.0 0.0 0.0 0.0\n 0.0 2.0 0.0 0.0 0.0\n\njulia> U, S, V = svd(A)\n([0.0 1.0 0.0 0.0; 1.0 0.0 0.0 0.0; 0.0 0.0 0.0 -1.0; 0.0 0.0 1.0 0.0], [3.0, 2.23607, 2.0, 0.0], [-0.0 0.447214 -0.0 0.0; 0.0 0.0 1.0 0.0; … ; -0.0 0.0 -0.0 1.0; 0.0 0.894427 0.0 0.0])\n\njulia> U*diagm(S)*V\'\n4×5 Array{Float64,2}:\n 1.0 0.0 0.0 0.0 2.0\n 0.0 0.0 3.0 0.0 0.0\n 0.0 0.0 0.0 0.0 0.0\n 0.0 2.0 0.0 0.0 0.0\n\n\n\nsvd(A, B) -> U, V, Q, D1, D2, R0\n\nWrapper around svdfact extracting all parts of the factorization to a tuple. Direct use of svdfact is therefore generally more efficient. The function returns the generalized SVD of A and B, returning U, V, Q, D1, D2, and R0 such that A = U*D1*R0*Q\' and B = V*D2*R0*Q\'.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.svdvals", - "page": "Linear Algebra", - "title": "Base.LinAlg.svdvals", - "category": "function", - "text": "svdvals(A)\n\nReturns the singular values of A in descending order.\n\nExample\n\njulia> A = [1. 0. 0. 0. 2.; 0. 0. 3. 0. 0.; 0. 0. 0. 0. 0.; 0. 2. 0. 0. 0.]\n4×5 Array{Float64,2}:\n 1.0 0.0 0.0 0.0 2.0\n 0.0 0.0 3.0 0.0 0.0\n 0.0 0.0 0.0 0.0 0.0\n 0.0 2.0 0.0 0.0 0.0\n\njulia> svdvals(A)\n4-element Array{Float64,1}:\n 3.0\n 2.23607\n 2.0\n 0.0\n\n\n\nsvdvals(A, B)\n\nReturn the generalized singular values from the generalized singular value decomposition of A and B. See also svdfact.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.Givens", - "page": "Linear Algebra", - "title": "Base.LinAlg.Givens", - "category": "type", - "text": "LinAlg.Givens(i1,i2,c,s) -> G\n\nA Givens rotation linear operator. The fields c and s represent the cosine and sine of the rotation angle, respectively. The Givens type supports left multiplication G*A and conjugated transpose right multiplication A*G\'. The type doesn\'t have a size and can therefore be multiplied with matrices of arbitrary size as long as i2<=size(A,2) for G*A or i2<=size(A,1) for A*G\'.\n\nSee also: givens\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.givens", - "page": "Linear Algebra", - "title": "Base.LinAlg.givens", - "category": "function", - "text": "givens{T}(f::T, g::T, i1::Integer, i2::Integer) -> (G::Givens, r::T)\n\nComputes the Givens rotation G and scalar r such that for any vector x where\n\nx[i1] = f\nx[i2] = g\n\nthe result of the multiplication\n\ny = G*x\n\nhas the property that\n\ny[i1] = r\ny[i2] = 0\n\nSee also: LinAlg.Givens\n\n\n\ngivens(A::AbstractArray, i1::Integer, i2::Integer, j::Integer) -> (G::Givens, r)\n\nComputes the Givens rotation G and scalar r such that the result of the multiplication\n\nB = G*A\n\nhas the property that\n\nB[i1,j] = r\nB[i2,j] = 0\n\nSee also: LinAlg.Givens\n\n\n\ngivens(x::AbstractVector, i1::Integer, i2::Integer) -> (G::Givens, r)\n\nComputes the Givens rotation G and scalar r such that the result of the multiplication\n\nB = G*x\n\nhas the property that\n\nB[i1] = r\nB[i2] = 0\n\nSee also: LinAlg.Givens\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.triu", - "page": "Linear Algebra", - "title": "Base.LinAlg.triu", - "category": "function", - "text": "triu(M)\n\nUpper triangle of a matrix.\n\nExample\n\njulia> a = ones(4,4)\n4×4 Array{Float64,2}:\n 1.0 1.0 1.0 1.0\n 1.0 1.0 1.0 1.0\n 1.0 1.0 1.0 1.0\n 1.0 1.0 1.0 1.0\n\njulia> triu(a)\n4×4 Array{Float64,2}:\n 1.0 1.0 1.0 1.0\n 0.0 1.0 1.0 1.0\n 0.0 0.0 1.0 1.0\n 0.0 0.0 0.0 1.0\n\n\n\ntriu(M, k::Integer)\n\nReturns the upper triangle of M starting from the kth superdiagonal.\n\nExample\n\njulia> a = ones(4,4)\n4×4 Array{Float64,2}:\n 1.0 1.0 1.0 1.0\n 1.0 1.0 1.0 1.0\n 1.0 1.0 1.0 1.0\n 1.0 1.0 1.0 1.0\n\njulia> triu(a,3)\n4×4 Array{Float64,2}:\n 0.0 0.0 0.0 1.0\n 0.0 0.0 0.0 0.0\n 0.0 0.0 0.0 0.0\n 0.0 0.0 0.0 0.0\n\njulia> triu(a,-3)\n4×4 Array{Float64,2}:\n 1.0 1.0 1.0 1.0\n 1.0 1.0 1.0 1.0\n 1.0 1.0 1.0 1.0\n 1.0 1.0 1.0 1.0\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.triu!", - "page": "Linear Algebra", - "title": "Base.LinAlg.triu!", - "category": "function", - "text": "triu!(M)\n\nUpper triangle of a matrix, overwriting M in the process. See also triu.\n\n\n\ntriu!(M, k::Integer)\n\nReturns the upper triangle of M starting from the kth superdiagonal, overwriting M in the process.\n\nExample\n\njulia> M = [1 2 3 4 5; 1 2 3 4 5; 1 2 3 4 5; 1 2 3 4 5; 1 2 3 4 5]\n5×5 Array{Int64,2}:\n 1 2 3 4 5\n 1 2 3 4 5\n 1 2 3 4 5\n 1 2 3 4 5\n 1 2 3 4 5\n\njulia> triu!(M, 1)\n5×5 Array{Int64,2}:\n 0 2 3 4 5\n 0 0 3 4 5\n 0 0 0 4 5\n 0 0 0 0 5\n 0 0 0 0 0\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.tril", - "page": "Linear Algebra", - "title": "Base.LinAlg.tril", - "category": "function", - "text": "tril(M)\n\nLower triangle of a matrix.\n\nExample\n\njulia> a = ones(4,4)\n4×4 Array{Float64,2}:\n 1.0 1.0 1.0 1.0\n 1.0 1.0 1.0 1.0\n 1.0 1.0 1.0 1.0\n 1.0 1.0 1.0 1.0\n\njulia> tril(a)\n4×4 Array{Float64,2}:\n 1.0 0.0 0.0 0.0\n 1.0 1.0 0.0 0.0\n 1.0 1.0 1.0 0.0\n 1.0 1.0 1.0 1.0\n\n\n\ntril(M, k::Integer)\n\nReturns the lower triangle of M starting from the kth superdiagonal.\n\nExample\n\njulia> a = ones(4,4)\n4×4 Array{Float64,2}:\n 1.0 1.0 1.0 1.0\n 1.0 1.0 1.0 1.0\n 1.0 1.0 1.0 1.0\n 1.0 1.0 1.0 1.0\n\njulia> tril(a,3)\n4×4 Array{Float64,2}:\n 1.0 1.0 1.0 1.0\n 1.0 1.0 1.0 1.0\n 1.0 1.0 1.0 1.0\n 1.0 1.0 1.0 1.0\n\njulia> tril(a,-3)\n4×4 Array{Float64,2}:\n 0.0 0.0 0.0 0.0\n 0.0 0.0 0.0 0.0\n 0.0 0.0 0.0 0.0\n 1.0 0.0 0.0 0.0\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.tril!", - "page": "Linear Algebra", - "title": "Base.LinAlg.tril!", - "category": "function", - "text": "tril!(M)\n\nLower triangle of a matrix, overwriting M in the process. See also tril.\n\n\n\ntril!(M, k::Integer)\n\nReturns the lower triangle of M starting from the kth superdiagonal, overwriting M in the process.\n\nExample\n\njulia> M = [1 2 3 4 5; 1 2 3 4 5; 1 2 3 4 5; 1 2 3 4 5; 1 2 3 4 5]\n5×5 Array{Int64,2}:\n 1 2 3 4 5\n 1 2 3 4 5\n 1 2 3 4 5\n 1 2 3 4 5\n 1 2 3 4 5\n\njulia> tril!(M, 2)\n5×5 Array{Int64,2}:\n 1 2 3 0 0\n 1 2 3 4 0\n 1 2 3 4 5\n 1 2 3 4 5\n 1 2 3 4 5\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.diagind", - "page": "Linear Algebra", - "title": "Base.LinAlg.diagind", - "category": "function", - "text": "diagind(M, k::Integer=0)\n\nA Range giving the indices of the kth diagonal of the matrix M.\n\nExample\n\njulia> A = [1 2 3; 4 5 6; 7 8 9]\n3×3 Array{Int64,2}:\n 1 2 3\n 4 5 6\n 7 8 9\n\njulia> diagind(A,-1)\n2:4:6\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.diag", - "page": "Linear Algebra", - "title": "Base.LinAlg.diag", - "category": "function", - "text": "diag(M, k::Integer=0)\n\nThe kth diagonal of a matrix, as a vector. Use diagm to construct a diagonal matrix.\n\nExample\n\njulia> A = [1 2 3; 4 5 6; 7 8 9]\n3×3 Array{Int64,2}:\n 1 2 3\n 4 5 6\n 7 8 9\n\njulia> diag(A,1)\n2-element Array{Int64,1}:\n 2\n 6\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.diagm", - "page": "Linear Algebra", - "title": "Base.LinAlg.diagm", - "category": "function", - "text": "diagm(v, k::Integer=0)\n\nConstruct a matrix by placing v on the kth diagonal.\n\nExample\n\njulia> diagm([1,2,3],1)\n4×4 Array{Int64,2}:\n 0 1 0 0\n 0 0 2 0\n 0 0 0 3\n 0 0 0 0\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.scale!", - "page": "Linear Algebra", - "title": "Base.LinAlg.scale!", - "category": "function", - "text": "scale!(A, b)\nscale!(b, A)\n\nScale an array A by a scalar b overwriting A in-place.\n\nIf A is a matrix and b is a vector, then scale!(A,b) scales each column i of A by b[i] (similar to A*Diagonal(b)), while scale!(b,A) scales each row i of A by b[i] (similar to Diagonal(b)*A), again operating in-place on A. An InexactError exception is thrown if the scaling produces a number not representable by the element type of A, e.g. for integer types.\n\nExample\n\njulia> a = [1 2; 3 4]\n2×2 Array{Int64,2}:\n 1 2\n 3 4\n\njulia> b = [1; 2]\n2-element Array{Int64,1}:\n 1\n 2\n\njulia> scale!(a,b)\n2×2 Array{Int64,2}:\n 1 4\n 3 8\n\njulia> a = [1 2; 3 4];\n\njulia> b = [1; 2];\n\njulia> scale!(b,a)\n2×2 Array{Int64,2}:\n 1 2\n 6 8\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.rank", - "page": "Linear Algebra", - "title": "Base.LinAlg.rank", - "category": "function", - "text": "rank(M[, tol::Real])\n\nCompute the rank of a matrix by counting how many singular values of M have magnitude greater than tol. By default, the value of tol is the largest dimension of M multiplied by the eps of the eltype of M.\n\nExample\n\njulia> rank(eye(3))\n3\n\njulia> rank(diagm([1, 0, 2]))\n2\n\njulia> rank(diagm([1, 0.001, 2]), 0.1)\n2\n\njulia> rank(diagm([1, 0.001, 2]), 0.00001)\n3\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.norm", - "page": "Linear Algebra", - "title": "Base.LinAlg.norm", - "category": "function", - "text": "norm(A::AbstractArray, p::Real=2)\n\nCompute the p-norm of a vector or the operator norm of a matrix A, defaulting to the 2-norm.\n\nnorm(A::AbstractVector, p::Real=2)\n\nFor vectors, this is equivalent to vecnorm and equal to:\n\nA_p = left( sum_i=1^n a_i ^p right)^1p\n\nwith a_i the entries of A and n its length.\n\np can assume any numeric value (even though not all values produce a mathematically valid vector norm). In particular, norm(A, Inf) returns the largest value in abs(A), whereas norm(A, -Inf) returns the smallest.\n\nExample\n\njulia> v = [3, -2, 6]\n3-element Array{Int64,1}:\n 3\n -2\n 6\n\njulia> norm(v)\n7.0\n\njulia> norm(v, Inf)\n6.0\n\n\n\nnorm(A::AbstractMatrix, p::Real=2)\n\nFor matrices, the matrix norm induced by the vector p-norm is used, where valid values of p are 1, 2, or Inf. (Note that for sparse matrices, p=2 is currently not implemented.) Use vecnorm to compute the Frobenius norm.\n\nWhen p=1, the matrix norm is the maximum absolute column sum of A:\n\nA_1 = max_1 j n sum_i=1^m a_ij \n\nwith a_ij the entries of A, and m and n its dimensions.\n\nWhen p=2, the matrix norm is the spectral norm, equal to the largest singular value of A.\n\nWhen p=Inf, the matrix norm is the maximum absolute row sum of A:\n\nA_infty = max_1 i m sum _j=1^n a_ij \n\nExample\n\njulia> A = [1 -2 -3; 2 3 -1]\n2×3 Array{Int64,2}:\n 1 -2 -3\n 2 3 -1\n\njulia> norm(A, Inf)\n6.0\n\n\n\nnorm(x::Number, p::Real=2)\n\nFor numbers, return left( x^p right)^1p. This is equivalent to vecnorm.\n\n\n\nnorm(A::RowVector, q::Real=2)\n\nFor row vectors, return the q-norm of A, which is equivalent to the p-norm with value p = q/(q-1). They coincide at p = q = 2.\n\nThe difference in norm between a vector space and its dual arises to preserve the relationship between duality and the inner product, and the result is consistent with the p-norm of 1 × n matrix.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.vecnorm", - "page": "Linear Algebra", - "title": "Base.LinAlg.vecnorm", - "category": "function", - "text": "vecnorm(A, p::Real=2)\n\nFor any iterable container A (including arrays of any dimension) of numbers (or any element type for which norm is defined), compute the p-norm (defaulting to p=2) as if A were a vector of the corresponding length.\n\nThe p-norm is defined as:\n\nA_p = left( sum_i=1^n a_i ^p right)^1p\n\nwith a_i the entries of A and n its length.\n\np can assume any numeric value (even though not all values produce a mathematically valid vector norm). In particular, vecnorm(A, Inf) returns the largest value in abs(A), whereas vecnorm(A, -Inf) returns the smallest. If A is a matrix and p=2, then this is equivalent to the Frobenius norm.\n\nExample\n\njulia> vecnorm([1 2 3; 4 5 6; 7 8 9])\n16.881943016134134\n\njulia> vecnorm([1 2 3 4 5 6 7 8 9])\n16.881943016134134\n\n\n\nvecnorm(x::Number, p::Real=2)\n\nFor numbers, return left( x^p right) ^1p.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.normalize!", - "page": "Linear Algebra", - "title": "Base.LinAlg.normalize!", - "category": "function", - "text": "normalize!(v::AbstractVector, p::Real=2)\n\nNormalize the vector v in-place so that its p-norm equals unity, i.e. norm(v, p) == 1. See also normalize and vecnorm.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.normalize", - "page": "Linear Algebra", - "title": "Base.LinAlg.normalize", - "category": "function", - "text": "normalize(v::AbstractVector, p::Real=2)\n\nNormalize the vector v so that its p-norm equals unity, i.e. norm(v, p) == vecnorm(v, p) == 1. See also normalize! and vecnorm.\n\nExamples\n\njulia> a = [1,2,4];\n\njulia> b = normalize(a)\n3-element Array{Float64,1}:\n 0.218218\n 0.436436\n 0.872872\n\njulia> norm(b)\n1.0\n\njulia> c = normalize(a, 1)\n3-element Array{Float64,1}:\n 0.142857\n 0.285714\n 0.571429\n\njulia> norm(c, 1)\n1.0\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.cond", - "page": "Linear Algebra", - "title": "Base.LinAlg.cond", - "category": "function", - "text": "cond(M, p::Real=2)\n\nCondition number of the matrix M, computed using the operator p-norm. Valid values for p are 1, 2 (default), or Inf.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.condskeel", - "page": "Linear Algebra", - "title": "Base.LinAlg.condskeel", - "category": "function", - "text": "condskeel(M, [x, p::Real=Inf])\n\nkappa_S(M p) = leftVert leftvert M rightvert leftvert M^-1 rightvert rightVert_p \nkappa_S(M x p) = leftVert leftvert M rightvert leftvert M^-1 rightvert leftvert x rightvert rightVert_p\n\nSkeel condition number kappa_S of the matrix M, optionally with respect to the vector x, as computed using the operator p-norm. leftvert M rightvert denotes the matrix of (entry wise) absolute values of M; leftvert M rightvert_ij = leftvert M_ij rightvert. Valid values for p are 1, 2 and Inf (default).\n\nThis quantity is also known in the literature as the Bauer condition number, relative condition number, or componentwise relative condition number.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.trace", - "page": "Linear Algebra", - "title": "Base.LinAlg.trace", - "category": "function", - "text": "trace(M)\n\nMatrix trace. Sums the diagonal elements of M.\n\nExample\n\njulia> A = [1 2; 3 4]\n2×2 Array{Int64,2}:\n 1 2\n 3 4\n\njulia> trace(A)\n5\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.det", - "page": "Linear Algebra", - "title": "Base.LinAlg.det", - "category": "function", - "text": "det(M)\n\nMatrix determinant.\n\nExample\n\njulia> M = [1 0; 2 2]\n2×2 Array{Int64,2}:\n 1 0\n 2 2\n\njulia> det(M)\n2.0\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.logdet", - "page": "Linear Algebra", - "title": "Base.LinAlg.logdet", - "category": "function", - "text": "logdet(M)\n\nLog of matrix determinant. Equivalent to log(det(M)), but may provide increased accuracy and/or speed.\n\nExamples\n\njulia> M = [1 0; 2 2]\n2×2 Array{Int64,2}:\n 1 0\n 2 2\n\njulia> logdet(M)\n0.6931471805599453\n\njulia> logdet(eye(3))\n0.0\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.logabsdet", - "page": "Linear Algebra", - "title": "Base.LinAlg.logabsdet", - "category": "function", - "text": "logabsdet(M)\n\nLog of absolute value of matrix determinant. Equivalent to (log(abs(det(M))), sign(det(M))), but may provide increased accuracy and/or speed.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.inv", - "page": "Linear Algebra", - "title": "Base.inv", - "category": "function", - "text": "inv(M)\n\nMatrix inverse. Computes matrix N such that M * N = I, where I is the identity matrix. Computed by solving the left-division N = M \\ I.\n\nExample\n\njulia> M = [2 5; 1 3]\n2×2 Array{Int64,2}:\n 2 5\n 1 3\n\njulia> N = inv(M)\n2×2 Array{Float64,2}:\n 3.0 -5.0\n -1.0 2.0\n\njulia> M*N == N*M == eye(2)\ntrue\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.pinv", - "page": "Linear Algebra", - "title": "Base.LinAlg.pinv", - "category": "function", - "text": "pinv(M[, tol::Real])\n\nComputes the Moore-Penrose pseudoinverse.\n\nFor matrices M with floating point elements, it is convenient to compute the pseudoinverse by inverting only singular values above a given threshold, tol.\n\nThe optimal choice of tol varies both with the value of M and the intended application of the pseudoinverse. The default value of tol is eps(real(float(one(eltype(M)))))*maximum(size(A)), which is essentially machine epsilon for the real part of a matrix element multiplied by the larger matrix dimension. For inverting dense ill-conditioned matrices in a least-squares sense, tol = sqrt(eps(real(float(one(eltype(M)))))) is recommended.\n\nFor more information, see [issue8859], [B96], [S84], [KY88].\n\nExample\n\njulia> M = [1.5 1.3; 1.2 1.9]\n2×2 Array{Float64,2}:\n 1.5 1.3\n 1.2 1.9\n\njulia> N = pinv(M)\n2×2 Array{Float64,2}:\n 1.47287 -1.00775\n -0.930233 1.16279\n\njulia> M * N\n2×2 Array{Float64,2}:\n 1.0 -2.22045e-16\n 4.44089e-16 1.0\n\n[issue8859]: Issue 8859, \"Fix least squares\", https://github.com/JuliaLang/julia/pull/8859\n\n[B96]: Åke Björck, \"Numerical Methods for Least Squares Problems\", SIAM Press, Philadelphia, 1996, \"Other Titles in Applied Mathematics\", Vol. 51. doi:10.1137/1.9781611971484\n\n[S84]: G. W. Stewart, \"Rank Degeneracy\", SIAM Journal on Scientific and Statistical Computing, 5(2), 1984, 403-413. doi:10.1137/0905030\n\n[KY88]: Konstantinos Konstantinides and Kung Yao, \"Statistical analysis of effective singular values in matrix rank determination\", IEEE Transactions on Acoustics, Speech and Signal Processing, 36(5), 1988, 757-763. doi:10.1109/29.1585\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.nullspace", - "page": "Linear Algebra", - "title": "Base.LinAlg.nullspace", - "category": "function", - "text": "nullspace(M)\n\nBasis for nullspace of M.\n\nExample\n\njulia> M = [1 0 0; 0 1 0; 0 0 0]\n3×3 Array{Int64,2}:\n 1 0 0\n 0 1 0\n 0 0 0\n\njulia> nullspace(M)\n3×1 Array{Float64,2}:\n 0.0\n 0.0\n 1.0\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.repmat", - "page": "Linear Algebra", - "title": "Base.repmat", - "category": "function", - "text": "repmat(A, m::Integer, n::Integer=1)\n\nConstruct a matrix by repeating the given matrix (or vector) m times in dimension 1 and n times in dimension 2.\n\nExamples\n\njulia> repmat([1, 2, 3], 2)\n6-element Array{Int64,1}:\n 1\n 2\n 3\n 1\n 2\n 3\n\njulia> repmat([1, 2, 3], 2, 3)\n6×3 Array{Int64,2}:\n 1 1 1\n 2 2 2\n 3 3 3\n 1 1 1\n 2 2 2\n 3 3 3\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.repeat", - "page": "Linear Algebra", - "title": "Base.repeat", - "category": "function", - "text": "repeat(A::AbstractArray; inner=ntuple(x->1, ndims(A)), outer=ntuple(x->1, ndims(A)))\n\nConstruct an array by repeating the entries of A. The i-th element of inner specifies the number of times that the individual entries of the i-th dimension of A should be repeated. The i-th element of outer specifies the number of times that a slice along the i-th dimension of A should be repeated. If inner or outer are omitted, no repetition is performed.\n\nExamples\n\njulia> repeat(1:2, inner=2)\n4-element Array{Int64,1}:\n 1\n 1\n 2\n 2\n\njulia> repeat(1:2, outer=2)\n4-element Array{Int64,1}:\n 1\n 2\n 1\n 2\n\njulia> repeat([1 2; 3 4], inner=(2, 1), outer=(1, 3))\n4×6 Array{Int64,2}:\n 1 2 1 2 1 2\n 1 2 1 2 1 2\n 3 4 3 4 3 4\n 3 4 3 4 3 4\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.kron", - "page": "Linear Algebra", - "title": "Base.kron", - "category": "function", - "text": "kron(A, B)\n\nKronecker tensor product of two vectors or two matrices.\n\nExample\n\njulia> A = [1 2; 3 4]\n2×2 Array{Int64,2}:\n 1 2\n 3 4\n\njulia> B = [im 1; 1 -im]\n2×2 Array{Complex{Int64},2}:\n 0+1im 1+0im\n 1+0im 0-1im\n\njulia> kron(A, B)\n4×4 Array{Complex{Int64},2}:\n 0+1im 1+0im 0+2im 2+0im\n 1+0im 0-1im 2+0im 0-2im\n 0+3im 3+0im 0+4im 4+0im\n 3+0im 0-3im 4+0im 0-4im\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.SparseArrays.blkdiag", - "page": "Linear Algebra", - "title": "Base.SparseArrays.blkdiag", - "category": "function", - "text": "blkdiag(A...)\n\nConcatenate matrices block-diagonally. Currently only implemented for sparse matrices.\n\nExample\n\njulia> blkdiag(speye(3), 2*speye(2))\n5×5 SparseMatrixCSC{Float64,Int64} with 5 stored entries:\n [1, 1] = 1.0\n [2, 2] = 1.0\n [3, 3] = 1.0\n [4, 4] = 2.0\n [5, 5] = 2.0\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.linreg", - "page": "Linear Algebra", - "title": "Base.LinAlg.linreg", - "category": "function", - "text": "linreg(x, y)\n\nPerform simple linear regression using Ordinary Least Squares. Returns a and b such that a + b*x is the closest straight line to the given points (x, y), i.e., such that the squared error between y and a + b*x is minimized.\n\nExamples:\n\nusing PyPlot\nx = 1.0:12.0\ny = [5.5, 6.3, 7.6, 8.8, 10.9, 11.79, 13.48, 15.02, 17.77, 20.81, 22.0, 22.99]\na, b = linreg(x, y) # Linear regression\nplot(x, y, \"o\") # Plot (x, y) points\nplot(x, a + b*x) # Plot line determined by linear regression\n\nSee also:\n\n\\, cov, std, mean.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.expm", - "page": "Linear Algebra", - "title": "Base.LinAlg.expm", - "category": "function", - "text": "expm(A)\n\nCompute the matrix exponential of A, defined by\n\ne^A = sum_n=0^infty fracA^nn\n\nFor symmetric or Hermitian A, an eigendecomposition (eigfact) is used, otherwise the scaling and squaring algorithm (see [H05]) is chosen.\n\n[H05]: Nicholas J. Higham, \"The squaring and scaling method for the matrix exponential revisited\", SIAM Journal on Matrix Analysis and Applications, 26(4), 2005, 1179-1193. doi:10.1137/090768539\n\nExample\n\njulia> A = eye(2, 2)\n2×2 Array{Float64,2}:\n 1.0 0.0\n 0.0 1.0\n\njulia> expm(A)\n2×2 Array{Float64,2}:\n 2.71828 0.0\n 0.0 2.71828\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.logm", - "page": "Linear Algebra", - "title": "Base.LinAlg.logm", - "category": "function", - "text": "logm(A{T}::StridedMatrix{T})\n\nIf A has no negative real eigenvalue, compute the principal matrix logarithm of A, i.e. the unique matrix X such that e^X = A and -pi Im(lambda) pi for all the eigenvalues lambda of X. If A has nonpositive eigenvalues, a nonprincipal matrix function is returned whenever possible.\n\nIf A is symmetric or Hermitian, its eigendecomposition (eigfact) is used, if A is triangular an improved version of the inverse scaling and squaring method is employed (see [AH12] and [AHR13]). For general matrices, the complex Schur form (schur) is computed and the triangular algorithm is used on the triangular factor.\n\n[AH12]: Awad H. Al-Mohy and Nicholas J. Higham, \"Improved inverse scaling and squaring algorithms for the matrix logarithm\", SIAM Journal on Scientific Computing, 34(4), 2012, C153-C169. doi:10.1137/110852553\n\n[AHR13]: Awad H. Al-Mohy, Nicholas J. Higham and Samuel D. Relton, \"Computing the Fréchet derivative of the matrix logarithm and estimating the condition number\", SIAM Journal on Scientific Computing, 35(4), 2013, C394-C410. doi:10.1137/120885991\n\nExample\n\njulia> A = 2.7182818 * eye(2)\n2×2 Array{Float64,2}:\n 2.71828 0.0\n 0.0 2.71828\n\njulia> logm(A)\n2×2 Symmetric{Float64,Array{Float64,2}}:\n 1.0 0.0\n 0.0 1.0\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.sqrtm", - "page": "Linear Algebra", - "title": "Base.LinAlg.sqrtm", - "category": "function", - "text": "sqrtm(A)\n\nIf A has no negative real eigenvalues, compute the principal matrix square root of A, that is the unique matrix X with eigenvalues having positive real part such that X^2 = A. Otherwise, a nonprincipal square root is returned.\n\nIf A is symmetric or Hermitian, its eigendecomposition (eigfact) is used to compute the square root. Otherwise, the square root is determined by means of the Björck-Hammarling method [BH83], which computes the complex Schur form (schur) and then the complex square root of the triangular factor.\n\n[BH83]: Åke Björck and Sven Hammarling, \"A Schur method for the square root of a matrix\", Linear Algebra and its Applications, 52-53, 1983, 127-140. doi:10.1016/0024-3795(83)80010-X\n\nExample\n\njulia> A = [4 0; 0 4]\n2×2 Array{Int64,2}:\n 4 0\n 0 4\n\njulia> sqrtm(A)\n2×2 Array{Float64,2}:\n 2.0 0.0\n 0.0 2.0\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.lyap", - "page": "Linear Algebra", - "title": "Base.LinAlg.lyap", - "category": "function", - "text": "lyap(A, C)\n\nComputes the solution X to the continuous Lyapunov equation AX + XA\' + C = 0, where no eigenvalue of A has a zero real part and no two eigenvalues are negative complex conjugates of each other.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.sylvester", - "page": "Linear Algebra", - "title": "Base.LinAlg.sylvester", - "category": "function", - "text": "sylvester(A, B, C)\n\nComputes the solution X to the Sylvester equation AX + XB + C = 0, where A, B and C have compatible dimensions and A and -B have no eigenvalues with equal real part.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.issymmetric", - "page": "Linear Algebra", - "title": "Base.LinAlg.issymmetric", - "category": "function", - "text": "issymmetric(A) -> Bool\n\nTest whether a matrix is symmetric.\n\nExamples\n\njulia> a = [1 2; 2 -1]\n2×2 Array{Int64,2}:\n 1 2\n 2 -1\n\njulia> issymmetric(a)\ntrue\n\njulia> b = [1 im; -im 1]\n2×2 Array{Complex{Int64},2}:\n 1+0im 0+1im\n 0-1im 1+0im\n\njulia> issymmetric(b)\nfalse\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.isposdef", - "page": "Linear Algebra", - "title": "Base.LinAlg.isposdef", - "category": "function", - "text": "isposdef(A) -> Bool\n\nTest whether a matrix is positive definite.\n\nExample\n\njulia> A = [1 2; 2 50]\n2×2 Array{Int64,2}:\n 1 2\n 2 50\n\njulia> isposdef(A)\ntrue\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.isposdef!", - "page": "Linear Algebra", - "title": "Base.LinAlg.isposdef!", - "category": "function", - "text": "isposdef!(A) -> Bool\n\nTest whether a matrix is positive definite, overwriting A in the process.\n\nExample\n\njulia> A = [1. 2.; 2. 50.];\n\njulia> isposdef!(A)\ntrue\n\njulia> A\n2×2 Array{Float64,2}:\n 1.0 2.0\n 2.0 6.78233\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.istril", - "page": "Linear Algebra", - "title": "Base.LinAlg.istril", - "category": "function", - "text": "istril(A) -> Bool\n\nTest whether a matrix is lower triangular.\n\nExamples\n\njulia> a = [1 2; 2 -1]\n2×2 Array{Int64,2}:\n 1 2\n 2 -1\n\njulia> istril(a)\nfalse\n\njulia> b = [1 0; -im -1]\n2×2 Array{Complex{Int64},2}:\n 1+0im 0+0im\n 0-1im -1+0im\n\njulia> istril(b)\ntrue\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.istriu", - "page": "Linear Algebra", - "title": "Base.LinAlg.istriu", - "category": "function", - "text": "istriu(A) -> Bool\n\nTest whether a matrix is upper triangular.\n\nExamples\n\njulia> a = [1 2; 2 -1]\n2×2 Array{Int64,2}:\n 1 2\n 2 -1\n\njulia> istriu(a)\nfalse\n\njulia> b = [1 im; 0 -1]\n2×2 Array{Complex{Int64},2}:\n 1+0im 0+1im\n 0+0im -1+0im\n\njulia> istriu(b)\ntrue\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.isdiag", - "page": "Linear Algebra", - "title": "Base.LinAlg.isdiag", - "category": "function", - "text": "isdiag(A) -> Bool\n\nTest whether a matrix is diagonal.\n\nExamples\n\njulia> a = [1 2; 2 -1]\n2×2 Array{Int64,2}:\n 1 2\n 2 -1\n\njulia> isdiag(a)\nfalse\n\njulia> b = [im 0; 0 -im]\n2×2 Array{Complex{Int64},2}:\n 0+1im 0+0im\n 0+0im 0-1im\n\njulia> isdiag(b)\ntrue\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.ishermitian", - "page": "Linear Algebra", - "title": "Base.LinAlg.ishermitian", - "category": "function", - "text": "ishermitian(A) -> Bool\n\nTest whether a matrix is Hermitian.\n\nExamples\n\njulia> a = [1 2; 2 -1]\n2×2 Array{Int64,2}:\n 1 2\n 2 -1\n\njulia> ishermitian(a)\ntrue\n\njulia> b = [1 im; -im 1]\n2×2 Array{Complex{Int64},2}:\n 1+0im 0+1im\n 0-1im 1+0im\n\njulia> ishermitian(b)\ntrue\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.RowVector", - "page": "Linear Algebra", - "title": "Base.LinAlg.RowVector", - "category": "type", - "text": "RowVector(vector)\n\nA lazy-view wrapper of an AbstractVector, which turns a length-n vector into a 1×n shaped row vector and represents the transpose of a vector (the elements are also transposed recursively). This type is usually constructed (and unwrapped) via the transpose function or .\' operator (or related ctranspose or \' operator).\n\nBy convention, a vector can be multiplied by a matrix on its left (A * v) whereas a row vector can be multiplied by a matrix on its right (such that v.\' * A = (A.\' * v).\'). It differs from a 1×n-sized matrix by the facts that its transpose returns a vector and the inner product v1.\' * v2 returns a scalar, but will otherwise behave similarly.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.ConjArray", - "page": "Linear Algebra", - "title": "Base.LinAlg.ConjArray", - "category": "type", - "text": "ConjArray(array)\n\nA lazy-view wrapper of an AbstractArray, taking the elementwise complex conjugate. This type is usually constructed (and unwrapped) via the conj function (or related ctranspose), but currently this is the default behavior for RowVector only. For other arrays, the ConjArray constructor can be used directly.\n\nExamples\n\njulia> [1+im, 1-im]\'\n1×2 RowVector{Complex{Int64},ConjArray{Complex{Int64},1,Array{Complex{Int64},1}}}:\n 1-1im 1+1im\n\njulia> ConjArray([1+im 0; 0 1-im])\n2×2 ConjArray{Complex{Int64},2,Array{Complex{Int64},2}}:\n 1-1im 0+0im\n 0+0im 1+1im\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.transpose", - "page": "Linear Algebra", - "title": "Base.transpose", - "category": "function", - "text": "transpose(A::AbstractMatrix)\n\nThe transposition operator (.\').\n\nExample\n\njulia> A = [1 2 3; 4 5 6; 7 8 9]\n3×3 Array{Int64,2}:\n 1 2 3\n 4 5 6\n 7 8 9\n\njulia> transpose(A)\n3×3 Array{Int64,2}:\n 1 4 7\n 2 5 8\n 3 6 9\n\n\n\ntranspose(v::AbstractVector)\n\nThe transposition operator (.\').\n\nExample\n\njulia> v = [1,2,3]\n3-element Array{Int64,1}:\n 1\n 2\n 3\n\njulia> transpose(v)\n1×3 RowVector{Int64,Array{Int64,1}}:\n 1 2 3\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.transpose!", - "page": "Linear Algebra", - "title": "Base.LinAlg.transpose!", - "category": "function", - "text": "transpose!(dest,src)\n\nTranspose array src and store the result in the preallocated array dest, which should have a size corresponding to (size(src,2),size(src,1)). No in-place transposition is supported and unexpected results will happen if src and dest have overlapping memory regions.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.ctranspose", - "page": "Linear Algebra", - "title": "Base.ctranspose", - "category": "function", - "text": "ctranspose(A)\n\nThe conjugate transposition operator (\').\n\nExample\n\njulia> A = [3+2im 9+2im; 8+7im 4+6im]\n2×2 Array{Complex{Int64},2}:\n 3+2im 9+2im\n 8+7im 4+6im\n\njulia> ctranspose(A)\n2×2 Array{Complex{Int64},2}:\n 3-2im 8-7im\n 9-2im 4-6im\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.ctranspose!", - "page": "Linear Algebra", - "title": "Base.LinAlg.ctranspose!", - "category": "function", - "text": "ctranspose!(dest,src)\n\nConjugate transpose array src and store the result in the preallocated array dest, which should have a size corresponding to (size(src,2),size(src,1)). No in-place transposition is supported and unexpected results will happen if src and dest have overlapping memory regions.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.eigs-Tuple{Any}", - "page": "Linear Algebra", - "title": "Base.LinAlg.eigs", - "category": "method", - "text": "eigs(A; nev=6, ncv=max(20,2*nev+1), which=:LM, tol=0.0, maxiter=300, sigma=nothing, ritzvec=true, v0=zeros((0,))) -> (d,[v,],nconv,niter,nmult,resid)\n\nComputes eigenvalues d of A using implicitly restarted Lanczos or Arnoldi iterations for real symmetric or general nonsymmetric matrices respectively.\n\nThe following keyword arguments are supported:\n\nnev: Number of eigenvalues\nncv: Number of Krylov vectors used in the computation; should satisfy nev+1 <= ncv <= n for real symmetric problems and nev+2 <= ncv <= n for other problems, where n is the size of the input matrix A. The default is ncv = max(20,2*nev+1). Note that these restrictions limit the input matrix A to be of dimension at least 2.\nwhich: type of eigenvalues to compute. See the note below.\n\nwhich type of eigenvalues\n:LM eigenvalues of largest magnitude (default)\n:SM eigenvalues of smallest magnitude\n:LR eigenvalues of largest real part\n:SR eigenvalues of smallest real part\n:LI eigenvalues of largest imaginary part (nonsymmetric or complex A only)\n:SI eigenvalues of smallest imaginary part (nonsymmetric or complex A only)\n:BE compute half of the eigenvalues from each end of the spectrum, biased in favor of the high end. (real symmetric A only)\n\ntol: parameter defining the relative tolerance for convergence of Ritz values (eigenvalue estimates). A Ritz value is considered converged when its associated residual is less than or equal to the product of tol and max(^23 ), where ɛ = eps(real(eltype(A)))/2 is LAPACK\'s machine epsilon. The residual associated with and its corresponding Ritz vector v is defined as the norm Av - v. The specified value of tol should be positive; otherwise, it is ignored and is used instead. Default: .\nmaxiter: Maximum number of iterations (default = 300)\nsigma: Specifies the level shift used in inverse iteration. If nothing (default), defaults to ordinary (forward) iterations. Otherwise, find eigenvalues close to sigma using shift and invert iterations.\nritzvec: Returns the Ritz vectors v (eigenvectors) if true\nv0: starting vector from which to start the iterations\n\neigs returns the nev requested eigenvalues in d, the corresponding Ritz vectors v (only if ritzvec=true), the number of converged eigenvalues nconv, the number of iterations niter and the number of matrix vector multiplications nmult, as well as the final residual vector resid.\n\nExample\n\njulia> A = spdiagm(1:4);\n\njulia> λ, ϕ = eigs(A, nev = 2);\n\njulia> λ\n2-element Array{Float64,1}:\n 4.0\n 3.0\n\nnote: Note\nThe sigma and which keywords interact: the description of eigenvalues searched for by which do not necessarily refer to the eigenvalues of A, but rather the linear operator constructed by the specification of the iteration mode implied by sigma.sigma iteration mode which refers to eigenvalues of\nnothing ordinary (forward) A\nreal or complex inverse with level shift sigma (A - sigma I )^-1\n\nnote: Note\nAlthough tol has a default value, the best choice depends strongly on the matrix A. We recommend that users _always_ specify a value for tol which suits their specific needs.For details of how the errors in the computed eigenvalues are estimated, see:B. N. Parlett, \"The Symmetric Eigenvalue Problem\", SIAM: Philadelphia, 2/e (1998), Ch. 13.2, \"Accessing Accuracy in Lanczos Problems\", pp. 290-292 ff.\nR. B. Lehoucq and D. C. Sorensen, \"Deflation Techniques for an Implicitly Restarted Arnoldi Iteration\", SIAM Journal on Matrix Analysis and Applications (1996), 17(4), 789–821. doi:10.1137/S0895479895281484\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.eigs-Tuple{Any,Any}", - "page": "Linear Algebra", - "title": "Base.LinAlg.eigs", - "category": "method", - "text": "eigs(A, B; nev=6, ncv=max(20,2*nev+1), which=:LM, tol=0.0, maxiter=300, sigma=nothing, ritzvec=true, v0=zeros((0,))) -> (d,[v,],nconv,niter,nmult,resid)\n\nComputes generalized eigenvalues d of A and B using implicitly restarted Lanczos or Arnoldi iterations for real symmetric or general nonsymmetric matrices respectively.\n\nThe following keyword arguments are supported:\n\nnev: Number of eigenvalues\nncv: Number of Krylov vectors used in the computation; should satisfy nev+1 <= ncv <= n for real symmetric problems and nev+2 <= ncv <= n for other problems, where n is the size of the input matrices A and B. The default is ncv = max(20,2*nev+1). Note that these restrictions limit the input matrix A to be of dimension at least 2.\nwhich: type of eigenvalues to compute. See the note below.\n\nwhich type of eigenvalues\n:LM eigenvalues of largest magnitude (default)\n:SM eigenvalues of smallest magnitude\n:LR eigenvalues of largest real part\n:SR eigenvalues of smallest real part\n:LI eigenvalues of largest imaginary part (nonsymmetric or complex A only)\n:SI eigenvalues of smallest imaginary part (nonsymmetric or complex A only)\n:BE compute half of the eigenvalues from each end of the spectrum, biased in favor of the high end. (real symmetric A only)\n\ntol: relative tolerance used in the convergence criterion for eigenvalues, similar to tol in the eigs(A) method for the ordinary eigenvalue problem, but effectively for the eigenvalues of B^-1 A instead of A. See the documentation for the ordinary eigenvalue problem in eigs(A) and the accompanying note about tol.\nmaxiter: Maximum number of iterations (default = 300)\nsigma: Specifies the level shift used in inverse iteration. If nothing (default), defaults to ordinary (forward) iterations. Otherwise, find eigenvalues close to sigma using shift and invert iterations.\nritzvec: Returns the Ritz vectors v (eigenvectors) if true\nv0: starting vector from which to start the iterations\n\neigs returns the nev requested eigenvalues in d, the corresponding Ritz vectors v (only if ritzvec=true), the number of converged eigenvalues nconv, the number of iterations niter and the number of matrix vector multiplications nmult, as well as the final residual vector resid.\n\nExample\n\njulia> A = speye(4, 4); B = spdiagm(1:4);\n\njulia> λ, ϕ = eigs(A, B, nev = 2);\n\njulia> λ\n2-element Array{Float64,1}:\n 1.0\n 0.5\n\nnote: Note\nThe sigma and which keywords interact: the description of eigenvalues searched for by which do not necessarily refer to the eigenvalue problem Av = Bvlambda, but rather the linear operator constructed by the specification of the iteration mode implied by sigma.sigma iteration mode which refers to the problem\nnothing ordinary (forward) Av = Bvlambda\nreal or complex inverse with level shift sigma (A - sigma B )^-1B = vnu\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.svds", - "page": "Linear Algebra", - "title": "Base.LinAlg.svds", - "category": "function", - "text": "svds(A; nsv=6, ritzvec=true, tol=0.0, maxiter=1000, ncv=2*nsv, u0=zeros((0,)), v0=zeros((0,))) -> (SVD([left_sv,] s, [right_sv,]), nconv, niter, nmult, resid)\n\nComputes the largest singular values s of A using implicitly restarted Lanczos iterations derived from eigs.\n\nInputs\n\nA: Linear operator whose singular values are desired. A may be represented as a subtype of AbstractArray, e.g., a sparse matrix, or any other type supporting the four methods size(A), eltype(A), A * vector, and A\' * vector.\nnsv: Number of singular values. Default: 6.\nritzvec: If true, return the left and right singular vectors left_sv and right_sv. If false, omit the singular vectors. Default: true.\ntol: tolerance, see eigs.\nmaxiter: Maximum number of iterations, see eigs. Default: 1000.\nncv: Maximum size of the Krylov subspace, see eigs (there called nev). Default: 2*nsv.\nu0: Initial guess for the first left Krylov vector. It may have length m (the first dimension of A), or 0.\nv0: Initial guess for the first right Krylov vector. It may have length n (the second dimension of A), or 0.\n\nOutputs\n\nsvd: An SVD object containing the left singular vectors, the requested values, and the right singular vectors. If ritzvec = false, the left and right singular vectors will be empty.\nnconv: Number of converged singular values.\nniter: Number of iterations.\nnmult: Number of matrix–vector products used.\nresid: Final residual vector.\n\nExample\n\njulia> A = spdiagm(1:4);\n\njulia> s = svds(A, nsv = 2)[1];\n\njulia> s[:S]\n2-element Array{Float64,1}:\n 4.0\n 3.0\n\nnote: Implementation\nsvds(A) is formally equivalent to calling eigs to perform implicitly restarted Lanczos tridiagonalization on the Hermitian matrix beginpmatrix 0 A^prime A 0 endpmatrix, whose eigenvalues are plus and minus the singular values of A.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.peakflops", - "page": "Linear Algebra", - "title": "Base.LinAlg.peakflops", - "category": "function", - "text": "peakflops(n::Integer=2000; parallel::Bool=false)\n\npeakflops computes the peak flop rate of the computer by using double precision gemm!. By default, if no arguments are specified, it multiplies a matrix of size n x n, where n = 2000. If the underlying BLAS is using multiple threads, higher flop rates are realized. The number of BLAS threads can be set with BLAS.set_num_threads(n).\n\nIf the keyword argument parallel is set to true, peakflops is run in parallel on all the worker processors. The flop rate of the entire parallel computer is returned. When running in parallel, only 1 BLAS thread is used. The argument n still refers to the size of the problem that is solved on each processor.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Standard-Functions-1", - "page": "Linear Algebra", - "title": "Standard Functions", - "category": "section", - "text": "Linear algebra functions in Julia are largely implemented by calling functions from LAPACK. Sparse factorizations call functions from SuiteSparse.Base.:*(::AbstractArray, ::AbstractArray)\nBase.:\\(::AbstractArray, ::Any)\nBase.LinAlg.dot\nBase.LinAlg.vecdot\nBase.LinAlg.cross\nBase.LinAlg.factorize\nBase.LinAlg.Diagonal\nBase.LinAlg.Bidiagonal\nBase.LinAlg.SymTridiagonal\nBase.LinAlg.Tridiagonal\nBase.LinAlg.Symmetric\nBase.LinAlg.Hermitian\nBase.LinAlg.LowerTriangular\nBase.LinAlg.UpperTriangular\nBase.LinAlg.lu\nBase.LinAlg.lufact\nBase.LinAlg.lufact!\nBase.LinAlg.chol\nBase.LinAlg.cholfact\nBase.LinAlg.cholfact!\nBase.LinAlg.lowrankupdate\nBase.LinAlg.lowrankdowndate\nBase.LinAlg.lowrankupdate!\nBase.LinAlg.lowrankdowndate!\nBase.LinAlg.ldltfact\nBase.LinAlg.ldltfact!\nBase.LinAlg.qr\nBase.LinAlg.qr!\nBase.LinAlg.qrfact\nBase.LinAlg.qrfact!\nBase.LinAlg.QR\nBase.LinAlg.QRCompactWY\nBase.LinAlg.QRPivoted\nBase.LinAlg.lqfact!\nBase.LinAlg.lqfact\nBase.LinAlg.lq\nBase.LinAlg.bkfact\nBase.LinAlg.bkfact!\nBase.LinAlg.eig\nBase.LinAlg.eigvals\nBase.LinAlg.eigvals!\nBase.LinAlg.eigmax\nBase.LinAlg.eigmin\nBase.LinAlg.eigvecs\nBase.LinAlg.eigfact\nBase.LinAlg.eigfact!\nBase.LinAlg.hessfact\nBase.LinAlg.hessfact!\nBase.LinAlg.schurfact\nBase.LinAlg.schurfact!\nBase.LinAlg.schur\nBase.LinAlg.ordschur\nBase.LinAlg.ordschur!\nBase.LinAlg.svdfact\nBase.LinAlg.svdfact!\nBase.LinAlg.svd\nBase.LinAlg.svdvals\nBase.LinAlg.Givens\nBase.LinAlg.givens\nBase.LinAlg.triu\nBase.LinAlg.triu!\nBase.LinAlg.tril\nBase.LinAlg.tril!\nBase.LinAlg.diagind\nBase.LinAlg.diag\nBase.LinAlg.diagm\nBase.LinAlg.scale!\nBase.LinAlg.rank\nBase.LinAlg.norm\nBase.LinAlg.vecnorm\nBase.LinAlg.normalize!\nBase.LinAlg.normalize\nBase.LinAlg.cond\nBase.LinAlg.condskeel\nBase.LinAlg.trace\nBase.LinAlg.det\nBase.LinAlg.logdet\nBase.LinAlg.logabsdet\nBase.inv\nBase.LinAlg.pinv\nBase.LinAlg.nullspace\nBase.repmat\nBase.repeat\nBase.kron\nBase.SparseArrays.blkdiag\nBase.LinAlg.linreg\nBase.LinAlg.expm\nBase.LinAlg.logm\nBase.LinAlg.sqrtm\nBase.LinAlg.lyap\nBase.LinAlg.sylvester\nBase.LinAlg.issymmetric\nBase.LinAlg.isposdef\nBase.LinAlg.isposdef!\nBase.LinAlg.istril\nBase.LinAlg.istriu\nBase.LinAlg.isdiag\nBase.LinAlg.ishermitian\nBase.LinAlg.RowVector\nBase.LinAlg.ConjArray\nBase.transpose\nBase.transpose!\nBase.ctranspose\nBase.ctranspose!\nBase.LinAlg.eigs(::Any)\nBase.LinAlg.eigs(::Any, ::Any)\nBase.LinAlg.svds\nBase.LinAlg.peakflops" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.A_ldiv_B!", - "page": "Linear Algebra", - "title": "Base.LinAlg.A_ldiv_B!", - "category": "function", - "text": "A_ldiv_B!([Y,] A, B) -> Y\n\nCompute A \\ B in-place and store the result in Y, returning the result. If only two arguments are passed, then A_ldiv_B!(A, B) overwrites B with the result.\n\nThe argument A should not be a matrix. Rather, instead of matrices it should be a factorization object (e.g. produced by factorize or cholfact). The reason for this is that factorization itself is both expensive and typically allocates memory (although it can also be done in-place via, e.g., lufact!), and performance-critical situations requiring A_ldiv_B! usually also require fine-grained control over the factorization of A.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.A_ldiv_Bc", - "page": "Linear Algebra", - "title": "Base.A_ldiv_Bc", - "category": "function", - "text": "A_ldiv_Bc(A, B)\n\nFor matrices or vectors A and B, calculates A \\ B.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.A_ldiv_Bt", - "page": "Linear Algebra", - "title": "Base.A_ldiv_Bt", - "category": "function", - "text": "A_ldiv_Bt(A, B)\n\nFor matrices or vectors A and B, calculates A \\ B.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.A_mul_B!", - "page": "Linear Algebra", - "title": "Base.LinAlg.A_mul_B!", - "category": "function", - "text": "A_mul_B!(Y, A, B) -> Y\n\nCalculates the matrix-matrix or matrix-vector product AB and stores the result in Y, overwriting the existing value of Y. Note that Y must not be aliased with either A or B.\n\nExample\n\njulia> A=[1.0 2.0; 3.0 4.0]; B=[1.0 1.0; 1.0 1.0]; Y = similar(B); A_mul_B!(Y, A, B);\n\njulia> Y\n2×2 Array{Float64,2}:\n 3.0 3.0\n 7.0 7.0\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.A_mul_Bc", - "page": "Linear Algebra", - "title": "Base.A_mul_Bc", - "category": "function", - "text": "A_mul_Bc(A, B)\n\nFor matrices or vectors A and B, calculates AB.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.A_mul_Bt", - "page": "Linear Algebra", - "title": "Base.A_mul_Bt", - "category": "function", - "text": "A_mul_Bt(A, B)\n\nFor matrices or vectors A and B, calculates AB.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.A_rdiv_Bc", - "page": "Linear Algebra", - "title": "Base.A_rdiv_Bc", - "category": "function", - "text": "A_rdiv_Bc(A, B)\n\nFor matrices or vectors A and B, calculates A B.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.A_rdiv_Bt", - "page": "Linear Algebra", - "title": "Base.A_rdiv_Bt", - "category": "function", - "text": "A_rdiv_Bt(A, B)\n\nFor matrices or vectors A and B, calculates A B.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.Ac_ldiv_B", - "page": "Linear Algebra", - "title": "Base.Ac_ldiv_B", - "category": "function", - "text": "Ac_ldiv_B(A, B)\n\nFor matrices or vectors A and B, calculates A \\ B.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.Ac_ldiv_B!", - "page": "Linear Algebra", - "title": "Base.LinAlg.Ac_ldiv_B!", - "category": "function", - "text": "Ac_ldiv_B!([Y,] A, B) -> Y\n\nSimilar to A_ldiv_B!, but return A \\ B, computing the result in-place in Y (or overwriting B if Y is not supplied).\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.Ac_ldiv_Bc", - "page": "Linear Algebra", - "title": "Base.Ac_ldiv_Bc", - "category": "function", - "text": "Ac_ldiv_Bc(A, B)\n\nFor matrices or vectors A and B, calculates A \\ B.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.Ac_mul_B", - "page": "Linear Algebra", - "title": "Base.Ac_mul_B", - "category": "function", - "text": "Ac_mul_B(A, B)\n\nFor matrices or vectors A and B, calculates AB.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.Ac_mul_Bc", - "page": "Linear Algebra", - "title": "Base.Ac_mul_Bc", - "category": "function", - "text": "Ac_mul_Bc(A, B)\n\nFor matrices or vectors A and B, calculates A B.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.Ac_rdiv_B", - "page": "Linear Algebra", - "title": "Base.Ac_rdiv_B", - "category": "function", - "text": "Ac_rdiv_B(A, B)\n\nFor matrices or vectors A and B, calculates A B.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.Ac_rdiv_Bc", - "page": "Linear Algebra", - "title": "Base.Ac_rdiv_Bc", - "category": "function", - "text": "Ac_rdiv_Bc(A, B)\n\nFor matrices or vectors A and B, calculates A B.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.At_ldiv_B", - "page": "Linear Algebra", - "title": "Base.At_ldiv_B", - "category": "function", - "text": "At_ldiv_B(A, B)\n\nFor matrices or vectors A and B, calculates A \\ B.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.At_ldiv_B!", - "page": "Linear Algebra", - "title": "Base.LinAlg.At_ldiv_B!", - "category": "function", - "text": "At_ldiv_B!([Y,] A, B) -> Y\n\nSimilar to A_ldiv_B!, but return A \\ B, computing the result in-place in Y (or overwriting B if Y is not supplied).\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.At_ldiv_Bt", - "page": "Linear Algebra", - "title": "Base.At_ldiv_Bt", - "category": "function", - "text": "At_ldiv_Bt(A, B)\n\nFor matrices or vectors A and B, calculates A \\ B.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.At_mul_B", - "page": "Linear Algebra", - "title": "Base.At_mul_B", - "category": "function", - "text": "At_mul_B(A, B)\n\nFor matrices or vectors A and B, calculates AB.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.At_mul_Bt", - "page": "Linear Algebra", - "title": "Base.At_mul_Bt", - "category": "function", - "text": "At_mul_Bt(A, B)\n\nFor matrices or vectors A and B, calculates AB.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.At_rdiv_B", - "page": "Linear Algebra", - "title": "Base.At_rdiv_B", - "category": "function", - "text": "At_rdiv_B(A, B)\n\nFor matrices or vectors A and B, calculates A B.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.At_rdiv_Bt", - "page": "Linear Algebra", - "title": "Base.At_rdiv_Bt", - "category": "function", - "text": "At_rdiv_Bt(A, B)\n\nFor matrices or vectors A and B, calculates A B.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Low-level-matrix-operations-1", - "page": "Linear Algebra", - "title": "Low-level matrix operations", - "category": "section", - "text": "Matrix operations involving transpositions operations like A\' \\ B are converted by the Julia parser into calls to specially named functions like Ac_ldiv_B. If you want to overload these operations for your own types, then it is useful to know the names of these functions.Also, in many cases there are in-place versions of matrix operations that allow you to supply a pre-allocated output vector or matrix. This is useful when optimizing critical code in order to avoid the overhead of repeated allocations. These in-place operations are suffixed with ! below (e.g. A_mul_B!) according to the usual Julia convention.Base.LinAlg.A_ldiv_B!\nBase.A_ldiv_Bc\nBase.A_ldiv_Bt\nBase.LinAlg.A_mul_B!\nBase.A_mul_Bc\nBase.A_mul_Bt\nBase.A_rdiv_Bc\nBase.A_rdiv_Bt\nBase.Ac_ldiv_B\nBase.LinAlg.Ac_ldiv_B!\nBase.Ac_ldiv_Bc\nBase.Ac_mul_B\nBase.Ac_mul_Bc\nBase.Ac_rdiv_B\nBase.Ac_rdiv_Bc\nBase.At_ldiv_B\nBase.LinAlg.At_ldiv_B!\nBase.At_ldiv_Bt\nBase.At_mul_B\nBase.At_mul_Bt\nBase.At_rdiv_B\nBase.At_rdiv_Bt" -}, - -{ - "location": "stdlib/linalg.html#BLAS-Functions-1", - "page": "Linear Algebra", - "title": "BLAS Functions", - "category": "section", - "text": "In Julia (as in much of scientific computation), dense linear-algebra operations are based on the LAPACK library, which in turn is built on top of basic linear-algebra building-blocks known as the BLAS. There are highly optimized implementations of BLAS available for every computer architecture, and sometimes in high-performance linear algebra routines it is useful to call the BLAS functions directly.Base.LinAlg.BLAS provides wrappers for some of the BLAS functions. Those BLAS functions that overwrite one of the input arrays have names ending in \'!\'. Usually, a BLAS function has four methods defined, for Float64, Float32, Complex128, and Complex64 arrays." -}, - -{ - "location": "stdlib/linalg.html#stdlib-blas-chars-1", - "page": "Linear Algebra", - "title": "BLAS Character Arguments", - "category": "section", - "text": "Many BLAS functions accept arguments that determine whether to transpose an argument (trans), which triangle of a matrix to reference (uplo or ul), whether the diagonal of a triangular matrix can be assumed to be all ones (dA) or which side of a matrix multiplication the input argument belongs on (side). The possiblities are:" -}, - -{ - "location": "stdlib/linalg.html#stdlib-blas-side-1", - "page": "Linear Algebra", - "title": "Multplication Order", - "category": "section", - "text": "side Meaning\n\'L\' The argument goes on the left side of a matrix-matrix operation.\n\'R\' The argument goes on the right side of a matrix-matrix operation." -}, - -{ - "location": "stdlib/linalg.html#stdlib-blas-uplo-1", - "page": "Linear Algebra", - "title": "Triangle Referencing", - "category": "section", - "text": "uplo/ul Meaning\n\'U\' Only the upper triangle of the matrix will be used.\n\'L\' Only the lower triangle of the matrix will be used." -}, - -{ - "location": "stdlib/linalg.html#stdlib-blas-trans-1", - "page": "Linear Algebra", - "title": "Transposition Operation", - "category": "section", - "text": "trans/tX Meaning\n\'N\' The input matrix X is not transposed or conjugated.\n\'T\' The input matrix X will be transposed.\n\'C\' The input matrix X will be conjugated and transposed." -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.BLAS.dotu", - "page": "Linear Algebra", - "title": "Base.LinAlg.BLAS.dotu", - "category": "function", - "text": "dotu(n, X, incx, Y, incy)\n\nDot function for two complex vectors consisting of n elements of array X with stride incx and n elements of array Y with stride incy.\n\nExample:\n\njulia> Base.BLAS.dotu(10, im*ones(10), 1, complex.(ones(20), ones(20)), 2)\n-10.0 + 10.0im\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.BLAS.dotc", - "page": "Linear Algebra", - "title": "Base.LinAlg.BLAS.dotc", - "category": "function", - "text": "dotc(n, X, incx, U, incy)\n\nDot function for two complex vectors, consisting of n elements of array X with stride incx and n elements of array U with stride incy, conjugating the first vector.\n\nExample:\n\njulia> Base.BLAS.dotc(10, im*ones(10), 1, complex.(ones(20), ones(20)), 2)\n10.0 - 10.0im\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.BLAS.blascopy!", - "page": "Linear Algebra", - "title": "Base.LinAlg.BLAS.blascopy!", - "category": "function", - "text": "blascopy!(n, X, incx, Y, incy)\n\nCopy n elements of array X with stride incx to array Y with stride incy. Returns Y.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.BLAS.nrm2", - "page": "Linear Algebra", - "title": "Base.LinAlg.BLAS.nrm2", - "category": "function", - "text": "nrm2(n, X, incx)\n\n2-norm of a vector consisting of n elements of array X with stride incx.\n\nExample:\n\njulia> Base.BLAS.nrm2(4, ones(8), 2)\n2.0\n\njulia> Base.BLAS.nrm2(1, ones(8), 2)\n1.0\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.BLAS.asum", - "page": "Linear Algebra", - "title": "Base.LinAlg.BLAS.asum", - "category": "function", - "text": "asum(n, X, incx)\n\nSum of the absolute values of the first n elements of array X with stride incx.\n\nExample:\n\njulia> Base.BLAS.asum(5, im*ones(10), 2)\n5.0\n\njulia> Base.BLAS.asum(2, im*ones(10), 5)\n2.0\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.axpy!", - "page": "Linear Algebra", - "title": "Base.LinAlg.axpy!", - "category": "function", - "text": "axpy!(a, X, Y)\n\nOverwrite Y with a*X + Y, where a is a scalar. Returns Y.\n\nExample:\n\njulia> x = [1; 2; 3];\n\njulia> y = [4; 5; 6];\n\njulia> Base.BLAS.axpy!(2, x, y)\n3-element Array{Int64,1}:\n 6\n 9\n 12\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.BLAS.scal!", - "page": "Linear Algebra", - "title": "Base.LinAlg.BLAS.scal!", - "category": "function", - "text": "scal!(n, a, X, incx)\n\nOverwrite X with a*X for the first n elements of array X with stride incx. Returns X.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.BLAS.scal", - "page": "Linear Algebra", - "title": "Base.LinAlg.BLAS.scal", - "category": "function", - "text": "scal(n, a, X, incx)\n\nReturns X scaled by a for the first n elements of array X with stride incx.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.BLAS.ger!", - "page": "Linear Algebra", - "title": "Base.LinAlg.BLAS.ger!", - "category": "function", - "text": "ger!(alpha, x, y, A)\n\nRank-1 update of the matrix A with vectors x and y as alpha*x*y\' + A.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.BLAS.syr!", - "page": "Linear Algebra", - "title": "Base.LinAlg.BLAS.syr!", - "category": "function", - "text": "syr!(uplo, alpha, x, A)\n\nRank-1 update of the symmetric matrix A with vector x as alpha*x*x.\' + A. uplo controls which triangle of A is updated. Returns A.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.BLAS.syrk!", - "page": "Linear Algebra", - "title": "Base.LinAlg.BLAS.syrk!", - "category": "function", - "text": "syrk!(uplo, trans, alpha, A, beta, C)\n\nRank-k update of the symmetric matrix C as alpha*A*A.\' + beta*C or alpha*A.\'*A + beta*C according to trans. Only the uplo triangle of C is used. Returns C.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.BLAS.syrk", - "page": "Linear Algebra", - "title": "Base.LinAlg.BLAS.syrk", - "category": "function", - "text": "syrk(uplo, trans, alpha, A)\n\nReturns either the upper triangle or the lower triangle of A, according to uplo, of alpha*A*A.\' or alpha*A.\'*A, according to trans.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.BLAS.her!", - "page": "Linear Algebra", - "title": "Base.LinAlg.BLAS.her!", - "category": "function", - "text": "her!(uplo, alpha, x, A)\n\nMethods for complex arrays only. Rank-1 update of the Hermitian matrix A with vector x as alpha*x*x\' + A. uplo controls which triangle of A is updated. Returns A.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.BLAS.herk!", - "page": "Linear Algebra", - "title": "Base.LinAlg.BLAS.herk!", - "category": "function", - "text": "herk!(uplo, trans, alpha, A, beta, C)\n\nMethods for complex arrays only. Rank-k update of the Hermitian matrix C as alpha*A*A\' + beta*C or alpha*A\'*A + beta*C according to trans. Only the uplo triangle of C is updated. Returns C.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.BLAS.herk", - "page": "Linear Algebra", - "title": "Base.LinAlg.BLAS.herk", - "category": "function", - "text": "herk(uplo, trans, alpha, A)\n\nMethods for complex arrays only. Returns the uplo triangle of alpha*A*A\' or alpha*A\'*A, according to trans.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.BLAS.gbmv!", - "page": "Linear Algebra", - "title": "Base.LinAlg.BLAS.gbmv!", - "category": "function", - "text": "gbmv!(trans, m, kl, ku, alpha, A, x, beta, y)\n\nUpdate vector y as alpha*A*x + beta*y or alpha*A\'*x + beta*y according to trans. The matrix A is a general band matrix of dimension m by size(A,2) with kl sub-diagonals and ku super-diagonals. alpha and beta are scalars. Returns the updated y.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.BLAS.gbmv", - "page": "Linear Algebra", - "title": "Base.LinAlg.BLAS.gbmv", - "category": "function", - "text": "gbmv(trans, m, kl, ku, alpha, A, x)\n\nReturns alpha*A*x or alpha*A\'*x according to trans. The matrix A is a general band matrix of dimension m by size(A,2) with kl sub-diagonals and ku super-diagonals, and alpha is a scalar.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.BLAS.sbmv!", - "page": "Linear Algebra", - "title": "Base.LinAlg.BLAS.sbmv!", - "category": "function", - "text": "sbmv!(uplo, k, alpha, A, x, beta, y)\n\nUpdate vector y as alpha*A*x + beta*y where A is a a symmetric band matrix of order size(A,2) with k super-diagonals stored in the argument A. The storage layout for A is described the reference BLAS module, level-2 BLAS at http://www.netlib.org/lapack/explore-html/. Only the uplo triangle of A is used.\n\nReturns the updated y.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.BLAS.sbmv-NTuple{5,Any}", - "page": "Linear Algebra", - "title": "Base.LinAlg.BLAS.sbmv", - "category": "method", - "text": "sbmv(uplo, k, alpha, A, x)\n\nReturns alpha*A*x where A is a symmetric band matrix of order size(A,2) with k super-diagonals stored in the argument A. Only the uplo triangle of A is used.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.BLAS.sbmv-NTuple{4,Any}", - "page": "Linear Algebra", - "title": "Base.LinAlg.BLAS.sbmv", - "category": "method", - "text": "sbmv(uplo, k, A, x)\n\nReturns A*x where A is a symmetric band matrix of order size(A,2) with k super-diagonals stored in the argument A. Only the uplo triangle of A is used.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.BLAS.gemm!", - "page": "Linear Algebra", - "title": "Base.LinAlg.BLAS.gemm!", - "category": "function", - "text": "gemm!(tA, tB, alpha, A, B, beta, C)\n\nUpdate C as alpha*A*B + beta*C or the other three variants according to tA and tB. Returns the updated C.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.BLAS.gemm-NTuple{5,Any}", - "page": "Linear Algebra", - "title": "Base.LinAlg.BLAS.gemm", - "category": "method", - "text": "gemm(tA, tB, alpha, A, B)\n\nReturns alpha*A*B or the other three variants according to tA and tB.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.BLAS.gemm-NTuple{4,Any}", - "page": "Linear Algebra", - "title": "Base.LinAlg.BLAS.gemm", - "category": "method", - "text": "gemm(tA, tB, A, B)\n\nReturns A*B or the other three variants according to tA and tB.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.BLAS.gemv!", - "page": "Linear Algebra", - "title": "Base.LinAlg.BLAS.gemv!", - "category": "function", - "text": "gemv!(tA, alpha, A, x, beta, y)\n\nUpdate the vector y as alpha*A*x + beta*y or alpha*A\'x + beta*y according to tA. alpha and beta are scalars. Returns the updated y.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.BLAS.gemv-NTuple{4,Any}", - "page": "Linear Algebra", - "title": "Base.LinAlg.BLAS.gemv", - "category": "method", - "text": "gemv(tA, alpha, A, x)\n\nReturns alpha*A*x or alpha*A\'x according to tA. alpha is a scalar.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.BLAS.gemv-Tuple{Any,Any,Any}", - "page": "Linear Algebra", - "title": "Base.LinAlg.BLAS.gemv", - "category": "method", - "text": "gemv(tA, A, x)\n\nReturns A*x or A\'x according to tA.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.BLAS.symm!", - "page": "Linear Algebra", - "title": "Base.LinAlg.BLAS.symm!", - "category": "function", - "text": "symm!(side, ul, alpha, A, B, beta, C)\n\nUpdate C as alpha*A*B + beta*C or alpha*B*A + beta*C according to side. A is assumed to be symmetric. Only the ul triangle of A is used. Returns the updated C.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.BLAS.symm-NTuple{5,Any}", - "page": "Linear Algebra", - "title": "Base.LinAlg.BLAS.symm", - "category": "method", - "text": "symm(side, ul, alpha, A, B)\n\nReturns alpha*A*B or alpha*B*A according to side. A is assumed to be symmetric. Only the ul triangle of A is used.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.BLAS.symm-NTuple{4,Any}", - "page": "Linear Algebra", - "title": "Base.LinAlg.BLAS.symm", - "category": "method", - "text": "symm(side, ul, A, B)\n\nReturns A*B or B*A according to side. A is assumed to be symmetric. Only the ul triangle of A is used.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.BLAS.symv!", - "page": "Linear Algebra", - "title": "Base.LinAlg.BLAS.symv!", - "category": "function", - "text": "symv!(ul, alpha, A, x, beta, y)\n\nUpdate the vector y as alpha*A*x + beta*y. A is assumed to be symmetric. Only the ul triangle of A is used. alpha and beta are scalars. Returns the updated y.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.BLAS.symv-NTuple{4,Any}", - "page": "Linear Algebra", - "title": "Base.LinAlg.BLAS.symv", - "category": "method", - "text": "symv(ul, alpha, A, x)\n\nReturns alpha*A*x. A is assumed to be symmetric. Only the ul triangle of A is used. alpha is a scalar.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.BLAS.symv-Tuple{Any,Any,Any}", - "page": "Linear Algebra", - "title": "Base.LinAlg.BLAS.symv", - "category": "method", - "text": "symv(ul, A, x)\n\nReturns A*x. A is assumed to be symmetric. Only the ul triangle of A is used.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.BLAS.trmm!", - "page": "Linear Algebra", - "title": "Base.LinAlg.BLAS.trmm!", - "category": "function", - "text": "trmm!(side, ul, tA, dA, alpha, A, B)\n\nUpdate B as alpha*A*B or one of the other three variants determined by side and tA. Only the ul triangle of A is used. dA determines if the diagonal values are read or are assumed to be all ones. Returns the updated B.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.BLAS.trmm", - "page": "Linear Algebra", - "title": "Base.LinAlg.BLAS.trmm", - "category": "function", - "text": "trmm(side, ul, tA, dA, alpha, A, B)\n\nReturns alpha*A*B or one of the other three variants determined by side and tA. Only the ul triangle of A is used. dA determines if the diagonal values are read or are assumed to be all ones.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.BLAS.trsm!", - "page": "Linear Algebra", - "title": "Base.LinAlg.BLAS.trsm!", - "category": "function", - "text": "trsm!(side, ul, tA, dA, alpha, A, B)\n\nOverwrite B with the solution to A*X = alpha*B or one of the other three variants determined by side and tA. Only the ul triangle of A is used. dA determines if the diagonal values are read or are assumed to be all ones. Returns the updated B.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.BLAS.trsm", - "page": "Linear Algebra", - "title": "Base.LinAlg.BLAS.trsm", - "category": "function", - "text": "trsm(side, ul, tA, dA, alpha, A, B)\n\nReturns the solution to A*X = alpha*B or one of the other three variants determined by determined by side and tA. Only the ul triangle of A is used. dA determines if the diagonal values are read or are assumed to be all ones.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.BLAS.trmv!", - "page": "Linear Algebra", - "title": "Base.LinAlg.BLAS.trmv!", - "category": "function", - "text": "trmv!(ul, tA, dA, A, b)\n\nReturns op(A)*b, where op is determined by tA. Only the ul triangle of A is used. dA determines if the diagonal values are read or are assumed to be all ones. The multiplication occurs in-place on b.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.BLAS.trmv", - "page": "Linear Algebra", - "title": "Base.LinAlg.BLAS.trmv", - "category": "function", - "text": "trmv(ul, tA, dA, A, b)\n\nReturns op(A)*b, where op is determined by tA. Only the ul triangle of A is used. dA determines if the diagonal values are read or are assumed to be all ones.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.BLAS.trsv!", - "page": "Linear Algebra", - "title": "Base.LinAlg.BLAS.trsv!", - "category": "function", - "text": "trsv!(ul, tA, dA, A, b)\n\nOverwrite b with the solution to A*x = b or one of the other two variants determined by tA and ul. dA determines if the diagonal values are read or are assumed to be all ones. Returns the updated b.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.BLAS.trsv", - "page": "Linear Algebra", - "title": "Base.LinAlg.BLAS.trsv", - "category": "function", - "text": "trsv(ul, tA, dA, A, b)\n\nReturns the solution to A*x = b or one of the other two variants determined by tA and ul. dA determines if the diagonal values are read or are assumed to be all ones.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.BLAS.set_num_threads", - "page": "Linear Algebra", - "title": "Base.LinAlg.BLAS.set_num_threads", - "category": "function", - "text": "set_num_threads(n)\n\nSet the number of threads the BLAS library should use.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.I", - "page": "Linear Algebra", - "title": "Base.LinAlg.I", - "category": "constant", - "text": "I\n\nAn object of type UniformScaling, representing an identity matrix of any size.\n\nExample\n\njulia> ones(5, 6) * I == ones(5, 6)\ntrue\n\njulia> [1 2im 3; 1im 2 3] * I\n2×3 Array{Complex{Int64},2}:\n 1+0im 0+2im 3+0im\n 0+1im 2+0im 3+0im\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#stdlib-blas-diag-1", - "page": "Linear Algebra", - "title": "Unit Diagonal", - "category": "section", - "text": "diag/dX Meaning\n\'N\' The diagonal values of the matrix X will be read.\n\'U\' The diagonal of the matrix X is assumed to be all ones.Base.LinAlg.BLAS.dotu\nBase.LinAlg.BLAS.dotc\nBase.LinAlg.BLAS.blascopy!\nBase.LinAlg.BLAS.nrm2\nBase.LinAlg.BLAS.asum\nBase.LinAlg.axpy!\nBase.LinAlg.BLAS.scal!\nBase.LinAlg.BLAS.scal\nBase.LinAlg.BLAS.ger!\nBase.LinAlg.BLAS.syr!\nBase.LinAlg.BLAS.syrk!\nBase.LinAlg.BLAS.syrk\nBase.LinAlg.BLAS.her!\nBase.LinAlg.BLAS.herk!\nBase.LinAlg.BLAS.herk\nBase.LinAlg.BLAS.gbmv!\nBase.LinAlg.BLAS.gbmv\nBase.LinAlg.BLAS.sbmv!\nBase.LinAlg.BLAS.sbmv(::Any, ::Any, ::Any, ::Any, ::Any)\nBase.LinAlg.BLAS.sbmv(::Any, ::Any, ::Any, ::Any)\nBase.LinAlg.BLAS.gemm!\nBase.LinAlg.BLAS.gemm(::Any, ::Any, ::Any, ::Any, ::Any)\nBase.LinAlg.BLAS.gemm(::Any, ::Any, ::Any, ::Any)\nBase.LinAlg.BLAS.gemv!\nBase.LinAlg.BLAS.gemv(::Any, ::Any, ::Any, ::Any)\nBase.LinAlg.BLAS.gemv(::Any, ::Any, ::Any)\nBase.LinAlg.BLAS.symm!\nBase.LinAlg.BLAS.symm(::Any, ::Any, ::Any, ::Any, ::Any)\nBase.LinAlg.BLAS.symm(::Any, ::Any, ::Any, ::Any)\nBase.LinAlg.BLAS.symv!\nBase.LinAlg.BLAS.symv(::Any, ::Any, ::Any, ::Any)\nBase.LinAlg.BLAS.symv(::Any, ::Any, ::Any)\nBase.LinAlg.BLAS.trmm!\nBase.LinAlg.BLAS.trmm\nBase.LinAlg.BLAS.trsm!\nBase.LinAlg.BLAS.trsm\nBase.LinAlg.BLAS.trmv!\nBase.LinAlg.BLAS.trmv\nBase.LinAlg.BLAS.trsv!\nBase.LinAlg.BLAS.trsv\nBase.LinAlg.BLAS.set_num_threads\nBase.LinAlg.I" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.LAPACK.gbtrf!", - "page": "Linear Algebra", - "title": "Base.LinAlg.LAPACK.gbtrf!", - "category": "function", - "text": "gbtrf!(kl, ku, m, AB) -> (AB, ipiv)\n\nCompute the LU factorization of a banded matrix AB. kl is the first subdiagonal containing a nonzero band, ku is the last superdiagonal containing one, and m is the first dimension of the matrix AB. Returns the LU factorization in-place and ipiv, the vector of pivots used.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.LAPACK.gbtrs!", - "page": "Linear Algebra", - "title": "Base.LinAlg.LAPACK.gbtrs!", - "category": "function", - "text": "gbtrs!(trans, kl, ku, m, AB, ipiv, B)\n\nSolve the equation AB * X = B. trans determines the orientation of AB. It may be N (no transpose), T (transpose), or C (conjugate transpose). kl is the first subdiagonal containing a nonzero band, ku is the last superdiagonal containing one, and m is the first dimension of the matrix AB. ipiv is the vector of pivots returned from gbtrf!. Returns the vector or matrix X, overwriting B in-place.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.LAPACK.gebal!", - "page": "Linear Algebra", - "title": "Base.LinAlg.LAPACK.gebal!", - "category": "function", - "text": "gebal!(job, A) -> (ilo, ihi, scale)\n\nBalance the matrix A before computing its eigensystem or Schur factorization. job can be one of N (A will not be permuted or scaled), P (A will only be permuted), S (A will only be scaled), or B (A will be both permuted and scaled). Modifies A in-place and returns ilo, ihi, and scale. If permuting was turned on, A[i,j] = 0 if j > i and 1 < j < ilo or j > ihi. scale contains information about the scaling/permutations performed.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.LAPACK.gebak!", - "page": "Linear Algebra", - "title": "Base.LinAlg.LAPACK.gebak!", - "category": "function", - "text": "gebak!(job, side, ilo, ihi, scale, V)\n\nTransform the eigenvectors V of a matrix balanced using gebal! to the unscaled/unpermuted eigenvectors of the original matrix. Modifies V in-place. side can be L (left eigenvectors are transformed) or R (right eigenvectors are transformed).\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.LAPACK.gebrd!", - "page": "Linear Algebra", - "title": "Base.LinAlg.LAPACK.gebrd!", - "category": "function", - "text": "gebrd!(A) -> (A, d, e, tauq, taup)\n\nReduce A in-place to bidiagonal form A = QBP\'. Returns A, containing the bidiagonal matrix B; d, containing the diagonal elements of B; e, containing the off-diagonal elements of B; tauq, containing the elementary reflectors representing Q; and taup, containing the elementary reflectors representing P.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.LAPACK.gelqf!", - "page": "Linear Algebra", - "title": "Base.LinAlg.LAPACK.gelqf!", - "category": "function", - "text": "gelqf!(A, tau)\n\nCompute the LQ factorization of A, A = LQ. tau contains scalars which parameterize the elementary reflectors of the factorization. tau must have length greater than or equal to the smallest dimension of A.\n\nReturns A and tau modified in-place.\n\n\n\ngelqf!(A) -> (A, tau)\n\nCompute the LQ factorization of A, A = LQ.\n\nReturns A, modified in-place, and tau, which contains scalars which parameterize the elementary reflectors of the factorization.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.LAPACK.geqlf!", - "page": "Linear Algebra", - "title": "Base.LinAlg.LAPACK.geqlf!", - "category": "function", - "text": "geqlf!(A, tau)\n\nCompute the QL factorization of A, A = QL. tau contains scalars which parameterize the elementary reflectors of the factorization. tau must have length greater than or equal to the smallest dimension of A.\n\nReturns A and tau modified in-place.\n\n\n\ngeqlf!(A) -> (A, tau)\n\nCompute the QL factorization of A, A = QL.\n\nReturns A, modified in-place, and tau, which contains scalars which parameterize the elementary reflectors of the factorization.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.LAPACK.geqrf!", - "page": "Linear Algebra", - "title": "Base.LinAlg.LAPACK.geqrf!", - "category": "function", - "text": "geqrf!(A, tau)\n\nCompute the QR factorization of A, A = QR. tau contains scalars which parameterize the elementary reflectors of the factorization. tau must have length greater than or equal to the smallest dimension of A.\n\nReturns A and tau modified in-place.\n\n\n\ngeqrf!(A) -> (A, tau)\n\nCompute the QR factorization of A, A = QR.\n\nReturns A, modified in-place, and tau, which contains scalars which parameterize the elementary reflectors of the factorization.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.LAPACK.geqp3!", - "page": "Linear Algebra", - "title": "Base.LinAlg.LAPACK.geqp3!", - "category": "function", - "text": "geqp3!(A, jpvt, tau)\n\nCompute the pivoted QR factorization of A, AP = QR using BLAS level 3. P is a pivoting matrix, represented by jpvt. tau stores the elementary reflectors. jpvt must have length length greater than or equal to n if A is an (m x n) matrix. tau must have length greater than or equal to the smallest dimension of A.\n\nA, jpvt, and tau are modified in-place.\n\n\n\ngeqp3!(A, jpvt) -> (A, jpvt, tau)\n\nCompute the pivoted QR factorization of A, AP = QR using BLAS level 3. P is a pivoting matrix, represented by jpvt. jpvt must have length greater than or equal to n if A is an (m x n) matrix.\n\nReturns A and jpvt, modified in-place, and tau, which stores the elementary reflectors.\n\n\n\ngeqp3!(A) -> (A, jpvt, tau)\n\nCompute the pivoted QR factorization of A, AP = QR using BLAS level 3.\n\nReturns A, modified in-place, jpvt, which represents the pivoting matrix P, and tau, which stores the elementary reflectors.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.LAPACK.gerqf!", - "page": "Linear Algebra", - "title": "Base.LinAlg.LAPACK.gerqf!", - "category": "function", - "text": "gerqf!(A, tau)\n\nCompute the RQ factorization of A, A = RQ. tau contains scalars which parameterize the elementary reflectors of the factorization. tau must have length greater than or equal to the smallest dimension of A.\n\nReturns A and tau modified in-place.\n\n\n\ngerqf!(A) -> (A, tau)\n\nCompute the RQ factorization of A, A = RQ.\n\nReturns A, modified in-place, and tau, which contains scalars which parameterize the elementary reflectors of the factorization.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.LAPACK.geqrt!", - "page": "Linear Algebra", - "title": "Base.LinAlg.LAPACK.geqrt!", - "category": "function", - "text": "geqrt!(A, T)\n\nCompute the blocked QR factorization of A, A = QR. T contains upper triangular block reflectors which parameterize the elementary reflectors of the factorization. The first dimension of T sets the block size and it must be between 1 and n. The second dimension of T must equal the smallest dimension of A.\n\nReturns A and T modified in-place.\n\n\n\ngeqrt!(A, nb) -> (A, T)\n\nCompute the blocked QR factorization of A, A = QR. nb sets the block size and it must be between 1 and n, the second dimension of A.\n\nReturns A, modified in-place, and T, which contains upper triangular block reflectors which parameterize the elementary reflectors of the factorization.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.LAPACK.geqrt3!", - "page": "Linear Algebra", - "title": "Base.LinAlg.LAPACK.geqrt3!", - "category": "function", - "text": "geqrt3!(A, T)\n\nRecursively computes the blocked QR factorization of A, A = QR. T contains upper triangular block reflectors which parameterize the elementary reflectors of the factorization. The first dimension of T sets the block size and it must be between 1 and n. The second dimension of T must equal the smallest dimension of A.\n\nReturns A and T modified in-place.\n\n\n\ngeqrt3!(A) -> (A, T)\n\nRecursively computes the blocked QR factorization of A, A = QR.\n\nReturns A, modified in-place, and T, which contains upper triangular block reflectors which parameterize the elementary reflectors of the factorization.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.LAPACK.getrf!", - "page": "Linear Algebra", - "title": "Base.LinAlg.LAPACK.getrf!", - "category": "function", - "text": "getrf!(A) -> (A, ipiv, info)\n\nCompute the pivoted LU factorization of A, A = LU.\n\nReturns A, modified in-place, ipiv, the pivoting information, and an info code which indicates success (info = 0), a singular value in U (info = i, in which case U[i,i] is singular), or an error code (info < 0).\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.LAPACK.tzrzf!", - "page": "Linear Algebra", - "title": "Base.LinAlg.LAPACK.tzrzf!", - "category": "function", - "text": "tzrzf!(A) -> (A, tau)\n\nTransforms the upper trapezoidal matrix A to upper triangular form in-place. Returns A and tau, the scalar parameters for the elementary reflectors of the transformation.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.LAPACK.ormrz!", - "page": "Linear Algebra", - "title": "Base.LinAlg.LAPACK.ormrz!", - "category": "function", - "text": "ormrz!(side, trans, A, tau, C)\n\nMultiplies the matrix C by Q from the transformation supplied by tzrzf!. Depending on side or trans the multiplication can be left-sided (side = L, Q*C) or right-sided (side = R, C*Q) and Q can be unmodified (trans = N), transposed (trans = T), or conjugate transposed (trans = C). Returns matrix C which is modified in-place with the result of the multiplication.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.LAPACK.gels!", - "page": "Linear Algebra", - "title": "Base.LinAlg.LAPACK.gels!", - "category": "function", - "text": "gels!(trans, A, B) -> (F, B, ssr)\n\nSolves the linear equation A * X = B, A.\' * X =B, or A\' * X = B using a QR or LQ factorization. Modifies the matrix/vector B in place with the solution. A is overwritten with its QR or LQ factorization. trans may be one of N (no modification), T (transpose), or C (conjugate transpose). gels! searches for the minimum norm/least squares solution. A may be under or over determined. The solution is returned in B.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.LAPACK.gesv!", - "page": "Linear Algebra", - "title": "Base.LinAlg.LAPACK.gesv!", - "category": "function", - "text": "gesv!(A, B) -> (B, A, ipiv)\n\nSolves the linear equation A * X = B where A is a square matrix using the LU factorization of A. A is overwritten with its LU factorization and B is overwritten with the solution X. ipiv contains the pivoting information for the LU factorization of A.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.LAPACK.getrs!", - "page": "Linear Algebra", - "title": "Base.LinAlg.LAPACK.getrs!", - "category": "function", - "text": "getrs!(trans, A, ipiv, B)\n\nSolves the linear equation A * X = B, A.\' * X =B, or A\' * X = B for square A. Modifies the matrix/vector B in place with the solution. A is the LU factorization from getrf!, with ipiv the pivoting information. trans may be one of N (no modification), T (transpose), or C (conjugate transpose).\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.LAPACK.getri!", - "page": "Linear Algebra", - "title": "Base.LinAlg.LAPACK.getri!", - "category": "function", - "text": "getri!(A, ipiv)\n\nComputes the inverse of A, using its LU factorization found by getrf!. ipiv is the pivot information output and A contains the LU factorization of getrf!. A is overwritten with its inverse.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.LAPACK.gesvx!", - "page": "Linear Algebra", - "title": "Base.LinAlg.LAPACK.gesvx!", - "category": "function", - "text": "gesvx!(fact, trans, A, AF, ipiv, equed, R, C, B) -> (X, equed, R, C, B, rcond, ferr, berr, work)\n\nSolves the linear equation A * X = B (trans = N), A.\' * X =B (trans = T), or A\' * X = B (trans = C) using the LU factorization of A. fact may be E, in which case A will be equilibrated and copied to AF; F, in which case AF and ipiv from a previous LU factorization are inputs; or N, in which case A will be copied to AF and then factored. If fact = F, equed may be N, meaning A has not been equilibrated; R, meaning A was multiplied by diagm(R) from the left; C, meaning A was multiplied by diagm(C) from the right; or B, meaning A was multiplied by diagm(R) from the left and diagm(C) from the right. If fact = F and equed = R or B the elements of R must all be positive. If fact = F and equed = C or B the elements of C must all be positive.\n\nReturns the solution X; equed, which is an output if fact is not N, and describes the equilibration that was performed; R, the row equilibration diagonal; C, the column equilibration diagonal; B, which may be overwritten with its equilibrated form diagm(R)*B (if trans = N and equed = R,B) or diagm(C)*B (if trans = T,C and equed = C,B); rcond, the reciprocal condition number of A after equilbrating; ferr, the forward error bound for each solution vector in X; berr, the forward error bound for each solution vector in X; and work, the reciprocal pivot growth factor.\n\n\n\ngesvx!(A, B)\n\nThe no-equilibration, no-transpose simplification of gesvx!.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.LAPACK.gelsd!", - "page": "Linear Algebra", - "title": "Base.LinAlg.LAPACK.gelsd!", - "category": "function", - "text": "gelsd!(A, B, rcond) -> (B, rnk)\n\nComputes the least norm solution of A * X = B by finding the SVD factorization of A, then dividing-and-conquering the problem. B is overwritten with the solution X. Singular values below rcond will be treated as zero. Returns the solution in B and the effective rank of A in rnk.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.LAPACK.gelsy!", - "page": "Linear Algebra", - "title": "Base.LinAlg.LAPACK.gelsy!", - "category": "function", - "text": "gelsy!(A, B, rcond) -> (B, rnk)\n\nComputes the least norm solution of A * X = B by finding the full QR factorization of A, then dividing-and-conquering the problem. B is overwritten with the solution X. Singular values below rcond will be treated as zero. Returns the solution in B and the effective rank of A in rnk.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.LAPACK.gglse!", - "page": "Linear Algebra", - "title": "Base.LinAlg.LAPACK.gglse!", - "category": "function", - "text": "gglse!(A, c, B, d) -> (X,res)\n\nSolves the equation A * x = c where x is subject to the equality constraint B * x = d. Uses the formula ||c - A*x||^2 = 0 to solve. Returns X and the residual sum-of-squares.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.LAPACK.geev!", - "page": "Linear Algebra", - "title": "Base.LinAlg.LAPACK.geev!", - "category": "function", - "text": "geev!(jobvl, jobvr, A) -> (W, VL, VR)\n\nFinds the eigensystem of A. If jobvl = N, the left eigenvectors of A aren\'t computed. If jobvr = N, the right eigenvectors of A aren\'t computed. If jobvl = V or jobvr = V, the corresponding eigenvectors are computed. Returns the eigenvalues in W, the right eigenvectors in VR, and the left eigenvectors in VL.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.LAPACK.gesdd!", - "page": "Linear Algebra", - "title": "Base.LinAlg.LAPACK.gesdd!", - "category": "function", - "text": "gesdd!(job, A) -> (U, S, VT)\n\nFinds the singular value decomposition of A, A = U * S * V\', using a divide and conquer approach. If job = A, all the columns of U and the rows of V\' are computed. If job = N, no columns of U or rows of V\' are computed. If job = O, A is overwritten with the columns of (thin) U and the rows of (thin) V\'. If job = S, the columns of (thin) U and the rows of (thin) V\' are computed and returned separately.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.LAPACK.gesvd!", - "page": "Linear Algebra", - "title": "Base.LinAlg.LAPACK.gesvd!", - "category": "function", - "text": "gesvd!(jobu, jobvt, A) -> (U, S, VT)\n\nFinds the singular value decomposition of A, A = U * S * V\'. If jobu = A, all the columns of U are computed. If jobvt = A all the rows of V\' are computed. If jobu = N, no columns of U are computed. If jobvt = N no rows of V\' are computed. If jobu = O, A is overwritten with the columns of (thin) U. If jobvt = O, A is overwritten with the rows of (thin) V\'. If jobu = S, the columns of (thin) U are computed and returned separately. If jobvt = S the rows of (thin) V\' are computed and returned separately. jobu and jobvt can\'t both be O.\n\nReturns U, S, and Vt, where S are the singular values of A.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.LAPACK.ggsvd!", - "page": "Linear Algebra", - "title": "Base.LinAlg.LAPACK.ggsvd!", - "category": "function", - "text": "ggsvd!(jobu, jobv, jobq, A, B) -> (U, V, Q, alpha, beta, k, l, R)\n\nFinds the generalized singular value decomposition of A and B, U\'*A*Q = D1*R and V\'*B*Q = D2*R. D1 has alpha on its diagonal and D2 has beta on its diagonal. If jobu = U, the orthogonal/unitary matrix U is computed. If jobv = V the orthogonal/unitary matrix V is computed. If jobq = Q, the orthogonal/unitary matrix Q is computed. If jobu, jobv or jobq is N, that matrix is not computed. This function is only available in LAPACK versions prior to 3.6.0.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.LAPACK.ggsvd3!", - "page": "Linear Algebra", - "title": "Base.LinAlg.LAPACK.ggsvd3!", - "category": "function", - "text": "ggsvd3!(jobu, jobv, jobq, A, B) -> (U, V, Q, alpha, beta, k, l, R)\n\nFinds the generalized singular value decomposition of A and B, U\'*A*Q = D1*R and V\'*B*Q = D2*R. D1 has alpha on its diagonal and D2 has beta on its diagonal. If jobu = U, the orthogonal/unitary matrix U is computed. If jobv = V the orthogonal/unitary matrix V is computed. If jobq = Q, the orthogonal/unitary matrix Q is computed. If jobu, jobv, or jobq is N, that matrix is not computed. This function requires LAPACK 3.6.0.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.LAPACK.geevx!", - "page": "Linear Algebra", - "title": "Base.LinAlg.LAPACK.geevx!", - "category": "function", - "text": "geevx!(balanc, jobvl, jobvr, sense, A) -> (A, w, VL, VR, ilo, ihi, scale, abnrm, rconde, rcondv)\n\nFinds the eigensystem of A with matrix balancing. If jobvl = N, the left eigenvectors of A aren\'t computed. If jobvr = N, the right eigenvectors of A aren\'t computed. If jobvl = V or jobvr = V, the corresponding eigenvectors are computed. If balanc = N, no balancing is performed. If balanc = P, A is permuted but not scaled. If balanc = S, A is scaled but not permuted. If balanc = B, A is permuted and scaled. If sense = N, no reciprocal condition numbers are computed. If sense = E, reciprocal condition numbers are computed for the eigenvalues only. If sense = V, reciprocal condition numbers are computed for the right eigenvectors only. If sense = B, reciprocal condition numbers are computed for the right eigenvectors and the eigenvectors. If sense = E,B, the right and left eigenvectors must be computed.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.LAPACK.ggev!", - "page": "Linear Algebra", - "title": "Base.LinAlg.LAPACK.ggev!", - "category": "function", - "text": "ggev!(jobvl, jobvr, A, B) -> (alpha, beta, vl, vr)\n\nFinds the generalized eigendecomposition of A and B. If jobvl = N, the left eigenvectors aren\'t computed. If jobvr = N, the right eigenvectors aren\'t computed. If jobvl = V or jobvr = V, the corresponding eigenvectors are computed.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.LAPACK.gtsv!", - "page": "Linear Algebra", - "title": "Base.LinAlg.LAPACK.gtsv!", - "category": "function", - "text": "gtsv!(dl, d, du, B)\n\nSolves the equation A * X = B where A is a tridiagonal matrix with dl on the subdiagonal, d on the diagonal, and du on the superdiagonal.\n\nOverwrites B with the solution X and returns it.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.LAPACK.gttrf!", - "page": "Linear Algebra", - "title": "Base.LinAlg.LAPACK.gttrf!", - "category": "function", - "text": "gttrf!(dl, d, du) -> (dl, d, du, du2, ipiv)\n\nFinds the LU factorization of a tridiagonal matrix with dl on the subdiagonal, d on the diagonal, and du on the superdiagonal.\n\nModifies dl, d, and du in-place and returns them and the second superdiagonal du2 and the pivoting vector ipiv.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.LAPACK.gttrs!", - "page": "Linear Algebra", - "title": "Base.LinAlg.LAPACK.gttrs!", - "category": "function", - "text": "gttrs!(trans, dl, d, du, du2, ipiv, B)\n\nSolves the equation A * X = B (trans = N), A.\' * X = B (trans = T), or A\' * X = B (trans = C) using the LU factorization computed by gttrf!. B is overwritten with the solution X.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.LAPACK.orglq!", - "page": "Linear Algebra", - "title": "Base.LinAlg.LAPACK.orglq!", - "category": "function", - "text": "orglq!(A, tau, k = length(tau))\n\nExplicitly finds the matrix Q of a LQ factorization after calling gelqf! on A. Uses the output of gelqf!. A is overwritten by Q.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.LAPACK.orgqr!", - "page": "Linear Algebra", - "title": "Base.LinAlg.LAPACK.orgqr!", - "category": "function", - "text": "orgqr!(A, tau, k = length(tau))\n\nExplicitly finds the matrix Q of a QR factorization after calling geqrf! on A. Uses the output of geqrf!. A is overwritten by Q.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.LAPACK.orgql!", - "page": "Linear Algebra", - "title": "Base.LinAlg.LAPACK.orgql!", - "category": "function", - "text": "orgql!(A, tau, k = length(tau))\n\nExplicitly finds the matrix Q of a QL factorization after calling geqlf! on A. Uses the output of geqlf!. A is overwritten by Q.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.LAPACK.orgrq!", - "page": "Linear Algebra", - "title": "Base.LinAlg.LAPACK.orgrq!", - "category": "function", - "text": "orgrq!(A, tau, k = length(tau))\n\nExplicitly finds the matrix Q of a RQ factorization after calling gerqf! on A. Uses the output of gerqf!. A is overwritten by Q.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.LAPACK.ormlq!", - "page": "Linear Algebra", - "title": "Base.LinAlg.LAPACK.ormlq!", - "category": "function", - "text": "ormlq!(side, trans, A, tau, C)\n\nComputes Q * C (trans = N), Q.\' * C (trans = T), Q\' * C (trans = C) for side = L or the equivalent right-sided multiplication for side = R using Q from a LQ factorization of A computed using gelqf!. C is overwritten.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.LAPACK.ormqr!", - "page": "Linear Algebra", - "title": "Base.LinAlg.LAPACK.ormqr!", - "category": "function", - "text": "ormqr!(side, trans, A, tau, C)\n\nComputes Q * C (trans = N), Q.\' * C (trans = T), Q\' * C (trans = C) for side = L or the equivalent right-sided multiplication for side = R using Q from a QR factorization of A computed using geqrf!. C is overwritten.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.LAPACK.ormql!", - "page": "Linear Algebra", - "title": "Base.LinAlg.LAPACK.ormql!", - "category": "function", - "text": "ormql!(side, trans, A, tau, C)\n\nComputes Q * C (trans = N), Q.\' * C (trans = T), Q\' * C (trans = C) for side = L or the equivalent right-sided multiplication for side = R using Q from a QL factorization of A computed using geqlf!. C is overwritten.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.LAPACK.ormrq!", - "page": "Linear Algebra", - "title": "Base.LinAlg.LAPACK.ormrq!", - "category": "function", - "text": "ormrq!(side, trans, A, tau, C)\n\nComputes Q * C (trans = N), Q.\' * C (trans = T), Q\' * C (trans = C) for side = L or the equivalent right-sided multiplication for side = R using Q from a RQ factorization of A computed using gerqf!. C is overwritten.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.LAPACK.gemqrt!", - "page": "Linear Algebra", - "title": "Base.LinAlg.LAPACK.gemqrt!", - "category": "function", - "text": "gemqrt!(side, trans, V, T, C)\n\nComputes Q * C (trans = N), Q.\' * C (trans = T), Q\' * C (trans = C) for side = L or the equivalent right-sided multiplication for side = R using Q from a QR factorization of A computed using geqrt!. C is overwritten.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.LAPACK.posv!", - "page": "Linear Algebra", - "title": "Base.LinAlg.LAPACK.posv!", - "category": "function", - "text": "posv!(uplo, A, B) -> (A, B)\n\nFinds the solution to A * X = B where A is a symmetric or Hermitian positive definite matrix. If uplo = U the upper Cholesky decomposition of A is computed. If uplo = L the lower Cholesky decomposition of A is computed. A is overwritten by its Cholesky decomposition. B is overwritten with the solution X.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.LAPACK.potrf!", - "page": "Linear Algebra", - "title": "Base.LinAlg.LAPACK.potrf!", - "category": "function", - "text": "potrf!(uplo, A)\n\nComputes the Cholesky (upper if uplo = U, lower if uplo = L) decomposition of positive-definite matrix A. A is overwritten and returned with an info code.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.LAPACK.potri!", - "page": "Linear Algebra", - "title": "Base.LinAlg.LAPACK.potri!", - "category": "function", - "text": "potri!(uplo, A)\n\nComputes the inverse of positive-definite matrix A after calling potrf! to find its (upper if uplo = U, lower if uplo = L) Cholesky decomposition.\n\nA is overwritten by its inverse and returned.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.LAPACK.potrs!", - "page": "Linear Algebra", - "title": "Base.LinAlg.LAPACK.potrs!", - "category": "function", - "text": "potrs!(uplo, A, B)\n\nFinds the solution to A * X = B where A is a symmetric or Hermitian positive definite matrix whose Cholesky decomposition was computed by potrf!. If uplo = U the upper Cholesky decomposition of A was computed. If uplo = L the lower Cholesky decomposition of A was computed. B is overwritten with the solution X.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.LAPACK.pstrf!", - "page": "Linear Algebra", - "title": "Base.LinAlg.LAPACK.pstrf!", - "category": "function", - "text": "pstrf!(uplo, A, tol) -> (A, piv, rank, info)\n\nComputes the (upper if uplo = U, lower if uplo = L) pivoted Cholesky decomposition of positive-definite matrix A with a user-set tolerance tol. A is overwritten by its Cholesky decomposition.\n\nReturns A, the pivots piv, the rank of A, and an info code. If info = 0, the factorization succeeded. If info = i > 0, then A is indefinite or rank-deficient.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.LAPACK.ptsv!", - "page": "Linear Algebra", - "title": "Base.LinAlg.LAPACK.ptsv!", - "category": "function", - "text": "ptsv!(D, E, B)\n\nSolves A * X = B for positive-definite tridiagonal A. D is the diagonal of A and E is the off-diagonal. B is overwritten with the solution X and returned.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.LAPACK.pttrf!", - "page": "Linear Algebra", - "title": "Base.LinAlg.LAPACK.pttrf!", - "category": "function", - "text": "pttrf!(D, E)\n\nComputes the LDLt factorization of a positive-definite tridiagonal matrix with D as diagonal and E as off-diagonal. D and E are overwritten and returned.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.LAPACK.pttrs!", - "page": "Linear Algebra", - "title": "Base.LinAlg.LAPACK.pttrs!", - "category": "function", - "text": "pttrs!(D, E, B)\n\nSolves A * X = B for positive-definite tridiagonal A with diagonal D and off-diagonal E after computing A\'s LDLt factorization using pttrf!. B is overwritten with the solution X.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.LAPACK.trtri!", - "page": "Linear Algebra", - "title": "Base.LinAlg.LAPACK.trtri!", - "category": "function", - "text": "trtri!(uplo, diag, A)\n\nFinds the inverse of (upper if uplo = U, lower if uplo = L) triangular matrix A. If diag = N, A has non-unit diagonal elements. If diag = U, all diagonal elements of A are one. A is overwritten with its inverse.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.LAPACK.trtrs!", - "page": "Linear Algebra", - "title": "Base.LinAlg.LAPACK.trtrs!", - "category": "function", - "text": "trtrs!(uplo, trans, diag, A, B)\n\nSolves A * X = B (trans = N), A.\' * X = B (trans = T), or A\' * X = B (trans = C) for (upper if uplo = U, lower if uplo = L) triangular matrix A. If diag = N, A has non-unit diagonal elements. If diag = U, all diagonal elements of A are one. B is overwritten with the solution X.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.LAPACK.trcon!", - "page": "Linear Algebra", - "title": "Base.LinAlg.LAPACK.trcon!", - "category": "function", - "text": "trcon!(norm, uplo, diag, A)\n\nFinds the reciprocal condition number of (upper if uplo = U, lower if uplo = L) triangular matrix A. If diag = N, A has non-unit diagonal elements. If diag = U, all diagonal elements of A are one. If norm = I, the condition number is found in the infinity norm. If norm = O or 1, the condition number is found in the one norm.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.LAPACK.trevc!", - "page": "Linear Algebra", - "title": "Base.LinAlg.LAPACK.trevc!", - "category": "function", - "text": "trevc!(side, howmny, select, T, VL = similar(T), VR = similar(T))\n\nFinds the eigensystem of an upper triangular matrix T. If side = R, the right eigenvectors are computed. If side = L, the left eigenvectors are computed. If side = B, both sets are computed. If howmny = A, all eigenvectors are found. If howmny = B, all eigenvectors are found and backtransformed using VL and VR. If howmny = S, only the eigenvectors corresponding to the values in select are computed.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.LAPACK.trrfs!", - "page": "Linear Algebra", - "title": "Base.LinAlg.LAPACK.trrfs!", - "category": "function", - "text": "trrfs!(uplo, trans, diag, A, B, X, Ferr, Berr) -> (Ferr, Berr)\n\nEstimates the error in the solution to A * X = B (trans = N), A.\' * X = B (trans = T), A\' * X = B (trans = C) for side = L, or the equivalent equations a right-handed side = R X * A after computing X using trtrs!. If uplo = U, A is upper triangular. If uplo = L, A is lower triangular. If diag = N, A has non-unit diagonal elements. If diag = U, all diagonal elements of A are one. Ferr and Berr are optional inputs. Ferr is the forward error and Berr is the backward error, each component-wise.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.LAPACK.stev!", - "page": "Linear Algebra", - "title": "Base.LinAlg.LAPACK.stev!", - "category": "function", - "text": "stev!(job, dv, ev) -> (dv, Zmat)\n\nComputes the eigensystem for a symmetric tridiagonal matrix with dv as diagonal and ev as off-diagonal. If job = N only the eigenvalues are found and returned in dv. If job = V then the eigenvectors are also found and returned in Zmat.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.LAPACK.stebz!", - "page": "Linear Algebra", - "title": "Base.LinAlg.LAPACK.stebz!", - "category": "function", - "text": "stebz!(range, order, vl, vu, il, iu, abstol, dv, ev) -> (dv, iblock, isplit)\n\nComputes the eigenvalues for a symmetric tridiagonal matrix with dv as diagonal and ev as off-diagonal. If range = A, all the eigenvalues are found. If range = V, the eigenvalues in the half-open interval (vl, vu] are found. If range = I, the eigenvalues with indices between il and iu are found. If order = B, eigvalues are ordered within a block. If order = E, they are ordered across all the blocks. abstol can be set as a tolerance for convergence.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.LAPACK.stegr!", - "page": "Linear Algebra", - "title": "Base.LinAlg.LAPACK.stegr!", - "category": "function", - "text": "stegr!(jobz, range, dv, ev, vl, vu, il, iu) -> (w, Z)\n\nComputes the eigenvalues (jobz = N) or eigenvalues and eigenvectors (jobz = V) for a symmetric tridiagonal matrix with dv as diagonal and ev as off-diagonal. If range = A, all the eigenvalues are found. If range = V, the eigenvalues in the half-open interval (vl, vu] are found. If range = I, the eigenvalues with indices between il and iu are found. The eigenvalues are returned in w and the eigenvectors in Z.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.LAPACK.stein!", - "page": "Linear Algebra", - "title": "Base.LinAlg.LAPACK.stein!", - "category": "function", - "text": "stein!(dv, ev_in, w_in, iblock_in, isplit_in)\n\nComputes the eigenvectors for a symmetric tridiagonal matrix with dv as diagonal and ev_in as off-diagonal. w_in specifies the input eigenvalues for which to find corresponding eigenvectors. iblock_in specifies the submatrices corresponding to the eigenvalues in w_in. isplit_in specifies the splitting points between the submatrix blocks.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.LAPACK.syconv!", - "page": "Linear Algebra", - "title": "Base.LinAlg.LAPACK.syconv!", - "category": "function", - "text": "syconv!(uplo, A, ipiv) -> (A, work)\n\nConverts a symmetric matrix A (which has been factorized into a triangular matrix) into two matrices L and D. If uplo = U, A is upper triangular. If uplo = L, it is lower triangular. ipiv is the pivot vector from the triangular factorization. A is overwritten by L and D.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.LAPACK.sysv!", - "page": "Linear Algebra", - "title": "Base.LinAlg.LAPACK.sysv!", - "category": "function", - "text": "sysv!(uplo, A, B) -> (B, A, ipiv)\n\nFinds the solution to A * X = B for symmetric matrix A. If uplo = U, the upper half of A is stored. If uplo = L, the lower half is stored. B is overwritten by the solution X. A is overwritten by its Bunch-Kaufman factorization. ipiv contains pivoting information about the factorization.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.LAPACK.sytrf!", - "page": "Linear Algebra", - "title": "Base.LinAlg.LAPACK.sytrf!", - "category": "function", - "text": "sytrf!(uplo, A) -> (A, ipiv, info)\n\nComputes the Bunch-Kaufman factorization of a symmetric matrix A. If uplo = U, the upper half of A is stored. If uplo = L, the lower half is stored.\n\nReturns A, overwritten by the factorization, a pivot vector ipiv, and the error code info which is a non-negative integer. If info is positive the matrix is singular and the diagonal part of the factorization is exactly zero at position info.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.LAPACK.sytri!", - "page": "Linear Algebra", - "title": "Base.LinAlg.LAPACK.sytri!", - "category": "function", - "text": "sytri!(uplo, A, ipiv)\n\nComputes the inverse of a symmetric matrix A using the results of sytrf!. If uplo = U, the upper half of A is stored. If uplo = L, the lower half is stored. A is overwritten by its inverse.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.LAPACK.sytrs!", - "page": "Linear Algebra", - "title": "Base.LinAlg.LAPACK.sytrs!", - "category": "function", - "text": "sytrs!(uplo, A, ipiv, B)\n\nSolves the equation A * X = B for a symmetric matrix A using the results of sytrf!. If uplo = U, the upper half of A is stored. If uplo = L, the lower half is stored. B is overwritten by the solution X.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.LAPACK.hesv!", - "page": "Linear Algebra", - "title": "Base.LinAlg.LAPACK.hesv!", - "category": "function", - "text": "hesv!(uplo, A, B) -> (B, A, ipiv)\n\nFinds the solution to A * X = B for Hermitian matrix A. If uplo = U, the upper half of A is stored. If uplo = L, the lower half is stored. B is overwritten by the solution X. A is overwritten by its Bunch-Kaufman factorization. ipiv contains pivoting information about the factorization.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.LAPACK.hetrf!", - "page": "Linear Algebra", - "title": "Base.LinAlg.LAPACK.hetrf!", - "category": "function", - "text": "hetrf!(uplo, A) -> (A, ipiv, info)\n\nComputes the Bunch-Kaufman factorization of a Hermitian matrix A. If uplo = U, the upper half of A is stored. If uplo = L, the lower half is stored.\n\nReturns A, overwritten by the factorization, a pivot vector ipiv, and the error code info which is a non-negative integer. If info is positive the matrix is singular and the diagonal part of the factorization is exactly zero at position info.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.LAPACK.hetri!", - "page": "Linear Algebra", - "title": "Base.LinAlg.LAPACK.hetri!", - "category": "function", - "text": "hetri!(uplo, A, ipiv)\n\nComputes the inverse of a Hermitian matrix A using the results of sytrf!. If uplo = U, the upper half of A is stored. If uplo = L, the lower half is stored. A is overwritten by its inverse.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.LAPACK.hetrs!", - "page": "Linear Algebra", - "title": "Base.LinAlg.LAPACK.hetrs!", - "category": "function", - "text": "hetrs!(uplo, A, ipiv, B)\n\nSolves the equation A * X = B for a Hermitian matrix A using the results of sytrf!. If uplo = U, the upper half of A is stored. If uplo = L, the lower half is stored. B is overwritten by the solution X.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.LAPACK.syev!", - "page": "Linear Algebra", - "title": "Base.LinAlg.LAPACK.syev!", - "category": "function", - "text": "syev!(jobz, uplo, A)\n\nFinds the eigenvalues (jobz = N) or eigenvalues and eigenvectors (jobz = V) of a symmetric matrix A. If uplo = U, the upper triangle of A is used. If uplo = L, the lower triangle of A is used.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.LAPACK.syevr!", - "page": "Linear Algebra", - "title": "Base.LinAlg.LAPACK.syevr!", - "category": "function", - "text": "syevr!(jobz, range, uplo, A, vl, vu, il, iu, abstol) -> (W, Z)\n\nFinds the eigenvalues (jobz = N) or eigenvalues and eigenvectors (jobz = V) of a symmetric matrix A. If uplo = U, the upper triangle of A is used. If uplo = L, the lower triangle of A is used. If range = A, all the eigenvalues are found. If range = V, the eigenvalues in the half-open interval (vl, vu] are found. If range = I, the eigenvalues with indices between il and iu are found. abstol can be set as a tolerance for convergence.\n\nThe eigenvalues are returned in W and the eigenvectors in Z.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.LAPACK.sygvd!", - "page": "Linear Algebra", - "title": "Base.LinAlg.LAPACK.sygvd!", - "category": "function", - "text": "sygvd!(itype, jobz, uplo, A, B) -> (w, A, B)\n\nFinds the generalized eigenvalues (jobz = N) or eigenvalues and eigenvectors (jobz = V) of a symmetric matrix A and symmetric positive-definite matrix B. If uplo = U, the upper triangles of A and B are used. If uplo = L, the lower triangles of A and B are used. If itype = 1, the problem to solve is A * x = lambda * B * x. If itype = 2, the problem to solve is A * B * x = lambda * x. If itype = 3, the problem to solve is B * A * x = lambda * x.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.LAPACK.bdsqr!", - "page": "Linear Algebra", - "title": "Base.LinAlg.LAPACK.bdsqr!", - "category": "function", - "text": "bdsqr!(uplo, d, e_, Vt, U, C) -> (d, Vt, U, C)\n\nComputes the singular value decomposition of a bidiagonal matrix with d on the diagonal and e_ on the off-diagonal. If uplo = U, e_ is the superdiagonal. If uplo = L, e_ is the subdiagonal. Can optionally also compute the product Q\' * C.\n\nReturns the singular values in d, and the matrix C overwritten with Q\' * C.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.LAPACK.bdsdc!", - "page": "Linear Algebra", - "title": "Base.LinAlg.LAPACK.bdsdc!", - "category": "function", - "text": "bdsdc!(uplo, compq, d, e_) -> (d, e, u, vt, q, iq)\n\nComputes the singular value decomposition of a bidiagonal matrix with d on the diagonal and e_ on the off-diagonal using a divide and conqueq method. If uplo = U, e_ is the superdiagonal. If uplo = L, e_ is the subdiagonal. If compq = N, only the singular values are found. If compq = I, the singular values and vectors are found. If compq = P, the singular values and vectors are found in compact form. Only works for real types.\n\nReturns the singular values in d, and if compq = P, the compact singular vectors in iq.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.LAPACK.gecon!", - "page": "Linear Algebra", - "title": "Base.LinAlg.LAPACK.gecon!", - "category": "function", - "text": "gecon!(normtype, A, anorm)\n\nFinds the reciprocal condition number of matrix A. If normtype = I, the condition number is found in the infinity norm. If normtype = O or 1, the condition number is found in the one norm. A must be the result of getrf! and anorm is the norm of A in the relevant norm.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.LAPACK.gehrd!", - "page": "Linear Algebra", - "title": "Base.LinAlg.LAPACK.gehrd!", - "category": "function", - "text": "gehrd!(ilo, ihi, A) -> (A, tau)\n\nConverts a matrix A to Hessenberg form. If A is balanced with gebal! then ilo and ihi are the outputs of gebal!. Otherwise they should be ilo = 1 and ihi = size(A,2). tau contains the elementary reflectors of the factorization.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.LAPACK.orghr!", - "page": "Linear Algebra", - "title": "Base.LinAlg.LAPACK.orghr!", - "category": "function", - "text": "orghr!(ilo, ihi, A, tau)\n\nExplicitly finds Q, the orthogonal/unitary matrix from gehrd!. ilo, ihi, A, and tau must correspond to the input/output to gehrd!.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.LAPACK.gees!", - "page": "Linear Algebra", - "title": "Base.LinAlg.LAPACK.gees!", - "category": "function", - "text": "gees!(jobvs, A) -> (A, vs, w)\n\nComputes the eigenvalues (jobvs = N) or the eigenvalues and Schur vectors (jobvs = V) of matrix A. A is overwritten by its Schur form.\n\nReturns A, vs containing the Schur vectors, and w, containing the eigenvalues.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.LAPACK.gges!", - "page": "Linear Algebra", - "title": "Base.LinAlg.LAPACK.gges!", - "category": "function", - "text": "gges!(jobvsl, jobvsr, A, B) -> (A, B, alpha, beta, vsl, vsr)\n\nComputes the generalized eigenvalues, generalized Schur form, left Schur vectors (jobsvl = V), or right Schur vectors (jobvsr = V) of A and B.\n\nThe generalized eigenvalues are returned in alpha and beta. The left Schur vectors are returned in vsl and the right Schur vectors are returned in vsr.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.LAPACK.trexc!", - "page": "Linear Algebra", - "title": "Base.LinAlg.LAPACK.trexc!", - "category": "function", - "text": "trexc!(compq, ifst, ilst, T, Q) -> (T, Q)\n\nReorder the Schur factorization of a matrix. If compq = V, the Schur vectors Q are reordered. If compq = N they are not modified. ifst and ilst specify the reordering of the vectors.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.LAPACK.trsen!", - "page": "Linear Algebra", - "title": "Base.LinAlg.LAPACK.trsen!", - "category": "function", - "text": "trsen!(compq, job, select, T, Q) -> (T, Q, w)\n\nReorder the Schur factorization of a matrix and optionally finds reciprocal condition numbers. If job = N, no condition numbers are found. If job = E, only the condition number for this cluster of eigenvalues is found. If job = V, only the condition number for the invariant subspace is found. If job = B then the condition numbers for the cluster and subspace are found. If compq = V the Schur vectors Q are updated. If compq = N the Schur vectors are not modified. select determines which eigenvalues are in the cluster.\n\nReturns T, Q, and reordered eigenvalues in w.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.LAPACK.tgsen!", - "page": "Linear Algebra", - "title": "Base.LinAlg.LAPACK.tgsen!", - "category": "function", - "text": "tgsen!(select, S, T, Q, Z) -> (S, T, alpha, beta, Q, Z)\n\nReorders the vectors of a generalized Schur decomposition. select specifices the eigenvalues in each cluster.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#Base.LinAlg.LAPACK.trsyl!", - "page": "Linear Algebra", - "title": "Base.LinAlg.LAPACK.trsyl!", - "category": "function", - "text": "trsyl!(transa, transb, A, B, C, isgn=1) -> (C, scale)\n\nSolves the Sylvester matrix equation A * X +/- X * B = scale*C where A and B are both quasi-upper triangular. If transa = N, A is not modified. If transa = T, A is transposed. If transa = C, A is conjugate transposed. Similarly for transb and B. If isgn = 1, the equation A * X + X * B = scale * C is solved. If isgn = -1, the equation A * X - X * B = scale * C is solved.\n\nReturns X (overwriting C) and scale.\n\n\n\n" -}, - -{ - "location": "stdlib/linalg.html#LAPACK-Functions-1", - "page": "Linear Algebra", - "title": "LAPACK Functions", - "category": "section", - "text": "Base.LinAlg.LAPACK provides wrappers for some of the LAPACK functions for linear algebra. Those functions that overwrite one of the input arrays have names ending in \'!\'.Usually a function has 4 methods defined, one each for Float64, Float32, Complex128 and Complex64 arrays.Note that the LAPACK API provided by Julia can and will change in the future. Since this API is not user-facing, there is no commitment to support/deprecate this specific set of functions in future releases.Base.LinAlg.LAPACK.gbtrf!\nBase.LinAlg.LAPACK.gbtrs!\nBase.LinAlg.LAPACK.gebal!\nBase.LinAlg.LAPACK.gebak!\nBase.LinAlg.LAPACK.gebrd!\nBase.LinAlg.LAPACK.gelqf!\nBase.LinAlg.LAPACK.geqlf!\nBase.LinAlg.LAPACK.geqrf!\nBase.LinAlg.LAPACK.geqp3!\nBase.LinAlg.LAPACK.gerqf!\nBase.LinAlg.LAPACK.geqrt!\nBase.LinAlg.LAPACK.geqrt3!\nBase.LinAlg.LAPACK.getrf!\nBase.LinAlg.LAPACK.tzrzf!\nBase.LinAlg.LAPACK.ormrz!\nBase.LinAlg.LAPACK.gels!\nBase.LinAlg.LAPACK.gesv!\nBase.LinAlg.LAPACK.getrs!\nBase.LinAlg.LAPACK.getri!\nBase.LinAlg.LAPACK.gesvx!\nBase.LinAlg.LAPACK.gelsd!\nBase.LinAlg.LAPACK.gelsy!\nBase.LinAlg.LAPACK.gglse!\nBase.LinAlg.LAPACK.geev!\nBase.LinAlg.LAPACK.gesdd!\nBase.LinAlg.LAPACK.gesvd!\nBase.LinAlg.LAPACK.ggsvd!\nBase.LinAlg.LAPACK.ggsvd3!\nBase.LinAlg.LAPACK.geevx!\nBase.LinAlg.LAPACK.ggev!\nBase.LinAlg.LAPACK.gtsv!\nBase.LinAlg.LAPACK.gttrf!\nBase.LinAlg.LAPACK.gttrs!\nBase.LinAlg.LAPACK.orglq!\nBase.LinAlg.LAPACK.orgqr!\nBase.LinAlg.LAPACK.orgql!\nBase.LinAlg.LAPACK.orgrq!\nBase.LinAlg.LAPACK.ormlq!\nBase.LinAlg.LAPACK.ormqr!\nBase.LinAlg.LAPACK.ormql!\nBase.LinAlg.LAPACK.ormrq!\nBase.LinAlg.LAPACK.gemqrt!\nBase.LinAlg.LAPACK.posv!\nBase.LinAlg.LAPACK.potrf!\nBase.LinAlg.LAPACK.potri!\nBase.LinAlg.LAPACK.potrs!\nBase.LinAlg.LAPACK.pstrf!\nBase.LinAlg.LAPACK.ptsv!\nBase.LinAlg.LAPACK.pttrf!\nBase.LinAlg.LAPACK.pttrs!\nBase.LinAlg.LAPACK.trtri!\nBase.LinAlg.LAPACK.trtrs!\nBase.LinAlg.LAPACK.trcon!\nBase.LinAlg.LAPACK.trevc!\nBase.LinAlg.LAPACK.trrfs!\nBase.LinAlg.LAPACK.stev!\nBase.LinAlg.LAPACK.stebz!\nBase.LinAlg.LAPACK.stegr!\nBase.LinAlg.LAPACK.stein!\nBase.LinAlg.LAPACK.syconv!\nBase.LinAlg.LAPACK.sysv!\nBase.LinAlg.LAPACK.sytrf!\nBase.LinAlg.LAPACK.sytri!\nBase.LinAlg.LAPACK.sytrs!\nBase.LinAlg.LAPACK.hesv!\nBase.LinAlg.LAPACK.hetrf!\nBase.LinAlg.LAPACK.hetri!\nBase.LinAlg.LAPACK.hetrs!\nBase.LinAlg.LAPACK.syev!\nBase.LinAlg.LAPACK.syevr!\nBase.LinAlg.LAPACK.sygvd!\nBase.LinAlg.LAPACK.bdsqr!\nBase.LinAlg.LAPACK.bdsdc!\nBase.LinAlg.LAPACK.gecon!\nBase.LinAlg.LAPACK.gehrd!\nBase.LinAlg.LAPACK.orghr!\nBase.LinAlg.LAPACK.gees!\nBase.LinAlg.LAPACK.gges!\nBase.LinAlg.LAPACK.trexc!\nBase.LinAlg.LAPACK.trsen!\nBase.LinAlg.LAPACK.tgsen!\nBase.LinAlg.LAPACK.trsyl!" -}, - -{ - "location": "stdlib/constants.html#", - "page": "Constants", - "title": "Constants", - "category": "page", - "text": "" -}, - -{ - "location": "stdlib/constants.html#Core.nothing", - "page": "Constants", - "title": "Core.nothing", - "category": "constant", - "text": "nothing\n\nThe singleton instance of type Void, used by convention when there is no value to return (as in a C void function). Can be converted to an empty Nullable value.\n\n\n\n" -}, - -{ - "location": "stdlib/constants.html#Base.PROGRAM_FILE", - "page": "Constants", - "title": "Base.PROGRAM_FILE", - "category": "constant", - "text": "PROGRAM_FILE\n\nA string containing the script name passed to Julia from the command line. Note that the script name remains unchanged from within included files. Alternatively see @__FILE__.\n\n\n\n" -}, - -{ - "location": "stdlib/constants.html#Base.ARGS", - "page": "Constants", - "title": "Base.ARGS", - "category": "constant", - "text": "ARGS\n\nAn array of the command line arguments passed to Julia, as strings.\n\n\n\n" -}, - -{ - "location": "stdlib/constants.html#Base.C_NULL", - "page": "Constants", - "title": "Base.C_NULL", - "category": "constant", - "text": "C_NULL\n\nThe C null pointer constant, sometimes used when calling external code.\n\n\n\n" -}, - -{ - "location": "stdlib/constants.html#Base.VERSION", - "page": "Constants", - "title": "Base.VERSION", - "category": "constant", - "text": "VERSION\n\nA VersionNumber object describing which version of Julia is in use. For details see Version Number Literals.\n\n\n\n" -}, - -{ - "location": "stdlib/constants.html#Base.LOAD_PATH", - "page": "Constants", - "title": "Base.LOAD_PATH", - "category": "constant", - "text": "LOAD_PATH\n\nAn array of paths as strings or custom loader objects for the require function and using and import statements to consider when loading code. To create a custom loader type, define the type and then add appropriate methods to the Base.load_hook function with the following signature:\n\nBase.load_hook(loader::Loader, name::String, found::Any)\n\nThe loader argument is the current value in LOAD_PATH, name is the name of the module to load, and found is the path of any previously found code to provide name. If no provider has been found earlier in LOAD_PATH then the value of found will be nothing. Custom loader functionality is experimental and may break or change in Julia 1.0.\n\n\n\n" -}, - -{ - "location": "stdlib/constants.html#Base.JULIA_HOME", - "page": "Constants", - "title": "Base.JULIA_HOME", - "category": "constant", - "text": "JULIA_HOME\n\nA string containing the full path to the directory containing the julia executable.\n\n\n\n" -}, - -{ - "location": "stdlib/constants.html#Core.ANY", - "page": "Constants", - "title": "Core.ANY", - "category": "constant", - "text": "ANY\n\nEquivalent to Any for dispatch purposes, but signals the compiler to skip code generation specialization for that field.\n\n\n\n" -}, - -{ - "location": "stdlib/constants.html#Base.Sys.CPU_CORES", - "page": "Constants", - "title": "Base.Sys.CPU_CORES", - "category": "constant", - "text": "Sys.CPU_CORES\n\nThe number of logical CPU cores available in the system.\n\nSee the Hwloc.jl package for extended information, including number of physical cores.\n\n\n\n" -}, - -{ - "location": "stdlib/constants.html#Base.Sys.WORD_SIZE", - "page": "Constants", - "title": "Base.Sys.WORD_SIZE", - "category": "constant", - "text": "Sys.WORD_SIZE\n\nStandard word size on the current machine, in bits.\n\n\n\n" -}, - -{ - "location": "stdlib/constants.html#Base.Sys.KERNEL", - "page": "Constants", - "title": "Base.Sys.KERNEL", - "category": "constant", - "text": "Sys.KERNEL\n\nA symbol representing the name of the operating system, as returned by uname of the build configuration.\n\n\n\n" -}, - -{ - "location": "stdlib/constants.html#Base.Sys.ARCH", - "page": "Constants", - "title": "Base.Sys.ARCH", - "category": "constant", - "text": "Sys.ARCH\n\nA symbol representing the architecture of the build configuration.\n\n\n\n" -}, - -{ - "location": "stdlib/constants.html#Base.Sys.MACHINE", - "page": "Constants", - "title": "Base.Sys.MACHINE", - "category": "constant", - "text": "Sys.MACHINE\n\nA string containing the build triple.\n\n\n\n" -}, - -{ - "location": "stdlib/constants.html#lib-constants-1", - "page": "Constants", - "title": "Constants", - "category": "section", - "text": "Core.nothing\nBase.PROGRAM_FILE\nBase.ARGS\nBase.C_NULL\nBase.VERSION\nBase.LOAD_PATH\nBase.JULIA_HOME\nCore.ANY\nBase.Sys.CPU_CORES\nBase.Sys.WORD_SIZE\nBase.Sys.KERNEL\nBase.Sys.ARCH\nBase.Sys.MACHINESee also:STDIN\nSTDOUT\nSTDERR\nENV\nENDIAN_BOM\nLibc.MS_ASYNC\nLibc.MS_INVALIDATE\nLibc.MS_SYNC\nLibdl.DL_LOAD_PATH\nLibdl.RTLD_DEEPBIND\nLibdl.RTLD_LOCAL\nLibdl.RTLD_NOLOAD\nLibdl.RTLD_LAZY\nLibdl.RTLD_NOW\nLibdl.RTLD_GLOBAL\nLibdl.RTLD_NODELETE\nLibdl.RTLD_FIRST" -}, - -{ - "location": "stdlib/file.html#", - "page": "Filesystem", - "title": "Filesystem", - "category": "page", - "text": "" -}, - -{ - "location": "stdlib/file.html#Base.Filesystem.pwd", - "page": "Filesystem", - "title": "Base.Filesystem.pwd", - "category": "function", - "text": "pwd() -> AbstractString\n\nGet the current working directory.\n\n\n\n" -}, - -{ - "location": "stdlib/file.html#Base.Filesystem.cd-Tuple{AbstractString}", - "page": "Filesystem", - "title": "Base.Filesystem.cd", - "category": "method", - "text": "cd(dir::AbstractString=homedir())\n\nSet the current working directory.\n\n\n\n" -}, - -{ - "location": "stdlib/file.html#Base.Filesystem.cd-Tuple{Function}", - "page": "Filesystem", - "title": "Base.Filesystem.cd", - "category": "method", - "text": "cd(f::Function, dir::AbstractString=homedir())\n\nTemporarily changes the current working directory and applies function f before returning.\n\n\n\n" -}, - -{ - "location": "stdlib/file.html#Base.Filesystem.readdir", - "page": "Filesystem", - "title": "Base.Filesystem.readdir", - "category": "function", - "text": "readdir(dir::AbstractString=\".\") -> Vector{String}\n\nReturns the files and directories in the directory dir (or the current working directory if not given).\n\n\n\n" -}, - -{ - "location": "stdlib/file.html#Base.Filesystem.walkdir", - "page": "Filesystem", - "title": "Base.Filesystem.walkdir", - "category": "function", - "text": "walkdir(dir; topdown=true, follow_symlinks=false, onerror=throw)\n\nThe walkdir method returns an iterator that walks the directory tree of a directory. The iterator returns a tuple containing (rootpath, dirs, files). The directory tree can be traversed top-down or bottom-up. If walkdir encounters a SystemError it will rethrow the error by default. A custom error handling function can be provided through onerror keyword argument. onerror is called with a SystemError as argument.\n\nfor (root, dirs, files) in walkdir(\".\")\n println(\"Directories in $root\")\n for dir in dirs\n println(joinpath(root, dir)) # path to directories\n end\n println(\"Files in $root\")\n for file in files\n println(joinpath(root, file)) # path to files\n end\nend\n\n\n\n" -}, - -{ - "location": "stdlib/file.html#Base.Filesystem.mkdir", - "page": "Filesystem", - "title": "Base.Filesystem.mkdir", - "category": "function", - "text": "mkdir(path::AbstractString, mode::Unsigned=0o777)\n\nMake a new directory with name path and permissions mode. mode defaults to 0o777, modified by the current file creation mask. This function never creates more than one directory. If the directory already exists, or some intermediate directories do not exist, this function throws an error. See mkpath for a function which creates all required intermediate directories.\n\n\n\n" -}, - -{ - "location": "stdlib/file.html#Base.Filesystem.mkpath", - "page": "Filesystem", - "title": "Base.Filesystem.mkpath", - "category": "function", - "text": "mkpath(path::AbstractString, mode::Unsigned=0o777)\n\nCreate all directories in the given path, with permissions mode. mode defaults to 0o777, modified by the current file creation mask.\n\n\n\n" -}, - -{ - "location": "stdlib/file.html#Base.Filesystem.symlink", - "page": "Filesystem", - "title": "Base.Filesystem.symlink", - "category": "function", - "text": "symlink(target::AbstractString, link::AbstractString)\n\nCreates a symbolic link to target with the name link.\n\nnote: Note\nThis function raises an error under operating systems that do not support soft symbolic links, such as Windows XP.\n\n\n\n" -}, - -{ - "location": "stdlib/file.html#Base.Filesystem.readlink", - "page": "Filesystem", - "title": "Base.Filesystem.readlink", - "category": "function", - "text": "readlink(path::AbstractString) -> AbstractString\n\nReturns the target location a symbolic link path points to.\n\n\n\n" -}, - -{ - "location": "stdlib/file.html#Base.Filesystem.chmod", - "page": "Filesystem", - "title": "Base.Filesystem.chmod", - "category": "function", - "text": "chmod(path::AbstractString, mode::Integer; recursive::Bool=false)\n\nChange the permissions mode of path to mode. Only integer modes (e.g. 0o777) are currently supported. If recursive=true and the path is a directory all permissions in that directory will be recursively changed.\n\n\n\n" -}, - -{ - "location": "stdlib/file.html#Base.Filesystem.chown", - "page": "Filesystem", - "title": "Base.Filesystem.chown", - "category": "function", - "text": "chown(path::AbstractString, owner::Integer, group::Integer=-1)\n\nChange the owner and/or group of path to owner and/or group. If the value entered for owner or group is -1 the corresponding ID will not change. Only integer owners and groups are currently supported.\n\n\n\n" -}, - -{ - "location": "stdlib/file.html#Base.stat", - "page": "Filesystem", - "title": "Base.stat", - "category": "function", - "text": "stat(file)\n\nReturns a structure whose fields contain information about the file. The fields of the structure are:\n\nName Description\nsize The size (in bytes) of the file\ndevice ID of the device that contains the file\ninode The inode number of the file\nmode The protection mode of the file\nnlink The number of hard links to the file\nuid The user id of the owner of the file\ngid The group id of the file owner\nrdev If this file refers to a device, the ID of the device it refers to\nblksize The file-system preferred block size for the file\nblocks The number of such blocks allocated\nmtime Unix timestamp of when the file was last modified\nctime Unix timestamp of when the file was created\n\n\n\n" -}, - -{ - "location": "stdlib/file.html#Base.Filesystem.lstat", - "page": "Filesystem", - "title": "Base.Filesystem.lstat", - "category": "function", - "text": "lstat(file)\n\nLike stat, but for symbolic links gets the info for the link itself rather than the file it refers to. This function must be called on a file path rather than a file object or a file descriptor.\n\n\n\n" -}, - -{ - "location": "stdlib/file.html#Base.Filesystem.ctime", - "page": "Filesystem", - "title": "Base.Filesystem.ctime", - "category": "function", - "text": "ctime(file)\n\nEquivalent to stat(file).ctime\n\n\n\n" -}, - -{ - "location": "stdlib/file.html#Base.Filesystem.mtime", - "page": "Filesystem", - "title": "Base.Filesystem.mtime", - "category": "function", - "text": "mtime(file)\n\nEquivalent to stat(file).mtime.\n\n\n\n" -}, - -{ - "location": "stdlib/file.html#Base.Filesystem.filemode", - "page": "Filesystem", - "title": "Base.Filesystem.filemode", - "category": "function", - "text": "filemode(file)\n\nEquivalent to stat(file).mode\n\n\n\n" -}, - -{ - "location": "stdlib/file.html#Base.Filesystem.filesize", - "page": "Filesystem", - "title": "Base.Filesystem.filesize", - "category": "function", - "text": "filesize(path...)\n\nEquivalent to stat(file).size.\n\n\n\n" -}, - -{ - "location": "stdlib/file.html#Base.Filesystem.uperm", - "page": "Filesystem", - "title": "Base.Filesystem.uperm", - "category": "function", - "text": "uperm(file)\n\nGets the permissions of the owner of the file as a bitfield of\n\nValue Description\n01 Execute Permission\n02 Write Permission\n04 Read Permission\n\nFor allowed arguments, see stat.\n\n\n\n" -}, - -{ - "location": "stdlib/file.html#Base.Filesystem.gperm", - "page": "Filesystem", - "title": "Base.Filesystem.gperm", - "category": "function", - "text": "gperm(file)\n\nLike uperm but gets the permissions of the group owning the file.\n\n\n\n" -}, - -{ - "location": "stdlib/file.html#Base.Filesystem.operm", - "page": "Filesystem", - "title": "Base.Filesystem.operm", - "category": "function", - "text": "operm(file)\n\nLike uperm but gets the permissions for people who neither own the file nor are a member of the group owning the file\n\n\n\n" -}, - -{ - "location": "stdlib/file.html#Base.Filesystem.cp", - "page": "Filesystem", - "title": "Base.Filesystem.cp", - "category": "function", - "text": "cp(src::AbstractString, dst::AbstractString; remove_destination::Bool=false, follow_symlinks::Bool=false)\n\nCopy the file, link, or directory from src to dest. remove_destination=true will first remove an existing dst.\n\nIf follow_symlinks=false, and src is a symbolic link, dst will be created as a symbolic link. If follow_symlinks=true and src is a symbolic link, dst will be a copy of the file or directory src refers to.\n\n\n\n" -}, - -{ - "location": "stdlib/file.html#Base.download", - "page": "Filesystem", - "title": "Base.download", - "category": "function", - "text": "download(url::AbstractString, [localfile::AbstractString])\n\nDownload a file from the given url, optionally renaming it to the given local file name. Note that this function relies on the availability of external tools such as curl, wget or fetch to download the file and is provided for convenience. For production use or situations in which more options are needed, please use a package that provides the desired functionality instead.\n\n\n\n" -}, - -{ - "location": "stdlib/file.html#Base.Filesystem.mv", - "page": "Filesystem", - "title": "Base.Filesystem.mv", - "category": "function", - "text": "mv(src::AbstractString, dst::AbstractString; remove_destination::Bool=false)\n\nMove the file, link, or directory from src to dst. remove_destination=true will first remove an existing dst.\n\n\n\n" -}, - -{ - "location": "stdlib/file.html#Base.Filesystem.rm", - "page": "Filesystem", - "title": "Base.Filesystem.rm", - "category": "function", - "text": "rm(path::AbstractString; force::Bool=false, recursive::Bool=false)\n\nDelete the file, link, or empty directory at the given path. If force=true is passed, a non-existing path is not treated as error. If recursive=true is passed and the path is a directory, then all contents are removed recursively.\n\n\n\n" -}, - -{ - "location": "stdlib/file.html#Base.Filesystem.touch", - "page": "Filesystem", - "title": "Base.Filesystem.touch", - "category": "function", - "text": "touch(path::AbstractString)\n\nUpdate the last-modified timestamp on a file to the current time.\n\n\n\n" -}, - -{ - "location": "stdlib/file.html#Base.Filesystem.tempname", - "page": "Filesystem", - "title": "Base.Filesystem.tempname", - "category": "function", - "text": "tempname()\n\nGenerate a unique temporary file path.\n\n\n\n" -}, - -{ - "location": "stdlib/file.html#Base.Filesystem.tempdir", - "page": "Filesystem", - "title": "Base.Filesystem.tempdir", - "category": "function", - "text": "tempdir()\n\nObtain the path of a temporary directory (possibly shared with other processes).\n\n\n\n" -}, - -{ - "location": "stdlib/file.html#Base.Filesystem.mktemp-Tuple{Any}", - "page": "Filesystem", - "title": "Base.Filesystem.mktemp", - "category": "method", - "text": "mktemp(parent=tempdir())\n\nReturns (path, io), where path is the path of a new temporary file in parent and io is an open file object for this path.\n\n\n\n" -}, - -{ - "location": "stdlib/file.html#Base.Filesystem.mktemp-Tuple{Function,Any}", - "page": "Filesystem", - "title": "Base.Filesystem.mktemp", - "category": "method", - "text": "mktemp(f::Function, parent=tempdir())\n\nApply the function f to the result of mktemp(parent) and remove the temporary file upon completion.\n\n\n\n" -}, - -{ - "location": "stdlib/file.html#Base.Filesystem.mktempdir-Tuple{Any}", - "page": "Filesystem", - "title": "Base.Filesystem.mktempdir", - "category": "method", - "text": "mktempdir(parent=tempdir())\n\nCreate a temporary directory in the parent directory and return its path. If parent does not exist, throw an error.\n\n\n\n" -}, - -{ - "location": "stdlib/file.html#Base.Filesystem.mktempdir-Tuple{Function,Any}", - "page": "Filesystem", - "title": "Base.Filesystem.mktempdir", - "category": "method", - "text": "mktempdir(f::Function, parent=tempdir())\n\nApply the function f to the result of mktempdir(parent) and remove the temporary directory upon completion.\n\n\n\n" -}, - -{ - "location": "stdlib/file.html#Base.Filesystem.isblockdev", - "page": "Filesystem", - "title": "Base.Filesystem.isblockdev", - "category": "function", - "text": "isblockdev(path) -> Bool\n\nReturns true if path is a block device, false otherwise.\n\n\n\n" -}, - -{ - "location": "stdlib/file.html#Base.Filesystem.ischardev", - "page": "Filesystem", - "title": "Base.Filesystem.ischardev", - "category": "function", - "text": "ischardev(path) -> Bool\n\nReturns true if path is a character device, false otherwise.\n\n\n\n" -}, - -{ - "location": "stdlib/file.html#Base.Filesystem.isdir", - "page": "Filesystem", - "title": "Base.Filesystem.isdir", - "category": "function", - "text": "isdir(path) -> Bool\n\nReturns true if path is a directory, false otherwise.\n\n\n\n" -}, - -{ - "location": "stdlib/file.html#Base.Filesystem.isfifo", - "page": "Filesystem", - "title": "Base.Filesystem.isfifo", - "category": "function", - "text": "isfifo(path) -> Bool\n\nReturns true if path is a FIFO, false otherwise.\n\n\n\n" -}, - -{ - "location": "stdlib/file.html#Base.Filesystem.isfile", - "page": "Filesystem", - "title": "Base.Filesystem.isfile", - "category": "function", - "text": "isfile(path) -> Bool\n\nReturns true if path is a regular file, false otherwise.\n\n\n\n" -}, - -{ - "location": "stdlib/file.html#Base.Filesystem.islink", - "page": "Filesystem", - "title": "Base.Filesystem.islink", - "category": "function", - "text": "islink(path) -> Bool\n\nReturns true if path is a symbolic link, false otherwise.\n\n\n\n" -}, - -{ - "location": "stdlib/file.html#Base.Filesystem.ismount", - "page": "Filesystem", - "title": "Base.Filesystem.ismount", - "category": "function", - "text": "ismount(path) -> Bool\n\nReturns true if path is a mount point, false otherwise.\n\n\n\n" -}, - -{ - "location": "stdlib/file.html#Base.Filesystem.ispath", - "page": "Filesystem", - "title": "Base.Filesystem.ispath", - "category": "function", - "text": "ispath(path) -> Bool\n\nReturns true if path is a valid filesystem path, false otherwise.\n\n\n\n" -}, - -{ - "location": "stdlib/file.html#Base.Filesystem.issetgid", - "page": "Filesystem", - "title": "Base.Filesystem.issetgid", - "category": "function", - "text": "issetgid(path) -> Bool\n\nReturns true if path has the setgid flag set, false otherwise.\n\n\n\n" -}, - -{ - "location": "stdlib/file.html#Base.Filesystem.issetuid", - "page": "Filesystem", - "title": "Base.Filesystem.issetuid", - "category": "function", - "text": "issetuid(path) -> Bool\n\nReturns true if path has the setuid flag set, false otherwise.\n\n\n\n" -}, - -{ - "location": "stdlib/file.html#Base.Filesystem.issocket", - "page": "Filesystem", - "title": "Base.Filesystem.issocket", - "category": "function", - "text": "issocket(path) -> Bool\n\nReturns true if path is a socket, false otherwise.\n\n\n\n" -}, - -{ - "location": "stdlib/file.html#Base.Filesystem.issticky", - "page": "Filesystem", - "title": "Base.Filesystem.issticky", - "category": "function", - "text": "issticky(path) -> Bool\n\nReturns true if path has the sticky bit set, false otherwise.\n\n\n\n" -}, - -{ - "location": "stdlib/file.html#Base.Filesystem.homedir", - "page": "Filesystem", - "title": "Base.Filesystem.homedir", - "category": "function", - "text": "homedir() -> AbstractString\n\nReturn the current user\'s home directory.\n\nnote: Note\nhomedir determines the home directory via libuv\'s uv_os_homedir. For details (for example on how to specify the home directory via environment variables), see the uv_os_homedir documentation.\n\n\n\n" -}, - -{ - "location": "stdlib/file.html#Base.Filesystem.dirname", - "page": "Filesystem", - "title": "Base.Filesystem.dirname", - "category": "function", - "text": "dirname(path::AbstractString) -> AbstractString\n\nGet the directory part of a path.\n\njulia> dirname(\"/home/myuser\")\n\"/home\"\n\nSee also: basename\n\n\n\n" -}, - -{ - "location": "stdlib/file.html#Base.Filesystem.basename", - "page": "Filesystem", - "title": "Base.Filesystem.basename", - "category": "function", - "text": "basename(path::AbstractString) -> AbstractString\n\nGet the file name part of a path.\n\njulia> basename(\"/home/myuser/example.jl\")\n\"example.jl\"\n\nSee also: dirname\n\n\n\n" -}, - -{ - "location": "stdlib/file.html#Base.@__FILE__", - "page": "Filesystem", - "title": "Base.@__FILE__", - "category": "macro", - "text": "@__FILE__ -> AbstractString\n\n@__FILE__ expands to a string with the absolute file path of the file containing the macro. Returns nothing if run from a REPL or an empty string if evaluated by julia -e . Alternatively see PROGRAM_FILE.\n\n\n\n" -}, - -{ - "location": "stdlib/file.html#Base.@__DIR__", - "page": "Filesystem", - "title": "Base.@__DIR__", - "category": "macro", - "text": "@__DIR__ -> AbstractString\n\n@__DIR__ expands to a string with the directory part of the absolute path of the file containing the macro. Returns nothing if run from a REPL or an empty string if evaluated by julia -e .\n\n\n\n" -}, - -{ - "location": "stdlib/file.html#@__LINE__", - "page": "Filesystem", - "title": "@__LINE__", - "category": "macro", - "text": "@__LINE__ -> Int\n\n@__LINE__ expands to the line number of the call-site.\n\n\n\n" -}, - -{ - "location": "stdlib/file.html#Base.Filesystem.isabspath", - "page": "Filesystem", - "title": "Base.Filesystem.isabspath", - "category": "function", - "text": "isabspath(path::AbstractString) -> Bool\n\nDetermines whether a path is absolute (begins at the root directory).\n\njulia> isabspath(\"/home\")\ntrue\n\njulia> isabspath(\"home\")\nfalse\n\n\n\n" -}, - -{ - "location": "stdlib/file.html#Base.Filesystem.isdirpath", - "page": "Filesystem", - "title": "Base.Filesystem.isdirpath", - "category": "function", - "text": "isdirpath(path::AbstractString) -> Bool\n\nDetermines whether a path refers to a directory (for example, ends with a path separator).\n\njulia> isdirpath(\"/home\")\nfalse\n\njulia> isdirpath(\"/home/\")\ntrue\n\n\n\n" -}, - -{ - "location": "stdlib/file.html#Base.Filesystem.joinpath", - "page": "Filesystem", - "title": "Base.Filesystem.joinpath", - "category": "function", - "text": "joinpath(parts...) -> AbstractString\n\nJoin path components into a full path. If some argument is an absolute path, then prior components are dropped.\n\njulia> joinpath(\"/home/myuser\",\"example.jl\")\n\"/home/myuser/example.jl\"\n\n\n\n" -}, - -{ - "location": "stdlib/file.html#Base.Filesystem.abspath", - "page": "Filesystem", - "title": "Base.Filesystem.abspath", - "category": "function", - "text": "abspath(path::AbstractString) -> AbstractString\n\nConvert a path to an absolute path by adding the current directory if necessary.\n\n\n\nabspath(path::AbstractString, paths::AbstractString...) -> AbstractString\n\nConvert a set of paths to an absolute path by joining them together and adding the current directory if necessary. Equivalent to abspath(joinpath(path, paths...)).\n\n\n\n" -}, - -{ - "location": "stdlib/file.html#Base.Filesystem.normpath", - "page": "Filesystem", - "title": "Base.Filesystem.normpath", - "category": "function", - "text": "normpath(path::AbstractString) -> AbstractString\n\nNormalize a path, removing \".\" and \"..\" entries.\n\njulia> normpath(\"/home/myuser/../example.jl\")\n\"/home/example.jl\"\n\n\n\n" -}, - -{ - "location": "stdlib/file.html#Base.Filesystem.realpath", - "page": "Filesystem", - "title": "Base.Filesystem.realpath", - "category": "function", - "text": "realpath(path::AbstractString) -> AbstractString\n\nCanonicalize a path by expanding symbolic links and removing \".\" and \"..\" entries.\n\n\n\n" -}, - -{ - "location": "stdlib/file.html#Base.Filesystem.relpath", - "page": "Filesystem", - "title": "Base.Filesystem.relpath", - "category": "function", - "text": "relpath(path::AbstractString, startpath::AbstractString = \".\") -> AbstractString\n\nReturn a relative filepath to path either from the current directory or from an optional start directory. This is a path computation: the filesystem is not accessed to confirm the existence or nature of path or startpath.\n\n\n\n" -}, - -{ - "location": "stdlib/file.html#Base.Filesystem.expanduser", - "page": "Filesystem", - "title": "Base.Filesystem.expanduser", - "category": "function", - "text": "expanduser(path::AbstractString) -> AbstractString\n\nOn Unix systems, replace a tilde character at the start of a path with the current user\'s home directory.\n\n\n\n" -}, - -{ - "location": "stdlib/file.html#Base.Filesystem.splitdir", - "page": "Filesystem", - "title": "Base.Filesystem.splitdir", - "category": "function", - "text": "splitdir(path::AbstractString) -> (AbstractString, AbstractString)\n\nSplit a path into a tuple of the directory name and file name.\n\njulia> splitdir(\"/home/myuser\")\n(\"/home\", \"myuser\")\n\n\n\n" -}, - -{ - "location": "stdlib/file.html#Base.Filesystem.splitdrive", - "page": "Filesystem", - "title": "Base.Filesystem.splitdrive", - "category": "function", - "text": "splitdrive(path::AbstractString) -> (AbstractString, AbstractString)\n\nOn Windows, split a path into the drive letter part and the path part. On Unix systems, the first component is always the empty string.\n\n\n\n" -}, - -{ - "location": "stdlib/file.html#Base.Filesystem.splitext", - "page": "Filesystem", - "title": "Base.Filesystem.splitext", - "category": "function", - "text": "splitext(path::AbstractString) -> (AbstractString, AbstractString)\n\nIf the last component of a path contains a dot, split the path into everything before the dot and everything including and after the dot. Otherwise, return a tuple of the argument unmodified and the empty string.\n\njulia> splitext(\"/home/myuser/example.jl\")\n(\"/home/myuser/example\", \".jl\")\n\njulia> splitext(\"/home/myuser/example\")\n(\"/home/myuser/example\", \"\")\n\n\n\n" -}, - -{ - "location": "stdlib/file.html#Filesystem-1", - "page": "Filesystem", - "title": "Filesystem", - "category": "section", - "text": "Base.Filesystem.pwd\nBase.Filesystem.cd(::AbstractString)\nBase.Filesystem.cd(::Function)\nBase.Filesystem.readdir\nBase.Filesystem.walkdir\nBase.Filesystem.mkdir\nBase.Filesystem.mkpath\nBase.Filesystem.symlink\nBase.Filesystem.readlink\nBase.Filesystem.chmod\nBase.Filesystem.chown\nBase.stat\nBase.Filesystem.lstat\nBase.Filesystem.ctime\nBase.Filesystem.mtime\nBase.Filesystem.filemode\nBase.Filesystem.filesize\nBase.Filesystem.uperm\nBase.Filesystem.gperm\nBase.Filesystem.operm\nBase.Filesystem.cp\nBase.download\nBase.Filesystem.mv\nBase.Filesystem.rm\nBase.Filesystem.touch\nBase.Filesystem.tempname\nBase.Filesystem.tempdir\nBase.Filesystem.mktemp(::Any)\nBase.Filesystem.mktemp(::Function, ::Any)\nBase.Filesystem.mktempdir(::Any)\nBase.Filesystem.mktempdir(::Function, ::Any)\nBase.Filesystem.isblockdev\nBase.Filesystem.ischardev\nBase.Filesystem.isdir\nBase.Filesystem.isfifo\nBase.Filesystem.isfile\nBase.Filesystem.islink\nBase.Filesystem.ismount\nBase.Filesystem.ispath\nBase.Filesystem.issetgid\nBase.Filesystem.issetuid\nBase.Filesystem.issocket\nBase.Filesystem.issticky\nBase.Filesystem.homedir\nBase.Filesystem.dirname\nBase.Filesystem.basename\nBase.@__FILE__\nBase.@__DIR__\n@__LINE__\nBase.Filesystem.isabspath\nBase.Filesystem.isdirpath\nBase.Filesystem.joinpath\nBase.Filesystem.abspath\nBase.Filesystem.normpath\nBase.Filesystem.realpath\nBase.Filesystem.relpath\nBase.Filesystem.expanduser\nBase.Filesystem.splitdir\nBase.Filesystem.splitdrive\nBase.Filesystem.splitext" -}, - -{ - "location": "stdlib/io-network.html#", - "page": "I/O and Network", - "title": "I/O and Network", - "category": "page", - "text": "" -}, - -{ - "location": "stdlib/io-network.html#I/O-and-Network-1", - "page": "I/O and Network", - "title": "I/O and Network", - "category": "section", - "text": "" -}, - -{ - "location": "stdlib/io-network.html#Base.STDOUT", - "page": "I/O and Network", - "title": "Base.STDOUT", - "category": "constant", - "text": "STDOUT\n\nGlobal variable referring to the standard out stream.\n\n\n\n" -}, - -{ - "location": "stdlib/io-network.html#Base.STDERR", - "page": "I/O and Network", - "title": "Base.STDERR", - "category": "constant", - "text": "STDERR\n\nGlobal variable referring to the standard error stream.\n\n\n\n" -}, - -{ - "location": "stdlib/io-network.html#Base.STDIN", - "page": "I/O and Network", - "title": "Base.STDIN", - "category": "constant", - "text": "STDIN\n\nGlobal variable referring to the standard input stream.\n\n\n\n" -}, - -{ - "location": "stdlib/io-network.html#Base.open", - "page": "I/O and Network", - "title": "Base.open", - "category": "function", - "text": "open(filename::AbstractString, [read::Bool, write::Bool, create::Bool, truncate::Bool, append::Bool]) -> IOStream\n\nOpen a file in a mode specified by five boolean arguments. The default is to open files for reading only. Returns a stream for accessing the file.\n\n\n\nopen(filename::AbstractString, [mode::AbstractString]) -> IOStream\n\nAlternate syntax for open, where a string-based mode specifier is used instead of the five booleans. The values of mode correspond to those from fopen(3) or Perl open, and are equivalent to setting the following boolean groups:\n\nMode Description\nr read\nr+ read, write\nw write, create, truncate\nw+ read, write, create, truncate\na write, create, append\na+ read, write, create, append\n\n\n\nopen(f::Function, args...)\n\nApply the function f to the result of open(args...) and close the resulting file descriptor upon completion.\n\nExample: open(readstring, \"file.txt\")\n\n\n\nopen(command, mode::AbstractString=\"r\", stdio=DevNull)\n\nStart running command asynchronously, and return a tuple (stream,process). If mode is \"r\", then stream reads from the process\'s standard output and stdio optionally specifies the process\'s standard input stream. If mode is \"w\", then stream writes to the process\'s standard input and stdio optionally specifies the process\'s standard output stream.\n\n\n\nopen(f::Function, command, mode::AbstractString=\"r\", stdio=DevNull)\n\nSimilar to open(command, mode, stdio), but calls f(stream) on the resulting read or write stream, then closes the stream and waits for the process to complete. Returns the value returned by f.\n\n\n\n" -}, - -{ - "location": "stdlib/io-network.html#Base.IOBuffer", - "page": "I/O and Network", - "title": "Base.IOBuffer", - "category": "type", - "text": "IOBuffer([data,],[readable::Bool=true, writable::Bool=true, [maxsize::Int=typemax(Int)]])\n\nCreate an IOBuffer, which may optionally operate on a pre-existing array. If the readable/writable arguments are given, they restrict whether or not the buffer may be read from or written to respectively. The last argument optionally specifies a size beyond which the buffer may not be grown.\n\n\n\nIOBuffer() -> IOBuffer\n\nCreate an in-memory I/O stream.\n\n\n\nIOBuffer(size::Int)\n\nCreate a fixed size IOBuffer. The buffer will not grow dynamically.\n\n\n\nIOBuffer(string::String)\n\nCreate a read-only IOBuffer on the data underlying the given string.\n\njulia> io = IOBuffer(\"Haho\");\n\njulia> String(take!(io))\n\"Haho\"\n\njulia> String(take!(io))\n\"Haho\"\n\n\n\n" -}, - -{ - "location": "stdlib/io-network.html#Base.take!-Tuple{Base.AbstractIOBuffer}", - "page": "I/O and Network", - "title": "Base.take!", - "category": "method", - "text": "take!(b::IOBuffer)\n\nObtain the contents of an IOBuffer as an array, without copying. Afterwards, the IOBuffer is reset to its initial state.\n\n\n\n" -}, - -{ - "location": "stdlib/io-network.html#Base.fdio", - "page": "I/O and Network", - "title": "Base.fdio", - "category": "function", - "text": "fdio([name::AbstractString, ]fd::Integer[, own::Bool=false]) -> IOStream\n\nCreate an IOStream object from an integer file descriptor. If own is true, closing this object will close the underlying descriptor. By default, an IOStream is closed when it is garbage collected. name allows you to associate the descriptor with a named file.\n\n\n\n" -}, - -{ - "location": "stdlib/io-network.html#Base.flush", - "page": "I/O and Network", - "title": "Base.flush", - "category": "function", - "text": "flush(stream)\n\nCommit all currently buffered writes to the given stream.\n\n\n\n" -}, - -{ - "location": "stdlib/io-network.html#Base.close", - "page": "I/O and Network", - "title": "Base.close", - "category": "function", - "text": "close(stream)\n\nClose an I/O stream. Performs a flush first.\n\n\n\n" -}, - -{ - "location": "stdlib/io-network.html#Base.write", - "page": "I/O and Network", - "title": "Base.write", - "category": "function", - "text": "write(stream::IO, x)\nwrite(filename::AbstractString, x)\n\nWrite the canonical binary representation of a value to the given I/O stream or file. Returns the number of bytes written into the stream.\n\nYou can write multiple values with the same write call. i.e. the following are equivalent:\n\nwrite(stream, x, y...)\nwrite(stream, x) + write(stream, y...)\n\n\n\n" -}, - -{ - "location": "stdlib/io-network.html#Base.read", - "page": "I/O and Network", - "title": "Base.read", - "category": "function", - "text": "read(filename::AbstractString, args...)\n\nOpen a file and read its contents. args is passed to read: this is equivalent to open(io->read(io, args...), filename).\n\n\n\nread(stream::IO, T, dims)\n\nRead a series of values of type T from stream, in canonical binary representation. dims is either a tuple or a series of integer arguments specifying the size of the Array{T} to return.\n\n\n\nread(s::IO, nb=typemax(Int))\n\nRead at most nb bytes from s, returning a Vector{UInt8} of the bytes read.\n\n\n\nread(s::IOStream, nb::Integer; all=true)\n\nRead at most nb bytes from s, returning a Vector{UInt8} of the bytes read.\n\nIf all is true (the default), this function will block repeatedly trying to read all requested bytes, until an error or end-of-file occurs. If all is false, at most one read call is performed, and the amount of data returned is device-dependent. Note that not all stream types support the all option.\n\n\n\nread(stream::IO, T)\n\nRead a single value of type T from stream, in canonical binary representation.\n\n\n\n" -}, - -{ - "location": "stdlib/io-network.html#Base.read!", - "page": "I/O and Network", - "title": "Base.read!", - "category": "function", - "text": "read!(stream::IO, array::Union{Array, BitArray})\nread!(filename::AbstractString, array::Union{Array, BitArray})\n\nRead binary data from an I/O stream or file, filling in array.\n\n\n\n" -}, - -{ - "location": "stdlib/io-network.html#Base.readbytes!", - "page": "I/O and Network", - "title": "Base.readbytes!", - "category": "function", - "text": "readbytes!(stream::IO, b::AbstractVector{UInt8}, nb=length(b))\n\nRead at most nb bytes from stream into b, returning the number of bytes read. The size of b will be increased if needed (i.e. if nb is greater than length(b) and enough bytes could be read), but it will never be decreased.\n\n\n\nreadbytes!(stream::IOStream, b::AbstractVector{UInt8}, nb=length(b); all::Bool=true)\n\nRead at most nb bytes from stream into b, returning the number of bytes read. The size of b will be increased if needed (i.e. if nb is greater than length(b) and enough bytes could be read), but it will never be decreased.\n\nSee read for a description of the all option.\n\n\n\n" -}, - -{ - "location": "stdlib/io-network.html#Base.unsafe_read", - "page": "I/O and Network", - "title": "Base.unsafe_read", - "category": "function", - "text": "unsafe_read(io::IO, ref, nbytes::UInt)\n\nCopy nbytes from the IO stream object into ref (converted to a pointer).\n\nIt is recommended that subtypes T<:IO override the following method signature to provide more efficient implementations: unsafe_read(s::T, p::Ptr{UInt8}, n::UInt)\n\n\n\n" -}, - -{ - "location": "stdlib/io-network.html#Base.unsafe_write", - "page": "I/O and Network", - "title": "Base.unsafe_write", - "category": "function", - "text": "unsafe_write(io::IO, ref, nbytes::UInt)\n\nCopy nbytes from ref (converted to a pointer) into the IO object.\n\nIt is recommended that subtypes T<:IO override the following method signature to provide more efficient implementations: unsafe_write(s::T, p::Ptr{UInt8}, n::UInt)\n\n\n\n" -}, - -{ - "location": "stdlib/io-network.html#Base.position", - "page": "I/O and Network", - "title": "Base.position", - "category": "function", - "text": "position(s)\n\nGet the current position of a stream.\n\n\n\n" -}, - -{ - "location": "stdlib/io-network.html#Base.seek", - "page": "I/O and Network", - "title": "Base.seek", - "category": "function", - "text": "seek(s, pos)\n\nSeek a stream to the given position.\n\n\n\n" -}, - -{ - "location": "stdlib/io-network.html#Base.seekstart", - "page": "I/O and Network", - "title": "Base.seekstart", - "category": "function", - "text": "seekstart(s)\n\nSeek a stream to its beginning.\n\n\n\n" -}, - -{ - "location": "stdlib/io-network.html#Base.seekend", - "page": "I/O and Network", - "title": "Base.seekend", - "category": "function", - "text": "seekend(s)\n\nSeek a stream to its end.\n\n\n\n" -}, - -{ - "location": "stdlib/io-network.html#Base.skip", - "page": "I/O and Network", - "title": "Base.skip", - "category": "function", - "text": "skip(s, offset)\n\nSeek a stream relative to the current position.\n\n\n\n" -}, - -{ - "location": "stdlib/io-network.html#Base.mark", - "page": "I/O and Network", - "title": "Base.mark", - "category": "function", - "text": "mark(s)\n\nAdd a mark at the current position of stream s. Returns the marked position.\n\nSee also unmark, reset, ismarked.\n\n\n\n" -}, - -{ - "location": "stdlib/io-network.html#Base.unmark", - "page": "I/O and Network", - "title": "Base.unmark", - "category": "function", - "text": "unmark(s)\n\nRemove a mark from stream s. Returns true if the stream was marked, false otherwise.\n\nSee also mark, reset, ismarked.\n\n\n\n" -}, - -{ - "location": "stdlib/io-network.html#Base.reset", - "page": "I/O and Network", - "title": "Base.reset", - "category": "function", - "text": "reset(s)\n\nReset a stream s to a previously marked position, and remove the mark. Returns the previously marked position. Throws an error if the stream is not marked.\n\nSee also mark, unmark, ismarked.\n\n\n\n" -}, - -{ - "location": "stdlib/io-network.html#Base.ismarked", - "page": "I/O and Network", - "title": "Base.ismarked", - "category": "function", - "text": "ismarked(s)\n\nReturns true if stream s is marked.\n\nSee also mark, unmark, reset.\n\n\n\n" -}, - -{ - "location": "stdlib/io-network.html#Base.eof", - "page": "I/O and Network", - "title": "Base.eof", - "category": "function", - "text": "eof(stream) -> Bool\n\nTests whether an I/O stream is at end-of-file. If the stream is not yet exhausted, this function will block to wait for more data if necessary, and then return false. Therefore it is always safe to read one byte after seeing eof return false. eof will return false as long as buffered data is still available, even if the remote end of a connection is closed.\n\n\n\n" -}, - -{ - "location": "stdlib/io-network.html#Base.isreadonly", - "page": "I/O and Network", - "title": "Base.isreadonly", - "category": "function", - "text": "isreadonly(stream) -> Bool\n\nDetermine whether a stream is read-only.\n\n\n\n" -}, - -{ - "location": "stdlib/io-network.html#Base.iswritable", - "page": "I/O and Network", - "title": "Base.iswritable", - "category": "function", - "text": "iswritable(io) -> Bool\n\nReturns true if the specified IO object is writable (if that can be determined).\n\n\n\n" -}, - -{ - "location": "stdlib/io-network.html#Base.isreadable", - "page": "I/O and Network", - "title": "Base.isreadable", - "category": "function", - "text": "isreadable(io) -> Bool\n\nReturns true if the specified IO object is readable (if that can be determined).\n\n\n\n" -}, - -{ - "location": "stdlib/io-network.html#Base.isopen", - "page": "I/O and Network", - "title": "Base.isopen", - "category": "function", - "text": "isopen(object) -> Bool\n\nDetermine whether an object - such as a stream, timer, or mmap – is not yet closed. Once an object is closed, it will never produce a new event. However, a closed stream may still have data to read in its buffer, use eof to check for the ability to read data. Use poll_fd to be notified when a stream might be writable or readable.\n\n\n\n" -}, - -{ - "location": "stdlib/io-network.html#Base.Serializer.serialize", - "page": "I/O and Network", - "title": "Base.Serializer.serialize", - "category": "function", - "text": "serialize(stream, value)\n\nWrite an arbitrary value to a stream in an opaque format, such that it can be read back by deserialize. The read-back value will be as identical as possible to the original. In general, this process will not work if the reading and writing are done by different versions of Julia, or an instance of Julia with a different system image. Ptr values are serialized as all-zero bit patterns (NULL).\n\n\n\n" -}, - -{ - "location": "stdlib/io-network.html#Base.Serializer.deserialize", - "page": "I/O and Network", - "title": "Base.Serializer.deserialize", - "category": "function", - "text": "deserialize(stream)\n\nRead a value written by serialize. deserialize assumes the binary data read from stream is correct and has been serialized by a compatible implementation of serialize. It has been designed with simplicity and performance as a goal and does not validate the data read. Malformed data can result in process termination. The caller has to ensure the integrity and correctness of data read from stream.\n\n\n\n" -}, - -{ - "location": "stdlib/io-network.html#Base.Grisu.print_shortest", - "page": "I/O and Network", - "title": "Base.Grisu.print_shortest", - "category": "function", - "text": "print_shortest(io, x)\n\nPrint the shortest possible representation, with the minimum number of consecutive non-zero digits, of number x, ensuring that it would parse to the exact same number.\n\n\n\n" -}, - -{ - "location": "stdlib/io-network.html#Base.fd", - "page": "I/O and Network", - "title": "Base.fd", - "category": "function", - "text": "fd(stream)\n\nReturns the file descriptor backing the stream or file. Note that this function only applies to synchronous File\'s and IOStream\'s not to any of the asynchronous streams.\n\n\n\n" -}, - -{ - "location": "stdlib/io-network.html#Base.redirect_stdout", - "page": "I/O and Network", - "title": "Base.redirect_stdout", - "category": "function", - "text": "redirect_stdout([stream]) -> (rd, wr)\n\nCreate a pipe to which all C and Julia level STDOUT output will be redirected. Returns a tuple (rd, wr) representing the pipe ends. Data written to STDOUT may now be read from the rd end of the pipe. The wr end is given for convenience in case the old STDOUT object was cached by the user and needs to be replaced elsewhere.\n\nnote: Note\nstream must be a TTY, a Pipe, or a TCPSocket.\n\n\n\n" -}, - -{ - "location": "stdlib/io-network.html#Base.redirect_stdout-Tuple{Function,Any}", - "page": "I/O and Network", - "title": "Base.redirect_stdout", - "category": "method", - "text": "redirect_stdout(f::Function, stream)\n\nRun the function f while redirecting STDOUT to stream. Upon completion, STDOUT is restored to its prior setting.\n\nnote: Note\nstream must be a TTY, a Pipe, or a TCPSocket.\n\n\n\n" -}, - -{ - "location": "stdlib/io-network.html#Base.redirect_stderr", - "page": "I/O and Network", - "title": "Base.redirect_stderr", - "category": "function", - "text": "redirect_stderr([stream]) -> (rd, wr)\n\nLike redirect_stdout, but for STDERR.\n\nnote: Note\nstream must be a TTY, a Pipe, or a TCPSocket.\n\n\n\n" -}, - -{ - "location": "stdlib/io-network.html#Base.redirect_stderr-Tuple{Function,Any}", - "page": "I/O and Network", - "title": "Base.redirect_stderr", - "category": "method", - "text": "redirect_stderr(f::Function, stream)\n\nRun the function f while redirecting STDERR to stream. Upon completion, STDERR is restored to its prior setting.\n\nnote: Note\nstream must be a TTY, a Pipe, or a TCPSocket.\n\n\n\n" -}, - -{ - "location": "stdlib/io-network.html#Base.redirect_stdin", - "page": "I/O and Network", - "title": "Base.redirect_stdin", - "category": "function", - "text": "redirect_stdin([stream]) -> (rd, wr)\n\nLike redirect_stdout, but for STDIN. Note that the order of the return tuple is still (rd, wr), i.e. data to be read from STDIN may be written to wr.\n\nnote: Note\nstream must be a TTY, a Pipe, or a TCPSocket.\n\n\n\n" -}, - -{ - "location": "stdlib/io-network.html#Base.redirect_stdin-Tuple{Function,Any}", - "page": "I/O and Network", - "title": "Base.redirect_stdin", - "category": "method", - "text": "redirect_stdin(f::Function, stream)\n\nRun the function f while redirecting STDIN to stream. Upon completion, STDIN is restored to its prior setting.\n\nnote: Note\nstream must be a TTY, a Pipe, or a TCPSocket.\n\n\n\n" -}, - -{ - "location": "stdlib/io-network.html#Base.readchomp", - "page": "I/O and Network", - "title": "Base.readchomp", - "category": "function", - "text": "readchomp(x)\n\nRead the entirety of x as a string and remove a single trailing newline. Equivalent to chomp!(readstring(x)).\n\n\n\n" -}, - -{ - "location": "stdlib/io-network.html#Base.truncate", - "page": "I/O and Network", - "title": "Base.truncate", - "category": "function", - "text": "truncate(file,n)\n\nResize the file or buffer given by the first argument to exactly n bytes, filling previously unallocated space with \'\\0\' if the file or buffer is grown.\n\n\n\n" -}, - -{ - "location": "stdlib/io-network.html#Base.skipchars", - "page": "I/O and Network", - "title": "Base.skipchars", - "category": "function", - "text": "skipchars(stream, predicate; linecomment::Char)\n\nAdvance the stream until before the first character for which predicate returns false. For example skipchars(stream, isspace) will skip all whitespace. If keyword argument linecomment is specified, characters from that character through the end of a line will also be skipped.\n\n\n\n" -}, - -{ - "location": "stdlib/io-network.html#Base.DataFmt.countlines", - "page": "I/O and Network", - "title": "Base.DataFmt.countlines", - "category": "function", - "text": "countlines(io::IO, eol::Char=\'\\n\')\n\nRead io until the end of the stream/file and count the number of lines. To specify a file pass the filename as the first argument. EOL markers other than \'\\n\' are supported by passing them as the second argument.\n\n\n\n" -}, - -{ - "location": "stdlib/io-network.html#Base.PipeBuffer", - "page": "I/O and Network", - "title": "Base.PipeBuffer", - "category": "function", - "text": "PipeBuffer(data::Vector{UInt8}=UInt8[],[maxsize::Int=typemax(Int)])\n\nAn IOBuffer that allows reading and performs writes by appending. Seeking and truncating are not supported. See IOBuffer for the available constructors. If data is given, creates a PipeBuffer to operate on a data vector, optionally specifying a size beyond which the underlying Array may not be grown.\n\n\n\n" -}, - -{ - "location": "stdlib/io-network.html#Base.readavailable", - "page": "I/O and Network", - "title": "Base.readavailable", - "category": "function", - "text": "readavailable(stream)\n\nRead all available data on the stream, blocking the task only if no data is available. The result is a Vector{UInt8,1}.\n\n\n\n" -}, - -{ - "location": "stdlib/io-network.html#Base.IOContext", - "page": "I/O and Network", - "title": "Base.IOContext", - "category": "type", - "text": "IOContext\n\nIOContext provides a mechanism for passing output configuration settings among show methods.\n\nIn short, it is an immutable dictionary that is a subclass of IO. It supports standard dictionary operations such as getindex, and can also be used as an I/O stream.\n\n\n\n" -}, - -{ - "location": "stdlib/io-network.html#Base.IOContext-Tuple{IO,Pair}", - "page": "I/O and Network", - "title": "Base.IOContext", - "category": "method", - "text": "IOContext(io::IO, KV::Pair)\n\nCreate an IOContext that wraps a given stream, adding the specified key=>value pair to the properties of that stream (note that io can itself be an IOContext).\n\nuse (key => value) in dict to see if this particular combination is in the properties set\nuse get(dict, key, default) to retrieve the most recent value for a particular key\n\nThe following properties are in common use:\n\n:compact: Boolean specifying that small values should be printed more compactly, e.g. that numbers should be printed with fewer digits. This is set when printing array elements.\n:limit: Boolean specifying that containers should be truncated, e.g. showing … in place of most elements.\n:displaysize: A Tuple{Int,Int} giving the size in rows and columns to use for text output. This can be used to override the display size for called functions, but to get the size of the screen use the displaysize function.\n\njulia> function f(io::IO)\n if get(io, :short, false)\n print(io, \"short\")\n else\n print(io, \"loooooong\")\n end\n end\nf (generic function with 1 method)\n\njulia> f(STDOUT)\nloooooong\njulia> f(IOContext(STDOUT, :short => true))\nshort\n\n\n\n" -}, - -{ - "location": "stdlib/io-network.html#Base.IOContext-Tuple{IO,IOContext}", - "page": "I/O and Network", - "title": "Base.IOContext", - "category": "method", - "text": "IOContext(io::IO, context::IOContext)\n\nCreate an IOContext that wraps an alternate IO but inherits the properties of context.\n\n\n\n" -}, - -{ - "location": "stdlib/io-network.html#General-I/O-1", - "page": "I/O and Network", - "title": "General I/O", - "category": "section", - "text": "Base.STDOUT\nBase.STDERR\nBase.STDIN\nBase.open\nBase.IOBuffer\nBase.take!(::Base.AbstractIOBuffer)\nBase.fdio\nBase.flush\nBase.close\nBase.write\nBase.read\nBase.read!\nBase.readbytes!\nBase.unsafe_read\nBase.unsafe_write\nBase.position\nBase.seek\nBase.seekstart\nBase.seekend\nBase.skip\nBase.mark\nBase.unmark\nBase.reset\nBase.ismarked\nBase.eof\nBase.isreadonly\nBase.iswritable\nBase.isreadable\nBase.isopen\nBase.Serializer.serialize\nBase.Serializer.deserialize\nBase.Grisu.print_shortest\nBase.fd\nBase.redirect_stdout\nBase.redirect_stdout(::Function, ::Any)\nBase.redirect_stderr\nBase.redirect_stderr(::Function, ::Any)\nBase.redirect_stdin\nBase.redirect_stdin(::Function, ::Any)\nBase.readchomp\nBase.truncate\nBase.skipchars\nBase.DataFmt.countlines\nBase.PipeBuffer\nBase.readavailable\nBase.IOContext\nBase.IOContext(::IO, ::Pair)\nBase.IOContext(::IO, ::IOContext)" -}, - -{ - "location": "stdlib/io-network.html#Base.show-Tuple{Any}", - "page": "I/O and Network", - "title": "Base.show", - "category": "method", - "text": "show(x)\n\nWrite an informative text representation of a value to the current output stream. New types should overload show(io, x) where the first argument is a stream. The representation used by show generally includes Julia-specific formatting and type information.\n\n\n\n" -}, - -{ - "location": "stdlib/io-network.html#Base.showcompact", - "page": "I/O and Network", - "title": "Base.showcompact", - "category": "function", - "text": "showcompact(x)\n\nShow a compact representation of a value.\n\nThis is used for printing array elements without repeating type information (which would be redundant with that printed once for the whole array), and without line breaks inside the representation of an element.\n\nTo offer a compact representation different from its standard one, a custom type should test get(io, :compact, false) in its normal show method.\n\n\n\n" -}, - -{ - "location": "stdlib/io-network.html#Base.showall", - "page": "I/O and Network", - "title": "Base.showall", - "category": "function", - "text": "showall(x)\n\nSimilar to show, except shows all elements of arrays.\n\n\n\n" -}, - -{ - "location": "stdlib/io-network.html#Base.summary", - "page": "I/O and Network", - "title": "Base.summary", - "category": "function", - "text": "summary(x)\n\nReturn a string giving a brief description of a value. By default returns string(typeof(x)), e.g. Int64.\n\nFor arrays, returns a string of size and type info, e.g. 10-element Array{Int64,1}.\n\njulia> summary(1)\n\"Int64\"\n\njulia> summary(zeros(2))\n\"2-element Array{Float64,1}\"\n\n\n\n" -}, - -{ - "location": "stdlib/io-network.html#Base.print", - "page": "I/O and Network", - "title": "Base.print", - "category": "function", - "text": "print(io::IO, x)\n\nWrite to io (or to the default output stream STDOUT if io is not given) a canonical (un-decorated) text representation of a value if there is one, otherwise call show. The representation used by print includes minimal formatting and tries to avoid Julia-specific details.\n\njulia> print(\"Hello World!\")\nHello World!\njulia> io = IOBuffer();\n\njulia> print(io, \"Hello World!\")\n\njulia> String(take!(io))\n\"Hello World!\"\n\n\n\n" -}, - -{ - "location": "stdlib/io-network.html#Base.println", - "page": "I/O and Network", - "title": "Base.println", - "category": "function", - "text": "println(io::IO, xs...)\n\nPrint (using print) xs followed by a newline. If io is not supplied, prints to STDOUT.\n\n\n\n" -}, - -{ - "location": "stdlib/io-network.html#Base.print_with_color", - "page": "I/O and Network", - "title": "Base.print_with_color", - "category": "function", - "text": "print_with_color(color::Union{Symbol, Int}, [io], xs...; bold::Bool = false)\n\nPrint xs in a color specified as a symbol.\n\ncolor may take any of the values :normal, :default, :bold, :black, :blue, :cyan, :green, :light_black, :light_blue, :light_cyan, :light_green, :light_magenta, :light_red, :light_yellow, :magenta, :nothing, :red, :white, or :yellow or an integer between 0 and 255 inclusive. Note that not all terminals support 256 colors. If the keyword bold is given as true, the result will be printed in bold.\n\n\n\n" -}, - -{ - "location": "stdlib/io-network.html#Base.info", - "page": "I/O and Network", - "title": "Base.info", - "category": "function", - "text": "info([io, ] msg..., [prefix=\"INFO: \"])\n\nDisplay an informational message. Argument msg is a string describing the information to be displayed. The prefix keyword argument can be used to override the default prepending of msg.\n\njulia> info(\"hello world\")\nINFO: hello world\n\njulia> info(\"hello world\"; prefix=\"MY INFO: \")\nMY INFO: hello world\n\nSee also logging.\n\n\n\n" -}, - -{ - "location": "stdlib/io-network.html#Base.warn", - "page": "I/O and Network", - "title": "Base.warn", - "category": "function", - "text": "warn([io, ] msg..., [prefix=\"WARNING: \", once=false, key=nothing, bt=nothing, filename=nothing, lineno::Int=0])\n\nDisplay a warning. Argument msg is a string describing the warning to be displayed. Set once to true and specify a key to only display msg the first time warn is called. If bt is not nothing a backtrace is displayed. If filename is not nothing both it and lineno are displayed.\n\nSee also logging.\n\n\n\nwarn(msg)\n\nDisplay a warning. Argument msg is a string describing the warning to be displayed.\n\njulia> warn(\"Beep Beep\")\nWARNING: Beep Beep\n\n\n\n" -}, - -{ - "location": "stdlib/io-network.html#Base.logging", - "page": "I/O and Network", - "title": "Base.logging", - "category": "function", - "text": "logging(io [, m [, f]][; kind=:all])\nlogging([; kind=:all])\n\nStream output of informational, warning, and/or error messages to io, overriding what was otherwise specified. Optionally, divert stream only for module m, or specifically function f within m. kind can be :all (the default), :info, :warn, or :error. See Base.log_{info,warn,error}_to for the current set of redirections. Call logging with no arguments (or just the kind) to reset everything.\n\n\n\n" -}, - -{ - "location": "stdlib/io-network.html#Base.Printf.@printf", - "page": "I/O and Network", - "title": "Base.Printf.@printf", - "category": "macro", - "text": "@printf([io::IOStream], \"%Fmt\", args...)\n\nPrint args using C printf() style format specification string, with some caveats: Inf and NaN are printed consistently as Inf and NaN for flags %a, %A, %e, %E, %f, %F, %g, and %G. Furthermore, if a floating point number is equally close to the numeric values of two possible output strings, the output string further away from zero is chosen.\n\nOptionally, an IOStream may be passed as the first argument to redirect output.\n\nExamples\n\njulia> @printf(\"%f %F %f %F\\n\", Inf, Inf, NaN, NaN)\nInf Inf NaN NaN\n\n\njulia> @printf \"%.0f %.1f %f\\n\" 0.5 0.025 -0.0078125\n1 0.0 -0.007813\n\n\n\n" -}, - -{ - "location": "stdlib/io-network.html#Base.Printf.@sprintf", - "page": "I/O and Network", - "title": "Base.Printf.@sprintf", - "category": "macro", - "text": "@sprintf(\"%Fmt\", args...)\n\nReturn @printf formatted output as string.\n\nExamples\n\njulia> s = @sprintf \"this is a %s %15.1f\" \"test\" 34.567;\n\njulia> println(s)\nthis is a test 34.6\n\n\n\n" -}, - -{ - "location": "stdlib/io-network.html#Base.sprint", - "page": "I/O and Network", - "title": "Base.sprint", - "category": "function", - "text": "sprint(f::Function, args...)\n\nCall the given function with an I/O stream and the supplied extra arguments. Everything written to this I/O stream is returned as a string.\n\njulia> sprint(showcompact, 66.66666)\n\"66.6667\"\n\n\n\n" -}, - -{ - "location": "stdlib/io-network.html#Base.showerror", - "page": "I/O and Network", - "title": "Base.showerror", - "category": "function", - "text": "showerror(io, e)\n\nShow a descriptive representation of an exception object.\n\n\n\n" -}, - -{ - "location": "stdlib/io-network.html#Base.dump", - "page": "I/O and Network", - "title": "Base.dump", - "category": "function", - "text": "dump(x)\n\nShow every part of the representation of a value.\n\n\n\n" -}, - -{ - "location": "stdlib/io-network.html#Base.readstring", - "page": "I/O and Network", - "title": "Base.readstring", - "category": "function", - "text": "readstring(stream::IO)\nreadstring(filename::AbstractString)\n\nRead the entire contents of an I/O stream or a file as a string. The text is assumed to be encoded in UTF-8.\n\n\n\n" -}, - -{ - "location": "stdlib/io-network.html#Base.readline", - "page": "I/O and Network", - "title": "Base.readline", - "category": "function", - "text": "readline(stream::IO=STDIN; chomp::Bool=true)\nreadline(filename::AbstractString; chomp::Bool=true)\n\nRead a single line of text from the given I/O stream or file (defaults to STDIN). When reading from a file, the text is assumed to be encoded in UTF-8. Lines in the input end with \'\\n\' or \"\\r\\n\" or the end of an input stream. When chomp is true (as it is by default), these trailing newline characters are removed from the line before it is returned. When chomp is false, they are returned as part of the line.\n\n\n\n" -}, - -{ - "location": "stdlib/io-network.html#Base.readuntil", - "page": "I/O and Network", - "title": "Base.readuntil", - "category": "function", - "text": "readuntil(stream::IO, delim)\nreaduntil(filename::AbstractString, delim)\n\nRead a string from an I/O stream or a file, up to and including the given delimiter byte. The text is assumed to be encoded in UTF-8.\n\n\n\n" -}, - -{ - "location": "stdlib/io-network.html#Base.readlines", - "page": "I/O and Network", - "title": "Base.readlines", - "category": "function", - "text": "readlines(stream::IO=STDIN; chomp::Bool=true)\nreadlines(filename::AbstractString; chomp::Bool=true)\n\nRead all lines of an I/O stream or a file as a vector of strings. Behavior is equivalent to saving the result of reading readline repeatedly with the same arguments and saving the resulting lines as a vector of strings.\n\n\n\n" -}, - -{ - "location": "stdlib/io-network.html#Base.eachline", - "page": "I/O and Network", - "title": "Base.eachline", - "category": "function", - "text": "eachline(stream::IO=STDIN; chomp::Bool=true)\neachline(filename::AbstractString; chomp::Bool=true)\n\nCreate an iterable EachLine object that will yield each line from an I/O stream or a file. Iteration calls readline on the stream argument repeatedly with chomp passed through, determining whether trailing end-of-line characters are removed. When called with a file name, the file is opened once at the beginning of iteration and closed at the end. If iteration is interrupted, the file will be closed when the EachLine object is garbage collected.\n\n\n\n" -}, - -{ - "location": "stdlib/io-network.html#Base.DataFmt.readdlm-Tuple{Any,Char,Type,Char}", - "page": "I/O and Network", - "title": "Base.DataFmt.readdlm", - "category": "method", - "text": "readdlm(source, delim::Char, T::Type, eol::Char; header=false, skipstart=0, skipblanks=true, use_mmap, quotes=true, dims, comments=true, comment_char=\'#\')\n\nRead a matrix from the source where each line (separated by eol) gives one row, with elements separated by the given delimiter. The source can be a text file, stream or byte array. Memory mapped files can be used by passing the byte array representation of the mapped segment as source.\n\nIf T is a numeric type, the result is an array of that type, with any non-numeric elements as NaN for floating-point types, or zero. Other useful values of T include String, AbstractString, and Any.\n\nIf header is true, the first row of data will be read as header and the tuple (data_cells, header_cells) is returned instead of only data_cells.\n\nSpecifying skipstart will ignore the corresponding number of initial lines from the input.\n\nIf skipblanks is true, blank lines in the input will be ignored.\n\nIf use_mmap is true, the file specified by source is memory mapped for potential speedups. Default is true except on Windows. On Windows, you may want to specify true if the file is large, and is only read once and not written to.\n\nIf quotes is true, columns enclosed within double-quote (\") characters are allowed to contain new lines and column delimiters. Double-quote characters within a quoted field must be escaped with another double-quote. Specifying dims as a tuple of the expected rows and columns (including header, if any) may speed up reading of large files. If comments is true, lines beginning with comment_char and text following comment_char in any line are ignored.\n\n\n\n" -}, - -{ - "location": "stdlib/io-network.html#Base.DataFmt.readdlm-Tuple{Any,Char,Char}", - "page": "I/O and Network", - "title": "Base.DataFmt.readdlm", - "category": "method", - "text": "readdlm(source, delim::Char, eol::Char; options...)\n\nIf all data is numeric, the result will be a numeric array. If some elements cannot be parsed as numbers, a heterogeneous array of numbers and strings is returned.\n\n\n\n" -}, - -{ - "location": "stdlib/io-network.html#Base.DataFmt.readdlm-Tuple{Any,Char,Type}", - "page": "I/O and Network", - "title": "Base.DataFmt.readdlm", - "category": "method", - "text": "readdlm(source, delim::Char, T::Type; options...)\n\nThe end of line delimiter is taken as \\n.\n\n\n\n" -}, - -{ - "location": "stdlib/io-network.html#Base.DataFmt.readdlm-Tuple{Any,Char}", - "page": "I/O and Network", - "title": "Base.DataFmt.readdlm", - "category": "method", - "text": "readdlm(source, delim::Char; options...)\n\nThe end of line delimiter is taken as \\n. If all data is numeric, the result will be a numeric array. If some elements cannot be parsed as numbers, a heterogeneous array of numbers and strings is returned.\n\n\n\n" -}, - -{ - "location": "stdlib/io-network.html#Base.DataFmt.readdlm-Tuple{Any,Type}", - "page": "I/O and Network", - "title": "Base.DataFmt.readdlm", - "category": "method", - "text": "readdlm(source, T::Type; options...)\n\nThe columns are assumed to be separated by one or more whitespaces. The end of line delimiter is taken as \\n.\n\n\n\n" -}, - -{ - "location": "stdlib/io-network.html#Base.DataFmt.readdlm-Tuple{Any}", - "page": "I/O and Network", - "title": "Base.DataFmt.readdlm", - "category": "method", - "text": "readdlm(source; options...)\n\nThe columns are assumed to be separated by one or more whitespaces. The end of line delimiter is taken as \\n. If all data is numeric, the result will be a numeric array. If some elements cannot be parsed as numbers, a heterogeneous array of numbers and strings is returned.\n\n\n\n" -}, - -{ - "location": "stdlib/io-network.html#Base.DataFmt.writedlm", - "page": "I/O and Network", - "title": "Base.DataFmt.writedlm", - "category": "function", - "text": "writedlm(f, A, delim=\'\\t\'; opts)\n\nWrite A (a vector, matrix, or an iterable collection of iterable rows) as text to f (either a filename string or an IO stream) using the given delimiter delim (which defaults to tab, but can be any printable Julia object, typically a Char or AbstractString).\n\nFor example, two vectors x and y of the same length can be written as two columns of tab-delimited text to f by either writedlm(f, [x y]) or by writedlm(f, zip(x, y)).\n\n\n\n" -}, - -{ - "location": "stdlib/io-network.html#Base.DataFmt.readcsv", - "page": "I/O and Network", - "title": "Base.DataFmt.readcsv", - "category": "function", - "text": "readcsv(source, [T::Type]; options...)\n\nEquivalent to readdlm with delim set to comma, and type optionally defined by T.\n\n\n\n" -}, - -{ - "location": "stdlib/io-network.html#Base.DataFmt.writecsv", - "page": "I/O and Network", - "title": "Base.DataFmt.writecsv", - "category": "function", - "text": "writecsv(filename, A; opts)\n\nEquivalent to writedlm with delim set to comma.\n\n\n\n" -}, - -{ - "location": "stdlib/io-network.html#Base.Base64.Base64EncodePipe", - "page": "I/O and Network", - "title": "Base.Base64.Base64EncodePipe", - "category": "type", - "text": "Base64EncodePipe(ostream)\n\nReturns a new write-only I/O stream, which converts any bytes written to it into base64-encoded ASCII bytes written to ostream. Calling close on the Base64EncodePipe stream is necessary to complete the encoding (but does not close ostream).\n\njulia> io = IOBuffer();\n\njulia> iob64_encode = Base64EncodePipe(io);\n\njulia> write(iob64_encode, \"Hello!\")\n6\n\njulia> close(iob64_encode);\n\njulia> str = String(take!(io))\n\"SGVsbG8h\"\n\njulia> String(base64decode(str))\n\"Hello!\"\n\n\n\n" -}, - -{ - "location": "stdlib/io-network.html#Base.Base64.Base64DecodePipe", - "page": "I/O and Network", - "title": "Base.Base64.Base64DecodePipe", - "category": "type", - "text": "Base64DecodePipe(istream)\n\nReturns a new read-only I/O stream, which decodes base64-encoded data read from istream.\n\njulia> io = IOBuffer();\n\njulia> iob64_decode = Base64DecodePipe(io);\n\njulia> write(io, \"SGVsbG8h\")\n8\n\njulia> seekstart(io);\n\njulia> String(read(iob64_decode))\n\"Hello!\"\n\n\n\n" -}, - -{ - "location": "stdlib/io-network.html#Base.Base64.base64encode", - "page": "I/O and Network", - "title": "Base.Base64.base64encode", - "category": "function", - "text": "base64encode(writefunc, args...)\nbase64encode(args...)\n\nGiven a write-like function writefunc, which takes an I/O stream as its first argument, base64encode(writefunc, args...) calls writefunc to write args... to a base64-encoded string, and returns the string. base64encode(args...) is equivalent to base64encode(write, args...): it converts its arguments into bytes using the standard write functions and returns the base64-encoded string.\n\nSee also base64decode.\n\n\n\n" -}, - -{ - "location": "stdlib/io-network.html#Base.Base64.base64decode", - "page": "I/O and Network", - "title": "Base.Base64.base64decode", - "category": "function", - "text": "base64decode(string)\n\nDecodes the base64-encoded string and returns a Vector{UInt8} of the decoded bytes.\n\nSee also base64encode\n\njulia> b = base64decode(\"SGVsbG8h\")\n6-element Array{UInt8,1}:\n 0x48\n 0x65\n 0x6c\n 0x6c\n 0x6f\n 0x21\n\njulia> String(b)\n\"Hello!\"\n\n\n\n" -}, - -{ - "location": "stdlib/io-network.html#Base.displaysize", - "page": "I/O and Network", - "title": "Base.displaysize", - "category": "function", - "text": "displaysize(io) -> (lines, columns)\n\nReturn the nominal size of the screen that may be used for rendering output to this io object\n\n\n\n" -}, - -{ - "location": "stdlib/io-network.html#Text-I/O-1", - "page": "I/O and Network", - "title": "Text I/O", - "category": "section", - "text": "Base.show(::Any)\nBase.showcompact\nBase.showall\nBase.summary\nBase.print\nBase.println\nBase.print_with_color\nBase.info\nBase.warn\nBase.logging\nBase.Printf.@printf\nBase.Printf.@sprintf\nBase.sprint\nBase.showerror\nBase.dump\nBase.readstring\nBase.readline\nBase.readuntil\nBase.readlines\nBase.eachline\nBase.DataFmt.readdlm(::Any, ::Char, ::Type, ::Char)\nBase.DataFmt.readdlm(::Any, ::Char, ::Char)\nBase.DataFmt.readdlm(::Any, ::Char, ::Type)\nBase.DataFmt.readdlm(::Any, ::Char)\nBase.DataFmt.readdlm(::Any, ::Type)\nBase.DataFmt.readdlm(::Any)\nBase.DataFmt.writedlm\nBase.DataFmt.readcsv\nBase.DataFmt.writecsv\nBase.Base64.Base64EncodePipe\nBase.Base64.Base64DecodePipe\nBase.Base64.base64encode\nBase.Base64.base64decode\nBase.displaysize" -}, - -{ - "location": "stdlib/io-network.html#Base.Multimedia.display", - "page": "I/O and Network", - "title": "Base.Multimedia.display", - "category": "function", - "text": "display(x)\ndisplay(d::Display, x)\ndisplay(mime, x)\ndisplay(d::Display, mime, x)\n\nDisplay x using the topmost applicable display in the display stack, typically using the richest supported multimedia output for x, with plain-text STDOUT output as a fallback. The display(d, x) variant attempts to display x on the given display d only, throwing a MethodError if d cannot display objects of this type.\n\nThere are also two variants with a mime argument (a MIME type string, such as \"image/png\"), which attempt to display x using the requested MIME type only, throwing a MethodError if this type is not supported by either the display(s) or by x. With these variants, one can also supply the \"raw\" data in the requested MIME type by passing x::AbstractString (for MIME types with text-based storage, such as text/html or application/postscript) or x::Vector{UInt8} (for binary MIME types).\n\n\n\n" -}, - -{ - "location": "stdlib/io-network.html#Base.Multimedia.redisplay", - "page": "I/O and Network", - "title": "Base.Multimedia.redisplay", - "category": "function", - "text": "redisplay(x)\nredisplay(d::Display, x)\nredisplay(mime, x)\nredisplay(d::Display, mime, x)\n\nBy default, the redisplay functions simply call display. However, some display backends may override redisplay to modify an existing display of x (if any). Using redisplay is also a hint to the backend that x may be redisplayed several times, and the backend may choose to defer the display until (for example) the next interactive prompt.\n\n\n\n" -}, - -{ - "location": "stdlib/io-network.html#Base.Multimedia.displayable", - "page": "I/O and Network", - "title": "Base.Multimedia.displayable", - "category": "function", - "text": "displayable(mime) -> Bool\ndisplayable(d::Display, mime) -> Bool\n\nReturns a boolean value indicating whether the given mime type (string) is displayable by any of the displays in the current display stack, or specifically by the display d in the second variant.\n\n\n\n" -}, - -{ - "location": "stdlib/io-network.html#Base.show-Tuple{Any,Any,Any}", - "page": "I/O and Network", - "title": "Base.show", - "category": "method", - "text": "show(stream, mime, x)\n\nThe display functions ultimately call show in order to write an object x as a given mime type to a given I/O stream (usually a memory buffer), if possible. In order to provide a rich multimedia representation of a user-defined type T, it is only necessary to define a new show method for T, via: show(stream, ::MIME\"mime\", x::T) = ..., where mime is a MIME-type string and the function body calls write (or similar) to write that representation of x to stream. (Note that the MIME\"\" notation only supports literal strings; to construct MIME types in a more flexible manner use MIME{Symbol(\"\")}.)\n\nFor example, if you define a MyImage type and know how to write it to a PNG file, you could define a function show(stream, ::MIME\"image/png\", x::MyImage) = ... to allow your images to be displayed on any PNG-capable Display (such as IJulia). As usual, be sure to import Base.show in order to add new methods to the built-in Julia function show.\n\nThe default MIME type is MIME\"text/plain\". There is a fallback definition for text/plain output that calls show with 2 arguments. Therefore, this case should be handled by defining a 2-argument show(stream::IO, x::MyType) method.\n\nTechnically, the MIME\"mime\" macro defines a singleton type for the given mime string, which allows us to exploit Julia\'s dispatch mechanisms in determining how to display objects of any given type.\n\nThe first argument to show can be an IOContext specifying output format properties. See IOContext for details.\n\n\n\n" -}, - -{ - "location": "stdlib/io-network.html#Base.Multimedia.mimewritable", - "page": "I/O and Network", - "title": "Base.Multimedia.mimewritable", - "category": "function", - "text": "mimewritable(mime, x)\n\nReturns a boolean value indicating whether or not the object x can be written as the given mime type. (By default, this is determined automatically by the existence of the corresponding show method for typeof(x).)\n\n\n\n" -}, - -{ - "location": "stdlib/io-network.html#Base.Multimedia.reprmime", - "page": "I/O and Network", - "title": "Base.Multimedia.reprmime", - "category": "function", - "text": "reprmime(mime, x)\n\nReturns an AbstractString or Vector{UInt8} containing the representation of x in the requested mime type, as written by show (throwing a MethodError if no appropriate show is available). An AbstractString is returned for MIME types with textual representations (such as \"text/html\" or \"application/postscript\"), whereas binary data is returned as Vector{UInt8}. (The function istextmime(mime) returns whether or not Julia treats a given mime type as text.)\n\nAs a special case, if x is an AbstractString (for textual MIME types) or a Vector{UInt8} (for binary MIME types), the reprmime function assumes that x is already in the requested mime format and simply returns x. This special case does not apply to the \"text/plain\" MIME type. This is useful so that raw data can be passed to display(m::MIME, x).\n\n\n\n" -}, - -{ - "location": "stdlib/io-network.html#Base.Multimedia.stringmime", - "page": "I/O and Network", - "title": "Base.Multimedia.stringmime", - "category": "function", - "text": "stringmime(mime, x)\n\nReturns an AbstractString containing the representation of x in the requested mime type. This is similar to reprmime except that binary data is base64-encoded as an ASCII string.\n\n\n\n" -}, - -{ - "location": "stdlib/io-network.html#Base.Multimedia.pushdisplay", - "page": "I/O and Network", - "title": "Base.Multimedia.pushdisplay", - "category": "function", - "text": "pushdisplay(d::Display)\n\nPushes a new display d on top of the global display-backend stack. Calling display(x) or display(mime, x) will display x on the topmost compatible backend in the stack (i.e., the topmost backend that does not throw a MethodError).\n\n\n\n" -}, - -{ - "location": "stdlib/io-network.html#Base.Multimedia.popdisplay", - "page": "I/O and Network", - "title": "Base.Multimedia.popdisplay", - "category": "function", - "text": "popdisplay()\npopdisplay(d::Display)\n\nPop the topmost backend off of the display-backend stack, or the topmost copy of d in the second variant.\n\n\n\n" -}, - -{ - "location": "stdlib/io-network.html#Base.Multimedia.TextDisplay", - "page": "I/O and Network", - "title": "Base.Multimedia.TextDisplay", - "category": "type", - "text": "TextDisplay(io::IO)\n\nReturns a TextDisplay <: Display, which displays any object as the text/plain MIME type (by default), writing the text representation to the given I/O stream. (This is how objects are printed in the Julia REPL.)\n\n\n\n" -}, - -{ - "location": "stdlib/io-network.html#Base.Multimedia.istextmime", - "page": "I/O and Network", - "title": "Base.Multimedia.istextmime", - "category": "function", - "text": "istextmime(m::MIME)\n\nDetermine whether a MIME type is text data. MIME types are assumed to be binary data except for a set of types known to be text data (possibly Unicode).\n\n\n\n" -}, - -{ - "location": "stdlib/io-network.html#Multimedia-I/O-1", - "page": "I/O and Network", - "title": "Multimedia I/O", - "category": "section", - "text": "Just as text output is performed by print and user-defined types can indicate their textual representation by overloading show, Julia provides a standardized mechanism for rich multimedia output (such as images, formatted text, or even audio and video), consisting of three parts:A function display(x) to request the richest available multimedia display of a Julia object x (with a plain-text fallback).\nOverloading show allows one to indicate arbitrary multimedia representations (keyed by standard MIME types) of user-defined types.\nMultimedia-capable display backends may be registered by subclassing a generic Display type and pushing them onto a stack of display backends via pushdisplay.The base Julia runtime provides only plain-text display, but richer displays may be enabled by loading external modules or by using graphical Julia environments (such as the IPython-based IJulia notebook).Base.Multimedia.display\nBase.Multimedia.redisplay\nBase.Multimedia.displayable\nBase.show(::Any, ::Any, ::Any)\nBase.Multimedia.mimewritable\nBase.Multimedia.reprmime\nBase.Multimedia.stringmimeAs mentioned above, one can also define new display backends. For example, a module that can display PNG images in a window can register this capability with Julia, so that calling display(x) on types with PNG representations will automatically display the image using the module\'s window.In order to define a new display backend, one should first create a subtype D of the abstract class Display. Then, for each MIME type (mime string) that can be displayed on D, one should define a function display(d::D, ::MIME\"mime\", x) = ... that displays x as that MIME type, usually by calling reprmime(mime, x). A MethodError should be thrown if x cannot be displayed as that MIME type; this is automatic if one calls reprmime. Finally, one should define a function display(d::D, x) that queries mimewritable(mime, x) for the mime types supported by D and displays the \"best\" one; a MethodError should be thrown if no supported MIME types are found for x. Similarly, some subtypes may wish to override redisplay(d::D, ...). (Again, one should import Base.display to add new methods to display.) The return values of these functions are up to the implementation (since in some cases it may be useful to return a display \"handle\" of some type). The display functions for D can then be called directly, but they can also be invoked automatically from display(x) simply by pushing a new display onto the display-backend stack with:Base.Multimedia.pushdisplay\nBase.Multimedia.popdisplay\nBase.Multimedia.TextDisplay\nBase.Multimedia.istextmime" -}, - -{ - "location": "stdlib/io-network.html#Base.Mmap.Anonymous", - "page": "I/O and Network", - "title": "Base.Mmap.Anonymous", - "category": "type", - "text": "Mmap.Anonymous(name, readonly, create)\n\nCreate an IO-like object for creating zeroed-out mmapped-memory that is not tied to a file for use in Mmap.mmap. Used by SharedArray for creating shared memory arrays.\n\n\n\n" -}, - -{ - "location": "stdlib/io-network.html#Base.Mmap.mmap-Tuple{Any,Type,Any,Any}", - "page": "I/O and Network", - "title": "Base.Mmap.mmap", - "category": "method", - "text": "Mmap.mmap(io::Union{IOStream,AbstractString,Mmap.AnonymousMmap}[, type::Type{Array{T,N}}, dims, offset]; grow::Bool=true, shared::Bool=true)\n Mmap.mmap(type::Type{Array{T,N}}, dims)\n\nCreate an Array whose values are linked to a file, using memory-mapping. This provides a convenient way of working with data too large to fit in the computer\'s memory.\n\nThe type is an Array{T,N} with a bits-type element of T and dimension N that determines how the bytes of the array are interpreted. Note that the file must be stored in binary format, and no format conversions are possible (this is a limitation of operating systems, not Julia).\n\ndims is a tuple or single Integer specifying the size or length of the array.\n\nThe file is passed via the stream argument, either as an open IOStream or filename string. When you initialize the stream, use \"r\" for a \"read-only\" array, and \"w+\" to create a new array used to write values to disk.\n\nIf no type argument is specified, the default is Vector{UInt8}.\n\nOptionally, you can specify an offset (in bytes) if, for example, you want to skip over a header in the file. The default value for the offset is the current stream position for an IOStream.\n\nThe grow keyword argument specifies whether the disk file should be grown to accommodate the requested size of array (if the total file size is < requested array size). Write privileges are required to grow the file.\n\nThe shared keyword argument specifies whether the resulting Array and changes made to it will be visible to other processes mapping the same file.\n\nFor example, the following code\n\n# Create a file for mmapping\n# (you could alternatively use mmap to do this step, too)\nA = rand(1:20, 5, 30)\ns = open(\"/tmp/mmap.bin\", \"w+\")\n# We\'ll write the dimensions of the array as the first two Ints in the file\nwrite(s, size(A,1))\nwrite(s, size(A,2))\n# Now write the data\nwrite(s, A)\nclose(s)\n\n# Test by reading it back in\ns = open(\"/tmp/mmap.bin\") # default is read-only\nm = read(s, Int)\nn = read(s, Int)\nA2 = Mmap.mmap(s, Matrix{Int}, (m,n))\n\ncreates a m-by-n Matrix{Int}, linked to the file associated with stream s.\n\nA more portable file would need to encode the word size – 32 bit or 64 bit – and endianness information in the header. In practice, consider encoding binary data using standard formats like HDF5 (which can be used with memory-mapping).\n\n\n\n" -}, - -{ - "location": "stdlib/io-network.html#Base.Mmap.mmap-Tuple{Any,BitArray,Any,Any}", - "page": "I/O and Network", - "title": "Base.Mmap.mmap", - "category": "method", - "text": "Mmap.mmap(io, BitArray, [dims, offset])\n\nCreate a BitArray whose values are linked to a file, using memory-mapping; it has the same purpose, works in the same way, and has the same arguments, as mmap, but the byte representation is different.\n\nExample: B = Mmap.mmap(s, BitArray, (25,30000))\n\nThis would create a 25-by-30000 BitArray, linked to the file associated with stream s.\n\n\n\n" -}, - -{ - "location": "stdlib/io-network.html#Base.Mmap.sync!", - "page": "I/O and Network", - "title": "Base.Mmap.sync!", - "category": "function", - "text": "Mmap.sync!(array)\n\nForces synchronization between the in-memory version of a memory-mapped Array or BitArray and the on-disk version.\n\n\n\n" -}, - -{ - "location": "stdlib/io-network.html#Memory-mapped-I/O-1", - "page": "I/O and Network", - "title": "Memory-mapped I/O", - "category": "section", - "text": "Base.Mmap.Anonymous\nBase.Mmap.mmap(::Any, ::Type, ::Any, ::Any)\nBase.Mmap.mmap(::Any, ::BitArray, ::Any, ::Any)\nBase.Mmap.sync!" -}, - -{ - "location": "stdlib/io-network.html#Base.connect-Tuple{TCPSocket,Integer}", - "page": "I/O and Network", - "title": "Base.connect", - "category": "method", - "text": "connect([host], port::Integer) -> TCPSocket\n\nConnect to the host host on port port.\n\n\n\n" -}, - -{ - "location": "stdlib/io-network.html#Base.connect-Tuple{AbstractString}", - "page": "I/O and Network", - "title": "Base.connect", - "category": "method", - "text": "connect(path::AbstractString) -> PipeEndpoint\n\nConnect to the named pipe / UNIX domain socket at path.\n\n\n\n" -}, - -{ - "location": "stdlib/io-network.html#Base.listen-Tuple{Any}", - "page": "I/O and Network", - "title": "Base.listen", - "category": "method", - "text": "listen([addr, ]port::Integer; backlog::Integer=BACKLOG_DEFAULT) -> TCPServer\n\nListen on port on the address specified by addr. By default this listens on localhost only. To listen on all interfaces pass IPv4(0) or IPv6(0) as appropriate. backlog determines how many connections can be pending (not having called accept) before the server will begin to reject them. The default value of backlog is 511.\n\n\n\n" -}, - -{ - "location": "stdlib/io-network.html#Base.listen-Tuple{AbstractString}", - "page": "I/O and Network", - "title": "Base.listen", - "category": "method", - "text": "listen(path::AbstractString) -> PipeServer\n\nCreate and listen on a named pipe / UNIX domain socket.\n\n\n\n" -}, - -{ - "location": "stdlib/io-network.html#Base.getaddrinfo", - "page": "I/O and Network", - "title": "Base.getaddrinfo", - "category": "function", - "text": "getaddrinfo(host::AbstractString) -> IPAddr\n\nGets the IP address of the host (may have to do a DNS lookup)\n\n\n\n" -}, - -{ - "location": "stdlib/io-network.html#Base.getsockname", - "page": "I/O and Network", - "title": "Base.getsockname", - "category": "function", - "text": "getsockname(sock::Union{TCPServer, TCPSocket}) -> (IPAddr, UInt16)\n\nGet the IP address and the port that the given TCPSocket is connected to (or bound to, in the case of TCPServer).\n\n\n\n" -}, - -{ - "location": "stdlib/io-network.html#Base.IPv4", - "page": "I/O and Network", - "title": "Base.IPv4", - "category": "type", - "text": "IPv4(host::Integer) -> IPv4\n\nReturns an IPv4 object from ip address host formatted as an Integer.\n\njulia> IPv4(3223256218)\nip\"192.30.252.154\"\n\n\n\n" -}, - -{ - "location": "stdlib/io-network.html#Base.IPv6", - "page": "I/O and Network", - "title": "Base.IPv6", - "category": "type", - "text": "IPv6(host::Integer) -> IPv6\n\nReturns an IPv6 object from ip address host formatted as an Integer.\n\njulia> IPv6(3223256218)\nip\"::c01e:fc9a\"\n\n\n\n" -}, - -{ - "location": "stdlib/io-network.html#Base.nb_available", - "page": "I/O and Network", - "title": "Base.nb_available", - "category": "function", - "text": "nb_available(stream)\n\nReturns the number of bytes available for reading before a read from this stream or buffer will block.\n\n\n\n" -}, - -{ - "location": "stdlib/io-network.html#Base.accept", - "page": "I/O and Network", - "title": "Base.accept", - "category": "function", - "text": "accept(server[,client])\n\nAccepts a connection on the given server and returns a connection to the client. An uninitialized client stream may be provided, in which case it will be used instead of creating a new stream.\n\n\n\n" -}, - -{ - "location": "stdlib/io-network.html#Base.listenany", - "page": "I/O and Network", - "title": "Base.listenany", - "category": "function", - "text": "listenany([host::IPAddr,] port_hint) -> (UInt16, TCPServer)\n\nCreate a TCPServer on any port, using hint as a starting point. Returns a tuple of the actual port that the server was created on and the server itself.\n\n\n\n" -}, - -{ - "location": "stdlib/io-network.html#Base.Filesystem.poll_fd", - "page": "I/O and Network", - "title": "Base.Filesystem.poll_fd", - "category": "function", - "text": "poll_fd(fd, timeout_s::Real=-1; readable=false, writable=false)\n\nMonitor a file descriptor fd for changes in the read or write availability, and with a timeout given by timeout_s seconds.\n\nThe keyword arguments determine which of read and/or write status should be monitored; at least one of them must be set to true.\n\nThe returned value is an object with boolean fields readable, writable, and timedout, giving the result of the polling.\n\n\n\n" -}, - -{ - "location": "stdlib/io-network.html#Base.Filesystem.poll_file", - "page": "I/O and Network", - "title": "Base.Filesystem.poll_file", - "category": "function", - "text": "poll_file(path::AbstractString, interval_s::Real=5.007, timeout_s::Real=-1) -> (previous::StatStruct, current::StatStruct)\n\nMonitor a file for changes by polling every interval_s seconds until a change occurs or timeout_s seconds have elapsed. The interval_s should be a long period; the default is 5.007 seconds.\n\nReturns a pair of StatStruct objects (previous, current) when a change is detected.\n\nTo determine when a file was modified, compare mtime(prev) != mtime(current) to detect notification of changes. However, using watch_file for this operation is preferred, since it is more reliable and efficient, although in some situations it may not be available.\n\n\n\n" -}, - -{ - "location": "stdlib/io-network.html#Base.Filesystem.watch_file", - "page": "I/O and Network", - "title": "Base.Filesystem.watch_file", - "category": "function", - "text": "watch_file(path::AbstractString, timeout_s::Real=-1)\n\nWatch file or directory path for changes until a change occurs or timeout_s seconds have elapsed.\n\nThe returned value is an object with boolean fields changed, renamed, and timedout, giving the result of watching the file.\n\nThis behavior of this function varies slightly across platforms. See https://nodejs.org/api/fs.html#fs_caveats for more detailed information.\n\n\n\n" -}, - -{ - "location": "stdlib/io-network.html#Base.bind", - "page": "I/O and Network", - "title": "Base.bind", - "category": "function", - "text": "bind(socket::Union{UDPSocket, TCPSocket}, host::IPAddr, port::Integer; ipv6only=false, reuseaddr=false, kws...)\n\nBind socket to the given host:port. Note that 0.0.0.0 will listen on all devices.\n\nThe ipv6only parameter disables dual stack mode. If ipv6only=true, only an IPv6 stack is created.\nIf reuseaddr=true, multiple threads or processes can bind to the same address without error if they all set reuseaddr=true, but only the last to bind will receive any traffic.\n\n\n\nbind(chnl::Channel, task::Task)\n\nAssociates the lifetime of chnl with a task. Channel chnl is automatically closed when the task terminates. Any uncaught exception in the task is propagated to all waiters on chnl.\n\nThe chnl object can be explicitly closed independent of task termination. Terminating tasks have no effect on already closed Channel objects.\n\nWhen a channel is bound to multiple tasks, the first task to terminate will close the channel. When multiple channels are bound to the same task, termination of the task will close all of the bound channels.\n\njulia> c = Channel(0);\n\njulia> task = @schedule foreach(i->put!(c, i), 1:4);\n\njulia> bind(c,task);\n\njulia> for i in c\n @show i\n end;\ni = 1\ni = 2\ni = 3\ni = 4\n\njulia> isopen(c)\nfalse\n\njulia> c = Channel(0);\n\njulia> task = @schedule (put!(c,1);error(\"foo\"));\n\njulia> bind(c,task);\n\njulia> take!(c)\n1\n\njulia> put!(c,1);\nERROR: foo\nStacktrace:\n [1] check_channel_state(::Channel{Any}) at ./channels.jl:131\n [2] put!(::Channel{Any}, ::Int64) at ./channels.jl:261\n\n\n\n" -}, - -{ - "location": "stdlib/io-network.html#Base.send", - "page": "I/O and Network", - "title": "Base.send", - "category": "function", - "text": "send(socket::UDPSocket, host, port::Integer, msg)\n\nSend msg over socket to host:port.\n\n\n\n" -}, - -{ - "location": "stdlib/io-network.html#Base.recv", - "page": "I/O and Network", - "title": "Base.recv", - "category": "function", - "text": "recv(socket::UDPSocket)\n\nRead a UDP packet from the specified socket, and return the bytes received. This call blocks.\n\n\n\n" -}, - -{ - "location": "stdlib/io-network.html#Base.recvfrom", - "page": "I/O and Network", - "title": "Base.recvfrom", - "category": "function", - "text": "recvfrom(socket::UDPSocket) -> (address, data)\n\nRead a UDP packet from the specified socket, returning a tuple of (address, data), where address will be either IPv4 or IPv6 as appropriate.\n\n\n\n" -}, - -{ - "location": "stdlib/io-network.html#Base.setopt", - "page": "I/O and Network", - "title": "Base.setopt", - "category": "function", - "text": "setopt(sock::UDPSocket; multicast_loop = nothing, multicast_ttl=nothing, enable_broadcast=nothing, ttl=nothing)\n\nSet UDP socket options.\n\nmulticast_loop: loopback for multicast packets (default: true).\nmulticast_ttl: TTL for multicast packets (default: nothing).\nenable_broadcast: flag must be set to true if socket will be used for broadcast messages, or else the UDP system will return an access error (default: false).\nttl: Time-to-live of packets sent on the socket (default: nothing).\n\n\n\n" -}, - -{ - "location": "stdlib/io-network.html#Base.ntoh", - "page": "I/O and Network", - "title": "Base.ntoh", - "category": "function", - "text": "ntoh(x)\n\nConverts the endianness of a value from Network byte order (big-endian) to that used by the Host.\n\n\n\n" -}, - -{ - "location": "stdlib/io-network.html#Base.hton", - "page": "I/O and Network", - "title": "Base.hton", - "category": "function", - "text": "hton(x)\n\nConverts the endianness of a value from that used by the Host to Network byte order (big-endian).\n\n\n\n" -}, - -{ - "location": "stdlib/io-network.html#Base.ltoh", - "page": "I/O and Network", - "title": "Base.ltoh", - "category": "function", - "text": "ltoh(x)\n\nConverts the endianness of a value from Little-endian to that used by the Host.\n\n\n\n" -}, - -{ - "location": "stdlib/io-network.html#Base.htol", - "page": "I/O and Network", - "title": "Base.htol", - "category": "function", - "text": "htol(x)\n\nConverts the endianness of a value from that used by the Host to Little-endian.\n\n\n\n" -}, - -{ - "location": "stdlib/io-network.html#Base.ENDIAN_BOM", - "page": "I/O and Network", - "title": "Base.ENDIAN_BOM", - "category": "constant", - "text": "ENDIAN_BOM\n\nThe 32-bit byte-order-mark indicates the native byte order of the host machine. Little-endian machines will contain the value 0x04030201. Big-endian machines will contain the value 0x01020304.\n\n\n\n" -}, - -{ - "location": "stdlib/io-network.html#Network-I/O-1", - "page": "I/O and Network", - "title": "Network I/O", - "category": "section", - "text": "Base.connect(::TCPSocket, ::Integer)\nBase.connect(::AbstractString)\nBase.listen(::Any)\nBase.listen(::AbstractString)\nBase.getaddrinfo\nBase.getsockname\nBase.IPv4\nBase.IPv6\nBase.nb_available\nBase.accept\nBase.listenany\nBase.Filesystem.poll_fd\nBase.Filesystem.poll_file\nBase.Filesystem.watch_file\nBase.bind\nBase.send\nBase.recv\nBase.recvfrom\nBase.setopt\nBase.ntoh\nBase.hton\nBase.ltoh\nBase.htol\nBase.ENDIAN_BOM" -}, - -{ - "location": "stdlib/punctuation.html#", - "page": "Punctuation", - "title": "Punctuation", - "category": "page", - "text": "" -}, - -{ - "location": "stdlib/punctuation.html#Punctuation-1", - "page": "Punctuation", - "title": "Punctuation", - "category": "section", - "text": "Extended documentation for mathematical symbols & functions is here.symbol meaning\n@m invoke macro m; followed by space-separated expressions\n! prefix \"not\" operator\na!( ) at the end of a function name, ! indicates that a function modifies its argument(s)\n# begin single line comment\n#= begin multi-line comment (these are nestable)\n=# end multi-line comment\n$ string and expression interpolation\n% remainder operator\n^ exponent operator\n& bitwise and\n&& short-circuiting boolean and\n| bitwise or\n|| short-circuiting boolean or\n⊻ bitwise xor operator\n* multiply, or matrix multiply\n() the empty tuple\n~ bitwise not operator\n\\ backslash operator\n\' complex transpose operator Aᴴ\na[] array indexing\n[,] vertical concatenation\n[;] also vertical concatenation\n[   ] with space-separated expressions, horizontal concatenation\nT{ } parametric type instantiation\n; statement separator\n, separate function arguments or tuple components\n? 3-argument conditional operator (conditional ? if_true : if_false)\n\"\" delimit string literals\n\'\' delimit character literals\n` ` delimit external process (command) specifications\n... splice arguments into a function call or declare a varargs function or type\n. access named fields in objects/modules, also prefixes elementwise operator/function calls\na:b range a, a+1, a+2, ..., b\na:s:b range a, a+s, a+2s, ..., b\n: index an entire dimension (1:end)\n:: type annotation, depending on context\n:( ) quoted expression\n:a symbol a\n<: subtype operator\n>: supertype operator (reverse of subtype operator)\n=== egal comparison operator" -}, - -{ - "location": "stdlib/sort.html#", - "page": "Sorting and Related Functions", - "title": "Sorting and Related Functions", - "category": "page", - "text": "" -}, - -{ - "location": "stdlib/sort.html#Sorting-and-Related-Functions-1", - "page": "Sorting and Related Functions", - "title": "Sorting and Related Functions", - "category": "section", - "text": "Julia has an extensive, flexible API for sorting and interacting with already-sorted arrays of values. By default, Julia picks reasonable algorithms and sorts in standard ascending order:julia> sort([2,3,1])\n3-element Array{Int64,1}:\n 1\n 2\n 3You can easily sort in reverse order as well:julia> sort([2,3,1], rev=true)\n3-element Array{Int64,1}:\n 3\n 2\n 1To sort an array in-place, use the \"bang\" version of the sort function:julia> a = [2,3,1];\n\njulia> sort!(a);\n\njulia> a\n3-element Array{Int64,1}:\n 1\n 2\n 3Instead of directly sorting an array, you can compute a permutation of the array\'s indices that puts the array into sorted order:julia> v = randn(5)\n5-element Array{Float64,1}:\n 0.297288\n 0.382396\n -0.597634\n -0.0104452\n -0.839027\n\njulia> p = sortperm(v)\n5-element Array{Int64,1}:\n 5\n 3\n 4\n 1\n 2\n\njulia> v[p]\n5-element Array{Float64,1}:\n -0.839027\n -0.597634\n -0.0104452\n 0.297288\n 0.382396Arrays can easily be sorted according to an arbitrary transformation of their values:julia> sort(v, by=abs)\n5-element Array{Float64,1}:\n -0.0104452\n 0.297288\n 0.382396\n -0.597634\n -0.839027Or in reverse order by a transformation:julia> sort(v, by=abs, rev=true)\n5-element Array{Float64,1}:\n -0.839027\n -0.597634\n 0.382396\n 0.297288\n -0.0104452If needed, the sorting algorithm can be chosen:julia> sort(v, alg=InsertionSort)\n5-element Array{Float64,1}:\n -0.839027\n -0.597634\n -0.0104452\n 0.297288\n 0.382396All the sorting and order related functions rely on a \"less than\" relation defining a total order on the values to be manipulated. The isless function is invoked by default, but the relation can be specified via the lt keyword." -}, - -{ - "location": "stdlib/sort.html#Base.sort!", - "page": "Sorting and Related Functions", - "title": "Base.sort!", - "category": "function", - "text": "sort!(v; alg::Algorithm=defalg(v), lt=isless, by=identity, rev::Bool=false, order::Ordering=Forward)\n\nSort the vector v in place. QuickSort is used by default for numeric arrays while MergeSort is used for other arrays. You can specify an algorithm to use via the alg keyword (see Sorting Algorithms for available algorithms). The by keyword lets you provide a function that will be applied to each element before comparison; the lt keyword allows providing a custom \"less than\" function; use rev=true to reverse the sorting order. These options are independent and can be used together in all possible combinations: if both by and lt are specified, the lt function is applied to the result of the by function; rev=true reverses whatever ordering specified via the by and lt keywords.\n\nExamples\n\njulia> v = [3, 1, 2]; sort!(v); v\n3-element Array{Int64,1}:\n 1\n 2\n 3\n\njulia> v = [3, 1, 2]; sort!(v, rev = true); v\n3-element Array{Int64,1}:\n 3\n 2\n 1\n\njulia> v = [(1, \"c\"), (3, \"a\"), (2, \"b\")]; sort!(v, by = x -> x[1]); v\n3-element Array{Tuple{Int64,String},1}:\n (1, \"c\")\n (2, \"b\")\n (3, \"a\")\n\njulia> v = [(1, \"c\"), (3, \"a\"), (2, \"b\")]; sort!(v, by = x -> x[2]); v\n3-element Array{Tuple{Int64,String},1}:\n (3, \"a\")\n (2, \"b\")\n (1, \"c\")\n\n\n\n" -}, - -{ - "location": "stdlib/sort.html#Base.sort", - "page": "Sorting and Related Functions", - "title": "Base.sort", - "category": "function", - "text": "sort(v; alg::Algorithm=defalg(v), lt=isless, by=identity, rev::Bool=false, order::Ordering=Forward)\n\nVariant of sort! that returns a sorted copy of v leaving v itself unmodified.\n\nExamples\n\njulia> v = [3, 1, 2];\n\njulia> sort(v)\n3-element Array{Int64,1}:\n 1\n 2\n 3\n\njulia> v\n3-element Array{Int64,1}:\n 3\n 1\n 2\n\n\n\nsort(A, dim::Integer; alg::Algorithm=DEFAULT_UNSTABLE, lt=isless, by=identity, rev::Bool=false, order::Ordering=Forward, initialized::Bool=false)\n\nSort a multidimensional array A along the given dimension. See sort! for a description of possible keyword arguments.\n\nExamples\n\njulia> A = [4 3; 1 2]\n2×2 Array{Int64,2}:\n 4 3\n 1 2\n\njulia> sort(A, 1)\n2×2 Array{Int64,2}:\n 1 2\n 4 3\n\njulia> sort(A, 2)\n2×2 Array{Int64,2}:\n 3 4\n 1 2\n\n\n\n" -}, - -{ - "location": "stdlib/sort.html#Base.sortperm", - "page": "Sorting and Related Functions", - "title": "Base.sortperm", - "category": "function", - "text": "sortperm(v; alg::Algorithm=DEFAULT_UNSTABLE, lt=isless, by=identity, rev::Bool=false, order::Ordering=Forward)\n\nReturn a permutation vector of indices of v that puts it in sorted order. Specify alg to choose a particular sorting algorithm (see Sorting Algorithms). MergeSort is used by default, and since it is stable, the resulting permutation will be the lexicographically first one that puts the input array into sorted order – i.e. indices of equal elements appear in ascending order. If you choose a non-stable sorting algorithm such as QuickSort, a different permutation that puts the array into order may be returned. The order is specified using the same keywords as sort!.\n\nSee also sortperm!.\n\nExamples\n\njulia> v = [3, 1, 2];\n\njulia> p = sortperm(v)\n3-element Array{Int64,1}:\n 2\n 3\n 1\n\njulia> v[p]\n3-element Array{Int64,1}:\n 1\n 2\n 3\n\n\n\n" -}, - -{ - "location": "stdlib/sort.html#Base.Sort.sortperm!", - "page": "Sorting and Related Functions", - "title": "Base.Sort.sortperm!", - "category": "function", - "text": "sortperm!(ix, v; alg::Algorithm=DEFAULT_UNSTABLE, lt=isless, by=identity, rev::Bool=false, order::Ordering=Forward, initialized::Bool=false)\n\nLike sortperm, but accepts a preallocated index vector ix. If initialized is false (the default), ix is initialized to contain the values 1:length(v).\n\nExamples\n\njulia> v = [3, 1, 2]; p = zeros(Int, 3);\n\njulia> sortperm!(p, v); p\n3-element Array{Int64,1}:\n 2\n 3\n 1\n\njulia> v[p]\n3-element Array{Int64,1}:\n 1\n 2\n 3\n\n\n\n" -}, - -{ - "location": "stdlib/sort.html#Base.Sort.sortrows", - "page": "Sorting and Related Functions", - "title": "Base.Sort.sortrows", - "category": "function", - "text": "sortrows(A; alg::Algorithm=DEFAULT_UNSTABLE, lt=isless, by=identity, rev::Bool=false, order::Ordering=Forward)\n\nSort the rows of matrix A lexicographically. See sort! for a description of possible keyword arguments.\n\nExamples\n\njulia> sortrows([7 3 5; -1 6 4; 9 -2 8])\n3×3 Array{Int64,2}:\n -1 6 4\n 7 3 5\n 9 -2 8\n\njulia> sortrows([7 3 5; -1 6 4; 9 -2 8], lt=(x,y)->isless(x[2],y[2]))\n3×3 Array{Int64,2}:\n 9 -2 8\n 7 3 5\n -1 6 4\n\njulia> sortrows([7 3 5; -1 6 4; 9 -2 8], rev=true)\n3×3 Array{Int64,2}:\n 9 -2 8\n 7 3 5\n -1 6 4\n\n\n\n" -}, - -{ - "location": "stdlib/sort.html#Base.Sort.sortcols", - "page": "Sorting and Related Functions", - "title": "Base.Sort.sortcols", - "category": "function", - "text": "sortcols(A; alg::Algorithm=DEFAULT_UNSTABLE, lt=isless, by=identity, rev::Bool=false, order::Ordering=Forward)\n\nSort the columns of matrix A lexicographically. See sort! for a description of possible keyword arguments.\n\nExamples\n\njulia> sortcols([7 3 5; 6 -1 -4; 9 -2 8])\n3×3 Array{Int64,2}:\n 3 5 7\n -1 -4 6\n -2 8 9\n\njulia> sortcols([7 3 5; 6 -1 -4; 9 -2 8], alg=InsertionSort, lt=(x,y)->isless(x[2],y[2]))\n3×3 Array{Int64,2}:\n 5 3 7\n -4 -1 6\n 8 -2 9\n\njulia> sortcols([7 3 5; 6 -1 -4; 9 -2 8], rev=true)\n3×3 Array{Int64,2}:\n 7 5 3\n 6 -4 -1\n 9 8 -2\n\n\n\n" -}, - -{ - "location": "stdlib/sort.html#Sorting-Functions-1", - "page": "Sorting and Related Functions", - "title": "Sorting Functions", - "category": "section", - "text": "Base.sort!\nBase.sort\nBase.sortperm\nBase.Sort.sortperm!\nBase.Sort.sortrows\nBase.Sort.sortcols" -}, - -{ - "location": "stdlib/sort.html#Base.issorted", - "page": "Sorting and Related Functions", - "title": "Base.issorted", - "category": "function", - "text": "issorted(v, lt=isless, by=identity, rev:Bool=false, order::Ordering=Forward)\n\nTest whether a vector is in sorted order. The lt, by and rev keywords modify what order is considered to be sorted just as they do for sort.\n\nExamples\n\njulia> issorted([1, 2, 3])\ntrue\n\njulia> issorted([(1, \"b\"), (2, \"a\")], by = x -> x[1])\ntrue\n\njulia> issorted([(1, \"b\"), (2, \"a\")], by = x -> x[2])\nfalse\n\njulia> issorted([(1, \"b\"), (2, \"a\")], by = x -> x[2], rev=true)\ntrue\n\n\n\n" -}, - -{ - "location": "stdlib/sort.html#Base.Sort.searchsorted", - "page": "Sorting and Related Functions", - "title": "Base.Sort.searchsorted", - "category": "function", - "text": "searchsorted(a, x, [by=,] [lt=,] [rev=false])\n\nReturns the range of indices of a which compare as equal to x (using binary search) according to the order specified by the by, lt and rev keywords, assuming that a is already sorted in that order. Returns an empty range located at the insertion point if a does not contain values equal to x.\n\nExamples\n\njulia> a = [4, 3, 2, 1]\n4-element Array{Int64,1}:\n 4\n 3\n 2\n 1\n\njulia> searchsorted(a, 4)\n5:4\n\njulia> searchsorted(a, 4, rev=true)\n1:1\n\n\n\n" -}, - -{ - "location": "stdlib/sort.html#Base.Sort.searchsortedfirst", - "page": "Sorting and Related Functions", - "title": "Base.Sort.searchsortedfirst", - "category": "function", - "text": "searchsortedfirst(a, x, [by=,] [lt=,] [rev=false])\n\nReturns the index of the first value in a greater than or equal to x, according to the specified order. Returns length(a)+1 if x is greater than all values in a. a is assumed to be sorted.\n\nExamples\n\njulia> searchsortedfirst([1, 2, 4, 5, 14], 4)\n3\n\njulia> searchsortedfirst([1, 2, 4, 5, 14], 4, rev=true)\n1\n\njulia> searchsortedfirst([1, 2, 4, 5, 14], 15)\n6\n\n\n\n" -}, - -{ - "location": "stdlib/sort.html#Base.Sort.searchsortedlast", - "page": "Sorting and Related Functions", - "title": "Base.Sort.searchsortedlast", - "category": "function", - "text": "searchsortedlast(a, x, [by=,] [lt=,] [rev=false])\n\nReturns the index of the last value in a less than or equal to x, according to the specified order. Returns 0 if x is less than all values in a. a is assumed to be sorted.\n\nExamples\n\njulia> searchsortedlast([1, 2, 4, 5, 14], 4)\n3\n\njulia> searchsortedlast([1, 2, 4, 5, 14], 4, rev=true)\n5\n\njulia> searchsortedlast([1, 2, 4, 5, 14], -1)\n0\n\n\n\n" -}, - -{ - "location": "stdlib/sort.html#Base.Sort.select!", - "page": "Sorting and Related Functions", - "title": "Base.Sort.select!", - "category": "function", - "text": "select!(v, k, [by=,] [lt=,] [rev=false])\n\nPartially sort the vector v in place, according to the order specified by by, lt and rev so that the value at index k (or range of adjacent values if k is a range) occurs at the position where it would appear if the array were fully sorted via a non-stable algorithm. If k is a single index, that value is returned; if k is a range, an array of values at those indices is returned. Note that select! does not fully sort the input array.\n\nExamples\n\njulia> a = [1, 2, 4, 3, 4]\n5-element Array{Int64,1}:\n 1\n 2\n 4\n 3\n 4\n\njulia> select!(a, 4)\n4\n\njulia> a\n5-element Array{Int64,1}:\n 1\n 2\n 3\n 4\n 4\n\njulia> a = [1, 2, 4, 3, 4]\n5-element Array{Int64,1}:\n 1\n 2\n 4\n 3\n 4\n\njulia> select!(a, 4, rev=true)\n2\n\njulia> a\n5-element Array{Int64,1}:\n 4\n 4\n 3\n 2\n 1\n\n\n\n" -}, - -{ - "location": "stdlib/sort.html#Base.Sort.select", - "page": "Sorting and Related Functions", - "title": "Base.Sort.select", - "category": "function", - "text": "select(v, k, [by=,] [lt=,] [rev=false])\n\nVariant of select! which copies v before partially sorting it, thereby returning the same thing as select! but leaving v unmodified.\n\n\n\n" -}, - -{ - "location": "stdlib/sort.html#Base.Sort.selectperm", - "page": "Sorting and Related Functions", - "title": "Base.Sort.selectperm", - "category": "function", - "text": "selectperm(v, k, [alg=,] [by=,] [lt=,] [rev=false])\n\nReturn a partial permutation of the vector v, according to the order specified by by, lt and rev, so that v[output] returns the first k (or range of adjacent values if k is a range) values of a fully sorted version of v. If k is a single index (Integer), an array of the first k indices is returned; if k is a range, an array of those indices is returned. Note that the handling of integer values for k is different from select in that it returns a vector of k elements instead of just the k th element. Also note that this is equivalent to, but more efficient than, calling sortperm(...)[k].\n\n\n\n" -}, - -{ - "location": "stdlib/sort.html#Base.Sort.selectperm!", - "page": "Sorting and Related Functions", - "title": "Base.Sort.selectperm!", - "category": "function", - "text": "selectperm!(ix, v, k, [alg=,] [by=,] [lt=,] [rev=false,] [initialized=false])\n\nLike selectperm, but accepts a preallocated index vector ix. If initialized is false (the default), ix is initialized to contain the values 1:length(ix).\n\n\n\n" -}, - -{ - "location": "stdlib/sort.html#Order-Related-Functions-1", - "page": "Sorting and Related Functions", - "title": "Order-Related Functions", - "category": "section", - "text": "Base.issorted\nBase.Sort.searchsorted\nBase.Sort.searchsortedfirst\nBase.Sort.searchsortedlast\nBase.Sort.select!\nBase.Sort.select\nBase.Sort.selectperm\nBase.Sort.selectperm!" -}, - -{ - "location": "stdlib/sort.html#Sorting-Algorithms-1", - "page": "Sorting and Related Functions", - "title": "Sorting Algorithms", - "category": "section", - "text": "There are currently four sorting algorithms available in base Julia:InsertionSort\nQuickSort\nPartialQuickSort(k)\nMergeSortInsertionSort is an O(n^2) stable sorting algorithm. It is efficient for very small n, and is used internally by QuickSort.QuickSort is an O(n log n) sorting algorithm which is in-place, very fast, but not stable – i.e. elements which are considered equal will not remain in the same order in which they originally appeared in the array to be sorted. QuickSort is the default algorithm for numeric values, including integers and floats.PartialQuickSort(k) is similar to QuickSort, but the output array is only sorted up to index k if k is an integer, or in the range of k if k is an OrdinalRange. For example:x = rand(1:500, 100)\nk = 50\nk2 = 50:100\ns = sort(x; alg=QuickSort)\nps = sort(x; alg=PartialQuickSort(k))\nqs = sort(x; alg=PartialQuickSort(k2))\nmap(issorted, (s, ps, qs)) # => (true, false, false)\nmap(x->issorted(x[1:k]), (s, ps, qs)) # => (true, true, false)\nmap(x->issorted(x[k2]), (s, ps, qs)) # => (true, false, true)\ns[1:k] == ps[1:k] # => true\ns[k2] == qs[k2] # => trueMergeSort is an O(n log n) stable sorting algorithm but is not in-place – it requires a temporary array of half the size of the input array – and is typically not quite as fast as QuickSort. It is the default algorithm for non-numeric data.The default sorting algorithms are chosen on the basis that they are fast and stable, or appear to be so. For numeric types indeed, QuickSort is selected as it is faster and indistinguishable in this case from a stable sort (unless the array records its mutations in some way). The stability property comes at a non-negligible cost, so if you don\'t need it, you may want to explicitly specify your preferred algorithm, e.g. sort!(v, alg=QuickSort).The mechanism by which Julia picks default sorting algorithms is implemented via the Base.Sort.defalg function. It allows a particular algorithm to be registered as the default in all sorting functions for specific arrays. For example, here are the two default methods from sort.jl:defalg(v::AbstractArray) = MergeSort\ndefalg{T<:Number}(v::AbstractArray{T}) = QuickSortAs for numeric arrays, choosing a non-stable default algorithm for array types for which the notion of a stable sort is meaningless (i.e. when two values comparing equal can not be distinguished) may make sense." -}, - -{ - "location": "stdlib/pkg.html#", - "page": "Package Manager Functions", - "title": "Package Manager Functions", - "category": "page", - "text": "" -}, - -{ - "location": "stdlib/pkg.html#Base.Pkg.dir", - "page": "Package Manager Functions", - "title": "Base.Pkg.dir", - "category": "function", - "text": "dir() -> AbstractString\n\nReturns the absolute path of the package directory. This defaults to joinpath(homedir(),\".julia\",\"v$(VERSION.major).$(VERSION.minor)\") on all platforms (i.e. ~/.julia/v0.6 in UNIX shell syntax). If the JULIA_PKGDIR environment variable is set, then that path is used in the returned value as joinpath(ENV[\"JULIA_PKGDIR\"],\"v$(VERSION.major).$(VERSION.minor)\"). If JULIA_PKGDIR is a relative path, it is interpreted relative to whatever the current working directory is.\n\n\n\ndir(names...) -> AbstractString\n\nEquivalent to normpath(Pkg.dir(),names...) – i.e. it appends path components to the package directory and normalizes the resulting path. In particular, Pkg.dir(pkg) returns the path to the package pkg.\n\n\n\n" -}, - -{ - "location": "stdlib/pkg.html#Base.Pkg.init", - "page": "Package Manager Functions", - "title": "Base.Pkg.init", - "category": "function", - "text": "init(meta::AbstractString=DEFAULT_META, branch::AbstractString=META_BRANCH)\n\nInitialize Pkg.dir() as a package directory. This will be done automatically when the JULIA_PKGDIR is not set and Pkg.dir() uses its default value. As part of this process, clones a local METADATA git repository from the site and branch specified by its arguments, which are typically not provided. Explicit (non-default) arguments can be used to support a custom METADATA setup.\n\n\n\n" -}, - -{ - "location": "stdlib/pkg.html#Base.Pkg.resolve", - "page": "Package Manager Functions", - "title": "Base.Pkg.resolve", - "category": "function", - "text": "resolve()\n\nDetermines an optimal, consistent set of package versions to install or upgrade to. The optimal set of package versions is based on the contents of Pkg.dir(\"REQUIRE\") and the state of installed packages in Pkg.dir(), Packages that are no longer required are moved into Pkg.dir(\".trash\").\n\n\n\n" -}, - -{ - "location": "stdlib/pkg.html#Base.Pkg.edit", - "page": "Package Manager Functions", - "title": "Base.Pkg.edit", - "category": "function", - "text": "edit()\n\nOpens Pkg.dir(\"REQUIRE\") in the editor specified by the VISUAL or EDITOR environment variables; when the editor command returns, it runs Pkg.resolve() to determine and install a new optimal set of installed package versions.\n\n\n\n" -}, - -{ - "location": "stdlib/pkg.html#Base.Pkg.add", - "page": "Package Manager Functions", - "title": "Base.Pkg.add", - "category": "function", - "text": "add(pkg, vers...)\n\nAdd a requirement entry for pkg to Pkg.dir(\"REQUIRE\") and call Pkg.resolve(). If vers are given, they must be VersionNumber objects and they specify acceptable version intervals for pkg.\n\n\n\n" -}, - -{ - "location": "stdlib/pkg.html#Base.Pkg.rm", - "page": "Package Manager Functions", - "title": "Base.Pkg.rm", - "category": "function", - "text": "rm(pkg)\n\nRemove all requirement entries for pkg from Pkg.dir(\"REQUIRE\") and call Pkg.resolve().\n\n\n\n" -}, - -{ - "location": "stdlib/pkg.html#Base.Pkg.clone", - "page": "Package Manager Functions", - "title": "Base.Pkg.clone", - "category": "function", - "text": "clone(pkg)\n\nIf pkg has a URL registered in Pkg.dir(\"METADATA\"), clone it from that URL on the default branch. The package does not need to have any registered versions.\n\n\n\nclone(url, [pkg])\n\nClone a package directly from the git URL url. The package does not need to be registered in Pkg.dir(\"METADATA\"). The package repo is cloned by the name pkg if provided; if not provided, pkg is determined automatically from url.\n\n\n\n" -}, - -{ - "location": "stdlib/pkg.html#Base.Pkg.setprotocol!", - "page": "Package Manager Functions", - "title": "Base.Pkg.setprotocol!", - "category": "function", - "text": "setprotocol!(proto)\n\nSet the protocol used to access GitHub-hosted packages. Defaults to \'https\', with a blank proto delegating the choice to the package developer.\n\n\n\n" -}, - -{ - "location": "stdlib/pkg.html#Base.Pkg.available", - "page": "Package Manager Functions", - "title": "Base.Pkg.available", - "category": "function", - "text": "available() -> Vector{String}\n\nReturns the names of available packages.\n\n\n\navailable(pkg) -> Vector{VersionNumber}\n\nReturns the version numbers available for package pkg.\n\n\n\n" -}, - -{ - "location": "stdlib/pkg.html#Base.Pkg.installed", - "page": "Package Manager Functions", - "title": "Base.Pkg.installed", - "category": "function", - "text": "installed() -> Dict{String,VersionNumber}\n\nReturns a dictionary mapping installed package names to the installed version number of each package.\n\n\n\ninstalled(pkg) -> Void | VersionNumber\n\nIf pkg is installed, return the installed version number. If pkg is registered, but not installed, return nothing.\n\n\n\n" -}, - -{ - "location": "stdlib/pkg.html#Base.Pkg.status", - "page": "Package Manager Functions", - "title": "Base.Pkg.status", - "category": "function", - "text": "status()\n\nPrints out a summary of what packages are installed and what version and state they\'re in.\n\n\n\nstatus(pkg)\n\nPrints out a summary of what version and state pkg, specifically, is in.\n\n\n\n" -}, - -{ - "location": "stdlib/pkg.html#Base.Pkg.update", - "page": "Package Manager Functions", - "title": "Base.Pkg.update", - "category": "function", - "text": "update(pkgs...)\n\nUpdate the metadata repo – kept in Pkg.dir(\"METADATA\") – then update any fixed packages that can safely be pulled from their origin; then call Pkg.resolve() to determine a new optimal set of packages versions.\n\nWithout arguments, updates all installed packages. When one or more package names are provided as arguments, only those packages and their dependencies are updated.\n\n\n\n" -}, - -{ - "location": "stdlib/pkg.html#Base.Pkg.checkout", - "page": "Package Manager Functions", - "title": "Base.Pkg.checkout", - "category": "function", - "text": "checkout(pkg, [branch=\"master\"]; merge=true, pull=true)\n\nCheckout the Pkg.dir(pkg) repo to the branch branch. Defaults to checking out the \"master\" branch. To go back to using the newest compatible released version, use Pkg.free(pkg). Changes are merged (fast-forward only) if the keyword argument merge == true, and the latest version is pulled from the upstream repo if pull == true.\n\n\n\n" -}, - -{ - "location": "stdlib/pkg.html#Base.Pkg.pin", - "page": "Package Manager Functions", - "title": "Base.Pkg.pin", - "category": "function", - "text": "pin(pkg)\n\nPin pkg at the current version. To go back to using the newest compatible released version, use Pkg.free(pkg)\n\n\n\npin(pkg, version)\n\nPin pkg at registered version version.\n\n\n\n" -}, - -{ - "location": "stdlib/pkg.html#Base.Pkg.free", - "page": "Package Manager Functions", - "title": "Base.Pkg.free", - "category": "function", - "text": "free(pkg)\n\nFree the package pkg to be managed by the package manager again. It calls Pkg.resolve() to determine optimal package versions after. This is an inverse for both Pkg.checkout and Pkg.pin.\n\nYou can also supply an iterable collection of package names, e.g., Pkg.free((\"Pkg1\", \"Pkg2\")) to free multiple packages at once.\n\n\n\n" -}, - -{ - "location": "stdlib/pkg.html#Base.Pkg.build", - "page": "Package Manager Functions", - "title": "Base.Pkg.build", - "category": "function", - "text": "build()\n\nRun the build scripts for all installed packages in depth-first recursive order.\n\n\n\nbuild(pkgs...)\n\nRun the build script in deps/build.jl for each package in pkgs and all of their dependencies in depth-first recursive order. This is called automatically by Pkg.resolve() on all installed or updated packages.\n\n\n\n" -}, - -{ - "location": "stdlib/pkg.html#Base.Pkg.test", - "page": "Package Manager Functions", - "title": "Base.Pkg.test", - "category": "function", - "text": "test(; coverage=false)\n\nRun the tests for all installed packages ensuring that each package\'s test dependencies are installed for the duration of the test. A package is tested by running its test/runtests.jl file and test dependencies are specified in test/REQUIRE. Coverage statistics for the packages may be generated by passing coverage=true. The default behavior is not to run coverage.\n\n\n\ntest(pkgs...; coverage=false)\n\nRun the tests for each package in pkgs ensuring that each package\'s test dependencies are installed for the duration of the test. A package is tested by running its test/runtests.jl file and test dependencies are specified in test/REQUIRE. Coverage statistics for the packages may be generated by passing coverage=true. The default behavior is not to run coverage.\n\n\n\n" -}, - -{ - "location": "stdlib/pkg.html#Base.Pkg.dependents", - "page": "Package Manager Functions", - "title": "Base.Pkg.dependents", - "category": "function", - "text": "dependents(pkg)\n\nList the packages that have pkg as a dependency.\n\n\n\n" -}, - -{ - "location": "stdlib/pkg.html#Package-Manager-Functions-1", - "page": "Package Manager Functions", - "title": "Package Manager Functions", - "category": "section", - "text": "All package manager functions are defined in the Pkg module. None of the Pkg module\'s functions are exported; to use them, you\'ll need to prefix each function call with an explicit Pkg., e.g. Pkg.status() or Pkg.dir().Functions for package development (e.g. tag, publish, etc.) have been moved to the PkgDev package. See PkgDev README for the documentation of those functions.Base.Pkg.dir\nBase.Pkg.init\nBase.Pkg.resolve\nBase.Pkg.edit\nBase.Pkg.add\nBase.Pkg.rm\nBase.Pkg.clone\nBase.Pkg.setprotocol!\nBase.Pkg.available\nBase.Pkg.installed\nBase.Pkg.status\nBase.Pkg.update\nBase.Pkg.checkout\nBase.Pkg.pin\nBase.Pkg.free\nBase.Pkg.build\nBase.Pkg.test\nBase.Pkg.dependents" -}, - -{ - "location": "stdlib/dates.html#", - "page": "Dates and Time", - "title": "Dates and Time", - "category": "page", - "text": "" -}, - -{ - "location": "stdlib/dates.html#stdlib-dates-1", - "page": "Dates and Time", - "title": "Dates and Time", - "category": "section", - "text": "" -}, - -{ - "location": "stdlib/dates.html#Base.Dates.Period", - "page": "Dates and Time", - "title": "Base.Dates.Period", - "category": "type", - "text": "Period\nYear\nMonth\nWeek\nDay\nHour\nMinute\nSecond\nMillisecond\nMicrosecond\nNanosecond\n\nPeriod types represent discrete, human representations of time.\n\n\n\n" -}, - -{ - "location": "stdlib/dates.html#Base.Dates.CompoundPeriod", - "page": "Dates and Time", - "title": "Base.Dates.CompoundPeriod", - "category": "type", - "text": "CompoundPeriod\n\nA CompoundPeriod is useful for expressing time periods that are not a fixed multiple of smaller periods. For example, \"a year and a day\" is not a fixed number of days, but can be expressed using a CompoundPeriod. In fact, a CompoundPeriod is automatically generated by addition of different period types, e.g. Year(1) + Day(1) produces a CompoundPeriod result.\n\n\n\n" -}, - -{ - "location": "stdlib/dates.html#Base.Dates.Instant", - "page": "Dates and Time", - "title": "Base.Dates.Instant", - "category": "type", - "text": "Instant\n\nInstant types represent integer-based, machine representations of time as continuous timelines starting from an epoch.\n\n\n\n" -}, - -{ - "location": "stdlib/dates.html#Base.Dates.UTInstant", - "page": "Dates and Time", - "title": "Base.Dates.UTInstant", - "category": "type", - "text": "UTInstant{T}\n\nThe UTInstant represents a machine timeline based on UT time (1 day = one revolution of the earth). The T is a Period parameter that indicates the resolution or precision of the instant.\n\n\n\n" -}, - -{ - "location": "stdlib/dates.html#Base.Dates.TimeType", - "page": "Dates and Time", - "title": "Base.Dates.TimeType", - "category": "type", - "text": "TimeType\n\nTimeType types wrap Instant machine instances to provide human representations of the machine instant. Time, DateTime and Date are subtypes of TimeType.\n\n\n\n" -}, - -{ - "location": "stdlib/dates.html#Base.Dates.DateTime", - "page": "Dates and Time", - "title": "Base.Dates.DateTime", - "category": "type", - "text": "DateTime\n\nDateTime wraps a UTInstant{Millisecond} and interprets it according to the proleptic Gregorian calendar.\n\n\n\n" -}, - -{ - "location": "stdlib/dates.html#Base.Dates.Date", - "page": "Dates and Time", - "title": "Base.Dates.Date", - "category": "type", - "text": "Date\n\nDate wraps a UTInstant{Day} and interprets it according to the proleptic Gregorian calendar.\n\n\n\n" -}, - -{ - "location": "stdlib/dates.html#Base.Dates.Time", - "page": "Dates and Time", - "title": "Base.Dates.Time", - "category": "type", - "text": "Time\n\nTime wraps a Nanosecond and represents a specific moment in a 24-hour day.\n\n\n\n" -}, - -{ - "location": "stdlib/dates.html#Dates-and-Time-Types-1", - "page": "Dates and Time", - "title": "Dates and Time Types", - "category": "section", - "text": "Base.Dates.Period\nBase.Dates.CompoundPeriod\nBase.Dates.Instant\nBase.Dates.UTInstant\nBase.Dates.TimeType\nBase.Dates.DateTime\nBase.Dates.Date\nBase.Dates.Time" -}, - -{ - "location": "stdlib/dates.html#Base.Dates.DateTime-NTuple{7,Int64}", - "page": "Dates and Time", - "title": "Base.Dates.DateTime", - "category": "method", - "text": "DateTime(y, [m, d, h, mi, s, ms]) -> DateTime\n\nConstruct a DateTime type by parts. Arguments must be convertible to Int64.\n\n\n\n" -}, - -{ - "location": "stdlib/dates.html#Base.Dates.DateTime-Tuple{Vararg{Base.Dates.Period,N} where N}", - "page": "Dates and Time", - "title": "Base.Dates.DateTime", - "category": "method", - "text": "DateTime(periods::Period...) -> DateTime\n\nConstruct a DateTime type by Period type parts. Arguments may be in any order. DateTime parts not provided will default to the value of Dates.default(period).\n\n\n\n" -}, - -{ - "location": "stdlib/dates.html#Base.Dates.DateTime-Tuple{Function,Vararg{Any,N} where N}", - "page": "Dates and Time", - "title": "Base.Dates.DateTime", - "category": "method", - "text": "DateTime(f::Function, y[, m, d, h, mi, s]; step=Day(1), limit=10000) -> DateTime\n\nCreate a DateTime through the adjuster API. The starting point will be constructed from the provided y, m, d... arguments, and will be adjusted until f::Function returns true. The step size in adjusting can be provided manually through the step keyword. limit provides a limit to the max number of iterations the adjustment API will pursue before throwing an error (in the case that f::Function is never satisfied).\n\n\n\n" -}, - -{ - "location": "stdlib/dates.html#Base.Dates.DateTime-Tuple{Base.Dates.TimeType}", - "page": "Dates and Time", - "title": "Base.Dates.DateTime", - "category": "method", - "text": "DateTime(dt::Date) -> DateTime\n\nConverts a Date to a DateTime. The hour, minute, second, and millisecond parts of the new DateTime are assumed to be zero.\n\n\n\n" -}, - -{ - "location": "stdlib/dates.html#Base.Dates.DateTime-Tuple{AbstractString,AbstractString}", - "page": "Dates and Time", - "title": "Base.Dates.DateTime", - "category": "method", - "text": "DateTime(dt::AbstractString, format::AbstractString; locale=\"english\") -> DateTime\n\nConstruct a DateTime by parsing the dt date string following the pattern given in the format string.\n\nThis method creates a DateFormat object each time it is called. If you are parsing many date strings of the same format, consider creating a DateFormat object once and using that as the second argument instead.\n\n\n\n" -}, - -{ - "location": "stdlib/dates.html#Base.Dates.format-Tuple{Base.Dates.TimeType,AbstractString}", - "page": "Dates and Time", - "title": "Base.Dates.format", - "category": "method", - "text": "format(dt::TimeType, format::AbstractString; locale=\"english\") -> AbstractString\n\nConstruct a string by using a TimeType object and applying the provided format. The following character codes can be used to construct the format string:\n\nCode Examples Comment\ny 6 Numeric year with a fixed width\nY 1996 Numeric year with a minimum width\nm 1, 12 Numeric month with a minimum width\nu Jan Month name shortened to 3-chars according to the locale\nU January Full month name according to the locale keyword\nd 1, 31 Day of the month with a minimum width\nH 0, 23 Hour (24-hour clock) with a minimum width\nM 0, 59 Minute with a minimum width\nS 0, 59 Second with a minimum width\ns 000, 500 Millisecond with a minimum width of 3\ne Mon, Tue Abbreviated days of the week\nE Monday Full day of week name\n\nThe number of sequential code characters indicate the width of the code. A format of yyyy-mm specifies that the code y should have a width of four while m a width of two. Codes that yield numeric digits have an associated mode: fixed-width or minimum-width. The fixed-width mode left-pads the value with zeros when it is shorter than the specified width and truncates the value when longer. Minimum-width mode works the same as fixed-width except that it does not truncate values longer than the width.\n\nWhen creating a format you can use any non-code characters as a separator. For example to generate the string \"1996-01-15T00:00:00\" you could use format: \"yyyy-mm-ddTHH:MM:SS\". Note that if you need to use a code character as a literal you can use the escape character backslash. The string \"1996y01m\" can be produced with the format \"yyyy\\ymm\\m\".\n\n\n\n" -}, - -{ - "location": "stdlib/dates.html#Base.Dates.DateFormat", - "page": "Dates and Time", - "title": "Base.Dates.DateFormat", - "category": "type", - "text": "DateFormat(format::AbstractString, locale=\"english\") -> DateFormat\n\nConstruct a date formatting object that can be used for parsing date strings or formatting a date object as a string. The following character codes can be used to construct the format string:\n\nCode Matches Comment\ny 1996, 96 Returns year of 1996, 0096\nY 1996, 96 Returns year of 1996, 0096. Equivalent to y\nm 1, 01 Matches 1 or 2-digit months\nu Jan Matches abbreviated months according to the locale keyword\nU January Matches full month names according to the locale keyword\nd 1, 01 Matches 1 or 2-digit days\nH 00 Matches hours\nM 00 Matches minutes\nS 00 Matches seconds\ns .500 Matches milliseconds\ne Mon, Tues Matches abbreviated days of the week\nE Monday Matches full name days of the week\nyyyymmdd 19960101 Matches fixed-width year, month, and day\n\nCharacters not listed above are normally treated as delimiters between date and time slots. For example a dt string of \"1996-01-15T00:00:00.0\" would have a format string like \"y-m-dTH:M:S.s\". If you need to use a code character as a delimiter you can escape it using backslash. The date \"1995y01m\" would have the format \"y\\ym\\m\".\n\nCreating a DateFormat object is expensive. Whenever possible, create it once and use it many times or try the dateformat\"\" string macro. Using this macro creates the DateFormat object once at macro expansion time and reuses it later. see @dateformat_str.\n\nSee DateTime and format for how to use a DateFormat object to parse and write Date strings respectively.\n\n\n\n" -}, - -{ - "location": "stdlib/dates.html#Base.Dates.@dateformat_str", - "page": "Dates and Time", - "title": "Base.Dates.@dateformat_str", - "category": "macro", - "text": "dateformat\"Y-m-d H:M:S\"\n\nCreate a DateFormat object. Similar to DateFormat(\"Y-m-d H:M:S\") but creates the DateFormat object once during macro expansion.\n\nSee DateFormat for details about format specifiers.\n\n\n\n" -}, - -{ - "location": "stdlib/dates.html#Base.Dates.DateTime-Tuple{AbstractString,DateFormat}", - "page": "Dates and Time", - "title": "Base.Dates.DateTime", - "category": "method", - "text": "DateTime(dt::AbstractString, df::DateFormat) -> DateTime\n\nConstruct a DateTime by parsing the dt date string following the pattern given in the DateFormat object. Similar to DateTime(::AbstractString, ::AbstractString) but more efficient when repeatedly parsing similarly formatted date strings with a pre-created DateFormat object.\n\n\n\n" -}, - -{ - "location": "stdlib/dates.html#Base.Dates.Date-Tuple{Int64,Int64,Int64}", - "page": "Dates and Time", - "title": "Base.Dates.Date", - "category": "method", - "text": "Date(y, [m, d]) -> Date\n\nConstruct a Date type by parts. Arguments must be convertible to Int64.\n\n\n\n" -}, - -{ - "location": "stdlib/dates.html#Base.Dates.Date-Tuple{Vararg{Base.Dates.Period,N} where N}", - "page": "Dates and Time", - "title": "Base.Dates.Date", - "category": "method", - "text": "Date(period::Period...) -> Date\n\nConstruct a Date type by Period type parts. Arguments may be in any order. Date parts not provided will default to the value of Dates.default(period).\n\n\n\n" -}, - -{ - "location": "stdlib/dates.html#Base.Dates.Date-Tuple{Function,Any,Any,Any}", - "page": "Dates and Time", - "title": "Base.Dates.Date", - "category": "method", - "text": "Date(f::Function, y[, m, d]; step=Day(1), limit=10000) -> Date\n\nCreate a Date through the adjuster API. The starting point will be constructed from the provided y, m, d arguments, and will be adjusted until f::Function returns true. The step size in adjusting can be provided manually through the step keyword. limit provides a limit to the max number of iterations the adjustment API will pursue before throwing an error (given that f::Function is never satisfied).\n\n\n\n" -}, - -{ - "location": "stdlib/dates.html#Base.Dates.Date-Tuple{Base.Dates.TimeType}", - "page": "Dates and Time", - "title": "Base.Dates.Date", - "category": "method", - "text": "Date(dt::DateTime) -> Date\n\nConverts a DateTime to a Date. The hour, minute, second, and millisecond parts of the DateTime are truncated, so only the year, month and day parts are used in construction.\n\n\n\n" -}, - -{ - "location": "stdlib/dates.html#Base.Dates.Date-Tuple{AbstractString,AbstractString}", - "page": "Dates and Time", - "title": "Base.Dates.Date", - "category": "method", - "text": "Date(dt::AbstractString, format::AbstractString; locale=\"english\") -> Date\n\nConstruct a Date object by parsing a dt date string following the pattern given in the format string. Follows the same conventions as DateTime(::AbstractString, ::AbstractString).\n\n\n\n" -}, - -{ - "location": "stdlib/dates.html#Base.Dates.Date-Tuple{AbstractString,DateFormat}", - "page": "Dates and Time", - "title": "Base.Dates.Date", - "category": "method", - "text": "Date(dt::AbstractString, df::DateFormat) -> Date\n\nParse a date from a date string dt using a DateFormat object df.\n\n\n\n" -}, - -{ - "location": "stdlib/dates.html#Base.Dates.Time-NTuple{5,Int64}", - "page": "Dates and Time", - "title": "Base.Dates.Time", - "category": "method", - "text": "Time(h, [mi, s, ms, us, ns]) -> Time\n\nConstruct a Time type by parts. Arguments must be convertible to Int64.\n\n\n\n" -}, - -{ - "location": "stdlib/dates.html#Base.Dates.Time-Tuple{Vararg{Base.Dates.TimePeriod,N} where N}", - "page": "Dates and Time", - "title": "Base.Dates.Time", - "category": "method", - "text": "Time(period::TimePeriod...) -> Time\n\nConstruct a Time type by Period type parts. Arguments may be in any order. Time parts not provided will default to the value of Dates.default(period).\n\n\n\n" -}, - -{ - "location": "stdlib/dates.html#Base.Dates.Time-Tuple{Function,Vararg{Any,N} where N}", - "page": "Dates and Time", - "title": "Base.Dates.Time", - "category": "method", - "text": "Time(f::Function, h, mi=0; step::Period=Second(1), limit::Int=10000)\nTime(f::Function, h, mi, s; step::Period=Millisecond(1), limit::Int=10000)\nTime(f::Function, h, mi, s, ms; step::Period=Microsecond(1), limit::Int=10000)\nTime(f::Function, h, mi, s, ms, us; step::Period=Nanosecond(1), limit::Int=10000)\n\nCreate a Time through the adjuster API. The starting point will be constructed from the provided h, mi, s, ms, us arguments, and will be adjusted until f::Function returns true. The step size in adjusting can be provided manually through the step keyword. limit provides a limit to the max number of iterations the adjustment API will pursue before throwing an error (in the case that f::Function is never satisfied). Note that the default step will adjust to allow for greater precision for the given arguments; i.e. if hour, minute, and second arguments are provided, the default step will be Millisecond(1) instead of Second(1).\n\n\n\n" -}, - -{ - "location": "stdlib/dates.html#Base.Dates.Time-Tuple{DateTime}", - "page": "Dates and Time", - "title": "Base.Dates.Time", - "category": "method", - "text": "Time(dt::DateTime) -> Time\n\nConverts a DateTime to a Time. The hour, minute, second, and millisecond parts of the DateTime are used to create the new Time. Microsecond and nanoseconds are zero by default.\n\n\n\n" -}, - -{ - "location": "stdlib/dates.html#Base.Dates.now-Tuple{}", - "page": "Dates and Time", - "title": "Base.Dates.now", - "category": "method", - "text": "now() -> DateTime\n\nReturns a DateTime corresponding to the user\'s system time including the system timezone locale.\n\n\n\n" -}, - -{ - "location": "stdlib/dates.html#Base.Dates.now-Tuple{Type{Base.Dates.UTC}}", - "page": "Dates and Time", - "title": "Base.Dates.now", - "category": "method", - "text": "now(::Type{UTC}) -> DateTime\n\nReturns a DateTime corresponding to the user\'s system time as UTC/GMT.\n\n\n\n" -}, - -{ - "location": "stdlib/dates.html#Base.eps", - "page": "Dates and Time", - "title": "Base.eps", - "category": "function", - "text": "eps(::DateTime) -> Millisecond\neps(::Date) -> Day\neps(::Time) -> Nanosecond\n\nReturns Millisecond(1) for DateTime values, Day(1) for Date values, and Nanosecond(1) for Time values.\n\n\n\n" -}, - -{ - "location": "stdlib/dates.html#Dates-Functions-1", - "page": "Dates and Time", - "title": "Dates Functions", - "category": "section", - "text": "All Dates functions are defined in the Dates module; note that only the Date, DateTime, and now functions are exported; to use all other Dates functions, you\'ll need to prefix each function call with an explicit Dates., e.g. Dates.dayofweek(dt). Alternatively, you can write using Base.Dates to bring all exported functions into Main to be used without the Dates. prefix.Base.Dates.DateTime(::Int64, ::Int64, ::Int64, ::Int64, ::Int64, ::Int64, ::Int64)\nBase.Dates.DateTime(::Base.Dates.Period...)\nBase.Dates.DateTime(::Function, ::Any...)\nBase.Dates.DateTime(::Base.Dates.TimeType)\nBase.Dates.DateTime(::AbstractString, ::AbstractString)\nBase.Dates.format(::Base.Dates.TimeType, ::AbstractString)\nBase.Dates.DateFormat\nBase.Dates.@dateformat_str\nBase.Dates.DateTime(::AbstractString, ::Base.Dates.DateFormat)\nBase.Dates.Date(::Int64, ::Int64, ::Int64)\nBase.Dates.Date(::Base.Dates.Period...)\nBase.Dates.Date(::Function, ::Any, ::Any, ::Any)\nBase.Dates.Date(::Base.Dates.TimeType)\nBase.Dates.Date(::AbstractString, ::AbstractString)\nBase.Dates.Date(::AbstractString, ::Base.Dates.DateFormat)\nBase.Dates.Time(::Int64::Int64, ::Int64, ::Int64, ::Int64, ::Int64)\nBase.Dates.Time(::Base.Dates.TimePeriod...)\nBase.Dates.Time(::Function, ::Any...)\nBase.Dates.Time(::Base.Dates.DateTime)\nBase.Dates.now()\nBase.Dates.now(::Type{Base.Dates.UTC})\nBase.eps" -}, - -{ - "location": "stdlib/dates.html#Base.Dates.year", - "page": "Dates and Time", - "title": "Base.Dates.year", - "category": "function", - "text": "year(dt::TimeType) -> Int64\n\nThe year of a Date or DateTime as an Int64.\n\n\n\n" -}, - -{ - "location": "stdlib/dates.html#Base.Dates.month", - "page": "Dates and Time", - "title": "Base.Dates.month", - "category": "function", - "text": "month(dt::TimeType) -> Int64\n\nThe month of a Date or DateTime as an Int64.\n\n\n\n" -}, - -{ - "location": "stdlib/dates.html#Base.Dates.week", - "page": "Dates and Time", - "title": "Base.Dates.week", - "category": "function", - "text": "week(dt::TimeType) -> Int64\n\nReturn the ISO week date of a Date or DateTime as an Int64. Note that the first week of a year is the week that contains the first Thursday of the year which can result in dates prior to January 4th being in the last week of the previous year. For example week(Date(2005,1,1)) is the 53rd week of 2004.\n\n\n\n" -}, - -{ - "location": "stdlib/dates.html#Base.Dates.day", - "page": "Dates and Time", - "title": "Base.Dates.day", - "category": "function", - "text": "day(dt::TimeType) -> Int64\n\nThe day of month of a Date or DateTime as an Int64.\n\n\n\n" -}, - -{ - "location": "stdlib/dates.html#Base.Dates.hour", - "page": "Dates and Time", - "title": "Base.Dates.hour", - "category": "function", - "text": "hour(dt::DateTime) -> Int64\n\nThe hour of day of a DateTime as an Int64.\n\n\n\nhour(t::Time) -> Int64\n\nThe hour of a Time as an Int64.\n\n\n\n" -}, - -{ - "location": "stdlib/dates.html#Base.Dates.minute", - "page": "Dates and Time", - "title": "Base.Dates.minute", - "category": "function", - "text": "minute(dt::DateTime) -> Int64\n\nThe minute of a DateTime as an Int64.\n\n\n\nminute(t::Time) -> Int64\n\nThe minute of a Time as an Int64.\n\n\n\n" -}, - -{ - "location": "stdlib/dates.html#Base.Dates.second", - "page": "Dates and Time", - "title": "Base.Dates.second", - "category": "function", - "text": "second(dt::DateTime) -> Int64\n\nThe second of a DateTime as an Int64.\n\n\n\nsecond(t::Time) -> Int64\n\nThe second of a Time as an Int64.\n\n\n\n" -}, - -{ - "location": "stdlib/dates.html#Base.Dates.millisecond", - "page": "Dates and Time", - "title": "Base.Dates.millisecond", - "category": "function", - "text": "millisecond(dt::DateTime) -> Int64\n\nThe millisecond of a DateTime as an Int64.\n\n\n\nmillisecond(t::Time) -> Int64\n\nThe millisecond of a Time as an Int64.\n\n\n\n" -}, - -{ - "location": "stdlib/dates.html#Base.Dates.microsecond", - "page": "Dates and Time", - "title": "Base.Dates.microsecond", - "category": "function", - "text": "microsecond(t::Time) -> Int64\n\nThe microsecond of a Time as an Int64.\n\n\n\n" -}, - -{ - "location": "stdlib/dates.html#Base.Dates.nanosecond", - "page": "Dates and Time", - "title": "Base.Dates.nanosecond", - "category": "function", - "text": "nanosecond(t::Time) -> Int64\n\nThe nanosecond of a Time as an Int64.\n\n\n\n" -}, - -{ - "location": "stdlib/dates.html#Base.Dates.Year-Tuple{Base.Dates.TimeType}", - "page": "Dates and Time", - "title": "Base.Dates.Year", - "category": "method", - "text": "Year(v)\n\nConstruct a Year object with the given v value. Input must be losslessly convertible to an Int64.\n\n\n\n" -}, - -{ - "location": "stdlib/dates.html#Base.Dates.Month-Tuple{Base.Dates.TimeType}", - "page": "Dates and Time", - "title": "Base.Dates.Month", - "category": "method", - "text": "Month(v)\n\nConstruct a Month object with the given v value. Input must be losslessly convertible to an Int64.\n\n\n\n" -}, - -{ - "location": "stdlib/dates.html#Base.Dates.Week-Tuple{Base.Dates.TimeType}", - "page": "Dates and Time", - "title": "Base.Dates.Week", - "category": "method", - "text": "Week(v)\n\nConstruct a Week object with the given v value. Input must be losslessly convertible to an Int64.\n\n\n\n" -}, - -{ - "location": "stdlib/dates.html#Base.Dates.Day-Tuple{Base.Dates.TimeType}", - "page": "Dates and Time", - "title": "Base.Dates.Day", - "category": "method", - "text": "Day(v)\n\nConstruct a Day object with the given v value. Input must be losslessly convertible to an Int64.\n\n\n\n" -}, - -{ - "location": "stdlib/dates.html#Base.Dates.Hour-Tuple{DateTime}", - "page": "Dates and Time", - "title": "Base.Dates.Hour", - "category": "method", - "text": "Hour(dt::DateTime) -> Hour\n\nThe hour part of a DateTime as a Hour.\n\n\n\n" -}, - -{ - "location": "stdlib/dates.html#Base.Dates.Minute-Tuple{DateTime}", - "page": "Dates and Time", - "title": "Base.Dates.Minute", - "category": "method", - "text": "Minute(dt::DateTime) -> Minute\n\nThe minute part of a DateTime as a Minute.\n\n\n\n" -}, - -{ - "location": "stdlib/dates.html#Base.Dates.Second-Tuple{DateTime}", - "page": "Dates and Time", - "title": "Base.Dates.Second", - "category": "method", - "text": "Second(dt::DateTime) -> Second\n\nThe second part of a DateTime as a Second.\n\n\n\n" -}, - -{ - "location": "stdlib/dates.html#Base.Dates.Millisecond-Tuple{DateTime}", - "page": "Dates and Time", - "title": "Base.Dates.Millisecond", - "category": "method", - "text": "Millisecond(dt::DateTime) -> Millisecond\n\nThe millisecond part of a DateTime as a Millisecond.\n\n\n\n" -}, - -{ - "location": "stdlib/dates.html#Base.Dates.Microsecond-Tuple{Base.Dates.Time}", - "page": "Dates and Time", - "title": "Base.Dates.Microsecond", - "category": "method", - "text": "Microsecond(dt::Time) -> Microsecond\n\nThe microsecond part of a Time as a Microsecond.\n\n\n\n" -}, - -{ - "location": "stdlib/dates.html#Base.Dates.Nanosecond-Tuple{Base.Dates.Time}", - "page": "Dates and Time", - "title": "Base.Dates.Nanosecond", - "category": "method", - "text": "Nanosecond(dt::Time) -> Nanosecond\n\nThe nanosecond part of a Time as a Nanosecond.\n\n\n\n" -}, - -{ - "location": "stdlib/dates.html#Base.Dates.yearmonth", - "page": "Dates and Time", - "title": "Base.Dates.yearmonth", - "category": "function", - "text": "yearmonth(dt::TimeType) -> (Int64, Int64)\n\nSimultaneously return the year and month parts of a Date or DateTime.\n\n\n\n" -}, - -{ - "location": "stdlib/dates.html#Base.Dates.monthday", - "page": "Dates and Time", - "title": "Base.Dates.monthday", - "category": "function", - "text": "monthday(dt::TimeType) -> (Int64, Int64)\n\nSimultaneously return the month and day parts of a Date or DateTime.\n\n\n\n" -}, - -{ - "location": "stdlib/dates.html#Base.Dates.yearmonthday", - "page": "Dates and Time", - "title": "Base.Dates.yearmonthday", - "category": "function", - "text": "yearmonthday(dt::TimeType) -> (Int64, Int64, Int64)\n\nSimultaneously return the year, month and day parts of a Date or DateTime.\n\n\n\n" -}, - -{ - "location": "stdlib/dates.html#Accessor-Functions-1", - "page": "Dates and Time", - "title": "Accessor Functions", - "category": "section", - "text": "Base.Dates.year\nBase.Dates.month\nBase.Dates.week\nBase.Dates.day\nBase.Dates.hour\nBase.Dates.minute\nBase.Dates.second\nBase.Dates.millisecond\nBase.Dates.microsecond\nBase.Dates.nanosecond\nBase.Dates.Year(::Base.Dates.TimeType)\nBase.Dates.Month(::Base.Dates.TimeType)\nBase.Dates.Week(::Base.Dates.TimeType)\nBase.Dates.Day(::Base.Dates.TimeType)\nBase.Dates.Hour(::DateTime)\nBase.Dates.Minute(::DateTime)\nBase.Dates.Second(::DateTime)\nBase.Dates.Millisecond(::DateTime)\nBase.Dates.Microsecond(::Dates.Time)\nBase.Dates.Nanosecond(::Dates.Time)\nBase.Dates.yearmonth\nBase.Dates.monthday\nBase.Dates.yearmonthday" -}, - -{ - "location": "stdlib/dates.html#Base.Dates.dayname", - "page": "Dates and Time", - "title": "Base.Dates.dayname", - "category": "function", - "text": "dayname(dt::TimeType; locale=\"english\") -> AbstractString\n\nReturn the full day name corresponding to the day of the week of the Date or DateTime in the given locale.\n\n\n\n" -}, - -{ - "location": "stdlib/dates.html#Base.Dates.dayabbr", - "page": "Dates and Time", - "title": "Base.Dates.dayabbr", - "category": "function", - "text": "dayabbr(dt::TimeType; locale=\"english\") -> AbstractString\n\nReturn the abbreviated name corresponding to the day of the week of the Date or DateTime in the given locale.\n\n\n\n" -}, - -{ - "location": "stdlib/dates.html#Base.Dates.dayofweek", - "page": "Dates and Time", - "title": "Base.Dates.dayofweek", - "category": "function", - "text": "dayofweek(dt::TimeType) -> Int64\n\nReturns the day of the week as an Int64 with 1 = Monday, 2 = Tuesday, etc..\n\n\n\n" -}, - -{ - "location": "stdlib/dates.html#Base.Dates.dayofmonth", - "page": "Dates and Time", - "title": "Base.Dates.dayofmonth", - "category": "function", - "text": "dayofmonth(dt::TimeType) -> Int64\n\nThe day of month of a Date or DateTime as an Int64.\n\n\n\n" -}, - -{ - "location": "stdlib/dates.html#Base.Dates.dayofweekofmonth", - "page": "Dates and Time", - "title": "Base.Dates.dayofweekofmonth", - "category": "function", - "text": "dayofweekofmonth(dt::TimeType) -> Int\n\nFor the day of week of dt, returns which number it is in dt\'s month. So if the day of the week of dt is Monday, then 1 = First Monday of the month, 2 = Second Monday of the month, etc. In the range 1:5.\n\n\n\n" -}, - -{ - "location": "stdlib/dates.html#Base.Dates.daysofweekinmonth", - "page": "Dates and Time", - "title": "Base.Dates.daysofweekinmonth", - "category": "function", - "text": "daysofweekinmonth(dt::TimeType) -> Int\n\nFor the day of week of dt, returns the total number of that day of the week in dt\'s month. Returns 4 or 5. Useful in temporal expressions for specifying the last day of a week in a month by including dayofweekofmonth(dt) == daysofweekinmonth(dt) in the adjuster function.\n\n\n\n" -}, - -{ - "location": "stdlib/dates.html#Base.Dates.monthname", - "page": "Dates and Time", - "title": "Base.Dates.monthname", - "category": "function", - "text": "monthname(dt::TimeType; locale=\"english\") -> AbstractString\n\nReturn the full name of the month of the Date or DateTime in the given locale.\n\n\n\n" -}, - -{ - "location": "stdlib/dates.html#Base.Dates.monthabbr", - "page": "Dates and Time", - "title": "Base.Dates.monthabbr", - "category": "function", - "text": "monthabbr(dt::TimeType; locale=\"english\") -> AbstractString\n\nReturn the abbreviated month name of the Date or DateTime in the given locale.\n\n\n\n" -}, - -{ - "location": "stdlib/dates.html#Base.Dates.daysinmonth", - "page": "Dates and Time", - "title": "Base.Dates.daysinmonth", - "category": "function", - "text": "daysinmonth(dt::TimeType) -> Int\n\nReturns the number of days in the month of dt. Value will be 28, 29, 30, or 31.\n\n\n\n" -}, - -{ - "location": "stdlib/dates.html#Base.Dates.isleapyear", - "page": "Dates and Time", - "title": "Base.Dates.isleapyear", - "category": "function", - "text": "isleapyear(dt::TimeType) -> Bool\n\nReturns true if the year of dt is a leap year.\n\n\n\n" -}, - -{ - "location": "stdlib/dates.html#Base.Dates.dayofyear", - "page": "Dates and Time", - "title": "Base.Dates.dayofyear", - "category": "function", - "text": "dayofyear(dt::TimeType) -> Int\n\nReturns the day of the year for dt with January 1st being day 1.\n\n\n\n" -}, - -{ - "location": "stdlib/dates.html#Base.Dates.daysinyear", - "page": "Dates and Time", - "title": "Base.Dates.daysinyear", - "category": "function", - "text": "daysinyear(dt::TimeType) -> Int\n\nReturns 366 if the year of dt is a leap year, otherwise returns 365.\n\n\n\n" -}, - -{ - "location": "stdlib/dates.html#Base.Dates.quarterofyear", - "page": "Dates and Time", - "title": "Base.Dates.quarterofyear", - "category": "function", - "text": "quarterofyear(dt::TimeType) -> Int\n\nReturns the quarter that dt resides in. Range of value is 1:4.\n\n\n\n" -}, - -{ - "location": "stdlib/dates.html#Base.Dates.dayofquarter", - "page": "Dates and Time", - "title": "Base.Dates.dayofquarter", - "category": "function", - "text": "dayofquarter(dt::TimeType) -> Int\n\nReturns the day of the current quarter of dt. Range of value is 1:92.\n\n\n\n" -}, - -{ - "location": "stdlib/dates.html#Query-Functions-1", - "page": "Dates and Time", - "title": "Query Functions", - "category": "section", - "text": "Base.Dates.dayname\nBase.Dates.dayabbr\nBase.Dates.dayofweek\nBase.Dates.dayofmonth\nBase.Dates.dayofweekofmonth\nBase.Dates.daysofweekinmonth\nBase.Dates.monthname\nBase.Dates.monthabbr\nBase.Dates.daysinmonth\nBase.Dates.isleapyear\nBase.Dates.dayofyear\nBase.Dates.daysinyear\nBase.Dates.quarterofyear\nBase.Dates.dayofquarter" -}, - -{ - "location": "stdlib/dates.html#Base.trunc-Tuple{Base.Dates.TimeType,Type{Base.Dates.Period}}", - "page": "Dates and Time", - "title": "Base.trunc", - "category": "method", - "text": "trunc(dt::TimeType, ::Type{Period}) -> TimeType\n\nTruncates the value of dt according to the provided Period type. E.g. if dt is 1996-01-01T12:30:00, then trunc(dt,Day) == 1996-01-01T00:00:00.\n\n\n\n" -}, - -{ - "location": "stdlib/dates.html#Base.Dates.firstdayofweek", - "page": "Dates and Time", - "title": "Base.Dates.firstdayofweek", - "category": "function", - "text": "firstdayofweek(dt::TimeType) -> TimeType\n\nAdjusts dt to the Monday of its week.\n\n\n\n" -}, - -{ - "location": "stdlib/dates.html#Base.Dates.lastdayofweek", - "page": "Dates and Time", - "title": "Base.Dates.lastdayofweek", - "category": "function", - "text": "lastdayofweek(dt::TimeType) -> TimeType\n\nAdjusts dt to the Sunday of its week.\n\n\n\n" -}, - -{ - "location": "stdlib/dates.html#Base.Dates.firstdayofmonth", - "page": "Dates and Time", - "title": "Base.Dates.firstdayofmonth", - "category": "function", - "text": "firstdayofmonth(dt::TimeType) -> TimeType\n\nAdjusts dt to the first day of its month.\n\n\n\n" -}, - -{ - "location": "stdlib/dates.html#Base.Dates.lastdayofmonth", - "page": "Dates and Time", - "title": "Base.Dates.lastdayofmonth", - "category": "function", - "text": "lastdayofmonth(dt::TimeType) -> TimeType\n\nAdjusts dt to the last day of its month.\n\n\n\n" -}, - -{ - "location": "stdlib/dates.html#Base.Dates.firstdayofyear", - "page": "Dates and Time", - "title": "Base.Dates.firstdayofyear", - "category": "function", - "text": "firstdayofyear(dt::TimeType) -> TimeType\n\nAdjusts dt to the first day of its year.\n\n\n\n" -}, - -{ - "location": "stdlib/dates.html#Base.Dates.lastdayofyear", - "page": "Dates and Time", - "title": "Base.Dates.lastdayofyear", - "category": "function", - "text": "lastdayofyear(dt::TimeType) -> TimeType\n\nAdjusts dt to the last day of its year.\n\n\n\n" -}, - -{ - "location": "stdlib/dates.html#Base.Dates.firstdayofquarter", - "page": "Dates and Time", - "title": "Base.Dates.firstdayofquarter", - "category": "function", - "text": "firstdayofquarter(dt::TimeType) -> TimeType\n\nAdjusts dt to the first day of its quarter.\n\n\n\n" -}, - -{ - "location": "stdlib/dates.html#Base.Dates.lastdayofquarter", - "page": "Dates and Time", - "title": "Base.Dates.lastdayofquarter", - "category": "function", - "text": "lastdayofquarter(dt::TimeType) -> TimeType\n\nAdjusts dt to the last day of its quarter.\n\n\n\n" -}, - -{ - "location": "stdlib/dates.html#Base.Dates.tonext-Tuple{Base.Dates.TimeType,Int64}", - "page": "Dates and Time", - "title": "Base.Dates.tonext", - "category": "method", - "text": "tonext(dt::TimeType, dow::Int; same::Bool=false) -> TimeType\n\nAdjusts dt to the next day of week corresponding to dow with 1 = Monday, 2 = Tuesday, etc. Setting same=true allows the current dt to be considered as the next dow, allowing for no adjustment to occur.\n\n\n\n" -}, - -{ - "location": "stdlib/dates.html#Base.Dates.toprev-Tuple{Base.Dates.TimeType,Int64}", - "page": "Dates and Time", - "title": "Base.Dates.toprev", - "category": "method", - "text": "toprev(dt::TimeType, dow::Int; same::Bool=false) -> TimeType\n\nAdjusts dt to the previous day of week corresponding to dow with 1 = Monday, 2 = Tuesday, etc. Setting same=true allows the current dt to be considered as the previous dow, allowing for no adjustment to occur.\n\n\n\n" -}, - -{ - "location": "stdlib/dates.html#Base.Dates.tofirst", - "page": "Dates and Time", - "title": "Base.Dates.tofirst", - "category": "function", - "text": "tofirst(dt::TimeType, dow::Int; of=Month) -> TimeType\n\nAdjusts dt to the first dow of its month. Alternatively, of=Year will adjust to the first dow of the year.\n\n\n\n" -}, - -{ - "location": "stdlib/dates.html#Base.Dates.tolast", - "page": "Dates and Time", - "title": "Base.Dates.tolast", - "category": "function", - "text": "tolast(dt::TimeType, dow::Int; of=Month) -> TimeType\n\nAdjusts dt to the last dow of its month. Alternatively, of=Year will adjust to the last dow of the year.\n\n\n\n" -}, - -{ - "location": "stdlib/dates.html#Base.Dates.tonext-Tuple{Function,Base.Dates.TimeType}", - "page": "Dates and Time", - "title": "Base.Dates.tonext", - "category": "method", - "text": "tonext(func::Function, dt::TimeType; step=Day(1), limit=10000, same=false) -> TimeType\n\nAdjusts dt by iterating at most limit iterations by step increments until func returns true. func must take a single TimeType argument and return a Bool. same allows dt to be considered in satisfying func.\n\n\n\n" -}, - -{ - "location": "stdlib/dates.html#Base.Dates.toprev-Tuple{Function,Base.Dates.TimeType}", - "page": "Dates and Time", - "title": "Base.Dates.toprev", - "category": "method", - "text": "toprev(func::Function, dt::TimeType; step=Day(-1), limit=10000, same=false) -> TimeType\n\nAdjusts dt by iterating at most limit iterations by step increments until func returns true. func must take a single TimeType argument and return a Bool. same allows dt to be considered in satisfying func.\n\n\n\n" -}, - -{ - "location": "stdlib/dates.html#Adjuster-Functions-1", - "page": "Dates and Time", - "title": "Adjuster Functions", - "category": "section", - "text": "Base.trunc(::Base.Dates.TimeType, ::Type{Base.Dates.Period})\nBase.Dates.firstdayofweek\nBase.Dates.lastdayofweek\nBase.Dates.firstdayofmonth\nBase.Dates.lastdayofmonth\nBase.Dates.firstdayofyear\nBase.Dates.lastdayofyear\nBase.Dates.firstdayofquarter\nBase.Dates.lastdayofquarter\nBase.Dates.tonext(::Base.Dates.TimeType, ::Int)\nBase.Dates.toprev(::Base.Dates.TimeType, ::Int)\nBase.Dates.tofirst\nBase.Dates.tolast\nBase.Dates.tonext(::Function, ::Base.Dates.TimeType)\nBase.Dates.toprev(::Function, ::Base.Dates.TimeType)" -}, - -{ - "location": "stdlib/dates.html#Base.Dates.Period-Tuple{Any}", - "page": "Dates and Time", - "title": "Base.Dates.Period", - "category": "method", - "text": "Year(v)\nMonth(v)\nWeek(v)\nDay(v)\nHour(v)\nMinute(v)\nSecond(v)\nMillisecond(v)\nMicrosecond(v)\nNanosecond(v)\n\nConstruct a Period type with the given v value. Input must be losslessly convertible to an Int64.\n\n\n\n" -}, - -{ - "location": "stdlib/dates.html#Base.Dates.CompoundPeriod-Tuple{Array{#s27,1} where #s27<:Base.Dates.Period}", - "page": "Dates and Time", - "title": "Base.Dates.CompoundPeriod", - "category": "method", - "text": "CompoundPeriod(periods) -> CompoundPeriod\n\nConstruct a CompoundPeriod from a Vector of Periods. All Periods of the same type will be added together.\n\nExamples\n\njulia> Dates.CompoundPeriod(Dates.Hour(12), Dates.Hour(13))\n25 hours\n\njulia> Dates.CompoundPeriod(Dates.Hour(-1), Dates.Minute(1))\n-1 hour, 1 minute\n\njulia> Dates.CompoundPeriod(Dates.Month(1), Dates.Week(-2))\n1 month, -2 weeks\n\njulia> Dates.CompoundPeriod(Dates.Minute(50000))\n50000 minutes\n\n\n\n" -}, - -{ - "location": "stdlib/dates.html#Base.Dates.default", - "page": "Dates and Time", - "title": "Base.Dates.default", - "category": "function", - "text": "default(p::Period) -> Period\n\nReturns a sensible \"default\" value for the input Period by returning T(1) for Year, Month, and Day, and T(0) for Hour, Minute, Second, and Millisecond.\n\n\n\n" -}, - -{ - "location": "stdlib/dates.html#Periods-1", - "page": "Dates and Time", - "title": "Periods", - "category": "section", - "text": "Base.Dates.Period(::Any)\nBase.Dates.CompoundPeriod(::Vector{<:Base.Dates.Period})\nBase.Dates.default" -}, - -{ - "location": "stdlib/dates.html#Base.floor-Tuple{Base.Dates.TimeType,Base.Dates.Period}", - "page": "Dates and Time", - "title": "Base.floor", - "category": "method", - "text": "floor(dt::TimeType, p::Period) -> TimeType\n\nReturns the nearest Date or DateTime less than or equal to dt at resolution p.\n\nFor convenience, p may be a type instead of a value: floor(dt, Dates.Hour) is a shortcut for floor(dt, Dates.Hour(1)).\n\njulia> floor(Date(1985, 8, 16), Dates.Month)\n1985-08-01\n\njulia> floor(DateTime(2013, 2, 13, 0, 31, 20), Dates.Minute(15))\n2013-02-13T00:30:00\n\njulia> floor(DateTime(2016, 8, 6, 12, 0, 0), Dates.Day)\n2016-08-06T00:00:00\n\n\n\n" -}, - -{ - "location": "stdlib/dates.html#Base.ceil-Tuple{Base.Dates.TimeType,Base.Dates.Period}", - "page": "Dates and Time", - "title": "Base.ceil", - "category": "method", - "text": "ceil(dt::TimeType, p::Period) -> TimeType\n\nReturns the nearest Date or DateTime greater than or equal to dt at resolution p.\n\nFor convenience, p may be a type instead of a value: ceil(dt, Dates.Hour) is a shortcut for ceil(dt, Dates.Hour(1)).\n\njulia> ceil(Date(1985, 8, 16), Dates.Month)\n1985-09-01\n\njulia> ceil(DateTime(2013, 2, 13, 0, 31, 20), Dates.Minute(15))\n2013-02-13T00:45:00\n\njulia> ceil(DateTime(2016, 8, 6, 12, 0, 0), Dates.Day)\n2016-08-07T00:00:00\n\n\n\n" -}, - -{ - "location": "stdlib/dates.html#Base.round-Tuple{Base.Dates.TimeType,Base.Dates.Period,RoundingMode{:NearestTiesUp}}", - "page": "Dates and Time", - "title": "Base.round", - "category": "method", - "text": "round(dt::TimeType, p::Period, [r::RoundingMode]) -> TimeType\n\nReturns the Date or DateTime nearest to dt at resolution p. By default (RoundNearestTiesUp), ties (e.g., rounding 9:30 to the nearest hour) will be rounded up.\n\nFor convenience, p may be a type instead of a value: round(dt, Dates.Hour) is a shortcut for round(dt, Dates.Hour(1)).\n\njulia> round(Date(1985, 8, 16), Dates.Month)\n1985-08-01\n\njulia> round(DateTime(2013, 2, 13, 0, 31, 20), Dates.Minute(15))\n2013-02-13T00:30:00\n\njulia> round(DateTime(2016, 8, 6, 12, 0, 0), Dates.Day)\n2016-08-07T00:00:00\n\nValid rounding modes for round(::TimeType, ::Period, ::RoundingMode) are RoundNearestTiesUp (default), RoundDown (floor), and RoundUp (ceil).\n\n\n\n" -}, - -{ - "location": "stdlib/dates.html#Base.Dates.floorceil", - "page": "Dates and Time", - "title": "Base.Dates.floorceil", - "category": "function", - "text": "floorceil(dt::TimeType, p::Period) -> (TimeType, TimeType)\n\nSimultaneously return the floor and ceil of a Date or DateTime at resolution p. More efficient than calling both floor and ceil individually.\n\n\n\n" -}, - -{ - "location": "stdlib/dates.html#Base.Dates.epochdays2date", - "page": "Dates and Time", - "title": "Base.Dates.epochdays2date", - "category": "function", - "text": "epochdays2date(days) -> Date\n\nTakes the number of days since the rounding epoch (0000-01-01T00:00:00) and returns the corresponding Date.\n\n\n\n" -}, - -{ - "location": "stdlib/dates.html#Base.Dates.epochms2datetime", - "page": "Dates and Time", - "title": "Base.Dates.epochms2datetime", - "category": "function", - "text": "epochms2datetime(milliseconds) -> DateTime\n\nTakes the number of milliseconds since the rounding epoch (0000-01-01T00:00:00) and returns the corresponding DateTime.\n\n\n\n" -}, - -{ - "location": "stdlib/dates.html#Base.Dates.date2epochdays", - "page": "Dates and Time", - "title": "Base.Dates.date2epochdays", - "category": "function", - "text": "date2epochdays(dt::Date) -> Int64\n\nTakes the given Date and returns the number of days since the rounding epoch (0000-01-01T00:00:00) as an Int64.\n\n\n\n" -}, - -{ - "location": "stdlib/dates.html#Base.Dates.datetime2epochms", - "page": "Dates and Time", - "title": "Base.Dates.datetime2epochms", - "category": "function", - "text": "datetime2epochms(dt::DateTime) -> Int64\n\nTakes the given DateTime and returns the number of milliseconds since the rounding epoch (0000-01-01T00:00:00) as an Int64.\n\n\n\n" -}, - -{ - "location": "stdlib/dates.html#Rounding-Functions-1", - "page": "Dates and Time", - "title": "Rounding Functions", - "category": "section", - "text": "Date and DateTime values can be rounded to a specified resolution (e.g., 1 month or 15 minutes) with floor, ceil, or round.Base.floor(::Base.Dates.TimeType, ::Base.Dates.Period)\nBase.ceil(::Base.Dates.TimeType, ::Base.Dates.Period)\nBase.round(::Base.Dates.TimeType, ::Base.Dates.Period, ::RoundingMode{:NearestTiesUp})The following functions are not exported:Base.Dates.floorceil\nBase.Dates.epochdays2date\nBase.Dates.epochms2datetime\nBase.Dates.date2epochdays\nBase.Dates.datetime2epochms" -}, - -{ - "location": "stdlib/dates.html#Base.Dates.today", - "page": "Dates and Time", - "title": "Base.Dates.today", - "category": "function", - "text": "today() -> Date\n\nReturns the date portion of now().\n\n\n\n" -}, - -{ - "location": "stdlib/dates.html#Base.Dates.unix2datetime", - "page": "Dates and Time", - "title": "Base.Dates.unix2datetime", - "category": "function", - "text": "unix2datetime(x) -> DateTime\n\nTakes the number of seconds since unix epoch 1970-01-01T00:00:00 and converts to the corresponding DateTime.\n\n\n\n" -}, - -{ - "location": "stdlib/dates.html#Base.Dates.datetime2unix", - "page": "Dates and Time", - "title": "Base.Dates.datetime2unix", - "category": "function", - "text": "datetime2unix(dt::DateTime) -> Float64\n\nTakes the given DateTime and returns the number of seconds since the unix epoch 1970-01-01T00:00:00 as a Float64.\n\n\n\n" -}, - -{ - "location": "stdlib/dates.html#Base.Dates.julian2datetime", - "page": "Dates and Time", - "title": "Base.Dates.julian2datetime", - "category": "function", - "text": "julian2datetime(julian_days) -> DateTime\n\nTakes the number of Julian calendar days since epoch -4713-11-24T12:00:00 and returns the corresponding DateTime.\n\n\n\n" -}, - -{ - "location": "stdlib/dates.html#Base.Dates.datetime2julian", - "page": "Dates and Time", - "title": "Base.Dates.datetime2julian", - "category": "function", - "text": "datetime2julian(dt::DateTime) -> Float64\n\nTakes the given DateTime and returns the number of Julian calendar days since the julian epoch -4713-11-24T12:00:00 as a Float64.\n\n\n\n" -}, - -{ - "location": "stdlib/dates.html#Base.Dates.rata2datetime", - "page": "Dates and Time", - "title": "Base.Dates.rata2datetime", - "category": "function", - "text": "rata2datetime(days) -> DateTime\n\nTakes the number of Rata Die days since epoch 0000-12-31T00:00:00 and returns the corresponding DateTime.\n\n\n\n" -}, - -{ - "location": "stdlib/dates.html#Base.Dates.datetime2rata", - "page": "Dates and Time", - "title": "Base.Dates.datetime2rata", - "category": "function", - "text": "datetime2rata(dt::TimeType) -> Int64\n\nReturns the number of Rata Die days since epoch from the given Date or DateTime.\n\n\n\n" -}, - -{ - "location": "stdlib/dates.html#Conversion-Functions-1", - "page": "Dates and Time", - "title": "Conversion Functions", - "category": "section", - "text": "Base.Dates.today\nBase.Dates.unix2datetime\nBase.Dates.datetime2unix\nBase.Dates.julian2datetime\nBase.Dates.datetime2julian\nBase.Dates.rata2datetime\nBase.Dates.datetime2rata" -}, - -{ - "location": "stdlib/dates.html#Constants-1", - "page": "Dates and Time", - "title": "Constants", - "category": "section", - "text": "Days of the Week:Variable Abbr. Value (Int)\nMonday Mon 1\nTuesday Tue 2\nWednesday Wed 3\nThursday Thu 4\nFriday Fri 5\nSaturday Sat 6\nSunday Sun 7Months of the Year:Variable Abbr. Value (Int)\nJanuary Jan 1\nFebruary Feb 2\nMarch Mar 3\nApril Apr 4\nMay May 5\nJune Jun 6\nJuly Jul 7\nAugust Aug 8\nSeptember Sep 9\nOctober Oct 10\nNovember Nov 11\nDecember Dec 12" -}, - -{ - "location": "stdlib/iterators.html#", - "page": "Iteration utilities", - "title": "Iteration utilities", - "category": "page", - "text": "" -}, - -{ - "location": "stdlib/iterators.html#Base.Iterators.zip", - "page": "Iteration utilities", - "title": "Base.Iterators.zip", - "category": "function", - "text": "zip(iters...)\n\nFor a set of iterable objects, returns an iterable of tuples, where the ith tuple contains the ith component of each input iterable.\n\nNote that zip is its own inverse: collect(zip(zip(a...)...)) == collect(a).\n\nExample\n\njulia> a = 1:5\n1:5\n\njulia> b = [\"e\",\"d\",\"b\",\"c\",\"a\"]\n5-element Array{String,1}:\n \"e\"\n \"d\"\n \"b\"\n \"c\"\n \"a\"\n\njulia> c = zip(a,b)\nBase.Iterators.Zip2{UnitRange{Int64},Array{String,1}}(1:5, String[\"e\", \"d\", \"b\", \"c\", \"a\"])\n\njulia> length(c)\n5\n\njulia> first(c)\n(1, \"e\")\n\n\n\n" -}, - -{ - "location": "stdlib/iterators.html#Base.Iterators.enumerate", - "page": "Iteration utilities", - "title": "Base.Iterators.enumerate", - "category": "function", - "text": "enumerate(iter)\n\nAn iterator that yields (i, x) where i is a counter starting at 1, and x is the ith value from the given iterator. It\'s useful when you need not only the values x over which you are iterating, but also the number of iterations so far. Note that i may not be valid for indexing iter; it\'s also possible that x != iter[i], if iter has indices that do not start at 1. See the enumerate(IndexLinear(), iter) method if you want to ensure that i is an index.\n\nExample\n\njulia> a = [\"a\", \"b\", \"c\"];\n\njulia> for (index, value) in enumerate(a)\n println(\"$index $value\")\n end\n1 a\n2 b\n3 c\n\n\n\nenumerate(IndexLinear(), A)\nenumerate(IndexCartesian(), A)\nenumerate(IndexStyle(A), A)\n\nAn iterator that accesses each element of the array A, returning (i, x), where i is the index for the element and x = A[i]. This is similar to enumerate(A), except i will always be a valid index for A.\n\nSpecifying IndexLinear() ensures that i will be an integer; specifying IndexCartesian() ensures that i will be a CartesianIndex; specifying IndexStyle(A) chooses whichever has been defined as the native indexing style for array A.\n\nExamples\n\njulia> A = [\"a\" \"d\"; \"b\" \"e\"; \"c\" \"f\"];\n\njulia> for (index, value) in enumerate(IndexStyle(A), A)\n println(\"$index $value\")\n end\n1 a\n2 b\n3 c\n4 d\n5 e\n6 f\n\njulia> S = view(A, 1:2, :);\n\njulia> for (index, value) in enumerate(IndexStyle(S), S)\n println(\"$index $value\")\n end\nCartesianIndex{2}((1, 1)) a\nCartesianIndex{2}((2, 1)) b\nCartesianIndex{2}((1, 2)) d\nCartesianIndex{2}((2, 2)) e\n\nNote that enumerate(A) returns i as a counter (always starting at 1), whereas enumerate(IndexLinear(), A) returns i as an index (starting at the first linear index of A, which may or may not be 1).\n\nSee also: IndexStyle, indices.\n\n\n\n" -}, - -{ - "location": "stdlib/iterators.html#Base.Iterators.rest", - "page": "Iteration utilities", - "title": "Base.Iterators.rest", - "category": "function", - "text": "rest(iter, state)\n\nAn iterator that yields the same elements as iter, but starting at the given state.\n\n\n\n" -}, - -{ - "location": "stdlib/iterators.html#Base.Iterators.countfrom", - "page": "Iteration utilities", - "title": "Base.Iterators.countfrom", - "category": "function", - "text": "countfrom(start=1, step=1)\n\nAn iterator that counts forever, starting at start and incrementing by step.\n\n\n\n" -}, - -{ - "location": "stdlib/iterators.html#Base.Iterators.take", - "page": "Iteration utilities", - "title": "Base.Iterators.take", - "category": "function", - "text": "take(iter, n)\n\nAn iterator that generates at most the first n elements of iter.\n\nExample\n\njulia> a = 1:2:11\n1:2:11\n\njulia> collect(a)\n6-element Array{Int64,1}:\n 1\n 3\n 5\n 7\n 9\n 11\n\njulia> collect(Iterators.take(a,3))\n3-element Array{Int64,1}:\n 1\n 3\n 5\n\n\n\n" -}, - -{ - "location": "stdlib/iterators.html#Base.Iterators.drop", - "page": "Iteration utilities", - "title": "Base.Iterators.drop", - "category": "function", - "text": "drop(iter, n)\n\nAn iterator that generates all but the first n elements of iter.\n\nExample\n\njulia> a = 1:2:11\n1:2:11\n\njulia> collect(a)\n6-element Array{Int64,1}:\n 1\n 3\n 5\n 7\n 9\n 11\n\njulia> collect(Iterators.drop(a,4))\n2-element Array{Int64,1}:\n 9\n 11\n\n\n\n" -}, - -{ - "location": "stdlib/iterators.html#Base.Iterators.cycle", - "page": "Iteration utilities", - "title": "Base.Iterators.cycle", - "category": "function", - "text": "cycle(iter)\n\nAn iterator that cycles through iter forever.\n\n\n\n" -}, - -{ - "location": "stdlib/iterators.html#Base.Iterators.repeated", - "page": "Iteration utilities", - "title": "Base.Iterators.repeated", - "category": "function", - "text": "repeated(x[, n::Int])\n\nAn iterator that generates the value x forever. If n is specified, generates x that many times (equivalent to take(repeated(x), n)).\n\nExample\n\njulia> a = Iterators.repeated([1 2], 4);\n\njulia> collect(a)\n4-element Array{Array{Int64,2},1}:\n [1 2]\n [1 2]\n [1 2]\n [1 2]\n\n\n\n" -}, - -{ - "location": "stdlib/iterators.html#Base.Iterators.product", - "page": "Iteration utilities", - "title": "Base.Iterators.product", - "category": "function", - "text": "product(iters...)\n\nReturns an iterator over the product of several iterators. Each generated element is a tuple whose ith element comes from the ith argument iterator. The first iterator changes the fastest. Example:\n\nExample\n\njulia> collect(Iterators.product(1:2,3:5))\n2×3 Array{Tuple{Int64,Int64},2}:\n (1, 3) (1, 4) (1, 5)\n (2, 3) (2, 4) (2, 5)\n\n\n\n" -}, - -{ - "location": "stdlib/iterators.html#Base.Iterators.flatten", - "page": "Iteration utilities", - "title": "Base.Iterators.flatten", - "category": "function", - "text": "flatten(iter)\n\nGiven an iterator that yields iterators, return an iterator that yields the elements of those iterators. Put differently, the elements of the argument iterator are concatenated.\n\nExample\n\njulia> collect(Iterators.flatten((1:2, 8:9)))\n4-element Array{Int64,1}:\n 1\n 2\n 8\n 9\n\n\n\n" -}, - -{ - "location": "stdlib/iterators.html#Base.Iterators.partition", - "page": "Iteration utilities", - "title": "Base.Iterators.partition", - "category": "function", - "text": "partition(collection, n)\n\nIterate over a collection n elements at a time.\n\nExample\n\njulia> collect(Iterators.partition([1,2,3,4,5], 2))\n3-element Array{Array{Int64,1},1}:\n [1, 2]\n [3, 4]\n [5]\n\n\n\n" -}, - -{ - "location": "stdlib/iterators.html#Iteration-utilities-1", - "page": "Iteration utilities", - "title": "Iteration utilities", - "category": "section", - "text": "Base.Iterators.zip\nBase.Iterators.enumerate\nBase.Iterators.rest\nBase.Iterators.countfrom\nBase.Iterators.take\nBase.Iterators.drop\nBase.Iterators.cycle\nBase.Iterators.repeated\nBase.Iterators.product\nBase.Iterators.flatten\nBase.Iterators.partition" -}, - -{ - "location": "stdlib/test.html#", - "page": "Unit Testing", - "title": "Unit Testing", - "category": "page", - "text": "" -}, - -{ - "location": "stdlib/test.html#Unit-Testing-1", - "page": "Unit Testing", - "title": "Unit Testing", - "category": "section", - "text": "DocTestSetup = quote\n using Base.Test\nend" -}, - -{ - "location": "stdlib/test.html#Base.runtests", - "page": "Unit Testing", - "title": "Base.runtests", - "category": "function", - "text": "runtests([tests=[\"all\"] [, numcores=ceil(Int, Sys.CPU_CORES / 2) ]])\n\nRun the Julia unit tests listed in tests, which can be either a string or an array of strings, using numcores processors. (not exported)\n\n\n\n" -}, - -{ - "location": "stdlib/test.html#Testing-Base-Julia-1", - "page": "Unit Testing", - "title": "Testing Base Julia", - "category": "section", - "text": "Julia is under rapid development and has an extensive test suite to verify functionality across multiple platforms. If you build Julia from source, you can run this test suite with make test. In a binary install, you can run the test suite using Base.runtests().Base.runtests" -}, - -{ - "location": "stdlib/test.html#Base.Test.@test", - "page": "Unit Testing", - "title": "Base.Test.@test", - "category": "macro", - "text": "@test ex\n@test f(args...) key=val ...\n\nTests that the expression ex evaluates to true. Returns a Pass Result if it does, a Fail Result if it is false, and an Error Result if it could not be evaluated.\n\nThe @test f(args...) key=val... form is equivalent to writing @test f(args..., key=val...) which can be useful when the expression is a call using infix syntax such as approximate comparisons:\n\n@test a ≈ b atol=ε\n\nThis is equivalent to the uglier test @test ≈(a, b, atol=ε). It is an error to supply more than one expression unless the first is a call expression and the rest are assignments (k=v).\n\n\n\n" -}, - -{ - "location": "stdlib/test.html#Base.Test.@test_throws", - "page": "Unit Testing", - "title": "Base.Test.@test_throws", - "category": "macro", - "text": "@test_throws extype ex\n\nTests that the expression ex throws an exception of type extype. Note that @test_throws does not support a trailing keyword form.\n\n\n\n" -}, - -{ - "location": "stdlib/test.html#Basic-Unit-Tests-1", - "page": "Unit Testing", - "title": "Basic Unit Tests", - "category": "section", - "text": "The Base.Test module provides simple unit testing functionality. Unit testing is a way to see if your code is correct by checking that the results are what you expect. It can be helpful to ensure your code still works after you make changes, and can be used when developing as a way of specifying the behaviors your code should have when complete.Simple unit testing can be performed with the @test() and @test_throws() macros:Base.Test.@test\nBase.Test.@test_throwsFor example, suppose we want to check our new function foo(x) works as expected:julia> using Base.Test\n\njulia> foo(x) = length(x)^2\nfoo (generic function with 1 method)If the condition is true, a Pass is returned:julia> @test foo(\"bar\") == 9\nTest Passed\n\njulia> @test foo(\"fizz\") >= 10\nTest PassedIf the condition is false, then a Fail is returned and an exception is thrown:julia> @test foo(\"f\") == 20\nTest Failed\n Expression: foo(\"f\") == 20\n Evaluated: 1 == 20\nERROR: There was an error during testingIf the condition could not be evaluated because an exception was thrown, which occurs in this case because length() is not defined for symbols, an Error object is returned and an exception is thrown:julia> @test foo(:cat) == 1\nError During Test\n Test threw an exception of type MethodError\n Expression: foo(:cat) == 1\n MethodError: no method matching length(::Symbol)\n Closest candidates are:\n length(::SimpleVector) at essentials.jl:256\n length(::Base.MethodList) at reflection.jl:521\n length(::MethodTable) at reflection.jl:597\n ...\n Stacktrace:\n [...]\nERROR: There was an error during testingIf we expect that evaluating an expression should throw an exception, then we can use @test_throws() to check that this occurs:julia> @test_throws MethodError foo(:cat)\nTest Passed\n Thrown: MethodError" -}, - -{ - "location": "stdlib/test.html#Base.Test.@testset", - "page": "Unit Testing", - "title": "Base.Test.@testset", - "category": "macro", - "text": "@testset [CustomTestSet] [option=val ...] [\"description\"] begin ... end\n@testset [CustomTestSet] [option=val ...] [\"description $v\"] for v in (...) ... end\n@testset [CustomTestSet] [option=val ...] [\"description $v, $w\"] for v in (...), w in (...) ... end\n\nStarts a new test set, or multiple test sets if a for loop is provided.\n\nIf no custom testset type is given it defaults to creating a DefaultTestSet. DefaultTestSet records all the results and, if there are any Fails or Errors, throws an exception at the end of the top-level (non-nested) test set, along with a summary of the test results.\n\nAny custom testset type (subtype of AbstractTestSet) can be given and it will also be used for any nested @testset invocations. The given options are only applied to the test set where they are given. The default test set type does not take any options.\n\nThe description string accepts interpolation from the loop indices. If no description is provided, one is constructed based on the variables.\n\nBy default the @testset macro will return the testset object itself, though this behavior can be customized in other testset types. If a for loop is used then the macro collects and returns a list of the return values of the finish method, which by default will return a list of the testset objects used in each iteration.\n\n\n\n" -}, - -{ - "location": "stdlib/test.html#Working-with-Test-Sets-1", - "page": "Unit Testing", - "title": "Working with Test Sets", - "category": "section", - "text": "Typically a large number of tests are used to make sure functions work correctly over a range of inputs. In the event a test fails, the default behavior is to throw an exception immediately. However, it is normally preferable to run the rest of the tests first to get a better picture of how many errors there are in the code being tested.The @testset() macro can be used to group tests into sets. All the tests in a test set will be run, and at the end of the test set a summary will be printed. If any of the tests failed, or could not be evaluated due to an error, the test set will then throw a TestSetException.Base.Test.@testsetWe can put our tests for the foo(x) function in a test set:julia> @testset \"Foo Tests\" begin\n @test foo(\"a\") == 1\n @test foo(\"ab\") == 4\n @test foo(\"abc\") == 9\n end;\nTest Summary: | Pass Total\nFoo Tests | 3 3Test sets can also be nested:julia> @testset \"Foo Tests\" begin\n @testset \"Animals\" begin\n @test foo(\"cat\") == 9\n @test foo(\"dog\") == foo(\"cat\")\n end\n @testset \"Arrays $i\" for i in 1:3\n @test foo(zeros(i)) == i^2\n @test foo(ones(i)) == i^2\n end\n end;\nTest Summary: | Pass Total\nFoo Tests | 8 8In the event that a nested test set has no failures, as happened here, it will be hidden in the summary. If we do have a test failure, only the details for the failed test sets will be shown:julia> @testset \"Foo Tests\" begin\n @testset \"Animals\" begin\n @testset \"Felines\" begin\n @test foo(\"cat\") == 9\n end\n @testset \"Canines\" begin\n @test foo(\"dog\") == 9\n end\n end\n @testset \"Arrays\" begin\n @test foo(zeros(2)) == 4\n @test foo(ones(4)) == 15\n end\n end\n\nArrays: Test Failed\n Expression: foo(ones(4)) == 15\n Evaluated: 16 == 15\nStacktrace:\n [...]\nTest Summary: | Pass Fail Total\nFoo Tests | 3 1 4\n Animals | 2 2\n Arrays | 1 1 2\nERROR: Some tests did not pass: 3 passed, 1 failed, 0 errored, 0 broken." -}, - -{ - "location": "stdlib/test.html#Base.Test.@inferred", - "page": "Unit Testing", - "title": "Base.Test.@inferred", - "category": "macro", - "text": "@inferred f(x)\n\nTests that the call expression f(x) returns a value of the same type inferred by the compiler. It is useful to check for type stability.\n\nf(x) can be any call expression. Returns the result of f(x) if the types match, and an Error Result if it finds different types.\n\njulia> using Base.Test\n\njulia> f(a,b,c) = b > 1 ? 1 : 1.0\nf (generic function with 1 method)\n\njulia> typeof(f(1,2,3))\nInt64\n\njulia> @code_warntype f(1,2,3)\nVariables:\n #self# \n a \n b::Int64\n c \n\nBody:\n begin\n unless (Base.slt_int)(1, b::Int64)::Bool goto 3\n return 1\n 3:\n return 1.0\n end::UNION{FLOAT64, INT64}\n\njulia> @inferred f(1,2,3)\nERROR: return type Int64 does not match inferred return type Union{Float64, Int64}\nStacktrace:\n [1] error(::String) at ./error.jl:21\n\njulia> @inferred max(1,2)\n2\n\n\n\n" -}, - -{ - "location": "stdlib/test.html#Base.Test.@test_warn", - "page": "Unit Testing", - "title": "Base.Test.@test_warn", - "category": "macro", - "text": "@test_warn msg expr\n\nTest whether evaluating expr results in STDERR output that contains the msg string or matches the msg regular expression. If msg is a boolean function, tests whether msg(output) returns true. If msg is a tuple or array, checks that the error output contains/matches each item in msg. Returns the result of evaluating expr.\n\nSee also @test_nowarn to check for the absence of error output.\n\n\n\n" -}, - -{ - "location": "stdlib/test.html#Base.Test.@test_nowarn", - "page": "Unit Testing", - "title": "Base.Test.@test_nowarn", - "category": "macro", - "text": "@test_nowarn expr\n\nTest whether evaluating expr results in empty STDERR output (no warnings or other messages). Returns the result of evaluating expr.\n\n\n\n" -}, - -{ - "location": "stdlib/test.html#Other-Test-Macros-1", - "page": "Unit Testing", - "title": "Other Test Macros", - "category": "section", - "text": "As calculations on floating-point values can be imprecise, you can perform approximate equality checks using either @test a ≈ b (where ≈, typed via tab completion of \\approx, is the isapprox() function) or use isapprox() directly.julia> @test 1 ≈ 0.999999999\nTest Passed\n\njulia> @test 1 ≈ 0.999999\nTest Failed\n Expression: 1 ≈ 0.999999\n Evaluated: 1 ≈ 0.999999\nERROR: There was an error during testingBase.Test.@inferred\nBase.Test.@test_warn\nBase.Test.@test_nowarn" -}, - -{ - "location": "stdlib/test.html#Base.Test.@test_broken", - "page": "Unit Testing", - "title": "Base.Test.@test_broken", - "category": "macro", - "text": "@test_broken ex\n@test_broken f(args...) key=val ...\n\nIndicates a test that should pass but currently consistently fails. Tests that the expression ex evaluates to false or causes an exception. Returns a Broken Result if it does, or an Error Result if the expression evaluates to true.\n\nThe @test_broken f(args...) key=val... form works as for the @test macro.\n\n\n\n" -}, - -{ - "location": "stdlib/test.html#Base.Test.@test_skip", - "page": "Unit Testing", - "title": "Base.Test.@test_skip", - "category": "macro", - "text": "@test_skip ex\n@test_skip f(args...) key=val ...\n\nMarks a test that should not be executed but should be included in test summary reporting as Broken. This can be useful for tests that intermittently fail, or tests of not-yet-implemented functionality.\n\nThe @test_skip f(args...) key=val... form works as for the @test macro.\n\n\n\n" -}, - -{ - "location": "stdlib/test.html#Broken-Tests-1", - "page": "Unit Testing", - "title": "Broken Tests", - "category": "section", - "text": "If a test fails consistently it can be changed to use the @test_broken() macro. This will denote the test as Broken if the test continues to fail and alerts the user via an Error if the test succeeds.Base.Test.@test_broken@test_skip() is also available to skip a test without evaluation, but counting the skipped test in the test set reporting. The test will not run but gives a Broken Result.Base.Test.@test_skip" -}, - -{ - "location": "stdlib/test.html#Base.Test.record", - "page": "Unit Testing", - "title": "Base.Test.record", - "category": "function", - "text": "record(ts::AbstractTestSet, res::Result)\n\nRecord a result to a testset. This function is called by the @testset infrastructure each time a contained @test macro completes, and is given the test result (which could be an Error). This will also be called with an Error if an exception is thrown inside the test block but outside of a @test context.\n\n\n\n" -}, - -{ - "location": "stdlib/test.html#Base.Test.finish", - "page": "Unit Testing", - "title": "Base.Test.finish", - "category": "function", - "text": "finish(ts::AbstractTestSet)\n\nDo any final processing necessary for the given testset. This is called by the @testset infrastructure after a test block executes. One common use for this function is to record the testset to the parent\'s results list, using get_testset.\n\n\n\n" -}, - -{ - "location": "stdlib/test.html#Base.Test.get_testset", - "page": "Unit Testing", - "title": "Base.Test.get_testset", - "category": "function", - "text": "get_testset()\n\nRetrieve the active test set from the task\'s local storage. If no test set is active, use the fallback default test set.\n\n\n\n" -}, - -{ - "location": "stdlib/test.html#Base.Test.get_testset_depth", - "page": "Unit Testing", - "title": "Base.Test.get_testset_depth", - "category": "function", - "text": "get_testset_depth()\n\nReturns the number of active test sets, not including the defaut test set\n\n\n\n" -}, - -{ - "location": "stdlib/test.html#Creating-Custom-AbstractTestSet-Types-1", - "page": "Unit Testing", - "title": "Creating Custom AbstractTestSet Types", - "category": "section", - "text": "Packages can create their own AbstractTestSet subtypes by implementing the record and finish methods. The subtype should have a one-argument constructor taking a description string, with any options passed in as keyword arguments.Base.Test.record\nBase.Test.finishBase.Test takes responsibility for maintaining a stack of nested testsets as they are executed, but any result accumulation is the responsibility of the AbstractTestSet subtype. You can access this stack with the get_testset and get_testset_depth methods. Note that these functions are not exported.Base.Test.get_testset\nBase.Test.get_testset_depthBase.Test also makes sure that nested @testset invocations use the same AbstractTestSet subtype as their parent unless it is set explicitly. It does not propagate any properties of the testset. Option inheritance behavior can be implemented by packages using the stack infrastructure that Base.Test provides.Defining a basic AbstractTestSet subtype might look like:import Base.Test: record, finish\nusing Base.Test: AbstractTestSet, Result, Pass, Fail, Error\nusing Base.Test: get_testset_depth, get_testset\nstruct CustomTestSet <: Base.Test.AbstractTestSet\n description::AbstractString\n foo::Int\n results::Vector\n # constructor takes a description string and options keyword arguments\n CustomTestSet(desc; foo=1) = new(desc, foo, [])\nend\n\nrecord(ts::CustomTestSet, child::AbstractTestSet) = push!(ts.results, child)\nrecord(ts::CustomTestSet, res::Result) = push!(ts.results, res)\nfunction finish(ts::CustomTestSet)\n # just record if we\'re not the top-level parent\n if get_testset_depth() > 0\n record(get_testset(), ts)\n end\n ts\nendAnd using that testset looks like:@testset CustomTestSet foo=4 \"custom testset inner 2\" begin\n # this testset should inherit the type, but not the argument.\n @testset \"custom testset inner\" begin\n @test true\n end\nendDocTestSetup = nothing" -}, - -{ - "location": "stdlib/c.html#", - "page": "C Interface", - "title": "C Interface", - "category": "page", - "text": "" -}, - -{ - "location": "stdlib/c.html#ccall", - "page": "C Interface", - "title": "ccall", - "category": "keyword", - "text": "ccall((symbol, library) or function_pointer, ReturnType, (ArgumentType1, ...), ArgumentValue1, ...)\n\nCall function in C-exported shared library, specified by (function name, library) tuple, where each component is a string or symbol.\n\nNote that the argument type tuple must be a literal tuple, and not a tuple-valued variable or expression. Alternatively, ccall may also be used to call a function pointer, such as one returned by dlsym.\n\nEach ArgumentValue to the ccall will be converted to the corresponding ArgumentType, by automatic insertion of calls to unsafe_convert(ArgumentType, cconvert(ArgumentType, ArgumentValue)). (See also the documentation for each of these functions for further details.) In most cases, this simply results in a call to convert(ArgumentType, ArgumentValue).\n\n\n\n" -}, - -{ - "location": "stdlib/c.html#Core.Intrinsics.cglobal", - "page": "C Interface", - "title": "Core.Intrinsics.cglobal", - "category": "function", - "text": "cglobal((symbol, library) [, type=Void])\n\nObtain a pointer to a global variable in a C-exported shared library, specified exactly as in ccall. Returns a Ptr{Type}, defaulting to Ptr{Void} if no Type argument is supplied. The values can be read or written by unsafe_load or unsafe_store!, respectively.\n\n\n\n" -}, - -{ - "location": "stdlib/c.html#Base.cfunction", - "page": "C Interface", - "title": "Base.cfunction", - "category": "function", - "text": "cfunction(function::Function, ReturnType::Type, ArgumentTypes::Type)\n\nGenerate C-callable function pointer from Julia function. Type annotation of the return value in the callback function is a must for situations where Julia cannot infer the return type automatically.\n\nExamples\n\njulia> function foo(x::Int, y::Int)\n return x + y\n end\n\njulia> cfunction(foo, Int, Tuple{Int,Int})\nPtr{Void} @0x000000001b82fcd0\n\n\n\n" -}, - -{ - "location": "stdlib/c.html#Base.unsafe_convert", - "page": "C Interface", - "title": "Base.unsafe_convert", - "category": "function", - "text": "unsafe_convert(T,x)\n\nConvert x to a value of type T\n\nIn cases where convert would need to take a Julia object and turn it into a Ptr, this function should be used to define and perform that conversion.\n\nBe careful to ensure that a Julia reference to x exists as long as the result of this function will be used. Accordingly, the argument x to this function should never be an expression, only a variable name or field reference. For example, x=a.b.c is acceptable, but x=[a,b,c] is not.\n\nThe unsafe prefix on this function indicates that using the result of this function after the x argument to this function is no longer accessible to the program may cause undefined behavior, including program corruption or segfaults, at any later time.\n\n\n\n" -}, - -{ - "location": "stdlib/c.html#Base.cconvert", - "page": "C Interface", - "title": "Base.cconvert", - "category": "function", - "text": "cconvert(T,x)\n\nConvert x to a value of type T, typically by calling convert(T,x)\n\nIn cases where x cannot be safely converted to T, unlike convert, cconvert may return an object of a type different from T, which however is suitable for unsafe_convert to handle.\n\nNeither convert nor cconvert should take a Julia object and turn it into a Ptr.\n\n\n\n" -}, - -{ - "location": "stdlib/c.html#Base.unsafe_load", - "page": "C Interface", - "title": "Base.unsafe_load", - "category": "function", - "text": "unsafe_load(p::Ptr{T}, i::Integer=1)\n\nLoad a value of type T from the address of the ith element (1-indexed) starting at p. This is equivalent to the C expression p[i-1].\n\nThe unsafe prefix on this function indicates that no validation is performed on the pointer p to ensure that it is valid. Incorrect usage may segfault your program or return garbage answers, in the same manner as C.\n\n\n\n" -}, - -{ - "location": "stdlib/c.html#Base.unsafe_store!", - "page": "C Interface", - "title": "Base.unsafe_store!", - "category": "function", - "text": "unsafe_store!(p::Ptr{T}, x, i::Integer=1)\n\nStore a value of type T to the address of the ith element (1-indexed) starting at p. This is equivalent to the C expression p[i-1] = x.\n\nThe unsafe prefix on this function indicates that no validation is performed on the pointer p to ensure that it is valid. Incorrect usage may corrupt or segfault your program, in the same manner as C.\n\n\n\n" -}, - -{ - "location": "stdlib/c.html#Base.unsafe_copy!-Union{Tuple{Ptr{T},Ptr{T},Any}, Tuple{T}} where T", - "page": "C Interface", - "title": "Base.unsafe_copy!", - "category": "method", - "text": "unsafe_copy!(dest::Ptr{T}, src::Ptr{T}, N)\n\nCopy N elements from a source pointer to a destination, with no checking. The size of an element is determined by the type of the pointers.\n\nThe unsafe prefix on this function indicates that no validation is performed on the pointers dest and src to ensure that they are valid. Incorrect usage may corrupt or segfault your program, in the same manner as C.\n\n\n\n" -}, - -{ - "location": "stdlib/c.html#Base.unsafe_copy!-Tuple{Array,Any,Array,Any,Any}", - "page": "C Interface", - "title": "Base.unsafe_copy!", - "category": "method", - "text": "unsafe_copy!(dest::Array, do, src::Array, so, N)\n\nCopy N elements from a source array to a destination, starting at offset so in the source and do in the destination (1-indexed).\n\nThe unsafe prefix on this function indicates that no validation is performed to ensure that N is inbounds on either array. Incorrect usage may corrupt or segfault your program, in the same manner as C.\n\n\n\n" -}, - -{ - "location": "stdlib/c.html#Base.copy!-Tuple{Any,Any}", - "page": "C Interface", - "title": "Base.copy!", - "category": "method", - "text": "copy!(dest, src) -> dest\n\nCopy all elements from collection src to array dest.\n\n\n\n" -}, - -{ - "location": "stdlib/c.html#Base.copy!-NTuple{5,Any}", - "page": "C Interface", - "title": "Base.copy!", - "category": "method", - "text": "copy!(dest, do, src, so, N)\n\nCopy N elements from collection src starting at offset so, to array dest starting at offset do. Returns dest.\n\n\n\n" -}, - -{ - "location": "stdlib/c.html#Base.pointer", - "page": "C Interface", - "title": "Base.pointer", - "category": "function", - "text": "pointer(array [, index])\n\nGet the native address of an array or string element. Be careful to ensure that a Julia reference to a exists as long as this pointer will be used. This function is \"unsafe\" like unsafe_convert.\n\nCalling Ref(array[, index]) is generally preferable to this function.\n\n\n\n" -}, - -{ - "location": "stdlib/c.html#Base.unsafe_wrap-Union{Tuple{N}, Tuple{T}, Tuple{Union{Type{Array{T,N} where N}, Type{Array{T,N}}, Type{Array}},Ptr{T},Tuple{Vararg{Int64,N}}}} where N where T", - "page": "C Interface", - "title": "Base.unsafe_wrap", - "category": "method", - "text": "unsafe_wrap(Array, pointer::Ptr{T}, dims, own=false)\n\nWrap a Julia Array object around the data at the address given by pointer, without making a copy. The pointer element type T determines the array element type. dims is either an integer (for a 1d array) or a tuple of the array dimensions. own optionally specifies whether Julia should take ownership of the memory, calling free on the pointer when the array is no longer referenced.\n\nThis function is labelled \"unsafe\" because it will crash if pointer is not a valid memory address to data of the requested length.\n\n\n\n" -}, - -{ - "location": "stdlib/c.html#Base.pointer_from_objref", - "page": "C Interface", - "title": "Base.pointer_from_objref", - "category": "function", - "text": "pointer_from_objref(x)\n\nGet the memory address of a Julia object as a Ptr. The existence of the resulting Ptr will not protect the object from garbage collection, so you must ensure that the object remains referenced for the whole time that the Ptr will be used.\n\n\n\n" -}, - -{ - "location": "stdlib/c.html#Base.unsafe_pointer_to_objref", - "page": "C Interface", - "title": "Base.unsafe_pointer_to_objref", - "category": "function", - "text": "unsafe_pointer_to_objref(p::Ptr)\n\nConvert a Ptr to an object reference. Assumes the pointer refers to a valid heap-allocated Julia object. If this is not the case, undefined behavior results, hence this function is considered \"unsafe\" and should be used with care.\n\n\n\n" -}, - -{ - "location": "stdlib/c.html#Base.disable_sigint", - "page": "C Interface", - "title": "Base.disable_sigint", - "category": "function", - "text": "disable_sigint(f::Function)\n\nDisable Ctrl-C handler during execution of a function on the current task, for calling external code that may call julia code that is not interrupt safe. Intended to be called using do block syntax as follows:\n\ndisable_sigint() do\n # interrupt-unsafe code\n ...\nend\n\nThis is not needed on worker threads (Threads.threadid() != 1) since the InterruptException will only be delivered to the master thread. External functions that do not call julia code or julia runtime automatically disable sigint during their execution.\n\n\n\n" -}, - -{ - "location": "stdlib/c.html#Base.reenable_sigint", - "page": "C Interface", - "title": "Base.reenable_sigint", - "category": "function", - "text": "reenable_sigint(f::Function)\n\nRe-enable Ctrl-C handler during execution of a function. Temporarily reverses the effect of disable_sigint.\n\n\n\n" -}, - -{ - "location": "stdlib/c.html#Base.systemerror", - "page": "C Interface", - "title": "Base.systemerror", - "category": "function", - "text": "systemerror(sysfunc, iftrue)\n\nRaises a SystemError for errno with the descriptive string sysfunc if iftrue is true\n\n\n\n" -}, - -{ - "location": "stdlib/c.html#Core.Ptr", - "page": "C Interface", - "title": "Core.Ptr", - "category": "type", - "text": "Ptr{T}\n\nA memory address referring to data of type T. However, there is no guarantee that the memory is actually valid, or that it actually represents data of the specified type.\n\n\n\n" -}, - -{ - "location": "stdlib/c.html#Core.Ref", - "page": "C Interface", - "title": "Core.Ref", - "category": "type", - "text": "Ref{T}\n\nAn object that safely references data of type T. This type is guaranteed to point to valid, Julia-allocated memory of the correct type. The underlying data is protected from freeing by the garbage collector as long as the Ref itself is referenced.\n\nWhen passed as a ccall argument (either as a Ptr or Ref type), a Ref object will be converted to a native pointer to the data it references.\n\nThere is no invalid (NULL) Ref.\n\n\n\n" -}, - -{ - "location": "stdlib/c.html#Base.Cchar", - "page": "C Interface", - "title": "Base.Cchar", - "category": "type", - "text": "Cchar\n\nEquivalent to the native char c-type.\n\n\n\n" -}, - -{ - "location": "stdlib/c.html#Base.Cuchar", - "page": "C Interface", - "title": "Base.Cuchar", - "category": "type", - "text": "Cuchar\n\nEquivalent to the native unsigned char c-type (UInt8).\n\n\n\n" -}, - -{ - "location": "stdlib/c.html#Base.Cshort", - "page": "C Interface", - "title": "Base.Cshort", - "category": "type", - "text": "Cshort\n\nEquivalent to the native signed short c-type (Int16).\n\n\n\n" -}, - -{ - "location": "stdlib/c.html#Base.Cushort", - "page": "C Interface", - "title": "Base.Cushort", - "category": "type", - "text": "Cushort\n\nEquivalent to the native unsigned short c-type (UInt16).\n\n\n\n" -}, - -{ - "location": "stdlib/c.html#Base.Cint", - "page": "C Interface", - "title": "Base.Cint", - "category": "type", - "text": "Cint\n\nEquivalent to the native signed int c-type (Int32).\n\n\n\n" -}, - -{ - "location": "stdlib/c.html#Base.Cuint", - "page": "C Interface", - "title": "Base.Cuint", - "category": "type", - "text": "Cuint\n\nEquivalent to the native unsigned int c-type (UInt32).\n\n\n\n" -}, - -{ - "location": "stdlib/c.html#Base.Clong", - "page": "C Interface", - "title": "Base.Clong", - "category": "type", - "text": "Clong\n\nEquivalent to the native signed long c-type.\n\n\n\n" -}, - -{ - "location": "stdlib/c.html#Base.Culong", - "page": "C Interface", - "title": "Base.Culong", - "category": "type", - "text": "Culong\n\nEquivalent to the native unsigned long c-type.\n\n\n\n" -}, - -{ - "location": "stdlib/c.html#Base.Clonglong", - "page": "C Interface", - "title": "Base.Clonglong", - "category": "type", - "text": "Clonglong\n\nEquivalent to the native signed long long c-type (Int64).\n\n\n\n" -}, - -{ - "location": "stdlib/c.html#Base.Culonglong", - "page": "C Interface", - "title": "Base.Culonglong", - "category": "type", - "text": "Culonglong\n\nEquivalent to the native unsigned long long c-type (UInt64).\n\n\n\n" -}, - -{ - "location": "stdlib/c.html#Base.Cintmax_t", - "page": "C Interface", - "title": "Base.Cintmax_t", - "category": "type", - "text": "Cintmax_t\n\nEquivalent to the native intmax_t c-type (Int64).\n\n\n\n" -}, - -{ - "location": "stdlib/c.html#Base.Cuintmax_t", - "page": "C Interface", - "title": "Base.Cuintmax_t", - "category": "type", - "text": "Cuintmax_t\n\nEquivalent to the native uintmax_t c-type (UInt64).\n\n\n\n" -}, - -{ - "location": "stdlib/c.html#Base.Csize_t", - "page": "C Interface", - "title": "Base.Csize_t", - "category": "type", - "text": "Csize_t\n\nEquivalent to the native size_t c-type (UInt).\n\n\n\n" -}, - -{ - "location": "stdlib/c.html#Base.Cssize_t", - "page": "C Interface", - "title": "Base.Cssize_t", - "category": "type", - "text": "Cssize_t\n\nEquivalent to the native ssize_t c-type.\n\n\n\n" -}, - -{ - "location": "stdlib/c.html#Base.Cptrdiff_t", - "page": "C Interface", - "title": "Base.Cptrdiff_t", - "category": "type", - "text": "Cptrdiff_t\n\nEquivalent to the native ptrdiff_t c-type (Int).\n\n\n\n" -}, - -{ - "location": "stdlib/c.html#Base.Cwchar_t", - "page": "C Interface", - "title": "Base.Cwchar_t", - "category": "type", - "text": "Cwchar_t\n\nEquivalent to the native wchar_t c-type (Int32).\n\n\n\n" -}, - -{ - "location": "stdlib/c.html#Base.Cfloat", - "page": "C Interface", - "title": "Base.Cfloat", - "category": "type", - "text": "Cfloat\n\nEquivalent to the native float c-type (Float32).\n\n\n\n" -}, - -{ - "location": "stdlib/c.html#Base.Cdouble", - "page": "C Interface", - "title": "Base.Cdouble", - "category": "type", - "text": "Cdouble\n\nEquivalent to the native double c-type (Float64).\n\n\n\n" -}, - -{ - "location": "stdlib/c.html#C-Interface-1", - "page": "C Interface", - "title": "C Interface", - "category": "section", - "text": "ccall\nCore.Intrinsics.cglobal\nBase.cfunction\nBase.unsafe_convert\nBase.cconvert\nBase.unsafe_load\nBase.unsafe_store!\nBase.unsafe_copy!{T}(::Ptr{T}, ::Ptr{T}, ::Any)\nBase.unsafe_copy!(::Array, ::Any, ::Array, ::Any, ::Any)\nBase.copy!(::Any, ::Any)\nBase.copy!(::Any, ::Any, ::Any, ::Any, ::Any)\nBase.pointer\nBase.unsafe_wrap{T,N}(::Union{Type{Array},Type{Array{T}},Type{Array{T,N}}}, ::Ptr{T}, ::NTuple{N,Int})\nBase.pointer_from_objref\nBase.unsafe_pointer_to_objref\nBase.disable_sigint\nBase.reenable_sigint\nBase.systemerror\nCore.Ptr\nCore.Ref\nBase.Cchar\nBase.Cuchar\nBase.Cshort\nBase.Cushort\nBase.Cint\nBase.Cuint\nBase.Clong\nBase.Culong\nBase.Clonglong\nBase.Culonglong\nBase.Cintmax_t\nBase.Cuintmax_t\nBase.Csize_t\nBase.Cssize_t\nBase.Cptrdiff_t\nBase.Cwchar_t\nBase.Cfloat\nBase.Cdouble" -}, - -{ - "location": "stdlib/c.html#Core.Intrinsics.llvmcall", - "page": "C Interface", - "title": "Core.Intrinsics.llvmcall", - "category": "function", - "text": "llvmcall(IR::String, ReturnType, (ArgumentType1, ...), ArgumentValue1, ...)\nllvmcall((declarations::String, IR::String), ReturnType, (ArgumentType1, ...), ArgumentValue1, ...)\n\nCall LLVM IR string in the first argument. Similar to an LLVM function define block, arguments are available as consecutive unnamed SSA variables (%0, %1, etc.).\n\nThe optional declarations string contains external functions declarations that are necessary for llvm to compile the IR string. Multiple declarations can be passed in by separating them with line breaks.\n\nNote that the argument type tuple must be a literal tuple, and not a tuple-valued variable or expression.\n\nEach ArgumentValue to llvmcall will be converted to the corresponding ArgumentType, by automatic insertion of calls to unsafe_convert(ArgumentType, cconvert(ArgumentType, ArgumentValue)). (see also the documentation for each of these functions for further details). In most cases, this simply results in a call to convert(ArgumentType, ArgumentValue).\n\nSee test/llvmcall.jl for usage examples.\n\n\n\n" -}, - -{ - "location": "stdlib/c.html#LLVM-Interface-1", - "page": "C Interface", - "title": "LLVM Interface", - "category": "section", - "text": "Core.Intrinsics.llvmcall" -}, - -{ - "location": "stdlib/libc.html#", - "page": "C Standard Library", - "title": "C Standard Library", - "category": "page", - "text": "" -}, - -{ - "location": "stdlib/libc.html#Base.Libc.malloc", - "page": "C Standard Library", - "title": "Base.Libc.malloc", - "category": "function", - "text": "malloc(size::Integer) -> Ptr{Void}\n\nCall malloc from the C standard library.\n\n\n\n" -}, - -{ - "location": "stdlib/libc.html#Base.Libc.calloc", - "page": "C Standard Library", - "title": "Base.Libc.calloc", - "category": "function", - "text": "calloc(num::Integer, size::Integer) -> Ptr{Void}\n\nCall calloc from the C standard library.\n\n\n\n" -}, - -{ - "location": "stdlib/libc.html#Base.Libc.realloc", - "page": "C Standard Library", - "title": "Base.Libc.realloc", - "category": "function", - "text": "realloc(addr::Ptr, size::Integer) -> Ptr{Void}\n\nCall realloc from the C standard library.\n\nSee warning in the documentation for free regarding only using this on memory originally obtained from malloc.\n\n\n\n" -}, - -{ - "location": "stdlib/libc.html#Base.Libc.free", - "page": "C Standard Library", - "title": "Base.Libc.free", - "category": "function", - "text": "free(addr::Ptr)\n\nCall free from the C standard library. Only use this on memory obtained from malloc, not on pointers retrieved from other C libraries. Ptr objects obtained from C libraries should be freed by the free functions defined in that library, to avoid assertion failures if multiple libc libraries exist on the system.\n\n\n\n" -}, - -{ - "location": "stdlib/libc.html#Base.Libc.errno", - "page": "C Standard Library", - "title": "Base.Libc.errno", - "category": "function", - "text": "errno([code])\n\nGet the value of the C library\'s errno. If an argument is specified, it is used to set the value of errno.\n\nThe value of errno is only valid immediately after a ccall to a C library routine that sets it. Specifically, you cannot call errno at the next prompt in a REPL, because lots of code is executed between prompts.\n\n\n\n" -}, - -{ - "location": "stdlib/libc.html#Base.Libc.strerror", - "page": "C Standard Library", - "title": "Base.Libc.strerror", - "category": "function", - "text": "strerror(n=errno())\n\nConvert a system call error code to a descriptive string\n\n\n\n" -}, - -{ - "location": "stdlib/libc.html#Base.Libc.GetLastError", - "page": "C Standard Library", - "title": "Base.Libc.GetLastError", - "category": "function", - "text": "GetLastError()\n\nCall the Win32 GetLastError function [only available on Windows].\n\n\n\n" -}, - -{ - "location": "stdlib/libc.html#Base.Libc.FormatMessage", - "page": "C Standard Library", - "title": "Base.Libc.FormatMessage", - "category": "function", - "text": "FormatMessage(n=GetLastError())\n\nConvert a Win32 system call error code to a descriptive string [only available on Windows].\n\n\n\n" -}, - -{ - "location": "stdlib/libc.html#Base.Libc.time-Tuple{Base.Libc.TmStruct}", - "page": "C Standard Library", - "title": "Base.Libc.time", - "category": "method", - "text": "time(t::TmStruct)\n\nConverts a TmStruct struct to a number of seconds since the epoch.\n\n\n\n" -}, - -{ - "location": "stdlib/libc.html#Base.Libc.strftime", - "page": "C Standard Library", - "title": "Base.Libc.strftime", - "category": "function", - "text": "strftime([format], time)\n\nConvert time, given as a number of seconds since the epoch or a TmStruct, to a formatted string using the given format. Supported formats are the same as those in the standard C library.\n\n\n\n" -}, - -{ - "location": "stdlib/libc.html#Base.Libc.strptime", - "page": "C Standard Library", - "title": "Base.Libc.strptime", - "category": "function", - "text": "strptime([format], timestr)\n\nParse a formatted time string into a TmStruct giving the seconds, minute, hour, date, etc. Supported formats are the same as those in the standard C library. On some platforms, timezones will not be parsed correctly. If the result of this function will be passed to time to convert it to seconds since the epoch, the isdst field should be filled in manually. Setting it to -1 will tell the C library to use the current system settings to determine the timezone.\n\n\n\n" -}, - -{ - "location": "stdlib/libc.html#Base.Libc.TmStruct", - "page": "C Standard Library", - "title": "Base.Libc.TmStruct", - "category": "type", - "text": "TmStruct([seconds])\n\nConvert a number of seconds since the epoch to broken-down format, with fields sec, min, hour, mday, month, year, wday, yday, and isdst.\n\n\n\n" -}, - -{ - "location": "stdlib/libc.html#Base.Libc.flush_cstdio", - "page": "C Standard Library", - "title": "Base.Libc.flush_cstdio", - "category": "function", - "text": "flush_cstdio()\n\nFlushes the C stdout and stderr streams (which may have been written to by external C code).\n\n\n\n" -}, - -{ - "location": "stdlib/libc.html#C-Standard-Library-1", - "page": "C Standard Library", - "title": "C Standard Library", - "category": "section", - "text": "Base.Libc.malloc\nBase.Libc.calloc\nBase.Libc.realloc\nBase.Libc.free\nBase.Libc.errno\nBase.Libc.strerror\nBase.Libc.GetLastError\nBase.Libc.FormatMessage\nBase.Libc.time(::Base.Libc.TmStruct)\nBase.Libc.strftime\nBase.Libc.strptime\nBase.Libc.TmStruct\nBase.Libc.flush_cstdio" -}, - -{ - "location": "stdlib/libdl.html#", - "page": "Dynamic Linker", - "title": "Dynamic Linker", - "category": "page", - "text": "" -}, - -{ - "location": "stdlib/libdl.html#Base.Libdl.dlopen", - "page": "Dynamic Linker", - "title": "Base.Libdl.dlopen", - "category": "function", - "text": "dlopen(libfile::AbstractString [, flags::Integer])\n\nLoad a shared library, returning an opaque handle.\n\nThe extension given by the constant dlext (.so, .dll, or .dylib) can be omitted from the libfile string, as it is automatically appended if needed. If libfile is not an absolute path name, then the paths in the array DL_LOAD_PATH are searched for libfile, followed by the system load path.\n\nThe optional flags argument is a bitwise-or of zero or more of RTLD_LOCAL, RTLD_GLOBAL, RTLD_LAZY, RTLD_NOW, RTLD_NODELETE, RTLD_NOLOAD, RTLD_DEEPBIND, and RTLD_FIRST. These are converted to the corresponding flags of the POSIX (and/or GNU libc and/or MacOS) dlopen command, if possible, or are ignored if the specified functionality is not available on the current platform. The default flags are platform specific. On MacOS the default dlopen flags are RTLD_LAZY|RTLD_DEEPBIND|RTLD_GLOBAL while on other platforms the defaults are RTLD_LAZY|RTLD_DEEPBIND|RTLD_LOCAL. An important usage of these flags is to specify non default behavior for when the dynamic library loader binds library references to exported symbols and if the bound references are put into process local or global scope. For instance RTLD_LAZY|RTLD_DEEPBIND|RTLD_GLOBAL allows the library\'s symbols to be available for usage in other shared libraries, addressing situations where there are dependencies between shared libraries.\n\n\n\n" -}, - -{ - "location": "stdlib/libdl.html#Base.Libdl.dlopen_e", - "page": "Dynamic Linker", - "title": "Base.Libdl.dlopen_e", - "category": "function", - "text": "dlopen_e(libfile::AbstractString [, flags::Integer])\n\nSimilar to dlopen, except returns a NULL pointer instead of raising errors.\n\n\n\n" -}, - -{ - "location": "stdlib/libdl.html#Base.Libdl.RTLD_NOW", - "page": "Dynamic Linker", - "title": "Base.Libdl.RTLD_NOW", - "category": "constant", - "text": "RTLD_DEEPBIND\nRTLD_FIRST\nRTLD_GLOBAL\nRTLD_LAZY\nRTLD_LOCAL\nRTLD_NODELETE\nRTLD_NOLOAD\nRTLD_NOW\n\nEnum constant for dlopen. See your platform man page for details, if applicable.\n\n\n\n" -}, - -{ - "location": "stdlib/libdl.html#Base.Libdl.dlsym", - "page": "Dynamic Linker", - "title": "Base.Libdl.dlsym", - "category": "function", - "text": "dlsym(handle, sym)\n\nLook up a symbol from a shared library handle, return callable function pointer on success.\n\n\n\n" -}, - -{ - "location": "stdlib/libdl.html#Base.Libdl.dlsym_e", - "page": "Dynamic Linker", - "title": "Base.Libdl.dlsym_e", - "category": "function", - "text": "dlsym_e(handle, sym)\n\nLook up a symbol from a shared library handle, silently return NULL pointer on lookup failure.\n\n\n\n" -}, - -{ - "location": "stdlib/libdl.html#Base.Libdl.dlclose", - "page": "Dynamic Linker", - "title": "Base.Libdl.dlclose", - "category": "function", - "text": "dlclose(handle)\n\nClose shared library referenced by handle.\n\n\n\n" -}, - -{ - "location": "stdlib/libdl.html#Base.Libdl.dlext", - "page": "Dynamic Linker", - "title": "Base.Libdl.dlext", - "category": "constant", - "text": "dlext\n\nFile extension for dynamic libraries (e.g. dll, dylib, so) on the current platform.\n\n\n\n" -}, - -{ - "location": "stdlib/libdl.html#Base.Libdl.find_library", - "page": "Dynamic Linker", - "title": "Base.Libdl.find_library", - "category": "function", - "text": "find_library(names, locations)\n\nSearches for the first library in names in the paths in the locations list, DL_LOAD_PATH, or system library paths (in that order) which can successfully be dlopen\'d. On success, the return value will be one of the names (potentially prefixed by one of the paths in locations). This string can be assigned to a global const and used as the library name in future ccall\'s. On failure, it returns the empty string.\n\n\n\n" -}, - -{ - "location": "stdlib/libdl.html#Base.Libdl.DL_LOAD_PATH", - "page": "Dynamic Linker", - "title": "Base.Libdl.DL_LOAD_PATH", - "category": "constant", - "text": "DL_LOAD_PATH\n\nWhen calling dlopen, the paths in this list will be searched first, in order, before searching the system locations for a valid library handle.\n\n\n\n" -}, - -{ - "location": "stdlib/libdl.html#Dynamic-Linker-1", - "page": "Dynamic Linker", - "title": "Dynamic Linker", - "category": "section", - "text": "The names in Base.Libdl are not exported and need to be called e.g. as Libdl.dlopen().Base.Libdl.dlopen\nBase.Libdl.dlopen_e\nBase.Libdl.RTLD_NOW\nBase.Libdl.dlsym\nBase.Libdl.dlsym_e\nBase.Libdl.dlclose\nBase.Libdl.dlext\nBase.Libdl.find_library\nBase.Libdl.DL_LOAD_PATH" -}, - -{ - "location": "stdlib/profile.html#", - "page": "Profiling", - "title": "Profiling", - "category": "page", - "text": "" -}, - -{ - "location": "stdlib/profile.html#Base.Profile.@profile", - "page": "Profiling", - "title": "Base.Profile.@profile", - "category": "macro", - "text": "@profile\n\n@profile runs your expression while taking periodic backtraces. These are appended to an internal buffer of backtraces.\n\n\n\n" -}, - -{ - "location": "stdlib/profile.html#Base.Profile.clear", - "page": "Profiling", - "title": "Base.Profile.clear", - "category": "function", - "text": "clear()\n\nClear any existing backtraces from the internal buffer.\n\n\n\n" -}, - -{ - "location": "stdlib/profile.html#Base.Profile.print", - "page": "Profiling", - "title": "Base.Profile.print", - "category": "function", - "text": "print([io::IO = STDOUT,] [data::Vector]; kwargs...)\n\nPrints profiling results to io (by default, STDOUT). If you do not supply a data vector, the internal buffer of accumulated backtraces will be used.\n\nThe keyword arguments can be any combination of:\n\nformat – Determines whether backtraces are printed with (default, :tree) or without (:flat) indentation indicating tree structure.\nC – If true, backtraces from C and Fortran code are shown (normally they are excluded).\ncombine – If true (default), instruction pointers are merged that correspond to the same line of code.\nmaxdepth – Limits the depth higher than maxdepth in the :tree format.\nsortedby – Controls the order in :flat format. :filefuncline (default) sorts by the source line, whereas :count sorts in order of number of collected samples.\nnoisefloor – Limits frames that exceed the heuristic noise floor of the sample (only applies to format :tree). A suggested value to try for this is 2.0 (the default is 0). This parameter hides samples for which n <= noisefloor * √N, where n is the number of samples on this line, and N is the number of samples for the callee.\nmincount – Limits the printout to only those lines with at least mincount occurrences.\n\n\n\nprint([io::IO = STDOUT,] data::Vector, lidict::LineInfoDict; kwargs...)\n\nPrints profiling results to io. This variant is used to examine results exported by a previous call to retrieve. Supply the vector data of backtraces and a dictionary lidict of line information.\n\nSee Profile.print([io], data) for an explanation of the valid keyword arguments.\n\n\n\n" -}, - -{ - "location": "stdlib/profile.html#Base.Profile.init", - "page": "Profiling", - "title": "Base.Profile.init", - "category": "function", - "text": "init(; n::Integer, delay::Float64)\n\nConfigure the delay between backtraces (measured in seconds), and the number n of instruction pointers that may be stored. Each instruction pointer corresponds to a single line of code; backtraces generally consist of a long list of instruction pointers. Default settings can be obtained by calling this function with no arguments, and each can be set independently using keywords or in the order (n, delay).\n\n\n\n" -}, - -{ - "location": "stdlib/profile.html#Base.Profile.fetch", - "page": "Profiling", - "title": "Base.Profile.fetch", - "category": "function", - "text": "fetch() -> data\n\nReturns a reference to the internal buffer of backtraces. Note that subsequent operations, like clear, can affect data unless you first make a copy. Note that the values in data have meaning only on this machine in the current session, because it depends on the exact memory addresses used in JIT-compiling. This function is primarily for internal use; retrieve may be a better choice for most users.\n\n\n\n" -}, - -{ - "location": "stdlib/profile.html#Base.Profile.retrieve", - "page": "Profiling", - "title": "Base.Profile.retrieve", - "category": "function", - "text": "retrieve() -> data, lidict\n\n\"Exports\" profiling results in a portable format, returning the set of all backtraces (data) and a dictionary that maps the (session-specific) instruction pointers in data to LineInfo values that store the file name, function name, and line number. This function allows you to save profiling results for future analysis.\n\n\n\n" -}, - -{ - "location": "stdlib/profile.html#Base.Profile.callers", - "page": "Profiling", - "title": "Base.Profile.callers", - "category": "function", - "text": "callers(funcname, [data, lidict], [filename=], [linerange=]) -> Vector{Tuple{count, lineinfo}}\n\nGiven a previous profiling run, determine who called a particular function. Supplying the filename (and optionally, range of line numbers over which the function is defined) allows you to disambiguate an overloaded method. The returned value is a vector containing a count of the number of calls and line information about the caller. One can optionally supply backtrace data obtained from retrieve; otherwise, the current internal profile buffer is used.\n\n\n\n" -}, - -{ - "location": "stdlib/profile.html#Base.Profile.clear_malloc_data", - "page": "Profiling", - "title": "Base.Profile.clear_malloc_data", - "category": "function", - "text": "clear_malloc_data()\n\nClears any stored memory allocation data when running julia with --track-allocation. Execute the command(s) you want to test (to force JIT-compilation), then call clear_malloc_data. Then execute your command(s) again, quit Julia, and examine the resulting *.mem files.\n\n\n\n" -}, - -{ - "location": "stdlib/profile.html#lib-profiling-1", - "page": "Profiling", - "title": "Profiling", - "category": "section", - "text": "Base.Profile.@profileThe methods in Base.Profile are not exported and need to be called e.g. as Profile.print().Base.Profile.clear\nBase.Profile.print\nBase.Profile.init\nBase.Profile.fetch\nBase.Profile.retrieve\nBase.Profile.callers\nBase.Profile.clear_malloc_data" -}, - -{ - "location": "stdlib/stacktraces.html#", - "page": "StackTraces", - "title": "StackTraces", - "category": "page", - "text": "" -}, - -{ - "location": "stdlib/stacktraces.html#Base.StackTraces.StackFrame", - "page": "StackTraces", - "title": "Base.StackTraces.StackFrame", - "category": "type", - "text": "StackFrame\n\nStack information representing execution context, with the following fields:\n\nfunc::Symbol\nThe name of the function containing the execution context.\nlinfo::Nullable{Core.MethodInstance}\nThe MethodInstance containing the execution context (if it could be found).\nfile::Symbol\nThe path to the file containing the execution context.\nline::Int\nThe line number in the file containing the execution context.\nfrom_c::Bool\nTrue if the code is from C.\ninlined::Bool\nTrue if the code is from an inlined frame.\npointer::UInt64\nRepresentation of the pointer to the execution context as returned by backtrace.\n\n\n\n" -}, - -{ - "location": "stdlib/stacktraces.html#Base.StackTraces.StackTrace", - "page": "StackTraces", - "title": "Base.StackTraces.StackTrace", - "category": "type", - "text": "StackTrace\n\nAn alias for Vector{StackFrame} provided for convenience; returned by calls to stacktrace and catch_stacktrace.\n\n\n\n" -}, - -{ - "location": "stdlib/stacktraces.html#Base.StackTraces.stacktrace", - "page": "StackTraces", - "title": "Base.StackTraces.stacktrace", - "category": "function", - "text": "stacktrace([trace::Vector{Ptr{Void}},] [c_funcs::Bool=false]) -> StackTrace\n\nReturns a stack trace in the form of a vector of StackFrames. (By default stacktrace doesn\'t return C functions, but this can be enabled.) When called without specifying a trace, stacktrace first calls backtrace.\n\n\n\n" -}, - -{ - "location": "stdlib/stacktraces.html#Base.StackTraces.catch_stacktrace", - "page": "StackTraces", - "title": "Base.StackTraces.catch_stacktrace", - "category": "function", - "text": "catch_stacktrace([c_funcs::Bool=false]) -> StackTrace\n\nReturns the stack trace for the most recent error thrown, rather than the current execution context.\n\n\n\n" -}, - -{ - "location": "stdlib/stacktraces.html#Base.StackTraces.lookup", - "page": "StackTraces", - "title": "Base.StackTraces.lookup", - "category": "function", - "text": "lookup(pointer::Union{Ptr{Void}, UInt}) -> Vector{StackFrame}\n\nGiven a pointer to an execution context (usually generated by a call to backtrace), looks up stack frame context information. Returns an array of frame information for all functions inlined at that point, innermost function first.\n\n\n\n" -}, - -{ - "location": "stdlib/stacktraces.html#Base.StackTraces.remove_frames!", - "page": "StackTraces", - "title": "Base.StackTraces.remove_frames!", - "category": "function", - "text": "remove_frames!(stack::StackTrace, name::Symbol)\n\nTakes a StackTrace (a vector of StackFrames) and a function name (a Symbol) and removes the StackFrame specified by the function name from the StackTrace (also removing all frames above the specified function). Primarily used to remove StackTraces functions from the StackTrace prior to returning it.\n\n\n\nremove_frames!(stack::StackTrace, m::Module)\n\nReturns the StackTrace with all StackFrames from the provided Module removed.\n\n\n\n" -}, - -{ - "location": "stdlib/stacktraces.html#StackTraces-1", - "page": "StackTraces", - "title": "StackTraces", - "category": "section", - "text": "Base.StackTraces.StackFrame\nBase.StackTraces.StackTrace\nBase.StackTraces.stacktrace\nBase.StackTraces.catch_stacktraceThe following methods and types in Base.StackTraces are not exported and need to be called e.g. as StackTraces.lookup(ptr).Base.StackTraces.lookup\nBase.StackTraces.remove_frames!" -}, - -{ - "location": "stdlib/simd-types.html#", - "page": "SIMD Support", - "title": "SIMD Support", - "category": "page", - "text": "" -}, - -{ - "location": "stdlib/simd-types.html#SIMD-Support-1", - "page": "SIMD Support", - "title": "SIMD Support", - "category": "section", - "text": "Type VecElement{T} is intended for building libraries of SIMD operations. Practical use of it requires using llvmcall. The type is defined as:struct VecElement{T}\n value::T\nendIt has a special compilation rule: a homogeneous tuple of VecElement{T} maps to an LLVM vector type when T is a primitive bits type and the tuple length is in the set {2-6,8-10,16}.At -O3, the compiler might automatically vectorize operations on such tuples. For example, the following program, when compiled with julia -O3 generates two SIMD addition instructions (addps) on x86 systems:const m128 = NTuple{4,VecElement{Float32}}\n\nfunction add(a::m128, b::m128)\n (VecElement(a[1].value+b[1].value),\n VecElement(a[2].value+b[2].value),\n VecElement(a[3].value+b[3].value),\n VecElement(a[4].value+b[4].value))\nend\n\ntriple(c::m128) = add(add(c,c),c)\n\ncode_native(triple,(m128,))However, since the automatic vectorization cannot be relied upon, future use will mostly be via libraries that use llvmcall." -}, - -{ - "location": "devdocs/reflection.html#", - "page": "Reflection and introspection", - "title": "Reflection and introspection", - "category": "page", - "text": "" -}, - -{ - "location": "devdocs/reflection.html#Reflection-and-introspection-1", - "page": "Reflection and introspection", - "title": "Reflection and introspection", - "category": "section", - "text": "Julia provides a variety of runtime reflection capabilities." -}, - -{ - "location": "devdocs/reflection.html#Module-bindings-1", - "page": "Reflection and introspection", - "title": "Module bindings", - "category": "section", - "text": "The exported names for a Module are available using names(m::Module), which will return an array of Symbol elements representing the exported bindings. names(m::Module, true) returns symbols for all bindings in m, regardless of export status." -}, - -{ - "location": "devdocs/reflection.html#DataType-fields-1", - "page": "Reflection and introspection", - "title": "DataType fields", - "category": "section", - "text": "The names of DataType fields may be interrogated using fieldnames(). For example, given the following type, fieldnames(Point) returns an arrays of Symbol elements representing the field names:julia> struct Point\n x::Int\n y\n end\n\njulia> fieldnames(Point)\n2-element Array{Symbol,1}:\n :x\n :yThe type of each field in a Point object is stored in the types field of the Point variable itself:julia> Point.types\nsvec(Int64, Any)While x is annotated as an Int, y was unannotated in the type definition, therefore y defaults to the Any type.Types are themselves represented as a structure called DataType:julia> typeof(Point)\nDataTypeNote that fieldnames(DataType) gives the names for each field of DataType itself, and one of these fields is the types field observed in the example above." -}, - -{ - "location": "devdocs/reflection.html#Subtypes-1", - "page": "Reflection and introspection", - "title": "Subtypes", - "category": "section", - "text": "The direct subtypes of any DataType may be listed using subtypes(). For example, the abstract DataType AbstractFloat has four (concrete) subtypes:julia> subtypes(AbstractFloat)\n4-element Array{Union{DataType, UnionAll},1}:\n BigFloat\n Float16\n Float32\n Float64Any abstract subtype will also be included in this list, but further subtypes thereof will not; recursive application of subtypes() may be used to inspect the full type tree." -}, - -{ - "location": "devdocs/reflection.html#DataType-layout-1", - "page": "Reflection and introspection", - "title": "DataType layout", - "category": "section", - "text": "The internal representation of a DataType is critically important when interfacing with C code and several functions are available to inspect these details. isbits(T::DataType) returns true if T is stored with C-compatible alignment. fieldoffset(T::DataType, i::Integer) returns the (byte) offset for field i relative to the start of the type." -}, - -{ - "location": "devdocs/reflection.html#Function-methods-1", - "page": "Reflection and introspection", - "title": "Function methods", - "category": "section", - "text": "The methods of any generic function may be listed using methods(). The method dispatch table may be searched for methods accepting a given type using methodswith()." -}, - -{ - "location": "devdocs/reflection.html#Expansion-and-lowering-1", - "page": "Reflection and introspection", - "title": "Expansion and lowering", - "category": "section", - "text": "As discussed in the Metaprogramming section, the macroexpand() function gives the unquoted and interpolated expression (Expr) form for a given macro. To use macroexpand, quote the expression block itself (otherwise, the macro will be evaluated and the result will be passed instead!). For example:julia> macroexpand( :(@edit println(\"\")) )\n:((Base.edit)(println, (Base.typesof)(\"\")))The functions Base.Meta.show_sexpr() and dump() are used to display S-expr style views and depth-nested detail views for any expression.Finally, the expand() function gives the lowered form of any expression and is of particular interest for understanding both macros and top-level statements such as function declarations and variable assignments:julia> expand( :(f() = 1) )\n:(begin\n $(Expr(:method, :f))\n $(Expr(:method, :f, :((Core.svec)((Core.svec)((Core.Typeof)(f)), (Core.svec)())), CodeInfo(:(begin # none, line 1:\n return 1\n end)), false))\n return f\n end)" -}, - -{ - "location": "devdocs/reflection.html#Intermediate-and-compiled-representations-1", - "page": "Reflection and introspection", - "title": "Intermediate and compiled representations", - "category": "section", - "text": "Inspecting the lowered form for functions requires selection of the specific method to display, because generic functions may have many methods with different type signatures. For this purpose, method-specific code-lowering is available using code_lowered(f::Function, (Argtypes...)), and the type-inferred form is available using code_typed(f::Function, (Argtypes...)). code_warntype(f::Function, (Argtypes...)) adds highlighting to the output of code_typed() (see @code_warntype).Closer to the machine, the LLVM intermediate representation of a function may be printed using by code_llvm(f::Function, (Argtypes...)), and finally the compiled machine code is available using code_native(f::Function, (Argtypes...)) (this will trigger JIT compilation/code generation for any function which has not previously been called).For convenience, there are macro versions of the above functions which take standard function calls and expand argument types automatically:julia> @code_llvm +(1,1)\n\n; Function Attrs: sspreq\ndefine i64 @\"julia_+_130862\"(i64, i64) #0 {\ntop:\n %2 = add i64 %1, %0, !dbg !8\n ret i64 %2, !dbg !8\n}(likewise @code_typed, @code_warntype, @code_lowered, and @code_native)" -}, - -{ - "location": "devdocs/init.html#", - "page": "Initialization of the Julia runtime", - "title": "Initialization of the Julia runtime", - "category": "page", - "text": "" -}, - -{ - "location": "devdocs/init.html#Initialization-of-the-Julia-runtime-1", - "page": "Initialization of the Julia runtime", - "title": "Initialization of the Julia runtime", - "category": "section", - "text": "How does the Julia runtime execute julia -e \'println(\"Hello World!\")\' ?" -}, - -{ - "location": "devdocs/init.html#main()-1", - "page": "Initialization of the Julia runtime", - "title": "main()", - "category": "section", - "text": "Execution starts at main() in ui/repl.c.main() calls libsupport_init() to set the C library locale and to initialize the \"ios\" library (see ios_init_stdstreams() and Legacy ios.c library).Next parse_opts() is called to process command line options. Note that parse_opts() only deals with options that affect code generation or early initialization. Other options are handled later by process_options() in base/client.jl.parse_opts() stores command line options in the global jl_options struct." -}, - -{ - "location": "devdocs/init.html#julia_init()-1", - "page": "Initialization of the Julia runtime", - "title": "julia_init()", - "category": "section", - "text": "julia_init() in task.c is called by main() and calls _julia_init() in init.c._julia_init() begins by calling libsupport_init() again (it does nothing the second time).restore_signals() is called to zero the signal handler mask.jl_resolve_sysimg_location() searches configured paths for the base system image. See Building the Julia system image.jl_gc_init() sets up allocation pools and lists for weak refs, preserved values and finalization.jl_init_frontend() loads and initializes a pre-compiled femtolisp image containing the scanner/parser.jl_init_types() creates jl_datatype_t type description objects for the built-in types defined in julia.h. e.g.jl_any_type = jl_new_abstracttype(jl_symbol(\"Any\"), NULL, jl_null);\njl_any_type->super = jl_any_type;\n\njl_type_type = jl_new_abstracttype(jl_symbol(\"Type\"), jl_any_type, jl_null);\n\njl_int32_type = jl_new_bitstype(jl_symbol(\"Int32\"),\n jl_any_type, jl_null, 32);jl_init_tasks() creates the jl_datatype_t* jl_task_type object; initializes the global jl_root_task struct; and sets jl_current_task to the root task.jl_init_codegen() initializes the LLVM library.jl_init_serializer() initializes 8-bit serialization tags for 256 frequently used jl_value_t values. The serialization mechanism uses these tags as shorthand (in lieu of storing whole objects) to save storage space.If there is no sysimg file (!jl_options.image_file) then the Core and Main modules are created and boot.jl is evaluated:jl_core_module = jl_new_module(jl_symbol(\"Core\")) creates the Julia Core module.jl_init_intrinsic_functions() creates a new Julia module Intrinsics containing constant jl_intrinsic_type symbols. These define an integer code for each intrinsic function. emit_intrinsic() translates these symbols into LLVM instructions during code generation.jl_init_primitives() hooks C functions up to Julia function symbols. e.g. the symbol Base.is() is bound to C function pointer jl_f_is() by calling add_builtin_func(\"eval\", jl_f_top_eval).jl_new_main_module() creates the global \"Main\" module and sets jl_current_task->current_module = jl_main_module.Note: _julia_init() then sets jl_root_task->current_module = jl_core_module. jl_root_task is an alias of jl_current_task at this point, so the current_module set by jl_new_main_module() above is overwritten.jl_load(\"boot.jl\", sizeof(\"boot.jl\")) calls jl_parse_eval_all which repeatedly calls jl_toplevel_eval_flex() to execute boot.jl. jl_get_builtin_hooks() initializes global C pointers to Julia globals defined in boot.jl.jl_init_box_caches() pre-allocates global boxed integer value objects for values up to 1024. This speeds up allocation of boxed ints later on. e.g.:jl_value_t *jl_box_uint8(uint32_t x)\n{\n return boxed_uint8_cache[(uint8_t)x];\n}_julia_init() iterates over the jl_core_module->bindings.table looking for jl_datatype_t values and sets the type name\'s module prefix to jl_core_module.jl_add_standard_imports(jl_main_module) does \"using Base\" in the \"Main\" module.Note: _julia_init() now reverts to jl_root_task->current_module = jl_main_module as it was before being set to jl_core_module above.Platform specific signal handlers are initialized for SIGSEGV (OSX, Linux), and SIGFPE (Windows).Other signals (SIGINFO, SIGBUS, SIGILL, SIGTERM, SIGABRT, SIGQUIT, SIGSYS and SIGPIPE) are hooked up to sigdie_handler() which prints a backtrace.jl_init_restored_modules() calls jl_module_run_initializer() for each deserialized module to run the __init__() function.Finally sigint_handler() is hooked up to SIGINT and calls jl_throw(jl_interrupt_exception)._julia_init() then returns back to main() in ui/repl.c and main() calls true_main(argc, (char**)argv).sidebar: sysimg\nIf there is a sysimg file, it contains a pre-cooked image of the Core and Main modules (and whatever else is created by boot.jl). See Building the Julia system image.jl_restore_system_image() deserializes the saved sysimg into the current Julia runtime environment and initialization continues after jl_init_box_caches() below...Note: jl_restore_system_image() (and dump.c in general) uses the Legacy ios.c library." -}, - -{ - "location": "devdocs/init.html#true_main()-1", - "page": "Initialization of the Julia runtime", - "title": "true_main()", - "category": "section", - "text": "true_main() loads the contents of argv[] into Base.ARGS.If a .jl \"program\" file was supplied on the command line, then exec_program() calls jl_load(program,len) which calls jl_parse_eval_all which repeatedly calls jl_toplevel_eval_flex() to execute the program.However, in our example (julia -e \'println(\"Hello World!\")\'), jl_get_global(jl_base_module, jl_symbol(\"_start\")) looks up Base._start and jl_apply() executes it." -}, - -{ - "location": "devdocs/init.html#Base._start-1", - "page": "Initialization of the Julia runtime", - "title": "Base._start", - "category": "section", - "text": "Base._start calls Base.process_options which calls jl_parse_input_line(\"println(\"Hello World!\")\") to create an expression object and Base.eval() to execute it." -}, - -{ - "location": "devdocs/init.html#Base.eval-1", - "page": "Initialization of the Julia runtime", - "title": "Base.eval", - "category": "section", - "text": "Base.eval() was mapped to jl_f_top_eval by jl_init_primitives().jl_f_top_eval() calls jl_toplevel_eval_in(jl_main_module, ex), where ex is the parsed expression println(\"Hello World!\").jl_toplevel_eval_in() calls jl_toplevel_eval_flex() which calls eval() in interpreter.c.The stack dump below shows how the interpreter works its way through various methods of Base.println() and Base.print() before arriving at write(s::IO, a::Array{T}) where T which does ccall(jl_uv_write()).jl_uv_write() calls uv_write() to write \"Hello World!\" to JL_STDOUT. See Libuv wrappers for stdio.:Hello World!Stack frame Source code Notes\njl_uv_write() jl_uv.c called though ccall\njulia_write_282942 stream.jl function write!(s::IO, a::Array{T}) where T\njulia_print_284639 ascii.jl print(io::IO, s::String) = (write(io, s); nothing)\njlcall_print_284639    \njl_apply() julia.h  \njl_trampoline() builtins.c  \njl_apply() julia.h  \njl_apply_generic() gf.c Base.print(Base.TTY, String)\njl_apply() julia.h  \njl_trampoline() builtins.c  \njl_apply() julia.h  \njl_apply_generic() gf.c Base.print(Base.TTY, String, Char, Char...)\njl_apply() julia.h  \njl_f_apply() builtins.c  \njl_apply() julia.h  \njl_trampoline() builtins.c  \njl_apply() julia.h  \njl_apply_generic() gf.c Base.println(Base.TTY, String, String...)\njl_apply() julia.h  \njl_trampoline() builtins.c  \njl_apply() julia.h  \njl_apply_generic() gf.c Base.println(String,)\njl_apply() julia.h  \ndo_call() interpreter.c  \neval() interpreter.c  \njl_interpret_toplevel_expr() interpreter.c  \njl_toplevel_eval_flex() toplevel.c  \njl_toplevel_eval() toplevel.c  \njl_toplevel_eval_in() builtins.c  \njl_f_top_eval() builtins.c  Since our example has just one function call, which has done its job of printing \"Hello World!\", the stack now rapidly unwinds back to main()." -}, - -{ - "location": "devdocs/init.html#jl_atexit_hook()-1", - "page": "Initialization of the Julia runtime", - "title": "jl_atexit_hook()", - "category": "section", - "text": "main() calls jl_atexit_hook(). This calls _atexit for each module, then calls jl_gc_run_all_finalizers() and cleans up libuv handles." -}, - -{ - "location": "devdocs/init.html#julia_save()-1", - "page": "Initialization of the Julia runtime", - "title": "julia_save()", - "category": "section", - "text": "Finally, main() calls julia_save(), which if requested on the command line, saves the runtime state to a new system image. See jl_compile_all() and jl_save_system_image()." -}, - -{ - "location": "devdocs/ast.html#", - "page": "Julia ASTs", - "title": "Julia ASTs", - "category": "page", - "text": "" -}, - -{ - "location": "devdocs/ast.html#Julia-ASTs-1", - "page": "Julia ASTs", - "title": "Julia ASTs", - "category": "section", - "text": "Julia has two representations of code. First there is a surface syntax AST returned by the parser (e.g. the parse() function), and manipulated by macros. It is a structured representation of code as it is written, constructed by julia-parser.scm from a character stream. Next there is a lowered form, or IR (intermediate representation), which is used by type inference and code generation. In the lowered form there are fewer types of nodes, all macros are expanded, and all control flow is converted to explicit branches and sequences of statements. The lowered form is constructed by julia-syntax.scm.First we will focus on the lowered form, since it is more important to the compiler. It is also less obvious to the human, since it results from a significant rearrangement of the input syntax." -}, - -{ - "location": "devdocs/ast.html#Lowered-form-1", - "page": "Julia ASTs", - "title": "Lowered form", - "category": "section", - "text": "The following data types exist in lowered form:Expr\nHas a node type indicated by the head field, and an args field which is a Vector{Any} of subexpressions.\nSlot\nIdentifies arguments and local variables by consecutive numbering. Slot is an abstract type with subtypes SlotNumber and TypedSlot. Both types have an integer-valued id field giving the slot index. Most slots have the same type at all uses, and so are represented with SlotNumber. The types of these slots are found in the slottypes field of their MethodInstance object. Slots that require per-use type annotations are represented with TypedSlot, which has a typ field.\nCodeInfo\nWraps the IR of a method.\nLineNumberNode\nContains a single number, specifying the line number the next statement came from.\nLabelNode\nBranch target, a consecutively-numbered integer starting at 0.\nGotoNode\nUnconditional branch.\nQuoteNode\nWraps an arbitrary value to reference as data. For example, the function f() = :a contains a QuoteNode whose value field is the symbol a, in order to return the symbol itself instead of evaluating it.\nGlobalRef\nRefers to global variable name in module mod.\nSSAValue\nRefers to a consecutively-numbered (starting at 0) static single assignment (SSA) variable inserted by the compiler.\nNewvarNode\nMarks a point where a variable is created. This has the effect of resetting a variable to undefined." -}, - -{ - "location": "devdocs/ast.html#Expr-types-1", - "page": "Julia ASTs", - "title": "Expr types", - "category": "section", - "text": "These symbols appear in the head field of Exprs in lowered form.call\nFunction call (dynamic dispatch). args[1] is the function to call, args[2:end] are the arguments.\ninvoke\nFunction call (static dispatch). args[1] is the MethodInstance to call, args[2:end] are the arguments (including the function that is being called, at args[2]).\nstatic_parameter\nReference a static parameter by index.\nline\nLine number and file name metadata. Unlike a LineNumberNode, can also contain a file name.\ngotoifnot\nConditional branch. If args[1] is false, goes to label identified in args[2].\n=\nAssignment.\nmethod\nAdds a method to a generic function and assigns the result if necessary.\nHas a 1-argument form and a 4-argument form. The 1-argument form arises from the syntax function foo end. In the 1-argument form, the argument is a symbol. If this symbol already names a function in the current scope, nothing happens. If the symbol is undefined, a new function is created and assigned to the identifier specified by the symbol. If the symbol is defined but names a non-function, an error is raised. The definition of \"names a function\" is that the binding is constant, and refers to an object of singleton type. The rationale for this is that an instance of a singleton type uniquely identifies the type to add the method to. When the type has fields, it wouldn\'t be clear whether the method was being added to the instance or its type.\nThe 4-argument form has the following arguments:\nargs[1]\nA function name, or false if unknown. If a symbol, then the expression first behaves like the 1-argument form above. This argument is ignored from then on. When this is false, it means a method is being added strictly by type, (::T)(x) = x.\nargs[2]\nA SimpleVector of argument type data. args[2][1] is a SimpleVector of the argument types, and args[2][2] is a SimpleVector of type variables corresponding to the method\'s static parameters.\nargs[3]\nA CodeInfo of the method itself. For \"out of scope\" method definitions (adding a method to a function that also has methods defined in different scopes) this is an expression that evaluates to a :lambda expression.\nargs[4]\ntrue or false, identifying whether the method is staged (@generated function).\nconst\nDeclares a (global) variable as constant.\nnull\nHas no arguments; simply yields the value nothing.\nnew\nAllocates a new struct-like object. First argument is the type. The new pseudo-function is lowered to this, and the type is always inserted by the compiler. This is very much an internal-only feature, and does no checking. Evaluating arbitrary new expressions can easily segfault.\nreturn\nReturns its argument as the value of the enclosing function.\nthe_exception\nYields the caught exception inside a catch block. This is the value of the run time system variable jl_exception_in_transit.\nenter\nEnters an exception handler (setjmp). args[1] is the label of the catch block to jump to on error.\nleave\nPop exception handlers. args[1] is the number of handlers to pop.\ninbounds\nControls turning bounds checks on or off. A stack is maintained; if the first argument of this expression is true or false (true means bounds checks are disabled), it is pushed onto the stack. If the first argument is :pop, the stack is popped.\nboundscheck\nIndicates the beginning or end of a section of code that performs a bounds check. Like inbounds, a stack is maintained, and the second argument can be one of: true, false, or :pop.\ncopyast\nPart of the implementation of quasi-quote. The argument is a surface syntax AST that is simply copied recursively and returned at run time.\nmeta\nMetadata. args[1] is typically a symbol specifying the kind of metadata, and the rest of the arguments are free-form. The following kinds of metadata are commonly used:\n:inline and :noinline: Inlining hints.\n:push_loc: enters a sequence of statements from a specified source location.\nargs[2] specifies a filename, as a symbol.\nargs[3] optionally specifies the name of an (inlined) function that originally contained the code.\n:pop_loc: returns to the source location before the matching :push_loc." -}, - -{ - "location": "devdocs/ast.html#Method-1", - "page": "Julia ASTs", - "title": "Method", - "category": "section", - "text": "A unique\'d container describing the shared metadata for a single method.name, module, file, line, sig\nMetadata to uniquely identify the method for the computer and the human.\nambig\nCache of other methods that may be ambiguous with this one.\nspecializations\nCache of all MethodInstance ever created for this Method, used to ensure uniqueness. Uniqueness is required for efficiency, especially for incremental precompile and tracking of method invalidation.\nsource\nThe original source code (usually compressed).\nroots\nPointers to non-AST things that have been interpolated into the AST, required by compression of the AST, type-inference, or the generation of native code.\nnargs, isva, called, isstaged, pure\nDescriptive bit-fields for the source code of this Method.\nmin_world / max_world\nThe range of world ages for which this method is visible to dispatch." -}, - -{ - "location": "devdocs/ast.html#MethodInstance-1", - "page": "Julia ASTs", - "title": "MethodInstance", - "category": "section", - "text": "A unique\'d container describing a single callable signature for a Method. See especially Proper maintenance and care of multi-threading locks for important details on how to modify these fields safely.specTypes\nThe primary key for this MethodInstance. Uniqueness is guaranteed through a def.specializations lookup.\ndef\nThe Method that this function describes a specialization of. Or #undef, if this is a top-level Lambda that is not part of a Method.\nsparam_vals\nThe values of the static parameters in specTypes indexed by def.sparam_syms. For the MethodInstance at Method.unspecialized, this is the empty SimpleVector. But for a runtime MethodInstance from the MethodTable cache, this will always be defined and indexable.\nrettype\nThe inferred return type for the specFunctionObject field, which (in most cases) is also the computed return type for the function in general.\ninferred\nMay contain a cache of the inferred source for this function, or other information about the inference result such as a constant return value may be put here (if jlcall_api == 2), or it could be set to nothing to just indicate rettype is inferred.\nftpr\nThe generic jlcall entry point.\njlcall_api\nThe ABI to use when calling fptr. Some significant ones include:\n0 - Not compiled yet\n1 - JL_CALLABLE jl_value_t *(*)(jl_function_t *f, jl_value_t *args[nargs], uint32_t nargs)\n2 - Constant (value stored in inferred)\n3 - With Static-parameters forwarded jl_value_t *(*)(jl_svec_t *sparams, jl_function_t *f, jl_value_t *args[nargs], uint32_t nargs)\n4 - Run in interpreter jl_value_t *(*)(jl_method_instance_t *meth, jl_function_t *f, jl_value_t *args[nargs], uint32_t nargs)\nmin_world / max_world\nThe range of world ages for which this method instance is valid to be called." -}, - -{ - "location": "devdocs/ast.html#CodeInfo-1", - "page": "Julia ASTs", - "title": "CodeInfo", - "category": "section", - "text": "A temporary container for holding lowered source code.code\nAn Any array of statements\nslotnames\nAn array of symbols giving the name of each slot (argument or local variable).\nslottypes\nAn array of types for the slots.\nslotflags\nA UInt8 array of slot properties, represented as bit flags:\n2 - assigned (only false if there are no assignment statements with this var on the left)\n8 - const (currently unused for local variables)\n16 - statically assigned once\n32 - might be used before assigned. This flag is only valid after type inference.\nssavaluetypes\nEither an array or an Int.\nIf an Int, it gives the number of compiler-inserted temporary locations in the function. If an array, specifies a type for each location.Boolean properties:inferred\nWhether this has been produced by type inference.\ninlineable\nWhether this should be inlined.\npropagate_inbounds\nWhether this should should propagate @inbounds when inlined for the purpose of eliding @boundscheck blocks.\npure\nWhether this is known to be a pure function of its arguments, without respect to the state of the method caches or other mutable global state." -}, - -{ - "location": "devdocs/ast.html#Surface-syntax-AST-1", - "page": "Julia ASTs", - "title": "Surface syntax AST", - "category": "section", - "text": "Front end ASTs consist entirely of Exprs and atoms (e.g. symbols, numbers). There is generally a different expression head for each visually distinct syntactic form. Examples will be given in s-expression syntax. Each parenthesized list corresponds to an Expr, where the first element is the head. For example (call f x) corresponds to Expr(:call, :f, :x) in Julia." -}, - -{ - "location": "devdocs/ast.html#Calls-1", - "page": "Julia ASTs", - "title": "Calls", - "category": "section", - "text": "Input AST\nf(x) (call f x)\nf(x, y=1, z=2) (call f x (kw y 1) (kw z 2))\nf(x; y=1) (call f (parameters (kw y 1)) x)\nf(x...) (call f (... x))do syntax:f(x) do a,b\n body\nendparses as (call f (-> (tuple a b) (block body)) x)." -}, - -{ - "location": "devdocs/ast.html#Operators-1", - "page": "Julia ASTs", - "title": "Operators", - "category": "section", - "text": "Most uses of operators are just function calls, so they are parsed with the head call. However some operators are special forms (not necessarily function calls), and in those cases the operator itself is the expression head. In julia-parser.scm these are referred to as \"syntactic operators\". Some operators (+ and *) use N-ary parsing; chained calls are parsed as a single N-argument call. Finally, chains of comparisons have their own special expression structure.Input AST\nx+y (call + x y)\na+b+c+d (call + a b c d)\n2x (call * 2 x)\na&&b (&& a b)\nx += 1 (+= x 1)\na ? 1 : 2 (if a 1 2)\na:b (: a b)\na:b:c (: a b c)\na,b (tuple a b)\na==b (call == a b)\n1 typeintersect(Int, Float64)\nUnion{}\n\njulia> Union{Int, Float64}\nUnion{Float64, Int64}\n\njulia> typejoin(Int, Float64)\nReal\n\njulia> typeintersect(Signed, Union{UInt8, Int8})\nInt8\n\njulia> Union{Signed, Union{UInt8, Int8}}\nUnion{Signed, UInt8}\n\njulia> typejoin(Signed, Union{UInt8, Int8})\nInteger\n\njulia> typeintersect(Tuple{Integer,Float64}, Tuple{Int,Real})\nTuple{Int64,Float64}\n\njulia> Union{Tuple{Integer,Float64}, Tuple{Int,Real}}\nUnion{Tuple{Int64,Real}, Tuple{Integer,Float64}}\n\njulia> typejoin(Tuple{Integer,Float64}, Tuple{Int,Real})\nTuple{Integer,Real}While these operations may seem abstract, they lie at the heart of Julia. For example, method dispatch is implemented by stepping through the items in a method list until reaching one for which the type of the argument tuple is a subtype of the method signature. For this algorithm to work, it\'s important that methods be sorted by their specificity, and that the search begins with the most specific methods. Consequently, Julia also implements a partial order on types; this is achieved by functionality that is similar to <:, but with differences that will be discussed below." -}, - -{ - "location": "devdocs/types.html#UnionAll-types-1", - "page": "More about types", - "title": "UnionAll types", - "category": "section", - "text": "Julia\'s type system can also express an iterated union of types: a union of types over all values of some variable. This is needed to describe parametric types where the values of some parameters are not known.For example, :obj:Array has two parameters as in Array{Int,2}. If we did not know the element type, we could write Array{T,2} where T, which is the union of Array{T,2} for all values of T: Union{Array{Int8,2}, Array{Int16,2}, ...}.Such a type is represented by a UnionAll object, which contains a variable (T in this example, of type TypeVar), and a wrapped type (Array{T,2} in this example).Consider the following methods:f1(A::Array) = 1\nf2(A::Array{Int}) = 2\nf3(A::Array{T}) where {T<:Any} = 3\nf4(A::Array{Any}) = 4The signature of f3 is a UnionAll type wrapping a tuple type. All but f4 can be called with a = [1,2]; all but f2 can be called with b = Any[1,2].Let\'s look at these types a little more closely:julia> dump(Array)\nUnionAll\n var: TypeVar\n name: Symbol T\n lb: Core.TypeofBottom Union{}\n ub: Any\n body: UnionAll\n var: TypeVar\n name: Symbol N\n lb: Core.TypeofBottom Union{}\n ub: Any\n body: Array{T,N} <: DenseArray{T,N}This indicates that Array actually names a UnionAll type. There is one UnionAll type for each parameter, nested. The syntax Array{Int,2} is equivalent to Array{Int}{2}; internally each UnionAll is instantiated with a particular variable value, one at a time, outermost-first. This gives a natural meaning to the omission of trailing type parameters; Array{Int} gives a type equivalent to Array{Int,N} where N.A TypeVar is not itself a type, but rather should be considered part of the structure of a UnionAll type. Type variables have lower and upper bounds on their values (in the fields lb and ub). The symbol name is purely cosmetic. Internally, TypeVars are compared by address, so they are defined as mutable types to ensure that \"different\" type variables can be distinguished. However, by convention they should not be mutated.One can construct TypeVars manually:julia> TypeVar(:V, Signed, Real)\nSigned<:V<:RealThere are convenience versions that allow you to omit any of these arguments except the name symbol.The syntax Array{T} where T<:Integer is lowered tolet T = TypeVar(:T,Integer)\n UnionAll(T, Array{T})\nendso it is seldom necessary to construct a TypeVar manually (indeed, this is to be avoided)." -}, - -{ - "location": "devdocs/types.html#Free-variables-1", - "page": "More about types", - "title": "Free variables", - "category": "section", - "text": "The concept of a free type variable is extremely important in the type system. We say that a variable V is free in type T if T does not contain the UnionAll that introduces variable V. For example, the type Array{Array{V} where V<:Integer} has no free variables, but the Array{V} part inside of it does have a free variable, V.A type with free variables is, in some sense, not really a type at all. Consider the type Array{Array{T}} where T, which refers to all homogeneous arrays of arrays. The inner type Array{T}, seen by itself, might seem to refer to any kind of array. However, every element of the outer array must have the same array type, so Array{T} cannot refer to just any old array. One could say that Array{T} effectively \"occurs\" multiple times, and T must have the same value each \"time\".For this reason, the function jl_has_free_typevars in the C API is very important. Types for which it returns true will not give meaningful answers in subtyping and other type functions." -}, - -{ - "location": "devdocs/types.html#TypeNames-1", - "page": "More about types", - "title": "TypeNames", - "category": "section", - "text": "The following two Array types are functionally equivalent, yet print differently:julia> TV, NV = TypeVar(:T), TypeVar(:N)\n(T, N)\n\njulia> Array\nArray\n\njulia> Array{TV,NV}\nArray{T,N}These can be distinguished by examining the name field of the type, which is an object of type TypeName:julia> dump(Array{Int,1}.name)\nTypeName\n name: Symbol Array\n module: Module Core\n names: empty SimpleVector\n wrapper: UnionAll\n var: TypeVar\n name: Symbol T\n lb: Core.TypeofBottom Union{}\n ub: Any\n body: UnionAll\n var: TypeVar\n name: Symbol N\n lb: Core.TypeofBottom Union{}\n ub: Any\n body: Array{T,N} <: DenseArray{T,N}\n cache: SimpleVector\n ...\n\n linearcache: SimpleVector\n ...\n\n hash: Int64 -7900426068641098781\n mt: MethodTable\n name: Symbol Array\n defs: Void nothing\n cache: Void nothing\n max_args: Int64 0\n kwsorter: #undef\n module: Module Core\n : Int64 0\n : Int64 0In this case, the relevant field is wrapper, which holds a reference to the top-level type used to make new Array types.julia> pointer_from_objref(Array)\nPtr{Void} @0x00007fcc7de64850\n\njulia> pointer_from_objref(Array.body.body.name.wrapper)\nPtr{Void} @0x00007fcc7de64850\n\njulia> pointer_from_objref(Array{TV,NV})\nPtr{Void} @0x00007fcc80c4d930\n\njulia> pointer_from_objref(Array{TV,NV}.name.wrapper)\nPtr{Void} @0x00007fcc7de64850The wrapper field of Array points to itself, but for Array{TV,NV} it points back to the original definition of the type.What about the other fields? hash assigns an integer to each type. To examine the cache field, it\'s helpful to pick a type that is less heavily used than Array. Let\'s first create our own type:julia> struct MyType{T,N} end\n\njulia> MyType{Int,2}\nMyType{Int64,2}\n\njulia> MyType{Float32, 5}\nMyType{Float32,5}\n\njulia> MyType.body.body.name.cache\nsvec(MyType{Float32,5}, MyType{Int64,2}, #undef, #undef, #undef, #undef, #undef, #undef)(The cache is pre-allocated to have length 8, but only the first two entries are populated.) Consequently, when you instantiate a parametric type, each concrete type gets saved in a type cache. However, instances containing free type variables are not cached." -}, - -{ - "location": "devdocs/types.html#Tuple-types-1", - "page": "More about types", - "title": "Tuple types", - "category": "section", - "text": "Tuple types constitute an interesting special case. For dispatch to work on declarations like x::Tuple, the type has to be able to accommodate any tuple. Let\'s check the parameters:julia> Tuple\nTuple\n\njulia> Tuple.parameters\nsvec(Vararg{Any,N} where N)Unlike other types, tuple types are covariant in their parameters, so this definition permits Tuple to match any type of tuple:julia> typeintersect(Tuple, Tuple{Int,Float64})\nTuple{Int64,Float64}\n\njulia> typeintersect(Tuple{Vararg{Any}}, Tuple{Int,Float64})\nTuple{Int64,Float64}However, if a variadic (Vararg) tuple type has free variables it can describe different kinds of tuples:julia> typeintersect(Tuple{Vararg{T} where T}, Tuple{Int,Float64})\nTuple{Int64,Float64}\n\njulia> typeintersect(Tuple{Vararg{T}} where T, Tuple{Int,Float64})\nUnion{}Notice that when T is free with respect to the Tuple type (i.e. its binding UnionAll type is outside the Tuple type), only one T value must work over the whole type. Therefore a heterogeneous tuple does not match.Finally, it\'s worth noting that Tuple{} is distinct:julia> Tuple{}\nTuple{}\n\njulia> Tuple{}.parameters\nsvec()\n\njulia> typeintersect(Tuple{}, Tuple{Int})\nUnion{}What is the \"primary\" tuple-type?julia> pointer_from_objref(Tuple)\nPtr{Void} @0x00007f5998a04370\n\njulia> pointer_from_objref(Tuple{})\nPtr{Void} @0x00007f5998a570d0\n\njulia> pointer_from_objref(Tuple.name.wrapper)\nPtr{Void} @0x00007f5998a04370\n\njulia> pointer_from_objref(Tuple{}.name.wrapper)\nPtr{Void} @0x00007f5998a04370so Tuple == Tuple{Vararg{Any}} is indeed the primary type." -}, - -{ - "location": "devdocs/types.html#Diagonal-types-1", - "page": "More about types", - "title": "Diagonal types", - "category": "section", - "text": "Consider the type Tuple{T,T} where T. A method with this signature would look like:f(x::T, y::T) where {T} = ...According to the usual interpretation of a UnionAll type, this T ranges over all types, including Any, so this type should be equivalent to Tuple{Any,Any}. However, this interpretation causes some practical problems.First, a value of T needs to be available inside the method definition. For a call like f(1, 1.0), it\'s not clear what T should be. It could be Union{Int,Float64}, or perhaps Real. Intuitively, we expect the declaration x::T to mean T === typeof(x). To make sure that invariant holds, we need typeof(x) === typeof(y) === T in this method. That implies the method should only be called for arguments of the exact same type.It turns out that being able to dispatch on whether two values have the same type is very useful (this is used by the promotion system for example), so we have multiple reasons to want a different interpretation of Tuple{T,T} where T. To make this work we add the following rule to subtyping: if a variable occurs more than once in covariant position, it is restricted to ranging over only concrete types. (\"Covariant position\" means that only Tuple and Union types occur between an occurrence of a variable and the UnionAll type that introduces it.) Such variables are called \"diagonal variables\" or \"concrete variables\".So for example, Tuple{T,T} where T can be seen as Union{Tuple{Int8,Int8}, Tuple{Int16,Int16}, ...}, where T ranges over all concrete types. This gives rise to some interesting subtyping results. For example Tuple{Real,Real} is not a subtype of Tuple{T,T} where T, because it includes some types like Tuple{Int8,Int16} where the two elements have different types. Tuple{Real,Real} and Tuple{T,T} where T have the non-trivial intersection Tuple{T,T} where T<:Real. However, Tuple{Real} is a subtype of Tuple{T} where T, because in that case T occurs only once and so is not diagonal.Next consider a signature like the following:f(a::Array{T}, x::T, y::T) where {T} = ...In this case, T occurs in invariant position inside Array{T}. That means whatever type of array is passed unambiguously determines the value of T –- we say T has an equality constraint on it. Therefore in this case the diagonal rule is not really necessary, since the array determines T and we can then allow x and y to be of any subtypes of T. So variables that occur in invariant position are never considered diagonal. This choice of behavior is slightly controversial –- some feel this definition should be written asf(a::Array{T}, x::S, y::S) where {T, S<:T} = ...to clarify whether x and y need to have the same type. In this version of the signature they would, or we could introduce a third variable for the type of y if x and y can have different types.The next complication is the interaction of unions and diagonal variables, e.g.f(x::Union{Void,T}, y::T) where {T} = ...Consider what this declaration means. y has type T. x then can have either the same type T, or else be of type Void. So all of the following calls should match:f(1, 1)\nf(\"\", \"\")\nf(2.0, 2.0)\nf(nothing, 1)\nf(nothing, \"\")\nf(nothing, 2.0)These examples are telling us something: when x is nothing::Void, there are no extra constraints on y. It is as if the method signature had y::Any. This means that whether a variable is diagonal is not a static property based on where it appears in a type. Rather, it depends on where a variable appears when the subtyping algorithm uses it. When x has type Void, we don\'t need to use the T in Union{Void,T}, so T does not \"occur\". Indeed, we have the following type equivalence:(Tuple{Union{Void,T},T} where T) == Union{Tuple{Void,Any}, Tuple{T,T} where T}" -}, - -{ - "location": "devdocs/types.html#Subtyping-diagonal-variables-1", - "page": "More about types", - "title": "Subtyping diagonal variables", - "category": "section", - "text": "The subtyping algorithm for diagonal variables has two components: (1) identifying variable occurrences, and (2) ensuring that diagonal variables range over concrete types only.The first task is accomplished by keeping counters occurs_inv and occurs_cov (in src/subtype.c) for each variable in the environment, tracking the number of invariant and covariant occurrences, respectively. A variable is diagonal when occurs_inv == 0 && occurs_cov > 1.The second task is accomplished by imposing a condition on a variable\'s lower bound. As the subtyping algorithm runs, it narrows the bounds of each variable (raising lower bounds and lowering upper bounds) to keep track of the range of variable values for which the subtype relation would hold. When we are done evaluating the body of a UnionAll type whose variable is diagonal, we look at the final values of the bounds. Since the variable must be concrete, a contradiction occurs if its lower bound could not be a subtype of a concrete type. For example, an abstract type like AbstractArray cannot be a subtype of a concrete type, but a concrete type like Int can be, and the empty type Bottom can be as well. If a lower bound fails this test the algorithm stops with the answer false.For example, in the problem Tuple{Int,String} <: Tuple{T,T} where T, we derive that this would be true if T were a supertype of Union{Int,String}. However, Union{Int,String} is an abstract type, so the relation does not hold.This concreteness test is done by the function is_leaf_bound. Note that this test is slightly different from jl_is_leaf_type, since it also returns true for Bottom. Currently this function is heuristic, and does not catch all possible concrete types. The difficulty is that whether a lower bound is concrete might depend on the values of other type variable bounds. For example, Vector{T} is equivalent to the concrete type Vector{Int} only if both the upper and lower bounds of T equal Int. We have not yet worked out a complete algorithm for this." -}, - -{ - "location": "devdocs/types.html#Introduction-to-the-internal-machinery-1", - "page": "More about types", - "title": "Introduction to the internal machinery", - "category": "section", - "text": "Most operations for dealing with types are found in the files jltypes.c and subtype.c. A good way to start is to watch subtyping in action. Build Julia with make debug and fire up Julia within a debugger. gdb debugging tips has some tips which may be useful.Because the subtyping code is used heavily in the REPL itself–and hence breakpoints in this code get triggered often–it will be easiest if you make the following definition:julia> function mysubtype(a,b)\n ccall(:jl_breakpoint, Void, (Any,), nothing)\n issubtype(a, b)\n endand then set a breakpoint in jl_breakpoint. Once this breakpoint gets triggered, you can set breakpoints in other functions.As a warm-up, try the following:mysubtype(Tuple{Int,Float64}, Tuple{Integer,Real})We can make it more interesting by trying a more complex case:mysubtype(Tuple{Array{Int,2}, Int8}, Tuple{Array{T}, T} where T)" -}, - -{ - "location": "devdocs/types.html#Subtyping-and-method-sorting-1", - "page": "More about types", - "title": "Subtyping and method sorting", - "category": "section", - "text": "The type_morespecific functions are used for imposing a partial order on functions in method tables (from most-to-least specific). Specificity is strict; if a is more specific than b, then a does not equal b and b is not more specific than a.If a is a strict subtype of b, then it is automatically considered more specific. From there, type_morespecific employs some less formal rules. For example, subtype is sensitive to the number of arguments, but type_morespecific may not be. In particular, Tuple{Int,AbstractFloat} is more specific than Tuple{Integer}, even though it is not a subtype. (Of Tuple{Int,AbstractFloat} and Tuple{Integer,Float64}, neither is more specific than the other.) Likewise, Tuple{Int,Vararg{Int}} is not a subtype of Tuple{Integer}, but it is considered more specific. However, morespecific does get a bonus for length: in particular, Tuple{Int,Int} is more specific than Tuple{Int,Vararg{Int}}.If you\'re debugging how methods get sorted, it can be convenient to define the function:type_morespecific(a, b) = ccall(:jl_type_morespecific, Cint, (Any,Any), a, b)which allows you to test whether tuple type a is more specific than tuple type b." -}, - -{ - "location": "devdocs/object.html#", - "page": "Memory layout of Julia Objects", - "title": "Memory layout of Julia Objects", - "category": "page", - "text": "" -}, - -{ - "location": "devdocs/object.html#Memory-layout-of-Julia-Objects-1", - "page": "Memory layout of Julia Objects", - "title": "Memory layout of Julia Objects", - "category": "section", - "text": "" -}, - -{ - "location": "devdocs/object.html#Object-layout-(jl_value_t)-1", - "page": "Memory layout of Julia Objects", - "title": "Object layout (jl_value_t)", - "category": "section", - "text": "The jl_value_t struct is the name for a block of memory owned by the Julia Garbage Collector, representing the data associated with a Julia object in memory. Absent any type information, it is simply an opaque pointer:typedef struct jl_value_t* jl_pvalue_t;Each jl_value_t struct is contained in a jl_typetag_t struct that contains metadata information about the Julia object, such as its type and garbage collector (gc) reachability:typedef struct {\n opaque metadata;\n jl_value_t value;\n} jl_typetag_t;The type of any Julia object is an instance of a leaf jl_datatype_t object. The jl_typeof() function can be used to query for it:jl_value_t *jl_typeof(jl_value_t *v);The layout of the object depends on its type. Reflection methods can be used to inspect that layout. A field can be accessed by calling one of the get-field methods:jl_value_t *jl_get_nth_field_checked(jl_value_t *v, size_t i);\njl_value_t *jl_get_field(jl_value_t *o, char *fld);If the field types are known, a priori, to be all pointers, the values can also be extracted directly as an array access:jl_value_t *v = value->fieldptr[n];As an example, a \"boxed\" uint16_t is stored as follows:struct {\n opaque metadata;\n struct {\n uint16_t data; // -- 2 bytes\n } jl_value_t;\n};This object is created by jl_box_uint16(). Note that the jl_value_t pointer references the data portion, not the metadata at the top of the struct.A value may be stored \"unboxed\" in many circumstances (just the data, without the metadata, and possibly not even stored but just kept in registers), so it is unsafe to assume that the address of a box is a unique identifier. The \"egal\" test (corresponding to the === function in Julia), should instead be used to compare two unknown objects for equivalence:int jl_egal(jl_value_t *a, jl_value_t *b);This optimization should be relatively transparent to the API, since the object will be \"boxed\" on-demand, whenever a jl_value_t pointer is needed.Note that modification of a jl_value_t pointer in memory is permitted only if the object is mutable. Otherwise, modification of the value may corrupt the program and the result will be undefined. The mutability property of a value can be queried for with:int jl_is_mutable(jl_value_t *v);If the object being stored is a jl_value_t, the Julia garbage collector must be notified also:void jl_gc_wb(jl_value_t *parent, jl_value_t *ptr);However, the Embedding Julia section of the manual is also required reading at this point, for covering other details of boxing and unboxing various types, and understanding the gc interactions.Mirror structs for some of the built-in types are defined in julia.h. The corresponding global jl_datatype_t objects are created by jl_init_types in jltypes.c." -}, - -{ - "location": "devdocs/object.html#Garbage-collector-mark-bits-1", - "page": "Memory layout of Julia Objects", - "title": "Garbage collector mark bits", - "category": "section", - "text": "The garbage collector uses several bits from the metadata portion of the jl_typetag_t to track each object in the system. Further details about this algorithm can be found in the comments of the garbage collector implementation in gc.c." -}, - -{ - "location": "devdocs/object.html#Object-allocation-1", - "page": "Memory layout of Julia Objects", - "title": "Object allocation", - "category": "section", - "text": "Most new objects are allocated by jl_new_structv():jl_value_t *jl_new_struct(jl_datatype_t *type, ...);\njl_value_t *jl_new_structv(jl_datatype_t *type, jl_value_t **args, uint32_t na);Although, isbits objects can be also constructed directly from memory:jl_value_t *jl_new_bits(jl_value_t *bt, void *data)And some objects have special constructors that must be used instead of the above functions:Types:jl_datatype_t *jl_apply_type(jl_datatype_t *tc, jl_tuple_t *params);\njl_datatype_t *jl_apply_array_type(jl_datatype_t *type, size_t dim);\njl_uniontype_t *jl_new_uniontype(jl_tuple_t *types);While these are the most commonly used options, there are more low-level constructors too, which you can find declared in julia.h. These are used in jl_init_types() to create the initial types needed to bootstrap the creation of the Julia system image.Tuples:jl_tuple_t *jl_tuple(size_t n, ...);\njl_tuple_t *jl_tuplev(size_t n, jl_value_t **v);\njl_tuple_t *jl_alloc_tuple(size_t n);The representation of tuples is highly unique in the Julia object representation ecosystem. In some cases, a Base.tuple() object may be an array of pointers to the objects contained by the tuple equivalent to:typedef struct {\n size_t length;\n jl_value_t *data[length];\n} jl_tuple_t;However, in other cases, the tuple may be converted to an anonymous isbits type and stored unboxed, or it may not stored at all (if it is not being used in a generic context as a jl_value_t*).Symbols:jl_sym_t *jl_symbol(const char *str);Functions and MethodInstance:jl_function_t *jl_new_generic_function(jl_sym_t *name);\njl_method_instance_t *jl_new_method_instance(jl_value_t *ast, jl_tuple_t *sparams);Arrays:jl_array_t *jl_new_array(jl_value_t *atype, jl_tuple_t *dims);\njl_array_t *jl_new_arrayv(jl_value_t *atype, ...);\njl_array_t *jl_alloc_array_1d(jl_value_t *atype, size_t nr);\njl_array_t *jl_alloc_array_2d(jl_value_t *atype, size_t nr, size_t nc);\njl_array_t *jl_alloc_array_3d(jl_value_t *atype, size_t nr, size_t nc, size_t z);\njl_array_t *jl_alloc_vec_any(size_t n);Note that many of these have alternative allocation functions for various special-purposes. The list here reflects the more common usages, but a more complete list can be found by reading the julia.h header file.Internal to Julia, storage is typically allocated by newstruct() (or newobj() for the special types):jl_value_t *newstruct(jl_value_t *type);\njl_value_t *newobj(jl_value_t *type, size_t nfields);And at the lowest level, memory is getting allocated by a call to the garbage collector (in gc.c), then tagged with its type:jl_value_t *jl_gc_allocobj(size_t nbytes);\nvoid jl_set_typeof(jl_value_t *v, jl_datatype_t *type);Note that all objects are allocated in multiples of 4 bytes and aligned to the platform pointer size. Memory is allocated from a pool for smaller objects, or directly with malloc() for large objects.sidebar: Singleton Types\nSingleton types have only one instance and no data fields. Singleton instances have a size of 0 bytes, and consist only of their metadata. e.g. nothing::Void.See Singleton Types and Nothingness and missing values" -}, - -{ - "location": "devdocs/eval.html#", - "page": "Eval of Julia code", - "title": "Eval of Julia code", - "category": "page", - "text": "" -}, - -{ - "location": "devdocs/eval.html#Eval-of-Julia-code-1", - "page": "Eval of Julia code", - "title": "Eval of Julia code", - "category": "section", - "text": "One of the hardest parts about learning how the Julia Language runs code is learning how all of the pieces work together to execute a block of code.Each chunk of code typically makes a trip through many steps with potentially unfamiliar names, such as (in no particular order): flisp, AST, C++, LLVM, eval, typeinf, macroexpand, sysimg (or system image), bootstrapping, compile, parse, execute, JIT, interpret, box, unbox, intrinsic function, and primitive function, before turning into the desired result (hopefully).sidebar: Definitions\nREPL\nREPL stands for Read-Eval-Print Loop. It\'s just what we call the command line environment for short.\nAST\nAbstract Syntax Tree The AST is the digital representation of the code structure. In this form the code has been tokenized for meaning so that it is more suitable for manipulation and execution." -}, - -{ - "location": "devdocs/eval.html#Julia-Execution-1", - "page": "Eval of Julia code", - "title": "Julia Execution", - "category": "section", - "text": "The 10,000 foot view of the whole process is as follows:The user starts julia.\nThe C function main() from ui/repl.c gets called. This function processes the command line arguments, filling in the jl_options struct and setting the variable ARGS. It then initializes Julia (by calling julia_init in task.c, which may load a previously compiled sysimg). Finally, it passes off control to Julia by calling Base._start().\nWhen _start() takes over control, the subsequent sequence of commands depends on the command line arguments given. For example, if a filename was supplied, it will proceed to execute that file. Otherwise, it will start an interactive REPL.\nSkipping the details about how the REPL interacts with the user, let\'s just say the program ends up with a block of code that it wants to run.\nIf the block of code to run is in a file, jl_load(char *filename) gets invoked to load the file and parse it. Each fragment of code is then passed to eval to execute.\nEach fragment of code (or AST), is handed off to eval() to turn into results.\neval() takes each code fragment and tries to run it in jl_toplevel_eval_flex().\njl_toplevel_eval_flex() decides whether the code is a \"toplevel\" action (such as using or module), which would be invalid inside a function. If so, it passes off the code to the toplevel interpreter.\njl_toplevel_eval_flex() then expands the code to eliminate any macros and to \"lower\" the AST to make it simpler to execute.\njl_toplevel_eval_flex() then uses some simple heuristics to decide whether to JIT compiler the AST or to interpret it directly.\nThe bulk of the work to interpret code is handled by eval in interpreter.c.\nIf instead, the code is compiled, the bulk of the work is handled by codegen.cpp. Whenever a Julia function is called for the first time with a given set of argument types, type inference will be run on that function. This information is used by the codegen step to generate faster code.\nEventually, the user quits the REPL, or the end of the program is reached, and the _start() method returns.\nJust before exiting, main() calls jl_atexit_hook(exit_code). This calls Base._atexit() (which calls any functions registered to atexit() inside Julia). Then it calls jl_gc_run_all_finalizers(). Finally, it gracefully cleans up all libuv handles and waits for them to flush and close." -}, - -{ - "location": "devdocs/eval.html#dev-parsing-1", - "page": "Eval of Julia code", - "title": "Parsing", - "category": "section", - "text": "The Julia parser is a small lisp program written in femtolisp, the source-code for which is distributed inside Julia in src/flisp.The interface functions for this are primarily defined in jlfrontend.scm. The code in ast.c handles this handoff on the Julia side.The other relevant files at this stage are julia-parser.scm, which handles tokenizing Julia code and turning it into an AST, and julia-syntax.scm, which handles transforming complex AST representations into simpler, \"lowered\" AST representations which are more suitable for analysis and execution." -}, - -{ - "location": "devdocs/eval.html#dev-macro-expansion-1", - "page": "Eval of Julia code", - "title": "Macro Expansion", - "category": "section", - "text": "When eval() encounters a macro, it expands that AST node before attempting to evaluate the expression. Macro expansion involves a handoff from eval() (in Julia), to the parser function jl_macroexpand() (written in flisp) to the Julia macro itself (written in - what else - Julia) via fl_invoke_julia_macro(), and back.Typically, macro expansion is invoked as a first step during a call to expand()/jl_expand(), although it can also be invoked directly by a call to macroexpand()/jl_macroexpand()." -}, - -{ - "location": "devdocs/eval.html#dev-type-inference-1", - "page": "Eval of Julia code", - "title": "Type Inference", - "category": "section", - "text": "Type inference is implemented in Julia by typeinf() in inference.jl. Type inference is the process of examining a Julia function and determining bounds for the types of each of its variables, as well as bounds on the type of the return value from the function. This enables many future optimizations, such as unboxing of known immutable values, and compile-time hoisting of various run-time operations such as computing field offsets and function pointers. Type inference may also include other steps such as constant propagation and inlining.sidebar: More Definitions\nJIT\nJust-In-Time Compilation The process of generating native-machine code into memory right when it is needed.\nLLVM\nLow-Level Virtual Machine (a compiler) The Julia JIT compiler is a program/library called libLLVM. Codegen in Julia refers both to the process of taking a Julia AST and turning it into LLVM instructions, and the process of LLVM optimizing that and turning it into native assembly instructions.\nC++\nThe programming language that LLVM is implemented in, which means that codegen is also implemented in this language. The rest of Julia\'s library is implemented in C, in part because its smaller feature set makes it more usable as a cross-language interface layer.\nbox\nThis term is used to describe the process of taking a value and allocating a wrapper around the data that is tracked by the garbage collector (gc) and is tagged with the object\'s type.\nunbox\nThe reverse of boxing a value. This operation enables more efficient manipulation of data when the type of that data is fully known at compile-time (through type inference).\ngeneric function\nA Julia function composed of multiple \"methods\" that are selected for dynamic dispatch based on the argument type-signature\nanonymous function or \"method\"\nA Julia function without a name and without type-dispatch capabilities\nprimitive function\nA function implemented in C but exposed in Julia as a named function \"method\" (albeit without generic function dispatch capabilities, similar to a anonymous function)\nintrinsic function\nA low-level operation exposed as a function in Julia. These pseudo-functions implement operations on raw bits such as add and sign extend that cannot be expressed directly in any other way. Since they operate on bits directly, they must be compiled into a function and surrounded by a call to Core.Intrinsics.box(T, ...) to reassign type information to the value." -}, - -{ - "location": "devdocs/eval.html#dev-codegen-1", - "page": "Eval of Julia code", - "title": "JIT Code Generation", - "category": "section", - "text": "Codegen is the process of turning a Julia AST into native machine code.The JIT environment is initialized by an early call to jl_init_codegen in codegen.cpp.On demand, a Julia method is converted into a native function by the function emit_function(jl_method_instance_t*). (note, when using the MCJIT (in LLVM v3.4+), each function must be JIT into a new module.) This function recursively calls emit_expr() until the entire function has been emitted.Much of the remaining bulk of this file is devoted to various manual optimizations of specific code patterns. For example, emit_known_call() knows how to inline many of the primitive functions (defined in builtins.c) for various combinations of argument types.Other parts of codegen are handled by various helper files:debuginfo.cpp\nHandles backtraces for JIT functions\nccall.cpp\nHandles the ccall and llvmcall FFI, along with various abi_*.cpp files\nintrinsics.cpp\nHandles the emission of various low-level intrinsic functionssidebar: Bootstrapping\nThe process of creating a new system image is called \"bootstrapping\".The etymology of this word comes from the phrase \"pulling oneself up by the bootstraps\", and refers to the idea of starting from a very limited set of available functions and definitions and ending with the creation of a full-featured environment." -}, - -{ - "location": "devdocs/eval.html#dev-sysimg-1", - "page": "Eval of Julia code", - "title": "System Image", - "category": "section", - "text": "The system image is a precompiled archive of a set of Julia files. The sys.ji file distributed with Julia is one such system image, generated by executing the file sysimg.jl, and serializing the resulting environment (including Types, Functions, Modules, and all other defined values) into a file. Therefore, it contains a frozen version of the Main, Core, and Base modules (and whatever else was in the environment at the end of bootstrapping). This serializer/deserializer is implemented by jl_save_system_image/jl_restore_system_image in dump.c.If there is no sysimg file (jl_options.image_file == NULL), this also implies that --build was given on the command line, so the final result should be a new sysimg file. During Julia initialization, minimal Core and Main modules are created. Then a file named boot.jl is evaluated from the current directory. Julia then evaluates any file given as a command line argument until it reaches the end. Finally, it saves the resulting environment to a \"sysimg\" file for use as a starting point for a future Julia run." -}, - -{ - "location": "devdocs/callconv.html#", - "page": "Calling Conventions", - "title": "Calling Conventions", - "category": "page", - "text": "" -}, - -{ - "location": "devdocs/callconv.html#Calling-Conventions-1", - "page": "Calling Conventions", - "title": "Calling Conventions", - "category": "section", - "text": "Julia uses three calling conventions for four distinct purposes:Name Prefix Purpose\nNative julia_ Speed via specialized signatures\nJL Call jlcall_ Wrapper for generic calls\nJL Call jl_ Builtins\nC ABI jlcapi_ Wrapper callable from C" -}, - -{ - "location": "devdocs/callconv.html#Julia-Native-Calling-Convention-1", - "page": "Calling Conventions", - "title": "Julia Native Calling Convention", - "category": "section", - "text": "The native calling convention is designed for fast non-generic calls. It usually uses a specialized signature.LLVM ghosts (zero-length types) are omitted.\nLLVM scalars and vectors are passed by value.\nLLVM aggregates (arrays and structs) are passed by reference.A small return values is returned as LLVM return values. A large return values is returned via the \"structure return\" (sret) convention, where the caller provides a pointer to a return slot.An argument or return values thta is a homogeneous tuple is sometimes represented as an LLVM vector instead of an LLVM array." -}, - -{ - "location": "devdocs/callconv.html#JL-Call-Convention-1", - "page": "Calling Conventions", - "title": "JL Call Convention", - "category": "section", - "text": "The JL Call convention is for builtins and generic dispatch. Hand-written functions using this convention are declared via the macro JL_CALLABLE. The convention uses exactly 3 parameters:F - Julia representation of function that is being applied\nargs - pointer to array of pointers to boxes\nnargs - length of the arrayThe return value is a pointer to a box." -}, - -{ - "location": "devdocs/callconv.html#C-ABI-1", - "page": "Calling Conventions", - "title": "C ABI", - "category": "section", - "text": "C ABI wrappers enable calling Julia from C. The wrapper calls a function using the native calling convention.Tuples are always represented as C arrays." -}, - -{ - "location": "devdocs/compiler.html#", - "page": "High-level Overview of the Native-Code Generation Process", - "title": "High-level Overview of the Native-Code Generation Process", - "category": "page", - "text": "" -}, - -{ - "location": "devdocs/compiler.html#High-level-Overview-of-the-Native-Code-Generation-Process-1", - "page": "High-level Overview of the Native-Code Generation Process", - "title": "High-level Overview of the Native-Code Generation Process", - "category": "section", - "text": "" -}, - -{ - "location": "devdocs/compiler.html#Representation-of-Pointers-1", - "page": "High-level Overview of the Native-Code Generation Process", - "title": "Representation of Pointers", - "category": "section", - "text": "When emitting code to an object file, pointers will be emitted as relocations. The deserialization code will ensure any object that pointed to one of these constants gets recreated and contains the right runtime pointer.Otherwise, they will be emitted as literal constants.To emit one of these objects, call literal_pointer_val. It\'ll handle tracking the Julia value and the LLVM global, ensuring they are valid both for the current runtime and after deserialization.When emitted into the object file, these globals are stored as references in a large gvals table. This allows the deserializer to reference them by index, and implement a custom manual mechanism similar to a Global Offset Table (GOT) to restore them.Function pointers are handled similarly. They are stored as values in a large fvals table. Like globals, this allows the deserializer to reference them by index.Note that extern functions are handled separately, with names, via the usual symbol resolution mechanism in the linker.Note too that ccall functions are also handled separately, via a manual GOT and Procedure Linkage Table (PLT)." -}, - -{ - "location": "devdocs/compiler.html#Representation-of-Intermediate-Values-1", - "page": "High-level Overview of the Native-Code Generation Process", - "title": "Representation of Intermediate Values", - "category": "section", - "text": "Values are passed around in a jl_cgval_t struct. This represents an R-value, and includes enough information to determine how to assign or pass it somewhere.They are created via one of the helper constructors, usually: mark_julia_type (for immediate values) and mark_julia_slot (for pointers to values).The function convert_julia_type can transform between any two types. It returns an R-value with cgval.typ set to typ. It\'ll cast the object to the requested representation, making heap boxes, allocating stack copies, and computing tagged unions as needed to change the representation.By contrast update_julia_type will change cgval.typ to typ, only if it can be done at zero-cost (i.e. without emitting any code)." -}, - -{ - "location": "devdocs/compiler.html#Union-representation-1", - "page": "High-level Overview of the Native-Code Generation Process", - "title": "Union representation", - "category": "section", - "text": "Inferred union types may be stack allocated via a tagged type representation.The primitive routines that need to be able to handle tagged unions are:mark-type\nload-local\nstore-local\nisa\nis\nemit_typeof\nemit_sizeof\nboxed\nunbox\nspecialized cc-retEverything else should be possible to handle in inference by using these primitives to implement union-splitting.The representation of the tagged-union is as a pair of < void* union, byte selector >. The selector is fixed-size as byte & 0x7f, and will union-tag the first 126 isbits. It records the one-based depth-first count into the type-union of the isbits objects inside. An index of zero indicates that the union* is actually a tagged heap-allocated jl_value_t*, and needs to be treated as normal for a boxed object rather than as a tagged union.The high bit of the selector (byte & 0x80) can be tested to determine if the void* is actually a heap-allocated (jl_value_t*) box, thus avoiding the cost of re-allocating a box, while maintaining the ability to efficiently handle union-splitting based on the low bits.It is guaranteed that byte & 0x7f is an exact test for the type, if the value can be represented by a tag – it will never be marked byte = 0x80. It is not necessary to also test the type-tag when testing isa.The union* memory region may be allocated at any size. The only constraint is that it is big enough to contain the data currently specified by selector. It might not be big enough to contain the union of all types that could be stored there according to the associated Union type field. Use appropriate care when copying." -}, - -{ - "location": "devdocs/compiler.html#Specialized-Calling-Convention-Signature-Representation-1", - "page": "High-level Overview of the Native-Code Generation Process", - "title": "Specialized Calling Convention Signature Representation", - "category": "section", - "text": "A jl_returninfo_t object describes the calling convention details of any callable.If any of the arguments or return type of a method can be represented unboxed, and the method is not varargs, it\'ll be given an optimized calling convention signature based on its specTypes and rettype fields.The general principles are that:Primitive types get passed in int/float registers.\nTuples of VecElement types get passed in vector registers.\nStructs get passed on the stack.\nReturn values are handle similarly to arguments, with a size-cutoff at which they will instead be returned via a hidden sret argument.The total logic for this is implemented by get_specsig_function and deserves_sret.Additionally, if the return type is a union, it may be returned as a pair of values (a pointer and a tag). If the union values can be stack-allocated, then sufficient space to store them will also be passed as a hidden first argument. It is up to the callee whether the returned pointer will point to this space, a boxed object, or even other constant memory." -}, - -{ - "location": "devdocs/functions.html#", - "page": "Julia Functions", - "title": "Julia Functions", - "category": "page", - "text": "" -}, - -{ - "location": "devdocs/functions.html#Julia-Functions-1", - "page": "Julia Functions", - "title": "Julia Functions", - "category": "section", - "text": "This document will explain how functions, method definitions, and method tables work." -}, - -{ - "location": "devdocs/functions.html#Method-Tables-1", - "page": "Julia Functions", - "title": "Method Tables", - "category": "section", - "text": "Every function in Julia is a generic function. A generic function is conceptually a single function, but consists of many definitions, or methods. The methods of a generic function are stored in a method table. Method tables (type MethodTable) are associated with TypeNames. A TypeName describes a family of parameterized types. For example Complex{Float32} and Complex{Float64} share the same Complex type name object.All objects in Julia are potentially callable, because every object has a type, which in turn has a TypeName." -}, - -{ - "location": "devdocs/functions.html#Function-calls-1", - "page": "Julia Functions", - "title": "Function calls", - "category": "section", - "text": "Given the call f(x,y), the following steps are performed: first, the method table to use is accessed as typeof(f).name.mt. Second, an argument tuple type is formed, Tuple{typeof(f), typeof(x), typeof(y)}. Note that the type of the function itself is the first element. This is because the type might have parameters, and so needs to take part in dispatch. This tuple type is looked up in the method table.This dispatch process is performed by jl_apply_generic, which takes two arguments: a pointer to an array of the values f, x, and y, and the number of values (in this case 3).Throughout the system, there are two kinds of APIs that handle functions and argument lists: those that accept the function and arguments separately, and those that accept a single argument structure. In the first kind of API, the \"arguments\" part does not contain information about the function, since that is passed separately. In the second kind of API, the function is the first element of the argument structure.For example, the following function for performing a call accepts just an args pointer, so the first element of the args array will be the function to call:jl_value_t *jl_apply(jl_value_t **args, uint32_t nargs)This entry point for the same functionality accepts the function separately, so the args array does not contain the function:jl_value_t *jl_call(jl_function_t *f, jl_value_t **args, int32_t nargs);" -}, - -{ - "location": "devdocs/functions.html#Adding-methods-1", - "page": "Julia Functions", - "title": "Adding methods", - "category": "section", - "text": "Given the above dispatch process, conceptually all that is needed to add a new method is (1) a tuple type, and (2) code for the body of the method. jl_method_def implements this operation. jl_first_argument_datatype is called to extract the relevant method table from what would be the type of the first argument. This is much more complicated than the corresponding procedure during dispatch, since the argument tuple type might be abstract. For example, we can define:(::Union{Foo{Int},Foo{Int8}})(x) = 0which works since all possible matching methods would belong to the same method table." -}, - -{ - "location": "devdocs/functions.html#Creating-generic-functions-1", - "page": "Julia Functions", - "title": "Creating generic functions", - "category": "section", - "text": "Since every object is callable, nothing special is needed to create a generic function. Therefore jl_new_generic_function simply creates a new singleton (0 size) subtype of Function and returns its instance. A function can have a mnemonic \"display name\" which is used in debug info and when printing objects. For example the name of Base.sin is sin. By convention, the name of the created type is the same as the function name, with a # prepended. So typeof(sin) is Base.#sin." -}, - -{ - "location": "devdocs/functions.html#Closures-1", - "page": "Julia Functions", - "title": "Closures", - "category": "section", - "text": "A closure is simply a callable object with field names corresponding to captured variables. For example, the following code:function adder(x)\n return y->x+y\nendis lowered to (roughly):struct ##1{T}\n x::T\nend\n\n(_::##1)(y) = _.x + y\n\nfunction adder(x)\n return ##1(x)\nend" -}, - -{ - "location": "devdocs/functions.html#Constructors-1", - "page": "Julia Functions", - "title": "Constructors", - "category": "section", - "text": "A constructor call is just a call to a type. The type of most types is DataType, so the method table for DataType contains most constructor definitions. One wrinkle is the fallback definition that makes all types callable via convert:(::Type{T}){T}(args...) = convert(T, args...)::TIn this definition the function type is abstract, which is not normally supported. To make this work, all subtypes of Type (Type, UnionAll, Union, and DataType) currently share a method table via special arrangement." -}, - -{ - "location": "devdocs/functions.html#Builtins-1", - "page": "Julia Functions", - "title": "Builtins", - "category": "section", - "text": "The \"builtin\" functions, defined in the Core module, are:=== typeof sizeof issubtype isa typeassert throw tuple getfield setfield! fieldtype\nnfields isdefined arrayref arrayset arraysize applicable invoke apply_type _apply\n_expr svecThese are all singleton objects whose types are subtypes of Builtin, which is a subtype of Function. Their purpose is to expose entry points in the run time that use the \"jlcall\" calling convention:jl_value_t *(jl_value_t*, jl_value_t**, uint32_t)The method tables of builtins are empty. Instead, they have a single catch-all method cache entry (Tuple{Vararg{Any}}) whose jlcall fptr points to the correct function. This is kind of a hack but works reasonably well." -}, - -{ - "location": "devdocs/functions.html#Keyword-arguments-1", - "page": "Julia Functions", - "title": "Keyword arguments", - "category": "section", - "text": "Keyword arguments work by associating a special, hidden function object with each method table that has definitions with keyword arguments. This function is called the \"keyword argument sorter\" or \"keyword sorter\", or \"kwsorter\", and is stored in the kwsorter field of MethodTable objects. Every definition in the kwsorter function has the same arguments as some definition in the normal method table, except with a single Array argument prepended. This array contains alternating symbols and values that represent the passed keyword arguments. The kwsorter\'s job is to move keyword arguments into their canonical positions based on name, plus evaluate and substite any needed default value expressions. The result is a normal positional argument list, which is then passed to yet another function.The easiest way to understand the process is to look at how a keyword argument method definition is lowered. The code:function circle(center, radius; color = black, fill::Bool = true, options...)\n # draw\nendactually produces three method definitions. The first is a function that accepts all arguments (including keywords) as positional arguments, and includes the code for the method body. It has an auto-generated name:function #circle#1(color, fill::Bool, options, circle, center, radius)\n # draw\nendThe second method is an ordinary definition for the original circle function, which handles the case where no keyword arguments are passed:function circle(center, radius)\n #circle#1(black, true, Any[], circle, center, radius)\nendThis simply dispatches to the first method, passing along default values. Finally there is the kwsorter definition:function (::Core.kwftype(typeof(circle)))(kw::Array, circle, center, radius)\n options = Any[]\n color = arg associated with :color, or black if not found\n fill = arg associated with :fill, or true if not found\n # push remaining elements of kw into options array\n #circle#1(color, fill, options, circle, center, radius)\nendThe front end generates code to loop over the kw array and pick out arguments in the right order, evaluating default expressions when an argument is not found.The function Core.kwftype(t) fetches (and creates, if necessary) the field t.name.mt.kwsorter.This design has the feature that call sites that don\'t use keyword arguments require no special handling; everything works as if they were not part of the language at all. Call sites that do use keyword arguments are dispatched directly to the called function\'s kwsorter. For example the call:circle((0,0), 1.0, color = red; other...)is lowered to:kwfunc(circle)(Any[:color,red,other...], circle, (0,0), 1.0)The unpacking procedure represented here as other... actually further unpacks each element of other, expecting each one to contain two values (a symbol and a value). kwfunc (also in Core) fetches the kwsorter for the called function. Notice that the original circle function is passed through, to handle closures." -}, - -{ - "location": "devdocs/functions.html#Compiler-efficiency-issues-1", - "page": "Julia Functions", - "title": "Compiler efficiency issues", - "category": "section", - "text": "Generating a new type for every function has potentially serious consequences for compiler resource use when combined with Julia\'s \"specialize on all arguments by default\" design. Indeed, the initial implementation of this design suffered from much longer build and test times, higher memory use, and a system image nearly 2x larger than the baseline. In a naive implementation, the problem is bad enough to make the system nearly unusable. Several significant optimizations were needed to make the design practical.The first issue is excessive specialization of functions for different values of function-valued arguments. Many functions simply \"pass through\" an argument to somewhere else, e.g. to another function or to a storage location. Such functions do not need to be specialized for every closure that might be passed in. Fortunately this case is easy to distinguish by simply considering whether a function calls one of its arguments (i.e. the argument appears in \"head position\" somewhere). Performance-critical higher-order functions like map certainly call their argument function and so will still be specialized as expected. This optimization is implemented by recording which arguments are called during the analyze-variables pass in the front end. When cache_method sees an argument in the Function type hierarchy passed to a slot declared as Any or Function, it pretends the slot was declared as ANY (the \"don\'t specialize\" hint). This heuristic seems to be extremely effective in practice.The next issue concerns the structure of method cache hash tables. Empirical studies show that the vast majority of dynamically-dispatched calls involve one or two arguments. In turn, many of these cases can be resolved by considering only the first argument. (Aside: proponents of single dispatch would not be surprised by this at all. However, this argument means \"multiple dispatch is easy to optimize in practice\", and that we should therefore use it, not \"we should use single dispatch\"!) So the method cache uses the type of the first argument as its primary key. Note, however, that this corresponds to the second element of the tuple type for a function call (the first element being the type of the function itself). Typically, type variation in head position is extremely low – indeed, the majority of functions belong to singleton types with no parameters. However, this is not the case for constructors, where a single method table holds constructors for every type. Therefore the Type method table is special-cased to use the first tuple type element instead of the second.The front end generates type declarations for all closures. Initially, this was implemented by generating normal type declarations. However, this produced an extremely large number of constructors, all of which were trivial (simply passing all arguments through to new). Since methods are partially ordered, inserting all of these methods is O(n^2), plus there are just too many of them to keep around. This was optimized by generating composite_type expressions directly (bypassing default constructor generation), and using new directly to create closure instances. Not the prettiest thing ever, but you do what you gotta do.The next problem was the @test macro, which generated a 0-argument closure for each test case. This is not really necessary, since each test case is simply run once in place. Therefore I modified @test to expand to a try-catch block that records the test result (true, false, or exception raised) and calls the test suite handler on it.However this caused a new problem. When many tests are grouped together in a single function, e.g. a single top level expression, or some other test grouping function, that function could have a very large number of exception handlers. This triggered a kind of dataflow analysis worst case, where type inference spun around for minutes enumerating possible paths through the forest of handlers. This was fixed by simply bailing out of type inference when it encounters more than some number of handlers (currently 25). Presumably no performance-critical function will have more than 25 exception handlers. If one ever does, I\'m willing to raise the limit to 26.A minor issue occurs during the bootstrap process due to storing all constructors in a single method table. In the second bootstrap step, where inference.ji is compiled using inference0.ji, constructors for inference0\'s types remain in the table, so there are still references to the old inference module and inference.ji is 2x the size it should be. This was fixed in dump.c by filtering definitions from \"replaced modules\" out of method tables and caches before saving a system image. A \"replaced module\" is one that satisfies the condition m != jl_get_global(m->parent, m->name) – in other words, some newer module has taken its name and place.Another type inference worst case was triggered by the following code from the QuadGK.jl package, formerly part of Base:function do_quadgk(f, s, n, ::Type{Tw}, abstol, reltol, maxevals, nrm) where Tw\n if eltype(s) <: Real # check for infinite or semi-infinite intervals\n s1 = s[1]; s2 = s[end]; inf1 = isinf(s1); inf2 = isinf(s2)\n if inf1 || inf2\n if inf1 && inf2 # x = t/(1-t^2) coordinate transformation\n return do_quadgk(t -> begin t2 = t*t; den = 1 / (1 - t2);\n f(t*den) * (1+t2)*den*den; end,\n map(x -> isinf(x) ? copysign(one(x), x) : 2x / (1+hypot(1,2x)), s),\n n, Tw, abstol, reltol, maxevals, nrm)\n end\n s0,si = inf1 ? (s2,s1) : (s1,s2)\n if si < 0 # x = s0 - t/(1-t)\n return do_quadgk(t -> begin den = 1 / (1 - t);\n f(s0 - t*den) * den*den; end,\n reverse!(map(x -> 1 / (1 + 1 / (s0 - x)), s)),\n n, Tw, abstol, reltol, maxevals, nrm)\n else # x = s0 + t/(1-t)\n return do_quadgk(t -> begin den = 1 / (1 - t);\n f(s0 + t*den) * den*den; end,\n map(x -> 1 / (1 + 1 / (x - s0)), s),\n n, Tw, abstol, reltol, maxevals, nrm)\n end\n end\n endThis code has a 3-way tail recursion, where each call wraps the current function argument f in a different new closure. Inference must consider 3^n (where n is the call depth) possible signatures. This blows up way too quickly, so logic was added to typeinf_uncached to immediately widen any argument that is a subtype of Function and that grows in depth down the stack." -}, - -{ - "location": "devdocs/cartesian.html#", - "page": "Base.Cartesian", - "title": "Base.Cartesian", - "category": "page", - "text": "" -}, - -{ - "location": "devdocs/cartesian.html#Base.Cartesian-1", - "page": "Base.Cartesian", - "title": "Base.Cartesian", - "category": "section", - "text": "The (non-exported) Cartesian module provides macros that facilitate writing multidimensional algorithms. It is hoped that Cartesian will not, in the long term, be necessary; however, at present it is one of the few ways to write compact and performant multidimensional code." -}, - -{ - "location": "devdocs/cartesian.html#Principles-of-usage-1", - "page": "Base.Cartesian", - "title": "Principles of usage", - "category": "section", - "text": "A simple example of usage is:@nloops 3 i A begin\n s += @nref 3 A i\nendwhich generates the following code:for i_3 = 1:size(A,3)\n for i_2 = 1:size(A,2)\n for i_1 = 1:size(A,1)\n s += A[i_1,i_2,i_3]\n end\n end\nendIn general, Cartesian allows you to write generic code that contains repetitive elements, like the nested loops in this example. Other applications include repeated expressions (e.g., loop unwinding) or creating function calls with variable numbers of arguments without using the \"splat\" construct (i...)." -}, - -{ - "location": "devdocs/cartesian.html#Basic-syntax-1", - "page": "Base.Cartesian", - "title": "Basic syntax", - "category": "section", - "text": "The (basic) syntax of @nloops is as follows:The first argument must be an integer (not a variable) specifying the number of loops.\nThe second argument is the symbol-prefix used for the iterator variable. Here we used i, and variables i_1, i_2, i_3 were generated.\nThe third argument specifies the range for each iterator variable. If you use a variable (symbol) here, it\'s taken as 1:size(A,dim). More flexibly, you can use the anonymous-function expression syntax described below.\nThe last argument is the body of the loop. Here, that\'s what appears between the begin...end.There are some additional features of @nloops described in the reference section.@nref follows a similar pattern, generating A[i_1,i_2,i_3] from @nref 3 A i. The general practice is to read from left to right, which is why @nloops is @nloops 3 i A expr (as in for i_2 = 1:size(A,2), where i_2 is to the left and the range is to the right) whereas @nref is @nref 3 A i (as in A[i_1,i_2,i_3], where the array comes first).If you\'re developing code with Cartesian, you may find that debugging is easier when you examine the generated code, using macroexpand:DocTestSetup = quote\n import Base.Cartesian: @nref\nendjulia> macroexpand(:(@nref 2 A i))\n:(A[i_1, i_2])DocTestSetup = nothing" -}, - -{ - "location": "devdocs/cartesian.html#Supplying-the-number-of-expressions-1", - "page": "Base.Cartesian", - "title": "Supplying the number of expressions", - "category": "section", - "text": "The first argument to both of these macros is the number of expressions, which must be an integer. When you\'re writing a function that you intend to work in multiple dimensions, this may not be something you want to hard-code. If you\'re writing code that you need to work with older Julia versions, currently you should use the @ngenerate macro described in an older version of this documentation.Starting in Julia 0.4-pre, the recommended approach is to use a @generated function. Here\'s an example:@generated function mysum(A::Array{T,N}) where {T,N}\n quote\n s = zero(T)\n @nloops $N i A begin\n s += @nref $N A i\n end\n s\n end\nendNaturally, you can also prepare expressions or perform calculations before the quote block." -}, - -{ - "location": "devdocs/cartesian.html#Anonymous-function-expressions-as-macro-arguments-1", - "page": "Base.Cartesian", - "title": "Anonymous-function expressions as macro arguments", - "category": "section", - "text": "Perhaps the single most powerful feature in Cartesian is the ability to supply anonymous-function expressions that get evaluated at parsing time. Let\'s consider a simple example:@nexprs 2 j->(i_j = 1)@nexprs generates n expressions that follow a pattern. This code would generate the following statements:i_1 = 1\ni_2 = 1In each generated statement, an \"isolated\" j (the variable of the anonymous function) gets replaced by values in the range 1:2. Generally speaking, Cartesian employs a LaTeX-like syntax. This allows you to do math on the index j. Here\'s an example computing the strides of an array:s_1 = 1\n@nexprs 3 j->(s_{j+1} = s_j * size(A, j))would generate expressionss_1 = 1\ns_2 = s_1 * size(A, 1)\ns_3 = s_2 * size(A, 2)\ns_4 = s_3 * size(A, 3)Anonymous-function expressions have many uses in practice." -}, - -{ - "location": "devdocs/cartesian.html#Base.Cartesian.@nloops", - "page": "Base.Cartesian", - "title": "Base.Cartesian.@nloops", - "category": "macro", - "text": "@nloops N itersym rangeexpr bodyexpr\n@nloops N itersym rangeexpr preexpr bodyexpr\n@nloops N itersym rangeexpr preexpr postexpr bodyexpr\n\nGenerate N nested loops, using itersym as the prefix for the iteration variables. rangeexpr may be an anonymous-function expression, or a simple symbol var in which case the range is indices(var, d) for dimension d.\n\nOptionally, you can provide \"pre\" and \"post\" expressions. These get executed first and last, respectively, in the body of each loop. For example:\n\n@nloops 2 i A d -> j_d = min(i_d, 5) begin\n s += @nref 2 A j\nend\n\nwould generate:\n\nfor i_2 = indices(A, 2)\n j_2 = min(i_2, 5)\n for i_1 = indices(A, 1)\n j_1 = min(i_1, 5)\n s += A[j_1, j_2]\n end\nend\n\nIf you want just a post-expression, supply nothing for the pre-expression. Using parentheses and semicolons, you can supply multi-statement expressions.\n\n\n\n" -}, - -{ - "location": "devdocs/cartesian.html#Base.Cartesian.@nref", - "page": "Base.Cartesian", - "title": "Base.Cartesian.@nref", - "category": "macro", - "text": "@nref N A indexexpr\n\nGenerate expressions like A[i_1, i_2, ...]. indexexpr can either be an iteration-symbol prefix, or an anonymous-function expression.\n\njulia> @macroexpand Base.Cartesian.@nref 3 A i\n:(A[i_1, i_2, i_3])\n\n\n\n" -}, - -{ - "location": "devdocs/cartesian.html#Base.Cartesian.@nextract", - "page": "Base.Cartesian", - "title": "Base.Cartesian.@nextract", - "category": "macro", - "text": "@nextract N esym isym\n\nGenerate N variables esym_1, esym_2, ..., esym_N to extract values from isym. isym can be either a Symbol or anonymous-function expression.\n\n@nextract 2 x y would generate\n\nx_1 = y[1]\nx_2 = y[2]\n\nwhile @nextract 3 x d->y[2d-1] yields\n\nx_1 = y[1]\nx_2 = y[3]\nx_3 = y[5]\n\n\n\n" -}, - -{ - "location": "devdocs/cartesian.html#Base.Cartesian.@nexprs", - "page": "Base.Cartesian", - "title": "Base.Cartesian.@nexprs", - "category": "macro", - "text": "@nexprs N expr\n\nGenerate N expressions. expr should be an anonymous-function expression.\n\njulia> @macroexpand Base.Cartesian.@nexprs 4 i -> y[i] = A[i+j]\nquote\n y[1] = A[1 + j]\n y[2] = A[2 + j]\n y[3] = A[3 + j]\n y[4] = A[4 + j]\nend\n\n\n\n" -}, - -{ - "location": "devdocs/cartesian.html#Base.Cartesian.@ncall", - "page": "Base.Cartesian", - "title": "Base.Cartesian.@ncall", - "category": "macro", - "text": "@ncall N f sym...\n\nGenerate a function call expression. sym represents any number of function arguments, the last of which may be an anonymous-function expression and is expanded into N arguments.\n\nFor example @ncall 3 func a generates\n\nfunc(a_1, a_2, a_3)\n\nwhile @ncall 2 func a b i->c[i] yields\n\nfunc(a, b, c[1], c[2])\n\n\n\n" -}, - -{ - "location": "devdocs/cartesian.html#Base.Cartesian.@ntuple", - "page": "Base.Cartesian", - "title": "Base.Cartesian.@ntuple", - "category": "macro", - "text": "@ntuple N expr\n\nGenerates an N-tuple. @ntuple 2 i would generate (i_1, i_2), and @ntuple 2 k->k+1 would generate (2,3).\n\n\n\n" -}, - -{ - "location": "devdocs/cartesian.html#Base.Cartesian.@nall", - "page": "Base.Cartesian", - "title": "Base.Cartesian.@nall", - "category": "macro", - "text": "@nall N expr\n\nCheck whether all of the expressions generated by the anonymous-function expression expr evaluate to true.\n\n@nall 3 d->(i_d > 1) would generate the expression (i_1 > 1 && i_2 > 1 && i_3 > 1). This can be convenient for bounds-checking.\n\n\n\n" -}, - -{ - "location": "devdocs/cartesian.html#Base.Cartesian.@nany", - "page": "Base.Cartesian", - "title": "Base.Cartesian.@nany", - "category": "macro", - "text": "@nany N expr\n\nCheck whether any of the expressions generated by the anonymous-function expression expr evaluate to true.\n\n@nany 3 d->(i_d > 1) would generate the expression (i_1 > 1 || i_2 > 1 || i_3 > 1).\n\n\n\n" -}, - -{ - "location": "devdocs/cartesian.html#Base.Cartesian.@nif", - "page": "Base.Cartesian", - "title": "Base.Cartesian.@nif", - "category": "macro", - "text": "@nif N conditionexpr expr\n@nif N conditionexpr expr elseexpr\n\nGenerates a sequence of if ... elseif ... else ... end statements. For example:\n\n@nif 3 d->(i_d >= size(A,d)) d->(error(\"Dimension \", d, \" too big\")) d->println(\"All OK\")\n\nwould generate:\n\nif i_1 > size(A, 1)\n error(\"Dimension \", 1, \" too big\")\nelseif i_2 > size(A, 2)\n error(\"Dimension \", 2, \" too big\")\nelse\n println(\"All OK\")\nend\n\n\n\n" -}, - -{ - "location": "devdocs/cartesian.html#dev-cartesian-reference-1", - "page": "Base.Cartesian", - "title": "Macro reference", - "category": "section", - "text": "Base.Cartesian.@nloops\nBase.Cartesian.@nref\nBase.Cartesian.@nextract\nBase.Cartesian.@nexprs\nBase.Cartesian.@ncall\nBase.Cartesian.@ntuple\nBase.Cartesian.@nall\nBase.Cartesian.@nany\nBase.Cartesian.@nif" -}, - -{ - "location": "devdocs/meta.html#", - "page": "Talking to the compiler (the :meta mechanism)", - "title": "Talking to the compiler (the :meta mechanism)", - "category": "page", - "text": "" -}, - -{ - "location": "devdocs/meta.html#Talking-to-the-compiler-(the-:meta-mechanism)-1", - "page": "Talking to the compiler (the :meta mechanism)", - "title": "Talking to the compiler (the :meta mechanism)", - "category": "section", - "text": "In some circumstances, one might wish to provide hints or instructions that a given block of code has special properties: you might always want to inline it, or you might want to turn on special compiler optimization passes. Starting with version 0.4, Julia has a convention that these instructions can be placed inside a :meta expression, which is typically (but not necessarily) the first expression in the body of a function.:meta expressions are created with macros. As an example, consider the implementation of the @inline macro:macro inline(ex)\n esc(isa(ex, Expr) ? pushmeta!(ex, :inline) : ex)\nendHere, ex is expected to be an expression defining a function. A statement like this:@inline function myfunction(x)\n x*(x+3)\nendgets turned into an expression like this:quote\n function myfunction(x)\n Expr(:meta, :inline)\n x*(x+3)\n end\nendBase.pushmeta!(ex, :symbol, args...) appends :symbol to the end of the :meta expression, creating a new :meta expression if necessary. If args is specified, a nested expression containing :symbol and these arguments is appended instead, which can be used to specify additional information.To use the metadata, you have to parse these :meta expressions. If your implementation can be performed within Julia, Base.popmeta! is very handy: Base.popmeta!(body, :symbol) will scan a function body expression (one without the function signature) for the first :meta expression containing :symbol, extract any arguments, and return a tuple (found::Bool, args::Array{Any}). If the metadata did not have any arguments, or :symbol was not found, the args array will be empty.Not yet provided is a convenient infrastructure for parsing :meta expressions from C++." -}, - -{ - "location": "devdocs/subarrays.html#", - "page": "SubArrays", - "title": "SubArrays", - "category": "page", - "text": "" -}, - -{ - "location": "devdocs/subarrays.html#SubArrays-1", - "page": "SubArrays", - "title": "SubArrays", - "category": "section", - "text": "Julia\'s SubArray type is a container encoding a \"view\" of a parent AbstractArray. This page documents some of the design principles and implementation of SubArrays." -}, - -{ - "location": "devdocs/subarrays.html#Indexing:-cartesian-vs.-linear-indexing-1", - "page": "SubArrays", - "title": "Indexing: cartesian vs. linear indexing", - "category": "section", - "text": "Broadly speaking, there are two main ways to access data in an array. The first, often called cartesian indexing, uses N indexes for an N -dimensional AbstractArray. For example, a matrix A (2-dimensional) can be indexed in cartesian style as A[i,j]. The second indexing method, referred to as linear indexing, uses a single index even for higher-dimensional objects. For example, if A = reshape(1:12, 3, 4), then the expression A[5] returns the value 5. Julia allows you to combine these styles of indexing: for example, a 3d array A3 can be indexed as A3[i,j], in which case i is interpreted as a cartesian index for the first dimension, and j is a linear index over dimensions 2 and 3.For Arrays, linear indexing appeals to the underlying storage format: an array is laid out as a contiguous block of memory, and hence the linear index is just the offset (+1) of the corresponding entry relative to the beginning of the array. However, this is not true for many other AbstractArray types: examples include SparseMatrixCSC, arrays that require some kind of computation (such as interpolation), and the type under discussion here, SubArray. For these types, the underlying information is more naturally described in terms of cartesian indexes.You can manually convert from a cartesian index to a linear index with sub2ind, and vice versa using ind2sub. getindex and setindex! functions for AbstractArray types may include similar operations.While converting from a cartesian index to a linear index is fast (it\'s just multiplication and addition), converting from a linear index to a cartesian index is very slow: it relies on the div operation, which is one of the slowest low-level operations you can perform with a CPU. For this reason, any code that deals with AbstractArray types is best designed in terms of cartesian, rather than linear, indexing." -}, - -{ - "location": "devdocs/subarrays.html#Index-replacement-1", - "page": "SubArrays", - "title": "Index replacement", - "category": "section", - "text": "Consider making 2d slices of a 3d array:S1 = view(A, :, 5, 2:6)\nS2 = view(A, 5, :, 2:6)view drops \"singleton\" dimensions (ones that are specified by an Int), so both S1 and S2 are two-dimensional SubArrays. Consequently, the natural way to index these is with S1[i,j]. To extract the value from the parent array A, the natural approach is to replace S1[i,j] with A[i,5,(2:6)[j]] and S2[i,j] with A[5,i,(2:6)[j]].The key feature of the design of SubArrays is that this index replacement can be performed without any runtime overhead." -}, - -{ - "location": "devdocs/subarrays.html#SubArray-design-1", - "page": "SubArrays", - "title": "SubArray design", - "category": "section", - "text": "" -}, - -{ - "location": "devdocs/subarrays.html#Type-parameters-and-fields-1", - "page": "SubArrays", - "title": "Type parameters and fields", - "category": "section", - "text": "The strategy adopted is first and foremost expressed in the definition of the type:struct SubArray{T,N,P,I,L} <: AbstractArray{T,N}\n parent::P\n indexes::I\n offset1::Int # for linear indexing and pointer, only valid when L==true\n stride1::Int # used only for linear indexing\n ...\nendSubArray has 5 type parameters. The first two are the standard element type and dimensionality. The next is the type of the parent AbstractArray. The most heavily-used is the fourth parameter, a Tuple of the types of the indices for each dimension. The final one, L, is only provided as a convenience for dispatch; it\'s a boolean that represents whether the index types support fast linear indexing. More on that later.If in our example above A is a Array{Float64, 3}, our S1 case above would be a SubArray{Int64,2,Array{Int64,3},Tuple{Colon,Int64,UnitRange{Int64}},false}. Note in particular the tuple parameter, which stores the types of the indices used to create S1. Likewise,julia> S1.indexes\n(Colon(),5,2:6)Storing these values allows index replacement, and having the types encoded as parameters allows one to dispatch to efficient algorithms." -}, - -{ - "location": "devdocs/subarrays.html#Index-translation-1", - "page": "SubArrays", - "title": "Index translation", - "category": "section", - "text": "Performing index translation requires that you do different things for different concrete SubArray types. For example, for S1, one needs to apply the i,j indices to the first and third dimensions of the parent array, whereas for S2 one needs to apply them to the second and third. The simplest approach to indexing would be to do the type-analysis at runtime:parentindexes = Array{Any}(0)\nfor thisindex in S.indexes\n ...\n if isa(thisindex, Int)\n # Don\'t consume one of the input indexes\n push!(parentindexes, thisindex)\n elseif isa(thisindex, AbstractVector)\n # Consume an input index\n push!(parentindexes, thisindex[inputindex[j]])\n j += 1\n elseif isa(thisindex, AbstractMatrix)\n # Consume two input indices\n push!(parentindexes, thisindex[inputindex[j], inputindex[j+1]])\n j += 2\n elseif ...\nend\nS.parent[parentindexes...]Unfortunately, this would be disastrous in terms of performance: each element access would allocate memory, and involves the running of a lot of poorly-typed code.The better approach is to dispatch to specific methods to handle each type of stored index. That\'s what reindex does: it dispatches on the type of the first stored index and consumes the appropriate number of input indices, and then it recurses on the remaining indices. In the case of S1, this expands toBase.reindex(S1, S1.indexes, (i, j)) == (i, S1.indexes[2], S1.indexes[3][j])for any pair of indices (i,j) (except CartesianIndexs and arrays thereof, see below).This is the core of a SubArray; indexing methods depend upon reindex to do this index translation. Sometimes, though, we can avoid the indirection and make it even faster." -}, - -{ - "location": "devdocs/subarrays.html#Linear-indexing-1", - "page": "SubArrays", - "title": "Linear indexing", - "category": "section", - "text": "Linear indexing can be implemented efficiently when the entire array has a single stride that separates successive elements, starting from some offset. This means that we can pre-compute these values and represent linear indexing simply as an addition and multiplication, avoiding the indirection of reindex and (more importantly) the slow computation of the cartesian coordinates entirely.For SubArray types, the availability of efficient linear indexing is based purely on the types of the indices, and does not depend on values like the size of the parent array. You can ask whether a given set of indices supports fast linear indexing with the internal Base.viewindexing function:julia> Base.viewindexing(S1.indexes)\nIndexCartesian()\n\njulia> Base.viewindexing(S2.indexes)\nIndexLinear()This is computed during construction of the SubArray and stored in the L type parameter as a boolean that encodes fast linear indexing support. While not strictly necessary, it means that we can define dispatch directly on SubArray{T,N,A,I,true} without any intermediaries.Since this computation doesn\'t depend on runtime values, it can miss some cases in which the stride happens to be uniform:julia> A = reshape(1:4*2, 4, 2)\n4×2 Base.ReshapedArray{Int64,2,UnitRange{Int64},Tuple{}}:\n 1 5\n 2 6\n 3 7\n 4 8\n\njulia> diff(A[2:2:4,:][:])\n3-element Array{Int64,1}:\n 2\n 2\n 2A view constructed as view(A, 2:2:4, :) happens to have uniform stride, and therefore linear indexing indeed could be performed efficiently. However, success in this case depends on the size of the array: if the first dimension instead were odd,julia> A = reshape(1:5*2, 5, 2)\n5×2 Base.ReshapedArray{Int64,2,UnitRange{Int64},Tuple{}}:\n 1 6\n 2 7\n 3 8\n 4 9\n 5 10\n\njulia> diff(A[2:2:4,:][:])\n3-element Array{Int64,1}:\n 2\n 3\n 2then A[2:2:4,:] does not have uniform stride, so we cannot guarantee efficient linear indexing. Since we have to base this decision based purely on types encoded in the parameters of the SubArray, S = view(A, 2:2:4, :) cannot implement efficient linear indexing." -}, - -{ - "location": "devdocs/subarrays.html#A-few-details-1", - "page": "SubArrays", - "title": "A few details", - "category": "section", - "text": "Note that the Base.reindex function is agnostic to the types of the input indices; it simply determines how and where the stored indices should be reindexed. It not only supports integer indices, but it supports non-scalar indexing, too. This means that views of views don\'t need two levels of indirection; they can simply re-compute the indices into the original parent array!\nHopefully by now it\'s fairly clear that supporting slices means that the dimensionality, given by the parameter N, is not necessarily equal to the dimensionality of the parent array or the length of the indexes tuple. Neither do user-supplied indices necessarily line up with entries in the indexes tuple (e.g., the second user-supplied index might correspond to the third dimension of the parent array, and the third element in the indexes tuple).\nWhat might be less obvious is that the dimensionality of the stored parent array must be equal to the number of effective indices in the indexes tuple. Some examples:\nA = reshape(1:35, 5, 7) # A 2d parent Array\nS = view(A, 2:7) # A 1d view created by linear indexing\nS = view(A, :, :, 1:1) # Appending extra indices is supported\nNaively, you\'d think you could just set S.parent = A and S.indexes = (:,:,1:1), but supporting this dramatically complicates the reindexing process, especially for views of views. Not only do you need to dispatch on the types of the stored indices, but you need to examine whether a given index is the final one and \"merge\" any remaining stored indices together. This is not an easy task, and even worse: it\'s slow since it implicitly depends upon linear indexing.\nFortunately, this is precisely the computation that ReshapedArray performs, and it does so linearly if possible. Consequently, view ensures that the parent array is the appropriate dimensionality for the given indices by reshaping it if needed. The inner SubArray constructor ensures that this invariant is satisfied.\nCartesianIndex and arrays thereof throw a nasty wrench into the reindex scheme. Recall that reindex simply dispatches on the type of the stored indices in order to determine how many passed indices should be used and where they should go. But with CartesianIndex, there\'s no longer a one-to-one correspondence between the number of passed arguments and the number of dimensions that they index into. If we return to the above example of Base.reindex(S1, S1.indexes, (i, j)), you can see that the expansion is incorrect for i, j = CartesianIndex(), CartesianIndex(2,1). It should skip the CartesianIndex() entirely and return:\n(CartesianIndex(2,1)[1], S1.indexes[2], S1.indexes[3][CartesianIndex(2,1)[2]])\nInstead, though, we get:\n(CartesianIndex(), S1.indexes[2], S1.indexes[3][CartesianIndex(2,1)])\nDoing this correctly would require combined dispatch on both the stored and passed indices across all combinations of dimensionalities in an intractable manner. As such, reindex must never be called with CartesianIndex indices. Fortunately, the scalar case is easily handled by first flattening the CartesianIndex arguments to plain integers. Arrays of CartesianIndex, however, cannot be split apart into orthogonal pieces so easily. Before attempting to use reindex, view must ensure that there are no arrays of CartesianIndex in the argument list. If there are, it can simply \"punt\" by avoiding the reindex calculation entirely, constructing a nested SubArray with two levels of indirection instead." -}, - -{ - "location": "devdocs/sysimg.html#", - "page": "System Image Building", - "title": "System Image Building", - "category": "page", - "text": "" -}, - -{ - "location": "devdocs/sysimg.html#System-Image-Building-1", - "page": "System Image Building", - "title": "System Image Building", - "category": "section", - "text": "" -}, - -{ - "location": "devdocs/sysimg.html#BuildSysImg.build_sysimg", - "page": "System Image Building", - "title": "BuildSysImg.build_sysimg", - "category": "function", - "text": "build_sysimg(sysimg_path=default_sysimg_path(), cpu_target=\"native\", userimg_path=nothing; force=false)\n\nRebuild the system image. Store it in sysimg_path, which defaults to a file named sys.ji that sits in the same folder as libjulia.{so,dylib}, except on Windows where it defaults to JULIA_HOME/../lib/julia/sys.ji. Use the cpu instruction set given by cpu_target. Valid CPU targets are the same as for the -C option to julia, or the -march option to gcc. Defaults to native, which means to use all CPU instructions available on the current processor. Include the user image file given by userimg_path, which should contain directives such as using MyPackage to include that package in the new system image. New system image will not replace an older image unless force is set to true.\n\n\n\n" -}, - -{ - "location": "devdocs/sysimg.html#Building-the-Julia-system-image-1", - "page": "System Image Building", - "title": "Building the Julia system image", - "category": "section", - "text": "Julia ships with a preparsed system image containing the contents of the Base module, named sys.ji. This file is also precompiled into a shared library called sys.{so,dll,dylib} on as many platforms as possible, so as to give vastly improved startup times. On systems that do not ship with a precompiled system image file, one can be generated from the source files shipped in Julia\'s DATAROOTDIR/julia/base folder.This operation is useful for multiple reasons. A user may:Build a precompiled shared library system image on a platform that did not ship with one, thereby improving startup times.\nModify Base, rebuild the system image and use the new Base next time Julia is started.\nInclude a userimg.jl file that includes packages into the system image, thereby creating a system image that has packages embedded into the startup environment.Julia now ships with a script that automates the tasks of building the system image, wittingly named build_sysimg.jl that lives in DATAROOTDIR/julia/. That is, to include it into a current Julia session, type:include(joinpath(JULIA_HOME, Base.DATAROOTDIR, \"julia\", \"build_sysimg.jl\"))This will include a build_sysimg() function:BuildSysImg.build_sysimgNote that this file can also be run as a script itself, with command line arguments taking the place of arguments passed to the build_sysimg function. For example, to build a system image in /tmp/sys.{so,dll,dylib}, with the core2 CPU instruction set, a user image of ~/userimg.jl and force set to true, one would execute:julia build_sysimg.jl /tmp/sys core2 ~/userimg.jl --force" -}, - -{ - "location": "devdocs/llvm.html#", - "page": "Working with LLVM", - "title": "Working with LLVM", - "category": "page", - "text": "" -}, - -{ - "location": "devdocs/llvm.html#Working-with-LLVM-1", - "page": "Working with LLVM", - "title": "Working with LLVM", - "category": "section", - "text": "This is not a replacement for the LLVM documentation, but a collection of tips for working on LLVM for Julia." -}, - -{ - "location": "devdocs/llvm.html#Overview-of-Julia-to-LLVM-Interface-1", - "page": "Working with LLVM", - "title": "Overview of Julia to LLVM Interface", - "category": "section", - "text": "Julia statically links in LLVM by default. Build with USE_LLVM_SHLIB=1 to link dynamically.The code for lowering Julia AST to LLVM IR or interpreting it directly is in directory src/.File Description\nbuiltins.c Builtin functions\nccall.cpp Lowering ccall\ncgutils.cpp Lowering utilities, notably for array and tuple accesses\ncodegen.cpp Top-level of code generation, pass list, lowering builtins\ndebuginfo.cpp Tracks debug information for JIT code\ndisasm.cpp Handles native object file and JIT code diassembly\ngf.c Generic functions\nintrinsics.cpp Lowering intrinsics\nllvm-simdloop.cpp Custom LLVM pass for @simd\nsys.c I/O and operating system utility functionsSome of the .cpp files form a group that compile to a single object.The difference between an intrinsic and a builtin is that a builtin is a first class function that can be used like any other Julia function. An intrinsic can operate only on unboxed data, and therefore its arguments must be statically typed." -}, - -{ - "location": "devdocs/llvm.html#Alias-Analysis-1", - "page": "Working with LLVM", - "title": "Alias Analysis", - "category": "section", - "text": "Julia currently uses LLVM\'s Type Based Alias Analysis. To find the comments that document the inclusion relationships, look for static MDNode* in src/codegen.cpp.The -O option enables LLVM\'s Basic Alias Analysis." -}, - -{ - "location": "devdocs/llvm.html#Building-Julia-with-a-different-version-of-LLVM-1", - "page": "Working with LLVM", - "title": "Building Julia with a different version of LLVM", - "category": "section", - "text": "The default version of LLVM is specified in deps/Versions.make. You can override it by creating a file called Make.user in the top-level directory and adding a line to it such as:LLVM_VER = 3.5.0Besides the LLVM release numerals, you can also use LLVM_VER = svn to bulid against the latest development version of LLVM." -}, - -{ - "location": "devdocs/llvm.html#Passing-options-to-LLVM-1", - "page": "Working with LLVM", - "title": "Passing options to LLVM", - "category": "section", - "text": "You can pass options to LLVM using debug builds of Julia. To create a debug build, run make debug. The resulting executable is usr/bin/julia-debug. You can pass LLVM options to this executable via the environment variable JULIA_LLVM_ARGS. Here are example settings using bash syntax:export JULIA_LLVM_ARGS = -print-after-all dumps IR after each pass.\nexport JULIA_LLVM_ARGS = -debug-only=loop-vectorize dumps LLVM DEBUG(...) diagnostics for loop vectorizer if you built Julia with LLVM_ASSERTIONS=1. Otherwise you will get warnings about \"Unknown command line argument\". Counter-intuitively, building Julia with LLVM_DEBUG=1 is not enough to dump DEBUG diagnostics from a pass." -}, - -{ - "location": "devdocs/llvm.html#Improving-LLVM-optimizations-for-Julia-1", - "page": "Working with LLVM", - "title": "Improving LLVM optimizations for Julia", - "category": "section", - "text": "Improving LLVM code generation usually involves either changing Julia lowering to be more friendly to LLVM\'s passes, or improving a pass.If you are planning to improve a pass, be sure to read the LLVM developer policy. The best strategy is to create a code example in a form where you can use LLVM\'s opt tool to study it and the pass of interest in isolation.Create an example Julia code of interest.\nUse JULIA_LLVM_ARGS = -print-after-all to dump the IR.\nPick out the IR at the point just before the pass of interest runs.\nStrip the debug metadata and fix up the TBAA metadata by hand.The last step is labor intensive. Suggestions on a better way would be appreciated." -}, - -{ - "location": "devdocs/stdio.html#", - "page": "printf() and stdio in the Julia runtime", - "title": "printf() and stdio in the Julia runtime", - "category": "page", - "text": "" -}, - -{ - "location": "devdocs/stdio.html#printf()-and-stdio-in-the-Julia-runtime-1", - "page": "printf() and stdio in the Julia runtime", - "title": "printf() and stdio in the Julia runtime", - "category": "section", - "text": "" -}, - -{ - "location": "devdocs/stdio.html#Libuv-wrappers-for-stdio-1", - "page": "printf() and stdio in the Julia runtime", - "title": "Libuv wrappers for stdio", - "category": "section", - "text": "julia.h defines libuv wrappers for the stdio.h streams:uv_stream_t *JL_STDIN;\nuv_stream_t *JL_STDOUT;\nuv_stream_t *JL_STDERR;... and corresponding output functions:int jl_printf(uv_stream_t *s, const char *format, ...);\nint jl_vprintf(uv_stream_t *s, const char *format, va_list args);These printf functions are used by the .c files in the src/ and ui/ directories wherever stdio is needed to ensure that output buffering is handled in a unified way.In special cases, like signal handlers, where the full libuv infrastructure is too heavy, jl_safe_printf() can be used to write(2) directly to STDERR_FILENO:void jl_safe_printf(const char *str, ...);" -}, - -{ - "location": "devdocs/stdio.html#Interface-between-JL_STD*-and-Julia-code-1", - "page": "printf() and stdio in the Julia runtime", - "title": "Interface between JL_STD* and Julia code", - "category": "section", - "text": "Base.STDIN, Base.STDOUT and Base.STDERR are bound to the JL_STD* libuv streams defined in the runtime.Julia\'s __init__() function (in base/sysimg.jl) calls reinit_stdio() (in base/stream.jl) to create Julia objects for Base.STDIN, Base.STDOUT and Base.STDERR.reinit_stdio() uses ccall to retrieve pointers to JL_STD* and calls jl_uv_handle_type() to inspect the type of each stream. It then creates a Julia Base.IOStream, Base.TTY or Base.PipeEndpoint object to represent each stream, e.g.:$ julia -e \'println(typeof((STDIN, STDOUT, STDERR)))\'\nTuple{Base.TTY,Base.TTY,Base.TTY}\n\n$ julia -e \'println(typeof((STDIN, STDOUT, STDERR)))\' < /dev/null 2>/dev/null\nTuple{IOStream,Base.TTY,IOStream}\n\n$ echo hello | julia -e \'println(typeof((STDIN, STDOUT, STDERR)))\' | cat\nTuple{Base.PipeEndpoint,Base.PipeEndpoint,Base.TTY}The Base.read() and Base.write() methods for these streams use ccall to call libuv wrappers in src/jl_uv.c, e.g.:stream.jl: function write(s::IO, p::Ptr, nb::Integer)\n -> ccall(:jl_uv_write, ...)\n jl_uv.c: -> int jl_uv_write(uv_stream_t *stream, ...)\n -> uv_write(uvw, stream, buf, ...)" -}, - -{ - "location": "devdocs/stdio.html#printf()-during-initialization-1", - "page": "printf() and stdio in the Julia runtime", - "title": "printf() during initialization", - "category": "section", - "text": "The libuv streams relied upon by jl_printf() etc., are not available until midway through initialization of the runtime (see init.c, init_stdio()). Error messages or warnings that need to be printed before this are routed to the standard C library fwrite() function by the following mechanism:In sys.c, the JL_STD* stream pointers are statically initialized to integer constants: STD*_FILENO (0, 1 and 2). In jl_uv.c the jl_uv_puts() function checks its uv_stream_t* stream argument and calls fwrite() if stream is set to STDOUT_FILENO or STDERR_FILENO.This allows for uniform use of jl_printf() throughout the runtime regardless of whether or not any particular piece of code is reachable before initialization is complete." -}, - -{ - "location": "devdocs/stdio.html#Legacy-ios.c-library-1", - "page": "printf() and stdio in the Julia runtime", - "title": "Legacy ios.c library", - "category": "section", - "text": "The src/support/ios.c library is inherited from femtolisp. It provides cross-platform buffered file IO and in-memory temporary buffers.ios.c is still used by:src/flisp/*.c\nsrc/dump.c – for serialization file IO and for memory buffers.\nbase/iostream.jl – for file IO (see base/fs.jl for libuv equivalent).Use of ios.c in these modules is mostly self-contained and separated from the libuv I/O system. However, there is one place where femtolisp calls through to jl_printf() with a legacy ios_t stream.There is a hack in ios.h that makes the ios_t.bm field line up with the uv_stream_t.type and ensures that the values used for ios_t.bm to not overlap with valid UV_HANDLE_TYPE values. This allows uv_stream_t pointers to point to ios_t streams.This is needed because jl_printf() caller jl_static_show() is passed an ios_t stream by femtolisp\'s fl_print() function. Julia\'s jl_uv_puts() function has special handling for this:if (stream->type > UV_HANDLE_TYPE_MAX) {\n return ios_write((ios_t*)stream, str, n);\n}" -}, - -{ - "location": "devdocs/boundscheck.html#", - "page": "Bounds checking", - "title": "Bounds checking", - "category": "page", - "text": "" -}, - -{ - "location": "devdocs/boundscheck.html#Bounds-checking-1", - "page": "Bounds checking", - "title": "Bounds checking", - "category": "section", - "text": "Like many modern programming languages, Julia uses bounds checking to ensure program safety when accessing arrays. In tight inner loops or other performance critical situations, you may wish to skip these bounds checks to improve runtime performance. For instance, in order to emit vectorized (SIMD) instructions, your loop body cannot contain branches, and thus cannot contain bounds checks. Consequently, Julia includes an @inbounds(...) macro to tell the compiler to skip such bounds checks within the given block. For the built-in Array type, the magic happens inside the arrayref and arrayset intrinsics. User-defined array types instead use the @boundscheck(...) macro to achieve context-sensitive code selection." -}, - -{ - "location": "devdocs/boundscheck.html#Eliding-bounds-checks-1", - "page": "Bounds checking", - "title": "Eliding bounds checks", - "category": "section", - "text": "The @boundscheck(...) macro marks blocks of code that perform bounds checking. When such blocks appear inside of an @inbounds(...) block, the compiler removes these blocks. When the @boundscheck(...) is nested inside of a calling function containing an @inbounds(...), the compiler will remove the @boundscheck block only if it is inlined into the calling function. For example, you might write the method sum as:function sum(A::AbstractArray)\n r = zero(eltype(A))\n for i = 1:length(A)\n @inbounds r += A[i]\n end\n return r\nendWith a custom array-like type MyArray having:@inline getindex(A::MyArray, i::Real) = (@boundscheck checkbounds(A,i); A.data[to_index(i)])Then when getindex is inlined into sum, the call to checkbounds(A,i) will be elided. If your function contains multiple layers of inlining, only @boundscheck blocks at most one level of inlining deeper are eliminated. The rule prevents unintended changes in program behavior from code further up the stack." -}, - -{ - "location": "devdocs/boundscheck.html#Propagating-inbounds-1", - "page": "Bounds checking", - "title": "Propagating inbounds", - "category": "section", - "text": "There may be certain scenarios where for code-organization reasons you want more than one layer between the @inbounds and @boundscheck declarations. For instance, the default getindex methods have the chain getindex(A::AbstractArray, i::Real) calls getindex(IndexStyle(A), A, i) calls _getindex(::IndexLinear, A, i).To override the \"one layer of inlining\" rule, a function may be marked with @propagate_inbounds to propagate an inbounds context (or out of bounds context) through one additional layer of inlining." -}, - -{ - "location": "devdocs/boundscheck.html#The-bounds-checking-call-hierarchy-1", - "page": "Bounds checking", - "title": "The bounds checking call hierarchy", - "category": "section", - "text": "The overall hierarchy is:checkbounds(A, I...) which calls\ncheckbounds(Bool, A, I...) which calls\ncheckbounds_indices(Bool, indices(A), I) which recursively calls\ncheckindex for each dimensionHere A is the array, and I contains the \"requested\" indices. indices(A) returns a tuple of \"permitted\" indices of A.checkbounds(A, I...) throws an error if the indices are invalid, whereas checkbounds(Bool, A, I...) returns false in that circumstance. checkbounds_indices discards any information about the array other than its indices tuple, and performs a pure indices-vs-indices comparison: this allows relatively few compiled methods to serve a huge variety of array types. Indices are specified as tuples, and are usually compared in a 1-1 fashion with individual dimensions handled by calling another important function, checkindex: typically,checkbounds_indices(Bool, (IA1, IA...), (I1, I...)) = checkindex(Bool, IA1, I1) &\n checkbounds_indices(Bool, IA, I)so checkindex checks a single dimension. All of these functions, including the unexported checkbounds_indices have docstrings accessible with ? .If you have to customize bounds checking for a specific array type, you should specialize checkbounds(Bool, A, I...). However, in most cases you should be able to rely on checkbounds_indices as long as you supply useful indices for your array type.If you have novel index types, first consider specializing checkindex, which handles a single index for a particular dimension of an array. If you have a custom multidimensional index type (similar to CartesianIndex), then you may have to consider specializing checkbounds_indices.Note this hierarchy has been designed to reduce the likelihood of method ambiguities. We try to make checkbounds the place to specialize on array type, and try to avoid specializations on index types; conversely, checkindex is intended to be specialized only on index type (especially, the last argument)." -}, - -{ - "location": "devdocs/locks.html#", - "page": "Proper maintenance and care of multi-threading locks", - "title": "Proper maintenance and care of multi-threading locks", - "category": "page", - "text": "" -}, - -{ - "location": "devdocs/locks.html#Proper-maintenance-and-care-of-multi-threading-locks-1", - "page": "Proper maintenance and care of multi-threading locks", - "title": "Proper maintenance and care of multi-threading locks", - "category": "section", - "text": "The following strategies are used to ensure that the code is dead-lock free (generally by addressing the 4th Coffman condition: circular wait).structure code such that only one lock will need to be acquired at a time\nalways acquire shared locks in the same order, as given by the table below\navoid constructs that expect to need unrestricted recursion" -}, - -{ - "location": "devdocs/locks.html#Locks-1", - "page": "Proper maintenance and care of multi-threading locks", - "title": "Locks", - "category": "section", - "text": "Below are all of the locks that exist in the system and the mechanisms for using them that avoid the potential for deadlocks (no Ostrich algorithm allowed here):The following are definitely leaf locks (level 1), and must not try to acquire any other lock:safepoint\nNote that this lock is acquired implicitly by JL_LOCK and JL_UNLOCK. use the _NOGC variants to avoid that for level 1 locks.While holding this lock, the code must not do any allocation or hit any safepoints. Note that there are safepoints when doing allocation, enabling / disabling GC, entering / restoring exception frames, and taking / releasing locks.\nshared_map\nfinalizers\npagealloc\ngc_perm_lock\nflisp\nflisp itself is already threadsafe, this lock only protects the jl_ast_context_list_t poolThe following is a leaf lock (level 2), and only acquires level 1 locks (safepoint) internally:typecacheThe following is a level 3 lock, which can only acquire level 1 or level 2 locks internally:Method->writelockThe following is a level 4 lock, which can only recurse to acquire level 1, 2, or 3 locks:MethodTable->writelockNo Julia code may be called while holding a lock above this point.The following is a level 6 lock, which can only recurse to acquire locks at lower levels:codegenThe following is an almost root lock (level end-1), meaning only the root look may be held when trying to acquire it:typeinf\nthis one is perhaps one of the most tricky ones, since type-inference can be invoked from many pointscurrently the lock is merged with the codegen lock, since they call each other recursivelyThe following is the root lock, meaning no other lock shall be held when trying to acquire it:toplevel\nthis should be held while attempting a top-level action (such as making a new type or defining a new method): trying to obtain this lock inside a staged function will cause a deadlock condition!additionally, it\'s unclear if any code can safely run in parallel with an arbitrary toplevel expression, so it may require all threads to get to a safepoint first" -}, - -{ - "location": "devdocs/locks.html#Broken-Locks-1", - "page": "Proper maintenance and care of multi-threading locks", - "title": "Broken Locks", - "category": "section", - "text": "The following locks are broken:toplevel\ndoesn\'t exist right nowfix: create it" -}, - -{ - "location": "devdocs/locks.html#Shared-Global-Data-Structures-1", - "page": "Proper maintenance and care of multi-threading locks", - "title": "Shared Global Data Structures", - "category": "section", - "text": "These data structures each need locks due to being shared mutable global state. It is the inverse list for the above lock priority list. This list does not include level 1 leaf resources due to their simplicity.MethodTable modifications (def, cache, kwsorter type) : MethodTable->writelockType declarations : toplevel lockType application : typecache lockModule serializer : toplevel lockJIT & type-inference : codegen lockMethodInstance updates : codegen lockThese fields are generally lazy initialized, using the test-and-test-and-set pattern.\nThese are set at construction and immutable:\nspecTypes\nsparam_vals\ndef\nThese are set by jl_type_infer (while holding codegen lock):\nrettype\ninferred\nthese can also be reset, see jl_set_lambda_rettype for that logic as it needs to keep functionObjectsDecls in sync\ninInference flag:\noptimization to quickly avoid recurring into jl_type_infer while it is already running\nactual state (of setting inferred, then fptr) is protected by codegen lock\nFunction pointers (jlcall_api and fptr, unspecialized_ducttape):\nthese transition once, from NULL to a value, while the codegen lock is held\nCode-generator cache (the contents of functionObjectsDecls):\nthese can transition multiple times, but only while the codegen lock is held\nit is valid to use old version of this, or block for new versions of this, so races are benign, as long as the code is careful not to reference other data in the method instance (such as rettype) and assume it is coordinated, unless also holding the codegen lock\ncompile_traced flag:\nunknownLLVMContext : codegen lockMethod : Method->writelockroots array (serializer and codegen)\ninvoke / specializations / tfunc modifications" -}, - -{ - "location": "devdocs/offset-arrays.html#", - "page": "Arrays with custom indices", - "title": "Arrays with custom indices", - "category": "page", - "text": "" -}, - -{ - "location": "devdocs/offset-arrays.html#Arrays-with-custom-indices-1", - "page": "Arrays with custom indices", - "title": "Arrays with custom indices", - "category": "section", - "text": "Julia 0.5 adds experimental support for arrays with arbitrary indices. Conventionally, Julia\'s arrays are indexed starting at 1, whereas some other languages start numbering at 0, and yet others (e.g., Fortran) allow you to specify arbitrary starting indices. While there is much merit in picking a standard (i.e., 1 for Julia), there are some algorithms which simplify considerably if you can index outside the range 1:size(A,d) (and not just 0:size(A,d)-1, either). Such array types are expected to be supplied through packages.The purpose of this page is to address the question, \"what do I have to do to support such arrays in my own code?\" First, let\'s address the simplest case: if you know that your code will never need to handle arrays with unconventional indexing, hopefully the answer is \"nothing.\" Old code, on conventional arrays, should function essentially without alteration as long as it was using the exported interfaces of Julia." -}, - -{ - "location": "devdocs/offset-arrays.html#Generalizing-existing-code-1", - "page": "Arrays with custom indices", - "title": "Generalizing existing code", - "category": "section", - "text": "As an overview, the steps are:replace many uses of size with indices\nreplace 1:length(A) with linearindices(A), and length(A) with length(linearindices(A))\nreplace explicit allocations like Array{Int}(size(B)) with similar(Array{Int}, indices(B))These are described in more detail below." -}, - -{ - "location": "devdocs/offset-arrays.html#Background-1", - "page": "Arrays with custom indices", - "title": "Background", - "category": "section", - "text": "Because unconventional indexing breaks deeply-held assumptions throughout the Julia ecosystem, early adopters running code that has not been updated are likely to experience errors. The most frustrating bugs would be incorrect results or segfaults (total crashes of Julia). For example, consider the following function:function mycopy!(dest::AbstractVector, src::AbstractVector)\n length(dest) == length(src) || throw(DimensionMismatch(\"vectors must match\"))\n # OK, now we\'re safe to use @inbounds, right? (not anymore!)\n for i = 1:length(src)\n @inbounds dest[i] = src[i]\n end\n dest\nendThis code implicitly assumes that vectors are indexed from 1. Previously that was a safe assumption, so this code was fine, but (depending on what types the user passes to this function) it may no longer be safe. If this code continued to work when passed a vector with non-1 indices, it would either produce an incorrect answer or it would segfault. (If you do get segfaults, to help locate the cause try running julia with the option --check-bounds=yes.)To ensure that such errors are caught, in Julia 0.5 both length and sizeshould throw an error when passed an array with non-1 indexing. This is designed to force users of such arrays to check the code, and inspect it for whether it needs to be generalized." -}, - -{ - "location": "devdocs/offset-arrays.html#Using-indices-for-bounds-checks-and-loop-iteration-1", - "page": "Arrays with custom indices", - "title": "Using indices for bounds checks and loop iteration", - "category": "section", - "text": "indices(A) (reminiscent of size(A)) returns a tuple of AbstractUnitRange objects, specifying the range of valid indices along each dimension of A. When A has unconventional indexing, the ranges may not start at 1. If you just want the range for a particular dimension d, there is indices(A, d).Base implements a custom range type, OneTo, where OneTo(n) means the same thing as 1:n but in a form that guarantees (via the type system) that the lower index is 1. For any new AbstractArray type, this is the default returned by indices, and it indicates that this array type uses \"conventional\" 1-based indexing. Note that if you don\'t want to be bothered supporting arrays with non-1 indexing, you can add the following line:@assert all(x->isa(x, Base.OneTo), indices(A))at the top of any function.For bounds checking, note that there are dedicated functions checkbounds and checkindex which can sometimes simplify such tests." -}, - -{ - "location": "devdocs/offset-arrays.html#Linear-indexing-(linearindices)-1", - "page": "Arrays with custom indices", - "title": "Linear indexing (linearindices)", - "category": "section", - "text": "Some algorithms are most conveniently (or efficiently) written in terms of a single linear index, A[i] even if A is multi-dimensional. In \"true\" linear indexing, the indices always range from 1:length(A). However, this raises an ambiguity for one-dimensional arrays (a.k.a., AbstractVector): does v[i] mean linear indexing, or Cartesian indexing with the array\'s native indices?For this reason, if you want to use linear indexing in an algorithm, your best option is to get the index range by calling linearindices(A). This will return indices(A, 1) if A is an AbstractVector, and the equivalent of 1:length(A) otherwise.In a sense, one can say that 1-dimensional arrays always use Cartesian indexing. To help enforce this, it\'s worth noting that sub2ind(shape, i...) and ind2sub(shape, ind) will throw an error if shape indicates a 1-dimensional array with unconventional indexing (i.e., is a Tuple{UnitRange} rather than a tuple of OneTo). For arrays with conventional indexing, these functions continue to work the same as always.Using indices and linearindices, here is one way you could rewrite mycopy!:function mycopy!(dest::AbstractVector, src::AbstractVector)\n indices(dest) == indices(src) || throw(DimensionMismatch(\"vectors must match\"))\n for i in linearindices(src)\n @inbounds dest[i] = src[i]\n end\n dest\nend" -}, - -{ - "location": "devdocs/offset-arrays.html#Allocating-storage-using-generalizations-of-similar-1", - "page": "Arrays with custom indices", - "title": "Allocating storage using generalizations of similar", - "category": "section", - "text": "Storage is often allocated with Array{Int}(dims) or similar(A, args...). When the result needs to match the indices of some other array, this may not always suffice. The generic replacement for such patterns is to use similar(storagetype, shape). storagetype indicates the kind of underlying \"conventional\" behavior you\'d like, e.g., Array{Int} or BitArray or even dims->zeros(Float32, dims) (which would allocate an all-zeros array). shape is a tuple of Integer or AbstractUnitRange values, specifying the indices that you want the result to use.Let\'s walk through a couple of explicit examples. First, if A has conventional indices, then similar(Array{Int}, indices(A)) would end up calling Array{Int}(size(A)), and thus return an array. If A is an AbstractArray type with unconventional indexing, then similar(Array{Int}, indices(A)) should return something that \"behaves like\" an Array{Int} but with a shape (including indices) that matches A. (The most obvious implementation is to allocate an Array{Int}(size(A)) and then \"wrap\" it in a type that shifts the indices.)Note also that similar(Array{Int}, (indices(A, 2),)) would allocate an AbstractVector{Int} (i.e., 1-dimensional array) that matches the indices of the columns of A." -}, - -{ - "location": "devdocs/offset-arrays.html#Deprecations-1", - "page": "Arrays with custom indices", - "title": "Deprecations", - "category": "section", - "text": "In generalizing Julia\'s code base, at least one deprecation was unavoidable: earlier versions of Julia defined first(::Colon) = 1, meaning that the first index along a dimension indexed by : is 1. This definition can no longer be justified, so it was deprecated. There is no provided replacement, because the proper replacement depends on what you are doing and might need to know more about the array. However, it appears that many uses of first(::Colon) are really about computing an index offset; when that is the case, a candidate replacement is:indexoffset(r::AbstractVector) = first(r) - 1\nindexoffset(::Colon) = 0In other words, while first(:) does not itself make sense, in general you can say that the offset associated with a colon-index is zero." -}, - -{ - "location": "devdocs/offset-arrays.html#Writing-custom-array-types-with-non-1-indexing-1", - "page": "Arrays with custom indices", - "title": "Writing custom array types with non-1 indexing", - "category": "section", - "text": "Most of the methods you\'ll need to define are standard for any AbstractArray type, see Abstract Arrays. This page focuses on the steps needed to define unconventional indexing." -}, - -{ - "location": "devdocs/offset-arrays.html#Do-**not**-implement-size-or-length-1", - "page": "Arrays with custom indices", - "title": "Do not implement size or length", - "category": "section", - "text": "Perhaps the majority of pre-existing code that uses size will not work properly for arrays with non-1 indices. For that reason, it is much better to avoid implementing these methods, and use the resulting MethodError to identify code that needs to be audited and perhaps generalized." -}, - -{ - "location": "devdocs/offset-arrays.html#Do-**not**-annotate-bounds-checks-1", - "page": "Arrays with custom indices", - "title": "Do not annotate bounds checks", - "category": "section", - "text": "Julia 0.5 includes @boundscheck to annotate code that can be removed for callers that exploit @inbounds. Initially, it seems far preferable to run with bounds checking always enabled (i.e., omit the @boundscheck annotation so the check always runs)." -}, - -{ - "location": "devdocs/offset-arrays.html#Custom-AbstractUnitRange-types-1", - "page": "Arrays with custom indices", - "title": "Custom AbstractUnitRange types", - "category": "section", - "text": "If you\'re writing a non-1 indexed array type, you will want to specialize indices so it returns a UnitRange, or (perhaps better) a custom AbstractUnitRange. The advantage of a custom type is that it \"signals\" the allocation type for functions like similar. If we\'re writing an array type for which indexing will start at 0, we likely want to begin by creating a new AbstractUnitRange, ZeroRange, where ZeroRange(n) is equivalent to 0:n-1.In general, you should probably not export ZeroRange from your package: there may be other packages that implement their own ZeroRange, and having multiple distinct ZeroRange types is (perhaps counterintuitively) an advantage: ModuleA.ZeroRange indicates that similar should create a ModuleA.ZeroArray, whereas ModuleB.ZeroRange indicates a ModuleB.ZeroArray type. This design allows peaceful coexistence among many different custom array types.Note that the Julia package CustomUnitRanges.jl can sometimes be used to avoid the need to write your own ZeroRange type." -}, - -{ - "location": "devdocs/offset-arrays.html#Specializing-indices-1", - "page": "Arrays with custom indices", - "title": "Specializing indices", - "category": "section", - "text": "Once you have your AbstractUnitRange type, then specialize indices:Base.indices(A::ZeroArray) = map(n->ZeroRange(n), A.size)where here we imagine that ZeroArray has a field called size (there would be other ways to implement this).In some cases, the fallback definition for indices(A, d):indices(A::AbstractArray{T,N}, d) where {T,N} = d <= N ? indices(A)[d] : OneTo(1)may not be what you want: you may need to specialize it to return something other than OneTo(1) when d > ndims(A). Likewise, in Base there is a dedicated function indices1 which is equivalent to indices(A, 1) but which avoids checking (at runtime) whether ndims(A) > 0. (This is purely a performance optimization.) It is defined as:indices1(A::AbstractArray{T,0}) where {T} = OneTo(1)\nindices1(A::AbstractArray) = indices(A)[1]If the first of these (the zero-dimensional case) is problematic for your custom array type, be sure to specialize it appropriately." -}, - -{ - "location": "devdocs/offset-arrays.html#Specializing-similar-1", - "page": "Arrays with custom indices", - "title": "Specializing similar", - "category": "section", - "text": "Given your custom ZeroRange type, then you should also add the following two specializations for similar:function Base.similar(A::AbstractArray, T::Type, shape::Tuple{ZeroRange,Vararg{ZeroRange}})\n # body\nend\n\nfunction Base.similar(f::Union{Function,DataType}, shape::Tuple{ZeroRange,Vararg{ZeroRange}})\n # body\nendBoth of these should allocate your custom array type." -}, - -{ - "location": "devdocs/offset-arrays.html#Specializing-reshape-1", - "page": "Arrays with custom indices", - "title": "Specializing reshape", - "category": "section", - "text": "Optionally, define a methodBase.reshape(A::AbstractArray, shape::Tuple{ZeroRange,Vararg{ZeroRange}}) = ...and you can reshape an array so that the result has custom indices." -}, - -{ - "location": "devdocs/offset-arrays.html#Summary-1", - "page": "Arrays with custom indices", - "title": "Summary", - "category": "section", - "text": "Writing code that doesn\'t make assumptions about indexing requires a few extra abstractions, but hopefully the necessary changes are relatively straightforward.As a reminder, this support is still experimental. While much of Julia\'s base code has been updated to support unconventional indexing, without a doubt there are many omissions that will be discovered only through usage. Moreover, at the time of this writing, most packages do not support unconventional indexing. As a consequence, early adopters should be prepared to identify and/or fix bugs. On the other hand, only through practical usage will it become clear whether this experimental feature should be retained in future versions of Julia; consequently, interested parties are encouraged to accept some ownership for putting it through its paces." -}, - -{ - "location": "devdocs/libgit2.html#", - "page": "Base.LibGit2", - "title": "Base.LibGit2", - "category": "page", - "text": "" -}, - -{ - "location": "devdocs/libgit2.html#Base.LibGit2-1", - "page": "Base.LibGit2", - "title": "Base.LibGit2", - "category": "section", - "text": "The LibGit2 module provides bindings to libgit2, a portable C library that implements core functionality for the Git version control system. These bindings are currently used to power Julia\'s package manager. It is expected that this module will eventually be moved into a separate package." -}, - -{ - "location": "devdocs/libgit2.html#Base.LibGit2.AbstractCredentials", - "page": "Base.LibGit2", - "title": "Base.LibGit2.AbstractCredentials", - "category": "type", - "text": "Abstract credentials payload\n\n\n\n" -}, - -{ - "location": "devdocs/libgit2.html#Base.LibGit2.Buffer", - "page": "Base.LibGit2", - "title": "Base.LibGit2.Buffer", - "category": "type", - "text": "LibGit2.Buffer\n\nA data buffer for exporting data from libgit2. Matches the git_buf struct.\n\nWhen fetching data from LibGit2, a typical usage would look like:\n\nbuf_ref = Ref(Buffer())\n@check ccall(..., (Ptr{Buffer},), buf_ref)\n# operation on buf_ref\nfree(buf_ref)\n\nIn particular, note that LibGit2.free should be called afterward on the Ref object.\n\n\n\n" -}, - -{ - "location": "devdocs/libgit2.html#Base.LibGit2.CachedCredentials", - "page": "Base.LibGit2", - "title": "Base.LibGit2.CachedCredentials", - "category": "type", - "text": "Credentials that support caching\n\n\n\n" -}, - -{ - "location": "devdocs/libgit2.html#Base.LibGit2.CheckoutOptions", - "page": "Base.LibGit2", - "title": "Base.LibGit2.CheckoutOptions", - "category": "type", - "text": "LibGit2.CheckoutOptions\n\nMatches the git_checkout_options struct.\n\n\n\n" -}, - -{ - "location": "devdocs/libgit2.html#Base.LibGit2.CloneOptions", - "page": "Base.LibGit2", - "title": "Base.LibGit2.CloneOptions", - "category": "type", - "text": "LibGit2.CloneOptions\n\nMatches the git_clone_options struct.\n\n\n\n" -}, - -{ - "location": "devdocs/libgit2.html#Base.LibGit2.DiffDelta", - "page": "Base.LibGit2", - "title": "Base.LibGit2.DiffDelta", - "category": "type", - "text": "LibGit2.DiffDelta\n\nDescription of changes to one entry. Matches the git_diff_delta struct.\n\nThe fields represent:\n\nstatus: One of Consts.DELTA_STATUS, indicating whether the file has been added/modified/deleted.\nflags: Flags for the delta and the objects on each side. Determines whether to treat the file(s) as binary/text, whether they exist on each side of the diff, and whether the object ids are known to be correct.\nsimilarity: Used to indicate if a file has been renamed or copied.\nnfiles: The number of files in the delta (for instance, if the delta was run on a submodule commit id, it may contain more than one file).\nold_file: A DiffFile containing information about the file(s) before the changes.\nnew_file: A DiffFile containing information about the file(s) after the changes.\n\n\n\n" -}, - -{ - "location": "devdocs/libgit2.html#Base.LibGit2.DiffFile", - "page": "Base.LibGit2", - "title": "Base.LibGit2.DiffFile", - "category": "type", - "text": "LibGit2.DiffFile\n\nDescription of one side of a delta. Matches the git_diff_file struct.\n\n\n\n" -}, - -{ - "location": "devdocs/libgit2.html#Base.LibGit2.DiffOptionsStruct", - "page": "Base.LibGit2", - "title": "Base.LibGit2.DiffOptionsStruct", - "category": "type", - "text": "LibGit2.DiffOptionsStruct\n\nMatches the git_diff_options struct.\n\n\n\n" -}, - -{ - "location": "devdocs/libgit2.html#Base.LibGit2.FetchHead", - "page": "Base.LibGit2", - "title": "Base.LibGit2.FetchHead", - "category": "type", - "text": "LibGit2.FetchHead\n\nContains the information about HEAD during a fetch, including the name and URL of the branch fetched from, the oid of the HEAD, and whether the fetched HEAD has been merged locally.\n\n\n\n" -}, - -{ - "location": "devdocs/libgit2.html#Base.LibGit2.FetchOptions", - "page": "Base.LibGit2", - "title": "Base.LibGit2.FetchOptions", - "category": "type", - "text": "LibGit2.FetchOptions\n\nMatches the git_fetch_options struct.\n\n\n\n" -}, - -{ - "location": "devdocs/libgit2.html#Base.LibGit2.GitBlob", - "page": "Base.LibGit2", - "title": "Base.LibGit2.GitBlob", - "category": "type", - "text": "GitBlob(repo::GitRepo, hash::AbstractGitHash)\nGitBlob(repo::GitRepo, spec::AbstractString)\n\nReturn a GitBlob object from repo specified by hash/spec.\n\nhash is a full (GitHash) or partial (GitShortHash) hash.\nspec is a textual specification: see the git docs for a full list.\n\n\n\n" -}, - -{ - "location": "devdocs/libgit2.html#Base.LibGit2.GitCommit", - "page": "Base.LibGit2", - "title": "Base.LibGit2.GitCommit", - "category": "type", - "text": "GitCommit(repo::GitRepo, hash::AbstractGitHash)\nGitCommit(repo::GitRepo, spec::AbstractString)\n\nReturn a GitCommit object from repo specified by hash/spec.\n\nhash is a full (GitHash) or partial (GitShortHash) hash.\nspec is a textual specification: see the git docs for a full list.\n\n\n\n" -}, - -{ - "location": "devdocs/libgit2.html#Base.LibGit2.GitHash", - "page": "Base.LibGit2", - "title": "Base.LibGit2.GitHash", - "category": "type", - "text": "GitHash\n\nA git object identifier, based on the sha-1 hash. It is a 20 byte string (40 hex digits) used to identify a GitObject in a repository.\n\n\n\n" -}, - -{ - "location": "devdocs/libgit2.html#Base.LibGit2.GitObject", - "page": "Base.LibGit2", - "title": "Base.LibGit2.GitObject", - "category": "type", - "text": "GitObject(repo::GitRepo, hash::AbstractGitHash)\nGitObject(repo::GitRepo, spec::AbstractString)\n\nReturn the specified object (GitCommit, GitBlob, GitTree or GitTag) from repo specified by hash/spec.\n\nhash is a full (GitHash) or partial (GitShortHash) hash.\nspec is a textual specification: see the git docs for a full list.\n\n\n\n" -}, - -{ - "location": "devdocs/libgit2.html#Base.LibGit2.GitRemote", - "page": "Base.LibGit2", - "title": "Base.LibGit2.GitRemote", - "category": "type", - "text": "GitRemote(repo::GitRepo, rmt_name::AbstractString, rmt_url::AbstractString) -> GitRemote\n\nLook up a remote git repository using its name and URL. Uses the default fetch refspec.\n\nExample\n\nrepo = LibGit2.init(repo_path)\nremote = LibGit2.GitRemote(repo, \"upstream\", repo_url)\n\n\n\nGitRemote(repo::GitRepo, rmt_name::AbstractString, rmt_url::AbstractString, fetch_spec::AbstractString) -> GitRemote\n\nLook up a remote git repository using the repository\'s name and URL, as well as specifications for how to fetch from the remote (e.g. which remote branch to fetch from).\n\nExample\n\nrepo = LibGit2.init(repo_path)\nrefspec = \"+refs/heads/mybranch:refs/remotes/origin/mybranch\"\nremote = LibGit2.GitRemote(repo, \"upstream\", repo_url, refspec)\n\n\n\n" -}, - -{ - "location": "devdocs/libgit2.html#Base.LibGit2.GitRemoteAnon", - "page": "Base.LibGit2", - "title": "Base.LibGit2.GitRemoteAnon", - "category": "function", - "text": "GitRemoteAnon(repo::GitRepo, url::AbstractString) -> GitRemote\n\nLook up a remote git repository using only its URL, not its name.\n\nExample\n\nrepo = LibGit2.init(repo_path)\nremote = LibGit2.GitRemoteAnon(repo, repo_url)\n\n\n\n" -}, - -{ - "location": "devdocs/libgit2.html#Base.LibGit2.GitRepo", - "page": "Base.LibGit2", - "title": "Base.LibGit2.GitRepo", - "category": "type", - "text": "LibGit2.GitRepo(path::AbstractString)\n\nOpens a git repository at path.\n\n\n\n" -}, - -{ - "location": "devdocs/libgit2.html#Base.LibGit2.GitRepoExt", - "page": "Base.LibGit2", - "title": "Base.LibGit2.GitRepoExt", - "category": "function", - "text": "LibGit2.GitRepoExt(path::AbstractString, flags::Cuint = Cuint(Consts.REPOSITORY_OPEN_DEFAULT))\n\nOpens a git repository at path with extended controls (for instance, if the current user must be a member of a special access group to read path).\n\n\n\n" -}, - -{ - "location": "devdocs/libgit2.html#Base.LibGit2.GitShortHash", - "page": "Base.LibGit2", - "title": "Base.LibGit2.GitShortHash", - "category": "type", - "text": "GitShortHash\n\nThis is a shortened form of GitHash, which can be used to identify a git object when it is unique.\n\nInternally it is stored as two fields: a full-size GitHash (hash) and a length (len). Only the initial len hex digits of hash are used.\n\n\n\n" -}, - -{ - "location": "devdocs/libgit2.html#Base.LibGit2.GitSignature", - "page": "Base.LibGit2", - "title": "Base.LibGit2.GitSignature", - "category": "type", - "text": "LibGit2.GitSignature\n\nThis is a Julia wrapper around a pointer to a git_signature object.\n\n\n\n" -}, - -{ - "location": "devdocs/libgit2.html#Base.LibGit2.GitStatus", - "page": "Base.LibGit2", - "title": "Base.LibGit2.GitStatus", - "category": "type", - "text": "LibGit2.GitStatus(repo::GitRepo; status_opts=StatusOptions())\n\nCollect information about the status of each file in the git repository repo (e.g. is the file modified, staged, etc.). status_opts can be used to set various options, for instance whether or not to look at untracked files or whether to include submodules or not.\n\n\n\n" -}, - -{ - "location": "devdocs/libgit2.html#Base.LibGit2.GitTag", - "page": "Base.LibGit2", - "title": "Base.LibGit2.GitTag", - "category": "type", - "text": "GitTag(repo::GitRepo, hash::AbstractGitHash)\nGitTag(repo::GitRepo, spec::AbstractString)\n\nReturn a GitTag object from repo specified by hash/spec.\n\nhash is a full (GitHash) or partial (GitShortHash) hash.\nspec is a textual specification: see the git docs for a full list.\n\n\n\n" -}, - -{ - "location": "devdocs/libgit2.html#Base.LibGit2.GitTree", - "page": "Base.LibGit2", - "title": "Base.LibGit2.GitTree", - "category": "type", - "text": "GitTree(repo::GitRepo, hash::AbstractGitHash)\nGitTree(repo::GitRepo, spec::AbstractString)\n\nReturn a GitTree object from repo specified by hash/spec.\n\nhash is a full (GitHash) or partial (GitShortHash) hash.\nspec is a textual specification: see the git docs for a full list.\n\n\n\n" -}, - -{ - "location": "devdocs/libgit2.html#Base.LibGit2.IndexEntry", - "page": "Base.LibGit2", - "title": "Base.LibGit2.IndexEntry", - "category": "type", - "text": "LibGit2.IndexEntry\n\nIn-memory representation of a file entry in the index. Matches the git_index_entry struct.\n\n\n\n" -}, - -{ - "location": "devdocs/libgit2.html#Base.LibGit2.IndexTime", - "page": "Base.LibGit2", - "title": "Base.LibGit2.IndexTime", - "category": "type", - "text": "LibGit2.IndexTime\n\nMatches the git_index_time struct.\n\n\n\n" -}, - -{ - "location": "devdocs/libgit2.html#Base.LibGit2.MergeOptions", - "page": "Base.LibGit2", - "title": "Base.LibGit2.MergeOptions", - "category": "type", - "text": "LibGit2.MergeOptions\n\nMatches the git_merge_options struct.\n\n\n\n" -}, - -{ - "location": "devdocs/libgit2.html#Base.LibGit2.ProxyOptions", - "page": "Base.LibGit2", - "title": "Base.LibGit2.ProxyOptions", - "category": "type", - "text": "LibGit2.ProxyOptions\n\nOptions for connecting through a proxy.\n\nMatches the git_proxy_options struct.\n\n\n\n" -}, - -{ - "location": "devdocs/libgit2.html#Base.LibGit2.PushOptions", - "page": "Base.LibGit2", - "title": "Base.LibGit2.PushOptions", - "category": "type", - "text": "LibGit2.PushOptions\n\nMatches the git_push_options struct.\n\n\n\n" -}, - -{ - "location": "devdocs/libgit2.html#Base.LibGit2.RebaseOperation", - "page": "Base.LibGit2", - "title": "Base.LibGit2.RebaseOperation", - "category": "type", - "text": "LibGit2.RebaseOperation\n\nDescribes a single instruction/operation to be performed during the rebase. Matches the git_rebase_operation struct.\n\n\n\n" -}, - -{ - "location": "devdocs/libgit2.html#Base.LibGit2.RebaseOptions", - "page": "Base.LibGit2", - "title": "Base.LibGit2.RebaseOptions", - "category": "type", - "text": "LibGit2.RebaseOptions\n\nMatches the git_rebase_options struct.\n\n\n\n" -}, - -{ - "location": "devdocs/libgit2.html#Base.LibGit2.RemoteCallbacks", - "page": "Base.LibGit2", - "title": "Base.LibGit2.RemoteCallbacks", - "category": "type", - "text": "LibGit2.RemoteCallbacks\n\nCallback settings. Matches the git_remote_callbacks struct.\n\n\n\n" -}, - -{ - "location": "devdocs/libgit2.html#Base.LibGit2.SSHCredentials", - "page": "Base.LibGit2", - "title": "Base.LibGit2.SSHCredentials", - "category": "type", - "text": "SSH credentials type\n\n\n\n" -}, - -{ - "location": "devdocs/libgit2.html#Base.LibGit2.SignatureStruct", - "page": "Base.LibGit2", - "title": "Base.LibGit2.SignatureStruct", - "category": "type", - "text": "LibGit2.SignatureStruct\n\nAn action signature (e.g. for committers, taggers, etc). Matches the git_signature struct.\n\n\n\n" -}, - -{ - "location": "devdocs/libgit2.html#Base.LibGit2.StatusEntry", - "page": "Base.LibGit2", - "title": "Base.LibGit2.StatusEntry", - "category": "type", - "text": "LibGit2.StatusEntry\n\nProviding the differences between the file as it exists in HEAD and the index, and providing the differences between the index and the working directory. Matches the git_status_entry struct.\n\n\n\n" -}, - -{ - "location": "devdocs/libgit2.html#Base.LibGit2.StatusOptions", - "page": "Base.LibGit2", - "title": "Base.LibGit2.StatusOptions", - "category": "type", - "text": "LibGit2.StatusOptions\n\nOptions to control how git_status_foreach_ext() will issue callbacks. Matches the git_status_opt_t struct.\n\n\n\n" -}, - -{ - "location": "devdocs/libgit2.html#Base.LibGit2.StrArrayStruct", - "page": "Base.LibGit2", - "title": "Base.LibGit2.StrArrayStruct", - "category": "type", - "text": "LibGit2.StrArrayStruct\n\nA LibGit2 representation of an array of strings. Matches the git_strarray struct.\n\nWhen fetching data from LibGit2, a typical usage would look like:\n\nsa_ref = Ref(StrArrayStruct())\n@check ccall(..., (Ptr{StrArrayStruct},), sa_ref)\nres = convert(Vector{String}, sa_ref[])\nfree(sa_ref)\n\nIn particular, note that LibGit2.free should be called afterward on the Ref object.\n\nConversely, when passing a vector of strings to LibGit2, it is generally simplest to rely on implicit conversion:\n\nstrs = String[...]\n@check ccall(..., (Ptr{StrArrayStruct},), strs)\n\nNote that no call to free is required as the data is allocated by Julia.\n\n\n\n" -}, - -{ - "location": "devdocs/libgit2.html#Base.LibGit2.TimeStruct", - "page": "Base.LibGit2", - "title": "Base.LibGit2.TimeStruct", - "category": "type", - "text": "LibGit2.TimeStruct\n\nTime in a signature. Matches the git_time struct.\n\n\n\n" -}, - -{ - "location": "devdocs/libgit2.html#Base.LibGit2.UserPasswordCredentials", - "page": "Base.LibGit2", - "title": "Base.LibGit2.UserPasswordCredentials", - "category": "type", - "text": "Credentials that support only user and password parameters\n\n\n\n" -}, - -{ - "location": "devdocs/libgit2.html#Base.LibGit2.add_fetch!", - "page": "Base.LibGit2", - "title": "Base.LibGit2.add_fetch!", - "category": "function", - "text": "add_fetch!(repo::GitRepo, rmt::GitRemote, fetch_spec::String)\n\nAdd a fetch refspec for the specified rmt. This refspec will contain information about which branch(es) to fetch from.\n\nExample\n\njulia> LibGit2.add_fetch!(repo, remote, \"upstream\");\n\njulia> LibGit2.fetch_refspecs(remote)\nString[\"+refs/heads/*:refs/remotes/upstream/*\"]\n\n\n\n" -}, - -{ - "location": "devdocs/libgit2.html#Base.LibGit2.add_push!", - "page": "Base.LibGit2", - "title": "Base.LibGit2.add_push!", - "category": "function", - "text": "add_push!(repo::GitRepo, rmt::GitRemote, push_spec::String)\n\nAdd a push refspec for the specified rmt. This refspec will contain information about which branch(es) to push to.\n\nExample\n\njulia> LibGit2.add_push!(repo, remote, \"refs/heads/master\");\n\njulia> remote = LibGit2.get(LibGit2.GitRemote, repo, branch);\n\njulia> LibGit2.push_refspecs(remote)\nString[\"refs/heads/master\"]\n\nnote: Note\nYou may need to close and reopen the GitRemote in question after updating its push refspecs in order for the change to take effect and for calls to push to work.\n\n\n\n" -}, - -{ - "location": "devdocs/libgit2.html#Base.LibGit2.addblob!", - "page": "Base.LibGit2", - "title": "Base.LibGit2.addblob!", - "category": "function", - "text": "LibGit2.addblob!(repo::GitRepo, path::AbstractString)\n\nReads the file at path and adds it to the object database of repo as a loose blob. Returns the GitHash of the resulting blob.\n\nExample\n\nhash_str = hex(commit_oid)\nblob_file = joinpath(repo_path, \".git\", \"objects\", hash_str[1:2], hash_str[3:end])\nid = LibGit2.addblob!(repo, blob_file)\n\n\n\n" -}, - -{ - "location": "devdocs/libgit2.html#Base.LibGit2.authors", - "page": "Base.LibGit2", - "title": "Base.LibGit2.authors", - "category": "function", - "text": "authors(repo::GitRepo) -> Vector{Signature}\n\nReturns all authors of commits to the repo repository.\n\nExample\n\nrepo = LibGit2.GitRepo(repo_path)\nrepo_file = open(joinpath(repo_path, test_file), \"a\")\n\nprintln(repo_file, commit_msg)\nflush(repo_file)\nLibGit2.add!(repo, test_file)\nsig = LibGit2.Signature(\"TEST\", \"TEST@TEST.COM\", round(time(), 0), 0)\ncommit_oid1 = LibGit2.commit(repo, \"commit1\"; author=sig, committer=sig)\nprintln(repo_file, randstring(10))\nflush(repo_file)\nLibGit2.add!(repo, test_file)\ncommit_oid2 = LibGit2.commit(repo, \"commit2\"; author=sig, committer=sig)\n\n# will be a Vector of [sig, sig]\nauths = LibGit2.authors(repo)\n\n\n\n" -}, - -{ - "location": "devdocs/libgit2.html#Base.LibGit2.branch", - "page": "Base.LibGit2", - "title": "Base.LibGit2.branch", - "category": "function", - "text": "branch(repo::GitRepo)\n\nEquivalent to git branch. Create a new branch from the current HEAD.\n\n\n\n" -}, - -{ - "location": "devdocs/libgit2.html#Base.LibGit2.branch!", - "page": "Base.LibGit2", - "title": "Base.LibGit2.branch!", - "category": "function", - "text": "branch!(repo::GitRepo, branch_name::AbstractString, commit::AbstractString=\"\"; kwargs...)\n\nCheckout a new git branch in the repo repository. commit is the GitHash, in string form, which will be the start of the new branch. If commit is an empty string, the current HEAD will be used.\n\nThe keyword arguments are:\n\ntrack::AbstractString=\"\": the name of the remote branch this new branch should track, if any. If empty (the default), no remote branch will be tracked.\nforce::Bool=false: if true, branch creation will be forced.\nset_head::Bool=true: if true, after the branch creation finishes the branch head will be set as the HEAD of repo.\n\nEquivalent to git checkout [-b|-B] [] [--track ].\n\nExample\n\nrepo = LibGit2.GitRepo(repo_path)\nLibGit2.branch!(repo, \"new_branch\", set_head=false)\n\n\n\n" -}, - -{ - "location": "devdocs/libgit2.html#Base.LibGit2.checkout!", - "page": "Base.LibGit2", - "title": "Base.LibGit2.checkout!", - "category": "function", - "text": "checkout!(repo::GitRepo, commit::AbstractString=\"\"; force::Bool=true)\n\nEquivalent to git checkout [-f] --detach . Checkout the git commit commit (a GitHash in string form) in repo. If force is true, force the checkout and discard any current changes. Note that this detaches the current HEAD.\n\nExample\n\nrepo = LibGit2.init(repo_path)\nopen(joinpath(LibGit2.path(repo), \"file1\"), \"w\") do f\n write(f, \"111\n\")\nend\nLibGit2.add!(repo, \"file1\")\ncommit_oid = LibGit2.commit(repo, \"add file1\")\nopen(joinpath(LibGit2.path(repo), \"file1\"), \"w\") do f\n write(f, \"112\n\")\nend\n# would fail without the force=true\n# since there are modifications to the file\nLibGit2.checkout!(repo, string(commit_oid), force=true)\n\n\n\n" -}, - -{ - "location": "devdocs/libgit2.html#Base.LibGit2.checkused!", - "page": "Base.LibGit2", - "title": "Base.LibGit2.checkused!", - "category": "function", - "text": "Checks if credentials were used\n\n\n\nChecks if credentials were used or failed authentication, see LibGit2.credentials_callback\n\n\n\n" -}, - -{ - "location": "devdocs/libgit2.html#Base.LibGit2.clone", - "page": "Base.LibGit2", - "title": "Base.LibGit2.clone", - "category": "function", - "text": "clone(repo_url::AbstractString, repo_path::AbstractString; kwargs...)\n\nClone a remote repository located at repo_url to the local filesystem location repo_path.\n\nThe keyword arguments are:\n\nbranch::AbstractString=\"\": which branch of the remote to clone, if not the default repository branch (usually master).\nisbare::Bool=false: if true, clone the remote as a bare repository, which will make repo_path itself the git directory instead of repo_path/.git. This means that a working tree cannot be checked out. Plays the role of the git CLI argument --bare.\nremote_cb::Ptr{Void}=C_NULL: a callback which will be used to create the remote before it is cloned. If C_NULL (the default), no attempt will be made to create the remote - it will be assumed to already exist.\npayload::Nullable{P<:AbstractCredentials}=Nullable{AbstractCredentials}(): provides credentials if necessary, for instance if the remote is a private repository.\n\nEquivalent to git clone [-b ] [--bare] .\n\nExamples\n\nrepo_url = \"https://github.com/JuliaLang/Example.jl\"\nrepo1 = LibGit2.clone(repo_url, \"test_path\")\nrepo2 = LibGit2.clone(repo_url, \"test_path\", isbare=true)\njulia_url = \"https://github.com/JuliaLang/julia\"\njulia_repo = LibGit2.clone(julia_url, \"julia_path\", branch=\"release-0.6\")\n\n\n\n" -}, - -{ - "location": "devdocs/libgit2.html#Base.LibGit2.commit", - "page": "Base.LibGit2", - "title": "Base.LibGit2.commit", - "category": "function", - "text": "Wrapper around git_commit_create \n\n\n\nCommit changes to repository\n\n\n\nLibGit2.commit(rb::GitRebase, sig::GitSignature)\n\nCommits the current patch to the rebase rb, using sig as the committer. Is silent if the commit has already been applied.\n\n\n\n" -}, - -{ - "location": "devdocs/libgit2.html#Base.LibGit2.create_branch", - "page": "Base.LibGit2", - "title": "Base.LibGit2.create_branch", - "category": "function", - "text": "LibGit2.create_branch(repo::GitRepo, bname::AbstractString, commit_obj::GitCommit; force::Bool=false)\n\nCreate a new branch in the repository repo with name bname, which points to commit commit_obj (which has to be part of repo). If force is true, overwrite an existing branch named bname if it exists. If force is false and a branch already exists named bname, this function will throw an error.\n\n\n\n" -}, - -{ - "location": "devdocs/libgit2.html#Base.LibGit2.credentials_callback", - "page": "Base.LibGit2", - "title": "Base.LibGit2.credentials_callback", - "category": "function", - "text": "Credentials callback function\n\nFunction provides different credential acquisition functionality w.r.t. a connection protocol. If a payload is provided then payload_ptr should contain a LibGit2.AbstractCredentials object.\n\nFor LibGit2.Consts.CREDTYPE_USERPASS_PLAINTEXT type, if the payload contains fields: user & pass, they are used to create authentication credentials. Empty user name and password trigger an authentication error.\n\nFor LibGit2.Consts.CREDTYPE_SSH_KEY type, if the payload contains fields: user, prvkey, pubkey & pass, they are used to create authentication credentials. Empty user name triggers an authentication error.\n\nCredentials are checked in the following order (if supported):\n\nssh key pair (ssh-agent if specified in payload\'s usesshagent field)\nplain text\n\nNote: Due to the specifics of the libgit2 authentication procedure, when authentication fails, this function is called again without any indication whether authentication was successful or not. To avoid an infinite loop from repeatedly using the same faulty credentials, the checkused! function can be called. This function returns true if the credentials were used. Using credentials triggers a user prompt for (re)entering required information. UserPasswordCredentials and CachedCredentials are implemented using a call counting strategy that prevents repeated usage of faulty credentials.\n\n\n\n" -}, - -{ - "location": "devdocs/libgit2.html#Base.LibGit2.credentials_cb", - "page": "Base.LibGit2", - "title": "Base.LibGit2.credentials_cb", - "category": "function", - "text": "C function pointer for credentials_callback\n\n\n\n" -}, - -{ - "location": "devdocs/libgit2.html#Base.LibGit2.default_signature", - "page": "Base.LibGit2", - "title": "Base.LibGit2.default_signature", - "category": "function", - "text": "Return signature object. Free it after use.\n\n\n\n" -}, - -{ - "location": "devdocs/libgit2.html#Base.LibGit2.delete_branch", - "page": "Base.LibGit2", - "title": "Base.LibGit2.delete_branch", - "category": "function", - "text": "LibGit2.delete_branch(branch::GitReference)\n\nDelete the branch pointed to by branch.\n\n\n\n" -}, - -{ - "location": "devdocs/libgit2.html#Base.LibGit2.diff_files", - "page": "Base.LibGit2", - "title": "Base.LibGit2.diff_files", - "category": "function", - "text": "diff_files(repo::GitRepo, branch1::AbstractString, branch2::AbstractString; kwarg...) -> Vector{AbstractString}\n\nShow which files have changed in the git repository repo between branches branch1 and branch2.\n\nThe keyword argument is:\n\nfilter::Set{Consts.DELTA_STATUS}=Set([Consts.DELTA_ADDED, Consts.DELTA_MODIFIED, Consts.DELTA_DELETED])), and it sets options for the diff. The default is to show files added, modified, or deleted.\n\nReturns only the names of the files which have changed, not their contents.\n\nExample\n\nLibGit2.branch!(repo, \"branch/a\")\nLibGit2.branch!(repo, \"branch/b\")\n# add a file to repo\nopen(joinpath(LibGit2.path(repo),\"file\"),\"w\") do f\n write(f, \"hello repo\n\")\nend\nLibGit2.add!(repo, \"file\")\nLibGit2.commit(repo, \"add file\")\n# returns [\"file\"]\nfilt = Set([LibGit2.Consts.DELTA_ADDED])\nfiles = LibGit2.diff_files(repo, \"branch/a\", \"branch/b\", filter=filt)\n# returns [] because existing files weren\'t modified\nfilt = Set([LibGit2.Consts.DELTA_MODIFIED])\nfiles = LibGit2.diff_files(repo, \"branch/a\", \"branch/b\", filter=filt)\n\nEquivalent to git diff --name-only --diff-filter= .\n\n\n\n" -}, - -{ - "location": "devdocs/libgit2.html#Base.LibGit2.fetch", - "page": "Base.LibGit2", - "title": "Base.LibGit2.fetch", - "category": "function", - "text": "fetch(rmt::GitRemote, refspecs; options::FetchOptions=FetchOptions(), msg=\"\")\n\nFetch from the specified rmt remote git repository, using refspecs to determine which remote branch(es) to fetch. The keyword arguments are:\n\noptions: determines the options for the fetch, e.g. whether to prune afterwards.\nmsg: a message to insert into the reflogs.\n\n\n\nfetch(repo::GitRepo; kwargs...)\n\nFetches updates from an upstream of the repository repo.\n\nThe keyword arguments are:\n\nremote::AbstractString=\"origin\": which remote, specified by name, of repo to fetch from. If this is empty, the URL will be used to construct an anonymous remote.\nremoteurl::AbstractString=\"\": the URL of remote. If not specified, will be assumed based on the given name of remote.\nrefspecs=AbstractString[]: determines properties of the fetch.\npayload=Nullable{AbstractCredentials}(): provides credentials, if necessary, for instance if remote is a private repository.\n\nEquivalent to git fetch [|] [].\n\n\n\n" -}, - -{ - "location": "devdocs/libgit2.html#Base.LibGit2.fetch_refspecs", - "page": "Base.LibGit2", - "title": "Base.LibGit2.fetch_refspecs", - "category": "function", - "text": "fetch_refspecs(rmt::GitRemote) -> Vector{String}\n\nGet the fetch refspecs for the specified rmt. These refspecs contain information about which branch(es) to fetch from.\n\n\n\n" -}, - -{ - "location": "devdocs/libgit2.html#Base.LibGit2.fetchhead_foreach_cb", - "page": "Base.LibGit2", - "title": "Base.LibGit2.fetchhead_foreach_cb", - "category": "function", - "text": "C function pointer for fetchhead_foreach_callback\n\n\n\n" -}, - -{ - "location": "devdocs/libgit2.html#Base.LibGit2.ffmerge!", - "page": "Base.LibGit2", - "title": "Base.LibGit2.ffmerge!", - "category": "function", - "text": "Fastforward merge changes into current head \n\n\n\n" -}, - -{ - "location": "devdocs/libgit2.html#Base.LibGit2.fullname", - "page": "Base.LibGit2", - "title": "Base.LibGit2.fullname", - "category": "function", - "text": "LibGit2.fullname(ref::GitReference)\n\nReturn the name of the reference pointed to by the symbolic reference ref. If ref is not a symbolic reference, returns an empty string.\n\n\n\n" -}, - -{ - "location": "devdocs/libgit2.html#Base.LibGit2.get_creds!", - "page": "Base.LibGit2", - "title": "Base.LibGit2.get_creds!", - "category": "function", - "text": "Obtain the cached credentials for the given host+protocol (credid), or return and store the default if not found\n\n\n\n" -}, - -{ - "location": "devdocs/libgit2.html#Base.LibGit2.gitdir", - "page": "Base.LibGit2", - "title": "Base.LibGit2.gitdir", - "category": "function", - "text": "LibGit2.gitdir(repo::GitRepo)\n\nReturns the location of the \"git\" files of repo:\n\nfor normal repositories, this is the location of the .git folder.\nfor bare repositories, this is the location of the repository itself.\n\nSee also workdir, path.\n\n\n\n" -}, - -{ - "location": "devdocs/libgit2.html#Base.LibGit2.head", - "page": "Base.LibGit2", - "title": "Base.LibGit2.head", - "category": "function", - "text": "LibGit2.head(repo::GitRepo) -> GitReference\n\nReturns a GitReference to the current HEAD of repo.\n\n\n\nhead(pkg::AbstractString) -> String\n\nReturn current HEAD GitHash of the pkg repo as a string.\n\n\n\n" -}, - -{ - "location": "devdocs/libgit2.html#Base.LibGit2.head!", - "page": "Base.LibGit2", - "title": "Base.LibGit2.head!", - "category": "function", - "text": "LibGit2.head!(repo::GitRepo, ref::GitReference) -> GitReference\n\nSet the HEAD of repo to the object pointed to by ref.\n\n\n\n" -}, - -{ - "location": "devdocs/libgit2.html#Base.LibGit2.head_oid", - "page": "Base.LibGit2", - "title": "Base.LibGit2.head_oid", - "category": "function", - "text": "LibGit2.head_oid(repo::GitRepo) -> GitHash\n\nLookup the object id of the current HEAD of git repository repo.\n\n\n\n" -}, - -{ - "location": "devdocs/libgit2.html#Base.LibGit2.headname", - "page": "Base.LibGit2", - "title": "Base.LibGit2.headname", - "category": "function", - "text": "LibGit2.headname(repo::GitRepo)\n\nLookup the name of the current HEAD of git repository repo. If repo is currently detached, returns the name of the HEAD it\'s detached from.\n\n\n\n" -}, - -{ - "location": "devdocs/libgit2.html#Base.LibGit2.init", - "page": "Base.LibGit2", - "title": "Base.LibGit2.init", - "category": "function", - "text": "LibGit2.init(path::AbstractString, bare::Bool=false) -> GitRepo\n\nOpens a new git repository at path. If bare is false, the working tree will be created in path/.git. If bare is true, no working directory will be created.\n\n\n\n" -}, - -{ - "location": "devdocs/libgit2.html#Base.LibGit2.is_ancestor_of", - "page": "Base.LibGit2", - "title": "Base.LibGit2.is_ancestor_of", - "category": "function", - "text": "is_ancestor_of(a::AbstractString, b::AbstractString, repo::GitRepo) -> Bool\n\nReturns true if a, a GitHash in string form, is an ancestor of b, a GitHash in string form.\n\nExample\n\njulia> repo = LibGit2.GitRepo(repo_path);\n\njulia> LibGit2.add!(repo, test_file1);\n\njulia> commit_oid1 = LibGit2.commit(repo, \"commit1\");\n\njulia> LibGit2.add!(repo, test_file2);\n\njulia> commit_oid2 = LibGit2.commit(repo, \"commit2\");\n\njulia> LibGit2.is_ancestor_of(string(commit_oid1), string(commit_oid2), repo)\ntrue\n\n\n\n" -}, - -{ - "location": "devdocs/libgit2.html#Base.LibGit2.isbinary", - "page": "Base.LibGit2", - "title": "Base.LibGit2.isbinary", - "category": "function", - "text": "Use a heuristic to guess if a file is binary: searching for NULL bytes and looking for a reasonable ratio of printable to non-printable characters among the first 8000 bytes.\n\n\n\n" -}, - -{ - "location": "devdocs/libgit2.html#Base.LibGit2.iscommit", - "page": "Base.LibGit2", - "title": "Base.LibGit2.iscommit", - "category": "function", - "text": "iscommit(id::AbstractString, repo::GitRepo) -> Bool\n\nChecks if commit id (which is a GitHash in string form) is in the repository.\n\nExample\n\njulia> repo = LibGit2.GitRepo(repo_path);\n\njulia> LibGit2.add!(repo, test_file);\n\njulia> commit_oid = LibGit2.commit(repo, \"add test_file\");\n\njulia> LibGit2.iscommit(string(commit_oid), repo)\ntrue\n\n\n\n" -}, - -{ - "location": "devdocs/libgit2.html#Base.LibGit2.isdiff", - "page": "Base.LibGit2", - "title": "Base.LibGit2.isdiff", - "category": "function", - "text": "LibGit2.isdiff(repo::GitRepo, treeish::AbstractString, pathspecs::AbstractString=\"\"; cached::Bool=false)\n\nChecks if there are any differences between the tree specified by treeish and the tracked files in the working tree (if cached=false) or the index (if cached=true). pathspecs are the specifications for options for the diff.\n\nExample\n\nrepo = LibGit2.GitRepo(repo_path)\nLibGit2.isdiff(repo, \"HEAD\") # should be false\nopen(joinpath(repo_path, new_file), \"a\") do f\n println(f, \"here\'s my cool new file\")\nend\nLibGit2.isdiff(repo, \"HEAD\") # now true\n\nEquivalent to git diff-index [-- ].\n\n\n\n" -}, - -{ - "location": "devdocs/libgit2.html#Base.LibGit2.isdirty", - "page": "Base.LibGit2", - "title": "Base.LibGit2.isdirty", - "category": "function", - "text": "LibGit2.isdirty(repo::GitRepo, pathspecs::AbstractString=\"\"; cached::Bool=false) -> Bool\n\nChecks if there have been any changes to tracked files in the working tree (if cached=false) or the index (if cached=true). pathspecs are the specifications for options for the diff.\n\nExample\n\nrepo = LibGit2.GitRepo(repo_path)\nLibGit2.isdirty(repo) # should be false\nopen(joinpath(repo_path, new_file), \"a\") do f\n println(f, \"here\'s my cool new file\")\nend\nLibGit2.isdirty(repo) # now true\nLibGit2.isdirty(repo, new_file) # now true\n\nEquivalent to git diff-index HEAD [-- ].\n\n\n\n" -}, - -{ - "location": "devdocs/libgit2.html#Base.LibGit2.isorphan", - "page": "Base.LibGit2", - "title": "Base.LibGit2.isorphan", - "category": "function", - "text": "LibGit2.isorphan(repo::GitRepo)\n\nChecks if the current branch is an \"orphan\" branch, i.e. has no commits. The first commit to this branch will have no parents.\n\n\n\n" -}, - -{ - "location": "devdocs/libgit2.html#Base.LibGit2.lookup_branch", - "page": "Base.LibGit2", - "title": "Base.LibGit2.lookup_branch", - "category": "function", - "text": "lookup_branch(repo::GitRepo, branch_name::AbstractString, remote::Bool=false) -> Nullable{GitReference}\n\nDetermine if the branch specified by branch_name exists in the repository repo. If remote is true, repo is assumed to be a remote git repository. Otherwise, it is part of the local filesystem.\n\nlookup_branch returns a Nullable, which will be null if the requested branch does not exist yet. If the branch does exist, the Nullable contains a GitReference to the branch.\n\n\n\n" -}, - -{ - "location": "devdocs/libgit2.html#Base.LibGit2.mirror_callback", - "page": "Base.LibGit2", - "title": "Base.LibGit2.mirror_callback", - "category": "function", - "text": "Mirror callback function\n\nFunction sets +refs/*:refs/* refspecs and mirror flag for remote reference.\n\n\n\n" -}, - -{ - "location": "devdocs/libgit2.html#Base.LibGit2.mirror_cb", - "page": "Base.LibGit2", - "title": "Base.LibGit2.mirror_cb", - "category": "function", - "text": "C function pointer for mirror_callback\n\n\n\n" -}, - -{ - "location": "devdocs/libgit2.html#Base.LibGit2.name", - "page": "Base.LibGit2", - "title": "Base.LibGit2.name", - "category": "function", - "text": "LibGit2.name(ref::GitReference)\n\nReturn the full name of ref.\n\n\n\nname(rmt::GitRemote)\n\nGet the name of a remote repository, for instance \"origin\". If the remote is anonymous (see GitRemoteAnon) the name will be an empty string \"\".\n\nExample\n\njulia> repo_url = \"https://github.com/JuliaLang/Example.jl\";\n\njulia> repo = LibGit2.clone(cache_repo, \"test_directory\");\n\njulia> remote = LibGit2.GitRemote(repo, \"origin\", repo_url);\n\njulia> name(remote)\n\"origin\"\n\n\n\nLibGit2.name(tag::GitTag)\n\nThe name of tag (e.g. \"v0.5\").\n\n\n\n" -}, - -{ - "location": "devdocs/libgit2.html#Base.LibGit2.need_update", - "page": "Base.LibGit2", - "title": "Base.LibGit2.need_update", - "category": "function", - "text": "need_update(repo::GitRepo)\n\nEquivalent to git update-index. Returns true if repo needs updating.\n\n\n\n" -}, - -{ - "location": "devdocs/libgit2.html#Base.LibGit2.objtype", - "page": "Base.LibGit2", - "title": "Base.LibGit2.objtype", - "category": "function", - "text": "objtype(obj_type::Consts.OBJECT)\n\nReturns the type corresponding to the enum value.\n\n\n\n" -}, - -{ - "location": "devdocs/libgit2.html#Base.LibGit2.path", - "page": "Base.LibGit2", - "title": "Base.LibGit2.path", - "category": "function", - "text": "LibGit2.path(repo::GitRepo)\n\nThe base file path of the repository repo.\n\nfor normal repositories, this will typically be the parent directory of the \".git\" directory (note: this may be different than the working directory, see workdir for more details).\nfor bare repositories, this is the location of the \"git\" files.\n\nSee also gitdir, workdir.\n\n\n\n" -}, - -{ - "location": "devdocs/libgit2.html#Base.LibGit2.peel", - "page": "Base.LibGit2", - "title": "Base.LibGit2.peel", - "category": "function", - "text": "peel([T,] ref::GitReference)\n\nRecursively peel ref until an object of type T is obtained. If no T is provided, then ref will be peeled until an object other than a GitTag is obtained.\n\nA GitTag will be peeled to the object it references.\nA GitCommit will be peeled to a GitTree.\n\nnote: Note\nOnly annotated tags can be peeled to GitTag objects. Lightweight tags (the default) are references under refs/tags/ which point directly to GitCommit objects.\n\n\n\npeel([T,] obj::GitObject)\n\nRecursively peel obj until an object of type T is obtained. If no T is provided, then obj will be peeled until the type changes.\n\nA GitTag will be peeled to the object it references.\nA GitCommit will be peeled to a GitTree.\n\n\n\n" -}, - -{ - "location": "devdocs/libgit2.html#Base.LibGit2.posixpath", - "page": "Base.LibGit2", - "title": "Base.LibGit2.posixpath", - "category": "function", - "text": "LibGit2.posixpath(path)\n\nStandardise the path string path to use POSIX separators.\n\n\n\n" -}, - -{ - "location": "devdocs/libgit2.html#Base.LibGit2.push", - "page": "Base.LibGit2", - "title": "Base.LibGit2.push", - "category": "function", - "text": "push(rmt::GitRemote, refspecs; force::Bool=false, options::PushOptions=PushOptions())\n\nPush to the specified rmt remote git repository, using refspecs to determine which remote branch(es) to push to. The keyword arguments are:\n\nforce: if true, a force-push will occur, disregarding conflicts.\noptions: determines the options for the push, e.g. which proxy headers to use.\n\nnote: Note\nYou can add information about the push refspecs in two other ways: by setting an option in the repository\'s GitConfig (with push.default as the key) or by calling add_push!. Otherwise you will need to explicitly specify a push refspec in the call to push for it to have any effect, like so: LibGit2.push(repo, refspecs=[\"refs/heads/master\"]).\n\n\n\npush(repo::GitRepo; kwargs...)\n\nPushes updates to an upstream of repo.\n\nThe keyword arguments are:\n\nremote::AbstractString=\"origin\": the name of the upstream remote to push to.\nremoteurl::AbstractString=\"\": the URL of remote.\nrefspecs=AbstractString[]: determines properties of the push.\nforce::Bool=false: determines if the push will be a force push, overwriting the remote branch.\npayload=Nullable{AbstractCredentials}(): provides credentials, if necessary, for instance if remote is a private repository.\n\nEquivalent to git push [|] [].\n\n\n\n" -}, - -{ - "location": "devdocs/libgit2.html#Base.LibGit2.push_refspecs", - "page": "Base.LibGit2", - "title": "Base.LibGit2.push_refspecs", - "category": "function", - "text": "push_refspecs(rmt::GitRemote) -> Vector{String}\n\nGet the push refspecs for the specified rmt. These refspecs contain information about which branch(es) to push to.\n\n\n\n" -}, - -{ - "location": "devdocs/libgit2.html#Base.LibGit2.read_tree!", - "page": "Base.LibGit2", - "title": "Base.LibGit2.read_tree!", - "category": "function", - "text": "LibGit2.read_tree!(idx::GitIndex, tree::GitTree)\nLibGit2.read_tree!(idx::GitIndex, treehash::AbstractGitHash)\n\nRead the tree tree (or the tree pointed to by treehash in the repository owned by idx) into the index idx. The current index contents will be replaced.\n\n\n\n" -}, - -{ - "location": "devdocs/libgit2.html#Base.LibGit2.rebase!", - "page": "Base.LibGit2", - "title": "Base.LibGit2.rebase!", - "category": "function", - "text": "LibGit2.rebase!(repo::GitRepo, upstream::AbstractString=\"\", newbase::AbstractString=\"\")\n\nAttempt an automatic merge rebase of the current branch, from upstream if provided, or otherwise from the upstream tracking branch. newbase is the branch to rebase onto. By default this is upstream.\n\nIf any conflicts arise which cannot be automatically resolved, the rebase will abort, leaving the repository and working tree in its original state, and the function will throw a GitError. This is roughly equivalent to the following command line statement:\n\ngit rebase --merge []\nif [ -d \".git/rebase-merge\" ]; then\n git rebase --abort\nfi\n\n\n\n" -}, - -{ - "location": "devdocs/libgit2.html#Base.LibGit2.ref_list", - "page": "Base.LibGit2", - "title": "Base.LibGit2.ref_list", - "category": "function", - "text": "LibGit2.ref_list(repo::GitRepo) -> Vector{String}\n\nGet a list of all reference names in the repo repository.\n\n\n\n" -}, - -{ - "location": "devdocs/libgit2.html#Base.LibGit2.reftype", - "page": "Base.LibGit2", - "title": "Base.LibGit2.reftype", - "category": "function", - "text": "LibGit2.reftype(ref::GitReference) -> Cint\n\nReturns a Cint corresponding to the type of ref:\n\n0 if the reference is invalid\n1 if the reference is an object id\n2 if the reference is symbolic\n\n\n\n" -}, - -{ - "location": "devdocs/libgit2.html#Base.LibGit2.remotes", - "page": "Base.LibGit2", - "title": "Base.LibGit2.remotes", - "category": "function", - "text": "LibGit2.remotes(repo::GitRepo)\n\nReturns a vector of the names of the remotes of repo.\n\n\n\n" -}, - -{ - "location": "devdocs/libgit2.html#Base.LibGit2.reset!", - "page": "Base.LibGit2", - "title": "Base.LibGit2.reset!", - "category": "function", - "text": "Resets credentials for another use\n\n\n\nUpdates some entries, determined by the pathspecs, in the index from the target commit tree.\n\n\n\nSets the current head to the specified commit oid and optionally resets the index and working tree to match.\n\n\n\ngit reset [] [–] ... \n\n\n\nreset!(repo::GitRepo, id::GitHash, mode::Cint = Consts.RESET_MIXED)\n\nReset the repository repo to its state at id, using one of three modes set by mode:\n\nConsts.RESET_SOFT - move HEAD to id.\nConsts.RESET_MIXED - default, move HEAD to id and reset the index to id.\nConsts.RESET_HARD - move HEAD to id, reset the index to id, and discard all working changes.\n\nEquivalent to git reset [--soft | --mixed | --hard] .\n\nExample\n\nrepo = LibGit2.GitRepo(repo_path)\nhead_oid = LibGit2.head_oid(repo)\nopen(joinpath(repo_path, \"file1\"), \"w\") do f\n write(f, \"111\n\")\nend\nLibGit2.add!(repo, \"file1\")\nmode = LibGit2.Consts.RESET_HARD\n# will discard the changes to file1\n# and unstage it\nnew_head = LibGit2.reset!(repo, head_oid, mode)\n\n\n\n" -}, - -{ - "location": "devdocs/libgit2.html#Base.LibGit2.restore", - "page": "Base.LibGit2", - "title": "Base.LibGit2.restore", - "category": "function", - "text": "restore(s::State, repo::GitRepo)\n\nReturn a repository repo to a previous State s, for example the HEAD of a branch before a merge attempt. s can be generated using the snapshot function.\n\n\n\n" -}, - -{ - "location": "devdocs/libgit2.html#Base.LibGit2.revcount", - "page": "Base.LibGit2", - "title": "Base.LibGit2.revcount", - "category": "function", - "text": "LibGit2.revcount(repo::GitRepo, commit1::AbstractString, commit2::AbstractString)\n\nList the number of revisions between commit1 and commit2 (committish OIDs in string form). Since commit1 and commit2 may be on different branches, revcount performs a \"left-right\" revision list (and count), returning a tuple of Ints - the number of left and right commits, respectively. A left (or right) commit refers to which side of a symmetric difference in a tree the commit is reachable from.\n\nEquivalent to git rev-list --left-right --count .\n\n\n\n" -}, - -{ - "location": "devdocs/libgit2.html#Base.LibGit2.set_remote_url", - "page": "Base.LibGit2", - "title": "Base.LibGit2.set_remote_url", - "category": "function", - "text": "set_remote_url(repo::GitRepo, url::AbstractString; remote::AbstractString=\"origin\")\n\nSet the url for remote for the git repository repo. The default name of the remote is \"origin\".\n\nExamples\n\nrepo_path = joinpath(\"test_directory\", \"Example\")\nrepo = LibGit2.init(repo_path)\nurl1 = \"https://github.com/JuliaLang/Example.jl\"\nLibGit2.set_remote_url(repo, url1, remote=\"upstream\")\nurl2 = \"https://github.com/JuliaLang/Example2.jl\"\nLibGit2.set_remote_url(repo_path, url2, remote=\"upstream2\")\n\n\n\nset_remote_url(path::AbstractString, url::AbstractString; remote::AbstractString=\"origin\")\n\nSet the url for remote for the git repository located at path. The default name of the remote is \"origin\".\n\n\n\n" -}, - -{ - "location": "devdocs/libgit2.html#Base.LibGit2.shortname", - "page": "Base.LibGit2", - "title": "Base.LibGit2.shortname", - "category": "function", - "text": "LibGit2.shortname(ref::GitReference)\n\nReturns a shortened version of the name of ref that\'s \"human-readable\".\n\njulia> repo = LibGit2.GitRepo(path_to_repo);\n\njulia> branch_ref = LibGit2.head(repo);\n\njulia> LibGit2.name(branch_ref)\n\"refs/heads/master\"\n\njulia> LibGit2.shortname(branch_ref)\n\"master\"\n\n\n\n" -}, - -{ - "location": "devdocs/libgit2.html#Base.LibGit2.snapshot", - "page": "Base.LibGit2", - "title": "Base.LibGit2.snapshot", - "category": "function", - "text": "snapshot(repo::GitRepo) -> State\n\nTake a snapshot of the current state of the repository repo, storing the current HEAD, index, and any uncommitted work. The output State can be used later during a call to restore to return the repository to the snapshotted state.\n\n\n\n" -}, - -{ - "location": "devdocs/libgit2.html#Base.LibGit2.status", - "page": "Base.LibGit2", - "title": "Base.LibGit2.status", - "category": "function", - "text": "LibGit2.status(repo::GitRepo, path::String)\n\nLookup the status of the file at path in the git repository repo. For instance, this can be used to check if the file at path has been modified and needs to be staged and committed.\n\n\n\n" -}, - -{ - "location": "devdocs/libgit2.html#Base.LibGit2.tag_create", - "page": "Base.LibGit2", - "title": "Base.LibGit2.tag_create", - "category": "function", - "text": "LibGit2.tag_create(repo::GitRepo, tag::AbstractString, commit; kwargs...)\n\nCreate a new git tag tag (e.g. \"v0.5\") in the repository repo, at the commit commit.\n\nThe keyword arguments are:\n\nmsg::AbstractString=\"\": the message for the tag.\nforce::Bool=false: if true, existing references will be overwritten.\nsig::Signature=Signature(repo): the tagger\'s signature.\n\n\n\n" -}, - -{ - "location": "devdocs/libgit2.html#Base.LibGit2.tag_delete", - "page": "Base.LibGit2", - "title": "Base.LibGit2.tag_delete", - "category": "function", - "text": "LibGit2.tag_delete(repo::GitRepo, tag::AbstractString)\n\nRemove the git tag tag from the repository repo.\n\n\n\n" -}, - -{ - "location": "devdocs/libgit2.html#Base.LibGit2.tag_list", - "page": "Base.LibGit2", - "title": "Base.LibGit2.tag_list", - "category": "function", - "text": "LibGit2.tag_list(repo::GitRepo) -> Vector{String}\n\nGet a list of all tags in the git repository repo.\n\n\n\n" -}, - -{ - "location": "devdocs/libgit2.html#Base.LibGit2.target", - "page": "Base.LibGit2", - "title": "Base.LibGit2.target", - "category": "function", - "text": "LibGit2.target(tag::GitTag)\n\nThe GitHash of the target object of tag.\n\n\n\n" -}, - -{ - "location": "devdocs/libgit2.html#Base.LibGit2.treewalk", - "page": "Base.LibGit2", - "title": "Base.LibGit2.treewalk", - "category": "function", - "text": "Traverse the entries in a tree and its subtrees in post or pre order.\n\nFunction parameter should have following signature:\n\n(Cstring, Ptr{Void}, Ptr{Void}) -> Cint\n\n\n\n" -}, - -{ - "location": "devdocs/libgit2.html#Base.LibGit2.upstream", - "page": "Base.LibGit2", - "title": "Base.LibGit2.upstream", - "category": "function", - "text": "upstream(ref::GitReference) -> Nullable{GitReference}\n\nDetermine if the branch containing ref has a specified upstream branch.\n\nupstream returns a Nullable, which will be null if the requested branch does not have an upstream counterpart. If the upstream branch does exist, the Nullable contains a GitReference to the upstream branch.\n\n\n\n" -}, - -{ - "location": "devdocs/libgit2.html#Base.LibGit2.url", - "page": "Base.LibGit2", - "title": "Base.LibGit2.url", - "category": "function", - "text": "url(rmt::GitRemote)\n\nGet the fetch URL of a remote git repository.\n\nExample\n\njulia> repo_url = \"https://github.com/JuliaLang/Example.jl\";\n\njulia> repo = LibGit2.init(mktempdir());\n\njulia> remote = LibGit2.GitRemote(repo, \"origin\", repo_url);\n\njulia> LibGit2.url(remote)\n\"https://github.com/JuliaLang/Example.jl\"\n\n\n\n" -}, - -{ - "location": "devdocs/libgit2.html#Base.LibGit2.with", - "page": "Base.LibGit2", - "title": "Base.LibGit2.with", - "category": "function", - "text": "Resource management helper function\n\n\n\n" -}, - -{ - "location": "devdocs/libgit2.html#Base.LibGit2.workdir", - "page": "Base.LibGit2", - "title": "Base.LibGit2.workdir", - "category": "function", - "text": "LibGit2.workdir(repo::GitRepo)\n\nThe location of the working directory of repo. This will throw an error for bare repositories.\n\nnote: Note\nThis will typically be the parent directory of gitdir(repo), but can be different in some cases: e.g. if either the core.worktree configuration variable or the GIT_WORK_TREE environment variable is set.\n\nSee also gitdir, path.\n\n\n\n" -}, - -{ - "location": "devdocs/libgit2.html#Functionality-1", - "page": "Base.LibGit2", - "title": "Functionality", - "category": "section", - "text": "Some of this documentation assumes some prior knowledge of the libgit2 API. For more information on some of the objects and methods referenced here, consult the upstream libgit2 API reference.Base.LibGit2.AbstractCredentials\nBase.LibGit2.Buffer\nBase.LibGit2.CachedCredentials\nBase.LibGit2.CheckoutOptions\nBase.LibGit2.CloneOptions\nBase.LibGit2.DiffDelta\nBase.LibGit2.DiffFile\nBase.LibGit2.DiffOptionsStruct\nBase.LibGit2.FetchHead\nBase.LibGit2.FetchOptions\nBase.LibGit2.GitBlob\nBase.LibGit2.GitCommit\nBase.LibGit2.GitHash\nBase.LibGit2.GitObject\nBase.LibGit2.GitRemote\nBase.LibGit2.GitRemoteAnon\nBase.LibGit2.GitRepo\nBase.LibGit2.GitRepoExt\nBase.LibGit2.GitShortHash\nBase.LibGit2.GitSignature\nBase.LibGit2.GitStatus\nBase.LibGit2.GitTag\nBase.LibGit2.GitTree\nBase.LibGit2.IndexEntry\nBase.LibGit2.IndexTime\nBase.LibGit2.MergeOptions\nBase.LibGit2.ProxyOptions\nBase.LibGit2.PushOptions\nBase.LibGit2.RebaseOperation\nBase.LibGit2.RebaseOptions\nBase.LibGit2.RemoteCallbacks\nBase.LibGit2.SSHCredentials\nBase.LibGit2.SignatureStruct\nBase.LibGit2.StatusEntry\nBase.LibGit2.StatusOptions\nBase.LibGit2.StrArrayStruct\nBase.LibGit2.TimeStruct\nBase.LibGit2.UserPasswordCredentials\nBase.LibGit2.add_fetch!\nBase.LibGit2.add_push!\nBase.LibGit2.addblob!\nBase.LibGit2.authors\nBase.LibGit2.branch\nBase.LibGit2.branch!\nBase.LibGit2.checkout!\nBase.LibGit2.checkused!\nBase.LibGit2.clone\nBase.LibGit2.commit\nBase.LibGit2.create_branch\nBase.LibGit2.credentials_callback\nBase.LibGit2.credentials_cb\nBase.LibGit2.default_signature\nBase.LibGit2.delete_branch\nBase.LibGit2.diff_files\nBase.LibGit2.fetch\nBase.LibGit2.fetch_refspecs\nBase.LibGit2.fetchhead_foreach_cb\nBase.LibGit2.ffmerge!\nBase.LibGit2.fullname\nBase.LibGit2.get_creds!\nBase.LibGit2.gitdir\nBase.LibGit2.head\nBase.LibGit2.head!\nBase.LibGit2.head_oid\nBase.LibGit2.headname\nBase.LibGit2.init\nBase.LibGit2.is_ancestor_of\nBase.LibGit2.isbinary\nBase.LibGit2.iscommit\nBase.LibGit2.isdiff\nBase.LibGit2.isdirty\nBase.LibGit2.isorphan\nBase.LibGit2.lookup_branch\nBase.LibGit2.mirror_callback\nBase.LibGit2.mirror_cb\nBase.LibGit2.name\nBase.LibGit2.need_update\nBase.LibGit2.objtype\nBase.LibGit2.path\nBase.LibGit2.peel\nBase.LibGit2.posixpath\nBase.LibGit2.push\nBase.LibGit2.push_refspecs\nBase.LibGit2.read_tree!\nBase.LibGit2.rebase!\nBase.LibGit2.ref_list\nBase.LibGit2.reftype\nBase.LibGit2.remotes\nBase.LibGit2.reset!\nBase.LibGit2.restore\nBase.LibGit2.revcount\nBase.LibGit2.set_remote_url\nBase.LibGit2.shortname\nBase.LibGit2.snapshot\nBase.LibGit2.status\nBase.LibGit2.tag_create\nBase.LibGit2.tag_delete\nBase.LibGit2.tag_list\nBase.LibGit2.target\nBase.LibGit2.treewalk\nBase.LibGit2.upstream\nBase.LibGit2.url\nBase.LibGit2.with\nBase.LibGit2.workdir" -}, - -{ - "location": "devdocs/require.html#", - "page": "Module loading", - "title": "Module loading", - "category": "page", - "text": "" -}, - -{ - "location": "devdocs/require.html#Module-loading-1", - "page": "Module loading", - "title": "Module loading", - "category": "section", - "text": "Base.require[@ref] is responsible for loading modules and it also manages the precompilation cache. It is the implementation of the import statement." -}, - -{ - "location": "devdocs/require.html#Experimental-features-1", - "page": "Module loading", - "title": "Experimental features", - "category": "section", - "text": "The features below are experimental and not part of the stable Julia API. Before building upon them inform yourself about the current thinking and whether they might change soon." -}, - -{ - "location": "devdocs/require.html#Module-loading-callbacks-1", - "page": "Module loading", - "title": "Module loading callbacks", - "category": "section", - "text": "It is possible to listen to the modules loaded by Base.require, by registering a callback.loaded_packages = Channel{Symbol}()\ncallback = (mod::Symbol) -> put!(loaded_packages, mod)\npush!(Base.package_callbacks, callback)Please note that the symbol given to the callback is a non-unique identifier and it is the responsibility of the callback provider to walk the module chain to determine the fully qualified name of the loaded binding.The callback below is an example of how to do that:# Get the fully-qualified name of a module.\nfunction module_fqn(name::Symbol)\n fqn = Symbol[name]\n mod = getfield(Main, name)\n parent = Base.module_parent(mod)\n while parent !== Main\n push!(fqn, Base.module_name(parent))\n parent = Base.module_parent(parent)\n end\n fqn = reverse!(fqn)\n return join(fqn, \'.\')\nend" -}, - -{ - "location": "devdocs/backtraces.html#", - "page": "Reporting and analyzing crashes (segfaults)", - "title": "Reporting and analyzing crashes (segfaults)", - "category": "page", - "text": "" -}, - -{ - "location": "devdocs/backtraces.html#Reporting-and-analyzing-crashes-(segfaults)-1", - "page": "Reporting and analyzing crashes (segfaults)", - "title": "Reporting and analyzing crashes (segfaults)", - "category": "section", - "text": "So you managed to break Julia. Congratulations! Collected here are some general procedures you can undergo for common symptoms encountered when something goes awry. Including the information from these debugging steps can greatly help the maintainers when tracking down a segfault or trying to figure out why your script is running slower than expected.If you\'ve been directed to this page, find the symptom that best matches what you\'re experiencing and follow the instructions to generate the debugging information requested. Table of symptoms:Segfaults during bootstrap (sysimg.jl)\nSegfaults when running a script\nErrors during Julia startup" -}, - -{ - "location": "devdocs/backtraces.html#dev-version-info-1", - "page": "Reporting and analyzing crashes (segfaults)", - "title": "Version/Environment info", - "category": "section", - "text": "No matter the error, we will always need to know what version of Julia you are running. When Julia first starts up, a header is printed out with a version number and date. If your version is 0.2.0 or higher, please include the output of versioninfo() in any report you create:versioninfo()" -}, - -{ - "location": "devdocs/backtraces.html#Segfaults-during-bootstrap-(sysimg.jl)-1", - "page": "Reporting and analyzing crashes (segfaults)", - "title": "Segfaults during bootstrap (sysimg.jl)", - "category": "section", - "text": "Segfaults toward the end of the make process of building Julia are a common symptom of something going wrong while Julia is preparsing the corpus of code in the base/ folder. Many factors can contribute toward this process dying unexpectedly, however it is as often as not due to an error in the C-code portion of Julia, and as such must typically be debugged with a debug build inside of gdb. Explicitly:Create a debug build of Julia:$ cd \n$ make debugNote that this process will likely fail with the same error as a normal make incantation, however this will create a debug executable that will offer gdb the debugging symbols needed to get accurate backtraces. Next, manually run the bootstrap process inside of gdb:$ cd base/\n$ gdb -x ../contrib/debug_bootstrap.gdbThis will start gdb, attempt to run the bootstrap process using the debug build of Julia, and print out a backtrace if (when) it segfaults. You may need to hit a few times to get the full backtrace. Create a gist with the backtrace, the version info, and any other pertinent information you can think of and open a new issue on Github with a link to the gist." -}, - -{ - "location": "devdocs/backtraces.html#Segfaults-when-running-a-script-1", - "page": "Reporting and analyzing crashes (segfaults)", - "title": "Segfaults when running a script", - "category": "section", - "text": "The procedure is very similar to Segfaults during bootstrap (sysimg.jl). Create a debug build of Julia, and run your script inside of a debugged Julia process:$ cd \n$ make debug\n$ gdb --args usr/bin/julia-debug Note that gdb will sit there, waiting for instructions. Type r to run the process, and bt to generate a backtrace once it segfaults:(gdb) r\nStarting program: /home/sabae/src/julia/usr/bin/julia-debug ./test.jl\n...\n(gdb) btCreate a gist with the backtrace, the version info, and any other pertinent information you can think of and open a new issue on Github with a link to the gist." -}, - -{ - "location": "devdocs/backtraces.html#Errors-during-Julia-startup-1", - "page": "Reporting and analyzing crashes (segfaults)", - "title": "Errors during Julia startup", - "category": "section", - "text": "Occasionally errors occur during Julia\'s startup process (especially when using binary distributions, as opposed to compiling from source) such as the following:$ julia\nexec: error -5These errors typically indicate something is not getting loaded properly very early on in the bootup phase, and our best bet in determining what\'s going wrong is to use external tools to audit the disk activity of the julia process:On Linux, use strace:\n$ strace julia\nOn OSX, use dtruss:\n$ dtruss -f juliaCreate a gist with the strace/ dtruss ouput, the version info, and any other pertinent information and open a new issue on Github with a link to the gist." -}, - -{ - "location": "devdocs/backtraces.html#Glossary-1", - "page": "Reporting and analyzing crashes (segfaults)", - "title": "Glossary", - "category": "section", - "text": "A few terms have been used as shorthand in this guide: refers to the root directory of the Julia source tree; e.g. it should contain folders such as base, deps, src, test, etc....." -}, - -{ - "location": "devdocs/debuggingtips.html#", - "page": "gdb debugging tips", - "title": "gdb debugging tips", - "category": "page", - "text": "" -}, - -{ - "location": "devdocs/debuggingtips.html#gdb-debugging-tips-1", - "page": "gdb debugging tips", - "title": "gdb debugging tips", - "category": "section", - "text": "" -}, - -{ - "location": "devdocs/debuggingtips.html#Displaying-Julia-variables-1", - "page": "gdb debugging tips", - "title": "Displaying Julia variables", - "category": "section", - "text": "Within gdb, any jl_value_t* object obj can be displayed using(gdb) call jl_(obj)The object will be displayed in the julia session, not in the gdb session. This is a useful way to discover the types and values of objects being manipulated by Julia\'s C code.Similarly, if you\'re debugging some of Julia\'s internals (e.g., inference.jl), you can print obj usingccall(:jl_, Void, (Any,), obj)This is a good way to circumvent problems that arise from the order in which julia\'s output streams are initialized.Julia\'s flisp interpreter uses value_t objects; these can be displayed with call fl_print(fl_ctx, ios_stdout, obj)." -}, - -{ - "location": "devdocs/debuggingtips.html#Useful-Julia-variables-for-Inspecting-1", - "page": "gdb debugging tips", - "title": "Useful Julia variables for Inspecting", - "category": "section", - "text": "While the addresses of many variables, like singletons, can be be useful to print for many failures, there are a number of additional variables (see julia.h for a complete list) that are even more useful.(when in jl_apply_generic) mfunc and jl_uncompress_ast(mfunc->def, mfunc->code) :: for figuring out a bit about the call-stack\njl_lineno and jl_filename :: for figuring out what line in a test to go start debugging from (or figure out how far into a file has been parsed)\n$1 :: not really a variable, but still a useful shorthand for referring to the result of the last gdb command (such as print)\njl_options :: sometimes useful, since it lists all of the command line options that were successfully parsed\njl_uv_stderr :: because who doesn\'t like to be able to interact with stdio" -}, - -{ - "location": "devdocs/debuggingtips.html#Useful-Julia-functions-for-Inspecting-those-variables-1", - "page": "gdb debugging tips", - "title": "Useful Julia functions for Inspecting those variables", - "category": "section", - "text": "jl_gdblookup($rip) :: For looking up the current function and line. (use $eip on i686 platforms)\njlbacktrace() :: For dumping the current Julia backtrace stack to stderr. Only usable after record_backtrace() has been called.\njl_dump_llvm_value(Value*) :: For invoking Value->dump() in gdb, where it doesn\'t work natively. For example, f->linfo->functionObject, f->linfo->specFunctionObject, and to_function(f->linfo).\nType->dump() :: only works in lldb. Note: add something like ;1 to prevent lldb from printing its prompt over the output\njl_eval_string(\"expr\") :: for invoking side-effects to modify the current state or to lookup symbols\njl_typeof(jl_value_t*) :: for extracting the type tag of a Julia value (in gdb, call macro define jl_typeof jl_typeof first, or pick something short like ty for the first arg to define a shorthand)" -}, - -{ - "location": "devdocs/debuggingtips.html#Inserting-breakpoints-for-inspection-from-gdb-1", - "page": "gdb debugging tips", - "title": "Inserting breakpoints for inspection from gdb", - "category": "section", - "text": "In your gdb session, set a breakpoint in jl_breakpoint like so:(gdb) break jl_breakpointThen within your Julia code, insert a call to jl_breakpoint by addingccall(:jl_breakpoint, Void, (Any,), obj)where obj can be any variable or tuple you want to be accessible in the breakpoint.It\'s particularly helpful to back up to the jl_apply frame, from which you can display the arguments to a function using, e.g.,(gdb) call jl_(args[0])Another useful frame is to_function(jl_method_instance_t *li, bool cstyle). The jl_method_instance_t* argument is a struct with a reference to the final AST sent into the compiler. However, the AST at this point will usually be compressed; to view the AST, call jl_uncompress_ast and then pass the result to jl_:#2 0x00007ffff7928bf7 in to_function (li=0x2812060, cstyle=false) at codegen.cpp:584\n584 abort();\n(gdb) p jl_(jl_uncompress_ast(li, li->ast))" -}, - -{ - "location": "devdocs/debuggingtips.html#Inserting-breakpoints-upon-certain-conditions-1", - "page": "gdb debugging tips", - "title": "Inserting breakpoints upon certain conditions", - "category": "section", - "text": "" -}, - -{ - "location": "devdocs/debuggingtips.html#Loading-a-particular-file-1", - "page": "gdb debugging tips", - "title": "Loading a particular file", - "category": "section", - "text": "Let\'s say the file is sysimg.jl:(gdb) break jl_load if strcmp(fname, \"sysimg.jl\")==0" -}, - -{ - "location": "devdocs/debuggingtips.html#Calling-a-particular-method-1", - "page": "gdb debugging tips", - "title": "Calling a particular method", - "category": "section", - "text": "(gdb) break jl_apply_generic if strcmp((char*)(jl_symbol_name)(jl_gf_mtable(F)->name), \"method_to_break\")==0Since this function is used for every call, you will make everything 1000x slower if you do this." -}, - -{ - "location": "devdocs/debuggingtips.html#Dealing-with-signals-1", - "page": "gdb debugging tips", - "title": "Dealing with signals", - "category": "section", - "text": "Julia requires a few signal to function property. The profiler uses SIGUSR2 for sampling and the garbage collector uses SIGSEGV for threads synchronization. If you are debugging some code that uses the profiler or multiple threads, you may want to let the debugger ignore these signals since they can be triggered very often during normal operations. The command to do this in GDB is (replace SIGSEGV with SIGUSRS or other signals you want to ignore):(gdb) handle SIGSEGV noprint nostop passThe corresponding LLDB command is (after the process is started):(lldb) pro hand -p true -s false -n false SIGSEGVIf you are debugging a segfault with threaded code, you can set a breakpoint on jl_critical_error (sigdie_handler should also work on Linux and BSD) in order to only catch the actual segfault rather than the GC synchronization points." -}, - -{ - "location": "devdocs/debuggingtips.html#Debugging-during-Julia\'s-build-process-(bootstrap)-1", - "page": "gdb debugging tips", - "title": "Debugging during Julia\'s build process (bootstrap)", - "category": "section", - "text": "Errors that occur during make need special handling. Julia is built in two stages, constructing sys0 and sys.ji. To see what commands are running at the time of failure, use make VERBOSE=1.At the time of this writing, you can debug build errors during the sys0 phase from the base directory using:julia/base$ gdb --args ../usr/bin/julia-debug -C native --build ../usr/lib/julia/sys0 sysimg.jlYou might need to delete all the files in usr/lib/julia/ to get this to work.You can debug the sys.ji phase using:julia/base$ gdb --args ../usr/bin/julia-debug -C native --build ../usr/lib/julia/sys -J ../usr/lib/julia/sys0.ji sysimg.jlBy default, any errors will cause Julia to exit, even under gdb. To catch an error \"in the act\", set a breakpoint in jl_error (there are several other useful spots, for specific kinds of failures, including: jl_too_few_args, jl_too_many_args, and jl_throw).Once an error is caught, a useful technique is to walk up the stack and examine the function by inspecting the related call to jl_apply. To take a real-world example:Breakpoint 1, jl_throw (e=0x7ffdf42de400) at task.c:802\n802 {\n(gdb) p jl_(e)\nErrorException(\"auto_unbox: unable to determine argument type\")\n$2 = void\n(gdb) bt 10\n#0 jl_throw (e=0x7ffdf42de400) at task.c:802\n#1 0x00007ffff65412fe in jl_error (str=0x7ffde56be000 <_j_str267> \"auto_unbox:\n unable to determine argument type\")\n at builtins.c:39\n#2 0x00007ffde56bd01a in julia_convert_16886 ()\n#3 0x00007ffff6541154 in jl_apply (f=0x7ffdf367f630, args=0x7fffffffc2b0, nargs=2) at julia.h:1281\n...The most recent jl_apply is at frame #3, so we can go back there and look at the AST for the function julia_convert_16886. This is the uniqued name for some method of convert. f in this frame is a jl_function_t*, so we can look at the type signature, if any, from the specTypes field:(gdb) f 3\n#3 0x00007ffff6541154 in jl_apply (f=0x7ffdf367f630, args=0x7fffffffc2b0, nargs=2) at julia.h:1281\n1281 return f->fptr((jl_value_t*)f, args, nargs);\n(gdb) p f->linfo->specTypes\n$4 = (jl_tupletype_t *) 0x7ffdf39b1030\n(gdb) p jl_( f->linfo->specTypes )\nTuple{Type{Float32}, Float64} # <-- type signature for julia_convert_16886Then, we can look at the AST for this function:(gdb) p jl_( jl_uncompress_ast(f->linfo, f->linfo->ast) )\nExpr(:lambda, Array{Any, 1}[:#s29, :x], Array{Any, 1}[Array{Any, 1}[], Array{Any, 1}[Array{Any, 1}[:#s29, :Any, 0], Array{Any, 1}[:x, :Any, 0]], Array{Any, 1}[], 0], Expr(:body,\nExpr(:line, 90, :float.jl)::Any,\nExpr(:return, Expr(:call, :box, :Float32, Expr(:call, :fptrunc, :Float32, :x)::Any)::Any)::Any)::Any)::AnyFinally, and perhaps most usefully, we can force the function to be recompiled in order to step through the codegen process. To do this, clear the cached functionObject from the jl_lamdbda_info_t*:(gdb) p f->linfo->functionObject\n$8 = (void *) 0x1289d070\n(gdb) set f->linfo->functionObject = NULLThen, set a breakpoint somewhere useful (e.g. emit_function, emit_expr, emit_call, etc.), and run codegen:(gdb) p jl_compile(f)\n... # your breakpoint here" -}, - -{ - "location": "devdocs/debuggingtips.html#Debugging-precompilation-errors-1", - "page": "gdb debugging tips", - "title": "Debugging precompilation errors", - "category": "section", - "text": "Module precompilation spawns a separate Julia process to precompile each module. Setting a breakpoint or catching failures in a precompile worker requires attaching a debugger to the worker. The easiest approach is to set the debugger watch for new process launches matching a given name. For example:(gdb) attach -w -n julia-debugor:(lldb) process attach -w -n julia-debugThen run a script/command to start precompilation. As described earlier, use conditional breakpoints in the parent process to catch specific file-loading events and narrow the debugging window. (some operating systems may require alternative approaches, such as following each fork from the parent process)" -}, - -{ - "location": "devdocs/debuggingtips.html#Mozilla\'s-Record-and-Replay-Framework-(rr)-1", - "page": "gdb debugging tips", - "title": "Mozilla\'s Record and Replay Framework (rr)", - "category": "section", - "text": "Julia now works out of the box with rr, the lightweight recording and deterministic debugging framework from Mozilla. This allows you to replay the trace of an execution deterministically. The replayed execution\'s address spaces, register contents, syscall data etc are exactly the same in every run.A recent version of rr (3.1.0 or higher) is required." -}, - -{ - "location": "devdocs/valgrind.html#", - "page": "Using Valgrind with Julia", - "title": "Using Valgrind with Julia", - "category": "page", - "text": "" -}, - -{ - "location": "devdocs/valgrind.html#Using-Valgrind-with-Julia-1", - "page": "Using Valgrind with Julia", - "title": "Using Valgrind with Julia", - "category": "section", - "text": "Valgrind is a tool for memory debugging, memory leak detection, and profiling. This section describes things to keep in mind when using Valgrind to debug memory issues with Julia." -}, - -{ - "location": "devdocs/valgrind.html#General-considerations-1", - "page": "Using Valgrind with Julia", - "title": "General considerations", - "category": "section", - "text": "By default, Valgrind assumes that there is no self modifying code in the programs it runs. This assumption works fine in most instances but fails miserably for a just-in-time compiler like julia. For this reason it is crucial to pass --smc-check=all-non-file to valgrind, else code may crash or behave unexpectedly (often in subtle ways).In some cases, to better detect memory errors using Valgrind it can help to compile julia with memory pools disabled. The compile-time flag MEMDEBUG disables memory pools in Julia, and MEMDEBUG2 disables memory pools in FemtoLisp. To build julia with both flags, add the following line to Make.user:CFLAGS = -DMEMDEBUG -DMEMDEBUG2Another thing to note: if your program uses multiple workers processes, it is likely that you want all such worker processes to run under Valgrind, not just the parent process. To do this, pass --trace-children=yes to valgrind." -}, - -{ - "location": "devdocs/valgrind.html#Suppressions-1", - "page": "Using Valgrind with Julia", - "title": "Suppressions", - "category": "section", - "text": "Valgrind will typically display spurious warnings as it runs. To reduce the number of such warnings, it helps to provide a suppressions file to Valgrind. A sample suppressions file is included in the Julia source distribution at contrib/valgrind-julia.supp.The suppressions file can be used from the julia/ source directory as follows:$ valgrind --smc-check=all-non-file --suppressions=contrib/valgrind-julia.supp ./julia progname.jlAny memory errors that are displayed should either be reported as bugs or contributed as additional suppressions. Note that some versions of Valgrind are shipped with insufficient default suppressions, so that may be one thing to consider before submitting any bugs." -}, - -{ - "location": "devdocs/valgrind.html#Running-the-Julia-test-suite-under-Valgrind-1", - "page": "Using Valgrind with Julia", - "title": "Running the Julia test suite under Valgrind", - "category": "section", - "text": "It is possible to run the entire Julia test suite under Valgrind, but it does take quite some time (typically several hours). To do so, run the following command from the julia/test/ directory:valgrind --smc-check=all-non-file --trace-children=yes --suppressions=$PWD/../contrib/valgrind-julia.supp ../julia runtests.jl allIf you would like to see a report of \"definite\" memory leaks, pass the flags --leak-check=full --show-leak-kinds=definite to valgrind as well." -}, - -{ - "location": "devdocs/valgrind.html#Caveats-1", - "page": "Using Valgrind with Julia", - "title": "Caveats", - "category": "section", - "text": "Valgrind currently does not support multiple rounding modes, so code that adjusts the rounding mode will behave differently when run under Valgrind.In general, if after setting --smc-check=all-non-file you find that your program behaves differently when run under Valgrind, it may help to pass --tool=none to valgrind as you investigate further. This will enable the minimal Valgrind machinery but will also run much faster than when the full memory checker is enabled." -}, - -{ - "location": "devdocs/sanitizers.html#", - "page": "Sanitizer support", - "title": "Sanitizer support", - "category": "page", - "text": "" -}, - -{ - "location": "devdocs/sanitizers.html#Sanitizer-support-1", - "page": "Sanitizer support", - "title": "Sanitizer support", - "category": "section", - "text": "" -}, - -{ - "location": "devdocs/sanitizers.html#General-considerations-1", - "page": "Sanitizer support", - "title": "General considerations", - "category": "section", - "text": "Using Clang\'s sanitizers obviously require you to use Clang (USECLANG=1), but there\'s another catch: most sanitizers require a run-time library, provided by the host compiler, while the instrumented code generated by Julia\'s JIT relies on functionality from that library. This implies that the LLVM version of your host compiler matches that of the LLVM library used within Julia.An easy solution is to have an dedicated build folder for providing a matching toolchain, by building with BUILD_LLVM_CLANG=1 and overriding LLVM_USE_CMAKE=1 (Autotool-based builds are incompatible with ASAN). You can then refer to this toolchain from another build folder by specifying USECLANG=1 while overriding the CC and CXX variables." -}, - -{ - "location": "devdocs/sanitizers.html#Address-Sanitizer-(ASAN)-1", - "page": "Sanitizer support", - "title": "Address Sanitizer (ASAN)", - "category": "section", - "text": "For detecting or debugging memory bugs, you can use Clang\'s address sanitizer (ASAN). By compiling with SANITIZE=1 you enable ASAN for the Julia compiler and its generated code. In addition, you can specify LLVM_SANITIZE=1 to sanitize the LLVM library as well. Note that these options incur a high performance and memory cost. For example, using ASAN for Julia and LLVM makes testall1 takes 8-10 times as long while using 20 times as much memory (this can be reduced to respectively a factor of 3 and 4 by using the options described below).By default, Julia sets the allow_user_segv_handler=1 ASAN flag, which is required for signal delivery to work properly. You can define other options using the ASAN_OPTIONS environment flag, in which case you\'ll need to repeat the default option mentioned before. For example, memory usage can be reduced by specifying fast_unwind_on_malloc=0 and malloc_context_size=2, at the cost of backtrace accuracy. For now, Julia also sets detect_leaks=0, but this should be removed in the future." -}, - -{ - "location": "devdocs/sanitizers.html#Memory-Sanitizer-(MSAN)-1", - "page": "Sanitizer support", - "title": "Memory Sanitizer (MSAN)", - "category": "section", - "text": "For detecting use of uninitialized memory, you can use Clang\'s memory sanitizer (MSAN) by compiling with SANITIZE_MEMORY=1." -}, - -]} diff --git a/julia-0.6.3/share/doc/julia/html/en/stdlib/arrays.html b/julia-0.6.3/share/doc/julia/html/en/stdlib/arrays.html deleted file mode 100644 index c70ada4..0000000 --- a/julia-0.6.3/share/doc/julia/html/en/stdlib/arrays.html +++ /dev/null @@ -1,1499 +0,0 @@ - -Arrays · The Julia Language

      Arrays

      Arrays

      Constructors and Types

      AbstractArray{T, N}

      Abstract array supertype which arrays inherit from.

      source
      Core.ArrayType.
      Array{T}(dims)
      -Array{T,N}(dims)

      Construct an uninitialized N-dimensional dense array with element type T, where N is determined from the length or number of dims. dims may be a tuple or a series of integer arguments corresponding to the lengths in each dimension. If the rank N is supplied explicitly as in Array{T,N}(dims), then it must match the length or number of dims.

      Example

      julia> A = Array{Float64, 2}(2, 2);
      -
      -julia> ndims(A)
      -2
      -
      -julia> eltype(A)
      -Float64
      source
      Base.getindexMethod.
      getindex(type[, elements...])

      Construct a 1-d array of the specified type. This is usually called with the syntax Type[]. Element values can be specified using Type[a,b,c,...].

      Example

      julia> Int8[1, 2, 3]
      -3-element Array{Int8,1}:
      - 1
      - 2
      - 3
      -
      -julia> getindex(Int8, 1, 2, 3)
      -3-element Array{Int8,1}:
      - 1
      - 2
      - 3
      source
      Base.zerosFunction.
      zeros([A::AbstractArray,] [T=eltype(A)::Type,] [dims=size(A)::Tuple])

      Create an array of all zeros with the same layout as A, element type T and size dims. The A argument can be skipped, which behaves like Array{Float64,0}() was passed. For convenience dims may also be passed in variadic form.

      Examples

      julia> zeros(1)
      -1-element Array{Float64,1}:
      - 0.0
      -
      -julia> zeros(Int8, 2, 3)
      -2×3 Array{Int8,2}:
      - 0  0  0
      - 0  0  0
      -
      -julia> A = [1 2; 3 4]
      -2×2 Array{Int64,2}:
      - 1  2
      - 3  4
      -
      -julia> zeros(A)
      -2×2 Array{Int64,2}:
      - 0  0
      - 0  0
      -
      -julia> zeros(A, Float64)
      -2×2 Array{Float64,2}:
      - 0.0  0.0
      - 0.0  0.0
      -
      -julia> zeros(A, Bool, (3,))
      -3-element Array{Bool,1}:
      - false
      - false
      - false

      See also ones, similar.

      source
      Base.onesFunction.
      ones([A::AbstractArray,] [T=eltype(A)::Type,] [dims=size(A)::Tuple])

      Create an array of all ones with the same layout as A, element type T and size dims. The A argument can be skipped, which behaves like Array{Float64,0}() was passed. For convenience dims may also be passed in variadic form.

      Examples

      julia> ones(Complex128, 2, 3)
      -2×3 Array{Complex{Float64},2}:
      - 1.0+0.0im  1.0+0.0im  1.0+0.0im
      - 1.0+0.0im  1.0+0.0im  1.0+0.0im
      -
      -julia> ones(1,2)
      -1×2 Array{Float64,2}:
      - 1.0  1.0
      -
      -julia> A = [1 2; 3 4]
      -2×2 Array{Int64,2}:
      - 1  2
      - 3  4
      -
      -julia> ones(A)
      -2×2 Array{Int64,2}:
      - 1  1
      - 1  1
      -
      -julia> ones(A, Float64)
      -2×2 Array{Float64,2}:
      - 1.0  1.0
      - 1.0  1.0
      -
      -julia> ones(A, Bool, (3,))
      -3-element Array{Bool,1}:
      - true
      - true
      - true

      See also zeros, similar.

      source
      Base.BitArrayType.
      BitArray(dims::Integer...)
      -BitArray{N}(dims::NTuple{N,Int})

      Construct an uninitialized BitArray with the given dimensions. Behaves identically to the Array constructor.

      julia> BitArray(2, 2)
      -2×2 BitArray{2}:
      - false  false
      - false  true
      -
      -julia> BitArray((3, 1))
      -3×1 BitArray{2}:
      - false
      - true
      - false
      source
      BitArray(itr)

      Construct a BitArray generated by the given iterable object. The shape is inferred from the itr object.

      julia> BitArray([1 0; 0 1])
      -2×2 BitArray{2}:
      -  true  false
      - false   true
      -
      -julia> BitArray(x+y == 3 for x = 1:2, y = 1:3)
      -2×3 BitArray{2}:
      - false   true  false
      -  true  false  false
      -
      -julia> BitArray(x+y == 3 for x = 1:2 for y = 1:3)
      -6-element BitArray{1}:
      - false
      -  true
      - false
      -  true
      - false
      - false
      source
      Base.truesFunction.
      trues(dims)

      Create a BitArray with all values set to true.

      julia> trues(2,3)
      -2×3 BitArray{2}:
      - true  true  true
      - true  true  true
      source
      trues(A)

      Create a BitArray with all values set to true of the same shape as A.

      julia> A = [1 2; 3 4]
      -2×2 Array{Int64,2}:
      - 1  2
      - 3  4
      -
      -julia> trues(A)
      -2×2 BitArray{2}:
      - true  true
      - true  true
      source
      Base.falsesFunction.
      falses(dims)

      Create a BitArray with all values set to false.

      julia> falses(2,3)
      -2×3 BitArray{2}:
      - false  false  false
      - false  false  false
      source
      falses(A)

      Create a BitArray with all values set to false of the same shape as A.

      julia> A = [1 2; 3 4]
      -2×2 Array{Int64,2}:
      - 1  2
      - 3  4
      -
      -julia> falses(A)
      -2×2 BitArray{2}:
      - false  false
      - false  false
      source
      Base.fillFunction.
      fill(x, dims)

      Create an array filled with the value x. For example, fill(1.0, (5,5)) returns a 5×5 array of floats, with each element initialized to 1.0.

      julia> fill(1.0, (5,5))
      -5×5 Array{Float64,2}:
      - 1.0  1.0  1.0  1.0  1.0
      - 1.0  1.0  1.0  1.0  1.0
      - 1.0  1.0  1.0  1.0  1.0
      - 1.0  1.0  1.0  1.0  1.0
      - 1.0  1.0  1.0  1.0  1.0

      If x is an object reference, all elements will refer to the same object. fill(Foo(), dims) will return an array filled with the result of evaluating Foo() once.

      source
      Base.fill!Function.
      fill!(A, x)

      Fill array A with the value x. If x is an object reference, all elements will refer to the same object. fill!(A, Foo()) will return A filled with the result of evaluating Foo() once.

      Examples

      julia> A = zeros(2,3)
      -2×3 Array{Float64,2}:
      - 0.0  0.0  0.0
      - 0.0  0.0  0.0
      -
      -julia> fill!(A, 2.)
      -2×3 Array{Float64,2}:
      - 2.0  2.0  2.0
      - 2.0  2.0  2.0
      -
      -julia> a = [1, 1, 1]; A = fill!(Vector{Vector{Int}}(3), a); a[1] = 2; A
      -3-element Array{Array{Int64,1},1}:
      - [2, 1, 1]
      - [2, 1, 1]
      - [2, 1, 1]
      -
      -julia> x = 0; f() = (global x += 1; x); fill!(Vector{Int}(3), f())
      -3-element Array{Int64,1}:
      - 1
      - 1
      - 1
      source
      Base.similarMethod.
      similar(array, [element_type=eltype(array)], [dims=size(array)])

      Create an uninitialized mutable array with the given element type and size, based upon the given source array. The second and third arguments are both optional, defaulting to the given array's eltype and size. The dimensions may be specified either as a single tuple argument or as a series of integer arguments.

      Custom AbstractArray subtypes may choose which specific array type is best-suited to return for the given element type and dimensionality. If they do not specialize this method, the default is an Array{element_type}(dims...).

      For example, similar(1:10, 1, 4) returns an uninitialized Array{Int,2} since ranges are neither mutable nor support 2 dimensions:

      julia> similar(1:10, 1, 4)
      -1×4 Array{Int64,2}:
      - 4419743872  4374413872  4419743888  0

      Conversely, similar(trues(10,10), 2) returns an uninitialized BitVector with two elements since BitArrays are both mutable and can support 1-dimensional arrays:

      julia> similar(trues(10,10), 2)
      -2-element BitArray{1}:
      - false
      - false

      Since BitArrays can only store elements of type Bool, however, if you request a different element type it will create a regular Array instead:

      julia> similar(falses(10), Float64, 2, 4)
      -2×4 Array{Float64,2}:
      - 2.18425e-314  2.18425e-314  2.18425e-314  2.18425e-314
      - 2.18425e-314  2.18425e-314  2.18425e-314  2.18425e-314
      source
      Base.similarMethod.
      similar(storagetype, indices)

      Create an uninitialized mutable array analogous to that specified by storagetype, but with indices specified by the last argument. storagetype might be a type or a function.

      Examples:

      similar(Array{Int}, indices(A))

      creates an array that "acts like" an Array{Int} (and might indeed be backed by one), but which is indexed identically to A. If A has conventional indexing, this will be identical to Array{Int}(size(A)), but if A has unconventional indexing then the indices of the result will match A.

      similar(BitArray, (indices(A, 2),))

      would create a 1-dimensional logical array whose indices match those of the columns of A.

      similar(dims->zeros(Int, dims), indices(A))

      would create an array of Int, initialized to zero, matching the indices of A.

      source
      Base.eyeFunction.
      eye([T::Type=Float64,] m::Integer, n::Integer)

      m-by-n identity matrix. The default element type is Float64.

      Examples

      julia> eye(3, 4)
      -3×4 Array{Float64,2}:
      - 1.0  0.0  0.0  0.0
      - 0.0  1.0  0.0  0.0
      - 0.0  0.0  1.0  0.0
      -
      -julia> eye(2, 2)
      -2×2 Array{Float64,2}:
      - 1.0  0.0
      - 0.0  1.0
      -
      -julia> eye(Int, 2, 2)
      -2×2 Array{Int64,2}:
      - 1  0
      - 0  1
      source
      eye(m, n)

      m-by-n identity matrix.

      source
      eye([T::Type=Float64,] n::Integer)

      n-by-n identity matrix. The default element type is Float64.

      Examples

      julia> eye(Int, 2)
      -2×2 Array{Int64,2}:
      - 1  0
      - 0  1
      -
      -julia> eye(2)
      -2×2 Array{Float64,2}:
      - 1.0  0.0
      - 0.0  1.0
      source
      eye(A)

      Constructs an identity matrix of the same dimensions and type as A.

      julia> A = [1 2 3; 4 5 6; 7 8 9]
      -3×3 Array{Int64,2}:
      - 1  2  3
      - 4  5  6
      - 7  8  9
      -
      -julia> eye(A)
      -3×3 Array{Int64,2}:
      - 1  0  0
      - 0  1  0
      - 0  0  1

      Note the difference from ones.

      source
      Base.linspaceFunction.
      linspace(start, stop, n=50)

      Construct a range of n linearly spaced elements from start to stop.

      julia> linspace(1.3,2.9,9)
      -1.3:0.2:2.9
      source
      Base.logspaceFunction.
      logspace(start::Real, stop::Real, n::Integer=50)

      Construct a vector of n logarithmically spaced numbers from 10^start to 10^stop.

      julia> logspace(1.,10.,5)
      -5-element Array{Float64,1}:
      -   10.0
      - 1778.28
      -    3.16228e5
      -    5.62341e7
      -    1.0e10
      source
      randsubseq(A, p) -> Vector

      Return a vector consisting of a random subsequence of the given array A, where each element of A is included (in order) with independent probability p. (Complexity is linear in p*length(A), so this function is efficient even if p is small and A is large.) Technically, this process is known as "Bernoulli sampling" of A.

      source
      randsubseq!(S, A, p)

      Like randsubseq, but the results are stored in S (which is resized as needed).

      source

      Basic functions

      Base.ndimsFunction.
      ndims(A::AbstractArray) -> Integer

      Returns the number of dimensions of A.

      julia> A = ones(3,4,5);
      -
      -julia> ndims(A)
      -3
      source
      Base.sizeFunction.
      size(A::AbstractArray, [dim...])

      Returns a tuple containing the dimensions of A. Optionally you can specify the dimension(s) you want the length of, and get the length of that dimension, or a tuple of the lengths of dimensions you asked for.

      julia> A = ones(2,3,4);
      -
      -julia> size(A, 2)
      -3
      -
      -julia> size(A,3,2)
      -(4, 3)
      source
      Base.indicesMethod.
      indices(A)

      Returns the tuple of valid indices for array A.

      julia> A = ones(5,6,7);
      -
      -julia> indices(A)
      -(Base.OneTo(5), Base.OneTo(6), Base.OneTo(7))
      source
      Base.indicesMethod.
      indices(A, d)

      Returns the valid range of indices for array A along dimension d.

      julia> A = ones(5,6,7);
      -
      -julia> indices(A,2)
      -Base.OneTo(6)
      source
      Base.lengthMethod.
      length(A::AbstractArray) -> Integer

      Returns the number of elements in A.

      julia> A = ones(3,4,5);
      -
      -julia> length(A)
      -60
      source
      Base.eachindexFunction.
      eachindex(A...)

      Creates an iterable object for visiting each index of an AbstractArray A in an efficient manner. For array types that have opted into fast linear indexing (like Array), this is simply the range 1:length(A). For other array types, this returns a specialized Cartesian range to efficiently index into the array with indices specified for every dimension. For other iterables, including strings and dictionaries, this returns an iterator object supporting arbitrary index types (e.g. unevenly spaced or non-integer indices).

      Example for a sparse 2-d array:

      julia> A = sparse([1, 1, 2], [1, 3, 1], [1, 2, -5])
      -2×3 SparseMatrixCSC{Int64,Int64} with 3 stored entries:
      -  [1, 1]  =  1
      -  [2, 1]  =  -5
      -  [1, 3]  =  2
      -
      -julia> for iter in eachindex(A)
      -           @show iter.I[1], iter.I[2]
      -           @show A[iter]
      -       end
      -(iter.I[1], iter.I[2]) = (1, 1)
      -A[iter] = 1
      -(iter.I[1], iter.I[2]) = (2, 1)
      -A[iter] = -5
      -(iter.I[1], iter.I[2]) = (1, 2)
      -A[iter] = 0
      -(iter.I[1], iter.I[2]) = (2, 2)
      -A[iter] = 0
      -(iter.I[1], iter.I[2]) = (1, 3)
      -A[iter] = 2
      -(iter.I[1], iter.I[2]) = (2, 3)
      -A[iter] = 0

      If you supply more than one AbstractArray argument, eachindex will create an iterable object that is fast for all arguments (a UnitRange if all inputs have fast linear indexing, a CartesianRange otherwise). If the arrays have different sizes and/or dimensionalities, eachindex returns an iterable that spans the largest range along each dimension.

      source
      Base.linearindicesFunction.
      linearindices(A)

      Returns a UnitRange specifying the valid range of indices for A[i] where i is an Int. For arrays with conventional indexing (indices start at 1), or any multidimensional array, this is 1:length(A); however, for one-dimensional arrays with unconventional indices, this is indices(A, 1).

      Calling this function is the "safe" way to write algorithms that exploit linear indexing.

      julia> A = ones(5,6,7);
      -
      -julia> b = linearindices(A);
      -
      -julia> extrema(b)
      -(1, 210)
      source
      Base.IndexStyleType.
      IndexStyle(A)
      -IndexStyle(typeof(A))

      IndexStyle specifies the "native indexing style" for array A. When you define a new AbstractArray type, you can choose to implement either linear indexing or cartesian indexing. If you decide to implement linear indexing, then you must set this trait for your array type:

      Base.IndexStyle(::Type{<:MyArray}) = IndexLinear()

      The default is IndexCartesian().

      Julia's internal indexing machinery will automatically (and invisibly) convert all indexing operations into the preferred style using sub2ind or ind2sub. This allows users to access elements of your array using any indexing style, even when explicit methods have not been provided.

      If you define both styles of indexing for your AbstractArray, this trait can be used to select the most performant indexing style. Some methods check this trait on their inputs, and dispatch to different algorithms depending on the most efficient access pattern. In particular, eachindex creates an iterator whose type depends on the setting of this trait.

      source
      Base.countnzFunction.
      countnz(A) -> Integer

      Counts the number of nonzero values in array A (dense or sparse). Note that this is not a constant-time operation. For sparse matrices, one should usually use nnz, which returns the number of stored values.

      julia> A = [1 2 4; 0 0 1; 1 1 0]
      -3×3 Array{Int64,2}:
      - 1  2  4
      - 0  0  1
      - 1  1  0
      -
      -julia> countnz(A)
      -6
      source
      Base.conj!Function.
      conj!(A)

      Transform an array to its complex conjugate in-place.

      See also conj.

      Example

      julia> A = [1+im 2-im; 2+2im 3+im]
      -2×2 Array{Complex{Int64},2}:
      - 1+1im  2-1im
      - 2+2im  3+1im
      -
      -julia> conj!(A);
      -
      -julia> A
      -2×2 Array{Complex{Int64},2}:
      - 1-1im  2+1im
      - 2-2im  3-1im
      source
      Base.strideFunction.
      stride(A, k::Integer)

      Returns the distance in memory (in number of elements) between adjacent elements in dimension k.

      julia> A = ones(3,4,5);
      -
      -julia> stride(A,2)
      -3
      -
      -julia> stride(A,3)
      -12
      source
      Base.stridesFunction.
      strides(A)

      Returns a tuple of the memory strides in each dimension.

      julia> A = ones(3,4,5);
      -
      -julia> strides(A)
      -(1, 3, 12)
      source
      Base.ind2subFunction.
      ind2sub(a, index) -> subscripts

      Returns a tuple of subscripts into array a corresponding to the linear index index.

      julia> A = ones(5,6,7);
      -
      -julia> ind2sub(A,35)
      -(5, 1, 2)
      -
      -julia> ind2sub(A,70)
      -(5, 2, 3)
      source
      ind2sub(dims, index) -> subscripts

      Returns a tuple of subscripts into an array with dimensions dims, corresponding to the linear index index.

      Example:

      i, j, ... = ind2sub(size(A), indmax(A))

      provides the indices of the maximum element.

      julia> ind2sub((3,4),2)
      -(2, 1)
      -
      -julia> ind2sub((3,4),3)
      -(3, 1)
      -
      -julia> ind2sub((3,4),4)
      -(1, 2)
      source
      Base.sub2indFunction.
      sub2ind(dims, i, j, k...) -> index

      The inverse of ind2sub, returns the linear index corresponding to the provided subscripts.

      julia> sub2ind((5,6,7),1,2,3)
      -66
      -
      -julia> sub2ind((5,6,7),1,6,3)
      -86
      source
      LinAlg.checksquare(A)

      Check that a matrix is square, then return its common dimension. For multiple arguments, return a vector.

      Example

      julia> A = ones(4,4); B = zeros(5,5);
      -
      -julia> LinAlg.checksquare(A, B)
      -2-element Array{Int64,1}:
      - 4
      - 5
      source

      Broadcast and vectorization

      See also the dot syntax for vectorizing functions; for example, f.(args...) implicitly calls broadcast(f, args...). Rather than relying on "vectorized" methods of functions like sin to operate on arrays, you should use sin.(a) to vectorize via broadcast.

      Base.broadcastFunction.
      broadcast(f, As...)

      Broadcasts the arrays, tuples, Refs, nullables, and/or scalars As to a container of the appropriate type and dimensions. In this context, anything that is not a subtype of AbstractArray, Ref (except for Ptrs), Tuple, or Nullable is considered a scalar. The resulting container is established by the following rules:

      • If all the arguments are scalars, it returns a scalar.

      • If the arguments are tuples and zero or more scalars, it returns a tuple.

      • If the arguments contain at least one array or Ref, it returns an array (expanding singleton dimensions), and treats Refs as 0-dimensional arrays, and tuples as 1-dimensional arrays.

      The following additional rule applies to Nullable arguments: If there is at least one Nullable, and all the arguments are scalars or Nullable, it returns a Nullable treating Nullables as "containers".

      A special syntax exists for broadcasting: f.(args...) is equivalent to broadcast(f, args...), and nested f.(g.(args...)) calls are fused into a single broadcast loop.

      julia> A = [1, 2, 3, 4, 5]
      -5-element Array{Int64,1}:
      - 1
      - 2
      - 3
      - 4
      - 5
      -
      -julia> B = [1 2; 3 4; 5 6; 7 8; 9 10]
      -5×2 Array{Int64,2}:
      - 1   2
      - 3   4
      - 5   6
      - 7   8
      - 9  10
      -
      -julia> broadcast(+, A, B)
      -5×2 Array{Int64,2}:
      -  2   3
      -  5   6
      -  8   9
      - 11  12
      - 14  15
      -
      -julia> parse.(Int, ["1", "2"])
      -2-element Array{Int64,1}:
      - 1
      - 2
      -
      -julia> abs.((1, -2))
      -(1, 2)
      -
      -julia> broadcast(+, 1.0, (0, -2.0))
      -(1.0, -1.0)
      -
      -julia> broadcast(+, 1.0, (0, -2.0), Ref(1))
      -2-element Array{Float64,1}:
      - 2.0
      - 0.0
      -
      -julia> (+).([[0,2], [1,3]], Ref{Vector{Int}}([1,-1]))
      -2-element Array{Array{Int64,1},1}:
      - [1, 1]
      - [2, 2]
      -
      -julia> string.(("one","two","three","four"), ": ", 1:4)
      -4-element Array{String,1}:
      - "one: 1"
      - "two: 2"
      - "three: 3"
      - "four: 4"
      -
      -julia> Nullable("X") .* "Y"
      -Nullable{String}("XY")
      -
      -julia> broadcast(/, 1.0, Nullable(2.0))
      -Nullable{Float64}(0.5)
      -
      -julia> (1 + im) ./ Nullable{Int}()
      -Nullable{Complex{Float64}}()
      source
      Base.broadcast!Function.
      broadcast!(f, dest, As...)

      Like broadcast, but store the result of broadcast(f, As...) in the dest array. Note that dest is only used to store the result, and does not supply arguments to f unless it is also listed in the As, as in broadcast!(f, A, A, B) to perform A[:] = broadcast(f, A, B).

      source
      @. expr

      Convert every function call or operator in expr into a "dot call" (e.g. convert f(x) to f.(x)), and convert every assignment in expr to a "dot assignment" (e.g. convert += to .+=).

      If you want to avoid adding dots for selected function calls in expr, splice those function calls in with $. For example, @. sqrt(abs($sort(x))) is equivalent to sqrt.(abs.(sort(x))) (no dot for sort).

      (@. is equivalent to a call to @__dot__.)

      julia> x = 1.0:3.0; y = similar(x);
      -
      -julia> @. y = x + 3 * sin(x)
      -3-element Array{Float64,1}:
      - 3.52441
      - 4.72789
      - 3.42336
      source
      broadcast_getindex(A, inds...)

      Broadcasts the inds arrays to a common size like broadcast and returns an array of the results A[ks...], where ks goes over the positions in the broadcast result A.

      julia> A = [1, 2, 3, 4, 5]
      -5-element Array{Int64,1}:
      - 1
      - 2
      - 3
      - 4
      - 5
      -
      -julia> B = [1 2; 3 4; 5 6; 7 8; 9 10]
      -5×2 Array{Int64,2}:
      - 1   2
      - 3   4
      - 5   6
      - 7   8
      - 9  10
      -
      -julia> C = broadcast(+,A,B)
      -5×2 Array{Int64,2}:
      -  2   3
      -  5   6
      -  8   9
      - 11  12
      - 14  15
      -
      -julia> broadcast_getindex(C,[1,2,10])
      -3-element Array{Int64,1}:
      -  2
      -  5
      - 15
      source
      broadcast_setindex!(A, X, inds...)

      Broadcasts the X and inds arrays to a common size and stores the value from each position in X at the indices in A given by the same positions in inds.

      source

      Indexing and assignment

      Base.getindexMethod.
      getindex(A, inds...)

      Returns a subset of array A as specified by inds, where each ind may be an Int, a Range, or a Vector. See the manual section on array indexing for details.

      Examples

      julia> A = [1 2; 3 4]
      -2×2 Array{Int64,2}:
      - 1  2
      - 3  4
      -
      -julia> getindex(A, 1)
      -1
      -
      -julia> getindex(A, [2, 1])
      -2-element Array{Int64,1}:
      - 3
      - 1
      -
      -julia> getindex(A, 2:4)
      -3-element Array{Int64,1}:
      - 3
      - 2
      - 4
      source
      Base.setindex!Method.
      setindex!(A, X, inds...)

      Store values from array X within some subset of A as specified by inds.

      source
      Base.copy!Method.
      copy!(dest, Rdest::CartesianRange, src, Rsrc::CartesianRange) -> dest

      Copy the block of src in the range of Rsrc to the block of dest in the range of Rdest. The sizes of the two regions must match.

      source
      Base.isassignedFunction.
      isassigned(array, i) -> Bool

      Tests whether the given array has a value associated with index i. Returns false if the index is out of bounds, or has an undefined reference.

      julia> isassigned(rand(3, 3), 5)
      -true
      -
      -julia> isassigned(rand(3, 3), 3 * 3 + 1)
      -false
      -
      -julia> mutable struct Foo end
      -
      -julia> v = similar(rand(3), Foo)
      -3-element Array{Foo,1}:
      - #undef
      - #undef
      - #undef
      -
      -julia> isassigned(v, 1)
      -false
      source
      Base.ColonType.
      Colon()

      Colons (:) are used to signify indexing entire objects or dimensions at once.

      Very few operations are defined on Colons directly; instead they are converted by to_indices to an internal vector type (Base.Slice) to represent the collection of indices they span before being used.

      source
      CartesianIndex(i, j, k...)   -> I
      -CartesianIndex((i, j, k...)) -> I

      Create a multidimensional index I, which can be used for indexing a multidimensional array A. In particular, A[I] is equivalent to A[i,j,k...]. One can freely mix integer and CartesianIndex indices; for example, A[Ipre, i, Ipost] (where Ipre and Ipost are CartesianIndex indices and i is an Int) can be a useful expression when writing algorithms that work along a single dimension of an array of arbitrary dimensionality.

      A CartesianIndex is sometimes produced by eachindex, and always when iterating with an explicit CartesianRange.

      Example

      julia> A = reshape(collect(1:16), (2, 2, 2, 2))
      -2×2×2×2 Array{Int64,4}:
      -[:, :, 1, 1] =
      - 1  3
      - 2  4
      -
      -[:, :, 2, 1] =
      - 5  7
      - 6  8
      -
      -[:, :, 1, 2] =
      -  9  11
      - 10  12
      -
      -[:, :, 2, 2] =
      - 13  15
      - 14  16
      -
      -julia> A[CartesianIndex((1, 1, 1, 1))]
      -1
      -
      -julia> A[CartesianIndex((1, 1, 1, 2))]
      -9
      -
      -julia> A[CartesianIndex((1, 1, 2, 1))]
      -5
      source
      CartesianRange(Istart::CartesianIndex, Istop::CartesianIndex) -> R
      -CartesianRange(sz::Dims) -> R
      -CartesianRange(istart:istop, jstart:jstop, ...) -> R

      Define a region R spanning a multidimensional rectangular range of integer indices. These are most commonly encountered in the context of iteration, where for I in R ... end will return CartesianIndex indices I equivalent to the nested loops

      for j = jstart:jstop
      -    for i = istart:istop
      -        ...
      -    end
      -end

      Consequently these can be useful for writing algorithms that work in arbitrary dimensions.

      julia> foreach(println, CartesianRange((2, 2, 2)))
      -CartesianIndex{3}((1, 1, 1))
      -CartesianIndex{3}((2, 1, 1))
      -CartesianIndex{3}((1, 2, 1))
      -CartesianIndex{3}((2, 2, 1))
      -CartesianIndex{3}((1, 1, 2))
      -CartesianIndex{3}((2, 1, 2))
      -CartesianIndex{3}((1, 2, 2))
      -CartesianIndex{3}((2, 2, 2))
      source
      Base.to_indicesFunction.
      to_indices(A, I::Tuple)

      Convert the tuple I to a tuple of indices for use in indexing into array A.

      The returned tuple must only contain either Ints or AbstractArrays of scalar indices that are supported by array A. It will error upon encountering a novel index type that it does not know how to process.

      For simple index types, it defers to the unexported Base.to_index(A, i) to process each index i. While this internal function is not intended to be called directly, Base.to_index may be extended by custom array or index types to provide custom indexing behaviors.

      More complicated index types may require more context about the dimension into which they index. To support those cases, to_indices(A, I) calls to_indices(A, indices(A), I), which then recursively walks through both the given tuple of indices and the dimensional indices of A in tandem. As such, not all index types are guaranteed to propagate to Base.to_index.

      source
      Base.checkboundsFunction.
      checkbounds(Bool, A, I...)

      Return true if the specified indices I are in bounds for the given array A. Subtypes of AbstractArray should specialize this method if they need to provide custom bounds checking behaviors; however, in many cases one can rely on A's indices and checkindex.

      See also checkindex.

      julia> A = rand(3, 3);
      -
      -julia> checkbounds(Bool, A, 2)
      -true
      -
      -julia> checkbounds(Bool, A, 3, 4)
      -false
      -
      -julia> checkbounds(Bool, A, 1:3)
      -true
      -
      -julia> checkbounds(Bool, A, 1:3, 2:4)
      -false
      source
      checkbounds(A, I...)

      Throw an error if the specified indices I are not in bounds for the given array A.

      source
      Base.checkindexFunction.
      checkindex(Bool, inds::AbstractUnitRange, index)

      Return true if the given index is within the bounds of inds. Custom types that would like to behave as indices for all arrays can extend this method in order to provide a specialized bounds checking implementation.

      julia> checkindex(Bool,1:20,8)
      -true
      -
      -julia> checkindex(Bool,1:20,21)
      -false
      source

      Views (SubArrays and other view types)

      Base.viewFunction.
      view(A, inds...)

      Like getindex, but returns a view into the parent array A with the given indices instead of making a copy. Calling getindex or setindex! on the returned SubArray computes the indices to the parent array on the fly without checking bounds.

      julia> A = [1 2; 3 4]
      -2×2 Array{Int64,2}:
      - 1  2
      - 3  4
      -
      -julia> b = view(A, :, 1)
      -2-element SubArray{Int64,1,Array{Int64,2},Tuple{Base.Slice{Base.OneTo{Int64}},Int64},true}:
      - 1
      - 3
      -
      -julia> fill!(b, 0)
      -2-element SubArray{Int64,1,Array{Int64,2},Tuple{Base.Slice{Base.OneTo{Int64}},Int64},true}:
      - 0
      - 0
      -
      -julia> A # Note A has changed even though we modified b
      -2×2 Array{Int64,2}:
      - 0  2
      - 0  4
      source
      Base.@viewMacro.
      @view A[inds...]

      Creates a SubArray from an indexing expression. This can only be applied directly to a reference expression (e.g. @view A[1,2:end]), and should not be used as the target of an assignment (e.g. @view(A[1,2:end]) = ...). See also @views to switch an entire block of code to use views for slicing.

      julia> A = [1 2; 3 4]
      -2×2 Array{Int64,2}:
      - 1  2
      - 3  4
      -
      -julia> b = @view A[:, 1]
      -2-element SubArray{Int64,1,Array{Int64,2},Tuple{Base.Slice{Base.OneTo{Int64}},Int64},true}:
      - 1
      - 3
      -
      -julia> fill!(b, 0)
      -2-element SubArray{Int64,1,Array{Int64,2},Tuple{Base.Slice{Base.OneTo{Int64}},Int64},true}:
      - 0
      - 0
      -
      -julia> A
      -2×2 Array{Int64,2}:
      - 0  2
      - 0  4
      source
      Base.@viewsMacro.
      @views expression

      Convert every array-slicing operation in the given expression (which may be a begin/end block, loop, function, etc.) to return a view. Scalar indices, non-array types, and explicit getindex calls (as opposed to array[...]) are unaffected.

      Note that the @views macro only affects array[...] expressions that appear explicitly in the given expression, not array slicing that occurs in functions called by that code.

      source
      Base.parentFunction.
      parent(A)

      Returns the "parent array" of an array view type (e.g., SubArray), or the array itself if it is not a view.

      source
      Base.parentindexesFunction.
      parentindexes(A)

      From an array view A, returns the corresponding indexes in the parent.

      source
      Base.slicedimFunction.
      slicedim(A, d::Integer, i)

      Return all the data of A where the index for dimension d equals i. Equivalent to A[:,:,...,i,:,:,...] where i is in position d.

      Example

      julia> A = [1 2 3 4; 5 6 7 8]
      -2×4 Array{Int64,2}:
      - 1  2  3  4
      - 5  6  7  8
      -
      -julia> slicedim(A,2,3)
      -2-element Array{Int64,1}:
      - 3
      - 7
      source
      Base.reinterpretFunction.
      reinterpret(type, A)

      Change the type-interpretation of a block of memory. For arrays, this constructs an array with the same binary data as the given array, but with the specified element type. For example, reinterpret(Float32, UInt32(7)) interprets the 4 bytes corresponding to UInt32(7) as a Float32.

      Warning

      It is not allowed to reinterpret an array to an element type with a larger alignment then the alignment of the array. For a normal Array, this is the alignment of its element type. For a reinterpreted array, this is the alignment of the Array it was reinterpreted from. For example, reinterpret(UInt32, UInt8[0, 0, 0, 0]) is not allowed but reinterpret(UInt32, reinterpret(UInt8, Float32[1.0])) is allowed.

      Examples

      julia> reinterpret(Float32, UInt32(7))
      -1.0f-44
      -
      -julia> reinterpret(Float32, UInt32[1 2 3 4 5])
      -1×5 Array{Float32,2}:
      - 1.4013f-45  2.8026f-45  4.2039f-45  5.60519f-45  7.00649f-45
      source
      Base.reshapeFunction.
      reshape(A, dims...) -> R
      -reshape(A, dims) -> R

      Return an array R with the same data as A, but with different dimension sizes or number of dimensions. The two arrays share the same underlying data, so that setting elements of R alters the values of A and vice versa.

      The new dimensions may be specified either as a list of arguments or as a shape tuple. At most one dimension may be specified with a :, in which case its length is computed such that its product with all the specified dimensions is equal to the length of the original array A. The total number of elements must not change.

      julia> A = collect(1:16)
      -16-element Array{Int64,1}:
      -  1
      -  2
      -  3
      -  4
      -  5
      -  6
      -  7
      -  8
      -  9
      - 10
      - 11
      - 12
      - 13
      - 14
      - 15
      - 16
      -
      -julia> reshape(A, (4, 4))
      -4×4 Array{Int64,2}:
      - 1  5   9  13
      - 2  6  10  14
      - 3  7  11  15
      - 4  8  12  16
      -
      -julia> reshape(A, 2, :)
      -2×8 Array{Int64,2}:
      - 1  3  5  7   9  11  13  15
      - 2  4  6  8  10  12  14  16
      source
      Base.squeezeFunction.
      squeeze(A, dims)

      Remove the dimensions specified by dims from array A. Elements of dims must be unique and within the range 1:ndims(A). size(A,i) must equal 1 for all i in dims.

      Example

      julia> a = reshape(collect(1:4),(2,2,1,1))
      -2×2×1×1 Array{Int64,4}:
      -[:, :, 1, 1] =
      - 1  3
      - 2  4
      -
      -julia> squeeze(a,3)
      -2×2×1 Array{Int64,3}:
      -[:, :, 1] =
      - 1  3
      - 2  4
      source
      Base.vecFunction.
      vec(a::AbstractArray) -> Vector

      Reshape the array a as a one-dimensional column vector. The resulting array shares the same underlying data as a, so modifying one will also modify the other.

      Example

      julia> a = [1 2 3; 4 5 6]
      -2×3 Array{Int64,2}:
      - 1  2  3
      - 4  5  6
      -
      -julia> vec(a)
      -6-element Array{Int64,1}:
      - 1
      - 4
      - 2
      - 5
      - 3
      - 6

      See also reshape.

      source

      Concatenation and permutation

      Base.catFunction.
      cat(dims, A...)

      Concatenate the input arrays along the specified dimensions in the iterable dims. For dimensions not in dims, all input arrays should have the same size, which will also be the size of the output array along that dimension. For dimensions in dims, the size of the output array is the sum of the sizes of the input arrays along that dimension. If dims is a single number, the different arrays are tightly stacked along that dimension. If dims is an iterable containing several dimensions, this allows one to construct block diagonal matrices and their higher-dimensional analogues by simultaneously increasing several dimensions for every new input array and putting zero blocks elsewhere. For example, cat([1,2], matrices...) builds a block diagonal matrix, i.e. a block matrix with matrices[1], matrices[2], ... as diagonal blocks and matching zero blocks away from the diagonal.

      source
      Base.vcatFunction.
      vcat(A...)

      Concatenate along dimension 1.

      julia> a = [1 2 3 4 5]
      -1×5 Array{Int64,2}:
      - 1  2  3  4  5
      -
      -julia> b = [6 7 8 9 10; 11 12 13 14 15]
      -2×5 Array{Int64,2}:
      -  6   7   8   9  10
      - 11  12  13  14  15
      -
      -julia> vcat(a,b)
      -3×5 Array{Int64,2}:
      -  1   2   3   4   5
      -  6   7   8   9  10
      - 11  12  13  14  15
      -
      -julia> c = ([1 2 3], [4 5 6])
      -([1 2 3], [4 5 6])
      -
      -julia> vcat(c...)
      -2×3 Array{Int64,2}:
      - 1  2  3
      - 4  5  6
      source
      Base.hcatFunction.
      hcat(A...)

      Concatenate along dimension 2.

      julia> a = [1; 2; 3; 4; 5]
      -5-element Array{Int64,1}:
      - 1
      - 2
      - 3
      - 4
      - 5
      -
      -julia> b = [6 7; 8 9; 10 11; 12 13; 14 15]
      -5×2 Array{Int64,2}:
      -  6   7
      -  8   9
      - 10  11
      - 12  13
      - 14  15
      -
      -julia> hcat(a,b)
      -5×3 Array{Int64,2}:
      - 1   6   7
      - 2   8   9
      - 3  10  11
      - 4  12  13
      - 5  14  15
      -
      -julia> c = ([1; 2; 3], [4; 5; 6])
      -([1, 2, 3], [4, 5, 6])
      -
      -julia> hcat(c...)
      -3×2 Array{Int64,2}:
      - 1  4
      - 2  5
      - 3  6
      source
      Base.hvcatFunction.
      hvcat(rows::Tuple{Vararg{Int}}, values...)

      Horizontal and vertical concatenation in one call. This function is called for block matrix syntax. The first argument specifies the number of arguments to concatenate in each block row.

      julia> a, b, c, d, e, f = 1, 2, 3, 4, 5, 6
      -(1, 2, 3, 4, 5, 6)
      -
      -julia> [a b c; d e f]
      -2×3 Array{Int64,2}:
      - 1  2  3
      - 4  5  6
      -
      -julia> hvcat((3,3), a,b,c,d,e,f)
      -2×3 Array{Int64,2}:
      - 1  2  3
      - 4  5  6
      -
      -julia> [a b;c d; e f]
      -3×2 Array{Int64,2}:
      - 1  2
      - 3  4
      - 5  6
      -
      -julia> hvcat((2,2,2), a,b,c,d,e,f)
      -3×2 Array{Int64,2}:
      - 1  2
      - 3  4
      - 5  6

      If the first argument is a single integer n, then all block rows are assumed to have n block columns.

      source
      Base.flipdimFunction.
      flipdim(A, d::Integer)

      Reverse A in dimension d.

      Example

      julia> b = [1 2; 3 4]
      -2×2 Array{Int64,2}:
      - 1  2
      - 3  4
      -
      -julia> flipdim(b,2)
      -2×2 Array{Int64,2}:
      - 2  1
      - 4  3
      source
      Base.circshiftFunction.
      circshift(A, shifts)

      Circularly shift the data in an array. The second argument is a vector giving the amount to shift in each dimension.

      Example

      julia> b = reshape(collect(1:16), (4,4))
      -4×4 Array{Int64,2}:
      - 1  5   9  13
      - 2  6  10  14
      - 3  7  11  15
      - 4  8  12  16
      -
      -julia> circshift(b, (0,2))
      -4×4 Array{Int64,2}:
      -  9  13  1  5
      - 10  14  2  6
      - 11  15  3  7
      - 12  16  4  8
      -
      -julia> circshift(b, (-1,0))
      -4×4 Array{Int64,2}:
      - 2  6  10  14
      - 3  7  11  15
      - 4  8  12  16
      - 1  5   9  13

      See also circshift!.

      source
      Base.circshift!Function.
      circshift!(dest, src, shifts)

      Circularly shift the data in src, storing the result in dest. shifts specifies the amount to shift in each dimension.

      The dest array must be distinct from the src array (they cannot alias each other).

      See also circshift.

      source
      Base.circcopy!Function.
      circcopy!(dest, src)

      Copy src to dest, indexing each dimension modulo its length. src and dest must have the same size, but can be offset in their indices; any offset results in a (circular) wraparound. If the arrays have overlapping indices, then on the domain of the overlap dest agrees with src.

      Example

      julia> src = reshape(collect(1:16), (4,4))
      -4×4 Array{Int64,2}:
      - 1  5   9  13
      - 2  6  10  14
      - 3  7  11  15
      - 4  8  12  16
      -
      -julia> dest = OffsetArray{Int}((0:3,2:5))
      -
      -julia> circcopy!(dest, src)
      -OffsetArrays.OffsetArray{Int64,2,Array{Int64,2}} with indices 0:3×2:5:
      - 8  12  16  4
      - 5   9  13  1
      - 6  10  14  2
      - 7  11  15  3
      -
      -julia> dest[1:3,2:4] == src[1:3,2:4]
      -true
      source
      Base.containsMethod.
      contains(fun, itr, x) -> Bool

      Returns true if there is at least one element y in itr such that fun(y,x) is true.

      julia> vec = [10, 100, 200]
      -3-element Array{Int64,1}:
      -  10
      - 100
      - 200
      -
      -julia> contains(==, vec, 200)
      -true
      -
      -julia> contains(==, vec, 300)
      -false
      -
      -julia> contains(>, vec, 100)
      -true
      -
      -julia> contains(>, vec, 200)
      -false
      source
      Base.findMethod.
      find(A)

      Return a vector of the linear indexes of the non-zeros in A (determined by A[i]!=0). A common use of this is to convert a boolean array to an array of indexes of the true elements. If there are no non-zero elements of A, find returns an empty array.

      Examples

      julia> A = [true false; false true]
      -2×2 Array{Bool,2}:
      -  true  false
      - false   true
      -
      -julia> find(A)
      -2-element Array{Int64,1}:
      - 1
      - 4
      -
      -julia> find(zeros(3))
      -0-element Array{Int64,1}
      source
      Base.findMethod.
      find(f::Function, A)

      Return a vector I of the linear indexes of A where f(A[I]) returns true. If there are no such elements of A, find returns an empty array.

      Examples

      julia> A = [1 2; 3 4]
      -2×2 Array{Int64,2}:
      - 1  2
      - 3  4
      -
      -julia> find(isodd,A)
      -2-element Array{Int64,1}:
      - 1
      - 2
      -
      -julia> find(isodd, [2, 4])
      -0-element Array{Int64,1}
      source
      Base.findnFunction.
      findn(A)

      Return a vector of indexes for each dimension giving the locations of the non-zeros in A (determined by A[i]!=0). If there are no non-zero elements of A, findn returns a 2-tuple of empty arrays.

      Examples

      julia> A = [1 2 0; 0 0 3; 0 4 0]
      -3×3 Array{Int64,2}:
      - 1  2  0
      - 0  0  3
      - 0  4  0
      -
      -julia> findn(A)
      -([1, 1, 3, 2], [1, 2, 2, 3])
      -
      -julia> A = zeros(2,2)
      -2×2 Array{Float64,2}:
      - 0.0  0.0
      - 0.0  0.0
      -
      -julia> findn(A)
      -(Int64[], Int64[])
      source
      Base.findnzFunction.
      findnz(A)

      Return a tuple (I, J, V) where I and J are the row and column indexes of the non-zero values in matrix A, and V is a vector of the non-zero values.

      Example

      julia> A = [1 2 0; 0 0 3; 0 4 0]
      -3×3 Array{Int64,2}:
      - 1  2  0
      - 0  0  3
      - 0  4  0
      -
      -julia> findnz(A)
      -([1, 1, 3, 2], [1, 2, 2, 3], [1, 2, 4, 3])
      source
      Base.findfirstMethod.
      findfirst(A)

      Return the linear index of the first non-zero value in A (determined by A[i]!=0). Returns 0 if no such value is found.

      Examples

      julia> A = [0 0; 1 0]
      -2×2 Array{Int64,2}:
      - 0  0
      - 1  0
      -
      -julia> findfirst(A)
      -2
      -
      -julia> findfirst(zeros(3))
      -0
      source
      Base.findfirstMethod.
      findfirst(A, v)

      Return the linear index of the first element equal to v in A. Returns 0 if v is not found.

      Examples

      julia> A = [4 6; 2 2]
      -2×2 Array{Int64,2}:
      - 4  6
      - 2  2
      -
      -julia> findfirst(A,2)
      -2
      -
      -julia> findfirst(A,3)
      -0
      source
      Base.findfirstMethod.
      findfirst(predicate::Function, A)

      Return the linear index of the first element of A for which predicate returns true. Returns 0 if there is no such element.

      Examples

      julia> A = [1 4; 2 2]
      -2×2 Array{Int64,2}:
      - 1  4
      - 2  2
      -
      -julia> findfirst(iseven, A)
      -2
      -
      -julia> findfirst(x -> x>10, A)
      -0
      source
      Base.findlastMethod.
      findlast(A)

      Return the linear index of the last non-zero value in A (determined by A[i]!=0). Returns 0 if there is no non-zero value in A.

      Examples

      julia> A = [1 0; 1 0]
      -2×2 Array{Int64,2}:
      - 1  0
      - 1  0
      -
      -julia> findlast(A)
      -2
      -
      -julia> A = zeros(2,2)
      -2×2 Array{Float64,2}:
      - 0.0  0.0
      - 0.0  0.0
      -
      -julia> findlast(A)
      -0
      source
      Base.findlastMethod.
      findlast(A, v)

      Return the linear index of the last element equal to v in A. Returns 0 if there is no element of A equal to v.

      Examples

      julia> A = [1 2; 2 1]
      -2×2 Array{Int64,2}:
      - 1  2
      - 2  1
      -
      -julia> findlast(A,1)
      -4
      -
      -julia> findlast(A,2)
      -3
      -
      -julia> findlast(A,3)
      -0
      source
      Base.findlastMethod.
      findlast(predicate::Function, A)

      Return the linear index of the last element of A for which predicate returns true. Returns 0 if there is no such element.

      Examples

      julia> A = [1 2; 3 4]
      -2×2 Array{Int64,2}:
      - 1  2
      - 3  4
      -
      -julia> findlast(isodd, A)
      -2
      -
      -julia> findlast(x -> x > 5, A)
      -0
      source
      Base.findnextMethod.
      findnext(A, i::Integer)

      Find the next linear index >= i of a non-zero element of A, or 0 if not found.

      Examples

      julia> A = [0 0; 1 0]
      -2×2 Array{Int64,2}:
      - 0  0
      - 1  0
      -
      -julia> findnext(A,1)
      -2
      -
      -julia> findnext(A,3)
      -0
      source
      Base.findnextMethod.
      findnext(predicate::Function, A, i::Integer)

      Find the next linear index >= i of an element of A for which predicate returns true, or 0 if not found.

      Examples

      julia> A = [1 4; 2 2]
      -2×2 Array{Int64,2}:
      - 1  4
      - 2  2
      -
      -julia> findnext(isodd, A, 1)
      -1
      -
      -julia> findnext(isodd, A, 2)
      -0
      source
      Base.findnextMethod.
      findnext(A, v, i::Integer)

      Find the next linear index >= i of an element of A equal to v (using ==), or 0 if not found.

      Examples

      julia> A = [1 4; 2 2]
      -2×2 Array{Int64,2}:
      - 1  4
      - 2  2
      -
      -julia> findnext(A,4,4)
      -0
      -
      -julia> findnext(A,4,3)
      -3
      source
      Base.findprevMethod.
      findprev(A, i::Integer)

      Find the previous linear index <= i of a non-zero element of A, or 0 if not found.

      Examples

      julia> A = [0 0; 1 2]
      -2×2 Array{Int64,2}:
      - 0  0
      - 1  2
      -
      -julia> findprev(A,2)
      -2
      -
      -julia> findprev(A,1)
      -0
      source
      Base.findprevMethod.
      findprev(predicate::Function, A, i::Integer)

      Find the previous linear index <= i of an element of A for which predicate returns true, or 0 if not found.

      Examples

      julia> A = [4 6; 1 2]
      -2×2 Array{Int64,2}:
      - 4  6
      - 1  2
      -
      -julia> findprev(isodd, A, 1)
      -0
      -
      -julia> findprev(isodd, A, 3)
      -2
      source
      Base.findprevMethod.
      findprev(A, v, i::Integer)

      Find the previous linear index <= i of an element of A equal to v (using ==), or 0 if not found.

      Examples

      julia> A = [0 0; 1 2]
      -2×2 Array{Int64,2}:
      - 0  0
      - 1  2
      -
      -julia> findprev(A, 1, 4)
      -2
      -
      -julia> findprev(A, 1, 1)
      -0
      source
      Base.permutedimsFunction.
      permutedims(A, perm)

      Permute the dimensions of array A. perm is a vector specifying a permutation of length ndims(A). This is a generalization of transpose for multi-dimensional arrays. Transpose is equivalent to permutedims(A, [2,1]).

      See also: PermutedDimsArray.

      Example

      julia> A = reshape(collect(1:8), (2,2,2))
      -2×2×2 Array{Int64,3}:
      -[:, :, 1] =
      - 1  3
      - 2  4
      -
      -[:, :, 2] =
      - 5  7
      - 6  8
      -
      -julia> permutedims(A, [3, 2, 1])
      -2×2×2 Array{Int64,3}:
      -[:, :, 1] =
      - 1  3
      - 5  7
      -
      -[:, :, 2] =
      - 2  4
      - 6  8
      source
      Base.permutedims!Function.
      permutedims!(dest, src, perm)

      Permute the dimensions of array src and store the result in the array dest. perm is a vector specifying a permutation of length ndims(src). The preallocated array dest should have size(dest) == size(src)[perm] and is completely overwritten. No in-place permutation is supported and unexpected results will happen if src and dest have overlapping memory regions.

      See also permutedims.

      source
      PermutedDimsArray(A, perm) -> B

      Given an AbstractArray A, create a view B such that the dimensions appear to be permuted. Similar to permutedims, except that no copying occurs (B shares storage with A).

      See also: permutedims.

      Example

      julia> A = rand(3,5,4);
      -
      -julia> B = PermutedDimsArray(A, (3,1,2));
      -
      -julia> size(B)
      -(4, 3, 5)
      -
      -julia> B[3,1,2] == A[1,2,3]
      -true
      source
      Base.promote_shapeFunction.
      promote_shape(s1, s2)

      Check two array shapes for compatibility, allowing trailing singleton dimensions, and return whichever shape has more dimensions.

      julia> a = ones(3,4,1,1,1);
      -
      -julia> b = ones(3,4);
      -
      -julia> promote_shape(a,b)
      -(Base.OneTo(3), Base.OneTo(4), Base.OneTo(1), Base.OneTo(1), Base.OneTo(1))
      -
      -julia> promote_shape((2,3,1,4), (2, 3, 1, 4, 1))
      -(2, 3, 1, 4, 1)
      source

      Array functions

      Base.accumulateMethod.
      accumulate(op, A, dim=1)

      Cumulative operation op along a dimension dim (defaults to 1). See also accumulate! to use a preallocated output array, both for performance and to control the precision of the output (e.g. to avoid overflow). For common operations there are specialized variants of accumulate, see: cumsum, cumprod

      julia> accumulate(+, [1,2,3])
      -3-element Array{Int64,1}:
      - 1
      - 3
      - 6
      -
      -julia> accumulate(*, [1,2,3])
      -3-element Array{Int64,1}:
      - 1
      - 2
      - 6
      source
      accumulate(op, v0, A)

      Like accumulate, but using a starting element v0. The first entry of the result will be op(v0, first(A)). For example:

      julia> accumulate(+, 100, [1,2,3])
      -3-element Array{Int64,1}:
      - 101
      - 103
      - 106
      -
      -julia> accumulate(min, 0, [1,2,-1])
      -3-element Array{Int64,1}:
      -  0
      -  0
      - -1
      source
      Base.accumulate!Function.
      accumulate!(op, B, A, dim=1)

      Cumulative operation op on A along a dimension, storing the result in B. The dimension defaults to 1. See also accumulate.

      source
      Base.cumprodFunction.
      cumprod(A, dim=1)

      Cumulative product along a dimension dim (defaults to 1). See also cumprod! to use a preallocated output array, both for performance and to control the precision of the output (e.g. to avoid overflow).

      julia> a = [1 2 3; 4 5 6]
      -2×3 Array{Int64,2}:
      - 1  2  3
      - 4  5  6
      -
      -julia> cumprod(a,1)
      -2×3 Array{Int64,2}:
      - 1   2   3
      - 4  10  18
      -
      -julia> cumprod(a,2)
      -2×3 Array{Int64,2}:
      - 1   2    6
      - 4  20  120
      source
      Base.cumprod!Function.
      cumprod!(B, A, dim::Integer=1)

      Cumulative product of A along a dimension, storing the result in B. The dimension defaults to 1. See also cumprod.

      source
      Base.cumsumFunction.
      cumsum(A, dim=1)

      Cumulative sum along a dimension dim (defaults to 1). See also cumsum! to use a preallocated output array, both for performance and to control the precision of the output (e.g. to avoid overflow).

      julia> a = [1 2 3; 4 5 6]
      -2×3 Array{Int64,2}:
      - 1  2  3
      - 4  5  6
      -
      -julia> cumsum(a,1)
      -2×3 Array{Int64,2}:
      - 1  2  3
      - 5  7  9
      -
      -julia> cumsum(a,2)
      -2×3 Array{Int64,2}:
      - 1  3   6
      - 4  9  15
      source
      Base.cumsum!Function.
      cumsum!(B, A, dim::Integer=1)

      Cumulative sum of A along a dimension, storing the result in B. The dimension defaults to 1. See also cumsum.

      source
      Base.cumsum_kbnFunction.
      cumsum_kbn(A, [dim::Integer=1])

      Cumulative sum along a dimension, using the Kahan-Babuska-Neumaier compensated summation algorithm for additional accuracy. The dimension defaults to 1.

      source
      Base.LinAlg.diffFunction.
      diff(A, [dim::Integer=1])

      Finite difference operator of matrix or vector A. If A is a matrix, compute the finite difference over a dimension dim (default 1).

      Example

      julia> a = [2 4; 6 16]
      -2×2 Array{Int64,2}:
      - 2   4
      - 6  16
      -
      -julia> diff(a,2)
      -2×1 Array{Int64,2}:
      -  2
      - 10
      source
      Base.LinAlg.gradientFunction.
      gradient(F::AbstractVector, [h::Real])

      Compute differences along vector F, using h as the spacing between points. The default spacing is one.

      Example

      julia> a = [2,4,6,8];
      -
      -julia> gradient(a)
      -4-element Array{Float64,1}:
      - 2.0
      - 2.0
      - 2.0
      - 2.0
      source
      Base.rot180Function.
      rot180(A)

      Rotate matrix A 180 degrees.

      Example

      julia> a = [1 2; 3 4]
      -2×2 Array{Int64,2}:
      - 1  2
      - 3  4
      -
      -julia> rot180(a)
      -2×2 Array{Int64,2}:
      - 4  3
      - 2  1
      source
      rot180(A, k)

      Rotate matrix A 180 degrees an integer k number of times. If k is even, this is equivalent to a copy.

      Examples

      julia> a = [1 2; 3 4]
      -2×2 Array{Int64,2}:
      - 1  2
      - 3  4
      -
      -julia> rot180(a,1)
      -2×2 Array{Int64,2}:
      - 4  3
      - 2  1
      -
      -julia> rot180(a,2)
      -2×2 Array{Int64,2}:
      - 1  2
      - 3  4
      source
      Base.rotl90Function.
      rotl90(A)

      Rotate matrix A left 90 degrees.

      Example

      julia> a = [1 2; 3 4]
      -2×2 Array{Int64,2}:
      - 1  2
      - 3  4
      -
      -julia> rotl90(a)
      -2×2 Array{Int64,2}:
      - 2  4
      - 1  3
      source
      rotl90(A, k)

      Rotate matrix A left 90 degrees an integer k number of times. If k is zero or a multiple of four, this is equivalent to a copy.

      Examples

      julia> a = [1 2; 3 4]
      -2×2 Array{Int64,2}:
      - 1  2
      - 3  4
      -
      -julia> rotl90(a,1)
      -2×2 Array{Int64,2}:
      - 2  4
      - 1  3
      -
      -julia> rotl90(a,2)
      -2×2 Array{Int64,2}:
      - 4  3
      - 2  1
      -
      -julia> rotl90(a,3)
      -2×2 Array{Int64,2}:
      - 3  1
      - 4  2
      -
      -julia> rotl90(a,4)
      -2×2 Array{Int64,2}:
      - 1  2
      - 3  4
      source
      Base.rotr90Function.
      rotr90(A)

      Rotate matrix A right 90 degrees.

      Example

      julia> a = [1 2; 3 4]
      -2×2 Array{Int64,2}:
      - 1  2
      - 3  4
      -
      -julia> rotr90(a)
      -2×2 Array{Int64,2}:
      - 3  1
      - 4  2
      source
      rotr90(A, k)

      Rotate matrix A right 90 degrees an integer k number of times. If k is zero or a multiple of four, this is equivalent to a copy.

      Examples

      julia> a = [1 2; 3 4]
      -2×2 Array{Int64,2}:
      - 1  2
      - 3  4
      -
      -julia> rotr90(a,1)
      -2×2 Array{Int64,2}:
      - 3  1
      - 4  2
      -
      -julia> rotr90(a,2)
      -2×2 Array{Int64,2}:
      - 4  3
      - 2  1
      -
      -julia> rotr90(a,3)
      -2×2 Array{Int64,2}:
      - 2  4
      - 1  3
      -
      -julia> rotr90(a,4)
      -2×2 Array{Int64,2}:
      - 1  2
      - 3  4
      source
      Base.reducedimFunction.
      reducedim(f, A, region[, v0])

      Reduce 2-argument function f along dimensions of A. region is a vector specifying the dimensions to reduce, and v0 is the initial value to use in the reductions. For +, *, max and min the v0 argument is optional.

      The associativity of the reduction is implementation-dependent; if you need a particular associativity, e.g. left-to-right, you should write your own loop. See documentation for reduce.

      Examples

      julia> a = reshape(collect(1:16), (4,4))
      -4×4 Array{Int64,2}:
      - 1  5   9  13
      - 2  6  10  14
      - 3  7  11  15
      - 4  8  12  16
      -
      -julia> reducedim(max, a, 2)
      -4×1 Array{Int64,2}:
      - 13
      - 14
      - 15
      - 16
      -
      -julia> reducedim(max, a, 1)
      -1×4 Array{Int64,2}:
      - 4  8  12  16
      source
      Base.mapreducedimFunction.
      mapreducedim(f, op, A, region[, v0])

      Evaluates to the same as reducedim(op, map(f, A), region, f(v0)), but is generally faster because the intermediate array is avoided.

      Examples

      julia> a = reshape(collect(1:16), (4,4))
      -4×4 Array{Int64,2}:
      - 1  5   9  13
      - 2  6  10  14
      - 3  7  11  15
      - 4  8  12  16
      -
      -julia> mapreducedim(isodd, *, a, 1)
      -1×4 Array{Bool,2}:
      - false  false  false  false
      -
      -julia> mapreducedim(isodd, |, a, 1, true)
      -1×4 Array{Bool,2}:
      - true  true  true  true
      source
      Base.mapslicesFunction.
      mapslices(f, A, dims)

      Transform the given dimensions of array A using function f. f is called on each slice of A of the form A[...,:,...,:,...]. dims is an integer vector specifying where the colons go in this expression. The results are concatenated along the remaining dimensions. For example, if dims is [1,2] and A is 4-dimensional, f is called on A[:,:,i,j] for all i and j.

      Examples

      julia> a = reshape(collect(1:16),(2,2,2,2))
      -2×2×2×2 Array{Int64,4}:
      -[:, :, 1, 1] =
      - 1  3
      - 2  4
      -
      -[:, :, 2, 1] =
      - 5  7
      - 6  8
      -
      -[:, :, 1, 2] =
      -  9  11
      - 10  12
      -
      -[:, :, 2, 2] =
      - 13  15
      - 14  16
      -
      -julia> mapslices(sum, a, [1,2])
      -1×1×2×2 Array{Int64,4}:
      -[:, :, 1, 1] =
      - 10
      -
      -[:, :, 2, 1] =
      - 26
      -
      -[:, :, 1, 2] =
      - 42
      -
      -[:, :, 2, 2] =
      - 58
      source
      Base.sum_kbnFunction.
      sum_kbn(A)

      Returns the sum of all elements of A, using the Kahan-Babuska-Neumaier compensated summation algorithm for additional accuracy.

      source

      Combinatorics

      Base.Random.randpermFunction.
      randperm([rng=GLOBAL_RNG,] n::Integer)

      Construct a random permutation of length n. The optional rng argument specifies a random number generator (see Random Numbers). To randomly permute a arbitrary vector, see shuffle or shuffle!.

      Example

      julia> rng = MersenneTwister(1234);
      -
      -julia> randperm(rng, 4)
      -4-element Array{Int64,1}:
      - 2
      - 1
      - 4
      - 3
      source
      Base.invpermFunction.
      invperm(v)

      Return the inverse permutation of v. If B = A[v], then A == B[invperm(v)].

      Example

      julia> v = [2; 4; 3; 1];
      -
      -julia> invperm(v)
      -4-element Array{Int64,1}:
      - 4
      - 1
      - 3
      - 2
      -
      -julia> A = ['a','b','c','d'];
      -
      -julia> B = A[v]
      -4-element Array{Char,1}:
      - 'b'
      - 'd'
      - 'c'
      - 'a'
      -
      -julia> B[invperm(v)]
      -4-element Array{Char,1}:
      - 'a'
      - 'b'
      - 'c'
      - 'd'
      source
      Base.ispermFunction.
      isperm(v) -> Bool

      Returns true if v is a valid permutation.

      Examples

      julia> isperm([1; 2])
      -true
      -
      -julia> isperm([1; 3])
      -false
      source
      Base.permute!Method.
      permute!(v, p)

      Permute vector v in-place, according to permutation p. No checking is done to verify that p is a permutation.

      To return a new permutation, use v[p]. Note that this is generally faster than permute!(v,p) for large vectors.

      See also ipermute!.

      Example

      julia> A = [1, 1, 3, 4];
      -
      -julia> perm = [2, 4, 3, 1];
      -
      -julia> permute!(A, perm);
      -
      -julia> A
      -4-element Array{Int64,1}:
      - 1
      - 4
      - 3
      - 1
      source
      Base.ipermute!Function.
      ipermute!(v, p)

      Like permute!, but the inverse of the given permutation is applied.

      Example

      julia> A = [1, 1, 3, 4];
      -
      -julia> perm = [2, 4, 3, 1];
      -
      -julia> ipermute!(A, perm);
      -
      -julia> A
      -4-element Array{Int64,1}:
      - 4
      - 1
      - 3
      - 1
      source
      Base.Random.randcycleFunction.
      randcycle([rng=GLOBAL_RNG,] n::Integer)

      Construct a random cyclic permutation of length n. The optional rng argument specifies a random number generator, see Random Numbers.

      Example

      julia> rng = MersenneTwister(1234);
      -
      -julia> randcycle(rng, 6)
      -6-element Array{Int64,1}:
      - 3
      - 5
      - 4
      - 6
      - 1
      - 2
      source
      Base.Random.shuffleFunction.
      shuffle([rng=GLOBAL_RNG,] v)

      Return a randomly permuted copy of v. The optional rng argument specifies a random number generator (see Random Numbers). To permute v in-place, see shuffle!. To obtain randomly permuted indices, see randperm.

      Example

      julia> rng = MersenneTwister(1234);
      -
      -julia> shuffle(rng, collect(1:10))
      -10-element Array{Int64,1}:
      -  6
      -  1
      - 10
      -  2
      -  3
      -  9
      -  5
      -  7
      -  4
      -  8
      source
      Base.Random.shuffle!Function.
      shuffle!([rng=GLOBAL_RNG,] v)

      In-place version of shuffle: randomly permute the array v in-place, optionally supplying the random-number generator rng.

      Example

      julia> rng = MersenneTwister(1234);
      -
      -julia> shuffle!(rng, collect(1:16))
      -16-element Array{Int64,1}:
      -  2
      - 15
      -  5
      - 14
      -  1
      -  9
      - 10
      -  6
      - 11
      -  3
      - 16
      -  7
      -  4
      - 12
      -  8
      - 13
      source
      Base.reverseFunction.
      reverse(v [, start=1 [, stop=length(v) ]] )

      Return a copy of v reversed from start to stop.

      Examples

      julia> A = collect(1:5)
      -5-element Array{Int64,1}:
      - 1
      - 2
      - 3
      - 4
      - 5
      -
      -julia> reverse(A)
      -5-element Array{Int64,1}:
      - 5
      - 4
      - 3
      - 2
      - 1
      -
      -julia> reverse(A, 1, 4)
      -5-element Array{Int64,1}:
      - 4
      - 3
      - 2
      - 1
      - 5
      -
      -julia> reverse(A, 3, 5)
      -5-element Array{Int64,1}:
      - 1
      - 2
      - 5
      - 4
      - 3
      source
      Base.reverseindFunction.
      reverseind(v, i)

      Given an index i in reverse(v), return the corresponding index in v so that v[reverseind(v,i)] == reverse(v)[i]. (This can be nontrivial in the case where v is a Unicode string.)

      source
      Base.reverse!Function.
      reverse!(v [, start=1 [, stop=length(v) ]]) -> v

      In-place version of reverse.

      source

      BitArrays

      BitArrays are space-efficient "packed" boolean arrays, which store one bit per boolean value. They can be used similarly to Array{Bool} arrays (which store one byte per boolean value), and can be converted to/from the latter via Array(bitarray) and BitArray(array), respectively.

      Base.flipbits!Function.
      flipbits!(B::BitArray{N}) -> BitArray{N}

      Performs a bitwise not operation on B. See ~.

      Example

      julia> A = trues(2,2)
      -2×2 BitArray{2}:
      - true  true
      - true  true
      -
      -julia> flipbits!(A)
      -2×2 BitArray{2}:
      - false  false
      - false  false
      source
      Base.rol!Function.
      rol!(dest::BitVector, src::BitVector, i::Integer) -> BitVector

      Performs a left rotation operation on src and puts the result into dest. i controls how far to rotate the bits.

      source
      rol!(B::BitVector, i::Integer) -> BitVector

      Performs a left rotation operation in-place on B. i controls how far to rotate the bits.

      source
      Base.rolFunction.
      rol(B::BitVector, i::Integer) -> BitVector

      Performs a left rotation operation, returning a new BitVector. i controls how far to rotate the bits. See also rol!.

      Examples

      julia> A = BitArray([true, true, false, false, true])
      -5-element BitArray{1}:
      -  true
      -  true
      - false
      - false
      -  true
      -
      -julia> rol(A,1)
      -5-element BitArray{1}:
      -  true
      - false
      - false
      -  true
      -  true
      -
      -julia> rol(A,2)
      -5-element BitArray{1}:
      - false
      - false
      -  true
      -  true
      -  true
      -
      -julia> rol(A,5)
      -5-element BitArray{1}:
      -  true
      -  true
      - false
      - false
      -  true
      source
      Base.ror!Function.
      ror!(dest::BitVector, src::BitVector, i::Integer) -> BitVector

      Performs a right rotation operation on src and puts the result into dest. i controls how far to rotate the bits.

      source
      ror!(B::BitVector, i::Integer) -> BitVector

      Performs a right rotation operation in-place on B. i controls how far to rotate the bits.

      source
      Base.rorFunction.
      ror(B::BitVector, i::Integer) -> BitVector

      Performs a right rotation operation on B, returning a new BitVector. i controls how far to rotate the bits. See also ror!.

      Examples

      julia> A = BitArray([true, true, false, false, true])
      -5-element BitArray{1}:
      -  true
      -  true
      - false
      - false
      -  true
      -
      -julia> ror(A,1)
      -5-element BitArray{1}:
      -  true
      -  true
      -  true
      - false
      - false
      -
      -julia> ror(A,2)
      -5-element BitArray{1}:
      - false
      -  true
      -  true
      -  true
      - false
      -
      -julia> ror(A,5)
      -5-element BitArray{1}:
      -  true
      -  true
      - false
      - false
      -  true
      source

      Sparse Vectors and Matrices

      Sparse vectors and matrices largely support the same set of operations as their dense counterparts. The following functions are specific to sparse arrays.

      SparseVector{Tv,Ti<:Integer} <: AbstractSparseVector{Tv,Ti}

      Vector type for storing sparse vectors.

      source
      SparseMatrixCSC{Tv,Ti<:Integer} <: AbstractSparseMatrix{Tv,Ti}

      Matrix type for storing sparse matrices in the Compressed Sparse Column format.

      source
      sparse(A)

      Convert an AbstractMatrix A into a sparse matrix.

      Example

      julia> A = eye(3)
      -3×3 Array{Float64,2}:
      - 1.0  0.0  0.0
      - 0.0  1.0  0.0
      - 0.0  0.0  1.0
      -
      -julia> sparse(A)
      -3×3 SparseMatrixCSC{Float64,Int64} with 3 stored entries:
      -  [1, 1]  =  1.0
      -  [2, 2]  =  1.0
      -  [3, 3]  =  1.0
      source
      sparse(I, J, V,[ m, n, combine])

      Create a sparse matrix S of dimensions m x n such that S[I[k], J[k]] = V[k]. The combine function is used to combine duplicates. If m and n are not specified, they are set to maximum(I) and maximum(J) respectively. If the combine function is not supplied, combine defaults to + unless the elements of V are Booleans in which case combine defaults to |. All elements of I must satisfy 1 <= I[k] <= m, and all elements of J must satisfy 1 <= J[k] <= n. Numerical zeros in (I, J, V) are retained as structural nonzeros; to drop numerical zeros, use dropzeros!.

      For additional documentation and an expert driver, see Base.SparseArrays.sparse!.

      Example

      julia> Is = [1; 2; 3];
      -
      -julia> Js = [1; 2; 3];
      -
      -julia> Vs = [1; 2; 3];
      -
      -julia> sparse(Is, Js, Vs)
      -3×3 SparseMatrixCSC{Int64,Int64} with 3 stored entries:
      -  [1, 1]  =  1
      -  [2, 2]  =  2
      -  [3, 3]  =  3
      source
      sparsevec(I, V, [m, combine])

      Create a sparse vector S of length m such that S[I[k]] = V[k]. Duplicates are combined using the combine function, which defaults to + if no combine argument is provided, unless the elements of V are Booleans in which case combine defaults to |.

      julia> II = [1, 3, 3, 5]; V = [0.1, 0.2, 0.3, 0.2];
      -
      -julia> sparsevec(II, V)
      -5-element SparseVector{Float64,Int64} with 3 stored entries:
      -  [1]  =  0.1
      -  [3]  =  0.5
      -  [5]  =  0.2
      -
      -julia> sparsevec(II, V, 8, -)
      -8-element SparseVector{Float64,Int64} with 3 stored entries:
      -  [1]  =  0.1
      -  [3]  =  -0.1
      -  [5]  =  0.2
      -
      -julia> sparsevec([1, 3, 1, 2, 2], [true, true, false, false, false])
      -3-element SparseVector{Bool,Int64} with 3 stored entries:
      -  [1]  =  true
      -  [2]  =  false
      -  [3]  =  true
      source
      sparsevec(d::Dict, [m])

      Create a sparse vector of length m where the nonzero indices are keys from the dictionary, and the nonzero values are the values from the dictionary.

      julia> sparsevec(Dict(1 => 3, 2 => 2))
      -2-element SparseVector{Int64,Int64} with 2 stored entries:
      -  [1]  =  3
      -  [2]  =  2
      source
      sparsevec(A)

      Convert a vector A into a sparse vector of length m.

      Example

      julia> sparsevec([1.0, 2.0, 0.0, 0.0, 3.0, 0.0])
      -6-element SparseVector{Float64,Int64} with 3 stored entries:
      -  [1]  =  1.0
      -  [2]  =  2.0
      -  [5]  =  3.0
      source
      issparse(S)

      Returns true if S is sparse, and false otherwise.

      source
      Base.fullFunction.
      full(S)

      Convert a sparse matrix or vector S into a dense matrix or vector.

      Example

      julia> A = speye(3)
      -3×3 SparseMatrixCSC{Float64,Int64} with 3 stored entries:
      -  [1, 1]  =  1.0
      -  [2, 2]  =  1.0
      -  [3, 3]  =  1.0
      -
      -julia> full(A)
      -3×3 Array{Float64,2}:
      - 1.0  0.0  0.0
      - 0.0  1.0  0.0
      - 0.0  0.0  1.0
      source
      Base.SparseArrays.nnzFunction.
      nnz(A)

      Returns the number of stored (filled) elements in a sparse array.

      Example

      julia> A = speye(3)
      -3×3 SparseMatrixCSC{Float64,Int64} with 3 stored entries:
      -  [1, 1]  =  1.0
      -  [2, 2]  =  1.0
      -  [3, 3]  =  1.0
      -
      -julia> nnz(A)
      -3
      source
      spzeros([type,]m[,n])

      Create a sparse vector of length m or sparse matrix of size m x n. This sparse array will not contain any nonzero values. No storage will be allocated for nonzero values during construction. The type defaults to Float64 if not specified.

      Examples

      julia> spzeros(3, 3)
      -3×3 SparseMatrixCSC{Float64,Int64} with 0 stored entries
      -
      -julia> spzeros(Float32, 4)
      -4-element SparseVector{Float32,Int64} with 0 stored entries
      source
      spones(S)

      Create a sparse array with the same structure as that of S, but with every nonzero element having the value 1.0.

      Example

      julia> A = sparse([1,2,3,4],[2,4,3,1],[5.,4.,3.,2.])
      -4×4 SparseMatrixCSC{Float64,Int64} with 4 stored entries:
      -  [4, 1]  =  2.0
      -  [1, 2]  =  5.0
      -  [3, 3]  =  3.0
      -  [2, 4]  =  4.0
      -
      -julia> spones(A)
      -4×4 SparseMatrixCSC{Float64,Int64} with 4 stored entries:
      -  [4, 1]  =  1.0
      -  [1, 2]  =  1.0
      -  [3, 3]  =  1.0
      -  [2, 4]  =  1.0

      Note the difference from speye.

      source
      speye([type,]m[,n])

      Create a sparse identity matrix of size m x m. When n is supplied, create a sparse identity matrix of size m x n. The type defaults to Float64 if not specified.

      sparse(I, m, n) is equivalent to speye(Int, m, n), and sparse(α*I, m, n) can be used to efficiently create a sparse multiple α of the identity matrix.

      source
      speye(S)

      Create a sparse identity matrix with the same size as S.

      Example

      julia> A = sparse([1,2,3,4],[2,4,3,1],[5.,4.,3.,2.])
      -4×4 SparseMatrixCSC{Float64,Int64} with 4 stored entries:
      -  [4, 1]  =  2.0
      -  [1, 2]  =  5.0
      -  [3, 3]  =  3.0
      -  [2, 4]  =  4.0
      -
      -julia> speye(A)
      -4×4 SparseMatrixCSC{Float64,Int64} with 4 stored entries:
      -  [1, 1]  =  1.0
      -  [2, 2]  =  1.0
      -  [3, 3]  =  1.0
      -  [4, 4]  =  1.0

      Note the difference from spones.

      source
      speye([type,]m[,n])

      Create a sparse identity matrix of size m x m. When n is supplied, create a sparse identity matrix of size m x n. The type defaults to Float64 if not specified.

      sparse(I, m, n) is equivalent to speye(Int, m, n), and sparse(α*I, m, n) can be used to efficiently create a sparse multiple α of the identity matrix.

      source
      spdiagm(B, d[, m, n])

      Construct a sparse diagonal matrix. B is a tuple of vectors containing the diagonals and d is a tuple containing the positions of the diagonals. In the case the input contains only one diagonal, B can be a vector (instead of a tuple) and d can be the diagonal position (instead of a tuple), defaulting to 0 (diagonal). Optionally, m and n specify the size of the resulting sparse matrix.

      Example

      julia> spdiagm(([1,2,3,4],[4,3,2,1]),(-1,1))
      -5×5 SparseMatrixCSC{Int64,Int64} with 8 stored entries:
      -  [2, 1]  =  1
      -  [1, 2]  =  4
      -  [3, 2]  =  2
      -  [2, 3]  =  3
      -  [4, 3]  =  3
      -  [3, 4]  =  2
      -  [5, 4]  =  4
      -  [4, 5]  =  1
      source
      sprand([rng],[type],m,[n],p::AbstractFloat,[rfn])

      Create a random length m sparse vector or m by n sparse matrix, in which the probability of any element being nonzero is independently given by p (and hence the mean density of nonzeros is also exactly p). Nonzero values are sampled from the distribution specified by rfn and have the type type. The uniform distribution is used in case rfn is not specified. The optional rng argument specifies a random number generator, see Random Numbers.

      Example

      julia> rng = MersenneTwister(1234);
      -
      -julia> sprand(rng, Bool, 2, 2, 0.5)
      -2×2 SparseMatrixCSC{Bool,Int64} with 2 stored entries:
      -  [1, 1]  =  true
      -  [2, 1]  =  true
      -
      -julia> sprand(rng, Float64, 3, 0.75)
      -3-element SparseVector{Float64,Int64} with 1 stored entry:
      -  [3]  =  0.298614
      source
      sprandn([rng], m[,n],p::AbstractFloat)

      Create a random sparse vector of length m or sparse matrix of size m by n with the specified (independent) probability p of any entry being nonzero, where nonzero values are sampled from the normal distribution. The optional rng argument specifies a random number generator, see Random Numbers.

      Example

      julia> rng = MersenneTwister(1234);
      -
      -julia> sprandn(rng, 2, 2, 0.75)
      -2×2 SparseMatrixCSC{Float64,Int64} with 3 stored entries:
      -  [1, 1]  =  0.532813
      -  [2, 1]  =  -0.271735
      -  [2, 2]  =  0.502334
      source
      nonzeros(A)

      Return a vector of the structural nonzero values in sparse array A. This includes zeros that are explicitly stored in the sparse array. The returned vector points directly to the internal nonzero storage of A, and any modifications to the returned vector will mutate A as well. See rowvals and nzrange.

      Example

      julia> A = speye(3)
      -3×3 SparseMatrixCSC{Float64,Int64} with 3 stored entries:
      -  [1, 1]  =  1.0
      -  [2, 2]  =  1.0
      -  [3, 3]  =  1.0
      -
      -julia> nonzeros(A)
      -3-element Array{Float64,1}:
      - 1.0
      - 1.0
      - 1.0
      source
      rowvals(A::SparseMatrixCSC)

      Return a vector of the row indices of A. Any modifications to the returned vector will mutate A as well. Providing access to how the row indices are stored internally can be useful in conjunction with iterating over structural nonzero values. See also nonzeros and nzrange.

      Example

      julia> A = speye(3)
      -3×3 SparseMatrixCSC{Float64,Int64} with 3 stored entries:
      -  [1, 1]  =  1.0
      -  [2, 2]  =  1.0
      -  [3, 3]  =  1.0
      -
      -julia> rowvals(A)
      -3-element Array{Int64,1}:
      - 1
      - 2
      - 3
      source
      nzrange(A::SparseMatrixCSC, col::Integer)

      Return the range of indices to the structural nonzero values of a sparse matrix column. In conjunction with nonzeros and rowvals, this allows for convenient iterating over a sparse matrix :

      A = sparse(I,J,V)
      -rows = rowvals(A)
      -vals = nonzeros(A)
      -m, n = size(A)
      -for i = 1:n
      -   for j in nzrange(A, i)
      -      row = rows[j]
      -      val = vals[j]
      -      # perform sparse wizardry...
      -   end
      -end
      source
      dropzeros!(A::SparseMatrixCSC, trim::Bool = true)

      Removes stored numerical zeros from A, optionally trimming resulting excess space from A.rowval and A.nzval when trim is true.

      For an out-of-place version, see dropzeros. For algorithmic information, see fkeep!.

      source
      dropzeros(A::SparseMatrixCSC, trim::Bool = true)

      Generates a copy of A and removes stored numerical zeros from that copy, optionally trimming excess space from the result's rowval and nzval arrays when trim is true.

      For an in-place version and algorithmic information, see dropzeros!.

      Example

      julia> A = sparse([1, 2, 3], [1, 2, 3], [1.0, 0.0, 1.0])
      -3×3 SparseMatrixCSC{Float64,Int64} with 3 stored entries:
      -  [1, 1]  =  1.0
      -  [2, 2]  =  0.0
      -  [3, 3]  =  1.0
      -
      -julia> dropzeros(A)
      -3×3 SparseMatrixCSC{Float64,Int64} with 2 stored entries:
      -  [1, 1]  =  1.0
      -  [3, 3]  =  1.0
      source
      dropzeros!(x::SparseVector, trim::Bool = true)

      Removes stored numerical zeros from x, optionally trimming resulting excess space from x.nzind and x.nzval when trim is true.

      For an out-of-place version, see dropzeros. For algorithmic information, see fkeep!.

      source
      dropzeros(x::SparseVector, trim::Bool = true)

      Generates a copy of x and removes numerical zeros from that copy, optionally trimming excess space from the result's nzind and nzval arrays when trim is true.

      For an in-place version and algorithmic information, see dropzeros!.

      Example

      julia> A = sparsevec([1, 2, 3], [1.0, 0.0, 1.0])
      -3-element SparseVector{Float64,Int64} with 3 stored entries:
      -  [1]  =  1.0
      -  [2]  =  0.0
      -  [3]  =  1.0
      -
      -julia> dropzeros(A)
      -3-element SparseVector{Float64,Int64} with 2 stored entries:
      -  [1]  =  1.0
      -  [3]  =  1.0
      source
      permute{Tv,Ti}(A::SparseMatrixCSC{Tv,Ti}, p::AbstractVector{<:Integer},
      -    q::AbstractVector{<:Integer})

      Bilaterally permute A, returning PAQ (A[p,q]). Column-permutation q's length must match A's column count (length(q) == A.n). Row-permutation p's length must match A's row count (length(p) == A.m).

      For expert drivers and additional information, see permute!.

      Example

      julia> A = spdiagm([1, 2, 3, 4], 0, 4, 4) + spdiagm([5, 6, 7], 1, 4, 4)
      -4×4 SparseMatrixCSC{Int64,Int64} with 7 stored entries:
      -  [1, 1]  =  1
      -  [1, 2]  =  5
      -  [2, 2]  =  2
      -  [2, 3]  =  6
      -  [3, 3]  =  3
      -  [3, 4]  =  7
      -  [4, 4]  =  4
      -
      -julia> permute(A, [4, 3, 2, 1], [1, 2, 3, 4])
      -4×4 SparseMatrixCSC{Int64,Int64} with 7 stored entries:
      -  [4, 1]  =  1
      -  [3, 2]  =  2
      -  [4, 2]  =  5
      -  [2, 3]  =  3
      -  [3, 3]  =  6
      -  [1, 4]  =  4
      -  [2, 4]  =  7
      -
      -julia> permute(A, [1, 2, 3, 4], [4, 3, 2, 1])
      -4×4 SparseMatrixCSC{Int64,Int64} with 7 stored entries:
      -  [3, 1]  =  7
      -  [4, 1]  =  4
      -  [2, 2]  =  6
      -  [3, 2]  =  3
      -  [1, 3]  =  5
      -  [2, 3]  =  2
      -  [1, 4]  =  1
      source
      Base.permute!Method.
      permute!{Tv,Ti}(X::SparseMatrixCSC{Tv,Ti}, A::SparseMatrixCSC{Tv,Ti},
      -    p::AbstractVector{<:Integer}, q::AbstractVector{<:Integer}[, C::SparseMatrixCSC{Tv,Ti}])

      Bilaterally permute A, storing result PAQ (A[p,q]) in X. Stores intermediate result (AQ)^T (transpose(A[:,q])) in optional argument C if present. Requires that none of X, A, and, if present, C alias each other; to store result PAQ back into A, use the following method lacking X:

      permute!{Tv,Ti}(A::SparseMatrixCSC{Tv,Ti}, p::AbstractVector{<:Integer},
      -    q::AbstractVector{<:Integer}[, C::SparseMatrixCSC{Tv,Ti}[, workcolptr::Vector{Ti}]])

      X's dimensions must match those of A (X.m == A.m and X.n == A.n), and X must have enough storage to accommodate all allocated entries in A (length(X.rowval) >= nnz(A) and length(X.nzval) >= nnz(A)). Column-permutation q's length must match A's column count (length(q) == A.n). Row-permutation p's length must match A's row count (length(p) == A.m).

      C's dimensions must match those of transpose(A) (C.m == A.n and C.n == A.m), and C must have enough storage to accommodate all allocated entries in A (length(C.rowval) >= nnz(A) and length(C.nzval) >= nnz(A)).

      For additional (algorithmic) information, and for versions of these methods that forgo argument checking, see (unexported) parent methods unchecked_noalias_permute! and unchecked_aliasing_permute!.

      See also: permute.

      source
      diff --git a/julia-0.6.3/share/doc/julia/html/en/stdlib/base.html b/julia-0.6.3/share/doc/julia/html/en/stdlib/base.html deleted file mode 100644 index 7db4732..0000000 --- a/julia-0.6.3/share/doc/julia/html/en/stdlib/base.html +++ /dev/null @@ -1,410 +0,0 @@ - -Essentials · The Julia Language

      Essentials

      Essentials

      Introduction

      The Julia standard library contains a range of functions and macros appropriate for performing scientific and numerical computing, but is also as broad as those of many general purpose programming languages. Additional functionality is available from a growing collection of available packages. Functions are grouped by topic below.

      Some general notes:

      • Except for functions in built-in modules (Pkg, Collections, Test and Profile), all functions documented here are directly available for use in programs.

      • To use module functions, use import Module to import the module, and Module.fn(x) to use the functions.

      • Alternatively, using Module will import all exported Module functions into the current namespace.

      • By convention, function names ending with an exclamation point (!) modify their arguments. Some functions have both modifying (e.g., sort!) and non-modifying (sort) versions.

      Getting Around

      Base.exitFunction.
      exit([code])

      Quit (or control-D at the prompt). The default exit code is zero, indicating that the processes completed successfully.

      source
      Base.quitFunction.
      quit()

      Quit the program indicating that the processes completed successfully. This function calls exit(0) (see exit).

      source
      Base.atexitFunction.
      atexit(f)

      Register a zero-argument function f() to be called at process exit. atexit() hooks are called in last in first out (LIFO) order and run before object finalizers.

      source
      Base.atreplinitFunction.
      atreplinit(f)

      Register a one-argument function to be called before the REPL interface is initialized in interactive sessions; this is useful to customize the interface. The argument of f is the REPL object. This function should be called from within the .juliarc.jl initialization file.

      source
      Base.isinteractiveFunction.
      isinteractive() -> Bool

      Determine whether Julia is running an interactive session.

      source
      Base.whosFunction.
      whos(io::IO=STDOUT, m::Module=current_module(), pattern::Regex=r"")

      Print information about exported global variables in a module, optionally restricted to those matching pattern.

      The memory consumption estimate is an approximate lower bound on the size of the internal structure of the object.

      source
      Base.summarysizeFunction.
      Base.summarysize(obj; exclude=Union{...}, chargeall=Union{...}) -> Int

      Compute the amount of memory used by all unique objects reachable from the argument.

      Keyword Arguments

      • exclude: specifies the types of objects to exclude from the traversal.

      • chargeall: specifies the types of objects to always charge the size of all of their fields, even if those fields would normally be excluded.

      source
      Base.editMethod.
      edit(path::AbstractString, line::Integer=0)

      Edit a file or directory optionally providing a line number to edit the file at. Returns to the julia prompt when you quit the editor. The editor can be changed by setting JULIA_EDITOR, VISUAL or EDITOR as an environment variable.

      source
      Base.editMethod.
      edit(function, [types])

      Edit the definition of a function, optionally specifying a tuple of types to indicate which method to edit. The editor can be changed by setting JULIA_EDITOR, VISUAL or EDITOR as an environment variable.

      source
      Base.@editMacro.
      @edit

      Evaluates the arguments to the function or macro call, determines their types, and calls the edit function on the resulting expression.

      source
      Base.lessMethod.
      less(file::AbstractString, [line::Integer])

      Show a file using the default pager, optionally providing a starting line number. Returns to the julia prompt when you quit the pager.

      source
      Base.lessMethod.
      less(function, [types])

      Show the definition of a function using the default pager, optionally specifying a tuple of types to indicate which method to see.

      source
      Base.@lessMacro.
      @less

      Evaluates the arguments to the function or macro call, determines their types, and calls the less function on the resulting expression.

      source
      Base.clipboardMethod.
      clipboard(x)

      Send a printed form of x to the operating system clipboard ("copy").

      source
      Base.clipboardMethod.
      clipboard() -> AbstractString

      Return a string with the contents of the operating system clipboard ("paste").

      source
      Base.reloadFunction.
      reload(name::AbstractString)

      Force reloading of a package, even if it has been loaded before. This is intended for use during package development as code is modified.

      source
      Base.requireFunction.
      require(module::Symbol)

      This function is part of the implementation of using / import, if a module is not already defined in Main. It can also be called directly to force reloading a module, regardless of whether it has been loaded before (for example, when interactively developing libraries).

      Loads a source file, in the context of the Main module, on every active node, searching standard locations for files. require is considered a top-level operation, so it sets the current include path but does not use it to search for files (see help for include). This function is typically used to load library code, and is implicitly called by using to load packages.

      When searching for files, require first looks for package code under Pkg.dir(), then tries paths in the global array LOAD_PATH. require is case-sensitive on all platforms, including those with case-insensitive filesystems like macOS and Windows.

      source
      Base.compilecacheFunction.
      Base.compilecache(module::String)

      Creates a precompiled cache file for a module and all of its dependencies. This can be used to reduce package load times. Cache files are stored in LOAD_CACHE_PATH[1], which defaults to ~/.julia/lib/VERSION. See Module initialization and precompilation for important notes.

      source
      Base.__precompile__Function.
      __precompile__(isprecompilable::Bool=true)

      Specify whether the file calling this function is precompilable. If isprecompilable is true, then __precompile__ throws an exception when the file is loaded by using/import/require unless the file is being precompiled, and in a module file it causes the module to be automatically precompiled when it is imported. Typically, __precompile__() should occur before the module declaration in the file, or better yet VERSION >= v"0.4" && __precompile__() in order to be backward-compatible with Julia 0.3.

      If a module or file is not safely precompilable, it should call __precompile__(false) in order to throw an error if Julia attempts to precompile it.

      __precompile__() should not be used in a module unless all of its dependencies are also using __precompile__(). Failure to do so can result in a runtime error when loading the module.

      source
      Base.includeFunction.
      include(path::AbstractString)

      Evaluate the contents of the input source file in the current context. Returns the result of the last evaluated expression of the input file. During including, a task-local include path is set to the directory containing the file. Nested calls to include will search relative to that path. All paths refer to files on node 1 when running in parallel, and files will be fetched from node 1. This function is typically used to load source interactively, or to combine files in packages that are broken into multiple source files.

      source
      Base.include_stringFunction.
      include_string(code::AbstractString, filename::AbstractString="string")

      Like include, except reads code from the given string rather than from a file. Since there is no file path involved, no path processing or fetching from node 1 is done.

      source
      include_dependency(path::AbstractString)

      In a module, declare that the file specified by path (relative or absolute) is a dependency for precompilation; that is, the module will need to be recompiled if this file changes.

      This is only needed if your module depends on a file that is not used via include. It has no effect outside of compilation.

      source
      Base.Docs.aproposFunction.
      apropos(string)

      Search through all documentation for a string, ignoring case.

      source
      Base.whichMethod.
      which(f, types)

      Returns the method of f (a Method object) that would be called for arguments of the given types.

      If types is an abstract type, then the method that would be called by invoke is returned.

      source
      Base.whichMethod.
      which(symbol)

      Return the module in which the binding for the variable referenced by symbol was created.

      source
      Base.@whichMacro.
      @which

      Applied to a function or macro call, it evaluates the arguments to the specified call, and returns the Method object for the method that would be called for those arguments. Applied to a variable, it returns the module in which the variable was bound. It calls out to the which function.

      source
      Base.methodsFunction.
      methods(f, [types])

      Returns the method table for f.

      If types is specified, returns an array of methods whose types match.

      source
      Base.methodswithFunction.
      methodswith(typ[, module or function][, showparents::Bool=false])

      Return an array of methods with an argument of type typ.

      The optional second argument restricts the search to a particular module or function (the default is all modules, starting from Main).

      If optional showparents is true, also return arguments with a parent type of typ, excluding type Any.

      source
      Base.@showMacro.
      @show

      Show an expression and result, returning the result.

      source
      Base.versioninfoFunction.
      versioninfo(io::IO=STDOUT, verbose::Bool=false)

      Print information about the version of Julia in use. If the verbose argument is true, detailed system information is shown as well.

      source
      Base.workspaceFunction.
      workspace()

      Replace the top-level module (Main) with a new one, providing a clean workspace. The previous Main module is made available as LastMain. A previously-loaded package can be accessed using a statement such as using LastMain.Package.

      This function should only be used interactively.

      source
      ansKeyword.
      ans

      A variable referring to the last computed value, automatically set at the interactive prompt.

      source

      All Objects

      Core.:===Function.
      ===(x,y) -> Bool
      -≡(x,y) -> Bool

      Determine whether x and y are identical, in the sense that no program could distinguish them. Compares mutable objects by address in memory, and compares immutable objects (such as numbers) by contents at the bit level. This function is sometimes called egal.

      julia> a = [1, 2]; b = [1, 2];
      -
      -julia> a == b
      -true
      -
      -julia> a === b
      -false
      -
      -julia> a === a
      -true
      source
      Core.isaFunction.
      isa(x, type) -> Bool

      Determine whether x is of the given type. Can also be used as an infix operator, e.g. x isa type.

      source
      Base.isequalMethod.
      isequal(x, y)

      Similar to ==, except treats all floating-point NaN values as equal to each other, and treats -0.0 as unequal to 0.0. The default implementation of isequal calls ==, so if you have a type that doesn't have these floating-point subtleties then you probably only need to define ==.

      isequal is the comparison function used by hash tables (Dict). isequal(x,y) must imply that hash(x) == hash(y).

      This typically means that if you define your own == function then you must define a corresponding hash (and vice versa). Collections typically implement isequal by calling isequal recursively on all contents.

      Scalar types generally do not need to implement isequal separate from ==, unless they represent floating-point numbers amenable to a more efficient implementation than that provided as a generic fallback (based on isnan, signbit, and ==).

      julia> isequal([1., NaN], [1., NaN])
      -true
      -
      -julia> [1., NaN] == [1., NaN]
      -false
      -
      -julia> 0.0 == -0.0
      -true
      -
      -julia> isequal(0.0, -0.0)
      -false
      source
      Base.isequalMethod.
      isequal(x, y)

      Similar to ==, except treats all floating-point NaN values as equal to each other, and treats -0.0 as unequal to 0.0. The default implementation of isequal calls ==, so if you have a type that doesn't have these floating-point subtleties then you probably only need to define ==.

      isequal is the comparison function used by hash tables (Dict). isequal(x,y) must imply that hash(x) == hash(y).

      This typically means that if you define your own == function then you must define a corresponding hash (and vice versa). Collections typically implement isequal by calling isequal recursively on all contents.

      Scalar types generally do not need to implement isequal separate from ==, unless they represent floating-point numbers amenable to a more efficient implementation than that provided as a generic fallback (based on isnan, signbit, and ==).

      julia> isequal([1., NaN], [1., NaN])
      -true
      -
      -julia> [1., NaN] == [1., NaN]
      -false
      -
      -julia> 0.0 == -0.0
      -true
      -
      -julia> isequal(0.0, -0.0)
      -false
      source
      isequal(x::Nullable, y::Nullable)

      If neither x nor y is null, compare them according to their values (i.e. isequal(get(x), get(y))). Else, return true if both arguments are null, and false if one is null but not the other: nulls are considered equal.

      source
      Base.islessFunction.
      isless(x, y)

      Test whether x is less than y, according to a canonical total order. Values that are normally unordered, such as NaN, are ordered in an arbitrary but consistent fashion. This is the default comparison used by sort. Non-numeric types with a canonical total order should implement this function. Numeric types only need to implement it if they have special values such as NaN.

      source
      Base.islessMethod.
      isless(x::Nullable, y::Nullable)

      If neither x nor y is null, compare them according to their values (i.e. isless(get(x), get(y))). Else, return true if only y is null, and false otherwise: nulls are always considered greater than non-nulls, but not greater than another null.

      source
      Base.ifelseFunction.
      ifelse(condition::Bool, x, y)

      Return x if condition is true, otherwise return y. This differs from ? or if in that it is an ordinary function, so all the arguments are evaluated first. In some cases, using ifelse instead of an if statement can eliminate the branch in generated code and provide higher performance in tight loops.

      julia> ifelse(1 > 2, 1, 2)
      -2
      source
      Base.lexcmpFunction.
      lexcmp(x, y)

      Compare x and y lexicographically and return -1, 0, or 1 depending on whether x is less than, equal to, or greater than y, respectively. This function should be defined for lexicographically comparable types, and lexless will call lexcmp by default.

      julia> lexcmp("abc", "abd")
      --1
      -
      -julia> lexcmp("abc", "abc")
      -0
      source
      Base.lexlessFunction.
      lexless(x, y)

      Determine whether x is lexicographically less than y.

      julia> lexless("abc", "abd")
      -true
      source
      Core.typeofFunction.
      typeof(x)

      Get the concrete type of x.

      source
      Core.tupleFunction.
      tuple(xs...)

      Construct a tuple of the given objects.

      Example

      julia> tuple(1, 'a', pi)
      -(1, 'a', π = 3.1415926535897...)
      source
      Base.ntupleFunction.
      ntuple(f::Function, n::Integer)

      Create a tuple of length n, computing each element as f(i), where i is the index of the element.

      julia> ntuple(i -> 2*i, 4)
      -(2, 4, 6, 8)
      source
      Base.object_idFunction.
      object_id(x)

      Get a hash value for x based on object identity. object_id(x)==object_id(y) if x === y.

      source
      Base.hashFunction.
      hash(x[, h::UInt])

      Compute an integer hash code such that isequal(x,y) implies hash(x)==hash(y). The optional second argument h is a hash code to be mixed with the result.

      New types should implement the 2-argument form, typically by calling the 2-argument hash method recursively in order to mix hashes of the contents with each other (and with h). Typically, any type that implements hash should also implement its own == (hence isequal) to guarantee the property mentioned above.

      source
      Base.finalizerFunction.
      finalizer(x, f)

      Register a function f(x) to be called when there are no program-accessible references to x. The type of x must be a mutable struct, otherwise the behavior of this function is unpredictable.

      source
      Base.finalizeFunction.
      finalize(x)

      Immediately run finalizers registered for object x.

      source
      Base.copyFunction.
      copy(x)

      Create a shallow copy of x: the outer structure is copied, but not all internal values. For example, copying an array produces a new array with identically-same elements as the original.

      source
      Base.deepcopyFunction.
      deepcopy(x)

      Create a deep copy of x: everything is copied recursively, resulting in a fully independent object. For example, deep-copying an array produces a new array whose elements are deep copies of the original elements. Calling deepcopy on an object should generally have the same effect as serializing and then deserializing it.

      As a special case, functions can only be actually deep-copied if they are anonymous, otherwise they are just copied. The difference is only relevant in the case of closures, i.e. functions which may contain hidden internal references.

      While it isn't normally necessary, user-defined types can override the default deepcopy behavior by defining a specialized version of the function deepcopy_internal(x::T, dict::ObjectIdDict) (which shouldn't otherwise be used), where T is the type to be specialized for, and dict keeps track of objects copied so far within the recursion. Within the definition, deepcopy_internal should be used in place of deepcopy, and the dict variable should be updated as appropriate before returning.

      source
      Core.isdefinedFunction.
      isdefined([m::Module,] s::Symbol)
      -isdefined(object, s::Symbol)
      -isdefined(object, index::Int)

      Tests whether an assignable location is defined. The arguments can be a module and a symbol or a composite object and field name (as a symbol) or index. With a single symbol argument, tests whether a global variable with that name is defined in current_module().

      source
      Base.convertFunction.
      convert(T, x)

      Convert x to a value of type T.

      If T is an Integer type, an InexactError will be raised if x is not representable by T, for example if x is not integer-valued, or is outside the range supported by T.

      Examples

      julia> convert(Int, 3.0)
      -3
      -
      -julia> convert(Int, 3.5)
      -ERROR: InexactError()
      -Stacktrace:
      - [1] convert(::Type{Int64}, ::Float64) at ./float.jl:679

      If T is a AbstractFloat or Rational type, then it will return the closest value to x representable by T.

      julia> x = 1/3
      -0.3333333333333333
      -
      -julia> convert(Float32, x)
      -0.33333334f0
      -
      -julia> convert(Rational{Int32}, x)
      -1//3
      -
      -julia> convert(Rational{Int64}, x)
      -6004799503160661//18014398509481984

      If T is a collection type and x a collection, the result of convert(T, x) may alias x.

      julia> x = Int[1,2,3];
      -
      -julia> y = convert(Vector{Int}, x);
      -
      -julia> y === x
      -true

      Similarly, if T is a composite type and x a related instance, the result of convert(T, x) may alias part or all of x.

      julia> x = speye(5);
      -
      -julia> typeof(x)
      -SparseMatrixCSC{Float64,Int64}
      -
      -julia> y = convert(SparseMatrixCSC{Float64,Int64}, x);
      -
      -julia> z = convert(SparseMatrixCSC{Float32,Int64}, y);
      -
      -julia> y === x
      -true
      -
      -julia> z === x
      -false
      -
      -julia> z.colptr === x.colptr
      -true
      source
      Base.promoteFunction.
      promote(xs...)

      Convert all arguments to their common promotion type (if any), and return them all (as a tuple).

      Example

      julia> promote(Int8(1), Float16(4.5), Float32(4.1))
      -(1.0f0, 4.5f0, 4.1f0)
      source
      Base.oftypeFunction.
      oftype(x, y)

      Convert y to the type of x (convert(typeof(x), y)).

      source
      Base.widenFunction.
      widen(x)

      If x is a type, return a "larger" type (for numeric types, this will be a type with at least as much range and precision as the argument, and usually more). Otherwise x is converted to widen(typeof(x)).

      Examples

      julia> widen(Int32)
      -Int64
      -
      -julia> widen(1.5f0)
      -1.5
      source
      Base.identityFunction.
      identity(x)

      The identity function. Returns its argument.

      julia> identity("Well, what did you expect?")
      -"Well, what did you expect?"
      source

      Types

      Base.supertypeFunction.
      supertype(T::DataType)

      Return the supertype of DataType T.

      julia> supertype(Int32)
      -Signed
      source
      Core.issubtypeFunction.
      issubtype(type1, type2)

      Return true if and only if all values of type1 are also of type2. Can also be written using the <: infix operator as type1 <: type2.

      Examples

      julia> issubtype(Int8, Int32)
      -false
      -
      -julia> Int8 <: Integer
      -true
      source
      Base.:<:Function.
      <:(T1, T2)

      Subtype operator, equivalent to issubtype(T1, T2).

      julia> Float64 <: AbstractFloat
      -true
      -
      -julia> Vector{Int} <: AbstractArray
      -true
      -
      -julia> Matrix{Float64} <: Matrix{AbstractFloat}
      -false
      source
      Base.:>:Function.
      >:(T1, T2)

      Supertype operator, equivalent to issubtype(T2, T1).

      source
      Base.subtypesFunction.
      subtypes(T::DataType)

      Return a list of immediate subtypes of DataType T. Note that all currently loaded subtypes are included, including those not visible in the current module.

      julia> subtypes(Integer)
      -4-element Array{Union{DataType, UnionAll},1}:
      - BigInt
      - Bool
      - Signed
      - Unsigned
      source
      Base.typeminFunction.
      typemin(T)

      The lowest value representable by the given (real) numeric DataType T.

      Examples

      julia> typemin(Float16)
      --Inf16
      -
      -julia> typemin(Float32)
      --Inf32
      source
      Base.typemaxFunction.
      typemax(T)

      The highest value representable by the given (real) numeric DataType.

      source
      Base.realminFunction.
      realmin(T)

      The smallest in absolute value non-subnormal value representable by the given floating-point DataType T.

      source
      Base.realmaxFunction.
      realmax(T)

      The highest finite value representable by the given floating-point DataType T.

      Examples

      julia> realmax(Float16)
      -Float16(6.55e4)
      -
      -julia> realmax(Float32)
      -3.4028235f38
      source
      Base.maxintfloatFunction.
      maxintfloat(T)

      The largest integer losslessly representable by the given floating-point DataType T.

      source
      maxintfloat(T, S)

      The largest integer losslessly representable by the given floating-point DataType T that also does not exceed the maximum integer representable by the integer DataType S.

      source
      Base.sizeofMethod.
      sizeof(T)

      Size, in bytes, of the canonical binary representation of the given DataType T, if any.

      Examples

      julia> sizeof(Float32)
      -4
      -
      -julia> sizeof(Complex128)
      -16

      If T does not have a specific size, an error is thrown.

      julia> sizeof(Base.LinAlg.LU)
      -ERROR: argument is an abstract type; size is indeterminate
      -Stacktrace:
      - [1] sizeof(::Type{T} where T) at ./essentials.jl:159
      source
      Base.epsMethod.
      eps(::Type{T}) where T<:AbstractFloat
      -eps()

      Returns the machine epsilon of the floating point type T (T = Float64 by default). This is defined as the gap between 1 and the next largest value representable by T, and is equivalent to eps(one(T)).

      julia> eps()
      -2.220446049250313e-16
      -
      -julia> eps(Float32)
      -1.1920929f-7
      -
      -julia> 1.0 + eps()
      -1.0000000000000002
      -
      -julia> 1.0 + eps()/2
      -1.0
      source
      Base.epsMethod.
      eps(x::AbstractFloat)

      Returns the unit in last place (ulp) of x. This is the distance between consecutive representable floating point values at x. In most cases, if the distance on either side of x is different, then the larger of the two is taken, that is

      eps(x) == max(x-prevfloat(x), nextfloat(x)-x)

      The exceptions to this rule are the smallest and largest finite values (e.g. nextfloat(-Inf) and prevfloat(Inf) for Float64), which round to the smaller of the values.

      The rationale for this behavior is that eps bounds the floating point rounding error. Under the default RoundNearest rounding mode, if $y$ is a real number and $x$ is the nearest floating point number to $y$, then

      \[|y-x| \leq \operatorname{eps}(x)/2.\]
      julia> eps(1.0)
      -2.220446049250313e-16
      -
      -julia> eps(prevfloat(2.0))
      -2.220446049250313e-16
      -
      -julia> eps(2.0)
      -4.440892098500626e-16
      -
      -julia> x = prevfloat(Inf)      # largest finite Float64
      -1.7976931348623157e308
      -
      -julia> x + eps(x)/2            # rounds up
      -Inf
      -
      -julia> x + prevfloat(eps(x)/2) # rounds down
      -1.7976931348623157e308
      source
      Base.promote_typeFunction.
      promote_type(type1, type2)

      Determine a type big enough to hold values of each argument type without loss, whenever possible. In some cases, where no type exists to which both types can be promoted losslessly, some loss is tolerated; for example, promote_type(Int64, Float64) returns Float64 even though strictly, not all Int64 values can be represented exactly as Float64 values.

      julia> promote_type(Int64, Float64)
      -Float64
      -
      -julia> promote_type(Int32, Int64)
      -Int64
      -
      -julia> promote_type(Float32, BigInt)
      -BigFloat
      source
      Base.promote_ruleFunction.
      promote_rule(type1, type2)

      Specifies what type should be used by promote when given values of types type1 and type2. This function should not be called directly, but should have definitions added to it for new types as appropriate.

      source
      Core.getfieldFunction.
      getfield(value, name::Symbol)

      Extract a named field from a value of composite type. The syntax a.b calls getfield(a, :b).

      Example

      julia> a = 1//2
      -1//2
      -
      -julia> getfield(a, :num)
      -1
      source
      Core.setfield!Function.
      setfield!(value, name::Symbol, x)

      Assign x to a named field in value of composite type. The syntax a.b = c calls setfield!(a, :b, c).

      source
      Base.fieldoffsetFunction.
      fieldoffset(type, i)

      The byte offset of field i of a type relative to the data start. For example, we could use it in the following manner to summarize information about a struct:

      julia> structinfo(T) = [(fieldoffset(T,i), fieldname(T,i), fieldtype(T,i)) for i = 1:nfields(T)];
      -
      -julia> structinfo(Base.Filesystem.StatStruct)
      -12-element Array{Tuple{UInt64,Symbol,DataType},1}:
      - (0x0000000000000000, :device, UInt64)
      - (0x0000000000000008, :inode, UInt64)
      - (0x0000000000000010, :mode, UInt64)
      - (0x0000000000000018, :nlink, Int64)
      - (0x0000000000000020, :uid, UInt64)
      - (0x0000000000000028, :gid, UInt64)
      - (0x0000000000000030, :rdev, UInt64)
      - (0x0000000000000038, :size, Int64)
      - (0x0000000000000040, :blksize, Int64)
      - (0x0000000000000048, :blocks, Int64)
      - (0x0000000000000050, :mtime, Float64)
      - (0x0000000000000058, :ctime, Float64)
      source
      Core.fieldtypeFunction.
      fieldtype(T, name::Symbol | index::Int)

      Determine the declared type of a field (specified by name or index) in a composite DataType T.

      julia> struct Foo
      -           x::Int64
      -           y::String
      -       end
      -
      -julia> fieldtype(Foo, :x)
      -Int64
      -
      -julia> fieldtype(Foo, 2)
      -String
      source
      Base.isimmutableFunction.
      isimmutable(v)

      Return true iff value v is immutable. See Mutable Composite Types for a discussion of immutability. Note that this function works on values, so if you give it a type, it will tell you that a value of DataType is mutable.

      julia> isimmutable(1)
      -true
      -
      -julia> isimmutable([1,2])
      -false
      source
      Base.isbitsFunction.
      isbits(T)

      Return true if T is a "plain data" type, meaning it is immutable and contains no references to other values. Typical examples are numeric types such as UInt8, Float64, and Complex{Float64}.

      julia> isbits(Complex{Float64})
      -true
      -
      -julia> isbits(Complex)
      -false
      source
      Base.isleaftypeFunction.
      isleaftype(T)

      Determine whether T's only subtypes are itself and Union{}. This means T is a concrete type that can have instances.

      julia> isleaftype(Complex)
      -false
      -
      -julia> isleaftype(Complex{Float32})
      -true
      -
      -julia> isleaftype(Vector{Complex})
      -true
      -
      -julia> isleaftype(Vector{Complex{Float32}})
      -true
      source
      Base.typejoinFunction.
      typejoin(T, S)

      Compute a type that contains both T and S.

      source
      Base.typeintersectFunction.
      typeintersect(T, S)

      Compute a type that contains the intersection of T and S. Usually this will be the smallest such type or one close to it.

      source
      Base.ValType.
      Val{c}

      Create a "value type" out of c, which must be an isbits value. The intent of this construct is to be able to dispatch on constants, e.g., f(Val{false}) allows you to dispatch directly (at compile-time) to an implementation f(::Type{Val{false}}), without having to test the boolean value at runtime.

      source
      Base.Enums.@enumMacro.
      @enum EnumName[::BaseType] value1[=x] value2[=y]

      Create an Enum{BaseType} subtype with name EnumName and enum member values of value1 and value2 with optional assigned values of x and y, respectively. EnumName can be used just like other types and enum member values as regular values, such as

      julia> @enum Fruit apple=1 orange=2 kiwi=3
      -
      -julia> f(x::Fruit) = "I'm a Fruit with value: $(Int(x))"
      -f (generic function with 1 method)
      -
      -julia> f(apple)
      -"I'm a Fruit with value: 1"

      BaseType, which defaults to Int32, must be a primitive subtype of Integer. Member values can be converted between the enum type and BaseType. read and write perform these conversions automatically.

      source
      Base.instancesFunction.
      instances(T::Type)

      Return a collection of all instances of the given type, if applicable. Mostly used for enumerated types (see @enum).

      julia> @enum Color red blue green
      -
      -julia> instances(Color)
      -(red::Color = 0, blue::Color = 1, green::Color = 2)
      source

      Generic Functions

      Core.FunctionType.
      Function

      Abstract type of all functions.

      julia> isa(+, Function)
      -true
      -
      -julia> typeof(sin)
      -Base.#sin
      -
      -julia> ans <: Function
      -true
      source
      Base.method_existsFunction.
      method_exists(f, Tuple type, world=typemax(UInt)) -> Bool

      Determine whether the given generic function has a method matching the given Tuple of argument types with the upper bound of world age given by world.

      julia> method_exists(length, Tuple{Array})
      -true
      source
      Core.applicableFunction.
      applicable(f, args...) -> Bool

      Determine whether the given generic function has a method applicable to the given arguments.

      Examples

      julia> function f(x, y)
      -           x + y
      -       end;
      -
      -julia> applicable(f, 1)
      -false
      -
      -julia> applicable(f, 1, 2)
      -true
      source
      Core.invokeFunction.
      invoke(f, types <: Tuple, args...)

      Invoke a method for the given generic function matching the specified types, on the specified arguments. The arguments must be compatible with the specified types. This allows invoking a method other than the most specific matching method, which is useful when the behavior of a more general definition is explicitly needed (often as part of the implementation of a more specific method of the same function).

      source
      Base.invokelatestFunction.
      invokelatest(f, args...)

      Calls f(args...), but guarantees that the most recent method of f will be executed. This is useful in specialized circumstances, e.g. long-running event loops or callback functions that may call obsolete versions of a function f. (The drawback is that invokelatest is somewhat slower than calling f directly, and the type of the result cannot be inferred by the compiler.)

      source
      Base.:|>Function.
      |>(x, f)

      Applies a function to the preceding argument. This allows for easy function chaining.

      julia> [1:5;] |> x->x.^2 |> sum |> inv
      -0.01818181818181818
      source
      Base.:∘Function.
      f ∘ g

      Compose functions: i.e. (f ∘ g)(args...) means f(g(args...)). The symbol can be entered in the Julia REPL (and most editors, appropriately configured) by typing \circ<tab>. Example:

      julia> map(uppercase∘hex, 250:255)
      -6-element Array{String,1}:
      - "FA"
      - "FB"
      - "FC"
      - "FD"
      - "FE"
      - "FF"
      source

      Syntax

      Core.evalFunction.
      eval([m::Module], expr::Expr)

      Evaluate an expression in the given module and return the result. Every Module (except those defined with baremodule) has its own 1-argument definition of eval, which evaluates expressions in that module.

      source
      Base.@evalMacro.
      @eval [mod,] ex

      Evaluate an expression with values interpolated into it using eval. If two arguments are provided, the first is the module to evaluate in.

      source
      Base.evalfileFunction.
      evalfile(path::AbstractString, args::Vector{String}=String[])

      Load the file using include, evaluate all expressions, and return the value of the last one.

      source
      Base.escFunction.
      esc(e::ANY)

      Only valid in the context of an Expr returned from a macro. Prevents the macro hygiene pass from turning embedded variables into gensym variables. See the Macros section of the Metaprogramming chapter of the manual for more details and examples.

      source
      Base.@inboundsMacro.
      @inbounds(blk)

      Eliminates array bounds checking within expressions.

      In the example below the bound check of array A is skipped to improve performance.

      function sum(A::AbstractArray)
      -    r = zero(eltype(A))
      -    for i = 1:length(A)
      -        @inbounds r += A[i]
      -    end
      -    return r
      -end
      Warning

      Using @inbounds may return incorrect results/crashes/corruption for out-of-bounds indices. The user is responsible for checking it manually.

      source
      Base.@inlineMacro.
      @inline

      Give a hint to the compiler that this function is worth inlining.

      Small functions typically do not need the @inline annotation, as the compiler does it automatically. By using @inline on bigger functions, an extra nudge can be given to the compiler to inline it. This is shown in the following example:

      @inline function bigfunction(x)
      -    #=
      -        Function Definition
      -    =#
      -end
      source
      Base.@noinlineMacro.
      @noinline

      Prevents the compiler from inlining a function.

      Small functions are typically inlined automatically. By using @noinline on small functions, auto-inlining can be prevented. This is shown in the following example:

      @noinline function smallfunction(x)
      -    #=
      -        Function Definition
      -    =#
      -end
      source
      Base.gensymFunction.
      gensym([tag])

      Generates a symbol which will not conflict with other variable names.

      source
      Base.@gensymMacro.
      @gensym

      Generates a gensym symbol for a variable. For example, @gensym x y is transformed into x = gensym("x"); y = gensym("y").

      source
      Base.@pollyMacro.
      @polly

      Tells the compiler to apply the polyhedral optimizer Polly to a function.

      source
      Base.parseMethod.
      parse(str, start; greedy=true, raise=true)

      Parse the expression string and return an expression (which could later be passed to eval for execution). start is the index of the first character to start parsing. If greedy is true (default), parse will try to consume as much input as it can; otherwise, it will stop as soon as it has parsed a valid expression. Incomplete but otherwise syntactically valid expressions will return Expr(:incomplete, "(error message)"). If raise is true (default), syntax errors other than incomplete expressions will raise an error. If raise is false, parse will return an expression that will raise an error upon evaluation.

      julia> parse("x = 3, y = 5", 7)
      -(:(y = 5), 13)
      -
      -julia> parse("x = 3, y = 5", 5)
      -(:((3, y) = 5), 13)
      source
      Base.parseMethod.
      parse(str; raise=true)

      Parse the expression string greedily, returning a single expression. An error is thrown if there are additional characters after the first expression. If raise is true (default), syntax errors will raise an error; otherwise, parse will return an expression that will raise an error upon evaluation.

      julia> parse("x = 3")
      -:(x = 3)
      -
      -julia> parse("x = ")
      -:($(Expr(:incomplete, "incomplete: premature end of input")))
      -
      -julia> parse("1.0.2")
      -ERROR: ParseError("invalid numeric constant \"1.0.\"")
      -Stacktrace:
      -[...]
      -
      -julia> parse("1.0.2"; raise = false)
      -:($(Expr(:error, "invalid numeric constant \"1.0.\"")))
      source

      Nullables

      Base.NullableType.
      Nullable(x, hasvalue::Bool=true)

      Wrap value x in an object of type Nullable, which indicates whether a value is present. Nullable(x) yields a non-empty wrapper and Nullable{T}() yields an empty instance of a wrapper that might contain a value of type T.

      Nullable(x, false) yields Nullable{typeof(x)}() with x stored in the result's value field.

      Examples

      julia> Nullable(1)
      -Nullable{Int64}(1)
      -
      -julia> Nullable{Int64}()
      -Nullable{Int64}()
      -
      -julia> Nullable(1, false)
      -Nullable{Int64}()
      -
      -julia> dump(Nullable(1, false))
      -Nullable{Int64}
      -  hasvalue: Bool false
      -  value: Int64 1
      source
      Base.getMethod.
      get(x::Nullable[, y])

      Attempt to access the value of x. Returns the value if it is present; otherwise, returns y if provided, or throws a NullException if not.

      source
      Base.isnullFunction.
      isnull(x)

      Return whether or not x is null for Nullable x; return false for all other x.

      Examples

      julia> x = Nullable(1, false)
      -Nullable{Int64}()
      -
      -julia> isnull(x)
      -true
      -
      -julia> x = Nullable(1, true)
      -Nullable{Int64}(1)
      -
      -julia> isnull(x)
      -false
      -
      -julia> x = 1
      -1
      -
      -julia> isnull(x)
      -false
      source
      Base.unsafe_getFunction.
      unsafe_get(x)

      Return the value of x for Nullable x; return x for all other x.

      This method does not check whether or not x is null before attempting to access the value of x for x::Nullable (hence "unsafe").

      julia> x = Nullable(1)
      -Nullable{Int64}(1)
      -
      -julia> unsafe_get(x)
      -1
      -
      -julia> x = Nullable{String}()
      -Nullable{String}()
      -
      -julia> unsafe_get(x)
      -ERROR: UndefRefError: access to undefined reference
      -Stacktrace:
      - [1] unsafe_get(::Nullable{String}) at ./nullable.jl:125
      -
      -julia> x = 1
      -1
      -
      -julia> unsafe_get(x)
      -1
      source

      System

      Base.runFunction.
      run(command, args...)

      Run a command object, constructed with backticks. Throws an error if anything goes wrong, including the process exiting with a non-zero status.

      source
      Base.spawnFunction.
      spawn(command)

      Run a command object asynchronously, returning the resulting Process object.

      source
      Base.DevNullConstant.
      DevNull

      Used in a stream redirect to discard all data written to it. Essentially equivalent to /dev/null on Unix or NUL on Windows. Usage:

      run(pipeline(`cat test.txt`, DevNull))
      source
      Base.successFunction.
      success(command)

      Run a command object, constructed with backticks, and tell whether it was successful (exited with a code of 0). An exception is raised if the process cannot be started.

      source
      Base.process_runningFunction.
      process_running(p::Process)

      Determine whether a process is currently running.

      source
      Base.process_exitedFunction.
      process_exited(p::Process)

      Determine whether a process has exited.

      source
      Base.killMethod.
      kill(p::Process, signum=SIGTERM)

      Send a signal to a process. The default is to terminate the process.

      source
      Sys.set_process_title(title::AbstractString)

      Set the process title. No-op on some operating systems.

      source
      Sys.get_process_title()

      Get the process title. On some systems, will always return an empty string.

      source
      Base.readandwriteFunction.
      readandwrite(command)

      Starts running a command asynchronously, and returns a tuple (stdout,stdin,process) of the output stream and input stream of the process, and the process object itself.

      source
      Base.ignorestatusFunction.
      ignorestatus(command)

      Mark a command object so that running it will not throw an error if the result code is non-zero.

      source
      Base.detachFunction.
      detach(command)

      Mark a command object so that it will be run in a new process group, allowing it to outlive the julia process, and not have Ctrl-C interrupts passed to it.

      source
      Base.CmdType.
      Cmd(cmd::Cmd; ignorestatus, detach, windows_verbatim, windows_hide, env, dir)

      Construct a new Cmd object, representing an external program and arguments, from cmd, while changing the settings of the optional keyword arguments:

      • ignorestatus::Bool: If true (defaults to false), then the Cmd will not throw an error if the return code is nonzero.

      • detach::Bool: If true (defaults to false), then the Cmd will be run in a new process group, allowing it to outlive the julia process and not have Ctrl-C passed to it.

      • windows_verbatim::Bool: If true (defaults to false), then on Windows the Cmd will send a command-line string to the process with no quoting or escaping of arguments, even arguments containing spaces. (On Windows, arguments are sent to a program as a single "command-line" string, and programs are responsible for parsing it into arguments. By default, empty arguments and arguments with spaces or tabs are quoted with double quotes " in the command line, and \ or " are preceded by backslashes. windows_verbatim=true is useful for launching programs that parse their command line in nonstandard ways.) Has no effect on non-Windows systems.

      • windows_hide::Bool: If true (defaults to false), then on Windows no new console window is displayed when the Cmd is executed. This has no effect if a console is already open or on non-Windows systems.

      • env: Set environment variables to use when running the Cmd. env is either a dictionary mapping strings to strings, an array of strings of the form "var=val", an array or tuple of "var"=>val pairs, or nothing. In order to modify (rather than replace) the existing environment, create env by copy(ENV) and then set env["var"]=val as desired.

      • dir::AbstractString: Specify a working directory for the command (instead of the current directory).

      For any keywords that are not specified, the current settings from cmd are used. Normally, to create a Cmd object in the first place, one uses backticks, e.g.

      Cmd(`echo "Hello world"`, ignorestatus=true, detach=false)
      source
      Base.setenvFunction.
      setenv(command::Cmd, env; dir="")

      Set environment variables to use when running the given command. env is either a dictionary mapping strings to strings, an array of strings of the form "var=val", or zero or more "var"=>val pair arguments. In order to modify (rather than replace) the existing environment, create env by copy(ENV) and then setting env["var"]=val as desired, or use withenv.

      The dir keyword argument can be used to specify a working directory for the command.

      source
      Base.withenvFunction.
      withenv(f::Function, kv::Pair...)

      Execute f() in an environment that is temporarily modified (not replaced as in setenv) by zero or more "var"=>val arguments kv. withenv is generally used via the withenv(kv...) do ... end syntax. A value of nothing can be used to temporarily unset an environment variable (if it is set). When withenv returns, the original environment has been restored.

      source
      Base.pipelineMethod.
      pipeline(from, to, ...)

      Create a pipeline from a data source to a destination. The source and destination can be commands, I/O streams, strings, or results of other pipeline calls. At least one argument must be a command. Strings refer to filenames. When called with more than two arguments, they are chained together from left to right. For example pipeline(a,b,c) is equivalent to pipeline(pipeline(a,b),c). This provides a more concise way to specify multi-stage pipelines.

      Examples:

      run(pipeline(`ls`, `grep xyz`))
      -run(pipeline(`ls`, "out.txt"))
      -run(pipeline("out.txt", `grep xyz`))
      source
      Base.pipelineMethod.
      pipeline(command; stdin, stdout, stderr, append=false)

      Redirect I/O to or from the given command. Keyword arguments specify which of the command's streams should be redirected. append controls whether file output appends to the file. This is a more general version of the 2-argument pipeline function. pipeline(from, to) is equivalent to pipeline(from, stdout=to) when from is a command, and to pipeline(to, stdin=from) when from is another kind of data source.

      Examples:

      run(pipeline(`dothings`, stdout="out.txt", stderr="errs.txt"))
      -run(pipeline(`update`, stdout="log.txt", append=true))
      source
      Base.Libc.gethostnameFunction.
      gethostname() -> AbstractString

      Get the local machine's host name.

      source
      Base.getipaddrFunction.
      getipaddr() -> IPAddr

      Get the IP address of the local machine.

      source
      Base.Libc.getpidFunction.
      getpid() -> Int32

      Get Julia's process ID.

      source
      Base.Libc.timeMethod.
      time()

      Get the system time in seconds since the epoch, with fairly high (typically, microsecond) resolution.

      source
      Base.time_nsFunction.
      time_ns()

      Get the time in nanoseconds. The time corresponding to 0 is undefined, and wraps every 5.8 years.

      source
      Base.ticFunction.
      tic()

      Set a timer to be read by the next call to toc or toq. The macro call @time expr can also be used to time evaluation.

      julia> tic()
      -0x0000c45bc7abac95
      -
      -julia> sleep(0.3)
      -
      -julia> toc()
      -elapsed time: 0.302745944 seconds
      -0.302745944
      source
      Base.tocFunction.
      toc()

      Print and return the time elapsed since the last tic. The macro call @time expr can also be used to time evaluation.

      julia> tic()
      -0x0000c45bc7abac95
      -
      -julia> sleep(0.3)
      -
      -julia> toc()
      -elapsed time: 0.302745944 seconds
      -0.302745944
      source
      Base.toqFunction.
      toq()

      Return, but do not print, the time elapsed since the last tic. The macro calls @timed expr and @elapsed expr also return evaluation time.

      julia> tic()
      -0x0000c46477a9675d
      -
      -julia> sleep(0.3)
      -
      -julia> toq()
      -0.302251004
      source
      Base.@timeMacro.
      @time

      A macro to execute an expression, printing the time it took to execute, the number of allocations, and the total number of bytes its execution caused to be allocated, before returning the value of the expression.

      See also @timev, @timed, @elapsed, and @allocated.

      julia> @time rand(10^6);
      -  0.001525 seconds (7 allocations: 7.630 MiB)
      -
      -julia> @time begin
      -           sleep(0.3)
      -           1+1
      -       end
      -  0.301395 seconds (8 allocations: 336 bytes)
      source
      Base.@timevMacro.
      @timev

      This is a verbose version of the @time macro. It first prints the same information as @time, then any non-zero memory allocation counters, and then returns the value of the expression.

      See also @time, @timed, @elapsed, and @allocated.

      julia> @timev rand(10^6);
      -  0.001006 seconds (7 allocations: 7.630 MiB)
      -elapsed time (ns): 1005567
      -bytes allocated:   8000256
      -pool allocs:       6
      -malloc() calls:    1
      source
      Base.@timedMacro.
      @timed

      A macro to execute an expression, and return the value of the expression, elapsed time, total bytes allocated, garbage collection time, and an object with various memory allocation counters.

      See also @time, @timev, @elapsed, and @allocated.

      julia> val, t, bytes, gctime, memallocs = @timed rand(10^6);
      -
      -julia> t
      -0.006634834
      -
      -julia> bytes
      -8000256
      -
      -julia> gctime
      -0.0055765
      -
      -julia> fieldnames(typeof(memallocs))
      -9-element Array{Symbol,1}:
      - :allocd
      - :malloc
      - :realloc
      - :poolalloc
      - :bigalloc
      - :freecall
      - :total_time
      - :pause
      - :full_sweep
      -
      -julia> memallocs.total_time
      -5576500
      source
      Base.@elapsedMacro.
      @elapsed

      A macro to evaluate an expression, discarding the resulting value, instead returning the number of seconds it took to execute as a floating-point number.

      See also @time, @timev, @timed, and @allocated.

      julia> @elapsed sleep(0.3)
      -0.301391426
      source
      Base.@allocatedMacro.
      @allocated

      A macro to evaluate an expression, discarding the resulting value, instead returning the total number of bytes allocated during evaluation of the expression. Note: the expression is evaluated inside a local function, instead of the current context, in order to eliminate the effects of compilation, however, there still may be some allocations due to JIT compilation. This also makes the results inconsistent with the @time macros, which do not try to adjust for the effects of compilation.

      See also @time, @timev, @timed, and @elapsed.

      julia> @allocated rand(10^6)
      -8000080
      source
      Base.EnvHashType.
      EnvHash() -> EnvHash

      A singleton of this type provides a hash table interface to environment variables.

      source
      Base.ENVConstant.
      ENV

      Reference to the singleton EnvHash, providing a dictionary interface to system environment variables.

      source
      Base.is_unixFunction.
      is_unix([os])

      Predicate for testing if the OS provides a Unix-like interface. See documentation in Handling Operating System Variation.

      source
      Base.is_appleFunction.
      is_apple([os])

      Predicate for testing if the OS is a derivative of Apple Macintosh OS X or Darwin. See documentation in Handling Operating System Variation.

      source
      Base.is_linuxFunction.
      is_linux([os])

      Predicate for testing if the OS is a derivative of Linux. See documentation in Handling Operating System Variation.

      source
      Base.is_bsdFunction.
      is_bsd([os])

      Predicate for testing if the OS is a derivative of BSD. See documentation in Handling Operating System Variation.

      source
      Base.is_windowsFunction.
      is_windows([os])

      Predicate for testing if the OS is a derivative of Microsoft Windows NT. See documentation in Handling Operating System Variation.

      source
      Sys.windows_version()

      Returns the version number for the Windows NT Kernel as a (major, minor) pair, or (0, 0) if this is not running on Windows.

      source
      Base.@staticMacro.
      @static

      Partially evaluates an expression at parse time.

      For example, @static is_windows() ? foo : bar will evaluate is_windows() and insert either foo or bar into the expression. This is useful in cases where a construct would be invalid on other platforms, such as a ccall to a non-existent function. @static if is_apple() foo end and @static foo <&&,||> bar are also valid syntax.

      source

      Errors

      Base.errorFunction.
      error(message::AbstractString)

      Raise an ErrorException with the given message.

      source
      Core.throwFunction.
      throw(e)

      Throw an object as an exception.

      source
      Base.rethrowFunction.
      rethrow([e])

      Throw an object without changing the current exception backtrace. The default argument is the current exception (if called within a catch block).

      source
      Base.backtraceFunction.
      backtrace()

      Get a backtrace object for the current program point.

      source
      Base.catch_backtraceFunction.
      catch_backtrace()

      Get the backtrace of the current exception, for use within catch blocks.

      source
      Base.assertFunction.
      assert(cond)

      Throw an AssertionError if cond is false. Also available as the macro @assert expr.

      source
      Base.@assertMacro.
      @assert cond [text]

      Throw an AssertionError if cond is false. Preferred syntax for writing assertions. Message text is optionally displayed upon assertion failure.

      source
      ArgumentError(msg)

      The parameters to a function call do not match a valid signature. Argument msg is a descriptive error string.

      source
      AssertionError([msg])

      The asserted condition did not evaluate to true. Optional argument msg is a descriptive error string.

      source
      BoundsError([a],[i])

      An indexing operation into an array, a, tried to access an out-of-bounds element, i.

      source
      DimensionMismatch([msg])

      The objects called do not have matching dimensionality. Optional argument msg is a descriptive error string.

      source
      DivideError()

      Integer division was attempted with a denominator value of 0.

      source
      DomainError()

      The arguments to a function or constructor are outside the valid domain.

      source
      Base.EOFErrorType.
      EOFError()

      No more data was available to read from a file or stream.

      source
      ErrorException(msg)

      Generic error type. The error message, in the .msg field, may provide more specific details.

      source
      InexactError()

      Type conversion cannot be done exactly.

      source
      InterruptException()

      The process was stopped by a terminal interrupt (CTRL+C).

      source
      Base.KeyErrorType.
      KeyError(key)

      An indexing operation into an Associative (Dict) or Set like object tried to access or delete a non-existent element.

      source
      Base.LoadErrorType.
      LoadError(file::AbstractString, line::Int, error)

      An error occurred while includeing, requireing, or using a file. The error specifics should be available in the .error field.

      source
      MethodError(f, args)

      A method with the required type signature does not exist in the given generic function. Alternatively, there is no unique most-specific method.

      source
      NullException()

      An attempted access to a Nullable with no defined value.

      source
      OutOfMemoryError()

      An operation allocated too much memory for either the system or the garbage collector to handle properly.

      source
      ReadOnlyMemoryError()

      An operation tried to write to memory that is read-only.

      source
      OverflowError()

      The result of an expression is too large for the specified type and will cause a wraparound.

      source
      Base.ParseErrorType.
      ParseError(msg)

      The expression passed to the parse function could not be interpreted as a valid Julia expression.

      source
      ProcessExitedException()

      After a client Julia process has exited, further attempts to reference the dead child will throw this exception.

      source
      StackOverflowError()

      The function call grew beyond the size of the call stack. This usually happens when a call recurses infinitely.

      source
      SystemError(prefix::AbstractString, [errno::Int32])

      A system call failed with an error code (in the errno global variable).

      source
      Core.TypeErrorType.
      TypeError(func::Symbol, context::AbstractString, expected::Type, got)

      A type assertion failure, or calling an intrinsic function with an incorrect argument type.

      source
      UndefRefError()

      The item or field is not defined for the given object.

      source
      UndefVarError(var::Symbol)

      A symbol in the current scope is not defined.

      source
      Base.InitErrorType.
      InitError(mod::Symbol, error)

      An error occurred when running a module's __init__ function. The actual error thrown is available in the .error field.

      source
      Base.retryFunction.
      retry(f::Function;  delays=ExponentialBackOff(), check=nothing) -> Function

      Returns an anonymous function that calls function f. If an exception arises, f is repeatedly called again, each time check returns true, after waiting the number of seconds specified in delays. check should input delays's current state and the Exception.

      Examples

      retry(f, delays=fill(5.0, 3))
      -retry(f, delays=rand(5:10, 2))
      -retry(f, delays=Base.ExponentialBackOff(n=3, first_delay=5, max_delay=1000))
      -retry(http_get, check=(s,e)->e.status == "503")(url)
      -retry(read, check=(s,e)->isa(e, UVError))(io, 128; all=false)
      source
      ExponentialBackOff(; n=1, first_delay=0.05, max_delay=10.0, factor=5.0, jitter=0.1)

      A Float64 iterator of length n whose elements exponentially increase at a rate in the interval factor * (1 ± jitter). The first element is first_delay and all elements are clamped to max_delay.

      source

      Events

      Base.TimerMethod.
      Timer(callback::Function, delay, repeat=0)

      Create a timer to call the given callback function. The callback is passed one argument, the timer object itself. The callback will be invoked after the specified initial delay, and then repeating with the given repeat interval. If repeat is 0, the timer is only triggered once. Times are in seconds. A timer is stopped and has its resources freed by calling close on it.

      source
      Base.TimerType.
      Timer(delay, repeat=0)

      Create a timer that wakes up tasks waiting for it (by calling wait on the timer object) at a specified interval. Times are in seconds. Waiting tasks are woken with an error when the timer is closed (by close. Use isopen to check whether a timer is still active.

      source
      AsyncCondition()

      Create a async condition that wakes up tasks waiting for it (by calling wait on the object) when notified from C by a call to uv_async_send. Waiting tasks are woken with an error when the object is closed (by close. Use isopen to check whether it is still active.

      source
      AsyncCondition(callback::Function)

      Create a async condition that calls the given callback function. The callback is passed one argument, the async condition object itself.

      source

      Reflection

      Base.module_nameFunction.
      module_name(m::Module) -> Symbol

      Get the name of a Module as a Symbol.

      julia> module_name(Base.LinAlg)
      -:LinAlg
      source
      Base.module_parentFunction.
      module_parent(m::Module) -> Module

      Get a module's enclosing Module. Main is its own parent, as is LastMain after workspace().

      julia> module_parent(Main)
      -Main
      -
      -julia> module_parent(Base.LinAlg.BLAS)
      -Base.LinAlg
      source
      Base.current_moduleFunction.
      current_module() -> Module

      Get the dynamically current Module, which is the Module code is currently being read from. In general, this is not the same as the module containing the call to this function.

      source
      Base.fullnameFunction.
      fullname(m::Module)

      Get the fully-qualified name of a module as a tuple of symbols. For example,

      julia> fullname(Base.Pkg)
      -(:Base, :Pkg)
      -
      -julia> fullname(Main)
      -()
      source
      Base.namesFunction.
      names(x::Module, all::Bool=false, imported::Bool=false)

      Get an array of the names exported by a Module, excluding deprecated names. If all is true, then the list also includes non-exported names defined in the module, deprecated names, and compiler-generated names. If imported is true, then names explicitly imported from other modules are also included.

      As a special case, all names defined in Main are considered "exported", since it is not idiomatic to explicitly export names from Main.

      source
      Core.nfieldsFunction.
      nfields(x::DataType) -> Int

      Get the number of fields of a DataType.

      source
      Base.fieldnamesFunction.
      fieldnames(x::DataType)

      Get an array of the fields of a DataType.

      julia> fieldnames(Hermitian)
      -2-element Array{Symbol,1}:
      - :data
      - :uplo
      source
      Base.fieldnameFunction.
      fieldname(x::DataType, i::Integer)

      Get the name of field i of a DataType.

      julia> fieldname(SparseMatrixCSC,1)
      -:m
      -
      -julia> fieldname(SparseMatrixCSC,5)
      -:nzval
      source
      Base.datatype_moduleFunction.
      Base.datatype_module(t::DataType) -> Module

      Determine the module containing the definition of a DataType.

      source
      Base.datatype_nameFunction.
      Base.datatype_name(t) -> Symbol

      Get the name of a (potentially UnionAll-wrapped) DataType (without its parent module) as a symbol.

      source
      Base.isconstFunction.
      isconst([m::Module], s::Symbol) -> Bool

      Determine whether a global is declared const in a given Module. The default Module argument is current_module().

      source
      Base.function_nameFunction.
      Base.function_name(f::Function) -> Symbol

      Get the name of a generic Function as a symbol, or :anonymous.

      source
      Base.function_module(f::Function) -> Module

      Determine the module containing the (first) definition of a generic function.

      source
      Base.function_module(f::Function, types) -> Module

      Determine the module containing a given definition of a generic function.

      source
      Base.functionlocMethod.
      functionloc(f::Function, types)

      Returns a tuple (filename,line) giving the location of a generic Function definition.

      source
      Base.functionlocMethod.
      functionloc(m::Method)

      Returns a tuple (filename,line) giving the location of a Method definition.

      source
      @functionloc

      Applied to a function or macro call, it evaluates the arguments to the specified call, and returns a tuple (filename,line) giving the location for the method that would be called for those arguments. It calls out to the functionloc function.

      source

      Internals

      Base.gcFunction.
      gc()

      Perform garbage collection. This should not generally be used.

      source
      Base.gc_enableFunction.
      gc_enable(on::Bool)

      Control whether garbage collection is enabled using a boolean argument (true for enabled, false for disabled). Returns previous GC state. Disabling garbage collection should be used only with extreme caution, as it can cause memory use to grow without bound.

      source
      Base.macroexpandFunction.
      macroexpand(x)

      Takes the expression x and returns an equivalent expression with all macros removed (expanded).

      source
      @macroexpand

      Return equivalent expression with all macros removed (expanded).

      There is a subtle difference between @macroexpand and macroexpand in that expansion takes place in different contexts. This is best seen in the following example:

      julia> module M
      -           macro m()
      -               1
      -           end
      -           function f()
      -               (@macroexpand(@m), macroexpand(:(@m)))
      -           end
      -       end
      -M
      -
      -julia> macro m()
      -           2
      -       end
      -@m (macro with 1 method)
      -
      -julia> M.f()
      -(1, 2)

      With @macroexpand the expression expands where @macroexpand appears in the code (module M in the example). With macroexpand the expression expands in the current module where the code was finally called (REPL in the example). Note that when calling macroexpand or @macroexpand directly from the REPL, both of these contexts coincide, hence there is no difference.

      source
      Base.expandFunction.
      expand(x)

      Takes the expression x and returns an equivalent expression in lowered form. See also code_lowered.

      source
      Base.code_loweredFunction.
      code_lowered(f, types)

      Returns an array of lowered ASTs for the methods matching the given generic function and type signature.

      source
      @code_lowered

      Evaluates the arguments to the function or macro call, determines their types, and calls code_lowered on the resulting expression.

      source
      Base.code_typedFunction.
      code_typed(f, types; optimize=true)

      Returns an array of lowered and type-inferred ASTs for the methods matching the given generic function and type signature. The keyword argument optimize controls whether additional optimizations, such as inlining, are also applied.

      source
      Base.@code_typedMacro.
      @code_typed

      Evaluates the arguments to the function or macro call, determines their types, and calls code_typed on the resulting expression.

      source
      Base.code_warntypeFunction.
      code_warntype([io::IO], f, types)

      Prints lowered and type-inferred ASTs for the methods matching the given generic function and type signature to io which defaults to STDOUT. The ASTs are annotated in such a way as to cause "non-leaf" types to be emphasized (if color is available, displayed in red). This serves as a warning of potential type instability. Not all non-leaf types are particularly problematic for performance, so the results need to be used judiciously. See @code_warntype for more information.

      source
      @code_warntype

      Evaluates the arguments to the function or macro call, determines their types, and calls code_warntype on the resulting expression.

      source
      Base.code_llvmFunction.
      code_llvm([io], f, types)

      Prints the LLVM bitcodes generated for running the method matching the given generic function and type signature to io which defaults to STDOUT.

      All metadata and dbg.* calls are removed from the printed bitcode. Use code_llvm_raw for the full IR.

      source
      Base.@code_llvmMacro.
      @code_llvm

      Evaluates the arguments to the function or macro call, determines their types, and calls code_llvm on the resulting expression.

      source
      Base.code_nativeFunction.
      code_native([io], f, types, [syntax])

      Prints the native assembly instructions generated for running the method matching the given generic function and type signature to io which defaults to STDOUT. Switch assembly syntax using syntax symbol parameter set to :att for AT&T syntax or :intel for Intel syntax. Output is AT&T syntax by default.

      source
      @code_native

      Evaluates the arguments to the function or macro call, determines their types, and calls code_native on the resulting expression.

      source
      Base.precompileFunction.
      precompile(f,args::Tuple{Vararg{Any}})

      Compile the given function f for the argument tuple (of types) args, but do not execute it.

      source
      diff --git a/julia-0.6.3/share/doc/julia/html/en/stdlib/c.html b/julia-0.6.3/share/doc/julia/html/en/stdlib/c.html deleted file mode 100644 index 4d9a8fc..0000000 --- a/julia-0.6.3/share/doc/julia/html/en/stdlib/c.html +++ /dev/null @@ -1,18 +0,0 @@ - -C Interface · The Julia Language

      C Interface

      C Interface

      ccallKeyword.
      ccall((symbol, library) or function_pointer, ReturnType, (ArgumentType1, ...), ArgumentValue1, ...)

      Call function in C-exported shared library, specified by (function name, library) tuple, where each component is a string or symbol.

      Note that the argument type tuple must be a literal tuple, and not a tuple-valued variable or expression. Alternatively, ccall may also be used to call a function pointer, such as one returned by dlsym.

      Each ArgumentValue to the ccall will be converted to the corresponding ArgumentType, by automatic insertion of calls to unsafe_convert(ArgumentType, cconvert(ArgumentType, ArgumentValue)). (See also the documentation for each of these functions for further details.) In most cases, this simply results in a call to convert(ArgumentType, ArgumentValue).

      source
      cglobal((symbol, library) [, type=Void])

      Obtain a pointer to a global variable in a C-exported shared library, specified exactly as in ccall. Returns a Ptr{Type}, defaulting to Ptr{Void} if no Type argument is supplied. The values can be read or written by unsafe_load or unsafe_store!, respectively.

      source
      Base.cfunctionFunction.
      cfunction(function::Function, ReturnType::Type, ArgumentTypes::Type)

      Generate C-callable function pointer from Julia function. Type annotation of the return value in the callback function is a must for situations where Julia cannot infer the return type automatically.

      Examples

      julia> function foo(x::Int, y::Int)
      -           return x + y
      -       end
      -
      -julia> cfunction(foo, Int, Tuple{Int,Int})
      -Ptr{Void} @0x000000001b82fcd0
      source
      Base.unsafe_convertFunction.
      unsafe_convert(T,x)

      Convert x to a value of type T

      In cases where convert would need to take a Julia object and turn it into a Ptr, this function should be used to define and perform that conversion.

      Be careful to ensure that a Julia reference to x exists as long as the result of this function will be used. Accordingly, the argument x to this function should never be an expression, only a variable name or field reference. For example, x=a.b.c is acceptable, but x=[a,b,c] is not.

      The unsafe prefix on this function indicates that using the result of this function after the x argument to this function is no longer accessible to the program may cause undefined behavior, including program corruption or segfaults, at any later time.

      source
      Base.cconvertFunction.
      cconvert(T,x)

      Convert x to a value of type T, typically by calling convert(T,x)

      In cases where x cannot be safely converted to T, unlike convert, cconvert may return an object of a type different from T, which however is suitable for unsafe_convert to handle.

      Neither convert nor cconvert should take a Julia object and turn it into a Ptr.

      source
      Base.unsafe_loadFunction.
      unsafe_load(p::Ptr{T}, i::Integer=1)

      Load a value of type T from the address of the ith element (1-indexed) starting at p. This is equivalent to the C expression p[i-1].

      The unsafe prefix on this function indicates that no validation is performed on the pointer p to ensure that it is valid. Incorrect usage may segfault your program or return garbage answers, in the same manner as C.

      source
      Base.unsafe_store!Function.
      unsafe_store!(p::Ptr{T}, x, i::Integer=1)

      Store a value of type T to the address of the ith element (1-indexed) starting at p. This is equivalent to the C expression p[i-1] = x.

      The unsafe prefix on this function indicates that no validation is performed on the pointer p to ensure that it is valid. Incorrect usage may corrupt or segfault your program, in the same manner as C.

      source
      Base.unsafe_copy!Method.
      unsafe_copy!(dest::Ptr{T}, src::Ptr{T}, N)

      Copy N elements from a source pointer to a destination, with no checking. The size of an element is determined by the type of the pointers.

      The unsafe prefix on this function indicates that no validation is performed on the pointers dest and src to ensure that they are valid. Incorrect usage may corrupt or segfault your program, in the same manner as C.

      source
      Base.unsafe_copy!Method.
      unsafe_copy!(dest::Array, do, src::Array, so, N)

      Copy N elements from a source array to a destination, starting at offset so in the source and do in the destination (1-indexed).

      The unsafe prefix on this function indicates that no validation is performed to ensure that N is inbounds on either array. Incorrect usage may corrupt or segfault your program, in the same manner as C.

      source
      Base.copy!Method.
      copy!(dest, src) -> dest

      Copy all elements from collection src to array dest.

      source
      Base.copy!Method.
      copy!(dest, do, src, so, N)

      Copy N elements from collection src starting at offset so, to array dest starting at offset do. Returns dest.

      source
      Base.pointerFunction.
      pointer(array [, index])

      Get the native address of an array or string element. Be careful to ensure that a Julia reference to a exists as long as this pointer will be used. This function is "unsafe" like unsafe_convert.

      Calling Ref(array[, index]) is generally preferable to this function.

      source
      Base.unsafe_wrapMethod.
      unsafe_wrap(Array, pointer::Ptr{T}, dims, own=false)

      Wrap a Julia Array object around the data at the address given by pointer, without making a copy. The pointer element type T determines the array element type. dims is either an integer (for a 1d array) or a tuple of the array dimensions. own optionally specifies whether Julia should take ownership of the memory, calling free on the pointer when the array is no longer referenced.

      This function is labelled "unsafe" because it will crash if pointer is not a valid memory address to data of the requested length.

      source
      pointer_from_objref(x)

      Get the memory address of a Julia object as a Ptr. The existence of the resulting Ptr will not protect the object from garbage collection, so you must ensure that the object remains referenced for the whole time that the Ptr will be used.

      source
      unsafe_pointer_to_objref(p::Ptr)

      Convert a Ptr to an object reference. Assumes the pointer refers to a valid heap-allocated Julia object. If this is not the case, undefined behavior results, hence this function is considered "unsafe" and should be used with care.

      source
      Base.disable_sigintFunction.
      disable_sigint(f::Function)

      Disable Ctrl-C handler during execution of a function on the current task, for calling external code that may call julia code that is not interrupt safe. Intended to be called using do block syntax as follows:

      disable_sigint() do
      -    # interrupt-unsafe code
      -    ...
      -end

      This is not needed on worker threads (Threads.threadid() != 1) since the InterruptException will only be delivered to the master thread. External functions that do not call julia code or julia runtime automatically disable sigint during their execution.

      source
      Base.reenable_sigintFunction.
      reenable_sigint(f::Function)

      Re-enable Ctrl-C handler during execution of a function. Temporarily reverses the effect of disable_sigint.

      source
      Base.systemerrorFunction.
      systemerror(sysfunc, iftrue)

      Raises a SystemError for errno with the descriptive string sysfunc if iftrue is true

      source
      Core.PtrType.
      Ptr{T}

      A memory address referring to data of type T. However, there is no guarantee that the memory is actually valid, or that it actually represents data of the specified type.

      source
      Core.RefType.
      Ref{T}

      An object that safely references data of type T. This type is guaranteed to point to valid, Julia-allocated memory of the correct type. The underlying data is protected from freeing by the garbage collector as long as the Ref itself is referenced.

      When passed as a ccall argument (either as a Ptr or Ref type), a Ref object will be converted to a native pointer to the data it references.

      There is no invalid (NULL) Ref.

      source
      Base.CcharType.
      Cchar

      Equivalent to the native char c-type.

      source
      Base.CucharType.
      Cuchar

      Equivalent to the native unsigned char c-type (UInt8).

      source
      Base.CshortType.
      Cshort

      Equivalent to the native signed short c-type (Int16).

      source
      Base.CushortType.
      Cushort

      Equivalent to the native unsigned short c-type (UInt16).

      source
      Base.CintType.
      Cint

      Equivalent to the native signed int c-type (Int32).

      source
      Base.CuintType.
      Cuint

      Equivalent to the native unsigned int c-type (UInt32).

      source
      Base.ClongType.
      Clong

      Equivalent to the native signed long c-type.

      source
      Base.CulongType.
      Culong

      Equivalent to the native unsigned long c-type.

      source
      Base.ClonglongType.
      Clonglong

      Equivalent to the native signed long long c-type (Int64).

      source
      Base.CulonglongType.
      Culonglong

      Equivalent to the native unsigned long long c-type (UInt64).

      source
      Base.Cintmax_tType.
      Cintmax_t

      Equivalent to the native intmax_t c-type (Int64).

      source
      Base.Cuintmax_tType.
      Cuintmax_t

      Equivalent to the native uintmax_t c-type (UInt64).

      source
      Base.Csize_tType.
      Csize_t

      Equivalent to the native size_t c-type (UInt).

      source
      Base.Cssize_tType.
      Cssize_t

      Equivalent to the native ssize_t c-type.

      source
      Base.Cptrdiff_tType.
      Cptrdiff_t

      Equivalent to the native ptrdiff_t c-type (Int).

      source
      Base.Cwchar_tType.
      Cwchar_t

      Equivalent to the native wchar_t c-type (Int32).

      source
      Base.CfloatType.
      Cfloat

      Equivalent to the native float c-type (Float32).

      source
      Base.CdoubleType.
      Cdouble

      Equivalent to the native double c-type (Float64).

      source

      LLVM Interface

      llvmcall(IR::String, ReturnType, (ArgumentType1, ...), ArgumentValue1, ...)
      -llvmcall((declarations::String, IR::String), ReturnType, (ArgumentType1, ...), ArgumentValue1, ...)

      Call LLVM IR string in the first argument. Similar to an LLVM function define block, arguments are available as consecutive unnamed SSA variables (%0, %1, etc.).

      The optional declarations string contains external functions declarations that are necessary for llvm to compile the IR string. Multiple declarations can be passed in by separating them with line breaks.

      Note that the argument type tuple must be a literal tuple, and not a tuple-valued variable or expression.

      Each ArgumentValue to llvmcall will be converted to the corresponding ArgumentType, by automatic insertion of calls to unsafe_convert(ArgumentType, cconvert(ArgumentType, ArgumentValue)). (see also the documentation for each of these functions for further details). In most cases, this simply results in a call to convert(ArgumentType, ArgumentValue).

      See test/llvmcall.jl for usage examples.

      source
      diff --git a/julia-0.6.3/share/doc/julia/html/en/stdlib/collections.html b/julia-0.6.3/share/doc/julia/html/en/stdlib/collections.html deleted file mode 100644 index f879d5f..0000000 --- a/julia-0.6.3/share/doc/julia/html/en/stdlib/collections.html +++ /dev/null @@ -1,843 +0,0 @@ - -Collections and Data Structures · The Julia Language

      Collections and Data Structures

      Collections and Data Structures

      Iteration

      Sequential iteration is implemented by the methods start(), done(), and next(). The general for loop:

      for i = I   # or  "for i in I"
      -    # body
      -end

      is translated into:

      state = start(I)
      -while !done(I, state)
      -    (i, state) = next(I, state)
      -    # body
      -end

      The state object may be anything, and should be chosen appropriately for each iterable type. See the manual section on the iteration interface for more details about defining a custom iterable type.

      Base.startFunction.
      start(iter) -> state

      Get initial iteration state for an iterable object.

      Examples

      julia> start(1:5)
      -1
      -
      -julia> start([1;2;3])
      -1
      -
      -julia> start([4;2;3])
      -1
      source
      Base.doneFunction.
      done(iter, state) -> Bool

      Test whether we are done iterating.

      Examples

      julia> done(1:5, 3)
      -false
      -
      -julia> done(1:5, 5)
      -false
      -
      -julia> done(1:5, 6)
      -true
      source
      Base.nextFunction.
      next(iter, state) -> item, state

      For a given iterable object and iteration state, return the current item and the next iteration state.

      Examples

      julia> next(1:5, 3)
      -(3, 4)
      -
      -julia> next(1:5, 5)
      -(5, 6)
      source
      Base.iteratorsizeFunction.
      iteratorsize(itertype::Type) -> IteratorSize

      Given the type of an iterator, returns one of the following values:

      • SizeUnknown() if the length (number of elements) cannot be determined in advance.

      • HasLength() if there is a fixed, finite length.

      • HasShape() if there is a known length plus a notion of multidimensional shape (as for an array). In this case the size function is valid for the iterator.

      • IsInfinite() if the iterator yields values forever.

      The default value (for iterators that do not define this function) is HasLength(). This means that most iterators are assumed to implement length.

      This trait is generally used to select between algorithms that pre-allocate space for their result, and algorithms that resize their result incrementally.

      julia> Base.iteratorsize(1:5)
      -Base.HasShape()
      -
      -julia> Base.iteratorsize((2,3))
      -Base.HasLength()
      source
      Base.iteratoreltypeFunction.
      iteratoreltype(itertype::Type) -> IteratorEltype

      Given the type of an iterator, returns one of the following values:

      • EltypeUnknown() if the type of elements yielded by the iterator is not known in advance.

      • HasEltype() if the element type is known, and eltype would return a meaningful value.

      HasEltype() is the default, since iterators are assumed to implement eltype.

      This trait is generally used to select between algorithms that pre-allocate a specific type of result, and algorithms that pick a result type based on the types of yielded values.

      julia> Base.iteratoreltype(1:5)
      -Base.HasEltype()
      source

      Fully implemented by:

      General Collections

      Base.isemptyFunction.
      isempty(collection) -> Bool

      Determine whether a collection is empty (has no elements).

      Examples

      julia> isempty([])
      -true
      -
      -julia> isempty([1 2 3])
      -false
      source
      Base.empty!Function.
      empty!(collection) -> collection

      Remove all elements from a collection.

      julia> A = Dict("a" => 1, "b" => 2)
      -Dict{String,Int64} with 2 entries:
      -  "b" => 2
      -  "a" => 1
      -
      -julia> empty!(A);
      -
      -julia> A
      -Dict{String,Int64} with 0 entries
      source
      Base.lengthMethod.
      length(collection) -> Integer

      For ordered, indexable collections, returns the maximum index i for which getindex(collection, i) is valid. For unordered collections, returns the number of elements.

      Examples

      julia> length(1:5)
      -5
      -
      -julia> length([1; 2; 3; 4])
      -4
      source
      Base.endofFunction.
      endof(collection) -> Integer

      Returns the last index of the collection.

      Example

      julia> endof([1,2,4])
      -3
      source

      Fully implemented by:

      Iterable Collections

      Base.inFunction.
      in(item, collection) -> Bool
      -∈(item,collection) -> Bool
      -∋(collection,item) -> Bool
      -∉(item,collection) -> Bool
      -∌(collection,item) -> Bool

      Determine whether an item is in the given collection, in the sense that it is == to one of the values generated by iterating over the collection. Some collections need a slightly different definition; for example Sets check whether the item isequal to one of the elements. Dicts look for (key,value) pairs, and the key is compared using isequal. To test for the presence of a key in a dictionary, use haskey or k in keys(dict).

      julia> a = 1:3:20
      -1:3:19
      -
      -julia> 4 in a
      -true
      -
      -julia> 5 in a
      -false
      source
      Base.eltypeFunction.
      eltype(type)

      Determine the type of the elements generated by iterating a collection of the given type. For associative collection types, this will be a Pair{KeyType,ValType}. The definition eltype(x) = eltype(typeof(x)) is provided for convenience so that instances can be passed instead of types. However the form that accepts a type argument should be defined for new types.

      julia> eltype(ones(Float32,2,2))
      -Float32
      -
      -julia> eltype(ones(Int8,2,2))
      -Int8
      source
      Base.indexinFunction.
      indexin(a, b)

      Returns a vector containing the highest index in b for each value in a that is a member of b . The output vector contains 0 wherever a is not a member of b.

      Examples

      julia> a = ['a', 'b', 'c', 'b', 'd', 'a'];
      -
      -julia> b = ['a','b','c'];
      -
      -julia> indexin(a,b)
      -6-element Array{Int64,1}:
      - 1
      - 2
      - 3
      - 2
      - 0
      - 1
      -
      -julia> indexin(b,a)
      -3-element Array{Int64,1}:
      - 6
      - 4
      - 3
      source
      Base.findinFunction.
      findin(a, b)

      Returns the indices of elements in collection a that appear in collection b.

      Examples

      julia> a = collect(1:3:15)
      -5-element Array{Int64,1}:
      -  1
      -  4
      -  7
      - 10
      - 13
      -
      -julia> b = collect(2:4:10)
      -3-element Array{Int64,1}:
      -  2
      -  6
      - 10
      -
      -julia> findin(a,b) # 10 is the only common element
      -1-element Array{Int64,1}:
      - 4
      source
      Base.uniqueFunction.
      unique(itr)

      Returns an array containing one value from itr for each unique value, as determined by isequal.

      julia> unique([1; 2; 2; 6])
      -3-element Array{Int64,1}:
      - 1
      - 2
      - 6
      source
      unique(f, itr)

      Returns an array containing one value from itr for each unique value produced by f applied to elements of itr.

      julia> unique(isodd, [1; 2; 2; 6])
      -2-element Array{Int64,1}:
      - 1
      - 2
      source
      unique(itr[, dim])

      Returns an array containing only the unique elements of the iterable itr, in the order that the first of each set of equivalent elements originally appears. If dim is specified, returns unique regions of the array itr along dim.

      julia> A = map(isodd, reshape(collect(1:8), (2,2,2)))
      -2×2×2 Array{Bool,3}:
      -[:, :, 1] =
      -  true   true
      - false  false
      -
      -[:, :, 2] =
      -  true   true
      - false  false
      -
      -julia> unique(A)
      -2-element Array{Bool,1}:
      -  true
      - false
      -
      -julia> unique(A, 2)
      -2×1×2 Array{Bool,3}:
      -[:, :, 1] =
      -  true
      - false
      -
      -[:, :, 2] =
      -  true
      - false
      -
      -julia> unique(A, 3)
      -2×2×1 Array{Bool,3}:
      -[:, :, 1] =
      -  true   true
      - false  false
      source
      Base.alluniqueFunction.
      allunique(itr) -> Bool

      Return true if all values from itr are distinct when compared with isequal.

      julia> a = [1; 2; 3]
      -3-element Array{Int64,1}:
      - 1
      - 2
      - 3
      -
      -julia> allunique([a, a])
      -false
      source
      Base.reduceMethod.
      reduce(op, v0, itr)

      Reduce the given collection ìtr with the given binary operator op. v0 must be a neutral element for op that will be returned for empty collections. It is unspecified whether v0 is used for non-empty collections.

      Reductions for certain commonly-used operators have special implementations which should be used instead: maximum(itr), minimum(itr), sum(itr), prod(itr), any(itr), all(itr).

      The associativity of the reduction is implementation dependent. This means that you can't use non-associative operations like - because it is undefined whether reduce(-,[1,2,3]) should be evaluated as (1-2)-3 or 1-(2-3). Use foldl or foldr instead for guaranteed left or right associativity.

      Some operations accumulate error, and parallelism will also be easier if the reduction can be executed in groups. Future versions of Julia might change the algorithm. Note that the elements are not reordered if you use an ordered collection.

      Examples

      julia> reduce(*, 1, [2; 3; 4])
      -24
      source
      Base.reduceMethod.
      reduce(op, itr)

      Like reduce(op, v0, itr). This cannot be used with empty collections, except for some special cases (e.g. when op is one of +, *, max, min, &, |) when Julia can determine the neutral element of op.

      julia> reduce(*, [2; 3; 4])
      -24
      source
      Base.foldlMethod.
      foldl(op, v0, itr)

      Like reduce, but with guaranteed left associativity. v0 will be used exactly once.

      julia> foldl(-, 1, 2:5)
      --13
      source
      Base.foldlMethod.
      foldl(op, itr)

      Like foldl(op, v0, itr), but using the first element of itr as v0. In general, this cannot be used with empty collections (see reduce(op, itr)).

      julia> foldl(-, 2:5)
      --10
      source
      Base.foldrMethod.
      foldr(op, v0, itr)

      Like reduce, but with guaranteed right associativity. v0 will be used exactly once.

      julia> foldr(-, 1, 2:5)
      --1
      source
      Base.foldrMethod.
      foldr(op, itr)

      Like foldr(op, v0, itr), but using the last element of itr as v0. In general, this cannot be used with empty collections (see reduce(op, itr)).

      julia> foldr(-, 2:5)
      --2
      source
      Base.maximumMethod.
      maximum(itr)

      Returns the largest element in a collection.

      julia> maximum(-20.5:10)
      -9.5
      -
      -julia> maximum([1,2,3])
      -3
      source
      Base.maximumMethod.
      maximum(A, dims)

      Compute the maximum value of an array over the given dimensions. See also the max(a,b) function to take the maximum of two or more arguments, which can be applied elementwise to arrays via max.(a,b).

      julia> A = [1 2; 3 4]
      -2×2 Array{Int64,2}:
      - 1  2
      - 3  4
      -
      -julia> maximum(A, 1)
      -1×2 Array{Int64,2}:
      - 3  4
      -
      -julia> maximum(A, 2)
      -2×1 Array{Int64,2}:
      - 2
      - 4
      source
      Base.maximum!Function.
      maximum!(r, A)

      Compute the maximum value of A over the singleton dimensions of r, and write results to r.

      Examples

      julia> A = [1 2; 3 4]
      -2×2 Array{Int64,2}:
      - 1  2
      - 3  4
      -
      -julia> maximum!([1; 1], A)
      -2-element Array{Int64,1}:
      - 2
      - 4
      -
      -julia> maximum!([1 1], A)
      -1×2 Array{Int64,2}:
      - 3  4
      source
      Base.minimumMethod.
      minimum(itr)

      Returns the smallest element in a collection.

      julia> minimum(-20.5:10)
      --20.5
      -
      -julia> minimum([1,2,3])
      -1
      source
      Base.minimumMethod.
      minimum(A, dims)

      Compute the minimum value of an array over the given dimensions. See also the min(a,b) function to take the minimum of two or more arguments, which can be applied elementwise to arrays via min.(a,b).

      Examples

      julia> A = [1 2; 3 4]
      -2×2 Array{Int64,2}:
      - 1  2
      - 3  4
      -
      -julia> minimum(A, 1)
      -1×2 Array{Int64,2}:
      - 1  2
      -
      -julia> minimum(A, 2)
      -2×1 Array{Int64,2}:
      - 1
      - 3
      source
      Base.minimum!Function.
      minimum!(r, A)

      Compute the minimum value of A over the singleton dimensions of r, and write results to r.

      Examples

      julia> A = [1 2; 3 4]
      -2×2 Array{Int64,2}:
      - 1  2
      - 3  4
      -
      -julia> minimum!([1; 1], A)
      -2-element Array{Int64,1}:
      - 1
      - 3
      -
      -julia> minimum!([1 1], A)
      -1×2 Array{Int64,2}:
      - 1  2
      source
      Base.extremaMethod.
      extrema(itr) -> Tuple

      Compute both the minimum and maximum element in a single pass, and return them as a 2-tuple.

      julia> extrema(2:10)
      -(2, 10)
      -
      -julia> extrema([9,pi,4.5])
      -(3.141592653589793, 9.0)
      source
      Base.extremaMethod.
      extrema(A, dims) -> Array{Tuple}

      Compute the minimum and maximum elements of an array over the given dimensions.

      Example

      julia> A = reshape(collect(1:2:16), (2,2,2))
      -2×2×2 Array{Int64,3}:
      -[:, :, 1] =
      - 1  5
      - 3  7
      -
      -[:, :, 2] =
      -  9  13
      - 11  15
      -
      -julia> extrema(A, (1,2))
      -1×1×2 Array{Tuple{Int64,Int64},3}:
      -[:, :, 1] =
      - (1, 7)
      -
      -[:, :, 2] =
      - (9, 15)
      source
      Base.indmaxFunction.
      indmax(itr) -> Integer

      Returns the index of the maximum element in a collection. If there are multiple maximal elements, then the first one will be returned. NaN values are ignored, unless all elements are NaN.

      The collection must not be empty.

      Examples

      julia> indmax([8,0.1,-9,pi])
      -1
      -
      -julia> indmax([1,7,7,6])
      -2
      -
      -julia> indmax([1,7,7,NaN])
      -2
      source
      Base.indminFunction.
      indmin(itr) -> Integer

      Returns the index of the minimum element in a collection. If there are multiple minimal elements, then the first one will be returned. NaN values are ignored, unless all elements are NaN.

      The collection must not be empty.

      Examples

      julia> indmin([8,0.1,-9,pi])
      -3
      -
      -julia> indmin([7,1,1,6])
      -2
      -
      -julia> indmin([7,1,1,NaN])
      -2
      source
      Base.findmaxMethod.
      findmax(itr) -> (x, index)

      Returns the maximum element of the collection itr and its index. If there are multiple maximal elements, then the first one will be returned. NaN values are ignored, unless all elements are NaN.

      The collection must not be empty.

      Examples

      julia> findmax([8,0.1,-9,pi])
      -(8.0, 1)
      -
      -julia> findmax([1,7,7,6])
      -(7, 2)
      -
      -julia> findmax([1,7,7,NaN])
      -(7.0, 2)
      source
      Base.findmaxMethod.
      findmax(A, region) -> (maxval, index)

      For an array input, returns the value and index of the maximum over the given region.

      Examples

      julia> A = [1 2; 3 4]
      -2×2 Array{Int64,2}:
      - 1  2
      - 3  4
      -
      -julia> findmax(A,1)
      -([3 4], [2 4])
      -
      -julia> findmax(A,2)
      -([2; 4], [3; 4])
      source
      Base.findminMethod.
      findmin(itr) -> (x, index)

      Returns the minimum element of the collection itr and its index. If there are multiple minimal elements, then the first one will be returned. NaN values are ignored, unless all elements are NaN.

      The collection must not be empty.

      Examples

      julia> findmin([8,0.1,-9,pi])
      -(-9.0, 3)
      -
      -julia> findmin([7,1,1,6])
      -(1, 2)
      -
      -julia> findmin([7,1,1,NaN])
      -(1.0, 2)
      source
      Base.findminMethod.
      findmin(A, region) -> (minval, index)

      For an array input, returns the value and index of the minimum over the given region.

      Examples

      julia> A = [1 2; 3 4]
      -2×2 Array{Int64,2}:
      - 1  2
      - 3  4
      -
      -julia> findmin(A, 1)
      -([1 2], [1 3])
      -
      -julia> findmin(A, 2)
      -([1; 3], [1; 2])
      source
      Base.findmax!Function.
      findmax!(rval, rind, A, [init=true]) -> (maxval, index)

      Find the maximum of A and the corresponding linear index along singleton dimensions of rval and rind, and store the results in rval and rind.

      source
      Base.findmin!Function.
      findmin!(rval, rind, A, [init=true]) -> (minval, index)

      Find the minimum of A and the corresponding linear index along singleton dimensions of rval and rind, and store the results in rval and rind.

      source
      Base.sumFunction.
      sum(f, itr)

      Sum the results of calling function f on each element of itr.

      julia> sum(abs2, [2; 3; 4])
      -29
      source
      sum(itr)

      Returns the sum of all elements in a collection.

      julia> sum(1:20)
      -210
      source
      sum(A, dims)

      Sum elements of an array over the given dimensions.

      Examples

      julia> A = [1 2; 3 4]
      -2×2 Array{Int64,2}:
      - 1  2
      - 3  4
      -
      -julia> sum(A, 1)
      -1×2 Array{Int64,2}:
      - 4  6
      -
      -julia> sum(A, 2)
      -2×1 Array{Int64,2}:
      - 3
      - 7
      source
      Base.sum!Function.
      sum!(r, A)

      Sum elements of A over the singleton dimensions of r, and write results to r.

      Examples

      julia> A = [1 2; 3 4]
      -2×2 Array{Int64,2}:
      - 1  2
      - 3  4
      -
      -julia> sum!([1; 1], A)
      -2-element Array{Int64,1}:
      - 3
      - 7
      -
      -julia> sum!([1 1], A)
      -1×2 Array{Int64,2}:
      - 4  6
      source
      Base.prodFunction.
      prod(f, itr)

      Returns the product of f applied to each element of itr.

      julia> prod(abs2, [2; 3; 4])
      -576
      source
      prod(itr)

      Returns the product of all elements of a collection.

      julia> prod(1:20)
      -2432902008176640000
      source
      prod(A, dims)

      Multiply elements of an array over the given dimensions.

      Examples

      julia> A = [1 2; 3 4]
      -2×2 Array{Int64,2}:
      - 1  2
      - 3  4
      -
      -julia> prod(A, 1)
      -1×2 Array{Int64,2}:
      - 3  8
      -
      -julia> prod(A, 2)
      -2×1 Array{Int64,2}:
      -  2
      - 12
      source
      Base.prod!Function.
      prod!(r, A)

      Multiply elements of A over the singleton dimensions of r, and write results to r.

      Examples

      julia> A = [1 2; 3 4]
      -2×2 Array{Int64,2}:
      - 1  2
      - 3  4
      -
      -julia> prod!([1; 1], A)
      -2-element Array{Int64,1}:
      -  2
      - 12
      -
      -julia> prod!([1 1], A)
      -1×2 Array{Int64,2}:
      - 3  8
      source
      Base.anyMethod.
      any(itr) -> Bool

      Test whether any elements of a boolean collection are true, returning true as soon as the first true value in itr is encountered (short-circuiting).

      julia> a = [true,false,false,true]
      -4-element Array{Bool,1}:
      -  true
      - false
      - false
      -  true
      -
      -julia> any(a)
      -true
      -
      -julia> any((println(i); v) for (i, v) in enumerate(a))
      -1
      -true
      source
      Base.anyMethod.
      any(A, dims)

      Test whether any values along the given dimensions of an array are true.

      Examples

      julia> A = [true false; true false]
      -2×2 Array{Bool,2}:
      - true  false
      - true  false
      -
      -julia> any(A, 1)
      -1×2 Array{Bool,2}:
      - true  false
      -
      -julia> any(A, 2)
      -2×1 Array{Bool,2}:
      - true
      - true
      source
      Base.any!Function.
      any!(r, A)

      Test whether any values in A along the singleton dimensions of r are true, and write results to r.

      Examples

      julia> A = [true false; true false]
      -2×2 Array{Bool,2}:
      - true  false
      - true  false
      -
      -julia> any!([1; 1], A)
      -2-element Array{Int64,1}:
      - 1
      - 1
      -
      -julia> any!([1 1], A)
      -1×2 Array{Int64,2}:
      - 1  0
      source
      Base.allMethod.
      all(itr) -> Bool

      Test whether all elements of a boolean collection are true, returning false as soon as the first false value in itr is encountered (short-circuiting).

      julia> a = [true,false,false,true]
      -4-element Array{Bool,1}:
      -  true
      - false
      - false
      -  true
      -
      -julia> all(a)
      -false
      -
      -julia> all((println(i); v) for (i, v) in enumerate(a))
      -1
      -2
      -false
      source
      Base.allMethod.
      all(A, dims)

      Test whether all values along the given dimensions of an array are true.

      Examples

      julia> A = [true false; true true]
      -2×2 Array{Bool,2}:
      - true  false
      - true   true
      -
      -julia> all(A, 1)
      -1×2 Array{Bool,2}:
      - true  false
      -
      -julia> all(A, 2)
      -2×1 Array{Bool,2}:
      - false
      -  true
      source
      Base.all!Function.
      all!(r, A)

      Test whether all values in A along the singleton dimensions of r are true, and write results to r.

      Examples

      julia> A = [true false; true false]
      -2×2 Array{Bool,2}:
      - true  false
      - true  false
      -
      -julia> all!([1; 1], A)
      -2-element Array{Int64,1}:
      - 0
      - 0
      -
      -julia> all!([1 1], A)
      -1×2 Array{Int64,2}:
      - 1  0
      source
      Base.countFunction.
      count(p, itr) -> Integer
      -count(itr) -> Integer

      Count the number of elements in itr for which predicate p returns true. If p is omitted, counts the number of true elements in itr (which should be a collection of boolean values).

      julia> count(i->(4<=i<=6), [2,3,4,5,6])
      -3
      -
      -julia> count([true, false, true, true])
      -3
      source
      Base.anyMethod.
      any(p, itr) -> Bool

      Determine whether predicate p returns true for any elements of itr, returning true as soon as the first item in itr for which p returns true is encountered (short-circuiting).

      julia> any(i->(4<=i<=6), [3,5,7])
      -true
      -
      -julia> any(i -> (println(i); i > 3), 1:10)
      -1
      -2
      -3
      -4
      -true
      source
      Base.allMethod.
      all(p, itr) -> Bool

      Determine whether predicate p returns true for all elements of itr, returning false as soon as the first item in itr for which p returns false is encountered (short-circuiting).

      julia> all(i->(4<=i<=6), [4,5,6])
      -true
      -
      -julia> all(i -> (println(i); i < 3), 1:10)
      -1
      -2
      -3
      -false
      source
      Base.foreachFunction.
      foreach(f, c...) -> Void

      Call function f on each element of iterable c. For multiple iterable arguments, f is called elementwise. foreach should be used instead of map when the results of f are not needed, for example in foreach(println, array).

      Example

      julia> a = 1:3:7;
      -
      -julia> foreach(x -> println(x^2), a)
      -1
      -16
      -49
      source
      Base.mapFunction.
      map(f, c...) -> collection

      Transform collection c by applying f to each element. For multiple collection arguments, apply f elementwise.

      Examples

      julia> map(x -> x * 2, [1, 2, 3])
      -3-element Array{Int64,1}:
      - 2
      - 4
      - 6
      -
      -julia> map(+, [1, 2, 3], [10, 20, 30])
      -3-element Array{Int64,1}:
      - 11
      - 22
      - 33
      source
      map(f, x::Nullable)

      Return f applied to the value of x if it has one, as a Nullable. If x is null, then return a null value of type Nullable{S}. S is guaranteed to be either Union{} or a concrete type. Whichever of these is chosen is an implementation detail, but typically the choice that maximizes performance would be used. If x has a value, then the return type is guaranteed to be of type Nullable{typeof(f(x))}.

      source
      Base.map!Function.
      map!(function, destination, collection...)

      Like map, but stores the result in destination rather than a new collection. destination must be at least as large as the first collection.

      Example

      julia> x = zeros(3);
      -
      -julia> map!(x -> x * 2, x, [1, 2, 3]);
      -
      -julia> x
      -3-element Array{Float64,1}:
      - 2.0
      - 4.0
      - 6.0
      source
      Base.mapreduceMethod.
      mapreduce(f, op, v0, itr)

      Apply function f to each element in itr, and then reduce the result using the binary function op. v0 must be a neutral element for op that will be returned for empty collections. It is unspecified whether v0 is used for non-empty collections.

      mapreduce is functionally equivalent to calling reduce(op, v0, map(f, itr)), but will in general execute faster since no intermediate collection needs to be created. See documentation for reduce and map.

      julia> mapreduce(x->x^2, +, [1:3;]) # == 1 + 4 + 9
      -14

      The associativity of the reduction is implementation-dependent. Additionally, some implementations may reuse the return value of f for elements that appear multiple times in itr. Use mapfoldl or mapfoldr instead for guaranteed left or right associativity and invocation of f for every value.

      source
      Base.mapreduceMethod.
      mapreduce(f, op, itr)

      Like mapreduce(f, op, v0, itr). In general, this cannot be used with empty collections (see reduce(op, itr)).

      source
      Base.mapfoldlMethod.
      mapfoldl(f, op, v0, itr)

      Like mapreduce, but with guaranteed left associativity, as in foldl. v0 will be used exactly once.

      source
      Base.mapfoldlMethod.
      mapfoldl(f, op, itr)

      Like mapfoldl(f, op, v0, itr), but using the first element of itr as v0. In general, this cannot be used with empty collections (see reduce(op, itr)).

      source
      Base.mapfoldrMethod.
      mapfoldr(f, op, v0, itr)

      Like mapreduce, but with guaranteed right associativity, as in foldr. v0 will be used exactly once.

      source
      Base.mapfoldrMethod.
      mapfoldr(f, op, itr)

      Like mapfoldr(f, op, v0, itr), but using the first element of itr as v0. In general, this cannot be used with empty collections (see reduce(op, itr)).

      source
      Base.firstFunction.
      first(coll)

      Get the first element of an iterable collection. Returns the start point of a Range even if it is empty.

      julia> first(2:2:10)
      -2
      -
      -julia> first([1; 2; 3; 4])
      -1
      source
      Base.lastFunction.
      last(coll)

      Get the last element of an ordered collection, if it can be computed in O(1) time. This is accomplished by calling endof to get the last index. Returns the end point of a Range even if it is empty.

      julia> last(1:2:10)
      -9
      -
      -julia> last([1; 2; 3; 4])
      -4
      source
      Base.stepFunction.
      step(r)

      Get the step size of a Range object.

      julia> step(1:10)
      -1
      -
      -julia> step(1:2:10)
      -2
      -
      -julia> step(2.5:0.3:10.9)
      -0.3
      -
      -julia> step(linspace(2.5,10.9,85))
      -0.1
      source
      Base.collectMethod.
      collect(collection)

      Return an Array of all items in a collection or iterator. For associative collections, returns Pair{KeyType, ValType}. If the argument is array-like or is an iterator with the HasShape() trait, the result will have the same shape and number of dimensions as the argument.

      Example

      julia> collect(1:2:13)
      -7-element Array{Int64,1}:
      -  1
      -  3
      -  5
      -  7
      -  9
      - 11
      - 13
      source
      Base.collectMethod.
      collect(element_type, collection)

      Return an Array with the given element type of all items in a collection or iterable. The result has the same shape and number of dimensions as collection.

      julia> collect(Float64, 1:2:5)
      -3-element Array{Float64,1}:
      - 1.0
      - 3.0
      - 5.0
      source
      Base.issubsetMethod.
      issubset(a, b)
      -⊆(a,b) -> Bool
      -⊈(a,b) -> Bool
      -⊊(a,b) -> Bool

      Determine whether every element of a is also in b, using in.

      Examples

      julia> issubset([1, 2], [1, 2, 3])
      -true
      -
      -julia> issubset([1, 2, 3], [1, 2])
      -false
      source
      Base.filterFunction.
      filter(function, collection)

      Return a copy of collection, removing elements for which function is false. For associative collections, the function is passed two arguments (key and value).

      Examples

      julia> a = 1:10
      -1:10
      -
      -julia> filter(isodd, a)
      -5-element Array{Int64,1}:
      - 1
      - 3
      - 5
      - 7
      - 9
      -
      -julia> d = Dict(1=>"a", 2=>"b")
      -Dict{Int64,String} with 2 entries:
      -  2 => "b"
      -  1 => "a"
      -
      -julia> filter((x,y)->isodd(x), d)
      -Dict{Int64,String} with 1 entry:
      -  1 => "a"
      source
      filter(p, x::Nullable)

      Return null if either x is null or p(get(x)) is false, and x otherwise.

      source
      Base.filter!Function.
      filter!(function, collection)

      Update collection, removing elements for which function is false. For associative collections, the function is passed two arguments (key and value).

      Example

      julia> filter!(isodd, collect(1:10))
      -5-element Array{Int64,1}:
      - 1
      - 3
      - 5
      - 7
      - 9
      source

      Indexable Collections

      Base.getindexMethod.
      getindex(collection, key...)

      Retrieve the value(s) stored at the given key or index within a collection. The syntax a[i,j,...] is converted by the compiler to getindex(a, i, j, ...).

      Example

      julia> A = Dict("a" => 1, "b" => 2)
      -Dict{String,Int64} with 2 entries:
      -  "b" => 2
      -  "a" => 1
      -
      -julia> getindex(A, "a")
      -1
      source
      Base.setindex!Method.
      setindex!(collection, value, key...)

      Store the given value at the given key or index within a collection. The syntax a[i,j,...] = x is converted by the compiler to (setindex!(a, x, i, j, ...); x).

      source

      Fully implemented by:

      Partially implemented by:

      • Range

      • UnitRange

      • Tuple

      Associative Collections

      Dict is the standard associative collection. Its implementation uses hash() as the hashing function for the key, and isequal() to determine equality. Define these two functions for custom types to override how they are stored in a hash table.

      ObjectIdDict is a special hash table where the keys are always object identities.

      WeakKeyDict is a hash table implementation where the keys are weak references to objects, and thus may be garbage collected even when referenced in a hash table.

      Dicts can be created by passing pair objects constructed with =>() to a Dict constructor: Dict("A"=>1, "B"=>2). This call will attempt to infer type information from the keys and values (i.e. this example creates a Dict{String, Int64}). To explicitly specify types use the syntax Dict{KeyType,ValueType}(...). For example, Dict{String,Int32}("A"=>1, "B"=>2).

      Associative collections may also be created with generators. For example, Dict(i => f(i) for i = 1:10).

      Given a dictionary D, the syntax D[x] returns the value of key x (if it exists) or throws an error, and D[x] = y stores the key-value pair x => y in D (replacing any existing value for the key x). Multiple arguments to D[...] are converted to tuples; for example, the syntax D[x,y] is equivalent to D[(x,y)], i.e. it refers to the value keyed by the tuple (x,y).

      Base.DictType.
      Dict([itr])

      Dict{K,V}() constructs a hash table with keys of type K and values of type V.

      Given a single iterable argument, constructs a Dict whose key-value pairs are taken from 2-tuples (key,value) generated by the argument.

      julia> Dict([("A", 1), ("B", 2)])
      -Dict{String,Int64} with 2 entries:
      -  "B" => 2
      -  "A" => 1

      Alternatively, a sequence of pair arguments may be passed.

      julia> Dict("A"=>1, "B"=>2)
      -Dict{String,Int64} with 2 entries:
      -  "B" => 2
      -  "A" => 1
      source
      ObjectIdDict([itr])

      ObjectIdDict() constructs a hash table where the keys are (always) object identities. Unlike Dict it is not parameterized on its key and value type and thus its eltype is always Pair{Any,Any}.

      See Dict for further help.

      source
      WeakKeyDict([itr])

      WeakKeyDict() constructs a hash table where the keys are weak references to objects, and thus may be garbage collected even when referenced in a hash table.

      See Dict for further help.

      source
      Base.haskeyFunction.
      haskey(collection, key) -> Bool

      Determine whether a collection has a mapping for a given key.

      julia> a = Dict('a'=>2, 'b'=>3)
      -Dict{Char,Int64} with 2 entries:
      -  'b' => 3
      -  'a' => 2
      -
      -julia> haskey(a,'a')
      -true
      -
      -julia> haskey(a,'c')
      -false
      source
      Base.getMethod.
      get(collection, key, default)

      Return the value stored for the given key, or the given default value if no mapping for the key is present.

      Examples

      julia> d = Dict("a"=>1, "b"=>2);
      -
      -julia> get(d, "a", 3)
      -1
      -
      -julia> get(d, "c", 3)
      -3
      source
      Base.getFunction.
      get(f::Function, collection, key)

      Return the value stored for the given key, or if no mapping for the key is present, return f(). Use get! to also store the default value in the dictionary.

      This is intended to be called using do block syntax

      get(dict, key) do
      -    # default value calculated here
      -    time()
      -end
      source
      Base.get!Method.
      get!(collection, key, default)

      Return the value stored for the given key, or if no mapping for the key is present, store key => default, and return default.

      Examples

      julia> d = Dict("a"=>1, "b"=>2, "c"=>3);
      -
      -julia> get!(d, "a", 5)
      -1
      -
      -julia> get!(d, "d", 4)
      -4
      -
      -julia> d
      -Dict{String,Int64} with 4 entries:
      -  "c" => 3
      -  "b" => 2
      -  "a" => 1
      -  "d" => 4
      source
      Base.get!Method.
      get!(f::Function, collection, key)

      Return the value stored for the given key, or if no mapping for the key is present, store key => f(), and return f().

      This is intended to be called using do block syntax:

      get!(dict, key) do
      -    # default value calculated here
      -    time()
      -end
      source
      Base.getkeyFunction.
      getkey(collection, key, default)

      Return the key matching argument key if one exists in collection, otherwise return default.

      julia> a = Dict('a'=>2, 'b'=>3)
      -Dict{Char,Int64} with 2 entries:
      -  'b' => 3
      -  'a' => 2
      -
      -julia> getkey(a,'a',1)
      -'a': ASCII/Unicode U+0061 (category Ll: Letter, lowercase)
      -
      -julia> getkey(a,'d','a')
      -'a': ASCII/Unicode U+0061 (category Ll: Letter, lowercase)
      source
      Base.delete!Function.
      delete!(collection, key)

      Delete the mapping for the given key in a collection, and return the collection.

      Example

      julia> d = Dict("a"=>1, "b"=>2)
      -Dict{String,Int64} with 2 entries:
      -  "b" => 2
      -  "a" => 1
      -
      -julia> delete!(d, "b")
      -Dict{String,Int64} with 1 entry:
      -  "a" => 1
      source
      Base.pop!Method.
      pop!(collection, key[, default])

      Delete and return the mapping for key if it exists in collection, otherwise return default, or throw an error if default is not specified.

      Examples

      julia> d = Dict("a"=>1, "b"=>2, "c"=>3);
      -
      -julia> pop!(d, "a")
      -1
      -
      -julia> pop!(d, "d")
      -ERROR: KeyError: key "d" not found
      -Stacktrace:
      - [1] pop!(::Dict{String,Int64}, ::String) at ./dict.jl:539
      -
      -julia> pop!(d, "e", 4)
      -4
      source
      Base.keysFunction.
      keys(a::Associative)

      Return an iterator over all keys in a collection. collect(keys(a)) returns an array of keys. Since the keys are stored internally in a hash table, the order in which they are returned may vary. But keys(a) and values(a) both iterate a and return the elements in the same order.

      julia> a = Dict('a'=>2, 'b'=>3)
      -Dict{Char,Int64} with 2 entries:
      -  'b' => 3
      -  'a' => 2
      -
      -julia> collect(keys(a))
      -2-element Array{Char,1}:
      - 'b'
      - 'a'
      source
      Base.valuesFunction.
      values(a::Associative)

      Return an iterator over all values in a collection. collect(values(a)) returns an array of values. Since the values are stored internally in a hash table, the order in which they are returned may vary. But keys(a) and values(a) both iterate a and return the elements in the same order.

      julia> a = Dict('a'=>2, 'b'=>3)
      -Dict{Char,Int64} with 2 entries:
      -  'b' => 3
      -  'a' => 2
      -
      -julia> collect(values(a))
      -2-element Array{Int64,1}:
      - 3
      - 2
      source
      Base.mergeFunction.
      merge(d::Associative, others::Associative...)

      Construct a merged collection from the given collections. If necessary, the types of the resulting collection will be promoted to accommodate the types of the merged collections. If the same key is present in another collection, the value for that key will be the value it has in the last collection listed.

      julia> a = Dict("foo" => 0.0, "bar" => 42.0)
      -Dict{String,Float64} with 2 entries:
      -  "bar" => 42.0
      -  "foo" => 0.0
      -
      -julia> b = Dict("baz" => 17, "bar" => 4711)
      -Dict{String,Int64} with 2 entries:
      -  "bar" => 4711
      -  "baz" => 17
      -
      -julia> merge(a, b)
      -Dict{String,Float64} with 3 entries:
      -  "bar" => 4711.0
      -  "baz" => 17.0
      -  "foo" => 0.0
      -
      -julia> merge(b, a)
      -Dict{String,Float64} with 3 entries:
      -  "bar" => 42.0
      -  "baz" => 17.0
      -  "foo" => 0.0
      source
      merge(combine, d::Associative, others::Associative...)

      Construct a merged collection from the given collections. If necessary, the types of the resulting collection will be promoted to accommodate the types of the merged collections. Values with the same key will be combined using the combiner function.

      julia> a = Dict("foo" => 0.0, "bar" => 42.0)
      -Dict{String,Float64} with 2 entries:
      -  "bar" => 42.0
      -  "foo" => 0.0
      -
      -julia> b = Dict("baz" => 17, "bar" => 4711)
      -Dict{String,Int64} with 2 entries:
      -  "bar" => 4711
      -  "baz" => 17
      -
      -julia> merge(+, a, b)
      -Dict{String,Float64} with 3 entries:
      -  "bar" => 4753.0
      -  "baz" => 17.0
      -  "foo" => 0.0
      source
      Base.merge!Function.

      Merge changes into current head

      source

      Internal implementation of merge. Returns true if merge was successful, otherwise false

      source
      merge!(repo::GitRepo; kwargs...) -> Bool

      Perform a git merge on the repository repo, merging commits with diverging history into the current branch. Returns true if the merge succeeded, false if not.

      The keyword arguments are:

      • committish::AbstractString="": Merge the named commit(s) in committish.

      • branch::AbstractString="": Merge the branch branch and all its commits since it diverged from the current branch.

      • fastforward::Bool=false: If fastforward is true, only merge if the merge is a fast-forward (the current branch head is an ancestor of the commits to be merged), otherwise refuse to merge and return false. This is equivalent to the git CLI option --ff-only.

      • merge_opts::MergeOptions=MergeOptions(): merge_opts specifies options for the merge, such as merge strategy in case of conflicts.

      • checkout_opts::CheckoutOptions=CheckoutOptions(): checkout_opts specifies options for the checkout step.

      Equivalent to git merge [--ff-only] [<committish> | <branch>].

      Note

      If you specify a branch, this must be done in reference format, since the string will be turned into a GitReference. For example, if you wanted to merge branch branch_a, you would call merge!(repo, branch="refs/heads/branch_a").

      source
      merge!(d::Associative, others::Associative...)

      Update collection with pairs from the other collections. See also merge.

      julia> d1 = Dict(1 => 2, 3 => 4);
      -
      -julia> d2 = Dict(1 => 4, 4 => 5);
      -
      -julia> merge!(d1, d2);
      -
      -julia> d1
      -Dict{Int64,Int64} with 3 entries:
      -  4 => 5
      -  3 => 4
      -  1 => 4
      source
      merge!(combine, d::Associative, others::Associative...)

      Update collection with pairs from the other collections. Values with the same key will be combined using the combiner function.

      julia> d1 = Dict(1 => 2, 3 => 4);
      -
      -julia> d2 = Dict(1 => 4, 4 => 5);
      -
      -julia> merge!(+, d1, d2);
      -
      -julia> d1
      -Dict{Int64,Int64} with 3 entries:
      -  4 => 5
      -  3 => 4
      -  1 => 6
      -
      -julia> merge!(-, d1, d1);
      -
      -julia> d1
      -Dict{Int64,Int64} with 3 entries:
      -  4 => 0
      -  3 => 0
      -  1 => 0
      source
      Base.sizehint!Function.
      sizehint!(s, n)

      Suggest that collection s reserve capacity for at least n elements. This can improve performance.

      source
      Base.keytypeFunction.
      keytype(type)

      Get the key type of an associative collection type. Behaves similarly to eltype.

      julia> keytype(Dict(Int32(1) => "foo"))
      -Int32
      source
      Base.valtypeFunction.
      valtype(type)

      Get the value type of an associative collection type. Behaves similarly to eltype.

      julia> valtype(Dict(Int32(1) => "foo"))
      -String
      source

      Fully implemented by:

      Partially implemented by:

      Set-Like Collections

      Base.SetType.
      Set([itr])

      Construct a Set of the values generated by the given iterable object, or an empty set. Should be used instead of IntSet for sparse integer sets, or for sets of arbitrary objects.

      source
      Base.IntSetType.
      IntSet([itr])

      Construct a sorted set of positive Ints generated by the given iterable object, or an empty set. Implemented as a bit string, and therefore designed for dense integer sets. Only Ints greater than 0 can be stored. If the set will be sparse (for example holding a few very large integers), use Set instead.

      source
      Base.unionFunction.
      union(s1,s2...)
      -∪(s1,s2...)

      Construct the union of two or more sets. Maintains order with arrays.

      Examples

      julia> union([1, 2], [3, 4])
      -4-element Array{Int64,1}:
      - 1
      - 2
      - 3
      - 4
      -
      -julia> union([1, 2], [2, 4])
      -3-element Array{Int64,1}:
      - 1
      - 2
      - 4
      -
      -julia> union([4, 2], [1, 2])
      -3-element Array{Int64,1}:
      - 4
      - 2
      - 1
      source
      Base.union!Function.
      union!(s, iterable)

      Union each element of iterable into set s in-place.

      source
      Base.intersectFunction.
      intersect(s1,s2...)
      -∩(s1,s2)

      Construct the intersection of two or more sets. Maintains order and multiplicity of the first argument for arrays and ranges.

      source
      Base.setdiffFunction.
      setdiff(a, b)

      Construct the set of elements in a but not b. Maintains order with arrays. Note that both arguments must be collections, and both will be iterated over. In particular, setdiff(set,element) where element is a potential member of set, will not work in general.

      Example

      julia> setdiff([1,2,3],[3,4,5])
      -2-element Array{Int64,1}:
      - 1
      - 2
      source
      Base.setdiff!Function.
      setdiff!(s, iterable)

      Remove each element of iterable from set s in-place.

      source
      Base.symdiffFunction.
      symdiff(a, b, rest...)

      Construct the symmetric difference of elements in the passed in sets or arrays. Maintains order with arrays.

      Example

      julia> symdiff([1,2,3],[3,4,5],[4,5,6])
      -3-element Array{Int64,1}:
      - 1
      - 2
      - 6
      source
      Base.symdiff!Method.
      symdiff!(s, n)

      The set s is destructively modified to toggle the inclusion of integer n.

      source
      Base.symdiff!Method.
      symdiff!(s, itr)

      For each element in itr, destructively toggle its inclusion in set s.

      source
      Base.symdiff!Method.
      symdiff!(s, itr)

      For each element in itr, destructively toggle its inclusion in set s.

      source
      Base.intersect!Function.
      intersect!(s1::IntSet, s2::IntSet)

      Intersects sets s1 and s2 and overwrites the set s1 with the result. If needed, s1 will be expanded to the size of s2.

      source
      Base.issubsetFunction.
      issubset(A, S) -> Bool
      -⊆(A,S) -> Bool

      Return true if A is a subset of or equal to S.

      source

      Fully implemented by:

      Partially implemented by:

      Dequeues

      Base.push!Function.
      push!(collection, items...) -> collection

      Insert one or more items at the end of collection.

      Example

      julia> push!([1, 2, 3], 4, 5, 6)
      -6-element Array{Int64,1}:
      - 1
      - 2
      - 3
      - 4
      - 5
      - 6

      Use append! to add all the elements of another collection to collection. The result of the preceding example is equivalent to append!([1, 2, 3], [4, 5, 6]).

      source
      Base.pop!Method.
      pop!(collection) -> item

      Remove the last item in collection and return it.

      Examples

      julia> A=[1, 2, 3, 4, 5, 6]
      -6-element Array{Int64,1}:
      - 1
      - 2
      - 3
      - 4
      - 5
      - 6
      -
      -julia> pop!(A)
      -6
      -
      -julia> A
      -5-element Array{Int64,1}:
      - 1
      - 2
      - 3
      - 4
      - 5
      source
      Base.unshift!Function.
      unshift!(collection, items...) -> collection

      Insert one or more items at the beginning of collection.

      Example

      julia> unshift!([1, 2, 3, 4], 5, 6)
      -6-element Array{Int64,1}:
      - 5
      - 6
      - 1
      - 2
      - 3
      - 4
      source
      Base.shift!Function.
      shift!(collection) -> item

      Remove the first item from collection.

      Example

      julia> A = [1, 2, 3, 4, 5, 6]
      -6-element Array{Int64,1}:
      - 1
      - 2
      - 3
      - 4
      - 5
      - 6
      -
      -julia> shift!(A)
      -1
      -
      -julia> A
      -5-element Array{Int64,1}:
      - 2
      - 3
      - 4
      - 5
      - 6
      source
      Base.insert!Function.
      insert!(a::Vector, index::Integer, item)

      Insert an item into a at the given index. index is the index of item in the resulting a.

      Example

      julia> insert!([6, 5, 4, 2, 1], 4, 3)
      -6-element Array{Int64,1}:
      - 6
      - 5
      - 4
      - 3
      - 2
      - 1
      source
      Base.deleteat!Function.
      deleteat!(a::Vector, i::Integer)

      Remove the item at the given i and return the modified a. Subsequent items are shifted to fill the resulting gap.

      Example

      julia> deleteat!([6, 5, 4, 3, 2, 1], 2)
      -5-element Array{Int64,1}:
      - 6
      - 4
      - 3
      - 2
      - 1
      source
      deleteat!(a::Vector, inds)

      Remove the items at the indices given by inds, and return the modified a. Subsequent items are shifted to fill the resulting gap.

      inds can be either an iterator or a collection of sorted and unique integer indices, or a boolean vector of the same length as a with true indicating entries to delete.

      Examples

      julia> deleteat!([6, 5, 4, 3, 2, 1], 1:2:5)
      -3-element Array{Int64,1}:
      - 5
      - 3
      - 1
      -
      -julia> deleteat!([6, 5, 4, 3, 2, 1], [true, false, true, false, true, false])
      -3-element Array{Int64,1}:
      - 5
      - 3
      - 1
      -
      -julia> deleteat!([6, 5, 4, 3, 2, 1], (2, 2))
      -ERROR: ArgumentError: indices must be unique and sorted
      -Stacktrace:
      - [1] _deleteat!(::Array{Int64,1}, ::Tuple{Int64,Int64}) at ./array.jl:921
      - [2] deleteat!(::Array{Int64,1}, ::Tuple{Int64,Int64}) at ./array.jl:908
      source
      Base.splice!Function.
      splice!(a::Vector, index::Integer, [replacement]) -> item

      Remove the item at the given index, and return the removed item. Subsequent items are shifted left to fill the resulting gap. If specified, replacement values from an ordered collection will be spliced in place of the removed item.

      Examples

      julia> A = [6, 5, 4, 3, 2, 1]; splice!(A, 5)
      -2
      -
      -julia> A
      -5-element Array{Int64,1}:
      - 6
      - 5
      - 4
      - 3
      - 1
      -
      -julia> splice!(A, 5, -1)
      -1
      -
      -julia> A
      -5-element Array{Int64,1}:
      -  6
      -  5
      -  4
      -  3
      - -1
      -
      -julia> splice!(A, 1, [-1, -2, -3])
      -6
      -
      -julia> A
      -7-element Array{Int64,1}:
      - -1
      - -2
      - -3
      -  5
      -  4
      -  3
      - -1

      To insert replacement before an index n without removing any items, use splice!(collection, n:n-1, replacement).

      source
      splice!(a::Vector, range, [replacement]) -> items

      Remove items in the specified index range, and return a collection containing the removed items. Subsequent items are shifted left to fill the resulting gap. If specified, replacement values from an ordered collection will be spliced in place of the removed items.

      To insert replacement before an index n without removing any items, use splice!(collection, n:n-1, replacement).

      Example

      julia> splice!(A, 4:3, 2)
      -0-element Array{Int64,1}
      -
      -julia> A
      -8-element Array{Int64,1}:
      - -1
      - -2
      - -3
      -  2
      -  5
      -  4
      -  3
      - -1
      source
      Base.resize!Function.
      resize!(a::Vector, n::Integer) -> Vector

      Resize a to contain n elements. If n is smaller than the current collection length, the first n elements will be retained. If n is larger, the new elements are not guaranteed to be initialized.

      Examples

      julia> resize!([6, 5, 4, 3, 2, 1], 3)
      -3-element Array{Int64,1}:
      - 6
      - 5
      - 4
      -
      -julia> a = resize!([6, 5, 4, 3, 2, 1], 8);
      -
      -julia> length(a)
      -8
      -
      -julia> a[1:6]
      -6-element Array{Int64,1}:
      - 6
      - 5
      - 4
      - 3
      - 2
      - 1
      source
      Base.append!Function.
      append!(collection, collection2) -> collection.

      Add the elements of collection2 to the end of collection.

      Examples

      julia> append!([1],[2,3])
      -3-element Array{Int64,1}:
      - 1
      - 2
      - 3
      -
      -julia> append!([1, 2, 3], [4, 5, 6])
      -6-element Array{Int64,1}:
      - 1
      - 2
      - 3
      - 4
      - 5
      - 6

      Use push! to add individual items to collection which are not already themselves in another collection. The result is of the preceding example is equivalent to push!([1, 2, 3], 4, 5, 6).

      source
      Base.prepend!Function.
      prepend!(a::Vector, items) -> collection

      Insert the elements of items to the beginning of a.

      Example

      julia> prepend!([3],[1,2])
      -3-element Array{Int64,1}:
      - 1
      - 2
      - 3
      source

      Fully implemented by:

      • Vector (a.k.a. 1-dimensional Array)

      • BitVector (a.k.a. 1-dimensional BitArray)

      diff --git a/julia-0.6.3/share/doc/julia/html/en/stdlib/constants.html b/julia-0.6.3/share/doc/julia/html/en/stdlib/constants.html deleted file mode 100644 index 445bc52..0000000 --- a/julia-0.6.3/share/doc/julia/html/en/stdlib/constants.html +++ /dev/null @@ -1,9 +0,0 @@ - -Constants · The Julia Language

      Constants

      Constants

      Core.nothingConstant.
      nothing

      The singleton instance of type Void, used by convention when there is no value to return (as in a C void function). Can be converted to an empty Nullable value.

      source
      Base.PROGRAM_FILEConstant.
      PROGRAM_FILE

      A string containing the script name passed to Julia from the command line. Note that the script name remains unchanged from within included files. Alternatively see @__FILE__.

      source
      Base.ARGSConstant.
      ARGS

      An array of the command line arguments passed to Julia, as strings.

      source
      Base.C_NULLConstant.
      C_NULL

      The C null pointer constant, sometimes used when calling external code.

      source
      Base.VERSIONConstant.
      VERSION

      A VersionNumber object describing which version of Julia is in use. For details see Version Number Literals.

      source
      Base.LOAD_PATHConstant.
      LOAD_PATH

      An array of paths as strings or custom loader objects for the require function and using and import statements to consider when loading code. To create a custom loader type, define the type and then add appropriate methods to the Base.load_hook function with the following signature:

      Base.load_hook(loader::Loader, name::String, found::Any)

      The loader argument is the current value in LOAD_PATH, name is the name of the module to load, and found is the path of any previously found code to provide name. If no provider has been found earlier in LOAD_PATH then the value of found will be nothing. Custom loader functionality is experimental and may break or change in Julia 1.0.

      source
      Base.JULIA_HOMEConstant.
      JULIA_HOME

      A string containing the full path to the directory containing the julia executable.

      source
      Core.ANYConstant.
      ANY

      Equivalent to Any for dispatch purposes, but signals the compiler to skip code generation specialization for that field.

      source
      Base.Sys.CPU_CORESConstant.
      Sys.CPU_CORES

      The number of logical CPU cores available in the system.

      See the Hwloc.jl package for extended information, including number of physical cores.

      source
      Base.Sys.WORD_SIZEConstant.
      Sys.WORD_SIZE

      Standard word size on the current machine, in bits.

      source
      Base.Sys.KERNELConstant.
      Sys.KERNEL

      A symbol representing the name of the operating system, as returned by uname of the build configuration.

      source
      Base.Sys.ARCHConstant.
      Sys.ARCH

      A symbol representing the architecture of the build configuration.

      source
      Base.Sys.MACHINEConstant.
      Sys.MACHINE

      A string containing the build triple.

      source

      See also:

      diff --git a/julia-0.6.3/share/doc/julia/html/en/stdlib/dates.html b/julia-0.6.3/share/doc/julia/html/en/stdlib/dates.html deleted file mode 100644 index da40c11..0000000 --- a/julia-0.6.3/share/doc/julia/html/en/stdlib/dates.html +++ /dev/null @@ -1,64 +0,0 @@ - -Dates and Time · The Julia Language

      Dates and Time

      Dates and Time

      Dates and Time Types

      Period
      -Year
      -Month
      -Week
      -Day
      -Hour
      -Minute
      -Second
      -Millisecond
      -Microsecond
      -Nanosecond

      Period types represent discrete, human representations of time.

      source
      CompoundPeriod

      A CompoundPeriod is useful for expressing time periods that are not a fixed multiple of smaller periods. For example, "a year and a day" is not a fixed number of days, but can be expressed using a CompoundPeriod. In fact, a CompoundPeriod is automatically generated by addition of different period types, e.g. Year(1) + Day(1) produces a CompoundPeriod result.

      source
      Instant

      Instant types represent integer-based, machine representations of time as continuous timelines starting from an epoch.

      source
      UTInstant{T}

      The UTInstant represents a machine timeline based on UT time (1 day = one revolution of the earth). The T is a Period parameter that indicates the resolution or precision of the instant.

      source
      TimeType

      TimeType types wrap Instant machine instances to provide human representations of the machine instant. Time, DateTime and Date are subtypes of TimeType.

      source
      DateTime

      DateTime wraps a UTInstant{Millisecond} and interprets it according to the proleptic Gregorian calendar.

      source
      Base.Dates.DateType.
      Date

      Date wraps a UTInstant{Day} and interprets it according to the proleptic Gregorian calendar.

      source
      Base.Dates.TimeType.
      Time

      Time wraps a Nanosecond and represents a specific moment in a 24-hour day.

      source

      Dates Functions

      All Dates functions are defined in the Dates module; note that only the Date, DateTime, and now functions are exported; to use all other Dates functions, you'll need to prefix each function call with an explicit Dates., e.g. Dates.dayofweek(dt). Alternatively, you can write using Base.Dates to bring all exported functions into Main to be used without the Dates. prefix.

      DateTime(y, [m, d, h, mi, s, ms]) -> DateTime

      Construct a DateTime type by parts. Arguments must be convertible to Int64.

      source
      DateTime(periods::Period...) -> DateTime

      Construct a DateTime type by Period type parts. Arguments may be in any order. DateTime parts not provided will default to the value of Dates.default(period).

      source
      DateTime(f::Function, y[, m, d, h, mi, s]; step=Day(1), limit=10000) -> DateTime

      Create a DateTime through the adjuster API. The starting point will be constructed from the provided y, m, d... arguments, and will be adjusted until f::Function returns true. The step size in adjusting can be provided manually through the step keyword. limit provides a limit to the max number of iterations the adjustment API will pursue before throwing an error (in the case that f::Function is never satisfied).

      source
      DateTime(dt::Date) -> DateTime

      Converts a Date to a DateTime. The hour, minute, second, and millisecond parts of the new DateTime are assumed to be zero.

      source
      DateTime(dt::AbstractString, format::AbstractString; locale="english") -> DateTime

      Construct a DateTime by parsing the dt date string following the pattern given in the format string.

      This method creates a DateFormat object each time it is called. If you are parsing many date strings of the same format, consider creating a DateFormat object once and using that as the second argument instead.

      source
      Base.Dates.formatMethod.
      format(dt::TimeType, format::AbstractString; locale="english") -> AbstractString

      Construct a string by using a TimeType object and applying the provided format. The following character codes can be used to construct the format string:

      CodeExamplesComment
      y6Numeric year with a fixed width
      Y1996Numeric year with a minimum width
      m1, 12Numeric month with a minimum width
      uJanMonth name shortened to 3-chars according to the locale
      UJanuaryFull month name according to the locale keyword
      d1, 31Day of the month with a minimum width
      H0, 23Hour (24-hour clock) with a minimum width
      M0, 59Minute with a minimum width
      S0, 59Second with a minimum width
      s000, 500Millisecond with a minimum width of 3
      eMon, TueAbbreviated days of the week
      EMondayFull day of week name

      The number of sequential code characters indicate the width of the code. A format of yyyy-mm specifies that the code y should have a width of four while m a width of two. Codes that yield numeric digits have an associated mode: fixed-width or minimum-width. The fixed-width mode left-pads the value with zeros when it is shorter than the specified width and truncates the value when longer. Minimum-width mode works the same as fixed-width except that it does not truncate values longer than the width.

      When creating a format you can use any non-code characters as a separator. For example to generate the string "1996-01-15T00:00:00" you could use format: "yyyy-mm-ddTHH:MM:SS". Note that if you need to use a code character as a literal you can use the escape character backslash. The string "1996y01m" can be produced with the format "yyyy\ymm\m".

      source
      DateFormat(format::AbstractString, locale="english") -> DateFormat

      Construct a date formatting object that can be used for parsing date strings or formatting a date object as a string. The following character codes can be used to construct the format string:

      CodeMatchesComment
      y1996, 96Returns year of 1996, 0096
      Y1996, 96Returns year of 1996, 0096. Equivalent to y
      m1, 01Matches 1 or 2-digit months
      uJanMatches abbreviated months according to the locale keyword
      UJanuaryMatches full month names according to the locale keyword
      d1, 01Matches 1 or 2-digit days
      H00Matches hours
      M00Matches minutes
      S00Matches seconds
      s.500Matches milliseconds
      eMon, TuesMatches abbreviated days of the week
      EMondayMatches full name days of the week
      yyyymmdd19960101Matches fixed-width year, month, and day

      Characters not listed above are normally treated as delimiters between date and time slots. For example a dt string of "1996-01-15T00:00:00.0" would have a format string like "y-m-dTH:M:S.s". If you need to use a code character as a delimiter you can escape it using backslash. The date "1995y01m" would have the format "y\ym\m".

      Creating a DateFormat object is expensive. Whenever possible, create it once and use it many times or try the dateformat"" string macro. Using this macro creates the DateFormat object once at macro expansion time and reuses it later. see @dateformat_str.

      See DateTime and format for how to use a DateFormat object to parse and write Date strings respectively.

      source
      dateformat"Y-m-d H:M:S"

      Create a DateFormat object. Similar to DateFormat("Y-m-d H:M:S") but creates the DateFormat object once during macro expansion.

      See DateFormat for details about format specifiers.

      source
      DateTime(dt::AbstractString, df::DateFormat) -> DateTime

      Construct a DateTime by parsing the dt date string following the pattern given in the DateFormat object. Similar to DateTime(::AbstractString, ::AbstractString) but more efficient when repeatedly parsing similarly formatted date strings with a pre-created DateFormat object.

      source
      Base.Dates.DateMethod.
      Date(y, [m, d]) -> Date

      Construct a Date type by parts. Arguments must be convertible to Int64.

      source
      Base.Dates.DateMethod.
      Date(period::Period...) -> Date

      Construct a Date type by Period type parts. Arguments may be in any order. Date parts not provided will default to the value of Dates.default(period).

      source
      Base.Dates.DateMethod.
      Date(f::Function, y[, m, d]; step=Day(1), limit=10000) -> Date

      Create a Date through the adjuster API. The starting point will be constructed from the provided y, m, d arguments, and will be adjusted until f::Function returns true. The step size in adjusting can be provided manually through the step keyword. limit provides a limit to the max number of iterations the adjustment API will pursue before throwing an error (given that f::Function is never satisfied).

      source
      Base.Dates.DateMethod.
      Date(dt::DateTime) -> Date

      Converts a DateTime to a Date. The hour, minute, second, and millisecond parts of the DateTime are truncated, so only the year, month and day parts are used in construction.

      source
      Base.Dates.DateMethod.
      Date(dt::AbstractString, format::AbstractString; locale="english") -> Date

      Construct a Date object by parsing a dt date string following the pattern given in the format string. Follows the same conventions as DateTime(::AbstractString, ::AbstractString).

      source
      Base.Dates.DateMethod.
      Date(dt::AbstractString, df::DateFormat) -> Date

      Parse a date from a date string dt using a DateFormat object df.

      source
      Base.Dates.TimeMethod.
      Time(h, [mi, s, ms, us, ns]) -> Time

      Construct a Time type by parts. Arguments must be convertible to Int64.

      source
      Base.Dates.TimeMethod.
      Time(period::TimePeriod...) -> Time

      Construct a Time type by Period type parts. Arguments may be in any order. Time parts not provided will default to the value of Dates.default(period).

      source
      Base.Dates.TimeMethod.
      Time(f::Function, h, mi=0; step::Period=Second(1), limit::Int=10000)
      -Time(f::Function, h, mi, s; step::Period=Millisecond(1), limit::Int=10000)
      -Time(f::Function, h, mi, s, ms; step::Period=Microsecond(1), limit::Int=10000)
      -Time(f::Function, h, mi, s, ms, us; step::Period=Nanosecond(1), limit::Int=10000)

      Create a Time through the adjuster API. The starting point will be constructed from the provided h, mi, s, ms, us arguments, and will be adjusted until f::Function returns true. The step size in adjusting can be provided manually through the step keyword. limit provides a limit to the max number of iterations the adjustment API will pursue before throwing an error (in the case that f::Function is never satisfied). Note that the default step will adjust to allow for greater precision for the given arguments; i.e. if hour, minute, and second arguments are provided, the default step will be Millisecond(1) instead of Second(1).

      source
      Base.Dates.TimeMethod.
      Time(dt::DateTime) -> Time

      Converts a DateTime to a Time. The hour, minute, second, and millisecond parts of the DateTime are used to create the new Time. Microsecond and nanoseconds are zero by default.

      source
      Base.Dates.nowMethod.
      now() -> DateTime

      Returns a DateTime corresponding to the user's system time including the system timezone locale.

      source
      Base.Dates.nowMethod.
      now(::Type{UTC}) -> DateTime

      Returns a DateTime corresponding to the user's system time as UTC/GMT.

      source
      Base.epsFunction.
      eps(::DateTime) -> Millisecond
      -eps(::Date) -> Day
      -eps(::Time) -> Nanosecond

      Returns Millisecond(1) for DateTime values, Day(1) for Date values, and Nanosecond(1) for Time values.

      source

      Accessor Functions

      Base.Dates.yearFunction.
      year(dt::TimeType) -> Int64

      The year of a Date or DateTime as an Int64.

      source
      Base.Dates.monthFunction.
      month(dt::TimeType) -> Int64

      The month of a Date or DateTime as an Int64.

      source
      Base.Dates.weekFunction.
      week(dt::TimeType) -> Int64

      Return the ISO week date of a Date or DateTime as an Int64. Note that the first week of a year is the week that contains the first Thursday of the year which can result in dates prior to January 4th being in the last week of the previous year. For example week(Date(2005,1,1)) is the 53rd week of 2004.

      source
      Base.Dates.dayFunction.
      day(dt::TimeType) -> Int64

      The day of month of a Date or DateTime as an Int64.

      source
      Base.Dates.hourFunction.
      hour(dt::DateTime) -> Int64

      The hour of day of a DateTime as an Int64.

      source
      hour(t::Time) -> Int64

      The hour of a Time as an Int64.

      source
      Base.Dates.minuteFunction.
      minute(dt::DateTime) -> Int64

      The minute of a DateTime as an Int64.

      source
      minute(t::Time) -> Int64

      The minute of a Time as an Int64.

      source
      Base.Dates.secondFunction.
      second(dt::DateTime) -> Int64

      The second of a DateTime as an Int64.

      source
      second(t::Time) -> Int64

      The second of a Time as an Int64.

      source
      millisecond(dt::DateTime) -> Int64

      The millisecond of a DateTime as an Int64.

      source
      millisecond(t::Time) -> Int64

      The millisecond of a Time as an Int64.

      source
      microsecond(t::Time) -> Int64

      The microsecond of a Time as an Int64.

      source
      Base.Dates.nanosecondFunction.
      nanosecond(t::Time) -> Int64

      The nanosecond of a Time as an Int64.

      source
      Base.Dates.YearMethod.
      Year(v)

      Construct a Year object with the given v value. Input must be losslessly convertible to an Int64.

      source
      Base.Dates.MonthMethod.
      Month(v)

      Construct a Month object with the given v value. Input must be losslessly convertible to an Int64.

      source
      Base.Dates.WeekMethod.
      Week(v)

      Construct a Week object with the given v value. Input must be losslessly convertible to an Int64.

      source
      Base.Dates.DayMethod.
      Day(v)

      Construct a Day object with the given v value. Input must be losslessly convertible to an Int64.

      source
      Base.Dates.HourMethod.
      Hour(dt::DateTime) -> Hour

      The hour part of a DateTime as a Hour.

      source
      Base.Dates.MinuteMethod.
      Minute(dt::DateTime) -> Minute

      The minute part of a DateTime as a Minute.

      source
      Base.Dates.SecondMethod.
      Second(dt::DateTime) -> Second

      The second part of a DateTime as a Second.

      source
      Millisecond(dt::DateTime) -> Millisecond

      The millisecond part of a DateTime as a Millisecond.

      source
      Microsecond(dt::Time) -> Microsecond

      The microsecond part of a Time as a Microsecond.

      source
      Nanosecond(dt::Time) -> Nanosecond

      The nanosecond part of a Time as a Nanosecond.

      source
      Base.Dates.yearmonthFunction.
      yearmonth(dt::TimeType) -> (Int64, Int64)

      Simultaneously return the year and month parts of a Date or DateTime.

      source
      Base.Dates.monthdayFunction.
      monthday(dt::TimeType) -> (Int64, Int64)

      Simultaneously return the month and day parts of a Date or DateTime.

      source
      yearmonthday(dt::TimeType) -> (Int64, Int64, Int64)

      Simultaneously return the year, month and day parts of a Date or DateTime.

      source

      Query Functions

      Base.Dates.daynameFunction.
      dayname(dt::TimeType; locale="english") -> AbstractString

      Return the full day name corresponding to the day of the week of the Date or DateTime in the given locale.

      source
      Base.Dates.dayabbrFunction.
      dayabbr(dt::TimeType; locale="english") -> AbstractString

      Return the abbreviated name corresponding to the day of the week of the Date or DateTime in the given locale.

      source
      Base.Dates.dayofweekFunction.
      dayofweek(dt::TimeType) -> Int64

      Returns the day of the week as an Int64 with 1 = Monday, 2 = Tuesday, etc..

      source
      Base.Dates.dayofmonthFunction.
      dayofmonth(dt::TimeType) -> Int64

      The day of month of a Date or DateTime as an Int64.

      source
      dayofweekofmonth(dt::TimeType) -> Int

      For the day of week of dt, returns which number it is in dt's month. So if the day of the week of dt is Monday, then 1 = First Monday of the month, 2 = Second Monday of the month, etc. In the range 1:5.

      source
      daysofweekinmonth(dt::TimeType) -> Int

      For the day of week of dt, returns the total number of that day of the week in dt's month. Returns 4 or 5. Useful in temporal expressions for specifying the last day of a week in a month by including dayofweekofmonth(dt) == daysofweekinmonth(dt) in the adjuster function.

      source
      Base.Dates.monthnameFunction.
      monthname(dt::TimeType; locale="english") -> AbstractString

      Return the full name of the month of the Date or DateTime in the given locale.

      source
      Base.Dates.monthabbrFunction.
      monthabbr(dt::TimeType; locale="english") -> AbstractString

      Return the abbreviated month name of the Date or DateTime in the given locale.

      source
      daysinmonth(dt::TimeType) -> Int

      Returns the number of days in the month of dt. Value will be 28, 29, 30, or 31.

      source
      Base.Dates.isleapyearFunction.
      isleapyear(dt::TimeType) -> Bool

      Returns true if the year of dt is a leap year.

      source
      Base.Dates.dayofyearFunction.
      dayofyear(dt::TimeType) -> Int

      Returns the day of the year for dt with January 1st being day 1.

      source
      Base.Dates.daysinyearFunction.
      daysinyear(dt::TimeType) -> Int

      Returns 366 if the year of dt is a leap year, otherwise returns 365.

      source
      quarterofyear(dt::TimeType) -> Int

      Returns the quarter that dt resides in. Range of value is 1:4.

      source
      dayofquarter(dt::TimeType) -> Int

      Returns the day of the current quarter of dt. Range of value is 1:92.

      source

      Adjuster Functions

      Base.truncMethod.
      trunc(dt::TimeType, ::Type{Period}) -> TimeType

      Truncates the value of dt according to the provided Period type. E.g. if dt is 1996-01-01T12:30:00, then trunc(dt,Day) == 1996-01-01T00:00:00.

      source
      firstdayofweek(dt::TimeType) -> TimeType

      Adjusts dt to the Monday of its week.

      source
      lastdayofweek(dt::TimeType) -> TimeType

      Adjusts dt to the Sunday of its week.

      source
      firstdayofmonth(dt::TimeType) -> TimeType

      Adjusts dt to the first day of its month.

      source
      lastdayofmonth(dt::TimeType) -> TimeType

      Adjusts dt to the last day of its month.

      source
      firstdayofyear(dt::TimeType) -> TimeType

      Adjusts dt to the first day of its year.

      source
      lastdayofyear(dt::TimeType) -> TimeType

      Adjusts dt to the last day of its year.

      source
      firstdayofquarter(dt::TimeType) -> TimeType

      Adjusts dt to the first day of its quarter.

      source
      lastdayofquarter(dt::TimeType) -> TimeType

      Adjusts dt to the last day of its quarter.

      source
      Base.Dates.tonextMethod.
      tonext(dt::TimeType, dow::Int; same::Bool=false) -> TimeType

      Adjusts dt to the next day of week corresponding to dow with 1 = Monday, 2 = Tuesday, etc. Setting same=true allows the current dt to be considered as the next dow, allowing for no adjustment to occur.

      source
      Base.Dates.toprevMethod.
      toprev(dt::TimeType, dow::Int; same::Bool=false) -> TimeType

      Adjusts dt to the previous day of week corresponding to dow with 1 = Monday, 2 = Tuesday, etc. Setting same=true allows the current dt to be considered as the previous dow, allowing for no adjustment to occur.

      source
      Base.Dates.tofirstFunction.
      tofirst(dt::TimeType, dow::Int; of=Month) -> TimeType

      Adjusts dt to the first dow of its month. Alternatively, of=Year will adjust to the first dow of the year.

      source
      Base.Dates.tolastFunction.
      tolast(dt::TimeType, dow::Int; of=Month) -> TimeType

      Adjusts dt to the last dow of its month. Alternatively, of=Year will adjust to the last dow of the year.

      source
      Base.Dates.tonextMethod.
      tonext(func::Function, dt::TimeType; step=Day(1), limit=10000, same=false) -> TimeType

      Adjusts dt by iterating at most limit iterations by step increments until func returns true. func must take a single TimeType argument and return a Bool. same allows dt to be considered in satisfying func.

      source
      Base.Dates.toprevMethod.
      toprev(func::Function, dt::TimeType; step=Day(-1), limit=10000, same=false) -> TimeType

      Adjusts dt by iterating at most limit iterations by step increments until func returns true. func must take a single TimeType argument and return a Bool. same allows dt to be considered in satisfying func.

      source

      Periods

      Base.Dates.PeriodMethod.
      Year(v)
      -Month(v)
      -Week(v)
      -Day(v)
      -Hour(v)
      -Minute(v)
      -Second(v)
      -Millisecond(v)
      -Microsecond(v)
      -Nanosecond(v)

      Construct a Period type with the given v value. Input must be losslessly convertible to an Int64.

      source
      CompoundPeriod(periods) -> CompoundPeriod

      Construct a CompoundPeriod from a Vector of Periods. All Periods of the same type will be added together.

      Examples

      julia> Dates.CompoundPeriod(Dates.Hour(12), Dates.Hour(13))
      -25 hours
      -
      -julia> Dates.CompoundPeriod(Dates.Hour(-1), Dates.Minute(1))
      --1 hour, 1 minute
      -
      -julia> Dates.CompoundPeriod(Dates.Month(1), Dates.Week(-2))
      -1 month, -2 weeks
      -
      -julia> Dates.CompoundPeriod(Dates.Minute(50000))
      -50000 minutes
      source
      Base.Dates.defaultFunction.
      default(p::Period) -> Period

      Returns a sensible "default" value for the input Period by returning T(1) for Year, Month, and Day, and T(0) for Hour, Minute, Second, and Millisecond.

      source

      Rounding Functions

      Date and DateTime values can be rounded to a specified resolution (e.g., 1 month or 15 minutes) with floor, ceil, or round.

      Base.floorMethod.
      floor(dt::TimeType, p::Period) -> TimeType

      Returns the nearest Date or DateTime less than or equal to dt at resolution p.

      For convenience, p may be a type instead of a value: floor(dt, Dates.Hour) is a shortcut for floor(dt, Dates.Hour(1)).

      julia> floor(Date(1985, 8, 16), Dates.Month)
      -1985-08-01
      -
      -julia> floor(DateTime(2013, 2, 13, 0, 31, 20), Dates.Minute(15))
      -2013-02-13T00:30:00
      -
      -julia> floor(DateTime(2016, 8, 6, 12, 0, 0), Dates.Day)
      -2016-08-06T00:00:00
      source
      Base.ceilMethod.
      ceil(dt::TimeType, p::Period) -> TimeType

      Returns the nearest Date or DateTime greater than or equal to dt at resolution p.

      For convenience, p may be a type instead of a value: ceil(dt, Dates.Hour) is a shortcut for ceil(dt, Dates.Hour(1)).

      julia> ceil(Date(1985, 8, 16), Dates.Month)
      -1985-09-01
      -
      -julia> ceil(DateTime(2013, 2, 13, 0, 31, 20), Dates.Minute(15))
      -2013-02-13T00:45:00
      -
      -julia> ceil(DateTime(2016, 8, 6, 12, 0, 0), Dates.Day)
      -2016-08-07T00:00:00
      source
      Base.roundMethod.
      round(dt::TimeType, p::Period, [r::RoundingMode]) -> TimeType

      Returns the Date or DateTime nearest to dt at resolution p. By default (RoundNearestTiesUp), ties (e.g., rounding 9:30 to the nearest hour) will be rounded up.

      For convenience, p may be a type instead of a value: round(dt, Dates.Hour) is a shortcut for round(dt, Dates.Hour(1)).

      julia> round(Date(1985, 8, 16), Dates.Month)
      -1985-08-01
      -
      -julia> round(DateTime(2013, 2, 13, 0, 31, 20), Dates.Minute(15))
      -2013-02-13T00:30:00
      -
      -julia> round(DateTime(2016, 8, 6, 12, 0, 0), Dates.Day)
      -2016-08-07T00:00:00

      Valid rounding modes for round(::TimeType, ::Period, ::RoundingMode) are RoundNearestTiesUp (default), RoundDown (floor), and RoundUp (ceil).

      source

      The following functions are not exported:

      Base.Dates.floorceilFunction.
      floorceil(dt::TimeType, p::Period) -> (TimeType, TimeType)

      Simultaneously return the floor and ceil of a Date or DateTime at resolution p. More efficient than calling both floor and ceil individually.

      source
      epochdays2date(days) -> Date

      Takes the number of days since the rounding epoch (0000-01-01T00:00:00) and returns the corresponding Date.

      source
      epochms2datetime(milliseconds) -> DateTime

      Takes the number of milliseconds since the rounding epoch (0000-01-01T00:00:00) and returns the corresponding DateTime.

      source
      date2epochdays(dt::Date) -> Int64

      Takes the given Date and returns the number of days since the rounding epoch (0000-01-01T00:00:00) as an Int64.

      source
      datetime2epochms(dt::DateTime) -> Int64

      Takes the given DateTime and returns the number of milliseconds since the rounding epoch (0000-01-01T00:00:00) as an Int64.

      source

      Conversion Functions

      Base.Dates.todayFunction.
      today() -> Date

      Returns the date portion of now().

      source
      unix2datetime(x) -> DateTime

      Takes the number of seconds since unix epoch 1970-01-01T00:00:00 and converts to the corresponding DateTime.

      source
      datetime2unix(dt::DateTime) -> Float64

      Takes the given DateTime and returns the number of seconds since the unix epoch 1970-01-01T00:00:00 as a Float64.

      source
      julian2datetime(julian_days) -> DateTime

      Takes the number of Julian calendar days since epoch -4713-11-24T12:00:00 and returns the corresponding DateTime.

      source
      datetime2julian(dt::DateTime) -> Float64

      Takes the given DateTime and returns the number of Julian calendar days since the julian epoch -4713-11-24T12:00:00 as a Float64.

      source
      rata2datetime(days) -> DateTime

      Takes the number of Rata Die days since epoch 0000-12-31T00:00:00 and returns the corresponding DateTime.

      source
      datetime2rata(dt::TimeType) -> Int64

      Returns the number of Rata Die days since epoch from the given Date or DateTime.

      source

      Constants

      Days of the Week:

      VariableAbbr.Value (Int)
      MondayMon1
      TuesdayTue2
      WednesdayWed3
      ThursdayThu4
      FridayFri5
      SaturdaySat6
      SundaySun7

      Months of the Year:

      VariableAbbr.Value (Int)
      JanuaryJan1
      FebruaryFeb2
      MarchMar3
      AprilApr4
      MayMay5
      JuneJun6
      JulyJul7
      AugustAug8
      SeptemberSep9
      OctoberOct10
      NovemberNov11
      DecemberDec12
      diff --git a/julia-0.6.3/share/doc/julia/html/en/stdlib/file.html b/julia-0.6.3/share/doc/julia/html/en/stdlib/file.html deleted file mode 100644 index 6058a44..0000000 --- a/julia-0.6.3/share/doc/julia/html/en/stdlib/file.html +++ /dev/null @@ -1,35 +0,0 @@ - -Filesystem · The Julia Language

      Filesystem

      Filesystem

      Base.Filesystem.pwdFunction.
      pwd() -> AbstractString

      Get the current working directory.

      source
      Base.Filesystem.cdMethod.
      cd(dir::AbstractString=homedir())

      Set the current working directory.

      source
      Base.Filesystem.cdMethod.
      cd(f::Function, dir::AbstractString=homedir())

      Temporarily changes the current working directory and applies function f before returning.

      source
      readdir(dir::AbstractString=".") -> Vector{String}

      Returns the files and directories in the directory dir (or the current working directory if not given).

      source
      walkdir(dir; topdown=true, follow_symlinks=false, onerror=throw)

      The walkdir method returns an iterator that walks the directory tree of a directory. The iterator returns a tuple containing (rootpath, dirs, files). The directory tree can be traversed top-down or bottom-up. If walkdir encounters a SystemError it will rethrow the error by default. A custom error handling function can be provided through onerror keyword argument. onerror is called with a SystemError as argument.

      for (root, dirs, files) in walkdir(".")
      -    println("Directories in $root")
      -    for dir in dirs
      -        println(joinpath(root, dir)) # path to directories
      -    end
      -    println("Files in $root")
      -    for file in files
      -        println(joinpath(root, file)) # path to files
      -    end
      -end
      source
      Base.Filesystem.mkdirFunction.
      mkdir(path::AbstractString, mode::Unsigned=0o777)

      Make a new directory with name path and permissions mode. mode defaults to 0o777, modified by the current file creation mask. This function never creates more than one directory. If the directory already exists, or some intermediate directories do not exist, this function throws an error. See mkpath for a function which creates all required intermediate directories.

      source
      mkpath(path::AbstractString, mode::Unsigned=0o777)

      Create all directories in the given path, with permissions mode. mode defaults to 0o777, modified by the current file creation mask.

      source
      symlink(target::AbstractString, link::AbstractString)

      Creates a symbolic link to target with the name link.

      Note

      This function raises an error under operating systems that do not support soft symbolic links, such as Windows XP.

      source
      readlink(path::AbstractString) -> AbstractString

      Returns the target location a symbolic link path points to.

      source
      Base.Filesystem.chmodFunction.
      chmod(path::AbstractString, mode::Integer; recursive::Bool=false)

      Change the permissions mode of path to mode. Only integer modes (e.g. 0o777) are currently supported. If recursive=true and the path is a directory all permissions in that directory will be recursively changed.

      source
      Base.Filesystem.chownFunction.
      chown(path::AbstractString, owner::Integer, group::Integer=-1)

      Change the owner and/or group of path to owner and/or group. If the value entered for owner or group is -1 the corresponding ID will not change. Only integer owners and groups are currently supported.

      source
      Base.statFunction.
      stat(file)

      Returns a structure whose fields contain information about the file. The fields of the structure are:

      NameDescription
      sizeThe size (in bytes) of the file
      deviceID of the device that contains the file
      inodeThe inode number of the file
      modeThe protection mode of the file
      nlinkThe number of hard links to the file
      uidThe user id of the owner of the file
      gidThe group id of the file owner
      rdevIf this file refers to a device, the ID of the device it refers to
      blksizeThe file-system preferred block size for the file
      blocksThe number of such blocks allocated
      mtimeUnix timestamp of when the file was last modified
      ctimeUnix timestamp of when the file was created
      source
      Base.Filesystem.lstatFunction.
      lstat(file)

      Like stat, but for symbolic links gets the info for the link itself rather than the file it refers to. This function must be called on a file path rather than a file object or a file descriptor.

      source
      Base.Filesystem.ctimeFunction.
      ctime(file)

      Equivalent to stat(file).ctime

      source
      Base.Filesystem.mtimeFunction.
      mtime(file)

      Equivalent to stat(file).mtime.

      source
      filemode(file)

      Equivalent to stat(file).mode

      source
      filesize(path...)

      Equivalent to stat(file).size.

      source
      Base.Filesystem.upermFunction.
      uperm(file)

      Gets the permissions of the owner of the file as a bitfield of

      ValueDescription
      01Execute Permission
      02Write Permission
      04Read Permission

      For allowed arguments, see stat.

      source
      Base.Filesystem.gpermFunction.
      gperm(file)

      Like uperm but gets the permissions of the group owning the file.

      source
      Base.Filesystem.opermFunction.
      operm(file)

      Like uperm but gets the permissions for people who neither own the file nor are a member of the group owning the file

      source
      Base.Filesystem.cpFunction.
      cp(src::AbstractString, dst::AbstractString; remove_destination::Bool=false, follow_symlinks::Bool=false)

      Copy the file, link, or directory from src to dest. remove_destination=true will first remove an existing dst.

      If follow_symlinks=false, and src is a symbolic link, dst will be created as a symbolic link. If follow_symlinks=true and src is a symbolic link, dst will be a copy of the file or directory src refers to.

      source
      Base.downloadFunction.
      download(url::AbstractString, [localfile::AbstractString])

      Download a file from the given url, optionally renaming it to the given local file name. Note that this function relies on the availability of external tools such as curl, wget or fetch to download the file and is provided for convenience. For production use or situations in which more options are needed, please use a package that provides the desired functionality instead.

      source
      Base.Filesystem.mvFunction.
      mv(src::AbstractString, dst::AbstractString; remove_destination::Bool=false)

      Move the file, link, or directory from src to dst. remove_destination=true will first remove an existing dst.

      source
      Base.Filesystem.rmFunction.
      rm(path::AbstractString; force::Bool=false, recursive::Bool=false)

      Delete the file, link, or empty directory at the given path. If force=true is passed, a non-existing path is not treated as error. If recursive=true is passed and the path is a directory, then all contents are removed recursively.

      source
      Base.Filesystem.touchFunction.
      touch(path::AbstractString)

      Update the last-modified timestamp on a file to the current time.

      source
      tempname()

      Generate a unique temporary file path.

      source
      tempdir()

      Obtain the path of a temporary directory (possibly shared with other processes).

      source
      mktemp(parent=tempdir())

      Returns (path, io), where path is the path of a new temporary file in parent and io is an open file object for this path.

      source
      mktemp(f::Function, parent=tempdir())

      Apply the function f to the result of mktemp(parent) and remove the temporary file upon completion.

      source
      mktempdir(parent=tempdir())

      Create a temporary directory in the parent directory and return its path. If parent does not exist, throw an error.

      source
      mktempdir(f::Function, parent=tempdir())

      Apply the function f to the result of mktempdir(parent) and remove the temporary directory upon completion.

      source
      isblockdev(path) -> Bool

      Returns true if path is a block device, false otherwise.

      source
      ischardev(path) -> Bool

      Returns true if path is a character device, false otherwise.

      source
      Base.Filesystem.isdirFunction.
      isdir(path) -> Bool

      Returns true if path is a directory, false otherwise.

      source
      isfifo(path) -> Bool

      Returns true if path is a FIFO, false otherwise.

      source
      isfile(path) -> Bool

      Returns true if path is a regular file, false otherwise.

      source
      islink(path) -> Bool

      Returns true if path is a symbolic link, false otherwise.

      source
      ismount(path) -> Bool

      Returns true if path is a mount point, false otherwise.

      source
      ispath(path) -> Bool

      Returns true if path is a valid filesystem path, false otherwise.

      source
      issetgid(path) -> Bool

      Returns true if path has the setgid flag set, false otherwise.

      source
      issetuid(path) -> Bool

      Returns true if path has the setuid flag set, false otherwise.

      source
      issocket(path) -> Bool

      Returns true if path is a socket, false otherwise.

      source
      issticky(path) -> Bool

      Returns true if path has the sticky bit set, false otherwise.

      source
      homedir() -> AbstractString

      Return the current user's home directory.

      Note

      homedir determines the home directory via libuv's uv_os_homedir. For details (for example on how to specify the home directory via environment variables), see the uv_os_homedir documentation.

      source
      dirname(path::AbstractString) -> AbstractString

      Get the directory part of a path.

      julia> dirname("/home/myuser")
      -"/home"

      See also: basename

      source
      basename(path::AbstractString) -> AbstractString

      Get the file name part of a path.

      julia> basename("/home/myuser/example.jl")
      -"example.jl"

      See also: dirname

      source
      Base.@__FILE__Macro.
      @__FILE__ -> AbstractString

      @__FILE__ expands to a string with the absolute file path of the file containing the macro. Returns nothing if run from a REPL or an empty string if evaluated by julia -e <expr>. Alternatively see PROGRAM_FILE.

      source
      Base.@__DIR__Macro.
      @__DIR__ -> AbstractString

      @__DIR__ expands to a string with the directory part of the absolute path of the file containing the macro. Returns nothing if run from a REPL or an empty string if evaluated by julia -e <expr>.

      source
      @__LINE__Macro.
      @__LINE__ -> Int

      @__LINE__ expands to the line number of the call-site.

      source
      isabspath(path::AbstractString) -> Bool

      Determines whether a path is absolute (begins at the root directory).

      julia> isabspath("/home")
      -true
      -
      -julia> isabspath("home")
      -false
      source
      isdirpath(path::AbstractString) -> Bool

      Determines whether a path refers to a directory (for example, ends with a path separator).

      julia> isdirpath("/home")
      -false
      -
      -julia> isdirpath("/home/")
      -true
      source
      joinpath(parts...) -> AbstractString

      Join path components into a full path. If some argument is an absolute path, then prior components are dropped.

      julia> joinpath("/home/myuser","example.jl")
      -"/home/myuser/example.jl"
      source
      abspath(path::AbstractString) -> AbstractString

      Convert a path to an absolute path by adding the current directory if necessary.

      source
      abspath(path::AbstractString, paths::AbstractString...) -> AbstractString

      Convert a set of paths to an absolute path by joining them together and adding the current directory if necessary. Equivalent to abspath(joinpath(path, paths...)).

      source
      normpath(path::AbstractString) -> AbstractString

      Normalize a path, removing "." and ".." entries.

      julia> normpath("/home/myuser/../example.jl")
      -"/home/example.jl"
      source
      realpath(path::AbstractString) -> AbstractString

      Canonicalize a path by expanding symbolic links and removing "." and ".." entries.

      source
      relpath(path::AbstractString, startpath::AbstractString = ".") -> AbstractString

      Return a relative filepath to path either from the current directory or from an optional start directory. This is a path computation: the filesystem is not accessed to confirm the existence or nature of path or startpath.

      source
      expanduser(path::AbstractString) -> AbstractString

      On Unix systems, replace a tilde character at the start of a path with the current user's home directory.

      source
      splitdir(path::AbstractString) -> (AbstractString, AbstractString)

      Split a path into a tuple of the directory name and file name.

      julia> splitdir("/home/myuser")
      -("/home", "myuser")
      source
      splitdrive(path::AbstractString) -> (AbstractString, AbstractString)

      On Windows, split a path into the drive letter part and the path part. On Unix systems, the first component is always the empty string.

      source
      splitext(path::AbstractString) -> (AbstractString, AbstractString)

      If the last component of a path contains a dot, split the path into everything before the dot and everything including and after the dot. Otherwise, return a tuple of the argument unmodified and the empty string.

      julia> splitext("/home/myuser/example.jl")
      -("/home/myuser/example", ".jl")
      -
      -julia> splitext("/home/myuser/example")
      -("/home/myuser/example", "")
      source
      diff --git a/julia-0.6.3/share/doc/julia/html/en/stdlib/io-network.html b/julia-0.6.3/share/doc/julia/html/en/stdlib/io-network.html deleted file mode 100644 index a3b2f13..0000000 --- a/julia-0.6.3/share/doc/julia/html/en/stdlib/io-network.html +++ /dev/null @@ -1,149 +0,0 @@ - -I/O and Network · The Julia Language

      I/O and Network

      I/O and Network

      General I/O

      Base.STDOUTConstant.
      STDOUT

      Global variable referring to the standard out stream.

      source
      Base.STDERRConstant.
      STDERR

      Global variable referring to the standard error stream.

      source
      Base.STDINConstant.
      STDIN

      Global variable referring to the standard input stream.

      source
      Base.openFunction.
      open(filename::AbstractString, [read::Bool, write::Bool, create::Bool, truncate::Bool, append::Bool]) -> IOStream

      Open a file in a mode specified by five boolean arguments. The default is to open files for reading only. Returns a stream for accessing the file.

      source
      open(filename::AbstractString, [mode::AbstractString]) -> IOStream

      Alternate syntax for open, where a string-based mode specifier is used instead of the five booleans. The values of mode correspond to those from fopen(3) or Perl open, and are equivalent to setting the following boolean groups:

      ModeDescription
      rread
      r+read, write
      wwrite, create, truncate
      w+read, write, create, truncate
      awrite, create, append
      a+read, write, create, append
      source
      open(f::Function, args...)

      Apply the function f to the result of open(args...) and close the resulting file descriptor upon completion.

      Example: open(readstring, "file.txt")

      source
      open(command, mode::AbstractString="r", stdio=DevNull)

      Start running command asynchronously, and return a tuple (stream,process). If mode is "r", then stream reads from the process's standard output and stdio optionally specifies the process's standard input stream. If mode is "w", then stream writes to the process's standard input and stdio optionally specifies the process's standard output stream.

      source
      open(f::Function, command, mode::AbstractString="r", stdio=DevNull)

      Similar to open(command, mode, stdio), but calls f(stream) on the resulting read or write stream, then closes the stream and waits for the process to complete. Returns the value returned by f.

      source
      Base.IOBufferType.
      IOBuffer([data,],[readable::Bool=true, writable::Bool=true, [maxsize::Int=typemax(Int)]])

      Create an IOBuffer, which may optionally operate on a pre-existing array. If the readable/writable arguments are given, they restrict whether or not the buffer may be read from or written to respectively. The last argument optionally specifies a size beyond which the buffer may not be grown.

      source
      IOBuffer() -> IOBuffer

      Create an in-memory I/O stream.

      source
      IOBuffer(size::Int)

      Create a fixed size IOBuffer. The buffer will not grow dynamically.

      source
      IOBuffer(string::String)

      Create a read-only IOBuffer on the data underlying the given string.

      julia> io = IOBuffer("Haho");
      -
      -julia> String(take!(io))
      -"Haho"
      -
      -julia> String(take!(io))
      -"Haho"
      source
      Base.take!Method.
      take!(b::IOBuffer)

      Obtain the contents of an IOBuffer as an array, without copying. Afterwards, the IOBuffer is reset to its initial state.

      source
      Base.fdioFunction.
      fdio([name::AbstractString, ]fd::Integer[, own::Bool=false]) -> IOStream

      Create an IOStream object from an integer file descriptor. If own is true, closing this object will close the underlying descriptor. By default, an IOStream is closed when it is garbage collected. name allows you to associate the descriptor with a named file.

      source
      Base.flushFunction.
      flush(stream)

      Commit all currently buffered writes to the given stream.

      source
      Base.closeFunction.
      close(stream)

      Close an I/O stream. Performs a flush first.

      source
      Base.writeFunction.
      write(stream::IO, x)
      -write(filename::AbstractString, x)

      Write the canonical binary representation of a value to the given I/O stream or file. Returns the number of bytes written into the stream.

      You can write multiple values with the same write call. i.e. the following are equivalent:

      write(stream, x, y...)
      -write(stream, x) + write(stream, y...)
      source
      Base.readFunction.
      read(filename::AbstractString, args...)

      Open a file and read its contents. args is passed to read: this is equivalent to open(io->read(io, args...), filename).

      source
      read(stream::IO, T, dims)

      Read a series of values of type T from stream, in canonical binary representation. dims is either a tuple or a series of integer arguments specifying the size of the Array{T} to return.

      source
      read(s::IO, nb=typemax(Int))

      Read at most nb bytes from s, returning a Vector{UInt8} of the bytes read.

      source
      read(s::IOStream, nb::Integer; all=true)

      Read at most nb bytes from s, returning a Vector{UInt8} of the bytes read.

      If all is true (the default), this function will block repeatedly trying to read all requested bytes, until an error or end-of-file occurs. If all is false, at most one read call is performed, and the amount of data returned is device-dependent. Note that not all stream types support the all option.

      source
      read(stream::IO, T)

      Read a single value of type T from stream, in canonical binary representation.

      source
      Base.read!Function.
      read!(stream::IO, array::Union{Array, BitArray})
      -read!(filename::AbstractString, array::Union{Array, BitArray})

      Read binary data from an I/O stream or file, filling in array.

      source
      Base.readbytes!Function.
      readbytes!(stream::IO, b::AbstractVector{UInt8}, nb=length(b))

      Read at most nb bytes from stream into b, returning the number of bytes read. The size of b will be increased if needed (i.e. if nb is greater than length(b) and enough bytes could be read), but it will never be decreased.

      source
      readbytes!(stream::IOStream, b::AbstractVector{UInt8}, nb=length(b); all::Bool=true)

      Read at most nb bytes from stream into b, returning the number of bytes read. The size of b will be increased if needed (i.e. if nb is greater than length(b) and enough bytes could be read), but it will never be decreased.

      See read for a description of the all option.

      source
      Base.unsafe_readFunction.
      unsafe_read(io::IO, ref, nbytes::UInt)

      Copy nbytes from the IO stream object into ref (converted to a pointer).

      It is recommended that subtypes T<:IO override the following method signature to provide more efficient implementations: unsafe_read(s::T, p::Ptr{UInt8}, n::UInt)

      source
      Base.unsafe_writeFunction.
      unsafe_write(io::IO, ref, nbytes::UInt)

      Copy nbytes from ref (converted to a pointer) into the IO object.

      It is recommended that subtypes T<:IO override the following method signature to provide more efficient implementations: unsafe_write(s::T, p::Ptr{UInt8}, n::UInt)

      source
      Base.positionFunction.
      position(s)

      Get the current position of a stream.

      source
      Base.seekFunction.
      seek(s, pos)

      Seek a stream to the given position.

      source
      Base.seekstartFunction.
      seekstart(s)

      Seek a stream to its beginning.

      source
      Base.seekendFunction.
      seekend(s)

      Seek a stream to its end.

      source
      Base.skipFunction.
      skip(s, offset)

      Seek a stream relative to the current position.

      source
      Base.markFunction.
      mark(s)

      Add a mark at the current position of stream s. Returns the marked position.

      See also unmark, reset, ismarked.

      source
      Base.unmarkFunction.
      unmark(s)

      Remove a mark from stream s. Returns true if the stream was marked, false otherwise.

      See also mark, reset, ismarked.

      source
      Base.resetFunction.
      reset(s)

      Reset a stream s to a previously marked position, and remove the mark. Returns the previously marked position. Throws an error if the stream is not marked.

      See also mark, unmark, ismarked.

      source
      Base.ismarkedFunction.
      ismarked(s)

      Returns true if stream s is marked.

      See also mark, unmark, reset.

      source
      Base.eofFunction.
      eof(stream) -> Bool

      Tests whether an I/O stream is at end-of-file. If the stream is not yet exhausted, this function will block to wait for more data if necessary, and then return false. Therefore it is always safe to read one byte after seeing eof return false. eof will return false as long as buffered data is still available, even if the remote end of a connection is closed.

      source
      Base.isreadonlyFunction.
      isreadonly(stream) -> Bool

      Determine whether a stream is read-only.

      source
      Base.iswritableFunction.
      iswritable(io) -> Bool

      Returns true if the specified IO object is writable (if that can be determined).

      source
      Base.isreadableFunction.
      isreadable(io) -> Bool

      Returns true if the specified IO object is readable (if that can be determined).

      source
      Base.isopenFunction.
      isopen(object) -> Bool

      Determine whether an object - such as a stream, timer, or mmap – is not yet closed. Once an object is closed, it will never produce a new event. However, a closed stream may still have data to read in its buffer, use eof to check for the ability to read data. Use poll_fd to be notified when a stream might be writable or readable.

      source
      serialize(stream, value)

      Write an arbitrary value to a stream in an opaque format, such that it can be read back by deserialize. The read-back value will be as identical as possible to the original. In general, this process will not work if the reading and writing are done by different versions of Julia, or an instance of Julia with a different system image. Ptr values are serialized as all-zero bit patterns (NULL).

      source
      deserialize(stream)

      Read a value written by serialize. deserialize assumes the binary data read from stream is correct and has been serialized by a compatible implementation of serialize. It has been designed with simplicity and performance as a goal and does not validate the data read. Malformed data can result in process termination. The caller has to ensure the integrity and correctness of data read from stream.

      source
      print_shortest(io, x)

      Print the shortest possible representation, with the minimum number of consecutive non-zero digits, of number x, ensuring that it would parse to the exact same number.

      source
      Base.fdFunction.
      fd(stream)

      Returns the file descriptor backing the stream or file. Note that this function only applies to synchronous File's and IOStream's not to any of the asynchronous streams.

      source
      Base.redirect_stdoutFunction.
      redirect_stdout([stream]) -> (rd, wr)

      Create a pipe to which all C and Julia level STDOUT output will be redirected. Returns a tuple (rd, wr) representing the pipe ends. Data written to STDOUT may now be read from the rd end of the pipe. The wr end is given for convenience in case the old STDOUT object was cached by the user and needs to be replaced elsewhere.

      Note

      stream must be a TTY, a Pipe, or a TCPSocket.

      source
      redirect_stdout(f::Function, stream)

      Run the function f while redirecting STDOUT to stream. Upon completion, STDOUT is restored to its prior setting.

      Note

      stream must be a TTY, a Pipe, or a TCPSocket.

      source
      Base.redirect_stderrFunction.
      redirect_stderr([stream]) -> (rd, wr)

      Like redirect_stdout, but for STDERR.

      Note

      stream must be a TTY, a Pipe, or a TCPSocket.

      source
      redirect_stderr(f::Function, stream)

      Run the function f while redirecting STDERR to stream. Upon completion, STDERR is restored to its prior setting.

      Note

      stream must be a TTY, a Pipe, or a TCPSocket.

      source
      Base.redirect_stdinFunction.
      redirect_stdin([stream]) -> (rd, wr)

      Like redirect_stdout, but for STDIN. Note that the order of the return tuple is still (rd, wr), i.e. data to be read from STDIN may be written to wr.

      Note

      stream must be a TTY, a Pipe, or a TCPSocket.

      source
      redirect_stdin(f::Function, stream)

      Run the function f while redirecting STDIN to stream. Upon completion, STDIN is restored to its prior setting.

      Note

      stream must be a TTY, a Pipe, or a TCPSocket.

      source
      Base.readchompFunction.
      readchomp(x)

      Read the entirety of x as a string and remove a single trailing newline. Equivalent to chomp!(readstring(x)).

      source
      Base.truncateFunction.
      truncate(file,n)

      Resize the file or buffer given by the first argument to exactly n bytes, filling previously unallocated space with '\0' if the file or buffer is grown.

      source
      Base.skipcharsFunction.
      skipchars(stream, predicate; linecomment::Char)

      Advance the stream until before the first character for which predicate returns false. For example skipchars(stream, isspace) will skip all whitespace. If keyword argument linecomment is specified, characters from that character through the end of a line will also be skipped.

      source
      countlines(io::IO, eol::Char='\n')

      Read io until the end of the stream/file and count the number of lines. To specify a file pass the filename as the first argument. EOL markers other than '\n' are supported by passing them as the second argument.

      source
      Base.PipeBufferFunction.
      PipeBuffer(data::Vector{UInt8}=UInt8[],[maxsize::Int=typemax(Int)])

      An IOBuffer that allows reading and performs writes by appending. Seeking and truncating are not supported. See IOBuffer for the available constructors. If data is given, creates a PipeBuffer to operate on a data vector, optionally specifying a size beyond which the underlying Array may not be grown.

      source
      Base.readavailableFunction.
      readavailable(stream)

      Read all available data on the stream, blocking the task only if no data is available. The result is a Vector{UInt8,1}.

      source
      Base.IOContextType.
      IOContext

      IOContext provides a mechanism for passing output configuration settings among show methods.

      In short, it is an immutable dictionary that is a subclass of IO. It supports standard dictionary operations such as getindex, and can also be used as an I/O stream.

      source
      Base.IOContextMethod.
      IOContext(io::IO, KV::Pair)

      Create an IOContext that wraps a given stream, adding the specified key=>value pair to the properties of that stream (note that io can itself be an IOContext).

      • use (key => value) in dict to see if this particular combination is in the properties set

      • use get(dict, key, default) to retrieve the most recent value for a particular key

      The following properties are in common use:

      • :compact: Boolean specifying that small values should be printed more compactly, e.g. that numbers should be printed with fewer digits. This is set when printing array elements.

      • :limit: Boolean specifying that containers should be truncated, e.g. showing in place of most elements.

      • :displaysize: A Tuple{Int,Int} giving the size in rows and columns to use for text output. This can be used to override the display size for called functions, but to get the size of the screen use the displaysize function.

      julia> function f(io::IO)
      -           if get(io, :short, false)
      -               print(io, "short")
      -           else
      -               print(io, "loooooong")
      -           end
      -       end
      -f (generic function with 1 method)
      -
      -julia> f(STDOUT)
      -loooooong
      -julia> f(IOContext(STDOUT, :short => true))
      -short
      source
      Base.IOContextMethod.
      IOContext(io::IO, context::IOContext)

      Create an IOContext that wraps an alternate IO but inherits the properties of context.

      source

      Text I/O

      Base.showMethod.
      show(x)

      Write an informative text representation of a value to the current output stream. New types should overload show(io, x) where the first argument is a stream. The representation used by show generally includes Julia-specific formatting and type information.

      source
      Base.showcompactFunction.
      showcompact(x)

      Show a compact representation of a value.

      This is used for printing array elements without repeating type information (which would be redundant with that printed once for the whole array), and without line breaks inside the representation of an element.

      To offer a compact representation different from its standard one, a custom type should test get(io, :compact, false) in its normal show method.

      source
      Base.showallFunction.
      showall(x)

      Similar to show, except shows all elements of arrays.

      source
      Base.summaryFunction.
      summary(x)

      Return a string giving a brief description of a value. By default returns string(typeof(x)), e.g. Int64.

      For arrays, returns a string of size and type info, e.g. 10-element Array{Int64,1}.

      julia> summary(1)
      -"Int64"
      -
      -julia> summary(zeros(2))
      -"2-element Array{Float64,1}"
      source
      Base.printFunction.
      print(io::IO, x)

      Write to io (or to the default output stream STDOUT if io is not given) a canonical (un-decorated) text representation of a value if there is one, otherwise call show. The representation used by print includes minimal formatting and tries to avoid Julia-specific details.

      julia> print("Hello World!")
      -Hello World!
      -julia> io = IOBuffer();
      -
      -julia> print(io, "Hello World!")
      -
      -julia> String(take!(io))
      -"Hello World!"
      source
      Base.printlnFunction.
      println(io::IO, xs...)

      Print (using print) xs followed by a newline. If io is not supplied, prints to STDOUT.

      source
      Base.print_with_colorFunction.
      print_with_color(color::Union{Symbol, Int}, [io], xs...; bold::Bool = false)

      Print xs in a color specified as a symbol.

      color may take any of the values :normal, :default, :bold, :black, :blue, :cyan, :green, :light_black, :light_blue, :light_cyan, :light_green, :light_magenta, :light_red, :light_yellow, :magenta, :nothing, :red, :white, or :yellow or an integer between 0 and 255 inclusive. Note that not all terminals support 256 colors. If the keyword bold is given as true, the result will be printed in bold.

      source
      Base.infoFunction.
      info([io, ] msg..., [prefix="INFO: "])

      Display an informational message. Argument msg is a string describing the information to be displayed. The prefix keyword argument can be used to override the default prepending of msg.

      julia> info("hello world")
      -INFO: hello world
      -
      -julia> info("hello world"; prefix="MY INFO: ")
      -MY INFO: hello world

      See also logging.

      source
      Base.warnFunction.
      warn([io, ] msg..., [prefix="WARNING: ", once=false, key=nothing, bt=nothing, filename=nothing, lineno::Int=0])

      Display a warning. Argument msg is a string describing the warning to be displayed. Set once to true and specify a key to only display msg the first time warn is called. If bt is not nothing a backtrace is displayed. If filename is not nothing both it and lineno are displayed.

      See also logging.

      source
      warn(msg)

      Display a warning. Argument msg is a string describing the warning to be displayed.

      julia> warn("Beep Beep")
      -WARNING: Beep Beep
      source
      Base.loggingFunction.
      logging(io [, m [, f]][; kind=:all])
      -logging([; kind=:all])

      Stream output of informational, warning, and/or error messages to io, overriding what was otherwise specified. Optionally, divert stream only for module m, or specifically function f within m. kind can be :all (the default), :info, :warn, or :error. See Base.log_{info,warn,error}_to for the current set of redirections. Call logging with no arguments (or just the kind) to reset everything.

      source
      @printf([io::IOStream], "%Fmt", args...)

      Print args using C printf() style format specification string, with some caveats: Inf and NaN are printed consistently as Inf and NaN for flags %a, %A, %e, %E, %f, %F, %g, and %G. Furthermore, if a floating point number is equally close to the numeric values of two possible output strings, the output string further away from zero is chosen.

      Optionally, an IOStream may be passed as the first argument to redirect output.

      Examples

      julia> @printf("%f %F %f %F\n", Inf, Inf, NaN, NaN)
      -Inf Inf NaN NaN
      -
      -
      -julia> @printf "%.0f %.1f %f\n" 0.5 0.025 -0.0078125
      -1 0.0 -0.007813
      source
      @sprintf("%Fmt", args...)

      Return @printf formatted output as string.

      Examples

      julia> s = @sprintf "this is a %s %15.1f" "test" 34.567;
      -
      -julia> println(s)
      -this is a test            34.6
      source
      Base.sprintFunction.
      sprint(f::Function, args...)

      Call the given function with an I/O stream and the supplied extra arguments. Everything written to this I/O stream is returned as a string.

      julia> sprint(showcompact, 66.66666)
      -"66.6667"
      source
      Base.showerrorFunction.
      showerror(io, e)

      Show a descriptive representation of an exception object.

      source
      Base.dumpFunction.
      dump(x)

      Show every part of the representation of a value.

      source
      Base.readstringFunction.
      readstring(stream::IO)
      -readstring(filename::AbstractString)

      Read the entire contents of an I/O stream or a file as a string. The text is assumed to be encoded in UTF-8.

      source
      Base.readlineFunction.
      readline(stream::IO=STDIN; chomp::Bool=true)
      -readline(filename::AbstractString; chomp::Bool=true)

      Read a single line of text from the given I/O stream or file (defaults to STDIN). When reading from a file, the text is assumed to be encoded in UTF-8. Lines in the input end with '\n' or "\r\n" or the end of an input stream. When chomp is true (as it is by default), these trailing newline characters are removed from the line before it is returned. When chomp is false, they are returned as part of the line.

      source
      Base.readuntilFunction.
      readuntil(stream::IO, delim)
      -readuntil(filename::AbstractString, delim)

      Read a string from an I/O stream or a file, up to and including the given delimiter byte. The text is assumed to be encoded in UTF-8.

      source
      Base.readlinesFunction.
      readlines(stream::IO=STDIN; chomp::Bool=true)
      -readlines(filename::AbstractString; chomp::Bool=true)

      Read all lines of an I/O stream or a file as a vector of strings. Behavior is equivalent to saving the result of reading readline repeatedly with the same arguments and saving the resulting lines as a vector of strings.

      source
      Base.eachlineFunction.
      eachline(stream::IO=STDIN; chomp::Bool=true)
      -eachline(filename::AbstractString; chomp::Bool=true)

      Create an iterable EachLine object that will yield each line from an I/O stream or a file. Iteration calls readline on the stream argument repeatedly with chomp passed through, determining whether trailing end-of-line characters are removed. When called with a file name, the file is opened once at the beginning of iteration and closed at the end. If iteration is interrupted, the file will be closed when the EachLine object is garbage collected.

      source
      readdlm(source, delim::Char, T::Type, eol::Char; header=false, skipstart=0, skipblanks=true, use_mmap, quotes=true, dims, comments=true, comment_char='#')

      Read a matrix from the source where each line (separated by eol) gives one row, with elements separated by the given delimiter. The source can be a text file, stream or byte array. Memory mapped files can be used by passing the byte array representation of the mapped segment as source.

      If T is a numeric type, the result is an array of that type, with any non-numeric elements as NaN for floating-point types, or zero. Other useful values of T include String, AbstractString, and Any.

      If header is true, the first row of data will be read as header and the tuple (data_cells, header_cells) is returned instead of only data_cells.

      Specifying skipstart will ignore the corresponding number of initial lines from the input.

      If skipblanks is true, blank lines in the input will be ignored.

      If use_mmap is true, the file specified by source is memory mapped for potential speedups. Default is true except on Windows. On Windows, you may want to specify true if the file is large, and is only read once and not written to.

      If quotes is true, columns enclosed within double-quote (") characters are allowed to contain new lines and column delimiters. Double-quote characters within a quoted field must be escaped with another double-quote. Specifying dims as a tuple of the expected rows and columns (including header, if any) may speed up reading of large files. If comments is true, lines beginning with comment_char and text following comment_char in any line are ignored.

      source
      readdlm(source, delim::Char, eol::Char; options...)

      If all data is numeric, the result will be a numeric array. If some elements cannot be parsed as numbers, a heterogeneous array of numbers and strings is returned.

      source
      readdlm(source, delim::Char, T::Type; options...)

      The end of line delimiter is taken as \n.

      source
      readdlm(source, delim::Char; options...)

      The end of line delimiter is taken as \n. If all data is numeric, the result will be a numeric array. If some elements cannot be parsed as numbers, a heterogeneous array of numbers and strings is returned.

      source
      readdlm(source, T::Type; options...)

      The columns are assumed to be separated by one or more whitespaces. The end of line delimiter is taken as \n.

      source
      readdlm(source; options...)

      The columns are assumed to be separated by one or more whitespaces. The end of line delimiter is taken as \n. If all data is numeric, the result will be a numeric array. If some elements cannot be parsed as numbers, a heterogeneous array of numbers and strings is returned.

      source
      Base.DataFmt.writedlmFunction.
      writedlm(f, A, delim='\t'; opts)

      Write A (a vector, matrix, or an iterable collection of iterable rows) as text to f (either a filename string or an IO stream) using the given delimiter delim (which defaults to tab, but can be any printable Julia object, typically a Char or AbstractString).

      For example, two vectors x and y of the same length can be written as two columns of tab-delimited text to f by either writedlm(f, [x y]) or by writedlm(f, zip(x, y)).

      source
      Base.DataFmt.readcsvFunction.
      readcsv(source, [T::Type]; options...)

      Equivalent to readdlm with delim set to comma, and type optionally defined by T.

      source
      Base.DataFmt.writecsvFunction.
      writecsv(filename, A; opts)

      Equivalent to writedlm with delim set to comma.

      source
      Base64EncodePipe(ostream)

      Returns a new write-only I/O stream, which converts any bytes written to it into base64-encoded ASCII bytes written to ostream. Calling close on the Base64EncodePipe stream is necessary to complete the encoding (but does not close ostream).

      julia> io = IOBuffer();
      -
      -julia> iob64_encode = Base64EncodePipe(io);
      -
      -julia> write(iob64_encode, "Hello!")
      -6
      -
      -julia> close(iob64_encode);
      -
      -julia> str = String(take!(io))
      -"SGVsbG8h"
      -
      -julia> String(base64decode(str))
      -"Hello!"
      source
      Base64DecodePipe(istream)

      Returns a new read-only I/O stream, which decodes base64-encoded data read from istream.

      julia> io = IOBuffer();
      -
      -julia> iob64_decode = Base64DecodePipe(io);
      -
      -julia> write(io, "SGVsbG8h")
      -8
      -
      -julia> seekstart(io);
      -
      -julia> String(read(iob64_decode))
      -"Hello!"
      source
      base64encode(writefunc, args...)
      -base64encode(args...)

      Given a write-like function writefunc, which takes an I/O stream as its first argument, base64encode(writefunc, args...) calls writefunc to write args... to a base64-encoded string, and returns the string. base64encode(args...) is equivalent to base64encode(write, args...): it converts its arguments into bytes using the standard write functions and returns the base64-encoded string.

      See also base64decode.

      source
      base64decode(string)

      Decodes the base64-encoded string and returns a Vector{UInt8} of the decoded bytes.

      See also base64encode

      julia> b = base64decode("SGVsbG8h")
      -6-element Array{UInt8,1}:
      - 0x48
      - 0x65
      - 0x6c
      - 0x6c
      - 0x6f
      - 0x21
      -
      -julia> String(b)
      -"Hello!"
      source
      Base.displaysizeFunction.
      displaysize(io) -> (lines, columns)

      Return the nominal size of the screen that may be used for rendering output to this io object

      source

      Multimedia I/O

      Just as text output is performed by print and user-defined types can indicate their textual representation by overloading show, Julia provides a standardized mechanism for rich multimedia output (such as images, formatted text, or even audio and video), consisting of three parts:

      • A function display(x) to request the richest available multimedia display of a Julia object x (with a plain-text fallback).

      • Overloading show allows one to indicate arbitrary multimedia representations (keyed by standard MIME types) of user-defined types.

      • Multimedia-capable display backends may be registered by subclassing a generic Display type and pushing them onto a stack of display backends via pushdisplay.

      The base Julia runtime provides only plain-text display, but richer displays may be enabled by loading external modules or by using graphical Julia environments (such as the IPython-based IJulia notebook).

      display(x)
      -display(d::Display, x)
      -display(mime, x)
      -display(d::Display, mime, x)

      Display x using the topmost applicable display in the display stack, typically using the richest supported multimedia output for x, with plain-text STDOUT output as a fallback. The display(d, x) variant attempts to display x on the given display d only, throwing a MethodError if d cannot display objects of this type.

      There are also two variants with a mime argument (a MIME type string, such as "image/png"), which attempt to display x using the requested MIME type only, throwing a MethodError if this type is not supported by either the display(s) or by x. With these variants, one can also supply the "raw" data in the requested MIME type by passing x::AbstractString (for MIME types with text-based storage, such as text/html or application/postscript) or x::Vector{UInt8} (for binary MIME types).

      source
      redisplay(x)
      -redisplay(d::Display, x)
      -redisplay(mime, x)
      -redisplay(d::Display, mime, x)

      By default, the redisplay functions simply call display. However, some display backends may override redisplay to modify an existing display of x (if any). Using redisplay is also a hint to the backend that x may be redisplayed several times, and the backend may choose to defer the display until (for example) the next interactive prompt.

      source
      displayable(mime) -> Bool
      -displayable(d::Display, mime) -> Bool

      Returns a boolean value indicating whether the given mime type (string) is displayable by any of the displays in the current display stack, or specifically by the display d in the second variant.

      source
      Base.showMethod.
      show(stream, mime, x)

      The display functions ultimately call show in order to write an object x as a given mime type to a given I/O stream (usually a memory buffer), if possible. In order to provide a rich multimedia representation of a user-defined type T, it is only necessary to define a new show method for T, via: show(stream, ::MIME"mime", x::T) = ..., where mime is a MIME-type string and the function body calls write (or similar) to write that representation of x to stream. (Note that the MIME"" notation only supports literal strings; to construct MIME types in a more flexible manner use MIME{Symbol("")}.)

      For example, if you define a MyImage type and know how to write it to a PNG file, you could define a function show(stream, ::MIME"image/png", x::MyImage) = ... to allow your images to be displayed on any PNG-capable Display (such as IJulia). As usual, be sure to import Base.show in order to add new methods to the built-in Julia function show.

      The default MIME type is MIME"text/plain". There is a fallback definition for text/plain output that calls show with 2 arguments. Therefore, this case should be handled by defining a 2-argument show(stream::IO, x::MyType) method.

      Technically, the MIME"mime" macro defines a singleton type for the given mime string, which allows us to exploit Julia's dispatch mechanisms in determining how to display objects of any given type.

      The first argument to show can be an IOContext specifying output format properties. See IOContext for details.

      source
      mimewritable(mime, x)

      Returns a boolean value indicating whether or not the object x can be written as the given mime type. (By default, this is determined automatically by the existence of the corresponding show method for typeof(x).)

      source
      reprmime(mime, x)

      Returns an AbstractString or Vector{UInt8} containing the representation of x in the requested mime type, as written by show (throwing a MethodError if no appropriate show is available). An AbstractString is returned for MIME types with textual representations (such as "text/html" or "application/postscript"), whereas binary data is returned as Vector{UInt8}. (The function istextmime(mime) returns whether or not Julia treats a given mime type as text.)

      As a special case, if x is an AbstractString (for textual MIME types) or a Vector{UInt8} (for binary MIME types), the reprmime function assumes that x is already in the requested mime format and simply returns x. This special case does not apply to the "text/plain" MIME type. This is useful so that raw data can be passed to display(m::MIME, x).

      source
      stringmime(mime, x)

      Returns an AbstractString containing the representation of x in the requested mime type. This is similar to reprmime except that binary data is base64-encoded as an ASCII string.

      source

      As mentioned above, one can also define new display backends. For example, a module that can display PNG images in a window can register this capability with Julia, so that calling display(x) on types with PNG representations will automatically display the image using the module's window.

      In order to define a new display backend, one should first create a subtype D of the abstract class Display. Then, for each MIME type (mime string) that can be displayed on D, one should define a function display(d::D, ::MIME"mime", x) = ... that displays x as that MIME type, usually by calling reprmime(mime, x). A MethodError should be thrown if x cannot be displayed as that MIME type; this is automatic if one calls reprmime. Finally, one should define a function display(d::D, x) that queries mimewritable(mime, x) for the mime types supported by D and displays the "best" one; a MethodError should be thrown if no supported MIME types are found for x. Similarly, some subtypes may wish to override redisplay(d::D, ...). (Again, one should import Base.display to add new methods to display.) The return values of these functions are up to the implementation (since in some cases it may be useful to return a display "handle" of some type). The display functions for D can then be called directly, but they can also be invoked automatically from display(x) simply by pushing a new display onto the display-backend stack with:

      pushdisplay(d::Display)

      Pushes a new display d on top of the global display-backend stack. Calling display(x) or display(mime, x) will display x on the topmost compatible backend in the stack (i.e., the topmost backend that does not throw a MethodError).

      source
      popdisplay()
      -popdisplay(d::Display)

      Pop the topmost backend off of the display-backend stack, or the topmost copy of d in the second variant.

      source
      TextDisplay(io::IO)

      Returns a TextDisplay <: Display, which displays any object as the text/plain MIME type (by default), writing the text representation to the given I/O stream. (This is how objects are printed in the Julia REPL.)

      source
      istextmime(m::MIME)

      Determine whether a MIME type is text data. MIME types are assumed to be binary data except for a set of types known to be text data (possibly Unicode).

      source

      Memory-mapped I/O

      Mmap.Anonymous(name, readonly, create)

      Create an IO-like object for creating zeroed-out mmapped-memory that is not tied to a file for use in Mmap.mmap. Used by SharedArray for creating shared memory arrays.

      source
      Base.Mmap.mmapMethod.
      Mmap.mmap(io::Union{IOStream,AbstractString,Mmap.AnonymousMmap}[, type::Type{Array{T,N}}, dims, offset]; grow::Bool=true, shared::Bool=true)
      -       Mmap.mmap(type::Type{Array{T,N}}, dims)

      Create an Array whose values are linked to a file, using memory-mapping. This provides a convenient way of working with data too large to fit in the computer's memory.

      The type is an Array{T,N} with a bits-type element of T and dimension N that determines how the bytes of the array are interpreted. Note that the file must be stored in binary format, and no format conversions are possible (this is a limitation of operating systems, not Julia).

      dims is a tuple or single Integer specifying the size or length of the array.

      The file is passed via the stream argument, either as an open IOStream or filename string. When you initialize the stream, use "r" for a "read-only" array, and "w+" to create a new array used to write values to disk.

      If no type argument is specified, the default is Vector{UInt8}.

      Optionally, you can specify an offset (in bytes) if, for example, you want to skip over a header in the file. The default value for the offset is the current stream position for an IOStream.

      The grow keyword argument specifies whether the disk file should be grown to accommodate the requested size of array (if the total file size is < requested array size). Write privileges are required to grow the file.

      The shared keyword argument specifies whether the resulting Array and changes made to it will be visible to other processes mapping the same file.

      For example, the following code

      # Create a file for mmapping
      -# (you could alternatively use mmap to do this step, too)
      -A = rand(1:20, 5, 30)
      -s = open("/tmp/mmap.bin", "w+")
      -# We'll write the dimensions of the array as the first two Ints in the file
      -write(s, size(A,1))
      -write(s, size(A,2))
      -# Now write the data
      -write(s, A)
      -close(s)
      -
      -# Test by reading it back in
      -s = open("/tmp/mmap.bin")   # default is read-only
      -m = read(s, Int)
      -n = read(s, Int)
      -A2 = Mmap.mmap(s, Matrix{Int}, (m,n))

      creates a m-by-n Matrix{Int}, linked to the file associated with stream s.

      A more portable file would need to encode the word size – 32 bit or 64 bit – and endianness information in the header. In practice, consider encoding binary data using standard formats like HDF5 (which can be used with memory-mapping).

      source
      Base.Mmap.mmapMethod.
      Mmap.mmap(io, BitArray, [dims, offset])

      Create a BitArray whose values are linked to a file, using memory-mapping; it has the same purpose, works in the same way, and has the same arguments, as mmap, but the byte representation is different.

      Example: B = Mmap.mmap(s, BitArray, (25,30000))

      This would create a 25-by-30000 BitArray, linked to the file associated with stream s.

      source
      Base.Mmap.sync!Function.
      Mmap.sync!(array)

      Forces synchronization between the in-memory version of a memory-mapped Array or BitArray and the on-disk version.

      source

      Network I/O

      Base.connectMethod.
      connect([host], port::Integer) -> TCPSocket

      Connect to the host host on port port.

      source
      Base.connectMethod.
      connect(path::AbstractString) -> PipeEndpoint

      Connect to the named pipe / UNIX domain socket at path.

      source
      Base.listenMethod.
      listen([addr, ]port::Integer; backlog::Integer=BACKLOG_DEFAULT) -> TCPServer

      Listen on port on the address specified by addr. By default this listens on localhost only. To listen on all interfaces pass IPv4(0) or IPv6(0) as appropriate. backlog determines how many connections can be pending (not having called accept) before the server will begin to reject them. The default value of backlog is 511.

      source
      Base.listenMethod.
      listen(path::AbstractString) -> PipeServer

      Create and listen on a named pipe / UNIX domain socket.

      source
      Base.getaddrinfoFunction.
      getaddrinfo(host::AbstractString) -> IPAddr

      Gets the IP address of the host (may have to do a DNS lookup)

      source
      Base.getsocknameFunction.
      getsockname(sock::Union{TCPServer, TCPSocket}) -> (IPAddr, UInt16)

      Get the IP address and the port that the given TCPSocket is connected to (or bound to, in the case of TCPServer).

      source
      Base.IPv4Type.
      IPv4(host::Integer) -> IPv4

      Returns an IPv4 object from ip address host formatted as an Integer.

      julia> IPv4(3223256218)
      -ip"192.30.252.154"
      source
      Base.IPv6Type.
      IPv6(host::Integer) -> IPv6

      Returns an IPv6 object from ip address host formatted as an Integer.

      julia> IPv6(3223256218)
      -ip"::c01e:fc9a"
      source
      Base.nb_availableFunction.
      nb_available(stream)

      Returns the number of bytes available for reading before a read from this stream or buffer will block.

      source
      Base.acceptFunction.
      accept(server[,client])

      Accepts a connection on the given server and returns a connection to the client. An uninitialized client stream may be provided, in which case it will be used instead of creating a new stream.

      source
      Base.listenanyFunction.
      listenany([host::IPAddr,] port_hint) -> (UInt16, TCPServer)

      Create a TCPServer on any port, using hint as a starting point. Returns a tuple of the actual port that the server was created on and the server itself.

      source
      poll_fd(fd, timeout_s::Real=-1; readable=false, writable=false)

      Monitor a file descriptor fd for changes in the read or write availability, and with a timeout given by timeout_s seconds.

      The keyword arguments determine which of read and/or write status should be monitored; at least one of them must be set to true.

      The returned value is an object with boolean fields readable, writable, and timedout, giving the result of the polling.

      source
      poll_file(path::AbstractString, interval_s::Real=5.007, timeout_s::Real=-1) -> (previous::StatStruct, current::StatStruct)

      Monitor a file for changes by polling every interval_s seconds until a change occurs or timeout_s seconds have elapsed. The interval_s should be a long period; the default is 5.007 seconds.

      Returns a pair of StatStruct objects (previous, current) when a change is detected.

      To determine when a file was modified, compare mtime(prev) != mtime(current) to detect notification of changes. However, using watch_file for this operation is preferred, since it is more reliable and efficient, although in some situations it may not be available.

      source
      watch_file(path::AbstractString, timeout_s::Real=-1)

      Watch file or directory path for changes until a change occurs or timeout_s seconds have elapsed.

      The returned value is an object with boolean fields changed, renamed, and timedout, giving the result of watching the file.

      This behavior of this function varies slightly across platforms. See https://nodejs.org/api/fs.html#fs_caveats for more detailed information.

      source
      Base.bindFunction.
      bind(socket::Union{UDPSocket, TCPSocket}, host::IPAddr, port::Integer; ipv6only=false, reuseaddr=false, kws...)

      Bind socket to the given host:port. Note that 0.0.0.0 will listen on all devices.

      • The ipv6only parameter disables dual stack mode. If ipv6only=true, only an IPv6 stack is created.

      • If reuseaddr=true, multiple threads or processes can bind to the same address without error if they all set reuseaddr=true, but only the last to bind will receive any traffic.

      source
      bind(chnl::Channel, task::Task)

      Associates the lifetime of chnl with a task. Channel chnl is automatically closed when the task terminates. Any uncaught exception in the task is propagated to all waiters on chnl.

      The chnl object can be explicitly closed independent of task termination. Terminating tasks have no effect on already closed Channel objects.

      When a channel is bound to multiple tasks, the first task to terminate will close the channel. When multiple channels are bound to the same task, termination of the task will close all of the bound channels.

      julia> c = Channel(0);
      -
      -julia> task = @schedule foreach(i->put!(c, i), 1:4);
      -
      -julia> bind(c,task);
      -
      -julia> for i in c
      -           @show i
      -       end;
      -i = 1
      -i = 2
      -i = 3
      -i = 4
      -
      -julia> isopen(c)
      -false
      julia> c = Channel(0);
      -
      -julia> task = @schedule (put!(c,1);error("foo"));
      -
      -julia> bind(c,task);
      -
      -julia> take!(c)
      -1
      -
      -julia> put!(c,1);
      -ERROR: foo
      -Stacktrace:
      - [1] check_channel_state(::Channel{Any}) at ./channels.jl:131
      - [2] put!(::Channel{Any}, ::Int64) at ./channels.jl:261
      source
      Base.sendFunction.
      send(socket::UDPSocket, host, port::Integer, msg)

      Send msg over socket to host:port.

      source
      Base.recvFunction.
      recv(socket::UDPSocket)

      Read a UDP packet from the specified socket, and return the bytes received. This call blocks.

      source
      Base.recvfromFunction.
      recvfrom(socket::UDPSocket) -> (address, data)

      Read a UDP packet from the specified socket, returning a tuple of (address, data), where address will be either IPv4 or IPv6 as appropriate.

      source
      Base.setoptFunction.
      setopt(sock::UDPSocket; multicast_loop = nothing, multicast_ttl=nothing, enable_broadcast=nothing, ttl=nothing)

      Set UDP socket options.

      • multicast_loop: loopback for multicast packets (default: true).

      • multicast_ttl: TTL for multicast packets (default: nothing).

      • enable_broadcast: flag must be set to true if socket will be used for broadcast messages, or else the UDP system will return an access error (default: false).

      • ttl: Time-to-live of packets sent on the socket (default: nothing).

      source
      Base.ntohFunction.
      ntoh(x)

      Converts the endianness of a value from Network byte order (big-endian) to that used by the Host.

      source
      Base.htonFunction.
      hton(x)

      Converts the endianness of a value from that used by the Host to Network byte order (big-endian).

      source
      Base.ltohFunction.
      ltoh(x)

      Converts the endianness of a value from Little-endian to that used by the Host.

      source
      Base.htolFunction.
      htol(x)

      Converts the endianness of a value from that used by the Host to Little-endian.

      source
      Base.ENDIAN_BOMConstant.
      ENDIAN_BOM

      The 32-bit byte-order-mark indicates the native byte order of the host machine. Little-endian machines will contain the value 0x04030201. Big-endian machines will contain the value 0x01020304.

      source
      diff --git a/julia-0.6.3/share/doc/julia/html/en/stdlib/iterators.html b/julia-0.6.3/share/doc/julia/html/en/stdlib/iterators.html deleted file mode 100644 index ee4a529..0000000 --- a/julia-0.6.3/share/doc/julia/html/en/stdlib/iterators.html +++ /dev/null @@ -1,106 +0,0 @@ - -Iteration utilities · The Julia Language

      Iteration utilities

      Iteration utilities

      Base.Iterators.zipFunction.
      zip(iters...)

      For a set of iterable objects, returns an iterable of tuples, where the ith tuple contains the ith component of each input iterable.

      Note that zip is its own inverse: collect(zip(zip(a...)...)) == collect(a).

      Example

      julia> a = 1:5
      -1:5
      -
      -julia> b = ["e","d","b","c","a"]
      -5-element Array{String,1}:
      - "e"
      - "d"
      - "b"
      - "c"
      - "a"
      -
      -julia> c = zip(a,b)
      -Base.Iterators.Zip2{UnitRange{Int64},Array{String,1}}(1:5, String["e", "d", "b", "c", "a"])
      -
      -julia> length(c)
      -5
      -
      -julia> first(c)
      -(1, "e")
      source
      enumerate(iter)

      An iterator that yields (i, x) where i is a counter starting at 1, and x is the ith value from the given iterator. It's useful when you need not only the values x over which you are iterating, but also the number of iterations so far. Note that i may not be valid for indexing iter; it's also possible that x != iter[i], if iter has indices that do not start at 1. See the enumerate(IndexLinear(), iter) method if you want to ensure that i is an index.

      Example

      julia> a = ["a", "b", "c"];
      -
      -julia> for (index, value) in enumerate(a)
      -           println("$index $value")
      -       end
      -1 a
      -2 b
      -3 c
      source
      enumerate(IndexLinear(), A)
      -enumerate(IndexCartesian(), A)
      -enumerate(IndexStyle(A), A)

      An iterator that accesses each element of the array A, returning (i, x), where i is the index for the element and x = A[i]. This is similar to enumerate(A), except i will always be a valid index for A.

      Specifying IndexLinear() ensures that i will be an integer; specifying IndexCartesian() ensures that i will be a CartesianIndex; specifying IndexStyle(A) chooses whichever has been defined as the native indexing style for array A.

      Examples

      julia> A = ["a" "d"; "b" "e"; "c" "f"];
      -
      -julia> for (index, value) in enumerate(IndexStyle(A), A)
      -           println("$index $value")
      -       end
      -1 a
      -2 b
      -3 c
      -4 d
      -5 e
      -6 f
      -
      -julia> S = view(A, 1:2, :);
      -
      -julia> for (index, value) in enumerate(IndexStyle(S), S)
      -           println("$index $value")
      -       end
      -CartesianIndex{2}((1, 1)) a
      -CartesianIndex{2}((2, 1)) b
      -CartesianIndex{2}((1, 2)) d
      -CartesianIndex{2}((2, 2)) e

      Note that enumerate(A) returns i as a counter (always starting at 1), whereas enumerate(IndexLinear(), A) returns i as an index (starting at the first linear index of A, which may or may not be 1).

      See also: IndexStyle, indices.

      source
      Base.Iterators.restFunction.
      rest(iter, state)

      An iterator that yields the same elements as iter, but starting at the given state.

      source
      countfrom(start=1, step=1)

      An iterator that counts forever, starting at start and incrementing by step.

      source
      Base.Iterators.takeFunction.
      take(iter, n)

      An iterator that generates at most the first n elements of iter.

      Example

      julia> a = 1:2:11
      -1:2:11
      -
      -julia> collect(a)
      -6-element Array{Int64,1}:
      -  1
      -  3
      -  5
      -  7
      -  9
      - 11
      -
      -julia> collect(Iterators.take(a,3))
      -3-element Array{Int64,1}:
      - 1
      - 3
      - 5
      source
      Base.Iterators.dropFunction.
      drop(iter, n)

      An iterator that generates all but the first n elements of iter.

      Example

      julia> a = 1:2:11
      -1:2:11
      -
      -julia> collect(a)
      -6-element Array{Int64,1}:
      -  1
      -  3
      -  5
      -  7
      -  9
      - 11
      -
      -julia> collect(Iterators.drop(a,4))
      -2-element Array{Int64,1}:
      -  9
      - 11
      source
      Base.Iterators.cycleFunction.
      cycle(iter)

      An iterator that cycles through iter forever.

      source
      repeated(x[, n::Int])

      An iterator that generates the value x forever. If n is specified, generates x that many times (equivalent to take(repeated(x), n)).

      Example

      julia> a = Iterators.repeated([1 2], 4);
      -
      -julia> collect(a)
      -4-element Array{Array{Int64,2},1}:
      - [1 2]
      - [1 2]
      - [1 2]
      - [1 2]
      source
      product(iters...)

      Returns an iterator over the product of several iterators. Each generated element is a tuple whose ith element comes from the ith argument iterator. The first iterator changes the fastest. Example:

      Example

      julia> collect(Iterators.product(1:2,3:5))
      -2×3 Array{Tuple{Int64,Int64},2}:
      - (1, 3)  (1, 4)  (1, 5)
      - (2, 3)  (2, 4)  (2, 5)
      source
      flatten(iter)

      Given an iterator that yields iterators, return an iterator that yields the elements of those iterators. Put differently, the elements of the argument iterator are concatenated.

      Example

      julia> collect(Iterators.flatten((1:2, 8:9)))
      -4-element Array{Int64,1}:
      - 1
      - 2
      - 8
      - 9
      source
      partition(collection, n)

      Iterate over a collection n elements at a time.

      Example

      julia> collect(Iterators.partition([1,2,3,4,5], 2))
      -3-element Array{Array{Int64,1},1}:
      - [1, 2]
      - [3, 4]
      - [5]
      source
      diff --git a/julia-0.6.3/share/doc/julia/html/en/stdlib/libc.html b/julia-0.6.3/share/doc/julia/html/en/stdlib/libc.html deleted file mode 100644 index 882a912..0000000 --- a/julia-0.6.3/share/doc/julia/html/en/stdlib/libc.html +++ /dev/null @@ -1,9 +0,0 @@ - -C Standard Library · The Julia Language

      C Standard Library

      C Standard Library

      Base.Libc.mallocFunction.
      malloc(size::Integer) -> Ptr{Void}

      Call malloc from the C standard library.

      source
      Base.Libc.callocFunction.
      calloc(num::Integer, size::Integer) -> Ptr{Void}

      Call calloc from the C standard library.

      source
      Base.Libc.reallocFunction.
      realloc(addr::Ptr, size::Integer) -> Ptr{Void}

      Call realloc from the C standard library.

      See warning in the documentation for free regarding only using this on memory originally obtained from malloc.

      source
      Base.Libc.freeFunction.
      free(addr::Ptr)

      Call free from the C standard library. Only use this on memory obtained from malloc, not on pointers retrieved from other C libraries. Ptr objects obtained from C libraries should be freed by the free functions defined in that library, to avoid assertion failures if multiple libc libraries exist on the system.

      source
      Base.Libc.errnoFunction.
      errno([code])

      Get the value of the C library's errno. If an argument is specified, it is used to set the value of errno.

      The value of errno is only valid immediately after a ccall to a C library routine that sets it. Specifically, you cannot call errno at the next prompt in a REPL, because lots of code is executed between prompts.

      source
      Base.Libc.strerrorFunction.
      strerror(n=errno())

      Convert a system call error code to a descriptive string

      source
      GetLastError()

      Call the Win32 GetLastError function [only available on Windows].

      source
      FormatMessage(n=GetLastError())

      Convert a Win32 system call error code to a descriptive string [only available on Windows].

      source
      Base.Libc.timeMethod.
      time(t::TmStruct)

      Converts a TmStruct struct to a number of seconds since the epoch.

      source
      Base.Libc.strftimeFunction.
      strftime([format], time)

      Convert time, given as a number of seconds since the epoch or a TmStruct, to a formatted string using the given format. Supported formats are the same as those in the standard C library.

      source
      Base.Libc.strptimeFunction.
      strptime([format], timestr)

      Parse a formatted time string into a TmStruct giving the seconds, minute, hour, date, etc. Supported formats are the same as those in the standard C library. On some platforms, timezones will not be parsed correctly. If the result of this function will be passed to time to convert it to seconds since the epoch, the isdst field should be filled in manually. Setting it to -1 will tell the C library to use the current system settings to determine the timezone.

      source
      TmStruct([seconds])

      Convert a number of seconds since the epoch to broken-down format, with fields sec, min, hour, mday, month, year, wday, yday, and isdst.

      source
      flush_cstdio()

      Flushes the C stdout and stderr streams (which may have been written to by external C code).

      source
      diff --git a/julia-0.6.3/share/doc/julia/html/en/stdlib/libdl.html b/julia-0.6.3/share/doc/julia/html/en/stdlib/libdl.html deleted file mode 100644 index 03a47c7..0000000 --- a/julia-0.6.3/share/doc/julia/html/en/stdlib/libdl.html +++ /dev/null @@ -1,16 +0,0 @@ - -Dynamic Linker · The Julia Language

      Dynamic Linker

      Dynamic Linker

      The names in Base.Libdl are not exported and need to be called e.g. as Libdl.dlopen().

      Base.Libdl.dlopenFunction.
      dlopen(libfile::AbstractString [, flags::Integer])

      Load a shared library, returning an opaque handle.

      The extension given by the constant dlext (.so, .dll, or .dylib) can be omitted from the libfile string, as it is automatically appended if needed. If libfile is not an absolute path name, then the paths in the array DL_LOAD_PATH are searched for libfile, followed by the system load path.

      The optional flags argument is a bitwise-or of zero or more of RTLD_LOCAL, RTLD_GLOBAL, RTLD_LAZY, RTLD_NOW, RTLD_NODELETE, RTLD_NOLOAD, RTLD_DEEPBIND, and RTLD_FIRST. These are converted to the corresponding flags of the POSIX (and/or GNU libc and/or MacOS) dlopen command, if possible, or are ignored if the specified functionality is not available on the current platform. The default flags are platform specific. On MacOS the default dlopen flags are RTLD_LAZY|RTLD_DEEPBIND|RTLD_GLOBAL while on other platforms the defaults are RTLD_LAZY|RTLD_DEEPBIND|RTLD_LOCAL. An important usage of these flags is to specify non default behavior for when the dynamic library loader binds library references to exported symbols and if the bound references are put into process local or global scope. For instance RTLD_LAZY|RTLD_DEEPBIND|RTLD_GLOBAL allows the library's symbols to be available for usage in other shared libraries, addressing situations where there are dependencies between shared libraries.

      source
      Base.Libdl.dlopen_eFunction.
      dlopen_e(libfile::AbstractString [, flags::Integer])

      Similar to dlopen, except returns a NULL pointer instead of raising errors.

      source
      Base.Libdl.RTLD_NOWConstant.
      RTLD_DEEPBIND
      -RTLD_FIRST
      -RTLD_GLOBAL
      -RTLD_LAZY
      -RTLD_LOCAL
      -RTLD_NODELETE
      -RTLD_NOLOAD
      -RTLD_NOW

      Enum constant for dlopen. See your platform man page for details, if applicable.

      source
      Base.Libdl.dlsymFunction.
      dlsym(handle, sym)

      Look up a symbol from a shared library handle, return callable function pointer on success.

      source
      Base.Libdl.dlsym_eFunction.
      dlsym_e(handle, sym)

      Look up a symbol from a shared library handle, silently return NULL pointer on lookup failure.

      source
      Base.Libdl.dlcloseFunction.
      dlclose(handle)

      Close shared library referenced by handle.

      source
      Base.Libdl.dlextConstant.
      dlext

      File extension for dynamic libraries (e.g. dll, dylib, so) on the current platform.

      source
      find_library(names, locations)

      Searches for the first library in names in the paths in the locations list, DL_LOAD_PATH, or system library paths (in that order) which can successfully be dlopen'd. On success, the return value will be one of the names (potentially prefixed by one of the paths in locations). This string can be assigned to a global const and used as the library name in future ccall's. On failure, it returns the empty string.

      source
      DL_LOAD_PATH

      When calling dlopen, the paths in this list will be searched first, in order, before searching the system locations for a valid library handle.

      source
      diff --git a/julia-0.6.3/share/doc/julia/html/en/stdlib/linalg.html b/julia-0.6.3/share/doc/julia/html/en/stdlib/linalg.html deleted file mode 100644 index ef1ef93..0000000 --- a/julia-0.6.3/share/doc/julia/html/en/stdlib/linalg.html +++ /dev/null @@ -1,1067 +0,0 @@ - -Linear Algebra · The Julia Language

      Linear Algebra

      Linear Algebra

      Standard Functions

      Linear algebra functions in Julia are largely implemented by calling functions from LAPACK. Sparse factorizations call functions from SuiteSparse.

      Base.:*Method.
      *(x, y...)

      Multiplication operator. x*y*z*... calls this function with all arguments, i.e. *(x, y, z, ...).

      source
      Base.:\Method.
      \(x, y)

      Left division operator: multiplication of y by the inverse of x on the left. Gives floating-point results for integer arguments.

      julia> 3 \ 6
      -2.0
      -
      -julia> inv(3) * 6
      -2.0
      -
      -julia> A = [1 2; 3 4]; x = [5, 6];
      -
      -julia> A \ x
      -2-element Array{Float64,1}:
      - -4.0
      -  4.5
      -
      -julia> inv(A) * x
      -2-element Array{Float64,1}:
      - -4.0
      -  4.5
      source
      Base.LinAlg.dotFunction.
      dot(n, X, incx, Y, incy)

      Dot product of two vectors consisting of n elements of array X with stride incx and n elements of array Y with stride incy.

      Example:

      julia> dot(10, ones(10), 1, ones(20), 2)
      -10.0
      source
      Base.LinAlg.vecdotFunction.
      vecdot(x, y)

      For any iterable containers x and y (including arrays of any dimension) of numbers (or any element type for which dot is defined), compute the Euclidean dot product (the sum of dot(x[i],y[i])) as if they were vectors.

      Examples

      julia> vecdot(1:5, 2:6)
      -70
      -
      -julia> x = fill(2., (5,5));
      -
      -julia> y = fill(3., (5,5));
      -
      -julia> vecdot(x, y)
      -150.0
      source
      Base.LinAlg.crossFunction.
      cross(x, y)
      -×(x,y)

      Compute the cross product of two 3-vectors.

      Example

      julia> a = [0;1;0]
      -3-element Array{Int64,1}:
      - 0
      - 1
      - 0
      -
      -julia> b = [0;0;1]
      -3-element Array{Int64,1}:
      - 0
      - 0
      - 1
      -
      -julia> cross(a,b)
      -3-element Array{Int64,1}:
      - 1
      - 0
      - 0
      source
      Base.LinAlg.factorizeFunction.
      factorize(A)

      Compute a convenient factorization of A, based upon the type of the input matrix. factorize checks A to see if it is symmetric/triangular/etc. if A is passed as a generic matrix. factorize checks every element of A to verify/rule out each property. It will short-circuit as soon as it can rule out symmetry/triangular structure. The return value can be reused for efficient solving of multiple systems. For example: A=factorize(A); x=A\b; y=A\C.

      Properties of Atype of factorization
      Positive-definiteCholesky (see cholfact)
      Dense Symmetric/HermitianBunch-Kaufman (see bkfact)
      Sparse Symmetric/HermitianLDLt (see ldltfact)
      TriangularTriangular
      DiagonalDiagonal
      BidiagonalBidiagonal
      TridiagonalLU (see lufact)
      Symmetric real tridiagonalLDLt (see ldltfact)
      General squareLU (see lufact)
      General non-squareQR (see qrfact)

      If factorize is called on a Hermitian positive-definite matrix, for instance, then factorize will return a Cholesky factorization.

      Example

      julia> A = Array(Bidiagonal(ones(5, 5), true))
      -5×5 Array{Float64,2}:
      - 1.0  1.0  0.0  0.0  0.0
      - 0.0  1.0  1.0  0.0  0.0
      - 0.0  0.0  1.0  1.0  0.0
      - 0.0  0.0  0.0  1.0  1.0
      - 0.0  0.0  0.0  0.0  1.0
      -
      -julia> factorize(A) # factorize will check to see that A is already factorized
      -5×5 Bidiagonal{Float64}:
      - 1.0  1.0   ⋅    ⋅    ⋅
      -  ⋅   1.0  1.0   ⋅    ⋅
      -  ⋅    ⋅   1.0  1.0   ⋅
      -  ⋅    ⋅    ⋅   1.0  1.0
      -  ⋅    ⋅    ⋅    ⋅   1.0

      This returns a 5×5 Bidiagonal{Float64}, which can now be passed to other linear algebra functions (e.g. eigensolvers) which will use specialized methods for Bidiagonal types.

      source
      Diagonal(A::AbstractMatrix)

      Constructs a matrix from the diagonal of A.

      Example

      julia> A = [1 2 3; 4 5 6; 7 8 9]
      -3×3 Array{Int64,2}:
      - 1  2  3
      - 4  5  6
      - 7  8  9
      -
      -julia> Diagonal(A)
      -3×3 Diagonal{Int64}:
      - 1  ⋅  ⋅
      - ⋅  5  ⋅
      - ⋅  ⋅  9
      source
      Diagonal(V::AbstractVector)

      Constructs a matrix with V as its diagonal.

      Example

      julia> V = [1; 2]
      -2-element Array{Int64,1}:
      - 1
      - 2
      -
      -julia> Diagonal(V)
      -2×2 Diagonal{Int64}:
      - 1  ⋅
      - ⋅  2
      source
      Bidiagonal(dv, ev, isupper::Bool)

      Constructs an upper (isupper=true) or lower (isupper=false) bidiagonal matrix using the given diagonal (dv) and off-diagonal (ev) vectors. The result is of type Bidiagonal and provides efficient specialized linear solvers, but may be converted into a regular matrix with convert(Array, _) (or Array(_) for short). ev's length must be one less than the length of dv.

      Example

      julia> dv = [1; 2; 3; 4]
      -4-element Array{Int64,1}:
      - 1
      - 2
      - 3
      - 4
      -
      -julia> ev = [7; 8; 9]
      -3-element Array{Int64,1}:
      - 7
      - 8
      - 9
      -
      -julia> Bu = Bidiagonal(dv, ev, true) # ev is on the first superdiagonal
      -4×4 Bidiagonal{Int64}:
      - 1  7  ⋅  ⋅
      - ⋅  2  8  ⋅
      - ⋅  ⋅  3  9
      - ⋅  ⋅  ⋅  4
      -
      -julia> Bl = Bidiagonal(dv, ev, false) # ev is on the first subdiagonal
      -4×4 Bidiagonal{Int64}:
      - 1  ⋅  ⋅  ⋅
      - 7  2  ⋅  ⋅
      - ⋅  8  3  ⋅
      - ⋅  ⋅  9  4
      source
      Bidiagonal(dv, ev, uplo::Char)

      Constructs an upper (uplo='U') or lower (uplo='L') bidiagonal matrix using the given diagonal (dv) and off-diagonal (ev) vectors. The result is of type Bidiagonal and provides efficient specialized linear solvers, but may be converted into a regular matrix with convert(Array, _) (or Array(_) for short). ev's length must be one less than the length of dv.

      Example

      julia> dv = [1; 2; 3; 4]
      -4-element Array{Int64,1}:
      - 1
      - 2
      - 3
      - 4
      -
      -julia> ev = [7; 8; 9]
      -3-element Array{Int64,1}:
      - 7
      - 8
      - 9
      -
      -julia> Bu = Bidiagonal(dv, ev, 'U') #e is on the first superdiagonal
      -4×4 Bidiagonal{Int64}:
      - 1  7  ⋅  ⋅
      - ⋅  2  8  ⋅
      - ⋅  ⋅  3  9
      - ⋅  ⋅  ⋅  4
      -
      -julia> Bl = Bidiagonal(dv, ev, 'L') #e is on the first subdiagonal
      -4×4 Bidiagonal{Int64}:
      - 1  ⋅  ⋅  ⋅
      - 7  2  ⋅  ⋅
      - ⋅  8  3  ⋅
      - ⋅  ⋅  9  4
      source
      Bidiagonal(A, isupper::Bool)

      Construct a Bidiagonal matrix from the main diagonal of A and its first super- (if isupper=true) or sub-diagonal (if isupper=false).

      Example

      julia> A = [1 1 1 1; 2 2 2 2; 3 3 3 3; 4 4 4 4]
      -4×4 Array{Int64,2}:
      - 1  1  1  1
      - 2  2  2  2
      - 3  3  3  3
      - 4  4  4  4
      -
      -julia> Bidiagonal(A, true) #contains the main diagonal and first superdiagonal of A
      -4×4 Bidiagonal{Int64}:
      - 1  1  ⋅  ⋅
      - ⋅  2  2  ⋅
      - ⋅  ⋅  3  3
      - ⋅  ⋅  ⋅  4
      -
      -julia> Bidiagonal(A, false) #contains the main diagonal and first subdiagonal of A
      -4×4 Bidiagonal{Int64}:
      - 1  ⋅  ⋅  ⋅
      - 2  2  ⋅  ⋅
      - ⋅  3  3  ⋅
      - ⋅  ⋅  4  4
      source
      SymTridiagonal(dv, ev)

      Construct a symmetric tridiagonal matrix from the diagonal and first sub/super-diagonal, respectively. The result is of type SymTridiagonal and provides efficient specialized eigensolvers, but may be converted into a regular matrix with convert(Array, _) (or Array(_) for short).

      Example

      julia> dv = [1; 2; 3; 4]
      -4-element Array{Int64,1}:
      - 1
      - 2
      - 3
      - 4
      -
      -julia> ev = [7; 8; 9]
      -3-element Array{Int64,1}:
      - 7
      - 8
      - 9
      -
      -julia> SymTridiagonal(dv, ev)
      -4×4 SymTridiagonal{Int64}:
      - 1  7  ⋅  ⋅
      - 7  2  8  ⋅
      - ⋅  8  3  9
      - ⋅  ⋅  9  4
      source
      Tridiagonal(dl, d, du)

      Construct a tridiagonal matrix from the first subdiagonal, diagonal, and first superdiagonal, respectively. The result is of type Tridiagonal and provides efficient specialized linear solvers, but may be converted into a regular matrix with convert(Array, _) (or Array(_) for short). The lengths of dl and du must be one less than the length of d.

      Example

      julia> dl = [1; 2; 3]
      -3-element Array{Int64,1}:
      - 1
      - 2
      - 3
      -
      -julia> du = [4; 5; 6]
      -3-element Array{Int64,1}:
      - 4
      - 5
      - 6
      -
      -julia> d = [7; 8; 9; 0]
      -4-element Array{Int64,1}:
      - 7
      - 8
      - 9
      - 0
      -
      -julia> Tridiagonal(dl, d, du)
      -4×4 Tridiagonal{Int64}:
      - 7  4  ⋅  ⋅
      - 1  8  5  ⋅
      - ⋅  2  9  6
      - ⋅  ⋅  3  0
      source
      Tridiagonal(A)

      returns a Tridiagonal array based on (abstract) matrix A, using its first lower diagonal, main diagonal, and first upper diagonal.

      Example

      julia> A = [1 2 3 4; 1 2 3 4; 1 2 3 4; 1 2 3 4]
      -4×4 Array{Int64,2}:
      - 1  2  3  4
      - 1  2  3  4
      - 1  2  3  4
      - 1  2  3  4
      -
      -julia> Tridiagonal(A)
      -4×4 Tridiagonal{Int64}:
      - 1  2  ⋅  ⋅
      - 1  2  3  ⋅
      - ⋅  2  3  4
      - ⋅  ⋅  3  4
      source
      Symmetric(A, uplo=:U)

      Construct a Symmetric view of the upper (if uplo = :U) or lower (if uplo = :L) triangle of the matrix A.

      Example

      julia> A = [1 0 2 0 3; 0 4 0 5 0; 6 0 7 0 8; 0 9 0 1 0; 2 0 3 0 4]
      -5×5 Array{Int64,2}:
      - 1  0  2  0  3
      - 0  4  0  5  0
      - 6  0  7  0  8
      - 0  9  0  1  0
      - 2  0  3  0  4
      -
      -julia> Supper = Symmetric(A)
      -5×5 Symmetric{Int64,Array{Int64,2}}:
      - 1  0  2  0  3
      - 0  4  0  5  0
      - 2  0  7  0  8
      - 0  5  0  1  0
      - 3  0  8  0  4
      -
      -julia> Slower = Symmetric(A, :L)
      -5×5 Symmetric{Int64,Array{Int64,2}}:
      - 1  0  6  0  2
      - 0  4  0  9  0
      - 6  0  7  0  3
      - 0  9  0  1  0
      - 2  0  3  0  4

      Note that Supper will not be equal to Slower unless A is itself symmetric (e.g. if A == A.').

      source
      Hermitian(A, uplo=:U)

      Construct a Hermitian view of the upper (if uplo = :U) or lower (if uplo = :L) triangle of the matrix A.

      Example

      julia> A = [1 0 2+2im 0 3-3im; 0 4 0 5 0; 6-6im 0 7 0 8+8im; 0 9 0 1 0; 2+2im 0 3-3im 0 4];
      -
      -julia> Hupper = Hermitian(A)
      -5×5 Hermitian{Complex{Int64},Array{Complex{Int64},2}}:
      - 1+0im  0+0im  2+2im  0+0im  3-3im
      - 0+0im  4+0im  0+0im  5+0im  0+0im
      - 2-2im  0+0im  7+0im  0+0im  8+8im
      - 0+0im  5+0im  0+0im  1+0im  0+0im
      - 3+3im  0+0im  8-8im  0+0im  4+0im
      -
      -julia> Hlower = Hermitian(A, :L)
      -5×5 Hermitian{Complex{Int64},Array{Complex{Int64},2}}:
      - 1+0im  0+0im  6+6im  0+0im  2-2im
      - 0+0im  4+0im  0+0im  9+0im  0+0im
      - 6-6im  0+0im  7+0im  0+0im  3+3im
      - 0+0im  9+0im  0+0im  1+0im  0+0im
      - 2+2im  0+0im  3-3im  0+0im  4+0im

      Note that Hupper will not be equal to Hlower unless A is itself Hermitian (e.g. if A == A').

      source
      LowerTriangular(A::AbstractMatrix)

      Construct a LowerTriangular view of the the matrix A.

      Example

      julia> A = [1.0 2.0 3.0; 4.0 5.0 6.0; 7.0 8.0 9.0]
      -3×3 Array{Float64,2}:
      - 1.0  2.0  3.0
      - 4.0  5.0  6.0
      - 7.0  8.0  9.0
      -
      -julia> LowerTriangular(A)
      -3×3 LowerTriangular{Float64,Array{Float64,2}}:
      - 1.0   ⋅    ⋅
      - 4.0  5.0   ⋅
      - 7.0  8.0  9.0
      source
      UpperTriangular(A::AbstractMatrix)

      Construct an UpperTriangular view of the the matrix A.

      Example

      julia> A = [1.0 2.0 3.0; 4.0 5.0 6.0; 7.0 8.0 9.0]
      -3×3 Array{Float64,2}:
      - 1.0  2.0  3.0
      - 4.0  5.0  6.0
      - 7.0  8.0  9.0
      -
      -julia> UpperTriangular(A)
      -3×3 UpperTriangular{Float64,Array{Float64,2}}:
      - 1.0  2.0  3.0
      -  ⋅   5.0  6.0
      -  ⋅    ⋅   9.0
      source
      Base.LinAlg.luFunction.
      lu(A, pivot=Val{true}) -> L, U, p

      Compute the LU factorization of A, such that A[p,:] = L*U. By default, pivoting is used. This can be overridden by passing Val{false} for the second argument.

      See also lufact.

      Example

      julia> A = [4. 3.; 6. 3.]
      -2×2 Array{Float64,2}:
      - 4.0  3.0
      - 6.0  3.0
      -
      -julia> L, U, p = lu(A)
      -([1.0 0.0; 0.666667 1.0], [6.0 3.0; 0.0 1.0], [2, 1])
      -
      -julia> A[p, :] == L * U
      -true
      source
      Base.LinAlg.lufactFunction.
      lufact(A [,pivot=Val{true}]) -> F::LU

      Compute the LU factorization of A.

      In most cases, if A is a subtype S of AbstractMatrix{T} with an element type T supporting +, -, * and /, the return type is LU{T,S{T}}. If pivoting is chosen (default) the element type should also support abs and <.

      The individual components of the factorization F can be accessed by indexing:

      ComponentDescription
      F[:L]L (lower triangular) part of LU
      F[:U]U (upper triangular) part of LU
      F[:p](right) permutation Vector
      F[:P](right) permutation Matrix

      The relationship between F and A is

      F[:L]*F[:U] == A[F[:p], :]

      F further supports the following functions:

      Supported functionLULU{T,Tridiagonal{T}}
      /
      \
      cond
      inv
      det
      logdet
      logabsdet
      size

      Example

      julia> A = [4 3; 6 3]
      -2×2 Array{Int64,2}:
      - 4  3
      - 6  3
      -
      -julia> F = lufact(A)
      -Base.LinAlg.LU{Float64,Array{Float64,2}} with factors L and U:
      -[1.0 0.0; 1.5 1.0]
      -[4.0 3.0; 0.0 -1.5]
      -
      -julia> F[:L] * F[:U] == A[F[:p], :]
      -true
      source
      lufact(A::SparseMatrixCSC) -> F::UmfpackLU

      Compute the LU factorization of a sparse matrix A.

      For sparse A with real or complex element type, the return type of F is UmfpackLU{Tv, Ti}, with Tv = Float64 or Complex128 respectively and Ti is an integer type (Int32 or Int64).

      The individual components of the factorization F can be accessed by indexing:

      ComponentDescription
      F[:L]L (lower triangular) part of LU
      F[:U]U (upper triangular) part of LU
      F[:p]right permutation Vector
      F[:q]left permutation Vector
      F[:Rs]Vector of scaling factors
      F[:(:)](L,U,p,q,Rs) components

      The relation between F and A is

      F[:L]*F[:U] == (F[:Rs] .* A)[F[:p], F[:q]]

      F further supports the following functions:

      Note

      lufact(A::SparseMatrixCSC) uses the UMFPACK library that is part of SuiteSparse. As this library only supports sparse matrices with Float64 or Complex128 elements, lufact converts A into a copy that is of type SparseMatrixCSC{Float64} or SparseMatrixCSC{Complex128} as appropriate.

      source
      Base.LinAlg.lufact!Function.
      lufact!(A, pivot=Val{true}) -> LU

      lufact! is the same as lufact, but saves space by overwriting the input A, instead of creating a copy. An InexactError exception is thrown if the factorization produces a number not representable by the element type of A, e.g. for integer types.

      source
      Base.LinAlg.cholFunction.
      chol(A) -> U

      Compute the Cholesky factorization of a positive definite matrix A and return the UpperTriangular matrix U such that A = U'U.

      Example

      julia> A = [1. 2.; 2. 50.]
      -2×2 Array{Float64,2}:
      - 1.0   2.0
      - 2.0  50.0
      -
      -julia> U = chol(A)
      -2×2 UpperTriangular{Float64,Array{Float64,2}}:
      - 1.0  2.0
      -  ⋅   6.78233
      -
      -julia> U'U
      -2×2 Array{Float64,2}:
      - 1.0   2.0
      - 2.0  50.0
      source
      chol(x::Number) -> y

      Compute the square root of a non-negative number x.

      Example

      julia> chol(16)
      -4.0
      source
      Base.LinAlg.cholfactFunction.
      cholfact(A, [uplo::Symbol,] Val{false}) -> Cholesky

      Compute the Cholesky factorization of a dense symmetric positive definite matrix A and return a Cholesky factorization. The matrix A can either be a Symmetric or Hermitian StridedMatrix or a perfectly symmetric or Hermitian StridedMatrix. In the latter case, the optional argument uplo may be :L for using the lower part or :U for the upper part of A. The default is to use :U. The triangular Cholesky factor can be obtained from the factorization F with: F[:L] and F[:U]. The following functions are available for Cholesky objects: size, \, inv, and det. A PosDefException exception is thrown in case the matrix is not positive definite.

      Example

      julia> A = [4. 12. -16.; 12. 37. -43.; -16. -43. 98.]
      -3×3 Array{Float64,2}:
      -   4.0   12.0  -16.0
      -  12.0   37.0  -43.0
      - -16.0  -43.0   98.0
      -
      -julia> C = cholfact(A)
      -Base.LinAlg.Cholesky{Float64,Array{Float64,2}} with factor:
      -[2.0 6.0 -8.0; 0.0 1.0 5.0; 0.0 0.0 3.0]
      -
      -julia> C[:U]
      -3×3 UpperTriangular{Float64,Array{Float64,2}}:
      - 2.0  6.0  -8.0
      -  ⋅   1.0   5.0
      -  ⋅    ⋅    3.0
      -
      -julia> C[:L]
      -3×3 LowerTriangular{Float64,Array{Float64,2}}:
      -  2.0   ⋅    ⋅
      -  6.0  1.0   ⋅
      - -8.0  5.0  3.0
      -
      -julia> C[:L] * C[:U] == A
      -true
      source
      cholfact(A, [uplo::Symbol,] Val{true}; tol = 0.0) -> CholeskyPivoted

      Compute the pivoted Cholesky factorization of a dense symmetric positive semi-definite matrix A and return a CholeskyPivoted factorization. The matrix A can either be a Symmetric or Hermitian StridedMatrix or a perfectly symmetric or Hermitian StridedMatrix. In the latter case, the optional argument uplo may be :L for using the lower part or :U for the upper part of A. The default is to use :U. The triangular Cholesky factor can be obtained from the factorization F with: F[:L] and F[:U]. The following functions are available for PivotedCholesky objects: size, \, inv, det, and rank. The argument tol determines the tolerance for determining the rank. For negative values, the tolerance is the machine precision.

      source
      cholfact(A; shift = 0.0, perm = Int[]) -> CHOLMOD.Factor

      Compute the Cholesky factorization of a sparse positive definite matrix A. A must be a SparseMatrixCSC or a Symmetric/Hermitian view of a SparseMatrixCSC. Note that even if A doesn't have the type tag, it must still be symmetric or Hermitian. A fill-reducing permutation is used. F = cholfact(A) is most frequently used to solve systems of equations with F\b, but also the methods diag, det, and logdet are defined for F. You can also extract individual factors from F, using F[:L]. However, since pivoting is on by default, the factorization is internally represented as A == P'*L*L'*P with a permutation matrix P; using just L without accounting for P will give incorrect answers. To include the effects of permutation, it's typically preferable to extract "combined" factors like PtL = F[:PtL] (the equivalent of P'*L) and LtP = F[:UP] (the equivalent of L'*P).

      Setting the optional shift keyword argument computes the factorization of A+shift*I instead of A. If the perm argument is nonempty, it should be a permutation of 1:size(A,1) giving the ordering to use (instead of CHOLMOD's default AMD ordering).

      Note

      This method uses the CHOLMOD library from SuiteSparse, which only supports doubles or complex doubles. Input matrices not of those element types will be converted to SparseMatrixCSC{Float64} or SparseMatrixCSC{Complex128} as appropriate.

      Many other functions from CHOLMOD are wrapped but not exported from the Base.SparseArrays.CHOLMOD module.

      source
      Base.LinAlg.cholfact!Function.
      cholfact!(A, [uplo::Symbol,] Val{false}) -> Cholesky

      The same as cholfact, but saves space by overwriting the input A, instead of creating a copy. An InexactError exception is thrown if the factorization produces a number not representable by the element type of A, e.g. for integer types.

      Example

      julia> A = [1 2; 2 50]
      -2×2 Array{Int64,2}:
      - 1   2
      - 2  50
      -
      -julia> cholfact!(A)
      -ERROR: InexactError()
      source
      cholfact!(A, [uplo::Symbol,] Val{true}; tol = 0.0) -> CholeskyPivoted

      The same as cholfact, but saves space by overwriting the input A, instead of creating a copy. An InexactError exception is thrown if the factorization produces a number not representable by the element type of A, e.g. for integer types.

      source
      cholfact!(F::Factor, A; shift = 0.0) -> CHOLMOD.Factor

      Compute the Cholesky ($LL'$) factorization of A, reusing the symbolic factorization F. A must be a SparseMatrixCSC or a Symmetric/ Hermitian view of a SparseMatrixCSC. Note that even if A doesn't have the type tag, it must still be symmetric or Hermitian.

      See also cholfact.

      Note

      This method uses the CHOLMOD library from SuiteSparse, which only supports doubles or complex doubles. Input matrices not of those element types will be converted to SparseMatrixCSC{Float64} or SparseMatrixCSC{Complex128} as appropriate.

      source
      lowrankupdate(C::Cholesky, v::StridedVector) -> CC::Cholesky

      Update a Cholesky factorization C with the vector v. If A = C[:U]'C[:U] then CC = cholfact(C[:U]'C[:U] + v*v') but the computation of CC only uses O(n^2) operations.

      source
      lowrankdowndate(C::Cholesky, v::StridedVector) -> CC::Cholesky

      Downdate a Cholesky factorization C with the vector v. If A = C[:U]'C[:U] then CC = cholfact(C[:U]'C[:U] - v*v') but the computation of CC only uses O(n^2) operations.

      source
      lowrankupdate!(C::Cholesky, v::StridedVector) -> CC::Cholesky

      Update a Cholesky factorization C with the vector v. If A = C[:U]'C[:U] then CC = cholfact(C[:U]'C[:U] + v*v') but the computation of CC only uses O(n^2) operations. The input factorization C is updated in place such that on exit C == CC. The vector v is destroyed during the computation.

      source
      lowrankdowndate!(C::Cholesky, v::StridedVector) -> CC::Cholesky

      Downdate a Cholesky factorization C with the vector v. If A = C[:U]'C[:U] then CC = cholfact(C[:U]'C[:U] - v*v') but the computation of CC only uses O(n^2) operations. The input factorization C is updated in place such that on exit C == CC. The vector v is destroyed during the computation.

      source
      Base.LinAlg.ldltfactFunction.
      ldltfact(S::SymTridiagonal) -> LDLt

      Compute an LDLt factorization of a real symmetric tridiagonal matrix such that A = L*Diagonal(d)*L' where L is a unit lower triangular matrix and d is a vector. The main use of an LDLt factorization F = ldltfact(A) is to solve the linear system of equations Ax = b with F\b.

      source
      ldltfact(A; shift = 0.0, perm=Int[]) -> CHOLMOD.Factor

      Compute the $LDL'$ factorization of a sparse matrix A. A must be a SparseMatrixCSC or a Symmetric/Hermitian view of a SparseMatrixCSC. Note that even if A doesn't have the type tag, it must still be symmetric or Hermitian. A fill-reducing permutation is used. F = ldltfact(A) is most frequently used to solve systems of equations A*x = b with F\b. The returned factorization object F also supports the methods diag, det, logdet, and inv. You can extract individual factors from F using F[:L]. However, since pivoting is on by default, the factorization is internally represented as A == P'*L*D*L'*P with a permutation matrix P; using just L without accounting for P will give incorrect answers. To include the effects of permutation, it is typically preferable to extract "combined" factors like PtL = F[:PtL] (the equivalent of P'*L) and LtP = F[:UP] (the equivalent of L'*P). The complete list of supported factors is :L, :PtL, :D, :UP, :U, :LD, :DU, :PtLD, :DUP.

      Setting the optional shift keyword argument computes the factorization of A+shift*I instead of A. If the perm argument is nonempty, it should be a permutation of 1:size(A,1) giving the ordering to use (instead of CHOLMOD's default AMD ordering).

      Note

      This method uses the CHOLMOD library from SuiteSparse, which only supports doubles or complex doubles. Input matrices not of those element types will be converted to SparseMatrixCSC{Float64} or SparseMatrixCSC{Complex128} as appropriate.

      Many other functions from CHOLMOD are wrapped but not exported from the Base.SparseArrays.CHOLMOD module.

      source
      Base.LinAlg.ldltfact!Function.
      ldltfact!(S::SymTridiagonal) -> LDLt

      Same as ldltfact, but saves space by overwriting the input A, instead of creating a copy.

      source
      ldltfact!(F::Factor, A; shift = 0.0) -> CHOLMOD.Factor

      Compute the $LDL'$ factorization of A, reusing the symbolic factorization F. A must be a SparseMatrixCSC or a Symmetric/Hermitian view of a SparseMatrixCSC. Note that even if A doesn't have the type tag, it must still be symmetric or Hermitian.

      See also ldltfact.

      Note

      This method uses the CHOLMOD library from SuiteSparse, which only supports doubles or complex doubles. Input matrices not of those element types will be converted to SparseMatrixCSC{Float64} or SparseMatrixCSC{Complex128} as appropriate.

      source
      Base.LinAlg.qrFunction.
      qr(A, pivot=Val{false}; thin::Bool=true) -> Q, R, [p]

      Compute the (pivoted) QR factorization of A such that either A = Q*R or A[:,p] = Q*R. Also see qrfact. The default is to compute a thin factorization. Note that R is not extended with zeros when the full Q is requested.

      source
      qr(v::AbstractVector) -> w, r

      Computes the polar decomposition of a vector. Returns w, a unit vector in the direction of v, and r, the norm of v.

      See also normalize, normalize!, and LinAlg.qr!.

      Example

      julia> v = [1; 2]
      -2-element Array{Int64,1}:
      - 1
      - 2
      -
      -julia> w, r = qr(v)
      -([0.447214, 0.894427], 2.23606797749979)
      -
      -julia> w*r == v
      -true
      source
      Base.LinAlg.qr!Function.
      LinAlg.qr!(v::AbstractVector) -> w, r

      Computes the polar decomposition of a vector. Instead of returning a new vector as qr(v::AbstractVector), this function mutates the input vector v in place. Returns w, a unit vector in the direction of v (this is a mutation of v), and r, the norm of v.

      See also normalize, normalize!, and qr.

      source
      Base.LinAlg.qrfactFunction.
      qrfact(A) -> SPQR.Factorization

      Compute the QR factorization of a sparse matrix A. A fill-reducing permutation is used. The main application of this type is to solve least squares problems with \. The function calls the C library SPQR and a few additional functions from the library are wrapped but not exported.

      source
      qrfact(A, pivot=Val{false}) -> F

      Compute the QR factorization of the matrix A: an orthogonal (or unitary if A is complex-valued) matrix Q, and an upper triangular matrix R such that

      \[A = Q R\]

      The returned object F stores the factorization in a packed format:

      • if pivot == Val{true} then F is a QRPivoted object,

      • otherwise if the element type of A is a BLAS type (Float32, Float64, Complex64 or Complex128), then F is a QRCompactWY object,

      • otherwise F is a QR object.

      The individual components of the factorization F can be accessed by indexing with a symbol:

      • F[:Q]: the orthogonal/unitary matrix Q

      • F[:R]: the upper triangular matrix R

      • F[:p]: the permutation vector of the pivot (QRPivoted only)

      • F[:P]: the permutation matrix of the pivot (QRPivoted only)

      The following functions are available for the QR objects: inv, size, and \. When A is rectangular, \ will return a least squares solution and if the solution is not unique, the one with smallest norm is returned.

      Multiplication with respect to either thin or full Q is allowed, i.e. both F[:Q]*F[:R] and F[:Q]*A are supported. A Q matrix can be converted into a regular matrix with full which has a named argument thin.

      Example

      julia> A = [3.0 -6.0; 4.0 -8.0; 0.0 1.0]
      -3×2 Array{Float64,2}:
      - 3.0  -6.0
      - 4.0  -8.0
      - 0.0   1.0
      -
      -julia> F = qrfact(A)
      -Base.LinAlg.QRCompactWY{Float64,Array{Float64,2}} with factors Q and R:
      -[-0.6 0.0 0.8; -0.8 0.0 -0.6; 0.0 -1.0 0.0]
      -[-5.0 10.0; 0.0 -1.0]
      -
      -julia> F[:Q] * F[:R] == A
      -true
      Note

      qrfact returns multiple types because LAPACK uses several representations that minimize the memory storage requirements of products of Householder elementary reflectors, so that the Q and R matrices can be stored compactly rather as two separate dense matrices.

      source
      Base.LinAlg.qrfact!Function.
      qrfact!(A, pivot=Val{false})

      qrfact! is the same as qrfact when A is a subtype of StridedMatrix, but saves space by overwriting the input A, instead of creating a copy. An InexactError exception is thrown if the factorization produces a number not representable by the element type of A, e.g. for integer types.

      source
      Base.LinAlg.QRType.
      QR <: Factorization

      A QR matrix factorization stored in a packed format, typically obtained from qrfact. If $A$ is an m×n matrix, then

      \[A = Q R\]

      where $Q$ is an orthogonal/unitary matrix and $R$ is upper triangular. The matrix $Q$ is stored as a sequence of Householder reflectors $v_i$ and coefficients $\tau_i$ where:

      \[Q = \prod_{i=1}^{\min(m,n)} (I - \tau_i v_i v_i^T).\]

      The object has two fields:

      • factors is an m×n matrix.

        • The upper triangular part contains the elements of $R$, that is R = triu(F.factors) for a QR object F.

        • The subdiagonal part contains the reflectors $v_i$ stored in a packed format where $v_i$ is the $i$th column of the matrix V = eye(m,n) + tril(F.factors,-1).

      • τ is a vector of length min(m,n) containing the coefficients $au_i$.

      source
      QRCompactWY <: Factorization

      A QR matrix factorization stored in a compact blocked format, typically obtained from qrfact. If $A$ is an m×n matrix, then

      \[A = Q R\]

      where $Q$ is an orthogonal/unitary matrix and $R$ is upper triangular. It is similar to the QR format except that the orthogonal/unitary matrix $Q$ is stored in Compact WY format [Schreiber1989], as a lower trapezoidal matrix $V$ and an upper triangular matrix $T$ where

      \[Q = \prod_{i=1}^{\min(m,n)} (I - \tau_i v_i v_i^T) = I - V T V^T\]

      such that $v_i$ is the $i$th column of $V$, and $au_i$ is the $i$th diagonal element of $T$.

      The object has two fields:

      • factors, as in the QR type, is an m×n matrix.

        • The upper triangular part contains the elements of $R$, that is R = triu(F.factors) for a QR object F.

        • The subdiagonal part contains the reflectors $v_i$ stored in a packed format such that V = eye(m,n) + tril(F.factors,-1).

      • T is a square matrix with min(m,n) columns, whose upper triangular part gives the matrix $T$ above (the subdiagonal elements are ignored).

      Note

      This format should not to be confused with the older WY representation [Bischof1987].

      [Bischof1987]

      C Bischof and C Van Loan, "The WY representation for products of Householder matrices", SIAM J Sci Stat Comput 8 (1987), s2-s13. doi:10.1137/0908009

      [Schreiber1989]

      R Schreiber and C Van Loan, "A storage-efficient WY representation for products of Householder transformations", SIAM J Sci Stat Comput 10 (1989), 53-57. doi:10.1137/0910005

      source
      QRPivoted <: Factorization

      A QR matrix factorization with column pivoting in a packed format, typically obtained from qrfact. If $A$ is an m×n matrix, then

      \[A P = Q R\]

      where $P$ is a permutation matrix, $Q$ is an orthogonal/unitary matrix and $R$ is upper triangular. The matrix $Q$ is stored as a sequence of Householder reflectors:

      \[Q = \prod_{i=1}^{\min(m,n)} (I - \tau_i v_i v_i^T).\]

      The object has three fields:

      • factors is an m×n matrix.

        • The upper triangular part contains the elements of $R$, that is R = triu(F.factors) for a QR object F.

        • The subdiagonal part contains the reflectors $v_i$ stored in a packed format where $v_i$ is the $i$th column of the matrix V = eye(m,n) + tril(F.factors,-1).

      • τ is a vector of length min(m,n) containing the coefficients $au_i$.

      • jpvt is an integer vector of length n corresponding to the permutation $P$.

      source
      Base.LinAlg.lqfact!Function.
      lqfact!(A) -> LQ

      Compute the LQ factorization of A, using the input matrix as a workspace. See also lq.

      source
      Base.LinAlg.lqfactFunction.
      lqfact(A) -> LQ

      Compute the LQ factorization of A. See also lq.

      source
      Base.LinAlg.lqFunction.
      lq(A; [thin=true]) -> L, Q

      Perform an LQ factorization of A such that A = L*Q. The default is to compute a thin factorization. The LQ factorization is the QR factorization of A.'. L is not extended with zeros if the full Q is requested.

      source
      Base.LinAlg.bkfactFunction.
      bkfact(A, uplo::Symbol=:U, symmetric::Bool=issymmetric(A), rook::Bool=false) -> BunchKaufman

      Compute the Bunch-Kaufman [Bunch1977] factorization of a symmetric or Hermitian matrix A and return a BunchKaufman object. uplo indicates which triangle of matrix A to reference. If symmetric is true, A is assumed to be symmetric. If symmetric is false, A is assumed to be Hermitian. If rook is true, rook pivoting is used. If rook is false, rook pivoting is not used. The following functions are available for BunchKaufman objects: size, \, inv, issymmetric, ishermitian.

      [Bunch1977]

      J R Bunch and L Kaufman, Some stable methods for calculating inertia and solving symmetric linear systems, Mathematics of Computation 31:137 (1977), 163-179. url.

      source
      Base.LinAlg.bkfact!Function.
      bkfact!(A, uplo::Symbol=:U, symmetric::Bool=issymmetric(A), rook::Bool=false) -> BunchKaufman

      bkfact! is the same as bkfact, but saves space by overwriting the input A, instead of creating a copy.

      source
      Base.LinAlg.eigFunction.
      eig(A::Union{SymTridiagonal, Hermitian, Symmetric}, irange::UnitRange) -> D, V
      -eig(A::Union{SymTridiagonal, Hermitian, Symmetric}, vl::Real, vu::Real) -> D, V
      -eig(A, permute::Bool=true, scale::Bool=true) -> D, V

      Computes eigenvalues (D) and eigenvectors (V) of A. See eigfact for details on the irange, vl, and vu arguments (for SymTridiagonal, Hermitian, and Symmetric matrices) and the permute and scale keyword arguments. The eigenvectors are returned columnwise.

      Example

      julia> eig([1.0 0.0 0.0; 0.0 3.0 0.0; 0.0 0.0 18.0])
      -([1.0, 3.0, 18.0], [1.0 0.0 0.0; 0.0 1.0 0.0; 0.0 0.0 1.0])

      eig is a wrapper around eigfact, extracting all parts of the factorization to a tuple; where possible, using eigfact is recommended.

      source
      eig(A, B) -> D, V

      Computes generalized eigenvalues (D) and vectors (V) of A with respect to B.

      eig is a wrapper around eigfact, extracting all parts of the factorization to a tuple; where possible, using eigfact is recommended.

      Example

      julia> A = [1 0; 0 -1]
      -2×2 Array{Int64,2}:
      - 1   0
      - 0  -1
      -
      -julia> B = [0 1; 1 0]
      -2×2 Array{Int64,2}:
      - 0  1
      - 1  0
      -
      -julia> eig(A, B)
      -(Complex{Float64}[0.0+1.0im, 0.0-1.0im], Complex{Float64}[0.0-1.0im 0.0+1.0im; -1.0-0.0im -1.0+0.0im])
      source
      Base.LinAlg.eigvalsFunction.
      eigvals(A; permute::Bool=true, scale::Bool=true) -> values

      Returns the eigenvalues of A.

      For general non-symmetric matrices it is possible to specify how the matrix is balanced before the eigenvalue calculation. The option permute=true permutes the matrix to become closer to upper triangular, and scale=true scales the matrix by its diagonal elements to make rows and columns more equal in norm. The default is true for both options.

      source
      eigvals(A, B) -> values

      Computes the generalized eigenvalues of A and B.

      Example

      julia> A = [1 0; 0 -1]
      -2×2 Array{Int64,2}:
      - 1   0
      - 0  -1
      -
      -julia> B = [0 1; 1 0]
      -2×2 Array{Int64,2}:
      - 0  1
      - 1  0
      -
      -julia> eigvals(A,B)
      -2-element Array{Complex{Float64},1}:
      - 0.0+1.0im
      - 0.0-1.0im
      source
      eigvals(A::Union{SymTridiagonal, Hermitian, Symmetric}, irange::UnitRange) -> values

      Returns the eigenvalues of A. It is possible to calculate only a subset of the eigenvalues by specifying a UnitRange irange covering indices of the sorted eigenvalues, e.g. the 2nd to 8th eigenvalues.

      julia> A = SymTridiagonal([1.; 2.; 1.], [2.; 3.])
      -3×3 SymTridiagonal{Float64}:
      - 1.0  2.0   ⋅
      - 2.0  2.0  3.0
      -  ⋅   3.0  1.0
      -
      -julia> eigvals(A, 2:2)
      -1-element Array{Float64,1}:
      - 1.0
      -
      -julia> eigvals(A)
      -3-element Array{Float64,1}:
      - -2.14005
      -  1.0
      -  5.14005
      source
      eigvals(A::Union{SymTridiagonal, Hermitian, Symmetric}, vl::Real, vu::Real) -> values

      Returns the eigenvalues of A. It is possible to calculate only a subset of the eigenvalues by specifying a pair vl and vu for the lower and upper boundaries of the eigenvalues.

      julia> A = SymTridiagonal([1.; 2.; 1.], [2.; 3.])
      -3×3 SymTridiagonal{Float64}:
      - 1.0  2.0   ⋅
      - 2.0  2.0  3.0
      -  ⋅   3.0  1.0
      -
      -julia> eigvals(A, -1, 2)
      -1-element Array{Float64,1}:
      - 1.0
      -
      -julia> eigvals(A)
      -3-element Array{Float64,1}:
      - -2.14005
      -  1.0
      -  5.14005
      source
      Base.LinAlg.eigvals!Function.
      eigvals!(A; permute::Bool=true, scale::Bool=true) -> values

      Same as eigvals, but saves space by overwriting the input A, instead of creating a copy. The option permute=true permutes the matrix to become closer to upper triangular, and scale=true scales the matrix by its diagonal elements to make rows and columns more equal in norm.

      source
      eigvals!(A, B) -> values

      Same as eigvals, but saves space by overwriting the input A (and B), instead of creating copies.

      source
      eigvals!(A::Union{SymTridiagonal, Hermitian, Symmetric}, irange::UnitRange) -> values

      Same as eigvals, but saves space by overwriting the input A, instead of creating a copy. irange is a range of eigenvalue indices to search for - for instance, the 2nd to 8th eigenvalues.

      source
      eigvals!(A::Union{SymTridiagonal, Hermitian, Symmetric}, vl::Real, vu::Real) -> values

      Same as eigvals, but saves space by overwriting the input A, instead of creating a copy. vl is the lower bound of the interval to search for eigenvalues, and vu is the upper bound.

      source
      Base.LinAlg.eigmaxFunction.
      eigmax(A; permute::Bool=true, scale::Bool=true)

      Returns the largest eigenvalue of A. The option permute=true permutes the matrix to become closer to upper triangular, and scale=true scales the matrix by its diagonal elements to make rows and columns more equal in norm. Note that if the eigenvalues of A are complex, this method will fail, since complex numbers cannot be sorted.

      Example

      julia> A = [0 im; -im 0]
      -2×2 Array{Complex{Int64},2}:
      - 0+0im  0+1im
      - 0-1im  0+0im
      -
      -julia> eigmax(A)
      -1.0
      -
      -julia> A = [0 im; -1 0]
      -2×2 Array{Complex{Int64},2}:
      -  0+0im  0+1im
      - -1+0im  0+0im
      -
      -julia> eigmax(A)
      -ERROR: DomainError:
      -Stacktrace:
      - [1] #eigmax#46(::Bool, ::Bool, ::Function, ::Array{Complex{Int64},2}) at ./linalg/eigen.jl:238
      - [2] eigmax(::Array{Complex{Int64},2}) at ./linalg/eigen.jl:236
      source
      Base.LinAlg.eigminFunction.
      eigmin(A; permute::Bool=true, scale::Bool=true)

      Returns the smallest eigenvalue of A. The option permute=true permutes the matrix to become closer to upper triangular, and scale=true scales the matrix by its diagonal elements to make rows and columns more equal in norm. Note that if the eigenvalues of A are complex, this method will fail, since complex numbers cannot be sorted.

      Example

      julia> A = [0 im; -im 0]
      -2×2 Array{Complex{Int64},2}:
      - 0+0im  0+1im
      - 0-1im  0+0im
      -
      -julia> eigmin(A)
      --1.0
      -
      -julia> A = [0 im; -1 0]
      -2×2 Array{Complex{Int64},2}:
      -  0+0im  0+1im
      - -1+0im  0+0im
      -
      -julia> eigmin(A)
      -ERROR: DomainError:
      -Stacktrace:
      - [1] #eigmin#47(::Bool, ::Bool, ::Function, ::Array{Complex{Int64},2}) at ./linalg/eigen.jl:280
      - [2] eigmin(::Array{Complex{Int64},2}) at ./linalg/eigen.jl:278
      source
      Base.LinAlg.eigvecsFunction.
      eigvecs(A::SymTridiagonal[, eigvals]) -> Matrix

      Returns a matrix M whose columns are the eigenvectors of A. (The kth eigenvector can be obtained from the slice M[:, k].)

      If the optional vector of eigenvalues eigvals is specified, eigvecs returns the specific corresponding eigenvectors.

      Example

      julia> A = SymTridiagonal([1.; 2.; 1.], [2.; 3.])
      -3×3 SymTridiagonal{Float64}:
      - 1.0  2.0   ⋅
      - 2.0  2.0  3.0
      -  ⋅   3.0  1.0
      -
      -julia> eigvals(A)
      -3-element Array{Float64,1}:
      - -2.14005
      -  1.0
      -  5.14005
      -
      -julia> eigvecs(A)
      -3×3 Array{Float64,2}:
      -  0.418304  -0.83205      0.364299
      - -0.656749  -7.39009e-16  0.754109
      -  0.627457   0.5547       0.546448
      -
      -julia> eigvecs(A, [1.])
      -3×1 Array{Float64,2}:
      -  0.83205
      -  4.26351e-17
      - -0.5547
      source
      eigvecs(A; permute::Bool=true, scale::Bool=true) -> Matrix

      Returns a matrix M whose columns are the eigenvectors of A. (The kth eigenvector can be obtained from the slice M[:, k].) The permute and scale keywords are the same as for eigfact.

      Example

      julia> eigvecs([1.0 0.0 0.0; 0.0 3.0 0.0; 0.0 0.0 18.0])
      -3×3 Array{Float64,2}:
      - 1.0  0.0  0.0
      - 0.0  1.0  0.0
      - 0.0  0.0  1.0
      source
      eigvecs(A, B) -> Matrix

      Returns a matrix M whose columns are the generalized eigenvectors of A and B. (The kth eigenvector can be obtained from the slice M[:, k].)

      Example

      julia> A = [1 0; 0 -1]
      -2×2 Array{Int64,2}:
      - 1   0
      - 0  -1
      -
      -julia> B = [0 1; 1 0]
      -2×2 Array{Int64,2}:
      - 0  1
      - 1  0
      -
      -julia> eigvecs(A, B)
      -2×2 Array{Complex{Float64},2}:
      -  0.0-1.0im   0.0+1.0im
      - -1.0-0.0im  -1.0+0.0im
      source
      Base.LinAlg.eigfactFunction.
      eigfact(A; permute::Bool=true, scale::Bool=true) -> Eigen

      Computes the eigenvalue decomposition of A, returning an Eigen factorization object F which contains the eigenvalues in F[:values] and the eigenvectors in the columns of the matrix F[:vectors]. (The kth eigenvector can be obtained from the slice F[:vectors][:, k].)

      The following functions are available for Eigen objects: inv, det, and isposdef.

      For general nonsymmetric matrices it is possible to specify how the matrix is balanced before the eigenvector calculation. The option permute=true permutes the matrix to become closer to upper triangular, and scale=true scales the matrix by its diagonal elements to make rows and columns more equal in norm. The default is true for both options.

      Example

      julia> F = eigfact([1.0 0.0 0.0; 0.0 3.0 0.0; 0.0 0.0 18.0])
      -Base.LinAlg.Eigen{Float64,Float64,Array{Float64,2},Array{Float64,1}}([1.0, 3.0, 18.0], [1.0 0.0 0.0; 0.0 1.0 0.0; 0.0 0.0 1.0])
      -
      -julia> F[:values]
      -3-element Array{Float64,1}:
      -  1.0
      -  3.0
      - 18.0
      -
      -julia> F[:vectors]
      -3×3 Array{Float64,2}:
      - 1.0  0.0  0.0
      - 0.0  1.0  0.0
      - 0.0  0.0  1.0
      source
      eigfact(A, B) -> GeneralizedEigen

      Computes the generalized eigenvalue decomposition of A and B, returning a GeneralizedEigen factorization object F which contains the generalized eigenvalues in F[:values] and the generalized eigenvectors in the columns of the matrix F[:vectors]. (The kth generalized eigenvector can be obtained from the slice F[:vectors][:, k].)

      source
      eigfact(A::Union{SymTridiagonal, Hermitian, Symmetric}, irange::UnitRange) -> Eigen

      Computes the eigenvalue decomposition of A, returning an Eigen factorization object F which contains the eigenvalues in F[:values] and the eigenvectors in the columns of the matrix F[:vectors]. (The kth eigenvector can be obtained from the slice F[:vectors][:, k].)

      The following functions are available for Eigen objects: inv, det, and isposdef.

      The UnitRange irange specifies indices of the sorted eigenvalues to search for.

      Note

      If irange is not 1:n, where n is the dimension of A, then the returned factorization will be a truncated factorization.

      source
      eigfact(A::Union{SymTridiagonal, Hermitian, Symmetric}, vl::Real, vu::Real) -> Eigen

      Computes the eigenvalue decomposition of A, returning an Eigen factorization object F which contains the eigenvalues in F[:values] and the eigenvectors in the columns of the matrix F[:vectors]. (The kth eigenvector can be obtained from the slice F[:vectors][:, k].)

      The following functions are available for Eigen objects: inv, det, and isposdef.

      vl is the lower bound of the window of eigenvalues to search for, and vu is the upper bound.

      Note

      If [vl, vu] does not contain all eigenvalues of A, then the returned factorization will be a truncated factorization.

      source
      Base.LinAlg.eigfact!Function.
      eigfact!(A, [B])

      Same as eigfact, but saves space by overwriting the input A (and B), instead of creating a copy.

      source
      Base.LinAlg.hessfactFunction.
      hessfact(A) -> Hessenberg

      Compute the Hessenberg decomposition of A and return a Hessenberg object. If F is the factorization object, the unitary matrix can be accessed with F[:Q] and the Hessenberg matrix with F[:H]. When Q is extracted, the resulting type is the HessenbergQ object, and may be converted to a regular matrix with convert(Array, _) (or Array(_) for short).

      Example

      julia> A = [4. 9. 7.; 4. 4. 1.; 4. 3. 2.]
      -3×3 Array{Float64,2}:
      - 4.0  9.0  7.0
      - 4.0  4.0  1.0
      - 4.0  3.0  2.0
      -
      -julia> F = hessfact(A);
      -
      -julia> F[:Q] * F[:H] * F[:Q]'
      -3×3 Array{Float64,2}:
      - 4.0  9.0  7.0
      - 4.0  4.0  1.0
      - 4.0  3.0  2.0
      source
      Base.LinAlg.hessfact!Function.
      hessfact!(A) -> Hessenberg

      hessfact! is the same as hessfact, but saves space by overwriting the input A, instead of creating a copy.

      source
      Base.LinAlg.schurfactFunction.
      schurfact(A::StridedMatrix) -> F::Schur

      Computes the Schur factorization of the matrix A. The (quasi) triangular Schur factor can be obtained from the Schur object F with either F[:Schur] or F[:T] and the orthogonal/unitary Schur vectors can be obtained with F[:vectors] or F[:Z] such that A = F[:vectors]*F[:Schur]*F[:vectors]'. The eigenvalues of A can be obtained with F[:values].

      Example

      julia> A = [-2. 1. 3.; 2. 1. -1.; -7. 2. 7.]
      -3×3 Array{Float64,2}:
      - -2.0  1.0   3.0
      -  2.0  1.0  -1.0
      - -7.0  2.0   7.0
      -
      -julia> F = schurfact(A)
      -Base.LinAlg.Schur{Float64,Array{Float64,2}} with factors T and Z:
      -[2.0 0.801792 6.63509; -8.55988e-11 2.0 8.08286; 0.0 0.0 1.99999]
      -[0.577351 0.154299 -0.801784; 0.577346 -0.77152 0.267262; 0.577354 0.617211 0.534522]
      -and values:
      -Complex{Float64}[2.0+8.28447e-6im, 2.0-8.28447e-6im, 1.99999+0.0im]
      -
      -julia> F[:vectors] * F[:Schur] * F[:vectors]'
      -3×3 Array{Float64,2}:
      - -2.0  1.0   3.0
      -  2.0  1.0  -1.0
      - -7.0  2.0   7.0
      source
      schurfact(A::StridedMatrix, B::StridedMatrix) -> F::GeneralizedSchur

      Computes the Generalized Schur (or QZ) factorization of the matrices A and B. The (quasi) triangular Schur factors can be obtained from the Schur object F with F[:S] and F[:T], the left unitary/orthogonal Schur vectors can be obtained with F[:left] or F[:Q] and the right unitary/orthogonal Schur vectors can be obtained with F[:right] or F[:Z] such that A=F[:left]*F[:S]*F[:right]' and B=F[:left]*F[:T]*F[:right]'. The generalized eigenvalues of A and B can be obtained with F[:alpha]./F[:beta].

      source
      schurfact!(A::StridedMatrix) -> F::Schur

      Same as schurfact but uses the input argument as workspace.

      source
      schurfact!(A::StridedMatrix, B::StridedMatrix) -> F::GeneralizedSchur

      Same as schurfact but uses the input matrices A and B as workspace.

      source
      Base.LinAlg.schurFunction.
      schur(A::StridedMatrix) -> T::Matrix, Z::Matrix, λ::Vector

      Computes the Schur factorization of the matrix A. The methods return the (quasi) triangular Schur factor T and the orthogonal/unitary Schur vectors Z such that A = Z*T*Z'. The eigenvalues of A are returned in the vector λ.

      See schurfact.

      Example

      julia> A = [-2. 1. 3.; 2. 1. -1.; -7. 2. 7.]
      -3×3 Array{Float64,2}:
      - -2.0  1.0   3.0
      -  2.0  1.0  -1.0
      - -7.0  2.0   7.0
      -
      -julia> T, Z, lambda = schur(A)
      -([2.0 0.801792 6.63509; -8.55988e-11 2.0 8.08286; 0.0 0.0 1.99999], [0.577351 0.154299 -0.801784; 0.577346 -0.77152 0.267262; 0.577354 0.617211 0.534522], Complex{Float64}[2.0+8.28447e-6im, 2.0-8.28447e-6im, 1.99999+0.0im])
      -
      -julia> Z * T * Z'
      -3×3 Array{Float64,2}:
      - -2.0  1.0   3.0
      -  2.0  1.0  -1.0
      - -7.0  2.0   7.0
      source
      schur(A::StridedMatrix, B::StridedMatrix) -> S::StridedMatrix, T::StridedMatrix, Q::StridedMatrix, Z::StridedMatrix, α::Vector, β::Vector

      See schurfact.

      source
      Base.LinAlg.ordschurFunction.
      ordschur(F::Schur, select::Union{Vector{Bool},BitVector}) -> F::Schur

      Reorders the Schur factorization F of a matrix A = Z*T*Z' according to the logical array select returning the reordered factorization F object. The selected eigenvalues appear in the leading diagonal of F[:Schur] and the corresponding leading columns of F[:vectors] form an orthogonal/unitary basis of the corresponding right invariant subspace. In the real case, a complex conjugate pair of eigenvalues must be either both included or both excluded via select.

      source
      ordschur(T::StridedMatrix, Z::StridedMatrix, select::Union{Vector{Bool},BitVector}) -> T::StridedMatrix, Z::StridedMatrix, λ::Vector

      Reorders the Schur factorization of a real matrix A = Z*T*Z' according to the logical array select returning the reordered matrices T and Z as well as the vector of eigenvalues λ. The selected eigenvalues appear in the leading diagonal of T and the corresponding leading columns of Z form an orthogonal/unitary basis of the corresponding right invariant subspace. In the real case, a complex conjugate pair of eigenvalues must be either both included or both excluded via select.

      source
      ordschur(F::GeneralizedSchur, select::Union{Vector{Bool},BitVector}) -> F::GeneralizedSchur

      Reorders the Generalized Schur factorization F of a matrix pair (A, B) = (Q*S*Z', Q*T*Z') according to the logical array select and returns a GeneralizedSchur object F. The selected eigenvalues appear in the leading diagonal of both F[:S] and F[:T], and the left and right orthogonal/unitary Schur vectors are also reordered such that (A, B) = F[:Q]*(F[:S], F[:T])*F[:Z]' still holds and the generalized eigenvalues of A and B can still be obtained with F[:alpha]./F[:beta].

      source
      ordschur(S::StridedMatrix, T::StridedMatrix, Q::StridedMatrix, Z::StridedMatrix, select) -> S::StridedMatrix, T::StridedMatrix, Q::StridedMatrix, Z::StridedMatrix, α::Vector, β::Vector

      Reorders the Generalized Schur factorization of a matrix pair (A, B) = (Q*S*Z', Q*T*Z') according to the logical array select and returns the matrices S, T, Q, Z and vectors α and β. The selected eigenvalues appear in the leading diagonal of both S and T, and the left and right unitary/orthogonal Schur vectors are also reordered such that (A, B) = Q*(S, T)*Z' still holds and the generalized eigenvalues of A and B can still be obtained with α./β.

      source
      Base.LinAlg.ordschur!Function.
      ordschur!(F::Schur, select::Union{Vector{Bool},BitVector}) -> F::Schur

      Same as ordschur but overwrites the factorization F.

      source
      ordschur!(T::StridedMatrix, Z::StridedMatrix, select::Union{Vector{Bool},BitVector}) -> T::StridedMatrix, Z::StridedMatrix, λ::Vector

      Same as ordschur but overwrites the input arguments.

      source
      ordschur!(F::GeneralizedSchur, select::Union{Vector{Bool},BitVector}) -> F::GeneralizedSchur

      Same as ordschur but overwrites the factorization F.

      source
      ordschur!(S::StridedMatrix, T::StridedMatrix, Q::StridedMatrix, Z::StridedMatrix, select) -> S::StridedMatrix, T::StridedMatrix, Q::StridedMatrix, Z::StridedMatrix, α::Vector, β::Vector

      Same as ordschur but overwrites the factorization the input arguments.

      source
      Base.LinAlg.svdfactFunction.
      svdfact(A; thin::Bool=true) -> SVD

      Compute the singular value decomposition (SVD) of A and return an SVD object.

      U, S, V and Vt can be obtained from the factorization F with F[:U], F[:S], F[:V] and F[:Vt], such that A = U*diagm(S)*Vt. The algorithm produces Vt and hence Vt is more efficient to extract than V. The singular values in S are sorted in descending order.

      If thin=true (default), a thin SVD is returned. For a $M \times N$ matrix A, U is $M \times M$ for a full SVD (thin=false) and $M \times \min(M, N)$ for a thin SVD.

      Example

      julia> A = [1. 0. 0. 0. 2.; 0. 0. 3. 0. 0.; 0. 0. 0. 0. 0.; 0. 2. 0. 0. 0.]
      -4×5 Array{Float64,2}:
      - 1.0  0.0  0.0  0.0  2.0
      - 0.0  0.0  3.0  0.0  0.0
      - 0.0  0.0  0.0  0.0  0.0
      - 0.0  2.0  0.0  0.0  0.0
      -
      -julia> F = svdfact(A)
      -Base.LinAlg.SVD{Float64,Float64,Array{Float64,2}}([0.0 1.0 0.0 0.0; 1.0 0.0 0.0 0.0; 0.0 0.0 0.0 -1.0; 0.0 0.0 1.0 0.0], [3.0, 2.23607, 2.0, 0.0], [-0.0 0.0 … -0.0 0.0; 0.447214 0.0 … 0.0 0.894427; -0.0 1.0 … -0.0 0.0; 0.0 0.0 … 1.0 0.0])
      -
      -julia> F[:U] * diagm(F[:S]) * F[:Vt]
      -4×5 Array{Float64,2}:
      - 1.0  0.0  0.0  0.0  2.0
      - 0.0  0.0  3.0  0.0  0.0
      - 0.0  0.0  0.0  0.0  0.0
      - 0.0  2.0  0.0  0.0  0.0
      source
      svdfact(A, B) -> GeneralizedSVD

      Compute the generalized SVD of A and B, returning a GeneralizedSVD factorization object F, such that A = F[:U]*F[:D1]*F[:R0]*F[:Q]' and B = F[:V]*F[:D2]*F[:R0]*F[:Q]'.

      For an M-by-N matrix A and P-by-N matrix B,

      • F[:U] is a M-by-M orthogonal matrix,

      • F[:V] is a P-by-P orthogonal matrix,

      • F[:Q] is a N-by-N orthogonal matrix,

      • F[:R0] is a (K+L)-by-N matrix whose rightmost (K+L)-by-(K+L) block is nonsingular upper block triangular,

      • F[:D1] is a M-by-(K+L) diagonal matrix with 1s in the first K entries,

      • F[:D2] is a P-by-(K+L) matrix whose top right L-by-L block is diagonal,

      K+L is the effective numerical rank of the matrix [A; B].

      The entries of F[:D1] and F[:D2] are related, as explained in the LAPACK documentation for the generalized SVD and the xGGSVD3 routine which is called underneath (in LAPACK 3.6.0 and newer).

      source
      Base.LinAlg.svdfact!Function.
      svdfact!(A, thin::Bool=true) -> SVD

      svdfact! is the same as svdfact, but saves space by overwriting the input A, instead of creating a copy.

      source
      svdfact!(A, B) -> GeneralizedSVD

      svdfact! is the same as svdfact, but modifies the arguments A and B in-place, instead of making copies.

      source
      Base.LinAlg.svdFunction.
      svd(A; thin::Bool=true) -> U, S, V

      Computes the SVD of A, returning U, vector S, and V such that A == U*diagm(S)*V'. The singular values in S are sorted in descending order.

      If thin=true (default), a thin SVD is returned. For a $M \times N$ matrix A, U is $M \times M$ for a full SVD (thin=false) and $M \times \min(M, N)$ for a thin SVD.

      svd is a wrapper around svdfact, extracting all parts of the SVD factorization to a tuple. Direct use of svdfact is therefore more efficient.

      Example

      julia> A = [1. 0. 0. 0. 2.; 0. 0. 3. 0. 0.; 0. 0. 0. 0. 0.; 0. 2. 0. 0. 0.]
      -4×5 Array{Float64,2}:
      - 1.0  0.0  0.0  0.0  2.0
      - 0.0  0.0  3.0  0.0  0.0
      - 0.0  0.0  0.0  0.0  0.0
      - 0.0  2.0  0.0  0.0  0.0
      -
      -julia> U, S, V = svd(A)
      -([0.0 1.0 0.0 0.0; 1.0 0.0 0.0 0.0; 0.0 0.0 0.0 -1.0; 0.0 0.0 1.0 0.0], [3.0, 2.23607, 2.0, 0.0], [-0.0 0.447214 -0.0 0.0; 0.0 0.0 1.0 0.0; … ; -0.0 0.0 -0.0 1.0; 0.0 0.894427 0.0 0.0])
      -
      -julia> U*diagm(S)*V'
      -4×5 Array{Float64,2}:
      - 1.0  0.0  0.0  0.0  2.0
      - 0.0  0.0  3.0  0.0  0.0
      - 0.0  0.0  0.0  0.0  0.0
      - 0.0  2.0  0.0  0.0  0.0
      source
      svd(A, B) -> U, V, Q, D1, D2, R0

      Wrapper around svdfact extracting all parts of the factorization to a tuple. Direct use of svdfact is therefore generally more efficient. The function returns the generalized SVD of A and B, returning U, V, Q, D1, D2, and R0 such that A = U*D1*R0*Q' and B = V*D2*R0*Q'.

      source
      Base.LinAlg.svdvalsFunction.
      svdvals(A)

      Returns the singular values of A in descending order.

      Example

      julia> A = [1. 0. 0. 0. 2.; 0. 0. 3. 0. 0.; 0. 0. 0. 0. 0.; 0. 2. 0. 0. 0.]
      -4×5 Array{Float64,2}:
      - 1.0  0.0  0.0  0.0  2.0
      - 0.0  0.0  3.0  0.0  0.0
      - 0.0  0.0  0.0  0.0  0.0
      - 0.0  2.0  0.0  0.0  0.0
      -
      -julia> svdvals(A)
      -4-element Array{Float64,1}:
      - 3.0
      - 2.23607
      - 2.0
      - 0.0
      source
      svdvals(A, B)

      Return the generalized singular values from the generalized singular value decomposition of A and B. See also svdfact.

      source
      LinAlg.Givens(i1,i2,c,s) -> G

      A Givens rotation linear operator. The fields c and s represent the cosine and sine of the rotation angle, respectively. The Givens type supports left multiplication G*A and conjugated transpose right multiplication A*G'. The type doesn't have a size and can therefore be multiplied with matrices of arbitrary size as long as i2<=size(A,2) for G*A or i2<=size(A,1) for A*G'.

      See also: givens

      source
      Base.LinAlg.givensFunction.
      givens{T}(f::T, g::T, i1::Integer, i2::Integer) -> (G::Givens, r::T)

      Computes the Givens rotation G and scalar r such that for any vector x where

      x[i1] = f
      -x[i2] = g

      the result of the multiplication

      y = G*x

      has the property that

      y[i1] = r
      -y[i2] = 0

      See also: LinAlg.Givens

      source
      givens(A::AbstractArray, i1::Integer, i2::Integer, j::Integer) -> (G::Givens, r)

      Computes the Givens rotation G and scalar r such that the result of the multiplication

      B = G*A

      has the property that

      B[i1,j] = r
      -B[i2,j] = 0

      See also: LinAlg.Givens

      source
      givens(x::AbstractVector, i1::Integer, i2::Integer) -> (G::Givens, r)

      Computes the Givens rotation G and scalar r such that the result of the multiplication

      B = G*x

      has the property that

      B[i1] = r
      -B[i2] = 0

      See also: LinAlg.Givens

      source
      Base.LinAlg.triuFunction.
      triu(M)

      Upper triangle of a matrix.

      Example

      julia> a = ones(4,4)
      -4×4 Array{Float64,2}:
      - 1.0  1.0  1.0  1.0
      - 1.0  1.0  1.0  1.0
      - 1.0  1.0  1.0  1.0
      - 1.0  1.0  1.0  1.0
      -
      -julia> triu(a)
      -4×4 Array{Float64,2}:
      - 1.0  1.0  1.0  1.0
      - 0.0  1.0  1.0  1.0
      - 0.0  0.0  1.0  1.0
      - 0.0  0.0  0.0  1.0
      source
      triu(M, k::Integer)

      Returns the upper triangle of M starting from the kth superdiagonal.

      Example

      julia> a = ones(4,4)
      -4×4 Array{Float64,2}:
      - 1.0  1.0  1.0  1.0
      - 1.0  1.0  1.0  1.0
      - 1.0  1.0  1.0  1.0
      - 1.0  1.0  1.0  1.0
      -
      -julia> triu(a,3)
      -4×4 Array{Float64,2}:
      - 0.0  0.0  0.0  1.0
      - 0.0  0.0  0.0  0.0
      - 0.0  0.0  0.0  0.0
      - 0.0  0.0  0.0  0.0
      -
      -julia> triu(a,-3)
      -4×4 Array{Float64,2}:
      - 1.0  1.0  1.0  1.0
      - 1.0  1.0  1.0  1.0
      - 1.0  1.0  1.0  1.0
      - 1.0  1.0  1.0  1.0
      source
      Base.LinAlg.triu!Function.
      triu!(M)

      Upper triangle of a matrix, overwriting M in the process. See also triu.

      source
      triu!(M, k::Integer)

      Returns the upper triangle of M starting from the kth superdiagonal, overwriting M in the process.

      Example

      julia> M = [1 2 3 4 5; 1 2 3 4 5; 1 2 3 4 5; 1 2 3 4 5; 1 2 3 4 5]
      -5×5 Array{Int64,2}:
      - 1  2  3  4  5
      - 1  2  3  4  5
      - 1  2  3  4  5
      - 1  2  3  4  5
      - 1  2  3  4  5
      -
      -julia> triu!(M, 1)
      -5×5 Array{Int64,2}:
      - 0  2  3  4  5
      - 0  0  3  4  5
      - 0  0  0  4  5
      - 0  0  0  0  5
      - 0  0  0  0  0
      source
      Base.LinAlg.trilFunction.
      tril(M)

      Lower triangle of a matrix.

      Example

      julia> a = ones(4,4)
      -4×4 Array{Float64,2}:
      - 1.0  1.0  1.0  1.0
      - 1.0  1.0  1.0  1.0
      - 1.0  1.0  1.0  1.0
      - 1.0  1.0  1.0  1.0
      -
      -julia> tril(a)
      -4×4 Array{Float64,2}:
      - 1.0  0.0  0.0  0.0
      - 1.0  1.0  0.0  0.0
      - 1.0  1.0  1.0  0.0
      - 1.0  1.0  1.0  1.0
      source
      tril(M, k::Integer)

      Returns the lower triangle of M starting from the kth superdiagonal.

      Example

      julia> a = ones(4,4)
      -4×4 Array{Float64,2}:
      - 1.0  1.0  1.0  1.0
      - 1.0  1.0  1.0  1.0
      - 1.0  1.0  1.0  1.0
      - 1.0  1.0  1.0  1.0
      -
      -julia> tril(a,3)
      -4×4 Array{Float64,2}:
      - 1.0  1.0  1.0  1.0
      - 1.0  1.0  1.0  1.0
      - 1.0  1.0  1.0  1.0
      - 1.0  1.0  1.0  1.0
      -
      -julia> tril(a,-3)
      -4×4 Array{Float64,2}:
      - 0.0  0.0  0.0  0.0
      - 0.0  0.0  0.0  0.0
      - 0.0  0.0  0.0  0.0
      - 1.0  0.0  0.0  0.0
      source
      Base.LinAlg.tril!Function.
      tril!(M)

      Lower triangle of a matrix, overwriting M in the process. See also tril.

      source
      tril!(M, k::Integer)

      Returns the lower triangle of M starting from the kth superdiagonal, overwriting M in the process.

      Example

      julia> M = [1 2 3 4 5; 1 2 3 4 5; 1 2 3 4 5; 1 2 3 4 5; 1 2 3 4 5]
      -5×5 Array{Int64,2}:
      - 1  2  3  4  5
      - 1  2  3  4  5
      - 1  2  3  4  5
      - 1  2  3  4  5
      - 1  2  3  4  5
      -
      -julia> tril!(M, 2)
      -5×5 Array{Int64,2}:
      - 1  2  3  0  0
      - 1  2  3  4  0
      - 1  2  3  4  5
      - 1  2  3  4  5
      - 1  2  3  4  5
      source
      Base.LinAlg.diagindFunction.
      diagind(M, k::Integer=0)

      A Range giving the indices of the kth diagonal of the matrix M.

      Example

      julia> A = [1 2 3; 4 5 6; 7 8 9]
      -3×3 Array{Int64,2}:
      - 1  2  3
      - 4  5  6
      - 7  8  9
      -
      -julia> diagind(A,-1)
      -2:4:6
      source
      Base.LinAlg.diagFunction.
      diag(M, k::Integer=0)

      The kth diagonal of a matrix, as a vector. Use diagm to construct a diagonal matrix.

      Example

      julia> A = [1 2 3; 4 5 6; 7 8 9]
      -3×3 Array{Int64,2}:
      - 1  2  3
      - 4  5  6
      - 7  8  9
      -
      -julia> diag(A,1)
      -2-element Array{Int64,1}:
      - 2
      - 6
      source
      Base.LinAlg.diagmFunction.
      diagm(v, k::Integer=0)

      Construct a matrix by placing v on the kth diagonal.

      Example

      julia> diagm([1,2,3],1)
      -4×4 Array{Int64,2}:
      - 0  1  0  0
      - 0  0  2  0
      - 0  0  0  3
      - 0  0  0  0
      source
      Base.LinAlg.scale!Function.
      scale!(A, b)
      -scale!(b, A)

      Scale an array A by a scalar b overwriting A in-place.

      If A is a matrix and b is a vector, then scale!(A,b) scales each column i of A by b[i] (similar to A*Diagonal(b)), while scale!(b,A) scales each row i of A by b[i] (similar to Diagonal(b)*A), again operating in-place on A. An InexactError exception is thrown if the scaling produces a number not representable by the element type of A, e.g. for integer types.

      Example

      julia> a = [1 2; 3 4]
      -2×2 Array{Int64,2}:
      - 1  2
      - 3  4
      -
      -julia> b = [1; 2]
      -2-element Array{Int64,1}:
      - 1
      - 2
      -
      -julia> scale!(a,b)
      -2×2 Array{Int64,2}:
      - 1  4
      - 3  8
      -
      -julia> a = [1 2; 3 4];
      -
      -julia> b = [1; 2];
      -
      -julia> scale!(b,a)
      -2×2 Array{Int64,2}:
      - 1  2
      - 6  8
      source
      Base.LinAlg.rankFunction.
      rank(M[, tol::Real])

      Compute the rank of a matrix by counting how many singular values of M have magnitude greater than tol. By default, the value of tol is the largest dimension of M multiplied by the eps of the eltype of M.

      Example

      julia> rank(eye(3))
      -3
      -
      -julia> rank(diagm([1, 0, 2]))
      -2
      -
      -julia> rank(diagm([1, 0.001, 2]), 0.1)
      -2
      -
      -julia> rank(diagm([1, 0.001, 2]), 0.00001)
      -3
      source
      Base.LinAlg.normFunction.
      norm(A::AbstractArray, p::Real=2)

      Compute the p-norm of a vector or the operator norm of a matrix A, defaulting to the 2-norm.

      norm(A::AbstractVector, p::Real=2)

      For vectors, this is equivalent to vecnorm and equal to:

      \[\|A\|_p = \left( \sum_{i=1}^n | a_i | ^p \right)^{1/p}\]

      with $a_i$ the entries of $A$ and $n$ its length.

      p can assume any numeric value (even though not all values produce a mathematically valid vector norm). In particular, norm(A, Inf) returns the largest value in abs(A), whereas norm(A, -Inf) returns the smallest.

      Example

      julia> v = [3, -2, 6]
      -3-element Array{Int64,1}:
      -  3
      - -2
      -  6
      -
      -julia> norm(v)
      -7.0
      -
      -julia> norm(v, Inf)
      -6.0
      source
      norm(A::AbstractMatrix, p::Real=2)

      For matrices, the matrix norm induced by the vector p-norm is used, where valid values of p are 1, 2, or Inf. (Note that for sparse matrices, p=2 is currently not implemented.) Use vecnorm to compute the Frobenius norm.

      When p=1, the matrix norm is the maximum absolute column sum of A:

      \[\|A\|_1 = \max_{1 ≤ j ≤ n} \sum_{i=1}^m | a_{ij} |\]

      with $a_{ij}$ the entries of $A$, and $m$ and $n$ its dimensions.

      When p=2, the matrix norm is the spectral norm, equal to the largest singular value of A.

      When p=Inf, the matrix norm is the maximum absolute row sum of A:

      \[\|A\|_\infty = \max_{1 ≤ i ≤ m} \sum _{j=1}^n | a_{ij} |\]

      Example

      julia> A = [1 -2 -3; 2 3 -1]
      -2×3 Array{Int64,2}:
      - 1  -2  -3
      - 2   3  -1
      -
      -julia> norm(A, Inf)
      -6.0
      source
      norm(x::Number, p::Real=2)

      For numbers, return $\left( |x|^p \right)^{1/p}$. This is equivalent to vecnorm.

      source
      norm(A::RowVector, q::Real=2)

      For row vectors, return the $q$-norm of A, which is equivalent to the p-norm with value p = q/(q-1). They coincide at p = q = 2.

      The difference in norm between a vector space and its dual arises to preserve the relationship between duality and the inner product, and the result is consistent with the p-norm of 1 × n matrix.

      source
      Base.LinAlg.vecnormFunction.
      vecnorm(A, p::Real=2)

      For any iterable container A (including arrays of any dimension) of numbers (or any element type for which norm is defined), compute the p-norm (defaulting to p=2) as if A were a vector of the corresponding length.

      The p-norm is defined as:

      \[\|A\|_p = \left( \sum_{i=1}^n | a_i | ^p \right)^{1/p}\]

      with $a_i$ the entries of $A$ and $n$ its length.

      p can assume any numeric value (even though not all values produce a mathematically valid vector norm). In particular, vecnorm(A, Inf) returns the largest value in abs(A), whereas vecnorm(A, -Inf) returns the smallest. If A is a matrix and p=2, then this is equivalent to the Frobenius norm.

      Example

      julia> vecnorm([1 2 3; 4 5 6; 7 8 9])
      -16.881943016134134
      -
      -julia> vecnorm([1 2 3 4 5 6 7 8 9])
      -16.881943016134134
      source
      vecnorm(x::Number, p::Real=2)

      For numbers, return $\left( |x|^p \right) ^{1/p}$.

      source
      normalize!(v::AbstractVector, p::Real=2)

      Normalize the vector v in-place so that its p-norm equals unity, i.e. norm(v, p) == 1. See also normalize and vecnorm.

      source
      Base.LinAlg.normalizeFunction.
      normalize(v::AbstractVector, p::Real=2)

      Normalize the vector v so that its p-norm equals unity, i.e. norm(v, p) == vecnorm(v, p) == 1. See also normalize! and vecnorm.

      Examples

      julia> a = [1,2,4];
      -
      -julia> b = normalize(a)
      -3-element Array{Float64,1}:
      - 0.218218
      - 0.436436
      - 0.872872
      -
      -julia> norm(b)
      -1.0
      -
      -julia> c = normalize(a, 1)
      -3-element Array{Float64,1}:
      - 0.142857
      - 0.285714
      - 0.571429
      -
      -julia> norm(c, 1)
      -1.0
      source
      Base.LinAlg.condFunction.
      cond(M, p::Real=2)

      Condition number of the matrix M, computed using the operator p-norm. Valid values for p are 1, 2 (default), or Inf.

      source
      Base.LinAlg.condskeelFunction.
      condskeel(M, [x, p::Real=Inf])
      \[\kappa_S(M, p) = \left\Vert \left\vert M \right\vert \left\vert M^{-1} \right\vert \right\Vert_p \\ -\kappa_S(M, x, p) = \left\Vert \left\vert M \right\vert \left\vert M^{-1} \right\vert \left\vert x \right\vert \right\Vert_p\]

      Skeel condition number $\kappa_S$ of the matrix M, optionally with respect to the vector x, as computed using the operator p-norm. $\left\vert M \right\vert$ denotes the matrix of (entry wise) absolute values of $M$; $\left\vert M \right\vert_{ij} = \left\vert M_{ij} \right\vert$. Valid values for p are 1, 2 and Inf (default).

      This quantity is also known in the literature as the Bauer condition number, relative condition number, or componentwise relative condition number.

      source
      Base.LinAlg.traceFunction.
      trace(M)

      Matrix trace. Sums the diagonal elements of M.

      Example

      julia> A = [1 2; 3 4]
      -2×2 Array{Int64,2}:
      - 1  2
      - 3  4
      -
      -julia> trace(A)
      -5
      source
      Base.LinAlg.detFunction.
      det(M)

      Matrix determinant.

      Example

      julia> M = [1 0; 2 2]
      -2×2 Array{Int64,2}:
      - 1  0
      - 2  2
      -
      -julia> det(M)
      -2.0
      source
      Base.LinAlg.logdetFunction.
      logdet(M)

      Log of matrix determinant. Equivalent to log(det(M)), but may provide increased accuracy and/or speed.

      Examples

      julia> M = [1 0; 2 2]
      -2×2 Array{Int64,2}:
      - 1  0
      - 2  2
      -
      -julia> logdet(M)
      -0.6931471805599453
      -
      -julia> logdet(eye(3))
      -0.0
      source
      Base.LinAlg.logabsdetFunction.
      logabsdet(M)

      Log of absolute value of matrix determinant. Equivalent to (log(abs(det(M))), sign(det(M))), but may provide increased accuracy and/or speed.

      source
      Base.invFunction.
      inv(M)

      Matrix inverse. Computes matrix N such that M * N = I, where I is the identity matrix. Computed by solving the left-division N = M \ I.

      Example

      julia> M = [2 5; 1 3]
      -2×2 Array{Int64,2}:
      - 2  5
      - 1  3
      -
      -julia> N = inv(M)
      -2×2 Array{Float64,2}:
      -  3.0  -5.0
      - -1.0   2.0
      -
      -julia> M*N == N*M == eye(2)
      -true
      source
      Base.LinAlg.pinvFunction.
      pinv(M[, tol::Real])

      Computes the Moore-Penrose pseudoinverse.

      For matrices M with floating point elements, it is convenient to compute the pseudoinverse by inverting only singular values above a given threshold, tol.

      The optimal choice of tol varies both with the value of M and the intended application of the pseudoinverse. The default value of tol is eps(real(float(one(eltype(M)))))*maximum(size(A)), which is essentially machine epsilon for the real part of a matrix element multiplied by the larger matrix dimension. For inverting dense ill-conditioned matrices in a least-squares sense, tol = sqrt(eps(real(float(one(eltype(M)))))) is recommended.

      For more information, see [issue8859], [B96], [S84], [KY88].

      Example

      julia> M = [1.5 1.3; 1.2 1.9]
      -2×2 Array{Float64,2}:
      - 1.5  1.3
      - 1.2  1.9
      -
      -julia> N = pinv(M)
      -2×2 Array{Float64,2}:
      -  1.47287   -1.00775
      - -0.930233   1.16279
      -
      -julia> M * N
      -2×2 Array{Float64,2}:
      - 1.0          -2.22045e-16
      - 4.44089e-16   1.0
      [issue8859]

      Issue 8859, "Fix least squares", https://github.com/JuliaLang/julia/pull/8859

      [B96]

      Åke Björck, "Numerical Methods for Least Squares Problems", SIAM Press, Philadelphia, 1996, "Other Titles in Applied Mathematics", Vol. 51. doi:10.1137/1.9781611971484

      [S84]

      G. W. Stewart, "Rank Degeneracy", SIAM Journal on Scientific and Statistical Computing, 5(2), 1984, 403-413. doi:10.1137/0905030

      [KY88]

      Konstantinos Konstantinides and Kung Yao, "Statistical analysis of effective singular values in matrix rank determination", IEEE Transactions on Acoustics, Speech and Signal Processing, 36(5), 1988, 757-763. doi:10.1109/29.1585

      source
      Base.LinAlg.nullspaceFunction.
      nullspace(M)

      Basis for nullspace of M.

      Example

      julia> M = [1 0 0; 0 1 0; 0 0 0]
      -3×3 Array{Int64,2}:
      - 1  0  0
      - 0  1  0
      - 0  0  0
      -
      -julia> nullspace(M)
      -3×1 Array{Float64,2}:
      - 0.0
      - 0.0
      - 1.0
      source
      Base.repmatFunction.
      repmat(A, m::Integer, n::Integer=1)

      Construct a matrix by repeating the given matrix (or vector) m times in dimension 1 and n times in dimension 2.

      Examples

      julia> repmat([1, 2, 3], 2)
      -6-element Array{Int64,1}:
      - 1
      - 2
      - 3
      - 1
      - 2
      - 3
      -
      -julia> repmat([1, 2, 3], 2, 3)
      -6×3 Array{Int64,2}:
      - 1  1  1
      - 2  2  2
      - 3  3  3
      - 1  1  1
      - 2  2  2
      - 3  3  3
      source
      Base.repeatFunction.
      repeat(A::AbstractArray; inner=ntuple(x->1, ndims(A)), outer=ntuple(x->1, ndims(A)))

      Construct an array by repeating the entries of A. The i-th element of inner specifies the number of times that the individual entries of the i-th dimension of A should be repeated. The i-th element of outer specifies the number of times that a slice along the i-th dimension of A should be repeated. If inner or outer are omitted, no repetition is performed.

      Examples

      julia> repeat(1:2, inner=2)
      -4-element Array{Int64,1}:
      - 1
      - 1
      - 2
      - 2
      -
      -julia> repeat(1:2, outer=2)
      -4-element Array{Int64,1}:
      - 1
      - 2
      - 1
      - 2
      -
      -julia> repeat([1 2; 3 4], inner=(2, 1), outer=(1, 3))
      -4×6 Array{Int64,2}:
      - 1  2  1  2  1  2
      - 1  2  1  2  1  2
      - 3  4  3  4  3  4
      - 3  4  3  4  3  4
      source
      Base.kronFunction.
      kron(A, B)

      Kronecker tensor product of two vectors or two matrices.

      Example

      julia> A = [1 2; 3 4]
      -2×2 Array{Int64,2}:
      - 1  2
      - 3  4
      -
      -julia> B = [im 1; 1 -im]
      -2×2 Array{Complex{Int64},2}:
      - 0+1im  1+0im
      - 1+0im  0-1im
      -
      -julia> kron(A, B)
      -4×4 Array{Complex{Int64},2}:
      - 0+1im  1+0im  0+2im  2+0im
      - 1+0im  0-1im  2+0im  0-2im
      - 0+3im  3+0im  0+4im  4+0im
      - 3+0im  0-3im  4+0im  0-4im
      source
      blkdiag(A...)

      Concatenate matrices block-diagonally. Currently only implemented for sparse matrices.

      Example

      julia> blkdiag(speye(3), 2*speye(2))
      -5×5 SparseMatrixCSC{Float64,Int64} with 5 stored entries:
      -  [1, 1]  =  1.0
      -  [2, 2]  =  1.0
      -  [3, 3]  =  1.0
      -  [4, 4]  =  2.0
      -  [5, 5]  =  2.0
      source
      Base.LinAlg.linregFunction.
      linreg(x, y)

      Perform simple linear regression using Ordinary Least Squares. Returns a and b such that a + b*x is the closest straight line to the given points (x, y), i.e., such that the squared error between y and a + b*x is minimized.

      Examples:

      using PyPlot
      -x = 1.0:12.0
      -y = [5.5, 6.3, 7.6, 8.8, 10.9, 11.79, 13.48, 15.02, 17.77, 20.81, 22.0, 22.99]
      -a, b = linreg(x, y)          # Linear regression
      -plot(x, y, "o")              # Plot (x, y) points
      -plot(x, a + b*x)             # Plot line determined by linear regression

      See also:

      \, cov, std, mean.

      source
      Base.LinAlg.expmFunction.
      expm(A)

      Compute the matrix exponential of A, defined by

      \[e^A = \sum_{n=0}^{\infty} \frac{A^n}{n!}.\]

      For symmetric or Hermitian A, an eigendecomposition (eigfact) is used, otherwise the scaling and squaring algorithm (see [H05]) is chosen.

      [H05]

      Nicholas J. Higham, "The squaring and scaling method for the matrix exponential revisited", SIAM Journal on Matrix Analysis and Applications, 26(4), 2005, 1179-1193. doi:10.1137/090768539

      Example

      julia> A = eye(2, 2)
      -2×2 Array{Float64,2}:
      - 1.0  0.0
      - 0.0  1.0
      -
      -julia> expm(A)
      -2×2 Array{Float64,2}:
      - 2.71828  0.0
      - 0.0      2.71828
      source
      Base.LinAlg.logmFunction.
      logm(A{T}::StridedMatrix{T})

      If A has no negative real eigenvalue, compute the principal matrix logarithm of A, i.e. the unique matrix $X$ such that $e^X = A$ and $-\pi < Im(\lambda) < \pi$ for all the eigenvalues $\lambda$ of $X$. If A has nonpositive eigenvalues, a nonprincipal matrix function is returned whenever possible.

      If A is symmetric or Hermitian, its eigendecomposition (eigfact) is used, if A is triangular an improved version of the inverse scaling and squaring method is employed (see [AH12] and [AHR13]). For general matrices, the complex Schur form (schur) is computed and the triangular algorithm is used on the triangular factor.

      [AH12]

      Awad H. Al-Mohy and Nicholas J. Higham, "Improved inverse scaling and squaring algorithms for the matrix logarithm", SIAM Journal on Scientific Computing, 34(4), 2012, C153-C169. doi:10.1137/110852553

      [AHR13]

      Awad H. Al-Mohy, Nicholas J. Higham and Samuel D. Relton, "Computing the Fréchet derivative of the matrix logarithm and estimating the condition number", SIAM Journal on Scientific Computing, 35(4), 2013, C394-C410. doi:10.1137/120885991

      Example

      julia> A = 2.7182818 * eye(2)
      -2×2 Array{Float64,2}:
      - 2.71828  0.0
      - 0.0      2.71828
      -
      -julia> logm(A)
      -2×2 Symmetric{Float64,Array{Float64,2}}:
      - 1.0  0.0
      - 0.0  1.0
      source
      Base.LinAlg.sqrtmFunction.
      sqrtm(A)

      If A has no negative real eigenvalues, compute the principal matrix square root of A, that is the unique matrix $X$ with eigenvalues having positive real part such that $X^2 = A$. Otherwise, a nonprincipal square root is returned.

      If A is symmetric or Hermitian, its eigendecomposition (eigfact) is used to compute the square root. Otherwise, the square root is determined by means of the Björck-Hammarling method [BH83], which computes the complex Schur form (schur) and then the complex square root of the triangular factor.

      [BH83]

      Åke Björck and Sven Hammarling, "A Schur method for the square root of a matrix", Linear Algebra and its Applications, 52-53, 1983, 127-140. doi:10.1016/0024-3795(83)80010-X

      Example

      julia> A = [4 0; 0 4]
      -2×2 Array{Int64,2}:
      - 4  0
      - 0  4
      -
      -julia> sqrtm(A)
      -2×2 Array{Float64,2}:
      - 2.0  0.0
      - 0.0  2.0
      source
      Base.LinAlg.lyapFunction.
      lyap(A, C)

      Computes the solution X to the continuous Lyapunov equation AX + XA' + C = 0, where no eigenvalue of A has a zero real part and no two eigenvalues are negative complex conjugates of each other.

      source
      Base.LinAlg.sylvesterFunction.
      sylvester(A, B, C)

      Computes the solution X to the Sylvester equation AX + XB + C = 0, where A, B and C have compatible dimensions and A and -B have no eigenvalues with equal real part.

      source
      issymmetric(A) -> Bool

      Test whether a matrix is symmetric.

      Examples

      julia> a = [1 2; 2 -1]
      -2×2 Array{Int64,2}:
      - 1   2
      - 2  -1
      -
      -julia> issymmetric(a)
      -true
      -
      -julia> b = [1 im; -im 1]
      -2×2 Array{Complex{Int64},2}:
      - 1+0im  0+1im
      - 0-1im  1+0im
      -
      -julia> issymmetric(b)
      -false
      source
      Base.LinAlg.isposdefFunction.
      isposdef(A) -> Bool

      Test whether a matrix is positive definite.

      Example

      julia> A = [1 2; 2 50]
      -2×2 Array{Int64,2}:
      - 1   2
      - 2  50
      -
      -julia> isposdef(A)
      -true
      source
      Base.LinAlg.isposdef!Function.
      isposdef!(A) -> Bool

      Test whether a matrix is positive definite, overwriting A in the process.

      Example

      julia> A = [1. 2.; 2. 50.];
      -
      -julia> isposdef!(A)
      -true
      -
      -julia> A
      -2×2 Array{Float64,2}:
      - 1.0  2.0
      - 2.0  6.78233
      source
      Base.LinAlg.istrilFunction.
      istril(A) -> Bool

      Test whether a matrix is lower triangular.

      Examples

      julia> a = [1 2; 2 -1]
      -2×2 Array{Int64,2}:
      - 1   2
      - 2  -1
      -
      -julia> istril(a)
      -false
      -
      -julia> b = [1 0; -im -1]
      -2×2 Array{Complex{Int64},2}:
      - 1+0im   0+0im
      - 0-1im  -1+0im
      -
      -julia> istril(b)
      -true
      source
      Base.LinAlg.istriuFunction.
      istriu(A) -> Bool

      Test whether a matrix is upper triangular.

      Examples

      julia> a = [1 2; 2 -1]
      -2×2 Array{Int64,2}:
      - 1   2
      - 2  -1
      -
      -julia> istriu(a)
      -false
      -
      -julia> b = [1 im; 0 -1]
      -2×2 Array{Complex{Int64},2}:
      - 1+0im   0+1im
      - 0+0im  -1+0im
      -
      -julia> istriu(b)
      -true
      source
      Base.LinAlg.isdiagFunction.
      isdiag(A) -> Bool

      Test whether a matrix is diagonal.

      Examples

      julia> a = [1 2; 2 -1]
      -2×2 Array{Int64,2}:
      - 1   2
      - 2  -1
      -
      -julia> isdiag(a)
      -false
      -
      -julia> b = [im 0; 0 -im]
      -2×2 Array{Complex{Int64},2}:
      - 0+1im  0+0im
      - 0+0im  0-1im
      -
      -julia> isdiag(b)
      -true
      source
      ishermitian(A) -> Bool

      Test whether a matrix is Hermitian.

      Examples

      julia> a = [1 2; 2 -1]
      -2×2 Array{Int64,2}:
      - 1   2
      - 2  -1
      -
      -julia> ishermitian(a)
      -true
      -
      -julia> b = [1 im; -im 1]
      -2×2 Array{Complex{Int64},2}:
      - 1+0im  0+1im
      - 0-1im  1+0im
      -
      -julia> ishermitian(b)
      -true
      source
      RowVector(vector)

      A lazy-view wrapper of an AbstractVector, which turns a length-n vector into a 1×n shaped row vector and represents the transpose of a vector (the elements are also transposed recursively). This type is usually constructed (and unwrapped) via the transpose function or .' operator (or related ctranspose or ' operator).

      By convention, a vector can be multiplied by a matrix on its left (A * v) whereas a row vector can be multiplied by a matrix on its right (such that v.' * A = (A.' * v).'). It differs from a 1×n-sized matrix by the facts that its transpose returns a vector and the inner product v1.' * v2 returns a scalar, but will otherwise behave similarly.

      source
      ConjArray(array)

      A lazy-view wrapper of an AbstractArray, taking the elementwise complex conjugate. This type is usually constructed (and unwrapped) via the conj function (or related ctranspose), but currently this is the default behavior for RowVector only. For other arrays, the ConjArray constructor can be used directly.

      Examples

      julia> [1+im, 1-im]'
      -1×2 RowVector{Complex{Int64},ConjArray{Complex{Int64},1,Array{Complex{Int64},1}}}:
      - 1-1im  1+1im
      -
      -julia> ConjArray([1+im 0; 0 1-im])
      -2×2 ConjArray{Complex{Int64},2,Array{Complex{Int64},2}}:
      - 1-1im  0+0im
      - 0+0im  1+1im
      source
      Base.transposeFunction.
      transpose(A::AbstractMatrix)

      The transposition operator (.').

      Example

      julia> A = [1 2 3; 4 5 6; 7 8 9]
      -3×3 Array{Int64,2}:
      - 1  2  3
      - 4  5  6
      - 7  8  9
      -
      -julia> transpose(A)
      -3×3 Array{Int64,2}:
      - 1  4  7
      - 2  5  8
      - 3  6  9
      source
      transpose(v::AbstractVector)

      The transposition operator (.').

      Example

      julia> v = [1,2,3]
      -3-element Array{Int64,1}:
      - 1
      - 2
      - 3
      -
      -julia> transpose(v)
      -1×3 RowVector{Int64,Array{Int64,1}}:
      - 1  2  3
      source
      transpose!(dest,src)

      Transpose array src and store the result in the preallocated array dest, which should have a size corresponding to (size(src,2),size(src,1)). No in-place transposition is supported and unexpected results will happen if src and dest have overlapping memory regions.

      source
      Base.ctransposeFunction.
      ctranspose(A)

      The conjugate transposition operator (').

      Example

      julia> A =  [3+2im 9+2im; 8+7im  4+6im]
      -2×2 Array{Complex{Int64},2}:
      - 3+2im  9+2im
      - 8+7im  4+6im
      -
      -julia> ctranspose(A)
      -2×2 Array{Complex{Int64},2}:
      - 3-2im  8-7im
      - 9-2im  4-6im
      source
      ctranspose!(dest,src)

      Conjugate transpose array src and store the result in the preallocated array dest, which should have a size corresponding to (size(src,2),size(src,1)). No in-place transposition is supported and unexpected results will happen if src and dest have overlapping memory regions.

      source
      Base.LinAlg.eigsMethod.
      eigs(A; nev=6, ncv=max(20,2*nev+1), which=:LM, tol=0.0, maxiter=300, sigma=nothing, ritzvec=true, v0=zeros((0,))) -> (d,[v,],nconv,niter,nmult,resid)

      Computes eigenvalues d of A using implicitly restarted Lanczos or Arnoldi iterations for real symmetric or general nonsymmetric matrices respectively.

      The following keyword arguments are supported:

      • nev: Number of eigenvalues

      • ncv: Number of Krylov vectors used in the computation; should satisfy nev+1 <= ncv <= n for real symmetric problems and nev+2 <= ncv <= n for other problems, where n is the size of the input matrix A. The default is ncv = max(20,2*nev+1). Note that these restrictions limit the input matrix A to be of dimension at least 2.

      • which: type of eigenvalues to compute. See the note below.

      whichtype of eigenvalues
      :LMeigenvalues of largest magnitude (default)
      :SMeigenvalues of smallest magnitude
      :LReigenvalues of largest real part
      :SReigenvalues of smallest real part
      :LIeigenvalues of largest imaginary part (nonsymmetric or complex A only)
      :SIeigenvalues of smallest imaginary part (nonsymmetric or complex A only)
      :BEcompute half of the eigenvalues from each end of the spectrum, biased in favor of the high end. (real symmetric A only)
      • tol: parameter defining the relative tolerance for convergence of Ritz values (eigenvalue estimates). A Ritz value $θ$ is considered converged when its associated residual is less than or equal to the product of tol and $max(ɛ^{2/3}, |θ|)$, where ɛ = eps(real(eltype(A)))/2 is LAPACK's machine epsilon. The residual associated with $θ$ and its corresponding Ritz vector $v$ is defined as the norm $||Av - vθ||$. The specified value of tol should be positive; otherwise, it is ignored and $ɛ$ is used instead. Default: $ɛ$.

      • maxiter: Maximum number of iterations (default = 300)

      • sigma: Specifies the level shift used in inverse iteration. If nothing (default), defaults to ordinary (forward) iterations. Otherwise, find eigenvalues close to sigma using shift and invert iterations.

      • ritzvec: Returns the Ritz vectors v (eigenvectors) if true

      • v0: starting vector from which to start the iterations

      eigs returns the nev requested eigenvalues in d, the corresponding Ritz vectors v (only if ritzvec=true), the number of converged eigenvalues nconv, the number of iterations niter and the number of matrix vector multiplications nmult, as well as the final residual vector resid.

      Example

      julia> A = spdiagm(1:4);
      -
      -julia> λ, ϕ = eigs(A, nev = 2);
      -
      -julia> λ
      -2-element Array{Float64,1}:
      - 4.0
      - 3.0
      Note

      The sigma and which keywords interact: the description of eigenvalues searched for by which do not necessarily refer to the eigenvalues of A, but rather the linear operator constructed by the specification of the iteration mode implied by sigma.

      sigmaiteration modewhich refers to eigenvalues of
      nothingordinary (forward)$A$
      real or complexinverse with level shift sigma$(A - \sigma I )^{-1}$
      Note

      Although tol has a default value, the best choice depends strongly on the matrix A. We recommend that users _always_ specify a value for tol which suits their specific needs.

      For details of how the errors in the computed eigenvalues are estimated, see:

      • B. N. Parlett, "The Symmetric Eigenvalue Problem", SIAM: Philadelphia, 2/e (1998), Ch. 13.2, "Accessing Accuracy in Lanczos Problems", pp. 290-292 ff.

      • R. B. Lehoucq and D. C. Sorensen, "Deflation Techniques for an Implicitly Restarted Arnoldi Iteration", SIAM Journal on Matrix Analysis and Applications (1996), 17(4), 789–821. doi:10.1137/S0895479895281484

      source
      Base.LinAlg.eigsMethod.
      eigs(A, B; nev=6, ncv=max(20,2*nev+1), which=:LM, tol=0.0, maxiter=300, sigma=nothing, ritzvec=true, v0=zeros((0,))) -> (d,[v,],nconv,niter,nmult,resid)

      Computes generalized eigenvalues d of A and B using implicitly restarted Lanczos or Arnoldi iterations for real symmetric or general nonsymmetric matrices respectively.

      The following keyword arguments are supported:

      • nev: Number of eigenvalues

      • ncv: Number of Krylov vectors used in the computation; should satisfy nev+1 <= ncv <= n for real symmetric problems and nev+2 <= ncv <= n for other problems, where n is the size of the input matrices A and B. The default is ncv = max(20,2*nev+1). Note that these restrictions limit the input matrix A to be of dimension at least 2.

      • which: type of eigenvalues to compute. See the note below.

      whichtype of eigenvalues
      :LMeigenvalues of largest magnitude (default)
      :SMeigenvalues of smallest magnitude
      :LReigenvalues of largest real part
      :SReigenvalues of smallest real part
      :LIeigenvalues of largest imaginary part (nonsymmetric or complex A only)
      :SIeigenvalues of smallest imaginary part (nonsymmetric or complex A only)
      :BEcompute half of the eigenvalues from each end of the spectrum, biased in favor of the high end. (real symmetric A only)
      • tol: relative tolerance used in the convergence criterion for eigenvalues, similar to tol in the eigs(A) method for the ordinary eigenvalue problem, but effectively for the eigenvalues of $B^{-1} A$ instead of $A$. See the documentation for the ordinary eigenvalue problem in eigs(A) and the accompanying note about tol.

      • maxiter: Maximum number of iterations (default = 300)

      • sigma: Specifies the level shift used in inverse iteration. If nothing (default), defaults to ordinary (forward) iterations. Otherwise, find eigenvalues close to sigma using shift and invert iterations.

      • ritzvec: Returns the Ritz vectors v (eigenvectors) if true

      • v0: starting vector from which to start the iterations

      eigs returns the nev requested eigenvalues in d, the corresponding Ritz vectors v (only if ritzvec=true), the number of converged eigenvalues nconv, the number of iterations niter and the number of matrix vector multiplications nmult, as well as the final residual vector resid.

      Example

      julia> A = speye(4, 4); B = spdiagm(1:4);
      -
      -julia> λ, ϕ = eigs(A, B, nev = 2);
      -
      -julia> λ
      -2-element Array{Float64,1}:
      - 1.0
      - 0.5
      Note

      The sigma and which keywords interact: the description of eigenvalues searched for by which do not necessarily refer to the eigenvalue problem $Av = Bv\lambda$, but rather the linear operator constructed by the specification of the iteration mode implied by sigma.

      sigmaiteration modewhich refers to the problem
      nothingordinary (forward)$Av = Bv\lambda$
      real or complexinverse with level shift sigma$(A - \sigma B )^{-1}B = v\nu$
      source
      Base.LinAlg.svdsFunction.
      svds(A; nsv=6, ritzvec=true, tol=0.0, maxiter=1000, ncv=2*nsv, u0=zeros((0,)), v0=zeros((0,))) -> (SVD([left_sv,] s, [right_sv,]), nconv, niter, nmult, resid)

      Computes the largest singular values s of A using implicitly restarted Lanczos iterations derived from eigs.

      Inputs

      • A: Linear operator whose singular values are desired. A may be represented as a subtype of AbstractArray, e.g., a sparse matrix, or any other type supporting the four methods size(A), eltype(A), A * vector, and A' * vector.

      • nsv: Number of singular values. Default: 6.

      • ritzvec: If true, return the left and right singular vectors left_sv and right_sv. If false, omit the singular vectors. Default: true.

      • tol: tolerance, see eigs.

      • maxiter: Maximum number of iterations, see eigs. Default: 1000.

      • ncv: Maximum size of the Krylov subspace, see eigs (there called nev). Default: 2*nsv.

      • u0: Initial guess for the first left Krylov vector. It may have length m (the first dimension of A), or 0.

      • v0: Initial guess for the first right Krylov vector. It may have length n (the second dimension of A), or 0.

      Outputs

      • svd: An SVD object containing the left singular vectors, the requested values, and the right singular vectors. If ritzvec = false, the left and right singular vectors will be empty.

      • nconv: Number of converged singular values.

      • niter: Number of iterations.

      • nmult: Number of matrix–vector products used.

      • resid: Final residual vector.

      Example

      julia> A = spdiagm(1:4);
      -
      -julia> s = svds(A, nsv = 2)[1];
      -
      -julia> s[:S]
      -2-element Array{Float64,1}:
      - 4.0
      - 3.0
      Implementation

      svds(A) is formally equivalent to calling eigs to perform implicitly restarted Lanczos tridiagonalization on the Hermitian matrix $\begin{pmatrix} 0 & A^\prime \\ A & 0 \end{pmatrix}$, whose eigenvalues are plus and minus the singular values of $A$.

      source
      Base.LinAlg.peakflopsFunction.
      peakflops(n::Integer=2000; parallel::Bool=false)

      peakflops computes the peak flop rate of the computer by using double precision gemm!. By default, if no arguments are specified, it multiplies a matrix of size n x n, where n = 2000. If the underlying BLAS is using multiple threads, higher flop rates are realized. The number of BLAS threads can be set with BLAS.set_num_threads(n).

      If the keyword argument parallel is set to true, peakflops is run in parallel on all the worker processors. The flop rate of the entire parallel computer is returned. When running in parallel, only 1 BLAS thread is used. The argument n still refers to the size of the problem that is solved on each processor.

      source

      Low-level matrix operations

      Matrix operations involving transpositions operations like A' \ B are converted by the Julia parser into calls to specially named functions like Ac_ldiv_B. If you want to overload these operations for your own types, then it is useful to know the names of these functions.

      Also, in many cases there are in-place versions of matrix operations that allow you to supply a pre-allocated output vector or matrix. This is useful when optimizing critical code in order to avoid the overhead of repeated allocations. These in-place operations are suffixed with ! below (e.g. A_mul_B!) according to the usual Julia convention.

      Base.LinAlg.A_ldiv_B!Function.
      A_ldiv_B!([Y,] A, B) -> Y

      Compute A \ B in-place and store the result in Y, returning the result. If only two arguments are passed, then A_ldiv_B!(A, B) overwrites B with the result.

      The argument A should not be a matrix. Rather, instead of matrices it should be a factorization object (e.g. produced by factorize or cholfact). The reason for this is that factorization itself is both expensive and typically allocates memory (although it can also be done in-place via, e.g., lufact!), and performance-critical situations requiring A_ldiv_B! usually also require fine-grained control over the factorization of A.

      source
      Base.A_ldiv_BcFunction.
      A_ldiv_Bc(A, B)

      For matrices or vectors $A$ and $B$, calculates $A$ \ $Bᴴ$.

      source
      Base.A_ldiv_BtFunction.
      A_ldiv_Bt(A, B)

      For matrices or vectors $A$ and $B$, calculates $A$ \ $Bᵀ$.

      source
      Base.LinAlg.A_mul_B!Function.
      A_mul_B!(Y, A, B) -> Y

      Calculates the matrix-matrix or matrix-vector product $A⋅B$ and stores the result in Y, overwriting the existing value of Y. Note that Y must not be aliased with either A or B.

      Example

      julia> A=[1.0 2.0; 3.0 4.0]; B=[1.0 1.0; 1.0 1.0]; Y = similar(B); A_mul_B!(Y, A, B);
      -
      -julia> Y
      -2×2 Array{Float64,2}:
      - 3.0  3.0
      - 7.0  7.0
      source
      Base.A_mul_BcFunction.
      A_mul_Bc(A, B)

      For matrices or vectors $A$ and $B$, calculates $A⋅Bᴴ$.

      source
      Base.A_mul_BtFunction.
      A_mul_Bt(A, B)

      For matrices or vectors $A$ and $B$, calculates $A⋅Bᵀ$.

      source
      Base.A_rdiv_BcFunction.
      A_rdiv_Bc(A, B)

      For matrices or vectors $A$ and $B$, calculates $A / Bᴴ$.

      source
      Base.A_rdiv_BtFunction.
      A_rdiv_Bt(A, B)

      For matrices or vectors $A$ and $B$, calculates $A / Bᵀ$.

      source
      Base.Ac_ldiv_BFunction.
      Ac_ldiv_B(A, B)

      For matrices or vectors $A$ and $B$, calculates $Aᴴ$ \ $B$.

      source
      Ac_ldiv_B!([Y,] A, B) -> Y

      Similar to A_ldiv_B!, but return $Aᴴ$ \ $B$, computing the result in-place in Y (or overwriting B if Y is not supplied).

      source
      Base.Ac_ldiv_BcFunction.
      Ac_ldiv_Bc(A, B)

      For matrices or vectors $A$ and $B$, calculates $Aᴴ$ \ $Bᴴ$.

      source
      Base.Ac_mul_BFunction.
      Ac_mul_B(A, B)

      For matrices or vectors $A$ and $B$, calculates $Aᴴ⋅B$.

      source
      Base.Ac_mul_BcFunction.
      Ac_mul_Bc(A, B)

      For matrices or vectors $A$ and $B$, calculates $Aᴴ Bᴴ$.

      source
      Base.Ac_rdiv_BFunction.
      Ac_rdiv_B(A, B)

      For matrices or vectors $A$ and $B$, calculates $Aᴴ / B$.

      source
      Base.Ac_rdiv_BcFunction.
      Ac_rdiv_Bc(A, B)

      For matrices or vectors $A$ and $B$, calculates $Aᴴ / Bᴴ$.

      source
      Base.At_ldiv_BFunction.
      At_ldiv_B(A, B)

      For matrices or vectors $A$ and $B$, calculates $Aᵀ$ \ $B$.

      source
      At_ldiv_B!([Y,] A, B) -> Y

      Similar to A_ldiv_B!, but return $Aᵀ$ \ $B$, computing the result in-place in Y (or overwriting B if Y is not supplied).

      source
      Base.At_ldiv_BtFunction.
      At_ldiv_Bt(A, B)

      For matrices or vectors $A$ and $B$, calculates $Aᵀ$ \ $Bᵀ$.

      source
      Base.At_mul_BFunction.
      At_mul_B(A, B)

      For matrices or vectors $A$ and $B$, calculates $Aᵀ⋅B$.

      source
      Base.At_mul_BtFunction.
      At_mul_Bt(A, B)

      For matrices or vectors $A$ and $B$, calculates $Aᵀ⋅Bᵀ$.

      source
      Base.At_rdiv_BFunction.
      At_rdiv_B(A, B)

      For matrices or vectors $A$ and $B$, calculates $Aᵀ / B$.

      source
      Base.At_rdiv_BtFunction.
      At_rdiv_Bt(A, B)

      For matrices or vectors $A$ and $B$, calculates $Aᵀ / Bᵀ$.

      source

      BLAS Functions

      In Julia (as in much of scientific computation), dense linear-algebra operations are based on the LAPACK library, which in turn is built on top of basic linear-algebra building-blocks known as the BLAS. There are highly optimized implementations of BLAS available for every computer architecture, and sometimes in high-performance linear algebra routines it is useful to call the BLAS functions directly.

      Base.LinAlg.BLAS provides wrappers for some of the BLAS functions. Those BLAS functions that overwrite one of the input arrays have names ending in '!'. Usually, a BLAS function has four methods defined, for Float64, Float32, Complex128, and Complex64 arrays.

      BLAS Character Arguments

      Many BLAS functions accept arguments that determine whether to transpose an argument (trans), which triangle of a matrix to reference (uplo or ul), whether the diagonal of a triangular matrix can be assumed to be all ones (dA) or which side of a matrix multiplication the input argument belongs on (side). The possiblities are:

      Multplication Order

      sideMeaning
      'L'The argument goes on the left side of a matrix-matrix operation.
      'R'The argument goes on the right side of a matrix-matrix operation.

      Triangle Referencing

      uplo/ulMeaning
      'U'Only the upper triangle of the matrix will be used.
      'L'Only the lower triangle of the matrix will be used.

      Transposition Operation

      trans/tXMeaning
      'N'The input matrix X is not transposed or conjugated.
      'T'The input matrix X will be transposed.
      'C'The input matrix X will be conjugated and transposed.

      Unit Diagonal

      diag/dXMeaning
      'N'The diagonal values of the matrix X will be read.
      'U'The diagonal of the matrix X is assumed to be all ones.
      Base.LinAlg.BLAS.dotuFunction.
      dotu(n, X, incx, Y, incy)

      Dot function for two complex vectors consisting of n elements of array X with stride incx and n elements of array Y with stride incy.

      Example:

      julia> Base.BLAS.dotu(10, im*ones(10), 1, complex.(ones(20), ones(20)), 2)
      --10.0 + 10.0im
      source
      Base.LinAlg.BLAS.dotcFunction.
      dotc(n, X, incx, U, incy)

      Dot function for two complex vectors, consisting of n elements of array X with stride incx and n elements of array U with stride incy, conjugating the first vector.

      Example:

      julia> Base.BLAS.dotc(10, im*ones(10), 1, complex.(ones(20), ones(20)), 2)
      -10.0 - 10.0im
      source
      blascopy!(n, X, incx, Y, incy)

      Copy n elements of array X with stride incx to array Y with stride incy. Returns Y.

      source
      Base.LinAlg.BLAS.nrm2Function.
      nrm2(n, X, incx)

      2-norm of a vector consisting of n elements of array X with stride incx.

      Example:

      julia> Base.BLAS.nrm2(4, ones(8), 2)
      -2.0
      -
      -julia> Base.BLAS.nrm2(1, ones(8), 2)
      -1.0
      source
      Base.LinAlg.BLAS.asumFunction.
      asum(n, X, incx)

      Sum of the absolute values of the first n elements of array X with stride incx.

      Example:

      julia> Base.BLAS.asum(5, im*ones(10), 2)
      -5.0
      -
      -julia> Base.BLAS.asum(2, im*ones(10), 5)
      -2.0
      source
      Base.LinAlg.axpy!Function.
      axpy!(a, X, Y)

      Overwrite Y with a*X + Y, where a is a scalar. Returns Y.

      Example:

      julia> x = [1; 2; 3];
      -
      -julia> y = [4; 5; 6];
      -
      -julia> Base.BLAS.axpy!(2, x, y)
      -3-element Array{Int64,1}:
      -  6
      -  9
      - 12
      source
      scal!(n, a, X, incx)

      Overwrite X with a*X for the first n elements of array X with stride incx. Returns X.

      source
      Base.LinAlg.BLAS.scalFunction.
      scal(n, a, X, incx)

      Returns X scaled by a for the first n elements of array X with stride incx.

      source
      Base.LinAlg.BLAS.ger!Function.
      ger!(alpha, x, y, A)

      Rank-1 update of the matrix A with vectors x and y as alpha*x*y' + A.

      source
      Base.LinAlg.BLAS.syr!Function.
      syr!(uplo, alpha, x, A)

      Rank-1 update of the symmetric matrix A with vector x as alpha*x*x.' + A. uplo controls which triangle of A is updated. Returns A.

      source
      syrk!(uplo, trans, alpha, A, beta, C)

      Rank-k update of the symmetric matrix C as alpha*A*A.' + beta*C or alpha*A.'*A + beta*C according to trans. Only the uplo triangle of C is used. Returns C.

      source
      Base.LinAlg.BLAS.syrkFunction.
      syrk(uplo, trans, alpha, A)

      Returns either the upper triangle or the lower triangle of A, according to uplo, of alpha*A*A.' or alpha*A.'*A, according to trans.

      source
      Base.LinAlg.BLAS.her!Function.
      her!(uplo, alpha, x, A)

      Methods for complex arrays only. Rank-1 update of the Hermitian matrix A with vector x as alpha*x*x' + A. uplo controls which triangle of A is updated. Returns A.

      source
      herk!(uplo, trans, alpha, A, beta, C)

      Methods for complex arrays only. Rank-k update of the Hermitian matrix C as alpha*A*A' + beta*C or alpha*A'*A + beta*C according to trans. Only the uplo triangle of C is updated. Returns C.

      source
      Base.LinAlg.BLAS.herkFunction.
      herk(uplo, trans, alpha, A)

      Methods for complex arrays only. Returns the uplo triangle of alpha*A*A' or alpha*A'*A, according to trans.

      source
      gbmv!(trans, m, kl, ku, alpha, A, x, beta, y)

      Update vector y as alpha*A*x + beta*y or alpha*A'*x + beta*y according to trans. The matrix A is a general band matrix of dimension m by size(A,2) with kl sub-diagonals and ku super-diagonals. alpha and beta are scalars. Returns the updated y.

      source
      Base.LinAlg.BLAS.gbmvFunction.
      gbmv(trans, m, kl, ku, alpha, A, x)

      Returns alpha*A*x or alpha*A'*x according to trans. The matrix A is a general band matrix of dimension m by size(A,2) with kl sub-diagonals and ku super-diagonals, and alpha is a scalar.

      source
      sbmv!(uplo, k, alpha, A, x, beta, y)

      Update vector y as alpha*A*x + beta*y where A is a a symmetric band matrix of order size(A,2) with k super-diagonals stored in the argument A. The storage layout for A is described the reference BLAS module, level-2 BLAS at http://www.netlib.org/lapack/explore-html/. Only the uplo triangle of A is used.

      Returns the updated y.

      source
      sbmv(uplo, k, alpha, A, x)

      Returns alpha*A*x where A is a symmetric band matrix of order size(A,2) with k super-diagonals stored in the argument A. Only the uplo triangle of A is used.

      source
      sbmv(uplo, k, A, x)

      Returns A*x where A is a symmetric band matrix of order size(A,2) with k super-diagonals stored in the argument A. Only the uplo triangle of A is used.

      source
      gemm!(tA, tB, alpha, A, B, beta, C)

      Update C as alpha*A*B + beta*C or the other three variants according to tA and tB. Returns the updated C.

      source
      gemm(tA, tB, alpha, A, B)

      Returns alpha*A*B or the other three variants according to tA and tB.

      source
      gemm(tA, tB, A, B)

      Returns A*B or the other three variants according to tA and tB.

      source
      gemv!(tA, alpha, A, x, beta, y)

      Update the vector y as alpha*A*x + beta*y or alpha*A'x + beta*y according to tA. alpha and beta are scalars. Returns the updated y.

      source
      gemv(tA, alpha, A, x)

      Returns alpha*A*x or alpha*A'x according to tA. alpha is a scalar.

      source
      gemv(tA, A, x)

      Returns A*x or A'x according to tA.

      source
      symm!(side, ul, alpha, A, B, beta, C)

      Update C as alpha*A*B + beta*C or alpha*B*A + beta*C according to side. A is assumed to be symmetric. Only the ul triangle of A is used. Returns the updated C.

      source
      symm(side, ul, alpha, A, B)

      Returns alpha*A*B or alpha*B*A according to side. A is assumed to be symmetric. Only the ul triangle of A is used.

      source
      symm(side, ul, A, B)

      Returns A*B or B*A according to side. A is assumed to be symmetric. Only the ul triangle of A is used.

      source
      symv!(ul, alpha, A, x, beta, y)

      Update the vector y as alpha*A*x + beta*y. A is assumed to be symmetric. Only the ul triangle of A is used. alpha and beta are scalars. Returns the updated y.

      source
      symv(ul, alpha, A, x)

      Returns alpha*A*x. A is assumed to be symmetric. Only the ul triangle of A is used. alpha is a scalar.

      source
      symv(ul, A, x)

      Returns A*x. A is assumed to be symmetric. Only the ul triangle of A is used.

      source
      trmm!(side, ul, tA, dA, alpha, A, B)

      Update B as alpha*A*B or one of the other three variants determined by side and tA. Only the ul triangle of A is used. dA determines if the diagonal values are read or are assumed to be all ones. Returns the updated B.

      source
      Base.LinAlg.BLAS.trmmFunction.
      trmm(side, ul, tA, dA, alpha, A, B)

      Returns alpha*A*B or one of the other three variants determined by side and tA. Only the ul triangle of A is used. dA determines if the diagonal values are read or are assumed to be all ones.

      source
      trsm!(side, ul, tA, dA, alpha, A, B)

      Overwrite B with the solution to A*X = alpha*B or one of the other three variants determined by side and tA. Only the ul triangle of A is used. dA determines if the diagonal values are read or are assumed to be all ones. Returns the updated B.

      source
      Base.LinAlg.BLAS.trsmFunction.
      trsm(side, ul, tA, dA, alpha, A, B)

      Returns the solution to A*X = alpha*B or one of the other three variants determined by determined by side and tA. Only the ul triangle of A is used. dA determines if the diagonal values are read or are assumed to be all ones.

      source
      trmv!(ul, tA, dA, A, b)

      Returns op(A)*b, where op is determined by tA. Only the ul triangle of A is used. dA determines if the diagonal values are read or are assumed to be all ones. The multiplication occurs in-place on b.

      source
      Base.LinAlg.BLAS.trmvFunction.
      trmv(ul, tA, dA, A, b)

      Returns op(A)*b, where op is determined by tA. Only the ul triangle of A is used. dA determines if the diagonal values are read or are assumed to be all ones.

      source
      trsv!(ul, tA, dA, A, b)

      Overwrite b with the solution to A*x = b or one of the other two variants determined by tA and ul. dA determines if the diagonal values are read or are assumed to be all ones. Returns the updated b.

      source
      Base.LinAlg.BLAS.trsvFunction.
      trsv(ul, tA, dA, A, b)

      Returns the solution to A*x = b or one of the other two variants determined by tA and ul. dA determines if the diagonal values are read or are assumed to be all ones.

      source
      set_num_threads(n)

      Set the number of threads the BLAS library should use.

      source
      Base.LinAlg.IConstant.
      I

      An object of type UniformScaling, representing an identity matrix of any size.

      Example

      julia> ones(5, 6) * I == ones(5, 6)
      -true
      -
      -julia> [1 2im 3; 1im 2 3] * I
      -2×3 Array{Complex{Int64},2}:
      - 1+0im  0+2im  3+0im
      - 0+1im  2+0im  3+0im
      source

      LAPACK Functions

      Base.LinAlg.LAPACK provides wrappers for some of the LAPACK functions for linear algebra. Those functions that overwrite one of the input arrays have names ending in '!'.

      Usually a function has 4 methods defined, one each for Float64, Float32, Complex128 and Complex64 arrays.

      Note that the LAPACK API provided by Julia can and will change in the future. Since this API is not user-facing, there is no commitment to support/deprecate this specific set of functions in future releases.

      gbtrf!(kl, ku, m, AB) -> (AB, ipiv)

      Compute the LU factorization of a banded matrix AB. kl is the first subdiagonal containing a nonzero band, ku is the last superdiagonal containing one, and m is the first dimension of the matrix AB. Returns the LU factorization in-place and ipiv, the vector of pivots used.

      source
      gbtrs!(trans, kl, ku, m, AB, ipiv, B)

      Solve the equation AB * X = B. trans determines the orientation of AB. It may be N (no transpose), T (transpose), or C (conjugate transpose). kl is the first subdiagonal containing a nonzero band, ku is the last superdiagonal containing one, and m is the first dimension of the matrix AB. ipiv is the vector of pivots returned from gbtrf!. Returns the vector or matrix X, overwriting B in-place.

      source
      gebal!(job, A) -> (ilo, ihi, scale)

      Balance the matrix A before computing its eigensystem or Schur factorization. job can be one of N (A will not be permuted or scaled), P (A will only be permuted), S (A will only be scaled), or B (A will be both permuted and scaled). Modifies A in-place and returns ilo, ihi, and scale. If permuting was turned on, A[i,j] = 0 if j > i and 1 < j < ilo or j > ihi. scale contains information about the scaling/permutations performed.

      source
      gebak!(job, side, ilo, ihi, scale, V)

      Transform the eigenvectors V of a matrix balanced using gebal! to the unscaled/unpermuted eigenvectors of the original matrix. Modifies V in-place. side can be L (left eigenvectors are transformed) or R (right eigenvectors are transformed).

      source
      gebrd!(A) -> (A, d, e, tauq, taup)

      Reduce A in-place to bidiagonal form A = QBP'. Returns A, containing the bidiagonal matrix B; d, containing the diagonal elements of B; e, containing the off-diagonal elements of B; tauq, containing the elementary reflectors representing Q; and taup, containing the elementary reflectors representing P.

      source
      gelqf!(A, tau)

      Compute the LQ factorization of A, A = LQ. tau contains scalars which parameterize the elementary reflectors of the factorization. tau must have length greater than or equal to the smallest dimension of A.

      Returns A and tau modified in-place.

      source
      gelqf!(A) -> (A, tau)

      Compute the LQ factorization of A, A = LQ.

      Returns A, modified in-place, and tau, which contains scalars which parameterize the elementary reflectors of the factorization.

      source
      geqlf!(A, tau)

      Compute the QL factorization of A, A = QL. tau contains scalars which parameterize the elementary reflectors of the factorization. tau must have length greater than or equal to the smallest dimension of A.

      Returns A and tau modified in-place.

      source
      geqlf!(A) -> (A, tau)

      Compute the QL factorization of A, A = QL.

      Returns A, modified in-place, and tau, which contains scalars which parameterize the elementary reflectors of the factorization.

      source
      geqrf!(A, tau)

      Compute the QR factorization of A, A = QR. tau contains scalars which parameterize the elementary reflectors of the factorization. tau must have length greater than or equal to the smallest dimension of A.

      Returns A and tau modified in-place.

      source
      geqrf!(A) -> (A, tau)

      Compute the QR factorization of A, A = QR.

      Returns A, modified in-place, and tau, which contains scalars which parameterize the elementary reflectors of the factorization.

      source
      geqp3!(A, jpvt, tau)

      Compute the pivoted QR factorization of A, AP = QR using BLAS level 3. P is a pivoting matrix, represented by jpvt. tau stores the elementary reflectors. jpvt must have length length greater than or equal to n if A is an (m x n) matrix. tau must have length greater than or equal to the smallest dimension of A.

      A, jpvt, and tau are modified in-place.

      source
      geqp3!(A, jpvt) -> (A, jpvt, tau)

      Compute the pivoted QR factorization of A, AP = QR using BLAS level 3. P is a pivoting matrix, represented by jpvt. jpvt must have length greater than or equal to n if A is an (m x n) matrix.

      Returns A and jpvt, modified in-place, and tau, which stores the elementary reflectors.

      source
      geqp3!(A) -> (A, jpvt, tau)

      Compute the pivoted QR factorization of A, AP = QR using BLAS level 3.

      Returns A, modified in-place, jpvt, which represents the pivoting matrix P, and tau, which stores the elementary reflectors.

      source
      gerqf!(A, tau)

      Compute the RQ factorization of A, A = RQ. tau contains scalars which parameterize the elementary reflectors of the factorization. tau must have length greater than or equal to the smallest dimension of A.

      Returns A and tau modified in-place.

      source
      gerqf!(A) -> (A, tau)

      Compute the RQ factorization of A, A = RQ.

      Returns A, modified in-place, and tau, which contains scalars which parameterize the elementary reflectors of the factorization.

      source
      geqrt!(A, T)

      Compute the blocked QR factorization of A, A = QR. T contains upper triangular block reflectors which parameterize the elementary reflectors of the factorization. The first dimension of T sets the block size and it must be between 1 and n. The second dimension of T must equal the smallest dimension of A.

      Returns A and T modified in-place.

      source
      geqrt!(A, nb) -> (A, T)

      Compute the blocked QR factorization of A, A = QR. nb sets the block size and it must be between 1 and n, the second dimension of A.

      Returns A, modified in-place, and T, which contains upper triangular block reflectors which parameterize the elementary reflectors of the factorization.

      source
      geqrt3!(A, T)

      Recursively computes the blocked QR factorization of A, A = QR. T contains upper triangular block reflectors which parameterize the elementary reflectors of the factorization. The first dimension of T sets the block size and it must be between 1 and n. The second dimension of T must equal the smallest dimension of A.

      Returns A and T modified in-place.

      source
      geqrt3!(A) -> (A, T)

      Recursively computes the blocked QR factorization of A, A = QR.

      Returns A, modified in-place, and T, which contains upper triangular block reflectors which parameterize the elementary reflectors of the factorization.

      source
      getrf!(A) -> (A, ipiv, info)

      Compute the pivoted LU factorization of A, A = LU.

      Returns A, modified in-place, ipiv, the pivoting information, and an info code which indicates success (info = 0), a singular value in U (info = i, in which case U[i,i] is singular), or an error code (info < 0).

      source
      tzrzf!(A) -> (A, tau)

      Transforms the upper trapezoidal matrix A to upper triangular form in-place. Returns A and tau, the scalar parameters for the elementary reflectors of the transformation.

      source
      ormrz!(side, trans, A, tau, C)

      Multiplies the matrix C by Q from the transformation supplied by tzrzf!. Depending on side or trans the multiplication can be left-sided (side = L, Q*C) or right-sided (side = R, C*Q) and Q can be unmodified (trans = N), transposed (trans = T), or conjugate transposed (trans = C). Returns matrix C which is modified in-place with the result of the multiplication.

      source
      gels!(trans, A, B) -> (F, B, ssr)

      Solves the linear equation A * X = B, A.' * X =B, or A' * X = B using a QR or LQ factorization. Modifies the matrix/vector B in place with the solution. A is overwritten with its QR or LQ factorization. trans may be one of N (no modification), T (transpose), or C (conjugate transpose). gels! searches for the minimum norm/least squares solution. A may be under or over determined. The solution is returned in B.

      source
      gesv!(A, B) -> (B, A, ipiv)

      Solves the linear equation A * X = B where A is a square matrix using the LU factorization of A. A is overwritten with its LU factorization and B is overwritten with the solution X. ipiv contains the pivoting information for the LU factorization of A.

      source
      getrs!(trans, A, ipiv, B)

      Solves the linear equation A * X = B, A.' * X =B, or A' * X = B for square A. Modifies the matrix/vector B in place with the solution. A is the LU factorization from getrf!, with ipiv the pivoting information. trans may be one of N (no modification), T (transpose), or C (conjugate transpose).

      source
      getri!(A, ipiv)

      Computes the inverse of A, using its LU factorization found by getrf!. ipiv is the pivot information output and A contains the LU factorization of getrf!. A is overwritten with its inverse.

      source
      gesvx!(fact, trans, A, AF, ipiv, equed, R, C, B) -> (X, equed, R, C, B, rcond, ferr, berr, work)

      Solves the linear equation A * X = B (trans = N), A.' * X =B (trans = T), or A' * X = B (trans = C) using the LU factorization of A. fact may be E, in which case A will be equilibrated and copied to AF; F, in which case AF and ipiv from a previous LU factorization are inputs; or N, in which case A will be copied to AF and then factored. If fact = F, equed may be N, meaning A has not been equilibrated; R, meaning A was multiplied by diagm(R) from the left; C, meaning A was multiplied by diagm(C) from the right; or B, meaning A was multiplied by diagm(R) from the left and diagm(C) from the right. If fact = F and equed = R or B the elements of R must all be positive. If fact = F and equed = C or B the elements of C must all be positive.

      Returns the solution X; equed, which is an output if fact is not N, and describes the equilibration that was performed; R, the row equilibration diagonal; C, the column equilibration diagonal; B, which may be overwritten with its equilibrated form diagm(R)*B (if trans = N and equed = R,B) or diagm(C)*B (if trans = T,C and equed = C,B); rcond, the reciprocal condition number of A after equilbrating; ferr, the forward error bound for each solution vector in X; berr, the forward error bound for each solution vector in X; and work, the reciprocal pivot growth factor.

      source
      gesvx!(A, B)

      The no-equilibration, no-transpose simplification of gesvx!.

      source
      gelsd!(A, B, rcond) -> (B, rnk)

      Computes the least norm solution of A * X = B by finding the SVD factorization of A, then dividing-and-conquering the problem. B is overwritten with the solution X. Singular values below rcond will be treated as zero. Returns the solution in B and the effective rank of A in rnk.

      source
      gelsy!(A, B, rcond) -> (B, rnk)

      Computes the least norm solution of A * X = B by finding the full QR factorization of A, then dividing-and-conquering the problem. B is overwritten with the solution X. Singular values below rcond will be treated as zero. Returns the solution in B and the effective rank of A in rnk.

      source
      gglse!(A, c, B, d) -> (X,res)

      Solves the equation A * x = c where x is subject to the equality constraint B * x = d. Uses the formula ||c - A*x||^2 = 0 to solve. Returns X and the residual sum-of-squares.

      source
      geev!(jobvl, jobvr, A) -> (W, VL, VR)

      Finds the eigensystem of A. If jobvl = N, the left eigenvectors of A aren't computed. If jobvr = N, the right eigenvectors of A aren't computed. If jobvl = V or jobvr = V, the corresponding eigenvectors are computed. Returns the eigenvalues in W, the right eigenvectors in VR, and the left eigenvectors in VL.

      source
      gesdd!(job, A) -> (U, S, VT)

      Finds the singular value decomposition of A, A = U * S * V', using a divide and conquer approach. If job = A, all the columns of U and the rows of V' are computed. If job = N, no columns of U or rows of V' are computed. If job = O, A is overwritten with the columns of (thin) U and the rows of (thin) V'. If job = S, the columns of (thin) U and the rows of (thin) V' are computed and returned separately.

      source
      gesvd!(jobu, jobvt, A) -> (U, S, VT)

      Finds the singular value decomposition of A, A = U * S * V'. If jobu = A, all the columns of U are computed. If jobvt = A all the rows of V' are computed. If jobu = N, no columns of U are computed. If jobvt = N no rows of V' are computed. If jobu = O, A is overwritten with the columns of (thin) U. If jobvt = O, A is overwritten with the rows of (thin) V'. If jobu = S, the columns of (thin) U are computed and returned separately. If jobvt = S the rows of (thin) V' are computed and returned separately. jobu and jobvt can't both be O.

      Returns U, S, and Vt, where S are the singular values of A.

      source
      ggsvd!(jobu, jobv, jobq, A, B) -> (U, V, Q, alpha, beta, k, l, R)

      Finds the generalized singular value decomposition of A and B, U'*A*Q = D1*R and V'*B*Q = D2*R. D1 has alpha on its diagonal and D2 has beta on its diagonal. If jobu = U, the orthogonal/unitary matrix U is computed. If jobv = V the orthogonal/unitary matrix V is computed. If jobq = Q, the orthogonal/unitary matrix Q is computed. If jobu, jobv or jobq is N, that matrix is not computed. This function is only available in LAPACK versions prior to 3.6.0.

      source
      ggsvd3!(jobu, jobv, jobq, A, B) -> (U, V, Q, alpha, beta, k, l, R)

      Finds the generalized singular value decomposition of A and B, U'*A*Q = D1*R and V'*B*Q = D2*R. D1 has alpha on its diagonal and D2 has beta on its diagonal. If jobu = U, the orthogonal/unitary matrix U is computed. If jobv = V the orthogonal/unitary matrix V is computed. If jobq = Q, the orthogonal/unitary matrix Q is computed. If jobu, jobv, or jobq is N, that matrix is not computed. This function requires LAPACK 3.6.0.

      source
      geevx!(balanc, jobvl, jobvr, sense, A) -> (A, w, VL, VR, ilo, ihi, scale, abnrm, rconde, rcondv)

      Finds the eigensystem of A with matrix balancing. If jobvl = N, the left eigenvectors of A aren't computed. If jobvr = N, the right eigenvectors of A aren't computed. If jobvl = V or jobvr = V, the corresponding eigenvectors are computed. If balanc = N, no balancing is performed. If balanc = P, A is permuted but not scaled. If balanc = S, A is scaled but not permuted. If balanc = B, A is permuted and scaled. If sense = N, no reciprocal condition numbers are computed. If sense = E, reciprocal condition numbers are computed for the eigenvalues only. If sense = V, reciprocal condition numbers are computed for the right eigenvectors only. If sense = B, reciprocal condition numbers are computed for the right eigenvectors and the eigenvectors. If sense = E,B, the right and left eigenvectors must be computed.

      source
      ggev!(jobvl, jobvr, A, B) -> (alpha, beta, vl, vr)

      Finds the generalized eigendecomposition of A and B. If jobvl = N, the left eigenvectors aren't computed. If jobvr = N, the right eigenvectors aren't computed. If jobvl = V or jobvr = V, the corresponding eigenvectors are computed.

      source
      gtsv!(dl, d, du, B)

      Solves the equation A * X = B where A is a tridiagonal matrix with dl on the subdiagonal, d on the diagonal, and du on the superdiagonal.

      Overwrites B with the solution X and returns it.

      source
      gttrf!(dl, d, du) -> (dl, d, du, du2, ipiv)

      Finds the LU factorization of a tridiagonal matrix with dl on the subdiagonal, d on the diagonal, and du on the superdiagonal.

      Modifies dl, d, and du in-place and returns them and the second superdiagonal du2 and the pivoting vector ipiv.

      source
      gttrs!(trans, dl, d, du, du2, ipiv, B)

      Solves the equation A * X = B (trans = N), A.' * X = B (trans = T), or A' * X = B (trans = C) using the LU factorization computed by gttrf!. B is overwritten with the solution X.

      source
      orglq!(A, tau, k = length(tau))

      Explicitly finds the matrix Q of a LQ factorization after calling gelqf! on A. Uses the output of gelqf!. A is overwritten by Q.

      source
      orgqr!(A, tau, k = length(tau))

      Explicitly finds the matrix Q of a QR factorization after calling geqrf! on A. Uses the output of geqrf!. A is overwritten by Q.

      source
      orgql!(A, tau, k = length(tau))

      Explicitly finds the matrix Q of a QL factorization after calling geqlf! on A. Uses the output of geqlf!. A is overwritten by Q.

      source
      orgrq!(A, tau, k = length(tau))

      Explicitly finds the matrix Q of a RQ factorization after calling gerqf! on A. Uses the output of gerqf!. A is overwritten by Q.

      source
      ormlq!(side, trans, A, tau, C)

      Computes Q * C (trans = N), Q.' * C (trans = T), Q' * C (trans = C) for side = L or the equivalent right-sided multiplication for side = R using Q from a LQ factorization of A computed using gelqf!. C is overwritten.

      source
      ormqr!(side, trans, A, tau, C)

      Computes Q * C (trans = N), Q.' * C (trans = T), Q' * C (trans = C) for side = L or the equivalent right-sided multiplication for side = R using Q from a QR factorization of A computed using geqrf!. C is overwritten.

      source
      ormql!(side, trans, A, tau, C)

      Computes Q * C (trans = N), Q.' * C (trans = T), Q' * C (trans = C) for side = L or the equivalent right-sided multiplication for side = R using Q from a QL factorization of A computed using geqlf!. C is overwritten.

      source
      ormrq!(side, trans, A, tau, C)

      Computes Q * C (trans = N), Q.' * C (trans = T), Q' * C (trans = C) for side = L or the equivalent right-sided multiplication for side = R using Q from a RQ factorization of A computed using gerqf!. C is overwritten.

      source
      gemqrt!(side, trans, V, T, C)

      Computes Q * C (trans = N), Q.' * C (trans = T), Q' * C (trans = C) for side = L or the equivalent right-sided multiplication for side = R using Q from a QR factorization of A computed using geqrt!. C is overwritten.

      source
      posv!(uplo, A, B) -> (A, B)

      Finds the solution to A * X = B where A is a symmetric or Hermitian positive definite matrix. If uplo = U the upper Cholesky decomposition of A is computed. If uplo = L the lower Cholesky decomposition of A is computed. A is overwritten by its Cholesky decomposition. B is overwritten with the solution X.

      source
      potrf!(uplo, A)

      Computes the Cholesky (upper if uplo = U, lower if uplo = L) decomposition of positive-definite matrix A. A is overwritten and returned with an info code.

      source
      potri!(uplo, A)

      Computes the inverse of positive-definite matrix A after calling potrf! to find its (upper if uplo = U, lower if uplo = L) Cholesky decomposition.

      A is overwritten by its inverse and returned.

      source
      potrs!(uplo, A, B)

      Finds the solution to A * X = B where A is a symmetric or Hermitian positive definite matrix whose Cholesky decomposition was computed by potrf!. If uplo = U the upper Cholesky decomposition of A was computed. If uplo = L the lower Cholesky decomposition of A was computed. B is overwritten with the solution X.

      source
      pstrf!(uplo, A, tol) -> (A, piv, rank, info)

      Computes the (upper if uplo = U, lower if uplo = L) pivoted Cholesky decomposition of positive-definite matrix A with a user-set tolerance tol. A is overwritten by its Cholesky decomposition.

      Returns A, the pivots piv, the rank of A, and an info code. If info = 0, the factorization succeeded. If info = i > 0, then A is indefinite or rank-deficient.

      source
      ptsv!(D, E, B)

      Solves A * X = B for positive-definite tridiagonal A. D is the diagonal of A and E is the off-diagonal. B is overwritten with the solution X and returned.

      source
      pttrf!(D, E)

      Computes the LDLt factorization of a positive-definite tridiagonal matrix with D as diagonal and E as off-diagonal. D and E are overwritten and returned.

      source
      pttrs!(D, E, B)

      Solves A * X = B for positive-definite tridiagonal A with diagonal D and off-diagonal E after computing A's LDLt factorization using pttrf!. B is overwritten with the solution X.

      source
      trtri!(uplo, diag, A)

      Finds the inverse of (upper if uplo = U, lower if uplo = L) triangular matrix A. If diag = N, A has non-unit diagonal elements. If diag = U, all diagonal elements of A are one. A is overwritten with its inverse.

      source
      trtrs!(uplo, trans, diag, A, B)

      Solves A * X = B (trans = N), A.' * X = B (trans = T), or A' * X = B (trans = C) for (upper if uplo = U, lower if uplo = L) triangular matrix A. If diag = N, A has non-unit diagonal elements. If diag = U, all diagonal elements of A are one. B is overwritten with the solution X.

      source
      trcon!(norm, uplo, diag, A)

      Finds the reciprocal condition number of (upper if uplo = U, lower if uplo = L) triangular matrix A. If diag = N, A has non-unit diagonal elements. If diag = U, all diagonal elements of A are one. If norm = I, the condition number is found in the infinity norm. If norm = O or 1, the condition number is found in the one norm.

      source
      trevc!(side, howmny, select, T, VL = similar(T), VR = similar(T))

      Finds the eigensystem of an upper triangular matrix T. If side = R, the right eigenvectors are computed. If side = L, the left eigenvectors are computed. If side = B, both sets are computed. If howmny = A, all eigenvectors are found. If howmny = B, all eigenvectors are found and backtransformed using VL and VR. If howmny = S, only the eigenvectors corresponding to the values in select are computed.

      source
      trrfs!(uplo, trans, diag, A, B, X, Ferr, Berr) -> (Ferr, Berr)

      Estimates the error in the solution to A * X = B (trans = N), A.' * X = B (trans = T), A' * X = B (trans = C) for side = L, or the equivalent equations a right-handed side = R X * A after computing X using trtrs!. If uplo = U, A is upper triangular. If uplo = L, A is lower triangular. If diag = N, A has non-unit diagonal elements. If diag = U, all diagonal elements of A are one. Ferr and Berr are optional inputs. Ferr is the forward error and Berr is the backward error, each component-wise.

      source
      stev!(job, dv, ev) -> (dv, Zmat)

      Computes the eigensystem for a symmetric tridiagonal matrix with dv as diagonal and ev as off-diagonal. If job = N only the eigenvalues are found and returned in dv. If job = V then the eigenvectors are also found and returned in Zmat.

      source
      stebz!(range, order, vl, vu, il, iu, abstol, dv, ev) -> (dv, iblock, isplit)

      Computes the eigenvalues for a symmetric tridiagonal matrix with dv as diagonal and ev as off-diagonal. If range = A, all the eigenvalues are found. If range = V, the eigenvalues in the half-open interval (vl, vu] are found. If range = I, the eigenvalues with indices between il and iu are found. If order = B, eigvalues are ordered within a block. If order = E, they are ordered across all the blocks. abstol can be set as a tolerance for convergence.

      source
      stegr!(jobz, range, dv, ev, vl, vu, il, iu) -> (w, Z)

      Computes the eigenvalues (jobz = N) or eigenvalues and eigenvectors (jobz = V) for a symmetric tridiagonal matrix with dv as diagonal and ev as off-diagonal. If range = A, all the eigenvalues are found. If range = V, the eigenvalues in the half-open interval (vl, vu] are found. If range = I, the eigenvalues with indices between il and iu are found. The eigenvalues are returned in w and the eigenvectors in Z.

      source
      stein!(dv, ev_in, w_in, iblock_in, isplit_in)

      Computes the eigenvectors for a symmetric tridiagonal matrix with dv as diagonal and ev_in as off-diagonal. w_in specifies the input eigenvalues for which to find corresponding eigenvectors. iblock_in specifies the submatrices corresponding to the eigenvalues in w_in. isplit_in specifies the splitting points between the submatrix blocks.

      source
      syconv!(uplo, A, ipiv) -> (A, work)

      Converts a symmetric matrix A (which has been factorized into a triangular matrix) into two matrices L and D. If uplo = U, A is upper triangular. If uplo = L, it is lower triangular. ipiv is the pivot vector from the triangular factorization. A is overwritten by L and D.

      source
      sysv!(uplo, A, B) -> (B, A, ipiv)

      Finds the solution to A * X = B for symmetric matrix A. If uplo = U, the upper half of A is stored. If uplo = L, the lower half is stored. B is overwritten by the solution X. A is overwritten by its Bunch-Kaufman factorization. ipiv contains pivoting information about the factorization.

      source
      sytrf!(uplo, A) -> (A, ipiv, info)

      Computes the Bunch-Kaufman factorization of a symmetric matrix A. If uplo = U, the upper half of A is stored. If uplo = L, the lower half is stored.

      Returns A, overwritten by the factorization, a pivot vector ipiv, and the error code info which is a non-negative integer. If info is positive the matrix is singular and the diagonal part of the factorization is exactly zero at position info.

      source
      sytri!(uplo, A, ipiv)

      Computes the inverse of a symmetric matrix A using the results of sytrf!. If uplo = U, the upper half of A is stored. If uplo = L, the lower half is stored. A is overwritten by its inverse.

      source
      sytrs!(uplo, A, ipiv, B)

      Solves the equation A * X = B for a symmetric matrix A using the results of sytrf!. If uplo = U, the upper half of A is stored. If uplo = L, the lower half is stored. B is overwritten by the solution X.

      source
      hesv!(uplo, A, B) -> (B, A, ipiv)

      Finds the solution to A * X = B for Hermitian matrix A. If uplo = U, the upper half of A is stored. If uplo = L, the lower half is stored. B is overwritten by the solution X. A is overwritten by its Bunch-Kaufman factorization. ipiv contains pivoting information about the factorization.

      source
      hetrf!(uplo, A) -> (A, ipiv, info)

      Computes the Bunch-Kaufman factorization of a Hermitian matrix A. If uplo = U, the upper half of A is stored. If uplo = L, the lower half is stored.

      Returns A, overwritten by the factorization, a pivot vector ipiv, and the error code info which is a non-negative integer. If info is positive the matrix is singular and the diagonal part of the factorization is exactly zero at position info.

      source
      hetri!(uplo, A, ipiv)

      Computes the inverse of a Hermitian matrix A using the results of sytrf!. If uplo = U, the upper half of A is stored. If uplo = L, the lower half is stored. A is overwritten by its inverse.

      source
      hetrs!(uplo, A, ipiv, B)

      Solves the equation A * X = B for a Hermitian matrix A using the results of sytrf!. If uplo = U, the upper half of A is stored. If uplo = L, the lower half is stored. B is overwritten by the solution X.

      source
      syev!(jobz, uplo, A)

      Finds the eigenvalues (jobz = N) or eigenvalues and eigenvectors (jobz = V) of a symmetric matrix A. If uplo = U, the upper triangle of A is used. If uplo = L, the lower triangle of A is used.

      source
      syevr!(jobz, range, uplo, A, vl, vu, il, iu, abstol) -> (W, Z)

      Finds the eigenvalues (jobz = N) or eigenvalues and eigenvectors (jobz = V) of a symmetric matrix A. If uplo = U, the upper triangle of A is used. If uplo = L, the lower triangle of A is used. If range = A, all the eigenvalues are found. If range = V, the eigenvalues in the half-open interval (vl, vu] are found. If range = I, the eigenvalues with indices between il and iu are found. abstol can be set as a tolerance for convergence.

      The eigenvalues are returned in W and the eigenvectors in Z.

      source
      sygvd!(itype, jobz, uplo, A, B) -> (w, A, B)

      Finds the generalized eigenvalues (jobz = N) or eigenvalues and eigenvectors (jobz = V) of a symmetric matrix A and symmetric positive-definite matrix B. If uplo = U, the upper triangles of A and B are used. If uplo = L, the lower triangles of A and B are used. If itype = 1, the problem to solve is A * x = lambda * B * x. If itype = 2, the problem to solve is A * B * x = lambda * x. If itype = 3, the problem to solve is B * A * x = lambda * x.

      source
      bdsqr!(uplo, d, e_, Vt, U, C) -> (d, Vt, U, C)

      Computes the singular value decomposition of a bidiagonal matrix with d on the diagonal and e_ on the off-diagonal. If uplo = U, e_ is the superdiagonal. If uplo = L, e_ is the subdiagonal. Can optionally also compute the product Q' * C.

      Returns the singular values in d, and the matrix C overwritten with Q' * C.

      source
      bdsdc!(uplo, compq, d, e_) -> (d, e, u, vt, q, iq)

      Computes the singular value decomposition of a bidiagonal matrix with d on the diagonal and e_ on the off-diagonal using a divide and conqueq method. If uplo = U, e_ is the superdiagonal. If uplo = L, e_ is the subdiagonal. If compq = N, only the singular values are found. If compq = I, the singular values and vectors are found. If compq = P, the singular values and vectors are found in compact form. Only works for real types.

      Returns the singular values in d, and if compq = P, the compact singular vectors in iq.

      source
      gecon!(normtype, A, anorm)

      Finds the reciprocal condition number of matrix A. If normtype = I, the condition number is found in the infinity norm. If normtype = O or 1, the condition number is found in the one norm. A must be the result of getrf! and anorm is the norm of A in the relevant norm.

      source
      gehrd!(ilo, ihi, A) -> (A, tau)

      Converts a matrix A to Hessenberg form. If A is balanced with gebal! then ilo and ihi are the outputs of gebal!. Otherwise they should be ilo = 1 and ihi = size(A,2). tau contains the elementary reflectors of the factorization.

      source
      orghr!(ilo, ihi, A, tau)

      Explicitly finds Q, the orthogonal/unitary matrix from gehrd!. ilo, ihi, A, and tau must correspond to the input/output to gehrd!.

      source
      gees!(jobvs, A) -> (A, vs, w)

      Computes the eigenvalues (jobvs = N) or the eigenvalues and Schur vectors (jobvs = V) of matrix A. A is overwritten by its Schur form.

      Returns A, vs containing the Schur vectors, and w, containing the eigenvalues.

      source
      gges!(jobvsl, jobvsr, A, B) -> (A, B, alpha, beta, vsl, vsr)

      Computes the generalized eigenvalues, generalized Schur form, left Schur vectors (jobsvl = V), or right Schur vectors (jobvsr = V) of A and B.

      The generalized eigenvalues are returned in alpha and beta. The left Schur vectors are returned in vsl and the right Schur vectors are returned in vsr.

      source
      trexc!(compq, ifst, ilst, T, Q) -> (T, Q)

      Reorder the Schur factorization of a matrix. If compq = V, the Schur vectors Q are reordered. If compq = N they are not modified. ifst and ilst specify the reordering of the vectors.

      source
      trsen!(compq, job, select, T, Q) -> (T, Q, w)

      Reorder the Schur factorization of a matrix and optionally finds reciprocal condition numbers. If job = N, no condition numbers are found. If job = E, only the condition number for this cluster of eigenvalues is found. If job = V, only the condition number for the invariant subspace is found. If job = B then the condition numbers for the cluster and subspace are found. If compq = V the Schur vectors Q are updated. If compq = N the Schur vectors are not modified. select determines which eigenvalues are in the cluster.

      Returns T, Q, and reordered eigenvalues in w.

      source
      tgsen!(select, S, T, Q, Z) -> (S, T, alpha, beta, Q, Z)

      Reorders the vectors of a generalized Schur decomposition. select specifices the eigenvalues in each cluster.

      source
      trsyl!(transa, transb, A, B, C, isgn=1) -> (C, scale)

      Solves the Sylvester matrix equation A * X +/- X * B = scale*C where A and B are both quasi-upper triangular. If transa = N, A is not modified. If transa = T, A is transposed. If transa = C, A is conjugate transposed. Similarly for transb and B. If isgn = 1, the equation A * X + X * B = scale * C is solved. If isgn = -1, the equation A * X - X * B = scale * C is solved.

      Returns X (overwriting C) and scale.

      source
      diff --git a/julia-0.6.3/share/doc/julia/html/en/stdlib/math.html b/julia-0.6.3/share/doc/julia/html/en/stdlib/math.html deleted file mode 100644 index 1a880fc..0000000 --- a/julia-0.6.3/share/doc/julia/html/en/stdlib/math.html +++ /dev/null @@ -1,508 +0,0 @@ - -Mathematics · The Julia Language

      Mathematics

      Mathematics

      Mathematical Operators

      Base.:-Method.
      -(x)

      Unary minus operator.

      source
      Base.:+Function.
      +(x, y...)

      Addition operator. x+y+z+... calls this function with all arguments, i.e. +(x, y, z, ...).

      source
      Base.:-Method.
      -(x, y)

      Subtraction operator.

      source
      Base.:*Method.
      *(x, y...)

      Multiplication operator. x*y*z*... calls this function with all arguments, i.e. *(x, y, z, ...).

      source
      Base.:/Function.
      /(x, y)

      Right division operator: multiplication of x by the inverse of y on the right. Gives floating-point results for integer arguments.

      source
      Base.:\Method.
      \(x, y)

      Left division operator: multiplication of y by the inverse of x on the left. Gives floating-point results for integer arguments.

      julia> 3 \ 6
      -2.0
      -
      -julia> inv(3) * 6
      -2.0
      -
      -julia> A = [1 2; 3 4]; x = [5, 6];
      -
      -julia> A \ x
      -2-element Array{Float64,1}:
      - -4.0
      -  4.5
      -
      -julia> inv(A) * x
      -2-element Array{Float64,1}:
      - -4.0
      -  4.5
      source
      Base.:^Method.
      ^(x, y)

      Exponentiation operator. If x is a matrix, computes matrix exponentiation.

      If y is an Int literal (e.g. 2 in x^2 or -3 in x^-3), the Julia code x^y is transformed by the compiler to Base.literal_pow(^, x, Val{y}), to enable compile-time specialization on the value of the exponent. (As a default fallback we have Base.literal_pow(^, x, Val{y}) = ^(x,y), where usually ^ == Base.^ unless ^ has been defined in the calling namespace.)

      julia> 3^5
      -243
      -
      -julia> A = [1 2; 3 4]
      -2×2 Array{Int64,2}:
      - 1  2
      - 3  4
      -
      -julia> A^3
      -2×2 Array{Int64,2}:
      - 37   54
      - 81  118
      source
      Base.fmaFunction.
      fma(x, y, z)

      Computes x*y+z without rounding the intermediate result x*y. On some systems this is significantly more expensive than x*y+z. fma is used to improve accuracy in certain algorithms. See muladd.

      source
      Base.muladdFunction.
      muladd(x, y, z)

      Combined multiply-add, computes x*y+z in an efficient manner. This may on some systems be equivalent to x*y+z, or to fma(x,y,z). muladd is used to improve performance. See fma.

      Example

      julia> muladd(3, 2, 1)
      -7
      -
      -julia> 3 * 2 + 1
      -7
      source
      Base.divFunction.
      div(x, y)
      -÷(x, y)

      The quotient from Euclidean division. Computes x/y, truncated to an integer.

      julia> 9 ÷ 4
      -2
      -
      -julia> -5 ÷ 3
      --1
      source
      Base.fldFunction.
      fld(x, y)

      Largest integer less than or equal to x/y.

      julia> fld(7.3,5.5)
      -1.0
      source
      Base.cldFunction.
      cld(x, y)

      Smallest integer larger than or equal to x/y.

      julia> cld(5.5,2.2)
      -3.0
      source
      Base.modFunction.
      mod(x, y)
      -rem(x, y, RoundDown)

      The reduction of x modulo y, or equivalently, the remainder of x after floored division by y, i.e.

      x - y*fld(x,y)

      if computed without intermediate rounding.

      The result will have the same sign as y, and magnitude less than abs(y) (with some exceptions, see note below).

      Note

      When used with floating point values, the exact result may not be representable by the type, and so rounding error may occur. In particular, if the exact result is very close to y, then it may be rounded to y.

      julia> mod(8, 3)
      -2
      -
      -julia> mod(9, 3)
      -0
      -
      -julia> mod(8.9, 3)
      -2.9000000000000004
      -
      -julia> mod(eps(), 3)
      -2.220446049250313e-16
      -
      -julia> mod(-eps(), 3)
      -3.0
      source
      rem(x::Integer, T::Type{<:Integer}) -> T
      -mod(x::Integer, T::Type{<:Integer}) -> T
      -%(x::Integer, T::Type{<:Integer}) -> T

      Find y::T such that xy (mod n), where n is the number of integers representable in T, and y is an integer in [typemin(T),typemax(T)]. If T can represent any integer (e.g. T == BigInt), then this operation corresponds to a conversion to T.

      julia> 129 % Int8
      --127
      source
      Base.remFunction.
      rem(x, y)
      -%(x, y)

      Remainder from Euclidean division, returning a value of the same sign as x, and smaller in magnitude than y. This value is always exact.

      julia> x = 15; y = 4;
      -
      -julia> x % y
      -3
      -
      -julia> x == div(x, y) * y + rem(x, y)
      -true
      source
      Base.Math.rem2piFunction.
      rem2pi(x, r::RoundingMode)

      Compute the remainder of x after integer division by , with the quotient rounded according to the rounding mode r. In other words, the quantity

      x - 2π*round(x/(2π),r)

      without any intermediate rounding. This internally uses a high precision approximation of 2π, and so will give a more accurate result than rem(x,2π,r)

      • if r == RoundNearest, then the result is in the interval $[-π, π]$. This will generally be the most accurate result.

      • if r == RoundToZero, then the result is in the interval $[0, 2π]$ if x is positive,. or $[-2π, 0]$ otherwise.

      • if r == RoundDown, then the result is in the interval $[0, 2π]$.

      • if r == RoundUp, then the result is in the interval $[-2π, 0]$.

      Example

      julia> rem2pi(7pi/4, RoundNearest)
      --0.7853981633974485
      -
      -julia> rem2pi(7pi/4, RoundDown)
      -5.497787143782138
      source
      Base.Math.mod2piFunction.
      mod2pi(x)

      Modulus after division by , returning in the range $[0,2π)$.

      This function computes a floating point representation of the modulus after division by numerically exact , and is therefore not exactly the same as mod(x,2π), which would compute the modulus of x relative to division by the floating-point number .

      Example

      julia> mod2pi(9*pi/4)
      -0.7853981633974481
      source
      Base.divremFunction.
      divrem(x, y)

      The quotient and remainder from Euclidean division. Equivalent to (div(x,y), rem(x,y)) or (x÷y, x%y).

      julia> divrem(3,7)
      -(0, 3)
      -
      -julia> divrem(7,3)
      -(2, 1)
      source
      Base.fldmodFunction.
      fldmod(x, y)

      The floored quotient and modulus after division. Equivalent to (fld(x,y), mod(x,y)).

      source
      Base.fld1Function.
      fld1(x, y)

      Flooring division, returning a value consistent with mod1(x,y)

      See also: mod1.

      julia> x = 15; y = 4;
      -
      -julia> fld1(x, y)
      -4
      -
      -julia> x == fld(x, y) * y + mod(x, y)
      -true
      -
      -julia> x == (fld1(x, y) - 1) * y + mod1(x, y)
      -true
      source
      Base.mod1Function.
      mod1(x, y)

      Modulus after flooring division, returning a value r such that mod(r, y) == mod(x, y) in the range $(0, y]$ for positive y and in the range $[y,0)$ for negative y.

      julia> mod1(4, 2)
      -2
      -
      -julia> mod1(4, 3)
      -1
      source
      Base.fldmod1Function.
      fldmod1(x, y)

      Return (fld1(x,y), mod1(x,y)).

      See also: fld1, mod1.

      source
      Base.://Function.
      //(num, den)

      Divide two integers or rational numbers, giving a Rational result.

      julia> 3 // 5
      -3//5
      -
      -julia> (3 // 5) // (2 // 1)
      -3//10
      source
      Base.rationalizeFunction.
      rationalize([T<:Integer=Int,] x; tol::Real=eps(x))

      Approximate floating point number x as a Rational number with components of the given integer type. The result will differ from x by no more than tol. If T is not provided, it defaults to Int.

      julia> rationalize(5.6)
      -28//5
      -
      -julia> a = rationalize(BigInt, 10.3)
      -103//10
      -
      -julia> typeof(numerator(a))
      -BigInt
      source
      Base.numeratorFunction.
      numerator(x)

      Numerator of the rational representation of x.

      julia> numerator(2//3)
      -2
      -
      -julia> numerator(4)
      -4
      source
      Base.denominatorFunction.
      denominator(x)

      Denominator of the rational representation of x.

      julia> denominator(2//3)
      -3
      -
      -julia> denominator(4)
      -1
      source
      Base.:<<Function.
      <<(x, n)

      Left bit shift operator, x << n. For n >= 0, the result is x shifted left by n bits, filling with 0s. This is equivalent to x * 2^n. For n < 0, this is equivalent to x >> -n.

      julia> Int8(3) << 2
      -12
      -
      -julia> bits(Int8(3))
      -"00000011"
      -
      -julia> bits(Int8(12))
      -"00001100"

      See also >>, >>>.

      source
      <<(B::BitVector, n) -> BitVector

      Left bit shift operator, B << n. For n >= 0, the result is B with elements shifted n positions backwards, filling with false values. If n < 0, elements are shifted forwards. Equivalent to B >> -n.

      Examples

      julia> B = BitVector([true, false, true, false, false])
      -5-element BitArray{1}:
      -  true
      - false
      -  true
      - false
      - false
      -
      -julia> B << 1
      -5-element BitArray{1}:
      - false
      -  true
      - false
      - false
      - false
      -
      -julia> B << -1
      -5-element BitArray{1}:
      - false
      -  true
      - false
      -  true
      - false
      source
      Base.:>>Function.
      >>(x, n)

      Right bit shift operator, x >> n. For n >= 0, the result is x shifted right by n bits, where n >= 0, filling with 0s if x >= 0, 1s if x < 0, preserving the sign of x. This is equivalent to fld(x, 2^n). For n < 0, this is equivalent to x << -n.

      julia> Int8(13) >> 2
      -3
      -
      -julia> bits(Int8(13))
      -"00001101"
      -
      -julia> bits(Int8(3))
      -"00000011"
      -
      -julia> Int8(-14) >> 2
      --4
      -
      -julia> bits(Int8(-14))
      -"11110010"
      -
      -julia> bits(Int8(-4))
      -"11111100"

      See also >>>, <<.

      source
      >>(B::BitVector, n) -> BitVector

      Right bit shift operator, B >> n. For n >= 0, the result is B with elements shifted n positions forward, filling with false values. If n < 0, elements are shifted backwards. Equivalent to B << -n.

      Example

      julia> B = BitVector([true, false, true, false, false])
      -5-element BitArray{1}:
      -  true
      - false
      -  true
      - false
      - false
      -
      -julia> B >> 1
      -5-element BitArray{1}:
      - false
      -  true
      - false
      -  true
      - false
      -
      -julia> B >> -1
      -5-element BitArray{1}:
      - false
      -  true
      - false
      - false
      - false
      source
      Base.:>>>Function.
      >>>(x, n)

      Unsigned right bit shift operator, x >>> n. For n >= 0, the result is x shifted right by n bits, where n >= 0, filling with 0s. For n < 0, this is equivalent to x << -n.

      For Unsigned integer types, this is equivalent to >>. For Signed integer types, this is equivalent to signed(unsigned(x) >> n).

      julia> Int8(-14) >>> 2
      -60
      -
      -julia> bits(Int8(-14))
      -"11110010"
      -
      -julia> bits(Int8(60))
      -"00111100"

      BigInts are treated as if having infinite size, so no filling is required and this is equivalent to >>.

      See also >>, <<.

      source
      >>>(B::BitVector, n) -> BitVector

      Unsigned right bitshift operator, B >>> n. Equivalent to B >> n. See >> for details and examples.

      source
      Base.colonFunction.
      colon(start, [step], stop)

      Called by : syntax for constructing ranges.

      julia> colon(1, 2, 5)
      -1:2:5
      source
      :(start, [step], stop)

      Range operator. a:b constructs a range from a to b with a step size of 1, and a:s:b is similar but uses a step size of s. These syntaxes call the function colon. The colon is also used in indexing to select whole dimensions.

      source
      Base.rangeFunction.
      range(start, [step], length)

      Construct a range by length, given a starting value and optional step (defaults to 1).

      source
      Base.OneToType.
      Base.OneTo(n)

      Define an AbstractUnitRange that behaves like 1:n, with the added distinction that the lower limit is guaranteed (by the type system) to be 1.

      source
      StepRangeLen{T,R,S}(ref::R, step::S, len, [offset=1])

      A range r where r[i] produces values of type T, parametrized by a reference value, a step, and the length. By default ref is the starting value r[1], but alternatively you can supply it as the value of r[offset] for some other index 1 <= offset <= len. In conjunction with TwicePrecision this can be used to implement ranges that are free of roundoff error.

      source
      Base.:==Function.
      ==(x, y)

      Generic equality operator, giving a single Bool result. Falls back to ===. Should be implemented for all types with a notion of equality, based on the abstract value that an instance represents. For example, all numeric types are compared by numeric value, ignoring type. Strings are compared as sequences of characters, ignoring encoding.

      Follows IEEE semantics for floating-point numbers.

      Collections should generally implement == by calling == recursively on all contents.

      New numeric types should implement this function for two arguments of the new type, and handle comparison to other types via promotion rules where possible.

      source
      Base.:!=Function.
      !=(x, y)
      -≠(x,y)

      Not-equals comparison operator. Always gives the opposite answer as ==. New types should generally not implement this, and rely on the fallback definition !=(x,y) = !(x==y) instead.

      julia> 3 != 2
      -true
      -
      -julia> "foo" ≠ "foo"
      -false
      source
      Base.:!==Function.
      !==(x, y)
      -≢(x,y)

      Equivalent to !(x === y).

      julia> a = [1, 2]; b = [1, 2];
      -
      -julia> a ≢ b
      -true
      -
      -julia> a ≢ a
      -false
      source
      Base.:<Function.
      <(x, y)

      Less-than comparison operator. New numeric types should implement this function for two arguments of the new type. Because of the behavior of floating-point NaN values, < implements a partial order. Types with a canonical partial order should implement <, and types with a canonical total order should implement isless.

      julia> 'a' < 'b'
      -true
      -
      -julia> "abc" < "abd"
      -true
      -
      -julia> 5 < 3
      -false
      source
      Base.:<=Function.
      <=(x, y)
      -≤(x,y)

      Less-than-or-equals comparison operator.

      julia> 'a' <= 'b'
      -true
      -
      -julia> 7 ≤ 7 ≤ 9
      -true
      -
      -julia> "abc" ≤ "abc"
      -true
      -
      -julia> 5 <= 3
      -false
      source
      Base.:>Function.
      >(x, y)

      Greater-than comparison operator. Generally, new types should implement < instead of this function, and rely on the fallback definition >(x, y) = y < x.

      julia> 'a' > 'b'
      -false
      -
      -julia> 7 > 3 > 1
      -true
      -
      -julia> "abc" > "abd"
      -false
      -
      -julia> 5 > 3
      -true
      source
      Base.:>=Function.
      >=(x, y)
      -≥(x,y)

      Greater-than-or-equals comparison operator.

      julia> 'a' >= 'b'
      -false
      -
      -julia> 7 ≥ 7 ≥ 3
      -true
      -
      -julia> "abc" ≥ "abc"
      -true
      -
      -julia> 5 >= 3
      -true
      source
      Base.cmpFunction.
      cmp(x,y)

      Return -1, 0, or 1 depending on whether x is less than, equal to, or greater than y, respectively. Uses the total order implemented by isless. For floating-point numbers, uses < but throws an error for unordered arguments.

      julia> cmp(1, 2)
      --1
      -
      -julia> cmp(2, 1)
      -1
      -
      -julia> cmp(2+im, 3-im)
      -ERROR: MethodError: no method matching isless(::Complex{Int64}, ::Complex{Int64})
      -[...]
      source
      Base.:~Function.
      ~(x)

      Bitwise not.

      Examples

      julia> ~4
      --5
      -
      -julia> ~10
      --11
      -
      -julia> ~true
      -false
      source
      Base.:&Function.
      &(x, y)

      Bitwise and.

      Examples

      julia> 4 & 10
      -0
      -
      -julia> 4 & 12
      -4
      source
      Base.:|Function.
      |(x, y)

      Bitwise or.

      Examples

      julia> 4 | 10
      -14
      -
      -julia> 4 | 1
      -5
      source
      Base.xorFunction.
      xor(x, y)
      -⊻(x, y)

      Bitwise exclusive or of x and y. The infix operation a ⊻ b is a synonym for xor(a,b), and can be typed by tab-completing \xor or \veebar in the Julia REPL.

      julia> [true; true; false] .⊻ [true; false; false]
      -3-element BitArray{1}:
      - false
      -  true
      - false
      source
      Base.:!Function.
      !(x)

      Boolean not.

      julia> !true
      -false
      -
      -julia> !false
      -true
      -
      -julia> .![true false true]
      -1×3 BitArray{2}:
      - false  true  false
      source
      !f::Function

      Predicate function negation: when the argument of ! is a function, it returns a function which computes the boolean negation of f. Example:

      julia> str = "∀ ε > 0, ∃ δ > 0: |x-y| < δ ⇒ |f(x)-f(y)| < ε"
      -"∀ ε > 0, ∃ δ > 0: |x-y| < δ ⇒ |f(x)-f(y)| < ε"
      -
      -julia> filter(isalpha, str)
      -"εδxyδfxfyε"
      -
      -julia> filter(!isalpha, str)
      -"∀  > 0, ∃  > 0: |-| <  ⇒ |()-()| < "
      source
      &&Keyword.
      x && y

      Short-circuiting boolean AND.

      source
      ||Keyword.
      x || y

      Short-circuiting boolean OR.

      source

      Mathematical Functions

      Base.isapproxFunction.
      isapprox(x, y; rtol::Real=sqrt(eps), atol::Real=0, nans::Bool=false, norm::Function)

      Inexact equality comparison: true if norm(x-y) <= atol + rtol*max(norm(x), norm(y)). The default atol is zero and the default rtol depends on the types of x and y. The keyword argument nans determines whether or not NaN values are considered equal (defaults to false).

      For real or complex floating-point values, rtol defaults to sqrt(eps(typeof(real(x-y)))). This corresponds to requiring equality of about half of the significand digits. For other types, rtol defaults to zero.

      x and y may also be arrays of numbers, in which case norm defaults to vecnorm but may be changed by passing a norm::Function keyword argument. (For numbers, norm is the same thing as abs.) When x and y are arrays, if norm(x-y) is not finite (i.e. ±Inf or NaN), the comparison falls back to checking whether all elements of x and y are approximately equal component-wise.

      The binary operator is equivalent to isapprox with the default arguments, and x ≉ y is equivalent to !isapprox(x,y).

      julia> 0.1 ≈ (0.1 - 1e-10)
      -true
      -
      -julia> isapprox(10, 11; atol = 2)
      -true
      -
      -julia> isapprox([10.0^9, 1.0], [10.0^9, 2.0])
      -true
      source
      Base.sinFunction.
      sin(x)

      Compute sine of x, where x is in radians.

      source
      Base.cosFunction.
      cos(x)

      Compute cosine of x, where x is in radians.

      source
      Base.tanFunction.
      tan(x)

      Compute tangent of x, where x is in radians.

      source
      Base.Math.sindFunction.
      sind(x)

      Compute sine of x, where x is in degrees.

      source
      Base.Math.cosdFunction.
      cosd(x)

      Compute cosine of x, where x is in degrees.

      source
      Base.Math.tandFunction.
      tand(x)

      Compute tangent of x, where x is in degrees.

      source
      Base.Math.sinpiFunction.
      sinpi(x)

      Compute $\sin(\pi x)$ more accurately than sin(pi*x), especially for large x.

      source
      Base.Math.cospiFunction.
      cospi(x)

      Compute $\cos(\pi x)$ more accurately than cos(pi*x), especially for large x.

      source
      Base.sinhFunction.
      sinh(x)

      Compute hyperbolic sine of x.

      source
      Base.coshFunction.
      cosh(x)

      Compute hyperbolic cosine of x.

      source
      Base.tanhFunction.
      tanh(x)

      Compute hyperbolic tangent of x.

      source
      Base.asinFunction.
      asin(x)

      Compute the inverse sine of x, where the output is in radians.

      source
      Base.acosFunction.
      acos(x)

      Compute the inverse cosine of x, where the output is in radians

      source
      Base.atanFunction.
      atan(x)

      Compute the inverse tangent of x, where the output is in radians.

      source
      Base.Math.atan2Function.
      atan2(y, x)

      Compute the inverse tangent of y/x, using the signs of both x and y to determine the quadrant of the return value.

      source
      Base.Math.asindFunction.
      asind(x)

      Compute the inverse sine of x, where the output is in degrees.

      source
      Base.Math.acosdFunction.
      acosd(x)

      Compute the inverse cosine of x, where the output is in degrees.

      source
      Base.Math.atandFunction.
      atand(x)

      Compute the inverse tangent of x, where the output is in degrees.

      source
      Base.Math.secFunction.
      sec(x)

      Compute the secant of x, where x is in radians.

      source
      Base.Math.cscFunction.
      csc(x)

      Compute the cosecant of x, where x is in radians.

      source
      Base.Math.cotFunction.
      cot(x)

      Compute the cotangent of x, where x is in radians.

      source
      Base.Math.secdFunction.
      secd(x)

      Compute the secant of x, where x is in degrees.

      source
      Base.Math.cscdFunction.
      cscd(x)

      Compute the cosecant of x, where x is in degrees.

      source
      Base.Math.cotdFunction.
      cotd(x)

      Compute the cotangent of x, where x is in degrees.

      source
      Base.Math.asecFunction.
      asec(x)

      Compute the inverse secant of x, where the output is in radians.

      source
      Base.Math.acscFunction.
      acsc(x)

      Compute the inverse cosecant of x, where the output is in radians.

      source
      Base.Math.acotFunction.
      acot(x)

      Compute the inverse cotangent of x, where the output is in radians.

      source
      Base.Math.asecdFunction.
      asecd(x)

      Compute the inverse secant of x, where the output is in degrees.

      source
      Base.Math.acscdFunction.
      acscd(x)

      Compute the inverse cosecant of x, where the output is in degrees.

      source
      Base.Math.acotdFunction.
      acotd(x)

      Compute the inverse cotangent of x, where the output is in degrees.

      source
      Base.Math.sechFunction.
      sech(x)

      Compute the hyperbolic secant of x

      source
      Base.Math.cschFunction.
      csch(x)

      Compute the hyperbolic cosecant of x.

      source
      Base.Math.cothFunction.
      coth(x)

      Compute the hyperbolic cotangent of x.

      source
      Base.asinhFunction.
      asinh(x)

      Compute the inverse hyperbolic sine of x.

      source
      Base.acoshFunction.
      acosh(x)

      Compute the inverse hyperbolic cosine of x.

      source
      Base.atanhFunction.
      atanh(x)

      Compute the inverse hyperbolic tangent of x.

      source
      Base.Math.asechFunction.
      asech(x)

      Compute the inverse hyperbolic secant of x.

      source
      Base.Math.acschFunction.
      acsch(x)

      Compute the inverse hyperbolic cosecant of x.

      source
      Base.Math.acothFunction.
      acoth(x)

      Compute the inverse hyperbolic cotangent of x.

      source
      Base.Math.sincFunction.
      sinc(x)

      Compute $\sin(\pi x) / (\pi x)$ if $x \neq 0$, and $1$ if $x = 0$.

      source
      Base.Math.coscFunction.
      cosc(x)

      Compute $\cos(\pi x) / x - \sin(\pi x) / (\pi x^2)$ if $x \neq 0$, and $0$ if $x = 0$. This is the derivative of sinc(x).

      source
      Base.Math.deg2radFunction.
      deg2rad(x)

      Convert x from degrees to radians.

      julia> deg2rad(90)
      -1.5707963267948966
      source
      Base.Math.rad2degFunction.
      rad2deg(x)

      Convert x from radians to degrees.

      julia> rad2deg(pi)
      -180.0
      source
      Base.Math.hypotFunction.
      hypot(x, y)

      Compute the hypotenuse $\sqrt{x^2+y^2}$ avoiding overflow and underflow.

      Examples

      julia> a = 10^10;
      -
      -julia> hypot(a, a)
      -1.4142135623730951e10
      -
      -julia> √(a^2 + a^2) # a^2 overflows
      -ERROR: DomainError:
      -sqrt will only return a complex result if called with a complex argument. Try sqrt(complex(x)).
      -Stacktrace:
      - [1] sqrt(::Int64) at ./math.jl:434
      source
      hypot(x...)

      Compute the hypotenuse $\sqrt{\sum x_i^2}$ avoiding overflow and underflow.

      source
      Base.logMethod.
      log(x)

      Compute the natural logarithm of x. Throws DomainError for negative Real arguments. Use complex negative arguments to obtain complex results.

      There is an experimental variant in the Base.Math.JuliaLibm module, which is typically faster and more accurate.

      source
      Base.logMethod.
      log(b,x)

      Compute the base b logarithm of x. Throws DomainError for negative Real arguments.

      julia> log(4,8)
      -1.5
      -
      -julia> log(4,2)
      -0.5
      Note

      If b is a power of 2 or 10, log2 or log10 should be used, as these will typically be faster and more accurate. For example,

      julia> log(100,1000000)
      -2.9999999999999996
      -
      -julia> log10(1000000)/2
      -3.0
      source
      Base.log2Function.
      log2(x)

      Compute the logarithm of x to base 2. Throws DomainError for negative Real arguments.

      Example

      julia> log2(4)
      -2.0
      -
      -julia> log2(10)
      -3.321928094887362
      source
      Base.log10Function.
      log10(x)

      Compute the logarithm of x to base 10. Throws DomainError for negative Real arguments.

      Example

      julia> log10(100)
      -2.0
      -
      -julia> log10(2)
      -0.3010299956639812
      source
      Base.log1pFunction.
      log1p(x)

      Accurate natural logarithm of 1+x. Throws DomainError for Real arguments less than -1.

      There is an experimental variant in the Base.Math.JuliaLibm module, which is typically faster and more accurate.

      Examples

      julia> log1p(-0.5)
      --0.6931471805599453
      -
      -julia> log1p(0)
      -0.0
      source
      Base.Math.frexpFunction.
      frexp(val)

      Return (x,exp) such that x has a magnitude in the interval $[1/2, 1)$ or 0, and val is equal to $x \times 2^{exp}$.

      source
      Base.expFunction.
      exp(x)

      Compute the natural base exponential of x, in other words $e^x$.

      source
      Base.exp2Function.
      exp2(x)

      Compute $2^x$.

      julia> exp2(5)
      -32.0
      source
      Base.exp10Function.
      exp10(x)

      Compute $10^x$.

      Examples

      julia> exp10(2)
      -100.0
      -
      -julia> exp10(0.2)
      -1.5848931924611136
      source
      Base.Math.ldexpFunction.
      ldexp(x, n)

      Compute $x \times 2^n$.

      Example

      julia> ldexp(5., 2)
      -20.0
      source
      Base.Math.modfFunction.
      modf(x)

      Return a tuple (fpart,ipart) of the fractional and integral parts of a number. Both parts have the same sign as the argument.

      Example

      julia> modf(3.5)
      -(0.5, 3.0)
      source
      Base.expm1Function.
      expm1(x)

      Accurately compute $e^x-1$.

      source
      Base.roundMethod.
      round([T,] x, [digits, [base]], [r::RoundingMode])

      Rounds x to an integer value according to the provided RoundingMode, returning a value of the same type as x. When not specifying a rounding mode the global mode will be used (see rounding), which by default is round to the nearest integer (RoundNearest mode), with ties (fractional values of 0.5) being rounded to the nearest even integer.

      julia> round(1.7)
      -2.0
      -
      -julia> round(1.5)
      -2.0
      -
      -julia> round(2.5)
      -2.0

      The optional RoundingMode argument will change how the number gets rounded.

      round(T, x, [r::RoundingMode]) converts the result to type T, throwing an InexactError if the value is not representable.

      round(x, digits) rounds to the specified number of digits after the decimal place (or before if negative). round(x, digits, base) rounds using a base other than 10.

      julia> round(pi, 2)
      -3.14
      -
      -julia> round(pi, 3, 2)
      -3.125
      Note

      Rounding to specified digits in bases other than 2 can be inexact when operating on binary floating point numbers. For example, the Float64 value represented by 1.15 is actually less than 1.15, yet will be rounded to 1.2.

      julia> x = 1.15
      -1.15
      -
      -julia> @sprintf "%.20f" x
      -"1.14999999999999991118"
      -
      -julia> x < 115//100
      -true
      -
      -julia> round(x, 1)
      -1.2
      source
      RoundingMode

      A type used for controlling the rounding mode of floating point operations (via rounding/setrounding functions), or as optional arguments for rounding to the nearest integer (via the round function).

      Currently supported rounding modes are:

      source
      RoundNearest

      The default rounding mode. Rounds to the nearest integer, with ties (fractional values of 0.5) being rounded to the nearest even integer.

      source
      RoundNearestTiesAway

      Rounds to nearest integer, with ties rounded away from zero (C/C++ round behaviour).

      source
      RoundNearestTiesUp

      Rounds to nearest integer, with ties rounded toward positive infinity (Java/JavaScript round behaviour).

      source
      RoundToZero

      round using this rounding mode is an alias for trunc.

      source
      Base.Rounding.RoundUpConstant.
      RoundUp

      round using this rounding mode is an alias for ceil.

      source
      RoundDown

      round using this rounding mode is an alias for floor.

      source
      Base.roundMethod.
      round(z, RoundingModeReal, RoundingModeImaginary)

      Returns the nearest integral value of the same type as the complex-valued z to z, breaking ties using the specified RoundingModes. The first RoundingMode is used for rounding the real components while the second is used for rounding the imaginary components.

      source
      Base.ceilFunction.
      ceil([T,] x, [digits, [base]])

      ceil(x) returns the nearest integral value of the same type as x that is greater than or equal to x.

      ceil(T, x) converts the result to type T, throwing an InexactError if the value is not representable.

      digits and base work as for round.

      source
      Base.floorFunction.
      floor([T,] x, [digits, [base]])

      floor(x) returns the nearest integral value of the same type as x that is less than or equal to x.

      floor(T, x) converts the result to type T, throwing an InexactError if the value is not representable.

      digits and base work as for round.

      source
      Base.truncFunction.
      trunc([T,] x, [digits, [base]])

      trunc(x) returns the nearest integral value of the same type as x whose absolute value is less than or equal to x.

      trunc(T, x) converts the result to type T, throwing an InexactError if the value is not representable.

      digits and base work as for round.

      source
      Base.unsafe_truncFunction.
      unsafe_trunc(T, x)

      unsafe_trunc(T, x) returns the nearest integral value of type T whose absolute value is less than or equal to x. If the value is not representable by T, an arbitrary value will be returned.

      source
      Base.signifFunction.
      signif(x, digits, [base])

      Rounds (in the sense of round) x so that there are digits significant digits, under a base base representation, default 10. E.g., signif(123.456, 2) is 120.0, and signif(357.913, 4, 2) is 352.0.

      source
      Base.minFunction.
      min(x, y, ...)

      Return the minimum of the arguments. See also the minimum function to take the minimum element from a collection.

      julia> min(2, 5, 1)
      -1
      source
      Base.maxFunction.
      max(x, y, ...)

      Return the maximum of the arguments. See also the maximum function to take the maximum element from a collection.

      julia> max(2, 5, 1)
      -5
      source
      Base.minmaxFunction.
      minmax(x, y)

      Return (min(x,y), max(x,y)). See also: extrema that returns (minimum(x), maximum(x)).

      julia> minmax('c','b')
      -('b', 'c')
      source
      Base.Math.clampFunction.
      clamp(x, lo, hi)

      Return x if lo <= x <= hi. If x < lo, return lo. If x > hi, return hi. Arguments are promoted to a common type.

      julia> clamp.([pi, 1.0, big(10.)], 2., 9.)
      -3-element Array{BigFloat,1}:
      - 3.141592653589793238462643383279502884197169399375105820974944592307816406286198
      - 2.000000000000000000000000000000000000000000000000000000000000000000000000000000
      - 9.000000000000000000000000000000000000000000000000000000000000000000000000000000
      source
      Base.Math.clamp!Function.
      clamp!(array::AbstractArray, lo, hi)

      Restrict values in array to the specified range, in-place. See also clamp.

      source
      Base.absFunction.
      abs(x)

      The absolute value of x.

      When abs is applied to signed integers, overflow may occur, resulting in the return of a negative value. This overflow occurs only when abs is applied to the minimum representable value of a signed integer. That is, when x == typemin(typeof(x)), abs(x) == x < 0, not -x as might be expected.

      julia> abs(-3)
      -3
      -
      -julia> abs(1 + im)
      -1.4142135623730951
      -
      -julia> abs(typemin(Int64))
      --9223372036854775808
      source
      Base.checked_abs(x)

      Calculates abs(x), checking for overflow errors where applicable. For example, standard two's complement signed integers (e.g. Int) cannot represent abs(typemin(Int)), thus leading to an overflow.

      The overflow protection may impose a perceptible performance penalty.

      source
      Base.checked_neg(x)

      Calculates -x, checking for overflow errors where applicable. For example, standard two's complement signed integers (e.g. Int) cannot represent -typemin(Int), thus leading to an overflow.

      The overflow protection may impose a perceptible performance penalty.

      source
      Base.checked_add(x, y)

      Calculates x+y, checking for overflow errors where applicable.

      The overflow protection may impose a perceptible performance penalty.

      source
      Base.checked_sub(x, y)

      Calculates x-y, checking for overflow errors where applicable.

      The overflow protection may impose a perceptible performance penalty.

      source
      Base.checked_mul(x, y)

      Calculates x*y, checking for overflow errors where applicable.

      The overflow protection may impose a perceptible performance penalty.

      source
      Base.checked_div(x, y)

      Calculates div(x,y), checking for overflow errors where applicable.

      The overflow protection may impose a perceptible performance penalty.

      source
      Base.checked_rem(x, y)

      Calculates x%y, checking for overflow errors where applicable.

      The overflow protection may impose a perceptible performance penalty.

      source
      Base.checked_fld(x, y)

      Calculates fld(x,y), checking for overflow errors where applicable.

      The overflow protection may impose a perceptible performance penalty.

      source
      Base.checked_mod(x, y)

      Calculates mod(x,y), checking for overflow errors where applicable.

      The overflow protection may impose a perceptible performance penalty.

      source
      Base.checked_cld(x, y)

      Calculates cld(x,y), checking for overflow errors where applicable.

      The overflow protection may impose a perceptible performance penalty.

      source
      Base.add_with_overflow(x, y) -> (r, f)

      Calculates r = x+y, with the flag f indicating whether overflow has occurred.

      source
      Base.sub_with_overflow(x, y) -> (r, f)

      Calculates r = x-y, with the flag f indicating whether overflow has occurred.

      source
      Base.mul_with_overflow(x, y) -> (r, f)

      Calculates r = x*y, with the flag f indicating whether overflow has occurred.

      source
      Base.abs2Function.
      abs2(x)

      Squared absolute value of x.

      julia> abs2(-3)
      -9
      source
      Base.copysignFunction.
      copysign(x, y) -> z

      Return z which has the magnitude of x and the same sign as y.

      Examples

      julia> copysign(1, -2)
      --1
      -
      -julia> copysign(-1, 2)
      -1
      source
      Base.signFunction.
      sign(x)

      Return zero if x==0 and $x/|x|$ otherwise (i.e., ±1 for real x).

      source
      Base.signbitFunction.
      signbit(x)

      Returns true if the value of the sign of x is negative, otherwise false.

      Examples

      julia> signbit(-4)
      -true
      -
      -julia> signbit(5)
      -false
      -
      -julia> signbit(5.5)
      -false
      -
      -julia> signbit(-4.1)
      -true
      source
      Base.flipsignFunction.
      flipsign(x, y)

      Return x with its sign flipped if y is negative. For example abs(x) = flipsign(x,x).

      julia> flipsign(5, 3)
      -5
      -
      -julia> flipsign(5, -3)
      --5
      source
      Base.sqrtFunction.
      sqrt(x)

      Return $\sqrt{x}$. Throws DomainError for negative Real arguments. Use complex negative arguments instead. The prefix operator is equivalent to sqrt.

      source
      Base.isqrtFunction.
      isqrt(n::Integer)

      Integer square root: the largest integer m such that m*m <= n.

      julia> isqrt(5)
      -2
      source
      Base.Math.cbrtFunction.
      cbrt(x::Real)

      Return the cube root of x, i.e. $x^{1/3}$. Negative values are accepted (returning the negative real root when $x < 0$).

      The prefix operator is equivalent to cbrt.

      julia> cbrt(big(27))
      -3.000000000000000000000000000000000000000000000000000000000000000000000000000000
      source
      Base.realMethod.
      real(z)

      Return the real part of the complex number z.

      julia> real(1 + 3im)
      -1
      source
      Base.imagFunction.
      imag(z)

      Return the imaginary part of the complex number z.

      julia> imag(1 + 3im)
      -3
      source
      Base.reimFunction.
      reim(z)

      Return both the real and imaginary parts of the complex number z.

      julia> reim(1 + 3im)
      -(1, 3)
      source
      Base.conjFunction.
      conj(v::RowVector)

      Returns a ConjArray lazy view of the input, where each element is conjugated.

      Example

      julia> v = [1+im, 1-im].'
      -1×2 RowVector{Complex{Int64},Array{Complex{Int64},1}}:
      - 1+1im  1-1im
      -
      -julia> conj(v)
      -1×2 RowVector{Complex{Int64},ConjArray{Complex{Int64},1,Array{Complex{Int64},1}}}:
      - 1-1im  1+1im
      source
      conj(z)

      Compute the complex conjugate of a complex number z.

      julia> conj(1 + 3im)
      -1 - 3im
      source
      Base.angleFunction.
      angle(z)

      Compute the phase angle in radians of a complex number z.

      source
      Base.cisFunction.
      cis(z)

      Return $\exp(iz)$.

      source
      Base.binomialFunction.
      binomial(n, k)

      Number of ways to choose k out of n items.

      Example

      julia> binomial(5, 3)
      -10
      -
      -julia> factorial(5) ÷ (factorial(5-3) * factorial(3))
      -10
      source
      Base.factorialFunction.
      factorial(n)

      Factorial of n. If n is an Integer, the factorial is computed as an integer (promoted to at least 64 bits). Note that this may overflow if n is not small, but you can use factorial(big(n)) to compute the result exactly in arbitrary precision. If n is not an Integer, factorial(n) is equivalent to gamma(n+1).

      julia> factorial(6)
      -720
      -
      -julia> factorial(21)
      -ERROR: OverflowError()
      -[...]
      -
      -julia> factorial(21.0)
      -5.109094217170944e19
      -
      -julia> factorial(big(21))
      -51090942171709440000
      source
      Base.gcdFunction.
      gcd(x,y)

      Greatest common (positive) divisor (or zero if x and y are both zero).

      Examples

      julia> gcd(6,9)
      -3
      -
      -julia> gcd(6,-9)
      -3
      source
      Base.lcmFunction.
      lcm(x,y)

      Least common (non-negative) multiple.

      Examples

      julia> lcm(2,3)
      -6
      -
      -julia> lcm(-2,3)
      -6
      source
      Base.gcdxFunction.
      gcdx(x,y)

      Computes the greatest common (positive) divisor of x and y and their Bézout coefficients, i.e. the integer coefficients u and v that satisfy $ux+vy = d = gcd(x,y)$. $gcdx(x,y)$ returns $(d,u,v)$.

      Examples

      julia> gcdx(12, 42)
      -(6, -3, 1)
      -
      -julia> gcdx(240, 46)
      -(2, -9, 47)
      Note

      Bézout coefficients are not uniquely defined. gcdx returns the minimal Bézout coefficients that are computed by the extended Euclidean algorithm. (Ref: D. Knuth, TAoCP, 2/e, p. 325, Algorithm X.) For signed integers, these coefficients u and v are minimal in the sense that $|u| < |y/d|$ and $|v| < |x/d|$. Furthermore, the signs of u and v are chosen so that d is positive. For unsigned integers, the coefficients u and v might be near their typemax, and the identity then holds only via the unsigned integers' modulo arithmetic.

      source
      Base.ispow2Function.
      ispow2(n::Integer) -> Bool

      Test whether n is a power of two.

      Examples

      julia> ispow2(4)
      -true
      -
      -julia> ispow2(5)
      -false
      source
      Base.nextpow2Function.
      nextpow2(n::Integer)

      The smallest power of two not less than n. Returns 0 for n==0, and returns -nextpow2(-n) for negative arguments.

      Examples

      julia> nextpow2(16)
      -16
      -
      -julia> nextpow2(17)
      -32
      source
      Base.prevpow2Function.
      prevpow2(n::Integer)

      The largest power of two not greater than n. Returns 0 for n==0, and returns -prevpow2(-n) for negative arguments.

      Examples

      julia> prevpow2(5)
      -4
      -
      -julia> prevpow2(0)
      -0
      source
      Base.nextpowFunction.
      nextpow(a, x)

      The smallest a^n not less than x, where n is a non-negative integer. a must be greater than 1, and x must be greater than 0.

      Examples

      julia> nextpow(2, 7)
      -8
      -
      -julia> nextpow(2, 9)
      -16
      -
      -julia> nextpow(5, 20)
      -25
      -
      -julia> nextpow(4, 16)
      -16

      See also prevpow.

      source
      Base.prevpowFunction.
      prevpow(a, x)

      The largest a^n not greater than x, where n is a non-negative integer. a must be greater than 1, and x must not be less than 1.

      Examples

      julia> prevpow(2, 7)
      -4
      -
      -julia> prevpow(2, 9)
      -8
      -
      -julia> prevpow(5, 20)
      -5
      -
      -julia> prevpow(4, 16)
      -16

      See also nextpow.

      source
      Base.nextprodFunction.
      nextprod([k_1, k_2,...], n)

      Next integer greater than or equal to n that can be written as $\prod k_i^{p_i}$ for integers $p_1$, $p_2$, etc.

      Example

      julia> nextprod([2, 3], 105)
      -108
      -
      -julia> 2^2 * 3^3
      -108
      source
      Base.invmodFunction.
      invmod(x,m)

      Take the inverse of x modulo m: y such that $x y = 1 \pmod m$, with $div(x,y) = 0$. This is undefined for $m = 0$, or if $gcd(x,m) \neq 1$.

      Examples

      julia> invmod(2,5)
      -3
      -
      -julia> invmod(2,3)
      -2
      -
      -julia> invmod(5,6)
      -5
      source
      Base.powermodFunction.
      powermod(x::Integer, p::Integer, m)

      Compute $x^p \pmod m$.

      Examples

      julia> powermod(2, 6, 5)
      -4
      -
      -julia> mod(2^6, 5)
      -4
      -
      -julia> powermod(5, 2, 20)
      -5
      -
      -julia> powermod(5, 2, 19)
      -6
      -
      -julia> powermod(5, 3, 19)
      -11
      source
      Base.Math.gammaFunction.
      gamma(x)

      Compute the gamma function of x.

      source
      Base.Math.lgammaFunction.
      lgamma(x)

      Compute the logarithm of the absolute value of gamma for Real x, while for Complex x compute the principal branch cut of the logarithm of gamma(x) (defined for negative real(x) by analytic continuation from positive real(x)).

      source
      Base.Math.lfactFunction.
      lfact(x)

      Compute the logarithmic factorial of a nonnegative integer x. Equivalent to lgamma of x + 1, but lgamma extends this function to non-integer x.

      source
      Base.Math.betaFunction.
      beta(x, y)

      Euler integral of the first kind $\operatorname{B}(x,y) = \Gamma(x)\Gamma(y)/\Gamma(x+y)$.

      source
      Base.Math.lbetaFunction.
      lbeta(x, y)

      Natural logarithm of the absolute value of the beta function $\log(|\operatorname{B}(x,y)|)$.

      source
      Base.ndigitsFunction.
      ndigits(n::Integer, b::Integer=10)

      Compute the number of digits in integer n written in base b. The base b must not be in [-1, 0, 1].

      Examples

      julia> ndigits(12345)
      -5
      -
      -julia> ndigits(1022, 16)
      -3
      -
      -julia> base(16, 1022)
      -"3fe"
      source
      Base.widemulFunction.
      widemul(x, y)

      Multiply x and y, giving the result as a larger type.

      julia> widemul(Float32(3.), 4.)
      -1.200000000000000000000000000000000000000000000000000000000000000000000000000000e+01
      source
      @evalpoly(z, c...)

      Evaluate the polynomial $\sum_k c[k] z^{k-1}$ for the coefficients c[1], c[2], ...; that is, the coefficients are given in ascending order by power of z. This macro expands to efficient inline code that uses either Horner's method or, for complex z, a more efficient Goertzel-like algorithm.

      julia> @evalpoly(3, 1, 0, 1)
      -10
      -
      -julia> @evalpoly(2, 1, 0, 1)
      -5
      -
      -julia> @evalpoly(2, 1, 1, 1)
      -7
      source

      Statistics

      Base.meanFunction.
      mean(f::Function, v)

      Apply the function f to each element of v and take the mean.

      julia> mean(√, [1, 2, 3])
      -1.3820881233139908
      -
      -julia> mean([√1, √2, √3])
      -1.3820881233139908
      source
      mean(v[, region])

      Compute the mean of whole array v, or optionally along the dimensions in region.

      Note

      Julia does not ignore NaN values in the computation. For applications requiring the handling of missing data, the DataArrays.jl package is recommended.

      source
      Base.mean!Function.
      mean!(r, v)

      Compute the mean of v over the singleton dimensions of r, and write results to r.

      source
      Base.stdFunction.
      std(v[, region]; corrected::Bool=true, mean=nothing)

      Compute the sample standard deviation of a vector or array v, optionally along dimensions in region. The algorithm returns an estimator of the generative distribution's standard deviation under the assumption that each entry of v is an IID drawn from that generative distribution. This computation is equivalent to calculating sqrt(sum((v - mean(v)).^2) / (length(v) - 1)). A pre-computed mean may be provided. If corrected is true, then the sum is scaled with n-1, whereas the sum is scaled with n if corrected is false where n = length(x).

      Note

      Julia does not ignore NaN values in the computation. For applications requiring the handling of missing data, the DataArrays.jl package is recommended.

      source
      Base.stdmFunction.
      stdm(v, m::Number; corrected::Bool=true)

      Compute the sample standard deviation of a vector v with known mean m. If corrected is true, then the sum is scaled with n-1, whereas the sum is scaled with n if corrected is false where n = length(x).

      Note

      Julia does not ignore NaN values in the computation. For applications requiring the handling of missing data, the DataArrays.jl package is recommended.

      source
      Base.varFunction.
      var(v[, region]; corrected::Bool=true, mean=nothing)

      Compute the sample variance of a vector or array v, optionally along dimensions in region. The algorithm will return an estimator of the generative distribution's variance under the assumption that each entry of v is an IID drawn from that generative distribution. This computation is equivalent to calculating sum(abs2, v - mean(v)) / (length(v) - 1). If corrected is true, then the sum is scaled with n-1, whereas the sum is scaled with n if corrected is false where n = length(x). The mean mean over the region may be provided.

      Note

      Julia does not ignore NaN values in the computation. For applications requiring the handling of missing data, the DataArrays.jl package is recommended.

      source
      Base.varmFunction.
      varm(v, m[, region]; corrected::Bool=true)

      Compute the sample variance of a collection v with known mean(s) m, optionally over region. m may contain means for each dimension of v. If corrected is true, then the sum is scaled with n-1, whereas the sum is scaled with n if corrected is false where n = length(x).

      Note

      Julia does not ignore NaN values in the computation. For applications requiring the handling of missing data, the DataArrays.jl package is recommended.

      source
      Base.middleFunction.
      middle(x)

      Compute the middle of a scalar value, which is equivalent to x itself, but of the type of middle(x, x) for consistency.

      source
      middle(x, y)

      Compute the middle of two reals x and y, which is equivalent in both value and type to computing their mean ((x + y) / 2).

      source
      middle(range)

      Compute the middle of a range, which consists of computing the mean of its extrema. Since a range is sorted, the mean is performed with the first and last element.

      julia> middle(1:10)
      -5.5
      source
      middle(a)

      Compute the middle of an array a, which consists of finding its extrema and then computing their mean.

      julia> a = [1,2,3.6,10.9]
      -4-element Array{Float64,1}:
      -  1.0
      -  2.0
      -  3.6
      - 10.9
      -
      -julia> middle(a)
      -5.95
      source
      Base.medianFunction.
      median(v[, region])

      Compute the median of an entire array v, or, optionally, along the dimensions in region. For an even number of elements no exact median element exists, so the result is equivalent to calculating mean of two median elements.

      Note

      Julia does not ignore NaN values in the computation. For applications requiring the handling of missing data, the DataArrays.jl package is recommended.

      source
      Base.median!Function.
      median!(v)

      Like median, but may overwrite the input vector.

      source
      Base.quantileFunction.
      quantile(v, p; sorted=false)

      Compute the quantile(s) of a vector v at a specified probability or vector p. The keyword argument sorted indicates whether v can be assumed to be sorted.

      The p should be on the interval [0,1], and v should not have any NaN values.

      Quantiles are computed via linear interpolation between the points ((k-1)/(n-1), v[k]), for k = 1:n where n = length(v). This corresponds to Definition 7 of Hyndman and Fan (1996), and is the same as the R default.

      Note

      Julia does not ignore NaN values in the computation. For applications requiring the handling of missing data, the DataArrays.jl package is recommended. quantile will throw an ArgumentError in the presence of NaN values in the data array.

      • Hyndman, R.J and Fan, Y. (1996) "Sample Quantiles in Statistical Packages", The American Statistician, Vol. 50, No. 4, pp. 361-365

      source
      Base.quantile!Function.
      quantile!([q, ] v, p; sorted=false)

      Compute the quantile(s) of a vector v at the probabilities p, with optional output into array q (if not provided, a new output array is created). The keyword argument sorted indicates whether v can be assumed to be sorted; if false (the default), then the elements of v may be partially sorted.

      The elements of p should be on the interval [0,1], and v should not have any NaN values.

      Quantiles are computed via linear interpolation between the points ((k-1)/(n-1), v[k]), for k = 1:n where n = length(v). This corresponds to Definition 7 of Hyndman and Fan (1996), and is the same as the R default.

      Note

      Julia does not ignore NaN values in the computation. For applications requiring the handling of missing data, the DataArrays.jl package is recommended. quantile! will throw an ArgumentError in the presence of NaN values in the data array.

      • Hyndman, R.J and Fan, Y. (1996) "Sample Quantiles in Statistical Packages", The American Statistician, Vol. 50, No. 4, pp. 361-365

      source
      Base.covFunction.
      cov(x[, corrected=true])

      Compute the variance of the vector x. If corrected is true (the default) then the sum is scaled with n-1, whereas the sum is scaled with n if corrected is false where n = length(x).

      source
      cov(X[, vardim=1, corrected=true])

      Compute the covariance matrix of the matrix X along the dimension vardim. If corrected is true (the default) then the sum is scaled with n-1, whereas the sum is scaled with n if corrected is false where n = size(X, vardim).

      source
      cov(x, y[, corrected=true])

      Compute the covariance between the vectors x and y. If corrected is true (the default), computes $\frac{1}{n-1}\sum_{i=1}^n (x_i-\bar x) (y_i-\bar y)^*$ where $*$ denotes the complex conjugate and n = length(x) = length(y). If corrected is false, computes $rac{1}{n}sum_{i=1}^n (x_i-\bar x) (y_i-\bar y)^*$.

      source
      cov(X, Y[, vardim=1, corrected=true])

      Compute the covariance between the vectors or matrices X and Y along the dimension vardim. If corrected is true (the default) then the sum is scaled with n-1, whereas the sum is scaled with n if corrected is false where n = size(X, vardim) = size(Y, vardim).

      source
      Base.corFunction.
      cor(x)

      Return the number one.

      source
      cor(X[, vardim=1])

      Compute the Pearson correlation matrix of the matrix X along the dimension vardim.

      source
      cor(x, y)

      Compute the Pearson correlation between the vectors x and y.

      source
      cor(X, Y[, vardim=1])

      Compute the Pearson correlation between the vectors or matrices X and Y along the dimension vardim.

      source

      Signal Processing

      Fast Fourier transform (FFT) functions in Julia are implemented by calling functions from FFTW.

      Base.DFT.fftFunction.
      fft(A [, dims])

      Performs a multidimensional FFT of the array A. The optional dims argument specifies an iterable subset of dimensions (e.g. an integer, range, tuple, or array) to transform along. Most efficient if the size of A along the transformed dimensions is a product of small primes; see nextprod(). See also plan_fft() for even greater efficiency.

      A one-dimensional FFT computes the one-dimensional discrete Fourier transform (DFT) as defined by

      \[\operatorname{DFT}(A)[k] = - \sum_{n=1}^{\operatorname{length}(A)} - \exp\left(-i\frac{2\pi - (n-1)(k-1)}{\operatorname{length}(A)} \right) A[n].\]

      A multidimensional FFT simply performs this operation along each transformed dimension of A.

      Note
      • Julia starts FFTW up with 1 thread by default. Higher performance is usually possible by increasing number of threads. Use FFTW.set_num_threads(Sys.CPU_CORES) to use as many threads as cores on your system.

      • This performs a multidimensional FFT by default. FFT libraries in other languages such as Python and Octave perform a one-dimensional FFT along the first non-singleton dimension of the array. This is worth noting while performing comparisons. For more details, refer to the Noteworthy Differences from other Languages section of the manual.

      source
      Base.DFT.fft!Function.
      fft!(A [, dims])

      Same as fft, but operates in-place on A, which must be an array of complex floating-point numbers.

      source
      Base.DFT.ifftFunction.
      ifft(A [, dims])

      Multidimensional inverse FFT.

      A one-dimensional inverse FFT computes

      \[\operatorname{IDFT}(A)[k] = \frac{1}{\operatorname{length}(A)} -\sum_{n=1}^{\operatorname{length}(A)} \exp\left(+i\frac{2\pi (n-1)(k-1)} -{\operatorname{length}(A)} \right) A[n].\]

      A multidimensional inverse FFT simply performs this operation along each transformed dimension of A.

      source
      Base.DFT.ifft!Function.
      ifft!(A [, dims])

      Same as ifft, but operates in-place on A.

      source
      Base.DFT.bfftFunction.
      bfft(A [, dims])

      Similar to ifft, but computes an unnormalized inverse (backward) transform, which must be divided by the product of the sizes of the transformed dimensions in order to obtain the inverse. (This is slightly more efficient than ifft because it omits a scaling step, which in some applications can be combined with other computational steps elsewhere.)

      \[\operatorname{BDFT}(A)[k] = \operatorname{length}(A) \operatorname{IDFT}(A)[k]\]
      source
      Base.DFT.bfft!Function.
      bfft!(A [, dims])

      Same as bfft, but operates in-place on A.

      source
      Base.DFT.plan_fftFunction.
      plan_fft(A [, dims]; flags=FFTW.ESTIMATE;  timelimit=Inf)

      Pre-plan an optimized FFT along given dimensions (dims) of arrays matching the shape and type of A. (The first two arguments have the same meaning as for fft.) Returns an object P which represents the linear operator computed by the FFT, and which contains all of the information needed to compute fft(A, dims) quickly.

      To apply P to an array A, use P * A; in general, the syntax for applying plans is much like that of matrices. (A plan can only be applied to arrays of the same size as the A for which the plan was created.) You can also apply a plan with a preallocated output array  by calling A_mul_B!(Â, plan, A). (For A_mul_B!, however, the input array A must be a complex floating-point array like the output Â.) You can compute the inverse-transform plan by inv(P) and apply the inverse plan with P \  (the inverse plan is cached and reused for subsequent calls to inv or \), and apply the inverse plan to a pre-allocated output array A with A_ldiv_B!(A, P, Â).

      The flags argument is a bitwise-or of FFTW planner flags, defaulting to FFTW.ESTIMATE. e.g. passing FFTW.MEASURE or FFTW.PATIENT will instead spend several seconds (or more) benchmarking different possible FFT algorithms and picking the fastest one; see the FFTW manual for more information on planner flags. The optional timelimit argument specifies a rough upper bound on the allowed planning time, in seconds. Passing FFTW.MEASURE or FFTW.PATIENT may cause the input array A to be overwritten with zeros during plan creation.

      plan_fft! is the same as plan_fft but creates a plan that operates in-place on its argument (which must be an array of complex floating-point numbers). plan_ifft and so on are similar but produce plans that perform the equivalent of the inverse transforms ifft and so on.

      source
      Base.DFT.plan_ifftFunction.
      plan_ifft(A [, dims]; flags=FFTW.ESTIMATE;  timelimit=Inf)

      Same as plan_fft, but produces a plan that performs inverse transforms ifft.

      source
      Base.DFT.plan_bfftFunction.
      plan_bfft(A [, dims]; flags=FFTW.ESTIMATE;  timelimit=Inf)

      Same as plan_fft, but produces a plan that performs an unnormalized backwards transform bfft.

      source
      Base.DFT.plan_fft!Function.
      plan_fft!(A [, dims]; flags=FFTW.ESTIMATE;  timelimit=Inf)

      Same as plan_fft, but operates in-place on A.

      source
      Base.DFT.plan_ifft!Function.
      plan_ifft!(A [, dims]; flags=FFTW.ESTIMATE;  timelimit=Inf)

      Same as plan_ifft, but operates in-place on A.

      source
      Base.DFT.plan_bfft!Function.
      plan_bfft!(A [, dims]; flags=FFTW.ESTIMATE;  timelimit=Inf)

      Same as plan_bfft, but operates in-place on A.

      source
      Base.DFT.rfftFunction.
      rfft(A [, dims])

      Multidimensional FFT of a real array A, exploiting the fact that the transform has conjugate symmetry in order to save roughly half the computational time and storage costs compared with fft. If A has size (n_1, ..., n_d), the result has size (div(n_1,2)+1, ..., n_d).

      The optional dims argument specifies an iterable subset of one or more dimensions of A to transform, similar to fft. Instead of (roughly) halving the first dimension of A in the result, the dims[1] dimension is (roughly) halved in the same way.

      source
      Base.DFT.irfftFunction.
      irfft(A, d [, dims])

      Inverse of rfft: for a complex array A, gives the corresponding real array whose FFT yields A in the first half. As for rfft, dims is an optional subset of dimensions to transform, defaulting to 1:ndims(A).

      d is the length of the transformed real array along the dims[1] dimension, which must satisfy div(d,2)+1 == size(A,dims[1]). (This parameter cannot be inferred from size(A) since both 2*size(A,dims[1])-2 as well as 2*size(A,dims[1])-1 are valid sizes for the transformed real array.)

      source
      Base.DFT.brfftFunction.
      brfft(A, d [, dims])

      Similar to irfft but computes an unnormalized inverse transform (similar to bfft), which must be divided by the product of the sizes of the transformed dimensions (of the real output array) in order to obtain the inverse transform.

      source
      Base.DFT.plan_rfftFunction.
      plan_rfft(A [, dims]; flags=FFTW.ESTIMATE;  timelimit=Inf)

      Pre-plan an optimized real-input FFT, similar to plan_fft except for rfft instead of fft. The first two arguments, and the size of the transformed result, are the same as for rfft.

      source
      Base.DFT.plan_brfftFunction.
      plan_brfft(A, d [, dims]; flags=FFTW.ESTIMATE;  timelimit=Inf)

      Pre-plan an optimized real-input unnormalized transform, similar to plan_rfft except for brfft instead of rfft. The first two arguments and the size of the transformed result, are the same as for brfft.

      source
      Base.DFT.plan_irfftFunction.
      plan_irfft(A, d [, dims]; flags=FFTW.ESTIMATE;  timelimit=Inf)

      Pre-plan an optimized inverse real-input FFT, similar to plan_rfft except for irfft and brfft, respectively. The first three arguments have the same meaning as for irfft.

      source
      Base.DFT.FFTW.dctFunction.
      dct(A [, dims])

      Performs a multidimensional type-II discrete cosine transform (DCT) of the array A, using the unitary normalization of the DCT. The optional dims argument specifies an iterable subset of dimensions (e.g. an integer, range, tuple, or array) to transform along. Most efficient if the size of A along the transformed dimensions is a product of small primes; see nextprod. See also plan_dct for even greater efficiency.

      source
      Base.DFT.FFTW.dct!Function.
      dct!(A [, dims])

      Same as dct!, except that it operates in-place on A, which must be an array of real or complex floating-point values.

      source
      Base.DFT.FFTW.idctFunction.
      idct(A [, dims])

      Computes the multidimensional inverse discrete cosine transform (DCT) of the array A (technically, a type-III DCT with the unitary normalization). The optional dims argument specifies an iterable subset of dimensions (e.g. an integer, range, tuple, or array) to transform along. Most efficient if the size of A along the transformed dimensions is a product of small primes; see nextprod. See also plan_idct for even greater efficiency.

      source
      Base.DFT.FFTW.idct!Function.
      idct!(A [, dims])

      Same as idct!, but operates in-place on A.

      source
      plan_dct(A [, dims [, flags [, timelimit]]])

      Pre-plan an optimized discrete cosine transform (DCT), similar to plan_fft except producing a function that computes dct. The first two arguments have the same meaning as for dct.

      source
      plan_dct!(A [, dims [, flags [, timelimit]]])

      Same as plan_dct, but operates in-place on A.

      source
      plan_idct(A [, dims [, flags [, timelimit]]])

      Pre-plan an optimized inverse discrete cosine transform (DCT), similar to plan_fft except producing a function that computes idct. The first two arguments have the same meaning as for idct.

      source
      plan_idct!(A [, dims [, flags [, timelimit]]])

      Same as plan_idct, but operates in-place on A.

      source
      Base.DFT.fftshiftMethod.
      fftshift(x)

      Swap the first and second halves of each dimension of x.

      source
      Base.DFT.fftshiftMethod.
      fftshift(x,dim)

      Swap the first and second halves of the given dimension or iterable of dimensions of array x.

      source
      Base.DFT.ifftshiftFunction.
      ifftshift(x, [dim])

      Undoes the effect of fftshift.

      source
      Base.DSP.filtFunction.
      filt(b, a, x, [si])

      Apply filter described by vectors a and b to vector x, with an optional initial filter state vector si (defaults to zeros).

      source
      Base.DSP.filt!Function.
      filt!(out, b, a, x, [si])

      Same as filt but writes the result into the out argument, which may alias the input x to modify it in-place.

      source
      Base.DSP.deconvFunction.
      deconv(b,a) -> c

      Construct vector c such that b = conv(a,c) + r. Equivalent to polynomial division.

      source
      Base.DSP.convFunction.
      conv(u,v)

      Convolution of two vectors. Uses FFT algorithm.

      source
      Base.DSP.conv2Function.
      conv2(u,v,A)

      2-D convolution of the matrix A with the 2-D separable kernel generated by the vectors u and v. Uses 2-D FFT algorithm.

      source
      conv2(B,A)

      2-D convolution of the matrix B with the matrix A. Uses 2-D FFT algorithm.

      source
      Base.DSP.xcorrFunction.
      xcorr(u,v)

      Compute the cross-correlation of two vectors.

      source

      The following functions are defined within the Base.FFTW module.

      Base.DFT.FFTW.r2rFunction.
      r2r(A, kind [, dims])

      Performs a multidimensional real-input/real-output (r2r) transform of type kind of the array A, as defined in the FFTW manual. kind specifies either a discrete cosine transform of various types (FFTW.REDFT00, FFTW.REDFT01, FFTW.REDFT10, or FFTW.REDFT11), a discrete sine transform of various types (FFTW.RODFT00, FFTW.RODFT01, FFTW.RODFT10, or FFTW.RODFT11), a real-input DFT with halfcomplex-format output (FFTW.R2HC and its inverse FFTW.HC2R), or a discrete Hartley transform (FFTW.DHT). The kind argument may be an array or tuple in order to specify different transform types along the different dimensions of A; kind[end] is used for any unspecified dimensions. See the FFTW manual for precise definitions of these transform types, at http://www.fftw.org/doc.

      The optional dims argument specifies an iterable subset of dimensions (e.g. an integer, range, tuple, or array) to transform along. kind[i] is then the transform type for dims[i], with kind[end] being used for i > length(kind).

      See also plan_r2r to pre-plan optimized r2r transforms.

      source
      Base.DFT.FFTW.r2r!Function.
      r2r!(A, kind [, dims])

      Same as r2r, but operates in-place on A, which must be an array of real or complex floating-point numbers.

      source
      plan_r2r(A, kind [, dims [, flags [, timelimit]]])

      Pre-plan an optimized r2r transform, similar to plan_fft except that the transforms (and the first three arguments) correspond to r2r and r2r!, respectively.

      source
      plan_r2r!(A, kind [, dims [, flags [, timelimit]]])

      Similar to plan_fft, but corresponds to r2r!.

      source
      diff --git a/julia-0.6.3/share/doc/julia/html/en/stdlib/numbers.html b/julia-0.6.3/share/doc/julia/html/en/stdlib/numbers.html deleted file mode 100644 index a5a8768..0000000 --- a/julia-0.6.3/share/doc/julia/html/en/stdlib/numbers.html +++ /dev/null @@ -1,252 +0,0 @@ - -Numbers · The Julia Language

      Numbers

      Numbers

      Standard Numeric Types

      Abstract number types

      Core.NumberType.
      Number

      Abstract supertype for all number types.

      source
      Core.RealType.
      Real <: Number

      Abstract supertype for all real numbers.

      source
      AbstractFloat <: Real

      Abstract supertype for all floating point numbers.

      source
      Core.IntegerType.
      Integer <: Real

      Abstract supertype for all integers.

      source
      Core.SignedType.
      Signed <: Integer

      Abstract supertype for all signed integers.

      source
      Core.UnsignedType.
      Unsigned <: Integer

      Abstract supertype for all unsigned integers.

      source

      Concrete number types

      Core.Float16Type.
      Float16 <: AbstractFloat

      16-bit floating point number type.

      source
      Core.Float32Type.
      Float32 <: AbstractFloat

      32-bit floating point number type.

      source
      Core.Float64Type.
      Float64 <: AbstractFloat

      64-bit floating point number type.

      source
      BigFloat <: AbstractFloat

      Arbitrary precision floating point number type.

      source
      Core.BoolType.
      Bool <: Integer

      Boolean type.

      source
      Core.Int8Type.
      Int8 <: Signed

      8-bit signed integer type.

      source
      Core.UInt8Type.
      UInt8 <: Unsigned

      8-bit unsigned integer type.

      source
      Core.Int16Type.
      Int16 <: Signed

      16-bit signed integer type.

      source
      Core.UInt16Type.
      UInt16 <: Unsigned

      16-bit unsigned integer type.

      source
      Core.Int32Type.
      Int32 <: Signed

      32-bit signed integer type.

      source
      Core.UInt32Type.
      UInt32 <: Unsigned

      32-bit unsigned integer type.

      source
      Core.Int64Type.
      Int64 <: Signed

      64-bit signed integer type.

      source
      Core.UInt64Type.
      UInt64 <: Unsigned

      64-bit unsigned integer type.

      source
      Core.Int128Type.
      Int128 <: Signed

      128-bit signed integer type.

      source
      Core.UInt128Type.
      UInt128 <: Unsigned

      128-bit unsigned integer type.

      source
      Base.GMP.BigIntType.
      BigInt <: Integer

      Arbitrary precision integer type.

      source
      Base.ComplexType.
      Complex{T<:Real} <: Number

      Complex number type with real and imaginary part of type T.

      Complex32, Complex64 and Complex128 are aliases for Complex{Float16}, Complex{Float32} and Complex{Float64} respectively.

      source
      Base.RationalType.
      Rational{T<:Integer} <: Real

      Rational number type, with numerator and denominator of type T.

      source
      Base.IrrationalType.
      Irrational <: Real

      Irrational number type.

      source

      Data Formats

      Base.binFunction.
      bin(n, pad::Int=1)

      Convert an integer to a binary string, optionally specifying a number of digits to pad to.

      julia> bin(10,2)
      -"1010"
      -
      -julia> bin(10,8)
      -"00001010"
      source
      Base.hexFunction.
      hex(n, pad::Int=1)

      Convert an integer to a hexadecimal string, optionally specifying a number of digits to pad to.

      julia> hex(20)
      -"14"
      -
      -julia> hex(20, 3)
      -"014"
      source
      Base.decFunction.
      dec(n, pad::Int=1)

      Convert an integer to a decimal string, optionally specifying a number of digits to pad to.

      Examples

      julia> dec(20)
      -"20"
      -
      -julia> dec(20, 3)
      -"020"
      source
      Base.octFunction.
      oct(n, pad::Int=1)

      Convert an integer to an octal string, optionally specifying a number of digits to pad to.

      julia> oct(20)
      -"24"
      -
      -julia> oct(20, 3)
      -"024"
      source
      Base.baseFunction.
      base(base::Integer, n::Integer, pad::Integer=1)

      Convert an integer n to a string in the given base, optionally specifying a number of digits to pad to.

      julia> base(13,5,4)
      -"0005"
      -
      -julia> base(5,13,4)
      -"0023"
      source
      Base.digitsFunction.
      digits([T<:Integer], n::Integer, base::T=10, pad::Integer=1)

      Returns an array with element type T (default Int) of the digits of n in the given base, optionally padded with zeros to a specified size. More significant digits are at higher indexes, such that n == sum([digits[k]*base^(k-1) for k=1:length(digits)]).

      Examples

      julia> digits(10, 10)
      -2-element Array{Int64,1}:
      - 0
      - 1
      -
      -julia> digits(10, 2)
      -4-element Array{Int64,1}:
      - 0
      - 1
      - 0
      - 1
      -
      -julia> digits(10, 2, 6)
      -6-element Array{Int64,1}:
      - 0
      - 1
      - 0
      - 1
      - 0
      - 0
      source
      Base.digits!Function.
      digits!(array, n::Integer, base::Integer=10)

      Fills an array of the digits of n in the given base. More significant digits are at higher indexes. If the array length is insufficient, the least significant digits are filled up to the array length. If the array length is excessive, the excess portion is filled with zeros.

      Examples

      julia> digits!([2,2,2,2], 10, 2)
      -4-element Array{Int64,1}:
      - 0
      - 1
      - 0
      - 1
      -
      -julia> digits!([2,2,2,2,2,2], 10, 2)
      -6-element Array{Int64,1}:
      - 0
      - 1
      - 0
      - 1
      - 0
      - 0
      source
      Base.bitsFunction.
      bits(n)

      A string giving the literal bit representation of a number.

      Example

      julia> bits(4)
      -"0000000000000000000000000000000000000000000000000000000000000100"
      -
      -julia> bits(2.2)
      -"0100000000000001100110011001100110011001100110011001100110011010"
      source
      Base.parseMethod.
      parse(type, str, [base])

      Parse a string as a number. If the type is an integer type, then a base can be specified (the default is 10). If the type is a floating point type, the string is parsed as a decimal floating point number. If the string does not contain a valid number, an error is raised.

      julia> parse(Int, "1234")
      -1234
      -
      -julia> parse(Int, "1234", 5)
      -194
      -
      -julia> parse(Int, "afc", 16)
      -2812
      -
      -julia> parse(Float64, "1.2e-3")
      -0.0012
      source
      Base.tryparseFunction.
      tryparse(type, str, [base])

      Like parse, but returns a Nullable of the requested type. The result will be null if the string does not contain a valid number.

      source
      Base.bigFunction.
      big(x)

      Convert a number to a maximum precision representation (typically BigInt or BigFloat). See BigFloat for information about some pitfalls with floating-point numbers.

      source
      Base.signedFunction.
      signed(x)

      Convert a number to a signed integer. If the argument is unsigned, it is reinterpreted as signed without checking for overflow.

      source
      Base.unsignedFunction.
      unsigned(x) -> Unsigned

      Convert a number to an unsigned integer. If the argument is signed, it is reinterpreted as unsigned without checking for negative values.

      Examples

      julia> unsigned(-2)
      -0xfffffffffffffffe
      -
      -julia> unsigned(2)
      -0x0000000000000002
      -
      -julia> signed(unsigned(-2))
      --2
      source
      Base.floatMethod.
      float(x)

      Convert a number or array to a floating point data type. When passed a string, this function is equivalent to parse(Float64, x).

      source
      Base.Math.significandFunction.
      significand(x)

      Extract the significand(s) (a.k.a. mantissa), in binary representation, of a floating-point number. If x is a non-zero finite number, then the result will be a number of the same type on the interval $[1,2)$. Otherwise x is returned.

      Examples

      julia> significand(15.2)/15.2
      -0.125
      -
      -julia> significand(15.2)*8
      -15.2
      source
      Base.Math.exponentFunction.
      exponent(x) -> Int

      Get the exponent of a normalized floating-point number.

      source
      Base.complexMethod.
      complex(r, [i])

      Convert real numbers or arrays to complex. i defaults to zero.

      source
      Base.bswapFunction.
      bswap(n)

      Byte-swap an integer. Flip the bits of its binary representation.

      Examples

      julia> a = bswap(4)
      -288230376151711744
      -
      -julia> bswap(a)
      -4
      -
      -julia> bin(1)
      -"1"
      -
      -julia> bin(bswap(1))
      -"100000000000000000000000000000000000000000000000000000000"
      source
      Base.num2hexFunction.
      num2hex(f)

      Get a hexadecimal string of the binary representation of a floating point number.

      Example

      julia> num2hex(2.2)
      -"400199999999999a"
      source
      Base.hex2numFunction.
      hex2num(str)

      Convert a hexadecimal string to the floating point number it represents.

      source
      Base.hex2bytesFunction.
      hex2bytes(s::AbstractString)

      Convert an arbitrarily long hexadecimal string to its binary representation. Returns an Array{UInt8,1}, i.e. an array of bytes.

      julia> a = hex(12345)
      -"3039"
      -
      -julia> hex2bytes(a)
      -2-element Array{UInt8,1}:
      - 0x30
      - 0x39
      source
      Base.bytes2hexFunction.
      bytes2hex(bin_arr::Array{UInt8, 1}) -> String

      Convert an array of bytes to its hexadecimal representation. All characters are in lower-case.

      julia> a = hex(12345)
      -"3039"
      -
      -julia> b = hex2bytes(a)
      -2-element Array{UInt8,1}:
      - 0x30
      - 0x39
      -
      -julia> bytes2hex(b)
      -"3039"
      source

      General Number Functions and Constants

      Base.oneFunction.
      one(x)
      -one(T::type)

      Return a multiplicative identity for x: a value such that one(x)*x == x*one(x) == x. Alternatively one(T) can take a type T, in which case one returns a multiplicative identity for any x of type T.

      If possible, one(x) returns a value of the same type as x, and one(T) returns a value of type T. However, this may not be the case for types representing dimensionful quantities (e.g. time in days), since the multiplicative identity must be dimensionless. In that case, one(x) should return an identity value of the same precision (and shape, for matrices) as x.

      If you want a quantity that is of the same type as x, or of type T, even if x is dimensionful, use oneunit instead.

      julia> one(3.7)
      -1.0
      -
      -julia> one(Int)
      -1
      -
      -julia> one(Dates.Day(1))
      -1
      source
      Base.oneunitFunction.
      oneunit(x::T)
      -oneunit(T::Type)

      Returns T(one(x)), where T is either the type of the argument or (if a type is passed) the argument. This differs from one for dimensionful quantities: one is dimensionless (a multiplicative identity) while oneunit is dimensionful (of the same type as x, or of type T).

      julia> oneunit(3.7)
      -1.0
      -
      -julia> oneunit(Dates.Day)
      -1 day
      source
      Base.zeroFunction.
      zero(x)

      Get the additive identity element for the type of x (x can also specify the type itself).

      julia> zero(1)
      -0
      -
      -julia> zero(big"2.0")
      -0.000000000000000000000000000000000000000000000000000000000000000000000000000000
      -
      -julia> zero(rand(2,2))
      -2×2 Array{Float64,2}:
      - 0.0  0.0
      - 0.0  0.0
      source
      Base.piConstant.
      pi
      -π

      The constant pi.

      julia> pi
      -π = 3.1415926535897...
      source
      Base.imConstant.
      im

      The imaginary unit.

      source
      Base.euConstant.
      e
      -eu

      The constant e.

      julia> e
      -e = 2.7182818284590...
      source
      Base.catalanConstant.
      catalan

      Catalan's constant.

      julia> catalan
      -catalan = 0.9159655941772...
      source
      Base.eulergammaConstant.
      γ
      -eulergamma

      Euler's constant.

      julia> eulergamma
      -γ = 0.5772156649015...
      source
      Base.goldenConstant.
      φ
      -golden

      The golden ratio.

      julia> golden
      -φ = 1.6180339887498...
      source
      Base.InfConstant.
      Inf

      Positive infinity of type Float64.

      source
      Base.Inf32Constant.
      Inf32

      Positive infinity of type Float32.

      source
      Base.Inf16Constant.
      Inf16

      Positive infinity of type Float16.

      source
      Base.NaNConstant.
      NaN

      A not-a-number value of type Float64.

      source
      Base.NaN32Constant.
      NaN32

      A not-a-number value of type Float32.

      source
      Base.NaN16Constant.
      NaN16

      A not-a-number value of type Float16.

      source
      Base.issubnormalFunction.
      issubnormal(f) -> Bool

      Test whether a floating point number is subnormal.

      source
      Base.isfiniteFunction.
      isfinite(f) -> Bool

      Test whether a number is finite.

      julia> isfinite(5)
      -true
      -
      -julia> isfinite(NaN32)
      -false
      source
      Base.isinfFunction.
      isinf(f) -> Bool

      Test whether a number is infinite.

      source
      Base.isnanFunction.
      isnan(f) -> Bool

      Test whether a floating point number is not a number (NaN).

      source
      Base.iszeroFunction.
      iszero(x)

      Return true if x == zero(x); if x is an array, this checks whether all of the elements of x are zero.

      source
      Base.nextfloatFunction.
      nextfloat(x::AbstractFloat, n::Integer)

      The result of n iterative applications of nextfloat to x if n >= 0, or -n applications of prevfloat if n < 0.

      source
      nextfloat(x::AbstractFloat)

      Returns the smallest floating point number y of the same type as x such x < y. If no such y exists (e.g. if x is Inf or NaN), then returns x.

      source
      Base.prevfloatFunction.
      prevfloat(x::AbstractFloat)

      Returns the largest floating point number y of the same type as x such y < x. If no such y exists (e.g. if x is -Inf or NaN), then returns x.

      source
      Base.isintegerFunction.
      isinteger(x) -> Bool

      Test whether x is numerically equal to some integer.

      julia> isinteger(4.0)
      -true
      source
      Base.isrealFunction.
      isreal(x) -> Bool

      Test whether x or all its elements are numerically equal to some real number.

      julia> isreal(5.)
      -true
      -
      -julia> isreal([4.; complex(0,1)])
      -false
      source
      Core.Float32Method.
      Float32(x [, mode::RoundingMode])

      Create a Float32 from x. If x is not exactly representable then mode determines how x is rounded.

      Examples

      julia> Float32(1/3, RoundDown)
      -0.3333333f0
      -
      -julia> Float32(1/3, RoundUp)
      -0.33333334f0

      See RoundingMode for available rounding modes.

      source
      Core.Float64Method.
      Float64(x [, mode::RoundingMode])

      Create a Float64 from x. If x is not exactly representable then mode determines how x is rounded.

      Examples

      julia> Float64(pi, RoundDown)
      -3.141592653589793
      -
      -julia> Float64(pi, RoundUp)
      -3.1415926535897936

      See RoundingMode for available rounding modes.

      source
      Base.GMP.BigIntMethod.
      BigInt(x)

      Create an arbitrary precision integer. x may be an Int (or anything that can be converted to an Int). The usual mathematical operators are defined for this type, and results are promoted to a BigInt.

      Instances can be constructed from strings via parse, or using the big string literal.

      julia> parse(BigInt, "42")
      -42
      -
      -julia> big"313"
      -313
      source
      Base.MPFR.BigFloatMethod.
      BigFloat(x)

      Create an arbitrary precision floating point number. x may be an Integer, a Float64 or a BigInt. The usual mathematical operators are defined for this type, and results are promoted to a BigFloat.

      Note that because decimal literals are converted to floating point numbers when parsed, BigFloat(2.1) may not yield what you expect. You may instead prefer to initialize constants from strings via parse, or using the big string literal.

      julia> BigFloat(2.1)
      -2.100000000000000088817841970012523233890533447265625000000000000000000000000000
      -
      -julia> big"2.1"
      -2.099999999999999999999999999999999999999999999999999999999999999999999999999986
      source
      rounding(T)

      Get the current floating point rounding mode for type T, controlling the rounding of basic arithmetic functions (+, -, *, / and sqrt) and type conversion.

      See RoundingMode for available modes.

      source
      setrounding(T, mode)

      Set the rounding mode of floating point type T, controlling the rounding of basic arithmetic functions (+, -, *, / and sqrt) and type conversion. Other numerical functions may give incorrect or invalid values when using rounding modes other than the default RoundNearest.

      Note that this may affect other types, for instance changing the rounding mode of Float64 will change the rounding mode of Float32. See RoundingMode for available modes.

      Warning

      This feature is still experimental, and may give unexpected or incorrect values.

      source
      setrounding(f::Function, T, mode)

      Change the rounding mode of floating point type T for the duration of f. It is logically equivalent to:

      old = rounding(T)
      -setrounding(T, mode)
      -f()
      -setrounding(T, old)

      See RoundingMode for available rounding modes.

      Warning

      This feature is still experimental, and may give unexpected or incorrect values. A known problem is the interaction with compiler optimisations, e.g.

      julia> setrounding(Float64,RoundDown) do
      -           1.1 + 0.1
      -       end
      -1.2000000000000002

      Here the compiler is constant folding, that is evaluating a known constant expression at compile time, however the rounding mode is only changed at runtime, so this is not reflected in the function result. This can be avoided by moving constants outside the expression, e.g.

      julia> x = 1.1; y = 0.1;
      -
      -julia> setrounding(Float64,RoundDown) do
      -           x + y
      -       end
      -1.2
      source
      get_zero_subnormals() -> Bool

      Returns false if operations on subnormal floating-point values ("denormals") obey rules for IEEE arithmetic, and true if they might be converted to zeros.

      source
      set_zero_subnormals(yes::Bool) -> Bool

      If yes is false, subsequent floating-point operations follow rules for IEEE arithmetic on subnormal values ("denormals"). Otherwise, floating-point operations are permitted (but not required) to convert subnormal inputs or outputs to zero. Returns true unless yes==true but the hardware does not support zeroing of subnormal numbers.

      set_zero_subnormals(true) can speed up some computations on some hardware. However, it can break identities such as (x-y==0) == (x==y).

      source

      Integers

      Base.count_onesFunction.
      count_ones(x::Integer) -> Integer

      Number of ones in the binary representation of x.

      julia> count_ones(7)
      -3
      source
      Base.count_zerosFunction.
      count_zeros(x::Integer) -> Integer

      Number of zeros in the binary representation of x.

      julia> count_zeros(Int32(2 ^ 16 - 1))
      -16
      source
      Base.leading_zerosFunction.
      leading_zeros(x::Integer) -> Integer

      Number of zeros leading the binary representation of x.

      julia> leading_zeros(Int32(1))
      -31
      source
      Base.leading_onesFunction.
      leading_ones(x::Integer) -> Integer

      Number of ones leading the binary representation of x.

      julia> leading_ones(UInt32(2 ^ 32 - 2))
      -31
      source
      Base.trailing_zerosFunction.
      trailing_zeros(x::Integer) -> Integer

      Number of zeros trailing the binary representation of x.

      julia> trailing_zeros(2)
      -1
      source
      Base.trailing_onesFunction.
      trailing_ones(x::Integer) -> Integer

      Number of ones trailing the binary representation of x.

      julia> trailing_ones(3)
      -2
      source
      Base.isoddFunction.
      isodd(x::Integer) -> Bool

      Returns true if x is odd (that is, not divisible by 2), and false otherwise.

      julia> isodd(9)
      -true
      -
      -julia> isodd(10)
      -false
      source
      Base.isevenFunction.
      iseven(x::Integer) -> Bool

      Returns true is x is even (that is, divisible by 2), and false otherwise.

      julia> iseven(9)
      -false
      -
      -julia> iseven(10)
      -true
      source

      BigFloats

      The BigFloat type implements arbitrary-precision floating-point arithmetic using the GNU MPFR library.

      Base.precisionFunction.
      precision(num::AbstractFloat)

      Get the precision of a floating point number, as defined by the effective number of bits in the mantissa.

      source
      Base.precisionMethod.
      precision(BigFloat)

      Get the precision (in bits) currently used for BigFloat arithmetic.

      source
      setprecision([T=BigFloat,] precision::Int)

      Set the precision (in bits) to be used for T arithmetic.

      source
      setprecision(f::Function, [T=BigFloat,] precision::Integer)

      Change the T arithmetic precision (in bits) for the duration of f. It is logically equivalent to:

      old = precision(BigFloat)
      -setprecision(BigFloat, precision)
      -f()
      -setprecision(BigFloat, old)

      Often used as setprecision(T, precision) do ... end

      source
      Base.MPFR.BigFloatMethod.
      BigFloat(x, prec::Int)

      Create a representation of x as a BigFloat with precision prec.

      source
      Base.MPFR.BigFloatMethod.
      BigFloat(x, rounding::RoundingMode)

      Create a representation of x as a BigFloat with the current global precision and rounding mode rounding.

      source
      Base.MPFR.BigFloatMethod.
      BigFloat(x, prec::Int, rounding::RoundingMode)

      Create a representation of x as a BigFloat with precision prec and rounding mode rounding.

      source
      Base.MPFR.BigFloatMethod.
      BigFloat(x::String)

      Create a representation of the string x as a BigFloat.

      source

      Random Numbers

      Random number generation in Julia uses the Mersenne Twister library via MersenneTwister objects. Julia has a global RNG, which is used by default. Other RNG types can be plugged in by inheriting the AbstractRNG type; they can then be used to have multiple streams of random numbers. Besides MersenneTwister, Julia also provides the RandomDevice RNG type, which is a wrapper over the OS provided entropy.

      Most functions related to random generation accept an optional AbstractRNG as the first argument, rng , which defaults to the global one if not provided. Morever, some of them accept optionally dimension specifications dims... (which can be given as a tuple) to generate arrays of random values.

      A MersenneTwister or RandomDevice RNG can generate random numbers of the following types: Float16, Float32, Float64, Bool, Int8, UInt8, Int16, UInt16, Int32, UInt32, Int64, UInt64, Int128, UInt128, BigInt (or complex numbers of those types). Random floating point numbers are generated uniformly in $[0, 1)$. As BigInt represents unbounded integers, the interval must be specified (e.g. rand(big(1:6))).

      Base.Random.srandFunction.
      srand([rng=GLOBAL_RNG], [seed]) -> rng
      -srand([rng=GLOBAL_RNG], filename, n=4) -> rng

      Reseed the random number generator. If a seed is provided, the RNG will give a reproducible sequence of numbers, otherwise Julia will get entropy from the system. For MersenneTwister, the seed may be a non-negative integer, a vector of UInt32 integers or a filename, in which case the seed is read from a file (4n bytes are read from the file, where n is an optional argument). RandomDevice does not support seeding.

      source
      MersenneTwister(seed)

      Create a MersenneTwister RNG object. Different RNG objects can have their own seeds, which may be useful for generating different streams of random numbers.

      Example

      julia> rng = MersenneTwister(1234);
      source
      RandomDevice()

      Create a RandomDevice RNG object. Two such objects will always generate different streams of random numbers.

      source
      Base.Random.randFunction.
      rand([rng=GLOBAL_RNG], [S], [dims...])

      Pick a random element or array of random elements from the set of values specified by S; S can be

      • an indexable collection (for example 1:n or ['x','y','z']), or

      • a type: the set of values to pick from is then equivalent to typemin(S):typemax(S) for integers (this is not applicable to BigInt), and to $[0, 1)$ for floating point numbers;

      S defaults to Float64.

      source
      Base.Random.rand!Function.
      rand!([rng=GLOBAL_RNG], A, [coll])

      Populate the array A with random values. If the indexable collection coll is specified, the values are picked randomly from coll. This is equivalent to copy!(A, rand(rng, coll, size(A))) or copy!(A, rand(rng, eltype(A), size(A))) but without allocating a new array.

      Example

      julia> rng = MersenneTwister(1234);
      -
      -julia> rand!(rng, zeros(5))
      -5-element Array{Float64,1}:
      - 0.590845
      - 0.766797
      - 0.566237
      - 0.460085
      - 0.794026
      source
      Base.Random.bitrandFunction.
      bitrand([rng=GLOBAL_RNG], [dims...])

      Generate a BitArray of random boolean values.

      Example

      julia> rng = MersenneTwister(1234);
      -
      -julia> bitrand(rng, 10)
      -10-element BitArray{1}:
      -  true
      -  true
      -  true
      - false
      -  true
      - false
      - false
      -  true
      - false
      -  true
      source
      Base.Random.randnFunction.
      randn([rng=GLOBAL_RNG], [T=Float64], [dims...])

      Generate a normally-distributed random number of type T with mean 0 and standard deviation 1. Optionally generate an array of normally-distributed random numbers. The Base module currently provides an implementation for the types Float16, Float32, and Float64 (the default).

      Examples

      julia> rng = MersenneTwister(1234);
      -
      -julia> randn(rng, Float64)
      -0.8673472019512456
      -
      -julia> randn(rng, Float32, (2, 4))
      -2×4 Array{Float32,2}:
      - -0.901744  -0.902914  2.21188   -0.271735
      - -0.494479   0.864401  0.532813   0.502334
      source
      Base.Random.randn!Function.
      randn!([rng=GLOBAL_RNG], A::AbstractArray) -> A

      Fill the array A with normally-distributed (mean 0, standard deviation 1) random numbers. Also see the rand function.

      Example

      julia> rng = MersenneTwister(1234);
      -
      -julia> randn!(rng, zeros(5))
      -5-element Array{Float64,1}:
      -  0.867347
      - -0.901744
      - -0.494479
      - -0.902914
      -  0.864401
      source
      Base.Random.randexpFunction.
      randexp([rng=GLOBAL_RNG], [T=Float64], [dims...])

      Generate a random number of type T according to the exponential distribution with scale 1. Optionally generate an array of such random numbers. The Base module currently provides an implementation for the types Float16, Float32, and Float64 (the default).

      Examples

      julia> rng = MersenneTwister(1234);
      -
      -julia> randexp(rng, Float32)
      -2.4835055f0
      -
      -julia> randexp(rng, 3, 3)
      -3×3 Array{Float64,2}:
      - 1.5167    1.30652   0.344435
      - 0.604436  2.78029   0.418516
      - 0.695867  0.693292  0.643644
      source
      Base.Random.randexp!Function.
      randexp!([rng=GLOBAL_RNG], A::AbstractArray) -> A

      Fill the array A with random numbers following the exponential distribution (with scale 1).

      Example

      julia> rng = MersenneTwister(1234);
      -
      -julia> randexp!(rng, zeros(5))
      -5-element Array{Float64,1}:
      - 2.48351
      - 1.5167
      - 0.604436
      - 0.695867
      - 1.30652
      source
      Base.Random.randjumpFunction.
      randjump(r::MersenneTwister, jumps::Integer, [jumppoly::AbstractString=dSFMT.JPOLY1e21]) -> Vector{MersenneTwister}

      Create an array of the size jumps of initialized MersenneTwister RNG objects. The first RNG object given as a parameter and following MersenneTwister RNGs in the array are initialized such that a state of the RNG object in the array would be moved forward (without generating numbers) from a previous RNG object array element on a particular number of steps encoded by the jump polynomial jumppoly.

      Default jump polynomial moves forward MersenneTwister RNG state by 10^20 steps.

      source
      diff --git a/julia-0.6.3/share/doc/julia/html/en/stdlib/parallel.html b/julia-0.6.3/share/doc/julia/html/en/stdlib/parallel.html deleted file mode 100644 index 0d7ba16..0000000 --- a/julia-0.6.3/share/doc/julia/html/en/stdlib/parallel.html +++ /dev/null @@ -1,221 +0,0 @@ - -Tasks and Parallel Computing · The Julia Language

      Tasks and Parallel Computing

      Tasks and Parallel Computing

      Tasks

      Core.TaskType.
      Task(func)

      Create a Task (i.e. coroutine) to execute the given function (which must be callable with no arguments). The task exits when this function returns.

      Example

      julia> a() = det(rand(1000, 1000));
      -
      -julia> b = Task(a);

      In this example, b is a runnable Task that hasn't started yet.

      source
      Base.current_taskFunction.
      current_task()

      Get the currently running Task.

      source
      Base.istaskdoneFunction.
      istaskdone(t::Task) -> Bool

      Determine whether a task has exited.

      julia> a2() = det(rand(1000, 1000));
      -
      -julia> b = Task(a2);
      -
      -julia> istaskdone(b)
      -false
      -
      -julia> schedule(b);
      -
      -julia> yield();
      -
      -julia> istaskdone(b)
      -true
      source
      Base.istaskstartedFunction.
      istaskstarted(t::Task) -> Bool

      Determine whether a task has started executing.

      julia> a3() = det(rand(1000, 1000));
      -
      -julia> b = Task(a3);
      -
      -julia> istaskstarted(b)
      -false
      source
      Base.yieldFunction.
      yield()

      Switch to the scheduler to allow another scheduled task to run. A task that calls this function is still runnable, and will be restarted immediately if there are no other runnable tasks.

      source
      yield(t::Task, arg = nothing)

      A fast, unfair-scheduling version of schedule(t, arg); yield() which immediately yields to t before calling the scheduler.

      source
      Base.yieldtoFunction.
      yieldto(t::Task, arg = nothing)

      Switch to the given task. The first time a task is switched to, the task's function is called with no arguments. On subsequent switches, arg is returned from the task's last call to yieldto. This is a low-level call that only switches tasks, not considering states or scheduling in any way. Its use is discouraged.

      source
      task_local_storage(key)

      Look up the value of a key in the current task's task-local storage.

      source
      task_local_storage(key, value)

      Assign a value to a key in the current task's task-local storage.

      source
      task_local_storage(body, key, value)

      Call the function body with a modified task-local storage, in which value is assigned to key; the previous value of key, or lack thereof, is restored afterwards. Useful for emulating dynamic scoping.

      source
      Base.ConditionType.
      Condition()

      Create an edge-triggered event source that tasks can wait for. Tasks that call wait on a Condition are suspended and queued. Tasks are woken up when notify is later called on the Condition. Edge triggering means that only tasks waiting at the time notify is called can be woken up. For level-triggered notifications, you must keep extra state to keep track of whether a notification has happened. The Channel type does this, and so can be used for level-triggered events.

      source
      Base.notifyFunction.
      notify(condition, val=nothing; all=true, error=false)

      Wake up tasks waiting for a condition, passing them val. If all is true (the default), all waiting tasks are woken, otherwise only one is. If error is true, the passed value is raised as an exception in the woken tasks.

      Returns the count of tasks woken up. Returns 0 if no tasks are waiting on condition.

      source
      Base.scheduleFunction.
      schedule(t::Task, [val]; error=false)

      Add a Task to the scheduler's queue. This causes the task to run constantly when the system is otherwise idle, unless the task performs a blocking operation such as wait.

      If a second argument val is provided, it will be passed to the task (via the return value of yieldto) when it runs again. If error is true, the value is raised as an exception in the woken task.

      julia> a5() = det(rand(1000, 1000));
      -
      -julia> b = Task(a5);
      -
      -julia> istaskstarted(b)
      -false
      -
      -julia> schedule(b);
      -
      -julia> yield();
      -
      -julia> istaskstarted(b)
      -true
      -
      -julia> istaskdone(b)
      -true
      source
      Base.@scheduleMacro.
      @schedule

      Wrap an expression in a Task and add it to the local machine's scheduler queue. Similar to @async except that an enclosing @sync does NOT wait for tasks started with an @schedule.

      source
      Base.@taskMacro.
      @task

      Wrap an expression in a Task without executing it, and return the Task. This only creates a task, and does not run it.

      julia> a1() = det(rand(1000, 1000));
      -
      -julia> b = @task a1();
      -
      -julia> istaskstarted(b)
      -false
      -
      -julia> schedule(b);
      -
      -julia> yield();
      -
      -julia> istaskdone(b)
      -true
      source
      Base.sleepFunction.
      sleep(seconds)

      Block the current task for a specified number of seconds. The minimum sleep time is 1 millisecond or input of 0.001.

      source
      Base.ChannelType.
      Channel{T}(sz::Int)

      Constructs a Channel with an internal buffer that can hold a maximum of sz objects of type T. put! calls on a full channel block until an object is removed with take!.

      Channel(0) constructs an unbuffered channel. put! blocks until a matching take! is called. And vice-versa.

      Other constructors:

      • Channel(Inf): equivalent to Channel{Any}(typemax(Int))

      • Channel(sz): equivalent to Channel{Any}(sz)

      source
      Base.put!Method.
      put!(c::Channel, v)

      Appends an item v to the channel c. Blocks if the channel is full.

      For unbuffered channels, blocks until a take! is performed by a different task.

      source
      Base.take!Method.
      take!(c::Channel)

      Removes and returns a value from a Channel. Blocks until data is available.

      For unbuffered channels, blocks until a put! is performed by a different task.

      source
      Base.isreadyMethod.
      isready(c::Channel)

      Determine whether a Channel has a value stored to it. Returns immediately, does not block.

      For unbuffered channels returns true if there are tasks waiting on a put!.

      source
      Base.fetchMethod.
      fetch(c::Channel)

      Waits for and gets the first available item from the channel. Does not remove the item. fetch is unsupported on an unbuffered (0-size) channel.

      source
      Base.closeMethod.
      close(c::Channel)

      Closes a channel. An exception is thrown by:

      source
      Base.bindMethod.
      bind(chnl::Channel, task::Task)

      Associates the lifetime of chnl with a task. Channel chnl is automatically closed when the task terminates. Any uncaught exception in the task is propagated to all waiters on chnl.

      The chnl object can be explicitly closed independent of task termination. Terminating tasks have no effect on already closed Channel objects.

      When a channel is bound to multiple tasks, the first task to terminate will close the channel. When multiple channels are bound to the same task, termination of the task will close all of the bound channels.

      julia> c = Channel(0);
      -
      -julia> task = @schedule foreach(i->put!(c, i), 1:4);
      -
      -julia> bind(c,task);
      -
      -julia> for i in c
      -           @show i
      -       end;
      -i = 1
      -i = 2
      -i = 3
      -i = 4
      -
      -julia> isopen(c)
      -false
      julia> c = Channel(0);
      -
      -julia> task = @schedule (put!(c,1);error("foo"));
      -
      -julia> bind(c,task);
      -
      -julia> take!(c)
      -1
      -
      -julia> put!(c,1);
      -ERROR: foo
      -Stacktrace:
      - [1] check_channel_state(::Channel{Any}) at ./channels.jl:131
      - [2] put!(::Channel{Any}, ::Int64) at ./channels.jl:261
      source
      Base.asyncmapFunction.
      asyncmap(f, c...; ntasks=0, batch_size=nothing)

      Uses multiple concurrent tasks to map f over a collection (or multiple equal length collections). For multiple collection arguments, f is applied elementwise.

      ntasks specifies the number of tasks to run concurrently. Depending on the length of the collections, if ntasks is unspecified, up to 100 tasks will be used for concurrent mapping.

      ntasks can also be specified as a zero-arg function. In this case, the number of tasks to run in parallel is checked before processing every element and a new task started if the value of ntasks_func() is less than the current number of tasks.

      If batch_size is specified, the collection is processed in batch mode. f must then be a function that must accept a Vector of argument tuples and must return a vector of results. The input vector will have a length of batch_size or less.

      The following examples highlight execution in different tasks by returning the object_id of the tasks in which the mapping function is executed.

      First, with ntasks undefined, each element is processed in a different task.

      julia> tskoid() = object_id(current_task());
      -
      -julia> asyncmap(x->tskoid(), 1:5)
      -5-element Array{UInt64,1}:
      - 0x6e15e66c75c75853
      - 0x440f8819a1baa682
      - 0x9fb3eeadd0c83985
      - 0xebd3e35fe90d4050
      - 0x29efc93edce2b961
      -
      -julia> length(unique(asyncmap(x->tskoid(), 1:5)))
      -5

      With ntasks=2 all elements are processed in 2 tasks.

      julia> asyncmap(x->tskoid(), 1:5; ntasks=2)
      -5-element Array{UInt64,1}:
      - 0x027ab1680df7ae94
      - 0xa23d2f80cd7cf157
      - 0x027ab1680df7ae94
      - 0xa23d2f80cd7cf157
      - 0x027ab1680df7ae94
      -
      -julia> length(unique(asyncmap(x->tskoid(), 1:5; ntasks=2)))
      -2

      With batch_size defined, the mapping function needs to be changed to accept an array of argument tuples and return an array of results. map is used in the modified mapping function to achieve this.

      julia> batch_func(input) = map(x->string("args_tuple: ", x, ", element_val: ", x[1], ", task: ", tskoid()), input)
      -batch_func (generic function with 1 method)
      -
      -julia> asyncmap(batch_func, 1:5; ntasks=2, batch_size=2)
      -5-element Array{String,1}:
      - "args_tuple: (1,), element_val: 1, task: 9118321258196414413"
      - "args_tuple: (2,), element_val: 2, task: 4904288162898683522"
      - "args_tuple: (3,), element_val: 3, task: 9118321258196414413"
      - "args_tuple: (4,), element_val: 4, task: 4904288162898683522"
      - "args_tuple: (5,), element_val: 5, task: 9118321258196414413"
      Note

      Currently, all tasks in Julia are executed in a single OS thread co-operatively. Consequently, ayncmap is beneficial only when the mapping function involves any I/O - disk, network, remote worker invocation, etc.

      source
      Base.asyncmap!Function.
      asyncmap!(f, results, c...; ntasks=0, batch_size=nothing)

      Like asyncmap(), but stores output in results rather than returning a collection.

      source

      General Parallel Computing Support

      addprocs(manager::ClusterManager; kwargs...) -> List of process identifiers

      Launches worker processes via the specified cluster manager.

      For example, Beowulf clusters are supported via a custom cluster manager implemented in the package ClusterManagers.jl.

      The number of seconds a newly launched worker waits for connection establishment from the master can be specified via variable JULIA_WORKER_TIMEOUT in the worker process's environment. Relevant only when using TCP/IP as transport.

      source
      addprocs(machines; tunnel=false, sshflags=``, max_parallel=10, kwargs...) -> List of process identifiers

      Add processes on remote machines via SSH. Requires julia to be installed in the same location on each node, or to be available via a shared file system.

      machines is a vector of machine specifications. Workers are started for each specification.

      A machine specification is either a string machine_spec or a tuple - (machine_spec, count).

      machine_spec is a string of the form [user@]host[:port] [bind_addr[:port]]. user defaults to current user, port to the standard ssh port. If [bind_addr[:port]] is specified, other workers will connect to this worker at the specified bind_addr and port.

      count is the number of workers to be launched on the specified host. If specified as :auto it will launch as many workers as the number of cores on the specific host.

      Keyword arguments:

      • tunnel: if true then SSH tunneling will be used to connect to the worker from the master process. Default is false.

      • sshflags: specifies additional ssh options, e.g. sshflags=`-i /home/foo/bar.pem`

      • max_parallel: specifies the maximum number of workers connected to in parallel at a host. Defaults to 10.

      • dir: specifies the working directory on the workers. Defaults to the host's current directory (as found by pwd())

      • enable_threaded_blas: if true then BLAS will run on multiple threads in added processes. Default is false.

      • exename: name of the julia executable. Defaults to "$JULIA_HOME/julia" or "$JULIA_HOME/julia-debug" as the case may be.

      • exeflags: additional flags passed to the worker processes.

      • topology: Specifies how the workers connect to each other. Sending a message between unconnected workers results in an error.

        • topology=:all_to_all: All processes are connected to each other. The default.

        • topology=:master_slave: Only the driver process, i.e. pid 1 connects to the workers. The workers do not connect to each other.

        • topology=:custom: The launch method of the cluster manager specifies the connection topology via fields ident and connect_idents in WorkerConfig. A worker with a cluster manager identity ident will connect to all workers specified in connect_idents.

      Environment variables :

      If the master process fails to establish a connection with a newly launched worker within 60.0 seconds, the worker treats it as a fatal situation and terminates. This timeout can be controlled via environment variable JULIA_WORKER_TIMEOUT. The value of JULIA_WORKER_TIMEOUT on the master process specifies the number of seconds a newly launched worker waits for connection establishment.

      source
      addprocs(; kwargs...) -> List of process identifiers

      Equivalent to addprocs(Sys.CPU_CORES; kwargs...)

      Note that workers do not run a .juliarc.jl startup script, nor do they synchronize their global state (such as global variables, new method definitions, and loaded modules) with any of the other running processes.

      source
      addprocs(np::Integer; restrict=true, kwargs...) -> List of process identifiers

      Launches workers using the in-built LocalManager which only launches workers on the local host. This can be used to take advantage of multiple cores. addprocs(4) will add 4 processes on the local machine. If restrict is true, binding is restricted to 127.0.0.1. Keyword args dir, exename, exeflags, topology, and enable_threaded_blas have the same effect as documented for addprocs(machines).

      source
      nprocs()

      Get the number of available processes.

      source
      nworkers()

      Get the number of available worker processes. This is one less than nprocs(). Equal to nprocs() if nprocs() == 1.

      source
      procs()

      Returns a list of all process identifiers.

      source
      procs(pid::Integer)

      Returns a list of all process identifiers on the same physical node. Specifically all workers bound to the same ip-address as pid are returned.

      source
      workers()

      Returns a list of all worker process identifiers.

      source
      rmprocs(pids...; waitfor=typemax(Int))

      Removes the specified workers. Note that only process 1 can add or remove workers.

      Argument waitfor specifies how long to wait for the workers to shut down: - If unspecified, rmprocs will wait until all requested pids are removed. - An ErrorException is raised if all workers cannot be terminated before the requested waitfor seconds. - With a waitfor value of 0, the call returns immediately with the workers scheduled for removal in a different task. The scheduled Task object is returned. The user should call wait on the task before invoking any other parallel calls.

      source
      interrupt(pids::Integer...)

      Interrupt the current executing task on the specified workers. This is equivalent to pressing Ctrl-C on the local machine. If no arguments are given, all workers are interrupted.

      source
      interrupt(pids::AbstractVector=workers())

      Interrupt the current executing task on the specified workers. This is equivalent to pressing Ctrl-C on the local machine. If no arguments are given, all workers are interrupted.

      source
      Base.Distributed.myidFunction.
      myid()

      Get the id of the current process.

      source
      Base.Distributed.pmapFunction.
      pmap([::AbstractWorkerPool], f, c...; distributed=true, batch_size=1, on_error=nothing, retry_delays=[]), retry_check=nothing) -> collection

      Transform collection c by applying f to each element using available workers and tasks.

      For multiple collection arguments, apply f elementwise.

      Note that f must be made available to all worker processes; see Code Availability and Loading Packages for details.

      If a worker pool is not specified, all available workers, i.e., the default worker pool is used.

      By default, pmap distributes the computation over all specified workers. To use only the local process and distribute over tasks, specify distributed=false. This is equivalent to using asyncmap. For example, pmap(f, c; distributed=false) is equivalent to asyncmap(f,c; ntasks=()->nworkers())

      pmap can also use a mix of processes and tasks via the batch_size argument. For batch sizes greater than 1, the collection is processed in multiple batches, each of length batch_size or less. A batch is sent as a single request to a free worker, where a local asyncmap processes elements from the batch using multiple concurrent tasks.

      Any error stops pmap from processing the remainder of the collection. To override this behavior you can specify an error handling function via argument on_error which takes in a single argument, i.e., the exception. The function can stop the processing by rethrowing the error, or, to continue, return any value which is then returned inline with the results to the caller.

      Consider the following two examples. The first one returns the exception object inline, the second a 0 in place of any exception:

      julia> pmap(x->iseven(x) ? error("foo") : x, 1:4; on_error=identity)
      -4-element Array{Any,1}:
      - 1
      -  ErrorException("foo")
      - 3
      -  ErrorException("foo")
      -
      -julia> pmap(x->iseven(x) ? error("foo") : x, 1:4; on_error=ex->0)
      -4-element Array{Int64,1}:
      - 1
      - 0
      - 3
      - 0

      Errors can also be handled by retrying failed computations. Keyword arguments retry_delays and retry_check are passed through to retry as keyword arguments delays and check respectively. If batching is specified, and an entire batch fails, all items in the batch are retried.

      Note that if both on_error and retry_delays are specified, the on_error hook is called before retrying. If on_error does not throw (or rethrow) an exception, the element will not be retried.

      Example: On errors, retry f on an element a maximum of 3 times without any delay between retries.

      pmap(f, c; retry_delays = zeros(3))

      Example: Retry f only if the exception is not of type InexactError, with exponentially increasing delays up to 3 times. Return a NaN in place for all InexactError occurrences.

      pmap(f, c; on_error = e->(isa(e, InexactError) ? NaN : rethrow(e)), retry_delays = ExponentialBackOff(n = 3))
      source
      RemoteException(captured)

      Exceptions on remote computations are captured and rethrown locally. A RemoteException wraps the pid of the worker and a captured exception. A CapturedException captures the remote exception and a serializable form of the call stack when the exception was raised.

      source
      Future(pid::Integer=myid())

      Create a Future on process pid. The default pid is the current process.

      source
      RemoteChannel(pid::Integer=myid())

      Make a reference to a Channel{Any}(1) on process pid. The default pid is the current process.

      source
      RemoteChannel(f::Function, pid::Integer=myid())

      Create references to remote channels of a specific size and type. f() is a function that when executed on pid must return an implementation of an AbstractChannel.

      For example, RemoteChannel(()->Channel{Int}(10), pid), will return a reference to a channel of type Int and size 10 on pid.

      The default pid is the current process.

      source
      Base.waitFunction.
      wait([x])

      Block the current task until some event occurs, depending on the type of the argument:

      • RemoteChannel : Wait for a value to become available on the specified remote channel.

      • Future : Wait for a value to become available for the specified future.

      • Channel: Wait for a value to be appended to the channel.

      • Condition: Wait for notify on a condition.

      • Process: Wait for a process or process chain to exit. The exitcode field of a process can be used to determine success or failure.

      • Task: Wait for a Task to finish, returning its result value. If the task fails with an exception, the exception is propagated (re-thrown in the task that called wait).

      • RawFD: Wait for changes on a file descriptor (see poll_fd for keyword arguments and return code)

      If no argument is passed, the task blocks for an undefined period. A task can only be restarted by an explicit call to schedule or yieldto.

      Often wait is called within a while loop to ensure a waited-for condition is met before proceeding.

      source
      Base.fetchMethod.
      fetch(x)

      Waits and fetches a value from x depending on the type of x:

      • Future: Wait for and get the value of a Future. The fetched value is cached locally. Further calls to fetch on the same reference return the cached value. If the remote value is an exception, throws a RemoteException which captures the remote exception and backtrace.

      • RemoteChannel: Wait for and get the value of a remote reference. Exceptions raised are same as for a Future .

      Does not remove the item fetched.

      source
      remotecall(f, id::Integer, args...; kwargs...) -> Future

      Call a function f asynchronously on the given arguments on the specified process. Returns a Future. Keyword arguments, if any, are passed through to f.

      source
      remotecall_wait(f, id::Integer, args...; kwargs...)

      Perform a faster wait(remotecall(...)) in one message on the Worker specified by worker id id. Keyword arguments, if any, are passed through to f.

      See also wait and remotecall.

      source
      remotecall_fetch(f, id::Integer, args...; kwargs...)

      Perform fetch(remotecall(...)) in one message. Keyword arguments, if any, are passed through to f. Any remote exceptions are captured in a RemoteException and thrown.

      See also fetch and remotecall.

      source
      remote_do(f, id::Integer, args...; kwargs...) -> nothing

      Executes f on worker id asynchronously. Unlike remotecall, it does not store the result of computation, nor is there a way to wait for its completion.

      A successful invocation indicates that the request has been accepted for execution on the remote node.

      While consecutive remotecalls to the same worker are serialized in the order they are invoked, the order of executions on the remote worker is undetermined. For example, remote_do(f1, 2); remotecall(f2, 2); remote_do(f3, 2) will serialize the call to f1, followed by f2 and f3 in that order. However, it is not guaranteed that f1 is executed before f3 on worker 2.

      Any exceptions thrown by f are printed to STDERR on the remote worker.

      Keyword arguments, if any, are passed through to f.

      source
      Base.put!Method.
      put!(rr::RemoteChannel, args...)

      Store a set of values to the RemoteChannel. If the channel is full, blocks until space is available. Returns its first argument.

      source
      Base.put!Method.
      put!(rr::Future, v)

      Store a value to a Future rr. Futures are write-once remote references. A put! on an already set Future throws an Exception. All asynchronous remote calls return Futures and set the value to the return value of the call upon completion.

      source
      Base.take!Method.
      take!(rr::RemoteChannel, args...)

      Fetch value(s) from a RemoteChannel rr, removing the value(s) in the processs.

      source
      Base.isreadyMethod.
      isready(rr::RemoteChannel, args...)

      Determine whether a RemoteChannel has a value stored to it. Note that this function can cause race conditions, since by the time you receive its result it may no longer be true. However, it can be safely used on a Future since they are assigned only once.

      source
      Base.isreadyMethod.
      isready(rr::Future)

      Determine whether a Future has a value stored to it.

      If the argument Future is owned by a different node, this call will block to wait for the answer. It is recommended to wait for rr in a separate task instead or to use a local Channel as a proxy:

      c = Channel(1)
      -@async put!(c, remotecall_fetch(long_computation, p))
      -isready(c)  # will not block
      source
      WorkerPool(workers::Vector{Int})

      Create a WorkerPool from a vector of worker ids.

      source
      CachingPool(workers::Vector{Int})

      An implementation of an AbstractWorkerPool. remote, remotecall_fetch, pmap (and other remote calls which execute functions remotely) benefit from caching the serialized/deserialized functions on the worker nodes, especially closures (which may capture large amounts of data).

      The remote cache is maintained for the lifetime of the returned CachingPool object. To clear the cache earlier, use clear!(pool).

      For global variables, only the bindings are captured in a closure, not the data. let blocks can be used to capture global data.

      For example:

      const foo=rand(10^8);
      -wp=CachingPool(workers())
      -let foo=foo
      -    pmap(wp, i->sum(foo)+i, 1:100);
      -end

      The above would transfer foo only once to each worker.

      source
      default_worker_pool()

      WorkerPool containing idle workers() - used by remote(f) and pmap (by default).

      source
      clear!(pool::CachingPool) -> pool

      Removes all cached functions from all participating workers.

      source
      remote([::AbstractWorkerPool], f) -> Function

      Returns an anonymous function that executes function f on an available worker using remotecall_fetch.

      source
      remotecall(f, pool::AbstractWorkerPool, args...; kwargs...) -> Future

      WorkerPool variant of remotecall(f, pid, ....). Waits for and takes a free worker from pool and performs a remotecall on it.

      source
      remotecall_wait(f, pool::AbstractWorkerPool, args...; kwargs...) -> Future

      WorkerPool variant of remotecall_wait(f, pid, ....). Waits for and takes a free worker from pool and performs a remotecall_wait on it.

      source
      remotecall_fetch(f, pool::AbstractWorkerPool, args...; kwargs...) -> result

      WorkerPool variant of remotecall_fetch(f, pid, ....). Waits for and takes a free worker from pool and performs a remotecall_fetch on it.

      source
      remote_do(f, pool::AbstractWorkerPool, args...; kwargs...) -> nothing

      WorkerPool variant of remote_do(f, pid, ....). Waits for and takes a free worker from pool and performs a remote_do on it.

      source
      Base.timedwaitFunction.
      timedwait(testcb::Function, secs::Float64; pollint::Float64=0.1)

      Waits until testcb returns true or for secs seconds, whichever is earlier. testcb is polled every pollint seconds.

      source
      @spawn

      Creates a closure around an expression and runs it on an automatically-chosen process, returning a Future to the result.

      source
      @spawnat

      Accepts two arguments, p and an expression. A closure is created around the expression and run asynchronously on process p. Returns a Future to the result.

      source
      @fetch

      Equivalent to fetch(@spawn expr). See fetch and @spawn.

      source
      @fetchfrom

      Equivalent to fetch(@spawnat p expr). See fetch and @spawnat.

      source
      Base.@asyncMacro.
      @async

      Like @schedule, @async wraps an expression in a Task and adds it to the local machine's scheduler queue. Additionally it adds the task to the set of items that the nearest enclosing @sync waits for.

      source
      Base.@syncMacro.
      @sync

      Wait until all dynamically-enclosed uses of @async, @spawn, @spawnat and @parallel are complete. All exceptions thrown by enclosed async operations are collected and thrown as a CompositeException.

      source
      @parallel

      A parallel for loop of the form :

      @parallel [reducer] for var = range
      -    body
      -end

      The specified range is partitioned and locally executed across all workers. In case an optional reducer function is specified, @parallel performs local reductions on each worker with a final reduction on the calling process.

      Note that without a reducer function, @parallel executes asynchronously, i.e. it spawns independent tasks on all available workers and returns immediately without waiting for completion. To wait for completion, prefix the call with @sync, like :

      @sync @parallel for var = range
      -    body
      -end
      source
      @everywhere expr

      Execute an expression under Main everywhere. Equivalent to calling eval(Main, expr) on all processes. Errors on any of the processes are collected into a CompositeException and thrown. For example :

      @everywhere bar=1

      will define Main.bar on all processes.

      Unlike @spawn and @spawnat, @everywhere does not capture any local variables. Prefixing @everywhere with @eval allows us to broadcast local variables using interpolation :

      foo = 1
      -@eval @everywhere bar=$foo

      The expression is evaluated under Main irrespective of where @everywhere is called from. For example :

      module FooBar
      -    foo() = @everywhere bar()=myid()
      -end
      -FooBar.foo()

      will result in Main.bar being defined on all processes and not FooBar.bar.

      source
      clear!(syms, pids=workers(); mod=Main)

      Clears global bindings in modules by initializing them to nothing. syms should be of type Symbol or a collection of Symbols . pids and mod identify the processes and the module in which global variables are to be reinitialized. Only those names found to be defined under mod are cleared.

      An exception is raised if a global constant is requested to be cleared.

      source
      Base.remoteref_id(r::AbstractRemoteRef) -> RRID

      Futures and RemoteChannels are identified by fields:

      • where - refers to the node where the underlying object/storage referred to by the reference actually exists.

      • whence - refers to the node the remote reference was created from. Note that this is different from the node where the underlying object referred to actually exists. For example calling RemoteChannel(2) from the master process would result in a where value of 2 and a whence value of 1.

      • id is unique across all references created from the worker specified by whence.

      Taken together, whence and id uniquely identify a reference across all workers.

      Base.remoteref_id is a low-level API which returns a Base.RRID object that wraps whence and id values of a remote reference.

      source
      Base.channel_from_id(id) -> c

      A low-level API which returns the backing AbstractChannel for an id returned by remoteref_id. The call is valid only on the node where the backing channel exists.

      source
      Base.worker_id_from_socket(s) -> pid

      A low-level API which given a IO connection or a Worker, returns the pid of the worker it is connected to. This is useful when writing custom serialize methods for a type, which optimizes the data written out depending on the receiving process id.

      source
      Base.cluster_cookie() -> cookie

      Returns the cluster cookie.

      source
      Base.cluster_cookie(cookie) -> cookie

      Sets the passed cookie as the cluster cookie, then returns it.

      source

      Shared Arrays

      SharedArray{T}(dims::NTuple; init=false, pids=Int[])
      -SharedArray{T,N}(...)

      Construct a SharedArray of a bits type T and size dims across the processes specified by pids - all of which have to be on the same host. If N is specified by calling SharedArray{T,N}(dims), then N must match the length of dims.

      If pids is left unspecified, the shared array will be mapped across all processes on the current host, including the master. But, localindexes and indexpids will only refer to worker processes. This facilitates work distribution code to use workers for actual computation with the master process acting as a driver.

      If an init function of the type initfn(S::SharedArray) is specified, it is called on all the participating workers.

      The shared array is valid as long as a reference to the SharedArray object exists on the node which created the mapping.

      SharedArray{T}(filename::AbstractString, dims::NTuple, [offset=0]; mode=nothing, init=false, pids=Int[])
      -SharedArray{T,N}(...)

      Construct a SharedArray backed by the file filename, with element type T (must be a bits type) and size dims, across the processes specified by pids - all of which have to be on the same host. This file is mmapped into the host memory, with the following consequences:

      • The array data must be represented in binary format (e.g., an ASCII format like CSV cannot be supported)

      • Any changes you make to the array values (e.g., A[3] = 0) will also change the values on disk

      If pids is left unspecified, the shared array will be mapped across all processes on the current host, including the master. But, localindexes and indexpids will only refer to worker processes. This facilitates work distribution code to use workers for actual computation with the master process acting as a driver.

      mode must be one of "r", "r+", "w+", or "a+", and defaults to "r+" if the file specified by filename already exists, or "w+" if not. If an init function of the type initfn(S::SharedArray) is specified, it is called on all the participating workers. You cannot specify an init function if the file is not writable.

      offset allows you to skip the specified number of bytes at the beginning of the file.

      source
      procs(S::SharedArray)

      Get the vector of processes mapping the shared array.

      source
      Base.sdataFunction.
      sdata(S::SharedArray)

      Returns the actual Array object backing S.

      source
      Base.indexpidsFunction.
      indexpids(S::SharedArray)

      Returns the current worker's index in the list of workers mapping the SharedArray (i.e. in the same list returned by procs(S)), or 0 if the SharedArray is not mapped locally.

      source
      Base.localindexesFunction.
      localindexes(S::SharedArray)

      Returns a range describing the "default" indexes to be handled by the current process. This range should be interpreted in the sense of linear indexing, i.e., as a sub-range of 1:length(S). In multi-process contexts, returns an empty range in the parent process (or any process for which indexpids returns 0).

      It's worth emphasizing that localindexes exists purely as a convenience, and you can partition work on the array among workers any way you wish. For a SharedArray, all indexes should be equally fast for each worker process.

      source

      Multi-Threading

      This experimental interface supports Julia's multi-threading capabilities. Types and functions described here might (and likely will) change in the future.

      Base.Threads.threadidFunction.
      Threads.threadid()

      Get the ID number of the current thread of execution. The master thread has ID 1.

      source
      Base.Threads.nthreadsFunction.
      Threads.nthreads()

      Get the number of threads available to the Julia process. This is the inclusive upper bound on threadid().

      source
      Threads.@threads

      A macro to parallelize a for-loop to run with multiple threads. This spawns nthreads() number of threads, splits the iteration space amongst them, and iterates in parallel. A barrier is placed at the end of the loop which waits for all the threads to finish execution, and the loop returns.

      source
      Threads.Atomic{T}

      Holds a reference to an object of type T, ensuring that it is only accessed atomically, i.e. in a thread-safe manner.

      Only certain "simple" types can be used atomically, namely the primitive integer and float-point types. These are Int8...Int128, UInt8...UInt128, and Float16...Float64.

      New atomic objects can be created from a non-atomic values; if none is specified, the atomic object is initialized with zero.

      Atomic objects can be accessed using the [] notation:

      julia> x = Threads.Atomic{Int}(3)
      -Base.Threads.Atomic{Int64}(3)
      -
      -julia> x[] = 1
      -1
      -
      -julia> x[]
      -1

      Atomic operations use an atomic_ prefix, such as atomic_add!, atomic_xchg!, etc.

      source
      Threads.atomic_cas!{T}(x::Atomic{T}, cmp::T, newval::T)

      Atomically compare-and-set x

      Atomically compares the value in x with cmp. If equal, write newval to x. Otherwise, leaves x unmodified. Returns the old value in x. By comparing the returned value to cmp (via ===) one knows whether x was modified and now holds the new value newval.

      For further details, see LLVM's cmpxchg instruction.

      This function can be used to implement transactional semantics. Before the transaction, one records the value in x. After the transaction, the new value is stored only if x has not been modified in the mean time.

      julia> x = Threads.Atomic{Int}(3)
      -Base.Threads.Atomic{Int64}(3)
      -
      -julia> Threads.atomic_cas!(x, 4, 2);
      -
      -julia> x
      -Base.Threads.Atomic{Int64}(3)
      -
      -julia> Threads.atomic_cas!(x, 3, 2);
      -
      -julia> x
      -Base.Threads.Atomic{Int64}(2)
      source
      Threads.atomic_xchg!{T}(x::Atomic{T}, newval::T)

      Atomically exchange the value in x

      Atomically exchanges the value in x with newval. Returns the old value.

      For further details, see LLVM's atomicrmw xchg instruction.

      julia> x = Threads.Atomic{Int}(3)
      -Base.Threads.Atomic{Int64}(3)
      -
      -julia> Threads.atomic_xchg!(x, 2)
      -3
      -
      -julia> x[]
      -2
      source
      Threads.atomic_add!{T}(x::Atomic{T}, val::T)

      Atomically add val to x

      Performs x[] += val atomically. Returns the old value.

      For further details, see LLVM's atomicrmw add instruction.

      julia> x = Threads.Atomic{Int}(3)
      -Base.Threads.Atomic{Int64}(3)
      -
      -julia> Threads.atomic_add!(x, 2)
      -3
      -
      -julia> x[]
      -5
      source
      Threads.atomic_sub!{T}(x::Atomic{T}, val::T)

      Atomically subtract val from x

      Performs x[] -= val atomically. Returns the old value.

      For further details, see LLVM's atomicrmw sub instruction.

      julia> x = Threads.Atomic{Int}(3)
      -Base.Threads.Atomic{Int64}(3)
      -
      -julia> Threads.atomic_sub!(x, 2)
      -3
      -
      -julia> x[]
      -1
      source
      Threads.atomic_and!{T}(x::Atomic{T}, val::T)

      Atomically bitwise-and x with val

      Performs x[] &= val atomically. Returns the old value.

      For further details, see LLVM's atomicrmw and instruction.

      julia> x = Threads.Atomic{Int}(3)
      -Base.Threads.Atomic{Int64}(3)
      -
      -julia> Threads.atomic_and!(x, 2)
      -3
      -
      -julia> x[]
      -2
      source
      Threads.atomic_nand!{T}(x::Atomic{T}, val::T)

      Atomically bitwise-nand (not-and) x with val

      Performs x[] = ~(x[] & val) atomically. Returns the old value.

      For further details, see LLVM's atomicrmw nand instruction.

      julia> x = Threads.Atomic{Int}(3)
      -Base.Threads.Atomic{Int64}(3)
      -
      -julia> Threads.atomic_nand!(x, 2)
      -3
      -
      -julia> x[]
      --3
      source
      Threads.atomic_or!{T}(x::Atomic{T}, val::T)

      Atomically bitwise-or x with val

      Performs x[] |= val atomically. Returns the old value.

      For further details, see LLVM's atomicrmw or instruction.

      julia> x = Threads.Atomic{Int}(5)
      -Base.Threads.Atomic{Int64}(5)
      -
      -julia> Threads.atomic_or!(x, 7)
      -5
      -
      -julia> x[]
      -7
      source
      Threads.atomic_xor!{T}(x::Atomic{T}, val::T)

      Atomically bitwise-xor (exclusive-or) x with val

      Performs x[] $= val atomically. Returns the old value.

      For further details, see LLVM's atomicrmw xor instruction.

      julia> x = Threads.Atomic{Int}(5)
      -Base.Threads.Atomic{Int64}(5)
      -
      -julia> Threads.atomic_xor!(x, 7)
      -5
      -
      -julia> x[]
      -2
      source
      Threads.atomic_max!{T}(x::Atomic{T}, val::T)

      Atomically store the maximum of x and val in x

      Performs x[] = max(x[], val) atomically. Returns the old value.

      For further details, see LLVM's atomicrmw max instruction.

      julia> x = Threads.Atomic{Int}(5)
      -Base.Threads.Atomic{Int64}(5)
      -
      -julia> Threads.atomic_max!(x, 7)
      -5
      -
      -julia> x[]
      -7
      source
      Threads.atomic_min!{T}(x::Atomic{T}, val::T)

      Atomically store the minimum of x and val in x

      Performs x[] = min(x[], val) atomically. Returns the old value.

      For further details, see LLVM's atomicrmw min instruction.

      julia> x = Threads.Atomic{Int}(7)
      -Base.Threads.Atomic{Int64}(7)
      -
      -julia> Threads.atomic_min!(x, 5)
      -7
      -
      -julia> x[]
      -5
      source
      Threads.atomic_fence()

      Insert a sequential-consistency memory fence

      Inserts a memory fence with sequentially-consistent ordering semantics. There are algorithms where this is needed, i.e. where an acquire/release ordering is insufficient.

      This is likely a very expensive operation. Given that all other atomic operations in Julia already have acquire/release semantics, explicit fences should not be necessary in most cases.

      For further details, see LLVM's fence instruction.

      source

      ccall using a threadpool (Experimental)

      Base.@threadcallMacro.
      @threadcall((cfunc, clib), rettype, (argtypes...), argvals...)

      The @threadcall macro is called in the same way as ccall but does the work in a different thread. This is useful when you want to call a blocking C function without causing the main julia thread to become blocked. Concurrency is limited by size of the libuv thread pool, which defaults to 4 threads but can be increased by setting the UV_THREADPOOL_SIZE environment variable and restarting the julia process.

      Note that the called function should never call back into Julia.

      source

      Synchronization Primitives

      AbstractLock

      Abstract supertype describing types that implement the thread-safe synchronization primitives: lock, trylock, unlock, and islocked

      source
      Base.lockFunction.
      lock(the_lock)

      Acquires the lock when it becomes available. If the lock is already locked by a different task/thread, it waits for it to become available.

      Each lock must be matched by an unlock.

      source
      Base.unlockFunction.
      unlock(the_lock)

      Releases ownership of the lock.

      If this is a recursive lock which has been acquired before, it just decrements an internal counter and returns immediately.

      source
      Base.trylockFunction.
      trylock(the_lock) -> Success (Boolean)

      Acquires the lock if it is available, returning true if successful. If the lock is already locked by a different task/thread, returns false.

      Each successful trylock must be matched by an unlock.

      source
      Base.islockedFunction.
      islocked(the_lock) -> Status (Boolean)

      Check whether the lock is held by any task/thread. This should not be used for synchronization (see instead trylock).

      source
      ReentrantLock()

      Creates a reentrant lock for synchronizing Tasks. The same task can acquire the lock as many times as required. Each lock must be matched with an unlock.

      This lock is NOT threadsafe. See Threads.Mutex for a threadsafe lock.

      source
      Mutex()

      These are standard system mutexes for locking critical sections of logic.

      On Windows, this is a critical section object, on pthreads, this is a pthread_mutex_t.

      See also SpinLock for a lighter-weight lock.

      source
      SpinLock()

      Creates a non-reentrant lock. Recursive use will result in a deadlock. Each lock must be matched with an unlock.

      Test-and-test-and-set spin locks are quickest up to about 30ish contending threads. If you have more contention than that, perhaps a lock is the wrong way to synchronize.

      See also RecursiveSpinLock for a version that permits recursion.

      See also Mutex for a more efficient version on one core or if the lock may be held for a considerable length of time.

      source
      RecursiveSpinLock()

      Creates a reentrant lock. The same thread can acquire the lock as many times as required. Each lock must be matched with an unlock.

      See also SpinLock for a slightly faster version.

      See also Mutex for a more efficient version on one core or if the lock may be held for a considerable length of time.

      source
      Base.SemaphoreType.
      Semaphore(sem_size)

      Creates a counting semaphore that allows at most sem_size acquires to be in use at any time. Each acquire must be mached with a release.

      This construct is NOT threadsafe.

      source
      Base.acquireFunction.
      acquire(s::Semaphore)

      Wait for one of the sem_size permits to be available, blocking until one can be acquired.

      source
      Base.releaseFunction.
      release(s::Semaphore)

      Return one permit to the pool, possibly allowing another task to acquire it and resume execution.

      source

      Cluster Manager Interface

      This interface provides a mechanism to launch and manage Julia workers on different cluster environments. There are two types of managers present in Base: LocalManager, for launching additional workers on the same host, and SSHManager, for launching on remote hosts via ssh. TCP/IP sockets are used to connect and transport messages between processes. It is possible for Cluster Managers to provide a different transport.

      launch(manager::ClusterManager, params::Dict, launched::Array, launch_ntfy::Condition)

      Implemented by cluster managers. For every Julia worker launched by this function, it should append a WorkerConfig entry to launched and notify launch_ntfy. The function MUST exit once all workers, requested by manager have been launched. params is a dictionary of all keyword arguments addprocs was called with.

      source
      manage(manager::ClusterManager, id::Integer, config::WorkerConfig. op::Symbol)

      Implemented by cluster managers. It is called on the master process, during a worker's lifetime, with appropriate op values:

      • with :register/:deregister when a worker is added / removed from the Julia worker pool.

      • with :interrupt when interrupt(workers) is called. The ClusterManager should signal the appropriate worker with an interrupt signal.

      • with :finalize for cleanup purposes.

      source
      Base.killMethod.
      kill(manager::ClusterManager, pid::Int, config::WorkerConfig)

      Implemented by cluster managers. It is called on the master process, by rmprocs. It should cause the remote worker specified by pid to exit. kill(manager::ClusterManager.....) executes a remote exit() on pid.

      source
      init_worker(cookie::AbstractString, manager::ClusterManager=DefaultClusterManager())

      Called by cluster managers implementing custom transports. It initializes a newly launched process as a worker. Command line argument --worker has the effect of initializing a process as a worker using TCP/IP sockets for transport. cookie is a cluster_cookie.

      source
      Base.connectMethod.
      connect(manager::ClusterManager, pid::Int, config::WorkerConfig) -> (instrm::IO, outstrm::IO)

      Implemented by cluster managers using custom transports. It should establish a logical connection to worker with id pid, specified by config and return a pair of IO objects. Messages from pid to current process will be read off instrm, while messages to be sent to pid will be written to outstrm. The custom transport implementation must ensure that messages are delivered and received completely and in order. connect(manager::ClusterManager.....) sets up TCP/IP socket connections in-between workers.

      source
      Base.process_messages(r_stream::IO, w_stream::IO, incoming::Bool=true)

      Called by cluster managers using custom transports. It should be called when the custom transport implementation receives the first message from a remote worker. The custom transport must manage a logical connection to the remote worker and provide two IO objects, one for incoming messages and the other for messages addressed to the remote worker. If incoming is true, the remote peer initiated the connection. Whichever of the pair initiates the connection sends the cluster cookie and its Julia version number to perform the authentication handshake.

      See also cluster_cookie.

      source
      diff --git a/julia-0.6.3/share/doc/julia/html/en/stdlib/pkg.html b/julia-0.6.3/share/doc/julia/html/en/stdlib/pkg.html deleted file mode 100644 index aabc612..0000000 --- a/julia-0.6.3/share/doc/julia/html/en/stdlib/pkg.html +++ /dev/null @@ -1,9 +0,0 @@ - -Package Manager Functions · The Julia Language

      Package Manager Functions

      Package Manager Functions

      All package manager functions are defined in the Pkg module. None of the Pkg module's functions are exported; to use them, you'll need to prefix each function call with an explicit Pkg., e.g. Pkg.status() or Pkg.dir().

      Functions for package development (e.g. tag, publish, etc.) have been moved to the PkgDev package. See PkgDev README for the documentation of those functions.

      Base.Pkg.dirFunction.
      dir() -> AbstractString

      Returns the absolute path of the package directory. This defaults to joinpath(homedir(),".julia","v$(VERSION.major).$(VERSION.minor)") on all platforms (i.e. ~/.julia/v0.6 in UNIX shell syntax). If the JULIA_PKGDIR environment variable is set, then that path is used in the returned value as joinpath(ENV["JULIA_PKGDIR"],"v$(VERSION.major).$(VERSION.minor)"). If JULIA_PKGDIR is a relative path, it is interpreted relative to whatever the current working directory is.

      source
      dir(names...) -> AbstractString

      Equivalent to normpath(Pkg.dir(),names...) – i.e. it appends path components to the package directory and normalizes the resulting path. In particular, Pkg.dir(pkg) returns the path to the package pkg.

      source
      Base.Pkg.initFunction.
      init(meta::AbstractString=DEFAULT_META, branch::AbstractString=META_BRANCH)

      Initialize Pkg.dir() as a package directory. This will be done automatically when the JULIA_PKGDIR is not set and Pkg.dir() uses its default value. As part of this process, clones a local METADATA git repository from the site and branch specified by its arguments, which are typically not provided. Explicit (non-default) arguments can be used to support a custom METADATA setup.

      source
      Base.Pkg.resolveFunction.
      resolve()

      Determines an optimal, consistent set of package versions to install or upgrade to. The optimal set of package versions is based on the contents of Pkg.dir("REQUIRE") and the state of installed packages in Pkg.dir(), Packages that are no longer required are moved into Pkg.dir(".trash").

      source
      Base.Pkg.editFunction.
      edit()

      Opens Pkg.dir("REQUIRE") in the editor specified by the VISUAL or EDITOR environment variables; when the editor command returns, it runs Pkg.resolve() to determine and install a new optimal set of installed package versions.

      source
      Base.Pkg.addFunction.
      add(pkg, vers...)

      Add a requirement entry for pkg to Pkg.dir("REQUIRE") and call Pkg.resolve(). If vers are given, they must be VersionNumber objects and they specify acceptable version intervals for pkg.

      source
      Base.Pkg.rmFunction.
      rm(pkg)

      Remove all requirement entries for pkg from Pkg.dir("REQUIRE") and call Pkg.resolve().

      source
      Base.Pkg.cloneFunction.
      clone(pkg)

      If pkg has a URL registered in Pkg.dir("METADATA"), clone it from that URL on the default branch. The package does not need to have any registered versions.

      source
      clone(url, [pkg])

      Clone a package directly from the git URL url. The package does not need to be registered in Pkg.dir("METADATA"). The package repo is cloned by the name pkg if provided; if not provided, pkg is determined automatically from url.

      source
      Base.Pkg.setprotocol!Function.
      setprotocol!(proto)

      Set the protocol used to access GitHub-hosted packages. Defaults to 'https', with a blank proto delegating the choice to the package developer.

      source
      Base.Pkg.availableFunction.
      available() -> Vector{String}

      Returns the names of available packages.

      source
      available(pkg) -> Vector{VersionNumber}

      Returns the version numbers available for package pkg.

      source
      Base.Pkg.installedFunction.
      installed() -> Dict{String,VersionNumber}

      Returns a dictionary mapping installed package names to the installed version number of each package.

      source
      installed(pkg) -> Void | VersionNumber

      If pkg is installed, return the installed version number. If pkg is registered, but not installed, return nothing.

      source
      Base.Pkg.statusFunction.
      status()

      Prints out a summary of what packages are installed and what version and state they're in.

      source
      status(pkg)

      Prints out a summary of what version and state pkg, specifically, is in.

      source
      Base.Pkg.updateFunction.
      update(pkgs...)

      Update the metadata repo – kept in Pkg.dir("METADATA") – then update any fixed packages that can safely be pulled from their origin; then call Pkg.resolve() to determine a new optimal set of packages versions.

      Without arguments, updates all installed packages. When one or more package names are provided as arguments, only those packages and their dependencies are updated.

      source
      Base.Pkg.checkoutFunction.
      checkout(pkg, [branch="master"]; merge=true, pull=true)

      Checkout the Pkg.dir(pkg) repo to the branch branch. Defaults to checking out the "master" branch. To go back to using the newest compatible released version, use Pkg.free(pkg). Changes are merged (fast-forward only) if the keyword argument merge == true, and the latest version is pulled from the upstream repo if pull == true.

      source
      Base.Pkg.pinFunction.
      pin(pkg)

      Pin pkg at the current version. To go back to using the newest compatible released version, use Pkg.free(pkg)

      source
      pin(pkg, version)

      Pin pkg at registered version version.

      source
      Base.Pkg.freeFunction.
      free(pkg)

      Free the package pkg to be managed by the package manager again. It calls Pkg.resolve() to determine optimal package versions after. This is an inverse for both Pkg.checkout and Pkg.pin.

      You can also supply an iterable collection of package names, e.g., Pkg.free(("Pkg1", "Pkg2")) to free multiple packages at once.

      source
      Base.Pkg.buildFunction.
      build()

      Run the build scripts for all installed packages in depth-first recursive order.

      source
      build(pkgs...)

      Run the build script in deps/build.jl for each package in pkgs and all of their dependencies in depth-first recursive order. This is called automatically by Pkg.resolve() on all installed or updated packages.

      source
      Base.Pkg.testFunction.
      test(; coverage=false)

      Run the tests for all installed packages ensuring that each package's test dependencies are installed for the duration of the test. A package is tested by running its test/runtests.jl file and test dependencies are specified in test/REQUIRE. Coverage statistics for the packages may be generated by passing coverage=true. The default behavior is not to run coverage.

      source
      test(pkgs...; coverage=false)

      Run the tests for each package in pkgs ensuring that each package's test dependencies are installed for the duration of the test. A package is tested by running its test/runtests.jl file and test dependencies are specified in test/REQUIRE. Coverage statistics for the packages may be generated by passing coverage=true. The default behavior is not to run coverage.

      source
      Base.Pkg.dependentsFunction.
      dependents(pkg)

      List the packages that have pkg as a dependency.

      source
      diff --git a/julia-0.6.3/share/doc/julia/html/en/stdlib/profile.html b/julia-0.6.3/share/doc/julia/html/en/stdlib/profile.html deleted file mode 100644 index f59173d..0000000 --- a/julia-0.6.3/share/doc/julia/html/en/stdlib/profile.html +++ /dev/null @@ -1,9 +0,0 @@ - -Profiling · The Julia Language

      Profiling

      Profiling

      @profile

      @profile <expression> runs your expression while taking periodic backtraces. These are appended to an internal buffer of backtraces.

      source

      The methods in Base.Profile are not exported and need to be called e.g. as Profile.print().

      Base.Profile.clearFunction.
      clear()

      Clear any existing backtraces from the internal buffer.

      source
      Base.Profile.printFunction.
      print([io::IO = STDOUT,] [data::Vector]; kwargs...)

      Prints profiling results to io (by default, STDOUT). If you do not supply a data vector, the internal buffer of accumulated backtraces will be used.

      The keyword arguments can be any combination of:

      • format – Determines whether backtraces are printed with (default, :tree) or without (:flat) indentation indicating tree structure.

      • C – If true, backtraces from C and Fortran code are shown (normally they are excluded).

      • combine – If true (default), instruction pointers are merged that correspond to the same line of code.

      • maxdepth – Limits the depth higher than maxdepth in the :tree format.

      • sortedby – Controls the order in :flat format. :filefuncline (default) sorts by the source line, whereas :count sorts in order of number of collected samples.

      • noisefloor – Limits frames that exceed the heuristic noise floor of the sample (only applies to format :tree). A suggested value to try for this is 2.0 (the default is 0). This parameter hides samples for which n <= noisefloor * √N, where n is the number of samples on this line, and N is the number of samples for the callee.

      • mincount – Limits the printout to only those lines with at least mincount occurrences.

      source
      print([io::IO = STDOUT,] data::Vector, lidict::LineInfoDict; kwargs...)

      Prints profiling results to io. This variant is used to examine results exported by a previous call to retrieve. Supply the vector data of backtraces and a dictionary lidict of line information.

      See Profile.print([io], data) for an explanation of the valid keyword arguments.

      source
      Base.Profile.initFunction.
      init(; n::Integer, delay::Float64)

      Configure the delay between backtraces (measured in seconds), and the number n of instruction pointers that may be stored. Each instruction pointer corresponds to a single line of code; backtraces generally consist of a long list of instruction pointers. Default settings can be obtained by calling this function with no arguments, and each can be set independently using keywords or in the order (n, delay).

      source
      Base.Profile.fetchFunction.
      fetch() -> data

      Returns a reference to the internal buffer of backtraces. Note that subsequent operations, like clear, can affect data unless you first make a copy. Note that the values in data have meaning only on this machine in the current session, because it depends on the exact memory addresses used in JIT-compiling. This function is primarily for internal use; retrieve may be a better choice for most users.

      source
      Base.Profile.retrieveFunction.
      retrieve() -> data, lidict

      "Exports" profiling results in a portable format, returning the set of all backtraces (data) and a dictionary that maps the (session-specific) instruction pointers in data to LineInfo values that store the file name, function name, and line number. This function allows you to save profiling results for future analysis.

      source
      Base.Profile.callersFunction.
      callers(funcname, [data, lidict], [filename=<filename>], [linerange=<start:stop>]) -> Vector{Tuple{count, lineinfo}}

      Given a previous profiling run, determine who called a particular function. Supplying the filename (and optionally, range of line numbers over which the function is defined) allows you to disambiguate an overloaded method. The returned value is a vector containing a count of the number of calls and line information about the caller. One can optionally supply backtrace data obtained from retrieve; otherwise, the current internal profile buffer is used.

      source
      clear_malloc_data()

      Clears any stored memory allocation data when running julia with --track-allocation. Execute the command(s) you want to test (to force JIT-compilation), then call clear_malloc_data. Then execute your command(s) again, quit Julia, and examine the resulting *.mem files.

      source
      diff --git a/julia-0.6.3/share/doc/julia/html/en/stdlib/punctuation.html b/julia-0.6.3/share/doc/julia/html/en/stdlib/punctuation.html deleted file mode 100644 index 5801b37..0000000 --- a/julia-0.6.3/share/doc/julia/html/en/stdlib/punctuation.html +++ /dev/null @@ -1,9 +0,0 @@ - -Punctuation · The Julia Language

      Punctuation

      Punctuation

      Extended documentation for mathematical symbols & functions is here.

      symbolmeaning
      @minvoke macro m; followed by space-separated expressions
      !prefix "not" operator
      a!( )at the end of a function name, ! indicates that a function modifies its argument(s)
      #begin single line comment
      #=begin multi-line comment (these are nestable)
      =#end multi-line comment
      $string and expression interpolation
      %remainder operator
      ^exponent operator
      &bitwise and
      &&short-circuiting boolean and
      |bitwise or
      ||short-circuiting boolean or
      bitwise xor operator
      *multiply, or matrix multiply
      ()the empty tuple
      ~bitwise not operator
      \backslash operator
      'complex transpose operator Aᴴ
      a[]array indexing
      [,]vertical concatenation
      [;]also vertical concatenation
      [   ]with space-separated expressions, horizontal concatenation
      T{ }parametric type instantiation
      ;statement separator
      ,separate function arguments or tuple components
      ?3-argument conditional operator (conditional ? if_true : if_false)
      ""delimit string literals
      ''delimit character literals
      ` `delimit external process (command) specifications
      ...splice arguments into a function call or declare a varargs function or type
      .access named fields in objects/modules, also prefixes elementwise operator/function calls
      a:brange a, a+1, a+2, ..., b
      a:s:brange a, a+s, a+2s, ..., b
      :index an entire dimension (1:end)
      ::type annotation, depending on context
      :( )quoted expression
      :asymbol a
      <:subtype operator
      >:supertype operator (reverse of subtype operator)
      ===egal comparison operator
      diff --git a/julia-0.6.3/share/doc/julia/html/en/stdlib/simd-types.html b/julia-0.6.3/share/doc/julia/html/en/stdlib/simd-types.html deleted file mode 100644 index 3547508..0000000 --- a/julia-0.6.3/share/doc/julia/html/en/stdlib/simd-types.html +++ /dev/null @@ -1,22 +0,0 @@ - -SIMD Support · The Julia Language

      SIMD Support

      SIMD Support

      Type VecElement{T} is intended for building libraries of SIMD operations. Practical use of it requires using llvmcall. The type is defined as:

      struct VecElement{T}
      -    value::T
      -end

      It has a special compilation rule: a homogeneous tuple of VecElement{T} maps to an LLVM vector type when T is a primitive bits type and the tuple length is in the set {2-6,8-10,16}.

      At -O3, the compiler might automatically vectorize operations on such tuples. For example, the following program, when compiled with julia -O3 generates two SIMD addition instructions (addps) on x86 systems:

      const m128 = NTuple{4,VecElement{Float32}}
      -
      -function add(a::m128, b::m128)
      -    (VecElement(a[1].value+b[1].value),
      -     VecElement(a[2].value+b[2].value),
      -     VecElement(a[3].value+b[3].value),
      -     VecElement(a[4].value+b[4].value))
      -end
      -
      -triple(c::m128) = add(add(c,c),c)
      -
      -code_native(triple,(m128,))

      However, since the automatic vectorization cannot be relied upon, future use will mostly be via libraries that use llvmcall.

      diff --git a/julia-0.6.3/share/doc/julia/html/en/stdlib/sort.html b/julia-0.6.3/share/doc/julia/html/en/stdlib/sort.html deleted file mode 100644 index 9429054..0000000 --- a/julia-0.6.3/share/doc/julia/html/en/stdlib/sort.html +++ /dev/null @@ -1,250 +0,0 @@ - -Sorting and Related Functions · The Julia Language

      Sorting and Related Functions

      Sorting and Related Functions

      Julia has an extensive, flexible API for sorting and interacting with already-sorted arrays of values. By default, Julia picks reasonable algorithms and sorts in standard ascending order:

      julia> sort([2,3,1])
      -3-element Array{Int64,1}:
      - 1
      - 2
      - 3

      You can easily sort in reverse order as well:

      julia> sort([2,3,1], rev=true)
      -3-element Array{Int64,1}:
      - 3
      - 2
      - 1

      To sort an array in-place, use the "bang" version of the sort function:

      julia> a = [2,3,1];
      -
      -julia> sort!(a);
      -
      -julia> a
      -3-element Array{Int64,1}:
      - 1
      - 2
      - 3

      Instead of directly sorting an array, you can compute a permutation of the array's indices that puts the array into sorted order:

      julia> v = randn(5)
      -5-element Array{Float64,1}:
      -  0.297288
      -  0.382396
      - -0.597634
      - -0.0104452
      - -0.839027
      -
      -julia> p = sortperm(v)
      -5-element Array{Int64,1}:
      - 5
      - 3
      - 4
      - 1
      - 2
      -
      -julia> v[p]
      -5-element Array{Float64,1}:
      - -0.839027
      - -0.597634
      - -0.0104452
      -  0.297288
      -  0.382396

      Arrays can easily be sorted according to an arbitrary transformation of their values:

      julia> sort(v, by=abs)
      -5-element Array{Float64,1}:
      - -0.0104452
      -  0.297288
      -  0.382396
      - -0.597634
      - -0.839027

      Or in reverse order by a transformation:

      julia> sort(v, by=abs, rev=true)
      -5-element Array{Float64,1}:
      - -0.839027
      - -0.597634
      -  0.382396
      -  0.297288
      - -0.0104452

      If needed, the sorting algorithm can be chosen:

      julia> sort(v, alg=InsertionSort)
      -5-element Array{Float64,1}:
      - -0.839027
      - -0.597634
      - -0.0104452
      -  0.297288
      -  0.382396

      All the sorting and order related functions rely on a "less than" relation defining a total order on the values to be manipulated. The isless function is invoked by default, but the relation can be specified via the lt keyword.

      Sorting Functions

      Base.sort!Function.
      sort!(v; alg::Algorithm=defalg(v), lt=isless, by=identity, rev::Bool=false, order::Ordering=Forward)

      Sort the vector v in place. QuickSort is used by default for numeric arrays while MergeSort is used for other arrays. You can specify an algorithm to use via the alg keyword (see Sorting Algorithms for available algorithms). The by keyword lets you provide a function that will be applied to each element before comparison; the lt keyword allows providing a custom "less than" function; use rev=true to reverse the sorting order. These options are independent and can be used together in all possible combinations: if both by and lt are specified, the lt function is applied to the result of the by function; rev=true reverses whatever ordering specified via the by and lt keywords.

      Examples

      julia> v = [3, 1, 2]; sort!(v); v
      -3-element Array{Int64,1}:
      - 1
      - 2
      - 3
      -
      -julia> v = [3, 1, 2]; sort!(v, rev = true); v
      -3-element Array{Int64,1}:
      - 3
      - 2
      - 1
      -
      -julia> v = [(1, "c"), (3, "a"), (2, "b")]; sort!(v, by = x -> x[1]); v
      -3-element Array{Tuple{Int64,String},1}:
      - (1, "c")
      - (2, "b")
      - (3, "a")
      -
      -julia> v = [(1, "c"), (3, "a"), (2, "b")]; sort!(v, by = x -> x[2]); v
      -3-element Array{Tuple{Int64,String},1}:
      - (3, "a")
      - (2, "b")
      - (1, "c")
      source
      Base.sortFunction.
      sort(v; alg::Algorithm=defalg(v), lt=isless, by=identity, rev::Bool=false, order::Ordering=Forward)

      Variant of sort! that returns a sorted copy of v leaving v itself unmodified.

      Examples

      julia> v = [3, 1, 2];
      -
      -julia> sort(v)
      -3-element Array{Int64,1}:
      - 1
      - 2
      - 3
      -
      -julia> v
      -3-element Array{Int64,1}:
      - 3
      - 1
      - 2
      source
      sort(A, dim::Integer; alg::Algorithm=DEFAULT_UNSTABLE, lt=isless, by=identity, rev::Bool=false, order::Ordering=Forward, initialized::Bool=false)

      Sort a multidimensional array A along the given dimension. See sort! for a description of possible keyword arguments.

      Examples

      julia> A = [4 3; 1 2]
      -2×2 Array{Int64,2}:
      - 4  3
      - 1  2
      -
      -julia> sort(A, 1)
      -2×2 Array{Int64,2}:
      - 1  2
      - 4  3
      -
      -julia> sort(A, 2)
      -2×2 Array{Int64,2}:
      - 3  4
      - 1  2
      source
      Base.sortpermFunction.
      sortperm(v; alg::Algorithm=DEFAULT_UNSTABLE, lt=isless, by=identity, rev::Bool=false, order::Ordering=Forward)

      Return a permutation vector of indices of v that puts it in sorted order. Specify alg to choose a particular sorting algorithm (see Sorting Algorithms). MergeSort is used by default, and since it is stable, the resulting permutation will be the lexicographically first one that puts the input array into sorted order – i.e. indices of equal elements appear in ascending order. If you choose a non-stable sorting algorithm such as QuickSort, a different permutation that puts the array into order may be returned. The order is specified using the same keywords as sort!.

      See also sortperm!.

      Examples

      julia> v = [3, 1, 2];
      -
      -julia> p = sortperm(v)
      -3-element Array{Int64,1}:
      - 2
      - 3
      - 1
      -
      -julia> v[p]
      -3-element Array{Int64,1}:
      - 1
      - 2
      - 3
      source
      Base.Sort.sortperm!Function.
      sortperm!(ix, v; alg::Algorithm=DEFAULT_UNSTABLE, lt=isless, by=identity, rev::Bool=false, order::Ordering=Forward, initialized::Bool=false)

      Like sortperm, but accepts a preallocated index vector ix. If initialized is false (the default), ix is initialized to contain the values 1:length(v).

      Examples

      julia> v = [3, 1, 2]; p = zeros(Int, 3);
      -
      -julia> sortperm!(p, v); p
      -3-element Array{Int64,1}:
      - 2
      - 3
      - 1
      -
      -julia> v[p]
      -3-element Array{Int64,1}:
      - 1
      - 2
      - 3
      source
      Base.Sort.sortrowsFunction.
      sortrows(A; alg::Algorithm=DEFAULT_UNSTABLE, lt=isless, by=identity, rev::Bool=false, order::Ordering=Forward)

      Sort the rows of matrix A lexicographically. See sort! for a description of possible keyword arguments.

      Examples

      julia> sortrows([7 3 5; -1 6 4; 9 -2 8])
      -3×3 Array{Int64,2}:
      - -1   6  4
      -  7   3  5
      -  9  -2  8
      -
      -julia> sortrows([7 3 5; -1 6 4; 9 -2 8], lt=(x,y)->isless(x[2],y[2]))
      -3×3 Array{Int64,2}:
      -  9  -2  8
      -  7   3  5
      - -1   6  4
      -
      -julia> sortrows([7 3 5; -1 6 4; 9 -2 8], rev=true)
      -3×3 Array{Int64,2}:
      -  9  -2  8
      -  7   3  5
      - -1   6  4
      source
      Base.Sort.sortcolsFunction.
      sortcols(A; alg::Algorithm=DEFAULT_UNSTABLE, lt=isless, by=identity, rev::Bool=false, order::Ordering=Forward)

      Sort the columns of matrix A lexicographically. See sort! for a description of possible keyword arguments.

      Examples

      julia> sortcols([7 3 5; 6 -1 -4; 9 -2 8])
      -3×3 Array{Int64,2}:
      -  3   5  7
      - -1  -4  6
      - -2   8  9
      -
      -julia> sortcols([7 3 5; 6 -1 -4; 9 -2 8], alg=InsertionSort, lt=(x,y)->isless(x[2],y[2]))
      -3×3 Array{Int64,2}:
      -  5   3  7
      - -4  -1  6
      -  8  -2  9
      -
      -julia> sortcols([7 3 5; 6 -1 -4; 9 -2 8], rev=true)
      -3×3 Array{Int64,2}:
      - 7   5   3
      - 6  -4  -1
      - 9   8  -2
      source

      Order-Related Functions

      Base.issortedFunction.
      issorted(v, lt=isless, by=identity, rev:Bool=false, order::Ordering=Forward)

      Test whether a vector is in sorted order. The lt, by and rev keywords modify what order is considered to be sorted just as they do for sort.

      Examples

      julia> issorted([1, 2, 3])
      -true
      -
      -julia> issorted([(1, "b"), (2, "a")], by = x -> x[1])
      -true
      -
      -julia> issorted([(1, "b"), (2, "a")], by = x -> x[2])
      -false
      -
      -julia> issorted([(1, "b"), (2, "a")], by = x -> x[2], rev=true)
      -true
      source
      searchsorted(a, x, [by=<transform>,] [lt=<comparison>,] [rev=false])

      Returns the range of indices of a which compare as equal to x (using binary search) according to the order specified by the by, lt and rev keywords, assuming that a is already sorted in that order. Returns an empty range located at the insertion point if a does not contain values equal to x.

      Examples

      julia> a = [4, 3, 2, 1]
      -4-element Array{Int64,1}:
      - 4
      - 3
      - 2
      - 1
      -
      -julia> searchsorted(a, 4)
      -5:4
      -
      -julia> searchsorted(a, 4, rev=true)
      -1:1
      source
      searchsortedfirst(a, x, [by=<transform>,] [lt=<comparison>,] [rev=false])

      Returns the index of the first value in a greater than or equal to x, according to the specified order. Returns length(a)+1 if x is greater than all values in a. a is assumed to be sorted.

      Examples

      julia> searchsortedfirst([1, 2, 4, 5, 14], 4)
      -3
      -
      -julia> searchsortedfirst([1, 2, 4, 5, 14], 4, rev=true)
      -1
      -
      -julia> searchsortedfirst([1, 2, 4, 5, 14], 15)
      -6
      source
      searchsortedlast(a, x, [by=<transform>,] [lt=<comparison>,] [rev=false])

      Returns the index of the last value in a less than or equal to x, according to the specified order. Returns 0 if x is less than all values in a. a is assumed to be sorted.

      Examples

      julia> searchsortedlast([1, 2, 4, 5, 14], 4)
      -3
      -
      -julia> searchsortedlast([1, 2, 4, 5, 14], 4, rev=true)
      -5
      -
      -julia> searchsortedlast([1, 2, 4, 5, 14], -1)
      -0
      source
      Base.Sort.select!Function.
      select!(v, k, [by=<transform>,] [lt=<comparison>,] [rev=false])

      Partially sort the vector v in place, according to the order specified by by, lt and rev so that the value at index k (or range of adjacent values if k is a range) occurs at the position where it would appear if the array were fully sorted via a non-stable algorithm. If k is a single index, that value is returned; if k is a range, an array of values at those indices is returned. Note that select! does not fully sort the input array.

      Examples

      julia> a = [1, 2, 4, 3, 4]
      -5-element Array{Int64,1}:
      - 1
      - 2
      - 4
      - 3
      - 4
      -
      -julia> select!(a, 4)
      -4
      -
      -julia> a
      -5-element Array{Int64,1}:
      - 1
      - 2
      - 3
      - 4
      - 4
      -
      -julia> a = [1, 2, 4, 3, 4]
      -5-element Array{Int64,1}:
      - 1
      - 2
      - 4
      - 3
      - 4
      -
      -julia> select!(a, 4, rev=true)
      -2
      -
      -julia> a
      -5-element Array{Int64,1}:
      - 4
      - 4
      - 3
      - 2
      - 1
      source
      Base.Sort.selectFunction.
      select(v, k, [by=<transform>,] [lt=<comparison>,] [rev=false])

      Variant of select! which copies v before partially sorting it, thereby returning the same thing as select! but leaving v unmodified.

      source
      Base.Sort.selectpermFunction.
      selectperm(v, k, [alg=<algorithm>,] [by=<transform>,] [lt=<comparison>,] [rev=false])

      Return a partial permutation of the vector v, according to the order specified by by, lt and rev, so that v[output] returns the first k (or range of adjacent values if k is a range) values of a fully sorted version of v. If k is a single index (Integer), an array of the first k indices is returned; if k is a range, an array of those indices is returned. Note that the handling of integer values for k is different from select in that it returns a vector of k elements instead of just the k th element. Also note that this is equivalent to, but more efficient than, calling sortperm(...)[k].

      source
      Base.Sort.selectperm!Function.
      selectperm!(ix, v, k, [alg=<algorithm>,] [by=<transform>,] [lt=<comparison>,] [rev=false,] [initialized=false])

      Like selectperm, but accepts a preallocated index vector ix. If initialized is false (the default), ix is initialized to contain the values 1:length(ix).

      source

      Sorting Algorithms

      There are currently four sorting algorithms available in base Julia:

      • InsertionSort

      • QuickSort

      • PartialQuickSort(k)

      • MergeSort

      InsertionSort is an O(n^2) stable sorting algorithm. It is efficient for very small n, and is used internally by QuickSort.

      QuickSort is an O(n log n) sorting algorithm which is in-place, very fast, but not stable – i.e. elements which are considered equal will not remain in the same order in which they originally appeared in the array to be sorted. QuickSort is the default algorithm for numeric values, including integers and floats.

      PartialQuickSort(k) is similar to QuickSort, but the output array is only sorted up to index k if k is an integer, or in the range of k if k is an OrdinalRange. For example:

      x = rand(1:500, 100)
      -k = 50
      -k2 = 50:100
      -s = sort(x; alg=QuickSort)
      -ps = sort(x; alg=PartialQuickSort(k))
      -qs = sort(x; alg=PartialQuickSort(k2))
      -map(issorted, (s, ps, qs))             # => (true, false, false)
      -map(x->issorted(x[1:k]), (s, ps, qs))  # => (true, true, false)
      -map(x->issorted(x[k2]), (s, ps, qs))   # => (true, false, true)
      -s[1:k] == ps[1:k]                      # => true
      -s[k2] == qs[k2]                        # => true

      MergeSort is an O(n log n) stable sorting algorithm but is not in-place – it requires a temporary array of half the size of the input array – and is typically not quite as fast as QuickSort. It is the default algorithm for non-numeric data.

      The default sorting algorithms are chosen on the basis that they are fast and stable, or appear to be so. For numeric types indeed, QuickSort is selected as it is faster and indistinguishable in this case from a stable sort (unless the array records its mutations in some way). The stability property comes at a non-negligible cost, so if you don't need it, you may want to explicitly specify your preferred algorithm, e.g. sort!(v, alg=QuickSort).

      The mechanism by which Julia picks default sorting algorithms is implemented via the Base.Sort.defalg function. It allows a particular algorithm to be registered as the default in all sorting functions for specific arrays. For example, here are the two default methods from sort.jl:

      defalg(v::AbstractArray) = MergeSort
      -defalg{T<:Number}(v::AbstractArray{T}) = QuickSort

      As for numeric arrays, choosing a non-stable default algorithm for array types for which the notion of a stable sort is meaningless (i.e. when two values comparing equal can not be distinguished) may make sense.

      diff --git a/julia-0.6.3/share/doc/julia/html/en/stdlib/stacktraces.html b/julia-0.6.3/share/doc/julia/html/en/stdlib/stacktraces.html deleted file mode 100644 index 2a1e2bf..0000000 --- a/julia-0.6.3/share/doc/julia/html/en/stdlib/stacktraces.html +++ /dev/null @@ -1,9 +0,0 @@ - -StackTraces · The Julia Language

      StackTraces

      StackTraces

      StackFrame

      Stack information representing execution context, with the following fields:

      • func::Symbol

        The name of the function containing the execution context.

      • linfo::Nullable{Core.MethodInstance}

        The MethodInstance containing the execution context (if it could be found).

      • file::Symbol

        The path to the file containing the execution context.

      • line::Int

        The line number in the file containing the execution context.

      • from_c::Bool

        True if the code is from C.

      • inlined::Bool

        True if the code is from an inlined frame.

      • pointer::UInt64

        Representation of the pointer to the execution context as returned by backtrace.

      source
      StackTrace

      An alias for Vector{StackFrame} provided for convenience; returned by calls to stacktrace and catch_stacktrace.

      source
      stacktrace([trace::Vector{Ptr{Void}},] [c_funcs::Bool=false]) -> StackTrace

      Returns a stack trace in the form of a vector of StackFrames. (By default stacktrace doesn't return C functions, but this can be enabled.) When called without specifying a trace, stacktrace first calls backtrace.

      source
      catch_stacktrace([c_funcs::Bool=false]) -> StackTrace

      Returns the stack trace for the most recent error thrown, rather than the current execution context.

      source

      The following methods and types in Base.StackTraces are not exported and need to be called e.g. as StackTraces.lookup(ptr).

      lookup(pointer::Union{Ptr{Void}, UInt}) -> Vector{StackFrame}

      Given a pointer to an execution context (usually generated by a call to backtrace), looks up stack frame context information. Returns an array of frame information for all functions inlined at that point, innermost function first.

      source
      remove_frames!(stack::StackTrace, name::Symbol)

      Takes a StackTrace (a vector of StackFrames) and a function name (a Symbol) and removes the StackFrame specified by the function name from the StackTrace (also removing all frames above the specified function). Primarily used to remove StackTraces functions from the StackTrace prior to returning it.

      source
      remove_frames!(stack::StackTrace, m::Module)

      Returns the StackTrace with all StackFrames from the provided Module removed.

      source
      diff --git a/julia-0.6.3/share/doc/julia/html/en/stdlib/strings.html b/julia-0.6.3/share/doc/julia/html/en/stdlib/strings.html deleted file mode 100644 index 625e371..0000000 --- a/julia-0.6.3/share/doc/julia/html/en/stdlib/strings.html +++ /dev/null @@ -1,132 +0,0 @@ - -Strings · The Julia Language

      Strings

      Strings

      Base.lengthMethod.
      length(s::AbstractString)

      The number of characters in string s.

      Example

      julia> length("jμΛIα")
      -5
      source
      Base.sizeofMethod.
      sizeof(s::AbstractString)

      The number of bytes in string s.

      Example

      julia> sizeof("❤")
      -3
      source
      Base.:*Method.
      *(x, y...)

      Multiplication operator. x*y*z*... calls this function with all arguments, i.e. *(x, y, z, ...).

      source
      Base.:^Method.
      ^(s::AbstractString, n::Integer)

      Repeat n times the string s. The repeat function is an alias to this operator.

      julia> "Test "^3
      -"Test Test Test "
      source
      Base.stringFunction.
      string(xs...)

      Create a string from any values using the print function.

      julia> string("a", 1, true)
      -"a1true"
      source
      Base.reprFunction.
      repr(x)

      Create a string from any value using the showall function.

      source
      Core.StringMethod.
      String(s::AbstractString)

      Convert a string to a contiguous byte array representation encoded as UTF-8 bytes. This representation is often appropriate for passing strings to C.

      source
      Base.transcodeFunction.
      transcode(T, src)

      Convert string data between Unicode encodings. src is either a String or a Vector{UIntXX} of UTF-XX code units, where XX is 8, 16, or 32. T indicates the encoding of the return value: String to return a (UTF-8 encoded) String or UIntXX to return a Vector{UIntXX} of UTF-XX data. (The alias Cwchar_t can also be used as the integer type, for converting wchar_t* strings used by external C libraries.)

      The transcode function succeeds as long as the input data can be reasonably represented in the target encoding; it always succeeds for conversions between UTF-XX encodings, even for invalid Unicode data.

      Only conversion to/from UTF-8 is currently supported.

      source
      Base.unsafe_stringFunction.
      unsafe_string(p::Ptr{UInt8}, [length::Integer])

      Copy a string from the address of a C-style (NUL-terminated) string encoded as UTF-8. (The pointer can be safely freed afterwards.) If length is specified (the length of the data in bytes), the string does not have to be NUL-terminated.

      This function is labelled "unsafe" because it will crash if p is not a valid memory address to data of the requested length.

      source
      Base.codeunitMethod.
      codeunit(s::AbstractString, i::Integer)

      Get the ith code unit of an encoded string. For example, returns the ith byte of the representation of a UTF-8 string.

      source
      Base.asciiFunction.
      ascii(s::AbstractString)

      Convert a string to String type and check that it contains only ASCII data, otherwise throwing an ArgumentError indicating the position of the first non-ASCII byte.

      julia> ascii("abcdeγfgh")
      -ERROR: ArgumentError: invalid ASCII at index 6 in "abcdeγfgh"
      -Stacktrace:
      - [1] ascii(::String) at ./strings/util.jl:479
      -
      -julia> ascii("abcdefgh")
      -"abcdefgh"
      source
      Base.@r_strMacro.
      @r_str -> Regex

      Construct a regex, such as r"^[a-z]*$". The regex also accepts one or more flags, listed after the ending quote, to change its behaviour:

      • i enables case-insensitive matching

      • m treats the ^ and $ tokens as matching the start and end of individual lines, as opposed to the whole string.

      • s allows the . modifier to match newlines.

      • x enables "comment mode": whitespace is enabled except when escaped with \, and # is treated as starting a comment.

      For example, this regex has all three flags enabled:

      julia> match(r"a+.*b+.*?d$"ism, "Goodbye,\nOh, angry,\nBad world\n")
      -RegexMatch("angry,\nBad world")
      source
      @html_str -> Docs.HTML

      Create an HTML object from a literal string.

      source
      @text_str -> Docs.Text

      Create a Text object from a literal string.

      source
      normalize_string(s::AbstractString, normalform::Symbol)

      Normalize the string s according to one of the four "normal forms" of the Unicode standard: normalform can be :NFC, :NFD, :NFKC, or :NFKD. Normal forms C (canonical composition) and D (canonical decomposition) convert different visually identical representations of the same abstract string into a single canonical form, with form C being more compact. Normal forms KC and KD additionally canonicalize "compatibility equivalents": they convert characters that are abstractly similar but visually distinct into a single canonical choice (e.g. they expand ligatures into the individual characters), with form KC being more compact.

      Alternatively, finer control and additional transformations may be be obtained by calling normalize_string(s; keywords...), where any number of the following boolean keywords options (which all default to false except for compose) are specified:

      • compose=false: do not perform canonical composition

      • decompose=true: do canonical decomposition instead of canonical composition (compose=true is ignored if present)

      • compat=true: compatibility equivalents are canonicalized

      • casefold=true: perform Unicode case folding, e.g. for case-insensitive string comparison

      • newline2lf=true, newline2ls=true, or newline2ps=true: convert various newline sequences (LF, CRLF, CR, NEL) into a linefeed (LF), line-separation (LS), or paragraph-separation (PS) character, respectively

      • stripmark=true: strip diacritical marks (e.g. accents)

      • stripignore=true: strip Unicode's "default ignorable" characters (e.g. the soft hyphen or the left-to-right marker)

      • stripcc=true: strip control characters; horizontal tabs and form feeds are converted to spaces; newlines are also converted to spaces unless a newline-conversion flag was specified

      • rejectna=true: throw an error if unassigned code points are found

      • stable=true: enforce Unicode Versioning Stability

      For example, NFKC corresponds to the options compose=true, compat=true, stable=true.

      source
      graphemes(s::AbstractString) -> GraphemeIterator

      Returns an iterator over substrings of s that correspond to the extended graphemes in the string, as defined by Unicode UAX #29. (Roughly, these are what users would perceive as single characters, even though they may contain more than one codepoint; for example a letter combined with an accent mark is a single grapheme.)

      source
      Base.isvalidMethod.
      isvalid(value) -> Bool

      Returns true if the given value is valid for its type, which currently can be either Char or String.

      source
      Base.isvalidMethod.
      isvalid(T, value) -> Bool

      Returns true if the given value is valid for that type. Types currently can be either Char or String. Values for Char can be of type Char or UInt32. Values for String can be of that type, or Vector{UInt8}.

      source
      Base.isvalidMethod.
      isvalid(str::AbstractString, i::Integer)

      Tells whether index i is valid for the given string.

      Examples

      julia> str = "αβγdef";
      -
      -julia> isvalid(str, 1)
      -true
      -
      -julia> str[1]
      -'α': Unicode U+03b1 (category Ll: Letter, lowercase)
      -
      -julia> isvalid(str, 2)
      -false
      -
      -julia> str[2]
      -ERROR: UnicodeError: invalid character index
      -[...]
      source
      is_assigned_char(c) -> Bool

      Returns true if the given char or integer is an assigned Unicode code point.

      source
      Base.ismatchFunction.
      ismatch(r::Regex, s::AbstractString) -> Bool

      Test whether a string contains a match of the given regular expression.

      source
      Base.matchFunction.
      match(r::Regex, s::AbstractString[, idx::Integer[, addopts]])

      Search for the first match of the regular expression r in s and return a RegexMatch object containing the match, or nothing if the match failed. The matching substring can be retrieved by accessing m.match and the captured sequences can be retrieved by accessing m.captures The optional idx argument specifies an index at which to start the search.

      source
      Base.eachmatchFunction.
      eachmatch(r::Regex, s::AbstractString[, overlap::Bool=false])

      Search for all matches of a the regular expression r in s and return a iterator over the matches. If overlap is true, the matching sequences are allowed to overlap indices in the original string, otherwise they must be from distinct character ranges.

      source
      Base.matchallFunction.
      matchall(r::Regex, s::AbstractString[, overlap::Bool=false]) -> Vector{AbstractString}

      Return a vector of the matching substrings from eachmatch.

      source
      Base.lpadFunction.
      lpad(s, n::Integer, p::AbstractString=" ")

      Make a string at least n columns wide when printed by padding s on the left with copies of p.

      julia> lpad("March",10)
      -"     March"
      source
      Base.rpadFunction.
      rpad(s, n::Integer, p::AbstractString=" ")

      Make a string at least n columns wide when printed by padding s on the right with copies of p.

      julia> rpad("March",20)
      -"March               "
      source
      Base.searchFunction.
      search(string::AbstractString, chars::Chars, [start::Integer])

      Search for the first occurrence of the given characters within the given string. The second argument may be a single character, a vector or a set of characters, a string, or a regular expression (though regular expressions are only allowed on contiguous strings, such as ASCII or UTF-8 strings). The third argument optionally specifies a starting index. The return value is a range of indexes where the matching sequence is found, such that s[search(s,x)] == x:

      search(string, "substring") = start:end such that string[start:end] == "substring", or 0:-1 if unmatched.

      search(string, 'c') = index such that string[index] == 'c', or 0 if unmatched.

      julia> search("Hello to the world", "z")
      -0:-1
      -
      -julia> search("JuliaLang","Julia")
      -1:5
      source
      Base.rsearchFunction.
      rsearch(s::AbstractString, chars::Chars, [start::Integer])

      Similar to search, but returning the last occurrence of the given characters within the given string, searching in reverse from start.

      julia> rsearch("aaabbb","b")
      -6:6
      source
      Base.searchindexFunction.
      searchindex(s::AbstractString, substring, [start::Integer])

      Similar to search, but return only the start index at which the substring is found, or 0 if it is not.

      julia> searchindex("Hello to the world", "z")
      -0
      -
      -julia> searchindex("JuliaLang","Julia")
      -1
      -
      -julia> searchindex("JuliaLang","Lang")
      -6
      source
      Base.rsearchindexFunction.
      rsearchindex(s::AbstractString, substring, [start::Integer])

      Similar to rsearch, but return only the start index at which the substring is found, or 0 if it is not.

      julia> rsearchindex("aaabbb","b")
      -6
      -
      -julia> rsearchindex("aaabbb","a")
      -3
      source
      Base.containsMethod.
      contains(haystack::AbstractString, needle::AbstractString)

      Determine whether the second argument is a substring of the first.

      julia> contains("JuliaLang is pretty cool!", "Julia")
      -true
      source
      Base.reverseMethod.
      reverse(s::AbstractString) -> AbstractString

      Reverses a string.

      julia> reverse("JuliaLang")
      -"gnaLailuJ"
      source
      Base.replaceFunction.
      replace(string::AbstractString, pat, r[, n::Integer=0])

      Search for the given pattern pat, and replace each occurrence with r. If n is provided, replace at most n occurrences. As with search, the second argument may be a single character, a vector or a set of characters, a string, or a regular expression. If r is a function, each occurrence is replaced with r(s) where s is the matched substring. If pat is a regular expression and r is a SubstitutionString, then capture group references in r are replaced with the corresponding matched text.

      source
      Base.splitFunction.
      split(s::AbstractString, [chars]; limit::Integer=0, keep::Bool=true)

      Return an array of substrings by splitting the given string on occurrences of the given character delimiters, which may be specified in any of the formats allowed by search's second argument (i.e. a single character, collection of characters, string, or regular expression). If chars is omitted, it defaults to the set of all space characters, and keep is taken to be false. The two keyword arguments are optional: they are a maximum size for the result and a flag determining whether empty fields should be kept in the result.

      julia> a = "Ma.rch"
      -"Ma.rch"
      -
      -julia> split(a,".")
      -2-element Array{SubString{String},1}:
      - "Ma"
      - "rch"
      source
      Base.rsplitFunction.
      rsplit(s::AbstractString, [chars]; limit::Integer=0, keep::Bool=true)

      Similar to split, but starting from the end of the string.

      julia> a = "M.a.r.c.h"
      -"M.a.r.c.h"
      -
      -julia> rsplit(a,".")
      -5-element Array{SubString{String},1}:
      - "M"
      - "a"
      - "r"
      - "c"
      - "h"
      -
      -julia> rsplit(a,".";limit=1)
      -1-element Array{SubString{String},1}:
      - "M.a.r.c.h"
      -
      -julia> rsplit(a,".";limit=2)
      -2-element Array{SubString{String},1}:
      - "M.a.r.c"
      - "h"
      source
      Base.stripFunction.
      strip(s::AbstractString, [chars::Chars])

      Return s with any leading and trailing whitespace removed. If chars (a character, or vector or set of characters) is provided, instead remove characters contained in it.

      julia> strip("{3, 5}\n", ['{', '}', '\n'])
      -"3, 5"
      source
      Base.lstripFunction.
      lstrip(s::AbstractString[, chars::Chars])

      Return s with any leading whitespace and delimiters removed. The default delimiters to remove are ' ', \t, \n, \v, \f, and \r. If chars (a character, or vector or set of characters) is provided, instead remove characters contained in it.

      julia> a = lpad("March", 20)
      -"               March"
      -
      -julia> lstrip(a)
      -"March"
      source
      Base.rstripFunction.
      rstrip(s::AbstractString[, chars::Chars])

      Return s with any trailing whitespace and delimiters removed. The default delimiters to remove are ' ', \t, \n, \v, \f, and \r. If chars (a character, or vector or set of characters) is provided, instead remove characters contained in it.

      julia> a = rpad("March", 20)
      -"March               "
      -
      -julia> rstrip(a)
      -"March"
      source
      Base.startswithFunction.
      startswith(s::AbstractString, prefix::AbstractString)

      Returns true if s starts with prefix. If prefix is a vector or set of characters, tests whether the first character of s belongs to that set.

      See also endswith.

      julia> startswith("JuliaLang", "Julia")
      -true
      source
      Base.endswithFunction.
      endswith(s::AbstractString, suffix::AbstractString)

      Returns true if s ends with suffix. If suffix is a vector or set of characters, tests whether the last character of s belongs to that set.

      See also startswith.

      julia> endswith("Sunday", "day")
      -true
      source
      Base.uppercaseFunction.
      uppercase(s::AbstractString)

      Returns s with all characters converted to uppercase.

      Example

      julia> uppercase("Julia")
      -"JULIA"
      source
      Base.lowercaseFunction.
      lowercase(s::AbstractString)

      Returns s with all characters converted to lowercase.

      Example

      julia> lowercase("STRINGS AND THINGS")
      -"strings and things"
      source
      Base.titlecaseFunction.
      titlecase(s::AbstractString)

      Capitalizes the first character of each word in s.

      Example

      julia> titlecase("the julia programming language")
      -"The Julia Programming Language"
      source
      Base.ucfirstFunction.
      ucfirst(s::AbstractString)

      Returns string with the first character converted to uppercase.

      Example

      julia> ucfirst("python")
      -"Python"
      source
      Base.lcfirstFunction.
      lcfirst(s::AbstractString)

      Returns string with the first character converted to lowercase.

      Example

      julia> lcfirst("Julia")
      -"julia"
      source
      Base.joinFunction.
      join(io::IO, strings, delim, [last])

      Join an array of strings into a single string, inserting the given delimiter between adjacent strings. If last is given, it will be used instead of delim between the last two strings. For example,

      julia> join(["apples", "bananas", "pineapples"], ", ", " and ")
      -"apples, bananas and pineapples"

      strings can be any iterable over elements x which are convertible to strings via print(io::IOBuffer, x). strings will be printed to io.

      source
      Base.chopFunction.
      chop(s::AbstractString)

      Remove the last character from s.

      julia> a = "March"
      -"March"
      -
      -julia> chop(a)
      -"Marc"
      source
      Base.chompFunction.
      chomp(s::AbstractString)

      Remove a single trailing newline from a string.

      julia> chomp("Hello\n")
      -"Hello"
      source
      Base.ind2chrFunction.
      ind2chr(s::AbstractString, i::Integer)

      Convert a byte index i to a character index with respect to string s.

      See also chr2ind.

      Example

      julia> str = "αβγdef";
      -
      -julia> ind2chr(str, 3)
      -2
      -
      -julia> chr2ind(str, 2)
      -3
      source
      Base.chr2indFunction.
      chr2ind(s::AbstractString, i::Integer)

      Convert a character index i to a byte index.

      See also ind2chr.

      Example

      julia> str = "αβγdef";
      -
      -julia> chr2ind(str, 2)
      -3
      -
      -julia> ind2chr(str, 3)
      -2
      source
      Base.nextindFunction.
      nextind(str::AbstractString, i::Integer)

      Get the next valid string index after i. Returns a value greater than endof(str) at or after the end of the string.

      Examples

      julia> str = "αβγdef";
      -
      -julia> nextind(str, 1)
      -3
      -
      -julia> endof(str)
      -9
      -
      -julia> nextind(str, 9)
      -10
      source
      Base.previndFunction.
      prevind(str::AbstractString, i::Integer)

      Get the previous valid string index before i. Returns a value less than 1 at the beginning of the string.

      Examples

      julia> prevind("αβγdef", 3)
      -1
      -
      -julia> prevind("αβγdef", 1)
      -0
      source
      randstring([rng,] len=8)

      Create a random ASCII string of length len, consisting of upper- and lower-case letters and the digits 0-9. The optional rng argument specifies a random number generator, see Random Numbers.

      Example

      julia> rng = MersenneTwister(1234);
      -
      -julia> randstring(rng, 4)
      -"mbDd"
      source
      charwidth(c)

      Gives the number of columns needed to print a character.

      source
      Base.strwidthFunction.
      strwidth(s::AbstractString)

      Gives the number of columns needed to print a string.

      Example

      julia> strwidth("March")
      -5
      source
      Base.UTF8proc.isalnumFunction.
      isalnum(c::Char) -> Bool

      Tests whether a character is alphanumeric. A character is classified as alphabetic if it belongs to the Unicode general category Letter or Number, i.e. a character whose category code begins with 'L' or 'N'.

      source
      Base.UTF8proc.isalphaFunction.
      isalpha(c::Char) -> Bool

      Tests whether a character is alphabetic. A character is classified as alphabetic if it belongs to the Unicode general category Letter, i.e. a character whose category code begins with 'L'.

      source
      Base.isasciiFunction.
      isascii(c::Union{Char,AbstractString}) -> Bool

      Tests whether a character belongs to the ASCII character set, or whether this is true for all elements of a string.

      source
      Base.UTF8proc.iscntrlFunction.
      iscntrl(c::Char) -> Bool

      Tests whether a character is a control character. Control characters are the non-printing characters of the Latin-1 subset of Unicode.

      source
      Base.UTF8proc.isdigitFunction.
      isdigit(c::Char) -> Bool

      Tests whether a character is a numeric digit (0-9).

      source
      Base.UTF8proc.isgraphFunction.
      isgraph(c::Char) -> Bool

      Tests whether a character is printable, and not a space. Any character that would cause a printer to use ink should be classified with isgraph(c)==true.

      source
      Base.UTF8proc.islowerFunction.
      islower(c::Char) -> Bool

      Tests whether a character is a lowercase letter. A character is classified as lowercase if it belongs to Unicode category Ll, Letter: Lowercase.

      source
      isnumber(c::Char) -> Bool

      Tests whether a character is numeric. A character is classified as numeric if it belongs to the Unicode general category Number, i.e. a character whose category code begins with 'N'.

      source
      Base.UTF8proc.isprintFunction.
      isprint(c::Char) -> Bool

      Tests whether a character is printable, including spaces, but not a control character.

      source
      Base.UTF8proc.ispunctFunction.
      ispunct(c::Char) -> Bool

      Tests whether a character belongs to the Unicode general category Punctuation, i.e. a character whose category code begins with 'P'.

      source
      Base.UTF8proc.isspaceFunction.
      isspace(c::Char) -> Bool

      Tests whether a character is any whitespace character. Includes ASCII characters '\t', '\n', '\v', '\f', '\r', and ' ', Latin-1 character U+0085, and characters in Unicode category Zs.

      source
      Base.UTF8proc.isupperFunction.
      isupper(c::Char) -> Bool

      Tests whether a character is an uppercase letter. A character is classified as uppercase if it belongs to Unicode category Lu, Letter: Uppercase, or Lt, Letter: Titlecase.

      source
      Base.isxdigitFunction.
      isxdigit(c::Char) -> Bool

      Tests whether a character is a valid hexadecimal digit. Note that this does not include x (as in the standard 0x prefix).

      Example

      julia> isxdigit('a')
      -true
      -
      -julia> isxdigit('x')
      -false
      source
      Core.SymbolType.
      Symbol(x...) -> Symbol

      Create a Symbol by concatenating the string representations of the arguments together.

      source
      Base.escape_stringFunction.
      escape_string([io,] str::AbstractString[, esc::AbstractString]) -> AbstractString

      General escaping of traditional C and Unicode escape sequences. Any characters in esc are also escaped (with a backslash). See also unescape_string.

      source
      Base.unescape_stringFunction.
      unescape_string([io,] s::AbstractString) -> AbstractString

      General unescaping of traditional C and Unicode escape sequences. Reverse of escape_string.

      source
      diff --git a/julia-0.6.3/share/doc/julia/html/en/stdlib/test.html b/julia-0.6.3/share/doc/julia/html/en/stdlib/test.html deleted file mode 100644 index d7614ea..0000000 --- a/julia-0.6.3/share/doc/julia/html/en/stdlib/test.html +++ /dev/null @@ -1,140 +0,0 @@ - -Unit Testing · The Julia Language

      Unit Testing

      Unit Testing

      Testing Base Julia

      Julia is under rapid development and has an extensive test suite to verify functionality across multiple platforms. If you build Julia from source, you can run this test suite with make test. In a binary install, you can run the test suite using Base.runtests().

      Base.runtestsFunction.
      runtests([tests=["all"] [, numcores=ceil(Int, Sys.CPU_CORES / 2) ]])

      Run the Julia unit tests listed in tests, which can be either a string or an array of strings, using numcores processors. (not exported)

      source

      Basic Unit Tests

      The Base.Test module provides simple unit testing functionality. Unit testing is a way to see if your code is correct by checking that the results are what you expect. It can be helpful to ensure your code still works after you make changes, and can be used when developing as a way of specifying the behaviors your code should have when complete.

      Simple unit testing can be performed with the @test() and @test_throws() macros:

      Base.Test.@testMacro.
      @test ex
      -@test f(args...) key=val ...

      Tests that the expression ex evaluates to true. Returns a Pass Result if it does, a Fail Result if it is false, and an Error Result if it could not be evaluated.

      The @test f(args...) key=val... form is equivalent to writing @test f(args..., key=val...) which can be useful when the expression is a call using infix syntax such as approximate comparisons:

      @test a ≈ b atol=ε

      This is equivalent to the uglier test @test ≈(a, b, atol=ε). It is an error to supply more than one expression unless the first is a call expression and the rest are assignments (k=v).

      source
      @test_throws extype ex

      Tests that the expression ex throws an exception of type extype. Note that @test_throws does not support a trailing keyword form.

      source

      For example, suppose we want to check our new function foo(x) works as expected:

      julia> using Base.Test
      -
      -julia> foo(x) = length(x)^2
      -foo (generic function with 1 method)

      If the condition is true, a Pass is returned:

      julia> @test foo("bar") == 9
      -Test Passed
      -
      -julia> @test foo("fizz") >= 10
      -Test Passed

      If the condition is false, then a Fail is returned and an exception is thrown:

      julia> @test foo("f") == 20
      -Test Failed
      -  Expression: foo("f") == 20
      -   Evaluated: 1 == 20
      -ERROR: There was an error during testing

      If the condition could not be evaluated because an exception was thrown, which occurs in this case because length() is not defined for symbols, an Error object is returned and an exception is thrown:

      julia> @test foo(:cat) == 1
      -Error During Test
      -  Test threw an exception of type MethodError
      -  Expression: foo(:cat) == 1
      -  MethodError: no method matching length(::Symbol)
      -  Closest candidates are:
      -    length(::SimpleVector) at essentials.jl:256
      -    length(::Base.MethodList) at reflection.jl:521
      -    length(::MethodTable) at reflection.jl:597
      -    ...
      -  Stacktrace:
      -   [...]
      -ERROR: There was an error during testing

      If we expect that evaluating an expression should throw an exception, then we can use @test_throws() to check that this occurs:

      julia> @test_throws MethodError foo(:cat)
      -Test Passed
      -      Thrown: MethodError

      Working with Test Sets

      Typically a large number of tests are used to make sure functions work correctly over a range of inputs. In the event a test fails, the default behavior is to throw an exception immediately. However, it is normally preferable to run the rest of the tests first to get a better picture of how many errors there are in the code being tested.

      The @testset() macro can be used to group tests into sets. All the tests in a test set will be run, and at the end of the test set a summary will be printed. If any of the tests failed, or could not be evaluated due to an error, the test set will then throw a TestSetException.

      @testset [CustomTestSet] [option=val  ...] ["description"] begin ... end
      -@testset [CustomTestSet] [option=val  ...] ["description $v"] for v in (...) ... end
      -@testset [CustomTestSet] [option=val  ...] ["description $v, $w"] for v in (...), w in (...) ... end

      Starts a new test set, or multiple test sets if a for loop is provided.

      If no custom testset type is given it defaults to creating a DefaultTestSet. DefaultTestSet records all the results and, if there are any Fails or Errors, throws an exception at the end of the top-level (non-nested) test set, along with a summary of the test results.

      Any custom testset type (subtype of AbstractTestSet) can be given and it will also be used for any nested @testset invocations. The given options are only applied to the test set where they are given. The default test set type does not take any options.

      The description string accepts interpolation from the loop indices. If no description is provided, one is constructed based on the variables.

      By default the @testset macro will return the testset object itself, though this behavior can be customized in other testset types. If a for loop is used then the macro collects and returns a list of the return values of the finish method, which by default will return a list of the testset objects used in each iteration.

      source

      We can put our tests for the foo(x) function in a test set:

      julia> @testset "Foo Tests" begin
      -           @test foo("a")   == 1
      -           @test foo("ab")  == 4
      -           @test foo("abc") == 9
      -       end;
      -Test Summary: | Pass  Total
      -Foo Tests     |    3      3

      Test sets can also be nested:

      julia> @testset "Foo Tests" begin
      -           @testset "Animals" begin
      -               @test foo("cat") == 9
      -               @test foo("dog") == foo("cat")
      -           end
      -           @testset "Arrays $i" for i in 1:3
      -               @test foo(zeros(i)) == i^2
      -               @test foo(ones(i)) == i^2
      -           end
      -       end;
      -Test Summary: | Pass  Total
      -Foo Tests     |    8      8

      In the event that a nested test set has no failures, as happened here, it will be hidden in the summary. If we do have a test failure, only the details for the failed test sets will be shown:

      julia> @testset "Foo Tests" begin
      -           @testset "Animals" begin
      -               @testset "Felines" begin
      -                   @test foo("cat") == 9
      -               end
      -               @testset "Canines" begin
      -                   @test foo("dog") == 9
      -               end
      -           end
      -           @testset "Arrays" begin
      -               @test foo(zeros(2)) == 4
      -               @test foo(ones(4)) == 15
      -           end
      -       end
      -
      -Arrays: Test Failed
      -  Expression: foo(ones(4)) == 15
      -   Evaluated: 16 == 15
      -Stacktrace:
      -    [...]
      -Test Summary: | Pass  Fail  Total
      -Foo Tests     |    3     1      4
      -  Animals     |    2            2
      -  Arrays      |    1     1      2
      -ERROR: Some tests did not pass: 3 passed, 1 failed, 0 errored, 0 broken.

      Other Test Macros

      As calculations on floating-point values can be imprecise, you can perform approximate equality checks using either @test a ≈ b (where , typed via tab completion of \approx, is the isapprox() function) or use isapprox() directly.

      julia> @test 1 ≈ 0.999999999
      -Test Passed
      -
      -julia> @test 1 ≈ 0.999999
      -Test Failed
      -  Expression: 1 ≈ 0.999999
      -   Evaluated: 1 ≈ 0.999999
      -ERROR: There was an error during testing
      @inferred f(x)

      Tests that the call expression f(x) returns a value of the same type inferred by the compiler. It is useful to check for type stability.

      f(x) can be any call expression. Returns the result of f(x) if the types match, and an Error Result if it finds different types.

      julia> using Base.Test
      -
      -julia> f(a,b,c) = b > 1 ? 1 : 1.0
      -f (generic function with 1 method)
      -
      -julia> typeof(f(1,2,3))
      -Int64
      -
      -julia> @code_warntype f(1,2,3)
      -Variables:
      -  #self# <optimized out>
      -  a <optimized out>
      -  b::Int64
      -  c <optimized out>
      -
      -Body:
      -  begin
      -      unless (Base.slt_int)(1, b::Int64)::Bool goto 3
      -      return 1
      -      3:
      -      return 1.0
      -  end::UNION{FLOAT64, INT64}
      -
      -julia> @inferred f(1,2,3)
      -ERROR: return type Int64 does not match inferred return type Union{Float64, Int64}
      -Stacktrace:
      - [1] error(::String) at ./error.jl:21
      -
      -julia> @inferred max(1,2)
      -2
      source
      @test_warn msg expr

      Test whether evaluating expr results in STDERR output that contains the msg string or matches the msg regular expression. If msg is a boolean function, tests whether msg(output) returns true. If msg is a tuple or array, checks that the error output contains/matches each item in msg. Returns the result of evaluating expr.

      See also @test_nowarn to check for the absence of error output.

      source
      @test_nowarn expr

      Test whether evaluating expr results in empty STDERR output (no warnings or other messages). Returns the result of evaluating expr.

      source

      Broken Tests

      If a test fails consistently it can be changed to use the @test_broken() macro. This will denote the test as Broken if the test continues to fail and alerts the user via an Error if the test succeeds.

      @test_broken ex
      -@test_broken f(args...) key=val ...

      Indicates a test that should pass but currently consistently fails. Tests that the expression ex evaluates to false or causes an exception. Returns a Broken Result if it does, or an Error Result if the expression evaluates to true.

      The @test_broken f(args...) key=val... form works as for the @test macro.

      source

      @test_skip() is also available to skip a test without evaluation, but counting the skipped test in the test set reporting. The test will not run but gives a Broken Result.

      @test_skip ex
      -@test_skip f(args...) key=val ...

      Marks a test that should not be executed but should be included in test summary reporting as Broken. This can be useful for tests that intermittently fail, or tests of not-yet-implemented functionality.

      The @test_skip f(args...) key=val... form works as for the @test macro.

      source

      Creating Custom AbstractTestSet Types

      Packages can create their own AbstractTestSet subtypes by implementing the record and finish methods. The subtype should have a one-argument constructor taking a description string, with any options passed in as keyword arguments.

      Base.Test.recordFunction.
      record(ts::AbstractTestSet, res::Result)

      Record a result to a testset. This function is called by the @testset infrastructure each time a contained @test macro completes, and is given the test result (which could be an Error). This will also be called with an Error if an exception is thrown inside the test block but outside of a @test context.

      source
      Base.Test.finishFunction.
      finish(ts::AbstractTestSet)

      Do any final processing necessary for the given testset. This is called by the @testset infrastructure after a test block executes. One common use for this function is to record the testset to the parent's results list, using get_testset.

      source

      Base.Test takes responsibility for maintaining a stack of nested testsets as they are executed, but any result accumulation is the responsibility of the AbstractTestSet subtype. You can access this stack with the get_testset and get_testset_depth methods. Note that these functions are not exported.

      Base.Test.get_testsetFunction.
      get_testset()

      Retrieve the active test set from the task's local storage. If no test set is active, use the fallback default test set.

      source
      get_testset_depth()

      Returns the number of active test sets, not including the defaut test set

      source

      Base.Test also makes sure that nested @testset invocations use the same AbstractTestSet subtype as their parent unless it is set explicitly. It does not propagate any properties of the testset. Option inheritance behavior can be implemented by packages using the stack infrastructure that Base.Test provides.

      Defining a basic AbstractTestSet subtype might look like:

      import Base.Test: record, finish
      -using Base.Test: AbstractTestSet, Result, Pass, Fail, Error
      -using Base.Test: get_testset_depth, get_testset
      -struct CustomTestSet <: Base.Test.AbstractTestSet
      -    description::AbstractString
      -    foo::Int
      -    results::Vector
      -    # constructor takes a description string and options keyword arguments
      -    CustomTestSet(desc; foo=1) = new(desc, foo, [])
      -end
      -
      -record(ts::CustomTestSet, child::AbstractTestSet) = push!(ts.results, child)
      -record(ts::CustomTestSet, res::Result) = push!(ts.results, res)
      -function finish(ts::CustomTestSet)
      -    # just record if we're not the top-level parent
      -    if get_testset_depth() > 0
      -        record(get_testset(), ts)
      -    end
      -    ts
      -end

      And using that testset looks like:

      @testset CustomTestSet foo=4 "custom testset inner 2" begin
      -    # this testset should inherit the type, but not the argument.
      -    @testset "custom testset inner" begin
      -        @test true
      -    end
      -end
      diff --git a/julia-0.6.3/share/icons/hicolor/scalable/apps/julia.svg b/julia-0.6.3/share/icons/hicolor/scalable/apps/julia.svg deleted file mode 100644 index b0b03de..0000000 --- a/julia-0.6.3/share/icons/hicolor/scalable/apps/julia.svg +++ /dev/null @@ -1,62 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/julia-0.6.3/share/julia/base/.gitignore b/julia-0.6.3/share/julia/base/.gitignore deleted file mode 100644 index 463d2f0..0000000 --- a/julia-0.6.3/share/julia/base/.gitignore +++ /dev/null @@ -1,8 +0,0 @@ -/pcre_h.jl -/errno_h.jl -/build_h.jl -/file_constants.jl -/uv_constants.jl -/version_git.jl -/version_git.jl.phony -/userimg.jl diff --git a/julia-0.6.3/share/julia/base/Enums.jl b/julia-0.6.3/share/julia/base/Enums.jl deleted file mode 100644 index 7519b5a..0000000 --- a/julia-0.6.3/share/julia/base/Enums.jl +++ /dev/null @@ -1,157 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -module Enums - -import Core.Intrinsics.bitcast -export Enum, @enum - -function basetype end - -abstract type Enum{T<:Integer} end - -Base.convert{T<:Integer}(::Type{Integer}, x::Enum{T}) = bitcast(T, x) -Base.convert{T<:Integer,T2<:Integer}(::Type{T}, x::Enum{T2}) = convert(T, bitcast(T2, x)) -Base.write{T<:Integer}(io::IO, x::Enum{T}) = write(io, T(x)) -Base.read{T<:Enum}(io::IO, ::Type{T}) = T(read(io, Enums.basetype(T))) - -# generate code to test whether expr is in the given set of values -function membershiptest(expr, values) - lo, hi = extrema(values) - if length(values) == hi - lo + 1 - :($lo <= $expr <= $hi) - elseif length(values) < 20 - foldl((x1,x2)->:($x1 || ($expr == $x2)), :($expr == $(values[1])), values[2:end]) - else - :($expr in $(Set(values))) - end -end - -@noinline enum_argument_error(typename, x) = throw(ArgumentError(string("invalid value for Enum $(typename): $x"))) - -""" - @enum EnumName[::BaseType] value1[=x] value2[=y] - -Create an `Enum{BaseType}` subtype with name `EnumName` and enum member values of -`value1` and `value2` with optional assigned values of `x` and `y`, respectively. -`EnumName` can be used just like other types and enum member values as regular values, such as - -```jldoctest -julia> @enum Fruit apple=1 orange=2 kiwi=3 - -julia> f(x::Fruit) = "I'm a Fruit with value: \$(Int(x))" -f (generic function with 1 method) - -julia> f(apple) -"I'm a Fruit with value: 1" -``` - -`BaseType`, which defaults to [`Int32`](@ref), must be a primitive subtype of `Integer`. -Member values can be converted between the enum type and `BaseType`. `read` and `write` -perform these conversions automatically. -""" -macro enum(T,syms...) - if isempty(syms) - throw(ArgumentError("no arguments given for Enum $T")) - end - basetype = Int32 - typename = T - if isa(T,Expr) && T.head == :(::) && length(T.args) == 2 && isa(T.args[1], Symbol) - typename = T.args[1] - basetype = eval(current_module(),T.args[2]) - if !isa(basetype, DataType) || !(basetype <: Integer) || !isbits(basetype) - throw(ArgumentError("invalid base type for Enum $typename, $T=::$basetype; base type must be an integer primitive type")) - end - elseif !isa(T,Symbol) - throw(ArgumentError("invalid type expression for enum $T")) - end - vals = Vector{Tuple{Symbol,Integer}}(0) - lo = hi = 0 - i = zero(basetype) - hasexpr = false - for s in syms - if isa(s,Symbol) - if i == typemin(basetype) && !isempty(vals) - throw(ArgumentError("overflow in value \"$s\" of Enum $typename")) - end - elseif isa(s,Expr) && - (s.head == :(=) || s.head == :kw) && - length(s.args) == 2 && isa(s.args[1],Symbol) - i = eval(current_module(),s.args[2]) # allow exprs, e.g. uint128"1" - if !isa(i, Integer) - throw(ArgumentError("invalid value for Enum $typename, $s=$i; values must be integers")) - end - i = convert(basetype, i) - s = s.args[1] - hasexpr = true - else - throw(ArgumentError(string("invalid argument for Enum ", typename, ": ", s))) - end - if !Base.isidentifier(s) - throw(ArgumentError("invalid name for Enum $typename; \"$s\" is not a valid identifier.")) - end - push!(vals, (s,i)) - if length(vals) == 1 - lo = hi = i - else - lo = min(lo, i) - hi = max(hi, i) - end - i += oneunit(i) - end - values = basetype[i[2] for i in vals] - if hasexpr && values != unique(values) - throw(ArgumentError("values for Enum $typename are not unique")) - end - blk = quote - # enum definition - Base.@__doc__(primitive type $(esc(typename)) <: Enum{$(basetype)} $(sizeof(basetype) * 8) end) - function Base.convert(::Type{$(esc(typename))}, x::Integer) - $(membershiptest(:x, values)) || enum_argument_error($(Expr(:quote, typename)), x) - return bitcast($(esc(typename)), convert($(basetype), x)) - end - Enums.basetype(::Type{$(esc(typename))}) = $(esc(basetype)) - Base.typemin(x::Type{$(esc(typename))}) = $(esc(typename))($lo) - Base.typemax(x::Type{$(esc(typename))}) = $(esc(typename))($hi) - Base.isless(x::$(esc(typename)), y::$(esc(typename))) = isless($basetype(x), $basetype(y)) - let insts = ntuple(i->$(esc(typename))($values[i]), $(length(vals))) - Base.instances(::Type{$(esc(typename))}) = insts - end - function Base.print(io::IO, x::$(esc(typename))) - for (sym, i) in $vals - if i == $(basetype)(x) - print(io, sym); break - end - end - end - function Base.show(io::IO, x::$(esc(typename))) - if get(io, :compact, false) - print(io, x) - else - print(io, x, "::") - showcompact(io, typeof(x)) - print(io, " = ", $basetype(x)) - end - end - function Base.show(io::IO, t::Type{$(esc(typename))}) - Base.show_datatype(io, t) - end - function Base.show(io::IO, ::MIME"text/plain", t::Type{$(esc(typename))}) - print(io, "Enum ") - Base.show_datatype(io, t) - print(io, ":") - for (sym, i) in $vals - print(io, "\n", sym, " = ", i) - end - end - end - if isa(typename,Symbol) - for (sym,i) in vals - push!(blk.args, :(const $(esc(sym)) = $(esc(typename))($i))) - end - end - push!(blk.args, :nothing) - blk.head = :toplevel - return blk -end - -end # module diff --git a/julia-0.6.3/share/julia/base/LineEdit.jl b/julia-0.6.3/share/julia/base/LineEdit.jl deleted file mode 100644 index 9909082..0000000 --- a/julia-0.6.3/share/julia/base/LineEdit.jl +++ /dev/null @@ -1,1644 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -module LineEdit - -using ..Terminals - -import ..Terminals: raw!, width, height, cmove, getX, - getY, clear_line, beep - -import Base: ensureroom, peek, show, AnyDict - -abstract type TextInterface end -abstract type ModeState end - -export run_interface, Prompt, ModalInterface, transition, reset_state, edit_insert, keymap - -struct ModalInterface <: TextInterface - modes -end - -mutable struct MIState - interface::ModalInterface - current_mode - aborted::Bool - mode_state - kill_buffer::String - previous_key::Array{Char,1} - key_repeats::Int -end -MIState(i, c, a, m) = MIState(i, c, a, m, "", Char[], 0) - -function show(io::IO, s::MIState) - print(io, "MI State (", s.current_mode, " active)") -end - -mutable struct Prompt <: TextInterface - prompt - # A string or function to be printed before the prompt. May not change the length of the prompt. - # This may be used for changing the color, issuing other terminal escape codes, etc. - prompt_prefix - # Same as prefix except after the prompt - prompt_suffix - keymap_dict - keymap_func_data - complete - on_enter - on_done - hist - sticky::Bool -end - -show(io::IO, x::Prompt) = show(io, string("Prompt(\"", x.prompt, "\",...)")) - -struct InputAreaState - num_rows::Int64 - curs_row::Int64 -end - -mutable struct PromptState <: ModeState - terminal - p::Prompt - input_buffer::IOBuffer - ias::InputAreaState - indent::Int -end - -input_string(s::PromptState) = String(s.input_buffer) - -input_string_newlines(s::PromptState) = count(c->(c == '\n'), input_string(s)) -function input_string_newlines_aftercursor(s::PromptState) - str = input_string(s) - isempty(str) && return 0 - rest = str[nextind(str, position(s.input_buffer)):end] - return count(c->(c == '\n'), rest) -end - -abstract type HistoryProvider end -abstract type CompletionProvider end - -mutable struct EmptyCompletionProvider <: CompletionProvider -end - -mutable struct EmptyHistoryProvider <: HistoryProvider -end - -reset_state(::EmptyHistoryProvider) = nothing - -complete_line(c::EmptyCompletionProvider, s) = [], true, true - -terminal(s::IO) = s -terminal(s::PromptState) = s.terminal - -for f in [:terminal, :edit_insert, :on_enter, :add_history, :buffer, :edit_backspace, :(Base.isempty), - :replace_line, :refresh_multi_line, :input_string, :edit_move_left, :edit_move_right, - :edit_move_word_left, :edit_move_word_right, :update_display_buffer] - @eval ($f)(s::MIState, args...) = $(f)(s.mode_state[s.current_mode], args...) -end - -function common_prefix(completions) - ret = "" - c1 = completions[1] - isempty(c1) && return ret - i = 1 - cc, nexti = next(c1, i) - while true - for c in completions - (i > endof(c) || c[i] != cc) && return ret - end - ret = string(ret, cc) - i >= endof(c1) && return ret - i = nexti - cc, nexti = next(c1, i) - end -end - -# Show available completions -function show_completions(s::PromptState, completions) - colmax = maximum(map(length, completions)) - num_cols = max(div(width(terminal(s)), colmax+2), 1) - entries_per_col, r = divrem(length(completions), num_cols) - entries_per_col += r != 0 - # skip any lines of input after the cursor - cmove_down(terminal(s), input_string_newlines_aftercursor(s)) - println(terminal(s)) - for row = 1:entries_per_col - for col = 0:num_cols - idx = row + col*entries_per_col - if idx <= length(completions) - cmove_col(terminal(s), (colmax+2)*col) - print(terminal(s), completions[idx]) - end - end - println(terminal(s)) - end - # make space for the prompt - for i = 1:input_string_newlines(s) - println(terminal(s)) - end -end - -# Prompt Completions -complete_line(s::MIState) = complete_line(s.mode_state[s.current_mode], s.key_repeats) -function complete_line(s::PromptState, repeats) - completions, partial, should_complete = complete_line(s.p.complete, s) - if isempty(completions) - beep(terminal(s)) - elseif !should_complete - # should_complete is false for cases where we only want to show - # a list of possible completions but not complete, e.g. foo(\t - show_completions(s, completions) - elseif length(completions) == 1 - # Replace word by completion - prev_pos = position(s.input_buffer) - seek(s.input_buffer, prev_pos-sizeof(partial)) - edit_replace(s, position(s.input_buffer), prev_pos, completions[1]) - else - p = common_prefix(completions) - if !isempty(p) && p != partial - # All possible completions share the same prefix, so we might as - # well complete that - prev_pos = position(s.input_buffer) - seek(s.input_buffer, prev_pos-sizeof(partial)) - edit_replace(s, position(s.input_buffer), prev_pos, p) - elseif repeats > 0 - show_completions(s, completions) - end - end -end - -clear_input_area(terminal, s) = (_clear_input_area(terminal, s.ias); s.ias = InputAreaState(0, 0)) -clear_input_area(s) = clear_input_area(s.terminal, s) -function _clear_input_area(terminal, state::InputAreaState) - # Go to the last line - if state.curs_row < state.num_rows - cmove_down(terminal, state.num_rows - state.curs_row) - end - - # Clear lines one by one going up - for j = 2:state.num_rows - clear_line(terminal) - cmove_up(terminal) - end - - # Clear top line - clear_line(terminal) -end - -prompt_string(s::PromptState) = s.p.prompt -prompt_string(s::AbstractString) = s - -refresh_multi_line(s::ModeState) = refresh_multi_line(terminal(s), s) -refresh_multi_line(termbuf::TerminalBuffer, s::ModeState) = refresh_multi_line(termbuf, terminal(s), s) -refresh_multi_line(termbuf::TerminalBuffer, term, s::ModeState) = (@assert term == terminal(s); refresh_multi_line(termbuf,s)) -function refresh_multi_line(termbuf::TerminalBuffer, terminal::UnixTerminal, buf, state::InputAreaState, prompt = ""; indent = 0) - _clear_input_area(termbuf, state) - - cols = width(terminal) - curs_row = -1 # relative to prompt (1-based) - curs_pos = -1 # 1-based column position of the cursor - cur_row = 0 # count of the number of rows - buf_pos = position(buf) - line_pos = buf_pos - # Write out the prompt string - write_prompt(termbuf, prompt) - prompt = prompt_string(prompt) - # Count the '\n' at the end of the line if the terminal emulator does (specific to DOS cmd prompt) - miscountnl = @static is_windows() ? (isa(Terminals.pipe_reader(terminal), Base.TTY) && !Base.ispty(Terminals.pipe_reader(terminal))) : false - lindent = strwidth(prompt) - - # Now go through the buffer line by line - seek(buf, 0) - moreinput = true # add a blank line if there is a trailing newline on the last line - while moreinput - l = readline(buf, chomp=false) - moreinput = endswith(l, "\n") - # We need to deal with on-screen characters, so use strwidth to compute occupied columns - llength = strwidth(l) - slength = sizeof(l) - cur_row += 1 - cmove_col(termbuf, lindent + 1) - write(termbuf, l) - # We expect to be line after the last valid output line (due to - # the '\n' at the end of the previous line) - if curs_row == -1 - # in this case, we haven't yet written the cursor position - line_pos -= slength # '\n' gets an extra pos - if line_pos < 0 || !moreinput - num_chars = (line_pos >= 0 ? llength : strwidth(l[1:(line_pos + slength)])) - curs_row, curs_pos = divrem(lindent + num_chars - 1, cols) - curs_row += cur_row - curs_pos += 1 - # There's an issue if the cursor is after the very right end of the screen. In that case we need to - # move the cursor to the next line, and emit a newline if needed - if curs_pos == cols - # only emit the newline if the cursor is at the end of the line we're writing - if line_pos == 0 - write(termbuf, "\n") - cur_row += 1 - end - curs_row += 1 - curs_pos = 0 - cmove_col(termbuf, 1) - end - end - end - cur_row += div(max(lindent + llength + miscountnl - 1, 0), cols) - lindent = indent - end - seek(buf, buf_pos) - - # Let's move the cursor to the right position - # The line first - n = cur_row - curs_row - if n > 0 - cmove_up(termbuf, n) - end - - #columns are 1 based - cmove_col(termbuf, curs_pos + 1) - - # Updated cur_row,curs_row - return InputAreaState(cur_row, curs_row) -end - -function refresh_multi_line(terminal::UnixTerminal, args...; kwargs...) - outbuf = IOBuffer() - termbuf = TerminalBuffer(outbuf) - ret = refresh_multi_line(termbuf, terminal, args...;kwargs...) - # Output the entire refresh at once - write(terminal, take!(outbuf)) - flush(terminal) - return ret -end - - -# Edit functionality -is_non_word_char(c) = c in " \t\n\"\\'`@\$><=:;|&{}()[].,+-*/?%^~" - -function reset_key_repeats(f::Function, s::MIState) - key_repeats_sav = s.key_repeats - try - s.key_repeats = 0 - f() - finally - s.key_repeats = key_repeats_sav - end -end - -char_move_left(s::PromptState) = char_move_left(s.input_buffer) -function char_move_left(buf::IOBuffer) - while position(buf) > 0 - seek(buf, position(buf)-1) - c = peek(buf) - (((c & 0x80) == 0) || ((c & 0xc0) == 0xc0)) && break - end - pos = position(buf) - c = read(buf, Char) - seek(buf, pos) - c -end - -function edit_move_left(buf::IOBuffer) - if position(buf) > 0 - #move to the next base UTF8 character to the left - while true - c = char_move_left(buf) - if charwidth(c) != 0 || c == '\n' || position(buf) == 0 - break - end - end - return true - end - return false -end -edit_move_left(s::PromptState) = edit_move_left(s.input_buffer) && refresh_line(s) - -function edit_move_word_left(s) - if position(s.input_buffer) > 0 - char_move_word_left(s.input_buffer) - refresh_line(s) - end -end - -char_move_right(s) = char_move_right(buffer(s)) -function char_move_right(buf::IOBuffer) - !eof(buf) && read(buf, Char) -end - -function char_move_word_right(buf::IOBuffer, is_delimiter=is_non_word_char) - while !eof(buf) && is_delimiter(char_move_right(buf)) - end - while !eof(buf) - pos = position(buf) - if is_delimiter(char_move_right(buf)) - seek(buf, pos) - break - end - end -end - -function char_move_word_left(buf::IOBuffer, is_delimiter=is_non_word_char) - while position(buf) > 0 && is_delimiter(char_move_left(buf)) - end - while position(buf) > 0 - pos = position(buf) - if is_delimiter(char_move_left(buf)) - seek(buf, pos) - break - end - end -end - -char_move_word_right(s) = char_move_word_right(buffer(s)) -char_move_word_left(s) = char_move_word_left(buffer(s)) - -function edit_move_right(buf::IOBuffer) - if !eof(buf) - # move to the next base UTF8 character to the right - while true - c = char_move_right(buf) - eof(buf) && break - pos = position(buf) - nextc = read(buf,Char) - seek(buf,pos) - (charwidth(nextc) != 0 || nextc == '\n') && break - end - return true - end - return false -end -edit_move_right(s::PromptState) = edit_move_right(s.input_buffer) && refresh_line(s) - -function edit_move_word_right(s) - if !eof(s.input_buffer) - char_move_word_right(s) - refresh_line(s) - end -end - -## Move line up/down -# Querying the terminal is expensive, memory access is cheap -# so to find the current column, we find the offset for the start -# of the line. - -function edit_move_up(buf::IOBuffer) - npos = rsearch(buf.data, '\n', position(buf)) - npos == 0 && return false # we're in the first line - # We're interested in character count, not byte count - offset = length(String(buf.data[(npos+1):(position(buf))])) - npos2 = rsearch(buf.data, '\n', npos-1) - seek(buf, npos2) - for _ = 1:offset - pos = position(buf) - if read(buf, Char) == '\n' - seek(buf, pos) - break - end - end - return true -end -function edit_move_up(s) - changed = edit_move_up(buffer(s)) - changed && refresh_line(s) - changed -end - -function edit_move_down(buf::IOBuffer) - npos = rsearch(buf.data[1:buf.size], '\n', position(buf)) - # We're interested in character count, not byte count - offset = length(String(buf.data[(npos+1):(position(buf))])) - npos2 = search(buf.data[1:buf.size], '\n', position(buf)+1) - if npos2 == 0 #we're in the last line - return false - end - seek(buf, npos2) - for _ = 1:offset - pos = position(buf) - if eof(buf) || read(buf, Char) == '\n' - seek(buf, pos) - break - end - end - return true -end -function edit_move_down(s) - changed = edit_move_down(buffer(s)) - changed && refresh_line(s) - changed -end - -# splice! for IOBuffer: convert from 0-indexed positions, update the size, -# and keep the cursor position stable with the text -function splice_buffer!(buf::IOBuffer, r::UnitRange{<:Integer}, ins::AbstractString = "") - pos = position(buf) - if !isempty(r) && pos in r - seek(buf, first(r)) - elseif pos > last(r) - seek(buf, pos - length(r)) - end - splice!(buf.data, r + 1, Vector{UInt8}(ins)) # position(), etc, are 0-indexed - buf.size = buf.size + sizeof(ins) - length(r) - seek(buf, position(buf) + sizeof(ins)) -end - -function edit_replace(s, from, to, str) - splice_buffer!(buffer(s), from:to-1, str) -end - -function edit_insert(s::PromptState, c) - buf = s.input_buffer - function line_size() - p = position(buf) - seek(buf, rsearch(buf.data, '\n', p)) - ls = p - position(buf) - seek(buf, p) - return ls - end - str = string(c) - edit_insert(buf, str) - offset = s.ias.curs_row == 1 ? sizeof(s.p.prompt) : s.indent - if !('\n' in str) && eof(buf) && - ((line_size() + offset + sizeof(str) - 1) < width(terminal(s))) - # Avoid full update when appending characters to the end - # and an update of curs_row isn't necessary (conservatively estimated) - write(terminal(s), str) - else - refresh_line(s) - end -end - -function edit_insert(buf::IOBuffer, c) - if eof(buf) - return write(buf, c) - else - s = string(c) - splice_buffer!(buf, position(buf):position(buf)-1, s) - return sizeof(s) - end -end - -function edit_backspace(s::PromptState) - if edit_backspace(s.input_buffer) - refresh_line(s) - else - beep(terminal(s)) - end -end -function edit_backspace(buf::IOBuffer) - if position(buf) > 0 - oldpos = position(buf) - char_move_left(buf) - splice_buffer!(buf, position(buf):oldpos-1) - return true - else - return false - end -end - -edit_delete(s) = edit_delete(buffer(s)) ? refresh_line(s) : beep(terminal(s)) -function edit_delete(buf::IOBuffer) - eof(buf) && return false - oldpos = position(buf) - char_move_right(buf) - splice_buffer!(buf, oldpos:position(buf)-1) - true -end - -function edit_werase(buf::IOBuffer) - pos1 = position(buf) - char_move_word_left(buf, isspace) - pos0 = position(buf) - pos0 < pos1 || return false - splice_buffer!(buf, pos0:pos1-1) - true -end -function edit_werase(s) - edit_werase(buffer(s)) && refresh_line(s) -end - -function edit_delete_prev_word(buf::IOBuffer) - pos1 = position(buf) - char_move_word_left(buf) - pos0 = position(buf) - pos0 < pos1 || return false - splice_buffer!(buf, pos0:pos1-1) - true -end -function edit_delete_prev_word(s) - edit_delete_prev_word(buffer(s)) && refresh_line(s) -end - -function edit_delete_next_word(buf::IOBuffer) - pos0 = position(buf) - char_move_word_right(buf) - pos1 = position(buf) - pos0 < pos1 || return false - splice_buffer!(buf, pos0:pos1-1) - true -end -function edit_delete_next_word(s) - edit_delete_next_word(buffer(s)) && refresh_line(s) -end - -function edit_yank(s::MIState) - edit_insert(buffer(s), s.kill_buffer) - refresh_line(s) -end - -function edit_kill_line(s::MIState) - buf = buffer(s) - pos = position(buf) - killbuf = readline(buf, chomp=false) - if length(killbuf) > 1 && killbuf[end] == '\n' - killbuf = killbuf[1:end-1] - char_move_left(buf) - end - s.kill_buffer = s.key_repeats > 0 ? s.kill_buffer * killbuf : killbuf - - splice_buffer!(buf, pos:position(buf)-1) - refresh_line(s) -end - -edit_transpose(s) = edit_transpose(buffer(s)) && refresh_line(s) -function edit_transpose(buf::IOBuffer) - position(buf) == 0 && return false - eof(buf) && char_move_left(buf) - char_move_left(buf) - pos = position(buf) - a, b = read(buf, Char), read(buf, Char) - seek(buf, pos) - write(buf, b, a) - return true -end - -edit_clear(buf::IOBuffer) = truncate(buf, 0) - -function edit_clear(s::MIState) - edit_clear(buffer(s)) - refresh_line(s) -end - -function replace_line(s::PromptState, l::IOBuffer) - s.input_buffer = copy(l) -end - -function replace_line(s::PromptState, l) - s.input_buffer.ptr = 1 - s.input_buffer.size = 0 - write(s.input_buffer, l) -end - -history_prev(::EmptyHistoryProvider) = ("", false) -history_next(::EmptyHistoryProvider) = ("", false) -history_search(::EmptyHistoryProvider, args...) = false -add_history(::EmptyHistoryProvider, s) = nothing -add_history(s::PromptState) = add_history(mode(s).hist, s) -history_next_prefix(s, hist, prefix) = false -history_prev_prefix(s, hist, prefix) = false - -function history_prev(s, hist) - l, ok = history_prev(mode(s).hist) - if ok - replace_line(s, l) - move_input_start(s) - refresh_line(s) - else - beep(terminal(s)) - end -end -function history_next(s, hist) - l, ok = history_next(mode(s).hist) - if ok - replace_line(s, l) - move_input_end(s) - refresh_line(s) - else - beep(terminal(s)) - end -end - -refresh_line(s) = refresh_multi_line(s) -refresh_line(s, termbuf) = refresh_multi_line(termbuf, s) - -default_completion_cb(::IOBuffer) = [] -default_enter_cb(_) = true - -write_prompt(terminal, s::PromptState) = write_prompt(terminal, s.p) -function write_prompt(terminal, p::Prompt) - prefix = isa(p.prompt_prefix,Function) ? eval(Expr(:call, p.prompt_prefix)) : p.prompt_prefix - suffix = isa(p.prompt_suffix,Function) ? eval(Expr(:call, p.prompt_suffix)) : p.prompt_suffix - write(terminal, prefix) - write(terminal, Base.text_colors[:bold]) - write(terminal, p.prompt) - write(terminal, Base.text_colors[:normal]) - write(terminal, suffix) -end -write_prompt(terminal, s::String) = write(terminal, s) - -### Keymap Support - -normalize_key(key::Char) = string(key) -normalize_key(key::Integer) = normalize_key(Char(key)) -function normalize_key(key::AbstractString) - '\0' in key && error("Matching \\0 not currently supported.") - buf = IOBuffer() - i = start(key) - while !done(key, i) - c, i = next(key, i) - if c == '*' - write(buf, '\0') - elseif c == '^' - c, i = next(key, i) - write(buf, uppercase(c)-64) - elseif c == '\\' - c, i = next(key, i) - if c == 'C' - c, i = next(key, i) - @assert c == '-' - c, i = next(key, i) - write(buf, uppercase(c)-64) - elseif c == 'M' - c, i = next(key, i) - @assert c == '-' - c, i = next(key, i) - write(buf, '\e') - write(buf, c) - end - else - write(buf, c) - end - end - return String(take!(buf)) -end - -function normalize_keys(keymap::Dict) - ret = Dict{Any,Any}() - for (k,v) in keymap - normalized = normalize_key(k) - if haskey(ret,normalized) - error("""Multiple spellings of a key in a single keymap - (\"$k\" conflicts with existing mapping)""") - end - ret[normalized] = v - end - return ret -end - -function add_nested_key!(keymap::Dict, key, value; override = false) - i = start(key) - while !done(key, i) - c, i = next(key, i) - if c in keys(keymap) - if done(key, i) && override - # isa(keymap[c], Dict) - In this case we're overriding a prefix of an existing command - keymap[c] = value - break - else - if !isa(keymap[c], Dict) - error("Conflicting definitions for keyseq " * escape_string(key) * " within one keymap") - end - end - elseif done(key, i) - keymap[c] = value - break - else - keymap[c] = Dict{Char,Any}() - end - keymap = keymap[c] - end -end - -# Redirect a key as if `seq` had been the keysequence instead in a lazy fashion. -# This is different from the default eager redirect, which only looks at the current and lower -# layers of the stack. -struct KeyAlias - seq::String - KeyAlias(seq) = new(normalize_key(seq)) -end - -match_input(k::Function, s, term, cs, keymap) = (update_key_repeats(s, cs); return keymap_fcn(k, String(cs))) -match_input(k::Void, s, term, cs, keymap) = (s,p) -> return :ok -match_input(k::KeyAlias, s, term, cs, keymap) = match_input(keymap, s, IOBuffer(k.seq), Char[], keymap) -function match_input(k::Dict, s, term=terminal(s), cs=Char[], keymap = k) - # if we run out of characters to match before resolving an action, - # return an empty keymap function - eof(term) && return keymap_fcn(nothing, "") - c = read(term, Char) - # Ignore any '\0' (eg, CTRL-space in xterm), as this is used as a - # placeholder for the wildcard (see normalize_key("*")) - c != '\0' || return keymap_fcn(nothing, "") - push!(cs, c) - key = haskey(k, c) ? c : '\0' - # if we don't match on the key, look for a default action then fallback on 'nothing' to ignore - return match_input(get(k, key, nothing), s, term, cs, keymap) -end - -keymap_fcn(f::Void, c) = (s, p) -> return :ok -function keymap_fcn(f::Function, c) - return function (s, p) - r = eval(Expr(:call,f,s, p, c)) - if isa(r, Symbol) - return r - else - return :ok - end - end -end - -update_key_repeats(s, keystroke) = nothing -function update_key_repeats(s::MIState, keystroke) - s.key_repeats = s.previous_key == keystroke ? s.key_repeats + 1 : 0 - s.previous_key = keystroke - return -end - - -## Conflict fixing -# Consider a keymap of the form -# -# { -# "**" => f -# "ab" => g -# } -# -# Naively this is transformed into a tree as -# -# { -# '*' => { -# '*' => f -# } -# 'a' => { -# 'b' => g -# } -# } -# -# However, that's not what we want, because now "ac" is -# is not defined. We need to fix this up and turn it into -# -# { -# '*' => { -# '*' => f -# } -# 'a' => { -# '*' => f -# 'b' => g -# } -# } -# -# i.e. copy over the appropraite default subdict -# - -# deep merge where target has higher precedence -function keymap_merge!(target::Dict, source::Dict) - for k in keys(source) - if !haskey(target, k) - target[k] = source[k] - elseif isa(target[k], Dict) - keymap_merge!(target[k], source[k]) - else - # Ignore, target has higher precedence - end - end -end - -fixup_keymaps!(d, l, s, sk) = nothing -function fixup_keymaps!(dict::Dict, level, s, subkeymap) - if level > 0 - for d in values(dict) - fixup_keymaps!(d, level-1, s, subkeymap) - end - else - if haskey(dict, s) - if isa(dict[s], Dict) && isa(subkeymap, Dict) - keymap_merge!(dict[s], subkeymap) - end - else - dict[s] = deepcopy(subkeymap) - end - end -end - -function add_specialisations(dict, subdict, level) - default_branch = subdict['\0'] - if isa(default_branch, Dict) - # Go through all the keymaps in the default branch - # and copy them over to dict - for s in keys(default_branch) - s == '\0' && add_specialisations(dict, default_branch, level+1) - fixup_keymaps!(dict, level, s, default_branch[s]) - end - end -end - -postprocess!(others) = nothing -function postprocess!(dict::Dict) - # needs to be done first for every branch - if haskey(dict, '\0') - add_specialisations(dict, dict, 1) - end - for (k,v) in dict - k == '\0' && continue - postprocess!(v) - end -end - -function getEntry(keymap,key) - v = keymap - for c in key - if !haskey(v,c) - return nothing - end - v = v[c] - end - return v -end - -# `target` is the total keymap being built up, already being a nested tree of Dicts. -# source is the keymap specified by the user (with normalized keys) -function keymap_merge(target,source) - ret = copy(target) - direct_keys = filter((k,v) -> isa(v, Union{Function, KeyAlias, Void}), source) - # first direct entries - for key in keys(direct_keys) - add_nested_key!(ret, key, source[key]; override = true) - end - # then redirected entries - for key in setdiff(keys(source), keys(direct_keys)) - # We first resolve redirects in the source - value = source[key] - visited = Vector{Any}(0) - while isa(value, Union{Char,AbstractString}) - value = normalize_key(value) - if value in visited - error("Eager redirection cycle detected for key " * escape_string(key)) - end - push!(visited,value) - if !haskey(source,value) - break - end - value = source[value] - end - - if isa(value, Union{Char,AbstractString}) - value = getEntry(ret, value) - if value === nothing - error("Could not find redirected value " * escape_string(source[key])) - end - end - add_nested_key!(ret, key, value; override = true) - end - ret -end - -function keymap_unify(keymaps) - ret = Dict{Char,Any}() - for keymap in keymaps - ret = keymap_merge(ret, keymap) - end - postprocess!(ret) - return ret -end - -function validate_keymap(keymap) - for key in keys(keymap) - visited_keys = Any[key] - v = getEntry(keymap,key) - while isa(v,KeyAlias) - if v.seq in visited_keys - error("Alias cycle detected in keymap") - end - push!(visited_keys,v.seq) - v = getEntry(keymap,v.seq) - end - end -end - -function keymap(keymaps::Array{<:Dict}) - # keymaps is a vector of prioritized keymaps, with highest priority first - ret = keymap_unify(map(normalize_keys, reverse(keymaps))) - validate_keymap(ret) - ret -end - -const escape_defaults = merge!( - AnyDict(Char(i) => nothing for i=vcat(1:26, 28:31)), # Ignore control characters by default - AnyDict( # And ignore other escape sequences by default - "\e*" => nothing, - "\e[*" => nothing, - "\eO*" => nothing, - # Also ignore extended escape sequences - # TODO: Support ranges of characters - "\e[1**" => nothing, - "\e[2**" => nothing, - "\e[3**" => nothing, - "\e[4**" => nothing, - "\e[5**" => nothing, - "\e[6**" => nothing, - # less commonly used VT220 editing keys - "\e[2~" => nothing, # insert - "\e[3~" => nothing, # delete - "\e[5~" => nothing, # page up - "\e[6~" => nothing, # page down - # These are different spellings of arrow keys, home keys, etc. - # and should always do the same as the canonical key sequence - "\e[1~" => KeyAlias("\e[H"), # home - "\e[4~" => KeyAlias("\e[F"), # end - "\e[7~" => KeyAlias("\e[H"), # home - "\e[8~" => KeyAlias("\e[F"), # end - "\eOA" => KeyAlias("\e[A"), - "\eOB" => KeyAlias("\e[B"), - "\eOC" => KeyAlias("\e[C"), - "\eOD" => KeyAlias("\e[D"), - "\eOH" => KeyAlias("\e[H"), - "\eOF" => KeyAlias("\e[F"), - ), - # set mode commands - AnyDict("\e[$(c)h" => nothing for c in 1:20), - # reset mode commands - AnyDict("\e[$(c)l" => nothing for c in 1:20) - ) - -function write_response_buffer(s::PromptState, data) - offset = s.input_buffer.ptr - ptr = data.response_buffer.ptr - seek(data.response_buffer, 0) - write(s.input_buffer, readstring(data.response_buffer)) - s.input_buffer.ptr = offset + ptr - 2 - data.response_buffer.ptr = ptr - refresh_line(s) -end - -mutable struct SearchState <: ModeState - terminal - histprompt - #rsearch (true) or ssearch (false) - backward::Bool - query_buffer::IOBuffer - response_buffer::IOBuffer - ias::InputAreaState - #The prompt whose input will be replaced by the matched history - parent - SearchState(terminal, histprompt, backward, query_buffer, response_buffer) = - new(terminal, histprompt, backward, query_buffer, response_buffer, InputAreaState(0,0)) -end - -terminal(s::SearchState) = s.terminal - -function update_display_buffer(s::SearchState, data) - history_search(data.histprompt.hp, data.query_buffer, data.response_buffer, data.backward, false) || beep(terminal(s)) - refresh_line(s) -end - -function history_next_result(s::MIState, data::SearchState) - history_search(data.histprompt.hp, data.query_buffer, data.response_buffer, data.backward, true) || beep(terminal(s)) - refresh_line(data) -end - -function history_set_backward(s::SearchState, backward) - s.backward = backward -end - -input_string(s::SearchState) = String(s.query_buffer) - -function reset_state(s::SearchState) - if s.query_buffer.size != 0 - s.query_buffer.size = 0 - s.query_buffer.ptr = 1 - end - if s.response_buffer.size != 0 - s.response_buffer.size = 0 - s.response_buffer.ptr = 1 - end - reset_state(s.histprompt.hp) -end - -mutable struct HistoryPrompt{T<:HistoryProvider} <: TextInterface - hp::T - complete - keymap_dict::Dict{Char,Any} - HistoryPrompt{T}(hp) where T<:HistoryProvider = new(hp, EmptyCompletionProvider()) -end - -HistoryPrompt(hp::T) where T<:HistoryProvider = HistoryPrompt{T}(hp) -init_state(terminal, p::HistoryPrompt) = SearchState(terminal, p, true, IOBuffer(), IOBuffer()) - -mutable struct PrefixSearchState <: ModeState - terminal - histprompt - prefix::String - response_buffer::IOBuffer - ias::InputAreaState - indent::Int - # The modal interface state, if present - mi - #The prompt whose input will be replaced by the matched history - parent - PrefixSearchState(terminal, histprompt, prefix, response_buffer) = - new(terminal, histprompt, prefix, response_buffer, InputAreaState(0,0), 0) -end - -function show(io::IO, s::PrefixSearchState) - print(io, "PrefixSearchState ", isdefined(s,:parent) ? - string("(", s.parent, " active)") : "(no parent)", " for ", - isdefined(s,:mi) ? s.mi : "no MI") -end - -refresh_multi_line(termbuf::TerminalBuffer, terminal::UnixTerminal, - s::Union{PromptState,PrefixSearchState}) = s.ias = - refresh_multi_line(termbuf, terminal, buffer(s), s.ias, s, indent = s.indent) - -input_string(s::PrefixSearchState) = String(s.response_buffer) - -# a meta-prompt that presents itself as parent_prompt, but which has an independent keymap -# for prefix searching -mutable struct PrefixHistoryPrompt{T<:HistoryProvider} <: TextInterface - hp::T - parent_prompt::Prompt - complete - keymap_dict::Dict{Char,Any} - PrefixHistoryPrompt{T}(hp, parent_prompt) where T<:HistoryProvider = - new(hp, parent_prompt, EmptyCompletionProvider()) -end - -PrefixHistoryPrompt(hp::T, parent_prompt) where T<:HistoryProvider = PrefixHistoryPrompt{T}(hp, parent_prompt) -init_state(terminal, p::PrefixHistoryPrompt) = PrefixSearchState(terminal, p, "", IOBuffer()) - -write_prompt(terminal, s::PrefixSearchState) = write_prompt(terminal, s.histprompt.parent_prompt) -prompt_string(s::PrefixSearchState) = s.histprompt.parent_prompt.prompt - -terminal(s::PrefixSearchState) = s.terminal - -function reset_state(s::PrefixSearchState) - if s.response_buffer.size != 0 - s.response_buffer.size = 0 - s.response_buffer.ptr = 1 - end - reset_state(s.histprompt.hp) -end - -function transition(f::Function, s::PrefixSearchState, mode) - if isdefined(s, :mi) - transition(s.mi, mode) - end - s.parent = mode - s.histprompt.parent_prompt = mode - if isdefined(s, :mi) - transition(f, s.mi, s.histprompt) - else - f() - end -end - -replace_line(s::PrefixSearchState, l::IOBuffer) = s.response_buffer = l -function replace_line(s::PrefixSearchState, l) - s.response_buffer.ptr = 1 - s.response_buffer.size = 0 - write(s.response_buffer, l) -end - -function refresh_multi_line(termbuf::TerminalBuffer, s::SearchState) - buf = IOBuffer() - unsafe_write(buf, pointer(s.query_buffer.data), s.query_buffer.ptr-1) - write(buf, "': ") - offset = buf.ptr - ptr = s.response_buffer.ptr - seek(s.response_buffer, 0) - write(buf, readstring(s.response_buffer)) - buf.ptr = offset + ptr - 1 - s.response_buffer.ptr = ptr - s.ias = refresh_multi_line(termbuf, s.terminal, buf, s.ias, s.backward ? "(reverse-i-search)`" : "(forward-i-search)`") -end - -state(s::MIState, p) = s.mode_state[p] -state(s::PromptState, p) = (@assert s.p == p; s) -mode(s::MIState) = s.current_mode -mode(s::PromptState) = s.p -mode(s::SearchState) = @assert false -mode(s::PrefixSearchState) = s.histprompt.parent_prompt - -# Search Mode completions -function complete_line(s::SearchState, repeats) - completions, partial, should_complete = complete_line(s.histprompt.complete, s) - # For now only allow exact completions in search mode - if length(completions) == 1 - prev_pos = position(s.query_buffer) - seek(s.query_buffer, prev_pos-sizeof(partial)) - edit_replace(s, position(s.query_buffer), prev_pos, completions[1]) - end -end - -function accept_result(s, p) - parent = state(s, p).parent - transition(s, parent) do - replace_line(state(s, parent), state(s, p).response_buffer) - end -end - -function copybuf!(dst::IOBuffer, src::IOBuffer) - n = src.size - ensureroom(dst, n) - copy!(dst.data, 1, src.data, 1, n) - dst.size = src.size - dst.ptr = src.ptr -end - -function enter_search(s::MIState, p::HistoryPrompt, backward::Bool) - # a bit of hack to help fix #6325 - buf = copy(buffer(s)) - parent = mode(s) - p.hp.last_mode = mode(s) - p.hp.last_buffer = buf - - transition(s, p) do - ss = state(s, p) - ss.parent = parent - ss.backward = backward - truncate(ss.query_buffer, 0) - copybuf!(ss.response_buffer, buf) - end -end - -function enter_prefix_search(s::MIState, p::PrefixHistoryPrompt, backward::Bool) - buf = copy(buffer(s)) - parent = mode(s) - - transition(s, p) do - pss = state(s, p) - pss.parent = parent - pss.histprompt.parent_prompt = parent - pss.prefix = String(buf.data[1:position(buf)]) - copybuf!(pss.response_buffer, buf) - pss.indent = state(s, parent).indent - pss.mi = s - end - pss = state(s, p) - if backward - history_prev_prefix(pss, pss.histprompt.hp, pss.prefix) - else - history_next_prefix(pss, pss.histprompt.hp, pss.prefix) - end -end - -function setup_search_keymap(hp) - p = HistoryPrompt(hp) - pkeymap = AnyDict( - "^R" => (s,data,c)->(history_set_backward(data, true); history_next_result(s, data)), - "^S" => (s,data,c)->(history_set_backward(data, false); history_next_result(s, data)), - '\r' => (s,o...)->accept_result(s, p), - '\n' => '\r', - # Limited form of tab completions - '\t' => (s,data,c)->(complete_line(s); update_display_buffer(s, data)), - "^L" => (s,data,c)->(Terminals.clear(terminal(s)); update_display_buffer(s, data)), - - # Backspace/^H - '\b' => (s,data,c)->(edit_backspace(data.query_buffer) ? - update_display_buffer(s, data) : beep(terminal(s))), - 127 => KeyAlias('\b'), - # Meta Backspace - "\e\b" => (s,data,c)->(edit_delete_prev_word(data.query_buffer) ? - update_display_buffer(s, data) : beep(terminal(s))), - "\e\x7f" => "\e\b", - # Word erase to whitespace - "^W" => (s,data,c)->(edit_werase(data.query_buffer) ? - update_display_buffer(s, data) : beep(terminal(s))), - # ^C and ^D - "^C" => (s,data,c)->(edit_clear(data.query_buffer); - edit_clear(data.response_buffer); - update_display_buffer(s, data); - reset_state(data.histprompt.hp); - transition(s, data.parent)), - "^D" => "^C", - # Other ways to cancel search mode (it's difficult to bind \e itself) - "^G" => "^C", - "\e\e" => "^C", - "^K" => (s,o...)->transition(s, state(s, p).parent), - "^Y" => (s,data,c)->(edit_yank(s); update_display_buffer(s, data)), - "^U" => (s,data,c)->(edit_clear(data.query_buffer); - edit_clear(data.response_buffer); - update_display_buffer(s, data)), - # Right Arrow - "\e[C" => (s,o...)->(accept_result(s, p); edit_move_right(s)), - # Left Arrow - "\e[D" => (s,o...)->(accept_result(s, p); edit_move_left(s)), - # Up Arrow - "\e[A" => (s,o...)->(accept_result(s, p); edit_move_up(s)), - # Down Arrow - "\e[B" => (s,o...)->(accept_result(s, p); edit_move_down(s)), - "^B" => (s,o...)->(accept_result(s, p); edit_move_left(s)), - "^F" => (s,o...)->(accept_result(s, p); edit_move_right(s)), - # Meta B - "\eb" => (s,o...)->(accept_result(s, p); edit_move_word_left(s)), - # Meta F - "\ef" => (s,o...)->(accept_result(s, p); edit_move_word_right(s)), - # Ctrl-Left Arrow - "\e[1;5D" => "\eb", - # Ctrl-Left Arrow on rxvt - "\eOd" => "\eb", - # Ctrl-Right Arrow - "\e[1;5C" => "\ef", - # Ctrl-Right Arrow on rxvt - "\eOc" => "\ef", - "^A" => (s,o...)->(accept_result(s, p); move_line_start(s); refresh_line(s)), - "^E" => (s,o...)->(accept_result(s, p); move_line_end(s); refresh_line(s)), - "^Z" => (s,o...)->(return :suspend), - # Try to catch all Home/End keys - "\e[H" => (s,o...)->(accept_result(s, p); move_input_start(s); refresh_line(s)), - "\e[F" => (s,o...)->(accept_result(s, p); move_input_end(s); refresh_line(s)), - # Use ^N and ^P to change search directions and iterate through results - "^N" => (s,data,c)->(history_set_backward(data, false); history_next_result(s, data)), - "^P" => (s,data,c)->(history_set_backward(data, true); history_next_result(s, data)), - # Bracketed paste mode - "\e[200~" => (s,data,c)-> begin - ps = state(s, mode(s)) - input = readuntil(ps.terminal, "\e[201~")[1:(end-6)] - edit_insert(data.query_buffer, input); update_display_buffer(s, data) - end, - "*" => (s,data,c)->(edit_insert(data.query_buffer, c); update_display_buffer(s, data)) - ) - p.keymap_dict = keymap([pkeymap, escape_defaults]) - skeymap = AnyDict( - "^R" => (s,o...)->(enter_search(s, p, true)), - "^S" => (s,o...)->(enter_search(s, p, false)), - ) - (p, skeymap) -end - -keymap(state, p::Union{HistoryPrompt,PrefixHistoryPrompt}) = p.keymap_dict -keymap_data(state, ::Union{HistoryPrompt, PrefixHistoryPrompt}) = state - -Base.isempty(s::PromptState) = s.input_buffer.size == 0 - -on_enter(s::PromptState) = s.p.on_enter(s) - -move_input_start(s) = (seek(buffer(s), 0)) -move_input_end(buf::IOBuffer) = seekend(buf) -move_input_end(s) = move_input_end(buffer(s)) -function move_line_start(s::MIState) - buf = buffer(s) - curpos = position(buf) - curpos == 0 && return - if s.key_repeats > 0 - move_input_start(s) - else - seek(buf, rsearch(buf.data, '\n', curpos)) - end -end -function move_line_end(s::MIState) - s.key_repeats > 0 ? - move_input_end(s) : - move_line_end(buffer(s)) -end -function move_line_end(buf::IOBuffer) - eof(buf) && return - pos = search(buf.data, '\n', position(buf)+1) - if pos == 0 - move_input_end(buf) - return - end - seek(buf, pos-1) -end - -function commit_line(s) - move_input_end(s) - refresh_line(s) - println(terminal(s)) - add_history(s) - state(s, mode(s)).ias = InputAreaState(0, 0) -end - -""" -`Base.LineEdit.tabwidth` controls the presumed tab width of code pasted into the REPL. - -You can modify it by doing `@eval Base.LineEdit tabwidth = 4`, for example. - -Must satisfy `0 < tabwidth <= 16`. -""" -global tabwidth = 8 - -function bracketed_paste(s) - ps = state(s, mode(s)) - input = readuntil(ps.terminal, "\e[201~")[1:(end-6)] - input = replace(input, '\r', '\n') - if position(buffer(s)) == 0 - indent = Base.indentation(input; tabwidth=tabwidth)[1] - input = Base.unindent(input, indent; tabwidth=tabwidth) - end - return replace(input, '\t', " "^tabwidth) -end - -const default_keymap = -AnyDict( - # Tab - '\t' => (s,o...)->begin - buf = buffer(s) - # Yes, we are ignoring the possiblity - # the we could be in the middle of a multi-byte - # sequence, here but that's ok, since any - # whitespace we're interested in is only one byte - i = position(buf) - if i != 0 - c = buf.data[i] - if c == UInt8('\n') || c == UInt8('\t') || - # hack to allow path completion in cmds - # after a space, e.g., `cd `, while still - # allowing multiple indent levels - (c == UInt8(' ') && i > 3 && buf.data[i-1] == UInt8(' ')) - edit_insert(s, " "^4) - return - end - end - complete_line(s) - refresh_line(s) - end, - # Enter - '\r' => (s,o...)->begin - if on_enter(s) || (eof(buffer(s)) && s.key_repeats > 1) - commit_line(s) - return :done - else - edit_insert(s, '\n') - end - end, - '\n' => KeyAlias('\r'), - # Backspace/^H - '\b' => (s,o...)->edit_backspace(s), - 127 => KeyAlias('\b'), - # Meta Backspace - "\e\b" => (s,o...)->edit_delete_prev_word(s), - "\e\x7f" => "\e\b", - # ^D - "^D" => (s,o...)->begin - if buffer(s).size > 0 - edit_delete(s) - else - println(terminal(s)) - return :abort - end - end, - "^B" => (s,o...)->edit_move_left(s), - "^F" => (s,o...)->edit_move_right(s), - # Meta B - "\eb" => (s,o...)->edit_move_word_left(s), - # Meta F - "\ef" => (s,o...)->edit_move_word_right(s), - # Ctrl-Left Arrow - "\e[1;5D" => "\eb", - # Ctrl-Left Arrow on rxvt - "\eOd" => "\eb", - # Ctrl-Right Arrow - "\e[1;5C" => "\ef", - # Ctrl-Right Arrow on rxvt - "\eOc" => "\ef", - # Meta Enter - "\e\r" => (s,o...)->(edit_insert(s, '\n')), - "\e\n" => "\e\r", - # Simply insert it into the buffer by default - "*" => (s,data,c)->(edit_insert(s, c)), - "^U" => (s,o...)->edit_clear(s), - "^K" => (s,o...)->edit_kill_line(s), - "^Y" => (s,o...)->edit_yank(s), - "^A" => (s,o...)->(move_line_start(s); refresh_line(s)), - "^E" => (s,o...)->(move_line_end(s); refresh_line(s)), - # Try to catch all Home/End keys - "\e[H" => (s,o...)->(move_input_start(s); refresh_line(s)), - "\e[F" => (s,o...)->(move_input_end(s); refresh_line(s)), - "^L" => (s,o...)->(Terminals.clear(terminal(s)); refresh_line(s)), - "^W" => (s,o...)->edit_werase(s), - # Meta D - "\ed" => (s,o...)->edit_delete_next_word(s), - "^C" => (s,o...)->begin - try # raise the debugger if present - ccall(:jl_raise_debugger, Int, ()) - end - move_input_end(s) - refresh_line(s) - print(terminal(s), "^C\n\n") - transition(s, :reset) - refresh_line(s) - end, - "^Z" => (s,o...)->(return :suspend), - # Right Arrow - "\e[C" => (s,o...)->edit_move_right(s), - # Left Arrow - "\e[D" => (s,o...)->edit_move_left(s), - # Up Arrow - "\e[A" => (s,o...)->edit_move_up(s), - # Down Arrow - "\e[B" => (s,o...)->edit_move_down(s), - # Delete - "\e[3~" => (s,o...)->edit_delete(s), - # Bracketed Paste Mode - "\e[200~" => (s,o...)->begin - input = bracketed_paste(s) - edit_insert(s, input) - end, - "^T" => (s,o...)->edit_transpose(s) -) - -const history_keymap = AnyDict( - "^P" => (s,o...)->(history_prev(s, mode(s).hist)), - "^N" => (s,o...)->(history_next(s, mode(s).hist)), - # Up Arrow - "\e[A" => (s,o...)->(edit_move_up(s) || history_prev(s, mode(s).hist)), - # Down Arrow - "\e[B" => (s,o...)->(edit_move_down(s) || history_next(s, mode(s).hist)), - # Page Up - "\e[5~" => (s,o...)->(history_prev(s, mode(s).hist)), - # Page Down - "\e[6~" => (s,o...)->(history_next(s, mode(s).hist)) -) - -const prefix_history_keymap = merge!( - AnyDict( - # Up Arrow - "\e[A" => (s,data,c)->history_prev_prefix(data, data.histprompt.hp, data.prefix), - # Down Arrow - "\e[B" => (s,data,c)->history_next_prefix(data, data.histprompt.hp, data.prefix), - # by default, pass thru to the parent mode - "*" => (s,data,c)->begin - accept_result(s, data.histprompt); - ps = state(s, mode(s)) - map = keymap(ps, mode(s)) - match_input(map, s, IOBuffer(c))(s, keymap_data(ps, mode(s))) - end, - # match escape sequences for pass thru - "\e*" => "*", - "\e[*" => "*", - "\eO*" => "*", - "\e[1;5*" => "*", # Ctrl-Arrow - "\e[200~" => "*" - ), - # VT220 editing commands - AnyDict("\e[$(n)~" => "*" for n in 1:8), - # set mode commands - AnyDict("\e[$(c)h" => "*" for c in 1:20), - # reset mode commands - AnyDict("\e[$(c)l" => "*" for c in 1:20) -) - -function setup_prefix_keymap(hp, parent_prompt) - p = PrefixHistoryPrompt(hp, parent_prompt) - p.keymap_dict = keymap([prefix_history_keymap]) - pkeymap = AnyDict( - # Up Arrow - "\e[A" => (s,o...)->(edit_move_up(s) || enter_prefix_search(s, p, true)), - # Down Arrow - "\e[B" => (s,o...)->(edit_move_down(s) || enter_prefix_search(s, p, false)), - ) - (p, pkeymap) -end - -function deactivate(p::TextInterface, s::ModeState, termbuf, term::TextTerminal) - clear_input_area(termbuf, s) - s -end - -function activate(p::TextInterface, s::ModeState, termbuf, term::TextTerminal) - s.ias = InputAreaState(0, 0) - refresh_line(s, termbuf) -end - -function activate(p::TextInterface, s::MIState, termbuf, term::TextTerminal) - @assert p == s.current_mode - activate(p, s.mode_state[s.current_mode], termbuf, term) -end -activate(m::ModalInterface, s::MIState, termbuf, term::TextTerminal) = - activate(s.current_mode, s, termbuf, term) - -commit_changes(t::UnixTerminal, termbuf) = write(t, take!(termbuf.out_stream)) -function transition(f::Function, s::MIState, mode) - if mode === :abort - s.aborted = true - return - end - if mode === :reset - reset_state(s) - return - end - if !haskey(s.mode_state,mode) - s.mode_state[mode] = init_state(terminal(s), mode) - end - termbuf = TerminalBuffer(IOBuffer()) - t = terminal(s) - s.mode_state[s.current_mode] = deactivate(s.current_mode, s.mode_state[s.current_mode], termbuf, t) - s.current_mode = mode - f() - activate(mode, s.mode_state[mode], termbuf, t) - commit_changes(t, termbuf) -end -transition(s::MIState, mode) = transition((args...)->nothing, s, mode) - -function reset_state(s::PromptState) - if s.input_buffer.size != 0 - s.input_buffer.size = 0 - s.input_buffer.ptr = 1 - end - s.ias = InputAreaState(0, 0) -end - -function reset_state(s::MIState) - for (mode,state) in s.mode_state - reset_state(state) - end -end - -const default_keymap_dict = keymap([default_keymap, escape_defaults]) - -function Prompt(prompt; - prompt_prefix = "", - prompt_suffix = "", - keymap_dict = default_keymap_dict, - keymap_func_data = nothing, - complete = EmptyCompletionProvider(), - on_enter = default_enter_cb, - on_done = ()->nothing, - hist = EmptyHistoryProvider(), - sticky = false) - - Prompt(prompt, prompt_prefix, prompt_suffix, keymap_dict, keymap_func_data, - complete, on_enter, on_done, hist, sticky) -end - -run_interface(::Prompt) = nothing - -init_state(terminal, prompt::Prompt) = PromptState(terminal, prompt, IOBuffer(), InputAreaState(1, 1), #=indent(spaces)=#strwidth(prompt.prompt)) - -function init_state(terminal, m::ModalInterface) - s = MIState(m, m.modes[1], false, Dict{Any,Any}()) - for mode in m.modes - s.mode_state[mode] = init_state(terminal, mode) - end - s -end - -function run_interface(terminal, m::ModalInterface) - s::MIState = init_state(terminal, m) - while !s.aborted - buf, ok, suspend = prompt!(terminal, m, s) - while suspend - @static if is_unix(); ccall(:jl_repl_raise_sigtstp, Cint, ()); end - buf, ok, suspend = prompt!(terminal, m, s) - end - eval(Main, - Expr(:body, - Expr(:return, - Expr(:call, - QuoteNode(mode(state(s, s.current_mode)).on_done), - QuoteNode(s), - QuoteNode(buf), - QuoteNode(ok))))) - end -end - -buffer(s::PromptState) = s.input_buffer -buffer(s::SearchState) = s.query_buffer -buffer(s::PrefixSearchState) = s.response_buffer - -keymap(s::PromptState, prompt::Prompt) = prompt.keymap_dict -keymap_data(s::PromptState, prompt::Prompt) = prompt.keymap_func_data -keymap(ms::MIState, m::ModalInterface) = keymap(ms.mode_state[ms.current_mode], ms.current_mode) -keymap_data(ms::MIState, m::ModalInterface) = keymap_data(ms.mode_state[ms.current_mode], ms.current_mode) - -function prompt!(term, prompt, s = init_state(term, prompt)) - Base.reseteof(term) - raw!(term, true) - enable_bracketed_paste(term) - try - activate(prompt, s, term, term) - old_state = mode(s) - while true - kmap = keymap(s, prompt) - fcn = match_input(kmap, s) - kdata = keymap_data(s, prompt) - # errors in keymaps shouldn't cause the REPL to fail, so wrap in a - # try/catch block - local state - try - state = fcn(s, kdata) - catch e - bt = catch_backtrace() - warn(e, bt = bt, prefix = "ERROR (in the keymap): ") - # try to cleanup and get `s` back to its original state before returning - transition(s, :reset) - transition(s, old_state) - state = :done - end - if state === :abort - return buffer(s), false, false - elseif state === :done - return buffer(s), true, false - elseif state === :suspend - if is_unix() - return buffer(s), true, true - end - else - @assert state === :ok - end - end - finally - raw!(term, false) && disable_bracketed_paste(term) - end -end - -end # module diff --git a/julia-0.6.3/share/julia/base/Makefile b/julia-0.6.3/share/julia/base/Makefile deleted file mode 100644 index 04c97fd..0000000 --- a/julia-0.6.3/share/julia/base/Makefile +++ /dev/null @@ -1,111 +0,0 @@ -SRCDIR := $(abspath $(dir $(lastword $(MAKEFILE_LIST)))) -BUILDDIR := . -JULIAHOME := $(abspath $(SRCDIR)/..) -include $(JULIAHOME)/deps/Versions.make -include $(JULIAHOME)/Make.inc - -TAGGED_RELEASE_BANNER := "" - -ifneq ($(USEMSVC), 1) -CPP_STDOUT := $(CPP) -P -else -CPP_STDOUT := $(CPP) -E -endif - -all: $(addprefix $(BUILDDIR)/,pcre_h.jl errno_h.jl build_h.jl.phony file_constants.jl uv_constants.jl version_git.jl.phony) - -PCRE_CONST := 0x[0-9a-fA-F]+|[0-9]+ -ifeq ($(USE_SYSTEM_PCRE), 1) - PCRE_INCL_PATH := $(shell $(PCRE_CONFIG) --prefix)/include/pcre2.h -else - PCRE_INCL_PATH := $(build_includedir)/pcre2.h -endif - -$(BUILDDIR)/pcre_h.jl: $(PCRE_INCL_PATH) - @$(call PRINT_PERL, $(CPP) -D PCRE2_CODE_UNIT_WIDTH=8 -dM $< | perl -nle '/^\s*#define\s+PCRE2_(\w*)\s*\(?($(PCRE_CONST))\)?u?\s*$$/ and print "const $$1 = UInt32($$2)"' | LC_ALL=C sort > $@) - -$(BUILDDIR)/errno_h.jl: - @$(call PRINT_PERL, echo '#include ' | $(CPP) -dM - | perl -nle 'print "const $$1 = Int32($$2)" if /^#define\s+(E\w+)\s+(\d+)\s*$$/' | LC_ALL=C sort > $@) - -$(BUILDDIR)/file_constants.jl: $(SRCDIR)/../src/file_constants.h - @$(call PRINT_PERL, $(CPP_STDOUT) -DJULIA $< | perl -nle 'print "$$1 0o$$2" if /^(\s*const\s+[A-z_]+\s+=)\s+(0[0-9]*)\s*$$/; print "$$1" if /^\s*(const\s+[A-z_]+\s+=\s+([1-9]|0x)[0-9A-z]*)\s*$$/' > $@) - -$(BUILDDIR)/uv_constants.jl: $(SRCDIR)/../src/uv_constants.h $(build_includedir)/uv-errno.h - @$(call PRINT_PERL, $(CPP_STDOUT) "-I$(LIBUV_INC)" -DJULIA $< | tail -n 16 > $@) - -$(BUILDDIR)/build_h.jl.phony: - @echo "# This file is automatically generated in base/Makefile" > $@ -ifeq ($(XC_HOST),) - @echo "const MACHINE = \"$(BUILD_MACHINE)\"" >> $@ -else - @echo "const MACHINE = \"$(XC_HOST)\"" >> $@ -endif - @echo "const libm_name = \"$(LIBMNAME)\"" >> $@ - @echo "const libblas_name = \"$(LIBBLASNAME)\"" >> $@ - @echo "const liblapack_name = \"$(LIBLAPACKNAME)\"" >> $@ -ifeq ($(USE_BLAS64), 1) - @echo "const USE_BLAS64 = true" >> $@ -else - @echo "const USE_BLAS64 = false" >> $@ -endif -ifeq ($(USE_GPL_LIBS), 1) - @echo "const USE_GPL_LIBS = true" >> $@ -else - @echo "const USE_GPL_LIBS = false" >> $@ -endif - @echo "const libfftw_name = \"$(LIBFFTWNAME)\"" >> $@ - @echo "const libfftwf_name = \"$(LIBFFTWFNAME)\"" >> $@ - @echo "const libllvm_version = \"$$($(LLVM_CONFIG_HOST) --version)\"" >> $@ - @echo "const VERSION_STRING = \"$(JULIA_VERSION)\"" >> $@ - @echo "const TAGGED_RELEASE_BANNER = \"$(TAGGED_RELEASE_BANNER)\"" >> $@ - @echo "const SYSCONFDIR = \"$(sysconfdir_rel)\"" >> $@ - @echo "const DATAROOTDIR = \"$(datarootdir_rel)\"" >> $@ - @echo "const DOCDIR = \"$(docdir_rel)\"" >> $@ - @echo "const LIBDIR = \"$(libdir_rel)\"" >> $@ - @echo "const PRIVATE_LIBDIR = \"$(private_libdir_rel)\"" >> $@ - @echo "const INCLUDEDIR = \"$(includedir_rel)\"" >> $@ - - @# This to ensure that we always rebuild this file, but only when it is modified do we touch build_h.jl, - @# ensuring we rebuild the system image as infrequently as possible - @if ! cmp -s $@ build_h.jl; then \ - $(call PRINT_PERL,) \ - mv $@ build_h.jl; \ - else \ - rm -f $@; \ - fi - -$(BUILDDIR)/version_git.jl.phony: $(SRCDIR)/version_git.sh -ifneq ($(NO_GIT), 1) - sh $< $(SRCDIR) > $@ - @# This to avoid touching git_version.jl when it is not modified, - @# so that the system image does not need to be rebuilt. - @if ! cmp -s $@ version_git.jl; then \ - $(call PRINT_PERL,) \ - mv $@ version_git.jl; \ - else \ - rm -f $@; \ - fi -else -ifeq ($(shell [ -f $(BUILDDIR)/version_git.jl ] && echo "true"), true) - @# Give warning if boilerplate git is used - @if grep -q "Default output if git is not available" $(BUILDDIR)/version_git.jl; then \ - echo "WARNING: Using boilerplate git version info" >&2; \ - fi -else - $(warning "WARNING: Generating boilerplate git version info") - @sh $(SRCDIR)/version_git.sh $(SRCDIR) NO_GIT > $(BUILDDIR)/version_git.jl -endif -endif - -.PHONY: $(BUILDDIR)/build_h.jl.phony $(BUILDDIR)/version_git.jl.phony clean all - -clean: - rm -f $(BUILDDIR)/pcre_h.jl - rm -f $(BUILDDIR)/errno_h.jl - rm -f $(BUILDDIR)/build_h.jl - rm -f $(BUILDDIR)/build_h.jl.phony - rm -f $(BUILDDIR)/fenv_constants.jl # To be removed - rm -f $(BUILDDIR)/uv_constants.jl - rm -f $(BUILDDIR)/file_constants.jl - rm -f $(BUILDDIR)/version_git.jl - rm -f $(BUILDDIR)/version_git.jl.phony diff --git a/julia-0.6.3/share/julia/base/REPL.jl b/julia-0.6.3/share/julia/base/REPL.jl deleted file mode 100644 index ec8d8f3..0000000 --- a/julia-0.6.3/share/julia/base/REPL.jl +++ /dev/null @@ -1,1067 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -module REPL - -using Base.Meta -using ..Terminals -using ..LineEdit -using ..REPLCompletions - -export - BasicREPL, - LineEditREPL, - StreamREPL - -import Base: - Display, - display, - show, - AnyDict, - == - -import ..LineEdit: - CompletionProvider, - HistoryProvider, - add_history, - complete_line, - history_next, - history_next_prefix, - history_prev, - history_prev_prefix, - history_search, - accept_result, - terminal - -abstract type AbstractREPL end - -answer_color(::AbstractREPL) = "" - -const JULIA_PROMPT = "julia> " - -mutable struct REPLBackend - "channel for AST" - repl_channel::Channel - "channel for results: (value, nothing) or (error, backtrace)" - response_channel::Channel - "flag indicating the state of this backend" - in_eval::Bool - "current backend task" - backend_task::Task - - REPLBackend(repl_channel, response_channel, in_eval) = - new(repl_channel, response_channel, in_eval) -end - -function eval_user_input(ast::ANY, backend::REPLBackend) - iserr, lasterr = false, ((), nothing) - Base.sigatomic_begin() - while true - try - Base.sigatomic_end() - if iserr - put!(backend.response_channel, lasterr) - iserr, lasterr = false, () - else - backend.in_eval = true - value = eval(Main, ast) - backend.in_eval = false - # note: value wrapped carefully here to ensure it doesn't get passed through expand - eval(Main, Expr(:body, Expr(:(=), :ans, QuoteNode(value)), Expr(:return, nothing))) - put!(backend.response_channel, (value, nothing)) - end - break - catch err - if iserr - println("SYSTEM ERROR: Failed to report error to REPL frontend") - println(err) - end - iserr, lasterr = true, (err, catch_backtrace()) - end - end - Base.sigatomic_end() -end - -function start_repl_backend(repl_channel::Channel, response_channel::Channel) - backend = REPLBackend(repl_channel, response_channel, false) - backend.backend_task = @schedule begin - # include looks at this to determine the relative include path - # nothing means cwd - while true - tls = task_local_storage() - tls[:SOURCE_PATH] = nothing - ast, show_value = take!(backend.repl_channel) - if show_value == -1 - # exit flag - break - end - eval_user_input(ast, backend) - end - end - backend -end - -function ip_matches_func(ip, func::Symbol) - for fr in StackTraces.lookup(ip) - if fr === StackTraces.UNKNOWN || fr.from_c - return false - end - fr.func === func && return true - end - return false -end - -struct REPLDisplay{R<:AbstractREPL} <: Display - repl::R -end - -==(a::REPLDisplay, b::REPLDisplay) = a.repl === b.repl - -function display(d::REPLDisplay, mime::MIME"text/plain", x) - io = outstream(d.repl) - Base.have_color && write(io, answer_color(d.repl)) - show(IOContext(io, :limit => true), mime, x) - println(io) -end -display(d::REPLDisplay, x) = display(d, MIME("text/plain"), x) - -function print_response(repl::AbstractREPL, val::ANY, bt, show_value::Bool, have_color::Bool) - repl.waserror = bt !== nothing - print_response(outstream(repl), val, bt, show_value, have_color, specialdisplay(repl)) -end -function print_response(errio::IO, val::ANY, bt, show_value::Bool, have_color::Bool, specialdisplay=nothing) - Base.sigatomic_begin() - while true - try - Base.sigatomic_end() - if bt !== nothing - eval(Main, Expr(:body, Expr(:return, Expr(:call, Base.display_error, - errio, QuoteNode(val), bt)))) - iserr, lasterr = false, () - else - if val !== nothing && show_value - try - if specialdisplay === nothing - eval(Main, Expr(:body, Expr(:return, Expr(:call, display, QuoteNode(val))))) - else - eval(Main, Expr(:body, Expr(:return, Expr(:call, specialdisplay, QuoteNode(val))))) - end - catch err - println(errio, "Error showing value of type ", typeof(val), ":") - rethrow(err) - end - end - end - break - catch err - if bt !== nothing - println(errio, "SYSTEM: show(lasterr) caused an error") - println(errio, err) - Base.show_backtrace(errio, bt) - break - end - val = err - bt = catch_backtrace() - end - end - Base.sigatomic_end() -end - -# A reference to a backend -struct REPLBackendRef - repl_channel::Channel - response_channel::Channel -end - -function run_repl(repl::AbstractREPL, consumer = x->nothing) - repl_channel = Channel(1) - response_channel = Channel(1) - backend = start_repl_backend(repl_channel, response_channel) - consumer(backend) - run_frontend(repl, REPLBackendRef(repl_channel,response_channel)) - return backend -end - -## BasicREPL ## - -mutable struct BasicREPL <: AbstractREPL - terminal::TextTerminal - waserror::Bool - BasicREPL(t) = new(t,false) -end - -outstream(r::BasicREPL) = r.terminal - -function run_frontend(repl::BasicREPL, backend::REPLBackendRef) - d = REPLDisplay(repl) - dopushdisplay = !in(d,Base.Multimedia.displays) - dopushdisplay && pushdisplay(d) - repl_channel, response_channel = backend.repl_channel, backend.response_channel - hit_eof = false - while true - Base.reseteof(repl.terminal) - write(repl.terminal, JULIA_PROMPT) - line = "" - ast = nothing - interrupted = false - while true - try - line *= readline(repl.terminal, chomp=false) - catch e - if isa(e,InterruptException) - try # raise the debugger if present - ccall(:jl_raise_debugger, Int, ()) - end - line = "" - interrupted = true - break - elseif isa(e,EOFError) - hit_eof = true - break - else - rethrow() - end - end - ast = Base.parse_input_line(line) - (isa(ast,Expr) && ast.head == :incomplete) || break - end - if !isempty(line) - put!(repl_channel, (ast, 1)) - val, bt = take!(response_channel) - if !ends_with_semicolon(line) - print_response(repl, val, bt, true, false) - end - end - write(repl.terminal, '\n') - ((!interrupted && isempty(line)) || hit_eof) && break - end - # terminate backend - put!(repl_channel, (nothing, -1)) - dopushdisplay && popdisplay(d) -end - -## LineEditREPL ## - -mutable struct LineEditREPL <: AbstractREPL - t::TextTerminal - hascolor::Bool - prompt_color::String - input_color::String - answer_color::String - shell_color::String - help_color::String - history_file::Bool - in_shell::Bool - in_help::Bool - envcolors::Bool - waserror::Bool - specialdisplay - interface - backendref::REPLBackendRef - LineEditREPL(t,hascolor,prompt_color,input_color,answer_color,shell_color,help_color,history_file,in_shell,in_help,envcolors) = - new(t,true,prompt_color,input_color,answer_color,shell_color,help_color,history_file,in_shell, - in_help,envcolors,false,nothing) -end -outstream(r::LineEditREPL) = r.t -specialdisplay(r::LineEditREPL) = r.specialdisplay -specialdisplay(r::AbstractREPL) = nothing -terminal(r::LineEditREPL) = r.t - -LineEditREPL(t::TextTerminal, envcolors = false) = LineEditREPL(t, - true, - Base.text_colors[:green], - Base.input_color(), - Base.answer_color(), - Base.text_colors[:red], - Base.text_colors[:yellow], - false, false, false, envcolors) - -mutable struct REPLCompletionProvider <: CompletionProvider; end - -mutable struct ShellCompletionProvider <: CompletionProvider; end - -struct LatexCompletions <: CompletionProvider; end - -beforecursor(buf::IOBuffer) = String(buf.data[1:buf.ptr-1]) - -function complete_line(c::REPLCompletionProvider, s) - partial = beforecursor(s.input_buffer) - full = LineEdit.input_string(s) - ret, range, should_complete = completions(full, endof(partial)) - return ret, partial[range], should_complete -end - -function complete_line(c::ShellCompletionProvider, s) - # First parse everything up to the current position - partial = beforecursor(s.input_buffer) - full = LineEdit.input_string(s) - ret, range, should_complete = shell_completions(full, endof(partial)) - return ret, partial[range], should_complete -end - -function complete_line(c::LatexCompletions, s) - partial = beforecursor(LineEdit.buffer(s)) - full = LineEdit.input_string(s) - ret, range, should_complete = bslash_completions(full, endof(partial))[2] - return ret, partial[range], should_complete -end - - -mutable struct REPLHistoryProvider <: HistoryProvider - history::Array{String,1} - history_file - start_idx::Int - cur_idx::Int - last_idx::Int - last_buffer::IOBuffer - last_mode - mode_mapping - modes::Array{Symbol,1} -end -REPLHistoryProvider(mode_mapping) = - REPLHistoryProvider(String[], nothing, 0, 0, -1, IOBuffer(), - nothing, mode_mapping, UInt8[]) - -invalid_history_message(path::String) = """ -Invalid history file ($path) format: -If you have a history file left over from an older version of Julia, -try renaming or deleting it. -Invalid character: """ - -munged_history_message(path::String) = """ -Invalid history file ($path) format: -An editor may have converted tabs to spaces at line """ - -function hist_getline(file) - while !eof(file) - line = readline(file, chomp=false) - isempty(line) && return line - line[1] in "\r\n" || return line - end - return "" -end - -function hist_from_file(hp, file, path) - hp.history_file = file - seek(file, 0) - countlines = 0 - while true - mode = :julia - line = hist_getline(file) - isempty(line) && break - countlines += 1 - line[1] != '#' && - error(invalid_history_message(path), repr(line[1]), " at line ", countlines) - while !isempty(line) - m = match(r"^#\s*(\w+)\s*:\s*(.*?)\s*$", line) - m === nothing && break - if m.captures[1] == "mode" - mode = Symbol(m.captures[2]) - end - line = hist_getline(file) - countlines += 1 - end - isempty(line) && break - # Make sure starts with tab - line[1] == ' ' && - error(munged_history_message(path), countlines) - line[1] != '\t' && - error(invalid_history_message(path), repr(line[1]), " at line ", countlines) - lines = String[] - while !isempty(line) - push!(lines, chomp(line[2:end])) - eof(file) && break - ch = Char(Base.peek(file)) - ch == ' ' && error(munged_history_message(path), countlines) - ch != '\t' && break - line = hist_getline(file) - countlines += 1 - end - push!(hp.modes, mode) - push!(hp.history, join(lines, '\n')) - end - seekend(file) - hp.start_idx = length(hp.history) - hp -end - -function mode_idx(hist::REPLHistoryProvider, mode) - c = :julia - for (k,v) in hist.mode_mapping - isequal(v, mode) && (c = k) - end - return c -end - -function add_history(hist::REPLHistoryProvider, s) - str = rstrip(String(s.input_buffer)) - isempty(strip(str)) && return - mode = mode_idx(hist, LineEdit.mode(s)) - !isempty(hist.history) && - isequal(mode, hist.modes[end]) && str == hist.history[end] && return - push!(hist.modes, mode) - push!(hist.history, str) - hist.history_file === nothing && return - entry = """ - # time: $(Libc.strftime("%Y-%m-%d %H:%M:%S %Z", time())) - # mode: $mode - $(replace(str, r"^"ms, "\t")) - """ - # TODO: write-lock history file - seekend(hist.history_file) - print(hist.history_file, entry) - flush(hist.history_file) -end - -function history_move(s::Union{LineEdit.MIState,LineEdit.PrefixSearchState}, hist::REPLHistoryProvider, idx::Int, save_idx::Int = hist.cur_idx) - max_idx = length(hist.history) + 1 - @assert 1 <= hist.cur_idx <= max_idx - (1 <= idx <= max_idx) || return :none - idx != hist.cur_idx || return :none - - # save the current line - if save_idx == max_idx - hist.last_mode = LineEdit.mode(s) - hist.last_buffer = copy(LineEdit.buffer(s)) - else - hist.history[save_idx] = LineEdit.input_string(s) - hist.modes[save_idx] = mode_idx(hist, LineEdit.mode(s)) - end - - # load the saved line - if idx == max_idx - last_buffer = hist.last_buffer - LineEdit.transition(s, hist.last_mode) do - LineEdit.replace_line(s, last_buffer) - end - hist.last_mode = nothing - hist.last_buffer = IOBuffer() - else - if haskey(hist.mode_mapping, hist.modes[idx]) - LineEdit.transition(s, hist.mode_mapping[hist.modes[idx]]) do - LineEdit.replace_line(s, hist.history[idx]) - end - else - return :skip - end - end - hist.cur_idx = idx - - return :ok -end - -# Modified version of accept_result that also transitions modes -function LineEdit.accept_result(s, p::LineEdit.HistoryPrompt{REPLHistoryProvider}) - parent = LineEdit.state(s, p).parent - hist = p.hp - if 1 <= hist.cur_idx <= length(hist.modes) - m = hist.mode_mapping[hist.modes[hist.cur_idx]] - LineEdit.transition(s, m) do - LineEdit.replace_line(LineEdit.state(s, m), LineEdit.state(s, p).response_buffer) - end - else - LineEdit.transition(s, parent) - end -end - -function history_prev(s::LineEdit.MIState, hist::REPLHistoryProvider, - save_idx::Int = hist.cur_idx) - hist.last_idx = -1 - m = history_move(s, hist, hist.cur_idx-1, save_idx) - if m === :ok - LineEdit.move_input_start(s) - LineEdit.reset_key_repeats(s) do - LineEdit.move_line_end(s) - end - LineEdit.refresh_line(s) - elseif m === :skip - hist.cur_idx -= 1 - history_prev(s, hist, save_idx) - else - Terminals.beep(LineEdit.terminal(s)) - end -end - -function history_next(s::LineEdit.MIState, hist::REPLHistoryProvider, - save_idx::Int = hist.cur_idx) - cur_idx = hist.cur_idx - max_idx = length(hist.history) + 1 - if cur_idx == max_idx && 0 < hist.last_idx - # issue #6312 - cur_idx = hist.last_idx - hist.last_idx = -1 - end - m = history_move(s, hist, cur_idx+1, save_idx) - if m === :ok - LineEdit.move_input_end(s) - LineEdit.refresh_line(s) - elseif m === :skip - hist.cur_idx += 1 - history_next(s, hist, save_idx) - else - Terminals.beep(LineEdit.terminal(s)) - end -end - -function history_move_prefix(s::LineEdit.PrefixSearchState, - hist::REPLHistoryProvider, - prefix::AbstractString, - backwards::Bool, - cur_idx = hist.cur_idx) - cur_response = String(LineEdit.buffer(s)) - # when searching forward, start at last_idx - if !backwards && hist.last_idx > 0 - cur_idx = hist.last_idx - end - hist.last_idx = -1 - max_idx = length(hist.history)+1 - idxs = backwards ? ((cur_idx-1):-1:1) : ((cur_idx+1):max_idx) - for idx in idxs - if (idx == max_idx) || (startswith(hist.history[idx], prefix) && (hist.history[idx] != cur_response || hist.modes[idx] != LineEdit.mode(s))) - m = history_move(s, hist, idx) - if m === :ok - if idx == max_idx - # on resuming the in-progress edit, leave the cursor where the user last had it - elseif isempty(prefix) - # on empty prefix search, move cursor to the end - LineEdit.move_input_end(s) - else - # otherwise, keep cursor at the prefix position as a visual cue - seek(LineEdit.buffer(s), sizeof(prefix)) - end - LineEdit.refresh_line(s) - return :ok - elseif m === :skip - return history_move_prefix(s,hist,prefix,backwards,idx) - end - end - end - Terminals.beep(LineEdit.terminal(s)) -end -history_next_prefix(s::LineEdit.PrefixSearchState, hist::REPLHistoryProvider, prefix::AbstractString) = - history_move_prefix(s, hist, prefix, false) -history_prev_prefix(s::LineEdit.PrefixSearchState, hist::REPLHistoryProvider, prefix::AbstractString) = - history_move_prefix(s, hist, prefix, true) - -function history_search(hist::REPLHistoryProvider, query_buffer::IOBuffer, response_buffer::IOBuffer, - backwards::Bool=false, skip_current::Bool=false) - - qpos = position(query_buffer) - qpos > 0 || return true - searchdata = beforecursor(query_buffer) - response_str = String(response_buffer) - - # Alright, first try to see if the current match still works - a = position(response_buffer) + 1 # position is zero-indexed - b = min(endof(response_str), prevind(response_str, a + sizeof(searchdata))) # ensure that b is valid - - !skip_current && searchdata == response_str[a:b] && return true - - searchfunc, searchstart, skipfunc = backwards ? (rsearch, b, prevind) : - (search, a, nextind) - skip_current && (searchstart = skipfunc(response_str, searchstart)) - - # Start searching - # First the current response buffer - if 1 <= searchstart <= endof(response_str) - match = searchfunc(response_str, searchdata, searchstart) - if match != 0:-1 - seek(response_buffer, first(match) - 1) - return true - end - end - - # Now search all the other buffers - idxs = backwards ? ((hist.cur_idx-1):-1:1) : ((hist.cur_idx+1):length(hist.history)) - for idx in idxs - h = hist.history[idx] - match = searchfunc(h, searchdata) - if match != 0:-1 && h != response_str && haskey(hist.mode_mapping, hist.modes[idx]) - truncate(response_buffer, 0) - write(response_buffer, h) - seek(response_buffer, first(match) - 1) - hist.cur_idx = idx - return true - end - end - - return false -end - -function history_reset_state(hist::REPLHistoryProvider) - if hist.cur_idx != length(hist.history) + 1 - hist.last_idx = hist.cur_idx - hist.cur_idx = length(hist.history) + 1 - end -end -LineEdit.reset_state(hist::REPLHistoryProvider) = history_reset_state(hist) - -function return_callback(s) - ast = Base.syntax_deprecation_warnings(false) do - Base.parse_input_line(String(LineEdit.buffer(s))) - end - if !isa(ast, Expr) || (ast.head != :continue && ast.head != :incomplete) - return true - else - return false - end -end - -function find_hist_file() - filename = ".julia_history" - if isfile(filename) - return filename - elseif haskey(ENV, "JULIA_HISTORY") - return ENV["JULIA_HISTORY"] - else - return joinpath(homedir(), filename) - end -end - -backend(r::AbstractREPL) = r.backendref - -send_to_backend(ast, backend::REPLBackendRef) = send_to_backend(ast, backend.repl_channel, backend.response_channel) -function send_to_backend(ast, req, rep) - put!(req, (ast, 1)) - return take!(rep) # (val, bt) -end - -function respond(f, repl, main; pass_empty = false) - return function do_respond(s, buf, ok) - if !ok - return transition(s, :abort) - end - line = String(take!(buf)) - if !isempty(line) || pass_empty - reset(repl) - local val, bt - try - # note: value wrapped carefully here to ensure it doesn't get passed through expand - response = eval(Main, Expr(:body, Expr(:return, Expr(:call, QuoteNode(f), QuoteNode(line))))) - val, bt = send_to_backend(response, backend(repl)) - catch err - val = err - bt = catch_backtrace() - end - if !ends_with_semicolon(line) || bt !== nothing - print_response(repl, val, bt, true, Base.have_color) - end - end - prepare_next(repl) - reset_state(s) - s.current_mode.sticky || transition(s, main) - end -end - -function reset(repl::LineEditREPL) - raw!(repl.t, false) - print(repl.t,Base.text_colors[:normal]) -end - -function prepare_next(repl::LineEditREPL) - println(terminal(repl)) -end - -function mode_keymap(julia_prompt) - AnyDict( - '\b' => function (s,o...) - if isempty(s) || position(LineEdit.buffer(s)) == 0 - buf = copy(LineEdit.buffer(s)) - transition(s, julia_prompt) do - LineEdit.state(s, julia_prompt).input_buffer = buf - end - else - LineEdit.edit_backspace(s) - end - end, - "^C" => function (s,o...) - LineEdit.move_input_end(s) - LineEdit.refresh_line(s) - print(LineEdit.terminal(s), "^C\n\n") - transition(s, julia_prompt) - transition(s, :reset) - LineEdit.refresh_line(s) - end) -end - -repl_filename(repl, hp::REPLHistoryProvider) = "REPL[$(length(hp.history)-hp.start_idx)]" -repl_filename(repl, hp) = "REPL" - -const JL_PROMPT_PASTE = Ref(true) -enable_promptpaste(v::Bool) = JL_PROMPT_PASTE[] = v - -function setup_interface(repl::LineEditREPL; hascolor = repl.hascolor, extra_repl_keymap = Dict{Any,Any}[]) - ### - # - # This function returns the main interface that describes the REPL - # functionality, it is called internally by functions that setup a - # Terminal-based REPL frontend, but if you want to customize your REPL - # or embed the REPL in another interface, you may call this function - # directly and append it to your interface. - # - # Usage: - # - # repl_channel,response_channel = Channel(),Channel() - # start_repl_backend(repl_channel, response_channel) - # setup_interface(REPLDisplay(t),repl_channel,response_channel) - # - ### - - ### - # We setup the interface in two stages. - # First, we set up all components (prompt,rsearch,shell,help) - # Second, we create keymaps with appropriate transitions between them - # and assign them to the components - # - ### - - ############################### Stage I ################################ - - # This will provide completions for REPL and help mode - replc = REPLCompletionProvider() - - # Set up the main Julia prompt - julia_prompt = Prompt(JULIA_PROMPT; - # Copy colors from the prompt object - prompt_prefix = hascolor ? repl.prompt_color : "", - prompt_suffix = hascolor ? - (repl.envcolors ? Base.input_color : repl.input_color) : "", - keymap_func_data = repl, - complete = replc, - on_enter = return_callback) - - # Setup help mode - help_mode = Prompt("help?> ", - prompt_prefix = hascolor ? repl.help_color : "", - prompt_suffix = hascolor ? - (repl.envcolors ? Base.input_color : repl.input_color) : "", - keymap_func_data = repl, - complete = replc, - # When we're done transform the entered line into a call to help("$line") - on_done = respond(Docs.helpmode, repl, julia_prompt)) - - # Set up shell mode - shell_mode = Prompt("shell> "; - prompt_prefix = hascolor ? repl.shell_color : "", - prompt_suffix = hascolor ? - (repl.envcolors ? Base.input_color : repl.input_color) : "", - keymap_func_data = repl, - complete = ShellCompletionProvider(), - # Transform "foo bar baz" into `foo bar baz` (shell quoting) - # and pass into Base.repl_cmd for processing (handles `ls` and `cd` - # special) - on_done = respond(repl, julia_prompt) do line - Expr(:call, :(Base.repl_cmd), - :(Base.cmd_gen($(Base.shell_parse(line)[1]))), - outstream(repl)) - end) - - - ################################# Stage II ############################# - - # Setup history - # We will have a unified history for all REPL modes - hp = REPLHistoryProvider(Dict{Symbol,Any}(:julia => julia_prompt, - :shell => shell_mode, - :help => help_mode)) - if repl.history_file - try - hist_path = find_hist_file() - f = open(hist_path, true, true, true, false, false) - finalizer(replc, replc->close(f)) - hist_from_file(hp, f, hist_path) - catch e - print_response(repl, e, catch_backtrace(), true, Base.have_color) - println(outstream(repl)) - info("Disabling history file for this session.") - repl.history_file = false - end - end - history_reset_state(hp) - julia_prompt.hist = hp - shell_mode.hist = hp - help_mode.hist = hp - - julia_prompt.on_done = respond(x->Base.parse_input_line(x,filename=repl_filename(repl,hp)), repl, julia_prompt) - - - search_prompt, skeymap = LineEdit.setup_search_keymap(hp) - search_prompt.complete = LatexCompletions() - - # Canonicalize user keymap input - if isa(extra_repl_keymap, Dict) - extra_repl_keymap = [extra_repl_keymap] - end - - const repl_keymap = AnyDict( - ';' => function (s,o...) - if isempty(s) || position(LineEdit.buffer(s)) == 0 - buf = copy(LineEdit.buffer(s)) - transition(s, shell_mode) do - LineEdit.state(s, shell_mode).input_buffer = buf - end - else - edit_insert(s, ';') - end - end, - '?' => function (s,o...) - if isempty(s) || position(LineEdit.buffer(s)) == 0 - buf = copy(LineEdit.buffer(s)) - transition(s, help_mode) do - LineEdit.state(s, help_mode).input_buffer = buf - end - else - edit_insert(s, '?') - end - end, - - # Bracketed Paste Mode - "\e[200~" => (s,o...)->begin - input = LineEdit.bracketed_paste(s) # read directly from s until reaching the end-bracketed-paste marker - sbuffer = LineEdit.buffer(s) - curspos = position(sbuffer) - seek(sbuffer, 0) - shouldeval = (nb_available(sbuffer) == curspos && search(sbuffer, UInt8('\n')) == 0) - seek(sbuffer, curspos) - if curspos == 0 - # if pasting at the beginning, strip leading whitespace - input = lstrip(input) - end - if !shouldeval - # when pasting in the middle of input, just paste in place - # don't try to execute all the WIP, since that's rather confusing - # and is often ill-defined how it should behave - edit_insert(s, input) - return - end - edit_insert(sbuffer, input) - input = String(take!(sbuffer)) - oldpos = start(input) - firstline = true - isprompt_paste = false - while !done(input, oldpos) # loop until all lines have been executed - if JL_PROMPT_PASTE[] - # Check if the next statement starts with "julia> ", in that case - # skip it. But first skip whitespace - while input[oldpos] in ('\n', ' ', '\t') - oldpos = nextind(input, oldpos) - oldpos >= sizeof(input) && return - end - # Check if input line starts with "julia> ", remove it if we are in prompt paste mode - jl_prompt_len = 7 - if (firstline || isprompt_paste) && (oldpos + jl_prompt_len <= sizeof(input) && input[oldpos:oldpos+jl_prompt_len-1] == JULIA_PROMPT) - isprompt_paste = true - oldpos += jl_prompt_len - # If we are prompt pasting and current statement does not begin with julia> , skip to next line - elseif isprompt_paste - while input[oldpos] != '\n' - oldpos = nextind(input, oldpos) - oldpos >= sizeof(input) && return - end - continue - end - end - ast, pos = Base.syntax_deprecation_warnings(false) do - Base.parse(input, oldpos, raise=false) - end - if (isa(ast, Expr) && (ast.head == :error || ast.head == :continue || ast.head == :incomplete)) || - (done(input, pos) && !endswith(input, '\n')) - # remaining text is incomplete (an error, or parser ran to the end but didn't stop with a newline): - # Insert all the remaining text as one line (might be empty) - tail = input[oldpos:end] - if !firstline - # strip leading whitespace, but only if it was the result of executing something - # (avoids modifying the user's current leading wip line) - tail = lstrip(tail) - end - LineEdit.replace_line(s, tail) - LineEdit.refresh_line(s) - break - end - # get the line and strip leading and trailing whitespace - line = strip(input[oldpos:prevind(input, pos)]) - if !isempty(line) - # put the line on the screen and history - LineEdit.replace_line(s, line) - LineEdit.commit_line(s) - # execute the statement - terminal = LineEdit.terminal(s) # This is slightly ugly but ok for now - raw!(terminal, false) && disable_bracketed_paste(terminal) - LineEdit.mode(s).on_done(s, LineEdit.buffer(s), true) - raw!(terminal, true) && enable_bracketed_paste(terminal) - end - oldpos = pos - firstline = false - end - end, - - # Open the editor at the location of a stackframe - # This is accessing a global variable that gets set in - # the show_backtrace function. - "^Q" => (s, o...) -> begin - linfos = Base.LAST_BACKTRACE_LINE_INFOS - str = String(take!(LineEdit.buffer(s))) - n = tryparse(Int, str) - isnull(n) && @goto writeback - n = get(n) - if n <= 0 || n > length(linfos) || startswith(linfos[n][1], "./REPL") - @goto writeback - end - Base.edit(linfos[n][1], linfos[n][2]) - Base.LineEdit.refresh_line(s) - return - @label writeback - write(Base.LineEdit.buffer(s), str) - return - end, - ) - - prefix_prompt, prefix_keymap = LineEdit.setup_prefix_keymap(hp, julia_prompt) - - a = Dict{Any,Any}[skeymap, repl_keymap, prefix_keymap, LineEdit.history_keymap, LineEdit.default_keymap, LineEdit.escape_defaults] - prepend!(a, extra_repl_keymap) - - julia_prompt.keymap_dict = LineEdit.keymap(a) - - mk = mode_keymap(julia_prompt) - - b = Dict{Any,Any}[skeymap, mk, prefix_keymap, LineEdit.history_keymap, LineEdit.default_keymap, LineEdit.escape_defaults] - prepend!(b, extra_repl_keymap) - - shell_mode.keymap_dict = help_mode.keymap_dict = LineEdit.keymap(b) - - ModalInterface([julia_prompt, shell_mode, help_mode, search_prompt, prefix_prompt]) -end - -function run_frontend(repl::LineEditREPL, backend) - d = REPLDisplay(repl) - dopushdisplay = repl.specialdisplay === nothing && !in(d,Base.Multimedia.displays) - dopushdisplay && pushdisplay(d) - if !isdefined(repl,:interface) - interface = repl.interface = setup_interface(repl) - else - interface = repl.interface - end - repl.backendref = backend - run_interface(repl.t, interface) - dopushdisplay && popdisplay(d) -end - -if isdefined(Base, :banner_color) - banner(io, t) = banner(io, hascolor(t)) - banner(io, x::Bool) = print(io, x ? Base.banner_color : Base.banner_plain) -else - banner(io,t) = Base.banner(io) -end - -## StreamREPL ## - -mutable struct StreamREPL <: AbstractREPL - stream::IO - prompt_color::String - input_color::String - answer_color::String - waserror::Bool - StreamREPL(stream,pc,ic,ac) = new(stream,pc,ic,ac,false) -end -StreamREPL(stream::IO) = StreamREPL(stream, Base.text_colors[:green], Base.input_color(), Base.answer_color()) -run_repl(stream::IO) = run_repl(StreamREPL(stream)) - -outstream(s::StreamREPL) = s.stream - -answer_color(r::LineEditREPL) = r.envcolors ? Base.answer_color() : r.answer_color -answer_color(r::StreamREPL) = r.answer_color -input_color(r::LineEditREPL) = r.envcolors ? Base.input_color() : r.input_color -input_color(r::StreamREPL) = r.input_color - -# heuristic function to decide if the presence of a semicolon -# at the end of the expression was intended for suppressing output -function ends_with_semicolon(line) - match = rsearch(line, ';') - if match != 0 - # state for comment parser, assuming that the `;` isn't in a string or comment - # so input like ";#" will still thwart this to give the wrong (anti-conservative) answer - comment = false - comment_start = false - comment_close = false - comment_multi = 0 - for c in line[(match + 1):end] - if comment_multi > 0 - # handle nested multi-line comments - if comment_close && c == '#' - comment_close = false - comment_multi -= 1 - elseif comment_start && c == '=' - comment_start = false - comment_multi += 1 - else - comment_start = (c == '#') - comment_close = (c == '=') - end - elseif comment - # handle line comments - if c == '\r' || c == '\n' - comment = false - end - elseif comment_start - # see what kind of comment this is - comment_start = false - if c == '=' - comment_multi = 1 - else - comment = true - end - elseif c == '#' - # start handling for a comment - comment_start = true - else - # outside of a comment, encountering anything but whitespace - # means the semi-colon was internal to the expression - isspace(c) || return false - end - end - return true - end - return false -end - -function run_frontend(repl::StreamREPL, backend::REPLBackendRef) - have_color = Base.have_color - banner(repl.stream, have_color) - d = REPLDisplay(repl) - dopushdisplay = !in(d,Base.Multimedia.displays) - dopushdisplay && pushdisplay(d) - repl_channel, response_channel = backend.repl_channel, backend.response_channel - while !eof(repl.stream) - if have_color - print(repl.stream,repl.prompt_color) - end - print(repl.stream, "julia> ") - if have_color - print(repl.stream, input_color(repl)) - end - line = readline(repl.stream, chomp=false) - if !isempty(line) - ast = Base.parse_input_line(line) - if have_color - print(repl.stream, Base.color_normal) - end - put!(repl_channel, (ast, 1)) - val, bt = take!(response_channel) - if !ends_with_semicolon(line) - print_response(repl, val, bt, true, have_color) - end - end - end - # Terminate Backend - put!(repl_channel, (nothing, -1)) - dopushdisplay && popdisplay(d) -end - -function start_repl_server(port) - listen(port) do server, status - client = accept(server) - run_repl(client) - end -end - -end # module diff --git a/julia-0.6.3/share/julia/base/REPLCompletions.jl b/julia-0.6.3/share/julia/base/REPLCompletions.jl deleted file mode 100644 index 7f0f03c..0000000 --- a/julia-0.6.3/share/julia/base/REPLCompletions.jl +++ /dev/null @@ -1,599 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -module REPLCompletions - -export completions, shell_completions, bslash_completions - -using Base.Meta - -function completes_global(x, name) - return startswith(x, name) && !('#' in x) -end - -function filtered_mod_names(ffunc::Function, mod::Module, name::AbstractString, all::Bool=false, imported::Bool=false) - ssyms = names(mod, all, imported) - filter!(ffunc, ssyms) - syms = String[string(s) for s in ssyms] - filter!(x->completes_global(x, name), syms) -end - -# REPL Symbol Completions -function complete_symbol(sym, ffunc) - # Maybe be smarter in the future - context_module = Main - mod = context_module - name = sym - - lookup_module = true - t = Union{} - if rsearch(sym, non_identifier_chars) < rsearch(sym, '.') - # Find module - lookup_name, name = rsplit(sym, ".", limit=2) - - ex = Base.syntax_deprecation_warnings(false) do - parse(lookup_name, raise=false) - end - - b, found = get_value(ex, context_module) - if found - if isa(b, Module) - mod = b - lookup_module = true - elseif Base.isstructtype(typeof(b)) - lookup_module = false - t = typeof(b) - end - else # If the value is not found using get_value, the expression contain an advanced expression - lookup_module = false - t, found = get_type(ex, context_module) - end - found || return String[] - # Ensure REPLCompletion do not crash when asked to complete a tuple, #15329 - !lookup_module && t <: Tuple && return String[] - end - - suggestions = String[] - if lookup_module - # We will exclude the results that the user does not want, as well - # as excluding Main.Main.Main, etc., because that's most likely not what - # the user wants - p = s->(!Base.isdeprecated(mod, s) && s != module_name(mod) && ffunc(mod, s)) - # Looking for a binding in a module - if mod == context_module - # Also look in modules we got through `using` - mods = ccall(:jl_module_usings, Any, (Any,), Main) - for m in mods - append!(suggestions, filtered_mod_names(p, m, name)) - end - append!(suggestions, filtered_mod_names(p, mod, name, true, true)) - else - append!(suggestions, filtered_mod_names(p, mod, name, true, false)) - end - else - # Looking for a member of a type - fields = fieldnames(t) - for field in fields - s = string(field) - if startswith(s, name) - push!(suggestions, s) - end - end - end - suggestions -end - -function complete_keyword(s::String) - const sorted_keywords = [ - "abstract type", "baremodule", "begin", "break", "catch", "ccall", - "const", "continue", "do", "else", "elseif", "end", "export", "false", - "finally", "for", "function", "global", "if", "import", - "importall", "let", "local", "macro", "module", "mutable struct", - "primitive type", "quote", "return", "struct", - "true", "try", "using", "while"] - r = searchsorted(sorted_keywords, s) - i = first(r) - n = length(sorted_keywords) - while i <= n && startswith(sorted_keywords[i],s) - r = first(r):i - i += 1 - end - sorted_keywords[r] -end - -function complete_path(path::AbstractString, pos; use_envpath=false) - if Base.is_unix() && ismatch(r"^~(?:/|$)", path) - # if the path is just "~", don't consider the expanded username as a prefix - if path == "~" - dir, prefix = homedir(), "" - else - dir, prefix = splitdir(homedir() * path[2:end]) - end - else - dir, prefix = splitdir(path) - end - local files - try - if isempty(dir) - files = readdir() - elseif isdir(dir) - files = readdir(dir) - else - return String[], 0:-1, false - end - catch - return String[], 0:-1, false - end - - matches = Set{String}() - for file in files - if startswith(file, prefix) - id = try isdir(joinpath(dir, file)) catch; false end - # joinpath is not used because windows needs to complete with double-backslash - push!(matches, id ? file * (@static is_windows() ? "\\\\" : "/") : file) - end - end - - if use_envpath && length(dir) == 0 - # Look for files in PATH as well - local pathdirs = split(ENV["PATH"], @static is_windows() ? ";" : ":") - - for pathdir in pathdirs - local actualpath - try - actualpath = realpath(pathdir) - catch - # Bash doesn't expect every folder in PATH to exist, so neither shall we - continue - end - - if actualpath != pathdir && in(actualpath,pathdirs) - # Remove paths which (after resolving links) are in the env path twice. - # Many distros eg. point /bin to /usr/bin but have both in the env path. - continue - end - - local filesinpath - try - filesinpath = readdir(pathdir) - catch e - # Bash allows dirs in PATH that can't be read, so we should as well. - if isa(e, SystemError) - continue - else - # We only handle SystemErrors here - rethrow(e) - end - end - - for file in filesinpath - # In a perfect world, we would filter on whether the file is executable - # here, or even on whether the current user can execute the file in question. - if startswith(file, prefix) && isfile(joinpath(pathdir, file)) - push!(matches, file) - end - end - end - end - - matchList = String[replace(s, r"\s", "\\ ") for s in matches] - startpos = pos - endof(prefix) + 1 - length(matchall(r" ", prefix)) - # The pos - endof(prefix) + 1 is correct due to `endof(prefix)-endof(prefix)==0`, - # hence we need to add one to get the first index. This is also correct when considering - # pos, because pos is the `endof` a larger string which `endswith(path)==true`. - return matchList, startpos:pos, !isempty(matchList) -end - -# Determines whether method_complete should be tried. It should only be done if -# the string endswiths ',' or '(' when disregarding whitespace_chars -function should_method_complete(s::AbstractString) - method_complete = false - for c in reverse(s) - if c in [',', '('] - method_complete = true - break - elseif !(c in whitespace_chars) - method_complete = false - break - end - end - method_complete -end - -# Returns a range that includes the method name in front of the first non -# closed start brace from the end of the string. -function find_start_brace(s::AbstractString; c_start='(', c_end=')') - braces = 0 - r = RevString(s) - i = start(r) - in_single_quotes = false - in_double_quotes = false - in_back_ticks = false - while !done(r, i) - c, i = next(r, i) - if !in_single_quotes && !in_double_quotes && !in_back_ticks - if c == c_start - braces += 1 - elseif c == c_end - braces -= 1 - elseif c == '\'' - in_single_quotes = true - elseif c == '"' - in_double_quotes = true - elseif c == '`' - in_back_ticks = true - end - else - if !in_back_ticks && !in_double_quotes && c == '\'' && !done(r, i) && next(r, i)[1]!='\\' - in_single_quotes = !in_single_quotes - elseif !in_back_ticks && !in_single_quotes && c == '"' && !done(r, i) && next(r, i)[1]!='\\' - in_double_quotes = !in_double_quotes - elseif !in_single_quotes && !in_double_quotes && c == '`' && !done(r, i) && next(r, i)[1]!='\\' - in_back_ticks = !in_back_ticks - end - end - braces == 1 && break - end - braces != 1 && return 0:-1, -1 - method_name_end = reverseind(r, i) - startind = nextind(s, rsearch(s, non_identifier_chars, method_name_end)) - return (startind:endof(s), method_name_end) -end - -# Returns the value in a expression if sym is defined in current namespace fn. -# This method is used to iterate to the value of a expression like: -# :(Base.REPLCompletions.whitespace_chars) a `dump` of this expression -# will show it consist of Expr, QuoteNode's and Symbol's which all needs to -# be handled differently to iterate down to get the value of whitespace_chars. -function get_value(sym::Expr, fn) - sym.head != :. && return (nothing, false) - for ex in sym.args - fn, found = get_value(ex, fn) - !found && return (nothing, false) - end - return (fn, true) -end -get_value(sym::Symbol, fn) = isdefined(fn, sym) ? (getfield(fn, sym), true) : (nothing, false) -get_value(sym::QuoteNode, fn) = isdefined(fn, sym.value) ? (getfield(fn, sym.value), true) : (nothing, false) -get_value(sym, fn) = (sym, true) - -# Return the value of a getfield call expression -function get_value_getfield(ex::Expr, fn) - # Example :((top(getfield))(Base,:max)) - val, found = get_value_getfield(ex.args[2],fn) #Look up Base in Main and returns the module - found || return (nothing, false) - return get_value_getfield(ex.args[3], val) #Look up max in Base and returns the function if found. -end -get_value_getfield(sym, fn) = get_value(sym, fn) - -# Determines the return type with Base.return_types of a function call using the type information of the arguments. -function get_type_call(expr::Expr) - f_name = expr.args[1] - # The if statement should find the f function. How f is found depends on how f is referenced - if isa(f_name, GlobalRef) && isconst(f_name.mod,f_name.name) && isdefined(f_name.mod,f_name.name) - ft = typeof(eval(f_name)) - found = true - else - ft, found = get_type(f_name, Main) - end - found || return (Any, false) # If the function f is not found return Any. - args = Any[] - for ex in expr.args[2:end] # Find the type of the function arguments - typ, found = get_type(ex, Main) - found ? push!(args, typ) : push!(args, Any) - end - # use _methods_by_ftype as the function is supplied as a type - world = ccall(:jl_get_world_counter, UInt, ()) - mt = Base._methods_by_ftype(Tuple{ft, args...}, -1, world) - length(mt) == 1 || return (Any, false) - m = first(mt) - # Typeinference - params = Core.Inference.InferenceParams(world) - return_type = Core.Inference.typeinf_type(m[3], m[1], m[2], true, params) - return_type === nothing && return (Any, false) - return (return_type, true) -end -# Returns the return type. example: get_type(:(Base.strip("",' ')),Main) returns (String,true) -function get_type(sym::Expr, fn) - sym=expand(sym) - val, found = get_value(sym, fn) - found && return Base.typesof(val).parameters[1], found - if sym.head === :call - # getfield call is special cased as the evaluation of getfield provides good type information, - # is inexpensive and it is also performed in the complete_symbol function. - a1 = sym.args[1] - if isa(a1,GlobalRef) && isconst(a1.mod,a1.name) && isdefined(a1.mod,a1.name) && - eval(a1) === Core.getfield - val, found = get_value_getfield(sym, Main) - return found ? Base.typesof(val).parameters[1] : Any, found - end - return get_type_call(sym) - end - return (Any, false) -end -function get_type(sym, fn) - val, found = get_value(sym, fn) - return found ? Base.typesof(val).parameters[1] : Any, found -end -# Method completion on function call expression that look like :(max(1)) -function complete_methods(ex_org::Expr) - args_ex = Any[] - func, found = get_value(ex_org.args[1], Main) - !found && return String[] - for ex in ex_org.args[2:end] - val, found = get_type(ex, Main) - push!(args_ex, val) - end - out = String[] - t_in = Tuple{Core.Typeof(func), args_ex...} # Input types - na = length(args_ex)+1 - ml = methods(func) - kwtype = isdefined(ml.mt, :kwsorter) ? Nullable{DataType}(typeof(ml.mt.kwsorter)) : Nullable{DataType}() - io = IOBuffer() - for method in ml - ms = method.sig - - # Do not suggest the default method from sysimg.jl. - if Base.is_default_method(method) - continue - end - - # Check if the method's type signature intersects the input types - if typeintersect(Base.rewrap_unionall(Tuple{Base.unwrap_unionall(ms).parameters[1 : min(na, end)]...}, ms), t_in) != Union{} - show(io, method, kwtype=kwtype) - push!(out, String(take!(io))) - end - end - return out -end - -include("latex_symbols.jl") -include("emoji_symbols.jl") - -const non_identifier_chars = [" \t\n\r\"\\'`\$><=:;|&{}()[],+-*/?%^~"...] -const whitespace_chars = [" \t\n\r"...] -# "\"'`"... is added to whitespace_chars as non of the bslash_completions -# characters contain any of these characters. It prohibits the -# bslash_completions function to try and complete on escaped characters in strings -const bslash_separators = [whitespace_chars..., "\"'`"...] - -# Aux function to detect whether we're right after a -# using or import keyword -function afterusing(string::String, startpos::Int) - (isempty(string) || startpos == 0) && return false - str = string[1:prevind(string,startpos)] - isempty(str) && return false - rstr = reverse(str) - r = search(rstr, r"\s(gnisu|tropmi)\b") - isempty(r) && return false - fr = reverseind(str, last(r)) - return ismatch(r"^\b(using|import)\s*(\w+\s*,\s*)*\w*$", str[fr:end]) -end - -function bslash_completions(string, pos) - slashpos = rsearch(string, '\\', pos) - if (rsearch(string, bslash_separators, pos) < slashpos && - !(1 < slashpos && (string[prevind(string, slashpos)]=='\\'))) - # latex / emoji symbol substitution - s = string[slashpos:pos] - latex = get(latex_symbols, s, "") - if !isempty(latex) # complete an exact match - return (true, ([latex], slashpos:pos, true)) - end - emoji = get(emoji_symbols, s, "") - if !isempty(emoji) - return (true, ([emoji], slashpos:pos, true)) - end - # return possible matches; these cannot be mixed with regular - # Julian completions as only latex / emoji symbols contain the leading \ - if startswith(s, "\\:") # emoji - emoji_names = Iterators.filter(k -> startswith(k, s), keys(emoji_symbols)) - return (true, (sort!(collect(emoji_names)), slashpos:pos, true)) - else # latex - latex_names = Iterators.filter(k -> startswith(k, s), keys(latex_symbols)) - return (true, (sort!(collect(latex_names)), slashpos:pos, true)) - end - end - return (false, (String[], 0:-1, false)) -end - -function dict_identifier_key(str,tag) - if tag === :string - str_close = str*"\"" - elseif tag === :cmd - str_close = str*"`" - else - str_close = str - end - - frange, end_of_indentifier = find_start_brace(str_close, c_start='[', c_end=']') - isempty(frange) && return (nothing, nothing, nothing) - obj = Main - for name in split(str[frange[1]:end_of_indentifier], '.') - Base.isidentifier(name) || return (nothing, nothing, nothing) - sym = Symbol(name) - isdefined(obj, sym) || return (nothing, nothing, nothing) - obj = getfield(obj, sym) - # Avoid `isdefined(::Array, ::Symbol)` - isa(obj, Array) && return (nothing, nothing, nothing) - end - begin_of_key = findnext(x->!in(x,whitespace_chars), str, end_of_indentifier+2) - begin_of_key==0 && return (true, nothing, nothing) - partial_key = str[begin_of_key:end] - (isa(obj, Associative) && length(obj) < 1e6) || return (true, nothing, nothing) - return (obj, partial_key, begin_of_key) -end - -# This needs to be a separate non-inlined function, see #19441 -@noinline function find_dict_matches(identifier, partial_key) - matches = [] - for key in keys(identifier) - rkey = repr(key) - startswith(rkey,partial_key) && push!(matches,rkey) - end - return matches -end - -function completions(string, pos) - # First parse everything up to the current position - partial = string[1:pos] - inc_tag = Base.syntax_deprecation_warnings(false) do - Base.incomplete_tag(parse(partial, raise=false)) - end - - # if completing a key in a Dict - identifier, partial_key, loc = dict_identifier_key(partial,inc_tag) - if identifier !== nothing - if partial_key !== nothing - matches = find_dict_matches(identifier, partial_key) - length(matches)==1 && (length(string) <= pos || string[pos+1] != ']') && (matches[1]*="]") - length(matches)>0 && return sort!(matches), loc:pos, true - else - return String[], 0:-1, false - end - end - - # otherwise... - if inc_tag in [:cmd, :string] - m = match(r"[\t\n\r\"'`@\$><=;|&\{]| (?!\\)", reverse(partial)) - startpos = nextind(partial, reverseind(partial, m.offset)) - r = startpos:pos - paths, r, success = complete_path(replace(string[r], r"\\ ", " "), pos) - if inc_tag == :string && - length(paths) == 1 && # Only close if there's a single choice, - !isdir(expanduser(replace(string[startpos:start(r)-1] * paths[1], r"\\ ", " "))) && # except if it's a directory - (length(string) <= pos || string[pos+1] != '"') # or there's already a " at the cursor. - paths[1] *= "\"" - end - #Latex symbols can be completed for strings - (success || inc_tag==:cmd) && return sort!(paths), r, success - end - - ok, ret = bslash_completions(string, pos) - ok && return ret - - # Make sure that only bslash_completions is working on strings - inc_tag==:string && return String[], 0:-1, false - - if inc_tag == :other && should_method_complete(partial) - frange, method_name_end = find_start_brace(partial) - ex = Base.syntax_deprecation_warnings(false) do - parse(partial[frange] * ")", raise=false) - end - if isa(ex, Expr) && ex.head==:call - return complete_methods(ex), start(frange):method_name_end, false - end - elseif inc_tag == :comment - return String[], 0:-1, false - end - - dotpos = rsearch(string, '.', pos) - startpos = nextind(string, rsearch(string, non_identifier_chars, pos)) - - ffunc = (mod,x)->true - suggestions = String[] - comp_keywords = true - if afterusing(string, startpos) - # We're right after using or import. Let's look only for packages - # and modules we can reach from here - - # If there's no dot, we're in toplevel, so we should - # also search for packages - s = string[startpos:pos] - if dotpos <= startpos - for dir in [Pkg.dir(); LOAD_PATH; pwd()] - dir isa AbstractString && isdir(dir) || continue - for pname in readdir(dir) - if pname[1] != '.' && pname != "METADATA" && - pname != "REQUIRE" && startswith(pname, s) - # Valid file paths are - # .jl - # /src/.jl - # .jl/src/.jl - if isfile(joinpath(dir, pname)) - endswith(pname, ".jl") && push!(suggestions, pname[1:end-3]) - else - mod_name = if endswith(pname, ".jl") - pname[1:end - 3] - else - pname - end - if isfile(joinpath(dir, pname, "src", - "$mod_name.jl")) - push!(suggestions, mod_name) - end - end - end - end - end - end - ffunc = (mod,x)->(isdefined(mod, x) && isa(getfield(mod, x), Module)) - comp_keywords = false - end - startpos == 0 && (pos = -1) - dotpos < startpos && (dotpos = startpos - 1) - s = string[startpos:pos] - comp_keywords && append!(suggestions, complete_keyword(s)) - # The case where dot and start pos is equal could look like: "(""*"").d","". or CompletionFoo.test_y_array[1].y - # This case can be handled by finding the begining of the expresion. This is done bellow. - if dotpos == startpos - i = prevind(string, startpos) - while 0 < i - c = string[i] - if c in [')', ']'] - if c==')' - c_start='('; c_end=')' - elseif c==']' - c_start='['; c_end=']' - end - frange, end_of_indentifier = find_start_brace(string[1:prevind(string, i)], c_start=c_start, c_end=c_end) - startpos = start(frange) - i = prevind(string, startpos) - elseif c in ["\'\"\`"...] - s = "$c$c"*string[startpos:pos] - break - else - break - end - s = string[startpos:pos] - end - end - append!(suggestions, complete_symbol(s, ffunc)) - return sort!(unique(suggestions)), (dotpos+1):pos, true -end - -function shell_completions(string, pos) - # First parse everything up to the current position - scs = string[1:pos] - local args, last_parse - try - args, last_parse = Base.shell_parse(scs, true) - catch - return String[], 0:-1, false - end - # Now look at the last thing we parsed - isempty(args.args[end].args) && return String[], 0:-1, false - arg = args.args[end].args[end] - if all(s -> isa(s, AbstractString), args.args[end].args) - # Treat this as a path - - # As Base.shell_parse throws away trailing spaces (unless they are escaped), - # we need to special case here. - # If the last char was a space, but shell_parse ignored it search on "". - ignore_last_word = arg != " " && scs[end] == ' ' - prefix = ignore_last_word ? "" : join(args.args[end].args) - - # Also try looking into the env path if the user wants to complete the first argument - use_envpath = !ignore_last_word && length(args.args) < 2 - - return complete_path(prefix, pos, use_envpath=use_envpath) - elseif isexpr(arg, :incomplete) || isexpr(arg, :error) - r = first(last_parse):prevind(last_parse, last(last_parse)) - partial = scs[r] - ret, range = completions(partial, endof(partial)) - range += first(r) - 1 - return ret, range, true - end - return String[], 0:-1, false -end - -end # module diff --git a/julia-0.6.3/share/julia/base/Terminals.jl b/julia-0.6.3/share/julia/base/Terminals.jl deleted file mode 100644 index 479d3c3..0000000 --- a/julia-0.6.3/share/julia/base/Terminals.jl +++ /dev/null @@ -1,172 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -module Terminals - -export - TextTerminal, - UnixTerminal, - TerminalBuffer, - TTYTerminal, - cmove, - cmove_col, - cmove_down, - cmove_left, - cmove_line_down, - cmove_line_up, - cmove_right, - cmove_up, - disable_bracketed_paste, - enable_bracketed_paste, - end_keypad_transmit_mode, - getX, - getY, - hascolor, - pos, - raw! - -import Base: - check_open, # stream.jl - displaysize, - flush, - pipe_reader, - pipe_writer, - read, - readuntil - -## TextTerminal ## - -abstract type TextTerminal <: Base.AbstractPipe end - -# INTERFACE -pipe_reader(::TextTerminal) = error("Unimplemented") -pipe_writer(::TextTerminal) = error("Unimplemented") -displaysize(::TextTerminal) = error("Unimplemented") -cmove(t::TextTerminal, x, y) = error("Unimplemented") -getX(t::TextTerminal) = error("Unimplemented") -getY(t::TextTerminal) = error("Unimplemented") -pos(t::TextTerminal) = (getX(t), getY(t)) - -# Relative moves (Absolute position fallbacks) -cmove_up(t::TextTerminal, n) = cmove(getX(t), max(1, getY(t)-n)) -cmove_up(t) = cmove_up(t, 1) - -cmove_down(t::TextTerminal, n) = cmove(getX(t), max(height(t), getY(t)+n)) -cmove_down(t) = cmove_down(t, 1) - -cmove_left(t::TextTerminal, n) = cmove(max(1, getX(t)-n), getY(t)) -cmove_left(t) = cmove_left(t, 1) - -cmove_right(t::TextTerminal, n) = cmove(max(width(t), getX(t)+n), getY(t)) -cmove_right(t) = cmove_right(t, 1) - -cmove_line_up(t::TextTerminal, n) = cmove(1, max(1, getY(t)-n)) -cmove_line_up(t) = cmove_line_up(t, 1) - -cmove_line_down(t::TextTerminal, n) = cmove(1, max(height(t), getY(t)+n)) -cmove_line_down(t) = cmove_line_down(t, 1) - -cmove_col(t::TextTerminal, c) = cmove(c, getY(t)) - -# Defaults -hascolor(::TextTerminal) = false - -# Utility Functions -width(t::TextTerminal) = displaysize(t)[2] -height(t::TextTerminal) = displaysize(t)[1] - -# For terminals with buffers -flush(t::TextTerminal) = nothing - -clear(t::TextTerminal) = error("Unimplemented") -clear_line(t::TextTerminal, row) = error("Unimplemented") -clear_line(t::TextTerminal) = error("Unimplemented") - -raw!(t::TextTerminal, raw::Bool) = error("Unimplemented") - -beep(t::TextTerminal) = nothing -enable_bracketed_paste(t::TextTerminal) = nothing -disable_bracketed_paste(t::TextTerminal) = nothing - -## UnixTerminal ## - -abstract type UnixTerminal <: TextTerminal end - -pipe_reader(t::UnixTerminal) = t.in_stream -pipe_writer(t::UnixTerminal) = t.out_stream - -mutable struct TerminalBuffer <: UnixTerminal - out_stream::Base.IO -end - -mutable struct TTYTerminal <: UnixTerminal - term_type::String - in_stream::IO - out_stream::IO - err_stream::IO -end - -const CSI = "\x1b[" - -cmove_up(t::UnixTerminal, n) = write(t.out_stream, "$(CSI)$(n)A") -cmove_down(t::UnixTerminal, n) = write(t.out_stream, "$(CSI)$(n)B") -cmove_right(t::UnixTerminal, n) = write(t.out_stream, "$(CSI)$(n)C") -cmove_left(t::UnixTerminal, n) = write(t.out_stream, "$(CSI)$(n)D") -cmove_line_up(t::UnixTerminal, n) = (cmove_up(t, n); cmove_col(t, 1)) -cmove_line_down(t::UnixTerminal, n) = (cmove_down(t, n); cmove_col(t, 1)) -cmove_col(t::UnixTerminal, n) = (write(t.out_stream, '\r'); n > 1 && cmove_right(t, n - 1)) - -if is_windows() - function raw!(t::TTYTerminal,raw::Bool) - check_open(t.in_stream) - if Base.ispty(t.in_stream) - run(if raw - `stty raw -echo onlcr -ocrnl opost` - else - `stty sane` - end,t.in_stream,t.out_stream,t.err_stream) - true - else - ccall(:jl_tty_set_mode, - Int32, (Ptr{Void},Int32), - t.in_stream.handle, raw) != -1 - end - end -else - function raw!(t::TTYTerminal, raw::Bool) - check_open(t.in_stream) - ccall(:jl_tty_set_mode, Int32, (Ptr{Void},Int32), t.in_stream.handle, raw) != -1 - end -end - -# eval some of these definitions to insert CSI as a constant string -@eval enable_bracketed_paste(t::UnixTerminal) = write(t.out_stream, $"$(CSI)?2004h") -@eval disable_bracketed_paste(t::UnixTerminal) = write(t.out_stream, $"$(CSI)?2004l") -@eval end_keypad_transmit_mode(t::UnixTerminal) = # tput rmkx - write(t.out_stream, $"$(CSI)?1l\x1b>") - -@eval clear(t::UnixTerminal) = write(t.out_stream, $"$(CSI)H$(CSI)2J") -@eval clear_line(t::UnixTerminal) = write(t.out_stream, $"\r$(CSI)0K") -#beep(t::UnixTerminal) = write(t.err_stream,"\x7") - -function Base.displaysize(t::UnixTerminal) - return displaysize(t.out_stream) -end - -if is_windows() - hascolor(t::TTYTerminal) = true -else - function hascolor(t::TTYTerminal) - startswith(t.term_type, "xterm") && return true - try - @static if Sys.KERNEL == :FreeBSD - return success(`tput AF 0`) - else - return success(`tput setaf 0`) - end - catch - return false - end - end -end - -end # module diff --git a/julia-0.6.3/share/julia/base/abstractarray.jl b/julia-0.6.3/share/julia/base/abstractarray.jl deleted file mode 100644 index 3318bc9..0000000 --- a/julia-0.6.3/share/julia/base/abstractarray.jl +++ /dev/null @@ -1,1978 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -## Basic functions ## - -""" - AbstractArray{T, N} - -Abstract array supertype which arrays inherit from. -""" -AbstractArray - -""" - size(A::AbstractArray, [dim...]) - -Returns a tuple containing the dimensions of `A`. Optionally you can specify the -dimension(s) you want the length of, and get the length of that dimension, or a tuple of the -lengths of dimensions you asked for. - -```jldoctest -julia> A = ones(2,3,4); - -julia> size(A, 2) -3 - -julia> size(A,3,2) -(4, 3) -``` -""" -size(t::AbstractArray{T,N}, d) where {T,N} = d <= N ? size(t)[d] : 1 -size(x, d1::Integer, d2::Integer, dx::Vararg{Integer, N}) where {N} = - (size(x, d1), size(x, d2), ntuple(k->size(x, dx[k]), Val{N})...) - -""" - indices(A, d) - -Returns the valid range of indices for array `A` along dimension `d`. - -```jldoctest -julia> A = ones(5,6,7); - -julia> indices(A,2) -Base.OneTo(6) -``` -""" -function indices(A::AbstractArray{T,N}, d) where {T,N} - @_inline_meta - d <= N ? indices(A)[d] : OneTo(1) -end - -""" - indices(A) - -Returns the tuple of valid indices for array `A`. - -```jldoctest -julia> A = ones(5,6,7); - -julia> indices(A) -(Base.OneTo(5), Base.OneTo(6), Base.OneTo(7)) -``` -""" -function indices(A) - @_inline_meta - map(OneTo, size(A)) -end - -# Performance optimization: get rid of a branch on `d` in `indices(A, -# d)` for d=1. 1d arrays are heavily used, and the first dimension -# comes up in other applications. -indices1(A::AbstractArray{<:Any,0}) = OneTo(1) -indices1(A::AbstractArray) = (@_inline_meta; indices(A)[1]) -indices1(iter) = OneTo(length(iter)) - -unsafe_indices(A) = indices(A) -unsafe_indices(r::Range) = (OneTo(unsafe_length(r)),) # Ranges use checked_sub for size - -""" - linearindices(A) - -Returns a `UnitRange` specifying the valid range of indices for `A[i]` -where `i` is an `Int`. For arrays with conventional indexing (indices -start at 1), or any multidimensional array, this is `1:length(A)`; -however, for one-dimensional arrays with unconventional indices, this -is `indices(A, 1)`. - -Calling this function is the "safe" way to write algorithms that -exploit linear indexing. - -```jldoctest -julia> A = ones(5,6,7); - -julia> b = linearindices(A); - -julia> extrema(b) -(1, 210) -``` -""" -linearindices(A) = (@_inline_meta; OneTo(_length(A))) -linearindices(A::AbstractVector) = (@_inline_meta; indices1(A)) -eltype(::Type{<:AbstractArray{E}}) where {E} = E -elsize(::AbstractArray{T}) where {T} = sizeof(T) - -""" - ndims(A::AbstractArray) -> Integer - -Returns the number of dimensions of `A`. - -```jldoctest -julia> A = ones(3,4,5); - -julia> ndims(A) -3 -``` -""" -ndims(::AbstractArray{T,N}) where {T,N} = N -ndims(::Type{AbstractArray{T,N}}) where {T,N} = N -ndims(::Type{T}) where {T<:AbstractArray} = ndims(supertype(T)) - -""" - length(A::AbstractArray) -> Integer - -Returns the number of elements in `A`. - -```jldoctest -julia> A = ones(3,4,5); - -julia> length(A) -60 -``` -""" -length(t::AbstractArray) = (@_inline_meta; prod(size(t))) -_length(A::AbstractArray) = (@_inline_meta; prod(map(unsafe_length, indices(A)))) # circumvent missing size -_length(A) = (@_inline_meta; length(A)) -endof(a::AbstractArray) = (@_inline_meta; last(linearindices(a))) -first(a::AbstractArray) = a[first(eachindex(a))] - -""" - first(coll) - -Get the first element of an iterable collection. Returns the start point of a -`Range` even if it is empty. - -```jldoctest -julia> first(2:2:10) -2 - -julia> first([1; 2; 3; 4]) -1 -``` -""" -function first(itr) - state = start(itr) - done(itr, state) && throw(ArgumentError("collection must be non-empty")) - next(itr, state)[1] -end - -""" - last(coll) - -Get the last element of an ordered collection, if it can be computed in O(1) time. This is -accomplished by calling [`endof`](@ref) to get the last index. Returns the end -point of a `Range` even if it is empty. - -```jldoctest -julia> last(1:2:10) -9 - -julia> last([1; 2; 3; 4]) -4 -``` -""" -last(a) = a[end] - -""" - stride(A, k::Integer) - -Returns the distance in memory (in number of elements) between adjacent elements in dimension `k`. - -```jldoctest -julia> A = ones(3,4,5); - -julia> stride(A,2) -3 - -julia> stride(A,3) -12 -``` -""" -function stride(a::AbstractArray, i::Integer) - if i > ndims(a) - return length(a) - end - s = 1 - for n = 1:(i-1) - s *= size(a, n) - end - return s -end - -""" - strides(A) - -Returns a tuple of the memory strides in each dimension. - -```jldoctest -julia> A = ones(3,4,5); - -julia> strides(A) -(1, 3, 12) -``` -""" -strides(A::AbstractArray) = _strides((1,), A) -_strides(out::Tuple{Int}, A::AbstractArray{<:Any,0}) = () -_strides(out::NTuple{N,Int}, A::AbstractArray{<:Any,N}) where {N} = out -function _strides(out::NTuple{M,Int}, A::AbstractArray) where M - @_inline_meta - _strides((out..., out[M]*size(A, M)), A) -end - -function isassigned(a::AbstractArray, i::Int...) - try - a[i...] - true - catch e - if isa(e, BoundsError) || isa(e, UndefRefError) - return false - else - rethrow(e) - end - end -end - -# used to compute "end" for last index -function trailingsize(A, n) - s = 1 - for i=n:ndims(A) - s *= size(A,i) - end - return s -end -function trailingsize(inds::Indices, n) - s = 1 - for i=n:length(inds) - s *= unsafe_length(inds[i]) - end - return s -end -# This version is type-stable even if inds is heterogeneous -function trailingsize(inds::Indices) - @_inline_meta - prod(map(unsafe_length, inds)) -end - -## Traits for array types ## - -abstract type IndexStyle end -struct IndexLinear <: IndexStyle end -struct IndexCartesian <: IndexStyle end - -""" - IndexStyle(A) - IndexStyle(typeof(A)) - -`IndexStyle` specifies the "native indexing style" for array `A`. When -you define a new `AbstractArray` type, you can choose to implement -either linear indexing or cartesian indexing. If you decide to -implement linear indexing, then you must set this trait for your array -type: - - Base.IndexStyle(::Type{<:MyArray}) = IndexLinear() - -The default is `IndexCartesian()`. - -Julia's internal indexing machinery will automatically (and invisibly) -convert all indexing operations into the preferred style using -[`sub2ind`](@ref) or [`ind2sub`](@ref). This allows users to access -elements of your array using any indexing style, even when explicit -methods have not been provided. - -If you define both styles of indexing for your `AbstractArray`, this -trait can be used to select the most performant indexing style. Some -methods check this trait on their inputs, and dispatch to different -algorithms depending on the most efficient access pattern. In -particular, [`eachindex`](@ref) creates an iterator whose type depends -on the setting of this trait. -""" -IndexStyle(A::AbstractArray) = IndexStyle(typeof(A)) -IndexStyle(::Type{Union{}}) = IndexLinear() -IndexStyle(::Type{<:AbstractArray}) = IndexCartesian() -IndexStyle(::Type{<:Array}) = IndexLinear() -IndexStyle(::Type{<:Range}) = IndexLinear() - -IndexStyle(A::AbstractArray, B::AbstractArray) = IndexStyle(IndexStyle(A), IndexStyle(B)) -IndexStyle(A::AbstractArray, B::AbstractArray...) = IndexStyle(IndexStyle(A), IndexStyle(B...)) -IndexStyle(::IndexLinear, ::IndexLinear) = IndexLinear() -IndexStyle(::IndexStyle, ::IndexStyle) = IndexCartesian() - -## Bounds checking ## - -# The overall hierarchy is -# `checkbounds(A, I...)` -> -# `checkbounds(Bool, A, I...)` -> -# `checkbounds_indices(Bool, IA, I)`, which recursively calls -# `checkindex` for each dimension -# -# See the "boundscheck" devdocs for more information. -# -# Note this hierarchy has been designed to reduce the likelihood of -# method ambiguities. We try to make `checkbounds` the place to -# specialize on array type, and try to avoid specializations on index -# types; conversely, `checkindex` is intended to be specialized only -# on index type (especially, its last argument). - -""" - checkbounds(Bool, A, I...) - -Return `true` if the specified indices `I` are in bounds for the given -array `A`. Subtypes of `AbstractArray` should specialize this method -if they need to provide custom bounds checking behaviors; however, in -many cases one can rely on `A`'s indices and [`checkindex`](@ref). - -See also [`checkindex`](@ref). - -```jldoctest -julia> A = rand(3, 3); - -julia> checkbounds(Bool, A, 2) -true - -julia> checkbounds(Bool, A, 3, 4) -false - -julia> checkbounds(Bool, A, 1:3) -true - -julia> checkbounds(Bool, A, 1:3, 2:4) -false -``` -""" -function checkbounds(::Type{Bool}, A::AbstractArray, I...) - @_inline_meta - checkbounds_indices(Bool, indices(A), I) -end -# Linear indexing is explicitly allowed when there is only one (non-cartesian) index -function checkbounds(::Type{Bool}, A::AbstractArray, i) - @_inline_meta - checkindex(Bool, linearindices(A), i) -end -# As a special extension, allow using logical arrays that match the source array exactly -function checkbounds(::Type{Bool}, A::AbstractArray{<:Any,N}, I::AbstractArray{Bool,N}) where N - @_inline_meta - indices(A) == indices(I) -end - -""" - checkbounds(A, I...) - -Throw an error if the specified indices `I` are not in bounds for the given array `A`. -""" -function checkbounds(A::AbstractArray, I...) - @_inline_meta - checkbounds(Bool, A, I...) || throw_boundserror(A, I) - nothing -end -checkbounds(A::AbstractArray) = checkbounds(A, 1) # 0-d case - -""" - checkbounds_indices(Bool, IA, I) - -Return `true` if the "requested" indices in the tuple `I` fall within -the bounds of the "permitted" indices specified by the tuple -`IA`. This function recursively consumes elements of these tuples, -usually in a 1-for-1 fashion, - - checkbounds_indices(Bool, (IA1, IA...), (I1, I...)) = checkindex(Bool, IA1, I1) & - checkbounds_indices(Bool, IA, I) - -Note that [`checkindex`](@ref) is being used to perform the actual -bounds-check for a single dimension of the array. - -There are two important exceptions to the 1-1 rule: linear indexing and -CartesianIndex{N}, both of which may "consume" more than one element -of `IA`. - -See also [`checkbounds`](@ref). -""" -function checkbounds_indices(::Type{Bool}, IA::Tuple, I::Tuple) - @_inline_meta - checkindex(Bool, IA[1], I[1]) & checkbounds_indices(Bool, tail(IA), tail(I)) -end -checkbounds_indices(::Type{Bool}, ::Tuple{}, ::Tuple{}) = true -function checkbounds_indices(::Type{Bool}, ::Tuple{}, I::Tuple{Any}) - @_inline_meta - checkindex(Bool, 1:1, I[1]) -end -function checkbounds_indices(::Type{Bool}, ::Tuple{}, I::Tuple) - @_inline_meta - checkindex(Bool, 1:1, I[1]) & checkbounds_indices(Bool, (), tail(I)) -end -function checkbounds_indices(::Type{Bool}, IA::Tuple{Any}, I::Tuple{Any}) - @_inline_meta - checkindex(Bool, IA[1], I[1]) -end -function checkbounds_indices(::Type{Bool}, IA::Tuple, I::Tuple{Any}) - @_inline_meta - checkbounds_linear_indices(Bool, IA, I[1]) -end -function checkbounds_linear_indices(::Type{Bool}, IA::Tuple{Vararg{OneTo}}, i) - @_inline_meta - ts = trailingsize(IA) - if checkindex(Bool, IA[1], i) && ts > 0 - return true - elseif checkindex(Bool, OneTo(ts), i) # partial linear indexing - partial_linear_indexing_warning_lookup(length(IA)) - return true # TODO: Return false after the above function is removed in deprecated.jl - end - return false -end -function checkbounds_linear_indices(::Type{Bool}, IA::Tuple{AbstractUnitRange,Vararg{AbstractUnitRange}}, i) - @_inline_meta - checkindex(Bool, IA[1], i) -end -function checkbounds_linear_indices(::Type{Bool}, IA::Tuple{Vararg{OneTo}}, i::Union{Slice,Colon}) - partial_linear_indexing_warning_lookup(length(IA)) - true -end -function checkbounds_linear_indices(::Type{Bool}, - IA::Tuple{AbstractUnitRange,Vararg{AbstractUnitRange}}, i::Union{Slice,Colon}) - partial_linear_indexing_warning_lookup(length(IA)) - true -end -checkbounds_indices(::Type{Bool}, ::Tuple, ::Tuple{}) = true - -throw_boundserror(A, I) = (@_noinline_meta; throw(BoundsError(A, I))) - -# check along a single dimension -""" - checkindex(Bool, inds::AbstractUnitRange, index) - -Return `true` if the given `index` is within the bounds of -`inds`. Custom types that would like to behave as indices for all -arrays can extend this method in order to provide a specialized bounds -checking implementation. - -```jldoctest -julia> checkindex(Bool,1:20,8) -true - -julia> checkindex(Bool,1:20,21) -false -``` -""" -checkindex(::Type{Bool}, inds::AbstractUnitRange, i) = - throw(ArgumentError("unable to check bounds for indices of type $(typeof(i))")) -checkindex(::Type{Bool}, inds::AbstractUnitRange, i::Real) = (first(inds) <= i) & (i <= last(inds)) -checkindex(::Type{Bool}, inds::AbstractUnitRange, ::Colon) = true -checkindex(::Type{Bool}, inds::AbstractUnitRange, ::Slice) = true -function checkindex(::Type{Bool}, inds::AbstractUnitRange, r::Range) - @_propagate_inbounds_meta - isempty(r) | (checkindex(Bool, inds, first(r)) & checkindex(Bool, inds, last(r))) -end -checkindex(::Type{Bool}, indx::AbstractUnitRange, I::AbstractVector{Bool}) = indx == indices1(I) -checkindex(::Type{Bool}, indx::AbstractUnitRange, I::AbstractArray{Bool}) = false -function checkindex(::Type{Bool}, inds::AbstractUnitRange, I::AbstractArray) - @_inline_meta - b = true - for i in I - b &= checkindex(Bool, inds, i) - end - b -end - -# See also specializations in multidimensional - -## Constructors ## - -# default arguments to similar() -""" - similar(array, [element_type=eltype(array)], [dims=size(array)]) - -Create an uninitialized mutable array with the given element type and size, based upon the -given source array. The second and third arguments are both optional, defaulting to the -given array's `eltype` and `size`. The dimensions may be specified either as a single tuple -argument or as a series of integer arguments. - -Custom AbstractArray subtypes may choose which specific array type is best-suited to return -for the given element type and dimensionality. If they do not specialize this method, the -default is an `Array{element_type}(dims...)`. - -For example, `similar(1:10, 1, 4)` returns an uninitialized `Array{Int,2}` since ranges are -neither mutable nor support 2 dimensions: - -```julia-repl -julia> similar(1:10, 1, 4) -1×4 Array{Int64,2}: - 4419743872 4374413872 4419743888 0 -``` - -Conversely, `similar(trues(10,10), 2)` returns an uninitialized `BitVector` with two -elements since `BitArray`s are both mutable and can support 1-dimensional arrays: - -```julia-repl -julia> similar(trues(10,10), 2) -2-element BitArray{1}: - false - false -``` - -Since `BitArray`s can only store elements of type [`Bool`](@ref), however, if you request a -different element type it will create a regular `Array` instead: - -```julia-repl -julia> similar(falses(10), Float64, 2, 4) -2×4 Array{Float64,2}: - 2.18425e-314 2.18425e-314 2.18425e-314 2.18425e-314 - 2.18425e-314 2.18425e-314 2.18425e-314 2.18425e-314 -``` - -""" -similar(a::AbstractArray{T}) where {T} = similar(a, T) -similar(a::AbstractArray, ::Type{T}) where {T} = similar(a, T, to_shape(indices(a))) -similar(a::AbstractArray{T}, dims::Tuple) where {T} = similar(a, T, to_shape(dims)) -similar(a::AbstractArray{T}, dims::DimOrInd...) where {T} = similar(a, T, to_shape(dims)) -similar(a::AbstractArray, ::Type{T}, dims::DimOrInd...) where {T} = similar(a, T, to_shape(dims)) -similar(a::AbstractArray, ::Type{T}, dims::NeedsShaping) where {T} = similar(a, T, to_shape(dims)) -# similar creates an Array by default -similar(a::AbstractArray, ::Type{T}, dims::Dims{N}) where {T,N} = Array{T,N}(dims) - -to_shape(::Tuple{}) = () -to_shape(dims::Dims) = dims -to_shape(dims::DimsOrInds) = map(to_shape, dims) -# each dimension -to_shape(i::Int) = i -to_shape(i::Integer) = Int(i) -to_shape(r::OneTo) = Int(last(r)) -to_shape(r::AbstractUnitRange) = r - -""" - similar(storagetype, indices) - -Create an uninitialized mutable array analogous to that specified by -`storagetype`, but with `indices` specified by the last -argument. `storagetype` might be a type or a function. - -**Examples**: - - similar(Array{Int}, indices(A)) - -creates an array that "acts like" an `Array{Int}` (and might indeed be -backed by one), but which is indexed identically to `A`. If `A` has -conventional indexing, this will be identical to -`Array{Int}(size(A))`, but if `A` has unconventional indexing then the -indices of the result will match `A`. - - similar(BitArray, (indices(A, 2),)) - -would create a 1-dimensional logical array whose indices match those -of the columns of `A`. - - similar(dims->zeros(Int, dims), indices(A)) - -would create an array of `Int`, initialized to zero, matching the -indices of `A`. -""" -similar(f, shape::Tuple) = f(to_shape(shape)) -similar(f, dims::DimOrInd...) = similar(f, dims) - -## from general iterable to any array - -function copy!(dest::AbstractArray, src) - destiter = eachindex(dest) - state = start(destiter) - for x in src - i, state = next(destiter, state) - dest[i] = x - end - return dest -end - -function copy!(dest::AbstractArray, dstart::Integer, src) - i = Int(dstart) - for x in src - dest[i] = x - i += 1 - end - return dest -end - -# copy from an some iterable object into an AbstractArray -function copy!(dest::AbstractArray, dstart::Integer, src, sstart::Integer) - if (sstart < 1) - throw(ArgumentError(string("source start offset (",sstart,") is < 1"))) - end - st = start(src) - for j = 1:(sstart-1) - if done(src, st) - throw(ArgumentError(string("source has fewer elements than required, ", - "expected at least ",sstart,", got ",j-1))) - end - _, st = next(src, st) - end - dn = done(src, st) - if dn - throw(ArgumentError(string("source has fewer elements than required, ", - "expected at least ",sstart,", got ",sstart-1))) - end - i = Int(dstart) - while !dn - val, st = next(src, st) - dest[i] = val - i += 1 - dn = done(src, st) - end - return dest -end - -# this method must be separate from the above since src might not have a length -function copy!(dest::AbstractArray, dstart::Integer, src, sstart::Integer, n::Integer) - n < 0 && throw(ArgumentError(string("tried to copy n=", n, " elements, but n should be nonnegative"))) - n == 0 && return dest - dmax = dstart + n - 1 - inds = linearindices(dest) - if (dstart ∉ inds || dmax ∉ inds) | (sstart < 1) - sstart < 1 && throw(ArgumentError(string("source start offset (",sstart,") is < 1"))) - throw(BoundsError(dest, dstart:dmax)) - end - st = start(src) - for j = 1:(sstart-1) - if done(src, st) - throw(ArgumentError(string("source has fewer elements than required, ", - "expected at least ",sstart,", got ",j-1))) - end - _, st = next(src, st) - end - i = Int(dstart) - while i <= dmax && !done(src, st) - val, st = next(src, st) - @inbounds dest[i] = val - i += 1 - end - i <= dmax && throw(BoundsError(dest, i)) - return dest -end - -## copy between abstract arrays - generally more efficient -## since a single index variable can be used. - -copy!(dest::AbstractArray, src::AbstractArray) = - copy!(IndexStyle(dest), dest, IndexStyle(src), src) - -function copy!(::IndexStyle, dest::AbstractArray, ::IndexStyle, src::AbstractArray) - destinds, srcinds = linearindices(dest), linearindices(src) - isempty(srcinds) || (first(srcinds) ∈ destinds && last(srcinds) ∈ destinds) || - throw(BoundsError(dest, srcinds)) - @inbounds for i in srcinds - dest[i] = src[i] - end - return dest -end - -function copy!(::IndexStyle, dest::AbstractArray, ::IndexCartesian, src::AbstractArray) - destinds, srcinds = linearindices(dest), linearindices(src) - isempty(srcinds) || (first(srcinds) ∈ destinds && last(srcinds) ∈ destinds) || - throw(BoundsError(dest, srcinds)) - i = 0 - @inbounds for a in src - dest[i+=1] = a - end - return dest -end - -function copy!(dest::AbstractArray, dstart::Integer, src::AbstractArray) - copy!(dest, dstart, src, first(linearindices(src)), _length(src)) -end - -function copy!(dest::AbstractArray, dstart::Integer, src::AbstractArray, sstart::Integer) - srcinds = linearindices(src) - sstart ∈ srcinds || throw(BoundsError(src, sstart)) - copy!(dest, dstart, src, sstart, last(srcinds)-sstart+1) -end - -function copy!(dest::AbstractArray, dstart::Integer, - src::AbstractArray, sstart::Integer, - n::Integer) - n == 0 && return dest - n < 0 && throw(ArgumentError(string("tried to copy n=", n, " elements, but n should be nonnegative"))) - destinds, srcinds = linearindices(dest), linearindices(src) - (dstart ∈ destinds && dstart+n-1 ∈ destinds) || throw(BoundsError(dest, dstart:dstart+n-1)) - (sstart ∈ srcinds && sstart+n-1 ∈ srcinds) || throw(BoundsError(src, sstart:sstart+n-1)) - @inbounds for i = 0:(n-1) - dest[dstart+i] = src[sstart+i] - end - return dest -end - -function copy(a::AbstractArray) - @_propagate_inbounds_meta - copymutable(a) -end - -function copy!(B::AbstractVecOrMat{R}, ir_dest::Range{Int}, jr_dest::Range{Int}, - A::AbstractVecOrMat{S}, ir_src::Range{Int}, jr_src::Range{Int}) where {R,S} - if length(ir_dest) != length(ir_src) - throw(ArgumentError(string("source and destination must have same size (got ", - length(ir_src)," and ",length(ir_dest),")"))) - end - if length(jr_dest) != length(jr_src) - throw(ArgumentError(string("source and destination must have same size (got ", - length(jr_src)," and ",length(jr_dest),")"))) - end - @boundscheck checkbounds(B, ir_dest, jr_dest) - @boundscheck checkbounds(A, ir_src, jr_src) - jdest = first(jr_dest) - for jsrc in jr_src - idest = first(ir_dest) - for isrc in ir_src - B[idest,jdest] = A[isrc,jsrc] - idest += step(ir_dest) - end - jdest += step(jr_dest) - end - return B -end - - -""" - copymutable(a) - -Make a mutable copy of an array or iterable `a`. For `a::Array`, -this is equivalent to `copy(a)`, but for other array types it may -differ depending on the type of `similar(a)`. For generic iterables -this is equivalent to `collect(a)`. - -```jldoctest -julia> tup = (1, 2, 3) -(1, 2, 3) - -julia> Base.copymutable(tup) -3-element Array{Int64,1}: - 1 - 2 - 3 -``` -""" -function copymutable(a::AbstractArray) - @_propagate_inbounds_meta - copy!(similar(a), a) -end -copymutable(itr) = collect(itr) - -zero(x::AbstractArray{T}) where {T} = fill!(similar(x), zero(T)) - -## iteration support for arrays by iterating over `eachindex` in the array ## -# Allows fast iteration by default for both IndexLinear and IndexCartesian arrays - -# While the definitions for IndexLinear are all simple enough to inline on their -# own, IndexCartesian's CartesianRange is more complicated and requires explicit -# inlining. -start(A::AbstractArray) = (@_inline_meta; itr = eachindex(A); (itr, start(itr))) -next(A::AbstractArray, i) = (@_propagate_inbounds_meta; (idx, s) = next(i[1], i[2]); (A[idx], (i[1], s))) -done(A::AbstractArray, i) = (@_propagate_inbounds_meta; done(i[1], i[2])) - -# eachindex iterates over all indices. IndexCartesian definitions are later. -eachindex(A::AbstractVector) = (@_inline_meta(); indices1(A)) - -""" - eachindex(A...) - -Creates an iterable object for visiting each index of an AbstractArray `A` in an efficient -manner. For array types that have opted into fast linear indexing (like `Array`), this is -simply the range `1:length(A)`. For other array types, this returns a specialized Cartesian -range to efficiently index into the array with indices specified for every dimension. For -other iterables, including strings and dictionaries, this returns an iterator object -supporting arbitrary index types (e.g. unevenly spaced or non-integer indices). - -Example for a sparse 2-d array: - -```jldoctest -julia> A = sparse([1, 1, 2], [1, 3, 1], [1, 2, -5]) -2×3 SparseMatrixCSC{Int64,Int64} with 3 stored entries: - [1, 1] = 1 - [2, 1] = -5 - [1, 3] = 2 - -julia> for iter in eachindex(A) - @show iter.I[1], iter.I[2] - @show A[iter] - end -(iter.I[1], iter.I[2]) = (1, 1) -A[iter] = 1 -(iter.I[1], iter.I[2]) = (2, 1) -A[iter] = -5 -(iter.I[1], iter.I[2]) = (1, 2) -A[iter] = 0 -(iter.I[1], iter.I[2]) = (2, 2) -A[iter] = 0 -(iter.I[1], iter.I[2]) = (1, 3) -A[iter] = 2 -(iter.I[1], iter.I[2]) = (2, 3) -A[iter] = 0 -``` - -If you supply more than one `AbstractArray` argument, `eachindex` will create an -iterable object that is fast for all arguments (a `UnitRange` -if all inputs have fast linear indexing, a [`CartesianRange`](@ref) -otherwise). -If the arrays have different sizes and/or dimensionalities, `eachindex` returns an -iterable that spans the largest range along each dimension. -""" -eachindex(A::AbstractArray) = (@_inline_meta(); eachindex(IndexStyle(A), A)) - -function eachindex(A::AbstractArray, B::AbstractArray) - @_inline_meta - eachindex(IndexStyle(A,B), A, B) -end -function eachindex(A::AbstractArray, B::AbstractArray...) - @_inline_meta - eachindex(IndexStyle(A,B...), A, B...) -end -eachindex(::IndexLinear, A::AbstractArray) = linearindices(A) -function eachindex(::IndexLinear, A::AbstractArray, B::AbstractArray...) - @_inline_meta - 1:_maxlength(A, B...) -end -_maxlength(A) = length(A) -function _maxlength(A, B, C...) - @_inline_meta - max(length(A), _maxlength(B, C...)) -end - -isempty(a::AbstractArray) = (_length(a) == 0) - -## Conversions ## - -convert(::Type{AbstractArray{T,N}}, A::AbstractArray{T,N}) where {T,N } = A -convert(::Type{AbstractArray{T,N}}, A::AbstractArray{S,N}) where {T,S,N} = copy!(similar(A,T), A) -convert(::Type{AbstractArray{T}}, A::AbstractArray{S,N}) where {T,S,N} = convert(AbstractArray{T,N}, A) - -convert(::Type{Array}, A::AbstractArray{T,N}) where {T,N} = convert(Array{T,N}, A) - -""" - of_indices(x, y) - -Represents the array `y` as an array having the same indices type as `x`. -""" -of_indices(x, y) = similar(dims->y, oftype(indices(x), indices(y))) - -full(x::AbstractArray) = x - -## range conversions ## - -map(::Type{T}, r::StepRange) where {T<:Real} = T(r.start):T(r.step):T(last(r)) -map(::Type{T}, r::UnitRange) where {T<:Real} = T(r.start):T(last(r)) -map(::Type{T}, r::StepRangeLen) where {T<:AbstractFloat} = convert(StepRangeLen{T}, r) -function map(::Type{T}, r::LinSpace) where T<:AbstractFloat - LinSpace(T(r.start), T(r.stop), length(r)) -end - -## unsafe/pointer conversions ## - -# note: the following type definitions don't mean any AbstractArray is convertible to -# a data Ref. they just map the array element type to the pointer type for -# convenience in cases that work. -pointer(x::AbstractArray{T}) where {T} = unsafe_convert(Ptr{T}, x) -function pointer(x::AbstractArray{T}, i::Integer) where T - @_inline_meta - unsafe_convert(Ptr{T}, x) + (i - first(linearindices(x)))*elsize(x) -end - -## Approach: -# We only define one fallback method on getindex for all argument types. -# That dispatches to an (inlined) internal _getindex function, where the goal is -# to transform the indices such that we can call the only getindex method that -# we require the type A{T,N} <: AbstractArray{T,N} to define; either: -# getindex(::A, ::Int) # if IndexStyle(A) == IndexLinear() OR -# getindex{T,N}(::A{T,N}, ::Vararg{Int, N}) # if IndexCartesian() -# If the subtype hasn't defined the required method, it falls back to the -# _getindex function again where an error is thrown to prevent stack overflows. - -function getindex(A::AbstractArray, I...) - @_propagate_inbounds_meta - error_if_canonical_indexing(IndexStyle(A), A, I...) - _getindex(IndexStyle(A), A, to_indices(A, I)...) -end -function unsafe_getindex(A::AbstractArray, I...) - @_inline_meta - @inbounds r = getindex(A, I...) - r -end - -error_if_canonical_indexing(::IndexLinear, A::AbstractArray, ::Int) = - error("indexing not defined for ", typeof(A)) -error_if_canonical_indexing(::IndexCartesian, A::AbstractArray{T,N}, ::Vararg{Int,N}) where {T,N} = - error("indexing not defined for ", typeof(A)) -error_if_canonical_indexing(::IndexStyle, ::AbstractArray, ::Any...) = nothing - -## Internal definitions -_getindex(::IndexStyle, A::AbstractArray, I...) = - error("indexing $(typeof(A)) with types $(typeof(I)) is not supported") - -## IndexLinear Scalar indexing: canonical method is one Int -_getindex(::IndexLinear, A::AbstractArray, i::Int) = (@_propagate_inbounds_meta; getindex(A, i)) -_getindex(::IndexLinear, A::AbstractArray) = (@_propagate_inbounds_meta; getindex(A, _to_linear_index(A))) -function _getindex(::IndexLinear, A::AbstractArray, I::Int...) - @_inline_meta - @boundscheck checkbounds(A, I...) # generally _to_linear_index requires bounds checking - @inbounds r = getindex(A, _to_linear_index(A, I...)) - r -end -_to_linear_index(A::AbstractArray, i::Int) = i -_to_linear_index(A::AbstractVector, i::Int, I::Int...) = i # TODO: DEPRECATE FOR #14770 -_to_linear_index(A::AbstractArray{T,N}, I::Vararg{Int,N}) where {T,N} = (@_inline_meta; sub2ind(A, I...)) -_to_linear_index(A::AbstractArray) = 1 # TODO: DEPRECATE FOR #14770 -_to_linear_index(A::AbstractArray, I::Int...) = (@_inline_meta; sub2ind(A, I...)) # TODO: DEPRECATE FOR #14770 - -## IndexCartesian Scalar indexing: Canonical method is full dimensionality of Ints -function _getindex(::IndexCartesian, A::AbstractArray) - @_propagate_inbounds_meta - getindex(A, _to_subscript_indices(A)...) -end -function _getindex(::IndexCartesian, A::AbstractArray, I::Int...) - @_inline_meta - @boundscheck checkbounds(A, I...) # generally _to_subscript_indices requires bounds checking - @inbounds r = getindex(A, _to_subscript_indices(A, I...)...) - r -end -function _getindex(::IndexCartesian, A::AbstractArray{T,N}, I::Vararg{Int, N}) where {T,N} - @_propagate_inbounds_meta - getindex(A, I...) -end -_to_subscript_indices(A::AbstractArray, i::Int) = (@_inline_meta; _unsafe_ind2sub(A, i)) -_to_subscript_indices(A::AbstractArray{T,N}) where {T,N} = (@_inline_meta; fill_to_length((), 1, Val{N})) # TODO: DEPRECATE FOR #14770 -_to_subscript_indices(A::AbstractArray{T,0}) where {T} = () # TODO: REMOVE FOR #14770 -_to_subscript_indices(A::AbstractArray{T,0}, i::Int) where {T} = () # TODO: REMOVE FOR #14770 -_to_subscript_indices(A::AbstractArray{T,0}, I::Int...) where {T} = () # TODO: DEPRECATE FOR #14770 -function _to_subscript_indices(A::AbstractArray{T,N}, I::Int...) where {T,N} # TODO: DEPRECATE FOR #14770 - @_inline_meta - J, Jrem = IteratorsMD.split(I, Val{N}) - _to_subscript_indices(A, J, Jrem) -end -_to_subscript_indices(A::AbstractArray, J::Tuple, Jrem::Tuple{}) = - __to_subscript_indices(A, indices(A), J, Jrem) -# We allow partial linear indexing deprecation for OneTo arrays -function __to_subscript_indices(A::AbstractArray, ::Tuple{Vararg{OneTo}}, J::Tuple, Jrem::Tuple{}) - @_inline_meta - sz = _remaining_size(J, indices(A)) # compute trailing size (overlapping the final index) - (front(J)..., _unsafe_ind2sub(sz, last(J))...) # (maybe) extend the last index -end -# After the partial linear indexing deprecation is removed, this next method can -# become the new normal. For now, it's limited to non-OneTo arrays. -function __to_subscript_indices(A::AbstractArray, - ::Tuple{AbstractUnitRange,Vararg{AbstractUnitRange}}, J::Tuple, Jrem::Tuple{}) - @_inline_meta - (J..., map(first, tail(_remaining_size(J, indices(A))))...) -end -_to_subscript_indices(A, J::Tuple, Jrem::Tuple) = J # already bounds-checked, safe to drop -_to_subscript_indices(A::AbstractArray{T,N}, I::Vararg{Int,N}) where {T,N} = I -_remaining_size(::Tuple{Any}, t::Tuple) = t -_remaining_size(h::Tuple, t::Tuple) = (@_inline_meta; _remaining_size(tail(h), tail(t))) -_unsafe_ind2sub(::Tuple{}, i) = () # ind2sub may throw(BoundsError()) in this case -_unsafe_ind2sub(sz, i) = (@_inline_meta; ind2sub(sz, i)) - -## Setindex! is defined similarly. We first dispatch to an internal _setindex! -# function that allows dispatch on array storage -function setindex!(A::AbstractArray, v, I...) - @_propagate_inbounds_meta - error_if_canonical_indexing(IndexStyle(A), A, I...) - _setindex!(IndexStyle(A), A, v, to_indices(A, I)...) -end -function unsafe_setindex!(A::AbstractArray, v, I...) - @_inline_meta - @inbounds r = setindex!(A, v, I...) - r -end -## Internal defitions -_setindex!(::IndexStyle, A::AbstractArray, v, I...) = - error("indexing $(typeof(A)) with types $(typeof(I)) is not supported") - -## IndexLinear Scalar indexing -_setindex!(::IndexLinear, A::AbstractArray, v, i::Int) = (@_propagate_inbounds_meta; setindex!(A, v, i)) -_setindex!(::IndexLinear, A::AbstractArray, v) = (@_propagate_inbounds_meta; setindex!(A, v, _to_linear_index(A))) -function _setindex!(::IndexLinear, A::AbstractArray, v, I::Int...) - @_inline_meta - @boundscheck checkbounds(A, I...) - @inbounds r = setindex!(A, v, _to_linear_index(A, I...)) - r -end - -# IndexCartesian Scalar indexing -function _setindex!(::IndexCartesian, A::AbstractArray{T,N}, v, I::Vararg{Int, N}) where {T,N} - @_propagate_inbounds_meta - setindex!(A, v, I...) -end -function _setindex!(::IndexCartesian, A::AbstractArray, v) - @_propagate_inbounds_meta - setindex!(A, v, _to_subscript_indices(A)...) -end -function _setindex!(::IndexCartesian, A::AbstractArray, v, I::Int...) - @_inline_meta - @boundscheck checkbounds(A, I...) - @inbounds r = setindex!(A, v, _to_subscript_indices(A, I...)...) - r -end - -## get (getindex with a default value) ## - -RangeVecIntList{A<:AbstractVector{Int}} = Union{Tuple{Vararg{Union{Range, AbstractVector{Int}}}}, - AbstractVector{UnitRange{Int}}, AbstractVector{Range{Int}}, AbstractVector{A}} - -get(A::AbstractArray, i::Integer, default) = checkbounds(Bool, A, i) ? A[i] : default -get(A::AbstractArray, I::Tuple{}, default) = similar(A, typeof(default), 0) -get(A::AbstractArray, I::Dims, default) = checkbounds(Bool, A, I...) ? A[I...] : default - -function get!(X::AbstractVector{T}, A::AbstractVector, I::Union{Range,AbstractVector{Int}}, default::T) where T - # 1d is not linear indexing - ind = findin(I, indices1(A)) - X[ind] = A[I[ind]] - Xind = indices1(X) - X[first(Xind):first(ind)-1] = default - X[last(ind)+1:last(Xind)] = default - X -end -function get!(X::AbstractArray{T}, A::AbstractArray, I::Union{Range,AbstractVector{Int}}, default::T) where T - # Linear indexing - ind = findin(I, 1:length(A)) - X[ind] = A[I[ind]] - X[1:first(ind)-1] = default - X[last(ind)+1:length(X)] = default - X -end - -get(A::AbstractArray, I::Range, default) = get!(similar(A, typeof(default), index_shape(I)), A, I, default) - -# TODO: DEPRECATE FOR #14770 (just the partial linear indexing part) -function get!(X::AbstractArray{T}, A::AbstractArray, I::RangeVecIntList, default::T) where T - fill!(X, default) - dst, src = indcopy(size(A), I) - X[dst...] = A[src...] - X -end - -get(A::AbstractArray, I::RangeVecIntList, default) = - get!(similar(A, typeof(default), index_shape(I...)), A, I, default) - -## structured matrix methods ## -replace_in_print_matrix(A::AbstractMatrix,i::Integer,j::Integer,s::AbstractString) = s -replace_in_print_matrix(A::AbstractVector,i::Integer,j::Integer,s::AbstractString) = s - -## Concatenation ## -eltypeof(x) = typeof(x) -eltypeof(x::AbstractArray) = eltype(x) - -promote_eltypeof() = Bottom -promote_eltypeof(v1, vs...) = promote_type(eltypeof(v1), promote_eltypeof(vs...)) - -promote_eltype() = Bottom -promote_eltype(v1, vs...) = promote_type(eltype(v1), promote_eltype(vs...)) - -#TODO: ERROR CHECK -cat(catdim::Integer) = Array{Any,1}(0) - -typed_vcat(::Type{T}) where {T} = Array{T,1}(0) -typed_hcat(::Type{T}) where {T} = Array{T,1}(0) - -## cat: special cases -vcat(X::T...) where {T} = T[ X[i] for i=1:length(X) ] -vcat(X::T...) where {T<:Number} = T[ X[i] for i=1:length(X) ] -hcat(X::T...) where {T} = T[ X[j] for i=1:1, j=1:length(X) ] -hcat(X::T...) where {T<:Number} = T[ X[j] for i=1:1, j=1:length(X) ] - -vcat(X::Number...) = hvcat_fill(Array{promote_typeof(X...)}(length(X)), X) -hcat(X::Number...) = hvcat_fill(Array{promote_typeof(X...)}(1,length(X)), X) -typed_vcat(::Type{T}, X::Number...) where {T} = hvcat_fill(Array{T,1}(length(X)), X) -typed_hcat(::Type{T}, X::Number...) where {T} = hvcat_fill(Array{T,2}(1,length(X)), X) - -vcat(V::AbstractVector...) = typed_vcat(promote_eltype(V...), V...) -vcat(V::AbstractVector{T}...) where {T} = typed_vcat(T, V...) - -function typed_vcat(::Type{T}, V::AbstractVector...) where T - n::Int = 0 - for Vk in V - n += length(Vk) - end - a = similar(V[1], T, n) - pos = 1 - for k=1:length(V) - Vk = V[k] - p1 = pos+length(Vk)-1 - a[pos:p1] = Vk - pos = p1+1 - end - a -end - -hcat(A::AbstractVecOrMat...) = typed_hcat(promote_eltype(A...), A...) -hcat(A::AbstractVecOrMat{T}...) where {T} = typed_hcat(T, A...) - -function typed_hcat(::Type{T}, A::AbstractVecOrMat...) where T - nargs = length(A) - nrows = size(A[1], 1) - ncols = 0 - dense = true - for j = 1:nargs - Aj = A[j] - if size(Aj, 1) != nrows - throw(ArgumentError("number of rows of each array must match (got $(map(x->size(x,1), A)))")) - end - dense &= isa(Aj,Array) - nd = ndims(Aj) - ncols += (nd==2 ? size(Aj,2) : 1) - end - B = similar(A[1], T, nrows, ncols) - pos = 1 - if dense - for k=1:nargs - Ak = A[k] - n = length(Ak) - copy!(B, pos, Ak, 1, n) - pos += n - end - else - for k=1:nargs - Ak = A[k] - p1 = pos+(isa(Ak,AbstractMatrix) ? size(Ak, 2) : 1)-1 - B[:, pos:p1] = Ak - pos = p1+1 - end - end - return B -end - -vcat(A::AbstractVecOrMat...) = typed_vcat(promote_eltype(A...), A...) -vcat(A::AbstractVecOrMat{T}...) where {T} = typed_vcat(T, A...) - -function typed_vcat(::Type{T}, A::AbstractVecOrMat...) where T - nargs = length(A) - nrows = sum(a->size(a, 1), A)::Int - ncols = size(A[1], 2) - for j = 2:nargs - if size(A[j], 2) != ncols - throw(ArgumentError("number of columns of each array must match (got $(map(x->size(x,2), A)))")) - end - end - B = similar(A[1], T, nrows, ncols) - pos = 1 - for k=1:nargs - Ak = A[k] - p1 = pos+size(Ak,1)-1 - B[pos:p1, :] = Ak - pos = p1+1 - end - return B -end - -## cat: general case - -# helper functions -cat_size(A) = (1,) -cat_size(A::AbstractArray) = size(A) -cat_size(A, d) = 1 -cat_size(A::AbstractArray, d) = size(A, d) - -cat_indices(A, d) = OneTo(1) -cat_indices(A::AbstractArray, d) = indices(A, d) - -cat_similar(A, T, shape) = Array{T}(shape) -cat_similar(A::AbstractArray, T, shape) = similar(A, T, shape) - -cat_shape(dims, shape::Tuple) = shape -@inline cat_shape(dims, shape::Tuple, nshape::Tuple, shapes::Tuple...) = - cat_shape(dims, _cshp(dims, (), shape, nshape), shapes...) - -_cshp(::Tuple{}, out, ::Tuple{}, ::Tuple{}) = out -_cshp(::Tuple{}, out, ::Tuple{}, nshape) = (out..., nshape...) -_cshp(dims, out, ::Tuple{}, ::Tuple{}) = (out..., map(b -> 1, dims)...) -@inline _cshp(dims, out, shape, ::Tuple{}) = - _cshp(tail(dims), (out..., shape[1] + dims[1]), tail(shape), ()) -@inline _cshp(dims, out, ::Tuple{}, nshape) = - _cshp(tail(dims), (out..., nshape[1]), (), tail(nshape)) -@inline function _cshp(::Tuple{}, out, shape, ::Tuple{}) - _cs(length(out) + 1, false, shape[1], 1) - _cshp((), (out..., 1), tail(shape), ()) -end -@inline function _cshp(::Tuple{}, out, shape, nshape) - next = _cs(length(out) + 1, false, shape[1], nshape[1]) - _cshp((), (out..., next), tail(shape), tail(nshape)) -end -@inline function _cshp(dims, out, shape, nshape) - next = _cs(length(out) + 1, dims[1], shape[1], nshape[1]) - _cshp(tail(dims), (out..., next), tail(shape), tail(nshape)) -end - -_cs(d, concat, a, b) = concat ? (a + b) : (a == b ? a : throw(DimensionMismatch(string( - "mismatch in dimension ", d, " (expected ", a, " got ", b, ")")))) - -dims2cat{n}(::Type{Val{n}}) = ntuple(i -> (i == n), Val{n}) -dims2cat(dims) = ntuple(i -> (i in dims), maximum(dims)) - -cat(dims, X...) = cat_t(dims, promote_eltypeof(X...), X...) - -function cat_t(dims, T::Type, X...) - catdims = dims2cat(dims) - shape = cat_shape(catdims, (), map(cat_size, X)...) - A = cat_similar(X[1], T, shape) - if T <: Number && countnz(catdims) > 1 - fill!(A, zero(T)) - end - return _cat(A, shape, catdims, X...) -end - -function _cat(A, shape::NTuple{N}, catdims, X...) where N - offsets = zeros(Int, N) - inds = Vector{UnitRange{Int}}(N) - concat = copy!(zeros(Bool, N), catdims) - for x in X - for i = 1:N - if concat[i] - inds[i] = offsets[i] + cat_indices(x, i) - offsets[i] += cat_size(x, i) - else - inds[i] = 1:shape[i] - end - end - I::NTuple{N, UnitRange{Int}} = (inds...,) - A[I...] = x - end - return A -end - -""" - vcat(A...) - -Concatenate along dimension 1. - -```jldoctest -julia> a = [1 2 3 4 5] -1×5 Array{Int64,2}: - 1 2 3 4 5 - -julia> b = [6 7 8 9 10; 11 12 13 14 15] -2×5 Array{Int64,2}: - 6 7 8 9 10 - 11 12 13 14 15 - -julia> vcat(a,b) -3×5 Array{Int64,2}: - 1 2 3 4 5 - 6 7 8 9 10 - 11 12 13 14 15 - -julia> c = ([1 2 3], [4 5 6]) -([1 2 3], [4 5 6]) - -julia> vcat(c...) -2×3 Array{Int64,2}: - 1 2 3 - 4 5 6 -``` -""" -vcat(X...) = cat(Val{1}, X...) -""" - hcat(A...) - -Concatenate along dimension 2. - -```jldoctest -julia> a = [1; 2; 3; 4; 5] -5-element Array{Int64,1}: - 1 - 2 - 3 - 4 - 5 - -julia> b = [6 7; 8 9; 10 11; 12 13; 14 15] -5×2 Array{Int64,2}: - 6 7 - 8 9 - 10 11 - 12 13 - 14 15 - -julia> hcat(a,b) -5×3 Array{Int64,2}: - 1 6 7 - 2 8 9 - 3 10 11 - 4 12 13 - 5 14 15 - -julia> c = ([1; 2; 3], [4; 5; 6]) -([1, 2, 3], [4, 5, 6]) - -julia> hcat(c...) -3×2 Array{Int64,2}: - 1 4 - 2 5 - 3 6 -``` -""" -hcat(X...) = cat(Val{2}, X...) - -typed_vcat(T::Type, X...) = cat_t(Val{1}, T, X...) -typed_hcat(T::Type, X...) = cat_t(Val{2}, T, X...) - -cat(catdims, A::AbstractArray{T}...) where {T} = cat_t(catdims, T, A...) - -# The specializations for 1 and 2 inputs are important -# especially when running with --inline=no, see #11158 -vcat(A::AbstractArray) = cat(Val{1}, A) -vcat(A::AbstractArray, B::AbstractArray) = cat(Val{1}, A, B) -vcat(A::AbstractArray...) = cat(Val{1}, A...) -hcat(A::AbstractArray) = cat(Val{2}, A) -hcat(A::AbstractArray, B::AbstractArray) = cat(Val{2}, A, B) -hcat(A::AbstractArray...) = cat(Val{2}, A...) - -typed_vcat(T::Type, A::AbstractArray) = cat_t(Val{1}, T, A) -typed_vcat(T::Type, A::AbstractArray, B::AbstractArray) = cat_t(Val{1}, T, A, B) -typed_vcat(T::Type, A::AbstractArray...) = cat_t(Val{1}, T, A...) -typed_hcat(T::Type, A::AbstractArray) = cat_t(Val{2}, T, A) -typed_hcat(T::Type, A::AbstractArray, B::AbstractArray) = cat_t(Val{2}, T, A, B) -typed_hcat(T::Type, A::AbstractArray...) = cat_t(Val{2}, T, A...) - -# 2d horizontal and vertical concatenation - -function hvcat(nbc::Integer, as...) - # nbc = # of block columns - n = length(as) - mod(n,nbc) != 0 && - throw(ArgumentError("number of arrays $n is not a multiple of the requested number of block columns $nbc")) - nbr = div(n,nbc) - hvcat(ntuple(i->nbc, nbr), as...) -end - -""" - hvcat(rows::Tuple{Vararg{Int}}, values...) - -Horizontal and vertical concatenation in one call. This function is called for block matrix -syntax. The first argument specifies the number of arguments to concatenate in each block -row. - -```jldoctest -julia> a, b, c, d, e, f = 1, 2, 3, 4, 5, 6 -(1, 2, 3, 4, 5, 6) - -julia> [a b c; d e f] -2×3 Array{Int64,2}: - 1 2 3 - 4 5 6 - -julia> hvcat((3,3), a,b,c,d,e,f) -2×3 Array{Int64,2}: - 1 2 3 - 4 5 6 - -julia> [a b;c d; e f] -3×2 Array{Int64,2}: - 1 2 - 3 4 - 5 6 - -julia> hvcat((2,2,2), a,b,c,d,e,f) -3×2 Array{Int64,2}: - 1 2 - 3 4 - 5 6 -``` - -If the first argument is a single integer `n`, then all block rows are assumed to have `n` -block columns. -""" -hvcat(rows::Tuple{Vararg{Int}}, xs::AbstractVecOrMat...) = typed_hvcat(promote_eltype(xs...), rows, xs...) -hvcat(rows::Tuple{Vararg{Int}}, xs::AbstractVecOrMat{T}...) where {T} = typed_hvcat(T, rows, xs...) - -function typed_hvcat(::Type{T}, rows::Tuple{Vararg{Int}}, as::AbstractVecOrMat...) where T - nbr = length(rows) # number of block rows - - nc = 0 - for i=1:rows[1] - nc += size(as[i],2) - end - - nr = 0 - a = 1 - for i = 1:nbr - nr += size(as[a],1) - a += rows[i] - end - - out = similar(as[1], T, nr, nc) - - a = 1 - r = 1 - for i = 1:nbr - c = 1 - szi = size(as[a],1) - for j = 1:rows[i] - Aj = as[a+j-1] - szj = size(Aj,2) - if size(Aj,1) != szi - throw(ArgumentError("mismatched height in block row $(i) (expected $szi, got $(size(Aj,1)))")) - end - if c-1+szj > nc - throw(ArgumentError("block row $(i) has mismatched number of columns (expected $nc, got $(c-1+szj))")) - end - out[r:r-1+szi, c:c-1+szj] = Aj - c += szj - end - if c != nc+1 - throw(ArgumentError("block row $(i) has mismatched number of columns (expected $nc, got $(c-1))")) - end - r += szi - a += rows[i] - end - out -end - -hvcat(rows::Tuple{Vararg{Int}}) = [] -typed_hvcat(::Type{T}, rows::Tuple{Vararg{Int}}) where {T} = Array{T,1}(0) - -function hvcat(rows::Tuple{Vararg{Int}}, xs::T...) where T<:Number - nr = length(rows) - nc = rows[1] - - a = Array{T,2}(nr, nc) - if length(a) != length(xs) - throw(ArgumentError("argument count does not match specified shape (expected $(length(a)), got $(length(xs)))")) - end - k = 1 - @inbounds for i=1:nr - if nc != rows[i] - throw(ArgumentError("row $(i) has mismatched number of columns (expected $nc, got $(rows[i]))")) - end - for j=1:nc - a[i,j] = xs[k] - k += 1 - end - end - a -end - -function hvcat_fill(a::Array, xs::Tuple) - k = 1 - nr, nc = size(a,1), size(a,2) - for i=1:nr - @inbounds for j=1:nc - a[i,j] = xs[k] - k += 1 - end - end - a -end - -hvcat(rows::Tuple{Vararg{Int}}, xs::Number...) = typed_hvcat(promote_typeof(xs...), rows, xs...) - -function typed_hvcat(::Type{T}, rows::Tuple{Vararg{Int}}, xs::Number...) where T - nr = length(rows) - nc = rows[1] - for i = 2:nr - if nc != rows[i] - throw(ArgumentError("row $(i) has mismatched number of columns (expected $nc, got $(rows[i]))")) - end - end - len = length(xs) - if nr*nc != len - throw(ArgumentError("argument count $(len) does not match specified shape $((nr,nc))")) - end - hvcat_fill(Array{T,2}(nr, nc), xs) -end - -# fallback definition of hvcat in terms of hcat and vcat -function hvcat(rows::Tuple{Vararg{Int}}, as...) - nbr = length(rows) # number of block rows - rs = Array{Any,1}(nbr) - a = 1 - for i = 1:nbr - rs[i] = hcat(as[a:a-1+rows[i]]...) - a += rows[i] - end - vcat(rs...) -end - -function typed_hvcat(::Type{T}, rows::Tuple{Vararg{Int}}, as...) where T - nbr = length(rows) # number of block rows - rs = Array{Any,1}(nbr) - a = 1 - for i = 1:nbr - rs[i] = typed_hcat(T, as[a:a-1+rows[i]]...) - a += rows[i] - end - T[rs...;] -end - -## Reductions and accumulates ## - -function isequal(A::AbstractArray, B::AbstractArray) - if A === B return true end - if indices(A) != indices(B) - return false - end - if isa(A,Range) != isa(B,Range) - return false - end - for (a, b) in zip(A, B) - if !isequal(a, b) - return false - end - end - return true -end - -function lexcmp(A::AbstractArray, B::AbstractArray) - for (a, b) in zip(A, B) - res = lexcmp(a, b) - res == 0 || return res - end - return cmp(length(A), length(B)) -end - -function (==)(A::AbstractArray, B::AbstractArray) - if indices(A) != indices(B) - return false - end - if isa(A,Range) != isa(B,Range) - return false - end - for (a, b) in zip(A, B) - if !(a == b) - return false - end - end - return true -end - -# sub2ind and ind2sub -# fallbacks -function sub2ind(A::AbstractArray, I...) - @_inline_meta - sub2ind(indices(A), I...) -end - -""" - ind2sub(a, index) -> subscripts - -Returns a tuple of subscripts into array `a` corresponding to the linear index `index`. - -```jldoctest -julia> A = ones(5,6,7); - -julia> ind2sub(A,35) -(5, 1, 2) - -julia> ind2sub(A,70) -(5, 2, 3) -``` -""" -function ind2sub(A::AbstractArray, ind) - @_inline_meta - ind2sub(indices(A), ind) -end - -# 0-dimensional arrays and indexing with [] -sub2ind(::Tuple{}) = 1 -sub2ind(::DimsInteger) = 1 -sub2ind(::Indices) = 1 -sub2ind(::Tuple{}, I::Integer...) = (@_inline_meta; _sub2ind((), 1, 1, I...)) -# Generic cases - -""" - sub2ind(dims, i, j, k...) -> index - -The inverse of [`ind2sub`](@ref), returns the linear index corresponding to the provided subscripts. - -```jldoctest -julia> sub2ind((5,6,7),1,2,3) -66 - -julia> sub2ind((5,6,7),1,6,3) -86 -``` -""" -sub2ind(dims::DimsInteger, I::Integer...) = (@_inline_meta; _sub2ind(dims, 1, 1, I...)) -sub2ind(inds::Indices, I::Integer...) = (@_inline_meta; _sub2ind(inds, 1, 1, I...)) -# In 1d, there's a question of whether we're doing cartesian indexing -# or linear indexing. Support only the former. -sub2ind(inds::Indices{1}, I::Integer...) = - throw(ArgumentError("Linear indexing is not defined for one-dimensional arrays")) -sub2ind(inds::Tuple{OneTo}, I::Integer...) = (@_inline_meta; _sub2ind(inds, 1, 1, I...)) # only OneTo is safe -sub2ind(inds::Tuple{OneTo}, i::Integer) = i - -_sub2ind(::Any, L, ind) = ind -function _sub2ind(::Tuple{}, L, ind, i::Integer, I::Integer...) - @_inline_meta - _sub2ind((), L, ind+(i-1)*L, I...) -end -function _sub2ind(inds, L, ind, i::Integer, I::Integer...) - @_inline_meta - r1 = inds[1] - _sub2ind(tail(inds), nextL(L, r1), ind+offsetin(i, r1)*L, I...) -end - -nextL(L, l::Integer) = L*l -nextL(L, r::AbstractUnitRange) = L*unsafe_length(r) -offsetin(i, l::Integer) = i-1 -offsetin(i, r::AbstractUnitRange) = i-first(r) - -ind2sub(::Tuple{}, ind::Integer) = (@_inline_meta; ind == 1 ? () : throw(BoundsError())) - -""" - ind2sub(dims, index) -> subscripts - -Returns a tuple of subscripts into an array with dimensions `dims`, -corresponding to the linear index `index`. - -**Example**: - -``` -i, j, ... = ind2sub(size(A), indmax(A)) -``` - -provides the indices of the maximum element. - -```jldoctest -julia> ind2sub((3,4),2) -(2, 1) - -julia> ind2sub((3,4),3) -(3, 1) - -julia> ind2sub((3,4),4) -(1, 2) -``` -""" -ind2sub(dims::DimsInteger, ind::Integer) = (@_inline_meta; _ind2sub(dims, ind-1)) -ind2sub(inds::Indices, ind::Integer) = (@_inline_meta; _ind2sub(inds, ind-1)) -ind2sub(inds::Indices{1}, ind::Integer) = - throw(ArgumentError("Linear indexing is not defined for one-dimensional arrays")) -ind2sub(inds::Tuple{OneTo}, ind::Integer) = (ind,) - -_ind2sub(::Tuple{}, ind) = (ind+1,) -function _ind2sub(indslast::NTuple{1}, ind) - @_inline_meta - (_lookup(ind, indslast[1]),) -end -function _ind2sub(inds, ind) - @_inline_meta - r1 = inds[1] - indnext, f, l = _div(ind, r1) - (ind-l*indnext+f, _ind2sub(tail(inds), indnext)...) -end - -_lookup(ind, d::Integer) = ind+1 -_lookup(ind, r::AbstractUnitRange) = ind+first(r) -_div(ind, d::Integer) = div(ind, d), 1, d -_div(ind, r::AbstractUnitRange) = (d = unsafe_length(r); (div(ind, d), first(r), d)) - -# Vectorized forms -function sub2ind(inds::Indices{1}, I1::AbstractVector{T}, I::AbstractVector{T}...) where T<:Integer - throw(ArgumentError("Linear indexing is not defined for one-dimensional arrays")) -end -sub2ind(inds::Tuple{OneTo}, I1::AbstractVector{T}, I::AbstractVector{T}...) where {T<:Integer} = - _sub2ind_vecs(inds, I1, I...) -sub2ind(inds::Union{DimsInteger,Indices}, I1::AbstractVector{T}, I::AbstractVector{T}...) where {T<:Integer} = - _sub2ind_vecs(inds, I1, I...) -function _sub2ind_vecs(inds, I::AbstractVector...) - I1 = I[1] - Iinds = indices1(I1) - for j = 2:length(I) - indices1(I[j]) == Iinds || throw(DimensionMismatch("indices of I[1] ($(Iinds)) does not match indices of I[$j] ($(indices1(I[j])))")) - end - Iout = similar(I1) - _sub2ind!(Iout, inds, Iinds, I) - Iout -end - -function _sub2ind!(Iout, inds, Iinds, I) - @_noinline_meta - for i in Iinds - # Iout[i] = sub2ind(inds, map(Ij->Ij[i], I)...) - Iout[i] = sub2ind_vec(inds, i, I) - end - Iout -end - -sub2ind_vec(inds, i, I) = (@_inline_meta; _sub2ind_vec(inds, (), i, I...)) -_sub2ind_vec(inds, out, i, I1, I...) = (@_inline_meta; _sub2ind_vec(inds, (out..., I1[i]), i, I...)) -_sub2ind_vec(inds, out, i) = (@_inline_meta; sub2ind(inds, out...)) - -function ind2sub(inds::Union{DimsInteger{N},Indices{N}}, ind::AbstractVector{<:Integer}) where N - M = length(ind) - t = ntuple(n->similar(ind),Val{N}) - for (i,idx) in enumerate(IndexLinear(), ind) - sub = ind2sub(inds, idx) - for j = 1:N - t[j][i] = sub[j] - end - end - t -end - -function ind2sub!(sub::Array{T}, dims::Tuple{Vararg{T}}, ind::T) where T<:Integer - ndims = length(dims) - for i=1:ndims-1 - ind2 = div(ind-1,dims[i])+1 - sub[i] = ind - dims[i]*(ind2-1) - ind = ind2 - end - sub[ndims] = ind - return sub -end - -## iteration utilities ## - -""" - foreach(f, c...) -> Void - -Call function `f` on each element of iterable `c`. -For multiple iterable arguments, `f` is called elementwise. -`foreach` should be used instead of `map` when the results of `f` are not -needed, for example in `foreach(println, array)`. - -# Example -```jldoctest -julia> a = 1:3:7; - -julia> foreach(x -> println(x^2), a) -1 -16 -49 -``` -""" -foreach(f) = (f(); nothing) -foreach(f, itr) = (for x in itr; f(x); end; nothing) -foreach(f, itrs...) = (for z in zip(itrs...); f(z...); end; nothing) - -## map over arrays ## - -## transform any set of dimensions -## dims specifies which dimensions will be transformed. for example -## dims==1:2 will call f on all slices A[:,:,...] -""" - mapslices(f, A, dims) - -Transform the given dimensions of array `A` using function `f`. `f` is called on each slice -of `A` of the form `A[...,:,...,:,...]`. `dims` is an integer vector specifying where the -colons go in this expression. The results are concatenated along the remaining dimensions. -For example, if `dims` is `[1,2]` and `A` is 4-dimensional, `f` is called on `A[:,:,i,j]` -for all `i` and `j`. - -# Examples -```jldoctest -julia> a = reshape(collect(1:16),(2,2,2,2)) -2×2×2×2 Array{Int64,4}: -[:, :, 1, 1] = - 1 3 - 2 4 - -[:, :, 2, 1] = - 5 7 - 6 8 - -[:, :, 1, 2] = - 9 11 - 10 12 - -[:, :, 2, 2] = - 13 15 - 14 16 - -julia> mapslices(sum, a, [1,2]) -1×1×2×2 Array{Int64,4}: -[:, :, 1, 1] = - 10 - -[:, :, 2, 1] = - 26 - -[:, :, 1, 2] = - 42 - -[:, :, 2, 2] = - 58 -``` -""" -mapslices(f, A::AbstractArray, dims) = mapslices(f, A, [dims...]) -function mapslices(f, A::AbstractArray, dims::AbstractVector) - if isempty(dims) - return map(f,A) - end - - dimsA = [indices(A)...] - ndimsA = ndims(A) - alldims = [1:ndimsA;] - - otherdims = setdiff(alldims, dims) - - idx = Any[first(ind) for ind in indices(A)] - itershape = tuple(dimsA[otherdims]...) - for d in dims - idx[d] = Slice(indices(A, d)) - end - - # Apply the function to the first slice in order to determine the next steps - Aslice = A[idx...] - r1 = f(Aslice) - # In some cases, we can re-use the first slice for a dramatic performance - # increase. The slice itself must be mutable and the result cannot contain - # any mutable containers. The following errs on the side of being overly - # strict (#18570 & #21123). - safe_for_reuse = isa(Aslice, StridedArray) && - (isa(r1, Number) || (isa(r1, AbstractArray) && eltype(r1) <: Number)) - - # determine result size and allocate - Rsize = copy(dimsA) - # TODO: maybe support removing dimensions - if !isa(r1, AbstractArray) || ndims(r1) == 0 - r1 = [r1] - end - nextra = max(0, length(dims)-ndims(r1)) - if eltype(Rsize) == Int - Rsize[dims] = [size(r1)..., ntuple(d->1, nextra)...] - else - Rsize[dims] = [indices(r1)..., ntuple(d->OneTo(1), nextra)...] - end - R = similar(r1, tuple(Rsize...,)) - - ridx = Any[map(first, indices(R))...] - for d in dims - ridx[d] = indices(R,d) - end - - R[ridx...] = r1 - - nidx = length(otherdims) - if safe_for_reuse - # when f returns an array, R[ridx...] = f(Aslice) line copies elements, - # so we can reuse Aslice - for I in Iterators.drop(CartesianRange(itershape), 1) # skip the first element, we already handled it - for i in 1:nidx - idx[otherdims[i]] = ridx[otherdims[i]] = I.I[i] - end - _unsafe_getindex!(Aslice, A, idx...) - R[ridx...] = f(Aslice) - end - else - # we can't guarantee safety (#18524), so allocate new storage for each slice - for I in Iterators.drop(CartesianRange(itershape), 1) - for i in 1:nidx - idx[otherdims[i]] = ridx[otherdims[i]] = I.I[i] - end - R[ridx...] = f(A[idx...]) - end - end - - return R -end - -## 1 argument - -function map!(f::F, dest::AbstractArray, A::AbstractArray) where F - for (i,j) in zip(eachindex(dest),eachindex(A)) - dest[i] = f(A[j]) - end - return dest -end - -# map on collections -map(f, A::Union{AbstractArray,AbstractSet,Associative}) = collect_similar(A, Generator(f,A)) - -# default to returning an Array for `map` on general iterators -""" - map(f, c...) -> collection - -Transform collection `c` by applying `f` to each element. For multiple collection arguments, -apply `f` elementwise. - -# Examples -```jldoctest -julia> map(x -> x * 2, [1, 2, 3]) -3-element Array{Int64,1}: - 2 - 4 - 6 - -julia> map(+, [1, 2, 3], [10, 20, 30]) -3-element Array{Int64,1}: - 11 - 22 - 33 -``` -""" -map(f, A) = collect(Generator(f,A)) - -## 2 argument -function map!(f::F, dest::AbstractArray, A::AbstractArray, B::AbstractArray) where F - for (i, j, k) in zip(eachindex(dest), eachindex(A), eachindex(B)) - dest[i] = f(A[j], B[k]) - end - return dest -end - -## N argument - -@inline ith_all(i, ::Tuple{}) = () -@inline ith_all(i, as) = (as[1][i], ith_all(i, tail(as))...) - -function map_n!(f::F, dest::AbstractArray, As) where F - for i = linearindices(As[1]) - dest[i] = f(ith_all(i, As)...) - end - return dest -end - -""" - map!(function, destination, collection...) - -Like [`map`](@ref), but stores the result in `destination` rather than a new -collection. `destination` must be at least as large as the first collection. - -# Example -```jldoctest -julia> x = zeros(3); - -julia> map!(x -> x * 2, x, [1, 2, 3]); - -julia> x -3-element Array{Float64,1}: - 2.0 - 4.0 - 6.0 -``` -""" -map!(f::F, dest::AbstractArray, As::AbstractArray...) where {F} = map_n!(f, dest, As) - -map(f) = f() -map(f, iters...) = collect(Generator(f, iters...)) - -# multi-item push!, unshift! (built on top of type-specific 1-item version) -# (note: must not cause a dispatch loop when 1-item case is not defined) -push!(A, a, b) = push!(push!(A, a), b) -push!(A, a, b, c...) = push!(push!(A, a, b), c...) -unshift!(A, a, b) = unshift!(unshift!(A, b), a) -unshift!(A, a, b, c...) = unshift!(unshift!(A, c...), a, b) - -## hashing collections ## - -const hashaa_seed = UInt === UInt64 ? 0x7f53e68ceb575e76 : 0xeb575e76 -const hashrle_seed = UInt === UInt64 ? 0x2aab8909bfea414c : 0xbfea414c -function hash(a::AbstractArray, h::UInt) - h += hashaa_seed - h += hash(size(a)) - - state = start(a) - done(a, state) && return h - x2, state = next(a, state) - done(a, state) && return hash(x2, h) - - x1 = x2 - while !done(a, state) - x1 = x2 - x2, state = next(a, state) - if isequal(x2, x1) - # For repeated elements, use run length encoding - # This allows efficient hashing of sparse arrays - runlength = 2 - while !done(a, state) - x2, state = next(a, state) - isequal(x1, x2) || break - runlength += 1 - end - h += hashrle_seed - h = hash(runlength, h) - end - h = hash(x1, h) - end - !isequal(x2, x1) && (h = hash(x2, h)) - return h -end diff --git a/julia-0.6.3/share/julia/base/abstractarraymath.jl b/julia-0.6.3/share/julia/base/abstractarraymath.jl deleted file mode 100644 index 7ccea62..0000000 --- a/julia-0.6.3/share/julia/base/abstractarraymath.jl +++ /dev/null @@ -1,442 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - - ## Basic functions ## - -isreal(x::AbstractArray) = all(isreal,x) -iszero(x::AbstractArray) = all(iszero,x) -isreal(x::AbstractArray{<:Real}) = true -all(::typeof(isinteger), ::AbstractArray{<:Integer}) = true - -## Constructors ## - -""" - vec(a::AbstractArray) -> Vector - -Reshape the array `a` as a one-dimensional column vector. The resulting array -shares the same underlying data as `a`, so modifying one will also modify the -other. - -# Example -```jldoctest -julia> a = [1 2 3; 4 5 6] -2×3 Array{Int64,2}: - 1 2 3 - 4 5 6 - -julia> vec(a) -6-element Array{Int64,1}: - 1 - 4 - 2 - 5 - 3 - 6 -``` - -See also [`reshape`](@ref). -""" -vec(a::AbstractArray) = reshape(a,_length(a)) -vec(a::AbstractVector) = a - -_sub(::Tuple{}, ::Tuple{}) = () -_sub(t::Tuple, ::Tuple{}) = t -_sub(t::Tuple, s::Tuple) = _sub(tail(t), tail(s)) - -""" - squeeze(A, dims) - -Remove the dimensions specified by `dims` from array `A`. -Elements of `dims` must be unique and within the range `1:ndims(A)`. -`size(A,i)` must equal 1 for all `i` in `dims`. - -# Example -```jldoctest -julia> a = reshape(collect(1:4),(2,2,1,1)) -2×2×1×1 Array{Int64,4}: -[:, :, 1, 1] = - 1 3 - 2 4 - -julia> squeeze(a,3) -2×2×1 Array{Int64,3}: -[:, :, 1] = - 1 3 - 2 4 -``` -""" -function squeeze(A::AbstractArray, dims::Dims) - for i in 1:length(dims) - 1 <= dims[i] <= ndims(A) || throw(ArgumentError("squeezed dims must be in range 1:ndims(A)")) - size(A, dims[i]) == 1 || throw(ArgumentError("squeezed dims must all be size 1")) - for j = 1:i-1 - dims[j] == dims[i] && throw(ArgumentError("squeezed dims must be unique")) - end - end - d = () - for i = 1:ndims(A) - if !in(i, dims) - d = tuple(d..., size(A, i)) - end - end - reshape(A, d::typeof(_sub(size(A), dims))) -end - -squeeze(A::AbstractArray, dim::Integer) = squeeze(A, (Int(dim),)) - - -## Unary operators ## - -conj(x::AbstractArray{<:Real}) = x -conj!(x::AbstractArray{<:Real}) = x - -real(x::AbstractArray{<:Real}) = x -imag(x::AbstractArray{<:Real}) = zero(x) - -+(x::AbstractArray{<:Number}) = x -*(x::AbstractArray{<:Number,2}) = x - -# index A[:,:,...,i,:,:,...] where "i" is in dimension "d" - -""" - slicedim(A, d::Integer, i) - -Return all the data of `A` where the index for dimension `d` equals `i`. Equivalent to -`A[:,:,...,i,:,:,...]` where `i` is in position `d`. - -# Example -```jldoctest -julia> A = [1 2 3 4; 5 6 7 8] -2×4 Array{Int64,2}: - 1 2 3 4 - 5 6 7 8 - -julia> slicedim(A,2,3) -2-element Array{Int64,1}: - 3 - 7 -``` -""" -function slicedim(A::AbstractArray, d::Integer, i) - d >= 1 || throw(ArgumentError("dimension must be ≥ 1")) - nd = ndims(A) - d > nd && (i == 1 || throw_boundserror(A, (ntuple(k->Colon(),nd)..., ntuple(k->1,d-1-nd)..., i))) - A[setindex(indices(A), i, d)...] -end - -""" - flipdim(A, d::Integer) - -Reverse `A` in dimension `d`. - -# Example -```jldoctest -julia> b = [1 2; 3 4] -2×2 Array{Int64,2}: - 1 2 - 3 4 - -julia> flipdim(b,2) -2×2 Array{Int64,2}: - 2 1 - 4 3 -``` -""" -function flipdim(A::AbstractArray, d::Integer) - nd = ndims(A) - 1 ≤ d ≤ nd || throw(ArgumentError("dimension $d is not 1 ≤ $d ≤ $nd")) - if isempty(A) - return copy(A) - elseif nd == 1 - return reverse(A) - end - inds = indices(A) - B = similar(A) - nnd = 0 - for i = 1:nd - nnd += Int(length(inds[i])==1 || i==d) - end - indsd = inds[d] - sd = first(indsd)+last(indsd) - if nnd==nd - # flip along the only non-singleton dimension - for i in indsd - B[i] = A[sd-i] - end - return B - end - alli = [ indices(B,n) for n in 1:nd ] - for i in indsd - B[[ n==d ? sd-i : alli[n] for n in 1:nd ]...] = slicedim(A, d, i) - end - return B -end - -function circshift(a::AbstractArray, shiftamt::Real) - circshift!(similar(a), a, (Integer(shiftamt),)) -end -circshift(a::AbstractArray, shiftamt::DimsInteger) = circshift!(similar(a), a, shiftamt) -""" - circshift(A, shifts) - -Circularly shift the data in an array. The second argument is a vector giving the amount to -shift in each dimension. - -# Example -```jldoctest -julia> b = reshape(collect(1:16), (4,4)) -4×4 Array{Int64,2}: - 1 5 9 13 - 2 6 10 14 - 3 7 11 15 - 4 8 12 16 - -julia> circshift(b, (0,2)) -4×4 Array{Int64,2}: - 9 13 1 5 - 10 14 2 6 - 11 15 3 7 - 12 16 4 8 - -julia> circshift(b, (-1,0)) -4×4 Array{Int64,2}: - 2 6 10 14 - 3 7 11 15 - 4 8 12 16 - 1 5 9 13 -``` - -See also [`circshift!`](@ref). -""" -function circshift(a::AbstractArray, shiftamt) - circshift!(similar(a), a, map(Integer, (shiftamt...,))) -end - -# Uses K-B-N summation -function cumsum_kbn(v::AbstractVector{T}) where T<:AbstractFloat - r = similar(v) - if isempty(v); return r; end - - inds = indices(v, 1) - i1 = first(inds) - s = r[i1] = v[i1] - c = zero(T) - for i=i1+1:last(inds) - vi = v[i] - t = s + vi - if abs(s) >= abs(vi) - c += ((s-t) + vi) - else - c += ((vi-t) + s) - end - s = t - r[i] = s+c - end - return r -end - -# Uses K-B-N summation -# TODO: Needs a separate IndexCartesian method, this is only fast for IndexLinear - -""" - cumsum_kbn(A, [dim::Integer=1]) - -Cumulative sum along a dimension, using the Kahan-Babuska-Neumaier compensated summation -algorithm for additional accuracy. The dimension defaults to 1. -""" -function cumsum_kbn(A::AbstractArray{T}, axis::Integer=1) where T<:AbstractFloat - dimsA = size(A) - ndimsA = ndims(A) - axis_size = dimsA[axis] - axis_stride = 1 - for i = 1:(axis-1) - axis_stride *= size(A,i) - end - - if axis_size <= 1 - return A - end - - B = similar(A) - C = similar(A) - - for i = 1:length(A) - if div(i-1, axis_stride) % axis_size == 0 - B[i] = A[i] - C[i] = zero(T) - else - s = B[i-axis_stride] - Ai = A[i] - B[i] = t = s + Ai - if abs(s) >= abs(Ai) - C[i] = C[i-axis_stride] + ((s-t) + Ai) - else - C[i] = C[i-axis_stride] + ((Ai-t) + s) - end - end - end - - return B + C -end - -## Other array functions ## - -""" - repmat(A, m::Integer, n::Integer=1) - -Construct a matrix by repeating the given matrix (or vector) `m` times in dimension 1 and `n` times in -dimension 2. - -# Examples -```jldoctest -julia> repmat([1, 2, 3], 2) -6-element Array{Int64,1}: - 1 - 2 - 3 - 1 - 2 - 3 - -julia> repmat([1, 2, 3], 2, 3) -6×3 Array{Int64,2}: - 1 1 1 - 2 2 2 - 3 3 3 - 1 1 1 - 2 2 2 - 3 3 3 -``` -""" -function repmat(a::AbstractVecOrMat, m::Int, n::Int=1) - o, p = size(a,1), size(a,2) - b = similar(a, o*m, p*n) - for j=1:n - d = (j-1)*p+1 - R = d:d+p-1 - for i=1:m - c = (i-1)*o+1 - b[c:c+o-1, R] = a - end - end - return b -end - -function repmat(a::AbstractVector, m::Int) - o = length(a) - b = similar(a, o*m) - for i=1:m - c = (i-1)*o+1 - b[c:c+o-1] = a - end - return b -end - -@inline repmat(a::AbstractVecOrMat, m::Integer, n::Integer=1) = repmat(a, Int(m), Int(n)) -@inline repmat(a::AbstractVector, m::Integer) = repmat(a, Int(m)) - -""" - repeat(A::AbstractArray; inner=ntuple(x->1, ndims(A)), outer=ntuple(x->1, ndims(A))) - -Construct an array by repeating the entries of `A`. The i-th element of `inner` specifies -the number of times that the individual entries of the i-th dimension of `A` should be -repeated. The i-th element of `outer` specifies the number of times that a slice along the -i-th dimension of `A` should be repeated. If `inner` or `outer` are omitted, no repetition -is performed. - -# Examples -```jldoctest -julia> repeat(1:2, inner=2) -4-element Array{Int64,1}: - 1 - 1 - 2 - 2 - -julia> repeat(1:2, outer=2) -4-element Array{Int64,1}: - 1 - 2 - 1 - 2 - -julia> repeat([1 2; 3 4], inner=(2, 1), outer=(1, 3)) -4×6 Array{Int64,2}: - 1 2 1 2 1 2 - 1 2 1 2 1 2 - 3 4 3 4 3 4 - 3 4 3 4 3 4 -``` -""" -function repeat(A::AbstractArray; - inner=ntuple(n->1, Val{ndims(A)}), - outer=ntuple(n->1, Val{ndims(A)})) - return _repeat(A, rep_kw2tup(inner), rep_kw2tup(outer)) -end - -rep_kw2tup(n::Integer) = (n,) -rep_kw2tup(v::AbstractArray{<:Integer}) = (v...) -rep_kw2tup(t::Tuple) = t - -rep_shapes(A, i, o) = _rshps((), (), size(A), i, o) - -_rshps(shp, shp_i, ::Tuple{}, ::Tuple{}, ::Tuple{}) = (shp, shp_i) -@inline _rshps(shp, shp_i, ::Tuple{}, ::Tuple{}, o) = - _rshps((shp..., o[1]), (shp_i..., 1), (), (), tail(o)) -@inline _rshps(shp, shp_i, ::Tuple{}, i, ::Tuple{}) = (n = i[1]; - _rshps((shp..., n), (shp_i..., n), (), tail(i), ())) -@inline _rshps(shp, shp_i, ::Tuple{}, i, o) = (n = i[1]; - _rshps((shp..., n * o[1]), (shp_i..., n), (), tail(i), tail(o))) -@inline _rshps(shp, shp_i, sz, i, o) = (n = sz[1] * i[1]; - _rshps((shp..., n * o[1]), (shp_i..., n), tail(sz), tail(i), tail(o))) -_rshps(shp, shp_i, sz, ::Tuple{}, ::Tuple{}) = - (n = length(shp); N = n + length(sz); _reperr("inner", n, N)) -_rshps(shp, shp_i, sz, ::Tuple{}, o) = - (n = length(shp); N = n + length(sz); _reperr("inner", n, N)) -_rshps(shp, shp_i, sz, i, ::Tuple{}) = - (n = length(shp); N = n + length(sz); _reperr("outer", n, N)) -_reperr(s, n, N) = throw(ArgumentError("number of " * s * " repetitions " * - "($n) cannot be less than number of dimensions of input ($N)")) - -# We need special handling when repeating arrays of arrays -cat_fill!(R, X, inds) = (R[inds...] = X) -cat_fill!(R, X::AbstractArray, inds) = fill!(view(R, inds...), X) - -@noinline function _repeat(A::AbstractArray, inner, outer) - shape, inner_shape = rep_shapes(A, inner, outer) - - R = similar(A, shape) - if any(iszero, shape) - return R - end - - # fill the first inner block - if all(x -> x == 1, inner) - R[indices(A)...] = A - else - inner_indices = [1:n for n in inner] - for c in CartesianRange(indices(A)) - for i in 1:ndims(A) - n = inner[i] - inner_indices[i] = (1:n) + ((c[i] - 1) * n) - end - cat_fill!(R, A[c], inner_indices) - end - end - - # fill the outer blocks along each dimension - if all(x -> x == 1, outer) - return R - end - src_indices = [1:n for n in inner_shape] - dest_indices = copy(src_indices) - for i in 1:length(outer) - B = view(R, src_indices...) - for j in 2:outer[i] - dest_indices[i] += inner_shape[i] - R[dest_indices...] = B - end - src_indices[i] = dest_indices[i] = 1:shape[i] - end - - return R -end diff --git a/julia-0.6.3/share/julia/base/array.jl b/julia-0.6.3/share/julia/base/array.jl deleted file mode 100644 index b1e8577..0000000 --- a/julia-0.6.3/share/julia/base/array.jl +++ /dev/null @@ -1,2014 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -## array.jl: Dense arrays - -## Type aliases for convenience ## - -const AbstractVector{T} = AbstractArray{T,1} -const AbstractMatrix{T} = AbstractArray{T,2} -const AbstractVecOrMat{T} = Union{AbstractVector{T}, AbstractMatrix{T}} -const RangeIndex = Union{Int, Range{Int}, AbstractUnitRange{Int}} -const DimOrInd = Union{Integer, AbstractUnitRange} -const IntOrInd = Union{Int, AbstractUnitRange} -const DimsOrInds{N} = NTuple{N,DimOrInd} -const NeedsShaping = Union{Tuple{Integer,Vararg{Integer}}, Tuple{OneTo,Vararg{OneTo}}} - -const Vector{T} = Array{T,1} -const Matrix{T} = Array{T,2} -const VecOrMat{T} = Union{Vector{T}, Matrix{T}} - -const DenseVector{T} = DenseArray{T,1} -const DenseMatrix{T} = DenseArray{T,2} -const DenseVecOrMat{T} = Union{DenseVector{T}, DenseMatrix{T}} - -## Basic functions ## - -""" - eltype(type) - -Determine the type of the elements generated by iterating a collection of the given `type`. -For associative collection types, this will be a `Pair{KeyType,ValType}`. The definition -`eltype(x) = eltype(typeof(x))` is provided for convenience so that instances can be passed -instead of types. However the form that accepts a type argument should be defined for new -types. - -```jldoctest -julia> eltype(ones(Float32,2,2)) -Float32 - -julia> eltype(ones(Int8,2,2)) -Int8 -``` -""" -eltype(::Type) = Any -eltype(::Type{Any}) = Any -eltype(::Type{Bottom}) = throw(ArgumentError("Union{} does not have elements")) -eltype(t::DataType) = eltype(supertype(t)) -eltype(x) = eltype(typeof(x)) - -import Core: arraysize, arrayset, arrayref - -""" - Array{T}(dims) - Array{T,N}(dims) - -Construct an uninitialized `N`-dimensional dense array with element type `T`, -where `N` is determined from the length or number of `dims`. `dims` may -be a tuple or a series of integer arguments corresponding to the lengths in each dimension. -If the rank `N` is supplied explicitly as in `Array{T,N}(dims)`, then it must -match the length or number of `dims`. - -# Example - -```jldoctest -julia> A = Array{Float64, 2}(2, 2); - -julia> ndims(A) -2 - -julia> eltype(A) -Float64 -``` -""" -Array - -vect() = Array{Any,1}(0) -vect(X::T...) where {T} = T[ X[i] for i = 1:length(X) ] - -function vect(X...) - T = promote_typeof(X...) - #T[ X[i] for i=1:length(X) ] - # TODO: this is currently much faster. should figure out why. not clear. - return copy!(Array{T,1}(length(X)), X) -end - -size(a::Array, d) = arraysize(a, d) -size(a::Vector) = (arraysize(a,1),) -size(a::Matrix) = (arraysize(a,1), arraysize(a,2)) -size(a::Array{<:Any,N}) where {N} = (@_inline_meta; ntuple(M -> size(a, M), Val{N})) - -asize_from(a::Array, n) = n > ndims(a) ? () : (arraysize(a,n), asize_from(a, n+1)...) - -length(a::Array) = arraylen(a) -elsize(a::Array{T}) where {T} = isbits(T) ? sizeof(T) : sizeof(Ptr) -sizeof(a::Array) = elsize(a) * length(a) - -function isassigned(a::Array, i::Int...) - @_inline_meta - ii = (sub2ind(size(a), i...) % UInt) - 1 - ii < length(a) % UInt || return false - ccall(:jl_array_isassigned, Cint, (Any, UInt), a, ii) == 1 -end - -## copy ## - -function unsafe_copy!(dest::Ptr{T}, src::Ptr{T}, n) where T - # Do not use this to copy data between pointer arrays. - # It can't be made safe no matter how carefully you checked. - ccall(:memmove, Ptr{Void}, (Ptr{Void}, Ptr{Void}, UInt), - dest, src, n*sizeof(T)) - return dest -end - -function unsafe_copy!(dest::Array{T}, doffs, src::Array{T}, soffs, n) where T - if isbits(T) - unsafe_copy!(pointer(dest, doffs), pointer(src, soffs), n) - else - ccall(:jl_array_ptr_copy, Void, (Any, Ptr{Void}, Any, Ptr{Void}, Int), - dest, pointer(dest, doffs), src, pointer(src, soffs), n) - end - return dest -end - -function copy!(dest::Array{T}, doffs::Integer, src::Array{T}, soffs::Integer, n::Integer) where T - n == 0 && return dest - n > 0 || throw(ArgumentError(string("tried to copy n=", n, " elements, but n should be nonnegative"))) - if soffs < 1 || doffs < 1 || soffs+n-1 > length(src) || doffs+n-1 > length(dest) - throw(BoundsError()) - end - unsafe_copy!(dest, doffs, src, soffs, n) -end - -copy!(dest::Array{T}, src::Array{T}) where {T} = copy!(dest, 1, src, 1, length(src)) - -copy(a::T) where {T<:Array} = ccall(:jl_array_copy, Ref{T}, (Any,), a) - -function reinterpret(::Type{T}, a::Array{S,1}) where T where S - nel = Int(div(length(a)*sizeof(S),sizeof(T))) - # TODO: maybe check that remainder is zero? - return reinterpret(T, a, (nel,)) -end - -function reinterpret(::Type{T}, a::Array{S}) where T where S - if sizeof(S) != sizeof(T) - throw(ArgumentError("result shape not specified")) - end - reinterpret(T, a, size(a)) -end - -function reinterpret(::Type{T}, a::Array{S}, dims::NTuple{N,Int}) where T where S where N - if !isbits(T) - throw(ArgumentError("cannot reinterpret Array{$(S)} to ::Type{Array{$(T)}}, type $(T) is not a bits type")) - end - if !isbits(S) - throw(ArgumentError("cannot reinterpret Array{$(S)} to ::Type{Array{$(T)}}, type $(S) is not a bits type")) - end - nel = div(length(a)*sizeof(S),sizeof(T)) - if prod(dims) != nel - throw(DimensionMismatch("new dimensions $(dims) must be consistent with array size $(nel)")) - end - ccall(:jl_reshape_array, Array{T,N}, (Any, Any, Any), Array{T,N}, a, dims) -end - -# reshaping to same # of dimensions -function reshape(a::Array{T,N}, dims::NTuple{N,Int}) where T where N - if prod(dims) != length(a) - throw(DimensionMismatch("new dimensions $(dims) must be consistent with array size $(length(a))")) - end - if dims == size(a) - return a - end - ccall(:jl_reshape_array, Array{T,N}, (Any, Any, Any), Array{T,N}, a, dims) -end - -# reshaping to different # of dimensions -function reshape(a::Array{T}, dims::NTuple{N,Int}) where T where N - if prod(dims) != length(a) - throw(DimensionMismatch("new dimensions $(dims) must be consistent with array size $(length(a))")) - end - ccall(:jl_reshape_array, Array{T,N}, (Any, Any, Any), Array{T,N}, a, dims) -end - -## Constructors ## - -similar(a::Array{T,1}) where {T} = Array{T,1}(size(a,1)) -similar(a::Array{T,2}) where {T} = Array{T,2}(size(a,1), size(a,2)) -similar(a::Array{T,1}, S::Type) where {T} = Array{S,1}(size(a,1)) -similar(a::Array{T,2}, S::Type) where {T} = Array{S,2}(size(a,1), size(a,2)) -similar(a::Array{T}, m::Int) where {T} = Array{T,1}(m) -similar(a::Array, T::Type, dims::Dims{N}) where {N} = Array{T,N}(dims) -similar(a::Array{T}, dims::Dims{N}) where {T,N} = Array{T,N}(dims) - -# T[x...] constructs Array{T,1} -function getindex(::Type{T}, vals...) where T - a = Array{T,1}(length(vals)) - @inbounds for i = 1:length(vals) - a[i] = vals[i] - end - return a -end - -getindex(::Type{T}) where {T} = (@_inline_meta; Array{T,1}(0)) -getindex(::Type{T}, x) where {T} = (@_inline_meta; a = Array{T,1}(1); @inbounds a[1] = x; a) -getindex(::Type{T}, x, y) where {T} = (@_inline_meta; a = Array{T,1}(2); @inbounds (a[1] = x; a[2] = y); a) -getindex(::Type{T}, x, y, z) where {T} = (@_inline_meta; a = Array{T,1}(3); @inbounds (a[1] = x; a[2] = y; a[3] = z); a) - -function getindex(::Type{Any}, vals::ANY...) - a = Array{Any,1}(length(vals)) - @inbounds for i = 1:length(vals) - a[i] = vals[i] - end - return a -end -getindex(::Type{Any}) = Array{Any,1}(0) - -function fill!(a::Union{Array{UInt8}, Array{Int8}}, x::Integer) - ccall(:memset, Ptr{Void}, (Ptr{Void}, Cint, Csize_t), a, x, length(a)) - return a -end - -function fill!(a::Array{T}, x) where T<:Union{Integer,AbstractFloat} - xT = convert(T, x) - for i in eachindex(a) - @inbounds a[i] = xT - end - return a -end - - -""" - fill(x, dims) - -Create an array filled with the value `x`. For example, `fill(1.0, (5,5))` returns a 5×5 -array of floats, with each element initialized to `1.0`. - -```jldoctest -julia> fill(1.0, (5,5)) -5×5 Array{Float64,2}: - 1.0 1.0 1.0 1.0 1.0 - 1.0 1.0 1.0 1.0 1.0 - 1.0 1.0 1.0 1.0 1.0 - 1.0 1.0 1.0 1.0 1.0 - 1.0 1.0 1.0 1.0 1.0 -``` - -If `x` is an object reference, all elements will refer to the same object. `fill(Foo(), -dims)` will return an array filled with the result of evaluating `Foo()` once. -""" -fill(v, dims::Dims) = fill!(Array{typeof(v)}(dims), v) -fill(v, dims::Integer...) = fill!(Array{typeof(v)}(dims...), v) - -for (fname, felt) in ((:zeros,:zero), (:ones,:one)) - @eval begin - # allow signature of similar - $fname(a::AbstractArray, T::Type, dims::Tuple) = fill!(similar(a, T, dims), $felt(T)) - $fname(a::AbstractArray, T::Type, dims...) = fill!(similar(a,T,dims...), $felt(T)) - $fname(a::AbstractArray, T::Type=eltype(a)) = fill!(similar(a,T), $felt(T)) - - $fname(T::Type, dims::Tuple) = fill!(Array{T}(Dims(dims)), $felt(T)) - $fname(dims::Tuple) = ($fname)(Float64, dims) - $fname(T::Type, dims...) = $fname(T, dims) - $fname(dims...) = $fname(dims) - end -end - -""" - eye([T::Type=Float64,] m::Integer, n::Integer) - -`m`-by-`n` identity matrix. -The default element type is [`Float64`](@ref). - -# Examples - -```jldoctest -julia> eye(3, 4) -3×4 Array{Float64,2}: - 1.0 0.0 0.0 0.0 - 0.0 1.0 0.0 0.0 - 0.0 0.0 1.0 0.0 - -julia> eye(2, 2) -2×2 Array{Float64,2}: - 1.0 0.0 - 0.0 1.0 - -julia> eye(Int, 2, 2) -2×2 Array{Int64,2}: - 1 0 - 0 1 -``` -""" -function eye(::Type{T}, m::Integer, n::Integer) where T - a = zeros(T,m,n) - for i = 1:min(m,n) - a[i,i] = oneunit(T) - end - return a -end - -""" - eye(m, n) - -`m`-by-`n` identity matrix. -""" -eye(m::Integer, n::Integer) = eye(Float64, m, n) -eye(::Type{T}, n::Integer) where {T} = eye(T, n, n) -""" - eye([T::Type=Float64,] n::Integer) - -`n`-by-`n` identity matrix. -The default element type is [`Float64`](@ref). - -# Examples -```jldoctest -julia> eye(Int, 2) -2×2 Array{Int64,2}: - 1 0 - 0 1 - -julia> eye(2) -2×2 Array{Float64,2}: - 1.0 0.0 - 0.0 1.0 -``` -""" -eye(n::Integer) = eye(Float64, n) - -""" - eye(A) - -Constructs an identity matrix of the same dimensions and type as `A`. - -```jldoctest -julia> A = [1 2 3; 4 5 6; 7 8 9] -3×3 Array{Int64,2}: - 1 2 3 - 4 5 6 - 7 8 9 - -julia> eye(A) -3×3 Array{Int64,2}: - 1 0 0 - 0 1 0 - 0 0 1 -``` - -Note the difference from [`ones`](@ref). -""" -eye(x::AbstractMatrix{T}) where {T} = eye(typeof(one(T)), size(x, 1), size(x, 2)) - -function _one(unit::T, x::AbstractMatrix) where T - m,n = size(x) - m==n || throw(DimensionMismatch("multiplicative identity defined only for square matrices")) - eye(T, m) -end - -one(x::AbstractMatrix{T}) where {T} = _one(one(T), x) -oneunit(x::AbstractMatrix{T}) where {T} = _one(oneunit(T), x) - -## Conversions ## - -convert(::Type{Vector}, x::AbstractVector{T}) where {T} = convert(Vector{T}, x) -convert(::Type{Matrix}, x::AbstractMatrix{T}) where {T} = convert(Matrix{T}, x) - -convert(::Type{Array{T}}, x::Array{T,n}) where {T,n} = x -convert(::Type{Array{T,n}}, x::Array{T,n}) where {T,n} = x - -convert(::Type{Array{T}}, x::AbstractArray{S,n}) where {T,n,S} = convert(Array{T,n}, x) -convert(::Type{Array{T,n}}, x::AbstractArray{S,n}) where {T,n,S} = copy!(Array{T,n}(size(x)), x) - -promote_rule(::Type{Array{T,n}}, ::Type{Array{S,n}}) where {T,n,S} = Array{promote_type(T,S),n} - -## copying iterators to containers - -""" - collect(element_type, collection) - -Return an `Array` with the given element type of all items in a collection or iterable. -The result has the same shape and number of dimensions as `collection`. - -```jldoctest -julia> collect(Float64, 1:2:5) -3-element Array{Float64,1}: - 1.0 - 3.0 - 5.0 -``` -""" -collect(::Type{T}, itr) where {T} = _collect(T, itr, iteratorsize(itr)) - -_collect(::Type{T}, itr, isz::HasLength) where {T} = copy!(Array{T,1}(Int(length(itr)::Integer)), itr) -_collect(::Type{T}, itr, isz::HasShape) where {T} = copy!(similar(Array{T}, indices(itr)), itr) -function _collect(::Type{T}, itr, isz::SizeUnknown) where T - a = Array{T,1}(0) - for x in itr - push!(a,x) - end - return a -end - -# make a collection similar to `c` and appropriate for collecting `itr` -_similar_for(c::AbstractArray, T, itr, ::SizeUnknown) = similar(c, T, 0) -_similar_for(c::AbstractArray, T, itr, ::HasLength) = similar(c, T, Int(length(itr)::Integer)) -_similar_for(c::AbstractArray, T, itr, ::HasShape) = similar(c, T, indices(itr)) -_similar_for(c, T, itr, isz) = similar(c, T) - -""" - collect(collection) - -Return an `Array` of all items in a collection or iterator. For associative collections, returns -`Pair{KeyType, ValType}`. If the argument is array-like or is an iterator with the `HasShape()` -trait, the result will have the same shape and number of dimensions as the argument. - -# Example -```jldoctest -julia> collect(1:2:13) -7-element Array{Int64,1}: - 1 - 3 - 5 - 7 - 9 - 11 - 13 -``` -""" -collect(itr) = _collect(1:1 #= Array =#, itr, iteratoreltype(itr), iteratorsize(itr)) - -collect(A::AbstractArray) = _collect_indices(indices(A), A) - -collect_similar(cont, itr) = _collect(cont, itr, iteratoreltype(itr), iteratorsize(itr)) - -_collect(cont, itr, ::HasEltype, isz::Union{HasLength,HasShape}) = - copy!(_similar_for(cont, eltype(itr), itr, isz), itr) - -function _collect(cont, itr, ::HasEltype, isz::SizeUnknown) - a = _similar_for(cont, eltype(itr), itr, isz) - for x in itr - push!(a,x) - end - return a -end - -_collect_indices(::Tuple{}, A) = copy!(Array{eltype(A)}(), A) -_collect_indices(indsA::Tuple{Vararg{OneTo}}, A) = - copy!(Array{eltype(A)}(length.(indsA)), A) -function _collect_indices(indsA, A) - B = Array{eltype(A)}(length.(indsA)) - copy!(B, CartesianRange(indices(B)), A, CartesianRange(indsA)) -end - -if isdefined(Core, :Inference) - _default_eltype(itrt::ANY) = Core.Inference.return_type(first, Tuple{itrt}) -else - _default_eltype(itr::ANY) = Any -end - -_array_for(::Type{T}, itr, ::HasLength) where {T} = Array{T,1}(Int(length(itr)::Integer)) -_array_for(::Type{T}, itr, ::HasShape) where {T} = similar(Array{T}, indices(itr)) - -function collect(itr::Generator) - isz = iteratorsize(itr.iter) - et = _default_eltype(typeof(itr)) - if isa(isz, SizeUnknown) - return grow_to!(Array{et,1}(0), itr) - else - st = start(itr) - if done(itr,st) - return _array_for(et, itr.iter, isz) - end - v1, st = next(itr, st) - collect_to_with_first!(_array_for(typeof(v1), itr.iter, isz), v1, itr, st) - end -end - -_collect(c, itr, ::EltypeUnknown, isz::SizeUnknown) = - grow_to!(_similar_for(c, _default_eltype(typeof(itr)), itr, isz), itr) - -function _collect(c, itr, ::EltypeUnknown, isz::Union{HasLength,HasShape}) - st = start(itr) - if done(itr,st) - return _similar_for(c, _default_eltype(typeof(itr)), itr, isz) - end - v1, st = next(itr, st) - collect_to_with_first!(_similar_for(c, typeof(v1), itr, isz), v1, itr, st) -end - -function collect_to_with_first!(dest::AbstractArray, v1, itr, st) - i1 = first(linearindices(dest)) - dest[i1] = v1 - return collect_to!(dest, itr, i1+1, st) -end - -function collect_to_with_first!(dest, v1, itr, st) - push!(dest, v1) - return grow_to!(dest, itr, st) -end - -function collect_to!(dest::AbstractArray{T}, itr, offs, st) where T - # collect to dest array, checking the type of each result. if a result does not - # match, widen the result type and re-dispatch. - i = offs - while !done(itr, st) - el, st = next(itr, st) - S = typeof(el) - if S === T || S <: T - @inbounds dest[i] = el::T - i += 1 - else - R = typejoin(T, S) - new = similar(dest, R) - copy!(new,1, dest,1, i-1) - @inbounds new[i] = el - return collect_to!(new, itr, i+1, st) - end - end - return dest -end - -function grow_to!(dest, itr) - out = grow_to!(similar(dest,Union{}), itr, start(itr)) - return isempty(out) ? dest : out -end - -function grow_to!(dest, itr, st) - T = eltype(dest) - while !done(itr, st) - el, st = next(itr, st) - S = typeof(el) - if S === T || S <: T - push!(dest, el::T) - else - new = similar(dest, typejoin(T, S)) - copy!(new, dest) - push!(new, el) - return grow_to!(new, itr, st) - end - end - return dest -end - -## Iteration ## -start(A::Array) = 1 -next(a::Array,i) = (@_propagate_inbounds_meta; (a[i],i+1)) -done(a::Array,i) = (@_inline_meta; i == length(a)+1) - -## Indexing: getindex ## - -# This is more complicated than it needs to be in order to get Win64 through bootstrap -getindex(A::Array, i1::Int) = arrayref(A, i1) -getindex(A::Array, i1::Int, i2::Int, I::Int...) = (@_inline_meta; arrayref(A, i1, i2, I...)) # TODO: REMOVE FOR #14770 - -# Faster contiguous indexing using copy! for UnitRange and Colon -function getindex(A::Array, I::UnitRange{Int}) - @_inline_meta - @boundscheck checkbounds(A, I) - lI = length(I) - X = similar(A, lI) - if lI > 0 - unsafe_copy!(X, 1, A, first(I), lI) - end - return X -end -function getindex(A::Array, c::Colon) - lI = length(A) - X = similar(A, lI) - if lI > 0 - unsafe_copy!(X, 1, A, 1, lI) - end - return X -end - -# This is redundant with the abstract fallbacks, but needed for bootstrap -function getindex(A::Array{S}, I::Range{Int}) where S - return S[ A[i] for i in I ] -end - -## Indexing: setindex! ## -setindex!(A::Array{T}, x, i1::Int) where {T} = arrayset(A, convert(T,x)::T, i1) -setindex!(A::Array{T}, x, i1::Int, i2::Int, I::Int...) where {T} = (@_inline_meta; arrayset(A, convert(T,x)::T, i1, i2, I...)) # TODO: REMOVE FOR #14770 - -# These are redundant with the abstract fallbacks but needed for bootstrap -function setindex!(A::Array, x, I::AbstractVector{Int}) - @_propagate_inbounds_meta - A === I && (I = copy(I)) - for i in I - A[i] = x - end - return A -end -function setindex!(A::Array, X::AbstractArray, I::AbstractVector{Int}) - @_propagate_inbounds_meta - @boundscheck setindex_shape_check(X, length(I)) - count = 1 - if X === A - X = copy(X) - I===A && (I = X::typeof(I)) - elseif I === A - I = copy(I) - end - for i in I - @inbounds x = X[count] - A[i] = x - count += 1 - end - return A -end - -# Faster contiguous setindex! with copy! -function setindex!(A::Array{T}, X::Array{T}, I::UnitRange{Int}) where T - @_inline_meta - @boundscheck checkbounds(A, I) - lI = length(I) - @boundscheck setindex_shape_check(X, lI) - if lI > 0 - unsafe_copy!(A, first(I), X, 1, lI) - end - return A -end -function setindex!(A::Array{T}, X::Array{T}, c::Colon) where T - @_inline_meta - lI = length(A) - @boundscheck setindex_shape_check(X, lI) - if lI > 0 - unsafe_copy!(A, 1, X, 1, lI) - end - return A -end - -setindex!(A::Array, x::Number, ::Colon) = fill!(A, x) -setindex!(A::Array{T, N}, x::Number, ::Vararg{Colon, N}) where {T, N} = fill!(A, x) - -# efficiently grow an array - -_growat!(a::Vector, i::Integer, delta::Integer) = - ccall(:jl_array_grow_at, Void, (Any, Int, UInt), a, i - 1, delta) - -# efficiently delete part of an array - -_deleteat!(a::Vector, i::Integer, delta::Integer) = - ccall(:jl_array_del_at, Void, (Any, Int, UInt), a, i - 1, delta) - -## Dequeue functionality ## - -function push!(a::Array{T,1}, item) where T - # convert first so we don't grow the array if the assignment won't work - itemT = convert(T, item) - ccall(:jl_array_grow_end, Void, (Any, UInt), a, 1) - a[end] = itemT - return a -end - -function push!(a::Array{Any,1}, item::ANY) - ccall(:jl_array_grow_end, Void, (Any, UInt), a, 1) - arrayset(a, item, length(a)) - return a -end - -function append!(a::Array{<:Any,1}, items::AbstractVector) - itemindices = eachindex(items) - n = length(itemindices) - ccall(:jl_array_grow_end, Void, (Any, UInt), a, n) - copy!(a, length(a)-n+1, items, first(itemindices), n) - return a -end - -append!(a::Vector, iter) = _append!(a, iteratorsize(iter), iter) -push!(a::Vector, iter...) = append!(a, iter) - -function _append!(a, ::Union{HasLength,HasShape}, iter) - n = length(a) - resize!(a, n+length(iter)) - @inbounds for (i,item) in zip(n+1:length(a), iter) - a[i] = item - end - a -end - -function _append!(a, ::IteratorSize, iter) - for item in iter - push!(a, item) - end - a -end - -""" - prepend!(a::Vector, items) -> collection - -Insert the elements of `items` to the beginning of `a`. - -# Example -```jldoctest -julia> prepend!([3],[1,2]) -3-element Array{Int64,1}: - 1 - 2 - 3 -``` -""" -function prepend! end - -function prepend!(a::Array{<:Any,1}, items::AbstractVector) - itemindices = eachindex(items) - n = length(itemindices) - ccall(:jl_array_grow_beg, Void, (Any, UInt), a, n) - if a === items - copy!(a, 1, items, n+1, n) - else - copy!(a, 1, items, first(itemindices), n) - end - return a -end - -prepend!(a::Vector, iter) = _prepend!(a, iteratorsize(iter), iter) -unshift!(a::Vector, iter...) = prepend!(a, iter) - -function _prepend!(a, ::Union{HasLength,HasShape}, iter) - n = length(iter) - ccall(:jl_array_grow_beg, Void, (Any, UInt), a, n) - i = 0 - for item in iter - @inbounds a[i += 1] = item - end - a -end -function _prepend!(a, ::IteratorSize, iter) - n = 0 - for item in iter - n += 1 - unshift!(a, item) - end - reverse!(a, 1, n) - a -end - - -""" - resize!(a::Vector, n::Integer) -> Vector - -Resize `a` to contain `n` elements. If `n` is smaller than the current collection -length, the first `n` elements will be retained. If `n` is larger, the new elements are not -guaranteed to be initialized. - -# Examples -```jldoctest -julia> resize!([6, 5, 4, 3, 2, 1], 3) -3-element Array{Int64,1}: - 6 - 5 - 4 - -julia> a = resize!([6, 5, 4, 3, 2, 1], 8); - -julia> length(a) -8 - -julia> a[1:6] -6-element Array{Int64,1}: - 6 - 5 - 4 - 3 - 2 - 1 -``` -""" -function resize!(a::Vector, nl::Integer) - l = length(a) - if nl > l - ccall(:jl_array_grow_end, Void, (Any, UInt), a, nl-l) - else - if nl < 0 - throw(ArgumentError("new length must be ≥ 0")) - end - ccall(:jl_array_del_end, Void, (Any, UInt), a, l-nl) - end - return a -end - -function sizehint!(a::Vector, sz::Integer) - ccall(:jl_array_sizehint, Void, (Any, UInt), a, sz) - a -end - -function pop!(a::Vector) - if isempty(a) - throw(ArgumentError("array must be non-empty")) - end - item = a[end] - ccall(:jl_array_del_end, Void, (Any, UInt), a, 1) - return item -end - -""" - unshift!(collection, items...) -> collection - -Insert one or more `items` at the beginning of `collection`. - -# Example -```jldoctest -julia> unshift!([1, 2, 3, 4], 5, 6) -6-element Array{Int64,1}: - 5 - 6 - 1 - 2 - 3 - 4 -``` -""" -function unshift!(a::Array{T,1}, item) where T - item = convert(T, item) - ccall(:jl_array_grow_beg, Void, (Any, UInt), a, 1) - a[1] = item - return a -end - -function shift!(a::Vector) - if isempty(a) - throw(ArgumentError("array must be non-empty")) - end - item = a[1] - ccall(:jl_array_del_beg, Void, (Any, UInt), a, 1) - return item -end - -""" - insert!(a::Vector, index::Integer, item) - -Insert an `item` into `a` at the given `index`. `index` is the index of `item` in -the resulting `a`. - -# Example -```jldoctest -julia> insert!([6, 5, 4, 2, 1], 4, 3) -6-element Array{Int64,1}: - 6 - 5 - 4 - 3 - 2 - 1 -``` -""" -function insert!(a::Array{T,1}, i::Integer, item) where T - # Throw convert error before changing the shape of the array - _item = convert(T, item) - _growat!(a, i, 1) - # _growat! already did bound check - @inbounds a[i] = _item - return a -end - -""" - deleteat!(a::Vector, i::Integer) - -Remove the item at the given `i` and return the modified `a`. Subsequent items -are shifted to fill the resulting gap. - -# Example -```jldoctest -julia> deleteat!([6, 5, 4, 3, 2, 1], 2) -5-element Array{Int64,1}: - 6 - 4 - 3 - 2 - 1 -``` -""" -deleteat!(a::Vector, i::Integer) = (_deleteat!(a, i, 1); a) - -function deleteat!(a::Vector, r::UnitRange{<:Integer}) - n = length(a) - isempty(r) || _deleteat!(a, first(r), length(r)) - return a -end - -""" - deleteat!(a::Vector, inds) - -Remove the items at the indices given by `inds`, and return the modified `a`. -Subsequent items are shifted to fill the resulting gap. - -`inds` can be either an iterator or a collection of sorted and unique integer indices, -or a boolean vector of the same length as `a` with `true` indicating entries to delete. - -# Examples -```jldoctest -julia> deleteat!([6, 5, 4, 3, 2, 1], 1:2:5) -3-element Array{Int64,1}: - 5 - 3 - 1 - -julia> deleteat!([6, 5, 4, 3, 2, 1], [true, false, true, false, true, false]) -3-element Array{Int64,1}: - 5 - 3 - 1 - -julia> deleteat!([6, 5, 4, 3, 2, 1], (2, 2)) -ERROR: ArgumentError: indices must be unique and sorted -Stacktrace: - [1] _deleteat!(::Array{Int64,1}, ::Tuple{Int64,Int64}) at ./array.jl:921 - [2] deleteat!(::Array{Int64,1}, ::Tuple{Int64,Int64}) at ./array.jl:908 -``` -""" -deleteat!(a::Vector, inds) = _deleteat!(a, inds) -deleteat!(a::Vector, inds::AbstractVector) = _deleteat!(a, to_indices(a, (inds,))[1]) - -function _deleteat!(a::Vector, inds) - n = length(a) - s = start(inds) - done(inds, s) && return a - (p, s) = next(inds, s) - q = p+1 - while !done(inds, s) - (i,s) = next(inds, s) - if !(q <= i <= n) - if i < q - throw(ArgumentError("indices must be unique and sorted")) - else - throw(BoundsError()) - end - end - while q < i - @inbounds a[p] = a[q] - p += 1; q += 1 - end - q = i+1 - end - while q <= n - @inbounds a[p] = a[q] - p += 1; q += 1 - end - ccall(:jl_array_del_end, Void, (Any, UInt), a, n-p+1) - return a -end - -# Simpler and more efficient version for logical indexing -function deleteat!(a::Vector, inds::AbstractVector{Bool}) - n = length(a) - length(inds) == n || throw(BoundsError(a, inds)) - p = 1 - for (q, i) in enumerate(inds) - @inbounds a[p] = a[q] - p += !i - end - ccall(:jl_array_del_end, Void, (Any, UInt), a, n-p+1) - return a -end - -const _default_splice = [] - -""" - splice!(a::Vector, index::Integer, [replacement]) -> item - -Remove the item at the given index, and return the removed item. -Subsequent items are shifted left to fill the resulting gap. -If specified, replacement values from an ordered -collection will be spliced in place of the removed item. - -# Examples -```jldoctest splice! -julia> A = [6, 5, 4, 3, 2, 1]; splice!(A, 5) -2 - -julia> A -5-element Array{Int64,1}: - 6 - 5 - 4 - 3 - 1 - -julia> splice!(A, 5, -1) -1 - -julia> A -5-element Array{Int64,1}: - 6 - 5 - 4 - 3 - -1 - -julia> splice!(A, 1, [-1, -2, -3]) -6 - -julia> A -7-element Array{Int64,1}: - -1 - -2 - -3 - 5 - 4 - 3 - -1 -``` - -To insert `replacement` before an index `n` without removing any items, use -`splice!(collection, n:n-1, replacement)`. -""" -function splice!(a::Vector, i::Integer, ins=_default_splice) - v = a[i] - m = length(ins) - if m == 0 - _deleteat!(a, i, 1) - elseif m == 1 - a[i] = ins[1] - else - _growat!(a, i, m-1) - k = 1 - for x in ins - a[i+k-1] = x - k += 1 - end - end - return v -end - -""" - splice!(a::Vector, range, [replacement]) -> items - -Remove items in the specified index range, and return a collection containing -the removed items. -Subsequent items are shifted left to fill the resulting gap. -If specified, replacement values from an ordered collection will be spliced in -place of the removed items. - -To insert `replacement` before an index `n` without removing any items, use -`splice!(collection, n:n-1, replacement)`. - -# Example -```jldoctest splice! -julia> splice!(A, 4:3, 2) -0-element Array{Int64,1} - -julia> A -8-element Array{Int64,1}: - -1 - -2 - -3 - 2 - 5 - 4 - 3 - -1 -``` -""" -function splice!(a::Vector, r::UnitRange{<:Integer}, ins=_default_splice) - v = a[r] - m = length(ins) - if m == 0 - deleteat!(a, r) - return v - end - - n = length(a) - f = first(r) - l = last(r) - d = length(r) - - if m < d - delta = d - m - _deleteat!(a, (f - 1 < n - l) ? f : (l - delta + 1), delta) - elseif m > d - _growat!(a, (f - 1 < n - l) ? f : (l + 1), m - d) - end - - k = 1 - for x in ins - a[f+k-1] = x - k += 1 - end - return v -end - -function empty!(a::Vector) - ccall(:jl_array_del_end, Void, (Any, UInt), a, length(a)) - return a -end - -# use memcmp for lexcmp on byte arrays -function lexcmp(a::Array{UInt8,1}, b::Array{UInt8,1}) - c = ccall(:memcmp, Int32, (Ptr{UInt8}, Ptr{UInt8}, UInt), - a, b, min(length(a),length(b))) - return c < 0 ? -1 : c > 0 ? +1 : cmp(length(a),length(b)) -end - -# use memcmp for == on bit integer types -function ==(a::Array{T,N}, b::Array{T,N}) where T<:BitInteger where N - size(a) == size(b) && 0 == ccall( - :memcmp, Int32, (Ptr{T}, Ptr{T}, UInt), a, b, sizeof(T) * length(a)) -end - -# this is ~20% faster than the generic implementation above for very small arrays -function ==(a::Array{T,1}, b::Array{T,1}) where T<:BitInteger - len = length(a) - len == length(b) && 0 == ccall( - :memcmp, Int32, (Ptr{T}, Ptr{T}, UInt), a, b, sizeof(T) * len) -end - -function reverse(A::AbstractVector, s=first(linearindices(A)), n=last(linearindices(A))) - B = similar(A) - for i = first(linearindices(A)):s-1 - B[i] = A[i] - end - for i = s:n - B[i] = A[n+s-i] - end - for i = n+1:last(linearindices(A)) - B[i] = A[i] - end - return B -end -function reverseind(a::AbstractVector, i::Integer) - li = linearindices(a) - first(li) + last(li) - i -end - -function reverse!(v::AbstractVector, s=first(linearindices(v)), n=last(linearindices(v))) - liv = linearindices(v) - if n <= s # empty case; ok - elseif !(first(liv) ≤ s ≤ last(liv)) - throw(BoundsError(v, s)) - elseif !(first(liv) ≤ n ≤ last(liv)) - throw(BoundsError(v, n)) - end - r = n - @inbounds for i in s:div(s+n-1, 2) - v[i], v[r] = v[r], v[i] - r -= 1 - end - return v -end - - -# concatenations of homogeneous combinations of vectors, horizontal and vertical - -vcat() = Array{Any,1}(0) -hcat() = Array{Any,1}(0) - -function hcat(V::Vector{T}...) where T - height = length(V[1]) - for j = 2:length(V) - if length(V[j]) != height - throw(DimensionMismatch("vectors must have same lengths")) - end - end - return [ V[j][i]::T for i=1:length(V[1]), j=1:length(V) ] -end - -function vcat(arrays::Vector{T}...) where T - n = 0 - for a in arrays - n += length(a) - end - arr = Array{T,1}(n) - ptr = pointer(arr) - if isbits(T) - elsz = Core.sizeof(T) - else - elsz = Core.sizeof(Ptr{Void}) - end - for a in arrays - na = length(a) - nba = na * elsz - if isbits(T) - ccall(:memcpy, Ptr{Void}, (Ptr{Void}, Ptr{Void}, UInt), - ptr, a, nba) - else - ccall(:jl_array_ptr_copy, Void, (Any, Ptr{Void}, Any, Ptr{Void}, Int), - arr, ptr, a, pointer(a), na) - end - ptr += nba - end - return arr -end - -cat(n::Integer, x::Integer...) = reshape([x...], (ntuple(x->1, n-1)..., length(x))) - - -## find ## - -""" - findnext(A, i::Integer) - -Find the next linear index >= `i` of a non-zero element of `A`, or `0` if not found. - -# Examples -```jldoctest -julia> A = [0 0; 1 0] -2×2 Array{Int64,2}: - 0 0 - 1 0 - -julia> findnext(A,1) -2 - -julia> findnext(A,3) -0 -``` -""" -function findnext(A, start::Integer) - for i = start:length(A) - if A[i] != 0 - return i - end - end - return 0 -end - -""" - findfirst(A) - -Return the linear index of the first non-zero value in `A` (determined by `A[i]!=0`). -Returns `0` if no such value is found. - -# Examples -```jldoctest -julia> A = [0 0; 1 0] -2×2 Array{Int64,2}: - 0 0 - 1 0 - -julia> findfirst(A) -2 - -julia> findfirst(zeros(3)) -0 -``` -""" -findfirst(A) = findnext(A, 1) - -""" - findnext(A, v, i::Integer) - -Find the next linear index >= `i` of an element of `A` equal to `v` (using `==`), or `0` if not found. - -# Examples -```jldoctest -julia> A = [1 4; 2 2] -2×2 Array{Int64,2}: - 1 4 - 2 2 - -julia> findnext(A,4,4) -0 - -julia> findnext(A,4,3) -3 -``` -""" -function findnext(A, v, start::Integer) - for i = start:length(A) - if A[i] == v - return i - end - end - return 0 -end -""" - findfirst(A, v) - -Return the linear index of the first element equal to `v` in `A`. -Returns `0` if `v` is not found. - -# Examples -```jldoctest -julia> A = [4 6; 2 2] -2×2 Array{Int64,2}: - 4 6 - 2 2 - -julia> findfirst(A,2) -2 - -julia> findfirst(A,3) -0 -``` -""" -findfirst(A, v) = findnext(A, v, 1) - -""" - findnext(predicate::Function, A, i::Integer) - -Find the next linear index >= `i` of an element of `A` for which `predicate` returns `true`, or `0` if not found. - -# Examples -```jldoctest -julia> A = [1 4; 2 2] -2×2 Array{Int64,2}: - 1 4 - 2 2 - -julia> findnext(isodd, A, 1) -1 - -julia> findnext(isodd, A, 2) -0 -``` -""" -function findnext(testf::Function, A, start::Integer) - for i = start:length(A) - if testf(A[i]) - return i - end - end - return 0 -end - -""" - findfirst(predicate::Function, A) - -Return the linear index of the first element of `A` for which `predicate` returns `true`. -Returns `0` if there is no such element. - -# Examples -```jldoctest -julia> A = [1 4; 2 2] -2×2 Array{Int64,2}: - 1 4 - 2 2 - -julia> findfirst(iseven, A) -2 - -julia> findfirst(x -> x>10, A) -0 -``` -""" -findfirst(testf::Function, A) = findnext(testf, A, 1) - -""" - findprev(A, i::Integer) - -Find the previous linear index <= `i` of a non-zero element of `A`, or `0` if not found. - -# Examples -```jldoctest -julia> A = [0 0; 1 2] -2×2 Array{Int64,2}: - 0 0 - 1 2 - -julia> findprev(A,2) -2 - -julia> findprev(A,1) -0 -``` -""" -function findprev(A, start::Integer) - for i = start:-1:1 - A[i] != 0 && return i - end - return 0 -end - -""" - findlast(A) - -Return the linear index of the last non-zero value in `A` (determined by `A[i]!=0`). -Returns `0` if there is no non-zero value in `A`. - -# Examples -```jldoctest -julia> A = [1 0; 1 0] -2×2 Array{Int64,2}: - 1 0 - 1 0 - -julia> findlast(A) -2 - -julia> A = zeros(2,2) -2×2 Array{Float64,2}: - 0.0 0.0 - 0.0 0.0 - -julia> findlast(A) -0 -``` -""" -findlast(A) = findprev(A, length(A)) - -""" - findprev(A, v, i::Integer) - -Find the previous linear index <= `i` of an element of `A` equal to `v` (using `==`), or `0` if not found. - -# Examples -```jldoctest -julia> A = [0 0; 1 2] -2×2 Array{Int64,2}: - 0 0 - 1 2 - -julia> findprev(A, 1, 4) -2 - -julia> findprev(A, 1, 1) -0 -``` -""" -function findprev(A, v, start::Integer) - for i = start:-1:1 - A[i] == v && return i - end - return 0 -end - -""" - findlast(A, v) - -Return the linear index of the last element equal to `v` in `A`. -Returns `0` if there is no element of `A` equal to `v`. - -# Examples -```jldoctest -julia> A = [1 2; 2 1] -2×2 Array{Int64,2}: - 1 2 - 2 1 - -julia> findlast(A,1) -4 - -julia> findlast(A,2) -3 - -julia> findlast(A,3) -0 -``` -""" -findlast(A, v) = findprev(A, v, length(A)) - -""" - findprev(predicate::Function, A, i::Integer) - -Find the previous linear index <= `i` of an element of `A` for which `predicate` returns `true`, or -`0` if not found. - -# Examples -```jldoctest -julia> A = [4 6; 1 2] -2×2 Array{Int64,2}: - 4 6 - 1 2 - -julia> findprev(isodd, A, 1) -0 - -julia> findprev(isodd, A, 3) -2 -``` -""" -function findprev(testf::Function, A, start::Integer) - for i = start:-1:1 - testf(A[i]) && return i - end - return 0 -end - -""" - findlast(predicate::Function, A) - -Return the linear index of the last element of `A` for which `predicate` returns `true`. -Returns `0` if there is no such element. - -# Examples -```jldoctest -julia> A = [1 2; 3 4] -2×2 Array{Int64,2}: - 1 2 - 3 4 - -julia> findlast(isodd, A) -2 - -julia> findlast(x -> x > 5, A) -0 -``` -""" -findlast(testf::Function, A) = findprev(testf, A, length(A)) - -""" - find(f::Function, A) - -Return a vector `I` of the linear indexes of `A` where `f(A[I])` returns `true`. -If there are no such elements of `A`, find returns an empty array. - -# Examples -```jldoctest -julia> A = [1 2; 3 4] -2×2 Array{Int64,2}: - 1 2 - 3 4 - -julia> find(isodd,A) -2-element Array{Int64,1}: - 1 - 2 - -julia> find(isodd, [2, 4]) -0-element Array{Int64,1} -``` -""" -function find(testf::Function, A) - # use a dynamic-length array to store the indexes, then copy to a non-padded - # array for the return - tmpI = Array{Int,1}(0) - inds = _index_remapper(A) - for (i,a) = enumerate(A) - if testf(a) - push!(tmpI, inds[i]) - end - end - I = Array{Int,1}(length(tmpI)) - copy!(I, tmpI) - return I -end -_index_remapper(A::AbstractArray) = linearindices(A) -_index_remapper(iter) = OneTo(typemax(Int)) # safe for objects that don't implement length - -""" - find(A) - -Return a vector of the linear indexes of the non-zeros in `A` (determined by `A[i]!=0`). A -common use of this is to convert a boolean array to an array of indexes of the `true` -elements. If there are no non-zero elements of `A`, `find` returns an empty array. - -# Examples -```jldoctest -julia> A = [true false; false true] -2×2 Array{Bool,2}: - true false - false true - -julia> find(A) -2-element Array{Int64,1}: - 1 - 4 - -julia> find(zeros(3)) -0-element Array{Int64,1} -``` -""" -function find(A) - nnzA = countnz(A) - I = Vector{Int}(nnzA) - count = 1 - inds = _index_remapper(A) - for (i,a) in enumerate(A) - if a != 0 - I[count] = inds[i] - count += 1 - end - end - return I -end - -find(x::Number) = x == 0 ? Array{Int,1}(0) : [1] -find(testf::Function, x::Number) = !testf(x) ? Array{Int,1}(0) : [1] - -findn(A::AbstractVector) = find(A) - -""" - findn(A) - -Return a vector of indexes for each dimension giving the locations of the non-zeros in `A` -(determined by `A[i]!=0`). -If there are no non-zero elements of `A`, `findn` returns a 2-tuple of empty arrays. - -# Examples -```jldoctest -julia> A = [1 2 0; 0 0 3; 0 4 0] -3×3 Array{Int64,2}: - 1 2 0 - 0 0 3 - 0 4 0 - -julia> findn(A) -([1, 1, 3, 2], [1, 2, 2, 3]) - -julia> A = zeros(2,2) -2×2 Array{Float64,2}: - 0.0 0.0 - 0.0 0.0 - -julia> findn(A) -(Int64[], Int64[]) -``` -""" -function findn(A::AbstractMatrix) - nnzA = countnz(A) - I = similar(A, Int, nnzA) - J = similar(A, Int, nnzA) - count = 1 - for j=indices(A,2), i=indices(A,1) - if A[i,j] != 0 - I[count] = i - J[count] = j - count += 1 - end - end - return (I, J) -end - -""" - findnz(A) - -Return a tuple `(I, J, V)` where `I` and `J` are the row and column indexes of the non-zero -values in matrix `A`, and `V` is a vector of the non-zero values. - -# Example -```jldoctest -julia> A = [1 2 0; 0 0 3; 0 4 0] -3×3 Array{Int64,2}: - 1 2 0 - 0 0 3 - 0 4 0 - -julia> findnz(A) -([1, 1, 3, 2], [1, 2, 2, 3], [1, 2, 4, 3]) -``` -""" -function findnz(A::AbstractMatrix{T}) where T - nnzA = countnz(A) - I = zeros(Int, nnzA) - J = zeros(Int, nnzA) - NZs = Array{T,1}(nnzA) - count = 1 - if nnzA > 0 - for j=indices(A,2), i=indices(A,1) - Aij = A[i,j] - if Aij != 0 - I[count] = i - J[count] = j - NZs[count] = Aij - count += 1 - end - end - end - return (I, J, NZs) -end - -""" - findmax(itr) -> (x, index) - -Returns the maximum element of the collection `itr` and its index. If there are multiple -maximal elements, then the first one will be returned. `NaN` values are ignored, unless -all elements are `NaN`. - -The collection must not be empty. - -# Examples -```jldoctest -julia> findmax([8,0.1,-9,pi]) -(8.0, 1) - -julia> findmax([1,7,7,6]) -(7, 2) - -julia> findmax([1,7,7,NaN]) -(7.0, 2) -``` -""" -function findmax(a) - if isempty(a) - throw(ArgumentError("collection must be non-empty")) - end - s = start(a) - mi = i = 1 - m, s = next(a, s) - while !done(a, s) - ai, s = next(a, s) - i += 1 - if ai > m || m!=m - m = ai - mi = i - end - end - return (m, mi) -end - -""" - findmin(itr) -> (x, index) - -Returns the minimum element of the collection `itr` and its index. If there are multiple -minimal elements, then the first one will be returned. `NaN` values are ignored, unless -all elements are `NaN`. - -The collection must not be empty. - -# Examples -```jldoctest -julia> findmin([8,0.1,-9,pi]) -(-9.0, 3) - -julia> findmin([7,1,1,6]) -(1, 2) - -julia> findmin([7,1,1,NaN]) -(1.0, 2) -``` -""" -function findmin(a) - if isempty(a) - throw(ArgumentError("collection must be non-empty")) - end - s = start(a) - mi = i = 1 - m, s = next(a, s) - while !done(a, s) - ai, s = next(a, s) - i += 1 - if ai < m || m!=m - m = ai - mi = i - end - end - return (m, mi) -end - -""" - indmax(itr) -> Integer - -Returns the index of the maximum element in a collection. If there are multiple maximal -elements, then the first one will be returned. `NaN` values are ignored, unless all -elements are `NaN`. - -The collection must not be empty. - -# Examples -```jldoctest -julia> indmax([8,0.1,-9,pi]) -1 - -julia> indmax([1,7,7,6]) -2 - -julia> indmax([1,7,7,NaN]) -2 -``` -""" -indmax(a) = findmax(a)[2] - -""" - indmin(itr) -> Integer - -Returns the index of the minimum element in a collection. If there are multiple minimal -elements, then the first one will be returned. `NaN` values are ignored, unless all -elements are `NaN`. - -The collection must not be empty. - -# Examples -```jldoctest -julia> indmin([8,0.1,-9,pi]) -3 - -julia> indmin([7,1,1,6]) -2 - -julia> indmin([7,1,1,NaN]) -2 -``` -""" -indmin(a) = findmin(a)[2] - -# similar to Matlab's ismember -""" - indexin(a, b) - -Returns a vector containing the highest index in `b` for -each value in `a` that is a member of `b` . The output -vector contains 0 wherever `a` is not a member of `b`. - -# Examples -```jldoctest -julia> a = ['a', 'b', 'c', 'b', 'd', 'a']; - -julia> b = ['a','b','c']; - -julia> indexin(a,b) -6-element Array{Int64,1}: - 1 - 2 - 3 - 2 - 0 - 1 - -julia> indexin(b,a) -3-element Array{Int64,1}: - 6 - 4 - 3 -``` -""" -function indexin(a::AbstractArray, b::AbstractArray) - bdict = Dict(zip(b, 1:length(b))) - [get(bdict, i, 0) for i in a] -end - -""" - findin(a, b) - -Returns the indices of elements in collection `a` that appear in collection `b`. - -# Examples -```jldoctest -julia> a = collect(1:3:15) -5-element Array{Int64,1}: - 1 - 4 - 7 - 10 - 13 - -julia> b = collect(2:4:10) -3-element Array{Int64,1}: - 2 - 6 - 10 - -julia> findin(a,b) # 10 is the only common element -1-element Array{Int64,1}: - 4 -``` -""" -function findin(a, b) - ind = Array{Int,1}(0) - bset = Set(b) - @inbounds for (i,ai) in enumerate(a) - ai in bset && push!(ind, i) - end - ind -end - -# Copying subregions -# TODO: DEPRECATE FOR #14770 -function indcopy(sz::Dims, I::Vector) - n = length(I) - s = sz[n] - for i = n+1:length(sz) - s *= sz[i] - end - dst = eltype(I)[findin(I[i], i < n ? (1:sz[i]) : (1:s)) for i = 1:n] - src = eltype(I)[I[i][findin(I[i], i < n ? (1:sz[i]) : (1:s))] for i = 1:n] - dst, src -end - -function indcopy(sz::Dims, I::Tuple{Vararg{RangeIndex}}) - n = length(I) - s = sz[n] - for i = n+1:length(sz) - s *= sz[i] - end - dst::typeof(I) = ntuple(i-> findin(I[i], i < n ? (1:sz[i]) : (1:s)), n)::typeof(I) - src::typeof(I) = ntuple(i-> I[i][findin(I[i], i < n ? (1:sz[i]) : (1:s))], n)::typeof(I) - dst, src -end - -## Filter ## - -""" - filter(function, collection) - -Return a copy of `collection`, removing elements for which `function` is `false`. For -associative collections, the function is passed two arguments (key and value). - -# Examples -```jldocttest -julia> a = 1:10 -1:10 - -julia> filter(isodd, a) -5-element Array{Int64,1}: - 1 - 3 - 5 - 7 - 9 - -julia> d = Dict(1=>"a", 2=>"b") -Dict{Int64,String} with 2 entries: - 2 => "b" - 1 => "a" - -julia> filter((x,y)->isodd(x), d) -Dict{Int64,String} with 1 entry: - 1 => "a" -``` -""" -filter(f, As::AbstractArray) = As[map(f, As)::AbstractArray{Bool}] - -function filter!(f, a::AbstractVector) - isempty(a) && return a - - idx = eachindex(a) - state = start(idx) - i, state = next(idx, state) - - for acurr in a - if f(acurr) - a[i] = acurr - i, state = next(idx, state) - end - end - - deleteat!(a, i:last(idx)) - - return a -end - -function filter(f, a::Vector) - r = Vector{eltype(a)}(0) - for ai in a - if f(ai) - push!(r, ai) - end - end - return r -end - -# set-like operators for vectors -# These are moderately efficient, preserve order, and remove dupes. - -function intersect(v1, vs...) - ret = Vector{promote_eltype(v1, vs...)}(0) - for v_elem in v1 - inall = true - for vsi in vs - if !in(v_elem, vsi) - inall=false; break - end - end - if inall - push!(ret, v_elem) - end - end - ret -end - -function union(vs...) - ret = Vector{promote_eltype(vs...)}(0) - seen = Set() - for v in vs - for v_elem in v - if !in(v_elem, seen) - push!(ret, v_elem) - push!(seen, v_elem) - end - end - end - ret -end -# setdiff only accepts two args - -""" - setdiff(a, b) - -Construct the set of elements in `a` but not `b`. Maintains order with arrays. Note that -both arguments must be collections, and both will be iterated over. In particular, -`setdiff(set,element)` where `element` is a potential member of `set`, will not work in -general. - -# Example -```jldoctest -julia> setdiff([1,2,3],[3,4,5]) -2-element Array{Int64,1}: - 1 - 2 -``` -""" -function setdiff(a, b) - args_type = promote_type(eltype(a), eltype(b)) - bset = Set(b) - ret = Array{args_type,1}(0) - seen = Set{eltype(a)}() - for a_elem in a - if !in(a_elem, seen) && !in(a_elem, bset) - push!(ret, a_elem) - push!(seen, a_elem) - end - end - ret -end -# symdiff is associative, so a relatively clean -# way to implement this is by using setdiff and union, and -# recursing. Has the advantage of keeping order, too, but -# not as fast as other methods that make a single pass and -# store counts with a Dict. -symdiff(a) = a -symdiff(a, b) = union(setdiff(a,b), setdiff(b,a)) -""" - symdiff(a, b, rest...) - -Construct the symmetric difference of elements in the passed in sets or arrays. -Maintains order with arrays. - -# Example -```jldoctest -julia> symdiff([1,2,3],[3,4,5],[4,5,6]) -3-element Array{Int64,1}: - 1 - 2 - 6 -``` -""" -symdiff(a, b, rest...) = symdiff(a, symdiff(b, rest...)) diff --git a/julia-0.6.3/share/julia/base/arraymath.jl b/julia-0.6.3/share/julia/base/arraymath.jl deleted file mode 100644 index 020dd9f..0000000 --- a/julia-0.6.3/share/julia/base/arraymath.jl +++ /dev/null @@ -1,296 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -## Unary operators ## - -""" - conj!(A) - -Transform an array to its complex conjugate in-place. - -See also [`conj`](@ref). - -# Example -```jldoctest -julia> A = [1+im 2-im; 2+2im 3+im] -2×2 Array{Complex{Int64},2}: - 1+1im 2-1im - 2+2im 3+1im - -julia> conj!(A); - -julia> A -2×2 Array{Complex{Int64},2}: - 1-1im 2+1im - 2-2im 3-1im -``` -""" -conj!(A::AbstractArray{<:Number}) = (@inbounds broadcast!(conj, A, A); A) - -for f in (:-, :conj, :real, :imag) - @eval ($f)(A::AbstractArray) = broadcast($f, A) -end - - -## Binary arithmetic operators ## - -for f in (:+, :-) - @eval function ($f)(A::AbstractArray, B::AbstractArray) - promote_shape(A, B) # check size compatibility - broadcast($f, A, B) - end -end - -for f in (:/, :\, :*, :+, :-) - if f != :/ - @eval ($f)(A::Number, B::AbstractArray) = broadcast($f, A, B) - end - if f != :\ - @eval ($f)(A::AbstractArray, B::Number) = broadcast($f, A, B) - end -end - -## data movement ## - -function flipdim(A::Array{T}, d::Integer) where T - nd = ndims(A) - 1 ≤ d ≤ nd || throw(ArgumentError("dimension $d is not 1 ≤ $d ≤ $nd")) - sd = size(A, d) - if sd == 1 || isempty(A) - return copy(A) - end - - B = similar(A) - - nnd = 0 - for i = 1:nd - nnd += Int(size(A,i)==1 || i==d) - end - if nnd==nd - # flip along the only non-singleton dimension - for i = 1:sd - B[i] = A[sd+1-i] - end - return B - end - - d_in = size(A) - leading = d_in[1:(d-1)] - M = prod(leading) - N = length(A) - stride = M * sd - - if M==1 - for j = 0:stride:(N-stride) - for i = 1:sd - ri = sd+1-i - B[j + ri] = A[j + i] - end - end - else - if isbits(T) && M>200 - for i = 1:sd - ri = sd+1-i - for j=0:stride:(N-stride) - offs = j + 1 + (i-1)*M - boffs = j + 1 + (ri-1)*M - copy!(B, boffs, A, offs, M) - end - end - else - for i = 1:sd - ri = sd+1-i - for j=0:stride:(N-stride) - offs = j + 1 + (i-1)*M - boffs = j + 1 + (ri-1)*M - for k=0:(M-1) - B[boffs + k] = A[offs + k] - end - end - end - end - end - return B -end - -""" - rotl90(A) - -Rotate matrix `A` left 90 degrees. - -# Example -```jldoctest -julia> a = [1 2; 3 4] -2×2 Array{Int64,2}: - 1 2 - 3 4 - -julia> rotl90(a) -2×2 Array{Int64,2}: - 2 4 - 1 3 -``` -""" -function rotl90(A::AbstractMatrix) - ind1, ind2 = indices(A) - B = similar(A, (ind2,ind1)) - n = first(ind2)+last(ind2) - for i=indices(A,1), j=ind2 - B[n-j,i] = A[i,j] - end - return B -end - -""" - rotr90(A) - -Rotate matrix `A` right 90 degrees. - -# Example -```jldoctest -julia> a = [1 2; 3 4] -2×2 Array{Int64,2}: - 1 2 - 3 4 - -julia> rotr90(a) -2×2 Array{Int64,2}: - 3 1 - 4 2 -``` -""" -function rotr90(A::AbstractMatrix) - ind1, ind2 = indices(A) - B = similar(A, (ind2,ind1)) - m = first(ind1)+last(ind1) - for i=ind1, j=indices(A,2) - B[j,m-i] = A[i,j] - end - return B -end -""" - rot180(A) - -Rotate matrix `A` 180 degrees. - -# Example -```jldoctest -julia> a = [1 2; 3 4] -2×2 Array{Int64,2}: - 1 2 - 3 4 - -julia> rot180(a) -2×2 Array{Int64,2}: - 4 3 - 2 1 -``` -""" -function rot180(A::AbstractMatrix) - B = similar(A) - ind1, ind2 = indices(A,1), indices(A,2) - m, n = first(ind1)+last(ind1), first(ind2)+last(ind2) - for j=ind2, i=ind1 - B[m-i,n-j] = A[i,j] - end - return B -end -""" - rotl90(A, k) - -Rotate matrix `A` left 90 degrees an integer `k` number of times. -If `k` is zero or a multiple of four, this is equivalent to a `copy`. - -# Examples -```jldoctest -julia> a = [1 2; 3 4] -2×2 Array{Int64,2}: - 1 2 - 3 4 - -julia> rotl90(a,1) -2×2 Array{Int64,2}: - 2 4 - 1 3 - -julia> rotl90(a,2) -2×2 Array{Int64,2}: - 4 3 - 2 1 - -julia> rotl90(a,3) -2×2 Array{Int64,2}: - 3 1 - 4 2 - -julia> rotl90(a,4) -2×2 Array{Int64,2}: - 1 2 - 3 4 -``` -""" -function rotl90(A::AbstractMatrix, k::Integer) - k = mod(k, 4) - k == 1 ? rotl90(A) : - k == 2 ? rot180(A) : - k == 3 ? rotr90(A) : copy(A) -end -""" - rotr90(A, k) - -Rotate matrix `A` right 90 degrees an integer `k` number of times. If `k` is zero or a -multiple of four, this is equivalent to a `copy`. - -# Examples -```jldoctest -julia> a = [1 2; 3 4] -2×2 Array{Int64,2}: - 1 2 - 3 4 - -julia> rotr90(a,1) -2×2 Array{Int64,2}: - 3 1 - 4 2 - -julia> rotr90(a,2) -2×2 Array{Int64,2}: - 4 3 - 2 1 - -julia> rotr90(a,3) -2×2 Array{Int64,2}: - 2 4 - 1 3 - -julia> rotr90(a,4) -2×2 Array{Int64,2}: - 1 2 - 3 4 -``` -""" -rotr90(A::AbstractMatrix, k::Integer) = rotl90(A,-k) -""" - rot180(A, k) - -Rotate matrix `A` 180 degrees an integer `k` number of times. -If `k` is even, this is equivalent to a `copy`. - -# Examples -```jldoctest -julia> a = [1 2; 3 4] -2×2 Array{Int64,2}: - 1 2 - 3 4 - -julia> rot180(a,1) -2×2 Array{Int64,2}: - 4 3 - 2 1 - -julia> rot180(a,2) -2×2 Array{Int64,2}: - 1 2 - 3 4 -``` -""" -rot180(A::AbstractMatrix, k::Integer) = mod(k, 2) == 1 ? rot180(A) : copy(A) diff --git a/julia-0.6.3/share/julia/base/associative.jl b/julia-0.6.3/share/julia/base/associative.jl deleted file mode 100644 index 564c3fd..0000000 --- a/julia-0.6.3/share/julia/base/associative.jl +++ /dev/null @@ -1,477 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -# generic operations on associative collections - -const secret_table_token = :__c782dbf1cf4d6a2e5e3865d7e95634f2e09b5902__ - -haskey(d::Associative, k) = in(k,keys(d)) - -function in(p::Pair, a::Associative, valcmp=(==)) - v = get(a,p[1],secret_table_token) - if v !== secret_table_token - valcmp(v, p[2]) && return true - end - return false -end - -function in(p, a::Associative) - error("""Associative collections only contain Pairs; - Either look for e.g. A=>B instead, or use the `keys` or `values` - function if you are looking for a key or value respectively.""") -end - -function summary(t::Associative) - n = length(t) - return string(typeof(t), " with ", n, (n==1 ? " entry" : " entries")) -end - -struct KeyIterator{T<:Associative} - dict::T -end -struct ValueIterator{T<:Associative} - dict::T -end - -summary{T<:Union{KeyIterator,ValueIterator}}(iter::T) = - string(T.name, " for a ", summary(iter.dict)) - -show(io::IO, iter::Union{KeyIterator,ValueIterator}) = show(io, collect(iter)) - -length(v::Union{KeyIterator,ValueIterator}) = length(v.dict) -isempty(v::Union{KeyIterator,ValueIterator}) = isempty(v.dict) -_tt1(::Type{Pair{A,B}}) where {A,B} = A -_tt2(::Type{Pair{A,B}}) where {A,B} = B -eltype(::Type{KeyIterator{D}}) where {D} = _tt1(eltype(D)) -eltype(::Type{ValueIterator{D}}) where {D} = _tt2(eltype(D)) - -start(v::Union{KeyIterator,ValueIterator}) = start(v.dict) -done(v::Union{KeyIterator,ValueIterator}, state) = done(v.dict, state) - -function next(v::KeyIterator, state) - n = next(v.dict, state) - n[1][1], n[2] -end - -function next(v::ValueIterator, state) - n = next(v.dict, state) - n[1][2], n[2] -end - -in(k, v::KeyIterator) = get(v.dict, k, secret_table_token) !== secret_table_token - - -""" - keys(a::Associative) - -Return an iterator over all keys in a collection. -`collect(keys(a))` returns an array of keys. -Since the keys are stored internally in a hash table, -the order in which they are returned may vary. -But `keys(a)` and `values(a)` both iterate `a` and -return the elements in the same order. - -```jldoctest -julia> a = Dict('a'=>2, 'b'=>3) -Dict{Char,Int64} with 2 entries: - 'b' => 3 - 'a' => 2 - -julia> collect(keys(a)) -2-element Array{Char,1}: - 'b' - 'a' -``` -""" -keys(a::Associative) = KeyIterator(a) -eachindex(a::Associative) = KeyIterator(a) - -""" - values(a::Associative) - -Return an iterator over all values in a collection. -`collect(values(a))` returns an array of values. -Since the values are stored internally in a hash table, -the order in which they are returned may vary. -But `keys(a)` and `values(a)` both iterate `a` and -return the elements in the same order. - -```jldoctest -julia> a = Dict('a'=>2, 'b'=>3) -Dict{Char,Int64} with 2 entries: - 'b' => 3 - 'a' => 2 - -julia> collect(values(a)) -2-element Array{Int64,1}: - 3 - 2 -``` -""" -values(a::Associative) = ValueIterator(a) - -function copy(a::Associative) - b = similar(a) - for (k,v) in a - b[k] = v - end - return b -end - -""" - merge!(d::Associative, others::Associative...) - -Update collection with pairs from the other collections. -See also [`merge`](@ref). - -```jldoctest -julia> d1 = Dict(1 => 2, 3 => 4); - -julia> d2 = Dict(1 => 4, 4 => 5); - -julia> merge!(d1, d2); - -julia> d1 -Dict{Int64,Int64} with 3 entries: - 4 => 5 - 3 => 4 - 1 => 4 -``` -""" -function merge!(d::Associative, others::Associative...) - for other in others - for (k,v) in other - d[k] = v - end - end - return d -end - -""" - merge!(combine, d::Associative, others::Associative...) - -Update collection with pairs from the other collections. -Values with the same key will be combined using the -combiner function. - -```jldoctest -julia> d1 = Dict(1 => 2, 3 => 4); - -julia> d2 = Dict(1 => 4, 4 => 5); - -julia> merge!(+, d1, d2); - -julia> d1 -Dict{Int64,Int64} with 3 entries: - 4 => 5 - 3 => 4 - 1 => 6 - -julia> merge!(-, d1, d1); - -julia> d1 -Dict{Int64,Int64} with 3 entries: - 4 => 0 - 3 => 0 - 1 => 0 -``` -""" -function merge!(combine::Function, d::Associative, others::Associative...) - for other in others - for (k,v) in other - d[k] = haskey(d, k) ? combine(d[k], v) : v - end - end - return d -end - -# very similar to `merge!`, but accepts any iterable and extends code -# that would otherwise only use `copy!` with arrays. -function copy!(dest::Union{Associative,AbstractSet}, src) - for x in src - push!(dest, x) - end - return dest -end - -""" - keytype(type) - -Get the key type of an associative collection type. Behaves similarly to [`eltype`](@ref). - -```jldoctest -julia> keytype(Dict(Int32(1) => "foo")) -Int32 -``` -""" -keytype(::Type{Associative{K,V}}) where {K,V} = K -keytype(a::Associative) = keytype(typeof(a)) -keytype(::Type{A}) where {A<:Associative} = keytype(supertype(A)) - -""" - valtype(type) - -Get the value type of an associative collection type. Behaves similarly to [`eltype`](@ref). - -```jldoctest -julia> valtype(Dict(Int32(1) => "foo")) -String -``` -""" -valtype(::Type{Associative{K,V}}) where {K,V} = V -valtype{A<:Associative}(::Type{A}) = valtype(supertype(A)) -valtype(a::Associative) = valtype(typeof(a)) - -""" - merge(d::Associative, others::Associative...) - -Construct a merged collection from the given collections. If necessary, the -types of the resulting collection will be promoted to accommodate the types of -the merged collections. If the same key is present in another collection, the -value for that key will be the value it has in the last collection listed. - -```jldoctest -julia> a = Dict("foo" => 0.0, "bar" => 42.0) -Dict{String,Float64} with 2 entries: - "bar" => 42.0 - "foo" => 0.0 - -julia> b = Dict("baz" => 17, "bar" => 4711) -Dict{String,Int64} with 2 entries: - "bar" => 4711 - "baz" => 17 - -julia> merge(a, b) -Dict{String,Float64} with 3 entries: - "bar" => 4711.0 - "baz" => 17.0 - "foo" => 0.0 - -julia> merge(b, a) -Dict{String,Float64} with 3 entries: - "bar" => 42.0 - "baz" => 17.0 - "foo" => 0.0 -``` -""" -merge(d::Associative, others::Associative...) = - merge!(emptymergedict(d, others...), d, others...) - -""" - merge(combine, d::Associative, others::Associative...) - -Construct a merged collection from the given collections. If necessary, the -types of the resulting collection will be promoted to accommodate the types of -the merged collections. Values with the same key will be combined using the -combiner function. - -```jldoctest -julia> a = Dict("foo" => 0.0, "bar" => 42.0) -Dict{String,Float64} with 2 entries: - "bar" => 42.0 - "foo" => 0.0 - -julia> b = Dict("baz" => 17, "bar" => 4711) -Dict{String,Int64} with 2 entries: - "bar" => 4711 - "baz" => 17 - -julia> merge(+, a, b) -Dict{String,Float64} with 3 entries: - "bar" => 4753.0 - "baz" => 17.0 - "foo" => 0.0 -``` -""" -merge(combine::Function, d::Associative, others::Associative...) = - merge!(combine, emptymergedict(d, others...), d, others...) - -promoteK(K) = K -promoteV(V) = V -promoteK(K, d, ds...) = promoteK(promote_type(K, keytype(d)), ds...) -promoteV(V, d, ds...) = promoteV(promote_type(V, valtype(d)), ds...) -function emptymergedict(d::Associative, others::Associative...) - K = promoteK(keytype(d), others...) - V = promoteV(valtype(d), others...) - Dict{K,V}() -end - -function filter!(f, d::Associative) - badkeys = Vector{keytype(d)}(0) - for (k,v) in d - # don't delete!(d, k) here, since associative types - # may not support mutation during iteration - f(k,v) || push!(badkeys, k) - end - for k in badkeys - delete!(d, k) - end - return d -end -function filter(f, d::Associative) - # don't just do filter!(f, copy(d)): avoid making a whole copy of d - df = similar(d) - for (k,v) in d - if f(k,v) - df[k] = v - end - end - return df -end - -eltype(::Type{Associative{K,V}}) where {K,V} = Pair{K,V} - -function isequal(l::Associative, r::Associative) - l === r && return true - if isa(l,ObjectIdDict) != isa(r,ObjectIdDict) - return false - end - if length(l) != length(r) return false end - for pair in l - if !in(pair, r, isequal) - return false - end - end - true -end - -function ==(l::Associative, r::Associative) - l === r && return true - if isa(l,ObjectIdDict) != isa(r,ObjectIdDict) - return false - end - if length(l) != length(r) return false end - for pair in l - if !in(pair, r, ==) - return false - end - end - true -end - -const hasha_seed = UInt === UInt64 ? 0x6d35bb51952d5539 : 0x952d5539 -function hash(a::Associative, h::UInt) - hv = hasha_seed - for (k,v) in a - hv ⊻= hash(k, hash(v)) - end - hash(hv, h) -end - -function getindex(t::Associative, key) - v = get(t, key, secret_table_token) - if v === secret_table_token - throw(KeyError(key)) - end - return v -end - -# t[k1,k2,ks...] is syntactic sugar for t[(k1,k2,ks...)]. (Note -# that we need to avoid dispatch loops if setindex!(t,v,k) is not defined.) -getindex(t::Associative, k1, k2, ks...) = getindex(t, tuple(k1,k2,ks...)) -setindex!(t::Associative, v, k1, k2, ks...) = setindex!(t, v, tuple(k1,k2,ks...)) - -push!(t::Associative, p::Pair) = setindex!(t, p.second, p.first) -push!(t::Associative, p::Pair, q::Pair) = push!(push!(t, p), q) -push!(t::Associative, p::Pair, q::Pair, r::Pair...) = push!(push!(push!(t, p), q), r...) - -# hashing objects by identity - -""" - ObjectIdDict([itr]) - -`ObjectIdDict()` constructs a hash table where the keys are (always) -object identities. Unlike `Dict` it is not parameterized on its key -and value type and thus its `eltype` is always `Pair{Any,Any}`. - -See [`Dict`](@ref) for further help. -""" -mutable struct ObjectIdDict <: Associative{Any,Any} - ht::Vector{Any} - ndel::Int - ObjectIdDict() = new(Vector{Any}(32), 0) - - function ObjectIdDict(itr) - d = ObjectIdDict() - for (k,v) in itr; d[k] = v; end - d - end - - function ObjectIdDict(pairs::Pair...) - d = ObjectIdDict() - for (k,v) in pairs; d[k] = v; end - d - end - - ObjectIdDict(o::ObjectIdDict) = new(copy(o.ht)) -end - -similar(d::ObjectIdDict) = ObjectIdDict() - -function rehash!(t::ObjectIdDict, newsz = length(t.ht)) - t.ht = ccall(:jl_idtable_rehash, Any, (Any, Csize_t), t.ht, newsz) - t -end - -function sizehint!(t::ObjectIdDict, newsz) - newsz = _tablesz(newsz*2) # *2 for keys and values in same array - oldsz = length(t.ht) - # grow at least 25% - if newsz < (oldsz*5)>>2 - return t - end - rehash!(t, newsz) -end - -function setindex!(t::ObjectIdDict, v::ANY, k::ANY) - if t.ndel >= ((3*length(t.ht))>>2) - rehash!(t, max(length(t.ht)>>1, 32)) - t.ndel = 0 - end - t.ht = ccall(:jl_eqtable_put, Array{Any,1}, (Any, Any, Any), t.ht, k, v) - return t -end - -get(t::ObjectIdDict, key::ANY, default::ANY) = - ccall(:jl_eqtable_get, Any, (Any, Any, Any), t.ht, key, default) - -function pop!(t::ObjectIdDict, key::ANY, default::ANY) - val = ccall(:jl_eqtable_pop, Any, (Any, Any, Any), t.ht, key, default) - # TODO: this can underestimate `ndel` - val === default || (t.ndel += 1) - return val -end - -function pop!(t::ObjectIdDict, key::ANY) - val = pop!(t, key, secret_table_token) - val !== secret_table_token ? val : throw(KeyError(key)) -end - -function delete!(t::ObjectIdDict, key::ANY) - pop!(t, key, secret_table_token) - t -end - -function empty!(t::ObjectIdDict) - resize!(t.ht, 32) - ccall(:memset, Ptr{Void}, (Ptr{Void}, Cint, Csize_t), t.ht, 0, sizeof(t.ht)) - t.ndel = 0 - return t -end - -_oidd_nextind(a, i) = reinterpret(Int,ccall(:jl_eqtable_nextind, Csize_t, (Any, Csize_t), a, i)) - -start(t::ObjectIdDict) = _oidd_nextind(t.ht, 0) -done(t::ObjectIdDict, i) = (i == -1) -next(t::ObjectIdDict, i) = (Pair{Any,Any}(t.ht[i+1],t.ht[i+2]), _oidd_nextind(t.ht, i+2)) - -function length(d::ObjectIdDict) - n = 0 - for pair in d - n+=1 - end - n -end - -copy(o::ObjectIdDict) = ObjectIdDict(o) - -get!(o::ObjectIdDict, key, default) = (o[key] = get(o, key, default)) diff --git a/julia-0.6.3/share/julia/base/asyncmap.jl b/julia-0.6.3/share/julia/base/asyncmap.jl deleted file mode 100644 index 3931cc9..0000000 --- a/julia-0.6.3/share/julia/base/asyncmap.jl +++ /dev/null @@ -1,424 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -using Base.Iterators.Enumerate - -""" - asyncmap(f, c...; ntasks=0, batch_size=nothing) - -Uses multiple concurrent tasks to map `f` over a collection (or multiple -equal length collections). For multiple collection arguments, `f` is -applied elementwise. - -`ntasks` specifies the number of tasks to run concurrently. -Depending on the length of the collections, if `ntasks` is unspecified, -up to 100 tasks will be used for concurrent mapping. - -`ntasks` can also be specified as a zero-arg function. In this case, the -number of tasks to run in parallel is checked before processing every element and a new -task started if the value of `ntasks_func()` is less than the current number -of tasks. - -If `batch_size` is specified, the collection is processed in batch mode. `f` must -then be a function that must accept a `Vector` of argument tuples and must -return a vector of results. The input vector will have a length of `batch_size` or less. - -The following examples highlight execution in different tasks by returning -the `object_id` of the tasks in which the mapping function is executed. - -First, with `ntasks` undefined, each element is processed in a different task. -``` -julia> tskoid() = object_id(current_task()); - -julia> asyncmap(x->tskoid(), 1:5) -5-element Array{UInt64,1}: - 0x6e15e66c75c75853 - 0x440f8819a1baa682 - 0x9fb3eeadd0c83985 - 0xebd3e35fe90d4050 - 0x29efc93edce2b961 - -julia> length(unique(asyncmap(x->tskoid(), 1:5))) -5 -``` - -With `ntasks=2` all elements are processed in 2 tasks. -``` -julia> asyncmap(x->tskoid(), 1:5; ntasks=2) -5-element Array{UInt64,1}: - 0x027ab1680df7ae94 - 0xa23d2f80cd7cf157 - 0x027ab1680df7ae94 - 0xa23d2f80cd7cf157 - 0x027ab1680df7ae94 - -julia> length(unique(asyncmap(x->tskoid(), 1:5; ntasks=2))) -2 -``` - -With `batch_size` defined, the mapping function needs to be changed to accept an array -of argument tuples and return an array of results. `map` is used in the modified mapping -function to achieve this. -``` -julia> batch_func(input) = map(x->string("args_tuple: ", x, ", element_val: ", x[1], ", task: ", tskoid()), input) -batch_func (generic function with 1 method) - -julia> asyncmap(batch_func, 1:5; ntasks=2, batch_size=2) -5-element Array{String,1}: - "args_tuple: (1,), element_val: 1, task: 9118321258196414413" - "args_tuple: (2,), element_val: 2, task: 4904288162898683522" - "args_tuple: (3,), element_val: 3, task: 9118321258196414413" - "args_tuple: (4,), element_val: 4, task: 4904288162898683522" - "args_tuple: (5,), element_val: 5, task: 9118321258196414413" -``` - -!!! note - Currently, all tasks in Julia are executed in a single OS thread co-operatively. Consequently, - `ayncmap` is beneficial only when the mapping function involves any I/O - disk, network, remote - worker invocation, etc. - -""" -function asyncmap(f, c...; ntasks=0, batch_size=nothing) - return async_usemap(f, c...; ntasks=ntasks, batch_size=batch_size) -end - -function async_usemap(f, c...; ntasks=0, batch_size=nothing) - ntasks = verify_ntasks(c[1], ntasks) - batch_size = verify_batch_size(batch_size) - - if batch_size !== nothing - exec_func = batch -> begin - # extract the Refs from the input tuple - batch_refs = map(x->x[1], batch) - - # and the args tuple.... - batched_args = map(x->x[2], batch) - - results = f(batched_args) - foreach(x -> (batch_refs[x[1]].x = x[2]), enumerate(results)) - end - else - exec_func = (r,args) -> (r.x = f(args...)) - end - chnl, worker_tasks = setup_chnl_and_tasks(exec_func, ntasks, batch_size) - return wrap_n_exec_twice(chnl, worker_tasks, ntasks, exec_func, c...) -end - -batch_size_err_str(batch_size) = string("batch_size must be specified as a positive integer. batch_size=", batch_size) -function verify_batch_size(batch_size) - if batch_size === nothing - return batch_size - elseif isa(batch_size, Number) - batch_size = Int(batch_size) - batch_size < 1 && throw(ArgumentError(batch_size_err_str(batch_size))) - return batch_size - else - throw(ArgumentError(batch_size_err_str(batch_size))) - end -end - - -function verify_ntasks(iterable, ntasks) - if !((isa(ntasks, Number) && (ntasks >= 0)) || isa(ntasks, Function)) - err = string("ntasks must be specified as a positive integer or a 0-arg function. ntasks=", ntasks) - throw(ArgumentError(err)) - end - - if ntasks == 0 - chklen = iteratorsize(iterable) - if (chklen == HasLength()) || (chklen == HasShape()) - ntasks = max(1,min(100, length(iterable))) - else - ntasks = 100 - end - end - return ntasks -end - -function wrap_n_exec_twice(chnl, worker_tasks, ntasks, exec_func, c...) - # The driver task, creates a Ref object and writes it and the args tuple to - # the communication channel for processing by a free worker task. - push_arg_to_channel = (x...) -> (r=Ref{Any}(nothing); put!(chnl,(r,x));r) - - if isa(ntasks, Function) - map_f = (x...) -> begin - # check number of tasks every time, and start one if required. - # number_tasks > optimal_number is fine, the other way around is inefficient. - if length(worker_tasks) < ntasks() - start_worker_task!(worker_tasks, exec_func, chnl) - end - push_arg_to_channel(x...) - end - else - map_f = push_arg_to_channel - end - maptwice(map_f, chnl, worker_tasks, c...) -end - -function maptwice(wrapped_f, chnl, worker_tasks, c...) - # first run, returns a collection of Refs - asyncrun_excp = nothing - local asyncrun - try - asyncrun = map(wrapped_f, c...) - catch ex - if isa(ex,InvalidStateException) - # channel could be closed due to exceptions in the async tasks, - # we propagate those errors, if any, over the `put!` failing - # in asyncrun due to a closed channel. - asyncrun_excp = ex - else - rethrow(ex) - end - end - - # close channel and wait for all worker tasks to finish - close(chnl) - - # check and throw any exceptions from the worker tasks - foreach(x->(v=wait(x); isa(v, Exception) && throw(v)), worker_tasks) - - # check if there was a genuine problem with asyncrun - (asyncrun_excp !== nothing) && throw(asyncrun_excp) - - if isa(asyncrun, Ref) - # scalar case - return asyncrun.x - else - # second run, extract values from the Refs and return - return map(ref->ref.x, asyncrun) - end -end - -function setup_chnl_and_tasks(exec_func, ntasks, batch_size=nothing) - if isa(ntasks, Function) - nt = ntasks() - # start at least one worker task. - if nt == 0 - nt = 1 - end - else - nt = ntasks - end - - # Use an unbuffered channel for communicating with the worker tasks. In the event - # of an error in any of the worker tasks, the channel is closed. This - # results in the `put!` in the driver task failing immediately. - chnl = Channel(0) - worker_tasks = [] - foreach(_ -> start_worker_task!(worker_tasks, exec_func, chnl, batch_size), 1:nt) - yield() - return (chnl, worker_tasks) -end - -function start_worker_task!(worker_tasks, exec_func, chnl, batch_size=nothing) - t = @schedule begin - retval = nothing - - try - if isa(batch_size, Number) - while isopen(chnl) - # The mapping function expects an array of input args, as it processes - # elements in a batch. - batch_collection=Any[] - n = 0 - for exec_data in chnl - push!(batch_collection, exec_data) - n += 1 - (n == batch_size) && break - end - if n > 0 - exec_func(batch_collection) - end - end - else - for exec_data in chnl - exec_func(exec_data...) - end - end - catch e - close(chnl) - retval = e - end - retval - end - push!(worker_tasks, t) -end - -# Special handling for some types. -function asyncmap(f, s::AbstractString; kwargs...) - s2 = Array{Char,1}(length(s)) - asyncmap!(f, s2, s; kwargs...) - return convert(String, s2) -end - -# map on a single BitArray returns a BitArray if the mapping function is boolean. -function asyncmap(f, b::BitArray; kwargs...) - b2 = async_usemap(f, b; kwargs...) - if eltype(b2) == Bool - return BitArray(b2) - end - return b2 -end - -# TODO: Optimize for sparse arrays -# For now process as regular arrays and convert back -function asyncmap(f, s::AbstractSparseArray...; kwargs...) - sa = map(Array, s) - return sparse(asyncmap(f, sa...; kwargs...)) -end - -mutable struct AsyncCollector - f - results - enumerator::Enumerate - ntasks - batch_size - nt_check::Bool # check number of tasks on every iteration - - AsyncCollector(f, r, en::Enumerate, ntasks, batch_size) = new(f, r, en, ntasks, batch_size, isa(ntasks, Function)) -end - -""" - AsyncCollector(f, results, c...; ntasks=0, batch_size=nothing) -> iterator - -Returns an iterator which applies `f` to each element of `c` asynchronously -and collects output into `results`. - -Keyword args `ntasks` and `batch_size` have the same behavior as in -[`asyncmap()`](@ref). If `batch_size` is specified, `f` must -be a function which operates on an array of argument tuples. - -!!! note - `next(::AsyncCollector, state) -> (nothing, state)`. A successful return - from `next` indicates that the next element from the input collection is - being processed asynchronously. It blocks until a free worker task becomes - available. - -!!! note - `for _ in AsyncCollector(f, results, c...; ntasks=1) end` is equivalent to - `map!(f, results, c...)`. -""" -function AsyncCollector(f, results, c...; ntasks=0, batch_size=nothing) - AsyncCollector(f, results, enumerate(zip(c...)), ntasks, batch_size) -end - -mutable struct AsyncCollectorState - chnl::Channel - worker_tasks::Array{Task,1} - enum_state # enumerator state -end - -function start(itr::AsyncCollector) - itr.ntasks = verify_ntasks(itr.enumerator, itr.ntasks) - itr.batch_size = verify_batch_size(itr.batch_size) - if itr.batch_size !== nothing - exec_func = batch -> begin - # extract indexes from the input tuple - batch_idxs = map(x->x[1], batch) - - # and the args tuple.... - batched_args = map(x->x[2], batch) - - results = f(batched_args) - foreach(x -> (itr.results[batch_idxs[x[1]]] = x[2]), enumerate(results)) - end - else - exec_func = (i,args) -> (itr.results[i]=itr.f(args...)) - end - chnl, worker_tasks = setup_chnl_and_tasks((i,args) -> (itr.results[i]=itr.f(args...)), itr.ntasks, itr.batch_size) - return AsyncCollectorState(chnl, worker_tasks, start(itr.enumerator)) -end - -function done(itr::AsyncCollector, state::AsyncCollectorState) - if !isopen(state.chnl) || done(itr.enumerator, state.enum_state) - close(state.chnl) - - # wait for all tasks to finish - foreach(x->(v=wait(x); isa(v, Exception) && throw(v)), state.worker_tasks) - empty!(state.worker_tasks) - return true - else - return false - end -end - -function next(itr::AsyncCollector, state::AsyncCollectorState) - if itr.nt_check && (length(state.worker_tasks) < itr.ntasks()) - start_worker_task!(state.worker_tasks, itr.f, state.chnl) - end - - # Get index and mapped function arguments from enumeration iterator. - (i, args), state.enum_state = next(itr.enumerator, state.enum_state) - put!(state.chnl, (i, args)) - - return (nothing, state) -end - -""" - AsyncGenerator(f, c...; ntasks=0, batch_size=nothing) -> iterator - -Apply `f` to each element of `c` using at most `ntasks` asynchronous tasks. - -Keyword args `ntasks` and `batch_size` have the same behavior as in -[`asyncmap()`](@ref). If `batch_size` is specified, `f` must -be a function which operates on an array of argument tuples. - -!!! note - `collect(AsyncGenerator(f, c...; ntasks=1))` is equivalent to - `map(f, c...)`. -""" -mutable struct AsyncGenerator - collector::AsyncCollector -end - -function AsyncGenerator(f, c...; ntasks=0) - AsyncGenerator(AsyncCollector(f, Dict{Int,Any}(), c...; ntasks=ntasks)) -end - -mutable struct AsyncGeneratorState - i::Int - collector_state::AsyncCollectorState -end - -start(itr::AsyncGenerator) = AsyncGeneratorState(0, start(itr.collector)) - -# Done when source async collector is done and all results have been consumed. -function done(itr::AsyncGenerator, state::AsyncGeneratorState) - done(itr.collector, state.collector_state) && isempty(itr.collector.results) -end - -function next(itr::AsyncGenerator, state::AsyncGeneratorState) - state.i += 1 - - results_dict = itr.collector.results - while !haskey(results_dict, state.i) - if done(itr.collector, state.collector_state) - # `done` waits for async tasks to finish. if we do not have the index - # we are looking for, it is an error. - !haskey(results_dict, state.i) && error("Error processing index ", i) - break; - end - _, state.collector_state = next(itr.collector, state.collector_state) - end - r = results_dict[state.i] - delete!(results_dict, state.i) - - return (r, state) -end - -# pass-through iterator traits to the iterable -# on which the mapping function is being applied -iteratorsize(itr::AsyncGenerator) = iteratorsize(itr.collector.enumerator) -size(itr::AsyncGenerator) = size(itr.collector.enumerator) -length(itr::AsyncGenerator) = length(itr.collector.enumerator) - -""" - asyncmap!(f, results, c...; ntasks=0, batch_size=nothing) - -Like [`asyncmap()`](@ref), but stores output in `results` rather than -returning a collection. -""" -function asyncmap!(f, r, c1, c...; ntasks=0, batch_size=nothing) - foreach(identity, AsyncCollector(f, r, c1, c...; ntasks=ntasks, batch_size=batch_size)) - r -end diff --git a/julia-0.6.3/share/julia/base/atomics.jl b/julia-0.6.3/share/julia/base/atomics.jl deleted file mode 100644 index 7374bad..0000000 --- a/julia-0.6.3/share/julia/base/atomics.jl +++ /dev/null @@ -1,482 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -using Core.Intrinsics: llvmcall - -import Base: setindex!, getindex, unsafe_convert -import Base.Sys: ARCH, WORD_SIZE - -export - Atomic, - atomic_cas!, - atomic_xchg!, - atomic_add!, atomic_sub!, - atomic_and!, atomic_nand!, atomic_or!, atomic_xor!, - atomic_max!, atomic_min!, - atomic_fence - -# Disable 128-bit types on 32-bit Intel sytems due to LLVM problems; -# see (fixed on LLVM 3.9) -# 128-bit atomics do not exist on AArch32. -if (VersionNumber(Base.libllvm_version) < v"3.9-" && ARCH === :i686) || - startswith(string(ARCH), "arm") - const inttypes = (Int8, Int16, Int32, Int64, - UInt8, UInt16, UInt32, UInt64) -else - const inttypes = (Int8, Int16, Int32, Int64, Int128, - UInt8, UInt16, UInt32, UInt64, UInt128) -end -const floattypes = (Float16, Float32, Float64) -# TODO: Support Bool, Ptr -const atomictypes = (inttypes..., floattypes...) -const IntTypes = Union{inttypes...} -const FloatTypes = Union{floattypes...} -const AtomicTypes = Union{atomictypes...} - -""" - Threads.Atomic{T} - -Holds a reference to an object of type `T`, ensuring that it is only -accessed atomically, i.e. in a thread-safe manner. - -Only certain "simple" types can be used atomically, namely the -primitive integer and float-point types. These are `Int8`...`Int128`, -`UInt8`...`UInt128`, and `Float16`...`Float64`. - -New atomic objects can be created from a non-atomic values; if none is -specified, the atomic object is initialized with zero. - -Atomic objects can be accessed using the `[]` notation: - -```jldoctest -julia> x = Threads.Atomic{Int}(3) -Base.Threads.Atomic{Int64}(3) - -julia> x[] = 1 -1 - -julia> x[] -1 -``` - -Atomic operations use an `atomic_` prefix, such as `atomic_add!`, -`atomic_xchg!`, etc. -""" -mutable struct Atomic{T<:AtomicTypes} - value::T - Atomic{T}() where {T<:AtomicTypes} = new(zero(T)) - Atomic{T}(value) where {T<:AtomicTypes} = new(value) -end - -Atomic() = Atomic{Int}() - -""" - Threads.atomic_cas!{T}(x::Atomic{T}, cmp::T, newval::T) - -Atomically compare-and-set `x` - -Atomically compares the value in `x` with `cmp`. If equal, write -`newval` to `x`. Otherwise, leaves `x` unmodified. Returns the old -value in `x`. By comparing the returned value to `cmp` (via `===`) one -knows whether `x` was modified and now holds the new value `newval`. - -For further details, see LLVM's `cmpxchg` instruction. - -This function can be used to implement transactional semantics. Before -the transaction, one records the value in `x`. After the transaction, -the new value is stored only if `x` has not been modified in the mean -time. - -```jldoctest -julia> x = Threads.Atomic{Int}(3) -Base.Threads.Atomic{Int64}(3) - -julia> Threads.atomic_cas!(x, 4, 2); - -julia> x -Base.Threads.Atomic{Int64}(3) - -julia> Threads.atomic_cas!(x, 3, 2); - -julia> x -Base.Threads.Atomic{Int64}(2) -``` -""" -function atomic_cas! end - -""" - Threads.atomic_xchg!{T}(x::Atomic{T}, newval::T) - -Atomically exchange the value in `x` - -Atomically exchanges the value in `x` with `newval`. Returns the **old** -value. - -For further details, see LLVM's `atomicrmw xchg` instruction. - -```jldoctest -julia> x = Threads.Atomic{Int}(3) -Base.Threads.Atomic{Int64}(3) - -julia> Threads.atomic_xchg!(x, 2) -3 - -julia> x[] -2 -``` -""" -function atomic_xchg! end - -""" - Threads.atomic_add!{T}(x::Atomic{T}, val::T) - -Atomically add `val` to `x` - -Performs `x[] += val` atomically. Returns the **old** value. - -For further details, see LLVM's `atomicrmw add` instruction. - -```jldoctest -julia> x = Threads.Atomic{Int}(3) -Base.Threads.Atomic{Int64}(3) - -julia> Threads.atomic_add!(x, 2) -3 - -julia> x[] -5 -``` -""" -function atomic_add! end - -""" - Threads.atomic_sub!{T}(x::Atomic{T}, val::T) - -Atomically subtract `val` from `x` - -Performs `x[] -= val` atomically. Returns the **old** value. - -For further details, see LLVM's `atomicrmw sub` instruction. - -```jldoctest -julia> x = Threads.Atomic{Int}(3) -Base.Threads.Atomic{Int64}(3) - -julia> Threads.atomic_sub!(x, 2) -3 - -julia> x[] -1 -``` -""" -function atomic_sub! end - -""" - Threads.atomic_and!{T}(x::Atomic{T}, val::T) - -Atomically bitwise-and `x` with `val` - -Performs `x[] &= val` atomically. Returns the **old** value. - -For further details, see LLVM's `atomicrmw and` instruction. - -```jldoctest -julia> x = Threads.Atomic{Int}(3) -Base.Threads.Atomic{Int64}(3) - -julia> Threads.atomic_and!(x, 2) -3 - -julia> x[] -2 -``` -""" -function atomic_and! end - -""" - Threads.atomic_nand!{T}(x::Atomic{T}, val::T) - -Atomically bitwise-nand (not-and) `x` with `val` - -Performs `x[] = ~(x[] & val)` atomically. Returns the **old** value. - -For further details, see LLVM's `atomicrmw nand` instruction. - -```jldoctest -julia> x = Threads.Atomic{Int}(3) -Base.Threads.Atomic{Int64}(3) - -julia> Threads.atomic_nand!(x, 2) -3 - -julia> x[] --3 -``` -""" -function atomic_nand! end - -""" - Threads.atomic_or!{T}(x::Atomic{T}, val::T) - -Atomically bitwise-or `x` with `val` - -Performs `x[] |= val` atomically. Returns the **old** value. - -For further details, see LLVM's `atomicrmw or` instruction. - -```jldoctest -julia> x = Threads.Atomic{Int}(5) -Base.Threads.Atomic{Int64}(5) - -julia> Threads.atomic_or!(x, 7) -5 - -julia> x[] -7 -``` -""" -function atomic_or! end - -""" - Threads.atomic_xor!{T}(x::Atomic{T}, val::T) - -Atomically bitwise-xor (exclusive-or) `x` with `val` - -Performs `x[] \$= val` atomically. Returns the **old** value. - -For further details, see LLVM's `atomicrmw xor` instruction. - -```jldoctest -julia> x = Threads.Atomic{Int}(5) -Base.Threads.Atomic{Int64}(5) - -julia> Threads.atomic_xor!(x, 7) -5 - -julia> x[] -2 -``` -""" -function atomic_xor! end - -""" - Threads.atomic_max!{T}(x::Atomic{T}, val::T) - -Atomically store the maximum of `x` and `val` in `x` - -Performs `x[] = max(x[], val)` atomically. Returns the **old** value. - -For further details, see LLVM's `atomicrmw max` instruction. - -```jldoctest -julia> x = Threads.Atomic{Int}(5) -Base.Threads.Atomic{Int64}(5) - -julia> Threads.atomic_max!(x, 7) -5 - -julia> x[] -7 -``` -""" -function atomic_max! end - -""" - Threads.atomic_min!{T}(x::Atomic{T}, val::T) - -Atomically store the minimum of `x` and `val` in `x` - -Performs `x[] = min(x[], val)` atomically. Returns the **old** value. - -For further details, see LLVM's `atomicrmw min` instruction. - -```jldoctest -julia> x = Threads.Atomic{Int}(7) -Base.Threads.Atomic{Int64}(7) - -julia> Threads.atomic_min!(x, 5) -7 - -julia> x[] -5 -``` -""" -function atomic_min! end - -unsafe_convert(::Type{Ptr{T}}, x::Atomic{T}) where {T} = convert(Ptr{T}, pointer_from_objref(x)) -setindex!(x::Atomic{T}, v) where {T} = setindex!(x, convert(T, v)) - -const llvmtypes = Dict( - Bool => "i1", - Int8 => "i8", UInt8 => "i8", - Int16 => "i16", UInt16 => "i16", - Int32 => "i32", UInt32 => "i32", - Int64 => "i64", UInt64 => "i64", - Int128 => "i128", UInt128 => "i128", - Float16 => "i16", # half - Float32 => "float", - Float64 => "double", -) -inttype(::Type{T}) where {T<:Integer} = T -inttype(::Type{Float16}) = Int16 -inttype(::Type{Float32}) = Int32 -inttype(::Type{Float64}) = Int64 - - -alignment(::Type{T}) where {T} = ccall(:jl_alignment, Cint, (Csize_t,), sizeof(T)) - -# All atomic operations have acquire and/or release semantics, depending on -# whether the load or store values. Most of the time, this is what one wants -# anyway, and it's only moderately expensive on most hardware. -for typ in atomictypes - lt = llvmtypes[typ] - ilt = llvmtypes[inttype(typ)] - rt = VersionNumber(Base.libllvm_version) >= v"3.6" ? "$lt, $lt*" : "$lt*" - irt = VersionNumber(Base.libllvm_version) >= v"3.6" ? "$ilt, $ilt*" : "$ilt*" - if VersionNumber(Base.libllvm_version) >= v"3.8" - @eval getindex(x::Atomic{$typ}) = - llvmcall($""" - %rv = load atomic $rt %0 acquire, align $(alignment(typ)) - ret $lt %rv - """, $typ, Tuple{Ptr{$typ}}, unsafe_convert(Ptr{$typ}, x)) - @eval setindex!(x::Atomic{$typ}, v::$typ) = - llvmcall($""" - store atomic $lt %1, $lt* %0 release, align $(alignment(typ)) - ret void - """, Void, Tuple{Ptr{$typ},$typ}, unsafe_convert(Ptr{$typ}, x), v) - else - if typ <: Integer - @eval getindex(x::Atomic{$typ}) = - llvmcall($""" - %rv = load atomic $rt %0 acquire, align $(alignment(typ)) - ret $lt %rv - """, $typ, Tuple{Ptr{$typ}}, unsafe_convert(Ptr{$typ}, x)) - @eval setindex!(x::Atomic{$typ}, v::$typ) = - llvmcall($""" - store atomic $lt %1, $lt* %0 release, align $(alignment(typ)) - ret void - """, Void, Tuple{Ptr{$typ},$typ}, unsafe_convert(Ptr{$typ}, x), v) - else - @eval getindex(x::Atomic{$typ}) = - llvmcall($""" - %iptr = bitcast $lt* %0 to $ilt* - %irv = load atomic $irt %iptr acquire, align $(alignment(typ)) - %rv = bitcast $ilt %irv to $lt - ret $lt %rv - """, $typ, Tuple{Ptr{$typ}}, unsafe_convert(Ptr{$typ}, x)) - @eval setindex!(x::Atomic{$typ}, v::$typ) = - llvmcall($""" - %iptr = bitcast $lt* %0 to $ilt* - %ival = bitcast $lt %1 to $ilt - store atomic $ilt %ival, $ilt* %iptr release, align $(alignment(typ)) - ret void - """, Void, Tuple{Ptr{$typ},$typ}, unsafe_convert(Ptr{$typ}, x), v) - end - end - # Note: atomic_cas! succeeded (i.e. it stored "new") if and only if the result is "cmp" - if VersionNumber(Base.libllvm_version) >= v"3.5" - if typ <: Integer - @eval atomic_cas!(x::Atomic{$typ}, cmp::$typ, new::$typ) = - llvmcall($""" - %rs = cmpxchg $lt* %0, $lt %1, $lt %2 acq_rel acquire - %rv = extractvalue { $lt, i1 } %rs, 0 - ret $lt %rv - """, $typ, Tuple{Ptr{$typ},$typ,$typ}, - unsafe_convert(Ptr{$typ}, x), cmp, new) - else - @eval atomic_cas!(x::Atomic{$typ}, cmp::$typ, new::$typ) = - llvmcall($""" - %iptr = bitcast $lt* %0 to $ilt* - %icmp = bitcast $lt %1 to $ilt - %inew = bitcast $lt %2 to $ilt - %irs = cmpxchg $ilt* %iptr, $ilt %icmp, $ilt %inew acq_rel acquire - %irv = extractvalue { $ilt, i1 } %irs, 0 - %rv = bitcast $ilt %irv to $lt - ret $lt %rv - """, $typ, Tuple{Ptr{$typ},$typ,$typ}, - unsafe_convert(Ptr{$typ}, x), cmp, new) - end - else - if typ <: Integer - @eval atomic_cas!(x::Atomic{$typ}, cmp::$typ, new::$typ) = - llvmcall($""" - %rv = cmpxchg $lt* %0, $lt %1, $lt %2 acq_rel - ret $lt %rv - """, $typ, Tuple{Ptr{$typ},$typ,$typ}, - unsafe_convert(Ptr{$typ}, x), cmp, new) - else - @eval atomic_cas!(x::Atomic{$typ}, cmp::$typ, new::$typ) = - llvmcall($""" - %iptr = bitcast $lt* %0 to $ilt* - %icmp = bitcast $lt %1 to $ilt - %inew = bitcast $lt %2 to $ilt - %irv = cmpxchg $ilt* %iptr, $ilt %icmp, $ilt %inew acq_rel - %rv = bitcast $ilt %irv to $lt - ret $lt %rv - """, $typ, Tuple{Ptr{$typ},$typ,$typ}, - unsafe_convert(Ptr{$typ}, x), cmp, new) - end - end - for rmwop in [:xchg, :add, :sub, :and, :nand, :or, :xor, :max, :min] - rmw = string(rmwop) - fn = Symbol("atomic_", rmw, "!") - if (rmw == "max" || rmw == "min") && typ <: Unsigned - # LLVM distinguishes signedness in the operation, not the integer type. - rmw = "u" * rmw - end - if typ <: Integer - @eval $fn(x::Atomic{$typ}, v::$typ) = - llvmcall($""" - %rv = atomicrmw $rmw $lt* %0, $lt %1 acq_rel - ret $lt %rv - """, $typ, Tuple{Ptr{$typ}, $typ}, unsafe_convert(Ptr{$typ}, x), v) - else - rmwop == :xchg || continue - @eval $fn(x::Atomic{$typ}, v::$typ) = - llvmcall($""" - %iptr = bitcast $lt* %0 to $ilt* - %ival = bitcast $lt %1 to $ilt - %irv = atomicrmw $rmw $ilt* %iptr, $ilt %ival acq_rel - %rv = bitcast $ilt %irv to $lt - ret $lt %rv - """, $typ, Tuple{Ptr{$typ}, $typ}, unsafe_convert(Ptr{$typ}, x), v) - end - end -end - -# Provide atomic floating-point operations via atomic_cas! -const opnames = Dict{Symbol, Symbol}(:+ => :add, :- => :sub) -for op in [:+, :-, :max, :min] - opname = get(opnames, op, op) - @eval function $(Symbol("atomic_", opname, "!"))(var::Atomic{T}, val::T) where T<:FloatTypes - IT = inttype(T) - old = var[] - while true - new = $op(old, val) - cmp = old - old = atomic_cas!(var, cmp, new) - reinterpret(IT, old) == reinterpret(IT, cmp) && return new - # Temporary solution before we have gc transition support in codegen. - ccall(:jl_gc_safepoint, Void, ()) - end - end -end - -""" - Threads.atomic_fence() - -Insert a sequential-consistency memory fence - -Inserts a memory fence with sequentially-consistent ordering -semantics. There are algorithms where this is needed, i.e. where an -acquire/release ordering is insufficient. - -This is likely a very expensive operation. Given that all other atomic -operations in Julia already have acquire/release semantics, explicit -fences should not be necessary in most cases. - -For further details, see LLVM's `fence` instruction. -""" -atomic_fence() = llvmcall(""" - fence seq_cst - ret void - """, Void, Tuple{}) diff --git a/julia-0.6.3/share/julia/base/base.jl b/julia-0.6.3/share/julia/base/base.jl deleted file mode 100644 index ee4bf7f..0000000 --- a/julia-0.6.3/share/julia/base/base.jl +++ /dev/null @@ -1,153 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -""" - SystemError(prefix::AbstractString, [errno::Int32]) - -A system call failed with an error code (in the `errno` global variable). -""" -mutable struct SystemError <: Exception - prefix::AbstractString - errnum::Int32 - extrainfo - SystemError(p::AbstractString, e::Integer, extrainfo) = new(p, e, extrainfo) - SystemError(p::AbstractString, e::Integer) = new(p, e, nothing) - SystemError(p::AbstractString) = new(p, Libc.errno()) -end - -""" - ParseError(msg) - -The expression passed to the `parse` function could not be interpreted as a valid Julia -expression. -""" -mutable struct ParseError <: Exception - msg::AbstractString -end - -""" - ArgumentError(msg) - -The parameters to a function call do not match a valid signature. Argument `msg` is a -descriptive error string. -""" -mutable struct ArgumentError <: Exception - msg::AbstractString -end - -""" - KeyError(key) - -An indexing operation into an `Associative` (`Dict`) or `Set` like object tried to access or -delete a non-existent element. -""" -mutable struct KeyError <: Exception - key -end - -""" - MethodError(f, args) - -A method with the required type signature does not exist in the given generic function. -Alternatively, there is no unique most-specific method. -""" -mutable struct MethodError <: Exception - f - args - world::UInt - MethodError(f::ANY, args::ANY, world::UInt) = new(f, args, world) -end -MethodError(f::ANY, args::ANY) = MethodError(f, args, typemax(UInt)) - -""" - EOFError() - -No more data was available to read from a file or stream. -""" -mutable struct EOFError <: Exception end - -""" - DimensionMismatch([msg]) - -The objects called do not have matching dimensionality. Optional argument `msg` is a -descriptive error string. -""" -mutable struct DimensionMismatch <: Exception - msg::AbstractString -end -DimensionMismatch() = DimensionMismatch("") - -""" - AssertionError([msg]) - -The asserted condition did not evaluate to `true`. -Optional argument `msg` is a descriptive error string. -""" -mutable struct AssertionError <: Exception - msg::AbstractString - AssertionError() = new("") - AssertionError(msg) = new(msg) -end - -#Generic wrapping of arbitrary exceptions -#Subtypes should put the exception in an 'error' field -abstract type WrappedException <: Exception end - -""" - LoadError(file::AbstractString, line::Int, error) - -An error occurred while `include`ing, `require`ing, or `using` a file. The error specifics -should be available in the `.error` field. -""" -mutable struct LoadError <: WrappedException - file::AbstractString - line::Int - error -end - -""" - InitError(mod::Symbol, error) - -An error occurred when running a module's `__init__` function. The actual error thrown is -available in the `.error` field. -""" -mutable struct InitError <: WrappedException - mod::Symbol - error -end - -ccall(:jl_get_system_hooks, Void, ()) - - -==(w::WeakRef, v::WeakRef) = isequal(w.value, v.value) -==(w::WeakRef, v) = isequal(w.value, v) -==(w, v::WeakRef) = isequal(w, v.value) - -function finalizer(o::ANY, f::ANY) - if isimmutable(o) - error("objects of type ", typeof(o), " cannot be finalized") - end - ccall(:jl_gc_add_finalizer_th, Void, (Ptr{Void}, Any, Any), - Core.getptls(), o, f) -end -function finalizer(o::T, f::Ptr{Void}) where T - @_inline_meta - if isimmutable(T) - error("objects of type ", T, " cannot be finalized") - end - ccall(:jl_gc_add_ptr_finalizer, Void, (Ptr{Void}, Any, Ptr{Void}), - Core.getptls(), o, f) -end - -finalize(o::ANY) = ccall(:jl_finalize_th, Void, (Ptr{Void}, Any,), - Core.getptls(), o) - -gc(full::Bool=true) = ccall(:jl_gc_collect, Void, (Int32,), full) -gc_enable(on::Bool) = ccall(:jl_gc_enable, Int32, (Int32,), on) != 0 - -struct Nullable{T} - hasvalue::Bool - value::T - - Nullable{T}() where {T} = new(false) - Nullable{T}(value::T, hasvalue::Bool=true) where {T} = new(hasvalue, value) -end diff --git a/julia-0.6.3/share/julia/base/base64.jl b/julia-0.6.3/share/julia/base/base64.jl deleted file mode 100644 index 99f507e..0000000 --- a/julia-0.6.3/share/julia/base/base64.jl +++ /dev/null @@ -1,287 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -module Base64 -import Base: read, write, close, eof, empty! -export Base64EncodePipe, Base64DecodePipe, base64encode, base64decode - -# Base64EncodePipe is a pipe-like IO object, which converts into base64 data sent -# to a stream. (You must close the pipe to complete the encode, separate from -# closing the target stream). We also have a function base64encode(f, -# args...) which works like sprint except that it produces -# base64-encoded data, along with base64encode(args...) which is equivalent -# to base64encode(write, args...), to return base64 strings. -# A Base64DecodePipe object can be used to decode base64-encoded data read from a stream -# , while function base64decode is useful for decoding strings -############################################################################# - -""" - Base64EncodePipe(ostream) - -Returns a new write-only I/O stream, which converts any bytes written to it into -base64-encoded ASCII bytes written to `ostream`. -Calling [`close`](@ref) on the `Base64EncodePipe` stream -is necessary to complete the encoding (but does not close `ostream`). - -```jldoctest -julia> io = IOBuffer(); - -julia> iob64_encode = Base64EncodePipe(io); - -julia> write(iob64_encode, "Hello!") -6 - -julia> close(iob64_encode); - -julia> str = String(take!(io)) -"SGVsbG8h" - -julia> String(base64decode(str)) -"Hello!" -``` -""" -mutable struct Base64EncodePipe <: IO - io::IO - # writing works in groups of 3, so we need to cache last two bytes written - b0::UInt8 - b1::UInt8 - nb::UInt8 # number of bytes in cache: 0, 1, or 2 - - function Base64EncodePipe(io::IO) - b = new(io,0,0,0) - finalizer(b, close) - return b - end -end - -############################################################################# - -# Based on code by Stefan Karpinski from https://github.com/hackerschool/WebSockets.jl (distributed under the same MIT license as Julia) - -const b64chars = ['A':'Z';'a':'z';'0':'9';'+';'/'] - -const base64_pad = UInt8('=') - -function b64(x::UInt8, y::UInt8, z::UInt8) - n = Int(x)<<16 | Int(y)<<8 | Int(z) - b64chars[(n >> 18) + 1], - b64chars[(n >> 12) & 0b111111 + 1], - b64chars[(n >> 6) & 0b111111 + 1], - b64chars[(n ) & 0b111111 + 1] -end - -function b64(x::UInt8, y::UInt8) - a, b, c = b64(x, y, 0x0) - a, b, c, base64_pad -end - -function b64(x::UInt8) - a, b = b64(x, 0x0, 0x0) - a, b, base64_pad, base64_pad -end - -const sentinel = typemax(UInt8) -const revb64chars = fill(sentinel, 256) -# Fill revb64chars -for (val, ch) in enumerate(b64chars) - revb64chars[UInt8(ch)] = UInt8(val - 1) -end - -# Decode a block of at least 2 and at most 4 bytes, received in encvec -# Returns the first decoded byte and stores up to two more in cache -function b64decode!(encvec::Vector{UInt8}, cache::Vector{UInt8}) - if length(encvec) < 2 - throw(ArgumentError("incorrect base64 format, block must be at least 2 and at most 4 bytes")) - end - @inbounds u = revb64chars[encvec[1]] - @inbounds v = revb64chars[encvec[2]] - empty!(cache) - res = (u << 2) | (v >> 4) - if length(encvec) > 2 - @inbounds w = revb64chars[encvec[3]] - push!(cache, (v << 4) | (w >> 2)) - end - if length(encvec) > 3 - @inbounds z = revb64chars[encvec[4]] - push!(cache, (w << 6) | z) - end - res -end - - -############################################################################# - -function unsafe_write(b::Base64EncodePipe, x::Ptr{UInt8}, n::UInt) - s = 1 # starting index - # finish any cached data to write: - if b.nb == 1 - if n >= 2 - write(b.io, b64(b.b0, unsafe_load(x, 1), unsafe_load(x, 2))...) - s = 3 - elseif n == 1 - b.b1 = unsafe_load(x, 1) - b.nb = 2 - return - else - return - end - elseif b.nb == 2 - if n >= 1 - write(b.io, b64(b.b0, b.b1, unsafe_load(x, 1))...) - s = 2 - else - return - end - end - # write all groups of three bytes: - while s + 2 <= n - write(b.io, b64(unsafe_load(x, s), unsafe_load(x, s + 1), unsafe_load(x, s + 2))...) - s += 3 - end - # cache any leftover bytes: - if s + 1 == n - b.b0 = unsafe_load(x, s) - b.b1 = unsafe_load(x, s + 1) - b.nb = 2 - elseif s == n - b.b0 = unsafe_load(x, s) - b.nb = 1 - else - b.nb = 0 - end - n -end - -function write(b::Base64EncodePipe, x::UInt8) - if b.nb == 0 - b.b0 = x - b.nb = 1 - elseif b.nb == 1 - b.b1 = x - b.nb = 2 - else - write(b.io, b64(b.b0,b.b1,x)...) - b.nb = 0 - end - 1 -end - -function close(b::Base64EncodePipe) - if b.nb > 0 - # write leftover bytes + padding - if b.nb == 1 - write(b.io, b64(b.b0)...) - else # b.nb == 2 - write(b.io, b64(b.b0, b.b1)...) - end - b.nb = 0 - end - nothing -end - -# like sprint, but returns base64 string -""" - base64encode(writefunc, args...) - base64encode(args...) - -Given a [`write`](@ref)-like function `writefunc`, which takes an I/O stream as its first argument, -`base64encode(writefunc, args...)` calls `writefunc` to write `args...` to a base64-encoded -string, and returns the string. `base64encode(args...)` is equivalent to `base64encode(write, args...)`: -it converts its arguments into bytes using the standard [`write`](@ref) functions and returns the -base64-encoded string. - -See also [`base64decode`](@ref). -""" -function base64encode(f::Function, args...) - s = IOBuffer() - b = Base64EncodePipe(s) - f(b, args...) - close(b) - String(take!(s)) -end -base64encode(x...) = base64encode(write, x...) - -############################################################################# - -""" - Base64DecodePipe(istream) - -Returns a new read-only I/O stream, which decodes base64-encoded data read from `istream`. - -```jldoctest -julia> io = IOBuffer(); - -julia> iob64_decode = Base64DecodePipe(io); - -julia> write(io, "SGVsbG8h") -8 - -julia> seekstart(io); - -julia> String(read(iob64_decode)) -"Hello!" -``` -""" -mutable struct Base64DecodePipe <: IO - io::IO - # reading works in blocks of 4 characters that are decoded into 3 bytes and 2 of them cached - cache::Vector{UInt8} - encvec::Vector{UInt8} - - function Base64DecodePipe(io::IO) - b = new(io,[],[]) - finalizer(b, close) - return b - end -end - -function read(b::Base64DecodePipe, t::Type{UInt8}) - if !isempty(b.cache) - return shift!(b.cache) - else - empty!(b.encvec) - while !eof(b.io) && length(b.encvec) < 4 - c::UInt8 = read(b.io, t) - @inbounds if revb64chars[c] != sentinel - push!(b.encvec, c) - end - end - return b64decode!(b.encvec,b.cache) - end -end - -eof(b::Base64DecodePipe) = isempty(b.cache) && eof(b.io) -close(b::Base64DecodePipe) = nothing - -# Decodes a base64-encoded string - -""" - base64decode(string) - -Decodes the base64-encoded `string` and returns a `Vector{UInt8}` of the decoded bytes. - -See also [`base64encode`](@ref) - -```jldoctest -julia> b = base64decode("SGVsbG8h") -6-element Array{UInt8,1}: - 0x48 - 0x65 - 0x6c - 0x6c - 0x6f - 0x21 - -julia> String(b) -"Hello!" -``` -""" -function base64decode(s) - b = IOBuffer(s) - try - return read(Base64DecodePipe(b)) - finally - close(b) - end -end - -end # module diff --git a/julia-0.6.3/share/julia/base/bitarray.jl b/julia-0.6.3/share/julia/base/bitarray.jl deleted file mode 100644 index 7fd2ba6..0000000 --- a/julia-0.6.3/share/julia/base/bitarray.jl +++ /dev/null @@ -1,2020 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -## BitArray - -# notes: bits are stored in contiguous chunks -# unused bits must always be set to 0 -mutable struct BitArray{N} <: DenseArray{Bool, N} - chunks::Vector{UInt64} - len::Int - dims::NTuple{N,Int} - function BitArray{N}(dims::Vararg{Int,N}) where N - n = 1 - i = 1 - for d in dims - d >= 0 || throw(ArgumentError("dimension size must be ≥ 0, got $d for dimension $i")) - n *= d - i += 1 - end - nc = num_bit_chunks(n) - chunks = Vector{UInt64}(nc) - nc > 0 && (chunks[end] = UInt64(0)) - b = new(chunks, n) - N != 1 && (b.dims = dims) - return b - end -end - -# note: the docs for the two signatures are unified, but only -# the first one is recognized by the help system; it would be nice -# to fix this. -""" - BitArray(dims::Integer...) - BitArray{N}(dims::NTuple{N,Int}) - -Construct an uninitialized `BitArray` with the given dimensions. -Behaves identically to the [`Array`](@ref) constructor. - -```julia-repl -julia> BitArray(2, 2) -2×2 BitArray{2}: - false false - false true - -julia> BitArray((3, 1)) -3×1 BitArray{2}: - false - true - false -``` -""" -BitArray(dims::Integer...) = BitArray(map(Int,dims)) -BitArray(dims::NTuple{N,Int}) where {N} = BitArray{N}(dims...) - -const BitVector = BitArray{1} -const BitMatrix = BitArray{2} - -BitVector() = BitArray{1}(0) - -## utility functions ## - -length(B::BitArray) = B.len -size(B::BitVector) = (B.len,) -size(B::BitArray) = B.dims - -@inline function size(B::BitVector, d) - d < 1 && throw_boundserror(size(B), d) - ifelse(d == 1, B.len, 1) -end - -isassigned(B::BitArray, i::Int) = 1 <= i <= length(B) - -IndexStyle(::Type{<:BitArray}) = IndexLinear() - -## aux functions ## - -const _msk64 = ~UInt64(0) -@inline _div64(l) = l >>> 6 -@inline _mod64(l) = l & 63 -@inline _msk_end(l::Integer) = _msk64 >>> _mod64(-l) -@inline _msk_end(B::BitArray) = _msk_end(length(B)) -num_bit_chunks(n::Int) = _div64(n+63) - -function _check_bitarray_consistency{N}(B::BitArray{N}) - n = length(B) - if N ≠ 1 - all(d ≥ 0 for d in B.dims) || (warn("negative d in dims: $(B.dims)"); return false) - prod(B.dims) ≠ n && (warn("inconsistent dims/len: prod(dims)=$(prod(B.dims)) len=$n"); return false) - end - Bc = B.chunks - nc = length(Bc) - nc == num_bit_chunks(n) || (warn("incorrect chunks length for length $n: expected=$(num_bit_chunks(n)) actual=$nc"); return false) - n == 0 && return true - Bc[end] & _msk_end(n) == Bc[end] || (warn("nonzero bits in chunk after BitArray end"); return false) - return true -end - -@inline get_chunks_id(i::Integer) = _div64(Int(i)-1)+1, _mod64(Int(i)-1) - -function glue_src_bitchunks(src::Vector{UInt64}, k::Int, ks1::Int, msk_s0::UInt64, ls0::Int) - @inbounds begin - chunk = ((src[k] & msk_s0) >>> ls0) - if ks1 > k && ls0 > 0 - chunk_n = (src[k + 1] & ~msk_s0) - chunk |= (chunk_n << (64 - ls0)) - end - end - return chunk -end - -function copy_chunks!(dest::Vector{UInt64}, pos_d::Integer, src::Vector{UInt64}, pos_s::Integer, numbits::Integer) - numbits == 0 && return - if dest === src && pos_d > pos_s - return copy_chunks_rtol!(dest, pos_d, pos_s, numbits) - end - - kd0, ld0 = get_chunks_id(pos_d) - kd1, ld1 = get_chunks_id(pos_d + numbits - 1) - ks0, ls0 = get_chunks_id(pos_s) - ks1, ls1 = get_chunks_id(pos_s + numbits - 1) - - delta_kd = kd1 - kd0 - delta_ks = ks1 - ks0 - - u = _msk64 - if delta_kd == 0 - msk_d0 = ~(u << ld0) | (u << (ld1+1)) - else - msk_d0 = ~(u << ld0) - msk_d1 = (u << (ld1+1)) - end - if delta_ks == 0 - msk_s0 = (u << ls0) & ~(u << (ls1+1)) - else - msk_s0 = (u << ls0) - end - - chunk_s0 = glue_src_bitchunks(src, ks0, ks1, msk_s0, ls0) - - dest[kd0] = (dest[kd0] & msk_d0) | ((chunk_s0 << ld0) & ~msk_d0) - - delta_kd == 0 && return - - for i = 1 : kd1 - kd0 - 1 - chunk_s1 = glue_src_bitchunks(src, ks0 + i, ks1, msk_s0, ls0) - - chunk_s = (chunk_s0 >>> (64 - ld0)) | (chunk_s1 << ld0) - - dest[kd0 + i] = chunk_s - - chunk_s0 = chunk_s1 - end - - if ks1 >= ks0 + delta_kd - chunk_s1 = glue_src_bitchunks(src, ks0 + delta_kd, ks1, msk_s0, ls0) - else - chunk_s1 = UInt64(0) - end - - chunk_s = (chunk_s0 >>> (64 - ld0)) | (chunk_s1 << ld0) - - dest[kd1] = (dest[kd1] & msk_d1) | (chunk_s & ~msk_d1) - - return -end - -function copy_chunks_rtol!(chunks::Vector{UInt64}, pos_d::Integer, pos_s::Integer, numbits::Integer) - pos_d == pos_s && return - pos_d < pos_s && return copy_chunks!(chunks, pos_d, chunks, pos_s, numbits) - - left = numbits - s = min(left, 64) - b = left - s - ps = pos_s + b - pd = pos_d + b - u = _msk64 - while left > 0 - kd0, ld0 = get_chunks_id(pd) - kd1, ld1 = get_chunks_id(pd + s - 1) - ks0, ls0 = get_chunks_id(ps) - ks1, ls1 = get_chunks_id(ps + s - 1) - - delta_kd = kd1 - kd0 - delta_ks = ks1 - ks0 - - if delta_kd == 0 - msk_d0 = ~(u << ld0) | (u << (ld1+1)) - else - msk_d0 = ~(u << ld0) - msk_d1 = (u << (ld1+1)) - end - if delta_ks == 0 - msk_s0 = (u << ls0) & ~(u << (ls1+1)) - else - msk_s0 = (u << ls0) - end - - chunk_s0 = glue_src_bitchunks(chunks, ks0, ks1, msk_s0, ls0) & ~(u << s) - chunks[kd0] = (chunks[kd0] & msk_d0) | ((chunk_s0 << ld0) & ~msk_d0) - - if delta_kd != 0 - chunk_s = (chunk_s0 >>> (64 - ld0)) - - chunks[kd1] = (chunks[kd1] & msk_d1) | (chunk_s & ~msk_d1) - end - - left -= s - s = min(left, 64) - b = left - s - ps = pos_s + b - pd = pos_d + b - end -end - -function fill_chunks!(Bc::Array{UInt64}, x::Bool, pos::Integer, numbits::Integer) - numbits <= 0 && return - k0, l0 = get_chunks_id(pos) - k1, l1 = get_chunks_id(pos+numbits-1) - - u = _msk64 - if k1 == k0 - msk0 = (u << l0) & ~(u << (l1+1)) - else - msk0 = (u << l0) - msk1 = ~(u << (l1+1)) - end - @inbounds if x - Bc[k0] |= msk0 - for k = k0+1:k1-1 - Bc[k] = u - end - k1 > k0 && (Bc[k1] |= msk1) - else - Bc[k0] &= ~msk0 - for k = k0+1:k1-1 - Bc[k] = 0 - end - k1 > k0 && (Bc[k1] &= ~msk1) - end -end - -copy_to_bitarray_chunks!(dest::Vector{UInt64}, pos_d::Int, src::BitArray, pos_s::Int, numbits::Int) = - copy_chunks!(dest, pos_d, src.chunks, pos_s, numbits) - -# pack 8 Bools encoded as one contiguous UIn64 into a single byte, e.g.: -# 0000001:0000001:00000000:00000000:00000001:00000000:00000000:00000001 → 11001001 → 0xc9 -function pack8bools(z::UInt64) - z |= z >>> 7 - z |= z >>> 14 - z |= z >>> 28 - z &= 0xFF - return z -end - -function copy_to_bitarray_chunks!(Bc::Vector{UInt64}, pos_d::Int, C::Array{Bool}, pos_s::Int, numbits::Int) - kd0, ld0 = get_chunks_id(pos_d) - kd1, ld1 = get_chunks_id(pos_d + numbits - 1) - - delta_kd = kd1 - kd0 - - u = _msk64 - if delta_kd == 0 - msk_d0 = msk_d1 = ~(u << ld0) | (u << (ld1+1)) - lt0 = ld1 - else - msk_d0 = ~(u << ld0) - msk_d1 = (u << (ld1+1)) - lt0 = 63 - end - - bind = kd0 - ind = pos_s - @inbounds if ld0 > 0 - c = UInt64(0) - for j = ld0:lt0 - c |= (UInt64(C[ind]) << j) - ind += 1 - end - Bc[kd0] = (Bc[kd0] & msk_d0) | (c & ~msk_d0) - bind += 1 - end - - nc = _div64(numbits - ind + pos_s) - nc8 = (nc >>> 3) << 3 - if nc8 > 0 - ind8 = 1 - P8 = Ptr{UInt64}(pointer(C, ind)) # unaligned i64 pointer - @inbounds for i = 1:nc8 - c = UInt64(0) - for j = 0:7 - # unaligned load - c |= (pack8bools(unsafe_load(P8, ind8)) << (j<<3)) - ind8 += 1 - end - Bc[bind] = c - bind += 1 - end - ind += (ind8-1) << 3 - end - @inbounds for i = (nc8+1):nc - c = UInt64(0) - for j = 0:63 - c |= (UInt64(C[ind]) << j) - ind += 1 - end - Bc[bind] = c - bind += 1 - end - @inbounds if bind ≤ kd1 - @assert bind == kd1 - c = UInt64(0) - for j = 0:ld1 - c |= (UInt64(C[ind]) << j) - ind += 1 - end - Bc[kd1] = (Bc[kd1] & msk_d1) | (c & ~msk_d1) - end -end - -## More definitions in multidimensional.jl - -# auxiliary definitions used when filling a BitArray via a Vector{Bool} cache -# (e.g. when constructing from an iterable, or in broadcast!) - -const bitcache_chunks = 64 # this can be changed -const bitcache_size = 64 * bitcache_chunks # do not change this - -dumpbitcache(Bc::Vector{UInt64}, bind::Int, C::Vector{Bool}) = - copy_to_bitarray_chunks!(Bc, ((bind - 1) << 6) + 1, C, 1, min(bitcache_size, (length(Bc)-bind+1) << 6)) - - -## custom iterator ## -start(B::BitArray) = 0 -next(B::BitArray, i::Int) = (B.chunks[_div64(i)+1] & (UInt64(1)<<_mod64(i)) != 0, i+1) -done(B::BitArray, i::Int) = i >= length(B) - -## similar, fill!, copy! etc ## - -similar(B::BitArray) = BitArray(size(B)) -similar(B::BitArray, dims::Int...) = BitArray(dims) -similar(B::BitArray, dims::Dims) = BitArray(dims...) - -similar(B::BitArray, T::Type{Bool}, dims::Dims) = BitArray(dims) -# changing type to a non-Bool returns an Array -# (this triggers conversions like float(bitvector) etc.) -similar(B::BitArray, T::Type, dims::Dims) = Array{T}(dims) - -function fill!(B::BitArray, x) - y = convert(Bool, x) - isempty(B) && return B - Bc = B.chunks - if !y - fill!(Bc, 0) - else - fill!(Bc, _msk64) - Bc[end] &= _msk_end(B) - end - return B -end - -""" - falses(dims) - -Create a `BitArray` with all values set to `false`. - -```jldoctest -julia> falses(2,3) -2×3 BitArray{2}: - false false false - false false false -``` -""" -falses(dims::Dims) = fill!(BitArray(dims), false) -falses(dims::Integer...) = falses(map(Int,dims)) -""" - falses(A) - -Create a `BitArray` with all values set to `false` of the same shape as `A`. - -```jldoctest -julia> A = [1 2; 3 4] -2×2 Array{Int64,2}: - 1 2 - 3 4 - -julia> falses(A) -2×2 BitArray{2}: - false false - false false -``` -""" -falses(A::AbstractArray) = falses(size(A)) - -""" - trues(dims) - -Create a `BitArray` with all values set to `true`. - -```jldoctest -julia> trues(2,3) -2×3 BitArray{2}: - true true true - true true true -``` -""" -trues(dims::Dims) = fill!(BitArray(dims), true) -trues(dims::Integer...) = trues(map(Int,dims)) -""" - trues(A) - -Create a `BitArray` with all values set to `true` of the same shape as `A`. - -```jldoctest -julia> A = [1 2; 3 4] -2×2 Array{Int64,2}: - 1 2 - 3 4 - -julia> trues(A) -2×2 BitArray{2}: - true true - true true -``` -""" -trues(A::AbstractArray) = trues(size(A)) - -function one(x::BitMatrix) - m, n = size(x) - m == n || throw(DimensionMismatch("multiplicative identity defined only for square matrices")) - a = falses(n, n) - for i = 1:n - a[i,i] = true - end - return a -end - -function copy!(dest::BitArray, src::BitArray) - length(src) > length(dest) && throw(BoundsError(dest, length(dest)+1)) - destc = dest.chunks; srcc = src.chunks - nc = min(length(destc), length(srcc)) - nc == 0 && return dest - @inbounds begin - for i = 1 : nc - 1 - destc[i] = srcc[i] - end - if length(src) == length(dest) - destc[nc] = srcc[nc] - else - msk_s = _msk_end(src) - msk_d = ~msk_s - destc[nc] = (msk_d & destc[nc]) | (msk_s & srcc[nc]) - end - end - return dest -end - -function unsafe_copy!(dest::BitArray, doffs::Integer, src::Union{BitArray,Array}, soffs::Integer, n::Integer) - copy_to_bitarray_chunks!(dest.chunks, doffs, src, soffs, n) - return dest -end - -function copy!(dest::BitArray, doffs::Integer, src::Array, soffs::Integer, n::Integer) - n == 0 && return dest - soffs < 1 && throw(BoundsError(src, soffs)) - doffs < 1 && throw(BoundsError(dest, doffs)) - soffs+n-1 > length(src) && throw(BoundsError(src, length(src)+1)) - doffs+n-1 > length(dest) && throw(BoundsError(dest, length(dest)+1)) - return unsafe_copy!(dest, doffs, src, soffs, n) -end - -function copy!(dest::BitArray, src::Array) - length(src) > length(dest) && throw(BoundsError(dest, length(dest)+1)) - length(src) == 0 && return det - return unsafe_copy!(dest, 1, src, 1, length(src)) -end - -function reshape(B::BitArray{N}, dims::NTuple{N,Int}) where N - return dims == size(B) ? B : _bitreshape(B, dims) -end -reshape(B::BitArray, dims::Tuple{Vararg{Int}}) = _bitreshape(B, dims) -function _bitreshape(B::BitArray, dims::NTuple{N,Int}) where N - prod(dims) == length(B) || - throw(DimensionMismatch("new dimensions $(dims) must be consistent with array size $(length(B))")) - Br = BitArray{N}(ntuple(i->0,Val{N})...) - Br.chunks = B.chunks - Br.len = prod(dims) - N != 1 && (Br.dims = dims) - return Br -end - -## Conversions ## - -convert(::Type{Array{T}}, B::BitArray{N}) where {T,N} = convert(Array{T,N}, B) -convert(::Type{Array{T,N}}, B::BitArray{N}) where {T,N} = _convert(Array{T,N}, B) # see #15801 -function _convert(::Type{Array{T,N}}, B::BitArray{N}) where {T,N} - A = Array{T}(size(B)) - Bc = B.chunks - @inbounds for i = 1:length(A) - A[i] = unsafe_bitgetindex(Bc, i) - end - return A -end - -convert(::Type{BitArray}, A::AbstractArray{T,N}) where {T,N} = convert(BitArray{N}, A) -function convert(::Type{BitArray{N}}, A::AbstractArray{T,N}) where N where T - B = BitArray(size(A)) - Bc = B.chunks - l = length(B) - l == 0 && return B - ind = 1 - @inbounds begin - for i = 1:length(Bc)-1 - c = UInt64(0) - for j = 0:63 - c |= (UInt64(A[ind] != 0) << j) - ind += 1 - end - Bc[i] = c - end - c = UInt64(0) - for j = 0:_mod64(l-1) - c |= (UInt64(A[ind] != 0) << j) - ind += 1 - end - Bc[end] = c - end - return B -end - -function convert(::Type{BitArray{N}}, A::Array{Bool,N}) where N - B = BitArray(size(A)) - Bc = B.chunks - l = length(B) - l == 0 && return B - copy_to_bitarray_chunks!(Bc, 1, A, 1, l) - return B -end - -convert(::Type{BitArray{N}}, B::BitArray{N}) where {N} = B -convert(::Type{AbstractArray{T,N}}, B::BitArray{N}) where {T,N} = convert(Array{T,N}, B) - -reinterpret(::Type{Bool}, B::BitArray, dims::NTuple{N,Int}) where {N} = reinterpret(B, dims) -reinterpret(B::BitArray, dims::NTuple{N,Int}) where {N} = reshape(B, dims) - -## Constructors from generic iterables ## - -BitArray{T,N}(A::AbstractArray{T,N}) = convert(BitArray{N}, A) - -""" - BitArray(itr) - -Construct a `BitArray` generated by the given iterable object. The shape is inferred from -the `itr` object. - -```jldoctest -julia> BitArray([1 0; 0 1]) -2×2 BitArray{2}: - true false - false true - -julia> BitArray(x+y == 3 for x = 1:2, y = 1:3) -2×3 BitArray{2}: - false true false - true false false - -julia> BitArray(x+y == 3 for x = 1:2 for y = 1:3) -6-element BitArray{1}: - false - true - false - true - false - false -``` -""" -BitArray(itr) = gen_bitarray(iteratorsize(itr), itr) - -# generic constructor from an iterable without compile-time info -# (we pass start(itr) explicitly to avoid a type-instability with filters) -gen_bitarray(isz::IteratorSize, itr) = gen_bitarray_from_itr(itr, start(itr)) - -# generic iterable with known shape -function gen_bitarray(::HasShape, itr) - B = BitArray(size(itr)) - for (I,x) in zip(CartesianRange(indices(itr)), itr) - B[I] = x - end - return B -end - -# generator with known shape or length -function gen_bitarray(::HasShape, itr::Generator) - B = BitArray(size(itr)) - return fill_bitarray_from_itr!(B, itr, start(itr)) -end -function gen_bitarray(::HasLength, itr) - n = length(itr) - B = BitArray(n) - return fill_bitarray_from_itr!(B, itr, start(itr)) -end - -gen_bitarray(::IsInfinite, itr) = throw(ArgumentError("infinite-size iterable used in BitArray constructor")) - -# The aux functions gen_bitarray_from_itr and fill_bitarray_from_itr! both -# use a Vector{Bool} cache for performance reasons - -function gen_bitarray_from_itr(itr, st) - B = empty!(BitArray(bitcache_size)) - C = Vector{Bool}(bitcache_size) - Bc = B.chunks - ind = 1 - cind = 1 - while !done(itr, st) - x, st = next(itr, st) - @inbounds C[ind] = x - ind += 1 - if ind > bitcache_size - resize!(B, length(B) + bitcache_size) - dumpbitcache(Bc, cind, C) - cind += bitcache_chunks - ind = 1 - end - end - if ind > 1 - @inbounds C[ind:bitcache_size] = false - resize!(B, length(B) + ind - 1) - dumpbitcache(Bc, cind, C) - end - return B -end - -function fill_bitarray_from_itr!(B::BitArray, itr, st) - n = length(B) - C = Vector{Bool}(bitcache_size) - Bc = B.chunks - ind = 1 - cind = 1 - while !done(itr, st) - x, st = next(itr, st) - @inbounds C[ind] = x - ind += 1 - if ind > bitcache_size - dumpbitcache(Bc, cind, C) - cind += bitcache_chunks - ind = 1 - end - end - if ind > 1 - @inbounds C[ind:bitcache_size] = false - dumpbitcache(Bc, cind, C) - end - return B -end - - -## Indexing: getindex ## - -@inline function unsafe_bitgetindex(Bc::Vector{UInt64}, i::Int) - i1, i2 = get_chunks_id(i) - u = UInt64(1) << i2 - @inbounds r = (Bc[i1] & u) != 0 - return r -end - -@inline function getindex(B::BitArray, i::Int) - @boundscheck checkbounds(B, i) - unsafe_bitgetindex(B.chunks, i) -end - -## Indexing: setindex! ## - -@inline function unsafe_bitsetindex!(Bc::Array{UInt64}, x::Bool, i::Int) - i1, i2 = get_chunks_id(i) - u = UInt64(1) << i2 - @inbounds begin - c = Bc[i1] - Bc[i1] = ifelse(x, c | u, c & ~u) - end -end - -@inline function setindex!(B::BitArray, x, i::Int) - @boundscheck checkbounds(B, i) - unsafe_bitsetindex!(B.chunks, convert(Bool, x), i) - return B -end - -indexoffset(i) = first(i)-1 -indexoffset(::Colon) = 0 - -@inline function setindex!(B::BitArray, x, J0::Union{Colon,UnitRange{Int}}) - I0 = to_indices(B, (J0,))[1] - @boundscheck checkbounds(B, I0) - y = Bool(x) - l0 = length(I0) - l0 == 0 && return B - f0 = indexoffset(I0)+1 - fill_chunks!(B.chunks, y, f0, l0) - return B -end - -# logical indexing - -# When indexing with a BitArray, we can operate whole chunks at a time for a ~100x gain -@inline function setindex!(B::BitArray, x, I::BitArray) - @boundscheck checkbounds(B, I) - _unsafe_setindex!(B, x, I) -end -function _unsafe_setindex!(B::BitArray, x, I::BitArray) - y = convert(Bool, x) - Bc = B.chunks - Ic = I.chunks - length(Bc) == length(Ic) || throw_boundserror(B, I) - @inbounds if y - for i = 1:length(Bc) - Bc[i] |= Ic[i] - end - else - for i = 1:length(Bc) - Bc[i] &= ~Ic[i] - end - end - return B -end - -# Assigning an array of bools is more complicated, but we can still do some -# work on chunks by combining X and I 64 bits at a time to improve perf by ~40% -@inline function setindex!(B::BitArray, X::AbstractArray, I::BitArray) - @boundscheck checkbounds(B, I) - _unsafe_setindex!(B, X, I) -end -function _unsafe_setindex!(B::BitArray, X::AbstractArray, I::BitArray) - Bc = B.chunks - Ic = I.chunks - length(Bc) == length(Ic) || throw_boundserror(B, I) - lc = length(Bc) - lx = length(X) - last_chunk_len = _mod64(length(B)-1)+1 - - c = 1 - for i = 1:lc - @inbounds Imsk = Ic[i] - @inbounds C = Bc[i] - u = UInt64(1) - for j = 1:(i < lc ? 64 : last_chunk_len) - if Imsk & u != 0 - lx < c && throw_setindex_mismatch(X, c) - @inbounds x = convert(Bool, X[c]) - C = ifelse(x, C | u, C & ~u) - c += 1 - end - u <<= 1 - end - @inbounds Bc[i] = C - end - if length(X) != c-1 - throw_setindex_mismatch(X, c-1) - end - return B -end - -## Dequeue functionality ## - -function push!(B::BitVector, item) - # convert first so we don't grow the bitarray if the assignment won't work - item = convert(Bool, item) - - Bc = B.chunks - - l = _mod64(length(B)) - if l == 0 - ccall(:jl_array_grow_end, Void, (Any, UInt), Bc, 1) - Bc[end] = UInt64(0) - end - B.len += 1 - if item - B[end] = true - end - return B -end - -function append!(B::BitVector, items::BitVector) - n0 = length(B) - n1 = length(items) - n1 == 0 && return B - Bc = B.chunks - k0 = length(Bc) - k1 = num_bit_chunks(n0 + n1) - if k1 > k0 - ccall(:jl_array_grow_end, Void, (Any, UInt), Bc, k1 - k0) - Bc[end] = UInt64(0) - end - B.len += n1 - copy_chunks!(Bc, n0+1, items.chunks, 1, n1) - return B -end - -append!(B::BitVector, items::AbstractVector{Bool}) = append!(B, BitArray(items)) -append!(A::Vector{Bool}, items::BitVector) = append!(A, Array(items)) - -function prepend!(B::BitVector, items::BitVector) - n0 = length(B) - n1 = length(items) - n1 == 0 && return B - Bc = B.chunks - k0 = length(Bc) - k1 = num_bit_chunks(n0 + n1) - if k1 > k0 - ccall(:jl_array_grow_end, Void, (Any, UInt), Bc, k1 - k0) - Bc[end] = UInt64(0) - end - B.len += n1 - copy_chunks!(Bc, 1 + n1, Bc, 1, n0) - copy_chunks!(Bc, 1, items.chunks, 1, n1) - return B -end - -prepend!(B::BitVector, items::AbstractVector{Bool}) = prepend!(B, BitArray(items)) -prepend!(A::Vector{Bool}, items::BitVector) = prepend!(A, Array(items)) - -function sizehint!(B::BitVector, sz::Integer) - ccall(:jl_array_sizehint, Void, (Any, UInt), B.chunks, num_bit_chunks(sz)) - return B -end - -function resize!(B::BitVector, n::Integer) - n0 = length(B) - n == n0 && return B - n >= 0 || throw(BoundsError(B, n)) - if n < n0 - deleteat!(B, n+1:n0) - return B - end - Bc = B.chunks - k0 = length(Bc) - k1 = num_bit_chunks(Int(n)) - if k1 > k0 - ccall(:jl_array_grow_end, Void, (Any, UInt), Bc, k1 - k0) - Bc[end] = UInt64(0) - end - B.len = n - return B -end - -function pop!(B::BitVector) - isempty(B) && throw(ArgumentError("argument must not be empty")) - item = B[end] - B[end] = false - - l = _mod64(length(B)) - l == 1 && ccall(:jl_array_del_end, Void, (Any, UInt), B.chunks, 1) - B.len -= 1 - - return item -end - -function unshift!(B::BitVector, item) - item = convert(Bool, item) - - Bc = B.chunks - - l = _mod64(length(B)) - if l == 0 - ccall(:jl_array_grow_end, Void, (Any, UInt), Bc, 1) - Bc[end] = UInt64(0) - end - B.len += 1 - if B.len == 1 - Bc[1] = item - return B - end - for i = length(Bc) : -1 : 2 - Bc[i] = (Bc[i] << 1) | (Bc[i-1] >>> 63) - end - Bc[1] = UInt64(item) | (Bc[1] << 1) - return B -end - -function shift!(B::BitVector) - isempty(B) && throw(ArgumentError("argument must not be empty")) - @inbounds begin - item = B[1] - - Bc = B.chunks - - for i = 1 : length(Bc) - 1 - Bc[i] = (Bc[i] >>> 1) | (Bc[i+1] << 63) - end - - l = _mod64(length(B)) - if l == 1 - ccall(:jl_array_del_end, Void, (Any, UInt), Bc, 1) - else - Bc[end] >>>= 1 - end - B.len -= 1 - end - - return item -end - -function insert!(B::BitVector, i::Integer, item) - n = length(B) - 1 <= i <= n+1 || throw(BoundsError(B, i)) - item = convert(Bool, item) - - Bc = B.chunks - - k, j = get_chunks_id(i) - - l = _mod64(length(B)) - if l == 0 - ccall(:jl_array_grow_end, Void, (Any, UInt), Bc, 1) - Bc[end] = UInt64(0) - end - B.len += 1 - - for t = length(Bc) : -1 : k + 1 - Bc[t] = (Bc[t] << 1) | (Bc[t - 1] >>> 63) - end - - msk_aft = (_msk64 << j) - msk_bef = ~msk_aft - Bc[k] = (msk_bef & Bc[k]) | ((msk_aft & Bc[k]) << 1) - B[i] = item - B -end - -function _deleteat!(B::BitVector, i::Integer) - k, j = get_chunks_id(i) - - msk_bef = _msk64 >>> (63 - j) - msk_aft = ~msk_bef - msk_bef >>>= 1 - - Bc = B.chunks - - @inbounds begin - Bc[k] = (msk_bef & Bc[k]) | ((msk_aft & Bc[k]) >> 1) - if length(Bc) > k - Bc[k] |= (Bc[k + 1] << 63) - end - - for t = k + 1 : length(Bc) - 1 - Bc[t] = (Bc[t] >>> 1) | (Bc[t + 1] << 63) - end - - l = _mod64(length(B)) - - if l == 1 - ccall(:jl_array_del_end, Void, (Any, UInt), Bc, 1) - elseif length(Bc) > k - Bc[end] >>>= 1 - end - end - - B.len -= 1 - - return B -end - -function deleteat!(B::BitVector, i::Integer) - n = length(B) - 1 <= i <= n || throw(BoundsError(B, i)) - - return _deleteat!(B, i) -end - -function deleteat!(B::BitVector, r::UnitRange{Int}) - n = length(B) - i_f = first(r) - i_l = last(r) - 1 <= i_f || throw(BoundsError(B, i_f)) - i_l <= n || throw(BoundsError(B, n+1)) - - Bc = B.chunks - new_l = length(B) - length(r) - delta_k = num_bit_chunks(new_l) - length(Bc) - - copy_chunks!(Bc, i_f, Bc, i_l+1, n-i_l) - - delta_k < 0 && ccall(:jl_array_del_end, Void, (Any, UInt), Bc, -delta_k) - - B.len = new_l - - if new_l > 0 - Bc[end] &= _msk_end(new_l) - end - - return B -end - -function deleteat!(B::BitVector, inds) - n = new_l = length(B) - s = start(inds) - done(inds, s) && return B - - Bc = B.chunks - - (p, s) = next(inds, s) - q = p+1 - new_l -= 1 - while !done(inds, s) - (i,s) = next(inds, s) - if !(q <= i <= n) - i < q && throw(ArgumentError("indices must be unique and sorted")) - throw(BoundsError(B, i)) - end - new_l -= 1 - if i > q - copy_chunks!(Bc, p, Bc, q, i-q) - p += i-q - end - q = i+1 - end - - q <= n && copy_chunks!(Bc, p, Bc, q, n-q+1) - - delta_k = num_bit_chunks(new_l) - length(Bc) - delta_k < 0 && ccall(:jl_array_del_end, Void, (Any, UInt), Bc, -delta_k) - - B.len = new_l - - if new_l > 0 - Bc[end] &= _msk_end(new_l) - end - - return B -end - -function splice!(B::BitVector, i::Integer) - n = length(B) - 1 <= i <= n || throw(BoundsError(B, i)) - - v = B[i] # TODO: change to a copy if/when subscripting becomes an ArrayView - _deleteat!(B, i) - return v -end - -const _default_bit_splice = BitVector(0) - -function splice!(B::BitVector, r::Union{UnitRange{Int}, Integer}, ins::AbstractArray = _default_bit_splice) - n = length(B) - i_f = first(r) - i_l = last(r) - - 1 <= i_f <= n+1 || throw(BoundsError(B, i_f)) - i_l <= n || throw(BoundsError(B, n+1)) - - Bins = convert(BitArray, ins) - - if (i_f > n) - append!(B, Bins) - return BitVector(0) - end - - v = B[r] # TODO: change to a copy if/when subscripting becomes an ArrayView - - Bc = B.chunks - - lins = length(Bins) - ldel = length(r) - - new_l = length(B) + lins - ldel - delta_k = num_bit_chunks(new_l) - length(Bc) - - delta_k > 0 && ccall(:jl_array_grow_end, Void, (Any, UInt), Bc, delta_k) - - copy_chunks!(Bc, i_f+lins, Bc, i_l+1, n-i_l) - copy_chunks!(Bc, i_f, Bins.chunks, 1, lins) - - delta_k < 0 && ccall(:jl_array_del_end, Void, (Any, UInt), Bc, -delta_k) - - B.len = new_l - - if new_l > 0 - Bc[end] &= _msk_end(new_l) - end - - return v -end - -function splice!(B::BitVector, r::Union{UnitRange{Int}, Integer}, ins) - Bins = BitArray(length(ins)) - i = 1 - for x in ins - Bins[i] = Bool(x) - i += 1 - end - return splice!(B, r, Bins) -end - - -function empty!(B::BitVector) - ccall(:jl_array_del_end, Void, (Any, UInt), B.chunks, length(B.chunks)) - B.len = 0 - return B -end - -## Unary operators ## - -function (-)(B::BitArray) - A = zeros(Int, size(B)) - l = length(B) - l == 0 && return A - Bc = B.chunks - ind = 1 - for i = 1:length(Bc)-1 - u = UInt64(1) - c = Bc[i] - for j = 1:64 - if c & u != 0 - A[ind] = -1 - end - ind += 1 - u <<= 1 - end - end - u = UInt64(1) - c = Bc[end] - for j = 0:_mod64(l-1) - if c & u != 0 - A[ind] = -1 - end - ind += 1 - u <<= 1 - end - return A -end -broadcast(::typeof(sign), B::BitArray) = copy(B) - -function broadcast(::typeof(~), B::BitArray) - C = similar(B) - Bc = B.chunks - if !isempty(Bc) - Cc = C.chunks - for i = 1:length(Bc) - Cc[i] = ~Bc[i] - end - Cc[end] &= _msk_end(B) - end - return C -end - -""" - flipbits!(B::BitArray{N}) -> BitArray{N} - -Performs a bitwise not operation on `B`. See [`~`](@ref). - -# Example -```jldoctest -julia> A = trues(2,2) -2×2 BitArray{2}: - true true - true true - -julia> flipbits!(A) -2×2 BitArray{2}: - false false - false false -``` -""" -function flipbits!(B::BitArray) - Bc = B.chunks - @inbounds if !isempty(Bc) - for i = 1:length(Bc) - Bc[i] = ~Bc[i] - end - Bc[end] &= _msk_end(B) - end - return B -end - - -## Binary arithmetic operators ## - -for f in (:+, :-) - @eval function ($f)(A::BitArray, B::BitArray) - r = Array{Int}(promote_shape(size(A), size(B))) - ai = start(A) - bi = start(B) - ri = 1 - while !done(A, ai) - a, ai = next(A, ai) - b, bi = next(B, bi) - @inbounds r[ri] = ($f)(a, b) - ri += 1 - end - return r - end -end - -for f in (:/, :\) - @eval begin - ($f)(A::Union{BitMatrix,BitVector}, B::Union{BitMatrix,BitVector}) = ($f)(Array(A), Array(B)) - end -end -(/)(B::BitArray, x::Number) = (/)(Array(B), x) -(/)(x::Number, B::BitArray) = (/)(x, Array(B)) - -# broadcast specializations for &, |, and xor/⊻ -broadcast(::typeof(&), B::BitArray, x::Bool) = x ? copy(B) : falses(size(B)) -broadcast(::typeof(&), x::Bool, B::BitArray) = broadcast(&, B, x) -broadcast(::typeof(|), B::BitArray, x::Bool) = x ? trues(size(B)) : copy(B) -broadcast(::typeof(|), x::Bool, B::BitArray) = broadcast(|, B, x) -broadcast(::typeof(xor), B::BitArray, x::Bool) = x ? .~B : copy(B) -broadcast(::typeof(xor), x::Bool, B::BitArray) = broadcast(xor, B, x) -for f in (:&, :|, :xor) - @eval begin - function broadcast(::typeof($f), A::BitArray, B::BitArray) - F = BitArray(promote_shape(size(A),size(B))...) - Fc = F.chunks - Ac = A.chunks - Bc = B.chunks - (isempty(Ac) || isempty(Bc)) && return F - for i = 1:length(Fc) - Fc[i] = ($f)(Ac[i], Bc[i]) - end - Fc[end] &= _msk_end(F) - return F - end - broadcast(::typeof($f), A::DenseArray{Bool}, B::BitArray) = broadcast($f, BitArray(A), B) - broadcast(::typeof($f), B::BitArray, A::DenseArray{Bool}) = broadcast($f, B, BitArray(A)) - end -end - - -## promotion to complex ## - -# TODO? - -## comparison operators ## - -function (==)(A::BitArray, B::BitArray) - size(A) != size(B) && return false - return A.chunks == B.chunks -end - - -## Data movement ## - -# preserve some special behavior -function slicedim(A::BitVector, d::Integer, i::Integer) - d >= 1 || throw(ArgumentError("dimension must be ≥ 1")) - if d > 1 - i == 1 || throw_boundserror(A, (:, ntuple(k->1,d-2)..., i)) - A[:] - else - fill!(BitArray{0}(), A[i]) # generic slicedim would return A[i] here - end -end - - -# TODO some of this could be optimized - -function flipdim(A::BitArray, d::Integer) - nd = ndims(A) - 1 ≤ d ≤ nd || throw(ArgumentError("dimension $d is not 1 ≤ $d ≤ $nd")) - sd = size(A, d) - sd == 1 && return copy(A) - - B = similar(A) - - nnd = 0 - for i = 1:nd - nnd += Int(size(A,i)==1 || i==d) - end - if nnd == nd - # flip along the only non-singleton dimension - for i = 1:sd - B[i] = A[sd+1-i] - end - return B - end - - d_in = size(A) - leading = d_in[1:(d-1)] - M = prod(leading) - N = length(A) - stride = M * sd - - if M == 1 - for j = 0:stride:(N-stride) - for i = 1:sd - ri = sd+1-i - B[j + ri] = A[j + i] - end - end - else - for i = 1:sd - ri = sd+1-i - for j=0:stride:(N-stride) - offs = j + 1 + (i-1)*M - boffs = j + 1 + (ri-1)*M - copy_chunks!(B.chunks, boffs, A.chunks, offs, M) - end - end - end - return B -end - -function reverse_bits(src::UInt64) - z = src - z = ((z >>> 1) & 0x5555555555555555) | ((z << 1) & 0xaaaaaaaaaaaaaaaa) - z = ((z >>> 2) & 0x3333333333333333) | ((z << 2) & 0xcccccccccccccccc) - z = ((z >>> 4) & 0x0f0f0f0f0f0f0f0f) | ((z << 4) & 0xf0f0f0f0f0f0f0f0) - z = ((z >>> 8) & 0x00ff00ff00ff00ff) | ((z << 8) & 0xff00ff00ff00ff00) - z = ((z >>> 16) & 0x0000ffff0000ffff) | ((z << 16) & 0xffff0000ffff0000) - return ((z >>> 32) & 0x00000000ffffffff) | ((z << 32) & 0xffffffff00000000) -end - -function reverse!(B::BitVector) - # Basic idea: each chunk is divided into two blocks of size k = n % 64, and - # h = 64 - k. Walk from either end (with indexes i and j) reversing chunks - # and separately ORing their two blocks into place. - # - # chunk 3 chunk 2 chunk 1 - # ┌───────────────┬───────┐┌───────────────┬───────┐┌───────────────┬───────┐ - # │000000000000000│ E ││ D │ C ││ B │ A │ - # └───────────────┴───────┘└───────────────┴───────┘└───────────────┴───────┘ - # k h k h k - # yielding; - # ┌───────────────┬───────┐┌───────────────┬───────┐┌───────────────┬───────┐ - # │000000000000000│ A' ││ B' │ C' ││ D' │ E' │ - # └───────────────┴───────┘└───────────────┴───────┘└───────────────┴───────┘ - - n = length(B) - n == 0 && return B - - k = _mod64(n+63) + 1 - h = 64 - k - - i, j = 0, length(B.chunks) - u = UInt64(0) - v = reverse_bits(B.chunks[j]) - B.chunks[j] = 0 - @inbounds while true - i += 1 - if i == j - break - end - u = reverse_bits(B.chunks[i]) - B.chunks[i] = 0 - B.chunks[j] |= u >>> h - B.chunks[i] |= v >>> h - - j -= 1 - if i == j - break - end - v = reverse_bits(B.chunks[j]) - B.chunks[j] = 0 - B.chunks[i] |= v << k - B.chunks[j] |= u << k - end - - if isodd(length(B.chunks)) - B.chunks[i] |= v >>> h - else - B.chunks[i] |= u << k - end - - return B -end - -reverse(v::BitVector) = reverse!(copy(v)) - - -function (<<)(B::BitVector, i::UInt) - n = length(B) - i == 0 && return copy(B) - A = falses(n) - i < n && copy_chunks!(A.chunks, 1, B.chunks, i+1, n-i) - return A -end - -function (>>>)(B::BitVector, i::UInt) - n = length(B) - i == 0 && return copy(B) - A = falses(n) - i < n && copy_chunks!(A.chunks, i+1, B.chunks, 1, n-i) - return A -end - -""" - >>(B::BitVector, n) -> BitVector - -Right bit shift operator, `B >> n`. For `n >= 0`, the result is `B` -with elements shifted `n` positions forward, filling with `false` -values. If `n < 0`, elements are shifted backwards. Equivalent to -`B << -n`. - -## Example - -```jldoctest -julia> B = BitVector([true, false, true, false, false]) -5-element BitArray{1}: - true - false - true - false - false - -julia> B >> 1 -5-element BitArray{1}: - false - true - false - true - false - -julia> B >> -1 -5-element BitArray{1}: - false - true - false - false - false -``` -""" -(>>)(B::BitVector, i::Union{Int, UInt}) = B >>> i - -# signed integer version of shift operators with handling of negative values -""" - <<(B::BitVector, n) -> BitVector - -Left bit shift operator, `B << n`. For `n >= 0`, the result is `B` -with elements shifted `n` positions backwards, filling with `false` -values. If `n < 0`, elements are shifted forwards. Equivalent to -`B >> -n`. - -## Examples - -```jldoctest -julia> B = BitVector([true, false, true, false, false]) -5-element BitArray{1}: - true - false - true - false - false - -julia> B << 1 -5-element BitArray{1}: - false - true - false - false - false - -julia> B << -1 -5-element BitArray{1}: - false - true - false - true - false -``` -""" -(<<)(B::BitVector, i::Int) = (i >=0 ? B << unsigned(i) : B >> unsigned(-i)) - -""" - >>>(B::BitVector, n) -> BitVector - -Unsigned right bitshift operator, `B >>> n`. Equivalent to `B >> n`. See [`>>`](@ref) for -details and examples. -""" -(>>>)(B::BitVector, i::Int) = (i >=0 ? B >> unsigned(i) : B << unsigned(-i)) - -""" - rol!(dest::BitVector, src::BitVector, i::Integer) -> BitVector - -Performs a left rotation operation on `src` and puts the result into `dest`. -`i` controls how far to rotate the bits. -""" -function rol!(dest::BitVector, src::BitVector, i::Integer) - length(dest) == length(src) || throw(ArgumentError("destination and source should be of same size")) - n = length(dest) - i %= n - i == 0 && return (src === dest ? src : copy!(dest, src)) - i < 0 && return ror!(dest, src, -i) - Bc = (src === dest ? copy(src.chunks) : src.chunks) - copy_chunks!(dest.chunks, 1, Bc, i+1, n-i) - copy_chunks!(dest.chunks, n-i+1, Bc, 1, i) - return dest -end - -""" - rol!(B::BitVector, i::Integer) -> BitVector - -Performs a left rotation operation in-place on `B`. -`i` controls how far to rotate the bits. -""" -rol!(B::BitVector, i::Integer) = rol!(B, B, i) - -""" - rol(B::BitVector, i::Integer) -> BitVector - -Performs a left rotation operation, returning a new `BitVector`. -`i` controls how far to rotate the bits. -See also [`rol!`](@ref). - -# Examples -```jldoctest -julia> A = BitArray([true, true, false, false, true]) -5-element BitArray{1}: - true - true - false - false - true - -julia> rol(A,1) -5-element BitArray{1}: - true - false - false - true - true - -julia> rol(A,2) -5-element BitArray{1}: - false - false - true - true - true - -julia> rol(A,5) -5-element BitArray{1}: - true - true - false - false - true -``` -""" -rol(B::BitVector, i::Integer) = rol!(similar(B), B, i) - -""" - ror!(dest::BitVector, src::BitVector, i::Integer) -> BitVector - -Performs a right rotation operation on `src` and puts the result into `dest`. -`i` controls how far to rotate the bits. -""" -function ror!(dest::BitVector, src::BitVector, i::Integer) - length(dest) == length(src) || throw(ArgumentError("destination and source should be of same size")) - n = length(dest) - i %= n - i == 0 && return (src === dest ? src : copy!(dest, src)) - i < 0 && return rol!(dest, src, -i) - Bc = (src === dest ? copy(src.chunks) : src.chunks) - copy_chunks!(dest.chunks, i+1, Bc, 1, n-i) - copy_chunks!(dest.chunks, 1, Bc, n-i+1, i) - return dest -end - -""" - ror!(B::BitVector, i::Integer) -> BitVector - -Performs a right rotation operation in-place on `B`. -`i` controls how far to rotate the bits. -""" -ror!(B::BitVector, i::Integer) = ror!(B, B, i) - -""" - ror(B::BitVector, i::Integer) -> BitVector - -Performs a right rotation operation on `B`, returning a new `BitVector`. -`i` controls how far to rotate the bits. -See also [`ror!`](@ref). - -# Examples -```jldoctest -julia> A = BitArray([true, true, false, false, true]) -5-element BitArray{1}: - true - true - false - false - true - -julia> ror(A,1) -5-element BitArray{1}: - true - true - true - false - false - -julia> ror(A,2) -5-element BitArray{1}: - false - true - true - true - false - -julia> ror(A,5) -5-element BitArray{1}: - true - true - false - false - true -``` -""" -ror(B::BitVector, i::Integer) = ror!(similar(B), B, i) - -## countnz & find ## - -function countnz(B::BitArray) - n = 0 - Bc = B.chunks - @inbounds for i = 1:length(Bc) - n += count_ones(Bc[i]) - end - return n -end -count(B::BitArray) = countnz(B) - -# returns the index of the next non-zero element, or 0 if all zeros -function findnext(B::BitArray, start::Integer) - start > 0 || throw(BoundsError(B, start)) - start > length(B) && return 0 - - Bc = B.chunks - - chunk_start = _div64(start-1)+1 - within_chunk_start = _mod64(start-1) - mask = _msk64 << within_chunk_start - - @inbounds begin - if Bc[chunk_start] & mask != 0 - return (chunk_start-1) << 6 + trailing_zeros(Bc[chunk_start] & mask) + 1 - end - - for i = chunk_start+1:length(Bc) - if Bc[i] != 0 - return (i-1) << 6 + trailing_zeros(Bc[i]) + 1 - end - end - end - return 0 -end -#findfirst(B::BitArray) = findnext(B, 1) ## defined in array.jl - -# aux function: same as findnext(~B, start), but performed without temporaries -function findnextnot(B::BitArray, start::Integer) - start > 0 || throw(BoundsError(B, start)) - start > length(B) && return 0 - - Bc = B.chunks - l = length(Bc) - l == 0 && return 0 - - chunk_start = _div64(start-1)+1 - within_chunk_start = _mod64(start-1) - mask = ~(_msk64 << within_chunk_start) - - @inbounds if chunk_start < l - if Bc[chunk_start] | mask != _msk64 - return (chunk_start-1) << 6 + trailing_ones(Bc[chunk_start] | mask) + 1 - end - for i = chunk_start+1:l-1 - if Bc[i] != _msk64 - return (i-1) << 6 + trailing_ones(Bc[i]) + 1 - end - end - if Bc[l] != _msk_end(B) - return (l-1) << 6 + trailing_ones(Bc[l]) + 1 - end - elseif Bc[l] | mask != _msk_end(B) - return (l-1) << 6 + trailing_ones(Bc[l] | mask) + 1 - end - return 0 -end -findfirstnot(B::BitArray) = findnextnot(B,1) - -# returns the index of the first matching element -function findnext(B::BitArray, v, start::Integer) - v == false && return findnextnot(B, start) - v == true && return findnext(B, start) - return 0 -end -#findfirst(B::BitArray, v) = findnext(B, 1, v) ## defined in array.jl - -# returns the index of the first element for which the function returns true -function findnext(testf::Function, B::BitArray, start::Integer) - f0::Bool = testf(false) - f1::Bool = testf(true) - !f0 && f1 && return findnext(B, start) - f0 && !f1 && return findnextnot(B, start) - - start > 0 || throw(BoundsError(B, start)) - start > length(B) && return 0 - f0 && f1 && return Int(start) - return 0 # last case: !f0 && !f1 -end -#findfirst(testf::Function, B::BitArray) = findnext(testf, B, 1) ## defined in array.jl - -# returns the index of the previous non-zero element, or 0 if all zeros -function findprev(B::BitArray, start::Integer) - start > 0 || return 0 - start > length(B) && throw(BoundsError(B, start)) - - Bc = B.chunks - - chunk_start = _div64(start-1)+1 - mask = _msk_end(start) - - @inbounds begin - if Bc[chunk_start] & mask != 0 - return (chunk_start-1) << 6 + (64 - leading_zeros(Bc[chunk_start] & mask)) - end - - for i = (chunk_start-1):-1:1 - if Bc[i] != 0 - return (i-1) << 6 + (64 - leading_zeros(Bc[i])) - end - end - end - return 0 -end - -function findprevnot(B::BitArray, start::Integer) - start > 0 || return 0 - start > length(B) && throw(BoundsError(B, start)) - - Bc = B.chunks - - chunk_start = _div64(start-1)+1 - mask = ~_msk_end(start) - - @inbounds begin - if Bc[chunk_start] | mask != _msk64 - return (chunk_start-1) << 6 + (64 - leading_ones(Bc[chunk_start] | mask)) - end - - for i = chunk_start-1:-1:1 - if Bc[i] != _msk64 - return (i-1) << 6 + (64 - leading_ones(Bc[i])) - end - end - end - return 0 -end -findlastnot(B::BitArray) = findprevnot(B, length(B)) - -# returns the index of the previous matching element -function findprev(B::BitArray, v, start::Integer) - v == false && return findprevnot(B, start) - v == true && return findprev(B, start) - return 0 -end -#findlast(B::BitArray, v) = findprev(B, 1, v) ## defined in array.jl - -# returns the index of the previous element for which the function returns true -function findprev(testf::Function, B::BitArray, start::Integer) - f0::Bool = testf(false) - f1::Bool = testf(true) - !f0 && f1 && return findprev(B, start) - f0 && !f1 && return findprevnot(B, start) - - start > 0 || return 0 - start > length(B) && throw(BoundsError(B, start)) - f0 && f1 && return Int(start) - return 0 # last case: !f0 && !f1 -end -#findlast(testf::Function, B::BitArray) = findprev(testf, B, 1) ## defined in array.jl - -function find(B::BitArray) - l = length(B) - nnzB = countnz(B) - I = Vector{Int}(nnzB) - nnzB == 0 && return I - Bc = B.chunks - Bcount = 1 - Icount = 1 - for i = 1:length(Bc)-1 - u = UInt64(1) - c = Bc[i] - for j = 1:64 - if c & u != 0 - I[Icount] = Bcount - Icount += 1 - end - Bcount += 1 - u <<= 1 - end - end - u = UInt64(1) - c = Bc[end] - for j = 0:_mod64(l-1) - if c & u != 0 - I[Icount] = Bcount - Icount += 1 - end - Bcount += 1 - u <<= 1 - end - return I -end - -findn(B::BitVector) = find(B) - -function findn(B::BitMatrix) - nnzB = countnz(B) - I = Vector{Int}(nnzB) - J = Vector{Int}(nnzB) - count = 1 - for j = 1:size(B,2), i = 1:size(B,1) - if B[i,j] - I[count] = i - J[count] = j - count += 1 - end - end - return I, J -end - -function findnz(B::BitMatrix) - I, J = findn(B) - return I, J, trues(length(I)) -end - -## Reductions ## - -sum(A::BitArray, region) = reducedim(+, A, region) -sum(B::BitArray) = countnz(B) - -function all(B::BitArray) - isempty(B) && return true - Bc = B.chunks - @inbounds begin - for i = 1:length(Bc)-1 - Bc[i] == _msk64 || return false - end - Bc[end] == _msk_end(B) || return false - end - return true -end - -function any(B::BitArray) - isempty(B) && return false - Bc = B.chunks - @inbounds begin - for i = 1:length(Bc) - Bc[i] == 0 || return true - end - end - return false -end - -minimum(B::BitArray) = isempty(B) ? throw(ArgumentError("argument must be non-empty")) : all(B) -maximum(B::BitArray) = isempty(B) ? throw(ArgumentError("argument must be non-empty")) : any(B) - -## map over bitarrays ## - -# Specializing map is even more important for bitarrays than it is for generic -# arrays since there can be a 64x speedup by working at the level of Int64 -# instead of looping bit-by-bit. - -map(::Union{typeof(~), typeof(!)}, A::BitArray) = bit_map!(~, similar(A), A) -map(::typeof(zero), A::BitArray) = fill!(similar(A), false) -map(::typeof(one), A::BitArray) = fill!(similar(A), true) -map(::typeof(identity), A::BitArray) = copy(A) - -map!(::Union{typeof(~), typeof(!)}, dest::BitArray, A::BitArray) = bit_map!(~, dest, A) -map!(::typeof(zero), dest::BitArray, A::BitArray) = fill!(dest, false) -map!(::typeof(one), dest::BitArray, A::BitArray) = fill!(dest, true) -map!(::typeof(identity), dest::BitArray, A::BitArray) = copy!(dest, A) - -for (T, f) in ((:(Union{typeof(&), typeof(*), typeof(min)}), :(&)), - (:(Union{typeof(|), typeof(max)}), :(|)), - (:(Union{typeof(xor), typeof(!=)}), :xor), - (:(Union{typeof(>=), typeof(^)}), :((p, q) -> p | ~q)), - (:(typeof(<=)), :((p, q) -> ~p | q)), - (:(typeof(==)), :((p, q) -> ~xor(p, q))), - (:(typeof(<)), :((p, q) -> ~p & q)), - (:(typeof(>)), :((p, q) -> p & ~q))) - @eval map(::$T, A::BitArray, B::BitArray) = bit_map!($f, similar(A), A, B) - @eval map!(::$T, dest::BitArray, A::BitArray, B::BitArray) = bit_map!($f, dest, A, B) -end - -# If we were able to specialize the function to a known bitwise operation, -# map across the chunks. Otherwise, fall-back to the AbstractArray method that -# iterates bit-by-bit. -function bit_map!{F}(f::F, dest::BitArray, A::BitArray) - size(A) == size(dest) || throw(DimensionMismatch("sizes of dest and A must match")) - isempty(A) && return dest - destc = dest.chunks - Ac = A.chunks - for i = 1:(length(Ac)-1) - destc[i] = f(Ac[i]) - end - destc[end] = f(Ac[end]) & _msk_end(A) - dest -end -function bit_map!{F}(f::F, dest::BitArray, A::BitArray, B::BitArray) - size(A) == size(B) == size(dest) || throw(DimensionMismatch("sizes of dest, A, and B must all match")) - isempty(A) && return dest - destc = dest.chunks - Ac = A.chunks - Bc = B.chunks - for i = 1:(length(Ac)-1) - destc[i] = f(Ac[i], Bc[i]) - end - destc[end] = f(Ac[end], Bc[end]) & _msk_end(A) - dest -end - -## Filter ## - -function filter(f, Bs::BitArray) - boolmap::Array{Bool} = map(f, Bs) - Bs[boolmap] -end - - -## Concatenation ## - -function hcat(B::BitVector...) - height = length(B[1]) - for j = 2:length(B) - length(B[j]) == height || - throw(DimensionMismatch("dimensions must match")) - end - M = BitArray(height, length(B)) - for j = 1:length(B) - copy_chunks!(M.chunks, (height*(j-1))+1, B[j].chunks, 1, height) - end - return M -end - -function vcat(V::BitVector...) - n = 0 - for Vk in V - n += length(Vk) - end - B = BitArray(n) - j = 1 - for Vk in V - copy_chunks!(B.chunks, j, Vk.chunks, 1, length(Vk)) - j += length(Vk) - end - return B -end - -function hcat(A::Union{BitMatrix,BitVector}...) - nargs = length(A) - nrows = size(A[1], 1) - ncols = 0 - dense = true - for j = 1:nargs - Aj = A[j] - nd = ndims(Aj) - ncols += (nd==2 ? size(Aj,2) : 1) - size(Aj, 1) == nrows || - throw(DimensionMismatch("row lengths must match")) - end - - B = BitArray(nrows, ncols) - - pos = 1 - for k = 1:nargs - Ak = A[k] - n = length(Ak) - copy_chunks!(B.chunks, pos, Ak.chunks, 1, n) - pos += n - end - return B -end - -function vcat(A::BitMatrix...) - nargs = length(A) - nrows = sum(a->size(a, 1), A)::Int - ncols = size(A[1], 2) - for j = 2:nargs - size(A[j], 2) == ncols || - throw(DimensionMismatch("column lengths must match")) - end - B = BitArray(nrows, ncols) - Bc = B.chunks - nrowsA = [size(a, 1) for a in A] - Ac = [a.chunks for a in A] - pos_d = 1 - pos_s = ones(Int, nargs) - for j = 1:ncols, k = 1:nargs - copy_chunks!(Bc, pos_d, Ac[k], pos_s[k], nrowsA[k]) - pos_s[k] += nrowsA[k] - pos_d += nrowsA[k] - end - return B -end - -# general case, specialized for BitArrays and Integers -function cat(dims::Integer, X::Union{BitArray, Bool}...) - catdims = dims2cat(dims) - shape = cat_shape(catdims, (), map(cat_size, X)...) - A = falses(shape) - return _cat(A, shape, catdims, X...) -end - -# hvcat -> use fallbacks in abstractarray.jl - - -# BitArray I/O - -write(s::IO, B::BitArray) = write(s, B.chunks) -function read!(s::IO, B::BitArray) - n = length(B) - Bc = B.chunks - nc = length(read!(s, Bc)) - if length(Bc) > 0 && Bc[end] & _msk_end(n) ≠ Bc[end] - Bc[end] &= _msk_end(n) # ensure that the BitArray is not broken - throw(DimensionMismatch("read mismatch, found non-zero bits after BitArray length")) - end - return B -end - -sizeof(B::BitArray) = sizeof(B.chunks) diff --git a/julia-0.6.3/share/julia/base/bool.jl b/julia-0.6.3/share/julia/base/bool.jl deleted file mode 100644 index f2c48bb..0000000 --- a/julia-0.6.3/share/julia/base/bool.jl +++ /dev/null @@ -1,112 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -## boolean conversions ## - -convert(::Type{Bool}, x::Bool) = x -convert(::Type{Bool}, x::Float16) = x==0 ? false : x==1 ? true : throw(InexactError()) -convert(::Type{Bool}, x::Real) = x==0 ? false : x==1 ? true : throw(InexactError()) - -# promote Bool to any other numeric type -promote_rule(::Type{Bool}, ::Type{T}) where {T<:Number} = T - -typemin(::Type{Bool}) = false -typemax(::Type{Bool}) = true - -## boolean operations ## - -""" - !(x) - -Boolean not. - -```jldoctest -julia> !true -false - -julia> !false -true - -julia> .![true false true] -1×3 BitArray{2}: - false true false -``` -""" -function !(x::Bool) - ## We need a better heuristic to detect this automatically - @_pure_meta - return not_int(x) -end - -(~)(x::Bool) = !x -(&)(x::Bool, y::Bool) = and_int(x, y) -(|)(x::Bool, y::Bool) = or_int(x, y) - -""" - xor(x, y) - ⊻(x, y) - -Bitwise exclusive or of `x` and `y`. The infix operation -`a ⊻ b` is a synonym for `xor(a,b)`, and -`⊻` can be typed by tab-completing `\\xor` -or `\\veebar` in the Julia REPL. - -```jldoctest -julia> [true; true; false] .⊻ [true; false; false] -3-element BitArray{1}: - false - true - false -``` -""" -xor(x::Bool, y::Bool) = (x != y) - ->>(x::Bool, c::Unsigned) = Int(x) >> c -<<(x::Bool, c::Unsigned) = Int(x) << c ->>>(x::Bool, c::Unsigned) = Int(x) >>> c - ->>(x::Bool, c::Int) = Int(x) >> c -<<(x::Bool, c::Int) = Int(x) << c ->>>(x::Bool, c::Int) = Int(x) >>> c - ->>(x::Bool, c::Integer) = Int(x) >> c -<<(x::Bool, c::Integer) = Int(x) << c ->>>(x::Bool, c::Integer) = Int(x) >>> c - -signbit(x::Bool) = false -sign(x::Bool) = x -abs(x::Bool) = x -abs2(x::Bool) = x -iszero(x::Bool) = !x - -<(x::Bool, y::Bool) = y&!x -<=(x::Bool, y::Bool) = y|!x - -## do arithmetic as Int ## - -+(x::Bool) = Int(x) --(x::Bool) = -Int(x) - -+(x::Bool, y::Bool) = Int(x) + Int(y) --(x::Bool, y::Bool) = Int(x) - Int(y) -*(x::Bool, y::Bool) = x & y -^(x::Bool, y::Bool) = x | !y -^(x::Integer, y::Bool) = ifelse(y, x, one(x)) - -function +(x::Bool, y::T)::promote_type(Bool,T) where T<:AbstractFloat - return ifelse(x, oneunit(y) + y, y) -end -+(y::AbstractFloat, x::Bool) = x + y - -function *(x::Bool, y::T)::promote_type(Bool,T) where T<:Number - return ifelse(x, y, copysign(zero(y), y)) -end -function *(x::Bool, y::T)::promote_type(Bool,T) where T<:Unsigned - return ifelse(x, y, zero(y)) -end -*(y::Number, x::Bool) = x * y - -div(x::Bool, y::Bool) = y ? x : throw(DivideError()) -fld(x::Bool, y::Bool) = div(x,y) -cld(x::Bool, y::Bool) = div(x,y) -rem(x::Bool, y::Bool) = y ? false : throw(DivideError()) -mod(x::Bool, y::Bool) = rem(x,y) diff --git a/julia-0.6.3/share/julia/base/boot.jl b/julia-0.6.3/share/julia/base/boot.jl deleted file mode 100644 index 13c6cc1..0000000 --- a/julia-0.6.3/share/julia/base/boot.jl +++ /dev/null @@ -1,384 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -# commented-out definitions are implemented in C - -#abstract type Any <: Any end -#abstract type Type{T} end - -#abstract type Vararg{T} end - -#mutable struct Symbol -# #opaque -#end - -#mutable struct TypeName -# name::Symbol -#end - -#mutable struct DataType <: Type -# name::TypeName -# super::Type -# parameters::Tuple -# names::Tuple -# types::Tuple -# ctor -# instance -# size::Int32 -# abstract::Bool -# mutable::Bool -# pointerfree::Bool -#end - -#struct Union <: Type -# a -# b -#end - -#mutable struct TypeVar -# name::Symbol -# lb::Type -# ub::Type -#end - -#struct UnionAll -# var::TypeVar -# body -#end - -#struct Void -#end -#const nothing = Void() - -#abstract type AbstractArray{T,N} end -#abstract type DenseArray{T,N} <: AbstractArray{T,N} end - -#mutable struct Array{T,N} <: DenseArray{T,N} -#end - -#mutable struct Module -# name::Symbol -#end - -#mutable struct Method -#end - -#mutable struct MethodInstance -#end - -#mutable struct CodeInfo -#end - -#mutable struct TypeMapLevel -#end - -#mutable struct TypeMapEntry -#end - -#abstract type Ref{T} end -#primitive type Ptr{T} <: Ref{T} {32|64} end - -# types for the front end - -#mutable struct Expr -# head::Symbol -# args::Array{Any,1} -# typ::Any -#end - -#struct LineNumberNode -# line::Int -#end - -#struct LabelNode -# label::Int -#end - -#struct GotoNode -# label::Int -#end - -#struct QuoteNode -# value -#end - -#struct GlobalRef -# mod::Module -# name::Symbol -#end - -#mutable struct Task -# parent::Task -# storage::Any -# consumers -# started::Bool -# done::Bool -# runnable::Bool -#end - -export - # key types - Any, DataType, Vararg, ANY, NTuple, - Tuple, Type, UnionAll, TypeName, TypeVar, Union, Void, - SimpleVector, AbstractArray, DenseArray, - # special objects - Function, CodeInfo, Method, MethodTable, TypeMapEntry, TypeMapLevel, - Module, Symbol, Task, Array, WeakRef, VecElement, - # numeric types - Number, Real, Integer, Bool, Ref, Ptr, - AbstractFloat, Float16, Float32, Float64, - Signed, Int, Int8, Int16, Int32, Int64, Int128, - Unsigned, UInt, UInt8, UInt16, UInt32, UInt64, UInt128, - # string types - Char, DirectIndexString, AbstractString, String, IO, - # errors - ErrorException, BoundsError, DivideError, DomainError, Exception, InexactError, - InterruptException, OutOfMemoryError, ReadOnlyMemoryError, OverflowError, - StackOverflowError, SegmentationFault, UndefRefError, UndefVarError, TypeError, - # AST representation - Expr, GotoNode, LabelNode, LineNumberNode, QuoteNode, - GlobalRef, NewvarNode, SSAValue, Slot, SlotNumber, TypedSlot, - # object model functions - fieldtype, getfield, setfield!, nfields, throw, tuple, ===, isdefined, eval, - # sizeof # not exported, to avoid conflicting with Base.sizeof - # type reflection - issubtype, typeof, isa, typeassert, - # method reflection - applicable, invoke, - # constants - nothing, Main - -const AnyVector = Array{Any,1} - -abstract type Number end -abstract type Real <: Number end -abstract type AbstractFloat <: Real end -abstract type Integer <: Real end -abstract type Signed <: Integer end -abstract type Unsigned <: Integer end - -primitive type Float16 <: AbstractFloat 16 end -primitive type Float32 <: AbstractFloat 32 end -primitive type Float64 <: AbstractFloat 64 end - -primitive type Bool <: Integer 8 end -primitive type Char 32 end - -primitive type Int8 <: Signed 8 end -primitive type UInt8 <: Unsigned 8 end -primitive type Int16 <: Signed 16 end -primitive type UInt16 <: Unsigned 16 end -primitive type Int32 <: Signed 32 end -primitive type UInt32 <: Unsigned 32 end -primitive type Int64 <: Signed 64 end -primitive type UInt64 <: Unsigned 64 end -primitive type Int128 <: Signed 128 end -primitive type UInt128 <: Unsigned 128 end - -if Int === Int64 - const UInt = UInt64 -else - const UInt = UInt32 -end - -function Typeof end -(f::typeof(Typeof))(x::ANY) = isa(x,Type) ? Type{x} : typeof(x) - -abstract type Exception end -mutable struct ErrorException <: Exception - msg::AbstractString - ErrorException(msg::AbstractString) = new(msg) -end - -Expr(args::ANY...) = _expr(args...) - -macro _noinline_meta() - Expr(:meta, :noinline) -end - -struct BoundsError <: Exception - a::Any - i::Any - BoundsError() = new() - BoundsError(a::ANY) = (@_noinline_meta; new(a)) - BoundsError(a::ANY, i) = (@_noinline_meta; new(a,i)) -end -struct DivideError <: Exception end -struct DomainError <: Exception end -struct OverflowError <: Exception end -struct InexactError <: Exception end -struct OutOfMemoryError <: Exception end -struct ReadOnlyMemoryError<: Exception end -struct SegmentationFault <: Exception end -struct StackOverflowError <: Exception end -struct UndefRefError <: Exception end -struct UndefVarError <: Exception - var::Symbol -end -struct InterruptException <: Exception end -mutable struct TypeError <: Exception - func::Symbol - context::AbstractString - expected::Type - got -end - -abstract type DirectIndexString <: AbstractString end - -String(s::String) = s # no constructor yet - -# This should always be inlined -getptls() = ccall(:jl_get_ptls_states, Ptr{Void}, ()) - -include(fname::String) = ccall(:jl_load_, Any, (Any,), fname) - -eval(e::ANY) = eval(Main, e) -eval(m::Module, e::ANY) = ccall(:jl_toplevel_eval_in, Any, (Any, Any), m, e) - -kwfunc(f::ANY) = ccall(:jl_get_keyword_sorter, Any, (Any,), f) - -kwftype(t::ANY) = typeof(ccall(:jl_get_kwsorter, Any, (Any,), t)) - -mutable struct Box - contents::Any - Box(x::ANY) = new(x) - Box() = new() -end - -# constructors for built-in types - -mutable struct WeakRef - value - WeakRef() = WeakRef(nothing) - WeakRef(v::ANY) = ccall(:jl_gc_new_weakref_th, Ref{WeakRef}, - (Ptr{Void}, Any), getptls(), v) -end - -TypeVar(n::Symbol) = - ccall(:jl_new_typevar, Ref{TypeVar}, (Any, Any, Any), n, Union{}, Any) -TypeVar(n::Symbol, ub::ANY) = - ccall(:jl_new_typevar, Ref{TypeVar}, (Any, Any, Any), n, Union{}, ub) -TypeVar(n::Symbol, lb::ANY, ub::ANY) = - ccall(:jl_new_typevar, Ref{TypeVar}, (Any, Any, Any), n, lb, ub) - -UnionAll(v::TypeVar, t::ANY) = ccall(:jl_type_unionall, Any, (Any, Any), v, t) - -Void() = nothing - -(::Type{Tuple{}})() = () # Tuple{}() - -struct VecElement{T} - value::T - VecElement{T}(value::T) where {T} = new(value) # disable converting constructor in Core -end -VecElement(arg::T) where {T} = VecElement{T}(arg) - -# used by lowering of splicing unquote -splicedexpr(hd::Symbol, args::Array{Any,1}) = (e=Expr(hd); e.args=args; e) - -_new(typ::Symbol, argty::Symbol) = eval(:((::Type{$typ})(n::$argty) = $(Expr(:new, typ, :n)))) -_new(:LabelNode, :Int) -_new(:GotoNode, :Int) -_new(:NewvarNode, :SlotNumber) -_new(:QuoteNode, :ANY) -_new(:SSAValue, :Int) -eval(:((::Type{LineNumberNode})(l::Int) = $(Expr(:new, :LineNumberNode, :l)))) -eval(:((::Type{GlobalRef})(m::Module, s::Symbol) = $(Expr(:new, :GlobalRef, :m, :s)))) -eval(:((::Type{SlotNumber})(n::Int) = $(Expr(:new, :SlotNumber, :n)))) -eval(:((::Type{TypedSlot})(n::Int, t::ANY) = $(Expr(:new, :TypedSlot, :n, :t)))) - -Module(name::Symbol=:anonymous, std_imports::Bool=true) = ccall(:jl_f_new_module, Ref{Module}, (Any, Bool), name, std_imports) - -Task(f::ANY) = ccall(:jl_new_task, Ref{Task}, (Any, Int), f, 0) - -# simple convert for use by constructors of types in Core -# note that there is no actual conversion defined here, -# so the methods and ccall's in Core aren't permitted to use convert -convert(::Type{Any}, x::ANY) = x -convert(::Type{T}, x::T) where {T} = x -cconvert(::Type{T}, x) where {T} = convert(T, x) -unsafe_convert(::Type{T}, x::T) where {T} = x - -const NTuple{N,T} = Tuple{Vararg{T,N}} - - -# primitive array constructors -Array{T,N}(d::NTuple{N,Int}) where {T,N} = - ccall(:jl_new_array, Array{T,N}, (Any, Any), Array{T,N}, d) -Array{T,1}(d::NTuple{1,Int}) where {T} = Array{T,1}(getfield(d,1)) -Array{T,2}(d::NTuple{2,Int}) where {T} = Array{T,2}(getfield(d,1), getfield(d,2)) -Array{T,3}(d::NTuple{3,Int}) where {T} = Array{T,3}(getfield(d,1), getfield(d,2), getfield(d,3)) -Array{T,N}(d::Vararg{Int,N}) where {T,N} = ccall(:jl_new_array, Array{T,N}, (Any, Any), Array{T,N}, d) -Array{T,1}(m::Int) where {T} = ccall(:jl_alloc_array_1d, Array{T,1}, (Any, Int), Array{T,1}, m) -Array{T,2}(m::Int, n::Int) where {T} = - ccall(:jl_alloc_array_2d, Array{T,2}, (Any, Int, Int), Array{T,2}, m, n) -Array{T,3}(m::Int, n::Int, o::Int) where {T} = - ccall(:jl_alloc_array_3d, Array{T,3}, (Any, Int, Int, Int), Array{T,3}, m, n, o) - -Array{T}(d::NTuple{N,Int}) where {T,N} = Array{T,N}(d) -Array{T}(m::Int) where {T} = Array{T,1}(m) -Array{T}(m::Int, n::Int) where {T} = Array{T,2}(m, n) -Array{T}(m::Int, n::Int, o::Int) where {T} = Array{T,3}(m, n, o) - -Array{T,1}() where {T} = Array{T,1}(0) - -# primitive Symbol constructors -function Symbol(s::String) - return ccall(:jl_symbol_n, Ref{Symbol}, (Ptr{UInt8}, Int), - ccall(:jl_string_ptr, Ptr{UInt8}, (Any,), s), - sizeof(s)) -end -function Symbol(a::Array{UInt8,1}) - return ccall(:jl_symbol_n, Ref{Symbol}, (Ptr{UInt8}, Int), - ccall(:jl_array_ptr, Ptr{UInt8}, (Any,), a), - Intrinsics.arraylen(a)) -end -Symbol(s::Symbol) = s - -# docsystem basics -macro doc(x...) - atdoc(x...) -end -macro __doc__(x) - Expr(:escape, Expr(:block, Expr(:meta, :doc), x)) -end -macro doc_str(s) - Expr(:escape, s) -end -atdoc = (str, expr) -> Expr(:escape, expr) -atdoc!(λ) = global atdoc = λ - - -# simple stand-alone print definitions for debugging -abstract type IO end -mutable struct CoreSTDOUT <: IO end -mutable struct CoreSTDERR <: IO end -const STDOUT = CoreSTDOUT() -const STDERR = CoreSTDERR() -io_pointer(::CoreSTDOUT) = Intrinsics.pointerref(Intrinsics.cglobal(:jl_uv_stdout, Ptr{Void}), 1, 1) -io_pointer(::CoreSTDERR) = Intrinsics.pointerref(Intrinsics.cglobal(:jl_uv_stderr, Ptr{Void}), 1, 1) - -unsafe_write(io::IO, x::Ptr{UInt8}, nb::UInt) = - (ccall(:jl_uv_puts, Void, (Ptr{Void}, Ptr{UInt8}, UInt), io_pointer(io), x, nb); nb) -unsafe_write(io::IO, x::Ptr{UInt8}, nb::Int) = - (ccall(:jl_uv_puts, Void, (Ptr{Void}, Ptr{UInt8}, Int), io_pointer(io), x, nb); nb) -write(io::IO, x::UInt8) = - (ccall(:jl_uv_putb, Void, (Ptr{Void}, UInt8), io_pointer(io), x); 1) -function write(io::IO, x::String) - nb = sizeof(x) - unsafe_write(io, ccall(:jl_string_ptr, Ptr{UInt8}, (Any,), x), nb) - return nb -end - -show(io::IO, x::ANY) = ccall(:jl_static_show, Void, (Ptr{Void}, Any), io_pointer(io), x) -print(io::IO, x::Char) = ccall(:jl_uv_putc, Void, (Ptr{Void}, Char), io_pointer(io), x) -print(io::IO, x::String) = (write(io, x); nothing) -print(io::IO, x::ANY) = show(io, x) -print(io::IO, x::ANY, a::ANY...) = (print(io, x); print(io, a...)) -println(io::IO) = (write(io, 0x0a); nothing) # 0x0a = '\n' -println(io::IO, x::ANY...) = (print(io, x...); println(io)) - -show(a::ANY) = show(STDOUT, a) -print(a::ANY...) = print(STDOUT, a...) -println(a::ANY...) = println(STDOUT, a...) - -ccall(:jl_set_istopmod, Void, (Bool,), true) diff --git a/julia-0.6.3/share/julia/base/broadcast.jl b/julia-0.6.3/share/julia/base/broadcast.jl deleted file mode 100644 index a07f419..0000000 --- a/julia-0.6.3/share/julia/base/broadcast.jl +++ /dev/null @@ -1,631 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -module Broadcast - -using Base.Cartesian -using Base: linearindices, tail, OneTo, to_shape, - _msk_end, unsafe_bitgetindex, bitcache_chunks, bitcache_size, dumpbitcache, - nullable_returntype, null_safe_op, hasvalue, isoperator -import Base: broadcast, broadcast! -export broadcast_getindex, broadcast_setindex!, dotview, @__dot__ - -const ScalarType = Union{Type{Any}, Type{Nullable}} - -## Broadcasting utilities ## -# fallbacks for some special cases -@inline broadcast(f, x::Number...) = f(x...) -@inline broadcast(f, t::NTuple{N,Any}, ts::Vararg{NTuple{N,Any}}) where {N} = map(f, t, ts...) -broadcast!(::typeof(identity), x::Array{T,N}, y::Array{S,N}) where {T,S,N} = - size(x) == size(y) ? copy!(x, y) : broadcast_c!(identity, Array, Array, x, y) - -# special cases for "X .= ..." (broadcast!) assignments -broadcast!(::typeof(identity), X::AbstractArray, x::Number) = fill!(X, x) -broadcast!(f, X::AbstractArray, x::Number...) = (@inbounds for I in eachindex(X); X[I] = f(x...); end; X) - -# logic for deciding the resulting container type -_containertype(::Type) = Any -_containertype(::Type{<:Ptr}) = Any -_containertype(::Type{<:Tuple}) = Tuple -_containertype(::Type{<:Ref}) = Array -_containertype(::Type{<:AbstractArray}) = Array -_containertype(::Type{<:Nullable}) = Nullable -containertype(x) = _containertype(typeof(x)) -containertype(ct1, ct2) = promote_containertype(containertype(ct1), containertype(ct2)) -@inline containertype(ct1, ct2, cts...) = promote_containertype(containertype(ct1), containertype(ct2, cts...)) - -promote_containertype(::Type{Array}, ::Type{Array}) = Array -promote_containertype(::Type{Array}, ct) = Array -promote_containertype(ct, ::Type{Array}) = Array -promote_containertype(::Type{Tuple}, ::ScalarType) = Tuple -promote_containertype(::ScalarType, ::Type{Tuple}) = Tuple -promote_containertype(::Type{Any}, ::Type{Nullable}) = Nullable -promote_containertype(::Type{Nullable}, ::Type{Any}) = Nullable -promote_containertype(::Type{T}, ::Type{T}) where {T} = T - -## Calculate the broadcast indices of the arguments, or error if incompatible -# array inputs -broadcast_indices() = () -broadcast_indices(A) = broadcast_indices(containertype(A), A) -broadcast_indices(::ScalarType, A) = () -broadcast_indices(::Type{Tuple}, A) = (OneTo(length(A)),) -broadcast_indices(::Type{Array}, A::Ref) = () -broadcast_indices(::Type{Array}, A) = indices(A) -@inline broadcast_indices(A, B...) = broadcast_shape((), broadcast_indices(A), map(broadcast_indices, B)...) - -# shape (i.e., tuple-of-indices) inputs -broadcast_shape(shape::Tuple) = shape -@inline broadcast_shape(shape::Tuple, shape1::Tuple, shapes::Tuple...) = broadcast_shape(_bcs((), shape, shape1), shapes...) -# _bcs consolidates two shapes into a single output shape -_bcs(out, ::Tuple{}, ::Tuple{}) = out -@inline _bcs(out, ::Tuple{}, newshape) = _bcs((out..., newshape[1]), (), tail(newshape)) -@inline _bcs(out, shape, ::Tuple{}) = _bcs((out..., shape[1]), tail(shape), ()) -@inline function _bcs(out, shape, newshape) - newout = _bcs1(shape[1], newshape[1]) - _bcs((out..., newout), tail(shape), tail(newshape)) -end -# _bcs1 handles the logic for a single dimension -_bcs1(a::Integer, b::Integer) = a == 1 ? b : (b == 1 ? a : (a == b ? a : throw(DimensionMismatch("arrays could not be broadcast to a common size")))) -_bcs1(a::Integer, b) = a == 1 ? b : (first(b) == 1 && last(b) == a ? b : throw(DimensionMismatch("arrays could not be broadcast to a common size"))) -_bcs1(a, b::Integer) = _bcs1(b, a) -_bcs1(a, b) = _bcsm(b, a) ? b : (_bcsm(a, b) ? a : throw(DimensionMismatch("arrays could not be broadcast to a common size"))) -# _bcsm tests whether the second index is consistent with the first -_bcsm(a, b) = a == b || length(b) == 1 -_bcsm(a, b::Number) = b == 1 -_bcsm(a::Number, b::Number) = a == b || b == 1 - -## Check that all arguments are broadcast compatible with shape -# comparing one input against a shape -check_broadcast_shape(shp) = nothing -check_broadcast_shape(shp, ::Tuple{}) = nothing -check_broadcast_shape(::Tuple{}, ::Tuple{}) = nothing -check_broadcast_shape(::Tuple{}, Ashp::Tuple) = throw(DimensionMismatch("cannot broadcast array to have fewer dimensions")) -function check_broadcast_shape(shp, Ashp::Tuple) - _bcsm(shp[1], Ashp[1]) || throw(DimensionMismatch("array could not be broadcast to match destination")) - check_broadcast_shape(tail(shp), tail(Ashp)) -end -check_broadcast_indices(shp, A) = check_broadcast_shape(shp, broadcast_indices(A)) -# comparing many inputs -@inline function check_broadcast_indices(shp, A, As...) - check_broadcast_indices(shp, A) - check_broadcast_indices(shp, As...) -end - -## Indexing manipulations - -# newindex(I, keep, Idefault) replaces a CartesianIndex `I` with something that -# is appropriate for a particular broadcast array/scalar. `keep` is a -# NTuple{N,Bool}, where keep[d] == true means that one should preserve -# I[d]; if false, replace it with Idefault[d]. -@inline newindex(I::CartesianIndex, keep, Idefault) = CartesianIndex(_newindex(I.I, keep, Idefault)) -@inline _newindex(I, keep, Idefault) = - (ifelse(keep[1], I[1], Idefault[1]), _newindex(tail(I), tail(keep), tail(Idefault))...) -@inline _newindex(I, keep::Tuple{}, Idefault) = () # truncate if keep is shorter than I - -# newindexer(shape, A) generates `keep` and `Idefault` (for use by -# `newindex` above) for a particular array `A`, given the -# broadcast_indices `shape` -# `keep` is equivalent to map(==, indices(A), shape) (but see #17126) -@inline newindexer(shape, A) = shapeindexer(shape, broadcast_indices(A)) -@inline shapeindexer(shape, indsA::Tuple{}) = (), () -@inline function shapeindexer(shape, indsA::Tuple) - ind1 = indsA[1] - keep, Idefault = shapeindexer(tail(shape), tail(indsA)) - (shape[1] == ind1, keep...), (first(ind1), Idefault...) -end - -# Equivalent to map(x->newindexer(shape, x), As) (but see #17126) -map_newindexer(shape, ::Tuple{}) = (), () -@inline function map_newindexer(shape, As) - A1 = As[1] - keeps, Idefaults = map_newindexer(shape, tail(As)) - keep, Idefault = newindexer(shape, A1) - (keep, keeps...), (Idefault, Idefaults...) -end -@inline function map_newindexer(shape, A, Bs) - keeps, Idefaults = map_newindexer(shape, Bs) - keep, Idefault = newindexer(shape, A) - (keep, keeps...), (Idefault, Idefaults...) -end - -Base.@propagate_inbounds _broadcast_getindex(A, I) = _broadcast_getindex(containertype(A), A, I) -# `(x,)`, where `x` is a scalar, broadcasts the same way as `[x]` or `x` -Base.@propagate_inbounds _broadcast_getindex(::Type{Tuple}, A::Tuple{Any}, I) = A[1] -Base.@propagate_inbounds _broadcast_getindex(::Type{Array}, A::Ref, I) = A[] -Base.@propagate_inbounds _broadcast_getindex(::ScalarType, A, I) = A -Base.@propagate_inbounds _broadcast_getindex(::Any, A, I) = A[I] - -## Broadcasting core -# nargs encodes the number of As arguments (which matches the number -# of keeps). The first two type parameters are to ensure specialization. -@generated function _broadcast!(f, B::AbstractArray, keeps::K, Idefaults::ID, A::AT, Bs::BT, ::Type{Val{N}}, iter) where {K,ID,AT,BT,N} - nargs = N + 1 - quote - $(Expr(:meta, :inline)) - # destructure the keeps and As tuples - A_1 = A - @nexprs $N i->(A_{i+1} = Bs[i]) - @nexprs $nargs i->(keep_i = keeps[i]) - @nexprs $nargs i->(Idefault_i = Idefaults[i]) - @simd for I in iter - # reverse-broadcast the indices - @nexprs $nargs i->(I_i = newindex(I, keep_i, Idefault_i)) - # extract array values - @nexprs $nargs i->(@inbounds val_i = _broadcast_getindex(A_i, I_i)) - # call the function and store the result - result = @ncall $nargs f val - @inbounds B[I] = result - end - end -end - -# For BitArray outputs, we cache the result in a "small" Vector{Bool}, -# and then copy in chunks into the output -@generated function _broadcast!(f, B::BitArray, keeps::K, Idefaults::ID, A::AT, Bs::BT, ::Type{Val{N}}, iter) where {K,ID,AT,BT,N} - nargs = N + 1 - quote - $(Expr(:meta, :inline)) - # destructure the keeps and As tuples - A_1 = A - @nexprs $N i->(A_{i+1} = Bs[i]) - @nexprs $nargs i->(keep_i = keeps[i]) - @nexprs $nargs i->(Idefault_i = Idefaults[i]) - C = Vector{Bool}(bitcache_size) - Bc = B.chunks - ind = 1 - cind = 1 - @simd for I in iter - # reverse-broadcast the indices - @nexprs $nargs i->(I_i = newindex(I, keep_i, Idefault_i)) - # extract array values - @nexprs $nargs i->(@inbounds val_i = _broadcast_getindex(A_i, I_i)) - # call the function and store the result - @inbounds C[ind] = @ncall $nargs f val - ind += 1 - if ind > bitcache_size - dumpbitcache(Bc, cind, C) - cind += bitcache_chunks - ind = 1 - end - end - if ind > 1 - @inbounds C[ind:bitcache_size] = false - dumpbitcache(Bc, cind, C) - end - end -end - -""" - broadcast!(f, dest, As...) - -Like [`broadcast`](@ref), but store the result of -`broadcast(f, As...)` in the `dest` array. -Note that `dest` is only used to store the result, and does not supply -arguments to `f` unless it is also listed in the `As`, -as in `broadcast!(f, A, A, B)` to perform `A[:] = broadcast(f, A, B)`. -""" -@inline broadcast!(f, C::AbstractArray, A, Bs::Vararg{Any,N}) where {N} = - broadcast_c!(f, containertype(C), containertype(A, Bs...), C, A, Bs...) -@inline function broadcast_c!(f, ::Type, ::Type, C, A, Bs::Vararg{Any,N}) where N - shape = indices(C) - @boundscheck check_broadcast_indices(shape, A, Bs...) - keeps, Idefaults = map_newindexer(shape, A, Bs) - iter = CartesianRange(shape) - _broadcast!(f, C, keeps, Idefaults, A, Bs, Val{N}, iter) - return C -end - -# broadcast with computed element type -@generated function _broadcast!(f, B::AbstractArray, keeps::K, Idefaults::ID, As::AT, ::Type{Val{nargs}}, iter, st, count) where {K,ID,AT,nargs} - quote - $(Expr(:meta, :noinline)) - # destructure the keeps and As tuples - @nexprs $nargs i->(A_i = As[i]) - @nexprs $nargs i->(keep_i = keeps[i]) - @nexprs $nargs i->(Idefault_i = Idefaults[i]) - while !done(iter, st) - I, st = next(iter, st) - # reverse-broadcast the indices - @nexprs $nargs i->(I_i = newindex(I, keep_i, Idefault_i)) - # extract array values - @nexprs $nargs i->(@inbounds val_i = _broadcast_getindex(A_i, I_i)) - # call the function - V = @ncall $nargs f val - S = typeof(V) - # store the result - if S <: eltype(B) - @inbounds B[I] = V - else - R = typejoin(eltype(B), S) - new = similar(B, R) - for II in Iterators.take(iter, count) - new[II] = B[II] - end - new[I] = V - return _broadcast!(f, new, keeps, Idefaults, As, Val{nargs}, iter, st, count+1) - end - count += 1 - end - return B - end -end - -# broadcast methods that dispatch on the type found by inference -function broadcast_t(f, ::Type{Any}, shape, iter, As...) - nargs = length(As) - keeps, Idefaults = map_newindexer(shape, As) - st = start(iter) - I, st = next(iter, st) - val = f([ _broadcast_getindex(As[i], newindex(I, keeps[i], Idefaults[i])) for i=1:nargs ]...) - if val isa Bool - B = similar(BitArray, shape) - else - B = similar(Array{typeof(val)}, shape) - end - B[I] = val - return _broadcast!(f, B, keeps, Idefaults, As, Val{nargs}, iter, st, 1) -end -@inline function broadcast_t(f, T, shape, iter, A, Bs::Vararg{Any,N}) where N - C = similar(Array{T}, shape) - keeps, Idefaults = map_newindexer(shape, A, Bs) - _broadcast!(f, C, keeps, Idefaults, A, Bs, Val{N}, iter) - return C -end - -# default to BitArray for broadcast operations producing Bool, to save 8x space -# in the common case where this is used for logical array indexing; in -# performance-critical cases where Array{Bool} is desired, one can always -# use broadcast! instead. -@inline function broadcast_t(f, ::Type{Bool}, shape, iter, A, Bs::Vararg{Any,N}) where N - C = similar(BitArray, shape) - keeps, Idefaults = map_newindexer(shape, A, Bs) - _broadcast!(f, C, keeps, Idefaults, A, Bs, Val{N}, iter) - return C -end - -maptoTuple(f) = Tuple{} -maptoTuple(f, a, b...) = Tuple{f(a), maptoTuple(f, b...).types...} - -# An element type satisfying for all A: -# broadcast_getindex( -# containertype(A), -# A, broadcast_indices(A) -# )::_broadcast_getindex_eltype(A) -_broadcast_getindex_eltype(A) = _broadcast_getindex_eltype(containertype(A), A) -_broadcast_getindex_eltype(::ScalarType, T::Type) = Type{T} -_broadcast_getindex_eltype(::ScalarType, A) = typeof(A) -_broadcast_getindex_eltype(::Any, A) = eltype(A) # Tuple, Array, etc. - -# An element type satisfying for all A: -# unsafe_get(A)::unsafe_get_eltype(A) -_unsafe_get_eltype(x::Nullable) = eltype(x) -_unsafe_get_eltype(T::Type) = Type{T} -_unsafe_get_eltype(x) = typeof(x) - -# Inferred eltype of result of broadcast(f, xs...) -_broadcast_eltype(f, A, As...) = - Base._return_type(f, maptoTuple(_broadcast_getindex_eltype, A, As...)) -_nullable_eltype(f, A, As...) = - Base._return_type(f, maptoTuple(_unsafe_get_eltype, A, As...)) - -# broadcast methods that dispatch on the type of the final container -@inline function broadcast_c(f, ::Type{Array}, A, Bs...) - T = _broadcast_eltype(f, A, Bs...) - shape = broadcast_indices(A, Bs...) - iter = CartesianRange(shape) - if isleaftype(T) - return broadcast_t(f, T, shape, iter, A, Bs...) - end - if isempty(iter) - return similar(Array{T}, shape) - end - return broadcast_t(f, Any, shape, iter, A, Bs...) -end -@inline function broadcast_c(f, ::Type{Nullable}, a...) - nonnull = all(hasvalue, a) - S = _nullable_eltype(f, a...) - if isleaftype(S) && null_safe_op(f, maptoTuple(_unsafe_get_eltype, - a...).types...) - Nullable{S}(f(map(unsafe_get, a)...), nonnull) - else - if nonnull - Nullable(f(map(unsafe_get, a)...)) - else - Nullable{nullable_returntype(S)}() - end - end -end -@inline broadcast_c(f, ::Type{Any}, a...) = f(a...) -@inline broadcast_c(f, ::Type{Tuple}, A, Bs...) = - tuplebroadcast(f, tuplebroadcast_maxtuple(A, Bs...), A, Bs...) -@inline tuplebroadcast(f, ::NTuple{N,Any}, As...) where {N} = - ntuple(k -> f(tuplebroadcast_getargs(As, k)...), Val{N}) -@inline tuplebroadcast(f, ::NTuple{N,Any}, ::Type{T}, As...) where {N,T} = - ntuple(k -> f(T, tuplebroadcast_getargs(As, k)...), Val{N}) -# When the result of broadcast is a tuple it can only come from mixing n-tuples -# of the same length with scalars and 1-tuples. So, in order to have a -# type-stable broadcast, we need to find a tuple of maximum length (except when -# there are only scalars, empty tuples and 1-tuples, in which case the -# returned value will be an empty tuple). -# The following methods compare broadcast arguments pairwise to determine the -# length of the final tuple. -tuplebroadcast_maxtuple(A, B) = - _tuplebroadcast_maxtuple(containertype(A), containertype(B), A, B) -@inline tuplebroadcast_maxtuple(A, Bs...) = - tuplebroadcast_maxtuple(A, tuplebroadcast_maxtuple(Bs...)) -tuplebroadcast_maxtuple(A::NTuple{N,Any}, ::NTuple{N,Any}...) where {N} = A -# Here we use the containertype trait to easier disambiguate between methods -_tuplebroadcast_maxtuple(::Any, ::Any, A, B) = (nothing,) -_tuplebroadcast_maxtuple(::Type{Tuple}, ::Any, A, B) = A -_tuplebroadcast_maxtuple(::Any, ::Type{Tuple}, A, B) = B -_tuplebroadcast_maxtuple(::Type{Tuple}, ::Type{Tuple}, A, B::Tuple{Any}) = A -_tuplebroadcast_maxtuple(::Type{Tuple}, ::Type{Tuple}, A::Tuple{Any}, B) = B -_tuplebroadcast_maxtuple(::Type{Tuple}, ::Type{Tuple}, A::Tuple{Any}, ::Tuple{Any}) = A -_tuplebroadcast_maxtuple(::Type{Tuple}, ::Type{Tuple}, A, B) = - throw(DimensionMismatch("tuples could not be broadcast to a common size")) -tuplebroadcast_getargs(::Tuple{}, k) = () -@inline tuplebroadcast_getargs(As, k) = - (_broadcast_getindex(first(As), k), tuplebroadcast_getargs(tail(As), k)...) - -""" - broadcast(f, As...) - -Broadcasts the arrays, tuples, `Ref`s, nullables, and/or scalars `As` to a -container of the appropriate type and dimensions. In this context, anything -that is not a subtype of `AbstractArray`, `Ref` (except for `Ptr`s), `Tuple`, -or `Nullable` is considered a scalar. The resulting container is established by -the following rules: - - - If all the arguments are scalars, it returns a scalar. - - If the arguments are tuples and zero or more scalars, it returns a tuple. - - If the arguments contain at least one array or `Ref`, it returns an array - (expanding singleton dimensions), and treats `Ref`s as 0-dimensional arrays, - and tuples as 1-dimensional arrays. - -The following additional rule applies to `Nullable` arguments: If there is at -least one `Nullable`, and all the arguments are scalars or `Nullable`, it -returns a `Nullable` treating `Nullable`s as "containers". - -A special syntax exists for broadcasting: `f.(args...)` is equivalent to -`broadcast(f, args...)`, and nested `f.(g.(args...))` calls are fused into a -single broadcast loop. - -```jldoctest -julia> A = [1, 2, 3, 4, 5] -5-element Array{Int64,1}: - 1 - 2 - 3 - 4 - 5 - -julia> B = [1 2; 3 4; 5 6; 7 8; 9 10] -5×2 Array{Int64,2}: - 1 2 - 3 4 - 5 6 - 7 8 - 9 10 - -julia> broadcast(+, A, B) -5×2 Array{Int64,2}: - 2 3 - 5 6 - 8 9 - 11 12 - 14 15 - -julia> parse.(Int, ["1", "2"]) -2-element Array{Int64,1}: - 1 - 2 - -julia> abs.((1, -2)) -(1, 2) - -julia> broadcast(+, 1.0, (0, -2.0)) -(1.0, -1.0) - -julia> broadcast(+, 1.0, (0, -2.0), Ref(1)) -2-element Array{Float64,1}: - 2.0 - 0.0 - -julia> (+).([[0,2], [1,3]], Ref{Vector{Int}}([1,-1])) -2-element Array{Array{Int64,1},1}: - [1, 1] - [2, 2] - -julia> string.(("one","two","three","four"), ": ", 1:4) -4-element Array{String,1}: - "one: 1" - "two: 2" - "three: 3" - "four: 4" - -julia> Nullable("X") .* "Y" -Nullable{String}("XY") - -julia> broadcast(/, 1.0, Nullable(2.0)) -Nullable{Float64}(0.5) - -julia> (1 + im) ./ Nullable{Int}() -Nullable{Complex{Float64}}() -``` -""" -@inline broadcast(f, A, Bs...) = broadcast_c(f, containertype(A, Bs...), A, Bs...) - -""" - broadcast_getindex(A, inds...) - -Broadcasts the `inds` arrays to a common size like [`broadcast`](@ref) -and returns an array of the results `A[ks...]`, -where `ks` goes over the positions in the broadcast result `A`. - -```jldoctest -julia> A = [1, 2, 3, 4, 5] -5-element Array{Int64,1}: - 1 - 2 - 3 - 4 - 5 - -julia> B = [1 2; 3 4; 5 6; 7 8; 9 10] -5×2 Array{Int64,2}: - 1 2 - 3 4 - 5 6 - 7 8 - 9 10 - -julia> C = broadcast(+,A,B) -5×2 Array{Int64,2}: - 2 3 - 5 6 - 8 9 - 11 12 - 14 15 - -julia> broadcast_getindex(C,[1,2,10]) -3-element Array{Int64,1}: - 2 - 5 - 15 -``` -""" -broadcast_getindex(src::AbstractArray, I::AbstractArray...) = broadcast_getindex!(similar(Array{eltype(src)}, broadcast_indices(I...)), src, I...) -@generated function broadcast_getindex!(dest::AbstractArray, src::AbstractArray, I::AbstractArray...) - N = length(I) - Isplat = Expr[:(I[$d]) for d = 1:N] - quote - @nexprs $N d->(I_d = I[d]) - check_broadcast_indices(indices(dest), $(Isplat...)) # unnecessary if this function is never called directly - checkbounds(src, $(Isplat...)) - @nexprs $N d->(@nexprs $N k->(Ibcast_d_k = indices(I_k, d) == OneTo(1))) - @nloops $N i dest d->(@nexprs $N k->(j_d_k = Ibcast_d_k ? 1 : i_d)) begin - @nexprs $N k->(@inbounds J_k = @nref $N I_k d->j_d_k) - @inbounds (@nref $N dest i) = (@nref $N src J) - end - dest - end -end - -""" - broadcast_setindex!(A, X, inds...) - -Broadcasts the `X` and `inds` arrays to a common size and stores the value from each -position in `X` at the indices in `A` given by the same positions in `inds`. -""" -@generated function broadcast_setindex!(A::AbstractArray, x, I::AbstractArray...) - N = length(I) - Isplat = Expr[:(I[$d]) for d = 1:N] - quote - @nexprs $N d->(I_d = I[d]) - checkbounds(A, $(Isplat...)) - shape = broadcast_indices($(Isplat...)) - @nextract $N shape d->(length(shape) < d ? OneTo(1) : shape[d]) - @nexprs $N d->(@nexprs $N k->(Ibcast_d_k = indices(I_k, d) == 1:1)) - if !isa(x, AbstractArray) - xA = convert(eltype(A), x) - @nloops $N i d->shape_d d->(@nexprs $N k->(j_d_k = Ibcast_d_k ? 1 : i_d)) begin - @nexprs $N k->(@inbounds J_k = @nref $N I_k d->j_d_k) - @inbounds (@nref $N A J) = xA - end - else - X = x - @nexprs $N d->(shapelen_d = length(shape_d)) - @ncall $N Base.setindex_shape_check X shapelen - Xstate = start(X) - @inbounds @nloops $N i d->shape_d d->(@nexprs $N k->(j_d_k = Ibcast_d_k ? 1 : i_d)) begin - @nexprs $N k->(J_k = @nref $N I_k d->j_d_k) - x_el, Xstate = next(X, Xstate) - (@nref $N A J) = x_el - end - end - A - end -end - -############################################################ - -# x[...] .= f.(y...) ---> broadcast!(f, dotview(x, ...), y...). -# The dotview function defaults to getindex, but we override it in -# a few cases to get the expected in-place behavior without affecting -# explicit calls to view. (All of this can go away if slices -# are changed to generate views by default.) - -Base.@propagate_inbounds dotview(args...) = getindex(args...) -Base.@propagate_inbounds dotview(A::AbstractArray, args...) = view(A, args...) -Base.@propagate_inbounds dotview(A::AbstractArray{<:AbstractArray}, args::Integer...) = getindex(A, args...) - - -############################################################ -# The parser turns @. into a call to the __dot__ macro, -# which converts all function calls and assignments into -# broadcasting "dot" calls/assignments: - -dottable(x) = false # avoid dotting spliced objects (e.g. view calls inserted by @view) -dottable(x::Symbol) = !isoperator(x) || first(string(x)) != '.' || x == :.. # don't add dots to dot operators -dottable(x::Expr) = x.head != :$ -undot(x) = x -function undot(x::Expr) - if x.head == :.= - Expr(:(=), x.args...) - elseif x.head == :block # occurs in for x=..., y=... - Expr(:block, map(undot, x.args)...) - else - x - end -end -__dot__(x) = x -function __dot__(x::Expr) - dotargs = map(__dot__, x.args) - if x.head == :call && dottable(x.args[1]) - Expr(:., dotargs[1], Expr(:tuple, dotargs[2:end]...)) - elseif x.head == :$ - x.args[1] - elseif x.head == :let # don't add dots to "let x=... assignments - Expr(:let, dotargs[1], map(undot, dotargs[2:end])...) - elseif x.head == :for # don't add dots to for x=... assignments - Expr(:for, undot(dotargs[1]), dotargs[2]) - elseif (x.head == :(=) || x.head == :function || x.head == :macro) && - Meta.isexpr(x.args[1], :call) # function or macro definition - Expr(x.head, x.args[1], dotargs[2]) - else - head = string(x.head) - if last(head) == '=' && first(head) != '.' - Expr(Symbol('.',head), dotargs...) - else - Expr(x.head, dotargs...) - end - end -end -""" - @. expr - -Convert every function call or operator in `expr` into a "dot call" -(e.g. convert `f(x)` to `f.(x)`), and convert every assignment in `expr` -to a "dot assignment" (e.g. convert `+=` to `.+=`). - -If you want to *avoid* adding dots for selected function calls in -`expr`, splice those function calls in with `\$`. For example, -`@. sqrt(abs(\$sort(x)))` is equivalent to `sqrt.(abs.(sort(x)))` -(no dot for `sort`). - -(`@.` is equivalent to a call to `@__dot__`.) - -```jldoctest -julia> x = 1.0:3.0; y = similar(x); - -julia> @. y = x + 3 * sin(x) -3-element Array{Float64,1}: - 3.52441 - 4.72789 - 3.42336 -``` -""" -macro __dot__(x) - esc(__dot__(x)) -end - -end # module diff --git a/julia-0.6.3/share/julia/base/c.jl b/julia-0.6.3/share/julia/base/c.jl deleted file mode 100644 index 405c7e5..0000000 --- a/julia-0.6.3/share/julia/base/c.jl +++ /dev/null @@ -1,399 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -# definitions related to C interface - -import Core.Intrinsics: cglobal, bitcast - -""" - cfunction(function::Function, ReturnType::Type, ArgumentTypes::Type) - -Generate C-callable function pointer from Julia function. Type annotation of the return -value in the callback function is a must for situations where Julia cannot infer the return -type automatically. - -# Examples -```julia-repl -julia> function foo(x::Int, y::Int) - return x + y - end - -julia> cfunction(foo, Int, Tuple{Int,Int}) -Ptr{Void} @0x000000001b82fcd0 -``` -""" -cfunction(f, r, a) = ccall(:jl_function_ptr, Ptr{Void}, (Any, Any, Any), f, r, a) - -if ccall(:jl_is_char_signed, Ref{Bool}, ()) - const Cchar = Int8 -else - const Cchar = UInt8 -end -""" - Cchar - -Equivalent to the native `char` c-type. -""" -Cchar - -if is_windows() - const Clong = Int32 - const Culong = UInt32 - const Cwchar_t = UInt16 -else - const Clong = Int - const Culong = UInt - const Cwchar_t = Int32 -end - -""" - Clong - -Equivalent to the native `signed long` c-type. -""" -Clong - -""" - Culong - -Equivalent to the native `unsigned long` c-type. -""" -Culong - -""" - Cwchar_t - -Equivalent to the native `wchar_t` c-type ([`Int32`](@ref)). -""" -Cwchar_t - -if !is_windows() - const sizeof_mode_t = ccall(:jl_sizeof_mode_t, Cint, ()) - if sizeof_mode_t == 2 - const Cmode_t = Int16 - elseif sizeof_mode_t == 4 - const Cmode_t = Int32 - elseif sizeof_mode_t == 8 - const Cmode_t = Int64 - end -end - -# construction from typed pointers -convert(::Type{Cstring}, p::Ptr{<:Union{Int8,UInt8}}) = bitcast(Cstring, p) -convert(::Type{Cwstring}, p::Ptr{Cwchar_t}) = bitcast(Cwstring, p) -convert(::Type{Ptr{T}}, p::Cstring) where {T<:Union{Int8,UInt8}} = bitcast(Ptr{T}, p) -convert(::Type{Ptr{Cwchar_t}}, p::Cwstring) = bitcast(Ptr{Cwchar_t}, p) - -# construction from untyped pointers -convert(::Type{T}, p::Ptr{Void}) where {T<:Union{Cstring,Cwstring}} = bitcast(T, p) - -pointer(p::Cstring) = convert(Ptr{UInt8}, p) -pointer(p::Cwstring) = convert(Ptr{Cwchar_t}, p) - -# comparisons against pointers (mainly to support `cstr==C_NULL`) -==(x::Union{Cstring,Cwstring}, y::Ptr) = pointer(x) == y -==(x::Ptr, y::Union{Cstring,Cwstring}) = x == pointer(y) - -unsafe_string(s::Cstring) = unsafe_string(convert(Ptr{UInt8}, s)) - -# convert strings to String etc. to pass as pointers -cconvert(::Type{Cstring}, s::String) = s -cconvert(::Type{Cstring}, s::AbstractString) = - cconvert(Cstring, String(s)::String) - -function cconvert(::Type{Cwstring}, s::AbstractString) - v = transcode(Cwchar_t, Vector{UInt8}(String(s))) - !isempty(v) && v[end] == 0 || push!(v, 0) - return v -end - -eltype(::Type{Cstring}) = UInt8 -eltype(::Type{Cwstring}) = Cwchar_t - -containsnul(p::Ptr, len) = - C_NULL != ccall(:memchr, Ptr{Cchar}, (Ptr{Cchar}, Cint, Csize_t), p, 0, len) -containsnul(s::String) = containsnul(unsafe_convert(Ptr{Cchar}, s), sizeof(s)) -containsnul(s::AbstractString) = '\0' in s - -function unsafe_convert(::Type{Cstring}, s::Union{String,Vector{UInt8}}) - p = unsafe_convert(Ptr{Cchar}, s) - containsnul(p, sizeof(s)) && - throw(ArgumentError("embedded NULs are not allowed in C strings: $(repr(s))")) - return Cstring(p) -end - -function unsafe_convert(::Type{Cwstring}, v::Vector{Cwchar_t}) - for i = 1:length(v)-1 - v[i] == 0 && - throw(ArgumentError("embedded NULs are not allowed in C strings: $(repr(v))")) - end - v[end] == 0 || - throw(ArgumentError("C string data must be NUL terminated: $(repr(v))")) - p = unsafe_convert(Ptr{Cwchar_t}, v) - return Cwstring(p) -end - -# symbols are guaranteed not to contain embedded NUL -convert(::Type{Cstring}, s::Symbol) = Cstring(unsafe_convert(Ptr{Cchar}, s)) - -if is_windows() -""" - Base.cwstring(s) - -Converts a string `s` to a NUL-terminated `Vector{Cwchar_t}`, suitable for passing to C -functions expecting a `Ptr{Cwchar_t}`. The main advantage of using this over the implicit -conversion provided by `Cwstring` is if the function is called multiple times with the -same argument. - -This is only available on Windows. -""" -function cwstring(s::AbstractString) - bytes = Vector{UInt8}(String(s)) - 0 in bytes && throw(ArgumentError("embedded NULs are not allowed in C strings: $(repr(s))")) - return push!(transcode(UInt16, bytes), 0) -end -end - -# transcoding between data in UTF-8 and UTF-16 for Windows APIs, -# and also UTF-32 for APIs using Cwchar_t on other platforms. - -""" - transcode(T, src) - -Convert string data between Unicode encodings. `src` is either a -`String` or a `Vector{UIntXX}` of UTF-XX code units, where -`XX` is 8, 16, or 32. `T` indicates the encoding of the return value: -`String` to return a (UTF-8 encoded) `String` or `UIntXX` -to return a `Vector{UIntXX}` of UTF-`XX` data. (The alias `Cwchar_t` -can also be used as the integer type, for converting `wchar_t*` strings -used by external C libraries.) - -The `transcode` function succeeds as long as the input data can be -reasonably represented in the target encoding; it always succeeds for -conversions between UTF-XX encodings, even for invalid Unicode data. - -Only conversion to/from UTF-8 is currently supported. -""" -function transcode end - -transcode(::Type{T}, src::Vector{T}) where {T<:Union{UInt8,UInt16,UInt32,Int32}} = src -transcode(::Type{T}, src::String) where {T<:Union{Int32,UInt32}} = T[T(c) for c in src] -transcode(::Type{T}, src::Vector{UInt8}) where {T<:Union{Int32,UInt32}} = transcode(T, String(src)) -function transcode(::Type{UInt8}, src::Vector{<:Union{Int32,UInt32}}) - buf = IOBuffer() - for c in src; print(buf, Char(c)); end - take!(buf) -end -transcode(::Type{String}, src::String) = src -transcode(T, src::String) = transcode(T, Vector{UInt8}(src)) -transcode(::Type{String}, src) = String(transcode(UInt8, src)) - -function transcode(::Type{UInt16}, src::Vector{UInt8}) - dst = UInt16[] - i, n = 1, length(src) - n > 0 || return dst - sizehint!(dst, 2n) - a = src[1] - while true - if i < n && -64 <= a % Int8 <= -12 # multi-byte character - b = src[i += 1] - if -64 <= (b % Int8) || a == 0xf4 && 0x8f < b - # invalid UTF-8 (non-continuation or too-high code point) - push!(dst, a) - a = b; continue - elseif a < 0xe0 # 2-byte UTF-8 - push!(dst, xor(0x3080, UInt16(a) << 6, b)) - elseif i < n # 3/4-byte character - c = src[i += 1] - if -64 <= (c % Int8) # invalid UTF-8 (non-continuation) - push!(dst, a, b) - a = c; continue - elseif a < 0xf0 # 3-byte UTF-8 - push!(dst, xor(0x2080, UInt16(a) << 12, UInt16(b) << 6, c)) - elseif i < n - d = src[i += 1] - if -64 <= (d % Int8) # invalid UTF-8 (non-continuation) - push!(dst, a, b, c) - a = d; continue - elseif a == 0xf0 && b < 0x90 # overlong encoding - push!(dst, xor(0x2080, UInt16(b) << 12, UInt16(c) << 6, d)) - else # 4-byte UTF-8 - push!(dst, 0xe5b8 + (UInt16(a) << 8) + (UInt16(b) << 2) + (c >> 4), - xor(0xdc80, UInt16(c & 0xf) << 6, d)) - end - else # too short - push!(dst, a, b, c) - break - end - else # too short - push!(dst, a, b) - break - end - else # ASCII or invalid UTF-8 (continuation byte or too-high code point) - push!(dst, a) - end - i < n || break - a = src[i += 1] - end - return dst -end - -function transcode(::Type{UInt8}, src::Vector{UInt16}) - n = length(src) - n == 0 && return UInt8[] - - # Precompute m = sizeof(dst). This involves annoying duplication - # of the loop over the src array. However, this is not just an - # optimization: it is problematic for security reasons to grow - # dst dynamically, because Base.winprompt uses this function to - # convert passwords to UTF-8 and we don't want to make unintentional - # copies of the password data. - a = src[1] - i, m = 1, 0 - while true - if a < 0x80 - m += 1 - elseif a < 0x800 # 2-byte UTF-8 - m += 2 - elseif a & 0xfc00 == 0xd800 && i < length(src) - b = src[i += 1] - if (b & 0xfc00) == 0xdc00 # 2-unit UTF-16 sequence => 4-byte UTF-8 - m += 4 - else - m += 3 - a = b; continue - end - else - # 1-unit high UTF-16 or unpaired high surrogate - # either way, encode as 3-byte UTF-8 code point - m += 3 - end - i < n || break - a = src[i += 1] - end - - dst = StringVector(m) - a = src[1] - i, j = 1, 0 - while true - if a < 0x80 # ASCII - dst[j += 1] = a % UInt8 - elseif a < 0x800 # 2-byte UTF-8 - dst[j += 1] = 0xc0 | ((a >> 6) % UInt8) - dst[j += 1] = 0x80 | ((a % UInt8) & 0x3f) - elseif a & 0xfc00 == 0xd800 && i < n - b = src[i += 1] - if (b & 0xfc00) == 0xdc00 - # 2-unit UTF-16 sequence => 4-byte UTF-8 - a += 0x2840 - dst[j += 1] = 0xf0 | ((a >> 8) % UInt8) - dst[j += 1] = 0x80 | ((a % UInt8) >> 2) - dst[j += 1] = xor(0xf0, ((a % UInt8) << 4) & 0x3f, (b >> 6) % UInt8) - dst[j += 1] = 0x80 | ((b % UInt8) & 0x3f) - else - dst[j += 1] = 0xe0 | ((a >> 12) % UInt8) - dst[j += 1] = 0x80 | (((a >> 6) % UInt8) & 0x3f) - dst[j += 1] = 0x80 | ((a % UInt8) & 0x3f) - a = b; continue - end - else - # 1-unit high UTF-16 or unpaired high surrogate - # either way, encode as 3-byte UTF-8 code point - dst[j += 1] = 0xe0 | ((a >> 12) % UInt8) - dst[j += 1] = 0x80 | (((a >> 6) % UInt8) & 0x3f) - dst[j += 1] = 0x80 | ((a % UInt8) & 0x3f) - end - i < n || break - a = src[i += 1] - end - return dst -end - -# deferring (or un-deferring) ctrl-c handler for external C code that -# is not interrupt safe (see also issue #2622). The sigatomic_begin/end -# functions should always be called in matched pairs, ideally via: -# disable_sigint() do .. end -# reennable_sigint is provided so that immediate ctrl-c handling is -# re-enabled within a sigatomic region, e.g. inside a Julia callback function -# within a long-running C routine. -sigatomic_begin() = ccall(:jl_sigatomic_begin, Void, ()) -sigatomic_end() = ccall(:jl_sigatomic_end, Void, ()) - -""" - disable_sigint(f::Function) - -Disable Ctrl-C handler during execution of a function on the current task, -for calling external code that may call julia code that is not interrupt safe. -Intended to be called using `do` block syntax as follows: - - disable_sigint() do - # interrupt-unsafe code - ... - end - -This is not needed on worker threads (`Threads.threadid() != 1`) since the -`InterruptException` will only be delivered to the master thread. -External functions that do not call julia code or julia runtime -automatically disable sigint during their execution. -""" -function disable_sigint(f::Function) - sigatomic_begin() - res = f() - # Exception unwind sigatomic automatically - sigatomic_end() - res -end - -""" - reenable_sigint(f::Function) - -Re-enable Ctrl-C handler during execution of a function. -Temporarily reverses the effect of `disable_sigint`. -""" -function reenable_sigint(f::Function) - sigatomic_end() - res = f() - # Exception unwind sigatomic automatically - sigatomic_begin() - res -end - -function ccallable(f::Function, rt::Type, argt::Type, name::Union{AbstractString,Symbol}=string(f)) - ccall(:jl_extern_c, Void, (Any, Any, Any, Cstring), f, rt, argt, name) -end - -function expand_ccallable(rt, def) - if isa(def,Expr) && (def.head === :(=) || def.head === :function) - sig = def.args[1] - if sig.head === :(::) - if rt === nothing - rt = sig.args[2] - end - sig = sig.args[1] - end - if rt === nothing - error("@ccallable requires a return type") - end - if sig.head === :call - name = sig.args[1] - at = map(sig.args[2:end]) do a - if isa(a,Expr) && a.head === :(::) - a.args[2] - else - :Any - end - end - return quote - $(esc(def)) - ccallable($(esc(name)), $(esc(rt)), $(Expr(:curly, :Tuple, map(esc, at)...)), $(string(name))) - end - end - end - error("expected method definition in @ccallable") -end - -macro ccallable(def) - expand_ccallable(nothing, def) -end -macro ccallable(rt, def) - expand_ccallable(rt, def) -end diff --git a/julia-0.6.3/share/julia/base/cartesian.jl b/julia-0.6.3/share/julia/base/cartesian.jl deleted file mode 100644 index 86068a2..0000000 --- a/julia-0.6.3/share/julia/base/cartesian.jl +++ /dev/null @@ -1,426 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -module Cartesian - -export @nloops, @nref, @ncall, @nexprs, @nextract, @nall, @nany, @ntuple, @nif - -### Cartesian-specific macros - -""" - @nloops N itersym rangeexpr bodyexpr - @nloops N itersym rangeexpr preexpr bodyexpr - @nloops N itersym rangeexpr preexpr postexpr bodyexpr - -Generate `N` nested loops, using `itersym` as the prefix for the iteration variables. -`rangeexpr` may be an anonymous-function expression, or a simple symbol `var` in which case -the range is `indices(var, d)` for dimension `d`. - -Optionally, you can provide "pre" and "post" expressions. These get executed first and last, -respectively, in the body of each loop. For example: - - @nloops 2 i A d -> j_d = min(i_d, 5) begin - s += @nref 2 A j - end - -would generate: - - for i_2 = indices(A, 2) - j_2 = min(i_2, 5) - for i_1 = indices(A, 1) - j_1 = min(i_1, 5) - s += A[j_1, j_2] - end - end - -If you want just a post-expression, supply `nothing` for the pre-expression. Using -parentheses and semicolons, you can supply multi-statement expressions. -""" -macro nloops(N, itersym, rangeexpr, args...) - _nloops(N, itersym, rangeexpr, args...) -end - -function _nloops(N::Int, itersym::Symbol, arraysym::Symbol, args::Expr...) - @gensym d - _nloops(N, itersym, :($d->indices($arraysym, $d)), args...) -end - -function _nloops(N::Int, itersym::Symbol, rangeexpr::Expr, args::Expr...) - if rangeexpr.head != :-> - throw(ArgumentError("second argument must be an anonymous function expression to compute the range")) - end - if !(1 <= length(args) <= 3) - throw(ArgumentError("number of arguments must be 1 ≤ length(args) ≤ 3, got $nargs")) - end - body = args[end] - ex = Expr(:escape, body) - for dim = 1:N - itervar = inlineanonymous(itersym, dim) - rng = inlineanonymous(rangeexpr, dim) - preexpr = length(args) > 1 ? inlineanonymous(args[1], dim) : (:(nothing)) - postexpr = length(args) > 2 ? inlineanonymous(args[2], dim) : (:(nothing)) - ex = quote - for $(esc(itervar)) = $(esc(rng)) - $(esc(preexpr)) - $ex - $(esc(postexpr)) - end - end - end - ex -end - -""" - @nref N A indexexpr - -Generate expressions like `A[i_1, i_2, ...]`. `indexexpr` can either be an iteration-symbol -prefix, or an anonymous-function expression. - -```jldoctest -julia> @macroexpand Base.Cartesian.@nref 3 A i -:(A[i_1, i_2, i_3]) -``` -""" -macro nref(N, A, sym) - _nref(N, A, sym) -end - -function _nref(N::Int, A::Symbol, ex) - vars = [ inlineanonymous(ex,i) for i = 1:N ] - Expr(:escape, Expr(:ref, A, vars...)) -end - -""" - @ncall N f sym... - -Generate a function call expression. `sym` represents any number of function arguments, the -last of which may be an anonymous-function expression and is expanded into `N` arguments. - -For example `@ncall 3 func a` generates - - func(a_1, a_2, a_3) - -while `@ncall 2 func a b i->c[i]` yields - - func(a, b, c[1], c[2]) - -""" -macro ncall(N, f, sym...) - _ncall(N, f, sym...) -end - -function _ncall(N::Int, f, args...) - pre = args[1:end-1] - ex = args[end] - vars = [ inlineanonymous(ex,i) for i = 1:N ] - Expr(:escape, Expr(:call, f, pre..., vars...)) -end - -""" - @nexprs N expr - -Generate `N` expressions. `expr` should be an anonymous-function expression. - -```jldoctest -julia> @macroexpand Base.Cartesian.@nexprs 4 i -> y[i] = A[i+j] -quote - y[1] = A[1 + j] - y[2] = A[2 + j] - y[3] = A[3 + j] - y[4] = A[4 + j] -end -``` -""" -macro nexprs(N, ex) - _nexprs(N, ex) -end - -function _nexprs(N::Int, ex::Expr) - exs = [ inlineanonymous(ex,i) for i = 1:N ] - Expr(:escape, Expr(:block, exs...)) -end - -""" - @nextract N esym isym - -Generate `N` variables `esym_1`, `esym_2`, ..., `esym_N` to extract values from `isym`. -`isym` can be either a `Symbol` or anonymous-function expression. - -`@nextract 2 x y` would generate - - x_1 = y[1] - x_2 = y[2] - -while `@nextract 3 x d->y[2d-1]` yields - - x_1 = y[1] - x_2 = y[3] - x_3 = y[5] - -""" -macro nextract(N, esym, isym) - _nextract(N, esym, isym) -end - -function _nextract(N::Int, esym::Symbol, isym::Symbol) - aexprs = [Expr(:escape, Expr(:(=), inlineanonymous(esym, i), :(($isym)[$i]))) for i = 1:N] - Expr(:block, aexprs...) -end - -function _nextract(N::Int, esym::Symbol, ex::Expr) - aexprs = [Expr(:escape, Expr(:(=), inlineanonymous(esym, i), inlineanonymous(ex,i))) for i = 1:N] - Expr(:block, aexprs...) -end - -""" - @nall N expr - -Check whether all of the expressions generated by the anonymous-function expression `expr` -evaluate to `true`. - -`@nall 3 d->(i_d > 1)` would generate the expression `(i_1 > 1 && i_2 > 1 && i_3 > 1)`. This -can be convenient for bounds-checking. -""" -macro nall(N, criterion) - _nall(N, criterion) -end - -function _nall(N::Int, criterion::Expr) - if criterion.head != :-> - throw(ArgumentError("second argument must be an anonymous function expression yielding the criterion")) - end - conds = [Expr(:escape, inlineanonymous(criterion, i)) for i = 1:N] - Expr(:&&, conds...) -end - -""" - @nany N expr - -Check whether any of the expressions generated by the anonymous-function expression `expr` -evaluate to `true`. - -`@nany 3 d->(i_d > 1)` would generate the expression `(i_1 > 1 || i_2 > 1 || i_3 > 1)`. -""" -macro nany(N, criterion) - _nany(N, criterion) -end - -function _nany(N::Int, criterion::Expr) - if criterion.head != :-> - error("Second argument must be an anonymous function expression yielding the criterion") - end - conds = [Expr(:escape, inlineanonymous(criterion, i)) for i = 1:N] - Expr(:||, conds...) -end - -""" - @ntuple N expr - -Generates an `N`-tuple. `@ntuple 2 i` would generate `(i_1, i_2)`, and `@ntuple 2 k->k+1` -would generate `(2,3)`. -""" -macro ntuple(N, ex) - _ntuple(N, ex) -end - -function _ntuple(N::Int, ex) - vars = [ inlineanonymous(ex,i) for i = 1:N ] - Expr(:escape, Expr(:tuple, vars...)) -end - -""" - @nif N conditionexpr expr - @nif N conditionexpr expr elseexpr - -Generates a sequence of `if ... elseif ... else ... end` statements. For example: - - @nif 3 d->(i_d >= size(A,d)) d->(error("Dimension ", d, " too big")) d->println("All OK") - -would generate: - - if i_1 > size(A, 1) - error("Dimension ", 1, " too big") - elseif i_2 > size(A, 2) - error("Dimension ", 2, " too big") - else - println("All OK") - end -""" -macro nif(N, condition, operation...) - # Handle the final "else" - ex = esc(inlineanonymous(length(operation) > 1 ? operation[2] : operation[1], N)) - # Make the nested if statements - for i = N-1:-1:1 - ex = Expr(:if, esc(inlineanonymous(condition,i)), esc(inlineanonymous(operation[1],i)), ex) - end - ex -end - -## Utilities - -# Simplify expressions like :(d->3:size(A,d)-3) given an explicit value for d -function inlineanonymous(ex::Expr, val) - if ex.head != :-> - throw(ArgumentError("not an anonymous function")) - end - if !isa(ex.args[1], Symbol) - throw(ArgumentError("not a single-argument anonymous function")) - end - sym = ex.args[1] - ex = ex.args[2] - exout = lreplace(ex, sym, val) - exout = poplinenum(exout) - exprresolve(exout) -end - -# Given :i and 3, this generates :i_3 -inlineanonymous(base::Symbol, ext) = Symbol(base,'_',ext) - -# Replace a symbol by a value or a "coded" symbol -# E.g., for d = 3, -# lreplace(:d, :d, 3) -> 3 -# lreplace(:i_d, :d, 3) -> :i_3 -# lreplace(:i_{d-1}, :d, 3) -> :i_2 -# This follows LaTeX notation. -struct LReplace{S<:AbstractString} - pat_sym::Symbol - pat_str::S - val::Int -end -LReplace(sym::Symbol, val::Integer) = LReplace(sym, string(sym), val) - -lreplace(ex, sym::Symbol, val) = lreplace!(copy(ex), LReplace(sym, val)) - -function lreplace!(sym::Symbol, r::LReplace) - sym == r.pat_sym && return r.val - Symbol(lreplace!(string(sym), r)) -end - -function lreplace!(str::AbstractString, r::LReplace) - i = start(str) - pat = r.pat_str - j = start(pat) - matching = false - while !done(str, i) - cstr, i = next(str, i) - if !matching - if cstr != '_' || done(str, i) - continue - end - istart = i - cstr, i = next(str, i) - end - if !done(pat, j) - cr, j = next(pat, j) - if cstr == cr - matching = true - else - matching = false - j = start(pat) - i = istart - continue - end - end - if matching && done(pat, j) - if done(str, i) || next(str, i)[1] == '_' - # We have a match - return string(str[1:prevind(str, istart)], r.val, lreplace!(str[i:end], r)) - end - matching = false - j = start(pat) - i = istart - end - end - str -end - -function lreplace!(ex::Expr, r::LReplace) - # Curly-brace notation, which acts like parentheses - if ex.head == :curly && length(ex.args) == 2 && isa(ex.args[1], Symbol) && endswith(string(ex.args[1]), "_") - excurly = exprresolve(lreplace!(ex.args[2], r)) - if isa(excurly, Number) - return Symbol(ex.args[1],excurly) - else - ex.args[2] = excurly - return ex - end - end - for i in 1:length(ex.args) - ex.args[i] = lreplace!(ex.args[i], r) - end - ex -end - -lreplace!(arg, r::LReplace) = arg - - -poplinenum(arg) = arg -function poplinenum(ex::Expr) - if ex.head == :block - if length(ex.args) == 1 - return ex.args[1] - elseif length(ex.args) == 2 && isa(ex.args[1], LineNumberNode) - return ex.args[2] - elseif (length(ex.args) == 2 && isa(ex.args[1], Expr) && ex.args[1].head == :line) - return ex.args[2] - end - end - ex -end - -## Resolve expressions at parsing time ## - -const exprresolve_arith_dict = Dict{Symbol,Function}(:+ => +, - :- => -, :* => *, :/ => /, :^ => ^, :div => div) -const exprresolve_cond_dict = Dict{Symbol,Function}(:(==) => ==, - :(<) => <, :(>) => >, :(<=) => <=, :(>=) => >=) - -function exprresolve_arith(ex::Expr) - if ex.head == :call && haskey(exprresolve_arith_dict, ex.args[1]) && all([isa(ex.args[i], Number) for i = 2:length(ex.args)]) - return true, exprresolve_arith_dict[ex.args[1]](ex.args[2:end]...) - end - false, 0 -end -exprresolve_arith(arg) = false, 0 - -exprresolve_conditional(b::Bool) = true, b -function exprresolve_conditional(ex::Expr) - if ex.head == :call && ex.args[1] ∈ keys(exprresolve_cond_dict) && isa(ex.args[2], Number) && isa(ex.args[3], Number) - return true, exprresolve_cond_dict[ex.args[1]](ex.args[2], ex.args[3]) - end - false, false -end -exprresolve_conditional(arg) = false, false - -exprresolve(arg) = arg -function exprresolve(ex::Expr) - for i = 1:length(ex.args) - ex.args[i] = exprresolve(ex.args[i]) - end - # Handle simple arithmetic - can_eval, result = exprresolve_arith(ex) - if can_eval - return result - elseif ex.head == :call && (ex.args[1] == :+ || ex.args[1] == :-) && length(ex.args) == 3 && ex.args[3] == 0 - # simplify x+0 and x-0 - return ex.args[2] - end - # Resolve array references - if ex.head == :ref && isa(ex.args[1], Array) - for i = 2:length(ex.args) - if !isa(ex.args[i], Real) - return ex - end - end - return ex.args[1][ex.args[2:end]...] - end - # Resolve conditionals - if ex.head == :if - can_eval, tf = exprresolve_conditional(ex.args[1]) - if can_eval - ex = tf?ex.args[2]:ex.args[3] - end - end - ex -end - -end diff --git a/julia-0.6.3/share/julia/base/channels.jl b/julia-0.6.3/share/julia/base/channels.jl deleted file mode 100644 index 95af3a8..0000000 --- a/julia-0.6.3/share/julia/base/channels.jl +++ /dev/null @@ -1,419 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -abstract type AbstractChannel end - -""" - Channel{T}(sz::Int) - -Constructs a `Channel` with an internal buffer that can hold a maximum of `sz` objects -of type `T`. -[`put!`](@ref) calls on a full channel block until an object is removed with [`take!`](@ref). - -`Channel(0)` constructs an unbuffered channel. `put!` blocks until a matching `take!` is called. -And vice-versa. - -Other constructors: - -* `Channel(Inf)`: equivalent to `Channel{Any}(typemax(Int))` -* `Channel(sz)`: equivalent to `Channel{Any}(sz)` -""" -mutable struct Channel{T} <: AbstractChannel - cond_take::Condition # waiting for data to become available - cond_put::Condition # waiting for a writeable slot - state::Symbol - excp::Nullable{Exception} # Exception to be thrown when state != :open - - data::Vector{T} - sz_max::Int # maximum size of channel - - # Used when sz_max == 0, i.e., an unbuffered channel. - waiters::Int - takers::Vector{Task} - putters::Vector{Task} - - function Channel{T}(sz::Float64) where T - if sz == Inf - Channel{T}(typemax(Int)) - else - Channel{T}(convert(Int, sz)) - end - end - function Channel{T}(sz::Integer) where T - if sz < 0 - throw(ArgumentError("Channel size must be either 0, a positive integer or Inf")) - end - ch = new(Condition(), Condition(), :open, Nullable{Exception}(), Vector{T}(0), sz, 0) - if sz == 0 - ch.takers = Vector{Task}(0) - ch.putters = Vector{Task}(0) - end - return ch - end - - # deprecated empty constructor - function Channel{T}() where T - depwarn(string("The empty constructor Channel() is deprecated. ", - "The channel size needs to be specified explictly. ", - "Defaulting to Channel{$T}(32)."), :Channel) - Channel(32) - end -end - -Channel(sz) = Channel{Any}(sz) - -# special constructors -""" - Channel(func::Function; ctype=Any, csize=0, taskref=nothing) - -Creates a new task from `func`, binds it to a new channel of type -`ctype` and size `csize`, and schedules the task, all in a single call. - -`func` must accept the bound channel as its only argument. - -If you need a reference to the created task, pass a `Ref{Task}` object via -keyword argument `taskref`. - -Returns a Channel. - -```jldoctest -julia> chnl = Channel(c->foreach(i->put!(c,i), 1:4)); - -julia> typeof(chnl) -Channel{Any} - -julia> for i in chnl - @show i - end; -i = 1 -i = 2 -i = 3 -i = 4 -``` - -An example of referencing the created task: - -```jldoctest -julia> taskref = Ref{Task}(); - -julia> chnl = Channel(c->(@show take!(c)); taskref=taskref); - -julia> istaskdone(taskref[]) -false - -julia> put!(chnl, "Hello"); -take!(c) = "Hello" - -julia> istaskdone(taskref[]) -true -``` -""" -function Channel(func::Function; ctype=Any, csize=0, taskref=nothing) - chnl = Channel{ctype}(csize) - task = Task(() -> func(chnl)) - bind(chnl, task) - yield(task) # immediately start it - - isa(taskref, Ref{Task}) && (taskref[] = task) - return chnl -end - - - -# deprecated empty constructor -Channel() = Channel{Any}() - -closed_exception() = InvalidStateException("Channel is closed.", :closed) - -isbuffered(c::Channel) = c.sz_max==0 ? false : true - -function check_channel_state(c::Channel) - if !isopen(c) - !isnull(c.excp) && throw(get(c.excp)) - throw(closed_exception()) - end -end -""" - close(c::Channel) - -Closes a channel. An exception is thrown by: - -* [`put!`](@ref) on a closed channel. -* [`take!`](@ref) and [`fetch`](@ref) on an empty, closed channel. -""" -function close(c::Channel) - c.state = :closed - c.excp = Nullable{}(closed_exception()) - notify_error(c) - nothing -end -isopen(c::Channel) = (c.state == :open) - -""" - bind(chnl::Channel, task::Task) - -Associates the lifetime of `chnl` with a task. -Channel `chnl` is automatically closed when the task terminates. -Any uncaught exception in the task is propagated to all waiters on `chnl`. - -The `chnl` object can be explicitly closed independent of task termination. -Terminating tasks have no effect on already closed Channel objects. - -When a channel is bound to multiple tasks, the first task to terminate will -close the channel. When multiple channels are bound to the same task, -termination of the task will close all of the bound channels. - -```jldoctest -julia> c = Channel(0); - -julia> task = @schedule foreach(i->put!(c, i), 1:4); - -julia> bind(c,task); - -julia> for i in c - @show i - end; -i = 1 -i = 2 -i = 3 -i = 4 - -julia> isopen(c) -false -``` - -```jldoctest -julia> c = Channel(0); - -julia> task = @schedule (put!(c,1);error("foo")); - -julia> bind(c,task); - -julia> take!(c) -1 - -julia> put!(c,1); -ERROR: foo -Stacktrace: - [1] check_channel_state(::Channel{Any}) at ./channels.jl:131 - [2] put!(::Channel{Any}, ::Int64) at ./channels.jl:261 -``` -""" -function bind(c::Channel, task::Task) - ref = WeakRef(c) - register_taskdone_hook(task, tsk->close_chnl_on_taskdone(tsk, ref)) - c -end - -""" - channeled_tasks(n::Int, funcs...; ctypes=fill(Any,n), csizes=fill(0,n)) - -A convenience method to create `n` channels and bind them to tasks started -from the provided functions in a single call. Each `func` must accept `n` arguments -which are the created channels. Channel types and sizes may be specified via -keyword arguments `ctypes` and `csizes` respectively. If unspecified, all channels are -of type `Channel{Any}(0)`. - -Returns a tuple, `(Array{Channel}, Array{Task})`, of the created channels and tasks. -""" -function channeled_tasks(n::Int, funcs...; ctypes=fill(Any,n), csizes=fill(0,n)) - @assert length(csizes) == n - @assert length(ctypes) == n - - chnls = map(i -> Channel{ctypes[i]}(csizes[i]), 1:n) - tasks = Task[ Task(() -> f(chnls...)) for f in funcs ] - - # bind all tasks to all channels and schedule them - foreach(t -> foreach(c -> bind(c, t), chnls), tasks) - foreach(schedule, tasks) - yield() # Allow scheduled tasks to run - - return (chnls, tasks) -end - -function close_chnl_on_taskdone(t::Task, ref::WeakRef) - if ref.value !== nothing - c = ref.value - !isopen(c) && return - if istaskfailed(t) - c.state = :closed - c.excp = Nullable{Exception}(task_result(t)) - notify_error(c) - else - close(c) - end - end -end - -mutable struct InvalidStateException <: Exception - msg::AbstractString - state::Symbol -end - -""" - put!(c::Channel, v) - -Appends an item `v` to the channel `c`. Blocks if the channel is full. - -For unbuffered channels, blocks until a [`take!`](@ref) is performed by a different -task. -""" -function put!(c::Channel, v) - check_channel_state(c) - isbuffered(c) ? put_buffered(c,v) : put_unbuffered(c,v) -end - -function put_buffered(c::Channel, v) - while length(c.data) == c.sz_max - wait(c.cond_put) - end - push!(c.data, v) - - # notify all, since some of the waiters may be on a "fetch" call. - notify(c.cond_take, nothing, true, false) - v -end - -function put_unbuffered(c::Channel, v) - if length(c.takers) == 0 - push!(c.putters, current_task()) - c.waiters > 0 && notify(c.cond_take, nothing, false, false) - - try - wait() - catch ex - filter!(x->x!=current_task(), c.putters) - rethrow(ex) - end - end - taker = shift!(c.takers) - yield(taker, v) # immediately give taker a chance to run, but don't block the current task - return v -end - -push!(c::Channel, v) = put!(c, v) - -""" - fetch(c::Channel) - -Waits for and gets the first available item from the channel. Does not -remove the item. `fetch` is unsupported on an unbuffered (0-size) channel. -""" -fetch(c::Channel) = isbuffered(c) ? fetch_buffered(c) : fetch_unbuffered(c) -function fetch_buffered(c::Channel) - wait(c) - c.data[1] -end -fetch_unbuffered(c::Channel) = throw(ErrorException("`fetch` is not supported on an unbuffered Channel.")) - - -""" - take!(c::Channel) - -Removes and returns a value from a [`Channel`](@ref). Blocks until data is available. - -For unbuffered channels, blocks until a [`put!`](@ref) is performed by a different -task. -""" -take!(c::Channel) = isbuffered(c) ? take_buffered(c) : take_unbuffered(c) -function take_buffered(c::Channel) - wait(c) - v = shift!(c.data) - notify(c.cond_put, nothing, false, false) # notify only one, since only one slot has become available for a put!. - v -end - -shift!(c::Channel) = take!(c) - -# 0-size channel -function take_unbuffered(c::Channel{T}) where T - check_channel_state(c) - push!(c.takers, current_task()) - try - if length(c.putters) > 0 - let putter = shift!(c.putters) - return Base.try_yieldto(putter) do - # if we fail to start putter, put it back in the queue - unshift!(c.putters, putter) - end::T - end - else - return wait()::T - end - catch ex - filter!(x->x!=current_task(), c.takers) - rethrow(ex) - end -end - -""" - isready(c::Channel) - -Determine whether a [`Channel`](@ref) has a value stored to it. Returns -immediately, does not block. - -For unbuffered channels returns `true` if there are tasks waiting -on a [`put!`](@ref). -""" -isready(c::Channel) = n_avail(c) > 0 -n_avail(c::Channel) = isbuffered(c) ? length(c.data) : length(c.putters) - -wait(c::Channel) = isbuffered(c) ? wait_impl(c) : wait_unbuffered(c) -function wait_impl(c::Channel) - while !isready(c) - check_channel_state(c) - wait(c.cond_take) - end - nothing -end - -function wait_unbuffered(c::Channel) - c.waiters += 1 - try - wait_impl(c) - finally - c.waiters -= 1 - end - nothing -end - -function notify_error(c::Channel, err) - notify_error(c.cond_take, err) - notify_error(c.cond_put, err) - - # release tasks on a `wait()/yieldto()` call (on unbuffered channels) - if !isbuffered(c) - waiters = filter!(t->(t.state == :runnable), vcat(c.takers, c.putters)) - foreach(t->schedule(t, err; error=true), waiters) - end -end -notify_error(c::Channel) = notify_error(c, get(c.excp)) - -eltype(::Type{Channel{T}}) where {T} = T - -show(io::IO, c::Channel) = print(io, "$(typeof(c))(sz_max:$(c.sz_max),sz_curr:$(n_avail(c)))") - -mutable struct ChannelIterState{T} - hasval::Bool - val::T - ChannelIterState{T}(has::Bool) where {T} = new(has) -end - -start(c::Channel{T}) where {T} = ChannelIterState{T}(false) -function done(c::Channel, state::ChannelIterState) - try - # we are waiting either for more data or channel to be closed - state.hasval && return false - state.val = take!(c) - state.hasval = true - return false - catch e - if isa(e, InvalidStateException) && e.state==:closed - return true - else - rethrow(e) - end - end -end -next(c::Channel, state) = (v=state.val; state.hasval=false; (v, state)) - -iteratorsize(::Type{<:Channel}) = SizeUnknown() diff --git a/julia-0.6.3/share/julia/base/char.jl b/julia-0.6.3/share/julia/base/char.jl deleted file mode 100644 index 6add31b..0000000 --- a/julia-0.6.3/share/julia/base/char.jl +++ /dev/null @@ -1,86 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -convert(::Type{Char}, x::UInt32) = reinterpret(Char, x) -convert(::Type{Char}, x::Number) = Char(UInt32(x)) -convert(::Type{UInt32}, x::Char) = reinterpret(UInt32, x) -convert(::Type{T}, x::Char) where {T<:Number} = convert(T, UInt32(x)) - -rem{T<:Number}(x::Char, ::Type{T}) = rem(UInt32(x), T) - -typemax(::Type{Char}) = reinterpret(Char, typemax(UInt32)) -typemin(::Type{Char}) = reinterpret(Char, typemin(UInt32)) - -size(c::Char) = () -size(c::Char,d) = convert(Int, d) < 1 ? throw(BoundsError()) : 1 -ndims(c::Char) = 0 -ndims(::Type{Char}) = 0 -length(c::Char) = 1 -endof(c::Char) = 1 -getindex(c::Char) = c -getindex(c::Char, i::Integer) = i == 1 ? c : throw(BoundsError()) -getindex(c::Char, I::Integer...) = all(x -> x == 1, I) ? c : throw(BoundsError()) -first(c::Char) = c -last(c::Char) = c -eltype(::Type{Char}) = Char - -start(c::Char) = false -next(c::Char, state) = (c, true) -done(c::Char, state) = state -isempty(c::Char) = false -in(x::Char, y::Char) = x == y - -==(x::Char, y::Char) = UInt32(x) == UInt32(y) -isless(x::Char, y::Char) = UInt32(x) < UInt32(y) - -const hashchar_seed = 0xd4d64234 -hash(x::Char, h::UInt) = hash_uint64(((UInt64(x)+hashchar_seed)<<32) ⊻ UInt64(h)) - --(x::Char, y::Char) = Int(x) - Int(y) --(x::Char, y::Integer) = Char(Int32(x) - Int32(y)) -+(x::Char, y::Integer) = Char(Int32(x) + Int32(y)) -+(x::Integer, y::Char) = y + x - -bswap(x::Char) = Char(bswap(UInt32(x))) - -print(io::IO, c::Char) = (write(io, c); nothing) - -const hex_chars = UInt8['0':'9';'a':'z'] - -function show(io::IO, c::Char) - if c <= '\\' - b = c == '\0' ? 0x30 : - c == '\a' ? 0x61 : - c == '\b' ? 0x62 : - c == '\t' ? 0x74 : - c == '\n' ? 0x6e : - c == '\v' ? 0x76 : - c == '\f' ? 0x66 : - c == '\r' ? 0x72 : - c == '\e' ? 0x65 : - c == '\'' ? 0x27 : - c == '\\' ? 0x5c : 0xff - if b != 0xff - write(io, 0x27, 0x5c, b, 0x27) - return - end - end - if isprint(c) - write(io, 0x27, c, 0x27) - else - u = UInt32(c) - write(io, 0x27, 0x5c, c <= '\x7f' ? 0x78 : c <= '\uffff' ? 0x75 : 0x55) - d = max(2, 8 - (leading_zeros(u) >> 2)) - while 0 < d - write(io, hex_chars[((u >> ((d -= 1) << 2)) & 0xf) + 1]) - end - write(io, 0x27) - end - return -end - -function show(io::IO, ::MIME"text/plain", c::Char) - show(io, c) - u = UInt32(c) - print(io, ": ", isascii(c) ? "ASCII/" : "", "Unicode U+", hex(u, u > 0xffff ? 6 : 4)) - print(io, " (category ", UTF8proc.category_abbrev(c), ": ", UTF8proc.category_string(c), ")") -end diff --git a/julia-0.6.3/share/julia/base/checked.jl b/julia-0.6.3/share/julia/base/checked.jl deleted file mode 100644 index 215f12a..0000000 --- a/julia-0.6.3/share/julia/base/checked.jl +++ /dev/null @@ -1,351 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -# Support for checked integer arithmetic - -module Checked - -export checked_neg, checked_abs, checked_add, checked_sub, checked_mul, - checked_div, checked_rem, checked_fld, checked_mod, checked_cld, - add_with_overflow, sub_with_overflow, mul_with_overflow - -import Core.Intrinsics: - checked_sadd_int, checked_ssub_int, checked_smul_int, checked_sdiv_int, - checked_srem_int, - checked_uadd_int, checked_usub_int, checked_umul_int, checked_udiv_int, - checked_urem_int -import Base: no_op_err, @_inline_meta - -# define promotion behavior for checked operations -checked_add(x::Integer, y::Integer) = checked_add(promote(x,y)...) -checked_sub(x::Integer, y::Integer) = checked_sub(promote(x,y)...) -checked_mul(x::Integer, y::Integer) = checked_mul(promote(x,y)...) -checked_div(x::Integer, y::Integer) = checked_div(promote(x,y)...) -checked_rem(x::Integer, y::Integer) = checked_rem(promote(x,y)...) -checked_fld(x::Integer, y::Integer) = checked_fld(promote(x,y)...) -checked_mod(x::Integer, y::Integer) = checked_mod(promote(x,y)...) -checked_cld(x::Integer, y::Integer) = checked_cld(promote(x,y)...) - -# fallback catchall rules to prevent infinite recursion if promotion succeeds, -# but no method exists to handle those types -checked_abs(x::T) where {T<:Integer} = no_op_err("checked_abs", T) - -const SignedInt = Union{Int8,Int16,Int32,Int64,Int128} -const UnsignedInt = Union{UInt8,UInt16,UInt32,UInt64,UInt128} - -# LLVM has several code generation bugs for checked integer arithmetic (see e.g. -# #4905). We thus distinguish between operations that can be implemented via -# intrinsics, and operations for which we have to provide work-arounds. - -# Note: As far as this code has been tested, most checked_* functions are -# working fine in LLVM. (Note that division is still handled via `base/int.jl`, -# which always checks for overflow, and which provides its own sets of -# work-arounds for LLVM codegen bugs.) However, the comments in `base/int.jl` -# and in issue #4905 are more pessimistic. For the time being, we thus retain -# the ability to handle codegen bugs in LLVM, until the code here has been -# tested on more systems and architectures. It also seems that things depend on -# which compiler that was used to build LLVM (i.e. either gcc or clang). - -# These unions are used for most checked functions: -# BrokenSignedInt -# BrokenUnsignedInt -# These unions are used for checked_{mul,div,rem}: -# BrokenSignedIntMul -# BrokenUnsignedIntMul - -# This code runs early during bootstrap, and we can't use Julia's version -# strings yet -const llvm_version = Int(ccall(:jl_get_LLVM_VERSION, UInt32, ())) - -brokenSignedInt = Union{} -brokenUnsignedInt = Union{} -brokenSignedIntMul = Int128 -brokenUnsignedIntMul = UInt128 -if Core.sizeof(Ptr{Void}) == 4 - brokenSignedIntMul = Union{brokenSignedIntMul, Int64} - brokenUnsignedIntMul = Union{brokenUnsignedIntMul, UInt64} -end -if llvm_version < 30500 - brokenSignedIntMul = Union{brokenSignedIntMul, Int8} - brokenUnsignedIntMul = Union{brokenUnsignedIntMul, UInt8} -end -const BrokenSignedInt = brokenSignedInt -const BrokenUnsignedInt = brokenUnsignedInt -const BrokenSignedIntMul = brokenSignedIntMul -const BrokenUnsignedIntMul = brokenUnsignedIntMul -# Use these definitions to test the non-LLVM implementations -# const BrokenSignedInt = SignedInt -# const BrokenUnsignedInt = UnsignedInt -# const BrokenSignedIntMul = SignedInt -# const BrokenUnsignedIntMul = UnsignedInt - -""" - Base.checked_neg(x) - -Calculates `-x`, checking for overflow errors where applicable. For -example, standard two's complement signed integers (e.g. `Int`) cannot -represent `-typemin(Int)`, thus leading to an overflow. - -The overflow protection may impose a perceptible performance penalty. -""" -function checked_neg(x::T) where T<:Integer - checked_sub(T(0), x) -end -if BrokenSignedInt != Union{} -function checked_neg(x::BrokenSignedInt) - r = -x - (x<0) & (r<0) && throw(OverflowError()) - r -end -end -if BrokenUnsignedInt != Union{} -function checked_neg(x::T) where T<:BrokenUnsignedInt - x != 0 && throw(OverflowError()) - T(0) -end -end - -""" - Base.checked_abs(x) - -Calculates `abs(x)`, checking for overflow errors where applicable. -For example, standard two's complement signed integers (e.g. `Int`) -cannot represent `abs(typemin(Int))`, thus leading to an overflow. - -The overflow protection may impose a perceptible performance penalty. -""" -function checked_abs end - -function checked_abs(x::SignedInt) - r = ifelse(x<0, -x, x) - r<0 && throw(OverflowError()) - r - end -checked_abs(x::UnsignedInt) = x -checked_abs(x::Bool) = x - - - -""" - Base.add_with_overflow(x, y) -> (r, f) - -Calculates `r = x+y`, with the flag `f` indicating whether overflow has occurred. -""" -function add_with_overflow end -add_with_overflow(x::T, y::T) where {T<:SignedInt} = checked_sadd_int(x, y) -add_with_overflow(x::T, y::T) where {T<:UnsignedInt} = checked_uadd_int(x, y) -add_with_overflow(x::Bool, y::Bool) = (x+y, false) - -if BrokenSignedInt != Union{} -function add_with_overflow(x::T, y::T) where T<:BrokenSignedInt - r = x + y - # x and y have the same sign, and the result has a different sign - f = (x<0) == (y<0) != (r<0) - r, f -end -end -if BrokenUnsignedInt != Union{} -function add_with_overflow(x::T, y::T) where T<:BrokenUnsignedInt - # x + y > typemax(T) - # Note: ~y == -y-1 - x + y, x > ~y -end -end - - -""" - Base.checked_add(x, y) - -Calculates `x+y`, checking for overflow errors where applicable. - -The overflow protection may impose a perceptible performance penalty. -""" -function checked_add(x::T, y::T) where T<:Integer - @_inline_meta - z, b = add_with_overflow(x, y) - b && throw(OverflowError()) - z -end - -# Handle multiple arguments -checked_add(x) = x -checked_add(x::Bool) = +x - -checked_add(x1::T, x2::T, x3::T) where {T} = - checked_add(checked_add(x1, x2), x3) -checked_add(x1::T, x2::T, x3::T, x4::T) where {T} = - checked_add(checked_add(x1, x2), x3, x4) -checked_add(x1::T, x2::T, x3::T, x4::T, x5::T) where {T} = - checked_add(checked_add(x1, x2), x3, x4, x5) -checked_add(x1::T, x2::T, x3::T, x4::T, x5::T, x6::T) where {T} = - checked_add(checked_add(x1, x2), x3, x4, x5, x6) -checked_add(x1::T, x2::T, x3::T, x4::T, x5::T, x6::T, x7::T) where {T} = - checked_add(checked_add(x1, x2), x3, x4, x5, x6, x7) -checked_add(x1::T, x2::T, x3::T, x4::T, x5::T, x6::T, x7::T, x8::T) where {T} = - checked_add(checked_add(x1, x2), x3, x4, x5, x6, x7, x8) - - -""" - Base.sub_with_overflow(x, y) -> (r, f) - -Calculates `r = x-y`, with the flag `f` indicating whether overflow has occurred. -""" -function sub_with_overflow end -sub_with_overflow(x::T, y::T) where {T<:SignedInt} = checked_ssub_int(x, y) -sub_with_overflow(x::T, y::T) where {T<:UnsignedInt} = checked_usub_int(x, y) -sub_with_overflow(x::Bool, y::Bool) = (x-y, false) - -if BrokenSignedInt != Union{} -function sub_with_overflow(x::T, y::T) where T<:BrokenSignedInt - r = x - y - # x and y have different signs, and the result has a different sign than x - f = (x<0) != (y<0) == (r<0) - r, f -end -end -if BrokenUnsignedInt != Union{} -function sub_with_overflow(x::T, y::T) where T<:BrokenUnsignedInt - # x - y < 0 - x - y, x < y -end -end - -""" - Base.checked_sub(x, y) - -Calculates `x-y`, checking for overflow errors where applicable. - -The overflow protection may impose a perceptible performance penalty. -""" -function checked_sub(x::T, y::T) where T<:Integer - @_inline_meta - z, b = sub_with_overflow(x, y) - b && throw(OverflowError()) - z -end - - -""" - Base.mul_with_overflow(x, y) -> (r, f) - -Calculates `r = x*y`, with the flag `f` indicating whether overflow has occurred. -""" -function mul_with_overflow end -mul_with_overflow(x::T, y::T) where {T<:SignedInt} = checked_smul_int(x, y) -mul_with_overflow(x::T, y::T) where {T<:UnsignedInt} = checked_umul_int(x, y) -mul_with_overflow(x::Bool, y::Bool) = (x*y, false) - -if BrokenSignedIntMul != Union{} && BrokenSignedIntMul != Int128 -function mul_with_overflow(x::T, y::T) where T<:BrokenSignedIntMul - r = widemul(x, y) - f = r % T != r - r % T, f -end -end -if BrokenUnsignedIntMul != Union{} && BrokenUnsignedIntMul != UInt128 -function mul_with_overflow(x::T, y::T) where T<:BrokenUnsignedIntMul - r = widemul(x, y) - f = r % T != r - r % T, f -end -end -if Int128 <: BrokenSignedIntMul - # Avoid BigInt - function mul_with_overflow(x::T, y::T) where T<:Int128 - f = if y > 0 - # x * y > typemax(T) - # x * y < typemin(T) - x > fld(typemax(T), y) || x < cld(typemin(T), y) - elseif y < 0 - # x * y > typemax(T) - # x * y < typemin(T) - # y == -1 can overflow fld - x < cld(typemax(T), y) || y != -1 && x > fld(typemin(T), y) - else - false - end - x*y, f - end -end -if UInt128 <: BrokenUnsignedIntMul - # Avoid BigInt - function mul_with_overflow(x::T, y::T) where T<:UInt128 - # x * y > typemax(T) - x * y, y > 0 && x > fld(typemax(T), y) - end -end - -""" - Base.checked_mul(x, y) - -Calculates `x*y`, checking for overflow errors where applicable. - -The overflow protection may impose a perceptible performance penalty. -""" -function checked_mul(x::T, y::T) where T<:Integer - @_inline_meta - z, b = mul_with_overflow(x, y) - b && throw(OverflowError()) - z -end - -# Handle multiple arguments -checked_mul(x) = x -checked_mul(x1::T, x2::T, x3::T) where {T} = - checked_mul(checked_mul(x1, x2), x3) -checked_mul(x1::T, x2::T, x3::T, x4::T) where {T} = - checked_mul(checked_mul(x1, x2), x3, x4) -checked_mul(x1::T, x2::T, x3::T, x4::T, x5::T) where {T} = - checked_mul(checked_mul(x1, x2), x3, x4, x5) -checked_mul(x1::T, x2::T, x3::T, x4::T, x5::T, x6::T) where {T} = - checked_mul(checked_mul(x1, x2), x3, x4, x5, x6) -checked_mul(x1::T, x2::T, x3::T, x4::T, x5::T, x6::T, x7::T) where {T} = - checked_mul(checked_mul(x1, x2), x3, x4, x5, x6, x7) -checked_mul(x1::T, x2::T, x3::T, x4::T, x5::T, x6::T, x7::T, x8::T) where {T} = - checked_mul(checked_mul(x1, x2), x3, x4, x5, x6, x7, x8) - -""" - Base.checked_div(x, y) - -Calculates `div(x,y)`, checking for overflow errors where applicable. - -The overflow protection may impose a perceptible performance penalty. -""" -checked_div(x::T, y::T) where {T<:Integer} = div(x, y) # Base.div already checks - -""" - Base.checked_rem(x, y) - -Calculates `x%y`, checking for overflow errors where applicable. - -The overflow protection may impose a perceptible performance penalty. -""" -checked_rem(x::T, y::T) where {T<:Integer} = rem(x, y) # Base.rem already checks - -""" - Base.checked_fld(x, y) - -Calculates `fld(x,y)`, checking for overflow errors where applicable. - -The overflow protection may impose a perceptible performance penalty. -""" -checked_fld(x::T, y::T) where {T<:Integer} = fld(x, y) # Base.fld already checks - -""" - Base.checked_mod(x, y) - -Calculates `mod(x,y)`, checking for overflow errors where applicable. - -The overflow protection may impose a perceptible performance penalty. -""" -checked_mod(x::T, y::T) where {T<:Integer} = mod(x, y) # Base.mod already checks - -""" - Base.checked_cld(x, y) - -Calculates `cld(x,y)`, checking for overflow errors where applicable. - -The overflow protection may impose a perceptible performance penalty. -""" -checked_cld(x::T, y::T) where {T<:Integer} = cld(x, y) # Base.cld already checks - -end diff --git a/julia-0.6.3/share/julia/base/client.jl b/julia-0.6.3/share/julia/base/client.jl deleted file mode 100644 index 9a7cfa3..0000000 --- a/julia-0.6.3/share/julia/base/client.jl +++ /dev/null @@ -1,424 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -## client.jl - frontend handling command line options, environment setup, -## and REPL - -const text_colors = AnyDict( - :black => "\033[30m", - :red => "\033[31m", - :green => "\033[32m", - :yellow => "\033[33m", - :blue => "\033[34m", - :magenta => "\033[35m", - :cyan => "\033[36m", - :white => "\033[37m", - :light_black => "\033[90m", # gray - :light_red => "\033[91m", - :light_green => "\033[92m", - :light_yellow => "\033[93m", - :light_blue => "\033[94m", - :light_magenta => "\033[95m", - :light_cyan => "\033[96m", - :normal => "\033[0m", - :default => "\033[39m", - :bold => "\033[1m", - :nothing => "", -) - -for i in 0:255 - text_colors[i] = "\033[38;5;$(i)m" -end - -const disable_text_style = AnyDict( - :bold => "\033[22m", - :normal => "", - :default => "", -) - -# Create a docstring with an automatically generated list -# of colors. -available_text_colors = collect(Iterators.filter(x -> !isa(x, Integer), keys(text_colors))) -const possible_formatting_symbols = [:normal, :bold, :default] -available_text_colors = cat(1, - sort!(intersect(available_text_colors, possible_formatting_symbols), rev=true), - sort!(setdiff( available_text_colors, possible_formatting_symbols))) - -const available_text_colors_docstring = - string(join([string("`:", key,"`") - for key in available_text_colors], ",\n", ", or \n")) - -"""Dictionary of color codes for the terminal. - -Available colors are: $available_text_colors_docstring as well as the integers 0 to 255 inclusive. - -The color `:default` will print text in the default color while the color `:normal` -will print text with all text properties (like boldness) reset. -Printing with the color `:nothing` will print the string without modifications. -""" -text_colors - -have_color = false -default_color_warn = :yellow -default_color_error = :light_red -default_color_info = :cyan -default_color_input = :normal -default_color_answer = :normal -color_normal = text_colors[:normal] - -function repl_color(key, default) - env_str = get(ENV, key, "") - c = tryparse(Int, env_str) - c_conv = isnull(c) ? Symbol(env_str) : get(c) - haskey(text_colors, c_conv) ? c_conv : default -end - -error_color() = repl_color("JULIA_ERROR_COLOR", default_color_error) -warn_color() = repl_color("JULIA_WARN_COLOR" , default_color_warn) -info_color() = repl_color("JULIA_INFO_COLOR" , default_color_info) - -input_color() = text_colors[repl_color("JULIA_INPUT_COLOR", default_color_input)] -answer_color() = text_colors[repl_color("JULIA_ANSWER_COLOR", default_color_answer)] - -stackframe_lineinfo_color() = repl_color("JULIA_STACKFRAME_LINEINFO_COLOR", :bold) -stackframe_function_color() = repl_color("JULIA_STACKFRAME_FUNCTION_COLOR", :bold) - -function repl_cmd(cmd, out) - shell = shell_split(get(ENV,"JULIA_SHELL",get(ENV,"SHELL","/bin/sh"))) - shell_name = Base.basename(shell[1]) - - if isempty(cmd.exec) - throw(ArgumentError("no cmd to execute")) - elseif cmd.exec[1] == "cd" - new_oldpwd = pwd() - if length(cmd.exec) > 2 - throw(ArgumentError("cd method only takes one argument")) - elseif length(cmd.exec) == 2 - dir = cmd.exec[2] - if dir == "-" - if !haskey(ENV, "OLDPWD") - error("cd: OLDPWD not set") - end - cd(ENV["OLDPWD"]) - else - cd(@static is_windows() ? dir : readchomp(`$shell -c "echo $(shell_escape(dir))"`)) - end - else - cd() - end - ENV["OLDPWD"] = new_oldpwd - println(out, pwd()) - else - run(ignorestatus(@static is_windows() ? cmd : (isa(STDIN, TTY) ? `$shell -i -c "$(shell_wrap_true(shell_name, cmd))"` : `$shell -c "$(shell_wrap_true(shell_name, cmd))"`))) - end - nothing -end - -function shell_wrap_true(shell_name, cmd) - if shell_name == "fish" - "begin; $(shell_escape(cmd)); and true; end" - else - "($(shell_escape(cmd))) && true" - end -end - -function display_error(io::IO, er, bt) - if !isempty(bt) - st = stacktrace(bt) - if !isempty(st) - io = redirect(io, log_error_to, st[1]) - end - end - print_with_color(Base.error_color(), io, "ERROR: "; bold = true) - # remove REPL-related frames from interactive printing - eval_ind = findlast(addr->Base.REPL.ip_matches_func(addr, :eval), bt) - if eval_ind != 0 - bt = bt[1:eval_ind-1] - end - showerror(IOContext(io, :limit => true), er, bt) - println(io) -end -display_error(er, bt) = display_error(STDERR, er, bt) -display_error(er) = display_error(er, []) - -function eval_user_input(ast::ANY, show_value) - errcount, lasterr, bt = 0, (), nothing - while true - try - if have_color - print(color_normal) - end - if errcount > 0 - display_error(lasterr,bt) - errcount, lasterr = 0, () - else - ast = expand(ast) - value = eval(Main, ast) - eval(Main, Expr(:body, Expr(:(=), :ans, QuoteNode(value)), Expr(:return, nothing))) - if !(value === nothing) && show_value - if have_color - print(answer_color()) - end - try - eval(Main, Expr(:body, Expr(:return, Expr(:call, display, QuoteNode(value))))) - catch err - println(STDERR, "Evaluation succeeded, but an error occurred while showing value of type ", typeof(value), ":") - rethrow(err) - end - println() - end - end - break - catch err - if errcount > 0 - println(STDERR, "SYSTEM: show(lasterr) caused an error") - end - errcount, lasterr = errcount+1, err - if errcount > 2 - println(STDERR, "WARNING: it is likely that something important is broken, and Julia will not be able to continue normally") - break - end - bt = catch_backtrace() - end - end - isa(STDIN,TTY) && println() -end - -syntax_deprecation_warnings(warn::Bool) = - ccall(:jl_parse_depwarn, Cint, (Cint,), warn) == 1 - -function syntax_deprecation_warnings(f::Function, warn::Bool) - prev = syntax_deprecation_warnings(warn) - try - f() - finally - syntax_deprecation_warnings(prev) - end -end - -function parse_input_line(s::String; filename::String="none") - # (expr, pos) = parse(s, 1) - # (ex, pos) = ccall(:jl_parse_string, Any, - # (Ptr{UInt8},Csize_t,Int32,Int32), - # s, sizeof(s), pos-1, 1) - # if ex!==() - # throw(ParseError("extra input after end of expression")) - # end - # expr - ex = ccall(:jl_parse_input_line, Any, (Ptr{UInt8}, Csize_t, Ptr{UInt8}, Csize_t), - s, sizeof(s), filename, sizeof(filename)) - if ex === :_ - # remove with 0.6 deprecation - expand(ex) # to get possible warning about using _ as an rvalue - end - return ex -end -parse_input_line(s::AbstractString) = parse_input_line(String(s)) - -function parse_input_line(io::IO) - s = "" - while !eof(io) - s *= readline(io, chomp=false) - e = parse_input_line(s) - if !(isa(e,Expr) && e.head === :incomplete) - return e - end - end -end - -# detect the reason which caused an :incomplete expression -# from the error message -# NOTE: the error messages are defined in src/julia-parser.scm -incomplete_tag(ex) = :none -function incomplete_tag(ex::Expr) - Meta.isexpr(ex, :incomplete) || return :none - msg = ex.args[1] - contains(msg, "string") && return :string - contains(msg, "comment") && return :comment - contains(msg, "requires end") && return :block - contains(msg, "\"`\"") && return :cmd - contains(msg, "character") && return :char - return :other -end - -# try to include() a file, ignoring if not found -try_include(path::AbstractString) = isfile(path) && include(path) - -function process_options(opts::JLOptions) - if !isempty(ARGS) - idxs = find(x -> x == "--", ARGS) - length(idxs) > 0 && deleteat!(ARGS, idxs[1]) - end - repl = true - startup = (opts.startupfile != 2) - history_file = (opts.historyfile != 0) - quiet = (opts.quiet != 0) - color_set = (opts.color != 0) - global have_color = (opts.color == 1) - global is_interactive = (opts.isinteractive != 0) - while true - # startup worker. - # opts.startupfile, opts.load, etc should should not be processed for workers. - if opts.worker != C_NULL - start_worker(unsafe_string(opts.worker)) # does not return - end - - # add processors - if opts.nprocs > 0 - addprocs(opts.nprocs) - end - # load processes from machine file - if opts.machinefile != C_NULL - addprocs(load_machine_file(unsafe_string(opts.machinefile))) - end - - # load ~/.juliarc file - startup && load_juliarc() - - # load file immediately on all processors - if opts.load != C_NULL - @sync for p in procs() - @async remotecall_fetch(include, p, unsafe_string(opts.load)) - end - end - # eval expression - if opts.eval != C_NULL - repl = false - eval(Main, parse_input_line(unsafe_string(opts.eval))) - break - end - # eval expression and show result - if opts.print != C_NULL - repl = false - show(eval(Main, parse_input_line(unsafe_string(opts.print)))) - println() - break - end - # load file - if !isempty(ARGS) && !isempty(ARGS[1]) - # program - repl = false - # remove filename from ARGS - global PROGRAM_FILE = shift!(ARGS) - if !is_interactive - ccall(:jl_exit_on_sigint, Void, (Cint,), 1) - end - include(PROGRAM_FILE) - end - break - end - repl |= is_interactive - return (quiet,repl,startup,color_set,history_file) -end - -function load_juliarc() - # If the user built us with a specific Base.SYSCONFDIR, check that location first for a juliarc.jl file - # If it is not found, then continue on to the relative path based on JULIA_HOME - if !isempty(Base.SYSCONFDIR) && isfile(joinpath(JULIA_HOME,Base.SYSCONFDIR,"julia","juliarc.jl")) - include(abspath(JULIA_HOME,Base.SYSCONFDIR,"julia","juliarc.jl")) - else - try_include(abspath(JULIA_HOME,"..","etc","julia","juliarc.jl")) - end - try_include(abspath(homedir(),".juliarc.jl")) -end - -function load_machine_file(path::AbstractString) - machines = [] - for line in split(readstring(path),'\n'; keep=false) - s = split(line, '*'; keep = false) - map!(strip, s, s) - if length(s) > 1 - cnt = isnumber(s[1]) ? parse(Int,s[1]) : Symbol(s[1]) - push!(machines,(s[2], cnt)) - else - push!(machines,line) - end - end - return machines -end - -import .Terminals -import .REPL - -const repl_hooks = [] - -""" - atreplinit(f) - -Register a one-argument function to be called before the REPL interface is initialized in -interactive sessions; this is useful to customize the interface. The argument of `f` is the -REPL object. This function should be called from within the `.juliarc.jl` initialization -file. -""" -atreplinit(f::Function) = (unshift!(repl_hooks, f); nothing) - -function __atreplinit(repl) - for f in repl_hooks - try - f(repl) - catch err - showerror(STDERR, err) - println(STDERR) - end - end -end -_atreplinit(repl) = @eval Main $__atreplinit($repl) - -function _start() - empty!(ARGS) - append!(ARGS, Core.ARGS) - opts = JLOptions() - try - (quiet,repl,startup,color_set,history_file) = process_options(opts) - - local term - global active_repl - global active_repl_backend - if repl - if !isa(STDIN,TTY) - global is_interactive |= !isa(STDIN, Union{File, IOStream}) - color_set || (global have_color = false) - else - term = Terminals.TTYTerminal(get(ENV, "TERM", @static is_windows() ? "" : "dumb"), STDIN, STDOUT, STDERR) - global is_interactive = true - color_set || (global have_color = Terminals.hascolor(term)) - quiet || REPL.banner(term,term) - if term.term_type == "dumb" - active_repl = REPL.BasicREPL(term) - quiet || warn("Terminal not fully functional") - else - active_repl = REPL.LineEditREPL(term, true) - active_repl.history_file = history_file - active_repl.hascolor = have_color - end - # Make sure any displays pushed in .juliarc.jl ends up above the - # REPLDisplay - pushdisplay(REPL.REPLDisplay(active_repl)) - end - end - - if repl - if !isa(STDIN,TTY) - # note: currently IOStream is used for file STDIN - if isa(STDIN,File) || isa(STDIN,IOStream) - # reading from a file, behave like include - eval(Main,parse_input_line(readstring(STDIN))) - else - # otherwise behave repl-like - while !eof(STDIN) - eval_user_input(parse_input_line(STDIN), true) - end - end - else - _atreplinit(active_repl) - REPL.run_repl(active_repl, backend->(global active_repl_backend = backend)) - end - end - catch err - eval(Main, Expr(:body, Expr(:return, Expr(:call, Base.display_error, - QuoteNode(err), catch_backtrace())))) - exit(1) - end - if is_interactive && have_color - print(color_normal) - end -end diff --git a/julia-0.6.3/share/julia/base/combinatorics.jl b/julia-0.6.3/share/julia/base/combinatorics.jl deleted file mode 100644 index 7cf2ecc..0000000 --- a/julia-0.6.3/share/julia/base/combinatorics.jl +++ /dev/null @@ -1,285 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -# Factorials - -const _fact_table64 = - Int64[1,2,6,24,120,720,5040,40320,362880,3628800,39916800,479001600,6227020800, - 87178291200,1307674368000,20922789888000,355687428096000,6402373705728000, - 121645100408832000,2432902008176640000] - -const _fact_table128 = - UInt128[0x00000000000000000000000000000001, 0x00000000000000000000000000000002, - 0x00000000000000000000000000000006, 0x00000000000000000000000000000018, - 0x00000000000000000000000000000078, 0x000000000000000000000000000002d0, - 0x000000000000000000000000000013b0, 0x00000000000000000000000000009d80, - 0x00000000000000000000000000058980, 0x00000000000000000000000000375f00, - 0x00000000000000000000000002611500, 0x0000000000000000000000001c8cfc00, - 0x0000000000000000000000017328cc00, 0x0000000000000000000000144c3b2800, - 0x00000000000000000000013077775800, 0x00000000000000000000130777758000, - 0x00000000000000000001437eeecd8000, 0x00000000000000000016beecca730000, - 0x000000000000000001b02b9306890000, 0x000000000000000021c3677c82b40000, - 0x0000000000000002c5077d36b8c40000, 0x000000000000003ceea4c2b3e0d80000, - 0x000000000000057970cd7e2933680000, 0x00000000000083629343d3dcd1c00000, - 0x00000000000cd4a0619fb0907bc00000, 0x00000000014d9849ea37eeac91800000, - 0x00000000232f0fcbb3e62c3358800000, 0x00000003d925ba47ad2cd59dae000000, - 0x0000006f99461a1e9e1432dcb6000000, 0x00000d13f6370f96865df5dd54000000, - 0x0001956ad0aae33a4560c5cd2c000000, 0x0032ad5a155c6748ac18b9a580000000, - 0x0688589cc0e9505e2f2fee5580000000, 0xde1bc4d19efcac82445da75b00000000] - -function factorial_lookup(n::Integer, table, lim) - n < 0 && throw(DomainError()) - n > lim && throw(OverflowError()) - n == 0 && return one(n) - @inbounds f = table[n] - return oftype(n, f) -end - -factorial(n::Int128) = factorial_lookup(n, _fact_table128, 33) -factorial(n::UInt128) = factorial_lookup(n, _fact_table128, 34) -factorial(n::Union{Int64,UInt64}) = factorial_lookup(n, _fact_table64, 20) - -if Int === Int32 - factorial(n::Union{Int8,UInt8,Int16,UInt16}) = factorial(Int32(n)) - factorial(n::Union{Int32,UInt32}) = factorial_lookup(n, _fact_table64, 12) -else - factorial(n::Union{Int8,UInt8,Int16,UInt16,Int32,UInt32}) = factorial(Int64(n)) -end - -function gamma(n::Union{Int8,UInt8,Int16,UInt16,Int32,UInt32,Int64,UInt64}) - n < 0 && throw(DomainError()) - n == 0 && return Inf - n <= 2 && return 1.0 - n > 20 && return gamma(Float64(n)) - @inbounds return Float64(_fact_table64[n-1]) -end - - -# Basic functions for working with permutations - -""" - isperm(v) -> Bool - -Returns `true` if `v` is a valid permutation. - -# Examples -```jldoctest -julia> isperm([1; 2]) -true - -julia> isperm([1; 3]) -false -``` -""" -function isperm(A) - n = length(A) - used = falses(n) - for a in A - (0 < a <= n) && (used[a] ⊻= true) || return false - end - true -end - -isperm(p::Tuple{}) = true -isperm(p::Tuple{Int}) = p[1] == 1 -isperm(p::Tuple{Int,Int}) = ((p[1] == 1) & (p[2] == 2)) | ((p[1] == 2) & (p[2] == 1)) - -function permute!!(a, p::AbstractVector{<:Integer}) - count = 0 - start = 0 - while count < length(a) - ptr = start = findnext(p, start+1) - temp = a[start] - next = p[start] - count += 1 - while next != start - a[ptr] = a[next] - p[ptr] = 0 - ptr = next - next = p[next] - count += 1 - end - a[ptr] = temp - p[ptr] = 0 - end - a -end - -""" - permute!(v, p) - -Permute vector `v` in-place, according to permutation `p`. No checking is done -to verify that `p` is a permutation. - -To return a new permutation, use `v[p]`. Note that this is generally faster than -`permute!(v,p)` for large vectors. - -See also [`ipermute!`](@ref). - -# Example -```jldoctest -julia> A = [1, 1, 3, 4]; - -julia> perm = [2, 4, 3, 1]; - -julia> permute!(A, perm); - -julia> A -4-element Array{Int64,1}: - 1 - 4 - 3 - 1 -``` -""" -permute!(a, p::AbstractVector) = permute!!(a, copymutable(p)) - -function ipermute!!(a, p::AbstractVector{<:Integer}) - count = 0 - start = 0 - while count < length(a) - start = findnext(p, start+1) - temp = a[start] - next = p[start] - count += 1 - while next != start - temp_next = a[next] - a[next] = temp - temp = temp_next - ptr = p[next] - p[next] = 0 - next = ptr - count += 1 - end - a[next] = temp - p[next] = 0 - end - a -end - -""" - ipermute!(v, p) - -Like [`permute!`](@ref), but the inverse of the given permutation is applied. - -# Example -```jldoctest -julia> A = [1, 1, 3, 4]; - -julia> perm = [2, 4, 3, 1]; - -julia> ipermute!(A, perm); - -julia> A -4-element Array{Int64,1}: - 4 - 1 - 3 - 1 -``` -""" -ipermute!(a, p::AbstractVector) = ipermute!!(a, copymutable(p)) - -""" - invperm(v) - -Return the inverse permutation of `v`. -If `B = A[v]`, then `A == B[invperm(v)]`. - -# Example -```jldoctest -julia> v = [2; 4; 3; 1]; - -julia> invperm(v) -4-element Array{Int64,1}: - 4 - 1 - 3 - 2 - -julia> A = ['a','b','c','d']; - -julia> B = A[v] -4-element Array{Char,1}: - 'b' - 'd' - 'c' - 'a' - -julia> B[invperm(v)] -4-element Array{Char,1}: - 'a' - 'b' - 'c' - 'd' -``` -""" -function invperm(a::AbstractVector) - b = zero(a) # similar vector of zeros - n = length(a) - @inbounds for (i, j) in enumerate(a) - ((1 <= j <= n) && b[j] == 0) || - throw(ArgumentError("argument is not a permutation")) - b[j] = i - end - b -end - -function invperm(p::Union{Tuple{},Tuple{Int},Tuple{Int,Int}}) - isperm(p) || throw(ArgumentError("argument is not a permutation")) - p # in dimensions 0-2, every permutation is its own inverse -end -invperm(a::Tuple) = (invperm([a...])...,) - -#XXX This function should be moved to Combinatorics.jl but is currently used by Base.DSP. -""" - nextprod([k_1, k_2,...], n) - -Next integer greater than or equal to `n` that can be written as ``\\prod k_i^{p_i}`` for integers -``p_1``, ``p_2``, etc. - -# Example -```jldoctest -julia> nextprod([2, 3], 105) -108 - -julia> 2^2 * 3^3 -108 -``` -""" -function nextprod(a::Vector{Int}, x) - if x > typemax(Int) - throw(ArgumentError("unsafe for x > typemax(Int), got $x")) - end - k = length(a) - v = ones(Int, k) # current value of each counter - mx = [nextpow(ai,x) for ai in a] # maximum value of each counter - v[1] = mx[1] # start at first case that is >= x - p::widen(Int) = mx[1] # initial value of product in this case - best = p - icarry = 1 - - while v[end] < mx[end] - if p >= x - best = p < best ? p : best # keep the best found yet - carrytest = true - while carrytest - p = div(p, v[icarry]) - v[icarry] = 1 - icarry += 1 - p *= a[icarry] - v[icarry] *= a[icarry] - carrytest = v[icarry] > mx[icarry] && icarry < k - end - if p < x - icarry = 1 - end - else - while p < x - p *= a[1] - v[1] *= a[1] - end - end - end - # might overflow, but want predictable return type - return mx[end] < best ? Int(mx[end]) : Int(best) -end diff --git a/julia-0.6.3/share/julia/base/complex.jl b/julia-0.6.3/share/julia/base/complex.jl deleted file mode 100644 index af737b3..0000000 --- a/julia-0.6.3/share/julia/base/complex.jl +++ /dev/null @@ -1,914 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -""" - Complex{T<:Real} <: Number - -Complex number type with real and imaginary part of type `T`. - -`Complex32`, `Complex64` and `Complex128` are aliases for -`Complex{Float16}`, `Complex{Float32}` and `Complex{Float64}` respectively. -""" -struct Complex{T<:Real} <: Number - re::T - im::T -end -Complex(x::Real, y::Real) = Complex(promote(x,y)...) -Complex(x::Real) = Complex(x, zero(x)) - -""" - im - -The imaginary unit. -""" -const im = Complex(false,true) - -const Complex128 = Complex{Float64} -const Complex64 = Complex{Float32} -const Complex32 = Complex{Float16} - -convert(::Type{Complex{T}}, x::Real) where {T<:Real} = Complex{T}(x,0) -convert(::Type{Complex{T}}, z::Complex) where {T<:Real} = Complex{T}(real(z),imag(z)) -convert(::Type{T}, z::Complex) where {T<:Real} = - isreal(z) ? convert(T,real(z)) : throw(InexactError()) - -convert(::Type{Complex}, z::Complex) = z -convert(::Type{Complex}, x::Real) = Complex(x) - -promote_rule(::Type{Complex{T}}, ::Type{S}) where {T<:Real,S<:Real} = - Complex{promote_type(T,S)} -promote_rule(::Type{Complex{T}}, ::Type{Complex{S}}) where {T<:Real,S<:Real} = - Complex{promote_type(T,S)} - -widen(::Type{Complex{T}}) where {T} = Complex{widen(T)} - -""" - real(z) - -Return the real part of the complex number `z`. - -```jldoctest -julia> real(1 + 3im) -1 -``` -""" -real(z::Complex) = z.re - -""" - imag(z) - -Return the imaginary part of the complex number `z`. - -```jldoctest -julia> imag(1 + 3im) -3 -``` -""" -imag(z::Complex) = z.im -real(x::Real) = x -imag(x::Real) = zero(x) - -""" - reim(z) - -Return both the real and imaginary parts of the complex number `z`. - -```jldoctest -julia> reim(1 + 3im) -(1, 3) -``` -""" -reim(z) = (real(z), imag(z)) - -""" - real(T::Type) - -Returns the type that represents the real part of a value of type `T`. -e.g: for `T == Complex{R}`, returns `R`. -Equivalent to `typeof(real(zero(T)))`. - -```jldoctest -julia> real(Complex{Int}) -Int64 - -julia> real(Float64) -Float64 -``` -""" -real(T::Type) = typeof(real(zero(T))) -real(::Type{T}) where {T<:Real} = T -real(::Type{Complex{T}}) where {T<:Real} = T - -""" - isreal(x) -> Bool - -Test whether `x` or all its elements are numerically equal to some real number. - -```jldoctest -julia> isreal(5.) -true - -julia> isreal([4.; complex(0,1)]) -false -``` -""" -isreal(x::Real) = true -isreal(z::Complex) = iszero(imag(z)) -isinteger(z::Complex) = isreal(z) & isinteger(real(z)) -isfinite(z::Complex) = isfinite(real(z)) & isfinite(imag(z)) -isnan(z::Complex) = isnan(real(z)) | isnan(imag(z)) -isinf(z::Complex) = isinf(real(z)) | isinf(imag(z)) -iszero(z::Complex) = iszero(real(z)) & iszero(imag(z)) - -""" - complex(r, [i]) - -Convert real numbers or arrays to complex. `i` defaults to zero. -""" -complex(z::Complex) = z -complex(x::Real) = Complex(x) -complex(x::Real, y::Real) = Complex(x, y) - -""" - complex(T::Type) - -Returns an appropriate type which can represent a value of type `T` as a complex number. -Equivalent to `typeof(complex(zero(T)))`. - -```jldoctest -julia> complex(Complex{Int}) -Complex{Int64} - -julia> complex(Int) -Complex{Int64} -``` -""" -complex(::Type{T}) where {T<:Real} = Complex{T} -complex(::Type{Complex{T}}) where {T<:Real} = Complex{T} - -flipsign(x::Complex, y::Real) = ifelse(signbit(y), -x, x) - -function show(io::IO, z::Complex) - r, i = reim(z) - compact = get(io, :compact, false) - show(io, r) - if signbit(i) && !isnan(i) - i = -i - print(io, compact ? "-" : " - ") - else - print(io, compact ? "+" : " + ") - end - show(io, i) - if !(isa(i,Integer) && !isa(i,Bool) || isa(i,AbstractFloat) && isfinite(i)) - print(io, "*") - end - print(io, "im") -end -show(io::IO, z::Complex{Bool}) = - print(io, z == im ? "im" : "Complex($(z.re),$(z.im))") - -function read(s::IO, ::Type{Complex{T}}) where T<:Real - r = read(s,T) - i = read(s,T) - Complex{T}(r,i) -end -function write(s::IO, z::Complex) - write(s,real(z),imag(z)) -end - -## byte order swaps: real and imaginary part are swapped individually -bswap(z::Complex) = Complex(bswap(real(z)), bswap(imag(z))) - -## equality and hashing of complex numbers ## - -==(z::Complex, w::Complex) = (real(z) == real(w)) & (imag(z) == imag(w)) -==(z::Complex, x::Real) = isreal(z) && real(z) == x -==(x::Real, z::Complex) = isreal(z) && real(z) == x - -isequal(z::Complex, w::Complex) = isequal(real(z),real(w)) & isequal(imag(z),imag(w)) - -if UInt === UInt64 - const h_imag = 0x32a7a07f3e7cd1f9 -else - const h_imag = 0x3e7cd1f9 -end -const hash_0_imag = hash(0, h_imag) - -function hash(z::Complex, h::UInt) - # TODO: with default argument specialization, this would be better: - # hash(real(z), h ⊻ hash(imag(z), h ⊻ h_imag) ⊻ hash(0, h ⊻ h_imag)) - hash(real(z), h ⊻ hash(imag(z), h_imag) ⊻ hash_0_imag) -end - -## generic functions of complex numbers ## - -""" - conj(z) - -Compute the complex conjugate of a complex number `z`. - -```jldoctest -julia> conj(1 + 3im) -1 - 3im -``` -""" -conj(z::Complex) = Complex(real(z),-imag(z)) -abs(z::Complex) = hypot(real(z), imag(z)) -abs2(z::Complex) = real(z)*real(z) + imag(z)*imag(z) -inv(z::Complex) = conj(z)/abs2(z) -inv(z::Complex{<:Integer}) = inv(float(z)) - --(z::Complex) = Complex(-real(z), -imag(z)) -+(z::Complex, w::Complex) = Complex(real(z) + real(w), imag(z) + imag(w)) --(z::Complex, w::Complex) = Complex(real(z) - real(w), imag(z) - imag(w)) -*(z::Complex, w::Complex) = Complex(real(z) * real(w) - imag(z) * imag(w), - real(z) * imag(w) + imag(z) * real(w)) - -muladd(z::Complex, w::Complex, x::Complex) = - Complex(muladd(real(z), real(w), real(x)) - imag(z)*imag(w), # TODO: use mulsub given #15985 - muladd(real(z), imag(w), muladd(imag(z), real(w), imag(x)))) - -# handle Bool and Complex{Bool} -# avoid type signature ambiguity warnings -+(x::Bool, z::Complex{Bool}) = Complex(x + real(z), imag(z)) -+(z::Complex{Bool}, x::Bool) = Complex(real(z) + x, imag(z)) --(x::Bool, z::Complex{Bool}) = Complex(x - real(z), - imag(z)) --(z::Complex{Bool}, x::Bool) = Complex(real(z) - x, imag(z)) -*(x::Bool, z::Complex{Bool}) = Complex(x * real(z), x * imag(z)) -*(z::Complex{Bool}, x::Bool) = Complex(real(z) * x, imag(z) * x) - -+(x::Bool, z::Complex) = Complex(x + real(z), imag(z)) -+(z::Complex, x::Bool) = Complex(real(z) + x, imag(z)) --(x::Bool, z::Complex) = Complex(x - real(z), - imag(z)) --(z::Complex, x::Bool) = Complex(real(z) - x, imag(z)) -*(x::Bool, z::Complex) = Complex(x * real(z), x * imag(z)) -*(z::Complex, x::Bool) = Complex(real(z) * x, imag(z) * x) - -+(x::Real, z::Complex{Bool}) = Complex(x + real(z), imag(z)) -+(z::Complex{Bool}, x::Real) = Complex(real(z) + x, imag(z)) -function -(x::Real, z::Complex{Bool}) - # we don't want the default type for -(Bool) - re = x-real(z) - Complex(re, - oftype(re, imag(z))) -end --(z::Complex{Bool}, x::Real) = Complex(real(z) - x, imag(z)) -*(x::Real, z::Complex{Bool}) = Complex(x * real(z), x * imag(z)) -*(z::Complex{Bool}, x::Real) = Complex(real(z) * x, imag(z) * x) - -# adding or multiplying real & complex is common -+(x::Real, z::Complex) = Complex(x + real(z), imag(z)) -+(z::Complex, x::Real) = Complex(x + real(z), imag(z)) -function -(x::Real, z::Complex) - # we don't want the default type for -(Bool) - re = x - real(z) - Complex(re, - oftype(re, imag(z))) -end --(z::Complex, x::Real) = Complex(real(z) - x, imag(z)) -*(x::Real, z::Complex) = Complex(x * real(z), x * imag(z)) -*(z::Complex, x::Real) = Complex(x * real(z), x * imag(z)) - -muladd(x::Real, z::Complex, y::Number) = muladd(z, x, y) -muladd(z::Complex, x::Real, y::Real) = Complex(muladd(real(z),x,y), imag(z)*x) -muladd(z::Complex, x::Real, w::Complex) = - Complex(muladd(real(z),x,real(w)), muladd(imag(z),x,imag(w))) -muladd(x::Real, y::Real, z::Complex) = Complex(muladd(x,y,real(z)), imag(z)) -muladd(z::Complex, w::Complex, x::Real) = - Complex(muladd(real(z), real(w), x) - imag(z)*imag(w), # TODO: use mulsub given #15985 - muladd(real(z), imag(w), imag(z) * real(w))) - -/(a::R, z::S) where {R<:Real,S<:Complex} = (T = promote_type(R,S); a*inv(T(z))) -/(z::Complex, x::Real) = Complex(real(z)/x, imag(z)/x) - -function /(a::Complex{T}, b::Complex{T}) where T<:Real - are = real(a); aim = imag(a); bre = real(b); bim = imag(b) - if abs(bre) <= abs(bim) - if isinf(bre) && isinf(bim) - r = sign(bre)/sign(bim) - else - r = bre / bim - end - den = bim + r*bre - Complex((are*r + aim)/den, (aim*r - are)/den) - else - if isinf(bre) && isinf(bim) - r = sign(bim)/sign(bre) - else - r = bim / bre - end - den = bre + r*bim - Complex((are + aim*r)/den, (aim - are*r)/den) - end -end - -inv(z::Complex{<:Union{Float16,Float32}}) = - oftype(z, conj(widen(z))/abs2(widen(z))) - -/(z::Complex{T}, w::Complex{T}) where {T<:Union{Float16,Float32}} = - oftype(z, widen(z)*inv(widen(w))) - -# robust complex division for double precision -# the first step is to scale variables if appropriate ,then do calculations -# in a way that avoids over/underflow (subfuncs 1 and 2), then undo the scaling. -# scaling variable s and other techniques -# based on arxiv.1210.4539 -# a + i*b -# p + i*q = --------- -# c + i*d -function /(z::Complex128, w::Complex128) - a, b = reim(z); c, d = reim(w) - half = 0.5 - two = 2.0 - ab = max(abs(a), abs(b)) - cd = max(abs(c), abs(d)) - ov = realmax(a) - un = realmin(a) - ϵ = eps(Float64) - bs = two/(ϵ*ϵ) - s = 1.0 - ab >= half*ov && (a=half*a; b=half*b; s=two*s ) # scale down a,b - cd >= half*ov && (c=half*c; d=half*d; s=s*half) # scale down c,d - ab <= un*two/ϵ && (a=a*bs; b=b*bs; s=s/bs ) # scale up a,b - cd <= un*two/ϵ && (c=c*bs; d=d*bs; s=s*bs ) # scale up c,d - abs(d)<=abs(c) ? ((p,q)=robust_cdiv1(a,b,c,d) ) : ((p,q)=robust_cdiv1(b,a,d,c); q=-q) - return Complex128(p*s,q*s) # undo scaling -end -function robust_cdiv1(a::Float64, b::Float64, c::Float64, d::Float64) - r = d/c - t = 1.0/(c+d*r) - p = robust_cdiv2(a,b,c,d,r,t) - q = robust_cdiv2(b,-a,c,d,r,t) - return p,q -end -function robust_cdiv2(a::Float64, b::Float64, c::Float64, d::Float64, r::Float64, t::Float64) - if r != 0 - br = b*r - return (br != 0 ? (a+br)*t : a*t + (b*t)*r) - else - return (a + d*(b/c)) * t - end -end - -function inv(w::Complex128) - c, d = reim(w) - half = 0.5 - two = 2.0 - cd = max(abs(c), abs(d)) - ov = realmax(c) - un = realmin(c) - ϵ = eps(Float64) - bs = two/(ϵ*ϵ) - s = 1.0 - cd >= half*ov && (c=half*c; d=half*d; s=s*half) # scale down c,d - cd <= un*two/ϵ && (c=c*bs; d=d*bs; s=s*bs ) # scale up c,d - if abs(d)<=abs(c) - r = d/c - t = 1.0/(c+d*r) - p = t - q = -r * t - else - c, d = d, c - r = d/c - t = 1.0/(c+d*r) - p = r * t - q = -t - end - return Complex128(p*s,q*s) # undo scaling -end - -function ssqs(x::T, y::T) where T<:AbstractFloat - k::Int = 0 - ρ = x*x + y*y - if !isfinite(ρ) && (isinf(x) || isinf(y)) - ρ = convert(T, Inf) - elseif isinf(ρ) || (ρ==0 && (x!=0 || y!=0)) || ρ= 0 -# return Complex(r, iz/r/2) -# end -# return Complex(abs(iz)/r/2, copysign(r,iz)) -# end - -# compute exp(im*theta) -cis(theta::Real) = Complex(cos(theta),sin(theta)) - -""" - cis(z) - -Return ``\\exp(iz)``. -""" -function cis(z::Complex) - v = exp(-imag(z)) - Complex(v*cos(real(z)), v*sin(real(z))) -end - -""" - angle(z) - -Compute the phase angle in radians of a complex number `z`. -""" -angle(z::Complex) = atan2(imag(z), real(z)) - -function log(z::Complex{T}) where T<:AbstractFloat - const T1::T = 1.25 - const T2::T = 3 - const ln2::T = log(convert(T,2)) #0.6931471805599453 - x, y = reim(z) - ρ, k = ssqs(x,y) - ax = abs(x) - ay = abs(y) - if ax < ay - θ, β = ax, ay - else - θ, β = ay, ax - end - if k==0 && (0.5 < β*β) && (β <= T1 || ρ < T2) - ρρ = log1p((β-1)*(β+1)+θ*θ)/2 - else - ρρ = log(ρ)/2 + k*ln2 - end - Complex(ρρ, angle(z)) -end -log(z::Complex) = log(float(z)) - -# function log(z::Complex) -# ar = abs(real(z)) -# ai = abs(imag(z)) -# if ar < ai -# r = ar/ai -# re = log(ai) + log1p(r*r)/2 -# else -# if ar == 0 -# re = isnan(ai) ? ai : -inv(ar) -# elseif isinf(ai) -# re = oftype(ar,Inf) -# else -# r = ai/ar -# re = log(ar) + log1p(r*r)/2 -# end -# end -# Complex(re, angle(z)) -# end - -function log10(z::Complex) - a = log(z) - a/log(oftype(real(a),10)) -end -function log2(z::Complex) - a = log(z) - a/log(oftype(real(a),2)) -end - -function exp(z::Complex) - zr, zi = reim(z) - if isnan(zr) - Complex(zr, zi==0 ? zi : zr) - elseif !isfinite(zi) - if zr == Inf - Complex(-zr, oftype(zr,NaN)) - elseif zr == -Inf - Complex(-zero(zr), copysign(zero(zi), zi)) - else - Complex(oftype(zr,NaN), oftype(zi,NaN)) - end - else - er = exp(zr) - if iszero(zi) - Complex(er, zi) - else - Complex(er*cos(zi), er*sin(zi)) - end - end -end - -function expm1(z::Complex{T}) where T<:Real - Tf = float(T) - zr,zi = reim(z) - if isnan(zr) - Complex(zr, zi==0 ? zi : zr) - elseif !isfinite(zi) - if zr == Inf - Complex(-zr, oftype(zr,NaN)) - elseif zr == -Inf - Complex(-one(zr), copysign(zero(zi), zi)) - else - Complex(oftype(zr,NaN), oftype(zi,NaN)) - end - else - erm1 = expm1(zr) - if zi == 0 - Complex(erm1, zi) - else - er = erm1+one(erm1) - if isfinite(er) - wr = erm1 - 2 * er * (sin(convert(Tf, 0.5) * zi))^2 - return Complex(wr, er * sin(zi)) - else - return Complex(er * cos(zi), er * sin(zi)) - end - end - end -end - -function log1p(z::Complex{T}) where T - zr,zi = reim(z) - if isfinite(zr) - isinf(zi) && return log(z) - # This is based on a well-known trick for log1p of real z, - # allegedly due to Kahan, only modified to handle real(u) <= 0 - # differently to avoid inaccuracy near z==-2 and for correct branch cut - u = float(one(T)) + z - u == 1 ? convert(typeof(u), z) : real(u) <= 0 ? log(u) : log(u)*z/(u-1) - elseif isnan(zr) - Complex(zr, zr) - elseif isfinite(zi) - Complex(T(Inf), copysign(zr > 0 ? zero(T) : convert(T, pi), zi)) - else - Complex(T(Inf), T(NaN)) - end -end - -function ^(z::Complex{T}, p::Complex{T})::Complex{T} where T<:AbstractFloat - if p == 2 #square - zr, zi = reim(z) - x = (zr-zi)*(zr+zi) - y = 2*zr*zi - if isnan(x) - if isinf(y) - x = copysign(zero(T),zr) - elseif isinf(zi) - x = convert(T,-Inf) - elseif isinf(zr) - x = convert(T,Inf) - end - elseif isnan(y) && isinf(x) - y = copysign(zero(T), y) - end - Complex(x,y) - elseif z!=0 - if p!=0 && isinteger(p) - rp = real(p) - if rp < 0 - return power_by_squaring(inv(z), convert(Integer, -rp)) - else - return power_by_squaring(z, convert(Integer, rp)) - end - end - exp(p*log(z)) - elseif p!=0 #0^p - zero(z) #CHECK SIGNS - else #0^0 - zer = copysign(zero(T),real(p))*copysign(zero(T),imag(z)) - Complex(one(T), zer) - end -end - -function exp2(z::Complex{T}) where T<:AbstractFloat - er = exp2(real(z)) - theta = imag(z) * log(convert(T, 2)) - Complex(er*cos(theta), er*sin(theta)) -end -exp2(z::Complex) = exp2(float(z)) - -function exp10(z::Complex{T}) where T<:AbstractFloat - er = exp10(real(z)) - theta = imag(z) * log(convert(T, 10)) - Complex(er*cos(theta), er*sin(theta)) -end -exp10(z::Complex) = exp10(float(z)) - -function ^(z::T, p::T) where T<:Complex - if isinteger(p) - rp = real(p) - if rp < 0 - return power_by_squaring(inv(float(z)), convert(Integer, -rp)) - else - return power_by_squaring(float(z), convert(Integer, rp)) - end - end - pr, pim = reim(p) - zr, zi = reim(z) - r = abs(z) - rp = r^pr - theta = atan2(zi, zr) - ntheta = pr*theta - if pim != 0 && r != 0 - rp = rp*exp(-pim*theta) - ntheta = ntheta + pim*log(r) - end - cosntheta = cos(ntheta) - sinntheta = sin(ntheta) - re, im = rp*cosntheta, rp*sinntheta - if isinf(rp) - if isnan(re) - re = copysign(zero(re), cosntheta) - end - if isnan(im) - im = copysign(zero(im), sinntheta) - end - end - - # apply some corrections to force known zeros - if pim == 0 - if isinteger(pr) - if zi == 0 - im = copysign(zero(im), im) - elseif zr == 0 - if isinteger(0.5*pr) # pr is even - im = copysign(zero(im), im) - else - re = copysign(zero(re), re) - end - end - else - dr = pr*2 - if isinteger(dr) && zi == 0 - if zr < 0 - re = copysign(zero(re), re) - else - im = copysign(zero(im), im) - end - end - end - end - - Complex(re, im) -end - -^(z::Complex, n::Bool) = n ? z : one(z) -^(z::Complex, n::Integer) = z^Complex(n) - -^(z::Complex{<:AbstractFloat}, n::Bool) = n ? z : one(z) # to resolve ambiguity -^(z::Complex{<:Integer}, n::Bool) = n ? z : one(z) # to resolve ambiguity - -^(z::Complex{<:AbstractFloat}, n::Integer) = - n>=0 ? power_by_squaring(z,n) : power_by_squaring(inv(z),-n) -^(z::Complex{<:Integer}, n::Integer) = power_by_squaring(z,n) # DomainError for n<0 - -function sin(z::Complex{T}) where T - F = float(T) - zr, zi = reim(z) - if zr == 0 - Complex(F(zr), sinh(zi)) - elseif !isfinite(zr) - if zi == 0 || isinf(zi) - Complex(F(NaN), F(zi)) - else - Complex(F(NaN), F(NaN)) - end - else - Complex(sin(zr)*cosh(zi), cos(zr)*sinh(zi)) - end -end - - -function cos(z::Complex{T}) where T - F = float(T) - zr, zi = reim(z) - if zr == 0 - Complex(cosh(zi), isnan(zi) ? F(zr) : -flipsign(F(zr),zi)) - elseif !isfinite(zr) - if zi == 0 - Complex(F(NaN), isnan(zr) ? zero(F) : -flipsign(F(zi),zr)) - elseif isinf(zi) - Complex(F(Inf), F(NaN)) - else - Complex(F(NaN), F(NaN)) - end - else - Complex(cos(zr)*cosh(zi), -sin(zr)*sinh(zi)) - end -end - - -function tan(z::Complex) - zr, zi = reim(z) - w = tanh(Complex(-zi, zr)) - Complex(imag(w), -real(w)) -end - -function asin(z::Complex) - zr, zi = reim(z) - if isinf(zr) && isinf(zi) - return Complex(copysign(oftype(zr,pi)/4, zr),zi) - elseif isnan(zi) && isinf(zr) - return Complex(zi, oftype(zr, Inf)) - end - ξ = zr == 0 ? zr : - !isfinite(zr) ? oftype(zr,pi)/2 * sign(zr) : - atan2(zr, real(sqrt(1-z)*sqrt(1+z))) - η = asinh(copysign(imag(sqrt(conj(1-z))*sqrt(1+z)), imag(z))) - Complex(ξ,η) -end - -function acos(z::Complex{<:AbstractFloat}) - zr, zi = reim(z) - if isnan(zr) - if isinf(zi) return Complex(zr, -zi) - else return Complex(zr, zr) end - elseif isnan(zi) - if isinf(zr) return Complex(zi, abs(zr)) - elseif zr==0 return Complex(oftype(zr,pi)/2, zi) - else return Complex(zi, zi) end - elseif zr==zi==0 - return Complex(oftype(zr,pi)/2, -zi) - elseif zr==Inf && zi===0.0 - return Complex(zi, -zr) - elseif zr==-Inf && zi===-0.0 - return Complex(oftype(zi,pi), -zr) - end - ξ = 2*atan2(real(sqrt(1-z)), real(sqrt(1+z))) - η = asinh(imag(sqrt(conj(1+z))*sqrt(1-z))) - if isinf(zr) && isinf(zi) ξ -= oftype(η,pi)/4 * sign(zr) end - Complex(ξ,η) -end -acos(z::Complex) = acos(float(z)) - -function atan(z::Complex) - w = atanh(Complex(-imag(z),real(z))) - Complex(imag(w),-real(w)) -end - -function sinh(z::Complex) - zr, zi = reim(z) - w = sin(Complex(zi, zr)) - Complex(imag(w),real(w)) -end - -function cosh(z::Complex) - zr, zi = reim(z) - cos(Complex(zi,-zr)) -end - -function tanh(z::Complex{T}) where T<:AbstractFloat - const Ω = prevfloat(typemax(T)) - ξ, η = reim(z) - if isnan(ξ) && η==0 return Complex(ξ, η) end - if 4*abs(ξ) > asinh(Ω) #Overflow? - Complex(copysign(one(T),ξ), - copysign(zero(T),η*(isfinite(η) ? sin(2*abs(η)) : one(η)))) - else - t = tan(η) - β = 1+t*t #sec(η)^2 - s = sinh(ξ) - ρ = sqrt(1 + s*s) #cosh(ξ) - if isinf(t) - Complex(ρ/s,1/t) - else - Complex(β*ρ*s,t)/(1+β*s*s) - end - end -end -tanh(z::Complex) = tanh(float(z)) - -function asinh(z::Complex) - w = asin(Complex(-imag(z),real(z))) - Complex(imag(w),-real(w)) -end - -function acosh(z::Complex) - zr, zi = reim(z) - if isnan(zr) || isnan(zi) - if isinf(zr) || isinf(zi) - return Complex(oftype(zr, Inf), oftype(zi, NaN)) - else - return Complex(oftype(zr, NaN), oftype(zi, NaN)) - end - elseif zr==-Inf && zi===-0.0 #Edge case is wrong - WHY? - return Complex(oftype(zr,Inf), oftype(zi, -pi)) - end - ξ = asinh(real(sqrt(conj(z-1))*sqrt(z+1))) - η = 2atan2(imag(sqrt(z-1)),real(sqrt(z+1))) - if isinf(zr) && isinf(zi) - η -= oftype(η,pi)/4 * sign(zi) * sign(zr) - end - Complex(ξ, η) -end - -function atanh(z::Complex{T}) where T<:AbstractFloat - const Ω = prevfloat(typemax(T)) - const θ = sqrt(Ω)/4 - const ρ = 1/θ - x, y = reim(z) - ax = abs(x) - ay = abs(y) - if ax > θ || ay > θ #Prevent overflow - if isnan(y) - if isinf(x) - return Complex(copysign(zero(x),x), y) - else - return Complex(real(1/z), y) - end - end - if isinf(y) - return Complex(copysign(zero(x),x), copysign(oftype(y,pi)/2, y)) - end - return Complex(real(1/z), copysign(oftype(y,pi)/2, y)) - elseif ax==1 - if y == 0 - ξ = copysign(oftype(x,Inf),x) - η = zero(y) - else - ym = ay+ρ - ξ = log(sqrt(sqrt(4+y*y))/sqrt(ym)) - η = copysign(oftype(y,pi)/2 + atan(ym/2), y)/2 - end - else #Normal case - ysq = (ay+ρ)^2 - if x == 0 - ξ = x - else - ξ = log1p(4x/((1-x)^2 + ysq))/4 - end - η = angle(Complex((1-x)*(1+x)-ysq, 2y))/2 - end - Complex(ξ, η) -end -atanh(z::Complex) = atanh(float(z)) - -function lexcmp(a::Complex, b::Complex) - c = cmp(real(a), real(b)) - c == 0 || return c - cmp(imag(a), imag(b)) -end - -#Rounding complex numbers -#Requires two different RoundingModes for the real and imaginary components -""" - round(z, RoundingModeReal, RoundingModeImaginary) - -Returns the nearest integral value of the same type as the complex-valued `z` to `z`, -breaking ties using the specified [`RoundingMode`](@ref)s. The first -[`RoundingMode`](@ref) is used for rounding the real components while the -second is used for rounding the imaginary components. -""" -function round(z::Complex{<:AbstractFloat}, ::RoundingMode{MR}, ::RoundingMode{MI}) where {MR,MI} - Complex(round(real(z), RoundingMode{MR}()), - round(imag(z), RoundingMode{MI}())) -end -round(z::Complex) = Complex(round(real(z)), round(imag(z))) - -function round(z::Complex, digits::Integer, base::Integer=10) - Complex(round(real(z), digits, base), - round(imag(z), digits, base)) -end - -float(z::Complex{<:AbstractFloat}) = z -float(z::Complex) = Complex(float(real(z)), float(imag(z))) - -big(z::Complex{<:AbstractFloat}) = Complex{BigFloat}(z) -big(z::Complex{<:Integer}) = Complex{BigInt}(z) - -## Array operations on complex numbers ## - -complex(A::AbstractArray{<:Complex}) = A - -function complex(A::AbstractArray{T}) where T - if !isleaftype(T) - error("`complex` not defined on abstractly-typed arrays; please convert to a more specific type") - end - convert(AbstractArray{typeof(complex(zero(T)))}, A) -end - -## promotion to complex ## - -_default_type(T::Type{Complex}) = Complex{Int} diff --git a/julia-0.6.3/share/julia/base/coreimg.jl b/julia-0.6.3/share/julia/base/coreimg.jl deleted file mode 100644 index 8b552d5..0000000 --- a/julia-0.6.3/share/julia/base/coreimg.jl +++ /dev/null @@ -1,70 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -Main.Core.eval(Main.Core, :(baremodule Inference -using Core.Intrinsics -import Core: print, println, show, write, unsafe_write, STDOUT, STDERR - -ccall(:jl_set_istopmod, Void, (Bool,), false) - -eval(x) = Core.eval(Inference, x) -eval(m, x) = Core.eval(m, x) - -const include = Core.include -# conditional to allow redefining Core.Inference after base exists -isdefined(Main, :Base) || ((::Type{T})(arg) where {T} = convert(T, arg)::T) - -function return_type end - -## Load essential files and libraries -include("essentials.jl") -include("ctypes.jl") -include("generator.jl") -include("reflection.jl") -include("options.jl") - -# core operations & types -include("promotion.jl") -include("tuple.jl") -include("pair.jl") -include("traits.jl") -include("range.jl") -include("expr.jl") -include("error.jl") - -# core numeric operations & types -include("bool.jl") -include("number.jl") -include("int.jl") -include("operators.jl") -include("pointer.jl") -const checked_add = + -const checked_sub = - - -# core array operations -include("indices.jl") -include("array.jl") -include("abstractarray.jl") - -include("hashing.jl") -include("nofloat_hashing.jl") - -# map-reduce operators -macro simd(forloop) - esc(forloop) -end -include("reduce.jl") - -## core structures -include("bitarray.jl") -include("intset.jl") -include("associative.jl") - -# core docsystem -include("docs/core.jl") - -# compiler -include("inference.jl") -ccall(:jl_set_typeinf_func, Void, (Any,), typeinf_ext) - -end # baremodule Inference -)) diff --git a/julia-0.6.3/share/julia/base/coreio.jl b/julia-0.6.3/share/julia/base/coreio.jl deleted file mode 100644 index b15fca1..0000000 --- a/julia-0.6.3/share/julia/base/coreio.jl +++ /dev/null @@ -1,32 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -show(x) = show(STDOUT::IO, x) -print(xs...) = print(STDOUT::IO, xs...) -println(xs...) = println(STDOUT::IO, xs...) -println(io::IO) = print(io, '\n') - -struct DevNullStream <: IO end -const DevNull = DevNullStream() -isreadable(::DevNullStream) = false -iswritable(::DevNullStream) = true -isopen(::DevNullStream) = true -read(::DevNullStream, ::Type{UInt8}) = throw(EOFError()) -write(::DevNullStream, ::UInt8) = 1 -unsafe_write(::DevNullStream, ::Ptr{UInt8}, n::UInt)::Int = n -close(::DevNullStream) = nothing -flush(::DevNullStream) = nothing -wait_connected(::DevNullStream) = nothing -wait_readnb(::DevNullStream) = wait() -wait_readbyte(::DevNullStream) = wait() -wait_close(::DevNullStream) = wait() -eof(::DevNullStream) = true - -let CoreIO = Union{Core.CoreSTDOUT, Core.CoreSTDERR} - global write, unsafe_write - write(io::CoreIO, x::UInt8) = Core.write(io, x) - unsafe_write(io::CoreIO, x::Ptr{UInt8}, nb::UInt) = Core.unsafe_write(io, x, nb) -end - -STDIN = DevNull -STDOUT = Core.STDOUT -STDERR = Core.STDERR diff --git a/julia-0.6.3/share/julia/base/ctypes.jl b/julia-0.6.3/share/julia/base/ctypes.jl deleted file mode 100644 index 26640ed..0000000 --- a/julia-0.6.3/share/julia/base/ctypes.jl +++ /dev/null @@ -1,115 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -# essential type definitions for interacting with C code -# (platform- or OS-dependent types are defined in c.jl) - -""" - Cuchar - -Equivalent to the native `unsigned char` c-type ([`UInt8`](@ref)). -""" -const Cuchar = UInt8 - - -""" - Cshort - -Equivalent to the native `signed short` c-type ([`Int16`](@ref)). -""" -const Cshort = Int16 - - -""" - Cushort - -Equivalent to the native `unsigned short` c-type ([`UInt16`](@ref)). -""" -const Cushort = UInt16 - - -""" - Cint - -Equivalent to the native `signed int` c-type ([`Int32`](@ref)). -""" -const Cint = Int32 - - -""" - Cuint - -Equivalent to the native `unsigned int` c-type ([`UInt32`](@ref)). -""" -const Cuint = UInt32 - - -""" - Cptrdiff_t - -Equivalent to the native `ptrdiff_t` c-type (`Int`). -""" -const Cptrdiff_t = Int - - -""" - Csize_t - -Equivalent to the native `size_t` c-type (`UInt`). -""" -const Csize_t = UInt - - -""" - Cssize_t - -Equivalent to the native `ssize_t` c-type. -""" -const Cssize_t = Int - - -""" - Cintmax_t - -Equivalent to the native `intmax_t` c-type ([`Int64`](@ref)). -""" -const Cintmax_t = Int64 - - -""" - Cuintmax_t - -Equivalent to the native `uintmax_t` c-type ([`UInt64`](@ref)). -""" -const Cuintmax_t = UInt64 - - -""" - Clonglong - -Equivalent to the native `signed long long` c-type ([`Int64`](@ref)). -""" -const Clonglong = Int64 - - -""" - Culonglong - -Equivalent to the native `unsigned long long` c-type ([`UInt64`](@ref)). -""" -const Culonglong = UInt64 - - -""" - Cfloat - -Equivalent to the native `float` c-type ([`Float32`](@ref)). -""" -const Cfloat = Float32 - - -""" - Cdouble - -Equivalent to the native `double` c-type ([`Float64`](@ref)). -""" -const Cdouble = Float64 diff --git a/julia-0.6.3/share/julia/base/dSFMT.jl b/julia-0.6.3/share/julia/base/dSFMT.jl deleted file mode 100644 index bd22f22..0000000 --- a/julia-0.6.3/share/julia/base/dSFMT.jl +++ /dev/null @@ -1,172 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -module dSFMT - -import Base: copy, copy!, == - -export DSFMT_state, dsfmt_get_min_array_size, dsfmt_get_idstring, - dsfmt_init_gen_rand, dsfmt_init_by_array, dsfmt_gv_init_by_array, - dsfmt_fill_array_close_open!, dsfmt_fill_array_close1_open2!, - win32_SystemFunction036! - -"Mersenne Exponent" -const MEXP = 19937 -"DSFMT internal state array size of N 128-bit integers." -const N = floor(Int, ((MEXP - 128) / 104 + 1)) -"""Julia DSFMT state representation size counted in 32-bit integers. - -Size: (DSFMT state array of Int128 + 1)*4 + Int32 index + Int32 padding -""" -const JN32 = (N+1)*4+1+1 -"Jump polynomial for 10^20 steps for dSFMT with exponent 19937" -const JPOLY1e21 = "e172e20c5d2de26b567c0cace9e7c6cc4407bd5ffcd22ca59d37b73d54fdbd937cd3abc6f502e8c186dbd4f1a06b9e2b894f31be77424f94dddfd5a45888a84ca66eeeb242eefe6764ed859dafccae7a6a635b3a63fe9dfbbd5f2d3f2610d39388f53060e84edae75be4f4f2272c0f1f26d1231836ad040ab091550f8a3a5423fb3ab83e068fe2684057f15691c4dc757a3aee4bca8595bf1ad03500d9620a5dbe3b2d64380694895d2f379ca928238293ea267ce14236d5be816a61f018fe4f6bc3c9865f5d4d4186e320ab653d1f3c035ae83e2ad725648a67d3480331e763a1dcdfb5711b56796170b124f5febd723a664a2deefbfa9999d922a108b0e683582ae8d3baacb5bb56683405ea9e6e0d71ddb24b2229c72bb9d07061f2d1fa097ade823b607a2029d6e121ae09d93de01a154199e8e6a6e77c970bda72ba8079b2b3a15dd494a3188b1d94a25ae108a8a5bd0b050e6ce64a365a21420e07fdeebecae02eb68a4304b59283055d22c27d680ea35952834d828c9b9b9dd1a886b4f7fe82fe8f2a962e1e5390e563dc281c799aee2a441b7a813facb6ff5e94c059710dcfe7e6b1635e21ae0dc878dd5f7cc0e1101a74452495a67d23a2672c939f32c81d4a2611073990e92a084cc3a62fd42ee566f29d963a9cc5100ccd0a200f49ce0a74fa891efa1b974d342b7fedf9269e40d9b34e3c59c3d37201aecd5a04f4ae3d0c9a68c7ab78c662390e4cf36cb63ea3539c442efd0bf4aace4b8c8bde93c3d84b4d6290adfae1c5e3fcd457b6f3159e501f17b72ff6bc13d6bf61fbdafabefd16ac1dae0bca667e4e16a2b800732f1d0a9274c8a4c6cccd2db62fc275dc308c31c11cd6fda78de2f81f0e542b76b42b2cc09ed8f965d94c714c9918064f53af5379cfbbc31edf9cbce694f63a75f122048de6e57b094908f749661456813a908027f5d8397ab7962bf75ac779a3e1b7ae3fbc93397a67b486bb849befff1de6162ef2819715a88f41881e366ace692a900796a2806393898dd1750ac2b4ca3d34ca48942322fb6375f0c9a00c9701048ee8d7d7a17e11739177a7ad5027556e85835daf8594d84a97fe6621c0fce1495ae6ab8676cdc992d247acf5a4e5ec8c4755fde28117228d2c3ecf89edb91e93d949e2174924572265e36d176d082ed1be884e51d885ba3cda175c51edcee5042eaf519d292aa05aa4185b03858d710a9d0880b3d4e5111f858a52fe352cbe0a24f06a3d977ae2eb85e2a03a68131d0ab91dac4941067cf90ecd0fce156bcd40b8968cd4aa11e0b4353b14508d79d13ac00af4a4d452496b7f2393699889aa1e508427dbf0be3db91d955feb51e559af57640c6b3f9d5f95609852c28f9462a9869dd93acbdb1aafb2381ebb886a0b3fcec278f8bb0f62c23e157e49b89245b0881268ce594acbddd3605b9eaa77c9ff513e0dbad514914136d96fe2843fe2b4e886a0b718a9b8d1132132110618d0d3595da284cd2a4c9d09386199e4f4d7723983d3a374b51cf20dac5cabb4ff7e7197c2ebd9318463409baa583d6a6115c1b768282ff37b0fe152c97671e400d5ccba7d6875df0bf95c5d91257fedb124de393f31908d0e36251326aa29dd5be86291c80b4bf78f419ec151eeaeff643a58b48ab35ad2cd2c0b77b1965966ef3db6b6373cb2c4b590cef2f16f4d6f62f13a6cbf1a481565b5935edd4e76f7b6a8fd0d74bc336b40a803aec38125c006c877dfdcdb9ba2b7aecab5cafe6076e024c73e3567adf97f607a71d180402c22a20a8388f517484cc4198f97c2fe4f3407e0dc577e61f0f71354aa601cf4e3e42e1edd8722d50f5af3441f68caa568cc1c3a19956c1233f265bb47236afab24ee42b27b0042b90693d77c1923147360ae6503f6ba6abbc9dd52a7b4c36a3b6b55f6a80cfa7f101dd9f1bfc7d7eaf09a5d636b510228f245bfb37b4625025d2c911435cdf6f878113753e0804ab8ecab870ad733b9728d7636b17578b41239393e7de47cbce871137d2b61729dda67b2b84cd3363aad64c5dd5bd172f1f091305b1ff78982abe7dab1588036d097cf497e300e6c78a926048febd1b9462c07f5868928357b74297c87f503056b89f786d22a538b6702e290bca04639a0f1d0939b67f409e5e58e472a6a07fa543e2531c2567ec73c41f6769b6ba94c5aa0a030d006f5b6b1c5fb218b86a8f63a48bc867466f20f699859e87956f48a182d26ed451861dd21201ecc7239037ada67319bdf0849c387c73a110af798b4c5f9018bc97993e060ea2a2937fa2eb095d65ec07009fc407a350f1d6fb3c98a0a5f204be985b0cb6962f0eb7844a179c4598a92ea32d2d706c800034d2e960ded5b476d77073316b933fb3e6ba2f4f24a3b73a1e4d8ed1491d757ecf56fd72465dac0000736744d28d29073091587c8bccad302f7054e8a32bb8724974d9f3e449fc70b2a41f0008b548f717ac0a2c3a6580bfb50774933a578ad6acdcb89940bb406ea540893f097d8a88d1609ed605f25499de939083a0c8a7c6db462df5dfa06c298dd233e249433a54267d5cdc22e5524705b7d6b16b96bb2cb83e00cef62e21d91528a74cf95bfd1d391590c93f4058e9bb02656fd087a5b63d738d1c3b5cf533fd59c81cf9136bfcd3e955c19daf9906ef175791fde6a1d98155d7881e241c3522551cf9fcae42e1e46929ea39fd00943446823f9755085ccc8456a3090b73a3031a201d9c704a4ad4868dd9b6d06205560013973f60d637de2f18354bf4523d9d81dc2a7e78cd42c586364bbe0ed86fde0f081f801c1a4abb830839b7796d9a01f141bec8bd93144104c6dc59170162c0a5a639eb63a0a164970de50eb2e04f027394b26ed48d341f7851994df79d7cd663672a556f25e5e16a3adbe1003d631de938fabfed234df12b5ff3027f4a2da823834cb098e0f977a4eb9614579d5c7a1d400a1a933a657aef8ea1a66743d73b0cf37a7d64e9a63e4c7b09945f0db750b311b39783fb5ea216616751967d480a630d3da7c89d1c7beae20369137e96734a4cfedca56a7887f076fe4fe97534ad3e4f74d1a81750581a5ea214b440c7f30331ab86c257534c71175d1e731303a48b01c589fda4fb0d4368b4dd63d91204cb6fc389b2202aa94391907bfb72902a4031f5589ed5f391c2ce92aa998c200ba3c77d8bd747b9d0a29fa85cda3949a6d2bd0c3402e68f98fd451aa27b6c2dfd170e004577cbdb25e3a1b9852e9f66a370789c47bfce722446dade1b32ceae71ee0e1d96edf7ed08a93e3690056f46c3d8e63f88e53673ee71d72cfedbeba493ee91333120e09e9ce9f9c9a7a400f814ea618b1de48f9805e092f4e20f301fbb65caa83735a2a5c89befe4bce4116dca3688e1e14c6f09a945671dedbb5c0ba526842b6cae31d8b5ff978bae928a17a75c134630dd9de988f6ad3d89a071b33775a9660a40b48ec61ad3f93ac81cb1c65d8b0bab5c214786abd13cc10a8ea2e2a370e86e2fa1a372d83c9697b5e37b281e51507685f714fdaebe49ffc93a5582e1936eaee8e4140a4b72" - -mutable struct DSFMT_state - val::Vector{Int32} - - DSFMT_state(val::Vector{Int32} = zeros(Int32, JN32)) = - new(length(val) == JN32 ? val : throw(DomainError())) -end - -copy!(dst::DSFMT_state, src::DSFMT_state) = (copy!(dst.val, src.val); dst) -copy(src::DSFMT_state) = DSFMT_state(copy(src.val)) - -==(s1::DSFMT_state, s2::DSFMT_state) = s1.val == s2.val - -function dsfmt_get_idstring() - idstring = ccall((:dsfmt_get_idstring,:libdSFMT), - Ptr{UInt8}, - ()) - return unsafe_string(idstring) -end - -function dsfmt_get_min_array_size() - min_array_size = ccall((:dsfmt_get_min_array_size,:libdSFMT), - Int32, - ()) -end - -const dsfmt_min_array_size = dsfmt_get_min_array_size() - -function dsfmt_init_gen_rand(s::DSFMT_state, seed::UInt32) - ccall((:dsfmt_init_gen_rand,:libdSFMT), - Void, - (Ptr{Void}, UInt32,), - s.val, seed) -end - -function dsfmt_init_by_array(s::DSFMT_state, seed::Vector{UInt32}) - ccall((:dsfmt_init_by_array,:libdSFMT), - Void, - (Ptr{Void}, Ptr{UInt32}, Int32), - s.val, seed, length(seed)) -end - -function dsfmt_gv_init_by_array(seed::Vector{UInt32}) - ccall((:dsfmt_gv_init_by_array,:libdSFMT), - Void, - (Ptr{UInt32}, Int32), - seed, length(seed)) -end - -function dsfmt_fill_array_close1_open2!(s::DSFMT_state, A::Ptr{Float64}, n::Int) - @assert Csize_t(A) % 16 == 0 # the underlying C array must be 16-byte aligned - @assert dsfmt_min_array_size <= n && iseven(n) - ccall((:dsfmt_fill_array_close1_open2,:libdSFMT), - Void, - (Ptr{Void}, Ptr{Float64}, Int), - s.val, A, n) -end - -function dsfmt_fill_array_close_open!(s::DSFMT_state, A::Ptr{Float64}, n::Int) - @assert Csize_t(A) % 16 == 0 # the underlying C array must be 16-byte aligned - @assert dsfmt_min_array_size <= n && iseven(n) - ccall((:dsfmt_fill_array_close_open,:libdSFMT), - Void, - (Ptr{Void}, Ptr{Float64}, Int), - s.val, A, n) -end - -# dSFMT jump -function dsfmt_jump(s::DSFMT_state, jp::AbstractString) - val = s.val - nval = length(val) - index = val[nval - 1] - work = zeros(UInt64, JN32 >> 1) - dsfmt = Vector{UInt64}(nval >> 1) - ccall(:memcpy, Ptr{Void}, (Ptr{UInt64}, Ptr{Int32}, Csize_t), - dsfmt, val, (nval - 1) * sizeof(Int32)) - dsfmt[end] = UInt64(N*2) - - for c in jp - bits = parse(UInt8,c,16) - for j in 1:4 - (bits & 0x01) != 0x00 && dsfmt_jump_add!(work, dsfmt) - bits = bits >> 0x01 - dsfmt_jump_next_state!(dsfmt) - end - end - - work[end] = index - return DSFMT_state(reinterpret(Int32, work)) -end - -function dsfmt_jump_add!(dest::Vector{UInt64}, src::Vector{UInt64}) - dp = dest[end] >> 1 - sp = src[end] >> 1 - diff = ((sp - dp + N) % N) - i = 1 - while i <= N-diff - j = i*2-1 - p = j + diff*2 - dest[j] ⊻= src[p] - dest[j+1] ⊻= src[p+1] - i += 1 - end - while i <= N - j = i*2-1 - p = j + (diff - N)*2 - dest[j] ⊻= src[p] - dest[j+1] ⊻= src[p+1] - i += 1 - end - dest[N*2+1] ⊻= src[N*2+1] - dest[N*2+2] ⊻= src[N*2+2] - return dest -end - -function dsfmt_jump_next_state!(mts::Vector{UInt64}) - POS1 = 117 - SL1 = 19 - SR = 12 - MSK1 = 0x000ffafffffffb3f - MSK2 = 0x000ffdfffc90fffd - - idx = (mts[end] >> 1) % N - - a = idx*2+1 - b = ((idx + POS1) % N)*2+1 - u = N*2+1 - - t0 = mts[a] - t1 = mts[a+1] - L0 = mts[u] - L1 = mts[u+1] - mts[u] = xor(t0 << SL1, L1 >> 32, L1 << 32, mts[b]) - mts[u+1] = xor(t1 << SL1, L0 >> 32, L0 << 32, mts[b+1]) - mts[a] = xor(mts[u] >> SR, mts[u] & MSK1, t0) - mts[a+1] = xor(mts[u+1] >> SR, mts[u+1] & MSK2, t1) - - mts[end] = (mts[end] + 2) % (N*2) - return mts -end - -## Windows entropy - -if is_windows() - function win32_SystemFunction036!(a::Array) - ccall((:SystemFunction036, :Advapi32), stdcall, UInt8, (Ptr{Void}, UInt32), a, sizeof(a)) - end -end - -end # module diff --git a/julia-0.6.3/share/julia/base/datafmt.jl b/julia-0.6.3/share/julia/base/datafmt.jl deleted file mode 100644 index 9253c4b..0000000 --- a/julia-0.6.3/share/julia/base/datafmt.jl +++ /dev/null @@ -1,710 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -## file formats ## - -module DataFmt - -import Base: _default_delims, tryparse_internal, show - -export countlines, readdlm, readcsv, writedlm, writecsv - -invalid_dlm(::Type{Char}) = reinterpret(Char, 0xfffffffe) -invalid_dlm(::Type{UInt8}) = 0xfe -invalid_dlm(::Type{UInt16}) = 0xfffe -invalid_dlm(::Type{UInt32}) = 0xfffffffe - -const offs_chunk_size = 5000 - -countlines(f::AbstractString, eol::Char='\n') = open(io->countlines(io,eol), f)::Int - -""" - countlines(io::IO, eol::Char='\\n') - -Read `io` until the end of the stream/file and count the number of lines. To specify a file -pass the filename as the first argument. EOL markers other than `'\\n'` are supported by -passing them as the second argument. -""" -function countlines(io::IO, eol::Char='\n') - isascii(eol) || throw(ArgumentError("only ASCII line terminators are supported")) - aeol = UInt8(eol) - a = Vector{UInt8}(8192) - nl = 0 - while !eof(io) - nb = readbytes!(io, a) - @simd for i=1:nb - @inbounds nl += a[i] == aeol - end - end - nl -end - -""" - readdlm(source, T::Type; options...) - -The columns are assumed to be separated by one or more whitespaces. The end of line -delimiter is taken as `\\n`. -""" -readdlm(input, T::Type; opts...) = readdlm(input, invalid_dlm(Char), T, '\n'; opts...) - -""" - readdlm(source, delim::Char, T::Type; options...) - -The end of line delimiter is taken as `\\n`. -""" -readdlm(input, dlm::Char, T::Type; opts...) = readdlm(input, dlm, T, '\n'; opts...) - -""" - readdlm(source; options...) - -The columns are assumed to be separated by one or more whitespaces. The end of line -delimiter is taken as `\\n`. If all data is numeric, the result will be a numeric array. If -some elements cannot be parsed as numbers, a heterogeneous array of numbers and strings -is returned. -""" -readdlm(input; opts...) = readdlm(input, invalid_dlm(Char), '\n'; opts...) - -""" - readdlm(source, delim::Char; options...) - -The end of line delimiter is taken as `\\n`. If all data is numeric, the result will be a -numeric array. If some elements cannot be parsed as numbers, a heterogeneous array of -numbers and strings is returned. -""" -readdlm(input, dlm::Char; opts...) = readdlm(input, dlm, '\n'; opts...) - -""" - readdlm(source, delim::Char, eol::Char; options...) - -If all data is numeric, the result will be a numeric array. If some elements cannot be -parsed as numbers, a heterogeneous array of numbers and strings is returned. -""" -readdlm(input, dlm::Char, eol::Char; opts...) = - readdlm_auto(input, dlm, Float64, eol, true; opts...) - -""" - readdlm(source, delim::Char, T::Type, eol::Char; header=false, skipstart=0, skipblanks=true, use_mmap, quotes=true, dims, comments=true, comment_char='#') - -Read a matrix from the source where each line (separated by `eol`) gives one row, with -elements separated by the given delimiter. The source can be a text file, stream or byte -array. Memory mapped files can be used by passing the byte array representation of the -mapped segment as source. - -If `T` is a numeric type, the result is an array of that type, with any non-numeric elements -as `NaN` for floating-point types, or zero. Other useful values of `T` include -`String`, `AbstractString`, and `Any`. - -If `header` is `true`, the first row of data will be read as header and the tuple -`(data_cells, header_cells)` is returned instead of only `data_cells`. - -Specifying `skipstart` will ignore the corresponding number of initial lines from the input. - -If `skipblanks` is `true`, blank lines in the input will be ignored. - -If `use_mmap` is `true`, the file specified by `source` is memory mapped for potential -speedups. Default is `true` except on Windows. On Windows, you may want to specify `true` if -the file is large, and is only read once and not written to. - -If `quotes` is `true`, columns enclosed within double-quote (\") characters are allowed to -contain new lines and column delimiters. Double-quote characters within a quoted field must -be escaped with another double-quote. Specifying `dims` as a tuple of the expected rows and -columns (including header, if any) may speed up reading of large files. If `comments` is -`true`, lines beginning with `comment_char` and text following `comment_char` in any line -are ignored. -""" -readdlm(input, dlm::Char, T::Type, eol::Char; opts...) = - readdlm_auto(input, dlm, T, eol, false; opts...) - -readdlm_auto(input::Vector{UInt8}, dlm::Char, T::Type, eol::Char, auto::Bool; opts...) = - readdlm_string(String(input), dlm, T, eol, auto, val_opts(opts)) -readdlm_auto(input::IO, dlm::Char, T::Type, eol::Char, auto::Bool; opts...) = - readdlm_string(readstring(input), dlm, T, eol, auto, val_opts(opts)) -function readdlm_auto(input::AbstractString, dlm::Char, T::Type, eol::Char, auto::Bool; opts...) - optsd = val_opts(opts) - use_mmap = get(optsd, :use_mmap, is_windows() ? false : true) - fsz = filesize(input) - if use_mmap && fsz > 0 && fsz < typemax(Int) - a = open(input, "r") do f - Mmap.mmap(f, Vector{UInt8}, (Int(fsz),)) - end - # TODO: It would be nicer to use String(a) without making a copy, - # but because the mmap'ed array is not NUL-terminated this causes - # jl_try_substrtod to segfault below. - return readdlm_string(unsafe_string(pointer(a),length(a)), dlm, T, eol, auto, optsd) - else - return readdlm_string(readstring(input), dlm, T, eol, auto, optsd) - end -end - -# -# Handlers act on events generated by the parser. -# Parser calls store_cell on the handler to pass events. -# -# DLMOffsets: Keep offsets (when result dimensions are not known) -# DLMStore: Store values directly into a result store (when result dimensions are known) -abstract type DLMHandler end - -mutable struct DLMOffsets <: DLMHandler - oarr::Vector{Vector{Int}} - offidx::Int - thresh::Int - bufflen::Int - - function DLMOffsets(sbuff::String) - offsets = Vector{Vector{Int}}(1) - offsets[1] = Vector{Int}(offs_chunk_size) - thresh = ceil(min(typemax(UInt), Base.Sys.total_memory()) / sizeof(Int) / 5) - new(offsets, 1, thresh, sizeof(sbuff)) - end -end - -function store_cell(dlmoffsets::DLMOffsets, row::Int, col::Int, - quoted::Bool, startpos::Int, endpos::Int) - offidx = dlmoffsets.offidx - (offidx == 0) && return # offset collection stopped to avoid choking on memory - - oarr = dlmoffsets.oarr - offsets = oarr[end] - if length(offsets) < offidx - offlen = offs_chunk_size * length(oarr) - if (offlen + offs_chunk_size) > dlmoffsets.thresh - est_tot = round(Int, offlen * dlmoffsets.bufflen / endpos) - if (est_tot - offlen) > offs_chunk_size # allow another chunk - # abandon offset collection - dlmoffsets.oarr = Vector{Int}[] - dlmoffsets.offidx = 0 - return - end - end - offsets = Vector{Int}(offs_chunk_size) - push!(oarr, offsets) - offidx = 1 - end - offsets[offidx] = row - offsets[offidx+1] = col - offsets[offidx+2] = Int(quoted) - offsets[offidx+3] = startpos - offsets[offidx+4] = endpos - dlmoffsets.offidx = offidx + 5 - nothing -end - -function result(dlmoffsets::DLMOffsets) - trimsz = (dlmoffsets.offidx-1) % offs_chunk_size - ((trimsz > 0) || (dlmoffsets.offidx == 1)) && resize!(dlmoffsets.oarr[end], trimsz) - dlmoffsets.oarr -end - -mutable struct DLMStore{T} <: DLMHandler - hdr::Array{AbstractString, 2} - data::Array{T, 2} - - nrows::Int - ncols::Int - lastrow::Int - lastcol::Int - hdr_offset::Int - sbuff::String - auto::Bool - eol::Char -end - -function DLMStore{T}(::Type{T}, dims::NTuple{2,Integer}, - has_header::Bool, sbuff::String, auto::Bool, eol::Char) - (nrows,ncols) = dims - nrows <= 0 && throw(ArgumentError("number of rows in dims must be > 0, got $nrows")) - ncols <= 0 && throw(ArgumentError("number of columns in dims must be > 0, got $ncols")) - hdr_offset = has_header ? 1 : 0 - DLMStore{T}(fill(SubString(sbuff,1,0), 1, ncols), Matrix{T}(nrows-hdr_offset, ncols), - nrows, ncols, 0, 0, hdr_offset, sbuff, auto, eol) -end - -_chrinstr(sbuff::String, chr::UInt8, startpos::Int, endpos::Int) = - (endpos >= startpos) && (C_NULL != ccall(:memchr, Ptr{UInt8}, - (Ptr{UInt8}, Int32, Csize_t), pointer(sbuff)+startpos-1, chr, endpos-startpos+1)) - -function store_cell(dlmstore::DLMStore{T}, row::Int, col::Int, - quoted::Bool, startpos::Int, endpos::Int) where T - drow = row - dlmstore.hdr_offset - - ncols = dlmstore.ncols - lastcol = dlmstore.lastcol - lastrow = dlmstore.lastrow - cells::Matrix{T} = dlmstore.data - sbuff = dlmstore.sbuff - - endpos = prevind(sbuff, nextind(sbuff,endpos)) - if (endpos > 0) && ('\n' == dlmstore.eol) && ('\r' == Char(sbuff[endpos])) - endpos = prevind(sbuff, endpos) - end - if quoted - startpos += 1 - endpos = prevind(sbuff, endpos) - end - - if drow > 0 - # fill missing elements - while ((drow - lastrow) > 1) || ((drow > lastrow > 0) && (lastcol < ncols)) - if (lastcol == ncols) || (lastrow == 0) - lastcol = 0 - lastrow += 1 - end - for cidx in (lastcol+1):ncols - if (T <: AbstractString) || (T == Any) - cells[lastrow, cidx] = SubString(sbuff, 1, 0) - elseif ((T <: Number) || (T <: Char)) && dlmstore.auto - throw(TypeError(:store_cell, "", Any, T)) - else - error("missing value at row $lastrow column $cidx") - end - end - lastcol = ncols - end - - # fill data - if quoted && _chrinstr(sbuff, UInt8('"'), startpos, endpos) - unescaped = replace(SubString(sbuff, startpos, endpos), r"\"\"", "\"") - fail = colval(unescaped, 1, endof(unescaped), cells, drow, col) - else - fail = colval(sbuff, startpos, endpos, cells, drow, col) - end - if fail - sval = SubString(sbuff, startpos, endpos) - if (T <: Number) && dlmstore.auto - throw(TypeError(:store_cell, "", Any, T)) - else - error("file entry \"$(sval)\" cannot be converted to $T") - end - end - - dlmstore.lastrow = drow - dlmstore.lastcol = col - else - # fill header - if quoted && _chrinstr(sbuff, UInt8('"'), startpos, endpos) - unescaped = replace(SubString(sbuff, startpos, endpos), r"\"\"", "\"") - colval(unescaped, 1, endof(unescaped), dlmstore.hdr, 1, col) - else - colval(sbuff, startpos, endpos, dlmstore.hdr, 1, col) - end - end - - nothing -end - -function result(dlmstore::DLMStore{T}) where T - nrows = dlmstore.nrows - dlmstore.hdr_offset - ncols = dlmstore.ncols - lastcol = dlmstore.lastcol - lastrow = dlmstore.lastrow - cells = dlmstore.data - sbuff = dlmstore.sbuff - - if (nrows > 0) && ((lastcol < ncols) || (lastrow < nrows)) - while lastrow <= nrows - (lastcol == ncols) && (lastcol = 0; lastrow += 1) - for cidx in (lastcol+1):ncols - if (T <: AbstractString) || (T == Any) - cells[lastrow, cidx] = SubString(sbuff, 1, 0) - elseif ((T <: Number) || (T <: Char)) && dlmstore.auto - throw(TypeError(:store_cell, "", Any, T)) - else - error("missing value at row $lastrow column $cidx") - end - end - lastcol = ncols - (lastrow == nrows) && break - end - dlmstore.lastrow = lastrow - dlmstore.lastcol = ncols - end - (dlmstore.hdr_offset > 0) ? (dlmstore.data, dlmstore.hdr) : dlmstore.data -end - - -function readdlm_string(sbuff::String, dlm::Char, T::Type, eol::Char, auto::Bool, optsd::Dict) - ign_empty = (dlm == invalid_dlm(Char)) - quotes = get(optsd, :quotes, true) - comments = get(optsd, :comments, true) - comment_char = get(optsd, :comment_char, '#') - dims = get(optsd, :dims, nothing) - - has_header = get(optsd, :header, get(optsd, :has_header, false)) - haskey(optsd, :has_header) && (optsd[:has_header] != has_header) && throw(ArgumentError("conflicting values for header and has_header")) - - skipstart = get(optsd, :skipstart, 0) - (skipstart >= 0) || throw(ArgumentError("skipstart must be ≥ 0, got $skipstart")) - - skipblanks = get(optsd, :skipblanks, true) - - offset_handler = (dims === nothing) ? DLMOffsets(sbuff) : DLMStore(T, dims, has_header, sbuff, auto, eol) - - for retry in 1:2 - try - dims = dlm_parse(sbuff, eol, dlm, '"', comment_char, ign_empty, quotes, comments, skipstart, skipblanks, offset_handler) - break - catch ex - if isa(ex, TypeError) && (ex.func == :store_cell) - T = ex.expected - else - rethrow(ex) - end - offset_handler = (dims === nothing) ? DLMOffsets(sbuff) : DLMStore(T, dims, has_header, sbuff, auto, eol) - end - end - - isa(offset_handler, DLMStore) && (return result(offset_handler)) - - offsets = result(offset_handler) - !isempty(offsets) && (return dlm_fill(T, offsets, dims, has_header, sbuff, auto, eol)) - - optsd[:dims] = dims - return readdlm_string(sbuff, dlm, T, eol, auto, optsd) -end - -const valid_opts = [:header, :has_header, :use_mmap, :quotes, :comments, :dims, :comment_char, :skipstart, :skipblanks] -const valid_opt_types = [Bool, Bool, Bool, Bool, Bool, NTuple{2,Integer}, Char, Integer, Bool] - -function val_opts(opts) - d = Dict{Symbol,Union{Bool,NTuple{2,Integer},Char,Integer}}() - for (opt_name, opt_val) in opts - in(opt_name, valid_opts) || - throw(ArgumentError("unknown option $opt_name")) - opt_typ = valid_opt_types[findfirst(valid_opts, opt_name)] - isa(opt_val, opt_typ) || - throw(ArgumentError("$opt_name should be of type $opt_typ, got $(typeof(opt_val))")) - d[opt_name] = opt_val - end - return d -end - -function dlm_fill(T::DataType, offarr::Vector{Vector{Int}}, dims::NTuple{2,Integer}, has_header::Bool, sbuff::String, auto::Bool, eol::Char) - idx = 1 - offidx = 1 - offsets = offarr[1] - row = 0 - col = 0 - try - dh = DLMStore(T, dims, has_header, sbuff, auto, eol) - while idx <= length(offsets) - row = offsets[idx] - col = offsets[idx+1] - quoted = offsets[idx+2] != 0 - startpos = offsets[idx+3] - endpos = offsets[idx+4] - - ((idx += 5) > offs_chunk_size) && (offidx < length(offarr)) && (idx = 1; offsets = offarr[offidx += 1]) - - store_cell(dh, row, col, quoted, startpos, endpos) - end - return result(dh) - catch ex - isa(ex, TypeError) && (ex.func == :store_cell) && (return dlm_fill(ex.expected, offarr, dims, has_header, sbuff, auto, eol)) - error("at row $row, column $col : $ex") - end -end - -function colval(sbuff::String, startpos::Int, endpos::Int, cells::Array{Bool,2}, row::Int, col::Int) - n = tryparse_internal(Bool, sbuff, startpos, endpos, 0, false) - isnull(n) || (cells[row, col] = get(n)) - isnull(n) -end -function colval{T<:Integer}(sbuff::String, startpos::Int, endpos::Int, cells::Array{T,2}, row::Int, col::Int) - n = tryparse_internal(T, sbuff, startpos, endpos, 0, false) - isnull(n) || (cells[row, col] = get(n)) - isnull(n) -end -function colval(sbuff::String, startpos::Int, endpos::Int, cells::Array{Float64,2}, row::Int, col::Int) - n = ccall(:jl_try_substrtod, Nullable{Float64}, (Ptr{UInt8},Csize_t,Csize_t), sbuff, startpos-1, endpos-startpos+1) - isnull(n) || (cells[row, col] = get(n)) - isnull(n) -end -function colval(sbuff::String, startpos::Int, endpos::Int, cells::Array{Float32,2}, row::Int, col::Int) - n = ccall(:jl_try_substrtof, Nullable{Float32}, (Ptr{UInt8}, Csize_t, Csize_t), sbuff, startpos-1, endpos-startpos+1) - isnull(n) || (cells[row, col] = get(n)) - isnull(n) -end -function colval(sbuff::String, startpos::Int, endpos::Int, cells::Array{<:AbstractString,2}, row::Int, col::Int) - cells[row, col] = SubString(sbuff, startpos, endpos) - return false -end -function colval(sbuff::String, startpos::Int, endpos::Int, cells::Array{Any,2}, row::Int, col::Int) - # if array is of Any type, attempt parsing only the most common types: Int, Bool, Float64 and fallback to SubString - len = endpos-startpos+1 - if len > 0 - # check Inteter - ni64 = tryparse_internal(Int, sbuff, startpos, endpos, 0, false) - isnull(ni64) || (cells[row, col] = get(ni64); return false) - - # check Bool - nb = tryparse_internal(Bool, sbuff, startpos, endpos, 0, false) - isnull(nb) || (cells[row, col] = get(nb); return false) - - # check float64 - nf64 = ccall(:jl_try_substrtod, Nullable{Float64}, (Ptr{UInt8}, Csize_t, Csize_t), sbuff, startpos-1, endpos-startpos+1) - isnull(nf64) || (cells[row, col] = get(nf64); return false) - end - cells[row, col] = SubString(sbuff, startpos, endpos) - false -end -function colval(sbuff::String, startpos::Int, endpos::Int, cells::Array{<:Char,2}, row::Int, col::Int) - if startpos == endpos - cells[row, col] = next(sbuff, startpos)[1] - return false - else - return true - end -end -colval(sbuff::String, startpos::Int, endpos::Int, cells::Array, row::Int, col::Int) = true - -function dlm_parse(dbuff::String, eol::D, dlm::D, qchar::D, cchar::D, - ign_adj_dlm::Bool, allow_quote::Bool, allow_comments::Bool, - skipstart::Int, skipblanks::Bool, dh::DLMHandler) where D - ncols = nrows = col = 0 - is_default_dlm = (dlm == invalid_dlm(D)) - error_str = "" - # 0: begin field, 1: quoted field, 2: unquoted field, - # 3: second quote (could either be end of field or escape character), - # 4: comment, 5: skipstart - state = (skipstart > 0) ? 5 : 0 - is_eol = is_dlm = is_cr = is_quote = is_comment = expct_col = false - idx = 1 - try - slen = sizeof(dbuff) - col_start_idx = 1 - was_cr = false - while idx <= slen - val,idx = next(dbuff, idx) - if (is_eol = (Char(val) == Char(eol))) - is_dlm = is_comment = is_cr = is_quote = false - elseif (is_dlm = (is_default_dlm ? in(Char(val), _default_delims) : (Char(val) == Char(dlm)))) - is_comment = is_cr = is_quote = false - elseif (is_quote = (Char(val) == Char(qchar))) - is_comment = is_cr = false - elseif (is_comment = (Char(val) == Char(cchar))) - is_cr = false - else - is_cr = (Char(eol) == '\n') && (Char(val) == '\r') - end - - if 2 == state # unquoted field - if is_dlm - state = 0 - col += 1 - store_cell(dh, nrows+1, col, false, col_start_idx, idx-2) - col_start_idx = idx - !ign_adj_dlm && (expct_col = true) - elseif is_eol - nrows += 1 - col += 1 - store_cell(dh, nrows, col, false, col_start_idx, idx - (was_cr ? 3 : 2)) - col_start_idx = idx - ncols = max(ncols, col) - col = 0 - state = 0 - elseif (is_comment && allow_comments) - nrows += 1 - col += 1 - store_cell(dh, nrows, col, false, col_start_idx, idx - 2) - ncols = max(ncols, col) - col = 0 - state = 4 - end - elseif 1 == state # quoted field - is_quote && (state = 3) - elseif 4 == state # comment line - if is_eol - col_start_idx = idx - state = 0 - end - elseif 0 == state # begin field - if is_quote - state = (allow_quote && !was_cr) ? 1 : 2 - expct_col = false - elseif is_dlm - if !ign_adj_dlm - expct_col = true - col += 1 - store_cell(dh, nrows+1, col, false, col_start_idx, idx-2) - end - col_start_idx = idx - elseif is_eol - if (col > 0) || !skipblanks - nrows += 1 - if expct_col - col += 1 - store_cell(dh, nrows, col, false, col_start_idx, idx - (was_cr ? 3 : 2)) - end - ncols = max(ncols, col) - col = 0 - end - col_start_idx = idx - expct_col = false - elseif is_comment && allow_comments - if col > 0 - nrows += 1 - if expct_col - col += 1 - store_cell(dh, nrows, col, false, col_start_idx, idx - 2) - end - ncols = max(ncols, col) - col = 0 - end - expct_col = false - state = 4 - elseif !is_cr - state = 2 - expct_col = false - end - elseif 3 == state # second quote - if is_quote && !was_cr - state = 1 - elseif is_dlm && !was_cr - state = 0 - col += 1 - store_cell(dh, nrows+1, col, true, col_start_idx, idx-2) - col_start_idx = idx - !ign_adj_dlm && (expct_col = true) - elseif is_eol - nrows += 1 - col += 1 - store_cell(dh, nrows, col, true, col_start_idx, idx - (was_cr ? 3 : 2)) - col_start_idx = idx - ncols = max(ncols, col) - col = 0 - state = 0 - elseif is_comment && allow_comments && !was_cr - nrows += 1 - col += 1 - store_cell(dh, nrows, col, true, col_start_idx, idx - 2) - ncols = max(ncols, col) - col = 0 - state = 4 - elseif (is_cr && was_cr) || !is_cr - error_str = escape_string("unexpected character '$(Char(val))' after quoted field at row $(nrows+1) column $(col+1)") - break - end - elseif 5 == state # skip start - if is_eol - col_start_idx = idx - skipstart -= 1 - (0 == skipstart) && (state = 0) - end - end - was_cr = is_cr - end - - if isempty(error_str) - if 1 == state # quoted field - error_str = "truncated column at row $(nrows+1) column $(col+1)" - elseif (2 == state) || (3 == state) || ((0 == state) && is_dlm) # unquoted field, second quote, or begin field with last character as delimiter - col += 1 - nrows += 1 - store_cell(dh, nrows, col, (3 == state), col_start_idx, idx-1) - ncols = max(ncols, col) - end - end - catch ex - if isa(ex, TypeError) && (ex.func == :store_cell) - rethrow(ex) - else - error("at row $(nrows+1), column $col : $ex)") - end - end - !isempty(error_str) && error(error_str) - - return (nrows, ncols) -end - -readcsv(io; opts...) = readdlm(io, ','; opts...) -readcsv(io, T::Type; opts...) = readdlm(io, ',', T; opts...) - -# todo: keyword argument for # of digits to print -writedlm_cell(io::IO, elt::AbstractFloat, dlm, quotes) = print_shortest(io, elt) -function writedlm_cell{T}(io::IO, elt::AbstractString, dlm::T, quotes::Bool) - if quotes && !isempty(elt) && (('"' in elt) || ('\n' in elt) || ((T <: Char) ? (dlm in elt) : contains(elt, dlm))) - print(io, '"', replace(elt, r"\"", "\"\""), '"') - else - print(io, elt) - end -end -writedlm_cell(io::IO, elt, dlm, quotes) = print(io, elt) -function writedlm(io::IO, a::AbstractMatrix, dlm; opts...) - optsd = val_opts(opts) - quotes = get(optsd, :quotes, true) - pb = PipeBuffer() - lastc = last(indices(a, 2)) - for i = indices(a, 1) - for j = indices(a, 2) - writedlm_cell(pb, a[i, j], dlm, quotes) - j == lastc ? write(pb,'\n') : print(pb,dlm) - end - (nb_available(pb) > (16*1024)) && write(io, take!(pb)) - end - write(io, take!(pb)) - nothing -end - -writedlm(io::IO, a::AbstractArray{<:Any,0}, dlm; opts...) = writedlm(io, reshape(a,1), dlm; opts...) - -# write an iterable row as dlm-separated items -function writedlm_row(io::IO, row, dlm, quotes) - state = start(row) - while !done(row, state) - (x, state) = next(row, state) - writedlm_cell(io, x, dlm, quotes) - done(row, state) ? write(io,'\n') : print(io,dlm) - end -end - -# If the row is a single string, write it as a string rather than -# iterating over characters. Also, include the common case of -# a Number (handled correctly by the generic writedlm_row above) -# purely as an optimization. -function writedlm_row(io::IO, row::Union{Number,AbstractString}, dlm, quotes) - writedlm_cell(io, row, dlm, quotes) - write(io, '\n') -end - -# write an iterable collection of iterable rows -function writedlm(io::IO, itr, dlm; opts...) - optsd = val_opts(opts) - quotes = get(optsd, :quotes, true) - pb = PipeBuffer() - for row in itr - writedlm_row(pb, row, dlm, quotes) - (nb_available(pb) > (16*1024)) && write(io, take!(pb)) - end - write(io, take!(pb)) - nothing -end - -function writedlm(fname::AbstractString, a, dlm; opts...) - open(fname, "w") do io - writedlm(io, a, dlm; opts...) - end -end - -""" - writedlm(f, A, delim='\\t'; opts) - -Write `A` (a vector, matrix, or an iterable collection of iterable rows) as text to `f` -(either a filename string or an `IO` stream) using the given delimiter -`delim` (which defaults to tab, but can be any printable Julia object, typically a `Char` or -`AbstractString`). - -For example, two vectors `x` and `y` of the same length can be written as two columns of -tab-delimited text to `f` by either `writedlm(f, [x y])` or by `writedlm(f, zip(x, y))`. -""" -writedlm(io, a; opts...) = writedlm(io, a, '\t'; opts...) - -""" - writecsv(filename, A; opts) - -Equivalent to [`writedlm`](@ref) with `delim` set to comma. -""" -writecsv(io, a; opts...) = writedlm(io, a, ','; opts...) - -show(io::IO, ::MIME"text/csv", a) = writedlm(io, a, ',') -show(io::IO, ::MIME"text/tab-separated-values", a) = writedlm(io, a, '\t') - -end # module DataFmt diff --git a/julia-0.6.3/share/julia/base/dates/Dates.jl b/julia-0.6.3/share/julia/base/dates/Dates.jl deleted file mode 100644 index cf5631a..0000000 --- a/julia-0.6.3/share/julia/base/dates/Dates.jl +++ /dev/null @@ -1,83 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -""" - Dates - -The `Dates` module provides `Date`, `DateTime`, `Time` types, and related functions. - -The types are not aware of time zones, based on UT seconds -(86400 seconds a day, avoiding leap seconds), and -use the proleptic Gregorian calendar, as specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601). -For time zone functionality, see the TimeZones.jl package. - -```jldoctest -julia> dt = DateTime(2017,12,31,23,59,59,999) -2017-12-31T23:59:59.999 - -julia> d1 = Date(Dates.Month(12), Dates.Year(2017)) -2017-12-01 - -julia> d2 = Date("2017-12-31", Dates.DateFormat("y-m-d")) -2017-12-31 - -julia> Dates.yearmonthday(d2) -(2017, 12, 31) - -julia> d2-d1 -30 days -``` - -Please see the manual section on [`Date`](@ref) and [`DateTime`](@ref) -for more information. -""" -module Dates - -importall ..Base.Operators -import ..Base.broadcast - -using Base.Iterators - -include("types.jl") -include("periods.jl") -include("accessors.jl") -include("query.jl") -include("arithmetic.jl") -include("conversions.jl") -include("ranges.jl") -include("adjusters.jl") -include("rounding.jl") -include("io.jl") -include("parse.jl") - -export Period, DatePeriod, TimePeriod, - Year, Month, Week, Day, Hour, Minute, Second, Millisecond, - Microsecond, Nanosecond, - TimeZone, UTC, TimeType, DateTime, Date, Time, - # periods.jl - canonicalize, - # accessors.jl - yearmonthday, yearmonth, monthday, year, month, week, day, - hour, minute, second, millisecond, dayofmonth, - microsecond, nanosecond, - # query.jl - dayofweek, isleapyear, daysinmonth, daysinyear, dayofyear, dayname, dayabbr, - dayofweekofmonth, daysofweekinmonth, monthname, monthabbr, - quarterofyear, dayofquarter, - Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday, - Mon, Tue, Wed, Thu, Fri, Sat, Sun, - January, February, March, April, May, June, - July, August, September, October, November, December, - Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec, - # conversions.jl - unix2datetime, datetime2unix, now, today, - rata2datetime, datetime2rata, julian2datetime, datetime2julian, - # adjusters.jl - firstdayofweek, lastdayofweek, - firstdayofmonth, lastdayofmonth, - firstdayofyear, lastdayofyear, - firstdayofquarter, lastdayofquarter, - adjust, tonext, toprev, tofirst, tolast, - # io.jl - ISODateTimeFormat, ISODateFormat, DateFormat, RFC1123Format, @dateformat_str - -end # module diff --git a/julia-0.6.3/share/julia/base/dates/accessors.jl b/julia-0.6.3/share/julia/base/dates/accessors.jl deleted file mode 100644 index 27c41d1..0000000 --- a/julia-0.6.3/share/julia/base/dates/accessors.jl +++ /dev/null @@ -1,144 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -# Convert # of Rata Die days to proleptic Gregorian calendar y,m,d,w -# Reference: http://mysite.verizon.net/aesir_research/date/date0.htm -function yearmonthday(days) - z = days + 306; h = 100z - 25; a = fld(h, 3652425); b = a - fld(a, 4) - y = fld(100b + h, 36525); c = b + z - 365y - fld(y, 4); m = div(5c + 456, 153) - d = c - div(153m - 457, 5); return m > 12 ? (y + 1, m - 12, d) : (y, m, d) -end -function year(days) - z = days + 306; h = 100z - 25; a = fld(h, 3652425); b = a - fld(a, 4) - y = fld(100b + h, 36525); c = b + z - 365y - fld(y, 4); m = div(5c + 456, 153) - return m > 12 ? y + 1 : y -end -function yearmonth(days) - z = days + 306; h = 100z - 25; a = fld(h,3652425); b = a - fld(a,4) - y = fld(100b + h, 36525); c = b + z - 365y - fld(y, 4); m = div(5c + 456, 153) - return m > 12 ? (y + 1, m - 12) : (y, m) -end -function month(days) - z = days + 306; h = 100z - 25; a = fld(h,3652425); b = a - fld(a,4) - y = fld(100b + h, 36525); c = b + z - 365y - fld(y, 4); m = div(5c + 456, 153) - return m > 12 ? m - 12 : m -end -function monthday(days) - z = days + 306; h = 100z - 25; a = fld(h,3652425); b = a - fld(a,4) - y = fld(100b + h, 36525); c = b + z - 365y - fld(y, 4); m = div(5c + 456, 153) - d = c - div(153m - 457, 5); return m > 12 ? (m - 12, d) : (m, d) -end -function day(days) - z = days + 306; h = 100z - 25; a = fld(h,3652425); b = a - fld(a,4) - y = fld(100b + h, 36525); c = b + z - 365y - fld(y, 4); m = div(5c + 456, 153) - return c - div(153m - 457, 5) -end -# https://en.wikipedia.org/wiki/Talk:ISO_week_date#Algorithms -const WEEK_INDEX = (15, 23, 3, 11) -function week(days) - w = div(abs(days - 1), 7) % 20871 - c, w = divrem((w + (w >= 10435)), 5218) - w = (w * 28 + WEEK_INDEX[c + 1]) % 1461 - return div(w, 28) + 1 -end - -# Accessor functions -value(dt::TimeType) = dt.instant.periods.value -value(t::Time) = t.instant.value -days(dt::Date) = value(dt) -days(dt::DateTime) = fld(value(dt), 86400000) -year(dt::TimeType) = year(days(dt)) -month(dt::TimeType) = month(days(dt)) -week(dt::TimeType) = week(days(dt)) -day(dt::TimeType) = day(days(dt)) -hour(dt::DateTime) = mod(fld(value(dt), 3600000), 24) -minute(dt::DateTime) = mod(fld(value(dt), 60000), 60) -second(dt::DateTime) = mod(fld(value(dt), 1000), 60) -millisecond(dt::DateTime) = mod(value(dt), 1000) -hour(t::Time) = mod(fld(value(t), 3600000000000), Int64(24)) -minute(t::Time) = mod(fld(value(t), 60000000000), Int64(60)) -second(t::Time) = mod(fld(value(t), 1000000000), Int64(60)) -millisecond(t::Time) = mod(fld(value(t), Int64(1000000)), Int64(1000)) -microsecond(t::Time) = mod(fld(value(t), Int64(1000)), Int64(1000)) -nanosecond(t::Time) = mod(value(t), Int64(1000)) - -dayofmonth(dt::TimeType) = day(dt) - -yearmonth(dt::TimeType) = yearmonth(days(dt)) -monthday(dt::TimeType) = monthday(days(dt)) -yearmonthday(dt::TimeType) = yearmonthday(days(dt)) - -# Documentation for exported accessors -for func in (:year, :month) - name = string(func) - @eval begin - @doc """ - $($name)(dt::TimeType) -> Int64 - - The $($name) of a `Date` or `DateTime` as an [`Int64`](@ref). - """ $func(dt::TimeType) - end -end - -""" - week(dt::TimeType) -> Int64 - -Return the [ISO week date](https://en.wikipedia.org/wiki/ISO_week_date) of a `Date` or -`DateTime` as an [`Int64`](@ref). Note that the first week of a year is the week that -contains the first Thursday of the year which can result in dates prior to January 4th -being in the last week of the previous year. For example `week(Date(2005,1,1))` is the 53rd -week of 2004. -""" -week(dt::TimeType) - -for func in (:day, :dayofmonth) - name = string(func) - @eval begin - @doc """ - $($name)(dt::TimeType) -> Int64 - - The day of month of a `Date` or `DateTime` as an [`Int64`](@ref). - """ $func(dt::TimeType) - end -end - -""" - hour(dt::DateTime) -> Int64 - -The hour of day of a `DateTime` as an [`Int64`](@ref). -""" -hour(dt::DateTime) - -for func in (:minute, :second, :millisecond) - name = string(func) - @eval begin - @doc """ - $($name)(dt::DateTime) -> Int64 - - The $($name) of a `DateTime` as an [`Int64`](@ref). - """ $func(dt::DateTime) - end -end - -for parts in (["year", "month"], ["month", "day"], ["year", "month", "day"]) - name = join(parts) - func = Symbol(name) - @eval begin - @doc """ - $($name)(dt::TimeType) -> ($(join(repeated(Int64, length($parts)), ", "))) - - Simultaneously return the $(join($parts, ", ", " and ")) parts of a `Date` or - `DateTime`. - """ $func(dt::TimeType) - end -end - -for func in (:hour, :minute, :second, :millisecond, :microsecond, :nanosecond) - name = string(func) - @eval begin - @doc """ - $($name)(t::Time) -> Int64 - - The $($name) of a `Time` as an [`Int64`](@ref). - """ $func(t::Time) - end -end diff --git a/julia-0.6.3/share/julia/base/dates/adjusters.jl b/julia-0.6.3/share/julia/base/dates/adjusters.jl deleted file mode 100644 index b93236e..0000000 --- a/julia-0.6.3/share/julia/base/dates/adjusters.jl +++ /dev/null @@ -1,307 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -### truncation -Base.trunc(dt::Date, p::Type{Year}) = Date(UTD(totaldays(year(dt), 1, 1))) -Base.trunc(dt::Date, p::Type{Month}) = firstdayofmonth(dt) -Base.trunc(dt::Date, p::Type{Day}) = dt - -Base.trunc(dt::DateTime, p::Type{Year}) = DateTime(trunc(Date(dt), Year)) -Base.trunc(dt::DateTime, p::Type{Month}) = DateTime(trunc(Date(dt), Month)) -Base.trunc(dt::DateTime, p::Type{Day}) = DateTime(Date(dt)) -Base.trunc(dt::DateTime, p::Type{Hour}) = dt - Minute(dt) - Second(dt) - Millisecond(dt) -Base.trunc(dt::DateTime, p::Type{Minute}) = dt - Second(dt) - Millisecond(dt) -Base.trunc(dt::DateTime, p::Type{Second}) = dt - Millisecond(dt) -Base.trunc(dt::DateTime, p::Type{Millisecond}) = dt - -Base.trunc(t::Time, p::Type{Hour}) = Time(Hour(t)) -Base.trunc(t::Time, p::Type{Minute}) = Time(Hour(t), Minute(t)) -Base.trunc(t::Time, p::Type{Second}) = Time(Hour(t), Minute(t), Second(t)) -Base.trunc(t::Time, p::Type{Millisecond}) = t - Microsecond(t) - Nanosecond(t) -Base.trunc(t::Time, p::Type{Microsecond}) = t - Nanosecond(t) -Base.trunc(t::Time, p::Type{Nanosecond}) = t - -""" - trunc(dt::TimeType, ::Type{Period}) -> TimeType - -Truncates the value of `dt` according to the provided `Period` type. E.g. if `dt` is -`1996-01-01T12:30:00`, then `trunc(dt,Day) == 1996-01-01T00:00:00`. -""" -Dates.trunc(::Dates.TimeType, ::Type{Dates.Period}) - -# Adjusters -""" - firstdayofweek(dt::TimeType) -> TimeType - -Adjusts `dt` to the Monday of its week. -""" -function firstdayofweek end - -firstdayofweek(dt::Date) = Date(UTD(value(dt) - dayofweek(dt) + 1)) -firstdayofweek(dt::DateTime) = DateTime(firstdayofweek(Date(dt))) - -""" - lastdayofweek(dt::TimeType) -> TimeType - -Adjusts `dt` to the Sunday of its week. -""" -function lastdayofweek end - -lastdayofweek(dt::Date) = Date(UTD(value(dt) + (7 - dayofweek(dt)))) -lastdayofweek(dt::DateTime) = DateTime(lastdayofweek(Date(dt))) - -""" - firstdayofmonth(dt::TimeType) -> TimeType - -Adjusts `dt` to the first day of its month. -""" -function firstdayofmonth end - -firstdayofmonth(dt::Date) = Date(UTD(value(dt) - day(dt) + 1)) -firstdayofmonth(dt::DateTime) = DateTime(firstdayofmonth(Date(dt))) - -""" - lastdayofmonth(dt::TimeType) -> TimeType - -Adjusts `dt` to the last day of its month. -""" -function lastdayofmonth end - -function lastdayofmonth(dt::Date) - y, m, d = yearmonthday(dt) - return Date(UTD(value(dt) + daysinmonth(y, m) - d)) -end -lastdayofmonth(dt::DateTime) = DateTime(lastdayofmonth(Date(dt))) - -""" - firstdayofyear(dt::TimeType) -> TimeType - -Adjusts `dt` to the first day of its year. -""" -function firstdayofyear end - -firstdayofyear(dt::Date) = Date(UTD(value(dt) - dayofyear(dt) + 1)) -firstdayofyear(dt::DateTime) = DateTime(firstdayofyear(Date(dt))) - -""" - lastdayofyear(dt::TimeType) -> TimeType - -Adjusts `dt` to the last day of its year. -""" -function lastdayofyear end - -function lastdayofyear(dt::Date) - y, m, d = yearmonthday(dt) - return Date(UTD(value(dt) + daysinyear(y) - dayofyear(y, m, d))) -end -lastdayofyear(dt::DateTime) = DateTime(lastdayofyear(Date(dt))) - -""" - firstdayofquarter(dt::TimeType) -> TimeType - -Adjusts `dt` to the first day of its quarter. -""" -function firstdayofquarter end - -function firstdayofquarter(dt::Date) - y,m = yearmonth(dt) - mm = m < 4 ? 1 : m < 7 ? 4 : m < 10 ? 7 : 10 - return Date(y, mm, 1) -end -firstdayofquarter(dt::DateTime) = DateTime(firstdayofquarter(Date(dt))) - -""" - lastdayofquarter(dt::TimeType) -> TimeType - -Adjusts `dt` to the last day of its quarter. -""" -function lastdayofquarter end - -function lastdayofquarter(dt::Date) - y,m = yearmonth(dt) - mm, d = m < 4 ? (3, 31) : m < 7 ? (6, 30) : m < 10 ? (9, 30) : (12, 31) - return Date(y, mm, d) -end -lastdayofquarter(dt::DateTime) = DateTime(lastdayofquarter(Date(dt))) - -# Temporal Adjusters -struct DateFunction - f::Function - # validate boolean, single-arg inner constructor - function DateFunction(f::ANY, dt::TimeType) - isa(f(dt), Bool) || throw(ArgumentError("Provided function must take a single TimeType argument and return true or false")) - return new(f) - end -end -Base.show(io::IO, df::DateFunction) = println(io, df.f) - -# Core adjuster -function adjust(df::DateFunction, start, step, limit) - for i = 1:limit - df.f(start) && return start - start += step - end - throw(ArgumentError("Adjustment limit reached: $limit iterations")) -end - -function adjust(func::Function, start; step::Period=Day(1), negate=nothing, limit::Int=10000) - func = deprecate_negate(:adjust, func, "func,start", negate) - return adjust(DateFunction(func, start), start, step, limit) -end - -# Constructors using DateFunctions - -""" - Date(f::Function, y[, m, d]; step=Day(1), limit=10000) -> Date - -Create a `Date` through the adjuster API. The starting point will be constructed from the -provided `y, m, d` arguments, and will be adjusted until `f::Function` returns `true`. -The step size in adjusting can be provided manually through the `step` keyword. -`limit` provides a limit to the max number of iterations the adjustment API will -pursue before throwing an error (given that `f::Function` is never satisfied). -""" -function Date(func::Function, y, m=1, d=1; step::Period=Day(1), negate=nothing, limit::Int=10000) - func = deprecate_negate(:Date, func, "func,y,m,d", negate) - return adjust(DateFunction(func, Date(y, m, d)), Date(y, m, d), step, limit) -end - -""" - DateTime(f::Function, y[, m, d, h, mi, s]; step=Day(1), limit=10000) -> DateTime - -Create a `DateTime` through the adjuster API. The starting point will be constructed from -the provided `y, m, d...` arguments, and will be adjusted until `f::Function` returns -`true`. The step size in adjusting can be provided manually through the `step` keyword. -`limit` provides a limit to the max number of iterations the adjustment API will -pursue before throwing an error (in the case that `f::Function` is never satisfied). -""" -DateTime(::Function, args...) - -function DateTime(func::Function, y, m=1; step::Period=Day(1), negate=nothing, limit::Int=10000) - func = deprecate_negate(:DateTime, func, "func,y,m", negate) - return adjust(DateFunction(func, DateTime(y, m)), DateTime(y, m), step, limit) -end -function DateTime(func::Function, y, m, d; step::Period=Hour(1), negate=nothing, limit::Int=10000) - func = deprecate_negate(:DateTime, func, "func,y,m,d", negate) - return adjust(DateFunction(func, DateTime(y)), DateTime(y, m, d), step, limit) -end -function DateTime(func::Function, y, m, d, h; step::Period=Minute(1), negate=nothing, limit::Int=10000) - func = deprecate_negate(:DateTime, func, "func,y,m,d,h", negate) - return adjust(DateFunction(func, DateTime(y)), DateTime(y, m, d, h), step, limit) -end -function DateTime(func::Function, y, m, d, h, mi; step::Period=Second(1), negate=nothing, limit::Int=10000) - func = deprecate_negate(:DateTime, func, "func,y,m,d,h,mi", negate) - return adjust(DateFunction(func, DateTime(y)), DateTime(y, m, d, h, mi), step, limit) -end -function DateTime(func::Function, y, m, d, h, mi, s; step::Period=Millisecond(1), negate=nothing, limit::Int=10000) - func = deprecate_negate(:DateTime, func, "func,y,m,d,h,mi,s", negate) - return adjust(DateFunction(func, DateTime(y)), DateTime(y, m, d, h, mi, s), step, limit) -end - -""" - Time(f::Function, h, mi=0; step::Period=Second(1), limit::Int=10000) - Time(f::Function, h, mi, s; step::Period=Millisecond(1), limit::Int=10000) - Time(f::Function, h, mi, s, ms; step::Period=Microsecond(1), limit::Int=10000) - Time(f::Function, h, mi, s, ms, us; step::Period=Nanosecond(1), limit::Int=10000) - -Create a `Time` through the adjuster API. The starting point will be constructed from the -provided `h, mi, s, ms, us` arguments, and will be adjusted until `f::Function` returns `true`. -The step size in adjusting can be provided manually through the `step` keyword. `limit` -provides a limit to the max number of iterations the adjustment API will pursue before -throwing an error (in the case that `f::Function` is never satisfied). Note that the default step -will adjust to allow for greater precision for the given arguments; i.e. if hour, minute, and second -arguments are provided, the default step will be `Millisecond(1)` instead of `Second(1)`. -""" -Time(::Function, args...) - -function Time(func::Function, h, mi=0; step::Period=Second(1), negate=nothing, limit::Int=10000) - func = deprecate_negate(:Time, func, "func,h,mi", negate) - return adjust(DateFunction(func, Time(h, mi)), Time(h, mi), step, limit) -end -function Time(func::Function, h, mi, s; step::Period=Millisecond(1), negate=nothing, limit::Int=10000) - func = deprecate_negate(:Time, func, "func,h,mi,s", negate) - return adjust(DateFunction(func, Time(h, mi, s)), Time(h, mi, s), step, limit) -end -function Time(func::Function, h, mi, s, ms; step::Period=Microsecond(1), negate=nothing, limit::Int=10000) - func = deprecate_negate(:Time, func, "func,h,mi,s,ms", negate) - return adjust(DateFunction(func, Time(h, mi, s, ms)), Time(h, mi, s, ms), step, limit) -end -function Time(func::Function, h, mi, s, ms, us; step::Period=Nanosecond(1), negate=nothing, limit::Int=10000) - func = deprecate_negate(:Time, func, "func,h,mi,s,ms,us", negate) - return adjust(DateFunction(func, Time(h, mi, s, ms, us)), Time(h, mi, s, ms, us), step, limit) -end - -# Return the next TimeType that falls on dow -ISDAYOFWEEK = Dict(Mon => DateFunction(ismonday, Date(0)), - Tue => DateFunction(istuesday, Date(0)), - Wed => DateFunction(iswednesday, Date(0)), - Thu => DateFunction(isthursday, Date(0)), - Fri => DateFunction(isfriday, Date(0)), - Sat => DateFunction(issaturday, Date(0)), - Sun => DateFunction(issunday, Date(0))) - -# "same" indicates whether the current date can be considered or not -""" - tonext(dt::TimeType, dow::Int; same::Bool=false) -> TimeType - -Adjusts `dt` to the next day of week corresponding to `dow` with `1 = Monday, 2 = Tuesday, -etc`. Setting `same=true` allows the current `dt` to be considered as the next `dow`, -allowing for no adjustment to occur. -""" -tonext(dt::TimeType, dow::Int; same::Bool=false) = adjust(ISDAYOFWEEK[dow], same ? dt : dt + Day(1), Day(1), 7) - -# Return the next TimeType where func evals true using step in incrementing -""" - tonext(func::Function, dt::TimeType; step=Day(1), limit=10000, same=false) -> TimeType - -Adjusts `dt` by iterating at most `limit` iterations by `step` increments until `func` -returns `true`. `func` must take a single `TimeType` argument and return a [`Bool`](@ref). -`same` allows `dt` to be considered in satisfying `func`. -""" -function tonext(func::Function, dt::TimeType; step::Period=Day(1), negate=nothing, limit::Int=10000, same::Bool=false) - func = deprecate_negate(:tonext, func, "func,dt", negate) - return adjust(DateFunction(func, dt), same ? dt : dt + step, step, limit) -end - -""" - toprev(dt::TimeType, dow::Int; same::Bool=false) -> TimeType - -Adjusts `dt` to the previous day of week corresponding to `dow` with `1 = Monday, 2 = -Tuesday, etc`. Setting `same=true` allows the current `dt` to be considered as the previous -`dow`, allowing for no adjustment to occur. -""" -toprev(dt::TimeType, dow::Int; same::Bool=false) = adjust(ISDAYOFWEEK[dow], same ? dt : dt + Day(-1), Day(-1), 7) - -""" - toprev(func::Function, dt::TimeType; step=Day(-1), limit=10000, same=false) -> TimeType - -Adjusts `dt` by iterating at most `limit` iterations by `step` increments until `func` -returns `true`. `func` must take a single `TimeType` argument and return a [`Bool`](@ref). -`same` allows `dt` to be considered in satisfying `func`. -""" -function toprev(func::Function, dt::TimeType; step::Period=Day(-1), negate=nothing, limit::Int=10000, same::Bool=false) - func = deprecate_negate(:toprev, func, "func,dt", negate) - return adjust(DateFunction(func, dt), same ? dt : dt + step, step, limit) -end - -# Return the first TimeType that falls on dow in the Month or Year -""" - tofirst(dt::TimeType, dow::Int; of=Month) -> TimeType - -Adjusts `dt` to the first `dow` of its month. Alternatively, `of=Year` will adjust to the -first `dow` of the year. -""" -function tofirst(dt::TimeType, dow::Int; of::Union{Type{Year}, Type{Month}}=Month) - dt = of <: Month ? firstdayofmonth(dt) : firstdayofyear(dt) - return adjust(ISDAYOFWEEK[dow], dt, Day(1), 366) -end - -# Return the last TimeType that falls on dow in the Month or Year -""" - tolast(dt::TimeType, dow::Int; of=Month) -> TimeType - -Adjusts `dt` to the last `dow` of its month. Alternatively, `of=Year` will adjust to the -last `dow` of the year. -""" -function tolast(dt::TimeType, dow::Int; of::Union{Type{Year}, Type{Month}}=Month) - dt = of <: Month ? lastdayofmonth(dt) : lastdayofyear(dt) - return adjust(ISDAYOFWEEK[dow], dt, Day(-1), 366) -end diff --git a/julia-0.6.3/share/julia/base/dates/arithmetic.jl b/julia-0.6.3/share/julia/base/dates/arithmetic.jl deleted file mode 100644 index 0507136..0000000 --- a/julia-0.6.3/share/julia/base/dates/arithmetic.jl +++ /dev/null @@ -1,98 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -# Instant arithmetic -(+)(x::Instant) = x -(-)(x::T, y::T) where {T<:Instant} = x.periods - y.periods - -# TimeType arithmetic -(+)(x::TimeType) = x -(-)(x::T, y::T) where {T<:TimeType} = x.instant - y.instant - -# Date-Time arithmetic -""" - dt::Date + t::Time -> DateTime - -The addition of a `Date` with a `Time` produces a `DateTime`. The hour, minute, second, and millisecond parts of -the `Time` are used along with the year, month, and day of the `Date` to create the new `DateTime`. -Non-zero microseconds or nanoseconds in the `Time` type will result in an `InexactError` being thrown. -""" -function (+)(dt::Date, t::Time) - (microsecond(t) > 0 || nanosecond(t) > 0) && throw(InexactError()) - y, m, d = yearmonthday(dt) - return DateTime(y, m, d, hour(t), minute(t), second(t), millisecond(t)) -end -(+)(t::Time, dt::Date) = dt + t - -# TimeType-Year arithmetic -function (+)(dt::DateTime, y::Year) - oy, m, d = yearmonthday(dt); ny = oy + value(y); ld = daysinmonth(ny, m) - return DateTime(ny, m, d <= ld ? d : ld, hour(dt), minute(dt), second(dt), millisecond(dt)) -end -function (+)(dt::Date,y::Year) - oy, m, d = yearmonthday(dt); ny = oy + value(y); ld = daysinmonth(ny, m) - return Date(ny, m, d <= ld ? d : ld) -end -function (-)(dt::DateTime,y::Year) - oy, m, d = yearmonthday(dt); ny = oy - value(y); ld = daysinmonth(ny, m) - return DateTime(ny, m, d <= ld ? d : ld, hour(dt), minute(dt), second(dt), millisecond(dt)) -end -function (-)(dt::Date,y::Year) - oy, m, d = yearmonthday(dt); ny = oy - value(y); ld = daysinmonth(ny, m) - return Date(ny, m, d <= ld ? d : ld) -end - -# TimeType-Month arithmetic -# monthwrap adds two months with wraparound behavior (i.e. 12 + 1 == 1) -monthwrap(m1, m2) = (v = mod1(m1 + m2, 12); return v < 0 ? 12 + v : v) -# yearwrap takes a starting year/month and a month to add and returns -# the resulting year with wraparound behavior (i.e. 2000-12 + 1 == 2001) -yearwrap(y, m1, m2) = y + fld(m1 + m2 - 1, 12) - -function (+)(dt::DateTime, z::Month) - y,m,d = yearmonthday(dt) - ny = yearwrap(y, m, value(z)) - mm = monthwrap(m, value(z)); ld = daysinmonth(ny, mm) - return DateTime(ny, mm, d <= ld ? d : ld, hour(dt), minute(dt), second(dt), millisecond(dt)) -end -function (+)(dt::Date, z::Month) - y,m,d = yearmonthday(dt) - ny = yearwrap(y, m, value(z)) - mm = monthwrap(m, value(z)); ld = daysinmonth(ny, mm) - return Date(ny, mm, d <= ld ? d : ld) -end -function (-)(dt::DateTime, z::Month) - y,m,d = yearmonthday(dt) - ny = yearwrap(y, m, -value(z)) - mm = monthwrap(m, -value(z)); ld = daysinmonth(ny, mm) - return DateTime(ny, mm, d <= ld ? d : ld, hour(dt), minute(dt), second(dt), millisecond(dt)) -end -function (-)(dt::Date, z::Month) - y,m,d = yearmonthday(dt) - ny = yearwrap(y, m, -value(z)) - mm = monthwrap(m, -value(z)); ld = daysinmonth(ny, mm) - return Date(ny, mm, d <= ld ? d : ld) -end -(+)(x::Date, y::Week) = return Date(UTD(value(x) + 7 * value(y))) -(-)(x::Date, y::Week) = return Date(UTD(value(x) - 7 * value(y))) -(+)(x::Date, y::Day) = return Date(UTD(value(x) + value(y))) -(-)(x::Date, y::Day) = return Date(UTD(value(x) - value(y))) -(+)(x::DateTime, y::Period) = return DateTime(UTM(value(x) + toms(y))) -(-)(x::DateTime, y::Period) = return DateTime(UTM(value(x) - toms(y))) -(+)(x::Time, y::TimePeriod) = return Time(Nanosecond(value(x) + tons(y))) -(-)(x::Time, y::TimePeriod) = return Time(Nanosecond(value(x) - tons(y))) -(+)(y::Period, x::TimeType) = x + y - -(+)(x::AbstractArray{<:TimeType}, y::GeneralPeriod) = x .+ y -(+)(x::StridedArray{<:GeneralPeriod}, y::TimeType) = x .+ y -(+)(y::GeneralPeriod, x::AbstractArray{<:TimeType}) = x .+ y -(+)(y::TimeType, x::StridedArray{<:GeneralPeriod}) = x .+ y -(-)(x::AbstractArray{<:TimeType}, y::GeneralPeriod) = x .- y -(-)(x::StridedArray{<:GeneralPeriod}, y::TimeType) = x .- y - -# TimeType, AbstractArray{TimeType} -(-)(x::AbstractArray{T}, y::T) where {T<:TimeType} = x .- y -(-)(y::T, x::AbstractArray{T}) where {T<:TimeType} = y .- x - -# AbstractArray{TimeType}, AbstractArray{TimeType} -(-)(x::OrdinalRange{T}, y::OrdinalRange{T}) where {T<:TimeType} = collect(x) - collect(y) -(-)(x::Range{T}, y::Range{T}) where {T<:TimeType} = collect(x) - collect(y) diff --git a/julia-0.6.3/share/julia/base/dates/conversions.jl b/julia-0.6.3/share/julia/base/dates/conversions.jl deleted file mode 100644 index 853f20b..0000000 --- a/julia-0.6.3/share/julia/base/dates/conversions.jl +++ /dev/null @@ -1,121 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -# Conversion/Promotion - -""" - Date(dt::DateTime) -> Date - -Converts a `DateTime` to a `Date`. The hour, minute, second, and millisecond parts of -the `DateTime` are truncated, so only the year, month and day parts are used in -construction. -""" -Date(dt::TimeType) = convert(Date, dt) - -""" - DateTime(dt::Date) -> DateTime - -Converts a `Date` to a `DateTime`. The hour, minute, second, and millisecond parts of -the new `DateTime` are assumed to be zero. -""" -DateTime(dt::TimeType) = convert(DateTime, dt) - -""" - Time(dt::DateTime) -> Time - -Converts a `DateTime` to a `Time`. The hour, minute, second, and millisecond parts of -the `DateTime` are used to create the new `Time`. Microsecond and nanoseconds are zero by default. -""" -Time(dt::DateTime) = convert(Time, dt) - -Base.convert(::Type{DateTime}, dt::Date) = DateTime(UTM(value(dt) * 86400000)) -Base.convert(::Type{Date}, dt::DateTime) = Date(UTD(days(dt))) -Base.convert(::Type{Time}, dt::DateTime) = Time(Nanosecond((value(dt) % 86400000) * 1000000)) - -Base.convert(::Type{DateTime},x::Millisecond) = DateTime(Dates.UTInstant(x)) # Converts Rata Die milliseconds to a DateTime -Base.convert(::Type{Millisecond},dt::DateTime) = Millisecond(value(dt)) # Converts DateTime to Rata Die milliseconds -Base.convert(::Type{Date},x::Day) = Date(Dates.UTInstant(x)) # Converts Rata Die days to a Date -Base.convert(::Type{Day},dt::Date) = Day(value(dt)) # Converts Date to Rata Die days - -### External Conversions -const UNIXEPOCH = value(DateTime(1970)) #Rata Die milliseconds for 1970-01-01T00:00:00 - -""" - unix2datetime(x) -> DateTime - -Takes the number of seconds since unix epoch `1970-01-01T00:00:00` and converts to the -corresponding `DateTime`. -""" -function unix2datetime(x) - rata = UNIXEPOCH + round(Int64, Int64(1000) * x) - return DateTime(UTM(rata)) -end -""" - datetime2unix(dt::DateTime) -> Float64 - -Takes the given `DateTime` and returns the number of seconds -since the unix epoch `1970-01-01T00:00:00` as a [`Float64`](@ref). -""" -datetime2unix(dt::DateTime) = (value(dt) - UNIXEPOCH) / 1000.0 - -""" - now() -> DateTime - -Returns a `DateTime` corresponding to the user's system time including the system timezone -locale. -""" -function now() - tv = Libc.TimeVal() - tm = Libc.TmStruct(tv.sec) - return DateTime(tm.year + 1900, tm.month + 1, tm.mday, tm.hour, tm.min, tm.sec, div(tv.usec, 1000)) -end - -""" - today() -> Date - -Returns the date portion of `now()`. -""" -today() = Date(now()) - -""" - now(::Type{UTC}) -> DateTime - -Returns a `DateTime` corresponding to the user's system time as UTC/GMT. -""" -now(::Type{UTC}) = unix2datetime(time()) - -""" - rata2datetime(days) -> DateTime - -Takes the number of Rata Die days since epoch `0000-12-31T00:00:00` and returns the -corresponding `DateTime`. -""" -rata2datetime(days) = DateTime(yearmonthday(days)...) - -""" - datetime2rata(dt::TimeType) -> Int64 - -Returns the number of Rata Die days since epoch from the given `Date` or `DateTime`. -""" -datetime2rata(dt::TimeType) = days(dt) - -# Julian conversions -const JULIANEPOCH = value(DateTime(-4713, 11, 24, 12)) - -""" - julian2datetime(julian_days) -> DateTime - -Takes the number of Julian calendar days since epoch `-4713-11-24T12:00:00` and returns the -corresponding `DateTime`. -""" -function julian2datetime(f) - rata = JULIANEPOCH + round(Int64, Int64(86400000) * f) - return DateTime(UTM(rata)) -end - -""" - datetime2julian(dt::DateTime) -> Float64 - -Takes the given `DateTime` and returns the number of Julian calendar days since the julian -epoch `-4713-11-24T12:00:00` as a [`Float64`](@ref). -""" -datetime2julian(dt::DateTime) = (value(dt) - JULIANEPOCH) / 86400000.0 diff --git a/julia-0.6.3/share/julia/base/dates/io.jl b/julia-0.6.3/share/julia/base/dates/io.jl deleted file mode 100644 index f5eb0fe..0000000 --- a/julia-0.6.3/share/julia/base/dates/io.jl +++ /dev/null @@ -1,547 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -""" - AbstractDateToken - -A token used in parsing or formatting a date time string. Each subtype must -define the tryparsenext and format methods. - -""" -abstract type AbstractDateToken end - -""" - tryparsenext(tok::AbstractDateToken, str::String, i::Int, len::Int, locale::DateLocale) - -`tryparsenext` parses for the `tok` token in `str` starting at index `i`. -`len` is the length of the string. parsing can be optionally based on the -`locale`. If a `tryparsenext` method does not need a locale, it can leave -the argument out in the method definition. - -Returns a tuple of 2 elements `(res, idx)`, where: - -* `res` is a `Nullable{T}` - the result of the parsing, null if parsing failed. -* `idx` is an `Int` - if parsing failed, the index at which it failed; if - parsing succeeded, `idx` is the index _after_ the index at which parsing ended. -""" -function tryparsenext end - -""" - format(io::IO, tok::AbstractDateToken, dt::TimeType, locale) - -Format the `tok` token from `dt` and write it to `io`. The formatting can -be based on `locale`. - -All subtypes of `AbstractDateToken` must define this method in order -to be able to print a Date / DateTime object according to a `DateFormat` -containing that token. -""" -function format end - -# fallback to tryparsenext/format methods that don't care about locale -@inline function tryparsenext(d::AbstractDateToken, str, i, len, locale) - tryparsenext(d, str, i, len) -end - -function Base.string(t::Time) - h, mi, s = hour(t), minute(t), second(t) - hh = lpad(h, 2, "0") - mii = lpad(mi, 2, "0") - ss = lpad(s, 2, "0") - nss = tons(Millisecond(t)) + tons(Microsecond(t)) + tons(Nanosecond(t)) - ns = nss == 0 ? "" : rstrip(@sprintf("%.9f", nss / 1e+9)[2:end], '0') - return "$hh:$mii:$ss$ns" -end - -Base.show(io::IO, x::Time) = print(io, string(x)) - -@inline function format(io, d::AbstractDateToken, dt, locale) - format(io, d, dt) -end - -# Information for parsing and formatting date time values. -struct DateFormat{S, T<:Tuple} - tokens::T - locale::DateLocale -end - -### Token types ### - -struct DatePart{letter} <: AbstractDateToken - width::Int - fixed::Bool -end - -@inline min_width(d::DatePart) = d.fixed ? d.width : 1 -@inline max_width(d::DatePart) = d.fixed ? d.width : 0 - -function _show_content(io::IO, d::DatePart{c}) where c - for i = 1:d.width - write(io, c) - end -end - -function Base.show(io::IO, d::DatePart{c}) where c - write(io, "DatePart(") - _show_content(io, d) - write(io, ")") -end - -### Parse tokens - -for c in "yYmdHMS" - @eval begin - @inline function tryparsenext(d::DatePart{$c}, str, i, len) - tryparsenext_base10(str, i, len, min_width(d), max_width(d)) - end - end -end - -for (tok, fn) in zip("uUeE", [monthabbr_to_value, monthname_to_value, dayabbr_to_value, dayname_to_value]) - @eval @inline function tryparsenext(d::DatePart{$tok}, str, i, len, locale) - word, i = tryparsenext_word(str, i, len, locale, max_width(d)) - val = isnull(word) ? 0 : $fn(get(word), locale) - if val == 0 - return Nullable{Int64}(), i - else - return Nullable{Int64}(val), i - end - end -end - -@inline function tryparsenext(d::DatePart{'s'}, str, i, len) - ms, ii = tryparsenext_base10(str, i, len, min_width(d), max_width(d)) - if !isnull(ms) - val = get(ms) - len = ii - i - if len > 3 - val, r = divrem(val, Int64(10) ^ (len - 3)) - r == 0 || throw(InexactError()) - else - val *= Int64(10) ^ (3 - len) - end - ms = Nullable{Int64}(val) - end - return ms, ii -end - -### Format tokens - -for (c, fn) in zip("YmdHMS", [year, month, day, hour, minute, second]) - @eval function format(io, d::DatePart{$c}, dt) - write(io, dec($fn(dt), d.width)) - end -end - -for (tok, fn) in zip("uU", [monthabbr, monthname]) - @eval function format(io, d::DatePart{$tok}, dt, locale) - write(io, $fn(month(dt), locale)) - end -end - -for (tok, fn) in zip("eE", [dayabbr, dayname]) - @eval function format(io, ::DatePart{$tok}, dt, locale) - write(io, $fn(dayofweek(dt), locale)) - end -end - -@inline function format(io, d::DatePart{'y'}, dt) - y = year(dt) - n = d.width - - # the last n digits of y - # will be 0 padded if y has less than n digits - str = dec(y, n) - l = endof(str) - if l == n - # fast path - write(io, str) - else - write(io, SubString(str, l - (n - 1), l)) - end -end - -function format(io, d::DatePart{'s'}, dt) - ms = millisecond(dt) - if ms % 100 == 0 - str = dec(div(ms, 100), 1) - elseif ms % 10 == 0 - str = dec(div(ms, 10), 2) - else - str = dec(ms, 3) - end - - write(io, rpad(str, d.width, '0')) -end - -### Delimiters - -struct Delim{T, length} <: AbstractDateToken - d::T -end - -Delim(d::Char) = Delim{Char, 1}(d) -Delim(d::String) = Delim{String, length(d)}(d) - -@inline function tryparsenext(d::Delim{Char, N}, str, i::Int, len) where N - R = Nullable{Bool} - for j=1:N - i > len && return (R(), i) - c, i = next(str, i) - c != d.d && return (R(), i) - end - return R(true), i -end - -@inline function tryparsenext(d::Delim{String, N}, str, i::Int, len) where N - R = Nullable{Bool} - i1 = i - i2 = start(d.d) - for j = 1:N - if i1 > len - return R(), i1 - end - c1, i1 = next(str, i1) - c2, i2 = next(d.d, i2) - if c1 != c2 - return R(), i1 - end - end - return R(true), i1 -end - -@inline function format(io, d::Delim, dt, locale) - write(io, d.d) -end - -function _show_content(io::IO, d::Delim{Char, N}) where N - if d.d in keys(CONVERSION_SPECIFIERS) - for i = 1:N - write(io, '\\', d.d) - end - else - for i = 1:N - write(io, d.d) - end - end -end - -function _show_content(io::IO, d::Delim) - for c in d.d - if c in keys(CONVERSION_SPECIFIERS) - write(io, '\\') - end - write(io, c) - end -end - -function Base.show(io::IO, d::Delim) - write(io, "Delim(") - _show_content(io, d) - write(io, ")") -end - -### DateFormat construction - -abstract type DayOfWeekToken end # special addition to Period types - -# Map conversion specifiers or character codes to tokens. -# Note: Allow addition of new character codes added by packages -const CONVERSION_SPECIFIERS = Dict{Char, Type}( - 'y' => Year, - 'Y' => Year, - 'm' => Month, - 'u' => Month, - 'U' => Month, - 'e' => DayOfWeekToken, - 'E' => DayOfWeekToken, - 'd' => Day, - 'H' => Hour, - 'M' => Minute, - 'S' => Second, - 's' => Millisecond, -) - -# Default values are needed when a conversion specifier is used in a DateFormat for parsing -# and we have reached the end of the input string. -# Note: Allow `Any` value as a default to support extensibility -const CONVERSION_DEFAULTS = Dict{Type, Any}( - Year => Int64(1), - Month => Int64(1), - DayOfWeekToken => Int64(0), - Day => Int64(1), - Hour => Int64(0), - Minute => Int64(0), - Second => Int64(0), - Millisecond => Int64(0), -) - -# Specifies the required fields in order to parse a TimeType -# Note: Allows for addition of new TimeTypes -const CONVERSION_TRANSLATIONS = Dict{Type{<:TimeType}, Tuple}( - Date => (Year, Month, Day), - DateTime => (Year, Month, Day, Hour, Minute, Second, Millisecond), -) - -""" - DateFormat(format::AbstractString, locale="english") -> DateFormat - -Construct a date formatting object that can be used for parsing date strings or -formatting a date object as a string. The following character codes can be used to construct the `format` -string: - -| Code | Matches | Comment | -|:-----------|:----------|:-------------------------------------------------------------| -| `y` | 1996, 96 | Returns year of 1996, 0096 | -| `Y` | 1996, 96 | Returns year of 1996, 0096. Equivalent to `y` | -| `m` | 1, 01 | Matches 1 or 2-digit months | -| `u` | Jan | Matches abbreviated months according to the `locale` keyword | -| `U` | January | Matches full month names according to the `locale` keyword | -| `d` | 1, 01 | Matches 1 or 2-digit days | -| `H` | 00 | Matches hours | -| `M` | 00 | Matches minutes | -| `S` | 00 | Matches seconds | -| `s` | .500 | Matches milliseconds | -| `e` | Mon, Tues | Matches abbreviated days of the week | -| `E` | Monday | Matches full name days of the week | -| `yyyymmdd` | 19960101 | Matches fixed-width year, month, and day | - -Characters not listed above are normally treated as delimiters between date and time slots. -For example a `dt` string of "1996-01-15T00:00:00.0" would have a `format` string like -"y-m-dTH:M:S.s". If you need to use a code character as a delimiter you can escape it using -backslash. The date "1995y01m" would have the format "y\\ym\\m". - -Creating a DateFormat object is expensive. Whenever possible, create it once and use it many times -or try the `dateformat""` string macro. Using this macro creates the DateFormat object once at -macro expansion time and reuses it later. see [`@dateformat_str`](@ref). - -See [`DateTime`](@ref) and [`format`](@ref) for how to use a DateFormat object to parse and write Date strings -respectively. -""" -function DateFormat(f::AbstractString, locale::DateLocale=ENGLISH) - tokens = AbstractDateToken[] - prev = () - prev_offset = 1 - - letters = String(collect(keys(CONVERSION_SPECIFIERS))) - for m in eachmatch(Regex("(? DateTime - -Construct a `DateTime` by parsing the `dt` date string following the pattern given in -the `format` string. - -This method creates a `DateFormat` object each time it is called. If you are parsing many -date strings of the same format, consider creating a [`DateFormat`](@ref) object once and using -that as the second argument instead. -""" -function DateTime(dt::AbstractString, format::AbstractString; locale::Locale=ENGLISH) - parse(DateTime, dt, DateFormat(format, locale)) -end - -""" - DateTime(dt::AbstractString, df::DateFormat) -> DateTime - -Construct a `DateTime` by parsing the `dt` date string following the pattern given in -the [`DateFormat`](@ref) object. Similar to -`DateTime(::AbstractString, ::AbstractString)` but more efficient when repeatedly parsing -similarly formatted date strings with a pre-created `DateFormat` object. -""" -DateTime(dt::AbstractString, df::DateFormat=ISODateTimeFormat) = parse(DateTime, dt, df) - -""" - Date(dt::AbstractString, format::AbstractString; locale="english") -> Date - -Construct a `Date` object by parsing a `dt` date string following the pattern given in the -`format` string. Follows the same conventions as -`DateTime(::AbstractString, ::AbstractString)`. -""" -function Date(dt::AbstractString, format::AbstractString; locale::Locale=ENGLISH) - parse(Date, dt, DateFormat(format, locale)) -end - -""" - Date(dt::AbstractString, df::DateFormat) -> Date - -Parse a date from a date string `dt` using a `DateFormat` object `df`. -""" -Date(dt::AbstractString,df::DateFormat=ISODateFormat) = parse(Date, dt, df) - -@generated function format{S, T}(io::IO, dt::TimeType, fmt::DateFormat{S, T}) - N = nfields(T) - quote - ts = fmt.tokens - loc = fmt.locale - Base.@nexprs $N i -> format(io, ts[i], dt, loc) - end -end - -function format(dt::TimeType, fmt::DateFormat, bufsize=12) - # preallocate to reduce resizing - io = IOBuffer(Vector{UInt8}(bufsize), true, true) - format(io, dt, fmt) - String(io.data[1:io.ptr - 1]) -end - - -""" - format(dt::TimeType, format::AbstractString; locale="english") -> AbstractString - -Construct a string by using a `TimeType` object and applying the provided `format`. The -following character codes can be used to construct the `format` string: - -| Code | Examples | Comment | -|:-----------|:----------|:-------------------------------------------------------------| -| `y` | 6 | Numeric year with a fixed width | -| `Y` | 1996 | Numeric year with a minimum width | -| `m` | 1, 12 | Numeric month with a minimum width | -| `u` | Jan | Month name shortened to 3-chars according to the `locale` | -| `U` | January | Full month name according to the `locale` keyword | -| `d` | 1, 31 | Day of the month with a minimum width | -| `H` | 0, 23 | Hour (24-hour clock) with a minimum width | -| `M` | 0, 59 | Minute with a minimum width | -| `S` | 0, 59 | Second with a minimum width | -| `s` | 000, 500 | Millisecond with a minimum width of 3 | -| `e` | Mon, Tue | Abbreviated days of the week | -| `E` | Monday | Full day of week name | - -The number of sequential code characters indicate the width of the code. A format of -`yyyy-mm` specifies that the code `y` should have a width of four while `m` a width of two. -Codes that yield numeric digits have an associated mode: fixed-width or minimum-width. -The fixed-width mode left-pads the value with zeros when it is shorter than the specified -width and truncates the value when longer. Minimum-width mode works the same as fixed-width -except that it does not truncate values longer than the width. - -When creating a `format` you can use any non-code characters as a separator. For example to -generate the string "1996-01-15T00:00:00" you could use `format`: "yyyy-mm-ddTHH:MM:SS". -Note that if you need to use a code character as a literal you can use the escape character -backslash. The string "1996y01m" can be produced with the format "yyyy\\ymm\\m". -""" -function format(dt::TimeType, f::AbstractString; locale::Locale=ENGLISH) - format(dt, DateFormat(f, locale)) -end - -# show - -function Base.show(io::IO, dt::DateTime) - if millisecond(dt) == 0 - format(io, dt, dateformat"YYYY-mm-dd\THH:MM:SS") - else - format(io, dt, dateformat"YYYY-mm-dd\THH:MM:SS.s") - end -end - -function Base.show(io::IO, dt::Date) - format(io, dt, dateformat"YYYY-mm-dd") -end - -function Base.string(dt::DateTime) - if millisecond(dt) == 0 - format(dt, dateformat"YYYY-mm-dd\THH:MM:SS", 24) - else - format(dt, dateformat"YYYY-mm-dd\THH:MM:SS.s", 26) - end -end - -function Base.string(dt::Date) - # don't use format - bypassing IOBuffer creation - # saves a bit of time here. - y,m,d = yearmonthday(value(dt)) - yy = y < 0 ? @sprintf("%05i", y) : lpad(y, 4, "0") - mm = lpad(m, 2, "0") - dd = lpad(d, 2, "0") - return "$yy-$mm-$dd" -end - -# vectorized -function DateTime(Y::AbstractArray{<:AbstractString}, f::AbstractString; locale::Locale=ENGLISH) - DateTime(Y, DateFormat(f, locale)) -end -function DateTime(Y::AbstractArray{<:AbstractString}, df::DateFormat=ISODateTimeFormat) - return reshape(DateTime[parse(DateTime, y, df) for y in Y], size(Y)) -end -function Date(Y::AbstractArray{<:AbstractString}, f::AbstractString; locale::Locale=ENGLISH) - Date(Y, DateFormat(f, locale)) -end -function Date(Y::AbstractArray{<:AbstractString}, df::DateFormat=ISODateFormat) - return reshape(Date[Date(parse(Date, y, df)) for y in Y], size(Y)) -end - -function format(Y::AbstractArray{<:TimeType}, f::AbstractString; locale::Locale=ENGLISH) - format(Y, DateFormat(f, locale)) -end -function format(Y::AbstractArray{T}, df::DateFormat=default_format(T)) where T<:TimeType - return reshape([format(y, df) for y in Y], size(Y)) -end diff --git a/julia-0.6.3/share/julia/base/dates/parse.jl b/julia-0.6.3/share/julia/base/dates/parse.jl deleted file mode 100644 index 07a04ac..0000000 --- a/julia-0.6.3/share/julia/base/dates/parse.jl +++ /dev/null @@ -1,311 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -### Parsing utilities - -_directives(::Type{DateFormat{S,T}}) where {S,T} = T.parameters - -character_codes(df::Type{DateFormat{S,T}}) where {S,T} = character_codes(_directives(df)) -function character_codes(directives::SimpleVector) - letters = sizehint!(Char[], length(directives)) - for (i, directive) in enumerate(directives) - if directive <: DatePart - letter = first(directive.parameters) - push!(letters, letter) - end - end - return letters -end - -genvar(t::DataType) = Symbol(lowercase(string(Base.datatype_name(t)))) - -""" - tryparsenext_core(str::AbstractString, pos::Int, len::Int, df::DateFormat, raise=false) - -Parses the string according to the directives within the DateFormat. Parsing will start at -character index `pos` and will stop when all directives are used or we have parsed up to -the end of the string, `len`. When a directive cannot be parsed the returned value tuple -will be null if `raise` is false otherwise an exception will be thrown. - -Returns a 3-element tuple `(values, pos, num_parsed)`: -* `values::Nullable{Tuple}`: A tuple which contains a value for each `DatePart` within the - `DateFormat` in the order in which they occur. If the string ends before we finish parsing - all the directives the missing values will be filled in with default values. -* `pos::Int`: The character index at which parsing stopped. -* `num_parsed::Int`: The number of values which were parsed and stored within `values`. - Useful for distinguishing parsed values from default values. -""" -@generated function tryparsenext_core(str::AbstractString, pos::Int, len::Int, - df::DateFormat, raise::Bool=false) - directives = _directives(df) - letters = character_codes(directives) - - tokens = Type[CONVERSION_SPECIFIERS[letter] for letter in letters] - value_names = Symbol[genvar(t) for t in tokens] - value_defaults = Tuple(CONVERSION_DEFAULTS[t] for t in tokens) - R = typeof(value_defaults) - - # Pre-assign variables to defaults. Allows us to use `@goto done` without worrying about - # unassigned variables. - assign_defaults = Expr[ - quote - $name = $default - end - for (name, default) in zip(value_names, value_defaults) - ] - - vi = 1 - parsers = Expr[ - begin - if directives[i] <: DatePart - name = value_names[vi] - nullable = Symbol(:nullable_, name) - vi += 1 - quote - pos > len && @goto done - $nullable, next_pos = tryparsenext(directives[$i], str, pos, len, locale) - isnull($nullable) && @goto error - $name = unsafe_get($nullable) - pos = next_pos - num_parsed += 1 - directive_index += 1 - end - else - quote - pos > len && @goto done - nullable_delim, next_pos = tryparsenext(directives[$i], str, pos, len, locale) - isnull(nullable_delim) && @goto error - pos = next_pos - directive_index += 1 - end - end - end - for i in 1:length(directives) - ] - - quote - directives = df.tokens - locale::DateLocale = df.locale - - num_parsed = 0 - directive_index = 1 - - $(assign_defaults...) - $(parsers...) - - pos > len || @goto error - - @label done - return Nullable{$R}($(Expr(:tuple, value_names...))), pos, num_parsed - - @label error - if raise - if directive_index > length(directives) - throw(ArgumentError("Found extra characters at the end of date time string")) - else - d = directives[directive_index] - throw(ArgumentError("Unable to parse date time. Expected directive $d at char $pos")) - end - end - return Nullable{$R}(), pos, 0 - end -end - -""" - tryparsenext_internal(::Type{<:TimeType}, str, pos, len, df::DateFormat, raise=false) - -Parses the string according to the directives within the DateFormat. The specified TimeType -type determines the type of and order of tokens returned. If the given DateFormat or string -does not provide a required token a default value will be used. When the string cannot be -parsed the returned value tuple will be null if `raise` is false otherwise an exception will -be thrown. - -Returns a 2-element tuple `(values, pos)`: -* `values::Nullable{Tuple}`: A tuple which contains a value for each token as specified by - the passed in type. -* `pos::Int`: The character index at which parsing stopped. -""" -@generated function tryparsenext_internal(::Type{T}, str::AbstractString, pos::Int, len::Int, - df::DateFormat, raise::Bool=false) where T<:TimeType - letters = character_codes(df) - - tokens = Type[CONVERSION_SPECIFIERS[letter] for letter in letters] - value_names = Symbol[genvar(t) for t in tokens] - - output_tokens = CONVERSION_TRANSLATIONS[T] - output_names = Symbol[genvar(t) for t in output_tokens] - output_defaults = Tuple(CONVERSION_DEFAULTS[t] for t in output_tokens) - R = typeof(output_defaults) - - # Pre-assign output variables to defaults. Ensures that all output variables are - # assigned as the value tuple returned from `tryparsenext_core` may not include all - # of the required variables. - assign_defaults = Expr[ - quote - $name = $default - end - for (name, default) in zip(output_names, output_defaults) - ] - - # Unpacks the value tuple returned by `tryparsenext_core` into separate variables. - value_tuple = Expr(:tuple, value_names...) - - quote - values, pos, num_parsed = tryparsenext_core(str, pos, len, df, raise) - isnull(values) && return Nullable{$R}(), pos - $(assign_defaults...) - $value_tuple = unsafe_get(values) - return Nullable{$R}($(Expr(:tuple, output_names...))), pos - end -end - -@inline function tryparsenext_base10(str::AbstractString, i::Int, len::Int, min_width::Int=1, max_width::Int=0) - i > len && (return Nullable{Int64}(), i) - min_pos = min_width <= 0 ? i : i + min_width - 1 - max_pos = max_width <= 0 ? len : min(i + max_width - 1, len) - d::Int64 = 0 - @inbounds while i <= max_pos - c, ii = next(str, i) - if '0' <= c <= '9' - d = d * 10 + (c - '0') - else - break - end - i = ii - end - if i <= min_pos - return Nullable{Int64}(), i - else - return Nullable{Int64}(d), i - end -end - -@inline function tryparsenext_word(str::AbstractString, i, len, locale, maxchars=0) - word_start, word_end = i, 0 - max_pos = maxchars <= 0 ? len : min(chr2ind(str, ind2chr(str,i) + maxchars - 1), len) - @inbounds while i <= max_pos - c, ii = next(str, i) - if isalpha(c) - word_end = i - else - break - end - i = ii - end - if word_end == 0 - return Nullable{SubString}(), i - else - return Nullable{SubString}(SubString(str, word_start, word_end)), i - end -end - -function Base.parse(::Type{DateTime}, s::AbstractString, df::typeof(ISODateTimeFormat)) - i, end_pos = start(s), endof(s) - - dm = dd = Int64(1) - th = tm = ts = tms = Int64(0) - - nv, i = tryparsenext_base10(s, i, end_pos, 1) - dy = isnull(nv) ? (@goto error) : unsafe_get(nv) - i > end_pos && @goto error - - c, i = next(s, i) - c != '-' && @goto error - i > end_pos && @goto done - - nv, i = tryparsenext_base10(s, i, end_pos, 1, 2) - dm = isnull(nv) ? (@goto error) : unsafe_get(nv) - i > end_pos && @goto done - - c, i = next(s, i) - c != '-' && @goto error - i > end_pos && @goto done - - nv, i = tryparsenext_base10(s, i, end_pos, 1, 2) - dd = isnull(nv) ? (@goto error) : unsafe_get(nv) - i > end_pos && @goto done - - c, i = next(s, i) - c != 'T' && @goto error - i > end_pos && @goto done - - nv, i = tryparsenext_base10(s, i, end_pos, 1, 2) - th = isnull(nv) ? (@goto error) : unsafe_get(nv) - i > end_pos && @goto done - - c, i = next(s, i) - c != ':' && @goto error - i > end_pos && @goto done - - nv, i = tryparsenext_base10(s, i, end_pos, 1, 2) - tm = isnull(nv) ? (@goto error) : unsafe_get(nv) - i > end_pos && @goto done - - c, i = next(s, i) - c != ':' && @goto error - i > end_pos && @goto done - - nv, i = tryparsenext_base10(s, i, end_pos, 1, 2) - ts = isnull(nv) ? (@goto error) : unsafe_get(nv) - i > end_pos && @goto done - - c, i = next(s, i) - c != '.' && @goto error - i > end_pos && @goto done - - nv, j = tryparsenext_base10(s, i, end_pos, 1, 3) - tms = isnull(nv) ? (@goto error) : unsafe_get(nv) - tms *= 10 ^ (3 - (j - i)) - - j > end_pos || @goto error - - @label done - return DateTime(dy, dm, dd, th, tm, ts, tms) - - @label error - throw(ArgumentError("Invalid DateTime string")) -end - -function Base.parse(::Type{T}, str::AbstractString, df::DateFormat=default_format(T)) where T<:TimeType - pos, len = start(str), endof(str) - values, pos = tryparsenext_internal(T, str, pos, len, df, true) - T(unsafe_get(values)...) -end - -function Base.tryparse(::Type{T}, str::AbstractString, df::DateFormat=default_format(T)) where T<:TimeType - pos, len = start(str), endof(str) - values, pos = tryparsenext_internal(T, str, pos, len, df, false) - if isnull(values) - Nullable{T}() - elseif isnull(validargs(T, unsafe_get(values)...)) - # TODO: validargs gets called twice, since it's called again in the T constructor - Nullable{T}(T(unsafe_get(values)...)) - else - Nullable{T}() - end -end - -""" - parse_components(str::AbstractString, df::DateFormat) -> Array{Any} - -Parse the string into its components according to the directives in the DateFormat. -Each component will be a distinct type, typically a subtype of Period. The order of the -components will match the order of the `DatePart` directives within the DateFormat. The -number of components may be less than the total number of `DatePart`. -""" -@generated function parse_components(str::AbstractString, df::DateFormat) - letters = character_codes(df) - tokens = Type[CONVERSION_SPECIFIERS[letter] for letter in letters] - - quote - pos, len = start(str), endof(str) - values, pos, num_parsed = tryparsenext_core(str, pos, len, df, true) - t = unsafe_get(values) - types = $(Expr(:tuple, tokens...)) - result = Vector{Any}(num_parsed) - for (i, typ) in enumerate(types) - i > num_parsed && break - result[i] = typ(t[i]) # Constructing types takes most of the time - end - return result - end -end diff --git a/julia-0.6.3/share/julia/base/dates/periods.jl b/julia-0.6.3/share/julia/base/dates/periods.jl deleted file mode 100644 index 27eafa5..0000000 --- a/julia-0.6.3/share/julia/base/dates/periods.jl +++ /dev/null @@ -1,472 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -#Period types -value(x::Period) = x.value - -# The default constructors for Periods work well in almost all cases -# P(x) = new((convert(Int64,x)) -# The following definitions are for Period-specific safety -for period in (:Year, :Month, :Week, :Day, :Hour, :Minute, :Second, :Millisecond, :Microsecond, :Nanosecond) - period_str = string(period) - accessor_str = lowercase(period_str) - # Convenience method for show() - @eval _units(x::$period) = " " * $accessor_str * (abs(value(x)) == 1 ? "" : "s") - # periodisless - @eval periodisless(x::$period, y::$period) = value(x) < value(y) - # AbstractString parsing (mainly for IO code) - @eval $period(x::AbstractString) = $period(Base.parse(Int64, x)) - # Period accessors - typs = period in (:Microsecond, :Nanosecond) ? ["Time"] : - period in (:Hour, :Minute, :Second, :Millisecond) ? ["Time", "DateTime"] : ["Date", "DateTime"] - reference = period == :Week ? " For details see [`$accessor_str(::Union{Date, DateTime})`](@ref)." : "" - for typ_str in typs - @eval begin - @doc """ - $($period_str)(dt::$($typ_str)) -> $($period_str) - - The $($accessor_str) part of a $($typ_str) as a `$($period_str)`.$($reference) - """ $period(dt::$(Symbol(typ_str))) = $period($(Symbol(accessor_str))(dt)) - end - end - @eval begin - @doc """ - $($period_str)(v) - - Construct a `$($period_str)` object with the given `v` value. Input must be - losslessly convertible to an [`Int64`](@ref). - """ $period(v) - end -end - -#Print/show/traits -Base.string(x::Period) = string(value(x), _units(x)) -Base.show(io::IO,x::Period) = print(io, string(x)) -Base.zero(::Union{Type{P},P}) where {P<:Period} = P(0) -Base.one(::Union{Type{P},P}) where {P<:Period} = 1 # see #16116 -Base.typemin(::Type{P}) where {P<:Period} = P(typemin(Int64)) -Base.typemax(::Type{P}) where {P<:Period} = P(typemax(Int64)) - -# Default values (as used by TimeTypes) -""" - default(p::Period) -> Period - -Returns a sensible "default" value for the input Period by returning `T(1)` for Year, -Month, and Day, and `T(0)` for Hour, Minute, Second, and Millisecond. -""" -function default end - -default(p::Union{T,Type{T}}) where {T<:DatePeriod} = T(1) -default(p::Union{T,Type{T}}) where {T<:TimePeriod} = T(0) - -(-)(x::P) where {P<:Period} = P(-value(x)) -==(x::P, y::P) where {P<:Period} = value(x) == value(y) -==(x::Period, y::Period) = (==)(promote(x, y)...) -Base.isless(x::P, y::P) where {P<:Period} = isless(value(x), value(y)) -Base.isless(x::Period, y::Period) = isless(promote(x, y)...) - -# Period Arithmetic, grouped by dimensionality: -import Base: div, fld, mod, rem, gcd, lcm, +, -, *, /, % -for op in (:+, :-, :lcm, :gcd) - @eval ($op)(x::P, y::P) where {P<:Period} = P(($op)(value(x), value(y))) -end - -for op in (:/, :div, :fld) - @eval begin - ($op)(x::P, y::P) where {P<:Period} = ($op)(value(x), value(y)) - ($op)(x::P, y::Real) where {P<:Period} = P(($op)(value(x), Int64(y))) - end -end - -for op in (:rem, :mod) - @eval begin - ($op)(x::P, y::P) where {P<:Period} = P(($op)(value(x), value(y))) - ($op)(x::P, y::Real) where {P<:Period} = P(($op)(value(x), Int64(y))) - end -end - -(*)(x::P, y::Real) where {P<:Period} = P(value(x) * Int64(y)) -(*)(y::Real, x::Period) = x * y -for (op, Ty, Tz) in ((:*, Real, :P), - (:/, :P, Float64), (:/, Real, :P)) - @eval begin - function ($op){P<:Period}(X::StridedArray{P}, y::$Ty) - Z = similar(X, $Tz) - for (Idst, Isrc) in zip(eachindex(Z), eachindex(X)) - @inbounds Z[Idst] = ($op)(X[Isrc], y) - end - return Z - end - end -end - -# intfuncs -Base.gcdx{T<:Period}(a::T, b::T) = ((g, x, y) = gcdx(value(a), value(b)); return T(g), x, y) -Base.abs{T<:Period}(a::T) = T(abs(value(a))) - -periodisless(::Period,::Year) = true -periodisless(::Period,::Month) = true -periodisless(::Year,::Month) = false -periodisless(::Period,::Week) = true -periodisless(::Year,::Week) = false -periodisless(::Month,::Week) = false -periodisless(::Period,::Day) = true -periodisless(::Year,::Day) = false -periodisless(::Month,::Day) = false -periodisless(::Week,::Day) = false -periodisless(::Period,::Hour) = false -periodisless(::Minute,::Hour) = true -periodisless(::Second,::Hour) = true -periodisless(::Millisecond,::Hour) = true -periodisless(::Microsecond,::Hour) = true -periodisless(::Nanosecond,::Hour) = true -periodisless(::Period,::Minute) = false -periodisless(::Second,::Minute) = true -periodisless(::Millisecond,::Minute) = true -periodisless(::Microsecond,::Minute) = true -periodisless(::Nanosecond,::Minute) = true -periodisless(::Period,::Second) = false -periodisless(::Millisecond,::Second) = true -periodisless(::Microsecond,::Second) = true -periodisless(::Nanosecond,::Second) = true -periodisless(::Period,::Millisecond) = false -periodisless(::Microsecond,::Millisecond) = true -periodisless(::Nanosecond,::Millisecond) = true -periodisless(::Period,::Microsecond) = false -periodisless(::Nanosecond,::Microsecond) = true -periodisless(::Period,::Nanosecond) = false - -# return (next coarser period, conversion factor): -coarserperiod{P<:Period}(::Type{P}) = (P, 1) -coarserperiod(::Type{Nanosecond}) = (Microsecond, 1000) -coarserperiod(::Type{Microsecond}) = (Millisecond, 1000) -coarserperiod(::Type{Millisecond}) = (Second, 1000) -coarserperiod(::Type{Second}) = (Minute, 60) -coarserperiod(::Type{Minute}) = (Hour, 60) -coarserperiod(::Type{Hour}) = (Day, 24) -coarserperiod(::Type{Day}) = (Week, 7) -coarserperiod(::Type{Month}) = (Year, 12) - -# Stores multiple periods in greatest to least order by type, not values, -# canonicalized to eliminate zero periods, merge equal period types, -# and convert more-precise periods to less-precise periods when possible -""" - CompoundPeriod - -A `CompoundPeriod` is useful for expressing time periods that are not a fixed multiple of -smaller periods. For example, \"a year and a day\" is not a fixed number of days, but can -be expressed using a `CompoundPeriod`. In fact, a `CompoundPeriod` is automatically -generated by addition of different period types, e.g. `Year(1) + Day(1)` produces a -`CompoundPeriod` result. -""" -mutable struct CompoundPeriod <: AbstractTime - periods::Array{Period, 1} - function CompoundPeriod(p::Vector{Period}) - n = length(p) - if n > 1 - sort!(p, rev=true, lt=periodisless) - # canonicalize p by merging equal period types and removing zeros - i = j = 1 - while j <= n - k = j + 1 - while k <= n - if typeof(p[j]) == typeof(p[k]) - p[j] += p[k] - k += 1 - else - break - end - end - if p[j] != zero(p[j]) - p[i] = p[j] - i += 1 - end - j = k - end - n = i - 1 # new length - p = resize!(p, n) - elseif n == 1 && value(p[1]) == 0 - p = Period[] - end - - return new(p) - end -end - -""" - CompoundPeriod(periods) -> CompoundPeriod - -Construct a `CompoundPeriod` from a `Vector` of `Period`s. All `Period`s of the same type -will be added together. - -# Examples -```jldoctest -julia> Dates.CompoundPeriod(Dates.Hour(12), Dates.Hour(13)) -25 hours - -julia> Dates.CompoundPeriod(Dates.Hour(-1), Dates.Minute(1)) --1 hour, 1 minute - -julia> Dates.CompoundPeriod(Dates.Month(1), Dates.Week(-2)) -1 month, -2 weeks - -julia> Dates.CompoundPeriod(Dates.Minute(50000)) -50000 minutes -``` -""" -CompoundPeriod(p::Vector{<:Period}) = CompoundPeriod(Vector{Period}(p)) - -CompoundPeriod(t::Time) = CompoundPeriod(Period[Hour(t), Minute(t), Second(t), Millisecond(t), - Microsecond(t), Nanosecond(t)]) - -CompoundPeriod(p::Period...) = CompoundPeriod(Period[p...]) - - -""" - canonicalize(::CompoundPeriod) -> CompoundPeriod - -Reduces the `CompoundPeriod` into its canonical form by applying the following rules: - -* Any `Period` large enough be partially representable by a coarser `Period` will be broken - into multiple `Period`s (eg. `Hour(30)` becomes `Day(1) + Hour(6)`) -* `Period`s with opposite signs will be combined when possible - (eg. `Hour(1) - Day(1)` becomes `-Hour(23)`) - -# Examples -```jldoctest -julia> Dates.canonicalize(Dates.CompoundPeriod(Dates.Hour(12), Dates.Hour(13))) -1 day, 1 hour - -julia> Dates.canonicalize(Dates.CompoundPeriod(Dates.Hour(-1), Dates.Minute(1))) --59 minutes - -julia> Dates.canonicalize(Dates.CompoundPeriod(Dates.Month(1), Dates.Week(-2))) -1 month, -2 weeks - -julia> Dates.canonicalize(Dates.CompoundPeriod(Dates.Minute(50000))) -4 weeks, 6 days, 17 hours, 20 minutes -``` -""" -function canonicalize(x::CompoundPeriod) - # canonicalize Periods by pushing "overflow" into a coarser period. - p = x.periods - n = length(p) - if n > 0 - pc = sizehint!(Period[], n) - P = typeof(p[n]) - v = value(p[n]) - i = n - 1 - while true - Pc, f = coarserperiod(P) - if i > 0 && typeof(p[i]) == P - v += value(p[i]) - i -= 1 - end - v0 = f == 1 ? v : rem(v, f) - v0 != 0 && push!(pc, P(v0)) - if v != v0 - P = Pc - v = div(v - v0, f) - elseif i > 0 - P = typeof(p[i]) - v = value(p[i]) - i -= 1 - else - break - end - end - p = reverse!(pc) - n = length(p) - else - return x - end - - # reduce the amount of mixed positive/negative Periods. - if n > 0 - pc = sizehint!(Period[], n) - i = n - while i > 0 - j = i - - # Determine sign of the largest period in this group which - # can be converted into via coarserperiod. - last = Union{} - current = typeof(p[i]) - while i > 0 && current != last - if typeof(p[i]) == current - i -= 1 - end - last, current = current, coarserperiod(current)[1] - end - s = sign(value(p[i + 1])) - - # Adjust all the periods in the group based upon the - # largest period sign. - P = typeof(p[j]) - v = 0 - while j > i - Pc, f = coarserperiod(P) - if j > 0 && typeof(p[j]) == P - v += value(p[j]) - j -= 1 - end - v0 = f == 1 ? v : mod(v, f * s) - v0 != 0 && push!(pc, P(v0)) - if v != v0 - P = Pc - v = div(v - v0, f) - elseif j > 0 - P = typeof(p[j]) - v = 0 - else - break - end - end - end - p = reverse!(pc) - end - - return CompoundPeriod(p) -end - -Base.convert(::Type{CompoundPeriod}, x::Period) = CompoundPeriod(Period[x]) -function Base.string(x::CompoundPeriod) - if isempty(x.periods) - return "empty period" - else - s = "" - for p in x.periods - s *= ", " * string(p) - end - return s[3:end] - end -end -Base.show(io::IO,x::CompoundPeriod) = print(io, string(x)) - -# E.g. Year(1) + Day(1) -(+)(x::Period,y::Period) = CompoundPeriod(Period[x, y]) -(+)(x::CompoundPeriod, y::Period) = CompoundPeriod(vcat(x.periods, y)) -(+)(y::Period, x::CompoundPeriod) = x + y -(+)(x::CompoundPeriod, y::CompoundPeriod) = CompoundPeriod(vcat(x.periods, y.periods)) -# E.g. Year(1) - Month(1) -(-)(x::Period, y::Period) = CompoundPeriod(Period[x, -y]) -(-)(x::CompoundPeriod, y::Period) = CompoundPeriod(vcat(x.periods, -y)) -(-)(x::CompoundPeriod) = CompoundPeriod(-x.periods) -(-)(y::Union{Period, CompoundPeriod}, x::CompoundPeriod) = (-x) + y - -GeneralPeriod = Union{Period, CompoundPeriod} -(+)(x::GeneralPeriod) = x -(+)(x::StridedArray{<:GeneralPeriod}) = x - -for op in (:+, :-) - @eval begin - ($op)(x::GeneralPeriod, Y::StridedArray{<:GeneralPeriod}) = broadcast($op, x, Y) - ($op)(Y::StridedArray{<:GeneralPeriod}, x::GeneralPeriod) = broadcast($op, Y, x) - ($op)(X::StridedArray{<:GeneralPeriod}, Y::StridedArray{<:GeneralPeriod}) = - reshape(CompoundPeriod[($op)(x, y) for (x, y) in zip(X, Y)], promote_shape(size(X), size(Y))) - end -end - -(==)(x::CompoundPeriod, y::Period) = x == CompoundPeriod(y) -(==)(x::Period, y::CompoundPeriod) = y == x -(==)(x::CompoundPeriod, y::CompoundPeriod) = canonicalize(x).periods == canonicalize(y).periods - -Base.isequal(x::CompoundPeriod, y::Period) = isequal(x, CompoundPeriod(y)) -Base.isequal(x::Period, y::CompoundPeriod) = isequal(y, x) -Base.isequal(x::CompoundPeriod, y::CompoundPeriod) = x.periods == y.periods - -# Capture TimeType+-Period methods -(+)(a::TimeType, b::Period, c::Period) = (+)(a, b + c) -(+)(a::TimeType, b::Period, c::Period, d::Period...) = (+)((+)(a, b + c), d...) - -function (+)(x::TimeType, y::CompoundPeriod) - for p in y.periods - x += p - end - return x -end -(+)(x::CompoundPeriod, y::TimeType) = y + x - -function (-)(x::TimeType, y::CompoundPeriod) - for p in y.periods - x -= p - end - return x -end - -# Fixed-value Periods (periods corresponding to a well-defined time interval, -# as opposed to variable calendar intervals like Year). -const FixedPeriod = Union{Week, Day, Hour, Minute, Second, Millisecond, Microsecond, Nanosecond} - -# like div but throw an error if remainder is nonzero -function divexact(x, y) - q, r = divrem(x, y) - r == 0 || throw(InexactError()) - return q -end - -# FixedPeriod conversions and promotion rules -const fixedperiod_conversions = [(Week, 7), (Day, 24), (Hour, 60), (Minute, 60), (Second, 1000), (Millisecond, 1000), (Microsecond, 1000), (Nanosecond, 1)] -for i = 1:length(fixedperiod_conversions) - T, n = fixedperiod_conversions[i] - N = Int64(1) - for j = (i - 1):-1:1 # less-precise periods - Tc, nc = fixedperiod_conversions[j] - N *= nc - vmax = typemax(Int64) ÷ N - vmin = typemin(Int64) ÷ N - @eval function Base.convert(::Type{$T}, x::$Tc) - $vmin ≤ value(x) ≤ $vmax || throw(InexactError()) - return $T(value(x) * $N) - end - end - N = n - for j = (i + 1):length(fixedperiod_conversions) # more-precise periods - Tc, nc = fixedperiod_conversions[j] - @eval Base.convert(::Type{$T}, x::$Tc) = $T(divexact(value(x), $N)) - @eval Base.promote_rule(::Type{$T}, ::Type{$Tc}) = $Tc - N *= nc - end -end - -# other periods with fixed conversions but which aren't fixed time periods -const OtherPeriod = Union{Month, Year} -let vmax = typemax(Int64) ÷ 12, vmin = typemin(Int64) ÷ 12 - @eval function Base.convert(::Type{Month}, x::Year) - $vmin ≤ value(x) ≤ $vmax || throw(InexactError()) - Month(value(x) * 12) - end -end -Base.convert(::Type{Year}, x::Month) = Year(divexact(value(x), 12)) -Base.promote_rule(::Type{Year}, ::Type{Month}) = Month - -# disallow comparing fixed to other periods -(==)(x::FixedPeriod, y::OtherPeriod) = throw(MethodError(==, (x, y))) -(==)(x::OtherPeriod, y::FixedPeriod) = throw(MethodError(==, (x, y))) - -Base.isless(x::FixedPeriod, y::OtherPeriod) = throw(MethodError(isless, (x, y))) -Base.isless(x::OtherPeriod, y::FixedPeriod) = throw(MethodError(isless, (x, y))) - -# truncating conversions to milliseconds and days: -toms(c::Nanosecond) = div(value(c), 1000000) -toms(c::Microsecond) = div(value(c), 1000) -toms(c::Millisecond) = value(c) -toms(c::Second) = 1000 * value(c) -toms(c::Minute) = 60000 * value(c) -toms(c::Hour) = 3600000 * value(c) -toms(c::Day) = 86400000 * value(c) -toms(c::Week) = 604800000 * value(c) -toms(c::Month) = 86400000.0 * 30.436875 * value(c) -toms(c::Year) = 86400000.0 * 365.2425 * value(c) -toms(c::CompoundPeriod) = isempty(c.periods) ? 0.0 : Float64(sum(toms, c.periods)) -tons(x) = toms(x) * 1000000 -tons(x::Microsecond) = value(x) * 1000 -tons(x::Nanosecond) = value(x) -days(c::Millisecond) = div(value(c), 86400000) -days(c::Second) = div(value(c), 86400) -days(c::Minute) = div(value(c), 1440) -days(c::Hour) = div(value(c), 24) -days(c::Day) = value(c) -days(c::Week) = 7 * value(c) -days(c::Year) = 365.2425 * value(c) -days(c::Month) = 30.436875 * value(c) -days(c::CompoundPeriod) = isempty(c.periods) ? 0.0 : Float64(sum(days, c.periods)) diff --git a/julia-0.6.3/share/julia/base/dates/query.jl b/julia-0.6.3/share/julia/base/dates/query.jl deleted file mode 100644 index 2e632e2..0000000 --- a/julia-0.6.3/share/julia/base/dates/query.jl +++ /dev/null @@ -1,249 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -# Date Locales - -struct DateLocale - months::Vector{String} - months_abbr::Vector{String} - days_of_week::Vector{String} - days_of_week_abbr::Vector{String} - month_value::Dict{String, Int} - month_abbr_value::Dict{String, Int} - day_of_week_value::Dict{String, Int} - day_of_week_abbr_value::Dict{String, Int} -end - -function locale_dict(names::Vector{<:AbstractString}) - result = Dict{String, Int}() - - # Keep both the common case-sensitive version of the name and an all lowercase - # version for case-insensitive matches. Storing both allows us to avoid using the - # lowercase function during parsing. - for i in 1:length(names) - name = names[i] - result[name] = i - result[lowercase(name)] = i - end - return result -end - -""" - DateLocale(["January", "February",...], ["Jan", "Feb",...], - ["Monday", "Tuesday",...], ["Mon", "Tue",...]) - -Create a locale for parsing or printing textual month names. - -Arguments: - -- `months::Vector`: 12 month names -- `months_abbr::Vector`: 12 abbreviated month names -- `days_of_week::Vector`: 7 days of week -- `days_of_week_abbr::Vector`: 7 days of week abbreviated - -This object is passed as the last argument to `tryparsenext` and `format` -methods defined for each `AbstractDateToken` type. -""" -function DateLocale(months::Vector, months_abbr::Vector, - days_of_week::Vector, days_of_week_abbr::Vector) - DateLocale( - months, months_abbr, days_of_week, days_of_week_abbr, - locale_dict(months), locale_dict(months_abbr), - locale_dict(days_of_week), locale_dict(days_of_week_abbr), - ) -end - -const ENGLISH = DateLocale( - ["January", "February", "March", "April", "May", "June", - "July", "August", "September", "October", "November", "December"], - ["Jan", "Feb", "Mar", "Apr", "May", "Jun", - "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"], - ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"], - ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"], -) - -const LOCALES = Dict{String, DateLocale}("english" => ENGLISH) - -for (fn, field) in zip( - [:dayname_to_value, :dayabbr_to_value, :monthname_to_value, :monthabbr_to_value], - [:day_of_week_value, :day_of_week_abbr_value, :month_value, :month_abbr_value], -) - @eval @inline function $fn(word::AbstractString, locale::DateLocale) - # Maximize performance by attempting to avoid the use of `lowercase` and trying - # a case-sensitive lookup first - value = get(locale.$field, word, 0) - if value == 0 - value = get(locale.$field, lowercase(word), 0) - end - value - end -end - -# Date functions - -### Core query functions - -# Monday = 1....Sunday = 7 -dayofweek(days) = mod1(days, 7) - -# Number of days in year -""" - daysinyear(dt::TimeType) -> Int - -Returns 366 if the year of `dt` is a leap year, otherwise returns 365. -""" -daysinyear(y) = 365 + isleapyear(y) - -# Day of the year -const MONTHDAYS = (0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334) -dayofyear(y, m, d) = MONTHDAYS[m] + d + (m > 2 && isleapyear(y)) - -### Days of the Week -""" - dayofweek(dt::TimeType) -> Int64 - -Returns the day of the week as an [`Int64`](@ref) with `1 = Monday, 2 = Tuesday, etc.`. -""" -dayofweek(dt::TimeType) = dayofweek(days(dt)) - -const Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday = 1, 2, 3, 4, 5, 6, 7 -const Mon, Tue, Wed, Thu, Fri, Sat, Sun = 1, 2, 3, 4, 5, 6, 7 - -dayname(day::Integer, locale::DateLocale) = locale.days_of_week[day] -dayabbr(day::Integer, locale::DateLocale) = locale.days_of_week_abbr[day] -dayname(day::Integer; locale::AbstractString="english") = dayname(day, LOCALES[locale]) -dayabbr(day::Integer; locale::AbstractString="english") = dayabbr(day, LOCALES[locale]) - -""" - dayname(dt::TimeType; locale="english") -> AbstractString - -Return the full day name corresponding to the day of the week of the `Date` or `DateTime` in -the given `locale`. -""" -function dayname(dt::TimeType;locale::AbstractString="english") - dayname(dayofweek(dt); locale=locale) -end - -""" - dayabbr(dt::TimeType; locale="english") -> AbstractString - -Return the abbreviated name corresponding to the day of the week of the `Date` or `DateTime` -in the given `locale`. -""" -function dayabbr(dt::TimeType;locale::AbstractString="english") - dayabbr(dayofweek(dt); locale=locale) -end - -# Convenience methods for each day -ismonday(dt::TimeType) = dayofweek(dt) == Mon -istuesday(dt::TimeType) = dayofweek(dt) == Tue -iswednesday(dt::TimeType) = dayofweek(dt) == Wed -isthursday(dt::TimeType) = dayofweek(dt) == Thu -isfriday(dt::TimeType) = dayofweek(dt) == Fri -issaturday(dt::TimeType) = dayofweek(dt) == Sat -issunday(dt::TimeType) = dayofweek(dt) == Sun - -# i.e. 1st Monday? 2nd Monday? 3rd Wednesday? 5th Sunday? -""" - dayofweekofmonth(dt::TimeType) -> Int - -For the day of week of `dt`, returns which number it is in `dt`'s month. So if the day of -the week of `dt` is Monday, then `1 = First Monday of the month, 2 = Second Monday of the -month, etc.` In the range 1:5. -""" -function dayofweekofmonth(dt::TimeType) - d = day(dt) - return d < 8 ? 1 : d < 15 ? 2 : d < 22 ? 3 : d < 29 ? 4 : 5 -end - -# Total number of a day of week in the month -# e.g. are there 4 or 5 Mondays in this month? -const TWENTYNINE = IntSet([1, 8, 15, 22, 29]) -const THIRTY = IntSet([1, 2, 8, 9, 15, 16, 22, 23, 29, 30]) -const THIRTYONE = IntSet([1, 2, 3, 8, 9, 10, 15, 16, 17, 22, 23, 24, 29, 30, 31]) - -""" - daysofweekinmonth(dt::TimeType) -> Int - -For the day of week of `dt`, returns the total number of that day of the week in `dt`'s -month. Returns 4 or 5. Useful in temporal expressions for specifying the last day of a week -in a month by including `dayofweekofmonth(dt) == daysofweekinmonth(dt)` in the adjuster -function. -""" -function daysofweekinmonth(dt::TimeType) - y, m, d = yearmonthday(dt) - ld = daysinmonth(y, m) - return ld == 28 ? 4 : ld == 29 ? ((d in TWENTYNINE) ? 5 : 4) : - ld == 30 ? ((d in THIRTY) ? 5 : 4) : - (d in THIRTYONE) ? 5 : 4 -end - -### Months -const January, February, March, April, May, June = 1, 2, 3, 4, 5, 6 -const July, August, September, October, November, December = 7, 8, 9, 10, 11, 12 -const Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec = 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 - -monthname(month::Integer, locale::DateLocale) = locale.months[month] -monthabbr(month::Integer, locale::DateLocale) = locale.months_abbr[month] -monthname(month::Integer; locale::AbstractString="english") = monthname(month, LOCALES[locale]) -monthabbr(month::Integer; locale::AbstractString="english") = monthabbr(month, LOCALES[locale]) - -""" - monthname(dt::TimeType; locale="english") -> AbstractString - -Return the full name of the month of the `Date` or `DateTime` in the given `locale`. -""" -function monthname(dt::TimeType; locale::AbstractString="english") - monthname(month(dt); locale=locale) -end - -""" - monthabbr(dt::TimeType; locale="english") -> AbstractString - -Return the abbreviated month name of the `Date` or `DateTime` in the given `locale`. -""" -function monthabbr(dt::TimeType; locale::AbstractString="english") - monthabbr(month(dt); locale=locale) -end - -""" - daysinmonth(dt::TimeType) -> Int - -Returns the number of days in the month of `dt`. Value will be 28, 29, 30, or 31. -""" -daysinmonth(dt::TimeType) = ((y, m) = yearmonth(dt); return daysinmonth(y, m)) - -### Years -""" - isleapyear(dt::TimeType) -> Bool - -Returns `true` if the year of `dt` is a leap year. -""" -isleapyear(dt::TimeType) = isleapyear(year(dt)) - -""" - dayofyear(dt::TimeType) -> Int - -Returns the day of the year for `dt` with January 1st being day 1. -""" -dayofyear(dt::TimeType) = ((y, m, d) = yearmonthday(dt); return dayofyear(y, m, d)) - -daysinyear(dt::TimeType) = 365 + isleapyear(dt) - -### Quarters -""" - quarterofyear(dt::TimeType) -> Int - -Returns the quarter that `dt` resides in. Range of value is 1:4. -""" -function quarterofyear(dt::TimeType) - m = month(dt) - return m < 4 ? 1 : m < 7 ? 2 : m < 10 ? 3 : 4 -end -const QUARTERDAYS = (0, 90, 181, 273) - -""" - dayofquarter(dt::TimeType) -> Int - -Returns the day of the current quarter of `dt`. Range of value is 1:92. -""" -dayofquarter(dt::TimeType) = dayofyear(dt) - QUARTERDAYS[quarterofyear(dt)] diff --git a/julia-0.6.3/share/julia/base/dates/ranges.jl b/julia-0.6.3/share/julia/base/dates/ranges.jl deleted file mode 100644 index 21b646b..0000000 --- a/julia-0.6.3/share/julia/base/dates/ranges.jl +++ /dev/null @@ -1,48 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -# Date/DateTime Ranges - -# Override default step; otherwise it would be Millisecond(1) -Base.colon(start::T, stop::T) where {T<:DateTime} = StepRange(start, Day(1), stop) -Base.colon(start::T, stop::T) where {T<:Date} = StepRange(start, Day(1), stop) -Base.colon(start::T, stop::T) where {T<:Time} = StepRange(start, Second(1), stop) - -Base.range(start::DateTime, len::Integer) = range(start, Day(1), len) -Base.range(start::Date, len::Integer) = range(start, Day(1), len) - -(::Type{StepRange{<:Dates.DatePeriod,<:Real}})(start, step, stop) = - throw(ArgumentError("must specify step as a Period when constructing Dates ranges")) - -# Given a start and end date, how many steps/periods are in between -guess(a::DateTime, b::DateTime, c) = floor(Int64, (Int128(value(b)) - Int128(value(a))) / toms(c)) -guess(a::Date, b::Date, c) = Int64(div(value(b - a), days(c))) -len(a::Time, b::Time, c) = Int64(div(value(b - a), tons(c))) -function len(a, b, c) - lo, hi, st = min(a, b), max(a, b), abs(c) - i = guess(a, b, c) - 1 - while lo + st * i <= hi - i += 1 - end - return i - 1 -end -Base.length(r::StepRange{<:TimeType}) = isempty(r) ? Int64(0) : len(r.start, r.stop, r.step) + 1 -# Period ranges hook into Int64 overflow detection -Base.length(r::StepRange{<:Period}) = length(StepRange(value(r.start), value(r.step), value(r.stop))) - -# Used to calculate the last valid date in the range given the start, stop, and step -# last = stop - steprem(start, stop, step) -Base.steprem(a::T, b::T, c) where {T<:TimeType} = b - (a + c * len(a, b, c)) - -import Base.in -function in(x::T, r::StepRange{T}) where T<:TimeType - n = len(first(r), x, step(r)) + 1 - n >= 1 && n <= length(r) && r[n] == x -end - -Base.start(r::StepRange{<:TimeType}) = 0 -Base.next(r::StepRange{<:TimeType}, i::Int) = (r.start + r.step*i, i + 1) -Base.done(r::StepRange{<:TimeType,<:Period}, i::Integer) = length(r) <= i - -+(x::Period, r::Range{<:TimeType}) = (x + first(r)):step(r):(x + last(r)) -+(r::Range{<:TimeType}, x::Period) = x + r --(r::Range{<:TimeType}, x::Period) = (first(r)-x):step(r):(last(r)-x) diff --git a/julia-0.6.3/share/julia/base/dates/rounding.jl b/julia-0.6.3/share/julia/base/dates/rounding.jl deleted file mode 100644 index 8adbf80..0000000 --- a/julia-0.6.3/share/julia/base/dates/rounding.jl +++ /dev/null @@ -1,180 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -# The epochs used for date rounding are based ISO 8601's "year zero" notation -const DATEEPOCH = value(Date(0)) -const DATETIMEEPOCH = value(DateTime(0)) - -# According to ISO 8601, the first day of the first week of year 0000 is 0000-01-03 -const WEEKEPOCH = value(Date(0, 1, 3)) - -""" - epochdays2date(days) -> Date - -Takes the number of days since the rounding epoch (`0000-01-01T00:00:00`) and returns the -corresponding `Date`. -""" -epochdays2date(i) = Date(UTD(DATEEPOCH + Int64(i))) - -""" - epochms2datetime(milliseconds) -> DateTime - -Takes the number of milliseconds since the rounding epoch (`0000-01-01T00:00:00`) and -returns the corresponding `DateTime`. -""" -epochms2datetime(i) = DateTime(UTM(DATETIMEEPOCH + Int64(i))) - -""" - date2epochdays(dt::Date) -> Int64 - -Takes the given `Date` and returns the number of days since the rounding epoch -(`0000-01-01T00:00:00`) as an [`Int64`](@ref). -""" -date2epochdays(dt::Date) = value(dt) - DATEEPOCH - -""" - datetime2epochms(dt::DateTime) -> Int64 - -Takes the given `DateTime` and returns the number of milliseconds since the rounding epoch -(`0000-01-01T00:00:00`) as an [`Int64`](@ref). -""" -datetime2epochms(dt::DateTime) = value(dt) - DATETIMEEPOCH - -function Base.floor(dt::Date, p::Year) - value(p) < 1 && throw(DomainError()) - years = year(dt) - return Date(years - mod(years, value(p))) -end - -function Base.floor(dt::Date, p::Month) - value(p) < 1 && throw(DomainError()) - y, m = yearmonth(dt) - months_since_epoch = y * 12 + m - 1 - month_offset = months_since_epoch - mod(months_since_epoch, value(p)) - target_month = mod(month_offset, 12) + 1 - target_year = div(month_offset, 12) - (month_offset < 0 && target_month != 1) - return Date(target_year, target_month) -end - -function Base.floor(dt::Date, p::Week) - value(p) < 1 && throw(DomainError()) - days = value(dt) - WEEKEPOCH - days = days - mod(days, value(Day(p))) - return Date(UTD(WEEKEPOCH + Int64(days))) -end - -function Base.floor(dt::Date, p::Day) - value(p) < 1 && throw(DomainError()) - days = date2epochdays(dt) - return epochdays2date(days - mod(days, value(p))) -end - -Base.floor(dt::DateTime, p::DatePeriod) = DateTime(Base.floor(Date(dt), p)) - -function Base.floor(dt::DateTime, p::TimePeriod) - value(p) < 1 && throw(DomainError()) - milliseconds = datetime2epochms(dt) - return epochms2datetime(milliseconds - mod(milliseconds, value(Millisecond(p)))) -end - -""" - floor(dt::TimeType, p::Period) -> TimeType - -Returns the nearest `Date` or `DateTime` less than or equal to `dt` at resolution `p`. - -For convenience, `p` may be a type instead of a value: `floor(dt, Dates.Hour)` is a shortcut -for `floor(dt, Dates.Hour(1))`. - -```jldoctest -julia> floor(Date(1985, 8, 16), Dates.Month) -1985-08-01 - -julia> floor(DateTime(2013, 2, 13, 0, 31, 20), Dates.Minute(15)) -2013-02-13T00:30:00 - -julia> floor(DateTime(2016, 8, 6, 12, 0, 0), Dates.Day) -2016-08-06T00:00:00 -``` -""" -Base.floor(::Dates.TimeType, ::Dates.Period) - -""" - ceil(dt::TimeType, p::Period) -> TimeType - -Returns the nearest `Date` or `DateTime` greater than or equal to `dt` at resolution `p`. - -For convenience, `p` may be a type instead of a value: `ceil(dt, Dates.Hour)` is a shortcut -for `ceil(dt, Dates.Hour(1))`. - -```jldoctest -julia> ceil(Date(1985, 8, 16), Dates.Month) -1985-09-01 - -julia> ceil(DateTime(2013, 2, 13, 0, 31, 20), Dates.Minute(15)) -2013-02-13T00:45:00 - -julia> ceil(DateTime(2016, 8, 6, 12, 0, 0), Dates.Day) -2016-08-07T00:00:00 -``` -""" -function Base.ceil(dt::TimeType, p::Period) - f = floor(dt, p) - return (dt == f) ? f : f + p -end - -""" - floorceil(dt::TimeType, p::Period) -> (TimeType, TimeType) - -Simultaneously return the `floor` and `ceil` of a `Date` or `DateTime` at resolution `p`. -More efficient than calling both `floor` and `ceil` individually. -""" -function floorceil(dt::TimeType, p::Period) - f = floor(dt, p) - return f, (dt == f) ? f : f + p -end - -""" - round(dt::TimeType, p::Period, [r::RoundingMode]) -> TimeType - -Returns the `Date` or `DateTime` nearest to `dt` at resolution `p`. By default -(`RoundNearestTiesUp`), ties (e.g., rounding 9:30 to the nearest hour) will be rounded up. - -For convenience, `p` may be a type instead of a value: `round(dt, Dates.Hour)` is a shortcut -for `round(dt, Dates.Hour(1))`. - -```jldoctest -julia> round(Date(1985, 8, 16), Dates.Month) -1985-08-01 - -julia> round(DateTime(2013, 2, 13, 0, 31, 20), Dates.Minute(15)) -2013-02-13T00:30:00 - -julia> round(DateTime(2016, 8, 6, 12, 0, 0), Dates.Day) -2016-08-07T00:00:00 -``` - -Valid rounding modes for `round(::TimeType, ::Period, ::RoundingMode)` are -`RoundNearestTiesUp` (default), `RoundDown` (`floor`), and `RoundUp` (`ceil`). -""" -function Base.round(dt::TimeType, p::Period, r::RoundingMode{:NearestTiesUp}) - f, c = floorceil(dt, p) - return (dt - f) < (c - dt) ? f : c -end - -Base.round(dt::TimeType, p::Period, r::RoundingMode{:Down}) = Base.floor(dt, p) -Base.round(dt::TimeType, p::Period, r::RoundingMode{:Up}) = Base.ceil(dt, p) - -# No implementation of other `RoundingMode`s: rounding to nearest "even" is skipped because -# "even" is not defined for Period; rounding toward/away from zero is skipped because ISO -# 8601's year 0000 is not really "zero". -Base.round(::TimeType, ::Period, ::RoundingMode) = throw(DomainError()) - -# Default to RoundNearestTiesUp. -Base.round(dt::TimeType, p::Period) = Base.round(dt, p, RoundNearestTiesUp) - -# Make rounding functions callable using Period types in addition to values. -Base.floor(dt::TimeType, p::Type{<:Period}) = Base.floor(dt, p(1)) -Base.ceil(dt::TimeType, p::Type{<:Period}) = Base.ceil(dt, p(1)) - -function Base.round(dt::TimeType, p::Type{<:Period}, r::RoundingMode=RoundNearestTiesUp) - return Base.round(dt, p(1), r) -end diff --git a/julia-0.6.3/share/julia/base/dates/types.jl b/julia-0.6.3/share/julia/base/dates/types.jl deleted file mode 100644 index 12e3e62..0000000 --- a/julia-0.6.3/share/julia/base/dates/types.jl +++ /dev/null @@ -1,358 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -abstract type AbstractTime end - -""" - Period - Year - Month - Week - Day - Hour - Minute - Second - Millisecond - Microsecond - Nanosecond - -`Period` types represent discrete, human representations of time. -""" -abstract type Period <: AbstractTime end -abstract type DatePeriod <: Period end -abstract type TimePeriod <: Period end - -for T in (:Year, :Month, :Week, :Day) - @eval struct $T <: DatePeriod - value::Int64 - $T(v::Number) = new(v) - end -end -for T in (:Hour, :Minute, :Second, :Millisecond, :Microsecond, :Nanosecond) - @eval struct $T <: TimePeriod - value::Int64 - $T(v::Number) = new(v) - end -end - -""" - Year(v) - Month(v) - Week(v) - Day(v) - Hour(v) - Minute(v) - Second(v) - Millisecond(v) - Microsecond(v) - Nanosecond(v) - -Construct a `Period` type with the given `v` value. Input must be losslessly convertible -to an [`Int64`](@ref). -""" -Period(v) - -""" - Instant - -`Instant` types represent integer-based, machine representations of time as continuous -timelines starting from an epoch. -""" -abstract type Instant <: AbstractTime end - -""" - UTInstant{T} - -The `UTInstant` represents a machine timeline based on UT time (1 day = one revolution of -the earth). The `T` is a `Period` parameter that indicates the resolution or precision of -the instant. -""" -struct UTInstant{P<:Period} <: Instant - periods::P -end - -# Convenience default constructors -UTM(x) = UTInstant(Millisecond(x)) -UTD(x) = UTInstant(Day(x)) - -# Calendar types provide rules for interpretating instant -# timelines in human-readable form. -abstract type Calendar <: AbstractTime end - -# ISOCalendar implements the ISO 8601 standard (en.wikipedia.org/wiki/ISO_8601) -# Notably based on the proleptic Gregorian calendar -# ISOCalendar provides interpretation rules for UTInstants to civil date and time parts -struct ISOCalendar <: Calendar end - -abstract type TimeZone end -struct UTC <: TimeZone end - -""" - TimeType - -`TimeType` types wrap `Instant` machine instances to provide human representations of the -machine instant. `Time`, `DateTime` and `Date` are subtypes of `TimeType`. -""" -abstract type TimeType <: AbstractTime end - -""" - DateTime - -`DateTime` wraps a `UTInstant{Millisecond}` and interprets it according to the proleptic -Gregorian calendar. -""" -struct DateTime <: TimeType - instant::UTInstant{Millisecond} - DateTime(instant::UTInstant{Millisecond}) = new(instant) -end - -""" - Date - -`Date` wraps a `UTInstant{Day}` and interprets it according to the proleptic Gregorian calendar. -""" -struct Date <: TimeType - instant::UTInstant{Day} - Date(instant::UTInstant{Day}) = new(instant) -end - -""" - Time - -`Time` wraps a `Nanosecond` and represents a specific moment in a 24-hour day. -""" -struct Time <: TimeType - instant::Nanosecond - Time(instant::Nanosecond) = new(instant) -end - -# Convert y,m,d to # of Rata Die days -# Works by shifting the beginning of the year to March 1, -# so a leap day is the very last day of the year -const SHIFTEDMONTHDAYS = (306, 337, 0, 31, 61, 92, 122, 153, 184, 214, 245, 275) -function totaldays(y, m, d) - # If we're in Jan/Feb, shift the given year back one - z = m < 3 ? y - 1 : y - mdays = SHIFTEDMONTHDAYS[m] - # days + month_days + year_days - return d + mdays + 365z + fld(z, 4) - fld(z, 100) + fld(z, 400) - 306 -end - -# If the year is divisible by 4, except for every 100 years, except for every 400 years -isleapyear(y) = ((y % 4 == 0) && (y % 100 != 0)) || (y % 400 == 0) - -# Number of days in month -const DAYSINMONTH = (31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31) -daysinmonth(y,m) = DAYSINMONTH[m] + (m == 2 && isleapyear(y)) - -### UTILITIES ### - -# These are necessary because the type constructors for TimeType subtypes can -# throw, and we want to be able to use tryparse without requiring a try/catch. -# This is made easier by providing a helper function that checks arguments, so -# we can validate arguments in tryparse. - -""" - validargs(::Type{<:TimeType}, args...) -> Nullable{ArgumentError} - -Determine whether the given arguments consitute valid inputs for the given type. -Returns a `Nullable{ArgumentError}` where null signifies success. -""" -function validargs end - -""" - argerror([msg]) -> Nullable{ArgumentError} - -Construct a `Nullable{ArgumentError}` with the given message, or null if no message -is provided. For use by `validargs`. -""" -argerror(msg::String) = Nullable(ArgumentError(msg)) -argerror() = Nullable{ArgumentError}() - -### CONSTRUCTORS ### -# Core constructors -""" - DateTime(y, [m, d, h, mi, s, ms]) -> DateTime - -Construct a `DateTime` type by parts. Arguments must be convertible to [`Int64`](@ref). -""" -function DateTime(y::Int64, m::Int64=1, d::Int64=1, - h::Int64=0, mi::Int64=0, s::Int64=0, ms::Int64=0) - err = validargs(DateTime, y, m, d, h, mi, s, ms) - isnull(err) || throw(unsafe_get(err)) - rata = ms + 1000 * (s + 60mi + 3600h + 86400 * totaldays(y, m, d)) - return DateTime(UTM(rata)) -end - -function validargs(::Type{DateTime}, y::Int64, m::Int64, d::Int64, - h::Int64, mi::Int64, s::Int64, ms::Int64) - 0 < m < 13 || return argerror("Month: $m out of range (1:12)") - 0 < d < daysinmonth(y, m) + 1 || return argerror("Day: $d out of range (1:$(daysinmonth(y, m)))") - -1 < h < 24 || return argerror("Hour: $h out of range (0:23)") - -1 < mi < 60 || return argerror("Minute: $mi out of range (0:59)") - -1 < s < 60 || return argerror("Second: $s out of range (0:59)") - -1 < ms < 1000 || return argerror("Millisecond: $ms out of range (0:999)") - return argerror() -end - -""" - Date(y, [m, d]) -> Date - -Construct a `Date` type by parts. Arguments must be convertible to [`Int64`](@ref). -""" -function Date(y::Int64, m::Int64=1, d::Int64=1) - err = validargs(Date, y, m, d) - isnull(err) || throw(unsafe_get(err)) - return Date(UTD(totaldays(y, m, d))) -end - -function validargs(::Type{Date}, y::Int64, m::Int64, d::Int64) - 0 < m < 13 || return argerror("Month: $m out of range (1:12)") - 0 < d < daysinmonth(y, m) + 1 || return argerror("Day: $d out of range (1:$(daysinmonth(y, m)))") - return argerror() -end - -""" - Time(h, [mi, s, ms, us, ns]) -> Time - -Construct a `Time` type by parts. Arguments must be convertible to [`Int64`](@ref). -""" -function Time(h::Int64, mi::Int64=0, s::Int64=0, ms::Int64=0, us::Int64=0, ns::Int64=0) - err = validargs(Time, h, mi, s, ms, us, ns) - isnull(err) || throw(unsafe_get(err)) - return Time(Nanosecond(ns + 1000us + 1000000ms + 1000000000s + 60000000000mi + 3600000000000h)) -end - -function validargs(::Type{Time}, h::Int64, mi::Int64, s::Int64, ms::Int64, us::Int64, ns::Int64) - -1 < h < 24 || return argerror("Hour: $h out of range (0:23)") - -1 < mi < 60 || return argerror("Minute: $mi out of range (0:59)") - -1 < s < 60 || return argerror("Second: $s out of range (0:59)") - -1 < ms < 1000 || return argerror("Millisecond: $ms out of range (0:999)") - -1 < us < 1000 || return argerror("Microsecond: $us out of range (0:999)") - -1 < ns < 1000 || return argerror("Nanosecond: $ns out of range (0:999)") - return argerror() -end - -# Convenience constructors from Periods -function DateTime(y::Year, m::Month=Month(1), d::Day=Day(1), - h::Hour=Hour(0), mi::Minute=Minute(0), - s::Second=Second(0), ms::Millisecond=Millisecond(0)) - return DateTime(value(y), value(m), value(d), - value(h), value(mi), value(s), value(ms)) -end - -Date(y::Year, m::Month=Month(1), d::Day=Day(1)) = Date(value(y), value(m), value(d)) - -function Time(h::Hour, mi::Minute=Minute(0), s::Second=Second(0), - ms::Millisecond=Millisecond(0), - us::Microsecond=Microsecond(0), ns::Nanosecond=Nanosecond(0)) - return Time(value(h), value(mi), value(s), value(ms), value(us), value(ns)) -end - -# To allow any order/combination of Periods - -""" - DateTime(periods::Period...) -> DateTime - -Construct a `DateTime` type by `Period` type parts. Arguments may be in any order. DateTime -parts not provided will default to the value of `Dates.default(period)`. -""" -function DateTime(periods::Period...) - y = Year(1); m = Month(1); d = Day(1) - h = Hour(0); mi = Minute(0); s = Second(0); ms = Millisecond(0) - for p in periods - isa(p, Year) && (y = p::Year) - isa(p, Month) && (m = p::Month) - isa(p, Day) && (d = p::Day) - isa(p, Hour) && (h = p::Hour) - isa(p, Minute) && (mi = p::Minute) - isa(p, Second) && (s = p::Second) - isa(p, Millisecond) && (ms = p::Millisecond) - end - return DateTime(y, m, d, h, mi, s, ms) -end - -""" - Date(period::Period...) -> Date - -Construct a `Date` type by `Period` type parts. Arguments may be in any order. `Date` parts -not provided will default to the value of `Dates.default(period)`. -""" -function Date(periods::Period...) - y = Year(1); m = Month(1); d = Day(1) - for p in periods - isa(p, Year) && (y = p::Year) - isa(p, Month) && (m = p::Month) - isa(p, Day) && (d = p::Day) - end - return Date(y, m, d) -end - -""" - Time(period::TimePeriod...) -> Time - -Construct a `Time` type by `Period` type parts. Arguments may be in any order. `Time` parts -not provided will default to the value of `Dates.default(period)`. -""" -function Time(periods::TimePeriod...) - h = Hour(0); mi = Minute(0); s = Second(0) - ms = Millisecond(0); us = Microsecond(0); ns = Nanosecond(0) - for p in periods - isa(p, Hour) && (h = p::Hour) - isa(p, Minute) && (mi = p::Minute) - isa(p, Second) && (s = p::Second) - isa(p, Millisecond) && (ms = p::Millisecond) - isa(p, Microsecond) && (us = p::Microsecond) - isa(p, Nanosecond) && (ns = p::Nanosecond) - end - return Time(h, mi, s, ms, us, ns) -end - -# Fallback constructors -DateTime(y, m=1, d=1, h=0, mi=0, s=0, ms=0) = DateTime(Int64(y), Int64(m), Int64(d), Int64(h), Int64(mi), Int64(s), Int64(ms)) -Date(y, m=1, d=1) = Date(Int64(y), Int64(m), Int64(d)) -Time(h, mi=0, s=0, ms=0, us=0, ns=0) = Time(Int64(h), Int64(mi), Int64(s), Int64(ms), Int64(us), Int64(ns)) - -# Traits, Equality -Base.isfinite(::Union{Type{T}, T}) where {T<:TimeType} = true -calendar(dt::DateTime) = ISOCalendar -calendar(dt::Date) = ISOCalendar - -""" - eps(::DateTime) -> Millisecond - eps(::Date) -> Day - eps(::Time) -> Nanosecond - -Returns `Millisecond(1)` for `DateTime` values, `Day(1)` for `Date` values, and `Nanosecond(1)` for `Time` values. -""" -Base.eps - -Base.eps(dt::DateTime) = Millisecond(1) -Base.eps(dt::Date) = Day(1) -Base.eps(t::Time) = Nanosecond(1) - -Base.typemax(::Union{DateTime, Type{DateTime}}) = DateTime(146138512, 12, 31, 23, 59, 59) -Base.typemin(::Union{DateTime, Type{DateTime}}) = DateTime(-146138511, 1, 1, 0, 0, 0) -Base.typemax(::Union{Date, Type{Date}}) = Date(252522163911149, 12, 31) -Base.typemin(::Union{Date, Type{Date}}) = Date(-252522163911150, 1, 1) -Base.typemax(::Union{Time, Type{Time}}) = Time(23, 59, 59, 999, 999, 999) -Base.typemin(::Union{Time, Type{Time}}) = Time(0) -# Date-DateTime promotion, isless, == -Base.eltype(::Type{T}) where {T<:Period} = T -Base.promote_rule(::Type{Date}, x::Type{DateTime}) = DateTime -Base.isless(x::T, y::T) where {T<:TimeType} = isless(value(x), value(y)) -Base.isless(x::TimeType, y::TimeType) = isless(Base.promote_noncircular(x, y)...) -(==)(x::T, y::T) where {T<:TimeType} = (==)(value(x), value(y)) -function ==(a::Time, b::Time) - return hour(a) == hour(b) && minute(a) == minute(b) && - second(a) == second(b) && millisecond(a) == millisecond(b) && - microsecond(a) == microsecond(b) && nanosecond(a) == nanosecond(b) -end -(==)(x::TimeType, y::TimeType) = (===)(promote(x, y)...) - -import Base: sleep, Timer, timedwait -sleep(time::Period) = sleep(toms(time) / 1000) -Timer(time::Period, repeat::Period=Second(0)) = Timer(toms(time) / 1000, toms(repeat) / 1000) -timedwait(testcb::Function, time::Period) = timedwait(testcb, toms(time) / 1000) - -Base.TypeOrder(::Type{<:AbstractTime}) = Base.HasOrder() -Base.TypeArithmetic(::Type{<:AbstractTime}) = Base.ArithmeticOverflows() diff --git a/julia-0.6.3/share/julia/base/deepcopy.jl b/julia-0.6.3/share/julia/base/deepcopy.jl deleted file mode 100644 index 929f67c..0000000 --- a/julia-0.6.3/share/julia/base/deepcopy.jl +++ /dev/null @@ -1,95 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -# deep copying - -# Note: deepcopy_internal(::Any, ::ObjectIdDict) is -# only exposed for specialization by libraries - -deepcopy(x) = deepcopy_internal(x, ObjectIdDict())::typeof(x) - -deepcopy_internal(x::Union{Symbol,Core.MethodInstance,Method,GlobalRef,DataType,Union,Task}, - stackdict::ObjectIdDict) = x -deepcopy_internal(x::Tuple, stackdict::ObjectIdDict) = - ntuple(i->deepcopy_internal(x[i], stackdict), length(x)) -deepcopy_internal(x::Module, stackdict::ObjectIdDict) = error("deepcopy of Modules not supported") - -function deepcopy_internal(x::SimpleVector, stackdict::ObjectIdDict) - if haskey(stackdict, x) - return stackdict[x] - end - y = Core.svec(Any[deepcopy_internal(x[i], stackdict) for i = 1:length(x)]...) - stackdict[x] = y - return y -end - -function deepcopy_internal(x::String, stackdict::ObjectIdDict) - if haskey(stackdict, x) - return stackdict[x] - end - y = unsafe_string(pointer(x), sizeof(x)) - stackdict[x] = y - return y -end - -function deepcopy_internal(x::ANY, stackdict::ObjectIdDict) - T = typeof(x)::DataType - nf = nfields(T) - (isbits(T) || nf == 0) && return x - if haskey(stackdict, x) - return stackdict[x] - end - y = ccall(:jl_new_struct_uninit, Any, (Any,), T) - if T.mutable - stackdict[x] = y - end - for i in 1:nf - if isdefined(x,i) - ccall(:jl_set_nth_field, Void, (Any, Csize_t, Any), y, i-1, - deepcopy_internal(getfield(x,i), stackdict)) - end - end - return y::T -end - -function deepcopy_internal(x::Array, stackdict::ObjectIdDict) - if haskey(stackdict, x) - return stackdict[x] - end - _deepcopy_array_t(x, eltype(x), stackdict) -end - -function _deepcopy_array_t(x::ANY, T, stackdict::ObjectIdDict) - if isbits(T) - return (stackdict[x]=copy(x)) - end - dest = similar(x) - stackdict[x] = dest - for i = 1:(length(x)::Int) - if ccall(:jl_array_isassigned, Cint, (Any, Csize_t), x, i-1) != 0 - xi = ccall(:jl_arrayref, Any, (Any, Csize_t), x, i-1) - if !isbits(typeof(xi)) - xi = deepcopy_internal(xi, stackdict) - end - ccall(:jl_arrayset, Void, (Any, Any, Csize_t), dest, xi, i-1) - end - end - return dest -end - -function deepcopy_internal(x::Dict, stackdict::ObjectIdDict) - if haskey(stackdict, x) - return stackdict[x]::typeof(x) - end - - if isbits(eltype(x)) - return (stackdict[x] = copy(x)) - end - - dest = similar(x) - stackdict[x] = dest - for (k, v) in x - dest[deepcopy_internal(k, stackdict)] = deepcopy_internal(v, stackdict) - end - dest -end - diff --git a/julia-0.6.3/share/julia/base/deprecated.jl b/julia-0.6.3/share/julia/base/deprecated.jl deleted file mode 100644 index 118e803..0000000 --- a/julia-0.6.3/share/julia/base/deprecated.jl +++ /dev/null @@ -1,1345 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -# Deprecated functions and objects -# -# Please add new deprecations at the bottom of the file. -# A function deprecated in a release will be removed in the next one. -# Please also add a reference to the pull request which introduced the -# deprecation. -# -# For simple cases where a direct replacement is available, use @deprecate: -# the first argument is the signature of the deprecated method, the second one -# is the call which replaces it. Remove the definition of the deprecated method -# and unexport it, as @deprecate takes care of calling the replacement -# and of exporting the function. -# -# For more complex cases, move the body of the deprecated method in this file, -# and call depwarn() directly from inside it. The symbol depwarn() expects is -# the name of the function, which is used to ensure that the deprecation warning -# is only printed the first time for each call place. - -macro deprecate(old, new, ex=true) - meta = Expr(:meta, :noinline) - @gensym oldmtname - if isa(old, Symbol) - oldname = Expr(:quote, old) - newname = Expr(:quote, new) - Expr(:toplevel, - ex ? Expr(:export, esc(old)) : nothing, - :(function $(esc(old))(args...) - $meta - depwarn(string($oldname, " is deprecated, use ", $newname, " instead."), - $oldmtname) - $(esc(new))(args...) - end), - :(const $oldmtname = Core.Typeof($(esc(old))).name.mt.name)) - elseif isa(old, Expr) && (old.head == :call || old.head == :where) - remove_linenums!(new) - oldcall = sprint(show_unquoted, old) - newcall = sprint(show_unquoted, new) - # if old.head is a :where, step down one level to the :call to avoid code duplication below - callexpr = old.head == :call ? old : old.args[1] - if callexpr.head == :call - if isa(callexpr.args[1], Symbol) - oldsym = callexpr.args[1]::Symbol - elseif isa(callexpr.args[1], Expr) && callexpr.args[1].head == :curly - oldsym = callexpr.args[1].args[1]::Symbol - else - error("invalid usage of @deprecate") - end - else - error("invalid usage of @deprecate") - end - Expr(:toplevel, - ex ? Expr(:export, esc(oldsym)) : nothing, - :($(esc(old)) = begin - $meta - depwarn(string($oldcall, " is deprecated, use ", $newcall, " instead."), - $oldmtname) - $(esc(new)) - end), - :(const $oldmtname = Core.Typeof($(esc(oldsym))).name.mt.name)) - else - error("invalid usage of @deprecate") - end -end - -function depwarn(msg, funcsym) - opts = JLOptions() - if opts.depwarn > 0 - bt = backtrace() - _depwarn(msg, opts, bt, firstcaller(bt, funcsym)) - end - nothing -end -function _depwarn(msg, opts, bt, caller) - ln = Int(unsafe_load(cglobal(:jl_lineno, Cint))) - fn = unsafe_string(unsafe_load(cglobal(:jl_filename, Ptr{Cchar}))) - if opts.depwarn == 1 # raise a warning - warn(msg, once=(caller != StackTraces.UNKNOWN), key=(caller,fn,ln), bt=bt, - filename=fn, lineno=ln) - elseif opts.depwarn == 2 # raise an error - throw(ErrorException(msg)) - end -end - -firstcaller(bt::Array{Ptr{Void},1}, funcsym::Symbol) = firstcaller(bt, (funcsym,)) -function firstcaller(bt::Array{Ptr{Void},1}, funcsyms) - # Identify the calling line - found = false - lkup = StackTraces.UNKNOWN - for frame in bt - lkups = StackTraces.lookup(frame) - for lkup in lkups - if lkup == StackTraces.UNKNOWN - continue - end - found && @goto found - found = lkup.func in funcsyms - # look for constructor type name - if !found && !isnull(lkup.linfo) - li = get(lkup.linfo) - ft = ccall(:jl_first_argument_datatype, Any, (Any,), li.def.sig) - if isa(ft,DataType) && ft.name === Type.body.name - ft = unwrap_unionall(ft.parameters[1]) - found = (isa(ft,DataType) && ft.name.name in funcsyms) - end - end - end - end - return StackTraces.UNKNOWN - @label found - return lkup -end - -deprecate(s::Symbol) = deprecate(current_module(), s) -deprecate(m::Module, s::Symbol) = ccall(:jl_deprecate_binding, Void, (Any, Any), m, s) - -macro deprecate_binding(old, new, export_old=true) - Expr(:toplevel, - export_old ? Expr(:export, esc(old)) : nothing, - Expr(:const, Expr(:(=), esc(old), esc(new))), - Expr(:call, :deprecate, Expr(:quote, old))) -end - -# BEGIN 0.6-alpha deprecations (delete when 0.6 is released) - -@deprecate isambiguous(m1::Method, m2::Method, b::Bool) isambiguous(m1, m2, ambiguous_bottom=b) false -# TODO: delete allow_bottom keyword code in Base.Test.detect_ambiguities - -# END 0.6-alpha deprecations - -# BEGIN 0.6 deprecations - -const _oldstyle_array_vcat_ = false - -@deprecate write(x) write(STDOUT::IO, x) - -function delete!(::EnvHash, k::AbstractString, def) - depwarn("`delete!(ENV, k, def)` should be replaced with `pop!(ENV, k, def)`. Be aware that `pop!` returns `k` or `def`, while `delete!` returns `ENV` or `def`.", :delete!) - haskey(ENV,k) ? delete!(ENV,k) : def -end - -@deprecate (+)(J::UniformScaling, x::Number) J.λ + x -@deprecate (+)(x::Number, J::UniformScaling) x + J.λ -@deprecate (-)(J::UniformScaling, x::Number) J.λ - x -@deprecate (-)(x::Number, J::UniformScaling) x - J.λ - -# Deprecate methods that convert Diagonal and Bidiagonal to <:AbstractTriangular. -function convert(::Type{UpperTriangular}, A::Diagonal) - depwarn(string("`convert(::Type{UpperTriangular}, A::Diagonal)` and other methods ", - "that convert `Diagonal`/`Bidiagonal` to `<:AbstractTriangular` are deprecated. ", - "Consider calling the `UpperTriangular` constructor directly ", - "(`UpperTriangular(A)`) instead."), :convert) - UpperTriangular(A) -end -function convert(::Type{LowerTriangular}, A::Diagonal) - depwarn(string("`convert(::Type{LowerTriangular}, A::Diagonal)` and other methods ", - "that convert `Diagonal`/`Bidiagonal` to `<:AbstractTriangular` are deprecated. ", - "Consider calling the `LowerTriangular` constructor directly ", - "(`LowerTriangular(A)`) instead."), :convert) - LowerTriangular(A) -end -function convert(::Type{Base.LinAlg.UnitUpperTriangular}, A::Diagonal) - depwarn(string("`convert(::Type{UnitUpperTriangular}, A::Diagonal)` and other methods ", - "that convert `Diagonal`/`Bidiagonal` to `<:AbstractTriangular` are deprecated. ", - "Consider calling the `UnitUpperTriangular` constructor directly ", - "(`Base.LinAlg.UnitUpperTriangular(A)`) instead."), :convert) - if !all(x -> x == oneunit(x), A.diag) - throw(ArgumentError("matrix cannot be represented as UnitUpperTriangular")) - end - Base.LinAlg.UnitUpperTriangular(Array(A)) -end -function convert(::Type{Base.LinAlg.UnitLowerTriangular}, A::Diagonal) - depwarn(string("`convert(::Type{UnitLowerTriangular}, A::Diagonal)` and other methods ", - "that convert `Diagonal`/`Bidiagonal` to `<:AbstractTriangular` are deprecated. ", - "Consider calling the `UnitLowerTriangular` constructor directly ", - "(`Base.LinAlg.UnitLowerTriangular(A)`) instead."), :convert) - if !all(x -> x == oneunit(x), A.diag) - throw(ArgumentError("matrix cannot be represented as UnitLowerTriangular")) - end - Base.LinAlg.UnitLowerTriangular(Array(A)) -end -function convert(::Type{LowerTriangular}, A::Bidiagonal) - depwarn(string("`convert(::Type{LowerTriangular}, A::Bidiagonal)` and other methods ", - "that convert `Diagonal`/`Bidiagonal` to `<:AbstractTriangular` are deprecated. ", - "Consider calling the `LowerTriangular` constructor directly (`LowerTriangular(A)`) ", - "instead."), :convert) - if !A.isupper - LowerTriangular(Array(A)) - else - throw(ArgumentError("Bidiagonal matrix must have lower off diagonal to be converted to LowerTriangular")) - end -end -function convert(::Type{UpperTriangular}, A::Bidiagonal) - depwarn(string("`convert(::Type{UpperTriangular}, A::Bidiagonal)` and other methods ", - "that convert `Diagoinal`/`Bidiagonal` to `<:AbstractTriangular` are deprecated. ", - "Consider calling the `UpperTriangular` constructor directly (`UpperTriangular(A)`) ", - "instead."), :convert) - if A.isupper - UpperTriangular(Array(A)) - else - throw(ArgumentError("Bidiagonal matrix must have upper off diagonal to be converted to UpperTriangular")) - end -end - -# Deprecate three-arg SubArray since the constructor doesn't need the dims tuple -@deprecate SubArray(parent::AbstractArray, indexes::Tuple, dims::Tuple) SubArray(parent, indexes) - -# Deprecate vectorized unary functions over sparse matrices in favor of compact broadcast syntax (#17265). -for f in (:sin, :sinh, :sind, :asin, :asinh, :asind, - :tan, :tanh, :tand, :atan, :atanh, :atand, - :sinpi, :cosc, :ceil, :floor, :trunc, :round, - :log1p, :expm1, :abs, :abs2, - :log, :log2, :log10, :exp, :exp2, :exp10, :sinc, :cospi, - :cos, :cosh, :cosd, :acos, :acosd, - :cot, :coth, :cotd, :acot, :acotd, - :sec, :sech, :secd, :asech, - :csc, :csch, :cscd, :acsch) - @eval @deprecate $f(A::SparseMatrixCSC) $f.(A) -end - -# For deprecating vectorized functions in favor of compact broadcast syntax -macro dep_vectorize_1arg(S, f) - S = esc(S) - f = esc(f) - T = esc(:T) - x = esc(:x) - AbsArr = esc(:AbstractArray) - :( @deprecate $f($x::$AbsArr{$T}) where {$T<:$S} $f.($x) ) -end -macro dep_vectorize_2arg(S, f) - S = esc(S) - f = esc(f) - T1 = esc(:T1) - T2 = esc(:T2) - x = esc(:x) - y = esc(:y) - AbsArr = esc(:AbstractArray) - quote - @deprecate $f($x::$S, $y::$AbsArr{$T1}) where {$T1<:$S} $f.($x,$y) - @deprecate $f($x::$AbsArr{$T1}, $y::$S) where {$T1<:$S} $f.($x,$y) - @deprecate $f($x::$AbsArr{$T1}, $y::$AbsArr{$T2}) where {$T1<:$S,$T2<:$S} $f.($x,$y) - end -end - -# Deprecate @vectorize_1arg-vectorized functions from... -for f in ( - # base/special/trig.jl - :sinpi, :cospi, :sinc, :cosc, - # base/special/log.jl - :log, :log1p, - # base/special/gamma.jl - :gamma, :lfact, - # base/math.jl - :cbrt, :sinh, :cosh, :tanh, :atan, :asinh, :exp, :exp2, - :expm1, :exp10, :sin, :cos, :tan, :asin, :acos, :acosh, :atanh, - #=:log,=# :log2, :log10, :lgamma, #=:log1p,=# :sqrt, - # base/floatfuncs.jl - :abs, :abs2, :angle, :isnan, :isinf, :isfinite, - # base/complex.jl - :cis, - ) - @eval @dep_vectorize_1arg Number $f -end -# base/fastmath.jl -for f in ( :acos_fast, :acosh_fast, :angle_fast, :asin_fast, :asinh_fast, - :atan_fast, :atanh_fast, :cbrt_fast, :cis_fast, :cos_fast, - :cosh_fast, :exp10_fast, :exp2_fast, :exp_fast, :expm1_fast, - :lgamma_fast, :log10_fast, :log1p_fast, :log2_fast, :log_fast, - :sin_fast, :sinh_fast, :sqrt_fast, :tan_fast, :tanh_fast ) - @eval FastMath Base.@dep_vectorize_1arg Number $f -end -for f in ( - :trunc, :floor, :ceil, :round, # base/floatfuncs.jl - :rad2deg, :deg2rad, :exponent, :significand, # base/math.jl - :sind, :cosd, :tand, :asind, :acosd, :atand, :asecd, :acscd, :acotd, # base/special/trig.jl - ) - @eval @dep_vectorize_1arg Real $f -end -# base/complex.jl -@dep_vectorize_1arg Complex round -@dep_vectorize_1arg Complex float -# base/dates/*.jl -for f in (:unix2datetime, :rata2datetime, :julian2datetime) # base/dates/conversions.jl - @eval Dates Base.@dep_vectorize_1arg Real $f -end -for f in ( - # base/dates/accessors.jl - :year, :month, :day, :week, :dayofmonth, :yearmonth, :monthday, :yearmonthday, - # base/dates/adjusters.jl - :firstdayofweek, :lastdayofweek, :firstdayofmonth, - :lastdayofmonth, :firstdayofyear, :lastdayofyear, - :firstdayofquarter, :lastdayofquarter, - # base/dates/query.jl - :dayname, :dayabbr, :dayofweek, :dayofweekofmonth, - :daysofweekinmonth, :monthname, :monthabbr, :daysinmonth, - :isleapyear, :dayofyear, :daysinyear, :quarterofyear, :dayofquarter, - ) - @eval Dates Base.@dep_vectorize_1arg Dates.TimeType $f -end -for f in ( - :hour, :minute, :second, :millisecond, # base/dates/accessors.jl - :Date, :datetime2unix, :datetime2rata, :datetime2julian, # base/dates/conversions.jl - ) - @eval Dates Base.@dep_vectorize_1arg Dates.DateTime $f -end -@eval Dates Base.@dep_vectorize_1arg Dates.Date Datetime # base/dates/conversions.jl - -# Deprecate @vectorize_2arg-vectorized functions from... -for f in ( - # base/special/gamma.jl - :beta, :lbeta, - # base/math.jl - :log, :hypot, :atan2, - ) - @eval @dep_vectorize_2arg Number $f -end -# base/fastmath.jl -for f in (:pow_fast, :atan2_fast, :hypot_fast, :max_fast, :min_fast, :minmax_fast) - @eval FastMath Base.@dep_vectorize_2arg Number $f -end -for f in ( - :max, :min, # base/math.jl - :copysign, :flipsign, # base/floatfuncs.jl - ) - @eval @dep_vectorize_2arg Real $f -end - -# Deprecate @vectorize_1arg and @vectorize_2arg themselves -macro vectorize_1arg(S,f) - depwarn(string("`@vectorize_1arg` is deprecated in favor of compact broadcast syntax. ", - "Instead of `@vectorize_1arg`'ing function `f` and calling `f(arg)`, call `f.(arg)`."), - :vectorize_1arg) - quote - @dep_vectorize_1arg($(esc(S)),$(esc(f))) - end -end -macro vectorize_2arg(S,f) - depwarn(string("`@vectorize_2arg` is deprecated in favor of compact broadcast syntax. ", - "Instead of `@vectorize_2arg`'ing function `f` and calling `f(arg1, arg2)`, call ", - "`f.(arg1,arg2)`. "), :vectorize_2arg) - quote - @dep_vectorize_2arg($(esc(S)),$(esc(f))) - end -end -export @vectorize_1arg, @vectorize_2arg - -# deprecations for uses of old dot operators (.* etc) as objects, rather than -# just calling them infix. -for op in (:(!=), :≠, :+, :-, :*, :/, :÷, :%, :<, :(<=), :≤, :(==), :>, :>=, :≥, :\, :^, ://, :>>, :<<) - dotop = Symbol('.', op) - # define as const dotop = (a,b) -> ... - # to work around syntax deprecation for dotop(a,b) = ... - @eval const $dotop = (a,b) -> begin - depwarn(string($(string(dotop)), " is no longer a function object; use broadcast(",$op,", ...) instead"), - $(QuoteNode(dotop))) - broadcast($op, a, b) - end - @eval export $dotop -end - -# Devectorize manually vectorized abs methods in favor of compact broadcast syntax -@deprecate abs(f::Base.Pkg.Resolve.MaxSum.Field) abs.(f) -@deprecate abs(B::BitArray) abs.(B) -@deprecate abs(M::Bidiagonal) abs.(M) -@deprecate abs(D::Diagonal) abs.(D) -@deprecate abs(M::Tridiagonal) abs.(M) -@deprecate abs(M::SymTridiagonal) abs.(M) -@deprecate abs(x::AbstractSparseVector) abs.(x) - -# Deprecate @textmime into the Multimedia module, #18441 -@eval Multimedia macro textmime(mime) - Base.depwarn(string("`@textmime \"mime\"` is deprecated; use ", - "`Base.Multimedia.istextmime(::MIME\"mime\") = true` instead" - ), :textmime) - quote - Base.Multimedia.istextmime(::MIME{$(Meta.quot(Symbol(mime)))}) = true - end -end - -@deprecate ipermutedims(A::AbstractArray,p) permutedims(A, invperm(p)) - -# 18696 -function ($)(x, y) - depwarn("`x \$ y` is deprecated. use `xor(x, y)` or `x ⊻ y` instead.", :$) - xor(x, y) -end -export $ - -@deprecate is (===) - -# midpoints of intervals -@deprecate midpoints(r::Range) r[1:length(r)-1] + 0.5*step(r) -@deprecate midpoints(v::AbstractVector) [0.5*(v[i] + v[i+1]) for i in 1:length(v)-1] - -@deprecate_binding Filter Iterators.Filter -@deprecate_binding Zip Iterators.Zip -@deprecate filter(flt, itr) Iterators.filter(flt, itr) -@deprecate_binding rest Iterators.rest -@deprecate_binding countfrom Iterators.countfrom -@deprecate_binding take Iterators.take -@deprecate_binding drop Iterators.drop -@deprecate_binding cycle Iterators.cycle -@deprecate_binding repeated Iterators.repeated - -# promote_op method where the operator is also a type -function promote_op(op::Type, Ts::Type...) - depwarn("promote_op(op::Type, ::Type...) is deprecated as it is no " * - "longer needed in Base. If you need its functionality, consider " * - "defining it locally.", :promote_op) - if isdefined(Core, :Inference) - return Core.Inference.return_type(op, Tuple{Ts...}) - end - return op -end - -# NOTE: Deprecation of `isdefined(a::Array, i::Int)` is implemented in src/array.c -# and deprecation of `invoke(f, (types...), ...)` is implemented in src/builtins.c -# To be removed when 0.6 deprecations are removed - -# NOTE: Deprecation of Channel{T}() is implemented in channels.jl. -# To be removed from there when 0.6 deprecations are removed. - -# Not exported, but probably better to have deprecations anyway -function reduced_dims(::Tuple{}, d::Int) - d < 1 && throw(ArgumentError("dimension must be ≥ 1, got $d")) - () -end -reduced_dims(::Tuple{}, region) = () -function reduced_dims(dims::Dims, region) - Base.depwarn("`reduced_dims` is deprecated for Dims-tuples; pass `indices` to `reduced_indices` instead", :reduced_dims) - map(last, reduced_indices(map(OneTo, dims), region)) -end - -function reduced_dims0(::Tuple{}, d::Int) - d < 1 && throw(ArgumentError("dimension must be ≥ 1, got $d")) - () -end -reduced_dims0(::Tuple{}, region) = () -function reduced_dims0(dims::Dims, region) - Base.depwarn("`reduced_dims0` is deprecated for Dims-tuples; pass `indices` to `reduced_indices0` instead", :reduced_dims0) - map(last, reduced_indices0(map(OneTo, dims), region)) -end - -function reduced_dims(a::AbstractArray, region) - Base.depwarn("`reduced_dims` is deprecated in favor of `reduced_indices`", :reduced_dims) - to_shape(reduced_indices(a, region)) # to_shape keeps the return-type consistent, when it's possible to do so -end - -function reduced_dims0(a::AbstractArray, region) - Base.depwarn("`reduced_dims0` is deprecated in favor of `reduced_indices0`", :reduced_dims) - to_shape(reduced_indices0(a, region)) -end - -# #18218 -@eval Base.LinAlg begin - function arithtype(T) - Base.depwarn(string("arithtype is now deprecated. If you were using it inside a ", - "promote_op call, use promote_op(LinAlg.matprod, Ts...) instead. Otherwise, ", - "if you need its functionality, consider defining it locally."), - :arithtype) - T - end - function arithtype(::Type{Bool}) - Base.depwarn(string("arithtype is now deprecated. If you were using it inside a ", - "promote_op call, use promote_op(LinAlg.matprod, Ts...) instead. Otherwise, ", - "if you need its functionality, consider defining it locally."), - :arithtype) - Int - end -end - -# #19246 -@deprecate den denominator -@deprecate num numerator - -Filesystem.stop_watching(stream::Filesystem._FDWatcher) = depwarn("stop_watching(::_FDWatcher) should not be used", :stop_watching) - -# #19088 -@deprecate takebuf_array take! -@deprecate takebuf_string(b) String(take!(b)) - -# #19288 -@eval Base.Dates begin - function recur(fun::Function, dr::StepRange{<:TimeType}; negate::Bool=false, limit::Int=10000) - Base.depwarn("Dates.recur is deprecated, use filter instead.",:recur) - if negate - filter(x -> !fun(x), dr) - else - filter(fun, dr) - end - end - recur(fun::Function, start::T, stop::T; step::Period=Day(1), negate::Bool=false, limit::Int=10000) where {T<:TimeType} = recur(fun, start:step:stop; negate=negate) -end - -# Index conversions revamp; #19730 -function getindex(A::LogicalIndex, i::Int) - depwarn("getindex(A::LogicalIndex, i) is deprecated; use iteration or index into the result of `collect(A)` instead.", :getindex) - checkbounds(A, i) - first(Iterators.drop(A, i-1)) -end -function to_indexes(I...) - Istr = join(I, ", ") - depwarn("to_indexes is deprecated; pass both the source array `A` and indices as `to_indices(A, $Istr)` instead.", :to_indexes) - map(_to_index, I) -end -_to_index(i) = to_index(I) -_to_index(c::Colon) = c -const _colon_usage_msg = "convert Colons to a set of indices for indexing into array `A` by passing them in a complete tuple of indices `I` to `to_indices(A, I)`" -function getindex(::Colon, i) - depwarn("getindex(::Colon, i) is deprecated; $_colon_usage_msg", :getindex) - to_index(i) -end -function unsafe_getindex(::Colon, i::Integer) - depwarn("getindex(::Colon, i) is deprecated; $_colon_usage_msg", :unsafe_getindex) - to_index(i) -end -function step(::Colon) - depwarn("step(::Colon) is deprecated; $_colon_usage_msg", :step) - 1 -end -function isempty(::Colon) - depwarn("isempty(::Colon) is deprecated; $_colon_usage_msg", :isempty) - false -end -function in(::Integer, ::Colon) - depwarn("in(::Integer, ::Colon) is deprecated; $_colon_usage_msg", :in) - true -end - -# #18931 -@deprecate cummin(A, dim=1) accumulate(min, A, dim) -@deprecate cummax(A, dim=1) accumulate(max, A, dim) - -# #19598 -@deprecate sumabs(x) sum(abs, x) -@deprecate sumabs(A, region) sum(abs, A, region) -@deprecate sumabs2(x) sum(abs2, x) -@deprecate sumabs2(A, region) sum(abs2, A, region) -@deprecate minabs(x) minimum(abs, x) -@deprecate minabs(A, region) minimum(abs, A, region) -@deprecate maxabs(x) maximum(abs, x) -@deprecate maxabs(A, region) maximum(abs, A, region) - -for (dep, f, op) in [(:sumabs!, :sum!, :abs), - (:sumabs2!, :sum!, :abs2), - (:minabs!, :minimum!, :abs), - (:maxabs!, :maximum!, :abs)] - @eval function ($dep)(r, A; init=true) - Base.depwarn("$dep(r, A; init=$init) is deprecated, use $f($op, r, A; init=$init) instead.", Symbol($dep)) - ($f)($op, r, A; init=init) - end -end - -## Deprecate broadcast_zpreserving[!] (wasn't exported, but might as well be friendly) -function gen_broadcast_function_sparse(genbody::Function, f::Function, is_first_sparse::Bool) - body = genbody(f, is_first_sparse) - @eval let - local _F_ - function _F_{Tv,Ti}(B::SparseMatrixCSC{Tv,Ti}, A_1, A_2) - $body - end - _F_ - end -end -function gen_broadcast_body_zpreserving(f::Function, is_first_sparse::Bool) - F = Expr(:quote, f) - if is_first_sparse - A1 = :(A_1) - A2 = :(A_2) - op1 = :(val1) - op2 = :(val2) - else - A1 = :(A_2) - A2 = :(A_1) - op1 = :(val2) - op2 = :(val1) - end - quote - Base.Broadcast.check_broadcast_indices(indices(B), $A1) - Base.Broadcast.check_broadcast_indices(indices(B), $A2) - - nnzB = isempty(B) ? 0 : - nnz($A1) * div(B.n, ($A1).n) * div(B.m, ($A1).m) - if length(B.rowval) < nnzB - resize!(B.rowval, nnzB) - end - if length(B.nzval) < nnzB - resize!(B.nzval, nnzB) - end - z = zero(Tv) - - ptrB = 1 - B.colptr[1] = 1 - - @inbounds for col = 1:B.n - ptr1::Int = ($A1).n == 1 ? ($A1).colptr[1] : ($A1).colptr[col] - stop1::Int = ($A1).n == 1 ? ($A1).colptr[2] : ($A1).colptr[col+1] - col2 = size($A2, 2) == 1 ? 1 : col - row = 1 - while ptr1 < stop1 && row <= B.m - if ($A1).m != 1 - row = ($A1).rowval[ptr1] - end - row2 = size($A2, 1) == 1 ? 1 : row - val1 = ($A1).nzval[ptr1] - val2 = ($A2)[row2,col2] - res = ($F)($op1, $op2) - if res != z - B.rowval[ptrB] = row - B.nzval[ptrB] = res - ptrB += 1 - end - if ($A1).m != 1 - ptr1 += 1 - else - row += 1 - end - end - B.colptr[col+1] = ptrB - end - deleteat!(B.rowval, B.colptr[end]:length(B.rowval)) - deleteat!(B.nzval, B.colptr[end]:length(B.nzval)) - nothing - end -end -for (Bsig, A1sig, A2sig, gbb, funcname) in - ( - (SparseMatrixCSC , SparseMatrixCSC , Array, :gen_broadcast_body_zpreserving, :_broadcast_zpreserving!), - (SparseMatrixCSC , Array , SparseMatrixCSC, :gen_broadcast_body_zpreserving, :_broadcast_zpreserving!), - (SparseMatrixCSC , Number , SparseMatrixCSC, :gen_broadcast_body_zpreserving, :_broadcast_zpreserving!), - (SparseMatrixCSC , SparseMatrixCSC , Number, :gen_broadcast_body_zpreserving, :_broadcast_zpreserving!), - (SparseMatrixCSC , BitArray , SparseMatrixCSC, :gen_broadcast_body_zpreserving, :_broadcast_zpreserving!), - (SparseMatrixCSC , SparseMatrixCSC , BitArray, :gen_broadcast_body_zpreserving, :_broadcast_zpreserving!), - ) - @eval let cache = Dict{Function,Function}() - global $funcname - function $funcname(f::Function, B::$Bsig, A1::$A1sig, A2::$A2sig) - func = @get! cache f gen_broadcast_function_sparse($gbb, f, ($A1sig) <: SparseMatrixCSC) - # need eval because func was just created by gen_broadcast_function_sparse - # TODO: convert this to a generated function - eval(current_module(), Expr(:body, Expr(:return, Expr(:call, QuoteNode(func), QuoteNode(B), QuoteNode(A1), QuoteNode(A2))))) - return B - end - end # let broadcast_cache -end -_broadcast_zpreserving!(args...) = broadcast!(args...) -# note: promote_eltype_op also deprecated, defined later in this file -_broadcast_zpreserving(f, As...) = - broadcast!(f, similar(Array{_promote_eltype_op(f, As...)}, Base.Broadcast.broadcast_indices(As...)), As...) -_broadcast_zpreserving(f::Function, A_1::SparseMatrixCSC{Tv1,Ti1}, A_2::SparseMatrixCSC{Tv2,Ti2}) where {Tv1,Ti1,Tv2,Ti2} = - _broadcast_zpreserving!(f, spzeros(promote_type(Tv1, Tv2), promote_type(Ti1, Ti2), Base.to_shape(Base.Broadcast.broadcast_indices(A_1, A_2))), A_1, A_2) -_broadcast_zpreserving(f::Function, A_1::SparseMatrixCSC{<:Any,Ti}, A_2::Union{Array,BitArray,Number}) where {Ti} = - _broadcast_zpreserving!(f, spzeros(promote_eltype(A_1, A_2), Ti, Base.to_shape(Base.Broadcast.broadcast_indices(A_1, A_2))), A_1, A_2) -_broadcast_zpreserving(f::Function, A_1::Union{Array,BitArray,Number}, A_2::SparseMatrixCSC{<:Any,Ti}) where {Ti} = - _broadcast_zpreserving!(f, spzeros(promote_eltype(A_1, A_2), Ti, Base.to_shape(Base.Broadcast.broadcast_indices(A_1, A_2))), A_1, A_2) - -function _depstring_bczpres() - return string("broadcast_zpreserving[!] is deprecated. Generic sparse broadcast[!] ", - "provides most of broadcast_zpreserving[!]'s functionality. If you have a use case ", - "that generic sparse broadcast[!] does not cover, please describe your use case in ", - " issue #19533 (https://github.com/JuliaLang/julia/issues/19533).") -end -function _depwarn_bczpres(f, args...) - depwarn(_depstring_bczpres(), :broadcast_zpreserving) - return _broadcast_zpreserving(f, args...) -end -function _depwarn_bczpres!(f, args...) - depwarn(_depstring_bczpres(), :broadcast_zpreserving!) - return _broadcast_zpreserving!(f, args...) -end -@eval SparseArrays begin - broadcast_zpreserving(f, args...) = Base._depwarn_bczpres(f, args...) - broadcast_zpreserving(f, A::SparseMatrixCSC, B::SparseMatrixCSC) = Base._depwarn_bczpres(f, A, B) - broadcast_zpreserving(f, A::SparseMatrixCSC, B::Union{Array,BitArray,Number}) = Base._depwarn_bczpres(f, A, B) - broadcast_zpreserving(f, A::Union{Array,BitArray,Number}, B::SparseMatrixCSC) = Base._depwarn_bczpres(f, A, B) - broadcast_zpreserving!(f, args...) = Base._depwarn_bczpres!(f, args...) - broadcast_zpreserving!(f, C::SparseMatrixCSC, A::SparseMatrixCSC, B::Union{Array,BitArray,Number}) = Base._depwarn_bczpres!(f, C, A, B) - broadcast_zpreserving!(f, C::SparseMatrixCSC, A::Union{Array,BitArray,Number}, B::SparseMatrixCSC) = Base._depwarn_bczpres!(f, C, A, B) -end - -# #19719 -@deprecate getindex(t::Tuple, r::AbstractArray) getindex(t, vec(r)) -@deprecate getindex(t::Tuple, b::AbstractArray{Bool}) getindex(t, vec(b)) - -# Deprecate isimag (#19947). -@deprecate isimag(z::Number) iszero(real(z)) - -# Deprecate vectorized xor in favor of compact broadcast syntax -@deprecate xor(a::Bool, B::BitArray) xor.(a, B) -@deprecate xor(A::BitArray, b::Bool) xor.(A, b) -@deprecate xor(a::Number, B::AbstractArray) xor.(a, B) -@deprecate xor(A::AbstractArray, b::Number) xor.(A, b) -@deprecate xor(A::AbstractArray, B::AbstractArray) xor.(A, B) - -# QuadGK moved to a package (#19741) -function quadgk(args...; kwargs...) - error(string(quadgk, args, " has been moved to the package QuadGK.jl.\n", - "Run Pkg.add(\"QuadGK\") to install QuadGK on Julia v0.6 and later, and then run `using QuadGK`.")) -end -export quadgk - -# Collections functions moved to a package (#19800) -module Collections - export PriorityQueue, enqueue!, dequeue!, heapify!, heapify, heappop!, heappush!, isheap, peek - for f in (:PriorityQueue, :enqueue!, :dequeue!, :heapify!, :heapify, :heappop!, :heappush!, :isheap, :peek) - @eval function ($f)(args...; kwargs...) - error(string($f, args, " has been moved to the package DataStructures.jl.\n", - "Run Pkg.add(\"DataStructures\") to install DataStructures on Julia v0.6 and later, ", - "and then run `using DataStructures`.")) - end - end -end -export Collections - -# Broadcast now returns a BitArray when the resulting eltype is Bool (#17623) -@deprecate bitbroadcast broadcast - -# Deprecate two-argument map! (map!(f, A)) for a cycle in anticipation of semantic change -@deprecate map!(f::F, A::AbstractArray) where {F} map!(f, A, A) -@deprecate asyncmap!(f, c; ntasks=0, batch_size=nothing) asyncmap!(f, c, c; ntasks=ntasks, batch_size=batch_size) - -# Not exported, but used outside Base -_promote_array_type(F, ::Type, ::Type, T::Type) = T -_promote_array_type(F, ::Type{<:Real}, ::Type{A}, ::Type) where {A<:AbstractFloat} = A -_promote_array_type(F, ::Type{<:Integer}, ::Type{A}, ::Type) where {A<:Integer} = A -_promote_array_type(::typeof(/), ::Type{<:Integer}, ::Type{<:Integer}, T::Type) = T -_promote_array_type(::typeof(\), ::Type{<:Integer}, ::Type{<:Integer}, T::Type) = T -_promote_array_type(::typeof(/), ::Type{<:Integer}, ::Type{Bool}, T::Type) = T -_promote_array_type(::typeof(\), ::Type{<:Integer}, ::Type{Bool}, T::Type) = T -_promote_array_type(F, ::Type{<:Integer}, ::Type{Bool}, T::Type) = T -_promote_array_type(F, ::Type{<:Union{Complex, Real}}, ::Type{Complex{T}}, ::Type) where {T<:AbstractFloat} = Complex{T} -function promote_array_type(F, R, S, T) - Base.depwarn("`promote_array_type` is deprecated as it is no longer needed " * - "in Base. See https://github.com/JuliaLang/julia/issues/19669 " * - "for more information.", :promote_array_type) - _promote_array_type(F, R, S, T) -end - -# Deprecate manually vectorized abs2 methods in favor of compact broadcast syntax -@deprecate abs2(x::AbstractSparseVector) abs2.(x) - -# Deprecate manually vectorized sign methods in favor of compact broadcast syntax -@deprecate sign(A::AbstractArray) sign.(A) - -# Deprecate manually vectorized trigonometric and hyperbolic functions in favor of compact broadcast syntax -for f in (:sec, :sech, :secd, :asec, :asech, - :csc, :csch, :cscd, :acsc, :acsch, - :cot, :coth, :cotd, :acot, :acoth) - @eval @deprecate $f(A::AbstractArray{<:Number}) $f.(A) -end - -# Deprecate vectorized two-argument complex in favor of compact broadcast syntax -@deprecate complex(A::AbstractArray, b::Real) complex.(A, b) -@deprecate complex(a::Real, B::AbstractArray) complex.(a, B) -@deprecate complex(A::AbstractArray, B::AbstractArray) complex.(A, B) - -# Deprecate manually vectorized clamp methods in favor of compact broadcast syntax -@deprecate clamp(A::AbstractArray, lo, hi) clamp.(A, lo, hi) - -# Deprecate manually vectorized round methods in favor of compact broadcast syntax -@deprecate round(M::Bidiagonal) round.(M) -@deprecate round(M::Tridiagonal) round.(M) -@deprecate round(M::SymTridiagonal) round.(M) -@deprecate round(::Type{T}, x::AbstractArray) where {T} round.(T, x) -@deprecate round(::Type{T}, x::AbstractArray, r::RoundingMode) where {T} round.(T, x, r) -@deprecate round(x::AbstractArray, r::RoundingMode) round.(x, r) -@deprecate round(x::AbstractArray, digits::Integer, base::Integer = 10) round.(x, digits, base) - -# Deprecate manually vectorized trunc methods in favor of compact broadcast syntax -@deprecate trunc(M::Bidiagonal) trunc.(M) -@deprecate trunc(M::Tridiagonal) trunc.(M) -@deprecate trunc(M::SymTridiagonal) trunc.(M) -@deprecate trunc(::Type{T}, x::AbstractArray) where {T} trunc.(T, x) -@deprecate trunc(x::AbstractArray, digits::Integer, base::Integer = 10) trunc.(x, digits, base) - -# Deprecate manually vectorized floor methods in favor of compact broadcast syntax -@deprecate floor(M::Bidiagonal) floor.(M) -@deprecate floor(M::Tridiagonal) floor.(M) -@deprecate floor(M::SymTridiagonal) floor.(M) -@deprecate floor(::Type{T}, A::AbstractArray) where {T} floor.(T, A) -@deprecate floor(A::AbstractArray, digits::Integer, base::Integer = 10) floor.(A, digits, base) - -# Deprecate manually vectorized ceil methods in favor of compact broadcast syntax -@deprecate ceil(M::Bidiagonal) ceil.(M) -@deprecate ceil(M::Tridiagonal) ceil.(M) -@deprecate ceil(M::SymTridiagonal) ceil.(M) -@deprecate ceil(::Type{T}, x::AbstractArray) where {T} ceil.(T, x) -@deprecate ceil(x::AbstractArray, digits::Integer, base::Integer = 10) ceil.(x, digits, base) - -# Deprecate manually vectorized `big` methods in favor of compact broadcast syntax -@deprecate big(r::UnitRange) big.(r) -@deprecate big(r::StepRange) big.(r) -@deprecate big(r::StepRangeLen) big.(r) -@deprecate big(r::LinSpace) big.(r) -@deprecate big(x::AbstractArray{<:Integer}) big.(x) -@deprecate big(x::AbstractArray{<:AbstractFloat}) big.(x) -@deprecate big(A::LowerTriangular) big.(A) -@deprecate big(A::UpperTriangular) big.(A) -@deprecate big(A::Base.LinAlg.UnitLowerTriangular) big.(A) -@deprecate big(A::Base.LinAlg.UnitUpperTriangular) big.(A) -@deprecate big(B::Bidiagonal) big.(B) -@deprecate big(A::AbstractArray{<:Complex{<:Integer}}) big.(A) -@deprecate big(A::AbstractArray{<:Complex{<:AbstractFloat}}) big.(A) -@deprecate big(x::AbstractArray{<:Complex{<:Rational{<:Integer}}}) big.(A) - -# Deprecate manually vectorized div methods in favor of compact broadcast syntax -@deprecate div(A::Number, B::AbstractArray) div.(A, B) -@deprecate div(A::AbstractArray, B::Number) div.(A, B) -@deprecate div(A::AbstractArray, B::AbstractArray) div.(A, B) - -# Deprecate manually vectorized rem methods in favor of compact broadcast syntax -@deprecate rem(A::Number, B::AbstractArray) rem.(A, B) -@deprecate rem(A::AbstractArray, B::Number) rem.(A, B) - -# Deprecate manually vectorized div, mod, and % methods for dates -@deprecate div(X::StridedArray{P}, y::P) where {P<:Dates.Period} div.(X, y) -@deprecate div(X::StridedArray{<:Dates.Period}, y::Integer) div.(X, y) -@deprecate (%)(X::StridedArray{P}, y::P) where {P<:Dates.Period} X .% y -@deprecate mod(X::StridedArray{P}, y::P) where {P<:Dates.Period} mod.(X, y) - -# Deprecate manually vectorized mod methods in favor of compact broadcast syntax -@deprecate mod(B::BitArray, x::Bool) mod.(B, x) -@deprecate mod(x::Bool, B::BitArray) mod.(x, B) -@deprecate mod(A::AbstractArray, B::AbstractArray) mod.(A, B) -@deprecate mod(x::Number, A::AbstractArray) mod.(x, A) -@deprecate mod(A::AbstractArray, x::Number) mod.(A, x) - -# Deprecate vectorized & in favor of dot syntax -@deprecate (&)(a::Bool, B::BitArray) a .& B -@deprecate (&)(A::BitArray, b::Bool) A .& b -@deprecate (&)(a::Number, B::AbstractArray) a .& B -@deprecate (&)(A::AbstractArray, b::Number) A .& b -@deprecate (&)(A::AbstractArray, B::AbstractArray) A .& B - -# Deprecate vectorized | in favor of compact broadcast syntax -@deprecate (|)(a::Bool, B::BitArray) a .| B -@deprecate (|)(A::BitArray, b::Bool) A .| b -@deprecate (|)(a::Number, B::AbstractArray) a .| B -@deprecate (|)(A::AbstractArray, b::Number) A .| b -@deprecate (|)(A::AbstractArray, B::AbstractArray) A .| B - -# Deprecate vectorized ifelse -@deprecate ifelse(c::AbstractArray{Bool}, x, y) ifelse.(c, x, y) -@deprecate ifelse(c::AbstractArray{Bool}, x, y::AbstractArray) ifelse.(c, x, y) -@deprecate ifelse(c::AbstractArray{Bool}, x::AbstractArray, y) ifelse.(c, x, y) -@deprecate ifelse(c::AbstractArray{Bool}, x::AbstractArray, y::AbstractArray) ifelse.(c, x, y) - -# Deprecate vectorized ! -@deprecate(!(A::AbstractArray{Bool}), .!A) # parens for #20541 -@deprecate(!(B::BitArray), .!B) # parens for #20541 -!(::typeof(()->())) = () # make sure ! has at least 4 methods so that for-loops don't end up getting a back-edge to depwarn - -# Deprecate vectorized ~ -@deprecate ~(A::AbstractArray) .~A -@deprecate ~(B::BitArray) .~B - -function frexp(A::Array{<:AbstractFloat}) - depwarn(string("`frexp(x::Array)` is discontinued. Though not a direct replacement, ", - "consider using dot-syntax to `broadcast` scalar `frexp` over `Array`s ", - "instead, for example `frexp.(rand(4))`."), :frexp) - F = similar(A) - E = Array{Int}(size(A)) - for (iF, iE, iA) in zip(eachindex(F), eachindex(E), eachindex(A)) - F[iF], E[iE] = frexp(A[iA]) - end - return (F, E) -end - -# Deprecate reducing isinteger over arrays -@deprecate isinteger(A::AbstractArray) all(isinteger, A) - -# Deprecate promote_eltype_op (#19814, #19937) -_promote_eltype_op(::Any) = Any -_promote_eltype_op(op, A) = (@_inline_meta; promote_op(op, eltype(A))) -_promote_eltype_op(op, A, B) = (@_inline_meta; promote_op(op, eltype(A), eltype(B))) -_promote_eltype_op(op, A, B, C, D...) = (@_inline_meta; _promote_eltype_op(op, eltype(A), _promote_eltype_op(op, B, C, D...))) -@inline function promote_eltype_op(args...) - depwarn(""" - `promote_eltype_op` is deprecated and should not be used. - See https://github.com/JuliaLang/julia/issues/19669.""", - :promote_eltype_op) - _promote_eltype_op(args...) -end - - -function unsafe_wrap(::Type{String}, p::Union{Ptr{UInt8},Ptr{Int8}}, len::Integer, own::Bool=false) - Base.depwarn("unsafe_wrap(String, ...) is deprecated; use `unsafe_string` instead.", :unsafe_wrap) - #ccall(:jl_array_to_string, Ref{String}, (Any,), - # ccall(:jl_ptr_to_array_1d, Vector{UInt8}, (Any, Ptr{UInt8}, Csize_t, Cint), - # Vector{UInt8}, p, len, own)) - unsafe_string(p, len) -end -unsafe_wrap(::Type{String}, p::Union{Ptr{UInt8},Ptr{Int8}}, own::Bool=false) = - unsafe_wrap(String, p, ccall(:strlen, Csize_t, (Ptr{UInt8},), p), own) -unsafe_wrap(::Type{String}, p::Cstring, own::Bool=false) = unsafe_wrap(String, convert(Ptr{UInt8}, p), own) -unsafe_wrap(::Type{String}, p::Cstring, len::Integer, own::Bool=false) = - unsafe_wrap(String, convert(Ptr{UInt8}, p), len, own) - -# #19660 -@deprecate finalize(sa::LibGit2.StrArrayStruct) LibGit2.free(sa) -@deprecate finalize(sa::LibGit2.Buffer) LibGit2.free(sa) - -## produce, consume, and task iteration -# NOTE: When removing produce/consume, also remove field Task.consumers and related code in -# task.jl and event.jl - -function produce(v) - depwarn("produce is now deprecated. Use Channels for inter-task communication.", :produce) - - ct = current_task() - local empty, t, q - while true - q = ct.consumers - if isa(q,Task) - t = q - ct.consumers = nothing - empty = true - break - elseif isa(q,Condition) && !isempty(q.waitq) - t = shift!(q.waitq) - empty = isempty(q.waitq) - break - end - wait() - end - - t.state == :runnable || throw(AssertionError("producer.consumer.state == :runnable")) - if empty - schedule_and_wait(t, v) - while true - # wait until there are more consumers - q = ct.consumers - if isa(q,Task) - return q.result - elseif isa(q,Condition) && !isempty(q.waitq) - return q.waitq[1].result - end - wait() - end - else - schedule(t, v) - # make sure `t` runs before us. otherwise, the producer might - # finish before `t` runs again, causing it to see the producer - # as done, causing done(::Task, _) to miss the value `v`. - # see issue #7727 - yield() - return q.waitq[1].result - end -end -produce(v...) = produce(v) -export produce - -function consume(P::Task, values...) - depwarn("consume is now deprecated. Use Channels for inter-task communication.", :consume) - - if istaskdone(P) - return wait(P) - end - - ct = current_task() - ct.result = length(values)==1 ? values[1] : values - - #### un-optimized version - #if P.consumers === nothing - # P.consumers = Condition() - #end - #push!(P.consumers.waitq, ct) - # optimized version that avoids the queue for 1 consumer - if P.consumers === nothing || (isa(P.consumers,Condition)&&isempty(P.consumers.waitq)) - P.consumers = ct - else - if isa(P.consumers, Task) - t = P.consumers - P.consumers = Condition() - push!(P.consumers.waitq, t) - end - push!(P.consumers.waitq, ct) - end - - P.state == :runnable ? schedule_and_wait(P) : wait() # don't attempt to queue it twice -end -export consume - -function start(t::Task) - depwarn(string("Task iteration is now deprecated.", - " Use Channels for inter-task communication. ", - " A for-loop on a Channel object is terminated by calling `close` on the object."), :taskfor) - nothing -end -function done(t::Task, val) - t.result = consume(t) - istaskdone(t) -end -next(t::Task, val) = (t.result, nothing) -iteratorsize(::Type{Task}) = SizeUnknown() -iteratoreltype(::Type{Task}) = EltypeUnknown() - -isempty(::Task) = error("isempty not defined for Tasks") - -@eval Base.Test begin - approx_full(x::AbstractArray) = x - approx_full(x::Number) = x - approx_full(x) = full(x) - - function test_approx_eq(va, vb, Eps, astr, bstr) - va = approx_full(va) - vb = approx_full(vb) - la, lb = length(linearindices(va)), length(linearindices(vb)) - if la != lb - error("lengths of ", astr, " and ", bstr, " do not match: ", - "\n ", astr, " (length $la) = ", va, - "\n ", bstr, " (length $lb) = ", vb) - end - diff = real(zero(eltype(va))) - for (xa, xb) = zip(va, vb) - if isfinite(xa) && isfinite(xb) - diff = max(diff, abs(xa-xb)) - elseif !isequal(xa,xb) - error("mismatch of non-finite elements: ", - "\n ", astr, " = ", va, - "\n ", bstr, " = ", vb) - end - end - - if !isnan(Eps) && !(diff <= Eps) - sdiff = string("|", astr, " - ", bstr, "| <= ", Eps) - error("assertion failed: ", sdiff, - "\n ", astr, " = ", va, - "\n ", bstr, " = ", vb, - "\n difference = ", diff, " > ", Eps) - end - end - - array_eps(a::AbstractArray{Complex{T}}) where {T} = eps(float(maximum(x->(isfinite(x) ? abs(x) : T(NaN)), a))) - array_eps(a) = eps(float(maximum(x->(isfinite(x) ? abs(x) : oftype(x,NaN)), a))) - - test_approx_eq(va, vb, astr, bstr) = - test_approx_eq(va, vb, 1E4*length(linearindices(va))*max(array_eps(va), array_eps(vb)), astr, bstr) - - """ - @test_approx_eq_eps(a, b, tol) - - Test two floating point numbers `a` and `b` for equality taking into account - a margin of tolerance given by `tol`. - """ - macro test_approx_eq_eps(a, b, c) - Base.depwarn(string("@test_approx_eq_eps is deprecated, use `@test ", a, " ≈ ", b, " atol=", c, "` instead"), - Symbol("@test_approx_eq_eps")) - :(test_approx_eq($(esc(a)), $(esc(b)), $(esc(c)), $(string(a)), $(string(b)))) - end - export @test_approx_eq_eps - - """ - @test_approx_eq(a, b) - - Deprecated. Test two floating point numbers `a` and `b` for equality taking into - account small numerical errors. - """ - macro test_approx_eq(a, b) - Base.depwarn(string("@test_approx_eq is deprecated, use `@test ", a, " ≈ ", b, "` instead"), - Symbol("@test_approx_eq")) - :(test_approx_eq($(esc(a)), $(esc(b)), $(string(a)), $(string(b)))) - end - export @test_approx_eq -end - -# Deprecate partial linear indexing -function partial_linear_indexing_warning_lookup(nidxs_remaining) - # We need to figure out how many indices were passed for a sensible deprecation warning - opts = JLOptions() - if opts.depwarn > 0 - # Find the caller -- this is very expensive so we don't want to do it twice - bt = backtrace() - found = false - call = StackTraces.UNKNOWN - caller = StackTraces.UNKNOWN - for frame in bt - lkups = StackTraces.lookup(frame) - for caller in lkups - if caller == StackTraces.UNKNOWN - continue - end - found && @goto found - if caller.func in (:getindex, :setindex!, :view) - found = true - call = caller - end - end - end - @label found - fn = "`reshape`" - if call != StackTraces.UNKNOWN && !isnull(call.linfo) - # Try to grab the number of dimensions in the parent array - mi = get(call.linfo) - args = mi.specTypes.parameters - if length(args) >= 2 && args[2] <: AbstractArray - fn = "`reshape(A, Val{$(ndims(args[2]) - nidxs_remaining + 1)})`" - end - end - _depwarn("Partial linear indexing is deprecated. Use $fn to make the dimensionality of the array match the number of indices.", opts, bt, caller) - end -end -function partial_linear_indexing_warning(n) - depwarn("Partial linear indexing is deprecated. Use `reshape(A, Val{$n})` to make the dimensionality of the array match the number of indices.", (:getindex, :setindex!, :view)) -end - -# Deprecate Array(T, dims...) in favor of proper type constructors -@deprecate Array(::Type{T}, d::NTuple{N,Int}) where {T,N} Array{T}(d) -@deprecate Array(::Type{T}, d::Int...) where {T} Array{T}(d...) -@deprecate Array(::Type{T}, m::Int) where {T} Array{T}(m) -@deprecate Array(::Type{T}, m::Int,n::Int) where {T} Array{T}(m,n) -@deprecate Array(::Type{T}, m::Int,n::Int,o::Int) where {T} Array{T}(m,n,o) -@deprecate Array(::Type{T}, d::Integer...) where {T} Array{T}(convert(Tuple{Vararg{Int}}, d)) -@deprecate Array(::Type{T}, m::Integer) where {T} Array{T}(Int(m)) -@deprecate Array(::Type{T}, m::Integer,n::Integer) where {T} Array{T}(Int(m),Int(n)) -@deprecate Array(::Type{T}, m::Integer,n::Integer,o::Integer) where {T} Array{T}(Int(m),Int(n),Int(o)) - -# Likewise for SharedArrays -@deprecate SharedArray(::Type{T}, dims::Dims{N}; kwargs...) where {T,N} SharedArray{T}(dims; kwargs...) -@deprecate SharedArray(::Type{T}, dims::Int...; kwargs...) where {T} SharedArray{T}(dims...; kwargs...) -@deprecate(SharedArray(filename::AbstractString, ::Type{T}, dims::NTuple{N,Int}, offset; kwargs...) where {T,N}, - SharedArray{T}(filename, dims, offset; kwargs...)) -@deprecate(SharedArray(filename::AbstractString, ::Type{T}, dims::NTuple, offset; kwargs...) where {T}, - SharedArray{T}(filename, dims, offset; kwargs...)) - -@noinline function is_intrinsic_expr(x::ANY) - Base.depwarn("is_intrinsic_expr is deprecated. There are no intrinsic functions anymore.", :is_intrinsic_expr) - return false -end - -@deprecate EachLine(stream, ondone) EachLine(stream, ondone=ondone) - -# These conversions should not be defined, see #19896 -@deprecate convert(::Type{T}, x::Dates.Period) where {T<:Number} convert(T, Dates.value(x)) -@deprecate convert(::Type{T}, x::Real) where {T<:Dates.Period} T(x) -@deprecate convert(::Type{R}, x::Dates.DateTime) where {R<:Real} R(Dates.value(x)) -@deprecate convert(::Type{R}, x::Dates.Date) where {R<:Real} R(Dates.value(x)) -@deprecate convert(::Type{Dates.DateTime}, x::Real) Dates.DateTime(Dates.Millisecond(x)) -@deprecate convert(::Type{Dates.Date}, x::Real) Dates.Date(Dates.Day(x)) - -function colon(start::T, stop::T) where T<:Dates.Period - depwarn("$start:$stop is deprecated, use $start:$T(1):$stop instead.", :colon) - colon(start, T(1), stop) -end - -# LibGit2 refactor (#19839) -@eval Base.LibGit2 begin - Base.@deprecate_binding Oid GitHash - Base.@deprecate_binding GitAnyObject GitUnknownObject - - @deprecate owner(x) repository(x) false - @deprecate get(::Type{T}, repo::GitRepo, x) where {T<:GitObject} T(repo, x) false - @deprecate get(::Type{T}, repo::GitRepo, oid::GitHash, oid_size::Int) where {T<:GitObject} T(repo, GitShortHash(oid, oid_size)) false - @deprecate revparse(repo::GitRepo, objname::AbstractString) GitObject(repo, objname) false - @deprecate object(repo::GitRepo, te::GitTreeEntry) GitObject(repo, te) false - @deprecate commit(ann::GitAnnotated) GitHash(ann) false - @deprecate lookup(repo::GitRepo, oid::GitHash) GitBlob(repo, oid) false - function Base.cat(repo::GitRepo, ::Type{T}, spec::Union{AbstractString,AbstractGitHash}) where T<:GitObject - Base.depwarn("cat(repo::GitRepo, T, spec) is deprecated, use content(T(repo, spec))", :cat) - try - return content(GitBlob(repo, spec)) - catch e - isa(e, LibGit2.GitError) && return nothing - rethrow(e) - end - end - Base.cat(repo::GitRepo, spec::Union{AbstractString,AbstractGitHash}) = cat(repo, GitBlob, spec) -end - -# when this deprecation is deleted, remove all calls to it, and all -# negate=nothing keyword arguments, from base/dates/adjusters.jl -@eval Dates function deprecate_negate(f, func, sig, negate) - if negate === nothing - return func - else - msg = "$f($sig; negate=$negate) is deprecated, use $f(" - negate && (msg *= "!") - msg *= "$sig) instead." - Base.depwarn(msg, f) - return negate ? !func : func - end -end - -# TODO: remove `:typealias` from BINDING_HEADS in base/docs/Docs.jl -# TODO: remove `'typealias` case in expand-table in julia-syntax.scm - -# FloatRange replaced by StepRangeLen - -## Old-style floating point ranges. We reimplement them here because -## the replacement StepRangeLen also has 4 real-valued fields, which -## makes deprecation tricky. See #20506. - -struct Use_StepRangeLen_Instead{T<:AbstractFloat} <: Range{T} - start::T - step::T - len::T - divisor::T -end - -Use_StepRangeLen_Instead(a::AbstractFloat, s::AbstractFloat, l::Real, d::AbstractFloat) = - Use_StepRangeLen_Instead{promote_type(typeof(a),typeof(s),typeof(d))}(a,s,l,d) - -isempty(r::Use_StepRangeLen_Instead) = length(r) == 0 - -step(r::Use_StepRangeLen_Instead) = r.step/r.divisor - -length(r::Use_StepRangeLen_Instead) = Integer(r.len) - -first(r::Use_StepRangeLen_Instead{T}) where {T} = convert(T, r.start/r.divisor) - -last(r::Use_StepRangeLen_Instead{T}) where {T} = convert(T, (r.start + (r.len-1)*r.step)/r.divisor) - -start(r::Use_StepRangeLen_Instead) = 0 -done(r::Use_StepRangeLen_Instead, i::Int) = length(r) <= i -next(r::Use_StepRangeLen_Instead{T}, i::Int) where {T} = - (convert(T, (r.start + i*r.step)/r.divisor), i+1) - -function getindex(r::Use_StepRangeLen_Instead{T}, i::Integer) where T - @_inline_meta - @boundscheck checkbounds(r, i) - convert(T, (r.start + (i-1)*r.step)/r.divisor) -end - -function getindex(r::Use_StepRangeLen_Instead, s::OrdinalRange) - @_inline_meta - @boundscheck checkbounds(r, s) - Use_StepRangeLen_Instead(r.start + (first(s)-1)*r.step, step(s)*r.step, length(s), r.divisor) -end - --(r::Use_StepRangeLen_Instead) = Use_StepRangeLen_Instead(-r.start, -r.step, r.len, r.divisor) -+(x::Real, r::Use_StepRangeLen_Instead) = Use_StepRangeLen_Instead(r.divisor*x + r.start, r.step, r.len, r.divisor) --(x::Real, r::Use_StepRangeLen_Instead) = Use_StepRangeLen_Instead(r.divisor*x - r.start, -r.step, r.len, r.divisor) --(r::Use_StepRangeLen_Instead, x::Real) = Use_StepRangeLen_Instead(r.start - r.divisor*x, r.step, r.len, r.divisor) -*(x::Real, r::Use_StepRangeLen_Instead) = Use_StepRangeLen_Instead(x*r.start, x*r.step, r.len, r.divisor) -*(r::Use_StepRangeLen_Instead, x::Real) = x * r -/(r::Use_StepRangeLen_Instead, x::Real) = Use_StepRangeLen_Instead(r.start/x, r.step/x, r.len, r.divisor) -promote_rule(::Type{Use_StepRangeLen_Instead{T1}},::Type{Use_StepRangeLen_Instead{T2}}) where {T1,T2} = - Use_StepRangeLen_Instead{promote_type(T1,T2)} -convert(::Type{Use_StepRangeLen_Instead{T}}, r::Use_StepRangeLen_Instead{T}) where {T<:AbstractFloat} = r -convert(::Type{Use_StepRangeLen_Instead{T}}, r::Use_StepRangeLen_Instead) where {T<:AbstractFloat} = - Use_StepRangeLen_Instead{T}(r.start,r.step,r.len,r.divisor) - -promote_rule(::Type{Use_StepRangeLen_Instead{F}}, ::Type{OR}) where {F,OR<:OrdinalRange} = - Use_StepRangeLen_Instead{promote_type(F,eltype(OR))} -convert(::Type{Use_StepRangeLen_Instead{T}}, r::OrdinalRange) where {T<:AbstractFloat} = - Use_StepRangeLen_Instead{T}(first(r), step(r), length(r), one(T)) -convert(::Type{Use_StepRangeLen_Instead}, r::OrdinalRange{T}) where {T} = - Use_StepRangeLen_Instead{typeof(float(first(r)))}(first(r), step(r), length(r), one(T)) - -promote_rule(::Type{LinSpace{F}}, ::Type{OR}) where {F,OR<:Use_StepRangeLen_Instead} = - LinSpace{promote_type(F,eltype(OR))} -convert(::Type{LinSpace{T}}, r::Use_StepRangeLen_Instead) where {T<:AbstractFloat} = - linspace(convert(T, first(r)), convert(T, last(r)), convert(T, length(r))) -convert(::Type{LinSpace}, r::Use_StepRangeLen_Instead{T}) where {T<:AbstractFloat} = - convert(LinSpace{T}, r) - -reverse(r::Use_StepRangeLen_Instead) = Use_StepRangeLen_Instead(r.start + (r.len-1)*r.step, -r.step, r.len, r.divisor) - -function sum(r::Use_StepRangeLen_Instead) - l = length(r) - if iseven(l) - s = r.step * (l-1) * (l>>1) - else - s = (r.step * l) * ((l-1)>>1) - end - return (l * r.start + s)/r.divisor -end - -@deprecate_binding FloatRange Use_StepRangeLen_Instead - -## end of FloatRange - -@noinline zero_arg_matrix_constructor(prefix::String) = - depwarn("$prefix() is deprecated, use $prefix(0, 0) instead.", :zero_arg_matrix_constructor) -function (::Type{Matrix{T}}){T}() - zero_arg_matrix_constructor("Matrix{T}") - return Matrix{T}(0, 0) -end -function (::Type{Matrix})() - zero_arg_matrix_constructor("Matrix") - return Matrix(0, 0) -end - -for name in ("alnum", "alpha", "cntrl", "digit", "number", "graph", - "lower", "print", "punct", "space", "upper", "xdigit") - f = Symbol("is",name) - @eval @deprecate ($f)(s::AbstractString) all($f, s) -end - -# TODO: remove warning for using `_` in parse_input_line in base/client.jl - -# Special functions have been moved to a package -for f in (:airyai, :airyaiprime, :airybi, :airybiprime, :airyaix, :airyaiprimex, :airybix, :airybiprimex, - :besselh, :besselhx, :besseli, :besselix, :besselj, :besselj0, :besselj1, :besseljx, :besselk, - :besselkx, :bessely, :bessely0, :bessely1, :besselyx, - :dawson, :erf, :erfc, :erfcinv, :erfcx, :erfi, :erfinv, - :eta, :zeta, :digamma, :invdigamma, :polygamma, :trigamma, - :hankelh1, :hankelh1x, :hankelh2, :hankelh2x, - :airy, :airyx, :airyprime) - @eval begin - function $f(args...; kwargs...) - error(string($f, args, " has been moved to the package SpecialFunctions.jl.\n", - "Run Pkg.add(\"SpecialFunctions\") to install SpecialFunctions on Julia v0.6 and later,\n", - "and then run `using SpecialFunctions`.")) - end - export $f - end -end - -@deprecate_binding LinearIndexing IndexStyle false -@deprecate_binding LinearFast IndexLinear false -@deprecate_binding LinearSlow IndexCartesian false -@deprecate_binding linearindexing IndexStyle false - -# #20876 -@eval Base.Dates begin - function Base.Dates.parse(x::AbstractString, df::DateFormat) - Base.depwarn(string( - "`Dates.parse(x::AbstractString, df::DateFormat)` is deprecated, use ", - "`sort!(filter!(el -> isa(el, Dates.Period), Dates.parse_components(x, df), rev=true, lt=Dates.periodisless)` ", - " instead."), :parse) - sort!(filter!(el -> isa(el, Period), parse_components(x, df)), rev=true, lt=periodisless) - end -end - -# PR #16984 -@deprecate MersenneTwister() MersenneTwister(0) - -# #19635 -for fname in (:ones, :zeros) - @eval @deprecate ($fname)(T::Type, arr) ($fname)(T, size(arr)) - @eval ($fname)(T::Type, i::Integer) = ($fname)(T, (i,)) - @eval function ($fname)(::Type{T}, arr::Array{T}) where T - msg = string("`", $fname, "{T}(::Type{T}, arr::Array{T})` is deprecated, use ", - "`", $fname , "(T, size(arr))` instead. ", - ) - error(msg) - end -end - -# END 0.6 deprecations - -# BEGIN 1.0 deprecations -# END 1.0 deprecations diff --git a/julia-0.6.3/share/julia/base/dft.jl b/julia-0.6.3/share/julia/base/dft.jl deleted file mode 100644 index ab4e7e0..0000000 --- a/julia-0.6.3/share/julia/base/dft.jl +++ /dev/null @@ -1,591 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -module DFT - -# DFT plan where the inputs are an array of eltype T -abstract type Plan{T} end - -import Base: show, summary, size, ndims, length, eltype, - *, A_mul_B!, inv, \, A_ldiv_B! - -eltype(::Type{Plan{T}}) where {T} = T - -# size(p) should return the size of the input array for p -size(p::Plan, d) = size(p)[d] -ndims(p::Plan) = length(size(p)) -length(p::Plan) = prod(size(p))::Int - -############################################################################## -export fft, ifft, bfft, fft!, ifft!, bfft!, - plan_fft, plan_ifft, plan_bfft, plan_fft!, plan_ifft!, plan_bfft!, - rfft, irfft, brfft, plan_rfft, plan_irfft, plan_brfft - -const FFTWFloat = Union{Float32,Float64} -fftwfloat(x) = _fftwfloat(float(x)) -_fftwfloat(::Type{T}) where {T<:FFTWFloat} = T -_fftwfloat(::Type{Float16}) = Float32 -_fftwfloat(::Type{Complex{T}}) where {T} = Complex{_fftwfloat(T)} -_fftwfloat(::Type{T}) where {T} = error("type $T not supported") -_fftwfloat(x::T) where {T} = _fftwfloat(T)(x) - -complexfloat(x::StridedArray{Complex{<:FFTWFloat}}) = x -realfloat(x::StridedArray{<:FFTWFloat}) = x - -# return an Array, rather than similar(x), to avoid an extra copy for FFTW -# (which only works on StridedArray types). -complexfloat(x::AbstractArray{T}) where {T<:Complex} = copy1(typeof(fftwfloat(zero(T))), x) -complexfloat(x::AbstractArray{T}) where {T<:Real} = copy1(typeof(complex(fftwfloat(zero(T)))), x) - -realfloat(x::AbstractArray{T}) where {T<:Real} = copy1(typeof(fftwfloat(zero(T))), x) - -# copy to a 1-based array, using circular permutation -function copy1(::Type{T}, x) where T - y = Array{T}(map(length, indices(x))) - Base.circcopy!(y, x) -end - -to1(x::AbstractArray) = _to1(indices(x), x) -_to1(::Tuple{Base.OneTo,Vararg{Base.OneTo}}, x) = x -_to1(::Tuple, x) = copy1(eltype(x), x) - -# implementations only need to provide plan_X(x, region) -# for X in (:fft, :bfft, ...): -for f in (:fft, :bfft, :ifft, :fft!, :bfft!, :ifft!, :rfft) - pf = Symbol("plan_", f) - @eval begin - $f(x::AbstractArray) = (y = to1(x); $pf(y) * y) - $f(x::AbstractArray, region) = (y = to1(x); $pf(y, region) * y) - $pf(x::AbstractArray; kws...) = (y = to1(x); $pf(y, 1:ndims(y); kws...)) - end -end - -""" - plan_ifft(A [, dims]; flags=FFTW.ESTIMATE; timelimit=Inf) - -Same as [`plan_fft`](@ref), but produces a plan that performs inverse transforms -[`ifft`](@ref). -""" -plan_ifft - -""" - plan_ifft!(A [, dims]; flags=FFTW.ESTIMATE; timelimit=Inf) - -Same as [`plan_ifft`](@ref), but operates in-place on `A`. -""" -plan_ifft! - -""" - plan_bfft!(A [, dims]; flags=FFTW.ESTIMATE; timelimit=Inf) - -Same as [`plan_bfft`](@ref), but operates in-place on `A`. -""" -plan_bfft! - -""" - plan_bfft(A [, dims]; flags=FFTW.ESTIMATE; timelimit=Inf) - -Same as [`plan_fft`](@ref), but produces a plan that performs an unnormalized -backwards transform [`bfft`](@ref). -""" -plan_bfft - -""" - plan_fft(A [, dims]; flags=FFTW.ESTIMATE; timelimit=Inf) - -Pre-plan an optimized FFT along given dimensions (`dims`) of arrays matching the shape and -type of `A`. (The first two arguments have the same meaning as for [`fft`](@ref).) -Returns an object `P` which represents the linear operator computed by the FFT, and which -contains all of the information needed to compute `fft(A, dims)` quickly. - -To apply `P` to an array `A`, use `P * A`; in general, the syntax for applying plans is much -like that of matrices. (A plan can only be applied to arrays of the same size as the `A` -for which the plan was created.) You can also apply a plan with a preallocated output array `Â` -by calling `A_mul_B!(Â, plan, A)`. (For `A_mul_B!`, however, the input array `A` must -be a complex floating-point array like the output `Â`.) You can compute the inverse-transform plan by `inv(P)` -and apply the inverse plan with `P \\ Â` (the inverse plan is cached and reused for -subsequent calls to `inv` or `\\`), and apply the inverse plan to a pre-allocated output -array `A` with `A_ldiv_B!(A, P, Â)`. - -The `flags` argument is a bitwise-or of FFTW planner flags, defaulting to `FFTW.ESTIMATE`. -e.g. passing `FFTW.MEASURE` or `FFTW.PATIENT` will instead spend several seconds (or more) -benchmarking different possible FFT algorithms and picking the fastest one; see the FFTW -manual for more information on planner flags. The optional `timelimit` argument specifies a -rough upper bound on the allowed planning time, in seconds. Passing `FFTW.MEASURE` or -`FFTW.PATIENT` may cause the input array `A` to be overwritten with zeros during plan -creation. - -[`plan_fft!`](@ref) is the same as [`plan_fft`](@ref) but creates a -plan that operates in-place on its argument (which must be an array of complex -floating-point numbers). [`plan_ifft`](@ref) and so on are similar but produce -plans that perform the equivalent of the inverse transforms [`ifft`](@ref) and so on. -""" -plan_fft - -""" - plan_fft!(A [, dims]; flags=FFTW.ESTIMATE; timelimit=Inf) - -Same as [`plan_fft`](@ref), but operates in-place on `A`. -""" -plan_fft! - -""" - rfft(A [, dims]) - -Multidimensional FFT of a real array `A`, exploiting the fact that the transform has -conjugate symmetry in order to save roughly half the computational time and storage costs -compared with [`fft`](@ref). If `A` has size `(n_1, ..., n_d)`, the result has size -`(div(n_1,2)+1, ..., n_d)`. - -The optional `dims` argument specifies an iterable subset of one or more dimensions of `A` -to transform, similar to [`fft`](@ref). Instead of (roughly) halving the first -dimension of `A` in the result, the `dims[1]` dimension is (roughly) halved in the same way. -""" -rfft - -""" - ifft!(A [, dims]) - -Same as [`ifft`](@ref), but operates in-place on `A`. -""" -ifft! - -""" - ifft(A [, dims]) - -Multidimensional inverse FFT. - -A one-dimensional inverse FFT computes - -```math -\\operatorname{IDFT}(A)[k] = \\frac{1}{\\operatorname{length}(A)} -\\sum_{n=1}^{\\operatorname{length}(A)} \\exp\\left(+i\\frac{2\\pi (n-1)(k-1)} -{\\operatorname{length}(A)} \\right) A[n]. -``` - -A multidimensional inverse FFT simply performs this operation along each transformed dimension of `A`. -""" -ifft - -""" - fft!(A [, dims]) - -Same as [`fft`](@ref), but operates in-place on `A`, which must be an array of -complex floating-point numbers. -""" -fft! - -""" - bfft(A [, dims]) - -Similar to [`ifft`](@ref), but computes an unnormalized inverse (backward) -transform, which must be divided by the product of the sizes of the transformed dimensions -in order to obtain the inverse. (This is slightly more efficient than [`ifft`](@ref) -because it omits a scaling step, which in some applications can be combined with other -computational steps elsewhere.) - -```math -\\operatorname{BDFT}(A)[k] = \\operatorname{length}(A) \\operatorname{IDFT}(A)[k] -``` -""" -bfft - -""" - bfft!(A [, dims]) - -Same as [`bfft`](@ref), but operates in-place on `A`. -""" -bfft! - -# promote to a complex floating-point type (out-of-place only), -# so implementations only need Complex{Float} methods -for f in (:fft, :bfft, :ifft) - pf = Symbol("plan_", f) - @eval begin - $f(x::AbstractArray{<:Real}, region=1:ndims(x)) = $f(complexfloat(x), region) - $pf(x::AbstractArray{<:Real}, region; kws...) = $pf(complexfloat(x), region; kws...) - $f(x::AbstractArray{<:Complex{<:Union{Integer,Rational}}}, region=1:ndims(x)) = $f(complexfloat(x), region) - $pf(x::AbstractArray{<:Complex{<:Union{Integer,Rational}}}, region; kws...) = $pf(complexfloat(x), region; kws...) - end -end -rfft(x::AbstractArray{<:Union{Integer,Rational}}, region=1:ndims(x)) = rfft(realfloat(x), region) -plan_rfft(x::AbstractArray, region; kws...) = plan_rfft(realfloat(x), region; kws...) - -# only require implementation to provide *(::Plan{T}, ::Array{T}) -*(p::Plan{T}, x::AbstractArray) where {T} = p * copy1(T, x) - -# Implementations should also implement A_mul_B!(Y, plan, X) so as to support -# pre-allocated output arrays. We don't define * in terms of A_mul_B! -# generically here, however, because of subtleties for in-place and rfft plans. - -############################################################################## -# To support inv, \, and A_ldiv_B!(y, p, x), we require Plan subtypes -# to have a pinv::Plan field, which caches the inverse plan, and which -# should be initially undefined. They should also implement -# plan_inv(p) to construct the inverse of a plan p. - -# hack from @simonster (in #6193) to compute the return type of plan_inv -# without actually calling it or even constructing the empty arrays. -_pinv_type(p::Plan) = typeof([plan_inv(x) for x in typeof(p)[]]) -pinv_type(p::Plan) = eltype(_pinv_type(p)) - -inv(p::Plan) = - isdefined(p, :pinv) ? p.pinv::pinv_type(p) : (p.pinv = plan_inv(p)) -\(p::Plan, x::AbstractArray) = inv(p) * x -A_ldiv_B!(y::AbstractArray, p::Plan, x::AbstractArray) = A_mul_B!(y, inv(p), x) - -############################################################################## -# implementations only need to provide the unnormalized backwards FFT, -# similar to FFTW, and we do the scaling generically to get the ifft: - -mutable struct ScaledPlan{T,P,N} <: Plan{T} - p::P - scale::N # not T, to avoid unnecessary promotion to Complex - pinv::Plan - ScaledPlan{T,P,N}(p, scale) where {T,P,N} = new(p, scale) -end -ScaledPlan{T}(p::P, scale::N) where {T,P,N} = ScaledPlan{T,P,N}(p, scale) -ScaledPlan(p::Plan{T}, scale::Number) where {T} = ScaledPlan{T}(p, scale) -ScaledPlan(p::ScaledPlan, α::Number) = ScaledPlan(p.p, p.scale * α) - -size(p::ScaledPlan) = size(p.p) - -show(io::IO, p::ScaledPlan) = print(io, p.scale, " * ", p.p) -summary(p::ScaledPlan) = string(p.scale, " * ", summary(p.p)) - -*(p::ScaledPlan, x::AbstractArray) = scale!(p.p * x, p.scale) - -*(α::Number, p::Plan) = ScaledPlan(p, α) -*(p::Plan, α::Number) = ScaledPlan(p, α) -*(I::UniformScaling, p::ScaledPlan) = ScaledPlan(p, I.λ) -*(p::ScaledPlan, I::UniformScaling) = ScaledPlan(p, I.λ) -*(I::UniformScaling, p::Plan) = ScaledPlan(p, I.λ) -*(p::Plan, I::UniformScaling) = ScaledPlan(p, I.λ) - -# Normalization for ifft, given unscaled bfft, is 1/prod(dimensions) -normalization(T, sz, region) = one(T) / Int(prod([sz...][[region...]])) -normalization(X, region) = normalization(real(eltype(X)), size(X), region) - -plan_ifft(x::AbstractArray, region; kws...) = - ScaledPlan(plan_bfft(x, region; kws...), normalization(x, region)) -plan_ifft!(x::AbstractArray, region; kws...) = - ScaledPlan(plan_bfft!(x, region; kws...), normalization(x, region)) - -plan_inv(p::ScaledPlan) = ScaledPlan(plan_inv(p.p), inv(p.scale)) - -A_mul_B!(y::AbstractArray, p::ScaledPlan, x::AbstractArray) = - scale!(p.scale, A_mul_B!(y, p.p, x)) - -############################################################################## -# Real-input DFTs are annoying because the output has a different size -# than the input if we want to gain the full factor-of-two(ish) savings -# For backward real-data transforms, we must specify the original length -# of the first dimension, since there is no reliable way to detect this -# from the data (we can't detect whether the dimension was originally even -# or odd). - -for f in (:brfft, :irfft) - pf = Symbol("plan_", f) - @eval begin - $f(x::AbstractArray, d::Integer) = $pf(x, d) * x - $f(x::AbstractArray, d::Integer, region) = $pf(x, d, region) * x - $pf(x::AbstractArray, d::Integer;kws...) = $pf(x, d, 1:ndims(x);kws...) - end -end - -for f in (:brfft, :irfft) - @eval begin - $f(x::AbstractArray{<:Real}, d::Integer, region=1:ndims(x)) = $f(complexfloat(x), d, region) - $f(x::AbstractArray{<:Complex{<:Union{Integer,Rational}}}, d::Integer, region=1:ndims(x)) = $f(complexfloat(x), d, region) - end -end - -""" - irfft(A, d [, dims]) - -Inverse of [`rfft`](@ref): for a complex array `A`, gives the corresponding real -array whose FFT yields `A` in the first half. As for [`rfft`](@ref), `dims` is an -optional subset of dimensions to transform, defaulting to `1:ndims(A)`. - -`d` is the length of the transformed real array along the `dims[1]` dimension, which must -satisfy `div(d,2)+1 == size(A,dims[1])`. (This parameter cannot be inferred from `size(A)` -since both `2*size(A,dims[1])-2` as well as `2*size(A,dims[1])-1` are valid sizes for the -transformed real array.) -""" -irfft - -""" - brfft(A, d [, dims]) - -Similar to [`irfft`](@ref) but computes an unnormalized inverse transform (similar -to [`bfft`](@ref)), which must be divided by the product of the sizes of the -transformed dimensions (of the real output array) in order to obtain the inverse transform. -""" -brfft - -function rfft_output_size(x::AbstractArray, region) - d1 = first(region) - osize = [size(x)...] - osize[d1] = osize[d1]>>1 + 1 - return osize -end - -function brfft_output_size(x::AbstractArray, d::Integer, region) - d1 = first(region) - osize = [size(x)...] - @assert osize[d1] == d>>1 + 1 - osize[d1] = d - return osize -end - -plan_irfft(x::AbstractArray{Complex{T}}, d::Integer, region; kws...) where {T} = - ScaledPlan(plan_brfft(x, d, region; kws...), - normalization(T, brfft_output_size(x, d, region), region)) - -""" - plan_irfft(A, d [, dims]; flags=FFTW.ESTIMATE; timelimit=Inf) - -Pre-plan an optimized inverse real-input FFT, similar to [`plan_rfft`](@ref) -except for [`irfft`](@ref) and [`brfft`](@ref), respectively. The first -three arguments have the same meaning as for [`irfft`](@ref). -""" -plan_irfft - -############################################################################## - -export fftshift, ifftshift - -fftshift(x) = circshift(x, div.([size(x)...],2)) - -""" - fftshift(x) - -Swap the first and second halves of each dimension of `x`. -""" -fftshift(x) - -function fftshift(x,dim) - s = zeros(Int,ndims(x)) - for i in dim - s[i] = div(size(x,i),2) - end - circshift(x, s) -end - -""" - fftshift(x,dim) - -Swap the first and second halves of the given dimension or iterable of dimensions of array `x`. -""" -fftshift(x,dim) - -ifftshift(x) = circshift(x, div.([size(x)...],-2)) - -""" - ifftshift(x, [dim]) - -Undoes the effect of `fftshift`. -""" -ifftshift - -function ifftshift(x,dim) - s = zeros(Int,ndims(x)) - for i in dim - s[i] = -div(size(x,i),2) - end - circshift(x, s) -end - -############################################################################## - -# FFTW module (may move to an external package at some point): -""" - fft(A [, dims]) - -Performs a multidimensional FFT of the array `A`. The optional `dims` argument specifies an -iterable subset of dimensions (e.g. an integer, range, tuple, or array) to transform along. -Most efficient if the size of `A` along the transformed dimensions is a product of small -primes; see `nextprod()`. See also `plan_fft()` for even greater efficiency. - -A one-dimensional FFT computes the one-dimensional discrete Fourier transform (DFT) as -defined by - -```math -\\operatorname{DFT}(A)[k] = - \\sum_{n=1}^{\\operatorname{length}(A)} - \\exp\\left(-i\\frac{2\\pi - (n-1)(k-1)}{\\operatorname{length}(A)} \\right) A[n]. -``` - -A multidimensional FFT simply performs this operation along each transformed dimension of `A`. - -!!! note - * Julia starts FFTW up with 1 thread by default. Higher performance is usually possible by - increasing number of threads. Use `FFTW.set_num_threads(Sys.CPU_CORES)` to use as many - threads as cores on your system. - - * This performs a multidimensional FFT by default. FFT libraries in other languages such as - Python and Octave perform a one-dimensional FFT along the first non-singleton dimension - of the array. This is worth noting while performing comparisons. For more details, - refer to the [Noteworthy Differences from other Languages](@ref) - section of the manual. -""" -fft - -""" - plan_rfft(A [, dims]; flags=FFTW.ESTIMATE; timelimit=Inf) - -Pre-plan an optimized real-input FFT, similar to [`plan_fft`](@ref) except for -[`rfft`](@ref) instead of [`fft`](@ref). The first two arguments, and the -size of the transformed result, are the same as for [`rfft`](@ref). -""" -plan_rfft - -""" - plan_brfft(A, d [, dims]; flags=FFTW.ESTIMATE; timelimit=Inf) - -Pre-plan an optimized real-input unnormalized transform, similar to -[`plan_rfft`](@ref) except for [`brfft`](@ref) instead of -[`rfft`](@ref). The first two arguments and the size of the transformed result, are -the same as for [`brfft`](@ref). -""" -plan_brfft - -module FFTW - import ..DFT: fft, bfft, ifft, rfft, brfft, irfft, plan_fft, plan_bfft, plan_ifft, - plan_rfft, plan_brfft, plan_irfft, fft!, bfft!, ifft!, plan_fft!, plan_bfft!, plan_ifft!, - Plan, rfft_output_size, brfft_output_size, plan_inv, normalization, ScaledPlan - - export r2r, r2r!, plan_r2r, plan_r2r! - - """ - plan_dct!(A [, dims [, flags [, timelimit]]]) - - Same as [`plan_dct`](@ref), but operates in-place on `A`. - """ - function plan_dct! end - - """ - plan_idct(A [, dims [, flags [, timelimit]]]) - - Pre-plan an optimized inverse discrete cosine transform (DCT), similar to - [`plan_fft`](@ref) except producing a function that computes - [`idct`](@ref). The first two arguments have the same meaning as for - [`idct`](@ref). - """ - function plan_idct end - - """ - plan_dct(A [, dims [, flags [, timelimit]]]) - - Pre-plan an optimized discrete cosine transform (DCT), similar to - [`plan_fft`](@ref) except producing a function that computes - [`dct`](@ref). The first two arguments have the same meaning as for - [`dct`](@ref). - """ - function plan_dct end - - """ - plan_idct!(A [, dims [, flags [, timelimit]]]) - - Same as [`plan_idct`](@ref), but operates in-place on `A`. - """ - function plan_idct! end - - """ - dct(A [, dims]) - - Performs a multidimensional type-II discrete cosine transform (DCT) of the array `A`, using - the unitary normalization of the DCT. The optional `dims` argument specifies an iterable - subset of dimensions (e.g. an integer, range, tuple, or array) to transform along. Most - efficient if the size of `A` along the transformed dimensions is a product of small primes; - see [`nextprod`](@ref). See also [`plan_dct`](@ref) for even greater - efficiency. - """ - function dct end - - """ - idct(A [, dims]) - - Computes the multidimensional inverse discrete cosine transform (DCT) of the array `A` - (technically, a type-III DCT with the unitary normalization). The optional `dims` argument - specifies an iterable subset of dimensions (e.g. an integer, range, tuple, or array) to - transform along. Most efficient if the size of `A` along the transformed dimensions is a - product of small primes; see [`nextprod`](@ref). See also - [`plan_idct`](@ref) for even greater efficiency. - """ - function idct end - - """ - dct!(A [, dims]) - - Same as [`dct!`](@ref), except that it operates in-place on `A`, which must be an - array of real or complex floating-point values. - """ - function dct! end - - """ - idct!(A [, dims]) - - Same as [`idct!`](@ref), but operates in-place on `A`. - """ - function idct! end - - """ - r2r(A, kind [, dims]) - - Performs a multidimensional real-input/real-output (r2r) transform - of type `kind` of the array `A`, as defined in the FFTW manual. - `kind` specifies either a discrete cosine transform of various types - (`FFTW.REDFT00`, `FFTW.REDFT01`, `FFTW.REDFT10`, or - `FFTW.REDFT11`), a discrete sine transform of various types - (`FFTW.RODFT00`, `FFTW.RODFT01`, `FFTW.RODFT10`, or - `FFTW.RODFT11`), a real-input DFT with halfcomplex-format output - (`FFTW.R2HC` and its inverse `FFTW.HC2R`), or a discrete - Hartley transform (`FFTW.DHT`). The `kind` argument may be - an array or tuple in order to specify different transform types - along the different dimensions of `A`; `kind[end]` is used - for any unspecified dimensions. See the FFTW manual for precise - definitions of these transform types, at http://www.fftw.org/doc. - - The optional `dims` argument specifies an iterable subset of - dimensions (e.g. an integer, range, tuple, or array) to transform - along. `kind[i]` is then the transform type for `dims[i]`, - with `kind[end]` being used for `i > length(kind)`. - - See also [`plan_r2r`](@ref) to pre-plan optimized r2r transforms. - """ - function r2r end - - """ - r2r!(A, kind [, dims]) - - Same as [`r2r`](@ref), but operates in-place on `A`, which must be - an array of real or complex floating-point numbers. - """ - function r2r! end - - """ - plan_r2r!(A, kind [, dims [, flags [, timelimit]]]) - - Similar to [`plan_fft`](@ref), but corresponds to [`r2r!`](@ref). - """ - function plan_r2r! end - - """ - plan_r2r(A, kind [, dims [, flags [, timelimit]]]) - - Pre-plan an optimized r2r transform, similar to [`plan_fft`](@ref) - except that the transforms (and the first three arguments) - correspond to [`r2r`](@ref) and [`r2r!`](@ref), respectively. - """ - function plan_r2r end - - (Base.USE_GPL_LIBS || Base.fftw_vendor() == :mkl) && include(joinpath("fft", "FFTW.jl")) -end - -importall .FFTW -export FFTW, dct, idct, dct!, idct!, plan_dct, plan_idct, plan_dct!, plan_idct! - -############################################################################## - -end diff --git a/julia-0.6.3/share/julia/base/dict.jl b/julia-0.6.3/share/julia/base/dict.jl deleted file mode 100644 index cd41a72..0000000 --- a/julia-0.6.3/share/julia/base/dict.jl +++ /dev/null @@ -1,675 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -function _truncate_at_width_or_chars(str, width, chars="", truncmark="…") - truncwidth = strwidth(truncmark) - (width <= 0 || width < truncwidth) && return "" - - wid = truncidx = lastidx = 0 - idx = start(str) - while !done(str, idx) - lastidx = idx - c, idx = next(str, idx) - wid += charwidth(c) - wid >= width - truncwidth && truncidx == 0 && (truncidx = lastidx) - (wid >= width || c in chars) && break - end - - lastidx != 0 && str[lastidx] in chars && (lastidx = prevind(str, lastidx)) - truncidx == 0 && (truncidx = lastidx) - if lastidx < endof(str) - return String(SubString(str, 1, truncidx) * truncmark) - else - return String(str) - end -end - -function show(io::IO, t::Associative{K,V}) where V where K - recur_io = IOContext(io, :SHOWN_SET => t) - limit::Bool = get(io, :limit, false) - if !haskey(io, :compact) - recur_io = IOContext(recur_io, :compact => true) - end - - # show in a Julia-syntax-like form: Dict(k=>v, ...) - if isempty(t) - print(io, typeof(t), "()") - else - if isleaftype(K) && isleaftype(V) - print(io, typeof(t).name) - else - print(io, typeof(t)) - end - print(io, '(') - if !show_circular(io, t) - first = true - n = 0 - for pair in t - first || print(io, ',') - first = false - show(recur_io, pair) - n+=1 - limit && n >= 10 && (print(io, "…"); break) - end - end - print(io, ')') - end -end - -abstract type AbstractSerializer end - -# Dict - -# These can be changed, to trade off better performance for space -const global maxallowedprobe = 16 -const global maxprobeshift = 6 - -_tablesz(x::Integer) = x < 16 ? 16 : one(x)<<((sizeof(x)<<3)-leading_zeros(x-1)) - -""" - Dict([itr]) - -`Dict{K,V}()` constructs a hash table with keys of type `K` and values of type `V`. - -Given a single iterable argument, constructs a [`Dict`](@ref) whose key-value pairs -are taken from 2-tuples `(key,value)` generated by the argument. - -```jldoctest -julia> Dict([("A", 1), ("B", 2)]) -Dict{String,Int64} with 2 entries: - "B" => 2 - "A" => 1 -``` - -Alternatively, a sequence of pair arguments may be passed. - -```jldoctest -julia> Dict("A"=>1, "B"=>2) -Dict{String,Int64} with 2 entries: - "B" => 2 - "A" => 1 -``` -""" -mutable struct Dict{K,V} <: Associative{K,V} - slots::Array{UInt8,1} - keys::Array{K,1} - vals::Array{V,1} - ndel::Int - count::Int - age::UInt - idxfloor::Int # an index <= the indexes of all used slots - maxprobe::Int - - function Dict{K,V}() where V where K - n = 16 - new(zeros(UInt8,n), Array{K,1}(n), Array{V,1}(n), 0, 0, 0, 1, 0) - end - function Dict{K,V}(d::Dict{K,V}) where V where K - if d.ndel > 0 - rehash!(d) - end - @assert d.ndel == 0 - new(copy(d.slots), copy(d.keys), copy(d.vals), 0, d.count, d.age, d.idxfloor, - d.maxprobe) - end -end -function Dict{K,V}(kv) where V where K - h = Dict{K,V}() - for (k,v) in kv - h[k] = v - end - return h -end -Dict{K,V}(p::Pair) where {K,V} = setindex!(Dict{K,V}(), p.second, p.first) -function Dict{K,V}(ps::Pair...) where V where K - h = Dict{K,V}() - sizehint!(h, length(ps)) - for p in ps - h[p.first] = p.second - end - return h -end -# Note the constructors of WeakKeyDict mirror these here, keep in sync. -Dict() = Dict{Any,Any}() -Dict(kv::Tuple{}) = Dict() -copy(d::Dict) = Dict(d) - -const AnyDict = Dict{Any,Any} - -Dict(ps::Pair{K,V}...) where {K,V} = Dict{K,V}(ps) -Dict(ps::Pair{K}...,) where K = Dict{K,Any}(ps) -Dict(ps::(Pair{K,V} where K)...,) where V = Dict{Any,V}(ps) -Dict(ps::Pair...) = Dict{Any,Any}(ps) - -function Dict(kv) - try - associative_with_eltype((K, V) -> Dict{K, V}, kv, eltype(kv)) - catch e - if !applicable(start, kv) || !all(x->isa(x,Union{Tuple,Pair}),kv) - throw(ArgumentError("Dict(kv): kv needs to be an iterator of tuples or pairs")) - else - rethrow(e) - end - end -end - -TP{K,V} = Union{Type{Tuple{K,V}},Type{Pair{K,V}}} - -associative_with_eltype(DT_apply, kv, ::TP{K,V}) where {K,V} = DT_apply(K, V)(kv) -associative_with_eltype(DT_apply, kv::Generator, ::TP{K,V}) where {K,V} = DT_apply(K, V)(kv) -associative_with_eltype(DT_apply, ::Type{Pair{K,V}}) where {K,V} = DT_apply(K, V)() -associative_with_eltype(DT_apply, ::Type) = DT_apply(Any, Any)() -associative_with_eltype(DT_apply::F, kv, t) where {F} = grow_to!(associative_with_eltype(DT_apply, _default_eltype(typeof(kv))), kv) -function associative_with_eltype(DT_apply::F, kv::Generator, t) where F - T = _default_eltype(typeof(kv)) - if T <: Union{Pair, Tuple{Any, Any}} && isleaftype(T) - return associative_with_eltype(DT_apply, kv, T) - end - return grow_to!(associative_with_eltype(DT_apply, T), kv) -end - -# this is a special case due to (1) allowing both Pairs and Tuples as elements, -# and (2) Pair being invariant. a bit annoying. -function grow_to!(dest::Associative, itr) - out = grow_to!(similar(dest, Pair{Union{},Union{}}), itr, start(itr)) - return isempty(out) ? dest : out -end - -function grow_to!(dest::Associative{K,V}, itr, st) where V where K - while !done(itr, st) - (k,v), st = next(itr, st) - if isa(k,K) && isa(v,V) - dest[k] = v - else - new = similar(dest, Pair{typejoin(K,typeof(k)), typejoin(V,typeof(v))}) - copy!(new, dest) - new[k] = v - return grow_to!(new, itr, st) - end - end - return dest -end - -similar(d::Dict{K,V}) where {K,V} = Dict{K,V}() -similar(d::Dict, ::Type{Pair{K,V}}) where {K,V} = Dict{K,V}() - -# conversion between Dict types -function convert(::Type{Dict{K,V}},d::Associative) where V where K - h = Dict{K,V}() - for (k,v) in d - ck = convert(K,k) - if !haskey(h,ck) - h[ck] = convert(V,v) - else - error("key collision during dictionary conversion") - end - end - return h -end -convert(::Type{Dict{K,V}},d::Dict{K,V}) where {K,V} = d - -hashindex(key, sz) = (((hash(key)%Int) & (sz-1)) + 1)::Int - -isslotempty(h::Dict, i::Int) = h.slots[i] == 0x0 -isslotfilled(h::Dict, i::Int) = h.slots[i] == 0x1 -isslotmissing(h::Dict, i::Int) = h.slots[i] == 0x2 - -function rehash!(h::Dict{K,V}, newsz = length(h.keys)) where V where K - olds = h.slots - oldk = h.keys - oldv = h.vals - sz = length(olds) - newsz = _tablesz(newsz) - h.age += 1 - h.idxfloor = 1 - if h.count == 0 - resize!(h.slots, newsz) - fill!(h.slots, 0) - resize!(h.keys, newsz) - resize!(h.vals, newsz) - h.ndel = 0 - return h - end - - slots = zeros(UInt8,newsz) - keys = Array{K,1}(newsz) - vals = Array{V,1}(newsz) - age0 = h.age - count = 0 - maxprobe = h.maxprobe - - for i = 1:sz - if olds[i] == 0x1 - k = oldk[i] - v = oldv[i] - index0 = index = hashindex(k, newsz) - while slots[index] != 0 - index = (index & (newsz-1)) + 1 - end - probe = (index - index0) & (newsz-1) - probe > maxprobe && (maxprobe = probe) - slots[index] = 0x1 - keys[index] = k - vals[index] = v - count += 1 - - if h.age != age0 - # if `h` is changed by a finalizer, retry - return rehash!(h, newsz) - end - end - end - - h.slots = slots - h.keys = keys - h.vals = vals - h.count = count - h.ndel = 0 - h.maxprobe = maxprobe - @assert h.age == age0 - - return h -end - -function sizehint!(d::Dict, newsz) - oldsz = length(d.slots) - if newsz <= oldsz - # todo: shrink - # be careful: rehash!() assumes everything fits. it was only designed - # for growing. - return d - end - # grow at least 25% - newsz = max(newsz, (oldsz*5)>>2) - rehash!(d, newsz) -end - -""" - empty!(collection) -> collection - -Remove all elements from a `collection`. - -```jldoctest -julia> A = Dict("a" => 1, "b" => 2) -Dict{String,Int64} with 2 entries: - "b" => 2 - "a" => 1 - -julia> empty!(A); - -julia> A -Dict{String,Int64} with 0 entries -``` -""" -function empty!(h::Dict{K,V}) where V where K - fill!(h.slots, 0x0) - sz = length(h.slots) - empty!(h.keys) - empty!(h.vals) - resize!(h.keys, sz) - resize!(h.vals, sz) - h.ndel = 0 - h.count = 0 - h.age += 1 - h.idxfloor = 1 - return h -end - -# get the index where a key is stored, or -1 if not present -function ht_keyindex(h::Dict{K,V}, key) where V where K - sz = length(h.keys) - iter = 0 - maxprobe = h.maxprobe - index = hashindex(key, sz) - keys = h.keys - - while true - if isslotempty(h,index) - break - end - if !isslotmissing(h,index) && (key === keys[index] || isequal(key,keys[index])) - return index - end - - index = (index & (sz-1)) + 1 - iter += 1 - iter > maxprobe && break - end - return -1 -end - -# get the index where a key is stored, or -pos if not present -# and the key would be inserted at pos -# This version is for use by setindex! and get! -function ht_keyindex2(h::Dict{K,V}, key) where V where K - age0 = h.age - sz = length(h.keys) - iter = 0 - maxprobe = h.maxprobe - index = hashindex(key, sz) - avail = 0 - keys = h.keys - - while true - if isslotempty(h,index) - if avail < 0 - return avail - end - return -index - end - - if isslotmissing(h,index) - if avail == 0 - # found an available slot, but need to keep scanning - # in case "key" already exists in a later collided slot. - avail = -index - end - elseif key === keys[index] || isequal(key, keys[index]) - return index - end - - index = (index & (sz-1)) + 1 - iter += 1 - iter > maxprobe && break - end - - avail < 0 && return avail - - maxallowed = max(maxallowedprobe, sz>>maxprobeshift) - # Check if key is not present, may need to keep searching to find slot - while iter < maxallowed - if !isslotfilled(h,index) - h.maxprobe = iter - return -index - end - index = (index & (sz-1)) + 1 - iter += 1 - end - - rehash!(h, h.count > 64000 ? sz*2 : sz*4) - - return ht_keyindex2(h, key) -end - -function _setindex!(h::Dict, v, key, index) - h.slots[index] = 0x1 - h.keys[index] = key - h.vals[index] = v - h.count += 1 - h.age += 1 - if index < h.idxfloor - h.idxfloor = index - end - - sz = length(h.keys) - # Rehash now if necessary - if h.ndel >= ((3*sz)>>2) || h.count*3 > sz*2 - # > 3/4 deleted or > 2/3 full - rehash!(h, h.count > 64000 ? h.count*2 : h.count*4) - end -end - -function setindex!(h::Dict{K,V}, v0, key0) where V where K - key = convert(K, key0) - if !isequal(key, key0) - throw(ArgumentError("$key0 is not a valid key for type $K")) - end - setindex!(h, v0, key) -end - -function setindex!(h::Dict{K,V}, v0, key::K) where V where K - v = convert(V, v0) - index = ht_keyindex2(h, key) - - if index > 0 - h.age += 1 - h.keys[index] = key - h.vals[index] = v - else - _setindex!(h, v, key, -index) - end - - return h -end - -get!(h::Dict{K,V}, key0, default) where {K,V} = get!(()->default, h, key0) -function get!(default::Callable, h::Dict{K,V}, key0) where V where K - key = convert(K, key0) - if !isequal(key, key0) - throw(ArgumentError("$key0 is not a valid key for type $K")) - end - return get!(default, h, key) -end - -function get!(default::Callable, h::Dict{K,V}, key::K) where V where K - index = ht_keyindex2(h, key) - - index > 0 && return h.vals[index] - - age0 = h.age - v = convert(V, default()) - if h.age != age0 - index = ht_keyindex2(h, key) - end - if index > 0 - h.age += 1 - h.keys[index] = key - h.vals[index] = v - else - _setindex!(h, v, key, -index) - end - return v -end - -# NOTE: this macro is trivial, and should -# therefore not be exported as-is: it's for internal use only. -macro get!(h, key0, default) - return quote - get!(()->$(esc(default)), $(esc(h)), $(esc(key0))) - end -end - - -function getindex(h::Dict{K,V}, key) where V where K - index = ht_keyindex(h, key) - return (index < 0) ? throw(KeyError(key)) : h.vals[index]::V -end - -function get(h::Dict{K,V}, key, default) where V where K - index = ht_keyindex(h, key) - return (index < 0) ? default : h.vals[index]::V -end - -function get(default::Callable, h::Dict{K,V}, key) where V where K - index = ht_keyindex(h, key) - return (index < 0) ? default() : h.vals[index]::V -end - -""" - haskey(collection, key) -> Bool - -Determine whether a collection has a mapping for a given key. - -```jldoctest -julia> a = Dict('a'=>2, 'b'=>3) -Dict{Char,Int64} with 2 entries: - 'b' => 3 - 'a' => 2 - -julia> haskey(a,'a') -true - -julia> haskey(a,'c') -false -``` -""" -haskey(h::Dict, key) = (ht_keyindex(h, key) >= 0) -in(key, v::KeyIterator{<:Dict}) = (ht_keyindex(v.dict, key) >= 0) - -""" - getkey(collection, key, default) - -Return the key matching argument `key` if one exists in `collection`, otherwise return `default`. - -```jldoctest -julia> a = Dict('a'=>2, 'b'=>3) -Dict{Char,Int64} with 2 entries: - 'b' => 3 - 'a' => 2 - -julia> getkey(a,'a',1) -'a': ASCII/Unicode U+0061 (category Ll: Letter, lowercase) - -julia> getkey(a,'d','a') -'a': ASCII/Unicode U+0061 (category Ll: Letter, lowercase) -``` -""" -function getkey(h::Dict{K,V}, key, default) where V where K - index = ht_keyindex(h, key) - return (index<0) ? default : h.keys[index]::K -end - -function _pop!(h::Dict, index) - val = h.vals[index] - _delete!(h, index) - return val -end - -function pop!(h::Dict, key) - index = ht_keyindex(h, key) - return index > 0 ? _pop!(h, index) : throw(KeyError(key)) -end - -function pop!(h::Dict, key, default) - index = ht_keyindex(h, key) - return index > 0 ? _pop!(h, index) : default -end - -function _delete!(h::Dict, index) - h.slots[index] = 0x2 - ccall(:jl_arrayunset, Void, (Any, UInt), h.keys, index-1) - ccall(:jl_arrayunset, Void, (Any, UInt), h.vals, index-1) - h.ndel += 1 - h.count -= 1 - h.age += 1 - return h -end - -function delete!(h::Dict, key) - index = ht_keyindex(h, key) - if index > 0 - _delete!(h, index) - end - return h -end - -function skip_deleted(h::Dict, i) - L = length(h.slots) - while i<=L && !isslotfilled(h,i) - i += 1 - end - return i -end - -function start(t::Dict) - i = skip_deleted(t, t.idxfloor) - t.idxfloor = i - return i -end -done(t::Dict, i) = i > length(t.vals) -next(t::Dict{K,V}, i) where {K,V} = (Pair{K,V}(t.keys[i],t.vals[i]), skip_deleted(t,i+1)) - -isempty(t::Dict) = (t.count == 0) -length(t::Dict) = t.count - -next(v::KeyIterator{<:Dict}, i) = (v.dict.keys[i], skip_deleted(v.dict,i+1)) -next(v::ValueIterator{<:Dict}, i) = (v.dict.vals[i], skip_deleted(v.dict,i+1)) - -# For these Associative types, it is safe to implement filter! -# by deleting keys during iteration. -function filter!(f, d::Union{ObjectIdDict,Dict}) - for (k,v) in d - if !f(k,v) - delete!(d,k) - end - end - return d -end - -struct ImmutableDict{K,V} <: Associative{K,V} - parent::ImmutableDict{K,V} - key::K - value::V - ImmutableDict{K,V}() where {K,V} = new() # represents an empty dictionary - ImmutableDict{K,V}(key, value) where {K,V} = (empty = new(); new(empty, key, value)) - ImmutableDict{K,V}(parent::ImmutableDict, key, value) where {K,V} = new(parent, key, value) -end - -""" - ImmutableDict - -ImmutableDict is a Dictionary implemented as an immutable linked list, -which is optimal for small dictionaries that are constructed over many individual insertions -Note that it is not possible to remove a value, although it can be partially overridden and hidden -by inserting a new value with the same key - - ImmutableDict(KV::Pair) - -Create a new entry in the Immutable Dictionary for the key => value pair - - - use `(key => value) in dict` to see if this particular combination is in the properties set - - use `get(dict, key, default)` to retrieve the most recent value for a particular key - -""" -ImmutableDict -ImmutableDict(KV::Pair{K,V}) where {K,V} = ImmutableDict{K,V}(KV[1], KV[2]) -ImmutableDict(t::ImmutableDict{K,V}, KV::Pair) where {K,V} = ImmutableDict{K,V}(t, KV[1], KV[2]) - -function in(key_value::Pair, dict::ImmutableDict, valcmp=(==)) - key, value = key_value - while isdefined(dict, :parent) - if dict.key == key - valcmp(value, dict.value) && return true - end - dict = dict.parent - end - return false -end - -function haskey(dict::ImmutableDict, key) - while isdefined(dict, :parent) - dict.key == key && return true - dict = dict.parent - end - return false -end - -function getindex(dict::ImmutableDict, key) - while isdefined(dict, :parent) - dict.key == key && return dict.value - dict = dict.parent - end - throw(KeyError(key)) -end -function get(dict::ImmutableDict, key, default) - while isdefined(dict, :parent) - dict.key == key && return dict.value - dict = dict.parent - end - return default -end - -# this actually defines reverse iteration (e.g. it should not be used for merge/copy/filter type operations) -start(t::ImmutableDict) = t -next(::ImmutableDict{K,V}, t) where {K,V} = (Pair{K,V}(t.key, t.value), t.parent) -done(::ImmutableDict, t) = !isdefined(t, :parent) -length(t::ImmutableDict) = count(x->true, t) -isempty(t::ImmutableDict) = done(t, start(t)) -function similar(t::ImmutableDict) - while isdefined(t, :parent) - t = t.parent - end - return t -end - -_similar_for{P<:Pair}(c::Dict, ::Type{P}, itr, isz) = similar(c, P) -_similar_for(c::Associative, T, itr, isz) = throw(ArgumentError("for Associatives, similar requires an element type of Pair;\n if calling map, consider a comprehension instead")) diff --git a/julia-0.6.3/share/julia/base/distributed/Distributed.jl b/julia-0.6.3/share/julia/base/distributed/Distributed.jl deleted file mode 100644 index 06e2bd9..0000000 --- a/julia-0.6.3/share/julia/base/distributed/Distributed.jl +++ /dev/null @@ -1,76 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -module Distributed - -# imports for extension -import Base: getindex, wait, put!, take!, fetch, isready, push!, length, - hash, ==, connect, kill, serialize, deserialize, close, showerror - -# imports for use -using Base: Process, Semaphore, JLOptions, AnyDict, buffer_writes, wait_connected, - VERSION_STRING, sync_begin, sync_add, sync_end, async_run_thunk, - binding_module, notify_error, atexit, julia_exename, julia_cmd, - AsyncGenerator, display_error, acquire, release, invokelatest, warn_once, - shell_escape, uv_error - -# NOTE: clusterserialize.jl imports additional symbols from Base.Serializer for use - -export - @spawn, - @spawnat, - @fetch, - @fetchfrom, - @everywhere, - @parallel, - - addprocs, - CachingPool, - clear!, - ClusterManager, - default_worker_pool, - init_worker, - interrupt, - launch, - manage, - myid, - nprocs, - nworkers, - pmap, - procs, - remote, - remotecall, - remotecall_fetch, - remotecall_wait, - remote_do, - rmprocs, - workers, - WorkerPool, - RemoteChannel, - Future, - WorkerConfig, - RemoteException, - ProcessExitedException, - -# Add the following into Base as some Packages access them via Base. -# Also documented as such. - process_messages, - remoteref_id, - channel_from_id, - worker_id_from_socket, - cluster_cookie, - start_worker, - -# Used only by shared arrays. - check_same_host - -include("clusterserialize.jl") -include("cluster.jl") # cluster setup and management, addprocs -include("messages.jl") -include("process_messages.jl") # process incoming messages -include("remotecall.jl") # the remotecall* api -include("macros.jl") # @spawn and friends -include("workerpool.jl") -include("pmap.jl") -include("managers.jl") # LocalManager and SSHManager - -end diff --git a/julia-0.6.3/share/julia/base/distributed/cluster.jl b/julia-0.6.3/share/julia/base/distributed/cluster.jl deleted file mode 100644 index 1d1f74d..0000000 --- a/julia-0.6.3/share/julia/base/distributed/cluster.jl +++ /dev/null @@ -1,1045 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -abstract type ClusterManager end - -mutable struct WorkerConfig - # Common fields relevant to all cluster managers - io::Nullable{IO} - host::Nullable{AbstractString} - port::Nullable{Integer} - - # Used when launching additional workers at a host - count::Nullable{Union{Int, Symbol}} - exename::Nullable{Union{AbstractString, Cmd}} - exeflags::Nullable{Cmd} - - # External cluster managers can use this to store information at a per-worker level - # Can be a dict if multiple fields need to be stored. - userdata::Nullable{Any} - - # SSHManager / SSH tunnel connections to workers - tunnel::Nullable{Bool} - bind_addr::Nullable{AbstractString} - sshflags::Nullable{Cmd} - max_parallel::Nullable{Integer} - - # Used by Local/SSH managers - connect_at::Nullable{Any} - - process::Nullable{Process} - ospid::Nullable{Integer} - - # Private dictionary used to store temporary information by Local/SSH managers. - environ::Nullable{Dict} - - # Connections to be setup depending on the network topology requested - ident::Nullable{Any} # Worker as identified by the Cluster Manager. - # List of other worker idents this worker must connect with. Used with topology T_CUSTOM. - connect_idents::Nullable{Array} - - # Run multithreaded blas on worker - enable_threaded_blas::Nullable{Bool} - - function WorkerConfig() - wc = new() - for n in 1:length(WorkerConfig.types) - T = eltype(fieldtype(WorkerConfig, n)) - setfield!(wc, n, Nullable{T}()) - end - wc - end -end - -@enum WorkerState W_CREATED W_CONNECTED W_TERMINATING W_TERMINATED -mutable struct Worker - id::Int - del_msgs::Array{Any,1} - add_msgs::Array{Any,1} - gcflag::Bool - state::WorkerState - c_state::Condition # wait for state changes - ct_time::Float64 # creation time - - r_stream::IO - w_stream::IO - w_serializer::ClusterSerializer # writes can happen from any task hence store the - # serializer as part of the Worker object - manager::ClusterManager - config::WorkerConfig - version::Nullable{VersionNumber} # Julia version of the remote process - - function Worker(id::Int, r_stream::IO, w_stream::IO, manager::ClusterManager; - version=Nullable{VersionNumber}(), config=WorkerConfig()) - w = Worker(id) - w.r_stream = r_stream - w.w_stream = buffer_writes(w_stream) - w.w_serializer = ClusterSerializer(w.w_stream) - w.manager = manager - w.config = config - w.version = version - set_worker_state(w, W_CONNECTED) - register_worker_streams(w) - w - end - - function Worker(id::Int) - @assert id > 0 - if haskey(map_pid_wrkr, id) - return map_pid_wrkr[id] - end - w=new(id, [], [], false, W_CREATED, Condition(), time()) - register_worker(w) - w - end - - Worker() = Worker(get_next_pid()) -end - -function set_worker_state(w, state) - w.state = state - notify(w.c_state; all=true) -end - -function check_worker_state(w::Worker) - if w.state == W_CREATED - if PGRP.topology == :all_to_all - # Since higher pids connect with lower pids, the remote worker - # may not have connected to us yet. Wait for some time. - timeout = worker_timeout() - (time() - w.ct_time) - timeout <= 0 && error("peer $(w.id) has not connected to $(myid())") - - @schedule (sleep(timeout); notify(w.c_state; all=true)) - wait(w.c_state) - w.state == W_CREATED && error("peer $(w.id) didn't connect to $(myid()) within $timeout seconds") - else - error("peer $(w.id) is not connected to $(myid()). Topology : " * string(PGRP.topology)) - end - end -end - -## process group creation ## - -mutable struct LocalProcess - id::Int - bind_addr::AbstractString - bind_port::UInt16 - cookie::AbstractString - LocalProcess() = new(1) -end - - -function disable_threaded_libs() - BLAS.set_num_threads(1) -end - -worker_timeout() = parse(Float64, get(ENV, "JULIA_WORKER_TIMEOUT", "60.0")) - - -## worker creation and setup ## - -# The entry point for julia worker processes. does not return. Used for TCP transport. -# Cluster managers implementing their own transport will provide their own. -# Argument is descriptor to write listening port # to. -start_worker(cookie::AbstractString) = start_worker(STDOUT, cookie) -function start_worker(out::IO, cookie::AbstractString) - # we only explicitly monitor worker STDOUT on the console, so redirect - # stderr to stdout so we can see the output. - # at some point we might want some or all worker output to go to log - # files instead. - # Currently disabled since this caused processes to spin instead of - # exit when process 1 shut down. Don't yet know why. - #redirect_stderr(STDOUT) - - init_worker(cookie) - interface = IPv4(LPROC.bind_addr) - if LPROC.bind_port == 0 - (port, sock) = listenany(interface, UInt16(9009)) - LPROC.bind_port = port - else - sock = listen(interface, LPROC.bind_port) - end - @schedule while isopen(sock) - client = accept(sock) - process_messages(client, client, true) - end - print(out, "julia_worker:") # print header - print(out, "$(dec(LPROC.bind_port))#") # print port - print(out, LPROC.bind_addr) - print(out, '\n') - flush(out) - # close STDIN; workers will not use it - #close(STDIN) - - disable_nagle(sock) - - if ccall(:jl_running_on_valgrind,Cint,()) != 0 - println(out, "PID = $(getpid())") - end - - try - # To prevent hanging processes on remote machines, newly launched workers exit if the - # master process does not connect in time. - # TODO : Make timeout configurable. - check_master_connect() - while true; wait(); end - catch err - print(STDERR, "unhandled exception on $(myid()): $(err)\nexiting.\n") - end - - close(sock) - exit(0) -end - - -function redirect_worker_output(ident, stream) - @schedule while !eof(stream) - line = readline(stream) - if startswith(line, "\tFrom worker ") - # STDOUT's of "additional" workers started from an initial worker on a host are not available - # on the master directly - they are routed via the initial worker's STDOUT. - println(line) - else - println("\tFrom worker $(ident):\t$line") - end - end -end - - -# The default TCP transport relies on the worker listening on a free -# port available and printing its bind address and port. -# The master process uses this to connect to the worker and subsequently -# setup a all-to-all network. -function read_worker_host_port(io::IO) - t0 = time() - - # Wait at most for JULIA_WORKER_TIMEOUT seconds to read host:port - # info from the worker - timeout = worker_timeout() - - # We expect the first line to contain the host:port string. However, as - # the worker may be launched via ssh or a cluster manager like SLURM, - # ignore any informational / warning lines printed by the launch command. - # If we do not find the host:port string in the first 1000 lines, treat it - # as an error. - - ntries = 1000 - while ntries > 0 - readtask = @schedule readline(io) - yield() - while !istaskdone(readtask) && ((time() - t0) < timeout) - sleep(0.05) - end - !istaskdone(readtask) && break - - conninfo = wait(readtask) - if isempty(conninfo) && !isopen(io) - error("Unable to read host:port string from worker. Launch command exited with error?") - end - - ntries -= 1 - bind_addr, port = parse_connection_info(conninfo) - if !isempty(bind_addr) - return bind_addr, port - end - - # TODO: Identify root cause and report a better actionable error. - # Also print unmatched lines? - end - close(io) - if ntries > 0 - error("Timed out waiting to read host:port string from worker.") - else - error("Unexpected output from worker launch command. Host:port string not found.") - end -end - -function parse_connection_info(str) - m = match(r"^julia_worker:(\d+)#(.*)", str) - if m !== nothing - (m.captures[2], parse(UInt16, m.captures[1])) - else - ("", UInt16(0)) - end -end - -""" - init_worker(cookie::AbstractString, manager::ClusterManager=DefaultClusterManager()) - -Called by cluster managers implementing custom transports. It initializes a newly launched -process as a worker. Command line argument `--worker` has the effect of initializing a -process as a worker using TCP/IP sockets for transport. -`cookie` is a [`cluster_cookie`](@ref). -""" -function init_worker(cookie::AbstractString, manager::ClusterManager=DefaultClusterManager()) - # On workers, the default cluster manager connects via TCP sockets. Custom - # transports will need to call this function with their own manager. - global cluster_manager - cluster_manager = manager - - # Since our pid has yet to be set, ensure no RemoteChannel / Future have been created or addprocs() called. - assert(nprocs() <= 1) - assert(isempty(PGRP.refs)) - assert(isempty(client_refs)) - - # System is started in head node mode, cleanup related entries - empty!(PGRP.workers) - empty!(map_pid_wrkr) - - cluster_cookie(cookie) - nothing -end - - -# The main function for adding worker processes. -# `manager` is of type ClusterManager. The respective managers are responsible -# for launching the workers. All keyword arguments (plus a few default values) -# are available as a dictionary to the `launch` methods -# -# Only one addprocs can be in progress at any time -# -const worker_lock = ReentrantLock() - -""" - addprocs(manager::ClusterManager; kwargs...) -> List of process identifiers - -Launches worker processes via the specified cluster manager. - -For example, Beowulf clusters are supported via a custom cluster manager implemented in -the package `ClusterManagers.jl`. - -The number of seconds a newly launched worker waits for connection establishment from the -master can be specified via variable `JULIA_WORKER_TIMEOUT` in the worker process's -environment. Relevant only when using TCP/IP as transport. -""" -function addprocs(manager::ClusterManager; kwargs...) - cluster_mgmt_from_master_check() - - lock(worker_lock) - try - addprocs_locked(manager::ClusterManager; kwargs...) - finally - unlock(worker_lock) - end -end - -function addprocs_locked(manager::ClusterManager; kwargs...) - params = merge(default_addprocs_params(), AnyDict(kwargs)) - topology(Symbol(params[:topology])) - - # References to launched workers, filled when each worker is fully initialized and - # has connected to all nodes. - launched_q = Int[] # Asynchronously filled by the launch method - - # The `launch` method should add an object of type WorkerConfig for every - # worker launched. It provides information required on how to connect - # to it. - launched = WorkerConfig[] - launch_ntfy = Condition() - - # call manager's `launch` is a separate task. This allows the master - # process initiate the connection setup process as and when workers come - # online - t_launch = @schedule launch(manager, params, launched, launch_ntfy) - - @sync begin - while true - if isempty(launched) - istaskdone(t_launch) && break - @schedule (sleep(1); notify(launch_ntfy)) - wait(launch_ntfy) - end - - if !isempty(launched) - wconfig = shift!(launched) - let wconfig=wconfig - @async setup_launched_worker(manager, wconfig, launched_q) - end - end - end - end - - wait(t_launch) # catches any thrown errors from the launch task - - # Since all worker-to-worker setups may not have completed by the time this - # function returns to the caller, send the complete list to all workers. - # Useful for nprocs(), nworkers(), etc to return valid values on the workers. - all_w = workers() - for pid in all_w - remote_do(set_valid_processes, pid, all_w) - end - - sort!(launched_q) -end - -function set_valid_processes(plist::Array{Int}) - for pid in setdiff(plist, workers()) - myid() != pid && Worker(pid) - end -end - -default_addprocs_params() = AnyDict( - :topology => :all_to_all, - :dir => pwd(), - :exename => joinpath(JULIA_HOME, julia_exename()), - :exeflags => ``, - :enable_threaded_blas => false) - - -function setup_launched_worker(manager, wconfig, launched_q) - pid = create_worker(manager, wconfig) - push!(launched_q, pid) - - # When starting workers on remote multi-core hosts, `launch` can (optionally) start only one - # process on the remote machine, with a request to start additional workers of the - # same type. This is done by setting an appropriate value to `WorkerConfig.cnt`. - cnt = get(wconfig.count, 1) - if cnt === :auto - cnt = get(wconfig.environ)[:cpu_cores] - end - cnt = cnt - 1 # Removing self from the requested number - - if cnt > 0 - launch_n_additional_processes(manager, pid, wconfig, cnt, launched_q) - end -end - - -function launch_n_additional_processes(manager, frompid, fromconfig, cnt, launched_q) - @sync begin - exename = get(fromconfig.exename) - exeflags = get(fromconfig.exeflags, ``) - cmd = `$exename $exeflags` - - new_addresses = remotecall_fetch(launch_additional, frompid, cnt, cmd) - for address in new_addresses - (bind_addr, port) = address - - wconfig = WorkerConfig() - for x in [:host, :tunnel, :sshflags, :exeflags, :exename, :enable_threaded_blas] - setfield!(wconfig, x, getfield(fromconfig, x)) - end - wconfig.bind_addr = bind_addr - wconfig.port = port - - let wconfig=wconfig - @async begin - pid = create_worker(manager, wconfig) - remote_do(redirect_output_from_additional_worker, frompid, pid, port) - push!(launched_q, pid) - end - end - end - end -end - -function create_worker(manager, wconfig) - # only node 1 can add new nodes, since nobody else has the full list of address:port - assert(LPROC.id == 1) - - # initiate a connect. Does not wait for connection completion in case of TCP. - w = Worker() - local r_s, w_s - try - (r_s, w_s) = connect(manager, w.id, wconfig) - catch e - deregister_worker(w.id) - rethrow(e) - end - - w = Worker(w.id, r_s, w_s, manager; config=wconfig) - # install a finalizer to perform cleanup if necessary - finalizer(w, (w)->if myid() == 1 manage(w.manager, w.id, w.config, :finalize) end) - - # set when the new worker has finshed connections with all other workers - ntfy_oid = RRID() - rr_ntfy_join = lookup_ref(ntfy_oid) - rr_ntfy_join.waitingfor = myid() - - # Start a new task to handle inbound messages from connected worker in master. - # Also calls `wait_connected` on TCP streams. - process_messages(w.r_stream, w.w_stream, false) - - # send address information of all workers to the new worker. - # Cluster managers set the address of each worker in `WorkerConfig.connect_at`. - # A new worker uses this to setup an all-to-all network if topology :all_to_all is specified. - # Workers with higher pids connect to workers with lower pids. Except process 1 (master) which - # initiates connections to all workers. - - # Connection Setup Protocol: - # - Master sends 16-byte cookie followed by 16-byte version string and a JoinPGRP message to all workers - # - On each worker - # - Worker responds with a 16-byte version followed by a JoinCompleteMsg - # - Connects to all workers less than its pid. Sends the cookie, version and an IdentifySocket message - # - Workers with incoming connection requests write back their Version and an IdentifySocketAckMsg message - # - On master, receiving a JoinCompleteMsg triggers rr_ntfy_join (signifies that worker setup is complete) - - join_list = [] - if PGRP.topology == :all_to_all - # need to wait for lower worker pids to have completed connecting, since the numerical value - # of pids is relevant to the connection process, i.e., higher pids connect to lower pids and they - # require the value of config.connect_at which is set only upon connection completion - for jw in PGRP.workers - if (jw.id != 1) && (jw.id < w.id) - (jw.state == W_CREATED) && wait(jw.c_state) - push!(join_list, jw) - end - end - - elseif PGRP.topology == :custom - # wait for requested workers to be up before connecting to them. - filterfunc(x) = (x.id != 1) && isdefined(x, :config) && (get(x.config.ident) in get(wconfig.connect_idents, [])) - - wlist = filter(filterfunc, PGRP.workers) - while length(wlist) < length(get(wconfig.connect_idents, [])) - sleep(1.0) - wlist = filter(filterfunc, PGRP.workers) - end - - for wl in wlist - (wl.state == W_CREATED) && wait(wl.c_state) - push!(join_list, wl) - end - end - - all_locs = map(x -> isa(x, Worker) ? (get(x.config.connect_at, ()), x.id) : ((), x.id, true), join_list) - send_connection_hdr(w, true) - join_message = JoinPGRPMsg(w.id, all_locs, PGRP.topology, get(wconfig.enable_threaded_blas, false)) - send_msg_now(w, MsgHeader(RRID(0,0), ntfy_oid), join_message) - - @schedule manage(w.manager, w.id, w.config, :register) - wait(rr_ntfy_join) - lock(client_refs) do - delete!(PGRP.refs, ntfy_oid) - end - - return w.id -end - - -# Called on the first worker on a remote host. Used to optimize launching -# of multiple workers on a remote host (to leverage multi-core) - -additional_io_objs=Dict() -function launch_additional(np::Integer, cmd::Cmd) - io_objs = Vector{Any}(np) - addresses = Vector{Any}(np) - - for i in 1:np - io, pobj = open(pipeline(detach(cmd), stderr=STDERR), "r") - io_objs[i] = io - end - - for (i,io) in enumerate(io_objs) - (host, port) = read_worker_host_port(io) - addresses[i] = (host, port) - additional_io_objs[port] = io - end - - return addresses -end - -function redirect_output_from_additional_worker(pid, port) - io = additional_io_objs[port] - redirect_worker_output("$pid", io) - delete!(additional_io_objs, port) - nothing -end - -function check_master_connect() - timeout = worker_timeout() - # If we do not have at least process 1 connect to us within timeout - # we log an error and exit, unless we're running on valgrind - if ccall(:jl_running_on_valgrind,Cint,()) != 0 - return - end - @schedule begin - start = time() - while !haskey(map_pid_wrkr, 1) && (time() - start) < timeout - sleep(1.0) - end - - if !haskey(map_pid_wrkr, 1) - print(STDERR, "Master process (id 1) could not connect within $timeout seconds.\nexiting.\n") - exit(1) - end - end -end - - -""" - Base.cluster_cookie() -> cookie - -Returns the cluster cookie. -""" -cluster_cookie() = LPROC.cookie - -""" - Base.cluster_cookie(cookie) -> cookie - -Sets the passed cookie as the cluster cookie, then returns it. -""" -function cluster_cookie(cookie) - # The cookie must be an ASCII string with length <= HDR_COOKIE_LEN - assert(isascii(cookie)) - assert(length(cookie) <= HDR_COOKIE_LEN) - - cookie = rpad(cookie, HDR_COOKIE_LEN) - - LPROC.cookie = cookie - cookie -end - - -let next_pid = 2 # 1 is reserved for the client (always) - global get_next_pid - function get_next_pid() - retval = next_pid - next_pid += 1 - retval - end -end - -mutable struct ProcessGroup - name::AbstractString - workers::Array{Any,1} - refs::Dict # global references - topology::Symbol - - ProcessGroup(w::Array{Any,1}) = new("pg-default", w, Dict(), :all_to_all) -end -const PGRP = ProcessGroup([]) - -function topology(t) - assert(t in [:all_to_all, :master_slave, :custom]) - if (PGRP.topology==t) || ((myid()==1) && (nprocs()==1)) || (myid() > 1) - PGRP.topology = t - else - error("Workers with Topology $(PGRP.topology) already exist. Requested Topology $(t) cannot be set.") - end - t -end - -get_bind_addr(pid::Integer) = get_bind_addr(worker_from_id(pid)) -get_bind_addr(w::LocalProcess) = LPROC.bind_addr -function get_bind_addr(w::Worker) - if isnull(w.config.bind_addr) - if w.id != myid() - w.config.bind_addr = remotecall_fetch(get_bind_addr, w.id, w.id) - end - end - get(w.config.bind_addr) -end - -# globals -const LPROC = LocalProcess() -const HDR_VERSION_LEN=16 -const HDR_COOKIE_LEN=16 -const map_pid_wrkr = Dict{Int, Union{Worker, LocalProcess}}() -const map_sock_wrkr = ObjectIdDict() -const map_del_wrkr = Set{Int}() - -# cluster management related API -""" - myid() - -Get the id of the current process. -""" -myid() = LPROC.id - -""" - nprocs() - -Get the number of available processes. -""" -function nprocs() - if myid() == 1 || PGRP.topology == :all_to_all - n = length(PGRP.workers) - # filter out workers in the process of being setup/shutdown. - for jw in PGRP.workers - if !isa(jw, LocalProcess) && (jw.state != W_CONNECTED) - n = n - 1 - end - end - return n - else - return length(PGRP.workers) - end -end - -""" - nworkers() - -Get the number of available worker processes. This is one less than `nprocs()`. Equal to -`nprocs()` if `nprocs() == 1`. -""" -function nworkers() - n = nprocs() - n == 1 ? 1 : n-1 -end - -""" - procs() - -Returns a list of all process identifiers. -""" -function procs() - if myid() == 1 || PGRP.topology == :all_to_all - # filter out workers in the process of being setup/shutdown. - return Int[x.id for x in PGRP.workers if isa(x, LocalProcess) || (x.state == W_CONNECTED)] - else - return Int[x.id for x in PGRP.workers] - end -end - -function id_in_procs(id) # faster version of `id in procs()` - if myid() == 1 || PGRP.topology == :all_to_all - for x in PGRP.workers - if (x.id::Int) == id && (isa(x, LocalProcess) || (x::Worker).state == W_CONNECTED) - return true - end - end - else - for x in PGRP.workers - if (x.id::Int) == id - return true - end - end - end - return false -end - -""" - procs(pid::Integer) - -Returns a list of all process identifiers on the same physical node. -Specifically all workers bound to the same ip-address as `pid` are returned. -""" -function procs(pid::Integer) - if myid() == 1 - all_workers = [x for x in PGRP.workers if isa(x, LocalProcess) || (x.state == W_CONNECTED)] - if (pid == 1) || (isa(map_pid_wrkr[pid].manager, LocalManager)) - Int[x.id for x in filter(w -> (w.id==1) || (isa(w.manager, LocalManager)), all_workers)] - else - ipatpid = get_bind_addr(pid) - Int[x.id for x in filter(w -> get_bind_addr(w) == ipatpid, all_workers)] - end - else - remotecall_fetch(procs, 1, pid) - end -end - -""" - workers() - -Returns a list of all worker process identifiers. -""" -function workers() - allp = procs() - if length(allp) == 1 - allp - else - filter(x -> x != 1, allp) - end -end - -function cluster_mgmt_from_master_check() - if myid() != 1 - throw(ErrorException("Only process 1 can add and remove workers")) - end -end - -""" - rmprocs(pids...; waitfor=typemax(Int)) - -Removes the specified workers. Note that only process 1 can add or remove -workers. - -Argument `waitfor` specifies how long to wait for the workers to shut down: - - If unspecified, `rmprocs` will wait until all requested `pids` are removed. - - An `ErrorException` is raised if all workers cannot be terminated before - the requested `waitfor` seconds. - - With a `waitfor` value of 0, the call returns immediately with the workers - scheduled for removal in a different task. The scheduled `Task` object is - returned. The user should call `wait` on the task before invoking any other - parallel calls. -""" -function rmprocs(pids...; waitfor=typemax(Int)) - cluster_mgmt_from_master_check() - - pids = vcat(pids...) - if waitfor == 0 - t = @schedule _rmprocs(pids, typemax(Int)) - yield() - return t - else - _rmprocs(pids, waitfor) - # return a dummy task object that user code can wait on. - return @schedule nothing - end -end - -function _rmprocs(pids, waitfor) - lock(worker_lock) - try - rmprocset = [] - for p in vcat(pids...) - if p == 1 - warn("rmprocs: process 1 not removed") - else - if haskey(map_pid_wrkr, p) - w = map_pid_wrkr[p] - set_worker_state(w, W_TERMINATING) - kill(w.manager, p, w.config) - push!(rmprocset, w) - end - end - end - - start = time() - while (time() - start) < waitfor - all(w -> w.state == W_TERMINATED, rmprocset) && break - sleep(min(0.1, waitfor - (time() - start))) - end - - unremoved = [wrkr.id for wrkr in filter(w -> w.state != W_TERMINATED, rmprocset)] - if length(unremoved) > 0 - estr = string("rmprocs: pids ", unremoved, " not terminated after ", waitfor, " seconds.") - throw(ErrorException(estr)) - end - finally - unlock(worker_lock) - end -end - - -""" - ProcessExitedException() - -After a client Julia process has exited, further attempts to reference the dead child will -throw this exception. -""" -ProcessExitedException() -mutable struct ProcessExitedException <: Exception end - -worker_from_id(i) = worker_from_id(PGRP, i) -function worker_from_id(pg::ProcessGroup, i) - if !isempty(map_del_wrkr) && in(i, map_del_wrkr) - throw(ProcessExitedException()) - end - w = get(map_pid_wrkr, i, nothing) - if w === nothing - if myid() == 1 - error("no process with id $i exists") - end - w = Worker(i) - map_pid_wrkr[i] = w - else - w = w::Union{Worker, LocalProcess} - end - w -end - -""" - Base.worker_id_from_socket(s) -> pid - -A low-level API which given a `IO` connection or a `Worker`, -returns the `pid` of the worker it is connected to. -This is useful when writing custom [`serialize`](@ref) methods for a type, -which optimizes the data written out depending on the receiving process id. -""" -function worker_id_from_socket(s) - w = get(map_sock_wrkr, s, nothing) - if isa(w,Worker) - if s === w.r_stream || s === w.w_stream - return w.id - end - end - if isa(s,IOStream) && fd(s)==-1 - # serializing to a local buffer - return myid() - end - return -1 -end - - -register_worker(w) = register_worker(PGRP, w) -function register_worker(pg, w) - push!(pg.workers, w) - map_pid_wrkr[w.id] = w -end - -function register_worker_streams(w) - map_sock_wrkr[w.r_stream] = w - map_sock_wrkr[w.w_stream] = w -end - -deregister_worker(pid) = deregister_worker(PGRP, pid) -function deregister_worker(pg, pid) - pg.workers = filter(x -> !(x.id == pid), pg.workers) - w = pop!(map_pid_wrkr, pid, nothing) - if isa(w, Worker) - if isdefined(w, :r_stream) - pop!(map_sock_wrkr, w.r_stream, nothing) - if w.r_stream != w.w_stream - pop!(map_sock_wrkr, w.w_stream, nothing) - end - end - - if myid() == 1 && isdefined(w, :config) - # Notify the cluster manager of this workers death - manage(w.manager, w.id, w.config, :deregister) - if PGRP.topology != :all_to_all - for rpid in workers() - try - remote_do(deregister_worker, rpid, pid) - catch - end - end - end - end - end - push!(map_del_wrkr, pid) - - # delete this worker from our remote reference client sets - ids = [] - tonotify = [] - lock(client_refs) do - for (id,rv) in pg.refs - if in(pid,rv.clientset) - push!(ids, id) - end - if rv.waitingfor == pid - push!(tonotify, (id,rv)) - end - end - for id in ids - del_client(pg, id, pid) - end - - # throw exception to tasks waiting for this pid - for (id,rv) in tonotify - notify_error(rv.c, ProcessExitedException()) - delete!(pg.refs, id) - end - end -end - - -function interrupt(pid::Integer) - assert(myid() == 1) - w = map_pid_wrkr[pid] - if isa(w, Worker) - manage(w.manager, w.id, w.config, :interrupt) - end -end - -""" - interrupt(pids::Integer...) - -Interrupt the current executing task on the specified workers. This is equivalent to -pressing Ctrl-C on the local machine. If no arguments are given, all workers are interrupted. -""" -interrupt(pids::Integer...) = interrupt([pids...]) - -""" - interrupt(pids::AbstractVector=workers()) - -Interrupt the current executing task on the specified workers. This is equivalent to -pressing Ctrl-C on the local machine. If no arguments are given, all workers are interrupted. -""" -function interrupt(pids::AbstractVector=workers()) - assert(myid() == 1) - @sync begin - for pid in pids - @async interrupt(pid) - end - end -end - - -function disable_nagle(sock) - # disable nagle on all OSes - ccall(:uv_tcp_nodelay, Cint, (Ptr{Void}, Cint), sock.handle, 1) - @static if is_linux() - # tcp_quickack is a linux only option - if ccall(:jl_tcp_quickack, Cint, (Ptr{Void}, Cint), sock.handle, 1) < 0 - warn_once("Networking unoptimized ( Error enabling TCP_QUICKACK : ", Libc.strerror(Libc.errno()), " )") - end - end -end - -function check_same_host(pids) - if myid() != 1 - return remotecall_fetch(check_same_host, 1, pids) - else - # We checkfirst if all test pids have been started using the local manager, - # else we check for the same bind_to addr. This handles the special case - # where the local ip address may change - as during a system sleep/awake - if all(p -> (p==1) || (isa(map_pid_wrkr[p].manager, LocalManager)), pids) - return true - else - first_bind_addr = get(map_pid_wrkr[pids[1]].config.bind_addr) - return all(p -> (p != 1) && (get(map_pid_wrkr[p].config.bind_addr) == first_bind_addr), pids[2:end]) - end - end -end - -function terminate_all_workers() - myid() != 1 && return - - if nprocs() > 1 - try - rmprocs(workers(); waitfor=5.0) - catch _ex - warn("Forcibly interrupting busy workers") - # Might be computation bound, interrupt them and try again - interrupt(workers()) - try - rmprocs(workers(); waitfor=5.0) - catch _ex2 - warn("Unable to terminate all workers") - end - end - end -end - -# initialize the local proc network address / port -function init_bind_addr() - opts = JLOptions() - if opts.bindto != C_NULL - bind_to = split(unsafe_string(opts.bindto), ":") - bind_addr = string(parse(IPAddr, bind_to[1])) - if length(bind_to) > 1 - bind_port = parse(Int,bind_to[2]) - else - bind_port = 0 - end - else - bind_port = 0 - try - bind_addr = string(getipaddr()) - catch - # All networking is unavailable, initialize bind_addr to the loopback address - # Will cause an exception to be raised only when used. - bind_addr = "127.0.0.1" - end - end - global LPROC - LPROC.bind_addr = bind_addr - LPROC.bind_port = UInt16(bind_port) -end - -function init_parallel() - start_gc_msgs_task() - atexit(terminate_all_workers) - - init_bind_addr() - - # start in "head node" mode, if worker, will override later. - global PGRP - global LPROC - LPROC.id = 1 - cluster_cookie(randstring(HDR_COOKIE_LEN)) - assert(isempty(PGRP.workers)) - register_worker(LPROC) -end diff --git a/julia-0.6.3/share/julia/base/distributed/clusterserialize.jl b/julia-0.6.3/share/julia/base/distributed/clusterserialize.jl deleted file mode 100644 index 9fb256d..0000000 --- a/julia-0.6.3/share/julia/base/distributed/clusterserialize.jl +++ /dev/null @@ -1,249 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -using Base.Serializer: object_number, serialize_cycle, deserialize_cycle, writetag, - __deserialized_types__, serialize_typename, deserialize_typename, - TYPENAME_TAG, object_numbers, reset_state, serialize_type - -import Base.Serializer: lookup_object_number, remember_object - -mutable struct ClusterSerializer{I<:IO} <: AbstractSerializer - io::I - counter::Int - table::ObjectIdDict - pending_refs::Vector{Int} - - pid::Int # Worker we are connected to. - tn_obj_sent::Set{UInt64} # TypeName objects sent - glbs_sent::Dict{UInt64, UInt64} # (key,value) -> (object_id, hash_value) - glbs_in_tnobj::Dict{UInt64, Vector{Symbol}} # Track globals referenced in - # anonymous functions. - anonfunc_id::UInt64 - - function ClusterSerializer{I}(io::I) where I<:IO - new(io, 0, ObjectIdDict(), Int[], Base.worker_id_from_socket(io), - Set{UInt64}(), Dict{UInt64, UInt64}(), Dict{UInt64, Vector{Symbol}}(), 0) - end -end -ClusterSerializer(io::IO) = ClusterSerializer{typeof(io)}(io) - -const known_object_data = Dict{UInt64,Any}() - -function lookup_object_number(s::ClusterSerializer, n::UInt64) - return get(known_object_data, n, nothing) -end - -function remember_object(s::ClusterSerializer, o::ANY, n::UInt64) - known_object_data[n] = o - if isa(o, TypeName) && !haskey(object_numbers, o) - # set up reverse mapping for serialize - object_numbers[o] = n - end - return nothing -end - -function deserialize(s::ClusterSerializer, ::Type{TypeName}) - full_body_sent = deserialize(s) - number = read(s.io, UInt64) - if !full_body_sent - tn = lookup_object_number(s, number)::TypeName - remember_object(s, tn, number) - deserialize_cycle(s, tn) - else - tn = deserialize_typename(s, number) - end - - # retrieve arrays of global syms sent if any and deserialize them all. - foreach(sym->deserialize_global_from_main(s, sym), deserialize(s)) - return tn -end - -function serialize(s::ClusterSerializer, t::TypeName) - serialize_cycle(s, t) && return - writetag(s.io, TYPENAME_TAG) - - identifier = object_number(t) - send_whole = !(identifier in s.tn_obj_sent) - serialize(s, send_whole) - write(s.io, identifier) - if send_whole - # Track globals referenced in this anonymous function. - # This information is used to resend modified globals when we - # only send the identifier. - prev = s.anonfunc_id - s.anonfunc_id = identifier - serialize_typename(s, t) - s.anonfunc_id = prev - push!(s.tn_obj_sent, identifier) - finalizer(t, x->cleanup_tname_glbs(s, identifier)) - end - - # Send global refs if required. - syms = syms_2b_sent(s, identifier) - serialize(s, syms) - foreach(sym->serialize_global_from_main(s, sym), syms) - nothing -end - -function serialize(s::ClusterSerializer, g::GlobalRef) - # Record if required and then invoke the default GlobalRef serializer. - sym = g.name - if g.mod === Main && isdefined(g.mod, sym) - if (binding_module(Main, sym) === Main) && (s.anonfunc_id != 0) && - !startswith(string(sym), "#") # Anonymous functions are handled via FULL_GLOBALREF_TAG - - push!(get!(s.glbs_in_tnobj, s.anonfunc_id, []), sym) - end - end - - invoke(serialize, Tuple{AbstractSerializer, GlobalRef}, s, g) -end - -# Send/resend a global object if -# a) has not been sent previously, i.e., we are seeing this object_id for the first time, or, -# b) hash value has changed or -# c) is a bits type -function syms_2b_sent(s::ClusterSerializer, identifier) - lst = Symbol[] - check_syms = get(s.glbs_in_tnobj, identifier, []) - for sym in check_syms - v = getfield(Main, sym) - - if isbits(v) - push!(lst, sym) - else - oid = object_id(v) - if haskey(s.glbs_sent, oid) - # We have sent this object before, see if it has changed. - s.glbs_sent[oid] != hash(sym, hash(v)) && push!(lst, sym) - else - push!(lst, sym) - end - end - end - return unique(lst) -end - -function serialize_global_from_main(s::ClusterSerializer, sym) - v = getfield(Main, sym) - - oid = object_id(v) - record_v = true - if isbits(v) - record_v = false - elseif !haskey(s.glbs_sent, oid) - # set up a finalizer the first time this object is sent - try - finalizer(v, x->delete_global_tracker(s,x)) - catch ex - # Do not track objects that cannot be finalized. - if isa(ex, ErrorException) - record_v = false - else - rethrow(ex) - end - end - end - record_v && (s.glbs_sent[oid] = hash(sym, hash(v))) - - serialize(s, isconst(Main, sym)) - serialize(s, v) -end - -function deserialize_global_from_main(s::ClusterSerializer, sym) - sym_isconst = deserialize(s) - v = deserialize(s) - if sym_isconst - @eval Main const $sym = $v - else - @eval Main $sym = $v - end -end - -function delete_global_tracker(s::ClusterSerializer, v) - oid = object_id(v) - if haskey(s.glbs_sent, oid) - delete!(s.glbs_sent, oid) - end - - # TODO: A global binding is released and gc'ed here but it continues - # to occupy memory on the remote node. Would be nice to release memory - # if possible. -end - -function cleanup_tname_glbs(s::ClusterSerializer, identifier) - delete!(s.glbs_in_tnobj, identifier) -end - -# TODO: cleanup from s.tn_obj_sent - - -# Specialized serialize-deserialize implementations for CapturedException to partially -# recover from any deserialization errors in `CapturedException.ex` - -function serialize(s::ClusterSerializer, ex::CapturedException) - serialize_type(s, typeof(ex)) - serialize(s, string(typeof(ex.ex))) # String type should not result in a deser error - serialize(s, ex.processed_bt) # Currently should not result in a deser error - serialize(s, ex.ex) # can result in a UndefVarError on the remote node - # if a type used in ex.ex is undefined on the remote node. -end - -function original_ex(s::ClusterSerializer, ex_str, remote_stktrace) - local pid_str = "" - try - pid_str = string(" from worker ", worker_id_from_socket(s.io)) - end - - stk_str = remote_stktrace ? "Remote" : "Local" - ErrorException(string("Error deserializing a remote exception", pid_str, "\n", - "Remote(original) exception of type ", ex_str, "\n", - stk_str, " stacktrace : ")) -end - -function deserialize(s::ClusterSerializer, t::Type{<:CapturedException}) - ex_str = deserialize(s) - local bt - local capex - try - bt = deserialize(s) - catch e - throw(CompositeException([ - original_ex(s, ex_str, false), - CapturedException(e, catch_backtrace()) - ])) - end - - try - capex = deserialize(s) - catch e - throw(CompositeException([ - CapturedException(original_ex(s, ex_str, true), bt), - CapturedException(e, catch_backtrace()) - ])) - end - - return CapturedException(capex, bt) -end - -""" - clear!(syms, pids=workers(); mod=Main) - -Clears global bindings in modules by initializing them to `nothing`. -`syms` should be of type `Symbol` or a collection of `Symbol`s . `pids` and `mod` -identify the processes and the module in which global variables are to be -reinitialized. Only those names found to be defined under `mod` are cleared. - -An exception is raised if a global constant is requested to be cleared. -""" -function clear!(syms, pids=workers(); mod=Main) - @sync for p in pids - @async remotecall_wait(clear_impl!, p, syms, mod) - end -end -clear!(sym::Symbol, pid::Int; mod=Main) = clear!([sym], [pid]; mod=mod) -clear!(sym::Symbol, pids=workers(); mod=Main) = clear!([sym], pids; mod=mod) -clear!(syms, pid::Int; mod=Main) = clear!(syms, [pid]; mod=mod) - -clear_impl!(syms, mod::Module) = foreach(x->clear_impl!(x,mod), syms) -clear_impl!(sym::Symbol, mod::Module) = isdefined(mod, sym) && @eval(mod, global $sym = nothing) - diff --git a/julia-0.6.3/share/julia/base/distributed/macros.jl b/julia-0.6.3/share/julia/base/distributed/macros.jl deleted file mode 100644 index b3fefa2..0000000 --- a/julia-0.6.3/share/julia/base/distributed/macros.jl +++ /dev/null @@ -1,223 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -let nextidx = 0 - global nextproc - function nextproc() - p = -1 - if p == -1 - p = workers()[(nextidx % nworkers()) + 1] - nextidx += 1 - end - p - end -end - -spawnat(p, thunk) = sync_add(remotecall(thunk, p)) - -spawn_somewhere(thunk) = spawnat(nextproc(),thunk) - -macro spawn(expr) - thunk = esc(:(()->($expr))) - :(spawn_somewhere($thunk)) -end - -macro spawnat(p, expr) - thunk = esc(:(()->($expr))) - :(spawnat($(esc(p)), $thunk)) -end - -""" - @fetch - -Equivalent to `fetch(@spawn expr)`. -See [`fetch`](@ref) and [`@spawn`](@ref). -""" -macro fetch(expr) - thunk = esc(:(()->($expr))) - :(remotecall_fetch($thunk, nextproc())) -end - -""" - @fetchfrom - -Equivalent to `fetch(@spawnat p expr)`. -See [`fetch`](@ref) and [`@spawnat`](@ref). -""" -macro fetchfrom(p, expr) - thunk = esc(:(()->($expr))) - :(remotecall_fetch($thunk, $(esc(p)))) -end - -# extract a list of modules to import from an expression -extract_imports!(imports, x) = imports -function extract_imports!(imports, ex::Expr) - if Meta.isexpr(ex, (:import, :using)) - return push!(imports, ex.args[1]) - elseif Meta.isexpr(ex, :let) - return extract_imports!(imports, ex.args[1]) - elseif Meta.isexpr(ex, (:toplevel, :block)) - for i in eachindex(ex.args) - extract_imports!(imports, ex.args[i]) - end - end - return imports -end -extract_imports(x) = extract_imports!(Symbol[], x) - -""" - @everywhere expr - -Execute an expression under `Main` everywhere. Equivalent to calling -`eval(Main, expr)` on all processes. Errors on any of the processes are collected into a -`CompositeException` and thrown. For example : - - @everywhere bar=1 - -will define `Main.bar` on all processes. - -Unlike [`@spawn`](@ref) and [`@spawnat`](@ref), -`@everywhere` does not capture any local variables. Prefixing -`@everywhere` with [`@eval`](@ref) allows us to broadcast -local variables using interpolation : - - foo = 1 - @eval @everywhere bar=\$foo - -The expression is evaluated under `Main` irrespective of where `@everywhere` is called from. -For example : - - module FooBar - foo() = @everywhere bar()=myid() - end - FooBar.foo() - -will result in `Main.bar` being defined on all processes and not `FooBar.bar`. -""" -macro everywhere(ex) - imps = [Expr(:import, m) for m in extract_imports(ex)] - quote - $(isempty(imps) ? nothing : Expr(:toplevel, imps...)) - sync_begin() - for pid in workers() - async_run_thunk(()->remotecall_fetch(eval_ew_expr, pid, $(Expr(:quote,ex)))) - yield() # ensure that the remotecall_fetch has been started - end - - # execute locally last as we do not want local execution to block serialization - # of the request to remote nodes. - if nprocs() > 1 - async_run_thunk(()->eval_ew_expr($(Expr(:quote,ex)))) - end - - sync_end() - end -end - -eval_ew_expr(ex) = (eval(Main, ex); nothing) - -# Statically split range [1,N] into equal sized chunks for np processors -function splitrange(N::Int, np::Int) - each = div(N,np) - extras = rem(N,np) - nchunks = each > 0 ? np : extras - chunks = Vector{UnitRange{Int}}(nchunks) - lo = 1 - for i in 1:nchunks - hi = lo + each - 1 - if extras > 0 - hi += 1 - extras -= 1 - end - chunks[i] = lo:hi - lo = hi+1 - end - return chunks -end - -function preduce(reducer, f, R) - N = length(R) - chunks = splitrange(N, nworkers()) - all_w = workers()[1:length(chunks)] - - w_exec = Task[] - for (idx,pid) in enumerate(all_w) - t = Task(()->remotecall_fetch(f, pid, reducer, R, first(chunks[idx]), last(chunks[idx]))) - schedule(t) - push!(w_exec, t) - end - reduce(reducer, [wait(t) for t in w_exec]) -end - -function pfor(f, R) - [@spawn f(R, first(c), last(c)) for c in splitrange(length(R), nworkers())] -end - -function make_preduce_body(var, body) - quote - function (reducer, R, lo::Int, hi::Int) - $(esc(var)) = R[lo] - ac = $(esc(body)) - if lo != hi - for $(esc(var)) in R[(lo+1):hi] - ac = reducer(ac, $(esc(body))) - end - end - ac - end - end -end - -function make_pfor_body(var, body) - quote - function (R, lo::Int, hi::Int) - for $(esc(var)) in R[lo:hi] - $(esc(body)) - end - end - end -end - -""" - @parallel - -A parallel for loop of the form : - - @parallel [reducer] for var = range - body - end - -The specified range is partitioned and locally executed across all workers. In case an -optional reducer function is specified, `@parallel` performs local reductions on each worker -with a final reduction on the calling process. - -Note that without a reducer function, `@parallel` executes asynchronously, i.e. it spawns -independent tasks on all available workers and returns immediately without waiting for -completion. To wait for completion, prefix the call with [`@sync`](@ref), like : - - @sync @parallel for var = range - body - end -""" -macro parallel(args...) - na = length(args) - if na==1 - loop = args[1] - elseif na==2 - reducer = args[1] - loop = args[2] - else - throw(ArgumentError("wrong number of arguments to @parallel")) - end - if !isa(loop,Expr) || loop.head !== :for - error("malformed @parallel loop") - end - var = loop.args[1].args[1] - r = loop.args[1].args[2] - body = loop.args[2] - if na==1 - thecall = :(pfor($(make_pfor_body(var, body)), $(esc(r)))) - else - thecall = :(preduce($(esc(reducer)), $(make_preduce_body(var, body)), $(esc(r)))) - end - thecall -end diff --git a/julia-0.6.3/share/julia/base/distributed/managers.jl b/julia-0.6.3/share/julia/base/distributed/managers.jl deleted file mode 100644 index 1ea79e2..0000000 --- a/julia-0.6.3/share/julia/base/distributed/managers.jl +++ /dev/null @@ -1,530 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -# Built-in SSH and Local Managers - -struct SSHManager <: ClusterManager - machines::Dict - - function SSHManager(machines) - # machines => array of machine elements - # machine => address or (address, cnt) - # address => string of form `[user@]host[:port] bind_addr[:bind_port]` - # cnt => :auto or number - # :auto launches NUM_CORES number of workers at address - # number launches the specified number of workers at address - mhist = Dict() - for m in machines - if isa(m, Tuple) - host=m[1] - cnt=m[2] - else - host=m - cnt=1 - end - current_cnt = get(mhist, host, 0) - - if isa(cnt, Number) - mhist[host] = isa(current_cnt, Number) ? current_cnt + Int(cnt) : Int(cnt) - else - mhist[host] = cnt - end - end - new(mhist) - end -end - - -function check_addprocs_args(kwargs) - valid_kw_names = collect(keys(default_addprocs_params())) - for keyname in kwargs - !(keyname[1] in valid_kw_names) && throw(ArgumentError("Invalid keyword argument $(keyname[1])")) - end -end - -# SSHManager - -# start and connect to processes via SSH, optionally through an SSH tunnel. -# the tunnel is only used from the head (process 1); the nodes are assumed -# to be mutually reachable without a tunnel, as is often the case in a cluster. -# Default value of kw arg max_parallel is the default value of MaxStartups in sshd_config -# A machine is either a or a tuple of (, count) -""" - addprocs(machines; tunnel=false, sshflags=\`\`, max_parallel=10, kwargs...) -> List of process identifiers - -Add processes on remote machines via SSH. Requires `julia` to be installed in the same -location on each node, or to be available via a shared file system. - -`machines` is a vector of machine specifications. Workers are started for each specification. - -A machine specification is either a string `machine_spec` or a tuple - `(machine_spec, count)`. - -`machine_spec` is a string of the form `[user@]host[:port] [bind_addr[:port]]`. `user` -defaults to current user, `port` to the standard ssh port. If `[bind_addr[:port]]` is -specified, other workers will connect to this worker at the specified `bind_addr` and -`port`. - -`count` is the number of workers to be launched on the specified host. If specified as -`:auto` it will launch as many workers as the number of cores on the specific host. - -Keyword arguments: - -* `tunnel`: if `true` then SSH tunneling will be used to connect to the worker from the - master process. Default is `false`. - -* `sshflags`: specifies additional ssh options, e.g. ```sshflags=\`-i /home/foo/bar.pem\```` - -* `max_parallel`: specifies the maximum number of workers connected to in parallel at a - host. Defaults to 10. - -* `dir`: specifies the working directory on the workers. Defaults to the host's current - directory (as found by `pwd()`) - -* `enable_threaded_blas`: if `true` then BLAS will run on multiple threads in added - processes. Default is `false`. - -* `exename`: name of the `julia` executable. Defaults to `"\$JULIA_HOME/julia"` or - `"\$JULIA_HOME/julia-debug"` as the case may be. - -* `exeflags`: additional flags passed to the worker processes. - -* `topology`: Specifies how the workers connect to each other. Sending a message between - unconnected workers results in an error. - - + `topology=:all_to_all`: All processes are connected to each other. The default. - - + `topology=:master_slave`: Only the driver process, i.e. `pid` 1 connects to the - workers. The workers do not connect to each other. - - + `topology=:custom`: The `launch` method of the cluster manager specifies the - connection topology via fields `ident` and `connect_idents` in `WorkerConfig`. - A worker with a cluster manager identity `ident` will connect to all workers specified - in `connect_idents`. - - -Environment variables : - -If the master process fails to establish a connection with a newly launched worker within -60.0 seconds, the worker treats it as a fatal situation and terminates. -This timeout can be controlled via environment variable `JULIA_WORKER_TIMEOUT`. -The value of `JULIA_WORKER_TIMEOUT` on the master process specifies the number of seconds a -newly launched worker waits for connection establishment. -""" -function addprocs(machines::AbstractVector; tunnel=false, sshflags=``, max_parallel=10, kwargs...) - check_addprocs_args(kwargs) - addprocs(SSHManager(machines); tunnel=tunnel, sshflags=sshflags, max_parallel=max_parallel, kwargs...) -end - - -function launch(manager::SSHManager, params::Dict, launched::Array, launch_ntfy::Condition) - # Launch one worker on each unique host in parallel. Additional workers are launched later. - # Wait for all launches to complete. - launch_tasks = Vector{Any}(length(manager.machines)) - - for (i,(machine, cnt)) in enumerate(manager.machines) - let machine=machine, cnt=cnt - launch_tasks[i] = @schedule try - launch_on_machine(manager, machine, cnt, params, launched, launch_ntfy) - catch e - print(STDERR, "exception launching on machine $(machine) : $(e)\n") - end - end - end - - for t in launch_tasks - wait(t) - end - - notify(launch_ntfy) -end - - -show(io::IO, manager::SSHManager) = println(io, "SSHManager(machines=", manager.machines, ")") - - -function launch_on_machine(manager::SSHManager, machine, cnt, params, launched, launch_ntfy::Condition) - dir = params[:dir] - exename = params[:exename] - exeflags = params[:exeflags] - - # machine could be of the format [user@]host[:port] bind_addr[:bind_port] - # machine format string is split on whitespace - machine_bind = split(machine) - if isempty(machine_bind) - throw(ArgumentError("invalid machine definition format string: \"$machine\$")) - end - if length(machine_bind) > 1 - exeflags = `--bind-to $(machine_bind[2]) $exeflags` - end - exeflags = `$exeflags --worker $(cluster_cookie())` - - machine_def = split(machine_bind[1], ':') - # if this machine def has a port number, add the port information to the ssh flags - if length(machine_def) > 2 - throw(ArgumentError("invalid machine definition format string: invalid port format \"$machine_def\"")) - end - host = machine_def[1] - portopt = `` - if length(machine_def) == 2 - portstr = machine_def[2] - if !all(isdigit, portstr) || (p = parse(Int,portstr); p < 1 || p > 65535) - msg = "invalid machine definition format string: invalid port format \"$machine_def\"" - throw(ArgumentError(msg)) - end - portopt = ` -p $(machine_def[2]) ` - end - sshflags = `$(params[:sshflags]) $portopt` - - # Build up the ssh command - - # the default worker timeout - tval = haskey(ENV, "JULIA_WORKER_TIMEOUT") ? - `export JULIA_WORKER_TIMEOUT=$(ENV["JULIA_WORKER_TIMEOUT"])\;` : `` - - # Julia process with passed in command line flag arguments - cmd = `cd $dir '&&' $tval $exename $exeflags` - - # shell login (-l) with string command (-c) to launch julia process - cmd = `sh -l -c $(shell_escape(cmd))` - - # remote launch with ssh with given ssh flags / host / port information - # -T → disable pseudo-terminal allocation - # -a → disable forwarding of auth agent connection - # -x → disable X11 forwarding - # -o ClearAllForwardings → option if forwarding connections and - # forwarded connections are causing collisions - # -n → Redirects stdin from /dev/null (actually, prevents reading from stdin). - # Used when running ssh in the background. - cmd = `ssh -T -a -x -o ClearAllForwardings=yes -n $sshflags $host $(shell_escape(cmd))` - - # launch the remote Julia process - - # detach launches the command in a new process group, allowing it to outlive - # the initial julia process (Ctrl-C and teardown methods are handled through messages) - # for the launched processes. - io, pobj = open(pipeline(detach(cmd), stderr=STDERR), "r") - - wconfig = WorkerConfig() - wconfig.io = io - wconfig.host = host - wconfig.tunnel = params[:tunnel] - wconfig.sshflags = sshflags - wconfig.exeflags = exeflags - wconfig.exename = exename - wconfig.count = cnt - wconfig.max_parallel = params[:max_parallel] - wconfig.enable_threaded_blas = params[:enable_threaded_blas] - - - push!(launched, wconfig) - notify(launch_ntfy) -end - - -function manage(manager::SSHManager, id::Integer, config::WorkerConfig, op::Symbol) - if op == :interrupt - ospid = get(config.ospid, 0) - if ospid > 0 - host = get(config.host) - sshflags = get(config.sshflags) - if !success(`ssh -T -a -x -o ClearAllForwardings=yes -n $sshflags $host "kill -2 $ospid"`) - warn(STDERR,"error sending a Ctrl-C to julia worker $id on $host") - end - else - # This state can happen immediately after an addprocs - warn(STDERR,"worker $id cannot be presently interrupted.") - end - end -end - -let tunnel_port = 9201 - global next_tunnel_port - function next_tunnel_port() - retval = tunnel_port - if tunnel_port > 32000 - tunnel_port = 9201 - else - tunnel_port += 1 - end - retval - end -end - - -""" - ssh_tunnel(user, host, bind_addr, port, sshflags) -> localport - -Establish an SSH tunnel to a remote worker. -Returns a port number `localport` such that `localhost:localport` connects to `host:port`. -""" -function ssh_tunnel(user, host, bind_addr, port, sshflags) - port = Int(port) - cnt = ntries = 100 - # if we cannot do port forwarding, bail immediately - # the connection is forwarded to `port` on the remote server over the local port `localport` - # the -f option backgrounds the ssh session - # `sleep 60` command specifies that an alloted time of 60 seconds is allowed to start the - # remote julia process and establish the network connections specified by the process topology. - # If no connections are made within 60 seconds, ssh will exit and an error will be printed on the - # process that launched the remote process. - ssh = `ssh -T -a -x -o ExitOnForwardFailure=yes` - while cnt > 0 - localport = next_tunnel_port() - if success(detach(`$ssh -f $sshflags $user@$host -L $localport:$bind_addr:$port sleep 60`)) - return localport - end - cnt -= 1 - end - - throw(ErrorException( - string("unable to create SSH tunnel after ", ntries, " tries. No free port?"))) -end - - -# LocalManager -struct LocalManager <: ClusterManager - np::Integer - restrict::Bool # Restrict binding to 127.0.0.1 only -end - -""" - addprocs(; kwargs...) -> List of process identifiers - -Equivalent to `addprocs(Sys.CPU_CORES; kwargs...)` - -Note that workers do not run a `.juliarc.jl` startup script, nor do they synchronize their -global state (such as global variables, new method definitions, and loaded modules) with any -of the other running processes. -""" -addprocs(; kwargs...) = addprocs(Sys.CPU_CORES; kwargs...) - -""" - addprocs(np::Integer; restrict=true, kwargs...) -> List of process identifiers - -Launches workers using the in-built `LocalManager` which only launches workers on the -local host. This can be used to take advantage of multiple cores. `addprocs(4)` will add 4 -processes on the local machine. If `restrict` is `true`, binding is restricted to -`127.0.0.1`. Keyword args `dir`, `exename`, `exeflags`, `topology`, and -`enable_threaded_blas` have the same effect as documented for `addprocs(machines)`. -""" -function addprocs(np::Integer; restrict=true, kwargs...) - check_addprocs_args(kwargs) - addprocs(LocalManager(np, restrict); kwargs...) -end - -show(io::IO, manager::LocalManager) = println(io, "LocalManager()") - -function launch(manager::LocalManager, params::Dict, launched::Array, c::Condition) - dir = params[:dir] - exename = params[:exename] - exeflags = params[:exeflags] - bind_to = manager.restrict ? `127.0.0.1` : `$(LPROC.bind_addr)` - - for i in 1:manager.np - io, pobj = open(pipeline(detach( - setenv(`$(julia_cmd(exename)) $exeflags --bind-to $bind_to --worker $(cluster_cookie())`, dir=dir)), - stderr=STDERR), "r") - wconfig = WorkerConfig() - wconfig.process = pobj - wconfig.io = io - wconfig.enable_threaded_blas = params[:enable_threaded_blas] - push!(launched, wconfig) - end - - notify(c) -end - -function manage(manager::LocalManager, id::Integer, config::WorkerConfig, op::Symbol) - if op == :interrupt - kill(get(config.process), 2) - end -end - -""" - launch(manager::ClusterManager, params::Dict, launched::Array, launch_ntfy::Condition) - -Implemented by cluster managers. For every Julia worker launched by this function, it should -append a `WorkerConfig` entry to `launched` and notify `launch_ntfy`. The function MUST exit -once all workers, requested by `manager` have been launched. `params` is a dictionary of all -keyword arguments [`addprocs`](@ref) was called with. -""" -launch - -""" - manage(manager::ClusterManager, id::Integer, config::WorkerConfig. op::Symbol) - -Implemented by cluster managers. It is called on the master process, during a worker's -lifetime, with appropriate `op` values: - -- with `:register`/`:deregister` when a worker is added / removed from the Julia worker pool. -- with `:interrupt` when `interrupt(workers)` is called. The `ClusterManager` - should signal the appropriate worker with an interrupt signal. -- with `:finalize` for cleanup purposes. -""" -manage - -# DefaultClusterManager for the default TCP transport - used by both SSHManager and LocalManager - -struct DefaultClusterManager <: ClusterManager -end - -const tunnel_hosts_map = Dict{AbstractString, Semaphore}() - -""" - connect(manager::ClusterManager, pid::Int, config::WorkerConfig) -> (instrm::IO, outstrm::IO) - -Implemented by cluster managers using custom transports. It should establish a logical -connection to worker with id `pid`, specified by `config` and return a pair of `IO` -objects. Messages from `pid` to current process will be read off `instrm`, while messages to -be sent to `pid` will be written to `outstrm`. The custom transport implementation must -ensure that messages are delivered and received completely and in order. -`connect(manager::ClusterManager.....)` sets up TCP/IP socket connections in-between -workers. -""" -function connect(manager::ClusterManager, pid::Int, config::WorkerConfig) - if !isnull(config.connect_at) - # this is a worker-to-worker setup call. - return connect_w2w(pid, config) - end - - # master connecting to workers - if !isnull(config.io) - (bind_addr, port) = read_worker_host_port(get(config.io)) - pubhost=get(config.host, bind_addr) - config.host = pubhost - config.port = port - else - pubhost=get(config.host) - port=get(config.port) - bind_addr=get(config.bind_addr, pubhost) - end - - tunnel = get(config.tunnel, false) - - s = split(pubhost,'@') - user = "" - if length(s) > 1 - user = s[1] - pubhost = s[2] - else - if haskey(ENV, "USER") - user = ENV["USER"] - elseif tunnel - error("USER must be specified either in the environment ", - "or as part of the hostname when tunnel option is used") - end - end - - if tunnel - if !haskey(tunnel_hosts_map, pubhost) - tunnel_hosts_map[pubhost] = Semaphore(get(config.max_parallel, typemax(Int))) - end - sem = tunnel_hosts_map[pubhost] - - sshflags = get(config.sshflags) - acquire(sem) - try - (s, bind_addr) = connect_to_worker(pubhost, bind_addr, port, user, sshflags) - finally - release(sem) - end - else - (s, bind_addr) = connect_to_worker(bind_addr, port) - end - - config.bind_addr = bind_addr - - # write out a subset of the connect_at required for further worker-worker connection setups - config.connect_at = (bind_addr, port) - - if !isnull(config.io) - let pid = pid - redirect_worker_output(pid, get(config.io)) - end - end - - (s, s) -end - -function connect_w2w(pid::Int, config::WorkerConfig) - (rhost, rport) = get(config.connect_at) - config.host = rhost - config.port = rport - (s, bind_addr) = connect_to_worker(rhost, rport) - (s,s) -end - -const client_port = Ref{Cushort}(0) - -function socket_reuse_port() - @static if is_linux() || is_apple() - s = TCPSocket(delay = false) - - # Linux requires the port to be bound before setting REUSEPORT, OSX after. - is_linux() && bind_client_port(s) - rc = ccall(:jl_tcp_reuseport, Int32, (Ptr{Void},), s.handle) - if rc > 0 # SO_REUSEPORT is unsupported, just return the ephemerally bound socket - return s - elseif rc < 0 - # This is an issue only on systems with lots of client connections, hence delay the warning - nworkers() > 128 && warn_once("Error trying to reuse client port number, falling back to regular socket.") - - # provide a clean new socket - return TCPSocket() - end - is_apple() && bind_client_port(s) - return s - else - return TCPSocket() - end -end - -function bind_client_port(s) - err = ccall(:jl_tcp_bind, Int32, (Ptr{Void}, UInt16, UInt32, Cuint), - s.handle, hton(client_port[]), hton(UInt32(0)), 0) - uv_error("bind() failed", err) - - _addr, port = Base._sockname(s, true) - client_port[] = port - return s -end - -function connect_to_worker(host::AbstractString, port::Integer) - # Revert support for now. Client socket port number reuse - # does not play well in a scenario where worker processes are repeatedly - # created and torn down, i.e., when the new workers end up reusing a - # a previous listen port. - s = TCPSocket() - connect(s, host, UInt16(port)) - - # Avoid calling getaddrinfo if possible - involves a DNS lookup - # host may be a stringified ipv4 / ipv6 address or a dns name - bind_addr = nothing - try - bind_addr = string(parse(IPAddr,host)) - catch - bind_addr = string(getaddrinfo(host)) - end - (s, bind_addr) -end - - -function connect_to_worker(host::AbstractString, bind_addr::AbstractString, port::Integer, tunnel_user::AbstractString, sshflags) - s = connect("localhost", ssh_tunnel(tunnel_user, host, bind_addr, UInt16(port), sshflags)) - (s, bind_addr) -end - - -""" - kill(manager::ClusterManager, pid::Int, config::WorkerConfig) - -Implemented by cluster managers. -It is called on the master process, by [`rmprocs`](@ref). -It should cause the remote worker specified by `pid` to exit. -`kill(manager::ClusterManager.....)` executes a remote `exit()` -on `pid`. -""" -function kill(manager::ClusterManager, pid::Int, config::WorkerConfig) - remote_do(exit, pid) # For TCP based transports this will result in a close of the socket - # at our end, which will result in a cleanup of the worker. - nothing -end diff --git a/julia-0.6.3/share/julia/base/distributed/messages.jl b/julia-0.6.3/share/julia/base/distributed/messages.jl deleted file mode 100644 index 17a447a..0000000 --- a/julia-0.6.3/share/julia/base/distributed/messages.jl +++ /dev/null @@ -1,215 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -abstract type AbstractMsg end - -const REF_ID = Ref(1) -next_ref_id() = (id = REF_ID[]; REF_ID[] = id+1; id) - -struct RRID - whence::Int - id::Int - - RRID() = RRID(myid(),next_ref_id()) - RRID(whence, id) = new(whence,id) -end -hash(r::RRID, h::UInt) = hash(r.whence, hash(r.id, h)) -==(r::RRID, s::RRID) = (r.whence==s.whence && r.id==s.id) - -## Wire format description -# -# Each message has three parts, which are written in order to the worker's stream. -# 1) A header of type MsgHeader is serialized to the stream (via `serialize`). -# 2) A message of type AbstractMsg is then serialized. -# 3) Finally, a fixed bounday of 10 bytes is written. - -# Message header stored separately from body to be able to send back errors if -# a deserialization error occurs when reading the message body. -struct MsgHeader - response_oid::RRID - notify_oid::RRID - MsgHeader(respond_oid=RRID(0,0), notify_oid=RRID(0,0)) = - new(respond_oid, notify_oid) -end - -# Special oid (0,0) uses to indicate a null ID. -# Used instead of Nullable to decrease wire size of header. -null_id(id) = id == RRID(0, 0) - -struct CallMsg{Mode} <: AbstractMsg - f::Function - args::Tuple - kwargs::Array -end -struct CallWaitMsg <: AbstractMsg - f::Function - args::Tuple - kwargs::Array -end -struct RemoteDoMsg <: AbstractMsg - f::Function - args::Tuple - kwargs::Array -end -struct ResultMsg <: AbstractMsg - value::Any -end - - -# Worker initialization messages -struct IdentifySocketMsg <: AbstractMsg - from_pid::Int -end - -struct IdentifySocketAckMsg <: AbstractMsg -end - -struct JoinPGRPMsg <: AbstractMsg - self_pid::Int - other_workers::Array - topology::Symbol - enable_threaded_blas::Bool -end -struct JoinCompleteMsg <: AbstractMsg - cpu_cores::Int - ospid::Int -end - -# Avoiding serializing AbstractMsg containers results in a speedup -# of approximately 10%. Can be removed once module Serializer -# has been suitably improved. - -const msgtypes = Any[CallWaitMsg, IdentifySocketAckMsg, IdentifySocketMsg, - JoinCompleteMsg, JoinPGRPMsg, RemoteDoMsg, ResultMsg, - CallMsg{:call}, CallMsg{:call_fetch}] - -for (idx, tname) in enumerate(msgtypes) - exprs = Any[ :(serialize(s, o.$fld)) for fld in fieldnames(tname) ] - @eval function serialize_msg(s::AbstractSerializer, o::$tname) - write(s.io, UInt8($idx)) - $(exprs...) - return nothing - end -end - -let msg_cases = :(assert(false)) - for i = length(msgtypes):-1:1 - mti = msgtypes[i] - msg_cases = :(if idx == $i - return $(Expr(:call, QuoteNode(mti), fill(:(deserialize(s)), nfields(mti))...)) - else - $msg_cases - end) - end - @eval function deserialize_msg(s::AbstractSerializer) - idx = read(s.io, UInt8) - $msg_cases - end -end - -function send_msg_unknown(s::IO, header, msg) - error("attempt to send to unknown socket") -end - -function send_msg(s::IO, header, msg) - id = worker_id_from_socket(s) - if id > -1 - return send_msg(worker_from_id(id), header, msg) - end - send_msg_unknown(s, header, msg) -end - -function send_msg_now(s::IO, header, msg::AbstractMsg) - id = worker_id_from_socket(s) - if id > -1 - return send_msg_now(worker_from_id(id), header, msg) - end - send_msg_unknown(s, header, msg) -end -function send_msg_now(w::Worker, header, msg) - send_msg_(w, header, msg, true) -end - -function send_msg(w::Worker, header, msg) - send_msg_(w, header, msg, false) -end - -function flush_gc_msgs(w::Worker) - if !isdefined(w, :w_stream) - return - end - w.gcflag = false - new_array = Any[] - msgs = w.add_msgs - w.add_msgs = new_array - if !isempty(msgs) - remote_do(add_clients, w, msgs) - end - - # del_msgs gets populated by finalizers, so be very careful here about ordering of allocations - new_array = Any[] - msgs = w.del_msgs - w.del_msgs = new_array - if !isempty(msgs) - #print("sending delete of $msgs\n") - remote_do(del_clients, w, msgs) - end -end - -# Boundary inserted between messages on the wire, used for recovering -# from deserialization errors. Picked arbitrarily. -# A size of 10 bytes indicates ~ ~1e24 possible boundaries, so chance of collision -# with message contents is negligible. -const MSG_BOUNDARY = UInt8[0x79, 0x8e, 0x8e, 0xf5, 0x6e, 0x9b, 0x2e, 0x97, 0xd5, 0x7d] - -# Faster serialization/deserialization of MsgHeader and RRID -function serialize_hdr_raw(io, hdr) - write(io, hdr.response_oid.whence, hdr.response_oid.id, hdr.notify_oid.whence, hdr.notify_oid.id) -end - -function deserialize_hdr_raw(io) - data = read(io, Ref{NTuple{4,Int}}())[] - return MsgHeader(RRID(data[1], data[2]), RRID(data[3], data[4])) -end - -function send_msg_(w::Worker, header, msg, now::Bool) - check_worker_state(w) - io = w.w_stream - lock(io.lock) - try - reset_state(w.w_serializer) - serialize_hdr_raw(io, header) - invokelatest(serialize_msg, w.w_serializer, msg) # io is wrapped in w_serializer - write(io, MSG_BOUNDARY) - - if !now && w.gcflag - flush_gc_msgs(w) - else - flush(io) - end - finally - unlock(io.lock) - end -end - -function flush_gc_msgs() - try - for w in (PGRP::ProcessGroup).workers - if isa(w,Worker) && w.gcflag && (w.state == W_CONNECTED) - flush_gc_msgs(w) - end - end - catch e - bt = catch_backtrace() - @schedule showerror(STDERR, e, bt) - end -end - -function send_connection_hdr(w::Worker, cookie=true) - # For a connection initiated from the remote side to us, we only send the version, - # else when we initiate a connection we first send the cookie followed by our version. - # The remote side validates the cookie. - if cookie - write(w.w_stream, LPROC.cookie) - end - write(w.w_stream, rpad(VERSION_STRING, HDR_VERSION_LEN)[1:HDR_VERSION_LEN]) -end diff --git a/julia-0.6.3/share/julia/base/distributed/pmap.jl b/julia-0.6.3/share/julia/base/distributed/pmap.jl deleted file mode 100644 index 3cf4c89..0000000 --- a/julia-0.6.3/share/julia/base/distributed/pmap.jl +++ /dev/null @@ -1,295 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -mutable struct BatchProcessingError <: Exception - data - ex -end - -""" - pgenerate([::WorkerPool], f, c...) -> iterator - -Apply `f` to each element of `c` in parallel using available workers and tasks. - -For multiple collection arguments, apply `f` elementwise. - -Results are returned in order as they become available. - -Note that `f` must be made available to all worker processes; see -[Code Availability and Loading Packages](@ref) -for details. -""" -function pgenerate(p::WorkerPool, f, c) - if length(p) == 0 - return AsyncGenerator(f, c; ntasks=()->nworkers(p)) - end - batches = batchsplit(c, min_batch_count = length(p) * 3) - return Iterators.flatten(AsyncGenerator(remote(p, b -> asyncmap(f, b)), batches)) -end -pgenerate(p::WorkerPool, f, c1, c...) = pgenerate(p, a->f(a...), zip(c1, c...)) -pgenerate(f, c) = pgenerate(default_worker_pool(), f, c) -pgenerate(f, c1, c...) = pgenerate(a->f(a...), zip(c1, c...)) - -""" - pmap([::AbstractWorkerPool], f, c...; distributed=true, batch_size=1, on_error=nothing, retry_delays=[]), retry_check=nothing) -> collection - -Transform collection `c` by applying `f` to each element using available -workers and tasks. - -For multiple collection arguments, apply `f` elementwise. - -Note that `f` must be made available to all worker processes; see -[Code Availability and Loading Packages](@ref) for details. - -If a worker pool is not specified, all available workers, i.e., the default worker pool -is used. - -By default, `pmap` distributes the computation over all specified workers. To use only the -local process and distribute over tasks, specify `distributed=false`. -This is equivalent to using [`asyncmap`](@ref). For example, -`pmap(f, c; distributed=false)` is equivalent to `asyncmap(f,c; ntasks=()->nworkers())` - -`pmap` can also use a mix of processes and tasks via the `batch_size` argument. For batch sizes -greater than 1, the collection is processed in multiple batches, each of length `batch_size` or less. -A batch is sent as a single request to a free worker, where a local [`asyncmap`](@ref) processes -elements from the batch using multiple concurrent tasks. - -Any error stops `pmap` from processing the remainder of the collection. To override this behavior -you can specify an error handling function via argument `on_error` which takes in a single argument, i.e., -the exception. The function can stop the processing by rethrowing the error, or, to continue, return any value -which is then returned inline with the results to the caller. - -Consider the following two examples. The first one returns the exception object inline, -the second a 0 in place of any exception: -```julia-repl -julia> pmap(x->iseven(x) ? error("foo") : x, 1:4; on_error=identity) -4-element Array{Any,1}: - 1 - ErrorException("foo") - 3 - ErrorException("foo") - -julia> pmap(x->iseven(x) ? error("foo") : x, 1:4; on_error=ex->0) -4-element Array{Int64,1}: - 1 - 0 - 3 - 0 -``` - -Errors can also be handled by retrying failed computations. Keyword arguments `retry_delays` and -`retry_check` are passed through to [`retry`](@ref) as keyword arguments `delays` and `check` -respectively. If batching is specified, and an entire batch fails, all items in -the batch are retried. - -Note that if both `on_error` and `retry_delays` are specified, the `on_error` hook is called -before retrying. If `on_error` does not throw (or rethrow) an exception, the element will not -be retried. - -Example: On errors, retry `f` on an element a maximum of 3 times without any delay between retries. -```julia -pmap(f, c; retry_delays = zeros(3)) -``` - -Example: Retry `f` only if the exception is not of type `InexactError`, with exponentially increasing -delays up to 3 times. Return a `NaN` in place for all `InexactError` occurrences. -```julia -pmap(f, c; on_error = e->(isa(e, InexactError) ? NaN : rethrow(e)), retry_delays = ExponentialBackOff(n = 3)) -``` -""" -function pmap(p::AbstractWorkerPool, f, c; distributed=true, batch_size=1, on_error=nothing, - retry_delays=[], retry_check=nothing) - f_orig = f - # Don't do remote calls if there are no workers. - if (length(p) == 0) || (length(p) == 1 && fetch(p.channel) == myid()) - distributed = false - end - - # Don't do batching if not doing remote calls. - if !distributed - batch_size = 1 - end - - # If not batching, do simple remote call. - if batch_size == 1 - if on_error !== nothing - f = wrap_on_error(f, on_error) - end - - if distributed - f = remote(p, f) - end - - if length(retry_delays) > 0 - f = wrap_retry(f, retry_delays, retry_check) - end - - return asyncmap(f, c; ntasks=()->nworkers(p)) - else - # During batch processing, We need to ensure that if on_error is set, it is called - # for each element in error, and that we return as many elements as the original list. - # retry, if set, has to be called element wise and we will do a best-effort - # to ensure that we do not call mapped function on the same element more than length(retry_delays). - # This guarantee is not possible in case of worker death / network errors, wherein - # we will retry the entire batch on a new worker. - - handle_errors = ((on_error !== nothing) || (length(retry_delays) > 0)) - - # Unlike the non-batch case, in batch mode, we trap all errors and the on_error hook (if present) - # is processed later in non-batch mode. - if handle_errors - f = wrap_on_error(f, (x,e)->BatchProcessingError(x,e); capture_data=true) - end - - f = wrap_batch(f, p, handle_errors) - results = asyncmap(f, c; ntasks=()->nworkers(p), batch_size=batch_size) - - # process errors if any. - if handle_errors - process_batch_errors!(p, f_orig, results, on_error, retry_delays, retry_check) - end - - return results - end -end - -pmap(p::AbstractWorkerPool, f, c1, c...; kwargs...) = pmap(p, a->f(a...), zip(c1, c...); kwargs...) -pmap(f, c; kwargs...) = pmap(default_worker_pool(), f, c; kwargs...) -pmap(f, c1, c...; kwargs...) = pmap(a->f(a...), zip(c1, c...); kwargs...) - -function wrap_on_error(f, on_error; capture_data=false) - return x -> begin - try - f(x) - catch e - if capture_data - on_error(x, e) - else - on_error(e) - end - end - end -end - -function wrap_retry(f, retry_delays, retry_check) - retry(delays=retry_delays, check=retry_check) do x - try - f(x) - catch e - rethrow(extract_exception(e)) - end - end -end - -function wrap_batch(f, p, handle_errors) - f = asyncmap_batch(f) - return batch -> begin - try - remotecall_fetch(f, p, batch) - catch e - if handle_errors - return Any[BatchProcessingError(batch[i], e) for i in 1:length(batch)] - else - rethrow(e) - end - end - end -end - -asyncmap_batch(f) = batch -> asyncmap(x->f(x...), batch) -extract_exception(e) = isa(e, RemoteException) ? e.captured.ex : e - - -function process_batch_errors!(p, f, results, on_error, retry_delays, retry_check) - # Handle all the ones in error in another pmap, with batch size set to 1 - reprocess = [] - for (idx, v) in enumerate(results) - if isa(v, BatchProcessingError) - push!(reprocess, (idx,v)) - end - end - - if length(reprocess) > 0 - errors = [x[2] for x in reprocess] - exceptions = [x.ex for x in errors] - state = start(retry_delays) - if (length(retry_delays) > 0) && - (retry_check==nothing || all([retry_check(state,ex)[2] for ex in exceptions])) - # BatchProcessingError.data is a tuple of original args - error_processed = pmap(p, x->f(x...), [x.data for x in errors]; - on_error = on_error, retry_delays = collect(retry_delays)[2:end], retry_check = retry_check) - elseif on_error !== nothing - error_processed = map(on_error, exceptions) - else - throw(CompositeException(exceptions)) - end - - for (idx, v) in enumerate(error_processed) - results[reprocess[idx][1]] = v - end - end - nothing -end - -""" - head_and_tail(c, n) -> head, tail - -Returns `head`: the first `n` elements of `c`; -and `tail`: an iterator over the remaining elements. - -```jldoctest -julia> a = 1:10 -1:10 - -julia> b, c = Base.head_and_tail(a, 3) -([1,2,3],Base.Iterators.Rest{UnitRange{Int64},Int64}(1:10,4)) - -julia> collect(c) -7-element Array{Any,1}: - 4 - 5 - 6 - 7 - 8 - 9 - 10 -``` -""" -function head_and_tail(c, n) - head = Vector{eltype(c)}(n) - s = start(c) - i = 0 - while i < n && !done(c, s) - i += 1 - head[i], s = next(c, s) - end - return resize!(head, i), Iterators.rest(c, s) -end - -""" - batchsplit(c; min_batch_count=1, max_batch_size=100) -> iterator - -Split a collection into at least `min_batch_count` batches. - -Equivalent to `partition(c, max_batch_size)` when `length(c) >> max_batch_size`. -""" -function batchsplit(c; min_batch_count=1, max_batch_size=100) - if min_batch_count < 1 - throw(ArgumentError("min_batch_count must be ≥ 1, got $min_batch_count")) - end - - if max_batch_size < 1 - throw(ArgumentError("max_batch_size must be ≥ 1, got $max_batch_size")) - end - - # Split collection into batches, then peek at the first few batches - batches = Iterators.partition(c, max_batch_size) - head, tail = head_and_tail(batches, min_batch_count) - - # If there are not enough batches, use a smaller batch size - if length(head) < min_batch_count - batch_size = max(1, div(sum(length, head), min_batch_count)) - return Iterators.partition(collect(Iterators.flatten(head)), batch_size) - end - - return Iterators.flatten((head, tail)) -end diff --git a/julia-0.6.3/share/julia/base/distributed/process_messages.jl b/julia-0.6.3/share/julia/base/distributed/process_messages.jl deleted file mode 100644 index 1eba6ea..0000000 --- a/julia-0.6.3/share/julia/base/distributed/process_messages.jl +++ /dev/null @@ -1,353 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -# data stored by the owner of a remote reference -def_rv_channel() = Channel(1) -mutable struct RemoteValue - c::AbstractChannel - clientset::IntSet # Set of workerids that have a reference to this channel. - # Keeping ids instead of a count aids in cleaning up upon - # a worker exit. - - waitingfor::Int # processor we need to hear from to fill this, or 0 - - RemoteValue(c) = new(c, IntSet(), 0) -end - -wait(rv::RemoteValue) = wait(rv.c) - -## core messages: do, call, fetch, wait, ref, put! ## -mutable struct RemoteException <: Exception - pid::Int - captured::CapturedException -end - -""" - RemoteException(captured) - -Exceptions on remote computations are captured and rethrown locally. A `RemoteException` -wraps the `pid` of the worker and a captured exception. A `CapturedException` captures the -remote exception and a serializable form of the call stack when the exception was raised. -""" -RemoteException(captured) = RemoteException(myid(), captured) -function showerror(io::IO, re::RemoteException) - (re.pid != myid()) && print(io, "On worker ", re.pid, ":\n") - showerror(io, get_root_exception(re.captured)) -end - -isa_exception_container(ex) = (isa(ex, RemoteException) || - isa(ex, CapturedException) || - isa(ex, CompositeException)) - -function get_root_exception(ex) - if isa(ex, RemoteException) - return get_root_exception(ex.captured) - elseif isa(ex, CapturedException) && isa_exception_container(ex.ex) - return get_root_exception(ex.ex) - elseif isa(ex, CompositeException) && length(ex.exceptions) > 0 && isa_exception_container(ex.exceptions[1]) - return get_root_exception(ex.exceptions[1]) - else - return ex - end -end - -function run_work_thunk(thunk, print_error) - local result - try - result = thunk() - catch err - ce = CapturedException(err, catch_backtrace()) - result = RemoteException(ce) - print_error && showerror(STDERR, ce) - end - return result -end -function run_work_thunk(rv::RemoteValue, thunk) - put!(rv, run_work_thunk(thunk, false)) - nothing -end - -function schedule_call(rid, thunk) - return lock(client_refs) do - rv = RemoteValue(def_rv_channel()) - (PGRP::ProcessGroup).refs[rid] = rv - push!(rv.clientset, rid.whence) - @schedule run_work_thunk(rv, thunk) - return rv - end -end - - -function deliver_result(sock::IO, msg, oid, value) - #print("$(myid()) sending result $oid\n") - if msg === :call_fetch || isa(value, RemoteException) - val = value - else - val = :OK - end - try - send_msg_now(sock, MsgHeader(oid), ResultMsg(val)) - catch e - # terminate connection in case of serialization error - # otherwise the reading end would hang - print(STDERR, "fatal error on ", myid(), ": ") - display_error(e, catch_backtrace()) - wid = worker_id_from_socket(sock) - close(sock) - if myid()==1 - rmprocs(wid) - elseif wid == 1 - exit(1) - else - remote_do(rmprocs, 1, wid) - end - end -end - -## message event handlers ## -function process_messages(r_stream::TCPSocket, w_stream::TCPSocket, incoming::Bool=true) - @schedule process_tcp_streams(r_stream, w_stream, incoming) -end - -function process_tcp_streams(r_stream::TCPSocket, w_stream::TCPSocket, incoming::Bool) - disable_nagle(r_stream) - wait_connected(r_stream) - if r_stream != w_stream - disable_nagle(w_stream) - wait_connected(w_stream) - end - message_handler_loop(r_stream, w_stream, incoming) -end - -""" - Base.process_messages(r_stream::IO, w_stream::IO, incoming::Bool=true) - -Called by cluster managers using custom transports. It should be called when the custom -transport implementation receives the first message from a remote worker. The custom -transport must manage a logical connection to the remote worker and provide two -`IO` objects, one for incoming messages and the other for messages addressed to the -remote worker. -If `incoming` is `true`, the remote peer initiated the connection. -Whichever of the pair initiates the connection sends the cluster cookie and its -Julia version number to perform the authentication handshake. - -See also [`cluster_cookie`](@ref). -""" -function process_messages(r_stream::IO, w_stream::IO, incoming::Bool=true) - @schedule message_handler_loop(r_stream, w_stream, incoming) -end - -function message_handler_loop(r_stream::IO, w_stream::IO, incoming::Bool) - wpid=0 # the worker r_stream is connected to. - boundary = similar(MSG_BOUNDARY) - try - version = process_hdr(r_stream, incoming) - serializer = ClusterSerializer(r_stream) - - # The first message will associate wpid with r_stream - header = deserialize_hdr_raw(r_stream) - msg = deserialize_msg(serializer) - handle_msg(msg, header, r_stream, w_stream, version) - wpid = worker_id_from_socket(r_stream) - @assert wpid > 0 - - readbytes!(r_stream, boundary, length(MSG_BOUNDARY)) - - while true - reset_state(serializer) - header = deserialize_hdr_raw(r_stream) - # println("header: ", header) - - try - msg = invokelatest(deserialize_msg, serializer) - catch e - # Deserialization error; discard bytes in stream until boundary found - boundary_idx = 1 - while true - # This may throw an EOF error if the terminal boundary was not written - # correctly, triggering the higher-scoped catch block below - byte = read(r_stream, UInt8) - if byte == MSG_BOUNDARY[boundary_idx] - boundary_idx += 1 - if boundary_idx > length(MSG_BOUNDARY) - break - end - else - boundary_idx = 1 - end - end - - # remotecalls only rethrow RemoteExceptions. Any other exception is treated as - # data to be returned. Wrap this exception in a RemoteException. - remote_err = RemoteException(myid(), CapturedException(e, catch_backtrace())) - # println("Deserialization error. ", remote_err) - if !null_id(header.response_oid) - ref = lookup_ref(header.response_oid) - put!(ref, remote_err) - end - if !null_id(header.notify_oid) - deliver_result(w_stream, :call_fetch, header.notify_oid, remote_err) - end - continue - end - readbytes!(r_stream, boundary, length(MSG_BOUNDARY)) - - # println("got msg: ", typeof(msg)) - handle_msg(msg, header, r_stream, w_stream, version) - end - catch e - # Check again as it may have been set in a message handler but not propagated to the calling block above - wpid = worker_id_from_socket(r_stream) - if (wpid < 1) - println(STDERR, e, CapturedException(e, catch_backtrace())) - println(STDERR, "Process($(myid())) - Unknown remote, closing connection.") - else - werr = worker_from_id(wpid) - oldstate = werr.state - set_worker_state(werr, W_TERMINATED) - - # If unhandleable error occurred talking to pid 1, exit - if wpid == 1 - if isopen(w_stream) - print(STDERR, "fatal error on ", myid(), ": ") - display_error(e, catch_backtrace()) - end - exit(1) - end - - # Will treat any exception as death of node and cleanup - # since currently we do not have a mechanism for workers to reconnect - # to each other on unhandled errors - deregister_worker(wpid) - end - - isopen(r_stream) && close(r_stream) - isopen(w_stream) && close(w_stream) - - if (myid() == 1) && (wpid > 1) - if oldstate != W_TERMINATING - println(STDERR, "Worker $wpid terminated.") - rethrow(e) - end - end - - return nothing - end -end - -function process_hdr(s, validate_cookie) - if validate_cookie - cookie = read(s, HDR_COOKIE_LEN) - if length(cookie) < HDR_COOKIE_LEN - error("Cookie read failed. Connection closed by peer.") - end - - self_cookie = cluster_cookie() - for i in 1:HDR_COOKIE_LEN - if UInt8(self_cookie[i]) != cookie[i] - error("Process($(myid())) - Invalid connection credentials sent by remote.") - end - end - end - - # When we have incompatible julia versions trying to connect to each other, - # and can be detected, raise an appropriate error. - # For now, just return the version. - version = read(s, HDR_VERSION_LEN) - if length(version) < HDR_VERSION_LEN - error("Version read failed. Connection closed by peer.") - end - - return VersionNumber(strip(String(version))) -end - -function handle_msg(msg::CallMsg{:call}, header, r_stream, w_stream, version) - schedule_call(header.response_oid, ()->msg.f(msg.args...; msg.kwargs...)) -end -function handle_msg(msg::CallMsg{:call_fetch}, header, r_stream, w_stream, version) - @schedule begin - v = run_work_thunk(()->msg.f(msg.args...; msg.kwargs...), false) - deliver_result(w_stream, :call_fetch, header.notify_oid, v) - end -end - -function handle_msg(msg::CallWaitMsg, header, r_stream, w_stream, version) - @schedule begin - rv = schedule_call(header.response_oid, ()->msg.f(msg.args...; msg.kwargs...)) - deliver_result(w_stream, :call_wait, header.notify_oid, fetch(rv.c)) - end -end - -function handle_msg(msg::RemoteDoMsg, header, r_stream, w_stream, version) - @schedule run_work_thunk(()->msg.f(msg.args...; msg.kwargs...), true) -end - -function handle_msg(msg::ResultMsg, header, r_stream, w_stream, version) - put!(lookup_ref(header.response_oid), msg.value) -end - -function handle_msg(msg::IdentifySocketMsg, header, r_stream, w_stream, version) - # register a new peer worker connection - w=Worker(msg.from_pid, r_stream, w_stream, cluster_manager; version=version) - send_connection_hdr(w, false) - send_msg_now(w, MsgHeader(), IdentifySocketAckMsg()) -end - -function handle_msg(msg::IdentifySocketAckMsg, header, r_stream, w_stream, version) - w = map_sock_wrkr[r_stream] - w.version = version -end - -function handle_msg(msg::JoinPGRPMsg, header, r_stream, w_stream, version) - LPROC.id = msg.self_pid - controller = Worker(1, r_stream, w_stream, cluster_manager; version=version) - register_worker(LPROC) - topology(msg.topology) - - if !msg.enable_threaded_blas - disable_threaded_libs() - end - - wait_tasks = Task[] - for (connect_at, rpid) in msg.other_workers - wconfig = WorkerConfig() - wconfig.connect_at = connect_at - - let rpid=rpid, wconfig=wconfig - t = @async connect_to_peer(cluster_manager, rpid, wconfig) - push!(wait_tasks, t) - end - end - - for wt in wait_tasks; wait(wt); end - - send_connection_hdr(controller, false) - send_msg_now(controller, MsgHeader(RRID(0,0), header.notify_oid), JoinCompleteMsg(Sys.CPU_CORES, getpid())) -end - -function connect_to_peer(manager::ClusterManager, rpid::Int, wconfig::WorkerConfig) - try - (r_s, w_s) = connect(manager, rpid, wconfig) - w = Worker(rpid, r_s, w_s, manager; config=wconfig) - process_messages(w.r_stream, w.w_stream, false) - send_connection_hdr(w, true) - send_msg_now(w, MsgHeader(), IdentifySocketMsg(myid())) - catch e - display_error(e, catch_backtrace()) - println(STDERR, "Error [$e] on $(myid()) while connecting to peer $rpid. Exiting.") - exit(1) - end -end - -function handle_msg(msg::JoinCompleteMsg, header, r_stream, w_stream, version) - w = map_sock_wrkr[r_stream] - environ = get(w.config.environ, Dict()) - environ[:cpu_cores] = msg.cpu_cores - w.config.environ = environ - w.config.ospid = msg.ospid - w.version = version - - ntfy_channel = lookup_ref(header.notify_oid) - put!(ntfy_channel, w.id) - - push!(default_worker_pool(), w.id) -end diff --git a/julia-0.6.3/share/julia/base/distributed/remotecall.jl b/julia-0.6.3/share/julia/base/distributed/remotecall.jl deleted file mode 100644 index 9c257cd..0000000 --- a/julia-0.6.3/share/julia/base/distributed/remotecall.jl +++ /dev/null @@ -1,559 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -""" - client_refs - -Tracks whether a particular `AbstractRemoteRef` -(identified by its RRID) exists on this worker. - -The `client_refs` lock is also used to synchronize access to `.refs` and associated `clientset` state. -""" -const client_refs = WeakKeyDict{Any, Void}() # used as a WeakKeySet - -abstract type AbstractRemoteRef end - -mutable struct Future <: AbstractRemoteRef - where::Int - whence::Int - id::Int - v::Nullable{Any} - - Future(w::Int, rrid::RRID) = Future(w, rrid, Nullable{Any}()) - Future(w::Int, rrid::RRID, v) = (r = new(w,rrid.whence,rrid.id,v); return test_existing_ref(r)) -end - -mutable struct RemoteChannel{T<:AbstractChannel} <: AbstractRemoteRef - where::Int - whence::Int - id::Int - - function RemoteChannel{T}(w::Int, rrid::RRID) where T<:AbstractChannel - r = new(w, rrid.whence, rrid.id) - return test_existing_ref(r) - end -end - -function test_existing_ref(r::AbstractRemoteRef) - found = getkey(client_refs, r, nothing) - if found !== nothing - @assert r.where > 0 - if isa(r, Future) && isnull(found.v) && !isnull(r.v) - # we have recd the value from another source, probably a deserialized ref, send a del_client message - send_del_client(r) - found.v = r.v - end - return found::typeof(r) - end - - client_refs[r] = nothing - finalizer(r, finalize_ref) - return r -end - -function finalize_ref(r::AbstractRemoteRef) - if r.where > 0 # Handle the case of the finalizer having been called manually - islocked(client_refs) && return finalizer(r, finalize_ref) # delay finalizer for later, when it's not already locked - delete!(client_refs, r) - if isa(r, RemoteChannel) - send_del_client(r) - else - # send_del_client only if the reference has not been set - isnull(r.v) && send_del_client(r) - r.v = Nullable{Any}() - end - r.where = 0 - end - nothing -end - -Future(w::LocalProcess) = Future(w.id) -Future(w::Worker) = Future(w.id) - -""" - Future(pid::Integer=myid()) - -Create a `Future` on process `pid`. -The default `pid` is the current process. -""" -Future(pid::Integer=myid()) = Future(pid, RRID()) - -""" - RemoteChannel(pid::Integer=myid()) - -Make a reference to a `Channel{Any}(1)` on process `pid`. -The default `pid` is the current process. -""" -RemoteChannel(pid::Integer=myid()) = RemoteChannel{Channel{Any}}(pid, RRID()) - -""" - RemoteChannel(f::Function, pid::Integer=myid()) - -Create references to remote channels of a specific size and type. `f()` is a function that -when executed on `pid` must return an implementation of an `AbstractChannel`. - -For example, `RemoteChannel(()->Channel{Int}(10), pid)`, will return a reference to a -channel of type `Int` and size 10 on `pid`. - -The default `pid` is the current process. -""" -function RemoteChannel(f::Function, pid::Integer=myid()) - remotecall_fetch(pid, f, RRID()) do f, rrid - rv=lookup_ref(rrid, f) - RemoteChannel{typeof(rv.c)}(myid(), rrid) - end -end - -hash(r::AbstractRemoteRef, h::UInt) = hash(r.whence, hash(r.id, h)) -==(r::AbstractRemoteRef, s::AbstractRemoteRef) = (r.whence==s.whence && r.id==s.id) - -""" - Base.remoteref_id(r::AbstractRemoteRef) -> RRID - -`Future`s and `RemoteChannel`s are identified by fields: - -* `where` - refers to the node where the underlying object/storage - referred to by the reference actually exists. - -* `whence` - refers to the node the remote reference was created from. - Note that this is different from the node where the underlying object - referred to actually exists. For example calling `RemoteChannel(2)` - from the master process would result in a `where` value of 2 and - a `whence` value of 1. - -* `id` is unique across all references created from the worker specified by `whence`. - -Taken together, `whence` and `id` uniquely identify a reference across all workers. - -`Base.remoteref_id` is a low-level API which returns a `Base.RRID` -object that wraps `whence` and `id` values of a remote reference. -""" -remoteref_id(r::AbstractRemoteRef) = RRID(r.whence, r.id) - -""" - Base.channel_from_id(id) -> c - -A low-level API which returns the backing `AbstractChannel` for an `id` returned by -[`remoteref_id`](@ref). -The call is valid only on the node where the backing channel exists. -""" -function channel_from_id(id) - rv = lock(client_refs) do - return get(PGRP.refs, id, false) - end - if rv === false - throw(ErrorException("Local instance of remote reference not found")) - end - return rv.c -end - -lookup_ref(rrid::RRID, f=def_rv_channel) = lookup_ref(PGRP, rrid, f) -function lookup_ref(pg, rrid, f) - return lock(client_refs) do - rv = get(pg.refs, rrid, false) - if rv === false - # first we've heard of this ref - rv = RemoteValue(invokelatest(f)) - pg.refs[rrid] = rv - push!(rv.clientset, rrid.whence) - end - return rv - end::RemoteValue -end - -""" - isready(rr::Future) - -Determine whether a [`Future`](@ref) has a value stored to it. - -If the argument `Future` is owned by a different node, this call will block to wait for the answer. -It is recommended to wait for `rr` in a separate task instead -or to use a local [`Channel`](@ref) as a proxy: - - c = Channel(1) - @async put!(c, remotecall_fetch(long_computation, p)) - isready(c) # will not block -""" -function isready(rr::Future) - !isnull(rr.v) && return true - - rid = remoteref_id(rr) - return if rr.where == myid() - isready(lookup_ref(rid).c) - else - remotecall_fetch(rid->isready(lookup_ref(rid).c), rr.where, rid) - end -end - -""" - isready(rr::RemoteChannel, args...) - -Determine whether a [`RemoteChannel`](@ref) has a value stored to it. -Note that this function can cause race conditions, since by the -time you receive its result it may no longer be true. However, -it can be safely used on a [`Future`](@ref) since they are assigned only once. -""" -function isready(rr::RemoteChannel, args...) - rid = remoteref_id(rr) - return if rr.where == myid() - isready(lookup_ref(rid).c, args...) - else - remotecall_fetch(rid->isready(lookup_ref(rid).c, args...), rr.where, rid) - end -end - -del_client(rr::AbstractRemoteRef) = del_client(remoteref_id(rr), myid()) - -del_client(id, client) = del_client(PGRP, id, client) -function del_client(pg, id, client) - lock(client_refs) do - rv = get(pg.refs, id, false) - if rv !== false - delete!(rv.clientset, client) - if isempty(rv.clientset) - delete!(pg.refs, id) - #print("$(myid()) collected $id\n") - end - end - end - nothing -end - -function del_clients(pairs::Vector) - for p in pairs - del_client(p[1], p[2]) - end -end - -any_gc_flag = Condition() -function start_gc_msgs_task() - @schedule while true - wait(any_gc_flag) - flush_gc_msgs() - end -end - -function send_del_client(rr) - if rr.where == myid() - del_client(rr) - elseif id_in_procs(rr.where) # process only if a valid worker - w = worker_from_id(rr.where) - push!(w.del_msgs, (remoteref_id(rr), myid())) - w.gcflag = true - notify(any_gc_flag) - end -end - -function add_client(id, client) - lock(client_refs) do - rv = lookup_ref(id) - push!(rv.clientset, client) - end - nothing -end - -function add_clients(pairs::Vector) - for p in pairs - add_client(p[1], p[2]...) - end -end - -function send_add_client(rr::AbstractRemoteRef, i) - if rr.where == myid() - add_client(remoteref_id(rr), i) - elseif (i != rr.where) && id_in_procs(rr.where) - # don't need to send add_client if the message is already going - # to the processor that owns the remote ref. it will add_client - # itself inside deserialize(). - w = worker_from_id(rr.where) - push!(w.add_msgs, (remoteref_id(rr), i)) - w.gcflag = true - notify(any_gc_flag) - end -end - -channel_type{T}(rr::RemoteChannel{T}) = T - -serialize(s::AbstractSerializer, f::Future) = serialize(s, f, isnull(f.v)) -serialize(s::AbstractSerializer, rr::RemoteChannel) = serialize(s, rr, true) -function serialize(s::AbstractSerializer, rr::AbstractRemoteRef, addclient) - if addclient - p = worker_id_from_socket(s.io) - (p !== rr.where) && send_add_client(rr, p) - end - invoke(serialize, Tuple{AbstractSerializer, Any}, s, rr) -end - -function deserialize(s::ClusterSerializer, t::Type{<:Future}) - f = invoke(deserialize, Tuple{ClusterSerializer, DataType}, s, t) - f2 = Future(f.where, RRID(f.whence, f.id), f.v) # ctor adds to client_refs table - - # 1) send_add_client() is not executed when the ref is being serialized - # to where it exists, hence do it here. - # 2) If we have recieved a 'fetch'ed Future or if the Future ctor found an - # already 'fetch'ed instance in client_refs (Issue #25847), we should not - # track it in the backing RemoteValue store. - if f2.where == myid() && f2.v === nothing - add_client(remoteref_id(f2), myid()) - end - f2 -end - -function deserialize(s::ClusterSerializer, t::Type{<:RemoteChannel}) - rr = invoke(deserialize, Tuple{ClusterSerializer, DataType}, s, t) - if rr.where == myid() - # send_add_client() is not executed when the ref is being - # serialized to where it exists - add_client(remoteref_id(rr), myid()) - end - # call ctor to make sure this rr gets added to the client_refs table - RemoteChannel{channel_type(rr)}(rr.where, RRID(rr.whence, rr.id)) -end - - -# make a thunk to call f on args in a way that simulates what would happen if -# the function were sent elsewhere -function local_remotecall_thunk(f, args, kwargs) - if isempty(args) && isempty(kwargs) - return f - end - return ()->f(args...; kwargs...) -end - -function remotecall(f, w::LocalProcess, args...; kwargs...) - rr = Future(w) - schedule_call(remoteref_id(rr), local_remotecall_thunk(f, args, kwargs)) - return rr -end - -function remotecall(f, w::Worker, args...; kwargs...) - rr = Future(w) - send_msg(w, MsgHeader(remoteref_id(rr)), CallMsg{:call}(f, args, kwargs)) - return rr -end - -""" - remotecall(f, id::Integer, args...; kwargs...) -> Future - -Call a function `f` asynchronously on the given arguments on the specified process. -Returns a [`Future`](@ref). -Keyword arguments, if any, are passed through to `f`. -""" -remotecall(f, id::Integer, args...; kwargs...) = remotecall(f, worker_from_id(id), args...; kwargs...) - -function remotecall_fetch(f, w::LocalProcess, args...; kwargs...) - v=run_work_thunk(local_remotecall_thunk(f,args, kwargs), false) - return isa(v, RemoteException) ? throw(v) : v -end - -function remotecall_fetch(f, w::Worker, args...; kwargs...) - # can be weak, because the program will have no way to refer to the Ref - # itself, it only gets the result. - oid = RRID() - rv = lookup_ref(oid) - rv.waitingfor = w.id - send_msg(w, MsgHeader(RRID(0,0), oid), CallMsg{:call_fetch}(f, args, kwargs)) - v = take!(rv) - lock(client_refs) do - delete!(PGRP.refs, oid) - end - return isa(v, RemoteException) ? throw(v) : v -end - -""" - remotecall_fetch(f, id::Integer, args...; kwargs...) - -Perform `fetch(remotecall(...))` in one message. -Keyword arguments, if any, are passed through to `f`. -Any remote exceptions are captured in a -[`RemoteException`](@ref) and thrown. - -See also [`fetch`](@ref) and [`remotecall`](@ref). -""" -remotecall_fetch(f, id::Integer, args...; kwargs...) = - remotecall_fetch(f, worker_from_id(id), args...; kwargs...) - -remotecall_wait(f, w::LocalProcess, args...; kwargs...) = wait(remotecall(f, w, args...; kwargs...)) - -function remotecall_wait(f, w::Worker, args...; kwargs...) - prid = RRID() - rv = lookup_ref(prid) - rv.waitingfor = w.id - rr = Future(w) - send_msg(w, MsgHeader(remoteref_id(rr), prid), CallWaitMsg(f, args, kwargs)) - v = fetch(rv.c) - lock(client_refs) do - delete!(PGRP.refs, prid) - end - isa(v, RemoteException) && throw(v) - return rr -end - -""" - remotecall_wait(f, id::Integer, args...; kwargs...) - -Perform a faster `wait(remotecall(...))` in one message on the `Worker` specified by worker id `id`. -Keyword arguments, if any, are passed through to `f`. - -See also [`wait`](@ref) and [`remotecall`](@ref). -""" -remotecall_wait(f, id::Integer, args...; kwargs...) = - remotecall_wait(f, worker_from_id(id), args...; kwargs...) - -function remote_do(f, w::LocalProcess, args...; kwargs...) - # the LocalProcess version just performs in local memory what a worker - # does when it gets a :do message. - # same for other messages on LocalProcess. - thk = local_remotecall_thunk(f, args, kwargs) - schedule(Task(thk)) - nothing -end - -function remote_do(f, w::Worker, args...; kwargs...) - send_msg(w, MsgHeader(), RemoteDoMsg(f, args, kwargs)) - nothing -end - - -""" - remote_do(f, id::Integer, args...; kwargs...) -> nothing - -Executes `f` on worker `id` asynchronously. -Unlike [`remotecall`](@ref), it does not store the -result of computation, nor is there a way to wait for its completion. - -A successful invocation indicates that the request has been accepted for execution on -the remote node. - -While consecutive `remotecall`s to the same worker are serialized in the order they are -invoked, the order of executions on the remote worker is undetermined. For example, -`remote_do(f1, 2); remotecall(f2, 2); remote_do(f3, 2)` will serialize the call -to `f1`, followed by `f2` and `f3` in that order. However, it is not guaranteed that `f1` -is executed before `f3` on worker 2. - -Any exceptions thrown by `f` are printed to [`STDERR`](@ref) on the remote worker. - -Keyword arguments, if any, are passed through to `f`. -""" -remote_do(f, id::Integer, args...; kwargs...) = remote_do(f, worker_from_id(id), args...; kwargs...) - -# have the owner of rr call f on it -function call_on_owner(f, rr::AbstractRemoteRef, args...) - rid = remoteref_id(rr) - if rr.where == myid() - f(rid, args...) - else - remotecall_fetch(f, rr.where, rid, args...) - end -end - -function wait_ref(rid, callee, args...) - v = fetch_ref(rid, args...) - if isa(v, RemoteException) - if myid() == callee - throw(v) - else - return v - end - end - nothing -end -wait(r::Future) = (!isnull(r.v) && return r; call_on_owner(wait_ref, r, myid()); r) -wait(r::RemoteChannel, args...) = (call_on_owner(wait_ref, r, myid(), args...); r) - -function fetch(r::Future) - !isnull(r.v) && return get(r.v) - v=call_on_owner(fetch_ref, r) - r.v=v - send_del_client(r) - v -end - -fetch_ref(rid, args...) = fetch(lookup_ref(rid).c, args...) -fetch(r::RemoteChannel, args...) = call_on_owner(fetch_ref, r, args...) - -""" - fetch(x) - -Waits and fetches a value from `x` depending on the type of `x`: - -* [`Future`](@ref): Wait for and get the value of a `Future`. The fetched value is cached locally. - Further calls to `fetch` on the same reference return the cached value. If the remote value - is an exception, throws a [`RemoteException`](@ref) which captures the remote exception and backtrace. -* [`RemoteChannel`](@ref): Wait for and get the value of a remote reference. Exceptions raised are - same as for a `Future` . - -Does not remove the item fetched. -""" -fetch(x::ANY) = x - -isready(rv::RemoteValue, args...) = isready(rv.c, args...) - -""" - put!(rr::Future, v) - -Store a value to a [`Future`](@ref) `rr`. -`Future`s are write-once remote references. -A `put!` on an already set `Future` throws an `Exception`. -All asynchronous remote calls return `Future`s and set the -value to the return value of the call upon completion. -""" -function put!(rr::Future, v) - !isnull(rr.v) && error("Future can be set only once") - call_on_owner(put_future, rr, v, myid()) - rr.v = v - rr -end -function put_future(rid, v, callee) - rv = lookup_ref(rid) - isready(rv) && error("Future can be set only once") - put!(rv, v) - # The callee has the value and hence can be removed from the remote store. - del_client(rid, callee) - nothing -end - - -put!(rv::RemoteValue, args...) = put!(rv.c, args...) -put_ref(rid, args...) = (put!(lookup_ref(rid), args...); nothing) - -""" - put!(rr::RemoteChannel, args...) - -Store a set of values to the [`RemoteChannel`](@ref). -If the channel is full, blocks until space is available. -Returns its first argument. -""" -put!(rr::RemoteChannel, args...) = (call_on_owner(put_ref, rr, args...); rr) - -# take! is not supported on Future - -take!(rv::RemoteValue, args...) = take!(rv.c, args...) -function take_ref(rid, callee, args...) - v=take!(lookup_ref(rid), args...) - isa(v, RemoteException) && (myid() == callee) && throw(v) - v -end - -""" - take!(rr::RemoteChannel, args...) - -Fetch value(s) from a [`RemoteChannel`](@ref) `rr`, -removing the value(s) in the processs. -""" -take!(rr::RemoteChannel, args...) = call_on_owner(take_ref, rr, myid(), args...) - -# close is not supported on Future - -close_ref(rid) = (close(lookup_ref(rid).c); nothing) -close(rr::RemoteChannel) = call_on_owner(close_ref, rr) - -getindex(r::RemoteChannel) = fetch(r) -getindex(r::Future) = fetch(r) - -getindex(r::Future, args...) = getindex(fetch(r), args...) -function getindex(r::RemoteChannel, args...) - if r.where == myid() - return getindex(fetch(r), args...) - end - return remotecall_fetch(getindex, r.where, r, args...) -end diff --git a/julia-0.6.3/share/julia/base/distributed/workerpool.jl b/julia-0.6.3/share/julia/base/distributed/workerpool.jl deleted file mode 100644 index 07d0831..0000000 --- a/julia-0.6.3/share/julia/base/distributed/workerpool.jl +++ /dev/null @@ -1,297 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -abstract type AbstractWorkerPool end - -# An AbstractWorkerPool should implement -# -# `push!` - add a new worker to the overall pool (available + busy) -# `put!` - put back a worker to the available pool -# `take!` - take a worker from the available pool (to be used for remote function execution) -# `length` - number of workers available in the overall pool -# `isready` - return false if a `take!` on the pool would block, else true -# -# The default implementations of the above (on a AbstractWorkerPool) require fields -# channel::Channel{Int} -# workers::Set{Int} -# - -mutable struct WorkerPool <: AbstractWorkerPool - channel::Channel{Int} - workers::Set{Int} - ref::RemoteChannel - - WorkerPool(c::Channel, ref::RemoteChannel) = new(c, Set{Int}(), ref) -end - -function WorkerPool() - wp = WorkerPool(Channel{Int}(typemax(Int)), RemoteChannel()) - put!(wp.ref, WeakRef(wp)) - wp -end - -""" - WorkerPool(workers::Vector{Int}) - -Create a WorkerPool from a vector of worker ids. -""" -function WorkerPool(workers::Vector{Int}) - pool = WorkerPool() - foreach(w->push!(pool, w), workers) - return pool -end - -# On workers where this pool has been serialized to, instantiate with a dummy local channel. -WorkerPool(ref::RemoteChannel) = WorkerPool(Channel{Int}(1), ref) - -function serialize(S::AbstractSerializer, pool::WorkerPool) - # Allow accessing a worker pool from other processors. When serialized, - # initialize the `ref` to point to self and only send the ref. - # Other workers will forward all put!, take!, calls to the process owning - # the ref (and hence the pool). - Serializer.serialize_type(S, typeof(pool)) - serialize(S, pool.ref) -end - -deserialize{T<:WorkerPool}(S::AbstractSerializer, t::Type{T}) = T(deserialize(S)) - -wp_local_push!(pool::AbstractWorkerPool, w::Int) = (push!(pool.workers, w); put!(pool.channel, w); pool) -wp_local_length(pool::AbstractWorkerPool) = length(pool.workers) -wp_local_isready(pool::AbstractWorkerPool) = isready(pool.channel) - -function wp_local_put!(pool::AbstractWorkerPool, w::Int) - # In case of default_worker_pool, the master is implictly considered a worker, i.e., - # it is not present in pool.workers. - # Confirm the that the worker is part of a pool before making it available. - w in pool.workers && put!(pool.channel, w) - w -end - -function wp_local_workers(pool::AbstractWorkerPool) - if length(pool) == 0 && pool === default_worker_pool() - return [1] - else - return collect(pool.workers) - end -end - -function wp_local_nworkers(pool::AbstractWorkerPool) - if length(pool) == 0 && pool === default_worker_pool() - return 1 - else - return length(pool.workers) - end -end - -function wp_local_take!(pool::AbstractWorkerPool) - # Find an active worker - worker = 0 - while true - if length(pool) == 0 - if pool === default_worker_pool() - # No workers, the master process is used as a worker - worker = 1 - break - else - throw(ErrorException("No active worker available in pool")) - end - end - - worker = take!(pool.channel) - if id_in_procs(worker) - break - else - delete!(pool.workers, worker) # Remove invalid worker from pool - end - end - return worker -end - -function remotecall_pool(rc_f, f, pool::AbstractWorkerPool, args...; kwargs...) - worker = take!(pool) - try - rc_f(f, worker, args...; kwargs...) - finally - put!(pool, worker) - end -end - -# Check if pool is local or remote and forward calls if required. -# NOTE: remotecall_fetch does it automatically, but this will be more efficient as -# it avoids the overhead associated with a local remotecall. - -for func = (:length, :isready, :workers, :nworkers, :take!) - func_local = Symbol(string("wp_local_", func)) - @eval begin - function ($func)(pool::WorkerPool) - if pool.ref.where != myid() - return remotecall_fetch(ref->($func_local)(fetch(ref).value), pool.ref.where, pool.ref) - else - return ($func_local)(pool) - end - end - - # default impl - ($func)(pool::AbstractWorkerPool) = ($func_local)(pool) - end -end - -for func = (:push!, :put!) - func_local = Symbol(string("wp_local_", func)) - @eval begin - function ($func)(pool::WorkerPool, w::Int) - if pool.ref.where != myid() - return remotecall_fetch((ref, w)->($func_local)(fetch(ref).value, w), pool.ref.where, pool.ref, w) - else - return ($func_local)(pool, w) - end - end - - # default impl - ($func)(pool::AbstractWorkerPool, w::Int) = ($func_local)(pool, w) - end -end - - -""" - remotecall(f, pool::AbstractWorkerPool, args...; kwargs...) -> Future - -`WorkerPool` variant of `remotecall(f, pid, ....)`. Waits for and takes a free worker from `pool` and performs a `remotecall` on it. -""" -remotecall(f, pool::AbstractWorkerPool, args...; kwargs...) = remotecall_pool(remotecall, f, pool, args...; kwargs...) - - -""" - remotecall_wait(f, pool::AbstractWorkerPool, args...; kwargs...) -> Future - -`WorkerPool` variant of `remotecall_wait(f, pid, ....)`. Waits for and takes a free worker from `pool` and -performs a `remotecall_wait` on it. -""" -remotecall_wait(f, pool::AbstractWorkerPool, args...; kwargs...) = remotecall_pool(remotecall_wait, f, pool, args...; kwargs...) - - -""" - remotecall_fetch(f, pool::AbstractWorkerPool, args...; kwargs...) -> result - -`WorkerPool` variant of `remotecall_fetch(f, pid, ....)`. Waits for and takes a free worker from `pool` and -performs a `remotecall_fetch` on it. -""" -remotecall_fetch(f, pool::AbstractWorkerPool, args...; kwargs...) = remotecall_pool(remotecall_fetch, f, pool, args...; kwargs...) - -""" - remote_do(f, pool::AbstractWorkerPool, args...; kwargs...) -> nothing - -`WorkerPool` variant of `remote_do(f, pid, ....)`. Waits for and takes a free worker from `pool` and -performs a `remote_do` on it. -""" -remote_do(f, pool::AbstractWorkerPool, args...; kwargs...) = remotecall_pool(remote_do, f, pool, args...; kwargs...) - -const _default_worker_pool = Ref{Nullable}(Nullable{WorkerPool}()) - -""" - default_worker_pool() - -`WorkerPool` containing idle `workers()` - used by `remote(f)` and [`pmap`](@ref) (by default). -""" -function default_worker_pool() - # On workers retrieve the default worker pool from the master when accessed - # for the first time - if isnull(_default_worker_pool[]) - if myid() == 1 - _default_worker_pool[] = Nullable(WorkerPool()) - else - _default_worker_pool[] = Nullable(remotecall_fetch(()->default_worker_pool(), 1)) - end - end - return get(_default_worker_pool[]) -end - -""" - remote([::AbstractWorkerPool], f) -> Function - -Returns an anonymous function that executes function `f` on an available worker -using [`remotecall_fetch`](@ref). -""" -remote(f) = (args...; kwargs...)->remotecall_fetch(f, default_worker_pool(), args...; kwargs...) -remote(p::AbstractWorkerPool, f) = (args...; kwargs...)->remotecall_fetch(f, p, args...; kwargs...) - -mutable struct CachingPool <: AbstractWorkerPool - channel::Channel{Int} - workers::Set{Int} - - # Mapping between a tuple (worker_id, f) and a remote_ref - map_obj2ref::Dict{Tuple{Int, Function}, RemoteChannel} - - function CachingPool() - wp = new(Channel{Int}(typemax(Int)), Set{Int}(), Dict{Int, Function}()) - finalizer(wp, clear!) - wp - end -end - -serialize(s::AbstractSerializer, cp::CachingPool) = throw(ErrorException("CachingPool objects are not serializable.")) - -""" - CachingPool(workers::Vector{Int}) - -An implementation of an `AbstractWorkerPool`. -[`remote`](@ref), [`remotecall_fetch`](@ref), -[`pmap`](@ref) (and other remote calls which execute functions remotely) -benefit from caching the serialized/deserialized functions on the worker nodes, -especially closures (which may capture large amounts of data). - -The remote cache is maintained for the lifetime of the returned `CachingPool` object. -To clear the cache earlier, use `clear!(pool)`. - -For global variables, only the bindings are captured in a closure, not the data. -`let` blocks can be used to capture global data. - -For example: -``` -const foo=rand(10^8); -wp=CachingPool(workers()) -let foo=foo - pmap(wp, i->sum(foo)+i, 1:100); -end -``` - -The above would transfer `foo` only once to each worker. - -""" -function CachingPool(workers::Vector{Int}) - pool = CachingPool() - for w in workers - push!(pool, w) - end - return pool -end - -""" - clear!(pool::CachingPool) -> pool - -Removes all cached functions from all participating workers. -""" -function clear!(pool::CachingPool) - for (_,rr) in pool.map_obj2ref - finalize(rr) - end - empty!(pool.map_obj2ref) - pool -end - -exec_from_cache(rr::RemoteChannel, args...; kwargs...) = fetch(rr)(args...; kwargs...) -function exec_from_cache(f_ref::Tuple{Function, RemoteChannel}, args...; kwargs...) - put!(f_ref[2], f_ref[1]) # Cache locally - f_ref[1](args...; kwargs...) -end - -function remotecall_pool(rc_f, f, pool::CachingPool, args...; kwargs...) - worker = take!(pool) - f_ref = get(pool.map_obj2ref, (worker, f), (f, RemoteChannel(worker))) - isa(f_ref, Tuple) && (pool.map_obj2ref[(worker, f)] = f_ref[2]) # Add to tracker - - try - rc_f(exec_from_cache, worker, f_ref, args...; kwargs...) - finally - put!(pool, worker) - end -end diff --git a/julia-0.6.3/share/julia/base/docs/Docs.jl b/julia-0.6.3/share/julia/base/docs/Docs.jl deleted file mode 100644 index 3894e26..0000000 --- a/julia-0.6.3/share/julia/base/docs/Docs.jl +++ /dev/null @@ -1,754 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -""" - Docs - -The `Docs` module provides the `@doc` macro which can be used to set and retrieve -documentation metadata for Julia objects. - -Please see the manual section on documentation for more -information. -""" -module Docs - -""" -# Documentation - -Functions, methods and types can be documented by placing a string before the definition: - - \""" - # The Foo Function - `foo(x)`: Foo the living hell out of `x`. - \""" - foo(x) = ... - -The `@doc` macro can be used directly to both set and retrieve documentation / metadata. By -default, documentation is written as Markdown, but any object can be placed before the -arrow. For example: - - @doc "blah" -> - function foo() ... - -The `->` is not required if the object is on the same line, e.g. - - @doc "foo" foo - -## Documenting objects after they are defined -You can document an object after its definition by - - @doc "foo" function_to_doc - @doc "bar" TypeToDoc - -For macros, the syntax is `@doc "macro doc" :(@Module.macro)` or `@doc "macro doc" -:(string_macro"")` for string macros. Without the quote `:()` the expansion of the macro -will be documented. - -## Retrieving Documentation -You can retrieve docs for functions, macros and other objects as follows: - - @doc foo - @doc @time - @doc md"" - -## Functions & Methods -Placing documentation before a method definition (e.g. `function foo() ...` or `foo() = ...`) -will cause that specific method to be documented, as opposed to the whole function. Method -docs are concatenated together in the order they were defined to provide docs for the -function. -""" -:(Core.@doc) - -include("bindings.jl") - -import Base.Markdown: @doc_str, MD -import Base.Meta: quot, isexpr -import Base: Callable -import ..CoreDocs: lazy_iterpolate - -export doc - -# Basic API / Storage - -const modules = Module[] -const META = gensym(:meta) - -meta(m::Module = current_module()) = isdefined(m, META) ? getfield(m, META) : ObjectIdDict() - -function initmeta(m::Module = current_module()) - if !isdefined(m, META) - eval(m, :(const $META = $(ObjectIdDict()))) - push!(modules, m) - end - nothing -end - -function signature!(tv, expr::Expr) - if isexpr(expr, (:call, :macrocall)) - sig = :(Union{Tuple{}}) - for arg in expr.args[2:end] - isexpr(arg, :parameters) && continue - if isexpr(arg, :kw) # optional arg - push!(sig.args, :(Tuple{$(sig.args[end].args[2:end]...)})) - end - push!(sig.args[end].args, argtype(arg)) - end - if isexpr(expr.args[1], :curly) && isempty(tv) - append!(tv, tvar.(expr.args[1].args[2:end])) - end - for i = length(tv):-1:1 - push!(sig.args, :(Tuple{$(tv[i].args[1])})) - end - for i = length(tv):-1:1 - sig = Expr(:where, sig, tv[i]) - end - sig - elseif isexpr(expr, :where) - append!(tv, tvar.(expr.args[2:end])) - signature!(tv, expr.args[1]) - else - signature!(tv, expr.args[1]) - end -end -signature!(tv, other) = :(Union{}) -signature(expr::Expr) = signature!([], expr) -signature(other) = signature!([], other) - -function argtype(expr::Expr) - isexpr(expr, :(::)) && return expr.args[end] - isexpr(expr, :(...)) && return :(Vararg{$(argtype(expr.args[1]))}) - argtype(expr.args[1]) -end -argtype(other) = :Any - -tvar(x::Expr) = x -tvar(s::Symbol) = :($s <: Any) - -# Docsystem types. -# ================ - -""" - Docs.DocStr - -Stores the contents of a single docstring as well as related metadata. - -Both the raw text, `.text`, and the parsed markdown, `.object`, are tracked by this type. -Parsing of the raw text is done lazily when a request is made to render the docstring, -which helps to reduce total precompiled image size. - -The `.data` fields stores several values related to the docstring, such as: path, -linenumber, source code, and fielddocs. -""" -mutable struct DocStr - text :: Core.SimpleVector - object :: Nullable - data :: Dict{Symbol, Any} -end - -function docstr(binding::Binding, typesig::ANY = Union{}) - for m in modules - dict = meta(m) - if haskey(dict, binding) - docs = dict[binding].docs - if haskey(docs, typesig) - return docs[typesig] - end - end - end - error("could not find matching docstring for '$binding :: $typesig'.") -end -docstr(object, data = Dict()) = _docstr(object, data) - -_docstr(vec::Core.SimpleVector, data) = DocStr(vec, Nullable(), data) -_docstr(str::AbstractString, data) = DocStr(Core.svec(str), Nullable(), data) -_docstr(object, data) = DocStr(Core.svec(), Nullable(object), data) - -_docstr(doc::DocStr, data) = (doc.data = merge(data, doc.data); doc) - -macro ref(x) - binding = bindingexpr(namify(x)) - typesig = signature(x) - esc(docexpr(binding, typesig)) -end - -docexpr(args...) = Expr(:call, docstr, args...) - -function formatdoc(d::DocStr) - buffer = IOBuffer() - for part in d.text - formatdoc(buffer, d, part) - end - Markdown.parse(seekstart(buffer)) -end -@noinline formatdoc(buffer, d, part) = print(buffer, part) - -function parsedoc(d::DocStr) - if isnull(d.object) - md = formatdoc(d) - md.meta[:module] = d.data[:module] - md.meta[:path] = d.data[:path] - d.object = Nullable(md) - end - get(d.object) -end - -""" - MultiDoc - -Stores a collection of docstrings for related objects, ie. a `Function`/`DataType` and -associated `Method` objects. - -Each documented object in a `MultiDoc` is referred to by it's signature which is represented -by a `Union` of `Tuple` types. For example the following `Method` definition - - f(x, y) = ... - -is stored as `Tuple{Any, Any}` in the `MultiDoc` while - - f{T}(x::T, y = ?) = ... - -is stored as `Union{Tuple{T, Any}, Tuple{T}} where T`. - -Note: The `Function`/`DataType` object's signature is always `Union{}`. -""" -mutable struct MultiDoc - "Ordered (via definition order) vector of object signatures." - order::Vector{Type} - "Documentation for each object. Keys are signatures." - docs::ObjectIdDict - - MultiDoc() = new(Type[], ObjectIdDict()) -end - -# Docstring registration. -# ======================= - -""" - Docs.doc!(binding, str, sig) - -Adds a new docstring `str` to the docsystem for `binding` and signature `sig`. -""" -function doc!(b::Binding, str::DocStr, sig::ANY = Union{}) - initmeta() - m = get!(meta(), b, MultiDoc()) - if haskey(m.docs, sig) - # We allow for docstrings to be updated, but print a warning since it is possible - # that over-writing a docstring *may* have been accidental. The warning - # is suppressed for symbols in Main, for interactive use (#23011). - current_module() == Main || warn("replacing docs for '$b :: $sig' in module '$(current_module())'.") - else - # The ordering of docstrings for each Binding is defined by the order in which they - # are initially added. Replacing a specific docstring does not change it's ordering. - push!(m.order, sig) - end - m.docs[sig] = str - str.data[:binding] = b - str.data[:typesig] = sig - return b -end - -# Docstring lookup. -# ================= - -""" - getdoc(obj) - getdoc(obj, sig) - -Return a custom docstring object associated with the object `obj` and, optionally, the tuple -type signature `sig`. See `MultiDoc` docs for an explanation of the possible values of `sig`. - -The returned object can either be a markdown object generated by `Markdown.parse` or some -other custom type used to display non-markdown formatted documentation. - -A return value of `nothing` can be used to signify to the docsystem that no documentation -was found for `obj`, in which case the docsystem will fall back to searching for the -`Binding` associated with `obj` instead. -""" -function getdoc end - -getdoc(x, sig) = getdoc(x) -getdoc(x) = nothing - -""" - Docs.doc(binding, sig) - -Returns all documentation that matches both `binding` and `sig`. - -If `getdoc` returns a non-`nothing` result on the value of the binding, then a -dynamic docstring is returned instead of one based on the binding itself. -""" -function doc(binding::Binding, sig::Type = Union{}) - if defined(binding) - result = getdoc(resolve(binding), sig) - result === nothing || return result - end - results, groups = DocStr[], MultiDoc[] - # Lookup `binding` and `sig` for matches in all modules of the docsystem. - for mod in modules - dict = meta(mod) - if haskey(dict, binding) - multidoc = dict[binding] - push!(groups, multidoc) - for msig in multidoc.order - sig <: msig && push!(results, multidoc.docs[msig]) - end - end - end - if isempty(groups) - # When no `MultiDoc`s are found that match `binding` then we check whether `binding` - # is an alias of some other `Binding`. When it is we then re-run `doc` with that - # `Binding`, otherwise if it's not an alias then we generate a summary for the - # `binding` and display that to the user instead. - alias = aliasof(binding) - alias == binding ? summarize(alias, sig) : doc(alias, sig) - else - # There was at least one match for `binding` while searching. If there weren't any - # matches for `sig` then we concatenate *all* the docs from the matching `Binding`s. - if isempty(results) - for group in groups, each in group.order - push!(results, group.docs[each]) - end - end - # Get parsed docs and concatenate them. - md = catdoc(map(parsedoc, results)...) - # Save metadata in the generated markdown. - if isa(md, Markdown.MD) - md.meta[:results] = results - md.meta[:binding] = binding - md.meta[:typesig] = sig - end - return md - end -end - -# Some additional convenience `doc` methods that take objects rather than `Binding`s. -doc(obj::UnionAll) = doc(Base.unwrap_unionall(obj)) -doc(object, sig::Type = Union{}) = doc(aliasof(object, typeof(object)), sig) -doc(object, sig...) = doc(object, Tuple{sig...}) - -""" - Docs.fielddoc(binding, field) - -Returns documentation for a particular `field` of a type if it exists. -""" -function fielddoc(binding::Binding, field::Symbol) - for mod in modules - dict = meta(mod) - if haskey(dict, binding) - multidoc = dict[binding] - if haskey(multidoc.docs, Union{}) - fields = multidoc.docs[Union{}].data[:fields] - if haskey(fields, field) - doc = fields[field] - return isa(doc, Markdown.MD) ? doc : Markdown.parse(doc) - end - end - end - end - fields = join(["`$f`" for f in fieldnames(resolve(binding))], ", ", ", and ") - fields = isempty(fields) ? "no fields" : "fields $fields" - Markdown.parse("`$(resolve(binding))` has $fields.") -end - -# As with the additional `doc` methods, this converts an object to a `Binding` first. -fielddoc(object, field::Symbol) = fielddoc(aliasof(object, typeof(object)), field) - -# Object Summaries. -# ================= - -function summarize(binding::Binding, sig) - io = IOBuffer() - println(io, "No documentation found.\n") - if defined(binding) - summarize(io, resolve(binding), binding) - else - println(io, "Binding `", binding, "` does not exist.") - end - md = Markdown.parse(seekstart(io)) - # Save metadata in the generated markdown. - md.meta[:results] = DocStr[] - md.meta[:binding] = binding - md.meta[:typesig] = sig - return md -end - -function summarize(io::IO, λ::Function, binding) - kind = startswith(string(binding.var), '@') ? "macro" : "`Function`" - println(io, "`", binding, "` is a ", kind, ".") - println(io, "```\n", methods(λ), "\n```") -end - -function summarize(io::IO, T::DataType, binding) - println(io, "**Summary:**") - println(io, "```") - println(io, - T.abstract ? "abstract type" : - T.mutable ? "mutable struct" : - Base.isstructtype(T) ? "struct" : "primitive type", - " ", T, " <: ", supertype(T) - ) - println(io, "```") - if !isempty(fieldnames(T)) - println(io, "**Fields:**") - println(io, "```") - pad = maximum(length(string(f)) for f in fieldnames(T)) - for (f, t) in zip(fieldnames(T), T.types) - println(io, rpad(f, pad), " :: ", t) - end - println(io, "```") - end - if !isempty(subtypes(T)) - println(io, "**Subtypes:**") - println(io, "```") - for t in subtypes(T) - println(io, t) - end - println(io, "```") - end -end - -function summarize(io::IO, m::Module, binding) - readme = Pkg.dir(string(m), "README.md") - if isfile(readme) - println(io, "Displaying the `README.md` for the module instead.\n") - println(io, "---\n") - println(io, readstring(readme)) - else - println(io, "No docstring or `README.md` found for module `", m, "`.\n") - end -end - -function summarize{T}(io::IO, ::T, binding) - println(io, "`", binding, "` is of type `", T, "`.\n") - summarize(io, T, binding) -end - -# Utilities. -# ========== - -""" -`catdoc(xs...)`: Combine the documentation metadata `xs` into a single meta object. -""" -catdoc() = nothing -catdoc(xs...) = vcat(xs...) - -const keywords = Dict{Symbol, DocStr}() - -isdoc(s::AbstractString) = true - -isdoc(x) = isexpr(x, :string) || - (isexpr(x, :macrocall) && x.args[1] === Symbol("@doc_str")) || - (isexpr(x, :call) && x.args[1] === Base.Markdown.doc_str) - -function unblock(ex) - isexpr(ex, :block) || return ex - exs = filter(ex -> !(isa(ex, LineNumberNode) || isexpr(ex, :line)), ex.args) - length(exs) == 1 || return ex - return unblock(exs[1]) -end - -uncurly(ex) = isexpr(ex, :curly) ? ex.args[1] : ex - -namify(x) = nameof(x, isexpr(x, :macro)) - -function nameof(x::Expr, ismacro) - if isexpr(x, :.) - ismacro ? macroname(x) : x - else - n = isexpr(x, (:module, :type, :bitstype)) ? 2 : 1 - nameof(x.args[n], ismacro) - end -end -nameof(q::QuoteNode, ismacro) = nameof(q.value, ismacro) -nameof(s::Symbol, ismacro) = ismacro ? macroname(s) : s -nameof(other, ismacro) = other - -macroname(s::Symbol) = Symbol('@', s) -macroname(x::Expr) = Expr(x.head, x.args[1], macroname(x.args[end].value)) - -isfield(x) = isexpr(x, :.) && - (isa(x.args[1], Symbol) || isfield(x.args[1])) && - (isa(x.args[2], QuoteNode) || isexpr(x.args[2], :quote)) - -# @doc expression builders. -# ========================= - -""" - Docs.metadata(expr) - -Build a `Dict` expression containing metadata captured from the expression `expr`. - -Fields that may be included in the returned `Dict`: - -- `:path`: String representing the file where `expr` is defined. -- `:linenumber`: Linenumber where `expr` is defined. -- `:module`: Module where the docstring is defined. -- `:fields`: `Dict` of all field docs found in `expr`. Only for concrete types. -""" -function metadata(expr) - args = [] - # Filename and linenumber of the docstring. - push!(args, :($(Pair)(:path, $(Base).@__FILE__))) - push!(args, :($(Pair)(:linenumber, $(unsafe_load(cglobal(:jl_lineno, Cint)))))) - # Module in which the docstring is defined. - push!(args, :($(Pair)(:module, $(current_module)()))) - # Field docs for concrete types. - if isexpr(expr, :type) - fields = [] - tmp = nothing - for each in expr.args[3].args - if isdoc(each) - tmp = each - elseif tmp !== nothing && (isa(each, Symbol) || isexpr(each, :(::))) - push!(fields, (namify(each), tmp)) - tmp = nothing - end - end - dict = :($(Dict)($([:($(Pair)($(quot(f)), $d)) for (f, d) in fields]...))) - push!(args, :($(Pair)(:fields, $dict))) - end - :($(Dict)($(args...))) -end - -function keyworddoc(str, def) - docstr = esc(docexpr(lazy_iterpolate(str), metadata(def))) - :($(keywords)[$(esc(quot(def.name)))] = $docstr) -end - -function objectdoc(str, def, expr, sig = :(Union{})) - binding = esc(bindingexpr(namify(expr))) - docstr = esc(docexpr(lazy_iterpolate(str), metadata(expr))) - quote - $(esc(def)) - $(doc!)($binding, $docstr, $(esc(sig))) - end -end - -function calldoc(str, def) - args = def.args[2:end] - if isempty(args) || all(validcall, args) - objectdoc(str, nothing, def, signature(def)) - else - docerror(def) - end -end -validcall(x) = isa(x, Symbol) || isexpr(x, (:(::), :..., :kw, :parameters)) - -function moduledoc(meta, def, def′) - name = namify(def′) - docex = Expr(:call, doc!, bindingexpr(name), - docexpr(lazy_iterpolate(meta), metadata(name)) - ) - if def === nothing - esc(:(eval($name, $(quot(docex))))) - else - def = unblock(def) - block = def.args[3].args - if !def.args[1] - isempty(block) && error("empty baremodules are not documentable.") - insert!(block, 2, :(import Base: @doc)) - end - push!(block, docex) - esc(Expr(:toplevel, def)) - end -end - -# Shares a single doc, `meta`, between several expressions from the tuple expression `ex`. -function multidoc(meta, ex, define) - out = Expr(:toplevel) - str = docexpr(lazy_iterpolate(meta), metadata(ex)) - ref = Ref{DocStr}() - for (n, arg) in enumerate(ex.args) - # The first `arg` to be documented needs to also create the docstring for the group. - # Subsequent `arg`s just need `ref` to be able to find the docstring without having - # to create an entirely new one each. - docstr = n === 1 ? :($(ref)[] = $str) : :($(ref)[]) - push!(out.args, :(@doc($docstr, $arg, $define))) - end - esc(out) -end - -""" - @__doc__(ex) - -Low-level macro used to mark expressions returned by a macro that should be documented. If -more than one expression is marked then the same docstring is applied to each expression. - - macro example(f) - quote - \$(f)() = 0 - @__doc__ \$(f)(x) = 1 - \$(f)(x, y) = 2 - end |> esc - end - -`@__doc__` has no effect when a macro that uses it is not documented. -""" -:(Core.@__doc__) - -function __doc__!(meta, def, define) - # Two cases must be handled here to avoid redefining all definitions contained in `def`: - if define - # `def` has not been defined yet (this is the common case, i.e. when not generating - # the Base image). We just need to convert each `@__doc__` marker to an `@doc`. - finddoc(def) do each - each.head = :macrocall - each.args = [Symbol("@doc"), meta, each.args[end], define] - end - else - # `def` has already been defined during Base image gen so we just need to find and - # document any subexpressions marked with `@__doc__`. - docs = [] - found = finddoc(def) do each - push!(docs, :(@doc($meta, $(each.args[end]), $define))) - end - # If any subexpressions have been documented then replace the entire expression with - # just those documented subexpressions to avoid redefining any definitions. - if found - def.head = :toplevel - def.args = docs - end - found - end -end -# Walk expression tree `def` and call `λ` when any `@__doc__` markers are found. Returns -# `true` to signify that at least one `@__doc__` has been found, and `false` otherwise. -function finddoc(λ, def::Expr) - if isexpr(def, :block, 2) && isexpr(def.args[1], :meta, 1) && def.args[1].args[1] === :doc - # Found the macroexpansion of an `@__doc__` expression. - λ(def) - true - else - found = false - for each in def.args - found |= finddoc(λ, each) - end - found - end -end -finddoc(λ, def) = false - -# Predicates and helpers for `docm` expression selection: - -const FUNC_HEADS = [:function, :stagedfunction, :macro, :(=)] -const BINDING_HEADS = [:typealias, :const, :global, :(=)] # deprecation: remove `typealias` post-0.6 -# For the special `:@mac` / `:(Base.@mac)` syntax for documenting a macro after definition. -isquotedmacrocall(x) = - isexpr(x, :copyast, 1) && - isa(x.args[1], QuoteNode) && - isexpr(x.args[1].value, :macrocall, 1) -# Simple expressions / atoms the may be documented. -isbasicdoc(x) = isexpr(x, :.) || isa(x, Union{QuoteNode, Symbol}) -is_signature(x) = isexpr(x, :call) || (isexpr(x, :(::), 2) && isexpr(x.args[1], :call)) || isexpr(x, :where) - -function docm(meta, ex, define = true) - # Some documented expressions may be decorated with macro calls which obscure the actual - # expression. Expand the macro calls and remove extra blocks. - x = unblock(macroexpand(ex)) - # Don't try to redefine expressions. This is only needed for `Base` img gen since - # otherwise calling `loaddocs` would redefine all documented functions and types. - def = define ? x : nothing - if isa(x, GlobalRef) && (x::GlobalRef).mod == current_module() - x = (x::GlobalRef).name - end - - # Keywords using the `@kw_str` macro in `base/docs/basedocs.jl`. - # - # "..." - # kw"if", kw"else" - # - isa(x, Base.BaseDocs.Keyword) ? keyworddoc(meta, x) : - - # Method / macro definitions and "call" syntax. - # - # function f(...) ... end - # f(...) = ... - # macro m(...) end - # function f end - # f(...) - # - isexpr(x, FUNC_HEADS) && is_signature(x.args[1]) ? objectdoc(meta, def, x, signature(x)) : - isexpr(x, :function) && !isexpr(x.args[1], :call) ? objectdoc(meta, def, x) : - isexpr(x, :call) ? calldoc(meta, x) : - - # Type definitions. - # - # type T ... end - # abstract T - # bitstype N T - # - isexpr(x, [:type, :abstract, :bitstype]) ? objectdoc(meta, def, x) : - - # "Bindings". Names that resolve to objects with different names, ie. - # - # const T = S - # T = S - # global T = S - # - isexpr(x, BINDING_HEADS) && !isexpr(x.args[1], :call) ? objectdoc(meta, def, x) : - - # Quoted macrocall syntax. `:@time` / `:(Base.@time)`. - isquotedmacrocall(x) ? objectdoc(meta, def, x) : - # Modules and baremodules. - isexpr(x, :module) ? moduledoc(meta, def, x) : - # Document several expressions with the same docstring. `a, b, c`. - isexpr(x, :tuple) ? multidoc(meta, x, define) : - # Errors generated by calling `macroexpand` are passed back to the call site. - isexpr(x, :error) ? esc(x) : - # When documenting macro-generated code we look for embedded `@__doc__` calls. - __doc__!(meta, x, define) ? esc(x) : - # Any "basic" expression such as a bare function or module name or numeric literal. - isbasicdoc(x) ? objectdoc(meta, nothing, x) : - - # All other expressions are undocumentable and should be handled on a case-by-case basis - # with `@__doc__`. Unbound string literals are also undocumentable since they cannot be - # retrieved from the module's metadata `ObjectIdDict` without a reference to the string. - docerror(ex) -end - -function docerror(ex) - txt = """ - cannot document the following expression: - - $(isa(ex, AbstractString) ? repr(ex) : ex)""" - if isexpr(ex, :macrocall) - txt *= "\n\n'$(ex.args[1])' not documentable. See 'Base.@__doc__' docs for details." - end - :($(error)($txt, "\n")) -end - -function docm(ex) - if isexpr(ex, :->) - docm(ex.args...) - elseif haskey(keywords, ex) - parsedoc(keywords[ex]) - elseif isa(ex, Union{Expr, Symbol}) - binding = esc(bindingexpr(namify(ex))) - if isexpr(ex, [:call, :macrocall]) - sig = esc(signature(ex)) - :($(doc)($binding, $sig)) - else - :($(doc)($binding)) - end - else - :($(doc)($(typeof)($(esc(ex))))) - end -end - -# MD support -catdoc(md::MD...) = MD(md...) - -include("utils.jl") - -# Swap out the bootstrap macro with the real one. -Core.atdoc!(docm) - -function loaddocs(docs) - for (mod, ex, str, file, line) in docs - data = Dict(:path => string(file), :linenumber => line) - doc = docstr(str, data) - eval(mod, :(@doc($doc, $ex, false))) - end - empty!(docs) -end - -end diff --git a/julia-0.6.3/share/julia/base/docs/basedocs.jl b/julia-0.6.3/share/julia/base/docs/basedocs.jl deleted file mode 100644 index bba031e..0000000 --- a/julia-0.6.3/share/julia/base/docs/basedocs.jl +++ /dev/null @@ -1,744 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -module BaseDocs - -struct Keyword - name :: Symbol -end -macro kw_str(text) Keyword(Symbol(text)) end - -""" -**Welcome to Julia $(string(VERSION)).** The full manual is available at - - https://docs.julialang.org/ - -as well many great tutorials and learning resources: - - https://julialang.org/learning/ - -For help on a specific function or macro, type `?` followed -by its name, e.g. `?fft`, or `?@time`, and press enter. -""" -kw"help", kw"?", kw"julia" - -""" -`using` will load the given module or package and make some of its names available for -use (see also `export`). For example: - - using Gadfly - -loads the plotting package, Gadfly, so that the `plot` function can be used. - -Names can be used via dot syntax, whether they are exported or not: - - Gadfly.plot(...) - -If you don't want to use the packages exports directly, see also `import`. If you're not -sure, `using` is almost definitely what you want. -""" -kw"using" - -""" - import Gadfly - -`import`, like `using`, will load modules and packages for use. Unlike `using`, however, -it will *not* make any `export`ed names available for use. To use Gadfly's `plot` -function after importing it, for example, you have to write: - - Gadfly.plot(...) - -Import can also be used with specific names, for example - - import Gadfly: plot, render - -This syntax is used when you want to extend the modules functions with new methods. -""" -kw"import" - -""" -`export` is used within modules and packages to tell Julia which functions should be -made available to the user. For example: - - module Test - export foo # foo is exported, but bar isn't - foo(x) = x - bar(y) = y - end - - using Test - foo(1) # 1 - bar(1) # Error: bar not defined - Test.bar(1) # 1 -""" -kw"export" - -""" -`abstract type` declares a type that cannot be instantiated, and serves only as a node in the -type graph, thereby describing sets of related concrete types: those concrete types -which are their descendants. Abstract types form the conceptual hierarchy which makes -Julia’s type system more than just a collection of object implementations. For example: - - abstract type Number end - abstract type Real <: Number end - -[`Number`](@ref) has no supertype, whereas [`Real`](@ref) is an abstract subtype of `Number`. -""" -kw"abstract type" - -""" -`module` declares a Module, which is a separate global variable workspace. Within a -module, you can control which names from other modules are visible (via importing), and -specify which of your names are intended to be public (via exporting). For example: - - module - import Base.show - export MyType, foo - - type MyType - x - end - - bar(x) = 2x - foo(a::MyType) = bar(a.x) + 1 - show(io, a::MyType) = print(io, "MyType \$(a.x)") - end - -Modules allow you to create top-level definitions without worrying about name conflicts -when your code is used together with somebody else’s. -""" -kw"module" - -""" -`baremodule` declares a module that does not contain `using Base` -or a definition of `eval`. It does still import `Core`. -""" -kw"baremodule" - -""" -`primitive type` declares a concrete type whose data consists only of a series of bits. Classic -examples of primitive types are integers and floating-point values. Some example built-in -primitive type declarations: - - primitive type Char 32 end - primitive type Bool <: Integer 8 end - -The number after the name indicates how many bits of storage the type requires. Currently, -only sizes that are multiples of 8 bits are supported. -The [`Bool`](@ref) declaration shows how a primitive type can be optionally -declared to be a subtype of some supertype. -""" -kw"primitive type" - -""" -`macro` defines a method to include generated code in the final body of a program. A -macro maps a tuple of arguments to a returned expression, and the resulting expression -is compiled directly rather than requiring a runtime `eval()` call. Macro arguments may -include expressions, literal values, and symbols. For example: - - macro sayhello(name) - return :( println("Hello, ", \$name) ) - end - -This macro takes one argument: `name`. When `@sayhello` is encountered, the quoted -expression is expanded to interpolate the value of the argument into the final -expression. -""" -kw"macro" - -""" -`importall` imports all names exported by the specified module, as if `import` were used -individually on all of them. For example: - - importall Distributions - -As with `import`, functions imported by `importall` can be extended. -""" -kw"importall" - -""" -`local` introduces a new local variable. For example: - - function foo(n) - x = 0 - for i = 1:n - local x - x = i - end - x - end - - julia> foo(10) - 0 - -Here `local x` introduces a separate `x` inside the loop, so the function returns `0`. -""" -kw"local" - -""" -`global x` makes `x` in the current scope and its inner scopes refer to the global -variable of that name. In the example below, `global` is needed so the function can -modify the global variable `z`: - - z=3 - function foo() - global z=6 - end - - julia> foo() - 6 - julia> z - 6 - -Without the `global` declaration in `foo()`, a new local variable would have been -created inside foo(), and the `z` in the global scope would have remained equal to `3`. -""" -kw"global" - -""" -`let` statements allocate new variable bindings each time they run. Whereas an -assignment modifies an existing value location, `let` creates new locations. This -difference is only detectable in the case of variables that outlive their scope via -closures. The `let` syntax accepts a comma-separated series of assignments and variable -names: - - let var1 = value1, var2, var3 = value3 - code - end - -The assignments are evaluated in order, with each right-hand side evaluated in the scope -before the new variable on the left-hand side has been introduced. Therefore it makes -sense to write something like `let x = x`, since the two `x` variables are distinct and -have separate storage. -""" -kw"let" - -""" -`quote` creates multiple expression objects in a block without using the explicit `Expr` -constructor. For example: - - ex = quote - x = 1 - y = 2 - x + y - end - -Unlike the other means of quoting, `:( ... )`, this form introduces `QuoteNode` elements -to the expression tree, which must be considered when directly manipulating the tree. -For other purposes, `:( ... )` and `quote .. end` blocks are treated identically. -""" -kw"quote" - -""" -`'` is the conjugate transposition operator: - - julia> A = reshape(1:4, 2,2) - 2×2 Array{Int64,2}: - 1 3 - 2 4 - - julia> A' - 2×2 Array{Int64,2}: - 1 2 - 3 4 - - julia> B = A + im - 2×2 Array{Complex{Int64},2}: - 1+1im 3+1im - 2+1im 4+1im - - julia> B' - 2×2 Array{Complex{Int64},2}: - 1-1im 2-1im - 3-1im 4-1im - -""" -kw"'" - - -""" -`.'` is the transposition operator: - - julia> A = reshape(1:4, 2,2) - 2×2 Array{Int64,2}: - 1 3 - 2 4 - - julia> A.' - 2×2 Array{Int64,2}: - 1 2 - 3 4 - - julia> B = A + im - 2×2 Array{Complex{Int64},2}: - 1+1im 3+1im - 2+1im 4+1im - - julia> B.' - 2×2 Array{Complex{Int64},2}: - 1+1im 2+1im - 3+1im 4+1im - - julia> v = [1,2,3] - 3-element Array{Int64,1}: - 1 - 2 - 3 - - julia> v.' - 1×3 RowVector{Int64,Array{Int64,1}}: - 1 2 3 - -""" -kw".'" - -""" -`const` is used to declare global variables which are also constant. In almost all code -(and particularly performance sensitive code) global variables should be declared -constant in this way. - - const x = 5 - -Note that "constant-ness" is not enforced inside containers, so if `x` is an array or -dictionary (for example) you can still add and remove elements. - -Technically, you can even redefine `const` variables, although this will generate a -warning from the compiler. The only strict requirement is that the *type* of the -variable does not change, which is why `const` variables are much faster than regular -globals. -""" -kw"const" - -""" -Functions are defined with the `function` keyword: - - function add(a, b) - return a + b - end - -Or the short form notation: - - add(a, b) = a + b - -The use of the `return` keyword is exactly the same as in other languages, but is often -optional. When it's not used, the last expression in the function body will be returned -by default: - - function compare(a, b) - a == b && return "equal to" - a < b ? "less than" : "greater than" - end -""" -kw"function" - -""" -`return` can be used function bodies to exit early and return a given value, e.g. - - function compare(a, b) - a == b && return "equal to" - a < b ? "less than" : "greater than" - end - -In general you can place a `return` statement anywhere within a function body, including -within deeply nested loops or conditionals, but be careful with `do` blocks. For -example: - - function test1(xs) - for x in xs - iseven(x) && return 2x - end - end - - function test2(xs) - map(xs) do x - iseven(x) && return 2x - x - end - end - -In the first example, the return breaks out of its enclosing function as soon as it hits -an even number, so `test1([5,6,7])` returns `12`. - -You might expect the second example to behave the same way, but in fact the `return` -there only breaks out of the *inner* function (inside the `do` block) and gives a value -back to `map`. `test2([5,6,7])` then returns `[5,12,7]`. -""" -kw"return" - -""" -`if`-`elseif`-`else` performs conditional evaluation, which allows portions of code to -be evaluated or not evaluated depending on the value of a boolean expression. Here is -the anatomy of the `if`-`elseif`-`else` conditional syntax: - - if x < y - println("x is less than y") - elseif x > y - println("x is greater than y") - else - println("x is equal to y") - end - -If the condition expression `x < y` is true, then the corresponding block is evaluated; -otherwise the condition expression `x > y` is evaluated, and if it is true, the -corresponding block is evaluated; if neither expression is true, the `else` block is -evaluated. The `elseif` and `else` blocks are optional, and as many `elseif` blocks as -desired can be used. -""" -kw"if", kw"elseif", kw"else" - -""" -`for` loops repeatedly evaluate the body of the loop by iterating over a sequence of -values. For example: - - for i in [1,4,0] - println(i) - end -""" -kw"for" - -""" -`while` loops repeatedly evaluate a conditional expression, and continues evaluating the -body of the while loop so long as the expression remains `true`. If the condition -expression is false when the while loop is first reached, the body is never evaluated. -For example: - - while i <= 5 - println(i) - i += 1 - end -""" -kw"while" - -""" -`end` marks the conclusion of a block of expressions. In the example below, `end` marks -the conclusion of a `function`. - - function foo() - println("hello, world") - end - -`end` marks the conclusion of all kinds of expression blocks: `module`, `type`, `begin`, -`let`, `for`, etc. - -In addition, `end` may be used when indexing into an array to represent the last index -of each dimension: - - x[1:end, 2:end-1] -""" -kw"end" - -""" -A `try/catch` statement allows for `Exception`s to be tested for. For example, a -customized square root function can be written to automatically call either the real or -complex square root method on demand using `Exception`s: - - f(x) = try - sqrt(x) - catch - sqrt(complex(x, 0)) - end - -`try/catch` statements also allow the `Exception` to be saved in a variable, e.g. `catch y`. - -The `catch` clause is not strictly necessary; when omitted, the default return value is -`nothing`. The power of the `try/catch` construct lies in the ability to unwind a deeply -nested computation immediately to a much higher level in the stack of calling functions. -""" -kw"try", kw"catch" - -""" -`finally` provides a way to run some code when a given block of code exits, regardless -of how it exits. For example, here is how we can guarantee that an opened file is -closed: - - f = open("file") - try - operate_on_file(f) - finally - close(f) - end - -When control leaves the `try` block (for example due to a `return`, or just finishing -normally), `close(f)` will be executed. If the `try` block exits due to an exception, -the exception will continue propagating. A `catch` block may be combined with `try` and -`finally` as well. In this case the `finally` block will run after `catch` has handled -the error. -""" -kw"finally" - -""" -`break` breaks out of a loop immediately. For example - - i = 0 - while true - i += 1 - i > 10 && break - println(i) - end - -prints the numbers 1 to 10. -""" -kw"break" - -""" -`continue` skips the rest of the current loop, then carries on looping. For example - - for i = 1:10 - iseven(i) && continue - println(i) - end - -prints the numbers 1, 3, 5..., skipping the even numbers. -""" -kw"continue" - -""" -The `do` keyword creates an anonymous function. For example - - map(1:10) do x - 2x - end - -is equivalent to `map(x->2x, 1:10)`. - -Use multiple arguments like so: - - map(1:10, 11:20) do x, y - x + y - end -""" -kw"do" - -""" -The "splat" operator, `...`, represents a sequence of arguments. For example - - add(xs...) = reduce(+, xs) - -can take any number of arguments: - - add(1, 2, 3, 4, 5) - -`...` can also be used to apply a function to a sequence of arguments like so: - - add([1, 2, 3]...) # 6 - add(7, 1:100..., 1000:1100...) # 111107 -""" -kw"..." - -""" -`;` has a similar role in Julia as in many C-like languages, and is used to delimit the -end of the previous statement. `;` is not necessary after new lines, but can be used to -separate statements on a single line or to join statements into a single expression: - - function foo() - println("Hello, "); println("World!") - return true - end - - foo() = (println("Hello, World!"); true) - -`;` is also used to suppress output in the REPL and similar interfaces. -""" -kw";" - -""" - x && y - -Short-circuiting boolean AND. -""" -kw"&&" - -""" - x || y - -Short-circuiting boolean OR. -""" -kw"||" - -""" - ccall((symbol, library) or function_pointer, ReturnType, (ArgumentType1, ...), ArgumentValue1, ...) - -Call function in C-exported shared library, specified by `(function name, library)` -tuple, where each component is a string or symbol. - -Note that the argument type tuple must be a literal tuple, and not a tuple-valued -variable or expression. Alternatively, `ccall` may also be used to call a function -pointer, such as one returned by `dlsym`. - -Each `ArgumentValue` to the `ccall` will be converted to the corresponding -`ArgumentType`, by automatic insertion of calls to `unsafe_convert(ArgumentType, -cconvert(ArgumentType, ArgumentValue))`. (See also the documentation for each of these -functions for further details.) In most cases, this simply results in a call to -`convert(ArgumentType, ArgumentValue)`. -""" -kw"ccall" - -""" - llvmcall(IR::String, ReturnType, (ArgumentType1, ...), ArgumentValue1, ...) - llvmcall((declarations::String, IR::String), ReturnType, (ArgumentType1, ...), ArgumentValue1, ...) - -Call LLVM IR string in the first argument. Similar to an LLVM function `define` block, -arguments are available as consecutive unnamed SSA variables (%0, %1, etc.). - -The optional declarations string contains external functions declarations that are -necessary for llvm to compile the IR string. Multiple declarations can be passed in by -separating them with line breaks. - -Note that the argument type tuple must be a literal tuple, and not a tuple-valued -variable or expression. - -Each `ArgumentValue` to `llvmcall` will be converted to the corresponding -`ArgumentType`, by automatic insertion of calls to `unsafe_convert(ArgumentType, -cconvert(ArgumentType, ArgumentValue))`. (see also the documentation for each of these -functions for further details). In most cases, this simply results in a call to -`convert(ArgumentType, ArgumentValue)`. - -See `test/llvmcall.jl` for usage examples. -""" -Core.Intrinsics.llvmcall - -""" -`begin...end` denotes a block of code. - - begin - println("Hello, ") - println("World!") - end - -Usually `begin` will not be necessary, since keywords such as `function` and `let` -implicitly begin blocks of code. See also `;`. -""" -kw"begin" - -""" -The most commonly used kind of type in Julia is a struct, specified as a name and a -set of fields. - - struct Point - x - y - end - -Fields can have type restrictions, which may be parameterized: - - struct Point{X} - x::X - y::Float64 - end - -A struct can also declare an abstract super type via `<:` syntax: - - struct Point <: AbstractPoint - ... - -Structs are immutable by default; an instance of one of these types cannot -be modified after construction. Use `mutable struct` instead to declare a -type whose instances can be modified. - -See the manual for more details, such as how to define constructors. -""" -kw"struct" - -""" -`mutable struct` is similar to `struct`, but additionally allows the fields of the type -to be set after construction. See `struct` and the manual for more information. -""" -kw"mutable struct" - -""" - @__LINE__ -> Int - -`@__LINE__` expands to the line number of the call-site. -""" -kw"@__LINE__" - -""" -The `where` keyword creates a type that is an iterated union of other types, over all -values of some variable. For example `Vector{T} where T<:Real` includes all `Vector`s -where the element type is some kind of `Real` number. - -The variable bound defaults to `Any` if it is omitted: - - Vector{T} where T # short for `where T<:Any` - -Variables can also have lower bounds: - - Vector{T} where T>:Int - Vector{T} where Int<:T<:Real - -There is also a concise syntax for nested `where` expressions. For example, this: - - Pair{T, S} where S<:Array{T} where T<:Number - -can be shortened to: - - Pair{T, S} where {T<:Number, S<:Array{T}} - -This form is often found on method signatures. - -Note that in this form, the variables are listed outermost-first. This matches the -order in which variables are substituted when a type is "applied" to parameter values -using the syntax `T{p1, p2, ...}`. -""" -kw"where" - -""" - ans - -A variable referring to the last computed value, automatically set at the interactive prompt. -""" -kw"ans" - -""" - nothing - -The singleton instance of type `Void`, used by convention when there is no value to return -(as in a C `void` function). Can be converted to an empty `Nullable` value. -""" -nothing - -""" - ANY - -Equivalent to `Any` for dispatch purposes, but signals the compiler to skip code -generation specialization for that field. -""" -ANY - -""" - Core.TypeofBottom - -The singleton type containing only the value `Union{}`. -""" -Core.TypeofBottom - -""" - DevNull - -Used in a stream redirect to discard all data written to it. Essentially equivalent to -/dev/null on Unix or NUL on Windows. Usage: - -```julia -run(pipeline(`cat test.txt`, DevNull)) -``` -""" -DevNull - -""" - Function - -Abstract type of all functions. - -```jldoctest -julia> isa(+, Function) -true - -julia> typeof(sin) -Base.#sin - -julia> ans <: Function -true -``` -""" -Function - -end diff --git a/julia-0.6.3/share/julia/base/docs/bindings.jl b/julia-0.6.3/share/julia/base/docs/bindings.jl deleted file mode 100644 index ac7fbab..0000000 --- a/julia-0.6.3/share/julia/base/docs/bindings.jl +++ /dev/null @@ -1,46 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -export @var - -struct Binding - mod::Module - var::Symbol - - function Binding(m::Module, v::Symbol) - # Normalise the binding module for module symbols so that: - # Binding(Base, :Base) === Binding(Main, :Base) - m = module_name(m) === v ? module_parent(m) : m - new(Base.binding_module(m, v), v) - end -end - -bindingexpr(x) = Expr(:call, Binding, splitexpr(x)...) - -defined(b::Binding) = isdefined(b.mod, b.var) -resolve(b::Binding) = getfield(b.mod, b.var) - -function splitexpr(x::Expr) - isexpr(x, :macrocall) ? splitexpr(x.args[1]) : - isexpr(x, :.) ? (x.args[1], x.args[2]) : - error("Invalid @var syntax `$x`.") -end -splitexpr(s::Symbol) = Expr(:call, current_module), quot(s) -splitexpr(other) = error("Invalid @var syntax `$other`.") - -macro var(x) - esc(bindingexpr(x)) -end - -function Base.show(io::IO, b::Binding) - if b.mod === Main - print(io, b.var) - else - print(io, b.mod, '.', Base.isoperator(b.var) ? ":" : "", b.var) - end -end - -aliasof(b::Binding) = defined(b) ? (a = aliasof(resolve(b), b); defined(a) ? a : b) : b -aliasof(d::DataType, b) = Binding(d.name.module, d.name.name) -aliasof(λ::Function, b) = (m = typeof(λ).name.mt; Binding(m.module, m.name)) -aliasof(m::Module, b) = Binding(m, module_name(m)) -aliasof(other, b) = b diff --git a/julia-0.6.3/share/julia/base/docs/core.jl b/julia-0.6.3/share/julia/base/docs/core.jl deleted file mode 100644 index 9b8cf34..0000000 --- a/julia-0.6.3/share/julia/base/docs/core.jl +++ /dev/null @@ -1,28 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -module CoreDocs - -import ..esc, ..push!, ..getindex, ..current_module, ..unsafe_load, ..Csize_t - -function doc!(str, ex) - ptr = unsafe_load(Core.Intrinsics.cglobal(:jl_filename, Ptr{UInt8})) - len = ccall(:strlen, Csize_t, (Ptr{UInt8},), ptr) - file = ccall(:jl_symbol_n, Any, (Ptr{UInt8}, Csize_t), ptr, len) - line = unsafe_load(Core.Intrinsics.cglobal(:jl_lineno, Int32)) # Cint - push!(DOCS, (current_module(), ex, str, file, line)) -end -const DOCS = Array{Any, 1}() - -isexpr(x, h) = isa(x, Expr) && x.head === h - -lazy_iterpolate(s::AbstractString) = Expr(:call, Core.svec, s) -lazy_iterpolate(x) = isexpr(x, :string) ? Expr(:call, Core.svec, x.args...) : x - -function docm(str, x) - out = esc(Expr(:call, doc!, lazy_iterpolate(str), Expr(:quote, x))) - isexpr(x, :module) ? Expr(:toplevel, out, esc(x)) : - isexpr(x, :call) ? out : Expr(:block, esc(x), out) -end -docm(x) = isexpr(x, :->) ? docm(x.args[1], x.args[2].args[2]) : error("invalid '@doc'.") - -end diff --git a/julia-0.6.3/share/julia/base/docs/helpdb.jl b/julia-0.6.3/share/julia/base/docs/helpdb.jl deleted file mode 100644 index 5e2a4fe..0000000 --- a/julia-0.6.3/share/julia/base/docs/helpdb.jl +++ /dev/null @@ -1,3 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -include(joinpath("helpdb", "Base.jl")) diff --git a/julia-0.6.3/share/julia/base/docs/helpdb/Base.jl b/julia-0.6.3/share/julia/base/docs/helpdb/Base.jl deleted file mode 100644 index 1328d51..0000000 --- a/julia-0.6.3/share/julia/base/docs/helpdb/Base.jl +++ /dev/null @@ -1,2744 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -# Base - -""" - fill!(A, x) - -Fill array `A` with the value `x`. If `x` is an object reference, all elements will refer to -the same object. `fill!(A, Foo())` will return `A` filled with the result of evaluating -`Foo()` once. - -# Examples -```jldoctest -julia> A = zeros(2,3) -2×3 Array{Float64,2}: - 0.0 0.0 0.0 - 0.0 0.0 0.0 - -julia> fill!(A, 2.) -2×3 Array{Float64,2}: - 2.0 2.0 2.0 - 2.0 2.0 2.0 - -julia> a = [1, 1, 1]; A = fill!(Vector{Vector{Int}}(3), a); a[1] = 2; A -3-element Array{Array{Int64,1},1}: - [2, 1, 1] - [2, 1, 1] - [2, 1, 1] - -julia> x = 0; f() = (global x += 1; x); fill!(Vector{Int}(3), f()) -3-element Array{Int64,1}: - 1 - 1 - 1 -``` -""" -fill! - -""" - read!(stream::IO, array::Union{Array, BitArray}) - read!(filename::AbstractString, array::Union{Array, BitArray}) - -Read binary data from an I/O stream or file, filling in `array`. -""" -read! - -""" - pointer(array [, index]) - -Get the native address of an array or string element. Be careful to ensure that a Julia -reference to `a` exists as long as this pointer will be used. This function is "unsafe" like -`unsafe_convert`. - -Calling `Ref(array[, index])` is generally preferable to this function. -""" -pointer - -""" - precision(num::AbstractFloat) - -Get the precision of a floating point number, as defined by the effective number of bits in -the mantissa. -""" -precision - -""" - -(x) - -Unary minus operator. -""" --(x) - -""" - -(x, y) - -Subtraction operator. -""" --(x, y) - -""" - bits(n) - -A string giving the literal bit representation of a number. - -# Example -```jldoctest -julia> bits(4) -"0000000000000000000000000000000000000000000000000000000000000100" - -julia> bits(2.2) -"0100000000000001100110011001100110011001100110011001100110011010" -``` -""" -bits - -""" - getindex(type[, elements...]) - -Construct a 1-d array of the specified type. This is usually called with the syntax -`Type[]`. Element values can be specified using `Type[a,b,c,...]`. - -# Example -```jldoctest -julia> Int8[1, 2, 3] -3-element Array{Int8,1}: - 1 - 2 - 3 - -julia> getindex(Int8, 1, 2, 3) -3-element Array{Int8,1}: - 1 - 2 - 3 -``` -""" -getindex(::Type, elements...) - -""" - getindex(A, inds...) - -Returns a subset of array `A` as specified by `inds`, where each `ind` may be an -`Int`, a `Range`, or a `Vector`. See the manual section on -[array indexing](@ref man-array-indexing) for details. - -# Examples -```jldoctest -julia> A = [1 2; 3 4] -2×2 Array{Int64,2}: - 1 2 - 3 4 - -julia> getindex(A, 1) -1 - -julia> getindex(A, [2, 1]) -2-element Array{Int64,1}: - 3 - 1 - -julia> getindex(A, 2:4) -3-element Array{Int64,1}: - 3 - 2 - 4 -``` -""" -getindex(::AbstractArray, inds...) - -""" - getindex(collection, key...) - -Retrieve the value(s) stored at the given key or index within a collection. The syntax -`a[i,j,...]` is converted by the compiler to `getindex(a, i, j, ...)`. - -# Example -```jldoctest -julia> A = Dict("a" => 1, "b" => 2) -Dict{String,Int64} with 2 entries: - "b" => 2 - "a" => 1 - -julia> getindex(A, "a") -1 -``` -""" -getindex(collection, key...) - -""" - cconvert(T,x) - -Convert `x` to a value of type `T`, typically by calling `convert(T,x)` - -In cases where `x` cannot be safely converted to `T`, unlike [`convert`](@ref), `cconvert` may -return an object of a type different from `T`, which however is suitable for -[`unsafe_convert`](@ref) to handle. - -Neither `convert` nor `cconvert` should take a Julia object and turn it into a `Ptr`. -""" -cconvert - -""" - assert(cond) - -Throw an [`AssertionError`](@ref) if `cond` is `false`. -Also available as the macro `@assert expr`. -""" -assert - -""" - sech(x) - -Compute the hyperbolic secant of `x` -""" -sech - -""" - unsafe_copy!(dest::Ptr{T}, src::Ptr{T}, N) - -Copy `N` elements from a source pointer to a destination, with no checking. The size of an -element is determined by the type of the pointers. - -The `unsafe` prefix on this function indicates that no validation is performed on the -pointers `dest` and `src` to ensure that they are valid. Incorrect usage may corrupt or -segfault your program, in the same manner as C. -""" -unsafe_copy!{T}(dest::Ptr{T}, src::Ptr{T}, N) - -""" - unsafe_copy!(dest::Array, do, src::Array, so, N) - -Copy `N` elements from a source array to a destination, starting at offset `so` in the -source and `do` in the destination (1-indexed). - -The `unsafe` prefix on this function indicates that no validation is performed to ensure -that N is inbounds on either array. Incorrect usage may corrupt or segfault your program, in -the same manner as C. -""" -unsafe_copy!(dest::Array, d, src::Array, so, N) - -""" - Float32(x [, mode::RoundingMode]) - -Create a Float32 from `x`. If `x` is not exactly representable then `mode` determines how -`x` is rounded. - -# Examples -```jldoctest -julia> Float32(1/3, RoundDown) -0.3333333f0 - -julia> Float32(1/3, RoundUp) -0.33333334f0 -``` - -See [`RoundingMode`](@ref) for available rounding modes. -""" -Float32(x) - -""" - Mmap.mmap(io::Union{IOStream,AbstractString,Mmap.AnonymousMmap}[, type::Type{Array{T,N}}, dims, offset]; grow::Bool=true, shared::Bool=true) - Mmap.mmap(type::Type{Array{T,N}}, dims) - -Create an `Array` whose values are linked to a file, using memory-mapping. This provides a -convenient way of working with data too large to fit in the computer's memory. - -The type is an `Array{T,N}` with a bits-type element of `T` and dimension `N` that -determines how the bytes of the array are interpreted. Note that the file must be stored in -binary format, and no format conversions are possible (this is a limitation of operating -systems, not Julia). - -`dims` is a tuple or single [`Integer`](@ref) specifying the size or length of the array. - -The file is passed via the stream argument, either as an open `IOStream` or filename string. -When you initialize the stream, use `"r"` for a "read-only" array, and `"w+"` to create a -new array used to write values to disk. - -If no `type` argument is specified, the default is `Vector{UInt8}`. - -Optionally, you can specify an offset (in bytes) if, for example, you want to skip over a -header in the file. The default value for the offset is the current stream position for an -`IOStream`. - -The `grow` keyword argument specifies whether the disk file should be grown to accommodate -the requested size of array (if the total file size is < requested array size). Write -privileges are required to grow the file. - -The `shared` keyword argument specifies whether the resulting `Array` and changes made to it -will be visible to other processes mapping the same file. - -For example, the following code - -```julia -# Create a file for mmapping -# (you could alternatively use mmap to do this step, too) -A = rand(1:20, 5, 30) -s = open("/tmp/mmap.bin", "w+") -# We'll write the dimensions of the array as the first two Ints in the file -write(s, size(A,1)) -write(s, size(A,2)) -# Now write the data -write(s, A) -close(s) - -# Test by reading it back in -s = open("/tmp/mmap.bin") # default is read-only -m = read(s, Int) -n = read(s, Int) -A2 = Mmap.mmap(s, Matrix{Int}, (m,n)) -``` - -creates a `m`-by-`n` `Matrix{Int}`, linked to the file associated with stream `s`. - -A more portable file would need to encode the word size -- 32 bit or 64 bit -- and endianness -information in the header. In practice, consider encoding binary data using standard formats -like HDF5 (which can be used with memory-mapping). -""" -Mmap.mmap(io, ::Type, dims, offset) - -""" - Mmap.mmap(io, BitArray, [dims, offset]) - -Create a `BitArray` whose values are linked to a file, using memory-mapping; it has the same -purpose, works in the same way, and has the same arguments, as [`mmap`](@ref Mmap.mmap), but -the byte representation is different. - -**Example**: `B = Mmap.mmap(s, BitArray, (25,30000))` - -This would create a 25-by-30000 `BitArray`, linked to the file associated with stream `s`. -""" -Mmap.mmap(io, ::BitArray, dims = ?, offset = ?) - -""" - filter!(function, collection) - -Update `collection`, removing elements for which `function` is `false`. -For associative collections, the function is passed two arguments (key and value). - -# Example -```jldoctest -julia> filter!(isodd, collect(1:10)) -5-element Array{Int64,1}: - 1 - 3 - 5 - 7 - 9 -``` -""" -filter! - -""" - sizeof(T) - -Size, in bytes, of the canonical binary representation of the given DataType `T`, if any. - -# Examples -```jldoctest -julia> sizeof(Float32) -4 - -julia> sizeof(Complex128) -16 -``` - -If `T` does not have a specific size, an error is thrown. - -```jldoctest -julia> sizeof(Base.LinAlg.LU) -ERROR: argument is an abstract type; size is indeterminate -Stacktrace: - [1] sizeof(::Type{T} where T) at ./essentials.jl:159 -``` -""" -sizeof(::Type) - -""" - ReadOnlyMemoryError() - -An operation tried to write to memory that is read-only. -""" -ReadOnlyMemoryError - -""" - ceil([T,] x, [digits, [base]]) - -`ceil(x)` returns the nearest integral value of the same type as `x` that is greater than or -equal to `x`. - -`ceil(T, x)` converts the result to type `T`, throwing an `InexactError` if the value is not -representable. - -`digits` and `base` work as for [`round`](@ref). -""" -ceil - -""" - oftype(x, y) - -Convert `y` to the type of `x` (`convert(typeof(x), y)`). -""" -oftype - -""" - push!(collection, items...) -> collection - -Insert one or more `items` at the end of `collection`. - -# Example -```jldoctest -julia> push!([1, 2, 3], 4, 5, 6) -6-element Array{Int64,1}: - 1 - 2 - 3 - 4 - 5 - 6 -``` - -Use [`append!`](@ref) to add all the elements of another collection to -`collection`. The result of the preceding example is equivalent to `append!([1, 2, 3], [4, -5, 6])`. -""" -push! - -""" - promote(xs...) - -Convert all arguments to their common promotion type (if any), and return them all (as a tuple). - -# Example -```jldoctest -julia> promote(Int8(1), Float16(4.5), Float32(4.1)) -(1.0f0, 4.5f0, 4.1f0) -``` -""" -promote - -""" - fd(stream) - -Returns the file descriptor backing the stream or file. Note that this function only applies -to synchronous `File`'s and `IOStream`'s not to any of the asynchronous streams. -""" -fd - - -""" - ones([A::AbstractArray,] [T=eltype(A)::Type,] [dims=size(A)::Tuple]) - -Create an array of all ones with the same layout as `A`, element type `T` and size `dims`. -The `A` argument can be skipped, which behaves like `Array{Float64,0}()` was passed. -For convenience `dims` may also be passed in variadic form. - -# Examples -```jldoctest -julia> ones(Complex128, 2, 3) -2×3 Array{Complex{Float64},2}: - 1.0+0.0im 1.0+0.0im 1.0+0.0im - 1.0+0.0im 1.0+0.0im 1.0+0.0im - -julia> ones(1,2) -1×2 Array{Float64,2}: - 1.0 1.0 - -julia> A = [1 2; 3 4] -2×2 Array{Int64,2}: - 1 2 - 3 4 - -julia> ones(A) -2×2 Array{Int64,2}: - 1 1 - 1 1 - -julia> ones(A, Float64) -2×2 Array{Float64,2}: - 1.0 1.0 - 1.0 1.0 - -julia> ones(A, Bool, (3,)) -3-element Array{Bool,1}: - true - true - true -``` -See also [`zeros`](@ref), [`similar`](@ref). -""" -ones - -""" - randsubseq!(S, A, p) - -Like [`randsubseq`](@ref), but the results are stored in `S` -(which is resized as needed). -""" -randsubseq! - -""" - redisplay(x) - redisplay(d::Display, x) - redisplay(mime, x) - redisplay(d::Display, mime, x) - -By default, the `redisplay` functions simply call [`display`](@ref). -However, some display backends may override `redisplay` to modify an existing -display of `x` (if any). -Using `redisplay` is also a hint to the backend that `x` may be redisplayed -several times, and the backend may choose to defer the display until -(for example) the next interactive prompt. -""" -redisplay - -""" - searchsorted(a, x, [by=,] [lt=,] [rev=false]) - -Returns the range of indices of `a` which compare as equal to `x` (using binary search) -according to the order specified by the `by`, `lt` and `rev` keywords, assuming that `a` -is already sorted in that order. Returns an empty range located at the insertion point -if `a` does not contain values equal to `x`. - -# Examples - -```jldoctest -julia> a = [4, 3, 2, 1] -4-element Array{Int64,1}: - 4 - 3 - 2 - 1 - -julia> searchsorted(a, 4) -5:4 - -julia> searchsorted(a, 4, rev=true) -1:1 -``` -""" -searchsorted - -""" - /(x, y) - -Right division operator: multiplication of `x` by the inverse of `y` on the right. Gives -floating-point results for integer arguments. -""" -Base.:(/) - -""" - dump(x) - -Show every part of the representation of a value. -""" -dump - -""" - isinteractive() -> Bool - -Determine whether Julia is running an interactive session. -""" -isinteractive - -""" - display(x) - display(d::Display, x) - display(mime, x) - display(d::Display, mime, x) - -Display `x` using the topmost applicable display in the display stack, typically using the -richest supported multimedia output for `x`, with plain-text [`STDOUT`](@ref) output as a fallback. -The `display(d, x)` variant attempts to display `x` on the given display `d` only, throwing -a `MethodError` if `d` cannot display objects of this type. - -There are also two variants with a `mime` argument (a MIME type string, such as -`"image/png"`), which attempt to display `x` using the requested MIME type *only*, throwing -a `MethodError` if this type is not supported by either the display(s) or by `x`. With these -variants, one can also supply the "raw" data in the requested MIME type by passing -`x::AbstractString` (for MIME types with text-based storage, such as text/html or -application/postscript) or `x::Vector{UInt8}` (for binary MIME types). -""" -display - -""" - @spawnat - -Accepts two arguments, `p` and an expression. A closure is created around the expression and -run asynchronously on process `p`. Returns a [`Future`](@ref) to the result. -""" -:@spawnat - -""" - print_shortest(io, x) - -Print the shortest possible representation, with the minimum number of consecutive non-zero -digits, of number `x`, ensuring that it would parse to the exact same number. -""" -print_shortest - -""" - tuple(xs...) - -Construct a tuple of the given objects. - -# Example -```jldoctest -julia> tuple(1, 'a', pi) -(1, 'a', π = 3.1415926535897...) -``` -""" -tuple - -""" - eachmatch(r::Regex, s::AbstractString[, overlap::Bool=false]) - -Search for all matches of a the regular expression `r` in `s` and return a iterator over the -matches. If overlap is `true`, the matching sequences are allowed to overlap indices in the -original string, otherwise they must be from distinct character ranges. -""" -eachmatch - -""" - num2hex(f) - -Get a hexadecimal string of the binary representation of a floating point number. - -# Example -```jldoctest -julia> num2hex(2.2) -"400199999999999a" -``` -""" -num2hex - -""" - truncate(file,n) - -Resize the file or buffer given by the first argument to exactly `n` bytes, filling -previously unallocated space with '\\0' if the file or buffer is grown. -""" -truncate - -""" - exp10(x) - -Compute ``10^x``. - -# Examples -```jldoctest -julia> exp10(2) -100.0 - -julia> exp10(0.2) -1.5848931924611136 -``` -""" -exp10 - -""" - &(x, y) - -Bitwise and. - -# Examples -```jldoctest -julia> 4 & 10 -0 - -julia> 4 & 12 -4 -``` -""" -& - -""" - select(v, k, [by=,] [lt=,] [rev=false]) - -Variant of [`select!`](@ref) which copies `v` before partially sorting it, thereby returning the -same thing as `select!` but leaving `v` unmodified. -""" -select - -""" - accept(server[,client]) - -Accepts a connection on the given server and returns a connection to the client. An -uninitialized client stream may be provided, in which case it will be used instead of -creating a new stream. -""" -accept - -""" - Mmap.Anonymous(name, readonly, create) - -Create an `IO`-like object for creating zeroed-out mmapped-memory that is not tied to a file -for use in `Mmap.mmap`. Used by `SharedArray` for creating shared memory arrays. -""" -Mmap.Anonymous - -""" - floor([T,] x, [digits, [base]]) - -`floor(x)` returns the nearest integral value of the same type as `x` that is less than or -equal to `x`. - -`floor(T, x)` converts the result to type `T`, throwing an `InexactError` if the value is -not representable. - -`digits` and `base` work as for [`round`](@ref). -""" -floor - -""" - ErrorException(msg) - -Generic error type. The error message, in the `.msg` field, may provide more specific details. -""" -ErrorException - -""" - reverse(v [, start=1 [, stop=length(v) ]] ) - -Return a copy of `v` reversed from start to stop. - -# Examples -```jldoctest -julia> A = collect(1:5) -5-element Array{Int64,1}: - 1 - 2 - 3 - 4 - 5 - -julia> reverse(A) -5-element Array{Int64,1}: - 5 - 4 - 3 - 2 - 1 - -julia> reverse(A, 1, 4) -5-element Array{Int64,1}: - 4 - 3 - 2 - 1 - 5 - -julia> reverse(A, 3, 5) -5-element Array{Int64,1}: - 1 - 2 - 5 - 4 - 3 -``` -""" -reverse - -""" - reverse!(v [, start=1 [, stop=length(v) ]]) -> v - -In-place version of [`reverse`](@ref). -""" -reverse! - -""" - UndefRefError() - -The item or field is not defined for the given object. -""" -UndefRefError - -""" - append!(collection, collection2) -> collection. - -Add the elements of `collection2` to the end of `collection`. - -# Examples -```jldoctest -julia> append!([1],[2,3]) -3-element Array{Int64,1}: - 1 - 2 - 3 - -julia> append!([1, 2, 3], [4, 5, 6]) -6-element Array{Int64,1}: - 1 - 2 - 3 - 4 - 5 - 6 -``` - -Use [`push!`](@ref) to add individual items to `collection` which are not already -themselves in another collection. The result is of the preceding example is equivalent to -`push!([1, 2, 3], 4, 5, 6)`. -""" -append! - -""" - skip(s, offset) - -Seek a stream relative to the current position. -""" -skip - -""" - setdiff!(s, iterable) - -Remove each element of `iterable` from set `s` in-place. -""" -setdiff! - -""" - copysign(x, y) -> z - -Return `z` which has the magnitude of `x` and the same sign as `y`. - -# Examples -```jldoctest -julia> copysign(1, -2) --1 - -julia> copysign(-1, 2) -1 -``` -""" -copysign - -""" - @show - -Show an expression and result, returning the result. -""" -:@show - -""" - showcompact(x) - -Show a compact representation of a value. - -This is used for printing array elements without repeating type information (which would -be redundant with that printed once for the whole array), and without line breaks inside -the representation of an element. - -To offer a compact representation different from its standard one, a custom type should -test `get(io, :compact, false)` in its normal `show` method. -""" -showcompact - -""" - getfield(value, name::Symbol) - -Extract a named field from a `value` of composite type. The syntax `a.b` calls -`getfield(a, :b)`. - -# Example -```jldoctest -julia> a = 1//2 -1//2 - -julia> getfield(a, :num) -1 -``` -""" -getfield - -""" - select!(v, k, [by=,] [lt=,] [rev=false]) - -Partially sort the vector `v` in place, according to the order specified by `by`, `lt` and -`rev` so that the value at index `k` (or range of adjacent values if `k` is a range) occurs -at the position where it would appear if the array were fully sorted via a non-stable -algorithm. If `k` is a single index, that value is returned; if `k` is a range, an array of -values at those indices is returned. Note that `select!` does not fully sort the input -array. - -# Examples - -```jldoctest -julia> a = [1, 2, 4, 3, 4] -5-element Array{Int64,1}: - 1 - 2 - 4 - 3 - 4 - -julia> select!(a, 4) -4 - -julia> a -5-element Array{Int64,1}: - 1 - 2 - 3 - 4 - 4 - -julia> a = [1, 2, 4, 3, 4] -5-element Array{Int64,1}: - 1 - 2 - 4 - 3 - 4 - -julia> select!(a, 4, rev=true) -2 - -julia> a -5-element Array{Int64,1}: - 4 - 4 - 3 - 2 - 1 -``` -""" -select! - -""" - randstring([rng,] len=8) - -Create a random ASCII string of length `len`, consisting of upper- and -lower-case letters and the digits 0-9. The optional `rng` argument -specifies a random number generator, see [Random Numbers](@ref). - -# Example - -```jldoctest -julia> rng = MersenneTwister(1234); - -julia> randstring(rng, 4) -"mbDd" -``` -""" -randstring - -""" - Float64(x [, mode::RoundingMode]) - -Create a Float64 from `x`. If `x` is not exactly representable then `mode` determines how -`x` is rounded. - -# Examples -```jldoctest -julia> Float64(pi, RoundDown) -3.141592653589793 - -julia> Float64(pi, RoundUp) -3.1415926535897936 -``` - -See [`RoundingMode`](@ref) for available rounding modes. -""" -Float64(x) - -""" - union(s1,s2...) - ∪(s1,s2...) - -Construct the union of two or more sets. Maintains order with arrays. - -# Examples -```jldoctest -julia> union([1, 2], [3, 4]) -4-element Array{Int64,1}: - 1 - 2 - 3 - 4 - -julia> union([1, 2], [2, 4]) -3-element Array{Int64,1}: - 1 - 2 - 4 - -julia> union([4, 2], [1, 2]) -3-element Array{Int64,1}: - 4 - 2 - 1 -``` -""" -union - -""" - realmax(T) - -The highest finite value representable by the given floating-point DataType `T`. - -# Examples -```jldoctest -julia> realmax(Float16) -Float16(6.55e4) - -julia> realmax(Float32) -3.4028235f38 -``` -""" -realmax - -""" - serialize(stream, value) - -Write an arbitrary value to a stream in an opaque format, such that it can be read back by -[`deserialize`](@ref). The read-back value will be as identical as possible to the original. In -general, this process will not work if the reading and writing are done by different -versions of Julia, or an instance of Julia with a different system image. `Ptr` values are -serialized as all-zero bit patterns (`NULL`). -""" -serialize - -""" - typemin(T) - -The lowest value representable by the given (real) numeric DataType `T`. - -# Examples -```jldoctest -julia> typemin(Float16) --Inf16 - -julia> typemin(Float32) --Inf32 -``` -""" -typemin - -""" - typeof(x) - -Get the concrete type of `x`. -""" -typeof - -""" - trunc([T,] x, [digits, [base]]) - -`trunc(x)` returns the nearest integral value of the same type as `x` whose absolute value -is less than or equal to `x`. - -`trunc(T, x)` converts the result to type `T`, throwing an `InexactError` if the value is -not representable. - -`digits` and `base` work as for [`round`](@ref). -""" -trunc - -""" - unsafe_convert(T,x) - -Convert `x` to a value of type `T` - -In cases where [`convert`](@ref) would need to take a Julia object -and turn it into a `Ptr`, this function should be used to define and perform -that conversion. - -Be careful to ensure that a Julia reference to `x` exists as long as the result of this -function will be used. Accordingly, the argument `x` to this function should never be an -expression, only a variable name or field reference. For example, `x=a.b.c` is acceptable, -but `x=[a,b,c]` is not. - -The `unsafe` prefix on this function indicates that using the result of this function after -the `x` argument to this function is no longer accessible to the program may cause undefined -behavior, including program corruption or segfaults, at any later time. -""" -unsafe_convert - -""" - seek(s, pos) - -Seek a stream to the given position. -""" -seek - -""" - popdisplay() - popdisplay(d::Display) - -Pop the topmost backend off of the display-backend stack, or the topmost copy of `d` in the -second variant. -""" -popdisplay - -""" - cglobal((symbol, library) [, type=Void]) - -Obtain a pointer to a global variable in a C-exported shared library, specified exactly as -in [`ccall`](@ref). -Returns a `Ptr{Type}`, defaulting to `Ptr{Void}` if no `Type` argument is -supplied. -The values can be read or written by [`unsafe_load`](@ref) or [`unsafe_store!`](@ref), -respectively. -""" -cglobal - -""" - endof(collection) -> Integer - -Returns the last index of the collection. - -# Example -```jldoctest -julia> endof([1,2,4]) -3 -``` -""" -endof - -""" - next(iter, state) -> item, state - -For a given iterable object and iteration state, return the current item and the next iteration state. - -# Examples -```jldoctest -julia> next(1:5, 3) -(3, 4) - -julia> next(1:5, 5) -(5, 6) -``` -""" -next - -""" - sizehint!(s, n) - -Suggest that collection `s` reserve capacity for at least `n` elements. This can improve performance. -""" -sizehint! - -""" - OutOfMemoryError() - -An operation allocated too much memory for either the system or the garbage collector to -handle properly. -""" -OutOfMemoryError - -""" - finalize(x) - -Immediately run finalizers registered for object `x`. -""" -finalize - -""" - BoundsError([a],[i]) - -An indexing operation into an array, `a`, tried to access an out-of-bounds element, `i`. -""" -BoundsError - -""" - invoke(f, types <: Tuple, args...) - -Invoke a method for the given generic function matching the specified types, on -the specified arguments. The arguments must be compatible with the specified types. This -allows invoking a method other than the most specific matching method, which is useful when -the behavior of a more general definition is explicitly needed (often as part of the -implementation of a more specific method of the same function). -""" -invoke - -""" - parse(str, start; greedy=true, raise=true) - -Parse the expression string and return an expression (which could later be passed to eval -for execution). `start` is the index of the first character to start parsing. If `greedy` is -`true` (default), `parse` will try to consume as much input as it can; otherwise, it will -stop as soon as it has parsed a valid expression. Incomplete but otherwise syntactically -valid expressions will return `Expr(:incomplete, "(error message)")`. If `raise` is `true` -(default), syntax errors other than incomplete expressions will raise an error. If `raise` -is `false`, `parse` will return an expression that will raise an error upon evaluation. - -```jldoctest -julia> parse("x = 3, y = 5", 7) -(:(y = 5), 13) - -julia> parse("x = 3, y = 5", 5) -(:((3, y) = 5), 13) -``` -""" -parse(str, start) - -""" - parse(str; raise=true) - -Parse the expression string greedily, returning a single expression. An error is thrown if -there are additional characters after the first expression. If `raise` is `true` (default), -syntax errors will raise an error; otherwise, `parse` will return an expression that will -raise an error upon evaluation. - -```jldoctest -julia> parse("x = 3") -:(x = 3) - -julia> parse("x = ") -:($(Expr(:incomplete, "incomplete: premature end of input"))) - -julia> parse("1.0.2") -ERROR: ParseError("invalid numeric constant \\\"1.0.\\\"") -Stacktrace: -[...] - -julia> parse("1.0.2"; raise = false) -:($(Expr(:error, "invalid numeric constant \"1.0.\""))) -``` -""" -parse(str) - -""" - parse(type, str, [base]) - -Parse a string as a number. If the type is an integer type, then a base can be specified -(the default is 10). If the type is a floating point type, the string is parsed as a decimal -floating point number. If the string does not contain a valid number, an error is raised. - -```jldoctest -julia> parse(Int, "1234") -1234 - -julia> parse(Int, "1234", 5) -194 - -julia> parse(Int, "afc", 16) -2812 - -julia> parse(Float64, "1.2e-3") -0.0012 -``` -""" -parse(T::Type, str, base=Int) - -""" - position(s) - -Get the current position of a stream. -""" -position - -""" - selectperm(v, k, [alg=,] [by=,] [lt=,] [rev=false]) - -Return a partial permutation of the vector `v`, according to the order specified by -`by`, `lt` and `rev`, so that `v[output]` returns the first `k` (or range of adjacent values -if `k` is a range) values of a fully sorted version of `v`. If `k` is a single index -(Integer), an array of the first `k` indices is returned; if `k` is a range, an array of -those indices is returned. Note that the handling of integer values for `k` is different -from [`select`](@ref) in that it returns a vector of `k` elements instead of just the `k` th -element. Also note that this is equivalent to, but more efficient than, calling -`sortperm(...)[k]`. -""" -selectperm - -""" - reinterpret(type, A) - -Change the type-interpretation of a block of memory. -For arrays, this constructs an array with the same binary data as the given -array, but with the specified element type. -For example, -`reinterpret(Float32, UInt32(7))` interprets the 4 bytes corresponding to `UInt32(7)` as a -[`Float32`](@ref). - -!!! warning - - It is not allowed to `reinterpret` an array to an element type with a larger alignment then - the alignment of the array. For a normal `Array`, this is the alignment of its element type. - For a reinterpreted array, this is the alignment of the `Array` it was reinterpreted from. - For example, `reinterpret(UInt32, UInt8[0, 0, 0, 0])` is not allowed but - `reinterpret(UInt32, reinterpret(UInt8, Float32[1.0]))` is allowed. - -# Examples -```jldoctest -julia> reinterpret(Float32, UInt32(7)) -1.0f-44 - -julia> reinterpret(Float32, UInt32[1 2 3 4 5]) -1×5 Array{Float32,2}: - 1.4013f-45 2.8026f-45 4.2039f-45 5.60519f-45 7.00649f-45 -``` -""" -reinterpret - -""" - ~(x) - -Bitwise not. - -# Examples -```jldoctest -julia> ~4 --5 - -julia> ~10 --11 - -julia> ~true -false -``` -""" -~ - -""" - bswap(n) - -Byte-swap an integer. Flip the bits of its binary representation. - -# Examples -```jldoctest -julia> a = bswap(4) -288230376151711744 - -julia> bswap(a) -4 - -julia> bin(1) -"1" - -julia> bin(bswap(1)) -"100000000000000000000000000000000000000000000000000000000" -``` -""" -bswap - -""" - maxintfloat(T) - -The largest integer losslessly representable by the given floating-point DataType `T`. -""" -maxintfloat(T) - -""" - maxintfloat(T, S) - -The largest integer losslessly representable by the given floating-point DataType `T` that -also does not exceed the maximum integer representable by the integer DataType `S`. -""" -maxintfloat(T, S) - -""" - delete!(collection, key) - -Delete the mapping for the given key in a collection, and return the collection. - -# Example -```jldoctest -julia> d = Dict("a"=>1, "b"=>2) -Dict{String,Int64} with 2 entries: - "b" => 2 - "a" => 1 - -julia> delete!(d, "b") -Dict{String,Int64} with 1 entry: - "a" => 1 -``` -""" -delete! - - -""" - searchsortedfirst(a, x, [by=,] [lt=,] [rev=false]) - -Returns the index of the first value in `a` greater than or equal to `x`, according to the -specified order. Returns `length(a)+1` if `x` is greater than all values in `a`. -`a` is assumed to be sorted. - -# Examples - -```jldoctest -julia> searchsortedfirst([1, 2, 4, 5, 14], 4) -3 - -julia> searchsortedfirst([1, 2, 4, 5, 14], 4, rev=true) -1 - -julia> searchsortedfirst([1, 2, 4, 5, 14], 15) -6 -``` -""" -searchsortedfirst - -""" - big(x) - -Convert a number to a maximum precision representation (typically [`BigInt`](@ref) or -`BigFloat`). See [`BigFloat`](@ref) for information about some pitfalls with floating-point numbers. -""" -big - -""" - quit() - -Quit the program indicating that the processes completed successfully. This function calls -`exit(0)` (see [`exit`](@ref)). -""" -quit - -""" - typejoin(T, S) - -Compute a type that contains both `T` and `S`. -""" -typejoin - -""" - selectperm!(ix, v, k, [alg=,] [by=,] [lt=,] [rev=false,] [initialized=false]) - -Like [`selectperm`](@ref), but accepts a preallocated index vector `ix`. If `initialized` is `false` -(the default), ix is initialized to contain the values `1:length(ix)`. -""" -selectperm! - -""" - precompile(f,args::Tuple{Vararg{Any}}) - -Compile the given function `f` for the argument tuple (of types) `args`, but do not execute it. -""" -precompile - -""" - cot(x) - -Compute the cotangent of `x`, where `x` is in radians. -""" -cot - -""" - get(collection, key, default) - -Return the value stored for the given key, or the given default value if no mapping for the -key is present. - -# Examples -```jldoctest -julia> d = Dict("a"=>1, "b"=>2); - -julia> get(d, "a", 3) -1 - -julia> get(d, "c", 3) -3 -``` -""" -get(collection,key,default) - -""" - get(f::Function, collection, key) - -Return the value stored for the given key, or if no mapping for the key is present, return -`f()`. Use [`get!`](@ref) to also store the default value in the dictionary. - -This is intended to be called using `do` block syntax - -```julia -get(dict, key) do - # default value calculated here - time() -end -``` -""" -get - -""" - Mmap.sync!(array) - -Forces synchronization between the in-memory version of a memory-mapped `Array` or -`BitArray` and the on-disk version. -""" -Mmap.sync! - -""" - csc(x) - -Compute the cosecant of `x`, where `x` is in radians. -""" -csc - -""" - hash(x[, h::UInt]) - -Compute an integer hash code such that `isequal(x,y)` implies `hash(x)==hash(y)`. The -optional second argument `h` is a hash code to be mixed with the result. - -New types should implement the 2-argument form, typically by calling the 2-argument `hash` -method recursively in order to mix hashes of the contents with each other (and with `h`). -Typically, any type that implements `hash` should also implement its own `==` (hence -`isequal`) to guarantee the property mentioned above. -""" -hash - -""" - read(stream::IO, T) - -Read a single value of type `T` from `stream`, in canonical binary representation. -""" -read(stream, t) - -""" - shift!(collection) -> item - -Remove the first `item` from `collection`. - -# Example -```jldoctest -julia> A = [1, 2, 3, 4, 5, 6] -6-element Array{Int64,1}: - 1 - 2 - 3 - 4 - 5 - 6 - -julia> shift!(A) -1 - -julia> A -5-element Array{Int64,1}: - 2 - 3 - 4 - 5 - 6 -``` -""" -shift! - -""" - spawn(command) - -Run a command object asynchronously, returning the resulting `Process` object. -""" -spawn - -""" - isdefined([m::Module,] s::Symbol) - isdefined(object, s::Symbol) - isdefined(object, index::Int) - -Tests whether an assignable location is defined. The arguments can be a module and a symbol -or a composite object and field name (as a symbol) or index. With a single symbol argument, -tests whether a global variable with that name is defined in [`current_module()`](@ref). -""" -isdefined - -""" - cotd(x) - -Compute the cotangent of `x`, where `x` is in degrees. -""" -cotd - -""" - wait([x]) - -Block the current task until some event occurs, depending on the type of the argument: - -* [`RemoteChannel`](@ref) : Wait for a value to become available on the specified remote - channel. -* [`Future`](@ref) : Wait for a value to become available for the specified future. -* [`Channel`](@ref): Wait for a value to be appended to the channel. -* [`Condition`](@ref): Wait for [`notify`](@ref) on a condition. -* `Process`: Wait for a process or process chain to exit. The `exitcode` field of a process - can be used to determine success or failure. -* [`Task`](@ref): Wait for a `Task` to finish, returning its result value. If the task fails - with an exception, the exception is propagated (re-thrown in the task that called `wait`). -* `RawFD`: Wait for changes on a file descriptor (see [`poll_fd`](@ref) for keyword - arguments and return code) - -If no argument is passed, the task blocks for an undefined period. A task can only be -restarted by an explicit call to [`schedule`](@ref) or [`yieldto`](@ref). - -Often `wait` is called within a `while` loop to ensure a waited-for condition is met before -proceeding. -""" -wait - -""" - atexit(f) - -Register a zero-argument function `f()` to be called at process exit. `atexit()` hooks are -called in last in first out (LIFO) order and run before object finalizers. -""" -atexit - -""" - copy(x) - -Create a shallow copy of `x`: the outer structure is copied, but not all internal values. -For example, copying an array produces a new array with identically-same elements as the -original. -""" -copy - -""" - isempty(collection) -> Bool - -Determine whether a collection is empty (has no elements). - -# Examples -```jldoctest -julia> isempty([]) -true - -julia> isempty([1 2 3]) -false -``` -""" -isempty - -""" - hex2num(str) - -Convert a hexadecimal string to the floating point number it represents. -""" -hex2num - -""" - InexactError() - -Type conversion cannot be done exactly. -""" -InexactError - -""" - typemax(T) - -The highest value representable by the given (real) numeric `DataType`. -""" -typemax - -""" - DomainError() - -The arguments to a function or constructor are outside the valid domain. -""" -DomainError - -""" - IntSet([itr]) - -Construct a sorted set of positive `Int`s generated by the given iterable object, or an -empty set. Implemented as a bit string, and therefore designed for dense integer sets. Only -`Int`s greater than 0 can be stored. If the set will be sparse (for example holding a few -very large integers), use [`Set`](@ref) instead. -""" -IntSet - -""" - Task(func) - -Create a `Task` (i.e. coroutine) to execute the given function (which must be -callable with no arguments). The task exits when this function returns. - -# Example -```jldoctest -julia> a() = det(rand(1000, 1000)); - -julia> b = Task(a); -``` - -In this example, `b` is a runnable `Task` that hasn't started yet. -""" -Task - -""" - pushdisplay(d::Display) - -Pushes a new display `d` on top of the global display-backend stack. Calling `display(x)` or -`display(mime, x)` will display `x` on the topmost compatible backend in the stack (i.e., -the topmost backend that does not throw a `MethodError`). -""" -pushdisplay - -""" - StackOverflowError() - -The function call grew beyond the size of the call stack. This usually happens when a call -recurses infinitely. -""" -StackOverflowError - -""" - ==(x, y) - -Generic equality operator, giving a single [`Bool`](@ref) result. Falls back to `===`. -Should be implemented for all types with a notion of equality, based on the abstract value -that an instance represents. For example, all numeric types are compared by numeric value, -ignoring type. Strings are compared as sequences of characters, ignoring encoding. - -Follows IEEE semantics for floating-point numbers. - -Collections should generally implement `==` by calling `==` recursively on all contents. - -New numeric types should implement this function for two arguments of the new type, and -handle comparison to other types via promotion rules where possible. -""" -Base.:(==) - -""" - seekstart(s) - -Seek a stream to its beginning. -""" -seekstart - -""" - nfields(x::DataType) -> Int - -Get the number of fields of a `DataType`. -""" -nfields - -""" - show(stream, mime, x) - -The `display` functions ultimately call `show` in order to write an object `x` as a -given `mime` type to a given I/O `stream` (usually a memory buffer), if possible. In order -to provide a rich multimedia representation of a user-defined type `T`, it is only necessary -to define a new `show` method for `T`, via: `show(stream, ::MIME"mime", x::T) = ...`, -where `mime` is a MIME-type string and the function body calls `write` (or similar) to write -that representation of `x` to `stream`. (Note that the `MIME""` notation only supports -literal strings; to construct `MIME` types in a more flexible manner use -`MIME{Symbol("")}`.) - -For example, if you define a `MyImage` type and know how to write it to a PNG file, you -could define a function `show(stream, ::MIME"image/png", x::MyImage) = ...` to allow -your images to be displayed on any PNG-capable `Display` (such as IJulia). As usual, be sure -to `import Base.show` in order to add new methods to the built-in Julia function -`show`. - -The default MIME type is `MIME"text/plain"`. There is a fallback definition for `text/plain` -output that calls `show` with 2 arguments. Therefore, this case should be handled by -defining a 2-argument `show(stream::IO, x::MyType)` method. - -Technically, the `MIME"mime"` macro defines a singleton type for the given `mime` string, -which allows us to exploit Julia's dispatch mechanisms in determining how to display objects -of any given type. - -The first argument to `show` can be an [`IOContext`](@ref) specifying output format properties. -See [`IOContext`](@ref) for details. -""" -show(stream, mime, x) - -""" - mean!(r, v) - -Compute the mean of `v` over the singleton dimensions of `r`, and write results to `r`. -""" -mean! - -""" - isless(x, y) - -Test whether `x` is less than `y`, according to a canonical total order. Values that are -normally unordered, such as `NaN`, are ordered in an arbitrary but consistent fashion. This -is the default comparison used by [`sort`](@ref). Non-numeric types with a canonical total order -should implement this function. Numeric types only need to implement it if they have special -values such as `NaN`. -""" -isless - -""" - showerror(io, e) - -Show a descriptive representation of an exception object. -""" -showerror - -""" - error(message::AbstractString) - -Raise an `ErrorException` with the given message. -""" -error - -""" - readcsv(source, [T::Type]; options...) - -Equivalent to [`readdlm`](@ref) with `delim` set to comma, and type optionally defined by `T`. -""" -readcsv - -""" - UndefVarError(var::Symbol) - -A symbol in the current scope is not defined. -""" -UndefVarError - -""" - gc() - -Perform garbage collection. This should not generally be used. -""" -gc - -""" - unsafe_trunc(T, x) - -`unsafe_trunc(T, x)` returns the nearest integral value of type `T` whose absolute value is -less than or equal to `x`. If the value is not representable by `T`, an arbitrary value will -be returned. -""" -unsafe_trunc - -""" - parent(A) - -Returns the "parent array" of an array view type (e.g., `SubArray`), or the array itself if -it is not a view. -""" -parent - -""" - gc_enable(on::Bool) - -Control whether garbage collection is enabled using a boolean argument (`true` for enabled, -`false` for disabled). Returns previous GC state. Disabling garbage collection should be -used only with extreme caution, as it can cause memory use to grow without bound. -""" -gc_enable - -""" - secd(x) - -Compute the secant of `x`, where `x` is in degrees. -""" -secd - -""" - OverflowError() - -The result of an expression is too large for the specified type and will cause a wraparound. -""" -OverflowError - -""" - object_id(x) - -Get a hash value for `x` based on object identity. `object_id(x)==object_id(y)` if `x === y`. -""" -object_id - -""" - cat(dims, A...) - -Concatenate the input arrays along the specified dimensions in the iterable `dims`. For -dimensions not in `dims`, all input arrays should have the same size, which will also be the -size of the output array along that dimension. For dimensions in `dims`, the size of the -output array is the sum of the sizes of the input arrays along that dimension. If `dims` is -a single number, the different arrays are tightly stacked along that dimension. If `dims` is -an iterable containing several dimensions, this allows one to construct block diagonal -matrices and their higher-dimensional analogues by simultaneously increasing several -dimensions for every new input array and putting zero blocks elsewhere. For example, -`cat([1,2], matrices...)` builds a block diagonal matrix, i.e. a block matrix with -`matrices[1]`, `matrices[2]`, ... as diagonal blocks and matching zero blocks away from the -diagonal. -""" -cat - -""" - show(x) - -Write an informative text representation of a value to the current output stream. New types -should overload `show(io, x)` where the first argument is a stream. The representation used -by `show` generally includes Julia-specific formatting and type information. -""" -show(x) - -""" - issubtype(type1, type2) - -Return `true` if and only if all values of `type1` are also of `type2`. Can also be written -using the `<:` infix operator as `type1 <: type2`. - -# Examples -```jldoctest -julia> issubtype(Int8, Int32) -false - -julia> Int8 <: Integer -true -``` -""" -issubtype(type1, type2) - -""" - finalizer(x, f) - -Register a function `f(x)` to be called when there are no program-accessible references to -`x`. The type of `x` must be a `mutable struct`, otherwise the behavior of this function is -unpredictable. -""" -finalizer - -""" - csch(x) - -Compute the hyperbolic cosecant of `x`. -""" -csch - -""" - sec(x) - -Compute the secant of `x`, where `x` is in radians. -""" -sec - -""" - TypeError(func::Symbol, context::AbstractString, expected::Type, got) - -A type assertion failure, or calling an intrinsic function with an incorrect argument type. -""" -TypeError - -""" - setfield!(value, name::Symbol, x) - -Assign `x` to a named field in `value` of composite type. The syntax `a.b = c` calls -`setfield!(a, :b, c)`. -""" -setfield! - -""" -``` -*(x, y...) -``` - -Multiplication operator. `x*y*z*...` calls this function with all arguments, i.e. `*(x, y, z, ...)`. -""" -Base.:(*)(x, y...) - -""" - time() - -Get the system time in seconds since the epoch, with fairly high (typically, microsecond) resolution. -""" -time() - -""" - ismatch(r::Regex, s::AbstractString) -> Bool - -Test whether a string contains a match of the given regular expression. -""" -ismatch - -""" - matchall(r::Regex, s::AbstractString[, overlap::Bool=false]) -> Vector{AbstractString} - -Return a vector of the matching substrings from [`eachmatch`](@ref). -""" -matchall - -""" - get!(collection, key, default) - -Return the value stored for the given key, or if no mapping for the key is present, store -`key => default`, and return `default`. - -# Examples -```jldoctest -julia> d = Dict("a"=>1, "b"=>2, "c"=>3); - -julia> get!(d, "a", 5) -1 - -julia> get!(d, "d", 4) -4 - -julia> d -Dict{String,Int64} with 4 entries: - "c" => 3 - "b" => 2 - "a" => 1 - "d" => 4 -``` -""" -get!(collection,key,default) - -""" - get!(f::Function, collection, key) - -Return the value stored for the given key, or if no mapping for the key is present, store -`key => f()`, and return `f()`. - -This is intended to be called using `do` block syntax: -```julia -get!(dict, key) do - # default value calculated here - time() -end -``` -""" -get!(f::Function,collection,key) - -""" - @assert cond [text] - -Throw an `AssertionError` if `cond` is `false`. Preferred syntax for writing assertions. -Message `text` is optionally displayed upon assertion failure. -""" -:@assert - -""" - deserialize(stream) - -Read a value written by [`serialize`](@ref). `deserialize` assumes the binary data read from -`stream` is correct and has been serialized by a compatible implementation of [`serialize`](@ref). -It has been designed with simplicity and performance as a goal and does not validate -the data read. Malformed data can result in process termination. The caller has to ensure -the integrity and correctness of data read from `stream`. -""" -deserialize - -""" - length(collection) -> Integer - -For ordered, indexable collections, returns the maximum index `i` for which `getindex(collection, i)` -is valid. -For unordered collections, returns the number of elements. - -# Examples -```jldoctest -julia> length(1:5) -5 - -julia> length([1; 2; 3; 4]) -4 -``` -""" -length(collection) - -""" - searchsortedlast(a, x, [by=,] [lt=,] [rev=false]) - -Returns the index of the last value in `a` less than or equal to `x`, according to the -specified order. Returns `0` if `x` is less than all values in `a`. `a` is assumed to -be sorted. - -# Examples - -```jldoctest -julia> searchsortedlast([1, 2, 4, 5, 14], 4) -3 - -julia> searchsortedlast([1, 2, 4, 5, 14], 4, rev=true) -5 - -julia> searchsortedlast([1, 2, 4, 5, 14], -1) -0 -``` -""" -searchsortedlast - -""" - InterruptException() - -The process was stopped by a terminal interrupt (CTRL+C). -""" -InterruptException - -""" - issubnormal(f) -> Bool - -Test whether a floating point number is subnormal. -""" -issubnormal - -""" - NullException() - -An attempted access to a [`Nullable`](@ref) with no defined value. -""" -NullException - -""" - intersect(s1,s2...) - ∩(s1,s2) - -Construct the intersection of two or more sets. -Maintains order and multiplicity of the first argument for arrays and ranges. -""" -intersect - -""" - @spawn - -Creates a closure around an expression and runs it on an automatically-chosen process, -returning a [`Future`](@ref) to the result. -""" -:@spawn - -""" - promote_rule(type1, type2) - -Specifies what type should be used by [`promote`](@ref) when given values of types `type1` and -`type2`. This function should not be called directly, but should have definitions added to -it for new types as appropriate. -""" -promote_rule - -""" - showall(x) - -Similar to [`show`](@ref), except shows all elements of arrays. -""" -showall - -""" - match(r::Regex, s::AbstractString[, idx::Integer[, addopts]]) - -Search for the first match of the regular expression `r` in `s` and return a `RegexMatch` -object containing the match, or nothing if the match failed. The matching substring can be -retrieved by accessing `m.match` and the captured sequences can be retrieved by accessing -`m.captures` The optional `idx` argument specifies an index at which to start the search. -""" -match - -""" - coth(x) - -Compute the hyperbolic cotangent of `x`. -""" -coth - -""" - start(iter) -> state - -Get initial iteration state for an iterable object. - -# Examples -```jldoctest -julia> start(1:5) -1 - -julia> start([1;2;3]) -1 - -julia> start([4;2;3]) -1 -``` -""" -start - -""" - readavailable(stream) - -Read all available data on the stream, blocking the task only if no data is available. The -result is a `Vector{UInt8,1}`. -""" -readavailable - -""" - isa(x, type) -> Bool - -Determine whether `x` is of the given `type`. Can also be used as an infix operator, e.g. -`x isa type`. -""" -isa - -""" - done(iter, state) -> Bool - -Test whether we are done iterating. - -# Examples -```jldoctest -julia> done(1:5, 3) -false - -julia> done(1:5, 5) -false - -julia> done(1:5, 6) -true -``` -""" -done - -""" - convert(T, x) - -Convert `x` to a value of type `T`. - -If `T` is an [`Integer`](@ref) type, an [`InexactError`](@ref) will be raised if `x` -is not representable by `T`, for example if `x` is not integer-valued, or is outside the -range supported by `T`. - -# Examples -```jldoctest -julia> convert(Int, 3.0) -3 - -julia> convert(Int, 3.5) -ERROR: InexactError() -Stacktrace: - [1] convert(::Type{Int64}, ::Float64) at ./float.jl:679 -``` - -If `T` is a [`AbstractFloat`](@ref) or [`Rational`](@ref) type, -then it will return the closest value to `x` representable by `T`. - -```jldoctest -julia> x = 1/3 -0.3333333333333333 - -julia> convert(Float32, x) -0.33333334f0 - -julia> convert(Rational{Int32}, x) -1//3 - -julia> convert(Rational{Int64}, x) -6004799503160661//18014398509481984 -``` - -If `T` is a collection type and `x` a collection, the result of `convert(T, x)` may alias -`x`. -```jldoctest -julia> x = Int[1,2,3]; - -julia> y = convert(Vector{Int}, x); - -julia> y === x -true -``` -Similarly, if `T` is a composite type and `x` a related instance, the result of -`convert(T, x)` may alias part or all of `x`. -```jldoctest -julia> x = speye(5); - -julia> typeof(x) -SparseMatrixCSC{Float64,Int64} - -julia> y = convert(SparseMatrixCSC{Float64,Int64}, x); - -julia> z = convert(SparseMatrixCSC{Float32,Int64}, y); - -julia> y === x -true - -julia> z === x -false - -julia> z.colptr === x.colptr -true -``` -""" -convert - -""" - applicable(f, args...) -> Bool - -Determine whether the given generic function has a method applicable to the given arguments. - -# Examples -```jldoctest -julia> function f(x, y) - x + y - end; - -julia> applicable(f, 1) -false - -julia> applicable(f, 1, 2) -true -``` -""" -applicable - -""" - fma(x, y, z) - -Computes `x*y+z` without rounding the intermediate result `x*y`. On some systems this is -significantly more expensive than `x*y+z`. `fma` is used to improve accuracy in certain -algorithms. See [`muladd`](@ref). -""" -fma - -""" - copy!(dest, do, src, so, N) - -Copy `N` elements from collection `src` starting at offset `so`, to array `dest` starting at -offset `do`. Returns `dest`. -""" -copy!(dest,d,src,so,N) - -""" - +(x, y...) - -Addition operator. `x+y+z+...` calls this function with all arguments, i.e. `+(x, y, z, ...)`. -""" -+ - -""" - setindex!(A, X, inds...) - -Store values from array `X` within some subset of `A` as specified by `inds`. -""" -setindex!(A::AbstractArray,X,inds...) - -""" - setindex!(collection, value, key...) - -Store the given value at the given key or index within a collection. The syntax `a[i,j,...] = -x` is converted by the compiler to `(setindex!(a, x, i, j, ...); x)`. -""" -setindex!(collection,value,key...) - -""" - signif(x, digits, [base]) - -Rounds (in the sense of [`round`](@ref)) `x` so that there are `digits` significant digits, under a -base `base` representation, default 10. E.g., `signif(123.456, 2)` is `120.0`, and -`signif(357.913, 4, 2)` is `352.0`. -""" -signif - -""" - full(F) - -Reconstruct the matrix `A` from the factorization `F=factorize(A)`. -""" -full(F) - -""" - throw(e) - -Throw an object as an exception. -""" -throw - -""" - issubset(a, b) - ⊆(a,b) -> Bool - ⊈(a,b) -> Bool - ⊊(a,b) -> Bool - -Determine whether every element of `a` is also in `b`, using [`in`](@ref). - -# Examples -```jldoctest -julia> issubset([1, 2], [1, 2, 3]) -true - -julia> issubset([1, 2, 3], [1, 2]) -false -``` -""" -issubset(a,b) - -""" - issubset(A, S) -> Bool - ⊆(A,S) -> Bool - -Return `true` if `A` is a subset of or equal to `S`. -""" -issubset - -""" - zeros([A::AbstractArray,] [T=eltype(A)::Type,] [dims=size(A)::Tuple]) - -Create an array of all zeros with the same layout as `A`, element type `T` and size `dims`. -The `A` argument can be skipped, which behaves like `Array{Float64,0}()` was passed. -For convenience `dims` may also be passed in variadic form. - -# Examples -```jldoctest -julia> zeros(1) -1-element Array{Float64,1}: - 0.0 - -julia> zeros(Int8, 2, 3) -2×3 Array{Int8,2}: - 0 0 0 - 0 0 0 - -julia> A = [1 2; 3 4] -2×2 Array{Int64,2}: - 1 2 - 3 4 - -julia> zeros(A) -2×2 Array{Int64,2}: - 0 0 - 0 0 - -julia> zeros(A, Float64) -2×2 Array{Float64,2}: - 0.0 0.0 - 0.0 0.0 - -julia> zeros(A, Bool, (3,)) -3-element Array{Bool,1}: - false - false - false -``` -See also [`ones`](@ref), [`similar`](@ref). -""" -zeros - -""" - Symbol(x...) -> Symbol - -Create a `Symbol` by concatenating the string representations of the arguments together. -""" -Symbol - -""" - isvalid(value) -> Bool - -Returns `true` if the given value is valid for its type, which currently can be either -`Char` or `String`. -""" -isvalid(value) - -""" - isvalid(T, value) -> Bool - -Returns `true` if the given value is valid for that type. Types currently can -be either `Char` or `String`. Values for `Char` can be of type `Char` or [`UInt32`](@ref). -Values for `String` can be of that type, or `Vector{UInt8}`. -""" -isvalid(T,value) - -""" - unsigned(x) -> Unsigned - -Convert a number to an unsigned integer. If the argument is signed, it is reinterpreted as -unsigned without checking for negative values. - -# Examples -```jldoctest -julia> unsigned(-2) -0xfffffffffffffffe - -julia> unsigned(2) -0x0000000000000002 - -julia> signed(unsigned(-2)) --2 -``` -""" -unsigned - -""" - reverseind(v, i) - -Given an index `i` in `reverse(v)`, return the corresponding index in `v` so that -`v[reverseind(v,i)] == reverse(v)[i]`. (This can be nontrivial in the case where `v` is a -Unicode string.) -""" -reverseind - -""" - signbit(x) - -Returns `true` if the value of the sign of `x` is negative, otherwise `false`. - -# Examples -```jldoctest -julia> signbit(-4) -true - -julia> signbit(5) -false - -julia> signbit(5.5) -false - -julia> signbit(-4.1) -true -``` -""" -signbit - -""" - cscd(x) - -Compute the cosecant of `x`, where `x` is in degrees. -""" -cscd - -""" - tryparse(type, str, [base]) - -Like [`parse`](@ref), but returns a [`Nullable`](@ref) of the requested type. The result will be null if the -string does not contain a valid number. -""" -tryparse - -""" - exit([code]) - -Quit (or control-D at the prompt). The default exit code is zero, indicating that the -processes completed successfully. -""" -exit - -""" - skipchars(stream, predicate; linecomment::Char) - -Advance the stream until before the first character for which `predicate` returns `false`. -For example `skipchars(stream, isspace)` will skip all whitespace. If keyword argument -`linecomment` is specified, characters from that character through the end of a line will -also be skipped. -""" -skipchars - -""" - realmin(T) - -The smallest in absolute value non-subnormal value representable by the given floating-point DataType `T`. -""" -realmin - -""" - union!(s, iterable) - -Union each element of `iterable` into set `s` in-place. -""" -union! - -""" - deepcopy(x) - -Create a deep copy of `x`: everything is copied recursively, resulting in a fully -independent object. For example, deep-copying an array produces a new array whose elements -are deep copies of the original elements. Calling `deepcopy` on an object should generally -have the same effect as serializing and then deserializing it. - -As a special case, functions can only be actually deep-copied if they are anonymous, -otherwise they are just copied. The difference is only relevant in the case of closures, -i.e. functions which may contain hidden internal references. - -While it isn't normally necessary, user-defined types can override the default `deepcopy` -behavior by defining a specialized version of the function `deepcopy_internal(x::T, dict::ObjectIdDict)` -(which shouldn't otherwise be used), where `T` is the type to be specialized for, and `dict` -keeps track of objects copied so far within the recursion. Within the definition, -`deepcopy_internal` should be used in place of `deepcopy`, and the `dict` variable should be -updated as appropriate before returning. -""" -deepcopy - -""" - widen(x) - -If `x` is a type, return a "larger" type (for numeric types, this will be -a type with at least as much range and precision as the argument, and usually more). -Otherwise `x` is converted to `widen(typeof(x))`. - -# Examples -```jldoctest -julia> widen(Int32) -Int64 - -julia> widen(1.5f0) -1.5 -``` -""" -widen - -""" - Set([itr]) - -Construct a [`Set`](@ref) of the values generated by the given iterable object, or an -empty set. Should be used instead of [`IntSet`](@ref) for sparse integer sets, or -for sets of arbitrary objects. -""" -Set - -""" - signed(x) - -Convert a number to a signed integer. If the argument is unsigned, it is reinterpreted as -signed without checking for overflow. -""" -signed - -""" - Val{c} - -Create a "value type" out of `c`, which must be an `isbits` value. The intent of this -construct is to be able to dispatch on constants, e.g., `f(Val{false})` allows you to -dispatch directly (at compile-time) to an implementation `f(::Type{Val{false}})`, without -having to test the boolean value at runtime. -""" -Val - -""" - |(x, y) - -Bitwise or. - -# Examples -```jldoctest -julia> 4 | 10 -14 - -julia> 4 | 1 -5 -``` -""" -Base.:(|) - -""" - pop!(collection, key[, default]) - -Delete and return the mapping for `key` if it exists in `collection`, otherwise return -`default`, or throw an error if `default` is not specified. - -# Examples -```jldoctest -julia> d = Dict("a"=>1, "b"=>2, "c"=>3); - -julia> pop!(d, "a") -1 - -julia> pop!(d, "d") -ERROR: KeyError: key "d" not found -Stacktrace: - [1] pop!(::Dict{String,Int64}, ::String) at ./dict.jl:539 - -julia> pop!(d, "e", 4) -4 -``` -""" -pop!(collection,key,?) - -""" - pop!(collection) -> item - -Remove the last item in `collection` and return it. - -# Examples -```jldoctest -julia> A=[1, 2, 3, 4, 5, 6] -6-element Array{Int64,1}: - 1 - 2 - 3 - 4 - 5 - 6 - -julia> pop!(A) -6 - -julia> A -5-element Array{Int64,1}: - 1 - 2 - 3 - 4 - 5 -``` -""" -pop!(collection) - -""" - seekend(s) - -Seek a stream to its end. -""" -seekend - -""" - DivideError() - -Integer division was attempted with a denominator value of 0. -""" -DivideError - -""" - Number - -Abstract supertype for all number types. -""" -Number - -""" - Real <: Number - -Abstract supertype for all real numbers. -""" -Real - -""" - AbstractFloat <: Real - -Abstract supertype for all floating point numbers. -""" -AbstractFloat - -""" - Integer <: Real - -Abstract supertype for all integers. -""" -Integer - -""" - Signed <: Integer - -Abstract supertype for all signed integers. -""" -Signed - -""" - Unsigned <: Integer - -Abstract supertype for all unsigned integers. -""" -Unsigned - -""" - Bool <: Integer - -Boolean type. -""" -Bool - -for bit in (16, 32, 64) - @eval begin - """ - Float$($bit) <: AbstractFloat - - $($bit)-bit floating point number type. - """ - $(Symbol("Float", bit)) - end -end - -for bit in (8, 16, 32, 64, 128) - @eval begin - """ - Int$($bit) <: Signed - - $($bit)-bit signed integer type. - """ - $(Symbol("Int", bit)) - - """ - UInt$($bit) <: Unsigned - - $($bit)-bit unsigned integer type. - """ - $(Symbol("UInt", bit)) - end -end diff --git a/julia-0.6.3/share/julia/base/docs/utils.jl b/julia-0.6.3/share/julia/base/docs/utils.jl deleted file mode 100644 index c597f39..0000000 --- a/julia-0.6.3/share/julia/base/docs/utils.jl +++ /dev/null @@ -1,455 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -# Text / HTML objects - -import Base: print, show, ==, hash - -export HTML, @html_str - -export HTML, Text, apropos - -""" -`HTML(s)`: Create an object that renders `s` as html. - - HTML("
      foo
      ") - -You can also use a stream for large amounts of data: - - HTML() do io - println(io, "
      foo
      ") - end -""" -mutable struct HTML{T} - content::T -end - -function HTML(xs...) - HTML() do io - for x in xs - show(io, MIME"text/html"(), x) - end - end -end - -show(io::IO, ::MIME"text/html", h::HTML) = print(io, h.content) -show(io::IO, ::MIME"text/html", h::HTML{<:Function}) = h.content(io) - -""" - @html_str -> Docs.HTML - -Create an `HTML` object from a literal string. -""" -macro html_str(s) - :(HTML($s)) -end - -function catdoc(xs::HTML...) - HTML() do io - for x in xs - show(io, MIME"text/html"(), x) - end - end -end - -export Text, @text_str - -""" -`Text(s)`: Create an object that renders `s` as plain text. - - Text("foo") - -You can also use a stream for large amounts of data: - - Text() do io - println(io, "foo") - end -""" -mutable struct Text{T} - content::T -end - -print(io::IO, t::Text) = print(io, t.content) -print(io::IO, t::Text{<:Function}) = t.content(io) -show(io::IO, t::Text) = print(io, t) - -==(t1::T, t2::T) where {T<:Union{HTML,Text}} = t1.content == t2.content -hash(t::T, h::UInt) where {T<:Union{HTML,Text}} = hash(T, hash(t.content, h)) - -""" - @text_str -> Docs.Text - -Create a `Text` object from a literal string. -""" -macro text_str(s) - :(Text($s)) -end - -function catdoc(xs::Text...) - Text() do io - for x in xs - show(io, MIME"text/plain"(), x) - end - end -end - -# REPL help - -function helpmode(io::IO, line::AbstractString) - line = strip(line) - expr = - if haskey(keywords, Symbol(line)) - # Docs for keywords must be treated separately since trying to parse a single - # keyword such as `function` would throw a parse error due to the missing `end`. - Symbol(line) - else - x = Base.syntax_deprecation_warnings(false) do - parse(line, raise = false) - end - # Retrieving docs for macros requires us to make a distinction between the text - # `@macroname` and `@macroname()`. These both parse the same, but are used by - # the docsystem to return different results. The first returns all documentation - # for `@macroname`, while the second returns *only* the docs for the 0-arg - # definition if it exists. - (isexpr(x, :macrocall, 1) && !endswith(line, "()")) ? quot(x) : x - end - # the following must call repl(io, expr) via the @repl macro - # so that the resulting expressions are evaluated in the Base.Docs namespace - :(Base.Docs.@repl $io $expr) -end -helpmode(line::AbstractString) = helpmode(STDOUT, line) - -function repl_search(io::IO, s) - pre = "search:" - print(io, pre) - printmatches(io, s, completions(s), cols = displaysize(io)[2] - length(pre)) - println(io, "\n") -end -repl_search(s) = repl_search(STDOUT, s) - -function repl_corrections(io::IO, s) - print(io, "Couldn't find ") - Markdown.with_output_format(:cyan, io) do io - println(io, s) - end - print_correction(io, s) -end -repl_corrections(s) = repl_corrections(STDOUT, s) - -# inverse of latex_symbols Dict, lazily created as needed -const symbols_latex = Dict{String,String}() -function symbol_latex(s::String) - if isempty(symbols_latex) - for (k,v) in Base.REPLCompletions.latex_symbols - symbols_latex[v] = k - end - end - return get(symbols_latex, s, "") -end -function repl_latex(io::IO, s::String) - latex = symbol_latex(s) - if !isempty(latex) - print(io, "\"") - Markdown.with_output_format(:cyan, io) do io - print(io, s) - end - print(io, "\" can be typed by ") - Markdown.with_output_format(:cyan, io) do io - print(io, latex, "") - end - println(io, '\n') - elseif any(c -> haskey(symbols_latex, string(c)), s) - print(io, "\"") - Markdown.with_output_format(:cyan, io) do io - print(io, s) - end - print(io, "\" can be typed by ") - Markdown.with_output_format(:cyan, io) do io - for c in s - cstr = string(c) - if haskey(symbols_latex, cstr) - print(io, symbols_latex[cstr], "") - else - print(io, c) - end - end - end - println(io, '\n') - end -end -repl_latex(s::String) = repl_latex(STDOUT, s) - -macro repl(ex) repl(ex) end -macro repl(io, ex) repl(io, ex) end - -function repl(io::IO, s::Symbol) - str = string(s) - quote - repl_latex($io, $str) - repl_search($io, $str) - ($(isdefined(s) || haskey(keywords, s))) || repl_corrections($io, $str) - $(_repl(s)) - end -end -isregex(x) = isexpr(x, :macrocall, 2) && x.args[1] === Symbol("@r_str") && !isempty(x.args[2]) -repl(io::IO, ex::Expr) = isregex(ex) ? :(apropos($io, $ex)) : _repl(ex) -repl(io::IO, str::AbstractString) = :(apropos($io, $str)) -repl(io::IO, other) = :(@doc $(esc(other))) - -repl(x) = repl(STDOUT, x) - -function _repl(x) - if (isexpr(x, :call) && !any(isexpr(x, :(::)) for x in x.args)) - x.args[2:end] = [:(::typeof($arg)) for arg in x.args[2:end]] - end - docs = :(@doc $(esc(x))) - if isfield(x) - quote - if isa($(esc(x.args[1])), DataType) - fielddoc($(esc(x.args[1])), $(esc(x.args[2]))) - else - $docs - end - end - else - docs - end -end - - -# Search & Rescue -# Utilities for correcting user mistakes and (eventually) -# doing full documentation searches from the repl. - -# Fuzzy Search Algorithm - -function matchinds(needle, haystack; acronym = false) - chars = collect(needle) - is = Int[] - lastc = '\0' - for (i, char) in enumerate(haystack) - isempty(chars) && break - while chars[1] == ' ' shift!(chars) end # skip spaces - if lowercase(char) == lowercase(chars[1]) && (!acronym || !isalpha(lastc)) - push!(is, i) - shift!(chars) - end - lastc = char - end - return is -end - -longer(x, y) = length(x) ≥ length(y) ? (x, true) : (y, false) - -bestmatch(needle, haystack) = - longer(matchinds(needle, haystack, acronym = true), - matchinds(needle, haystack)) - -avgdistance(xs) = - isempty(xs) ? 0 : - (xs[end] - xs[1] - length(xs)+1)/length(xs) - -function fuzzyscore(needle, haystack) - score = 0. - is, acro = bestmatch(needle, haystack) - score += (acro?2:1)*length(is) # Matched characters - score -= 2(length(needle)-length(is)) # Missing characters - !acro && (score -= avgdistance(is)/10) # Contiguous - !isempty(is) && (score -= mean(is)/100) # Closer to beginning - return score -end - -function fuzzysort(search, candidates) - scores = map(cand -> (fuzzyscore(search, cand), -levenshtein(search, cand)), candidates) - candidates[sortperm(scores)] |> reverse -end - -# Levenshtein Distance - -function levenshtein(s1, s2) - a, b = collect(s1), collect(s2) - m = length(a) - n = length(b) - d = Matrix{Int}(m+1, n+1) - - d[1:m+1, 1] = 0:m - d[1, 1:n+1] = 0:n - - for i = 1:m, j = 1:n - d[i+1,j+1] = min(d[i , j+1] + 1, - d[i+1, j ] + 1, - d[i , j ] + (a[i] != b[j])) - end - - return d[m+1, n+1] -end - -function levsort(search, candidates) - scores = map(cand -> (levenshtein(search, cand), -fuzzyscore(search, cand)), candidates) - candidates = candidates[sortperm(scores)] - i = 0 - for i = 1:length(candidates) - levenshtein(search, candidates[i]) > 3 && break - end - return candidates[1:i] -end - -# Result printing - -function printmatch(io::IO, word, match) - is, _ = bestmatch(word, match) - Markdown.with_output_format(:fade, io) do io - for (i, char) = enumerate(match) - if i in is - Markdown.with_output_format(print, :bold, io, char) - else - print(io, char) - end - end - end -end - -printmatch(args...) = printfuzzy(STDOUT, args...) - -function printmatches(io::IO, word, matches; cols = displaysize(io)[2]) - total = 0 - for match in matches - total + length(match) + 1 > cols && break - fuzzyscore(word, match) < 0 && break - print(io, " ") - printmatch(io, word, match) - total += length(match) + 1 - end -end - -printmatches(args...; cols = displaysize(STDOUT)[2]) = printmatches(STDOUT, args..., cols = cols) - -function print_joined_cols(io::IO, ss, delim = "", last = delim; cols = displaysize(io)[2]) - i = 0 - total = 0 - for i = 1:length(ss) - total += length(ss[i]) - total + max(i-2,0)*length(delim) + (i>1?1:0)*length(last) > cols && (i-=1; break) - end - join(io, ss[1:i], delim, last) -end - -print_joined_cols(args...; cols = displaysize(STDOUT)[2]) = print_joined_cols(STDOUT, args...; cols=cols) - -function print_correction(io, word) - cors = levsort(word, accessible(current_module())) - pre = "Perhaps you meant " - print(io, pre) - print_joined_cols(io, cors, ", ", " or "; cols = displaysize(io)[2] - length(pre)) - println(io) - return -end - -print_correction(word) = print_correction(STDOUT, word) - -# Completion data - -const builtins = ["abstract type", "baremodule", "begin", "break", - "catch", "ccall", "const", "continue", "do", "else", - "elseif", "end", "export", "finally", "for", "function", - "global", "if", "import", "importall", "let", - "local", "macro", "module", "mutable struct", "primitive type", - "quote", "return", "struct", "try", "using", "while"] - -moduleusings(mod) = ccall(:jl_module_usings, Any, (Any,), mod) - -filtervalid(names) = filter(x->!ismatch(r"#", x), map(string, names)) - -accessible(mod::Module) = - [filter!(s->Base.isdeprecated(mod, s), names(mod, true, true)); - map(names, moduleusings(mod))...; - builtins] |> unique |> filtervalid - -completions(name) = fuzzysort(name, accessible(current_module())) -completions(name::Symbol) = completions(string(name)) - - -# Searching and apropos - -# Docsearch simply returns true or false if an object contains the given needle -docsearch(haystack::AbstractString, needle) = !isempty(search(haystack, needle)) -docsearch(haystack::Symbol, needle) = docsearch(string(haystack), needle) -docsearch(::Void, needle) = false -function docsearch(haystack::Array, needle) - for elt in haystack - docsearch(elt, needle) && return true - end - false -end -function docsearch(haystack, needle) - Base.warn_once("unable to search documentation of type $(typeof(haystack))") - false -end - -## Searching specific documentation objects -function docsearch(haystack::MultiDoc, needle) - for v in values(haystack.docs) - docsearch(v, needle) && return true - end - false -end - -function docsearch(haystack::DocStr, needle) - docsearch(parsedoc(haystack), needle) && return true - if haskey(haystack.data, :fields) - for doc in values(haystack.data[:fields]) - docsearch(doc, needle) && return true - end - end - false -end - -## Markdown search simply strips all markup and searches plain text version -docsearch(haystack::Markdown.MD, needle) = - docsearch(stripmd(haystack.content), needle) - -""" - stripmd(x) - -Strip all Markdown markup from x, leaving the result in plain text. Used -internally by apropos to make docstrings containing more than one markdown -element searchable. -""" -stripmd(x::ANY) = string(x) # for random objects interpolated into the docstring -stripmd(x::AbstractString) = x # base case -stripmd(x::Void) = " " -stripmd(x::Vector) = string(map(stripmd, x)...) -stripmd(x::Markdown.BlockQuote) = "$(stripmd(x.content))" -stripmd(x::Markdown.Admonition) = "$(stripmd(x.content))" -stripmd(x::Markdown.Bold) = "$(stripmd(x.text))" -stripmd(x::Markdown.Code) = "$(stripmd(x.code))" -stripmd(x::Markdown.Header) = stripmd(x.text) -stripmd(x::Markdown.HorizontalRule) = " " -stripmd(x::Markdown.Image) = "$(stripmd(x.alt)) $(x.url)" -stripmd(x::Markdown.Italic) = "$(stripmd(x.text))" -stripmd(x::Markdown.LaTeX) = "$(x.formula)" -stripmd(x::Markdown.LineBreak) = " " -stripmd(x::Markdown.Link) = "$(stripmd(x.text)) $(x.url)" -stripmd(x::Markdown.List) = join(map(stripmd, x.items), " ") -stripmd(x::Markdown.MD) = join(map(stripmd, x.content), " ") -stripmd(x::Markdown.Paragraph) = stripmd(x.content) -stripmd(x::Markdown.Footnote) = "$(stripmd(x.id)) $(stripmd(x.text))" -stripmd(x::Markdown.Table) = - join([join(map(stripmd, r), " ") for r in x.rows], " ") - -# Apropos searches through all available documentation for some string or regex -""" - apropos(string) - -Search through all documentation for a string, ignoring case. -""" -apropos(string) = apropos(STDOUT, string) -apropos(io::IO, string) = apropos(io, Regex("\\Q$string", "i")) -function apropos(io::IO, needle::Regex) - for mod in modules - # Module doc might be in README.md instead of the META dict - docsearch(doc(mod), needle) && println(io, mod) - for (k, v) in meta(mod) - docsearch(v, needle) && println(io, k) - end - end -end diff --git a/julia-0.6.3/share/julia/base/dsp.jl b/julia-0.6.3/share/julia/base/dsp.jl deleted file mode 100644 index 470852e..0000000 --- a/julia-0.6.3/share/julia/base/dsp.jl +++ /dev/null @@ -1,207 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -module DSP - -import Base.trailingsize - -export filt, filt!, deconv, conv, conv2, xcorr - -_zerosi(b,a,T) = zeros(promote_type(eltype(b), eltype(a), T), max(length(a), length(b))-1) - -""" - filt(b, a, x, [si]) - -Apply filter described by vectors `a` and `b` to vector `x`, with an optional initial filter -state vector `si` (defaults to zeros). -""" -function filt(b::Union{AbstractVector, Number}, a::Union{AbstractVector, Number}, - x::AbstractArray{T}, si::AbstractArray{S} = _zerosi(b,a,T)) where {T,S} - filt!(Array{promote_type(eltype(b), eltype(a), T, S)}(size(x)), b, a, x, si) -end - -# in-place filtering: returns results in the out argument, which may shadow x -# (and does so by default) - -""" - filt!(out, b, a, x, [si]) - -Same as [`filt`](@ref) but writes the result into the `out` argument, which may -alias the input `x` to modify it in-place. -""" -function filt!(out::AbstractArray, b::Union{AbstractVector, Number}, a::Union{AbstractVector, Number}, - x::AbstractArray{T}, si::AbstractArray{S,N} = _zerosi(b,a,T)) where {T,S,N} - isempty(b) && throw(ArgumentError("filter vector b must be non-empty")) - isempty(a) && throw(ArgumentError("filter vector a must be non-empty")) - a[1] == 0 && throw(ArgumentError("filter vector a[1] must be nonzero")) - if size(x) != size(out) - throw(ArgumentError("output size $(size(out)) must match input size $(size(x))")) - end - - as = length(a) - bs = length(b) - sz = max(as, bs) - silen = sz - 1 - ncols = trailingsize(x,2) - - if size(si, 1) != silen - throw(ArgumentError("initial state vector si must have max(length(a),length(b))-1 rows")) - end - if N > 1 && trailingsize(si,2) != ncols - throw(ArgumentError("initial state vector si must be a vector or have the same number of columns as x")) - end - - size(x,1) == 0 && return out - sz == 1 && return scale!(out, x, b[1]/a[1]) # Simple scaling without memory - - # Filter coefficient normalization - if a[1] != 1 - norml = a[1] - a ./= norml - b ./= norml - end - # Pad the coefficients with zeros if needed - bs 1 ? col : 1] - if as > 1 - _filt_iir!(out, b, a, x, si, col) - else - _filt_fir!(out, b, x, si, col) - end - end - return out -end - -function _filt_iir!(out, b, a, x, si, col) - silen = length(si) - @inbounds for i=1:size(x, 1) - xi = x[i,col] - val = si[1] + b[1]*xi - for j=1:(silen-1) - si[j] = si[j+1] + b[j+1]*xi - a[j+1]*val - end - si[silen] = b[silen+1]*xi - a[silen+1]*val - out[i,col] = val - end -end - -function _filt_fir!(out, b, x, si, col) - silen = length(si) - @inbounds for i=1:size(x, 1) - xi = x[i,col] - val = si[1] + b[1]*xi - for j=1:(silen-1) - si[j] = si[j+1] + b[j+1]*xi - end - si[silen] = b[silen+1]*xi - out[i,col] = val - end -end - -""" - deconv(b,a) -> c - -Construct vector `c` such that `b = conv(a,c) + r`. -Equivalent to polynomial division. -""" -function deconv(b::StridedVector{T}, a::StridedVector{T}) where T - lb = size(b,1) - la = size(a,1) - if lb < la - return [zero(T)] - end - lx = lb-la+1 - x = zeros(T, lx) - x[1] = 1 - filt(b, a, x) -end - -""" - conv(u,v) - -Convolution of two vectors. Uses FFT algorithm. -""" -function conv(u::StridedVector{T}, v::StridedVector{T}) where T<:Base.LinAlg.BlasFloat - nu = length(u) - nv = length(v) - n = nu + nv - 1 - np2 = n > 1024 ? nextprod([2,3,5], n) : nextpow2(n) - upad = [u; zeros(T, np2 - nu)] - vpad = [v; zeros(T, np2 - nv)] - if T <: Real - p = plan_rfft(upad) - y = irfft((p*upad).*(p*vpad), np2) - else - p = plan_fft!(upad) - y = ifft!((p*upad).*(p*vpad)) - end - return y[1:n] -end -conv(u::StridedVector{T}, v::StridedVector{T}) where {T<:Integer} = round.(Int, conv(float(u), float(v))) -conv(u::StridedVector{<:Integer}, v::StridedVector{<:Base.LinAlg.BlasFloat}) = conv(float(u), v) -conv(u::StridedVector{<:Base.LinAlg.BlasFloat}, v::StridedVector{<:Integer}) = conv(u, float(v)) - -""" - conv2(u,v,A) - -2-D convolution of the matrix `A` with the 2-D separable kernel generated by -the vectors `u` and `v`. -Uses 2-D FFT algorithm. -""" -function conv2(u::StridedVector{T}, v::StridedVector{T}, A::StridedMatrix{T}) where T - m = length(u)+size(A,1)-1 - n = length(v)+size(A,2)-1 - B = zeros(T, m, n) - B[1:size(A,1),1:size(A,2)] = A - u = fft([u;zeros(T,m-length(u))]) - v = fft([v;zeros(T,n-length(v))]) - C = ifft(fft(B) .* (u * v.')) - if T <: Real - return real(C) - end - return C -end - -""" - conv2(B,A) - -2-D convolution of the matrix `B` with the matrix `A`. Uses 2-D FFT algorithm. -""" -function conv2(A::StridedMatrix{T}, B::StridedMatrix{T}) where T - sa, sb = size(A), size(B) - At = zeros(T, sa[1]+sb[1]-1, sa[2]+sb[2]-1) - Bt = zeros(T, sa[1]+sb[1]-1, sa[2]+sb[2]-1) - At[1:sa[1], 1:sa[2]] = A - Bt[1:sb[1], 1:sb[2]] = B - p = plan_fft(At) - C = ifft((p*At).*(p*Bt)) - if T <: Real - return real(C) - end - return C -end -conv2(A::StridedMatrix{T}, B::StridedMatrix{T}) where {T<:Integer} = - round.(Int, conv2(float(A), float(B))) -conv2(u::StridedVector{T}, v::StridedVector{T}, A::StridedMatrix{T}) where {T<:Integer} = - round.(Int, conv2(float(u), float(v), float(A))) - -""" - xcorr(u,v) - -Compute the cross-correlation of two vectors. -""" -function xcorr(u, v) - su = size(u,1); sv = size(v,1) - if su < sv - u = [u;zeros(eltype(u),sv-su)] - elseif sv < su - v = [v;zeros(eltype(v),su-sv)] - end - flipdim(conv(flipdim(u, 1), v), 1) -end - -end # module diff --git a/julia-0.6.3/share/julia/base/emoji_symbols.jl b/julia-0.6.3/share/julia/base/emoji_symbols.jl deleted file mode 100644 index f8a5043..0000000 --- a/julia-0.6.3/share/julia/base/emoji_symbols.jl +++ /dev/null @@ -1,859 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -#= -import JSON -emojis = JSON.parsefile(download("https://raw.githubusercontent.com/iamcal/emoji-data/0f0cf4ea8845eb52d26df2a48c3c31c3b8cad14e/emoji_pretty.json")) - -result = Dict() -for emj in emojis - name = "\\:" * emj["short_name"] * ":" - unicode = emj["unified"] - if '-' in unicode - continue - end - result[name] = "$(Char(parse(UInt32, unicode, 16)))" -end - -skeys = sort(collect(keys(result))) - -open("emoji_symbols.jl", "w") do fh - println(fh, "const emoji_symbols = Dict(") - for key in skeys - println(fh, " \"", escape_string(key), "\" => \"", - escape_string(result[key]), "\",") - end - println(fh, ")") -end -=# - -const emoji_symbols = Dict( - "\\:+1:" => "👍", - "\\:-1:" => "👎", - "\\:100:" => "💯", - "\\:1234:" => "🔢", - "\\:8ball:" => "🎱", - "\\:a:" => "🅰", - "\\:ab:" => "🆎", - "\\:abc:" => "🔤", - "\\:abcd:" => "🔡", - "\\:accept:" => "🉑", - "\\:aerial_tramway:" => "🚡", - "\\:airplane:" => "✈", - "\\:alarm_clock:" => "⏰", - "\\:alien:" => "👽", - "\\:ambulance:" => "🚑", - "\\:anchor:" => "⚓", - "\\:angel:" => "👼", - "\\:anger:" => "💢", - "\\:angry:" => "😠", - "\\:anguished:" => "😧", - "\\:ant:" => "🐜", - "\\:apple:" => "🍎", - "\\:aquarius:" => "♒", - "\\:aries:" => "♈", - "\\:arrow_backward:" => "◀", - "\\:arrow_double_down:" => "⏬", - "\\:arrow_double_up:" => "⏫", - "\\:arrow_down:" => "⬇", - "\\:arrow_down_small:" => "🔽", - "\\:arrow_forward:" => "▶", - "\\:arrow_heading_down:" => "⤵", - "\\:arrow_heading_up:" => "⤴", - "\\:arrow_left:" => "⬅", - "\\:arrow_lower_left:" => "↙", - "\\:arrow_lower_right:" => "↘", - "\\:arrow_right:" => "➡", - "\\:arrow_right_hook:" => "↪", - "\\:arrow_up:" => "⬆", - "\\:arrow_up_down:" => "↕", - "\\:arrow_up_small:" => "🔼", - "\\:arrow_upper_left:" => "↖", - "\\:arrow_upper_right:" => "↗", - "\\:arrows_clockwise:" => "🔃", - "\\:arrows_counterclockwise:" => "🔄", - "\\:art:" => "🎨", - "\\:articulated_lorry:" => "🚛", - "\\:astonished:" => "😲", - "\\:athletic_shoe:" => "👟", - "\\:atm:" => "🏧", - "\\:b:" => "🅱", - "\\:baby:" => "👶", - "\\:baby_bottle:" => "🍼", - "\\:baby_chick:" => "🐤", - "\\:baby_symbol:" => "🚼", - "\\:back:" => "🔙", - "\\:baggage_claim:" => "🛄", - "\\:balloon:" => "🎈", - "\\:ballot_box_with_check:" => "☑", - "\\:bamboo:" => "🎍", - "\\:banana:" => "🍌", - "\\:bangbang:" => "‼", - "\\:bank:" => "🏦", - "\\:bar_chart:" => "📊", - "\\:barber:" => "💈", - "\\:baseball:" => "⚾", - "\\:basketball:" => "🏀", - "\\:bath:" => "🛀", - "\\:bathtub:" => "🛁", - "\\:battery:" => "🔋", - "\\:bear:" => "🐻", - "\\:bee:" => "🐝", - "\\:beer:" => "🍺", - "\\:beers:" => "🍻", - "\\:beetle:" => "🐞", - "\\:beginner:" => "🔰", - "\\:bell:" => "🔔", - "\\:bento:" => "🍱", - "\\:bicyclist:" => "🚴", - "\\:bike:" => "🚲", - "\\:bikini:" => "👙", - "\\:bird:" => "🐦", - "\\:birthday:" => "🎂", - "\\:black_circle:" => "⚫", - "\\:black_joker:" => "🃏", - "\\:black_large_square:" => "⬛", - "\\:black_medium_small_square:" => "◾", - "\\:black_medium_square:" => "◼", - "\\:black_nib:" => "✒", - "\\:black_small_square:" => "▪", - "\\:black_square_button:" => "🔲", - "\\:blossom:" => "🌼", - "\\:blowfish:" => "🐡", - "\\:blue_book:" => "📘", - "\\:blue_car:" => "🚙", - "\\:blue_heart:" => "💙", - "\\:blush:" => "😊", - "\\:boar:" => "🐗", - "\\:boat:" => "⛵", - "\\:bomb:" => "💣", - "\\:book:" => "📖", - "\\:bookmark:" => "🔖", - "\\:bookmark_tabs:" => "📑", - "\\:books:" => "📚", - "\\:boom:" => "💥", - "\\:boot:" => "👢", - "\\:bouquet:" => "💐", - "\\:bow:" => "🙇", - "\\:bowling:" => "🎳", - "\\:boy:" => "👦", - "\\:bread:" => "🍞", - "\\:bride_with_veil:" => "👰", - "\\:bridge_at_night:" => "🌉", - "\\:briefcase:" => "💼", - "\\:broken_heart:" => "💔", - "\\:bug:" => "🐛", - "\\:bulb:" => "💡", - "\\:bullettrain_front:" => "🚅", - "\\:bullettrain_side:" => "🚄", - "\\:bus:" => "🚌", - "\\:busstop:" => "🚏", - "\\:bust_in_silhouette:" => "👤", - "\\:busts_in_silhouette:" => "👥", - "\\:cactus:" => "🌵", - "\\:cake:" => "🍰", - "\\:calendar:" => "📆", - "\\:calling:" => "📲", - "\\:camel:" => "🐫", - "\\:camera:" => "📷", - "\\:cancer:" => "♋", - "\\:candy:" => "🍬", - "\\:capital_abcd:" => "🔠", - "\\:capricorn:" => "♑", - "\\:car:" => "🚗", - "\\:card_index:" => "📇", - "\\:carousel_horse:" => "🎠", - "\\:cat2:" => "🐈", - "\\:cat:" => "🐱", - "\\:cd:" => "💿", - "\\:chart:" => "💹", - "\\:chart_with_downwards_trend:" => "📉", - "\\:chart_with_upwards_trend:" => "📈", - "\\:checkered_flag:" => "🏁", - "\\:cherries:" => "🍒", - "\\:cherry_blossom:" => "🌸", - "\\:chestnut:" => "🌰", - "\\:chicken:" => "🐔", - "\\:children_crossing:" => "🚸", - "\\:chocolate_bar:" => "🍫", - "\\:christmas_tree:" => "🎄", - "\\:church:" => "⛪", - "\\:cinema:" => "🎦", - "\\:circus_tent:" => "🎪", - "\\:city_sunrise:" => "🌇", - "\\:city_sunset:" => "🌆", - "\\:cl:" => "🆑", - "\\:clap:" => "👏", - "\\:clapper:" => "🎬", - "\\:clipboard:" => "📋", - "\\:clock1030:" => "🕥", - "\\:clock10:" => "🕙", - "\\:clock1130:" => "🕦", - "\\:clock11:" => "🕚", - "\\:clock1230:" => "🕧", - "\\:clock12:" => "🕛", - "\\:clock130:" => "🕜", - "\\:clock1:" => "🕐", - "\\:clock230:" => "🕝", - "\\:clock2:" => "🕑", - "\\:clock330:" => "🕞", - "\\:clock3:" => "🕒", - "\\:clock430:" => "🕟", - "\\:clock4:" => "🕓", - "\\:clock530:" => "🕠", - "\\:clock5:" => "🕔", - "\\:clock630:" => "🕡", - "\\:clock6:" => "🕕", - "\\:clock730:" => "🕢", - "\\:clock7:" => "🕖", - "\\:clock830:" => "🕣", - "\\:clock8:" => "🕗", - "\\:clock930:" => "🕤", - "\\:clock9:" => "🕘", - "\\:closed_book:" => "📕", - "\\:closed_lock_with_key:" => "🔐", - "\\:closed_umbrella:" => "🌂", - "\\:cloud:" => "☁", - "\\:clubs:" => "♣", - "\\:cocktail:" => "🍸", - "\\:coffee:" => "☕", - "\\:cold_sweat:" => "😰", - "\\:computer:" => "💻", - "\\:confetti_ball:" => "🎊", - "\\:confounded:" => "😖", - "\\:confused:" => "😕", - "\\:congratulations:" => "㊗", - "\\:construction:" => "🚧", - "\\:construction_worker:" => "👷", - "\\:convenience_store:" => "🏪", - "\\:cookie:" => "🍪", - "\\:cool:" => "🆒", - "\\:cop:" => "👮", - "\\:copyright:" => "©", - "\\:corn:" => "🌽", - "\\:couple:" => "👫", - "\\:couple_with_heart:" => "💑", - "\\:couplekiss:" => "💏", - "\\:cow2:" => "🐄", - "\\:cow:" => "🐮", - "\\:credit_card:" => "💳", - "\\:crescent_moon:" => "🌙", - "\\:crocodile:" => "🐊", - "\\:crossed_flags:" => "🎌", - "\\:crown:" => "👑", - "\\:cry:" => "😢", - "\\:crying_cat_face:" => "😿", - "\\:crystal_ball:" => "🔮", - "\\:cupid:" => "💘", - "\\:curly_loop:" => "➰", - "\\:currency_exchange:" => "💱", - "\\:curry:" => "🍛", - "\\:custard:" => "🍮", - "\\:customs:" => "🛃", - "\\:cyclone:" => "🌀", - "\\:dancer:" => "💃", - "\\:dancers:" => "👯", - "\\:dango:" => "🍡", - "\\:dart:" => "🎯", - "\\:dash:" => "💨", - "\\:date:" => "📅", - "\\:deciduous_tree:" => "🌳", - "\\:department_store:" => "🏬", - "\\:diamond_shape_with_a_dot_inside:" => "💠", - "\\:diamonds:" => "♦", - "\\:disappointed:" => "😞", - "\\:disappointed_relieved:" => "😥", - "\\:dizzy:" => "💫", - "\\:dizzy_face:" => "😵", - "\\:do_not_litter:" => "🚯", - "\\:dog2:" => "🐕", - "\\:dog:" => "🐶", - "\\:dollar:" => "💵", - "\\:dolls:" => "🎎", - "\\:dolphin:" => "🐬", - "\\:door:" => "🚪", - "\\:doughnut:" => "🍩", - "\\:dragon:" => "🐉", - "\\:dragon_face:" => "🐲", - "\\:dress:" => "👗", - "\\:dromedary_camel:" => "🐪", - "\\:droplet:" => "💧", - "\\:dvd:" => "📀", - "\\:e-mail:" => "📧", - "\\:ear:" => "👂", - "\\:ear_of_rice:" => "🌾", - "\\:earth_africa:" => "🌍", - "\\:earth_americas:" => "🌎", - "\\:earth_asia:" => "🌏", - "\\:egg:" => "🍳", - "\\:eggplant:" => "🍆", - "\\:eight_pointed_black_star:" => "✴", - "\\:eight_spoked_asterisk:" => "✳", - "\\:electric_plug:" => "🔌", - "\\:elephant:" => "🐘", - "\\:email:" => "✉", - "\\:end:" => "🔚", - "\\:envelope_with_arrow:" => "📩", - "\\:euro:" => "💶", - "\\:european_castle:" => "🏰", - "\\:european_post_office:" => "🏤", - "\\:evergreen_tree:" => "🌲", - "\\:exclamation:" => "❗", - "\\:expressionless:" => "😑", - "\\:eyeglasses:" => "👓", - "\\:eyes:" => "👀", - "\\:facepunch:" => "👊", - "\\:factory:" => "🏭", - "\\:fallen_leaf:" => "🍂", - "\\:family:" => "👪", - "\\:fast_forward:" => "⏩", - "\\:fax:" => "📠", - "\\:fearful:" => "😨", - "\\:feet:" => "🐾", - "\\:ferris_wheel:" => "🎡", - "\\:file_folder:" => "📁", - "\\:fire:" => "🔥", - "\\:fire_engine:" => "🚒", - "\\:fireworks:" => "🎆", - "\\:first_quarter_moon:" => "🌓", - "\\:first_quarter_moon_with_face:" => "🌛", - "\\:fish:" => "🐟", - "\\:fish_cake:" => "🍥", - "\\:fishing_pole_and_fish:" => "🎣", - "\\:fist:" => "✊", - "\\:flags:" => "🎏", - "\\:flashlight:" => "🔦", - "\\:floppy_disk:" => "💾", - "\\:flower_playing_cards:" => "🎴", - "\\:flushed:" => "😳", - "\\:foggy:" => "🌁", - "\\:football:" => "🏈", - "\\:footprints:" => "👣", - "\\:fork_and_knife:" => "🍴", - "\\:fountain:" => "⛲", - "\\:four_leaf_clover:" => "🍀", - "\\:free:" => "🆓", - "\\:fried_shrimp:" => "🍤", - "\\:fries:" => "🍟", - "\\:frog:" => "🐸", - "\\:frowning:" => "😦", - "\\:fuelpump:" => "⛽", - "\\:full_moon:" => "🌕", - "\\:full_moon_with_face:" => "🌝", - "\\:game_die:" => "🎲", - "\\:gem:" => "💎", - "\\:gemini:" => "♊", - "\\:ghost:" => "👻", - "\\:gift:" => "🎁", - "\\:gift_heart:" => "💝", - "\\:girl:" => "👧", - "\\:globe_with_meridians:" => "🌐", - "\\:goat:" => "🐐", - "\\:golf:" => "⛳", - "\\:grapes:" => "🍇", - "\\:green_apple:" => "🍏", - "\\:green_book:" => "📗", - "\\:green_heart:" => "💚", - "\\:grey_exclamation:" => "❕", - "\\:grey_question:" => "❔", - "\\:grimacing:" => "😬", - "\\:grin:" => "😁", - "\\:grinning:" => "😀", - "\\:guardsman:" => "💂", - "\\:guitar:" => "🎸", - "\\:gun:" => "🔫", - "\\:haircut:" => "💇", - "\\:hamburger:" => "🍔", - "\\:hammer:" => "🔨", - "\\:hamster:" => "🐹", - "\\:hand:" => "✋", - "\\:handbag:" => "👜", - "\\:hankey:" => "💩", - "\\:hatched_chick:" => "🐥", - "\\:hatching_chick:" => "🐣", - "\\:headphones:" => "🎧", - "\\:hear_no_evil:" => "🙉", - "\\:heart:" => "❤", - "\\:heart_decoration:" => "💟", - "\\:heart_eyes:" => "😍", - "\\:heart_eyes_cat:" => "😻", - "\\:heartbeat:" => "💓", - "\\:heartpulse:" => "💗", - "\\:hearts:" => "♥", - "\\:heavy_check_mark:" => "✔", - "\\:heavy_division_sign:" => "➗", - "\\:heavy_dollar_sign:" => "💲", - "\\:heavy_minus_sign:" => "➖", - "\\:heavy_multiplication_x:" => "✖", - "\\:heavy_plus_sign:" => "➕", - "\\:helicopter:" => "🚁", - "\\:herb:" => "🌿", - "\\:hibiscus:" => "🌺", - "\\:high_brightness:" => "🔆", - "\\:high_heel:" => "👠", - "\\:hocho:" => "🔪", - "\\:honey_pot:" => "🍯", - "\\:horse:" => "🐴", - "\\:horse_racing:" => "🏇", - "\\:hospital:" => "🏥", - "\\:hotel:" => "🏨", - "\\:hotsprings:" => "♨", - "\\:hourglass:" => "⌛", - "\\:hourglass_flowing_sand:" => "⏳", - "\\:house:" => "🏠", - "\\:house_with_garden:" => "🏡", - "\\:hushed:" => "😯", - "\\:ice_cream:" => "🍨", - "\\:icecream:" => "🍦", - "\\:id:" => "🆔", - "\\:ideograph_advantage:" => "🉐", - "\\:imp:" => "👿", - "\\:inbox_tray:" => "📥", - "\\:incoming_envelope:" => "📨", - "\\:information_desk_person:" => "💁", - "\\:information_source:" => "ℹ", - "\\:innocent:" => "😇", - "\\:interrobang:" => "⁉", - "\\:iphone:" => "📱", - "\\:izakaya_lantern:" => "🏮", - "\\:jack_o_lantern:" => "🎃", - "\\:japan:" => "🗾", - "\\:japanese_castle:" => "🏯", - "\\:japanese_goblin:" => "👺", - "\\:japanese_ogre:" => "👹", - "\\:jeans:" => "👖", - "\\:joy:" => "😂", - "\\:joy_cat:" => "😹", - "\\:key:" => "🔑", - "\\:keycap_ten:" => "🔟", - "\\:kimono:" => "👘", - "\\:kiss:" => "💋", - "\\:kissing:" => "😗", - "\\:kissing_cat:" => "😽", - "\\:kissing_closed_eyes:" => "😚", - "\\:kissing_heart:" => "😘", - "\\:kissing_smiling_eyes:" => "😙", - "\\:koala:" => "🐨", - "\\:koko:" => "🈁", - "\\:large_blue_circle:" => "🔵", - "\\:large_blue_diamond:" => "🔷", - "\\:large_orange_diamond:" => "🔶", - "\\:last_quarter_moon:" => "🌗", - "\\:last_quarter_moon_with_face:" => "🌜", - "\\:laughing:" => "😆", - "\\:leaves:" => "🍃", - "\\:ledger:" => "📒", - "\\:left_luggage:" => "🛅", - "\\:left_right_arrow:" => "↔", - "\\:leftwards_arrow_with_hook:" => "↩", - "\\:lemon:" => "🍋", - "\\:leo:" => "♌", - "\\:leopard:" => "🐆", - "\\:libra:" => "♎", - "\\:light_rail:" => "🚈", - "\\:link:" => "🔗", - "\\:lips:" => "👄", - "\\:lipstick:" => "💄", - "\\:lock:" => "🔒", - "\\:lock_with_ink_pen:" => "🔏", - "\\:lollipop:" => "🍭", - "\\:loop:" => "➿", - "\\:loud_sound:" => "🔊", - "\\:loudspeaker:" => "📢", - "\\:love_hotel:" => "🏩", - "\\:love_letter:" => "💌", - "\\:low_brightness:" => "🔅", - "\\:m:" => "Ⓜ", - "\\:mag:" => "🔍", - "\\:mag_right:" => "🔎", - "\\:mahjong:" => "🀄", - "\\:mailbox:" => "📫", - "\\:mailbox_closed:" => "📪", - "\\:mailbox_with_mail:" => "📬", - "\\:mailbox_with_no_mail:" => "📭", - "\\:man:" => "👨", - "\\:man_with_gua_pi_mao:" => "👲", - "\\:man_with_turban:" => "👳", - "\\:mans_shoe:" => "👞", - "\\:maple_leaf:" => "🍁", - "\\:mask:" => "😷", - "\\:massage:" => "💆", - "\\:meat_on_bone:" => "🍖", - "\\:mega:" => "📣", - "\\:melon:" => "🍈", - "\\:memo:" => "📝", - "\\:mens:" => "🚹", - "\\:metro:" => "🚇", - "\\:microphone:" => "🎤", - "\\:microscope:" => "🔬", - "\\:milky_way:" => "🌌", - "\\:minibus:" => "🚐", - "\\:minidisc:" => "💽", - "\\:mobile_phone_off:" => "📴", - "\\:money_with_wings:" => "💸", - "\\:moneybag:" => "💰", - "\\:monkey:" => "🐒", - "\\:monkey_face:" => "🐵", - "\\:monorail:" => "🚝", - "\\:moon:" => "🌔", - "\\:mortar_board:" => "🎓", - "\\:mount_fuji:" => "🗻", - "\\:mountain_bicyclist:" => "🚵", - "\\:mountain_cableway:" => "🚠", - "\\:mountain_railway:" => "🚞", - "\\:mouse2:" => "🐁", - "\\:mouse:" => "🐭", - "\\:movie_camera:" => "🎥", - "\\:moyai:" => "🗿", - "\\:muscle:" => "💪", - "\\:mushroom:" => "🍄", - "\\:musical_keyboard:" => "🎹", - "\\:musical_note:" => "🎵", - "\\:musical_score:" => "🎼", - "\\:mute:" => "🔇", - "\\:nail_care:" => "💅", - "\\:name_badge:" => "📛", - "\\:necktie:" => "👔", - "\\:negative_squared_cross_mark:" => "❎", - "\\:neutral_face:" => "😐", - "\\:new:" => "🆕", - "\\:new_moon:" => "🌑", - "\\:new_moon_with_face:" => "🌚", - "\\:newspaper:" => "📰", - "\\:ng:" => "🆖", - "\\:night_with_stars:" => "🌃", - "\\:no_bell:" => "🔕", - "\\:no_bicycles:" => "🚳", - "\\:no_entry:" => "⛔", - "\\:no_entry_sign:" => "🚫", - "\\:no_good:" => "🙅", - "\\:no_mobile_phones:" => "📵", - "\\:no_mouth:" => "😶", - "\\:no_pedestrians:" => "🚷", - "\\:no_smoking:" => "🚭", - "\\:non-potable_water:" => "🚱", - "\\:nose:" => "👃", - "\\:notebook:" => "📓", - "\\:notebook_with_decorative_cover:" => "📔", - "\\:notes:" => "🎶", - "\\:nut_and_bolt:" => "🔩", - "\\:o2:" => "🅾", - "\\:o:" => "⭕", - "\\:ocean:" => "🌊", - "\\:octopus:" => "🐙", - "\\:oden:" => "🍢", - "\\:office:" => "🏢", - "\\:ok:" => "🆗", - "\\:ok_hand:" => "👌", - "\\:ok_woman:" => "🙆", - "\\:older_man:" => "👴", - "\\:older_woman:" => "👵", - "\\:on:" => "🔛", - "\\:oncoming_automobile:" => "🚘", - "\\:oncoming_bus:" => "🚍", - "\\:oncoming_police_car:" => "🚔", - "\\:oncoming_taxi:" => "🚖", - "\\:open_file_folder:" => "📂", - "\\:open_hands:" => "👐", - "\\:open_mouth:" => "😮", - "\\:ophiuchus:" => "⛎", - "\\:orange_book:" => "📙", - "\\:outbox_tray:" => "📤", - "\\:ox:" => "🐂", - "\\:package:" => "📦", - "\\:page_facing_up:" => "📄", - "\\:page_with_curl:" => "📃", - "\\:pager:" => "📟", - "\\:palm_tree:" => "🌴", - "\\:panda_face:" => "🐼", - "\\:paperclip:" => "📎", - "\\:parking:" => "🅿", - "\\:part_alternation_mark:" => "〽", - "\\:partly_sunny:" => "⛅", - "\\:passport_control:" => "🛂", - "\\:peach:" => "🍑", - "\\:pear:" => "🍐", - "\\:pencil2:" => "✏", - "\\:penguin:" => "🐧", - "\\:pensive:" => "😔", - "\\:performing_arts:" => "🎭", - "\\:persevere:" => "😣", - "\\:person_frowning:" => "🙍", - "\\:person_with_blond_hair:" => "👱", - "\\:person_with_pouting_face:" => "🙎", - "\\:phone:" => "☎", - "\\:pig2:" => "🐖", - "\\:pig:" => "🐷", - "\\:pig_nose:" => "🐽", - "\\:pill:" => "💊", - "\\:pineapple:" => "🍍", - "\\:pisces:" => "♓", - "\\:pizza:" => "🍕", - "\\:point_down:" => "👇", - "\\:point_left:" => "👈", - "\\:point_right:" => "👉", - "\\:point_up:" => "☝", - "\\:point_up_2:" => "👆", - "\\:police_car:" => "🚓", - "\\:poodle:" => "🐩", - "\\:post_office:" => "🏣", - "\\:postal_horn:" => "📯", - "\\:postbox:" => "📮", - "\\:potable_water:" => "🚰", - "\\:pouch:" => "👝", - "\\:poultry_leg:" => "🍗", - "\\:pound:" => "💷", - "\\:pouting_cat:" => "😾", - "\\:pray:" => "🙏", - "\\:princess:" => "👸", - "\\:purple_heart:" => "💜", - "\\:purse:" => "👛", - "\\:pushpin:" => "📌", - "\\:put_litter_in_its_place:" => "🚮", - "\\:question:" => "❓", - "\\:rabbit2:" => "🐇", - "\\:rabbit:" => "🐰", - "\\:racehorse:" => "🐎", - "\\:radio:" => "📻", - "\\:radio_button:" => "🔘", - "\\:rage:" => "😡", - "\\:railway_car:" => "🚃", - "\\:rainbow:" => "🌈", - "\\:raised_hands:" => "🙌", - "\\:raising_hand:" => "🙋", - "\\:ram:" => "🐏", - "\\:ramen:" => "🍜", - "\\:rat:" => "🐀", - "\\:recycle:" => "♻", - "\\:red_circle:" => "🔴", - "\\:registered:" => "®", - "\\:relaxed:" => "☺", - "\\:relieved:" => "😌", - "\\:repeat:" => "🔁", - "\\:repeat_one:" => "🔂", - "\\:restroom:" => "🚻", - "\\:revolving_hearts:" => "💞", - "\\:rewind:" => "⏪", - "\\:ribbon:" => "🎀", - "\\:rice:" => "🍚", - "\\:rice_ball:" => "🍙", - "\\:rice_cracker:" => "🍘", - "\\:rice_scene:" => "🎑", - "\\:ring:" => "💍", - "\\:rocket:" => "🚀", - "\\:roller_coaster:" => "🎢", - "\\:rooster:" => "🐓", - "\\:rose:" => "🌹", - "\\:rotating_light:" => "🚨", - "\\:round_pushpin:" => "📍", - "\\:rowboat:" => "🚣", - "\\:rugby_football:" => "🏉", - "\\:runner:" => "🏃", - "\\:running_shirt_with_sash:" => "🎽", - "\\:sa:" => "🈂", - "\\:sagittarius:" => "♐", - "\\:sake:" => "🍶", - "\\:sandal:" => "👡", - "\\:santa:" => "🎅", - "\\:satellite:" => "📡", - "\\:saxophone:" => "🎷", - "\\:school:" => "🏫", - "\\:school_satchel:" => "🎒", - "\\:scissors:" => "✂", - "\\:scorpius:" => "♏", - "\\:scream:" => "😱", - "\\:scream_cat:" => "🙀", - "\\:scroll:" => "📜", - "\\:seat:" => "💺", - "\\:secret:" => "㊙", - "\\:see_no_evil:" => "🙈", - "\\:seedling:" => "🌱", - "\\:shaved_ice:" => "🍧", - "\\:sheep:" => "🐑", - "\\:shell:" => "🐚", - "\\:ship:" => "🚢", - "\\:shirt:" => "👕", - "\\:shower:" => "🚿", - "\\:signal_strength:" => "📶", - "\\:six_pointed_star:" => "🔯", - "\\:ski:" => "🎿", - "\\:skin-tone-2:" => "\U1f3fb", - "\\:skin-tone-3:" => "\U1f3fc", - "\\:skin-tone-4:" => "\U1f3fd", - "\\:skin-tone-5:" => "\U1f3fe", - "\\:skin-tone-6:" => "\U1f3ff", - "\\:skull:" => "💀", - "\\:sleeping:" => "😴", - "\\:sleepy:" => "😪", - "\\:slot_machine:" => "🎰", - "\\:small_blue_diamond:" => "🔹", - "\\:small_orange_diamond:" => "🔸", - "\\:small_red_triangle:" => "🔺", - "\\:small_red_triangle_down:" => "🔻", - "\\:smile:" => "😄", - "\\:smile_cat:" => "😸", - "\\:smiley:" => "😃", - "\\:smiley_cat:" => "😺", - "\\:smiling_imp:" => "😈", - "\\:smirk:" => "😏", - "\\:smirk_cat:" => "😼", - "\\:smoking:" => "🚬", - "\\:snail:" => "🐌", - "\\:snake:" => "🐍", - "\\:snowboarder:" => "🏂", - "\\:snowflake:" => "❄", - "\\:snowman:" => "⛄", - "\\:sob:" => "😭", - "\\:soccer:" => "⚽", - "\\:soon:" => "🔜", - "\\:sos:" => "🆘", - "\\:sound:" => "🔉", - "\\:space_invader:" => "👾", - "\\:spades:" => "♠", - "\\:spaghetti:" => "🍝", - "\\:sparkle:" => "❇", - "\\:sparkler:" => "🎇", - "\\:sparkles:" => "✨", - "\\:sparkling_heart:" => "💖", - "\\:speak_no_evil:" => "🙊", - "\\:speaker:" => "🔈", - "\\:speech_balloon:" => "💬", - "\\:speedboat:" => "🚤", - "\\:star2:" => "🌟", - "\\:star:" => "⭐", - "\\:stars:" => "🌠", - "\\:station:" => "🚉", - "\\:statue_of_liberty:" => "🗽", - "\\:steam_locomotive:" => "🚂", - "\\:stew:" => "🍲", - "\\:straight_ruler:" => "📏", - "\\:strawberry:" => "🍓", - "\\:stuck_out_tongue:" => "😛", - "\\:stuck_out_tongue_closed_eyes:" => "😝", - "\\:stuck_out_tongue_winking_eye:" => "😜", - "\\:sun_with_face:" => "🌞", - "\\:sunflower:" => "🌻", - "\\:sunglasses:" => "😎", - "\\:sunny:" => "☀", - "\\:sunrise:" => "🌅", - "\\:sunrise_over_mountains:" => "🌄", - "\\:surfer:" => "🏄", - "\\:sushi:" => "🍣", - "\\:suspension_railway:" => "🚟", - "\\:sweat:" => "😓", - "\\:sweat_drops:" => "💦", - "\\:sweat_smile:" => "😅", - "\\:sweet_potato:" => "🍠", - "\\:swimmer:" => "🏊", - "\\:symbols:" => "🔣", - "\\:syringe:" => "💉", - "\\:tada:" => "🎉", - "\\:tanabata_tree:" => "🎋", - "\\:tangerine:" => "🍊", - "\\:taurus:" => "♉", - "\\:taxi:" => "🚕", - "\\:tea:" => "🍵", - "\\:telephone_receiver:" => "📞", - "\\:telescope:" => "🔭", - "\\:tennis:" => "🎾", - "\\:tent:" => "⛺", - "\\:thought_balloon:" => "💭", - "\\:ticket:" => "🎫", - "\\:tiger2:" => "🐅", - "\\:tiger:" => "🐯", - "\\:tired_face:" => "😫", - "\\:tm:" => "™", - "\\:toilet:" => "🚽", - "\\:tokyo_tower:" => "🗼", - "\\:tomato:" => "🍅", - "\\:tongue:" => "👅", - "\\:top:" => "🔝", - "\\:tophat:" => "🎩", - "\\:tractor:" => "🚜", - "\\:traffic_light:" => "🚥", - "\\:train2:" => "🚆", - "\\:train:" => "🚋", - "\\:tram:" => "🚊", - "\\:triangular_flag_on_post:" => "🚩", - "\\:triangular_ruler:" => "📐", - "\\:trident:" => "🔱", - "\\:triumph:" => "😤", - "\\:trolleybus:" => "🚎", - "\\:trophy:" => "🏆", - "\\:tropical_drink:" => "🍹", - "\\:tropical_fish:" => "🐠", - "\\:truck:" => "🚚", - "\\:trumpet:" => "🎺", - "\\:tulip:" => "🌷", - "\\:turtle:" => "🐢", - "\\:tv:" => "📺", - "\\:twisted_rightwards_arrows:" => "🔀", - "\\:two_hearts:" => "💕", - "\\:two_men_holding_hands:" => "👬", - "\\:two_women_holding_hands:" => "👭", - "\\:u5272:" => "🈹", - "\\:u5408:" => "🈴", - "\\:u55b6:" => "🈺", - "\\:u6307:" => "🈯", - "\\:u6708:" => "🈷", - "\\:u6709:" => "🈶", - "\\:u6e80:" => "🈵", - "\\:u7121:" => "🈚", - "\\:u7533:" => "🈸", - "\\:u7981:" => "🈲", - "\\:u7a7a:" => "🈳", - "\\:umbrella:" => "☔", - "\\:unamused:" => "😒", - "\\:underage:" => "🔞", - "\\:unlock:" => "🔓", - "\\:up:" => "🆙", - "\\:v:" => "✌", - "\\:vertical_traffic_light:" => "🚦", - "\\:vhs:" => "📼", - "\\:vibration_mode:" => "📳", - "\\:video_camera:" => "📹", - "\\:video_game:" => "🎮", - "\\:violin:" => "🎻", - "\\:virgo:" => "♍", - "\\:volcano:" => "🌋", - "\\:vs:" => "🆚", - "\\:walking:" => "🚶", - "\\:waning_crescent_moon:" => "🌘", - "\\:waning_gibbous_moon:" => "🌖", - "\\:warning:" => "⚠", - "\\:watch:" => "⌚", - "\\:water_buffalo:" => "🐃", - "\\:watermelon:" => "🍉", - "\\:wave:" => "👋", - "\\:wavy_dash:" => "〰", - "\\:waxing_crescent_moon:" => "🌒", - "\\:wc:" => "🚾", - "\\:weary:" => "😩", - "\\:wedding:" => "💒", - "\\:whale2:" => "🐋", - "\\:whale:" => "🐳", - "\\:wheelchair:" => "♿", - "\\:white_check_mark:" => "✅", - "\\:white_circle:" => "⚪", - "\\:white_flower:" => "💮", - "\\:white_large_square:" => "⬜", - "\\:white_medium_small_square:" => "◽", - "\\:white_medium_square:" => "◻", - "\\:white_small_square:" => "▫", - "\\:white_square_button:" => "🔳", - "\\:wind_chime:" => "🎐", - "\\:wine_glass:" => "🍷", - "\\:wink:" => "😉", - "\\:wolf:" => "🐺", - "\\:woman:" => "👩", - "\\:womans_clothes:" => "👚", - "\\:womans_hat:" => "👒", - "\\:womens:" => "🚺", - "\\:worried:" => "😟", - "\\:wrench:" => "🔧", - "\\:x:" => "❌", - "\\:yellow_heart:" => "💛", - "\\:yen:" => "💴", - "\\:yum:" => "😋", - "\\:zap:" => "⚡", - "\\:zzz:" => "💤", -) diff --git a/julia-0.6.3/share/julia/base/env.jl b/julia-0.6.3/share/julia/base/env.jl deleted file mode 100644 index 485987f..0000000 --- a/julia-0.6.3/share/julia/base/env.jl +++ /dev/null @@ -1,164 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -if is_windows() - const ERROR_ENVVAR_NOT_FOUND = UInt32(203) - - _getenvlen(var::Vector{UInt16}) = ccall(:GetEnvironmentVariableW,stdcall,UInt32,(Ptr{UInt16},Ptr{UInt16},UInt32),var,C_NULL,0) - _hasenv(s::Vector{UInt16}) = _getenvlen(s) != 0 || Libc.GetLastError() != ERROR_ENVVAR_NOT_FOUND - _hasenv(s::AbstractString) = _hasenv(cwstring(s)) - - function access_env(onError::Function, str::AbstractString) - var = cwstring(str) - len = _getenvlen(var) - if len == 0 - return Libc.GetLastError() != ERROR_ENVVAR_NOT_FOUND ? "" : onError(str) - end - val = zeros(UInt16,len) - ret = ccall(:GetEnvironmentVariableW,stdcall,UInt32,(Ptr{UInt16},Ptr{UInt16},UInt32),var,val,len) - if (ret == 0 && len != 1) || ret != len-1 || val[end] != 0 - error(string("getenv: ", str, ' ', len, "-1 != ", ret, ": ", Libc.FormatMessage())) - end - pop!(val) # NUL - return transcode(String, val) - end - - function _setenv(svar::AbstractString, sval::AbstractString, overwrite::Bool=true) - var = cwstring(svar) - val = cwstring(sval) - if overwrite || !_hasenv(var) - ret = ccall(:SetEnvironmentVariableW,stdcall,Int32,(Ptr{UInt16},Ptr{UInt16}),var,val) - systemerror(:setenv, ret == 0) - end - end - - function _unsetenv(svar::AbstractString) - var = cwstring(svar) - ret = ccall(:SetEnvironmentVariableW,stdcall,Int32,(Ptr{UInt16},Ptr{UInt16}),var,C_NULL) - systemerror(:setenv, ret == 0) - end -else # !windows - _getenv(var::AbstractString) = ccall(:getenv, Cstring, (Cstring,), var) - _hasenv(s::AbstractString) = _getenv(s) != C_NULL - - function access_env(onError::Function, var::AbstractString) - val = _getenv(var) - val == C_NULL ? onError(var) : unsafe_string(val) - end - - function _setenv(var::AbstractString, val::AbstractString, overwrite::Bool=true) - ret = ccall(:setenv, Int32, (Cstring,Cstring,Int32), var, val, overwrite) - systemerror(:setenv, ret != 0) - end - - function _unsetenv(var::AbstractString) - ret = ccall(:unsetenv, Int32, (Cstring,), var) - systemerror(:unsetenv, ret != 0) - end -end # os test - -## ENV: hash interface ## - -""" - EnvHash() -> EnvHash - -A singleton of this type provides a hash table interface to environment variables. -""" -mutable struct EnvHash <: Associative{String,String}; end - -""" - ENV - -Reference to the singleton `EnvHash`, providing a dictionary interface to system environment -variables. -""" -const ENV = EnvHash() - -similar(::EnvHash) = Dict{String,String}() - -getindex(::EnvHash, k::AbstractString) = access_env(k->throw(KeyError(k)), k) -get(::EnvHash, k::AbstractString, def) = access_env(k->def, k) -in(k::AbstractString, ::KeyIterator{EnvHash}) = _hasenv(k) -pop!(::EnvHash, k::AbstractString) = (v = ENV[k]; _unsetenv(k); v) -pop!(::EnvHash, k::AbstractString, def) = haskey(ENV,k) ? pop!(ENV,k) : def -delete!(::EnvHash, k::AbstractString) = (_unsetenv(k); ENV) -setindex!(::EnvHash, v, k::AbstractString) = _setenv(k,string(v)) -push!(::EnvHash, k::AbstractString, v) = setindex!(ENV, v, k) - -if is_windows() - start(hash::EnvHash) = (pos = ccall(:GetEnvironmentStringsW,stdcall,Ptr{UInt16},()); (pos,pos)) - function done(hash::EnvHash, block::Tuple{Ptr{UInt16},Ptr{UInt16}}) - if unsafe_load(block[1]) == 0 - ccall(:FreeEnvironmentStringsW, stdcall, Int32, (Ptr{UInt16},), block[2]) - return true - end - return false - end - function next(hash::EnvHash, block::Tuple{Ptr{UInt16},Ptr{UInt16}}) - pos = block[1] - blk = block[2] - len = ccall(:wcslen, UInt, (Ptr{UInt16},), pos) - buf = Vector{UInt16}(len) - unsafe_copy!(pointer(buf), pos, len) - env = transcode(String, buf) - m = match(r"^(=?[^=]+)=(.*)$"s, env) - if m === nothing - error("malformed environment entry: $env") - end - return (Pair{String,String}(m.captures[1], m.captures[2]), (pos+(len+1)*2, blk)) - end -else # !windows - start(::EnvHash) = 0 - done(::EnvHash, i) = (ccall(:jl_environ, Any, (Int32,), i) === nothing) - - function next(::EnvHash, i) - env = ccall(:jl_environ, Any, (Int32,), i) - if env === nothing - throw(BoundsError()) - end - env = env::String - m = match(r"^(.*?)=(.*)$"s, env) - if m === nothing - error("malformed environment entry: $env") - end - return (Pair{String,String}(m.captures[1], m.captures[2]), i+1) - end -end # os-test - -#TODO: Make these more efficent -function length(::EnvHash) - i = 0 - for (k,v) in ENV - i += 1 - end - return i -end - -function show(io::IO, ::EnvHash) - for (k,v) = ENV - println(io, "$k=$v") - end -end - -""" - withenv(f::Function, kv::Pair...) - -Execute `f()` in an environment that is temporarily modified (not replaced as in `setenv`) -by zero or more `"var"=>val` arguments `kv`. `withenv` is generally used via the -`withenv(kv...) do ... end` syntax. A value of `nothing` can be used to temporarily unset an -environment variable (if it is set). When `withenv` returns, the original environment has -been restored. -""" -function withenv{T<:AbstractString}(f::Function, keyvals::Pair{T}...) - old = Dict{T,Any}() - for (key,val) in keyvals - old[key] = get(ENV,key,nothing) - val !== nothing ? (ENV[key]=val) : delete!(ENV, key) - end - try f() - finally - for (key,val) in old - val !== nothing ? (ENV[key]=val) : delete!(ENV, key) - end - end -end -withenv(f::Function) = f() # handle empty keyvals case; see #10853 diff --git a/julia-0.6.3/share/julia/base/errno.jl b/julia-0.6.3/share/julia/base/errno.jl deleted file mode 100644 index 19da123..0000000 --- a/julia-0.6.3/share/julia/base/errno.jl +++ /dev/null @@ -1,135 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -include("errno_h.jl") -export - E2BIG, - EACCES, - EADDRINUSE, - EADDRNOTAVAIL, - EADV, - EAFNOSUPPORT, - EAGAIN, - EALREADY, - EBADE, - EBADF, - EBADFD, - EBADMSG, - EBADR, - EBADRQC, - EBADSLT, - EBFONT, - EBUSY, - ECANCELED, - ECHILD, - ECHRNG, - ECOMM, - ECONNABORTED, - ECONNREFUSED, - ECONNRESET, - EDEADLK, - EDESTADDRREQ, - EDOM, - EDOTDOT, - EDQUOT, - EEXIST, - EFAULT, - EFBIG, - EHOSTDOWN, - EHOSTUNREACH, - EHWPOISON, - EIDRM, - EILSEQ, - EINPROGRESS, - EINTR, - EINVAL, - EIO, - EISCONN, - EISDIR, - EISNAM, - EKEYEXPIRED, - EKEYREJECTED, - EKEYREVOKED, - EL2HLT, - EL2NSYNC, - EL3HLT, - EL3RST, - ELIBACC, - ELIBBAD, - ELIBEXEC, - ELIBMAX, - ELIBSCN, - ELNRNG, - ELOOP, - EMEDIUMTYPE, - EMFILE, - EMLINK, - EMSGSIZE, - EMULTIHOP, - ENAMETOOLONG, - ENAVAIL, - ENETDOWN, - ENETRESET, - ENETUNREACH, - ENFILE, - ENOANO, - ENOBUFS, - ENOCSI, - ENODATA, - ENODEV, - ENOENT, - ENOEXEC, - ENOKEY, - ENOLCK, - ENOLINK, - ENOMEDIUM, - ENOMEM, - ENOMSG, - ENONET, - ENOPKG, - ENOPROTOOPT, - ENOSPC, - ENOSR, - ENOSTR, - ENOSYS, - ENOTBLK, - ENOTCONN, - ENOTDIR, - ENOTEMPTY, - ENOTNAM, - ENOTRECOVERABLE, - ENOTSOCK, - ENOTTY, - ENOTUNIQ, - ENXIO, - EOPNOTSUPP, - EOVERFLOW, - EOWNERDEAD, - EPERM, - EPFNOSUPPORT, - EPIPE, - EPROTO, - EPROTONOSUPPORT, - EPROTOTYPE, - ERANGE, - EREMCHG, - EREMOTE, - EREMOTEIO, - ERESTART, - ERFKILL, - EROFS, - ESHUTDOWN, - ESOCKTNOSUPPORT, - ESPIPE, - ESRCH, - ESRMNT, - ESTALE, - ESTRPIPE, - ETIME, - ETIMEDOUT, - ETOOMANYREFS, - ETXTBSY, - EUCLEAN, - EUNATCH, - EUSERS, - EXDEV, - EXFULL diff --git a/julia-0.6.3/share/julia/base/error.jl b/julia-0.6.3/share/julia/base/error.jl deleted file mode 100644 index f26df61..0000000 --- a/julia-0.6.3/share/julia/base/error.jl +++ /dev/null @@ -1,151 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -# pseudo-definitions to show how everything behaves -# -# throw(label, val) = # throw a value to a dynamically enclosing block -# -# function rethrow(val) -# global current_exception = val -# throw(current_handler(), current_exception) -# end -# -# rethrow() = rethrow(current_exception) -# -# function throw(val) -# global catch_backtrace = backtrace() -# rethrow(val) -# end - -## native julia error handling ## - -error(s::AbstractString) = throw(ErrorException(s)) - -""" - error(msg...) - -Raise an `ErrorException` with the given message. - -See also [`logging`](@ref). -""" -error(s...) = throw(ErrorException(Main.Base.string(s...))) - -""" - rethrow([e]) - -Throw an object without changing the current exception backtrace. The default argument is -the current exception (if called within a `catch` block). -""" -rethrow() = ccall(:jl_rethrow, Bottom, ()) -rethrow(e) = ccall(:jl_rethrow_other, Bottom, (Any,), e) - -""" - backtrace() - -Get a backtrace object for the current program point. -""" -backtrace() = ccall(:jl_backtrace_from_here, Array{Ptr{Void},1}, (Int32,), false) - -""" - catch_backtrace() - -Get the backtrace of the current exception, for use within `catch` blocks. -""" -catch_backtrace() = ccall(:jl_get_backtrace, Array{Ptr{Void},1}, ()) - -## keyword arg lowering generates calls to this ## -kwerr(kw, args...) = throw(MethodError(typeof(args[1]).name.mt.kwsorter, (kw,args...))) - -## system error handling ## -""" - systemerror(sysfunc, iftrue) - -Raises a `SystemError` for `errno` with the descriptive string `sysfunc` if `iftrue` is `true` -""" -systemerror(p, b::Bool; extrainfo=nothing) = b ? throw(Main.Base.SystemError(string(p), Libc.errno(), extrainfo)) : nothing - -## assertion functions and macros ## - -assert(x) = x ? nothing : throw(Main.Base.AssertionError()) -macro assert(ex, msgs...) - msg = isempty(msgs) ? ex : msgs[1] - if isa(msg, AbstractString) - msg = msg # pass-through - elseif !isempty(msgs) && (isa(msg, Expr) || isa(msg, Symbol)) - # message is an expression needing evaluating - msg = :(Main.Base.string($(esc(msg)))) - elseif isdefined(Main, :Base) && isdefined(Main.Base, :string) && applicable(Main.Base.string, msg) - msg = Main.Base.string(msg) - else - # string() might not be defined during bootstrap - msg = :(Main.Base.string($(Expr(:quote,msg)))) - end - return :($(esc(ex)) ? $(nothing) : throw(Main.Base.AssertionError($msg))) -end - -struct ExponentialBackOff - n::Int - first_delay::Float64 - max_delay::Float64 - factor::Float64 - jitter::Float64 - - function ExponentialBackOff(n, first_delay, max_delay, factor, jitter) - all(x->x>=0, (n, first_delay, max_delay, factor, jitter)) || error("all inputs must be non-negative") - new(n, first_delay, max_delay, factor, jitter) - end -end - -""" - ExponentialBackOff(; n=1, first_delay=0.05, max_delay=10.0, factor=5.0, jitter=0.1) - -A [`Float64`](@ref) iterator of length `n` whose elements exponentially increase at a -rate in the interval `factor` * (1 ± `jitter`). The first element is -`first_delay` and all elements are clamped to `max_delay`. -""" -ExponentialBackOff(; n=1, first_delay=0.05, max_delay=10.0, factor=5.0, jitter=0.1) = - ExponentialBackOff(n, first_delay, max_delay, factor, jitter) -start(ebo::ExponentialBackOff) = (ebo.n, min(ebo.first_delay, ebo.max_delay)) -function next(ebo::ExponentialBackOff, state) - next_n = state[1]-1 - curr_delay = state[2] - next_delay = min(ebo.max_delay, state[2] * ebo.factor * (1.0 - ebo.jitter + (rand() * 2.0 * ebo.jitter))) - (curr_delay, (next_n, next_delay)) -end -done(ebo::ExponentialBackOff, state) = state[1]<1 -length(ebo::ExponentialBackOff) = ebo.n - -""" - retry(f::Function; delays=ExponentialBackOff(), check=nothing) -> Function - -Returns an anonymous function that calls function `f`. If an exception arises, -`f` is repeatedly called again, each time `check` returns `true`, after waiting the -number of seconds specified in `delays`. `check` should input `delays`'s -current state and the `Exception`. - -# Examples -```julia -retry(f, delays=fill(5.0, 3)) -retry(f, delays=rand(5:10, 2)) -retry(f, delays=Base.ExponentialBackOff(n=3, first_delay=5, max_delay=1000)) -retry(http_get, check=(s,e)->e.status == "503")(url) -retry(read, check=(s,e)->isa(e, UVError))(io, 128; all=false) -``` -""" -function retry(f::Function; delays=ExponentialBackOff(), check=nothing) - (args...; kwargs...) -> begin - state = start(delays) - while true - try - return f(args...; kwargs...) - catch e - done(delays, state) && rethrow(e) - if check !== nothing - state, retry_or_not = check(state, e) - retry_or_not || rethrow(e) - end - end - (delay, state) = next(delays, state) - sleep(delay) - end - end -end diff --git a/julia-0.6.3/share/julia/base/essentials.jl b/julia-0.6.3/share/julia/base/essentials.jl deleted file mode 100644 index cdeb952..0000000 --- a/julia-0.6.3/share/julia/base/essentials.jl +++ /dev/null @@ -1,370 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -using Core: CodeInfo - -const Callable = Union{Function,Type} - -const Bottom = Union{} - -abstract type AbstractSet{T} end -abstract type Associative{K,V} end - -# The real @inline macro is not available until after array.jl, so this -# internal macro splices the meta Expr directly into the function body. -macro _inline_meta() - Expr(:meta, :inline) -end -macro _noinline_meta() - Expr(:meta, :noinline) -end -macro _pure_meta() - Expr(:meta, :pure) -end -# another version of inlining that propagates an inbounds context -macro _propagate_inbounds_meta() - Expr(:meta, :inline, :propagate_inbounds) -end - -convert(::Type{Any}, x::ANY) = x -convert(::Type{T}, x::T) where {T} = x - -convert(::Type{Tuple{}}, ::Tuple{}) = () -convert(::Type{Tuple}, x::Tuple) = x -convert(::Type{Tuple{Vararg{T}}}, x::Tuple) where {T} = cnvt_all(T, x...) -cnvt_all(T) = () -cnvt_all(T, x, rest...) = tuple(convert(T,x), cnvt_all(T, rest...)...) - -macro generated(f) - if isa(f, Expr) && (f.head === :function || is_short_function_def(f)) - f.head = :stagedfunction - return Expr(:escape, f) - else - error("invalid syntax; @generated must be used with a function definition") - end -end - -""" - @eval [mod,] ex - -Evaluate an expression with values interpolated into it using `eval`. -If two arguments are provided, the first is the module to evaluate in. -""" -macro eval(ex) - :(eval($(current_module()), $(Expr(:quote,ex)))) -end -macro eval(mod, ex) - :(eval($(esc(mod)), $(Expr(:quote,ex)))) -end - -argtail(x, rest...) = rest -tail(x::Tuple) = argtail(x...) - -tuple_type_head(T::UnionAll) = (@_pure_meta; UnionAll(T.var, tuple_type_head(T.body))) -function tuple_type_head(T::DataType) - @_pure_meta - T.name === Tuple.name || throw(MethodError(tuple_type_head, (T,))) - return unwrapva(T.parameters[1]) -end -tuple_type_tail(T::UnionAll) = (@_pure_meta; UnionAll(T.var, tuple_type_tail(T.body))) -function tuple_type_tail(T::DataType) - @_pure_meta - T.name === Tuple.name || throw(MethodError(tuple_type_tail, (T,))) - if isvatuple(T) && length(T.parameters) == 1 - return T - end - return Tuple{argtail(T.parameters...)...} -end - -tuple_type_cons(::Type, ::Type{Union{}}) = Union{} -function tuple_type_cons{S,T<:Tuple}(::Type{S}, ::Type{T}) - @_pure_meta - Tuple{S, T.parameters...} -end - -function unwrap_unionall(a::ANY) - while isa(a,UnionAll) - a = a.body - end - return a -end - -function rewrap_unionall(t::ANY, u::ANY) - if !isa(u, UnionAll) - return t - end - return UnionAll(u.var, rewrap_unionall(t, u.body)) -end - -# replace TypeVars in all enclosing UnionAlls with fresh TypeVars -function rename_unionall(u::ANY) - if !isa(u,UnionAll) - return u - end - body = rename_unionall(u.body) - if body === u.body - body = u - else - body = UnionAll(u.var, body) - end - var = u.var::TypeVar - nv = TypeVar(var.name, var.lb, var.ub) - return UnionAll(nv, body{nv}) -end - -const _va_typename = Vararg.body.body.name -function isvarargtype(t::ANY) - t = unwrap_unionall(t) - isa(t, DataType) && (t::DataType).name === _va_typename -end - -isvatuple(t::DataType) = (n = length(t.parameters); n > 0 && isvarargtype(t.parameters[n])) -function unwrapva(t::ANY) - t2 = unwrap_unionall(t) - isvarargtype(t2) ? t2.parameters[1] : t -end - -typename(a) = error("typename does not apply to this type") -typename(a::DataType) = a.name -function typename(a::Union) - ta = typename(a.a) - tb = typename(a.b) - ta === tb ? tb : error("typename does not apply to unions whose components have different typenames") -end -typename(union::UnionAll) = typename(union.body) - -convert(::Type{T}, x::Tuple{Any,Vararg{Any}}) where {T<:Tuple{Any,Vararg{Any}}} = - tuple(convert(tuple_type_head(T),x[1]), convert(tuple_type_tail(T), tail(x))...) -convert(::Type{T}, x::T) where {T<:Tuple{Any,Vararg{Any}}} = x - -oftype(x,c) = convert(typeof(x),c) - -unsigned(x::Int) = reinterpret(UInt, x) -signed(x::UInt) = reinterpret(Int, x) - -# conversions used by ccall -ptr_arg_cconvert(::Type{Ptr{T}}, x) where {T} = cconvert(T, x) -ptr_arg_unsafe_convert(::Type{Ptr{T}}, x) where {T} = unsafe_convert(T, x) -ptr_arg_unsafe_convert(::Type{Ptr{Void}}, x) = x - -cconvert(T::Type, x) = convert(T, x) # do the conversion eagerly in most cases -cconvert(::Type{<:Ptr}, x) = x # but defer the conversion to Ptr to unsafe_convert -unsafe_convert(::Type{T}, x::T) where {T} = x # unsafe_convert (like convert) defaults to assuming the convert occurred -unsafe_convert(::Type{T}, x::T) where {T<:Ptr} = x # to resolve ambiguity with the next method -unsafe_convert(::Type{P}, x::Ptr) where {P<:Ptr} = convert(P, x) - -reinterpret(::Type{T}, x) where {T} = bitcast(T, x) -reinterpret(::Type{Unsigned}, x::Float16) = reinterpret(UInt16,x) -reinterpret(::Type{Signed}, x::Float16) = reinterpret(Int16,x) - -sizeof(x) = Core.sizeof(x) - -function append_any(xs...) - # used by apply() and quote - # must be a separate function from append(), since apply() needs this - # exact function. - out = Vector{Any}(4) - l = 4 - i = 1 - for x in xs - for y in x - if i > l - ccall(:jl_array_grow_end, Void, (Any, UInt), out, 16) - l += 16 - end - Core.arrayset(out, y, i) - i += 1 - end - end - ccall(:jl_array_del_end, Void, (Any, UInt), out, l-i+1) - out -end - -# simple Array{Any} operations needed for bootstrap -setindex!(A::Array{Any}, x::ANY, i::Int) = Core.arrayset(A, x, i) - -function precompile(f::ANY, args::Tuple) - ccall(:jl_compile_hint, Int32, (Any,), Tuple{Core.Typeof(f), args...}) != 0 -end - -function precompile(argt::Type) - ccall(:jl_compile_hint, Int32, (Any,), argt) != 0 -end - -""" - esc(e::ANY) - -Only valid in the context of an `Expr` returned from a macro. Prevents the macro hygiene -pass from turning embedded variables into gensym variables. See the [Macros](@ref man-macros) -section of the Metaprogramming chapter of the manual for more details and examples. -""" -esc(e::ANY) = Expr(:escape, e) - -macro boundscheck(blk) - # hack: use this syntax since it avoids introducing line numbers - :($(Expr(:boundscheck,true)); - $(esc(blk)); - $(Expr(:boundscheck,:pop))) -end - -""" - @inbounds(blk) - -Eliminates array bounds checking within expressions. - -In the example below the bound check of array A is skipped to improve performance. - -```julia -function sum(A::AbstractArray) - r = zero(eltype(A)) - for i = 1:length(A) - @inbounds r += A[i] - end - return r -end -``` - -!!! warning - - Using `@inbounds` may return incorrect results/crashes/corruption - for out-of-bounds indices. The user is responsible for checking it manually. -""" -macro inbounds(blk) - :($(Expr(:inbounds,true)); - $(esc(blk)); - $(Expr(:inbounds,:pop))) -end - -macro label(name::Symbol) - Expr(:symboliclabel, name) -end - -macro goto(name::Symbol) - Expr(:symbolicgoto, name) -end - -# SimpleVector - -function getindex(v::SimpleVector, i::Int) - if !(1 <= i <= length(v)) - throw(BoundsError(v,i)) - end - x = unsafe_load(convert(Ptr{Ptr{Void}},data_pointer_from_objref(v)) + i*sizeof(Ptr)) - x == C_NULL && throw(UndefRefError()) - return unsafe_pointer_to_objref(x) -end - -length(v::SimpleVector) = v.length -endof(v::SimpleVector) = v.length -start(v::SimpleVector) = 1 -next(v::SimpleVector,i) = (v[i],i+1) -done(v::SimpleVector,i) = (i > v.length) -isempty(v::SimpleVector) = (v.length == 0) -indices(v::SimpleVector) = (OneTo(length(v)),) -linearindices(v::SimpleVector) = indices(v, 1) -indices(v::SimpleVector, d) = d <= 1 ? indices(v)[d] : OneTo(1) - -function ==(v1::SimpleVector, v2::SimpleVector) - length(v1)==length(v2) || return false - for i = 1:length(v1) - v1[i] == v2[i] || return false - end - return true -end - -map(f, v::SimpleVector) = Any[ f(v[i]) for i = 1:length(v) ] - -getindex(v::SimpleVector, I::AbstractArray) = Core.svec(Any[ v[i] for i in I ]...) - -""" - isassigned(array, i) -> Bool - -Tests whether the given array has a value associated with index `i`. Returns `false` -if the index is out of bounds, or has an undefined reference. - -```jldoctest -julia> isassigned(rand(3, 3), 5) -true - -julia> isassigned(rand(3, 3), 3 * 3 + 1) -false - -julia> mutable struct Foo end - -julia> v = similar(rand(3), Foo) -3-element Array{Foo,1}: - #undef - #undef - #undef - -julia> isassigned(v, 1) -false -``` -""" -function isassigned end - -function isassigned(v::SimpleVector, i::Int) - 1 <= i <= length(v) || return false - x = unsafe_load(convert(Ptr{Ptr{Void}},data_pointer_from_objref(v)) + i*sizeof(Ptr)) - return x != C_NULL -end - -""" - Colon() - -Colons (:) are used to signify indexing entire objects or dimensions at once. - -Very few operations are defined on Colons directly; instead they are converted -by [`to_indices`](@ref) to an internal vector type (`Base.Slice`) to represent the -collection of indices they span before being used. -""" -struct Colon -end -const (:) = Colon() - -# For passing constants through type inference -struct Val{T} -end - -# used by interpolating quote and some other things in the front end -function vector_any(xs::ANY...) - n = length(xs) - a = Vector{Any}(n) - @inbounds for i = 1:n - Core.arrayset(a,xs[i],i) - end - a -end - -function as_kwargs(xs::Union{AbstractArray,Associative}) - n = length(xs) - to = Vector{Any}(n*2) - i = 1 - for (k, v) in xs - to[i] = k::Symbol - to[i+1] = v - i += 2 - end - return to -end - -function as_kwargs(xs) - to = Vector{Any}(0) - for (k, v) in xs - ccall(:jl_array_ptr_1d_push2, Void, (Any, Any, Any), to, k::Symbol, v) - end - return to -end - -isempty(itr) = done(itr, start(itr)) - -""" - invokelatest(f, args...) - -Calls `f(args...)`, but guarantees that the most recent method of `f` -will be executed. This is useful in specialized circumstances, -e.g. long-running event loops or callback functions that may -call obsolete versions of a function `f`. -(The drawback is that `invokelatest` is somewhat slower than calling -`f` directly, and the type of the result cannot be inferred by the compiler.) -""" -invokelatest(f, args...) = Core._apply_latest(f, args) diff --git a/julia-0.6.3/share/julia/base/event.jl b/julia-0.6.3/share/julia/base/event.jl deleted file mode 100644 index d6aaf36..0000000 --- a/julia-0.6.3/share/julia/base/event.jl +++ /dev/null @@ -1,443 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -## condition variables - -""" - Condition() - -Create an edge-triggered event source that tasks can wait for. Tasks that call [`wait`](@ref) on a -`Condition` are suspended and queued. Tasks are woken up when [`notify`](@ref) is later called on -the `Condition`. Edge triggering means that only tasks waiting at the time [`notify`](@ref) is -called can be woken up. For level-triggered notifications, you must keep extra state to keep -track of whether a notification has happened. The [`Channel`](@ref) type does -this, and so can be used for level-triggered events. -""" -mutable struct Condition - waitq::Vector{Any} - - Condition() = new([]) -end - -function wait(c::Condition) - ct = current_task() - - push!(c.waitq, ct) - - try - return wait() - catch - filter!(x->x!==ct, c.waitq) - rethrow() - end -end - -""" - notify(condition, val=nothing; all=true, error=false) - -Wake up tasks waiting for a condition, passing them `val`. If `all` is `true` (the default), -all waiting tasks are woken, otherwise only one is. If `error` is `true`, the passed value -is raised as an exception in the woken tasks. - -Returns the count of tasks woken up. Returns 0 if no tasks are waiting on `condition`. -""" -notify(c::Condition, arg::ANY=nothing; all=true, error=false) = notify(c, arg, all, error) -function notify(c::Condition, arg, all, error) - cnt = 0 - if all - cnt = length(c.waitq) - for t in c.waitq - error ? schedule(t, arg, error=error) : schedule(t, arg) - end - empty!(c.waitq) - elseif !isempty(c.waitq) - cnt = 1 - t = shift!(c.waitq) - error ? schedule(t, arg, error=error) : schedule(t, arg) - end - cnt -end - -notify_error(c::Condition, err) = notify(c, err, true, true) - -n_waiters(c::Condition) = length(c.waitq) - -# schedule an expression to run asynchronously, with minimal ceremony -""" - @schedule - -Wrap an expression in a [`Task`](@ref) and add it to the local machine's scheduler queue. -Similar to [`@async`](@ref) except that an enclosing `@sync` does NOT wait for tasks -started with an `@schedule`. -""" -macro schedule(expr) - thunk = esc(:(()->($expr))) - :(enq_work(Task($thunk))) -end - -## scheduler and work queue - -global const Workqueue = Task[] - -function enq_work(t::Task) - t.state == :runnable || error("schedule: Task not runnable") - ccall(:uv_stop, Void, (Ptr{Void},), eventloop()) - push!(Workqueue, t) - t.state = :queued - return t -end - -schedule(t::Task) = enq_work(t) - -""" - schedule(t::Task, [val]; error=false) - -Add a [`Task`](@ref) to the scheduler's queue. This causes the task to run constantly when the system -is otherwise idle, unless the task performs a blocking operation such as [`wait`](@ref). - -If a second argument `val` is provided, it will be passed to the task (via the return value of -[`yieldto`](@ref)) when it runs again. If `error` is `true`, the value is raised as an exception in -the woken task. - -```jldoctest -julia> a5() = det(rand(1000, 1000)); - -julia> b = Task(a5); - -julia> istaskstarted(b) -false - -julia> schedule(b); - -julia> yield(); - -julia> istaskstarted(b) -true - -julia> istaskdone(b) -true -``` -""" -function schedule(t::Task, arg; error=false) - # schedule a task to be (re)started with the given value or exception - if error - t.exception = arg - else - t.result = arg - end - return enq_work(t) -end - -# fast version of `schedule(t, arg); wait()` -function schedule_and_wait(t::Task, arg=nothing) - t.state == :runnable || error("schedule: Task not runnable") - if isempty(Workqueue) - return yieldto(t, arg) - else - t.result = arg - push!(Workqueue, t) - t.state = :queued - end - return wait() -end - -""" - yield() - -Switch to the scheduler to allow another scheduled task to run. A task that calls this -function is still runnable, and will be restarted immediately if there are no other runnable -tasks. -""" -yield() = (enq_work(current_task()); wait()) - -""" - yield(t::Task, arg = nothing) - -A fast, unfair-scheduling version of `schedule(t, arg); yield()` which -immediately yields to `t` before calling the scheduler. -""" -function yield(t::Task, x::ANY = nothing) - t.state == :runnable || error("schedule: Task not runnable") - t.result = x - enq_work(current_task()) - return try_yieldto(ensure_self_descheduled, t) -end - -""" - yieldto(t::Task, arg = nothing) - -Switch to the given task. The first time a task is switched to, the task's function is -called with no arguments. On subsequent switches, `arg` is returned from the task's last -call to `yieldto`. This is a low-level call that only switches tasks, not considering states -or scheduling in any way. Its use is discouraged. -""" -function yieldto(t::Task, x::ANY = nothing) - t.result = x - return try_yieldto(Void, t) -end - -function try_yieldto(undo::F, t::Task) where F - try - ccall(:jl_switchto, Void, (Any,), t) - catch e - undo() - rethrow(e) - end - ct = current_task() - exc = ct.exception - if exc !== nothing - ct.exception = nothing - throw(exc) - end - result = ct.result - ct.result = nothing - return result -end - -# yield to a task, throwing an exception in it -function throwto(t::Task, exc::ANY) - t.exception = exc - return yieldto(t) -end - -function ensure_self_descheduled() - # return a queued task to the runnable state - ct = current_task() - if ct.state == :queued - i = findfirst(Workqueue, ct) - i == 0 || deleteat!(Workqueue, i) - ct.state = :runnable - end - nothing -end - -function wait() - while true - if isempty(Workqueue) - c = process_events(true) - if c==0 && eventloop()!=C_NULL && isempty(Workqueue) - # if there are no active handles and no runnable tasks, just - # wait for signals. - pause() - end - else - let t = shift!(Workqueue) - if t.state != :queued - # assume this somehow got queued twice, - # probably broken now, but try discarding this switch and keep going - # can't throw here, because it's probably not the fault of the caller to wait - # and don't want to use print() here, because that may try to incur a task switch - ccall(:jl_safe_printf, Void, (Ptr{UInt8}, Vararg{Int32}), - "\nWARNING: Workqueue inconsistency detected: shift!(Workqueue).state != :queued\n") - continue - end - t.state = :runnable - result = try_yieldto(t) do - # we failed to yield to t - # return it to the head of the queue to be scheduled later - unshift!(Workqueue, t) - t.state = :queued - ensure_self_descheduled() - end - process_events(false) - # return when we come out of the queue - return result - end - end - end - # unreachable -end - -if is_windows() - pause() = ccall(:Sleep, stdcall, Void, (UInt32,), 0xffffffff) -else - pause() = ccall(:pause, Void, ()) -end - - -## async event notifications - -""" - AsyncCondition() - -Create a async condition that wakes up tasks waiting for it -(by calling [`wait`](@ref) on the object) -when notified from C by a call to `uv_async_send`. -Waiting tasks are woken with an error when the object is closed (by [`close`](@ref). -Use [`isopen`](@ref) to check whether it is still active. -""" -mutable struct AsyncCondition - handle::Ptr{Void} - cond::Condition - isopen::Bool - - function AsyncCondition() - this = new(Libc.malloc(_sizeof_uv_async), Condition(), true) - associate_julia_struct(this.handle, this) - finalizer(this, uvfinalize) - err = ccall(:uv_async_init, Cint, (Ptr{Void}, Ptr{Void}, Ptr{Void}), - eventloop(), this, uv_jl_asynccb::Ptr{Void}) - if err != 0 - #TODO: this codepath is currently not tested - Libc.free(this.handle) - this.handle = C_NULL - throw(UVError("uv_async_init", err)) - end - return this - end -end - -""" - AsyncCondition(callback::Function) - -Create a async condition that calls the given `callback` function. The `callback` is passed one argument, -the async condition object itself. -""" -function AsyncCondition(cb::Function) - async = AsyncCondition() - waiter = Task(function() - while isopen(async) - success = try - wait(async) - true - catch exc # ignore possible exception on close() - isa(exc, EOFError) || rethrow(exc) - end - success && cb(async) - end - end) - # must start the task right away so that it can wait for the AsyncCondition before - # we re-enter the event loop. this avoids a race condition. see issue #12719 - yield(waiter) - return async -end - -## timer-based notifications - -""" - Timer(delay, repeat=0) - -Create a timer that wakes up tasks waiting for it (by calling [`wait`](@ref) on the timer object) at -a specified interval. Times are in seconds. Waiting tasks are woken with an error when the -timer is closed (by [`close`](@ref). Use [`isopen`](@ref) to check whether a timer is still active. -""" -mutable struct Timer - handle::Ptr{Void} - cond::Condition - isopen::Bool - - function Timer(timeout::Real, repeat::Real=0.0) - timeout ≥ 0 || throw(ArgumentError("timer cannot have negative timeout of $timeout seconds")) - repeat ≥ 0 || throw(ArgumentError("timer cannot have negative repeat interval of $repeat seconds")) - - this = new(Libc.malloc(_sizeof_uv_timer), Condition(), true) - err = ccall(:uv_timer_init, Cint, (Ptr{Void}, Ptr{Void}), eventloop(), this) - if err != 0 - #TODO: this codepath is currently not tested - Libc.free(this.handle) - this.handle = C_NULL - throw(UVError("uv_timer_init", err)) - end - - associate_julia_struct(this.handle, this) - finalizer(this, uvfinalize) - - ccall(:uv_update_time, Void, (Ptr{Void},), eventloop()) - ccall(:uv_timer_start, Cint, (Ptr{Void}, Ptr{Void}, UInt64, UInt64), - this, uv_jl_timercb::Ptr{Void}, - UInt64(round(timeout * 1000)) + 1, UInt64(round(repeat * 1000))) - return this - end -end - -unsafe_convert(::Type{Ptr{Void}}, t::Timer) = t.handle -unsafe_convert(::Type{Ptr{Void}}, async::AsyncCondition) = async.handle - -function wait(t::Union{Timer, AsyncCondition}) - isopen(t) || throw(EOFError()) - stream_wait(t, t.cond) -end - -isopen(t::Union{Timer, AsyncCondition}) = t.isopen - -function close(t::Union{Timer, AsyncCondition}) - if t.handle != C_NULL && isopen(t) - t.isopen = false - isa(t, Timer) && ccall(:uv_timer_stop, Cint, (Ptr{Void},), t) - ccall(:jl_close_uv, Void, (Ptr{Void},), t) - end - nothing -end - -function uvfinalize(t::Union{Timer, AsyncCondition}) - if t.handle != C_NULL - disassociate_julia_struct(t.handle) # not going to call the usual close hooks - close(t) - t.handle = C_NULL - end - t.isopen = false - nothing -end - -function _uv_hook_close(t::Union{Timer, AsyncCondition}) - uvfinalize(t) - notify_error(t.cond, EOFError()) - nothing -end - -function uv_asynccb(handle::Ptr{Void}) - async = @handle_as handle AsyncCondition - notify(async.cond) - nothing -end - -function uv_timercb(handle::Ptr{Void}) - t = @handle_as handle Timer - if ccall(:uv_timer_get_repeat, UInt64, (Ptr{Void},), t) == 0 - # timer is stopped now - close(t) - end - notify(t.cond) - nothing -end - -""" - sleep(seconds) - -Block the current task for a specified number of seconds. The minimum sleep time is 1 -millisecond or input of `0.001`. -""" -function sleep(sec::Real) - sec ≥ 0 || throw(ArgumentError("cannot sleep for $sec seconds")) - wait(Timer(sec)) - nothing -end - -# timer with repeated callback -""" - Timer(callback::Function, delay, repeat=0) - -Create a timer to call the given `callback` function. The `callback` is passed one argument, -the timer object itself. The callback will be invoked after the specified initial `delay`, -and then repeating with the given `repeat` interval. If `repeat` is `0`, the timer is only -triggered once. Times are in seconds. A timer is stopped and has its resources freed by -calling [`close`](@ref) on it. -""" -function Timer(cb::Function, timeout::Real, repeat::Real=0.0) - t = Timer(timeout, repeat) - waiter = Task(function() - while isopen(t) - success = try - wait(t) - true - catch exc # ignore possible exception on close() - isa(exc, EOFError) || rethrow(exc) - false - end - success && cb(t) - end - end) - # must start the task right away so that it can wait for the Timer before - # we re-enter the event loop. this avoids a race condition. see issue #12719 - yield(waiter) - return t -end diff --git a/julia-0.6.3/share/julia/base/exports.jl b/julia-0.6.3/share/julia/base/exports.jl deleted file mode 100644 index 5a807c0..0000000 --- a/julia-0.6.3/share/julia/base/exports.jl +++ /dev/null @@ -1,1381 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -export -# Modules - FFTW, - Meta, - Operators, - Pkg, - LibGit2, - StackTraces, - Profile, - Dates, - Sys, - Test, - Libc, - Libdl, - Mmap, - LinAlg, - BLAS, - LAPACK, - Serializer, - Docs, - Markdown, - Threads, - Iterators, - Distributed, - -# Types - AbstractChannel, - AbstractMatrix, - AbstractSet, - AbstractUnitRange, - AbstractVector, - AbstractVecOrMat, - Array, - Associative, - Bidiagonal, - BigFloat, - BigInt, - BitArray, - BitMatrix, - BitVector, - BufferStream, - CartesianIndex, - CartesianRange, - Channel, - Cmd, - Colon, - Complex, - Complex128, - Complex64, - Complex32, - ConjArray, - ConjVector, - ConjMatrix, - DenseMatrix, - DenseVecOrMat, - DenseVector, - DevNull, - Diagonal, - Dict, - Dims, - EachLine, - Enum, - Enumerate, - ExponentialBackOff, - Factorization, - FileMonitor, - Hermitian, - UniformScaling, - IndexCartesian, - IndexLinear, - IndexStyle, - InsertionSort, - IntSet, - IOBuffer, - IOStream, - LinSpace, - LowerTriangular, - Irrational, - Matrix, - MergeSort, - NTuple, - Nullable, - ObjectIdDict, - OrdinalRange, - Pair, - PartialQuickSort, - PermutedDimsArray, - PollingFileWatcher, - QuickSort, - Range, - RangeIndex, - Rational, - Regex, - RegexMatch, - RevString, - RoundFromZero, - RoundDown, - RoundingMode, - RoundNearest, - RoundNearestTiesAway, - RoundNearestTiesUp, - RoundToZero, - RoundUp, - RowVector, - AbstractSerializer, - SerializationState, - Set, - SharedArray, - SharedMatrix, - SharedVector, - StepRange, - StepRangeLen, - StridedArray, - StridedMatrix, - StridedVecOrMat, - StridedVector, - SubArray, - SubString, - Symmetric, - SymTridiagonal, - Timer, - Tridiagonal, - UnitRange, - UpperTriangular, - Val, - VecOrMat, - Vector, - VersionNumber, - WeakKeyDict, - -# Ccall types - Cchar, - Cdouble, - Cfloat, - Cint, - Cintmax_t, - Clong, - Clonglong, - Cptrdiff_t, - Cshort, - Csize_t, - Cssize_t, - Cuchar, - Cuint, - Cuintmax_t, - Culong, - Culonglong, - Cushort, - Cwchar_t, - Cstring, - Cwstring, - -# Exceptions - ArgumentError, - DimensionMismatch, - CapturedException, - CompositeException, - EOFError, - ErrorException, - InvalidStateException, - KeyError, - LoadError, - InitError, - MethodError, - NullException, - ParseError, - SystemError, - TypeError, - AssertionError, - UnicodeError, - -# Global constants and variables - ARGS, - C_NULL, - ENDIAN_BOM, - ENV, - JULIA_HOME, - LOAD_PATH, - PROGRAM_FILE, - STDERR, - STDIN, - STDOUT, - VERSION, - -# Mathematical constants - Inf, - Inf16, - Inf32, - Inf64, - NaN, - NaN16, - NaN32, - NaN64, - im, - π, pi, - e, eu, - γ, eulergamma, - catalan, - φ, golden, - I, - -# Operators - !, - !=, - ≠, - !==, - ≡, - ≢, - xor, - ⊻, - %, - ÷, - &, - *, - +, - -, - /, - //, - <, - <:, - <<, - <=, - ≤, - ==, - >, - >:, - >=, - ≥, - >>, - >>>, - \, - ^, - |, - |>, - ~, - :, - =>, - ∘, - A_ldiv_B!, - A_ldiv_Bc, - A_ldiv_Bt, - A_mul_B!, - A_mul_Bc, - A_mul_Bc!, - A_mul_Bt, - A_mul_Bt!, - A_rdiv_Bc, - A_rdiv_Bt, - Ac_ldiv_B, - Ac_ldiv_B!, - Ac_ldiv_Bc, - Ac_mul_B, - Ac_mul_B!, - Ac_mul_Bc, - Ac_mul_Bc!, - Ac_rdiv_B, - Ac_rdiv_Bc, - At_ldiv_B, - At_ldiv_B!, - At_ldiv_Bt, - At_mul_B, - At_mul_B!, - At_mul_Bt, - At_mul_Bt!, - At_rdiv_B, - At_rdiv_Bt, - -# scalar math - @evalpoly, - abs, - abs2, - acos, - acosd, - acosh, - acot, - acotd, - acoth, - acsc, - acscd, - acsch, - angle, - asec, - asecd, - asech, - asin, - asind, - asinh, - atan, - atan2, - atand, - atanh, - big, - binomial, - bswap, - cbrt, - ceil, - cis, - clamp, - cld, - cmp, - complex, - conj, - copysign, - cos, - cosc, - cosd, - cosh, - cospi, - cot, - cotd, - coth, - count_ones, - count_zeros, - csc, - cscd, - csch, - deg2rad, - denominator, - div, - divrem, - eps, - exp, - exp10, - exp2, - expm1, - exponent, - factorial, - fld, - fld1, - fldmod, - fldmod1, - flipsign, - float, - tryparse, - floor, - fma, - frexp, - gamma, - gcd, - gcdx, - hex2num, - hypot, - imag, - inv, - invmod, - isapprox, - iseven, - isfinite, - isinf, - isinteger, - isnan, - isodd, - ispow2, - isqrt, - isreal, - issubnormal, - iszero, - lcm, - ldexp, - leading_ones, - leading_zeros, - lfact, - lgamma, - log, - log10, - log1p, - log2, - maxintfloat, - mod, - mod1, - modf, - mod2pi, - muladd, - nextfloat, - nextpow, - nextpow2, - nextprod, - numerator, - num2hex, - one, - oneunit, - powermod, - prevfloat, - prevpow, - prevpow2, - rad2deg, - rationalize, - real, - realmax, - realmin, - reim, - reinterpret, - rem, - rem2pi, - round, - sec, - secd, - sech, - sign, - signbit, - signed, - signif, - significand, - sin, - sinc, - sind, - sinh, - sinpi, - sqrt, - tan, - tand, - tanh, - trailing_ones, - trailing_zeros, - trunc, - unsafe_trunc, - typemax, - typemin, - unsigned, - widemul, - zero, - √, - ∛, - ≈, - ≉, - -# specfun - beta, - lbeta, - -# arrays - broadcast!, - broadcast, - broadcast_getindex, - broadcast_setindex!, - cat, - checkbounds, - checkindex, - circcopy!, - circshift, - circshift!, - clamp!, - colon, - conj!, - copy!, - cumprod, - cumprod!, - cumsum, - cumsum!, - accumulate, - accumulate!, - cumsum_kbn, - eachindex, - extrema, - fill!, - fill, - find, - findfirst, - findlast, - findin, - findmax, - findmin, - findmin!, - findmax!, - findn, - findnext, - findprev, - findnz, - first, - flipdim, - gradient, - hcat, - hvcat, - ind2sub, - indexin, - indices, - indmax, - indmin, - invperm, - ipermute!, - isassigned, - isperm, - issorted, - last, - linearindices, - linspace, - logspace, - mapslices, - max, - maximum!, - maximum, - min, - minimum!, - minimum, - minmax, - ndims, - nonzeros, - countnz, - ones, - parent, - parentindexes, - permute, - permute!, - permutedims, - permutedims!, - prod!, - prod, - promote_shape, - randcycle, - randperm, - randsubseq!, - randsubseq, - range, - reducedim, - repmat, - reshape, - reverse!, - reverse, - rot180, - rotl90, - rotr90, - searchsorted, - searchsortedfirst, - searchsortedlast, - select!, - select, - shuffle, - shuffle!, - size, - slicedim, - sort!, - sort, - sortcols, - selectperm, - selectperm!, - sortperm, - sortperm!, - sortrows, - squeeze, - step, - stride, - strides, - sub2ind, - sum!, - sum, - sum_kbn, - to_indices, - vcat, - vec, - view, - zeros, - -# linear algebra - bkfact!, - bkfact, - blkdiag, - chol, - cholfact!, - cholfact, - cond, - condskeel, - cross, - ctranspose!, - ctranspose, - det, - diag, - diagind, - diagm, - diff, - dot, - eig, - eigfact!, - eigfact, - eigmax, - eigmin, - eigs, - eigvals, - eigvals!, - eigvecs, - expm, - eye, - factorize, - givens, - hessfact!, - hessfact, - isdiag, - ishermitian, - isposdef!, - isposdef, - issymmetric, - istril, - istriu, - kron, - ldltfact, - ldltfact!, - linreg, - logabsdet, - logdet, - logm, - lu, - lufact!, - lufact, - lyap, - norm, - normalize, - normalize!, - nullspace, - ordschur!, - ordschur, - peakflops, - pinv, - qr, - qrfact!, - qrfact, - lq, - lqfact!, - lqfact, - rank, - scale!, - schur, - schurfact!, - schurfact, - sqrtm, - svd, - svdfact!, - svdfact, - svds, - svdvals!, - svdvals, - sylvester, - trace, - transpose!, - transpose, - tril!, - tril, - triu!, - triu, - vecdot, - vecnorm, - ⋅, - ×, - -# sparse - full, - dropzeros, - dropzeros!, - -# bitarrays - falses, - flipbits!, - rol, - rol!, - ror, - ror!, - trues, - -# dequeues - append!, - insert!, - pop!, - prepend!, - push!, - resize!, - shift!, - unshift!, - -# collections - all!, - all, - allunique, - any!, - any, - collect, - contains, - count, - delete!, - deleteat!, - eltype, - empty!, - endof, - filter!, - filter, - foldl, - foldr, - foreach, - get, - get!, - getindex, - getkey, - haskey, - in, - intersect!, - intersect, - isempty, - issubset, - keys, - keytype, - length, - map!, - map, - mapfoldl, - mapfoldr, - mapreduce, - mapreducedim, - merge!, - merge, - #pop!, - #push!, - reduce, - setdiff!, - setdiff, - setindex!, - similar, - sizehint!, - splice!, - symdiff!, - symdiff, - union!, - union, - unique, - values, - valtype, - ∈, - ∉, - ∋, - ∌, - ⊆, - ⊈, - ⊊, - ∩, - ∪, - -# strings and text output - ascii, - base, - base64encode, - base64decode, - Base64EncodePipe, - Base64DecodePipe, - startswith, - bin, - bits, - bytes2hex, - charwidth, - chomp, - chop, - chr2ind, - codeunit, - dec, - digits, - digits!, - dump, - eachmatch, - endswith, - escape_string, - graphemes, - hex, - hex2bytes, - ind2chr, - info, - is_assigned_char, - isalnum, - isalpha, - isascii, - iscntrl, - isdigit, - isgraph, - islower, - ismatch, - isnumber, - isprint, - ispunct, - isspace, - isupper, - isvalid, - isxdigit, - join, - lcfirst, - logging, - lowercase, - lpad, - lstrip, - match, - matchall, - ndigits, - nextind, - normalize_string, - oct, - prevind, - print, - print_shortest, - print_with_color, - println, - randstring, - repeat, - replace, - repr, - reverseind, - rpad, - rsearch, - rsearchindex, - rsplit, - rstrip, - search, - searchindex, - show, - showall, - showcompact, - showerror, - split, - sprint, - string, - strip, - strwidth, - summary, - titlecase, - transcode, - ucfirst, - unescape_string, - uppercase, - warn, - -# random numbers - AbstractRNG, - MersenneTwister, - RandomDevice, - rand!, - rand, - randn!, - randn, - randexp!, - randexp, - srand, - bitrand, - randjump, - -# bigfloat & precision - precision, - rounding, - setprecision, - setrounding, - get_zero_subnormals, - set_zero_subnormals, - -# statistics - cor, - cov, - mean!, - mean, - median!, - median, - middle, - quantile!, - quantile, - std, - stdm, - var, - varm, - -# signal processing - bfft!, - bfft, - brfft, - conv, - conv2, - dct!, - dct, - deconv, - fft!, - fft, - fftshift, - filt, - filt!, - idct!, - idct, - ifft!, - ifft, - ifftshift, - irfft, - plan_bfft!, - plan_bfft, - plan_brfft, - plan_dct!, - plan_dct, - plan_fft!, - plan_fft, - plan_idct!, - plan_idct, - plan_ifft!, - plan_ifft, - plan_irfft, - plan_rfft, - rfft, - xcorr, - -# iteration - done, - next, - start, - - enumerate, # re-exported from Iterators - zip, - -# object identity and equality - copy, - deepcopy, - hash, - identity, - isbits, - isequal, - isimmutable, - isless, - ifelse, - lexless, - lexcmp, - object_id, - sizeof, - -# tasks and conditions - Condition, - current_task, - islocked, - istaskdone, - istaskstarted, - lock, - notify, - ReentrantLock, - schedule, - task_local_storage, - trylock, - unlock, - yield, - yieldto, - wait, - timedwait, - asyncmap, - asyncmap!, - -# channels - take!, - put!, - isready, - fetch, - -# time - sleep, - tic, - time, - time_ns, - toc, - toq, - -# dates - Date, - DateTime, - DateFormat, - @dateformat_str, - now, - -# errors - assert, - backtrace, - catch_backtrace, - error, - rethrow, - retry, - systemerror, - -# stack traces - StackTrace, - StackFrame, - stacktrace, - catch_stacktrace, - -# types - convert, - fieldoffset, - fieldname, - fieldnames, - isleaftype, - oftype, - promote, - promote_rule, - promote_type, - subtypes, - instances, - supertype, - typeintersect, - typejoin, - widen, - -# syntax - esc, - expand, - gensym, - macroexpand, - @macroexpand, - parse, - -# help and reflection - apropos, - current_module, - edit, - code_typed, - code_warntype, - code_lowered, - code_llvm, - code_native, - fullname, - functionloc, - isconst, - isinteractive, - less, - method_exists, - methods, - methodswith, - module_name, - module_parent, - names, - versioninfo, - which, - whos, - workspace, - -# loading source files - __precompile__, - evalfile, - include, - include_string, - include_dependency, - reload, - -# RTS internals - finalizer, - finalize, - gc, - gc_enable, - precompile, - -# misc - atexit, - atreplinit, - clipboard, - exit, - ntuple, - quit, - -# IP address stuff - @ip_str, - IPAddr, - IPv4, - IPv6, - -# I/O and events - accept, - bind, - close, - connect, - countlines, - deserialize, - eachline, - eof, - fd, - fdio, - flush, - getaddrinfo, - gethostname, - getipaddr, - getsockname, - htol, - hton, - IOContext, - displaysize, - ismarked, - isopen, - isreadonly, - listen, - listenany, - ltoh, - mark, - nb_available, - ntoh, - open, - pipeline, - Pipe, - PipeBuffer, - poll_fd, - poll_file, - position, - RawFD, - read, - read!, - readavailable, - readbytes!, - readchomp, - readcsv, - readdir, - readdlm, - readline, - readlines, - readstring, - readuntil, - redirect_stderr, - redirect_stdin, - redirect_stdout, - recv, - recvfrom, - reset, - seek, - seekend, - seekstart, - send, - serialize, - skip, - skipchars, - take!, - truncate, - unmark, - watch_file, - write, - writecsv, - writedlm, - TCPSocket, - UDPSocket, - -# multimedia I/O - Display, - display, - displayable, - TextDisplay, - istextmime, - MIME, - @MIME_str, - reprmime, - stringmime, - mimewritable, - popdisplay, - pushdisplay, - redisplay, - HTML, - Text, - -# shared arrays - sdata, - indexpids, - localindexes, - -# paths and file names - abspath, - basename, - dirname, - expanduser, - homedir, - isabspath, - isdirpath, - joinpath, - normpath, - realpath, - relpath, - splitdir, - splitdrive, - splitext, - -# filesystem operations - cd, - chmod, - chown, - cp, - ctime, - download, - filemode, - filesize, - gperm, - isblockdev, - ischardev, - isdir, - isfifo, - isfile, - islink, - ismount, - ispath, - isreadable, - issetgid, - issetuid, - issocket, - issticky, - iswritable, - lstat, - mkdir, - mkpath, - mktemp, - mktempdir, - mtime, - mv, - operm, - pwd, - readlink, - rm, - stat, - symlink, - tempdir, - tempname, - touch, - uperm, - walkdir, - -# external processes ## TODO: whittle down these exports. - detach, - getpid, - ignorestatus, - kill, - process_exited, - process_running, - readandwrite, - run, - setenv, - spawn, - success, - withenv, - -# C interface - cfunction, - cglobal, - disable_sigint, - pointer, - pointer_from_objref, - unsafe_wrap, - unsafe_string, - reenable_sigint, - unsafe_copy!, - unsafe_load, - unsafe_pointer_to_objref, - unsafe_read, - unsafe_store!, - unsafe_write, - -# nullable types - isnull, - unsafe_get, - -# Macros - # parser internal - @__FILE__, - @__DIR__, - @int128_str, - @uint128_str, - @big_str, - @cmd, # `commands` - - # notation for certain types - @b_str, # byte vector - @r_str, # regex - @s_str, # regex substitution string - @v_str, # version number - @raw_str, # raw string with no interpolation/unescaping - - # documentation - @text_str, - @html_str, - @doc, - @doc_str, - - # output - @show, - @printf, - @sprintf, - - # profiling - @time, - @timed, - @timev, - @elapsed, - @allocated, - @profile, - - # reflection - @which, - @edit, - @functionloc, - @less, - @code_typed, - @code_warntype, - @code_lowered, - @code_llvm, - @code_native, - - # platform-conditional code - @static, - is_windows, - is_linux, - is_apple, - is_bsd, - is_unix, - - # tasks - @schedule, - @sync, - @async, - @task, - @threadcall, - - # metaprogramming utilities - @generated, - @gensym, - @eval, - @deprecate, - - # performance annotations - @boundscheck, - @inbounds, - @fastmath, - @simd, - @inline, - @noinline, - @polly, - - @assert, - @__dot__, - @enum, - @label, - @goto, - @view, - @views, - -# SparseArrays module re-exports - SparseArrays, - AbstractSparseArray, - AbstractSparseMatrix, - AbstractSparseVector, - SparseMatrixCSC, - SparseVector, - issparse, - sparse, - sparsevec, - spdiagm, - speye, - spones, - sprand, - sprandn, - spzeros, - rowvals, - nzrange, - nnz, - -# Distributed module re-exports - @spawn, - @spawnat, - @fetch, - @fetchfrom, - @everywhere, - @parallel, - - addprocs, - CachingPool, - clear!, - ClusterManager, - default_worker_pool, - init_worker, - interrupt, - launch, - manage, - myid, - nprocs, - nworkers, - pmap, - procs, - remote, - remotecall, - remotecall_fetch, - remotecall_wait, - remote_do, - rmprocs, - workers, - WorkerPool, - RemoteChannel, - Future, - WorkerConfig, - RemoteException, - ProcessExitedException diff --git a/julia-0.6.3/share/julia/base/expr.jl b/julia-0.6.3/share/julia/base/expr.jl deleted file mode 100644 index fa1f658..0000000 --- a/julia-0.6.3/share/julia/base/expr.jl +++ /dev/null @@ -1,284 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -## symbols ## - -""" - gensym([tag]) - -Generates a symbol which will not conflict with other variable names. -""" -gensym() = ccall(:jl_gensym, Ref{Symbol}, ()) - -gensym(s::String) = ccall(:jl_tagged_gensym, Ref{Symbol}, (Ptr{UInt8}, Int32), s, sizeof(s)) - -gensym(ss::String...) = map(gensym, ss) -gensym(s::Symbol) = - ccall(:jl_tagged_gensym, Ref{Symbol}, (Ptr{UInt8}, Int32), s, ccall(:strlen, Csize_t, (Ptr{UInt8},), s)) - -""" - @gensym - -Generates a gensym symbol for a variable. For example, `@gensym x y` is transformed into -`x = gensym("x"); y = gensym("y")`. -""" -macro gensym(names...) - blk = Expr(:block) - for name in names - push!(blk.args, :($(esc(name)) = gensym($(string(name))))) - end - push!(blk.args, :nothing) - return blk -end - -## expressions ## - -copy(e::Expr) = (n = Expr(e.head); - n.args = copy_exprargs(e.args); - n.typ = e.typ; - n) - -# copy parts of an AST that the compiler mutates -copy_exprs(x::Expr) = copy(x) -copy_exprs(x::ANY) = x -copy_exprargs(x::Array{Any,1}) = Any[copy_exprs(a) for a in x] - -==(x::Expr, y::Expr) = x.head === y.head && isequal(x.args, y.args) -==(x::QuoteNode, y::QuoteNode) = isequal(x.value, y.value) - -""" - expand(x) - -Takes the expression `x` and returns an equivalent expression in lowered form. -See also [`code_lowered`](@ref). -""" -expand(x::ANY) = ccall(:jl_expand, Any, (Any,), x) - -""" - macroexpand(x) - -Takes the expression `x` and returns an equivalent expression with all macros removed (expanded). -""" -macroexpand(x::ANY) = ccall(:jl_macroexpand, Any, (Any,), x) - -""" - @macroexpand - -Return equivalent expression with all macros removed (expanded). - -There is a subtle difference between `@macroexpand` and `macroexpand` in that expansion takes place in -different contexts. This is best seen in the following example: - -```jldoctest -julia> module M - macro m() - 1 - end - function f() - (@macroexpand(@m), macroexpand(:(@m))) - end - end -M - -julia> macro m() - 2 - end -@m (macro with 1 method) - -julia> M.f() -(1, 2) -``` -With `@macroexpand` the expression expands where `@macroexpand` appears in the code (module -`M` in the example). With `macroexpand` the expression expands in the current module where -the code was finally called (REPL in the example). -Note that when calling `macroexpand` or `@macroexpand` directly from the REPL, both of these contexts coincide, hence there is no difference. -""" -macro macroexpand(code) - code_expanded = macroexpand(code) - QuoteNode(code_expanded) -end - -## misc syntax ## - -""" - eval([m::Module], expr::Expr) - -Evaluate an expression in the given module and return the result. Every `Module` (except -those defined with `baremodule`) has its own 1-argument definition of `eval`, which -evaluates expressions in that module. -""" -Core.eval - -""" - @inline - -Give a hint to the compiler that this function is worth inlining. - -Small functions typically do not need the `@inline` annotation, -as the compiler does it automatically. By using `@inline` on bigger functions, -an extra nudge can be given to the compiler to inline it. -This is shown in the following example: - -```julia -@inline function bigfunction(x) - #= - Function Definition - =# -end -``` -""" -macro inline(ex) - esc(isa(ex, Expr) ? pushmeta!(ex, :inline) : ex) -end - -""" - @noinline - -Prevents the compiler from inlining a function. - -Small functions are typically inlined automatically. -By using `@noinline` on small functions, auto-inlining can be -prevented. This is shown in the following example: - -```julia -@noinline function smallfunction(x) - #= - Function Definition - =# -end -``` -""" -macro noinline(ex) - esc(isa(ex, Expr) ? pushmeta!(ex, :noinline) : ex) -end - -macro pure(ex) - esc(isa(ex, Expr) ? pushmeta!(ex, :pure) : ex) -end - -""" - @propagate_inbounds - -Tells the compiler to inline a function while retaining the caller's inbounds context. -""" -macro propagate_inbounds(ex) - if isa(ex, Expr) - pushmeta!(ex, :inline) - pushmeta!(ex, :propagate_inbounds) - esc(ex) - else - esc(ex) - end -end - -""" - @polly - -Tells the compiler to apply the polyhedral optimizer Polly to a function. -""" -macro polly(ex) - esc(isa(ex, Expr) ? pushmeta!(ex, :polly) : ex) -end - -## some macro utilities ## - -function pushmeta!(ex::Expr, sym::Symbol, args::Any...) - if isempty(args) - tag = sym - else - tag = Expr(sym, args...) - end - - inner = ex - while inner.head == :macrocall - inner = inner.args[end]::Expr - end - - idx, exargs = findmeta(inner) - if idx != 0 - push!(exargs[idx].args, tag) - else - body::Expr = inner.args[2] - unshift!(body.args, Expr(:meta, tag)) - end - ex -end - -function popmeta!(body::Expr, sym::Symbol) - body.head == :block || return false, [] - popmeta!(body.args, sym) -end -popmeta!(arg, sym) = (false, []) -function popmeta!(body::Array{Any,1}, sym::Symbol) - idx, blockargs = findmeta_block(body, args -> findmetaarg(args,sym)!=0) - if idx == 0 - return false, [] - end - metaargs = blockargs[idx].args - i = findmetaarg(blockargs[idx].args, sym) - if i == 0 - return false, [] - end - ret = isa(metaargs[i], Expr) ? (metaargs[i]::Expr).args : [] - deleteat!(metaargs, i) - isempty(metaargs) && deleteat!(blockargs, idx) - true, ret -end - -# Find index of `sym` in a meta expression argument list, or 0. -function findmetaarg(metaargs, sym) - for i = 1:length(metaargs) - arg = metaargs[i] - if (isa(arg, Symbol) && (arg::Symbol) == sym) || - (isa(arg, Expr) && (arg::Expr).head == sym) - return i - end - end - return 0 -end - -function is_short_function_def(ex) - ex.head == :(=) || return false - while length(ex.args) >= 1 && isa(ex.args[1], Expr) - (ex.args[1].head == :call) && return true - (ex.args[1].head == :where || ex.args[1].head == :(::)) || return false - ex = ex.args[1] - end - return false -end - -function findmeta(ex::Expr) - if ex.head == :function || is_short_function_def(ex) - body::Expr = ex.args[2] - body.head == :block || error(body, " is not a block expression") - return findmeta_block(ex.args) - end - error(ex, " is not a function expression") -end - -findmeta(ex::Array{Any,1}) = findmeta_block(ex) - -function findmeta_block(exargs, argsmatch=args->true) - for i = 1:length(exargs) - a = exargs[i] - if isa(a, Expr) - if (a::Expr).head == :meta && argsmatch((a::Expr).args) - return i, exargs - elseif (a::Expr).head == :block - idx, exa = findmeta_block(a.args, argsmatch) - if idx != 0 - return idx, exa - end - end - end - end - return 0, [] -end - -remove_linenums!(ex) = ex -function remove_linenums!(ex::Expr) - filter!(x->!((isa(x,Expr) && x.head === :line) || isa(x,LineNumberNode)), ex.args) - for subex in ex.args - remove_linenums!(subex) - end - ex -end diff --git a/julia-0.6.3/share/julia/base/fastmath.jl b/julia-0.6.3/share/julia/base/fastmath.jl deleted file mode 100644 index bc0d9b4..0000000 --- a/julia-0.6.3/share/julia/base/fastmath.jl +++ /dev/null @@ -1,348 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -# Support for @fastmath - -# This module provides versions of math functions that may violate -# strict IEEE semantics. - -# This allows the following transformations: -# nnan: No NaNs - Allow optimizations to assume the arguments and -# result are not NaN. Such optimizations are required to retain -# defined behavior over NaNs, but the value of the result is -# undefined. -# ninf: No Infs - Allow optimizations to assume the arguments and -# result are not +/-Inf. Such optimizations are required to -# retain defined behavior over +/-Inf, but the value of the -# result is undefined. -# nsz: No Signed Zeros - Allow optimizations to treat the sign of a -# zero argument or result as insignificant. -# arcp: Allow Reciprocal - Allow optimizations to use the reciprocal -# of an argument rather than perform division. - -module FastMath - -export @fastmath - -import Core.Intrinsics: sqrt_llvm_fast, neg_float_fast, - add_float_fast, sub_float_fast, mul_float_fast, div_float_fast, rem_float_fast, - eq_float_fast, ne_float_fast, lt_float_fast, le_float_fast - -const fast_op = - Dict(# basic arithmetic - :+ => :add_fast, - :- => :sub_fast, - :* => :mul_fast, - :/ => :div_fast, - :(==) => :eq_fast, - :!= => :ne_fast, - :< => :lt_fast, - :<= => :le_fast, - :abs => :abs_fast, - :abs2 => :abs2_fast, - :cmp => :cmp_fast, - :conj => :conj_fast, - :inv => :inv_fast, - :rem => :rem_fast, - :sign => :sign_fast, - :isfinite => :isfinite_fast, - :isinf => :isinf_fast, - :isnan => :isnan_fast, - :issubnormal => :issubnormal_fast, - # math functions - :^ => :pow_fast, - :acos => :acos_fast, - :acosh => :acosh_fast, - :angle => :angle_fast, - :asin => :asin_fast, - :asinh => :asinh_fast, - :atan => :atan_fast, - :atan2 => :atan2_fast, - :atanh => :atanh_fast, - :cbrt => :cbrt_fast, - :cis => :cis_fast, - :cos => :cos_fast, - :cosh => :cosh_fast, - :exp10 => :exp10_fast, - :exp2 => :exp2_fast, - :exp => :exp_fast, - :expm1 => :expm1_fast, - :hypot => :hypot_fast, - :lgamma => :lgamma_fast, - :log10 => :log10_fast, - :log1p => :log1p_fast, - :log2 => :log2_fast, - :log => :log_fast, - :max => :max_fast, - :min => :min_fast, - :minmax => :minmax_fast, - :sin => :sin_fast, - :sinh => :sinh_fast, - :sqrt => :sqrt_fast, - :tan => :tan_fast, - :tanh => :tanh_fast) - -const rewrite_op = - Dict(:+= => :+, - :-= => :-, - :*= => :*, - :/= => :/, - :^= => :^) - -function make_fastmath(expr::Expr) - if expr.head === :quote - return expr - end - op = get(rewrite_op, expr.head, :nothing) - if op !== :nothing - var = expr.args[1] - rhs = expr.args[2] - if isa(var, Symbol) - # simple assignment - expr = :($var = $op($var, $rhs)) - elseif isa(var, Expr) && var.head === :ref - # array reference - arr = var.args[1] - inds = tuple(var.args[2:end]...) - arrvar = gensym() - indvars = tuple([gensym() for i in inds]...) - expr = quote - $(Expr(:(=), arrvar, arr)) - $(Expr(:(=), Expr(:tuple, indvars...), Expr(:tuple, inds...))) - $arrvar[$(indvars...)] = $op($arrvar[$(indvars...)], $rhs) - end - end - end - Expr(make_fastmath(expr.head), map(make_fastmath, expr.args)...) -end -function make_fastmath(symb::Symbol) - fast_symb = get(fast_op, symb, :nothing) - if fast_symb === :nothing - return symb - end - :(Base.FastMath.$fast_symb) -end -make_fastmath(expr) = expr - -macro fastmath(expr) - make_fastmath(esc(expr)) -end - - -# Basic arithmetic - -FloatTypes = Union{Float32, Float64} - -sub_fast(x::FloatTypes) = neg_float_fast(x) - -add_fast(x::T, y::T) where {T<:FloatTypes} = add_float_fast(x, y) -sub_fast(x::T, y::T) where {T<:FloatTypes} = sub_float_fast(x, y) -mul_fast(x::T, y::T) where {T<:FloatTypes} = mul_float_fast(x, y) -div_fast(x::T, y::T) where {T<:FloatTypes} = div_float_fast(x, y) -rem_fast(x::T, y::T) where {T<:FloatTypes} = rem_float_fast(x, y) - -add_fast{T<:FloatTypes}(x::T, y::T, zs::T...) = - add_fast(add_fast(x, y), zs...) -mul_fast{T<:FloatTypes}(x::T, y::T, zs::T...) = - mul_fast(mul_fast(x, y), zs...) - -@fastmath begin - cmp_fast(x::T, y::T) where {T<:FloatTypes} = ifelse(x==y, 0, ifelse(x x, y, x) - min_fast(x::T, y::T) where {T<:FloatTypes} = ifelse(y > x, x, y) - minmax_fast(x::T, y::T) where {T<:FloatTypes} = ifelse(y > x, (x,y), (y,x)) - - # complex numbers - - cis_fast(x::T) where {T<:FloatTypes} = Complex{T}(cos(x), sin(x)) - - # See - pow_fast(x::T, y::T) where {T<:ComplexTypes} = exp(y*log(x)) - pow_fast(x::T, y::Complex{T}) where {T<:FloatTypes} = exp(y*log(x)) - pow_fast(x::Complex{T}, y::T) where {T<:FloatTypes} = exp(y*log(x)) - acos_fast(x::T) where {T<:ComplexTypes} = - convert(T,π)/2 + im*log(im*x + sqrt(1-x*x)) - acosh_fast(x::ComplexTypes) = log(x + sqrt(x+1) * sqrt(x-1)) - angle_fast(x::ComplexTypes) = atan2(imag(x), real(x)) - asin_fast(x::ComplexTypes) = -im*asinh(im*x) - asinh_fast(x::ComplexTypes) = log(x + sqrt(1+x*x)) - atan_fast(x::ComplexTypes) = -im*atanh(im*x) - atanh_fast(x::T) where {T<:ComplexTypes} = convert(T,1)/2*(log(1+x) - log(1-x)) - cis_fast(x::ComplexTypes) = exp(-imag(x)) * cis(real(x)) - cos_fast(x::ComplexTypes) = cosh(im*x) - cosh_fast(x::T) where {T<:ComplexTypes} = convert(T,1)/2*(exp(x) + exp(-x)) - exp10_fast(x::T) where {T<:ComplexTypes} = - exp10(real(x)) * cis(imag(x)*log(convert(T,10))) - exp2_fast(x::T) where {T<:ComplexTypes} = - exp2(real(x)) * cis(imag(x)*log(convert(T,2))) - exp_fast(x::ComplexTypes) = exp(real(x)) * cis(imag(x)) - expm1_fast(x::ComplexTypes) = exp(x)-1 - log10_fast(x::T) where {T<:ComplexTypes} = log(x) / log(convert(T,10)) - log1p_fast(x::ComplexTypes) = log(1+x) - log2_fast(x::T) where {T<:ComplexTypes} = log(x) / log(convert(T,2)) - log_fast(x::T) where {T<:ComplexTypes} = T(log(abs2(x))/2, angle(x)) - sin_fast(x::ComplexTypes) = -im*sinh(im*x) - sinh_fast(x::T) where {T<:ComplexTypes} = convert(T,1)/2*(exp(x) - exp(-x)) - sqrt_fast(x::ComplexTypes) = sqrt(abs(x)) * cis(angle(x)/2) - tan_fast(x::ComplexTypes) = -im*tanh(im*x) - tanh_fast(x::ComplexTypes) = (a=exp(x); b=exp(-x); (a-b)/(a+b)) -end - -# fall-back implementations and type promotion - -for f in (:acos, :acosh, :angle, :asin, :asinh, :atan, :atanh, :cbrt, - :cis, :cos, :cosh, :exp10, :exp2, :exp, :expm1, :lgamma, - :log10, :log1p, :log2, :log, :sin, :sinh, :sqrt, :tan, - :tanh) - f_fast = fast_op[f] - @eval begin - $f_fast(x) = $f(x) - end -end - -for f in (:^, :atan2, :hypot, :max, :min, :minmax) - f_fast = fast_op[f] - @eval begin - # fall-back implementation for non-numeric types - $f_fast(x, y) = $f(x, y) - # type promotion - $f_fast(x::Number, y::Number) = $f_fast(promote(x, y)...) - # fall-back implementation that applies after promotion - $f_fast(x::T, y::T) where {T<:Number} = $f(x, y) - end -end - -end diff --git a/julia-0.6.3/share/julia/base/fft/FFTW.jl b/julia-0.6.3/share/julia/base/fft/FFTW.jl deleted file mode 100644 index 4ef2f70..0000000 --- a/julia-0.6.3/share/julia/base/fft/FFTW.jl +++ /dev/null @@ -1,802 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -import Base: show, *, convert, unsafe_convert, size, strides, ndims, pointer, A_mul_B! - -export export_wisdom, import_wisdom, import_system_wisdom, forget_wisdom, - MEASURE, DESTROY_INPUT, UNALIGNED, CONSERVE_MEMORY, EXHAUSTIVE, - PRESERVE_INPUT, PATIENT, ESTIMATE, WISDOM_ONLY, NO_TIMELIMIT, - R2HC, HC2R, DHT, REDFT00, REDFT01, REDFT10, REDFT11, - RODFT00, RODFT01, RODFT10, RODFT11, - fftwNumber, fftwReal, fftwComplex, flops - -## FFT: Implement fft by calling fftw. - -const libfftw = Base.libfftw_name -const libfftwf = Base.libfftwf_name - -const version = convert(VersionNumber, split(unsafe_string(cglobal( - (:fftw_version,Base.DFT.FFTW.libfftw), UInt8)), ['-', ' '])[2]) - -## Direction of FFT - -const FORWARD = -1 -const BACKWARD = 1 - -## FFTW Flags from fftw3.h - -const MEASURE = UInt32(0) -const DESTROY_INPUT = UInt32(1 << 0) -const UNALIGNED = UInt32(1 << 1) -const CONSERVE_MEMORY = UInt32(1 << 2) -const EXHAUSTIVE = UInt32(1 << 3) # NO_EXHAUSTIVE is default -const PRESERVE_INPUT = UInt32(1 << 4) # cancels DESTROY_INPUT -const PATIENT = UInt32(1 << 5) # IMPATIENT is default -const ESTIMATE = UInt32(1 << 6) -const WISDOM_ONLY = UInt32(1 << 21) -const NO_SIMD = UInt32(1 << 17) # disable SIMD, useful for benchmarking - -## R2R transform kinds - -const R2HC = 0 -const HC2R = 1 -const DHT = 2 -const REDFT00 = 3 -const REDFT01 = 4 -const REDFT10 = 5 -const REDFT11 = 6 -const RODFT00 = 7 -const RODFT01 = 8 -const RODFT10 = 9 -const RODFT11 = 10 - -let k2s = Dict(R2HC => "R2HC", HC2R => "HC2R", DHT => "DHT", REDFT00 => "REDFT00", REDFT01 => "REDFT01", REDFT10 => "REDFT10", REDFT11 => "REDFT11", RODFT00 => "RODFT00", RODFT01 => "RODFT01", RODFT10 => "RODFT10", RODFT11 => "RODFT11") - global kind2string - kind2string(k::Integer) = k2s[Int(k)] -end - -# FFTW floating-point types: - -const fftwNumber = Union{Float64,Float32,Complex128,Complex64} -const fftwReal = Union{Float64,Float32} -const fftwComplex = Union{Complex128,Complex64} -const fftwDouble = Union{Float64,Complex128} -const fftwSingle = Union{Float32,Complex64} -const fftwTypeDouble = Union{Type{Float64},Type{Complex128}} -const fftwTypeSingle = Union{Type{Float32},Type{Complex64}} - -# For ESTIMATE plans, FFTW allows one to pass NULL for the array pointer, -# since it is not written to. Hence, it is convenient to create an -# array-like type that carries a size and a stride like a "real" array -# but which is converted to C_NULL as a pointer. -struct FakeArray{T,N} <: DenseArray{T,N} - sz::NTuple{N,Int} - st::NTuple{N,Int} -end -size(a::FakeArray) = a.sz -strides(a::FakeArray) = a.st -unsafe_convert(::Type{Ptr{T}}, a::FakeArray{T}) where {T} = convert(Ptr{T}, C_NULL) -pointer(a::FakeArray{T}) where {T} = convert(Ptr{T}, C_NULL) -FakeArray{T,N}(::Type{T}, sz::NTuple{N,Int}) = FakeArray{T,N}(sz, colmajorstrides(sz)) -FakeArray{T}(::Type{T}, sz::Int...) = FakeArray(T, sz) -fakesimilar(flags, X, T) = flags & ESTIMATE != 0 ? FakeArray(T, size(X)) : Array{T}(size(X)) -alignment_of(A::FakeArray) = Int32(0) - -## Julia wrappers around FFTW functions - -# _init_() must be called before any FFTW planning routine. -# -- Once FFTW is split into its own module, this can be called -# in the module __init__(), but for now we must call it lazily -# in every routine that might initialize the FFTW planner. -# -- This initializes FFTW's threads support (defaulting to 1 thread). -# If this isn't called before the FFTW planner is created, then -# FFTW's threads algorithms won't be registered or used at all. -# (Previously, we called fftw_cleanup, but this invalidated existing -# plans, causing issue #19892.) -const threads_initialized = Ref(false) -function _init_() - if !threads_initialized[] - stat = ccall((:fftw_init_threads,libfftw), Int32, ()) - statf = ccall((:fftwf_init_threads,libfftwf), Int32, ()) - if stat == 0 || statf == 0 - error("could not initialize FFTW threads") - end - threads_initialized[] = true - end -end - -# Wisdom - -# Import and export wisdom to/from a single file for all precisions, -# which is more user-friendly than requiring the user to call a -# separate routine depending on the fp precision of the plans. This -# requires a bit of trickness since we have to (a) use the libc file -# I/O routines with fftw_export_wisdom_to_file/import_wisdom_from_file -# (b) we need 256 bytes of space padding between the wisdoms to work -# around FFTW's internal file i/o buffering [see the BUFSZ constant in -# FFTW's api/import-wisdom-from-file.c file]. - -function export_wisdom(fname::AbstractString) - _init_() - f = ccall(:fopen, Ptr{Void}, (Cstring,Cstring), fname, :w) - systemerror("could not open wisdom file $fname for writing", f == C_NULL) - ccall((:fftw_export_wisdom_to_file,libfftw), Void, (Ptr{Void},), f) - ccall(:fputs, Int32, (Ptr{UInt8},Ptr{Void}), " "^256, f) # no NUL, hence no Cstring - ccall((:fftwf_export_wisdom_to_file,libfftwf), Void, (Ptr{Void},), f) - ccall(:fclose, Void, (Ptr{Void},), f) -end - -function import_wisdom(fname::AbstractString) - _init_() - f = ccall(:fopen, Ptr{Void}, (Cstring,Cstring), fname, :r) - systemerror("could not open wisdom file $fname for reading", f == C_NULL) - if ccall((:fftw_import_wisdom_from_file,libfftw),Int32,(Ptr{Void},),f)==0|| - ccall((:fftwf_import_wisdom_from_file,libfftwf),Int32,(Ptr{Void},),f)==0 - error("failed to import wisdom from $fname") - end - ccall(:fclose, Void, (Ptr{Void},), f) -end - -function import_system_wisdom() - _init_() - if ccall((:fftw_import_system_wisdom,libfftw), Int32, ()) == 0 || - ccall((:fftwf_import_system_wisdom,libfftwf), Int32, ()) == 0 - error("failed to import system wisdom") - end -end - -function forget_wisdom() - _init_() - ccall((:fftw_forget_wisdom,libfftw), Void, ()) - ccall((:fftwf_forget_wisdom,libfftwf), Void, ()) -end - -# Threads - -function set_num_threads(nthreads::Integer) - _init_() - ccall((:fftw_plan_with_nthreads,libfftw), Void, (Int32,), nthreads) - ccall((:fftwf_plan_with_nthreads,libfftwf), Void, (Int32,), nthreads) -end - -# pointer type for fftw_plan (opaque pointer) - -struct fftw_plan_struct end -const PlanPtr = Ptr{fftw_plan_struct} - -# Planner timelimits - -const NO_TIMELIMIT = -1.0 # from fftw3.h - -function set_timelimit(precision::fftwTypeDouble,seconds) - _init_() - ccall((:fftw_set_timelimit,libfftw), Void, (Float64,), seconds) -end - -function set_timelimit(precision::fftwTypeSingle,seconds) - _init_() - ccall((:fftwf_set_timelimit,libfftwf), Void, (Float64,), seconds) -end - -# Array alignment mod 16: -# FFTW plans may depend on the alignment of the array mod 16 bytes, -# i.e. the address mod 16 of the first element of the array, in order -# to exploit SIMD operations. Julia arrays are, by default, aligned -# to 16-byte boundaries (address mod 16 == 0), but this may not be -# true for data imported from external C code, or for SubArrays. -# Use the undocumented routine fftw_alignment_of to determine the -# alignment of a given pointer modulo whatever FFTW needs; this -# function will be documented in FFTW 3.3.4. - - -if Base.libfftw_name == "libmkl_rt" - alignment_of(A::StridedArray{<:fftwDouble}) = - convert(Int32, convert(Int64, pointer(A)) % 16) - alignment_of(A::StridedArray{<:fftwSingle}) = - convert(Int32, convert(Int64, pointer(A)) % 16) -else - alignment_of{T<:fftwDouble}(A::StridedArray{T}) = - ccall((:fftw_alignment_of, libfftw), Int32, (Ptr{T},), A) - alignment_of{T<:fftwSingle}(A::StridedArray{T}) = - ccall((:fftwf_alignment_of, libfftwf), Int32, (Ptr{T},), A) -end - -# FFTWPlan (low-level) - -# low-level storage of the FFTW plan, along with the information -# needed to determine whether it is applicable. We need to put -# this into a type to support a finalizer on the fftw_plan. -# K is FORWARD/BACKWARD for forward/backward or r2c/c2r plans, respectively. -# For r2r plans, K is a tuple of the transform kinds along each dimension. -abstract type FFTWPlan{T<:fftwNumber,K,inplace} <: Plan{T} end -for P in (:cFFTWPlan, :rFFTWPlan, :r2rFFTWPlan) # complex, r2c/c2r, and r2r - @eval begin - mutable struct $P{T<:fftwNumber,K,inplace,N} <: FFTWPlan{T,K,inplace} - plan::PlanPtr - sz::NTuple{N,Int} # size of array on which plan operates (Int tuple) - osz::NTuple{N,Int} # size of output array (Int tuple) - istride::NTuple{N,Int} # strides of input - ostride::NTuple{N,Int} # strides of output - ialign::Int32 # alignment mod 16 of input - oalign::Int32 # alignment mod 16 of input - flags::UInt32 # planner flags - region::Any # region (iterable) of dims that are transormed - pinv::ScaledPlan - function $P{T,K,inplace,N}(plan::PlanPtr, flags::Integer, R::Any, - X::StridedArray{T,N}, Y::StridedArray) where {T<:fftwNumber,K,inplace,N} - p = new(plan, size(X), size(Y), strides(X), strides(Y), - alignment_of(X), alignment_of(Y), flags, R) - finalizer(p, destroy_plan) - p - end - end - end -end - -size(p::FFTWPlan) = p.sz - -unsafe_convert(::Type{PlanPtr}, p::FFTWPlan) = p.plan - -destroy_plan(plan::FFTWPlan{<:fftwDouble}) = - ccall((:fftw_destroy_plan,libfftw), Void, (PlanPtr,), plan) - -destroy_plan(plan::FFTWPlan{<:fftwSingle}) = - ccall((:fftwf_destroy_plan,libfftwf), Void, (PlanPtr,), plan) - -cost(plan::FFTWPlan{<:fftwDouble}) = - ccall((:fftw_cost,libfftw), Float64, (PlanPtr,), plan) -cost(plan::FFTWPlan{<:fftwSingle}) = - ccall((:fftwf_cost,libfftwf), Float64, (PlanPtr,), plan) - -function arithmetic_ops(plan::FFTWPlan{<:fftwDouble}) - # Change to individual Ref after we can allocate them on stack - ref = Ref{NTuple{3,Float64}}() - ptr = Ptr{Float64}(Base.unsafe_convert(Ptr{NTuple{3,Float64}}, ref)) - ccall((:fftw_flops,libfftw), Void, - (PlanPtr,Ptr{Float64},Ptr{Float64},Ptr{Float64}), - plan, ptr, ptr + 8, ptr + 16) - (round(Int64, ref[][1]), round(Int64, ref[][2]), round(Int64, ref[][3])) -end -function arithmetic_ops(plan::FFTWPlan{<:fftwSingle}) - # Change to individual Ref after we can allocate them on stack - ref = Ref{NTuple{3,Float64}}() - ptr = Ptr{Float64}(Base.unsafe_convert(Ptr{NTuple{3,Float64}}, ref)) - ccall((:fftwf_flops,libfftwf), Void, - (PlanPtr,Ptr{Float64},Ptr{Float64},Ptr{Float64}), - plan, ptr, ptr + 8, ptr + 16) - (round(Int64, ref[][1]), round(Int64, ref[][2]), round(Int64, ref[][3])) -end -flops(plan::FFTWPlan) = let ops = arithmetic_ops(plan) - ops[1] + ops[2] + 2 * ops[3] # add + mul + 2*fma -end - -# Pretty-printing plans - -function showfftdims(io, sz::Dims, istride::Dims, T) - if isempty(sz) - print(io, "0-dimensional") - elseif length(sz) == 1 - print(io, sz[1], "-element") - else - print(io, join(sz, "×")) - end - if istride == colmajorstrides(sz) - print(io, " array of ", T) - else - print(io, " $istride-strided array of ", T) - end -end - -# The sprint_plan function was released in FFTW 3.3.4 -sprint_plan_(plan::FFTWPlan{<:fftwDouble}) = - ccall((:fftw_sprint_plan,libfftw), Ptr{UInt8}, (PlanPtr,), plan) -sprint_plan_(plan::FFTWPlan{<:fftwSingle}) = - ccall((:fftwf_sprint_plan,libfftwf), Ptr{UInt8}, (PlanPtr,), plan) -function sprint_plan(plan::FFTWPlan) - p = sprint_plan_(plan) - str = unsafe_string(p) - Libc.free(p) - return str -end - -function show(io::IO, p::cFFTWPlan{T,K,inplace}) where {T,K,inplace} - print(io, inplace ? "FFTW in-place " : "FFTW ", - K < 0 ? "forward" : "backward", " plan for ") - showfftdims(io, p.sz, p.istride, T) - version >= v"3.3.4" && print(io, "\n", sprint_plan(p)) -end - -function show(io::IO, p::rFFTWPlan{T,K,inplace}) where {T,K,inplace} - print(io, inplace ? "FFTW in-place " : "FFTW ", - K < 0 ? "real-to-complex" : "complex-to-real", - " plan for ") - showfftdims(io, p.sz, p.istride, T) - version >= v"3.3.4" && print(io, "\n", sprint_plan(p)) -end - -function show(io::IO, p::r2rFFTWPlan{T,K,inplace}) where {T,K,inplace} - print(io, inplace ? "FFTW in-place r2r " : "FFTW r2r ") - if isempty(K) - print(io, "0-dimensional") - elseif K == ntuple(i -> K[1], length(K)) - print(io, kind2string(K[1])) - if length(K) > 1 - print(io, "^", length(K)) - end - else - print(io, join(map(kind2string, K), "×")) - end - print(io, " plan for ") - showfftdims(io, p.sz, p.istride, T) - version >= v"3.3.4" && print(io, "\n", sprint_plan(p)) -end - -# Check whether a FFTWPlan is applicable to a given input array, and -# throw an informative error if not: -function assert_applicable(p::FFTWPlan{T}, X::StridedArray{T}) where T - if size(X) != p.sz - throw(ArgumentError("FFTW plan applied to wrong-size array")) - elseif strides(X) != p.istride - throw(ArgumentError("FFTW plan applied to wrong-strides array")) - elseif alignment_of(X) != p.ialign || p.flags & UNALIGNED != 0 - throw(ArgumentError("FFTW plan applied to array with wrong memory alignment")) - end -end - -function assert_applicable(p::FFTWPlan{T,K,inplace}, X::StridedArray{T}, Y::StridedArray) where {T,K,inplace} - assert_applicable(p, X) - if size(Y) != p.osz - throw(ArgumentError("FFTW plan applied to wrong-size output")) - elseif strides(Y) != p.ostride - throw(ArgumentError("FFTW plan applied to wrong-strides output")) - elseif alignment_of(Y) != p.oalign || p.flags & UNALIGNED != 0 - throw(ArgumentError("FFTW plan applied to output with wrong memory alignment")) - elseif inplace != (pointer(X) == pointer(Y)) - throw(ArgumentError(string("FFTW ", - inplace ? "in-place" : "out-of-place", - " plan applied to ", - inplace ? "out-of-place" : "in-place", - " data"))) - end -end - -# strides for a column-major (Julia-style) array of size == sz -colmajorstrides(sz) = isempty(sz) ? () : (1,cumprod(Int[sz[1:end-1]...])...) - -# Execute - -unsafe_execute!(plan::FFTWPlan{<:fftwDouble}) = - ccall((:fftw_execute,libfftw), Void, (PlanPtr,), plan) - -unsafe_execute!(plan::FFTWPlan{<:fftwSingle}) = - ccall((:fftwf_execute,libfftwf), Void, (PlanPtr,), plan) - -unsafe_execute!(plan::cFFTWPlan{T}, - X::StridedArray{T}, Y::StridedArray{T}) where {T<:fftwDouble} = - ccall((:fftw_execute_dft,libfftw), Void, - (PlanPtr,Ptr{T},Ptr{T}), plan, X, Y) - -unsafe_execute!(plan::cFFTWPlan{T}, - X::StridedArray{T}, Y::StridedArray{T}) where {T<:fftwSingle} = - ccall((:fftwf_execute_dft,libfftwf), Void, - (PlanPtr,Ptr{T},Ptr{T}), plan, X, Y) - -unsafe_execute!(plan::rFFTWPlan{Float64,FORWARD}, - X::StridedArray{Float64}, Y::StridedArray{Complex128}) = - ccall((:fftw_execute_dft_r2c,libfftw), Void, - (PlanPtr,Ptr{Float64},Ptr{Complex128}), plan, X, Y) - -unsafe_execute!(plan::rFFTWPlan{Float32,FORWARD}, - X::StridedArray{Float32}, Y::StridedArray{Complex64}) = - ccall((:fftwf_execute_dft_r2c,libfftwf), Void, - (PlanPtr,Ptr{Float32},Ptr{Complex64}), plan, X, Y) - -unsafe_execute!(plan::rFFTWPlan{Complex128,BACKWARD}, - X::StridedArray{Complex128}, Y::StridedArray{Float64}) = - ccall((:fftw_execute_dft_c2r,libfftw), Void, - (PlanPtr,Ptr{Complex128},Ptr{Float64}), plan, X, Y) - -unsafe_execute!(plan::rFFTWPlan{Complex64,BACKWARD}, - X::StridedArray{Complex64}, Y::StridedArray{Float32}) = - ccall((:fftwf_execute_dft_c2r,libfftwf), Void, - (PlanPtr,Ptr{Complex64},Ptr{Float32}), plan, X, Y) - -unsafe_execute!(plan::r2rFFTWPlan{T}, - X::StridedArray{T}, Y::StridedArray{T}) where {T<:fftwDouble} = - ccall((:fftw_execute_r2r,libfftw), Void, - (PlanPtr,Ptr{T},Ptr{T}), plan, X, Y) - -unsafe_execute!(plan::r2rFFTWPlan{T}, - X::StridedArray{T}, Y::StridedArray{T}) where {T<:fftwSingle} = - ccall((:fftwf_execute_r2r,libfftwf), Void, - (PlanPtr,Ptr{T},Ptr{T}), plan, X, Y) - -# NOTE ON GC (garbage collection): -# The FFTWPlan has a finalizer so that gc will destroy the plan, -# which is necessary for gc to work with plan_fft. However, -# even when we are creating a single-use FFTWPlan [e.g. for fftn(x)], -# we intentionally do NOT call destroy_plan explicitly, and instead -# wait for garbage collection. The reason is that, in the common -# case where the user calls fft(x) a second time soon afterwards, -# if destroy_plan has not yet been called then FFTW will internally -# re-use the table of trigonometric constants from the first plan. - -# Compute dims and howmany for FFTW guru planner -function dims_howmany(X::StridedArray, Y::StridedArray, - sz::Array{Int,1}, region) - reg = [region...] - if length(unique(reg)) < length(reg) - throw(ArgumentError("each dimension can be transformed at most once")) - end - ist = [strides(X)...] - ost = [strides(Y)...] - dims = [sz[reg] ist[reg] ost[reg]]' - oreg = [1:ndims(X);] - oreg[reg] = 0 - oreg = filter(d -> d > 0, oreg) - howmany = [sz[oreg] ist[oreg] ost[oreg]]' - return (dims, howmany) -end - -# check & convert kinds into int32 array with same length as region -function fix_kinds(region, kinds) - if length(kinds) != length(region) - if length(kinds) > length(region) - throw(ArgumentError("too many transform kinds")) - else - if isempty(kinds) - throw(ArgumentError("must supply a transform kind")) - end - k = Vector{Int32}(length(region)) - k[1:length(kinds)] = [kinds...] - k[length(kinds)+1:end] = kinds[end] - kinds = k - end - else - kinds = Int32[kinds...] - end - for i = 1:length(kinds) - if kinds[i] < 0 || kinds[i] > 10 - throw(ArgumentError("invalid transform kind")) - end - end - return kinds -end - -# low-level FFTWPlan creation (for internal use in FFTW module) - -for (Tr,Tc,fftw,lib) in ((:Float64,:Complex128,"fftw",libfftw), - (:Float32,:Complex64,"fftwf",libfftwf)) - @eval function (::Type{cFFTWPlan{$Tc,K,inplace,N}})(X::StridedArray{$Tc,N}, - Y::StridedArray{$Tc,N}, - region, flags::Integer, timelimit::Real) where {K,inplace,N} - direction = K - set_timelimit($Tr, timelimit) - R = isa(region, Tuple) ? region : copy(region) - dims, howmany = dims_howmany(X, Y, [size(X)...], R) - plan = ccall(($(string(fftw,"_plan_guru64_dft")),$lib), - PlanPtr, - (Int32, Ptr{Int}, Int32, Ptr{Int}, - Ptr{$Tc}, Ptr{$Tc}, Int32, UInt32), - size(dims,2), dims, size(howmany,2), howmany, - X, Y, direction, flags) - set_timelimit($Tr, NO_TIMELIMIT) - if plan == C_NULL - error("FFTW could not create plan") # shouldn't normally happen - end - return cFFTWPlan{$Tc,K,inplace,N}(plan, flags, R, X, Y) - end - - @eval function (::Type{rFFTWPlan{$Tr,$FORWARD,inplace,N}})(X::StridedArray{$Tr,N}, - Y::StridedArray{$Tc,N}, - region, flags::Integer, timelimit::Real) where {inplace,N} - R = isa(region, Tuple) ? region : copy(region) - region = circshift([region...],-1) # FFTW halves last dim - set_timelimit($Tr, timelimit) - dims, howmany = dims_howmany(X, Y, [size(X)...], region) - plan = ccall(($(string(fftw,"_plan_guru64_dft_r2c")),$lib), - PlanPtr, - (Int32, Ptr{Int}, Int32, Ptr{Int}, - Ptr{$Tr}, Ptr{$Tc}, UInt32), - size(dims,2), dims, size(howmany,2), howmany, - X, Y, flags) - set_timelimit($Tr, NO_TIMELIMIT) - if plan == C_NULL - error("FFTW could not create plan") # shouldn't normally happen - end - return rFFTWPlan{$Tr,$FORWARD,inplace,N}(plan, flags, R, X, Y) - end - - @eval function (::Type{rFFTWPlan{$Tc,$BACKWARD,inplace,N}})(X::StridedArray{$Tc,N}, - Y::StridedArray{$Tr,N}, - region, flags::Integer, timelimit::Real) where {inplace,N} - R = isa(region, Tuple) ? region : copy(region) - region = circshift([region...],-1) # FFTW halves last dim - set_timelimit($Tr, timelimit) - dims, howmany = dims_howmany(X, Y, [size(Y)...], region) - plan = ccall(($(string(fftw,"_plan_guru64_dft_c2r")),$lib), - PlanPtr, - (Int32, Ptr{Int}, Int32, Ptr{Int}, - Ptr{$Tc}, Ptr{$Tr}, UInt32), - size(dims,2), dims, size(howmany,2), howmany, - X, Y, flags) - set_timelimit($Tr, NO_TIMELIMIT) - if plan == C_NULL - error("FFTW could not create plan") # shouldn't normally happen - end - return rFFTWPlan{$Tc,$BACKWARD,inplace,N}(plan, flags, R, X, Y) - end - - @eval function (::Type{r2rFFTWPlan{$Tr,ANY,inplace,N}})(X::StridedArray{$Tr,N}, - Y::StridedArray{$Tr,N}, - region, kinds, flags::Integer, - timelimit::Real) where {inplace,N} - R = isa(region, Tuple) ? region : copy(region) - knd = fix_kinds(region, kinds) - set_timelimit($Tr, timelimit) - dims, howmany = dims_howmany(X, Y, [size(X)...], region) - plan = ccall(($(string(fftw,"_plan_guru64_r2r")),$lib), - PlanPtr, - (Int32, Ptr{Int}, Int32, Ptr{Int}, - Ptr{$Tr}, Ptr{$Tr}, Ptr{Int32}, UInt32), - size(dims,2), dims, size(howmany,2), howmany, - X, Y, knd, flags) - set_timelimit($Tr, NO_TIMELIMIT) - if plan == C_NULL - error("FFTW could not create plan") # shouldn't normally happen - end - r2rFFTWPlan{$Tr,(map(Int,knd)...),inplace,N}(plan, flags, R, X, Y) - end - - # support r2r transforms of complex = transforms of real & imag parts - @eval function (::Type{r2rFFTWPlan{$Tc,ANY,inplace,N}})(X::StridedArray{$Tc,N}, - Y::StridedArray{$Tc,N}, - region, kinds, flags::Integer, - timelimit::Real) where {inplace,N} - R = isa(region, Tuple) ? region : copy(region) - knd = fix_kinds(region, kinds) - set_timelimit($Tr, timelimit) - dims, howmany = dims_howmany(X, Y, [size(X)...], region) - dims[2:3, 1:size(dims,2)] *= 2 - howmany[2:3, 1:size(howmany,2)] *= 2 - howmany = [howmany [2,1,1]] # append loop over real/imag parts - plan = ccall(($(string(fftw,"_plan_guru64_r2r")),$lib), - PlanPtr, - (Int32, Ptr{Int}, Int32, Ptr{Int}, - Ptr{$Tc}, Ptr{$Tc}, Ptr{Int32}, UInt32), - size(dims,2), dims, size(howmany,2), howmany, - X, Y, knd, flags) - set_timelimit($Tr, NO_TIMELIMIT) - if plan == C_NULL - error("FFTW could not create plan") # shouldn't normally happen - end - r2rFFTWPlan{$Tc,(map(Int,knd)...),inplace,N}(plan, flags, R, X, Y) - end - -end - -# Convert arrays of numeric types to FFTW-supported packed complex-float types -# (FIXME: is there a way to use the Julia promotion rules more cleverly here?) -fftwcomplex(X::StridedArray{<:fftwComplex}) = X -fftwcomplex(X::AbstractArray{T}) where {T<:fftwReal} = - copy!(Array{typeof(complex(zero(T)))}(size(X)), X) -fftwcomplex(X::AbstractArray{<:Real}) = copy!(Array{Complex128}(size(X)),X) -fftwcomplex(X::AbstractArray{<:Complex}) = copy!(Array{Complex128}(size(X)), X) -fftwfloat(X::StridedArray{<:fftwReal}) = X -fftwfloat(X::AbstractArray{<:Real}) = copy!(Array{Float64}(size(X)), X) -fftwfloat(X::AbstractArray{<:Complex}) = fftwcomplex(X) - -for (f,direction) in ((:fft,FORWARD), (:bfft,BACKWARD)) - plan_f = Symbol("plan_",f) - plan_f! = Symbol("plan_",f,"!") - idirection = -direction - @eval begin - function $plan_f(X::StridedArray{T,N}, region; - flags::Integer=ESTIMATE, - timelimit::Real=NO_TIMELIMIT) where {T<:fftwComplex,N} - cFFTWPlan{T,$direction,false,N}(X, fakesimilar(flags, X, T), - region, flags, timelimit) - end - - function $plan_f!(X::StridedArray{T,N}, region; - flags::Integer=ESTIMATE, - timelimit::Real=NO_TIMELIMIT) where {T<:fftwComplex,N} - cFFTWPlan{T,$direction,true,N}(X, X, region, flags, timelimit) - end - $plan_f(X::StridedArray{<:fftwComplex}; kws...) = - $plan_f(X, 1:ndims(X); kws...) - $plan_f!(X::StridedArray{<:fftwComplex}; kws...) = - $plan_f!(X, 1:ndims(X); kws...) - - function plan_inv(p::cFFTWPlan{T,$direction,inplace,N}) where {T<:fftwComplex,N,inplace} - X = Array{T}(p.sz) - Y = inplace ? X : fakesimilar(p.flags, X, T) - ScaledPlan(cFFTWPlan{T,$idirection,inplace,N}(X, Y, p.region, - p.flags, NO_TIMELIMIT), - normalization(X, p.region)) - end - end -end - -function A_mul_B!(y::StridedArray{T}, p::cFFTWPlan{T}, x::StridedArray{T}) where T - assert_applicable(p, x, y) - unsafe_execute!(p, x, y) - return y -end - -function *(p::cFFTWPlan{T,K,false}, x::StridedArray{T,N}) where {T,K,N} - assert_applicable(p, x) - y = Array{T}(p.osz)::Array{T,N} - unsafe_execute!(p, x, y) - return y -end - -function *(p::cFFTWPlan{T,K,true}, x::StridedArray{T}) where {T,K} - assert_applicable(p, x) - unsafe_execute!(p, x, x) - return x -end - -# rfft/brfft and planned variants. No in-place version for now. - -for (Tr,Tc) in ((:Float32,:Complex64),(:Float64,:Complex128)) - # Note: use $FORWARD and $BACKWARD below because of issue #9775 - @eval begin - function plan_rfft(X::StridedArray{$Tr,N}, region; - flags::Integer=ESTIMATE, - timelimit::Real=NO_TIMELIMIT) where N - osize = rfft_output_size(X, region) - Y = flags&ESTIMATE != 0 ? FakeArray($Tc,osize...) : Array{$Tc}(osize...) - rFFTWPlan{$Tr,$FORWARD,false,N}(X, Y, region, flags, timelimit) - end - - function plan_brfft(X::StridedArray{$Tc,N}, d::Integer, region; - flags::Integer=ESTIMATE, - timelimit::Real=NO_TIMELIMIT) where N - osize = brfft_output_size(X, d, region) - Y = flags&ESTIMATE != 0 ? FakeArray($Tr,osize...) : Array{$Tr}(osize...) - - # FFTW currently doesn't support PRESERVE_INPUT for - # multidimensional out-of-place c2r transforms, so - # we have to handle 1d and >1d cases separately with a copy. Ugh. - if length(region) <= 1 - rFFTWPlan{$Tc,$BACKWARD,false,N}(X, Y, region, - flags | PRESERVE_INPUT, - timelimit) - else - rFFTWPlan{$Tc,$BACKWARD,false,N}(copy(X), Y, region, flags, - timelimit) - end - end - - plan_rfft(X::StridedArray{$Tr};kws...)=plan_rfft(X,1:ndims(X);kws...) - plan_brfft(X::StridedArray{$Tr};kws...)=plan_brfft(X,1:ndims(X);kws...) - - function plan_inv(p::rFFTWPlan{$Tr,$FORWARD,false,N}) where N - X = Array{$Tr}(p.sz) - Y = p.flags&ESTIMATE != 0 ? FakeArray($Tc,p.osz) : Array{$Tc}(p.osz) - ScaledPlan(rFFTWPlan{$Tc,$BACKWARD,false,N}(Y, X, p.region, - length(p.region) <= 1 ? - p.flags | PRESERVE_INPUT : - p.flags, NO_TIMELIMIT), - normalization(X, p.region)) - end - - function plan_inv(p::rFFTWPlan{$Tc,$BACKWARD,false,N}) where N - X = Arra{$Tc}(p.sz) - Y = p.flags&ESTIMATE != 0 ? FakeArray($Tr,p.osz) : Array{$Tr}(p.osz) - ScaledPlan(rFFTWPlan{$Tr,$FORWARD,false,N}(Y, X, p.region, - p.flags, NO_TIMELIMIT), - normalization(Y, p.region)) - end - - function A_mul_B!(y::StridedArray{$Tc}, p::rFFTWPlan{$Tr,$FORWARD}, x::StridedArray{$Tr}) - assert_applicable(p, x, y) - unsafe_execute!(p, x, y) - return y - end - function A_mul_B!(y::StridedArray{$Tr}, p::rFFTWPlan{$Tc,$BACKWARD}, x::StridedArray{$Tc}) - assert_applicable(p, x, y) - unsafe_execute!(p, x, y) # note: may overwrite x as well as y! - return y - end - - function *(p::rFFTWPlan{$Tr,$FORWARD,false}, x::StridedArray{$Tr,N}) where N - assert_applicable(p, x) - y = Array{$Tc}(p.osz)::Array{$Tc,N} - unsafe_execute!(p, x, y) - return y - end - - function *(p::rFFTWPlan{$Tc,$BACKWARD,false}, x::StridedArray{$Tc,N}) where N - if p.flags & PRESERVE_INPUT != 0 - assert_applicable(p, x) - y = Array{$Tr}(p.osz)::Array{$Tr,N} - unsafe_execute!(p, x, y) - else # need to make a copy to avoid overwriting x - xc = copy(x) - assert_applicable(p, xc) - y = Array{$Tr}(p.osz)::Array{$Tr,N} - unsafe_execute!(p, xc, y) - end - return y - end - end -end - -# FFTW r2r transforms (low-level interface) - -for f in (:r2r, :r2r!) - pf = Symbol("plan_", f) - @eval begin - $f(x::AbstractArray{<:fftwNumber}, kinds) = $pf(x, kinds) * x - $f(x::AbstractArray{<:fftwNumber}, kinds, region) = $pf(x, kinds, region) * x - $pf(x::AbstractArray, kinds; kws...) = $pf(x, kinds, 1:ndims(x); kws...) - $f(x::AbstractArray{<:Real}, kinds, region=1:ndims(x)) = $f(fftwfloat(x), kinds, region) - $pf(x::AbstractArray{<:Real}, kinds, region; kws...) = $pf(fftwfloat(x), kinds, region; kws...) - $f(x::AbstractArray{<:Complex}, kinds, region=1:ndims(x)) = $f(fftwcomplex(x), kinds, region) - $pf(x::AbstractArray{<:Complex}, kinds, region; kws...) = $pf(fftwcomplex(x), kinds, region; kws...) - end -end - -function plan_r2r(X::StridedArray{T,N}, kinds, region; - flags::Integer=ESTIMATE, - timelimit::Real=NO_TIMELIMIT) where {T<:fftwNumber,N} - r2rFFTWPlan{T,ANY,false,N}(X, fakesimilar(flags, X, T), region, kinds, - flags, timelimit) -end - -function plan_r2r!(X::StridedArray{T,N}, kinds, region; - flags::Integer=ESTIMATE, - timelimit::Real=NO_TIMELIMIT) where {T<:fftwNumber,N} - r2rFFTWPlan{T,ANY,true,N}(X, X, region, kinds, flags, timelimit) -end - -# mapping from r2r kind to the corresponding inverse transform -const inv_kind = Dict{Int,Int}(R2HC => HC2R, HC2R => R2HC, DHT => DHT, - REDFT00 => REDFT00, - REDFT01 => REDFT10, REDFT10 => REDFT01, - REDFT11 => REDFT11, - RODFT00 => RODFT00, - RODFT01 => RODFT10, RODFT10 => RODFT01, - RODFT11 => RODFT11) - -# r2r inverses are normalized to 1/N, where N is a "logical" size -# the transform with length n and kind k: -function logical_size(n::Integer, k::Integer) - k <= DHT && return n - k == REDFT00 && return 2(n-1) - k == RODFT00 && return 2(n+1) - return 2n -end - -function plan_inv(p::r2rFFTWPlan{T,K,inplace,N}) where {T<:fftwNumber,K,inplace,N} - X = Array{T}(p.sz) - iK = fix_kinds(p.region, [inv_kind[k] for k in K]) - Y = inplace ? X : fakesimilar(p.flags, X, T) - ScaledPlan(r2rFFTWPlan{T,ANY,inplace,N}(X, Y, p.region, iK, - p.flags, NO_TIMELIMIT), - normalization(real(T), - map(logical_size, [p.sz...][[p.region...]], iK), - 1:length(iK))) -end - -function A_mul_B!(y::StridedArray{T}, p::r2rFFTWPlan{T}, x::StridedArray{T}) where T - assert_applicable(p, x, y) - unsafe_execute!(p, x, y) - return y -end - -function *(p::r2rFFTWPlan{T,K,false}, x::StridedArray{T,N}) where {T,K,N} - assert_applicable(p, x) - y = Array{T}(p.osz)::Array{T,N} - unsafe_execute!(p, x, y) - return y -end - -function *(p::r2rFFTWPlan{T,K,true}, x::StridedArray{T}) where {T,K} - assert_applicable(p, x) - unsafe_execute!(p, x, x) - return x -end - -include("dct.jl") diff --git a/julia-0.6.3/share/julia/base/fft/dct.jl b/julia-0.6.3/share/julia/base/fft/dct.jl deleted file mode 100644 index a341096..0000000 --- a/julia-0.6.3/share/julia/base/fft/dct.jl +++ /dev/null @@ -1,103 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -# (This is part of the FFTW module.) - -export dct, idct, dct!, idct!, plan_dct, plan_idct, plan_dct!, plan_idct! - -# Discrete cosine transforms (type II/III) via FFTW's r2r transforms; -# we follow the Matlab convention and adopt a unitary normalization here. -# Unlike Matlab we compute the multidimensional transform by default, -# similar to the Julia fft functions. - -mutable struct DCTPlan{T<:fftwNumber,K,inplace} <: Plan{T} - plan::r2rFFTWPlan{T} - r::Array{UnitRange{Int}} # array of indices for rescaling - nrm::Float64 # normalization factor - region::Dims # dimensions being transformed - pinv::DCTPlan{T} - DCTPlan{T,K,inplace}(plan,r,nrm,region) where {T<:fftwNumber,K,inplace} = new(plan,r,nrm,region) -end - -size(p::DCTPlan) = size(p.plan) - -function show(io::IO, p::DCTPlan{T,K,inplace}) where {T,K,inplace} - print(io, inplace ? "FFTW in-place " : "FFTW ", - K == REDFT10 ? "DCT (DCT-II)" : "IDCT (DCT-III)", " plan for ") - showfftdims(io, p.plan.sz, p.plan.istride, eltype(p)) -end - -for (pf, pfr, K, inplace) in ((:plan_dct, :plan_r2r, REDFT10, false), - (:plan_dct!, :plan_r2r!, REDFT10, true), - (:plan_idct, :plan_r2r, REDFT01, false), - (:plan_idct!, :plan_r2r!, REDFT01, true)) - @eval function $pf(X::StridedArray{T}, region; kws...) where T<:fftwNumber - r = [1:n for n in size(X)] - nrm = sqrt(0.5^length(region) * normalization(X,region)) - DCTPlan{T,$K,$inplace}($pfr(X, $K, region; kws...), r, nrm, - ntuple(i -> Int(region[i]), length(region))) - end -end - -function plan_inv(p::DCTPlan{T,K,inplace}) where {T,K,inplace} - X = Array{T}(p.plan.sz) - iK = inv_kind[K] - DCTPlan{T,iK,inplace}(inplace ? - plan_r2r!(X, iK, p.region, flags=p.plan.flags) : - plan_r2r(X, iK, p.region, flags=p.plan.flags), - p.r, p.nrm, p.region) -end - -for f in (:dct, :dct!, :idct, :idct!) - pf = Symbol("plan_", f) - @eval begin - $f(x::AbstractArray{<:fftwNumber}) = $pf(x) * x - $f(x::AbstractArray{<:fftwNumber}, region) = $pf(x, region) * x - $pf(x::AbstractArray; kws...) = $pf(x, 1:ndims(x); kws...) - $f(x::AbstractArray{<:Real}, region=1:ndims(x)) = $f(fftwfloat(x), region) - $pf(x::AbstractArray{<:Real}, region; kws...) = $pf(fftwfloat(x), region; kws...) - $pf(x::AbstractArray{<:Complex}, region; kws...) = $pf(fftwcomplex(x), region; kws...) - end -end - -const sqrthalf = sqrt(0.5) -const sqrt2 = sqrt(2.0) -const onerange = 1:1 - -function A_mul_B!(y::StridedArray{T}, p::DCTPlan{T,REDFT10}, - x::StridedArray{T}) where T - assert_applicable(p.plan, x, y) - unsafe_execute!(p.plan, x, y) - scale!(y, p.nrm) - r = p.r - for d in p.region - oldr = r[d] - r[d] = onerange - y[r...] *= sqrthalf - r[d] = oldr - end - return y -end - -# note: idct changes input data -function A_mul_B!(y::StridedArray{T}, p::DCTPlan{T,REDFT01}, - x::StridedArray{T}) where T - assert_applicable(p.plan, x, y) - scale!(x, p.nrm) - r = p.r - for d in p.region - oldr = r[d] - r[d] = onerange - x[r...] *= sqrt2 - r[d] = oldr - end - unsafe_execute!(p.plan, x, y) - return y -end - -*(p::DCTPlan{T,REDFT10,false}, x::StridedArray{T}) where {T} = - A_mul_B!(Array{T}(p.plan.osz), p, x) - -*(p::DCTPlan{T,REDFT01,false}, x::StridedArray{T}) where {T} = - A_mul_B!(Array{T}(p.plan.osz), p, copy(x)) # need copy to preserve input - -*(p::DCTPlan{T,K,true}, x::StridedArray{T}) where {T,K} = A_mul_B!(x, p, x) diff --git a/julia-0.6.3/share/julia/base/file.jl b/julia-0.6.3/share/julia/base/file.jl deleted file mode 100644 index b9e8506..0000000 --- a/julia-0.6.3/share/julia/base/file.jl +++ /dev/null @@ -1,628 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -# Operations with the file system (paths) ## - -export - cd, - chmod, - chown, - cp, - cptree, - mkdir, - mkpath, - mktemp, - mktempdir, - mv, - pwd, - rename, - readlink, - readdir, - rm, - samefile, - sendfile, - symlink, - tempdir, - tempname, - touch, - unlink, - walkdir - -# get and set current directory - -""" - pwd() -> AbstractString - -Get the current working directory. -""" -function pwd() - b = Vector{UInt8}(1024) - len = Ref{Csize_t}(length(b)) - uv_error(:getcwd, ccall(:uv_cwd, Cint, (Ptr{UInt8}, Ptr{Csize_t}), b, len)) - String(b[1:len[]]) -end - -""" - cd(dir::AbstractString=homedir()) - -Set the current working directory. -""" -function cd(dir::AbstractString) - uv_error("chdir $dir", ccall(:uv_chdir, Cint, (Cstring,), dir)) -end -cd() = cd(homedir()) - -if is_windows() - function cd(f::Function, dir::AbstractString) - old = pwd() - try - cd(dir) - f() - finally - cd(old) - end - end -else - function cd(f::Function, dir::AbstractString) - fd = ccall(:open, Int32, (Cstring, Int32), :., 0) - systemerror(:open, fd == -1) - try - cd(dir) - f() - finally - systemerror(:fchdir, ccall(:fchdir, Int32, (Int32,), fd) != 0) - systemerror(:close, ccall(:close, Int32, (Int32,), fd) != 0) - end - end -end -""" - cd(f::Function, dir::AbstractString=homedir()) - -Temporarily changes the current working directory and applies function `f` before returning. -""" -cd(f::Function) = cd(f, homedir()) - -""" - mkdir(path::AbstractString, mode::Unsigned=0o777) - -Make a new directory with name `path` and permissions `mode`. `mode` defaults to `0o777`, -modified by the current file creation mask. This function never creates more than one -directory. If the directory already exists, or some intermediate directories do not exist, -this function throws an error. See [`mkpath`](@ref) for a function which creates all -required intermediate directories. -""" -function mkdir(path::AbstractString, mode::Unsigned=0o777) - @static if is_windows() - ret = ccall(:_wmkdir, Int32, (Cwstring,), path) - else - ret = ccall(:mkdir, Int32, (Cstring, UInt32), path, mode) - end - systemerror(:mkdir, ret != 0; extrainfo=path) -end - -""" - mkpath(path::AbstractString, mode::Unsigned=0o777) - -Create all directories in the given `path`, with permissions `mode`. `mode` defaults to -`0o777`, modified by the current file creation mask. -""" -function mkpath(path::AbstractString, mode::Unsigned=0o777) - isdirpath(path) && (path = dirname(path)) - dir = dirname(path) - (path == dir || isdir(path)) && return - mkpath(dir, mode) - try - mkdir(path, mode) - # If there is a problem with making the directory, but the directory - # does in fact exist, then ignore the error. Else re-throw it. - catch err - if isa(err, SystemError) && isdir(path) - return - else - rethrow() - end - end -end - -mkdir(path::AbstractString, mode::Signed) = throw(ArgumentError("mode must be an unsigned integer; try 0o$mode")) -mkpath(path::AbstractString, mode::Signed) = throw(ArgumentError("mode must be an unsigned integer; try 0o$mode")) - -""" - rm(path::AbstractString; force::Bool=false, recursive::Bool=false) - -Delete the file, link, or empty directory at the given path. If `force=true` is passed, a -non-existing path is not treated as error. If `recursive=true` is passed and the path is a -directory, then all contents are removed recursively. -""" -function rm(path::AbstractString; force::Bool=false, recursive::Bool=false) - if islink(path) || !isdir(path) - try - @static if is_windows() - # is writable on windows actually means "is deletable" - if (filemode(path) & 0o222) == 0 - chmod(path, 0o777) - end - end - unlink(path) - catch err - if force && isa(err, UVError) && err.code==Base.UV_ENOENT - return - end - rethrow() - end - else - if recursive - for p in readdir(path) - rm(joinpath(path, p), force=force, recursive=true) - end - end - @static if is_windows() - ret = ccall(:_wrmdir, Int32, (Cwstring,), path) - else - ret = ccall(:rmdir, Int32, (Cstring,), path) - end - systemerror(:rmdir, ret != 0, extrainfo=path) - end -end - - -# The following use Unix command line facilites -function checkfor_mv_cp_cptree(src::AbstractString, dst::AbstractString, txt::AbstractString; - remove_destination::Bool=false) - if ispath(dst) - if remove_destination - # Check for issue when: (src == dst) or when one is a link to the other - # https://github.com/JuliaLang/julia/pull/11172#issuecomment-100391076 - if Base.samefile(src, dst) - abs_src = islink(src) ? abspath(readlink(src)) : abspath(src) - abs_dst = islink(dst) ? abspath(readlink(dst)) : abspath(dst) - throw(ArgumentError(string("'src' and 'dst' refer to the same file/dir.", - "This is not supported.\n ", - "`src` refers to: $(abs_src)\n ", - "`dst` refers to: $(abs_dst)\n"))) - end - rm(dst; recursive=true) - else - throw(ArgumentError(string("'$dst' exists. `remove_destination=true` ", - "is required to remove '$dst' before $(txt)."))) - end - end -end - -function cptree(src::AbstractString, dst::AbstractString; remove_destination::Bool=false, - follow_symlinks::Bool=false) - isdir(src) || throw(ArgumentError("'$src' is not a directory. Use `cp(src, dst)`")) - checkfor_mv_cp_cptree(src, dst, "copying"; remove_destination=remove_destination) - mkdir(dst) - for name in readdir(src) - srcname = joinpath(src, name) - if !follow_symlinks && islink(srcname) - symlink(readlink(srcname), joinpath(dst, name)) - elseif isdir(srcname) - cptree(srcname, joinpath(dst, name); remove_destination=remove_destination, - follow_symlinks=follow_symlinks) - else - sendfile(srcname, joinpath(dst, name)) - end - end -end - -""" - cp(src::AbstractString, dst::AbstractString; remove_destination::Bool=false, follow_symlinks::Bool=false) - -Copy the file, link, or directory from `src` to `dest`. -`remove_destination=true` will first remove an existing `dst`. - -If `follow_symlinks=false`, and `src` is a symbolic link, `dst` will be created as a -symbolic link. If `follow_symlinks=true` and `src` is a symbolic link, `dst` will be a copy -of the file or directory `src` refers to. -""" -function cp(src::AbstractString, dst::AbstractString; remove_destination::Bool=false, - follow_symlinks::Bool=false) - checkfor_mv_cp_cptree(src, dst, "copying"; remove_destination=remove_destination) - if !follow_symlinks && islink(src) - symlink(readlink(src), dst) - elseif isdir(src) - cptree(src, dst; remove_destination=remove_destination, follow_symlinks=follow_symlinks) - else - sendfile(src, dst) - end -end - -""" - mv(src::AbstractString, dst::AbstractString; remove_destination::Bool=false) - -Move the file, link, or directory from `src` to `dst`. -`remove_destination=true` will first remove an existing `dst`. -""" -function mv(src::AbstractString, dst::AbstractString; remove_destination::Bool=false) - checkfor_mv_cp_cptree(src, dst, "moving"; remove_destination=remove_destination) - rename(src, dst) -end - -""" - touch(path::AbstractString) - -Update the last-modified timestamp on a file to the current time. -""" -function touch(path::AbstractString) - f = open(path, JL_O_WRONLY | JL_O_CREAT, 0o0666) - try - t = time() - futime(f,t,t) - finally - close(f) - end -end - -if is_windows() - -function tempdir() - temppath = Vector{UInt16}(32767) - lentemppath = ccall(:GetTempPathW,stdcall,UInt32,(UInt32,Ptr{UInt16}),length(temppath),temppath) - if lentemppath >= length(temppath) || lentemppath == 0 - error("GetTempPath failed: $(Libc.FormatMessage())") - end - resize!(temppath,lentemppath) - return transcode(String, temppath) -end -tempname(uunique::UInt32=UInt32(0)) = tempname(tempdir(), uunique) -const temp_prefix = cwstring("jl_") -function tempname(temppath::AbstractString,uunique::UInt32) - tempp = cwstring(temppath) - tname = Vector{UInt16}(32767) - uunique = ccall(:GetTempFileNameW,stdcall,UInt32,(Ptr{UInt16},Ptr{UInt16},UInt32,Ptr{UInt16}), tempp,temp_prefix,uunique,tname) - lentname = findfirst(tname,0)-1 - if uunique == 0 || lentname <= 0 - error("GetTempFileName failed: $(Libc.FormatMessage())") - end - resize!(tname,lentname) - return transcode(String, tname) -end - -function mktemp(parent=tempdir()) - filename = tempname(parent, UInt32(0)) - return (filename, Base.open(filename, "r+")) -end - -function mktempdir(parent=tempdir()) - seed::UInt32 = rand(UInt32) - while true - if (seed & typemax(UInt16)) == 0 - seed += 1 - end - filename = tempname(parent, seed) - ret = ccall(:_wmkdir, Int32, (Ptr{UInt16},), cwstring(filename)) - if ret == 0 - return filename - end - systemerror(:mktempdir, Libc.errno()!=Libc.EEXIST) - seed += 1 - end -end - -else # !windows -# Obtain a temporary filename. -function tempname() - d = get(ENV, "TMPDIR", C_NULL) # tempnam ignores TMPDIR on darwin - p = ccall(:tempnam, Cstring, (Cstring,Cstring), d, :julia) - systemerror(:tempnam, p == C_NULL) - s = unsafe_string(p) - Libc.free(p) - return s -end - -# Obtain a temporary directory's path. -tempdir() = dirname(tempname()) - -# Create and return the name of a temporary file along with an IOStream -function mktemp(parent=tempdir()) - b = joinpath(parent, "tmpXXXXXX") - p = ccall(:mkstemp, Int32, (Cstring,), b) # modifies b - systemerror(:mktemp, p == -1) - return (b, fdio(p, true)) -end - -# Create and return the name of a temporary directory -function mktempdir(parent=tempdir()) - b = joinpath(parent, "tmpXXXXXX") - p = ccall(:mkdtemp, Cstring, (Cstring,), b) - systemerror(:mktempdir, p == C_NULL) - return unsafe_string(p) -end - -end # os-test - - -""" - tempdir() - -Obtain the path of a temporary directory (possibly shared with other processes). -""" -tempdir() - -""" - tempname() - -Generate a unique temporary file path. -""" -tempname() - -""" - mktemp(parent=tempdir()) - -Returns `(path, io)`, where `path` is the path of a new temporary file in `parent` and `io` -is an open file object for this path. -""" -mktemp(parent) - -""" - mktempdir(parent=tempdir()) - -Create a temporary directory in the `parent` directory and return its path. -If `parent` does not exist, throw an error. -""" -mktempdir(parent) - - -""" - mktemp(f::Function, parent=tempdir()) - -Apply the function `f` to the result of [`mktemp(parent)`](@ref) and remove the -temporary file upon completion. -""" -function mktemp(fn::Function, parent=tempdir()) - (tmp_path, tmp_io) = mktemp(parent) - try - fn(tmp_path, tmp_io) - finally - close(tmp_io) - rm(tmp_path) - end -end - -""" - mktempdir(f::Function, parent=tempdir()) - -Apply the function `f` to the result of [`mktempdir(parent)`](@ref) and remove the -temporary directory upon completion. -""" -function mktempdir(fn::Function, parent=tempdir()) - tmpdir = mktempdir(parent) - try - fn(tmpdir) - finally - rm(tmpdir, recursive=true) - end -end - -struct uv_dirent_t - name::Ptr{UInt8} - typ::Cint -end - -""" - readdir(dir::AbstractString=".") -> Vector{String} - -Returns the files and directories in the directory `dir` (or the current working directory if not given). -""" -function readdir(path::AbstractString) - # Allocate space for uv_fs_t struct - uv_readdir_req = zeros(UInt8, ccall(:jl_sizeof_uv_fs_t, Int32, ())) - - # defined in sys.c, to call uv_fs_readdir, which sets errno on error. - err = ccall(:uv_fs_scandir, Int32, (Ptr{Void}, Ptr{UInt8}, Cstring, Cint, Ptr{Void}), - eventloop(), uv_readdir_req, path, 0, C_NULL) - err < 0 && throw(SystemError("unable to read directory $path", -err)) - #uv_error("unable to read directory $path", err) - - # iterate the listing into entries - entries = String[] - ent = Ref{uv_dirent_t}() - while Base.UV_EOF != ccall(:uv_fs_scandir_next, Cint, (Ptr{Void}, Ptr{uv_dirent_t}), uv_readdir_req, ent) - push!(entries, unsafe_string(ent[].name)) - end - - # Clean up the request string - ccall(:jl_uv_fs_req_cleanup, Void, (Ptr{UInt8},), uv_readdir_req) - - return entries -end - -readdir() = readdir(".") - -""" - walkdir(dir; topdown=true, follow_symlinks=false, onerror=throw) - -The `walkdir` method returns an iterator that walks the directory tree of a directory. -The iterator returns a tuple containing `(rootpath, dirs, files)`. -The directory tree can be traversed top-down or bottom-up. -If `walkdir` encounters a [`SystemError`](@ref) -it will rethrow the error by default. -A custom error handling function can be provided through `onerror` keyword argument. -`onerror` is called with a `SystemError` as argument. - - for (root, dirs, files) in walkdir(".") - println("Directories in \$root") - for dir in dirs - println(joinpath(root, dir)) # path to directories - end - println("Files in \$root") - for file in files - println(joinpath(root, file)) # path to files - end - end - -""" -function walkdir(root; topdown=true, follow_symlinks=false, onerror=throw) - content = nothing - try - content = readdir(root) - catch err - isa(err, SystemError) || throw(err) - onerror(err) - # Need to return an empty closed channel to skip the current root folder - chnl = Channel(0) - close(chnl) - return chnl - end - dirs = Vector{eltype(content)}(0) - files = Vector{eltype(content)}(0) - for name in content - if isdir(joinpath(root, name)) - push!(dirs, name) - else - push!(files, name) - end - end - - function _it(chnl) - if topdown - put!(chnl, (root, dirs, files)) - end - for dir in dirs - path = joinpath(root,dir) - if follow_symlinks || !islink(path) - for (root_l, dirs_l, files_l) in walkdir(path, topdown=topdown, follow_symlinks=follow_symlinks, onerror=onerror) - put!(chnl, (root_l, dirs_l, files_l)) - end - end - end - if !topdown - put!(chnl, (root, dirs, files)) - end - end - - return Channel(_it) -end - -function unlink(p::AbstractString) - err = ccall(:jl_fs_unlink, Int32, (Cstring,), p) - uv_error("unlink", err) - nothing -end - -# For move command -function rename(src::AbstractString, dst::AbstractString) - err = ccall(:jl_fs_rename, Int32, (Cstring, Cstring), src, dst) - # on error, default to cp && rm - if err < 0 - # remove_destination: is already done in the mv function - cp(src, dst; remove_destination=false, follow_symlinks=false) - rm(src; recursive=true) - end - nothing -end - -function sendfile(src::AbstractString, dst::AbstractString) - local src_open = false - local dst_open = false - local src_file, dst_file - try - src_file = open(src, JL_O_RDONLY) - src_open = true - dst_file = open(dst, JL_O_CREAT | JL_O_TRUNC | JL_O_WRONLY, - S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP| S_IROTH | S_IWOTH) - dst_open = true - - bytes = filesize(stat(src_file)) - sendfile(dst_file, src_file, Int64(0), Int(bytes)) - finally - if src_open && isopen(src_file) - close(src_file) - end - if dst_open && isopen(dst_file) - close(dst_file) - end - end -end - -if is_windows() - const UV_FS_SYMLINK_JUNCTION = 0x0002 -end - -""" - symlink(target::AbstractString, link::AbstractString) - -Creates a symbolic link to `target` with the name `link`. - -!!! note - This function raises an error under operating systems that do not support - soft symbolic links, such as Windows XP. -""" -function symlink(p::AbstractString, np::AbstractString) - @static if is_windows() - if Sys.windows_version() < Sys.WINDOWS_VISTA_VER - error("Windows XP does not support soft symlinks") - end - end - flags = 0 - @static if is_windows() - if isdir(p) - flags |= UV_FS_SYMLINK_JUNCTION - p = abspath(p) - end - end - err = ccall(:jl_fs_symlink, Int32, (Cstring, Cstring, Cint), p, np, flags) - @static if is_windows() - if err < 0 && !isdir(p) - Base.warn_once("Note: on Windows, creating file symlinks requires Administrator privileges.") - end - end - uv_error("symlink",err) -end - -""" - readlink(path::AbstractString) -> AbstractString - -Returns the target location a symbolic link `path` points to. -""" -function readlink(path::AbstractString) - req = Libc.malloc(_sizeof_uv_fs) - try - ret = ccall(:uv_fs_readlink, Int32, - (Ptr{Void}, Ptr{Void}, Cstring, Ptr{Void}), - eventloop(), req, path, C_NULL) - if ret < 0 - ccall(:uv_fs_req_cleanup, Void, (Ptr{Void},), req) - uv_error("readlink", ret) - assert(false) - end - tgt = unsafe_string(ccall(:jl_uv_fs_t_ptr, Ptr{Cchar}, (Ptr{Void},), req)) - ccall(:uv_fs_req_cleanup, Void, (Ptr{Void},), req) - return tgt - finally - Libc.free(req) - end -end - -""" - chmod(path::AbstractString, mode::Integer; recursive::Bool=false) - -Change the permissions mode of `path` to `mode`. Only integer `mode`s (e.g. `0o777`) are -currently supported. If `recursive=true` and the path is a directory all permissions in -that directory will be recursively changed. -""" -function chmod(path::AbstractString, mode::Integer; recursive::Bool=false) - err = ccall(:jl_fs_chmod, Int32, (Cstring, Cint), path, mode) - uv_error("chmod", err) - if recursive && isdir(path) - for p in readdir(path) - if !islink(joinpath(path, p)) - chmod(joinpath(path, p), mode, recursive=true) - end - end - end - nothing -end - -""" - chown(path::AbstractString, owner::Integer, group::Integer=-1) - -Change the owner and/or group of `path` to `owner` and/or `group`. If the value entered for `owner` or `group` -is `-1` the corresponding ID will not change. Only integer `owner`s and `group`s are currently supported. -""" -function chown(path::AbstractString, owner::Integer, group::Integer=-1) - err = ccall(:jl_fs_chown, Int32, (Cstring, Cint, Cint), path, owner, group) - uv_error("chown",err) - nothing -end diff --git a/julia-0.6.3/share/julia/base/filesystem.jl b/julia-0.6.3/share/julia/base/filesystem.jl deleted file mode 100644 index bdbd8a0..0000000 --- a/julia-0.6.3/share/julia/base/filesystem.jl +++ /dev/null @@ -1,212 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -## File Operations (Libuv-based) ## - -module Filesystem - -const S_IRUSR = 0o400 -const S_IWUSR = 0o200 -const S_IXUSR = 0o100 -const S_IRWXU = 0o700 -const S_IRGRP = 0o040 -const S_IWGRP = 0o020 -const S_IXGRP = 0o010 -const S_IRWXG = 0o070 -const S_IROTH = 0o004 -const S_IWOTH = 0o002 -const S_IXOTH = 0o001 -const S_IRWXO = 0o007 - -export File, - StatStruct, - # open, - futime, - write, - JL_O_WRONLY, - JL_O_RDONLY, - JL_O_RDWR, - JL_O_APPEND, - JL_O_CREAT, - JL_O_EXCL, - JL_O_TRUNC, - JL_O_TEMPORARY, - JL_O_SHORT_LIVED, - JL_O_SEQUENTIAL, - JL_O_RANDOM, - JL_O_NOCTTY, - S_IRUSR, S_IWUSR, S_IXUSR, S_IRWXU, - S_IRGRP, S_IWGRP, S_IXGRP, S_IRWXG, - S_IROTH, S_IWOTH, S_IXOTH, S_IRWXO - -import Base: - UVError, _sizeof_uv_fs, check_open, close, eof, eventloop, fd, isopen, - nb_available, position, read, read!, readavailable, seek, seekend, show, - skip, stat, unsafe_read, unsafe_write, transcode, uv_error, uvhandle, - uvtype, write - -if is_windows() - import Base: cwstring -end - -include("path.jl") -include("stat.jl") -include("file.jl") -include("poll.jl") -include(string(length(Core.ARGS)>=2?Core.ARGS[2]:"","file_constants.jl")) # include($BUILDROOT/base/file_constants.jl) - -## Operations with File (fd) objects ## - -abstract type AbstractFile <: IO end - -mutable struct File <: AbstractFile - open::Bool - handle::RawFD - File(fd::RawFD) = new(true, fd) -end - -# Not actually a pointer, but that's how we pass it through the C API so it's fine -uvhandle(file::File) = convert(Ptr{Void}, Base.cconvert(Cint, file.handle) % UInt) -uvtype(::File) = Base.UV_RAW_FD - -# Filesystem.open, not Base.open -function open(path::AbstractString, flags::Integer, mode::Integer=0) - req = Libc.malloc(_sizeof_uv_fs) - local handle - try - ret = ccall(:uv_fs_open, Int32, - (Ptr{Void}, Ptr{Void}, Cstring, Int32, Int32, Ptr{Void}), - eventloop(), req, path, flags, mode, C_NULL) - handle = ccall(:jl_uv_fs_result, Int32, (Ptr{Void},), req) - ccall(:uv_fs_req_cleanup, Void, (Ptr{Void},), req) - uv_error("open", ret) - finally # conversion to Cstring could cause an exception - Libc.free(req) - end - return File(RawFD(handle)) -end - -isopen(f::File) = f.open -function check_open(f::File) - if !isopen(f) - throw(ArgumentError("file is closed")) - end -end - -function close(f::File) - check_open(f) - err = ccall(:jl_fs_close, Int32, (Int32,), f.handle) - uv_error("close", err) - f.handle = RawFD(-1) - f.open = false - return nothing -end - -# sendfile is the most efficient way to copy a file (or any file descriptor) -function sendfile(dst::File, src::File, src_offset::Int64, bytes::Int) - check_open(dst) - check_open(src) - err = ccall(:jl_fs_sendfile, Int32, (Int32, Int32, Int64, Csize_t), - src.handle, dst.handle, src_offset, bytes) - uv_error("sendfile", err) - nothing -end - -function unsafe_write(f::File, buf::Ptr{UInt8}, len::UInt, offset::Int64=Int64(-1)) - check_open(f) - err = ccall(:jl_fs_write, Int32, (Int32, Ptr{UInt8}, Csize_t, Int64), - f.handle, buf, len, offset) - uv_error("write", err) - return len -end - -write(f::File, c::UInt8) = write(f, Ref{UInt8}(c)) - -function truncate(f::File, n::Integer) - check_open(f) - req = Libc.malloc(_sizeof_uv_fs) - err = ccall(:uv_fs_ftruncate, Int32, - (Ptr{Void}, Ptr{Void}, Int32, Int64, Ptr{Void}), - eventloop(), req, f.handle, n, C_NULL) - Libc.free(req) - uv_error("ftruncate", err) - return f -end - -function futime(f::File, atime::Float64, mtime::Float64) - check_open(f) - req = Libc.malloc(_sizeof_uv_fs) - err = ccall(:uv_fs_futime, Int32, - (Ptr{Void}, Ptr{Void}, Int32, Float64, Float64, Ptr{Void}), - eventloop(), req, f.handle, atime, mtime, C_NULL) - Libc.free(req) - uv_error("futime", err) - return f -end - -function read(f::File, ::Type{UInt8}) - check_open(f) - ret = ccall(:jl_fs_read_byte, Int32, (Int32,), f.handle) - uv_error("read", ret) - return ret % UInt8 -end - -function unsafe_read(f::File, p::Ptr{UInt8}, nel::UInt) - check_open(f) - ret = ccall(:jl_fs_read, Int32, (Int32, Ptr{Void}, Csize_t), - f.handle, p, nel) - uv_error("read",ret) - ret == nel || throw(EOFError()) - nothing -end - -nb_available(f::File) = max(0, filesize(f) - position(f)) # position can be > filesize - -eof(f::File) = nb_available(f) == 0 - -function readbytes!(f::File, b::Array{UInt8}, nb=length(b)) - nr = min(nb, nb_available(f)) - if length(b) < nr - resize!(b, nr) - end - ret = ccall(:jl_fs_read, Int32, (Int32, Ptr{Void}, Csize_t), - f.handle, b, nr) - uv_error("read",ret) - return ret -end -read(io::File) = read!(io, Base.StringVector(nb_available(io))) -readavailable(io::File) = read(io) -read(io::File, nb::Integer) = read!(io, Base.StringVector(min(nb, nb_available(io)))) - -const SEEK_SET = Int32(0) -const SEEK_CUR = Int32(1) -const SEEK_END = Int32(2) - -function seek(f::File, n::Integer) - ret = ccall(:jl_lseek, Int64, (Int32, Int64, Int32), f.handle, n, SEEK_SET) - systemerror("seek", ret == -1) - return f -end - -function seekend(f::File) - ret = ccall(:jl_lseek, Int64, (Int32, Int64, Int32), f.handle, 0, SEEK_END) - systemerror("seekend", ret == -1) - return f -end - -function skip(f::File, n::Integer) - ret = ccall(:jl_lseek, Int64, (Int32, Int64, Int32), f.handle, n, SEEK_CUR) - systemerror("skip", ret == -1) - return f -end - -function position(f::File) - check_open(f) - ret = ccall(:jl_lseek, Int64, (Int32, Int64, Int32), f.handle, 0, SEEK_CUR) - systemerror("lseek", ret == -1) - return ret -end - -fd(f::File) = f.handle -stat(f::File) = stat(f.handle) - -end diff --git a/julia-0.6.3/share/julia/base/float.jl b/julia-0.6.3/share/julia/base/float.jl deleted file mode 100644 index bd4cf0d..0000000 --- a/julia-0.6.3/share/julia/base/float.jl +++ /dev/null @@ -1,868 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -## floating point traits ## - -""" - Inf16 - -Positive infinity of type [`Float16`](@ref). -""" -const Inf16 = bitcast(Float16, 0x7c00) -""" - NaN16 - -A not-a-number value of type [`Float16`](@ref). -""" -const NaN16 = bitcast(Float16, 0x7e00) -""" - Inf32 - -Positive infinity of type [`Float32`](@ref). -""" -const Inf32 = bitcast(Float32, 0x7f800000) -""" - NaN32 - -A not-a-number value of type [`Float32`](@ref). -""" -const NaN32 = bitcast(Float32, 0x7fc00000) -const Inf64 = bitcast(Float64, 0x7ff0000000000000) -const NaN64 = bitcast(Float64, 0x7ff8000000000000) - -""" - Inf - -Positive infinity of type [`Float64`](@ref). -""" -const Inf = Inf64 -""" - NaN - -A not-a-number value of type [`Float64`](@ref). -""" -const NaN = NaN64 - -## conversions to floating-point ## -convert(::Type{Float16}, x::Integer) = convert(Float16, convert(Float32, x)) -for t in (Int8, Int16, Int32, Int64, Int128, UInt8, UInt16, UInt32, UInt64, UInt128) - @eval promote_rule(::Type{Float16}, ::Type{$t}) = Float16 -end -promote_rule(::Type{Float16}, ::Type{Bool}) = Float16 - -for t1 in (Float32, Float64) - for st in (Int8, Int16, Int32, Int64) - @eval begin - convert(::Type{$t1}, x::($st)) = sitofp($t1, x) - promote_rule(::Type{$t1}, ::Type{$st}) = $t1 - end - end - for ut in (Bool, UInt8, UInt16, UInt32, UInt64) - @eval begin - convert(::Type{$t1}, x::($ut)) = uitofp($t1, x) - promote_rule(::Type{$t1}, ::Type{$ut}) = $t1 - end - end -end -convert(::Type{Integer}, x::Float16) = convert(Integer, Float32(x)) -convert(::Type{T}, x::Float16) where {T<:Integer} = convert(T, Float32(x)) - - -promote_rule(::Type{Float64}, ::Type{UInt128}) = Float64 -promote_rule(::Type{Float64}, ::Type{Int128}) = Float64 -promote_rule(::Type{Float32}, ::Type{UInt128}) = Float32 -promote_rule(::Type{Float32}, ::Type{Int128}) = Float32 - -function convert(::Type{Float64}, x::UInt128) - x == 0 && return 0.0 - n = 128-leading_zeros(x) # ndigits0z(x,2) - if n <= 53 - y = ((x % UInt64) << (53-n)) & 0x000f_ffff_ffff_ffff - else - y = ((x >> (n-54)) % UInt64) & 0x001f_ffff_ffff_ffff # keep 1 extra bit - y = (y+1)>>1 # round, ties up (extra leading bit in case of next exponent) - y &= ~UInt64(trailing_zeros(x) == (n-54)) # fix last bit to round to even - end - d = ((n+1022) % UInt64) << 52 - reinterpret(Float64, d + y) -end - -function convert(::Type{Float64}, x::Int128) - x == 0 && return 0.0 - s = ((x >>> 64) % UInt64) & 0x8000_0000_0000_0000 # sign bit - x = abs(x) % UInt128 - n = 128-leading_zeros(x) # ndigits0z(x,2) - if n <= 53 - y = ((x % UInt64) << (53-n)) & 0x000f_ffff_ffff_ffff - else - y = ((x >> (n-54)) % UInt64) & 0x001f_ffff_ffff_ffff # keep 1 extra bit - y = (y+1)>>1 # round, ties up (extra leading bit in case of next exponent) - y &= ~UInt64(trailing_zeros(x) == (n-54)) # fix last bit to round to even - end - d = ((n+1022) % UInt64) << 52 - reinterpret(Float64, s | d + y) -end - -function convert(::Type{Float32}, x::UInt128) - x == 0 && return 0f0 - n = 128-leading_zeros(x) # ndigits0z(x,2) - if n <= 24 - y = ((x % UInt32) << (24-n)) & 0x007f_ffff - else - y = ((x >> (n-25)) % UInt32) & 0x00ff_ffff # keep 1 extra bit - y = (y+one(UInt32))>>1 # round, ties up (extra leading bit in case of next exponent) - y &= ~UInt32(trailing_zeros(x) == (n-25)) # fix last bit to round to even - end - d = ((n+126) % UInt32) << 23 - reinterpret(Float32, d + y) -end - -function convert(::Type{Float32}, x::Int128) - x == 0 && return 0f0 - s = ((x >>> 96) % UInt32) & 0x8000_0000 # sign bit - x = abs(x) % UInt128 - n = 128-leading_zeros(x) # ndigits0z(x,2) - if n <= 24 - y = ((x % UInt32) << (24-n)) & 0x007f_ffff - else - y = ((x >> (n-25)) % UInt32) & 0x00ff_ffff # keep 1 extra bit - y = (y+one(UInt32))>>1 # round, ties up (extra leading bit in case of next exponent) - y &= ~UInt32(trailing_zeros(x) == (n-25)) # fix last bit to round to even - end - d = ((n+126) % UInt32) << 23 - reinterpret(Float32, s | d + y) -end - -function convert(::Type{Float16}, val::Float32) - f = reinterpret(UInt32, val) - i = (f >> 23) & 0x1ff + 1 - sh = shifttable[i] - f &= 0x007fffff - h::UInt16 = basetable[i] + (f >> sh) - # round - # NOTE: we maybe should ignore NaNs here, but the payload is - # getting truncated anyway so "rounding" it might not matter - nextbit = (f >> (sh-1)) & 1 - if nextbit != 0 - # Round halfway to even or check lower bits - if h&1 == 1 || (f & ((1<<(sh-1))-1)) != 0 - h += 1 - end - end - reinterpret(Float16, h) -end - -function convert(::Type{Float32}, val::Float16) - local ival::UInt32 = reinterpret(UInt16, val) - local sign::UInt32 = (ival & 0x8000) >> 15 - local exp::UInt32 = (ival & 0x7c00) >> 10 - local sig::UInt32 = (ival & 0x3ff) >> 0 - local ret::UInt32 - - if exp == 0 - if sig == 0 - sign = sign << 31 - ret = sign | exp | sig - else - n_bit = 1 - bit = 0x0200 - while (bit & sig) == 0 - n_bit = n_bit + 1 - bit = bit >> 1 - end - sign = sign << 31 - exp = (-14 - n_bit + 127) << 23 - sig = ((sig & (~bit)) << n_bit) << (23 - 10) - ret = sign | exp | sig - end - elseif exp == 0x1f - if sig == 0 # Inf - if sign == 0 - ret = 0x7f800000 - else - ret = 0xff800000 - end - else # NaN - ret = 0x7fc00000 | (sign<<31) - end - else - sign = sign << 31 - exp = (exp - 15 + 127) << 23 - sig = sig << (23 - 10) - ret = sign | exp | sig - end - return reinterpret(Float32, ret) -end - -# Float32 -> Float16 algorithm from: -# "Fast Half Float Conversion" by Jeroen van der Zijp -# ftp://ftp.fox-toolkit.org/pub/fasthalffloatconversion.pdf - -const basetable = Vector{UInt16}(512) -const shifttable = Vector{UInt8}(512) - -for i = 0:255 - e = i - 127 - if e < -24 # Very small numbers map to zero - basetable[i|0x000+1] = 0x0000 - basetable[i|0x100+1] = 0x8000 - shifttable[i|0x000+1] = 24 - shifttable[i|0x100+1] = 24 - elseif e < -14 # Small numbers map to denorms - basetable[i|0x000+1] = (0x0400>>(-e-14)) - basetable[i|0x100+1] = (0x0400>>(-e-14)) | 0x8000 - shifttable[i|0x000+1] = -e-1 - shifttable[i|0x100+1] = -e-1 - elseif e <= 15 # Normal numbers just lose precision - basetable[i|0x000+1] = ((e+15)<<10) - basetable[i|0x100+1] = ((e+15)<<10) | 0x8000 - shifttable[i|0x000+1] = 13 - shifttable[i|0x100+1] = 13 - elseif e < 128 # Large numbers map to Infinity - basetable[i|0x000+1] = 0x7C00 - basetable[i|0x100+1] = 0xFC00 - shifttable[i|0x000+1] = 24 - shifttable[i|0x100+1] = 24 - else # Infinity and NaN's stay Infinity and NaN's - basetable[i|0x000+1] = 0x7C00 - basetable[i|0x100+1] = 0xFC00 - shifttable[i|0x000+1] = 13 - shifttable[i|0x100+1] = 13 - end -end -#convert(::Type{Float16}, x::Float32) = fptrunc(Float16, x) -convert(::Type{Float32}, x::Float64) = fptrunc(Float32, x) -convert(::Type{Float16}, x::Float64) = convert(Float16, convert(Float32, x)) - -#convert(::Type{Float32}, x::Float16) = fpext(Float32, x) -convert(::Type{Float64}, x::Float32) = fpext(Float64, x) -convert(::Type{Float64}, x::Float16) = convert(Float64, convert(Float32, x)) - -convert(::Type{AbstractFloat}, x::Bool) = convert(Float64, x) -convert(::Type{AbstractFloat}, x::Int8) = convert(Float64, x) -convert(::Type{AbstractFloat}, x::Int16) = convert(Float64, x) -convert(::Type{AbstractFloat}, x::Int32) = convert(Float64, x) -convert(::Type{AbstractFloat}, x::Int64) = convert(Float64, x) # LOSSY -convert(::Type{AbstractFloat}, x::Int128) = convert(Float64, x) # LOSSY -convert(::Type{AbstractFloat}, x::UInt8) = convert(Float64, x) -convert(::Type{AbstractFloat}, x::UInt16) = convert(Float64, x) -convert(::Type{AbstractFloat}, x::UInt32) = convert(Float64, x) -convert(::Type{AbstractFloat}, x::UInt64) = convert(Float64, x) # LOSSY -convert(::Type{AbstractFloat}, x::UInt128) = convert(Float64, x) # LOSSY - -""" - float(x) - -Convert a number or array to a floating point data type. -When passed a string, this function is equivalent to `parse(Float64, x)`. -""" -float(x) = convert(AbstractFloat, x) - -""" - float(T::Type) - -Returns an appropriate type to represent a value of type `T` as a floating point value. -Equivalent to `typeof(float(zero(T)))`. - -```jldoctest -julia> float(Complex{Int}) -Complex{Float64} - -julia> float(Int) -Float64 -``` -""" -float(::Type{T}) where {T<:Number} = typeof(float(zero(T))) - -for Ti in (Int8, Int16, Int32, Int64) - @eval begin - unsafe_trunc(::Type{$Ti}, x::Float16) = unsafe_trunc($Ti, Float32(x)) - unsafe_trunc(::Type{$Ti}, x::Float32) = fptosi($Ti, x) - unsafe_trunc(::Type{$Ti}, x::Float64) = fptosi($Ti, x) - end -end -for Ti in (UInt8, UInt16, UInt32, UInt64) - @eval begin - unsafe_trunc(::Type{$Ti}, x::Float16) = unsafe_trunc($Ti, Float32(x)) - unsafe_trunc(::Type{$Ti}, x::Float32) = fptoui($Ti, x) - unsafe_trunc(::Type{$Ti}, x::Float64) = fptoui($Ti, x) - end -end - -function unsafe_trunc(::Type{UInt128}, x::Float64) - xu = reinterpret(UInt64,x) - k = Int(xu >> 52) & 0x07ff - 1075 - xu = (xu & 0x000f_ffff_ffff_ffff) | 0x0010_0000_0000_0000 - if k <= 0 - UInt128(xu >> -k) - else - UInt128(xu) << k - end -end -function unsafe_trunc(::Type{Int128}, x::Float64) - copysign(unsafe_trunc(UInt128,x) % Int128, x) -end - -function unsafe_trunc(::Type{UInt128}, x::Float32) - xu = reinterpret(UInt32,x) - k = Int(xu >> 23) & 0x00ff - 150 - xu = (xu & 0x007f_ffff) | 0x0080_0000 - if k <= 0 - UInt128(xu >> -k) - else - UInt128(xu) << k - end -end -function unsafe_trunc(::Type{Int128}, x::Float32) - copysign(unsafe_trunc(UInt128,x) % Int128, x) -end - -unsafe_trunc(::Type{UInt128}, x::Float16) = unsafe_trunc(UInt128, Float32(x)) -unsafe_trunc(::Type{Int128}, x::Float16) = unsafe_trunc(Int128, Float32(x)) - -# matches convert methods -# also determines floor, ceil, round -trunc(::Type{Signed}, x::Float32) = trunc(Int,x) -trunc(::Type{Signed}, x::Float64) = trunc(Int,x) -trunc(::Type{Unsigned}, x::Float32) = trunc(UInt,x) -trunc(::Type{Unsigned}, x::Float64) = trunc(UInt,x) -trunc(::Type{Integer}, x::Float32) = trunc(Int,x) -trunc(::Type{Integer}, x::Float64) = trunc(Int,x) -trunc(::Type{T}, x::Float16) where {T<:Integer} = trunc(T, Float32(x)) - -# fallbacks -floor(::Type{T}, x::AbstractFloat) where {T<:Integer} = trunc(T,floor(x)) -floor(::Type{T}, x::Float16) where {T<:Integer} = floor(T, Float32(x)) -ceil(::Type{T}, x::AbstractFloat) where {T<:Integer} = trunc(T,ceil(x)) -ceil(::Type{T}, x::Float16) where {T<:Integer} = ceil(T, Float32(x)) -round(::Type{T}, x::AbstractFloat) where {T<:Integer} = trunc(T,round(x)) -round(::Type{T}, x::Float16) where {T<:Integer} = round(T, Float32(x)) - -trunc(x::Float64) = trunc_llvm(x) -trunc(x::Float32) = trunc_llvm(x) -trunc(x::Float16) = Float16(trunc(Float32(x))) - -floor(x::Float64) = floor_llvm(x) -floor(x::Float32) = floor_llvm(x) -floor(x::Float16) = Float16(floor(Float32(x))) - -ceil(x::Float64) = ceil_llvm(x) -ceil(x::Float32) = ceil_llvm(x) -ceil(x::Float16) = Float16( ceil(Float32(x))) - -round(x::Float64) = rint_llvm(x) -round(x::Float32) = rint_llvm(x) -round(x::Float16) = Float16(round(Float32(x))) - -## floating point promotions ## -promote_rule(::Type{Float32}, ::Type{Float16}) = Float32 -promote_rule(::Type{Float64}, ::Type{Float16}) = Float64 -promote_rule(::Type{Float64}, ::Type{Float32}) = Float64 - -widen(::Type{Float16}) = Float32 -widen(::Type{Float32}) = Float64 - -_default_type(T::Union{Type{Real},Type{AbstractFloat}}) = Float64 - -## floating point arithmetic ## --(x::Float64) = neg_float(x) --(x::Float32) = neg_float(x) --(x::Float16) = reinterpret(Float16, reinterpret(UInt16, x) ⊻ 0x8000) - -for op in (:+, :-, :*, :/, :\, :^) - @eval ($op)(a::Float16, b::Float16) = Float16(($op)(Float32(a), Float32(b))) -end -+(x::Float32, y::Float32) = add_float(x, y) -+(x::Float64, y::Float64) = add_float(x, y) --(x::Float32, y::Float32) = sub_float(x, y) --(x::Float64, y::Float64) = sub_float(x, y) -*(x::Float32, y::Float32) = mul_float(x, y) -*(x::Float64, y::Float64) = mul_float(x, y) -/(x::Float32, y::Float32) = div_float(x, y) -/(x::Float64, y::Float64) = div_float(x, y) - -muladd(x::Float32, y::Float32, z::Float32) = muladd_float(x, y, z) -muladd(x::Float64, y::Float64, z::Float64) = muladd_float(x, y, z) -function muladd(a::Float16, b::Float16, c::Float16) - Float16(muladd(Float32(a), Float32(b), Float32(c))) -end - -# TODO: faster floating point div? -# TODO: faster floating point fld? -# TODO: faster floating point mod? - -for func in (:div,:fld,:cld,:rem,:mod) - @eval begin - $func(a::Float16,b::Float16) = Float16($func(Float32(a),Float32(b))) - end -end - -rem(x::Float32, y::Float32) = rem_float(x, y) -rem(x::Float64, y::Float64) = rem_float(x, y) - -cld(x::T, y::T) where {T<:AbstractFloat} = -fld(-x,y) - -function mod(x::T, y::T) where T<:AbstractFloat - r = rem(x,y) - if r == 0 - copysign(r,y) - elseif (r > 0) ⊻ (y > 0) - r+y - else - r - end -end - -## floating point comparisons ## -function ==(x::Float16, y::Float16) - ix = reinterpret(UInt16,x) - iy = reinterpret(UInt16,y) - if (ix|iy)&0x7fff > 0x7c00 #isnan(x) || isnan(y) - return false - end - if (ix|iy)&0x7fff == 0x0000 - return true - end - return ix == iy -end -==(x::Float32, y::Float32) = eq_float(x, y) -==(x::Float64, y::Float64) = eq_float(x, y) -!=(x::Float32, y::Float32) = ne_float(x, y) -!=(x::Float64, y::Float64) = ne_float(x, y) -<( x::Float32, y::Float32) = lt_float(x, y) -<( x::Float64, y::Float64) = lt_float(x, y) -<=(x::Float32, y::Float32) = le_float(x, y) -<=(x::Float64, y::Float64) = le_float(x, y) - -isequal(x::Float32, y::Float32) = fpiseq(x, y) -isequal(x::Float64, y::Float64) = fpiseq(x, y) -isless( x::Float32, y::Float32) = fpislt(x, y) -isless( x::Float64, y::Float64) = fpislt(x, y) -for op in (:<, :<=, :isless) - @eval ($op)(a::Float16, b::Float16) = ($op)(Float32(a), Float32(b)) -end - -function cmp(x::AbstractFloat, y::AbstractFloat) - (isnan(x) || isnan(y)) && throw(DomainError()) - ifelse(xy, 1, 0)) -end - -function cmp(x::Real, y::AbstractFloat) - isnan(y) && throw(DomainError()) - ifelse(xy, 1, 0)) -end - -function cmp(x::AbstractFloat, y::Real) - isnan(x) && throw(DomainError()) - ifelse(xy, 1, 0)) -end - -# Exact Float (Tf) vs Integer (Ti) comparisons -# Assumes: -# - typemax(Ti) == 2^n-1 -# - typemax(Ti) can't be exactly represented by Tf: -# => Tf(typemax(Ti)) == 2^n or Inf -# - typemin(Ti) can be exactly represented by Tf -# -# 1. convert y::Ti to float fy::Tf -# 2. perform Tf comparison x vs fy -# 3. if x == fy, check if (1) resulted in rounding: -# a. convert fy back to Ti and compare with original y -# b. unsafe_convert undefined behaviour if fy == Tf(typemax(Ti)) -# (but consequently x == fy > y) -for Ti in (Int64,UInt64,Int128,UInt128) - for Tf in (Float32,Float64) - @eval begin - function ==(x::$Tf, y::$Ti) - fy = ($Tf)(y) - (x == fy) & (fy != $(Tf(typemax(Ti)))) & (y == unsafe_trunc($Ti,fy)) - end - ==(y::$Ti, x::$Tf) = x==y - - function <(x::$Ti, y::$Tf) - fx = ($Tf)(x) - (fx < y) | ((fx == y) & ((fx == $(Tf(typemax(Ti)))) | (x < unsafe_trunc($Ti,fx)) )) - end - function <=(x::$Ti, y::$Tf) - fx = ($Tf)(x) - (fx < y) | ((fx == y) & ((fx == $(Tf(typemax(Ti)))) | (x <= unsafe_trunc($Ti,fx)) )) - end - - function <(x::$Tf, y::$Ti) - fy = ($Tf)(y) - (x < fy) | ((x == fy) & (fy < $(Tf(typemax(Ti)))) & (unsafe_trunc($Ti,fy) < y)) - end - function <=(x::$Tf, y::$Ti) - fy = ($Tf)(y) - (x < fy) | ((x == fy) & (fy < $(Tf(typemax(Ti)))) & (unsafe_trunc($Ti,fy) <= y)) - end - end - end -end - -==(x::Float32, y::Union{Int32,UInt32}) = Float64(x)==Float64(y) -==(x::Union{Int32,UInt32}, y::Float32) = Float64(x)==Float64(y) - -<(x::Float32, y::Union{Int32,UInt32}) = Float64(x) Bool - -Test whether a floating point number is not a number (NaN). -""" -isnan(x::AbstractFloat) = x != x -isnan(x::Float16) = reinterpret(UInt16,x)&0x7fff > 0x7c00 -isnan(x::Real) = false - -""" - isfinite(f) -> Bool - -Test whether a number is finite. - -```jldoctest -julia> isfinite(5) -true - -julia> isfinite(NaN32) -false -``` -""" -isfinite(x::AbstractFloat) = x - x == 0 -isfinite(x::Float16) = reinterpret(UInt16,x)&0x7c00 != 0x7c00 -isfinite(x::Real) = decompose(x)[3] != 0 -isfinite(x::Integer) = true - -""" - isinf(f) -> Bool - -Test whether a number is infinite. -""" -isinf(x::Real) = !isnan(x) & !isfinite(x) - -## hashing small, built-in numeric types ## - -hx(a::UInt64, b::Float64, h::UInt) = hash_uint64((3a + reinterpret(UInt64,b)) - h) -const hx_NaN = hx(UInt64(0), NaN, UInt(0 )) - -hash(x::UInt64, h::UInt) = hx(x, Float64(x), h) -hash(x::Int64, h::UInt) = hx(reinterpret(UInt64, abs(x)), Float64(x), h) -hash(x::Float64, h::UInt) = isnan(x) ? (hx_NaN ⊻ h) : hx(fptoui(UInt64, abs(x)), x, h) - -hash(x::Union{Bool,Int8,UInt8,Int16,UInt16,Int32,UInt32}, h::UInt) = hash(Int64(x), h) -hash(x::Float32, h::UInt) = hash(Float64(x), h) - -## precision, as defined by the effective number of bits in the mantissa ## -precision(::Type{Float16}) = 11 -precision(::Type{Float32}) = 24 -precision(::Type{Float64}) = 53 -precision(::T) where {T<:AbstractFloat} = precision(T) - -""" - uabs(x::Integer) - -Returns the absolute value of `x`, possibly returning a different type should the -operation be susceptible to overflow. This typically arises when `x` is a two's complement -signed integer, so that `abs(typemin(x)) == typemin(x) < 0`, in which case the result of -`uabs(x)` will be an unsigned integer of the same size. -""" -uabs(x::Integer) = abs(x) -uabs(x::Signed) = unsigned(abs(x)) - - -""" - nextfloat(x::AbstractFloat, n::Integer) - -The result of `n` iterative applications of `nextfloat` to `x` if `n >= 0`, or `-n` -applications of `prevfloat` if `n < 0`. -""" -function nextfloat(f::Union{Float16,Float32,Float64}, d::Integer) - F = typeof(f) - fumax = reinterpret(Unsigned, F(Inf)) - U = typeof(fumax) - - isnan(f) && return f - fi = reinterpret(Signed, f) - fneg = fi < 0 - fu = unsigned(fi & typemax(fi)) - - dneg = d < 0 - da = uabs(d) - if da > typemax(U) - fneg = dneg - fu = fumax - else - du = da % U - if fneg ⊻ dneg - if du > fu - fu = min(fumax, du - fu) - fneg = !fneg - else - fu = fu - du - end - else - if fumax - fu < du - fu = fumax - else - fu = fu + du - end - end - end - if fneg - fu |= sign_mask(F) - end - reinterpret(F, fu) -end - -""" - nextfloat(x::AbstractFloat) - -Returns the smallest floating point number `y` of the same type as `x` such `x < y`. If no -such `y` exists (e.g. if `x` is `Inf` or `NaN`), then returns `x`. -""" -nextfloat(x::AbstractFloat) = nextfloat(x,1) - -""" - prevfloat(x::AbstractFloat) - -Returns the largest floating point number `y` of the same type as `x` such `y < x`. If no -such `y` exists (e.g. if `x` is `-Inf` or `NaN`), then returns `x`. -""" -prevfloat(x::AbstractFloat) = nextfloat(x,-1) - -for Ti in (Int8, Int16, Int32, Int64, Int128, UInt8, UInt16, UInt32, UInt64, UInt128) - for Tf in (Float32, Float64) - if Ti <: Unsigned || sizeof(Ti) < sizeof(Tf) - # Here `Tf(typemin(Ti))-1` is exact, so we can compare the lower-bound - # directly. `Tf(typemax(Ti))+1` is either always exactly representable, or - # rounded to `Inf` (e.g. when `Ti==UInt128 && Tf==Float32`). - @eval begin - function trunc(::Type{$Ti},x::$Tf) - if $(Tf(typemin(Ti))-one(Tf)) < x < $(Tf(typemax(Ti))+one(Tf)) - return unsafe_trunc($Ti,x) - else - throw(InexactError()) - end - end - function convert(::Type{$Ti}, x::$Tf) - if ($(Tf(typemin(Ti))) <= x <= $(Tf(typemax(Ti)))) && (trunc(x) == x) - return unsafe_trunc($Ti,x) - else - throw(InexactError()) - end - end - end - else - # Here `eps(Tf(typemin(Ti))) > 1`, so the only value which can be truncated to - # `Tf(typemin(Ti)` is itself. Similarly, `Tf(typemax(Ti))` is inexact and will - # be rounded up. This assumes that `Tf(typemin(Ti)) > -Inf`, which is true for - # these types, but not for `Float16` or larger integer types. - @eval begin - function trunc(::Type{$Ti},x::$Tf) - if $(Tf(typemin(Ti))) <= x < $(Tf(typemax(Ti))) - return unsafe_trunc($Ti,x) - else - throw(InexactError()) - end - end - function convert(::Type{$Ti}, x::$Tf) - if ($(Tf(typemin(Ti))) <= x < $(Tf(typemax(Ti)))) && (trunc(x) == x) - return unsafe_trunc($Ti,x) - else - throw(InexactError()) - end - end - end - end - end -end - -@eval begin - issubnormal(x::Float32) = (abs(x) < $(bitcast(Float32, 0x00800000))) & (x!=0) - issubnormal(x::Float64) = (abs(x) < $(bitcast(Float64, 0x0010000000000000))) & (x!=0) - - typemin(::Type{Float16}) = $(bitcast(Float16, 0xfc00)) - typemax(::Type{Float16}) = $(Inf16) - typemin(::Type{Float32}) = $(-Inf32) - typemax(::Type{Float32}) = $(Inf32) - typemin(::Type{Float64}) = $(-Inf64) - typemax(::Type{Float64}) = $(Inf64) - typemin(x::T) where {T<:Real} = typemin(T) - typemax(x::T) where {T<:Real} = typemax(T) - - realmin(::Type{Float16}) = $(bitcast(Float16, 0x0400)) - realmin(::Type{Float32}) = $(bitcast(Float32, 0x00800000)) - realmin(::Type{Float64}) = $(bitcast(Float64, 0x0010000000000000)) - realmax(::Type{Float16}) = $(bitcast(Float16, 0x7bff)) - realmax(::Type{Float32}) = $(bitcast(Float32, 0x7f7fffff)) - realmax(::Type{Float64}) = $(bitcast(Float64, 0x7fefffffffffffff)) - realmin(x::T) where {T<:AbstractFloat} = realmin(T) - realmax(x::T) where {T<:AbstractFloat} = realmax(T) - realmin() = realmin(Float64) - realmax() = realmax(Float64) - - eps(x::AbstractFloat) = isfinite(x) ? abs(x) >= realmin(x) ? ldexp(eps(typeof(x)), exponent(x)) : nextfloat(zero(x)) : oftype(x, NaN) - eps(::Type{Float16}) = $(bitcast(Float16, 0x1400)) - eps(::Type{Float32}) = $(bitcast(Float32, 0x34000000)) - eps(::Type{Float64}) = $(bitcast(Float64, 0x3cb0000000000000)) - eps() = eps(Float64) -end - -""" - eps(::Type{T}) where T<:AbstractFloat - eps() - -Returns the *machine epsilon* of the floating point type `T` (`T = Float64` by -default). This is defined as the gap between 1 and the next largest value representable by -`T`, and is equivalent to `eps(one(T))`. - -```jldoctest -julia> eps() -2.220446049250313e-16 - -julia> eps(Float32) -1.1920929f-7 - -julia> 1.0 + eps() -1.0000000000000002 - -julia> 1.0 + eps()/2 -1.0 -``` -""" -eps(::Type{<:AbstractFloat}) - -""" - eps(x::AbstractFloat) - -Returns the *unit in last place* (ulp) of `x`. This is the distance between consecutive -representable floating point values at `x`. In most cases, if the distance on either side -of `x` is different, then the larger of the two is taken, that is - - eps(x) == max(x-prevfloat(x), nextfloat(x)-x) - -The exceptions to this rule are the smallest and largest finite values -(e.g. `nextfloat(-Inf)` and `prevfloat(Inf)` for [`Float64`](@ref)), which round to the -smaller of the values. - -The rationale for this behavior is that `eps` bounds the floating point rounding -error. Under the default `RoundNearest` rounding mode, if ``y`` is a real number and ``x`` -is the nearest floating point number to ``y``, then - -```math -|y-x| \\leq \\operatorname{eps}(x)/2. -``` - -```jldoctest -julia> eps(1.0) -2.220446049250313e-16 - -julia> eps(prevfloat(2.0)) -2.220446049250313e-16 - -julia> eps(2.0) -4.440892098500626e-16 - -julia> x = prevfloat(Inf) # largest finite Float64 -1.7976931348623157e308 - -julia> x + eps(x)/2 # rounds up -Inf - -julia> x + prevfloat(eps(x)/2) # rounds down -1.7976931348623157e308 -``` -""" -eps(::AbstractFloat) - - -## byte order swaps for arbitrary-endianness serialization/deserialization ## -bswap(x::Float32) = bswap_int(x) -bswap(x::Float64) = bswap_int(x) - -# bit patterns -reinterpret(::Type{Unsigned}, x::Float64) = reinterpret(UInt64, x) -reinterpret(::Type{Unsigned}, x::Float32) = reinterpret(UInt32, x) -reinterpret(::Type{Signed}, x::Float64) = reinterpret(Int64, x) -reinterpret(::Type{Signed}, x::Float32) = reinterpret(Int32, x) - -sign_mask(::Type{Float64}) = 0x8000_0000_0000_0000 -exponent_mask(::Type{Float64}) = 0x7ff0_0000_0000_0000 -exponent_one(::Type{Float64}) = 0x3ff0_0000_0000_0000 -exponent_half(::Type{Float64}) = 0x3fe0_0000_0000_0000 -significand_mask(::Type{Float64}) = 0x000f_ffff_ffff_ffff - -sign_mask(::Type{Float32}) = 0x8000_0000 -exponent_mask(::Type{Float32}) = 0x7f80_0000 -exponent_one(::Type{Float32}) = 0x3f80_0000 -exponent_half(::Type{Float32}) = 0x3f00_0000 -significand_mask(::Type{Float32}) = 0x007f_ffff - -sign_mask(::Type{Float16}) = 0x8000 -exponent_mask(::Type{Float16}) = 0x7c00 -exponent_one(::Type{Float16}) = 0x3c00 -exponent_half(::Type{Float16}) = 0x3800 -significand_mask(::Type{Float16}) = 0x03ff - -# integer size of float -fpinttype(::Type{Float64}) = UInt64 -fpinttype(::Type{Float32}) = UInt32 -fpinttype(::Type{Float16}) = UInt16 - -## TwicePrecision utilities -# The numeric constants are half the number of bits in the mantissa -for (F, T, n) in ((Float16, UInt16, 5), (Float32, UInt32, 12), (Float64, UInt64, 26)) - @eval begin - function truncbits(x::$F, nb) - @_inline_meta - truncmask(x, typemax($T) << nb) - end - function truncmask(x::$F, mask) - @_inline_meta - reinterpret($F, mask & reinterpret($T, x)) - end - function splitprec(x::$F) - @_inline_meta - hi = truncmask(x, typemax($T) << $n) - hi, x-hi - end - end -end - -truncbits(x, nb) = x -truncmask(x, mask) = x - -## Array operations on floating point numbers ## - -float(A::AbstractArray{<:AbstractFloat}) = A - -function float(A::AbstractArray{T}) where T - if !isleaftype(T) - error("`float` not defined on abstractly-typed arrays; please convert to a more specific type") - end - convert(AbstractArray{typeof(float(zero(T)))}, A) -end - -float(r::StepRange) = float(r.start):float(r.step):float(last(r)) -float(r::UnitRange) = float(r.start):float(last(r)) -float(r::StepRangeLen) = StepRangeLen(float(r.ref), float(r.step), length(r), r.offset) -function float(r::LinSpace) - LinSpace(float(r.start), float(r.stop), length(r)) -end - -# big, broadcast over arrays -# TODO: do the definitions below primarily pertaining to integers belong in float.jl? -function big end # no prior definitions of big in sysimg.jl, necessitating this -broadcast(::typeof(big), r::UnitRange) = big(r.start):big(last(r)) -broadcast(::typeof(big), r::StepRange) = big(r.start):big(r.step):big(last(r)) -broadcast(::typeof(big), r::StepRangeLen) = StepRangeLen(big(r.ref), big(r.step), length(r), r.offset) -function broadcast(::typeof(big), r::LinSpace) - LinSpace(big(r.start), big(r.stop), length(r)) -end diff --git a/julia-0.6.3/share/julia/base/floatfuncs.jl b/julia-0.6.3/share/julia/base/floatfuncs.jl deleted file mode 100644 index 88f5723..0000000 --- a/julia-0.6.3/share/julia/base/floatfuncs.jl +++ /dev/null @@ -1,246 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -## floating-point functions ## - -copysign(x::Float64, y::Float64) = copysign_float(x, y) -copysign(x::Float32, y::Float32) = copysign_float(x, y) -copysign(x::Float32, y::Real) = copysign(x, Float32(y)) -copysign(x::Float64, y::Real) = copysign(x, Float64(y)) - -flipsign(x::Float64, y::Float64) = bitcast(Float64, xor_int(bitcast(UInt64, x), and_int(bitcast(UInt64, y), 0x8000000000000000))) -flipsign(x::Float32, y::Float32) = bitcast(Float32, xor_int(bitcast(UInt32, x), and_int(bitcast(UInt32, y), 0x80000000))) -flipsign(x::Float32, y::Real) = flipsign(x, Float32(y)) -flipsign(x::Float64, y::Real) = flipsign(x, Float64(y)) - -signbit(x::Float64) = signbit(bitcast(Int64, x)) -signbit(x::Float32) = signbit(bitcast(Int32, x)) -signbit(x::Float16) = signbit(bitcast(Int16, x)) - -maxintfloat(::Type{Float64}) = 9007199254740992. -maxintfloat(::Type{Float32}) = Float32(16777216.) -maxintfloat(::Type{Float16}) = Float16(2048f0) -maxintfloat(x::T) where {T<:AbstractFloat} = maxintfloat(T) -maxintfloat(::Type{S}, ::Type{T}) where {S<:AbstractFloat, T<:Integer} = min(maxintfloat(S), S(typemax(T))) -maxintfloat() = maxintfloat(Float64) - -isinteger(x::AbstractFloat) = (x - trunc(x) == 0) - -num2hex(x::Float16) = hex(bitcast(UInt16, x), 4) -num2hex(x::Float32) = hex(bitcast(UInt32, x), 8) -num2hex(x::Float64) = hex(bitcast(UInt64, x), 16) - -function hex2num(s::AbstractString) - if length(s) <= 4 - return bitcast(Float16, parse(UInt16, s, 16)) - end - if length(s) <= 8 - return bitcast(Float32, parse(UInt32, s, 16)) - end - return bitcast(Float64, parse(UInt64, s, 16)) -end - -""" - round([T,] x, [digits, [base]], [r::RoundingMode]) - -Rounds `x` to an integer value according to the provided -[`RoundingMode`](@ref), returning a value of the same type as `x`. When not -specifying a rounding mode the global mode will be used -(see [`rounding`](@ref)), which by default is round to the nearest integer -([`RoundNearest`](@ref) mode), with ties (fractional values of 0.5) being -rounded to the nearest even integer. - -```jldoctest -julia> round(1.7) -2.0 - -julia> round(1.5) -2.0 - -julia> round(2.5) -2.0 -``` - -The optional [`RoundingMode`](@ref) argument will change how the number gets -rounded. - -`round(T, x, [r::RoundingMode])` converts the result to type `T`, throwing an -[`InexactError`](@ref) if the value is not representable. - -`round(x, digits)` rounds to the specified number of digits after the decimal place (or -before if negative). `round(x, digits, base)` rounds using a base other than 10. - -```jldoctest -julia> round(pi, 2) -3.14 - -julia> round(pi, 3, 2) -3.125 -``` - -!!! note - Rounding to specified digits in bases other than 2 can be inexact when - operating on binary floating point numbers. For example, the [`Float64`](@ref) - value represented by `1.15` is actually *less* than 1.15, yet will be - rounded to 1.2. - - ```jldoctest - julia> x = 1.15 - 1.15 - - julia> @sprintf "%.20f" x - "1.14999999999999991118" - - julia> x < 115//100 - true - - julia> round(x, 1) - 1.2 - ``` -""" -round(T::Type, x) -round(x::Real, ::RoundingMode{:ToZero}) = trunc(x) -round(x::Real, ::RoundingMode{:Up}) = ceil(x) -round(x::Real, ::RoundingMode{:Down}) = floor(x) -# C-style round -function round(x::AbstractFloat, ::RoundingMode{:NearestTiesAway}) - y = trunc(x) - ifelse(x==y,y,trunc(2*x-y)) -end -# Java-style round -function round(x::AbstractFloat, ::RoundingMode{:NearestTiesUp}) - y = floor(x) - ifelse(x==y,y,copysign(floor(2*x-y),x)) -end -round(::Type{T}, x::AbstractFloat, r::RoundingMode) where {T<:Integer} = trunc(T,round(x,r)) - -# adapted from Matlab File Exchange roundsd: http://www.mathworks.com/matlabcentral/fileexchange/26212 -# for round, og is the power of 10 relative to the decimal point -# for signif, og is the absolute power of 10 -# digits and base must be integers, x must be convertable to float - -function _signif_og(x, digits, base) - if base == 10 - e = floor(log10(abs(x)) - digits + 1.) - og = oftype(x, exp10(abs(e))) - elseif base == 2 - e = exponent(abs(x)) - digits + 1. - og = oftype(x, exp2(abs(e))) - else - e = floor(log(base, abs(x)) - digits + 1.) - og = oftype(x, float(base) ^ abs(e)) - end - return og, e -end - -function signif(x::Real, digits::Integer, base::Integer=10) - digits < 1 && throw(DomainError()) - - x = float(x) - (x == 0 || !isfinite(x)) && return x - og, e = _signif_og(x, digits, base) - if e >= 0 # for numeric stability - r = round(x/og)*og - else - r = round(x*og)/og - end - !isfinite(r) ? x : r -end - -for f in (:round, :ceil, :floor, :trunc) - @eval begin - function ($f)(x::Real, digits::Integer, base::Integer=10) - x = float(x) - og = convert(eltype(x),base)^digits - r = ($f)(x * og) / og - - if !isfinite(r) - if digits > 0 - return x - elseif x > 0 - return $(:ceil == f ? :(convert(eltype(x), Inf)) : :(zero(x))) - elseif x < 0 - return $(:floor == f ? :(-convert(eltype(x), Inf)) : :(-zero(x))) - else - return x - end - end - return r - end - end -end - -# isapprox: approximate equality of numbers -""" - isapprox(x, y; rtol::Real=sqrt(eps), atol::Real=0, nans::Bool=false, norm::Function) - -Inexact equality comparison: `true` if `norm(x-y) <= atol + rtol*max(norm(x), norm(y))`. The -default `atol` is zero and the default `rtol` depends on the types of `x` and `y`. The keyword -argument `nans` determines whether or not NaN values are considered equal (defaults to false). - -For real or complex floating-point values, `rtol` defaults to -`sqrt(eps(typeof(real(x-y))))`. This corresponds to requiring equality of about half of the -significand digits. For other types, `rtol` defaults to zero. - -`x` and `y` may also be arrays of numbers, in which case `norm` defaults to `vecnorm` but -may be changed by passing a `norm::Function` keyword argument. (For numbers, `norm` is the -same thing as `abs`.) When `x` and `y` are arrays, if `norm(x-y)` is not finite (i.e. `±Inf` -or `NaN`), the comparison falls back to checking whether all elements of `x` and `y` are -approximately equal component-wise. - -The binary operator `≈` is equivalent to `isapprox` with the default arguments, and `x ≉ y` -is equivalent to `!isapprox(x,y)`. - -```jldoctest -julia> 0.1 ≈ (0.1 - 1e-10) -true - -julia> isapprox(10, 11; atol = 2) -true - -julia> isapprox([10.0^9, 1.0], [10.0^9, 2.0]) -true -``` -""" -function isapprox(x::Number, y::Number; rtol::Real=rtoldefault(x,y), atol::Real=0, nans::Bool=false) - x == y || (isfinite(x) && isfinite(y) && abs(x-y) <= atol + rtol*max(abs(x), abs(y))) || (nans && isnan(x) && isnan(y)) -end - -const ≈ = isapprox -≉(args...; kws...) = !≈(args...; kws...) - -# default tolerance arguments -rtoldefault(::Type{T}) where {T<:AbstractFloat} = sqrt(eps(T)) -rtoldefault(::Type{<:Real}) = 0 -rtoldefault(x::Union{T,Type{T}}, y::Union{S,Type{S}}) where {T<:Number,S<:Number} = max(rtoldefault(real(T)),rtoldefault(real(S))) - -# fused multiply-add -fma_libm(x::Float32, y::Float32, z::Float32) = - ccall(("fmaf", libm_name), Float32, (Float32,Float32,Float32), x, y, z) -fma_libm(x::Float64, y::Float64, z::Float64) = - ccall(("fma", libm_name), Float64, (Float64,Float64,Float64), x, y, z) -fma_llvm(x::Float32, y::Float32, z::Float32) = fma_float(x, y, z) -fma_llvm(x::Float64, y::Float64, z::Float64) = fma_float(x, y, z) -# Disable LLVM's fma if it is incorrect, e.g. because LLVM falls back -# onto a broken system libm; if so, use openlibm's fma instead -# 1.0000305f0 = 1 + 1/2^15 -# 1.0000000009313226 = 1 + 1/2^30 -# If fma_llvm() clobbers the rounding mode, the result of 0.1 + 0.2 will be 0.3 -# instead of the properly-rounded 0.30000000000000004; check after calling fma -if (Sys.ARCH != :i686 && fma_llvm(1.0000305f0, 1.0000305f0, -1.0f0) == 6.103609f-5 && - (fma_llvm(1.0000000009313226, 1.0000000009313226, -1.0) == - 1.8626451500983188e-9) && 0.1 + 0.2 == 0.30000000000000004) - fma(x::Float32, y::Float32, z::Float32) = fma_llvm(x,y,z) - fma(x::Float64, y::Float64, z::Float64) = fma_llvm(x,y,z) -else - fma(x::Float32, y::Float32, z::Float32) = fma_libm(x,y,z) - fma(x::Float64, y::Float64, z::Float64) = fma_libm(x,y,z) -end -function fma(a::Float16, b::Float16, c::Float16) - Float16(fma(Float32(a), Float32(b), Float32(c))) -end - -# This is necessary at least on 32-bit Intel Linux, since fma_llvm may -# have called glibc, and some broken glibc fma implementations don't -# properly restore the rounding mode -Rounding.setrounding_raw(Float32, Rounding.JL_FE_TONEAREST) -Rounding.setrounding_raw(Float64, Rounding.JL_FE_TONEAREST) diff --git a/julia-0.6.3/share/julia/base/generator.jl b/julia-0.6.3/share/julia/base/generator.jl deleted file mode 100644 index d49ed63..0000000 --- a/julia-0.6.3/share/julia/base/generator.jl +++ /dev/null @@ -1,118 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -""" - Generator(f, iter) - -Given a function `f` and an iterator `iter`, construct an iterator that yields -the values of `f` applied to the elements of `iter`. -The syntax `f(x) for x in iter [if cond(x)::Bool]` is syntax for constructing an instance of this -type. The `[if cond(x)::Bool]` expression is optional and acts as a "guard", effectively -filtering out values where the condition is false. - -```jldoctest -julia> g = (abs2(x) for x in 1:5 if x != 3); - -julia> for x in g - println(x) - end -1 -4 -16 -25 - -julia> collect(g) -4-element Array{Int64,1}: - 1 - 4 - 16 - 25 -``` -""" -struct Generator{I,F} - f::F - iter::I -end - -Generator(f, I1, I2, Is...) = Generator(a->f(a...), zip(I1, I2, Is...)) - -Generator(::Type{T}, iter::I) where {T,I} = Generator{I,Type{T}}(T, iter) - -start(g::Generator) = (@_inline_meta; start(g.iter)) -done(g::Generator, s) = (@_inline_meta; done(g.iter, s)) -function next(g::Generator, s) - @_inline_meta - v, s2 = next(g.iter, s) - g.f(v), s2 -end - - -## iterator traits - -abstract type IteratorSize end -struct SizeUnknown <: IteratorSize end -struct HasLength <: IteratorSize end -struct HasShape <: IteratorSize end -struct IsInfinite <: IteratorSize end - -""" - iteratorsize(itertype::Type) -> IteratorSize - -Given the type of an iterator, returns one of the following values: - -* `SizeUnknown()` if the length (number of elements) cannot be determined in advance. -* `HasLength()` if there is a fixed, finite length. -* `HasShape()` if there is a known length plus a notion of multidimensional shape (as for an array). - In this case the [`size`](@ref) function is valid for the iterator. -* `IsInfinite()` if the iterator yields values forever. - -The default value (for iterators that do not define this function) is `HasLength()`. -This means that most iterators are assumed to implement [`length`](@ref). - -This trait is generally used to select between algorithms that pre-allocate space for their -result, and algorithms that resize their result incrementally. - -```jldoctest -julia> Base.iteratorsize(1:5) -Base.HasShape() - -julia> Base.iteratorsize((2,3)) -Base.HasLength() -``` -""" -iteratorsize(x) = iteratorsize(typeof(x)) -iteratorsize(::Type) = HasLength() # HasLength is the default - -abstract type IteratorEltype end -struct EltypeUnknown <: IteratorEltype end -struct HasEltype <: IteratorEltype end - -""" - iteratoreltype(itertype::Type) -> IteratorEltype - -Given the type of an iterator, returns one of the following values: - -* `EltypeUnknown()` if the type of elements yielded by the iterator is not known in advance. -* `HasEltype()` if the element type is known, and [`eltype`](@ref) would return a meaningful value. - -`HasEltype()` is the default, since iterators are assumed to implement [`eltype`](@ref). - -This trait is generally used to select between algorithms that pre-allocate a specific -type of result, and algorithms that pick a result type based on the types of yielded -values. - -```jldoctest -julia> Base.iteratoreltype(1:5) -Base.HasEltype() -``` -""" -iteratoreltype(x) = iteratoreltype(typeof(x)) -iteratoreltype(::Type) = HasEltype() # HasEltype is the default - -iteratorsize(::Type{<:AbstractArray}) = HasShape() -iteratorsize(::Type{Generator{I,F}}) where {I,F} = iteratorsize(I) -length(g::Generator) = length(g.iter) -size(g::Generator) = size(g.iter) -indices(g::Generator) = indices(g.iter) -ndims(g::Generator) = ndims(g.iter) - -iteratoreltype(::Type{Generator{I,T}}) where {I,T} = EltypeUnknown() diff --git a/julia-0.6.3/share/julia/base/gmp.jl b/julia-0.6.3/share/julia/base/gmp.jl deleted file mode 100644 index e8e7d81..0000000 --- a/julia-0.6.3/share/julia/base/gmp.jl +++ /dev/null @@ -1,650 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -module GMP - -export BigInt - -import Base: *, +, -, /, <, <<, >>, >>>, <=, ==, >, >=, ^, (~), (&), (|), xor, - binomial, cmp, convert, div, divrem, factorial, fld, gcd, gcdx, lcm, mod, - ndigits, promote_rule, rem, show, isqrt, string, powermod, - sum, trailing_zeros, trailing_ones, count_ones, base, tryparse_internal, - bin, oct, dec, hex, isequal, invmod, prevpow2, nextpow2, ndigits0z, widen, signed, unsafe_trunc, trunc, - iszero, flipsign, signbit - -if Clong == Int32 - const ClongMax = Union{Int8, Int16, Int32} - const CulongMax = Union{UInt8, UInt16, UInt32} -else - const ClongMax = Union{Int8, Int16, Int32, Int64} - const CulongMax = Union{UInt8, UInt16, UInt32, UInt64} -end -const CdoubleMax = Union{Float16, Float32, Float64} - -gmp_version() = VersionNumber(unsafe_string(unsafe_load(cglobal((:__gmp_version, :libgmp), Ptr{Cchar})))) -gmp_bits_per_limb() = Int(unsafe_load(cglobal((:__gmp_bits_per_limb, :libgmp), Cint))) - -const GMP_VERSION = gmp_version() -const GMP_BITS_PER_LIMB = gmp_bits_per_limb() - -# GMP's mp_limb_t is by default a typedef of `unsigned long`, but can also be configured to be either -# `unsigned int` or `unsigned long long int`. The correct unsigned type is here named Limb, and must -# be used whenever mp_limb_t is in the signature of ccall'ed GMP functions. -if GMP_BITS_PER_LIMB == 32 - const Limb = UInt32 -elseif GMP_BITS_PER_LIMB == 64 - const Limb = UInt64 -else - error("GMP: cannot determine the type mp_limb_t (__gmp_bits_per_limb == $GMP_BITS_PER_LIMB)") -end - -""" - BigInt <: Integer - -Arbitrary precision integer type. -""" -mutable struct BigInt <: Integer - alloc::Cint - size::Cint - d::Ptr{Limb} - function BigInt() - b = new(zero(Cint), zero(Cint), C_NULL) - ccall((:__gmpz_init,:libgmp), Void, (Ptr{BigInt},), &b) - finalizer(b, cglobal((:__gmpz_clear, :libgmp))) - return b - end -end - -const ZERO = BigInt() -const ONE = BigInt() -const _ONE = Limb[1] - -""" - BigInt(x) - -Create an arbitrary precision integer. `x` may be an `Int` (or anything that can be -converted to an `Int`). The usual mathematical operators are defined for this type, and -results are promoted to a [`BigInt`](@ref). - -Instances can be constructed from strings via [`parse`](@ref), or using the `big` -string literal. - -```jldoctest -julia> parse(BigInt, "42") -42 - -julia> big"313" -313 -``` -""" -BigInt(x) - -function __init__() - try - if gmp_version().major != GMP_VERSION.major || gmp_bits_per_limb() != GMP_BITS_PER_LIMB - error(string("The dynamically loaded GMP library (version $(gmp_version()) with __gmp_bits_per_limb == $(gmp_bits_per_limb()))\n", - "does not correspond to the compile time version (version $GMP_VERSION with __gmp_bits_per_limb == $GMP_BITS_PER_LIMB).\n", - "Please rebuild Julia.")) - end - - ccall((:__gmp_set_memory_functions, :libgmp), Void, - (Ptr{Void},Ptr{Void},Ptr{Void}), - cglobal(:jl_gc_counted_malloc), - cglobal(:jl_gc_counted_realloc_with_old_size), - cglobal(:jl_gc_counted_free)) - - ZERO.alloc, ZERO.size, ZERO.d = 0, 0, C_NULL - ONE.alloc, ONE.size, ONE.d = 1, 1, pointer(_ONE) - catch ex - Base.showerror_nostdio(ex, - "WARNING: Error during initialization of module GMP") - end -end - -widen(::Type{Int128}) = BigInt -widen(::Type{UInt128}) = BigInt -widen(::Type{BigInt}) = BigInt - -signed(x::BigInt) = x - -convert(::Type{BigInt}, x::BigInt) = x - -function tryparse_internal(::Type{BigInt}, s::AbstractString, startpos::Int, endpos::Int, base_::Integer, raise::Bool) - _n = Nullable{BigInt}() - - # don't make a copy in the common case where we are parsing a whole String - bstr = startpos == start(s) && endpos == endof(s) ? String(s) : String(SubString(s,startpos,endpos)) - - sgn, base, i = Base.parseint_preamble(true,Int(base_),bstr,start(bstr),endof(bstr)) - if !(2 <= base <= 62) - raise && throw(ArgumentError("invalid base: base must be 2 ≤ base ≤ 62, got $base")) - return _n - end - if i == 0 - raise && throw(ArgumentError("premature end of integer: $(repr(bstr))")) - return _n - end - z = BigInt() - if Base.containsnul(bstr) - err = -1 # embedded NUL char (not handled correctly by GMP) - else - err = ccall((:__gmpz_set_str, :libgmp), - Int32, (Ptr{BigInt}, Ptr{UInt8}, Int32), - &z, pointer(bstr)+(i-start(bstr)), base) - end - if err != 0 - raise && throw(ArgumentError("invalid BigInt: $(repr(bstr))")) - return _n - end - Nullable(flipsign!(z, sgn)) -end - -function convert(::Type{BigInt}, x::Union{Clong,Int32}) - z = BigInt() - ccall((:__gmpz_set_si, :libgmp), Void, (Ptr{BigInt}, Clong), &z, x) - return z -end -function convert(::Type{BigInt}, x::Union{Culong,UInt32}) - z = BigInt() - ccall((:__gmpz_set_ui, :libgmp), Void, (Ptr{BigInt}, Culong), &z, x) - return z -end - -convert(::Type{BigInt}, x::Bool) = BigInt(UInt(x)) - - -function unsafe_trunc(::Type{BigInt}, x::Union{Float32,Float64}) - z = BigInt() - ccall((:__gmpz_set_d, :libgmp), Void, (Ptr{BigInt}, Cdouble), &z, x) - return z -end - -function convert(::Type{BigInt}, x::Union{Float32,Float64}) - isinteger(x) || throw(InexactError()) - unsafe_trunc(BigInt,x) -end - -function trunc(::Type{BigInt}, x::Union{Float32,Float64}) - isfinite(x) || throw(InexactError()) - unsafe_trunc(BigInt,x) -end - -convert(::Type{BigInt}, x::Float16) = BigInt(Float64(x)) -convert(::Type{BigInt}, x::Float32) = BigInt(Float64(x)) - -function convert(::Type{BigInt}, x::Integer) - if x < 0 - if typemin(Clong) <= x - return BigInt(convert(Clong,x)) - end - b = BigInt(0) - shift = 0 - while x < -1 - b += BigInt(~UInt32(x&0xffffffff))<>= 32 - shift += 32 - end - return -b-1 - else - if x <= typemax(Culong) - return BigInt(convert(Culong,x)) - end - b = BigInt(0) - shift = 0 - while x > 0 - b += BigInt(UInt32(x&0xffffffff))<>>= 32 - shift += 32 - end - return b - end -end - - -rem(x::BigInt, ::Type{Bool}) = ((x&1)!=0) -function rem{T<:Union{Unsigned,Signed}}(x::BigInt, ::Type{T}) - u = zero(T) - for l = 1:min(abs(x.size), cld(sizeof(T),sizeof(Limb))) - u += (unsafe_load(x.d,l)%T) << ((sizeof(Limb)<<3)*(l-1)) - end - flipsign(u, x) -end - -rem(x::Integer, ::Type{BigInt}) = convert(BigInt, x) - -function convert(::Type{T}, x::BigInt) where T<:Unsigned - if sizeof(T) < sizeof(Limb) - convert(T, convert(Limb,x)) - else - 0 <= x.size <= cld(sizeof(T),sizeof(Limb)) || throw(InexactError()) - x % T - end -end - -function convert(::Type{T}, x::BigInt) where T<:Signed - n = abs(x.size) - if sizeof(T) < sizeof(Limb) - SLimb = typeof(Signed(one(Limb))) - convert(T, convert(SLimb, x)) - else - 0 <= n <= cld(sizeof(T),sizeof(Limb)) || throw(InexactError()) - y = x % T - ispos(x) ⊻ (y > 0) && throw(InexactError()) # catch overflow - y - end -end - - -function (::Type{Float64})(n::BigInt, ::RoundingMode{:ToZero}) - ccall((:__gmpz_get_d, :libgmp), Float64, (Ptr{BigInt},), &n) -end - -function (::Type{T})(n::BigInt, ::RoundingMode{:ToZero}) where T<:Union{Float16,Float32} - T(Float64(n,RoundToZero),RoundToZero) -end - -function (::Type{T})(n::BigInt, ::RoundingMode{:Down}) where T<:CdoubleMax - x = T(n,RoundToZero) - x > n ? prevfloat(x) : x -end -function (::Type{T})(n::BigInt, ::RoundingMode{:Up}) where T<:CdoubleMax - x = T(n,RoundToZero) - x < n ? nextfloat(x) : x -end - -function (::Type{T})(n::BigInt, ::RoundingMode{:Nearest}) where T<:CdoubleMax - x = T(n,RoundToZero) - if maxintfloat(T) <= abs(x) < T(Inf) - r = n-BigInt(x) - h = eps(x)/2 - if iseven(reinterpret(Unsigned,x)) # check if last bit is odd/even - if r < -h - return prevfloat(x) - elseif r > h - return nextfloat(x) - end - else - if r <= -h - return prevfloat(x) - elseif r >= h - return nextfloat(x) - end - end - end - x -end - -convert(::Type{Float64}, n::BigInt) = Float64(n,RoundNearest) -convert(::Type{Float32}, n::BigInt) = Float32(n,RoundNearest) -convert(::Type{Float16}, n::BigInt) = Float16(n,RoundNearest) - -promote_rule(::Type{BigInt}, ::Type{<:Integer}) = BigInt - -# Binary ops -for (fJ, fC) in ((:+, :add), (:-,:sub), (:*, :mul), - (:fld, :fdiv_q), (:div, :tdiv_q), (:mod, :fdiv_r), (:rem, :tdiv_r), - (:gcd, :gcd), (:lcm, :lcm), - (:&, :and), (:|, :ior), (:xor, :xor)) - @eval begin - function ($fJ)(x::BigInt, y::BigInt) - z = BigInt() - ccall(($(string(:__gmpz_,fC)), :libgmp), Void, (Ptr{BigInt}, Ptr{BigInt}, Ptr{BigInt}), &z, &x, &y) - return z - end - end -end - -/(x::BigInt, y::BigInt) = float(x)/float(y) - -function invmod(x::BigInt, y::BigInt) - z = zero(BigInt) - ya = abs(y) - if ya == 1 - return z - end - if (y==0 || ccall((:__gmpz_invert, :libgmp), Cint, (Ptr{BigInt}, Ptr{BigInt}, Ptr{BigInt}), &z, &x, &ya) == 0) - throw(DomainError()) - end - # GMP always returns a positive inverse; we instead want to - # normalize such that div(z, y) == 0, i.e. we want a negative z - # when y is negative. - if y < 0 - z = z + y - end - # The postcondition is: mod(z * x, y) == mod(big(1), m) && div(z, y) == 0 - return z -end - -# More efficient commutative operations -for (fJ, fC) in ((:+, :add), (:*, :mul), (:&, :and), (:|, :ior), (:xor, :xor)) - @eval begin - function ($fJ)(a::BigInt, b::BigInt, c::BigInt) - z = BigInt() - ccall(($(string(:__gmpz_,fC)), :libgmp), Void, (Ptr{BigInt}, Ptr{BigInt}, Ptr{BigInt}), &z, &a, &b) - ccall(($(string(:__gmpz_,fC)), :libgmp), Void, (Ptr{BigInt}, Ptr{BigInt}, Ptr{BigInt}), &z, &z, &c) - return z - end - function ($fJ)(a::BigInt, b::BigInt, c::BigInt, d::BigInt) - z = BigInt() - ccall(($(string(:__gmpz_,fC)), :libgmp), Void, (Ptr{BigInt}, Ptr{BigInt}, Ptr{BigInt}), &z, &a, &b) - ccall(($(string(:__gmpz_,fC)), :libgmp), Void, (Ptr{BigInt}, Ptr{BigInt}, Ptr{BigInt}), &z, &z, &c) - ccall(($(string(:__gmpz_,fC)), :libgmp), Void, (Ptr{BigInt}, Ptr{BigInt}, Ptr{BigInt}), &z, &z, &d) - return z - end - function ($fJ)(a::BigInt, b::BigInt, c::BigInt, d::BigInt, e::BigInt) - z = BigInt() - ccall(($(string(:__gmpz_,fC)), :libgmp), Void, (Ptr{BigInt}, Ptr{BigInt}, Ptr{BigInt}), &z, &a, &b) - ccall(($(string(:__gmpz_,fC)), :libgmp), Void, (Ptr{BigInt}, Ptr{BigInt}, Ptr{BigInt}), &z, &z, &c) - ccall(($(string(:__gmpz_,fC)), :libgmp), Void, (Ptr{BigInt}, Ptr{BigInt}, Ptr{BigInt}), &z, &z, &d) - ccall(($(string(:__gmpz_,fC)), :libgmp), Void, (Ptr{BigInt}, Ptr{BigInt}, Ptr{BigInt}), &z, &z, &e) - return z - end - end -end - -# Basic arithmetic without promotion -function +(x::BigInt, c::CulongMax) - z = BigInt() - ccall((:__gmpz_add_ui, :libgmp), Void, (Ptr{BigInt}, Ptr{BigInt}, Culong), &z, &x, c) - return z -end -+(c::CulongMax, x::BigInt) = x + c - -function -(x::BigInt, c::CulongMax) - z = BigInt() - ccall((:__gmpz_sub_ui, :libgmp), Void, (Ptr{BigInt}, Ptr{BigInt}, Culong), &z, &x, c) - return z -end -function -(c::CulongMax, x::BigInt) - z = BigInt() - ccall((:__gmpz_ui_sub, :libgmp), Void, (Ptr{BigInt}, Culong, Ptr{BigInt}), &z, c, &x) - return z -end -+(x::BigInt, c::ClongMax) = c < 0 ? -(x, -(c % Culong)) : x + convert(Culong, c) -+(c::ClongMax, x::BigInt) = c < 0 ? -(x, -(c % Culong)) : x + convert(Culong, c) --(x::BigInt, c::ClongMax) = c < 0 ? +(x, -(c % Culong)) : -(x, convert(Culong, c)) --(c::ClongMax, x::BigInt) = c < 0 ? -(x + -(c % Culong)) : -(convert(Culong, c), x) - -function *(x::BigInt, c::CulongMax) - z = BigInt() - ccall((:__gmpz_mul_ui, :libgmp), Void, (Ptr{BigInt}, Ptr{BigInt}, Culong), &z, &x, c) - return z -end -*(c::CulongMax, x::BigInt) = x * c -function *(x::BigInt, c::ClongMax) - z = BigInt() - ccall((:__gmpz_mul_si, :libgmp), Void, (Ptr{BigInt}, Ptr{BigInt}, Clong), &z, &x, c) - return z -end -*(c::ClongMax, x::BigInt) = x * c - -/(x::BigInt, y::Union{ClongMax,CulongMax}) = float(x)/y -/(x::Union{ClongMax,CulongMax}, y::BigInt) = x/float(y) - -# unary ops -for (fJ, fC) in ((:-, :neg), (:~, :com)) - @eval begin - function ($fJ)(x::BigInt) - z = BigInt() - ccall(($(string(:__gmpz_,fC)), :libgmp), Void, (Ptr{BigInt}, Ptr{BigInt}), &z, &x) - return z - end - end -end - -function <<(x::BigInt, c::UInt) - c == 0 && return x - z = BigInt() - ccall((:__gmpz_mul_2exp, :libgmp), Void, (Ptr{BigInt}, Ptr{BigInt}, Culong), &z, &x, c) - return z -end - -function >>(x::BigInt, c::UInt) - c == 0 && return x - z = BigInt() - ccall((:__gmpz_fdiv_q_2exp, :libgmp), Void, (Ptr{BigInt}, Ptr{BigInt}, Culong), &z, &x, c) - return z -end - ->>>(x::BigInt, c::UInt) = x >> c - - -trailing_zeros(x::BigInt) = Int(ccall((:__gmpz_scan1, :libgmp), Culong, (Ptr{BigInt}, Culong), &x, 0)) -trailing_ones(x::BigInt) = Int(ccall((:__gmpz_scan0, :libgmp), Culong, (Ptr{BigInt}, Culong), &x, 0)) - -count_ones(x::BigInt) = Int(ccall((:__gmpz_popcount, :libgmp), Culong, (Ptr{BigInt},), &x)) - -""" - count_ones_abs(x::BigInt) - -Number of ones in the binary representation of abs(x). -""" -count_ones_abs(x::BigInt) = iszero(x) ? 0 : ccall((:__gmpn_popcount, :libgmp), Culong, (Ptr{Limb}, Csize_t), x.d, abs(x.size)) % Int - -function divrem(x::BigInt, y::BigInt) - z1 = BigInt() - z2 = BigInt() - ccall((:__gmpz_tdiv_qr, :libgmp), Void, (Ptr{BigInt}, Ptr{BigInt}, Ptr{BigInt}, Ptr{BigInt}), &z1, &z2, &x, &y) - z1, z2 -end - -function cmp(x::BigInt, y::BigInt) - ccall((:__gmpz_cmp, :libgmp), Int32, (Ptr{BigInt}, Ptr{BigInt}), &x, &y) -end -function cmp(x::BigInt, y::ClongMax) - ccall((:__gmpz_cmp_si, :libgmp), Int32, (Ptr{BigInt}, Clong), &x, y) -end -function cmp(x::BigInt, y::CulongMax) - ccall((:__gmpz_cmp_ui, :libgmp), Int32, (Ptr{BigInt}, Culong), &x, y) -end -cmp(x::BigInt, y::Integer) = cmp(x,big(y)) -cmp(x::Integer, y::BigInt) = -cmp(y,x) - -function cmp(x::BigInt, y::CdoubleMax) - isnan(y) && throw(DomainError()) - ccall((:__gmpz_cmp_d, :libgmp), Int32, (Ptr{BigInt}, Cdouble), &x, y) -end -cmp(x::CdoubleMax, y::BigInt) = -cmp(y,x) - -function isqrt(x::BigInt) - z = BigInt() - ccall((:__gmpz_sqrt, :libgmp), Void, (Ptr{BigInt}, Ptr{BigInt}), &z, &x) - return z -end - -function ^(x::BigInt, y::Culong) - z = BigInt() - ccall((:__gmpz_pow_ui, :libgmp), Void, (Ptr{BigInt}, Ptr{BigInt}, Culong), &z, &x, y) - return z -end - -function bigint_pow(x::BigInt, y::Integer) - if y<0; throw(DomainError()); end - if x== 1; return x; end - if x==-1; return isodd(y) ? x : -x; end - if y>typemax(Culong) - x==0 && return x - - #At this point, x is not 1, 0 or -1 and it is not possible to use - #gmpz_pow_ui to compute the answer. Note that the magnitude of the - #answer is: - #- at least 2^(2^32-1) ≈ 10^(1.3e9) (if Culong === UInt32). - #- at least 2^(2^64-1) ≈ 10^(5.5e18) (if Culong === UInt64). - # - #Assume that the answer will definitely overflow. - - throw(OverflowError()) - end - return x^convert(Culong, y) -end - -^(x::BigInt , y::BigInt ) = bigint_pow(x, y) -^(x::BigInt , y::Bool ) = y ? x : one(x) -^(x::BigInt , y::Integer) = bigint_pow(x, y) -^(x::Integer, y::BigInt ) = bigint_pow(BigInt(x), y) -^(x::Bool , y::BigInt ) = Base.power_by_squaring(x, y) - -function powermod(x::BigInt, p::BigInt, m::BigInt) - r = BigInt() - ccall((:__gmpz_powm, :libgmp), Void, - (Ptr{BigInt}, Ptr{BigInt}, Ptr{BigInt}, Ptr{BigInt}), - &r, &x, &p, &m) - return m < 0 && r > 0 ? r + m : r # choose sign conistent with mod(x^p, m) -end - -powermod(x::Integer, p::Integer, m::BigInt) = powermod(big(x), big(p), m) - -function gcdx(a::BigInt, b::BigInt) - if iszero(b) # shortcut this to ensure consistent results with gcdx(a,b) - return a < 0 ? (-a,-ONE,b) : (a,one(BigInt),b) - # we don't return the globals ONE and ZERO in case the user wants to - # mutate the result - end - g = BigInt() - s = BigInt() - t = BigInt() - ccall((:__gmpz_gcdext, :libgmp), Void, - (Ptr{BigInt}, Ptr{BigInt}, Ptr{BigInt}, Ptr{BigInt}, Ptr{BigInt}), - &g, &s, &t, &a, &b) - if t == 0 - # work around a difference in some versions of GMP - if a == b - return g, t, s - elseif abs(a)==abs(b) - return g, t, -s - end - end - g, s, t -end - -function sum(arr::AbstractArray{BigInt}) - n = BigInt(0) - for i in arr - ccall((:__gmpz_add, :libgmp), Void, - (Ptr{BigInt}, Ptr{BigInt}, Ptr{BigInt}), - &n, &n, &i) - end - return n -end - -function factorial(x::BigInt) - isneg(x) && return BigInt(0) - z = BigInt() - ccall((:__gmpz_fac_ui, :libgmp), Void, (Ptr{BigInt}, Culong), &z, x) - return z -end - -function binomial(n::BigInt, k::UInt) - z = BigInt() - ccall((:__gmpz_bin_ui, :libgmp), Void, (Ptr{BigInt}, Ptr{BigInt}, Culong), &z, &n, k) - return z -end -binomial(n::BigInt, k::Integer) = k < 0 ? BigInt(0) : binomial(n, UInt(k)) - -==(x::BigInt, y::BigInt) = cmp(x,y) == 0 -==(x::BigInt, i::Integer) = cmp(x,i) == 0 -==(i::Integer, x::BigInt) = cmp(x,i) == 0 -==(x::BigInt, f::CdoubleMax) = isnan(f) ? false : cmp(x,f) == 0 -==(f::CdoubleMax, x::BigInt) = isnan(f) ? false : cmp(x,f) == 0 -iszero(x::BigInt) = x.size == 0 - -<=(x::BigInt, y::BigInt) = cmp(x,y) <= 0 -<=(x::BigInt, i::Integer) = cmp(x,i) <= 0 -<=(i::Integer, x::BigInt) = cmp(x,i) >= 0 -<=(x::BigInt, f::CdoubleMax) = isnan(f) ? false : cmp(x,f) <= 0 -<=(f::CdoubleMax, x::BigInt) = isnan(f) ? false : cmp(x,f) >= 0 - -<(x::BigInt, y::BigInt) = cmp(x,y) < 0 -<(x::BigInt, i::Integer) = cmp(x,i) < 0 -<(i::Integer, x::BigInt) = cmp(x,i) > 0 -<(x::BigInt, f::CdoubleMax) = isnan(f) ? false : cmp(x,f) < 0 -<(f::CdoubleMax, x::BigInt) = isnan(f) ? false : cmp(x,f) > 0 -isneg(x::BigInt) = x.size < 0 -ispos(x::BigInt) = x.size > 0 - -signbit(x::BigInt) = isneg(x) -flipsign!(x::BigInt, y::Integer) = (signbit(y) && (x.size = -x.size); x) -flipsign( x::BigInt, y::Integer) = signbit(y) ? -x : x - -string(x::BigInt) = dec(x) -show(io::IO, x::BigInt) = print(io, string(x)) - -bin(n::BigInt) = base( 2, n) -oct(n::BigInt) = base( 8, n) -dec(n::BigInt) = base(10, n) -hex(n::BigInt) = base(16, n) - -bin(n::BigInt, pad::Int) = base( 2, n, pad) -oct(n::BigInt, pad::Int) = base( 8, n, pad) -dec(n::BigInt, pad::Int) = base(10, n, pad) -hex(n::BigInt, pad::Int) = base(16, n, pad) - -function base(b::Integer, n::BigInt, pad::Integer=1) - b < 0 && return base(Int(b), n, pad, (b>0) & (n.size<0)) - 2 <= b <= 62 || throw(ArgumentError("base must be 2 ≤ base ≤ 62, got $b")) - nd1 = ndigits(n, b) - nd = max(nd1, pad) - str = Base._string_n(nd + isneg(n) + 1) # +1 for final '\0' - ptr = pointer(str) - ccall((:__gmpz_get_str,:libgmp), Ptr{UInt8}, (Ptr{UInt8}, Cint, Ref{BigInt}), ptr + nd - nd1, b, n) - for i = (0:nd-nd1-1) + isneg(n) - unsafe_store!(ptr+i, '0' % UInt8) - end - isneg(n) && unsafe_store!(ptr, '-' % UInt8) - str.len -= 1 # final '\0' - iszero(n) && pad < 1 && (str.len -= 1) - str -end - -function ndigits0z(x::BigInt, b::Integer=10) - b < 2 && throw(DomainError()) - if ispow2(b) && 2 <= b <= 62 # GMP assumes b is in this range - Int(ccall((:__gmpz_sizeinbase,:libgmp), Csize_t, (Ptr{BigInt}, Cint), &x, b)) - else - # non-base 2 mpz_sizeinbase might return an answer 1 too big - # use property that log(b, x) < ndigits(x, b) <= log(b, x) + 1 - n = Int(ccall((:__gmpz_sizeinbase,:libgmp), Csize_t, (Ptr{BigInt}, Cint), &x, 2)) - lb = log2(b) # assumed accurate to <1ulp (true for openlibm) - q,r = divrem(n,lb) - iq = Int(q) - maxerr = q*eps(lb) # maximum error in remainder - if r-1.0 < maxerr - abs(x) >= big(b)^iq ? iq+1 : iq - elseif lb-r < maxerr - abs(x) >= big(b)^(iq+1) ? iq+2 : iq+1 - else - iq+1 - end - end -end -ndigits(x::BigInt, b::Integer=10) = iszero(x) ? 1 : ndigits0z(x,b) - -# below, ONE is always left-shifted by at least one digit, so a new BigInt is -# allocated, which can be safely mutated -prevpow2(x::BigInt) = -2 <= x <= 2 ? x : flipsign!(ONE << (ndigits(x, 2) - 1), x) -nextpow2(x::BigInt) = count_ones_abs(x) <= 1 ? x : flipsign!(ONE << ndigits(x, 2), x) - -Base.checked_abs(x::BigInt) = abs(x) -Base.checked_neg(x::BigInt) = -x -Base.checked_add(a::BigInt, b::BigInt) = a + b -Base.checked_sub(a::BigInt, b::BigInt) = a - b -Base.checked_mul(a::BigInt, b::BigInt) = a * b -Base.checked_div(a::BigInt, b::BigInt) = div(a, b) -Base.checked_rem(a::BigInt, b::BigInt) = rem(a, b) -Base.checked_fld(a::BigInt, b::BigInt) = fld(a, b) -Base.checked_mod(a::BigInt, b::BigInt) = mod(a, b) -Base.checked_cld(a::BigInt, b::BigInt) = cld(a, b) -Base.add_with_overflow(a::BigInt, b::BigInt) = a + b, false -Base.sub_with_overflow(a::BigInt, b::BigInt) = a - b, false -Base.mul_with_overflow(a::BigInt, b::BigInt) = a * b, false - -function Base.deepcopy_internal(x::BigInt, stackdict::ObjectIdDict) - if haskey(stackdict, x) - return stackdict[x] - end - y = BigInt() - ccall((:__gmpz_set,:libgmp), Void, (Ptr{BigInt}, Ptr{BigInt}), &y, &x) - stackdict[x] = y - return y -end - -end # module diff --git a/julia-0.6.3/share/julia/base/grisu/bignum.jl b/julia-0.6.3/share/julia/base/grisu/bignum.jl deleted file mode 100644 index 734dbef..0000000 --- a/julia-0.6.3/share/julia/base/grisu/bignum.jl +++ /dev/null @@ -1,256 +0,0 @@ -# This file is a part of Julia, but is derived from -# https://github.com/google/double-conversion which has the following license -# -# Copyright 2006-2014, the V8 project authors. All rights reserved. -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are -# met: -# -# * Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# * Redistributions in binary form must reproduce the above -# copyright notice, this list of conditions and the following -# disclaimer in the documentation and/or other materials provided -# with the distribution. -# * Neither the name of Google Inc. nor the names of its -# contributors may be used to endorse or promote products derived -# from this software without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -function normalizedexponent(significand, exponent::Int32) - significand = UInt64(significand) - while (significand & HiddenBit(Float64)) == 0 - significand <<= UInt64(1) - exponent -= Int32(1) - end - return exponent -end - -function bignumdtoa(v,mode,requested_digits::Int,buffer,bignums) - significand = _significand(v) - exponent = _exponent(v) - lower_boundary_is_closer = lowerboundaryiscloser(v) - need_boundary_deltas = mode == SHORTEST - - is_even = (significand & 1) == 0 - normalized_exponent = normalizedexponent(significand, exponent) - estimated_power = estimatepower(Int(normalized_exponent)) - - if mode == FIXED && -estimated_power - 1 > requested_digits - buffer[1] = 0 - len = 1 - decimal_point = -requested_digits - return true, len, decimal_point - end - num, den, minus, plus = bignums[1], bignums[2], bignums[3], bignums[4] - initialscaledstartvalues!(significand,exponent,lower_boundary_is_closer, - estimated_power,need_boundary_deltas, - num,den,minus,plus) - decimal_point = fixupmultiply10!(estimated_power,is_even,num,den,minus,plus) - if mode == SHORTEST - len = generateshortestdigits!(num,den,minus,plus,is_even,buffer) - elseif mode == FIXED - len, decimal_point = bignumtofixed!(requested_digits,num,den,buffer,decimal_point) - elseif mode == PRECISION - len, decimal_point = generatecounteddigits!(requested_digits,num,den,buffer,decimal_point) - end - buffer[len] = 0 - return true, len, decimal_point -end - -function generateshortestdigits!(num,den,minus,plus,is_even,buffer) - minus == plus && (plus = minus) - len = 1 - while true - digit = Bignums.dividemodulointbignum!(num,den) - buffer[len] = 0x30 + (digit % UInt8) - len += 1 - in_delta_room_minus = is_even ? - Bignums.lessequal(num,minus) : Bignums.less(num,minus) - in_delta_room_plus = is_even ? - Bignums.pluscompare(num,plus,den) >= 0: Bignums.pluscompare(num,plus,den) > 0 - if !in_delta_room_minus && !in_delta_room_plus - Bignums.times10!(num) - Bignums.times10!(minus) - minus != plus && Bignums.times10!(plus) - elseif in_delta_room_minus && in_delta_room_plus - compare = Bignums.pluscompare(num,num,den) - if compare < 0 - elseif compare > 0 - buffer[len - 1] += 1 - else - if (buffer[len - 1] - 0x30) % 2 == 0 - else - buffer[len - 1] += 1 - end - end - return len - elseif in_delta_room_minus - return len - else - buffer[len - 1] += 1 - return len - end - end -end - -function generatecounteddigits!(count,num,den,buffer,decimal_point) - for i = 1:(count-1) - digit = Bignums.dividemodulointbignum!(num,den) - buffer[i] = 0x30 + (digit % UInt8) - Bignums.times10!(num) - end - digit = Bignums.dividemodulointbignum!(num,den) - if Bignums.pluscompare(num,num,den) >= 0 - digit += 1 - end - buffer[count] = 0x30 + (digit % UInt8) - for i = count:-1:2 - buffer[i] != 0x30 + 10 && break - buffer[i] = 0x30 - buffer[i - 1] += 1 - end - if buffer[1] == 0x30 + 10 - buffer[1] = 0x31 - decimal_point += 1 - end - len = count+1 - return len, decimal_point -end - -function bignumtofixed!(requested_digits,num,den,buffer,decimal_point) - if -decimal_point > requested_digits - decimal_point = -requested_digits - len = 1 - return len, decimal_point - elseif -decimal_point == requested_digits - Bignums.times10!(den) - if Bignums.pluscompare(num,num,den) >= 0 - buffer[1] = 0x31 - len = 2 - decimal_point += 1 - else - len = 1 - end - return len, decimal_point - else - needed_digits = decimal_point + requested_digits - len, decimal_point = generatecounteddigits!( - needed_digits,num,den,buffer,decimal_point) - end - return len, decimal_point -end - - -const k1Log10 = 0.30102999566398114 -const kSignificandSize = SignificandSize(Float64) -estimatepower(exponent::Int) = ceil(Int,(exponent + kSignificandSize - 1) * k1Log10 - 1e-10) - -function init3!( - significand,exponent,estimated_power,need_boundary_deltas, - num,den,minus,plus) - Bignums.assignuint64!(num,UInt64(significand)) - Bignums.shiftleft!(num,exponent) - Bignums.assignpoweruint16!(den,UInt16(10),estimated_power) - if need_boundary_deltas - Bignums.shiftleft!(den,1) - Bignums.shiftleft!(num,1) - Bignums.assignuint16!(plus,UInt16(1)) - Bignums.shiftleft!(plus,exponent) - Bignums.assignuint16!(minus,UInt16(1)) - Bignums.shiftleft!(minus,exponent) - else - Bignums.zero!(plus) - Bignums.zero!(minus) - end - return -end - - -function init1!( - significand,exponent,estimated_power,need_boundary_deltas, - num,den,minus,plus) - Bignums.assignuint64!(num,UInt64(significand)) - Bignums.assignpoweruint16!(den,UInt16(10),estimated_power) - Bignums.shiftleft!(den,-exponent) - if need_boundary_deltas - Bignums.shiftleft!(den,1) - Bignums.shiftleft!(num,1) - Bignums.assignuint16!(plus,UInt16(1)) - Bignums.assignuint16!(minus,UInt16(1)) - else - Bignums.zero!(plus) - Bignums.zero!(minus) - end - return -end - -function init2!( - significand,exponent,estimated_power,need_boundary_deltas, - num,den,minus,plus) - power_ten = num - Bignums.assignpoweruint16!(power_ten,UInt16(10),-estimated_power) - if need_boundary_deltas - Bignums.assignbignum!(plus,power_ten) - Bignums.assignbignum!(minus,power_ten) - else - Bignums.zero!(plus) - Bignums.zero!(minus) - end - Bignums.multiplybyuint64!(num,UInt64(significand)) - Bignums.assignuint16!(den,UInt16(1)) - Bignums.shiftleft!(den,-exponent) - if need_boundary_deltas - Bignums.shiftleft!(num,1) - Bignums.shiftleft!(den,1) - end - return -end - -function initialscaledstartvalues!(significand, - exponent,lower_boundary_is_closer,estimated_power, - need_boundary_deltas,num,den,minus,plus) - if exponent >= 0 - init3!(significand, exponent, estimated_power, need_boundary_deltas,num,den,minus,plus) - elseif estimated_power >= 0 - init1!(significand, exponent, estimated_power, need_boundary_deltas,num,den,minus,plus) - else - init2!(significand, exponent, estimated_power, need_boundary_deltas,num,den,minus,plus) - end - if need_boundary_deltas && lower_boundary_is_closer - Bignums.shiftleft!(den,1) - Bignums.shiftleft!(num,1) - Bignums.shiftleft!(plus,1) - end - return -end - -function fixupmultiply10!(estimated_power,is_even,num,den,minus,plus) - in_range = is_even ? Bignums.pluscompare(num,plus,den) >= 0 : - Bignums.pluscompare(num,plus,den) > 0 - if in_range - decimal_point = estimated_power + 1 - else - decimal_point = estimated_power - Bignums.times10!(num) - if minus == plus - Bignums.times10!(minus) - Bignums.assignbignum!(plus,minus) - else - Bignums.times10!(minus) - Bignums.times10!(plus) - end - end - return decimal_point -end diff --git a/julia-0.6.3/share/julia/base/grisu/bignums.jl b/julia-0.6.3/share/julia/base/grisu/bignums.jl deleted file mode 100644 index 7398028..0000000 --- a/julia-0.6.3/share/julia/base/grisu/bignums.jl +++ /dev/null @@ -1,495 +0,0 @@ -# This file is a part of Julia, but is derived from -# https://github.com/google/double-conversion which has the following license -# -# Copyright 2006-2014, the V8 project authors. All rights reserved. -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are -# met: -# -# * Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# * Redistributions in binary form must reproduce the above -# copyright notice, this list of conditions and the following -# disclaimer in the documentation and/or other materials provided -# with the distribution. -# * Neither the name of Google Inc. nor the names of its -# contributors may be used to endorse or promote products derived -# from this software without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -module Bignums - -import Base: ==, < - -export Bignum - -const kMaxSignificantBits = 3584 - -const Chunk = UInt32 -const DoubleChunk = UInt64 - -const kChunkSize = sizeof(Chunk) * 8 -const kDoubleChunkSize = sizeof(DoubleChunk) * 8 -# With bigit size of 28 we loose some bits, but a double still fits easily -# into two chunks, and more importantly we can use the Comba multiplication. -const kBigitSize = 28 -const kBigitMask = Chunk((1 << kBigitSize) - 1) -# Every instance allocates kBigitLength chunks on the stack. Bignums cannot -# grow. There are no checks if the stack-allocated space is sufficient. -const kBigitCapacity = div(kMaxSignificantBits, kBigitSize) - -mutable struct Bignum - bigits::Vector{UInt32} - used_digits::Int32 - exponent::Int32 - function Bignum() - bigits = Vector{UInt32}(kBigitCapacity) - @inbounds for i = 1:kBigitCapacity - bigits[i] = 0 - end - new(bigits,0,0) - end -end - -==(a::Bignum,b::Bignum) = compare(a,b) == 0 -<(a::Bignum,b::Bignum) = compare(a,b) < 0 - -times10!(x::Bignum) = multiplybyuint32!(x,UInt32(10)) - -plusequal(a,b,c) = pluscompare(a,b,c) == 0 -pluslessequal(a,b,c) = pluscompare(a,b,c) <= 0 -plusless(a,b,c) = pluscompare(a,b,c) < 0 -lessequal(a::Bignum,b::Bignum) = compare(a,b) <= 0 -less(a::Bignum,b::Bignum) = compare(a,b) < 0 - -bigitlength(x::Bignum) = x.used_digits + x.exponent - -bitsize(value) = 8 * sizeof(value) - -function zero!(x::Bignum) - for i = 1:x.used_digits - @inbounds x.bigits[i] = 0 - end - x.used_digits = 0 - x.exponent = 0 - return -end - -function clamp!(x::Bignum) - @inbounds while (x.used_digits > 0 && x.bigits[x.used_digits] == 0) - x.used_digits -= 1 - end - x.used_digits == 0 && (x.exponent = 0) - return -end - -isclamped(x::Bignum) = x.used_digits == 0 || x.bigits[x.used_digits] != 0 - -function align!(x::Bignum,other::Bignum) - @inbounds if x.exponent > other.exponent - zero_digits = x.exponent - other.exponent - for i = x.used_digits:-1:1 - x.bigits[i + zero_digits] = x.bigits[i] - end - for i = 1:zero_digits - x.bigits[i] = 0 - end - x.used_digits += zero_digits - x.exponent -= zero_digits - end - return -end - -function bigitshiftleft!(x::Bignum,shift_amount) - carry::UInt32 = 0 - @inbounds begin - for i = 1:x.used_digits - new_carry::Chunk = x.bigits[i] >> (kBigitSize - shift_amount) - x.bigits[i] = ((x.bigits[i] << shift_amount) + carry) & kBigitMask - carry = new_carry - end - if carry != 0 - x.bigits[x.used_digits+1] = carry - x.used_digits += 1 - end - end - return -end - -function subtracttimes!(x::Bignum,other::Bignum,factor) - if factor < 3 - for i = 1:factor - subtractbignum!(x,other) - end - return - end - borrow::Chunk = 0 - exponent_diff = other.exponent - x.exponent - @inbounds begin - for i = 1:other.used_digits - product::DoubleChunk = DoubleChunk(factor) * other.bigits[i] - remove::DoubleChunk = borrow + product - difference::Chunk = (x.bigits[i+exponent_diff] - (remove & kBigitMask)) % Chunk - x.bigits[i+exponent_diff] = difference & kBigitMask - borrow = ((difference >> (kChunkSize - 1)) + (remove >> kBigitSize)) % Chunk - end - for i = (other.used_digits + exponent_diff + 1):x.used_digits - borrow == 0 && return - difference::Chunk = x.bigits[i] - borrow - x.bigits[i] = difference & kBigitMask - borrow = difference >> (kChunkSize - 1) - end - end - clamp!(x) -end - -function assignuint16!(x::Bignum,value::UInt16) - zero!(x) - value == 0 && return - x.bigits[1] = value - x.used_digits = 1 - return -end - -const kUInt64Size = 64 -function assignuint64!(x::Bignum,value::UInt64) - zero!(x) - value == 0 && return - needed_bigits = div(kUInt64Size,kBigitSize) + 1 - @inbounds for i = 1:needed_bigits - x.bigits[i] = value & kBigitMask - value >>= kBigitSize - end - x.used_digits = needed_bigits - clamp!(x) -end - -function assignbignum!(x::Bignum,other::Bignum) - x.exponent = other.exponent - @inbounds begin - for i = 1:other.used_digits - x.bigits[i] = other.bigits[i] - end - for i = (other.used_digits+1):x.used_digits - x.bigits[i] = 0 - end - end - x.used_digits = other.used_digits - return -end - -function adduint64!(x::Bignum,operand::UInt64) - operand == 0 && return - other = Bignum() - assignuint64!(other,operand) - addbignum!(x,other) -end - -function addbignum!(x::Bignum,other::Bignum) - align!(x,other) - carry::Chunk = 0 - bigit_pos = other.exponent - x.exponent - @inbounds for i = 1:other.used_digits - sum::Chunk = x.bigits[bigit_pos+1] + other.bigits[i] + carry - x.bigits[bigit_pos+1] = sum & kBigitMask - carry = sum >> kBigitSize - bigit_pos += 1 - end - @inbounds while carry != 0 - sum = x.bigits[bigit_pos+1] + carry - x.bigits[bigit_pos+1] = sum & kBigitMask - carry = sum >> kBigitSize - bigit_pos += 1 - end - x.used_digits = max(bigit_pos,x.used_digits) - return -end - -function subtractbignum!(x::Bignum,other::Bignum) - align!(x,other) - offset = other.exponent - x.exponent - borrow = Chunk(0) - @inbounds begin - for i = 1:other.used_digits - difference = x.bigits[i+offset] - other.bigits[i] - borrow - x.bigits[i+offset] = difference & kBigitMask - borrow = difference >> (kChunkSize - 1) - end - i = other.used_digits+1 - while borrow != 0 - difference = x.bigits[i+offset] - borrow - x.bigits[i+offset] = difference & kBigitMask - borrow = difference >> (kChunkSize - 1) - i += 1 - end - end - clamp!(x) -end - -function shiftleft!(x::Bignum,shift_amount) - x.used_digits == 0 && return - x.exponent += div(shift_amount,kBigitSize) - local_shift = shift_amount % kBigitSize - bigitshiftleft!(x,local_shift) -end - -function multiplybyuint32!(x::Bignum,factor::UInt32) - factor == 1 && return - if factor == 0 - zero!(x) - return - end - x.used_digits == 0 && return - carry::DoubleChunk = 0 - @inbounds begin - for i = 1:x.used_digits - product::DoubleChunk = (factor % DoubleChunk) * x.bigits[i] + carry - x.bigits[i] = (product & kBigitMask) % Chunk - carry = product >> kBigitSize - end - while carry != 0 - x.bigits[x.used_digits+1] = carry & kBigitMask - x.used_digits += 1 - carry >>= kBigitSize - end - end - return -end - -function multiplybyuint64!(x::Bignum,factor::UInt64) - factor == 1 && return - if factor == 0 - zero!(x) - return - end - carry::UInt64 = 0 - low::UInt64 = factor & 0xFFFFFFFF - high::UInt64 = factor >> 32 - @inbounds begin - for i = 1:x.used_digits - product_low::UInt64 = low * x.bigits[i] - product_high::UInt64 = high * x.bigits[i] - tmp::UInt64 = (carry & kBigitMask) + product_low - x.bigits[i] = tmp & kBigitMask - carry = (carry >> kBigitSize) + (tmp >> kBigitSize) + - (product_high << (32 - kBigitSize)) - end - while carry != 0 - x.bigits[x.used_digits+1] = carry & kBigitMask - x.used_digits += 1 - carry >>= kBigitSize - end - end - return -end - -const kFive27 = UInt64(0x6765c793fa10079d) -const kFive1 = UInt16(5) -const kFive2 = UInt16(kFive1 * 5) -const kFive3 = UInt16(kFive2 * 5) -const kFive4 = UInt16(kFive3 * 5) -const kFive5 = UInt16(kFive4 * 5) -const kFive6 = UInt16(kFive5 * 5) -const kFive7 = UInt32(kFive6 * 5) -const kFive8 = UInt32(kFive7 * 5) -const kFive9 = UInt32(kFive8 * 5) -const kFive10 = UInt32(kFive9 * 5) -const kFive11 = UInt32(kFive10 * 5) -const kFive12 = UInt32(kFive11 * 5) -const kFive13 = UInt32(kFive12 * 5) -const kFive1_to_12 = UInt32[kFive1, kFive2, kFive3, kFive4, kFive5, kFive6, - kFive7, kFive8, kFive9, kFive10, kFive11, kFive12] -function multiplybypoweroften!(x::Bignum,exponent) - exponent == 0 && return - x.used_digits == 0 && return - remaining_exponent = exponent - while remaining_exponent >= 27 - multiplybyuint64!(x,kFive27) - remaining_exponent -= 27 - end - while remaining_exponent >= 13 - multiplybyuint32!(x,kFive13) - remaining_exponent -= 13 - end - remaining_exponent > 0 && multiplybyuint32!(x, - kFive1_to_12[remaining_exponent]) - shiftleft!(x,exponent) -end - -function square!(x::Bignum) - product_length = 2 * x.used_digits - (1 << (2 * (kChunkSize - kBigitSize))) <= x.used_digits && error("unimplemented") - accumulator::DoubleChunk = 0 - copy_offset = x.used_digits - @inbounds begin - for i = 1:x.used_digits - x.bigits[copy_offset + i] = x.bigits[i] - end - for i = 1:x.used_digits - bigit_index1 = i-1 - bigit_index2 = 0 - while bigit_index1 >= 0 - chunk1::Chunk = x.bigits[copy_offset + bigit_index1 + 1] - chunk2::Chunk = x.bigits[copy_offset + bigit_index2 + 1] - accumulator += (chunk1 % DoubleChunk) * chunk2 - bigit_index1 -= 1 - bigit_index2 += 1 - end - x.bigits[i] = (accumulator % Chunk) & kBigitMask - accumulator >>= kBigitSize - end - for i = x.used_digits+1:product_length - bigit_index1 = x.used_digits - 1 - bigit_index2 = i - bigit_index1 - 1 - while bigit_index2 < x.used_digits - chunk1::Chunk = x.bigits[copy_offset + bigit_index1 + 1] - chunk2::Chunk = x.bigits[copy_offset + bigit_index2 + 1] - accumulator += (chunk1 % DoubleChunk) * chunk2 - bigit_index1 -= 1 - bigit_index2 += 1 - end - x.bigits[i] = (accumulator % Chunk) & kBigitMask - accumulator >>= kBigitSize - end - end - x.used_digits = product_length - x.exponent *= 2 - clamp!(x) -end - -function assignpoweruint16!(x::Bignum,base::UInt16,power_exponent::Int) - if power_exponent == 0 - assignuint16!(x,UInt16(1)) - return - end - zero!(x) - shifts::Int = 0 - while base & UInt16(1) == UInt16(0) - base >>= UInt16(1) - shifts += 1 - end - bit_size::Int = 0 - tmp_base::Int= base - while tmp_base != 0 - tmp_base >>= 1 - bit_size += 1 - end - final_size = bit_size * power_exponent - mask::Int = 1 - while power_exponent >= mask - mask <<= 1 - end - mask >>= 2 - this_value::UInt64 = base - delayed_multiplication = false - max_32bits::UInt64 = 0xFFFFFFFF - while mask != 0 && this_value <= max_32bits - this_value *= this_value - if (power_exponent & mask) != 0 - base_bits_mask::UInt64 = ~(UInt64(1) << (64 - bit_size) - 1) - high_bits_zero = (this_value & base_bits_mask) == 0 - if high_bits_zero - this_value *= base - else - delayed_multiplication = true - end - end - mask >>= 1 - end - assignuint64!(x,this_value) - delayed_multiplication && multiplybyuint32!(x,UInt32(base)) - while mask != 0 - square!(x) - (power_exponent & mask) != 0 && multiplybyuint32!(x,UInt32(base)) - mask >>= 1 - end - shiftleft!(x,shifts * power_exponent) -end - -function dividemodulointbignum!(x::Bignum,other::Bignum) - bigitlength(x) < bigitlength(other) && return UInt16(0) - align!(x,other) - result::UInt16 = 0 - @inbounds begin - while bigitlength(x) > bigitlength(other) - result += x.bigits[x.used_digits] % UInt16 - subtracttimes!(x,other,x.bigits[x.used_digits]) - end - this_bigit::Chunk = x.bigits[x.used_digits] - other_bigit::Chunk = other.bigits[other.used_digits] - if other.used_digits == 1 - quotient = reinterpret(Int32,div(this_bigit,other_bigit)) - x.bigits[x.used_digits] = this_bigit - other_bigit * reinterpret(UInt32,quotient) - result += quotient % UInt16 - clamp!(x) - return result - end - end - division_estimate = reinterpret(Int32,div(this_bigit,other_bigit+Chunk(1))) - result += division_estimate % UInt16 - subtracttimes!(x,other,division_estimate) - other_bigit * (division_estimate+1) > this_bigit && return result - while lessequal(other, x) - subtractbignum!(x,other) - result += UInt16(1) - end - return result -end - -function pluscompare(a::Bignum,b::Bignum,c::Bignum) - bigitlength(a) < bigitlength(b) && return pluscompare(b,a,c) - bigitlength(a) + 1 < bigitlength(c) && return -1 - bigitlength(a) > bigitlength(c) && return 1 - a.exponent >= bigitlength(b) && bigitlength(a) < bigitlength(c) && return -1 - borrow::Chunk = 0 - min_exponent = min(a.exponent,b.exponent,c.exponent) - for i = (bigitlength(c)-1):-1:min_exponent - chunk_a::Chunk = bigitat(a,i) - chunk_b::Chunk = bigitat(b,i) - chunk_c::Chunk = bigitat(c,i) - sum::Chunk = chunk_a + chunk_b - if sum > chunk_c + borrow - return 1 - else - borrow = chunk_c + borrow - sum - borrow > 1 && return -1 - borrow <<= kBigitSize - end - end - borrow == 0 && return 0 - return -1 -end - -function compare(a::Bignum,b::Bignum) - bigit_length_a = bigitlength(a) - bigit_length_b = bigitlength(b) - bigit_length_a < bigit_length_b && return -1 - bigit_length_a > bigit_length_b && return 1 - for i = (bigit_length_a-1):-1:min(a.exponent,b.exponent) - bigit_a::Chunk = bigitat(a,i) - bigit_b::Chunk = bigitat(b,i) - bigit_a < bigit_b && return -1 - bigit_a > bigit_b && return 1 - end - return 0 -end - -function bigitat(x::Bignum,index) - index >= bigitlength(x) && return Chunk(0) - index < x.exponent && return Chunk(0) - @inbounds ret = x.bigits[index - x.exponent+1]::Chunk - return ret -end - -end # module diff --git a/julia-0.6.3/share/julia/base/grisu/fastfixed.jl b/julia-0.6.3/share/julia/base/grisu/fastfixed.jl deleted file mode 100644 index 014806b..0000000 --- a/julia-0.6.3/share/julia/base/grisu/fastfixed.jl +++ /dev/null @@ -1,252 +0,0 @@ -# This file is a part of Julia, but is derived from -# https://github.com/google/double-conversion which has the following license -# -# Copyright 2006-2014, the V8 project authors. All rights reserved. -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are -# met: -# -# * Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# * Redistributions in binary form must reproduce the above -# copyright notice, this list of conditions and the following -# disclaimer in the documentation and/or other materials provided -# with the distribution. -# * Neither the name of Google Inc. nor the names of its -# contributors may be used to endorse or promote products derived -# from this software without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -const kDoubleSignificandSize = 53 - -function filldigits32fixedlength(n1,requested_len,buffer,len) - for i = (requested_len-1):-1:0 - buffer[len+i] = 0x30 + n1 % 10 - n1 = div(n1,10) - end - return len + requested_len -end - -function filldigits32(n,buffer,len) - n_len = 0 - while n != 0 - digit = n % 10 - n = div(n,10) - buffer[len+n_len] = 0x30 + digit - n_len += 1 - end - i,j = len, len + n_len - 1 - while i < j - buffer[i], buffer[j] = buffer[j], buffer[i] - i += 1 - j -= 1 - end - return len + n_len -end - -function filldigits64fixedlength(n2,buffer,len) - kTen7 = 10000000 - part2 = n2 % kTen7 - n2 = div(n2,kTen7) - part0, part1 = divrem(n2,kTen7) - len = filldigits32fixedlength(part0, 3, buffer, len) - len = filldigits32fixedlength(part1, 7, buffer, len) - len = filldigits32fixedlength(part2, 7, buffer, len) - return len -end - -function filldigits64(n3,buffer,len) - kTen7 = 10000000 - part2 = n3 % kTen7 - n3 = div(n3,kTen7) - part0, part1 = divrem(n3,kTen7) - if part0 != 0 - len = filldigits32(part0, buffer, len) - len = filldigits32fixedlength(part1, 7, buffer, len) - len = filldigits32fixedlength(part2, 7, buffer, len) - elseif part1 != 0 - len = filldigits32(part1, buffer, len) - len = filldigits32fixedlength(part2, 7, buffer, len) - else - len = filldigits32(part2, buffer, len) - end - return len -end - -function roundup(buffer, len, decimal_point) - if len == 1 - buffer[1] = 0x31 - decimal_point = 1 - len = 2 - return len, decimal_point - end - buffer[len - 1] += 1 - for i = (len-1):-1:2 - buffer[i] != 0x30 + 10 && return len, decimal_point - buffer[i] = 0x30 - buffer[i - 1] += 1 - end - if buffer[1] == 0x30 + 10 - buffer[1] = 0x31 - decimal_point += 1 - end - return len, decimal_point -end - -function fillfractionals(fractionals, exponent, - fractional_count, buffer, - len, decimal_point) - if -exponent <= 64 - point = -exponent - for i = 1:fractional_count - fractionals == 0 && break - fractionals *= 5 - point -= 1 - digit = fractionals >> point - buffer[len] = 0x30 + digit - len += 1 - fractionals -= UInt64(digit) << point - end - if ((fractionals >> (point - 1)) & 1) == 1 - len, decimal_point = roundup(buffer, len, decimal_point) - end - else - fract128 = UInt128(fractionals) << 64 - fract128 = shift(fract128,-exponent - 64) - point = 128 - for i = 1:fractional_count - fract128 == 0 && break - fract128 *= 5 - point -= 1 - digit, fract128 = divrem2(fract128,point) - buffer[len] = 0x30 + digit - len += 1 - end - if bitat(fract128,point - 1) == 1 - len, decimal_point = roundup(buffer, len, decimal_point) - end - end - return len, decimal_point -end - -low(x) = UInt64(x&0xffffffffffffffff) -high(x) = UInt64(x >>> 64) -bitat(x::UInt128,y) = y >= 64 ? (Int32(high(x) >> (y-64)) & 1) : (Int32(low(x) >> y) & 1) -function divrem2(x,power) - h = high(x) - l = low(x) - if power >= 64 - result = Int32(h >> (power - 64)) - h -= UInt64(result) << (power - 64) - return result, (UInt128(h) << 64) + l - else - part_low::UInt64 = l >> power - part_high::UInt64 = h << (64 - power) - result = Int32(part_low + part_high) - return result, UInt128(l - (part_low << power)) - end -end -function shift(x::UInt128,amt) - if amt == 0 - return x - elseif amt == -64 - return x << 64 - elseif amt == 64 - return x >> 64 - elseif amt <= 0 - h = high(x); l = low(x) - h <<= -amt - h += l >> (64 + amt) - l <<= -amt - return (UInt128(h) << 64) + l - else - h = high(x); l = low(x) - l >>= amt - l += h << (64 - amt) - h >>= amt - return (UInt128(h) << 64) + l - end -end - -function trimzeros(buffer, len, decimal_point) - while len > 1 && buffer[len - 1] == 0x30 - len -= 1 - end - first_non_zero::Int32 = 1 - while first_non_zero < len && buffer[first_non_zero] == 0x30 - first_non_zero += 1 - end - if first_non_zero != 1 - for i = first_non_zero:(len-1) - buffer[i - first_non_zero + 1] = buffer[i] - end - len -= first_non_zero-1 - decimal_point -= first_non_zero-1 - end - return len, decimal_point -end - -function fastfixedtoa(v,mode,fractional_count,buffer) - v = Float64(v) - significand::UInt64 = _significand(v) - exponent = _exponent(v) - exponent > 20 && return false, 0, 0 - fractional_count > 20 && return false, 0, 0 - len = 1 - if exponent + kDoubleSignificandSize > 64 - kFive17 = divisor = Int64(5)^17 - divisor_power = 17 - dividend = significand - if exponent > divisor_power - dividend <<= exponent - divisor_power - quotient = div(dividend,divisor) - remainder = (dividend % divisor) << divisor_power - else - divisor <<= divisor_power - exponent - quotient = div(dividend,divisor) - remainder = (dividend % divisor) << exponent - end - len = filldigits32(quotient, buffer, len) - len = filldigits64fixedlength(remainder, buffer, len) - decimal_point = len-1 - elseif exponent >= 0 - significand <<= exponent - len = filldigits64(significand, buffer, len) - decimal_point = len-1 - elseif exponent > -kDoubleSignificandSize - integrals = significand >> -exponent - fractionals = significand - (integrals << -exponent) - if integrals > 0xFFFFFFFF - len = filldigits64(integrals,buffer,len) - else - len = filldigits32(integrals%UInt32,buffer,len) - end - decimal_point = len-1 - len, decimal_point = fillfractionals(fractionals,exponent,fractional_count, - buffer,len, decimal_point) - elseif exponent < -128 - len = 1 - decimal_point = -fractional_count - else - decimal_point = 0 - len, decimal_point = fillfractionals(significand,exponent,fractional_count, - buffer,len, decimal_point) - end - len, decimal_point = trimzeros(buffer,len,decimal_point) - buffer[len] = 0 - if (len-1) == 0 - decimal_point = -fractional_count - end - return true, len, decimal_point -end diff --git a/julia-0.6.3/share/julia/base/grisu/fastprecision.jl b/julia-0.6.3/share/julia/base/grisu/fastprecision.jl deleted file mode 100644 index 3d737b1..0000000 --- a/julia-0.6.3/share/julia/base/grisu/fastprecision.jl +++ /dev/null @@ -1,99 +0,0 @@ -# This file is a part of Julia, but is derived from -# https://github.com/google/double-conversion which has the following license -# -# Copyright 2006-2014, the V8 project authors. All rights reserved. -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are -# met: -# -# * Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# * Redistributions in binary form must reproduce the above -# copyright notice, this list of conditions and the following -# disclaimer in the documentation and/or other materials provided -# with the distribution. -# * Neither the name of Google Inc. nor the names of its -# contributors may be used to endorse or promote products derived -# from this software without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -function roundweed(buffer,len,rest,tk,unit,kappa) - unit >= tk && return false, kappa - tk - unit <= unit && return false, kappa - tk - rest > rest && (tk - 2 * rest >= 2 * unit) && return true, kappa - if rest > unit && (tk - (rest - unit) <= (rest - unit)) - buffer[len-1] += 1 - for i = (len-1):-1:2 - buffer[i] != 0x30 + 10 && break - buffer[i] = 0x30 - buffer[i-1] += 1 - end - if buffer[1] == 0x30 + 10 - buffer[1] = 0x31 - kappa += 1 - end - return true, kappa - end - return false, kappa -end - -function digitgen(w,buffer,requested_digits=1000) - unit::UInt64 = 1 - one = Float(unit << -w.e, w.e) - integrals = w.s >> -one.e - fractionals = w.s & (one.s-1) - divisor, kappa = bigpowten(integrals, 64 + one.e) - len = 1 - rest = 0 - while kappa > 0 - digit = div(integrals,divisor) - buffer[len] = 0x30 + digit - len += 1 - requested_digits -= 1 - integrals %= divisor - kappa -= 1 - if requested_digits == 0 - rest = (UInt64(integrals) << -one.e) + fractionals - r, kappa = roundweed(buffer, len, rest, UInt64(divisor) << -one.e, - unit,kappa) - return r, kappa, len - end - divisor = div(divisor,10) - end - while requested_digits > 0 && fractionals > unit - fractionals *= 10 - unit *= 10 - digit = fractionals >> -one.e - buffer[len] = 0x30 + digit - len += 1 - requested_digits -= 1 - fractionals &= one.s - 1 - kappa -= 1 - end - requested_digits != 0 && return false, kappa, len - r, kappa = roundweed(buffer,len,fractionals,one.s, - unit,kappa) - return r, kappa, len -end - -function fastprecision(v, requested_digits, buffer = Vector{UInt8}(100)) - f = normalize(Float64(v)) - ten_mk_min_exp = kMinExp - (f.e + FloatSignificandSize) - ten_mk_max_exp = kMaxExp - (f.e + FloatSignificandSize) - cp = binexp_cache(ten_mk_min_exp,ten_mk_max_exp) - scaled_w = f * cp - r, kappa, len = digitgen(scaled_w,buffer,requested_digits) - decimal_exponent = -cp.de + kappa - return r, len, decimal_exponent+len-1 -end diff --git a/julia-0.6.3/share/julia/base/grisu/fastshortest.jl b/julia-0.6.3/share/julia/base/grisu/fastshortest.jl deleted file mode 100644 index f9009a7..0000000 --- a/julia-0.6.3/share/julia/base/grisu/fastshortest.jl +++ /dev/null @@ -1,118 +0,0 @@ -# This file is a part of Julia, but is derived from -# https://github.com/google/double-conversion which has the following license -# -# Copyright 2006-2014, the V8 project authors. All rights reserved. -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are -# met: -# -# * Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# * Redistributions in binary form must reproduce the above -# copyright notice, this list of conditions and the following -# disclaimer in the documentation and/or other materials provided -# with the distribution. -# * Neither the name of Google Inc. nor the names of its -# contributors may be used to endorse or promote products derived -# from this software without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -const kMinExp = -60 -const kMaxExp = -32 - -function roundweed(buffer,len,rest,tk,unit,kappa,too_high::UInt64,unsafe_interval::UInt64) - small = too_high - unit - big = too_high + unit - while rest < small && - unsafe_interval - rest >= tk && - (rest + tk < small || - small - rest >= rest + tk - small) - buffer[len-1] -= 1 - rest += tk - end - if rest < big && - unsafe_interval - rest >= tk && - (rest + tk < big || - big - rest > rest + tk - big) - return false, kappa - end - return (2 * unit <= rest) && (rest <= unsafe_interval - 4 * unit), kappa -end - -const SmallPowersOfTen = [ - 0, 1, 10, 100, 1000, 10000, 100000, - 1000000, 10000000, 100000000, 1000000000] - -function bigpowten(n,n_bits) - guess = (n_bits + 1) * 1233 >> 12 - guess += 1 - i = SmallPowersOfTen[guess+1] - return n < i ? (SmallPowersOfTen[guess], guess-1) : (i,guess) -end - -function digitgen(low,w,high,buffer) - unit::UInt64 = 1 - one = Float(unit << -w.e, w.e) - too_high = Float(high.s+unit,high.e) - unsafe_interval = too_high - Float(low.s-unit,low.e) - integrals = too_high.s >> -one.e - fractionals = too_high.s & (one.s-1) - divisor, kappa = bigpowten(integrals, 64 + one.e) - len = 1 - rest = UInt64(0) - while kappa > 0 - digit = div(integrals,divisor) - buffer[len] = 0x30 + digit - len += 1 - integrals %= divisor - kappa -= 1 - rest = (UInt64(integrals) << -one.e) + fractionals - if rest < unsafe_interval.s - r, kappa = roundweed(buffer, len, rest, UInt64(divisor) << -one.e, - unit,kappa,(too_high - w).s,unsafe_interval.s) - return r, kappa, len - end - divisor = div(divisor,10) - end - while true - fractionals *= 10 - unit *= 10 - unsafe_interval = Float(unsafe_interval.s*10,unsafe_interval.e) - digit = fractionals >> -one.e - buffer[len] = 0x30 + digit - len += 1 - fractionals &= one.s - 1 - kappa -= 1 - if fractionals < unsafe_interval.s - r, kappa = roundweed(buffer,len,fractionals,one.s, - unit,kappa,(too_high - w).s*unit,unsafe_interval.s) - return r, kappa, len - end - end -end - -function fastshortest(v, buffer = Vector{UInt8}(17)) - f = normalize(Float64(v)) - bound_minus, bound_plus = normalizedbound(v) - ten_mk_min_exp = kMinExp - (f.e + FloatSignificandSize) - ten_mk_max_exp = kMaxExp - (f.e + FloatSignificandSize) - cp = binexp_cache(ten_mk_min_exp,ten_mk_max_exp) - scaled_w = f * cp - scaled_bound_minus = bound_minus * cp - scaled_bound_plus = bound_plus * cp - r, kappa, len = digitgen(scaled_bound_minus,scaled_w, - scaled_bound_plus,buffer) - decimal_exponent = -cp.de + kappa - return r, len, decimal_exponent+len-1 -end diff --git a/julia-0.6.3/share/julia/base/grisu/float.jl b/julia-0.6.3/share/julia/base/grisu/float.jl deleted file mode 100644 index 2adec17..0000000 --- a/julia-0.6.3/share/julia/base/grisu/float.jl +++ /dev/null @@ -1,256 +0,0 @@ -# This file is a part of Julia, but is derived from -# https://github.com/google/double-conversion which has the following license -# -# Copyright 2006-2014, the V8 project authors. All rights reserved. -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are -# met: -# -# * Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# * Redistributions in binary form must reproduce the above -# copyright notice, this list of conditions and the following -# disclaimer in the documentation and/or other materials provided -# with the distribution. -# * Neither the name of Google Inc. nor the names of its -# contributors may be used to endorse or promote products derived -# from this software without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -struct Float - s::UInt64 - e::Int32 - de::Int32 -end - -Float() = Float(0,0,0) -Float(x,y) = Float(x,y,Int32(0)) -Float(d::AbstractFloat) = Float(_significand(d), _exponent(d)) - -# Consts -const Float10MSBits = 0xFFC0000000000000 # used normalize(Float) -const FloatSignMask = 0x8000000000000000 # used in normalize(Float) -const FloatSignificandSize = Int32(64) - -function normalize(v::Float) - f = v.s - e::Int32 = v.e - while (f & Float10MSBits) == 0 - f <<= 10 - e -= 10 - end - while (f & FloatSignMask) == 0 - f <<= 1 - e -= 1 - end - return Float(f,e) -end -function normalize(v::Float64) - s = _significand(v); e = _exponent(v) - while (s & HiddenBit(Float64)) == 0 - s <<= UInt64(1) - e -= Int32(1) - end - s <<= UInt64(FloatSignificandSize - SignificandSize(Float64)) - e -= Int32( FloatSignificandSize - SignificandSize(Float64)) - return Float(s, e) -end - -# Float128 -#DenormalExponent(::Type{Float128}) = Int32(-ExponentBias(Float128) + 1) -#ExponentMask(::Type{Float128}) = 0x7fff0000000000000000000000000000 -#PhysicalSignificandSize(::Type{Float128}) = Int32(112) -#SignificandSize(::Type{Float128}) = Int32(113) -#ExponentBias(::Type{Float128}) = Int32(0x00003fff + PhysicalSignificandSize(Float128)) -#SignificandMask(::Type{Float128}) = 0x0000ffffffffffffffffffffffffffff -#HiddenBit(::Type{Float128}) = 0x00010000000000000000000000000000 -#uint_t(d::Float128) = reinterpret(UInt128,d) -# Float64 -DenormalExponent(::Type{Float64}) = Int32(-ExponentBias(Float64) + 1) -ExponentMask(::Type{Float64}) = 0x7FF0000000000000 -PhysicalSignificandSize(::Type{Float64}) = Int32(52) -SignificandSize(::Type{Float64}) = Int32(53) -ExponentBias(::Type{Float64}) = Int32(0x3FF + PhysicalSignificandSize(Float64)) -SignificandMask(::Type{Float64}) = 0x000FFFFFFFFFFFFF -HiddenBit(::Type{Float64}) = 0x0010000000000000 -uint_t(d::Float64) = reinterpret(UInt64,d) -# Float32 -DenormalExponent(::Type{Float32}) = Int32(-ExponentBias(Float32) + 1) -ExponentMask(::Type{Float32}) = 0x7F800000 -PhysicalSignificandSize(::Type{Float32}) = Int32(23) -SignificandSize(::Type{Float32}) = Int32(24) -ExponentBias(::Type{Float32}) = Int32(0x7F + PhysicalSignificandSize(Float32)) -SignificandMask(::Type{Float32}) = 0x007FFFFF -HiddenBit(::Type{Float32}) = 0x00800000 -uint_t(d::Float32) = reinterpret(UInt32,d) -# Float16 -DenormalExponent(::Type{Float16}) = Int32(-ExponentBias(Float16) + 1) -ExponentMask(::Type{Float16}) = 0x7c00 -PhysicalSignificandSize(::Type{Float16}) = Int32(10) -SignificandSize(::Type{Float16}) = Int32(11) -ExponentBias(::Type{Float16}) = Int32(0x000f + PhysicalSignificandSize(Float16)) -SignificandMask(::Type{Float16}) = 0x03ff -HiddenBit(::Type{Float16}) = 0x0400 -uint_t(d::Float16) = reinterpret(UInt16,d) - -function _exponent(d::T) where T<:AbstractFloat - isdenormal(d) && return DenormalExponent(T) - biased_e::Int32 = Int32((uint_t(d) & ExponentMask(T)) >> PhysicalSignificandSize(T)) - return Int32(biased_e - ExponentBias(T)) -end -function _significand(d::T) where T<:AbstractFloat - s = uint_t(d) & SignificandMask(T) - return !isdenormal(d) ? s + HiddenBit(T) : s -end -isdenormal{T<:AbstractFloat}(d::T) = (uint_t(d) & ExponentMask(T)) == 0 - -function normalizedbound(f::AbstractFloat) - v = Float(_significand(f),_exponent(f)) - m_plus = normalize(Float((v.s << 1) + 1, v.e - 1)) - if lowerboundaryiscloser(f) - m_minus = Float((v.s << 2) - 1, v.e - 2) - else - m_minus = Float((v.s << 1) - 1, v.e - 1) - end - return Float(m_minus.s << (m_minus.e - m_plus.e), m_plus.e), m_plus -end -function lowerboundaryiscloser(f::T) where T<:AbstractFloat - physical_significand_is_zero = (uint_t(f) & SignificandMask(T)) == 0 - return physical_significand_is_zero && (_exponent(f) != DenormalExponent(T)) -end - -(-)(a::Float,b::Float) = Float(a.s - b.s,a.e,a.de) - -const FloatM32 = 0xFFFFFFFF - -function (*)(this::Float,other::Float) - a::UInt64 = this.s >> 32 - b::UInt64 = this.s & FloatM32 - c::UInt64 = other.s >> 32 - d::UInt64 = other.s & FloatM32 - ac::UInt64 = a * c - bc::UInt64 = b * c - ad::UInt64 = a * d - bd::UInt64 = b * d - tmp::UInt64 = (bd >> 32) + (ad & FloatM32) + (bc & FloatM32) - # By adding 1U << 31 to tmp we round the final result. - # Halfway cases will be round up. - tmp += UInt64(1) << 31 - result_f::UInt64 = ac + (ad >> 32) + (bc >> 32) + (tmp >> 32) - return Float(result_f,this.e + other.e + 64,this.de) -end - -const CachedPowers = Float[ - Float(0xfa8fd5a0081c0288, -1220, -348), - Float(0xbaaee17fa23ebf76, -1193, -340), - Float(0x8b16fb203055ac76, -1166, -332), - Float(0xcf42894a5dce35ea, -1140, -324), - Float(0x9a6bb0aa55653b2d, -1113, -316), - Float(0xe61acf033d1a45df, -1087, -308), - Float(0xab70fe17c79ac6ca, -1060, -300), - Float(0xff77b1fcbebcdc4f, -1034, -292), - Float(0xbe5691ef416bd60c, -1007, -284), - Float(0x8dd01fad907ffc3c, -980, -276), - Float(0xd3515c2831559a83, -954, -268), - Float(0x9d71ac8fada6c9b5, -927, -260), - Float(0xea9c227723ee8bcb, -901, -252), - Float(0xaecc49914078536d, -874, -244), - Float(0x823c12795db6ce57, -847, -236), - Float(0xc21094364dfb5637, -821, -228), - Float(0x9096ea6f3848984f, -794, -220), - Float(0xd77485cb25823ac7, -768, -212), - Float(0xa086cfcd97bf97f4, -741, -204), - Float(0xef340a98172aace5, -715, -196), - Float(0xb23867fb2a35b28e, -688, -188), - Float(0x84c8d4dfd2c63f3b, -661, -180), - Float(0xc5dd44271ad3cdba, -635, -172), - Float(0x936b9fcebb25c996, -608, -164), - Float(0xdbac6c247d62a584, -582, -156), - Float(0xa3ab66580d5fdaf6, -555, -148), - Float(0xf3e2f893dec3f126, -529, -140), - Float(0xb5b5ada8aaff80b8, -502, -132), - Float(0x87625f056c7c4a8b, -475, -124), - Float(0xc9bcff6034c13053, -449, -116), - Float(0x964e858c91ba2655, -422, -108), - Float(0xdff9772470297ebd, -396, -100), - Float(0xa6dfbd9fb8e5b88f, -369, -92), - Float(0xf8a95fcf88747d94, -343, -84), - Float(0xb94470938fa89bcf, -316, -76), - Float(0x8a08f0f8bf0f156b, -289, -68), - Float(0xcdb02555653131b6, -263, -60), - Float(0x993fe2c6d07b7fac, -236, -52), - Float(0xe45c10c42a2b3b06, -210, -44), - Float(0xaa242499697392d3, -183, -36), - Float(0xfd87b5f28300ca0e, -157, -28), - Float(0xbce5086492111aeb, -130, -20), - Float(0x8cbccc096f5088cc, -103, -12), - Float(0xd1b71758e219652c, -77, -4), - Float(0x9c40000000000000, -50, 4), - Float(0xe8d4a51000000000, -24, 12), - Float(0xad78ebc5ac620000, 3, 20), - Float(0x813f3978f8940984, 30, 28), - Float(0xc097ce7bc90715b3, 56, 36), - Float(0x8f7e32ce7bea5c70, 83, 44), - Float(0xd5d238a4abe98068, 109, 52), - Float(0x9f4f2726179a2245, 136, 60), - Float(0xed63a231d4c4fb27, 162, 68), - Float(0xb0de65388cc8ada8, 189, 76), - Float(0x83c7088e1aab65db, 216, 84), - Float(0xc45d1df942711d9a, 242, 92), - Float(0x924d692ca61be758, 269, 100), - Float(0xda01ee641a708dea, 295, 108), - Float(0xa26da3999aef774a, 322, 116), - Float(0xf209787bb47d6b85, 348, 124), - Float(0xb454e4a179dd1877, 375, 132), - Float(0x865b86925b9bc5c2, 402, 140), - Float(0xc83553c5c8965d3d, 428, 148), - Float(0x952ab45cfa97a0b3, 455, 156), - Float(0xde469fbd99a05fe3, 481, 164), - Float(0xa59bc234db398c25, 508, 172), - Float(0xf6c69a72a3989f5c, 534, 180), - Float(0xb7dcbf5354e9bece, 561, 188), - Float(0x88fcf317f22241e2, 588, 196), - Float(0xcc20ce9bd35c78a5, 614, 204), - Float(0x98165af37b2153df, 641, 212), - Float(0xe2a0b5dc971f303a, 667, 220), - Float(0xa8d9d1535ce3b396, 694, 228), - Float(0xfb9b7cd9a4a7443c, 720, 236), - Float(0xbb764c4ca7a44410, 747, 244), - Float(0x8bab8eefb6409c1a, 774, 252), - Float(0xd01fef10a657842c, 800, 260), - Float(0x9b10a4e5e9913129, 827, 268), - Float(0xe7109bfba19c0c9d, 853, 276), - Float(0xac2820d9623bf429, 880, 284), - Float(0x80444b5e7aa7cf85, 907, 292), - Float(0xbf21e44003acdd2d, 933, 300), - Float(0x8e679c2f5e44ff8f, 960, 308), - Float(0xd433179d9c8cb841, 986, 316), - Float(0x9e19db92b4e31ba9, 1013, 324), - Float(0xeb96bf6ebadf77d9, 1039, 332), - Float(0xaf87023b9bf0ee6b, 1066, 340)] - -const CachedPowersLength = length(CachedPowers) -const CachedPowersOffset = 348 # -1 * the first decimal_exponent. -const D_1_LOG2_10 = 0.30102999566398114 # 1 / lg(10) -# Difference between the decimal exponents in the table above. -const DecimalExponentDistance = 8 -const MinDecimalExponent = -348 -const MaxDecimalExponent = 340 - -function binexp_cache(min_exponent,max_exponent) - k = ceil(Integer,(min_exponent+63)*D_1_LOG2_10) - index = div(CachedPowersOffset+k-1,DecimalExponentDistance) + 1 - cp = CachedPowers[index+1] - return cp -end diff --git a/julia-0.6.3/share/julia/base/grisu/grisu.jl b/julia-0.6.3/share/julia/base/grisu/grisu.jl deleted file mode 100644 index 40ddf40..0000000 --- a/julia-0.6.3/share/julia/base/grisu/grisu.jl +++ /dev/null @@ -1,190 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -module Grisu - -importall ..Base.Operators - -export print_shortest -export DIGITS, grisu - -const SHORTEST = 1 -const FIXED = 2 -const PRECISION = 3 - -const DIGITS = Vector{UInt8}(309+17) - -include(joinpath("grisu", "float.jl")) -include(joinpath("grisu", "fastshortest.jl")) -include(joinpath("grisu", "fastprecision.jl")) -include(joinpath("grisu", "fastfixed.jl")) -include(joinpath("grisu", "bignums.jl")) -include(joinpath("grisu", "bignum.jl")) - -const BIGNUMS = [Bignums.Bignum(),Bignums.Bignum(),Bignums.Bignum(),Bignums.Bignum()] - -function grisu(v::AbstractFloat,mode,requested_digits,buffer=DIGITS,bignums=BIGNUMS) - if signbit(v) - neg = true - v = -v - else - neg = false - end - if mode == PRECISION && requested_digits == 0 - buffer[1] = 0x00 - len = 0 - return 0, 0, neg - end - if v == 0.0 - buffer[1] = 0x30 - buffer[2] = 0x00 - len = point = 1 - return len, point, neg - end - if mode == SHORTEST - status,len,point = fastshortest(v,buffer) - elseif mode == FIXED - status,len,point = fastfixedtoa(v,0,requested_digits,buffer) - elseif mode == PRECISION - status,len,point = fastprecision(v,requested_digits,buffer) - end - status && return len-1, point, neg - status, len, point = bignumdtoa(v,mode,requested_digits,buffer,bignums) - return len-1, point, neg -end - -nanstr(x::AbstractFloat) = "NaN" -nanstr(x::Float32) = "NaN32" -nanstr(x::Float16) = "NaN16" -infstr(x::AbstractFloat) = "Inf" -infstr(x::Float32) = "Inf32" -infstr(x::Float16) = "Inf16" - -function _show(io::IO, x::AbstractFloat, mode, n::Int, typed, compact) - isnan(x) && return write(io, typed ? nanstr(x) : "NaN") - if isinf(x) - signbit(x) && write(io,'-') - write(io, typed ? infstr(x) : "Inf") - return - end - typed && isa(x,Float16) && write(io, "Float16(") - (len,pt,neg),buffer = grisu(x,mode,n),DIGITS - pdigits = pointer(buffer) - if mode == PRECISION - while len > 1 && buffer[len] == 0x30 - len -= 1 - end - end - neg && write(io,'-') - exp_form = pt <= -4 || pt > 6 - exp_form = exp_form || (pt >= len && abs(mod(x + 0.05, 10^(pt - len)) - 0.05) > 0.05) # see issue #6608 - if exp_form # .00001 to 100000. - # => #.#######e### - unsafe_write(io, pdigits, 1) - write(io, '.') - if len > 1 - unsafe_write(io, pdigits+1, len-1) - else - write(io, '0') - end - write(io, (typed && isa(x,Float32)) ? 'f' : 'e') - write(io, dec(pt-1)) - typed && isa(x,Float16) && write(io, ")") - return - elseif pt <= 0 - # => 0.00######## - write(io, "0.") - while pt < 0 - write(io, '0') - pt += 1 - end - unsafe_write(io, pdigits, len) - elseif pt >= len - # => ########00.0 - unsafe_write(io, pdigits, len) - while pt > len - write(io, '0') - len += 1 - end - write(io, ".0") - else # => ####.#### - unsafe_write(io, pdigits, pt) - write(io, '.') - unsafe_write(io, pdigits+pt, len-pt) - end - typed && !compact && isa(x,Float32) && write(io, "f0") - typed && isa(x,Float16) && write(io, ")") - nothing -end - -function Base.show(io::IO, x::Union{Float64,Float32}) - if get(io, :compact, false) - _show(io, x, PRECISION, 6, true, true) - else - _show(io, x, SHORTEST, 0, true, false) - end -end - -function Base.show(io::IO, x::Float16) - if get(io, :compact, false) - _show(io, x, PRECISION, 5, false, true) - else - _show(io, x, SHORTEST, 0, true, false) - end -end - -Base.print(io::IO, x::Float32) = _show(io, x, SHORTEST, 0, false, false) -Base.print(io::IO, x::Float16) = _show(io, x, SHORTEST, 0, false, false) - -# normal: -# 0 < pt < len ####.#### len+1 -# pt <= 0 0.000######## len-pt+1 -# len <= pt (dot) ########000. pt+1 -# len <= pt (no dot) ########000 pt -# exponential: -# pt <= 0 ########e-### len+k+2 -# 0 < pt ########e### len+k+1 - -function _print_shortest(io::IO, x::AbstractFloat, dot::Bool, mode, n::Int) - isnan(x) && return write(io, "NaN") - x < 0 && write(io,'-') - isinf(x) && return write(io, "Inf") - (len,pt,neg),buffer = grisu(x,mode,n),DIGITS - pdigits = pointer(buffer) - e = pt-len - k = -9<=e<=9 ? 1 : 2 - if -pt > k+1 || e+dot > k+1 - # => ########e### - unsafe_write(io, pdigits+0, len) - write(io, 'e') - write(io, dec(e)) - return - elseif pt <= 0 - # => 0.000######## - write(io, "0.") - while pt < 0 - write(io, '0') - pt += 1 - end - unsafe_write(io, pdigits+0, len) - elseif e >= dot - # => ########000. - unsafe_write(io, pdigits+0, len) - while e > 0 - write(io, '0') - e -= 1 - end - if dot - write(io, '.') - end - else # => ####.#### - unsafe_write(io, pdigits+0, pt) - write(io, '.') - unsafe_write(io, pdigits+pt, len-pt) - end - nothing -end - -print_shortest(io::IO, x::AbstractFloat, dot::Bool) = _print_shortest(io, x, dot, SHORTEST, 0) -print_shortest(io::IO, x::Union{AbstractFloat,Integer}) = print_shortest(io, float(x), false) - -end # module diff --git a/julia-0.6.3/share/julia/base/hashing.jl b/julia-0.6.3/share/julia/base/hashing.jl deleted file mode 100644 index efc87a4..0000000 --- a/julia-0.6.3/share/julia/base/hashing.jl +++ /dev/null @@ -1,73 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -## hashing a single value ## - -hash(x::Any) = hash(x, zero(UInt)) -hash(w::WeakRef, h::UInt) = hash(w.value, h) - -## hashing general objects ## - -hash(x::ANY, h::UInt) = hash_uint(3h - object_id(x)) - -## core data hashing functions ## - -function hash_64_64(n::UInt64) - local a::UInt64 = n - a = ~a + a << 21 - a = a ⊻ a >> 24 - a = a + a << 3 + a << 8 - a = a ⊻ a >> 14 - a = a + a << 2 + a << 4 - a = a ⊻ a >> 28 - a = a + a << 31 - return a -end - -function hash_64_32(n::UInt64) - local a::UInt64 = n - a = ~a + a << 18 - a = a ⊻ a >> 31 - a = a * 21 - a = a ⊻ a >> 11 - a = a + a << 6 - a = a ⊻ a >> 22 - return a % UInt32 -end - -function hash_32_32(n::UInt32) - local a::UInt32 = n - a = a + 0x7ed55d16 + a << 12 - a = a ⊻ 0xc761c23c ⊻ a >> 19 - a = a + 0x165667b1 + a << 5 - a = a + 0xd3a2646c ⊻ a << 9 - a = a + 0xfd7046c5 + a << 3 - a = a ⊻ 0xb55a4f09 ⊻ a >> 16 - return a -end - -if UInt === UInt64 - hash_uint64(x::UInt64) = hash_64_64(x) - hash_uint(x::UInt) = hash_64_64(x) -else - hash_uint64(x::UInt64) = hash_64_32(x) - hash_uint(x::UInt) = hash_32_32(x) -end - -## symbol & expression hashing ## - -if UInt === UInt64 - hash(x::Expr, h::UInt) = hash(x.args, hash(x.head, h + 0x83c7900696d26dc6)) -else - hash(x::Expr, h::UInt) = hash(x.args, hash(x.head, h + 0x96d26dc6)) -end - -hash(x::QuoteNode, h::UInt) = hash(x.value, hash(QuoteNode, h)) - -# hashing ranges by component at worst leads to collisions for very similar ranges -const hashr_seed = UInt === UInt64 ? 0x80707b6821b70087 : 0x21b70087 -function hash(r::Range, h::UInt) - h += hashr_seed - h = hash(first(r), h) - h = hash(step(r), h) - h = hash(last(r), h) -end diff --git a/julia-0.6.3/share/julia/base/hashing2.jl b/julia-0.6.3/share/julia/base/hashing2.jl deleted file mode 100644 index 37a401a..0000000 --- a/julia-0.6.3/share/julia/base/hashing2.jl +++ /dev/null @@ -1,181 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -## efficient value-based hashing of integers ## - -function hash_integer(n::Integer, h::UInt) - h ⊻= hash_uint((n % UInt) ⊻ h) - n = abs(n) - n >>>= sizeof(UInt) << 3 - while n != 0 - h ⊻= hash_uint((n % UInt) ⊻ h) - n >>>= sizeof(UInt) << 3 - end - return h -end - -function hash_integer(n::BigInt, h::UInt) - s = n.size - s == 0 && return hash_integer(0, h) - p = convert(Ptr{UInt}, n.d) - b = unsafe_load(p) - h ⊻= hash_uint(ifelse(s < 0, -b, b) ⊻ h) - for k = 2:abs(s) - h ⊻= hash_uint(unsafe_load(p, k) ⊻ h) - end - return h -end - -## generic hashing for rational values ## - -function hash(x::Real, h::UInt) - # decompose x as num*2^pow/den - num, pow, den = decompose(x) - - # handle special values - num == 0 && den == 0 && return hash(NaN, h) - num == 0 && return hash(ifelse(den > 0, 0.0, -0.0), h) - den == 0 && return hash(ifelse(num > 0, Inf, -Inf), h) - - # normalize decomposition - if den < 0 - num = -num - den = -den - end - z = trailing_zeros(num) - if z != 0 - num >>= z - pow += z - end - z = trailing_zeros(den) - if z != 0 - den >>= z - pow -= z - end - - # handle values representable as Int64, UInt64, Float64 - if den == 1 - left = ndigits0z(num,2) + pow - right = trailing_zeros(num) + pow - if -1074 <= right - if 0 <= right && left <= 64 - left <= 63 && return hash(Int64(num) << Int(pow), h) - signbit(num) == signbit(den) && return hash(UInt64(num) << Int(pow), h) - end # typemin(Int64) handled by Float64 case - left <= 1024 && left - right <= 53 && return hash(ldexp(Float64(num),pow), h) - end - end - - # handle generic rational values - h = hash_integer(den, h) - h = hash_integer(pow, h) - h = hash_integer(num, h) - return h -end - -#= -`decompose(x)`: non-canonical decomposition of rational values as `num*2^pow/den`. - -The decompose function is the point where rational-valued numeric types that support -hashing hook into the hashing protocol. `decompose(x)` should return three integer -values `num, pow, den`, such that the value of `x` is mathematically equal to - - num*2^pow/den - -The decomposition need not be canonical in the sense that it just needs to be *some* -way to express `x` in this form, not any particular way – with the restriction that -`num` and `den` may not share any odd common factors. They may, however, have powers -of two in common – the generic hashing code will normalize those as necessary. - -Special values: - - - `x` is zero: `num` should be zero and `den` should have the same sign as `x` - - `x` is infinite: `den` should be zero and `num` should have the same sign as `x` - - `x` is not a number: `num` and `den` should both be zero -=# - -decompose(x::Integer) = x, 0, 1 -decompose(x::Rational) = numerator(x), 0, denominator(x) - -function decompose(x::Float16)::NTuple{3,Int} - isnan(x) && return 0, 0, 0 - isinf(x) && return ifelse(x < 0, -1, 1), 0, 0 - n = reinterpret(UInt16, x) - s = (n & 0x03ff) % Int16 - e = (n & 0x7c00 >> 10) % Int - s |= Int16(e != 0) << 10 - d = ifelse(signbit(x), -1, 1) - s, e - 25 + (e == 0), d -end - -function decompose(x::Float32)::NTuple{3,Int} - isnan(x) && return 0, 0, 0 - isinf(x) && return ifelse(x < 0, -1, 1), 0, 0 - n = reinterpret(UInt32, x) - s = (n & 0x007fffff) % Int32 - e = (n & 0x7f800000 >> 23) % Int - s |= Int32(e != 0) << 23 - d = ifelse(signbit(x), -1, 1) - s, e - 150 + (e == 0), d -end - -function decompose(x::Float64)::Tuple{Int64, Int, Int} - isnan(x) && return 0, 0, 0 - isinf(x) && return ifelse(x < 0, -1, 1), 0, 0 - n = reinterpret(UInt64, x) - s = (n & 0x000fffffffffffff) % Int64 - e = (n & 0x7ff0000000000000 >> 52) % Int - s |= Int64(e != 0) << 52 - d = ifelse(signbit(x), -1, 1) - s, e - 1075 + (e == 0), d -end - -function decompose(x::BigFloat)::Tuple{BigInt, Int, Int} - isnan(x) && return 0, 0, 0 - isinf(x) && return x.sign, 0, 0 - x == 0 && return 0, 0, x.sign - s = BigInt() - s.size = cld(x.prec, 8*sizeof(GMP.Limb)) # limbs - b = s.size * sizeof(GMP.Limb) # bytes - ccall((:__gmpz_realloc2, :libgmp), Void, (Ptr{BigInt}, Culong), &s, 8b) # bits - ccall(:memcpy, Ptr{Void}, (Ptr{Void}, Ptr{Void}, Csize_t), s.d, x.d, b) # bytes - s, x.exp - 8b, x.sign -end - -## streamlined hashing for smallish rational types ## - -function hash(x::Rational{<:BitInteger64}, h::UInt) - num, den = Base.numerator(x), Base.denominator(x) - den == 1 && return hash(num, h) - den == 0 && return hash(ifelse(num > 0, Inf, -Inf), h) - if isodd(den) - pow = trailing_zeros(num) - num >>= pow - else - pow = trailing_zeros(den) - den >>= pow - pow = -pow - if den == 1 && abs(num) < 9007199254740992 - return hash(ldexp(Float64(num),pow)) - end - end - h = hash_integer(den, h) - h = hash_integer(pow, h) - h = hash_integer(num, h) - return h -end - -## hashing Float16s ## - -hash(x::Float16, h::UInt) = hash(Float64(x), h) - -## hashing strings ## - -const memhash = UInt === UInt64 ? :memhash_seed : :memhash32_seed -const memhash_seed = UInt === UInt64 ? 0x71e729fd56419c81 : 0x56419c81 - -function hash(s::Union{String,SubString{String}}, h::UInt) - h += memhash_seed - # note: use pointer(s) here (see #6058). - ccall(memhash, UInt, (Ptr{UInt8}, Csize_t, UInt32), pointer(s), sizeof(s), h % UInt32) + h -end -hash(s::AbstractString, h::UInt) = hash(String(s), h) diff --git a/julia-0.6.3/share/julia/base/i18n.jl b/julia-0.6.3/share/julia/base/i18n.jl deleted file mode 100644 index d4488cc..0000000 --- a/julia-0.6.3/share/julia/base/i18n.jl +++ /dev/null @@ -1,26 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -module I18n - -export locale - -LOCALE = nothing -CALLBACKS = Function[] - -function locale() - if LOCALE === nothing - # XXX:TBD return default locale - return "" - end - LOCALE -end - -function locale(s::String) - global LOCALE = s - # XXX:TBD call setlocale - for cb in CALLBACKS - cb() - end -end - -end # module diff --git a/julia-0.6.3/share/julia/base/indices.jl b/julia-0.6.3/share/julia/base/indices.jl deleted file mode 100644 index e55a64d..0000000 --- a/julia-0.6.3/share/julia/base/indices.jl +++ /dev/null @@ -1,248 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -Dims{N} = NTuple{N,Int} -DimsInteger{N} = NTuple{N,Integer} -Indices{N} = NTuple{N,AbstractUnitRange} - -# array shape rules - -promote_shape(::Tuple{}, ::Tuple{}) = () - -function promote_shape(a::Tuple{Int,}, b::Tuple{Int,}) - if a[1] != b[1] - throw(DimensionMismatch("dimensions must match")) - end - return a -end - -function promote_shape(a::Tuple{Int,Int}, b::Tuple{Int,}) - if a[1] != b[1] || a[2] != 1 - throw(DimensionMismatch("dimensions must match")) - end - return a -end - -promote_shape(a::Tuple{Int,}, b::Tuple{Int,Int}) = promote_shape(b, a) - -function promote_shape(a::Tuple{Int, Int}, b::Tuple{Int, Int}) - if a[1] != b[1] || a[2] != b[2] - throw(DimensionMismatch("dimensions must match")) - end - return a -end - -""" - promote_shape(s1, s2) - -Check two array shapes for compatibility, allowing trailing singleton dimensions, and return -whichever shape has more dimensions. - -```jldoctest -julia> a = ones(3,4,1,1,1); - -julia> b = ones(3,4); - -julia> promote_shape(a,b) -(Base.OneTo(3), Base.OneTo(4), Base.OneTo(1), Base.OneTo(1), Base.OneTo(1)) - -julia> promote_shape((2,3,1,4), (2, 3, 1, 4, 1)) -(2, 3, 1, 4, 1) -``` -""" -function promote_shape(a::Dims, b::Dims) - if length(a) < length(b) - return promote_shape(b, a) - end - for i=1:length(b) - if a[i] != b[i] - throw(DimensionMismatch("dimensions must match")) - end - end - for i=length(b)+1:length(a) - if a[i] != 1 - throw(DimensionMismatch("dimensions must match")) - end - end - return a -end - -function promote_shape(a::AbstractArray, b::AbstractArray) - promote_shape(indices(a), indices(b)) -end - -function promote_shape(a::Indices, b::Indices) - if length(a) < length(b) - return promote_shape(b, a) - end - for i=1:length(b) - if a[i] != b[i] - throw(DimensionMismatch("dimensions must match")) - end - end - for i=length(b)+1:length(a) - if a[i] != 1:1 - throw(DimensionMismatch("dimensions must match")) - end - end - return a -end - -function throw_setindex_mismatch(X, I) - if length(I) == 1 - throw(DimensionMismatch("tried to assign $(length(X)) elements to $(I[1]) destinations")) - else - throw(DimensionMismatch("tried to assign $(dims2string(size(X))) array to $(dims2string(I)) destination")) - end -end - -# check for valid sizes in A[I...] = X where X <: AbstractArray -# we want to allow dimensions that are equal up to permutation, but only -# for permutations that leave array elements in the same linear order. -# those are the permutations that preserve the order of the non-singleton -# dimensions. -function setindex_shape_check(X::AbstractArray, I::Integer...) - li = ndims(X) - lj = length(I) - i = j = 1 - while true - ii = length(indices(X,i)) - jj = I[j] - if i == li || j == lj - while i < li - i += 1 - ii *= length(indices(X,i)) - end - while j < lj - j += 1 - jj *= I[j] - end - if ii != jj - throw_setindex_mismatch(X, I) - end - return - end - if ii == jj - i += 1 - j += 1 - elseif ii == 1 - i += 1 - elseif jj == 1 - j += 1 - else - throw_setindex_mismatch(X, I) - end - end -end - -setindex_shape_check(X::AbstractArray) = - (_length(X)==1 || throw_setindex_mismatch(X,())) - -setindex_shape_check(X::AbstractArray, i::Integer) = - (_length(X)==i || throw_setindex_mismatch(X, (i,))) - -setindex_shape_check(X::AbstractArray{<:Any,1}, i::Integer) = - (_length(X)==i || throw_setindex_mismatch(X, (i,))) - -setindex_shape_check(X::AbstractArray{<:Any,1}, i::Integer, j::Integer) = - (_length(X)==i*j || throw_setindex_mismatch(X, (i,j))) - -function setindex_shape_check(X::AbstractArray{<:Any,2}, i::Integer, j::Integer) - if length(X) != i*j - throw_setindex_mismatch(X, (i,j)) - end - sx1 = length(indices(X,1)) - if !(i == 1 || i == sx1 || sx1 == 1) - throw_setindex_mismatch(X, (i,j)) - end -end -setindex_shape_check(X, I...) = nothing # Non-arrays broadcast to all idxs - -# convert to a supported index type (array or Int) -""" - to_index(A, i) - -Convert index `i` to an `Int` or array of indices to be used as an index into array `A`. - -Custom array types may specialize `to_index(::CustomArray, i)` to provide -special indexing behaviors. Note that some index types (like `Colon`) require -more context in order to transform them into an array of indices; those get -converted in the more complicated `to_indices` function. By default, this -simply calls the generic `to_index(i)`. This must return either an `Int` or an -`AbstractArray` of scalar indices that are supported by `A`. -""" -to_index(A, i) = to_index(i) - -""" - to_index(i) - -Convert index `i` to an `Int` or array of `Int`s to be used as an index for all arrays. - -Custom index types may specialize `to_index(::CustomIndex)` to provide special -indexing behaviors. This must return either an `Int` or an `AbstractArray` of -`Int`s. -""" -to_index(i::Integer) = convert(Int,i)::Int -to_index(I::AbstractArray{Bool}) = LogicalIndex(I) -to_index(I::AbstractArray) = I -to_index(I::AbstractArray{<:Union{AbstractArray, Colon}}) = throw(ArgumentError("invalid index: $I")) -to_index(::Colon) = throw(ArgumentError("colons must be converted by to_indices(...)")) -to_index(i) = throw(ArgumentError("invalid index: $i")) - -# The general to_indices is mostly defined in multidimensional.jl, but this -# definition is required for bootstrap: -""" - to_indices(A, I::Tuple) - -Convert the tuple `I` to a tuple of indices for use in indexing into array `A`. - -The returned tuple must only contain either `Int`s or `AbstractArray`s of -scalar indices that are supported by array `A`. It will error upon encountering -a novel index type that it does not know how to process. - -For simple index types, it defers to the unexported `Base.to_index(A, i)` to -process each index `i`. While this internal function is not intended to be -called directly, `Base.to_index` may be extended by custom array or index types -to provide custom indexing behaviors. - -More complicated index types may require more context about the dimension into -which they index. To support those cases, `to_indices(A, I)` calls -`to_indices(A, indices(A), I)`, which then recursively walks through both the -given tuple of indices and the dimensional indices of `A` in tandem. As such, -not all index types are guaranteed to propagate to `Base.to_index`. -""" -to_indices(A, I::Tuple) = (@_inline_meta; to_indices(A, indices(A), I)) -to_indices(A, inds, ::Tuple{}) = () -to_indices(A, inds, I::Tuple{Any, Vararg{Any}}) = - (@_inline_meta; (to_index(A, I[1]), to_indices(A, _maybetail(inds), tail(I))...)) - -_maybetail(::Tuple{}) = () -_maybetail(t::Tuple) = tail(t) - -""" - Slice(indices) - -Represent an AbstractUnitRange of indices as a vector of the indices themselves. - -Upon calling `to_indices()`, Colons are converted to Slice objects to represent -the indices over which the Colon spans. Slice objects are themselves unit -ranges with the same indices as those they wrap. This means that indexing into -Slice objects with an integer always returns that exact integer, and they -iterate over all the wrapped indices, even supporting offset indices. -""" -struct Slice{T<:AbstractUnitRange} <: AbstractUnitRange{Int} - indices::T -end -indices(S::Slice) = (S.indices,) -unsafe_indices(S::Slice) = (S.indices,) -indices1(S::Slice) = S.indices -first(S::Slice) = first(S.indices) -last(S::Slice) = last(S.indices) -errmsg(A) = error("size not supported for arrays with indices $(indices(A)); see https://docs.julialang.org/en/latest/devdocs/offset-arrays/") -size(S::Slice) = first(S.indices) == 1 ? (length(S.indices),) : errmsg(S) -length(S::Slice) = first(S.indices) == 1 ? length(S.indices) : errmsg(S) -unsafe_length(S::Slice) = first(S.indices) == 1 ? unsafe_length(S.indices) : errmsg(S) -getindex(S::Slice, i::Int) = (@_inline_meta; @boundscheck checkbounds(S, i); i) -show(io::IO, r::Slice) = print(io, "Base.Slice(", r.indices, ")") -start(S::Slice) = start(S.indices) -next(S::Slice, s) = next(S.indices, s) -done(S::Slice, s) = done(S.indices, s) diff --git a/julia-0.6.3/share/julia/base/inference.jl b/julia-0.6.3/share/julia/base/inference.jl deleted file mode 100644 index 8455889..0000000 --- a/julia-0.6.3/share/julia/base/inference.jl +++ /dev/null @@ -1,5443 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -import Core: _apply, svec, apply_type, Builtin, IntrinsicFunction, MethodInstance - -#### parameters limiting potentially-infinite types #### -const MAX_TYPEUNION_LEN = 3 -const MAX_TYPE_DEPTH = 8 - -const MAX_INLINE_CONST_SIZE = 256 - -struct InferenceParams - world::UInt - - # optimization - inlining::Bool - - # parameters limiting potentially-infinite types (configurable) - MAX_TUPLETYPE_LEN::Int - MAX_TUPLE_DEPTH::Int - MAX_TUPLE_SPLAT::Int - MAX_UNION_SPLITTING::Int - MAX_APPLY_UNION_ENUM::Int - - # reasonable defaults - function InferenceParams(world::UInt; - inlining::Bool = inlining_enabled(), - tupletype_len::Int = 15, - tuple_depth::Int = 4, - tuple_splat::Int = 16, - union_splitting::Int = 4, - apply_union_enum::Int = 8) - return new(world, inlining, tupletype_len, - tuple_depth, tuple_splat, union_splitting, apply_union_enum) - end -end - -const UNION_SPLIT_MISMATCH_ERROR = false - -# alloc_elim_pass! relies on `Slot_AssignedOnce | Slot_UsedUndef` being -# SSA. This should be true now but can break if we start to track conditional -# constants. e.g. -# -# cond && (a = 1) -# other_code() -# cond && use(a) - -# slot property bit flags -const Slot_Assigned = 2 -const Slot_AssignedOnce = 16 -const Slot_UsedUndef = 32 - -#### inference state types #### - -struct NotFound end -const NF = NotFound() -const LineNum = Int -const VarTable = Array{Any,1} - -# The type of a variable load is either a value or an UndefVarError -mutable struct VarState - typ - undef::Bool - VarState(typ::ANY, undef::Bool) = new(typ, undef) -end - -# The type of a value might be constant -struct Const - val - actual::Bool # if true, we obtained `val` by actually calling a @pure function - Const(v::ANY) = new(v, false) - Const(v::ANY, a::Bool) = new(v, a) -end - -# The type of a value might be Bool, -# but where the value of the boolean can be used in back-propagation to -# limit the type of some other variable -# The Conditional type tracks the set of branches on variable type info -# that was used to create the boolean condition -mutable struct Conditional - var::Union{Slot,SSAValue} - vtype - elsetype - function Conditional( - var::ANY, - vtype::ANY, - nottype::ANY) - return new(var, vtype, nottype) - end -end - -struct PartialTypeVar - tv::TypeVar - # N.B.: Currently unused, but would allow turning something back - # into Const, if the bounds are pulled out of this TypeVar - lb_certain::Bool - ub_certain::Bool - PartialTypeVar(tv::TypeVar, lb_certain::Bool, ub_certain::Bool) = new(tv, lb_certain, ub_certain) -end - -function rewrap(t::ANY, u::ANY) - isa(t, Const) && return t - isa(t, Conditional) && return t - return rewrap_unionall(t, u) -end - -mutable struct InferenceState - sp::SimpleVector # static parameters - label_counter::Int # index of the current highest label for this function - mod::Module - currpc::LineNum - - # info on the state of inference and the linfo - params::InferenceParams - linfo::MethodInstance # used here for the tuple (specTypes, env, Method) - src::CodeInfo - min_valid::UInt - max_valid::UInt - nargs::Int - stmt_types::Vector{Any} - stmt_edges::Vector{Any} - # return type - bestguess #::Type - # current active instruction pointers - ip::IntSet - pc´´::Int - nstmts::Int - # current exception handler info - cur_hand #::Tuple{LineNum, Tuple{LineNum, ...}} - handler_at::Vector{Any} - n_handlers::Int - # ssavalue sparsity and restart info - ssavalue_uses::Vector{IntSet} - ssavalue_init::Vector{Any} - - backedges::Vector{Tuple{InferenceState, LineNum}} # call-graph backedges connecting from callee to caller - callers_in_cycle::Vector{InferenceState} - parent::Union{Void, InferenceState} - - const_api::Bool - const_ret::Bool - - # TODO: put these in InferenceParams (depends on proper multi-methodcache support) - optimize::Bool - cached::Bool - - inferred::Bool - - dont_work_on_me::Bool - - # src is assumed to be a newly-allocated CodeInfo, that can be modified in-place to contain intermediate results - function InferenceState(linfo::MethodInstance, src::CodeInfo, - optimize::Bool, cached::Bool, params::InferenceParams) - code = src.code::Array{Any,1} - nl = label_counter(code) + 1 - toplevel = !isdefined(linfo, :def) - - if !toplevel && isempty(linfo.sparam_vals) && !isempty(linfo.def.sparam_syms) - # linfo is unspecialized - sp = Any[] - sig = linfo.def.sig - while isa(sig,UnionAll) - push!(sp, sig.var) - sig = sig.body - end - sp = svec(sp...) - else - sp = linfo.sparam_vals - end - - src.ssavaluetypes = Any[ NF for i = 1:(src.ssavaluetypes::Int) ] - - n = length(code) - s_edges = Any[ () for i = 1:n ] - s_types = Any[ () for i = 1:n ] - - # initial types - nslots = length(src.slotnames) - s_types[1] = Any[ VarState(Bottom, true) for i = 1:nslots ] - src.slottypes = Any[ Bottom for i = 1:nslots ] - - atypes = unwrap_unionall(linfo.specTypes) - nargs::Int = toplevel ? 0 : linfo.def.nargs - la = nargs - if la > 0 - if linfo.def.isva - if atypes == Tuple - if la > 1 - atypes = Tuple{Any[Any for i = 1:(la - 1)]..., Tuple.parameters[1]} - end - vararg_type = Tuple - else - vararg_type = limit_tuple_depth(params, tupletype_tail(atypes, la)) - vararg_type = tuple_tfunc(vararg_type) # returns a Const object, if applicable - vararg_type = rewrap(vararg_type, linfo.specTypes) - end - s_types[1][la] = VarState(vararg_type, false) - src.slottypes[la] = vararg_type - la -= 1 - end - end - - laty = length(atypes.parameters) - if laty > 0 - if laty > la - laty = la - end - local lastatype - atail = laty - for i = 1:laty - atyp = atypes.parameters[i] - if i == laty && isvarargtype(atyp) - atyp = unwrap_unionall(atyp).parameters[1] - atail -= 1 - end - if isa(atyp, TypeVar) - atyp = atyp.ub - end - if isa(atyp, DataType) && isdefined(atyp, :instance) - # replace singleton types with their equivalent Const object - atyp = Const(atyp.instance) - elseif isconstType(atyp) - atype = Const(atyp.parameters[1]) - else - atyp = rewrap_unionall(atyp, linfo.specTypes) - end - i == laty && (lastatype = atyp) - s_types[1][i] = VarState(atyp, false) - src.slottypes[i] = atyp - end - for i = (atail + 1):la - s_types[1][i] = VarState(lastatype, false) - src.slottypes[i] = lastatype - end - else - @assert la == 0 # wrong number of arguments - end - - ssavalue_uses = find_ssavalue_uses(code) - ssavalue_init = copy(src.ssavaluetypes::Vector{Any}) - - # exception handlers - cur_hand = () - handler_at = Any[ () for i=1:n ] - n_handlers = 0 - - W = IntSet() - push!(W, 1) #initial pc to visit - - if !toplevel - meth = linfo.def - inmodule = meth.module - else - inmodule = current_module() # toplevel thunks are inferred in the current module - end - - if cached && !toplevel - min_valid = min_world(linfo.def) - max_valid = max_world(linfo.def) - else - min_valid = typemax(UInt) - max_valid = typemin(UInt) - end - frame = new( - sp, nl, inmodule, 0, params, - linfo, src, min_valid, max_valid, - nargs, s_types, s_edges, - Union{}, W, 1, n, - cur_hand, handler_at, n_handlers, - ssavalue_uses, ssavalue_init, - Vector{Tuple{InferenceState,LineNum}}(), # backedges - Vector{InferenceState}(), # callers_in_cycle - #=parent=#nothing, - false, false, optimize, cached, false, false) - return frame - end -end - -function InferenceState(linfo::MethodInstance, - optimize::Bool, cached::Bool, params::InferenceParams) - # prepare an InferenceState object for inferring lambda - # create copies of the CodeInfo definition, and any fields that type-inference might modify - if linfo.def.isstaged - try - # user code might throw errors – ignore them - src = get_staged(linfo) - catch - return nothing - end - else - # TODO: post-inference see if we can swap back to the original arrays? - if isa(linfo.def.source, Array{UInt8,1}) - src = ccall(:jl_uncompress_ast, Any, (Any, Any), linfo.def, linfo.def.source) - else - src = ccall(:jl_copy_code_info, Ref{CodeInfo}, (Any,), linfo.def.source) - src.code = copy_exprargs(src.code) - src.slotnames = copy(src.slotnames) - src.slotflags = copy(src.slotflags) - end - end - return InferenceState(linfo, src, optimize, cached, params) -end - -function get_staged(li::MethodInstance) - return ccall(:jl_code_for_staged, Any, (Any,), li)::CodeInfo -end - -#### helper functions #### - -@inline slot_id(s) = isa(s, SlotNumber) ? (s::SlotNumber).id : (s::TypedSlot).id # using a function to ensure we can infer this - -# avoid cycle due to over-specializing `any` when used by inference -function _any(f::ANY, a) - for x in a - f(x) && return true - end - return false -end - -function contains_is(itr, x::ANY) - for y in itr - if y === x - return true - end - end - return false -end - -anymap(f::Function, a::Array{Any,1}) = Any[ f(a[i]) for i=1:length(a) ] - -_topmod(sv::InferenceState) = _topmod(sv.mod) -_topmod(m::Module) = ccall(:jl_base_relative_to, Any, (Any,), m)::Module - -function istopfunction(topmod, f::ANY, sym) - if isdefined(Main, :Base) && isdefined(Main.Base, sym) && isconst(Main.Base, sym) && f === getfield(Main.Base, sym) - return true - elseif isdefined(topmod, sym) && isconst(topmod, sym) && f === getfield(topmod, sym) - return true - end - return false -end - -isknownlength(t::DataType) = !isvatuple(t) || - (length(t.parameters) > 0 && isa(unwrap_unionall(t.parameters[end]).parameters[2],Int)) - -# t[n:end] -tupletype_tail(t::ANY, n) = Tuple{t.parameters[n:end]...} - - -#### type-functions for builtins / intrinsics #### - -const _Type_name = Type.body.name -isType(t::ANY) = isa(t, DataType) && (t::DataType).name === _Type_name - -# true if Type is inlineable as constant (is a singleton) -isconstType(t::ANY) = isType(t) && (isleaftype(t.parameters[1]) || t.parameters[1] === Union{}) - -iskindtype(t::ANY) = (t === DataType || t === UnionAll || t === Union || t === typeof(Bottom)) - -const IInf = typemax(Int) # integer infinity -const n_ifunc = reinterpret(Int32, arraylen) + 1 -const t_ifunc = Array{Tuple{Int, Int, Any}, 1}(n_ifunc) -const t_ffunc_key = Array{Any, 1}(0) -const t_ffunc_val = Array{Tuple{Int, Int, Any}, 1}(0) -function add_tfunc(f::IntrinsicFunction, minarg::Int, maxarg::Int, tfunc::ANY) - t_ifunc[reinterpret(Int32, f) + 1] = (minarg, maxarg, tfunc) -end -function add_tfunc(f::Function, minarg::Int, maxarg::Int, tfunc::ANY) - push!(t_ffunc_key, f) - push!(t_ffunc_val, (minarg, maxarg, tfunc)) -end - -add_tfunc(throw, 1, 1, (x::ANY) -> Bottom) - -# the inverse of typeof_tfunc -# returns (type, isexact) -# if isexact is false, the actual runtime type may (will) be a subtype of t -function instanceof_tfunc(t::ANY) - if t === Bottom || t === typeof(Bottom) - return Bottom, true - elseif isa(t, Const) - if isa(t.val, Type) - return t.val, true - end - elseif isType(t) - tp = t.parameters[1] - return tp, !has_free_typevars(tp) - elseif isa(t, UnionAll) - t′ = unwrap_unionall(t) - t′′, isexact = instanceof_tfunc(t′) - return rewrap_unionall(t′′, t), isexact - elseif isa(t, Union) - ta, isexact_a = instanceof_tfunc(t.a) - tb, isexact_b = instanceof_tfunc(t.b) - return Union{ta, tb}, false # at runtime, will be exactly one of these - end - return Any, false -end -bitcast_tfunc(t::ANY, x::ANY) = instanceof_tfunc(t)[1] -math_tfunc(x::ANY) = widenconst(x) -math_tfunc(x::ANY, y::ANY) = widenconst(x) -math_tfunc(x::ANY, y::ANY, z::ANY) = widenconst(x) -fptoui_tfunc(t::ANY, x::ANY) = bitcast_tfunc(t, x) -fptosi_tfunc(t::ANY, x::ANY) = bitcast_tfunc(t, x) -function fptoui_tfunc(x::ANY) - T = widenconst(x) - T === Float64 && return UInt64 - T === Float32 && return UInt32 - T === Float16 && return UInt16 - return Any -end -function fptosi_tfunc(x::ANY) - T = widenconst(x) - T === Float64 && return Int64 - T === Float32 && return Int32 - T === Float16 && return Int16 - return Any -end - - ## conversion ## -add_tfunc(bitcast, 2, 2, bitcast_tfunc) -add_tfunc(sext_int, 2, 2, bitcast_tfunc) -add_tfunc(zext_int, 2, 2, bitcast_tfunc) -add_tfunc(trunc_int, 2, 2, bitcast_tfunc) -add_tfunc(fptoui, 1, 2, fptoui_tfunc) -add_tfunc(fptosi, 1, 2, fptosi_tfunc) -add_tfunc(uitofp, 2, 2, bitcast_tfunc) -add_tfunc(sitofp, 2, 2, bitcast_tfunc) -add_tfunc(fptrunc, 2, 2, bitcast_tfunc) -add_tfunc(fpext, 2, 2, bitcast_tfunc) - ## checked conversion ## -add_tfunc(checked_trunc_sint, 2, 2, bitcast_tfunc) -add_tfunc(checked_trunc_uint, 2, 2, bitcast_tfunc) -add_tfunc(check_top_bit, 1, 1, math_tfunc) - ## arithmetic ## -add_tfunc(neg_int, 1, 1, math_tfunc) -add_tfunc(add_int, 2, 2, math_tfunc) -add_tfunc(sub_int, 2, 2, math_tfunc) -add_tfunc(mul_int, 2, 2, math_tfunc) -add_tfunc(sdiv_int, 2, 2, math_tfunc) -add_tfunc(udiv_int, 2, 2, math_tfunc) -add_tfunc(srem_int, 2, 2, math_tfunc) -add_tfunc(urem_int, 2, 2, math_tfunc) -add_tfunc(neg_float, 1, 1, math_tfunc) -add_tfunc(add_float, 2, 2, math_tfunc) -add_tfunc(sub_float, 2, 2, math_tfunc) -add_tfunc(mul_float, 2, 2, math_tfunc) -add_tfunc(div_float, 2, 2, math_tfunc) -add_tfunc(rem_float, 2, 2, math_tfunc) -add_tfunc(fma_float, 3, 3, math_tfunc) -add_tfunc(muladd_float, 3, 3, math_tfunc) - ## fast arithmetic ## -add_tfunc(neg_float_fast, 1, 1, math_tfunc) -add_tfunc(add_float_fast, 2, 2, math_tfunc) -add_tfunc(sub_float_fast, 2, 2, math_tfunc) -add_tfunc(mul_float_fast, 2, 2, math_tfunc) -add_tfunc(div_float_fast, 2, 2, math_tfunc) -add_tfunc(rem_float_fast, 2, 2, math_tfunc) - ## bitwise operators ## -add_tfunc(and_int, 2, 2, math_tfunc) -add_tfunc(or_int, 2, 2, math_tfunc) -add_tfunc(xor_int, 2, 2, math_tfunc) -add_tfunc(not_int, 1, 1, math_tfunc) -add_tfunc(shl_int, 2, 2, math_tfunc) -add_tfunc(lshr_int, 2, 2, math_tfunc) -add_tfunc(ashr_int, 2, 2, math_tfunc) -add_tfunc(bswap_int, 1, 1, math_tfunc) -add_tfunc(ctpop_int, 1, 1, math_tfunc) -add_tfunc(ctlz_int, 1, 1, math_tfunc) -add_tfunc(cttz_int, 1, 1, math_tfunc) -add_tfunc(checked_sdiv_int, 2, 2, math_tfunc) -add_tfunc(checked_udiv_int, 2, 2, math_tfunc) -add_tfunc(checked_srem_int, 2, 2, math_tfunc) -add_tfunc(checked_urem_int, 2, 2, math_tfunc) - ## functions ## -add_tfunc(abs_float, 1, 1, math_tfunc) -add_tfunc(copysign_float, 2, 2, math_tfunc) -add_tfunc(flipsign_int, 2, 2, math_tfunc) -add_tfunc(ceil_llvm, 1, 1, math_tfunc) -add_tfunc(floor_llvm, 1, 1, math_tfunc) -add_tfunc(trunc_llvm, 1, 1, math_tfunc) -add_tfunc(rint_llvm, 1, 1, math_tfunc) -add_tfunc(sqrt_llvm, 1, 1, math_tfunc) -add_tfunc(sqrt_llvm_fast, 1, 1, math_tfunc) - ## same-type comparisons ## -cmp_tfunc(x::ANY, y::ANY) = Bool -add_tfunc(eq_int, 2, 2, cmp_tfunc) -add_tfunc(ne_int, 2, 2, cmp_tfunc) -add_tfunc(slt_int, 2, 2, cmp_tfunc) -add_tfunc(ult_int, 2, 2, cmp_tfunc) -add_tfunc(sle_int, 2, 2, cmp_tfunc) -add_tfunc(ule_int, 2, 2, cmp_tfunc) -add_tfunc(eq_float, 2, 2, cmp_tfunc) -add_tfunc(ne_float, 2, 2, cmp_tfunc) -add_tfunc(lt_float, 2, 2, cmp_tfunc) -add_tfunc(le_float, 2, 2, cmp_tfunc) -add_tfunc(fpiseq, 2, 2, cmp_tfunc) -add_tfunc(fpislt, 2, 2, cmp_tfunc) -add_tfunc(eq_float_fast, 2, 2, cmp_tfunc) -add_tfunc(ne_float_fast, 2, 2, cmp_tfunc) -add_tfunc(lt_float_fast, 2, 2, cmp_tfunc) -add_tfunc(le_float_fast, 2, 2, cmp_tfunc) - - ## checked arithmetic ## -chk_tfunc(x::ANY, y::ANY) = Tuple{widenconst(x), Bool} -add_tfunc(checked_sadd_int, 2, 2, chk_tfunc) -add_tfunc(checked_uadd_int, 2, 2, chk_tfunc) -add_tfunc(checked_ssub_int, 2, 2, chk_tfunc) -add_tfunc(checked_usub_int, 2, 2, chk_tfunc) -add_tfunc(checked_smul_int, 2, 2, chk_tfunc) -add_tfunc(checked_umul_int, 2, 2, chk_tfunc) - ## other, misc intrinsics ## -add_tfunc(Core.Intrinsics.llvmcall, 3, IInf, - (fptr::ANY, rt::ANY, at::ANY, a...) -> instanceof_tfunc(rt)[1]) -cglobal_tfunc(fptr::ANY) = Ptr{Void} -cglobal_tfunc(fptr::ANY, t::ANY) = (isType(t) ? Ptr{t.parameters[1]} : Ptr) -cglobal_tfunc(fptr::ANY, t::Const) = (isa(t.val, Type) ? Ptr{t.val} : Ptr) -add_tfunc(Core.Intrinsics.cglobal, 1, 2, cglobal_tfunc) -add_tfunc(Core.Intrinsics.select_value, 3, 3, - function (cnd::ANY, x::ANY, y::ANY) - if isa(cnd, Const) - if cnd.val === true - return x - elseif cnd.val === false - return y - else - return Bottom - end - end - (Bool ⊑ cnd) || return Bottom - return tmerge(x, y) - end) -add_tfunc(===, 2, 2, - function (x::ANY, y::ANY) - if isa(x, Const) && isa(y, Const) - return Const(x.val === y.val) - elseif typeintersect(widenconst(x), widenconst(y)) === Bottom - return Const(false) - elseif (isa(x, Const) && y === typeof(x.val) && isdefined(y, :instance)) || - (isa(y, Const) && x === typeof(y.val) && isdefined(x, :instance)) - return Const(true) - elseif isa(x, Conditional) && isa(y, Const) - y.val === false && return Conditional(x.var, x.elsetype, x.vtype) - y.val === true && return x - return x - elseif isa(y, Conditional) && isa(x, Const) - x.val === false && return Conditional(y.var, y.elsetype, y.vtype) - x.val === true && return y - end - return Bool - end) -add_tfunc(isdefined, 1, IInf, (args...)->Bool) -add_tfunc(Core.sizeof, 1, 1, x->Int) -add_tfunc(nfields, 1, 1, - function (x::ANY) - isa(x,Const) && return Const(nfields(x.val)) - isa(x,Conditional) && return Const(nfields(Bool)) - if isType(x) - isleaftype(x.parameters[1]) && return Const(nfields(x.parameters[1])) - elseif isa(x,DataType) && !x.abstract && !(x.name === Tuple.name && isvatuple(x)) && x !== DataType - return Const(length(x.types)) - end - return Int - end) -add_tfunc(Core._expr, 1, IInf, (args...)->Expr) -add_tfunc(applicable, 1, IInf, (f::ANY, args...)->Bool) -add_tfunc(Core.Intrinsics.arraylen, 1, 1, x->Int) -add_tfunc(arraysize, 2, 2, (a::ANY, d::ANY)->Int) -add_tfunc(pointerref, 3, 3, - function (a::ANY, i::ANY, align::ANY) - a = widenconst(a) - if a <: Ptr - if isa(a,DataType) && isa(a.parameters[1],Type) - return a.parameters[1] - elseif isa(a,UnionAll) && !has_free_typevars(a) - unw = unwrap_unionall(a) - if isa(unw,DataType) - return rewrap_unionall(unw.parameters[1], a) - end - end - end - return Any - end) -add_tfunc(pointerset, 4, 4, (a::ANY, v::ANY, i::ANY, align::ANY) -> a) - -function typeof_tfunc(t::ANY) - if isa(t, Const) - return Const(typeof(t.val)) - elseif isa(t, Conditional) - return Const(Bool) - elseif isType(t) - tp = t.parameters[1] - if !isleaftype(tp) - return DataType # typeof(Kind::Type)::DataType - else - return Const(typeof(tp)) # XXX: this is not necessarily true - end - elseif isa(t, DataType) - if isleaftype(t) || isvarargtype(t) - return Const(t) - elseif t === Any - return DataType - else - return Type{<:t} - end - elseif isa(t, Union) - a = widenconst(typeof_tfunc(t.a)) - b = widenconst(typeof_tfunc(t.b)) - return Union{a, b} - elseif isa(t, TypeVar) && !(Any <: t.ub) - return typeof_tfunc(t.ub) - elseif isa(t, UnionAll) - return rewrap_unionall(widenconst(typeof_tfunc(unwrap_unionall(t))), t) - else - return DataType # typeof(anything)::DataType - end -end -add_tfunc(typeof, 1, 1, typeof_tfunc) -add_tfunc(typeassert, 2, 2, - function (v::ANY, t::ANY) - t, isexact = instanceof_tfunc(t) - t === Any && return v - if isa(v, Const) - if !has_free_typevars(t) && !isa(v.val, t) - return Bottom - end - return v - elseif isa(v, Conditional) - if !(Bool <: t) - return Bottom - end - return v - end - return typeintersect(v, t) - end) -add_tfunc(isa, 2, 2, - function (v::ANY, t::ANY) - t, isexact = instanceof_tfunc(t) - if !has_free_typevars(t) - if t === Bottom - return Const(false) - elseif v ⊑ t - if isexact - return Const(true) - end - elseif isa(v, Const) || isa(v, Conditional) || (isleaftype(v) && !iskindtype(v)) - return Const(false) - elseif isexact && typeintersect(v, t) === Bottom - if !iskindtype(v) #= subtyping currently intentionally answers this query incorrectly for kinds =# - return Const(false) - end - end - end - # TODO: handle non-leaftype(t) by testing against lower and upper bounds - return Bool - end) -add_tfunc(<:, 2, 2, - function (a::ANY, b::ANY) - a, isexact_a = instanceof_tfunc(a) - b, isexact_b = instanceof_tfunc(b) - if !has_free_typevars(a) && !has_free_typevars(b) - if a <: b - if isexact_b || a === Bottom - return Const(true) - end - else - if isexact_a || (b !== Bottom && typeintersect(a, b) === Union{}) - return Const(false) - end - end - end - return Bool - end) - -function type_depth(t::ANY) - if t === Bottom - return 0 - elseif isa(t, Union) - return max(type_depth(t.a), type_depth(t.b)) + 1 - elseif isa(t, DataType) - return (t::DataType).depth - elseif isa(t, UnionAll) - if t.var.ub === Any && t.var.lb === Bottom - return type_depth(t.body) - end - return max(type_depth(t.var.ub)+1, type_depth(t.var.lb)+1, type_depth(t.body)) - end - return 0 -end - -function limit_type_depth(t::ANY, d::Int) - r = limit_type_depth(t, d, true, TypeVar[]) - @assert !isa(t, Type) || t <: r - return r -end - -function limit_type_depth(t::ANY, d::Int, cov::Bool, vars::Vector{TypeVar}=TypeVar[]) - if isa(t,Union) - if d > MAX_TYPE_DEPTH - if cov - return Any - else - var = TypeVar(:_) - push!(vars, var) - return var - end - end - return Union{limit_type_depth(t.a, d+1, cov, vars), - limit_type_depth(t.b, d+1, cov, vars)} - elseif isa(t,UnionAll) - v = t.var - if v.ub === Any - if v.lb === Bottom - return UnionAll(t.var, limit_type_depth(t.body, d, cov, vars)) - end - ub = Any - else - ub = limit_type_depth(v.ub, d+1, true) - end - if v.lb === Bottom || type_depth(v.lb) > MAX_TYPE_DEPTH - # note: lower bounds need to be widened by making them lower - lb = Bottom - else - lb = v.lb - end - v2 = TypeVar(v.name, lb, ub) - return UnionAll(v2, limit_type_depth(t{v2}, d, cov, vars)) - elseif !isa(t,DataType) - return t - end - P = t.parameters - isempty(P) && return t - if d > MAX_TYPE_DEPTH - if isvarargtype(t) - # never replace Vararg with non-Vararg - return Vararg{limit_type_depth(P[1], d, cov, vars), P[2]} - end - widert = t.name.wrapper - if !(t <: widert) - # This can happen when a typevar has bounds too wide for its context, e.g. - # `Complex{T} where T` is not a subtype of `Complex`. In that case widen even - # faster to something safe to ensure the result is a supertype of the input. - widert = Any - end - cov && return widert - var = TypeVar(:_, widert) - push!(vars, var) - return var - end - stillcov = cov && (t.name === Tuple.name) - Q = map(x->limit_type_depth(x, d+1, stillcov, vars), P) - R = t.name.wrapper{Q...} - if cov && !stillcov - for var in vars - R = UnionAll(var, R) - end - end - return R -end - -const DataType_name_fieldindex = fieldindex(DataType, :name) -const DataType_parameters_fieldindex = fieldindex(DataType, :parameters) -const DataType_types_fieldindex = fieldindex(DataType, :types) -const DataType_super_fieldindex = fieldindex(DataType, :super) - -const TypeName_name_fieldindex = fieldindex(TypeName, :name) -const TypeName_module_fieldindex = fieldindex(TypeName, :module) -const TypeName_wrapper_fieldindex = fieldindex(TypeName, :wrapper) - -function const_datatype_getfield_tfunc(sv, fld) - if (fld == DataType_name_fieldindex || - fld == DataType_parameters_fieldindex || - fld == DataType_types_fieldindex || - fld == DataType_super_fieldindex) - return abstract_eval_constant(getfield(sv, fld)) - end - return nothing -end - -function getfield_tfunc(s00::ANY, name) - if isa(s00, TypeVar) - s00 = s00.ub - end - s = unwrap_unionall(s00) - if isa(s, Union) - return tmerge(rewrap(getfield_tfunc(s.a, name),s00), - rewrap(getfield_tfunc(s.b, name),s00)) - elseif isa(s, Conditional) - return Bottom # Bool has no fields - elseif isa(s, Const) || isType(s) - if !isa(s, Const) - p1 = s.parameters[1] - if !isleaftype(p1) - return Any - end - sv = p1 - else - sv = s.val - end - if isa(name, Const) - nv = name.val - if isa(sv, UnionAll) - if nv === :var || nv === 1 - return Const(sv.var) - elseif nv === :body || nv === 2 - return Const(sv.body) - end - elseif isa(sv, DataType) - t = const_datatype_getfield_tfunc(sv, isa(nv, Symbol) ? - fieldindex(DataType, nv, false) : nv) - t !== nothing && return t - elseif isa(sv, TypeName) - fld = isa(nv, Symbol) ? fieldindex(TypeName, nv, false) : nv - if (fld == TypeName_name_fieldindex || - fld == TypeName_module_fieldindex || - fld == TypeName_wrapper_fieldindex) - return abstract_eval_constant(getfield(sv, fld)) - end - end - if isa(sv, Module) && isa(nv, Symbol) - return abstract_eval_global(sv, nv) - end - if !(isa(nv,Symbol) || isa(nv,Int)) - return Bottom - end - if (isa(sv, SimpleVector) || isimmutable(sv)) && isdefined(sv, nv) - return abstract_eval_constant(getfield(sv, nv)) - end - end - s = typeof(sv) - end - if !isa(s,DataType) || s.abstract - return Any - end - if s <: Tuple && name ⊑ Symbol - return Bottom - end - if s <: Module - if name ⊑ Int - return Bottom - end - return Any - end - if isempty(s.types) - return Bottom - end - if isa(name, Conditional) - return Bottom # can't index fields with Bool - end - if !isa(name, Const) - if !(Int <: name || Symbol <: name) - return Bottom - end - if length(s.types) == 1 - return rewrap_unionall(unwrapva(s.types[1]), s00) - end - # union together types of all fields - R = reduce(tmerge, Bottom, map(t -> rewrap_unionall(unwrapva(t), s00), s.types)) - # do the same limiting as the known-symbol case to preserve type-monotonicity - if isempty(s.parameters) - return R - end - return limit_type_depth(R, 0) - end - fld = name.val - if isa(fld,Symbol) - fld = fieldindex(s, fld, false) - end - if !isa(fld,Int) - return Bottom - end - nf = length(s.types) - if s <: Tuple && fld >= nf && isvarargtype(s.types[nf]) - return rewrap_unionall(unwrapva(s.types[nf]), s00) - end - if fld < 1 || fld > nf - return Bottom - end - if isType(s00) && isleaftype(s00.parameters[1]) - sp = s00.parameters[1] - elseif isa(s00, Const) && isa(s00.val, DataType) - sp = s00.val - else - sp = nothing - end - if sp !== nothing - t = const_datatype_getfield_tfunc(sp, fld) - t !== nothing && return t - end - R = s.types[fld] - if isempty(s.parameters) - return R - end - # TODO jb/subtype is this still necessary? - # conservatively limit the type depth here, - # since the UnionAll type bound is otherwise incorrect - # in the current type system - return rewrap_unionall(limit_type_depth(R, 0), s00) -end -add_tfunc(getfield, 2, 2, (s::ANY, name::ANY) -> getfield_tfunc(s, name)) -add_tfunc(setfield!, 3, 3, (o::ANY, f::ANY, v::ANY) -> v) -function fieldtype_tfunc(s0::ANY, name::ANY) - if s0 === Any || s0 === Type || DataType ⊑ s0 || UnionAll ⊑ s0 - return Type - end - # fieldtype only accepts DataType and UnionAll, errors on `Module` - if isa(s0,Const) && (!(isa(s0.val,DataType) || isa(s0.val,UnionAll)) || s0.val === Module) - return Bottom - end - if s0 == Type{Module} || s0 == Type{Union{}} || isa(s0, Conditional) - return Bottom - end - - s = instanceof_tfunc(s0)[1] - u = unwrap_unionall(s) - - if isa(u,Union) - return tmerge(rewrap(fieldtype_tfunc(u.a, name),s), - rewrap(fieldtype_tfunc(u.b, name),s)) - end - - if !isa(u,DataType) || u.abstract - return Type - end - ftypes = u.types - if isempty(ftypes) - return Bottom - end - - if !isa(name, Const) - if !(Int <: name || Symbol <: name) - return Bottom - end - return reduce(tmerge, Bottom, - Any[ fieldtype_tfunc(s0, Const(i)) for i = 1:length(ftypes) ]) - end - - fld = name.val - if isa(fld,Symbol) - fld = fieldindex(u, fld, false) - end - if !isa(fld, Int) - return Bottom - end - nf = length(ftypes) - if u.name === Tuple.name && fld >= nf && isvarargtype(ftypes[nf]) - ft = unwrapva(ftypes[nf]) - elseif fld < 1 || fld > nf - return Bottom - else - ft = ftypes[fld] - end - - exact = (isa(s0, Const) || isType(s0)) && !has_free_typevars(s) - ft = rewrap_unionall(ft,s) - if exact - return Const(ft) - end - return Type{<:ft} -end -add_tfunc(fieldtype, 2, 2, fieldtype_tfunc) - -function valid_tparam(x::ANY) - if isa(x,Tuple) - for t in x - !valid_tparam(t) && return false - end - return true - end - return isa(x,Int) || isa(x,Symbol) || isa(x,Bool) || (!isa(x,Type) && isbits(x)) -end - -has_free_typevars(t::ANY) = ccall(:jl_has_free_typevars, Cint, (Any,), t)!=0 - -# TODO: handle e.g. apply_type(T, R::Union{Type{Int32},Type{Float64}}) -function apply_type_tfunc(headtypetype::ANY, args::ANY...) - if isa(headtypetype, Const) - headtype = headtypetype.val - elseif isType(headtypetype) && isleaftype(headtypetype.parameters[1]) - headtype = headtypetype.parameters[1] - else - return Any - end - largs = length(args) - if headtype === Union - largs == 0 && return Const(Bottom) - largs == 1 && return args[1] - for i = 1:largs - ai = args[i] - if !isa(ai, Const) || !isa(ai.val, Type) - if !isType(ai) - return Any - end - end - end - ty = Union{} - allconst = true - for i = 1:largs - ai = args[i] - if isType(ai) - aty = ai.parameters[1] - isleaftype(aty) || (allconst = false) - else - aty = (ai::Const).val - end - ty = Union{ty, aty} - end - return allconst ? Const(ty) : Type{ty} - end - istuple = (headtype == Tuple) - if !istuple && !isa(headtype, UnionAll) - # TODO: return `Bottom` for trying to apply a non-UnionAll - return Any - end - uncertain = false - canconst = true - tparams = Any[] - outervars = Any[] - for i = 1:largs - ai = args[i] - if isType(ai) - aip1 = ai.parameters[1] - canconst &= !has_free_typevars(aip1) - push!(tparams, aip1) - elseif isa(ai, Const) && (isa(ai.val, Type) || isa(ai.val, TypeVar) || valid_tparam(ai.val)) - push!(tparams, ai.val) - elseif isa(ai, PartialTypeVar) - canconst = false - push!(tparams, ai.tv) - else - # TODO: return `Bottom` for trying to apply a non-UnionAll - uncertain = true - # These blocks improve type info but make compilation a bit slower. - # XXX - #unw = unwrap_unionall(ai) - #isT = isType(unw) - #if isT && isa(ai,UnionAll) && contains_is(outervars, ai.var) - # ai = rename_unionall(ai) - # unw = unwrap_unionall(ai) - #end - if istuple - if i == largs - push!(tparams, Vararg) - # XXX - #elseif isT - # push!(tparams, rewrap_unionall(unw.parameters[1], ai)) - else - push!(tparams, Any) - end - # XXX - #elseif isT - # push!(tparams, unw.parameters[1]) - # while isa(ai, UnionAll) - # push!(outervars, ai.var) - # ai = ai.body - # end - else - v = TypeVar(:_) - push!(tparams, v) - push!(outervars, v) - end - end - end - local appl - try - appl = apply_type(headtype, tparams...) - catch ex - # type instantiation might fail if one of the type parameters - # doesn't match, which could happen if a type estimate is too coarse - return Type{<:headtype} - end - !uncertain && canconst && return Const(appl) - if isvarargtype(headtype) - return Type - end - if uncertain && type_too_complex(appl,0) - return Type{<:headtype} - end - if istuple - return Type{<:appl} - end - ans = Type{appl} - for i = length(outervars):-1:1 - ans = UnionAll(outervars[i], ans) - end - return ans -end -add_tfunc(apply_type, 1, IInf, apply_type_tfunc) - -@pure function type_typeof(v::ANY) - if isa(v, Type) - return Type{v} - end - return typeof(v) -end - -function invoke_tfunc(f::ANY, types::ANY, argtype::ANY, sv::InferenceState) - if !isleaftype(Type{types}) - return Any - end - argtype = typeintersect(types,limit_tuple_type(argtype, sv.params)) - if argtype === Bottom - return Bottom - end - ft = type_typeof(f) - types = Tuple{ft, types.parameters...} - argtype = Tuple{ft, argtype.parameters...} - entry = ccall(:jl_gf_invoke_lookup, Any, (Any, UInt), types, sv.params.world) - if entry === nothing - return Any - end - meth = entry.func - (ti, env) = ccall(:jl_match_method, Ref{SimpleVector}, (Any, Any), - argtype, meth.sig) - rt, edge = typeinf_edge(meth::Method, ti, env, sv) - edge !== nothing && add_backedge!(edge::MethodInstance, sv) - return rt -end - -function tuple_tfunc(argtype::ANY) - if isa(argtype, DataType) && argtype.name === Tuple.name - p = Any[ isType(x) && !isa(x.parameters[1], TypeVar) ? typeof(x.parameters[1]) : x - for x in argtype.parameters ] - t = Tuple{p...} - # replace a singleton type with its equivalent Const object - isdefined(t, :instance) && return Const(t.instance) - return t - end - return argtype -end - -function builtin_tfunction(f::ANY, argtypes::Array{Any,1}, - sv::Union{InferenceState,Void}, params::InferenceParams = sv.params) - isva = !isempty(argtypes) && isvarargtype(argtypes[end]) - if f === tuple - for a in argtypes - if !isa(a, Const) - return tuple_tfunc(limit_tuple_depth(params, argtypes_to_type(argtypes))) - end - end - return Const(tuple(anymap(a->a.val, argtypes)...)) - elseif f === svec - return SimpleVector - elseif f === arrayset - if length(argtypes) < 3 && !isva - return Bottom - end - a1 = argtypes[1] - if isvarargtype(a1) - return unwrap_unionall(a1).parameters[1] - end - return a1 - elseif f === arrayref - if length(argtypes) < 2 && !isva - return Bottom - end - a = widenconst(argtypes[1]) - if a <: Array - if isa(a,DataType) && (isa(a.parameters[1],Type) || isa(a.parameters[1],TypeVar)) - # TODO: the TypeVar case should not be needed here - a = a.parameters[1] - return isa(a,TypeVar) ? a.ub : a - elseif isa(a,UnionAll) && !has_free_typevars(a) - unw = unwrap_unionall(a) - if isa(unw,DataType) - return rewrap_unionall(unw.parameters[1], a) - end - end - end - return Any - elseif f === Expr - if length(argtypes) < 1 && !isva - return Bottom - end - return Expr - elseif f === invoke - if length(argtypes)>1 && isa(argtypes[1], Const) - af = argtypes[1].val - sig = argtypes[2] - if isa(sig, Const) - sigty = sig.val - elseif isType(sig) - sigty = sig.parameters[1] - else - sigty = nothing - end - if isa(sigty, Type) && sigty <: Tuple && sv !== nothing - return invoke_tfunc(af, sigty, argtypes_to_type(argtypes[3:end]), sv) - end - end - return Any - end - if isva - return Any - end - if isa(f, IntrinsicFunction) - iidx = Int(reinterpret(Int32, f::IntrinsicFunction)) + 1 - if iidx < 0 || iidx > length(t_ifunc) - # invalid intrinsic - return Any - end - tf = t_ifunc[iidx] - else - fidx = findfirst(t_ffunc_key, f) - if fidx == 0 - # unknown/unhandled builtin function - return Any - end - tf = t_ffunc_val[fidx] - end - tf = tf::Tuple{Int, Int, Any} - if !(tf[1] <= length(argtypes) <= tf[2]) - # wrong # of args - return Bottom - end - return tf[3](argtypes...) -end - -limit_tuple_depth(params::InferenceParams, t::ANY) = limit_tuple_depth_(params,t,0) - -function limit_tuple_depth_(params::InferenceParams, t::ANY, d::Int) - if isa(t,Union) - # also limit within Union types. - # may have to recur into other stuff in the future too. - return Union{limit_tuple_depth_(params, t.a, d+1), - limit_tuple_depth_(params, t.b, d+1)} - elseif isa(t,UnionAll) - ub = limit_tuple_depth_(params, t.var.ub, d) - if ub !== t.var.ub - var = TypeVar(t.var.name, t.var.lb, ub) - body = t{var} - else - var = t.var - body = t.body - end - body = limit_tuple_depth_(params, body, d) - return UnionAll(var, body) - elseif !(isa(t,DataType) && t.name === Tuple.name) - return t - elseif d > params.MAX_TUPLE_DEPTH - return Tuple - end - p = map(x->limit_tuple_depth_(params,x,d+1), t.parameters) - Tuple{p...} -end - -limit_tuple_type = (t::ANY, params::InferenceParams) -> limit_tuple_type_n(t, params.MAX_TUPLETYPE_LEN) - -function limit_tuple_type_n(t::ANY, lim::Int) - if isa(t,UnionAll) - return UnionAll(t.var, limit_tuple_type_n(t.body, lim)) - end - p = t.parameters - n = length(p) - if n > lim - tail = reduce(typejoin, Bottom, Any[p[lim:(n-1)]..., unwrapva(p[n])]) - return Tuple{p[1:(lim-1)]..., Vararg{tail}} - end - return t -end - -# return an upper-bound on type `a` with type `b` removed -# such that `return <: a` && `Union{return, b} == Union{a, b}` -function typesubtract(a::ANY, b::ANY) - if a <: b - return Bottom - end - if isa(a, Union) - return Union{typesubtract(a.a, b), - typesubtract(a.b, b)} - end - return a # TODO: improve this bound? -end - -#### recursing into expression #### - -function abstract_call_gf_by_type(f::ANY, atype::ANY, sv::InferenceState) - tm = _topmod(sv) - # don't consider more than N methods. this trades off between - # compiler performance and generated code performance. - # typically, considering many methods means spending lots of time - # obtaining poor type information. - # It is important for N to be >= the number of methods in the error() - # function, so we can still know that error() is always Bottom. - # here I picked 4. - argtype = limit_tuple_type(atype, sv.params) - argtypes = unwrap_unionall(argtype).parameters - ft = unwrap_unionall(argtypes[1]) # TODO: ccall jl_first_argument_datatype here - isa(ft, DataType) || return Any # the function being called is unknown. can't properly handle this backedge right now - ftname = ft.name - isdefined(ftname, :mt) || return Any # not callable. should be Bottom, but can't track this backedge right now - if ftname === _Type_name - tname = ft.parameters[1] - if isa(tname, TypeVar) - tname = tname.ub - end - tname = unwrap_unionall(tname) - if !isa(tname, DataType) - # can't track the backedge to the ctor right now - # for things like Union - return Any - end - end - min_valid = UInt[typemin(UInt)] - max_valid = UInt[typemax(UInt)] - applicable = _methods_by_ftype(argtype, 4, sv.params.world, min_valid, max_valid) - rettype = Bottom - if applicable === false - # this means too many methods matched - return Any - end - applicable = applicable::Array{Any,1} - fullmatch = false - for (m::SimpleVector) in applicable - sig = m[1] - sigtuple = unwrap_unionall(sig)::DataType - method = m[3]::Method - sparams = m[2]::SimpleVector - recomputesvec = false - if !fullmatch && (argtype <: method.sig) - fullmatch = true - end - - # limit argument type tuple growth - msig = unwrap_unionall(method.sig) - lsig = length(msig.parameters) - ls = length(sigtuple.parameters) - td = type_depth(sig) - mightlimitlength = ls > lsig + 1 - mightlimitdepth = td > 2 - limitlength = false - if mightlimitlength || mightlimitdepth - # TODO: FIXME: this heuristic depends on non-local state making type-inference unpredictable - cyclei = 0 - infstate = sv - while infstate !== nothing - infstate = infstate::InferenceState - if isdefined(infstate.linfo, :def) && method === infstate.linfo.def - if mightlimitlength && ls > length(unwrap_unionall(infstate.linfo.specTypes).parameters) - limitlength = true - end - if mightlimitdepth && td > type_depth(infstate.linfo.specTypes) - # impose limit if we recur and the argument types grow beyond MAX_TYPE_DEPTH - if td > MAX_TYPE_DEPTH - sig = limit_type_depth(sig, 0) - sigtuple = unwrap_unionall(sig) - recomputesvec = true - break - else - p1, p2 = sigtuple.parameters, unwrap_unionall(infstate.linfo.specTypes).parameters - if length(p2) == ls - limitdepth = false - newsig = Vector{Any}(ls) - for i = 1:ls - if p1[i] <: Function && type_depth(p1[i]) > type_depth(p2[i]) && - isa(p1[i],DataType) - # if a Function argument is growing (e.g. nested closures) - # then widen to the outermost function type. without this - # inference fails to terminate on do_quadgk. - newsig[i] = p1[i].name.wrapper - limitdepth = true - else - newsig[i] = limit_type_depth(p1[i], 1) - end - end - if limitdepth - sigtuple = Tuple{newsig...} - sig = rewrap_unionall(sigtuple, sig) - recomputesvec = true - break - end - end - end - end - end - # iterate through the cycle before walking to the parent - if cyclei < length(infstate.callers_in_cycle) - cyclei += 1 - infstate = infstate.callers_in_cycle[cyclei] - else - cyclei = 0 - infstate = infstate.parent - end - end - end - - # limit length based on size of definition signature. - # for example, given function f(T, Any...), limit to 3 arguments - # instead of the default (MAX_TUPLETYPE_LEN) - if limitlength - if !istopfunction(tm, f, :promote_typeof) - fst = sigtuple.parameters[lsig + 1] - allsame = true - # allow specializing on longer arglists if all the trailing - # arguments are the same, since there is no exponential - # blowup in this case. - for i = (lsig + 2):ls - if sigtuple.parameters[i] != fst - allsame = false - break - end - end - if !allsame - sigtuple = limit_tuple_type_n(sigtuple, lsig + 1) - sig = rewrap_unionall(sigtuple, sig) - recomputesvec = true - end - end - end - - # if sig changed, may need to recompute the sparams environment - if recomputesvec && !isempty(sparams) - recomputed = ccall(:jl_env_from_type_intersection, Ref{SimpleVector}, (Any, Any), sig, method.sig) - sig = recomputed[1] - if !isa(unwrap_unionall(sig), DataType) # probably Union{} - rettype = Any - break - end - sparams = recomputed[2]::SimpleVector - end - rt, edge = typeinf_edge(method, sig, sparams, sv) - edge !== nothing && add_backedge!(edge::MethodInstance, sv) - rettype = tmerge(rettype, rt) - if rettype === Any - break - end - end - if !(fullmatch || rettype === Any) - # also need an edge to the method table in case something gets - # added that did not intersect with any existing method - add_mt_backedge(ftname.mt, argtype, sv) - update_valid_age!(min_valid[1], max_valid[1], sv) - end - if isempty(applicable) - # TODO: this is needed because type intersection is wrong in some cases - return Any - end - #print("=> ", rettype, "\n") - return rettype -end - -# determine whether `ex` abstractly evals to constant `c` -function abstract_evals_to_constant(ex::ANY, c::ANY, vtypes::VarTable, sv::InferenceState) - av = abstract_eval(ex, vtypes, sv) - return isa(av,Const) && av.val === c -end - -# `typ` is the inferred type for expression `arg`. -# if the expression constructs a container (e.g. `svec(x,y,z)`), -# refine its type to an array of element types. -# Union of Tuples of the same length is converted to Tuple of Unions. -# returns an array of types -function precise_container_type(arg::ANY, typ::ANY, vtypes::VarTable, sv::InferenceState) - if isa(typ, Const) - val = typ.val - if isa(val, SimpleVector) || isa(val, Tuple) - return Any[ abstract_eval_constant(x) for x in val ] - end - end - - tti0 = widenconst(typ) - tti = unwrap_unionall(tti0) - if isa(arg, Expr) && arg.head === :call && (abstract_evals_to_constant(arg.args[1], svec, vtypes, sv) || - abstract_evals_to_constant(arg.args[1], tuple, vtypes, sv)) - aa = arg.args - result = Any[ (isa(aa[j],Expr) ? aa[j].typ : abstract_eval(aa[j],vtypes,sv)) for j=2:length(aa) ] - if _any(isvarargtype, result) - return Any[Vararg{Any}] - end - return result - elseif isa(tti, Union) - utis = uniontypes(tti) - if _any(t -> !isa(t,DataType) || !(t <: Tuple) || !isknownlength(t), utis) - return Any[Vararg{Any}] - end - result = Any[rewrap_unionall(p, tti0) for p in utis[1].parameters] - for t in utis[2:end] - if length(t.parameters) != length(result) - return Any[Vararg{Any}] - end - for j in 1:length(t.parameters) - result[j] = tmerge(result[j], rewrap_unionall(t.parameters[j], tti0)) - end - end - return result - elseif isa(tti0,DataType) && tti0 <: Tuple - if isvatuple(tti0) && length(tti0.parameters) == 1 - return Any[Vararg{unwrapva(tti0.parameters[1])}] - else - return tti0.parameters - end - elseif tti0 <: Array - return Any[Vararg{eltype(tti0)}] - else - return Any[abstract_iteration(typ, vtypes, sv)] - end -end - -# simulate iteration protocol on container type up to fixpoint -function abstract_iteration(itertype::ANY, vtypes::VarTable, sv::InferenceState) - tm = _topmod(sv) - if !isdefined(tm, :start) || !isdefined(tm, :next) || !isconst(tm, :start) || !isconst(tm, :next) - return Vararg{Any} - end - startf = getfield(tm, :start) - nextf = getfield(tm, :next) - statetype = abstract_call(startf, (), Any[Const(startf), itertype], vtypes, sv) - statetype === Bottom && return Bottom - valtype = Bottom - while valtype !== Any - nt = abstract_call(nextf, (), Any[Const(nextf), itertype, statetype], vtypes, sv) - nt = widenconst(nt) - if !isa(nt, DataType) || !(nt <: Tuple) || isvatuple(nt) || length(nt.parameters) != 2 - return Vararg{Any} - end - if nt.parameters[1] <: valtype && nt.parameters[2] <: statetype - break - end - valtype = tmerge(valtype, nt.parameters[1]) - statetype = tmerge(statetype, nt.parameters[2]) - end - return Vararg{valtype} -end - -# do apply(af, fargs...), where af is a function value -function abstract_apply(af::ANY, fargs::Vector{Any}, aargtypes::Vector{Any}, vtypes::VarTable, sv::InferenceState) - res = Union{} - nargs = length(fargs) - assert(nargs == length(aargtypes)) - splitunions = countunionsplit(aargtypes) <= sv.params.MAX_APPLY_UNION_ENUM - ctypes = Any[Any[]] - for i = 1:nargs - if aargtypes[i] === Any - # bail out completely and infer as f(::Any...) - # instead could keep what we got so far and just append a Vararg{Any} (by just - # using the normal logic from below), but that makes the time of the subarray - # test explode - ctypes = Any[Any[Vararg{Any}]] - break - end - ctypes´ = [] - for ti in (splitunions ? uniontypes(aargtypes[i]) : Any[aargtypes[i]]) - cti = precise_container_type(fargs[i], ti, vtypes, sv) - for ct in ctypes - if !isempty(ct) && isvarargtype(ct[end]) - tail = foldl((a,b)->tmerge(a,unwrapva(b)), unwrapva(ct[end]), cti) - push!(ctypes´, push!(ct[1:end-1], Vararg{widenconst(tail)})) - else - push!(ctypes´, append_any(ct, cti)) - end - end - end - ctypes = ctypes´ - end - for ct in ctypes - if length(ct) > sv.params.MAX_TUPLETYPE_LEN - tail = foldl((a,b)->tmerge(a,unwrapva(b)), Bottom, ct[sv.params.MAX_TUPLETYPE_LEN:end]) - resize!(ct, sv.params.MAX_TUPLETYPE_LEN) - ct[end] = Vararg{widenconst(tail)} - end - at = append_any(Any[Const(af)], ct) - res = tmerge(res, abstract_call(af, (), at, vtypes, sv)) - if res === Any - break - end - end - return res -end - -function return_type_tfunc(argtypes::ANY, vtypes::VarTable, sv::InferenceState) - if length(argtypes) == 3 - tt = argtypes[3] - if isa(tt, Const) || (isType(tt) && !has_free_typevars(tt)) - aft = argtypes[2] - if isa(aft, Const) || (isType(aft) && !has_free_typevars(aft)) || - (isleaftype(aft) && !(aft <: Builtin)) - af_argtype = isa(tt, Const) ? tt.val : tt.parameters[1] - if isa(af_argtype, DataType) && af_argtype <: Tuple - argtypes_vec = Any[aft, af_argtype.parameters...] - astype = argtypes_to_type(argtypes_vec) - if !(aft ⊑ Builtin) && - _methods_by_ftype(astype, 0, sv.params.world, - UInt[typemin(UInt)], UInt[typemax(UInt)]) !== false - # return_type returns Bottom if no methods match, even though - # inference doesn't necessarily. - return Const(Bottom) - end - if isa(aft, Const) - rt = abstract_call(aft.val, (), argtypes_vec, vtypes, sv) - elseif isconstType(aft) - rt = abstract_call(aft.parameters[1], (), argtypes_vec, vtypes, sv) - else - rt = abstract_call_gf_by_type(nothing, astype, sv) - end - if isa(rt, Const) - # output was computed to be constant - return Const(typeof(rt.val)) - elseif isleaftype(rt) || rt === Bottom - # output type was known for certain - return Const(rt) - elseif (isa(tt, Const) || isconstType(tt)) && - (isa(aft, Const) || isconstType(aft)) - # input arguments were known for certain - return Const(rt) - else - return Type{<:rt} - end - end - end - end - end - return NF -end - -function pure_eval_call(f::ANY, argtypes::ANY, atype::ANY, sv::InferenceState) - for i = 2:length(argtypes) - a = argtypes[i] - if !(isa(a,Const) || isconstType(a)) - return false - end - end - - min_valid = UInt[typemin(UInt)] - max_valid = UInt[typemax(UInt)] - meth = _methods_by_ftype(atype, 1, sv.params.world, min_valid, max_valid) - if meth === false || length(meth) != 1 - return false - end - meth = meth[1]::SimpleVector - method = meth[3]::Method - # TODO: check pure on the inferred thunk - if method.isstaged || !method.pure - return false - end - - args = Any[ (a=argtypes[i]; isa(a,Const) ? a.val : a.parameters[1]) for i in 2:length(argtypes) ] - try - value = Core._apply_pure(f, args) - # TODO: add some sort of edge(s) - return Const(value, true) - catch - return false - end -end - -argtypes_to_type(argtypes::Array{Any,1}) = Tuple{anymap(widenconst, argtypes)...} - -_Pair_name = nothing -function Pair_name() - global _Pair_name - if _Pair_name === nothing - if isdefined(Main, :Base) && isdefined(Main.Base, :Pair) - _Pair_name = Main.Base.Pair.body.body.name - end - end - return _Pair_name -end - -_typename(a) = Union{} -_typename(a::Vararg) = Any -_typename(a::TypeVar) = Any -_typename(a::DataType) = Const(a.name) -function _typename(a::Union) - ta = _typename(a.a) - tb = _typename(a.b) - ta === tb ? tb : (ta === Any || tb === Any) ? Any : Union{} -end -_typename(union::UnionAll) = _typename(union.body) - -# N.B.: typename maps type equivalence classes to a single value -typename_static(t::Const) = _typename(t.val) -typename_static(t::ANY) = isType(t) ? _typename(t.parameters[1]) : Any - -function abstract_call(f::ANY, fargs::Union{Tuple{},Vector{Any}}, argtypes::Vector{Any}, vtypes::VarTable, sv::InferenceState) - if f === _apply - length(fargs) > 1 || return Any - aft = argtypes[2] - if isa(aft, Const) - af = aft.val - else - if isType(aft) && isleaftype(aft.parameters[1]) - af = aft.parameters[1] - elseif isleaftype(aft) && isdefined(aft, :instance) - af = aft.instance - else - # TODO jb/functions: take advantage of case where non-constant `af`'s type is known - return Any - end - end - return abstract_apply(af, fargs[3:end], argtypes[3:end], vtypes, sv) - end - - la = length(argtypes) - for i = 2:(la - 1) - if isvarargtype(argtypes[i]) - return Any - end - end - - tm = _topmod(sv) - if isa(f, Builtin) || isa(f, IntrinsicFunction) - rt = builtin_tfunction(f, argtypes[2:end], sv) - if rt === Bool && isa(fargs, Vector{Any}) - # perform very limited back-propagation of type information for `is` and `isa` - if f === isa - a = fargs[2] - if isa(a, fieldtype(Conditional, :var)) - aty = widenconst(argtypes[2]) - tty_ub, isexact_tty = instanceof_tfunc(argtypes[3]) - if isexact_tty && !isa(tty_ub, TypeVar) - tty_lb = tty_ub # TODO: this would be wrong if !isexact_tty, but instanceof_tfunc doesn't preserve this info - if !has_free_typevars(tty_lb) && !has_free_typevars(tty_ub) - ifty = typeintersect(aty, tty_ub) - elsety = typesubtract(aty, tty_lb) - if ifty != elsety - return Conditional(a, ifty, elsety) - end - end - end - return Bool - end - elseif f === (===) - a = fargs[2] - b = fargs[3] - aty = argtypes[2] - bty = argtypes[3] - # if doing a comparison to a singleton, consider returning a `Conditional` instead - if isa(aty, Const) && isa(b, fieldtype(Conditional, :var)) - if isdefined(typeof(aty.val), :instance) # can only widen a if it is a singleton - return Conditional(b, aty, typesubtract(widenconst(bty), typeof(aty.val))) - end - return Conditional(b, aty, bty) - end - if isa(bty, Const) && isa(a, fieldtype(Conditional, :var)) - if isdefined(typeof(bty.val), :instance) # same for b - return Conditional(a, bty, typesubtract(widenconst(aty), typeof(bty.val))) - end - return Conditional(a, bty, aty) - end - end - end - return isa(rt, TypeVar) ? rt.ub : rt - elseif f === Core.kwfunc - if length(fargs) == 2 - ft = widenconst(argtypes[2]) - if isa(ft, DataType) && isdefined(ft.name, :mt) && isdefined(ft.name.mt, :kwsorter) - return Const(ft.name.mt.kwsorter) - end - end - return Any - elseif f === TypeVar - lb = Union{} - ub = Any - ub_certain = lb_certain = true - if length(fargs) >= 2 && isa(argtypes[2], Const) - nv = argtypes[2].val - ubidx = 3 - if length(fargs) >= 4 - ubidx = 4 - if isa(argtypes[3], Const) - lb = argtypes[3].val - elseif isType(argtypes[3]) - lb = argtypes[3].parameters[1] - lb_certain = false - else - return TypeVar - end - end - if length(fargs) >= ubidx - if isa(argtypes[ubidx], Const) - ub = argtypes[ubidx].val - elseif isType(argtypes[ubidx]) - ub = argtypes[ubidx].parameters[1] - ub_certain = false - else - return TypeVar - end - end - tv = TypeVar(nv, lb, ub) - return PartialTypeVar(tv, lb_certain, ub_certain) - end - return TypeVar - elseif f === UnionAll - if length(fargs) == 3 - canconst = true - if isa(argtypes[3], Const) - body = argtypes[3].val - elseif isType(argtypes[3]) - body = argtypes[3].parameters[1] - canconst = false - else - return Any - end - if !isa(body, Type) && !isa(body, TypeVar) - return Any - end - has_free_typevars(body) || return body - if isa(argtypes[2], Const) - tv = argtypes[2].val - elseif isa(argtypes[2], PartialTypeVar) - ptv = argtypes[2] - tv = ptv.tv - canconst = false - else - return Any - end - !isa(tv, TypeVar) && return Any - theunion = UnionAll(tv, body) - ret = canconst ? abstract_eval_constant(theunion) : Type{theunion} - return ret - end - return Any - elseif f === return_type - rt_rt = return_type_tfunc(argtypes, vtypes, sv) - if rt_rt !== NF - return rt_rt - end - elseif length(fargs) == 2 && istopfunction(tm, f, :!) - aty = argtypes[2] - if isa(aty, Conditional) - abstract_call_gf_by_type(f, Tuple{typeof(f), Bool}, sv) # make sure we've inferred `!(::Bool)` - return Conditional(aty.var, aty.elsetype, aty.vtype) - end - elseif length(fargs) == 3 && istopfunction(tm, f, :!==) - rty = abstract_call((===), fargs, argtypes, vtypes, sv) - if isa(rty, Conditional) - return Conditional(rty.var, rty.elsetype, rty.vtype) # swap if-else - elseif isa(rty, Const) - return Const(rty.val === false) - end - return rty - elseif length(fargs) == 3 && istopfunction(tm, f, :(>:)) - # swap T1 and T2 arguments and call issubtype - fargs = Any[issubtype, fargs[3], fargs[2]] - argtypes = Any[typeof(issubtype), argtypes[3], argtypes[2]] - rty = abstract_call(issubtype, fargs, argtypes, vtypes, sv) - return rty - end - - if la>2 && argtypes[3] ⊑ Int - at2 = widenconst(argtypes[2]) - if la==3 && at2 <: SimpleVector && istopfunction(tm, f, :getindex) - if isa(argtypes[2], Const) && isa(argtypes[3], Const) - svecval = argtypes[2].val - idx = argtypes[3].val - if isa(idx, Int) && 1 <= idx <= length(svecval) && - isassigned(svecval, idx) - return Const(getindex(svecval, idx)) - end - end - elseif (at2 <: Tuple || - (isa(at2, DataType) && (at2::DataType).name === Pair_name())) - # allow tuple indexing functions to take advantage of constant - # index arguments. - if istopfunction(tm, f, :getindex) && la==3 - return getfield_tfunc(argtypes[2], argtypes[3]) - elseif istopfunction(tm, f, :next) && la==3 - t1 = widenconst(getfield_tfunc(argtypes[2], argtypes[3])) - return t1===Bottom ? Bottom : Tuple{t1, Int} - elseif istopfunction(tm, f, :indexed_next) && la==4 - t1 = widenconst(getfield_tfunc(argtypes[2], argtypes[3])) - return t1===Bottom ? Bottom : Tuple{t1, Int} - end - end - elseif la==2 && argtypes[2] ⊑ SimpleVector && istopfunction(tm, f, :length) - if isa(argtypes[2], Const) - return Const(length(argtypes[2].val)) - end - end - - atype = argtypes_to_type(argtypes) - t = pure_eval_call(f, argtypes, atype, sv) - t !== false && return t - - if istopfunction(tm, f, :typejoin) || f === return_type - return Type # don't try to infer these function edges directly -- it won't actually come up with anything useful - elseif length(argtypes) == 2 && istopfunction(tm, f, :typename) - return typename_static(argtypes[2]) - end - - if sv.params.inlining - # need to model the special inliner for ^ - # to ensure we have added the same edge - if isdefined(Main, :Base) && - ((isdefined(Main.Base, :^) && f === Main.Base.:^) || - (isdefined(Main.Base, :.^) && f === Main.Base.:.^)) && - length(argtypes) == 3 && (argtypes[3] ⊑ Int32 || argtypes[3] ⊑ Int64) - - a1 = argtypes[2] - basenumtype = Union{corenumtype, Main.Base.Complex64, Main.Base.Complex128, Main.Base.Rational} - if a1 ⊑ basenumtype - ftimes = Main.Base.:* - ta1 = widenconst(a1) - abstract_call_gf_by_type(ftimes, Tuple{typeof(ftimes), ta1, ta1}, sv) - end - end - end - return abstract_call_gf_by_type(f, atype, sv) -end - -function abstract_eval_call(e::Expr, vtypes::VarTable, sv::InferenceState) - argtypes = Any[abstract_eval(a, vtypes, sv) for a in e.args] - #print("call ", e.args[1], argtypes, "\n\n") - for x in argtypes - x === Bottom && return Bottom - end - ft = argtypes[1] - if isa(ft, Const) - f = ft.val - else - if isType(ft) && isleaftype(ft.parameters[1]) - f = ft.parameters[1] - elseif isleaftype(ft) && isdefined(ft, :instance) - f = ft.instance - else - for i = 2:(length(argtypes)-1) - if isvarargtype(argtypes[i]) - return Any - end - end - # non-constant function, but type is known - if (isleaftype(ft) || ft <: Type) && !(ft <: Builtin) && !(ft <: IntrinsicFunction) - return abstract_call_gf_by_type(nothing, argtypes_to_type(argtypes), sv) - end - return Any - end - end - return abstract_call(f, e.args, argtypes, vtypes, sv) -end - -const _Ref_name = Ref.body.name - -function abstract_eval(e::ANY, vtypes::VarTable, sv::InferenceState) - if isa(e, QuoteNode) - return abstract_eval_constant((e::QuoteNode).value) - elseif isa(e, SSAValue) - return abstract_eval_ssavalue(e::SSAValue, sv.src) - elseif isa(e, Slot) - return vtypes[slot_id(e)].typ - elseif isa(e, Symbol) - return abstract_eval_global(sv.mod, e) - elseif isa(e,GlobalRef) - return abstract_eval_global(e.mod, e.name) - end - - if !isa(e, Expr) - return abstract_eval_constant(e) - end - e = e::Expr - if e.head === :call - t = abstract_eval_call(e, vtypes, sv) - elseif e.head === :null - t = Void - elseif e.head === :new - t = instanceof_tfunc(abstract_eval(e.args[1], vtypes, sv))[1] - for i = 2:length(e.args) - if abstract_eval(e.args[i], vtypes, sv) === Bottom - rt = Bottom - end - end - elseif e.head === :& - abstract_eval(e.args[1], vtypes, sv) - t = Any - elseif e.head === :foreigncall - rt = e.args[2] - if isdefined(sv.linfo, :def) - spsig = sv.linfo.def.sig - if isa(spsig, UnionAll) - if !isempty(sv.linfo.sparam_vals) - env = data_pointer_from_objref(sv.linfo.sparam_vals) + sizeof(Ptr{Void}) - rt = ccall(:jl_instantiate_type_in_env, Any, (Any, Any, Ptr{Any}), e.args[2], spsig, env) - else - rt = rewrap_unionall(e.args[2], spsig) - end - end - end - abstract_eval(e.args[1], vtypes, sv) - for i = 3:length(e.args) - if abstract_eval(e.args[i], vtypes, sv) === Bottom - t = Bottom - end - end - if rt === Bottom - t = Bottom - elseif isa(rt, Type) - t = rt - if isa(t, DataType) && (t::DataType).name === _Ref_name - t = t.parameters[1] - if t === Any - t = Bottom # a return type of Box{Any} is invalid - end - end - for v in sv.linfo.sparam_vals - if isa(v,TypeVar) - t = UnionAll(v, t) - end - end - else - t = Any - end - elseif e.head === :static_parameter - n = e.args[1] - t = Any - if n <= length(sv.sp) - val = sv.sp[n] - if isa(val, TypeVar) && Any <: val.ub - # static param bound to typevar - # if the tvar does not refer to anything more specific than Any, - # the static param might actually be an integer, symbol, etc. - elseif has_free_typevars(val) - vs = ccall(:jl_find_free_typevars, Any, (Any,), val) - t = Type{val} - for v in vs - t = UnionAll(v, t) - end - else - t = abstract_eval_constant(val) - end - end - elseif e.head === :method - t = (length(e.args) == 1) ? Any : Void - elseif e.head === :copyast - t = abstract_eval(e.args[1], vtypes, sv) - elseif e.head === :inert - return abstract_eval_constant(e.args[1]) - elseif e.head === :invoke - error("type inference data-flow error: tried to double infer a function") - else - t = Any - end - if isa(t, TypeVar) - # no need to use a typevar as the type of an expression - t = t.ub - end - if isa(t, DataType) && isdefined(t, :instance) - # replace singleton types with their equivalent Const object - t = Const(t.instance) - end - if isa(t, Conditional) - e.typ = Bool - else - e.typ = t - end - return t -end - -const abstract_eval_constant = Const - -function abstract_eval_global(M::Module, s::Symbol) - if isdefined(M,s) && isconst(M,s) - return abstract_eval_constant(getfield(M,s)) - end - return Any -end - -function abstract_eval_ssavalue(s::SSAValue, src::CodeInfo) - typ = src.ssavaluetypes[s.id + 1] - if typ === NF - return Bottom - end - return typ -end - - -#### handling for statement-position expressions #### - -mutable struct StateUpdate - var::Union{Slot,SSAValue} - vtype::VarState - state::VarTable -end - -function abstract_interpret(e::ANY, vtypes::VarTable, sv::InferenceState) - !isa(e, Expr) && return vtypes - # handle assignment - if e.head === :(=) - t = abstract_eval(e.args[2], vtypes, sv) - t === Bottom && return () - lhs = e.args[1] - if isa(lhs, Slot) || isa(lhs, SSAValue) - # don't bother for GlobalRef - return StateUpdate(lhs, VarState(t, false), vtypes) - end - elseif e.head === :call || e.head === :foreigncall - t = abstract_eval(e, vtypes, sv) - t === Bottom && return () - elseif e.head === :gotoifnot - t = abstract_eval(e.args[1], vtypes, sv) - t === Bottom && return () - elseif e.head === :method - fname = e.args[1] - if isa(fname, Slot) - return StateUpdate(fname, VarState(Any, false), vtypes) - end - end - return vtypes -end - -function type_too_complex(t::ANY, d) - if d > MAX_TYPE_DEPTH - return true - elseif isa(t,Union) - return type_too_complex(t.a, d+1) || type_too_complex(t.b, d+1) - elseif isa(t,TypeVar) - return type_too_complex(t.lb,d+1) || type_too_complex(t.ub,d+1) - elseif isa(t,UnionAll) - return type_too_complex(t.var, d) || type_too_complex(t.body, d) - elseif isa(t,DataType) - for x in (t.parameters)::SimpleVector - if type_too_complex(x, d+1) - return true - end - end - end - return false -end - -## lattice operators - -function issubconditional(a::Conditional, b::Conditional) - avar = a.var - bvar = b.var - if (isa(avar, Slot) && isa(bvar, Slot) && slot_id(avar) === slot_id(bvar)) || - (isa(avar, SSAValue) && isa(bvar, SSAValue) && avar === bvar) - if a.vtype ⊑ b.vtype - if a.elsetype ⊑ b.elsetype - return true - end - end - end - return false -end - -function ⊑(a::ANY, b::ANY) - a === NF && return true - b === NF && return false - if isa(a, Conditional) - if isa(b, Conditional) - return issubconditional(a, b) - end - a = Bool - elseif isa(b, Conditional) - return a === Bottom - end - if isa(a, Const) - if isa(b, Const) - return a.val === b.val - end - return isa(a.val, widenconst(b)) - elseif isa(b, Const) - return a === Bottom - elseif !(isa(a, Type) || isa(a, TypeVar)) || - !(isa(b, Type) || isa(b, TypeVar)) - return a === b - else - return a <: b - end -end - -widenconst(c::Conditional) = Bool -function widenconst(c::Const) - if isa(c.val, Type) - if isvarargtype(c.val) - return Type - end - return Type{c.val} - else - return typeof(c.val) - end -end -widenconst(c::PartialTypeVar) = TypeVar -widenconst(t::ANY) = t - -issubstate(a::VarState, b::VarState) = (a.typ ⊑ b.typ && a.undef <= b.undef) - -# Meta expression head, these generally can't be deleted even when they are -# in a dead branch but can be ignored when analyzing uses/liveness. -is_meta_expr_head(head::Symbol) = - (head === :inbounds || head === :boundscheck || head === :meta || - head === :line || head === :simdloop) -is_meta_expr(ex::Expr) = is_meta_expr_head(ex.head) - -function tmerge(typea::ANY, typeb::ANY) - typea ⊑ typeb && return typeb - typeb ⊑ typea && return typea - if isa(typea, Conditional) && isa(typeb, Conditional) - if typea.var === typeb.var - vtype = tmerge(typea.vtype, typeb.vtype) - elsetype = tmerge(typea.elsetype, typeb.elsetype) - if vtype != elsetype - return Conditional(typea.var, vtype, elsetype) - end - end - return Bool - end - typea, typeb = widenconst(typea), widenconst(typeb) - typea === typeb && return typea - if !(isa(typea,Type) || isa(typea,TypeVar)) || !(isa(typeb,Type) || isa(typeb,TypeVar)) - return Any - end - if (typea <: Tuple) && (typeb <: Tuple) - if isa(typea, DataType) && isa(typeb, DataType) && length(typea.parameters) == length(typeb.parameters) && !isvatuple(typea) && !isvatuple(typeb) - return typejoin(typea, typeb) - end - if isa(typea, Union) || isa(typeb, Union) || (isa(typea,DataType) && length(typea.parameters)>3) || - (isa(typeb,DataType) && length(typeb.parameters)>3) - # widen tuples faster (see #6704), but not too much, to make sure we can infer - # e.g. (t::Union{Tuple{Bool},Tuple{Bool,Int}})[1] - return Tuple - end - end - u = Union{typea, typeb} - if unionlen(u) > MAX_TYPEUNION_LEN || type_too_complex(u, 0) - # don't let type unions get too big - # TODO: something smarter, like a common supertype - return Any - end - return u -end - -function smerge(sa::Union{NotFound,VarState}, sb::Union{NotFound,VarState}) - sa === sb && return sa - sa === NF && return sb - sb === NF && return sa - issubstate(sa, sb) && return sb - issubstate(sb, sa) && return sa - return VarState(tmerge(sa.typ, sb.typ), sa.undef | sb.undef) -end - -@inline tchanged(n::ANY, o::ANY) = o === NF || (n !== NF && !(n ⊑ o)) -@inline schanged(n::ANY, o::ANY) = (n !== o) && (o === NF || (n !== NF && !issubstate(n, o))) - -function stupdate!(state::Tuple{}, changes::StateUpdate) - newst = copy(changes.state) - if isa(changes.var, Slot) - newst[slot_id(changes.var::Slot)] = changes.vtype - end - return newst -end - -function stupdate!(state::VarTable, change::StateUpdate) - if !isa(change.var, Slot) - return stupdate!(state, change.state) - end - newstate = false - changeid = slot_id(change.var::Slot) - for i = 1:length(state) - if i == changeid - newtype = change.vtype - else - newtype = change.state[i] - end - oldtype = state[i] - if schanged(newtype, oldtype) - newstate = state - state[i] = smerge(oldtype, newtype) - end - end - return newstate -end - -function stupdate!(state::VarTable, changes::VarTable) - newstate = false - for i = 1:length(state) - newtype = changes[i] - oldtype = state[i] - if schanged(newtype, oldtype) - newstate = state - state[i] = smerge(oldtype, newtype) - end - end - return newstate -end - -stupdate!(state::Tuple{}, changes::VarTable) = copy(changes) - -stupdate!(state::Tuple{}, changes::Tuple{}) = false - -function stupdate1!(state::VarTable, change::StateUpdate) - if !isa(change.var, Slot) - return false - end - i = slot_id(change.var::Slot) - newtype = change.vtype - oldtype = state[i] - if schanged(newtype, oldtype) - state[i] = smerge(oldtype, newtype) - return true - end - return false -end - - -#### helper functions for typeinf initialization and looping #### - -function label_counter(body) - l = -1 - for b in body - if isa(b,LabelNode) && (b::LabelNode).label > l - l = (b::LabelNode).label - end - end - return l -end -genlabel(sv) = LabelNode(sv.label_counter += 1) - -function find_ssavalue_uses(body) - uses = IntSet[] - for line = 1:length(body) - find_ssavalue_uses(body[line], uses, line) - end - return uses -end -function find_ssavalue_uses(e::ANY, uses, line) - if isa(e,SSAValue) - id = (e::SSAValue).id + 1 - while length(uses) < id - push!(uses, IntSet()) - end - push!(uses[id], line) - elseif isa(e,Expr) - b = e::Expr - head = b.head - is_meta_expr_head(head) && return - if head === :(=) - if isa(b.args[1],SSAValue) - id = (b.args[1]::SSAValue).id + 1 - while length(uses) < id - push!(uses, IntSet()) - end - end - find_ssavalue_uses(b.args[2], uses, line) - return - end - for a in b.args - find_ssavalue_uses(a, uses, line) - end - end -end - -function newvar!(sv::InferenceState, typ::ANY) - id = length(sv.src.ssavaluetypes) - push!(sv.src.ssavaluetypes, typ) - return SSAValue(id) -end - -inlining_enabled() = (JLOptions().can_inline == 1) -coverage_enabled() = (JLOptions().code_coverage != 0) - -# work towards converging the valid age range for sv -function update_valid_age!(min_valid::UInt, max_valid::UInt, sv::InferenceState) - sv.min_valid = max(sv.min_valid, min_valid) - sv.max_valid = min(sv.max_valid, max_valid) - @assert !isdefined(sv.linfo, :def) || !sv.cached || sv.min_valid <= sv.params.world <= sv.max_valid "invalid age range update" - nothing -end -update_valid_age!(edge::InferenceState, sv::InferenceState) = update_valid_age!(edge.min_valid, edge.max_valid, sv) -update_valid_age!(li::MethodInstance, sv::InferenceState) = update_valid_age!(min_world(li), max_world(li), sv) - -# temporarily accumulate our edges to later add as backedges in the callee -function add_backedge!(li::MethodInstance, caller::InferenceState) - isdefined(caller.linfo, :def) || return # don't add backedges to toplevel exprs - if caller.stmt_edges[caller.currpc] === () - caller.stmt_edges[caller.currpc] = [] - end - push!(caller.stmt_edges[caller.currpc], li) - update_valid_age!(li, caller) - nothing -end - -# temporarily accumulate our no method errors to later add as backedges in the callee method table -function add_mt_backedge(mt::MethodTable, typ::ANY, caller::InferenceState) - isdefined(caller.linfo, :def) || return # don't add backedges to toplevel exprs - if caller.stmt_edges[caller.currpc] === () - caller.stmt_edges[caller.currpc] = [] - end - push!(caller.stmt_edges[caller.currpc], mt) - push!(caller.stmt_edges[caller.currpc], typ) - nothing -end - -# add the real backedges now -function finalize_backedges(frame::InferenceState) - toplevel = !isdefined(frame.linfo, :def) - if !toplevel && frame.cached && frame.max_valid == typemax(UInt) - caller = frame.linfo - for edges in frame.stmt_edges - i = 1 - while i <= length(edges) - to = edges[i] - if isa(to, MethodInstance) - ccall(:jl_method_instance_add_backedge, Void, (Any, Any), to, caller) - i += 1 - else - typeassert(to, MethodTable) - typ = edges[i + 1] - ccall(:jl_method_table_add_backedge, Void, (Any, Any, Any), to, typ, caller) - i += 2 - end - end - end - end -end - -function code_for_method(method::Method, atypes::ANY, sparams::SimpleVector, world::UInt, preexisting::Bool=false) - if world < min_world(method) - return nothing - end - if method.isstaged && !isleaftype(atypes) - # don't call staged functions on abstract types. - # (see issues #8504, #10230) - # we can't guarantee that their type behavior is monotonic. - # XXX: this test is wrong if Types (such as DataType or Bottom) are present - return nothing - end - if preexisting - if method.specializations !== nothing - # check cached specializations - # for an existing result stored there - return ccall(:jl_specializations_lookup, Any, (Any, Any, UInt), method, atypes, world) - end - return nothing - end - return ccall(:jl_specializations_get_linfo, Ref{MethodInstance}, (Any, Any, Any, UInt), method, atypes, sparams, world) -end - -function typeinf_active(linfo::MethodInstance, sv::InferenceState) - for infstate in sv.callers_in_cycle - linfo === infstate.linfo && return infstate - end - return nothing -end - -function add_backedge!(frame::InferenceState, caller::InferenceState, currpc::Int) - update_valid_age!(frame, caller) - backedge = (caller, currpc) - contains_is(frame.backedges, backedge) || push!(frame.backedges, backedge) - return frame -end - -# at the end, all items in b's cycle -# will now be added to a's cycle -function union_caller_cycle!(a::InferenceState, b::InferenceState) - callers_in_cycle = b.callers_in_cycle - b.parent = a.parent - b.callers_in_cycle = a.callers_in_cycle - contains_is(a.callers_in_cycle, b) || push!(a.callers_in_cycle, b) - if callers_in_cycle !== a.callers_in_cycle - for caller in callers_in_cycle - if caller !== b - caller.parent = a.parent - caller.callers_in_cycle = a.callers_in_cycle - push!(a.callers_in_cycle, caller) - end - end - end - return -end - -function merge_call_chain!(parent::InferenceState, ancestor::InferenceState, child::InferenceState) - # add backedge of parent <- child - # then add all backedges of parent <- parent.parent - # and merge all of the callers into ancestor.callers_in_cycle - # and ensure that walking the parent list will get the same result (DAG) from everywhere - while true - add_backedge!(child, parent, parent.currpc) - union_caller_cycle!(ancestor, child) - child = parent - parent = child.parent - child === ancestor && break - end -end - -# Walk through `linfo`'s upstream call chain, starting at `parent`. If a parent -# frame matching `linfo` is encountered, then there is a cycle in the call graph -# (i.e. `linfo` is a descendant callee of itself). Upon encountering this cycle, -# we "resolve" it by merging the call chain, which entails unioning each intermediary -# frame's `callers_in_cycle` field and adding the appropriate backedges. Finally, -# we return `linfo`'s pre-existing frame. If no cycles are found, `nothing` is -# returned instead. -function resolve_call_cycle!(linfo::MethodInstance, parent::InferenceState) - frame = parent - while isa(frame, InferenceState) - if frame.linfo === linfo - merge_call_chain!(parent, frame, frame) - return frame - end - for caller in frame.callers_in_cycle - if caller.linfo === linfo - merge_call_chain!(parent, frame, caller) - return caller - end - end - frame = frame.parent - end - return nothing -end - -# build (and start inferring) the inference frame for the linfo -function typeinf_frame(linfo::MethodInstance, - optimize::Bool, cached::Bool, params::InferenceParams) - frame = InferenceState(linfo, optimize, cached, params) - frame === nothing && return nothing - cached && (linfo.inInference = true) - typeinf(frame) - return frame -end - -# compute (and cache) an inferred AST and return the current best estimate of the result type -function typeinf_edge(method::Method, atypes::ANY, sparams::SimpleVector, caller::InferenceState) - code = code_for_method(method, atypes, sparams, caller.params.world) - code === nothing && return Any, nothing - code = code::MethodInstance - if isdefined(code, :inferred) - # return rettype if the code is already inferred - # staged functions make this hard since they have two "inferred" conditions, - # so need to check whether the code itself is also inferred - inf = code.inferred - if !isa(inf, CodeInfo) || (inf::CodeInfo).inferred - if isdefined(code, :inferred_const) - return abstract_eval_constant(code.inferred_const), code - else - return code.rettype, code - end - end - end - frame = resolve_call_cycle!(code, caller) - if frame === nothing - code.inInference = true - frame = InferenceState(code, true, true, caller.params) # always optimize and cache edge targets - if frame === nothing - code.inInference = false - return Any, nothing - end - frame.parent = caller - typeinf(frame) - return frame.bestguess, frame.inferred ? frame.linfo : nothing - end - frame = frame::InferenceState - return frame.bestguess, nothing -end - -#### entry points for inferring a MethodInstance given a type signature #### - -# compute an inferred AST and return type -function typeinf_code(method::Method, atypes::ANY, sparams::SimpleVector, - optimize::Bool, cached::Bool, params::InferenceParams) - code = code_for_method(method, atypes, sparams, params.world) - code === nothing && return (nothing, nothing, Any) - return typeinf_code(code::MethodInstance, optimize, cached, params) -end -function typeinf_code(linfo::MethodInstance, optimize::Bool, cached::Bool, - params::InferenceParams) - for i = 1:2 # test-and-lock-and-test - i == 2 && ccall(:jl_typeinf_begin, Void, ()) - if cached && isdefined(linfo, :inferred) - # see if this code already exists in the cache - # staged functions make this hard since they have two "inferred" conditions, - # so need to check whether the code itself is also inferred - if min_world(linfo) <= params.world <= max_world(linfo) - inf = linfo.inferred - if linfo.jlcall_api == 2 - method = linfo.def - tree = ccall(:jl_new_code_info_uninit, Ref{CodeInfo}, ()) - tree.code = Any[ Expr(:return, QuoteNode(linfo.inferred_const)) ] - tree.slotnames = Any[ compiler_temp_sym for i = 1:method.nargs ] - tree.slotflags = UInt8[ 0 for i = 1:method.nargs ] - tree.slottypes = nothing - tree.ssavaluetypes = 0 - tree.inferred = true - tree.pure = true - tree.inlineable = true - i == 2 && ccall(:jl_typeinf_end, Void, ()) - return svec(linfo, tree, linfo.rettype) - elseif isa(inf, CodeInfo) - if inf.inferred - i == 2 && ccall(:jl_typeinf_end, Void, ()) - return svec(linfo, inf, linfo.rettype) - end - end - end - end - end - frame = typeinf_frame(linfo, optimize, cached, params) - ccall(:jl_typeinf_end, Void, ()) - frame === nothing && return svec(nothing, nothing, Any) - frame = frame::InferenceState - frame.inferred || return svec(nothing, nothing, Any) - frame.cached || return svec(nothing, frame.src, widenconst(frame.bestguess)) - return svec(frame.linfo, frame.src, widenconst(frame.bestguess)) -end - -# compute (and cache) an inferred AST and return the inferred return type -function typeinf_type(method::Method, atypes::ANY, sparams::SimpleVector, - cached::Bool, params::InferenceParams) - code = code_for_method(method, atypes, sparams, params.world) - code === nothing && return nothing - code = code::MethodInstance - for i = 1:2 # test-and-lock-and-test - i == 2 && ccall(:jl_typeinf_begin, Void, ()) - if cached && isdefined(code, :inferred) - # see if this rettype already exists in the cache - # staged functions make this hard since they have two "inferred" conditions, - # so need to check whether the code itself is also inferred - inf = code.inferred - if !isa(inf, CodeInfo) || (inf::CodeInfo).inferred - i == 2 && ccall(:jl_typeinf_end, Void, ()) - return code.rettype - end - end - end - frame = typeinf_frame(code, cached, cached, params) - ccall(:jl_typeinf_end, Void, ()) - frame === nothing && return nothing - frame = frame::InferenceState - frame.inferred || return nothing - return widenconst(frame.bestguess) -end - -function typeinf_ext(linfo::MethodInstance, world::UInt) - if isdefined(linfo, :def) - # method lambda - infer this specialization via the method cache - return typeinf_code(linfo, true, true, InferenceParams(world)) - else - # toplevel lambda - infer directly - ccall(:jl_typeinf_begin, Void, ()) - frame = InferenceState(linfo, linfo.inferred::CodeInfo, - true, true, InferenceParams(world)) - typeinf(frame) - ccall(:jl_typeinf_end, Void, ()) - @assert frame.inferred # TODO: deal with this better - @assert frame.linfo === linfo - return svec(linfo, frame.src, linfo.rettype) - end -end - -#### do the work of inference #### - -function typeinf_work(frame::InferenceState) - @assert !frame.inferred - frame.dont_work_on_me = true # mark that this function is currently on the stack - W = frame.ip - s = frame.stmt_types - n = frame.nstmts - while frame.pc´´ <= n - # make progress on the active ip set - local pc::Int = frame.pc´´ # current program-counter - while true # inner loop optimizes the common case where it can run straight from pc to pc + 1 - #print(pc,": ",s[pc],"\n") - local pc´::Int = pc + 1 # next program-counter (after executing instruction) - if pc == frame.pc´´ - # need to update pc´´ to point at the new lowest instruction in W - min_pc = next(W, pc)[2] - if done(W, min_pc) - frame.pc´´ = max(min_pc, n + 1) - else - frame.pc´´ = min_pc - end - end - delete!(W, pc) - frame.currpc = pc - frame.cur_hand = frame.handler_at[pc] - frame.stmt_edges[pc] === () || empty!(frame.stmt_edges[pc]) - stmt = frame.src.code[pc] - changes = abstract_interpret(stmt, s[pc]::VarTable, frame) - if changes === () - break # this line threw an error and so there is no need to continue - # changes = s[pc] - end - if frame.cur_hand !== () && isa(changes, StateUpdate) - # propagate new type info to exception handler - # the handling for Expr(:enter) propagates all changes from before the try/catch - # so this only needs to propagate any changes - l = frame.cur_hand[1] - if stupdate1!(s[l]::VarTable, changes::StateUpdate) !== false - if l < frame.pc´´ - frame.pc´´ = l - end - push!(W, l) - end - end - if isa(changes, StateUpdate) - changes_var = changes.var - if isa(changes_var, SSAValue) - # directly forward changes to an SSAValue to the applicable line - record_ssa_assign(changes_var.id + 1, changes.vtype.typ, frame) - end - elseif isa(stmt, GotoNode) - pc´ = (stmt::GotoNode).label - elseif isa(stmt, Expr) - stmt = stmt::Expr - hd = stmt.head - if hd === :gotoifnot - condt = abstract_eval(stmt.args[1], s[pc], frame) - condval = isa(condt, Const) ? condt.val : nothing - l = stmt.args[2]::Int - changes = changes::VarTable - # constant conditions - if condval === true - elseif condval === false - pc´ = l - else - # general case - frame.handler_at[l] = frame.cur_hand - if isa(condt, Conditional) - changes_else = StateUpdate(condt.var, VarState(condt.elsetype, false), changes) - changes = StateUpdate(condt.var, VarState(condt.vtype, false), changes) - else - changes_else = changes - end - newstate_else = stupdate!(s[l], changes_else) - if newstate_else !== false - # add else branch to active IP list - if l < frame.pc´´ - frame.pc´´ = l - end - push!(W, l) - s[l] = newstate_else - end - end - elseif hd === :return - pc´ = n + 1 - rt = abstract_eval(stmt.args[1], s[pc], frame) - if tchanged(rt, frame.bestguess) - # new (wider) return type for frame - frame.bestguess = tmerge(frame.bestguess, rt) - for (caller, caller_pc) in frame.backedges - # notify backedges of updated type information - if caller.stmt_types[caller_pc] !== () - if caller_pc < caller.pc´´ - caller.pc´´ = caller_pc - end - push!(caller.ip, caller_pc) - end - end - end - elseif hd === :enter - l = stmt.args[1]::Int - frame.cur_hand = (l, frame.cur_hand) - # propagate type info to exception handler - l = frame.cur_hand[1] - old = s[l] - new = s[pc]::Array{Any,1} - newstate_catch = stupdate!(old, new) - if newstate_catch !== false - if l < frame.pc´´ - frame.pc´´ = l - end - push!(W, l) - s[l] = newstate_catch - end - typeassert(s[l], VarTable) - frame.handler_at[l] = frame.cur_hand - elseif hd === :leave - for i = 1:((stmt.args[1])::Int) - frame.cur_hand = frame.cur_hand[2] - end - end - end - pc´ > n && break # can't proceed with the fast-path fall-through - frame.handler_at[pc´] = frame.cur_hand - newstate = stupdate!(s[pc´], changes) - if isa(stmt, GotoNode) && frame.pc´´ < pc´ - # if we are processing a goto node anyways, - # (such as a terminator for a loop, if-else, or try block), - # consider whether we should jump to an older backedge first, - # to try to traverse the statements in approximate dominator order - if newstate !== false - s[pc´] = newstate - end - push!(W, pc´) - pc = frame.pc´´ - elseif newstate !== false - s[pc´] = newstate - pc = pc´ - elseif pc´ in W - pc = pc´ - else - break - end - end - end - frame.dont_work_on_me = false -end - -function typeinf(frame::InferenceState) - - typeinf_work(frame) - - # If the current frame is part of a cycle, solve the cycle before finishing - no_active_ips_in_callers = false - while !no_active_ips_in_callers - no_active_ips_in_callers = true - for caller in frame.callers_in_cycle - caller.dont_work_on_me && return - if caller.pc´´ <= caller.nstmts # equivalent to `isempty(caller.ip)` - # Note that `typeinf_work(caller)` can potentially modify the other frames - # `frame.callers_in_cycle`, which is why making incremental progress requires the - # outer while loop. - typeinf_work(caller) - no_active_ips_in_callers = false - end - if caller.min_valid < frame.min_valid - caller.min_valid = frame.min_valid - end - if caller.max_valid > frame.max_valid - caller.max_valid = frame.max_valid - end - end - end - - # with no active ip's, type inference on frame is done - - if isempty(frame.callers_in_cycle) - @assert !(frame.dont_work_on_me) - frame.dont_work_on_me = true - optimize(frame) - finish(frame) - finalize_backedges(frame) - else # frame is in frame.callers_in_cycle - for caller in frame.callers_in_cycle - @assert !(caller.dont_work_on_me) - caller.dont_work_on_me = true - end - for caller in frame.callers_in_cycle - optimize(caller) - if frame.min_valid < caller.min_valid - frame.min_valid = caller.min_valid - end - if frame.max_valid > caller.max_valid - frame.max_valid = caller.max_valid - end - end - for caller in frame.callers_in_cycle - caller.min_valid = frame.min_valid - end - for caller in frame.callers_in_cycle - finish(caller) - end - for caller in frame.callers_in_cycle - finalize_backedges(caller) - end - end - - nothing -end - - -function record_ssa_assign(ssa_id::Int, new::ANY, frame::InferenceState) - old = frame.src.ssavaluetypes[ssa_id] - if old === NF || !(new ⊑ old) - frame.src.ssavaluetypes[ssa_id] = tmerge(old, new) - W = frame.ip - s = frame.stmt_types - for r in frame.ssavalue_uses[ssa_id] - if s[r] !== () # s[r] === () => unreached statement - if r < frame.pc´´ - frame.pc´´ = r - end - push!(W, r) - end - end - end - nothing -end - - -#### finalize and record the result of running type inference #### - -function isinlineable(m::Method, src::CodeInfo) - inlineable = false - cost = 1000 - if m.module === _topmod(m.module) - name = m.name - sig = m.sig - if ((name === :+ || name === :* || name === :min || name === :max) && - isa(sig,DataType) && - sig == Tuple{sig.parameters[1],Any,Any,Any,Vararg{Any}}) - inlineable = true - elseif (name === :next || name === :done || name === :unsafe_convert || - name === :cconvert) - cost ÷= 4 - end - end - if !inlineable - inlineable = inline_worthy_stmts(src.code, cost) - end - return inlineable -end - -# inference completed on `me` -# now converge the optimization work -function optimize(me::InferenceState) - # annotate fulltree with type information - type_annotate!(me) - - # run optimization passes on fulltree - force_noinline = false - if me.optimize - # This pass is required for the AST to be valid in codegen - # if any `SSAValue` is created by type inference. Ref issue #6068 - # This (and `reindex_labels!`) needs to be run for `!me.optimize` - # if we start to create `SSAValue` in type inference when not - # optimizing and use unoptimized IR in codegen. - gotoifnot_elim_pass!(me) - inlining_pass!(me) - void_use_elim_pass!(me) - alloc_elim_pass!(me) - getfield_elim_pass!(me) - # Clean up for `alloc_elim_pass!` and `getfield_elim_pass!` - void_use_elim_pass!(me) - do_coverage = coverage_enabled() - meta_elim_pass!(me.src.code::Array{Any,1}, me.src.propagate_inbounds, do_coverage) - # Pop metadata before label reindexing - force_noinline = popmeta!(me.src.code::Array{Any,1}, :noinline)[1] - reindex_labels!(me) - end - - # convert all type information into the form consumed by the code-generator - widen_all_consts!(me.src) - - if isa(me.bestguess, Const) || isconstType(me.bestguess) - me.const_ret = true - proven_pure = false - # must be proven pure to use const_api; otherwise we might skip throwing errors - # (issue #20704) - # TODO: Improve this analysis; if a function is marked @pure we should really - # only care about certain errors (e.g. method errors and type errors). - if length(me.src.code) < 10 - proven_pure = true - for stmt in me.src.code - if !statement_effect_free(stmt, me.src, me.mod) - proven_pure = false - break - end - end - if proven_pure - for fl in me.src.slotflags - if (fl & Slot_UsedUndef) != 0 - proven_pure = false - break - end - end - end - end - if proven_pure - me.src.pure = true - end - - if proven_pure && !coverage_enabled() - # use constant calling convention - # Do not emit `jlcall_api == 2` if coverage is enabled - # so that we don't need to add coverage support - # to the `jl_call_method_internal` fast path - # Still set pure flag to make sure `inference` tests pass - # and to possibly enable more optimization in the future - me.const_api = true - force_noinline || (me.src.inlineable = true) - end - end - - # determine and cache inlineability - if !me.src.inlineable && !force_noinline && isdefined(me.linfo, :def) - me.src.inlineable = isinlineable(me.linfo.def, me.src) - end - me.src.inferred = true - nothing -end - -# inference completed on `me` -# update the MethodInstance and notify the edges -function finish(me::InferenceState) - me.currpc = 1 # used by add_backedge - if me.cached - toplevel = !isdefined(me.linfo, :def) - if !toplevel - min_valid = me.min_valid - max_valid = me.max_valid - else - min_valid = UInt(0) - max_valid = UInt(0) - end - - # check if the existing me.linfo metadata is also sufficient to describe the current inference result - # to decide if it is worth caching it again (which would also clear any generated code) - already_inferred = !me.linfo.inInference - if isdefined(me.linfo, :inferred) - inf = me.linfo.inferred - if !isa(inf, CodeInfo) || (inf::CodeInfo).inferred - if min_world(me.linfo) == min_valid && max_world(me.linfo) == max_valid - already_inferred = true - end - end - end - - if !already_inferred - const_flags = (me.const_ret) << 1 | me.const_api - if me.const_ret - if isa(me.bestguess, Const) - inferred_const = (me.bestguess::Const).val - else - @assert isconstType(me.bestguess) - inferred_const = me.bestguess.parameters[1] - end - else - inferred_const = nothing - end - if me.const_api - # use constant calling convention - inferred_result = nothing - else - inferred_result = me.src - end - - if !toplevel - if !me.const_api - keeptree = me.src.inlineable || ccall(:jl_is_cacheable_sig, Int32, (Any, Any, Any), - me.linfo.specTypes, me.linfo.def.sig, me.linfo.def) != 0 - if !keeptree - inferred_result = nothing - else - # compress code for non-toplevel thunks - inferred_result = ccall(:jl_compress_ast, Any, (Any, Any), me.linfo.def, inferred_result) - end - end - end - cache = ccall(:jl_set_method_inferred, Ref{MethodInstance}, (Any, Any, Any, Any, Int32, UInt, UInt), - me.linfo, widenconst(me.bestguess), inferred_const, inferred_result, - const_flags, min_valid, max_valid) - if cache !== me.linfo - me.linfo.inInference = false - me.linfo = cache - end - end - end - - # update all of the callers with real backedges by traversing the temporary list of backedges - for (i, _) in me.backedges - add_backedge!(me.linfo, i) - end - - # finalize and record the linfo result - me.cached && (me.linfo.inInference = false) - me.inferred = true - nothing -end - -function annotate_slot_load!(e::Expr, vtypes::VarTable, sv::InferenceState, undefs::Array{Bool,1}) - head = e.head - i0 = 1 - if is_meta_expr_head(head) || head === :const - return - end - if head === :(=) || head === :method - i0 = 2 - end - for i = i0:length(e.args) - subex = e.args[i] - if isa(subex, Expr) - annotate_slot_load!(subex, vtypes, sv, undefs) - elseif isa(subex, Slot) - id = slot_id(subex) - s = vtypes[id] - vt = widenconst(s.typ) - if s.undef - # find used-undef variables - undefs[id] = true - end - # add type annotations where needed - if !(sv.src.slottypes[id] ⊑ vt) - e.args[i] = TypedSlot(id, vt) - end - end - end -end - -function record_slot_assign!(sv::InferenceState) - # look at all assignments to slots - # and union the set of types stored there - # to compute a lower bound on the storage required - states = sv.stmt_types - body = sv.src.code::Vector{Any} - slottypes = sv.src.slottypes::Vector{Any} - for i = 1:length(body) - expr = body[i] - st_i = states[i] - # find all reachable assignments to locals - if isa(st_i, VarTable) && isa(expr, Expr) && expr.head === :(=) - lhs = expr.args[1] - rhs = expr.args[2] - if isa(lhs, Slot) - id = slot_id(lhs) - if isa(rhs, Slot) - # exprtype isn't yet computed for slots - vt = st_i[slot_id(rhs)].typ - else - vt = exprtype(rhs, sv.src, sv.mod) - end - vt = widenconst(vt) - if vt !== Bottom - otherTy = slottypes[id] - if otherTy === Bottom - slottypes[id] = vt - elseif otherTy === Any - slottypes[id] = Any - else - slottypes[id] = tmerge(otherTy, vt) - end - end - end - end - end -end - -# annotate types of all symbols in AST -function type_annotate!(sv::InferenceState) - # remove all unused ssa values - gt = sv.src.ssavaluetypes - for i = 1:length(gt) - if gt[i] === NF - gt[i] = Union{} - end - end - - # compute the required type for each slot - # to hold all of the items assigned into it - record_slot_assign!(sv) - - # annotate variables load types - # remove dead code - # and compute which variables may be used undef - src = sv.src - states = sv.stmt_types - nargs = sv.nargs - nslots = length(states[1]) - undefs = fill(false, nslots) - body = src.code::Array{Any,1} - nexpr = length(body) - i = 1 - while i <= nexpr - st_i = states[i] - expr = body[i] - if isa(st_i, VarTable) - # st_i === () => unreached statement (see issue #7836) - if isa(expr, Expr) - annotate_slot_load!(expr, st_i, sv, undefs) - elseif isa(expr, Slot) - id = slot_id(expr) - if st_i[slot_id(expr)].undef - # find used-undef variables in statement position - undefs[id] = true - end - end - elseif sv.optimize - if ((isa(expr, Expr) && is_meta_expr(expr)) || - isa(expr, LineNumberNode)) - # keep any lexically scoped expressions - i += 1 - continue - end - # This can create `Expr(:gotoifnot)` with dangling label, which we - # will clean up in `reindex_labels!` - deleteat!(body, i) - deleteat!(states, i) - nexpr -= 1 - continue - end - i += 1 - end - - # finish marking used-undef variables - for i = 1:nslots - if undefs[i] - src.slotflags[i] |= Slot_UsedUndef - end - end - nothing -end - -# widen all Const elements in type annotations -function _widen_all_consts!(e::Expr, untypedload::Vector{Bool}) - e.typ = widenconst(e.typ) - for i = 1:length(e.args) - x = e.args[i] - if isa(x, Expr) - _widen_all_consts!(x, untypedload) - elseif isa(x, Slot) && (i != 1 || e.head !== :(=)) - untypedload[slot_id(x)] = true - end - end - nothing -end -function widen_all_consts!(src::CodeInfo) - for i = 1:length(src.ssavaluetypes) - src.ssavaluetypes[i] = widenconst(src.ssavaluetypes[i]) - end - nslots = length(src.slottypes) - untypedload = fill(false, nslots) - for i = 1:length(src.code) - x = src.code[i] - isa(x, Expr) && _widen_all_consts!(x, untypedload) - end - for i = 1:nslots - src.slottypes[i] = widen_slot_type(src.slottypes[i], untypedload[i]) - end - return src -end - -# widen all slots to their optimal storage layout -# we also need to preserve the type for any untyped load of a DataType -# since codegen optimizations of functions like `is` will depend on knowing it -function widen_slot_type(ty::ANY, untypedload::Bool) - ty = widenconst(ty) - if isa(ty, DataType) - if untypedload || isbits(ty) || isdefined(ty, :instance) - return ty - end - elseif isa(ty, Union) - ty_a = widen_slot_type(ty.a, false) - ty_b = widen_slot_type(ty.b, false) - if ty_a !== Any || ty_b !== Any - # TODO: better optimized codegen for unions? - return ty - end - elseif isa(ty, UnionAll) - if untypedload - return ty - end - end - return Any -end - -# replace slots 1:na with argexprs, static params with spvals, and increment -# other slots by offset. -function substitute!(e::ANY, na::Int, argexprs::Vector{Any}, spsig::ANY, spvals::Vector{Any}, offset::Int) - if isa(e, Slot) - id = slot_id(e) - if 1 <= id <= na - ae = argexprs[id] - if isa(e, TypedSlot) && isa(ae, Slot) - return TypedSlot(ae.id, e.typ) - end - return ae - end - if isa(e, SlotNumber) - return SlotNumber(id + offset) - else - return TypedSlot(id + offset, e.typ) - end - end - if isa(e, NewvarNode) - return NewvarNode(substitute!(e.slot, na, argexprs, spsig, spvals, offset)) - end - if isa(e, Expr) - e = e::Expr - head = e.head - if head === :static_parameter - return spvals[e.args[1]] - elseif head === :foreigncall - @assert !isa(spsig,UnionAll) || !isempty(spvals) - for i = 1:length(e.args) - if i == 2 - e.args[2] = ccall(:jl_instantiate_type_in_env, Any, (Any, Any, Ptr{Any}), e.args[2], spsig, spvals) - elseif i == 3 - argtuple = Any[ - ccall(:jl_instantiate_type_in_env, Any, (Any, Any, Ptr{Any}), argt, spsig, spvals) - for argt - in e.args[3] ] - e.args[3] = svec(argtuple...) - else - e.args[i] = substitute!(e.args[i], na, argexprs, spsig, spvals, offset) - end - end - elseif !is_meta_expr_head(head) - for i = 1:length(e.args) - e.args[i] = substitute!(e.args[i], na, argexprs, spsig, spvals, offset) - end - end - end - return e -end - -# count occurrences up to n+1 -function occurs_more(e::ANY, pred, n) - if isa(e,Expr) - e = e::Expr - head = e.head - is_meta_expr_head(head) && return 0 - c = 0 - for a = e.args - c += occurs_more(a, pred, n) - if c>n - return c - end - end - return c - end - if pred(e) - return 1 - end - return 0 -end - -function exprtype(x::ANY, src::CodeInfo, mod::Module) - if isa(x, Expr) - return (x::Expr).typ - elseif isa(x, SlotNumber) - return src.slottypes[(x::SlotNumber).id] - elseif isa(x, TypedSlot) - return (x::TypedSlot).typ - elseif isa(x, SSAValue) - return abstract_eval_ssavalue(x::SSAValue, src) - elseif isa(x, Symbol) - return abstract_eval_global(mod, x::Symbol) - elseif isa(x, QuoteNode) - return abstract_eval_constant((x::QuoteNode).value) - elseif isa(x, GlobalRef) - return abstract_eval_global(x.mod, (x::GlobalRef).name) - else - return abstract_eval_constant(x) - end -end - -# known affect-free calls (also effect-free) -const _pure_builtins = Any[tuple, svec, fieldtype, apply_type, ===, isa, typeof, UnionAll, nfields] - -# known effect-free calls (might not be affect-free) -const _pure_builtins_volatile = Any[getfield, arrayref] - -function is_pure_intrinsic(f::IntrinsicFunction) - return !(f === Intrinsics.pointerref || # this one is volatile - f === Intrinsics.pointerset || # this one is never effect-free - f === Intrinsics.llvmcall || # this one is never effect-free - f === Intrinsics.checked_trunc_sint || - f === Intrinsics.checked_trunc_uint || - f === Intrinsics.checked_sdiv_int || - f === Intrinsics.checked_udiv_int || - f === Intrinsics.checked_srem_int || - f === Intrinsics.checked_urem_int || - f === Intrinsics.check_top_bit || - f === Intrinsics.sqrt_llvm || - f === Intrinsics.cglobal) # cglobal throws an error for symbol-not-found -end - -function is_pure_builtin(f::ANY) - return (contains_is(_pure_builtins, f) || - contains_is(_pure_builtins_volatile, f) || - (isa(f,IntrinsicFunction) && is_pure_intrinsic(f)) || - f === return_type) -end - -function statement_effect_free(e::ANY, src::CodeInfo, mod::Module) - if isa(e, Expr) - if e.head === :(=) - return !isa(e.args[1], GlobalRef) && effect_free(e.args[2], src, mod, false) - elseif e.head === :gotoifnot - return effect_free(e.args[1], src, mod, false) - end - elseif isa(e, LabelNode) || isa(e, GotoNode) - return true - end - return effect_free(e, src, mod, false) -end - -# detect some important side-effect-free calls (allow_volatile=true) -# and some affect-free calls (allow_volatile=false) -- affect_free means the call -# cannot be affected by previous calls, except assignment nodes -function effect_free(e::ANY, src::CodeInfo, mod::Module, allow_volatile::Bool) - if isa(e, GlobalRef) - return (isdefined(e.mod, e.name) && (allow_volatile || isconst(e.mod, e.name))) - elseif isa(e, Symbol) - return allow_volatile - elseif isa(e, Slot) - return src.slotflags[slot_id(e)] & Slot_UsedUndef == 0 - elseif isa(e, Expr) - e = e::Expr - head = e.head - if head === :static_parameter || is_meta_expr_head(head) - return true - end - if e.typ === Bottom - return false - end - ea = e.args - if head === :call - if is_known_call_p(e, is_pure_builtin, src, mod) - if !allow_volatile - if is_known_call(e, arrayref, src, mod) || is_known_call(e, arraylen, src, mod) - return false - elseif is_known_call(e, getfield, src, mod) - length(ea) == 3 || return false - et = exprtype(e, src, mod) - if !isa(et,Const) && !(isType(et) && isleaftype(et)) - # first argument must be immutable to ensure e is affect_free - a = ea[2] - typ = widenconst(exprtype(a, src, mod)) - if isconstType(typ) - if Const(:uid) ⊑ exprtype(ea[3], src, mod) - return false # DataType uid field can change - end - elseif typ !== SimpleVector && (!isa(typ, DataType) || typ.mutable || typ.abstract) - return false - end - end - end - end - # fall-through - elseif is_known_call(e, _apply, src, mod) && length(ea) > 1 - ft = exprtype(ea[2], src, mod) - if !isa(ft, Const) || !contains_is(_pure_builtins, ft.val) - return false - end - # fall-through - else - return false - end - elseif head === :new - if !allow_volatile - a = ea[1] - typ = widenconst(exprtype(a, src, mod)) - if !isType(typ) || !isa((typ::Type).parameters[1],DataType) || ((typ::Type).parameters[1]::DataType).mutable - return false - end - end - # fall-through - elseif head === :return - # fall-through - elseif head === :the_exception - return allow_volatile - else - return false - end - for a in ea - if !effect_free(a, src, mod, allow_volatile) - return false - end - end - elseif isa(e, LabelNode) || isa(e, GotoNode) - return false - end - return true -end - - -#### post-inference optimizations #### - -struct InvokeData - mt::MethodTable - entry::TypeMapEntry - types0 - fexpr - texpr -end - -function inline_as_constant(val::ANY, argexprs, sv::InferenceState, invoke_data::ANY) - if invoke_data === nothing - invoke_fexpr = nothing - invoke_texpr = nothing - else - invoke_data = invoke_data::InvokeData - invoke_fexpr = invoke_data.fexpr - invoke_texpr = invoke_data.texpr - end - # check if any arguments aren't effect_free and need to be kept around - stmts = invoke_fexpr === nothing ? [] : Any[invoke_fexpr] - for i = 1:length(argexprs) - arg = argexprs[i] - if !effect_free(arg, sv.src, sv.mod, false) - push!(stmts, arg) - end - if i == 1 && !(invoke_texpr === nothing) - push!(stmts, invoke_texpr) - end - end - if !is_self_quoting(val) - val = QuoteNode(val) - end - return (val, stmts) -end - -function is_self_quoting(x::ANY) - return isa(x,Number) || isa(x,AbstractString) || isa(x,Tuple) || isa(x,Type) -end - -function countunionsplit(atypes::Vector{Any}) - nu = 1 - for ti in atypes - if isa(ti, Union) - nu *= unionlen(ti::Union) - end - end - return nu -end - -function get_spec_lambda(atypes::ANY, sv, invoke_data::ANY) - if invoke_data === nothing - return ccall(:jl_get_spec_lambda, Any, (Any, UInt), atypes, sv.params.world) - else - invoke_data = invoke_data::InvokeData - atypes <: invoke_data.types0 || return nothing - return ccall(:jl_get_invoke_lambda, Any, (Any, Any, Any, UInt), - invoke_data.mt, invoke_data.entry, atypes, sv.params.world) - end -end - -function invoke_NF(argexprs, etype::ANY, atypes, sv, atype_unlimited::ANY, - invoke_data::ANY) - # converts a :call to :invoke - nu = countunionsplit(atypes) - nu > sv.params.MAX_UNION_SPLITTING && return NF - if invoke_data === nothing - invoke_fexpr = nothing - invoke_texpr = nothing - else - invoke_data = invoke_data::InvokeData - invoke_fexpr = invoke_data.fexpr - invoke_texpr = invoke_data.texpr - end - - if nu > 1 - spec_hit = nothing - spec_miss = nothing - error_label = nothing - linfo_var = add_slot!(sv.src, MethodInstance, false) - ex = Expr(:call) - ex.args = copy(argexprs) - ex.typ = etype - stmts = [] - arg_hoisted = false - for i = length(atypes):-1:1 - if i == 1 && !(invoke_texpr === nothing) - unshift!(stmts, invoke_texpr) - arg_hoisted = true - end - ti = atypes[i] - if arg_hoisted || isa(ti, Union) - aei = ex.args[i] - if !effect_free(aei, sv.src, sv.mod, false) - arg_hoisted = true - newvar = newvar!(sv, ti) - unshift!(stmts, :($newvar = $aei)) - ex.args[i] = newvar - end - end - end - invoke_fexpr === nothing || unshift!(stmts, invoke_fexpr) - function splitunion(atypes::Vector{Any}, i::Int) - if i == 0 - local sig = argtypes_to_type(atypes) - local li = get_spec_lambda(sig, sv, invoke_data) - li === nothing && return false - add_backedge!(li, sv) - local stmt = [] - push!(stmt, Expr(:(=), linfo_var, li)) - spec_hit === nothing && (spec_hit = genlabel(sv)) - push!(stmt, GotoNode(spec_hit.label)) - return stmt - else - local ti = atypes[i] - if isa(ti, Union) - local all = true - local stmts = [] - local aei = ex.args[i] - for ty in uniontypes(ti::Union) - local ty - atypes[i] = ty - local match = splitunion(atypes, i - 1) - if match !== false - after = genlabel(sv) - isa_ty = Expr(:call, GlobalRef(Core, :isa), aei, ty) - isa_ty.typ = Bool - unshift!(match, Expr(:gotoifnot, isa_ty, after.label)) - append!(stmts, match) - push!(stmts, after) - else - all = false - end - end - if UNION_SPLIT_MISMATCH_ERROR && all - error_label === nothing && (error_label = genlabel(sv)) - push!(stmts, GotoNode(error_label.label)) - else - spec_miss === nothing && (spec_miss = genlabel(sv)) - push!(stmts, GotoNode(spec_miss.label)) - end - atypes[i] = ti - return isempty(stmts) ? false : stmts - else - return splitunion(atypes, i - 1) - end - end - end - local match = splitunion(atypes, length(atypes)) - if match !== false && spec_hit !== nothing - append!(stmts, match) - if error_label !== nothing - push!(stmts, error_label) - push!(stmts, Expr(:call, GlobalRef(_topmod(sv.mod), :error), "fatal error in type inference (type bound)")) - end - local ret_var, merge - if spec_miss !== nothing - ret_var = add_slot!(sv.src, widenconst(ex.typ), false) - merge = genlabel(sv) - push!(stmts, spec_miss) - push!(stmts, Expr(:(=), ret_var, ex)) - push!(stmts, GotoNode(merge.label)) - else - ret_var = newvar!(sv, ex.typ) - end - push!(stmts, spec_hit) - ex = copy(ex) - ex.head = :invoke - unshift!(ex.args, linfo_var) - push!(stmts, Expr(:(=), ret_var, ex)) - if spec_miss !== nothing - push!(stmts, merge) - end - return (ret_var, stmts) - end - else - local cache_linfo = get_spec_lambda(atype_unlimited, sv, invoke_data) - cache_linfo === nothing && return NF - add_backedge!(cache_linfo, sv) - unshift!(argexprs, cache_linfo) - ex = Expr(:invoke) - ex.args = argexprs - ex.typ = etype - if invoke_texpr === nothing - if invoke_fexpr === nothing - return ex - else - return ex, Any[invoke_fexpr] - end - end - newvar = newvar!(sv, atypes[1]) - stmts = Any[invoke_fexpr, - :($newvar = $(argexprs[2])), - invoke_texpr] - argexprs[2] = newvar - return ex, stmts - end - return NF -end - -# inline functions whose bodies are "inline_worthy" -# where the function body doesn't contain any argument more than once. -# static parameters are ok if all the static parameter values are leaf types, -# meaning they are fully known. -# `ft` is the type of the function. `f` is the exact function if known, or else `nothing`. -# `pending_stmts` is an array of statements from functions inlined so far, so -# we can estimate the total size of the enclosing function after inlining. -function inlineable(f::ANY, ft::ANY, e::Expr, atypes::Vector{Any}, sv::InferenceState, - pending_stmts) - argexprs = e.args - - if (f === typeassert || ft ⊑ typeof(typeassert)) && length(atypes)==3 - # typeassert(x::S, T) => x, when S<:T - a3 = atypes[3] - if (isType(a3) && isleaftype(a3) && atypes[2] ⊑ a3.parameters[1]) || - (isa(a3,Const) && isa(a3.val,Type) && atypes[2] ⊑ a3.val) - return (argexprs[2], ()) - end - end - topmod = _topmod(sv) - # special-case inliners for known pure functions that compute types - if sv.params.inlining - if isa(e.typ, Const) # || isconstType(e.typ) - val = e.typ.val - if (f === apply_type || f === fieldtype || f === typeof || f === (===) || - istopfunction(topmod, f, :typejoin) || - istopfunction(topmod, f, :isbits) || - istopfunction(topmod, f, :promote_type) || - (f === Core.kwfunc && length(argexprs) == 2) || - (isbits(val) && Core.sizeof(val) <= MAX_INLINE_CONST_SIZE && - (contains_is(_pure_builtins, f) || - (f === getfield && effect_free(e, sv.src, sv.mod, false)) || - (isa(f,IntrinsicFunction) && is_pure_intrinsic(f))))) - return inline_as_constant(val, argexprs, sv, nothing) - end - end - end - invoke_data = nothing - invoke_fexpr = nothing - invoke_texpr = nothing - if f === Core.invoke && length(atypes) >= 3 - ft = widenconst(atypes[2]) - invoke_tt = widenconst(atypes[3]) - if !isleaftype(ft) || !isleaftype(invoke_tt) || !isType(invoke_tt) - return NF - end - if !(isa(invoke_tt.parameters[1], Type) && - invoke_tt.parameters[1] <: Tuple) - return NF - end - invoke_tt_params = invoke_tt.parameters[1].parameters - invoke_types = Tuple{ft, invoke_tt_params...} - invoke_entry = ccall(:jl_gf_invoke_lookup, Any, (Any, UInt), - invoke_types, sv.params.world) - invoke_entry === nothing && return NF - invoke_fexpr = argexprs[1] - invoke_texpr = argexprs[3] - if effect_free(invoke_fexpr, sv.src, sv.mod, false) - invoke_fexpr = nothing - end - if effect_free(invoke_texpr, sv.src, sv.mod, false) - invoke_fexpr = nothing - end - invoke_data = InvokeData(ft.name.mt, invoke_entry, - invoke_types, invoke_fexpr, invoke_texpr) - atype0 = atypes[2] - argexpr0 = argexprs[2] - atypes = atypes[4:end] - argexprs = argexprs[4:end] - unshift!(atypes, atype0) - unshift!(argexprs, argexpr0) - f = isdefined(ft, :instance) ? ft.instance : nothing - elseif isa(f, IntrinsicFunction) || ft ⊑ IntrinsicFunction || - isa(f, Builtin) || ft ⊑ Builtin - return NF - end - - atype_unlimited = argtypes_to_type(atypes) - if !(invoke_data === nothing) - invoke_data = invoke_data::InvokeData - # TODO emit a type check and proceed for this case - atype_unlimited <: invoke_data.types0 || return NF - end - if !sv.params.inlining - return invoke_NF(argexprs, e.typ, atypes, sv, atype_unlimited, - invoke_data) - end - - if length(atypes) == 3 && istopfunction(topmod, f, :!==) - # special-case inliner for !== that precedes _methods_by_ftype union splitting - # and that works, even though inference generally avoids inferring the `!==` Method - if isa(e.typ, Const) - return inline_as_constant(e.typ.val, argexprs, sv, nothing) - end - not_is = Expr(:call, GlobalRef(Core.Intrinsics, :not_int), - Expr(:call, GlobalRef(Core, :(===)), argexprs[2], argexprs[3])) - not_is.typ = Bool - not_is.args[2].typ = Bool - return (not_is, ()) - elseif length(atypes) == 3 && istopfunction(topmod, f, :(>:)) - # special-case inliner for issupertype - # that works, even though inference generally avoids inferring the `>:` Method - if isa(e.typ, Const) - return inline_as_constant(e.typ.val, argexprs, sv, nothing) - end - arg_T1 = argexprs[2] - arg_T2 = argexprs[3] - issubtype_stmts = () - if !effect_free(arg_T2, sv.src, sv.mod, false) - # spill first argument to preserve order-of-execution - issubtype_vnew = newvar!(sv, widenconst(exprtype(arg_T1, sv.src, sv.mod))) - issubtype_stmts = Any[ Expr(:(=), issubtype_vnew, arg_T1) ] - arg_T1 = issubtype_vnew - end - issubtype_expr = Expr(:call, GlobalRef(Core, :issubtype), arg_T2, arg_T1) - issubtype_expr.typ = Bool - return (issubtype_expr, issubtype_stmts) - end - - if length(atype_unlimited.parameters) - 1 > sv.params.MAX_TUPLETYPE_LEN - atype = limit_tuple_type(atype_unlimited, sv.params) - else - atype = atype_unlimited - end - if invoke_data === nothing - min_valid = UInt[typemin(UInt)] - max_valid = UInt[typemax(UInt)] - meth = _methods_by_ftype(atype, 1, sv.params.world, min_valid, max_valid) - if meth === false || length(meth) != 1 - return invoke_NF(argexprs, e.typ, atypes, sv, - atype_unlimited, invoke_data) - end - meth = meth[1]::SimpleVector - metharg = meth[1]::Type - methsp = meth[2]::SimpleVector - method = meth[3]::Method - else - invoke_data = invoke_data::InvokeData - method = invoke_data.entry.func - (metharg, methsp) = ccall(:jl_match_method, Ref{SimpleVector}, (Any, Any), - atype_unlimited, method.sig) - methsp = methsp::SimpleVector - end - - methsig = method.sig - if !(atype <: metharg) - return invoke_NF(argexprs, e.typ, atypes, sv, atype_unlimited, - invoke_data) - end - - # check whether call can be inlined to just a quoted constant value - if isa(f, widenconst(ft)) && !method.isstaged - if f === return_type - if isconstType(e.typ) - return inline_as_constant(e.typ.parameters[1], argexprs, sv, invoke_data) - elseif isa(e.typ, Const) - return inline_as_constant(e.typ.val, argexprs, sv, invoke_data) - end - elseif method.pure && isa(e.typ, Const) && e.typ.actual - return inline_as_constant(e.typ.val, argexprs, sv, invoke_data) - end - end - - argexprs0 = argexprs - na = Int(method.nargs) - # check for vararg function - isva = false - if na > 0 && method.isva - @assert length(argexprs) >= na - 1 - # construct tuple-forming expression for argument tail - vararg = mk_tuplecall(argexprs[na:end], sv) - argexprs = Any[argexprs[1:(na - 1)]..., vararg] - isva = true - elseif na != length(argexprs) - # we have a method match only because an earlier - # inference step shortened our call args list, even - # though we have too many arguments to actually - # call this function - return NF - end - - @assert na == length(argexprs) - - for i = 1:length(methsp) - si = methsp[i] - isa(si, TypeVar) && return NF - end - - # some gf have special tfunc, meaning they wouldn't have been inferred yet - # check the same conditions from abstract_call to detect this case - force_infer = false - if !method.isstaged - if method.module == _topmod(method.module) || (isdefined(Main, :Base) && method.module == Main.Base) - la = length(atypes) - if (la==3 && (method.name == :getindex || method.name == :next)) || - (la==4 && method.name == :indexed_next) - if atypes[3] ⊑ Int - at2 = widenconst(atypes[2]) - if (at2 <: Tuple || at2 <: SimpleVector || - (isa(at2, DataType) && (at2::DataType).name === Pair_name())) - force_infer = true - end - end - elseif la == 2 && method.name == :length && atypes[2] ⊑ SimpleVector - force_infer = true - end - end - end - - # see if the method has been previously inferred (and cached) - linfo = code_for_method(method, metharg, methsp, sv.params.world, !force_infer) # Union{Void, MethodInstance} - isa(linfo, MethodInstance) || return invoke_NF(argexprs0, e.typ, atypes, sv, - atype_unlimited, invoke_data) - linfo = linfo::MethodInstance - if linfo.jlcall_api == 2 - # in this case function can be inlined to a constant - add_backedge!(linfo, sv) - return inline_as_constant(linfo.inferred_const, argexprs, sv, invoke_data) - end - - # see if the method has a current InferenceState frame - # or existing inferred code info - frame = nothing # Union{Void, InferenceState} - inferred = nothing # Union{Void, CodeInfo} - if force_infer && la > 2 && isa(atypes[3], Const) - # Since we inferred this with the information that atypes[3]::Const, - # must inline with that same information. - # We do that by overriding the argument type, - # while ensuring we don't cache that information - # This isn't particularly important for `getindex`, - # as we'll be able to fix that up at the end of inlinable when we verify the return type. - # But `next` and `indexed_next` make tuples which would end up burying some of that information in the AST - # where we can't easily correct it afterwards. - frame = InferenceState(linfo, #=optimize=#true, #=cache=#false, sv.params) - frame.stmt_types[1][3] = VarState(atypes[3], false) - typeinf(frame) - else - if isdefined(linfo, :inferred) && linfo.inferred !== nothing - # use cache - inferred = linfo.inferred - elseif force_infer - # create inferred code on-demand - # but if we decided in the past not to try to infer this particular signature - # (due to signature coarsening in abstract_call_gf_by_type) - # don't infer it now, as attempting to force it now would be a bad idea (non terminating) - frame = typeinf_frame(linfo, #=optimize=#true, #=cache=#true, sv.params) - end - end - - # compute the return value - if isa(frame, InferenceState) - frame = frame::InferenceState - linfo = frame.linfo - inferred = frame.src - if frame.const_api # handle like jlcall_api == 2 - if frame.inferred || !frame.cached - add_backedge!(frame.linfo, sv) - else - add_backedge!(frame, sv, 0) - end - if isa(frame.bestguess, Const) - inferred_const = (frame.bestguess::Const).val - else - @assert isconstType(frame.bestguess) - inferred_const = frame.bestguess.parameters[1] - end - return inline_as_constant(inferred_const, argexprs, sv, invoke_data) - end - rettype = widenconst(frame.bestguess) - else - rettype = linfo.rettype - end - - # check that the code is inlineable - if inferred === nothing - src_inferred = src_inlineable = false - else - src_inferred = ccall(:jl_ast_flag_inferred, Bool, (Any,), inferred) - src_inlineable = ccall(:jl_ast_flag_inlineable, Bool, (Any,), inferred) - end - if !src_inferred || !src_inlineable - return invoke_NF(argexprs0, e.typ, atypes, sv, atype_unlimited, - invoke_data) - end - - if isa(inferred, CodeInfo) - src = inferred - ast = copy_exprargs(inferred.code) - else - src = ccall(:jl_uncompress_ast, Any, (Any, Any), method, inferred)::CodeInfo - ast = src.code - end - ast = ast::Array{Any,1} - - # `promote` is a tuple-returning function that is very important to inline - if isdefined(Main, :Base) && isdefined(Main.Base, :promote) && - length(sv.src.slottypes) > 0 && sv.src.slottypes[1] ⊑ typeof(getfield(Main.Base, :promote)) - # check for non-isbits Tuple return - if sv.bestguess ⊑ Tuple && !isbits(widenconst(sv.bestguess)) - # See if inlining this call would change the enclosing function - # from inlineable to not inlineable. - # This heuristic is applied to functions that return non-bits - # tuples, since we want to be able to inline those functions to - # avoid the tuple allocation. - current_stmts = vcat(sv.src.code, pending_stmts) - if inline_worthy_stmts(current_stmts) - append!(current_stmts, ast) - if !inline_worthy_stmts(current_stmts) - return invoke_NF(argexprs0, e.typ, atypes, sv, atype_unlimited, - invoke_data) - end - end - end - end - - # create the backedge - if isa(frame, InferenceState) && !frame.inferred && frame.cached - # in this case, the actual backedge linfo hasn't been computed - # yet, but will be when inference on the frame finishes - add_backedge!(frame, sv, 0) - else - add_backedge!(linfo, sv) - end - - spvals = Any[] - for i = 1:length(methsp) - push!(spvals, methsp[i]) - end - for i = 1:length(spvals) - si = spvals[i] - if isa(si, Symbol) || isa(si, SSAValue) || isa(si, Slot) - spvals[i] = QuoteNode(si) - end - end - - nm = length(unwrap_unionall(metharg).parameters) - - body = Expr(:block) - body.args = ast - propagate_inbounds = src.propagate_inbounds - - # see if each argument occurs only once in the body expression - stmts = [] - prelude_stmts = [] - stmts_free = true # true = all entries of stmts are effect_free - - for i = na:-1:1 # stmts_free needs to be calculated in reverse-argument order - #args_i = args[i] - aei = argexprs[i] - aeitype = argtype = widenconst(exprtype(aei, sv.src, sv.mod)) - if i == 1 && !(invoke_texpr === nothing) - unshift!(prelude_stmts, invoke_texpr) - end - - # ok for argument to occur more than once if the actual argument - # is a symbol or constant, or is not affected by previous statements - # that will exist after the inlining pass finishes - affect_free = stmts_free # false = previous statements might affect the result of evaluating argument - occ = 0 - for j = length(body.args):-1:1 - b = body.args[j] - if occ < 6 - occ += occurs_more(b, x->(isa(x, Slot) && slot_id(x) == i), 6) - end - if occ > 0 && affect_free && !effect_free(b, src, method.module, true) - #TODO: we might be able to short-circuit this test better by memoizing effect_free(b) in the for loop over i - affect_free = false - end - if occ > 5 && !affect_free - break - end - end - free = effect_free(aei, sv.src, sv.mod, true) - if ((occ==0 && aeitype===Bottom) || (occ > 1 && !inline_worthy(aei, occ*2000)) || - (affect_free && !free) || (!affect_free && !effect_free(aei, sv.src, sv.mod, false))) - if occ != 0 - vnew = newvar!(sv, aeitype) - argexprs[i] = vnew - unshift!(prelude_stmts, Expr(:(=), vnew, aei)) - stmts_free &= free - elseif !free && !isType(aeitype) - unshift!(prelude_stmts, aei) - stmts_free = false - end - end - end - invoke_fexpr === nothing || unshift!(prelude_stmts, invoke_fexpr) - - # re-number the SSAValues and copy their type-info to the new ast - ssavalue_types = src.ssavaluetypes - if !isempty(ssavalue_types) - incr = length(sv.src.ssavaluetypes) - if incr != 0 - body = ssavalue_increment(body, incr) - end - append!(sv.src.ssavaluetypes, ssavalue_types) - end - - # ok, substitute argument expressions for argument names in the body - body = substitute!(body, na, argexprs, method.sig, spvals, length(sv.src.slotnames) - na) - append!(sv.src.slotnames, src.slotnames[(na + 1):end]) - append!(sv.src.slottypes, src.slottypes[(na + 1):end]) - append!(sv.src.slotflags, src.slotflags[(na + 1):end]) - - # make labels / goto statements unique - # relocate inlining information - newlabels = zeros(Int,label_counter(body.args)+1) - for i = 1:length(body.args) - a = body.args[i] - if isa(a,LabelNode) - a = a::LabelNode - newlabel = genlabel(sv) - newlabels[a.label+1] = newlabel.label - body.args[i] = newlabel - end - end - for i = 1:length(body.args) - a = body.args[i] - if isa(a,GotoNode) - a = a::GotoNode - body.args[i] = GotoNode(newlabels[a.label+1]) - elseif isa(a,Expr) - a = a::Expr - if a.head === :enter - a.args[1] = newlabels[a.args[1]+1] - elseif a.head === :gotoifnot - a.args[2] = newlabels[a.args[2]+1] - end - end - end - - # convert return statements into a series of goto's - retstmt = genlabel(sv) - local retval - multiret = false - lastexpr = pop!(body.args) - if isa(lastexpr,LabelNode) - push!(body.args, lastexpr) - push!(body.args, Expr(:call, GlobalRef(topmod, :error), "fatal error in type inference (lowering)")) - lastexpr = nothing - elseif !(isa(lastexpr,Expr) && lastexpr.head === :return) - # code sometimes ends with a meta node, e.g. inbounds pop - push!(body.args, lastexpr) - lastexpr = nothing - end - for a in body.args - push!(stmts, a) - if isa(a,Expr) - a = a::Expr - if a.head === :return - if !multiret - # create slot first time - retval = add_slot!(sv.src, rettype, false) - end - multiret = true - unshift!(a.args, retval) - a.head = :(=) - push!(stmts, GotoNode(retstmt.label)) - end - end - end - - if multiret - if lastexpr !== nothing - unshift!(lastexpr.args, retval) - lastexpr.head = :(=) - push!(stmts, lastexpr) - end - push!(stmts, retstmt) - expr = retval - else - # Dead code elimination can leave a non-return statement at the end - if lastexpr === nothing - expr = nothing - else - expr = lastexpr.args[1] - end - end - - inlining_ignore = function (stmt::ANY) - isa(stmt, Expr) && return is_meta_expr(stmt::Expr) - isa(stmt, LineNumberNode) && return true - stmt === nothing && return true - return false - end - - do_coverage = coverage_enabled() - if do_coverage - line = method.line - if !isempty(stmts) && isa(stmts[1], LineNumberNode) - line = (shift!(stmts)::LineNumberNode).line - end - # Check if we are switching module, which is necessary to catch user - # code inlined into `Base` with `--code-coverage=user`. - # Assume we are inlining directly into `enclosing` instead of another - # function inlined in it - mod = method.module - if mod === sv.mod - unshift!(stmts, Expr(:meta, :push_loc, method.file, - method.name, line)) - else - unshift!(stmts, Expr(:meta, :push_loc, method.file, - method.name, line, mod)) - end - push!(stmts, Expr(:meta, :pop_loc)) - elseif !isempty(stmts) - if all(inlining_ignore, stmts) - empty!(stmts) - else - line::Int = method.line - if isa(stmts[1], LineNumberNode) - line = (shift!(stmts)::LineNumberNode).line - end - unshift!(stmts, Expr(:meta, :push_loc, method.file, - method.name, line)) - if isa(stmts[end], LineNumberNode) - stmts[end] = Expr(:meta, :pop_loc) - else - push!(stmts, Expr(:meta, :pop_loc)) - end - end - end - if !isempty(stmts) && !propagate_inbounds - # avoid redundant inbounds annotations - s_1, s_end = stmts[1], stmts[end] - i = 2 - while length(stmts) > i && ((isa(s_1,Expr)&&s_1.head===:line) || isa(s_1,LineNumberNode)) - s_1 = stmts[i] - i += 1 - end - if isa(s_1, Expr) && s_1.head === :inbounds && s_1.args[1] === false && - isa(s_end, Expr) && s_end.head === :inbounds && s_end.args[1] === :pop - else - # inlined statements are out-of-bounds by default - unshift!(stmts, Expr(:inbounds, false)) - push!(stmts, Expr(:inbounds, :pop)) - end - end - - if isa(expr,Expr) - old_t = e.typ - if old_t ⊑ expr.typ - # if we had better type information than the content being inlined, - # change the return type now to use the better type - expr.typ = old_t - end - end - if !isempty(prelude_stmts) - stmts = append!(prelude_stmts, stmts) - end - return (expr, stmts) -end - -inline_worthy(body::ANY, cost::Integer) = true - -# should the expression be part of the inline cost model -function inline_ignore(ex::ANY) - if isa(ex, LineNumberNode) || ex === nothing - return true - end - return isa(ex, Expr) && is_meta_expr(ex::Expr) -end - -function inline_worthy_stmts(stmts::Vector{Any}, cost::Integer = 1000) - body = Expr(:block) - body.args = stmts - return inline_worthy(body, cost) -end - -function inline_worthy(body::Expr, cost::Integer=1000) # precondition: 0 < cost; nominal cost = 1000 - symlim = 1000 + 5_000_000 ÷ cost - nstmt = 0 - for stmt in body.args - if !(isa(stmt, SSAValue) || inline_ignore(stmt)) - nstmt += 1 - end - end - if nstmt < (symlim + 500) ÷ 1000 - symlim *= 16 - symlim ÷= 1000 - if occurs_more(body, e->!inline_ignore(e), symlim) < symlim - return true - end - end - return false -end - -ssavalue_increment(body::ANY, incr) = body -ssavalue_increment(body::SSAValue, incr) = SSAValue(body.id + incr) -function ssavalue_increment(body::Expr, incr) - if is_meta_expr(body) - return body - end - for i in 1:length(body.args) - body.args[i] = ssavalue_increment(body.args[i], incr) - end - return body -end - -const top_getfield = GlobalRef(Core, :getfield) -const top_tuple = GlobalRef(Core, :tuple) - -function mk_getfield(texpr, i, T) - e = Expr(:call, top_getfield, texpr, i) - e.typ = T - return e -end - -function mk_tuplecall(args, sv::InferenceState) - e = Expr(:call, top_tuple, args...) - e.typ = tuple_tfunc(Tuple{Any[widenconst(exprtype(x, sv.src, sv.mod)) for x in args]...}) - return e -end - -function inlining_pass!(sv::InferenceState) - eargs = sv.src.code - i = 1 - stmtbuf = [] - while i <= length(eargs) - ei = eargs[i] - if isa(ei, Expr) - eargs[i] = inlining_pass(ei, sv, stmtbuf, 1) - if !isempty(stmtbuf) - splice!(eargs, i:i-1, stmtbuf) - i += length(stmtbuf) - empty!(stmtbuf) - end - end - i += 1 - end -end - -const corenumtype = Union{Int32, Int64, Float32, Float64} - -# return inlined replacement for `e`, inserting new needed statements -# at index `ins` in `stmts`. -function inlining_pass(e::Expr, sv::InferenceState, stmts, ins) - if e.head === :method - # avoid running the inlining pass on function definitions - return e - end - eargs = e.args - if length(eargs) < 1 - return e - end - arg1 = eargs[1] - isccall = false - i0 = 1 - # don't inline first (global) arguments of ccall, as this needs to be evaluated - # by the interpreter and inlining might put in something it can't handle, - # like another ccall (or try to move the variables out into the function) - if e.head === :foreigncall - # 3 is rewritten to 1 below to handle the callee. - i0 = 3 - isccall = true - elseif is_known_call(e, Core.Intrinsics.llvmcall, sv.src, sv.mod) - i0 = 5 - end - has_stmts = false # needed to preserve order-of-execution - prev_stmts_length = length(stmts) - for _i = length(eargs):-1:i0 - if isccall && _i == 3 - i = 1 - isccallee = true - else - i = _i - isccallee = false - end - ei = eargs[i] - if isa(ei,Expr) - ei = ei::Expr - if ei.head === :& - argloc = ei.args - i = 1 - ei = argloc[1] - if !isa(ei,Expr) - continue - end - ei = ei::Expr - else - argloc = eargs - end - sl0 = length(stmts) - res = inlining_pass(ei, sv, stmts, ins) - ns = length(stmts) - sl0 # number of new statements just added - if isccallee - restype = exprtype(res, sv.src, sv.mod) - if isa(restype, Const) - argloc[i] = restype.val - if !effect_free(res, sv.src, sv.mod, false) - insert!(stmts, ins+ns, res) - end - # Assume this is the last argument to process - break - end - end - if has_stmts && !effect_free(res, sv.src, sv.mod, false) - restype = exprtype(res, sv.src, sv.mod) - vnew = newvar!(sv, restype) - argloc[i] = vnew - insert!(stmts, ins+ns, Expr(:(=), vnew, res)) - else - argloc[i] = res - end - if !has_stmts && ns > 0 && !(_i == i0) - for s = ins:ins+ns-1 - stmt = stmts[s] - if !effect_free(stmt, sv.src, sv.mod, true) - has_stmts = true; break - end - end - end - end - end - if isccall - le = length(eargs) - for i = 4:2:(le - 1) - if eargs[i] === eargs[i + 1] - eargs[i + 1] = 0 - end - end - end - if e.head !== :call - return e - end - - ft = exprtype(arg1, sv.src, sv.mod) - if isa(ft, Const) - f = ft.val - elseif isa(ft, Conditional) - f = nothing - ft = Bool - else - f = nothing - if !( isleaftype(ft) || ft<:Type ) - return e - end - end - - ins += (length(stmts) - prev_stmts_length) - - if sv.params.inlining - if isdefined(Main, :Base) && - ((isdefined(Main.Base, :^) && f === Main.Base.:^) || - (isdefined(Main.Base, :.^) && f === Main.Base.:.^)) && - length(e.args) == 3 - - a2 = e.args[3] - if isa(a2, Symbol) || isa(a2, Slot) || isa(a2, SSAValue) - ta2 = exprtype(a2, sv.src, sv.mod) - if isa(ta2, Const) - a2 = ta2.val - end - end - - square = (a2 === Int32(2) || a2 === Int64(2)) - triple = (a2 === Int32(3) || a2 === Int64(3)) - if square || triple - a1 = e.args[2] - basenumtype = Union{corenumtype, Main.Base.Complex64, Main.Base.Complex128, Main.Base.Rational} - if isa(a1, basenumtype) || ((isa(a1, Symbol) || isa(a1, Slot) || isa(a1, SSAValue)) && - exprtype(a1, sv.src, sv.mod) ⊑ basenumtype) - if square - e.args = Any[GlobalRef(Main.Base,:*), a1, a1] - res = inlining_pass(e, sv, stmts, ins) - else - e.args = Any[GlobalRef(Main.Base,:*), Expr(:call, GlobalRef(Main.Base,:*), a1, a1), a1] - e.args[2].typ = e.typ - res = inlining_pass(e, sv, stmts, ins) - end - return res - end - end - end - end - - for ninline = 1:100 - ata = Vector{Any}(length(e.args)) - ata[1] = ft - for i = 2:length(e.args) - a = exprtype(e.args[i], sv.src, sv.mod) - (a === Bottom || isvarargtype(a)) && return e - ata[i] = a - end - res = inlineable(f, ft, e, ata, sv, stmts) - if isa(res,Tuple) - if isa(res[2],Array) && !isempty(res[2]) - splice!(stmts, ins:ins-1, res[2]) - ins += length(res[2]) - end - res = res[1] - end - - if res !== NF - # iteratively inline apply(f, tuple(...), tuple(...), ...) in order - # to simplify long vararg lists as in multi-arg + - if isa(res,Expr) && is_known_call(res, _apply, sv.src, sv.mod) - e = res::Expr - f = _apply; ft = abstract_eval_constant(f) - else - return res - end - end - - if f === _apply - na = length(e.args) - newargs = Vector{Any}(na-2) - newstmts = Any[] - effect_free_upto = 0 - for i = 3:na - aarg = e.args[i] - argt = exprtype(aarg, sv.src, sv.mod) - t = widenconst(argt) - if isa(aarg,Expr) && (is_known_call(aarg, tuple, sv.src, sv.mod) || is_known_call(aarg, svec, sv.src, sv.mod)) - # apply(f,tuple(x,y,...)) => f(x,y,...) - newargs[i-2] = aarg.args[2:end] - elseif isa(argt,Const) && (isa(argt.val, Tuple) || isa(argt.val, SimpleVector)) && - effect_free(aarg, sv.src, sv.mod, true) - newargs[i-2] = Any[ QuoteNode(x) for x in argt.val ] - elseif isa(aarg, Tuple) || (isa(aarg, QuoteNode) && (isa(aarg.value, Tuple) || isa(aarg.value, SimpleVector))) - if isa(aarg, QuoteNode) - aarg = aarg.value - end - newargs[i-2] = Any[ QuoteNode(x) for x in aarg ] - elseif isa(t, DataType) && t.name === Tuple.name && !isvatuple(t) && - length(t.parameters) <= sv.params.MAX_TUPLE_SPLAT - for k = (effect_free_upto+1):(i-3) - as = newargs[k] - for kk = 1:length(as) - ak = as[kk] - if !effect_free(ak, sv.src, sv.mod, true) - tmpv = newvar!(sv, widenconst(exprtype(ak, sv.src, sv.mod))) - push!(newstmts, Expr(:(=), tmpv, ak)) - as[kk] = tmpv - end - end - end - effect_free_upto = i-3 - if effect_free(aarg, sv.src, sv.mod, true) - # apply(f,t::(x,y)) => f(t[1],t[2]) - tmpv = aarg - else - # apply(f,t::(x,y)) => tmp=t; f(tmp[1],tmp[2]) - tmpv = newvar!(sv, t) - push!(newstmts, Expr(:(=), tmpv, aarg)) - end - tp = t.parameters - newargs[i-2] = Any[ mk_getfield(tmpv,j,tp[j]) for j=1:length(tp) ] - else - # not all args expandable - return e - end - end - splice!(stmts, ins:ins-1, newstmts) - ins += length(newstmts) - e.args = [Any[e.args[2]]; newargs...] - - # now try to inline the simplified call - ft = exprtype(e.args[1], sv.src, sv.mod) - if isa(ft, Const) - f = ft.val - elseif isa(ft, Conditional) - f = nothing - ft = Bool - else - f = nothing - if !( isleaftype(ft) || ft<:Type ) - return e - end - end - else - return e - end - end - return e -end - -const compiler_temp_sym = Symbol("#temp#") - -function add_slot!(src::CodeInfo, typ::ANY, is_sa::Bool, name::Symbol=compiler_temp_sym) - @assert !isa(typ, Const) && !isa(typ, Conditional) - id = length(src.slotnames) + 1 - push!(src.slotnames, name) - push!(src.slottypes, typ) - push!(src.slotflags, Slot_Assigned + is_sa * Slot_AssignedOnce) - return SlotNumber(id) -end - -function is_known_call(e::Expr, func::ANY, src::CodeInfo, mod::Module) - if e.head !== :call - return false - end - f = exprtype(e.args[1], src, mod) - return isa(f, Const) && f.val === func -end - -function is_known_call_p(e::Expr, pred::ANY, src::CodeInfo, mod::Module) - if e.head !== :call - return false - end - f = exprtype(e.args[1], src, mod) - return (isa(f, Const) && pred(f.val)) || (isType(f) && pred(f.parameters[1])) -end - -function record_used(e::ANY, T::ANY, used::Vector{Bool}) - if isa(e,T) - used[e.id+1] = true - elseif isa(e,Expr) - i0 = e.head === :(=) ? 2 : 1 - for i = i0:length(e.args) - record_used(e.args[i], T, used) - end - end -end - -function remove_unused_vars!(src::CodeInfo) - used = fill(false, length(src.slotnames)+1) - used_ssa = fill(false, length(src.ssavaluetypes)+1) - for i = 1:length(src.code) - record_used(src.code[i], Slot, used) - record_used(src.code[i], SSAValue, used_ssa) - end - for i = 1:length(src.code) - e = src.code[i] - if isa(e,NewvarNode) && !used[e.slot.id+1] - src.code[i] = nothing - elseif isa(e,Expr) && e.head === :(=) - if (isa(e.args[1],Slot) && !used[e.args[1].id+1]) || - (isa(e.args[1],SSAValue) && !used_ssa[e.args[1].id+1]) - src.code[i] = e.args[2] - end - end - end -end - -function delete_vars!(src::CodeInfo, r::ObjectIdDict) - filter!(x->!(isa(x,Expr) && (x.head === :(=) || x.head === :const) && - haskey(r, normvar(x.args[1]))), - src.code) - return src -end - -function replace_vars!(src::CodeInfo, r::ObjectIdDict) - for i = 1:length(src.code) - src.code[i] = _replace_vars!(src.code[i], r) - end - return src -end - -function _replace_vars!(e::ANY, r::ObjectIdDict) - if isa(e,SSAValue) || isa(e,Slot) - v = normvar(e) - if haskey(r, v) - return r[v] - end - end - if isa(e,Expr) - for i = 1:length(e.args) - e.args[i] = _replace_vars!(e.args[i], r) - end - end - return e -end - -is_argument(nargs::Int, v::Slot) = slot_id(v) <= nargs - -normslot(s::SlotNumber) = s -normslot(s::TypedSlot) = SlotNumber(slot_id(s)) -normvar(s::Slot) = normslot(s) -normvar(s::SSAValue) = s -normvar(s::ANY) = s - -# given a single-assigned var and its initializer `init`, return what we can -# replace `var` with, or `var` itself if we shouldn't replace it -function get_replacement(table, var::Union{SlotNumber, SSAValue}, init::ANY, nargs, slottypes, ssavaluetypes) - #if isa(init, QuoteNode) # this can cause slight code size increases - # return init - if (isa(init, Expr) && init.head === :static_parameter) || isa(init, corenumtype) || - init === () || init === nothing - return init - elseif isa(init, Slot) && is_argument(nargs, init::Slot) - # the transformation is not ideal if the assignment - # is present for the auto-unbox functionality - # (from inlining improved type inference information) - # and this transformation would worsen the type information - # everywhere later in the function - ityp = isa(init, TypedSlot) ? init.typ : slottypes[(init::SlotNumber).id] - if ityp ⊑ (isa(var,SSAValue) ? ssavaluetypes[var.id + 1] : slottypes[var.id]) - return init - end - elseif isa(init, SSAValue) - if isa(var, SlotNumber) && slottypes[var.id] ⊑ Tuple - # Here we avoid replacing a Slot with an SSAValue when the type is an - # aggregate. That can cause LLVM to generate a bunch of extra memcpys - # if the data ever needs to be stack allocated later. - return var - end - if haskey(table, init) - return get_replacement(table, init, table[init], nargs, slottypes, ssavaluetypes) - end - return init - elseif isa(init, SlotNumber) && haskey(table, init) - return get_replacement(table, init, table[init], nargs, slottypes, ssavaluetypes) - elseif isa(init, TypedSlot) - sl = normslot(init) - if haskey(table, sl) - rep = get_replacement(table, sl, table[sl], nargs, slottypes, ssavaluetypes) - if isa(rep, SlotNumber) - rep = TypedSlot(rep.id, init.typ) - end - return rep - end - end - return var -end - -# remove all single-assigned vars v in "v = x" where x is an argument. -# "sa" is the result of find_sa_vars -function remove_redundant_temp_vars!(src::CodeInfo, nargs::Int, sa::ObjectIdDict) - flags = src.slotflags - slottypes = src.slottypes - ssavaluetypes = src.ssavaluetypes - repls = ObjectIdDict() - for (v, init) in sa - repl = get_replacement(sa, v, init, nargs, slottypes, ssavaluetypes) - compare = isa(repl,TypedSlot) ? normslot(repl) : repl - if compare !== v - repls[v] = repl - end - end - if !isempty(repls) - delete_vars!(src, repls) - replace_vars!(src, repls) - end - return src -end - -# compute set of slots assigned once -function find_sa_vars(src::CodeInfo, nargs::Int) - body = src.code - av = ObjectIdDict() - av2 = ObjectIdDict() - for i = 1:length(body) - e = body[i] - if isa(e,Expr) && e.head === :(=) - lhs = e.args[1] - if isa(lhs, SSAValue) - av[lhs] = e.args[2] - elseif isa(lhs, Slot) - lhs = normslot(lhs) - id = lhs.id - # exclude args and used undef vars - # this transformation is not valid for vars used before def. - # we need to preserve the point of assignment to know where to - # throw errors (issue #4645). - if id > nargs && (src.slotflags[id] & Slot_UsedUndef == 0) - if !haskey(av, lhs) - av[lhs] = e.args[2] - else - av2[lhs] = true - end - end - end - end - end - filter!((v, _) -> !haskey(av2, v), av) - return av -end - -symequal(x::SSAValue, y::SSAValue) = x.id === y.id -symequal(x::Slot , y::Slot) = x.id === y.id -symequal(x::ANY , y::ANY) = x === y - -function occurs_outside_getfield(e::ANY, sym::ANY, - sv::InferenceState, field_count::Int, field_names::ANY) - if e === sym || (isa(e, Slot) && isa(sym, Slot) && slot_id(e) == slot_id(sym)) - return true - end - if isa(e,Expr) - e = e::Expr - head = e.head - is_meta_expr_head(head) && return false - if is_known_call(e, getfield, sv.src, sv.mod) && symequal(e.args[2],sym) - idx = e.args[3] - if isa(idx,QuoteNode) && (idx.value in field_names) - return false - end - if isa(idx,Int) && (1 <= idx <= field_count) - return false - end - return true - end - if head === :(=) - return occurs_outside_getfield(e.args[2], sym, sv, - field_count, field_names) - else - if (head === :block && isa(sym, Slot) && - sv.src.slotflags[slot_id(sym)] & Slot_UsedUndef == 0) - ignore_void = true - else - ignore_void = false - end - for a in e.args - if ignore_void && isa(a, Slot) && slot_id(a) == slot_id(sym) - continue - end - if occurs_outside_getfield(a, sym, sv, field_count, field_names) - return true - end - end - end - end - return false -end - -function void_use_elim_pass!(sv::InferenceState) - # Remove top level SSAValue and slots that is `!usedUndef`. - # Also remove some `nothing` while we are at it.... - not_void_use = function (ex::ANY) - if isa(ex, SSAValue) - # Explicitly listed here for clarity - return false - elseif isa(ex, Slot) - return sv.src.slotflags[slot_id(ex)] & Slot_UsedUndef != 0 - elseif isa(ex, GlobalRef) - ex = ex::GlobalRef - return !isdefined(ex.mod, ex.name) - elseif isa(ex, Expr) - h = ex.head - if h === :return || h === :(=) || h === :gotoifnot || is_meta_expr_head(h) - return true - end - return !effect_free(ex, sv.src, sv.mod, false) - elseif (isa(ex, GotoNode) || isa(ex, LineNumberNode) || - isa(ex, NewvarNode) || isa(ex, Symbol) || isa(ex, LabelNode)) - # This is a list of special types handled by the compiler - return true - end - return false - end - filter!(not_void_use, sv.src.code::Array{Any,1}) - nothing -end - -function meta_elim_pass!(code::Array{Any,1}, propagate_inbounds::Bool, do_coverage::Bool) - # 1. Remove place holders - # - # 2. If coverage is off, remove line number nodes that don't mark any - # real expressions. - # - # 3. Remove top level SSAValue - # - # 4. Handle bounds check elision - # - # 4.1. If check_bounds is always on, delete all `Expr(:boundscheck)` - # 4.2. If check_bounds is always off, delete all boundscheck blocks. - # 4.3. If check_bounds is default, figure out whether each checkbounds - # blocks needs to be eliminated or could be eliminated when inlined - # into another function. Delete the blocks that should be eliminated - # and delete the `Expr(:boundscheck)` for blocks that will never be - # deleted. (i.e. the ones that are not eliminated with - # `length(inbounds_stack) >= 2`) - # - # When deleting IR with boundscheck, keep the label node in order to not - # confuse later passes or codegen. (we could also track if any SSAValue - # is deleted while still having uses that are not but that's a little - # expensive). - # - # 5. Clean up `Expr(:inbounds)` - # - # Delete all `Expr(:inbounds)` that is unnecessary, which is all of them - # for non-default check_bounds. For default check_bounds this includes - # - # * `Expr(:inbounds, true)` in `Expr(:inbounds, true)` - # * `Expr(:inbounds, false)` when - # `!is_inbounds && length(inbounds_stack) >= 2` - # - # Functions without `propagate_inbounds` have an implicit `false` on the - # `inbounds_stack` - # - # There are other cases in which we can eliminate `Expr(:inbounds)` or - # `Expr(:boundscheck)` (e.g. when they don't enclose any non-meta - # expressions). Those are a little harder to detect and are hopefully - # not too common. - check_bounds = JLOptions().check_bounds - - inbounds_stack = propagate_inbounds ? Bool[] : Bool[false] - # Whether the push is deleted (therefore if the pop has to be too) - # Shared for `Expr(:boundscheck)` and `Expr(:inbounds)` - bounds_elim_stack = Bool[] - # The expression index of the push, set to `0` when encountering a - # non-meta expression that might be affect by the push. - # The clearing needs to be propagated up during pop - # This is not pushed to if the push is already eliminated - # Also shared for `Expr(:boundscheck)` and `Expr(:inbounds)` - bounds_push_pos_stack = Int[0] # always non-empty - # Number of boundscheck pushes in a eliminated boundscheck block - void_boundscheck_depth = 0 - is_inbounds = check_bounds == 2 - enabled = true - - # Position of the last line number node without any non-meta expressions - # in between. - prev_dbg_stack = Int[0] # always non-empty - # Whether there's any non-meta exprs after the enclosing `push_loc` - push_loc_pos_stack = Int[0] # always non-empty - - for i in 1:length(code) - ex = code[i] - if ex === nothing - continue - elseif isa(ex, SSAValue) - code[i] = nothing - continue - elseif isa(ex, LabelNode) - prev_dbg_stack[end] = 0 - push_loc_pos_stack[end] = 0 - continue - elseif !do_coverage && (isa(ex, LineNumberNode) || - (isa(ex, Expr) && (ex::Expr).head === :line)) - prev_label = prev_dbg_stack[end] - if prev_label != 0 - code[prev_label] = nothing - end - prev_dbg_stack[end] = i - continue - elseif !isa(ex, Expr) - if enabled - prev_dbg_stack[end] = 0 - push_loc_pos_stack[end] = 0 - bounds_push_pos_stack[end] = 0 - else - code[i] = nothing - end - continue - end - ex = ex::Expr - args = ex.args - head = ex.head - if head === :boundscheck - if !enabled - # we are in an eliminated boundscheck, simply record the number - # of push/pop - if !(args[1] === :pop) - void_boundscheck_depth += 1 - elseif void_boundscheck_depth == 0 - # There must have been a push - pop!(bounds_elim_stack) - enabled = true - else - void_boundscheck_depth -= 1 - end - code[i] = nothing - elseif args[1] === :pop - # This will also delete pops that don't match - if (isempty(bounds_elim_stack) ? true : - pop!(bounds_elim_stack)) - code[i] = nothing - continue - end - push_idx = bounds_push_pos_stack[end] - if length(bounds_push_pos_stack) > 1 - pop!(bounds_push_pos_stack) - end - if push_idx > 0 - code[push_idx] = nothing - code[i] = nothing - else - bounds_push_pos_stack[end] = 0 - end - elseif is_inbounds - code[i] = nothing - push!(bounds_elim_stack, true) - enabled = false - elseif check_bounds == 1 || length(inbounds_stack) >= 2 - # Not inbounds and at least two levels deep, this will never - # be eliminated when inlined to another function. - code[i] = nothing - push!(bounds_elim_stack, true) - else - push!(bounds_elim_stack, false) - push!(bounds_push_pos_stack, i) - end - continue - end - if !enabled && !(do_coverage && head === :meta) - code[i] = nothing - continue - end - if head === :inbounds - if check_bounds != 0 - code[i] = nothing - continue - end - arg1 = args[1] - if arg1 === true - if !isempty(inbounds_stack) && inbounds_stack[end] - code[i] = nothing - push!(bounds_elim_stack, true) - else - is_inbounds = true - push!(bounds_elim_stack, false) - push!(bounds_push_pos_stack, i) - end - push!(inbounds_stack, true) - elseif arg1 === false - if is_inbounds - # There must have been a `true` on the stack so - # `inbounds_stack` must not be empty - if !inbounds_stack[end] - is_inbounds = false - end - push!(bounds_elim_stack, false) - push!(bounds_push_pos_stack, i) - elseif length(inbounds_stack) >= 2 - code[i] = nothing - push!(bounds_elim_stack, true) - else - push!(bounds_elim_stack, false) - push!(bounds_push_pos_stack, i) - end - push!(inbounds_stack, false) - else - # pop - inbounds_len = length(inbounds_stack) - if inbounds_len != 0 - pop!(inbounds_stack) - inbounds_len -= 1 - end - # This will also delete pops that don't match - if (isempty(bounds_elim_stack) ? true : - pop!(bounds_elim_stack)) - # No need to update `is_inbounds` since the push was a no-op - code[i] = nothing - continue - end - if inbounds_len >= 2 - is_inbounds = (inbounds_stack[inbounds_len] || - inbounds_stack[inbounds_len - 1]) - elseif inbounds_len == 1 - is_inbounds = inbounds_stack[inbounds_len] - else - is_inbounds = false - end - push_idx = bounds_push_pos_stack[end] - if length(bounds_push_pos_stack) > 1 - pop!(bounds_push_pos_stack) - end - if push_idx > 0 - code[push_idx] = nothing - code[i] = nothing - else - bounds_push_pos_stack[end] = 0 - end - end - continue - end - if head !== :meta - prev_dbg_stack[end] = 0 - push_loc_pos_stack[end] = 0 - bounds_push_pos_stack[end] = 0 - continue - end - nargs = length(args) - if do_coverage || nargs == 0 - continue - end - arg1 = args[1] - if arg1 === :push_loc - push!(prev_dbg_stack, 0) - push!(push_loc_pos_stack, i) - elseif arg1 === :pop_loc - prev_dbg = if length(prev_dbg_stack) > 1 - pop!(prev_dbg_stack) - else - prev_dbg_stack[end] - end - if prev_dbg > 0 - code[prev_dbg] = nothing - end - push_loc = if length(push_loc_pos_stack) > 1 - pop!(push_loc_pos_stack) - else - push_loc_pos_stack[end] - end - if push_loc > 0 - code[push_loc] = nothing - code[i] = nothing - else - prev_dbg_stack[end] = 0 - push_loc_pos_stack[end] = 0 - end - else - continue - end - end - return filter!(x -> x !== nothing, code) -end - -# does the same job as alloc_elim_pass for allocations inline in getfields -# TODO can probably be removed when we switch to a linear IR -function getfield_elim_pass!(sv::InferenceState) - body = sv.src.code - for i = 1:length(body) - body[i] = _getfield_elim_pass!(body[i], sv) - end -end - -function _getfield_elim_pass!(e::Expr, sv::InferenceState) - for i = 1:length(e.args) - e.args[i] = _getfield_elim_pass!(e.args[i], sv) - end - if is_known_call(e, getfield, sv.src, sv.mod) && length(e.args)==3 && - (isa(e.args[3],Int) || isa(e.args[3],QuoteNode)) - e1 = e.args[2] - j = e.args[3] - if isa(e1,Expr) - alloc = is_allocation(e1, sv) - if alloc !== false - flen, fnames = alloc - if isa(j,QuoteNode) - j = findfirst(fnames, j.value) - end - if 1 <= j <= flen - ok = true - for k = 2:length(e1.args) - k == j+1 && continue - if !effect_free(e1.args[k], sv.src, sv.mod, true) - ok = false; break - end - end - if ok - return e1.args[j+1] - end - end - end - elseif isa(e1, GlobalRef) || isa(e1, Symbol) || isa(e1, Slot) || isa(e1, SSAValue) - # non-self-quoting value - else - if isa(e1, QuoteNode) - e1 = e1.value - end - if isimmutable(e1) || isa(e1,SimpleVector) - # SimpleVector length field is immutable - if isa(j, QuoteNode) - j = j.value - if !(isa(j,Int) || isa(j,Symbol)) - return e - end - end - if isdefined(e1, j) - e1j = getfield(e1, j) - if !is_self_quoting(e1j) - e1j = QuoteNode(e1j) - end - return e1j - end - end - end - end - return e -end - -_getfield_elim_pass!(e::ANY, sv) = e - -# check if e is a successful allocation of an struct -# if it is, returns (n,f) such that it is always valid to call -# getfield(..., 1 <= x <= n) or getfield(..., x in f) on the result -function is_allocation(e::ANY, sv::InferenceState) - isa(e, Expr) || return false - if is_known_call(e, tuple, sv.src, sv.mod) - return (length(e.args)-1,()) - elseif e.head === :new - typ = widenconst(exprtype(e, sv.src, sv.mod)) - if isa(typ, DataType) && isleaftype(typ) - nf = length(e.args) - 1 - names = fieldnames(typ) - @assert(nf <= nfields(typ)) - if nf < nfields(typ) - # some fields were left undef - # we could potentially propagate Bottom - # for pointer fields - names = names[1:nf] - end - return (nf, names) - end - end - false -end - -# Replace branches with constant conditions with unconditional branches -function gotoifnot_elim_pass!(sv::InferenceState) - body = sv.src.code - i = 1 - while i < length(body) - expr = body[i] - i += 1 - isa(expr, Expr) || continue - expr = expr::Expr - expr.head === :gotoifnot || continue - cond = expr.args[1] - condt = exprtype(cond, sv.src, sv.mod) - isa(condt, Const) || continue - val = (condt::Const).val - # Codegen should emit an unreachable if val is not a Bool so - # we don't need to do anything (also, type inference currently - # doesn't recognize the error for strictly non-Bool condition) - if isa(val, Bool) - # in case there's side effects... (like raising `UndefVarError`) - body[i - 1] = cond - if val === false - insert!(body, i, GotoNode(expr.args[2])) - i += 1 - end - end - end -end - -# eliminate allocation of unnecessary objects -# that are only used as arguments to safe getfield calls -function alloc_elim_pass!(sv::InferenceState) - body = sv.src.code - bexpr = Expr(:block) - bexpr.args = body - vs = find_sa_vars(sv.src, sv.nargs) - remove_redundant_temp_vars!(sv.src, sv.nargs, vs) - remove_unused_vars!(sv.src) - i = 1 - while i < length(body) - e = body[i] - if !isa(e, Expr) - i += 1 - continue - end - e = e::Expr - if e.head === :(=) && (isa(e.args[1], SSAValue) || - (isa(e.args[1], Slot) && haskey(vs, normslot(e.args[1])))) - var = e.args[1] - rhs = e.args[2] - # Need to make sure LLVM can recognize this as LLVM ssa value too - is_ssa = (isa(var, SSAValue) || - sv.src.slotflags[slot_id(var)] & Slot_UsedUndef == 0) - else - var = nothing - rhs = e - is_ssa = false # doesn't matter as long as it's a Bool... - end - alloc = is_allocation(rhs, sv) - if alloc !== false - nv, field_names = alloc - tup = rhs.args - # This makes sure the value doesn't escape so we can elide - # allocation of mutable structs too - if (var !== nothing && - occurs_outside_getfield(bexpr, var, sv, nv, field_names)) - i += 1 - continue - end - - deleteat!(body, i) # remove tuple allocation - # convert tuple allocation to a series of local var assignments - n_ins = 0 - if var === nothing - for j=1:nv - tupelt = tup[j+1] - if !(isa(tupelt,Number) || isa(tupelt,AbstractString) || - isa(tupelt,QuoteNode) || isa(tupelt, SSAValue)) - insert!(body, i+n_ins, tupelt) - n_ins += 1 - end - end - else - vals = Vector{Any}(nv) - local new_slots::Vector{Int} - if !is_ssa - new_slots = Vector{Int}(nv) - end - for j=1:nv - tupelt = tup[j+1] - # If `!is_ssa` we have to create new variables for each - # (used) fields in order to preserve the undef check. - if is_ssa && (isa(tupelt,Number) || - isa(tupelt,AbstractString) || - isa(tupelt,QuoteNode) || isa(tupelt, SSAValue)) - vals[j] = tupelt - else - elty = exprtype(tupelt, sv.src, sv.mod) - if is_ssa - tmpv = newvar!(sv, elty) - else - tmpv = add_slot!(sv.src, widenconst(elty), false, - sv.src.slotnames[slot_id(var)]) - tmpv_id = slot_id(tmpv) - new_slots[j] = tmpv_id - sv.src.slotflags[tmpv_id] |= Slot_UsedUndef - end - tmp = Expr(:(=), tmpv, tupelt) - insert!(body, i+n_ins, tmp) - vals[j] = tmpv - n_ins += 1 - end - end - replace_getfield!(bexpr, var, vals, field_names, sv) - if !is_ssa - i += replace_newvar_node!(body, slot_id(var), - new_slots, i) - elseif isa(var, Slot) - # occurs_outside_getfield might have allowed - # void use of the slot, we need to delete them too - i -= delete_void_use!(body, var, i) - end - end - # Do not increment counter and do the optimization recursively - # on the allocation of fields too. - # This line can probably be added back for linear IR - # i += n_ins - else - i += 1 - end - end -end - -# Return the number of expressions added before `i0` -function replace_newvar_node!(body, orig, new_slots, i0) - nvars = length(new_slots) - nvars == 0 && return 0 - narg = length(body) - i = 1 - nins = 0 - newvars = [ NewvarNode(SlotNumber(id)) for id in new_slots ] - while i <= narg - a = body[i] - if isa(a, NewvarNode) && slot_id((a::NewvarNode).slot) == orig - splice!(body, i, newvars) - if i - nins < i0 - nins += nvars - 1 - end - narg += nvars - 1 - i += nvars - else - i += 1 - end - end - return nins -end - -# Return the number of expressions deleted before `i0` -function delete_void_use!(body, var::Slot, i0) - narg = length(body) - i = 1 - ndel = 0 - while i <= narg - a = body[i] - if isa(a, Slot) && slot_id(a) == slot_id(var) - deleteat!(body, i) - if i + ndel < i0 - ndel += 1 - end - narg -= 1 - else - i += 1 - end - end - return ndel -end - -function replace_getfield!(e::Expr, tupname, vals, field_names, sv::InferenceState) - for i = 1:length(e.args) - a = e.args[i] - if isa(a,Expr) && is_known_call(a, getfield, sv.src, sv.mod) && - symequal(a.args[2],tupname) - idx = if isa(a.args[3], Int) - a.args[3] - else - @assert isa(a.args[3], QuoteNode) - findfirst(field_names, a.args[3].value) - end - @assert(idx > 0) # clients should check that all getfields are valid - val = vals[idx] - # original expression might have better type info than - # the tuple element expression that's replacing it. - if isa(val, Slot) - val = val::Slot - id = slot_id(val) - valtyp = isa(val, TypedSlot) ? val.typ : sv.src.slottypes[id] - if a.typ ⊑ valtyp && !(valtyp ⊑ a.typ) - if isa(val, TypedSlot) - val = TypedSlot(id, a.typ) - end - sv.src.slottypes[id] = widenconst(a.typ) - end - elseif isa(val,SSAValue) - val = val::SSAValue - typ = exprtype(val, sv.src, sv.mod) - if a.typ ⊑ typ && !(typ ⊑ a.typ) - sv.src.ssavaluetypes[val.id + 1] = a.typ - end - end - e.args[i] = val - elseif isa(a, Expr) - replace_getfield!(a::Expr, tupname, vals, field_names, sv) - end - end -end - -# fix label numbers to always equal the statement index of the label -function reindex_labels!(sv::InferenceState) - body = sv.src.code - mapping = zeros(Int, sv.label_counter) - for i = 1:length(body) - el = body[i] - if isa(el,LabelNode) - mapping[el.label] = i - body[i] = LabelNode(i) - end - end - for i = 1:length(body) - el = body[i] - # For goto and enter, the statement and the target has to be - # both reachable or both not. For gotoifnot, the dead code - # elimination in type_annotate! can delete the target - # of a reachable (but never taken) node. In which case we can - # just replace the node with the branch condition. - if isa(el,GotoNode) - labelnum = mapping[el.label] - @assert labelnum !== 0 - body[i] = GotoNode(labelnum) - elseif isa(el,Expr) - el = el::Expr - if el.head === :gotoifnot - labelnum = mapping[el.args[2]] - if labelnum !== 0 - el.args[2] = mapping[el.args[2]] - else - # Might have side effects - body[i] = el.args[1] - end - elseif el.head === :enter - labelnum = mapping[el.args[1]] - @assert labelnum !== 0 - el.args[1] = labelnum - end - end - end -end - -function return_type(f::ANY, t::ANY) - params = InferenceParams(ccall(:jl_get_tls_world_age, UInt, ())) - rt = Union{} - if isa(f, Builtin) - rt = builtin_tfunction(f, Any[t.parameters...], nothing, params) - if isa(rt, TypeVar) - rt = rt.ub - else - rt = widenconst(rt) - end - else - for m in _methods(f, t, -1, params.world) - ty = typeinf_type(m[3], m[1], m[2], true, params) - ty === nothing && return Any - rt = tmerge(rt, ty) - rt === Any && break - end - end - return rt -end - -#### bootstrapping #### - -# make sure that typeinf is executed before turning on typeinf_ext -# this ensures that typeinf_ext doesn't recurse before it can add the item to the workq -# especially try to make sure any recursive and leaf functions have concrete signatures, -# since we won't be able to specialize & infer them at runtime - -let fs = Any[typeinf_ext, typeinf, typeinf_edge, occurs_outside_getfield, pure_eval_call], - world = ccall(:jl_get_world_counter, UInt, ()) - for x in t_ffunc_val - push!(fs, x[3]) - end - for i = 1:length(t_ifunc) - if isassigned(t_ifunc, i) - x = t_ifunc[i] - push!(fs, x[3]) - else - println(STDERR, "WARNING: tfunc missing for ", reinterpret(IntrinsicFunction, Int32(i))) - end - end - for f in fs - for m in _methods_by_ftype(Tuple{typeof(f), Vararg{Any}}, 10, typemax(UInt)) - # remove any TypeVars from the intersection - typ = Any[m[1].parameters...] - for i = 1:length(typ) - if isa(typ[i], TypeVar) - typ[i] = typ[i].ub - end - end - typeinf_type(m[3], Tuple{typ...}, m[2], true, InferenceParams(world)) - end - end -end diff --git a/julia-0.6.3/share/julia/base/initdefs.jl b/julia-0.6.3/share/julia/base/initdefs.jl deleted file mode 100644 index 20437a4..0000000 --- a/julia-0.6.3/share/julia/base/initdefs.jl +++ /dev/null @@ -1,91 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -## initdefs.jl - initialization and runtime management definitions - -""" - PROGRAM_FILE - -A string containing the script name passed to Julia from the command line. Note that the -script name remains unchanged from within included files. Alternatively see -[`@__FILE__`](@ref). -""" -PROGRAM_FILE = "" - -""" - ARGS - -An array of the command line arguments passed to Julia, as strings. -""" -const ARGS = String[] - -exit(n) = ccall(:jl_exit, Void, (Int32,), n) -exit() = exit(0) -quit() = exit() - -const roottask = current_task() - -is_interactive = false -isinteractive() = (is_interactive::Bool) - -""" - LOAD_PATH - -An array of paths as strings or custom loader objects for the `require` -function and `using` and `import` statements to consider when loading -code. To create a custom loader type, define the type and then add -appropriate methods to the `Base.load_hook` function with the following -signature: - - Base.load_hook(loader::Loader, name::String, found::Any) - -The `loader` argument is the current value in `LOAD_PATH`, `name` is the -name of the module to load, and `found` is the path of any previously -found code to provide `name`. If no provider has been found earlier in -`LOAD_PATH` then the value of `found` will be `nothing`. Custom loader -functionality is experimental and may break or change in Julia 1.0. -""" -const LOAD_PATH = Any[] -const LOAD_CACHE_PATH = String[] - -function init_load_path() - vers = "v$(VERSION.major).$(VERSION.minor)" - if haskey(ENV, "JULIA_LOAD_PATH") - prepend!(LOAD_PATH, split(ENV["JULIA_LOAD_PATH"], @static is_windows() ? ';' : ':')) - end - push!(LOAD_PATH, abspath(JULIA_HOME, "..", "local", "share", "julia", "site", vers)) - push!(LOAD_PATH, abspath(JULIA_HOME, "..", "share", "julia", "site", vers)) - #push!(LOAD_CACHE_PATH, abspath(JULIA_HOME, "..", "lib", "julia")) #TODO: add a builtin location? -end - -function early_init() - global const JULIA_HOME = ccall(:jl_get_julia_home, Any, ()) - # make sure OpenBLAS does not set CPU affinity (#1070, #9639) - ENV["OPENBLAS_MAIN_FREE"] = get(ENV, "OPENBLAS_MAIN_FREE", - get(ENV, "GOTOBLAS_MAIN_FREE", "1")) - if Sys.CPU_CORES > 8 && !("OPENBLAS_NUM_THREADS" in keys(ENV)) && !("OMP_NUM_THREADS" in keys(ENV)) - # Prevent openblas from starting too many threads, unless/until specifically requested - ENV["OPENBLAS_NUM_THREADS"] = 8 - end -end - -""" - JULIA_HOME - -A string containing the full path to the directory containing the `julia` executable. -""" -:JULIA_HOME - -const atexit_hooks = [] - -atexit(f::Function) = (unshift!(atexit_hooks, f); nothing) - -function _atexit() - for f in atexit_hooks - try - f() - catch err - show(STDERR, err) - println(STDERR) - end - end -end diff --git a/julia-0.6.3/share/julia/base/int.jl b/julia-0.6.3/share/julia/base/int.jl deleted file mode 100644 index fc17516..0000000 --- a/julia-0.6.3/share/julia/base/int.jl +++ /dev/null @@ -1,578 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -## integer arithmetic ## - -# The tuples and types that do not include 128 bit sizes are necessary to handle -# certain issues on 32-bit machines, and also to simplify promotion rules, as -# they are also used elsewhere where Int128/UInt128 support is separated out, -# such as in hashing2.jl - -const BitSigned64_types = (Int8, Int16, Int32, Int64) -const BitUnsigned64_types = (UInt8, UInt16, UInt32, UInt64) -const BitInteger64_types = (BitSigned64_types..., BitUnsigned64_types...) -const BitSigned_types = (BitSigned64_types..., Int128) -const BitUnsigned_types = (BitUnsigned64_types..., UInt128) -const BitInteger_types = (BitSigned_types..., BitUnsigned_types...) - -const BitSigned64 = Union{BitSigned64_types...} -const BitUnsigned64 = Union{BitUnsigned64_types...} -const BitInteger64 = Union{BitInteger64_types...} -const BitSigned = Union{BitSigned_types...} -const BitUnsigned = Union{BitUnsigned_types...} -const BitInteger = Union{BitInteger_types...} -const BitSigned64T = Union{Type{Int8}, Type{Int16}, Type{Int32}, Type{Int64}} -const BitUnsigned64T = Union{Type{UInt8}, Type{UInt16}, Type{UInt32}, Type{UInt64}} - -## integer comparisons ## - -(<)(x::T, y::T) where {T<:BitSigned} = slt_int(x, y) - -(-)(x::BitInteger) = neg_int(x) -(-)(x::T, y::T) where {T<:BitInteger} = sub_int(x, y) -(+)(x::T, y::T) where {T<:BitInteger} = add_int(x, y) -(*)(x::T, y::T) where {T<:BitInteger} = mul_int(x, y) - -inv(x::Integer) = float(one(x)) / float(x) -(/)(x::T, y::T) where {T<:Integer} = float(x) / float(y) -# skip promotion for system integer types -(/)(x::BitInteger, y::BitInteger) = float(x) / float(y) - -""" - isodd(x::Integer) -> Bool - -Returns `true` if `x` is odd (that is, not divisible by 2), and `false` otherwise. - -```jldoctest -julia> isodd(9) -true - -julia> isodd(10) -false -``` -""" -isodd(n::Integer) = rem(n, 2) != 0 - -""" - iseven(x::Integer) -> Bool - -Returns `true` is `x` is even (that is, divisible by 2), and `false` otherwise. - -```jldoctest -julia> iseven(9) -false - -julia> iseven(10) -true -``` -""" -iseven(n::Integer) = !isodd(n) - -signbit(x::Integer) = x < 0 -signbit(x::Unsigned) = false - -flipsign(x::T, y::T) where {T<:BitSigned} = flipsign_int(x, y) - -flipsign(x::Signed, y::Signed) = convert(typeof(x), flipsign(promote_noncircular(x, y)...)) -flipsign(x::Signed, y::Float16) = flipsign(x, bitcast(Int16, y)) -flipsign(x::Signed, y::Float32) = flipsign(x, bitcast(Int32, y)) -flipsign(x::Signed, y::Float64) = flipsign(x, bitcast(Int64, y)) -flipsign(x::Signed, y::Real) = flipsign(x, -oftype(x, signbit(y))) - -copysign(x::Signed, y::Signed) = flipsign(x, x ⊻ y) -copysign(x::Signed, y::Float16) = copysign(x, bitcast(Int16, y)) -copysign(x::Signed, y::Float32) = copysign(x, bitcast(Int32, y)) -copysign(x::Signed, y::Float64) = copysign(x, bitcast(Int64, y)) -copysign(x::Signed, y::Real) = copysign(x, -oftype(x, signbit(y))) - -""" - abs(x) - -The absolute value of `x`. - -When `abs` is applied to signed integers, overflow may occur, -resulting in the return of a negative value. This overflow occurs only -when `abs` is applied to the minimum representable value of a signed -integer. That is, when `x == typemin(typeof(x))`, `abs(x) == x < 0`, -not `-x` as might be expected. - -```jldoctest -julia> abs(-3) -3 - -julia> abs(1 + im) -1.4142135623730951 - -julia> abs(typemin(Int64)) --9223372036854775808 -``` -""" -function abs end - -abs(x::Unsigned) = x -abs(x::Signed) = flipsign(x,x) - -~(n::Integer) = -n-1 - -unsigned(x::Signed) = reinterpret(typeof(convert(Unsigned, zero(x))), x) -unsigned(x::Bool) = convert(Unsigned, x) -unsigned(x) = convert(Unsigned, x) -signed(x::Unsigned) = reinterpret(typeof(convert(Signed, zero(x))), x) -signed(x) = convert(Signed, x) - -div(x::Signed, y::Unsigned) = flipsign(signed(div(unsigned(abs(x)), y)), x) -div(x::Unsigned, y::Signed) = unsigned(flipsign(signed(div(x, unsigned(abs(y)))), y)) - -rem(x::Signed, y::Unsigned) = flipsign(signed(rem(unsigned(abs(x)), y)), x) -rem(x::Unsigned, y::Signed) = rem(x, unsigned(abs(y))) - -fld(x::Signed, y::Unsigned) = div(x, y) - (signbit(x) & (rem(x, y) != 0)) -fld(x::Unsigned, y::Signed) = div(x, y) - (signbit(y) & (rem(x, y) != 0)) - - -""" - mod(x, y) - rem(x, y, RoundDown) - -The reduction of `x` modulo `y`, or equivalently, the remainder of `x` after floored -division by `y`, i.e. -```julia -x - y*fld(x,y) -``` -if computed without intermediate rounding. - -The result will have the same sign as `y`, and magnitude less than `abs(y)` (with some -exceptions, see note below). - -!!! note - - When used with floating point values, the exact result may not be representable by the - type, and so rounding error may occur. In particular, if the exact result is very - close to `y`, then it may be rounded to `y`. - -```jldoctest -julia> mod(8, 3) -2 - -julia> mod(9, 3) -0 - -julia> mod(8.9, 3) -2.9000000000000004 - -julia> mod(eps(), 3) -2.220446049250313e-16 - -julia> mod(-eps(), 3) -3.0 -``` -""" -function mod(x::T, y::T) where T<:Integer - y == -1 && return T(0) # avoid potential overflow in fld - return x - fld(x, y) * y -end -mod(x::Signed, y::Unsigned) = rem(y + unsigned(rem(x, y)), y) -mod(x::Unsigned, y::Signed) = rem(y + signed(rem(x, y)), y) -mod(x::T, y::T) where {T<:Unsigned} = rem(x, y) - -cld(x::Signed, y::Unsigned) = div(x, y) + (!signbit(x) & (rem(x, y) != 0)) -cld(x::Unsigned, y::Signed) = div(x, y) + (!signbit(y) & (rem(x, y) != 0)) - -# Don't promote integers for div/rem/mod since there is no danger of overflow, -# while there is a substantial performance penalty to 64-bit promotion. -div(x::T, y::T) where {T<:BitSigned64} = checked_sdiv_int(x, y) -rem(x::T, y::T) where {T<:BitSigned64} = checked_srem_int(x, y) -div(x::T, y::T) where {T<:BitUnsigned64} = checked_udiv_int(x, y) -rem(x::T, y::T) where {T<:BitUnsigned64} = checked_urem_int(x, y) - - -# fld(x,y) == div(x,y) - ((x>=0) != (y>=0) && rem(x,y) != 0 ? 1 : 0) -fld(x::T, y::T) where {T<:Unsigned} = div(x,y) -function fld(x::T, y::T) where T<:Integer - d = div(x, y) - return d - (signbit(x ⊻ y) & (d * y != x)) -end - -# cld(x,y) = div(x,y) + ((x>0) == (y>0) && rem(x,y) != 0 ? 1 : 0) -function cld(x::T, y::T) where T<:Unsigned - d = div(x, y) - return d + (d * y != x) -end -function cld(x::T, y::T) where T<:Integer - d = div(x, y) - return d + (((x > 0) == (y > 0)) & (d * y != x)) -end - -## integer bitwise operations ## - -(~)(x::BitInteger) = not_int(x) -(&)(x::T, y::T) where {T<:BitInteger} = and_int(x, y) -(|)(x::T, y::T) where {T<:BitInteger} = or_int(x, y) -xor(x::T, y::T) where {T<:BitInteger} = xor_int(x, y) - -bswap(x::Union{Int8, UInt8}) = x -bswap(x::Union{Int16, UInt16, Int32, UInt32, Int64, UInt64, Int128, UInt128}) = - bswap_int(x) - -""" - count_ones(x::Integer) -> Integer - -Number of ones in the binary representation of `x`. - -```jldoctest -julia> count_ones(7) -3 -``` -""" -count_ones(x::BitInteger) = Int(ctpop_int(x)) - -""" - leading_zeros(x::Integer) -> Integer - -Number of zeros leading the binary representation of `x`. - -```jldoctest -julia> leading_zeros(Int32(1)) -31 -``` -""" -leading_zeros(x::BitInteger) = Int(ctlz_int(x)) - -""" - trailing_zeros(x::Integer) -> Integer - -Number of zeros trailing the binary representation of `x`. - -```jldoctest -julia> trailing_zeros(2) -1 -``` -""" -trailing_zeros(x::BitInteger) = Int(cttz_int(x)) - -""" - count_zeros(x::Integer) -> Integer - -Number of zeros in the binary representation of `x`. - -```jldoctest -julia> count_zeros(Int32(2 ^ 16 - 1)) -16 -``` -""" -count_zeros(x::Integer) = count_ones(~x) - -""" - leading_ones(x::Integer) -> Integer - -Number of ones leading the binary representation of `x`. - -```jldoctest -julia> leading_ones(UInt32(2 ^ 32 - 2)) -31 -``` -""" -leading_ones(x::Integer) = leading_zeros(~x) - -""" - trailing_ones(x::Integer) -> Integer - -Number of ones trailing the binary representation of `x`. - -```jldoctest -julia> trailing_ones(3) -2 -``` -""" -trailing_ones(x::Integer) = trailing_zeros(~x) - -## integer comparisons ## - -(< )(x::T, y::T) where {T<:BitUnsigned} = ult_int(x, y) -(<=)(x::T, y::T) where {T<:BitSigned} = sle_int(x, y) -(<=)(x::T, y::T) where {T<:BitUnsigned} = ule_int(x, y) - -==(x::Signed, y::Unsigned) = (x >= 0) & (unsigned(x) == y) -==(x::Unsigned, y::Signed ) = (y >= 0) & (x == unsigned(y)) -<( x::Signed, y::Unsigned) = (x < 0) | (unsigned(x) < y) -<( x::Unsigned, y::Signed ) = (y >= 0) & (x < unsigned(y)) -<=(x::Signed, y::Unsigned) = (x < 0) | (unsigned(x) <= y) -<=(x::Unsigned, y::Signed ) = (y >= 0) & (x <= unsigned(y)) - -## integer shifts ## - -# unsigned shift counts always shift in the same direction ->>(x::BitSigned, y::BitUnsigned) = ashr_int(x, y) ->>(x::BitUnsigned, y::BitUnsigned) = lshr_int(x, y) -<<(x::BitInteger, y::BitUnsigned) = shl_int(x, y) ->>>(x::BitInteger, y::BitUnsigned) = lshr_int(x, y) -# signed shift counts can shift in either direction -# note: this early during bootstrap, `>=` is not yet available -# note: we only define Int shift counts here; the generic case is handled later ->>(x::BitInteger, y::Int) = - select_value(0 <= y, x >> unsigned(y), x << unsigned(-y)) -<<(x::BitInteger, y::Int) = - select_value(0 <= y, x << unsigned(y), x >> unsigned(-y)) ->>>(x::BitInteger, y::Int) = - select_value(0 <= y, x >>> unsigned(y), x << unsigned(-y)) - -## integer conversions ## - -for to in BitInteger_types, from in (BitInteger_types..., Bool) - if !(to === from) - if to.size < from.size - if issubtype(to, Signed) - if issubtype(from, Unsigned) - @eval convert(::Type{$to}, x::($from)) = - checked_trunc_sint($to, check_top_bit(x)) - else - @eval convert(::Type{$to}, x::($from)) = - checked_trunc_sint($to, x) - end - else - @eval convert(::Type{$to}, x::($from)) = - checked_trunc_uint($to, x) - end - @eval rem(x::($from), ::Type{$to}) = trunc_int($to, x) - elseif from === Bool - # Bools use i8 storage and may have garbage in their 7 high bits - @eval convert(::Type{$to}, x::($from)) = zext_int($to, x) & $to(1) - @eval rem(x::($from), ::Type{$to}) = convert($to, x) - elseif from.size < to.size - if issubtype(from, Signed) - if issubtype(to, Unsigned) - @eval convert(::Type{$to}, x::($from)) = - sext_int($to, check_top_bit(x)) - else - @eval convert(::Type{$to}, x::($from)) = - sext_int($to, x) - end - @eval rem(x::($from), ::Type{$to}) = sext_int($to, x) - else - @eval convert(::Type{$to}, x::($from)) = zext_int($to, x) - @eval rem(x::($from), ::Type{$to}) = convert($to, x) - end - else - if !(issubtype(from, Signed) === issubtype(to, Signed)) - # raise InexactError if x's top bit is set - @eval convert(::Type{$to}, x::($from)) = bitcast($to, check_top_bit(x)) - else - @eval convert(::Type{$to}, x::($from)) = bitcast($to, x) - end - @eval rem(x::($from), ::Type{$to}) = bitcast($to, x) - end - end -end - -# @doc isn't available when running in Core at this point. -# Tuple syntax for documention two function signatures at the same time -# doesn't work either at this point. -isdefined(Main, :Base) && for fname in (:mod, :rem) - @eval @doc """ - rem(x::Integer, T::Type{<:Integer}) -> T - mod(x::Integer, T::Type{<:Integer}) -> T - %(x::Integer, T::Type{<:Integer}) -> T - - Find `y::T` such that `x` ≡ `y` (mod n), where n is the number of integers representable - in `T`, and `y` is an integer in `[typemin(T),typemax(T)]`. - If `T` can represent any integer (e.g. `T == BigInt`), then this operation corresponds to - a conversion to `T`. - - ```jldoctest - julia> 129 % Int8 - -127 - ``` - """ -> $fname(x::Integer, T::Type{<:Integer}) -end - -rem(x::T, ::Type{T}) where {T<:Integer} = x -rem(x::Integer, ::Type{Bool}) = ((x & 1) != 0) -mod(x::Integer, ::Type{T}) where {T<:Integer} = rem(x, T) - -unsafe_trunc(::Type{T}, x::Integer) where {T<:Integer} = rem(x, T) -for (Ts, Tu) in ((Int8, UInt8), (Int16, UInt16), (Int32, UInt32), (Int64, UInt64), (Int128, UInt128)) - @eval convert(::Type{Signed}, x::$Tu) = convert($Ts, x) - @eval convert(::Type{Unsigned}, x::$Ts) = convert($Tu, x) -end - -convert(::Type{Signed}, x::Union{Float32, Float64, Bool}) = convert(Int, x) -convert(::Type{Unsigned}, x::Union{Float32, Float64, Bool}) = convert(UInt, x) - -convert(::Type{Integer}, x::Integer) = x -convert(::Type{Integer}, x::Real) = convert(Signed, x) - -round(x::Integer) = x -trunc(x::Integer) = x -floor(x::Integer) = x - ceil(x::Integer) = x - -round(::Type{T}, x::Integer) where {T<:Integer} = convert(T, x) -trunc(::Type{T}, x::Integer) where {T<:Integer} = convert(T, x) -floor(::Type{T}, x::Integer) where {T<:Integer} = convert(T, x) - ceil(::Type{T}, x::Integer) where {T<:Integer} = convert(T, x) - -## integer construction ## - -macro int128_str(s) - return parse(Int128, s) -end - -macro uint128_str(s) - return parse(UInt128, s) -end - -macro big_str(s) - n = tryparse(BigInt, s) - !isnull(n) && return get(n) - n = tryparse(BigFloat, s) - !isnull(n) && return get(n) - message = "invalid number format $s for BigInt or BigFloat" - return :(throw(ArgumentError($message))) -end - -## integer promotions ## - -promote_rule(::Type{Int8}, ::Type{Int16}) = Int16 -promote_rule(::Type{UInt8}, ::Type{UInt16}) = UInt16 -promote_rule(::Type{Int32}, ::Type{<:Union{Int8,Int16}}) = Int32 -promote_rule(::Type{UInt32}, ::Type{<:Union{UInt8,UInt16}}) = UInt32 -promote_rule(::Type{Int64}, ::Type{<:Union{Int8,Int16,Int32}}) = Int64 -promote_rule(::Type{UInt64}, ::Type{<:Union{UInt8,UInt16,UInt32}}) = UInt64 -promote_rule(::Type{Int128}, ::Type{<:BitSigned64}) = Int128 -promote_rule(::Type{UInt128}, ::Type{<:BitUnsigned64}) = UInt128 -for T in BitSigned_types - @eval promote_rule(::Type{<:Union{UInt8,UInt16}}, ::Type{$T}) = - $(sizeof(T) < sizeof(Int) ? Int : T) -end -@eval promote_rule(::Type{UInt32}, ::Type{<:Union{Int8,Int16,Int32}}) = - $(Core.sizeof(Int) == 8 ? Int : UInt) -promote_rule(::Type{UInt32}, ::Type{Int64}) = Int64 -promote_rule(::Type{UInt64}, ::Type{<:BitSigned64}) = UInt64 -promote_rule(::Type{<:Union{UInt32, UInt64}}, ::Type{Int128}) = Int128 -promote_rule(::Type{UInt128}, ::Type{<:BitSigned}) = UInt128 - -_default_type(::Type{Unsigned}) = UInt -_default_type(::Union{Type{Integer},Type{Signed}}) = Int - -## traits ## - -typemin(::Type{Int8 }) = Int8(-128) -typemax(::Type{Int8 }) = Int8(127) -typemin(::Type{UInt8 }) = UInt8(0) -typemax(::Type{UInt8 }) = UInt8(255) -typemin(::Type{Int16 }) = Int16(-32768) -typemax(::Type{Int16 }) = Int16(32767) -typemin(::Type{UInt16}) = UInt16(0) -typemax(::Type{UInt16}) = UInt16(65535) -typemin(::Type{Int32 }) = Int32(-2147483648) -typemax(::Type{Int32 }) = Int32(2147483647) -typemin(::Type{UInt32}) = UInt32(0) -typemax(::Type{UInt32}) = UInt32(4294967295) -typemin(::Type{Int64 }) = -9223372036854775808 -typemax(::Type{Int64 }) = 9223372036854775807 -typemin(::Type{UInt64}) = UInt64(0) -typemax(::Type{UInt64}) = 0xffffffffffffffff -@eval typemin(::Type{UInt128}) = $(convert(UInt128, 0)) -@eval typemax(::Type{UInt128}) = $(bitcast(UInt128, convert(Int128, -1))) -@eval typemin(::Type{Int128} ) = $(convert(Int128, 1) << 127) -@eval typemax(::Type{Int128} ) = $(bitcast(Int128, typemax(UInt128) >> 1)) - -widen(::Type{<:Union{Int8, Int16}}) = Int32 -widen(::Type{Int32}) = Int64 -widen(::Type{Int64}) = Int128 -widen(::Type{<:Union{UInt8, UInt16}}) = UInt32 -widen(::Type{UInt32}) = UInt64 -widen(::Type{UInt64}) = UInt128 - -# a few special cases, -# Int64*UInt64 => Int128 -# |x|<=2^(k-1), |y|<=2^k-1 => |x*y|<=2^(2k-1)-1 -widemul(x::Signed,y::Unsigned) = widen(x) * signed(widen(y)) -widemul(x::Unsigned,y::Signed) = signed(widen(x)) * widen(y) -# multplication by Bool doesn't require widening -widemul(x::Bool,y::Bool) = x * y -widemul(x::Bool,y::Number) = x * y -widemul(x::Number,y::Bool) = x * y - - -## wide multiplication, Int128 multiply and divide ## - -if Core.sizeof(Int) == 4 - function widemul(u::Int64, v::Int64) - local u0::UInt64, v0::UInt64, w0::UInt64 - local u1::Int64, v1::Int64, w1::UInt64, w2::Int64, t::UInt64 - - u0 = u & 0xffffffff; u1 = u >> 32 - v0 = v & 0xffffffff; v1 = v >> 32 - w0 = u0 * v0 - t = reinterpret(UInt64, u1) * v0 + (w0 >>> 32) - w2 = reinterpret(Int64, t) >> 32 - w1 = u0 * reinterpret(UInt64, v1) + (t & 0xffffffff) - hi = u1 * v1 + w2 + (reinterpret(Int64, w1) >> 32) - lo = w0 & 0xffffffff + (w1 << 32) - return Int128(hi) << 64 + Int128(lo) - end - - function widemul(u::UInt64, v::UInt64) - local u0::UInt64, v0::UInt64, w0::UInt64 - local u1::UInt64, v1::UInt64, w1::UInt64, w2::UInt64, t::UInt64 - - u0 = u & 0xffffffff; u1 = u >>> 32 - v0 = v & 0xffffffff; v1 = v >>> 32 - w0 = u0 * v0 - t = u1 * v0 + (w0 >>> 32) - w2 = t >>> 32 - w1 = u0 * v1 + (t & 0xffffffff) - hi = u1 * v1 + w2 + (w1 >>> 32) - lo = w0 & 0xffffffff + (w1 << 32) - return UInt128(hi) << 64 + UInt128(lo) - end - - function *(u::Int128, v::Int128) - u0 = u % UInt64; u1 = Int64(u >> 64) - v0 = v % UInt64; v1 = Int64(v >> 64) - lolo = widemul(u0, v0) - lohi = widemul(reinterpret(Int64, u0), v1) - hilo = widemul(u1, reinterpret(Int64, v0)) - t = reinterpret(UInt128, hilo) + (lolo >>> 64) - w1 = reinterpret(UInt128, lohi) + (t & 0xffffffffffffffff) - return Int128(lolo & 0xffffffffffffffff) + reinterpret(Int128, w1) << 64 - end - - function *(u::UInt128, v::UInt128) - u0 = u % UInt64; u1 = UInt64(u>>>64) - v0 = v % UInt64; v1 = UInt64(v>>>64) - lolo = widemul(u0, v0) - lohi = widemul(u0, v1) - hilo = widemul(u1, v0) - t = hilo + (lolo >>> 64) - w1 = lohi + (t & 0xffffffffffffffff) - return (lolo & 0xffffffffffffffff) + UInt128(w1) << 64 - end - - function div(x::Int128, y::Int128) - (x == typemin(Int128)) & (y == -1) && throw(DivideError()) - return Int128(div(BigInt(x), BigInt(y))) - end - function div(x::UInt128, y::UInt128) - return UInt128(div(BigInt(x), BigInt(y))) - end - - function rem(x::Int128, y::Int128) - return Int128(rem(BigInt(x), BigInt(y))) - end - function rem(x::UInt128, y::UInt128) - return UInt128(rem(BigInt(x), BigInt(y))) - end - - function mod(x::Int128, y::Int128) - return Int128(mod(BigInt(x), BigInt(y))) - end -else - *(x::T, y::T) where {T<:Union{Int128,UInt128}} = mul_int(x, y) - - div(x::Int128, y::Int128) = checked_sdiv_int(x, y) - div(x::UInt128, y::UInt128) = checked_udiv_int(x, y) - - rem(x::Int128, y::Int128) = checked_srem_int(x, y) - rem(x::UInt128, y::UInt128) = checked_urem_int(x, y) -end diff --git a/julia-0.6.3/share/julia/base/interactiveutil.jl b/julia-0.6.3/share/julia/base/interactiveutil.jl deleted file mode 100644 index 6abc70b..0000000 --- a/julia-0.6.3/share/julia/base/interactiveutil.jl +++ /dev/null @@ -1,769 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -# editing files - -""" - editor() - -Determines the editor to use when running functions like `edit`. Returns an Array compatible -for use within backticks. You can change the editor by setting `JULIA_EDITOR`, `VISUAL` or -`EDITOR` as an environment variable. -""" -function editor() - if is_windows() || is_apple() - default_editor = "open" - elseif isfile("/etc/alternatives/editor") - default_editor = "/etc/alternatives/editor" - else - default_editor = "emacs" - end - # Note: the editor path can include spaces (if escaped) and flags. - args = shell_split(get(ENV,"JULIA_EDITOR", get(ENV,"VISUAL", get(ENV,"EDITOR", default_editor)))) - isempty(args) && error("editor is empty") - return args -end - -""" - edit(path::AbstractString, line::Integer=0) - -Edit a file or directory optionally providing a line number to edit the file at. -Returns to the `julia` prompt when you quit the editor. The editor can be changed -by setting `JULIA_EDITOR`, `VISUAL` or `EDITOR` as an environment variable. -""" -function edit(path::AbstractString, line::Integer=0) - command = editor() - name = basename(first(command)) - issrc = length(path)>2 && path[end-2:end] == ".jl" - if issrc - f = find_source_file(path) - f !== nothing && (path = f) - end - background = true - line_unsupported = false - if startswith(name, "emacs") || name == "gedit" - cmd = line != 0 ? `$command +$line $path` : `$command $path` - elseif startswith(name, "vim.") || name == "vi" || name == "vim" || name == "nvim" || name == "mvim" || name == "nano" - cmd = line != 0 ? `$command +$line $path` : `$command $path` - background = false - elseif name == "textmate" || name == "mate" || name == "kate" - cmd = line != 0 ? `$command $path -l $line` : `$command $path` - elseif startswith(name, "subl") || startswith(name, "atom") - cmd = line != 0 ? `$command $path:$line` : `$command $path` - elseif name == "code" || (is_windows() && uppercase(name) == "CODE.EXE") - cmd = line != 0 ? `$command -g $path:$line` : `$command -g $path` - elseif startswith(name, "notepad++") - cmd = line != 0 ? `$command $path -n$line` : `$command $path` - elseif is_apple() && name == "open" - cmd = `open -t $path` - line_unsupported = true - else - cmd = `$command $path` - background = false - line_unsupported = true - end - - if is_windows() && name == "open" - @static is_windows() && # don't emit this ccall on other platforms - systemerror(:edit, ccall((:ShellExecuteW, "shell32"), stdcall, Int, - (Ptr{Void}, Cwstring, Cwstring, Ptr{Void}, Ptr{Void}, Cint), - C_NULL, "open", path, C_NULL, C_NULL, 10) ≤ 32) - elseif background - spawn(pipeline(cmd, stderr=STDERR)) - else - run(cmd) - end - line != 0 && line_unsupported && println("Unknown editor: no line number information passed.\nThe method is defined at line $line.") - - nothing -end - -""" - edit(function, [types]) - -Edit the definition of a function, optionally specifying a tuple of types to -indicate which method to edit. The editor can be changed by setting `JULIA_EDITOR`, -`VISUAL` or `EDITOR` as an environment variable. -""" -edit(f) = edit(functionloc(f)...) -edit(f, t::ANY) = edit(functionloc(f,t)...) -edit(file, line::Integer) = error("could not find source file for function") - -# terminal pager - -if is_windows() - function less(file::AbstractString, line::Integer) - pager = get(ENV, "PAGER", "more") - g = pager == "more" ? "" : "g" - run(Cmd(`$pager +$(line)$(g) \"$file\"`, windows_verbatim = true)) - end -else - function less(file::AbstractString, line::Integer) - pager = get(ENV, "PAGER", "less") - run(`$pager +$(line)g $file`) - end -end - -""" - less(file::AbstractString, [line::Integer]) - -Show a file using the default pager, optionally providing a starting line number. Returns to -the `julia` prompt when you quit the pager. -""" -less(file::AbstractString) = less(file, 1) - -""" - less(function, [types]) - -Show the definition of a function using the default pager, optionally specifying a tuple of -types to indicate which method to see. -""" -less(f) = less(functionloc(f)...) -less(f, t::ANY) = less(functionloc(f,t)...) -less(file, line::Integer) = error("could not find source file for function") - -# clipboard copy and paste - -if is_apple() - function clipboard(x) - open(pipeline(`pbcopy`, stderr=STDERR), "w") do io - print(io, x) - end - end - clipboard() = readstring(`pbpaste`) - -elseif is_linux() || Sys.KERNEL === :FreeBSD - _clipboardcmd = nothing - const _clipboardcmds = Dict( - :copy => Dict( - :xsel => is_linux() ? - `xsel --nodetach --input --clipboard` : `xsel -c`, - :xclip => `xclip -silent -in -selection clipboard`, - ), - :paste => Dict( - :xsel => is_linux() ? - `xsel --nodetach --output --clipboard` : `xsel -p`, - :xclip => `xclip -quiet -out -selection clipboard`, - ) - ) - function clipboardcmd() - global _clipboardcmd - _clipboardcmd !== nothing && return _clipboardcmd - for cmd in (:xclip, :xsel) - success(pipeline(`which $cmd`, DevNull)) && return _clipboardcmd = cmd - end - pkgs = @static if is_linux() - "xsel or xclip" - elseif Sys.KERNEL === :FreeBSD - "x11/xsel or x11/xclip" - end - error("no clipboard command found, please install $pkgs") - end - function clipboard(x) - c = clipboardcmd() - cmd = get(_clipboardcmds[:copy], c, nothing) - if cmd === nothing - error("unexpected clipboard command: $c") - end - open(pipeline(cmd, stderr=STDERR), "w") do io - print(io, x) - end - end - function clipboard() - c = clipboardcmd() - cmd = get(_clipboardcmds[:paste], c, nothing) - if cmd === nothing - error("unexpected clipboard command: $c") - end - readstring(pipeline(cmd, stderr=STDERR)) - end - -elseif is_windows() - # TODO: these functions leak memory and memory locks if they throw an error - function clipboard(x::AbstractString) - if containsnul(x) - throw(ArgumentError("Windows clipboard strings cannot contain NUL character")) - end - systemerror(:OpenClipboard, 0==ccall((:OpenClipboard, "user32"), stdcall, Cint, (Ptr{Void},), C_NULL)) - systemerror(:EmptyClipboard, 0==ccall((:EmptyClipboard, "user32"), stdcall, Cint, ())) - x_u16 = cwstring(x) - # copy data to locked, allocated space - p = ccall((:GlobalAlloc, "kernel32"), stdcall, Ptr{UInt16}, (UInt16, Int32), 2, sizeof(x_u16)) - systemerror(:GlobalAlloc, p==C_NULL) - plock = ccall((:GlobalLock, "kernel32"), stdcall, Ptr{UInt16}, (Ptr{UInt16},), p) - systemerror(:GlobalLock, plock==C_NULL) - ccall(:memcpy, Ptr{UInt16}, (Ptr{UInt16},Ptr{UInt16},Int), plock, x_u16, sizeof(x_u16)) - systemerror(:GlobalUnlock, 0==ccall((:GlobalUnlock, "kernel32"), stdcall, Cint, (Ptr{Void},), plock)) - pdata = ccall((:SetClipboardData, "user32"), stdcall, Ptr{UInt16}, (UInt32, Ptr{UInt16}), 13, p) - systemerror(:SetClipboardData, pdata!=p) - ccall((:CloseClipboard, "user32"), stdcall, Void, ()) - end - clipboard(x) = clipboard(sprint(print, x)::String) - function clipboard() - systemerror(:OpenClipboard, 0==ccall((:OpenClipboard, "user32"), stdcall, Cint, (Ptr{Void},), C_NULL)) - pdata = ccall((:GetClipboardData, "user32"), stdcall, Ptr{UInt16}, (UInt32,), 13) - systemerror(:SetClipboardData, pdata==C_NULL) - systemerror(:CloseClipboard, 0==ccall((:CloseClipboard, "user32"), stdcall, Cint, ())) - plock = ccall((:GlobalLock, "kernel32"), stdcall, Ptr{UInt16}, (Ptr{UInt16},), pdata) - systemerror(:GlobalLock, plock==C_NULL) - # find NUL terminator (0x0000 16-bit code unit) - len = 0 - while unsafe_load(plock, len+1) != 0; len += 1; end - # get Vector{UInt16}, transcode data to UTF-8, make a String of it - s = transcode(String, unsafe_wrap(Array, plock, len)) - systemerror(:GlobalUnlock, 0==ccall((:GlobalUnlock, "kernel32"), stdcall, Cint, (Ptr{UInt16},), plock)) - return s - end - -else - clipboard(x="") = error("`clipboard` function not implemented for $(Sys.KERNEL)") -end - - -""" - clipboard(x) - -Send a printed form of `x` to the operating system clipboard ("copy"). -""" -clipboard(x) - -""" - clipboard() -> AbstractString - -Return a string with the contents of the operating system clipboard ("paste"). -""" -clipboard() - - -# system information - -# used by sysinfo.jl -function _show_cpuinfo(io::IO, info::Sys.CPUinfo, header::Bool=true, prefix::AbstractString=" ") - tck = Sys.SC_CLK_TCK - if header - println(io, info.model, ": ") - print(io, " "^length(prefix)) - if tck > 0 - @printf(io, " %5s %9s %9s %9s %9s %9s\n", - "speed", "user", "nice", "sys", "idle", "irq") - else - @printf(io, " %5s %9s %9s %9s %9s %9s ticks\n", - "speed", "user", "nice", "sys", "idle", "irq") - end - end - print(io, prefix) - if tck > 0 - @printf(io, "%5d MHz %9d s %9d s %9d s %9d s %9d s", - info.speed, info.cpu_times!user / tck, info.cpu_times!nice / tck, - info.cpu_times!sys / tck, info.cpu_times!idle / tck, info.cpu_times!irq / tck) - else - @printf(io, "%5d MHz %9d %9d %9d %9d %9d ticks", - info.speed, info.cpu_times!user, info.cpu_times!nice, - info.cpu_times!sys, info.cpu_times!idle, info.cpu_times!irq) - end -end - - -""" - versioninfo(io::IO=STDOUT, verbose::Bool=false) - -Print information about the version of Julia in use. If the `verbose` argument is `true`, -detailed system information is shown as well. -""" -function versioninfo(io::IO=STDOUT, verbose::Bool=false) - println(io, "Julia Version $VERSION") - if !isempty(GIT_VERSION_INFO.commit_short) - println(io, "Commit $(GIT_VERSION_INFO.commit_short) ($(GIT_VERSION_INFO.date_string))") - end - if ccall(:jl_is_debugbuild, Cint, ())!=0 - println(io, "DEBUG build") - end - println(io, "Platform Info:") - println(io, " OS: ", is_windows() ? "Windows" : is_apple() ? - "macOS" : Sys.KERNEL, " (", Sys.MACHINE, ")") - - cpu = Sys.cpu_info() - println(io, " CPU: ", cpu[1].model) - println(io, " WORD_SIZE: ", Sys.WORD_SIZE) - if verbose - lsb = "" - if is_linux() - try lsb = readchomp(pipeline(`lsb_release -ds`, stderr=DevNull)) end - end - if is_windows() - try lsb = strip(readstring(`$(ENV["COMSPEC"]) /c ver`)) end - end - if !isempty(lsb) - println(io, " ", lsb) - end - if is_unix() - println(io, " uname: ", readchomp(`uname -mprsv`)) - end - println(io, "Memory: $(Sys.total_memory()/2^30) GB ($(Sys.free_memory()/2^20) MB free)") - try println(io, "Uptime: $(Sys.uptime()) sec") end - print(io, "Load Avg: ") - print_matrix(io, Sys.loadavg()') - println(io ) - Sys.cpu_summary(io) - println(io ) - end - if Base.libblas_name == "libopenblas" || BLAS.vendor() == :openblas || BLAS.vendor() == :openblas64 - openblas_config = BLAS.openblas_get_config() - println(io, " BLAS: libopenblas (", openblas_config, ")") - else - println(io, " BLAS: ",libblas_name) - end - println(io, " LAPACK: ",liblapack_name) - println(io, " LIBM: ",libm_name) - println(io, " LLVM: libLLVM-",libllvm_version," (", Sys.JIT, ", ", Sys.cpu_name, ")") - if verbose - println(io, "Environment:") - for (k,v) in ENV - if match(r"JULIA|PATH|FLAG|^TERM$|HOME", String(k)) !== nothing - println(io, " $(k) = $(v)") - end - end - println(io ) - println(io, "Package Directory: ", Pkg.dir()) - Pkg.status(io) - end -end -versioninfo(verbose::Bool) = versioninfo(STDOUT,verbose) - -# displaying type-ambiguity warnings - - -""" - code_warntype([io::IO], f, types) - -Prints lowered and type-inferred ASTs for the methods matching the given generic function -and type signature to `io` which defaults to `STDOUT`. The ASTs are annotated in such a way -as to cause "non-leaf" types to be emphasized (if color is available, displayed in red). -This serves as a warning of potential type instability. Not all non-leaf types are particularly -problematic for performance, so the results need to be used judiciously. -See [`@code_warntype`](@ref man-code-warntype) for more information. -""" -function code_warntype(io::IO, f, t::ANY) - function slots_used(ci, slotnames) - used = falses(length(slotnames)) - scan_exprs!(used, ci.code) - return used - end - - function scan_exprs!(used, exprs) - for ex in exprs - if isa(ex, Slot) - used[ex.id] = true - elseif isa(ex, Expr) - scan_exprs!(used, ex.args) - end - end - end - - emph_io = IOContext(io, :TYPEEMPHASIZE => true) - for (src, rettype) in code_typed(f, t) - println(emph_io, "Variables:") - slotnames = sourceinfo_slotnames(src) - used_slotids = slots_used(src, slotnames) - for i = 1:length(slotnames) - print(emph_io, " ", slotnames[i]) - if used_slotids[i] - if isa(src.slottypes, Array) - show_expr_type(emph_io, src.slottypes[i], true) - end - else - print(emph_io, " ") - end - print(emph_io, '\n') - end - print(emph_io, "\nBody:\n ") - body = Expr(:body) - body.args = src.code - body.typ = rettype - # Fix slot names and types in function body - show_unquoted(IOContext(IOContext(emph_io, :SOURCEINFO => src), - :SOURCE_SLOTNAMES => slotnames), - body, 2) - print(emph_io, '\n') - end - nothing -end -code_warntype(f, t::ANY) = code_warntype(STDOUT, f, t) - -typesof(args...) = Tuple{map(a->(isa(a,Type) ? Type{a} : typeof(a)), args)...} - -gen_call_with_extracted_types(fcn, ex0::Symbol) = Expr(:call, fcn, Meta.quot(ex0)) -function gen_call_with_extracted_types(fcn, ex0) - if isa(ex0, Expr) - if any(a->(Meta.isexpr(a, :kw) || Meta.isexpr(a, :parameters)), ex0.args) - # remove keyword args, but call the kwfunc - args = filter(a->!(Meta.isexpr(a, :kw) || Meta.isexpr(a, :parameters)), ex0.args) - return quote - local arg1 = $(esc(args[1])) - $(fcn)(Core.kwfunc(arg1), - Tuple{Vector{Any}, Core.Typeof(arg1), - $(typesof)($(map(esc, args[2:end])...)).parameters...}) - end - elseif ex0.head == :call - return Expr(:call, fcn, esc(ex0.args[1]), - Expr(:call, typesof, map(esc, ex0.args[2:end])...)) - end - end - exret = Expr(:none) - is_macro = false - ex = expand(ex0) - if isa(ex0, Expr) && ex0.head == :macrocall # Make @edit @time 1+2 edit the macro - is_macro = true - exret = Expr(:call, fcn, esc(ex0.args[1]), typesof(ex0.args[2:end]...)) - elseif !isa(ex, Expr) - exret = Expr(:call, :error, "expression is not a function call or symbol") - elseif ex.head == :call - if any(e->(isa(e, Expr) && e.head==:(...)), ex0.args) && - (ex.args[1] === GlobalRef(Core,:_apply) || - ex.args[1] === GlobalRef(Base,:_apply)) - # check for splatting - exret = Expr(:call, ex.args[1], fcn, - Expr(:tuple, esc(ex.args[2]), - Expr(:call, typesof, map(esc, ex.args[3:end])...))) - else - exret = Expr(:call, fcn, esc(ex.args[1]), - Expr(:call, typesof, map(esc, ex.args[2:end])...)) - end - elseif ex.head == :body - a1 = ex.args[1] - if isa(a1, Expr) && a1.head == :call - a11 = a1.args[1] - if a11 == :setindex! - exret = Expr(:call, fcn, a11, - Expr(:call, typesof, map(esc, a1.args[2:end])...)) - end - end - end - if (!is_macro && ex.head == :thunk) || exret.head == :none - exret = Expr(:call, :error, "expression is not a function call, " - * "or is too complex for @$fcn to analyze; " - * "break it down to simpler parts if possible") - end - exret -end - -for fname in [:which, :less, :edit, :functionloc, :code_warntype, - :code_llvm, :code_llvm_raw, :code_native] - @eval begin - macro ($fname)(ex0) - gen_call_with_extracted_types($(Expr(:quote,fname)), ex0) - end - end -end - -for fname in [:code_typed, :code_lowered] - @eval begin - macro ($fname)(ex0) - thecall = gen_call_with_extracted_types($(Expr(:quote,fname)), ex0) - quote - results = $thecall - length(results) == 1 ? results[1] : results - end - end - end -end - -""" - @which - -Applied to a function or macro call, it evaluates the arguments to the specified call, and -returns the `Method` object for the method that would be called for those arguments. Applied -to a variable, it returns the module in which the variable was bound. It calls out to the -`which` function. -""" -:@which - -""" - @less - -Evaluates the arguments to the function or macro call, determines their types, and calls the `less` -function on the resulting expression. -""" -:@less - -""" - @edit - -Evaluates the arguments to the function or macro call, determines their types, and calls the `edit` -function on the resulting expression. -""" -:@edit - -""" - @functionloc - -Applied to a function or macro call, it evaluates the arguments to the specified call, and -returns a tuple `(filename,line)` giving the location for the method that would be called for those arguments. -It calls out to the `functionloc` function. -""" -:@functionloc - -""" - @code_typed - -Evaluates the arguments to the function or macro call, determines their types, and calls -[`code_typed`](@ref) on the resulting expression. -""" -:@code_typed - -""" - @code_warntype - -Evaluates the arguments to the function or macro call, determines their types, and calls -[`code_warntype`](@ref) on the resulting expression. -""" -:@code_warntype - -""" - @code_lowered - -Evaluates the arguments to the function or macro call, determines their types, and calls -[`code_lowered`](@ref) on the resulting expression. -""" -:@code_lowered - -""" - @code_llvm - -Evaluates the arguments to the function or macro call, determines their types, and calls -[`code_llvm`](@ref) on the resulting expression. -""" -:@code_llvm - -""" - @code_native - -Evaluates the arguments to the function or macro call, determines their types, and calls -[`code_native`](@ref) on the resulting expression. -""" -:@code_native - -function type_close_enough(x::ANY, t::ANY) - x == t && return true - return (isa(x,DataType) && isa(t,DataType) && x.name === t.name && - !isleaftype(t) && x <: t) || - (isa(x,Union) && isa(t,DataType) && (type_close_enough(x.a, t) || type_close_enough(x.b, t))) -end - -# `methodswith` -- shows a list of methods using the type given -""" - methodswith(typ[, module or function][, showparents::Bool=false]) - -Return an array of methods with an argument of type `typ`. - -The optional second argument restricts the search to a particular module or function -(the default is all modules, starting from Main). - -If optional `showparents` is `true`, also return arguments with a parent type of `typ`, -excluding type `Any`. -""" -function methodswith(t::Type, f::Function, showparents::Bool=false, meths = Method[]) - for d in methods(f) - if any(function (x) - let x = rewrap_unionall(x, d.sig) - (type_close_enough(x, t) || - (showparents ? (t <: x && (!isa(x,TypeVar) || x.ub != Any)) : - (isa(x,TypeVar) && x.ub != Any && t == x.ub)) && - x != Any && x != ANY) - end - end, - unwrap_unionall(d.sig).parameters) - push!(meths, d) - end - end - return meths -end - -function methodswith(t::Type, m::Module, showparents::Bool=false) - meths = Method[] - for nm in names(m) - if isdefined(m, nm) - f = getfield(m, nm) - if isa(f, Function) - methodswith(t, f, showparents, meths) - end - end - end - return unique(meths) -end - -function methodswith(t::Type, showparents::Bool=false) - meths = Method[] - mainmod = Main - # find modules in Main - for nm in names(mainmod) - if isdefined(mainmod, nm) - mod = getfield(mainmod, nm) - if isa(mod, Module) - append!(meths, methodswith(t, mod, showparents)) - end - end - end - return unique(meths) -end - -# file downloading - -downloadcmd = nothing -if is_windows() - function download(url::AbstractString, filename::AbstractString) - res = ccall((:URLDownloadToFileW,:urlmon),stdcall,Cuint, - (Ptr{Void},Cwstring,Cwstring,Cuint,Ptr{Void}),C_NULL,url,filename,0,C_NULL) - if res != 0 - error("automatic download failed (error: $res): $url") - end - filename - end -else - function download(url::AbstractString, filename::AbstractString) - global downloadcmd - if downloadcmd === nothing - for checkcmd in (:curl, :wget, :fetch) - if success(pipeline(`which $checkcmd`, DevNull)) - downloadcmd = checkcmd - break - end - end - end - if downloadcmd == :wget - try - run(`wget -O $filename $url`) - catch - rm(filename) # wget always creates a file - rethrow() - end - elseif downloadcmd == :curl - run(`curl -L -f -o $filename $url`) - elseif downloadcmd == :fetch - run(`fetch -f $filename $url`) - else - error("no download agent available; install curl, wget, or fetch") - end - filename - end -end -function download(url::AbstractString) - filename = tempname() - download(url, filename) -end - -""" - download(url::AbstractString, [localfile::AbstractString]) - -Download a file from the given url, optionally renaming it to the given local file name. -Note that this function relies on the availability of external tools such as `curl`, `wget` -or `fetch` to download the file and is provided for convenience. For production use or -situations in which more options are needed, please use a package that provides the desired -functionality instead. -""" -download(url, filename) - -# workspace management - -""" - workspace() - -Replace the top-level module (`Main`) with a new one, providing a clean workspace. The -previous `Main` module is made available as `LastMain`. A previously-loaded package can be -accessed using a statement such as `using LastMain.Package`. - -This function should only be used interactively. -""" -function workspace() - last = Core.Main - b = last.Base - ccall(:jl_new_main_module, Any, ()) - m = Core.Main - ccall(:jl_add_standard_imports, Void, (Any,), m) - eval(m, - Expr(:toplevel, - :(const Base = $(Expr(:quote, b))), - :(const LastMain = $(Expr(:quote, last))))) - empty!(package_locks) - nothing -end - -# testing - -""" - runtests([tests=["all"] [, numcores=ceil(Int, Sys.CPU_CORES / 2) ]]) - -Run the Julia unit tests listed in `tests`, which can be either a string or an array of -strings, using `numcores` processors. (not exported) -""" -function runtests(tests = ["all"], numcores = ceil(Int, Sys.CPU_CORES / 2)) - if isa(tests,AbstractString) - tests = split(tests) - end - ENV2 = copy(ENV) - ENV2["JULIA_CPU_CORES"] = "$numcores" - try - run(setenv(`$(julia_cmd()) $(joinpath(JULIA_HOME, - Base.DATAROOTDIR, "julia", "test", "runtests.jl")) $tests`, ENV2)) - catch - buf = PipeBuffer() - versioninfo(buf) - error("A test has failed. Please submit a bug report (https://github.com/JuliaLang/julia/issues)\n" * - "including error messages above and the output of versioninfo():\n$(readstring(buf))") - end -end - -# testing - - -""" - whos(io::IO=STDOUT, m::Module=current_module(), pattern::Regex=r"") - -Print information about exported global variables in a module, optionally restricted to those matching `pattern`. - -The memory consumption estimate is an approximate lower bound on the size of the internal structure of the object. -""" -function whos(io::IO=STDOUT, m::Module=current_module(), pattern::Regex=r"") - maxline = displaysize(io)[2] - line = zeros(UInt8, maxline) - head = PipeBuffer(maxline + 1) - for v in sort!(names(m)) - s = string(v) - if isdefined(m, v) && ismatch(pattern, s) - value = getfield(m, v) - @printf head "%30s " s - try - if value ∈ (Base, Main, Core) - print(head, " ") - else - bytes = summarysize(value) - if bytes < 10_000 - @printf(head, "%6d bytes ", bytes) - else - @printf(head, "%6d KB ", bytes ÷ (1024)) - end - end - print(head, summary(value)) - catch e - print(head, "#=ERROR: unable to show value=#") - end - newline = search(head, UInt8('\n')) - 1 - if newline < 0 - newline = nb_available(head) - end - if newline > maxline - newline = maxline - 1 # make space for ... - end - line = resize!(line, newline) - line = read!(head, line) - - write(io, line) - if nb_available(head) > 0 # more to read? replace with ... - print(io, '\u2026') # hdots - end - println(io) - seekend(head) # skip the rest of the text - end - end -end -whos(m::Module, pat::Regex=r"") = whos(STDOUT, m, pat) -whos(pat::Regex) = whos(STDOUT, current_module(), pat) diff --git a/julia-0.6.3/share/julia/base/intfuncs.jl b/julia-0.6.3/share/julia/base/intfuncs.jl deleted file mode 100644 index 9eea4a7..0000000 --- a/julia-0.6.3/share/julia/base/intfuncs.jl +++ /dev/null @@ -1,816 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -## number-theoretic functions ## - -""" - gcd(x,y) - -Greatest common (positive) divisor (or zero if `x` and `y` are both zero). - -# Examples -```jldoctest -julia> gcd(6,9) -3 - -julia> gcd(6,-9) -3 -``` -""" -function gcd(a::T, b::T) where T<:Integer - while b != 0 - t = b - b = rem(a, b) - a = t - end - checked_abs(a) -end - -# binary GCD (aka Stein's) algorithm -# about 1.7x (2.1x) faster for random Int64s (Int128s) -function gcd(a::T, b::T) where T<:Union{Int64,UInt64,Int128,UInt128} - a == 0 && return abs(b) - b == 0 && return abs(a) - za = trailing_zeros(a) - zb = trailing_zeros(b) - k = min(za, zb) - u = unsigned(abs(a >> za)) - v = unsigned(abs(b >> zb)) - while u != v - if u > v - u, v = v, u - end - v -= u - v >>= trailing_zeros(v) - end - r = u << k - # T(r) would throw InexactError; we want OverflowError instead - r > typemax(T) && throw(OverflowError()) - r % T -end - -""" - lcm(x,y) - -Least common (non-negative) multiple. - -# Examples -```jldoctest -julia> lcm(2,3) -6 - -julia> lcm(-2,3) -6 -``` -""" -function lcm(a::T, b::T) where T<:Integer - # explicit a==0 test is to handle case of lcm(0,0) correctly - if a == 0 - return a - else - return checked_abs(a * div(b, gcd(b,a))) - end -end - -gcd(a::Integer) = a -lcm(a::Integer) = a -gcd(a::Integer, b::Integer) = gcd(promote(a,b)...) -lcm(a::Integer, b::Integer) = lcm(promote(a,b)...) -gcd(a::Integer, b::Integer...) = gcd(a, gcd(b...)) -lcm(a::Integer, b::Integer...) = lcm(a, lcm(b...)) - -gcd(abc::AbstractArray{<:Integer}) = reduce(gcd,abc) -lcm(abc::AbstractArray{<:Integer}) = reduce(lcm,abc) - -# return (gcd(a,b),x,y) such that ax+by == gcd(a,b) -""" - gcdx(x,y) - -Computes the greatest common (positive) divisor of `x` and `y` and their Bézout -coefficients, i.e. the integer coefficients `u` and `v` that satisfy -``ux+vy = d = gcd(x,y)``. ``gcdx(x,y)`` returns ``(d,u,v)``. - -# Examples -```jldoctest -julia> gcdx(12, 42) -(6, -3, 1) - -julia> gcdx(240, 46) -(2, -9, 47) -``` - -!!! note - Bézout coefficients are *not* uniquely defined. `gcdx` returns the minimal - Bézout coefficients that are computed by the extended Euclidean algorithm. - (Ref: D. Knuth, TAoCP, 2/e, p. 325, Algorithm X.) - For signed integers, these coefficients `u` and `v` are minimal in - the sense that ``|u| < |y/d|`` and ``|v| < |x/d|``. Furthermore, - the signs of `u` and `v` are chosen so that `d` is positive. - For unsigned integers, the coefficients `u` and `v` might be near - their `typemax`, and the identity then holds only via the unsigned - integers' modulo arithmetic. -""" -function gcdx(a::T, b::T) where T<:Integer - # a0, b0 = a, b - s0, s1 = oneunit(T), zero(T) - t0, t1 = s1, s0 - # The loop invariant is: s0*a0 + t0*b0 == a - while b != 0 - q = div(a, b) - a, b = b, rem(a, b) - s0, s1 = s1, s0 - q*s1 - t0, t1 = t1, t0 - q*t1 - end - a < 0 ? (-a, -s0, -t0) : (a, s0, t0) -end -gcdx(a::Integer, b::Integer) = gcdx(promote(a,b)...) - -# multiplicative inverse of n mod m, error if none - -""" - invmod(x,m) - -Take the inverse of `x` modulo `m`: `y` such that ``x y = 1 \\pmod m``, -with ``div(x,y) = 0``. This is undefined for ``m = 0``, or if -``gcd(x,m) \\neq 1``. - -# Examples -```jldoctest -julia> invmod(2,5) -3 - -julia> invmod(2,3) -2 - -julia> invmod(5,6) -5 -``` -""" -function invmod(n::T, m::T) where T<:Integer - g, x, y = gcdx(n, m) - (g != 1 || m == 0) && throw(DomainError()) - # Note that m might be negative here. - # For unsigned T, x might be close to typemax; add m to force a wrap-around. - r = mod(x + m, m) - # The postcondition is: mod(r * n, m) == mod(T(1), m) && div(r, m) == 0 - r -end -invmod(n::Integer, m::Integer) = invmod(promote(n,m)...) - -# ^ for any x supporting * -to_power_type(x::Number) = oftype(x*x, x) -to_power_type(x) = x -function power_by_squaring(x_, p::Integer) - x = to_power_type(x_) - if p == 1 - return copy(x) - elseif p == 0 - return one(x) - elseif p == 2 - return x*x - elseif p < 0 - x == 1 && return copy(x) - x == -1 && return iseven(p) ? one(x) : copy(x) - throw(DomainError()) - end - t = trailing_zeros(p) + 1 - p >>= t - while (t -= 1) > 0 - x *= x - end - y = x - while p > 0 - t = trailing_zeros(p) + 1 - p >>= t - while (t -= 1) >= 0 - x *= x - end - y *= x - end - return y -end -power_by_squaring(x::Bool, p::Unsigned) = ((p==0) | x) -function power_by_squaring(x::Bool, p::Integer) - p < 0 && !x && throw(DomainError()) - return (p==0) | x -end - -^(x::T, p::T) where {T<:Integer} = power_by_squaring(x,p) -^(x::Number, p::Integer) = power_by_squaring(x,p) -^(x, p::Integer) = power_by_squaring(x,p) - -# x^p for any literal integer p is lowered to Base.literal_pow(^, x, Val{p}) -# to enable compile-time optimizations specialized to p. -# However, we still need a fallback that calls the function ^ which may either -# mean Base.^ or something else, depending on context. -# We mark these @inline since if the target is marked @inline, -# we want to make sure that gets propagated, -# even if it is over the inlining threshold. -@inline literal_pow(f, x, ::Type{Val{p}}) where {p} = f(x,p) - -# Restrict inlining to hardware-supported arithmetic types, which -# are fast enough to benefit from inlining. -const HWReal = Union{Int8,Int16,Int32,Int64,UInt8,UInt16,UInt32,UInt64,Float32,Float64} -const HWNumber = Union{HWReal, Complex{<:HWReal}, Rational{<:HWReal}} - -# inference.jl has complicated logic to inline x^2 and x^3 for -# numeric types. In terms of Val we can do it much more simply. -# (The first argument prevents unexpected behavior if a function ^ -# is defined that is not equal to Base.^) -@inline literal_pow(::typeof(^), x::HWNumber, ::Type{Val{0}}) = one(x) -@inline literal_pow(::typeof(^), x::HWNumber, ::Type{Val{1}}) = x -@inline literal_pow(::typeof(^), x::HWNumber, ::Type{Val{2}}) = x*x -@inline literal_pow(::typeof(^), x::HWNumber, ::Type{Val{3}}) = x*x*x - -# b^p mod m - -""" - powermod(x::Integer, p::Integer, m) - -Compute ``x^p \\pmod m``. - -# Examples -```jldoctest -julia> powermod(2, 6, 5) -4 - -julia> mod(2^6, 5) -4 - -julia> powermod(5, 2, 20) -5 - -julia> powermod(5, 2, 19) -6 - -julia> powermod(5, 3, 19) -11 -``` -""" -function powermod(x::Integer, p::Integer, m::T) where T<:Integer - p < 0 && return powermod(invmod(x, m), -p, m) - p == 0 && return mod(one(m),m) - (m == 1 || m == -1) && return zero(m) - b = oftype(m,mod(x,m)) # this also checks for divide by zero - - t = prevpow2(p) - local r::T - r = 1 - while true - if p >= t - r = mod(widemul(r,b),m) - p -= t - end - t >>>= 1 - t <= 0 && break - r = mod(widemul(r,r),m) - end - return r -end - -# optimization: promote the modulus m to BigInt only once (cf. widemul in generic powermod above) -powermod(x::Integer, p::Integer, m::Union{Int128,UInt128}) = oftype(m, powermod(x, p, big(m))) - -# smallest power of 2 >= x - -""" - nextpow2(n::Integer) - -The smallest power of two not less than `n`. Returns 0 for `n==0`, and returns -`-nextpow2(-n)` for negative arguments. - -# Examples -```jldoctest -julia> nextpow2(16) -16 - -julia> nextpow2(17) -32 -``` -""" -nextpow2(x::Unsigned) = oneunit(x)<<((sizeof(x)<<3)-leading_zeros(x-oneunit(x))) -nextpow2(x::Integer) = reinterpret(typeof(x),x < 0 ? -nextpow2(unsigned(-x)) : nextpow2(unsigned(x))) - -""" - prevpow2(n::Integer) - -The largest power of two not greater than `n`. Returns 0 for `n==0`, and returns -`-prevpow2(-n)` for negative arguments. - -# Examples -```jldoctest -julia> prevpow2(5) -4 - -julia> prevpow2(0) -0 -``` -""" -prevpow2(x::Unsigned) = one(x) << unsigned((sizeof(x)<<3)-leading_zeros(x)-1) -prevpow2(x::Integer) = reinterpret(typeof(x),x < 0 ? -prevpow2(unsigned(-x)) : prevpow2(unsigned(x))) - -""" - ispow2(n::Integer) -> Bool - -Test whether `n` is a power of two. - -# Examples -```jldoctest -julia> ispow2(4) -true - -julia> ispow2(5) -false -``` -""" -ispow2(x::Integer) = x > 0 && count_ones(x) == 1 - -""" - nextpow(a, x) - -The smallest `a^n` not less than `x`, where `n` is a non-negative integer. `a` must be -greater than 1, and `x` must be greater than 0. - -# Examples -```jldoctest -julia> nextpow(2, 7) -8 - -julia> nextpow(2, 9) -16 - -julia> nextpow(5, 20) -25 - -julia> nextpow(4, 16) -16 -``` - -See also [`prevpow`](@ref). -""" -function nextpow(a::Real, x::Real) - (a <= 1 || x <= 0) && throw(DomainError()) - x <= 1 && return one(a) - n = ceil(Integer,log(a, x)) - p = a^(n-1) - # guard against roundoff error, e.g., with a=5 and x=125 - p >= x ? p : a^n -end - -""" - prevpow(a, x) - -The largest `a^n` not greater than `x`, where `n` is a non-negative integer. -`a` must be greater than 1, and `x` must not be less than 1. - -# Examples -```jldoctest -julia> prevpow(2, 7) -4 - -julia> prevpow(2, 9) -8 - -julia> prevpow(5, 20) -5 - -julia> prevpow(4, 16) -16 -``` -See also [`nextpow`](@ref). -""" -function prevpow(a::Real, x::Real) - (a <= 1 || x < 1) && throw(DomainError()) - n = floor(Integer,log(a, x)) - p = a^(n+1) - p <= x ? p : a^n -end - -# decimal digits in an unsigned integer -const powers_of_ten = [ - 0x0000000000000001, 0x000000000000000a, 0x0000000000000064, 0x00000000000003e8, - 0x0000000000002710, 0x00000000000186a0, 0x00000000000f4240, 0x0000000000989680, - 0x0000000005f5e100, 0x000000003b9aca00, 0x00000002540be400, 0x000000174876e800, - 0x000000e8d4a51000, 0x000009184e72a000, 0x00005af3107a4000, 0x00038d7ea4c68000, - 0x002386f26fc10000, 0x016345785d8a0000, 0x0de0b6b3a7640000, 0x8ac7230489e80000, -] -function ndigits0z(x::Union{UInt8,UInt16,UInt32,UInt64}) - lz = (sizeof(x)<<3)-leading_zeros(x) - nd = (1233*lz)>>12+1 - nd -= x < powers_of_ten[nd] -end -function ndigits0z(x::UInt128) - n = 0 - while x > 0x8ac7230489e80000 - x = div(x,0x8ac7230489e80000) - n += 19 - end - return n + ndigits0z(UInt64(x)) -end -ndigits0z(x::Integer) = ndigits0z(unsigned(abs(x))) - -function ndigits0znb(n::Signed, b::Int) - d = 0 - while n != 0 - n = cld(n,b) - d += 1 - end - return d -end - -function ndigits0z(n::Unsigned, b::Int) - n == 0 && return 0 - b < 0 && return ndigits0znb(signed(n), b) - b == 2 && return sizeof(n)<<3 - leading_zeros(n) - b == 8 && return (sizeof(n)<<3 - leading_zeros(n) + 2) ÷ 3 - b == 16 && return sizeof(n)<<1 - leading_zeros(n)>>2 - b == 10 && return ndigits0z(n) - - d = 0 - while n > typemax(Int) - n = div(n,b) - d += 1 - end - n = div(n,b) - d += 1 - - m = 1 - while m <= n - m *= b - d += 1 - end - return d -end -ndigits0z(x::Integer, b::Integer) = ndigits0z(unsigned(abs(x)),Int(b)) - -ndigitsnb(x::Integer, b::Integer) = x==0 ? 1 : ndigits0znb(x, b) - -ndigits(x::Unsigned, b::Integer) = x==0 ? 1 : ndigits0z(x,Int(b)) -ndigits(x::Unsigned) = x==0 ? 1 : ndigits0z(x) - -# The suffix "0z" means that the output is 0 on input zero (cf. #16841) -""" - ndigits0z(n::Integer, b::Integer=10) - -Return 0 if `n == 0`, otherwise compute the number of digits in -integer `n` written in base `b` (i.e. equal to `ndigits(n, b)` -in this case). -The base `b` must not be in `[-1, 0, 1]`. - -# Examples -```jldoctest -julia> Base.ndigits0z(0, 16) -0 - -julia> Base.ndigits(0, 16) -1 - -julia> Base.ndigits0z(0) -0 - -julia> Base.ndigits0z(10, 2) -4 - -julia> Base.ndigits0z(10) -2 -``` - -See also [`ndigits`](@ref). -""" -ndigits0z - -""" - ndigits(n::Integer, b::Integer=10) - -Compute the number of digits in integer `n` written in base `b`. -The base `b` must not be in `[-1, 0, 1]`. - -# Examples -```jldoctest -julia> ndigits(12345) -5 - -julia> ndigits(1022, 16) -3 - -julia> base(16, 1022) -"3fe" -``` -""" -ndigits(x::Integer, b::Integer) = b >= 0 ? ndigits(unsigned(abs(x)),Int(b)) : ndigitsnb(x, b) -ndigits(x::Integer) = ndigits(unsigned(abs(x))) - -## integer to string functions ## - -string(x::Union{Int8,Int16,Int32,Int64,Int128}) = dec(x) - -function bin(x::Unsigned, pad::Int, neg::Bool) - i = neg + max(pad,sizeof(x)<<3-leading_zeros(x)) - a = StringVector(i) - while i > neg - a[i] = '0'+(x&0x1) - x >>= 1 - i -= 1 - end - if neg; a[1]='-'; end - String(a) -end - -function oct(x::Unsigned, pad::Int, neg::Bool) - i = neg + max(pad,div((sizeof(x)<<3)-leading_zeros(x)+2,3)) - a = StringVector(i) - while i > neg - a[i] = '0'+(x&0x7) - x >>= 3 - i -= 1 - end - if neg; a[1]='-'; end - String(a) -end - -function dec(x::Unsigned, pad::Int, neg::Bool) - i = neg + max(pad,ndigits0z(x)) - a = StringVector(i) - while i > neg - a[i] = '0'+rem(x,10) - x = oftype(x,div(x,10)) - i -= 1 - end - if neg; a[1]='-'; end - String(a) -end - -function hex(x::Unsigned, pad::Int, neg::Bool) - i = neg + max(pad,(sizeof(x)<<1)-(leading_zeros(x)>>2)) - a = StringVector(i) - while i > neg - d = x & 0xf - a[i] = '0'+d+39*(d>9) - x >>= 4 - i -= 1 - end - if neg; a[1]='-'; end - String(a) -end - -num2hex(n::Integer) = hex(n, sizeof(n)*2) - -const base36digits = ['0':'9';'a':'z'] -const base62digits = ['0':'9';'A':'Z';'a':'z'] - -function base(b::Int, x::Unsigned, pad::Int, neg::Bool) - 2 <= b <= 62 || throw(ArgumentError("base must be 2 ≤ base ≤ 62, got $b")) - digits = b <= 36 ? base36digits : base62digits - i = neg + max(pad,ndigits0z(x,b)) - a = StringVector(i) - while i > neg - a[i] = digits[1+rem(x,b)] - x = div(x,b) - i -= 1 - end - if neg; a[1]='-'; end - String(a) -end - -""" - base(base::Integer, n::Integer, pad::Integer=1) - -Convert an integer `n` to a string in the given `base`, -optionally specifying a number of digits to pad to. - -```jldoctest -julia> base(13,5,4) -"0005" - -julia> base(5,13,4) -"0023" -``` -""" -base(b::Integer, n::Integer, pad::Integer=1) = base(Int(b), unsigned(abs(n)), pad, n<0) - -for sym in (:bin, :oct, :dec, :hex) - @eval begin - ($sym)(x::Unsigned, p::Int) = ($sym)(x,p,false) - ($sym)(x::Unsigned) = ($sym)(x,1,false) - ($sym)(x::Char, p::Int) = ($sym)(unsigned(x),p,false) - ($sym)(x::Char) = ($sym)(unsigned(x),1,false) - ($sym)(x::Integer, p::Int) = ($sym)(unsigned(abs(x)),p,x<0) - ($sym)(x::Integer) = ($sym)(unsigned(abs(x)),1,x<0) - end -end - -""" - bin(n, pad::Int=1) - -Convert an integer to a binary string, optionally specifying a number of digits to pad to. - -```jldoctest -julia> bin(10,2) -"1010" - -julia> bin(10,8) -"00001010" -``` -""" -bin - -""" - hex(n, pad::Int=1) - -Convert an integer to a hexadecimal string, optionally specifying a number of -digits to pad to. - -```jldoctest -julia> hex(20) -"14" - -julia> hex(20, 3) -"014" -``` -""" -hex - -""" - oct(n, pad::Int=1) - -Convert an integer to an octal string, optionally specifying a number of digits -to pad to. - -```jldoctest -julia> oct(20) -"24" - -julia> oct(20, 3) -"024" -``` -""" -oct - -""" - dec(n, pad::Int=1) - -Convert an integer to a decimal string, optionally specifying a number of digits -to pad to. - -# Examples -```jldoctest -julia> dec(20) -"20" - -julia> dec(20, 3) -"020" -``` -""" -dec - -bits(x::Union{Bool,Int8,UInt8}) = bin(reinterpret(UInt8,x),8) -bits(x::Union{Int16,UInt16,Float16}) = bin(reinterpret(UInt16,x),16) -bits(x::Union{Char,Int32,UInt32,Float32}) = bin(reinterpret(UInt32,x),32) -bits(x::Union{Int64,UInt64,Float64}) = bin(reinterpret(UInt64,x),64) -bits(x::Union{Int128,UInt128}) = bin(reinterpret(UInt128,x),128) - -""" - digits([T<:Integer], n::Integer, base::T=10, pad::Integer=1) - -Returns an array with element type `T` (default `Int`) of the digits of `n` in the given -base, optionally padded with zeros to a specified size. More significant digits are at -higher indexes, such that `n == sum([digits[k]*base^(k-1) for k=1:length(digits)])`. - -# Examples -```jldoctest -julia> digits(10, 10) -2-element Array{Int64,1}: - 0 - 1 - -julia> digits(10, 2) -4-element Array{Int64,1}: - 0 - 1 - 0 - 1 - -julia> digits(10, 2, 6) -6-element Array{Int64,1}: - 0 - 1 - 0 - 1 - 0 - 0 -``` -""" -digits(n::Integer, base::T=10, pad::Integer=1) where {T<:Integer} = digits(T, n, base, pad) - -function digits(::Type{T}, n::Integer, base::Integer=10, pad::Integer=1) where T<:Integer - 2 <= base || throw(ArgumentError("base must be ≥ 2, got $base")) - digits!(zeros(T, max(pad, ndigits0z(n,base))), n, base) -end - -""" - digits!(array, n::Integer, base::Integer=10) - -Fills an array of the digits of `n` in the given base. More significant digits are at higher -indexes. If the array length is insufficient, the least significant digits are filled up to -the array length. If the array length is excessive, the excess portion is filled with zeros. - -# Examples -```jldoctest -julia> digits!([2,2,2,2], 10, 2) -4-element Array{Int64,1}: - 0 - 1 - 0 - 1 - -julia> digits!([2,2,2,2,2,2], 10, 2) -6-element Array{Int64,1}: - 0 - 1 - 0 - 1 - 0 - 0 -``` -""" -function digits!(a::AbstractArray{T,1}, n::Integer, base::Integer=10) where T<:Integer - 2 <= base || throw(ArgumentError("base must be ≥ 2, got $base")) - base - 1 <= typemax(T) || throw(ArgumentError("type $T too small for base $base")) - for i in eachindex(a) - a[i] = rem(n, base) - n = div(n, base) - end - return a -end - -""" - isqrt(n::Integer) - -Integer square root: the largest integer `m` such that `m*m <= n`. - -```jldoctest -julia> isqrt(5) -2 -``` -""" -isqrt(x::Integer) = oftype(x, trunc(sqrt(x))) - -function isqrt(x::Union{Int64,UInt64,Int128,UInt128}) - x==0 && return x - s = oftype(x, trunc(sqrt(x))) - # fix with a Newton iteration, since conversion to float discards - # too many bits. - s = (s + div(x,s)) >> 1 - s*s > x ? s-1 : s -end - -function factorial(n::Integer) - n < 0 && throw(DomainError()) - local f::typeof(n*n), i::typeof(n*n) - f = 1 - for i = 2:n - f *= i - end - return f -end - -""" - binomial(n, k) - -Number of ways to choose `k` out of `n` items. - -# Example -```jldoctest -julia> binomial(5, 3) -10 - -julia> factorial(5) ÷ (factorial(5-3) * factorial(3)) -10 -``` -""" -function binomial(n::T, k::T) where T<:Integer - k < 0 && return zero(T) - sgn = one(T) - if n < 0 - n = -n + k -1 - if isodd(k) - sgn = -sgn - end - end - k > n && return zero(T) - (k == 0 || k == n) && return sgn - k == 1 && return sgn*n - if k > (n>>1) - k = (n - k) - end - x::T = nn = n - k + 1 - nn += 1 - rr = 2 - while rr <= k - xt = div(widemul(x, nn), rr) - x = xt - x == xt || throw(OverflowError()) - rr += 1 - nn += 1 - end - convert(T, copysign(x, sgn)) -end diff --git a/julia-0.6.3/share/julia/base/intset.jl b/julia-0.6.3/share/julia/base/intset.jl deleted file mode 100644 index 956d124..0000000 --- a/julia-0.6.3/share/julia/base/intset.jl +++ /dev/null @@ -1,232 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -struct IntSet <: AbstractSet{Int} - bits::BitVector - IntSet() = new(falses(256)) -end -IntSet(itr) = union!(IntSet(), itr) - -eltype(::Type{IntSet}) = Int -similar(s::IntSet) = IntSet() -copy(s1::IntSet) = copy!(IntSet(), s1) -function copy!(dest::IntSet, src::IntSet) - resize!(dest.bits, length(src.bits)) - copy!(dest.bits, src.bits) - dest -end -eltype(s::IntSet) = Int -sizehint!(s::IntSet, n::Integer) = (_resize0!(s.bits, max(n, length(s.bits))); s) - -# An internal function for setting the inclusion bit for a given integer n >= 0 -@inline function _setint!(s::IntSet, idx::Integer, b::Bool) - if idx > length(s.bits) - b || return s # setting a bit to zero outside the set's bits is a no-op - newlen = Int(idx) + Int(idx)>>1 # This operation may overflow; we want saturation - _resize0!(s.bits, ifelse(newlen<0, typemax(Int), newlen)) - end - @inbounds s.bits[idx] = b - s -end - -# An internal function to resize a bitarray and ensure the newly allocated -# elements are zeroed (will become unnecessary if this behavior changes) -@inline function _resize0!(b::BitVector, newlen::Integer) - len = length(b) - resize!(b, newlen) - len < newlen && @inbounds b[len+1:newlen] = false # resize! gives dirty memory - b -end - -# An internal function that takes a pure function `f` and maps across two BitArrays -# allowing the lengths to be different and altering b1 with the result -function _matched_map!(f, b1::BitArray, b2::BitArray) - l1, l2 = length(b1), length(b2) - if l1 == l2 - map!(f, b1, b1, b2) - elseif l1 < l2 - _resize0!(b1, l2) - map!(f, b1, b1, b2) - elseif l1 > l2 - if f(false, false) == f(true, false) == false - # We don't need to worry about the trailing bits — they're all false - resize!(b1, l2) - map!(f, b1, b1, b2) - else - # We transiently extend b2 — as IntSet internal storage this is unobservable - _resize0!(b2, l1) - map!(f, b1, b1, b2) - resize!(b2, l2) - end - end - b1 -end - -@noinline _throw_intset_bounds_err() = throw(ArgumentError("elements of IntSet must be between 1 and typemax(Int)")) -@noinline _throw_keyerror(n) = throw(KeyError(n)) - -@inline function push!(s::IntSet, n::Integer) - 0 < n <= typemax(Int) || _throw_intset_bounds_err() - _setint!(s, n, true) -end -push!(s::IntSet, ns::Integer...) = (for n in ns; push!(s, n); end; s) - -@inline function pop!(s::IntSet) - pop!(s, last(s)) -end -@inline function pop!(s::IntSet, n::Integer) - n in s ? (_delete!(s, n); n) : _throw_keyerror(n) -end -@inline function pop!(s::IntSet, n::Integer, default) - n in s ? (_delete!(s, n); n) : default -end -@inline _delete!(s::IntSet, n::Integer) = _setint!(s, n, false) -@inline delete!(s::IntSet, n::Integer) = n < 0 ? s : _delete!(s, n) -shift!(s::IntSet) = pop!(s, first(s)) - -empty!(s::IntSet) = (fill!(s.bits, false); s) -isempty(s::IntSet) = !any(s.bits) - -# Mathematical set functions: union!, intersect!, setdiff!, symdiff! - -union(s::IntSet) = copy(s) -union(s1::IntSet, s2::IntSet) = union!(copy(s1), s2) -union(s1::IntSet, ss::IntSet...) = union(s1, union(ss...)) -union(s::IntSet, ns) = union!(copy(s), ns) -union!(s::IntSet, ns) = (for n in ns; push!(s, n); end; s) -function union!(s1::IntSet, s2::IntSet) - _matched_map!(|, s1.bits, s2.bits) - s1 -end - -intersect(s1::IntSet) = copy(s1) -intersect(s1::IntSet, ss::IntSet...) = intersect(s1, intersect(ss...)) -function intersect(s1::IntSet, ns) - s = IntSet() - for n in ns - n in s1 && push!(s, n) - end - s -end -intersect(s1::IntSet, s2::IntSet) = - (length(s1.bits) >= length(s2.bits) ? intersect!(copy(s1), s2) : intersect!(copy(s2), s1)) -""" - intersect!(s1::IntSet, s2::IntSet) - -Intersects sets `s1` and `s2` and overwrites the set `s1` with the result. If needed, `s1` -will be expanded to the size of `s2`. -""" -function intersect!(s1::IntSet, s2::IntSet) - _matched_map!(&, s1.bits, s2.bits) - s1 -end - -setdiff(s::IntSet, ns) = setdiff!(copy(s), ns) -setdiff!(s::IntSet, ns) = (for n in ns; _delete!(s, n); end; s) -function setdiff!(s1::IntSet, s2::IntSet) - _matched_map!(>, s1.bits, s2.bits) - s1 -end - -symdiff(s::IntSet, ns) = symdiff!(copy(s), ns) -""" - symdiff!(s, itr) - -For each element in `itr`, destructively toggle its inclusion in set `s`. -""" -symdiff!(s::IntSet, ns) = (for n in ns; symdiff!(s, n); end; s) -""" - symdiff!(s, n) - -The set `s` is destructively modified to toggle the inclusion of integer `n`. -""" -function symdiff!(s::IntSet, n::Integer) - 0 < n < typemax(Int) || _throw_intset_bounds_err() - val = !(n in s) - _setint!(s, n, val) - s -end -function symdiff!(s1::IntSet, s2::IntSet) - _matched_map!(xor, s1.bits, s2.bits) - s1 -end - -@inline function in(n::Integer, s::IntSet) - if 1 <= n <= length(s.bits) - @inbounds b = s.bits[n] - else - b = false - end - b -end - -# Use the next-set index as the state to prevent looking it up again in done -start(s::IntSet) = next(s, 0)[2] -function next(s::IntSet, i) - nextidx = i == typemax(Int) ? 0 : findnext(s.bits, i+1) - (i, nextidx) -end -done(s::IntSet, i) = i <= 0 - - -@noinline _throw_intset_notempty_error() = throw(ArgumentError("collection must be non-empty")) -function last(s::IntSet) - idx = findprev(s.bits, length(s.bits)) - idx == 0 ? _throw_intset_notempty_error() : idx -end - -length(s::IntSet) = sum(s.bits) - -function show(io::IO, s::IntSet) - print(io, "IntSet([") - first = true - for n in s - !first && print(io, ", ") - print(io, n) - first = false - end - print(io, "])") -end - -function ==(s1::IntSet, s2::IntSet) - l1 = length(s1.bits) - l2 = length(s2.bits) - # If the lengths are the same, simply punt to bitarray comparison - l1 == l2 && return s1.bits == s2.bits - - # Swap so s1 is always longer - if l1 < l2 - s2, s1 = s1, s2 - l2, l1 = l1, l2 - end - # Iteratively check the chunks of the bitarrays - c1 = s1.bits.chunks - c2 = s2.bits.chunks - @inbounds for i in 1:length(c2) - c1[i] == c2[i] || return false - end - # Ensure remaining chunks are zero - @inbounds for i in length(c2)+1:length(c1) - c1[i] == UInt64(0) || return false - end - return true -end - -issubset(a::IntSet, b::IntSet) = isequal(a, intersect(a,b)) -<(a::IntSet, b::IntSet) = (a<=b) && !isequal(a,b) -<=(a::IntSet, b::IntSet) = issubset(a, b) - -const hashis_seed = UInt === UInt64 ? 0x88989f1fc7dea67d : 0xc7dea67d -function hash(s::IntSet, h::UInt) - h ⊻= hashis_seed - bc = s.bits.chunks - i = length(bc) - while i > 0 && bc[i] == UInt64(0) - # Skip trailing empty bytes to prevent extra space from changing the hash - i -= 1 - end - while i > 0 - h = hash(bc[i], h) - i -= 1 - end - h -end diff --git a/julia-0.6.3/share/julia/base/io.jl b/julia-0.6.3/share/julia/base/io.jl deleted file mode 100644 index be201e7..0000000 --- a/julia-0.6.3/share/julia/base/io.jl +++ /dev/null @@ -1,646 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -# Generic IO stubs -- all subtypes should implement these (if meaningful) - -lock(::IO) = nothing -unlock(::IO) = nothing -reseteof(x::IO) = nothing - -const SZ_UNBUFFERED_IO = 65536 -buffer_writes(x::IO, bufsize=SZ_UNBUFFERED_IO) = x - -""" - isopen(object) -> Bool - -Determine whether an object - such as a stream, timer, or mmap -- is not yet closed. Once an -object is closed, it will never produce a new event. However, a closed stream may still have -data to read in its buffer, use [`eof`](@ref) to check for the ability to read data. -Use [`poll_fd`](@ref) to be notified when a stream might be writable or readable. -""" -function isopen end - -""" - close(stream) - -Close an I/O stream. Performs a [`flush`](@ref) first. -""" -function close end -function flush end -function wait_connected end -function wait_readnb end -function wait_readbyte end -function wait_close end -function nb_available end -function readavailable end - -""" - isreadable(io) -> Bool - -Returns `true` if the specified IO object is readable (if that can be determined). -""" -function isreadable end - -""" - iswritable(io) -> Bool - -Returns `true` if the specified IO object is writable (if that can be determined). -""" -function iswritable end -function copy end -function eof end - -""" - write(stream::IO, x) - write(filename::AbstractString, x) - -Write the canonical binary representation of a value to the given I/O stream or file. -Returns the number of bytes written into the stream. - -You can write multiple values with the same `write` call. i.e. the following are equivalent: - - write(stream, x, y...) - write(stream, x) + write(stream, y...) -""" -function write end - -read(s::IO, ::Type{UInt8}) = error(typeof(s)," does not support byte I/O") -write(s::IO, x::UInt8) = error(typeof(s)," does not support byte I/O") - -""" - unsafe_write(io::IO, ref, nbytes::UInt) - -Copy `nbytes` from `ref` (converted to a pointer) into the `IO` object. - -It is recommended that subtypes `T<:IO` override the following method signature -to provide more efficient implementations: -`unsafe_write(s::T, p::Ptr{UInt8}, n::UInt)` -""" -function unsafe_write(s::IO, p::Ptr{UInt8}, n::UInt) - local written::Int = 0 - for i = 1:n - written += write(s, unsafe_load(p, i)) - end - return written -end - -""" - unsafe_read(io::IO, ref, nbytes::UInt) - -Copy `nbytes` from the `IO` stream object into `ref` (converted to a pointer). - -It is recommended that subtypes `T<:IO` override the following method signature -to provide more efficient implementations: -`unsafe_read(s::T, p::Ptr{UInt8}, n::UInt)` -""" -function unsafe_read(s::IO, p::Ptr{UInt8}, n::UInt) - for i = 1:n - unsafe_store!(p, read(s, UInt8)::UInt8, i) - end - nothing -end - - -# Generic wrappers around other IO objects -abstract type AbstractPipe <: IO end -function pipe_reader end -function pipe_writer end - -write(io::AbstractPipe, byte::UInt8) = write(pipe_writer(io), byte) -unsafe_write(io::AbstractPipe, p::Ptr{UInt8}, nb::UInt) = unsafe_write(pipe_writer(io), p, nb) -buffer_writes(io::AbstractPipe, args...) = buffer_writes(pipe_writer(io), args...) -flush(io::AbstractPipe) = flush(pipe_writer(io)) - -read(io::AbstractPipe, byte::Type{UInt8}) = read(pipe_reader(io), byte) -unsafe_read(io::AbstractPipe, p::Ptr{UInt8}, nb::UInt) = unsafe_read(pipe_reader(io), p, nb) -read(io::AbstractPipe) = read(pipe_reader(io)) -readuntil(io::AbstractPipe, arg::UInt8) = readuntil(pipe_reader(io), arg) -readuntil(io::AbstractPipe, arg::Char) = readuntil(pipe_reader(io), arg) -readuntil(io::AbstractPipe, arg::AbstractString) = readuntil(pipe_reader(io), arg) -readuntil(io::AbstractPipe, arg) = readuntil(pipe_reader(io), arg) -readavailable(io::AbstractPipe) = readavailable(pipe_reader(io)) - -isreadable(io::AbstractPipe) = isreadable(pipe_reader(io)) -iswritable(io::AbstractPipe) = iswritable(pipe_writer(io)) -isopen(io::AbstractPipe) = isopen(pipe_writer(io)) || isopen(pipe_reader(io)) -close(io::AbstractPipe) = (close(pipe_writer(io)); close(pipe_reader(io))) -wait_readnb(io::AbstractPipe, nb::Int) = wait_readnb(pipe_reader(io), nb) -wait_readbyte(io::AbstractPipe, byte::UInt8) = wait_readbyte(pipe_reader(io), byte) -wait_close(io::AbstractPipe) = (wait_close(pipe_writer(io)); wait_close(pipe_reader(io))) - -""" - nb_available(stream) - -Returns the number of bytes available for reading before a read from this stream or buffer will block. -""" -nb_available(io::AbstractPipe) = nb_available(pipe_reader(io)) - -""" - eof(stream) -> Bool - -Tests whether an I/O stream is at end-of-file. If the stream is not yet exhausted, this -function will block to wait for more data if necessary, and then return `false`. Therefore -it is always safe to read one byte after seeing `eof` return `false`. `eof` will return -`false` as long as buffered data is still available, even if the remote end of a connection -is closed. -""" -eof(io::AbstractPipe) = eof(pipe_reader(io)) -reseteof(io::AbstractPipe) = reseteof(pipe_reader(io)) - - -# Exception-safe wrappers (io = open(); try f(io) finally close(io)) - -write(filename::AbstractString, args...) = open(io->write(io, args...), filename, "w") - -""" - read(filename::AbstractString, args...) - -Open a file and read its contents. `args` is passed to `read`: this is equivalent to -`open(io->read(io, args...), filename)`. -""" -read(filename::AbstractString, args...) = open(io->read(io, args...), filename) -read!(filename::AbstractString, a) = open(io->read!(io, a), filename) - -""" - readuntil(stream::IO, delim) - readuntil(filename::AbstractString, delim) - -Read a string from an I/O stream or a file, up to and including the given delimiter byte. -The text is assumed to be encoded in UTF-8. -""" -readuntil(filename::AbstractString, args...) = open(io->readuntil(io, args...), filename) - -""" - readline(stream::IO=STDIN; chomp::Bool=true) - readline(filename::AbstractString; chomp::Bool=true) - -Read a single line of text from the given I/O stream or file (defaults to `STDIN`). -When reading from a file, the text is assumed to be encoded in UTF-8. Lines in the -input end with `'\\n'` or `"\\r\\n"` or the end of an input stream. When `chomp` is -true (as it is by default), these trailing newline characters are removed from the -line before it is returned. When `chomp` is false, they are returned as part of the -line. -""" -function readline(filename::AbstractString; chomp::Bool=true) - open(filename) do f - readline(f, chomp=chomp) - end -end - -function readline(s::IO=STDIN; chomp::Bool=true) - line = readuntil(s, 0x0a) - i = length(line) - if !chomp || i == 0 || line[i] != 0x0a - return String(line) - elseif i < 2 || line[i-1] != 0x0d - return String(resize!(line,i-1)) - else - return String(resize!(line,i-2)) - end -end - -""" - readlines(stream::IO=STDIN; chomp::Bool=true) - readlines(filename::AbstractString; chomp::Bool=true) - -Read all lines of an I/O stream or a file as a vector of strings. Behavior is -equivalent to saving the result of reading `readline` repeatedly with the same -arguments and saving the resulting lines as a vector of strings. -""" -function readlines(filename::AbstractString; chomp::Bool=true) - open(filename) do f - readlines(f, chomp=chomp) - end -end -readlines(s=STDIN; chomp::Bool=true) = collect(eachline(s, chomp=chomp)) - -## byte-order mark, ntoh & hton ## - -let endian_boms = reinterpret(UInt8, UInt32[0x01020304]) - global ntoh, hton, ltoh, htol - if endian_boms == UInt8[1:4;] - ntoh(x) = x - hton(x) = x - ltoh(x) = bswap(x) - htol(x) = bswap(x) - const global ENDIAN_BOM = 0x01020304 - elseif endian_boms == UInt8[4:-1:1;] - ntoh(x) = bswap(x) - hton(x) = bswap(x) - ltoh(x) = x - htol(x) = x - const global ENDIAN_BOM = 0x04030201 - else - error("seriously? what is this machine?") - end -end - -""" - ENDIAN_BOM - -The 32-bit byte-order-mark indicates the native byte order of the host machine. -Little-endian machines will contain the value `0x04030201`. Big-endian machines will contain -the value `0x01020304`. -""" -ENDIAN_BOM - -""" - ntoh(x) - -Converts the endianness of a value from Network byte order (big-endian) to that used by the Host. -""" -ntoh(x) - -""" - hton(x) - -Converts the endianness of a value from that used by the Host to Network byte order (big-endian). -""" -hton(x) - -""" - ltoh(x) - -Converts the endianness of a value from Little-endian to that used by the Host. -""" -ltoh(x) - -""" - htol(x) - -Converts the endianness of a value from that used by the Host to Little-endian. -""" -htol(x) - - -""" - isreadonly(stream) -> Bool - -Determine whether a stream is read-only. -""" -isreadonly(s) = isreadable(s) && !iswritable(s) - -## binary I/O ## - -write(io::IO, x) = throw(MethodError(write, (io, x))) -function write(io::IO, xs...) - local written::Int = 0 - for x in xs - written += write(io, x) - end - return written -end - -@noinline unsafe_write{T}(s::IO, p::Ref{T}, n::Integer) = unsafe_write(s, unsafe_convert(Ref{T}, p)::Ptr, n) # mark noinline to ensure ref is gc-rooted somewhere (by the caller) -unsafe_write(s::IO, p::Ptr, n::Integer) = unsafe_write(s, convert(Ptr{UInt8}, p), convert(UInt, n)) -write{T}(s::IO, x::Ref{T}) = unsafe_write(s, x, Core.sizeof(T)) -write(s::IO, x::Int8) = write(s, reinterpret(UInt8, x)) -function write(s::IO, x::Union{Int16,UInt16,Int32,UInt32,Int64,UInt64,Int128,UInt128,Float16,Float32,Float64}) - return write(s, Ref(x)) -end - -write(s::IO, x::Bool) = write(s, UInt8(x)) -write(to::IO, p::Ptr) = write(to, convert(UInt, p)) - -function write(s::IO, A::AbstractArray) - nb = 0 - for a in A - nb += write(s, a) - end - return nb -end - -@noinline function write(s::IO, a::Array{UInt8}) # mark noinline to ensure the array is gc-rooted somewhere (by the caller) - return unsafe_write(s, pointer(a), sizeof(a)) -end - -@noinline function write{T}(s::IO, a::Array{T}) # mark noinline to ensure the array is gc-rooted somewhere (by the caller) - if isbits(T) - return unsafe_write(s, pointer(a), sizeof(a)) - else - nb = 0 - for b in a - nb += write(s, b) - end - return nb - end -end - - -function write(s::IO, ch::Char) - c = reinterpret(UInt32, ch) - if c < 0x80 - return write(s, c%UInt8) - elseif c < 0x800 - return (write(s, (( c >> 6 ) | 0xC0)%UInt8)) + - (write(s, (( c & 0x3F ) | 0x80)%UInt8)) - elseif c < 0x10000 - return (write(s, (( c >> 12 ) | 0xE0)%UInt8)) + - (write(s, (((c >> 6) & 0x3F ) | 0x80)%UInt8)) + - (write(s, (( c & 0x3F ) | 0x80)%UInt8)) - elseif c < 0x110000 - return (write(s, (( c >> 18 ) | 0xF0)%UInt8)) + - (write(s, (((c >> 12) & 0x3F ) | 0x80)%UInt8)) + - (write(s, (((c >> 6) & 0x3F ) | 0x80)%UInt8)) + - (write(s, (( c & 0x3F ) | 0x80)%UInt8)) - else - return write(s, '\ufffd') - end -end - -function write(io::IO, s::Symbol) - pname = unsafe_convert(Ptr{UInt8}, s) - return unsafe_write(io, pname, Int(ccall(:strlen, Csize_t, (Cstring,), pname))) -end - -function write(to::IO, from::IO) - while !eof(from) - write(to, readavailable(from)) - end -end - -@noinline unsafe_read(s::IO, p::Ref{T}, n::Integer) where {T} = unsafe_read(s, unsafe_convert(Ref{T}, p)::Ptr, n) # mark noinline to ensure ref is gc-rooted somewhere (by the caller) -unsafe_read(s::IO, p::Ptr, n::Integer) = unsafe_read(s, convert(Ptr{UInt8}, p), convert(UInt, n)) -read(s::IO, x::Ref{T}) where {T} = (unsafe_read(s, x, Core.sizeof(T)); x) - -read(s::IO, ::Type{Int8}) = reinterpret(Int8, read(s, UInt8)) -function read(s::IO, T::Union{Type{Int16},Type{UInt16},Type{Int32},Type{UInt32},Type{Int64},Type{UInt64},Type{Int128},Type{UInt128},Type{Float16},Type{Float32},Type{Float64}}) - return read(s, Ref{T}(0))[]::T -end - -read(s::IO, ::Type{Bool}) = (read(s, UInt8) != 0) -read(s::IO, ::Type{Ptr{T}}) where {T} = convert(Ptr{T}, read(s, UInt)) - -read(s::IO, t::Type{T}, d1::Int, dims::Int...) where {T} = read(s, t, tuple(d1,dims...)) -read(s::IO, t::Type{T}, d1::Integer, dims::Integer...) where {T} = - read(s, t, convert(Tuple{Vararg{Int}},tuple(d1,dims...))) - -""" - read(stream::IO, T, dims) - -Read a series of values of type `T` from `stream`, in canonical binary representation. -`dims` is either a tuple or a series of integer arguments specifying the size of the `Array{T}` -to return. -""" -read(s::IO, ::Type{T}, dims::Dims) where {T} = read!(s, Array{T}(dims)) - -@noinline function read!(s::IO, a::Array{UInt8}) # mark noinline to ensure the array is gc-rooted somewhere (by the caller) - unsafe_read(s, pointer(a), sizeof(a)) - return a -end - -@noinline function read!(s::IO, a::Array{T}) where T # mark noinline to ensure the array is gc-rooted somewhere (by the caller) - if isbits(T) - unsafe_read(s, pointer(a), sizeof(a)) - else - for i in eachindex(a) - a[i] = read(s, T) - end - end - return a -end - -function read(s::IO, ::Type{Char}) - ch = read(s, UInt8) - if ch < 0x80 - return Char(ch) - end - - # mimic utf8.next function - trailing = Base.utf8_trailing[ch+1] - c::UInt32 = 0 - for j = 1:trailing - c += ch - c <<= 6 - ch = read(s, UInt8) - end - c += ch - c -= Base.utf8_offset[trailing+1] - return Char(c) -end - -# readuntil_string is useful below since it has -# an optimized method for s::IOStream -readuntil_string(s::IO, delim::UInt8) = String(readuntil(s, delim)) - -function readuntil(s::IO, delim::Char) - if delim < Char(0x80) - return readuntil_string(s, delim % UInt8) - end - out = IOBuffer() - while !eof(s) - c = read(s, Char) - write(out, c) - if c == delim - break - end - end - return String(take!(out)) -end - -function readuntil{T}(s::IO, delim::T) - out = T[] - while !eof(s) - c = read(s, T) - push!(out, c) - if c == delim - break - end - end - return out -end - -# based on code by Glen Hertz -function readuntil(s::IO, t::AbstractString) - l = length(t) - if l == 0 - return "" - end - if l > 40 - warn("readuntil(IO,AbstractString) will perform poorly with a long string") - end - out = IOBuffer() - m = Vector{Char}(l) # last part of stream to match - t = collect(t) - i = 0 - while !eof(s) - i += 1 - c = read(s, Char) - write(out, c) - if i <= l - m[i] = c - else - # shift to last part of s - for j = 2:l - m[j-1] = m[j] - end - m[l] = c - end - if i >= l && m == t - break - end - end - return String(take!(out)) -end - -""" - readchomp(x) - -Read the entirety of `x` as a string and remove a single trailing newline. -Equivalent to `chomp!(readstring(x))`. -""" -readchomp(x) = chomp!(readstring(x)) - -# read up to nb bytes into nb, returning # bytes read - -""" - readbytes!(stream::IO, b::AbstractVector{UInt8}, nb=length(b)) - -Read at most `nb` bytes from `stream` into `b`, returning the number of bytes read. -The size of `b` will be increased if needed (i.e. if `nb` is greater than `length(b)` -and enough bytes could be read), but it will never be decreased. -""" -function readbytes!(s::IO, b::AbstractArray{UInt8}, nb=length(b)) - olb = lb = length(b) - nr = 0 - while nr < nb && !eof(s) - a = read(s, UInt8) - nr += 1 - if nr > lb - lb = nr * 2 - resize!(b, lb) - end - b[nr] = a - end - if lb > olb - resize!(b, nr) # shrink to just contain input data if was resized - end - return nr -end - -""" - read(s::IO, nb=typemax(Int)) - -Read at most `nb` bytes from `s`, returning a `Vector{UInt8}` of the bytes read. -""" -function read(s::IO, nb=typemax(Int)) - # Let readbytes! grow the array progressively by default - # instead of taking of risk of over-allocating - b = Vector{UInt8}(nb == typemax(Int) ? 1024 : nb) - nr = readbytes!(s, b, nb) - return resize!(b, nr) -end - -""" - readstring(stream::IO) - readstring(filename::AbstractString) - -Read the entire contents of an I/O stream or a file as a string. -The text is assumed to be encoded in UTF-8. -""" -readstring(s::IO) = String(read(s)) -readstring(filename::AbstractString) = open(readstring, filename) - -## high-level iterator interfaces ## - -mutable struct EachLine - stream::IO - ondone::Function - chomp::Bool - - EachLine(stream::IO=STDIN; ondone::Function=()->nothing, chomp::Bool=true) = - new(stream, ondone, chomp) -end - -""" - eachline(stream::IO=STDIN; chomp::Bool=true) - eachline(filename::AbstractString; chomp::Bool=true) - -Create an iterable `EachLine` object that will yield each line from an I/O stream -or a file. Iteration calls `readline` on the stream argument repeatedly with -`chomp` passed through, determining whether trailing end-of-line characters are -removed. When called with a file name, the file is opened once at the beginning of -iteration and closed at the end. If iteration is interrupted, the file will be -closed when the `EachLine` object is garbage collected. -""" -eachline(stream::IO=STDIN; chomp::Bool=true) = EachLine(stream, chomp=chomp)::EachLine - -function eachline(filename::AbstractString; chomp::Bool=true) - s = open(filename) - EachLine(s, ondone=()->close(s), chomp=chomp)::EachLine -end - -start(itr::EachLine) = nothing -function done(itr::EachLine, ::Void) - eof(itr.stream) || return false - itr.ondone() - true -end -next(itr::EachLine, ::Void) = (readline(itr.stream, chomp=itr.chomp), nothing) - -eltype(::Type{EachLine}) = String - -iteratorsize(::Type{EachLine}) = SizeUnknown() - -# IOStream Marking -# Note that these functions expect that io.mark exists for -# the concrete IO type. This may not be true for IO types -# not in base. - -""" - mark(s) - -Add a mark at the current position of stream `s`. Returns the marked position. - -See also [`unmark`](@ref), [`reset`](@ref), [`ismarked`](@ref). -""" -function mark(io::IO) - io.mark = position(io) -end - -""" - unmark(s) - -Remove a mark from stream `s`. Returns `true` if the stream was marked, `false` otherwise. - -See also [`mark`](@ref), [`reset`](@ref), [`ismarked`](@ref). -""" -function unmark(io::IO) - !ismarked(io) && return false - io.mark = -1 - return true -end - -""" - reset(s) - -Reset a stream `s` to a previously marked position, and remove the mark. Returns the -previously marked position. Throws an error if the stream is not marked. - -See also [`mark`](@ref), [`unmark`](@ref), [`ismarked`](@ref). -""" -function reset(io::T) where T<:IO - ismarked(io) || throw(ArgumentError("$(T) not marked")) - m = io.mark - seek(io, m) - io.mark = -1 # must be after seek, or seek may fail - return m -end - -""" - ismarked(s) - -Returns `true` if stream `s` is marked. - -See also [`mark`](@ref), [`unmark`](@ref), [`reset`](@ref). -""" -ismarked(io::IO) = io.mark >= 0 - -# Make sure all IO streams support flush, even if only as a no-op, -# to make it easier to write generic I/O code. - -""" - flush(stream) - -Commit all currently buffered writes to the given stream. -""" -flush(io::IO) = nothing diff --git a/julia-0.6.3/share/julia/base/iobuffer.jl b/julia-0.6.3/share/julia/base/iobuffer.jl deleted file mode 100644 index 6441461..0000000 --- a/julia-0.6.3/share/julia/base/iobuffer.jl +++ /dev/null @@ -1,414 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -## work with AbstractVector{UInt8} via I/O primitives ## - -# Stateful string -mutable struct AbstractIOBuffer{T<:AbstractVector{UInt8}} <: IO - data::T # T should support: getindex, setindex!, length, copy!, and resize! - readable::Bool - writable::Bool - seekable::Bool # if not seekable, implementation is free to destroy (compact) past read data - append::Bool # add data at end instead of at pointer - size::Int # end pointer (and write pointer if append == true) - maxsize::Int # fixed array size (typically pre-allocated) - ptr::Int # read (and maybe write) pointer - mark::Int # reset mark location for ptr (or <0 for no mark) - - function AbstractIOBuffer{T}(data::T, readable::Bool, writable::Bool, seekable::Bool, append::Bool, - maxsize::Int) where T<:AbstractVector{UInt8} - new(data,readable,writable,seekable,append,length(data),maxsize,1,-1) - end -end -const IOBuffer = AbstractIOBuffer{Vector{UInt8}} - -function AbstractIOBuffer(data::T, readable::Bool, writable::Bool, seekable::Bool, append::Bool, - maxsize::Int) where T<:AbstractVector{UInt8} - AbstractIOBuffer{T}(data, readable, writable, seekable, append, maxsize) -end - -# allocate Vector{UInt8}s for IOBuffer storage that can efficiently become Strings -StringVector(n::Integer) = Vector{UInt8}(_string_n(n)) - -# IOBuffers behave like Files. They are typically readable and writable. They are seekable. (They can be appendable). - -""" - IOBuffer([data,],[readable::Bool=true, writable::Bool=true, [maxsize::Int=typemax(Int)]]) - -Create an `IOBuffer`, which may optionally operate on a pre-existing array. If the -readable/writable arguments are given, they restrict whether or not the buffer may be read -from or written to respectively. The last argument optionally specifies a size beyond which -the buffer may not be grown. -""" -IOBuffer(data::AbstractVector{UInt8}, readable::Bool=true, writable::Bool=false, maxsize::Int=typemax(Int)) = - AbstractIOBuffer(data, readable, writable, true, false, maxsize) -function IOBuffer(readable::Bool, writable::Bool) - b = IOBuffer(StringVector(32), readable, writable) - b.data[:] = 0 - b.size = 0 - return b -end - -""" - IOBuffer() -> IOBuffer - -Create an in-memory I/O stream. -""" -IOBuffer() = IOBuffer(true, true) - -""" - IOBuffer(size::Int) - -Create a fixed size IOBuffer. The buffer will not grow dynamically. -""" -IOBuffer(maxsize::Int) = (x=IOBuffer(StringVector(maxsize), true, true, maxsize); x.size=0; x) - -# PipeBuffers behave like Unix Pipes. They are typically readable and writable, they act appendable, and are not seekable. - -""" - PipeBuffer(data::Vector{UInt8}=UInt8[],[maxsize::Int=typemax(Int)]) - -An [`IOBuffer`](@ref) that allows reading and performs writes by appending. -Seeking and truncating are not supported. -See [`IOBuffer`](@ref) for the available constructors. -If `data` is given, creates a `PipeBuffer` to operate on a data vector, -optionally specifying a size beyond which the underlying `Array` may not be grown. -""" -PipeBuffer(data::Vector{UInt8}=UInt8[], maxsize::Int=typemax(Int)) = - AbstractIOBuffer(data,true,true,false,true,maxsize) -PipeBuffer(maxsize::Int) = (x = PipeBuffer(StringVector(maxsize),maxsize); x.size=0; x) - -function copy(b::AbstractIOBuffer) - ret = typeof(b)(b.writable ? copy(b.data) : b.data, - b.readable, b.writable, b.seekable, b.append, b.maxsize) - ret.size = b.size - ret.ptr = b.ptr - return ret -end - -show(io::IO, b::AbstractIOBuffer) = print(io, "IOBuffer(data=UInt8[...], ", - "readable=", b.readable, ", ", - "writable=", b.writable, ", ", - "seekable=", b.seekable, ", ", - "append=", b.append, ", ", - "size=", b.size, ", ", - "maxsize=", b.maxsize == typemax(Int) ? "Inf" : b.maxsize, ", ", - "ptr=", b.ptr, ", ", - "mark=", b.mark, ")") - -function unsafe_read(from::AbstractIOBuffer, p::Ptr{UInt8}, nb::UInt) - from.readable || throw(ArgumentError("read failed, IOBuffer is not readable")) - avail = nb_available(from) - adv = min(avail, nb) - unsafe_copy!(p, pointer(from.data, from.ptr), adv) - from.ptr += adv - if nb > avail - throw(EOFError()) - end - nothing -end - -function read_sub(from::AbstractIOBuffer, a::AbstractArray{T}, offs, nel) where T - from.readable || throw(ArgumentError("read failed, IOBuffer is not readable")) - if offs+nel-1 > length(a) || offs < 1 || nel < 0 - throw(BoundsError()) - end - if isbits(T) && isa(a,Array) - nb = UInt(nel * sizeof(T)) - unsafe_read(from, pointer(a, offs), nb) - else - for i = offs:offs+nel-1 - a[i] = read(to, T) - end - end - return a -end - -@inline function read(from::AbstractIOBuffer, ::Type{UInt8}) - from.readable || throw(ArgumentError("read failed, IOBuffer is not readable")) - ptr = from.ptr - size = from.size - if ptr > size - throw(EOFError()) - end - @inbounds byte = from.data[ptr] - from.ptr = ptr + 1 - return byte -end - -function peek(from::AbstractIOBuffer) - from.readable || throw(ArgumentError("read failed, IOBuffer is not readable")) - if from.ptr > from.size - throw(EOFError()) - end - return from.data[from.ptr] -end - -read(from::AbstractIOBuffer, ::Type{Ptr{T}}) where {T} = convert(Ptr{T}, read(from, UInt)) - -isreadable(io::AbstractIOBuffer) = io.readable -iswritable(io::AbstractIOBuffer) = io.writable - -# TODO: AbstractIOBuffer is not iterable, so doesn't really have a length. -# This should maybe be sizeof() instead. -#length(io::AbstractIOBuffer) = (io.seekable ? io.size : nb_available(io)) -nb_available(io::AbstractIOBuffer) = io.size - io.ptr + 1 -position(io::AbstractIOBuffer) = io.ptr-1 - -function skip(io::AbstractIOBuffer, n::Integer) - seekto = io.ptr + n - n < 0 && return seek(io, seekto-1) # Does error checking - io.ptr = min(seekto, io.size+1) - return io -end - -function seek(io::AbstractIOBuffer, n::Integer) - if !io.seekable - ismarked(io) || throw(ArgumentError("seek failed, IOBuffer is not seekable and is not marked")) - n == io.mark || throw(ArgumentError("seek failed, IOBuffer is not seekable and n != mark")) - end - # TODO: REPL.jl relies on the fact that this does not throw (by seeking past the beginning or end - # of an AbstractIOBuffer), so that would need to be fixed in order to throw an error here - #(n < 0 || n > io.size) && throw(ArgumentError("Attempted to seek outside IOBuffer boundaries.")) - #io.ptr = n+1 - io.ptr = max(min(n+1, io.size+1), 1) - return io -end - -function seekend(io::AbstractIOBuffer) - io.ptr = io.size+1 - return io -end - -function truncate(io::AbstractIOBuffer, n::Integer) - io.writable || throw(ArgumentError("truncate failed, IOBuffer is not writeable")) - io.seekable || throw(ArgumentError("truncate failed, IOBuffer is not seekable")) - n < 0 && throw(ArgumentError("truncate failed, n bytes must be ≥ 0, got $n")) - n > io.maxsize && throw(ArgumentError("truncate failed, $(n) bytes is exceeds IOBuffer maxsize $(io.maxsize)")) - if n > length(io.data) - resize!(io.data, n) - end - io.data[io.size+1:n] = 0 - io.size = n - io.ptr = min(io.ptr, n+1) - ismarked(io) && io.mark > n && unmark(io) - return io -end - -function compact(io::AbstractIOBuffer) - io.writable || throw(ArgumentError("compact failed, IOBuffer is not writeable")) - io.seekable && throw(ArgumentError("compact failed, IOBuffer is seekable")) - local ptr::Int, bytes_to_move::Int - if ismarked(io) && io.mark < io.ptr - if io.mark == 0 return end - ptr = io.mark - bytes_to_move = nb_available(io) + (io.ptr-io.mark) - else - ptr = io.ptr - bytes_to_move = nb_available(io) - end - copy!(io.data, 1, io.data, ptr, bytes_to_move) - io.size -= ptr - 1 - io.ptr -= ptr - 1 - io.mark -= ptr - 1 - return io -end - -@inline ensureroom(io::AbstractIOBuffer, nshort::Int) = ensureroom(io, UInt(nshort)) -@inline function ensureroom(io::AbstractIOBuffer, nshort::UInt) - io.writable || throw(ArgumentError("ensureroom failed, IOBuffer is not writeable")) - if !io.seekable - nshort >= 0 || throw(ArgumentError("ensureroom failed, requested number of bytes must be ≥ 0, got $nshort")) - if !ismarked(io) && io.ptr > 1 && io.size <= io.ptr - 1 - io.ptr = 1 - io.size = 0 - else - datastart = ismarked(io) ? io.mark : io.ptr - if (io.size+nshort > io.maxsize) || - (datastart > 4096 && datastart > io.size - io.ptr) || - (datastart > 262144) - # apply somewhat arbitrary heuristics to decide when to destroy - # old, read data to make more room for new data - compact(io) - end - end - end - n = min(nshort + (io.append ? io.size : io.ptr-1), io.maxsize) - if n > length(io.data) - resize!(io.data, n) - end - return io -end - -eof(io::AbstractIOBuffer) = (io.ptr-1 == io.size) - -@noinline function close(io::AbstractIOBuffer{T}) where T - io.readable = false - io.writable = false - io.seekable = false - io.size = 0 - io.maxsize = 0 - io.ptr = 1 - io.mark = -1 - if io.writable - resize!(io.data, 0) - end - nothing -end - -isopen(io::AbstractIOBuffer) = io.readable || io.writable || io.seekable || nb_available(io) > 0 - -function String(io::AbstractIOBuffer) - io.readable || throw(ArgumentError("IOBuffer is not readable")) - io.seekable || throw(ArgumentError("IOBuffer is not seekable")) - return unsafe_string(pointer(io.data), io.size) -end - -""" - take!(b::IOBuffer) - -Obtain the contents of an `IOBuffer` as an array, without copying. Afterwards, the -`IOBuffer` is reset to its initial state. -""" -function take!(io::AbstractIOBuffer) - ismarked(io) && unmark(io) - if io.seekable - nbytes = io.size - data = copy!(StringVector(nbytes), 1, io.data, 1, nbytes) - else - nbytes = nb_available(io) - data = read!(io,StringVector(nbytes)) - end - if io.writable - io.ptr = 1 - io.size = 0 - end - return data -end -function take!(io::IOBuffer) - ismarked(io) && unmark(io) - if io.seekable - data = io.data - if io.writable - maxsize = (io.maxsize == typemax(Int) ? 0 : min(length(io.data),io.maxsize)) - io.data = StringVector(maxsize) - else - data = copy(data) - end - resize!(data,io.size) - else - nbytes = nb_available(io) - a = StringVector(nbytes) - data = read!(io, a) - end - if io.writable - io.ptr = 1 - io.size = 0 - end - return data -end - -function write(to::AbstractIOBuffer, from::AbstractIOBuffer) - if to === from - from.ptr = from.size + 1 - return 0 - end - written::Int = write_sub(to, from.data, from.ptr, nb_available(from)) - from.ptr += written - return written -end - -function unsafe_write(to::AbstractIOBuffer, p::Ptr{UInt8}, nb::UInt) - ensureroom(to, nb) - ptr = (to.append ? to.size+1 : to.ptr) - written = Int(min(nb, length(to.data) - ptr + 1)) - towrite = written - d = to.data - while towrite > 0 - @inbounds d[ptr] = unsafe_load(p) - ptr += 1 - p += 1 - towrite -= 1 - end - to.size = max(to.size, ptr - 1) - if !to.append - to.ptr += written - end - return written -end - -function write_sub(to::AbstractIOBuffer, a::AbstractArray{UInt8}, offs, nel) - if offs+nel-1 > length(a) || offs < 1 || nel < 0 - throw(BoundsError()) - end - unsafe_write(to, pointer(a, offs), UInt(nel)) -end - -@inline function write(to::AbstractIOBuffer, a::UInt8) - ensureroom(to, UInt(1)) - ptr = (to.append ? to.size+1 : to.ptr) - if ptr > to.maxsize - return 0 - else - to.data[ptr] = a - end - to.size = max(to.size, ptr) - if !to.append - to.ptr += 1 - end - return sizeof(UInt8) -end - -readbytes!(io::AbstractIOBuffer, b::Array{UInt8}, nb=length(b)) = readbytes!(io, b, Int(nb)) -function readbytes!(io::AbstractIOBuffer, b::Array{UInt8}, nb::Int) - nr = min(nb, nb_available(io)) - if length(b) < nr - resize!(b, nr) - end - read_sub(io, b, 1, nr) - return nr -end -read(io::AbstractIOBuffer) = read!(io,StringVector(nb_available(io))) -readavailable(io::AbstractIOBuffer) = read(io) -read(io::AbstractIOBuffer, nb::Integer) = read!(io,StringVector(min(nb, nb_available(io)))) - -function search(buf::IOBuffer, delim::UInt8) - p = pointer(buf.data, buf.ptr) - q = ccall(:memchr,Ptr{UInt8},(Ptr{UInt8},Int32,Csize_t),p,delim,nb_available(buf)) - nb::Int = (q == C_NULL ? 0 : q-p+1) - return nb -end - -function search(buf::AbstractIOBuffer, delim::UInt8) - data = buf.data - for i = buf.ptr : buf.size - @inbounds b = data[i] - if b == delim - return i - buf.ptr + 1 - end - end - return 0 -end - -function readuntil(io::AbstractIOBuffer, delim::UInt8) - lb = 70 - A = StringVector(lb) - n = 0 - data = io.data - for i = io.ptr : io.size - n += 1 - if n > lb - lb = n*2 - resize!(A, lb) - end - @inbounds b = data[i] - @inbounds A[n] = b - if b == delim - break - end - end - io.ptr += n - if lb != n - resize!(A, n) - end - A -end diff --git a/julia-0.6.3/share/julia/base/iostream.jl b/julia-0.6.3/share/julia/base/iostream.jl deleted file mode 100644 index 7517fd1..0000000 --- a/julia-0.6.3/share/julia/base/iostream.jl +++ /dev/null @@ -1,335 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -## IOStream - -const sizeof_ios_t = Int(ccall(:jl_sizeof_ios_t, Cint, ())) - -mutable struct IOStream <: IO - handle::Ptr{Void} - ios::Array{UInt8,1} - name::AbstractString - mark::Int64 - - IOStream(name::AbstractString, buf::Array{UInt8,1}) = new(pointer(buf), buf, name, -1) -end -# TODO: delay adding finalizer, e.g. for memio with a small buffer, or -# in the case where we take! it. -function IOStream(name::AbstractString, finalize::Bool) - buf = zeros(UInt8,sizeof_ios_t) - x = IOStream(name, buf) - if finalize - finalizer(x, close) - end - return x -end -IOStream(name::AbstractString) = IOStream(name, true) - -unsafe_convert(T::Type{Ptr{Void}}, s::IOStream) = convert(T, pointer(s.ios)) -show(io::IO, s::IOStream) = print(io, "IOStream(", s.name, ")") -fd(s::IOStream) = Int(ccall(:jl_ios_fd, Clong, (Ptr{Void},), s.ios)) -stat(s::IOStream) = stat(fd(s)) -close(s::IOStream) = ccall(:ios_close, Void, (Ptr{Void},), s.ios) -isopen(s::IOStream) = ccall(:ios_isopen, Cint, (Ptr{Void},), s.ios)!=0 -function flush(s::IOStream) - sigatomic_begin() - bad = ccall(:ios_flush, Cint, (Ptr{Void},), s.ios) != 0 - sigatomic_end() - systemerror("flush", bad) -end -iswritable(s::IOStream) = ccall(:ios_get_writable, Cint, (Ptr{Void},), s.ios)!=0 -isreadable(s::IOStream) = ccall(:ios_get_readable, Cint, (Ptr{Void},), s.ios)!=0 - -function truncate(s::IOStream, n::Integer) - systemerror("truncate", ccall(:ios_trunc, Cint, (Ptr{Void}, Csize_t), s.ios, n) != 0) - return s -end - -function seek(s::IOStream, n::Integer) - ret = ccall(:ios_seek, Int64, (Ptr{Void}, Int64), s.ios, n) - systemerror("seek", ret == -1) - ret < -1 && error("seek failed") - return s -end - -seekstart(s::IO) = seek(s,0) - -function seekend(s::IOStream) - systemerror("seekend", ccall(:ios_seek_end, Int64, (Ptr{Void},), s.ios) != 0) - return s -end - -function skip(s::IOStream, delta::Integer) - ret = ccall(:ios_skip, Int64, (Ptr{Void}, Int64), s.ios, delta) - systemerror("skip", ret == -1) - ret < -1 && error("skip failed") - return s -end - -function position(s::IOStream) - pos = ccall(:ios_pos, Int64, (Ptr{Void},), s.ios) - systemerror("position", pos == -1) - return pos -end - -eof(s::IOStream) = ccall(:ios_eof_blocking, Cint, (Ptr{Void},), s.ios)!=0 - -## constructing and opening streams ## - -# "own" means the descriptor will be closed with the IOStream - -""" - fdio([name::AbstractString, ]fd::Integer[, own::Bool=false]) -> IOStream - -Create an `IOStream` object from an integer file descriptor. If `own` is `true`, closing -this object will close the underlying descriptor. By default, an `IOStream` is closed when -it is garbage collected. `name` allows you to associate the descriptor with a named file. -""" -function fdio(name::AbstractString, fd::Integer, own::Bool=false) - s = IOStream(name) - ccall(:ios_fd, Ptr{Void}, (Ptr{Void}, Clong, Cint, Cint), - s.ios, fd, 0, own) - return s -end -fdio(fd::Integer, own::Bool=false) = fdio(string(""), fd, own) - - -""" - open(filename::AbstractString, [read::Bool, write::Bool, create::Bool, truncate::Bool, append::Bool]) -> IOStream - -Open a file in a mode specified by five boolean arguments. The default is to open files for -reading only. Returns a stream for accessing the file. -""" -function open(fname::AbstractString, rd::Bool, wr::Bool, cr::Bool, tr::Bool, ff::Bool) - s = IOStream(string("")) - systemerror("opening file $fname", - ccall(:ios_file, Ptr{Void}, - (Ptr{UInt8}, Cstring, Cint, Cint, Cint, Cint), - s.ios, fname, rd, wr, cr, tr) == C_NULL) - if ff - systemerror("seeking to end of file $fname", ccall(:ios_seek_end, Int64, (Ptr{Void},), s.ios) != 0) - end - return s -end -open(fname::AbstractString) = open(fname, true, false, false, false, false) - -""" - open(filename::AbstractString, [mode::AbstractString]) -> IOStream - -Alternate syntax for open, where a string-based mode specifier is used instead of the five -booleans. The values of `mode` correspond to those from `fopen(3)` or Perl `open`, and are -equivalent to setting the following boolean groups: - -| Mode | Description | -|:-----|:------------------------------| -| r | read | -| r+ | read, write | -| w | write, create, truncate | -| w+ | read, write, create, truncate | -| a | write, create, append | -| a+ | read, write, create, append | -""" -function open(fname::AbstractString, mode::AbstractString) - mode == "r" ? open(fname, true , false, false, false, false) : - mode == "r+" ? open(fname, true , true , false, false, false) : - mode == "w" ? open(fname, false, true , true , true , false) : - mode == "w+" ? open(fname, true , true , true , true , false) : - mode == "a" ? open(fname, false, true , true , false, true ) : - mode == "a+" ? open(fname, true , true , true , false, true ) : - throw(ArgumentError("invalid open mode: $mode")) -end - -""" - open(f::Function, args...) - -Apply the function `f` to the result of `open(args...)` and close the resulting file -descriptor upon completion. - -**Example**: `open(readstring, "file.txt")` -""" -function open(f::Function, args...) - io = open(args...) - try - f(io) - finally - close(io) - end -end - -## low-level calls ## - -write(s::IOStream, b::UInt8) = Int(ccall(:ios_putc, Cint, (Cint, Ptr{Void}), b, s.ios)) - -function unsafe_write(s::IOStream, p::Ptr{UInt8}, nb::UInt) - if !iswritable(s) - throw(ArgumentError("write failed, IOStream is not writeable")) - end - return Int(ccall(:ios_write, Csize_t, (Ptr{Void}, Ptr{Void}, Csize_t), s.ios, p, nb)) -end - -function write{T,N}(s::IOStream, a::SubArray{T,N,<:Array}) - if !isbits(T) || stride(a,1)!=1 - return invoke(write, Tuple{Any, AbstractArray}, s, a) - end - colsz = size(a,1)*sizeof(T) - if N<=1 - return unsafe_write(s, pointer(a, 1), colsz) - else - for idxs in CartesianRange((1, size(a)[2:end]...)) - unsafe_write(s, pointer(a, idxs.I), colsz) - end - return colsz*trailingsize(a,2) - end -end - -# num bytes available without blocking -nb_available(s::IOStream) = ccall(:jl_nb_available, Int32, (Ptr{Void},), s.ios) - -readavailable(s::IOStream) = read!(s, Vector{UInt8}(nb_available(s))) - -function read(s::IOStream, ::Type{UInt8}) - b = ccall(:ios_getc, Cint, (Ptr{Void},), s.ios) - if b == -1 - throw(EOFError()) - end - return b % UInt8 -end - -if ENDIAN_BOM == 0x04030201 -function read(s::IOStream, T::Union{Type{Int16},Type{UInt16},Type{Int32},Type{UInt32},Type{Int64},Type{UInt64}}) - return ccall(:jl_ios_get_nbyte_int, UInt64, (Ptr{Void}, Csize_t), s.ios, sizeof(T)) % T -end -end - -function unsafe_read(s::IOStream, p::Ptr{UInt8}, nb::UInt) - if ccall(:ios_readall, Csize_t, - (Ptr{Void}, Ptr{Void}, Csize_t), s, p, nb) != nb - throw(EOFError()) - end - nothing -end - -## text I/O ## - -function write(s::IOStream, c::Char) - if !iswritable(s) - throw(ArgumentError("write failed, IOStream is not writeable")) - end - Int(ccall(:ios_pututf8, Cint, (Ptr{Void}, UInt32), s.ios, c)) -end -read(s::IOStream, ::Type{Char}) = Char(ccall(:jl_getutf8, UInt32, (Ptr{Void},), s.ios)) - -take!(s::IOStream) = - ccall(:jl_take_buffer, Vector{UInt8}, (Ptr{Void},), s.ios) - -function readuntil(s::IOStream, delim::UInt8) - ccall(:jl_readuntil, Array{UInt8,1}, (Ptr{Void}, UInt8, UInt8, UInt8), s.ios, delim, 0, 0) -end - -# like readuntil, above, but returns a String without requiring a copy -function readuntil_string(s::IOStream, delim::UInt8) - ccall(:jl_readuntil, Ref{String}, (Ptr{Void}, UInt8, UInt8, UInt8), s.ios, delim, 1, false) -end - -function readline(s::IOStream; chomp::Bool=true) - ccall(:jl_readuntil, Ref{String}, (Ptr{Void}, UInt8, UInt8, UInt8), s.ios, '\n', 1, chomp) -end - -function readbytes_all!(s::IOStream, b::Array{UInt8}, nb) - olb = lb = length(b) - nr = 0 - while nr < nb - if lb < nr+1 - lb = max(65536, (nr+1) * 2) - resize!(b, lb) - end - nr += Int(ccall(:ios_readall, Csize_t, (Ptr{Void}, Ptr{Void}, Csize_t), - s.ios, pointer(b, nr+1), min(lb-nr, nb-nr))) - eof(s) && break - end - if lb > olb && lb > nr - resize!(b, nr) # shrink to just contain input data if was resized - end - return nr -end - -function readbytes_some!(s::IOStream, b::Array{UInt8}, nb) - olb = lb = length(b) - if nb > lb - resize!(b, nb) - end - nr = Int(ccall(:ios_read, Csize_t, (Ptr{Void}, Ptr{Void}, Csize_t), - s.ios, pointer(b), nb)) - if lb > olb && lb > nr - resize!(b, nr) - end - return nr -end - -""" - readbytes!(stream::IOStream, b::AbstractVector{UInt8}, nb=length(b); all::Bool=true) - -Read at most `nb` bytes from `stream` into `b`, returning the number of bytes read. -The size of `b` will be increased if needed (i.e. if `nb` is greater than `length(b)` -and enough bytes could be read), but it will never be decreased. - -See [`read`](@ref) for a description of the `all` option. -""" -function readbytes!(s::IOStream, b::Array{UInt8}, nb=length(b); all::Bool=true) - return all ? readbytes_all!(s, b, nb) : readbytes_some!(s, b, nb) -end - -function read(s::IOStream) - sz = 0 - try # filesize is just a hint, so ignore if it fails - sz = filesize(s) - pos = ccall(:ios_pos, Int64, (Ptr{Void},), s.ios) - if pos > 0 - sz -= pos - end - end - b = StringVector(sz<=0 ? 1024 : sz) - nr = readbytes_all!(s, b, typemax(Int)) - resize!(b, nr) -end - -""" - read(s::IOStream, nb::Integer; all=true) - -Read at most `nb` bytes from `s`, returning a `Vector{UInt8}` of the bytes read. - -If `all` is `true` (the default), this function will block repeatedly trying to read all -requested bytes, until an error or end-of-file occurs. If `all` is `false`, at most one -`read` call is performed, and the amount of data returned is device-dependent. Note that not -all stream types support the `all` option. -""" -function read(s::IOStream, nb::Integer; all::Bool=true) - b = Array{UInt8,1}(nb) - nr = readbytes!(s, b, nb, all=all) - resize!(b, nr) -end - -## Character streams ## -const _chtmp = Ref{Char}() -function peekchar(s::IOStream) - if ccall(:ios_peekutf8, Cint, (Ptr{Void}, Ptr{Char}), s, _chtmp) < 0 - return typemax(Char) - end - return _chtmp[] -end - -function peek(s::IOStream) - ccall(:ios_peekc, Cint, (Ptr{Void},), s) -end - -function skipchars(io::IOStream, pred; linecomment=nothing) - while !eof(io) - c = read(io, Char) - if c === linecomment - readline(io) - elseif !pred(c) - skip(io, -codelen(c)) - break - end - end - return io -end diff --git a/julia-0.6.3/share/julia/base/irrationals.jl b/julia-0.6.3/share/julia/base/irrationals.jl deleted file mode 100644 index 5653106..0000000 --- a/julia-0.6.3/share/julia/base/irrationals.jl +++ /dev/null @@ -1,230 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -## general machinery for irrational mathematical constants - -""" - Irrational <: Real - -Irrational number type. -""" -struct Irrational{sym} <: Real end - -show(io::IO, x::Irrational{sym}) where {sym} = print(io, "$sym = $(string(float(x))[1:15])...") - -promote_rule(::Type{<:Irrational}, ::Type{Float16}) = Float16 -promote_rule(::Type{<:Irrational}, ::Type{Float32}) = Float32 -promote_rule(::Type{<:Irrational}, ::Type{<:Irrational}) = Float64 -promote_rule(::Type{<:Irrational}, ::Type{T}) where {T<:Number} = promote_type(Float64, T) - -convert(::Type{AbstractFloat}, x::Irrational) = Float64(x) -convert(::Type{Float16}, x::Irrational) = Float16(Float32(x)) -convert(::Type{Complex{T}}, x::Irrational) where {T<:Real} = convert(Complex{T}, convert(T,x)) - -@pure function convert(::Type{Rational{T}}, x::Irrational) where T<:Integer - o = precision(BigFloat) - p = 256 - while true - setprecision(BigFloat, p) - bx = BigFloat(x) - r = rationalize(T, bx, tol=0) - if abs(BigFloat(r) - bx) > eps(bx) - setprecision(BigFloat, o) - return r - end - p += 32 - end -end -convert(::Type{Rational{BigInt}}, x::Irrational) = throw(ArgumentError("Cannot convert an Irrational to a Rational{BigInt}: use rationalize(Rational{BigInt}, x) instead")) - -@pure function (t::Type{T})(x::Irrational, r::RoundingMode) where T<:Union{Float32,Float64} - setprecision(BigFloat, 256) do - T(BigFloat(x), r) - end -end - -==(::Irrational{s}, ::Irrational{s}) where {s} = true -==(::Irrational, ::Irrational) = false - -# Irrationals, by definition, can't have a finite representation equal them exactly -==(x::Irrational, y::Real) = false -==(x::Real, y::Irrational) = false - -# Irrational vs AbstractFloat -<(x::Irrational, y::Float64) = Float64(x,RoundUp) <= y -<(x::Float64, y::Irrational) = x <= Float64(y,RoundDown) -<(x::Irrational, y::Float32) = Float32(x,RoundUp) <= y -<(x::Float32, y::Irrational) = x <= Float32(y,RoundDown) -<(x::Irrational, y::Float16) = Float32(x,RoundUp) <= y -<(x::Float16, y::Irrational) = x <= Float32(y,RoundDown) -<(x::Irrational, y::BigFloat) = setprecision(precision(y)+32) do - big(x) < y -end -<(x::BigFloat, y::Irrational) = setprecision(precision(x)+32) do - x < big(y) -end - -<=(x::Irrational, y::AbstractFloat) = x < y -<=(x::AbstractFloat, y::Irrational) = x < y - -# Irrational vs Rational -@pure function rationalize(::Type{T}, x::Irrational; tol::Real=0) where T - return rationalize(T, big(x), tol=tol) -end -@pure function lessrational(rx::Rational{<:Integer}, x::Irrational) - # an @pure version of `<` for determining if the rationalization of - # an irrational number required rounding up or down - return rx < big(x) -end -function <(x::Irrational, y::Rational{T}) where T - T <: Unsigned && x < 0.0 && return true - rx = rationalize(T, x) - if lessrational(rx, x) - return rx < y - else - return rx <= y - end -end -function <(x::Rational{T}, y::Irrational) where T - T <: Unsigned && y < 0.0 && return false - ry = rationalize(T, y) - if lessrational(ry, y) - return x <= ry - else - return x < ry - end -end -<(x::Irrational, y::Rational{BigInt}) = big(x) < y -<(x::Rational{BigInt}, y::Irrational) = x < big(y) - -<=(x::Irrational, y::Rational) = x < y -<=(x::Rational, y::Irrational) = x < y - -isfinite(::Irrational) = true -iszero(::Irrational) = false - -hash(x::Irrational, h::UInt) = 3*object_id(x) - h - --(x::Irrational) = -Float64(x) -for op in Symbol[:+, :-, :*, :/, :^] - @eval $op(x::Irrational, y::Irrational) = $op(Float64(x),Float64(y)) -end -*(x::Bool, y::Irrational) = ifelse(x, Float64(y), 0.0) - -macro irrational(sym, val, def) - esym = esc(sym) - qsym = esc(Expr(:quote, sym)) - bigconvert = isa(def,Symbol) ? quote - function Base.convert(::Type{BigFloat}, ::Irrational{$qsym}) - c = BigFloat() - ccall(($(string("mpfr_const_", def)), :libmpfr), - Cint, (Ptr{BigFloat}, Int32), - &c, MPFR.ROUNDING_MODE[]) - return c - end - end : quote - Base.convert(::Type{BigFloat}, ::Irrational{$qsym}) = $(esc(def)) - end - quote - const $esym = Irrational{$qsym}() - $bigconvert - Base.convert(::Type{Float64}, ::Irrational{$qsym}) = $val - Base.convert(::Type{Float32}, ::Irrational{$qsym}) = $(Float32(val)) - @assert isa(big($esym), BigFloat) - @assert Float64($esym) == Float64(big($esym)) - @assert Float32($esym) == Float32(big($esym)) - end -end - -big(x::Irrational) = convert(BigFloat,x) - -## specific irrational mathematical constants - -@irrational π 3.14159265358979323846 pi -@irrational e 2.71828182845904523536 exp(big(1)) -@irrational γ 0.57721566490153286061 euler -@irrational catalan 0.91596559417721901505 catalan -@irrational φ 1.61803398874989484820 (1+sqrt(big(5)))/2 - -# aliases -""" - pi - π - -The constant pi. - -```jldoctest -julia> pi -π = 3.1415926535897... -``` -""" -π, const pi = π - -""" - e - eu - -The constant e. - -```jldoctest -julia> e -e = 2.7182818284590... -``` -""" -e, const eu = e - -""" - γ - eulergamma - -Euler's constant. - -```jldoctest -julia> eulergamma -γ = 0.5772156649015... -``` -""" -γ, const eulergamma = γ - -""" - φ - golden - -The golden ratio. - -```jldoctest -julia> golden -φ = 1.6180339887498... -``` -""" -φ, const golden = φ - -""" - catalan - -Catalan's constant. - -```jldoctest -julia> catalan -catalan = 0.9159655941772... -``` -""" -catalan - -# special behaviors - -# use exp for e^x or e.^x, as in -# ^(::Irrational{:e}, x::Number) = exp(x) -# but need to loop over types to prevent ambiguity with generic rules for ^(::Number, x) etc. -for T in (Irrational, Rational, Integer, Number) - ^(::Irrational{:e}, x::T) = exp(x) -end - -log(::Irrational{:e}) = 1 # use 1 to correctly promote expressions like log(x)/log(e) -log(::Irrational{:e}, x::Number) = log(x) - -# align along = for nice Array printing -function alignment(io::IO, x::Irrational) - m = match(r"^(.*?)(=.*)$", sprint(0, showcompact, x, env=io)) - m === nothing ? (length(sprint(0, showcompact, x, env=io)), 0) : - (length(m.captures[1]), length(m.captures[2])) -end diff --git a/julia-0.6.3/share/julia/base/iterators.jl b/julia-0.6.3/share/julia/base/iterators.jl deleted file mode 100644 index ef4e7ac..0000000 --- a/julia-0.6.3/share/julia/base/iterators.jl +++ /dev/null @@ -1,788 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -module Iterators - -import Base: start, done, next, isempty, length, size, eltype, iteratorsize, iteratoreltype, indices, ndims - -using Base: tuple_type_cons, SizeUnknown, HasLength, HasShape, IsInfinite, EltypeUnknown, HasEltype, OneTo, @propagate_inbounds - -export enumerate, zip, rest, countfrom, take, drop, cycle, repeated, product, flatten, partition - -_min_length(a, b, ::IsInfinite, ::IsInfinite) = min(length(a),length(b)) # inherit behaviour, error -_min_length(a, b, A, ::IsInfinite) = length(a) -_min_length(a, b, ::IsInfinite, B) = length(b) -_min_length(a, b, A, B) = min(length(a),length(b)) - -_diff_length(a, b, A, ::IsInfinite) = 0 -_diff_length(a, b, ::IsInfinite, ::IsInfinite) = 0 -_diff_length(a, b, ::IsInfinite, B) = length(a) # inherit behaviour, error -_diff_length(a, b, A, B) = max(length(a)-length(b), 0) - -and_iteratorsize{T}(isz::T, ::T) = isz -and_iteratorsize(::HasLength, ::HasShape) = HasLength() -and_iteratorsize(::HasShape, ::HasLength) = HasLength() -and_iteratorsize(a, b) = SizeUnknown() - -and_iteratoreltype(iel::T, ::T) where {T} = iel -and_iteratoreltype(a, b) = EltypeUnknown() - -# enumerate - -struct Enumerate{I} - itr::I -end - -""" - enumerate(iter) - -An iterator that yields `(i, x)` where `i` is a counter starting at 1, -and `x` is the `i`th value from the given iterator. It's useful when -you need not only the values `x` over which you are iterating, but -also the number of iterations so far. Note that `i` may not be valid -for indexing `iter`; it's also possible that `x != iter[i]`, if `iter` -has indices that do not start at 1. See the `enumerate(IndexLinear(), -iter)` method if you want to ensure that `i` is an index. - -# Example - -```jldoctest -julia> a = ["a", "b", "c"]; - -julia> for (index, value) in enumerate(a) - println("\$index \$value") - end -1 a -2 b -3 c -``` -""" -enumerate(iter) = Enumerate(iter) - -length(e::Enumerate) = length(e.itr) -size(e::Enumerate) = size(e.itr) -@inline start(e::Enumerate) = (1, start(e.itr)) -@inline function next(e::Enumerate, state) - n = next(e.itr,state[2]) - (state[1],n[1]), (state[1]+1,n[2]) -end -@inline done(e::Enumerate, state) = done(e.itr, state[2]) - -eltype(::Type{Enumerate{I}}) where {I} = Tuple{Int, eltype(I)} - -iteratorsize(::Type{Enumerate{I}}) where {I} = iteratorsize(I) -iteratoreltype(::Type{Enumerate{I}}) where {I} = iteratoreltype(I) - -struct IndexValue{I,A<:AbstractArray} - data::A - itr::I -end - -""" - enumerate(IndexLinear(), A) - enumerate(IndexCartesian(), A) - enumerate(IndexStyle(A), A) - -An iterator that accesses each element of the array `A`, returning -`(i, x)`, where `i` is the index for the element and `x = A[i]`. This -is similar to `enumerate(A)`, except `i` will always be a valid index -for `A`. - -Specifying `IndexLinear()` ensures that `i` will be an integer; -specifying `IndexCartesian()` ensures that `i` will be a -`CartesianIndex`; specifying `IndexStyle(A)` chooses whichever has -been defined as the native indexing style for array `A`. - -# Examples - -```jldoctest -julia> A = ["a" "d"; "b" "e"; "c" "f"]; - -julia> for (index, value) in enumerate(IndexStyle(A), A) - println("\$index \$value") - end -1 a -2 b -3 c -4 d -5 e -6 f - -julia> S = view(A, 1:2, :); - -julia> for (index, value) in enumerate(IndexStyle(S), S) - println("\$index \$value") - end -CartesianIndex{2}((1, 1)) a -CartesianIndex{2}((2, 1)) b -CartesianIndex{2}((1, 2)) d -CartesianIndex{2}((2, 2)) e -``` - -Note that `enumerate(A)` returns `i` as a *counter* (always starting -at 1), whereas `enumerate(IndexLinear(), A)` returns `i` as an *index* -(starting at the first linear index of `A`, which may or may not be -1). - -See also: [`IndexStyle`](@ref), [`indices`](@ref). -""" -enumerate(::IndexLinear, A::AbstractArray) = IndexValue(A, linearindices(A)) -enumerate(::IndexCartesian, A::AbstractArray) = IndexValue(A, CartesianRange(indices(A))) - -length(v::IndexValue) = length(v.itr) -indices(v::IndexValue) = indices(v.itr) -size(v::IndexValue) = size(v.itr) -@inline start(v::IndexValue) = start(v.itr) -@propagate_inbounds function next(v::IndexValue, state) - indx, n = next(v.itr, state) - item = v.data[indx] - (indx, item), n -end -@inline done(v::IndexValue, state) = done(v.itr, state) - -eltype(::Type{IndexValue{I,A}}) where {I,A} = Tuple{eltype(I), eltype(A)} - -iteratorsize(::Type{IndexValue{I}}) where {I} = iteratorsize(I) -iteratoreltype(::Type{IndexValue{I}}) where {I} = iteratoreltype(I) - -# zip - -abstract type AbstractZipIterator end - -zip_iteratorsize(a, b) = and_iteratorsize(a,b) # as `and_iteratorsize` but inherit `Union{HasLength,IsInfinite}` of the shorter iterator -zip_iteratorsize(::HasLength, ::IsInfinite) = HasLength() -zip_iteratorsize(::HasShape, ::IsInfinite) = HasLength() -zip_iteratorsize(a::IsInfinite, b) = zip_iteratorsize(b,a) -zip_iteratorsize(a::IsInfinite, b::IsInfinite) = IsInfinite() - - -struct Zip1{I} <: AbstractZipIterator - a::I -end -zip(a) = Zip1(a) -length(z::Zip1) = length(z.a) -size(z::Zip1) = size(z.a) -indices(z::Zip1) = indices(z.a) -eltype(::Type{Zip1{I}}) where {I} = Tuple{eltype(I)} -@inline start(z::Zip1) = start(z.a) -@inline function next(z::Zip1, st) - n = next(z.a,st) - return ((n[1],), n[2]) -end -@inline done(z::Zip1, st) = done(z.a,st) - -iteratorsize(::Type{Zip1{I}}) where {I} = iteratorsize(I) -iteratoreltype(::Type{Zip1{I}}) where {I} = iteratoreltype(I) - -struct Zip2{I1, I2} <: AbstractZipIterator - a::I1 - b::I2 -end -zip(a, b) = Zip2(a, b) -length(z::Zip2) = _min_length(z.a, z.b, iteratorsize(z.a), iteratorsize(z.b)) -size(z::Zip2) = promote_shape(size(z.a), size(z.b)) -indices(z::Zip2) = promote_shape(indices(z.a), indices(z.b)) -eltype(::Type{Zip2{I1,I2}}) where {I1,I2} = Tuple{eltype(I1), eltype(I2)} -@inline start(z::Zip2) = (start(z.a), start(z.b)) -@inline function next(z::Zip2, st) - n1 = next(z.a,st[1]) - n2 = next(z.b,st[2]) - return ((n1[1], n2[1]), (n1[2], n2[2])) -end -@inline done(z::Zip2, st) = done(z.a,st[1]) | done(z.b,st[2]) - -iteratorsize(::Type{Zip2{I1,I2}}) where {I1,I2} = zip_iteratorsize(iteratorsize(I1),iteratorsize(I2)) -iteratoreltype(::Type{Zip2{I1,I2}}) where {I1,I2} = and_iteratoreltype(iteratoreltype(I1),iteratoreltype(I2)) - -struct Zip{I, Z<:AbstractZipIterator} <: AbstractZipIterator - a::I - z::Z -end - -""" - zip(iters...) - -For a set of iterable objects, returns an iterable of tuples, where the `i`th tuple contains -the `i`th component of each input iterable. - -Note that [`zip`](@ref) is its own inverse: `collect(zip(zip(a...)...)) == collect(a)`. - -# Example - -```jldoctest -julia> a = 1:5 -1:5 - -julia> b = ["e","d","b","c","a"] -5-element Array{String,1}: - "e" - "d" - "b" - "c" - "a" - -julia> c = zip(a,b) -Base.Iterators.Zip2{UnitRange{Int64},Array{String,1}}(1:5, String["e", "d", "b", "c", "a"]) - -julia> length(c) -5 - -julia> first(c) -(1, "e") -``` -""" -zip(a, b, c...) = Zip(a, zip(b, c...)) -length(z::Zip) = _min_length(z.a, z.z, iteratorsize(z.a), iteratorsize(z.z)) -size(z::Zip) = promote_shape(size(z.a), size(z.z)) -indices(z::Zip) = promote_shape(indices(z.a), indices(z.z)) -eltype(::Type{Zip{I,Z}}) where {I,Z} = tuple_type_cons(eltype(I), eltype(Z)) -@inline start(z::Zip) = tuple(start(z.a), start(z.z)) -@inline function next(z::Zip, st) - n1 = next(z.a, st[1]) - n2 = next(z.z, st[2]) - (tuple(n1[1], n2[1]...), (n1[2], n2[2])) -end -@inline done(z::Zip, st) = done(z.a,st[1]) | done(z.z,st[2]) - -iteratorsize(::Type{Zip{I1,I2}}) where {I1,I2} = zip_iteratorsize(iteratorsize(I1),iteratorsize(I2)) -iteratoreltype(::Type{Zip{I1,I2}}) where {I1,I2} = and_iteratoreltype(iteratoreltype(I1),iteratoreltype(I2)) - -# filter - -struct Filter{F,I} - flt::F - itr::I -end - -""" - Iterators.filter(flt, itr) - -Given a predicate function `flt` and an iterable object `itr`, return an -iterable object which upon iteration yields the elements `x` of `itr` that -satisfy `flt(x)`. The order of the original iterator is preserved. - -This function is *lazy*; that is, it is guaranteed to return in ``Θ(1)`` time -and use ``Θ(1)`` additional space, and `flt` will not be called by an -invocation of `filter`. Calls to `flt` will be made when iterating over the -returned iterable object. These calls are not cached and repeated calls will be -made when reiterating. - -See [`Base.filter`](@ref) for an eager implementation of filtering for arrays. -""" -filter(flt, itr) = Filter(flt, itr) - -start(f::Filter) = start_filter(f.flt, f.itr) -function start_filter(pred, itr) - s = start(itr) - while !done(itr,s) - v,t = next(itr,s) - if pred(v) - return (false, v, t) - end - s=t - end - (true,) -end - -next(f::Filter, s) = advance_filter(f.flt, f.itr, s) -function advance_filter(pred, itr, st) - _, v, s = st - while !done(itr,s) - w,t = next(itr,s) - if pred(w) - return v, (false, w, t) - end - s=t - end - v, (true, v, s) -end - -done(f::Filter, s) = s[1] - -eltype(::Type{Filter{F,I}}) where {F,I} = eltype(I) -iteratoreltype(::Type{Filter{F,I}}) where {F,I} = iteratoreltype(I) -iteratorsize(::Type{<:Filter}) = SizeUnknown() - -# Rest -- iterate starting at the given state - -struct Rest{I,S} - itr::I - st::S -end - -""" - rest(iter, state) - -An iterator that yields the same elements as `iter`, but starting at the given `state`. -""" -rest(itr,state) = Rest(itr,state) - -start(i::Rest) = i.st -next(i::Rest, st) = next(i.itr, st) -done(i::Rest, st) = done(i.itr, st) - -eltype(::Type{Rest{I}}) where {I} = eltype(I) -iteratoreltype(::Type{Rest{I,S}}) where {I,S} = iteratoreltype(I) -rest_iteratorsize(a) = SizeUnknown() -rest_iteratorsize(::IsInfinite) = IsInfinite() -iteratorsize(::Type{Rest{I,S}}) where {I,S} = rest_iteratorsize(iteratorsize(I)) - - -# Count -- infinite counting - -struct Count{S<:Number} - start::S - step::S -end - -""" - countfrom(start=1, step=1) - -An iterator that counts forever, starting at `start` and incrementing by `step`. -""" -countfrom(start::Number, step::Number) = Count(promote(start, step)...) -countfrom(start::Number) = Count(start, oneunit(start)) -countfrom() = Count(1, 1) - -eltype(::Type{Count{S}}) where {S} = S - -start(it::Count) = it.start -next(it::Count, state) = (state, state + it.step) -done(it::Count, state) = false - -iteratorsize(::Type{<:Count}) = IsInfinite() - -# Take -- iterate through the first n elements - -struct Take{I} - xs::I - n::Int -end - -""" - take(iter, n) - -An iterator that generates at most the first `n` elements of `iter`. - -# Example - -```jldoctest -julia> a = 1:2:11 -1:2:11 - -julia> collect(a) -6-element Array{Int64,1}: - 1 - 3 - 5 - 7 - 9 - 11 - -julia> collect(Iterators.take(a,3)) -3-element Array{Int64,1}: - 1 - 3 - 5 -``` -""" -take(xs, n::Integer) = Take(xs, Int(n)) -take(xs::Take, n::Integer) = Take(xs.xs, min(Int(n), xs.n)) - -eltype(::Type{Take{I}}) where {I} = eltype(I) -iteratoreltype(::Type{Take{I}}) where {I} = iteratoreltype(I) -take_iteratorsize(a) = HasLength() -take_iteratorsize(::SizeUnknown) = SizeUnknown() -iteratorsize(::Type{Take{I}}) where {I} = take_iteratorsize(iteratorsize(I)) -length(t::Take) = _min_length(t.xs, 1:t.n, iteratorsize(t.xs), HasLength()) - -start(it::Take) = (it.n, start(it.xs)) - -function next(it::Take, state) - n, xs_state = state - v, xs_state = next(it.xs, xs_state) - return v, (n - 1, xs_state) -end - -function done(it::Take, state) - n, xs_state = state - return n <= 0 || done(it.xs, xs_state) -end - -# Drop -- iterator through all but the first n elements - -struct Drop{I} - xs::I - n::Int -end - -""" - drop(iter, n) - -An iterator that generates all but the first `n` elements of `iter`. - -# Example - -```jldoctest -julia> a = 1:2:11 -1:2:11 - -julia> collect(a) -6-element Array{Int64,1}: - 1 - 3 - 5 - 7 - 9 - 11 - -julia> collect(Iterators.drop(a,4)) -2-element Array{Int64,1}: - 9 - 11 -``` -""" -drop(xs, n::Integer) = Drop(xs, Int(n)) -drop(xs::Take, n::Integer) = Take(drop(xs.xs, Int(n)), max(0, xs.n - Int(n))) -drop(xs::Drop, n::Integer) = Drop(xs.xs, Int(n) + xs.n) - -eltype(::Type{Drop{I}}) where {I} = eltype(I) -iteratoreltype(::Type{Drop{I}}) where {I} = iteratoreltype(I) -drop_iteratorsize(::SizeUnknown) = SizeUnknown() -drop_iteratorsize(::Union{HasShape, HasLength}) = HasLength() -drop_iteratorsize(::IsInfinite) = IsInfinite() -iteratorsize(::Type{Drop{I}}) where {I} = drop_iteratorsize(iteratorsize(I)) -length(d::Drop) = _diff_length(d.xs, 1:d.n, iteratorsize(d.xs), HasLength()) - -function start(it::Drop) - xs_state = start(it.xs) - for i in 1:it.n - if done(it.xs, xs_state) - break - end - - _, xs_state = next(it.xs, xs_state) - end - xs_state -end - -next(it::Drop, state) = next(it.xs, state) -done(it::Drop, state) = done(it.xs, state) - -# Cycle an iterator forever - -struct Cycle{I} - xs::I -end - -""" - cycle(iter) - -An iterator that cycles through `iter` forever. -""" -cycle(xs) = Cycle(xs) - -eltype(::Type{Cycle{I}}) where {I} = eltype(I) -iteratoreltype(::Type{Cycle{I}}) where {I} = iteratoreltype(I) -iteratorsize(::Type{Cycle{I}}) where {I} = IsInfinite() - -function start(it::Cycle) - s = start(it.xs) - return s, done(it.xs, s) -end - -function next(it::Cycle, state) - s, d = state - if done(it.xs, s) - s = start(it.xs) - end - v, s = next(it.xs, s) - return v, (s, false) -end - -done(it::Cycle, state) = state[2] - - -# Repeated - repeat an object infinitely many times - -struct Repeated{O} - x::O -end -repeated(x) = Repeated(x) - -""" - repeated(x[, n::Int]) - -An iterator that generates the value `x` forever. If `n` is specified, generates `x` that -many times (equivalent to `take(repeated(x), n)`). - -# Example - -```jldoctest -julia> a = Iterators.repeated([1 2], 4); - -julia> collect(a) -4-element Array{Array{Int64,2},1}: - [1 2] - [1 2] - [1 2] - [1 2] -``` -""" -repeated(x, n::Integer) = take(repeated(x), Int(n)) - -eltype(::Type{Repeated{O}}) where {O} = O - -start(it::Repeated) = nothing -next(it::Repeated, state) = (it.x, nothing) -done(it::Repeated, state) = false - -iteratorsize(::Type{<:Repeated}) = IsInfinite() -iteratoreltype(::Type{<:Repeated}) = HasEltype() - - -# Product -- cartesian product of iterators - -abstract type AbstractProdIterator end - -length(p::AbstractProdIterator) = prod(size(p)) -_length(p::AbstractProdIterator) = prod(map(unsafe_length, indices(p))) -size(p::AbstractProdIterator) = _prod_size(p.a, p.b, iteratorsize(p.a), iteratorsize(p.b)) -indices(p::AbstractProdIterator) = _prod_indices(p.a, p.b, iteratorsize(p.a), iteratorsize(p.b)) -ndims(p::AbstractProdIterator) = length(indices(p)) - -# generic methods to handle size of Prod* types -_prod_size(a, ::HasShape) = size(a) -_prod_size(a, ::HasLength) = (length(a),) -_prod_size(a, A) = - throw(ArgumentError("Cannot compute size for object of type $(typeof(a))")) -_prod_size(a, b, ::HasLength, ::HasLength) = (length(a), length(b)) -_prod_size(a, b, ::HasLength, ::HasShape) = (length(a), size(b)...) -_prod_size(a, b, ::HasShape, ::HasLength) = (size(a)..., length(b)) -_prod_size(a, b, ::HasShape, ::HasShape) = (size(a)..., size(b)...) -_prod_size(a, b, A, B) = - throw(ArgumentError("Cannot construct size for objects of types $(typeof(a)) and $(typeof(b))")) - -_prod_indices(a, ::HasShape) = indices(a) -_prod_indices(a, ::HasLength) = (OneTo(length(a)),) -_prod_indices(a, A) = - throw(ArgumentError("Cannot compute indices for object of type $(typeof(a))")) -_prod_indices(a, b, ::HasLength, ::HasLength) = (OneTo(length(a)), OneTo(length(b))) -_prod_indices(a, b, ::HasLength, ::HasShape) = (OneTo(length(a)), indices(b)...) -_prod_indices(a, b, ::HasShape, ::HasLength) = (indices(a)..., OneTo(length(b))) -_prod_indices(a, b, ::HasShape, ::HasShape) = (indices(a)..., indices(b)...) -_prod_indices(a, b, A, B) = - throw(ArgumentError("Cannot construct indices for objects of types $(typeof(a)) and $(typeof(b))")) - -# one iterator -struct Prod1{I} <: AbstractProdIterator - a::I -end -product(a) = Prod1(a) - -eltype(::Type{Prod1{I}}) where {I} = Tuple{eltype(I)} -size(p::Prod1) = _prod_size(p.a, iteratorsize(p.a)) -indices(p::Prod1) = _prod_indices(p.a, iteratorsize(p.a)) - -@inline start(p::Prod1) = start(p.a) -@inline function next(p::Prod1, st) - n, st = next(p.a, st) - (n,), st -end -@inline done(p::Prod1, st) = done(p.a, st) - -iteratoreltype(::Type{Prod1{I}}) where {I} = iteratoreltype(I) -iteratorsize(::Type{Prod1{I}}) where {I} = iteratorsize(I) - -# two iterators -struct Prod2{I1, I2} <: AbstractProdIterator - a::I1 - b::I2 -end - -""" - product(iters...) - -Returns an iterator over the product of several iterators. Each generated element is -a tuple whose `i`th element comes from the `i`th argument iterator. The first iterator -changes the fastest. Example: - -# Example - -```jldoctest -julia> collect(Iterators.product(1:2,3:5)) -2×3 Array{Tuple{Int64,Int64},2}: - (1, 3) (1, 4) (1, 5) - (2, 3) (2, 4) (2, 5) -``` -""" -product(a, b) = Prod2(a, b) - -eltype(::Type{Prod2{I1,I2}}) where {I1,I2} = Tuple{eltype(I1), eltype(I2)} - -iteratoreltype(::Type{Prod2{I1,I2}}) where {I1,I2} = and_iteratoreltype(iteratoreltype(I1),iteratoreltype(I2)) -iteratorsize(::Type{Prod2{I1,I2}}) where {I1,I2} = prod_iteratorsize(iteratorsize(I1),iteratorsize(I2)) - -function start(p::AbstractProdIterator) - s1, s2 = start(p.a), start(p.b) - s1, s2, Nullable{eltype(p.b)}(), (done(p.a,s1) || done(p.b,s2)) -end - -@inline function prod_next(p, st) - s1, s2 = st[1], st[2] - v1, s1 = next(p.a, s1) - - nv2 = st[3] - if isnull(nv2) - v2, s2 = next(p.b, s2) - else - v2 = nv2.value - end - - if done(p.a, s1) - return (v1,v2), (start(p.a), s2, Nullable{eltype(nv2)}(), done(p.b,s2)) - end - return (v1,v2), (s1, s2, Nullable(v2), false) -end - -@inline next(p::Prod2, st) = prod_next(p, st) -@inline done(p::AbstractProdIterator, st) = st[4] - -# n iterators -struct Prod{I1, I2<:AbstractProdIterator} <: AbstractProdIterator - a::I1 - b::I2 -end -product(a, b, c...) = Prod(a, product(b, c...)) - -eltype(::Type{Prod{I1,I2}}) where {I1,I2} = tuple_type_cons(eltype(I1), eltype(I2)) - -iteratoreltype(::Type{Prod{I1,I2}}) where {I1,I2} = and_iteratoreltype(iteratoreltype(I1),iteratoreltype(I2)) -iteratorsize(::Type{Prod{I1,I2}}) where {I1,I2} = prod_iteratorsize(iteratorsize(I1),iteratorsize(I2)) - -@inline function next{I1,I2}(p::Prod{I1,I2}, st) - x = prod_next(p, st) - ((x[1][1],x[1][2]...), x[2]) -end - -prod_iteratorsize(::Union{HasLength,HasShape}, ::Union{HasLength,HasShape}) = HasShape() -# products can have an infinite iterator -prod_iteratorsize(::IsInfinite, ::IsInfinite) = IsInfinite() -prod_iteratorsize(a, ::IsInfinite) = IsInfinite() -prod_iteratorsize(::IsInfinite, b) = IsInfinite() -prod_iteratorsize(a, b) = SizeUnknown() - - -# flatten an iterator of iterators - -struct Flatten{I} - it::I -end - -""" - flatten(iter) - -Given an iterator that yields iterators, return an iterator that yields the -elements of those iterators. -Put differently, the elements of the argument iterator are concatenated. - -# Example - -```jldoctest -julia> collect(Iterators.flatten((1:2, 8:9))) -4-element Array{Int64,1}: - 1 - 2 - 8 - 9 -``` -""" -flatten(itr) = Flatten(itr) - -eltype(::Type{Flatten{I}}) where {I} = eltype(eltype(I)) -iteratorsize(::Type{Flatten{I}}) where {I} = SizeUnknown() -iteratoreltype(::Type{Flatten{I}}) where {I} = _flatteneltype(I, iteratoreltype(I)) -_flatteneltype(I, ::HasEltype) = iteratoreltype(eltype(I)) -_flatteneltype(I, et) = EltypeUnknown() - -function start(f::Flatten) - local inner, s2 - s = start(f.it) - d = done(f.it, s) - # this is a simple way to make this function type stable - d && throw(ArgumentError("argument to Flatten must contain at least one iterator")) - while !d - inner, s = next(f.it, s) - s2 = start(inner) - !done(inner, s2) && break - d = done(f.it, s) - end - return s, inner, s2 -end - -@inline function next(f::Flatten, state) - s, inner, s2 = state - val, s2 = next(inner, s2) - while done(inner, s2) && !done(f.it, s) - inner, s = next(f.it, s) - s2 = start(inner) - end - return val, (s, inner, s2) -end - -@inline function done(f::Flatten, state) - s, inner, s2 = state - return done(f.it, s) && done(inner, s2) -end - - -""" - partition(collection, n) - -Iterate over a collection `n` elements at a time. - -# Example - -```jldoctest -julia> collect(Iterators.partition([1,2,3,4,5], 2)) -3-element Array{Array{Int64,1},1}: - [1, 2] - [3, 4] - [5] -``` -""" -partition(c::T, n::Integer) where {T} = PartitionIterator{T}(c, Int(n)) - - -mutable struct PartitionIterator{T} - c::T - n::Int -end - -eltype(::Type{PartitionIterator{T}}) where {T} = Vector{eltype(T)} - -function length(itr::PartitionIterator) - l = length(itr.c) - return div(l, itr.n) + ((mod(l, itr.n) > 0) ? 1 : 0) -end - -start(itr::PartitionIterator) = start(itr.c) - -done(itr::PartitionIterator, state) = done(itr.c, state) - -function next(itr::PartitionIterator{<:Vector}, state) - l = state - r = min(state + itr.n-1, length(itr.c)) - return view(itr.c, l:r), r + 1 -end - -function next(itr::PartitionIterator, state) - v = Vector{eltype(itr.c)}(itr.n) - i = 0 - while !done(itr.c, state) && i < itr.n - i += 1 - v[i], state = next(itr.c, state) - end - return resize!(v, i), state -end - -end diff --git a/julia-0.6.3/share/julia/base/latex_symbols.jl b/julia-0.6.3/share/julia/base/latex_symbols.jl deleted file mode 100644 index 2a546b0..0000000 --- a/julia-0.6.3/share/julia/base/latex_symbols.jl +++ /dev/null @@ -1,2574 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -# Mapping from LaTeX math symbol to the corresponding Unicode codepoint. -# This is used for tab substitution in the REPL. - -# The initial symbol listing was generated from the W3C symbol mapping file: -# http://www.w3.org/Math/characters/unicode.xml -# by the following Julia script: -#= -using LightXML -xdoc = parse_file("unicode.xml") -latexsym = [] -Ls = Set() -for c in child_nodes(root(xdoc)) - if name(c) == "character" && is_elementnode(c) - ce = XMLElement(c) - latex = nothing - for el in ("AMS", "IEEE", "mathlatex", "latex") - latex = find_element(ce, el) - latex !== nothing && break - end - if latex !== nothing - L = strip(content(latex)) - id = attribute(ce, "id") - U = string(map(s -> Char(parse(Int, s, 16)), - split(id[2:end], "-"))...) - if ismatch(r"^\\[A-Za-z]+$",L) && !isa(U,String) - if L in Ls - println("# duplicated symbol $L ($id)") - else - if U[1] == '\u22a5' # unicode.xml incorrectly uses \perp for \bot - L = "\\bot" - end - push!(latexsym, (L, U)) - push!(Ls, L) - end - end - end - end -end -println("# ", length(latexsym), " symbols generated from unicode.xml") -for (L, U) in latexsym - println(" \"$(escape_string(L))\" => \"$(escape_string(U))\",") -end -=# - -# Additional symbols were generated from the unicode-math LaTeX package -# symbol listing, using the following script: -#= -fname = "unicode-math-table.tex" -isfile(fname) || download("http://mirror.math.ku.edu/tex-archive/macros/latex/contrib/unicode-math/$fname", fname) -const latex_strings = Set(values(Base.REPLCompletions.latex_symbols)) -open(fname) do f - for L in eachline(f) - x = map(s -> rstrip(s, [' ','\t','\n']), - split(replace(L, r"[{}\"]+", "\t"), "\t")) - c = Char(parse(Int, x[2], 16)) - if (Base.is_id_char(c) || Base.isoperator(Symbol(c))) && - string(c) ∉ latex_strings && !isascii(c) - tabcomname = escape_string(x[3]) - if startswith(tabcomname, "\\\\math") - tabcomname = string("\\\\", tabcomname[7:end]) - end - println(" \"", tabcomname, "\" => \"", - escape_string("$c"), "\", # ", x[5]) - end - end -end -=# - -# Finally, we also add some symbols manually (at the top) as needed. - -const latex_symbols = Dict( - -# manual additions: - - "\\sqrt" => "\u221A", - "\\cbrt" => "\u221B", - "\\female" => "♀", - "\\mars" => "♂", - "\\pprime" => "″", - "\\ppprime" => "‴", - "\\pppprime" => "⁗", - "\\backpprime" => "‶", - "\\backppprime" => "‷", - "\\xor" => "⊻", - "\\iff" => "⟺", - "\\implies" => "⟹", - "\\impliedby" => "⟸", - "\\to" => "→", - - # Superscripts - "\\^0" => "⁰", - "\\^1" => "¹", - "\\^2" => "²", - "\\^3" => "³", - "\\^4" => "⁴", - "\\^5" => "⁵", - "\\^6" => "⁶", - "\\^7" => "⁷", - "\\^8" => "⁸", - "\\^9" => "⁹", - "\\^+" => "⁺", - "\\^-" => "⁻", - "\\^=" => "⁼", - "\\^(" => "⁽", - "\\^)" => "⁾", - "\\^a" => "ᵃ", - "\\^b" => "ᵇ", - "\\^c" => "ᶜ", - "\\^d" => "ᵈ", - "\\^e" => "ᵉ", - "\\^f" => "ᶠ", - "\\^g" => "ᵍ", - "\\^h" => "ʰ", - "\\^i" => "ⁱ", - "\\^j" => "ʲ", - "\\^k" => "ᵏ", - "\\^l" => "ˡ", - "\\^m" => "ᵐ", - "\\^n" => "ⁿ", - "\\^o" => "ᵒ", - "\\^p" => "ᵖ", - "\\^r" => "ʳ", - "\\^s" => "ˢ", - "\\^t" => "ᵗ", - "\\^u" => "ᵘ", - "\\^v" => "ᵛ", - "\\^w" => "ʷ", - "\\^x" => "ˣ", - "\\^y" => "ʸ", - "\\^z" => "ᶻ", - "\\^A" => "ᴬ", - "\\^B" => "ᴮ", - "\\^D" => "ᴰ", - "\\^E" => "ᴱ", - "\\^G" => "ᴳ", - "\\^H" => "ᴴ", - "\\^I" => "ᴵ", - "\\^J" => "ᴶ", - "\\^K" => "ᴷ", - "\\^L" => "ᴸ", - "\\^M" => "ᴹ", - "\\^N" => "ᴺ", - "\\^O" => "ᴼ", - "\\^P" => "ᴾ", - "\\^R" => "ᴿ", - "\\^T" => "ᵀ", - "\\^U" => "ᵁ", - "\\^V" => "ⱽ", - "\\^W" => "ᵂ", - "\\^alpha" => "ᵅ", - "\\^beta" => "ᵝ", - "\\^gamma" => "ᵞ", - "\\^delta" => "ᵟ", - "\\^epsilon" => "ᵋ", - "\\^theta" => "ᶿ", - "\\^iota" => "ᶥ", - "\\^phi" => "ᵠ", - "\\^chi" => "ᵡ", - "\\^Phi" => "ᶲ", - - # Subscripts - "\\_0" => "₀", - "\\_1" => "₁", - "\\_2" => "₂", - "\\_3" => "₃", - "\\_4" => "₄", - "\\_5" => "₅", - "\\_6" => "₆", - "\\_7" => "₇", - "\\_8" => "₈", - "\\_9" => "₉", - "\\_+" => "₊", - "\\_-" => "₋", - "\\_=" => "₌", - "\\_(" => "₍", - "\\_)" => "₎", - "\\_a" => "ₐ", - "\\_e" => "ₑ", - "\\_h" => "ₕ", - "\\_i" => "ᵢ", - "\\_j" => "ⱼ", - "\\_k" => "ₖ", - "\\_l" => "ₗ", - "\\_m" => "ₘ", - "\\_n" => "ₙ", - "\\_o" => "ₒ", - "\\_p" => "ₚ", - "\\_r" => "ᵣ", - "\\_s" => "ₛ", - "\\_t" => "ₜ", - "\\_u" => "ᵤ", - "\\_v" => "ᵥ", - "\\_x" => "ₓ", - "\\_schwa" => "ₔ", - "\\_beta" => "ᵦ", - "\\_gamma" => "ᵧ", - "\\_rho" => "ᵨ", - "\\_phi" => "ᵩ", - "\\_chi" => "ᵪ", - - # Misc. Math and Physics - "\\ldots" => "…", - "\\hbar" => "ħ", - "\\del" => "∇", - - "\\sout" => "̶",# ulem package, same as Elzbar - "\\euro" => "€", - -# 732 symbols generated from unicode.xml - "\\textexclamdown" => "¡", - "\\sterling" => "£", - "\\yen" => "¥", - "\\textbrokenbar" => "¦", - "\\S" => "§", - "\\textasciidieresis" => "¨", - "\\copyright" => "©", - "\\textordfeminine" => "ª", - "\\neg" => "¬", - "\\circledR" => "®", - "\\textasciimacron" => "¯", - "\\degree" => "°", - "\\pm" => "±", - "\\textasciiacute" => "´", - "\\P" => "¶", - "\\cdotp" => "·", - "\\textordmasculine" => "º", - "\\textonequarter" => "¼", - "\\textonehalf" => "½", - "\\textthreequarters" => "¾", - "\\textquestiondown" => "¿", - "\\AA" => "Å", - "\\AE" => "Æ", - "\\DH" => "Ð", - "\\times" => "×", - "\\O" => "Ø", - "\\TH" => "Þ", - "\\ss" => "ß", - "\\aa" => "å", - "\\ae" => "æ", - "\\eth" => "ð", - "\\div" => "÷", - "\\o" => "ø", - "\\th" => "þ", - "\\DJ" => "Đ", - "\\dj" => "đ", - "\\Elzxh" => "ħ", - "\\imath" => "ı", - "\\L" => "Ł", - "\\l" => "ł", - "\\NG" => "Ŋ", - "\\ng" => "ŋ", - "\\OE" => "Œ", - "\\oe" => "œ", - "\\texthvlig" => "ƕ", - "\\textnrleg" => "ƞ", - "\\textdoublepipe" => "ǂ", - "\\Elztrna" => "ɐ", - "\\Elztrnsa" => "ɒ", - "\\Elzopeno" => "ɔ", - "\\Elzrtld" => "ɖ", - "\\Elzschwa" => "ə", - "\\varepsilon" => "ε", - "\\Elzpgamma" => "ɣ", - "\\Elzpbgam" => "ɤ", - "\\Elztrnh" => "ɥ", - "\\Elzbtdl" => "ɬ", - "\\Elzrtll" => "ɭ", - "\\Elztrnm" => "ɯ", - "\\Elztrnmlr" => "ɰ", - "\\Elzltlmr" => "ɱ", - "\\Elzltln" => "ɲ", - "\\Elzrtln" => "ɳ", - "\\Elzclomeg" => "ɷ", - "\\textphi" => "ɸ", - "\\Elztrnr" => "ɹ", - "\\Elztrnrl" => "ɺ", - "\\Elzrttrnr" => "ɻ", - "\\Elzrl" => "ɼ", - "\\Elzrtlr" => "ɽ", - "\\Elzfhr" => "ɾ", - "\\Elzrtls" => "ʂ", - "\\Elzesh" => "ʃ", - "\\Elztrnt" => "ʇ", - "\\Elzrtlt" => "ʈ", - "\\Elzpupsil" => "ʊ", - "\\Elzpscrv" => "ʋ", - "\\Elzinvv" => "ʌ", - "\\Elzinvw" => "ʍ", - "\\Elztrny" => "ʎ", - "\\Elzrtlz" => "ʐ", - "\\Elzyogh" => "ʒ", - "\\Elzglst" => "ʔ", - "\\Elzreglst" => "ʕ", - "\\Elzinglst" => "ʖ", - "\\textturnk" => "ʞ", - "\\Elzdyogh" => "ʤ", - "\\Elztesh" => "ʧ", - "\\rasp" => "ʼ", - "\\textasciicaron" => "ˇ", - "\\Elzverts" => "ˈ", - "\\Elzverti" => "ˌ", - "\\Elzlmrk" => "ː", - "\\Elzhlmrk" => "ˑ", - "\\Elzsbrhr" => "˒", - "\\Elzsblhr" => "˓", - "\\Elzrais" => "˔", - "\\Elzlow" => "˕", - "\\u" => "˘", - "\\texttildelow" => "˜", - "\\grave" => "̀", - "\\acute" => "́", - "\\hat" => "̂", - "\\tilde" => "̃", - "\\bar" => "̄", - "\\breve" => "̆", - "\\dot" => "̇", - "\\ddot" => "̈", - "\\ocirc" => "̊", - "\\H" => "̋", - "\\check" => "̌", - "\\Elzpalh" => "̡", - "\\Elzrh" => "̢", - "\\c" => "̧", - "\\k" => "̨", - "\\Elzsbbrg" => "̪", - "\\Elzxl" => "̵", - "\\Elzbar" => "̶", - "\\Alpha" => "Α", - "\\Beta" => "Β", - "\\Gamma" => "Γ", - "\\Delta" => "Δ", - "\\Epsilon" => "Ε", - "\\Zeta" => "Ζ", - "\\Eta" => "Η", - "\\Theta" => "Θ", - "\\Iota" => "Ι", - "\\Kappa" => "Κ", - "\\Lambda" => "Λ", - "\\Xi" => "Ξ", - "\\Pi" => "Π", - "\\Rho" => "Ρ", - "\\Sigma" => "Σ", - "\\Tau" => "Τ", - "\\Upsilon" => "Υ", - "\\Phi" => "Φ", - "\\Chi" => "Χ", - "\\Psi" => "Ψ", - "\\Omega" => "Ω", - "\\alpha" => "α", - "\\beta" => "β", - "\\gamma" => "γ", - "\\delta" => "δ", - "\\zeta" => "ζ", - "\\eta" => "η", - "\\theta" => "θ", - "\\iota" => "ι", - "\\kappa" => "κ", - "\\lambda" => "λ", - "\\mu" => "μ", - "\\nu" => "ν", - "\\xi" => "ξ", - "\\pi" => "π", - "\\rho" => "ρ", - "\\varsigma" => "ς", - "\\sigma" => "σ", - "\\tau" => "τ", - "\\upsilon" => "υ", - "\\varphi" => "φ", - "\\chi" => "χ", - "\\psi" => "ψ", - "\\omega" => "ω", - "\\vartheta" => "ϑ", - "\\phi" => "ϕ", - "\\varpi" => "ϖ", - "\\Stigma" => "Ϛ", - "\\Digamma" => "Ϝ", - "\\digamma" => "ϝ", - "\\Koppa" => "Ϟ", - "\\Sampi" => "Ϡ", - "\\varkappa" => "ϰ", - "\\varrho" => "ϱ", - "\\textTheta" => "ϴ", - "\\epsilon" => "ϵ", - "\\backepsilon" => "϶", - "\\enspace" => " ", - "\\quad" => " ", - "\\thickspace" => " ", - "\\thinspace" => " ", - "\\hspace" => " ", - "\\endash" => "–", - "\\emdash" => "—", - "\\Vert" => "‖", - "\\lq" => "‘", - "\\rq" => "’", - "\\Elzreapos" => "‛", - "\\textquotedblleft" => "“", - "\\textquotedblright" => "”", - "\\dagger" => "†", - "\\ddagger" => "‡", - "\\bullet" => "•", - "\\dots" => "…", - "\\textperthousand" => "‰", - "\\textpertenthousand" => "‱", - "\\prime" => "′", - "\\backprime" => "‵", - "\\guilsinglleft" => "‹", - "\\guilsinglright" => "›", - "\\nolinebreak" => "\u2060", - "\\Elzpes" => "₧", - "\\dddot" => "⃛", - "\\ddddot" => "⃜", - "\\hslash" => "ℏ", - "\\Im" => "ℑ", - "\\ell" => "ℓ", - "\\textnumero" => "№", - "\\wp" => "℘", - "\\Re" => "ℜ", - "\\Elzxrat" => "℞", - "\\texttrademark" => "™", - "\\mho" => "℧", - "\\aleph" => "ℵ", - "\\beth" => "ℶ", - "\\gimel" => "ℷ", - "\\daleth" => "ℸ", - "\\BbbPi" => "ℿ", - "\\bbsum" => "⅀", - "\\Game" => "⅁", - "\\leftarrow" => "←", - "\\uparrow" => "↑", - "\\rightarrow" => "→", - "\\downarrow" => "↓", - "\\leftrightarrow" => "↔", - "\\updownarrow" => "↕", - "\\nwarrow" => "↖", - "\\nearrow" => "↗", - "\\searrow" => "↘", - "\\swarrow" => "↙", - "\\nleftarrow" => "↚", - "\\nrightarrow" => "↛", - "\\leftsquigarrow" => "↜", - "\\rightsquigarrow" => "↝", - "\\twoheadleftarrow" => "↞", - "\\twoheadrightarrow" => "↠", - "\\leftarrowtail" => "↢", - "\\rightarrowtail" => "↣", - "\\mapsto" => "↦", - "\\hookleftarrow" => "↩", - "\\hookrightarrow" => "↪", - "\\looparrowleft" => "↫", - "\\looparrowright" => "↬", - "\\leftrightsquigarrow" => "↭", - "\\nleftrightarrow" => "↮", - "\\Lsh" => "↰", - "\\Rsh" => "↱", - "\\curvearrowleft" => "↶", - "\\curvearrowright" => "↷", - "\\circlearrowleft" => "↺", - "\\circlearrowright" => "↻", - "\\leftharpoonup" => "↼", - "\\leftharpoondown" => "↽", - "\\upharpoonleft" => "↾", - "\\upharpoonright" => "↿", - "\\rightharpoonup" => "⇀", - "\\rightharpoondown" => "⇁", - "\\downharpoonright" => "⇂", - "\\downharpoonleft" => "⇃", - "\\rightleftarrows" => "⇄", - "\\dblarrowupdown" => "⇅", - "\\leftrightarrows" => "⇆", - "\\leftleftarrows" => "⇇", - "\\upuparrows" => "⇈", - "\\rightrightarrows" => "⇉", - "\\downdownarrows" => "⇊", - "\\leftrightharpoons" => "⇋", - "\\rightleftharpoons" => "⇌", - "\\nLeftarrow" => "⇍", - "\\nRightarrow" => "⇏", - "\\Leftarrow" => "⇐", - "\\Uparrow" => "⇑", - "\\Rightarrow" => "⇒", - "\\Downarrow" => "⇓", - "\\Leftrightarrow" => "⇔", - "\\Updownarrow" => "⇕", - "\\Lleftarrow" => "⇚", - "\\Rrightarrow" => "⇛", - "\\DownArrowUpArrow" => "⇵", - "\\leftarrowtriangle" => "⇽", - "\\rightarrowtriangle" => "⇾", - "\\forall" => "∀", - "\\complement" => "∁", - "\\partial" => "∂", - "\\exists" => "∃", - "\\nexists" => "∄", - "\\varnothing" => "∅", - "\\emptyset" => "∅", - "\\nabla" => "∇", - "\\in" => "∈", - "\\notin" => "∉", - "\\ni" => "∋", - "\\prod" => "∏", - "\\coprod" => "∐", - "\\sum" => "∑", - "\\minus" => "−", - "\\mp" => "∓", - "\\dotplus" => "∔", - "\\setminus" => "∖", - "\\ast" => "∗", - "\\circ" => "∘", - "\\surd" => "√", - "\\propto" => "∝", - "\\infty" => "∞", - "\\rightangle" => "∟", - "\\angle" => "∠", - "\\measuredangle" => "∡", - "\\sphericalangle" => "∢", - "\\mid" => "∣", - "\\nmid" => "∤", - "\\parallel" => "∥", - "\\nparallel" => "∦", - "\\wedge" => "∧", - "\\vee" => "∨", - "\\cap" => "∩", - "\\cup" => "∪", - "\\int" => "∫", - "\\iint" => "∬", - "\\iiint" => "∭", - "\\oint" => "∮", - "\\oiint" => "∯", - "\\oiiint" => "∰", - "\\clwintegral" => "∱", - "\\therefore" => "∴", - "\\because" => "∵", - "\\Colon" => "∷", - "\\dotminus" => "∸", - "\\kernelcontraction" => "∻", - "\\sim" => "∼", - "\\backsim" => "∽", - "\\lazysinv" => "∾", - "\\wr" => "≀", - "\\nsim" => "≁", - "\\eqsim" => "≂", - "\\neqsim" => "≂̸", - "\\simeq" => "≃", - "\\nsime" => "≄", - "\\cong" => "≅", - "\\approxnotequal" => "≆", - "\\ncong" => "≇", - "\\approx" => "≈", - "\\napprox" => "≉", - "\\approxeq" => "≊", - "\\tildetrpl" => "≋", - "\\allequal" => "≌", - "\\asymp" => "≍", - "\\Bumpeq" => "≎", - "\\nBumpeq" => "≎̸", - "\\bumpeq" => "≏", - "\\nbumpeq" => "≏̸", - "\\doteq" => "≐", - "\\Doteq" => "≑", - "\\fallingdotseq" => "≒", - "\\risingdotseq" => "≓", - "\\coloneq" => "≔", - "\\eqcolon" => "≕", - "\\eqcirc" => "≖", - "\\circeq" => "≗", - "\\wedgeq" => "≙", - "\\starequal" => "≛", - "\\triangleq" => "≜", - "\\questeq" => "≟", - "\\ne" => "≠", - "\\equiv" => "≡", - "\\nequiv" => "≢", - "\\le" => "≤", - "\\ge" => "≥", - "\\leqq" => "≦", - "\\geqq" => "≧", - "\\lneqq" => "≨", - "\\lvertneqq" => "≨︀", - "\\gneqq" => "≩", - "\\gvertneqq" => "≩︀", - "\\ll" => "≪", - "\\NotLessLess" => "≪̸", - "\\gg" => "≫", - "\\NotGreaterGreater" => "≫̸", - "\\between" => "≬", - "\\nless" => "≮", - "\\ngtr" => "≯", - "\\nleq" => "≰", - "\\ngeq" => "≱", - "\\lesssim" => "≲", - "\\gtrsim" => "≳", - "\\lessgtr" => "≶", - "\\gtrless" => "≷", - "\\notlessgreater" => "≸", - "\\notgreaterless" => "≹", - "\\prec" => "≺", - "\\succ" => "≻", - "\\preccurlyeq" => "≼", - "\\succcurlyeq" => "≽", - "\\precsim" => "≾", - "\\nprecsim" => "≾̸", - "\\succsim" => "≿", - "\\nsuccsim" => "≿̸", - "\\nprec" => "⊀", - "\\nsucc" => "⊁", - "\\subset" => "⊂", - "\\supset" => "⊃", - "\\nsubset" => "⊄", - "\\nsupset" => "⊅", - "\\subseteq" => "⊆", - "\\supseteq" => "⊇", - "\\nsubseteq" => "⊈", - "\\nsupseteq" => "⊉", - "\\subsetneq" => "⊊", - "\\varsubsetneqq" => "⊊︀", - "\\supsetneq" => "⊋", - "\\varsupsetneq" => "⊋︀", - "\\cupdot" => "⊍", - "\\uplus" => "⊎", - "\\sqsubset" => "⊏", - "\\NotSquareSubset" => "⊏̸", - "\\sqsupset" => "⊐", - "\\NotSquareSuperset" => "⊐̸", - "\\sqsubseteq" => "⊑", - "\\sqsupseteq" => "⊒", - "\\sqcap" => "⊓", - "\\sqcup" => "⊔", - "\\oplus" => "⊕", - "\\ominus" => "⊖", - "\\otimes" => "⊗", - "\\oslash" => "⊘", - "\\odot" => "⊙", - "\\circledcirc" => "⊚", - "\\circledast" => "⊛", - "\\circleddash" => "⊝", - "\\boxplus" => "⊞", - "\\boxminus" => "⊟", - "\\boxtimes" => "⊠", - "\\boxdot" => "⊡", - "\\vdash" => "⊢", - "\\dashv" => "⊣", - "\\top" => "⊤", - "\\bot" => "⊥", - "\\models" => "⊧", - "\\vDash" => "⊨", - "\\Vdash" => "⊩", - "\\Vvdash" => "⊪", - "\\VDash" => "⊫", - "\\nvdash" => "⊬", - "\\nvDash" => "⊭", - "\\nVdash" => "⊮", - "\\nVDash" => "⊯", - "\\vartriangleleft" => "⊲", - "\\vartriangleright" => "⊳", - "\\trianglelefteq" => "⊴", - "\\trianglerighteq" => "⊵", - "\\original" => "⊶", - "\\image" => "⊷", - "\\multimap" => "⊸", - "\\hermitconjmatrix" => "⊹", - "\\intercal" => "⊺", - "\\veebar" => "⊻", - "\\rightanglearc" => "⊾", - "\\bigwedge" => "⋀", - "\\bigvee" => "⋁", - "\\bigcap" => "⋂", - "\\bigcup" => "⋃", - "\\diamond" => "⋄", - "\\cdot" => "⋅", - "\\star" => "⋆", - "\\divideontimes" => "⋇", - "\\bowtie" => "⋈", - "\\ltimes" => "⋉", - "\\rtimes" => "⋊", - "\\leftthreetimes" => "⋋", - "\\rightthreetimes" => "⋌", - "\\backsimeq" => "⋍", - "\\curlyvee" => "⋎", - "\\curlywedge" => "⋏", - "\\Subset" => "⋐", - "\\Supset" => "⋑", - "\\Cap" => "⋒", - "\\Cup" => "⋓", - "\\pitchfork" => "⋔", - "\\lessdot" => "⋖", - "\\gtrdot" => "⋗", - "\\verymuchless" => "⋘", - "\\ggg" => "⋙", - "\\lesseqgtr" => "⋚", - "\\gtreqless" => "⋛", - "\\curlyeqprec" => "⋞", - "\\curlyeqsucc" => "⋟", - "\\Elzsqspne" => "⋥", - "\\lnsim" => "⋦", - "\\gnsim" => "⋧", - "\\precnsim" => "⋨", - "\\succnsim" => "⋩", - "\\ntriangleleft" => "⋪", - "\\ntriangleright" => "⋫", - "\\ntrianglelefteq" => "⋬", - "\\ntrianglerighteq" => "⋭", - "\\vdots" => "⋮", - "\\cdots" => "⋯", - "\\adots" => "⋰", - "\\ddots" => "⋱", - "\\barwedge" => "⌅", - "\\lceil" => "⌈", - "\\rceil" => "⌉", - "\\lfloor" => "⌊", - "\\rfloor" => "⌋", - "\\recorder" => "⌕", - "\\ulcorner" => "⌜", - "\\urcorner" => "⌝", - "\\llcorner" => "⌞", - "\\lrcorner" => "⌟", - "\\frown" => "⌢", - "\\smile" => "⌣", - "\\langle" => "⟨", - "\\rangle" => "⟩", - "\\obar" => "⌽", - "\\Elzdlcorn" => "⎣", - "\\lmoustache" => "⎰", - "\\rmoustache" => "⎱", - "\\textvisiblespace" => "␣", - "\\circledS" => "Ⓢ", - "\\Elzdshfnc" => "┆", - "\\Elzsqfnw" => "┙", - "\\diagup" => "╱", - "\\diagdown" => "╲", - "\\blacksquare" => "■", - "\\square" => "□", - "\\Elzvrecto" => "▯", - "\\bigtriangleup" => "△", - "\\blacktriangle" => "▴", - "\\vartriangle" => "▵", - "\\blacktriangleright" => "▸", - "\\triangleright" => "▹", - "\\bigtriangledown" => "▽", - "\\blacktriangledown" => "▾", - "\\triangledown" => "▿", - "\\blacktriangleleft" => "◂", - "\\triangleleft" => "◃", - "\\lozenge" => "◊", - "\\bigcirc" => "○", - "\\Elzcirfl" => "◐", - "\\Elzcirfr" => "◑", - "\\Elzcirfb" => "◒", - "\\Elzrvbull" => "◘", - "\\Elzsqfl" => "◧", - "\\Elzsqfr" => "◨", - "\\Elzsqfse" => "◪", - "\\bigstar" => "★", - "\\rightmoon" => "☾", - "\\mercury" => "☿", - "\\venus" => "♀", - "\\male" => "♂", - "\\jupiter" => "♃", - "\\saturn" => "♄", - "\\uranus" => "♅", - "\\neptune" => "♆", - "\\pluto" => "♇", - "\\aries" => "♈", - "\\taurus" => "♉", - "\\gemini" => "♊", - "\\cancer" => "♋", - "\\leo" => "♌", - "\\virgo" => "♍", - "\\libra" => "♎", - "\\scorpio" => "♏", - "\\sagittarius" => "♐", - "\\capricornus" => "♑", - "\\aquarius" => "♒", - "\\pisces" => "♓", - "\\spadesuit" => "♠", - "\\heartsuit" => "♡", - "\\diamondsuit" => "♢", - "\\clubsuit" => "♣", - "\\quarternote" => "♩", - "\\eighthnote" => "♪", - "\\flat" => "♭", - "\\natural" => "♮", - "\\sharp" => "♯", - "\\checkmark" => "✓", - "\\maltese" => "✠", - "\\longleftarrow" => "⟵", - "\\longrightarrow" => "⟶", - "\\longleftrightarrow" => "⟷", - "\\Longleftarrow" => "⟸", - "\\Longrightarrow" => "⟹", - "\\Longleftrightarrow" => "⟺", - "\\longmapsto" => "⟼", - "\\Mapsfrom" => "⤆", - "\\Mapsto" => "⤇", - "\\Uuparrow" => "⤊", - "\\Ddownarrow" => "⤋", - "\\bkarow" => "⤍", - "\\dbkarow" => "⤏", - "\\drbkarrow" => "⤐", - "\\UpArrowBar" => "⤒", - "\\DownArrowBar" => "⤓", - "\\twoheadrightarrowtail" => "⤖", - "\\hksearow" => "⤥", - "\\hkswarow" => "⤦", - "\\tona" => "⤧", - "\\toea" => "⤨", - "\\tosa" => "⤩", - "\\towa" => "⤪", - "\\rdiagovfdiag" => "⤫", - "\\fdiagovrdiag" => "⤬", - "\\seovnearrow" => "⤭", - "\\neovsearrow" => "⤮", - "\\fdiagovnearrow" => "⤯", - "\\rdiagovsearrow" => "⤰", - "\\neovnwarrow" => "⤱", - "\\nwovnearrow" => "⤲", - "\\ElzRlarr" => "⥂", - "\\ElzrLarr" => "⥄", - "\\Elzrarrx" => "⥇", - "\\LeftRightVector" => "⥎", - "\\RightUpDownVector" => "⥏", - "\\DownLeftRightVector" => "⥐", - "\\LeftUpDownVector" => "⥑", - "\\LeftVectorBar" => "⥒", - "\\RightVectorBar" => "⥓", - "\\RightUpVectorBar" => "⥔", - "\\RightDownVectorBar" => "⥕", - "\\DownLeftVectorBar" => "⥖", - "\\DownRightVectorBar" => "⥗", - "\\LeftUpVectorBar" => "⥘", - "\\LeftDownVectorBar" => "⥙", - "\\LeftTeeVector" => "⥚", - "\\RightTeeVector" => "⥛", - "\\RightUpTeeVector" => "⥜", - "\\RightDownTeeVector" => "⥝", - "\\DownLeftTeeVector" => "⥞", - "\\DownRightTeeVector" => "⥟", - "\\LeftUpTeeVector" => "⥠", - "\\LeftDownTeeVector" => "⥡", - "\\UpEquilibrium" => "⥮", - "\\ReverseUpEquilibrium" => "⥯", - "\\RoundImplies" => "⥰", - "\\Vvert" => "⦀", - "\\Elroang" => "⦆", - "\\Elzddfnc" => "⦙", - "\\Angle" => "⦜", - "\\Elzlpargt" => "⦠", - "\\obslash" => "⦸", - "\\boxdiag" => "⧄", - "\\boxbslash" => "⧅", - "\\boxast" => "⧆", - "\\boxcircle" => "⧇", - "\\ElzLap" => "⧊", - "\\Elzdefas" => "⧋", - "\\LeftTriangleBar" => "⧏", - "\\NotLeftTriangleBar" => "⧏̸", - "\\RightTriangleBar" => "⧐", - "\\NotRightTriangleBar" => "⧐̸", - "\\dualmap" => "⧟", - "\\shuffle" => "⧢", - "\\blacklozenge" => "⧫", - "\\RuleDelayed" => "⧴", - "\\bigodot" => "⨀", - "\\bigoplus" => "⨁", - "\\bigotimes" => "⨂", - "\\bigcupdot" => "⨃", - "\\biguplus" => "⨄", - "\\bigsqcap" => "⨅", - "\\bigsqcup" => "⨆", - "\\conjquant" => "⨇", - "\\disjquant" => "⨈", - "\\bigtimes" => "⨉", - "\\iiiint" => "⨌", - "\\intbar" => "⨍", - "\\intBar" => "⨎", - "\\clockoint" => "⨏", - "\\sqrint" => "⨖", - "\\intx" => "⨘", - "\\intcap" => "⨙", - "\\intcup" => "⨚", - "\\upint" => "⨛", - "\\lowint" => "⨜", - "\\plusdot" => "⨥", - "\\minusdot" => "⨪", - "\\ElzTimes" => "⨯", - "\\btimes" => "⨲", - "\\intprod" => "⨼", - "\\intprodr" => "⨽", - "\\amalg" => "⨿", - "\\ElzAnd" => "⩓", - "\\ElzOr" => "⩔", - "\\ElOr" => "⩖", - "\\perspcorrespond" => "⩞", - "\\Elzminhat" => "⩟", - "\\Equal" => "⩵", - "\\ddotseq" => "⩷", - "\\leqslant" => "⩽", - "\\nleqslant" => "⩽̸", - "\\geqslant" => "⩾", - "\\ngeqslant" => "⩾̸", - "\\lessapprox" => "⪅", - "\\gtrapprox" => "⪆", - "\\lneq" => "⪇", - "\\gneq" => "⪈", - "\\lnapprox" => "⪉", - "\\gnapprox" => "⪊", - "\\lesseqqgtr" => "⪋", - "\\gtreqqless" => "⪌", - "\\eqslantless" => "⪕", - "\\eqslantgtr" => "⪖", - "\\NestedLessLess" => "⪡", - "\\NotNestedLessLess" => "⪡̸", - "\\NestedGreaterGreater" => "⪢", - "\\NotNestedGreaterGreater" => "⪢̸", - "\\partialmeetcontraction" => "⪣", - "\\bumpeqq" => "⪮", - "\\preceq" => "⪯", - "\\npreceq" => "⪯̸", - "\\succeq" => "⪰", - "\\nsucceq" => "⪰̸", - "\\precneqq" => "⪵", - "\\succneqq" => "⪶", - "\\precapprox" => "⪷", - "\\succapprox" => "⪸", - "\\precnapprox" => "⪹", - "\\succnapprox" => "⪺", - "\\subseteqq" => "⫅", - "\\nsubseteqq" => "⫅̸", - "\\supseteqq" => "⫆", - "\\nsupseteqq" => "⫆̸", - "\\subsetneqq" => "⫋", - "\\supsetneqq" => "⫌", - "\\mlcp" => "⫛", - "\\forks" => "⫝̸", - "\\forksnot" => "⫝", - "\\dashV" => "⫣", - "\\Dashv" => "⫤", - "\\interleave" => "⫴", - "\\Elztdcol" => "⫶", - "\\openbracketleft" => "⟦", - "\\llbracket" => "⟦", - "\\openbracketright" => "⟧", - "\\rrbracket" => "⟧", - "\\overbrace" => "⏞", - "\\underbrace" => "⏟", - -# 1607 symbols generated from unicode-math-table.tex: - "\\Zbar" => "Ƶ", # impedance (latin capital letter z with stroke) - "\\overbar" => "̅", # overbar embellishment - "\\ovhook" => "̉", # combining hook above - "\\candra" => "̐", # candrabindu (non-spacing) - "\\oturnedcomma" => "̒", # combining turned comma above - "\\ocommatopright" => "̕", # combining comma above right - "\\droang" => "̚", # left angle above (non-spacing) - "\\wideutilde" => "̰", # under tilde accent (multiple characters and non-spacing) - "\\underbar" => "̱", # combining macron below - "\\not" => "̸", # combining long solidus overlay - "\\upMu" => "Μ", # capital mu, greek - "\\upNu" => "Ν", # capital nu, greek - "\\upOmicron" => "Ο", # capital omicron, greek - "\\upepsilon" => "ε", # rounded small epsilon, greek - "\\upomicron" => "ο", # small omicron, greek - "\\upvarbeta" => "ϐ", # rounded small beta, greek - "\\upoldKoppa" => "Ϙ", # greek letter archaic koppa - "\\upoldkoppa" => "ϙ", # greek small letter archaic koppa - "\\upstigma" => "ϛ", # greek small letter stigma - "\\upkoppa" => "ϟ", # greek small letter koppa - "\\upsampi" => "ϡ", # greek small letter sampi - "\\tieconcat" => "⁀", # character tie, z notation sequence concatenation - "\\leftharpoonaccent" => "⃐", # combining left harpoon above - "\\rightharpoonaccent" => "⃑", # combining right harpoon above - "\\vertoverlay" => "⃒", # combining long vertical line overlay - "\\overleftarrow" => "⃖", # combining left arrow above - "\\vec" => "⃗", # combining right arrow above - "\\enclosecircle" => "⃝", # combining enclosing circle - "\\enclosesquare" => "⃞", # combining enclosing square - "\\enclosediamond" => "⃟", # combining enclosing diamond - "\\overleftrightarrow" => "⃡", # combining left right arrow above - "\\enclosetriangle" => "⃤", # combining enclosing upward pointing triangle - "\\annuity" => "⃧", # combining annuity symbol - "\\threeunderdot" => "⃨", # combining triple underdot - "\\widebridgeabove" => "⃩", # combining wide bridge above - "\\underrightharpoondown" => "\u20ec", # combining rightwards harpoon with barb downwards - "\\underleftharpoondown" => "\u20ed", # combining leftwards harpoon with barb downwards - "\\underleftarrow" => "\u20ee", # combining left arrow below - "\\underrightarrow" => "\u20ef", # combining right arrow below - "\\asteraccent" => "\u20f0", # combining asterisk above - "\\BbbC" => "ℂ", # /bbb c, open face c - "\\Eulerconst" => "ℇ", # euler constant - "\\mscrg" => "ℊ", # /scr g, script letter g - "\\mscrH" => "ℋ", # hamiltonian (script capital h) - "\\mfrakH" => "ℌ", # /frak h, upper case h - "\\BbbH" => "ℍ", # /bbb h, open face h - "\\Planckconst" => "ℎ", # planck constant - "\\mscrI" => "ℐ", # /scr i, script letter i - "\\mscrL" => "ℒ", # lagrangian (script capital l) - "\\BbbN" => "ℕ", # /bbb n, open face n - "\\BbbP" => "ℙ", # /bbb p, open face p - "\\BbbQ" => "ℚ", # /bbb q, open face q - "\\mscrR" => "ℛ", # /scr r, script letter r - "\\BbbR" => "ℝ", # /bbb r, open face r - "\\BbbZ" => "ℤ", # /bbb z, open face z - "\\mfrakZ" => "ℨ", # /frak z, upper case z - "\\turnediota" => "℩", # turned iota - "\\Angstrom" => "Å", # angstrom capital a, ring - "\\mscrB" => "ℬ", # bernoulli function (script capital b) - "\\mfrakC" => "ℭ", # black-letter capital c - "\\mscre" => "ℯ", # /scr e, script letter e - "\\mscrE" => "ℰ", # /scr e, script letter e - "\\mscrF" => "ℱ", # /scr f, script letter f - "\\Finv" => "Ⅎ", # turned capital f - "\\mscrM" => "ℳ", # physics m-matrix (script capital m) - "\\mscro" => "ℴ", # order of (script small o) - "\\Bbbpi" => "\u213c", # double-struck small pi - "\\Bbbgamma" => "ℽ", # double-struck small gamma - "\\BbbGamma" => "ℾ", # double-struck capital gamma - "\\sansLturned" => "⅂", # turned sans-serif capital l - "\\sansLmirrored" => "⅃", # reversed sans-serif capital l - "\\Yup" => "⅄", # turned sans-serif capital y - "\\mitBbbD" => "ⅅ", # double-struck italic capital d - "\\mitBbbd" => "ⅆ", # double-struck italic small d - "\\mitBbbe" => "ⅇ", # double-struck italic small e - "\\mitBbbi" => "ⅈ", # double-struck italic small i - "\\mitBbbj" => "ⅉ", # double-struck italic small j - "\\PropertyLine" => "⅊", # property line - "\\upand" => "⅋", # turned ampersand - "\\twoheaduparrow" => "↟", # up two-headed arrow - "\\twoheaddownarrow" => "↡", # down two-headed arrow - "\\mapsfrom" => "↤", # maps to, leftward - "\\mapsup" => "↥", # maps to, upward - "\\mapsdown" => "↧", # maps to, downward - "\\updownarrowbar" => "↨", # up down arrow with base (perpendicular) - "\\downzigzagarrow" => "↯", # downwards zigzag arrow - "\\Ldsh" => "↲", # left down angled arrow - "\\Rdsh" => "↳", # right down angled arrow - "\\linefeed" => "↴", # rightwards arrow with corner downwards - "\\carriagereturn" => "↵", # downwards arrow with corner leftward = carriage return - "\\barovernorthwestarrow" => "↸", # north west arrow to long bar - "\\barleftarrowrightarrowbar" => "↹", # leftwards arrow to bar over rightwards arrow to bar - "\\nLeftrightarrow" => "⇎", # not left and right double arrows - "\\Nwarrow" => "⇖", # nw pointing double arrow - "\\Nearrow" => "⇗", # ne pointing double arrow - "\\Searrow" => "⇘", # se pointing double arrow - "\\Swarrow" => "⇙", # sw pointing double arrow - "\\leftsquigarrow" => "⇜", # leftwards squiggle arrow - "\\rightsquigarrow" => "⇝", # rightwards squiggle arrow - "\\nHuparrow" => "⇞", # upwards arrow with double stroke - "\\nHdownarrow" => "⇟", # downwards arrow with double stroke - "\\leftdasharrow" => "⇠", # leftwards dashed arrow - "\\updasharrow" => "⇡", # upwards dashed arrow - "\\rightdasharrow" => "⇢", # rightwards dashed arrow - "\\downdasharrow" => "⇣", # downwards dashed arrow - "\\barleftarrow" => "⇤", # leftwards arrow to bar - "\\rightarrowbar" => "⇥", # rightwards arrow to bar - "\\leftwhitearrow" => "⇦", # leftwards white arrow - "\\upwhitearrow" => "⇧", # upwards white arrow - "\\rightwhitearrow" => "⇨", # rightwards white arrow - "\\downwhitearrow" => "⇩", # downwards white arrow - "\\whitearrowupfrombar" => "⇪", # upwards white arrow from bar - "\\circleonrightarrow" => "⇴", # right arrow with small circle - "\\rightthreearrows" => "⇶", # three rightwards arrows - "\\nvleftarrow" => "⇷", # leftwards arrow with vertical stroke - "\\nvrightarrow" => "⇸", # rightwards arrow with vertical stroke - "\\nvleftrightarrow" => "⇹", # left right arrow with vertical stroke - "\\nVleftarrow" => "⇺", # leftwards arrow with double vertical stroke - "\\nVrightarrow" => "⇻", # rightwards arrow with double vertical stroke - "\\nVleftrightarrow" => "⇼", # left right arrow with double vertical stroke - "\\leftrightarrowtriangle" => "⇿", # left right open-headed arrow - "\\increment" => "∆", # laplacian (delta; nabla\string^2) - "\\smallin" => "∊", # set membership (small set membership) - "\\nni" => "∌", # negated contains, variant - "\\smallni" => "∍", # /ni /owns r: contains (small contains as member) - "\\QED" => "∎", # end of proof - "\\vysmblkcircle" => "∙", # bullet operator - "\\fourthroot" => "∜", # fourth root - "\\varointclockwise" => "∲", # contour integral, clockwise - "\\ointctrclockwise" => "∳", # contour integral, anticlockwise - "\\dotsminusdots" => "∺", # minus with four dots, geometric properties - "\\sinewave" => "∿", # sine wave - "\\arceq" => "≘", # arc, equals; corresponds to - "\\veeeq" => "≚", # logical or, equals - "\\eqdef" => "≝", # equals by definition - "\\measeq" => "≞", # measured by (m over equals) - "\\Equiv" => "≣", # strict equivalence (4 lines) - "\\nasymp" => "≭", # not asymptotically equal to - "\\nlesssim" => "≴", # not less, similar - "\\ngtrsim" => "≵", # not greater, similar - "\\circledequal" => "⊜", # equal in circle - "\\prurel" => "⊰", # element precedes under relation - "\\scurel" => "⊱", # succeeds under relation - "\\barwedge" => "⊼", # bar, wedge (large wedge) - "\\barvee" => "⊽", # bar, vee (large vee) - "\\varlrtriangle" => "⊿", # right triangle - "\\equalparallel" => "⋕", # parallel, equal; equal or parallel - "\\eqless" => "⋜", # equal-or-less - "\\eqgtr" => "⋝", # equal-or-greater - "\\npreccurlyeq" => "⋠", # not precedes, curly equals - "\\nsucccurlyeq" => "⋡", # not succeeds, curly equals - "\\nsqsubseteq" => "⋢", # not, square subset, equals - "\\nsqsupseteq" => "⋣", # not, square superset, equals - "\\sqsubsetneq" => "⋤", # square subset, not equals - "\\disin" => "⋲", # element of with long horizontal stroke - "\\varisins" => "⋳", # element of with vertical bar at end of horizontal stroke - "\\isins" => "⋴", # small element of with vertical bar at end of horizontal stroke - "\\isindot" => "⋵", # element of with dot above - "\\varisinobar" => "⋶", # element of with overbar - "\\isinobar" => "⋷", # small element of with overbar - "\\isinvb" => "⋸", # element of with underbar - "\\isinE" => "⋹", # element of with two horizontal strokes - "\\nisd" => "⋺", # contains with long horizontal stroke - "\\varnis" => "⋻", # contains with vertical bar at end of horizontal stroke - "\\nis" => "⋼", # small contains with vertical bar at end of horizontal stroke - "\\varniobar" => "⋽", # contains with overbar - "\\niobar" => "⋾", # small contains with overbar - "\\bagmember" => "⋿", # z notation bag membership - "\\diameter" => "⌀", # diameter sign - "\\house" => "⌂", # house - "\\vardoublebarwedge" => "⌆", # /doublebarwedge b: logical and, double bar above [perspective (double bar over small wedge)] - "\\invnot" => "⌐", # reverse not - "\\sqlozenge" => "⌑", # square lozenge - "\\profline" => "⌒", # profile of a line - "\\profsurf" => "⌓", # profile of a surface - "\\viewdata" => "⌗", # viewdata square - "\\turnednot" => "⌙", # turned not sign - "\\varhexagonlrbonds" => "⌬", # six carbon ring, corner down, double bonds lower right etc - "\\conictaper" => "⌲", # conical taper - "\\topbot" => "⌶", # top and bottom - "\\APLnotslash" => "⌿", # solidus, bar through (apl functional symbol slash bar) - "\\APLnotbackslash" => "⍀", # apl functional symbol backslash bar - "\\APLboxupcaret" => "⍓", # boxed up caret - "\\APLboxquestion" => "⍰", # boxed question mark - "\\hexagon" => "⎔", # horizontal benzene ring [hexagon flat open] - "\\overbracket" => "⎴", # top square bracket - "\\underbracket" => "⎵", # bottom square bracket - "\\bbrktbrk" => "⎶", # bottom square bracket over top square bracket - "\\sqrtbottom" => "⎷", # radical symbol bottom - "\\lvboxline" => "⎸", # left vertical box line - "\\rvboxline" => "⎹", # right vertical box line - "\\varcarriagereturn" => "⏎", # return symbol - "\\trapezium" => "\u23e2", # white trapezium - "\\benzenr" => "\u23e3", # benzene ring with circle - "\\strns" => "\u23e4", # straightness - "\\fltns" => "\u23e5", # flatness - "\\accurrent" => "\u23e6", # ac current - "\\elinters" => "\u23e7", # electrical intersection - "\\blanksymbol" => "␢", # blank symbol - "\\blockuphalf" => "▀", # upper half block - "\\blocklowhalf" => "▄", # lower half block - "\\blockfull" => "█", # full block - "\\blocklefthalf" => "▌", # left half block - "\\blockrighthalf" => "▐", # right half block - "\\blockqtrshaded" => "░", # 25\% shaded block - "\\blockhalfshaded" => "▒", # 50\% shaded block - "\\blockthreeqtrshaded" => "▓", # 75\% shaded block - "\\squoval" => "▢", # white square with rounded corners - "\\blackinwhitesquare" => "▣", # white square containing black small square - "\\squarehfill" => "▤", # square, horizontal rule filled - "\\squarevfill" => "▥", # square, vertical rule filled - "\\squarehvfill" => "▦", # square with orthogonal crosshatch fill - "\\squarenwsefill" => "▧", # square, nw-to-se rule filled - "\\squareneswfill" => "▨", # square, ne-to-sw rule filled - "\\squarecrossfill" => "▩", # square with diagonal crosshatch fill - "\\smblksquare" => "▪", # /blacksquare - sq bullet, filled - "\\smwhtsquare" => "▫", # white small square - "\\hrectangleblack" => "▬", # black rectangle - "\\hrectangle" => "▭", # horizontal rectangle, open - "\\vrectangleblack" => "▮", # black vertical rectangle - "\\parallelogramblack" => "▰", # black parallelogram - "\\parallelogram" => "▱", # parallelogram, open - "\\bigblacktriangleup" => "▲", # 0x25b2 6 6d black up-pointing triangle - "\\blacktriangleright" => "▶", # (large) right triangle, filled - "\\blackpointerright" => "►", # black right-pointing pointer - "\\whitepointerright" => "▻", # white right-pointing pointer - "\\bigblacktriangledown" => "▼", # big down triangle, filled - "\\blacktriangleleft" => "◀", # (large) left triangle, filled - "\\blackpointerleft" => "◄", # black left-pointing pointer - "\\whitepointerleft" => "◅", # white left-pointing pointer - "\\mdlgblkdiamond" => "◆", # black diamond - "\\mdlgwhtdiamond" => "◇", # white diamond; diamond, open - "\\blackinwhitediamond" => "◈", # white diamond containing black small diamond - "\\fisheye" => "◉", # fisheye - "\\dottedcircle" => "◌", # dotted circle - "\\circlevertfill" => "◍", # circle with vertical fill - "\\bullseye" => "◎", # bullseye - "\\mdlgblkcircle" => "●", # circle, filled - "\\circletophalfblack" => "◓", # circle, filled top half - "\\circleurquadblack" => "◔", # circle with upper right quadrant black - "\\blackcircleulquadwhite" => "◕", # circle with all but upper left quadrant black - "\\blacklefthalfcircle" => "◖", # left half black circle - "\\blackrighthalfcircle" => "◗", # right half black circle - "\\inversewhitecircle" => "◙", # inverse white circle - "\\invwhiteupperhalfcircle" => "◚", # upper half inverse white circle - "\\invwhitelowerhalfcircle" => "◛", # lower half inverse white circle - "\\ularc" => "◜", # upper left quadrant circular arc - "\\urarc" => "◝", # upper right quadrant circular arc - "\\lrarc" => "◞", # lower right quadrant circular arc - "\\llarc" => "◟", # lower left quadrant circular arc - "\\topsemicircle" => "◠", # upper half circle - "\\botsemicircle" => "◡", # lower half circle - "\\lrblacktriangle" => "◢", # lower right triangle, filled - "\\llblacktriangle" => "◣", # lower left triangle, filled - "\\ulblacktriangle" => "◤", # upper left triangle, filled - "\\urblacktriangle" => "◥", # upper right triangle, filled - "\\smwhtcircle" => "◦", # white bullet - "\\squareulblack" => "◩", # square, filled top left corner - "\\boxbar" => "◫", # vertical bar in box - "\\trianglecdot" => "◬", # triangle with centered dot - "\\triangleleftblack" => "◭", # up-pointing triangle with left half black - "\\trianglerightblack" => "◮", # up-pointing triangle with right half black - "\\lgwhtcircle" => "◯", # large circle - "\\squareulquad" => "◰", # white square with upper left quadrant - "\\squarellquad" => "◱", # white square with lower left quadrant - "\\squarelrquad" => "◲", # white square with lower right quadrant - "\\squareurquad" => "◳", # white square with upper right quadrant - "\\circleulquad" => "◴", # white circle with upper left quadrant - "\\circlellquad" => "◵", # white circle with lower left quadrant - "\\circlelrquad" => "◶", # white circle with lower right quadrant - "\\circleurquad" => "◷", # white circle with upper right quadrant - "\\ultriangle" => "◸", # upper left triangle - "\\urtriangle" => "◹", # upper right triangle - "\\lltriangle" => "◺", # lower left triangle - "\\mdwhtsquare" => "◻", # white medium square - "\\mdblksquare" => "◼", # black medium square - "\\mdsmwhtsquare" => "◽", # white medium small square - "\\mdsmblksquare" => "◾", # black medium small square - "\\lrtriangle" => "◿", # lower right triangle - "\\bigwhitestar" => "☆", # star, open - "\\astrosun" => "☉", # sun - "\\danger" => "☡", # dangerous bend (caution sign) - "\\blacksmiley" => "☻", # black smiling face - "\\sun" => "☼", # white sun with rays - "\\rightmoon" => "☽", # first quarter moon - "\\varspadesuit" => "♤", # spade, white (card suit) - "\\varheartsuit" => "♥", # filled heart (card suit) - "\\vardiamondsuit" => "♦", # filled diamond (card suit) - "\\varclubsuit" => "♧", # club, white (card suit) - "\\twonotes" => "♫", # beamed eighth notes - "\\acidfree" => "\u267e", # permanent paper sign - "\\dicei" => "⚀", # die face-1 - "\\diceii" => "⚁", # die face-2 - "\\diceiii" => "⚂", # die face-3 - "\\diceiv" => "⚃", # die face-4 - "\\dicev" => "⚄", # die face-5 - "\\dicevi" => "⚅", # die face-6 - "\\circledrightdot" => "⚆", # white circle with dot right - "\\circledtwodots" => "⚇", # white circle with two dots - "\\blackcircledrightdot" => "⚈", # black circle with white dot right - "\\blackcircledtwodots" => "⚉", # black circle with two white dots - "\\Hermaphrodite" => "\u26a5", # male and female sign - "\\mdwhtcircle" => "\u26aa", # medium white circle - "\\mdblkcircle" => "\u26ab", # medium black circle - "\\mdsmwhtcircle" => "\u26ac", # medium small white circle - "\\neuter" => "\u26b2", # neuter - "\\circledstar" => "✪", # circled white star - "\\varstar" => "✶", # six pointed black star - "\\dingasterisk" => "✽", # heavy teardrop-spoked asterisk - "\\draftingarrow" => "➛", # right arrow with bold head (drafting) - "\\threedangle" => "\u27c0", # three dimensional angle - "\\whiteinwhitetriangle" => "\u27c1", # white triangle containing small white triangle - "\\perp" => "\u27c2", # perpendicular - "\\bsolhsub" => "\u27c8", # reverse solidus preceding subset - "\\suphsol" => "\u27c9", # superset preceding solidus - "\\wedgedot" => "⟑", # and with dot - "\\upin" => "⟒", # element of opening upwards - "\\bigbot" => "⟘", # large up tack - "\\bigtop" => "⟙", # large down tack - "\\UUparrow" => "⟰", # upwards quadruple arrow - "\\DDownarrow" => "⟱", # downwards quadruple arrow - "\\longmapsfrom" => "⟻", # long leftwards arrow from bar - "\\Longmapsfrom" => "⟽", # long leftwards double arrow from bar - "\\Longmapsto" => "⟾", # long rightwards double arrow from bar - "\\longrightsquigarrow" => "⟿", # long rightwards squiggle arrow - "\\nvtwoheadrightarrow" => "⤀", # rightwards two-headed arrow with vertical stroke - "\\nVtwoheadrightarrow" => "⤁", # rightwards two-headed arrow with double vertical stroke - "\\nvLeftarrow" => "⤂", # leftwards double arrow with vertical stroke - "\\nvRightarrow" => "⤃", # rightwards double arrow with vertical stroke - "\\nvLeftrightarrow" => "⤄", # left right double arrow with vertical stroke - "\\twoheadmapsto" => "⤅", # rightwards two-headed arrow from bar - "\\downarrowbarred" => "⤈", # downwards arrow with horizontal stroke - "\\uparrowbarred" => "⤉", # upwards arrow with horizontal stroke - "\\leftbkarrow" => "⤌", # leftwards double dash arrow - "\\leftdbkarrow" => "⤎", # leftwards triple dash arrow - "\\rightdotarrow" => "⤑", # rightwards arrow with dotted stem - "\\nvrightarrowtail" => "⤔", # rightwards arrow with tail with vertical stroke - "\\nVrightarrowtail" => "⤕", # rightwards arrow with tail with double vertical stroke - "\\nvtwoheadrightarrowtail" => "⤗", # rightwards two-headed arrow with tail with vertical stroke - "\\nVtwoheadrightarrowtail" => "⤘", # rightwards two-headed arrow with tail with double vertical stroke - "\\diamondleftarrow" => "⤝", # leftwards arrow to black diamond - "\\rightarrowdiamond" => "⤞", # rightwards arrow to black diamond - "\\diamondleftarrowbar" => "⤟", # leftwards arrow from bar to black diamond - "\\barrightarrowdiamond" => "⤠", # rightwards arrow from bar to black diamond - "\\rightarrowplus" => "⥅", # rightwards arrow with plus below - "\\leftarrowplus" => "⥆", # leftwards arrow with plus below - "\\leftrightarrowcircle" => "⥈", # left right arrow through small circle - "\\twoheaduparrowcircle" => "⥉", # upwards two-headed arrow from small circle - "\\leftrightharpoonupdown" => "⥊", # left barb up right barb down harpoon - "\\leftrightharpoondownup" => "⥋", # left barb down right barb up harpoon - "\\updownharpoonrightleft" => "⥌", # up barb right down barb left harpoon - "\\updownharpoonleftright" => "⥍", # up barb left down barb right harpoon - "\\leftharpoonsupdown" => "⥢", # leftwards harpoon with barb up above leftwards harpoon with barb down - "\\upharpoonsleftright" => "⥣", # upwards harpoon with barb left beside upwards harpoon with barb right - "\\rightharpoonsupdown" => "⥤", # rightwards harpoon with barb up above rightwards harpoon with barb down - "\\downharpoonsleftright" => "⥥", # downwards harpoon with barb left beside downwards harpoon with barb right - "\\leftrightharpoonsup" => "⥦", # leftwards harpoon with barb up above rightwards harpoon with barb up - "\\leftrightharpoonsdown" => "⥧", # leftwards harpoon with barb down above rightwards harpoon with barb down - "\\rightleftharpoonsup" => "⥨", # rightwards harpoon with barb up above leftwards harpoon with barb up - "\\rightleftharpoonsdown" => "⥩", # rightwards harpoon with barb down above leftwards harpoon with barb down - "\\leftharpoonupdash" => "⥪", # leftwards harpoon with barb up above long dash - "\\dashleftharpoondown" => "⥫", # leftwards harpoon with barb down below long dash - "\\rightharpoonupdash" => "⥬", # rightwards harpoon with barb up above long dash - "\\dashrightharpoondown" => "⥭", # rightwards harpoon with barb down below long dash - "\\measuredangleleft" => "⦛", # measured angle opening left - "\\rightanglemdot" => "⦝", # measured right angle with dot - "\\angles" => "⦞", # angle with s inside - "\\angdnr" => "⦟", # acute angle - "\\sphericalangleup" => "⦡", # spherical angle opening up - "\\turnangle" => "⦢", # turned angle - "\\revangle" => "⦣", # reversed angle - "\\angleubar" => "⦤", # angle with underbar - "\\revangleubar" => "⦥", # reversed angle with underbar - "\\wideangledown" => "⦦", # oblique angle opening up - "\\wideangleup" => "⦧", # oblique angle opening down - "\\measanglerutone" => "⦨", # measured angle with open arm ending in arrow pointing up and right - "\\measanglelutonw" => "⦩", # measured angle with open arm ending in arrow pointing up and left - "\\measanglerdtose" => "⦪", # measured angle with open arm ending in arrow pointing down and right - "\\measangleldtosw" => "⦫", # measured angle with open arm ending in arrow pointing down and left - "\\measangleurtone" => "⦬", # measured angle with open arm ending in arrow pointing right and up - "\\measangleultonw" => "⦭", # measured angle with open arm ending in arrow pointing left and up - "\\measangledrtose" => "⦮", # measured angle with open arm ending in arrow pointing right and down - "\\measangledltosw" => "⦯", # measured angle with open arm ending in arrow pointing left and down - "\\revemptyset" => "⦰", # reversed empty set - "\\emptysetobar" => "⦱", # empty set with overbar - "\\emptysetocirc" => "⦲", # empty set with small circle above - "\\emptysetoarr" => "⦳", # empty set with right arrow above - "\\emptysetoarrl" => "⦴", # empty set with left arrow above - "\\circledparallel" => "⦷", # circled parallel - "\\odotslashdot" => "⦼", # circled anticlockwise-rotated division sign - "\\circledwhitebullet" => "⦾", # circled white bullet - "\\circledbullet" => "⦿", # circled bullet - "\\olessthan" => "⧀", # circled less-than - "\\ogreaterthan" => "⧁", # circled greater-than - "\\lrtriangleeq" => "⧡", # increases as - "\\eparsl" => "⧣", # equals sign and slanted parallel - "\\smeparsl" => "⧤", # equals sign and slanted parallel with tilde above - "\\eqvparsl" => "⧥", # identical to and slanted parallel - "\\dsol" => "⧶", # solidus with overbar - "\\rsolbar" => "⧷", # reverse solidus with horizontal stroke - "\\doubleplus" => "⧺", # double plus - "\\tripleplus" => "⧻", # triple plus - "\\modtwosum" => "⨊", # modulo two sum - "\\sumint" => "⨋", # summation with integral - "\\cirfnint" => "⨐", # circulation function - "\\awint" => "⨑", # anticlockwise integration - "\\rppolint" => "⨒", # line integration with rectangular path around pole - "\\scpolint" => "⨓", # line integration with semicircular path around pole - "\\npolint" => "⨔", # line integration not including the pole - "\\pointint" => "⨕", # integral around a point operator - "\\ringplus" => "⨢", # plus sign with small circle above - "\\plushat" => "⨣", # plus sign with circumflex accent above - "\\simplus" => "⨤", # plus sign with tilde above - "\\plussim" => "⨦", # plus sign with tilde below - "\\plussubtwo" => "⨧", # plus sign with subscript two - "\\plustrif" => "⨨", # plus sign with black triangle - "\\commaminus" => "⨩", # minus sign with comma above - "\\minusfdots" => "⨫", # minus sign with falling dots - "\\minusrdots" => "⨬", # minus sign with rising dots - "\\opluslhrim" => "⨭", # plus sign in left half circle - "\\oplusrhrim" => "⨮", # plus sign in right half circle - "\\dottimes" => "⨰", # multiplication sign with dot above - "\\timesbar" => "⨱", # multiplication sign with underbar - "\\smashtimes" => "⨳", # smash product - "\\otimeslhrim" => "⨴", # multiplication sign in left half circle - "\\otimesrhrim" => "⨵", # multiplication sign in right half circle - "\\otimeshat" => "⨶", # circled multiplication sign with circumflex accent - "\\Otimes" => "⨷", # multiplication sign in double circle - "\\odiv" => "⨸", # circled division sign - "\\triangleplus" => "⨹", # plus sign in triangle - "\\triangleminus" => "⨺", # minus sign in triangle - "\\triangletimes" => "⨻", # multiplication sign in triangle - "\\capdot" => "⩀", # intersection with dot - "\\uminus" => "⩁", # union with minus sign - "\\barcup" => "⩂", # union with overbar - "\\barcap" => "⩃", # intersection with overbar - "\\capwedge" => "⩄", # intersection with logical and - "\\cupvee" => "⩅", # union with logical or - "\\twocups" => "⩊", # union beside and joined with union - "\\twocaps" => "⩋", # intersection beside and joined with intersection - "\\closedvarcup" => "⩌", # closed union with serifs - "\\closedvarcap" => "⩍", # closed intersection with serifs - "\\Sqcap" => "⩎", # double square intersection - "\\Sqcup" => "⩏", # double square union - "\\closedvarcupsmashprod" => "⩐", # closed union with serifs and smash product - "\\wedgeodot" => "⩑", # logical and with dot above - "\\veeodot" => "⩒", # logical or with dot above - "\\wedgeonwedge" => "⩕", # two intersecting logical and - "\\bigslopedvee" => "⩗", # sloping large or - "\\bigslopedwedge" => "⩘", # sloping large and - "\\wedgemidvert" => "⩚", # logical and with middle stem - "\\veemidvert" => "⩛", # logical or with middle stem - "\\midbarwedge" => "⩜", # ogical and with horizontal dash - "\\midbarvee" => "⩝", # logical or with horizontal dash - "\\wedgedoublebar" => "⩠", # logical and with double underbar - "\\varveebar" => "⩡", # small vee with underbar - "\\doublebarvee" => "⩢", # logical or with double overbar - "\\veedoublebar" => "⩣", # logical or with double underbar - "\\eqdot" => "⩦", # equals sign with dot below - "\\dotequiv" => "⩧", # identical with dot above - "\\dotsim" => "⩪", # tilde operator with dot above - "\\simrdots" => "⩫", # tilde operator with rising dots - "\\simminussim" => "⩬", # similar minus similar - "\\congdot" => "⩭", # congruent with dot above - "\\asteq" => "⩮", # equals with asterisk - "\\hatapprox" => "⩯", # almost equal to with circumflex accent - "\\approxeqq" => "⩰", # approximately equal or equal to - "\\eqqplus" => "⩱", # equals sign above plus sign - "\\pluseqq" => "⩲", # plus sign above equals sign - "\\eqqsim" => "⩳", # equals sign above tilde operator - "\\Coloneq" => "⩴", # double colon equal - "\\eqeqeq" => "⩶", # three consecutive equals signs - "\\equivDD" => "⩸", # equivalent with four dots above - "\\ltcir" => "⩹", # less-than with circle inside - "\\gtcir" => "⩺", # greater-than with circle inside - "\\ltquest" => "⩻", # less-than with question mark above - "\\gtquest" => "⩼", # greater-than with question mark above - "\\lesdot" => "⩿", # less-than or slanted equal to with dot inside - "\\gesdot" => "⪀", # greater-than or slanted equal to with dot inside - "\\lesdoto" => "⪁", # less-than or slanted equal to with dot above - "\\gesdoto" => "⪂", # greater-than or slanted equal to with dot above - "\\lesdotor" => "⪃", # less-than or slanted equal to with dot above right - "\\gesdotol" => "⪄", # greater-than or slanted equal to with dot above left - "\\lsime" => "⪍", # less-than above similar or equal - "\\gsime" => "⪎", # greater-than above similar or equal - "\\lsimg" => "⪏", # less-than above similar above greater-than - "\\gsiml" => "⪐", # greater-than above similar above less-than - "\\lgE" => "⪑", # less-than above greater-than above double-line equal - "\\glE" => "⪒", # greater-than above less-than above double-line equal - "\\lesges" => "⪓", # less-than above slanted equal above greater-than above slanted equal - "\\gesles" => "⪔", # greater-than above slanted equal above less-than above slanted equal - "\\elsdot" => "⪗", # slanted equal to or less-than with dot inside - "\\egsdot" => "⪘", # slanted equal to or greater-than with dot inside - "\\eqqless" => "⪙", # double-line equal to or less-than - "\\eqqgtr" => "⪚", # double-line equal to or greater-than - "\\eqqslantless" => "⪛", # double-line slanted equal to or less-than - "\\eqqslantgtr" => "⪜", # double-line slanted equal to or greater-than - "\\simless" => "⪝", # similar or less-than - "\\simgtr" => "⪞", # similar or greater-than - "\\simlE" => "⪟", # similar above less-than above equals sign - "\\simgE" => "⪠", # similar above greater-than above equals sign - "\\glj" => "⪤", # greater-than overlapping less-than - "\\gla" => "⪥", # greater-than beside less-than - "\\ltcc" => "⪦", # less-than closed by curve - "\\gtcc" => "⪧", # greater-than closed by curve - "\\lescc" => "⪨", # less-than closed by curve above slanted equal - "\\gescc" => "⪩", # greater-than closed by curve above slanted equal - "\\smt" => "⪪", # smaller than - "\\lat" => "⪫", # larger than - "\\smte" => "⪬", # smaller than or equal to - "\\late" => "⪭", # larger than or equal to - "\\precneq" => "⪱", # precedes above single-line not equal to - "\\succneq" => "⪲", # succeeds above single-line not equal to - "\\preceqq" => "⪳", # precedes above equals sign - "\\succeqq" => "⪴", # succeeds above equals sign - "\\Prec" => "⪻", # double precedes - "\\Succ" => "⪼", # double succeeds - "\\subsetdot" => "⪽", # subset with dot - "\\supsetdot" => "⪾", # superset with dot - "\\subsetplus" => "⪿", # subset with plus sign below - "\\supsetplus" => "⫀", # superset with plus sign below - "\\submult" => "⫁", # subset with multiplication sign below - "\\supmult" => "⫂", # superset with multiplication sign below - "\\subedot" => "⫃", # subset of or equal to with dot above - "\\supedot" => "⫄", # superset of or equal to with dot above - "\\subsim" => "⫇", # subset of above tilde operator - "\\supsim" => "⫈", # superset of above tilde operator - "\\subsetapprox" => "⫉", # subset of above almost equal to - "\\supsetapprox" => "⫊", # superset of above almost equal to - "\\lsqhook" => "⫍", # square left open box operator - "\\rsqhook" => "⫎", # square right open box operator - "\\csub" => "⫏", # closed subset - "\\csup" => "⫐", # closed superset - "\\csube" => "⫑", # closed subset or equal to - "\\csupe" => "⫒", # closed superset or equal to - "\\subsup" => "⫓", # subset above superset - "\\supsub" => "⫔", # superset above subset - "\\subsub" => "⫕", # subset above subset - "\\supsup" => "⫖", # superset above superset - "\\suphsub" => "⫗", # superset beside subset - "\\supdsub" => "⫘", # superset beside and joined by dash with subset - "\\forkv" => "⫙", # element of opening downwards - "\\lllnest" => "⫷", # stacked very much less-than - "\\gggnest" => "⫸", # stacked very much greater-than - "\\leqqslant" => "⫹", # double-line slanted less-than or equal to - "\\geqqslant" => "⫺", # double-line slanted greater-than or equal to - "\\squaretopblack" => "\u2b12", # square with top half black - "\\squarebotblack" => "\u2b13", # square with bottom half black - "\\squareurblack" => "\u2b14", # square with upper right diagonal half black - "\\squarellblack" => "\u2b15", # square with lower left diagonal half black - "\\diamondleftblack" => "\u2b16", # diamond with left half black - "\\diamondrightblack" => "\u2b17", # diamond with right half black - "\\diamondtopblack" => "\u2b18", # diamond with top half black - "\\diamondbotblack" => "\u2b19", # diamond with bottom half black - "\\dottedsquare" => "\u2b1a", # dotted square - "\\lgblksquare" => "\u2b1b", # black large square - "\\lgwhtsquare" => "\u2b1c", # white large square - "\\vysmblksquare" => "\u2b1d", # black very small square - "\\vysmwhtsquare" => "\u2b1e", # white very small square - "\\pentagonblack" => "\u2b1f", # black pentagon - "\\pentagon" => "\u2b20", # white pentagon - "\\varhexagon" => "\u2b21", # white hexagon - "\\varhexagonblack" => "\u2b22", # black hexagon - "\\hexagonblack" => "\u2b23", # horizontal black hexagon - "\\lgblkcircle" => "\u2b24", # black large circle - "\\mdblkdiamond" => "\u2b25", # black medium diamond - "\\mdwhtdiamond" => "\u2b26", # white medium diamond - "\\mdblklozenge" => "\u2b27", # black medium lozenge - "\\mdwhtlozenge" => "\u2b28", # white medium lozenge - "\\smblkdiamond" => "\u2b29", # black small diamond - "\\smblklozenge" => "\u2b2a", # black small lozenge - "\\smwhtlozenge" => "\u2b2b", # white small lozenge - "\\blkhorzoval" => "\u2b2c", # black horizontal ellipse - "\\whthorzoval" => "\u2b2d", # white horizontal ellipse - "\\blkvertoval" => "\u2b2e", # black vertical ellipse - "\\whtvertoval" => "\u2b2f", # white vertical ellipse - "\\circleonleftarrow" => "\u2b30", # left arrow with small circle - "\\leftthreearrows" => "\u2b31", # three leftwards arrows - "\\leftarrowonoplus" => "\u2b32", # left arrow with circled plus - "\\longleftsquigarrow" => "\u2b33", # long leftwards squiggle arrow - "\\nvtwoheadleftarrow" => "\u2b34", # leftwards two-headed arrow with vertical stroke - "\\nVtwoheadleftarrow" => "\u2b35", # leftwards two-headed arrow with double vertical stroke - "\\twoheadmapsfrom" => "\u2b36", # leftwards two-headed arrow from bar - "\\twoheadleftdbkarrow" => "\u2b37", # leftwards two-headed triple-dash arrow - "\\leftdotarrow" => "\u2b38", # leftwards arrow with dotted stem - "\\nvleftarrowtail" => "\u2b39", # leftwards arrow with tail with vertical stroke - "\\nVleftarrowtail" => "\u2b3a", # leftwards arrow with tail with double vertical stroke - "\\twoheadleftarrowtail" => "\u2b3b", # leftwards two-headed arrow with tail - "\\nvtwoheadleftarrowtail" => "\u2b3c", # leftwards two-headed arrow with tail with vertical stroke - "\\nVtwoheadleftarrowtail" => "\u2b3d", # leftwards two-headed arrow with tail with double vertical stroke - "\\leftarrowx" => "\u2b3e", # leftwards arrow through x - "\\leftcurvedarrow" => "\u2b3f", # wave arrow pointing directly left - "\\equalleftarrow" => "\u2b40", # equals sign above leftwards arrow - "\\bsimilarleftarrow" => "\u2b41", # reverse tilde operator above leftwards arrow - "\\leftarrowbackapprox" => "\u2b42", # leftwards arrow above reverse almost equal to - "\\rightarrowgtr" => "\u2b43", # rightwards arrow through greater-than - "\\rightarrowsupset" => "\u2b44", # rightwards arrow through subset - "\\LLeftarrow" => "\u2b45", # leftwards quadruple arrow - "\\RRightarrow" => "\u2b46", # rightwards quadruple arrow - "\\bsimilarrightarrow" => "\u2b47", # reverse tilde operator above rightwards arrow - "\\rightarrowbackapprox" => "\u2b48", # rightwards arrow above reverse almost equal to - "\\similarleftarrow" => "\u2b49", # tilde operator above leftwards arrow - "\\leftarrowapprox" => "\u2b4a", # leftwards arrow above almost equal to - "\\leftarrowbsimilar" => "\u2b4b", # leftwards arrow above reverse tilde operator - "\\rightarrowbsimilar" => "\u2b4c", # righttwards arrow above reverse tilde operator - "\\medwhitestar" => "\u2b50", # white medium star - "\\medblackstar" => "\u2b51", # black medium star - "\\smwhitestar" => "\u2b52", # white small star - "\\rightpentagonblack" => "\u2b53", # black right-pointing pentagon - "\\rightpentagon" => "\u2b54", # white right-pointing pentagon - "\\postalmark" => "〒", # postal mark - "\\mbfA" => "𝐀", # mathematical bold capital a - "\\mbfB" => "𝐁", # mathematical bold capital b - "\\mbfC" => "𝐂", # mathematical bold capital c - "\\mbfD" => "𝐃", # mathematical bold capital d - "\\mbfE" => "𝐄", # mathematical bold capital e - "\\mbfF" => "𝐅", # mathematical bold capital f - "\\mbfG" => "𝐆", # mathematical bold capital g - "\\mbfH" => "𝐇", # mathematical bold capital h - "\\mbfI" => "𝐈", # mathematical bold capital i - "\\mbfJ" => "𝐉", # mathematical bold capital j - "\\mbfK" => "𝐊", # mathematical bold capital k - "\\mbfL" => "𝐋", # mathematical bold capital l - "\\mbfM" => "𝐌", # mathematical bold capital m - "\\mbfN" => "𝐍", # mathematical bold capital n - "\\mbfO" => "𝐎", # mathematical bold capital o - "\\mbfP" => "𝐏", # mathematical bold capital p - "\\mbfQ" => "𝐐", # mathematical bold capital q - "\\mbfR" => "𝐑", # mathematical bold capital r - "\\mbfS" => "𝐒", # mathematical bold capital s - "\\mbfT" => "𝐓", # mathematical bold capital t - "\\mbfU" => "𝐔", # mathematical bold capital u - "\\mbfV" => "𝐕", # mathematical bold capital v - "\\mbfW" => "𝐖", # mathematical bold capital w - "\\mbfX" => "𝐗", # mathematical bold capital x - "\\mbfY" => "𝐘", # mathematical bold capital y - "\\mbfZ" => "𝐙", # mathematical bold capital z - "\\mbfa" => "𝐚", # mathematical bold small a - "\\mbfb" => "𝐛", # mathematical bold small b - "\\mbfc" => "𝐜", # mathematical bold small c - "\\mbfd" => "𝐝", # mathematical bold small d - "\\mbfe" => "𝐞", # mathematical bold small e - "\\mbff" => "𝐟", # mathematical bold small f - "\\mbfg" => "𝐠", # mathematical bold small g - "\\mbfh" => "𝐡", # mathematical bold small h - "\\mbfi" => "𝐢", # mathematical bold small i - "\\mbfj" => "𝐣", # mathematical bold small j - "\\mbfk" => "𝐤", # mathematical bold small k - "\\mbfl" => "𝐥", # mathematical bold small l - "\\mbfm" => "𝐦", # mathematical bold small m - "\\mbfn" => "𝐧", # mathematical bold small n - "\\mbfo" => "𝐨", # mathematical bold small o - "\\mbfp" => "𝐩", # mathematical bold small p - "\\mbfq" => "𝐪", # mathematical bold small q - "\\mbfr" => "𝐫", # mathematical bold small r - "\\mbfs" => "𝐬", # mathematical bold small s - "\\mbft" => "𝐭", # mathematical bold small t - "\\mbfu" => "𝐮", # mathematical bold small u - "\\mbfv" => "𝐯", # mathematical bold small v - "\\mbfw" => "𝐰", # mathematical bold small w - "\\mbfx" => "𝐱", # mathematical bold small x - "\\mbfy" => "𝐲", # mathematical bold small y - "\\mbfz" => "𝐳", # mathematical bold small z - "\\mitA" => "𝐴", # mathematical italic capital a - "\\mitB" => "𝐵", # mathematical italic capital b - "\\mitC" => "𝐶", # mathematical italic capital c - "\\mitD" => "𝐷", # mathematical italic capital d - "\\mitE" => "𝐸", # mathematical italic capital e - "\\mitF" => "𝐹", # mathematical italic capital f - "\\mitG" => "𝐺", # mathematical italic capital g - "\\mitH" => "𝐻", # mathematical italic capital h - "\\mitI" => "𝐼", # mathematical italic capital i - "\\mitJ" => "𝐽", # mathematical italic capital j - "\\mitK" => "𝐾", # mathematical italic capital k - "\\mitL" => "𝐿", # mathematical italic capital l - "\\mitM" => "𝑀", # mathematical italic capital m - "\\mitN" => "𝑁", # mathematical italic capital n - "\\mitO" => "𝑂", # mathematical italic capital o - "\\mitP" => "𝑃", # mathematical italic capital p - "\\mitQ" => "𝑄", # mathematical italic capital q - "\\mitR" => "𝑅", # mathematical italic capital r - "\\mitS" => "𝑆", # mathematical italic capital s - "\\mitT" => "𝑇", # mathematical italic capital t - "\\mitU" => "𝑈", # mathematical italic capital u - "\\mitV" => "𝑉", # mathematical italic capital v - "\\mitW" => "𝑊", # mathematical italic capital w - "\\mitX" => "𝑋", # mathematical italic capital x - "\\mitY" => "𝑌", # mathematical italic capital y - "\\mitZ" => "𝑍", # mathematical italic capital z - "\\mita" => "𝑎", # mathematical italic small a - "\\mitb" => "𝑏", # mathematical italic small b - "\\mitc" => "𝑐", # mathematical italic small c - "\\mitd" => "𝑑", # mathematical italic small d - "\\mite" => "𝑒", # mathematical italic small e - "\\mitf" => "𝑓", # mathematical italic small f - "\\mitg" => "𝑔", # mathematical italic small g - "\\miti" => "𝑖", # mathematical italic small i - "\\mitj" => "𝑗", # mathematical italic small j - "\\mitk" => "𝑘", # mathematical italic small k - "\\mitl" => "𝑙", # mathematical italic small l - "\\mitm" => "𝑚", # mathematical italic small m - "\\mitn" => "𝑛", # mathematical italic small n - "\\mito" => "𝑜", # mathematical italic small o - "\\mitp" => "𝑝", # mathematical italic small p - "\\mitq" => "𝑞", # mathematical italic small q - "\\mitr" => "𝑟", # mathematical italic small r - "\\mits" => "𝑠", # mathematical italic small s - "\\mitt" => "𝑡", # mathematical italic small t - "\\mitu" => "𝑢", # mathematical italic small u - "\\mitv" => "𝑣", # mathematical italic small v - "\\mitw" => "𝑤", # mathematical italic small w - "\\mitx" => "𝑥", # mathematical italic small x - "\\mity" => "𝑦", # mathematical italic small y - "\\mitz" => "𝑧", # mathematical italic small z - "\\mbfitA" => "𝑨", # mathematical bold italic capital a - "\\mbfitB" => "𝑩", # mathematical bold italic capital b - "\\mbfitC" => "𝑪", # mathematical bold italic capital c - "\\mbfitD" => "𝑫", # mathematical bold italic capital d - "\\mbfitE" => "𝑬", # mathematical bold italic capital e - "\\mbfitF" => "𝑭", # mathematical bold italic capital f - "\\mbfitG" => "𝑮", # mathematical bold italic capital g - "\\mbfitH" => "𝑯", # mathematical bold italic capital h - "\\mbfitI" => "𝑰", # mathematical bold italic capital i - "\\mbfitJ" => "𝑱", # mathematical bold italic capital j - "\\mbfitK" => "𝑲", # mathematical bold italic capital k - "\\mbfitL" => "𝑳", # mathematical bold italic capital l - "\\mbfitM" => "𝑴", # mathematical bold italic capital m - "\\mbfitN" => "𝑵", # mathematical bold italic capital n - "\\mbfitO" => "𝑶", # mathematical bold italic capital o - "\\mbfitP" => "𝑷", # mathematical bold italic capital p - "\\mbfitQ" => "𝑸", # mathematical bold italic capital q - "\\mbfitR" => "𝑹", # mathematical bold italic capital r - "\\mbfitS" => "𝑺", # mathematical bold italic capital s - "\\mbfitT" => "𝑻", # mathematical bold italic capital t - "\\mbfitU" => "𝑼", # mathematical bold italic capital u - "\\mbfitV" => "𝑽", # mathematical bold italic capital v - "\\mbfitW" => "𝑾", # mathematical bold italic capital w - "\\mbfitX" => "𝑿", # mathematical bold italic capital x - "\\mbfitY" => "𝒀", # mathematical bold italic capital y - "\\mbfitZ" => "𝒁", # mathematical bold italic capital z - "\\mbfita" => "𝒂", # mathematical bold italic small a - "\\mbfitb" => "𝒃", # mathematical bold italic small b - "\\mbfitc" => "𝒄", # mathematical bold italic small c - "\\mbfitd" => "𝒅", # mathematical bold italic small d - "\\mbfite" => "𝒆", # mathematical bold italic small e - "\\mbfitf" => "𝒇", # mathematical bold italic small f - "\\mbfitg" => "𝒈", # mathematical bold italic small g - "\\mbfith" => "𝒉", # mathematical bold italic small h - "\\mbfiti" => "𝒊", # mathematical bold italic small i - "\\mbfitj" => "𝒋", # mathematical bold italic small j - "\\mbfitk" => "𝒌", # mathematical bold italic small k - "\\mbfitl" => "𝒍", # mathematical bold italic small l - "\\mbfitm" => "𝒎", # mathematical bold italic small m - "\\mbfitn" => "𝒏", # mathematical bold italic small n - "\\mbfito" => "𝒐", # mathematical bold italic small o - "\\mbfitp" => "𝒑", # mathematical bold italic small p - "\\mbfitq" => "𝒒", # mathematical bold italic small q - "\\mbfitr" => "𝒓", # mathematical bold italic small r - "\\mbfits" => "𝒔", # mathematical bold italic small s - "\\mbfitt" => "𝒕", # mathematical bold italic small t - "\\mbfitu" => "𝒖", # mathematical bold italic small u - "\\mbfitv" => "𝒗", # mathematical bold italic small v - "\\mbfitw" => "𝒘", # mathematical bold italic small w - "\\mbfitx" => "𝒙", # mathematical bold italic small x - "\\mbfity" => "𝒚", # mathematical bold italic small y - "\\mbfitz" => "𝒛", # mathematical bold italic small z - "\\mscrA" => "𝒜", # mathematical script capital a - "\\mscrC" => "𝒞", # mathematical script capital c - "\\mscrD" => "𝒟", # mathematical script capital d - "\\mscrG" => "𝒢", # mathematical script capital g - "\\mscrJ" => "𝒥", # mathematical script capital j - "\\mscrK" => "𝒦", # mathematical script capital k - "\\mscrN" => "𝒩", # mathematical script capital n - "\\mscrO" => "𝒪", # mathematical script capital o - "\\mscrP" => "𝒫", # mathematical script capital p - "\\mscrQ" => "𝒬", # mathematical script capital q - "\\mscrS" => "𝒮", # mathematical script capital s - "\\mscrT" => "𝒯", # mathematical script capital t - "\\mscrU" => "𝒰", # mathematical script capital u - "\\mscrV" => "𝒱", # mathematical script capital v - "\\mscrW" => "𝒲", # mathematical script capital w - "\\mscrX" => "𝒳", # mathematical script capital x - "\\mscrY" => "𝒴", # mathematical script capital y - "\\mscrZ" => "𝒵", # mathematical script capital z - "\\mscra" => "𝒶", # mathematical script small a - "\\mscrb" => "𝒷", # mathematical script small b - "\\mscrc" => "𝒸", # mathematical script small c - "\\mscrd" => "𝒹", # mathematical script small d - "\\mscrf" => "𝒻", # mathematical script small f - "\\mscrh" => "𝒽", # mathematical script small h - "\\mscri" => "𝒾", # mathematical script small i - "\\mscrj" => "𝒿", # mathematical script small j - "\\mscrk" => "𝓀", # mathematical script small k - "\\mscrl" => "\U1d4c1", # mathematical script small l - "\\mscrm" => "𝓂", # mathematical script small m - "\\mscrn" => "𝓃", # mathematical script small n - "\\mscrp" => "𝓅", # mathematical script small p - "\\mscrq" => "𝓆", # mathematical script small q - "\\mscrr" => "𝓇", # mathematical script small r - "\\mscrs" => "𝓈", # mathematical script small s - "\\mscrt" => "𝓉", # mathematical script small t - "\\mscru" => "𝓊", # mathematical script small u - "\\mscrv" => "𝓋", # mathematical script small v - "\\mscrw" => "𝓌", # mathematical script small w - "\\mscrx" => "𝓍", # mathematical script small x - "\\mscry" => "𝓎", # mathematical script small y - "\\mscrz" => "𝓏", # mathematical script small z - "\\mbfscrA" => "𝓐", # mathematical bold script capital a - "\\mbfscrB" => "𝓑", # mathematical bold script capital b - "\\mbfscrC" => "𝓒", # mathematical bold script capital c - "\\mbfscrD" => "𝓓", # mathematical bold script capital d - "\\mbfscrE" => "𝓔", # mathematical bold script capital e - "\\mbfscrF" => "𝓕", # mathematical bold script capital f - "\\mbfscrG" => "𝓖", # mathematical bold script capital g - "\\mbfscrH" => "𝓗", # mathematical bold script capital h - "\\mbfscrI" => "𝓘", # mathematical bold script capital i - "\\mbfscrJ" => "𝓙", # mathematical bold script capital j - "\\mbfscrK" => "𝓚", # mathematical bold script capital k - "\\mbfscrL" => "𝓛", # mathematical bold script capital l - "\\mbfscrM" => "𝓜", # mathematical bold script capital m - "\\mbfscrN" => "𝓝", # mathematical bold script capital n - "\\mbfscrO" => "𝓞", # mathematical bold script capital o - "\\mbfscrP" => "𝓟", # mathematical bold script capital p - "\\mbfscrQ" => "𝓠", # mathematical bold script capital q - "\\mbfscrR" => "𝓡", # mathematical bold script capital r - "\\mbfscrS" => "𝓢", # mathematical bold script capital s - "\\mbfscrT" => "𝓣", # mathematical bold script capital t - "\\mbfscrU" => "𝓤", # mathematical bold script capital u - "\\mbfscrV" => "𝓥", # mathematical bold script capital v - "\\mbfscrW" => "𝓦", # mathematical bold script capital w - "\\mbfscrX" => "𝓧", # mathematical bold script capital x - "\\mbfscrY" => "𝓨", # mathematical bold script capital y - "\\mbfscrZ" => "𝓩", # mathematical bold script capital z - "\\mbfscra" => "𝓪", # mathematical bold script small a - "\\mbfscrb" => "𝓫", # mathematical bold script small b - "\\mbfscrc" => "𝓬", # mathematical bold script small c - "\\mbfscrd" => "𝓭", # mathematical bold script small d - "\\mbfscre" => "𝓮", # mathematical bold script small e - "\\mbfscrf" => "𝓯", # mathematical bold script small f - "\\mbfscrg" => "𝓰", # mathematical bold script small g - "\\mbfscrh" => "𝓱", # mathematical bold script small h - "\\mbfscri" => "𝓲", # mathematical bold script small i - "\\mbfscrj" => "𝓳", # mathematical bold script small j - "\\mbfscrk" => "𝓴", # mathematical bold script small k - "\\mbfscrl" => "𝓵", # mathematical bold script small l - "\\mbfscrm" => "𝓶", # mathematical bold script small m - "\\mbfscrn" => "𝓷", # mathematical bold script small n - "\\mbfscro" => "𝓸", # mathematical bold script small o - "\\mbfscrp" => "𝓹", # mathematical bold script small p - "\\mbfscrq" => "𝓺", # mathematical bold script small q - "\\mbfscrr" => "𝓻", # mathematical bold script small r - "\\mbfscrs" => "𝓼", # mathematical bold script small s - "\\mbfscrt" => "𝓽", # mathematical bold script small t - "\\mbfscru" => "𝓾", # mathematical bold script small u - "\\mbfscrv" => "𝓿", # mathematical bold script small v - "\\mbfscrw" => "𝔀", # mathematical bold script small w - "\\mbfscrx" => "𝔁", # mathematical bold script small x - "\\mbfscry" => "𝔂", # mathematical bold script small y - "\\mbfscrz" => "𝔃", # mathematical bold script small z - "\\mfrakA" => "𝔄", # mathematical fraktur capital a - "\\mfrakB" => "𝔅", # mathematical fraktur capital b - "\\mfrakD" => "𝔇", # mathematical fraktur capital d - "\\mfrakE" => "𝔈", # mathematical fraktur capital e - "\\mfrakF" => "𝔉", # mathematical fraktur capital f - "\\mfrakG" => "𝔊", # mathematical fraktur capital g - "\\mfrakJ" => "𝔍", # mathematical fraktur capital j - "\\mfrakK" => "𝔎", # mathematical fraktur capital k - "\\mfrakL" => "𝔏", # mathematical fraktur capital l - "\\mfrakM" => "𝔐", # mathematical fraktur capital m - "\\mfrakN" => "𝔑", # mathematical fraktur capital n - "\\mfrakO" => "𝔒", # mathematical fraktur capital o - "\\mfrakP" => "𝔓", # mathematical fraktur capital p - "\\mfrakQ" => "𝔔", # mathematical fraktur capital q - "\\mfrakS" => "𝔖", # mathematical fraktur capital s - "\\mfrakT" => "𝔗", # mathematical fraktur capital t - "\\mfrakU" => "𝔘", # mathematical fraktur capital u - "\\mfrakV" => "𝔙", # mathematical fraktur capital v - "\\mfrakW" => "𝔚", # mathematical fraktur capital w - "\\mfrakX" => "𝔛", # mathematical fraktur capital x - "\\mfrakY" => "𝔜", # mathematical fraktur capital y - "\\mfraka" => "𝔞", # mathematical fraktur small a - "\\mfrakb" => "𝔟", # mathematical fraktur small b - "\\mfrakc" => "𝔠", # mathematical fraktur small c - "\\mfrakd" => "𝔡", # mathematical fraktur small d - "\\mfrake" => "𝔢", # mathematical fraktur small e - "\\mfrakf" => "𝔣", # mathematical fraktur small f - "\\mfrakg" => "𝔤", # mathematical fraktur small g - "\\mfrakh" => "𝔥", # mathematical fraktur small h - "\\mfraki" => "𝔦", # mathematical fraktur small i - "\\mfrakj" => "𝔧", # mathematical fraktur small j - "\\mfrakk" => "𝔨", # mathematical fraktur small k - "\\mfrakl" => "𝔩", # mathematical fraktur small l - "\\mfrakm" => "𝔪", # mathematical fraktur small m - "\\mfrakn" => "𝔫", # mathematical fraktur small n - "\\mfrako" => "𝔬", # mathematical fraktur small o - "\\mfrakp" => "𝔭", # mathematical fraktur small p - "\\mfrakq" => "𝔮", # mathematical fraktur small q - "\\mfrakr" => "𝔯", # mathematical fraktur small r - "\\mfraks" => "𝔰", # mathematical fraktur small s - "\\mfrakt" => "𝔱", # mathematical fraktur small t - "\\mfraku" => "𝔲", # mathematical fraktur small u - "\\mfrakv" => "𝔳", # mathematical fraktur small v - "\\mfrakw" => "𝔴", # mathematical fraktur small w - "\\mfrakx" => "𝔵", # mathematical fraktur small x - "\\mfraky" => "𝔶", # mathematical fraktur small y - "\\mfrakz" => "𝔷", # mathematical fraktur small z - "\\BbbA" => "𝔸", # mathematical double-struck capital a - "\\BbbB" => "𝔹", # mathematical double-struck capital b - "\\BbbD" => "𝔻", # mathematical double-struck capital d - "\\BbbE" => "𝔼", # mathematical double-struck capital e - "\\BbbF" => "𝔽", # mathematical double-struck capital f - "\\BbbG" => "𝔾", # mathematical double-struck capital g - "\\BbbI" => "𝕀", # mathematical double-struck capital i - "\\BbbJ" => "𝕁", # mathematical double-struck capital j - "\\BbbK" => "𝕂", # mathematical double-struck capital k - "\\BbbL" => "𝕃", # mathematical double-struck capital l - "\\BbbM" => "𝕄", # mathematical double-struck capital m - "\\BbbO" => "𝕆", # mathematical double-struck capital o - "\\BbbS" => "𝕊", # mathematical double-struck capital s - "\\BbbT" => "𝕋", # mathematical double-struck capital t - "\\BbbU" => "𝕌", # mathematical double-struck capital u - "\\BbbV" => "𝕍", # mathematical double-struck capital v - "\\BbbW" => "𝕎", # mathematical double-struck capital w - "\\BbbX" => "𝕏", # mathematical double-struck capital x - "\\BbbY" => "𝕐", # mathematical double-struck capital y - "\\Bbba" => "𝕒", # mathematical double-struck small a - "\\Bbbb" => "𝕓", # mathematical double-struck small b - "\\Bbbc" => "𝕔", # mathematical double-struck small c - "\\Bbbd" => "𝕕", # mathematical double-struck small d - "\\Bbbe" => "𝕖", # mathematical double-struck small e - "\\Bbbf" => "𝕗", # mathematical double-struck small f - "\\Bbbg" => "𝕘", # mathematical double-struck small g - "\\Bbbh" => "𝕙", # mathematical double-struck small h - "\\Bbbi" => "𝕚", # mathematical double-struck small i - "\\Bbbj" => "𝕛", # mathematical double-struck small j - "\\Bbbk" => "𝕜", # mathematical double-struck small k - "\\Bbbl" => "𝕝", # mathematical double-struck small l - "\\Bbbm" => "𝕞", # mathematical double-struck small m - "\\Bbbn" => "𝕟", # mathematical double-struck small n - "\\Bbbo" => "𝕠", # mathematical double-struck small o - "\\Bbbp" => "𝕡", # mathematical double-struck small p - "\\Bbbq" => "𝕢", # mathematical double-struck small q - "\\Bbbr" => "𝕣", # mathematical double-struck small r - "\\Bbbs" => "𝕤", # mathematical double-struck small s - "\\Bbbt" => "𝕥", # mathematical double-struck small t - "\\Bbbu" => "𝕦", # mathematical double-struck small u - "\\Bbbv" => "𝕧", # mathematical double-struck small v - "\\Bbbw" => "𝕨", # mathematical double-struck small w - "\\Bbbx" => "𝕩", # mathematical double-struck small x - "\\Bbby" => "𝕪", # mathematical double-struck small y - "\\Bbbz" => "𝕫", # mathematical double-struck small z - "\\mbffrakA" => "𝕬", # mathematical bold fraktur capital a - "\\mbffrakB" => "𝕭", # mathematical bold fraktur capital b - "\\mbffrakC" => "𝕮", # mathematical bold fraktur capital c - "\\mbffrakD" => "𝕯", # mathematical bold fraktur capital d - "\\mbffrakE" => "𝕰", # mathematical bold fraktur capital e - "\\mbffrakF" => "𝕱", # mathematical bold fraktur capital f - "\\mbffrakG" => "𝕲", # mathematical bold fraktur capital g - "\\mbffrakH" => "𝕳", # mathematical bold fraktur capital h - "\\mbffrakI" => "𝕴", # mathematical bold fraktur capital i - "\\mbffrakJ" => "𝕵", # mathematical bold fraktur capital j - "\\mbffrakK" => "𝕶", # mathematical bold fraktur capital k - "\\mbffrakL" => "𝕷", # mathematical bold fraktur capital l - "\\mbffrakM" => "𝕸", # mathematical bold fraktur capital m - "\\mbffrakN" => "𝕹", # mathematical bold fraktur capital n - "\\mbffrakO" => "𝕺", # mathematical bold fraktur capital o - "\\mbffrakP" => "𝕻", # mathematical bold fraktur capital p - "\\mbffrakQ" => "𝕼", # mathematical bold fraktur capital q - "\\mbffrakR" => "𝕽", # mathematical bold fraktur capital r - "\\mbffrakS" => "𝕾", # mathematical bold fraktur capital s - "\\mbffrakT" => "𝕿", # mathematical bold fraktur capital t - "\\mbffrakU" => "𝖀", # mathematical bold fraktur capital u - "\\mbffrakV" => "𝖁", # mathematical bold fraktur capital v - "\\mbffrakW" => "𝖂", # mathematical bold fraktur capital w - "\\mbffrakX" => "𝖃", # mathematical bold fraktur capital x - "\\mbffrakY" => "𝖄", # mathematical bold fraktur capital y - "\\mbffrakZ" => "𝖅", # mathematical bold fraktur capital z - "\\mbffraka" => "𝖆", # mathematical bold fraktur small a - "\\mbffrakb" => "𝖇", # mathematical bold fraktur small b - "\\mbffrakc" => "𝖈", # mathematical bold fraktur small c - "\\mbffrakd" => "𝖉", # mathematical bold fraktur small d - "\\mbffrake" => "𝖊", # mathematical bold fraktur small e - "\\mbffrakf" => "𝖋", # mathematical bold fraktur small f - "\\mbffrakg" => "𝖌", # mathematical bold fraktur small g - "\\mbffrakh" => "𝖍", # mathematical bold fraktur small h - "\\mbffraki" => "𝖎", # mathematical bold fraktur small i - "\\mbffrakj" => "𝖏", # mathematical bold fraktur small j - "\\mbffrakk" => "𝖐", # mathematical bold fraktur small k - "\\mbffrakl" => "𝖑", # mathematical bold fraktur small l - "\\mbffrakm" => "𝖒", # mathematical bold fraktur small m - "\\mbffrakn" => "𝖓", # mathematical bold fraktur small n - "\\mbffrako" => "𝖔", # mathematical bold fraktur small o - "\\mbffrakp" => "𝖕", # mathematical bold fraktur small p - "\\mbffrakq" => "𝖖", # mathematical bold fraktur small q - "\\mbffrakr" => "𝖗", # mathematical bold fraktur small r - "\\mbffraks" => "𝖘", # mathematical bold fraktur small s - "\\mbffrakt" => "𝖙", # mathematical bold fraktur small t - "\\mbffraku" => "𝖚", # mathematical bold fraktur small u - "\\mbffrakv" => "𝖛", # mathematical bold fraktur small v - "\\mbffrakw" => "𝖜", # mathematical bold fraktur small w - "\\mbffrakx" => "𝖝", # mathematical bold fraktur small x - "\\mbffraky" => "𝖞", # mathematical bold fraktur small y - "\\mbffrakz" => "𝖟", # mathematical bold fraktur small z - "\\msansA" => "𝖠", # mathematical sans-serif capital a - "\\msansB" => "𝖡", # mathematical sans-serif capital b - "\\msansC" => "𝖢", # mathematical sans-serif capital c - "\\msansD" => "𝖣", # mathematical sans-serif capital d - "\\msansE" => "𝖤", # mathematical sans-serif capital e - "\\msansF" => "𝖥", # mathematical sans-serif capital f - "\\msansG" => "𝖦", # mathematical sans-serif capital g - "\\msansH" => "𝖧", # mathematical sans-serif capital h - "\\msansI" => "𝖨", # mathematical sans-serif capital i - "\\msansJ" => "𝖩", # mathematical sans-serif capital j - "\\msansK" => "𝖪", # mathematical sans-serif capital k - "\\msansL" => "𝖫", # mathematical sans-serif capital l - "\\msansM" => "𝖬", # mathematical sans-serif capital m - "\\msansN" => "𝖭", # mathematical sans-serif capital n - "\\msansO" => "𝖮", # mathematical sans-serif capital o - "\\msansP" => "𝖯", # mathematical sans-serif capital p - "\\msansQ" => "𝖰", # mathematical sans-serif capital q - "\\msansR" => "𝖱", # mathematical sans-serif capital r - "\\msansS" => "𝖲", # mathematical sans-serif capital s - "\\msansT" => "𝖳", # mathematical sans-serif capital t - "\\msansU" => "𝖴", # mathematical sans-serif capital u - "\\msansV" => "𝖵", # mathematical sans-serif capital v - "\\msansW" => "𝖶", # mathematical sans-serif capital w - "\\msansX" => "𝖷", # mathematical sans-serif capital x - "\\msansY" => "𝖸", # mathematical sans-serif capital y - "\\msansZ" => "𝖹", # mathematical sans-serif capital z - "\\msansa" => "𝖺", # mathematical sans-serif small a - "\\msansb" => "𝖻", # mathematical sans-serif small b - "\\msansc" => "𝖼", # mathematical sans-serif small c - "\\msansd" => "𝖽", # mathematical sans-serif small d - "\\msanse" => "𝖾", # mathematical sans-serif small e - "\\msansf" => "𝖿", # mathematical sans-serif small f - "\\msansg" => "𝗀", # mathematical sans-serif small g - "\\msansh" => "𝗁", # mathematical sans-serif small h - "\\msansi" => "𝗂", # mathematical sans-serif small i - "\\msansj" => "𝗃", # mathematical sans-serif small j - "\\msansk" => "𝗄", # mathematical sans-serif small k - "\\msansl" => "𝗅", # mathematical sans-serif small l - "\\msansm" => "𝗆", # mathematical sans-serif small m - "\\msansn" => "𝗇", # mathematical sans-serif small n - "\\msanso" => "𝗈", # mathematical sans-serif small o - "\\msansp" => "𝗉", # mathematical sans-serif small p - "\\msansq" => "𝗊", # mathematical sans-serif small q - "\\msansr" => "𝗋", # mathematical sans-serif small r - "\\msanss" => "𝗌", # mathematical sans-serif small s - "\\msanst" => "𝗍", # mathematical sans-serif small t - "\\msansu" => "𝗎", # mathematical sans-serif small u - "\\msansv" => "𝗏", # mathematical sans-serif small v - "\\msansw" => "𝗐", # mathematical sans-serif small w - "\\msansx" => "𝗑", # mathematical sans-serif small x - "\\msansy" => "𝗒", # mathematical sans-serif small y - "\\msansz" => "𝗓", # mathematical sans-serif small z - "\\mbfsansA" => "𝗔", # mathematical sans-serif bold capital a - "\\mbfsansB" => "𝗕", # mathematical sans-serif bold capital b - "\\mbfsansC" => "𝗖", # mathematical sans-serif bold capital c - "\\mbfsansD" => "𝗗", # mathematical sans-serif bold capital d - "\\mbfsansE" => "𝗘", # mathematical sans-serif bold capital e - "\\mbfsansF" => "𝗙", # mathematical sans-serif bold capital f - "\\mbfsansG" => "𝗚", # mathematical sans-serif bold capital g - "\\mbfsansH" => "𝗛", # mathematical sans-serif bold capital h - "\\mbfsansI" => "𝗜", # mathematical sans-serif bold capital i - "\\mbfsansJ" => "𝗝", # mathematical sans-serif bold capital j - "\\mbfsansK" => "𝗞", # mathematical sans-serif bold capital k - "\\mbfsansL" => "𝗟", # mathematical sans-serif bold capital l - "\\mbfsansM" => "𝗠", # mathematical sans-serif bold capital m - "\\mbfsansN" => "𝗡", # mathematical sans-serif bold capital n - "\\mbfsansO" => "𝗢", # mathematical sans-serif bold capital o - "\\mbfsansP" => "𝗣", # mathematical sans-serif bold capital p - "\\mbfsansQ" => "𝗤", # mathematical sans-serif bold capital q - "\\mbfsansR" => "𝗥", # mathematical sans-serif bold capital r - "\\mbfsansS" => "𝗦", # mathematical sans-serif bold capital s - "\\mbfsansT" => "𝗧", # mathematical sans-serif bold capital t - "\\mbfsansU" => "𝗨", # mathematical sans-serif bold capital u - "\\mbfsansV" => "𝗩", # mathematical sans-serif bold capital v - "\\mbfsansW" => "𝗪", # mathematical sans-serif bold capital w - "\\mbfsansX" => "𝗫", # mathematical sans-serif bold capital x - "\\mbfsansY" => "𝗬", # mathematical sans-serif bold capital y - "\\mbfsansZ" => "𝗭", # mathematical sans-serif bold capital z - "\\mbfsansa" => "𝗮", # mathematical sans-serif bold small a - "\\mbfsansb" => "𝗯", # mathematical sans-serif bold small b - "\\mbfsansc" => "𝗰", # mathematical sans-serif bold small c - "\\mbfsansd" => "𝗱", # mathematical sans-serif bold small d - "\\mbfsanse" => "𝗲", # mathematical sans-serif bold small e - "\\mbfsansf" => "𝗳", # mathematical sans-serif bold small f - "\\mbfsansg" => "𝗴", # mathematical sans-serif bold small g - "\\mbfsansh" => "𝗵", # mathematical sans-serif bold small h - "\\mbfsansi" => "𝗶", # mathematical sans-serif bold small i - "\\mbfsansj" => "𝗷", # mathematical sans-serif bold small j - "\\mbfsansk" => "𝗸", # mathematical sans-serif bold small k - "\\mbfsansl" => "𝗹", # mathematical sans-serif bold small l - "\\mbfsansm" => "𝗺", # mathematical sans-serif bold small m - "\\mbfsansn" => "𝗻", # mathematical sans-serif bold small n - "\\mbfsanso" => "𝗼", # mathematical sans-serif bold small o - "\\mbfsansp" => "𝗽", # mathematical sans-serif bold small p - "\\mbfsansq" => "𝗾", # mathematical sans-serif bold small q - "\\mbfsansr" => "𝗿", # mathematical sans-serif bold small r - "\\mbfsanss" => "𝘀", # mathematical sans-serif bold small s - "\\mbfsanst" => "𝘁", # mathematical sans-serif bold small t - "\\mbfsansu" => "𝘂", # mathematical sans-serif bold small u - "\\mbfsansv" => "𝘃", # mathematical sans-serif bold small v - "\\mbfsansw" => "𝘄", # mathematical sans-serif bold small w - "\\mbfsansx" => "𝘅", # mathematical sans-serif bold small x - "\\mbfsansy" => "𝘆", # mathematical sans-serif bold small y - "\\mbfsansz" => "𝘇", # mathematical sans-serif bold small z - "\\mitsansA" => "𝘈", # mathematical sans-serif italic capital a - "\\mitsansB" => "𝘉", # mathematical sans-serif italic capital b - "\\mitsansC" => "𝘊", # mathematical sans-serif italic capital c - "\\mitsansD" => "𝘋", # mathematical sans-serif italic capital d - "\\mitsansE" => "𝘌", # mathematical sans-serif italic capital e - "\\mitsansF" => "𝘍", # mathematical sans-serif italic capital f - "\\mitsansG" => "𝘎", # mathematical sans-serif italic capital g - "\\mitsansH" => "𝘏", # mathematical sans-serif italic capital h - "\\mitsansI" => "𝘐", # mathematical sans-serif italic capital i - "\\mitsansJ" => "𝘑", # mathematical sans-serif italic capital j - "\\mitsansK" => "𝘒", # mathematical sans-serif italic capital k - "\\mitsansL" => "𝘓", # mathematical sans-serif italic capital l - "\\mitsansM" => "𝘔", # mathematical sans-serif italic capital m - "\\mitsansN" => "𝘕", # mathematical sans-serif italic capital n - "\\mitsansO" => "𝘖", # mathematical sans-serif italic capital o - "\\mitsansP" => "𝘗", # mathematical sans-serif italic capital p - "\\mitsansQ" => "𝘘", # mathematical sans-serif italic capital q - "\\mitsansR" => "𝘙", # mathematical sans-serif italic capital r - "\\mitsansS" => "𝘚", # mathematical sans-serif italic capital s - "\\mitsansT" => "𝘛", # mathematical sans-serif italic capital t - "\\mitsansU" => "𝘜", # mathematical sans-serif italic capital u - "\\mitsansV" => "𝘝", # mathematical sans-serif italic capital v - "\\mitsansW" => "𝘞", # mathematical sans-serif italic capital w - "\\mitsansX" => "𝘟", # mathematical sans-serif italic capital x - "\\mitsansY" => "𝘠", # mathematical sans-serif italic capital y - "\\mitsansZ" => "𝘡", # mathematical sans-serif italic capital z - "\\mitsansa" => "𝘢", # mathematical sans-serif italic small a - "\\mitsansb" => "𝘣", # mathematical sans-serif italic small b - "\\mitsansc" => "𝘤", # mathematical sans-serif italic small c - "\\mitsansd" => "𝘥", # mathematical sans-serif italic small d - "\\mitsanse" => "𝘦", # mathematical sans-serif italic small e - "\\mitsansf" => "𝘧", # mathematical sans-serif italic small f - "\\mitsansg" => "𝘨", # mathematical sans-serif italic small g - "\\mitsansh" => "𝘩", # mathematical sans-serif italic small h - "\\mitsansi" => "𝘪", # mathematical sans-serif italic small i - "\\mitsansj" => "𝘫", # mathematical sans-serif italic small j - "\\mitsansk" => "𝘬", # mathematical sans-serif italic small k - "\\mitsansl" => "𝘭", # mathematical sans-serif italic small l - "\\mitsansm" => "𝘮", # mathematical sans-serif italic small m - "\\mitsansn" => "𝘯", # mathematical sans-serif italic small n - "\\mitsanso" => "𝘰", # mathematical sans-serif italic small o - "\\mitsansp" => "𝘱", # mathematical sans-serif italic small p - "\\mitsansq" => "𝘲", # mathematical sans-serif italic small q - "\\mitsansr" => "𝘳", # mathematical sans-serif italic small r - "\\mitsanss" => "𝘴", # mathematical sans-serif italic small s - "\\mitsanst" => "𝘵", # mathematical sans-serif italic small t - "\\mitsansu" => "𝘶", # mathematical sans-serif italic small u - "\\mitsansv" => "𝘷", # mathematical sans-serif italic small v - "\\mitsansw" => "𝘸", # mathematical sans-serif italic small w - "\\mitsansx" => "𝘹", # mathematical sans-serif italic small x - "\\mitsansy" => "𝘺", # mathematical sans-serif italic small y - "\\mitsansz" => "𝘻", # mathematical sans-serif italic small z - "\\mbfitsansA" => "𝘼", # mathematical sans-serif bold italic capital a - "\\mbfitsansB" => "𝘽", # mathematical sans-serif bold italic capital b - "\\mbfitsansC" => "𝘾", # mathematical sans-serif bold italic capital c - "\\mbfitsansD" => "𝘿", # mathematical sans-serif bold italic capital d - "\\mbfitsansE" => "𝙀", # mathematical sans-serif bold italic capital e - "\\mbfitsansF" => "𝙁", # mathematical sans-serif bold italic capital f - "\\mbfitsansG" => "𝙂", # mathematical sans-serif bold italic capital g - "\\mbfitsansH" => "𝙃", # mathematical sans-serif bold italic capital h - "\\mbfitsansI" => "𝙄", # mathematical sans-serif bold italic capital i - "\\mbfitsansJ" => "𝙅", # mathematical sans-serif bold italic capital j - "\\mbfitsansK" => "𝙆", # mathematical sans-serif bold italic capital k - "\\mbfitsansL" => "𝙇", # mathematical sans-serif bold italic capital l - "\\mbfitsansM" => "𝙈", # mathematical sans-serif bold italic capital m - "\\mbfitsansN" => "𝙉", # mathematical sans-serif bold italic capital n - "\\mbfitsansO" => "𝙊", # mathematical sans-serif bold italic capital o - "\\mbfitsansP" => "𝙋", # mathematical sans-serif bold italic capital p - "\\mbfitsansQ" => "𝙌", # mathematical sans-serif bold italic capital q - "\\mbfitsansR" => "𝙍", # mathematical sans-serif bold italic capital r - "\\mbfitsansS" => "𝙎", # mathematical sans-serif bold italic capital s - "\\mbfitsansT" => "𝙏", # mathematical sans-serif bold italic capital t - "\\mbfitsansU" => "𝙐", # mathematical sans-serif bold italic capital u - "\\mbfitsansV" => "𝙑", # mathematical sans-serif bold italic capital v - "\\mbfitsansW" => "𝙒", # mathematical sans-serif bold italic capital w - "\\mbfitsansX" => "𝙓", # mathematical sans-serif bold italic capital x - "\\mbfitsansY" => "𝙔", # mathematical sans-serif bold italic capital y - "\\mbfitsansZ" => "𝙕", # mathematical sans-serif bold italic capital z - "\\mbfitsansa" => "𝙖", # mathematical sans-serif bold italic small a - "\\mbfitsansb" => "𝙗", # mathematical sans-serif bold italic small b - "\\mbfitsansc" => "𝙘", # mathematical sans-serif bold italic small c - "\\mbfitsansd" => "𝙙", # mathematical sans-serif bold italic small d - "\\mbfitsanse" => "𝙚", # mathematical sans-serif bold italic small e - "\\mbfitsansf" => "𝙛", # mathematical sans-serif bold italic small f - "\\mbfitsansg" => "𝙜", # mathematical sans-serif bold italic small g - "\\mbfitsansh" => "𝙝", # mathematical sans-serif bold italic small h - "\\mbfitsansi" => "𝙞", # mathematical sans-serif bold italic small i - "\\mbfitsansj" => "𝙟", # mathematical sans-serif bold italic small j - "\\mbfitsansk" => "𝙠", # mathematical sans-serif bold italic small k - "\\mbfitsansl" => "𝙡", # mathematical sans-serif bold italic small l - "\\mbfitsansm" => "𝙢", # mathematical sans-serif bold italic small m - "\\mbfitsansn" => "𝙣", # mathematical sans-serif bold italic small n - "\\mbfitsanso" => "𝙤", # mathematical sans-serif bold italic small o - "\\mbfitsansp" => "𝙥", # mathematical sans-serif bold italic small p - "\\mbfitsansq" => "𝙦", # mathematical sans-serif bold italic small q - "\\mbfitsansr" => "𝙧", # mathematical sans-serif bold italic small r - "\\mbfitsanss" => "𝙨", # mathematical sans-serif bold italic small s - "\\mbfitsanst" => "𝙩", # mathematical sans-serif bold italic small t - "\\mbfitsansu" => "𝙪", # mathematical sans-serif bold italic small u - "\\mbfitsansv" => "𝙫", # mathematical sans-serif bold italic small v - "\\mbfitsansw" => "𝙬", # mathematical sans-serif bold italic small w - "\\mbfitsansx" => "𝙭", # mathematical sans-serif bold italic small x - "\\mbfitsansy" => "𝙮", # mathematical sans-serif bold italic small y - "\\mbfitsansz" => "𝙯", # mathematical sans-serif bold italic small z - "\\mttA" => "𝙰", # mathematical monospace capital a - "\\mttB" => "𝙱", # mathematical monospace capital b - "\\mttC" => "𝙲", # mathematical monospace capital c - "\\mttD" => "𝙳", # mathematical monospace capital d - "\\mttE" => "𝙴", # mathematical monospace capital e - "\\mttF" => "𝙵", # mathematical monospace capital f - "\\mttG" => "𝙶", # mathematical monospace capital g - "\\mttH" => "𝙷", # mathematical monospace capital h - "\\mttI" => "𝙸", # mathematical monospace capital i - "\\mttJ" => "𝙹", # mathematical monospace capital j - "\\mttK" => "𝙺", # mathematical monospace capital k - "\\mttL" => "𝙻", # mathematical monospace capital l - "\\mttM" => "𝙼", # mathematical monospace capital m - "\\mttN" => "𝙽", # mathematical monospace capital n - "\\mttO" => "𝙾", # mathematical monospace capital o - "\\mttP" => "𝙿", # mathematical monospace capital p - "\\mttQ" => "𝚀", # mathematical monospace capital q - "\\mttR" => "𝚁", # mathematical monospace capital r - "\\mttS" => "𝚂", # mathematical monospace capital s - "\\mttT" => "𝚃", # mathematical monospace capital t - "\\mttU" => "𝚄", # mathematical monospace capital u - "\\mttV" => "𝚅", # mathematical monospace capital v - "\\mttW" => "𝚆", # mathematical monospace capital w - "\\mttX" => "𝚇", # mathematical monospace capital x - "\\mttY" => "𝚈", # mathematical monospace capital y - "\\mttZ" => "𝚉", # mathematical monospace capital z - "\\mtta" => "𝚊", # mathematical monospace small a - "\\mttb" => "𝚋", # mathematical monospace small b - "\\mttc" => "𝚌", # mathematical monospace small c - "\\mttd" => "𝚍", # mathematical monospace small d - "\\mtte" => "𝚎", # mathematical monospace small e - "\\mttf" => "𝚏", # mathematical monospace small f - "\\mttg" => "𝚐", # mathematical monospace small g - "\\mtth" => "𝚑", # mathematical monospace small h - "\\mtti" => "𝚒", # mathematical monospace small i - "\\mttj" => "𝚓", # mathematical monospace small j - "\\mttk" => "𝚔", # mathematical monospace small k - "\\mttl" => "𝚕", # mathematical monospace small l - "\\mttm" => "𝚖", # mathematical monospace small m - "\\mttn" => "𝚗", # mathematical monospace small n - "\\mtto" => "𝚘", # mathematical monospace small o - "\\mttp" => "𝚙", # mathematical monospace small p - "\\mttq" => "𝚚", # mathematical monospace small q - "\\mttr" => "𝚛", # mathematical monospace small r - "\\mtts" => "𝚜", # mathematical monospace small s - "\\mttt" => "𝚝", # mathematical monospace small t - "\\mttu" => "𝚞", # mathematical monospace small u - "\\mttv" => "𝚟", # mathematical monospace small v - "\\mttw" => "𝚠", # mathematical monospace small w - "\\mttx" => "𝚡", # mathematical monospace small x - "\\mtty" => "𝚢", # mathematical monospace small y - "\\mttz" => "𝚣", # mathematical monospace small z - "\\imath" => "\U1d6a4", # mathematical italic small dotless i - "\\jmath" => "\U1d6a5", # mathematical italic small dotless j - "\\mbfAlpha" => "𝚨", # mathematical bold capital alpha - "\\mbfBeta" => "𝚩", # mathematical bold capital beta - "\\mbfGamma" => "𝚪", # mathematical bold capital gamma - "\\mbfDelta" => "𝚫", # mathematical bold capital delta - "\\mbfEpsilon" => "𝚬", # mathematical bold capital epsilon - "\\mbfZeta" => "𝚭", # mathematical bold capital zeta - "\\mbfEta" => "𝚮", # mathematical bold capital eta - "\\mbfTheta" => "𝚯", # mathematical bold capital theta - "\\mbfIota" => "𝚰", # mathematical bold capital iota - "\\mbfKappa" => "𝚱", # mathematical bold capital kappa - "\\mbfLambda" => "𝚲", # mathematical bold capital lambda - "\\mbfMu" => "𝚳", # mathematical bold capital mu - "\\mbfNu" => "𝚴", # mathematical bold capital nu - "\\mbfXi" => "𝚵", # mathematical bold capital xi - "\\mbfOmicron" => "𝚶", # mathematical bold capital omicron - "\\mbfPi" => "𝚷", # mathematical bold capital pi - "\\mbfRho" => "𝚸", # mathematical bold capital rho - "\\mbfvarTheta" => "𝚹", # mathematical bold capital theta symbol - "\\mbfSigma" => "𝚺", # mathematical bold capital sigma - "\\mbfTau" => "𝚻", # mathematical bold capital tau - "\\mbfUpsilon" => "𝚼", # mathematical bold capital upsilon - "\\mbfPhi" => "𝚽", # mathematical bold capital phi - "\\mbfChi" => "𝚾", # mathematical bold capital chi - "\\mbfPsi" => "𝚿", # mathematical bold capital psi - "\\mbfOmega" => "𝛀", # mathematical bold capital omega - "\\mbfnabla" => "𝛁", # mathematical bold nabla - "\\mbfalpha" => "𝛂", # mathematical bold small alpha - "\\mbfbeta" => "𝛃", # mathematical bold small beta - "\\mbfgamma" => "𝛄", # mathematical bold small gamma - "\\mbfdelta" => "𝛅", # mathematical bold small delta - "\\mbfepsilon" => "𝛆", # mathematical bold small epsilon - "\\mbfzeta" => "𝛇", # mathematical bold small zeta - "\\mbfeta" => "𝛈", # mathematical bold small eta - "\\mbftheta" => "𝛉", # mathematical bold small theta - "\\mbfiota" => "𝛊", # mathematical bold small iota - "\\mbfkappa" => "𝛋", # mathematical bold small kappa - "\\mbflambda" => "𝛌", # mathematical bold small lambda - "\\mbfmu" => "𝛍", # mathematical bold small mu - "\\mbfnu" => "𝛎", # mathematical bold small nu - "\\mbfxi" => "𝛏", # mathematical bold small xi - "\\mbfomicron" => "𝛐", # mathematical bold small omicron - "\\mbfpi" => "𝛑", # mathematical bold small pi - "\\mbfrho" => "𝛒", # mathematical bold small rho - "\\mbfvarsigma" => "𝛓", # mathematical bold small final sigma - "\\mbfsigma" => "𝛔", # mathematical bold small sigma - "\\mbftau" => "𝛕", # mathematical bold small tau - "\\mbfupsilon" => "𝛖", # mathematical bold small upsilon - "\\mbfvarphi" => "𝛗", # mathematical bold small phi - "\\mbfchi" => "𝛘", # mathematical bold small chi - "\\mbfpsi" => "𝛙", # mathematical bold small psi - "\\mbfomega" => "𝛚", # mathematical bold small omega - "\\mbfpartial" => "𝛛", # mathematical bold partial differential - "\\mbfvarepsilon" => "𝛜", # mathematical bold epsilon symbol - "\\mbfvartheta" => "𝛝", # mathematical bold theta symbol - "\\mbfvarkappa" => "𝛞", # mathematical bold kappa symbol - "\\mbfphi" => "𝛟", # mathematical bold phi symbol - "\\mbfvarrho" => "𝛠", # mathematical bold rho symbol - "\\mbfvarpi" => "𝛡", # mathematical bold pi symbol - "\\mitAlpha" => "𝛢", # mathematical italic capital alpha - "\\mitBeta" => "𝛣", # mathematical italic capital beta - "\\mitGamma" => "𝛤", # mathematical italic capital gamma - "\\mitDelta" => "𝛥", # mathematical italic capital delta - "\\mitEpsilon" => "𝛦", # mathematical italic capital epsilon - "\\mitZeta" => "𝛧", # mathematical italic capital zeta - "\\mitEta" => "𝛨", # mathematical italic capital eta - "\\mitTheta" => "𝛩", # mathematical italic capital theta - "\\mitIota" => "𝛪", # mathematical italic capital iota - "\\mitKappa" => "𝛫", # mathematical italic capital kappa - "\\mitLambda" => "𝛬", # mathematical italic capital lambda - "\\mitMu" => "𝛭", # mathematical italic capital mu - "\\mitNu" => "𝛮", # mathematical italic capital nu - "\\mitXi" => "𝛯", # mathematical italic capital xi - "\\mitOmicron" => "𝛰", # mathematical italic capital omicron - "\\mitPi" => "𝛱", # mathematical italic capital pi - "\\mitRho" => "𝛲", # mathematical italic capital rho - "\\mitvarTheta" => "𝛳", # mathematical italic capital theta symbol - "\\mitSigma" => "𝛴", # mathematical italic capital sigma - "\\mitTau" => "𝛵", # mathematical italic capital tau - "\\mitUpsilon" => "𝛶", # mathematical italic capital upsilon - "\\mitPhi" => "𝛷", # mathematical italic capital phi - "\\mitChi" => "𝛸", # mathematical italic capital chi - "\\mitPsi" => "𝛹", # mathematical italic capital psi - "\\mitOmega" => "𝛺", # mathematical italic capital omega - "\\mitnabla" => "𝛻", # mathematical italic nabla - "\\mitalpha" => "𝛼", # mathematical italic small alpha - "\\mitbeta" => "𝛽", # mathematical italic small beta - "\\mitgamma" => "𝛾", # mathematical italic small gamma - "\\mitdelta" => "𝛿", # mathematical italic small delta - "\\mitepsilon" => "𝜀", # mathematical italic small epsilon - "\\mitzeta" => "𝜁", # mathematical italic small zeta - "\\miteta" => "𝜂", # mathematical italic small eta - "\\mittheta" => "𝜃", # mathematical italic small theta - "\\mitiota" => "𝜄", # mathematical italic small iota - "\\mitkappa" => "𝜅", # mathematical italic small kappa - "\\mitlambda" => "𝜆", # mathematical italic small lambda - "\\mitmu" => "𝜇", # mathematical italic small mu - "\\mitnu" => "𝜈", # mathematical italic small nu - "\\mitxi" => "𝜉", # mathematical italic small xi - "\\mitomicron" => "𝜊", # mathematical italic small omicron - "\\mitpi" => "𝜋", # mathematical italic small pi - "\\mitrho" => "𝜌", # mathematical italic small rho - "\\mitvarsigma" => "𝜍", # mathematical italic small final sigma - "\\mitsigma" => "𝜎", # mathematical italic small sigma - "\\mittau" => "𝜏", # mathematical italic small tau - "\\mitupsilon" => "𝜐", # mathematical italic small upsilon - "\\mitphi" => "𝜑", # mathematical italic small phi - "\\mitchi" => "𝜒", # mathematical italic small chi - "\\mitpsi" => "𝜓", # mathematical italic small psi - "\\mitomega" => "𝜔", # mathematical italic small omega - "\\mitpartial" => "𝜕", # mathematical italic partial differential - "\\mitvarepsilon" => "𝜖", # mathematical italic epsilon symbol - "\\mitvartheta" => "𝜗", # mathematical italic theta symbol - "\\mitvarkappa" => "𝜘", # mathematical italic kappa symbol - "\\mitvarphi" => "𝜙", # mathematical italic phi symbol - "\\mitvarrho" => "𝜚", # mathematical italic rho symbol - "\\mitvarpi" => "𝜛", # mathematical italic pi symbol - "\\mbfitAlpha" => "𝜜", # mathematical bold italic capital alpha - "\\mbfitBeta" => "𝜝", # mathematical bold italic capital beta - "\\mbfitGamma" => "𝜞", # mathematical bold italic capital gamma - "\\mbfitDelta" => "𝜟", # mathematical bold italic capital delta - "\\mbfitEpsilon" => "𝜠", # mathematical bold italic capital epsilon - "\\mbfitZeta" => "𝜡", # mathematical bold italic capital zeta - "\\mbfitEta" => "𝜢", # mathematical bold italic capital eta - "\\mbfitTheta" => "𝜣", # mathematical bold italic capital theta - "\\mbfitIota" => "𝜤", # mathematical bold italic capital iota - "\\mbfitKappa" => "𝜥", # mathematical bold italic capital kappa - "\\mbfitLambda" => "𝜦", # mathematical bold italic capital lambda - "\\mbfitMu" => "𝜧", # mathematical bold italic capital mu - "\\mbfitNu" => "𝜨", # mathematical bold italic capital nu - "\\mbfitXi" => "𝜩", # mathematical bold italic capital xi - "\\mbfitOmicron" => "𝜪", # mathematical bold italic capital omicron - "\\mbfitPi" => "𝜫", # mathematical bold italic capital pi - "\\mbfitRho" => "𝜬", # mathematical bold italic capital rho - "\\mbfitvarTheta" => "𝜭", # mathematical bold italic capital theta symbol - "\\mbfitSigma" => "𝜮", # mathematical bold italic capital sigma - "\\mbfitTau" => "𝜯", # mathematical bold italic capital tau - "\\mbfitUpsilon" => "𝜰", # mathematical bold italic capital upsilon - "\\mbfitPhi" => "𝜱", # mathematical bold italic capital phi - "\\mbfitChi" => "𝜲", # mathematical bold italic capital chi - "\\mbfitPsi" => "𝜳", # mathematical bold italic capital psi - "\\mbfitOmega" => "𝜴", # mathematical bold italic capital omega - "\\mbfitnabla" => "𝜵", # mathematical bold italic nabla - "\\mbfitalpha" => "𝜶", # mathematical bold italic small alpha - "\\mbfitbeta" => "𝜷", # mathematical bold italic small beta - "\\mbfitgamma" => "𝜸", # mathematical bold italic small gamma - "\\mbfitdelta" => "𝜹", # mathematical bold italic small delta - "\\mbfitepsilon" => "𝜺", # mathematical bold italic small epsilon - "\\mbfitzeta" => "𝜻", # mathematical bold italic small zeta - "\\mbfiteta" => "𝜼", # mathematical bold italic small eta - "\\mbfittheta" => "𝜽", # mathematical bold italic small theta - "\\mbfitiota" => "𝜾", # mathematical bold italic small iota - "\\mbfitkappa" => "𝜿", # mathematical bold italic small kappa - "\\mbfitlambda" => "𝝀", # mathematical bold italic small lambda - "\\mbfitmu" => "𝝁", # mathematical bold italic small mu - "\\mbfitnu" => "𝝂", # mathematical bold italic small nu - "\\mbfitxi" => "𝝃", # mathematical bold italic small xi - "\\mbfitomicron" => "𝝄", # mathematical bold italic small omicron - "\\mbfitpi" => "𝝅", # mathematical bold italic small pi - "\\mbfitrho" => "𝝆", # mathematical bold italic small rho - "\\mbfitvarsigma" => "𝝇", # mathematical bold italic small final sigma - "\\mbfitsigma" => "𝝈", # mathematical bold italic small sigma - "\\mbfittau" => "𝝉", # mathematical bold italic small tau - "\\mbfitupsilon" => "𝝊", # mathematical bold italic small upsilon - "\\mbfitphi" => "𝝋", # mathematical bold italic small phi - "\\mbfitchi" => "𝝌", # mathematical bold italic small chi - "\\mbfitpsi" => "𝝍", # mathematical bold italic small psi - "\\mbfitomega" => "𝝎", # mathematical bold italic small omega - "\\mbfitpartial" => "𝝏", # mathematical bold italic partial differential - "\\mbfitvarepsilon" => "𝝐", # mathematical bold italic epsilon symbol - "\\mbfitvartheta" => "𝝑", # mathematical bold italic theta symbol - "\\mbfitvarkappa" => "𝝒", # mathematical bold italic kappa symbol - "\\mbfitvarphi" => "𝝓", # mathematical bold italic phi symbol - "\\mbfitvarrho" => "𝝔", # mathematical bold italic rho symbol - "\\mbfitvarpi" => "𝝕", # mathematical bold italic pi symbol - "\\mbfsansAlpha" => "𝝖", # mathematical sans-serif bold capital alpha - "\\mbfsansBeta" => "𝝗", # mathematical sans-serif bold capital beta - "\\mbfsansGamma" => "𝝘", # mathematical sans-serif bold capital gamma - "\\mbfsansDelta" => "𝝙", # mathematical sans-serif bold capital delta - "\\mbfsansEpsilon" => "𝝚", # mathematical sans-serif bold capital epsilon - "\\mbfsansZeta" => "𝝛", # mathematical sans-serif bold capital zeta - "\\mbfsansEta" => "𝝜", # mathematical sans-serif bold capital eta - "\\mbfsansTheta" => "𝝝", # mathematical sans-serif bold capital theta - "\\mbfsansIota" => "𝝞", # mathematical sans-serif bold capital iota - "\\mbfsansKappa" => "𝝟", # mathematical sans-serif bold capital kappa - "\\mbfsansLambda" => "𝝠", # mathematical sans-serif bold capital lambda - "\\mbfsansMu" => "𝝡", # mathematical sans-serif bold capital mu - "\\mbfsansNu" => "𝝢", # mathematical sans-serif bold capital nu - "\\mbfsansXi" => "𝝣", # mathematical sans-serif bold capital xi - "\\mbfsansOmicron" => "𝝤", # mathematical sans-serif bold capital omicron - "\\mbfsansPi" => "𝝥", # mathematical sans-serif bold capital pi - "\\mbfsansRho" => "𝝦", # mathematical sans-serif bold capital rho - "\\mbfsansvarTheta" => "𝝧", # mathematical sans-serif bold capital theta symbol - "\\mbfsansSigma" => "𝝨", # mathematical sans-serif bold capital sigma - "\\mbfsansTau" => "𝝩", # mathematical sans-serif bold capital tau - "\\mbfsansUpsilon" => "𝝪", # mathematical sans-serif bold capital upsilon - "\\mbfsansPhi" => "𝝫", # mathematical sans-serif bold capital phi - "\\mbfsansChi" => "𝝬", # mathematical sans-serif bold capital chi - "\\mbfsansPsi" => "𝝭", # mathematical sans-serif bold capital psi - "\\mbfsansOmega" => "𝝮", # mathematical sans-serif bold capital omega - "\\mbfsansnabla" => "𝝯", # mathematical sans-serif bold nabla - "\\mbfsansalpha" => "𝝰", # mathematical sans-serif bold small alpha - "\\mbfsansbeta" => "𝝱", # mathematical sans-serif bold small beta - "\\mbfsansgamma" => "𝝲", # mathematical sans-serif bold small gamma - "\\mbfsansdelta" => "𝝳", # mathematical sans-serif bold small delta - "\\mbfsansepsilon" => "𝝴", # mathematical sans-serif bold small epsilon - "\\mbfsanszeta" => "𝝵", # mathematical sans-serif bold small zeta - "\\mbfsanseta" => "𝝶", # mathematical sans-serif bold small eta - "\\mbfsanstheta" => "𝝷", # mathematical sans-serif bold small theta - "\\mbfsansiota" => "𝝸", # mathematical sans-serif bold small iota - "\\mbfsanskappa" => "𝝹", # mathematical sans-serif bold small kappa - "\\mbfsanslambda" => "𝝺", # mathematical sans-serif bold small lambda - "\\mbfsansmu" => "𝝻", # mathematical sans-serif bold small mu - "\\mbfsansnu" => "𝝼", # mathematical sans-serif bold small nu - "\\mbfsansxi" => "𝝽", # mathematical sans-serif bold small xi - "\\mbfsansomicron" => "𝝾", # mathematical sans-serif bold small omicron - "\\mbfsanspi" => "𝝿", # mathematical sans-serif bold small pi - "\\mbfsansrho" => "𝞀", # mathematical sans-serif bold small rho - "\\mbfsansvarsigma" => "𝞁", # mathematical sans-serif bold small final sigma - "\\mbfsanssigma" => "𝞂", # mathematical sans-serif bold small sigma - "\\mbfsanstau" => "𝞃", # mathematical sans-serif bold small tau - "\\mbfsansupsilon" => "𝞄", # mathematical sans-serif bold small upsilon - "\\mbfsansphi" => "𝞅", # mathematical sans-serif bold small phi - "\\mbfsanschi" => "𝞆", # mathematical sans-serif bold small chi - "\\mbfsanspsi" => "𝞇", # mathematical sans-serif bold small psi - "\\mbfsansomega" => "𝞈", # mathematical sans-serif bold small omega - "\\mbfsanspartial" => "𝞉", # mathematical sans-serif bold partial differential - "\\mbfsansvarepsilon" => "𝞊", # mathematical sans-serif bold epsilon symbol - "\\mbfsansvartheta" => "𝞋", # mathematical sans-serif bold theta symbol - "\\mbfsansvarkappa" => "𝞌", # mathematical sans-serif bold kappa symbol - "\\mbfsansvarphi" => "𝞍", # mathematical sans-serif bold phi symbol - "\\mbfsansvarrho" => "𝞎", # mathematical sans-serif bold rho symbol - "\\mbfsansvarpi" => "𝞏", # mathematical sans-serif bold pi symbol - "\\mbfitsansAlpha" => "𝞐", # mathematical sans-serif bold italic capital alpha - "\\mbfitsansBeta" => "𝞑", # mathematical sans-serif bold italic capital beta - "\\mbfitsansGamma" => "𝞒", # mathematical sans-serif bold italic capital gamma - "\\mbfitsansDelta" => "𝞓", # mathematical sans-serif bold italic capital delta - "\\mbfitsansEpsilon" => "𝞔", # mathematical sans-serif bold italic capital epsilon - "\\mbfitsansZeta" => "𝞕", # mathematical sans-serif bold italic capital zeta - "\\mbfitsansEta" => "𝞖", # mathematical sans-serif bold italic capital eta - "\\mbfitsansTheta" => "𝞗", # mathematical sans-serif bold italic capital theta - "\\mbfitsansIota" => "𝞘", # mathematical sans-serif bold italic capital iota - "\\mbfitsansKappa" => "𝞙", # mathematical sans-serif bold italic capital kappa - "\\mbfitsansLambda" => "𝞚", # mathematical sans-serif bold italic capital lambda - "\\mbfitsansMu" => "𝞛", # mathematical sans-serif bold italic capital mu - "\\mbfitsansNu" => "𝞜", # mathematical sans-serif bold italic capital nu - "\\mbfitsansXi" => "𝞝", # mathematical sans-serif bold italic capital xi - "\\mbfitsansOmicron" => "𝞞", # mathematical sans-serif bold italic capital omicron - "\\mbfitsansPi" => "𝞟", # mathematical sans-serif bold italic capital pi - "\\mbfitsansRho" => "𝞠", # mathematical sans-serif bold italic capital rho - "\\mbfitsansvarTheta" => "𝞡", # mathematical sans-serif bold italic capital theta symbol - "\\mbfitsansSigma" => "𝞢", # mathematical sans-serif bold italic capital sigma - "\\mbfitsansTau" => "𝞣", # mathematical sans-serif bold italic capital tau - "\\mbfitsansUpsilon" => "𝞤", # mathematical sans-serif bold italic capital upsilon - "\\mbfitsansPhi" => "𝞥", # mathematical sans-serif bold italic capital phi - "\\mbfitsansChi" => "𝞦", # mathematical sans-serif bold italic capital chi - "\\mbfitsansPsi" => "𝞧", # mathematical sans-serif bold italic capital psi - "\\mbfitsansOmega" => "𝞨", # mathematical sans-serif bold italic capital omega - "\\mbfitsansnabla" => "𝞩", # mathematical sans-serif bold italic nabla - "\\mbfitsansalpha" => "𝞪", # mathematical sans-serif bold italic small alpha - "\\mbfitsansbeta" => "𝞫", # mathematical sans-serif bold italic small beta - "\\mbfitsansgamma" => "𝞬", # mathematical sans-serif bold italic small gamma - "\\mbfitsansdelta" => "𝞭", # mathematical sans-serif bold italic small delta - "\\mbfitsansepsilon" => "𝞮", # mathematical sans-serif bold italic small epsilon - "\\mbfitsanszeta" => "𝞯", # mathematical sans-serif bold italic small zeta - "\\mbfitsanseta" => "𝞰", # mathematical sans-serif bold italic small eta - "\\mbfitsanstheta" => "𝞱", # mathematical sans-serif bold italic small theta - "\\mbfitsansiota" => "𝞲", # mathematical sans-serif bold italic small iota - "\\mbfitsanskappa" => "𝞳", # mathematical sans-serif bold italic small kappa - "\\mbfitsanslambda" => "𝞴", # mathematical sans-serif bold italic small lambda - "\\mbfitsansmu" => "𝞵", # mathematical sans-serif bold italic small mu - "\\mbfitsansnu" => "𝞶", # mathematical sans-serif bold italic small nu - "\\mbfitsansxi" => "𝞷", # mathematical sans-serif bold italic small xi - "\\mbfitsansomicron" => "𝞸", # mathematical sans-serif bold italic small omicron - "\\mbfitsanspi" => "𝞹", # mathematical sans-serif bold italic small pi - "\\mbfitsansrho" => "𝞺", # mathematical sans-serif bold italic small rho - "\\mbfitsansvarsigma" => "𝞻", # mathematical sans-serif bold italic small final sigma - "\\mbfitsanssigma" => "𝞼", # mathematical sans-serif bold italic small sigma - "\\mbfitsanstau" => "𝞽", # mathematical sans-serif bold italic small tau - "\\mbfitsansupsilon" => "𝞾", # mathematical sans-serif bold italic small upsilon - "\\mbfitsansphi" => "𝞿", # mathematical sans-serif bold italic small phi - "\\mbfitsanschi" => "𝟀", # mathematical sans-serif bold italic small chi - "\\mbfitsanspsi" => "𝟁", # mathematical sans-serif bold italic small psi - "\\mbfitsansomega" => "𝟂", # mathematical sans-serif bold italic small omega - "\\mbfitsanspartial" => "𝟃", # mathematical sans-serif bold italic partial differential - "\\mbfitsansvarepsilon" => "𝟄", # mathematical sans-serif bold italic epsilon symbol - "\\mbfitsansvartheta" => "𝟅", # mathematical sans-serif bold italic theta symbol - "\\mbfitsansvarkappa" => "𝟆", # mathematical sans-serif bold italic kappa symbol - "\\mbfitsansvarphi" => "𝟇", # mathematical sans-serif bold italic phi symbol - "\\mbfitsansvarrho" => "𝟈", # mathematical sans-serif bold italic rho symbol - "\\mbfitsansvarpi" => "𝟉", # mathematical sans-serif bold italic pi symbol - "\\mbfDigamma" => "\U1d7ca", # mathematical bold capital digamma - "\\mbfdigamma" => "\U1d7cb", # mathematical bold small digamma - "\\mbfzero" => "𝟎", # mathematical bold digit 0 - "\\mbfone" => "𝟏", # mathematical bold digit 1 - "\\mbftwo" => "𝟐", # mathematical bold digit 2 - "\\mbfthree" => "𝟑", # mathematical bold digit 3 - "\\mbffour" => "𝟒", # mathematical bold digit 4 - "\\mbffive" => "𝟓", # mathematical bold digit 5 - "\\mbfsix" => "𝟔", # mathematical bold digit 6 - "\\mbfseven" => "𝟕", # mathematical bold digit 7 - "\\mbfeight" => "𝟖", # mathematical bold digit 8 - "\\mbfnine" => "𝟗", # mathematical bold digit 9 - "\\Bbbzero" => "𝟘", # mathematical double-struck digit 0 - "\\Bbbone" => "𝟙", # mathematical double-struck digit 1 - "\\Bbbtwo" => "𝟚", # mathematical double-struck digit 2 - "\\Bbbthree" => "𝟛", # mathematical double-struck digit 3 - "\\Bbbfour" => "𝟜", # mathematical double-struck digit 4 - "\\Bbbfive" => "𝟝", # mathematical double-struck digit 5 - "\\Bbbsix" => "𝟞", # mathematical double-struck digit 6 - "\\Bbbseven" => "𝟟", # mathematical double-struck digit 7 - "\\Bbbeight" => "𝟠", # mathematical double-struck digit 8 - "\\Bbbnine" => "𝟡", # mathematical double-struck digit 9 - "\\msanszero" => "𝟢", # mathematical sans-serif digit 0 - "\\msansone" => "𝟣", # mathematical sans-serif digit 1 - "\\msanstwo" => "𝟤", # mathematical sans-serif digit 2 - "\\msansthree" => "𝟥", # mathematical sans-serif digit 3 - "\\msansfour" => "𝟦", # mathematical sans-serif digit 4 - "\\msansfive" => "𝟧", # mathematical sans-serif digit 5 - "\\msanssix" => "𝟨", # mathematical sans-serif digit 6 - "\\msansseven" => "𝟩", # mathematical sans-serif digit 7 - "\\msanseight" => "𝟪", # mathematical sans-serif digit 8 - "\\msansnine" => "𝟫", # mathematical sans-serif digit 9 - "\\mbfsanszero" => "𝟬", # mathematical sans-serif bold digit 0 - "\\mbfsansone" => "𝟭", # mathematical sans-serif bold digit 1 - "\\mbfsanstwo" => "𝟮", # mathematical sans-serif bold digit 2 - "\\mbfsansthree" => "𝟯", # mathematical sans-serif bold digit 3 - "\\mbfsansfour" => "𝟰", # mathematical sans-serif bold digit 4 - "\\mbfsansfive" => "𝟱", # mathematical sans-serif bold digit 5 - "\\mbfsanssix" => "𝟲", # mathematical sans-serif bold digit 6 - "\\mbfsansseven" => "𝟳", # mathematical sans-serif bold digit 7 - "\\mbfsanseight" => "𝟴", # mathematical sans-serif bold digit 8 - "\\mbfsansnine" => "𝟵", # mathematical sans-serif bold digit 9 - "\\mttzero" => "𝟶", # mathematical monospace digit 0 - "\\mttone" => "𝟷", # mathematical monospace digit 1 - "\\mtttwo" => "𝟸", # mathematical monospace digit 2 - "\\mttthree" => "𝟹", # mathematical monospace digit 3 - "\\mttfour" => "𝟺", # mathematical monospace digit 4 - "\\mttfive" => "𝟻", # mathematical monospace digit 5 - "\\mttsix" => "𝟼", # mathematical monospace digit 6 - "\\mttseven" => "𝟽", # mathematical monospace digit 7 - "\\mtteight" => "𝟾", # mathematical monospace digit 8 - "\\mttnine" => "𝟿", # mathematical monospace digit 9 - - "\\triangleright" => "▷", # (large) right triangle, open; z notation range restriction - "\\triangleleft" => "◁", # (large) left triangle, open; z notation domain restriction - "\\leftouterjoin" => "⟕", # left outer join - "\\rightouterjoin" => "⟖", # right outer join - "\\fullouterjoin" => "⟗", # full outer join - "\\Join" => "⨝", # join - "\\underbar" => "̲", # combining low line - "\\underleftrightarrow" => "͍", # underleftrightarrow accent - "\\leftwavearrow" => "↜", # left arrow-wavy - "\\rightwavearrow" => "↝", # right arrow-wavy - "\\varbarwedge" => "⌅", # /barwedge b: logical and, bar above [projective (bar over small wedge)] - "\\smallblacktriangleright" => "▸", # right triangle, filled - "\\smallblacktriangleleft" => "◂", # left triangle, filled - "\\leftmoon" => "☾", # last quarter moon - "\\smalltriangleright" => "▹", # right triangle, open - "\\smalltriangleleft" => "◃", # left triangle, open - -) diff --git a/julia-0.6.3/share/julia/base/libc.jl b/julia-0.6.3/share/julia/base/libc.jl deleted file mode 100644 index bfce78f..0000000 --- a/julia-0.6.3/share/julia/base/libc.jl +++ /dev/null @@ -1,350 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -module Libc - -import Base: transcode - -export FILE, TmStruct, strftime, strptime, getpid, gethostname, free, malloc, calloc, realloc, - errno, strerror, flush_cstdio, systemsleep, time, transcode -if is_windows() - export GetLastError, FormatMessage -end - -include(string(length(Core.ARGS)>=2?Core.ARGS[2]:"","errno_h.jl")) # include($BUILDROOT/base/errno_h.jl) - -## RawFD ## - -# Wrapper for an OS file descriptor (on both Unix and Windows) -struct RawFD - fd::Int32 - RawFD(fd::Integer) = new(fd) - RawFD(fd::RawFD) = fd -end - -Base.cconvert(::Type{Int32}, fd::RawFD) = fd.fd - -dup(x::RawFD) = RawFD(ccall((@static is_windows() ? :_dup : :dup), Int32, (Int32,), x.fd)) -dup(src::RawFD, target::RawFD) = systemerror("dup", -1 == - ccall((@static is_windows() ? :_dup2 : :dup2), Int32, - (Int32, Int32), src.fd, target.fd)) - -# Wrapper for an OS file descriptor (for Windows) -if is_windows() - struct WindowsRawSocket - handle::Ptr{Void} # On Windows file descriptors are HANDLE's and 64-bit on 64-bit Windows - end - Base.cconvert(::Type{Ptr{Void}}, fd::WindowsRawSocket) = fd.handle - _get_osfhandle(fd::RawFD) = WindowsRawSocket(ccall(:_get_osfhandle, Ptr{Void}, (Cint,), fd.fd)) - _get_osfhandle(fd::WindowsRawSocket) = fd - function dup(src::WindowsRawSocket) - new_handle = Ref{Ptr{Void}}(-1) - my_process = ccall(:GetCurrentProcess, stdcall, Ptr{Void}, ()) - const DUPLICATE_SAME_ACCESS = 0x2 - status = ccall(:DuplicateHandle, stdcall, Int32, - (Ptr{Void}, Ptr{Void}, Ptr{Void}, Ptr{Ptr{Void}}, UInt32, Int32, UInt32), - my_process, src.handle, my_process, new_handle, 0, false, DUPLICATE_SAME_ACCESS) - status == 0 && error("dup failed: $(FormatMessage())") - return new_handle[] - end - function dup(src::WindowsRawSocket, target::RawFD) - fd = ccall(:_open_osfhandle, Int32, (Ptr{Void}, Int32), dup(src), 0) - dup(RawFD(fd), target) - ccall(:_close, Int32, (Int32,), fd) - nothing - end - -else - _get_osfhandle(fd::RawFD) = fd -end - -## FILE (not auto-finalized) ## - -struct FILE - ptr::Ptr{Void} -end - -modestr(s::IO) = modestr(isreadable(s), iswritable(s)) -modestr(r::Bool, w::Bool) = r ? (w ? "r+" : "r") : (w ? "w" : throw(ArgumentError("neither readable nor writable"))) - -function FILE(fd::RawFD, mode) - FILEp = ccall((@static is_windows() ? :_fdopen : :fdopen), Ptr{Void}, (Cint, Cstring), fd, mode) - systemerror("fdopen", FILEp == C_NULL) - FILE(FILEp) -end - -function FILE(s::IO) - f = FILE(dup(RawFD(fd(s))),modestr(s)) - seek(f, position(s)) - f -end - -Base.unsafe_convert(T::Union{Type{Ptr{Void}},Type{Ptr{FILE}}}, f::FILE) = convert(T, f.ptr) -Base.close(f::FILE) = systemerror("fclose", ccall(:fclose, Cint, (Ptr{Void},), f.ptr) != 0) -Base.convert(::Type{FILE}, s::IO) = FILE(s) - -function Base.seek(h::FILE, offset::Integer) - systemerror("fseek", ccall(:fseek, Cint, (Ptr{Void}, Clong, Cint), - h.ptr, offset, 0) != 0) - h -end - -Base.position(h::FILE) = ccall(:ftell, Clong, (Ptr{Void},), h.ptr) - -# flush C stdio output from external libraries - -""" - flush_cstdio() - -Flushes the C `stdout` and `stderr` streams (which may have been written to by external C code). -""" -flush_cstdio() = ccall(:jl_flush_cstdio, Void, ()) - -## time-related functions ## - -# TODO: check for usleep errors? -if is_unix() - systemsleep(s::Real) = ccall(:usleep, Int32, (UInt32,), round(UInt32, s*1e6)) -elseif is_windows() - function systemsleep(s::Real) - ccall(:Sleep, stdcall, Void, (UInt32,), round(UInt32, s * 1e3)) - return Int32(0) - end -else - error("systemsleep undefined for this OS") -end - -struct TimeVal - sec::Int64 - usec::Int64 -end - -function TimeVal() - tv = Ref{TimeVal}() - status = ccall(:jl_gettimeofday, Cint, (Ref{TimeVal},), tv) - status != 0 && error("unable to determine current time: ", status) - return tv[] -end - -""" - TmStruct([seconds]) - -Convert a number of seconds since the epoch to broken-down format, with fields `sec`, `min`, -`hour`, `mday`, `month`, `year`, `wday`, `yday`, and `isdst`. -""" -mutable struct TmStruct - sec::Int32 - min::Int32 - hour::Int32 - mday::Int32 - month::Int32 - year::Int32 - wday::Int32 - yday::Int32 - isdst::Int32 - # on some platforms the struct is 14 words, even though 9 are specified - _10::Int32 - _11::Int32 - _12::Int32 - _13::Int32 - _14::Int32 - - TmStruct(sec, min, hour, mday, month, year, wday, yday, isdst) = - new(sec, min, hour, mday, month, year, wday, yday, isdst, 0,0,0,0,0) - TmStruct() = new(0,0,0,0,0,0,0,0,0,0,0,0,0,0) - function TmStruct(t::Real) - t = floor(t) - tm = TmStruct() - # TODO: add support for UTC via gmtime_r() - ccall(:localtime_r, Ptr{TmStruct}, (Ptr{Int}, Ptr{TmStruct}), &t, &tm) - return tm - end -end - -""" - strftime([format], time) - -Convert time, given as a number of seconds since the epoch or a `TmStruct`, to a formatted -string using the given format. Supported formats are the same as those in the standard C -library. -""" -strftime(t) = strftime("%c", t) -strftime(fmt::AbstractString, t::Real) = strftime(fmt, TmStruct(t)) -function strftime(fmt::AbstractString, tm::TmStruct) - timestr = Vector{UInt8}(128) - n = ccall(:strftime, Int, (Ptr{UInt8}, Int, Cstring, Ptr{TmStruct}), - timestr, length(timestr), fmt, &tm) - if n == 0 - return "" - end - return String(timestr[1:n]) -end - -""" - strptime([format], timestr) - -Parse a formatted time string into a `TmStruct` giving the seconds, minute, hour, date, etc. -Supported formats are the same as those in the standard C library. On some platforms, -timezones will not be parsed correctly. If the result of this function will be passed to -`time` to convert it to seconds since the epoch, the `isdst` field should be filled in -manually. Setting it to `-1` will tell the C library to use the current system settings to -determine the timezone. -""" -strptime(timestr::AbstractString) = strptime("%c", timestr) -function strptime(fmt::AbstractString, timestr::AbstractString) - tm = TmStruct() - r = ccall(:strptime, Cstring, (Cstring, Cstring, Ptr{TmStruct}), - timestr, fmt, &tm) - # the following would tell mktime() that this is a local time, and that - # it should try to guess the timezone. not sure if/how this should be - # exposed in the API. - # tm.isdst = -1 - if r == C_NULL - # TODO: better error message - throw(ArgumentError("invalid arguments")) - end - @static if is_apple() - # if we didn't explicitly parse the weekday or year day, use mktime - # to fill them in automatically. - if !ismatch(r"([^%]|^)%(a|A|j|w|Ow)", fmt) - ccall(:mktime, Int, (Ptr{TmStruct},), &tm) - end - end - return tm -end - -# system date in seconds - -""" - time(t::TmStruct) - -Converts a `TmStruct` struct to a number of seconds since the epoch. -""" -time(tm::TmStruct) = Float64(ccall(:mktime, Int, (Ptr{TmStruct},), &tm)) -time() = ccall(:jl_clock_now, Float64, ()) - -## process-related functions ## - -""" - getpid() -> Int32 - -Get Julia's process ID. -""" -getpid() = ccall(:jl_getpid, Int32, ()) - -## network functions ## - -""" - gethostname() -> AbstractString - -Get the local machine's host name. -""" -function gethostname() - hn = Vector{UInt8}(256) - err = @static if is_windows() - ccall(:gethostname, stdcall, Int32, (Ptr{UInt8}, UInt32), hn, length(hn)) - else - ccall(:gethostname, Int32, (Ptr{UInt8}, UInt), hn, length(hn)) - end - systemerror("gethostname", err != 0) - return unsafe_string(pointer(hn)) -end - -## system error handling ## - -""" - errno([code]) - -Get the value of the C library's `errno`. If an argument is specified, it is used to set the -value of `errno`. - -The value of `errno` is only valid immediately after a `ccall` to a C library routine that -sets it. Specifically, you cannot call `errno` at the next prompt in a REPL, because lots of -code is executed between prompts. -""" -errno() = ccall(:jl_errno, Cint, ()) -errno(e::Integer) = ccall(:jl_set_errno, Void, (Cint,), e) - -""" - strerror(n=errno()) - -Convert a system call error code to a descriptive string -""" -strerror(e::Integer) = unsafe_string(ccall(:strerror, Cstring, (Int32,), e)) -strerror() = strerror(errno()) - -""" - GetLastError() - -Call the Win32 `GetLastError` function [only available on Windows]. -""" -function GetLastError end - -""" - FormatMessage(n=GetLastError()) - -Convert a Win32 system call error code to a descriptive string [only available on Windows]. -""" -function FormatMessage end - -if is_windows() - GetLastError() = ccall(:GetLastError, stdcall, UInt32, ()) - - function FormatMessage(e=GetLastError()) - const FORMAT_MESSAGE_ALLOCATE_BUFFER = UInt32(0x100) - const FORMAT_MESSAGE_FROM_SYSTEM = UInt32(0x1000) - const FORMAT_MESSAGE_IGNORE_INSERTS = UInt32(0x200) - const FORMAT_MESSAGE_MAX_WIDTH_MASK = UInt32(0xFF) - lpMsgBuf = Ref{Ptr{UInt16}}() - lpMsgBuf[] = 0 - len = ccall(:FormatMessageW, stdcall, UInt32, (Cint, Ptr{Void}, Cint, Cint, Ptr{Ptr{UInt16}}, Cint, Ptr{Void}), - FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_MAX_WIDTH_MASK, - C_NULL, e, 0, lpMsgBuf, 0, C_NULL) - p = lpMsgBuf[] - len == 0 && return "" - buf = Vector{UInt16}(len) - unsafe_copy!(pointer(buf), p, len) - ccall(:LocalFree, stdcall, Ptr{Void}, (Ptr{Void},), p) - return transcode(String, buf) - end -end - -## Memory related ## - -""" - free(addr::Ptr) - -Call `free` from the C standard library. Only use this on memory obtained from `malloc`, not -on pointers retrieved from other C libraries. `Ptr` objects obtained from C libraries should -be freed by the free functions defined in that library, to avoid assertion failures if -multiple `libc` libraries exist on the system. -""" -free(p::Ptr) = ccall(:free, Void, (Ptr{Void},), p) - -""" - malloc(size::Integer) -> Ptr{Void} - -Call `malloc` from the C standard library. -""" -malloc(size::Integer) = ccall(:malloc, Ptr{Void}, (Csize_t,), size) - -""" - realloc(addr::Ptr, size::Integer) -> Ptr{Void} - -Call `realloc` from the C standard library. - -See warning in the documentation for `free` regarding only using this on memory originally -obtained from `malloc`. -""" -realloc(p::Ptr, size::Integer) = ccall(:realloc, Ptr{Void}, (Ptr{Void}, Csize_t), p, size) - -""" - calloc(num::Integer, size::Integer) -> Ptr{Void} - -Call `calloc` from the C standard library. -""" -calloc(num::Integer, size::Integer) = ccall(:calloc, Ptr{Void}, (Csize_t, Csize_t), num, size) - -free(p::Cstring) = free(convert(Ptr{UInt8}, p)) -free(p::Cwstring) = free(convert(Ptr{Cwchar_t}, p)) - -end # module diff --git a/julia-0.6.3/share/julia/base/libdl.jl b/julia-0.6.3/share/julia/base/libdl.jl deleted file mode 100644 index c15ab2a..0000000 --- a/julia-0.6.3/share/julia/base/libdl.jl +++ /dev/null @@ -1,266 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -module Libdl - -export DL_LOAD_PATH, RTLD_DEEPBIND, RTLD_FIRST, RTLD_GLOBAL, RTLD_LAZY, RTLD_LOCAL, - RTLD_NODELETE, RTLD_NOLOAD, RTLD_NOW, dlclose, dlopen, dlopen_e, dlsym, dlsym_e, - dlpath, find_library, dlext, dllist - -""" - DL_LOAD_PATH - -When calling [`dlopen`](@ref), the paths in this list will be searched first, in -order, before searching the system locations for a valid library handle. -""" -const DL_LOAD_PATH = String[] -if is_apple() - push!(DL_LOAD_PATH, "@loader_path/julia") - push!(DL_LOAD_PATH, "@loader_path") -end - -# note: constants to match JL_RTLD_* in src/julia.h, translated -# to system-specific values by JL_RTLD macro in src/dlload.c -const RTLD_LOCAL = 0x00000001 -const RTLD_GLOBAL = 0x00000002 -const RTLD_LAZY = 0x00000004 -const RTLD_NOW = 0x00000008 -const RTLD_NODELETE = 0x00000010 -const RTLD_NOLOAD = 0x00000020 -const RTLD_DEEPBIND = 0x00000040 -const RTLD_FIRST = 0x00000080 - -@doc """ - RTLD_DEEPBIND - RTLD_FIRST - RTLD_GLOBAL - RTLD_LAZY - RTLD_LOCAL - RTLD_NODELETE - RTLD_NOLOAD - RTLD_NOW - -Enum constant for [`dlopen`](@ref). See your platform man page for details, if -applicable. -""" -> -(RTLD_DEEPBIND, RTLD_FIRST, RTLD_GLOBAL, RTLD_LAZY, RTLD_LOCAL, RTLD_NODELETE, RTLD_NOLOAD, RTLD_NOW) - - -""" - dlsym(handle, sym) - -Look up a symbol from a shared library handle, return callable function pointer on success. -""" -function dlsym(hnd::Ptr, s::Union{Symbol,AbstractString}) - hnd == C_NULL && throw(ArgumentError("NULL library handle")) - ccall(:jl_dlsym, Ptr{Void}, (Ptr{Void}, Cstring), hnd, s) -end - -""" - dlsym_e(handle, sym) - -Look up a symbol from a shared library handle, silently return `NULL` pointer on lookup failure. -""" -function dlsym_e(hnd::Ptr, s::Union{Symbol,AbstractString}) - hnd == C_NULL && throw(ArgumentError("NULL library handle")) - ccall(:jl_dlsym_e, Ptr{Void}, (Ptr{Void}, Cstring), hnd, s) -end - -""" - dlopen(libfile::AbstractString [, flags::Integer]) - -Load a shared library, returning an opaque handle. - -The extension given by the constant `dlext` (`.so`, `.dll`, or `.dylib`) -can be omitted from the `libfile` string, as it is automatically appended -if needed. If `libfile` is not an absolute path name, then the paths -in the array `DL_LOAD_PATH` are searched for `libfile`, followed by the -system load path. - -The optional flags argument is a bitwise-or of zero or more of `RTLD_LOCAL`, `RTLD_GLOBAL`, -`RTLD_LAZY`, `RTLD_NOW`, `RTLD_NODELETE`, `RTLD_NOLOAD`, `RTLD_DEEPBIND`, and `RTLD_FIRST`. -These are converted to the corresponding flags of the POSIX (and/or GNU libc and/or MacOS) -dlopen command, if possible, or are ignored if the specified functionality is not available -on the current platform. The default flags are platform specific. On MacOS the default -`dlopen` flags are `RTLD_LAZY|RTLD_DEEPBIND|RTLD_GLOBAL` while on other platforms the -defaults are `RTLD_LAZY|RTLD_DEEPBIND|RTLD_LOCAL`. An important usage of these flags is to -specify non default behavior for when the dynamic library loader binds library references to -exported symbols and if the bound references are put into process local or global scope. For -instance `RTLD_LAZY|RTLD_DEEPBIND|RTLD_GLOBAL` allows the library's symbols to be available -for usage in other shared libraries, addressing situations where there are dependencies -between shared libraries. -""" -function dlopen end - -dlopen(s::Symbol, flags::Integer = RTLD_LAZY | RTLD_DEEPBIND) = - dlopen(string(s), flags) - -dlopen(s::AbstractString, flags::Integer = RTLD_LAZY | RTLD_DEEPBIND) = - ccall(:jl_load_dynamic_library, Ptr{Void}, (Cstring,UInt32), s, flags) - -""" - dlopen_e(libfile::AbstractString [, flags::Integer]) - -Similar to [`dlopen`](@ref), except returns a `NULL` pointer instead of raising errors. -""" -function dlopen_e end - -dlopen_e(s::Symbol, flags::Integer = RTLD_LAZY | RTLD_DEEPBIND) = - dlopen_e(string(s), flags) - -dlopen_e(s::AbstractString, flags::Integer = RTLD_LAZY | RTLD_DEEPBIND) = - ccall(:jl_load_dynamic_library_e, Ptr{Void}, (Cstring,UInt32), s, flags) - -""" - dlclose(handle) - -Close shared library referenced by handle. -""" -function dlclose(p::Ptr) - 0 == ccall(:jl_dlclose, Cint, (Ptr{Void},), p) -end - -""" - find_library(names, locations) - -Searches for the first library in `names` in the paths in the `locations` list, -`DL_LOAD_PATH`, or system library paths (in that order) which can successfully be dlopen'd. -On success, the return value will be one of the names (potentially prefixed by one of the -paths in locations). This string can be assigned to a `global const` and used as the library -name in future `ccall`'s. On failure, it returns the empty string. -""" -function find_library(libnames, extrapaths=String[]) - for lib in libnames - for path in extrapaths - l = joinpath(path, lib) - p = dlopen_e(l, RTLD_LAZY) - if p != C_NULL - dlclose(p) - return l - end - end - p = dlopen_e(lib, RTLD_LAZY) - if p != C_NULL - dlclose(p) - return lib - end - end - return "" -end -find_library(libname::Union{Symbol,AbstractString}, extrapaths=String[]) = - find_library([string(libname)], extrapaths) - -function dlpath(handle::Ptr{Void}) - p = ccall(:jl_pathname_for_handle, Cstring, (Ptr{Void},), handle) - s = unsafe_string(p) - is_windows() && Libc.free(p) - return s -end - -function dlpath(libname::Union{AbstractString, Symbol}) - handle = dlopen(libname) - path = dlpath(handle) - dlclose(handle) - return path -end - -if is_apple() - const dlext = "dylib" -elseif is_windows() - const dlext = "dll" -else - #assume is_linux, or similar - const dlext = "so" -end - -""" - dlext - -File extension for dynamic libraries (e.g. dll, dylib, so) on the current platform. -""" -dlext - -if is_linux() - struct dl_phdr_info - # Base address of object - addr::Cuint - - # Null-terminated name of object - name::Ptr{UInt8} - - # Pointer to array of ELF program headers for this object - phdr::Ptr{Void} - - # Number of program headers for this object - phnum::Cshort - end - - # This callback function called by dl_iterate_phdr() on Linux - function dl_phdr_info_callback(di::dl_phdr_info, size::Csize_t, dynamic_libraries::Array{AbstractString,1}) - # Skip over objects without a path (as they represent this own object) - name = unsafe_string(di.name) - if !isempty(name) - push!(dynamic_libraries, name) - end - return convert(Cint, 0)::Cint - end -end # linux-only - -if is_bsd() && !is_apple() - # DL_ITERATE_PHDR(3) on freebsd - struct dl_phdr_info - # Base address of object - addr::Cuint - - # Null-terminated name of object - name::Ptr{UInt8} - - # Pointer to array of ELF program headers for this object - phdr::Ptr{Void} - - # Number of program headers for this object - phnum::Cshort - end - - function dl_phdr_info_callback(di::dl_phdr_info, size::Csize_t, dy_libs::Vector{AbstractString}) - name = unsafe_string(di.name) - if !isempty(name) - push!(dy_libs, name) - end - return convert(Cint, 0)::Cint - end -end # bsd family - -function dllist() - dynamic_libraries = Vector{AbstractString}(0) - - @static if is_linux() - const callback = cfunction(dl_phdr_info_callback, Cint, - Tuple{Ref{dl_phdr_info}, Csize_t, Ref{Vector{AbstractString}}}) - ccall(:dl_iterate_phdr, Cint, (Ptr{Void}, Ref{Vector{AbstractString}}), callback, dynamic_libraries) - end - - @static if is_apple() - numImages = ccall(:_dyld_image_count, Cint, ()) - - # start at 1 instead of 0 to skip self - for i in 1:numImages-1 - name = unsafe_string(ccall(:_dyld_get_image_name, Cstring, (UInt32,), i)) - push!(dynamic_libraries, name) - end - end - - @static if is_windows() - ccall(:jl_dllist, Cint, (Any,), dynamic_libraries) - end - - @static if is_bsd() && !is_apple() - const callback = cfunction(dl_phdr_info_callback, Cint, - Tuple{Ref{dl_phdr_info}, Csize_t, Ref{Vector{AbstractString}}}) - ccall(:dl_iterate_phdr, Cint, (Ptr{Void}, Ref{Vector{AbstractString}}), callback, dynamic_libraries) - shift!(dynamic_libraries) - end - - return dynamic_libraries -end - -end # module diff --git a/julia-0.6.3/share/julia/base/libgit2/blob.jl b/julia-0.6.3/share/julia/base/libgit2/blob.jl deleted file mode 100644 index 0676dec..0000000 --- a/julia-0.6.3/share/julia/base/libgit2/blob.jl +++ /dev/null @@ -1,69 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -function Base.length(blob::GitBlob) - return ccall((:git_blob_rawsize, :libgit2), Int64, (Ptr{Void},), blob.ptr) -end - -function rawcontent(blob::GitBlob) - ptr = ccall((:git_blob_rawcontent, :libgit2), Ptr{UInt8}, (Ptr{Void},), blob.ptr) - copy(unsafe_wrap(Array, ptr, (length(blob),), false)) -end - -""" - content(blob::GitBlob) - -Fetch the contents of the `GitBlob` `blob`. If the `blob` contains -binary data (which can be determined using [`isbinary`](@ref)), -throw an error. Otherwise, return a `String` containing the contents -of the `blob`. -""" -function content(blob::GitBlob) - s = String(rawcontent(blob)) - isvalid(s) || error("Blob does not contain valid UTF-8 data") - return s -end - -""" -Use a heuristic to guess if a file is binary: searching for NULL bytes and -looking for a reasonable ratio of printable to non-printable characters among -the first 8000 bytes. -""" -function isbinary(blob::GitBlob) - bin_flag = ccall((:git_blob_is_binary, :libgit2), Cint, (Ptr{Void},), blob.ptr) - return bin_flag == 1 -end - -""" - LibGit2.addblob!(repo::GitRepo, path::AbstractString) - -Reads the file at `path` and adds it to the object database of `repo` as a loose blob. -Returns the `GitHash` of the resulting blob. - -# Example - -```julia -hash_str = hex(commit_oid) -blob_file = joinpath(repo_path, ".git", "objects", hash_str[1:2], hash_str[3:end]) -id = LibGit2.addblob!(repo, blob_file) -``` -""" -function addblob!(repo::GitRepo, path::AbstractString) - id_ref = Ref{GitHash}() - @check ccall((:git_blob_create_fromdisk, :libgit2), Cint, - (Ptr{GitHash}, Ptr{Void}, Cstring), - id_ref, repo.ptr, path) - return id_ref[] -end - -function Base.show(io::IO, blob::GitBlob) - if !isbinary(blob) - conts = split(content(blob), "\n") - showlen = max(length(conts), 3) - println(io, "GitBlob:\nBlob id: ", GitHash(blob), "\nContents:") - for i in 1:showlen - println(io, conts[i]) - end - else - println(io, "GitBlob:\nBlob id: ", GitHash(blob), "\nContents are binary.") - end -end diff --git a/julia-0.6.3/share/julia/base/libgit2/callbacks.jl b/julia-0.6.3/share/julia/base/libgit2/callbacks.jl deleted file mode 100644 index 639a874..0000000 --- a/julia-0.6.3/share/julia/base/libgit2/callbacks.jl +++ /dev/null @@ -1,265 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -"""Mirror callback function - -Function sets `+refs/*:refs/*` refspecs and `mirror` flag for remote reference. -""" -function mirror_callback(remote::Ptr{Ptr{Void}}, repo_ptr::Ptr{Void}, - name::Cstring, url::Cstring, payload::Ptr{Void}) - # Create the remote with a mirroring url - fetch_spec = "+refs/*:refs/*" - err = ccall((:git_remote_create_with_fetchspec, :libgit2), Cint, - (Ptr{Ptr{Void}}, Ptr{Void}, Cstring, Cstring, Cstring), - remote, repo_ptr, name, url, fetch_spec) - err != 0 && return Cint(err) - - # And set the configuration option to true for the push command - config = GitConfig(GitRepo(repo_ptr,false)) - name_str = unsafe_string(name) - err= try set!(config, "remote.$name_str.mirror", true) - catch -1 - finally close(config) - end - err != 0 && return Cint(err) - return Cint(0) -end - -function authenticate_ssh(creds::SSHCredentials, libgit2credptr::Ptr{Ptr{Void}}, - username_ptr, schema, host) - isusedcreds = checkused!(creds) - - # Note: The same SSHCredentials can be used to authenticate separate requests using the - # same credential cache. e.g. using Pkg.update when there are two private packages. - errcls, errmsg = Error.last_error() - if errcls != Error.None - # Check if we used ssh-agent - if creds.usesshagent == "U" - creds.usesshagent = "E" # reported ssh-agent error, disables ssh agent use for the future - end - end - - # first try ssh-agent if credentials support its usage - if creds.usesshagent == "Y" || creds.usesshagent == "U" - err = ccall((:git_cred_ssh_key_from_agent, :libgit2), Cint, - (Ptr{Ptr{Void}}, Cstring), libgit2credptr, username_ptr) - creds.usesshagent = "U" # used ssh-agent only one time - err == 0 && return Cint(0) - end - - if creds.prompt_if_incorrect - # if username is not provided, then prompt for it - username = if username_ptr == Cstring(C_NULL) - uname = creds.user # check if credentials were already used - !isusedcreds ? uname : prompt("Username for '$schema$host'", default=uname) - else - unsafe_string(username_ptr) - end - isempty(username) && return Cint(Error.EAUTH) - - # For SSH we need a private key location - privatekey = if haskey(ENV,"SSH_KEY_PATH") - ENV["SSH_KEY_PATH"] - else - keydefpath = creds.prvkey # check if credentials were already used - if isempty(keydefpath) || isusedcreds - defaultkeydefpath = joinpath(homedir(),".ssh","id_rsa") - if isempty(keydefpath) && isfile(defaultkeydefpath) - keydefpath = defaultkeydefpath - else - keydefpath = - prompt("Private key location for '$schema$username@$host'", default=keydefpath) - end - end - keydefpath - end - - # If the private key changed, invalidate the cached public key - (privatekey != creds.prvkey) && - (creds.pubkey = "") - - # For SSH we need a public key location, look for environment vars SSH_* as well - publickey = if haskey(ENV,"SSH_PUB_KEY_PATH") - ENV["SSH_PUB_KEY_PATH"] - else - keydefpath = creds.pubkey # check if credentials were already used - if isempty(keydefpath) || isusedcreds - if isempty(keydefpath) - keydefpath = privatekey*".pub" - end - if !isfile(keydefpath) - prompt("Public key location for '$schema$username@$host'", default=keydefpath) - end - end - keydefpath - end - - passphrase_required = true - if !isfile(privatekey) - warn("Private key not found") - else - # In encrypted private keys, the second line is "Proc-Type: 4,ENCRYPTED" - open(privatekey) do f - readline(f) - passphrase_required = readline(f) == "Proc-Type: 4,ENCRYPTED" - end - end - - passphrase = if haskey(ENV,"SSH_KEY_PASS") - ENV["SSH_KEY_PASS"] - else - passdef = creds.pass # check if credentials were already used - if passphrase_required && (isempty(passdef) || isusedcreds) - if is_windows() - passdef = Base.winprompt( - "Your SSH Key requires a password, please enter it now:", - "Passphrase required", privatekey; prompt_username = false) - isnull(passdef) && return Cint(Error.EAUTH) - passdef = Base.get(passdef)[2] - else - passdef = prompt("Passphrase for $privatekey", password=true) - end - end - passdef - end - ((creds.user != username) || (creds.pass != passphrase) || - (creds.prvkey != privatekey) || (creds.pubkey != publickey)) && reset!(creds) - - creds.user = username # save credentials - creds.prvkey = privatekey # save credentials - creds.pubkey = publickey # save credentials - creds.pass = passphrase - else - isusedcreds && return Cint(Error.EAUTH) - end - - return ccall((:git_cred_ssh_key_new, :libgit2), Cint, - (Ptr{Ptr{Void}}, Cstring, Cstring, Cstring, Cstring), - libgit2credptr, creds.user, creds.pubkey, creds.prvkey, creds.pass) -end - -function authenticate_userpass(creds::UserPasswordCredentials, libgit2credptr::Ptr{Ptr{Void}}, - schema, host, urlusername) - isusedcreds = checkused!(creds) - - if creds.prompt_if_incorrect - username = creds.user - userpass = creds.pass - if is_windows() - if isempty(username) || isempty(userpass) || isusedcreds - res = Base.winprompt("Please enter your credentials for '$schema$host'", "Credentials required", - isempty(username) ? urlusername : username; prompt_username = true) - isnull(res) && return Cint(Error.EAUTH) - username, userpass = Base.get(res) - end - elseif isusedcreds - username = prompt("Username for '$schema$host'", - default=isempty(username) ? urlusername : username) - userpass = prompt("Password for '$schema$username@$host'", password=true) - end - ((creds.user != username) || (creds.pass != userpass)) && reset!(creds) - creds.user = username # save credentials - creds.pass = userpass # save credentials - - isempty(username) && isempty(userpass) && return Cint(Error.EAUTH) - else - isusedcreds && return Cint(Error.EAUTH) - end - - return ccall((:git_cred_userpass_plaintext_new, :libgit2), Cint, - (Ptr{Ptr{Void}}, Cstring, Cstring), - libgit2credptr, creds.user, creds.pass) -end - - -"""Credentials callback function - -Function provides different credential acquisition functionality w.r.t. a connection protocol. -If a payload is provided then `payload_ptr` should contain a `LibGit2.AbstractCredentials` object. - -For `LibGit2.Consts.CREDTYPE_USERPASS_PLAINTEXT` type, if the payload contains fields: -`user` & `pass`, they are used to create authentication credentials. -Empty `user` name and `pass`word trigger an authentication error. - -For `LibGit2.Consts.CREDTYPE_SSH_KEY` type, if the payload contains fields: -`user`, `prvkey`, `pubkey` & `pass`, they are used to create authentication credentials. -Empty `user` name triggers an authentication error. - -Credentials are checked in the following order (if supported): -- ssh key pair (`ssh-agent` if specified in payload's `usesshagent` field) -- plain text - -**Note**: Due to the specifics of the `libgit2` authentication procedure, when -authentication fails, this function is called again without any indication whether -authentication was successful or not. To avoid an infinite loop from repeatedly -using the same faulty credentials, the `checkused!` function can be called. This -function returns `true` if the credentials were used. -Using credentials triggers a user prompt for (re)entering required information. -`UserPasswordCredentials` and `CachedCredentials` are implemented using a call -counting strategy that prevents repeated usage of faulty credentials. -""" -function credentials_callback(libgit2credptr::Ptr{Ptr{Void}}, url_ptr::Cstring, - username_ptr::Cstring, - allowed_types::Cuint, payload_ptr::Ptr{Void}) - err = Cint(0) - url = unsafe_string(url_ptr) - - # parse url for schema and host - urlparts = match(URL_REGEX, url) - schema = urlparts[:scheme] === nothing ? "" : urlparts[:scheme] * "://" - urlusername = urlparts[:user] === nothing ? "" : urlparts[:user] - host = urlparts[:host] - - # get credentials object from payload pointer - @assert payload_ptr != C_NULL - creds = unsafe_pointer_to_objref(payload_ptr) - explicit = !isnull(creds[]) && !isa(Base.get(creds[]), CachedCredentials) - # use ssh key or ssh-agent - if isset(allowed_types, Cuint(Consts.CREDTYPE_SSH_KEY)) - sshcreds = get_creds!(creds, "ssh://$host", reset!(SSHCredentials(true), -1)) - if isa(sshcreds, SSHCredentials) - err = authenticate_ssh(sshcreds, libgit2credptr, username_ptr, schema, host) - err == 0 && return err - end - end - - if isset(allowed_types, Cuint(Consts.CREDTYPE_USERPASS_PLAINTEXT)) - defaultcreds = reset!(UserPasswordCredentials(true), -1) - credid = "$schema$host" - upcreds = get_creds!(creds, credid, defaultcreds) - # If there were stored SSH credentials, but we ended up here that must - # mean that something went wrong. Replace the SSH credentials by user/pass - # credentials - if !isa(upcreds, UserPasswordCredentials) - upcreds = defaultcreds - isa(Base.get(creds[]), CachedCredentials) && (Base.get(creds[]).creds[credid] = upcreds) - end - return authenticate_userpass(upcreds, libgit2credptr, schema, host, urlusername) - end - - # No authentication method we support succeeded. The most likely cause is - # that explicit credentials were passed in, but said credentials are incompatible - # with the remote host. - if err == 0 - if explicit - warn("The explicitly provided credentials were incompatible with " * - "the server's supported authentication methods") - end - err = Cint(Error.EAUTH) - end - return err -end - -function fetchhead_foreach_callback(ref_name::Cstring, remote_url::Cstring, - oid_ptr::Ptr{GitHash}, is_merge::Cuint, payload::Ptr{Void}) - fhead_vec = unsafe_pointer_to_objref(payload)::Vector{FetchHead} - push!(fhead_vec, FetchHead(unsafe_string(ref_name), unsafe_string(remote_url), - unsafe_load(oid_ptr), is_merge == 1)) - return Cint(0) -end - -"C function pointer for `mirror_callback`" -mirror_cb() = cfunction(mirror_callback, Cint, Tuple{Ptr{Ptr{Void}}, Ptr{Void}, Cstring, Cstring, Ptr{Void}}) -"C function pointer for `credentials_callback`" -credentials_cb() = cfunction(credentials_callback, Cint, Tuple{Ptr{Ptr{Void}}, Cstring, Cstring, Cuint, Ptr{Void}}) -"C function pointer for `fetchhead_foreach_callback`" -fetchhead_foreach_cb() = cfunction(fetchhead_foreach_callback, Cint, Tuple{Cstring, Cstring, Ptr{GitHash}, Cuint, Ptr{Void}}) diff --git a/julia-0.6.3/share/julia/base/libgit2/commit.jl b/julia-0.6.3/share/julia/base/libgit2/commit.jl deleted file mode 100644 index 39feb98..0000000 --- a/julia-0.6.3/share/julia/base/libgit2/commit.jl +++ /dev/null @@ -1,95 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -function message(c::GitCommit, raw::Bool=false) - local msg_ptr::Cstring - msg_ptr = raw? ccall((:git_commit_message_raw, :libgit2), Cstring, (Ptr{Void},), c.ptr) : - ccall((:git_commit_message, :libgit2), Cstring, (Ptr{Void},), c.ptr) - if msg_ptr == C_NULL - return nothing - end - return unsafe_string(msg_ptr) -end - -function author(c::GitCommit) - ptr = ccall((:git_commit_author, :libgit2), Ptr{SignatureStruct}, (Ptr{Void},), c.ptr) - @assert ptr != C_NULL - return Signature(ptr) -end - -function committer(c::GitCommit) - ptr = ccall((:git_commit_committer, :libgit2), Ptr{SignatureStruct}, (Ptr{Void},), c.ptr) - @assert ptr != C_NULL - return Signature(ptr) -end - -function Base.show(io::IO, c::GitCommit) - authstr = sprint(show, author(c)) - cmtrstr = sprint(show, committer(c)) - print(io, "Git Commit:\nCommit Author: $authstr\nCommitter: $cmtrstr\nSHA: $(GitHash(c))\nMessage:\n$(message(c))") -end - -""" Wrapper around `git_commit_create` """ -function commit(repo::GitRepo, - refname::AbstractString, - msg::AbstractString, - author::GitSignature, - committer::GitSignature, - tree::GitTree, - parents::GitCommit...) - commit_id_ptr = Ref(GitHash()) - nparents = length(parents) - parentptrs = Ptr{Void}[c.ptr for c in parents] - @check ccall((:git_commit_create, :libgit2), Cint, - (Ptr{GitHash}, Ptr{Void}, Ptr{UInt8}, - Ptr{SignatureStruct}, Ptr{SignatureStruct}, - Ptr{UInt8}, Ptr{UInt8}, Ptr{Void}, - Csize_t, Ptr{Ptr{Void}}), - commit_id_ptr, repo.ptr, isempty(refname) ? C_NULL : refname, - author.ptr, committer.ptr, - C_NULL, msg, tree.ptr, - nparents, nparents > 0 ? parentptrs : C_NULL) - return commit_id_ptr[] -end - -"""Commit changes to repository""" -function commit(repo::GitRepo, msg::AbstractString; - refname::AbstractString=Consts.HEAD_FILE, - author::Signature = Signature(repo), - committer::Signature = Signature(repo), - tree_id::GitHash = GitHash(), - parent_ids::Vector{GitHash}=GitHash[]) - # Retrieve tree identifier - if iszero(tree_id) - tree_id = with(GitIndex, repo) do idx; write_tree!(idx) end - end - - # Retrieve parents from HEAD - if isempty(parent_ids) - try # if throws then HEAD not found -> empty repo - push!(parent_ids, GitHash(repo, refname)) - end - end - - # return commit id - commit_id = GitHash() - - # get necessary objects - tree = GitTree(repo, tree_id) - auth_sig = convert(GitSignature, author) - comm_sig = convert(GitSignature, committer) - parents = GitCommit[] - try - for id in parent_ids - push!(parents, GitCommit(repo, id)) - end - commit_id = commit(repo, refname, msg, auth_sig, comm_sig, tree, parents...) - finally - for parent in parents - close(parent) - end - close(tree) - close(auth_sig) - close(comm_sig) - end - return commit_id -end diff --git a/julia-0.6.3/share/julia/base/libgit2/config.jl b/julia-0.6.3/share/julia/base/libgit2/config.jl deleted file mode 100644 index 0abfa28..0000000 --- a/julia-0.6.3/share/julia/base/libgit2/config.jl +++ /dev/null @@ -1,130 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -function GitConfig(path::AbstractString, - level::Consts.GIT_CONFIG = Consts.CONFIG_LEVEL_APP, - force::Bool=false) - # create new config object - cfg_ptr_ptr = Ref{Ptr{Void}}(C_NULL) - @check ccall((:git_config_new, :libgit2), Cint, (Ptr{Ptr{Void}},), cfg_ptr_ptr) - cfg = GitConfig(cfg_ptr_ptr[]) - try - addfile(cfg, path, level, force) - catch ex - close(cfg) - rethrow(ex) - end - return cfg -end - -function GitConfig(repo::GitRepo) - cfg_ptr_ptr = Ref{Ptr{Void}}(C_NULL) - @check ccall((:git_repository_config, :libgit2), Cint, - (Ptr{Ptr{Void}}, Ptr{Void}), cfg_ptr_ptr, repo.ptr) - return GitConfig(repo, cfg_ptr_ptr[]) -end - -function GitConfig(level::Consts.GIT_CONFIG = Consts.CONFIG_LEVEL_DEFAULT) - cfg_ptr_ptr = Ref{Ptr{Void}}(C_NULL) - @check ccall((:git_config_open_default, :libgit2), Cint, - (Ptr{Ptr{Void}},), cfg_ptr_ptr) - cfg = GitConfig(cfg_ptr_ptr[]) - if level != Consts.CONFIG_LEVEL_DEFAULT - glb_cfg_ptr_ptr = Ref{Ptr{Void}}(C_NULL) - tmpcfg = cfg - try - @check ccall((:git_config_open_level, :libgit2), Cint, - (Ptr{Ptr{Void}}, Ptr{Void}, Cint), - glb_cfg_ptr_ptr, cfg.ptr, Cint(level)) - cfg = GitConfig(glb_cfg_ptr_ptr[]) - finally - close(tmpcfg) - end - end - return cfg -end - -function addfile(cfg::GitConfig, path::AbstractString, - level::Consts.GIT_CONFIG = Consts.CONFIG_LEVEL_APP, - force::Bool=false) - @check ccall((:git_config_add_file_ondisk, :libgit2), Cint, - (Ptr{Ptr{Void}}, Cstring, Cint, Cint), - cfg.ptr, path, Cint(level), Cint(force)) -end - -function get(::Type{<:AbstractString}, c::GitConfig, name::AbstractString) - buf_ref = Ref(Buffer()) - @check ccall((:git_config_get_string_buf, :libgit2), Cint, - (Ptr{Buffer}, Ptr{Void}, Cstring), buf_ref, c.ptr, name) - buf = buf_ref[] - str = unsafe_string(buf.ptr, buf.size) - free(buf_ref) - str -end - -function get(::Type{Bool}, c::GitConfig, name::AbstractString) - val_ptr = Ref(Cint(0)) - @check ccall((:git_config_get_bool, :libgit2), Cint, - (Ptr{Cint}, Ptr{Void}, Cstring), val_ptr, c.ptr, name) - return Bool(val_ptr[]) -end - -function get(::Type{Int32}, c::GitConfig, name::AbstractString) - val_ptr = Ref(Cint(0)) - @check ccall((:git_config_get_int32, :libgit2), Cint, - (Ptr{Cint}, Ptr{Void}, Cstring), val_ptr, c.ptr, name) - return val_ptr[] -end - -function get(::Type{Int64}, c::GitConfig, name::AbstractString) - val_ptr = Ref(Cintmax_t(0)) - @check ccall((:git_config_get_int64, :libgit2), Cint, - (Ptr{Cintmax_t}, Ptr{Void}, Cstring), val_ptr, c.ptr, name) - return val_ptr[] -end - -function get(c::GitConfig, name::AbstractString, default::T) where T - res = default - try res = get(T,c,name) end - return res -end - -function getconfig(r::GitRepo, name::AbstractString, default) - with(GitConfig, r) do cfg - get(cfg, name, default) - end -end - -function getconfig(rname::AbstractString, name::AbstractString, default) - with(GitRepo, rname) do r - with(GitConfig, r) do cfg - get(cfg, name, default) - end - end -end - -function getconfig(name::AbstractString, default) - with(GitConfig) do cfg - get(cfg, name, default) - end -end - -function set!(c::GitConfig, name::AbstractString, value::AbstractString) - @check ccall((:git_config_set_string, :libgit2), Cint, - (Ptr{Void}, Cstring, Cstring), c.ptr, name, value) -end - -function set!(c::GitConfig, name::AbstractString, value::Bool) - bval = Int32(value) - @check ccall((:git_config_set_bool, :libgit2), Cint, - (Ptr{Void}, Cstring, Cint), c.ptr, name, bval) -end - -function set!(c::GitConfig, name::AbstractString, value::Int32) - @check ccall((:git_config_set_int32, :libgit2), Cint, - (Ptr{Void}, Cstring, Cint), c.ptr, name, value) -end - -function set!(c::GitConfig, name::AbstractString, value::Int64) - @check ccall((:git_config_set_int64, :libgit2), Cint, - (Ptr{Void}, Cstring, Cintmax_t), c.ptr, name, value) -end diff --git a/julia-0.6.3/share/julia/base/libgit2/consts.jl b/julia-0.6.3/share/julia/base/libgit2/consts.jl deleted file mode 100644 index b5aa73c..0000000 --- a/julia-0.6.3/share/julia/base/libgit2/consts.jl +++ /dev/null @@ -1,353 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -module Consts - - const HEAD_FILE = "HEAD" - const FETCH_HEAD = "FETCH_HEAD" - const REMOTE_ORIGIN = "origin" - - # objs - @enum(OBJECT, - OBJ_ANY = -2, - OBJ_BAD = -1, - OBJ_COMMIT = 1, - OBJ_TREE = 2, - OBJ_BLOB = 3, - OBJ_TAG = 4) - - #revwalk - const SORT_NONE = Cint(0) - const SORT_TOPOLOGICAL = Cint(1 << 0) - const SORT_TIME = Cint(1 << 1) - const SORT_REVERSE = Cint(1 << 2) - - # refs - const REF_INVALID = Cint(0) - const REF_OID = Cint(1) - const REF_SYMBOLIC = Cint(2) - const REF_LISTALL = REF_OID | REF_SYMBOLIC - - # checkout - const CHECKOUT_NONE = Cuint(0) - const CHECKOUT_SAFE = Cuint(1 << 0) - const CHECKOUT_FORCE = Cuint(1 << 1) - const CHECKOUT_RECREATE_MISSING = Cuint(1 << 2) - const CHECKOUT_ALLOW_CONFLICTS = Cuint(1 << 4) - const CHECKOUT_REMOVE_UNTRACKED = Cuint(1 << 5) - const CHECKOUT_REMOVE_IGNORED = Cuint(1 << 6) - const CHECKOUT_UPDATE_ONLY = Cuint(1 << 7) - const CHECKOUT_DONT_UPDATE_INDEX = Cuint(1 << 8) - const CHECKOUT_NO_REFRESH = Cuint(1 << 9) - const CHECKOUT_SKIP_UNMERGED = Cuint(1 << 10) - const CHECKOUT_USE_OURS = Cuint(1 << 11) - const CHECKOUT_USE_THEIRS = Cuint(1 << 12) - const CHECKOUT_DISABLE_PATHSPEC_MATCH = Cuint(1 << 13) - const CHECKOUT_SKIP_LOCKED_DIRECTORIES = Cuint(1 << 18) - const CHECKOUT_DONT_OVERWRITE_IGNORED = Cuint(1 << 19) - const CHECKOUT_CONFLICT_STYLE_MERGE = Cuint(1 << 20) - const CHECKOUT_CONFLICT_STYLE_DIFF3 = Cuint(1 << 21) - const CHECKOUT_DONT_REMOVE_EXISTING = Cuint(1 << 22) - - const CHECKOUT_UPDATE_SUBMODULES = Cuint(1 << 16) - const CHECKOUT_UPDATE_SUBMODULES_IF_CHANGED = Cuint(1 << 17) - - const CHECKOUT_NOTIFY_NONE = Cuint(0) - const CHECKOUT_NOTIFY_CONFLICT = Cuint(1 << 0) - const CHECKOUT_NOTIFY_DIRTY = Cuint(1 << 1) - const CHECKOUT_NOTIFY_UPDATED = Cuint(1 << 2) - const CHECKOUT_NOTIFY_UNTRACKED = Cuint(1 << 3) - const CHECKOUT_NOTIFY_IGNORED = Cuint(1 << 4) - const CHECKOUT_NOTIFY_ALL = 0x0FFFF - - # diff - const DIFF_OPTIONS_VERSION = Cuint(1) - - const DIFF_NORMAL = Cuint(0) - const DIFF_REVERSE = Cuint(1 << 0) - const DIFF_INCLUDE_IGNORED = Cuint(1 << 1) - const DIFF_RECURSE_IGNORED_DIRS = Cuint(1 << 2) - const DIFF_INCLUDE_UNTRACKED = Cuint(1 << 3) - const DIFF_RECURSE_UNTRACKED_DIRS = Cuint(1 << 4) - const DIFF_INCLUDE_UNMODIFIED = Cuint(1 << 5) - const DIFF_INCLUDE_TYPECHANGE = Cuint(1 << 6) - const DIFF_INCLUDE_TYPECHANGE_TREES = Cuint(1 << 7) - const DIFF_IGNORE_FILEMODE = Cuint(1 << 8) - const DIFF_IGNORE_SUBMODULES = Cuint(1 << 9) - const DIFF_IGNORE_CASE = Cuint(1 << 10) - const DIFF_DISABLE_PATHSPEC_MATCH = Cuint(1 << 12) - const DIFF_SKIP_BINARY_CHECK = Cuint(1 << 13) - const DIFF_ENABLE_FAST_UNTRACKED_DIRS = Cuint(1 << 14) - - const DIFF_FORCE_TEXT = Cuint(1 << 20) - const DIFF_FORCE_BINARY = Cuint(1 << 21) - const DIFF_IGNORE_WHITESPACE = Cuint(1 << 22) - const DIFF_IGNORE_WHITESPACE_CHANGE = Cuint(1 << 23) - const DIFF_IGNORE_WHITESPACE_EOL = Cuint(1 << 24) - const DIFF_SHOW_UNTRACKED_CONTENT = Cuint(1 << 25) - const DIFF_SHOW_UNMODIFIED = Cuint(1 << 26) - const DIFF_PATIENCE = Cuint(1 << 28) - const DIFF_MINIMAL = Cuint(1 << 29) - - const DIFF_FLAG_BINARY = Cuint(1 << 0) - const DIFF_FLAG_NOT_BINARY = Cuint(1 << 1) - const DIFF_FLAG_VALID_OID = Cuint(1 << 2) - - const DIFF_FORMAT_PATCH = Cuint(1) - const DIFF_FORMAT_PATCH_HEADER = Cuint(2) - const DIFF_FORMAT_RAW = Cuint(3) - const DIFF_FORMAT_NAME_ONLY = Cuint(4) - const DIFF_FORMAT_NAME_STATUS = Cuint(5) - - @enum(DELTA_STATUS, DELTA_UNMODIFIED = Cint(0), - DELTA_ADDED = Cint(1), - DELTA_DELETED = Cint(2), - DELTA_MODIFIED = Cint(3), - DELTA_RENAMED = Cint(4), - DELTA_COPIED = Cint(5), - DELTA_IGNORED = Cint(6), - DELTA_UNTRACKED = Cint(7), - DELTA_TYPECHANGE = Cint(8)) - - # index - const IDXENTRY_NAMEMASK = (0x0fff) - const IDXENTRY_STAGEMASK = (0x3000) - const IDXENTRY_EXTENDED = (0x4000) - const IDXENTRY_VALID = (0x8000) - const IDXENTRY_STAGESHIFT = Cint(12) - - const IDXENTRY_UPDATE = Cint(1 << 0) - const IDXENTRY_REMOVE = Cint(1 << 1) - const IDXENTRY_UPTODATE = Cint(1 << 2) - const IDXENTRY_ADDED = Cint(1 << 3) - - const IDXENTRY_HASHED = Cint(1 << 4) - const IDXENTRY_UNHASHED = Cint(1 << 5) - const IDXENTRY_WT_REMOVE = Cint(1 << 6) - const IDXENTRY_CONFLICTED = Cint(1 << 7) - - const IDXENTRY_UNPACKED = Cint(1 << 8) - const IDXENTRY_NEW_SKIP_WORKTREE = Cint(1 << 9) - - const INDEXCAP_IGNORE_CASE = Cuint(1) - const INDEXCAP_NO_FILEMODE = Cuint(2) - const INDEXCAP_NO_SYMLINKS = Cuint(4) - const INDEXCAP_FROM_OWNER = ~Cuint(0) - - const INDEX_ADD_DEFAULT = Cuint(0) - const INDEX_ADD_FORCE = Cuint(1 << 0) - const INDEX_ADD_DISABLE_PATHSPEC_MATCH = Cuint(1 << 1) - const INDEX_ADD_CHECK_PATHSPEC = Cuint(1 << 2) - - const INDEX_STAGE_ANY = Cint(-1) - - # merge - @enum(GIT_MERGE, MERGE_FIND_RENAMES = 1 << 0, - MERGE_FAIL_ON_CONFLICT = 1 << 1, - MERGE_SKIP_REUC = 1 << 2, - MERGE_NO_RECURSIVE = 1 << 3) - - @enum(GIT_MERGE_FILE, MERGE_FILE_DEFAULT = 0, # Defaults - MERGE_FILE_STYLE_MERGE = 1 << 0, # Create standard conflicted merge files - MERGE_FILE_STYLE_DIFF3 = 1 << 1, # Create diff3-style files - MERGE_FILE_SIMPLIFY_ALNUM = 1 << 2, # Condense non-alphanumeric regions for simplified diff file - MERGE_FILE_IGNORE_WHITESPACE = 1 << 3, # Ignore all whitespace - MERGE_FILE_IGNORE_WHITESPACE_CHANGE = 1 << 4, # Ignore changes in amount of whitespace - MERGE_FILE_IGNORE_WHITESPACE_EOL = 1 << 5, # Ignore whitespace at end of line - MERGE_FILE_DIFF_PATIENCE = 1 << 6, # Use the "patience diff" algorithm - MERGE_FILE_DIFF_MINIMAL = 1 << 7) # Take extra time to find minimal diff - - @enum(GIT_MERGE_FILE_FAVOR, MERGE_FILE_FAVOR_NORMAL = 0, - MERGE_FILE_FAVOR_OURS = 1, - MERGE_FILE_FAVOR_THEIRS = 2, - MERGE_FILE_FAVOR_UNION = 3) - - @enum(GIT_MERGE_PREFERENCE, MERGE_PREFERENCE_NONE = 0, - MERGE_PREFERENCE_NO_FASTFORWARD = 1, - MERGE_PREFERENCE_FASTFORWARD_ONLY = 2) - - @enum(GIT_MERGE_ANALYSIS, MERGE_ANALYSIS_NONE = 0, - MERGE_ANALYSIS_NORMAL = 1 << 0, - MERGE_ANALYSIS_UP_TO_DATE = 1 << 1, - MERGE_ANALYSIS_FASTFORWARD = 1 << 2, - MERGE_ANALYSIS_UNBORN = 1 << 3) - - # reset - const RESET_SOFT = Cint(1) # Move the head to the given commit - const RESET_MIXED = Cint(2) # SOFT plus reset index to the commit - const RESET_HARD = Cint(3) # MIXED plus changes in working tree discarded - - #rebase - @enum(GIT_REBASE_OPERATION, REBASE_OPERATION_PICK = Cint(0), - REBASE_OPERATION_REWORD = Cint(1), - REBASE_OPERATION_EDIT = Cint(2), - REBASE_OPERATION_SQUASH = Cint(3), - REBASE_OPERATION_FIXUP = Cint(4), - REBASE_OPERATION_EXEC = Cint(5)) - - # fetch_prune - const FETCH_PRUNE_UNSPECIFIED = Cint(0) - const FETCH_PRUNE = Cint(1) - const FETCH_NO_PRUNE = Cint(2) - - # remote_autotag - const REMOTE_DOWNLOAD_TAGS_UNSPECIFIED = Cint(0) - const REMOTE_DOWNLOAD_TAGS_AUTO = Cint(1) - const REMOTE_DOWNLOAD_TAGS_NONE = Cint(2) - const REMOTE_DOWNLOAD_TAGS_ALL = Cint(3) - - # clone - const CLONE_LOCAL_AUTO = Cint(0) - const CLONE_LOCAL = Cint(1) - const CLONE_NO_LOCAL = Cint(2) - const CLONE_LOCAL_NO_LINKS = Cint(3) - - # status - const STATUS_CURRENT = Cuint(0) - const STATUS_INDEX_NEW = Cuint(1 << 0) - const STATUS_INDEX_MODIFIED = Cuint(1 << 1) - const STATUS_INDEX_DELETED = Cuint(1 << 2) - const STATUS_INDEX_RENAMED = Cuint(1 << 3) - const STATUS_INDEX_TYPECHANGE = Cuint(1 << 4) - const STATUS_WT_NEW = Cuint(1 << 7) - const STATUS_WT_MODIFIED = Cuint(1 << 8) - const STATUS_WT_DELETED = Cuint(1 << 9) - const STATUS_WT_TYPECHANGE = Cuint(1 << 10) - const STATUS_WT_RENAMED = Cuint(1 << 11) - const STATUS_WT_UNREADABLE = Cuint(1 << 12) - const STATUS_IGNORED = Cuint(1 << 14) - const STATUS_CONFLICTED = Cuint(1 << 15) - - # status show - const STATUS_SHOW_INDEX_AND_WORKDIR = Cint(0) - const STATUS_SHOW_INDEX_ONLY = Cint(1) - const STATUS_SHOW_WORKDIR_ONLY = Cint(2) - - # status options - const STATUS_OPT_INCLUDE_UNTRACKED = Cuint(1 << 0) - const STATUS_OPT_INCLUDE_IGNORED = Cuint(1 << 1) - const STATUS_OPT_INCLUDE_UNMODIFIED = Cuint(1 << 2) - const STATUS_OPT_EXCLUDE_SUBMODULES = Cuint(1 << 3) - const STATUS_OPT_RECURSE_UNTRACKED_DIRS = Cuint(1 << 4) - const STATUS_OPT_DISABLE_PATHSPEC_MATCH = Cuint(1 << 5) - const STATUS_OPT_RECURSE_IGNORED_DIRS = Cuint(1 << 6) - const STATUS_OPT_RENAMES_HEAD_TO_INDEX = Cuint(1 << 7) - const STATUS_OPT_RENAMES_INDEX_TO_WORKDIR = Cuint(1 << 8) - const STATUS_OPT_SORT_CASE_SENSITIVELY = Cuint(1 << 9) - const STATUS_OPT_SORT_CASE_INSENSITIVELY = Cuint(1 << 10) - const STATUS_OPT_RENAMES_FROM_REWRITES = Cuint(1 << 11) - const STATUS_OPT_NO_REFRESH = Cuint(1 << 12) - const STATUS_OPT_UPDATE_INDEX = Cuint(1 << 13) - const STATUS_OPT_INCLUDE_UNREADABLE = Cuint(1 << 14) - const STATUS_OPT_INCLUDE_UNREADABLE_AS_UNTRACKED = Cuint(1 << 15) - - @enum(GIT_SUBMODULE_IGNORE, SUBMODULE_IGNORE_UNSPECIFIED = -1, # use the submodule's configuration - SUBMODULE_IGNORE_NONE = 1, # any change or untracked == dirty - SUBMODULE_IGNORE_UNTRACKED = 2, # dirty if tracked files change - SUBMODULE_IGNORE_DIRTY = 3, # only dirty if HEAD moved - SUBMODULE_IGNORE_ALL = 4) # never dirty - - """ -Option flags for `GitRepo`. - -* `REPOSITORY_OPEN_NO_SEARCH` - Only open the repository if it can be immediately found in the `path`. Do not walk up from the `path` looking at parent directories. -* `REPOSITORY_OPEN_CROSS_FS` - Unless this flag is set, open will not continue searching across filesystem boundaries. (E.g. Searching in a user's home directory `/home/user/source/` will not return `/.git/` as the found repo if `/` is a different filesystem than `/home`.) -* `REPOSITORY_OPEN_BARE` - Open repository as a bare repo regardless of core.bare config, and defer loading config file for faster setup. - """ - @enum(GIT_REPOSITORY_OPEN, REPOSITORY_OPEN_DEFAULT = 0, - REPOSITORY_OPEN_NO_SEARCH = 1<<0, - REPOSITORY_OPEN_CROSS_FS = 1<<1, - REPOSITORY_OPEN_BARE = 1<<2) - - @enum(GIT_BRANCH, BRANCH_LOCAL = 1, BRANCH_REMOTE = 2) - - @enum(GIT_FILEMODE, FILEMODE_UNREADABLE = 0o000000, - FILEMODE_TREE = 0o040000, - FILEMODE_BLOB = 0o100644, - FILEMODE_BLOB_EXECUTABLE = 0o100755, - FILEMODE_LINK = 0o120000, - FILEMODE_COMMIT = 0o160000) - - @enum(GIT_CREDTYPE, CREDTYPE_USERPASS_PLAINTEXT = Cuint(1 << 0), - CREDTYPE_SSH_KEY = Cuint(1 << 1), - CREDTYPE_SSH_CUSTOM = Cuint(1 << 2), - CREDTYPE_DEFAULT = Cuint(1 << 3), - CREDTYPE_SSH_INTERACTIVE = Cuint(1 << 4), - CREDTYPE_USERNAME = Cuint(1 << 5), - CREDTYPE_SSH_MEMORY = Cuint(1 << 6)) - - @enum(GIT_FEATURE, FEATURE_THREADS = Cuint(1 << 0), - FEATURE_HTTPS = Cuint(1 << 1), - FEATURE_SSH = Cuint(1 << 2), - FEATURE_NSEC = Cuint(1 << 3)) - -if LibGit2.version() >= v"0.24.0" - """ -Priority level of a config file. - -These priority levels correspond to the natural escalation logic (from higher to lower) when searching for config entries in git. - -* `CONFIG_LEVEL_DEFAULT` - Open the global, XDG and system configuration files if any available. -* `CONFIG_LEVEL_PROGRAMDATA` - System-wide on Windows, for compatibility with portable git -* `CONFIG_LEVEL_SYSTEM` - System-wide configuration file; `/etc/gitconfig` on Linux systems -* `CONFIG_LEVEL_XDG` - XDG compatible configuration file; typically `~/.config/git/config` -* `CONFIG_LEVEL_GLOBAL` - User-specific configuration file (also called Global configuration file); typically `~/.gitconfig` -* `CONFIG_LEVEL_LOCAL` - Repository specific configuration file; `\$WORK_DIR/.git/config` on non-bare repos -* `CONFIG_LEVEL_APP` - Application specific configuration file; freely defined by applications -* `CONFIG_HIGHEST_LEVEL` - Represents the highest level available config file (i.e. the most specific config file available that actually is loaded) - """ - @enum(GIT_CONFIG, CONFIG_LEVEL_DEFAULT = 0, - CONFIG_LEVEL_PROGRAMDATA = 1, - CONFIG_LEVEL_SYSTEM = 2, - CONFIG_LEVEL_XDG = 3, - CONFIG_LEVEL_GLOBAL = 4, - CONFIG_LEVEL_LOCAL = 5, - CONFIG_LEVEL_APP = 6, - CONFIG_HIGHEST_LEVEL =-1) -else - """ -Priority level of a config file. - -These priority levels correspond to the natural escalation logic (from higher to lower) when searching for config entries in git. - -* `CONFIG_LEVEL_DEFAULT` - Open the global, XDG and system configuration files if any available. -* `CONFIG_LEVEL_SYSTEM` - System-wide configuration file; `/etc/gitconfig` on Linux systems -* `CONFIG_LEVEL_XDG` - XDG compatible configuration file; typically `~/.config/git/config` -* `CONFIG_LEVEL_GLOBAL` - User-specific configuration file (also called Global configuration file); typically `~/.gitconfig` -* `CONFIG_LEVEL_LOCAL` - Repository specific configuration file; `\$WORK_DIR/.git/config` on non-bare repos -* `CONFIG_LEVEL_APP` - Application specific configuration file; freely defined by applications -* `CONFIG_HIGHEST_LEVEL` - Represents the highest level available config file (i.e. the most specific config file available that actually is loaded) - """ - @enum(GIT_CONFIG, CONFIG_LEVEL_DEFAULT = 0, - CONFIG_LEVEL_SYSTEM = 1, - CONFIG_LEVEL_XDG = 2, - CONFIG_LEVEL_GLOBAL = 3, - CONFIG_LEVEL_LOCAL = 4, - CONFIG_LEVEL_APP = 5, - CONFIG_HIGHEST_LEVEL =-1) -end - - """ -Global library options. - -These are used to select which global option to set or get and are used in `git_libgit2_opts()`. - """ - @enum(GIT_OPT, GET_MWINDOW_SIZE = 0, - SET_MWINDOW_SIZE = 1, - GET_MWINDOW_MAPPED_LIMIT = 2, - SET_MWINDOW_MAPPED_LIMIT = 3, - GET_SEARCH_PATH = 4, - SET_SEARCH_PATH = 5, - SET_CACHE_OBJECT_LIMIT = 6, - SET_CACHE_MAX_SIZE = 7, - ENABLE_CACHING = 8, - GET_CACHED_MEMORY = 9, - GET_TEMPLATE_PATH = 10, - SET_TEMPLATE_PATH = 11, - SET_SSL_CERT_LOCATIONS = 12) - - - @enum(GIT_PROXY, PROXY_NONE, - PROXY_AUTO, - PROXY_SPECIFIED) - -end diff --git a/julia-0.6.3/share/julia/base/libgit2/diff.jl b/julia-0.6.3/share/julia/base/libgit2/diff.jl deleted file mode 100644 index c01e226..0000000 --- a/julia-0.6.3/share/julia/base/libgit2/diff.jl +++ /dev/null @@ -1,82 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -# TODO: make this a general purpose solution -function Base.cconvert(::Type{Ptr{DiffOptionsStruct}}, pathspecs::AbstractString) - str_ref = Base.cconvert(Ref{Cstring}, [pathspecs]) - sa = StrArrayStruct(Base.unsafe_convert(Ref{Cstring}, str_ref), 1) - do_ref = Ref(DiffOptionsStruct(pathspec = sa)) - do_ref, str_ref -end -function Base.unsafe_convert(::Type{Ptr{DiffOptionsStruct}}, rr::Tuple{Ref{DiffOptionsStruct}, Ref{Cstring}}) - Base.unsafe_convert(Ptr{DiffOptionsStruct}, first(rr)) -end - - -function diff_tree(repo::GitRepo, tree::GitTree, pathspecs::AbstractString=""; cached::Bool=false) - diff_ptr_ptr = Ref{Ptr{Void}}(C_NULL) - if cached - @check ccall((:git_diff_tree_to_index, :libgit2), Cint, - (Ptr{Ptr{Void}}, Ptr{Void}, Ptr{Void}, Ptr{Void}, Ptr{DiffOptionsStruct}), - diff_ptr_ptr, repo.ptr, tree.ptr, C_NULL, isempty(pathspecs) ? C_NULL : pathspecs) - else - @check ccall((:git_diff_tree_to_workdir_with_index, :libgit2), Cint, - (Ptr{Ptr{Void}}, Ptr{Void}, Ptr{Void}, Ptr{DiffOptionsStruct}), - diff_ptr_ptr, repo.ptr, tree.ptr, isempty(pathspecs) ? C_NULL : pathspecs) - end - return GitDiff(repo, diff_ptr_ptr[]) -end - -function diff_tree(repo::GitRepo, oldtree::GitTree, newtree::GitTree) - diff_ptr_ptr = Ref{Ptr{Void}}(C_NULL) - @check ccall((:git_diff_tree_to_tree, :libgit2), Cint, - (Ptr{Ptr{Void}}, Ptr{Void}, Ptr{Void}, Ptr{Void}, Ptr{DiffOptionsStruct}), - diff_ptr_ptr, repo.ptr, oldtree.ptr, newtree.ptr, C_NULL) - return GitDiff(repo, diff_ptr_ptr[]) -end - -function GitDiffStats(diff::GitDiff) - diff_stat_ptr_ptr = Ref{Ptr{Void}}(C_NULL) - @check ccall((:git_diff_get_stats, :libgit2), Cint, - (Ptr{Ptr{Void}}, Ptr{Void}), - diff_stat_ptr_ptr, diff.ptr) - return GitDiffStats(diff.owner, diff_stat_ptr_ptr[]) -end - -function files_changed(diff_stat::GitDiffStats) - return ccall((:git_diff_stats_files_changed, :libgit2), Csize_t, (Ptr{Void},), diff_stat.ptr) -end - -function insertions(diff_stat::GitDiffStats) - return ccall((:git_diff_stats_insertions, :libgit2), Csize_t, (Ptr{Void},), diff_stat.ptr) -end - -function deletions(diff_stat::GitDiffStats) - return ccall((:git_diff_stats_deletions, :libgit2), Csize_t, (Ptr{Void},), diff_stat.ptr) -end - -function Base.count(diff::GitDiff) - return ccall((:git_diff_num_deltas, :libgit2), Cint, (Ptr{Void},), diff.ptr) -end - -function Base.getindex(diff::GitDiff, i::Integer) - if i < 1 || i > count(diff) - throw(BoundsError(diff, (i,))) - end - delta_ptr = ccall((:git_diff_get_delta, :libgit2), - Ptr{DiffDelta}, - (Ptr{Void}, Csize_t), diff.ptr, i-1) - return unsafe_load(delta_ptr) -end - -function Base.show(io::IO, diff_stat::GitDiffStats) - println(io, "GitDiffStats:") - println(io, "Files changed: $(files_changed(diff_stat))") - println(io, "Insertions: $(insertions(diff_stat))") - println(io, "Deletions: $(deletions(diff_stat))") -end - -function Base.show(io::IO, diff::GitDiff) - println(io, "GitDiff:") - println(io, "Number of deltas: $(count(diff))") - show(io, GitDiffStats(diff)) -end diff --git a/julia-0.6.3/share/julia/base/libgit2/error.jl b/julia-0.6.3/share/julia/base/libgit2/error.jl deleted file mode 100644 index 2f5739e..0000000 --- a/julia-0.6.3/share/julia/base/libgit2/error.jl +++ /dev/null @@ -1,103 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -module Error - -export GitError - -@enum(Code, GIT_OK = Cint(0), # no error - ERROR = Cint(-01), # generic error - ENOTFOUND = Cint(-03), # requested object could not be found - EEXISTS = Cint(-04), # object exits preventing op - EAMBIGUOUS = Cint(-05), # more than one object matches - EBUFS = Cint(-06), # output buffer too small to hold data - EUSER = Cint(-07), # user callback generated error - EBAREREPO = Cint(-08), # operation not allowed on bare repo - EUNBORNBRANCH = Cint(-09), # HEAD refers to branch with 0 commits - EUNMERGED = Cint(-10), # merge in progress prevented op - ENONFASTFORWARD = Cint(-11), # ref not fast-forwardable - EINVALIDSPEC = Cint(-12), # name / ref not in valid format - EMERGECONFLICT = Cint(-13), # merge conflict prevented op - ELOCKED = Cint(-14), # lock file prevented op - EMODIFIED = Cint(-15), # ref value does not match expected - EAUTH = Cint(-16), # authentication error - ECERTIFICATE = Cint(-17), # server certificate is invalid - EAPPLIED = Cint(-18), # patch/merge has already been applied - EPEEL = Cint(-19), # the requested peel operation is not possible - EEOF = Cint(-20), # Unexpted EOF - PASSTHROUGH = Cint(-30), # internal only - ITEROVER = Cint(-31)) # signals end of iteration - -@enum(Class, None, - NoMemory, - OS, - Invalid, - Reference, - Zlib, - Repository, - Config, - Regex, - Odb, - Index, - Object, - Net, - Tag, - Tree, - Indexer, - SSL, - Submodule, - Thread, - Stash, - Checkout, - FetchHead, - Merge, - SSH, - Filter, - Revert, - Callback, - CherryPick, - Describe, - Rebase) - -struct ErrorStruct - message::Ptr{UInt8} - class::Cint -end - -struct GitError <: Exception - class::Class - code::Code - msg::AbstractString -end -Base.show(io::IO, err::GitError) = print(io, "GitError(Code:$(err.code), Class:$(err.class), $(err.msg))") - -function last_error() - err = ccall((:giterr_last, :libgit2), Ptr{ErrorStruct}, ()) - if err != C_NULL - err_obj = unsafe_load(err) - err_class = Class[err_obj.class][] - err_msg = unsafe_string(err_obj.message) - else - err_class = Class[0][] - err_msg = "No errors" - end - return (err_class, err_msg) -end - -function GitError(code::Integer) - err_code = Code[code][] - err_class, err_msg = last_error() - return GitError(err_class, err_code, err_msg) -end - -end # Error module - -macro check(git_func) - quote - local err::Cint - err = $(esc(git_func::Expr)) - if err < 0 - throw(Error.GitError(err)) - end - err - end -end diff --git a/julia-0.6.3/share/julia/base/libgit2/index.jl b/julia-0.6.3/share/julia/base/libgit2/index.jl deleted file mode 100644 index c7e04c3..0000000 --- a/julia-0.6.3/share/julia/base/libgit2/index.jl +++ /dev/null @@ -1,124 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -function GitIndex(repo::GitRepo) - idx_ptr_ptr = Ref{Ptr{Void}}(C_NULL) - @check ccall((:git_repository_index, :libgit2), Cint, - (Ptr{Ptr{Void}}, Ptr{Void}), idx_ptr_ptr, repo.ptr) - return GitIndex(repo, idx_ptr_ptr[]) -end - -function read!(idx::GitIndex, force::Bool = false) - @check ccall((:git_index_read, :libgit2), Cint, (Ptr{Void}, Cint), idx.ptr, Cint(force)) - return idx -end - -function write!(idx::GitIndex) - @check ccall((:git_index_write, :libgit2), Cint, (Ptr{Void},), idx.ptr) - return idx -end - -function write_tree!(idx::GitIndex) - oid_ptr = Ref(GitHash()) - @check ccall((:git_index_write_tree, :libgit2), Cint, - (Ptr{GitHash}, Ptr{Void}), oid_ptr, idx.ptr) - return oid_ptr[] -end - -function repository(idx::GitIndex) - if isnull(idx.owner) - throw(GitError(Error.Index, Error.ENOTFOUND, "Index does not have an owning repository.")) - else - return Base.get(idx.owner) - end -end - -""" - LibGit2.read_tree!(idx::GitIndex, tree::GitTree) - LibGit2.read_tree!(idx::GitIndex, treehash::AbstractGitHash) - -Read the tree `tree` (or the tree pointed to by `treehash` in the repository owned by -`idx`) into the index `idx`. The current index contents will be replaced. -""" -function read_tree!(idx::GitIndex, tree::GitTree) - @check ccall((:git_index_read_tree, :libgit2), Cint, - (Ptr{Void}, Ptr{Void}), idx.ptr, tree.ptr) -end -read_tree!(idx::GitIndex, hash::AbstractGitHash) = - read_tree!(idx, GitTree(repository(idx), hash)) - -function add!(idx::GitIndex, files::AbstractString...; - flags::Cuint = Consts.INDEX_ADD_DEFAULT) - @check ccall((:git_index_add_all, :libgit2), Cint, - (Ptr{Void}, Ptr{StrArrayStruct}, Cuint, Ptr{Void}, Ptr{Void}), - idx.ptr, collect(files), flags, C_NULL, C_NULL) -end - -function update!(idx::GitIndex, files::AbstractString...) - @check ccall((:git_index_update_all, :libgit2), Cint, - (Ptr{Void}, Ptr{StrArrayStruct}, Ptr{Void}, Ptr{Void}), - idx.ptr, collect(files), C_NULL, C_NULL) -end - -function remove!(idx::GitIndex, files::AbstractString...) - @check ccall((:git_index_remove_all, :libgit2), Cint, - (Ptr{Void}, Ptr{StrArrayStruct}, Ptr{Void}, Ptr{Void}), - idx.ptr, collect(files), C_NULL, C_NULL) -end - -function add!(repo::GitRepo, files::AbstractString...; - flags::Cuint = Consts.INDEX_ADD_DEFAULT) - with(GitIndex, repo) do idx - add!(idx, files..., flags = flags) - write!(idx) - end - return -end - -function update!(repo::GitRepo, files::AbstractString...) - with(GitIndex, repo) do idx - update!(idx, files...) - write!(idx) - end - return -end - -function remove!(repo::GitRepo, files::AbstractString...) - with(GitIndex, repo) do idx - remove!(idx, files...) - write!(idx) - end - return -end - -function read!(repo::GitRepo, force::Bool = false) - with(GitIndex, repo) do idx - read!(idx, force) - end - return -end - -function Base.count(idx::GitIndex) - return ccall((:git_index_entrycount, :libgit2), Csize_t, (Ptr{Void},), idx.ptr) -end - -function Base.getindex(idx::GitIndex, i::Integer) - ie_ptr = ccall((:git_index_get_byindex, :libgit2), - Ptr{IndexEntry}, - (Ptr{Void}, Csize_t), idx.ptr, i-1) - ie_ptr == C_NULL && return nothing - return unsafe_load(ie_ptr) -end - -function Base.find(path::String, idx::GitIndex) - pos_ref = Ref{Csize_t}(0) - ret = ccall((:git_index_find, :libgit2), Cint, - (Ref{Csize_t}, Ptr{Void}, Cstring), pos_ref, idx.ptr, path) - ret == Cint(Error.ENOTFOUND) && return Nullable{Csize_t}() - return Nullable(pos_ref[]+1) -end - -stage(ie::IndexEntry) = ccall((:git_index_entry_stage, :libgit2), Cint, (Ptr{IndexEntry},), Ref(ie)) - -function Base.show(io::IO, idx::GitIndex) - println(io, "GitIndex:\nRepository: ", repository(idx), "\nNumber of elements: ", count(idx)) -end diff --git a/julia-0.6.3/share/julia/base/libgit2/libgit2.jl b/julia-0.6.3/share/julia/base/libgit2/libgit2.jl deleted file mode 100644 index 22b0f12..0000000 --- a/julia-0.6.3/share/julia/base/libgit2/libgit2.jl +++ /dev/null @@ -1,949 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -module LibGit2 - -import Base: merge!, == - -export with, GitRepo, GitConfig - -const GITHUB_REGEX = - r"^(?:git@|git://|https://(?:[\w\.\+\-]+@)?)github.com[:/](([^/].+)/(.+?))(?:\.git)?$"i - -const REFCOUNT = Threads.Atomic{UInt}() - -include("utils.jl") -include("consts.jl") -include("types.jl") -include("error.jl") -include("signature.jl") -include("oid.jl") -include("reference.jl") -include("commit.jl") -include("repository.jl") -include("config.jl") -include("walker.jl") -include("remote.jl") -include("strarray.jl") -include("index.jl") -include("merge.jl") -include("tag.jl") -include("blob.jl") -include("diff.jl") -include("rebase.jl") -include("status.jl") -include("tree.jl") -include("callbacks.jl") - -using .Error - -struct State - head::GitHash - index::GitHash - work::GitHash -end - -""" - head(pkg::AbstractString) -> String - -Return current HEAD [`GitHash`](@ref) of -the `pkg` repo as a string. -""" -function head(pkg::AbstractString) - with(GitRepo, pkg) do repo - string(head_oid(repo)) - end -end - -""" - need_update(repo::GitRepo) - -Equivalent to `git update-index`. Returns `true` -if `repo` needs updating. -""" -function need_update(repo::GitRepo) - if !isbare(repo) - # read updates index from filesystem - read!(repo, true) - end -end - -""" - iscommit(id::AbstractString, repo::GitRepo) -> Bool - -Checks if commit `id` (which is a [`GitHash`](@ref) in string form) -is in the repository. - -# Example - -```julia-repl -julia> repo = LibGit2.GitRepo(repo_path); - -julia> LibGit2.add!(repo, test_file); - -julia> commit_oid = LibGit2.commit(repo, "add test_file"); - -julia> LibGit2.iscommit(string(commit_oid), repo) -true -``` -""" -function iscommit(id::AbstractString, repo::GitRepo) - res = true - try - c = GitCommit(repo, id) - if c === nothing - res = false - else - close(c) - end - catch - res = false - end - return res -end - -""" - LibGit2.isdirty(repo::GitRepo, pathspecs::AbstractString=""; cached::Bool=false) -> Bool - -Checks if there have been any changes to tracked files in the working tree (if -`cached=false`) or the index (if `cached=true`). -`pathspecs` are the specifications for options for the diff. - -# Example -```julia -repo = LibGit2.GitRepo(repo_path) -LibGit2.isdirty(repo) # should be false -open(joinpath(repo_path, new_file), "a") do f - println(f, "here's my cool new file") -end -LibGit2.isdirty(repo) # now true -LibGit2.isdirty(repo, new_file) # now true -``` - -Equivalent to `git diff-index HEAD [-- ]`. -""" -isdirty(repo::GitRepo, paths::AbstractString=""; cached::Bool=false) = - isdiff(repo, Consts.HEAD_FILE, paths, cached=cached) - -""" - LibGit2.isdiff(repo::GitRepo, treeish::AbstractString, pathspecs::AbstractString=""; cached::Bool=false) - -Checks if there are any differences between the tree specified by `treeish` and the -tracked files in the working tree (if `cached=false`) or the index (if `cached=true`). -`pathspecs` are the specifications for options for the diff. - -# Example -```julia -repo = LibGit2.GitRepo(repo_path) -LibGit2.isdiff(repo, "HEAD") # should be false -open(joinpath(repo_path, new_file), "a") do f - println(f, "here's my cool new file") -end -LibGit2.isdiff(repo, "HEAD") # now true -``` - -Equivalent to `git diff-index [-- ]`. -""" -function isdiff(repo::GitRepo, treeish::AbstractString, paths::AbstractString=""; cached::Bool=false) - tree = GitTree(repo, "$treeish^{tree}") - try - diff = diff_tree(repo, tree, paths, cached=cached) - result = count(diff) > 0 - close(diff) - return result - finally - close(tree) - end -end - -""" - diff_files(repo::GitRepo, branch1::AbstractString, branch2::AbstractString; kwarg...) -> Vector{AbstractString} - -Show which files have changed in the git repository `repo` between branches `branch1` -and `branch2`. - -The keyword argument is: - * `filter::Set{Consts.DELTA_STATUS}=Set([Consts.DELTA_ADDED, Consts.DELTA_MODIFIED, Consts.DELTA_DELETED]))`, - and it sets options for the diff. The default is to show files added, modified, or deleted. - -Returns only the *names* of the files which have changed, *not* their contents. - -# Example - -```julia -LibGit2.branch!(repo, "branch/a") -LibGit2.branch!(repo, "branch/b") -# add a file to repo -open(joinpath(LibGit2.path(repo),"file"),"w") do f - write(f, "hello repo\n") -end -LibGit2.add!(repo, "file") -LibGit2.commit(repo, "add file") -# returns ["file"] -filt = Set([LibGit2.Consts.DELTA_ADDED]) -files = LibGit2.diff_files(repo, "branch/a", "branch/b", filter=filt) -# returns [] because existing files weren't modified -filt = Set([LibGit2.Consts.DELTA_MODIFIED]) -files = LibGit2.diff_files(repo, "branch/a", "branch/b", filter=filt) -``` - -Equivalent to `git diff --name-only --diff-filter= `. -""" -function diff_files(repo::GitRepo, branch1::AbstractString, branch2::AbstractString; - filter::Set{Consts.DELTA_STATUS}=Set([Consts.DELTA_ADDED, Consts.DELTA_MODIFIED, Consts.DELTA_DELETED])) - b1_id = revparseid(repo, branch1*"^{tree}") - b2_id = revparseid(repo, branch2*"^{tree}") - tree1 = GitTree(repo, b1_id) - tree2 = GitTree(repo, b2_id) - files = AbstractString[] - try - diff = diff_tree(repo, tree1, tree2) - for i in 1:count(diff) - delta = diff[i] - delta === nothing && break - if Consts.DELTA_STATUS(delta.status) in filter - push!(files, unsafe_string(delta.new_file.path)) - end - end - close(diff) - finally - close(tree1) - close(tree2) - end - return files -end - -""" - is_ancestor_of(a::AbstractString, b::AbstractString, repo::GitRepo) -> Bool - -Returns `true` if `a`, a [`GitHash`](@ref) in string form, is an ancestor of -`b`, a [`GitHash`](@ref) in string form. - -# Example - -```julia-repl -julia> repo = LibGit2.GitRepo(repo_path); - -julia> LibGit2.add!(repo, test_file1); - -julia> commit_oid1 = LibGit2.commit(repo, "commit1"); - -julia> LibGit2.add!(repo, test_file2); - -julia> commit_oid2 = LibGit2.commit(repo, "commit2"); - -julia> LibGit2.is_ancestor_of(string(commit_oid1), string(commit_oid2), repo) -true -``` -""" -function is_ancestor_of(a::AbstractString, b::AbstractString, repo::GitRepo) - A = revparseid(repo, a) - merge_base(repo, a, b) == A -end - -""" - set_remote_url(repo::GitRepo, url::AbstractString; remote::AbstractString="origin") - -Set the `url` for `remote` for the git repository `repo`. -The default name of the remote is `"origin"`. - -# Examples - -```julia -repo_path = joinpath("test_directory", "Example") -repo = LibGit2.init(repo_path) -url1 = "https://github.com/JuliaLang/Example.jl" -LibGit2.set_remote_url(repo, url1, remote="upstream") -url2 = "https://github.com/JuliaLang/Example2.jl" -LibGit2.set_remote_url(repo_path, url2, remote="upstream2") -``` -""" -function set_remote_url(repo::GitRepo, url::AbstractString; remote::AbstractString="origin") - with(GitConfig, repo) do cfg - set!(cfg, "remote.$remote.url", url) - set!(cfg, "remote.$remote.pushurl", url) - end -end - -""" - set_remote_url(path::AbstractString, url::AbstractString; remote::AbstractString="origin") - -Set the `url` for `remote` for the git repository located at `path`. -The default name of the remote is `"origin"`. -""" -function set_remote_url(path::AbstractString, url::AbstractString; remote::AbstractString="origin") - with(GitRepo, path) do repo - set_remote_url(repo, url, remote=remote) - end -end - -function make_payload(payload::Nullable{<:AbstractCredentials}) - Ref{Nullable{AbstractCredentials}}(payload) -end - -""" - fetch(repo::GitRepo; kwargs...) - -Fetches updates from an upstream of the repository `repo`. - -The keyword arguments are: - * `remote::AbstractString="origin"`: which remote, specified by name, - of `repo` to fetch from. If this is empty, the URL will be used to - construct an anonymous remote. - * `remoteurl::AbstractString=""`: the URL of `remote`. If not specified, - will be assumed based on the given name of `remote`. - * `refspecs=AbstractString[]`: determines properties of the fetch. - * `payload=Nullable{AbstractCredentials}()`: provides credentials, if necessary, - for instance if `remote` is a private repository. - -Equivalent to `git fetch [|] []`. -""" -function fetch(repo::GitRepo; remote::AbstractString="origin", - remoteurl::AbstractString="", - refspecs::Vector{<:AbstractString}=AbstractString[], - payload::Nullable{<:AbstractCredentials}=Nullable{AbstractCredentials}()) - rmt = if isempty(remoteurl) - get(GitRemote, repo, remote) - else - GitRemoteAnon(repo, remoteurl) - end - try - payload = make_payload(payload) - fo = FetchOptions(callbacks=RemoteCallbacks(credentials_cb(), payload)) - fetch(rmt, refspecs, msg="from $(url(rmt))", options = fo) - finally - close(rmt) - end -end - -""" - push(repo::GitRepo; kwargs...) - -Pushes updates to an upstream of `repo`. - -The keyword arguments are: - * `remote::AbstractString="origin"`: the name of the upstream remote to push to. - * `remoteurl::AbstractString=""`: the URL of `remote`. - * `refspecs=AbstractString[]`: determines properties of the push. - * `force::Bool=false`: determines if the push will be a force push, - overwriting the remote branch. - * `payload=Nullable{AbstractCredentials}()`: provides credentials, if necessary, - for instance if `remote` is a private repository. - -Equivalent to `git push [|] []`. -""" -function push(repo::GitRepo; remote::AbstractString="origin", - remoteurl::AbstractString="", - refspecs::Vector{<:AbstractString}=AbstractString[], - force::Bool=false, - payload::Nullable{<:AbstractCredentials}=Nullable{AbstractCredentials}()) - rmt = if isempty(remoteurl) - get(GitRemote, repo, remote) - else - GitRemoteAnon(repo, remoteurl) - end - try - payload = make_payload(payload) - push_opts=PushOptions(callbacks=RemoteCallbacks(credentials_cb(), payload)) - push(rmt, refspecs, force=force, options=push_opts) - finally - close(rmt) - end -end - -""" - branch(repo::GitRepo) - -Equivalent to `git branch`. -Create a new branch from the current HEAD. -""" -function branch(repo::GitRepo) - head_ref = head(repo) - try - branch(head_ref) - finally - close(head_ref) - end -end - -""" - branch!(repo::GitRepo, branch_name::AbstractString, commit::AbstractString=""; kwargs...) - -Checkout a new git branch in the `repo` repository. `commit` is the [`GitHash`](@ref), -in string form, which will be the start of the new branch. -If `commit` is an empty string, the current HEAD will be used. - -The keyword arguments are: - * `track::AbstractString=""`: the name of the - remote branch this new branch should track, if any. - If empty (the default), no remote branch - will be tracked. - * `force::Bool=false`: if `true`, branch creation will - be forced. - * `set_head::Bool=true`: if `true`, after the branch creation - finishes the branch head will be set as the HEAD of `repo`. - -Equivalent to `git checkout [-b|-B] [] [--track ]`. - -# Example - -```julia -repo = LibGit2.GitRepo(repo_path) -LibGit2.branch!(repo, "new_branch", set_head=false) -``` -""" -function branch!(repo::GitRepo, branch_name::AbstractString, - commit::AbstractString = ""; # start point - track::AbstractString = "", # track remote branch - force::Bool=false, # force branch creation - set_head::Bool=true) # set as head reference on exit - # try to lookup branch first - branch_ref = force ? Nullable{GitReference}() : lookup_branch(repo, branch_name) - if isnull(branch_ref) - branch_rmt_ref = isempty(track) ? Nullable{GitReference}() : lookup_branch(repo, "$track/$branch_name", true) - # if commit is empty get head commit oid - commit_id = if isempty(commit) - if isnull(branch_rmt_ref) - with(head(repo)) do head_ref - with(peel(GitCommit, head_ref)) do hrc - GitHash(hrc) - end - end - else - tmpcmt = with(peel(GitCommit, Base.get(branch_rmt_ref))) do hrc - GitHash(hrc) - end - close(Base.get(branch_rmt_ref)) - tmpcmt - end - else - GitHash(commit) - end - iszero(commit_id) && return - cmt = GitCommit(repo, commit_id) - new_branch_ref = nothing - try - new_branch_ref = Nullable(create_branch(repo, branch_name, cmt, force=force)) - finally - close(cmt) - isnull(new_branch_ref) && throw(GitError(Error.Object, Error.ERROR, "cannot create branch `$branch_name` with `$commit_id`")) - branch_ref = new_branch_ref - end - end - try - #TODO: what if branch tracks other then "origin" remote - if !isempty(track) # setup tracking - try - with(GitConfig, repo) do cfg - set!(cfg, "branch.$branch_name.remote", Consts.REMOTE_ORIGIN) - set!(cfg, "branch.$branch_name.merge", name(Base.get(branch_ref))) - end - catch - warn("Please provide remote tracking for branch '$branch_name' in '$(path(repo))'") - end - end - - if set_head - # checkout selected branch - with(peel(GitTree, Base.get(branch_ref))) do btree - checkout_tree(repo, btree) - end - - # switch head to the branch - head!(repo, Base.get(branch_ref)) - end - finally - close(Base.get(branch_ref)) - end - return -end - -""" - checkout!(repo::GitRepo, commit::AbstractString=""; force::Bool=true) - -Equivalent to `git checkout [-f] --detach `. -Checkout the git commit `commit` (a [`GitHash`](@ref) in string form) -in `repo`. If `force` is `true`, force the checkout and discard any -current changes. Note that this detaches the current HEAD. - -# Example - -```julia -repo = LibGit2.init(repo_path) -open(joinpath(LibGit2.path(repo), "file1"), "w") do f - write(f, "111\n") -end -LibGit2.add!(repo, "file1") -commit_oid = LibGit2.commit(repo, "add file1") -open(joinpath(LibGit2.path(repo), "file1"), "w") do f - write(f, "112\n") -end -# would fail without the force=true -# since there are modifications to the file -LibGit2.checkout!(repo, string(commit_oid), force=true) -``` -""" -function checkout!(repo::GitRepo, commit::AbstractString = ""; - force::Bool = true) - # nothing to do - isempty(commit) && return - - # grab head name - head_name = Consts.HEAD_FILE - try - with(head(repo)) do head_ref - head_name = shortname(head_ref) - # if it is HEAD use short OID instead - if head_name == Consts.HEAD_FILE - head_name = string(GitHash(head_ref)) - end - end - end - - # search for commit to get a commit object - obj = GitObject(repo, GitHash(commit)) - peeled = peel(GitCommit, obj) - obj_oid = GitHash(peeled) - - # checkout commit - checkout_tree(repo, peeled, options = force ? CheckoutOptions(checkout_strategy = Consts.CHECKOUT_FORCE) : CheckoutOptions()) - - GitReference(repo, obj_oid, force=force, - msg="libgit2.checkout: moving from $head_name to $(obj_oid))") - - return nothing -end - -""" - clone(repo_url::AbstractString, repo_path::AbstractString; kwargs...) - -Clone a remote repository located at `repo_url` to the local filesystem location `repo_path`. - -The keyword arguments are: - * `branch::AbstractString=""`: which branch of the remote to clone, - if not the default repository branch (usually `master`). - * `isbare::Bool=false`: if `true`, clone the remote as a bare repository, - which will make `repo_path` itself the git directory instead of `repo_path/.git`. - This means that a working tree cannot be checked out. Plays the role of the - git CLI argument `--bare`. - * `remote_cb::Ptr{Void}=C_NULL`: a callback which will be used to create the remote - before it is cloned. If `C_NULL` (the default), no attempt will be made to create - the remote - it will be assumed to already exist. - * `payload::Nullable{P<:AbstractCredentials}=Nullable{AbstractCredentials}()`: - provides credentials if necessary, for instance if the remote is a private - repository. - -Equivalent to `git clone [-b ] [--bare] `. - -# Examples - -```julia -repo_url = "https://github.com/JuliaLang/Example.jl" -repo1 = LibGit2.clone(repo_url, "test_path") -repo2 = LibGit2.clone(repo_url, "test_path", isbare=true) -julia_url = "https://github.com/JuliaLang/julia" -julia_repo = LibGit2.clone(julia_url, "julia_path", branch="release-0.6") -``` -""" -function clone(repo_url::AbstractString, repo_path::AbstractString; - branch::AbstractString="", - isbare::Bool = false, - remote_cb::Ptr{Void} = C_NULL, - payload::Nullable{<:AbstractCredentials}=Nullable{AbstractCredentials}()) - # setup clone options - lbranch = Base.cconvert(Cstring, branch) - payload = make_payload(payload) - fetch_opts=FetchOptions(callbacks = RemoteCallbacks(credentials_cb(), payload)) - clone_opts = CloneOptions( - bare = Cint(isbare), - checkout_branch = isempty(lbranch) ? Cstring(C_NULL) : Base.unsafe_convert(Cstring, lbranch), - fetch_opts=fetch_opts, - remote_cb = remote_cb - ) - return clone(repo_url, repo_path, clone_opts) -end - -""" git reset [] [--] ... """ -function reset!(repo::GitRepo, committish::AbstractString, pathspecs::AbstractString...) - obj = GitObject(repo, isempty(committish) ? Consts.HEAD_FILE : committish) - # do not remove entries in the index matching the provided pathspecs with empty target commit tree - reset!(repo, Nullable(obj), pathspecs...) -end - -""" - reset!(repo::GitRepo, id::GitHash, mode::Cint = Consts.RESET_MIXED) - -Reset the repository `repo` to its state at `id`, using one of three modes -set by `mode`: - 1. `Consts.RESET_SOFT` - move HEAD to `id`. - 2. `Consts.RESET_MIXED` - default, move HEAD to `id` and reset the index to `id`. - 3. `Consts.RESET_HARD` - move HEAD to `id`, reset the index to `id`, and discard all working changes. - -Equivalent to `git reset [--soft | --mixed | --hard] `. - -# Example - -```julia -repo = LibGit2.GitRepo(repo_path) -head_oid = LibGit2.head_oid(repo) -open(joinpath(repo_path, "file1"), "w") do f - write(f, "111\n") -end -LibGit2.add!(repo, "file1") -mode = LibGit2.Consts.RESET_HARD -# will discard the changes to file1 -# and unstage it -new_head = LibGit2.reset!(repo, head_oid, mode) -``` -""" -reset!(repo::GitRepo, id::GitHash, mode::Cint = Consts.RESET_MIXED) = - reset!(repo, GitObject(repo, id), mode) - -""" - LibGit2.revcount(repo::GitRepo, commit1::AbstractString, commit2::AbstractString) - -List the number of revisions between `commit1` and `commit2` (committish OIDs in string form). -Since `commit1` and `commit2` may be on different branches, `revcount` performs a "left-right" -revision list (and count), returning a tuple of `Int`s - the number of left and right -commits, respectively. A left (or right) commit refers to which side of a symmetric -difference in a tree the commit is reachable from. - -Equivalent to `git rev-list --left-right --count `. -""" -function revcount(repo::GitRepo, commit1::AbstractString, commit2::AbstractString) - commit1_id = revparseid(repo, commit1) - commit2_id = revparseid(repo, commit2) - base_id = merge_base(repo, string(commit1_id), string(commit2_id)) - fc = with(GitRevWalker(repo)) do walker - count((i,r)->i!=base_id, walker, oid=commit1_id, by=Consts.SORT_TOPOLOGICAL) - end - sc = with(GitRevWalker(repo)) do walker - count((i,r)->i!=base_id, walker, oid=commit2_id, by=Consts.SORT_TOPOLOGICAL) - end - return (fc-1, sc-1) -end - -""" - merge!(repo::GitRepo; kwargs...) -> Bool - -Perform a git merge on the repository `repo`, merging commits -with diverging history into the current branch. Returns `true` -if the merge succeeded, `false` if not. - -The keyword arguments are: - * `committish::AbstractString=""`: Merge the named commit(s) in `committish`. - * `branch::AbstractString=""`: Merge the branch `branch` and all its commits - since it diverged from the current branch. - * `fastforward::Bool=false`: If `fastforward` is `true`, only merge if the - merge is a fast-forward (the current branch head is an ancestor of the - commits to be merged), otherwise refuse to merge and return `false`. - This is equivalent to the git CLI option `--ff-only`. - * `merge_opts::MergeOptions=MergeOptions()`: `merge_opts` specifies options - for the merge, such as merge strategy in case of conflicts. - * `checkout_opts::CheckoutOptions=CheckoutOptions()`: `checkout_opts` specifies - options for the checkout step. - -Equivalent to `git merge [--ff-only] [ | ]`. - -!!! note - If you specify a `branch`, this must be done in reference format, since - the string will be turned into a `GitReference`. For example, if you - wanted to merge branch `branch_a`, you would call - `merge!(repo, branch="refs/heads/branch_a")`. -""" -function merge!(repo::GitRepo; - committish::AbstractString = "", - branch::AbstractString = "", - fastforward::Bool = false, - merge_opts::MergeOptions = MergeOptions(), - checkout_opts::CheckoutOptions = CheckoutOptions()) - # merge into head branch - upst_anns = if !isempty(committish) # merge committish into HEAD - if committish == Consts.FETCH_HEAD # merge FETCH_HEAD - fheads = fetchheads(repo) - filter!(fh->fh.ismerge, fheads) - if isempty(fheads) - throw(GitError(Error.Merge, Error.ERROR, - "There is no fetch reference for this branch.")) - end - map(fh->GitAnnotated(repo,fh), fheads) - else # merge commitish - [GitAnnotated(repo, committish)] - end - else - if !isempty(branch) # merge provided branch into HEAD - with(GitReference(repo, branch)) do brn_ref - [GitAnnotated(repo, brn_ref)] - end - else # try to get tracking remote branch for the head - if !isattached(repo) - throw(GitError(Error.Merge, Error.ERROR, - "Repository HEAD is detached. Remote tracking branch cannot be used.")) - end - if isorphan(repo) - # this isn't really a merge, but really moving HEAD - # https://github.com/libgit2/libgit2/issues/2135#issuecomment-35997764 - # try to figure out remote tracking of orphan head - - m = with(GitReference(repo, Consts.HEAD_FILE)) do head_sym_ref - match(r"refs/heads/(.*)", fullname(head_sym_ref)) - end - if m === nothing - throw(GitError(Error.Merge, Error.ERROR, - "Unable to determine name of orphan branch.")) - end - branchname = m.captures[1] - remotename = with(GitConfig, repo) do cfg - LibGit2.get(String, cfg, "branch.$branchname.remote") - end - oid = with(GitReference(repo, "refs/remotes/$remotename/$branchname")) do ref - LibGit2.GitHash(ref) - end - with(GitCommit(repo, oid)) do cmt - LibGit2.create_branch(repo, branchname, cmt) - end - return true - else - with(head(repo)) do head_ref - tr_brn_ref = upstream(head_ref) - if isnull(tr_brn_ref) - throw(GitError(Error.Merge, Error.ERROR, - "There is no tracking information for the current branch.")) - end - try - [GitAnnotated(repo, Base.get(tr_brn_ref))] - finally - close(Base.get(tr_brn_ref)) - end - end - end - end - end - try - merge!(repo, upst_anns, fastforward, - merge_opts=merge_opts, - checkout_opts=checkout_opts) - finally - map(close, upst_anns) - end -end - -""" - LibGit2.rebase!(repo::GitRepo, upstream::AbstractString="", newbase::AbstractString="") - -Attempt an automatic merge rebase of the current branch, from `upstream` if provided, or -otherwise from the upstream tracking branch. -`newbase` is the branch to rebase onto. By default this is `upstream`. - -If any conflicts arise which cannot be automatically resolved, the rebase will abort, -leaving the repository and working tree in its original state, and the function will throw -a `GitError`. This is roughly equivalent to the following command line statement: - - git rebase --merge [] - if [ -d ".git/rebase-merge" ]; then - git rebase --abort - fi - -""" -function rebase!(repo::GitRepo, upstream::AbstractString="", newbase::AbstractString="") - with(head(repo)) do head_ref - head_ann = GitAnnotated(repo, head_ref) - upst_ann = if isempty(upstream) - brn_ref = LibGit2.upstream(head_ref) - if isnull(brn_ref) - throw(GitError(Error.Rebase, Error.ERROR, - "There is no tracking information for the current branch.")) - end - try - GitAnnotated(repo, Base.get(brn_ref)) - finally - close(brn_ref) - end - else - GitAnnotated(repo, upstream) - end - onto_ann = Nullable{GitAnnotated}(isempty(newbase) ? nothing : GitAnnotated(repo, newbase)) - try - sig = default_signature(repo) - try - rbs = GitRebase(repo, head_ann, upst_ann, onto=onto_ann) - try - while (rbs_op = next(rbs)) !== nothing - commit(rbs, sig) - end - finish(rbs, sig) - catch err - abort(rbs) - rethrow(err) - finally - close(rbs) - end - finally - #!isnull(onto_ann) && close(get(onto_ann)) - close(sig) - end - finally - if !isempty(newbase) - close(Base.get(onto_ann)) - end - close(upst_ann) - close(head_ann) - end - end - return head_oid(repo) -end - - -""" - authors(repo::GitRepo) -> Vector{Signature} - -Returns all authors of commits to the `repo` repository. - -# Example - -```julia -repo = LibGit2.GitRepo(repo_path) -repo_file = open(joinpath(repo_path, test_file), "a") - -println(repo_file, commit_msg) -flush(repo_file) -LibGit2.add!(repo, test_file) -sig = LibGit2.Signature("TEST", "TEST@TEST.COM", round(time(), 0), 0) -commit_oid1 = LibGit2.commit(repo, "commit1"; author=sig, committer=sig) -println(repo_file, randstring(10)) -flush(repo_file) -LibGit2.add!(repo, test_file) -commit_oid2 = LibGit2.commit(repo, "commit2"; author=sig, committer=sig) - -# will be a Vector of [sig, sig] -auths = LibGit2.authors(repo) -``` -""" -function authors(repo::GitRepo) - return with(GitRevWalker(repo)) do walker - map((oid,repo)->with(GitCommit(repo, oid)) do cmt - author(cmt)::Signature - end, - walker) #, by = Consts.SORT_TIME) - end -end - -""" - snapshot(repo::GitRepo) -> State - -Take a snapshot of the current state of the repository `repo`, -storing the current HEAD, index, and any uncommitted work. -The output `State` can be used later during a call to [`restore`](@ref) -to return the repository to the snapshotted state. -""" -function snapshot(repo::GitRepo) - head = GitHash(repo, Consts.HEAD_FILE) - index = with(GitIndex, repo) do idx; write_tree!(idx) end - work = try - with(GitIndex, repo) do idx - if length(readdir(path(repo))) > 1 - add!(idx, ".") - write!(idx) - end - write_tree!(idx) - end - finally - # restore index - with(GitIndex, repo) do idx - read_tree!(idx, index) - write!(idx) - end - end - State(head, index, work) -end - -""" - restore(s::State, repo::GitRepo) - -Return a repository `repo` to a previous `State` `s`, for -example the HEAD of a branch before a merge attempt. `s` -can be generated using the [`snapshot`](@ref) function. -""" -function restore(s::State, repo::GitRepo) - head = reset!(repo, Consts.HEAD_FILE, "*") # unstage everything - with(GitIndex, repo) do idx - read_tree!(idx, s.work) # move work tree to index - opts = CheckoutOptions( - checkout_strategy = Consts.CHECKOUT_FORCE | # check the index out to work - Consts.CHECKOUT_REMOVE_UNTRACKED) # remove everything else - checkout_index(repo, Nullable(idx), options = opts) - - read_tree!(idx, s.index) # restore index - end - reset!(repo, s.head, Consts.RESET_SOFT) # restore head -end - -function transact(f::Function, repo::GitRepo) - state = snapshot(repo) - try f(repo) catch - restore(state, repo) - rethrow() - finally - close(repo) - end -end - -function set_ssl_cert_locations(cert_loc) - cert_file = isfile(cert_loc) ? cert_loc : Cstring(C_NULL) - cert_dir = isdir(cert_loc) ? cert_loc : Cstring(C_NULL) - cert_file == C_NULL && cert_dir == C_NULL && return - # TODO FIX https://github.com/libgit2/libgit2/pull/3935#issuecomment-253910017 - #ccall((:git_libgit2_opts, :libgit2), Cint, - # (Cint, Cstring, Cstring), - # Cint(Consts.SET_SSL_CERT_LOCATIONS), cert_file, cert_dir) - ENV["SSL_CERT_FILE"] = cert_file - ENV["SSL_CERT_DIR"] = cert_dir -end - -function __init__() - # Look for OpenSSL env variable for CA bundle (linux only) - # windows and macOS use the OS native security backends - old_ssl_cert_dir = Base.get(ENV, "SSL_CERT_DIR", nothing) - old_ssl_cert_file = Base.get(ENV, "SSL_CERT_FILE", nothing) - @static if is_linux() - cert_loc = if "SSL_CERT_DIR" in keys(ENV) - ENV["SSL_CERT_DIR"] - elseif "SSL_CERT_FILE" in keys(ENV) - ENV["SSL_CERT_FILE"] - else - # If we have a bundled ca cert file, point libgit2 at that so SSL connections work. - abspath(ccall(:jl_get_julia_home, Any, ()),Base.DATAROOTDIR,"julia","cert.pem") - end - set_ssl_cert_locations(cert_loc) - end - - err = ccall((:git_libgit2_init, :libgit2), Cint, ()) - err > 0 || throw(ErrorException("error initializing LibGit2 module")) - REFCOUNT[] = 1 - - atexit() do - if Threads.atomic_sub!(REFCOUNT, UInt(1)) == 1 - # refcount zero, no objects to be finalized - ccall((:git_libgit2_shutdown, :libgit2), Cint, ()) - end - end - - @static if is_linux() - if old_ssl_cert_dir != Base.get(ENV, "SSL_CERT_DIR", "") - if old_ssl_cert_dir === nothing - delete!(ENV, "SSL_CERT_DIR") - else - ENV["SSL_CERT_DIR"] = old_ssl_cert_dir - end - end - if old_ssl_cert_file != Base.get(ENV, "SSL_CERT_FILE", "") - if old_ssl_cert_file === nothing - delete!(ENV, "SSL_CERT_FILE") - else - ENV["SSL_CERT_FILE"] = old_ssl_cert_file - end - end - end -end - - -end # module diff --git a/julia-0.6.3/share/julia/base/libgit2/merge.jl b/julia-0.6.3/share/julia/base/libgit2/merge.jl deleted file mode 100644 index 2760a40..0000000 --- a/julia-0.6.3/share/julia/base/libgit2/merge.jl +++ /dev/null @@ -1,154 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -function GitAnnotated(repo::GitRepo, commit_id::GitHash) - ann_ptr_ptr = Ref{Ptr{Void}}(C_NULL) - @check ccall((:git_annotated_commit_lookup, :libgit2), Cint, - (Ptr{Ptr{Void}}, Ptr{Void}, Ptr{GitHash}), - ann_ptr_ptr, repo.ptr, Ref(commit_id)) - return GitAnnotated(repo, ann_ptr_ptr[]) -end - -function GitAnnotated(repo::GitRepo, ref::GitReference) - ann_ref_ref = Ref{Ptr{Void}}(C_NULL) - @check ccall((:git_annotated_commit_from_ref, :libgit2), Cint, - (Ptr{Ptr{Void}}, Ptr{Void}, Ptr{Void}), - ann_ref_ref, repo.ptr, ref.ptr) - return GitAnnotated(repo, ann_ref_ref[]) -end - -function GitAnnotated(repo::GitRepo, fh::FetchHead) - ann_ref_ref = Ref{Ptr{Void}}(C_NULL) - @check ccall((:git_annotated_commit_from_fetchhead, :libgit2), Cint, - (Ptr{Ptr{Void}}, Ptr{Void}, Cstring, Cstring, Ptr{GitHash}), - ann_ref_ref, repo.ptr, fh.name, fh.url, Ref(fh.oid)) - return GitAnnotated(repo, ann_ref_ref[]) -end - -function GitAnnotated(repo::GitRepo, comittish::AbstractString) - obj = GitObject(repo, comittish) - cmt = peel(GitCommit, obj) - return GitAnnotated(repo, GitHash(cmt)) -end - -function GitHash(ann::GitAnnotated) - unsafe_load(ccall((:git_annotated_commit_id, :libgit2), Ptr{GitHash}, (Ptr{Void},), ann.ptr)) -end - -function merge_analysis(repo::GitRepo, anns::Vector{GitAnnotated}) - analysis = Ref{Cint}(0) - preference = Ref{Cint}(0) - anns_ref = Ref(map(a->a.ptr, anns)) - anns_size = Csize_t(length(anns)) - @check ccall((:git_merge_analysis, :libgit2), Cint, - (Ptr{Cint}, Ptr{Cint}, Ptr{Void}, Ptr{Ptr{Void}}, Csize_t), - analysis, preference, repo.ptr, anns_ref, anns_size) - return analysis[], preference[] -end - -"""Fastforward merge changes into current head """ -function ffmerge!(repo::GitRepo, ann::GitAnnotated) - cmt = GitCommit(repo, GitHash(ann)) - - checkout_tree(repo, cmt) - with(head(repo)) do head_ref - cmt_oid = GitHash(cmt) - msg = "libgit2.merge: fastforward $(string(cmt_oid)) into $(name(head_ref))" - new_head_ref = if reftype(head_ref) == Consts.REF_OID - target!(head_ref, cmt_oid, msg=msg) - else - GitReference(repo, cmt_oid, fullname(head_ref), msg=msg) - end - close(new_head_ref) - end - return true -end - -""" Merge changes into current head """ -function merge!(repo::GitRepo, anns::Vector{GitAnnotated}; - merge_opts::MergeOptions = MergeOptions(), - checkout_opts::CheckoutOptions = CheckoutOptions()) - anns_size = Csize_t(length(anns)) - @check ccall((:git_merge, :libgit2), Cint, - (Ptr{Void}, Ptr{Ptr{Void}}, Csize_t, - Ptr{MergeOptions}, Ptr{CheckoutOptions}), - repo.ptr, map(x->x.ptr, anns), anns_size, - Ref(merge_opts), Ref(checkout_opts)) - info("Review and commit merged changes.") - return true -end - -"""Internal implementation of merge. -Returns `true` if merge was successful, otherwise `false` -""" -function merge!(repo::GitRepo, anns::Vector{GitAnnotated}, fastforward::Bool; - merge_opts::MergeOptions = MergeOptions(), - checkout_opts::CheckoutOptions = CheckoutOptions()) - ma, mp = merge_analysis(repo, anns) - if isset(ma, Cint(Consts.MERGE_ANALYSIS_UP_TO_DATE)) - return true # no merge - everything is up to date - end - - ffpref = if fastforward - Consts.MERGE_PREFERENCE_FASTFORWARD_ONLY - elseif isset(mp, Cint(Consts.MERGE_PREFERENCE_NONE)) - Consts.MERGE_PREFERENCE_NONE - elseif isset(mp, Cint(Consts.MERGE_PREFERENCE_NO_FASTFORWARD)) - Consts.MERGE_PREFERENCE_NO_FASTFORWARD - elseif isset(mp, Cint(Consts.MERGE_PREFERENCE_FASTFORWARD_ONLY)) - Consts.MERGE_PREFERENCE_FASTFORWARD_ONLY - else - throw(ArgumentError("unknown merge preference: $(mp).")) - end - - merge_result = if ffpref == Consts.MERGE_PREFERENCE_NONE - if isset(ma, Cint(Consts.MERGE_ANALYSIS_FASTFORWARD)) - if length(anns) > 1 - warn("Unable to perform Fast-Forward merge with mith multiple merge heads.") - false - else - ffmerge!(repo, anns[1]) - end - elseif isset(ma, Cint(Consts.MERGE_ANALYSIS_NORMAL)) - merge!(repo, anns, - merge_opts=merge_opts, - checkout_opts=checkout_opts) - end - elseif ffpref == Consts.MERGE_PREFERENCE_FASTFORWARD_ONLY - if isset(ma, Cint(Consts.MERGE_ANALYSIS_FASTFORWARD)) - if length(anns) > 1 - warn("Unable to perform Fast-Forward merge with mith multiple merge heads.") - false - else - ffmerge!(repo, anns[1]) - end - else - warn("Cannot perform fast-forward merge.") - false - end - elseif ffpref == Consts.MERGE_PREFERENCE_NO_FASTFORWARD - if isset(ma, Cint(Consts.MERGE_ANALYSIS_NORMAL)) - merge!(repo, anns, - merge_opts=merge_opts, - checkout_opts=checkout_opts) - end - else - throw(ArgumentError("unknown merge analysis result: $(ma)")) - end - return merge_result -end - -function merge_base(repo::GitRepo, one::AbstractString, two::AbstractString) - oid1_ptr = Ref(GitHash(one)) - oid2_ptr = Ref(GitHash(two)) - moid_ptr = Ref(GitHash()) - moid = try - @check ccall((:git_merge_base, :libgit2), Cint, - (Ptr{GitHash}, Ptr{Void}, Ptr{GitHash}, Ptr{GitHash}), - moid_ptr, repo.ptr, oid1_ptr, oid2_ptr) - moid_ptr[] - catch e - #warn("Pkg:",path(repo),"=>",e.msg) - GitHash() - end - return moid -end diff --git a/julia-0.6.3/share/julia/base/libgit2/oid.jl b/julia-0.6.3/share/julia/base/libgit2/oid.jl deleted file mode 100644 index 21e527c..0000000 --- a/julia-0.6.3/share/julia/base/libgit2/oid.jl +++ /dev/null @@ -1,106 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -function GitHash(ptr::Ptr{UInt8}) - if ptr == C_NULL - throw(ArgumentError("NULL pointer passed to GitHash() constructor")) - end - oid_ptr = Ref(GitHash()) - ccall((:git_oid_fromraw, :libgit2), Void, (Ptr{GitHash}, Ptr{UInt8}), oid_ptr, ptr) - return oid_ptr[] -end - -function GitHash(id::Array{UInt8,1}) - if length(id) != OID_RAWSZ - throw(ArgumentError("invalid raw buffer size")) - end - return GitHash(pointer(id)) -end - -function GitHash(id::AbstractString) - bstr = String(id) - len = sizeof(bstr) - if len < OID_HEXSZ - throw(ArgumentError("Input string is too short, use `GitShortHash` for partial hashes")) - end - oid_ptr = Ref{GitHash}() - @check ccall((:git_oid_fromstrn, :libgit2), Cint, - (Ptr{GitHash}, Ptr{UInt8}, Csize_t), oid_ptr, bstr, len) - return oid_ptr[] -end -function GitShortHash(id::AbstractString) - bstr = String(id) - len = sizeof(bstr) - oid_ptr = Ref{GitHash}() - @check ccall((:git_oid_fromstrn, :libgit2), Cint, - (Ptr{GitHash}, Ptr{UInt8}, Csize_t), oid_ptr, bstr, len) - GitShortHash(oid_ptr[], len) -end - -macro githash_str(id) - bstr = String(id) - if sizeof(bstr) < OID_HEXSZ - GitShortHash(id) - else - GitHash(id) - end -end -function GitHash(ref::GitReference) - isempty(ref) && return GitHash() - reftype(ref) != Consts.REF_OID && return GitHash() - oid_ptr = ccall((:git_reference_target, :libgit2), Ptr{UInt8}, (Ptr{Void},), ref.ptr) - oid_ptr == C_NULL && return GitHash() - return GitHash(oid_ptr) -end - -function GitHash(repo::GitRepo, ref_name::AbstractString) - isempty(repo) && return GitHash() - oid_ptr = Ref(GitHash()) - @check ccall((:git_reference_name_to_id, :libgit2), Cint, - (Ptr{GitHash}, Ptr{Void}, Cstring), - oid_ptr, repo.ptr, ref_name) - return oid_ptr[] -end - -function GitHash(obj::GitObject) - GitHash(ccall((:git_object_id, :libgit2), Ptr{UInt8}, (Ptr{Void},), obj.ptr)) -end - -Base.hex(id::GitHash) = join([hex(i,2) for i in id.val]) -Base.hex(id::GitShortHash) = hex(id.hash)[1:id.len] - -raw(id::GitHash) = collect(id.val) - -Base.string(id::AbstractGitHash) = hex(id) - -Base.show(io::IO, id::GitHash) = print(io, "GitHash(\"$(string(id))\")") -Base.show(io::IO, id::GitShortHash) = print(io, "GitShortHash(\"$(string(id))\")") - -Base.hash(id::GitHash, h::UInt) = hash(id.val, h) - -function Base.cmp(id1::GitHash, id2::GitHash) - Int(ccall((:git_oid_cmp, :libgit2), Cint, - (Ptr{GitHash}, Ptr{GitHash}), - Ref(id1), Ref(id2))) -end -function Base.cmp(id1::GitShortHash, id2::GitShortHash) - # shortened hashes appear at the beginning of the order, i.e. - # 000 < 01 < 010 < 011 < 0112 - c = Int(ccall((:git_oid_ncmp, :libgit2), Cint, - (Ptr{GitHash}, Ptr{GitHash}, Csize_t), - Ref(id1.hash), Ref(id2.hash), min(id1.len, id2.len))) - return c == 0 ? cmp(id1.len, id2.len) : c -end -Base.cmp(id1::GitHash, id2::GitShortHash) = cmp(GitShortHash(id1, OID_HEXSZ), id2) -Base.cmp(id1::GitShortHash, id2::GitHash) = cmp(id1, GitShortHash(id2, OID_HEXSZ)) - -==(id1::GitHash, id2::GitHash) = cmp(id1, id2) == 0 -Base.isless(id1::AbstractGitHash, id2::AbstractGitHash) = cmp(id1, id2) < 0 - -function iszero(id::GitHash) - for i in 1:OID_RAWSZ - id.val[i] != zero(UInt8) && return false - end - return true -end - -Base.zero(::Type{GitHash}) = GitHash() diff --git a/julia-0.6.3/share/julia/base/libgit2/rebase.jl b/julia-0.6.3/share/julia/base/libgit2/rebase.jl deleted file mode 100644 index c794e3f..0000000 --- a/julia-0.6.3/share/julia/base/libgit2/rebase.jl +++ /dev/null @@ -1,81 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -function GitRebase(repo::GitRepo, branch::GitAnnotated, upstream::GitAnnotated; - onto::Nullable{GitAnnotated}=Nullable{GitAnnotated}(), - opts::RebaseOptions = RebaseOptions()) - rebase_ptr_ptr = Ref{Ptr{Void}}(C_NULL) - @check ccall((:git_rebase_init, :libgit2), Cint, - (Ptr{Ptr{Void}}, Ptr{Void}, Ptr{Void}, Ptr{Void}, - Ptr{Void}, Ptr{RebaseOptions}), - rebase_ptr_ptr, repo.ptr, branch.ptr, upstream.ptr, - isnull(onto) ? C_NULL : Base.get(onto).ptr, Ref(opts)) - return GitRebase(repo, rebase_ptr_ptr[]) -end - -function Base.count(rb::GitRebase) - return ccall((:git_rebase_operation_entrycount, :libgit2), Csize_t, (Ptr{Void},), rb.ptr) -end - -function current(rb::GitRebase) - return ccall((:git_rebase_operation_current, :libgit2), Csize_t, (Ptr{Void},), rb.ptr) -end - -function Base.getindex(rb::GitRebase, i::Integer) - if !(1 <= i <= count(rb)) - throw(BoundsError(rb, (i,))) - end - rb_op_ptr = ccall((:git_rebase_operation_byindex, :libgit2), - Ptr{RebaseOperation}, - (Ptr{Void}, Csize_t), rb.ptr, i-1) - return unsafe_load(rb_op_ptr) -end - -function Base.next(rb::GitRebase) - rb_op_ptr_ptr = Ref{Ptr{RebaseOperation}}(C_NULL) - try - @check ccall((:git_rebase_next, :libgit2), Cint, - (Ptr{Ptr{RebaseOperation}}, Ptr{Void}), - rb_op_ptr_ptr, rb.ptr) - catch err - err.code == Error.ITEROVER && return nothing - rethrow(err) - end - return unsafe_load(rb_op_ptr_ptr[]) -end - -function Base.show(io::IO, rb::GitRebase) - println(io, "GitRebase:") - println(io, "Number: ", count(rb)) - println(io, "Currently performing operation: ", current(rb)+1) -end - -""" - LibGit2.commit(rb::GitRebase, sig::GitSignature) - -Commits the current patch to the rebase `rb`, using `sig` as the committer. Is silent if -the commit has already been applied. -""" -function commit(rb::GitRebase, sig::GitSignature) - oid_ptr = Ref(GitHash()) - try - @check ccall((:git_rebase_commit, :libgit2), Error.Code, - (Ptr{GitHash}, Ptr{Void}, Ptr{SignatureStruct}, Ptr{SignatureStruct}, Ptr{UInt8}, Ptr{UInt8}), - oid_ptr, rb.ptr, C_NULL, sig.ptr, C_NULL, C_NULL) - catch err - # TODO: return current HEAD instead - err.code == Error.EAPPLIED && return nothing - rethrow(err) - end - return oid_ptr[] -end - -function abort(rb::GitRebase) - return ccall((:git_rebase_abort, :libgit2), Csize_t, - (Ptr{Void},), rb.ptr) -end - -function finish(rb::GitRebase, sig::GitSignature) - return ccall((:git_rebase_finish, :libgit2), Csize_t, - (Ptr{Void}, Ptr{SignatureStruct}), - rb.ptr, sig.ptr) -end diff --git a/julia-0.6.3/share/julia/base/libgit2/reference.jl b/julia-0.6.3/share/julia/base/libgit2/reference.jl deleted file mode 100644 index da6f26b..0000000 --- a/julia-0.6.3/share/julia/base/libgit2/reference.jl +++ /dev/null @@ -1,347 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -function GitReference(repo::GitRepo, refname::AbstractString) - ref_ptr_ptr = Ref{Ptr{Void}}(C_NULL) - @check ccall((:git_reference_lookup, :libgit2), Cint, - (Ptr{Ptr{Void}}, Ptr{Void}, Cstring), - ref_ptr_ptr, repo.ptr, refname) - return GitReference(repo, ref_ptr_ptr[]) -end - -function GitReference(repo::GitRepo, obj_oid::GitHash, refname::AbstractString = Consts.HEAD_FILE; - force::Bool=false, msg::AbstractString="") - ref_ptr_ptr = Ref{Ptr{Void}}(C_NULL) - @check ccall((:git_reference_create, :libgit2), Cint, - (Ptr{Ptr{Void}}, Ptr{Void}, Ptr{UInt8}, Ptr{GitHash}, Cint, Cstring), - ref_ptr_ptr, repo.ptr, refname, Ref(obj_oid), Cint(force), - isempty(msg) ? C_NULL : msg) - return GitReference(repo, ref_ptr_ptr[]) -end - -""" - LibGit2.isorphan(repo::GitRepo) - -Checks if the current branch is an "orphan" branch, i.e. has no commits. The first commit -to this branch will have no parents. -""" -function isorphan(repo::GitRepo) - r = @check ccall((:git_repository_head_unborn, :libgit2), Cint, - (Ptr{Void},), repo.ptr) - r != 0 -end - -""" - LibGit2.head(repo::GitRepo) -> GitReference - -Returns a `GitReference` to the current HEAD of `repo`. -""" -function head(repo::GitRepo) - head_ptr_ptr = Ref{Ptr{Void}}(C_NULL) - @check ccall((:git_repository_head, :libgit2), Cint, - (Ptr{Ptr{Void}}, Ptr{Void}), head_ptr_ptr, repo.ptr) - return GitReference(repo, head_ptr_ptr[]) -end - -""" - LibGit2.shortname(ref::GitReference) - -Returns a shortened version of the name of `ref` that's -"human-readable". - -```julia-repl -julia> repo = LibGit2.GitRepo(path_to_repo); - -julia> branch_ref = LibGit2.head(repo); - -julia> LibGit2.name(branch_ref) -"refs/heads/master" - -julia> LibGit2.shortname(branch_ref) -"master" -``` -""" -function shortname(ref::GitReference) - isempty(ref) && return "" - name_ptr = ccall((:git_reference_shorthand, :libgit2), Cstring, (Ptr{Void},), ref.ptr) - name_ptr == C_NULL && return "" - return unsafe_string(name_ptr) -end - -""" - LibGit2.reftype(ref::GitReference) -> Cint - -Returns a `Cint` corresponding to the type of `ref`: - * `0` if the reference is invalid - * `1` if the reference is an object id - * `2` if the reference is symbolic -""" -function reftype(ref::GitReference) - return ccall((:git_reference_type, :libgit2), Cint, (Ptr{Void},), ref.ptr) -end - -""" - LibGit2.fullname(ref::GitReference) - -Return the name of the reference pointed to by the -symbolic reference `ref`. If `ref` is not a symbolic -reference, returns an empty string. -""" -function fullname(ref::GitReference) - isempty(ref) && return "" - reftype(ref) == Consts.REF_OID && return "" - rname = ccall((:git_reference_symbolic_target, :libgit2), Cstring, (Ptr{Void},), ref.ptr) - rname == C_NULL && return "" - return unsafe_string(rname) -end - -""" - LibGit2.name(ref::GitReference) - -Return the full name of `ref`. -""" -function name(ref::GitReference) - isempty(ref) && return "" - name_ptr = ccall((:git_reference_name, :libgit2), Cstring, (Ptr{Void},), ref.ptr) - name_ptr == C_NULL && return "" - return unsafe_string(name_ptr) -end - -function branch(ref::GitReference) - isempty(ref) && return "" - str_ptr_ptr = Ref{Cstring}() - @check ccall((:git_branch_name, :libgit2), Cint, - (Ptr{Cstring}, Ptr{Void},), str_ptr_ptr, ref.ptr) - return unsafe_string(str_ptr_ptr[]) -end - -function ishead(ref::GitReference) - isempty(ref) && return false - err = ccall((:git_branch_is_head, :libgit2), Cint, - (Ptr{Void},), ref.ptr) - return err == 1 -end - -function isbranch(ref::GitReference) - isempty(ref) && return false - err = ccall((:git_reference_is_branch, :libgit2), Cint, - (Ptr{Void},), ref.ptr) - return err == 1 -end - -function istag(ref::GitReference) - isempty(ref) && return false - err = ccall((:git_reference_is_tag, :libgit2), Cint, - (Ptr{Void},), ref.ptr) - return err == 1 -end - -function isremote(ref::GitReference) - isempty(ref) && return false - err = ccall((:git_reference_is_remote, :libgit2), Cint, - (Ptr{Void},), ref.ptr) - return err == 1 -end - -function Base.show(io::IO, ref::GitReference) - println(io, "GitReference:") - if isremote(ref) - println(io, "Remote with name ", name(ref)) - elseif isbranch(ref) - println(io, "Branch with name ", name(ref)) - if ishead(ref) - println(io, "Branch is HEAD.") - else - println(io, "Branch is not HEAD.") - end - elseif istag(ref) - println(io, "Tag with name ", name(ref)) - end -end - -""" - peel([T,] ref::GitReference) - -Recursively peel `ref` until an object of type `T` is obtained. If no `T` is provided, -then `ref` will be peeled until an object other than a [`GitTag`](@ref) is obtained. - -- A `GitTag` will be peeled to the object it references. -- A [`GitCommit`](@ref) will be peeled to a [`GitTree`](@ref). - -!!! note - Only annotated tags can be peeled to `GitTag` objects. Lightweight tags (the default) - are references under `refs/tags/` which point directly to `GitCommit` objects. -""" -function peel{T<:GitObject}(::Type{T}, ref::GitReference) - obj_ptr_ptr = Ref{Ptr{Void}}(C_NULL) - @check ccall((:git_reference_peel, :libgit2), Cint, - (Ptr{Ptr{Void}}, Ptr{Void}, Cint), obj_ptr_ptr, ref.ptr, Consts.OBJECT(T)) - return T(ref.owner, obj_ptr_ptr[]) -end -peel(ref::GitReference) = peel(GitObject, ref) - -""" - LibGit2.ref_list(repo::GitRepo) -> Vector{String} - -Get a list of all reference names in the `repo` repository. -""" -function ref_list(repo::GitRepo) - sa_ref = Ref(StrArrayStruct()) - @check ccall((:git_reference_list, :libgit2), Cint, - (Ptr{StrArrayStruct}, Ptr{Void}), sa_ref, repo.ptr) - res = convert(Vector{String}, sa_ref[]) - free(sa_ref) - res -end - -""" - LibGit2.create_branch(repo::GitRepo, bname::AbstractString, commit_obj::GitCommit; force::Bool=false) - -Create a new branch in the repository `repo` with name `bname`, which -points to commit `commit_obj` (which has to be part of `repo`). If -`force` is `true`, overwrite an existing branch named `bname` if it -exists. If `force` is `false` and a branch already exists named `bname`, -this function will throw an error. -""" -function create_branch(repo::GitRepo, - bname::AbstractString, - commit_obj::GitCommit; - force::Bool=false) - ref_ptr_ptr = Ref{Ptr{Void}}(C_NULL) - @check ccall((:git_branch_create, :libgit2), Cint, - (Ptr{Ptr{Void}}, Ptr{Void}, Cstring, Ptr{Void}, Cint), - ref_ptr_ptr, repo.ptr, bname, commit_obj.ptr, Cint(force)) - return GitReference(repo, ref_ptr_ptr[]) -end - -""" - LibGit2.delete_branch(branch::GitReference) - -Delete the branch pointed to by `branch`. -""" -function delete_branch(branch::GitReference) - @check ccall((:git_branch_delete, :libgit2), Cint, (Ptr{Void},), branch.ptr) -end - -""" - LibGit2.head!(repo::GitRepo, ref::GitReference) -> GitReference - -Set the HEAD of `repo` to the object pointed to by `ref`. -""" -function head!(repo::GitRepo, ref::GitReference) - ref_name = name(ref) - @check ccall((:git_repository_set_head, :libgit2), Cint, - (Ptr{Void}, Cstring), repo.ptr, ref_name) - return ref -end - -""" - lookup_branch(repo::GitRepo, branch_name::AbstractString, remote::Bool=false) -> Nullable{GitReference} - -Determine if the branch specified by `branch_name` exists in the repository `repo`. -If `remote` is `true`, `repo` is assumed to be a remote git repository. Otherwise, it -is part of the local filesystem. - -`lookup_branch` returns a [`Nullable`](@ref), which will be null if the requested branch does -not exist yet. If the branch does exist, the `Nullable` contains a `GitReference` to -the branch. -""" -function lookup_branch(repo::GitRepo, - branch_name::AbstractString, - remote::Bool=false) - ref_ptr_ptr = Ref{Ptr{Void}}(C_NULL) - branch_type = remote ? Consts.BRANCH_REMOTE : Consts.BRANCH_LOCAL - err = ccall((:git_branch_lookup, :libgit2), Cint, - (Ptr{Ptr{Void}}, Ptr{Void}, Ptr{UInt8}, Cint), - ref_ptr_ptr, repo.ptr, branch_name, branch_type) - if err != Int(Error.GIT_OK) - if err == Int(Error.ENOTFOUND) - return Nullable{GitReference}() - end - if ref_ptr_ptr[] != C_NULL - close(GitReference(repo, ref_ptr_ptr[])) - end - throw(Error.GitError(err)) - end - return Nullable{GitReference}(GitReference(repo, ref_ptr_ptr[])) -end - -""" - upstream(ref::GitReference) -> Nullable{GitReference} - -Determine if the branch containing `ref` has a specified upstream branch. - -`upstream` returns a [`Nullable`](@ref), which will be null if the requested branch does -not have an upstream counterpart. If the upstream branch does exist, the `Nullable` -contains a `GitReference` to the upstream branch. -""" -function upstream(ref::GitReference) - isempty(ref) && return nothing - ref_ptr_ptr = Ref{Ptr{Void}}(C_NULL) - err = ccall((:git_branch_upstream, :libgit2), Cint, - (Ref{Ptr{Void}}, Ptr{Void},), ref_ptr_ptr, ref.ptr) - if err != Int(Error.GIT_OK) - if err == Int(Error.ENOTFOUND) - return Nullable{GitReference}() - end - if ref_ptr_ptr[] != C_NULL - close(GitReference(ref.owner, ref_ptr_ptr[])) - end - throw(Error.GitError(err)) - end - return Nullable{GitReference}(GitReference(ref.owner, ref_ptr_ptr[])) -end - -repository(ref::GitReference) = ref.owner - -function target!(ref::GitReference, new_oid::GitHash; msg::AbstractString="") - ref_ptr_ptr = Ref{Ptr{Void}}(C_NULL) - @check ccall((:git_reference_set_target, :libgit2), Cint, - (Ptr{Ptr{Void}}, Ptr{Void}, Ptr{GitHash}, Cstring), - ref_ptr_ptr, ref.ptr, Ref(new_oid), isempty(msg) ? C_NULL : msg) - return GitReference(ref.owner, ref_ptr_ptr[]) -end - -function GitBranchIter(repo::GitRepo, flags::Cint=Cint(Consts.BRANCH_LOCAL)) - bi_ptr = Ref{Ptr{Void}}(C_NULL) - @check ccall((:git_branch_iterator_new, :libgit2), Cint, - (Ptr{Ptr{Void}}, Ptr{Void}, Cint), bi_ptr, repo.ptr, flags) - return GitBranchIter(repo, bi_ptr[]) -end - -function Base.start(bi::GitBranchIter) - ref_ptr_ptr = Ref{Ptr{Void}}(C_NULL) - btype = Ref{Cint}() - err = ccall((:git_branch_next, :libgit2), Cint, - (Ptr{Ptr{Void}}, Ptr{Cint}, Ptr{Void}), - ref_ptr_ptr, btype, bi.ptr) - err != Int(Error.GIT_OK) && return (nothing, -1, true) - return (GitReference(bi.owner, ref_ptr_ptr[]), btype[], false) -end - -Base.done(bi::GitBranchIter, state) = Bool(state[3]) - -function Base.next(bi::GitBranchIter, state) - ref_ptr_ptr = Ref{Ptr{Void}}(C_NULL) - btype = Ref{Cint}() - err = ccall((:git_branch_next, :libgit2), Cint, - (Ptr{Ptr{Void}}, Ptr{Cint}, Ptr{Void}), - ref_ptr_ptr, btype, bi.ptr) - err != Int(Error.GIT_OK) && return (state[1:2], (nothing, -1, true)) - return (state[1:2], (GitReference(bi.owner, ref_ptr_ptr[]), btype[], false)) -end - -Base.iteratorsize(::Type{GitBranchIter}) = Base.SizeUnknown() - -function Base.map(f::Function, bi::GitBranchIter) - res = nothing - s = start(bi) - while !done(bi, s) - val = f(s[1:2]) - if res === nothing - res = Vector{typeof(val)}(0) - end - push!(res, val) - val, s = next(bi, s) - end - return res -end diff --git a/julia-0.6.3/share/julia/base/libgit2/remote.jl b/julia-0.6.3/share/julia/base/libgit2/remote.jl deleted file mode 100644 index 6e4d4bb..0000000 --- a/julia-0.6.3/share/julia/base/libgit2/remote.jl +++ /dev/null @@ -1,254 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -""" - GitRemote(repo::GitRepo, rmt_name::AbstractString, rmt_url::AbstractString) -> GitRemote - -Look up a remote git repository using its name and URL. Uses the default fetch refspec. - -# Example - -```julia -repo = LibGit2.init(repo_path) -remote = LibGit2.GitRemote(repo, "upstream", repo_url) -``` -""" -function GitRemote(repo::GitRepo, rmt_name::AbstractString, rmt_url::AbstractString) - rmt_ptr_ptr = Ref{Ptr{Void}}(C_NULL) - @check ccall((:git_remote_create, :libgit2), Cint, - (Ptr{Ptr{Void}}, Ptr{Void}, Cstring, Cstring), - rmt_ptr_ptr, repo.ptr, rmt_name, rmt_url) - return GitRemote(repo, rmt_ptr_ptr[]) -end - -""" - GitRemote(repo::GitRepo, rmt_name::AbstractString, rmt_url::AbstractString, fetch_spec::AbstractString) -> GitRemote - -Look up a remote git repository using the repository's name and URL, -as well as specifications for how to fetch from the remote -(e.g. which remote branch to fetch from). - -# Example - -```julia -repo = LibGit2.init(repo_path) -refspec = "+refs/heads/mybranch:refs/remotes/origin/mybranch" -remote = LibGit2.GitRemote(repo, "upstream", repo_url, refspec) -``` -""" -function GitRemote(repo::GitRepo, rmt_name::AbstractString, rmt_url::AbstractString, fetch_spec::AbstractString) - rmt_ptr_ptr = Ref{Ptr{Void}}(C_NULL) - @check ccall((:git_remote_create_with_fetchspec, :libgit2), Cint, - (Ptr{Ptr{Void}}, Ptr{Void}, Cstring, Cstring, Cstring), - rmt_ptr_ptr, repo.ptr, rmt_name, rmt_url, fetch_spec) - return GitRemote(repo, rmt_ptr_ptr[]) -end - -""" - GitRemoteAnon(repo::GitRepo, url::AbstractString) -> GitRemote - -Look up a remote git repository using only its URL, not its name. - -# Example - -```julia -repo = LibGit2.init(repo_path) -remote = LibGit2.GitRemoteAnon(repo, repo_url) -``` -""" -function GitRemoteAnon(repo::GitRepo, url::AbstractString) - rmt_ptr_ptr = Ref{Ptr{Void}}(C_NULL) - @check ccall((:git_remote_create_anonymous, :libgit2), Cint, - (Ptr{Ptr{Void}}, Ptr{Void}, Cstring), - rmt_ptr_ptr, repo.ptr, url) - return GitRemote(repo, rmt_ptr_ptr[]) -end - -function get(::Type{GitRemote}, repo::GitRepo, rmt_name::AbstractString) - rmt_ptr_ptr = Ref{Ptr{Void}}(C_NULL) - @check ccall((:git_remote_lookup, :libgit2), Cint, - (Ptr{Ptr{Void}}, Ptr{Void}, Cstring), - rmt_ptr_ptr, repo.ptr, rmt_name) - return GitRemote(repo, rmt_ptr_ptr[]) -end - -""" - url(rmt::GitRemote) - -Get the fetch URL of a remote git repository. - -# Example - -```julia-repl -julia> repo_url = "https://github.com/JuliaLang/Example.jl"; - -julia> repo = LibGit2.init(mktempdir()); - -julia> remote = LibGit2.GitRemote(repo, "origin", repo_url); - -julia> LibGit2.url(remote) -"https://github.com/JuliaLang/Example.jl" -``` -""" -function url(rmt::GitRemote) - url_ptr = ccall((:git_remote_url, :libgit2), Cstring, (Ptr{Void},), rmt.ptr) - url_ptr == C_NULL && return "" - return unsafe_string(url_ptr) -end - -""" - push_url(rmt::GitRemote) - -Get the push URL of a remote git repository. -""" -function push_url(rmt::GitRemote) - url_ptr = ccall((:git_remote_pushurl, :libgit2), Cstring, (Ptr{Void},), rmt.ptr) - url_ptr == C_NULL && return "" - return unsafe_string(url_ptr) -end - -""" - name(rmt::GitRemote) - -Get the name of a remote repository, for instance `"origin"`. -If the remote is anonymous (see [`GitRemoteAnon`](@ref)) -the name will be an empty string `""`. - -# Example - -```julia-repl -julia> repo_url = "https://github.com/JuliaLang/Example.jl"; - -julia> repo = LibGit2.clone(cache_repo, "test_directory"); - -julia> remote = LibGit2.GitRemote(repo, "origin", repo_url); - -julia> name(remote) -"origin" -``` -""" -function name(rmt::GitRemote) - name_ptr = ccall((:git_remote_name, :libgit2), Cstring, (Ptr{Void},), rmt.ptr) - name_ptr == C_NULL && return "" - return unsafe_string(name_ptr) -end - -""" - fetch_refspecs(rmt::GitRemote) -> Vector{String} - -Get the *fetch* refspecs for the specified `rmt`. These refspecs contain -information about which branch(es) to fetch from. -""" -function fetch_refspecs(rmt::GitRemote) - sa_ref = Ref(StrArrayStruct()) - @check ccall((:git_remote_get_fetch_refspecs, :libgit2), Cint, - (Ptr{StrArrayStruct}, Ptr{Void}), sa_ref, rmt.ptr) - res = convert(Vector{String}, sa_ref[]) - free(sa_ref) - res -end - -""" - push_refspecs(rmt::GitRemote) -> Vector{String} - -Get the *push* refspecs for the specified `rmt`. These refspecs contain -information about which branch(es) to push to. -""" -function push_refspecs(rmt::GitRemote) - sa_ref = Ref(StrArrayStruct()) - @check ccall((:git_remote_get_push_refspecs, :libgit2), Cint, - (Ptr{StrArrayStruct}, Ptr{Void}), sa_ref, rmt.ptr) - res = convert(Vector{String}, sa_ref[]) - free(sa_ref) - res -end - -""" - add_fetch!(repo::GitRepo, rmt::GitRemote, fetch_spec::String) - -Add a *fetch* refspec for the specified `rmt`. This refspec will contain -information about which branch(es) to fetch from. - -# Example -```julia-repl -julia> LibGit2.add_fetch!(repo, remote, "upstream"); - -julia> LibGit2.fetch_refspecs(remote) -String["+refs/heads/*:refs/remotes/upstream/*"] -``` -""" -function add_fetch!(repo::GitRepo, rmt::GitRemote, fetch_spec::String) - @check ccall((:git_remote_add_fetch, :libgit2), Cint, - (Ptr{Void}, Cstring, Cstring), repo.ptr, - name(rmt), fetch_spec) -end - -""" - add_push!(repo::GitRepo, rmt::GitRemote, push_spec::String) - -Add a *push* refspec for the specified `rmt`. This refspec will contain -information about which branch(es) to push to. - -# Example -```julia-repl -julia> LibGit2.add_push!(repo, remote, "refs/heads/master"); - -julia> remote = LibGit2.get(LibGit2.GitRemote, repo, branch); - -julia> LibGit2.push_refspecs(remote) -String["refs/heads/master"] -``` - -!!! note - You may need to [`close`](@ref) and reopen the `GitRemote` - in question after updating its push refspecs in order for - the change to take effect and for calls to [`push`](@ref) - to work. -""" -function add_push!(repo::GitRepo, rmt::GitRemote, push_spec::String) - @check ccall((:git_remote_add_push, :libgit2), Cint, - (Ptr{Void}, Cstring, Cstring), repo.ptr, - name(rmt), push_spec) -end - -""" - fetch(rmt::GitRemote, refspecs; options::FetchOptions=FetchOptions(), msg="") - -Fetch from the specified `rmt` remote git repository, using `refspecs` to -determine which remote branch(es) to fetch. -The keyword arguments are: - * `options`: determines the options for the fetch, e.g. whether to prune afterwards. - * `msg`: a message to insert into the reflogs. -""" -function fetch(rmt::GitRemote, refspecs::Vector{<:AbstractString}; - options::FetchOptions = FetchOptions(), - msg::AbstractString="") - msg = "libgit2.fetch: $msg" - @check ccall((:git_remote_fetch, :libgit2), Cint, - (Ptr{Void}, Ptr{StrArrayStruct}, Ptr{FetchOptions}, Cstring), - rmt.ptr, isempty(refspecs) ? C_NULL : refspecs, Ref(options), msg) -end - -""" - push(rmt::GitRemote, refspecs; force::Bool=false, options::PushOptions=PushOptions()) - -Push to the specified `rmt` remote git repository, using `refspecs` to -determine which remote branch(es) to push to. -The keyword arguments are: - * `force`: if `true`, a force-push will occur, disregarding conflicts. - * `options`: determines the options for the push, e.g. which proxy headers to use. - -!!! note - You can add information about the push refspecs in two other ways: by setting - an option in the repository's `GitConfig` (with `push.default` as the key) or - by calling [`add_push!`](@ref). Otherwise you will need to explicitly specify - a push refspec in the call to `push` for it to have any effect, like so: - `LibGit2.push(repo, refspecs=["refs/heads/master"])`. -""" -function push(rmt::GitRemote, refspecs::Vector{<:AbstractString}; - force::Bool = false, options::PushOptions = PushOptions()) - @check ccall((:git_remote_push, :libgit2), Cint, - (Ptr{Void}, Ptr{StrArrayStruct}, Ptr{PushOptions}), - rmt.ptr, isempty(refspecs) ? C_NULL : refspecs, Ref(options)) -end - -Base.show(io::IO, rmt::GitRemote) = print(io, "GitRemote:\nRemote name: ", name(rmt), " url: ", url(rmt)) diff --git a/julia-0.6.3/share/julia/base/libgit2/repository.jl b/julia-0.6.3/share/julia/base/libgit2/repository.jl deleted file mode 100644 index 020d0ff..0000000 --- a/julia-0.6.3/share/julia/base/libgit2/repository.jl +++ /dev/null @@ -1,309 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -""" - LibGit2.GitRepo(path::AbstractString) - -Opens a git repository at `path`. -""" -function GitRepo(path::AbstractString) - repo_ptr_ptr = Ref{Ptr{Void}}(C_NULL) - @check ccall((:git_repository_open, :libgit2), Cint, - (Ptr{Ptr{Void}}, Cstring), repo_ptr_ptr, path) - return GitRepo(repo_ptr_ptr[]) -end - -""" - LibGit2.GitRepoExt(path::AbstractString, flags::Cuint = Cuint(Consts.REPOSITORY_OPEN_DEFAULT)) - -Opens a git repository at `path` with extended controls (for instance, if the current -user must be a member of a special access group to read `path`). -""" -function GitRepoExt(path::AbstractString, flags::Cuint = Cuint(Consts.REPOSITORY_OPEN_DEFAULT)) - separator = @static is_windows() ? ";" : ":" - repo_ptr_ptr = Ref{Ptr{Void}}(C_NULL) - @check ccall((:git_repository_open_ext, :libgit2), Cint, - (Ptr{Ptr{Void}}, Cstring, Cuint, Cstring), - repo_ptr_ptr, path, flags, separator) - return GitRepo(repo_ptr_ptr[]) -end - -function cleanup(r::GitRepo) - if r.ptr != C_NULL - ccall((:git_repository__cleanup, :libgit2), Void, (Ptr{Void},), r.ptr) - end -end - -""" - LibGit2.init(path::AbstractString, bare::Bool=false) -> GitRepo - -Opens a new git repository at `path`. If `bare` is `false`, -the working tree will be created in `path/.git`. If `bare` -is `true`, no working directory will be created. -""" -function init(path::AbstractString, bare::Bool=false) - repo_ptr_ptr = Ref{Ptr{Void}}(C_NULL) - @check ccall((:git_repository_init, :libgit2), Cint, - (Ptr{Ptr{Void}}, Cstring, Cuint), repo_ptr_ptr, path, bare) - return GitRepo(repo_ptr_ptr[]) -end - -""" - LibGit2.head_oid(repo::GitRepo) -> GitHash - -Lookup the object id of the current HEAD of git -repository `repo`. -""" -function head_oid(repo::GitRepo) - head_ref = head(repo) - try - return GitHash(head_ref) - finally - close(head_ref) - end -end - -""" - LibGit2.headname(repo::GitRepo) - -Lookup the name of the current HEAD of git -repository `repo`. If `repo` is currently -detached, returns the name of the HEAD it's -detached from. -""" -function headname(repo::GitRepo) - with(head(repo)) do href - if isattached(repo) - shortname(href) - else - "(detached from $(string(GitHash(href))[1:7]))" - end - end -end - -function isbare(repo::GitRepo) - return ccall((:git_repository_is_bare, :libgit2), Cint, (Ptr{Void},), repo.ptr) == 1 -end - -function isattached(repo::GitRepo) - ccall((:git_repository_head_detached, :libgit2), Cint, (Ptr{Void},), repo.ptr) != 1 -end - -@doc """ - GitObject(repo::GitRepo, hash::AbstractGitHash) - GitObject(repo::GitRepo, spec::AbstractString) - -Return the specified object ([`GitCommit`](@ref), [`GitBlob`](@ref), [`GitTree`](@ref) or [`GitTag`](@ref)) from `repo` -specified by `hash`/`spec`. - -- `hash` is a full (`GitHash`) or partial (`GitShortHash`) hash. -- `spec` is a textual specification: see [the git docs](https://git-scm.com/docs/git-rev-parse.html#_specifying_revisions) for a full list. -""" GitObject - -for T in (:GitCommit, :GitBlob, :GitTree, :GitTag) - @eval @doc $""" - $T(repo::GitRepo, hash::AbstractGitHash) - $T(repo::GitRepo, spec::AbstractString) - -Return a `$T` object from `repo` specified by `hash`/`spec`. - -- `hash` is a full (`GitHash`) or partial (`GitShortHash`) hash. -- `spec` is a textual specification: see [the git docs](https://git-scm.com/docs/git-rev-parse.html#_specifying_revisions) for a full list. -""" $T -end - -function (::Type{T})(repo::GitRepo, spec::AbstractString) where T<:GitObject - obj_ptr_ptr = Ref{Ptr{Void}}(C_NULL) - @check ccall((:git_revparse_single, :libgit2), Cint, - (Ptr{Ptr{Void}}, Ptr{Void}, Cstring), obj_ptr_ptr, repo.ptr, spec) - # check object is of correct type - if T != GitObject && T != GitUnknownObject - t = Consts.OBJECT(obj_ptr_ptr[]) - t == Consts.OBJECT(T) || throw(GitError(Error.Object, Error.ERROR, "Expected object of type $T, received object of type $(objtype(t))")) - end - return T(repo, obj_ptr_ptr[]) -end - -function (::Type{T})(repo::GitRepo, oid::GitHash) where T<:GitObject - oid_ptr = Ref(oid) - obj_ptr_ptr = Ref{Ptr{Void}}(C_NULL) - - @check ccall((:git_object_lookup, :libgit2), Cint, - (Ptr{Ptr{Void}}, Ptr{Void}, Ptr{GitHash}, Consts.OBJECT), - obj_ptr_ptr, repo.ptr, oid_ptr, Consts.OBJECT(T)) - - return T(repo, obj_ptr_ptr[]) -end -function (::Type{T})(repo::GitRepo, oid::GitShortHash) where T<:GitObject - oid_ptr = Ref(oid.hash) - obj_ptr_ptr = Ref{Ptr{Void}}(C_NULL) - - @check ccall((:git_object_lookup_prefix, :libgit2), Cint, - (Ptr{Ptr{Void}}, Ptr{Void}, Ptr{GitHash}, Csize_t, Consts.OBJECT), - obj_ptr_ptr, repo.ptr, oid_ptr, oid.len, Consts.OBJECT(T)) - - return T(repo, obj_ptr_ptr[]) -end - -# TODO: deprecate this function -revparseid(repo::GitRepo, spec) = GitHash(GitUnknownObject(repo, spec)) - -""" - LibGit2.gitdir(repo::GitRepo) - -Returns the location of the "git" files of `repo`: - - - for normal repositories, this is the location of the `.git` folder. - - for bare repositories, this is the location of the repository itself. - -See also [`workdir`](@ref), [`path`](@ref). -""" -function gitdir(repo::GitRepo) - return unsafe_string(ccall((:git_repository_path, :libgit2), Cstring, - (Ptr{Void},), repo.ptr)) -end - -""" - LibGit2.workdir(repo::GitRepo) - -The location of the working directory of `repo`. This will throw an error for bare -repositories. - -!!! note - - This will typically be the parent directory of `gitdir(repo)`, but can be different in - some cases: e.g. if either the `core.worktree` configuration variable or the - `GIT_WORK_TREE` environment variable is set. - -See also [`gitdir`](@ref), [`path`](@ref). -""" -function workdir(repo::GitRepo) - sptr = ccall((:git_repository_workdir, :libgit2), Cstring, - (Ptr{Void},), repo.ptr) - sptr == C_NULL && throw(GitError(Error.Object, Error.ERROR, "No working directory found.")) - return unsafe_string(sptr) -end - -""" - LibGit2.path(repo::GitRepo) - -The base file path of the repository `repo`. - - - for normal repositories, this will typically be the parent directory of the ".git" - directory (note: this may be different than the working directory, see `workdir` for - more details). - - for bare repositories, this is the location of the "git" files. - -See also [`gitdir`](@ref), [`workdir`](@ref). -""" -function path(repo::GitRepo) - d = gitdir(repo) - if isdirpath(d) - d = dirname(d) # strip trailing separator - end - if isbare(repo) - return d - else - parent, base = splitdir(d) - return base == ".git" ? parent : d - end -end - -""" - peel([T,] obj::GitObject) - -Recursively peel `obj` until an object of type `T` is obtained. If no `T` is provided, -then `obj` will be peeled until the type changes. - -- A `GitTag` will be peeled to the object it references. -- A `GitCommit` will be peeled to a `GitTree`. -""" -function peel(::Type{T}, obj::GitObject) where T<:GitObject - new_ptr_ptr = Ref{Ptr{Void}}(C_NULL) - - @check ccall((:git_object_peel, :libgit2), Cint, - (Ptr{Ptr{Void}}, Ptr{Void}, Cint), new_ptr_ptr, obj.ptr, Consts.OBJECT(T)) - - return T(obj.owner, new_ptr_ptr[]) -end -peel(obj::GitObject) = peel(GitObject, obj) - - -function checkout_tree(repo::GitRepo, obj::GitObject; - options::CheckoutOptions = CheckoutOptions()) - @check ccall((:git_checkout_tree, :libgit2), Cint, - (Ptr{Void}, Ptr{Void}, Ptr{CheckoutOptions}), - repo.ptr, obj.ptr, Ref(options)) -end - -function checkout_index(repo::GitRepo, idx::Nullable{GitIndex} = Nullable{GitIndex}(); - options::CheckoutOptions = CheckoutOptions()) - @check ccall((:git_checkout_index, :libgit2), Cint, - (Ptr{Void}, Ptr{Void}, Ptr{CheckoutOptions}), - repo.ptr, - isnull(idx) ? C_NULL : Base.get(idx).ptr, - Ref(options)) -end - -function checkout_head(repo::GitRepo; options::CheckoutOptions = CheckoutOptions()) - @check ccall((:git_checkout_head, :libgit2), Cint, - (Ptr{Void}, Ptr{CheckoutOptions}), - repo.ptr, Ref(options)) -end - -"""Updates some entries, determined by the `pathspecs`, in the index from the target commit tree.""" -function reset!(repo::GitRepo, obj::Nullable{<:GitObject}, pathspecs::AbstractString...) - @check ccall((:git_reset_default, :libgit2), Cint, - (Ptr{Void}, Ptr{Void}, Ptr{StrArrayStruct}), - repo.ptr, - isnull(obj) ? C_NULL: Base.get(obj).ptr, - collect(pathspecs)) - return head_oid(repo) -end - -"""Sets the current head to the specified commit oid and optionally resets the index and working tree to match.""" -function reset!(repo::GitRepo, obj::GitObject, mode::Cint; - checkout_opts::CheckoutOptions = CheckoutOptions()) - @check ccall((:git_reset, :libgit2), Cint, - (Ptr{Void}, Ptr{Void}, Cint, Ptr{CheckoutOptions}), - repo.ptr, obj.ptr, mode, Ref(checkout_opts)) - return head_oid(repo) -end - -function clone(repo_url::AbstractString, repo_path::AbstractString, - clone_opts::CloneOptions) - clone_opts_ref = Ref(clone_opts) - repo_ptr_ptr = Ref{Ptr{Void}}(C_NULL) - @check ccall((:git_clone, :libgit2), Cint, - (Ptr{Ptr{Void}}, Cstring, Cstring, Ref{CloneOptions}), - repo_ptr_ptr, repo_url, repo_path, clone_opts_ref) - return GitRepo(repo_ptr_ptr[]) -end - -function fetchheads(repo::GitRepo) - fhr = Ref{Vector{FetchHead}}(FetchHead[]) - ffcb = fetchhead_foreach_cb() - @check ccall((:git_repository_fetchhead_foreach, :libgit2), Cint, - (Ptr{Void}, Ptr{Void}, Ptr{Void}), - repo.ptr, ffcb, fhr) - return fhr[] -end - -""" - LibGit2.remotes(repo::GitRepo) - -Returns a vector of the names of the remotes of `repo`. -""" -function remotes(repo::GitRepo) - sa_ref = Ref(StrArrayStruct()) - @check ccall((:git_remote_list, :libgit2), Cint, - (Ptr{StrArrayStruct}, Ptr{Void}), sa_ref, repo.ptr) - res = convert(Vector{String}, sa_ref[]) - free(sa_ref) - return res -end - -function Base.show(io::IO, repo::GitRepo) - print(io, "LibGit2.GitRepo(") - show(io, path(repo)) - print(io, ")") -end diff --git a/julia-0.6.3/share/julia/base/libgit2/signature.jl b/julia-0.6.3/share/julia/base/libgit2/signature.jl deleted file mode 100644 index fb099ef..0000000 --- a/julia-0.6.3/share/julia/base/libgit2/signature.jl +++ /dev/null @@ -1,51 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -function Signature(ptr::Ptr{SignatureStruct}) - sig = unsafe_load(ptr)::SignatureStruct - name = unsafe_string(sig.name) - email = unsafe_string(sig.email) - time = sig.when.time - offset = sig.when.offset - return Signature(name, email, time, offset) -end -Signature(sig::GitSignature) = Signature(sig.ptr) - -function Signature(name::AbstractString, email::AbstractString) - sig_ptr_ptr = Ref{Ptr{SignatureStruct}}(C_NULL) - @check ccall((:git_signature_now, :libgit2), Cint, - (Ptr{Ptr{SignatureStruct}}, Cstring, Cstring), sig_ptr_ptr, name, email) - sig = GitSignature(sig_ptr_ptr[]) - s = Signature(sig.ptr) - close(sig) - return s -end - -function Signature(repo::GitRepo) - sig = default_signature(repo) - s = Signature(sig.ptr) - close(sig) - return s -end - -function Base.convert(::Type{GitSignature}, sig::Signature) - sig_ptr_ptr = Ref{Ptr{SignatureStruct}}(C_NULL) - @check ccall((:git_signature_new, :libgit2), Cint, - (Ptr{Ptr{SignatureStruct}}, Cstring, Cstring, Int64, Cint), - sig_ptr_ptr, sig.name, sig.email, sig.time, sig.time_offset) - return GitSignature(sig_ptr_ptr[]) -end - -function Base.show(io::IO, sig::Signature) - print(io, "Name: ", sig.name, ", ") - print(io, "Email: ", sig.email, ", ") - print(io, "Time: ", Dates.unix2datetime(sig.time + 60*sig.time_offset)) - @printf(io, "%+03i:%02i", divrem(sig.time_offset, 60)...) -end - -"""Return signature object. Free it after use.""" -function default_signature(repo::GitRepo) - sig_ptr_ptr = Ref{Ptr{SignatureStruct}}(C_NULL) - @check ccall((:git_signature_default, :libgit2), Cint, - (Ptr{Ptr{SignatureStruct}}, Ptr{Void}), sig_ptr_ptr, repo.ptr) - return GitSignature(sig_ptr_ptr[]) -end diff --git a/julia-0.6.3/share/julia/base/libgit2/status.jl b/julia-0.6.3/share/julia/base/libgit2/status.jl deleted file mode 100644 index ccfb4c8..0000000 --- a/julia-0.6.3/share/julia/base/libgit2/status.jl +++ /dev/null @@ -1,50 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -""" - LibGit2.GitStatus(repo::GitRepo; status_opts=StatusOptions()) - -Collect information about the status of each file in the git -repository `repo` (e.g. is the file modified, staged, etc.). -`status_opts` can be used to set various options, for instance -whether or not to look at untracked files or whether to include -submodules or not. -""" -function GitStatus(repo::GitRepo; status_opts=StatusOptions()) - stat_ptr_ptr = Ref{Ptr{Void}}(C_NULL) - @check ccall((:git_status_list_new, :libgit2), Cint, - (Ptr{Ptr{Void}}, Ptr{Void}, Ptr{StatusOptions}), - stat_ptr_ptr, repo.ptr, Ref(status_opts)) - return GitStatus(repo, stat_ptr_ptr[]) -end - -function Base.length(status::GitStatus) - return Int(ccall((:git_status_list_entrycount, :libgit2), Csize_t, - (Ptr{Ptr{Void}},), status.ptr)) -end - -function Base.getindex(status::GitStatus, i::Integer) - 1 <= i <= length(status) || throw(BoundsError()) - entry_ptr = ccall((:git_status_byindex, :libgit2), - Ptr{StatusEntry}, - (Ptr{Void}, Csize_t), - status.ptr, i-1) - entry_ptr == C_NULL && throw(Error.GitError(Error.ERROR)) - return unsafe_load(entry_ptr) -end - -""" - LibGit2.status(repo::GitRepo, path::String) - -Lookup the status of the file at `path` in the git -repository `repo`. For instance, this can be used -to check if the file at `path` has been modified -and needs to be staged and committed. -""" -function status(repo::GitRepo, path::String) - status_ptr = Ref{Cuint}(0) - ret = ccall((:git_status_file, :libgit2), Cint, - (Ref{Cuint}, Ptr{Void}, Cstring), - status_ptr, repo.ptr, path) - (ret == Cint(Error.ENOTFOUND) || ret == Cint(Error.EAMBIGUOUS)) && return Nullable{Cuint}() - return Nullable(status_ptr[]) -end diff --git a/julia-0.6.3/share/julia/base/libgit2/strarray.jl b/julia-0.6.3/share/julia/base/libgit2/strarray.jl deleted file mode 100644 index db08036..0000000 --- a/julia-0.6.3/share/julia/base/libgit2/strarray.jl +++ /dev/null @@ -1,15 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - - -function Base.cconvert(::Type{Ptr{StrArrayStruct}}, x::Vector) - str_ref = Base.cconvert(Ref{Cstring}, x) - sa_ref = Ref(StrArrayStruct(Base.unsafe_convert(Ref{Cstring}, str_ref), length(x))) - sa_ref, str_ref -end -function Base.unsafe_convert(::Type{Ptr{StrArrayStruct}}, rr::Tuple{Ref{StrArrayStruct}, Ref{Cstring}}) - Base.unsafe_convert(Ptr{StrArrayStruct}, first(rr)) -end - -function Base.convert(::Type{Vector{String}}, sa::StrArrayStruct) - [unsafe_string(unsafe_load(sa.strings, i)) for i = 1:sa.count] -end diff --git a/julia-0.6.3/share/julia/base/libgit2/tag.jl b/julia-0.6.3/share/julia/base/libgit2/tag.jl deleted file mode 100644 index cde38e3..0000000 --- a/julia-0.6.3/share/julia/base/libgit2/tag.jl +++ /dev/null @@ -1,77 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -""" - LibGit2.tag_list(repo::GitRepo) -> Vector{String} - -Get a list of all tags in the git repository `repo`. -""" -function tag_list(repo::GitRepo) - sa_ref = Ref(StrArrayStruct()) - @check ccall((:git_tag_list, :libgit2), Cint, - (Ptr{StrArrayStruct}, Ptr{Void}), sa_ref, repo.ptr) - res = convert(Vector{String}, sa_ref[]) - free(sa_ref) - res -end - -""" - LibGit2.tag_delete(repo::GitRepo, tag::AbstractString) - -Remove the git tag `tag` from the repository `repo`. -""" -function tag_delete(repo::GitRepo, tag::AbstractString) - @check ccall((:git_tag_delete, :libgit2), Cint, - (Ptr{Void}, Cstring), repo.ptr, tag) -end - -""" - LibGit2.tag_create(repo::GitRepo, tag::AbstractString, commit; kwargs...) - -Create a new git tag `tag` (e.g. `"v0.5"`) in the repository `repo`, at -the commit `commit`. - -The keyword arguments are: - * `msg::AbstractString=""`: the message for the tag. - * `force::Bool=false`: if `true`, existing references will be overwritten. - * `sig::Signature=Signature(repo)`: the tagger's signature. -""" -function tag_create(repo::GitRepo, tag::AbstractString, commit::Union{AbstractString,AbstractGitHash}; - msg::AbstractString = "", - force::Bool = false, - sig::Signature = Signature(repo)) - oid_ptr = Ref(GitHash()) - with(GitCommit(repo, commit)) do commit_obj - commit_obj === nothing && return oid_ptr[] # return empty oid - with(convert(GitSignature, sig)) do git_sig - @check ccall((:git_tag_create, :libgit2), Cint, - (Ptr{GitHash}, Ptr{Void}, Cstring, Ptr{Void}, Ptr{SignatureStruct}, Cstring, Cint), - oid_ptr, repo.ptr, tag, commit_obj.ptr, git_sig.ptr, msg, Cint(force)) - end - end - return oid_ptr[] -end - -""" - LibGit2.name(tag::GitTag) - -The name of `tag` (e.g. `"v0.5"`). -""" -function name(tag::GitTag) - str_ptr = ccall((:git_tag_name, :libgit2), Cstring, (Ptr{Void},), tag.ptr) - str_ptr == C_NULL && throw(Error.GitError(Error.ERROR)) - return unsafe_string(str_ptr) -end - -# should we return the actual object? i.e. git_tag_target? -""" - LibGit2.target(tag::GitTag) - -The `GitHash` of the target object of `tag`. -""" -function target(tag::GitTag) - oid_ptr = ccall((:git_tag_target_id, :libgit2), Ptr{GitHash}, (Ptr{Void},), tag.ptr) - oid_ptr == C_NULL && throw(Error.GitError(Error.ERROR)) - return unsafe_load(oid_ptr) -end - -Base.show(io::IO, tag::GitTag) = print(io, "GitTag:\nTag name: $(name(tag)) target: $(target(tag))") diff --git a/julia-0.6.3/share/julia/base/libgit2/tree.jl b/julia-0.6.3/share/julia/base/libgit2/tree.jl deleted file mode 100644 index 60da6a8..0000000 --- a/julia-0.6.3/share/julia/base/libgit2/tree.jl +++ /dev/null @@ -1,76 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -""" -Traverse the entries in a tree and its subtrees in post or pre order. - -Function parameter should have following signature: - - (Cstring, Ptr{Void}, Ptr{Void}) -> Cint -""" -function treewalk(f::Function, tree::GitTree, payload=Any[], post::Bool = false) - cbf = cfunction(f, Cint, Tuple{Cstring, Ptr{Void}, Ptr{Void}}) - cbf_payload = Ref{typeof(payload)}(payload) - @check ccall((:git_tree_walk, :libgit2), Cint, - (Ptr{Void}, Cint, Ptr{Void}, Ptr{Void}), - tree.ptr, post, cbf, cbf_payload) - return cbf_payload -end - -repository(tree::GitTree) = tree.owner -repository(te::GitTreeEntry) = repository(te.owner) - -function filename(te::GitTreeEntry) - str = ccall((:git_tree_entry_name, :libgit2), Cstring, (Ptr{Void},), te.ptr) - str != C_NULL && return unsafe_string(str) - return nothing -end - -function filemode(te::GitTreeEntry) - return ccall((:git_tree_entry_filemode, :libgit2), Cint, (Ptr{Void},), te.ptr) -end - -function entrytype(te::GitTreeEntry) - otype = ccall((:git_tree_entry_type, :libgit2), Cint, (Ptr{Void},), te.ptr) - return objtype(Consts.OBJECT(otype)) -end - -function entryid(te::GitTreeEntry) - oid_ptr = ccall((:git_tree_entry_id, :libgit2), Ptr{UInt8}, (Ptr{Void},), te.ptr) - return GitHash(oid_ptr) -end - -function Base.count(tree::GitTree) - return ccall((:git_tree_entrycount, :libgit2), Csize_t, (Ptr{Void},), tree.ptr) -end - -function Base.getindex(tree::GitTree, i::Integer) - if i < 1 || i > count(tree) - throw(BoundsError(tree, i)) - end - te_ptr = ccall((:git_tree_entry_byindex, :libgit2), - Ptr{Void}, - (Ptr{Void}, Csize_t), tree.ptr, i-1) - return GitTreeEntry(tree, te_ptr, false) -end - -function (::Type{T})(te::GitTreeEntry) where T<:GitObject - repo = repository(te) - obj_ptr_ptr = Ref{Ptr{Void}}(C_NULL) - @check ccall((:git_tree_entry_to_object, :libgit2), Cint, - (Ptr{Ptr{Void}}, Ptr{Void}, Ref{Void}), - obj_ptr_ptr, repo.ptr, te.ptr) - return T(repo, obj_ptr_ptr[]) -end - -function Base.show(io::IO, te::GitTreeEntry) - println(io, "GitTreeEntry:") - println(io, "Entry name: ", filename(te)) - println(io, "Entry type: ", entrytype(te)) - println(io, "Entry OID: ", entryid(te)) -end - -function Base.show(io::IO, tree::GitTree) - println(io, "GitTree:") - println(io, "Owner: ", repository(tree)) - println(io, "Number of entries: ", count(tree)) -end diff --git a/julia-0.6.3/share/julia/base/libgit2/types.jl b/julia-0.6.3/share/julia/base/libgit2/types.jl deleted file mode 100644 index 89cb7e1..0000000 --- a/julia-0.6.3/share/julia/base/libgit2/types.jl +++ /dev/null @@ -1,751 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -import Base.@kwdef -import .Consts: GIT_SUBMODULE_IGNORE, GIT_MERGE_FILE_FAVOR, GIT_MERGE_FILE - -const OID_RAWSZ = 20 -const OID_HEXSZ = OID_RAWSZ * 2 -const OID_MINPREFIXLEN = 4 - -abstract type AbstractGitHash end - -""" - GitHash - -A git object identifier, based on the sha-1 hash. It is a $OID_RAWSZ byte string -($OID_HEXSZ hex digits) used to identify a `GitObject` in a repository. -""" -struct GitHash <: AbstractGitHash - val::NTuple{OID_RAWSZ, UInt8} - GitHash(val::NTuple{OID_RAWSZ, UInt8}) = new(val) -end -GitHash() = GitHash(ntuple(i->zero(UInt8), OID_RAWSZ)) - -""" - GitShortHash - -This is a shortened form of `GitHash`, which can be used to identify a git object when it -is unique. - -Internally it is stored as two fields: a full-size `GitHash` (`hash`) and a length -(`len`). Only the initial `len` hex digits of `hash` are used. -""" -struct GitShortHash <: AbstractGitHash - hash::GitHash # underlying hash: unused digits are ignored - len::Csize_t # length in hex digits -end - - -""" - LibGit2.TimeStruct - -Time in a signature. -Matches the [`git_time`](https://libgit2.github.com/libgit2/#HEAD/type/git_time) struct. -""" -struct TimeStruct - time::Int64 # time in seconds from epoch - offset::Cint # timezone offset in minutes -end - -""" - LibGit2.SignatureStruct - -An action signature (e.g. for committers, taggers, etc). -Matches the [`git_signature`](https://libgit2.github.com/libgit2/#HEAD/type/git_signature) struct. -""" -struct SignatureStruct - name::Ptr{UInt8} # full name of the author - email::Ptr{UInt8} # email of the author - when::TimeStruct # time when the action happened -end - -""" - LibGit2.StrArrayStruct - -A LibGit2 representation of an array of strings. -Matches the [`git_strarray`](https://libgit2.github.com/libgit2/#HEAD/type/git_strarray) struct. - -When fetching data from LibGit2, a typical usage would look like: -```julia -sa_ref = Ref(StrArrayStruct()) -@check ccall(..., (Ptr{StrArrayStruct},), sa_ref) -res = convert(Vector{String}, sa_ref[]) -free(sa_ref) -``` -In particular, note that `LibGit2.free` should be called afterward on the `Ref` object. - -Conversely, when passing a vector of strings to LibGit2, it is generally simplest to rely -on implicit conversion: -```julia -strs = String[...] -@check ccall(..., (Ptr{StrArrayStruct},), strs) -``` -Note that no call to `free` is required as the data is allocated by Julia. -""" -struct StrArrayStruct - strings::Ptr{Cstring} - count::Csize_t -end -StrArrayStruct() = StrArrayStruct(C_NULL, 0) - -function free(sa_ref::Base.Ref{StrArrayStruct}) - ccall((:git_strarray_free, :libgit2), Void, (Ptr{StrArrayStruct},), sa_ref) -end - -""" - LibGit2.Buffer - -A data buffer for exporting data from libgit2. -Matches the [`git_buf`](https://libgit2.github.com/libgit2/#HEAD/type/git_buf) struct. - -When fetching data from LibGit2, a typical usage would look like: -```julia -buf_ref = Ref(Buffer()) -@check ccall(..., (Ptr{Buffer},), buf_ref) -# operation on buf_ref -free(buf_ref) -``` -In particular, note that `LibGit2.free` should be called afterward on the `Ref` object. -""" -struct Buffer - ptr::Ptr{Cchar} - asize::Csize_t - size::Csize_t -end -Buffer() = Buffer(C_NULL, 0, 0) - -function free(buf_ref::Base.Ref{Buffer}) - ccall((:git_buf_free, :libgit2), Void, (Ptr{Buffer},), buf_ref) -end - -"Abstract credentials payload" -abstract type AbstractCredentials end - -"Checks if credentials were used" -checkused!(p::AbstractCredentials) = true -checkused!(p::Void) = false -"Resets credentials for another use" -reset!(p::AbstractCredentials, cnt::Int=3) = nothing - -""" - LibGit2.CheckoutOptions - -Matches the [`git_checkout_options`](https://libgit2.github.com/libgit2/#HEAD/type/git_checkout_options) struct. -""" -@kwdef struct CheckoutOptions - version::Cuint = 1 - - checkout_strategy::Cuint = Consts.CHECKOUT_SAFE - - disable_filters::Cint - dir_mode::Cuint - file_mode::Cuint - file_open_flags::Cint - - notify_flags::Cuint = Consts.CHECKOUT_NOTIFY_NONE - notify_cb::Ptr{Void} - notify_payload::Ptr{Void} - - progress_cb::Ptr{Void} - progress_payload::Ptr{Void} - - paths::StrArrayStruct - - baseline::Ptr{Void} - baseline_index::Ptr{Void} - - target_directory::Cstring - ancestor_label::Cstring - our_label::Cstring - their_label::Cstring - - perfdata_cb::Ptr{Void} - perfdata_payload::Ptr{Void} -end - -""" - LibGit2.RemoteCallbacks - -Callback settings. -Matches the [`git_remote_callbacks`](https://libgit2.github.com/libgit2/#HEAD/type/git_remote_callbacks) struct. -""" -@kwdef struct RemoteCallbacks - version::Cuint = 1 - sideband_progress::Ptr{Void} - completion::Ptr{Void} - credentials::Ptr{Void} - certificate_check::Ptr{Void} - transfer_progress::Ptr{Void} - update_tips::Ptr{Void} - pack_progress::Ptr{Void} - push_transfer_progress::Ptr{Void} - push_update_reference::Ptr{Void} - push_negotiation::Ptr{Void} - transport::Ptr{Void} - payload::Ptr{Void} -end - -function RemoteCallbacks(credentials::Ptr{Void}, payload::Ref{Nullable{AbstractCredentials}}) - RemoteCallbacks(credentials=credentials_cb(), payload=pointer_from_objref(payload)) -end - -""" - LibGit2.ProxyOptions - -Options for connecting through a proxy. - -Matches the [`git_proxy_options`](https://libgit2.github.com/libgit2/#HEAD/type/git_proxy_options) struct. -""" -@kwdef struct ProxyOptions - version::Cuint = 1 - proxytype::Consts.GIT_PROXY = Consts.PROXY_AUTO - url::Cstring - credential_cb::Ptr{Void} - certificate_cb::Ptr{Void} - payload::Ptr{Void} -end - - -""" - LibGit2.FetchOptions - -Matches the [`git_fetch_options`](https://libgit2.github.com/libgit2/#HEAD/type/git_fetch_options) struct. -""" -@kwdef struct FetchOptions - version::Cuint = 1 - callbacks::RemoteCallbacks - prune::Cint = Consts.FETCH_PRUNE_UNSPECIFIED - update_fetchhead::Cint = 1 - download_tags::Cint = Consts.REMOTE_DOWNLOAD_TAGS_AUTO - @static if LibGit2.VERSION >= v"0.25.0" - proxy_opts::ProxyOptions - end - @static if LibGit2.VERSION >= v"0.24.0" - custom_headers::StrArrayStruct - end -end - -""" - LibGit2.CloneOptions - -Matches the [`git_clone_options`](https://libgit2.github.com/libgit2/#HEAD/type/git_clone_options) struct. -""" -@kwdef struct CloneOptions - version::Cuint = 1 - checkout_opts::CheckoutOptions - fetch_opts::FetchOptions - bare::Cint - localclone::Cint = Consts.CLONE_LOCAL_AUTO - checkout_branch::Cstring - repository_cb::Ptr{Void} - repository_cb_payload::Ptr{Void} - remote_cb::Ptr{Void} - remote_cb_payload::Ptr{Void} -end - -""" - LibGit2.DiffOptionsStruct - -Matches the [`git_diff_options`](https://libgit2.github.com/libgit2/#HEAD/type/git_diff_options) struct. -""" -@kwdef struct DiffOptionsStruct - version::Cuint = Consts.DIFF_OPTIONS_VERSION - flags::UInt32 = Consts.DIFF_NORMAL - - # options controlling which files are in the diff - ignore_submodules::GIT_SUBMODULE_IGNORE = Consts.SUBMODULE_IGNORE_UNSPECIFIED - pathspec::StrArrayStruct - notify_cb::Ptr{Void} - @static if LibGit2.VERSION >= v"0.24.0" - progress_cb::Ptr{Void} - end - payload::Ptr{Void} - - # options controlling how the diff text is generated - context_lines::UInt32 = UInt32(3) - interhunk_lines::UInt32 - id_abbrev::UInt16 = UInt16(7) - max_size::Int64 = Int64(512*1024*1024) #512Mb - old_prefix::Cstring - new_prefix::Cstring -end - -""" - LibGit2.DiffFile - -Description of one side of a delta. -Matches the [`git_diff_file`](https://libgit2.github.com/libgit2/#HEAD/type/git_diff_file) struct. -""" -struct DiffFile - id::GitHash - path::Cstring - size::Int64 - flags::UInt32 - mode::UInt16 - @static if LibGit2.VERSION >= v"0.25.0" - id_abbrev::UInt16 - end -end - -function Base.show(io::IO, df::DiffFile) - println(io, "DiffFile:") - println(io, "Oid: $(df.id))") - println(io, "Path: $(df.path)") - println(io, "Size: $(df.size)") -end - -""" - LibGit2.DiffDelta - -Description of changes to one entry. -Matches the [`git_diff_delta`](https://libgit2.github.com/libgit2/#HEAD/type/git_diff_delta) struct. - -The fields represent: - * `status`: One of `Consts.DELTA_STATUS`, indicating whether the file has been added/modified/deleted. - * `flags`: Flags for the delta and the objects on each side. Determines whether to treat the file(s) - as binary/text, whether they exist on each side of the diff, and whether the object ids are known - to be correct. - * `similarity`: Used to indicate if a file has been renamed or copied. - * `nfiles`: The number of files in the delta (for instance, if the delta - was run on a submodule commit id, it may contain more than one file). - * `old_file`: A [`DiffFile`](@ref) containing information about the file(s) before the changes. - * `new_file`: A [`DiffFile`](@ref) containing information about the file(s) after the changes. -""" -struct DiffDelta - status::Cint - flags::UInt32 - similarity::UInt16 - nfiles::UInt16 - old_file::DiffFile - new_file::DiffFile -end - -function Base.show(io::IO, dd::DiffDelta) - println(io, "DiffDelta:") - println(io, "Status: $(Consts.DELTA_STATUS(dd.status))") - println(io, "Number of files: $(dd.nfiles)") - println(io, "Old file:\n$(dd.old_file)") - println(io, "New file:\n$(dd.new_file)") -end - -""" - LibGit2.MergeOptions - -Matches the [`git_merge_options`](https://libgit2.github.com/libgit2/#HEAD/type/git_merge_options) struct. -""" -@kwdef struct MergeOptions - version::Cuint = 1 - flags::Cint - rename_threshold::Cuint = 50 - target_limit::Cuint = 200 - metric::Ptr{Void} - @static if LibGit2.VERSION >= v"0.24.0" - recursion_limit::Cuint - end - @static if LibGit2.VERSION >= v"0.25.0" - default_driver::Cstring - end - file_favor::GIT_MERGE_FILE_FAVOR = Consts.MERGE_FILE_FAVOR_NORMAL - file_flags::GIT_MERGE_FILE = Consts.MERGE_FILE_DEFAULT -end - -""" - LibGit2.PushOptions - -Matches the [`git_push_options`](https://libgit2.github.com/libgit2/#HEAD/type/git_push_options) struct. -""" -@kwdef struct PushOptions - version::Cuint = 1 - parallelism::Cint = 1 - callbacks::RemoteCallbacks - @static if LibGit2.VERSION >= v"0.25.0" - proxy_opts::ProxyOptions - end - @static if LibGit2.VERSION >= v"0.24.0" - custom_headers::StrArrayStruct - end -end - -""" - LibGit2.IndexTime - -Matches the [`git_index_time`](https://libgit2.github.com/libgit2/#HEAD/type/git_index_time) struct. -""" -struct IndexTime - seconds::Int64 - nanoseconds::Cuint -end - -""" - LibGit2.IndexEntry - -In-memory representation of a file entry in the index. -Matches the [`git_index_entry`](https://libgit2.github.com/libgit2/#HEAD/type/git_index_entry) struct. -""" -struct IndexEntry - ctime::IndexTime - mtime::IndexTime - - dev::UInt32 - ino::UInt32 - mode::UInt32 - uid::UInt32 - gid::UInt32 - file_size::Int64 - - id::GitHash - - flags::UInt16 - flags_extended::UInt16 - - path::Ptr{UInt8} -end -Base.show(io::IO, ie::IndexEntry) = print(io, "IndexEntry($(string(ie.id)))") - -""" - LibGit2.RebaseOptions - -Matches the `git_rebase_options` struct. -""" -@kwdef struct RebaseOptions - version::Cuint = 1 - quiet::Cint = 1 - @static if LibGit2.VERSION >= v"0.24.0" - inmemory::Cint - end - rewrite_notes_ref::Cstring - @static if LibGit2.VERSION >= v"0.24.0" - merge_opts::MergeOptions - end - checkout_opts::CheckoutOptions -end - -""" - LibGit2.RebaseOperation - -Describes a single instruction/operation to be performed during the rebase. -Matches the [`git_rebase_operation`](https://libgit2.github.com/libgit2/#HEAD/type/git_rebase_operation_t) struct. -""" -struct RebaseOperation - optype::Cint - id::GitHash - exec::Cstring -end -function Base.show(io::IO, rbo::RebaseOperation) - println(io, "RebaseOperation($(string(rbo.id)))") - println(io, "Operation type: $(Consts.GIT_REBASE_OPERATION(rbo.optype))") -end - -""" - LibGit2.StatusOptions - -Options to control how `git_status_foreach_ext()` will issue callbacks. -Matches the [`git_status_opt_t`](https://libgit2.github.com/libgit2/#HEAD/type/git_status_opt_t) struct. -""" -@kwdef struct StatusOptions - version::Cuint = 1 - show::Cint = Consts.STATUS_SHOW_INDEX_AND_WORKDIR - flags::Cuint = Consts.STATUS_OPT_INCLUDE_UNTRACKED | - Consts.STATUS_OPT_RECURSE_UNTRACKED_DIRS | - Consts.STATUS_OPT_RENAMES_HEAD_TO_INDEX | - Consts.STATUS_OPT_SORT_CASE_SENSITIVELY - pathspec::StrArrayStruct -end - -""" - LibGit2.StatusEntry - -Providing the differences between the file as it exists in HEAD and the index, and -providing the differences between the index and the working directory. -Matches the `git_status_entry` struct. -""" -struct StatusEntry - status::Cuint - head_to_index::Ptr{DiffDelta} - index_to_workdir::Ptr{DiffDelta} -end - -""" - LibGit2.FetchHead - -Contains the information about HEAD during a fetch, including the name and URL -of the branch fetched from, the oid of the HEAD, and whether the fetched HEAD -has been merged locally. -""" -struct FetchHead - name::String - url::String - oid::GitHash - ismerge::Bool -end - -function Base.show(io::IO, fh::FetchHead) - println(io, "FetchHead:") - println(io, "Name: $(fh.name)") - println(io, "URL: $(fh.url)") - print(io, "OID: ") - show(io, fh.oid) - println(io) - println(io, "Merged: $(fh.ismerge)") -end - -# Abstract object types -abstract type AbstractGitObject end -Base.isempty(obj::AbstractGitObject) = (obj.ptr == C_NULL) - -abstract type GitObject <: AbstractGitObject end - -for (typ, owntyp, sup, cname) in [ - (:GitRepo, nothing, :AbstractGitObject, :git_repository), - (:GitConfig, :(Nullable{GitRepo}), :AbstractGitObject, :git_config), - (:GitIndex, :(Nullable{GitRepo}), :AbstractGitObject, :git_index), - (:GitRemote, :GitRepo, :AbstractGitObject, :git_remote), - (:GitRevWalker, :GitRepo, :AbstractGitObject, :git_revwalk), - (:GitReference, :GitRepo, :AbstractGitObject, :git_reference), - (:GitDiff, :GitRepo, :AbstractGitObject, :git_diff), - (:GitDiffStats, :GitRepo, :AbstractGitObject, :git_diff_stats), - (:GitAnnotated, :GitRepo, :AbstractGitObject, :git_annotated_commit), - (:GitRebase, :GitRepo, :AbstractGitObject, :git_rebase), - (:GitStatus, :GitRepo, :AbstractGitObject, :git_status_list), - (:GitBranchIter, :GitRepo, :AbstractGitObject, :git_branch_iterator), - (:GitUnknownObject, :GitRepo, :GitObject, :git_object), - (:GitCommit, :GitRepo, :GitObject, :git_commit), - (:GitBlob, :GitRepo, :GitObject, :git_blob), - (:GitTree, :GitRepo, :GitObject, :git_tree), - (:GitTag, :GitRepo, :GitObject, :git_tag), - (:GitTreeEntry, :GitTree, :AbstractGitObject, :git_tree_entry), - ] - - if owntyp === nothing - @eval mutable struct $typ <: $sup - ptr::Ptr{Void} - function $typ(ptr::Ptr{Void}, fin::Bool=true) - # fin=false should only be used when the pointer should not be free'd - # e.g. from within callback functions which are passed a pointer - @assert ptr != C_NULL - obj = new(ptr) - if fin - Threads.atomic_add!(REFCOUNT, UInt(1)) - finalizer(obj, Base.close) - end - return obj - end - end - else - @eval mutable struct $typ <: $sup - owner::$owntyp - ptr::Ptr{Void} - function $typ(owner::$owntyp, ptr::Ptr{Void}, fin::Bool=true) - @assert ptr != C_NULL - obj = new(owner, ptr) - if fin - Threads.atomic_add!(REFCOUNT, UInt(1)) - finalizer(obj, Base.close) - end - return obj - end - end - if isa(owntyp, Expr) && owntyp.args[1] == :Nullable - @eval begin - $typ(ptr::Ptr{Void}, fin::Bool=true) = $typ($owntyp(), ptr, fin) - $typ(owner::$(owntyp.args[2]), ptr::Ptr{Void}, fin::Bool=true) = - $typ($owntyp(owner), ptr, fin) - end - end - end - @eval function Base.close(obj::$typ) - if obj.ptr != C_NULL - ccall(($(string(cname, :_free)), :libgit2), Void, (Ptr{Void},), obj.ptr) - obj.ptr = C_NULL - if Threads.atomic_sub!(REFCOUNT, UInt(1)) == 1 - # will the last finalizer please turn out the lights? - ccall((:git_libgit2_shutdown, :libgit2), Cint, ()) - end - end - end -end - -## Calling `GitObject(repo, ...)` will automatically resolve to the appropriate type. -function GitObject(repo::GitRepo, ptr::Ptr{Void}) - T = objtype(Consts.OBJECT(ptr)) - T(repo, ptr) -end - -""" - LibGit2.GitSignature - -This is a Julia wrapper around a pointer to a -[`git_signature`](https://libgit2.github.com/libgit2/#HEAD/type/git_signature) object. -""" -mutable struct GitSignature <: AbstractGitObject - ptr::Ptr{SignatureStruct} - function GitSignature(ptr::Ptr{SignatureStruct}) - @assert ptr != C_NULL - obj = new(ptr) - finalizer(obj, Base.close) - return obj - end -end -function Base.close(obj::GitSignature) - if obj.ptr != C_NULL - ccall((:git_signature_free, :libgit2), Void, (Ptr{SignatureStruct},), obj.ptr) - obj.ptr = C_NULL - end -end - -# Structure has the same layout as SignatureStruct -mutable struct Signature - name::String - email::String - time::Int64 - time_offset::Cint -end - -""" Resource management helper function -""" -function with(f::Function, obj) - try - f(obj) - finally - close(obj) - end -end - -with{T}(f::Function, ::Type{T}, args...) = with(f, T(args...)) - -function with_warn{T}(f::Function, ::Type{T}, args...) - obj = T(args...) - try - with(f, obj) - catch err - warn("$(string(T)) thrown exception: $err") - end -end - -""" - LibGit2.Consts.OBJECT{T<:GitObject}(::Type{T}) - -The `OBJECT` enum value corresponding to type `T`. -""" -Consts.OBJECT(::Type{GitCommit}) = Consts.OBJ_COMMIT -Consts.OBJECT(::Type{GitTree}) = Consts.OBJ_TREE -Consts.OBJECT(::Type{GitBlob}) = Consts.OBJ_BLOB -Consts.OBJECT(::Type{GitTag}) = Consts.OBJ_TAG -Consts.OBJECT(::Type{GitUnknownObject}) = Consts.OBJ_ANY -Consts.OBJECT(::Type{GitObject}) = Consts.OBJ_ANY - -Consts.OBJECT(ptr::Ptr{Void}) = - ccall((:git_object_type, :libgit2), Consts.OBJECT, (Ptr{Void},), ptr) - -""" - objtype(obj_type::Consts.OBJECT) - -Returns the type corresponding to the enum value. -""" -function objtype(obj_type::Consts.OBJECT) - if obj_type == Consts.OBJ_COMMIT - GitCommit - elseif obj_type == Consts.OBJ_TREE - GitTree - elseif obj_type == Consts.OBJ_BLOB - GitBlob - elseif obj_type == Consts.OBJ_TAG - GitTag - elseif obj_type == Consts.OBJ_ANY #this name comes from the header - GitUnknownObject - else - throw(GitError(Error.Object, Error.ENOTFOUND, "Object type $obj_type is not supported")) - end -end - -import Base.securezero! - -"Credentials that support only `user` and `password` parameters" -mutable struct UserPasswordCredentials <: AbstractCredentials - user::String - pass::String - prompt_if_incorrect::Bool # Whether to allow interactive prompting if the credentials are incorrect - count::Int # authentication failure protection count - function UserPasswordCredentials(u::AbstractString,p::AbstractString,prompt_if_incorrect::Bool=false) - c = new(u,p,prompt_if_incorrect,3) - finalizer(c, securezero!) - return c - end - UserPasswordCredentials(prompt_if_incorrect::Bool=false) = UserPasswordCredentials("","",prompt_if_incorrect) -end - -function securezero!(cred::UserPasswordCredentials) - securezero!(cred.user) - securezero!(cred.pass) - cred.count = 0 - return cred -end - -function Base.:(==)(a::UserPasswordCredentials, b::UserPasswordCredentials) - a.user == b.user && a.pass == b.pass -end - -"SSH credentials type" -mutable struct SSHCredentials <: AbstractCredentials - user::String - pass::String - prvkey::String - pubkey::String - usesshagent::String # used for ssh-agent authentication - prompt_if_incorrect::Bool # Whether to allow interactive prompting if the credentials are incorrect - count::Int - function SSHCredentials(u::AbstractString,p::AbstractString,prvkey::AbstractString,pubkey::AbstractString,prompt_if_incorrect::Bool=false) - c = new(u,p,prvkey,pubkey,"Y",prompt_if_incorrect,3) - finalizer(c, securezero!) - return c - end - SSHCredentials(u::AbstractString,p::AbstractString,prompt_if_incorrect::Bool=false) = SSHCredentials(u,p,"","",prompt_if_incorrect) - SSHCredentials(prompt_if_incorrect::Bool=false) = SSHCredentials("","","","",prompt_if_incorrect) -end - -function securezero!(cred::SSHCredentials) - securezero!(cred.user) - securezero!(cred.pass) - securezero!(cred.prvkey) - securezero!(cred.pubkey) - cred.count = 0 - return cred -end - -function Base.:(==)(a::SSHCredentials, b::SSHCredentials) - a.user == b.user && a.pass == b.pass && a.prvkey == b.prvkey && a.pubkey == b.pubkey -end - -"Credentials that support caching" -mutable struct CachedCredentials <: AbstractCredentials - cred::Dict{String,AbstractCredentials} - count::Int # authentication failure protection count - CachedCredentials() = new(Dict{String,AbstractCredentials}(),3) -end - -"Checks if credentials were used or failed authentication, see `LibGit2.credentials_callback`" -function checkused!(p::Union{UserPasswordCredentials, SSHCredentials}) - p.count <= 0 && return true - p.count -= 1 - return false -end -reset!(p::Union{UserPasswordCredentials, SSHCredentials}, cnt::Int=3) = (p.count = cnt; p) -reset!(p::CachedCredentials) = (foreach(reset!, values(p.cred)); p) - -"Obtain the cached credentials for the given host+protocol (credid), or return and store the default if not found" -get_creds!(collection::CachedCredentials, credid, default) = get!(collection.cred, credid, default) -get_creds!(creds::AbstractCredentials, credid, default) = creds -get_creds!(creds::Void, credid, default) = default -function get_creds!(creds::Ref{Nullable{AbstractCredentials}}, credid, default) - if isnull(creds[]) - creds[] = Nullable{AbstractCredentials}(default) - return default - else - get_creds!(Base.get(creds[]), credid, default) - end -end - -function securezero!(p::CachedCredentials) - foreach(securezero!, values(p.cred)) - return p -end diff --git a/julia-0.6.3/share/julia/base/libgit2/utils.jl b/julia-0.6.3/share/julia/base/libgit2/utils.jl deleted file mode 100644 index 59b84bf..0000000 --- a/julia-0.6.3/share/julia/base/libgit2/utils.jl +++ /dev/null @@ -1,67 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -# Parse "GIT URLs" syntax (URLs and a scp-like syntax). For details see: -# https://git-scm.com/docs/git-clone#_git_urls_a_id_urls_a -const URL_REGEX = r""" -^(?:(?ssh|git|https?)://)? -(?: - (?.*?) - (?:\:(?.*?))?@ -)? -(?[A-Za-z0-9\-\.]+) -(?() - (?:\:(?\d+))? # only parse port when not using SCP-like syntax - | - :? -) -(?.*?)$ -"""x - -function version() - major = Ref{Cint}(0) - minor = Ref{Cint}(0) - patch = Ref{Cint}(0) - ccall((:git_libgit2_version, :libgit2), Void, - (Ptr{Cint}, Ptr{Cint}, Ptr{Cint}), major, minor, patch) - return VersionNumber(major[], minor[], patch[]) -end -const VERSION = version() - -isset(val::Integer, flag::Integer) = (val & flag == flag) -reset(val::Integer, flag::Integer) = (val &= ~flag) -toggle(val::Integer, flag::Integer) = (val |= flag) - -function prompt(msg::AbstractString; default::AbstractString="", password::Bool=false) - if is_windows() && password - error("Command line prompt not supported for password entry on windows. Use winprompt instead") - end - msg = !isempty(default) ? msg*" [$default]:" : msg*":" - uinput = if password - Base.getpass(msg) - else - print(msg) - readline() - end - isempty(uinput) ? default : uinput -end - -function features() - feat = ccall((:git_libgit2_features, :libgit2), Cint, ()) - res = Consts.GIT_FEATURE[] - for f in instances(Consts.GIT_FEATURE) - isset(feat, Cuint(f)) && push!(res, f) - end - return res -end - -""" - LibGit2.posixpath(path) - -Standardise the path string `path` to use POSIX separators. -""" -function posixpath end -if is_windows() - posixpath(path) = replace(path,'\\','/') -else is_unix() - posixpath(path) = path -end diff --git a/julia-0.6.3/share/julia/base/libgit2/walker.jl b/julia-0.6.3/share/julia/base/libgit2/walker.jl deleted file mode 100644 index 41b44fc..0000000 --- a/julia-0.6.3/share/julia/base/libgit2/walker.jl +++ /dev/null @@ -1,102 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -function GitRevWalker(repo::GitRepo) - w_ptr = Ref{Ptr{Void}}(C_NULL) - @check ccall((:git_revwalk_new, :libgit2), Cint, - (Ptr{Ptr{Void}}, Ptr{Void}), w_ptr, repo.ptr) - return GitRevWalker(repo, w_ptr[]) -end - -function Base.start(w::GitRevWalker) - id_ptr = Ref(GitHash()) - err = ccall((:git_revwalk_next, :libgit2), Cint, - (Ptr{GitHash}, Ptr{Void}), id_ptr, w.ptr) - err != Int(Error.GIT_OK) && return (nothing, true) - return (id_ptr[], false) -end - -Base.done(w::GitRevWalker, state) = Bool(state[2]) - -function Base.next(w::GitRevWalker, state) - id_ptr = Ref(GitHash()) - err = ccall((:git_revwalk_next, :libgit2), Cint, - (Ptr{GitHash}, Ptr{Void}), id_ptr, w.ptr) - err != Int(Error.GIT_OK) && return (state[1], (nothing, true)) - return (state[1], (id_ptr[], false)) -end - -Base.iteratorsize(::Type{GitRevWalker}) = Base.SizeUnknown() - -function push_head!(w::GitRevWalker) - @check ccall((:git_revwalk_push_head, :libgit2), Cint, (Ptr{Void},), w.ptr) - return w -end - -function Base.push!(w::GitRevWalker, cid::GitHash) - @check ccall((:git_revwalk_push, :libgit2), Cint, (Ptr{Void}, Ptr{GitHash}), w.ptr, Ref(cid)) - return w -end - -function Base.push!(w::GitRevWalker, range::AbstractString) - @check ccall((:git_revwalk_push_range, :libgit2), Cint, (Ptr{Void}, Ptr{UInt8}), w.ptr, range) - return w -end - -function Base.sort!(w::GitRevWalker; by::Cint = Consts.SORT_NONE, rev::Bool=false) - rev && (by |= Consts.SORT_REVERSE) - ccall((:git_revwalk_sorting, :libgit2), Void, (Ptr{Void}, Cint), w.ptr, by) - return w -end - -repository(w::GitRevWalker) = w.owner - -function Base.map(f::Function, walker::GitRevWalker; - oid::GitHash=GitHash(), - range::AbstractString="", - by::Cint = Consts.SORT_NONE, - rev::Bool=false, - count::Int=0) - res = [] - sort!(walker, by=by, rev=rev) - if !iszero(oid) - push!(walker, oid) - elseif !isempty(range) - push!(walker, range) - else - push_head!(walker) - end - s = start(walker) - - c = 0 - repo = repository(walker) - while !done(walker, s) - val = f(s[1], repo) - push!(res, val) - val, s = next(walker, s) - c +=1 - count == c && break - end - return res -end - -function Base.count(f::Function, walker::GitRevWalker; - oid::GitHash=GitHash(), - by::Cint = Consts.SORT_NONE, - rev::Bool=false) - c = 0 - sort!(walker, by=by, rev=rev) - if !iszero(oid) - push!(walker, oid) - else - push_head!(walker) - end - s = start(walker) - - repo = repository(walker) - while !done(walker, s) - val = f(s[1], repo) - _, s = next(walker, s) - c += (val == true) - end - return c -end diff --git a/julia-0.6.3/share/julia/base/libuv.jl b/julia-0.6.3/share/julia/base/libuv.jl deleted file mode 100644 index 63894de..0000000 --- a/julia-0.6.3/share/julia/base/libuv.jl +++ /dev/null @@ -1,126 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -# Core definitions for interacting with the libuv library from Julia - -include(string(length(Core.ARGS)>=2?Core.ARGS[2]:"","uv_constants.jl")) # include($BUILDROOT/base/uv_constants.jl) - -# convert UV handle data to julia object, checking for null -function uv_sizeof_handle(handle) - if !(UV_UNKNOWN_HANDLE < handle < UV_HANDLE_TYPE_MAX) - throw(DomainError()) - end - ccall(:uv_handle_size,Csize_t,(Int32,),handle) -end - -function uv_sizeof_req(req) - if !(UV_UNKNOWN_REQ < req < UV_REQ_TYPE_MAX) - throw(DomainError()) - end - ccall(:uv_req_size,Csize_t,(Int32,),req) -end - -for h in uv_handle_types -@eval const $(Symbol("_sizeof_",lowercase(string(h)))) = uv_sizeof_handle($h) -end -for r in uv_req_types -@eval const $(Symbol("_sizeof_",lowercase(string(r)))) = uv_sizeof_req($r) -end - -uv_handle_data(handle) = ccall(:jl_uv_handle_data,Ptr{Void},(Ptr{Void},),handle) -uv_req_data(handle) = ccall(:jl_uv_req_data,Ptr{Void},(Ptr{Void},),handle) -uv_req_set_data(req,data) = ccall(:jl_uv_req_set_data,Void,(Ptr{Void},Any),req,data) -uv_req_set_data(req,data::Ptr{Void}) = ccall(:jl_uv_req_set_data,Void,(Ptr{Void},Ptr{Void}),req,data) - -macro handle_as(hand, typ) - quote - data = uv_handle_data($(esc(hand))) - data == C_NULL && return - unsafe_pointer_to_objref(data)::($(esc(typ))) - end -end - -associate_julia_struct(handle::Ptr{Void}, jlobj::ANY) = - ccall(:jl_uv_associate_julia_struct, Void, (Ptr{Void}, Any), handle, jlobj) -disassociate_julia_struct(uv) = disassociate_julia_struct(uv.handle) -disassociate_julia_struct(handle::Ptr{Void}) = - handle != C_NULL && ccall(:jl_uv_disassociate_julia_struct, Void, (Ptr{Void},), handle) - -# A dict of all libuv handles that are being waited on somewhere in the system -# and should thus not be garbage collected -const uvhandles = ObjectIdDict() -preserve_handle(x) = uvhandles[x] = get(uvhandles,x,0)::Int+1 -unpreserve_handle(x) = (v = uvhandles[x]::Int; v == 1 ? pop!(uvhandles,x) : (uvhandles[x] = v-1); nothing) - -## Libuv error handling ## - -mutable struct UVError <: Exception - prefix::AbstractString - code::Int32 - UVError(p::AbstractString,code::Integer)=new(p,code) -end - -struverror(err::Int32) = unsafe_string(ccall(:uv_strerror,Cstring,(Int32,),err)) -struverror(err::UVError) = struverror(err.code) -uverrorname(err::Int32) = unsafe_string(ccall(:uv_err_name,Cstring,(Int32,),err)) -uverrorname(err::UVError) = uverrorname(err.code) - -uv_error(prefix::Symbol, c::Integer) = uv_error(string(prefix),c) -uv_error(prefix::AbstractString, c::Integer) = c < 0 ? throw(UVError(prefix,c)) : nothing -show(io::IO, e::UVError) = print(io, e.prefix*": "*struverror(e)*" ("*uverrorname(e)*")") - -## event loop ## - -eventloop() = uv_eventloop::Ptr{Void} -#mkNewEventLoop() = ccall(:jl_new_event_loop,Ptr{Void},()) # this would probably be fine, but is nowhere supported - -function run_event_loop() - ccall(:jl_run_event_loop,Void,(Ptr{Void},),eventloop()) -end -function process_events(block::Bool) - loop = eventloop() - if block - return ccall(:jl_run_once,Int32,(Ptr{Void},),loop) - else - return ccall(:jl_process_events,Int32,(Ptr{Void},),loop) - end -end - -function reinit_stdio() - global uv_jl_alloc_buf = cfunction(uv_alloc_buf, Void, Tuple{Ptr{Void}, Csize_t, Ptr{Void}}) - global uv_jl_readcb = cfunction(uv_readcb, Void, Tuple{Ptr{Void}, Cssize_t, Ptr{Void}}) - global uv_jl_connectioncb = cfunction(uv_connectioncb, Void, Tuple{Ptr{Void}, Cint}) - global uv_jl_connectcb = cfunction(uv_connectcb, Void, Tuple{Ptr{Void}, Cint}) - global uv_jl_writecb_task = cfunction(uv_writecb_task, Void, Tuple{Ptr{Void}, Cint}) - global uv_jl_getaddrinfocb = cfunction(uv_getaddrinfocb, Void, Tuple{Ptr{Void}, Cint, Ptr{Void}}) - global uv_jl_recvcb = cfunction(uv_recvcb, Void, Tuple{Ptr{Void}, Cssize_t, Ptr{Void}, Ptr{Void}, Cuint}) - global uv_jl_sendcb = cfunction(uv_sendcb, Void, Tuple{Ptr{Void}, Cint}) - global uv_jl_return_spawn = cfunction(uv_return_spawn, Void, Tuple{Ptr{Void}, Int64, Int32}) - global uv_jl_asynccb = cfunction(uv_asynccb, Void, Tuple{Ptr{Void}}) - global uv_jl_timercb = cfunction(uv_timercb, Void, Tuple{Ptr{Void}}) - - global uv_eventloop = ccall(:jl_global_event_loop, Ptr{Void}, ()) - global STDIN = init_stdio(ccall(:jl_stdin_stream, Ptr{Void}, ())) - global STDOUT = init_stdio(ccall(:jl_stdout_stream, Ptr{Void}, ())) - global STDERR = init_stdio(ccall(:jl_stderr_stream, Ptr{Void}, ())) -end - -""" - STDIN - -Global variable referring to the standard input stream. -""" -:STDIN - -""" - STDOUT - -Global variable referring to the standard out stream. -""" -:STDOUT - -""" - STDERR - -Global variable referring to the standard error stream. -""" -:STDERR diff --git a/julia-0.6.3/share/julia/base/linalg/arnoldi.jl b/julia-0.6.3/share/julia/base/linalg/arnoldi.jl deleted file mode 100644 index 70e893a..0000000 --- a/julia-0.6.3/share/julia/base/linalg/arnoldi.jl +++ /dev/null @@ -1,422 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -using .ARPACK - -## eigs -""" - eigs(A; nev=6, ncv=max(20,2*nev+1), which=:LM, tol=0.0, maxiter=300, sigma=nothing, ritzvec=true, v0=zeros((0,))) -> (d,[v,],nconv,niter,nmult,resid) - -Computes eigenvalues `d` of `A` using implicitly restarted Lanczos or Arnoldi iterations for real symmetric or -general nonsymmetric matrices respectively. - -The following keyword arguments are supported: - -* `nev`: Number of eigenvalues -* `ncv`: Number of Krylov vectors used in the computation; should satisfy `nev+1 <= ncv <= n` - for real symmetric problems and `nev+2 <= ncv <= n` for other problems, where `n` is the - size of the input matrix `A`. The default is `ncv = max(20,2*nev+1)`. Note that these - restrictions limit the input matrix `A` to be of dimension at least 2. -* `which`: type of eigenvalues to compute. See the note below. - -| `which` | type of eigenvalues | -|:--------|:--------------------------------------------------------------------------------------------------------------------------| -| `:LM` | eigenvalues of largest magnitude (default) | -| `:SM` | eigenvalues of smallest magnitude | -| `:LR` | eigenvalues of largest real part | -| `:SR` | eigenvalues of smallest real part | -| `:LI` | eigenvalues of largest imaginary part (nonsymmetric or complex `A` only) | -| `:SI` | eigenvalues of smallest imaginary part (nonsymmetric or complex `A` only) | -| `:BE` | compute half of the eigenvalues from each end of the spectrum, biased in favor of the high end. (real symmetric `A` only) | - -* `tol`: parameter defining the relative tolerance for convergence of Ritz values (eigenvalue estimates). - A Ritz value ``θ`` is considered converged when its associated residual - is less than or equal to the product of `tol` and ``max(ɛ^{2/3}, |θ|)``, - where `ɛ = eps(real(eltype(A)))/2` is LAPACK's machine epsilon. - The residual associated with ``θ`` and its corresponding Ritz vector ``v`` - is defined as the norm ``||Av - vθ||``. - The specified value of `tol` should be positive; otherwise, it is ignored - and ``ɛ`` is used instead. - Default: ``ɛ``. - -* `maxiter`: Maximum number of iterations (default = 300) -* `sigma`: Specifies the level shift used in inverse iteration. If `nothing` (default), - defaults to ordinary (forward) iterations. Otherwise, find eigenvalues close to `sigma` - using shift and invert iterations. -* `ritzvec`: Returns the Ritz vectors `v` (eigenvectors) if `true` -* `v0`: starting vector from which to start the iterations - -`eigs` returns the `nev` requested eigenvalues in `d`, the corresponding Ritz vectors `v` -(only if `ritzvec=true`), the number of converged eigenvalues `nconv`, the number of -iterations `niter` and the number of matrix vector multiplications `nmult`, as well as the -final residual vector `resid`. - -# Example - -```jldoctest -julia> A = spdiagm(1:4); - -julia> λ, ϕ = eigs(A, nev = 2); - -julia> λ -2-element Array{Float64,1}: - 4.0 - 3.0 -``` - -!!! note - The `sigma` and `which` keywords interact: the description of eigenvalues - searched for by `which` do *not* necessarily refer to the eigenvalues of - `A`, but rather the linear operator constructed by the specification of the - iteration mode implied by `sigma`. - - | `sigma` | iteration mode | `which` refers to eigenvalues of | - |:----------------|:---------------------------------|:---------------------------------| - | `nothing` | ordinary (forward) | ``A`` | - | real or complex | inverse with level shift `sigma` | ``(A - \\sigma I )^{-1}`` | - -!!! note - Although `tol` has a default value, the best choice depends strongly on the - matrix `A`. We recommend that users _always_ specify a value for `tol` - which suits their specific needs. - - For details of how the errors in the computed eigenvalues are estimated, see: - - * B. N. Parlett, "The Symmetric Eigenvalue Problem", SIAM: Philadelphia, 2/e - (1998), Ch. 13.2, "Accessing Accuracy in Lanczos Problems", pp. 290-292 ff. - * R. B. Lehoucq and D. C. Sorensen, "Deflation Techniques for an Implicitly - Restarted Arnoldi Iteration", SIAM Journal on Matrix Analysis and - Applications (1996), 17(4), 789–821. doi:10.1137/S0895479895281484 -""" -eigs(A; kwargs...) = eigs(A, I; kwargs...) -eigs(A::AbstractMatrix{<:BlasFloat}, ::UniformScaling; kwargs...) = _eigs(A, I; kwargs...) - -eigs(A::AbstractMatrix{T}, B::AbstractMatrix{T}; kwargs...) where {T<:BlasFloat} = _eigs(A, B; kwargs...) -eigs(A::AbstractMatrix{BigFloat}, B::AbstractMatrix...; kwargs...) = throw(MethodError(eigs, Any[A,B,kwargs...])) -eigs(A::AbstractMatrix{BigFloat}, B::UniformScaling; kwargs...) = throw(MethodError(eigs, Any[A,B,kwargs...])) -function eigs(A::AbstractMatrix{T}, ::UniformScaling; kwargs...) where T - Tnew = typeof(zero(T)/sqrt(one(T))) - eigs(convert(AbstractMatrix{Tnew}, A), I; kwargs...) -end -function eigs(A::AbstractMatrix, B::AbstractMatrix; kwargs...) - T = promote_type(eltype(A), eltype(B)) - Tnew = typeof(zero(T)/sqrt(one(T))) - eigs(convert(AbstractMatrix{Tnew}, A), convert(AbstractMatrix{Tnew}, B); kwargs...) -end -""" - eigs(A, B; nev=6, ncv=max(20,2*nev+1), which=:LM, tol=0.0, maxiter=300, sigma=nothing, ritzvec=true, v0=zeros((0,))) -> (d,[v,],nconv,niter,nmult,resid) - -Computes generalized eigenvalues `d` of `A` and `B` using implicitly restarted Lanczos or Arnoldi iterations for -real symmetric or general nonsymmetric matrices respectively. - -The following keyword arguments are supported: - -* `nev`: Number of eigenvalues -* `ncv`: Number of Krylov vectors used in the computation; should satisfy `nev+1 <= ncv <= n` - for real symmetric problems and `nev+2 <= ncv <= n` for other problems, where `n` is the - size of the input matrices `A` and `B`. The default is `ncv = max(20,2*nev+1)`. Note that - these restrictions limit the input matrix `A` to be of dimension at least 2. -* `which`: type of eigenvalues to compute. See the note below. - -| `which` | type of eigenvalues | -|:--------|:--------------------------------------------------------------------------------------------------------------------------| -| `:LM` | eigenvalues of largest magnitude (default) | -| `:SM` | eigenvalues of smallest magnitude | -| `:LR` | eigenvalues of largest real part | -| `:SR` | eigenvalues of smallest real part | -| `:LI` | eigenvalues of largest imaginary part (nonsymmetric or complex `A` only) | -| `:SI` | eigenvalues of smallest imaginary part (nonsymmetric or complex `A` only) | -| `:BE` | compute half of the eigenvalues from each end of the spectrum, biased in favor of the high end. (real symmetric `A` only) | - -* `tol`: relative tolerance used in the convergence criterion for eigenvalues, similar to - `tol` in the [`eigs(A)`](@ref) method for the ordinary eigenvalue - problem, but effectively for the eigenvalues of ``B^{-1} A`` instead of ``A``. - See the documentation for the ordinary eigenvalue problem in - [`eigs(A)`](@ref) and the accompanying note about `tol`. -* `maxiter`: Maximum number of iterations (default = 300) -* `sigma`: Specifies the level shift used in inverse iteration. If `nothing` (default), - defaults to ordinary (forward) iterations. Otherwise, find eigenvalues close to `sigma` - using shift and invert iterations. -* `ritzvec`: Returns the Ritz vectors `v` (eigenvectors) if `true` -* `v0`: starting vector from which to start the iterations - -`eigs` returns the `nev` requested eigenvalues in `d`, the corresponding Ritz vectors `v` -(only if `ritzvec=true`), the number of converged eigenvalues `nconv`, the number of -iterations `niter` and the number of matrix vector multiplications `nmult`, as well as the -final residual vector `resid`. - -# Example - -```jldoctest -julia> A = speye(4, 4); B = spdiagm(1:4); - -julia> λ, ϕ = eigs(A, B, nev = 2); - -julia> λ -2-element Array{Float64,1}: - 1.0 - 0.5 -``` - -!!! note - The `sigma` and `which` keywords interact: the description of eigenvalues searched for by - `which` do *not* necessarily refer to the eigenvalue problem ``Av = Bv\\lambda``, but rather - the linear operator constructed by the specification of the iteration mode implied by `sigma`. - - | `sigma` | iteration mode | `which` refers to the problem | - |:----------------|:---------------------------------|:-----------------------------------| - | `nothing` | ordinary (forward) | ``Av = Bv\\lambda`` | - | real or complex | inverse with level shift `sigma` | ``(A - \\sigma B )^{-1}B = v\\nu`` | -""" -eigs(A, B; kwargs...) = _eigs(A, B; kwargs...) -function _eigs(A, B; - nev::Integer=6, ncv::Integer=max(20,2*nev+1), which=:LM, - tol=0.0, maxiter::Integer=300, sigma=nothing, v0::Vector=zeros(eltype(A),(0,)), - ritzvec::Bool=true) - n = checksquare(A) - - T = eltype(A) - iscmplx = T <: Complex - isgeneral = B !== I - sym = issymmetric(A) && issymmetric(B) && !iscmplx - nevmax=sym ? n-1 : n-2 - if nevmax <= 0 - throw(ArgumentError("input matrix A is too small. Use eigfact instead.")) - end - if nev > nevmax - warn("Adjusting nev from $nev to $nevmax") - nev = nevmax - end - if nev <= 0 - throw(ArgumentError("requested number of eigenvalues (nev) must be ≥ 1, got $nev")) - end - ncvmin = nev + (sym ? 1 : 2) - if ncv < ncvmin - warn("Adjusting ncv from $ncv to $ncvmin") - ncv = ncvmin - end - ncv = BlasInt(min(ncv, n)) - bmat = isgeneral ? "G" : "I" - isshift = sigma !== nothing - - if isa(which,AbstractString) - warn("Use symbols instead of strings for specifying which eigenvalues to compute") - which=Symbol(which) - end - if (which != :LM && which != :SM && which != :LR && which != :SR && - which != :LI && which != :SI && which != :BE) - throw(ArgumentError("which must be :LM, :SM, :LR, :SR, :LI, :SI, or :BE, got $(repr(which))")) - end - if which == :BE && !sym - throw(ArgumentError("which=:BE only possible for real symmetric problem")) - end - isshift && which == :SM && warn("use of :SM in shift-and-invert mode is not recommended, use :LM to find eigenvalues closest to sigma") - - if which==:SM && !isshift # transform into shift-and-invert method with sigma = 0 - isshift=true - sigma=zero(T) - which=:LM - end - - if sigma !== nothing && !iscmplx && isa(sigma,Complex) - throw(ArgumentError("complex shifts for real problems are not yet supported")) - end - sigma = isshift ? convert(T,sigma) : zero(T) - - if !isempty(v0) - if length(v0) != n - throw(DimensionMismatch()) - end - if eltype(v0) != T - throw(ArgumentError("starting vector must have element type $T, got $(eltype(v0))")) - end - end - - whichstr = "LM" - if which == :BE - whichstr = "BE" - end - if which == :LR - whichstr = (!sym ? "LR" : "LA") - end - if which == :SR - whichstr = (!sym ? "SR" : "SA") - end - if which == :LI - if !sym - whichstr = "LI" - else - throw(ArgumentError("largest imaginary is meaningless for symmetric eigenvalue problems")) - end - end - if which == :SI - if !sym - whichstr = "SI" - else - throw(ArgumentError("smallest imaginary is meaningless for symmetric eigenvalue problems")) - end - end - - # Refer to ex-*.doc files in ARPACK/DOCUMENTS for calling sequence - matvecA!(y, x) = A_mul_B!(y, A, x) - if !isgeneral # Standard problem - matvecB = x -> x - if !isshift # Regular mode - mode = 1 - solveSI = x->x - else # Shift-invert mode - mode = 3 - F = factorize(A - UniformScaling(sigma)) - solveSI = x -> F \ x - end - else # Generalized eigenproblem - matvecB = x -> B * x - if !isshift # Regular inverse mode - mode = 2 - F = factorize(B) - solveSI = x -> F \ x - else # Shift-invert mode - mode = 3 - F = factorize(A - sigma*B) - solveSI = x -> F \ x - end - end - - # Compute the Ritz values and Ritz vectors - (resid, v, ldv, iparam, ipntr, workd, workl, lworkl, rwork, TOL) = - ARPACK.aupd_wrapper(T, matvecA!, matvecB, solveSI, n, sym, iscmplx, bmat, nev, ncv, whichstr, tol, maxiter, mode, v0) - - # Postprocessing to get eigenvalues and eigenvectors - output = ARPACK.eupd_wrapper(T, n, sym, iscmplx, bmat, nev, whichstr, ritzvec, TOL, - resid, ncv, v, ldv, sigma, iparam, ipntr, workd, workl, lworkl, rwork) - - # Issue 10495, 10701: Check that all eigenvalues are converged - nev = length(output[1]) - nconv = output[ritzvec ? 3 : 2] - nev ≤ nconv || warn("not all wanted Ritz pairs converged. Requested: $nev, converged: $nconv") - - return output -end - - -## svds -### Restrict operator to BlasFloat because ARPACK only supports that. Loosen restriction -### when we switch to our own implementation -mutable struct SVDOperator{T<:BlasFloat,S} <: AbstractArray{T, 2} - X::S - m::Int - n::Int - SVDOperator{T,S}(X::AbstractMatrix) where {T<:BlasFloat,S} = new(X, size(X, 1), size(X, 2)) -end - -function SVDOperator(A::AbstractMatrix{T}) where T - Tnew = typeof(zero(T)/sqrt(one(T))) - Anew = convert(AbstractMatrix{Tnew}, A) - SVDOperator{Tnew,typeof(Anew)}(Anew) -end - -function A_mul_B!(u::StridedVector{T}, s::SVDOperator{T}, v::StridedVector{T}) where T - a, b = s.m, length(v) - A_mul_B!(view(u,1:a), s.X, view(v,a+1:b)) # left singular vector - Ac_mul_B!(view(u,a+1:b), s.X, view(v,1:a)) # right singular vector - u -end -size(s::SVDOperator) = s.m + s.n, s.m + s.n -issymmetric(s::SVDOperator) = true - -svds(A::AbstractMatrix{<:BlasFloat}; kwargs...) = _svds(A; kwargs...) -svds(A::AbstractMatrix{BigFloat}; kwargs...) = throw(MethodError(svds, Any[A, kwargs...])) -function svds(A::AbstractMatrix{T}; kwargs...) where T - Tnew = typeof(zero(T)/sqrt(one(T))) - svds(convert(AbstractMatrix{Tnew}, A); kwargs...) -end - -""" - svds(A; nsv=6, ritzvec=true, tol=0.0, maxiter=1000, ncv=2*nsv, u0=zeros((0,)), v0=zeros((0,))) -> (SVD([left_sv,] s, [right_sv,]), nconv, niter, nmult, resid) - -Computes the largest singular values `s` of `A` using implicitly restarted Lanczos -iterations derived from [`eigs`](@ref). - -**Inputs** - -* `A`: Linear operator whose singular values are desired. `A` may be represented as a - subtype of `AbstractArray`, e.g., a sparse matrix, or any other type supporting the four - methods `size(A)`, `eltype(A)`, `A * vector`, and `A' * vector`. -* `nsv`: Number of singular values. Default: 6. -* `ritzvec`: If `true`, return the left and right singular vectors `left_sv` and `right_sv`. - If `false`, omit the singular vectors. Default: `true`. -* `tol`: tolerance, see [`eigs`](@ref). -* `maxiter`: Maximum number of iterations, see [`eigs`](@ref). Default: 1000. -* `ncv`: Maximum size of the Krylov subspace, see [`eigs`](@ref) (there called `nev`). Default: `2*nsv`. -* `u0`: Initial guess for the first left Krylov vector. It may have length `m` (the first dimension of `A`), or 0. -* `v0`: Initial guess for the first right Krylov vector. It may have length `n` (the second dimension of `A`), or 0. - -**Outputs** - -* `svd`: An `SVD` object containing the left singular vectors, the requested values, and the - right singular vectors. If `ritzvec = false`, the left and right singular vectors will be - empty. -* `nconv`: Number of converged singular values. -* `niter`: Number of iterations. -* `nmult`: Number of matrix--vector products used. -* `resid`: Final residual vector. - -# Example - -```jldoctest -julia> A = spdiagm(1:4); - -julia> s = svds(A, nsv = 2)[1]; - -julia> s[:S] -2-element Array{Float64,1}: - 4.0 - 3.0 -``` - -!!! note "Implementation" - `svds(A)` is formally equivalent to calling [`eigs`](@ref) to perform implicitly restarted - Lanczos tridiagonalization on the Hermitian matrix - ``\\begin{pmatrix} 0 & A^\\prime \\\\ A & 0 \\end{pmatrix}``, whose eigenvalues are - plus and minus the singular values of ``A``. -""" -svds(A; kwargs...) = _svds(A; kwargs...) -function _svds(X; nsv::Int = 6, ritzvec::Bool = true, tol::Float64 = 0.0, maxiter::Int = 1000, ncv::Int = 2*nsv, u0::Vector=zeros(eltype(X),(0,)), v0::Vector=zeros(eltype(X),(0,))) - if nsv < 1 - throw(ArgumentError("number of singular values (nsv) must be ≥ 1, got $nsv")) - end - if nsv > minimum(size(X)) - throw(ArgumentError("number of singular values (nsv) must be ≤ $(minimum(size(X))), got $nsv")) - end - m,n = size(X) - otype = eltype(X) - padv0 = zeros(eltype(X),(0,)) - if length(v0) ∉ [0,n] - throw(DimensionMismatch("length of v0, the guess for the starting right Krylov vector, must be 0, or $n, got $(length(v0))")) - end - if length(u0) ∉ [0,m] - throw(DimensionMismatch("length of u0, the guess for the starting left Krylov vector, must be 0, or $m, got $(length(u0))")) - end - if length(v0) == n && length(u0) == m - padv0 = [u0; v0] - elseif length(v0) == n && length(u0) == 0 - padv0 = [zeros(otype,m); v0] - elseif length(v0) == 0 && length(u0) == m - padv0 = [u0; zeros(otype,n) ] - end - ex = eigs(SVDOperator(X), I; ritzvec = ritzvec, nev = ncv, tol = tol, maxiter = maxiter, v0=padv0) - ind = [1:2:ncv;] - sval = abs.(ex[1][ind]) - - if ritzvec - # calculating singular vectors - left_sv = sqrt(2) * ex[2][ 1:size(X,1), ind ] .* sign.(ex[1][ind]') - right_sv = sqrt(2) * ex[2][ size(X,1)+1:end, ind ] - return (SVD(left_sv, sval, right_sv'), ex[3], ex[4], ex[5], ex[6]) - else - #The sort is necessary to work around #10329 - return (SVD(zeros(eltype(sval), n, 0), - sort!(sval, by=real, rev=true), - zeros(eltype(sval), 0, m)), - ex[2], ex[3], ex[4], ex[5]) - end -end diff --git a/julia-0.6.3/share/julia/base/linalg/arpack.jl b/julia-0.6.3/share/julia/base/linalg/arpack.jl deleted file mode 100644 index be6db87..0000000 --- a/julia-0.6.3/share/julia/base/linalg/arpack.jl +++ /dev/null @@ -1,288 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -module ARPACK - -import ..LinAlg: BlasInt, ARPACKException - -## aupd and eupd wrappers - -function aupd_wrapper(T, matvecA!::Function, matvecB::Function, solveSI::Function, n::Integer, - sym::Bool, cmplx::Bool, bmat::String, - nev::Integer, ncv::Integer, which::String, - tol::Real, maxiter::Integer, mode::Integer, v0::Vector) - lworkl = cmplx ? ncv * (3*ncv + 5) : (sym ? ncv * (ncv + 8) : ncv * (3*ncv + 6) ) - TR = cmplx ? T.types[1] : T - TOL = Vector{TR}(1) - TOL[1] = tol - - v = Matrix{T}(n, ncv) - workd = Vector{T}(3*n) - workl = Vector{T}(lworkl) - rwork = cmplx ? Vector{TR}(ncv) : Vector{TR}(0) - - if isempty(v0) - resid = Vector{T}(n) - info = zeros(BlasInt, 1) - else - resid = deepcopy(v0) - info = ones(BlasInt, 1) - end - iparam = zeros(BlasInt, 11) - ipntr = zeros(BlasInt, (sym && !cmplx) ? 11 : 14) - ido = zeros(BlasInt, 1) - - iparam[1] = BlasInt(1) # ishifts - iparam[3] = BlasInt(maxiter) # maxiter - iparam[7] = BlasInt(mode) # mode - - zernm1 = 0:(n-1) - - while true - if cmplx - naupd(ido, bmat, n, which, nev, TOL, resid, ncv, v, n, - iparam, ipntr, workd, workl, lworkl, rwork, info) - elseif sym - saupd(ido, bmat, n, which, nev, TOL, resid, ncv, v, n, - iparam, ipntr, workd, workl, lworkl, info) - else - naupd(ido, bmat, n, which, nev, TOL, resid, ncv, v, n, - iparam, ipntr, workd, workl, lworkl, info) - end - if info[1] != 0 - throw(ARPACKException(info[1])) - end - - x = view(workd, ipntr[1]+zernm1) - y = view(workd, ipntr[2]+zernm1) - if mode == 1 # corresponds to dsdrv1, dndrv1 or zndrv1 - if ido[1] == 1 - matvecA!(y, x) - elseif ido[1] == 99 - break - else - throw(ARPACKException("unexpected behavior")) - end - elseif mode == 3 && bmat == "I" # corresponds to dsdrv2, dndrv2 or zndrv2 - if ido[1] == -1 || ido[1] == 1 - y[:] = solveSI(x) - elseif ido[1] == 99 - break - else - throw(ARPACKException("unexpected behavior")) - end - elseif mode == 2 # corresponds to dsdrv3, dndrv3 or zndrv3 - if ido[1] == -1 || ido[1] == 1 - matvecA!(y, x) - if sym - x[:] = y # overwrite as per Remark 5 in dsaupd.f - end - y[:] = solveSI(y) - elseif ido[1] == 2 - y[:] = matvecB(x) - elseif ido[1] == 99 - break - else - throw(ARPACKException("unexpected behavior")) - end - elseif mode == 3 && bmat == "G" # corresponds to dsdrv4, dndrv4 or zndrv4 - if ido[1] == -1 - y[:] = solveSI(matvecB(x)) - elseif ido[1] == 1 - y[:] = solveSI(view(workd,ipntr[3]+zernm1)) - elseif ido[1] == 2 - y[:] = matvecB(x) - elseif ido[1] == 99 - break - else - throw(ARPACKException("unexpected behavior")) - end - else - throw(ArgumentError("ARPACK mode ($mode) not yet supported")) - end - end - - return (resid, v, n, iparam, ipntr, workd, workl, lworkl, rwork, TOL) -end - -function eupd_wrapper(T, n::Integer, sym::Bool, cmplx::Bool, bmat::String, - nev::Integer, which::String, ritzvec::Bool, - TOL::Array, resid, ncv::Integer, v, ldv, sigma, iparam, ipntr, - workd, workl, lworkl, rwork) - howmny = "A" - select = Vector{BlasInt}(ncv) - info = zeros(BlasInt, 1) - - dmap = x->abs.(x) - if iparam[7] == 3 # shift-and-invert - dmap = x->abs.(1 ./ (x .- sigma)) - elseif which == "LR" || which == "LA" || which == "BE" - dmap = real - elseif which == "SR" || which == "SA" - dmap = x->-real(x) - elseif which == "LI" - dmap = imag - elseif which == "SI" - dmap = x->-imag(x) - end - - if cmplx - d = Vector{T}(nev+1) - sigmar = ones(T, 1)*sigma - workev = Vector{T}(2ncv) - neupd(ritzvec, howmny, select, d, v, ldv, sigmar, workev, - bmat, n, which, nev, TOL, resid, ncv, v, ldv, - iparam, ipntr, workd, workl, lworkl, rwork, info) - if info[1] != 0 - throw(ARPACKException(info[1])) - end - - p = sortperm(dmap(d[1:nev]), rev=true) - return ritzvec ? (d[p], v[1:n, p],iparam[5],iparam[3],iparam[9],resid) : (d[p],iparam[5],iparam[3],iparam[9],resid) - elseif sym - d = Vector{T}(nev) - sigmar = ones(T, 1)*sigma - seupd(ritzvec, howmny, select, d, v, ldv, sigmar, - bmat, n, which, nev, TOL, resid, ncv, v, ldv, - iparam, ipntr, workd, workl, lworkl, info) - if info[1] != 0 - throw(ARPACKException(info[1])) - end - - p = sortperm(dmap(d), rev=true) - return ritzvec ? (d[p], v[1:n, p],iparam[5],iparam[3],iparam[9],resid) : (d,iparam[5],iparam[3],iparam[9],resid) - else - dr = Vector{T}(nev+1) - di = Vector{T}(nev+1) - fill!(dr,NaN) - fill!(di,NaN) - sigmar = ones(T, 1)*real(sigma) - sigmai = ones(T, 1)*imag(sigma) - workev = Vector{T}(3*ncv) - neupd(ritzvec, howmny, select, dr, di, v, ldv, sigmar, sigmai, - workev, bmat, n, which, nev, TOL, resid, ncv, v, ldv, - iparam, ipntr, workd, workl, lworkl, info) - if info[1] != 0 - throw(ARPACKException(info[1])) - end - evec = complex.(Matrix{T}(n, nev+1), Matrix{T}(n, nev+1)) - - j = 1 - while j <= nev - if di[j] == 0 - evec[:,j] = v[:,j] - else # For complex conjugate pairs - evec[:,j] = v[:,j] + im*v[:,j+1] - evec[:,j+1] = v[:,j] - im*v[:,j+1] - j += 1 - end - j += 1 - end - if j == nev+1 && !isnan(di[j]) - if di[j] == 0 - evec[:,j] = v[:,j] - j += 1 - else - throw(ARPACKException("unexpected behavior")) - end - end - - d = complex.(dr, di) - - if j == nev+1 - p = sortperm(dmap(d[1:nev]), rev=true) - else - p = sortperm(dmap(d), rev=true) - p = p[1:nev] - end - - return ritzvec ? (d[p], evec[1:n, p],iparam[5],iparam[3],iparam[9],resid) : (d[p],iparam[5],iparam[3],iparam[9],resid) - end -end - -for (T, saupd_name, seupd_name, naupd_name, neupd_name) in - ((:Float64, :dsaupd_, :dseupd_, :dnaupd_, :dneupd_), - (:Float32, :ssaupd_, :sseupd_, :snaupd_, :sneupd_)) - @eval begin - function naupd(ido, bmat, n, evtype, nev, TOL::Array{$T}, resid::Array{$T}, ncv, v::Array{$T}, ldv, - iparam, ipntr, workd::Array{$T}, workl::Array{$T}, lworkl, info) - ccall(($(string(naupd_name)), :libarpack), Void, - (Ptr{BlasInt}, Ptr{UInt8}, Ptr{BlasInt}, Ptr{UInt8}, Ptr{BlasInt}, - Ptr{$T}, Ptr{$T}, Ptr{BlasInt}, Ptr{$T}, Ptr{BlasInt}, - Ptr{BlasInt}, Ptr{BlasInt}, Ptr{$T}, Ptr{$T}, Ptr{BlasInt}, Ptr{BlasInt}, Clong, Clong), - ido, bmat, &n, evtype, &nev, TOL, resid, &ncv, v, &ldv, - iparam, ipntr, workd, workl, &lworkl, info, sizeof(bmat), sizeof(evtype)) - end - - function neupd(rvec, howmny, select, dr, di, z, ldz, sigmar, sigmai, - workev::Array{$T}, bmat, n, evtype, nev, TOL::Array{$T}, resid::Array{$T}, ncv, v, ldv, - iparam, ipntr, workd::Array{$T}, workl::Array{$T}, lworkl, info) - ccall(($(string(neupd_name)), :libarpack), Void, - (Ptr{BlasInt}, Ptr{UInt8}, Ptr{BlasInt}, Ptr{$T}, Ptr{$T}, Ptr{$T}, - Ptr{BlasInt}, Ptr{$T}, Ptr{$T}, Ptr{$T}, Ptr{UInt8}, Ptr{BlasInt}, - Ptr{UInt8}, Ptr{BlasInt}, Ptr{$T}, Ptr{$T}, Ptr{BlasInt}, Ptr{$T}, - Ptr{BlasInt}, Ptr{BlasInt}, Ptr{BlasInt}, Ptr{$T}, Ptr{$T}, - Ptr{BlasInt}, Ptr{BlasInt}, Clong, Clong, Clong), - &rvec, howmny, select, dr, di, z, &ldz, sigmar, sigmai, - workev, bmat, &n, evtype, &nev, TOL, resid, &ncv, v, &ldv, - iparam, ipntr, workd, workl, &lworkl, info, - sizeof(howmny), sizeof(bmat), sizeof(evtype)) - end - - function saupd(ido, bmat, n, which, nev, TOL::Array{$T}, resid::Array{$T}, ncv, v::Array{$T}, ldv, - iparam, ipntr, workd::Array{$T}, workl::Array{$T}, lworkl, info) - ccall(($(string(saupd_name)), :libarpack), Void, - (Ptr{BlasInt}, Ptr{UInt8}, Ptr{BlasInt}, Ptr{UInt8}, Ptr{BlasInt}, - Ptr{$T}, Ptr{$T}, Ptr{BlasInt}, Ptr{$T}, Ptr{BlasInt}, - Ptr{BlasInt}, Ptr{BlasInt}, Ptr{$T}, Ptr{$T}, Ptr{BlasInt}, Ptr{BlasInt}, Clong, Clong), - ido, bmat, &n, which, &nev, TOL, resid, &ncv, v, &ldv, - iparam, ipntr, workd, workl, &lworkl, info, sizeof(bmat), sizeof(which)) - end - - function seupd(rvec, howmny, select, d, z, ldz, sigma, - bmat, n, evtype, nev, TOL::Array{$T}, resid::Array{$T}, ncv, v::Array{$T}, ldv, - iparam, ipntr, workd::Array{$T}, workl::Array{$T}, lworkl, info) - ccall(($(string(seupd_name)), :libarpack), Void, - (Ptr{BlasInt}, Ptr{UInt8}, Ptr{BlasInt}, Ptr{$T}, Ptr{$T}, Ptr{BlasInt}, Ptr{$T}, - Ptr{UInt8}, Ptr{BlasInt}, Ptr{UInt8}, Ptr{BlasInt}, - Ptr{$T}, Ptr{$T}, Ptr{BlasInt}, Ptr{$T}, Ptr{BlasInt}, Ptr{BlasInt}, - Ptr{BlasInt}, Ptr{$T}, Ptr{$T}, Ptr{BlasInt}, Ptr{BlasInt}, Clong, Clong, Clong), - &rvec, howmny, select, d, z, &ldz, sigma, - bmat, &n, evtype, &nev, TOL, resid, &ncv, v, &ldv, - iparam, ipntr, workd, workl, &lworkl, info, sizeof(howmny), sizeof(bmat), sizeof(evtype)) - end - end -end - -for (T, TR, naupd_name, neupd_name) in - ((:Complex128, :Float64, :znaupd_, :zneupd_), - (:Complex64, :Float32, :cnaupd_, :cneupd_)) - @eval begin - function naupd(ido, bmat, n, evtype, nev, TOL::Array{$TR}, resid::Array{$T}, ncv, v::Array{$T}, ldv, - iparam, ipntr, workd::Array{$T}, workl::Array{$T}, lworkl, - rwork::Array{$TR}, info) - ccall(($(string(naupd_name)), :libarpack), Void, - (Ptr{BlasInt}, Ptr{UInt8}, Ptr{BlasInt}, Ptr{UInt8}, Ptr{BlasInt}, - Ptr{$TR}, Ptr{$T}, Ptr{BlasInt}, Ptr{$T}, Ptr{BlasInt}, - Ptr{BlasInt}, Ptr{BlasInt}, Ptr{$T}, Ptr{$T}, Ptr{BlasInt}, - Ptr{$TR}, Ptr{BlasInt}), - ido, bmat, &n, evtype, &nev, TOL, resid, &ncv, v, &ldv, - iparam, ipntr, workd, workl, &lworkl, rwork, info) - end - - function neupd(rvec, howmny, select, d, z, ldz, sigma, workev::Array{$T}, - bmat, n, evtype, nev, TOL::Array{$TR}, resid::Array{$T}, ncv, v::Array{$T}, ldv, - iparam, ipntr, workd::Array{$T}, workl::Array{$T}, lworkl, - rwork::Array{$TR}, info) - ccall(($(string(neupd_name)), :libarpack), Void, - (Ptr{BlasInt}, Ptr{UInt8}, Ptr{BlasInt}, Ptr{$T}, Ptr{$T}, Ptr{BlasInt}, - Ptr{$T}, Ptr{$T}, Ptr{UInt8}, Ptr{BlasInt}, Ptr{UInt8}, Ptr{BlasInt}, - Ptr{$TR}, Ptr{$T}, Ptr{BlasInt}, Ptr{$T}, Ptr{BlasInt}, Ptr{BlasInt}, - Ptr{BlasInt}, Ptr{$T}, Ptr{$T}, Ptr{BlasInt}, Ptr{$TR}, Ptr{BlasInt}), - &rvec, howmny, select, d, z, &ldz, sigma, workev, - bmat, &n, evtype, &nev, TOL, resid, &ncv, v, &ldv, - iparam, ipntr, workd, workl, &lworkl, rwork, info) - end - end -end - -end # module ARPACK diff --git a/julia-0.6.3/share/julia/base/linalg/bidiag.jl b/julia-0.6.3/share/julia/base/linalg/bidiag.jl deleted file mode 100644 index 9e9af0b..0000000 --- a/julia-0.6.3/share/julia/base/linalg/bidiag.jl +++ /dev/null @@ -1,641 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -# Bidiagonal matrices -mutable struct Bidiagonal{T} <: AbstractMatrix{T} - dv::Vector{T} # diagonal - ev::Vector{T} # sub/super diagonal - isupper::Bool # is upper bidiagonal (true) or lower (false) - function Bidiagonal{T}(dv::Vector{T}, ev::Vector{T}, isupper::Bool) where T - if length(ev) != length(dv)-1 - throw(DimensionMismatch("length of diagonal vector is $(length(dv)), length of off-diagonal vector is $(length(ev))")) - end - new(dv, ev, isupper) - end -end -""" - Bidiagonal(dv, ev, isupper::Bool) - -Constructs an upper (`isupper=true`) or lower (`isupper=false`) bidiagonal matrix using the -given diagonal (`dv`) and off-diagonal (`ev`) vectors. The result is of type `Bidiagonal` -and provides efficient specialized linear solvers, but may be converted into a regular -matrix with [`convert(Array, _)`](@ref) (or `Array(_)` for short). `ev`'s length -must be one less than the length of `dv`. - -# Example - -```jldoctest -julia> dv = [1; 2; 3; 4] -4-element Array{Int64,1}: - 1 - 2 - 3 - 4 - -julia> ev = [7; 8; 9] -3-element Array{Int64,1}: - 7 - 8 - 9 - -julia> Bu = Bidiagonal(dv, ev, true) # ev is on the first superdiagonal -4×4 Bidiagonal{Int64}: - 1 7 ⋅ ⋅ - ⋅ 2 8 ⋅ - ⋅ ⋅ 3 9 - ⋅ ⋅ ⋅ 4 - -julia> Bl = Bidiagonal(dv, ev, false) # ev is on the first subdiagonal -4×4 Bidiagonal{Int64}: - 1 ⋅ ⋅ ⋅ - 7 2 ⋅ ⋅ - ⋅ 8 3 ⋅ - ⋅ ⋅ 9 4 -``` -""" -Bidiagonal(dv::AbstractVector{T}, ev::AbstractVector{T}, isupper::Bool) where {T} = Bidiagonal{T}(collect(dv), collect(ev), isupper) -Bidiagonal(dv::AbstractVector, ev::AbstractVector) = throw(ArgumentError("did you want an upper or lower Bidiagonal? Try again with an additional true (upper) or false (lower) argument.")) - -""" - Bidiagonal(dv, ev, uplo::Char) - -Constructs an upper (`uplo='U'`) or lower (`uplo='L'`) bidiagonal matrix using the -given diagonal (`dv`) and off-diagonal (`ev`) vectors. The result is of type `Bidiagonal` -and provides efficient specialized linear solvers, but may be converted into a regular -matrix with [`convert(Array, _)`](@ref) (or `Array(_)` for short). `ev`'s -length must be one less than the length of `dv`. - -# Example - -```jldoctest -julia> dv = [1; 2; 3; 4] -4-element Array{Int64,1}: - 1 - 2 - 3 - 4 - -julia> ev = [7; 8; 9] -3-element Array{Int64,1}: - 7 - 8 - 9 - -julia> Bu = Bidiagonal(dv, ev, 'U') #e is on the first superdiagonal -4×4 Bidiagonal{Int64}: - 1 7 ⋅ ⋅ - ⋅ 2 8 ⋅ - ⋅ ⋅ 3 9 - ⋅ ⋅ ⋅ 4 - -julia> Bl = Bidiagonal(dv, ev, 'L') #e is on the first subdiagonal -4×4 Bidiagonal{Int64}: - 1 ⋅ ⋅ ⋅ - 7 2 ⋅ ⋅ - ⋅ 8 3 ⋅ - ⋅ ⋅ 9 4 -``` -""" -#Convert from BLAS uplo flag to boolean internal -function Bidiagonal(dv::AbstractVector, ev::AbstractVector, uplo::Char) - if uplo === 'U' - isupper = true - elseif uplo === 'L' - isupper = false - else - throw(ArgumentError("Bidiagonal uplo argument must be upper 'U' or lower 'L', got $(repr(uplo))")) - end - Bidiagonal(collect(dv), collect(ev), isupper) -end -function Bidiagonal(dv::AbstractVector{Td}, ev::AbstractVector{Te}, isupper::Bool) where {Td,Te} - T = promote_type(Td,Te) - Bidiagonal(convert(Vector{T}, dv), convert(Vector{T}, ev), isupper) -end - -""" - Bidiagonal(A, isupper::Bool) - -Construct a `Bidiagonal` matrix from the main diagonal of `A` and -its first super- (if `isupper=true`) or sub-diagonal (if `isupper=false`). - -# Example - -```jldoctest -julia> A = [1 1 1 1; 2 2 2 2; 3 3 3 3; 4 4 4 4] -4×4 Array{Int64,2}: - 1 1 1 1 - 2 2 2 2 - 3 3 3 3 - 4 4 4 4 - -julia> Bidiagonal(A, true) #contains the main diagonal and first superdiagonal of A -4×4 Bidiagonal{Int64}: - 1 1 ⋅ ⋅ - ⋅ 2 2 ⋅ - ⋅ ⋅ 3 3 - ⋅ ⋅ ⋅ 4 - -julia> Bidiagonal(A, false) #contains the main diagonal and first subdiagonal of A -4×4 Bidiagonal{Int64}: - 1 ⋅ ⋅ ⋅ - 2 2 ⋅ ⋅ - ⋅ 3 3 ⋅ - ⋅ ⋅ 4 4 -``` -""" -Bidiagonal(A::AbstractMatrix, isupper::Bool)=Bidiagonal(diag(A), diag(A, isupper?1:-1), isupper) - -function getindex(A::Bidiagonal{T}, i::Integer, j::Integer) where T - if !((1 <= i <= size(A,2)) && (1 <= j <= size(A,2))) - throw(BoundsError(A,(i,j))) - end - if i == j - return A.dv[i] - elseif (istriu(A) && (i == j - 1)) || (istril(A) && (i == j + 1)) - return A.ev[min(i,j)] - else - return zero(T) - end -end - -function setindex!(A::Bidiagonal, x, i::Integer, j::Integer) - @boundscheck checkbounds(A, i, j) - if i == j - @inbounds A.dv[i] = x - elseif istriu(A) && (i == j - 1) - @inbounds A.ev[i] = x - elseif istril(A) && (i == j + 1) - @inbounds A.ev[j] = x - elseif !iszero(x) - throw(ArgumentError(string("cannot set entry ($i, $j) off the ", - "$(istriu(A) ? "upper" : "lower") bidiagonal band to a nonzero value ($x)"))) - end - return x -end - -## structured matrix methods ## -function Base.replace_in_print_matrix(A::Bidiagonal,i::Integer,j::Integer,s::AbstractString) - if A.isupper - i==j || i==j-1 ? s : Base.replace_with_centered_mark(s) - else - i==j || i==j+1 ? s : Base.replace_with_centered_mark(s) - end -end - -#Converting from Bidiagonal to dense Matrix -function convert(::Type{Matrix{T}}, A::Bidiagonal) where T - n = size(A, 1) - B = zeros(T, n, n) - for i = 1:n - 1 - B[i,i] = A.dv[i] - if A.isupper - B[i, i + 1] = A.ev[i] - else - B[i + 1, i] = A.ev[i] - end - end - B[n,n] = A.dv[n] - return B -end -convert(::Type{Matrix}, A::Bidiagonal{T}) where {T} = convert(Matrix{T}, A) -convert(::Type{Array}, A::Bidiagonal) = convert(Matrix, A) -full(A::Bidiagonal) = convert(Array, A) -promote_rule(::Type{Matrix{T}}, ::Type{Bidiagonal{S}}) where {T,S} = Matrix{promote_type(T,S)} - -#Converting from Bidiagonal to Tridiagonal -Tridiagonal(M::Bidiagonal{T}) where {T} = convert(Tridiagonal{T}, M) -function convert(::Type{Tridiagonal{T}}, A::Bidiagonal) where T - z = zeros(T, size(A)[1]-1) - A.isupper ? Tridiagonal(z, convert(Vector{T},A.dv), convert(Vector{T},A.ev)) : Tridiagonal(convert(Vector{T},A.ev), convert(Vector{T},A.dv), z) -end -promote_rule(::Type{Tridiagonal{T}}, ::Type{Bidiagonal{S}}) where {T,S} = Tridiagonal{promote_type(T,S)} - -# No-op for trivial conversion Bidiagonal{T} -> Bidiagonal{T} -convert(::Type{Bidiagonal{T}}, A::Bidiagonal{T}) where {T} = A -# Convert Bidiagonal to Bidiagonal{T} by constructing a new instance with converted elements -convert(::Type{Bidiagonal{T}}, A::Bidiagonal) where {T} = Bidiagonal(convert(Vector{T}, A.dv), convert(Vector{T}, A.ev), A.isupper) -# When asked to convert Bidiagonal to AbstractMatrix{T}, preserve structure by converting to Bidiagonal{T} <: AbstractMatrix{T} -convert(::Type{AbstractMatrix{T}}, A::Bidiagonal) where {T} = convert(Bidiagonal{T}, A) - -broadcast(::typeof(big), B::Bidiagonal) = Bidiagonal(big.(B.dv), big.(B.ev), B.isupper) - -similar(B::Bidiagonal, ::Type{T}) where {T} = Bidiagonal{T}(similar(B.dv, T), similar(B.ev, T), B.isupper) - -################### -# LAPACK routines # -################### - -#Singular values -svdvals!(M::Bidiagonal{<:BlasReal}) = LAPACK.bdsdc!(M.isupper ? 'U' : 'L', 'N', M.dv, M.ev)[1] -function svdfact!(M::Bidiagonal{<:BlasReal}; thin::Bool=true) - d, e, U, Vt, Q, iQ = LAPACK.bdsdc!(M.isupper ? 'U' : 'L', 'I', M.dv, M.ev) - SVD(U, d, Vt) -end -svdfact(M::Bidiagonal; thin::Bool=true) = svdfact!(copy(M),thin=thin) - -#################### -# Generic routines # -#################### - -function show(io::IO, M::Bidiagonal) - # TODO: make this readable and one-line - println(io, summary(M), ":") - print(io, " diag:") - print_matrix(io, (M.dv)') - print(io, M.isupper?"\n super:":"\n sub:") - print_matrix(io, (M.ev)') -end - -size(M::Bidiagonal) = (length(M.dv), length(M.dv)) -function size(M::Bidiagonal, d::Integer) - if d < 1 - throw(ArgumentError("dimension must be ≥ 1, got $d")) - elseif d <= 2 - return length(M.dv) - else - return 1 - end -end - -#Elementary operations -broadcast(::typeof(abs), M::Bidiagonal) = Bidiagonal(abs.(M.dv), abs.(M.ev), abs.(M.isupper)) -broadcast(::typeof(round), M::Bidiagonal) = Bidiagonal(round.(M.dv), round.(M.ev), M.isupper) -broadcast(::typeof(trunc), M::Bidiagonal) = Bidiagonal(trunc.(M.dv), trunc.(M.ev), M.isupper) -broadcast(::typeof(floor), M::Bidiagonal) = Bidiagonal(floor.(M.dv), floor.(M.ev), M.isupper) -broadcast(::typeof(ceil), M::Bidiagonal) = Bidiagonal(ceil.(M.dv), ceil.(M.ev), M.isupper) -for func in (:conj, :copy, :real, :imag) - @eval ($func)(M::Bidiagonal) = Bidiagonal(($func)(M.dv), ($func)(M.ev), M.isupper) -end -broadcast(::typeof(round), ::Type{T}, M::Bidiagonal) where {T<:Integer} = Bidiagonal(round.(T, M.dv), round.(T, M.ev), M.isupper) -broadcast(::typeof(trunc), ::Type{T}, M::Bidiagonal) where {T<:Integer} = Bidiagonal(trunc.(T, M.dv), trunc.(T, M.ev), M.isupper) -broadcast(::typeof(floor), ::Type{T}, M::Bidiagonal) where {T<:Integer} = Bidiagonal(floor.(T, M.dv), floor.(T, M.ev), M.isupper) -broadcast(::typeof(ceil), ::Type{T}, M::Bidiagonal) where {T<:Integer} = Bidiagonal(ceil.(T, M.dv), ceil.(T, M.ev), M.isupper) - -transpose(M::Bidiagonal) = Bidiagonal(M.dv, M.ev, !M.isupper) -ctranspose(M::Bidiagonal) = Bidiagonal(conj(M.dv), conj(M.ev), !M.isupper) - -istriu(M::Bidiagonal) = M.isupper || iszero(M.ev) -istril(M::Bidiagonal) = !M.isupper || iszero(M.ev) - -function tril!(M::Bidiagonal, k::Integer=0) - n = length(M.dv) - if abs(k) > n - throw(ArgumentError("requested diagonal, $k, out of bounds in matrix of size ($n,$n)")) - elseif M.isupper && k < 0 - fill!(M.dv,0) - fill!(M.ev,0) - elseif k < -1 - fill!(M.dv,0) - fill!(M.ev,0) - elseif M.isupper && k == 0 - fill!(M.ev,0) - elseif !M.isupper && k == -1 - fill!(M.dv,0) - end - return M -end - -function triu!(M::Bidiagonal, k::Integer=0) - n = length(M.dv) - if abs(k) > n - throw(ArgumentError("requested diagonal, $k, out of bounds in matrix of size ($n,$n)")) - elseif !M.isupper && k > 0 - fill!(M.dv,0) - fill!(M.ev,0) - elseif k > 1 - fill!(M.dv,0) - fill!(M.ev,0) - elseif !M.isupper && k == 0 - fill!(M.ev,0) - elseif M.isupper && k == 1 - fill!(M.dv,0) - end - return M -end - -function diag(M::Bidiagonal{T}, n::Integer=0) where T - if n == 0 - return M.dv - elseif n == 1 - return M.isupper ? M.ev : zeros(T, size(M,1)-1) - elseif n == -1 - return M.isupper ? zeros(T, size(M,1)-1) : M.ev - elseif -size(M,1) < n < size(M,1) - return zeros(T, size(M,1)-abs(n)) - else - throw(ArgumentError("matrix size is $(size(M)), n is $n")) - end -end - -function +(A::Bidiagonal, B::Bidiagonal) - if A.isupper == B.isupper - Bidiagonal(A.dv+B.dv, A.ev+B.ev, A.isupper) - else - Tridiagonal((A.isupper ? (B.ev,A.dv+B.dv,A.ev) : (A.ev,A.dv+B.dv,B.ev))...) - end -end - -function -(A::Bidiagonal, B::Bidiagonal) - if A.isupper == B.isupper - Bidiagonal(A.dv-B.dv, A.ev-B.ev, A.isupper) - else - Tridiagonal((A.isupper ? (-B.ev,A.dv-B.dv,A.ev) : (A.ev,A.dv-B.dv,-B.ev))...) - end -end - --(A::Bidiagonal)=Bidiagonal(-A.dv,-A.ev,A.isupper) -*(A::Bidiagonal, B::Number) = Bidiagonal(A.dv*B, A.ev*B, A.isupper) -*(B::Number, A::Bidiagonal) = A*B -/(A::Bidiagonal, B::Number) = Bidiagonal(A.dv/B, A.ev/B, A.isupper) -==(A::Bidiagonal, B::Bidiagonal) = (A.dv==B.dv) && (A.ev==B.ev) && (A.isupper==B.isupper) - -const BiTriSym = Union{Bidiagonal,Tridiagonal,SymTridiagonal} -const BiTri = Union{Bidiagonal,Tridiagonal} -A_mul_B!(C::AbstractMatrix, A::SymTridiagonal, B::BiTriSym) = A_mul_B_td!(C, A, B) -A_mul_B!(C::AbstractMatrix, A::BiTri, B::BiTriSym) = A_mul_B_td!(C, A, B) -A_mul_B!(C::AbstractMatrix, A::BiTriSym, B::BiTriSym) = A_mul_B_td!(C, A, B) -A_mul_B!(C::AbstractMatrix, A::AbstractTriangular, B::BiTriSym) = A_mul_B_td!(C, A, B) -A_mul_B!(C::AbstractMatrix, A::AbstractMatrix, B::BiTriSym) = A_mul_B_td!(C, A, B) -A_mul_B!(C::AbstractVector, A::BiTri, B::AbstractVector) = A_mul_B_td!(C, A, B) -A_mul_B!(C::AbstractMatrix, A::BiTri, B::AbstractVecOrMat) = A_mul_B_td!(C, A, B) -A_mul_B!(C::AbstractVecOrMat, A::BiTri, B::AbstractVecOrMat) = A_mul_B_td!(C, A, B) - -\(::Diagonal, ::RowVector) = throw(DimensionMismatch("Cannot left-divide matrix by transposed vector")) -\(::Bidiagonal, ::RowVector) = throw(DimensionMismatch("Cannot left-divide matrix by transposed vector")) -\(::Bidiagonal{<:Number}, ::RowVector{<:Number}) = throw(DimensionMismatch("Cannot left-divide matrix by transposed vector")) - -At_ldiv_B(::Bidiagonal, ::RowVector) = throw(DimensionMismatch("Cannot left-divide matrix by transposed vector")) -At_ldiv_B(::Bidiagonal{<:Number}, ::RowVector{<:Number}) = throw(DimensionMismatch("Cannot left-divide matrix by transposed vector")) - -Ac_ldiv_B(::Bidiagonal, ::RowVector) = throw(DimensionMismatch("Cannot left-divide matrix by transposed vector")) -Ac_ldiv_B(::Bidiagonal{<:Number}, ::RowVector{<:Number}) = throw(DimensionMismatch("Cannot left-divide matrix by transposed vector")) - -function check_A_mul_B!_sizes(C, A, B) - nA, mA = size(A) - nB, mB = size(B) - nC, mC = size(C) - if nA != nC - throw(DimensionMismatch("sizes size(A)=$(size(A)) and size(C) = $(size(C)) must match at first entry.")) - elseif mA != nB - throw(DimensionMismatch("second entry of size(A)=$(size(A)) and first entry of size(B) = $(size(B)) must match.")) - elseif mB != mC - throw(DimensionMismatch("sizes size(B)=$(size(B)) and size(C) = $(size(C)) must match at first second entry.")) - end -end - -function A_mul_B_td!(C::AbstractMatrix, A::BiTriSym, B::BiTriSym) - check_A_mul_B!_sizes(C, A, B) - n = size(A,1) - n <= 3 && return A_mul_B!(C, Array(A), Array(B)) - fill!(C, zero(eltype(C))) - Al = diag(A, -1) - Ad = diag(A, 0) - Au = diag(A, 1) - Bl = diag(B, -1) - Bd = diag(B, 0) - Bu = diag(B, 1) - @inbounds begin - # first row of C - C[1,1] = A[1,1]*B[1,1] + A[1, 2]*B[2, 1] - C[1,2] = A[1,1]*B[1,2] + A[1,2]*B[2,2] - C[1,3] = A[1,2]*B[2,3] - # second row of C - C[2,1] = A[2,1]*B[1,1] + A[2,2]*B[2,1] - C[2,2] = A[2,1]*B[1,2] + A[2,2]*B[2,2] + A[2,3]*B[3,2] - C[2,3] = A[2,2]*B[2,3] + A[2,3]*B[3,3] - C[2,4] = A[2,3]*B[3,4] - for j in 3:n-2 - Ajj₋1 = Al[j-1] - Ajj = Ad[j] - Ajj₊1 = Au[j] - Bj₋1j₋2 = Bl[j-2] - Bj₋1j₋1 = Bd[j-1] - Bj₋1j = Bu[j-1] - Bjj₋1 = Bl[j-1] - Bjj = Bd[j] - Bjj₊1 = Bu[j] - Bj₊1j = Bl[j] - Bj₊1j₊1 = Bd[j+1] - Bj₊1j₊2 = Bu[j+1] - C[j,j-2] = Ajj₋1*Bj₋1j₋2 - C[j, j-1] = Ajj₋1*Bj₋1j₋1 + Ajj*Bjj₋1 - C[j, j ] = Ajj₋1*Bj₋1j + Ajj*Bjj + Ajj₊1*Bj₊1j - C[j, j+1] = Ajj *Bjj₊1 + Ajj₊1*Bj₊1j₊1 - C[j, j+2] = Ajj₊1*Bj₊1j₊2 - end - # row before last of C - C[n-1,n-3] = A[n-1,n-2]*B[n-2,n-3] - C[n-1,n-2] = A[n-1,n-1]*B[n-1,n-2] + A[n-1,n-2]*B[n-2,n-2] - C[n-1,n-1] = A[n-1,n-2]*B[n-2,n-1] + A[n-1,n-1]*B[n-1,n-1] + A[n-1,n]*B[n,n-1] - C[n-1,n ] = A[n-1,n-1]*B[n-1,n ] + A[n-1, n]*B[n ,n ] - # last row of C - C[n,n-2] = A[n,n-1]*B[n-1,n-2] - C[n,n-1] = A[n,n-1]*B[n-1,n-1] + A[n,n]*B[n,n-1] - C[n,n ] = A[n,n-1]*B[n-1,n ] + A[n,n]*B[n,n ] - end # inbounds - C -end - -function A_mul_B_td!(C::AbstractVecOrMat, A::BiTriSym, B::AbstractVecOrMat) - nA = size(A,1) - nB = size(B,2) - if !(size(C,1) == size(B,1) == nA) - throw(DimensionMismatch("A has first dimension $nA, B has $(size(B,1)), C has $(size(C,1)) but all must match")) - end - if size(C,2) != nB - throw(DimensionMismatch("A has second dimension $nA, B has $(size(B,2)), C has $(size(C,2)) but all must match")) - end - nA <= 3 && return A_mul_B!(C, Array(A), Array(B)) - l = diag(A, -1) - d = diag(A, 0) - u = diag(A, 1) - @inbounds begin - for j = 1:nB - b₀, b₊ = B[1, j], B[2, j] - C[1, j] = d[1]*b₀ + u[1]*b₊ - for i = 2:nA - 1 - b₋, b₀, b₊ = b₀, b₊, B[i + 1, j] - C[i, j] = l[i - 1]*b₋ + d[i]*b₀ + u[i]*b₊ - end - C[nA, j] = l[nA - 1]*b₀ + d[nA]*b₊ - end - end - C -end - -function A_mul_B_td!(C::AbstractMatrix, A::AbstractMatrix, B::BiTriSym) - check_A_mul_B!_sizes(C, A, B) - n = size(A,1) - n <= 3 && return A_mul_B!(C, Array(A), Array(B)) - m = size(B,2) - Bl = diag(B, -1) - Bd = diag(B, 0) - Bu = diag(B, 1) - @inbounds begin - # first and last column of C - B11 = Bd[1] - B21 = Bl[1] - Bmm = Bd[m] - Bm₋1m = Bu[m-1] - for i in 1:n - C[i, 1] = A[i,1] * B11 + A[i, 2] * B21 - C[i, m] = A[i, m-1] * Bm₋1m + A[i, m] * Bmm - end - # middle columns of C - for j = 2:m-1 - Bj₋1j = Bu[j-1] - Bjj = Bd[j] - Bj₊1j = Bl[j] - for i = 1:n - C[i, j] = A[i, j-1] * Bj₋1j + A[i, j]*Bjj + A[i, j+1] * Bj₊1j - end - end - end # inbounds - C -end - -const SpecialMatrix = Union{Bidiagonal,SymTridiagonal,Tridiagonal} -# to avoid ambiguity warning, but shouldn't be necessary -*(A::AbstractTriangular, B::SpecialMatrix) = Array(A) * Array(B) -*(A::SpecialMatrix, B::SpecialMatrix) = Array(A) * Array(B) - -#Generic multiplication -for func in (:*, :Ac_mul_B, :A_mul_Bc, :/, :A_rdiv_Bc) - @eval ($func)(A::Bidiagonal{T}, B::AbstractVector{T}) where {T} = ($func)(Array(A), B) -end - -#Linear solvers -A_ldiv_B!(A::Union{Bidiagonal, AbstractTriangular}, b::AbstractVector) = naivesub!(A, b) -At_ldiv_B!(A::Bidiagonal, b::AbstractVector) = A_ldiv_B!(transpose(A), b) -Ac_ldiv_B!(A::Bidiagonal, b::AbstractVector) = A_ldiv_B!(ctranspose(A), b) -function A_ldiv_B!(A::Union{Bidiagonal,AbstractTriangular}, B::AbstractMatrix) - nA,mA = size(A) - tmp = similar(B,size(B,1)) - n = size(B, 1) - if nA != n - throw(DimensionMismatch("size of A is ($nA,$mA), corresponding dimension of B is $n")) - end - for i = 1:size(B,2) - copy!(tmp, 1, B, (i - 1)*n + 1, n) - A_ldiv_B!(A, tmp) - copy!(B, (i - 1)*n + 1, tmp, 1, n) # Modify this when array view are implemented. - end - B -end -for func in (:Ac_ldiv_B!, :At_ldiv_B!) - @eval function ($func)(A::Union{Bidiagonal,AbstractTriangular}, B::AbstractMatrix) - nA,mA = size(A) - tmp = similar(B,size(B,1)) - n = size(B, 1) - if mA != n - throw(DimensionMismatch("size of A' is ($mA,$nA), corresponding dimension of B is $n")) - end - for i = 1:size(B,2) - copy!(tmp, 1, B, (i - 1)*n + 1, n) - ($func)(A, tmp) - copy!(B, (i - 1)*n + 1, tmp, 1, n) # Modify this when array view are implemented. - end - B - end -end -#Generic solver using naive substitution -function naivesub!(A::Bidiagonal{T}, b::AbstractVector, x::AbstractVector = b) where T - N = size(A, 2) - if N != length(b) || N != length(x) - throw(DimensionMismatch("second dimension of A, $N, does not match one of the lengths of x, $(length(x)), or b, $(length(b))")) - end - if !A.isupper #do forward substitution - for j = 1:N - x[j] = b[j] - j > 1 && (x[j] -= A.ev[j-1] * x[j-1]) - x[j] /= A.dv[j] == zero(T) ? throw(SingularException(j)) : A.dv[j] - end - else #do backward substitution - for j = N:-1:1 - x[j] = b[j] - j < N && (x[j] -= A.ev[j] * x[j+1]) - x[j] /= A.dv[j] == zero(T) ? throw(SingularException(j)) : A.dv[j] - end - end - x -end - -### Generic promotion methods and fallbacks -for (f,g) in ((:\, :A_ldiv_B!), (:At_ldiv_B, :At_ldiv_B!), (:Ac_ldiv_B, :Ac_ldiv_B!)) - @eval begin - function ($f)(A::Bidiagonal{TA}, B::AbstractVecOrMat{TB}) where {TA<:Number,TB<:Number} - TAB = typeof((zero(TA)*zero(TB) + zero(TA)*zero(TB))/one(TA)) - ($g)(convert(AbstractArray{TAB}, A), copy_oftype(B, TAB)) - end - ($f)(A::Bidiagonal, B::AbstractVecOrMat) = ($g)(A, copy(B)) - end -end - -factorize(A::Bidiagonal) = A - -# Eigensystems -eigvals(M::Bidiagonal) = M.dv -function eigvecs(M::Bidiagonal{T}) where T - n = length(M.dv) - Q = Matrix{T}(n,n) - blks = [0; find(x -> x == 0, M.ev); n] - v = zeros(T, n) - if M.isupper - for idx_block = 1:length(blks) - 1, i = blks[idx_block] + 1:blks[idx_block + 1] #index of eigenvector - fill!(v, zero(T)) - v[blks[idx_block] + 1] = one(T) - for j = blks[idx_block] + 1:i - 1 #Starting from j=i, eigenvector elements will be 0 - v[j+1] = (M.dv[i] - M.dv[j])/M.ev[j] * v[j] - end - c = norm(v) - for j = 1:n - Q[j, i] = v[j] / c - end - end - else - for idx_block = 1:length(blks) - 1, i = blks[idx_block + 1]:-1:blks[idx_block] + 1 #index of eigenvector - fill!(v, zero(T)) - v[blks[idx_block+1]] = one(T) - for j = (blks[idx_block+1] - 1):-1:max(1, (i - 1)) #Starting from j=i, eigenvector elements will be 0 - v[j] = (M.dv[i] - M.dv[j+1])/M.ev[j] * v[j+1] - end - c = norm(v) - for j = 1:n - Q[j, i] = v[j] / c - end - end - end - Q #Actually Triangular -end -eigfact(M::Bidiagonal) = Eigen(eigvals(M), eigvecs(M)) - -# fill! methods -_valuefields(::Type{<:Diagonal}) = [:diag] -_valuefields(::Type{<:Bidiagonal}) = [:dv, :ev] -_valuefields(::Type{<:Tridiagonal}) = [:dl, :d, :du] -_valuefields(::Type{<:SymTridiagonal}) = [:dv, :ev] -_valuefields(::Type{<:AbstractTriangular}) = [:data] - -const SpecialArrays = Union{Diagonal,Bidiagonal,Tridiagonal,SymTridiagonal,AbstractTriangular} - -@generated function fillslots!(A::SpecialArrays, x) - ex = :(xT = convert(eltype(A), x)) - for field in _valuefields(A) - ex = :($ex; fill!(A.$field, xT)) - end - :($ex;return A) -end - -# for historical reasons: -fill!(a::AbstractTriangular, x) = fillslots!(a, x) -fill!(D::Diagonal, x) = fillslots!(D, x) - -_small_enough(A::Bidiagonal) = size(A, 1) <= 1 -_small_enough(A::Tridiagonal) = size(A, 1) <= 2 -_small_enough(A::SymTridiagonal) = size(A, 1) <= 2 - -function fill!(A::Union{Bidiagonal,Tridiagonal,SymTridiagonal}, x) - xT = convert(eltype(A), x) - (xT == zero(eltype(A)) || _small_enough(A)) && return fillslots!(A, xT) - throw(ArgumentError("array A of type $(typeof(A)) and size $(size(A)) can - not be filled with x=$x, since some of its entries are constrained.")) -end diff --git a/julia-0.6.3/share/julia/base/linalg/bitarray.jl b/julia-0.6.3/share/julia/base/linalg/bitarray.jl deleted file mode 100644 index 375f7ad..0000000 --- a/julia-0.6.3/share/julia/base/linalg/bitarray.jl +++ /dev/null @@ -1,298 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -function dot(x::BitVector, y::BitVector) - # simplest way to mimic Array dot behavior - length(x) == length(y) || throw(DimensionMismatch()) - s = 0 - xc = x.chunks - yc = y.chunks - @inbounds for i = 1:length(xc) - s += count_ones(xc[i] & yc[i]) - end - s -end - -## slower than the unpacked version, which is MUCH slower -# than blas'd (this one saves storage though, keeping it commented -# just in case) -#function aTb(A::BitMatrix, B::BitMatrix) - #(mA, nA) = size(A) - #(mB, nB) = size(B) - #C = falses(nA, nB) - #if mA != mB; throw(DimensionMismatch()) end - #if mA == 0; return C; end - #col_ch = num_bit_chunks(mA) - ## TODO: avoid using aux chunks and copy (?) - #aux_chunksA = zeros(UInt64, col_ch) - #aux_chunksB = [zeros(UInt64, col_ch) for j=1:nB] - #for j = 1:nB - #Base.copy_chunks!(aux_chunksB[j], 1, B.chunks, (j-1)*mA+1, mA) - #end - #for i = 1:nA - #Base.copy_chunks!(aux_chunksA, 1, A.chunks, (i-1)*mA+1, mA) - #for j = 1:nB - #for k = 1:col_ch - ## TODO: improve - #C[i, j] += count_ones(aux_chunksA[k] & aux_chunksB[j][k]) - #end - #end - #end - #C -#end - -#aCb{T, S}(A::BitMatrix{T}, B::BitMatrix{S}) = aTb(A, B) - -function triu(B::BitMatrix, k::Integer=0) - m,n = size(B) - A = falses(m,n) - Ac = A.chunks - Bc = B.chunks - for i = max(k+1,1):n - j = clamp((i - 1) * m + 1, 1, i * m) - Base.copy_chunks!(Ac, j, Bc, j, min(i-k, m)) - end - A -end - -function tril(B::BitMatrix, k::Integer=0) - m,n = size(B) - A = falses(m, n) - Ac = A.chunks - Bc = B.chunks - for i = 1:min(n, m+k) - j = clamp((i - 1) * m + i - k, 1, i * m) - Base.copy_chunks!(Ac, j, Bc, j, max(m-i+k+1, 0)) - end - A -end - -## diff and gradient - -# TODO: this could be improved (is it worth it?) -gradient(F::BitVector) = gradient(Array(F)) -gradient(F::BitVector, h::Real) = gradient(Array(F), h) -gradient(F::Vector, h::BitVector) = gradient(F, Array(h)) -gradient(F::BitVector, h::Vector) = gradient(Array(F), h) -gradient(F::BitVector, h::BitVector) = gradient(Array(F), Array(h)) - -## diag and related - -function diag(B::BitMatrix) - n = minimum(size(B)) - v = similar(B, n) - for i = 1:n - v[i] = B[i,i] - end - v -end - -function diagm(v::Union{BitVector,BitMatrix}) - isa(v, BitMatrix) && size(v,1)==1 || size(v,2)==1 || throw(DimensionMismatch()) - n = length(v) - a = falses(n, n) - for i=1:n - a[i,i] = v[i] - end - a -end - -## norm and rank - -svd(A::BitMatrix) = svd(float(A)) -qr(A::BitMatrix) = qr(float(A)) - -## kron - -function kron(a::BitVector, b::BitVector) - m = length(a) - n = length(b) - R = falses(n * m) - Rc = R.chunks - bc = b.chunks - for j = 1:m - a[j] && Base.copy_chunks!(Rc, (j-1)*n+1, bc, 1, n) - end - R -end - -function kron(a::BitMatrix, b::BitMatrix) - mA,nA = size(a) - mB,nB = size(b) - R = falses(mA*mB, nA*nB) - - for i = 1:mA - ri = (1:mB)+(i-1)*mB - for j = 1:nA - if a[i,j] - rj = (1:nB)+(j-1)*nB - R[ri,rj] = b - end - end - end - R -end - -## Structure query functions - -issymmetric(A::BitMatrix) = size(A, 1)==size(A, 2) && countnz(A - A.')==0 -ishermitian(A::BitMatrix) = issymmetric(A) - -function nonzero_chunks(chunks::Vector{UInt64}, pos0::Int, pos1::Int) - k0, l0 = Base.get_chunks_id(pos0) - k1, l1 = Base.get_chunks_id(pos1) - - delta_k = k1 - k0 - - z = UInt64(0) - u = ~z - if delta_k == 0 - msk_0 = (u << l0) & ~(u << l1 << 1) - else - msk_0 = (u << l0) - msk_1 = ~(u << l1 << 1) - end - - @inbounds begin - (chunks[k0] & msk_0) == z || return true - delta_k == 0 && return false - for i = k0 + 1 : k1 - 1 - chunks[i] == z || return true - end - (chunks[k1] & msk_1)==z || return true - end - return false -end - -function istriu(A::BitMatrix) - m, n = size(A) - for j = 1:min(n,m-1) - stride = (j-1) * m - nonzero_chunks(A.chunks, stride+j+1, stride+m) && return false - end - return true -end - -function istril(A::BitMatrix) - m, n = size(A) - (m == 0 || n == 0) && return true - for j = 2:n - stride = (j-1) * m - nonzero_chunks(A.chunks, stride+1, stride+min(j-1,m)) && return false - end - return true -end - -function findmax(a::BitArray) - isempty(a) && throw(ArgumentError("BitArray must be non-empty")) - m, mi = false, 1 - ti = 1 - ac = a.chunks - for i = 1:length(ac) - @inbounds k = trailing_zeros(ac[i]) - ti += k - k == 64 || return (true, ti) - end - return m, mi -end - -function findmin(a::BitArray) - isempty(a) && throw(ArgumentError("BitArray must be non-empty")) - m, mi = true, 1 - ti = 1 - ac = a.chunks - for i = 1:length(ac)-1 - @inbounds k = trailing_ones(ac[i]) - ti += k - k == 64 || return (false, ti) - end - l = Base._mod64(length(a)-1) + 1 - @inbounds k = trailing_ones(ac[end] & Base._msk_end(l)) - ti += k - k == l || return (false, ti) - return m, mi -end - -# fast 8x8 bit transpose from Henry S. Warrens's "Hacker's Delight" -# http://www.hackersdelight.org/hdcodetxt/transpose8.c.txt -function transpose8x8(x::UInt64) - y = x - t = xor(y, y >>> 7) & 0x00aa00aa00aa00aa - y = xor(y, t, t << 7) - t = xor(y, y >>> 14) & 0x0000cccc0000cccc - y = xor(y, t, t << 14) - t = xor(y, y >>> 28) & 0x00000000f0f0f0f0 - return xor(y, t, t << 28) -end - -function form_8x8_chunk(Bc::Vector{UInt64}, i1::Int, i2::Int, m::Int, cgap::Int, cinc::Int, nc::Int, msk8::UInt64) - x = UInt64(0) - - k, l = Base.get_chunks_id(i1 + (i2 - 1) * m) - r = 0 - for j = 1:8 - k > nc && break - x |= ((Bc[k] >>> l) & msk8) << r - if l + 8 >= 64 && nc > k - r0 = 8 - Base._mod64(l + 8) - x |= (Bc[k + 1] & (msk8 >>> r0)) << (r + r0) - end - k += cgap + (l + cinc >= 64 ? 1 : 0) - l = Base._mod64(l + cinc) - r += 8 - end - return x -end - -# note: assumes B is filled with 0's -function put_8x8_chunk(Bc::Vector{UInt64}, i1::Int, i2::Int, x::UInt64, m::Int, cgap::Int, cinc::Int, nc::Int, msk8::UInt64) - k, l = Base.get_chunks_id(i1 + (i2 - 1) * m) - r = 0 - for j = 1:8 - k > nc && break - Bc[k] |= ((x >>> r) & msk8) << l - if l + 8 >= 64 && nc > k - r0 = 8 - Base._mod64(l + 8) - Bc[k + 1] |= ((x >>> (r + r0)) & (msk8 >>> r0)) - end - k += cgap + (l + cinc >= 64 ? 1 : 0) - l = Base._mod64(l + cinc) - r += 8 - end - return -end - -function transpose(B::BitMatrix) - l1 = size(B, 1) - l2 = size(B, 2) - Bt = falses(l2, l1) - - cgap1, cinc1 = Base._div64(l1), Base._mod64(l1) - cgap2, cinc2 = Base._div64(l2), Base._mod64(l2) - - Bc = B.chunks - Btc = Bt.chunks - - nc = length(Bc) - - for i = 1:8:l1 - msk8_1 = UInt64(0xff) - if (l1 < i + 7) - msk8_1 >>>= i + 7 - l1 - end - - for j = 1:8:l2 - x = form_8x8_chunk(Bc, i, j, l1, cgap1, cinc1, nc, msk8_1) - x = transpose8x8(x) - - msk8_2 = UInt64(0xff) - if (l2 < j + 7) - msk8_2 >>>= j + 7 - l2 - end - - put_8x8_chunk(Btc, j, i, x, l2, cgap2, cinc2, nc, msk8_2) - end - end - return Bt -end - -ctranspose(B::Union{BitMatrix,BitVector}) = transpose(B) diff --git a/julia-0.6.3/share/julia/base/linalg/blas.jl b/julia-0.6.3/share/julia/base/linalg/blas.jl deleted file mode 100644 index 9e1ab6f..0000000 --- a/julia-0.6.3/share/julia/base/linalg/blas.jl +++ /dev/null @@ -1,1480 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -module BLAS - -import Base: copy! -import Base.LinAlg: axpy!, dot - -export -# Level 1 - asum, - blascopy!, - dotc, - dotu, - scal!, - scal, - nrm2, - iamax, -# Level 2 - gbmv!, - gbmv, - gemv!, - gemv, - hemv!, - hemv, - sbmv!, - sbmv, - symv!, - symv, - trsv!, - trsv, - trmv!, - trmv, - ger!, - syr!, - her!, -# Level 3 - herk!, - herk, - her2k!, - her2k, - gemm!, - gemm, - symm!, - symm, - hemm!, - hemm, - syrk!, - syrk, - syr2k!, - syr2k, - trmm!, - trmm, - trsm!, - trsm - - -const libblas = Base.libblas_name -const liblapack = Base.liblapack_name - -import ..LinAlg: BlasReal, BlasComplex, BlasFloat, BlasInt, DimensionMismatch, checksquare, axpy! - -# utility routines -function vendor() - lib = Libdl.dlopen_e(Base.libblas_name) - if lib != C_NULL - if Libdl.dlsym_e(lib, :openblas_set_num_threads) != C_NULL - return :openblas - elseif Libdl.dlsym_e(lib, :openblas_set_num_threads64_) != C_NULL - return :openblas64 - elseif Libdl.dlsym_e(lib, :MKL_Set_Num_Threads) != C_NULL - return :mkl - end - end - return :unknown -end - -if vendor() == :openblas64 - macro blasfunc(x) - return Expr(:quote, Symbol(x, "64_")) - end - openblas_get_config() = strip(unsafe_string(ccall((:openblas_get_config64_, Base.libblas_name), Ptr{UInt8}, () ))) -else - macro blasfunc(x) - return Expr(:quote, x) - end - openblas_get_config() = strip(unsafe_string(ccall((:openblas_get_config, Base.libblas_name), Ptr{UInt8}, () ))) -end - -""" - set_num_threads(n) - -Set the number of threads the BLAS library should use. -""" -function set_num_threads(n::Integer) - blas = vendor() - if blas == :openblas - return ccall((:openblas_set_num_threads, Base.libblas_name), Void, (Int32,), n) - elseif blas == :openblas64 - return ccall((:openblas_set_num_threads64_, Base.libblas_name), Void, (Int32,), n) - elseif blas == :mkl - # MKL may let us set the number of threads in several ways - return ccall((:MKL_Set_Num_Threads, Base.libblas_name), Void, (Cint,), n) - end - - # OSX BLAS looks at an environment variable - @static if is_apple() - ENV["VECLIB_MAXIMUM_THREADS"] = n - end - - return nothing -end - -function check() - blas = vendor() - if blas == :openblas || blas == :openblas64 - openblas_config = openblas_get_config() - openblas64 = ismatch(r".*USE64BITINT.*", openblas_config) - if Base.USE_BLAS64 != openblas64 - if !openblas64 - println("ERROR: OpenBLAS was not built with 64bit integer support.") - println("You're seeing this error because Julia was built with USE_BLAS64=1") - println("Please rebuild Julia with USE_BLAS64=0") - else - println("ERROR: Julia was not built with support for OpenBLAS with 64bit integer support") - println("You're seeing this error because Julia was built with USE_BLAS64=0") - println("Please rebuild Julia with USE_BLAS64=1") - end - println("Quitting.") - quit() - end - elseif blas == :mkl - if Base.USE_BLAS64 - ENV["MKL_INTERFACE_LAYER"] = "ILP64" - end - end - - # - # Check if BlasInt is the expected bitsize, by triggering an error - # - (_, info) = LinAlg.LAPACK.potrf!('U', [1.0 0.0; 0.0 -1.0]) - if info != 2 # mangled info code - if info == 2^33 - error("""BLAS and LAPACK are compiled with 32-bit integer support, but Julia expects 64-bit integers. Please build Julia with USE_BLAS64=0.""") - elseif info == 0 - error("""BLAS and LAPACK are compiled with 64-bit integer support but Julia expects 32-bit integers. Please build Julia with USE_BLAS64=1.""") - else - error("""The LAPACK library produced an undefined error code. Please verify the installation of BLAS and LAPACK.""") - end - end - -end - - -# Level 1 -## copy - -""" - blascopy!(n, X, incx, Y, incy) - -Copy `n` elements of array `X` with stride `incx` to array `Y` with stride `incy`. Returns `Y`. -""" -function blascopy! end - -for (fname, elty) in ((:dcopy_,:Float64), - (:scopy_,:Float32), - (:zcopy_,:Complex128), - (:ccopy_,:Complex64)) - @eval begin - # SUBROUTINE DCOPY(N,DX,INCX,DY,INCY) - function blascopy!(n::Integer, DX::Union{Ptr{$elty},StridedArray{$elty}}, incx::Integer, DY::Union{Ptr{$elty},StridedArray{$elty}}, incy::Integer) - ccall((@blasfunc($fname), libblas), Void, - (Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}), - &n, DX, &incx, DY, &incy) - DY - end - end -end - -## scal - -""" - scal!(n, a, X, incx) - -Overwrite `X` with `a*X` for the first `n` elements of array `X` with stride `incx`. Returns `X`. -""" -function scal! end - -""" - scal(n, a, X, incx) - -Returns `X` scaled by `a` for the first `n` elements of array `X` with stride `incx`. -""" -function scal end - -for (fname, elty) in ((:dscal_,:Float64), - (:sscal_,:Float32), - (:zscal_,:Complex128), - (:cscal_,:Complex64)) - @eval begin - # SUBROUTINE DSCAL(N,DA,DX,INCX) - function scal!(n::Integer, DA::$elty, DX::Union{Ptr{$elty},DenseArray{$elty}}, incx::Integer) - ccall((@blasfunc($fname), libblas), Void, - (Ptr{BlasInt}, Ptr{$elty}, Ptr{$elty}, Ptr{BlasInt}), - &n, &DA, DX, &incx) - DX - end - end -end -scal(n, DA, DX, incx) = scal!(n, DA, copy(DX), incx) - -## dot - -""" - dot(n, X, incx, Y, incy) - -Dot product of two vectors consisting of `n` elements of array `X` with stride `incx` and -`n` elements of array `Y` with stride `incy`. - -# Example: -```jldoctest -julia> dot(10, ones(10), 1, ones(20), 2) -10.0 -``` -""" -function dot end - -""" - dotc(n, X, incx, U, incy) - -Dot function for two complex vectors, consisting of `n` elements of array `X` -with stride `incx` and `n` elements of array `U` with stride `incy`, -conjugating the first vector. - -# Example: -```jldoctest -julia> Base.BLAS.dotc(10, im*ones(10), 1, complex.(ones(20), ones(20)), 2) -10.0 - 10.0im -``` -""" -function dotc end - -""" - dotu(n, X, incx, Y, incy) - -Dot function for two complex vectors consisting of `n` elements of array `X` -with stride `incx` and `n` elements of array `Y` with stride `incy`. - -# Example: -```jldoctest -julia> Base.BLAS.dotu(10, im*ones(10), 1, complex.(ones(20), ones(20)), 2) --10.0 + 10.0im -``` -""" -function dotu end - -for (fname, elty) in ((:ddot_,:Float64), - (:sdot_,:Float32)) - @eval begin - # DOUBLE PRECISION FUNCTION DDOT(N,DX,INCX,DY,INCY) - # * .. Scalar Arguments .. - # INTEGER INCX,INCY,N - # * .. - # * .. Array Arguments .. - # DOUBLE PRECISION DX(*),DY(*) - function dot(n::Integer, DX::Union{Ptr{$elty},DenseArray{$elty}}, incx::Integer, DY::Union{Ptr{$elty},DenseArray{$elty}}, incy::Integer) - ccall((@blasfunc($fname), libblas), $elty, - (Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}), - &n, DX, &incx, DY, &incy) - end - end -end -for (fname, elty) in ((:cblas_zdotc_sub,:Complex128), - (:cblas_cdotc_sub,:Complex64)) - @eval begin - # DOUBLE PRECISION FUNCTION DDOT(N,DX,INCX,DY,INCY) - # * .. Scalar Arguments .. - # INTEGER INCX,INCY,N - # * .. - # * .. Array Arguments .. - # DOUBLE PRECISION DX(*),DY(*) - function dotc(n::Integer, DX::Union{Ptr{$elty},DenseArray{$elty}}, incx::Integer, DY::Union{Ptr{$elty},DenseArray{$elty}}, incy::Integer) - result = Ref{$elty}() - ccall((@blasfunc($fname), libblas), Void, - (BlasInt, Ptr{$elty}, BlasInt, Ptr{$elty}, BlasInt, Ptr{$elty}), - n, DX, incx, DY, incy, result) - result[] - end - end -end -for (fname, elty) in ((:cblas_zdotu_sub,:Complex128), - (:cblas_cdotu_sub,:Complex64)) - @eval begin - # DOUBLE PRECISION FUNCTION DDOT(N,DX,INCX,DY,INCY) - # * .. Scalar Arguments .. - # INTEGER INCX,INCY,N - # * .. - # * .. Array Arguments .. - # DOUBLE PRECISION DX(*),DY(*) - function dotu(n::Integer, DX::Union{Ptr{$elty},DenseArray{$elty}}, incx::Integer, DY::Union{Ptr{$elty},DenseArray{$elty}}, incy::Integer) - result = Ref{$elty}() - ccall((@blasfunc($fname), libblas), Void, - (BlasInt, Ptr{$elty}, BlasInt, Ptr{$elty}, BlasInt, Ptr{$elty}), - n, DX, incx, DY, incy, result) - result[] - end - end -end -function dot(DX::Union{DenseArray{T},StridedVector{T}}, DY::Union{DenseArray{T},StridedVector{T}}) where T<:BlasReal - n = length(DX) - if n != length(DY) - throw(DimensionMismatch("dot product arguments have lengths $(length(DX)) and $(length(DY))")) - end - dot(n, pointer(DX), stride(DX, 1), pointer(DY), stride(DY, 1)) -end -function dotc(DX::Union{DenseArray{T},StridedVector{T}}, DY::Union{DenseArray{T},StridedVector{T}}) where T<:BlasComplex - n = length(DX) - if n != length(DY) - throw(DimensionMismatch("dot product arguments have lengths $(length(DX)) and $(length(DY))")) - end - dotc(n, pointer(DX), stride(DX, 1), pointer(DY), stride(DY, 1)) -end -function dotu(DX::Union{DenseArray{T},StridedVector{T}}, DY::Union{DenseArray{T},StridedVector{T}}) where T<:BlasComplex - n = length(DX) - if n != length(DY) - throw(DimensionMismatch("dot product arguments have lengths $(length(DX)) and $(length(DY))")) - end - dotu(n, pointer(DX), stride(DX, 1), pointer(DY), stride(DY, 1)) -end - -## nrm2 - -stride1(x) = stride(x,1) -stride1(x::Array) = 1 - -""" - nrm2(n, X, incx) - -2-norm of a vector consisting of `n` elements of array `X` with stride `incx`. - -# Example: -```jldoctest -julia> Base.BLAS.nrm2(4, ones(8), 2) -2.0 - -julia> Base.BLAS.nrm2(1, ones(8), 2) -1.0 -``` -""" -function nrm2 end - -for (fname, elty, ret_type) in ((:dnrm2_,:Float64,:Float64), - (:snrm2_,:Float32,:Float32), - (:dznrm2_,:Complex128,:Float64), - (:scnrm2_,:Complex64,:Float32)) - @eval begin - # SUBROUTINE DNRM2(N,X,INCX) - function nrm2(n::Integer, X::Union{Ptr{$elty},DenseArray{$elty}}, incx::Integer) - ccall((@blasfunc($fname), libblas), $ret_type, - (Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}), - &n, X, &incx) - end - end -end -nrm2(x::Union{StridedVector,Array}) = nrm2(length(x), pointer(x), stride1(x)) - -## asum - -""" - asum(n, X, incx) - -Sum of the absolute values of the first `n` elements of array `X` with stride `incx`. - -# Example: -```jldoctest -julia> Base.BLAS.asum(5, im*ones(10), 2) -5.0 - -julia> Base.BLAS.asum(2, im*ones(10), 5) -2.0 -``` -""" -function asum end - -for (fname, elty, ret_type) in ((:dasum_,:Float64,:Float64), - (:sasum_,:Float32,:Float32), - (:dzasum_,:Complex128,:Float64), - (:scasum_,:Complex64,:Float32)) - @eval begin - # SUBROUTINE ASUM(N, X, INCX) - function asum(n::Integer, X::Union{Ptr{$elty},DenseArray{$elty}}, incx::Integer) - ccall((@blasfunc($fname), libblas), $ret_type, - (Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}), - &n, X, &incx) - end - end -end -asum(x::Union{StridedVector,Array}) = asum(length(x), pointer(x), stride1(x)) - -## axpy - -""" - axpy!(a, X, Y) - -Overwrite `Y` with `a*X + Y`, where `a` is a scalar. Returns `Y`. - -# Example: -```jldoctest -julia> x = [1; 2; 3]; - -julia> y = [4; 5; 6]; - -julia> Base.BLAS.axpy!(2, x, y) -3-element Array{Int64,1}: - 6 - 9 - 12 -``` -""" -function axpy! end - -for (fname, elty) in ((:daxpy_,:Float64), - (:saxpy_,:Float32), - (:zaxpy_,:Complex128), - (:caxpy_,:Complex64)) - @eval begin - # SUBROUTINE DAXPY(N,DA,DX,INCX,DY,INCY) - # DY <- DA*DX + DY - #* .. Scalar Arguments .. - # DOUBLE PRECISION DA - # INTEGER INCX,INCY,N - #* .. Array Arguments .. - # DOUBLE PRECISION DX(*),DY(*) - function axpy!(n::Integer, alpha::($elty), dx::Union{Ptr{$elty}, DenseArray{$elty}}, incx::Integer, dy::Union{Ptr{$elty}, DenseArray{$elty}}, incy::Integer) - ccall((@blasfunc($fname), libblas), Void, - (Ptr{BlasInt}, Ptr{$elty}, Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}), - &n, &alpha, dx, &incx, dy, &incy) - dy - end - end -end -function axpy!(alpha::Number, x::Union{DenseArray{T},StridedVector{T}}, y::Union{DenseArray{T},StridedVector{T}}) where T<:BlasFloat - if length(x) != length(y) - throw(DimensionMismatch("x has length $(length(x)), but y has length $(length(y))")) - end - axpy!(length(x), convert(T,alpha), pointer(x), stride(x, 1), pointer(y), stride(y, 1)) - y -end - -function axpy!(alpha::Number, x::Array{T}, rx::Union{UnitRange{Ti},Range{Ti}}, - y::Array{T}, ry::Union{UnitRange{Ti},Range{Ti}}) where {T<:BlasFloat,Ti<:Integer} - if length(rx) != length(ry) - throw(DimensionMismatch("ranges of differing lengths")) - end - if minimum(rx) < 1 || maximum(rx) > length(x) - throw(ArgumentError("range out of bounds for x, of length $(length(x))")) - end - if minimum(ry) < 1 || maximum(ry) > length(y) - throw(ArgumentError("range out of bounds for y, of length $(length(y))")) - end - axpy!(length(rx), convert(T, alpha), pointer(x)+(first(rx)-1)*sizeof(T), step(rx), pointer(y)+(first(ry)-1)*sizeof(T), step(ry)) - y -end - -## iamax -for (fname, elty) in ((:idamax_,:Float64), - (:isamax_,:Float32), - (:izamax_,:Complex128), - (:icamax_,:Complex64)) - @eval begin - function iamax(n::Integer, dx::Union{Ptr{$elty}, DenseArray{$elty}}, incx::Integer) - ccall((@blasfunc($fname), libblas),BlasInt, - (Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}), - &n, dx, &incx) - end - end -end -iamax(dx::Union{StridedVector,Array}) = iamax(length(dx), pointer(dx), stride1(dx)) - -# Level 2 -## mv -### gemv -for (fname, elty) in ((:dgemv_,:Float64), - (:sgemv_,:Float32), - (:zgemv_,:Complex128), - (:cgemv_,:Complex64)) - @eval begin - #SUBROUTINE DGEMV(TRANS,M,N,ALPHA,A,LDA,X,INCX,BETA,Y,INCY) - #* .. Scalar Arguments .. - # DOUBLE PRECISION ALPHA,BETA - # INTEGER INCX,INCY,LDA,M,N - # CHARACTER TRANS - #* .. Array Arguments .. - # DOUBLE PRECISION A(LDA,*),X(*),Y(*) - function gemv!(trans::Char, alpha::($elty), A::StridedVecOrMat{$elty}, X::StridedVector{$elty}, beta::($elty), Y::StridedVector{$elty}) - m,n = size(A,1),size(A,2) - if trans == 'N' && (length(X) != n || length(Y) != m) - throw(DimensionMismatch("A has dimensions $(size(A)), X has length $(length(X)) and Y has length $(length(Y))")) - elseif trans == 'C' && (length(X) != m || length(Y) != n) - throw(DimensionMismatch("A' has dimensions $n, $m, X has length $(length(X)) and Y has length $(length(Y))")) - elseif trans == 'T' && (length(X) != m || length(Y) != n) - throw(DimensionMismatch("A.' has dimensions $n, $m, X has length $(length(X)) and Y has length $(length(Y))")) - end - ccall((@blasfunc($fname), libblas), Void, - (Ptr{UInt8}, Ptr{BlasInt}, Ptr{BlasInt}, Ptr{$elty}, - Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, - Ptr{$elty}, Ptr{$elty}, Ptr{BlasInt}), - &trans, &size(A,1), &size(A,2), &alpha, - A, &max(1,stride(A,2)), X, &stride(X,1), - &beta, Y, &stride(Y,1)) - Y - end - function gemv(trans::Char, alpha::($elty), A::StridedMatrix{$elty}, X::StridedVector{$elty}) - gemv!(trans, alpha, A, X, zero($elty), similar(X, $elty, size(A, (trans == 'N' ? 1 : 2)))) - end - function gemv(trans::Char, A::StridedMatrix{$elty}, X::StridedVector{$elty}) - gemv!(trans, one($elty), A, X, zero($elty), similar(X, $elty, size(A, (trans == 'N' ? 1 : 2)))) - end - end -end - -""" - gemv!(tA, alpha, A, x, beta, y) - -Update the vector `y` as `alpha*A*x + beta*y` or `alpha*A'x + beta*y` -according to [`tA`](@ref stdlib-blas-trans). -`alpha` and `beta` are scalars. Returns the updated `y`. -""" -gemv! - -""" - gemv(tA, alpha, A, x) - -Returns `alpha*A*x` or `alpha*A'x` according to [`tA`](@ref stdlib-blas-trans). -`alpha` is a scalar. -""" -gemv(tA, alpha, A, x) - -""" - gemv(tA, A, x) - -Returns `A*x` or `A'x` according to [`tA`](@ref stdlib-blas-trans). -""" -gemv(tA, A, x) - -### (GB) general banded matrix-vector multiplication - -""" - gbmv!(trans, m, kl, ku, alpha, A, x, beta, y) - -Update vector `y` as `alpha*A*x + beta*y` or `alpha*A'*x + beta*y` according to [`trans`](@ref stdlib-blas-trans). -The matrix `A` is a general band matrix of dimension `m` by `size(A,2)` with `kl` -sub-diagonals and `ku` super-diagonals. `alpha` and `beta` are scalars. Returns the updated `y`. -""" -function gbmv! end - -""" - gbmv(trans, m, kl, ku, alpha, A, x) - -Returns `alpha*A*x` or `alpha*A'*x` according to [`trans`](@ref stdlib-blas-trans). -The matrix `A` is a general band matrix of dimension `m` by `size(A,2)` with `kl` sub-diagonals and `ku` -super-diagonals, and `alpha` is a scalar. -""" -function gbmv end - -for (fname, elty) in ((:dgbmv_,:Float64), - (:sgbmv_,:Float32), - (:zgbmv_,:Complex128), - (:cgbmv_,:Complex64)) - @eval begin - # SUBROUTINE DGBMV(TRANS,M,N,KL,KU,ALPHA,A,LDA,X,INCX,BETA,Y,INCY) - # * .. Scalar Arguments .. - # DOUBLE PRECISION ALPHA,BETA - # INTEGER INCX,INCY,KL,KU,LDA,M,N - # CHARACTER TRANS - # * .. Array Arguments .. - # DOUBLE PRECISION A(LDA,*),X(*),Y(*) - function gbmv!(trans::Char, m::Integer, kl::Integer, ku::Integer, alpha::($elty), A::StridedMatrix{$elty}, x::StridedVector{$elty}, beta::($elty), y::StridedVector{$elty}) - ccall((@blasfunc($fname), libblas), Void, - (Ptr{UInt8}, Ptr{BlasInt}, Ptr{BlasInt}, Ptr{BlasInt}, - Ptr{BlasInt}, Ptr{$elty}, Ptr{$elty}, Ptr{BlasInt}, - Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, Ptr{$elty}, - Ptr{BlasInt}), - &trans, &m, &size(A,2), &kl, - &ku, &alpha, A, &max(1,stride(A,2)), - x, &stride(x,1), &beta, y, &stride(y,1)) - y - end - function gbmv(trans::Char, m::Integer, kl::Integer, ku::Integer, alpha::($elty), A::StridedMatrix{$elty}, x::StridedVector{$elty}) - n = size(A,2) - leny = trans == 'N' ? m : n - gbmv!(trans, m, kl, ku, alpha, A, x, zero($elty), similar(x, $elty, leny)) - end - function gbmv(trans::Char, m::Integer, kl::Integer, ku::Integer, A::StridedMatrix{$elty}, x::StridedVector{$elty}) - gbmv(trans, m, kl, ku, one($elty), A, x) - end - end -end - -### symv - -""" - symv!(ul, alpha, A, x, beta, y) - -Update the vector `y` as `alpha*A*x + beta*y`. `A` is assumed to be symmetric. -Only the [`ul`](@ref stdlib-blas-uplo) triangle of `A` is used. -`alpha` and `beta` are scalars. Returns the updated `y`. -""" -function symv! end - -for (fname, elty, lib) in ((:dsymv_,:Float64,libblas), - (:ssymv_,:Float32,libblas), - (:zsymv_,:Complex128,liblapack), - (:csymv_,:Complex64,liblapack)) - # Note that the complex symv are not BLAS but auiliary functions in LAPACK - @eval begin - # SUBROUTINE DSYMV(UPLO,N,ALPHA,A,LDA,X,INCX,BETA,Y,INCY) - # .. Scalar Arguments .. - # DOUBLE PRECISION ALPHA,BETA - # INTEGER INCX,INCY,LDA,N - # CHARACTER UPLO - # .. Array Arguments .. - # DOUBLE PRECISION A(LDA,*),X(*),Y(*) - function symv!(uplo::Char, alpha::($elty), A::StridedMatrix{$elty}, x::StridedVector{$elty},beta::($elty), y::StridedVector{$elty}) - m, n = size(A) - if m != n - throw(DimensionMismatch("matrix A is $m by $n but must be square")) - end - if n != length(x) - throw(DimensionMismatch("A has size $(size(A)), and x has length $(length(x))")) - end - if m != length(y) - throw(DimensionMismatch("A has size $(size(A)), and y has length $(length(y))")) - end - ccall((@blasfunc($fname), $lib), Void, - (Ptr{UInt8}, Ptr{BlasInt}, Ptr{$elty}, Ptr{$elty}, - Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, - Ptr{$elty}, Ptr{BlasInt}), - &uplo, &n, &alpha, A, - &max(1,stride(A,2)), x, &stride(x,1), &beta, - y, &stride(y,1)) - y - end - function symv(uplo::Char, alpha::($elty), A::StridedMatrix{$elty}, x::StridedVector{$elty}) - symv!(uplo, alpha, A, x, zero($elty), similar(x)) - end - function symv(uplo::Char, A::StridedMatrix{$elty}, x::StridedVector{$elty}) - symv(uplo, one($elty), A, x) - end - end -end - -""" - symv(ul, alpha, A, x) - -Returns `alpha*A*x`. `A` is assumed to be symmetric. -Only the [`ul`](@ref stdlib-blas-uplo) triangle of `A` is used. -`alpha` is a scalar. -""" -symv(ul, alpha, A, x) - -""" - symv(ul, A, x) - -Returns `A*x`. `A` is assumed to be symmetric. -Only the [`ul`](@ref stdlib-blas-uplo) triangle of `A` is used. -""" -symv(ul, A, x) - -### hemv -for (fname, elty) in ((:zhemv_,:Complex128), - (:chemv_,:Complex64)) - @eval begin - function hemv!(uplo::Char, α::$elty, A::StridedMatrix{$elty}, x::StridedVector{$elty}, β::$elty, y::StridedVector{$elty}) - m, n = size(A) - if m != n - throw(DimensionMismatch("matrix A is $m by $n but must be square")) - end - if n != length(x) - throw(DimensionMismatch("A has size $(size(A)), and x has length $(length(x))")) - end - if m != length(y) - throw(DimensionMismatch("A has size $(size(A)), and y has length $(length(y))")) - end - lda = max(1, stride(A, 2)) - incx = stride(x, 1) - incy = stride(y, 1) - ccall((@blasfunc($fname), libblas), Void, - (Ptr{UInt8}, Ptr{BlasInt}, Ptr{$elty}, Ptr{$elty}, - Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, - Ptr{$elty}, Ptr{BlasInt}), - &uplo, &n, &α, A, - &lda, x, &incx, &β, - y, &incy) - y - end - function hemv(uplo::Char, α::($elty), A::StridedMatrix{$elty}, x::StridedVector{$elty}) - hemv!(uplo, α, A, x, zero($elty), similar(x)) - end - function hemv(uplo::Char, A::StridedMatrix{$elty}, x::StridedVector{$elty}) - hemv(uplo, one($elty), A, x) - end - end -end - -### sbmv, (SB) symmetric banded matrix-vector multiplication -for (fname, elty) in ((:dsbmv_,:Float64), - (:ssbmv_,:Float32)) - @eval begin - # SUBROUTINE DSBMV(UPLO,N,K,ALPHA,A,LDA,X,INCX,BETA,Y,INCY) - # * .. Scalar Arguments .. - # DOUBLE PRECISION ALPHA,BETA - # INTEGER INCX,INCY,K,LDA,N - # CHARACTER UPLO - # * .. Array Arguments .. - # DOUBLE PRECISION A(LDA,*),X(*),Y(*) - function sbmv!(uplo::Char, k::Integer, alpha::($elty), A::StridedMatrix{$elty}, x::StridedVector{$elty}, beta::($elty), y::StridedVector{$elty}) - ccall((@blasfunc($fname), libblas), Void, - (Ptr{UInt8}, Ptr{BlasInt}, Ptr{BlasInt}, Ptr{$elty}, - Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, - Ptr{$elty}, Ptr{$elty}, Ptr{BlasInt}), - &uplo, &size(A,2), &k, &alpha, - A, &max(1,stride(A,2)), x, &stride(x,1), - &beta, y, &stride(y,1)) - y - end - function sbmv(uplo::Char, k::Integer, alpha::($elty), A::StridedMatrix{$elty}, x::StridedVector{$elty}) - n = size(A,2) - sbmv!(uplo, k, alpha, A, x, zero($elty), similar(x, $elty, n)) - end - function sbmv(uplo::Char, k::Integer, A::StridedMatrix{$elty}, x::StridedVector{$elty}) - sbmv(uplo, k, one($elty), A, x) - end - end -end - -""" - sbmv(uplo, k, alpha, A, x) - -Returns `alpha*A*x` where `A` is a symmetric band matrix of order `size(A,2)` with `k` -super-diagonals stored in the argument `A`. -Only the [`uplo`](@ref stdlib-blas-uplo) triangle of `A` is used. -""" -sbmv(uplo, k, alpha, A, x) - -""" - sbmv(uplo, k, A, x) - -Returns `A*x` where `A` is a symmetric band matrix of order `size(A,2)` with `k` -super-diagonals stored in the argument `A`. -Only the [`uplo`](@ref stdlib-blas-uplo) triangle of `A` is used. -""" -sbmv(uplo, k, A, x) - -""" - sbmv!(uplo, k, alpha, A, x, beta, y) - -Update vector `y` as `alpha*A*x + beta*y` where `A` is a a symmetric band matrix of order -`size(A,2)` with `k` super-diagonals stored in the argument `A`. The storage layout for `A` -is described the reference BLAS module, level-2 BLAS at -. -Only the [`uplo`](@ref stdlib-blas-uplo) triangle of `A` is used. - -Returns the updated `y`. -""" -sbmv! - -### hbmv, (HB) Hermitian banded matrix-vector multiplication -for (fname, elty) in ((:zhbmv_,:Complex128), - (:chbmv_,:Complex64)) - @eval begin - # SUBROUTINE ZHBMV(UPLO,N,K,ALPHA,A,LDA,X,INCX,BETA,Y,INCY) - # * .. Scalar Arguments .. - # DOUBLE PRECISION ALPHA,BETA - # INTEGER INCX,INCY,K,LDA,N - # CHARACTER UPLO - # * .. Array Arguments .. - # DOUBLE PRECISION A(LDA,*),X(*),Y(*) - function hbmv!(uplo::Char, k::Integer, alpha::($elty), A::StridedMatrix{$elty}, x::StridedVector{$elty}, beta::($elty), y::StridedVector{$elty}) - ccall((@blasfunc($fname), libblas), Void, - (Ptr{UInt8}, Ptr{BlasInt}, Ptr{BlasInt}, Ptr{$elty}, - Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, - Ptr{$elty}, Ptr{$elty}, Ptr{BlasInt}), - &uplo, &size(A,2), &k, &alpha, - A, &max(1,stride(A,2)), x, &stride(x,1), - &beta, y, &stride(y,1)) - y - end - function hbmv(uplo::Char, k::Integer, alpha::($elty), A::StridedMatrix{$elty}, x::StridedVector{$elty}) - n = size(A,2) - hbmv!(uplo, k, alpha, A, x, zero($elty), similar(x, $elty, n)) - end - function hbmv(uplo::Char, k::Integer, A::StridedMatrix{$elty}, x::StridedVector{$elty}) - hbmv(uplo, k, one($elty), A, x) - end - end -end - -### trmv, Triangular matrix-vector multiplication - -""" - trmv(ul, tA, dA, A, b) - -Returns `op(A)*b`, where `op` is determined by [`tA`](@ref stdlib-blas-trans). -Only the [`ul`](@ref stdlib-blas-uplo) triangle of `A` is used. -[`dA`](@ref stdlib-blas-diag) determines if the diagonal values are read or -are assumed to be all ones. -""" -function trmv end - -""" - trmv!(ul, tA, dA, A, b) - -Returns `op(A)*b`, where `op` is determined by [`tA`](@ref stdlib-blas-trans). -Only the [`ul`](@ref stdlib-blas-uplo) triangle of `A` is used. -[`dA`](@ref stdlib-blas-diag) determines if the diagonal values are read or -are assumed to be all ones. -The multiplication occurs in-place on `b`. -""" -function trmv! end - -for (fname, elty) in ((:dtrmv_,:Float64), - (:strmv_,:Float32), - (:ztrmv_,:Complex128), - (:ctrmv_,:Complex64)) - @eval begin - # SUBROUTINE DTRMV(UPLO,TRANS,DIAG,N,A,LDA,X,INCX) - # * .. Scalar Arguments .. - # INTEGER INCX,LDA,N - # CHARACTER DIAG,TRANS,UPLO - # * .. Array Arguments .. - # DOUBLE PRECISION A(LDA,*),X(*) - function trmv!(uplo::Char, trans::Char, diag::Char, A::StridedMatrix{$elty}, x::StridedVector{$elty}) - n = checksquare(A) - if n != length(x) - throw(DimensionMismatch("A has size ($n,$n), x has length $(length(x))")) - end - ccall((@blasfunc($fname), libblas), Void, - (Ptr{UInt8}, Ptr{UInt8}, Ptr{UInt8}, Ptr{BlasInt}, - Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}), - &uplo, &trans, &diag, &n, - A, &max(1,stride(A,2)), x, &max(1,stride(x, 1))) - x - end - function trmv(uplo::Char, trans::Char, diag::Char, A::StridedMatrix{$elty}, x::StridedVector{$elty}) - trmv!(uplo, trans, diag, A, copy(x)) - end - end -end - -### trsv, Triangular matrix-vector solve - -""" - trsv!(ul, tA, dA, A, b) - -Overwrite `b` with the solution to `A*x = b` or one of the other two variants determined by -[`tA`](@ref stdlib-blas-trans) and [`ul`](@ref stdlib-blas-uplo). -[`dA`](@ref stdlib-blas-diag) determines if the diagonal values are read or -are assumed to be all ones. -Returns the updated `b`. -""" -function trsv! end - -""" - trsv(ul, tA, dA, A, b) - -Returns the solution to `A*x = b` or one of the other two variants determined by -[`tA`](@ref stdlib-blas-trans) and [`ul`](@ref stdlib-blas-uplo). -[`dA`](@ref stdlib-blas-diag) determines if the diagonal values are read or -are assumed to be all ones. -""" -function trsv end - -for (fname, elty) in ((:dtrsv_,:Float64), - (:strsv_,:Float32), - (:ztrsv_,:Complex128), - (:ctrsv_,:Complex64)) - @eval begin - # SUBROUTINE DTRSV(UPLO,TRANS,DIAG,N,A,LDA,X,INCX) - # .. Scalar Arguments .. - # INTEGER INCX,LDA,N - # CHARACTER DIAG,TRANS,UPLO - # .. Array Arguments .. - # DOUBLE PRECISION A(LDA,*),X(*) - function trsv!(uplo::Char, trans::Char, diag::Char, A::StridedMatrix{$elty}, x::StridedVector{$elty}) - n = checksquare(A) - if n != length(x) - throw(DimensionMismatch("size of A is $n != length(x) = $(length(x))")) - end - ccall((@blasfunc($fname), libblas), Void, - (Ptr{UInt8}, Ptr{UInt8}, Ptr{UInt8}, Ptr{BlasInt}, - Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}), - &uplo, &trans, &diag, &n, - A, &max(1,stride(A,2)), x, &stride(x, 1)) - x - end - function trsv(uplo::Char, trans::Char, diag::Char, A::StridedMatrix{$elty}, x::StridedVector{$elty}) - trsv!(uplo, trans, diag, A, copy(x)) - end - end -end - -### ger - -""" - ger!(alpha, x, y, A) - -Rank-1 update of the matrix `A` with vectors `x` and `y` as `alpha*x*y' + A`. -""" -function ger! end - -for (fname, elty) in ((:dger_,:Float64), - (:sger_,:Float32), - (:zgerc_,:Complex128), - (:cgerc_,:Complex64)) - @eval begin - function ger!(α::$elty, x::StridedVector{$elty}, y::StridedVector{$elty}, A::StridedMatrix{$elty}) - m, n = size(A) - if m != length(x) || n != length(y) - throw(DimensionMismatch("A has size ($m,$n), x has length $(length(x)), y has length $(length(y))")) - end - ccall((@blasfunc($fname), libblas), Void, - (Ptr{BlasInt}, Ptr{BlasInt}, Ptr{$elty}, Ptr{$elty}, - Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, - Ptr{BlasInt}), - &m, &n, &α, x, - &stride(x, 1), y, &stride(y, 1), A, - &max(1,stride(A,2))) - A - end - end -end - -### syr - -""" - syr!(uplo, alpha, x, A) - -Rank-1 update of the symmetric matrix `A` with vector `x` as `alpha*x*x.' + A`. -[`uplo`](@ref stdlib-blas-uplo) controls which triangle of `A` is updated. Returns `A`. -""" -function syr! end - -for (fname, elty, lib) in ((:dsyr_,:Float64,libblas), - (:ssyr_,:Float32,libblas), - (:zsyr_,:Complex128,liblapack), - (:csyr_,:Complex64,liblapack)) - @eval begin - function syr!(uplo::Char, α::$elty, x::StridedVector{$elty}, A::StridedMatrix{$elty}) - n = checksquare(A) - if length(x) != n - throw(DimensionMismatch("A has size ($n,$n), x has length $(length(x))")) - end - ccall((@blasfunc($fname), $lib), Void, - (Ptr{UInt8}, Ptr{BlasInt}, Ptr{$elty}, Ptr{$elty}, - Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}), - &uplo, &n, &α, x, - &stride(x, 1), A, &max(1,stride(A, 2))) - A - end - end -end - -### her - -""" - her!(uplo, alpha, x, A) - -Methods for complex arrays only. Rank-1 update of the Hermitian matrix `A` with vector `x` -as `alpha*x*x' + A`. -[`uplo`](@ref stdlib-blas-uplo) controls which triangle of `A` is updated. Returns `A`. -""" -function her! end - -for (fname, elty, relty) in ((:zher_,:Complex128, :Float64), - (:cher_,:Complex64, :Float32)) - @eval begin - function her!(uplo::Char, α::$relty, x::StridedVector{$elty}, A::StridedMatrix{$elty}) - n = checksquare(A) - if length(x) != n - throw(DimensionMismatch("A has size ($n,$n), x has length $(length(x))")) - end - ccall((@blasfunc($fname), libblas), Void, - (Ptr{UInt8}, Ptr{BlasInt}, Ptr{$relty}, Ptr{$elty}, - Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}), - &uplo, &n, &α, x, - &stride(x, 1), A, &max(1,stride(A,2))) - A - end - end -end - -# Level 3 -## (GE) general matrix-matrix multiplication - -""" - gemm!(tA, tB, alpha, A, B, beta, C) - -Update `C` as `alpha*A*B + beta*C` or the other three variants according to -[`tA`](@ref stdlib-blas-trans) and `tB`. Returns the updated `C`. -""" -function gemm! end - -for (gemm, elty) in - ((:dgemm_,:Float64), - (:sgemm_,:Float32), - (:zgemm_,:Complex128), - (:cgemm_,:Complex64)) - @eval begin - # SUBROUTINE DGEMM(TRANSA,TRANSB,M,N,K,ALPHA,A,LDA,B,LDB,BETA,C,LDC) - # * .. Scalar Arguments .. - # DOUBLE PRECISION ALPHA,BETA - # INTEGER K,LDA,LDB,LDC,M,N - # CHARACTER TRANSA,TRANSB - # * .. Array Arguments .. - # DOUBLE PRECISION A(LDA,*),B(LDB,*),C(LDC,*) - function gemm!(transA::Char, transB::Char, alpha::($elty), A::StridedVecOrMat{$elty}, B::StridedVecOrMat{$elty}, beta::($elty), C::StridedVecOrMat{$elty}) -# if any([stride(A,1), stride(B,1), stride(C,1)] .!= 1) -# error("gemm!: BLAS module requires contiguous matrix columns") -# end # should this be checked on every call? - m = size(A, transA == 'N' ? 1 : 2) - ka = size(A, transA == 'N' ? 2 : 1) - kb = size(B, transB == 'N' ? 1 : 2) - n = size(B, transB == 'N' ? 2 : 1) - if ka != kb || m != size(C,1) || n != size(C,2) - throw(DimensionMismatch("A has size ($m,$ka), B has size ($kb,$n), C has size $(size(C))")) - end - ccall((@blasfunc($gemm), libblas), Void, - (Ptr{UInt8}, Ptr{UInt8}, Ptr{BlasInt}, Ptr{BlasInt}, - Ptr{BlasInt}, Ptr{$elty}, Ptr{$elty}, Ptr{BlasInt}, - Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, Ptr{$elty}, - Ptr{BlasInt}), - &transA, &transB, &m, &n, - &ka, &alpha, A, &max(1,stride(A,2)), - B, &max(1,stride(B,2)), &beta, C, - &max(1,stride(C,2))) - C - end - function gemm(transA::Char, transB::Char, alpha::($elty), A::StridedMatrix{$elty}, B::StridedMatrix{$elty}) - gemm!(transA, transB, alpha, A, B, zero($elty), similar(B, $elty, (size(A, transA == 'N' ? 1 : 2), size(B, transB == 'N' ? 2 : 1)))) - end - function gemm(transA::Char, transB::Char, A::StridedMatrix{$elty}, B::StridedMatrix{$elty}) - gemm(transA, transB, one($elty), A, B) - end - end -end - -""" - gemm(tA, tB, alpha, A, B) - -Returns `alpha*A*B` or the other three variants according to [`tA`](@ref stdlib-blas-trans) and `tB`. -""" -gemm(tA, tB, alpha, A, B) - -""" - gemm(tA, tB, A, B) - -Returns `A*B` or the other three variants according to [`tA`](@ref stdlib-blas-trans) and `tB`. -""" -gemm(tA, tB, A, B) - - -## (SY) symmetric matrix-matrix and matrix-vector multiplication -for (mfname, elty) in ((:dsymm_,:Float64), - (:ssymm_,:Float32), - (:zsymm_,:Complex128), - (:csymm_,:Complex64)) - @eval begin - # SUBROUTINE DSYMM(SIDE,UPLO,M,N,ALPHA,A,LDA,B,LDB,BETA,C,LDC) - # .. Scalar Arguments .. - # DOUBLE PRECISION ALPHA,BETA - # INTEGER LDA,LDB,LDC,M,N - # CHARACTER SIDE,UPLO - # .. Array Arguments .. - # DOUBLE PRECISION A(LDA,*),B(LDB,*),C(LDC,*) - function symm!(side::Char, uplo::Char, alpha::($elty), A::StridedMatrix{$elty}, B::StridedMatrix{$elty}, beta::($elty), C::StridedMatrix{$elty}) - m, n = size(C) - j = checksquare(A) - if j != (side == 'L' ? m : n) - throw(DimensionMismatch("A has size $(size(A)), C has size ($m,$n)")) - end - if size(B,2) != n - throw(DimensionMismatch("B has second dimension $(size(B,2)) but needs to match second dimension of C, $n")) - end - ccall((@blasfunc($mfname), libblas), Void, - (Ptr{UInt8}, Ptr{UInt8}, Ptr{BlasInt}, Ptr{BlasInt}, - Ptr{$elty}, Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, - Ptr{BlasInt}, Ptr{$elty}, Ptr{$elty}, Ptr{BlasInt}), - &side, &uplo, &m, &n, - &alpha, A, &max(1,stride(A,2)), B, - &max(1,stride(B,2)), &beta, C, &max(1,stride(C,2))) - C - end - function symm(side::Char, uplo::Char, alpha::($elty), A::StridedMatrix{$elty}, B::StridedMatrix{$elty}) - symm!(side, uplo, alpha, A, B, zero($elty), similar(B)) - end - function symm(side::Char, uplo::Char, A::StridedMatrix{$elty}, B::StridedMatrix{$elty}) - symm(side, uplo, one($elty), A, B) - end - end -end - -""" - symm(side, ul, alpha, A, B) - -Returns `alpha*A*B` or `alpha*B*A` according to [`side`](@ref stdlib-blas-side). -`A` is assumed to be symmetric. Only -the [`ul`](@ref stdlib-blas-uplo) triangle of `A` is used. -""" -symm(side, ul, alpha, A, B) - -""" - symm(side, ul, A, B) - -Returns `A*B` or `B*A` according to [`side`](@ref stdlib-blas-side). -`A` is assumed to be symmetric. Only the [`ul`](@ref stdlib-blas-uplo) -triangle of `A` is used. -""" -symm(side, ul, A, B) - -""" - symm!(side, ul, alpha, A, B, beta, C) - -Update `C` as `alpha*A*B + beta*C` or `alpha*B*A + beta*C` according to [`side`](@ref stdlib-blas-side). -`A` is assumed to be symmetric. Only the [`ul`](@ref stdlib-blas-uplo) triangle of -`A` is used. Returns the updated `C`. -""" -symm! - -## (HE) Hermitian matrix-matrix and matrix-vector multiplication -for (mfname, elty) in ((:zhemm_,:Complex128), - (:chemm_,:Complex64)) - @eval begin - # SUBROUTINE DHEMM(SIDE,UPLO,M,N,ALPHA,A,LDA,B,LDB,BETA,C,LDC) - # .. Scalar Arguments .. - # DOUBLE PRECISION ALPHA,BETA - # INTEGER LDA,LDB,LDC,M,N - # CHARACTER SIDE,UPLO - # .. Array Arguments .. - # DOUBLE PRECISION A(LDA,*),B(LDB,*),C(LDC,*) - function hemm!(side::Char, uplo::Char, alpha::($elty), A::StridedMatrix{$elty}, B::StridedMatrix{$elty}, beta::($elty), C::StridedMatrix{$elty}) - m, n = size(C) - j = checksquare(A) - if j != (side == 'L' ? m : n) - throw(DimensionMismatch("A has size $(size(A)), C has size ($m,$n)")) - end - if size(B,2) != n - throw(DimensionMismatch("B has second dimension $(size(B,2)) but needs to match second dimension of C, $n")) - end - ccall((@blasfunc($mfname), libblas), Void, - (Ptr{UInt8}, Ptr{UInt8}, Ptr{BlasInt}, Ptr{BlasInt}, - Ptr{$elty}, Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, - Ptr{BlasInt}, Ptr{$elty}, Ptr{$elty}, Ptr{BlasInt}), - &side, &uplo, &m, &n, - &alpha, A, &max(1,stride(A,2)), B, - &max(1,stride(B,2)), &beta, C, &max(1,stride(C,2))) - C - end - function hemm(side::Char, uplo::Char, alpha::($elty), A::StridedMatrix{$elty}, B::StridedMatrix{$elty}) - hemm!(side, uplo, alpha, A, B, zero($elty), similar(B)) - end - function hemm(side::Char, uplo::Char, A::StridedMatrix{$elty}, B::StridedMatrix{$elty}) - hemm(side, uplo, one($elty), A, B) - end - end -end - -## syrk - -""" - syrk!(uplo, trans, alpha, A, beta, C) - -Rank-k update of the symmetric matrix `C` as `alpha*A*A.' + beta*C` or `alpha*A.'*A + -beta*C` according to [`trans`](@ref stdlib-blas-trans). -Only the [`uplo`](@ref stdlib-blas-uplo) triangle of `C` is used. Returns `C`. -""" -function syrk! end - -""" - syrk(uplo, trans, alpha, A) - -Returns either the upper triangle or the lower triangle of `A`, -according to [`uplo`](@ref stdlib-blas-uplo), -of `alpha*A*A.'` or `alpha*A.'*A`, -according to [`trans`](@ref stdlib-blas-trans). -""" -function syrk end - -for (fname, elty) in ((:dsyrk_,:Float64), - (:ssyrk_,:Float32), - (:zsyrk_,:Complex128), - (:csyrk_,:Complex64)) - @eval begin - # SUBROUTINE DSYRK(UPLO,TRANS,N,K,ALPHA,A,LDA,BETA,C,LDC) - # * .. Scalar Arguments .. - # REAL ALPHA,BETA - # INTEGER K,LDA,LDC,N - # CHARACTER TRANS,UPLO - # * .. Array Arguments .. - # REAL A(LDA,*),C(LDC,*) - function syrk!(uplo::Char, trans::Char, - alpha::($elty), A::StridedVecOrMat{$elty}, - beta::($elty), C::StridedMatrix{$elty}) - n = checksquare(C) - nn = size(A, trans == 'N' ? 1 : 2) - if nn != n throw(DimensionMismatch("C has size ($n,$n), corresponding dimension of A is $nn")) end - k = size(A, trans == 'N' ? 2 : 1) - ccall((@blasfunc($fname), libblas), Void, - (Ptr{UInt8}, Ptr{UInt8}, Ptr{BlasInt}, Ptr{BlasInt}, - Ptr{$elty}, Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, - Ptr{$elty}, Ptr{BlasInt}), - &uplo, &trans, &n, &k, - &alpha, A, &max(1,stride(A,2)), &beta, - C, &max(1,stride(C,2))) - C - end - end -end -function syrk(uplo::Char, trans::Char, alpha::Number, A::StridedVecOrMat) - T = eltype(A) - n = size(A, trans == 'N' ? 1 : 2) - syrk!(uplo, trans, convert(T,alpha), A, zero(T), similar(A, T, (n, n))) -end -syrk(uplo::Char, trans::Char, A::StridedVecOrMat) = syrk(uplo, trans, one(eltype(A)), A) - -""" - herk!(uplo, trans, alpha, A, beta, C) - -Methods for complex arrays only. Rank-k update of the Hermitian matrix `C` as `alpha*A*A' + -beta*C` or `alpha*A'*A + beta*C` according to [`trans`](@ref stdlib-blas-trans). -Only the [`uplo`](@ref stdlib-blas-uplo) triangle of `C` is updated. -Returns `C`. -""" -function herk! end - -""" - herk(uplo, trans, alpha, A) - -Methods for complex arrays only. -Returns the [`uplo`](@ref stdlib-blas-uplo) triangle of `alpha*A*A'` or `alpha*A'*A`, -according to [`trans`](@ref stdlib-blas-trans). -""" -function herk end - -for (fname, elty, relty) in ((:zherk_, :Complex128, :Float64), - (:cherk_, :Complex64, :Float32)) - @eval begin - # SUBROUTINE CHERK(UPLO,TRANS,N,K,ALPHA,A,LDA,BETA,C,LDC) - # * .. Scalar Arguments .. - # REAL ALPHA,BETA - # INTEGER K,LDA,LDC,N - # CHARACTER TRANS,UPLO - # * .. - # * .. Array Arguments .. - # COMPLEX A(LDA,*),C(LDC,*) - function herk!(uplo::Char, trans::Char, α::$relty, A::StridedVecOrMat{$elty}, - β::$relty, C::StridedMatrix{$elty}) - n = checksquare(C) - nn = size(A, trans == 'N' ? 1 : 2) - if nn != n - throw(DimensionMismatch("the matrix to update has dimension $n but the implied dimension of the update is $(size(A, trans == 'N' ? 1 : 2))")) - end - k = size(A, trans == 'N' ? 2 : 1) - ccall((@blasfunc($fname), libblas), Void, - (Ptr{UInt8}, Ptr{UInt8}, Ptr{BlasInt}, Ptr{BlasInt}, - Ptr{$relty}, Ptr{$elty}, Ptr{BlasInt}, Ptr{$relty}, - Ptr{$elty}, Ptr{BlasInt}), - &uplo, &trans, &n, &k, - &α, A, &max(1,stride(A,2)), &β, - C, &max(1,stride(C,2))) - C - end - function herk(uplo::Char, trans::Char, α::$relty, A::StridedVecOrMat{$elty}) - n = size(A, trans == 'N' ? 1 : 2) - herk!(uplo, trans, α, A, zero($relty), similar(A, (n,n))) - end - herk(uplo::Char, trans::Char, A::StridedVecOrMat{$elty}) = herk(uplo, trans, one($relty), A) - end -end - -## syr2k -for (fname, elty) in ((:dsyr2k_,:Float64), - (:ssyr2k_,:Float32), - (:zsyr2k_,:Complex128), - (:csyr2k_,:Complex64)) - @eval begin - # SUBROUTINE DSYR2K(UPLO,TRANS,N,K,ALPHA,A,LDA,B,LDB,BETA,C,LDC) - # - # .. Scalar Arguments .. - # REAL PRECISION ALPHA,BETA - # INTEGER K,LDA,LDB,LDC,N - # CHARACTER TRANS,UPLO - # .. - # .. Array Arguments .. - # REAL PRECISION A(LDA,*),B(LDB,*),C(LDC,*) - function syr2k!(uplo::Char, trans::Char, - alpha::($elty), A::StridedVecOrMat{$elty}, B::StridedVecOrMat{$elty}, - beta::($elty), C::StridedMatrix{$elty}) - n = checksquare(C) - nn = size(A, trans == 'N' ? 1 : 2) - if nn != n throw(DimensionMismatch("C has size ($n,$n), corresponding dimension of A is $nn")) end - k = size(A, trans == 'N' ? 2 : 1) - ccall((@blasfunc($fname), libblas), Void, - (Ptr{UInt8}, Ptr{UInt8}, Ptr{BlasInt}, Ptr{BlasInt}, - Ptr{$elty}, Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, - Ptr{$elty}, Ptr{BlasInt}), - &uplo, &trans, &n, &k, - &alpha, A, &max(1,stride(A,2)), B, &max(1,stride(B,2)), &beta, - C, &max(1,stride(C,2))) - C - end - end -end -function syr2k(uplo::Char, trans::Char, alpha::Number, A::StridedVecOrMat, B::StridedVecOrMat) - T = eltype(A) - n = size(A, trans == 'N' ? 1 : 2) - syr2k!(uplo, trans, convert(T,alpha), A, B, zero(T), similar(A, T, (n, n))) -end -syr2k(uplo::Char, trans::Char, A::StridedVecOrMat, B::StridedVecOrMat) = syr2k(uplo, trans, one(eltype(A)), A, B) - -for (fname, elty1, elty2) in ((:zher2k_,:Complex128,:Float64), (:cher2k_,:Complex64,:Float32)) - @eval begin - # SUBROUTINE CHER2K(UPLO,TRANS,N,K,ALPHA,A,LDA,B,LDB,BETA,C,LDC) - # - # .. Scalar Arguments .. - # COMPLEX ALPHA - # REAL BETA - # INTEGER K,LDA,LDB,LDC,N - # CHARACTER TRANS,UPLO - # .. - # .. Array Arguments .. - # COMPLEX A(LDA,*),B(LDB,*),C(LDC,*) - function her2k!(uplo::Char, trans::Char, alpha::($elty1), - A::StridedVecOrMat{$elty1}, B::StridedVecOrMat{$elty1}, - beta::($elty2), C::StridedMatrix{$elty1}) - n = checksquare(C) - nn = size(A, trans == 'N' ? 1 : 2) - if nn != n throw(DimensionMismatch("C has size ($n,$n), corresponding dimension of A is $nn")) end - k = size(A, trans == 'N' ? 2 : 1) - ccall((@blasfunc($fname), libblas), Void, - (Ptr{UInt8}, Ptr{UInt8}, Ptr{BlasInt}, Ptr{BlasInt}, - Ptr{$elty1}, Ptr{$elty1}, Ptr{BlasInt}, Ptr{$elty1}, Ptr{BlasInt}, - Ptr{$elty2}, Ptr{$elty1}, Ptr{BlasInt}), - &uplo, &trans, &n, &k, - &alpha, A, &max(1,stride(A,2)), B, &max(1,stride(B,2)), - &beta, C, &max(1,stride(C,2))) - C - end - function her2k(uplo::Char, trans::Char, alpha::($elty1), A::StridedVecOrMat{$elty1}, B::StridedVecOrMat{$elty1}) - n = size(A, trans == 'N' ? 1 : 2) - her2k!(uplo, trans, alpha, A, B, zero($elty2), similar(A, $elty1, (n,n))) - end - her2k(uplo::Char, trans::Char, A::StridedVecOrMat{$elty1}, B::StridedVecOrMat{$elty1}) = her2k(uplo, trans, one($elty1), A, B) - end -end - -## (TR) Triangular matrix and vector multiplication and solution - -""" - trmm!(side, ul, tA, dA, alpha, A, B) - -Update `B` as `alpha*A*B` or one of the other three variants determined by -[`side`](@ref stdlib-blas-side) and [`tA`](@ref stdlib-blas-trans). -Only the [`ul`](@ref stdlib-blas-uplo) triangle of `A` is used. -[`dA`](@ref stdlib-blas-diag) determines if the diagonal values are read or -are assumed to be all ones. -Returns the updated `B`. -""" -function trmm! end - -""" - trmm(side, ul, tA, dA, alpha, A, B) - -Returns `alpha*A*B` or one of the other three variants determined by -[`side`](@ref stdlib-blas-side) and [`tA`](@ref stdlib-blas-trans). -Only the [`ul`](@ref stdlib-blas-uplo) triangle of `A` is used. -[`dA`](@ref stdlib-blas-diag) determines if the diagonal values are read or -are assumed to be all ones. -""" -function trmm end - -""" - trsm!(side, ul, tA, dA, alpha, A, B) - -Overwrite `B` with the solution to `A*X = alpha*B` or one of the other three variants -determined by [`side`](@ref stdlib-blas-side) and [`tA`](@ref stdlib-blas-trans). -Only the [`ul`](@ref stdlib-blas-uplo) triangle of `A` is used. -[`dA`](@ref stdlib-blas-diag) determines if the diagonal values are read or -are assumed to be all ones. -Returns the updated `B`. -""" -function trsm! end - -""" - trsm(side, ul, tA, dA, alpha, A, B) - -Returns the solution to `A*X = alpha*B` or one of the other three variants determined by -determined by [`side`](@ref stdlib-blas-side) and [`tA`](@ref stdlib-blas-trans). -Only the [`ul`](@ref stdlib-blas-uplo) triangle of `A` is used. -[`dA`](@ref stdlib-blas-diag) determines if the diagonal values are read or -are assumed to be all ones. -""" -function trsm end - -for (mmname, smname, elty) in - ((:dtrmm_,:dtrsm_,:Float64), - (:strmm_,:strsm_,:Float32), - (:ztrmm_,:ztrsm_,:Complex128), - (:ctrmm_,:ctrsm_,:Complex64)) - @eval begin - # SUBROUTINE DTRMM(SIDE,UPLO,TRANSA,DIAG,M,N,ALPHA,A,LDA,B,LDB) - # * .. Scalar Arguments .. - # DOUBLE PRECISION ALPHA - # INTEGER LDA,LDB,M,N - # CHARACTER DIAG,SIDE,TRANSA,UPLO - # * .. Array Arguments .. - # DOUBLE PRECISION A(LDA,*),B(LDB,*) - function trmm!(side::Char, uplo::Char, transa::Char, diag::Char, alpha::Number, - A::StridedMatrix{$elty}, B::StridedMatrix{$elty}) - m, n = size(B) - nA = checksquare(A) - if nA != (side == 'L' ? m : n) - throw(DimensionMismatch("size of A, $(size(A)), doesn't match $side size of B with dims, $(size(B))")) - end - ccall((@blasfunc($mmname), libblas), Void, - (Ptr{UInt8}, Ptr{UInt8}, Ptr{UInt8}, Ptr{UInt8}, Ptr{BlasInt}, Ptr{BlasInt}, - Ptr{$elty}, Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}), - &side, &uplo, &transa, &diag, &m, &n, - &alpha, A, &max(1,stride(A,2)), B, &max(1,stride(B,2))) - B - end - function trmm(side::Char, uplo::Char, transa::Char, diag::Char, - alpha::$elty, A::StridedMatrix{$elty}, B::StridedMatrix{$elty}) - trmm!(side, uplo, transa, diag, alpha, A, copy(B)) - end - # SUBROUTINE DTRSM(SIDE,UPLO,TRANSA,DIAG,M,N,ALPHA,A,LDA,B,LDB) - # * .. Scalar Arguments .. - # DOUBLE PRECISION ALPHA - # INTEGER LDA,LDB,M,N - # CHARACTER DIAG,SIDE,TRANSA,UPLO - # * .. Array Arguments .. - # DOUBLE PRECISION A(LDA,*),B(LDB,*) - function trsm!(side::Char, uplo::Char, transa::Char, diag::Char, - alpha::$elty, A::StridedMatrix{$elty}, B::StridedMatrix{$elty}) - m, n = size(B) - k = checksquare(A) - if k != (side == 'L' ? m : n) - throw(DimensionMismatch("size of A is ($k,$k), size of B is ($m,$n), side is $side, and transa='$transa'")) - end - ccall((@blasfunc($smname), libblas), Void, - (Ptr{UInt8}, Ptr{UInt8}, Ptr{UInt8}, Ptr{UInt8}, - Ptr{BlasInt}, Ptr{BlasInt}, Ptr{$elty}, Ptr{$elty}, - Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}), - &side, &uplo, &transa, &diag, - &m, &n, &alpha, A, - &max(1,stride(A,2)), B, &max(1,stride(B,2))) - B - end - function trsm(side::Char, uplo::Char, transa::Char, diag::Char, alpha::$elty, A::StridedMatrix{$elty}, B::StridedMatrix{$elty}) - trsm!(side, uplo, transa, diag, alpha, A, copy(B)) - end - end -end - -end # module - -function copy!(dest::Array{T}, rdest::Union{UnitRange{Ti},Range{Ti}}, - src::Array{T}, rsrc::Union{UnitRange{Ti},Range{Ti}}) where {T<:BlasFloat,Ti<:Integer} - if minimum(rdest) < 1 || maximum(rdest) > length(dest) - throw(ArgumentError("range out of bounds for dest, of length $(length(dest))")) - end - if minimum(rsrc) < 1 || maximum(rsrc) > length(src) - throw(ArgumentError("range out of bounds for src, of length $(length(src))")) - end - if length(rdest) != length(rsrc) - throw(DimensionMismatch("ranges must be of the same length")) - end - BLAS.blascopy!(length(rsrc), pointer(src)+(first(rsrc)-1)*sizeof(T), step(rsrc), - pointer(dest)+(first(rdest)-1)*sizeof(T), step(rdest)) - dest -end diff --git a/julia-0.6.3/share/julia/base/linalg/bunchkaufman.jl b/julia-0.6.3/share/julia/base/linalg/bunchkaufman.jl deleted file mode 100644 index 224fb39..0000000 --- a/julia-0.6.3/share/julia/base/linalg/bunchkaufman.jl +++ /dev/null @@ -1,199 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -## Create an extractor that extracts the modified original matrix, e.g. -## LD for BunchKaufman, UL for CholeskyDense, LU for LUDense and -## define size methods for Factorization types using it. - -struct BunchKaufman{T,S<:AbstractMatrix} <: Factorization{T} - LD::S - ipiv::Vector{BlasInt} - uplo::Char - symmetric::Bool - rook::Bool - info::BlasInt -end -BunchKaufman{T}(A::AbstractMatrix{T}, ipiv::Vector{BlasInt}, uplo::Char, symmetric::Bool, - rook::Bool, info::BlasInt) = - BunchKaufman{T,typeof(A)}(A, ipiv, uplo, symmetric, rook, info) - -""" - bkfact!(A, uplo::Symbol=:U, symmetric::Bool=issymmetric(A), rook::Bool=false) -> BunchKaufman - -`bkfact!` is the same as [`bkfact`](@ref), but saves space by overwriting the -input `A`, instead of creating a copy. -""" -function bkfact!(A::StridedMatrix{<:BlasReal}, uplo::Symbol = :U, - symmetric::Bool = issymmetric(A), rook::Bool = false) - - if !symmetric - throw(ArgumentError("Bunch-Kaufman decomposition is only valid for symmetric matrices")) - end - if rook - LD, ipiv, info = LAPACK.sytrf_rook!(char_uplo(uplo), A) - else - LD, ipiv, info = LAPACK.sytrf!(char_uplo(uplo), A) - end - BunchKaufman(LD, ipiv, char_uplo(uplo), symmetric, rook, info) -end -function bkfact!(A::StridedMatrix{<:BlasComplex}, uplo::Symbol=:U, - symmetric::Bool=issymmetric(A), rook::Bool=false) - - if rook - if symmetric - LD, ipiv, info = LAPACK.sytrf_rook!(char_uplo(uplo), A) - else - LD, ipiv, info = LAPACK.hetrf_rook!(char_uplo(uplo), A) - end - else - if symmetric - LD, ipiv, info = LAPACK.sytrf!(char_uplo(uplo), A) - else - LD, ipiv, info = LAPACK.hetrf!(char_uplo(uplo), A) - end - end - BunchKaufman(LD, ipiv, char_uplo(uplo), symmetric, rook, info) -end - -""" - bkfact(A, uplo::Symbol=:U, symmetric::Bool=issymmetric(A), rook::Bool=false) -> BunchKaufman - -Compute the Bunch-Kaufman [^Bunch1977] factorization of a symmetric or Hermitian -matrix `A` and return a `BunchKaufman` object. -`uplo` indicates which triangle of matrix `A` to reference. -If `symmetric` is `true`, `A` is assumed to be symmetric. If `symmetric` is `false`, -`A` is assumed to be Hermitian. If `rook` is `true`, rook pivoting is used. If -`rook` is false, rook pivoting is not used. -The following functions are available for -`BunchKaufman` objects: [`size`](@ref), `\\`, [`inv`](@ref), [`issymmetric`](@ref), [`ishermitian`](@ref). - -[^Bunch1977]: J R Bunch and L Kaufman, Some stable methods for calculating inertia and solving symmetric linear systems, Mathematics of Computation 31:137 (1977), 163-179. [url](http://www.ams.org/journals/mcom/1977-31-137/S0025-5718-1977-0428694-0/). - -""" -bkfact(A::StridedMatrix{<:BlasFloat}, uplo::Symbol=:U, symmetric::Bool=issymmetric(A), - rook::Bool=false) = - bkfact!(copy(A), uplo, symmetric, rook) -bkfact(A::StridedMatrix{T}, uplo::Symbol=:U, symmetric::Bool=issymmetric(A), - rook::Bool=false) where {T} = - bkfact!(convert(Matrix{promote_type(Float32, typeof(sqrt(one(T))))}, A), - uplo, symmetric, rook) - -convert(::Type{BunchKaufman{T}}, B::BunchKaufman{T}) where {T} = B -convert(::Type{BunchKaufman{T}}, B::BunchKaufman) where {T} = - BunchKaufman(convert(Matrix{T}, B.LD), B.ipiv, B.uplo, B.symmetric, B.rook, B.info) -convert(::Type{Factorization{T}}, B::BunchKaufman{T}) where {T} = B -convert(::Type{Factorization{T}}, B::BunchKaufman) where {T} = convert(BunchKaufman{T}, B) - -size(B::BunchKaufman) = size(B.LD) -size(B::BunchKaufman, d::Integer) = size(B.LD, d) -issymmetric(B::BunchKaufman) = B.symmetric -ishermitian(B::BunchKaufman) = !B.symmetric - -function inv(B::BunchKaufman{<:BlasReal}) - if B.info > 0 - throw(SingularException(B.info)) - end - - if B.rook - copytri!(LAPACK.sytri_rook!(B.uplo, copy(B.LD), B.ipiv), B.uplo, true) - else - copytri!(LAPACK.sytri!(B.uplo, copy(B.LD), B.ipiv), B.uplo, true) - end -end - -function inv(B::BunchKaufman{<:BlasComplex}) - if B.info > 0 - throw(SingularException(B.info)) - end - - if issymmetric(B) - if B.rook - copytri!(LAPACK.sytri_rook!(B.uplo, copy(B.LD), B.ipiv), B.uplo) - else - copytri!(LAPACK.sytri!(B.uplo, copy(B.LD), B.ipiv), B.uplo) - end - else - if B.rook - copytri!(LAPACK.hetri_rook!(B.uplo, copy(B.LD), B.ipiv), B.uplo, true) - else - copytri!(LAPACK.hetri!(B.uplo, copy(B.LD), B.ipiv), B.uplo, true) - end - end -end - -function A_ldiv_B!(B::BunchKaufman{T}, R::StridedVecOrMat{T}) where T<:BlasReal - if B.info > 0 - throw(SingularException(B.info)) - end - - if B.rook - LAPACK.sytrs_rook!(B.uplo, B.LD, B.ipiv, R) - else - LAPACK.sytrs!(B.uplo, B.LD, B.ipiv, R) - end -end -function A_ldiv_B!(B::BunchKaufman{T}, R::StridedVecOrMat{T}) where T<:BlasComplex - if B.info > 0 - throw(SingularException(B.info)) - end - - if B.rook - if issymmetric(B) - LAPACK.sytrs_rook!(B.uplo, B.LD, B.ipiv, R) - else - LAPACK.hetrs_rook!(B.uplo, B.LD, B.ipiv, R) - end - else - if issymmetric(B) - LAPACK.sytrs!(B.uplo, B.LD, B.ipiv, R) - else - LAPACK.hetrs!(B.uplo, B.LD, B.ipiv, R) - end - end -end -# There is no fallback solver for Bunch-Kaufman so we'll have to promote to same element type -function A_ldiv_B!(B::BunchKaufman{T}, R::StridedVecOrMat{S}) where {T,S} - TS = promote_type(T,S) - return A_ldiv_B!(convert(BunchKaufman{TS}, B), convert(AbstractArray{TS}, R)) -end - -function logabsdet(F::BunchKaufman) - M = F.LD - p = F.ipiv - n = size(F.LD, 1) - - if F.info > 0 - return eltype(F)(-Inf), zero(eltype(F)) - end - s = one(real(eltype(F))) - i = 1 - abs_det = zero(real(eltype(F))) - while i <= n - if p[i] > 0 - elm = M[i,i] - s *= sign(elm) - abs_det += log(abs(elm)) - i += 1 - else - # 2x2 pivot case. Make sure not to square before the subtraction by scaling - # with the off-diagonal element. This is safe because the off diagonal is - # always large for 2x2 pivots. - if F.uplo == 'U' - elm = M[i, i + 1]*(M[i,i]/M[i, i + 1]*M[i + 1, i + 1] - - (issymmetric(F) ? M[i, i + 1] : conj(M[i, i + 1]))) - s *= sign(elm) - abs_det += log(abs(elm)) - else - elm = M[i + 1,i]*(M[i, i]/M[i + 1, i]*M[i + 1, i + 1] - - (issymmetric(F) ? M[i + 1, i] : conj(M[i + 1, i]))) - s *= sign(elm) - abs_det += log(abs(elm)) - end - i += 2 - end - end - return abs_det, s -end - -## reconstruct the original matrix -## TODO: understand the procedure described at -## http://www.nag.com/numeric/FL/nagdoc_fl22/pdf/F07/f07mdf.pdf diff --git a/julia-0.6.3/share/julia/base/linalg/cholesky.jl b/julia-0.6.3/share/julia/base/linalg/cholesky.jl deleted file mode 100644 index 4629fb9..0000000 --- a/julia-0.6.3/share/julia/base/linalg/cholesky.jl +++ /dev/null @@ -1,669 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -########################## -# Cholesky Factorization # -########################## - -# The dispatch structure in the chol!, chol, cholfact, and cholfact! methods is a bit -# complicated and some explanation is therefore provided in the following -# -# In the methods below, LAPACK is called when possible, i.e. StridedMatrices with Float32, -# Float64, Complex{Float32}, and Complex{Float64} element types. For other element or -# matrix types, the unblocked Julia implementation in _chol! is used. For cholfact -# and cholfact! pivoting is supported through a Val{Bool} argument. A type argument is -# necessary for type stability since the output of cholfact and cholfact! is either -# Cholesky or PivotedCholesky. The latter is only -# supported for the four LAPACK element types. For other types, e.g. BigFloats Val{true} will -# give an error. It is required that the input is Hermitian (including real symmetric) either -# through the Hermitian and Symmetric views or exact symmetric or Hermitian elements which -# is checked for and an error is thrown if the check fails. The dispatch -# is further complicated by a limitation in the formulation of Unions. The relevant union -# would be Union{Symmetric{T<:Real,S}, Hermitian} but, right now, it doesn't work in Julia -# so we'll have to define methods for the two elements of the union separately. - -# FixMe? The dispatch below seems overly complicated. One simplification could be to -# merge the two Cholesky types into one. It would remove the need for Val completely but -# the cost would be extra unnecessary/unused fields for the unpivoted Cholesky and runtime -# checks of those fields before calls to LAPACK to check which version of the Cholesky -# factorization the type represents. - -struct Cholesky{T,S<:AbstractMatrix} <: Factorization{T} - factors::S - uplo::Char -end -Cholesky{T}(A::AbstractMatrix{T}, uplo::Symbol) = Cholesky{T,typeof(A)}(A, char_uplo(uplo)) -Cholesky{T}(A::AbstractMatrix{T}, uplo::Char) = Cholesky{T,typeof(A)}(A, uplo) - -struct CholeskyPivoted{T,S<:AbstractMatrix} <: Factorization{T} - factors::S - uplo::Char - piv::Vector{BlasInt} - rank::BlasInt - tol::Real - info::BlasInt -end -function CholeskyPivoted{T}(A::AbstractMatrix{T}, uplo::Char, piv::Vector{BlasInt}, - rank::BlasInt, tol::Real, info::BlasInt) - CholeskyPivoted{T,typeof(A)}(A, uplo, piv, rank, tol, info) -end - - -# _chol!. Internal methods for calling unpivoted Cholesky -## BLAS/LAPACK element types -function _chol!(A::StridedMatrix{<:BlasFloat}, ::Type{UpperTriangular}) - C, info = LAPACK.potrf!('U', A) - return @assertposdef UpperTriangular(C) info -end -function _chol!(A::StridedMatrix{<:BlasFloat}, ::Type{LowerTriangular}) - C, info = LAPACK.potrf!('L', A) - return @assertposdef LowerTriangular(C) info -end - -## Non BLAS/LAPACK element types (generic) -function _chol!(A::AbstractMatrix, ::Type{UpperTriangular}) - n = checksquare(A) - @inbounds begin - for k = 1:n - for i = 1:k - 1 - A[k,k] -= A[i,k]'A[i,k] - end - Akk = _chol!(A[k,k], UpperTriangular) - A[k,k] = Akk - AkkInv = inv(Akk') - for j = k + 1:n - for i = 1:k - 1 - A[k,j] -= A[i,k]'A[i,j] - end - A[k,j] = AkkInv*A[k,j] - end - end - end - return UpperTriangular(A) -end -function _chol!(A::AbstractMatrix, ::Type{LowerTriangular}) - n = checksquare(A) - @inbounds begin - for k = 1:n - for i = 1:k - 1 - A[k,k] -= A[k,i]*A[k,i]' - end - Akk = _chol!(A[k,k], LowerTriangular) - A[k,k] = Akk - AkkInv = inv(Akk) - for j = 1:k - for i = k + 1:n - if j == 1 - A[i,k] = A[i,k]*AkkInv' - end - if j < k - A[i,k] -= A[i,j]*A[k,j]'*AkkInv' - end - end - end - end - end - return LowerTriangular(A) -end - -## Numbers -function _chol!(x::Number, uplo) - rx = real(x) - if rx != abs(x) - throw(ArgumentError("x must be positive semidefinite")) - end - rxr = sqrt(rx) - convert(promote_type(typeof(x), typeof(rxr)), rxr) -end - -non_hermitian_error(f) = throw(ArgumentError("matrix is not symmetric/" * - "Hermitian. This error can be avoided by calling $f(Hermitian(A)) " * - "which will ignore either the upper or lower triangle of the matrix.")) - -# chol!. Destructive methods for computing Cholesky factor of real symmetric or Hermitian -# matrix -chol!(A::Hermitian) = - _chol!(A.uplo == 'U' ? A.data : LinAlg.copytri!(A.data, 'L', true), UpperTriangular) -chol!(A::Symmetric{<:Real,<:StridedMatrix}) = - _chol!(A.uplo == 'U' ? A.data : LinAlg.copytri!(A.data, 'L', true), UpperTriangular) -function chol!(A::StridedMatrix) - ishermitian(A) || non_hermitian_error("chol!") - return _chol!(A, UpperTriangular) -end - - - -# chol. Non-destructive methods for computing Cholesky factor of a real symmetric or -# Hermitian matrix. Promotes elements to a type that is stable under square roots. -function chol(A::Hermitian) - T = promote_type(typeof(chol(one(eltype(A)))), Float32) - AA = similar(A, T, size(A)) - if A.uplo == 'U' - copy!(AA, A.data) - else - Base.ctranspose!(AA, A.data) - end - chol!(Hermitian(AA, :U)) -end -function chol(A::Symmetric{T,<:AbstractMatrix}) where T<:Real - TT = promote_type(typeof(chol(one(T))), Float32) - AA = similar(A, TT, size(A)) - if A.uplo == 'U' - copy!(AA, A.data) - else - Base.ctranspose!(AA, A.data) - end - chol!(Hermitian(AA, :U)) -end - -## for StridedMatrices, check that matrix is symmetric/Hermitian -""" - chol(A) -> U - -Compute the Cholesky factorization of a positive definite matrix `A` -and return the [`UpperTriangular`](@ref) matrix `U` such that `A = U'U`. - -# Example - -```jldoctest -julia> A = [1. 2.; 2. 50.] -2×2 Array{Float64,2}: - 1.0 2.0 - 2.0 50.0 - -julia> U = chol(A) -2×2 UpperTriangular{Float64,Array{Float64,2}}: - 1.0 2.0 - ⋅ 6.78233 - -julia> U'U -2×2 Array{Float64,2}: - 1.0 2.0 - 2.0 50.0 -``` -""" -function chol(A::AbstractMatrix) - ishermitian(A) || non_hermitian_error("chol") - return chol(Hermitian(A)) -end - -## Numbers -""" - chol(x::Number) -> y - -Compute the square root of a non-negative number `x`. - -# Example - -```jldoctest -julia> chol(16) -4.0 -``` -""" -chol(x::Number, args...) = _chol!(x, nothing) - - - -# cholfact!. Destructive methods for computing Cholesky factorization of real symmetric -# or Hermitian matrix -## No pivoting -function cholfact!(A::Hermitian, ::Type{Val{false}}) - if A.uplo == 'U' - Cholesky(_chol!(A.data, UpperTriangular).data, 'U') - else - Cholesky(_chol!(A.data, LowerTriangular).data, 'L') - end -end -function cholfact!(A::Symmetric{<:Real}, ::Type{Val{false}}) - if A.uplo == 'U' - Cholesky(_chol!(A.data, UpperTriangular).data, 'U') - else - Cholesky(_chol!(A.data, LowerTriangular).data, 'L') - end -end - -### for StridedMatrices, check that matrix is symmetric/Hermitian -""" - cholfact!(A, [uplo::Symbol,] Val{false}) -> Cholesky - -The same as [`cholfact`](@ref), but saves space by overwriting the input `A`, -instead of creating a copy. An [`InexactError`](@ref) exception is thrown if -the factorization produces a number not representable by the element type of -`A`, e.g. for integer types. - -# Example - -```jldoctest -julia> A = [1 2; 2 50] -2×2 Array{Int64,2}: - 1 2 - 2 50 - -julia> cholfact!(A) -ERROR: InexactError() -``` -""" -function cholfact!(A::StridedMatrix, uplo::Symbol, ::Type{Val{false}}) - ishermitian(A) || non_hermitian_error("cholfact!") - return cholfact!(Hermitian(A, uplo), Val{false}) -end - -### Default to no pivoting (and storing of upper factor) when not explicit -cholfact!(A::Hermitian) = cholfact!(A, Val{false}) -cholfact!(A::Symmetric{<:Real}) = cholfact!(A, Val{false}) -#### for StridedMatrices, check that matrix is symmetric/Hermitian -function cholfact!(A::StridedMatrix, uplo::Symbol = :U) - ishermitian(A) || non_hermitian_error("cholfact!") - return cholfact!(Hermitian(A, uplo)) -end - - -## With pivoting -### BLAS/LAPACK element types -function cholfact!(A::RealHermSymComplexHerm{<:BlasReal,<:StridedMatrix}, - ::Type{Val{true}}; tol = 0.0) - AA, piv, rank, info = LAPACK.pstrf!(A.uplo, A.data, tol) - return CholeskyPivoted{eltype(AA),typeof(AA)}(AA, A.uplo, piv, rank, tol, info) -end - -### Non BLAS/LAPACK element types (generic). Since generic fallback for pivoted Cholesky -### is not implemented yet we throw an error -cholfact!(A::RealHermSymComplexHerm{<:Real}, ::Type{Val{true}}; - tol = 0.0) = - throw(ArgumentError("generic pivoted Cholesky factorization is not implemented yet")) - -### for StridedMatrices, check that matrix is symmetric/Hermitian -""" - cholfact!(A, [uplo::Symbol,] Val{true}; tol = 0.0) -> CholeskyPivoted - -The same as [`cholfact`](@ref), but saves space by overwriting the input `A`, -instead of creating a copy. An [`InexactError`](@ref) exception is thrown if the -factorization produces a number not representable by the element type of `A`, -e.g. for integer types. -""" -function cholfact!(A::StridedMatrix, uplo::Symbol, ::Type{Val{true}}; tol = 0.0) - ishermitian(A) || non_hermitian_error("cholfact!") - return cholfact!(Hermitian(A, uplo), Val{true}; tol = tol) -end - -# cholfact. Non-destructive methods for computing Cholesky factorization of real symmetric -# or Hermitian matrix -## No pivoting -cholfact(A::Hermitian, ::Type{Val{false}}) = - cholfact!(copy_oftype(A, promote_type(typeof(chol(one(eltype(A)))),Float32)), Val{false}) -cholfact(A::Symmetric{<:Real,<:StridedMatrix}, ::Type{Val{false}}) = - cholfact!(copy_oftype(A, promote_type(typeof(chol(one(eltype(A)))),Float32)), Val{false}) - -### for StridedMatrices, check that matrix is symmetric/Hermitian -""" - cholfact(A, [uplo::Symbol,] Val{false}) -> Cholesky - -Compute the Cholesky factorization of a dense symmetric positive definite matrix `A` -and return a `Cholesky` factorization. The matrix `A` can either be a [`Symmetric`](@ref) or [`Hermitian`](@ref) -`StridedMatrix` or a *perfectly* symmetric or Hermitian `StridedMatrix`. In the latter case, -the optional argument `uplo` may be `:L` for using the lower part or `:U` for the upper part of `A`. -The default is to use `:U`. -The triangular Cholesky factor can be obtained from the factorization `F` with: `F[:L]` and `F[:U]`. -The following functions are available for `Cholesky` objects: [`size`](@ref), [`\\`](@ref), -[`inv`](@ref), and [`det`](@ref). -A `PosDefException` exception is thrown in case the matrix is not positive definite. - -# Example - -```jldoctest -julia> A = [4. 12. -16.; 12. 37. -43.; -16. -43. 98.] -3×3 Array{Float64,2}: - 4.0 12.0 -16.0 - 12.0 37.0 -43.0 - -16.0 -43.0 98.0 - -julia> C = cholfact(A) -Base.LinAlg.Cholesky{Float64,Array{Float64,2}} with factor: -[2.0 6.0 -8.0; 0.0 1.0 5.0; 0.0 0.0 3.0] - -julia> C[:U] -3×3 UpperTriangular{Float64,Array{Float64,2}}: - 2.0 6.0 -8.0 - ⋅ 1.0 5.0 - ⋅ ⋅ 3.0 - -julia> C[:L] -3×3 LowerTriangular{Float64,Array{Float64,2}}: - 2.0 ⋅ ⋅ - 6.0 1.0 ⋅ - -8.0 5.0 3.0 - -julia> C[:L] * C[:U] == A -true -``` -""" -function cholfact(A::StridedMatrix, uplo::Symbol, ::Type{Val{false}}) - ishermitian(A) || non_hermitian_error("cholfact") - return cholfact(Hermitian(A, uplo), Val{false}) -end - -### Default to no pivoting (and storing of upper factor) when not explicit -cholfact(A::Hermitian) = cholfact(A, Val{false}) -cholfact(A::Symmetric{<:Real,<:StridedMatrix}) = cholfact(A, Val{false}) -#### for StridedMatrices, check that matrix is symmetric/Hermitian -function cholfact(A::StridedMatrix, uplo::Symbol = :U) - ishermitian(A) || non_hermitian_error("cholfact") - return cholfact(Hermitian(A, uplo)) -end - - -## With pivoting -cholfact(A::Hermitian, ::Type{Val{true}}; tol = 0.0) = - cholfact!(copy_oftype(A, promote_type(typeof(chol(one(eltype(A)))),Float32)), - Val{true}; tol = tol) -cholfact(A::RealHermSymComplexHerm{<:Real,<:StridedMatrix}, ::Type{Val{true}}; tol = 0.0) = - cholfact!(copy_oftype(A, promote_type(typeof(chol(one(eltype(A)))),Float32)), - Val{true}; tol = tol) - -### for StridedMatrices, check that matrix is symmetric/Hermitian -""" - cholfact(A, [uplo::Symbol,] Val{true}; tol = 0.0) -> CholeskyPivoted - -Compute the pivoted Cholesky factorization of a dense symmetric positive semi-definite matrix `A` -and return a `CholeskyPivoted` factorization. The matrix `A` can either be a [`Symmetric`](@ref) -or [`Hermitian`](@ref) `StridedMatrix` or a *perfectly* symmetric or Hermitian `StridedMatrix`. -In the latter case, the optional argument `uplo` may be `:L` for using the lower part or `:U` -for the upper part of `A`. The default is to use `:U`. -The triangular Cholesky factor can be obtained from the factorization `F` with: `F[:L]` and `F[:U]`. -The following functions are available for `PivotedCholesky` objects: -[`size`](@ref), [`\\`](@ref), [`inv`](@ref), [`det`](@ref), and [`rank`](@ref). -The argument `tol` determines the tolerance for determining the rank. -For negative values, the tolerance is the machine precision. -""" -function cholfact(A::StridedMatrix, uplo::Symbol, ::Type{Val{true}}; tol = 0.0) - ishermitian(A) || non_hermitian_error("cholfact") - return cholfact(Hermitian(A, uplo), Val{true}; tol = tol) -end - -## Number -function cholfact(x::Number, uplo::Symbol=:U) - xf = fill(chol(x), 1, 1) - Cholesky(xf, uplo) -end - - -function convert(::Type{Cholesky{T}}, C::Cholesky) where T - Cnew = convert(AbstractMatrix{T}, C.factors) - Cholesky{T, typeof(Cnew)}(Cnew, C.uplo) -end -convert(::Type{Factorization{T}}, C::Cholesky{T}) where {T} = C -convert(::Type{Factorization{T}}, C::Cholesky) where {T} = convert(Cholesky{T}, C) -convert(::Type{CholeskyPivoted{T}},C::CholeskyPivoted{T}) where {T} = C -convert(::Type{CholeskyPivoted{T}},C::CholeskyPivoted) where {T} = - CholeskyPivoted(AbstractMatrix{T}(C.factors),C.uplo,C.piv,C.rank,C.tol,C.info) -convert(::Type{Factorization{T}}, C::CholeskyPivoted{T}) where {T} = C -convert(::Type{Factorization{T}}, C::CholeskyPivoted) where {T} = convert(CholeskyPivoted{T}, C) - -convert(::Type{AbstractMatrix}, C::Cholesky) = C.uplo == 'U' ? C[:U]'C[:U] : C[:L]*C[:L]' -convert(::Type{AbstractArray}, C::Cholesky) = convert(AbstractMatrix, C) -convert(::Type{Matrix}, C::Cholesky) = convert(Array, convert(AbstractArray, C)) -convert(::Type{Array}, C::Cholesky) = convert(Matrix, C) -full(C::Cholesky) = convert(AbstractArray, C) - -function convert(::Type{AbstractMatrix}, F::CholeskyPivoted) - ip = invperm(F[:p]) - (F[:L] * F[:U])[ip,ip] -end -convert(::Type{AbstractArray}, F::CholeskyPivoted) = convert(AbstractMatrix, F) -convert(::Type{Matrix}, F::CholeskyPivoted) = convert(Array, convert(AbstractArray, F)) -convert(::Type{Array}, F::CholeskyPivoted) = convert(Matrix, F) -full(F::CholeskyPivoted) = convert(AbstractArray, F) - -copy(C::Cholesky) = Cholesky(copy(C.factors), C.uplo) -copy(C::CholeskyPivoted) = CholeskyPivoted(copy(C.factors), C.uplo, C.piv, C.rank, C.tol, C.info) - -size(C::Union{Cholesky, CholeskyPivoted}) = size(C.factors) -size(C::Union{Cholesky, CholeskyPivoted}, d::Integer) = size(C.factors, d) - -function getindex(C::Cholesky, d::Symbol) - d == :U && return UpperTriangular(Symbol(C.uplo) == d ? C.factors : C.factors') - d == :L && return LowerTriangular(Symbol(C.uplo) == d ? C.factors : C.factors') - d == :UL && return Symbol(C.uplo) == :U ? UpperTriangular(C.factors) : LowerTriangular(C.factors) - throw(KeyError(d)) -end -function getindex(C::CholeskyPivoted{T}, d::Symbol) where T<:BlasFloat - d == :U && return UpperTriangular(Symbol(C.uplo) == d ? C.factors : C.factors') - d == :L && return LowerTriangular(Symbol(C.uplo) == d ? C.factors : C.factors') - d == :p && return C.piv - if d == :P - n = size(C, 1) - P = zeros(T, n, n) - for i = 1:n - P[C.piv[i],i] = one(T) - end - return P - end - throw(KeyError(d)) -end - -show(io::IO, C::Cholesky{<:Any,<:AbstractMatrix}) = - (println(io, "$(typeof(C)) with factor:");show(io,C[:UL])) - -A_ldiv_B!(C::Cholesky{T,<:AbstractMatrix}, B::StridedVecOrMat{T}) where {T<:BlasFloat} = - LAPACK.potrs!(C.uplo, C.factors, B) - -function A_ldiv_B!(C::Cholesky{<:Any,<:AbstractMatrix}, B::StridedVecOrMat) - if C.uplo == 'L' - return Ac_ldiv_B!(LowerTriangular(C.factors), A_ldiv_B!(LowerTriangular(C.factors), B)) - else - return A_ldiv_B!(UpperTriangular(C.factors), Ac_ldiv_B!(UpperTriangular(C.factors), B)) - end -end - -function A_ldiv_B!(C::CholeskyPivoted{T}, B::StridedVector{T}) where T<:BlasFloat - chkfullrank(C) - ipermute!(LAPACK.potrs!(C.uplo, C.factors, permute!(B, C.piv)), C.piv) -end -function A_ldiv_B!(C::CholeskyPivoted{T}, B::StridedMatrix{T}) where T<:BlasFloat - chkfullrank(C) - n = size(C, 1) - for i=1:size(B, 2) - permute!(view(B, 1:n, i), C.piv) - end - LAPACK.potrs!(C.uplo, C.factors, B) - for i=1:size(B, 2) - ipermute!(view(B, 1:n, i), C.piv) - end - B -end - -function A_ldiv_B!(C::CholeskyPivoted, B::StridedVector) - if C.uplo == 'L' - Ac_ldiv_B!(LowerTriangular(C.factors), - A_ldiv_B!(LowerTriangular(C.factors), B[C.piv]))[invperm(C.piv)] - else - A_ldiv_B!(UpperTriangular(C.factors), - Ac_ldiv_B!(UpperTriangular(C.factors), B[C.piv]))[invperm(C.piv)] - end -end - -function A_ldiv_B!(C::CholeskyPivoted, B::StridedMatrix) - if C.uplo == 'L' - Ac_ldiv_B!(LowerTriangular(C.factors), - A_ldiv_B!(LowerTriangular(C.factors), B[C.piv,:]))[invperm(C.piv),:] - else - A_ldiv_B!(UpperTriangular(C.factors), - Ac_ldiv_B!(UpperTriangular(C.factors), B[C.piv,:]))[invperm(C.piv),:] - end -end - -function det(C::Cholesky) - dd = one(real(eltype(C))) - for i in 1:size(C.factors,1) - dd *= real(C.factors[i,i])^2 - end - dd -end - -function logdet(C::Cholesky) - dd = zero(real(eltype(C))) - for i in 1:size(C.factors,1) - dd += log(real(C.factors[i,i])) - end - dd + dd # instead of 2.0dd which can change the type -end - -function det(C::CholeskyPivoted) - if C.rank < size(C.factors, 1) - return zero(real(eltype(C))) - else - dd = one(real(eltype(C))) - for i in 1:size(C.factors,1) - dd *= real(C.factors[i,i])^2 - end - return dd - end -end - -function logdet(C::CholeskyPivoted) - if C.rank < size(C.factors, 1) - return real(eltype(C))(-Inf) - else - dd = zero(real(eltype(C))) - for i in 1:size(C.factors,1) - dd += log(real(C.factors[i,i])) - end - return dd + dd # instead of 2.0dd which can change the type - end -end - -inv!(C::Cholesky{<:BlasFloat,<:StridedMatrix}) = - copytri!(LAPACK.potri!(C.uplo, C.factors), C.uplo, true) - -inv(C::Cholesky{<:BlasFloat,<:StridedMatrix}) = - inv!(copy(C)) - -function inv(C::CholeskyPivoted) - chkfullrank(C) - ipiv = invperm(C.piv) - copytri!(LAPACK.potri!(C.uplo, copy(C.factors)), C.uplo, true)[ipiv, ipiv] -end - -function chkfullrank(C::CholeskyPivoted) - if C.rank < size(C.factors, 1) - throw(RankDeficientException(C.info)) - end -end - -rank(C::CholeskyPivoted) = C.rank - -""" - lowrankupdate!(C::Cholesky, v::StridedVector) -> CC::Cholesky - -Update a Cholesky factorization `C` with the vector `v`. If `A = C[:U]'C[:U]` then -`CC = cholfact(C[:U]'C[:U] + v*v')` but the computation of `CC` only uses `O(n^2)` -operations. The input factorization `C` is updated in place such that on exit `C == CC`. -The vector `v` is destroyed during the computation. -""" -function lowrankupdate!(C::Cholesky, v::StridedVector) - A = C.factors - n = length(v) - if size(C, 1) != n - throw(DimensionMismatch("updating vector must fit size of factorization")) - end - if C.uplo == 'U' - conj!(v) - end - - for i = 1:n - - # Compute Givens rotation - c, s, r = givensAlgorithm(A[i,i], v[i]) - - # Store new diagonal element - A[i,i] = r - - # Update remaining elements in row/column - if C.uplo == 'U' - for j = i + 1:n - Aij = A[i,j] - vj = v[j] - A[i,j] = c*Aij + s*vj - v[j] = -s'*Aij + c*vj - end - else - for j = i + 1:n - Aji = A[j,i] - vj = v[j] - A[j,i] = c*Aji + s*vj - v[j] = -s'*Aji + c*vj - end - end - end - return C -end - -""" - lowrankdowndate!(C::Cholesky, v::StridedVector) -> CC::Cholesky - -Downdate a Cholesky factorization `C` with the vector `v`. If `A = C[:U]'C[:U]` then -`CC = cholfact(C[:U]'C[:U] - v*v')` but the computation of `CC` only uses `O(n^2)` -operations. The input factorization `C` is updated in place such that on exit `C == CC`. -The vector `v` is destroyed during the computation. -""" -function lowrankdowndate!(C::Cholesky, v::StridedVector) - A = C.factors - n = length(v) - if size(C, 1) != n - throw(DimensionMismatch("updating vector must fit size of factorization")) - end - if C.uplo == 'U' - conj!(v) - end - - for i = 1:n - - Aii = A[i,i] - - # Compute Givens rotation - s = conj(v[i]/Aii) - s2 = abs2(s) - if s2 > 1 - throw(LinAlg.PosDefException(i)) - end - c = sqrt(1 - abs2(s)) - - # Store new diagonal element - A[i,i] = c*Aii - - # Update remaining elements in row/column - if C.uplo == 'U' - for j = i + 1:n - vj = v[j] - Aij = (A[i,j] - s*vj)/c - A[i,j] = Aij - v[j] = -s'*Aij + c*vj - end - else - for j = i + 1:n - vj = v[j] - Aji = (A[j,i] - s*vj)/c - A[j,i] = Aji - v[j] = -s'*Aji + c*vj - end - end - end - return C -end - -""" - lowrankupdate(C::Cholesky, v::StridedVector) -> CC::Cholesky - -Update a Cholesky factorization `C` with the vector `v`. If `A = C[:U]'C[:U]` -then `CC = cholfact(C[:U]'C[:U] + v*v')` but the computation of `CC` only uses -`O(n^2)` operations. -""" -lowrankupdate(C::Cholesky, v::StridedVector) = lowrankupdate!(copy(C), copy(v)) - -""" - lowrankdowndate(C::Cholesky, v::StridedVector) -> CC::Cholesky - -Downdate a Cholesky factorization `C` with the vector `v`. If `A = C[:U]'C[:U]` -then `CC = cholfact(C[:U]'C[:U] - v*v')` but the computation of `CC` only uses -`O(n^2)` operations. -""" -lowrankdowndate(C::Cholesky, v::StridedVector) = lowrankdowndate!(copy(C), copy(v)) diff --git a/julia-0.6.3/share/julia/base/linalg/conjarray.jl b/julia-0.6.3/share/julia/base/linalg/conjarray.jl deleted file mode 100644 index e7dc4b4..0000000 --- a/julia-0.6.3/share/julia/base/linalg/conjarray.jl +++ /dev/null @@ -1,62 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -""" - ConjArray(array) - -A lazy-view wrapper of an `AbstractArray`, taking the elementwise complex conjugate. This -type is usually constructed (and unwrapped) via the [`conj`](@ref) function (or related -[`ctranspose`](@ref)), but currently this is the default behavior for `RowVector` only. For -other arrays, the `ConjArray` constructor can be used directly. - -# Examples - -```jldoctest -julia> [1+im, 1-im]' -1×2 RowVector{Complex{Int64},ConjArray{Complex{Int64},1,Array{Complex{Int64},1}}}: - 1-1im 1+1im - -julia> ConjArray([1+im 0; 0 1-im]) -2×2 ConjArray{Complex{Int64},2,Array{Complex{Int64},2}}: - 1-1im 0+0im - 0+0im 1+1im -``` -""" -struct ConjArray{T,N,A<:AbstractArray} <: AbstractArray{T,N} - parent::A -end - -@inline ConjArray(a::AbstractArray{T,N}) where {T,N} = ConjArray{conj_type(T),N,typeof(a)}(a) - -const ConjVector{T,V<:AbstractVector} = ConjArray{T,1,V} -@inline ConjVector(v::AbstractVector{T}) where {T} = ConjArray{conj_type(T),1,typeof(v)}(v) - -const ConjMatrix{T,M<:AbstractMatrix} = ConjArray{T,2,M} -@inline ConjMatrix(m::AbstractMatrix{T}) where {T} = ConjArray{conj_type(T),2,typeof(m)}(m) - -# This type can cause the element type to change under conjugation - e.g. an array of complex arrays. -@inline conj_type(x) = conj_type(typeof(x)) -@inline conj_type(::Type{T}) where {T} = promote_op(conj, T) - -@inline parent(c::ConjArray) = c.parent -@inline parent_type(c::ConjArray) = parent_type(typeof(c)) -@inline parent_type(::Type{ConjArray{T,N,A}}) where {T,N,A} = A - -@inline size(a::ConjArray) = size(a.parent) -IndexStyle(::CA) where {CA<:ConjArray} = IndexStyle(parent_type(CA)) -IndexStyle(::Type{CA}) where {CA<:ConjArray} = IndexStyle(parent_type(CA)) - -@propagate_inbounds getindex(a::ConjArray{T,N}, i::Int) where {T,N} = conj(getindex(a.parent, i)) -@propagate_inbounds getindex(a::ConjArray{T,N}, i::Vararg{Int,N}) where {T,N} = conj(getindex(a.parent, i...)) -@propagate_inbounds setindex!(a::ConjArray{T,N}, v, i::Int) where {T,N} = setindex!(a.parent, conj(v), i) -@propagate_inbounds setindex!(a::ConjArray{T,N}, v, i::Vararg{Int,N}) where {T,N} = setindex!(a.parent, conj(v), i...) - -@inline similar(a::ConjArray, ::Type{T}, dims::Dims{N}) where {T,N} = similar(parent(a), T, dims) - -# Currently, this is default behavior for RowVector only -@inline conj(a::ConjArray) = parent(a) - -# Helper functions, currently used by RowVector -@inline _conj(a::AbstractArray) = ConjArray(a) -@inline _conj(a::AbstractArray{T}) where {T<:Real} = a -@inline _conj(a::ConjArray) = parent(a) -@inline _conj(a::ConjArray{T}) where {T<:Real} = parent(a) diff --git a/julia-0.6.3/share/julia/base/linalg/dense.jl b/julia-0.6.3/share/julia/base/linalg/dense.jl deleted file mode 100644 index 1c4a3f4..0000000 --- a/julia-0.6.3/share/julia/base/linalg/dense.jl +++ /dev/null @@ -1,961 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -# Linear algebra functions for dense matrices in column major format - -## BLAS cutoff threshold constants - -const SCAL_CUTOFF = 2048 -const DOT_CUTOFF = 128 -const ASUM_CUTOFF = 32 -const NRM2_CUTOFF = 32 - -function scale!(X::Array{T}, s::T) where T<:BlasFloat - s == 0 && return fill!(X, zero(T)) - s == 1 && return X - if length(X) < SCAL_CUTOFF - generic_scale!(X, s) - else - BLAS.scal!(length(X), s, X, 1) - end - X -end - -scale!(s::T, X::Array{T}) where {T<:BlasFloat} = scale!(X, s) - -scale!(X::Array{T}, s::Number) where {T<:BlasFloat} = scale!(X, convert(T, s)) -function scale!(X::Array{T}, s::Real) where T<:BlasComplex - R = typeof(real(zero(T))) - BLAS.scal!(2*length(X), convert(R,s), convert(Ptr{R},pointer(X)), 1) - X -end - -# Test whether a matrix is positive-definite -isposdef!(A::StridedMatrix{<:BlasFloat}, UL::Symbol) = LAPACK.potrf!(char_uplo(UL), A)[2] == 0 - -""" - isposdef!(A) -> Bool - -Test whether a matrix is positive definite, overwriting `A` in the process. - -# Example - -```jldoctest -julia> A = [1. 2.; 2. 50.]; - -julia> isposdef!(A) -true - -julia> A -2×2 Array{Float64,2}: - 1.0 2.0 - 2.0 6.78233 -``` -""" -isposdef!(A::StridedMatrix) = ishermitian(A) && isposdef!(A, :U) - -function isposdef(A::AbstractMatrix{T}, UL::Symbol) where T - S = typeof(sqrt(one(T))) - isposdef!(S == T ? copy(A) : convert(AbstractMatrix{S}, A), UL) -end -""" - isposdef(A) -> Bool - -Test whether a matrix is positive definite. - -# Example - -```jldoctest -julia> A = [1 2; 2 50] -2×2 Array{Int64,2}: - 1 2 - 2 50 - -julia> isposdef(A) -true -``` -""" -function isposdef(A::AbstractMatrix{T}) where T - S = typeof(sqrt(one(T))) - isposdef!(S == T ? copy(A) : convert(AbstractMatrix{S}, A)) -end -isposdef(x::Number) = imag(x)==0 && real(x) > 0 - -stride1(x::Array) = 1 -stride1(x::StridedVector) = stride(x, 1)::Int - -function norm(x::StridedVector{T}, rx::Union{UnitRange{TI},Range{TI}}) where {T<:BlasFloat,TI<:Integer} - if minimum(rx) < 1 || maximum(rx) > length(x) - throw(BoundsError(x, rx)) - end - BLAS.nrm2(length(rx), pointer(x)+(first(rx)-1)*sizeof(T), step(rx)) -end - -vecnorm1(x::Union{Array{T},StridedVector{T}}) where {T<:BlasReal} = - length(x) < ASUM_CUTOFF ? generic_vecnorm1(x) : BLAS.asum(x) - -vecnorm2(x::Union{Array{T},StridedVector{T}}) where {T<:BlasFloat} = - length(x) < NRM2_CUTOFF ? generic_vecnorm2(x) : BLAS.nrm2(x) - -""" - triu!(M, k::Integer) - -Returns the upper triangle of `M` starting from the `k`th superdiagonal, -overwriting `M` in the process. - -# Example -```jldoctest -julia> M = [1 2 3 4 5; 1 2 3 4 5; 1 2 3 4 5; 1 2 3 4 5; 1 2 3 4 5] -5×5 Array{Int64,2}: - 1 2 3 4 5 - 1 2 3 4 5 - 1 2 3 4 5 - 1 2 3 4 5 - 1 2 3 4 5 - -julia> triu!(M, 1) -5×5 Array{Int64,2}: - 0 2 3 4 5 - 0 0 3 4 5 - 0 0 0 4 5 - 0 0 0 0 5 - 0 0 0 0 0 -``` -""" -function triu!(M::AbstractMatrix, k::Integer) - m, n = size(M) - if (k > 0 && k > n) || (k < 0 && -k > m) - throw(ArgumentError("requested diagonal, $k, out of bounds in matrix of size ($m,$n)")) - end - idx = 1 - for j = 0:n-1 - ii = min(max(0, j+1-k), m) - for i = (idx+ii):(idx+m-1) - M[i] = zero(M[i]) - end - idx += m - end - M -end - -triu(M::Matrix, k::Integer) = triu!(copy(M), k) - -""" - tril!(M, k::Integer) - -Returns the lower triangle of `M` starting from the `k`th superdiagonal, overwriting `M` in -the process. - -# Example - -```jldoctest -julia> M = [1 2 3 4 5; 1 2 3 4 5; 1 2 3 4 5; 1 2 3 4 5; 1 2 3 4 5] -5×5 Array{Int64,2}: - 1 2 3 4 5 - 1 2 3 4 5 - 1 2 3 4 5 - 1 2 3 4 5 - 1 2 3 4 5 - -julia> tril!(M, 2) -5×5 Array{Int64,2}: - 1 2 3 0 0 - 1 2 3 4 0 - 1 2 3 4 5 - 1 2 3 4 5 - 1 2 3 4 5 -``` -""" -function tril!(M::AbstractMatrix, k::Integer) - m, n = size(M) - if (k > 0 && k > n) || (k < 0 && -k > m) - throw(ArgumentError("requested diagonal, $k, out of bounds in matrix of size ($m,$n)")) - end - idx = 1 - for j = 0:n-1 - ii = min(max(0, j-k), m) - for i = idx:(idx+ii-1) - M[i] = zero(M[i]) - end - idx += m - end - M -end -tril(M::Matrix, k::Integer) = tril!(copy(M), k) - -function gradient(F::AbstractVector, h::Vector) - n = length(F) - T = typeof(oneunit(eltype(F))/oneunit(eltype(h))) - g = similar(F, T) - if n == 1 - g[1] = zero(T) - elseif n > 1 - g[1] = (F[2] - F[1]) / (h[2] - h[1]) - g[n] = (F[n] - F[n-1]) / (h[end] - h[end-1]) - if n > 2 - h = h[3:n] - h[1:n-2] - g[2:n-1] = (F[3:n] - F[1:n-2]) ./ h - end - end - g -end - -function diagind(m::Integer, n::Integer, k::Integer=0) - if !(-m <= k <= n) - throw(ArgumentError("requested diagonal, $k, out of bounds in matrix of size ($m,$n)")) - end - k <= 0 ? range(1-k, m+1, min(m+k, n)) : range(k*m+1, m+1, min(m, n-k)) -end - -""" - diagind(M, k::Integer=0) - -A `Range` giving the indices of the `k`th diagonal of the matrix `M`. - -# Example - -```jldoctest -julia> A = [1 2 3; 4 5 6; 7 8 9] -3×3 Array{Int64,2}: - 1 2 3 - 4 5 6 - 7 8 9 - -julia> diagind(A,-1) -2:4:6 -``` -""" -diagind(A::AbstractMatrix, k::Integer=0) = diagind(size(A,1), size(A,2), k) - -""" - diag(M, k::Integer=0) - -The `k`th diagonal of a matrix, as a vector. -Use [`diagm`](@ref) to construct a diagonal matrix. - -# Example - -```jldoctest -julia> A = [1 2 3; 4 5 6; 7 8 9] -3×3 Array{Int64,2}: - 1 2 3 - 4 5 6 - 7 8 9 - -julia> diag(A,1) -2-element Array{Int64,1}: - 2 - 6 -``` -""" -diag(A::AbstractMatrix, k::Integer=0) = A[diagind(A,k)] - -""" - diagm(v, k::Integer=0) - -Construct a matrix by placing `v` on the `k`th diagonal. - -# Example - -```jldoctest -julia> diagm([1,2,3],1) -4×4 Array{Int64,2}: - 0 1 0 0 - 0 0 2 0 - 0 0 0 3 - 0 0 0 0 -``` -""" -function diagm(v::AbstractVector{T}, k::Integer=0) where T - n = length(v) + abs(k) - A = zeros(T,n,n) - A[diagind(A,k)] = v - A -end - -diagm(x::Number) = (X = Matrix{typeof(x)}(1,1); X[1,1] = x; X) - -function trace(A::Matrix{T}) where T - n = checksquare(A) - t = zero(T) - for i=1:n - t += A[i,i] - end - t -end - -""" - kron(A, B) - -Kronecker tensor product of two vectors or two matrices. - -# Example - -```jldoctest -julia> A = [1 2; 3 4] -2×2 Array{Int64,2}: - 1 2 - 3 4 - -julia> B = [im 1; 1 -im] -2×2 Array{Complex{Int64},2}: - 0+1im 1+0im - 1+0im 0-1im - -julia> kron(A, B) -4×4 Array{Complex{Int64},2}: - 0+1im 1+0im 0+2im 2+0im - 1+0im 0-1im 2+0im 0-2im - 0+3im 3+0im 0+4im 4+0im - 3+0im 0-3im 4+0im 0-4im -``` -""" -function kron(a::AbstractMatrix{T}, b::AbstractMatrix{S}) where {T,S} - R = Matrix{promote_op(*,T,S)}(size(a,1)*size(b,1), size(a,2)*size(b,2)) - m = 1 - for j = 1:size(a,2), l = 1:size(b,2), i = 1:size(a,1) - aij = a[i,j] - for k = 1:size(b,1) - R[m] = aij*b[k,l] - m += 1 - end - end - R -end - -kron(a::Number, b::Union{Number, AbstractVecOrMat}) = a * b -kron(a::AbstractVecOrMat, b::Number) = a * b -kron(a::AbstractVector, b::AbstractVector) = vec(kron(reshape(a ,length(a), 1), reshape(b, length(b), 1))) -kron(a::AbstractMatrix, b::AbstractVector) = kron(a, reshape(b, length(b), 1)) -kron(a::AbstractVector, b::AbstractMatrix) = kron(reshape(a, length(a), 1), b) - -# Matrix power -(^)(A::AbstractMatrix{T}, p::Integer) where {T} = p < 0 ? Base.power_by_squaring(inv(A), -p) : Base.power_by_squaring(A, p) -function (^)(A::AbstractMatrix{T}, p::Real) where T - # For integer powers, use repeated squaring - if isinteger(p) - TT = Base.promote_op(^, eltype(A), typeof(p)) - return (TT == eltype(A) ? A : copy!(similar(A, TT), A))^Integer(p) - end - - # If possible, use diagonalization - if T <: Real && issymmetric(A) - return (Symmetric(A)^p) - end - if ishermitian(A) - return (Hermitian(A)^p) - end - - n = checksquare(A) - - # Quicker return if A is diagonal - if isdiag(A) - retmat = copy(A) - for i in 1:n - retmat[i, i] = retmat[i, i] ^ p - end - return retmat - end - - # Otherwise, use Schur decomposition - if istriu(A) - # Integer part - retmat = A ^ floor(p) - # Real part - if p - floor(p) == 0.5 - # special case: A^0.5 === sqrtm(A) - retmat = retmat * sqrtm(A) - else - retmat = retmat * powm!(UpperTriangular(float.(A)), real(p - floor(p))) - end - else - S,Q,d = schur(complex(A)) - # Integer part - R = S ^ floor(p) - # Real part - if p - floor(p) == 0.5 - # special case: A^0.5 === sqrtm(A) - R = R * sqrtm(S) - else - R = R * powm!(UpperTriangular(float.(S)), real(p - floor(p))) - end - retmat = Q * R * Q' - end - - # if A has nonpositive real eigenvalues, retmat is a nonprincipal matrix power. - if isreal(retmat) - return real(retmat) - else - return retmat - end -end -(^)(A::AbstractMatrix, p::Number) = expm(p*logm(A)) - -# Matrix exponential - -""" - expm(A) - -Compute the matrix exponential of `A`, defined by - -```math -e^A = \\sum_{n=0}^{\\infty} \\frac{A^n}{n!}. -``` - -For symmetric or Hermitian `A`, an eigendecomposition ([`eigfact`](@ref)) is -used, otherwise the scaling and squaring algorithm (see [^H05]) is chosen. - -[^H05]: Nicholas J. Higham, "The squaring and scaling method for the matrix exponential revisited", SIAM Journal on Matrix Analysis and Applications, 26(4), 2005, 1179-1193. [doi:10.1137/090768539](http://dx.doi.org/10.1137/090768539) - -# Example - -```jldoctest -julia> A = eye(2, 2) -2×2 Array{Float64,2}: - 1.0 0.0 - 0.0 1.0 - -julia> expm(A) -2×2 Array{Float64,2}: - 2.71828 0.0 - 0.0 2.71828 -``` -""" -expm(A::StridedMatrix{<:BlasFloat}) = expm!(copy(A)) -expm(A::StridedMatrix{<:Integer}) = expm!(float(A)) -expm(x::Number) = exp(x) - -## Destructive matrix exponential using algorithm from Higham, 2008, -## "Functions of Matrices: Theory and Computation", SIAM -function expm!(A::StridedMatrix{T}) where T<:BlasFloat - n = checksquare(A) - if ishermitian(A) - return full(expm(Hermitian(A))) - end - ilo, ihi, scale = LAPACK.gebal!('B', A) # modifies A - nA = norm(A, 1) - I = eye(T,n) - ## For sufficiently small nA, use lower order Padé-Approximations - if (nA <= 2.1) - if nA > 0.95 - C = T[17643225600.,8821612800.,2075673600.,302702400., - 30270240., 2162160., 110880., 3960., - 90., 1.] - elseif nA > 0.25 - C = T[17297280.,8648640.,1995840.,277200., - 25200., 1512., 56., 1.] - elseif nA > 0.015 - C = T[30240.,15120.,3360., - 420., 30., 1.] - else - C = T[120.,60.,12.,1.] - end - A2 = A * A - P = copy(I) - U = C[2] * P - V = C[1] * P - for k in 1:(div(size(C, 1), 2) - 1) - k2 = 2 * k - P *= A2 - U += C[k2 + 2] * P - V += C[k2 + 1] * P - end - U = A * U - X = V + U - LAPACK.gesv!(V-U, X) - else - s = log2(nA/5.4) # power of 2 later reversed by squaring - if s > 0 - si = ceil(Int,s) - A /= convert(T,2^si) - end - CC = T[64764752532480000.,32382376266240000.,7771770303897600., - 1187353796428800., 129060195264000., 10559470521600., - 670442572800., 33522128640., 1323241920., - 40840800., 960960., 16380., - 182., 1.] - A2 = A * A - A4 = A2 * A2 - A6 = A2 * A4 - U = A * (A6 * (CC[14]*A6 + CC[12]*A4 + CC[10]*A2) + - CC[8]*A6 + CC[6]*A4 + CC[4]*A2 + CC[2]*I) - V = A6 * (CC[13]*A6 + CC[11]*A4 + CC[9]*A2) + - CC[7]*A6 + CC[5]*A4 + CC[3]*A2 + CC[1]*I - - X = V + U - LAPACK.gesv!(V-U, X) - - if s > 0 # squaring to reverse dividing by power of 2 - for t=1:si; X *= X end - end - end - - # Undo the balancing - for j = ilo:ihi - scj = scale[j] - for i = 1:n - X[j,i] *= scj - end - for i = 1:n - X[i,j] /= scj - end - end - - if ilo > 1 # apply lower permutations in reverse order - for j in (ilo-1):-1:1; rcswap!(j, Int(scale[j]), X) end - end - if ihi < n # apply upper permutations in forward order - for j in (ihi+1):n; rcswap!(j, Int(scale[j]), X) end - end - X -end - -## Swap rows i and j and columns i and j in X -function rcswap!(i::Integer, j::Integer, X::StridedMatrix{<:Number}) - for k = 1:size(X,1) - X[k,i], X[k,j] = X[k,j], X[k,i] - end - for k = 1:size(X,2) - X[i,k], X[j,k] = X[j,k], X[i,k] - end -end - -""" - logm(A{T}::StridedMatrix{T}) - -If `A` has no negative real eigenvalue, compute the principal matrix logarithm of `A`, i.e. -the unique matrix ``X`` such that ``e^X = A`` and ``-\\pi < Im(\\lambda) < \\pi`` for all -the eigenvalues ``\\lambda`` of ``X``. If `A` has nonpositive eigenvalues, a nonprincipal -matrix function is returned whenever possible. - -If `A` is symmetric or Hermitian, its eigendecomposition ([`eigfact`](@ref)) is -used, if `A` is triangular an improved version of the inverse scaling and squaring method is -employed (see [^AH12] and [^AHR13]). For general matrices, the complex Schur form -([`schur`](@ref)) is computed and the triangular algorithm is used on the -triangular factor. - -[^AH12]: Awad H. Al-Mohy and Nicholas J. Higham, "Improved inverse scaling and squaring algorithms for the matrix logarithm", SIAM Journal on Scientific Computing, 34(4), 2012, C153-C169. [doi:10.1137/110852553](http://dx.doi.org/10.1137/110852553) - -[^AHR13]: Awad H. Al-Mohy, Nicholas J. Higham and Samuel D. Relton, "Computing the Fréchet derivative of the matrix logarithm and estimating the condition number", SIAM Journal on Scientific Computing, 35(4), 2013, C394-C410. [doi:10.1137/120885991](http://dx.doi.org/10.1137/120885991) - -# Example - -```jldoctest -julia> A = 2.7182818 * eye(2) -2×2 Array{Float64,2}: - 2.71828 0.0 - 0.0 2.71828 - -julia> logm(A) -2×2 Symmetric{Float64,Array{Float64,2}}: - 1.0 0.0 - 0.0 1.0 -``` -""" -function logm(A::StridedMatrix{T}) where T - # If possible, use diagonalization - if issymmetric(A) && T <: Real - return logm(Symmetric(A)) - end - if ishermitian(A) - return logm(Hermitian(A)) - end - - # Use Schur decomposition - n = checksquare(A) - if istriu(A) - return full(logm(UpperTriangular(complex(A)))) - else - if isreal(A) - SchurF = schurfact(real(A)) - else - SchurF = schurfact(A) - end - if !istriu(SchurF.T) - SchurS = schurfact(complex(SchurF.T)) - logT = SchurS.Z * logm(UpperTriangular(SchurS.T)) * SchurS.Z' - return SchurF.Z * logT * SchurF.Z' - else - R = logm(UpperTriangular(complex(SchurF.T))) - return SchurF.Z * R * SchurF.Z' - end - end -end -function logm(a::Number) - b = log(complex(a)) - return imag(b) == 0 ? real(b) : b -end -logm(a::Complex) = log(a) - -""" - sqrtm(A) - -If `A` has no negative real eigenvalues, compute the principal matrix square root of `A`, -that is the unique matrix ``X`` with eigenvalues having positive real part such that -``X^2 = A``. Otherwise, a nonprincipal square root is returned. - -If `A` is symmetric or Hermitian, its eigendecomposition ([`eigfact`](@ref)) is -used to compute the square root. Otherwise, the square root is determined by means of the -Björck-Hammarling method [^BH83], which computes the complex Schur form ([`schur`](@ref)) -and then the complex square root of the triangular factor. - -[^BH83]: - - Åke Björck and Sven Hammarling, "A Schur method for the square root of a matrix", - Linear Algebra and its Applications, 52-53, 1983, 127-140. - [doi:10.1016/0024-3795(83)80010-X](http://dx.doi.org/10.1016/0024-3795(83)80010-X) - -# Example - -```jldoctest -julia> A = [4 0; 0 4] -2×2 Array{Int64,2}: - 4 0 - 0 4 - -julia> sqrtm(A) -2×2 Array{Float64,2}: - 2.0 0.0 - 0.0 2.0 -``` -""" -function sqrtm(A::StridedMatrix{<:Real}) - if issymmetric(A) - return full(sqrtm(Symmetric(A))) - end - n = checksquare(A) - if istriu(A) - return full(sqrtm(UpperTriangular(A))) - else - SchurF = schurfact(complex(A)) - R = full(sqrtm(UpperTriangular(SchurF[:T]))) - return SchurF[:vectors] * R * SchurF[:vectors]' - end -end -function sqrtm(A::StridedMatrix{<:Complex}) - if ishermitian(A) - return full(sqrtm(Hermitian(A))) - end - n = checksquare(A) - if istriu(A) - return full(sqrtm(UpperTriangular(A))) - else - SchurF = schurfact(A) - R = full(sqrtm(UpperTriangular(SchurF[:T]))) - return SchurF[:vectors] * R * SchurF[:vectors]' - end -end -sqrtm(a::Number) = (b = sqrt(complex(a)); imag(b) == 0 ? real(b) : b) -sqrtm(a::Complex) = sqrt(a) - -function inv(A::StridedMatrix{T}) where T - checksquare(A) - S = typeof((one(T)*zero(T) + one(T)*zero(T))/one(T)) - AA = convert(AbstractArray{S}, A) - if istriu(AA) - Ai = inv(UpperTriangular(AA)) - elseif istril(AA) - Ai = inv(LowerTriangular(AA)) - else - Ai = inv(lufact(AA)) - end - return convert(typeof(parent(Ai)), Ai) -end - -""" - factorize(A) - -Compute a convenient factorization of `A`, based upon the type of the input matrix. -`factorize` checks `A` to see if it is symmetric/triangular/etc. if `A` is passed -as a generic matrix. `factorize` checks every element of `A` to verify/rule out -each property. It will short-circuit as soon as it can rule out symmetry/triangular -structure. The return value can be reused for efficient solving of multiple -systems. For example: `A=factorize(A); x=A\\b; y=A\\C`. - -| Properties of `A` | type of factorization | -|:---------------------------|:-----------------------------------------------| -| Positive-definite | Cholesky (see [`cholfact`](@ref)) | -| Dense Symmetric/Hermitian | Bunch-Kaufman (see [`bkfact`](@ref)) | -| Sparse Symmetric/Hermitian | LDLt (see [`ldltfact`](@ref)) | -| Triangular | Triangular | -| Diagonal | Diagonal | -| Bidiagonal | Bidiagonal | -| Tridiagonal | LU (see [`lufact`](@ref)) | -| Symmetric real tridiagonal | LDLt (see [`ldltfact`](@ref)) | -| General square | LU (see [`lufact`](@ref)) | -| General non-square | QR (see [`qrfact`](@ref)) | - -If `factorize` is called on a Hermitian positive-definite matrix, for instance, then `factorize` -will return a Cholesky factorization. - -# Example - -```jldoctest -julia> A = Array(Bidiagonal(ones(5, 5), true)) -5×5 Array{Float64,2}: - 1.0 1.0 0.0 0.0 0.0 - 0.0 1.0 1.0 0.0 0.0 - 0.0 0.0 1.0 1.0 0.0 - 0.0 0.0 0.0 1.0 1.0 - 0.0 0.0 0.0 0.0 1.0 - -julia> factorize(A) # factorize will check to see that A is already factorized -5×5 Bidiagonal{Float64}: - 1.0 1.0 ⋅ ⋅ ⋅ - ⋅ 1.0 1.0 ⋅ ⋅ - ⋅ ⋅ 1.0 1.0 ⋅ - ⋅ ⋅ ⋅ 1.0 1.0 - ⋅ ⋅ ⋅ ⋅ 1.0 -``` -This returns a `5×5 Bidiagonal{Float64}`, which can now be passed to other linear algebra functions -(e.g. eigensolvers) which will use specialized methods for `Bidiagonal` types. -""" -function factorize(A::StridedMatrix{T}) where T - m, n = size(A) - if m == n - if m == 1 return A[1] end - utri = true - utri1 = true - herm = true - sym = true - for j = 1:n-1, i = j+1:m - if utri1 - if A[i,j] != 0 - utri1 = i == j + 1 - utri = false - end - end - if sym - sym &= A[i,j] == A[j,i] - end - if herm - herm &= A[i,j] == conj(A[j,i]) - end - if !(utri1|herm|sym) break end - end - ltri = true - ltri1 = true - for j = 3:n, i = 1:j-2 - ltri1 &= A[i,j] == 0 - if !ltri1 break end - end - if ltri1 - for i = 1:n-1 - if A[i,i+1] != 0 - ltri &= false - break - end - end - if ltri - if utri - return Diagonal(A) - end - if utri1 - return Bidiagonal(diag(A), diag(A, -1), false) - end - return LowerTriangular(A) - end - if utri - return Bidiagonal(diag(A), diag(A, 1), true) - end - if utri1 - if (herm & (T <: Complex)) | sym - try - return ldltfact!(SymTridiagonal(diag(A), diag(A, -1))) - end - end - return lufact(Tridiagonal(diag(A, -1), diag(A), diag(A, 1))) - end - end - if utri - return UpperTriangular(A) - end - if herm - try - return cholfact(A) - end - return factorize(Hermitian(A)) - end - if sym - return factorize(Symmetric(A)) - end - return lufact(A) - end - qrfact(A, Val{true}) -end - -## Moore-Penrose pseudoinverse - -""" - pinv(M[, tol::Real]) - -Computes the Moore-Penrose pseudoinverse. - -For matrices `M` with floating point elements, it is convenient to compute -the pseudoinverse by inverting only singular values above a given threshold, -`tol`. - -The optimal choice of `tol` varies both with the value of `M` and the intended application -of the pseudoinverse. The default value of `tol` is -`eps(real(float(one(eltype(M)))))*maximum(size(A))`, which is essentially machine epsilon -for the real part of a matrix element multiplied by the larger matrix dimension. For -inverting dense ill-conditioned matrices in a least-squares sense, -`tol = sqrt(eps(real(float(one(eltype(M))))))` is recommended. - -For more information, see [^issue8859], [^B96], [^S84], [^KY88]. - -# Example - -```jldoctest -julia> M = [1.5 1.3; 1.2 1.9] -2×2 Array{Float64,2}: - 1.5 1.3 - 1.2 1.9 - -julia> N = pinv(M) -2×2 Array{Float64,2}: - 1.47287 -1.00775 - -0.930233 1.16279 - -julia> M * N -2×2 Array{Float64,2}: - 1.0 -2.22045e-16 - 4.44089e-16 1.0 -``` - -[^issue8859]: Issue 8859, "Fix least squares", https://github.com/JuliaLang/julia/pull/8859 - -[^B96]: Åke Björck, "Numerical Methods for Least Squares Problems", SIAM Press, Philadelphia, 1996, "Other Titles in Applied Mathematics", Vol. 51. [doi:10.1137/1.9781611971484](http://epubs.siam.org/doi/book/10.1137/1.9781611971484) - -[^S84]: G. W. Stewart, "Rank Degeneracy", SIAM Journal on Scientific and Statistical Computing, 5(2), 1984, 403-413. [doi:10.1137/0905030](http://epubs.siam.org/doi/abs/10.1137/0905030) - -[^KY88]: Konstantinos Konstantinides and Kung Yao, "Statistical analysis of effective singular values in matrix rank determination", IEEE Transactions on Acoustics, Speech and Signal Processing, 36(5), 1988, 757-763. [doi:10.1109/29.1585](http://dx.doi.org/10.1109/29.1585) -""" -function pinv(A::StridedMatrix{T}, tol::Real) where T - m, n = size(A) - Tout = typeof(zero(T)/sqrt(one(T) + one(T))) - if m == 0 || n == 0 - return Matrix{Tout}(n, m) - end - if istril(A) - if istriu(A) - maxabsA = maximum(abs.(diag(A))) - B = zeros(Tout, n, m) - for i = 1:min(m, n) - if abs(A[i,i]) > tol*maxabsA - Aii = inv(A[i,i]) - if isfinite(Aii) - B[i,i] = Aii - end - end - end - return B - end - end - SVD = svdfact(A, thin=true) - Stype = eltype(SVD.S) - Sinv = zeros(Stype, length(SVD.S)) - index = SVD.S .> tol*maximum(SVD.S) - Sinv[index] = one(Stype) ./ SVD.S[index] - Sinv[find(.!isfinite.(Sinv))] = zero(Stype) - return SVD.Vt' * (Diagonal(Sinv) * SVD.U') -end -function pinv(A::StridedMatrix{T}) where T - tol = eps(real(float(one(T))))*maximum(size(A)) - return pinv(A, tol) -end -pinv(a::StridedVector) = pinv(reshape(a, length(a), 1)) -function pinv(x::Number) - xi = inv(x) - return ifelse(isfinite(xi), xi, zero(xi)) -end - -## Basis for null space - -""" - nullspace(M) - -Basis for nullspace of `M`. - -# Example - -```jldoctest -julia> M = [1 0 0; 0 1 0; 0 0 0] -3×3 Array{Int64,2}: - 1 0 0 - 0 1 0 - 0 0 0 - -julia> nullspace(M) -3×1 Array{Float64,2}: - 0.0 - 0.0 - 1.0 -``` -""" -function nullspace(A::StridedMatrix{T}) where T - m, n = size(A) - (m == 0 || n == 0) && return eye(T, n) - SVD = svdfact(A, thin = false) - indstart = sum(SVD.S .> max(m,n)*maximum(SVD.S)*eps(eltype(SVD.S))) + 1 - return SVD.Vt[indstart:end,:]' -end -nullspace(a::StridedVector) = nullspace(reshape(a, length(a), 1)) - -""" - cond(M, p::Real=2) - -Condition number of the matrix `M`, computed using the operator `p`-norm. Valid values for -`p` are `1`, `2` (default), or `Inf`. -""" -function cond(A::AbstractMatrix, p::Real=2) - if p == 2 - v = svdvals(A) - maxv = maximum(v) - return maxv == 0.0 ? oftype(real(A[1,1]),Inf) : maxv / minimum(v) - elseif p == 1 || p == Inf - checksquare(A) - return cond(lufact(A), p) - end - throw(ArgumentError("p-norm must be 1, 2 or Inf, got $p")) -end - -## Lyapunov and Sylvester equation - -# AX + XB + C = 0 - -""" - sylvester(A, B, C) - -Computes the solution `X` to the Sylvester equation `AX + XB + C = 0`, where `A`, `B` and -`C` have compatible dimensions and `A` and `-B` have no eigenvalues with equal real part. -""" -function sylvester(A::StridedMatrix{T},B::StridedMatrix{T},C::StridedMatrix{T}) where T<:BlasFloat - RA, QA = schur(A) - RB, QB = schur(B) - - D = -Ac_mul_B(QA,C*QB) - Y, scale = LAPACK.trsyl!('N','N', RA, RB, D) - scale!(QA*A_mul_Bc(Y,QB), inv(scale)) -end -sylvester(A::StridedMatrix{T}, B::StridedMatrix{T}, C::StridedMatrix{T}) where {T<:Integer} = sylvester(float(A), float(B), float(C)) - -sylvester(a::Union{Real,Complex}, b::Union{Real,Complex}, c::Union{Real,Complex}) = -c / (a + b) - -# AX + XA' + C = 0 - -""" - lyap(A, C) - -Computes the solution `X` to the continuous Lyapunov equation `AX + XA' + C = 0`, where no -eigenvalue of `A` has a zero real part and no two eigenvalues are negative complex -conjugates of each other. -""" -function lyap(A::StridedMatrix{T}, C::StridedMatrix{T}) where {T<:BlasFloat} - R, Q = schur(A) - - D = -Ac_mul_B(Q,C*Q) - Y, scale = LAPACK.trsyl!('N', T <: Complex ? 'C' : 'T', R, R, D) - scale!(Q*A_mul_Bc(Y,Q), inv(scale)) -end -lyap(A::StridedMatrix{T}, C::StridedMatrix{T}) where {T<:Integer} = lyap(float(A), float(C)) -lyap(a::T, c::T) where {T<:Number} = -c/(2a) diff --git a/julia-0.6.3/share/julia/base/linalg/diagonal.jl b/julia-0.6.3/share/julia/base/linalg/diagonal.jl deleted file mode 100644 index def3471..0000000 --- a/julia-0.6.3/share/julia/base/linalg/diagonal.jl +++ /dev/null @@ -1,373 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -## Diagonal matrices - -struct Diagonal{T} <: AbstractMatrix{T} - diag::Vector{T} -end -""" - Diagonal(A::AbstractMatrix) - -Constructs a matrix from the diagonal of `A`. - -# Example - -```jldoctest -julia> A = [1 2 3; 4 5 6; 7 8 9] -3×3 Array{Int64,2}: - 1 2 3 - 4 5 6 - 7 8 9 - -julia> Diagonal(A) -3×3 Diagonal{Int64}: - 1 ⋅ ⋅ - ⋅ 5 ⋅ - ⋅ ⋅ 9 -``` -""" -Diagonal(A::AbstractMatrix) = Diagonal(diag(A)) -""" - Diagonal(V::AbstractVector) - -Constructs a matrix with `V` as its diagonal. - -# Example - -```jldoctest -julia> V = [1; 2] -2-element Array{Int64,1}: - 1 - 2 - -julia> Diagonal(V) -2×2 Diagonal{Int64}: - 1 ⋅ - ⋅ 2 -``` -""" -Diagonal(V::AbstractVector) = Diagonal(collect(V)) - -convert(::Type{Diagonal{T}}, D::Diagonal{T}) where {T} = D -convert(::Type{Diagonal{T}}, D::Diagonal) where {T} = Diagonal{T}(convert(Vector{T}, D.diag)) -convert(::Type{AbstractMatrix{T}}, D::Diagonal) where {T} = convert(Diagonal{T}, D) -convert(::Type{Matrix}, D::Diagonal) = diagm(D.diag) -convert(::Type{Array}, D::Diagonal) = convert(Matrix, D) -full(D::Diagonal) = convert(Array, D) - -function similar(D::Diagonal, ::Type{T}) where T - return Diagonal{T}(similar(D.diag, T)) -end - -copy!(D1::Diagonal, D2::Diagonal) = (copy!(D1.diag, D2.diag); D1) - -size(D::Diagonal) = (length(D.diag),length(D.diag)) - -function size(D::Diagonal,d::Integer) - if d<1 - throw(ArgumentError("dimension must be ≥ 1, got $d")) - end - return d<=2 ? length(D.diag) : 1 -end - -@inline function getindex(D::Diagonal, i::Int, j::Int) - @boundscheck checkbounds(D, i, j) - if i == j - @inbounds r = D.diag[i] - else - r = diagzero(D, i, j) - end - r -end -diagzero(::Diagonal{T},i,j) where {T} = zero(T) -diagzero(D::Diagonal{Matrix{T}},i,j) where {T} = zeros(T, size(D.diag[i], 1), size(D.diag[j], 2)) - -function setindex!(D::Diagonal, v, i::Int, j::Int) - @boundscheck checkbounds(D, i, j) - if i == j - @inbounds D.diag[i] = v - elseif !iszero(v) - throw(ArgumentError("cannot set off-diagonal entry ($i, $j) to a nonzero value ($v)")) - end - return v -end - - -## structured matrix methods ## -function Base.replace_in_print_matrix(A::Diagonal,i::Integer,j::Integer,s::AbstractString) - i==j ? s : Base.replace_with_centered_mark(s) -end - -parent(D::Diagonal) = D.diag - -ishermitian(D::Diagonal{<:Real}) = true -ishermitian(D::Diagonal{<:Number}) = isreal(D.diag) -ishermitian(D::Diagonal) = all(ishermitian, D.diag) -issymmetric(D::Diagonal{<:Number}) = true -issymmetric(D::Diagonal) = all(issymmetric, D.diag) -isposdef(D::Diagonal) = all(x -> x > 0, D.diag) - -factorize(D::Diagonal) = D - -broadcast(::typeof(abs), D::Diagonal) = Diagonal(abs.(D.diag)) -real(D::Diagonal) = Diagonal(real(D.diag)) -imag(D::Diagonal) = Diagonal(imag(D.diag)) - -istriu(D::Diagonal) = true -istril(D::Diagonal) = true -function triu!(D::Diagonal,k::Integer=0) - n = size(D,1) - if abs(k) > n - throw(ArgumentError("requested diagonal, $k, out of bounds in matrix of size ($n,$n)")) - elseif k > 0 - fill!(D.diag,0) - end - return D -end - -function tril!(D::Diagonal,k::Integer=0) - n = size(D,1) - if abs(k) > n - throw(ArgumentError("requested diagonal, $k, out of bounds in matrix of size ($n,$n)")) - elseif k < 0 - fill!(D.diag,0) - end - return D -end - -(==)(Da::Diagonal, Db::Diagonal) = Da.diag == Db.diag -(-)(A::Diagonal) = Diagonal(-A.diag) -(+)(Da::Diagonal, Db::Diagonal) = Diagonal(Da.diag + Db.diag) -(-)(Da::Diagonal, Db::Diagonal) = Diagonal(Da.diag - Db.diag) - -(*)(x::Number, D::Diagonal) = Diagonal(x * D.diag) -(*)(D::Diagonal, x::Number) = Diagonal(D.diag * x) -(/)(D::Diagonal, x::Number) = Diagonal(D.diag / x) -(*)(Da::Diagonal, Db::Diagonal) = Diagonal(Da.diag .* Db.diag) -(*)(D::Diagonal, V::AbstractVector) = D.diag .* V - -(*)(A::AbstractTriangular, D::Diagonal) = A_mul_B!(copy(A), D) -(*)(D::Diagonal, B::AbstractTriangular) = A_mul_B!(D, copy(B)) - -(*)(A::AbstractMatrix, D::Diagonal) = - scale!(similar(A, promote_op(*, eltype(A), eltype(D.diag)), size(A)), A, D.diag) -(*)(D::Diagonal, A::AbstractMatrix) = - scale!(similar(A, promote_op(*, eltype(A), eltype(D.diag)), size(A)), D.diag, A) - -A_mul_B!(A::Union{LowerTriangular,UpperTriangular}, D::Diagonal) = - typeof(A)(A_mul_B!(A.data, D)) -function A_mul_B!(A::UnitLowerTriangular, D::Diagonal) - A_mul_B!(A.data, D) - for i = 1:size(A, 1) - A.data[i,i] = D.diag[i] - end - LowerTriangular(A.data) -end -function A_mul_B!(A::UnitUpperTriangular, D::Diagonal) - A_mul_B!(A.data, D) - for i = 1:size(A, 1) - A.data[i,i] = D.diag[i] - end - UpperTriangular(A.data) -end -function A_mul_B!(D::Diagonal, B::UnitLowerTriangular) - A_mul_B!(D, B.data) - for i = 1:size(B, 1) - B.data[i,i] = D.diag[i] - end - LowerTriangular(B.data) -end -function A_mul_B!(D::Diagonal, B::UnitUpperTriangular) - A_mul_B!(D, B.data) - for i = 1:size(B, 1) - B.data[i,i] = D.diag[i] - end - UpperTriangular(B.data) -end - -Ac_mul_B(A::AbstractTriangular, D::Diagonal) = A_mul_B!(ctranspose(A), D) -function Ac_mul_B(A::AbstractMatrix, D::Diagonal) - Ac = similar(A, promote_op(*, eltype(A), eltype(D.diag)), (size(A, 2), size(A, 1))) - ctranspose!(Ac, A) - A_mul_B!(Ac, D) -end - -At_mul_B(A::AbstractTriangular, D::Diagonal) = A_mul_B!(transpose(A), D) -function At_mul_B(A::AbstractMatrix, D::Diagonal) - At = similar(A, promote_op(*, eltype(A), eltype(D.diag)), (size(A, 2), size(A, 1))) - transpose!(At, A) - A_mul_B!(At, D) -end - -A_mul_Bc(D::Diagonal, B::AbstractTriangular) = A_mul_B!(D, ctranspose(B)) -A_mul_Bc(D::Diagonal, Q::Union{Base.LinAlg.QRCompactWYQ,Base.LinAlg.QRPackedQ}) = A_mul_Bc!(Array(D), Q) -function A_mul_Bc(D::Diagonal, A::AbstractMatrix) - Ac = similar(A, promote_op(*, eltype(A), eltype(D.diag)), (size(A, 2), size(A, 1))) - ctranspose!(Ac, A) - A_mul_B!(D, Ac) -end - -A_mul_Bt(D::Diagonal, B::AbstractTriangular) = A_mul_B!(D, transpose(B)) -function A_mul_Bt(D::Diagonal, A::AbstractMatrix) - At = similar(A, promote_op(*, eltype(A), eltype(D.diag)), (size(A, 2), size(A, 1))) - transpose!(At, A) - A_mul_B!(D, At) -end - -A_mul_B!(A::Diagonal,B::Diagonal) = throw(MethodError(A_mul_B!, Tuple{Diagonal,Diagonal})) -At_mul_B!(A::Diagonal,B::Diagonal) = throw(MethodError(At_mul_B!, Tuple{Diagonal,Diagonal})) -Ac_mul_B!(A::Diagonal,B::Diagonal) = throw(MethodError(Ac_mul_B!, Tuple{Diagonal,Diagonal})) -A_mul_B!(A::Base.LinAlg.QRPackedQ, D::Diagonal) = throw(MethodError(A_mul_B!, Tuple{Diagonal,Diagonal})) -A_mul_B!(A::Diagonal,B::AbstractMatrix) = scale!(A.diag,B) -At_mul_B!(A::Diagonal,B::AbstractMatrix) = scale!(A.diag,B) -Ac_mul_B!(A::Diagonal,B::AbstractMatrix) = scale!(conj(A.diag),B) -A_mul_B!(A::AbstractMatrix,B::Diagonal) = scale!(A,B.diag) -A_mul_Bt!(A::AbstractMatrix,B::Diagonal) = scale!(A,B.diag) -A_mul_Bc!(A::AbstractMatrix,B::Diagonal) = scale!(A,conj(B.diag)) - -# Get ambiguous method if try to unify AbstractVector/AbstractMatrix here using AbstractVecOrMat -A_mul_B!(out::AbstractVector, A::Diagonal, in::AbstractVector) = out .= A.diag .* in -Ac_mul_B!(out::AbstractVector, A::Diagonal, in::AbstractVector) = out .= ctranspose.(A.diag) .* in -At_mul_B!(out::AbstractVector, A::Diagonal, in::AbstractVector) = out .= transpose.(A.diag) .* in - -A_mul_B!(out::AbstractMatrix, A::Diagonal, in::AbstractMatrix) = out .= A.diag .* in -Ac_mul_B!(out::AbstractMatrix, A::Diagonal, in::AbstractMatrix) = out .= ctranspose.(A.diag) .* in -At_mul_B!(out::AbstractMatrix, A::Diagonal, in::AbstractMatrix) = out .= transpose.(A.diag) .* in - - -(/)(Da::Diagonal, Db::Diagonal) = Diagonal(Da.diag ./ Db.diag) -function A_ldiv_B!(D::Diagonal{T}, v::AbstractVector{T}) where T - if length(v) != length(D.diag) - throw(DimensionMismatch("diagonal matrix is $(length(D.diag)) by $(length(D.diag)) but right hand side has $(length(v)) rows")) - end - for i=1:length(D.diag) - d = D.diag[i] - if d == zero(T) - throw(SingularException(i)) - end - v[i] *= inv(d) - end - v -end -function A_ldiv_B!(D::Diagonal{T}, V::AbstractMatrix{T}) where T - if size(V,1) != length(D.diag) - throw(DimensionMismatch("diagonal matrix is $(length(D.diag)) by $(length(D.diag)) but right hand side has $(size(V,1)) rows")) - end - for i=1:length(D.diag) - d = D.diag[i] - if d == zero(T) - throw(SingularException(i)) - end - d⁻¹ = inv(d) - for j=1:size(V,2) - @inbounds V[i,j] *= d⁻¹ - end - end - V -end - -# Methods to resolve ambiguities with `Diagonal` -@inline *(rowvec::RowVector, D::Diagonal) = transpose(D * transpose(rowvec)) -@inline A_mul_Bt(D::Diagonal, rowvec::RowVector) = D*transpose(rowvec) -@inline A_mul_Bc(D::Diagonal, rowvec::RowVector) = D*ctranspose(rowvec) - -conj(D::Diagonal) = Diagonal(conj(D.diag)) -transpose(D::Diagonal{<:Number}) = D -transpose(D::Diagonal) = Diagonal(transpose.(D.diag)) -ctranspose(D::Diagonal{<:Number}) = conj(D) -ctranspose(D::Diagonal) = Diagonal(ctranspose.(D.diag)) - -diag(D::Diagonal) = D.diag -trace(D::Diagonal) = sum(D.diag) -det(D::Diagonal) = prod(D.diag) -logdet(D::Diagonal{<:Real}) = sum(log, D.diag) -function logdet(D::Diagonal{<:Complex}) # make sure branch cut is correct - z = sum(log, D.diag) - complex(real(z), rem2pi(imag(z), RoundNearest)) -end -# identity matrices via eye(Diagonal{type},n) -eye(::Type{Diagonal{T}}, n::Int) where {T} = Diagonal(ones(T,n)) - -# Matrix functions -expm(D::Diagonal) = Diagonal(exp.(D.diag)) -expm(D::Diagonal{<:AbstractMatrix}) = Diagonal(expm.(D.diag)) -logm(D::Diagonal) = Diagonal(log.(D.diag)) -logm(D::Diagonal{<:AbstractMatrix}) = Diagonal(logm.(D.diag)) -sqrtm(D::Diagonal) = Diagonal(sqrt.(D.diag)) -sqrtm(D::Diagonal{<:AbstractMatrix}) = Diagonal(sqrtm.(D.diag)) - -#Linear solver -function A_ldiv_B!(D::Diagonal, B::StridedVecOrMat) - m, n = size(B, 1), size(B, 2) - if m != length(D.diag) - throw(DimensionMismatch("diagonal matrix is $(length(D.diag)) by $(length(D.diag)) but right hand side has $m rows")) - end - (m == 0 || n == 0) && return B - for j = 1:n - for i = 1:m - di = D.diag[i] - if di == 0 - throw(SingularException(i)) - end - B[i,j] /= di - end - end - return B -end -(\)(D::Diagonal, A::AbstractMatrix) = D.diag .\ A -(\)(D::Diagonal, b::AbstractVector) = D.diag .\ b -(\)(Da::Diagonal, Db::Diagonal) = Diagonal(Da.diag .\ Db.diag) - -function inv(D::Diagonal{T}) where T - Di = similar(D.diag, typeof(inv(zero(T)))) - for i = 1:length(D.diag) - if D.diag[i] == zero(T) - throw(SingularException(i)) - end - Di[i] = inv(D.diag[i]) - end - Diagonal(Di) -end - -function pinv(D::Diagonal{T}) where T - Di = similar(D.diag, typeof(inv(zero(T)))) - for i = 1:length(D.diag) - isfinite(inv(D.diag[i])) ? Di[i]=inv(D.diag[i]) : Di[i]=zero(T) - end - Diagonal(Di) -end -function pinv(D::Diagonal{T}, tol::Real) where T - Di = similar(D.diag, typeof(inv(zero(T)))) - if( !isempty(D.diag) ) maxabsD = maximum(abs.(D.diag)) end - for i = 1:length(D.diag) - if( abs(D.diag[i]) > tol*maxabsD && isfinite(inv(D.diag[i])) ) - Di[i]=inv(D.diag[i]) - else - Di[i]=zero(T) - end - end - Diagonal(Di) -end - -#Eigensystem -eigvals(D::Diagonal{<:Number}) = D.diag -eigvals(D::Diagonal) = [eigvals(x) for x in D.diag] #For block matrices, etc. -eigvecs(D::Diagonal) = eye(D) -eigfact(D::Diagonal) = Eigen(eigvals(D), eigvecs(D)) - -#Singular system -svdvals(D::Diagonal{<:Number}) = sort!(abs.(D.diag), rev = true) -svdvals(D::Diagonal) = [svdvals(v) for v in D.diag] -function svd(D::Diagonal{<:Number}) - S = abs.(D.diag) - piv = sortperm(S, rev = true) - U = Diagonal(D.diag ./ S) - Up = hcat([U[:,i] for i = 1:length(D.diag)][piv]...) - V = Diagonal(ones(D.diag)) - Vp = hcat([V[:,i] for i = 1:length(D.diag)][piv]...) - return (Up, S[piv], Vp) -end -function svdfact(D::Diagonal) - U, s, V = svd(D) - SVD(U, s, V') -end diff --git a/julia-0.6.3/share/julia/base/linalg/eigen.jl b/julia-0.6.3/share/julia/base/linalg/eigen.jl deleted file mode 100644 index 0ef75b8..0000000 --- a/julia-0.6.3/share/julia/base/linalg/eigen.jl +++ /dev/null @@ -1,446 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -# Eigendecomposition -struct Eigen{T,V,S<:AbstractMatrix,U<:AbstractVector} <: Factorization{T} - values::U - vectors::S - Eigen{T,V,S,U}(values::AbstractVector{V}, vectors::AbstractMatrix{T}) where {T,V,S,U} = - new(values, vectors) -end -Eigen(values::AbstractVector{V}, vectors::AbstractMatrix{T}) where {T,V} = - Eigen{T,V,typeof(vectors),typeof(values)}(values, vectors) - -# Generalized eigenvalue problem. -struct GeneralizedEigen{T,V,S<:AbstractMatrix,U<:AbstractVector} <: Factorization{T} - values::U - vectors::S - GeneralizedEigen{T,V,S,U}(values::AbstractVector{V}, vectors::AbstractMatrix{T}) where {T,V,S,U} = - new(values, vectors) -end -GeneralizedEigen(values::AbstractVector{V}, vectors::AbstractMatrix{T}) where {T,V} = - GeneralizedEigen{T,V,typeof(vectors),typeof(values)}(values, vectors) - - -function getindex(A::Union{Eigen,GeneralizedEigen}, d::Symbol) - d == :values && return A.values - d == :vectors && return A.vectors - throw(KeyError(d)) -end - -isposdef(A::Union{Eigen,GeneralizedEigen}) = isreal(A.values) && all(x -> x > 0, A.values) - -""" - eigfact!(A, [B]) - -Same as [`eigfact`](@ref), but saves space by overwriting the input `A` (and -`B`), instead of creating a copy. -""" -function eigfact!(A::StridedMatrix{T}; permute::Bool=true, scale::Bool=true) where T<:BlasReal - n = size(A, 2) - n == 0 && return Eigen(zeros(T, 0), zeros(T, 0, 0)) - issymmetric(A) && return eigfact!(Symmetric(A)) - A, WR, WI, VL, VR, _ = LAPACK.geevx!(permute ? (scale ? 'B' : 'P') : (scale ? 'S' : 'N'), 'N', 'V', 'N', A) - iszero(WI) && return Eigen(WR, VR) - evec = zeros(Complex{T}, n, n) - j = 1 - while j <= n - if WI[j] == 0 - evec[:,j] = view(VR, :, j) - else - for i = 1:n - evec[i,j] = VR[i,j] + im*VR[i,j+1] - evec[i,j+1] = VR[i,j] - im*VR[i,j+1] - end - j += 1 - end - j += 1 - end - return Eigen(complex.(WR, WI), evec) -end - -function eigfact!(A::StridedMatrix{T}; permute::Bool=true, scale::Bool=true) where T<:BlasComplex - n = size(A, 2) - n == 0 && return Eigen(zeros(T, 0), zeros(T, 0, 0)) - ishermitian(A) && return eigfact!(Hermitian(A)) - return Eigen(LAPACK.geevx!(permute ? (scale ? 'B' : 'P') : (scale ? 'S' : 'N'), 'N', 'V', 'N', A)[[2,4]]...) -end - -""" - eigfact(A; permute::Bool=true, scale::Bool=true) -> Eigen - -Computes the eigenvalue decomposition of `A`, returning an `Eigen` factorization object `F` -which contains the eigenvalues in `F[:values]` and the eigenvectors in the columns of the -matrix `F[:vectors]`. (The `k`th eigenvector can be obtained from the slice `F[:vectors][:, k]`.) - -The following functions are available for `Eigen` objects: [`inv`](@ref), [`det`](@ref), and [`isposdef`](@ref). - -For general nonsymmetric matrices it is possible to specify how the matrix is balanced -before the eigenvector calculation. The option `permute=true` permutes the matrix to become -closer to upper triangular, and `scale=true` scales the matrix by its diagonal elements to -make rows and columns more equal in norm. The default is `true` for both options. - -# Example - -```jldoctest -julia> F = eigfact([1.0 0.0 0.0; 0.0 3.0 0.0; 0.0 0.0 18.0]) -Base.LinAlg.Eigen{Float64,Float64,Array{Float64,2},Array{Float64,1}}([1.0, 3.0, 18.0], [1.0 0.0 0.0; 0.0 1.0 0.0; 0.0 0.0 1.0]) - -julia> F[:values] -3-element Array{Float64,1}: - 1.0 - 3.0 - 18.0 - -julia> F[:vectors] -3×3 Array{Float64,2}: - 1.0 0.0 0.0 - 0.0 1.0 0.0 - 0.0 0.0 1.0 -``` -""" -function eigfact(A::StridedMatrix{T}; permute::Bool=true, scale::Bool=true) where T - S = promote_type(Float32, typeof(one(T)/norm(one(T)))) - eigfact!(copy_oftype(A, S), permute = permute, scale = scale) -end -eigfact(x::Number) = Eigen([x], fill(one(x), 1, 1)) - -function eig(A::Union{Number, StridedMatrix}; permute::Bool=true, scale::Bool=true) - F = eigfact(A, permute=permute, scale=scale) - F.values, F.vectors -end - -""" - eig(A::Union{SymTridiagonal, Hermitian, Symmetric}, irange::UnitRange) -> D, V - eig(A::Union{SymTridiagonal, Hermitian, Symmetric}, vl::Real, vu::Real) -> D, V - eig(A, permute::Bool=true, scale::Bool=true) -> D, V - -Computes eigenvalues (`D`) and eigenvectors (`V`) of `A`. -See [`eigfact`](@ref) for details on the -`irange`, `vl`, and `vu` arguments -(for [`SymTridiagonal`](@ref), `Hermitian`, and -`Symmetric` matrices) -and the `permute` and `scale` keyword arguments. -The eigenvectors are returned columnwise. - -# Example - -```jldoctest -julia> eig([1.0 0.0 0.0; 0.0 3.0 0.0; 0.0 0.0 18.0]) -([1.0, 3.0, 18.0], [1.0 0.0 0.0; 0.0 1.0 0.0; 0.0 0.0 1.0]) -``` - -`eig` is a wrapper around [`eigfact`](@ref), extracting all parts of the -factorization to a tuple; where possible, using [`eigfact`](@ref) is recommended. -""" -function eig(A::AbstractMatrix, args...) - F = eigfact(A, args...) - F.values, F.vectors -end - -""" - eigvecs(A; permute::Bool=true, scale::Bool=true) -> Matrix - -Returns a matrix `M` whose columns are the eigenvectors of `A`. (The `k`th eigenvector can -be obtained from the slice `M[:, k]`.) The `permute` and `scale` keywords are the same as -for [`eigfact`](@ref). - -# Example - -```jldoctest -julia> eigvecs([1.0 0.0 0.0; 0.0 3.0 0.0; 0.0 0.0 18.0]) -3×3 Array{Float64,2}: - 1.0 0.0 0.0 - 0.0 1.0 0.0 - 0.0 0.0 1.0 -``` -""" -eigvecs(A::Union{Number, AbstractMatrix}; permute::Bool=true, scale::Bool=true) = - eigvecs(eigfact(A, permute=permute, scale=scale)) -eigvecs(F::Union{Eigen{T,V,S,U}, GeneralizedEigen{T,V,S,U}}) where {T,V,S,U} = F[:vectors]::S - -eigvals(F::Union{Eigen{T,V,S,U}, GeneralizedEigen{T,V,S,U}}) where {T,V,S,U} = F[:values]::U - -""" - eigvals!(A; permute::Bool=true, scale::Bool=true) -> values - -Same as [`eigvals`](@ref), but saves space by overwriting the input `A`, instead of creating a copy. -The option `permute=true` permutes the matrix to become -closer to upper triangular, and `scale=true` scales the matrix by its diagonal elements to -make rows and columns more equal in norm. -""" -function eigvals!(A::StridedMatrix{<:BlasReal}; permute::Bool=true, scale::Bool=true) - issymmetric(A) && return eigvals!(Symmetric(A)) - _, valsre, valsim, _ = LAPACK.geevx!(permute ? (scale ? 'B' : 'P') : (scale ? 'S' : 'N'), 'N', 'N', 'N', A) - return iszero(valsim) ? valsre : complex.(valsre, valsim) -end -function eigvals!(A::StridedMatrix{<:BlasComplex}; permute::Bool=true, scale::Bool=true) - ishermitian(A) && return eigvals(Hermitian(A)) - return LAPACK.geevx!(permute ? (scale ? 'B' : 'P') : (scale ? 'S' : 'N'), 'N', 'N', 'N', A)[2] -end - -""" - eigvals(A; permute::Bool=true, scale::Bool=true) -> values - -Returns the eigenvalues of `A`. - -For general non-symmetric matrices it is possible to specify how the matrix is balanced -before the eigenvalue calculation. The option `permute=true` permutes the matrix to -become closer to upper triangular, and `scale=true` scales the matrix by its diagonal -elements to make rows and columns more equal in norm. The default is `true` for both -options. -""" -function eigvals(A::StridedMatrix{T}; permute::Bool=true, scale::Bool=true) where T - S = promote_type(Float32, typeof(one(T)/norm(one(T)))) - return eigvals!(copy_oftype(A, S), permute = permute, scale = scale) -end -function eigvals(x::T; kwargs...) where T<:Number - val = convert(promote_type(Float32, typeof(one(T)/norm(one(T)))), x) - return imag(val) == 0 ? [real(val)] : [val] -end - -""" - eigmax(A; permute::Bool=true, scale::Bool=true) - -Returns the largest eigenvalue of `A`. -The option `permute=true` permutes the matrix to become -closer to upper triangular, and `scale=true` scales the matrix by its diagonal elements to -make rows and columns more equal in norm. -Note that if the eigenvalues of `A` are complex, -this method will fail, since complex numbers cannot -be sorted. - -# Example - -```jldoctest -julia> A = [0 im; -im 0] -2×2 Array{Complex{Int64},2}: - 0+0im 0+1im - 0-1im 0+0im - -julia> eigmax(A) -1.0 - -julia> A = [0 im; -1 0] -2×2 Array{Complex{Int64},2}: - 0+0im 0+1im - -1+0im 0+0im - -julia> eigmax(A) -ERROR: DomainError: -Stacktrace: - [1] #eigmax#46(::Bool, ::Bool, ::Function, ::Array{Complex{Int64},2}) at ./linalg/eigen.jl:238 - [2] eigmax(::Array{Complex{Int64},2}) at ./linalg/eigen.jl:236 -``` -""" -function eigmax(A::Union{Number, StridedMatrix}; permute::Bool=true, scale::Bool=true) - v = eigvals(A, permute = permute, scale = scale) - if eltype(v)<:Complex - throw(DomainError()) - end - maximum(v) -end - -""" - eigmin(A; permute::Bool=true, scale::Bool=true) - -Returns the smallest eigenvalue of `A`. -The option `permute=true` permutes the matrix to become -closer to upper triangular, and `scale=true` scales the matrix by its diagonal elements to -make rows and columns more equal in norm. -Note that if the eigenvalues of `A` are complex, -this method will fail, since complex numbers cannot -be sorted. - -# Example - -```jldoctest -julia> A = [0 im; -im 0] -2×2 Array{Complex{Int64},2}: - 0+0im 0+1im - 0-1im 0+0im - -julia> eigmin(A) --1.0 - -julia> A = [0 im; -1 0] -2×2 Array{Complex{Int64},2}: - 0+0im 0+1im - -1+0im 0+0im - -julia> eigmin(A) -ERROR: DomainError: -Stacktrace: - [1] #eigmin#47(::Bool, ::Bool, ::Function, ::Array{Complex{Int64},2}) at ./linalg/eigen.jl:280 - [2] eigmin(::Array{Complex{Int64},2}) at ./linalg/eigen.jl:278 -``` -""" -function eigmin(A::Union{Number, StridedMatrix}; permute::Bool=true, scale::Bool=true) - v = eigvals(A, permute = permute, scale = scale) - if eltype(v)<:Complex - throw(DomainError()) - end - minimum(v) -end - -inv(A::Eigen) = A.vectors * inv(Diagonal(A.values)) / A.vectors -det(A::Eigen) = prod(A.values) - -# Generalized eigenproblem -function eigfact!(A::StridedMatrix{T}, B::StridedMatrix{T}) where T<:BlasReal - issymmetric(A) && isposdef(B) && return eigfact!(Symmetric(A), Symmetric(B)) - n = size(A, 1) - alphar, alphai, beta, _, vr = LAPACK.ggev!('N', 'V', A, B) - iszero(alphai) && return GeneralizedEigen(alphar ./ beta, vr) - - vecs = zeros(Complex{T}, n, n) - j = 1 - while j <= n - if alphai[j] == 0 - vecs[:,j] = view(vr, :, j) - else - for i = 1:n - vecs[i,j ] = vr[i,j] + im*vr[i,j+1] - vecs[i,j+1] = vr[i,j] - im*vr[i,j+1] - end - j += 1 - end - j += 1 - end - return GeneralizedEigen(complex.(alphar, alphai)./beta, vecs) -end - -function eigfact!(A::StridedMatrix{T}, B::StridedMatrix{T}) where T<:BlasComplex - ishermitian(A) && isposdef(B) && return eigfact!(Hermitian(A), Hermitian(B)) - alpha, beta, _, vr = LAPACK.ggev!('N', 'V', A, B) - return GeneralizedEigen(alpha./beta, vr) -end - -""" - eigfact(A, B) -> GeneralizedEigen - -Computes the generalized eigenvalue decomposition of `A` and `B`, returning a -`GeneralizedEigen` factorization object `F` which contains the generalized eigenvalues in -`F[:values]` and the generalized eigenvectors in the columns of the matrix `F[:vectors]`. -(The `k`th generalized eigenvector can be obtained from the slice `F[:vectors][:, k]`.) -""" -function eigfact(A::AbstractMatrix{TA}, B::AbstractMatrix{TB}) where {TA,TB} - S = promote_type(Float32, typeof(one(TA)/norm(one(TA))),TB) - return eigfact!(copy_oftype(A, S), copy_oftype(B, S)) -end - -eigfact(A::Number, B::Number) = eigfact(fill(A,1,1), fill(B,1,1)) - -""" - eig(A, B) -> D, V - -Computes generalized eigenvalues (`D`) and vectors (`V`) of `A` with respect to `B`. - -`eig` is a wrapper around [`eigfact`](@ref), extracting all parts of the -factorization to a tuple; where possible, using [`eigfact`](@ref) is recommended. - -# Example - -```jldoctest -julia> A = [1 0; 0 -1] -2×2 Array{Int64,2}: - 1 0 - 0 -1 - -julia> B = [0 1; 1 0] -2×2 Array{Int64,2}: - 0 1 - 1 0 - -julia> eig(A, B) -(Complex{Float64}[0.0+1.0im, 0.0-1.0im], Complex{Float64}[0.0-1.0im 0.0+1.0im; -1.0-0.0im -1.0+0.0im]) -``` -""" -function eig(A::AbstractMatrix, B::AbstractMatrix) - F = eigfact(A,B) - F.values, F.vectors -end -function eig(A::Number, B::Number) - F = eigfact(A,B) - F.values, F.vectors -end - -""" - eigvals!(A, B) -> values - -Same as [`eigvals`](@ref), but saves space by overwriting the input `A` (and `B`), instead of creating copies. -""" -function eigvals!(A::StridedMatrix{T}, B::StridedMatrix{T}) where T<:BlasReal - issymmetric(A) && isposdef(B) && return eigvals!(Symmetric(A), Symmetric(B)) - alphar, alphai, beta, vl, vr = LAPACK.ggev!('N', 'N', A, B) - return (iszero(alphai) ? alphar : complex.(alphar, alphai))./beta -end -function eigvals!(A::StridedMatrix{T}, B::StridedMatrix{T}) where T<:BlasComplex - ishermitian(A) && isposdef(B) && return eigvals!(Hermitian(A), Hermitian(B)) - alpha, beta, vl, vr = LAPACK.ggev!('N', 'N', A, B) - alpha./beta -end - -""" - eigvals(A, B) -> values - -Computes the generalized eigenvalues of `A` and `B`. - -# Example - -```jldoctest -julia> A = [1 0; 0 -1] -2×2 Array{Int64,2}: - 1 0 - 0 -1 - -julia> B = [0 1; 1 0] -2×2 Array{Int64,2}: - 0 1 - 1 0 - -julia> eigvals(A,B) -2-element Array{Complex{Float64},1}: - 0.0+1.0im - 0.0-1.0im -``` -""" -function eigvals(A::AbstractMatrix{TA}, B::AbstractMatrix{TB}) where {TA,TB} - S = promote_type(Float32, typeof(one(TA)/norm(one(TA))),TB) - return eigvals!(copy_oftype(A, S), copy_oftype(B, S)) -end - -""" - eigvecs(A, B) -> Matrix - -Returns a matrix `M` whose columns are the generalized eigenvectors of `A` and `B`. (The `k`th eigenvector can -be obtained from the slice `M[:, k]`.) - -# Example - -```jldoctest -julia> A = [1 0; 0 -1] -2×2 Array{Int64,2}: - 1 0 - 0 -1 - -julia> B = [0 1; 1 0] -2×2 Array{Int64,2}: - 0 1 - 1 0 - -julia> eigvecs(A, B) -2×2 Array{Complex{Float64},2}: - 0.0-1.0im 0.0+1.0im - -1.0-0.0im -1.0+0.0im -``` -""" -eigvecs(A::AbstractMatrix, B::AbstractMatrix) = eigvecs(eigfact(A, B)) - -# Conversion methods - -## Can we determine the source/result is Real? This is not stored in the type Eigen -convert(::Type{AbstractMatrix}, F::Eigen) = F.vectors * Diagonal(F.values) / F.vectors -convert(::Type{AbstractArray}, F::Eigen) = convert(AbstractMatrix, F) -convert(::Type{Matrix}, F::Eigen) = convert(Array, convert(AbstractArray, F)) -convert(::Type{Array}, F::Eigen) = convert(Matrix, F) -full(F::Eigen) = convert(AbstractArray, F) diff --git a/julia-0.6.3/share/julia/base/linalg/exceptions.jl b/julia-0.6.3/share/julia/base/linalg/exceptions.jl deleted file mode 100644 index ea3cb5f..0000000 --- a/julia-0.6.3/share/julia/base/linalg/exceptions.jl +++ /dev/null @@ -1,38 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -export LAPACKException, - ARPACKException, - SingularException, - PosDefException, - RankDeficientException - -mutable struct LAPACKException <: Exception - info::BlasInt -end - -mutable struct ARPACKException <: Exception - info::String -end - -function ARPACKException(i::Integer) - if i == -8 - return ARPACKException("error return from calculation of a real Schur form.") - elseif i == -9 - return ARPACKException("error return from calculation of eigenvectors.") - elseif i == -14 - return ARPACKException("did not find any eigenvalues to sufficient accuracy. Try with a different starting vector or more Lanczos vectors by increasing the value of ncv.") - end - return ARPACKException("unspecified ARPACK error: $i") -end - -mutable struct SingularException <: Exception - info::BlasInt -end - -mutable struct PosDefException <: Exception - info::BlasInt -end - -mutable struct RankDeficientException <: Exception - info::BlasInt -end diff --git a/julia-0.6.3/share/julia/base/linalg/factorization.jl b/julia-0.6.3/share/julia/base/linalg/factorization.jl deleted file mode 100644 index 75e6c0a..0000000 --- a/julia-0.6.3/share/julia/base/linalg/factorization.jl +++ /dev/null @@ -1,93 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -## Matrix factorizations and decompositions - -abstract type Factorization{T} end - -eltype(::Type{Factorization{T}}) where {T} = T -transpose(F::Factorization) = error("transpose not implemented for $(typeof(F))") -ctranspose(F::Factorization) = error("ctranspose not implemented for $(typeof(F))") - -macro assertposdef(A, info) - :($(esc(info)) == 0 ? $(esc(A)) : throw(PosDefException($(esc(info))))) -end - -macro assertnonsingular(A, info) - :($(esc(info)) == 0 ? $(esc(A)) : throw(SingularException($(esc(info))))) -end - -function logdet(F::Factorization) - d, s = logabsdet(F) - return d + log(s) -end - -function det(F::Factorization) - d, s = logabsdet(F) - return exp(d)*s -end - -### General promotion rules -convert(::Type{Factorization{T}}, F::Factorization{T}) where {T} = F -inv(F::Factorization{T}) where {T} = A_ldiv_B!(F, eye(T, size(F,1))) - -# With a real lhs and complex rhs with the same precision, we can reinterpret -# the complex rhs as a real rhs with twice the number of columns -function (\){T<:BlasReal}(F::Factorization{T}, B::VecOrMat{Complex{T}}) - c2r = reshape(transpose(reinterpret(T, B, (2, length(B)))), size(B, 1), 2*size(B, 2)) - x = A_ldiv_B!(F, c2r) - return reinterpret(Complex{T}, transpose(reshape(x, div(length(x), 2), 2)), _ret_size(F, B)) -end - -for (f1, f2) in ((:\, :A_ldiv_B!), - (:Ac_ldiv_B, :Ac_ldiv_B!)) - @eval begin - function $f1(F::Factorization, B::AbstractVecOrMat) - TFB = typeof(oneunit(eltype(B)) / oneunit(eltype(F))) - BB = similar(B, TFB, size(B)) - copy!(BB, B) - $f2(F, BB) - end - end -end - -# support the same 3-arg idiom as in our other in-place A_*_B functions: -for f in (:A_ldiv_B!, :Ac_ldiv_B!, :At_ldiv_B!) - @eval $f(Y::AbstractVecOrMat, A::Factorization, B::AbstractVecOrMat) = - $f(A, copy!(Y, B)) -end - -# fallback methods for transposed solves -At_ldiv_B(F::Factorization{<:Real}, B::AbstractVecOrMat) = Ac_ldiv_B(F, B) -At_ldiv_B(F::Factorization, B) = conj.(Ac_ldiv_B(F, conj.(B))) - -""" - A_ldiv_B!([Y,] A, B) -> Y - -Compute `A \\ B` in-place and store the result in `Y`, returning the result. -If only two arguments are passed, then `A_ldiv_B!(A, B)` overwrites `B` with -the result. - -The argument `A` should *not* be a matrix. Rather, instead of matrices it should be a -factorization object (e.g. produced by [`factorize`](@ref) or [`cholfact`](@ref)). -The reason for this is that factorization itself is both expensive and typically allocates memory -(although it can also be done in-place via, e.g., [`lufact!`](@ref)), -and performance-critical situations requiring `A_ldiv_B!` usually also require fine-grained -control over the factorization of `A`. -""" -A_ldiv_B! - -""" - Ac_ldiv_B!([Y,] A, B) -> Y - -Similar to [`A_ldiv_B!`](@ref), but return ``Aᴴ`` \\ ``B``, -computing the result in-place in `Y` (or overwriting `B` if `Y` is not supplied). -""" -Ac_ldiv_B! - -""" - At_ldiv_B!([Y,] A, B) -> Y - -Similar to [`A_ldiv_B!`](@ref), but return ``Aᵀ`` \\ ``B``, -computing the result in-place in `Y` (or overwriting `B` if `Y` is not supplied). -""" -At_ldiv_B! diff --git a/julia-0.6.3/share/julia/base/linalg/generic.jl b/julia-0.6.3/share/julia/base/linalg/generic.jl deleted file mode 100644 index 01af43e..0000000 --- a/julia-0.6.3/share/julia/base/linalg/generic.jl +++ /dev/null @@ -1,1375 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -## linalg.jl: Some generic Linear Algebra definitions - -# For better performance when input and output are the same array -# See https://github.com/JuliaLang/julia/issues/8415#issuecomment-56608729 -function generic_scale!(X::AbstractArray, s::Number) - @simd for I in eachindex(X) - @inbounds X[I] *= s - end - X -end - -function generic_scale!(s::Number, X::AbstractArray) - @simd for I in eachindex(X) - @inbounds X[I] = s*X[I] - end - X -end - -function generic_scale!(C::AbstractArray, X::AbstractArray, s::Number) - if _length(C) != _length(X) - throw(DimensionMismatch("first array has length $(_length(C)) which does not match the length of the second, $(_length(X)).")) - end - for (IC, IX) in zip(eachindex(C), eachindex(X)) - @inbounds C[IC] = X[IX]*s - end - C -end - -function generic_scale!(C::AbstractArray, s::Number, X::AbstractArray) - if _length(C) != _length(X) - throw(DimensionMismatch("first array has length $(_length(C)) which does not -match the length of the second, $(_length(X)).")) - end - for (IC, IX) in zip(eachindex(C), eachindex(X)) - @inbounds C[IC] = s*X[IX] - end - C -end - -scale!(C::AbstractArray, s::Number, X::AbstractArray) = generic_scale!(C, X, s) -scale!(C::AbstractArray, X::AbstractArray, s::Number) = generic_scale!(C, s, X) - -""" - scale!(A, b) - scale!(b, A) - -Scale an array `A` by a scalar `b` overwriting `A` in-place. - -If `A` is a matrix and `b` is a vector, then `scale!(A,b)` scales each column `i` of `A` by -`b[i]` (similar to `A*Diagonal(b)`), while `scale!(b,A)` scales each row `i` of `A` by `b[i]` -(similar to `Diagonal(b)*A`), again operating in-place on `A`. An `InexactError` exception is -thrown if the scaling produces a number not representable by the element type of `A`, -e.g. for integer types. - -# Example - -```jldoctest -julia> a = [1 2; 3 4] -2×2 Array{Int64,2}: - 1 2 - 3 4 - -julia> b = [1; 2] -2-element Array{Int64,1}: - 1 - 2 - -julia> scale!(a,b) -2×2 Array{Int64,2}: - 1 4 - 3 8 - -julia> a = [1 2; 3 4]; - -julia> b = [1; 2]; - -julia> scale!(b,a) -2×2 Array{Int64,2}: - 1 2 - 6 8 -``` -""" -scale!(X::AbstractArray, s::Number) = generic_scale!(X, s) -scale!(s::Number, X::AbstractArray) = generic_scale!(s, X) - -""" - cross(x, y) - ×(x,y) - -Compute the cross product of two 3-vectors. - -# Example - -```jldoctest -julia> a = [0;1;0] -3-element Array{Int64,1}: - 0 - 1 - 0 - -julia> b = [0;0;1] -3-element Array{Int64,1}: - 0 - 0 - 1 - -julia> cross(a,b) -3-element Array{Int64,1}: - 1 - 0 - 0 -``` -""" -cross(a::AbstractVector, b::AbstractVector) = - [a[2]*b[3]-a[3]*b[2], a[3]*b[1]-a[1]*b[3], a[1]*b[2]-a[2]*b[1]] - -""" - triu(M) - -Upper triangle of a matrix. - -# Example - -```jldoctest -julia> a = ones(4,4) -4×4 Array{Float64,2}: - 1.0 1.0 1.0 1.0 - 1.0 1.0 1.0 1.0 - 1.0 1.0 1.0 1.0 - 1.0 1.0 1.0 1.0 - -julia> triu(a) -4×4 Array{Float64,2}: - 1.0 1.0 1.0 1.0 - 0.0 1.0 1.0 1.0 - 0.0 0.0 1.0 1.0 - 0.0 0.0 0.0 1.0 -``` -""" -triu(M::AbstractMatrix) = triu!(copy(M)) - -""" - tril(M) - -Lower triangle of a matrix. - -# Example - -```jldoctest -julia> a = ones(4,4) -4×4 Array{Float64,2}: - 1.0 1.0 1.0 1.0 - 1.0 1.0 1.0 1.0 - 1.0 1.0 1.0 1.0 - 1.0 1.0 1.0 1.0 - -julia> tril(a) -4×4 Array{Float64,2}: - 1.0 0.0 0.0 0.0 - 1.0 1.0 0.0 0.0 - 1.0 1.0 1.0 0.0 - 1.0 1.0 1.0 1.0 -``` -""" -tril(M::AbstractMatrix) = tril!(copy(M)) - -""" - triu(M, k::Integer) - -Returns the upper triangle of `M` starting from the `k`th superdiagonal. - -# Example - -```jldoctest -julia> a = ones(4,4) -4×4 Array{Float64,2}: - 1.0 1.0 1.0 1.0 - 1.0 1.0 1.0 1.0 - 1.0 1.0 1.0 1.0 - 1.0 1.0 1.0 1.0 - -julia> triu(a,3) -4×4 Array{Float64,2}: - 0.0 0.0 0.0 1.0 - 0.0 0.0 0.0 0.0 - 0.0 0.0 0.0 0.0 - 0.0 0.0 0.0 0.0 - -julia> triu(a,-3) -4×4 Array{Float64,2}: - 1.0 1.0 1.0 1.0 - 1.0 1.0 1.0 1.0 - 1.0 1.0 1.0 1.0 - 1.0 1.0 1.0 1.0 -``` -""" -triu(M::AbstractMatrix,k::Integer) = triu!(copy(M),k) - -""" - tril(M, k::Integer) - -Returns the lower triangle of `M` starting from the `k`th superdiagonal. - -# Example - -```jldoctest -julia> a = ones(4,4) -4×4 Array{Float64,2}: - 1.0 1.0 1.0 1.0 - 1.0 1.0 1.0 1.0 - 1.0 1.0 1.0 1.0 - 1.0 1.0 1.0 1.0 - -julia> tril(a,3) -4×4 Array{Float64,2}: - 1.0 1.0 1.0 1.0 - 1.0 1.0 1.0 1.0 - 1.0 1.0 1.0 1.0 - 1.0 1.0 1.0 1.0 - -julia> tril(a,-3) -4×4 Array{Float64,2}: - 0.0 0.0 0.0 0.0 - 0.0 0.0 0.0 0.0 - 0.0 0.0 0.0 0.0 - 1.0 0.0 0.0 0.0 -``` -""" -tril(M::AbstractMatrix,k::Integer) = tril!(copy(M),k) - -""" - triu!(M) - -Upper triangle of a matrix, overwriting `M` in the process. -See also [`triu`](@ref). -""" -triu!(M::AbstractMatrix) = triu!(M,0) - -""" - tril!(M) - -Lower triangle of a matrix, overwriting `M` in the process. -See also [`tril`](@ref). -""" -tril!(M::AbstractMatrix) = tril!(M,0) - -diff(a::AbstractVector) = [ a[i+1] - a[i] for i=1:length(a)-1 ] - -""" - diff(A, [dim::Integer=1]) - -Finite difference operator of matrix or vector `A`. If `A` is a matrix, -compute the finite difference over a dimension `dim` (default `1`). - -# Example - -```jldoctest -julia> a = [2 4; 6 16] -2×2 Array{Int64,2}: - 2 4 - 6 16 - -julia> diff(a,2) -2×1 Array{Int64,2}: - 2 - 10 -``` -""" -function diff(A::AbstractMatrix, dim::Integer=1) - if dim == 1 - [A[i+1,j] - A[i,j] for i=1:size(A,1)-1, j=1:size(A,2)] - elseif dim == 2 - [A[i,j+1] - A[i,j] for i=1:size(A,1), j=1:size(A,2)-1] - else - throw(ArgumentError("dimension dim must be 1 or 2, got $dim")) - end -end - - -gradient(F::AbstractVector) = gradient(F, [1:length(F);]) - -""" - gradient(F::AbstractVector, [h::Real]) - -Compute differences along vector `F`, using `h` as the spacing between points. The default -spacing is one. - -# Example - -```jldoctest -julia> a = [2,4,6,8]; - -julia> gradient(a) -4-element Array{Float64,1}: - 2.0 - 2.0 - 2.0 - 2.0 -``` -""" -gradient(F::AbstractVector, h::Real) = gradient(F, [h*(1:length(F));]) - -diag(A::AbstractVector) = throw(ArgumentError("use diagm instead of diag to construct a diagonal matrix")) - -#diagm{T}(v::AbstractVecOrMat{T}) - -########################################################################################### -# Inner products and norms - -# special cases of vecnorm; note that they don't need to handle isempty(x) -function generic_vecnormMinusInf(x) - s = start(x) - (v, s) = next(x, s) - minabs = norm(v) - while !done(x, s) - (v, s) = next(x, s) - vnorm = norm(v) - minabs = ifelse(isnan(minabs) | (minabs < vnorm), minabs, vnorm) - end - return float(minabs) -end - -function generic_vecnormInf(x) - s = start(x) - (v, s) = next(x, s) - maxabs = norm(v) - while !done(x, s) - (v, s) = next(x, s) - vnorm = norm(v) - maxabs = ifelse(isnan(maxabs) | (maxabs > vnorm), maxabs, vnorm) - end - return float(maxabs) -end - -function generic_vecnorm1(x) - s = start(x) - (v, s) = next(x, s) - av = float(norm(v)) - T = typeof(av) - sum::promote_type(Float64, T) = av - while !done(x, s) - (v, s) = next(x, s) - sum += norm(v) - end - return convert(T, sum) -end - -# faster computation of norm(x)^2, avoiding overflow for integers -norm_sqr(x) = norm(x)^2 -norm_sqr(x::Number) = abs2(x) -norm_sqr(x::Union{T,Complex{T},Rational{T}}) where {T<:Integer} = abs2(float(x)) - -function generic_vecnorm2(x) - maxabs = vecnormInf(x) - (maxabs == 0 || isinf(maxabs)) && return maxabs - s = start(x) - (v, s) = next(x, s) - T = typeof(maxabs) - if isfinite(_length(x)*maxabs*maxabs) && maxabs*maxabs != 0 # Scaling not necessary - sum::promote_type(Float64, T) = norm_sqr(v) - while !done(x, s) - (v, s) = next(x, s) - sum += norm_sqr(v) - end - return convert(T, sqrt(sum)) - else - sum = abs2(norm(v)/maxabs) - while !done(x, s) - (v, s) = next(x, s) - sum += (norm(v)/maxabs)^2 - end - return convert(T, maxabs*sqrt(sum)) - end -end - -# Compute L_p norm ‖x‖ₚ = sum(abs(x).^p)^(1/p) -# (Not technically a "norm" for p < 1.) -function generic_vecnormp(x, p) - s = start(x) - (v, s) = next(x, s) - if p > 1 || p < -1 # might need to rescale to avoid overflow - maxabs = p > 1 ? vecnormInf(x) : vecnormMinusInf(x) - (maxabs == 0 || isinf(maxabs)) && return maxabs - T = typeof(maxabs) - else - T = typeof(float(norm(v))) - end - spp::promote_type(Float64, T) = p - if -1 <= p <= 1 || (isfinite(_length(x)*maxabs^spp) && maxabs^spp != 0) # scaling not necessary - sum::promote_type(Float64, T) = norm(v)^spp - while !done(x, s) - (v, s) = next(x, s) - sum += norm(v)^spp - end - return convert(T, sum^inv(spp)) - else # rescaling - sum = (norm(v)/maxabs)^spp - while !done(x, s) - (v, s) = next(x, s) - sum += (norm(v)/maxabs)^spp - end - return convert(T, maxabs*sum^inv(spp)) - end -end - -vecnormMinusInf(x) = generic_vecnormMinusInf(x) -vecnormInf(x) = generic_vecnormInf(x) -vecnorm1(x) = generic_vecnorm1(x) -vecnorm2(x) = generic_vecnorm2(x) -vecnormp(x, p) = generic_vecnormp(x, p) - -""" - vecnorm(A, p::Real=2) - -For any iterable container `A` (including arrays of any dimension) of numbers (or any -element type for which `norm` is defined), compute the `p`-norm (defaulting to `p=2`) as if -`A` were a vector of the corresponding length. - -The `p`-norm is defined as: -```math -\\|A\\|_p = \\left( \\sum_{i=1}^n | a_i | ^p \\right)^{1/p} -``` -with ``a_i`` the entries of ``A`` and ``n`` its length. - -`p` can assume any numeric value (even though not all values produce a -mathematically valid vector norm). In particular, `vecnorm(A, Inf)` returns the largest value -in `abs(A)`, whereas `vecnorm(A, -Inf)` returns the smallest. If `A` is a matrix and `p=2`, -then this is equivalent to the Frobenius norm. - -# Example - -```jldoctest -julia> vecnorm([1 2 3; 4 5 6; 7 8 9]) -16.881943016134134 - -julia> vecnorm([1 2 3 4 5 6 7 8 9]) -16.881943016134134 -``` -""" -function vecnorm(itr, p::Real=2) - isempty(itr) && return float(real(zero(eltype(itr)))) - if p == 2 - return vecnorm2(itr) - elseif p == 1 - return vecnorm1(itr) - elseif p == Inf - return vecnormInf(itr) - elseif p == 0 - return convert(typeof(float(real(zero(eltype(itr))))), - countnz(itr)) - elseif p == -Inf - return vecnormMinusInf(itr) - else - vecnormp(itr,p) - end -end - -""" - vecnorm(x::Number, p::Real=2) - -For numbers, return ``\\left( |x|^p \\right) ^{1/p}``. -""" -@inline vecnorm(x::Number, p::Real=2) = p == 0 ? (x==0 ? zero(abs(x)) : oneunit(abs(x))) : abs(x) - -function norm1(A::AbstractMatrix{T}) where T - m, n = size(A) - Tnorm = typeof(float(real(zero(T)))) - Tsum = promote_type(Float64, Tnorm) - nrm::Tsum = 0 - @inbounds begin - for j = 1:n - nrmj::Tsum = 0 - for i = 1:m - nrmj += norm(A[i,j]) - end - nrm = max(nrm,nrmj) - end - end - return convert(Tnorm, nrm) -end -function norm2(A::AbstractMatrix{T}) where T - m,n = size(A) - if m == 1 || n == 1 return vecnorm2(A) end - Tnorm = typeof(float(real(zero(T)))) - (m == 0 || n == 0) ? zero(Tnorm) : convert(Tnorm, svdvals(A)[1]) -end -function normInf(A::AbstractMatrix{T}) where T - m,n = size(A) - Tnorm = typeof(float(real(zero(T)))) - Tsum = promote_type(Float64, Tnorm) - nrm::Tsum = 0 - @inbounds begin - for i = 1:m - nrmi::Tsum = 0 - for j = 1:n - nrmi += norm(A[i,j]) - end - nrm = max(nrm,nrmi) - end - end - return convert(Tnorm, nrm) -end - -""" - norm(A::AbstractArray, p::Real=2) - -Compute the `p`-norm of a vector or the operator norm of a matrix `A`, -defaulting to the 2-norm. - - norm(A::AbstractVector, p::Real=2) - -For vectors, this is equivalent to [`vecnorm`](@ref) and equal to: -```math -\\|A\\|_p = \\left( \\sum_{i=1}^n | a_i | ^p \\right)^{1/p} -``` -with ``a_i`` the entries of ``A`` and ``n`` its length. - -`p` can assume any numeric value (even though not all values produce a -mathematically valid vector norm). In particular, `norm(A, Inf)` returns the largest value -in `abs(A)`, whereas `norm(A, -Inf)` returns the smallest. - -# Example - -```jldoctest -julia> v = [3, -2, 6] -3-element Array{Int64,1}: - 3 - -2 - 6 - -julia> norm(v) -7.0 - -julia> norm(v, Inf) -6.0 -``` -""" -norm(x::AbstractVector, p::Real=2) = vecnorm(x, p) - -""" - norm(A::AbstractMatrix, p::Real=2) - -For matrices, the matrix norm induced by the vector `p`-norm is used, where valid values of -`p` are `1`, `2`, or `Inf`. (Note that for sparse matrices, `p=2` is currently not -implemented.) Use [`vecnorm`](@ref) to compute the Frobenius norm. - -When `p=1`, the matrix norm is the maximum absolute column sum of `A`: -```math -\\|A\\|_1 = \\max_{1 ≤ j ≤ n} \\sum_{i=1}^m | a_{ij} | -``` -with ``a_{ij}`` the entries of ``A``, and ``m`` and ``n`` its dimensions. - -When `p=2`, the matrix norm is the spectral norm, equal to the largest -singular value of `A`. - -When `p=Inf`, the matrix norm is the maximum absolute row sum of `A`: -```math -\\|A\\|_\\infty = \\max_{1 ≤ i ≤ m} \\sum _{j=1}^n | a_{ij} | -``` - -# Example - -```jldoctest -julia> A = [1 -2 -3; 2 3 -1] -2×3 Array{Int64,2}: - 1 -2 -3 - 2 3 -1 - -julia> norm(A, Inf) -6.0 -``` -""" -function norm(A::AbstractMatrix, p::Real=2) - if p == 2 - return norm2(A) - elseif p == 1 - return norm1(A) - elseif p == Inf - return normInf(A) - else - throw(ArgumentError("invalid p-norm p=$p. Valid: 1, 2, Inf")) - end -end - -""" - norm(x::Number, p::Real=2) - -For numbers, return ``\\left( |x|^p \\right)^{1/p}``. -This is equivalent to [`vecnorm`](@ref). -""" -@inline norm(x::Number, p::Real=2) = vecnorm(x, p) - -@inline norm(tv::RowVector) = norm(transpose(tv)) - -""" - norm(A::RowVector, q::Real=2) - -For row vectors, return the ``q``-norm of `A`, which is equivalent to the p-norm with -value `p = q/(q-1)`. They coincide at `p = q = 2`. - -The difference in norm between a vector space and its dual arises to preserve -the relationship between duality and the inner product, and the result is -consistent with the p-norm of `1 × n` matrix. -""" -@inline norm(tv::RowVector, q::Real) = q == Inf ? norm(transpose(tv), 1) : norm(transpose(tv), q/(q-1)) - -function vecdot(x::AbstractArray, y::AbstractArray) - lx = _length(x) - if lx != _length(y) - throw(DimensionMismatch("first array has length $(lx) which does not match the length of the second, $(_length(y)).")) - end - if lx == 0 - return dot(zero(eltype(x)), zero(eltype(y))) - end - s = zero(dot(first(x), first(y))) - for (Ix, Iy) in zip(eachindex(x), eachindex(y)) - @inbounds s += dot(x[Ix], y[Iy]) - end - s -end - -""" - vecdot(x, y) - -For any iterable containers `x` and `y` (including arrays of any dimension) of numbers (or -any element type for which `dot` is defined), compute the Euclidean dot product (the sum of -`dot(x[i],y[i])`) as if they were vectors. - -# Examples -```jldoctest -julia> vecdot(1:5, 2:6) -70 - -julia> x = fill(2., (5,5)); - -julia> y = fill(3., (5,5)); - -julia> vecdot(x, y) -150.0 -``` -""" -function vecdot(x, y) # arbitrary iterables - ix = start(x) - if done(x, ix) - if !isempty(y) - throw(DimensionMismatch("x and y are of different lengths!")) - end - return dot(zero(eltype(x)), zero(eltype(y))) - end - iy = start(y) - if done(y, iy) - throw(DimensionMismatch("x and y are of different lengths!")) - end - (vx, ix) = next(x, ix) - (vy, iy) = next(y, iy) - s = dot(vx, vy) - while !done(x, ix) - if done(y, iy) - throw(DimensionMismatch("x and y are of different lengths!")) - end - (vx, ix) = next(x, ix) - (vy, iy) = next(y, iy) - s += dot(vx, vy) - end - if !done(y, iy) - throw(DimensionMismatch("x and y are of different lengths!")) - end - return s -end - -vecdot(x::Number, y::Number) = conj(x) * y - -dot(x::Number, y::Number) = vecdot(x, y) - -""" - dot(x, y) - ⋅(x,y) - -Compute the dot product. For complex vectors, the first vector is conjugated. - -# Example - -```jldoctest -julia> dot([1; 1], [2; 3]) -5 - -julia> dot([im; im], [1; 1]) -0 - 2im -``` -""" -dot(x::AbstractVector, y::AbstractVector) = vecdot(x, y) - -########################################################################################### - -""" - rank(M[, tol::Real]) - -Compute the rank of a matrix by counting how many singular -values of `M` have magnitude greater than `tol`. -By default, the value of `tol` is the largest -dimension of `M` multiplied by the [`eps`](@ref) -of the [`eltype`](@ref) of `M`. - -# Example -```jldoctest -julia> rank(eye(3)) -3 - -julia> rank(diagm([1, 0, 2])) -2 - -julia> rank(diagm([1, 0.001, 2]), 0.1) -2 - -julia> rank(diagm([1, 0.001, 2]), 0.00001) -3 -``` -""" -rank(A::AbstractMatrix, tol::Real) = mapreduce(x -> x > tol, +, 0, svdvals(A)) -function rank(A::AbstractMatrix) - m,n = size(A) - (m == 0 || n == 0) && return 0 - sv = svdvals(A) - return sum(sv .> maximum(size(A))*eps(sv[1])) -end -rank(x::Number) = x==0 ? 0 : 1 - -""" - trace(M) - -Matrix trace. Sums the diagonal elements of `M`. - -# Example - -```jldoctest -julia> A = [1 2; 3 4] -2×2 Array{Int64,2}: - 1 2 - 3 4 - -julia> trace(A) -5 -``` -""" -function trace(A::AbstractMatrix) - checksquare(A) - sum(diag(A)) -end -trace(x::Number) = x - -#kron(a::AbstractVector, b::AbstractVector) -#kron{T,S}(a::AbstractMatrix{T}, b::AbstractMatrix{S}) - -#det(a::AbstractMatrix) - -""" - inv(M) - -Matrix inverse. Computes matrix `N` such that -`M * N = I`, where `I` is the identity matrix. -Computed by solving the left-division -`N = M \\ I`. - -# Example - -```jldoctest -julia> M = [2 5; 1 3] -2×2 Array{Int64,2}: - 2 5 - 1 3 - -julia> N = inv(M) -2×2 Array{Float64,2}: - 3.0 -5.0 - -1.0 2.0 - -julia> M*N == N*M == eye(2) -true -``` -""" -function inv(A::AbstractMatrix{T}) where T - S = typeof(zero(T)/one(T)) # dimensionful - S0 = typeof(zero(T)/oneunit(T)) # dimensionless - A_ldiv_B!(factorize(convert(AbstractMatrix{S}, A)), eye(S0, checksquare(A))) -end - -""" - \\(A, B) - -Matrix division using a polyalgorithm. For input matrices `A` and `B`, the result `X` is -such that `A*X == B` when `A` is square. The solver that is used depends upon the structure -of `A`. If `A` is upper or lower triangular (or diagonal), no factorization of `A` is -required and the system is solved with either forward or backward substitution. -For non-triangular square matrices, an LU factorization is used. - -For rectangular `A` the result is the minimum-norm least squares solution computed by a -pivoted QR factorization of `A` and a rank estimate of `A` based on the R factor. - -When `A` is sparse, a similar polyalgorithm is used. For indefinite matrices, the `LDLt` -factorization does not use pivoting during the numerical factorization and therefore the -procedure can fail even for invertible matrices. - -# Example - -```jldoctest -julia> A = [1 0; 1 -2]; B = [32; -4]; - -julia> X = A \\ B -2-element Array{Float64,1}: - 32.0 - 18.0 - -julia> A * X == B -true -``` -""" -function (\)(A::AbstractMatrix, B::AbstractVecOrMat) - m, n = size(A) - if m == n - if istril(A) - if istriu(A) - return Diagonal(A) \ B - else - return LowerTriangular(A) \ B - end - end - if istriu(A) - return UpperTriangular(A) \ B - end - return lufact(A) \ B - end - return qrfact(A,Val{true}) \ B -end - -(\)(a::AbstractVector, b::AbstractArray) = reshape(a, length(a), 1) \ b -(/)(A::AbstractVecOrMat, B::AbstractVecOrMat) = (B' \ A')' -# \(A::StridedMatrix,x::Number) = inv(A)*x Should be added at some point when the old elementwise version has been deprecated long enough -# /(x::Number,A::StridedMatrix) = x*inv(A) - -cond(x::Number) = x == 0 ? Inf : 1.0 -cond(x::Number, p) = cond(x) - -#Skeel condition numbers -condskeel(A::AbstractMatrix, p::Real=Inf) = norm(abs.(inv(A))*abs.(A), p) - -""" - condskeel(M, [x, p::Real=Inf]) - -```math -\\kappa_S(M, p) = \\left\\Vert \\left\\vert M \\right\\vert \\left\\vert M^{-1} \\right\\vert \\right\\Vert_p \\\\ -\\kappa_S(M, x, p) = \\left\\Vert \\left\\vert M \\right\\vert \\left\\vert M^{-1} \\right\\vert \\left\\vert x \\right\\vert \\right\\Vert_p -``` - -Skeel condition number ``\\kappa_S`` of the matrix `M`, optionally with respect to the -vector `x`, as computed using the operator `p`-norm. ``\\left\\vert M \\right\\vert`` -denotes the matrix of (entry wise) absolute values of ``M``; -``\\left\\vert M \\right\\vert_{ij} = \\left\\vert M_{ij} \\right\\vert``. -Valid values for `p` are `1`, `2` and `Inf` (default). - -This quantity is also known in the literature as the Bauer condition number, relative -condition number, or componentwise relative condition number. -""" -condskeel(A::AbstractMatrix, x::AbstractVector, p::Real=Inf) = norm(abs.(inv(A))*(abs.(A)*abs.(x)), p) - -""" - issymmetric(A) -> Bool - -Test whether a matrix is symmetric. - -# Examples - -```jldoctest -julia> a = [1 2; 2 -1] -2×2 Array{Int64,2}: - 1 2 - 2 -1 - -julia> issymmetric(a) -true - -julia> b = [1 im; -im 1] -2×2 Array{Complex{Int64},2}: - 1+0im 0+1im - 0-1im 1+0im - -julia> issymmetric(b) -false -``` -""" -function issymmetric(A::AbstractMatrix) - indsm, indsn = indices(A) - if indsm != indsn - return false - end - for i = first(indsn):last(indsn), j = (i):last(indsn) - if A[i,j] != transpose(A[j,i]) - return false - end - end - return true -end - -issymmetric(x::Number) = x == x - -""" - ishermitian(A) -> Bool - -Test whether a matrix is Hermitian. - -# Examples - -```jldoctest -julia> a = [1 2; 2 -1] -2×2 Array{Int64,2}: - 1 2 - 2 -1 - -julia> ishermitian(a) -true - -julia> b = [1 im; -im 1] -2×2 Array{Complex{Int64},2}: - 1+0im 0+1im - 0-1im 1+0im - -julia> ishermitian(b) -true -``` -""" -function ishermitian(A::AbstractMatrix) - indsm, indsn = indices(A) - if indsm != indsn - return false - end - for i = indsn, j = i:last(indsn) - if A[i,j] != ctranspose(A[j,i]) - return false - end - end - return true -end - -ishermitian(x::Number) = (x == conj(x)) - -""" - istriu(A) -> Bool - -Test whether a matrix is upper triangular. - -# Examples - -```jldoctest -julia> a = [1 2; 2 -1] -2×2 Array{Int64,2}: - 1 2 - 2 -1 - -julia> istriu(a) -false - -julia> b = [1 im; 0 -1] -2×2 Array{Complex{Int64},2}: - 1+0im 0+1im - 0+0im -1+0im - -julia> istriu(b) -true -``` -""" -function istriu(A::AbstractMatrix) - m, n = size(A) - for j = 1:min(n,m-1), i = j+1:m - if A[i,j] != 0 - return false - end - end - return true -end - -""" - istril(A) -> Bool - -Test whether a matrix is lower triangular. - -# Examples - -```jldoctest -julia> a = [1 2; 2 -1] -2×2 Array{Int64,2}: - 1 2 - 2 -1 - -julia> istril(a) -false - -julia> b = [1 0; -im -1] -2×2 Array{Complex{Int64},2}: - 1+0im 0+0im - 0-1im -1+0im - -julia> istril(b) -true -``` -""" -function istril(A::AbstractMatrix) - m, n = size(A) - for j = 2:n, i = 1:min(j-1,m) - if A[i,j] != 0 - return false - end - end - return true -end - -""" - isdiag(A) -> Bool - -Test whether a matrix is diagonal. - -# Examples - -```jldoctest -julia> a = [1 2; 2 -1] -2×2 Array{Int64,2}: - 1 2 - 2 -1 - -julia> isdiag(a) -false - -julia> b = [im 0; 0 -im] -2×2 Array{Complex{Int64},2}: - 0+1im 0+0im - 0+0im 0-1im - -julia> isdiag(b) -true -``` -""" -isdiag(A::AbstractMatrix) = istril(A) && istriu(A) - -istriu(x::Number) = true -istril(x::Number) = true -isdiag(x::Number) = true - -""" - linreg(x, y) - -Perform simple linear regression using Ordinary Least Squares. Returns `a` and `b` such -that `a + b*x` is the closest straight line to the given points `(x, y)`, i.e., such that -the squared error between `y` and `a + b*x` is minimized. - -**Examples:** - - using PyPlot - x = 1.0:12.0 - y = [5.5, 6.3, 7.6, 8.8, 10.9, 11.79, 13.48, 15.02, 17.77, 20.81, 22.0, 22.99] - a, b = linreg(x, y) # Linear regression - plot(x, y, "o") # Plot (x, y) points - plot(x, a + b*x) # Plot line determined by linear regression - -See also: - -`\\`, [`cov`](@ref), [`std`](@ref), [`mean`](@ref). - -""" -function linreg(x::AbstractVector, y::AbstractVector) - # Least squares given - # Y = a + b*X - # where - # b = cov(X, Y)/var(X) - # a = mean(Y) - b*mean(X) - if size(x) != size(y) - throw(DimensionMismatch("x has size $(size(x)) and y has size $(size(y)), " * - "but these must be the same size")) - end - mx = mean(x) - my = mean(y) - # don't need to worry about the scaling (n vs n - 1) since they cancel in the ratio - b = Base.covm(x, mx, y, my)/Base.varm(x, mx) - a = my - b*mx - return (a, b) -end - -# multiply by diagonal matrix as vector -#diagmm!(C::AbstractMatrix, A::AbstractMatrix, b::AbstractVector) - -#diagmm!(C::AbstractMatrix, b::AbstractVector, A::AbstractMatrix) - -scale!(A::AbstractMatrix, b::AbstractVector) = scale!(A,A,b) -scale!(b::AbstractVector, A::AbstractMatrix) = scale!(A,b,A) - -#diagmm(A::AbstractMatrix, b::AbstractVector) -#diagmm(b::AbstractVector, A::AbstractMatrix) - -#^(A::AbstractMatrix, p::Number) - -#findmax(a::AbstractArray) -#findmin(a::AbstractArray) - -""" - peakflops(n::Integer=2000; parallel::Bool=false) - -`peakflops` computes the peak flop rate of the computer by using double precision -[`gemm!`](@ref Base.LinAlg.BLAS.gemm!). By default, if no arguments are specified, it -multiplies a matrix of size `n x n`, where `n = 2000`. If the underlying BLAS is using -multiple threads, higher flop rates are realized. The number of BLAS threads can be set with -[`BLAS.set_num_threads(n)`](@ref). - -If the keyword argument `parallel` is set to `true`, `peakflops` is run in parallel on all -the worker processors. The flop rate of the entire parallel computer is returned. When -running in parallel, only 1 BLAS thread is used. The argument `n` still refers to the size -of the problem that is solved on each processor. -""" -function peakflops(n::Integer=2000; parallel::Bool=false) - a = ones(Float64,100,100) - t = @elapsed a2 = a*a - a = ones(Float64,n,n) - t = @elapsed a2 = a*a - @assert a2[1,1] == n - parallel ? sum(pmap(peakflops, [ n for i in 1:nworkers()])) : (2*Float64(n)^3/t) -end - -# BLAS-like in-place y = x*α+y function (see also the version in blas.jl -# for BlasFloat Arrays) -function axpy!(α, x::AbstractArray, y::AbstractArray) - n = _length(x) - if n != _length(y) - throw(DimensionMismatch("x has length $n, but y has length $(_length(y))")) - end - for (IY, IX) in zip(eachindex(y), eachindex(x)) - @inbounds y[IY] += x[IX]*α - end - y -end - -function axpy!(α, x::AbstractArray, rx::AbstractArray{<:Integer}, y::AbstractArray, ry::AbstractArray{<:Integer}) - if _length(rx) != _length(ry) - throw(DimensionMismatch("rx has length $(_length(rx)), but ry has length $(_length(ry))")) - elseif !checkindex(Bool, linearindices(x), rx) - throw(BoundsError(x, rx)) - elseif !checkindex(Bool, linearindices(y), ry) - throw(BoundsError(y, ry)) - end - for (IY, IX) in zip(eachindex(ry), eachindex(rx)) - @inbounds y[ry[IY]] += x[rx[IX]]*α - end - y -end - - -# Elementary reflection similar to LAPACK. The reflector is not Hermitian but -# ensures that tridiagonalization of Hermitian matrices become real. See lawn72 -@inline function reflector!(x::AbstractVector) - n = length(x) - @inbounds begin - ξ1 = x[1] - normu = abs2(ξ1) - for i = 2:n - normu += abs2(x[i]) - end - if normu == zero(normu) - return zero(ξ1/normu) - end - normu = sqrt(normu) - ν = copysign(normu, real(ξ1)) - ξ1 += ν - x[1] = -ν - for i = 2:n - x[i] /= ξ1 - end - end - ξ1/ν -end - -# apply reflector from left -@inline function reflectorApply!(x::AbstractVector, τ::Number, A::StridedMatrix) - m, n = size(A) - if length(x) != m - throw(DimensionMismatch("reflector has length $(length(x)), which must match the first dimension of matrix A, $m")) - end - @inbounds begin - for j = 1:n - # dot - vAj = A[1, j] - for i = 2:m - vAj += x[i]'*A[i, j] - end - - vAj = τ'*vAj - - # ger - A[1, j] -= vAj - for i = 2:m - A[i, j] -= x[i]*vAj - end - end - end - return A -end - -""" - det(M) - -Matrix determinant. - -# Example - -```jldoctest -julia> M = [1 0; 2 2] -2×2 Array{Int64,2}: - 1 0 - 2 2 - -julia> det(M) -2.0 -``` -""" -function det(A::AbstractMatrix{T}) where T - if istriu(A) || istril(A) - S = typeof((one(T)*zero(T) + zero(T))/one(T)) - return convert(S, det(UpperTriangular(A))) - end - return det(lufact(A)) -end -det(x::Number) = x - -""" - logabsdet(M) - -Log of absolute value of matrix determinant. Equivalent to -`(log(abs(det(M))), sign(det(M)))`, but may provide increased accuracy and/or speed. -""" -logabsdet(A::AbstractMatrix) = logabsdet(lufact(A)) - -""" - logdet(M) - -Log of matrix determinant. Equivalent to `log(det(M))`, but may provide -increased accuracy and/or speed. - -# Examples - -```jldoctest -julia> M = [1 0; 2 2] -2×2 Array{Int64,2}: - 1 0 - 2 2 - -julia> logdet(M) -0.6931471805599453 - -julia> logdet(eye(3)) -0.0 -``` -""" -function logdet(A::AbstractMatrix) - d,s = logabsdet(A) - return d + log(s) -end - -const NumberArray{T<:Number} = AbstractArray{T} - -""" - promote_leaf_eltypes(itr) - -For an (possibly nested) iterable object `itr`, promote the types of leaf -elements. Equivalent to `promote_type(typeof(leaf1), typeof(leaf2), ...)`. -Currently supports only numeric leaf elements. - -# Example - -```jldoctest -julia> a = [[1,2, [3,4]], 5.0, [6im, [7.0, 8.0]]] -3-element Array{Any,1}: - Any[1,2,[3,4]] - 5.0 - Any[0+6im,[7.0,8.0]] - -julia> promote_leaf_eltypes(a) -Complex{Float64} -``` -""" -promote_leaf_eltypes(x::Union{AbstractArray{T},Tuple{Vararg{T}}}) where {T<:Number} = T -promote_leaf_eltypes(x::Union{AbstractArray{T},Tuple{Vararg{T}}}) where {T<:NumberArray} = eltype(T) -promote_leaf_eltypes(x::T) where {T} = T -promote_leaf_eltypes(x::Union{AbstractArray,Tuple}) = mapreduce(promote_leaf_eltypes, promote_type, Bool, x) - -# isapprox: approximate equality of arrays [like isapprox(Number,Number)] -# Supports nested arrays; e.g., for `a = [[1,2, [3,4]], 5.0, [6im, [7.0, 8.0]]]` -# `a ≈ a` is `true`. -function isapprox(x::AbstractArray, y::AbstractArray; - rtol::Real=Base.rtoldefault(promote_leaf_eltypes(x),promote_leaf_eltypes(y)), - atol::Real=0, nans::Bool=false, norm::Function=vecnorm) - d = norm(x - y) - if isfinite(d) - return d <= atol + rtol*max(norm(x), norm(y)) - else - # Fall back to a component-wise approximate comparison - return all(ab -> isapprox(ab[1], ab[2]; rtol=rtol, atol=atol, nans=nans), zip(x, y)) - end -end - -""" - normalize!(v::AbstractVector, p::Real=2) - -Normalize the vector `v` in-place so that its `p`-norm equals unity, -i.e. `norm(v, p) == 1`. -See also [`normalize`](@ref) and [`vecnorm`](@ref). -""" -function normalize!(v::AbstractVector, p::Real=2) - nrm = norm(v, p) - __normalize!(v, nrm) -end - -@inline function __normalize!(v::AbstractVector, nrm::AbstractFloat) - # The largest positive floating point number whose inverse is less than infinity - δ = inv(prevfloat(typemax(nrm))) - - if nrm ≥ δ # Safe to multiply with inverse - invnrm = inv(nrm) - scale!(v, invnrm) - - else # scale elements to avoid overflow - εδ = eps(one(nrm))/δ - scale!(v, εδ) - scale!(v, inv(nrm*εδ)) - end - - v -end - -""" - normalize(v::AbstractVector, p::Real=2) - -Normalize the vector `v` so that its `p`-norm equals unity, -i.e. `norm(v, p) == vecnorm(v, p) == 1`. -See also [`normalize!`](@ref) and [`vecnorm`](@ref). - -# Examples - -```jldoctest -julia> a = [1,2,4]; - -julia> b = normalize(a) -3-element Array{Float64,1}: - 0.218218 - 0.436436 - 0.872872 - -julia> norm(b) -1.0 - -julia> c = normalize(a, 1) -3-element Array{Float64,1}: - 0.142857 - 0.285714 - 0.571429 - -julia> norm(c, 1) -1.0 -``` -""" -function normalize(v::AbstractVector, p::Real = 2) - nrm = norm(v, p) - if !isempty(v) - vv = copy_oftype(v, typeof(v[1]/nrm)) - return __normalize!(vv, nrm) - else - T = typeof(zero(eltype(v))/nrm) - return T[] - end -end diff --git a/julia-0.6.3/share/julia/base/linalg/givens.jl b/julia-0.6.3/share/julia/base/linalg/givens.jl deleted file mode 100644 index ed1c967..0000000 --- a/julia-0.6.3/share/julia/base/linalg/givens.jl +++ /dev/null @@ -1,363 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license -# givensAlgorithm functions are derived from LAPACK, see below - -abstract type AbstractRotation{T} end - -transpose(R::AbstractRotation) = error("transpose not implemented for $(typeof(R)). Consider using conjugate transpose (') instead of transpose (.').") - -function *(R::AbstractRotation{T}, A::AbstractVecOrMat{S}) where {T,S} - TS = typeof(zero(T)*zero(S) + zero(T)*zero(S)) - A_mul_B!(convert(AbstractRotation{TS}, R), TS == S ? copy(A) : convert(AbstractArray{TS}, A)) -end -function A_mul_Bc(A::AbstractVecOrMat{T}, R::AbstractRotation{S}) where {T,S} - TS = typeof(zero(T)*zero(S) + zero(T)*zero(S)) - A_mul_Bc!(TS == T ? copy(A) : convert(AbstractArray{TS}, A), convert(AbstractRotation{TS}, R)) -end -""" - LinAlg.Givens(i1,i2,c,s) -> G - -A Givens rotation linear operator. The fields `c` and `s` represent the cosine and sine of -the rotation angle, respectively. The `Givens` type supports left multiplication `G*A` and -conjugated transpose right multiplication `A*G'`. The type doesn't have a `size` and can -therefore be multiplied with matrices of arbitrary size as long as `i2<=size(A,2)` for -`G*A` or `i2<=size(A,1)` for `A*G'`. - -See also: [`givens`](@ref) -""" -struct Givens{T} <: AbstractRotation{T} - i1::Int - i2::Int - c::T - s::T -end -mutable struct Rotation{T} <: AbstractRotation{T} - rotations::Vector{Givens{T}} -end - -convert(::Type{Givens{T}}, G::Givens{T}) where {T} = G -convert(::Type{Givens{T}}, G::Givens) where {T} = Givens(G.i1, G.i2, convert(T, G.c), convert(T, G.s)) -convert(::Type{Rotation{T}}, R::Rotation{T}) where {T} = R -convert(::Type{Rotation{T}}, R::Rotation) where {T} = Rotation{T}([convert(Givens{T}, g) for g in R.rotations]) -convert(::Type{AbstractRotation{T}}, G::Givens) where {T} = convert(Givens{T}, G) -convert(::Type{AbstractRotation{T}}, R::Rotation) where {T} = convert(Rotation{T}, R) - -ctranspose(G::Givens) = Givens(G.i1, G.i2, conj(G.c), -G.s) -ctranspose(R::Rotation{T}) where {T} = Rotation{T}(reverse!([ctranspose(r) for r in R.rotations])) - -realmin2(::Type{Float32}) = reinterpret(Float32, 0x26000000) -realmin2(::Type{Float64}) = reinterpret(Float64, 0x21a0000000000000) -realmin2(::Type{T}) where {T} = (twopar = 2one(T); twopar^trunc(Integer,log(realmin(T)/eps(T))/log(twopar)/twopar)) - -# derived from LAPACK's dlartg -# Copyright: -# Univ. of Tennessee -# Univ. of California Berkeley -# Univ. of Colorado Denver -# NAG Ltd. -function givensAlgorithm(f::T, g::T) where T<:AbstractFloat - onepar = one(T) - twopar = 2one(T) - T0 = typeof(onepar) # dimensionless - zeropar = T0(zero(T)) # must be dimensionless - - # need both dimensionful and dimensionless versions of these: - safmn2 = realmin2(T0) - safmn2u = realmin2(T) - safmx2 = one(T)/safmn2 - safmx2u = oneunit(T)/safmn2 - - if g == 0 - cs = onepar - sn = zeropar - r = f - elseif f == 0 - cs = zeropar - sn = onepar - r = g - else - f1 = f - g1 = g - scalepar = max(abs(f1), abs(g1)) - if scalepar >= safmx2u - count = 0 - while true - count += 1 - f1 *= safmn2 - g1 *= safmn2 - scalepar = max(abs(f1), abs(g1)) - if scalepar < safmx2u break end - end - r = sqrt(f1*f1 + g1*g1) - cs = f1/r - sn = g1/r - for i = 1:count - r *= safmx2 - end - elseif scalepar <= safmn2u - count = 0 - while true - count += 1 - f1 *= safmx2 - g1 *= safmx2 - scalepar = max(abs(f1), abs(g1)) - if scalepar > safmn2u break end - end - r = sqrt(f1*f1 + g1*g1) - cs = f1/r - sn = g1/r - for i = 1:count - r *= safmn2 - end - else - r = sqrt(f1*f1 + g1*g1) - cs = f1/r - sn = g1/r - end - if abs(f) > abs(g) && cs < 0 - cs = -cs - sn = -sn - r = -r - end - end - return cs, sn, r -end - -# derived from LAPACK's zlartg -# Copyright: -# Univ. of Tennessee -# Univ. of California Berkeley -# Univ. of Colorado Denver -# NAG Ltd. -function givensAlgorithm(f::Complex{T}, g::Complex{T}) where T<:AbstractFloat - twopar, onepar = 2one(T), one(T) - T0 = typeof(onepar) # dimensionless - zeropar = T0(zero(T)) # must be dimensionless - czero = complex(zeropar) - - abs1(ff) = max(abs(real(ff)), abs(imag(ff))) - safmin = realmin(T0) - safmn2 = realmin2(T0) - safmn2u = realmin2(T) - safmx2 = one(T)/safmn2 - safmx2u = oneunit(T)/safmn2 - scalepar = max(abs1(f), abs1(g)) - fs = f - gs = g - count = 0 - if scalepar >= safmx2u - while true - count += 1 - fs *= safmn2 - gs *= safmn2 - scalepar *= safmn2 - if scalepar < safmx2u break end - end - elseif scalepar <= safmn2u - if g == 0 - cs = onepar - sn = czero - r = f - return cs, sn, r - end - while true - count -= 1 - fs *= safmx2 - gs *= safmx2 - scalepar *= safmx2 - if scalepar > safmn2u break end - end - end - f2 = abs2(fs) - g2 = abs2(gs) - if f2 <= max(g2, oneunit(T))*safmin - # This is a rare case: F is very small. - if f == 0 - cs = zero(T) - r = complex(hypot(real(g), imag(g))) - # do complex/real division explicitly with two real divisions - d = hypot(real(gs), imag(gs)) - sn = complex(real(gs)/d, -imag(gs)/d) - return cs, sn, r - end - f2s = hypot(real(fs), imag(fs)) - # g2 and g2s are accurate - # g2 is at least safmin, and g2s is at least safmn2 - g2s = sqrt(g2) - # error in cs from underflow in f2s is at most - # unfl / safmn2 .lt. sqrt(unfl*eps) .lt. eps - # if max(g2,one)=g2, then f2 .lt. g2*safmin, - # and so cs .lt. sqrt(safmin) - # if max(g2,one)=one, then f2 .lt. safmin - # and so cs .lt. sqrt(safmin)/safmn2 = sqrt(eps) - # therefore, cs = f2s/g2s / sqrt( 1 + (f2s/g2s)**2 ) = f2s/g2s - cs = f2s/g2s - # make sure abs(ff) = 1 - # do complex/real division explicitly with 2 real divisions - if abs1(f) > 1 - d = hypot(real(f), imag(f)) - ff = complex(real(f)/d, imag(f)/d) - else - dr = safmx2*real(f) - di = safmx2*imag(f) - d = hypot(dr, di) - ff = complex(dr/d, di/d) - end - sn = ff*complex(real(gs)/g2s, -imag(gs)/g2s) - r = cs*f + sn*g - else - # This is the most common case. - # Neither F2 nor F2/G2 are less than SAFMIN - # F2S cannot overflow, and it is accurate - f2s = sqrt(onepar + g2/f2) - # do the f2s(real)*fs(complex) multiply with two real multiplies - r = complex(f2s*real(fs), f2s*imag(fs)) - cs = onepar/f2s - d = f2 + g2 - # do complex/real division explicitly with two real divisions - sn = complex(real(r)/d, imag(r)/d) - sn *= conj(gs) - if count != 0 - if count > 0 - for i = 1:count - r *= safmx2 - end - else - for i = 1:-count - r *= safmn2 - end - end - end - end - return cs, sn, r -end - -""" - - givens{T}(f::T, g::T, i1::Integer, i2::Integer) -> (G::Givens, r::T) - -Computes the Givens rotation `G` and scalar `r` such that for any vector `x` where -``` -x[i1] = f -x[i2] = g -``` -the result of the multiplication -``` -y = G*x -``` -has the property that -``` -y[i1] = r -y[i2] = 0 -``` - -See also: [`LinAlg.Givens`](@ref) -""" -function givens(f::T, g::T, i1::Integer, i2::Integer) where T - if i1 == i2 - throw(ArgumentError("Indices must be distinct.")) - end - c, s, r = givensAlgorithm(f, g) - if i1 > i2 - s = -conj(s) - i1,i2 = i2,i1 - end - Givens(i1, i2, convert(T, c), convert(T, s)), r -end -""" - givens(A::AbstractArray, i1::Integer, i2::Integer, j::Integer) -> (G::Givens, r) - -Computes the Givens rotation `G` and scalar `r` such that the result of the multiplication -``` -B = G*A -``` -has the property that -``` -B[i1,j] = r -B[i2,j] = 0 -``` - -See also: [`LinAlg.Givens`](@ref) -""" -givens(A::AbstractMatrix, i1::Integer, i2::Integer, j::Integer) = - givens(A[i1,j], A[i2,j],i1,i2) - - -""" - givens(x::AbstractVector, i1::Integer, i2::Integer) -> (G::Givens, r) - -Computes the Givens rotation `G` and scalar `r` such that the result of the multiplication -``` -B = G*x -``` -has the property that -``` -B[i1] = r -B[i2] = 0 -``` - -See also: [`LinAlg.Givens`](@ref) -""" -givens(x::AbstractVector, i1::Integer, i2::Integer) = - givens(x[i1], x[i2], i1, i2) - - -function getindex(G::Givens, i::Integer, j::Integer) - if i == j - if i == G.i1 || i == G.i2 - G.c - else - oneunit(G.c) - end - elseif i == G.i1 && j == G.i2 - G.s - elseif i == G.i2 && j == G.i1 - -conj(G.s) - else - zero(G.s) - end -end - - -A_mul_B!(G1::Givens, G2::Givens) = error("Operation not supported. Consider *") - -function A_mul_B!(G::Givens, A::AbstractVecOrMat) - m, n = size(A, 1), size(A, 2) - if G.i2 > m - throw(DimensionMismatch("column indices for rotation are outside the matrix")) - end - @inbounds @simd for i = 1:n - a1, a2 = A[G.i1,i], A[G.i2,i] - A[G.i1,i] = G.c *a1 + G.s*a2 - A[G.i2,i] = -conj(G.s)*a1 + G.c*a2 - end - return A -end -function A_mul_Bc!(A::AbstractMatrix, G::Givens) - m, n = size(A, 1), size(A, 2) - if G.i2 > n - throw(DimensionMismatch("column indices for rotation are outside the matrix")) - end - @inbounds @simd for i = 1:m - a1, a2 = A[i,G.i1], A[i,G.i2] - A[i,G.i1] = a1*G.c + a2*conj(G.s) - A[i,G.i2] = -a1*G.s + a2*G.c - end - return A -end -function A_mul_B!(G::Givens, R::Rotation) - push!(R.rotations, G) - return R -end -function A_mul_B!(R::Rotation, A::AbstractMatrix) - @inbounds for i = 1:length(R.rotations) - A_mul_B!(R.rotations[i], A) - end - return A -end -function A_mul_Bc!(A::AbstractMatrix, R::Rotation) - @inbounds for i = 1:length(R.rotations) - A_mul_Bc!(A, R.rotations[i]) - end - return A -end -*(G1::Givens{T}, G2::Givens{T}) where {T} = Rotation(push!(push!(Givens{T}[], G2), G1)) diff --git a/julia-0.6.3/share/julia/base/linalg/hessenberg.jl b/julia-0.6.3/share/julia/base/linalg/hessenberg.jl deleted file mode 100644 index 22aaf5b..0000000 --- a/julia-0.6.3/share/julia/base/linalg/hessenberg.jl +++ /dev/null @@ -1,115 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -struct Hessenberg{T,S<:AbstractMatrix} <: Factorization{T} - factors::S - τ::Vector{T} - Hessenberg{T,S}(factors::AbstractMatrix{T}, τ::Vector{T}) where {T,S<:AbstractMatrix} = - new(factors, τ) -end -Hessenberg(factors::AbstractMatrix{T}, τ::Vector{T}) where {T} = Hessenberg{T,typeof(factors)}(factors, τ) - -Hessenberg(A::StridedMatrix) = Hessenberg(LAPACK.gehrd!(A)...) - - -""" - hessfact!(A) -> Hessenberg - -`hessfact!` is the same as [`hessfact`](@ref), but saves space by overwriting -the input `A`, instead of creating a copy. -""" -hessfact!(A::StridedMatrix{<:BlasFloat}) = Hessenberg(A) - -hessfact(A::StridedMatrix{<:BlasFloat}) = hessfact!(copy(A)) - -""" - hessfact(A) -> Hessenberg - -Compute the Hessenberg decomposition of `A` and return a `Hessenberg` object. If `F` is the -factorization object, the unitary matrix can be accessed with `F[:Q]` and the Hessenberg -matrix with `F[:H]`. When `Q` is extracted, the resulting type is the `HessenbergQ` object, -and may be converted to a regular matrix with [`convert(Array, _)`](@ref) - (or `Array(_)` for short). - -# Example - -```jldoctest -julia> A = [4. 9. 7.; 4. 4. 1.; 4. 3. 2.] -3×3 Array{Float64,2}: - 4.0 9.0 7.0 - 4.0 4.0 1.0 - 4.0 3.0 2.0 - -julia> F = hessfact(A); - -julia> F[:Q] * F[:H] * F[:Q]' -3×3 Array{Float64,2}: - 4.0 9.0 7.0 - 4.0 4.0 1.0 - 4.0 3.0 2.0 -``` -""" -function hessfact(A::StridedMatrix{T}) where T - S = promote_type(Float32, typeof(zero(T)/norm(one(T)))) - return hessfact!(copy_oftype(A, S)) -end - -struct HessenbergQ{T,S<:AbstractMatrix} <: AbstractMatrix{T} - factors::S - τ::Vector{T} - HessenbergQ{T,S}(factors::AbstractMatrix{T}, τ::Vector{T}) where {T,S<:AbstractMatrix} = new(factors, τ) -end -HessenbergQ(factors::AbstractMatrix{T}, τ::Vector{T}) where {T} = HessenbergQ{T,typeof(factors)}(factors, τ) -HessenbergQ(A::Hessenberg) = HessenbergQ(A.factors, A.τ) -size(A::HessenbergQ, d) = size(A.factors, d) -size(A::HessenbergQ) = size(A.factors) - -function getindex(A::Hessenberg, d::Symbol) - d == :Q && return HessenbergQ(A) - d == :H && return triu(A.factors, -1) - throw(KeyError(d)) -end - -function getindex(A::HessenbergQ, i::Integer, j::Integer) - x = zeros(eltype(A), size(A, 1)) - x[i] = 1 - y = zeros(eltype(A), size(A, 2)) - y[j] = 1 - return dot(x, A_mul_B!(A, y)) -end - -## reconstruct the original matrix -convert(::Type{Matrix}, A::HessenbergQ{<:BlasFloat}) = LAPACK.orghr!(1, size(A.factors, 1), copy(A.factors), A.τ) -convert(::Type{Array}, A::HessenbergQ) = convert(Matrix, A) -full(A::HessenbergQ) = convert(Array, A) -convert(::Type{AbstractMatrix}, F::Hessenberg) = (fq = Array(F[:Q]); (fq * F[:H]) * fq') -convert(::Type{AbstractArray}, F::Hessenberg) = convert(AbstractMatrix, F) -convert(::Type{Matrix}, F::Hessenberg) = convert(Array, convert(AbstractArray, F)) -convert(::Type{Array}, F::Hessenberg) = convert(Matrix, F) -full(F::Hessenberg) = convert(AbstractArray, F) - -A_mul_B!(Q::HessenbergQ{T}, X::StridedVecOrMat{T}) where {T<:BlasFloat} = - LAPACK.ormhr!('L', 'N', 1, size(Q.factors, 1), Q.factors, Q.τ, X) -A_mul_B!(X::StridedMatrix{T}, Q::HessenbergQ{T}) where {T<:BlasFloat} = - LAPACK.ormhr!('R', 'N', 1, size(Q.factors, 1), Q.factors, Q.τ, X) -Ac_mul_B!(Q::HessenbergQ{T}, X::StridedVecOrMat{T}) where {T<:BlasFloat} = - LAPACK.ormhr!('L', ifelse(T<:Real, 'T', 'C'), 1, size(Q.factors, 1), Q.factors, Q.τ, X) -A_mul_Bc!(X::StridedMatrix{T}, Q::HessenbergQ{T}) where {T<:BlasFloat} = - LAPACK.ormhr!('R', ifelse(T<:Real, 'T', 'C'), 1, size(Q.factors, 1), Q.factors, Q.τ, X) - - -function (*)(Q::HessenbergQ{T}, X::StridedVecOrMat{S}) where {T,S} - TT = typeof(zero(T)*zero(S) + zero(T)*zero(S)) - return A_mul_B!(Q, copy_oftype(X, TT)) -end -function (*)(X::StridedVecOrMat{S}, Q::HessenbergQ{T}) where {T,S} - TT = typeof(zero(T)*zero(S) + zero(T)*zero(S)) - return A_mul_B!(copy_oftype(X, TT), Q) -end -function Ac_mul_B(Q::HessenbergQ{T}, X::StridedVecOrMat{S}) where {T,S} - TT = typeof(zero(T)*zero(S) + zero(T)*zero(S)) - return Ac_mul_B!(Q, copy_oftype(X, TT)) -end -function A_mul_Bc(X::StridedVecOrMat{S}, Q::HessenbergQ{T}) where {T,S} - TT = typeof(zero(T)*zero(S) + zero(T)*zero(S)) - return A_mul_Bc!(copy_oftype(X, TT), Q) -end diff --git a/julia-0.6.3/share/julia/base/linalg/lapack.jl b/julia-0.6.3/share/julia/base/linalg/lapack.jl deleted file mode 100644 index 07522f5..0000000 --- a/julia-0.6.3/share/julia/base/linalg/lapack.jl +++ /dev/null @@ -1,6050 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -## The LAPACK module of interfaces to LAPACK subroutines -module LAPACK - -const liblapack = Base.liblapack_name - -import ..LinAlg.BLAS.@blasfunc - -import ..LinAlg: BlasFloat, Char, BlasInt, LAPACKException, - DimensionMismatch, SingularException, PosDefException, chkstride1, checksquare - -using Base: iszero - -#Generic LAPACK error handlers -""" -Handle only negative LAPACK error codes - -*NOTE* use only if the positive error code is useful. -""" -function chkargsok(ret::BlasInt) - if ret < 0 - throw(ArgumentError("invalid argument #$(-ret) to LAPACK call")) - end -end - -"Handle all nonzero info codes" -function chklapackerror(ret::BlasInt) - if ret == 0 - return - elseif ret < 0 - throw(ArgumentError("invalid argument #$(-ret) to LAPACK call")) - else # ret > 0 - throw(LAPACKException(ret)) - end -end - -function chknonsingular(ret::BlasInt) - if ret > 0 - throw(SingularException(ret)) - end -end - -function chkposdef(ret::BlasInt) - if ret > 0 - throw(PosDefException(ret)) - end -end - -"Check that upper/lower (for special matrices) is correctly specified" -function chkuplo(uplo::Char) - if !(uplo == 'U' || uplo == 'L') - throw(ArgumentError("uplo argument must be 'U' (upper) or 'L' (lower), got $uplo")) - end - uplo -end - -"Check that {c}transpose is correctly specified" -function chktrans(trans::Char) - if !(trans == 'N' || trans == 'C' || trans == 'T') - throw(ArgumentError("trans argument must be 'N' (no transpose), 'T' (transpose), or 'C' (conjugate transpose), got $trans")) - end - trans -end - -"Check that left/right hand side multiply is correctly specified" -function chkside(side::Char) - if !(side == 'L' || side == 'R') - throw(ArgumentError("side argument must be 'L' (left hand multiply) or 'R' (right hand multiply), got $side")) - end - side -end - -"Check that unit diagonal flag is correctly specified" -function chkdiag(diag::Char) - if !(diag == 'U' || diag =='N') - throw(ArgumentError("diag argument must be 'U' (unit diagonal) or 'N' (non-unit diagonal), got $diag")) - end - diag -end - -subsetrows(X::AbstractVector, Y::AbstractArray, k) = Y[1:k] -subsetrows(X::AbstractMatrix, Y::AbstractArray, k) = Y[1:k, :] - -function chkfinite(A::StridedMatrix) - for a in A - if !isfinite(a) - throw(ArgumentError("matrix contains Infs or NaNs")) - end - end - return true -end - -# LAPACK version number -function laver() - major = Ref{BlasInt}(0) - minor = Ref{BlasInt}(0) - patch = Ref{BlasInt}(0) - ccall((@blasfunc(ilaver_), liblapack), Void, - (Ptr{BlasInt}, Ptr{BlasInt}, Ptr{BlasInt}), - major, minor, patch) - return major[], minor[], patch[] -end - -# (GB) general banded matrices, LU decomposition and solver -for (gbtrf, gbtrs, elty) in - ((:dgbtrf_,:dgbtrs_,:Float64), - (:sgbtrf_,:sgbtrs_,:Float32), - (:zgbtrf_,:zgbtrs_,:Complex128), - (:cgbtrf_,:cgbtrs_,:Complex64)) - @eval begin - # SUBROUTINE DGBTRF( M, N, KL, KU, AB, LDAB, IPIV, INFO ) - # * .. Scalar Arguments .. - # INTEGER INFO, KL, KU, LDAB, M, N - # * .. Array Arguments .. - # INTEGER IPIV( * ) - # DOUBLE PRECISION AB( LDAB, * ) - function gbtrf!(kl::Integer, ku::Integer, m::Integer, AB::StridedMatrix{$elty}) - chkstride1(AB) - n = size(AB, 2) - mnmn = min(m, n) - ipiv = similar(AB, BlasInt, mnmn) - info = Ref{BlasInt}() - ccall((@blasfunc($gbtrf), liblapack), Void, - (Ptr{BlasInt}, Ptr{BlasInt}, Ptr{BlasInt}, Ptr{BlasInt}, - Ptr{$elty}, Ptr{BlasInt}, Ptr{BlasInt}, Ptr{BlasInt}), - &m, &n, &kl, &ku, AB, &max(1,stride(AB,2)), ipiv, info) - chklapackerror(info[]) - AB, ipiv - end - - # SUBROUTINE DGBTRS( TRANS, N, KL, KU, NRHS, AB, LDAB, IPIV, B, LDB, INFO) - # * .. Scalar Arguments .. - # CHARACTER TRANS - # INTEGER INFO, KL, KU, LDAB, LDB, N, NRHS - # * .. Array Arguments .. - # INTEGER IPIV( * ) - # DOUBLE PRECISION AB( LDAB, * ), B( LDB, * ) - function gbtrs!(trans::Char, kl::Integer, ku::Integer, m::Integer, - AB::StridedMatrix{$elty}, ipiv::StridedVector{BlasInt}, - B::StridedVecOrMat{$elty}) - chkstride1(AB, B, ipiv) - chktrans(trans) - info = Ref{BlasInt}() - n = size(AB,2) - if m != n || m != size(B,1) - throw(DimensionMismatch("matrix AB has dimensions $(size(AB)), but right hand side matrix B has dimensions $(size(B))")) - end - ccall((@blasfunc($gbtrs), liblapack), Void, - (Ptr{UInt8}, Ptr{BlasInt}, Ptr{BlasInt}, Ptr{BlasInt}, Ptr{BlasInt}, - Ptr{$elty}, Ptr{BlasInt}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, - Ptr{BlasInt}), - &trans, &n, &kl, &ku, &size(B,2), AB, &max(1,stride(AB,2)), ipiv, - B, &max(1,stride(B,2)), info) - chklapackerror(info[]) - B - end - end -end - -""" - gbtrf!(kl, ku, m, AB) -> (AB, ipiv) - -Compute the LU factorization of a banded matrix `AB`. `kl` is the first -subdiagonal containing a nonzero band, `ku` is the last superdiagonal -containing one, and `m` is the first dimension of the matrix `AB`. Returns -the LU factorization in-place and `ipiv`, the vector of pivots used. -""" -gbtrf!(kl::Integer, ku::Integer, m::Integer, AB::StridedMatrix) - -""" - gbtrs!(trans, kl, ku, m, AB, ipiv, B) - -Solve the equation `AB * X = B`. `trans` determines the orientation of `AB`. It may -be `N` (no transpose), `T` (transpose), or `C` (conjugate transpose). `kl` is the -first subdiagonal containing a nonzero band, `ku` is the last superdiagonal -containing one, and `m` is the first dimension of the matrix `AB`. `ipiv` is the vector -of pivots returned from `gbtrf!`. Returns the vector or matrix `X`, overwriting `B` in-place. -""" -gbtrs!(trans::Char, kl::Integer, ku::Integer, m::Integer, AB::StridedMatrix, ipiv::StridedVector{BlasInt}, B::StridedVecOrMat) - -## (GE) general matrices: balancing and back-transforming -for (gebal, gebak, elty, relty) in - ((:dgebal_, :dgebak_, :Float64, :Float64), - (:sgebal_, :sgebak_, :Float32, :Float32), - (:zgebal_, :zgebak_, :Complex128, :Float64), - (:cgebal_, :cgebak_, :Complex64, :Float32)) - @eval begin - # SUBROUTINE DGEBAL( JOB, N, A, LDA, ILO, IHI, SCALE, INFO ) - #* .. Scalar Arguments .. - # CHARACTER JOB - # INTEGER IHI, ILP, INFO, LDA, N - # .. Array Arguments .. - # DOUBLE PRECISION A( LDA, * ), SCALE( * ) - function gebal!(job::Char, A::StridedMatrix{$elty}) - chkstride1(A) - n = checksquare(A) - chkfinite(A) # balancing routines don't support NaNs and Infs - ihi = Ref{BlasInt}() - ilo = Ref{BlasInt}() - scale = similar(A, $relty, n) - info = Ref{BlasInt}() - ccall((@blasfunc($gebal), liblapack), Void, - (Ptr{UInt8}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, - Ptr{BlasInt}, Ptr{BlasInt}, Ptr{$relty}, Ptr{BlasInt}), - &job, &n, A, &max(1,stride(A,2)), ilo, ihi, scale, info) - chklapackerror(info[]) - ilo[], ihi[], scale - end - - # SUBROUTINE DGEBAK( JOB, SIDE, N, ILO, IHI, SCALE, M, V, LDV, INFO ) - #* .. Scalar Arguments .. - # CHARACTER JOB, SIDE - # INTEGER IHI, ILP, INFO, LDV, M, N - # .. Array Arguments .. - # DOUBLE PRECISION SCALE( * ), V( LDV, * ) - function gebak!(job::Char, side::Char, - ilo::BlasInt, ihi::BlasInt, scale::StridedVector{$relty}, - V::StridedMatrix{$elty}) - chkstride1(scale, V) - chkside(side) - chkfinite(V) # balancing routines don't support NaNs and Infs - n = checksquare(V) - info = Ref{BlasInt}() - ccall((@blasfunc($gebak), liblapack), Void, - (Ptr{UInt8}, Ptr{UInt8}, Ptr{BlasInt}, Ptr{BlasInt}, Ptr{BlasInt}, - Ptr{$relty}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, Ptr{BlasInt}), - &job, &side, &size(V,1), &ilo, &ihi, scale, &n, V, &max(1,stride(V,2)), info) - chklapackerror(info[]) - V - end - end -end - -""" - gebal!(job, A) -> (ilo, ihi, scale) - -Balance the matrix `A` before computing its eigensystem or Schur factorization. -`job` can be one of `N` (`A` will not be permuted or scaled), `P` (`A` will only -be permuted), `S` (`A` will only be scaled), or `B` (`A` will be both permuted -and scaled). Modifies `A` in-place and returns `ilo`, `ihi`, and `scale`. If -permuting was turned on, `A[i,j] = 0` if `j > i` and `1 < j < ilo` or `j > ihi`. -`scale` contains information about the scaling/permutations performed. -""" -gebal!(job::Char, A::StridedMatrix) - -""" - gebak!(job, side, ilo, ihi, scale, V) - -Transform the eigenvectors `V` of a matrix balanced using `gebal!` to -the unscaled/unpermuted eigenvectors of the original matrix. Modifies `V` -in-place. `side` can be `L` (left eigenvectors are transformed) or `R` -(right eigenvectors are transformed). -""" -gebak!(job::Char, side::Char, ilo::BlasInt, ihi::BlasInt, scale::StridedVector, V::StridedMatrix) - -# (GE) general matrices, direct decompositions -# -# These mutating functions take as arguments all the values they -# return, even if the value of the function does not depend on them -# (e.g. the tau argument). This is so that a factorization can be -# updated in place. The condensed mutating functions, usually a -# function of A only, are defined after this block. -for (gebrd, gelqf, geqlf, geqrf, geqp3, geqrt, geqrt3, gerqf, getrf, elty, relty) in - ((:dgebrd_,:dgelqf_,:dgeqlf_,:dgeqrf_,:dgeqp3_,:dgeqrt_,:dgeqrt3_,:dgerqf_,:dgetrf_,:Float64,:Float64), - (:sgebrd_,:sgelqf_,:sgeqlf_,:sgeqrf_,:sgeqp3_,:sgeqrt_,:sgeqrt3_,:sgerqf_,:sgetrf_,:Float32,:Float32), - (:zgebrd_,:zgelqf_,:zgeqlf_,:zgeqrf_,:zgeqp3_,:zgeqrt_,:zgeqrt3_,:zgerqf_,:zgetrf_,:Complex128,:Float64), - (:cgebrd_,:cgelqf_,:cgeqlf_,:cgeqrf_,:cgeqp3_,:cgeqrt_,:cgeqrt3_,:cgerqf_,:cgetrf_,:Complex64,:Float32)) - @eval begin - # SUBROUTINE DGEBRD( M, N, A, LDA, D, E, TAUQ, TAUP, WORK, LWORK, - # INFO ) - # .. Scalar Arguments .. - # INTEGER INFO, LDA, LWORK, M, N - # .. Array Arguments .. - # DOUBLE PRECISION A( LDA, * ), D( * ), E( * ), TAUP( * ), - # TAUQ( * ), WORK( * ) - function gebrd!(A::StridedMatrix{$elty}) - chkstride1(A) - m, n = size(A) - k = min(m, n) - d = similar(A, $relty, k) - e = similar(A, $relty, k) - tauq = similar(A, $elty, k) - taup = similar(A, $elty, k) - work = Vector{$elty}(1) - lwork = BlasInt(-1) - info = Ref{BlasInt}() - for i = 1:2 - ccall((@blasfunc($gebrd), liblapack), Void, - (Ptr{BlasInt}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, - Ptr{$relty}, Ptr{$relty}, Ptr{$elty}, Ptr{$elty}, - Ptr{$elty}, Ptr{BlasInt}, Ptr{BlasInt}), - &m, &n, A, &max(1,stride(A,2)), - d, e, tauq, taup, - work, &lwork, info) - chklapackerror(info[]) - if i == 1 - lwork = BlasInt(real(work[1])) - work = Vector{$elty}(lwork) - end - end - A, d, e, tauq, taup - end - - # SUBROUTINE DGELQF( M, N, A, LDA, TAU, WORK, LWORK, INFO ) - # * .. Scalar Arguments .. - # INTEGER INFO, LDA, LWORK, M, N - # * .. Array Arguments .. - # DOUBLE PRECISION A( LDA, * ), TAU( * ), WORK( * ) - function gelqf!(A::StridedMatrix{$elty}, tau::StridedVector{$elty}) - chkstride1(A,tau) - m = BlasInt(size(A, 1)) - n = BlasInt(size(A, 2)) - lda = BlasInt(max(1,stride(A, 2))) - if length(tau) != min(m,n) - throw(DimensionMismatch("tau has length $(length(tau)), but needs length $(min(m,n))")) - end - lwork = BlasInt(-1) - work = Vector{$elty}(1) - info = Ref{BlasInt}() - for i = 1:2 # first call returns lwork as work[1] - ccall((@blasfunc($gelqf), liblapack), Void, - (Ptr{BlasInt}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, - Ptr{$elty}, Ptr{$elty}, Ptr{BlasInt}, Ptr{BlasInt}), - &m, &n, A, &lda, tau, work, &lwork, info) - chklapackerror(info[]) - if i == 1 - lwork = BlasInt(real(work[1])) - work = Vector{$elty}(lwork) - end - end - A, tau - end - - # SUBROUTINE DGEQLF( M, N, A, LDA, TAU, WORK, LWORK, INFO ) - # * .. Scalar Arguments .. - # INTEGER INFO, LDA, LWORK, M, N - # * .. Array Arguments .. - # DOUBLE PRECISION A( LDA, * ), TAU( * ), WORK( * ) - function geqlf!(A::StridedMatrix{$elty}, tau::StridedVector{$elty}) - chkstride1(A,tau) - m = BlasInt(size(A, 1)) - n = BlasInt(size(A, 2)) - lda = BlasInt(max(1,stride(A, 2))) - if length(tau) != min(m,n) - throw(DimensionMismatch("tau has length $(length(tau)), but needs length $(min(m,n))")) - end - lwork = BlasInt(-1) - work = Vector{$elty}(1) - info = Ref{BlasInt}() - for i = 1:2 # first call returns lwork as work[1] - ccall((@blasfunc($geqlf), liblapack), Void, - (Ptr{BlasInt}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, - Ptr{$elty}, Ptr{$elty}, Ptr{BlasInt}, Ptr{BlasInt}), - &m, &n, A, &lda, tau, work, &lwork, info) - chklapackerror(info[]) - if i == 1 - lwork = BlasInt(real(work[1])) - work = Vector{$elty}(lwork) - end - end - A, tau - end - - # SUBROUTINE DGEQP3( M, N, A, LDA, JPVT, TAU, WORK, LWORK, INFO ) - # * .. Scalar Arguments .. - # INTEGER INFO, LDA, LWORK, M, N - # * .. Array Arguments .. - # INTEGER JPVT( * ) - # DOUBLE PRECISION A( LDA, * ), TAU( * ), WORK( * ) - function geqp3!(A::StridedMatrix{$elty}, jpvt::StridedVector{BlasInt}, tau::StridedVector{$elty}) - chkstride1(A,jpvt,tau) - m,n = size(A) - if length(tau) != min(m,n) - throw(DimensionMismatch("tau has length $(length(tau)), but needs length $(min(m,n))")) - end - if length(jpvt) != n - throw(DimensionMismatch("jpvt has length $(length(jpvt)), but needs length $n")) - end - lda = stride(A,2) - if lda == 0 - return A, tau, jpvt - end # Early exit - work = Vector{$elty}(1) - lwork = BlasInt(-1) - cmplx = eltype(A)<:Complex - if cmplx - rwork = Vector{$relty}(2n) - end - info = Ref{BlasInt}() - for i = 1:2 - if cmplx - ccall((@blasfunc($geqp3), liblapack), Void, - (Ptr{BlasInt}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, - Ptr{BlasInt}, Ptr{$elty}, Ptr{$elty}, Ptr{BlasInt}, - Ptr{$relty}, Ptr{BlasInt}), - &m, &n, A, &lda, - jpvt, tau, work, &lwork, - rwork, info) - else - ccall((@blasfunc($geqp3), liblapack), Void, - (Ptr{BlasInt}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, - Ptr{BlasInt}, Ptr{$elty}, Ptr{$elty}, Ptr{BlasInt}, - Ptr{BlasInt}), - &m, &n, A, &lda, - jpvt, tau, work, - &lwork, info) - end - chklapackerror(info[]) - if i == 1 - lwork = BlasInt(real(work[1])) - work = Vector{$elty}(lwork) - end - end - return A, tau, jpvt - end - - function geqrt!(A::StridedMatrix{$elty}, T::StridedMatrix{$elty}) - chkstride1(A) - m, n = size(A) - minmn = min(m, n) - nb = size(T, 1) - if nb > minmn - throw(ArgumentError("block size $nb > $minmn too large")) - end - lda = max(1, stride(A,2)) - work = Vector{$elty}(nb*n) - if n > 0 - info = Ref{BlasInt}() - ccall((@blasfunc($geqrt), liblapack), Void, - (Ptr{BlasInt}, Ptr{BlasInt}, Ptr{BlasInt}, Ptr{$elty}, - Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, - Ptr{BlasInt}), - &m, &n, &nb, A, - &lda, T, &max(1,stride(T,2)), work, - info) - chklapackerror(info[]) - end - A, T - end - - function geqrt3!(A::StridedMatrix{$elty}, T::StridedMatrix{$elty}) - chkstride1(A) - chkstride1(T) - m, n = size(A) - p, q = size(T) - if m < n - throw(DimensionMismatch("input matrix A has dimensions ($m,$n), but should have more rows than columns")) - end - if p != n || q != n - throw(DimensionMismatch("block reflector T has dimensions ($p,$q), but should have dimensions ($n,$n)")) - end - if n > 0 - info = Ref{BlasInt}() - ccall((@blasfunc($geqrt3), liblapack), Void, - (Ptr{BlasInt}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, - Ptr{$elty}, Ptr{BlasInt}, Ptr{BlasInt}), - &m, &n, A, &max(1, stride(A, 2)), - T, &max(1,stride(T,2)), info) - chklapackerror(info[]) - end - A, T - end - - ## geqrfp! - positive elements on diagonal of R - not defined yet - # SUBROUTINE DGEQRFP( M, N, A, LDA, TAU, WORK, LWORK, INFO ) - # * .. Scalar Arguments .. - # INTEGER INFO, LDA, LWORK, M, N - # * .. Array Arguments .. - # DOUBLE PRECISION A( LDA, * ), TAU( * ), WORK( * ) - function geqrf!(A::StridedMatrix{$elty}, tau::StridedVector{$elty}) - chkstride1(A,tau) - m, n = size(A) - if length(tau) != min(m,n) - throw(DimensionMismatch("tau has length $(length(tau)), but needs length $(min(m,n))")) - end - work = Vector{$elty}(1) - lwork = BlasInt(-1) - info = Ref{BlasInt}() - for i = 1:2 # first call returns lwork as work[1] - ccall((@blasfunc($geqrf), liblapack), Void, - (Ptr{BlasInt}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, - Ptr{$elty}, Ptr{$elty}, Ptr{BlasInt}, Ptr{BlasInt}), - &m, &n, A, &max(1,stride(A,2)), tau, work, &lwork, info) - chklapackerror(info[]) - if i == 1 - lwork = BlasInt(real(work[1])) - work = Vector{$elty}(lwork) - end - end - A, tau - end - - # SUBROUTINE DGERQF( M, N, A, LDA, TAU, WORK, LWORK, INFO ) - # * .. Scalar Arguments .. - # INTEGER INFO, LDA, LWORK, M, N - # * .. Array Arguments .. - # DOUBLE PRECISION A( LDA, * ), TAU( * ), WORK( * ) - function gerqf!(A::StridedMatrix{$elty},tau::StridedVector{$elty}) - chkstride1(A,tau) - m, n = size(A) - if length(tau) != min(m,n) - throw(DimensionMismatch("tau has length $(length(tau)), but needs length $(min(m,n))")) - end - lwork = BlasInt(-1) - work = Vector{$elty}(1) - info = Ref{BlasInt}() - for i = 1:2 # first call returns lwork as work[1] - ccall((@blasfunc($gerqf), liblapack), Void, - (Ptr{BlasInt}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, - Ptr{$elty}, Ptr{$elty}, Ptr{BlasInt}, Ptr{BlasInt}), - &m, &n, A, &max(1,stride(A,2)), tau, work, &lwork, info) - chklapackerror(info[]) - if i == 1 - lwork = BlasInt(real(work[1])) - work = Vector{$elty}(lwork) - end - end - A, tau - end - - # SUBROUTINE DGETRF( M, N, A, LDA, IPIV, INFO ) - # * .. Scalar Arguments .. - # INTEGER INFO, LDA, M, N - # * .. Array Arguments .. - # INTEGER IPIV( * ) - # DOUBLE PRECISION A( LDA, * ) - function getrf!(A::StridedMatrix{$elty}) - chkstride1(A) - m, n = size(A) - lda = max(1,stride(A, 2)) - ipiv = similar(A, BlasInt, min(m,n)) - info = Ref{BlasInt}() - ccall((@blasfunc($getrf), liblapack), Void, - (Ptr{BlasInt}, Ptr{BlasInt}, Ptr{$elty}, - Ptr{BlasInt}, Ptr{BlasInt}, Ptr{BlasInt}), - &m, &n, A, &lda, ipiv, info) - chkargsok(info[]) - A, ipiv, info[] #Error code is stored in LU factorization type - end - end -end - -""" - gebrd!(A) -> (A, d, e, tauq, taup) - -Reduce `A` in-place to bidiagonal form `A = QBP'`. Returns `A`, containing the -bidiagonal matrix `B`; `d`, containing the diagonal elements of `B`; `e`, -containing the off-diagonal elements of `B`; `tauq`, containing the -elementary reflectors representing `Q`; and `taup`, containing the -elementary reflectors representing `P`. -""" -gebrd!(A::StridedMatrix) - -""" - gelqf!(A, tau) - -Compute the `LQ` factorization of `A`, `A = LQ`. `tau` contains scalars -which parameterize the elementary reflectors of the factorization. `tau` -must have length greater than or equal to the smallest dimension of `A`. - -Returns -`A` and `tau` modified in-place. -""" -gelqf!(A::StridedMatrix, tau::StridedVector) - -""" - geqlf!(A, tau) - -Compute the `QL` factorization of `A`, `A = QL`. `tau` contains scalars -which parameterize the elementary reflectors of the factorization. `tau` -must have length greater than or equal to the smallest dimension of `A`. - -Returns `A` and `tau` modified in-place. -""" -geqlf!(A::StridedMatrix, tau::StridedVector) - -""" - geqp3!(A, jpvt, tau) - -Compute the pivoted `QR` factorization of `A`, `AP = QR` using BLAS level 3. -`P` is a pivoting matrix, represented by `jpvt`. `tau` stores the elementary -reflectors. `jpvt` must have length length greater than or equal to `n` if `A` -is an `(m x n)` matrix. `tau` must have length greater than or equal to the -smallest dimension of `A`. - -`A`, `jpvt`, and `tau` are modified in-place. -""" -geqp3!(A::StridedMatrix, jpvt::StridedVector{BlasInt}, tau::StridedVector) - -""" - geqrt!(A, T) - -Compute the blocked `QR` factorization of `A`, `A = QR`. `T` contains upper -triangular block reflectors which parameterize the elementary reflectors of -the factorization. The first dimension of `T` sets the block size and it must -be between 1 and `n`. The second dimension of `T` must equal the smallest -dimension of `A`. - -Returns `A` and `T` modified in-place. -""" -geqrt!(A::StridedMatrix, T::StridedMatrix) - -""" - geqrt3!(A, T) - -Recursively computes the blocked `QR` factorization of `A`, `A = QR`. `T` -contains upper triangular block reflectors which parameterize the -elementary reflectors of the factorization. The first dimension of `T` sets the -block size and it must be between 1 and `n`. The second dimension of `T` must -equal the smallest dimension of `A`. - -Returns `A` and `T` modified in-place. -""" -geqrt3!(A::StridedMatrix, T::StridedMatrix) - -""" - geqrf!(A, tau) - -Compute the `QR` factorization of `A`, `A = QR`. `tau` contains scalars -which parameterize the elementary reflectors of the factorization. `tau` -must have length greater than or equal to the smallest dimension of `A`. - -Returns `A` and `tau` modified in-place. -""" -geqrf!(A::StridedMatrix, tau::StridedVector) - -""" - gerqf!(A, tau) - -Compute the `RQ` factorization of `A`, `A = RQ`. `tau` contains scalars -which parameterize the elementary reflectors of the factorization. `tau` -must have length greater than or equal to the smallest dimension of `A`. - -Returns `A` and `tau` modified in-place. -""" -gerqf!(A::StridedMatrix, tau::StridedVector) - -""" - getrf!(A) -> (A, ipiv, info) - -Compute the pivoted `LU` factorization of `A`, `A = LU`. - -Returns `A`, modified in-place, `ipiv`, the pivoting information, and an `info` -code which indicates success (`info = 0`), a singular value in `U` -(`info = i`, in which case `U[i,i]` is singular), or an error code (`info < 0`). -""" -getrf!(A::StridedMatrix, tau::StridedVector) - -""" - gelqf!(A) -> (A, tau) - -Compute the `LQ` factorization of `A`, `A = LQ`. - -Returns `A`, modified in-place, and `tau`, which contains scalars -which parameterize the elementary reflectors of the factorization. -""" -gelqf!(A::StridedMatrix{<:BlasFloat}) = ((m,n) = size(A); gelqf!(A, similar(A, min(m, n)))) - -""" - geqlf!(A) -> (A, tau) - -Compute the `QL` factorization of `A`, `A = QL`. - -Returns `A`, modified in-place, and `tau`, which contains scalars -which parameterize the elementary reflectors of the factorization. -""" -geqlf!(A::StridedMatrix{<:BlasFloat}) = ((m,n) = size(A); geqlf!(A, similar(A, min(m, n)))) - -""" - geqrt!(A, nb) -> (A, T) - -Compute the blocked `QR` factorization of `A`, `A = QR`. `nb` sets the block size -and it must be between 1 and `n`, the second dimension of `A`. - -Returns `A`, modified in-place, and `T`, which contains upper -triangular block reflectors which parameterize the elementary reflectors of -the factorization. -""" -geqrt!(A::StridedMatrix{<:BlasFloat}, nb::Integer) = geqrt!(A, similar(A, nb, minimum(size(A)))) - -""" - geqrt3!(A) -> (A, T) - -Recursively computes the blocked `QR` factorization of `A`, `A = QR`. - -Returns `A`, modified in-place, and `T`, which contains upper triangular block -reflectors which parameterize the elementary reflectors of the factorization. -""" -geqrt3!(A::StridedMatrix{<:BlasFloat}) = (n = size(A, 2); geqrt3!(A, similar(A, n, n))) - -""" - geqrf!(A) -> (A, tau) - -Compute the `QR` factorization of `A`, `A = QR`. - -Returns `A`, modified in-place, and `tau`, which contains scalars -which parameterize the elementary reflectors of the factorization. -""" -geqrf!(A::StridedMatrix{<:BlasFloat}) = ((m,n) = size(A); geqrf!(A, similar(A, min(m, n)))) - -""" - gerqf!(A) -> (A, tau) - -Compute the `RQ` factorization of `A`, `A = RQ`. - -Returns `A`, modified in-place, and `tau`, which contains scalars -which parameterize the elementary reflectors of the factorization. -""" -gerqf!(A::StridedMatrix{<:BlasFloat}) = ((m,n) = size(A); gerqf!(A, similar(A, min(m, n)))) - -""" - geqp3!(A, jpvt) -> (A, jpvt, tau) - -Compute the pivoted `QR` factorization of `A`, `AP = QR` using BLAS level 3. -`P` is a pivoting matrix, represented by `jpvt`. `jpvt` must have length -greater than or equal to `n` if `A` is an `(m x n)` matrix. - -Returns `A` and `jpvt`, modified in-place, and `tau`, which stores the elementary -reflectors. -""" -function geqp3!(A::StridedMatrix{<:BlasFloat}, jpvt::StridedVector{BlasInt}) - m, n = size(A) - geqp3!(A, jpvt, similar(A, min(m, n))) -end - -""" - geqp3!(A) -> (A, jpvt, tau) - -Compute the pivoted `QR` factorization of `A`, `AP = QR` using BLAS level 3. - -Returns `A`, modified in-place, `jpvt`, which represents the pivoting matrix `P`, -and `tau`, which stores the elementary reflectors. -""" -function geqp3!(A::StridedMatrix{<:BlasFloat}) - m, n = size(A) - geqp3!(A, zeros(BlasInt, n), similar(A, min(m, n))) -end - -## Complete orthogonaliztion tools -for (tzrzf, ormrz, elty) in - ((:dtzrzf_,:dormrz_,:Float64), - (:stzrzf_,:sormrz_,:Float32), - (:ztzrzf_,:zunmrz_,:Complex128), - (:ctzrzf_,:cunmrz_,:Complex64)) - @eval begin - # SUBROUTINE ZTZRZF( M, N, A, LDA, TAU, WORK, LWORK, INFO ) - # - # .. Scalar Arguments .. - # INTEGER INFO, LDA, LWORK, M, N - # .. - # .. Array Arguments .. - # COMPLEX*16 A( LDA, * ), TAU( * ), WORK( * ) - function tzrzf!(A::StridedMatrix{$elty}) - m, n = size(A) - if n < m - throw(DimensionMismatch("input matrix A has dimensions ($m,$n), but cannot have fewer columns than rows")) - end - lda = max(1, m) - tau = similar(A, $elty, m) - work = Vector{$elty}(1) - lwork = BlasInt(-1) - info = Ref{BlasInt}() - for i = 1:2 - ccall((@blasfunc($tzrzf), liblapack), Void, - (Ptr{BlasInt}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, - Ptr{$elty}, Ptr{$elty}, Ptr{BlasInt}, Ptr{BlasInt}), - &m, &n, A, &lda, - tau, work, &lwork, info) - chklapackerror(info[]) - if i == 1 - lwork = BlasInt(real(work[1])) - work = Vector{$elty}(lwork) - end - end - A, tau - end - - # SUBROUTINE ZUNMRZ( SIDE, TRANS, M, N, K, L, A, LDA, TAU, C, LDC, - # WORK, LWORK, INFO ) - # - # .. Scalar Arguments .. - # CHARACTER SIDE, TRANS - # INTEGER INFO, K, L, LDA, LDC, LWORK, M, N - # .. - # .. Array Arguments .. - # COMPLEX*16 A( LDA, * ), C( LDC, * ), TAU( * ), WORK( * ) - function ormrz!(side::Char, trans::Char, A::StridedMatrix{$elty}, - tau::StridedVector{$elty}, C::StridedMatrix{$elty}) - chktrans(trans) - chkside(side) - chkstride1(tau) - m, n = size(C) - k = length(tau) - l = size(A, 2) - size(A, 1) - lda = max(1, stride(A,2)) - ldc = max(1, stride(C,2)) - work = Vector{$elty}(1) - lwork = BlasInt(-1) - info = Ref{BlasInt}() - for i = 1:2 - ccall((@blasfunc($ormrz), liblapack), Void, - (Ptr{UInt8}, Ptr{UInt8}, Ptr{BlasInt}, Ptr{BlasInt}, - Ptr{BlasInt}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, - Ptr{$elty}, Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, - Ptr{BlasInt}, Ptr{BlasInt}), - &side, &trans, &m, &n, - &k, &l, A, &lda, - tau, C, &ldc, work, - &lwork, info) - chklapackerror(info[]) - if i == 1 - lwork = BlasInt(real(work[1])) - work = Vector{$elty}(lwork) - end - end - C - end - end -end - -""" - ormrz!(side, trans, A, tau, C) - -Multiplies the matrix `C` by `Q` from the transformation supplied by -`tzrzf!`. Depending on `side` or `trans` the multiplication can be -left-sided (`side = L, Q*C`) or right-sided (`side = R, C*Q`) and `Q` -can be unmodified (`trans = N`), transposed (`trans = T`), or conjugate -transposed (`trans = C`). Returns matrix `C` which is modified in-place -with the result of the multiplication. -""" -ormrz!(side::Char, trans::Char, A::StridedMatrix, tau::StridedVector, C::StridedMatrix) - -""" - tzrzf!(A) -> (A, tau) - -Transforms the upper trapezoidal matrix `A` to upper triangular form in-place. -Returns `A` and `tau`, the scalar parameters for the elementary reflectors -of the transformation. -""" -tzrzf!(A::StridedMatrix) - -## (GE) general matrices, solvers with factorization, solver and inverse -for (gels, gesv, getrs, getri, elty) in - ((:dgels_,:dgesv_,:dgetrs_,:dgetri_,:Float64), - (:sgels_,:sgesv_,:sgetrs_,:sgetri_,:Float32), - (:zgels_,:zgesv_,:zgetrs_,:zgetri_,:Complex128), - (:cgels_,:cgesv_,:cgetrs_,:cgetri_,:Complex64)) - @eval begin - # SUBROUTINE DGELS( TRANS, M, N, NRHS, A, LDA, B, LDB, WORK, LWORK,INFO) - # * .. Scalar Arguments .. - # CHARACTER TRANS - # INTEGER INFO, LDA, LDB, LWORK, M, N, NRHS - function gels!(trans::Char, A::StridedMatrix{$elty}, B::StridedVecOrMat{$elty}) - chktrans(trans) - chkstride1(A, B) - btrn = trans == 'T' - m, n = size(A) - if size(B,1) != (btrn ? n : m) - throw(DimensionMismatch("matrix A has dimensions ($m,$n), transposed: $btrn, but leading dimension of B is $(size(B,1))")) - end - info = Ref{BlasInt}() - work = Vector{$elty}(1) - lwork = BlasInt(-1) - for i = 1:2 - ccall((@blasfunc($gels), liblapack), Void, - (Ptr{UInt8}, Ptr{BlasInt}, Ptr{BlasInt}, Ptr{BlasInt}, - Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, - Ptr{$elty}, Ptr{BlasInt}, Ptr{BlasInt}), - &(btrn?'T':'N'), &m, &n, &size(B,2), A, &max(1,stride(A,2)), - B, &max(1,stride(B,2)), work, &lwork, info) - chklapackerror(info[]) - if i == 1 - lwork = BlasInt(real(work[1])) - work = Vector{$elty}(lwork) - end - end - k = min(m, n) - F = m < n ? tril(A[1:k, 1:k]) : triu(A[1:k, 1:k]) - ssr = Vector{$elty}(size(B, 2)) - for i = 1:size(B,2) - x = zero($elty) - for j = k+1:size(B,1) - x += abs2(B[j,i]) - end - ssr[i] = x - end - F, subsetrows(B, B, k), ssr - end - - # SUBROUTINE DGESV( N, NRHS, A, LDA, IPIV, B, LDB, INFO ) - # * .. Scalar Arguments .. - # INTEGER INFO, LDA, LDB, N, NRHS - # * .. - # * .. Array Arguments .. - # INTEGER IPIV( * ) - # DOUBLE PRECISION A( LDA, * ), B( LDB, * ) - function gesv!(A::StridedMatrix{$elty}, B::StridedVecOrMat{$elty}) - chkstride1(A, B) - n = checksquare(A) - if size(B,1) != n - throw(DimensionMismatch("B has leading dimension $(size(B,1)), but needs $n")) - end - ipiv = similar(A, BlasInt, n) - info = Ref{BlasInt}() - ccall((@blasfunc($gesv), liblapack), Void, - (Ptr{BlasInt}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, Ptr{BlasInt}, - Ptr{$elty}, Ptr{BlasInt}, Ptr{BlasInt}), - &n, &size(B,2), A, &max(1,stride(A,2)), ipiv, B, &max(1,stride(B,2)), info) - chklapackerror(info[]) - B, A, ipiv - end - - # SUBROUTINE DGETRS( TRANS, N, NRHS, A, LDA, IPIV, B, LDB, INFO ) - #* .. Scalar Arguments .. - # CHARACTER TRANS - # INTEGER INFO, LDA, LDB, N, NRHS - # .. Array Arguments .. - # INTEGER IPIV( * ) - # DOUBLE PRECISION A( LDA, * ), B( LDB, * ) - function getrs!(trans::Char, A::StridedMatrix{$elty}, ipiv::StridedVector{BlasInt}, B::StridedVecOrMat{$elty}) - chktrans(trans) - chkstride1(A, B, ipiv) - n = checksquare(A) - if n != size(B, 1) - throw(DimensionMismatch("B has leading dimension $(size(B,1)), but needs $n")) - end - nrhs = size(B, 2) - info = Ref{BlasInt}() - ccall((@blasfunc($getrs), liblapack), Void, - (Ptr{UInt8}, Ptr{BlasInt}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, - Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, Ptr{BlasInt}), - &trans, &n, &size(B,2), A, &max(1,stride(A,2)), ipiv, B, &max(1,stride(B,2)), info) - chklapackerror(info[]) - B - end - - # SUBROUTINE DGETRI( N, A, LDA, IPIV, WORK, LWORK, INFO ) - #* .. Scalar Arguments .. - # INTEGER INFO, LDA, LWORK, N - #* .. Array Arguments .. - # INTEGER IPIV( * ) - # DOUBLE PRECISION A( LDA, * ), WORK( * ) - function getri!(A::StridedMatrix{$elty}, ipiv::StridedVector{BlasInt}) - chkstride1(A, ipiv) - n = checksquare(A) - if n != length(ipiv) - throw(DimensionMismatch("ipiv has length $(length(ipiv)), but needs $n")) - end - lda = max(1,stride(A, 2)) - lwork = BlasInt(-1) - work = Vector{$elty}(1) - info = Ref{BlasInt}() - for i = 1:2 - ccall((@blasfunc($getri), liblapack), Void, - (Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, Ptr{BlasInt}, - Ptr{$elty}, Ptr{BlasInt}, Ptr{BlasInt}), - &n, A, &lda, ipiv, work, &lwork, info) - chklapackerror(info[]) - if i == 1 - lwork = BlasInt(real(work[1])) - work = Vector{$elty}(lwork) - end - end - A - end - end -end - -""" - gels!(trans, A, B) -> (F, B, ssr) - -Solves the linear equation `A * X = B`, `A.' * X =B`, or `A' * X = B` using -a QR or LQ factorization. Modifies the matrix/vector `B` in place with the -solution. `A` is overwritten with its `QR` or `LQ` factorization. `trans` -may be one of `N` (no modification), `T` (transpose), or `C` (conjugate -transpose). `gels!` searches for the minimum norm/least squares solution. -`A` may be under or over determined. The solution is returned in `B`. -""" -gels!(trans::Char, A::StridedMatrix, B::StridedVecOrMat) - -""" - gesv!(A, B) -> (B, A, ipiv) - -Solves the linear equation `A * X = B` where `A` is a square matrix using -the `LU` factorization of `A`. `A` is overwritten with its `LU` -factorization and `B` is overwritten with the solution `X`. `ipiv` contains the -pivoting information for the `LU` factorization of `A`. -""" -gesv!(A::StridedMatrix, B::StridedVecOrMat) - -""" - getrs!(trans, A, ipiv, B) - -Solves the linear equation `A * X = B`, `A.' * X =B`, or `A' * X = B` for -square `A`. Modifies the matrix/vector `B` in place with the solution. `A` -is the `LU` factorization from `getrf!`, with `ipiv` the pivoting -information. `trans` may be one of `N` (no modification), `T` (transpose), -or `C` (conjugate transpose). -""" -getrs!(trans::Char, A::StridedMatrix, ipiv::StridedVector{BlasInt}, B::StridedVecOrMat) - -""" - getri!(A, ipiv) - -Computes the inverse of `A`, using its `LU` factorization found by -`getrf!`. `ipiv` is the pivot information output and `A` -contains the `LU` factorization of `getrf!`. `A` is overwritten with -its inverse. -""" -getri!(A::StridedMatrix, ipiv::StridedVector{BlasInt}) - -for (gesvx, elty) in - ((:dgesvx_,:Float64), - (:sgesvx_,:Float32)) - @eval begin - # SUBROUTINE DGESVX( FACT, TRANS, N, NRHS, A, LDA, AF, LDAF, IPIV, - # EQUED, R, C, B, LDB, X, LDX, RCOND, FERR, BERR, - # WORK, IWORK, INFO ) - # - # .. Scalar Arguments .. - # CHARACTER EQUED, FACT, TRANS - # INTEGER INFO, LDA, LDAF, LDB, LDX, N, NRHS - # DOUBLE PRECISION RCOND - # .. - # .. Array Arguments .. - # INTEGER IPIV( * ), IWORK( * ) - # DOUBLE PRECISION A( LDA, * ), AF( LDAF, * ), B( LDB, * ), - # $ BERR( * ), C( * ), FERR( * ), R( * ), - # $ WORK( * ), X( LDX, * - # - function gesvx!(fact::Char, trans::Char, A::StridedMatrix{$elty}, - AF::StridedMatrix{$elty}, ipiv::StridedVector{BlasInt}, equed::Char, - R::StridedVector{$elty}, C::StridedVector{$elty}, B::StridedVecOrMat{$elty}) - chktrans(trans) - chkstride1(ipiv, R, C) - n = checksquare(A) - lda = stride(A,2) - n = checksquare(AF) - ldaf = stride(AF,2) - nrhs = size(B,2) - ldb = stride(B,2) - rcond = Vector{$elty}(1) - ferr = similar(A, $elty, nrhs) - berr = similar(A, $elty, nrhs) - work = Vector{$elty}(4n) - iwork = Vector{BlasInt}(n) - info = Ref{BlasInt}() - X = similar(A, $elty, n, nrhs) - ccall((@blasfunc($gesvx), liblapack), Void, - (Ptr{UInt8}, Ptr{UInt8}, Ptr{BlasInt}, Ptr{BlasInt}, - Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, Ptr{BlasInt}, - Ptr{UInt8}, Ptr{$elty}, Ptr{$elty}, Ptr{$elty}, Ptr{BlasInt}, - Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, Ptr{$elty}, Ptr{$elty}, - Ptr{$elty}, Ptr{BlasInt}, Ptr{BlasInt}), - &fact, &trans, &n, &nrhs, A, &lda, AF, &ldaf, ipiv, &equed, R, C, B, - &ldb, X, &n, rcond, ferr, berr, work, iwork, info) - chklapackerror(info[]) - if info[] == n + 1 - warn("matrix is singular to working precision") - else - chknonsingular(info[]) - end - #WORK(1) contains the reciprocal pivot growth factor norm(A)/norm(U) - X, equed, R, C, B, rcond[1], ferr, berr, work[1] - end - - function gesvx!(A::StridedMatrix{$elty}, B::StridedVecOrMat{$elty}) - n = size(A,1) - X, equed, R, C, B, rcond, ferr, berr, rpgf = - gesvx!('N', 'N', A, - similar(A, $elty, n, n), - similar(A, BlasInt, n), - 'N', - similar(A, $elty, n), - similar(A, $elty, n), - B) - X, rcond, ferr, berr, rpgf - end - end -end -for (gesvx, elty, relty) in - ((:zgesvx_,:Complex128,:Float64), - (:cgesvx_,:Complex64 ,:Float32)) - @eval begin - # SUBROUTINE ZGESVX( FACT, TRANS, N, NRHS, A, LDA, AF, LDAF, IPIV, - # EQUED, R, C, B, LDB, X, LDX, RCOND, FERR, BERR, - # WORK, RWORK, INFO ) - # - # .. Scalar Arguments .. - # CHARACTER EQUED, FACT, TRANS - # INTEGER INFO, LDA, LDAF, LDB, LDX, N, NRHS - # DOUBLE PRECISION RCOND - # .. - # .. Array Arguments .. - # INTEGER IPIV( * ) - # DOUBLE PRECISION BERR( * ), C( * ), FERR( * ), R( * ), - # $ RWORK( * ) - # COMPLEX*16 A( LDA, * ), AF( LDAF, * ), B( LDB, * ), - # $ WORK( * ), X( LDX, * ) - function gesvx!(fact::Char, trans::Char, A::StridedMatrix{$elty}, - AF::StridedMatrix{$elty}, ipiv::StridedVector{BlasInt}, equed::Char, - R::StridedVector{$relty}, C::StridedVector{$relty}, B::StridedVecOrMat{$elty}) - chktrans(trans) - chkstride1(ipiv, R, C) - n = checksquare(A) - lda = stride(A,2) - n = checksquare(AF) - ldaf = stride(AF,2) - nrhs = size(B,2) - ldb = stride(B,2) - rcond = Vector{$relty}(1) - ferr = similar(A, $relty, nrhs) - berr = similar(A, $relty, nrhs) - work = Vector{$elty}(2n) - rwork = Vector{$relty}(2n) - info = Ref{BlasInt}() - X = similar(A, $elty, n, nrhs) - ccall((@blasfunc($gesvx), liblapack), Void, - (Ptr{UInt8}, Ptr{UInt8}, Ptr{BlasInt}, Ptr{BlasInt}, - Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, Ptr{BlasInt}, - Ptr{UInt8}, Ptr{$relty}, Ptr{$relty}, Ptr{$elty}, Ptr{BlasInt}, - Ptr{$elty}, Ptr{BlasInt}, Ptr{$relty}, Ptr{$relty}, Ptr{$relty}, - Ptr{$elty}, Ptr{$relty}, Ptr{BlasInt}), - &fact, &trans, &n, &nrhs, A, &lda, AF, &ldaf, ipiv, &equed, R, C, B, - &ldb, X, &n, rcond, ferr, berr, work, rwork, info) - chklapackerror(info[]) - if info[] == n + 1 - warn("matrix is singular to working precision") - else - chknonsingular(info[]) - end - #RWORK(1) contains the reciprocal pivot growth factor norm(A)/norm(U) - X, equed, R, C, B, rcond[1], ferr, berr, rwork[1] - end - - #Wrapper for the no-equilibration, no-transpose calculation - function gesvx!(A::StridedMatrix{$elty}, B::StridedVecOrMat{$elty}) - n = size(A,1) - X, equed, R, C, B, rcond, ferr, berr, rpgf = - gesvx!('N', 'N', A, - similar(A, $elty, n, n), - similar(A, BlasInt, n), - 'N', - similar(A, $relty, n), - similar(A, $relty, n), - B) - X, rcond, ferr, berr, rpgf - end - end -end - -""" - gesvx!(fact, trans, A, AF, ipiv, equed, R, C, B) -> (X, equed, R, C, B, rcond, ferr, berr, work) - -Solves the linear equation `A * X = B` (`trans = N`), `A.' * X =B` -(`trans = T`), or `A' * X = B` (`trans = C`) using the `LU` factorization -of `A`. `fact` may be `E`, in which case `A` will be equilibrated and copied -to `AF`; `F`, in which case `AF` and `ipiv` from a previous `LU` factorization -are inputs; or `N`, in which case `A` will be copied to `AF` and then -factored. If `fact = F`, `equed` may be `N`, meaning `A` has not been -equilibrated; `R`, meaning `A` was multiplied by `diagm(R)` from the left; -`C`, meaning `A` was multiplied by `diagm(C)` from the right; or `B`, meaning -`A` was multiplied by `diagm(R)` from the left and `diagm(C)` from the right. -If `fact = F` and `equed = R` or `B` the elements of `R` must all be positive. -If `fact = F` and `equed = C` or `B` the elements of `C` must all be positive. - -Returns the solution `X`; `equed`, which is an output if `fact` is not `N`, -and describes the equilibration that was performed; `R`, the row equilibration -diagonal; `C`, the column equilibration diagonal; `B`, which may be overwritten -with its equilibrated form `diagm(R)*B` (if `trans = N` and `equed = R,B`) or -`diagm(C)*B` (if `trans = T,C` and `equed = C,B`); `rcond`, the reciprocal -condition number of `A` after equilbrating; `ferr`, the forward error bound for -each solution vector in `X`; `berr`, the forward error bound for each solution -vector in `X`; and `work`, the reciprocal pivot growth factor. -""" -gesvx!(fact::Char, trans::Char, A::StridedMatrix, AF::StridedMatrix, - ipiv::StridedVector{BlasInt}, equed::Char, R::StridedVector, C::StridedVector, B::StridedVecOrMat) - -""" - gesvx!(A, B) - -The no-equilibration, no-transpose simplification of `gesvx!`. -""" -gesvx!(A::StridedMatrix, B::StridedVecOrMat) - -for (gelsd, gelsy, elty) in - ((:dgelsd_,:dgelsy_,:Float64), - (:sgelsd_,:sgelsy_,:Float32)) - @eval begin - # SUBROUTINE DGELSD( M, N, NRHS, A, LDA, B, LDB, S, RCOND, RANK, - # $ WORK, LWORK, IWORK, INFO ) - # * .. Scalar Arguments .. - # INTEGER INFO, LDA, LDB, LWORK, M, N, NRHS, RANK - # DOUBLE PRECISION RCOND - # * .. - # * .. Array Arguments .. - # INTEGER IWORK( * ) - # DOUBLE PRECISION A( LDA, * ), B( LDB, * ), S( * ), WORK( * ) - function gelsd!(A::StridedMatrix{$elty}, B::StridedVecOrMat{$elty}, rcond::Real=-one($elty)) - chkstride1(A, B) - m, n = size(A) - if size(B, 1) != m - throw(DimensionMismatch("B has leading dimension $(size(B,1)) but needs $m")) - end - newB = [B; zeros($elty, max(0, n - size(B, 1)), size(B, 2))] - s = similar(A, $elty, min(m, n)) - rcond = convert($elty, rcond) - rnk = Vector{BlasInt}(1) - info = Ref{BlasInt}() - work = Vector{$elty}(1) - lwork = BlasInt(-1) - iwork = Vector{BlasInt}(1) - for i = 1:2 - ccall((@blasfunc($gelsd), liblapack), Void, - (Ptr{BlasInt}, Ptr{BlasInt}, Ptr{BlasInt}, - Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, - Ptr{$elty}, Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, - Ptr{BlasInt}, Ptr{BlasInt}, Ptr{BlasInt}), - &m, &n, &size(B,2), A, &max(1,stride(A,2)), - newB, &max(1,stride(B,2),n), s, &rcond, rnk, work, &lwork, iwork, info) - chklapackerror(info[]) - if i == 1 - lwork = BlasInt(real(work[1])) - work = Vector{$elty}(lwork) - iwork = Vector{BlasInt}(iwork[1]) - end - end - subsetrows(B, newB, n), rnk[1] - end - - # SUBROUTINE DGELSY( M, N, NRHS, A, LDA, B, LDB, JPVT, RCOND, RANK, - # $ WORK, LWORK, INFO ) - # * .. Scalar Arguments .. - # INTEGER INFO, LDA, LDB, LWORK, M, N, NRHS, RANK - # DOUBLE PRECISION RCOND - # * .. - # * .. Array Arguments .. - # INTEGER JPVT( * ) - # DOUBLE PRECISION A( LDA, * ), B( LDB, * ), WORK( * ) - function gelsy!(A::StridedMatrix{$elty}, B::StridedVecOrMat{$elty}, rcond::Real=eps($elty)) - chkstride1(A, B) - m = size(A, 1) - n = size(A, 2) - nrhs = size(B, 2) - if size(B, 1) != m - throw(DimensionMismatch("B has leading dimension $(size(B,1)) but needs $m")) - end - newB = [B; zeros($elty, max(0, n - size(B, 1)), size(B, 2))] - lda = max(1, m) - ldb = max(1, m, n) - jpvt = zeros(BlasInt, n) - rcond = convert($elty, rcond) - rnk = Vector{BlasInt}(1) - work = Vector{$elty}(1) - lwork = BlasInt(-1) - info = Ref{BlasInt}() - for i = 1:2 - ccall((@blasfunc($gelsy), liblapack), Void, - (Ptr{BlasInt}, Ptr{BlasInt}, Ptr{BlasInt}, Ptr{$elty}, - Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, Ptr{BlasInt}, - Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, - Ptr{BlasInt}), - &m, &n, &nrhs, A, - &lda, newB, &ldb, jpvt, - &rcond, rnk, work, &lwork, - info) - chklapackerror(info[]) - if i == 1 - lwork = BlasInt(work[1]) - work = Vector{$elty}(lwork) - end - end - subsetrows(B, newB, n), rnk[1] - end - end -end - -for (gelsd, gelsy, elty, relty) in - ((:zgelsd_,:zgelsy_,:Complex128,:Float64), - (:cgelsd_,:cgelsy_,:Complex64,:Float32)) - @eval begin - # SUBROUTINE ZGELSD( M, N, NRHS, A, LDA, B, LDB, S, RCOND, RANK, - # $ WORK, LWORK, RWORK, IWORK, INFO ) - # * .. Scalar Arguments .. - # INTEGER INFO, LDA, LDB, LWORK, M, N, NRHS, RANK - # DOUBLE PRECISION RCOND - # * .. - # * .. Array Arguments .. - # INTEGER IWORK( * ) - # DOUBLE PRECISION RWORK( * ), S( * ) - # COMPLEX*16 A( LDA, * ), B( LDB, * ), WORK( * ) - function gelsd!(A::StridedMatrix{$elty}, B::StridedVecOrMat{$elty}, rcond::Real=-one($relty)) - chkstride1(A, B) - m, n = size(A) - if size(B, 1) != m - throw(DimensionMismatch("B has leading dimension $(size(B,1)) but needs $m")) - end - newB = [B; zeros($elty, max(0, n - size(B, 1)), size(B, 2))] - s = similar(A, $relty, min(m, n)) - rcond = convert($relty, rcond) - rnk = Vector{BlasInt}(1) - info = Ref{BlasInt}() - work = Vector{$elty}(1) - lwork = BlasInt(-1) - rwork = Vector{$relty}(1) - iwork = Vector{BlasInt}(1) - for i = 1:2 - ccall((@blasfunc($gelsd), liblapack), Void, - (Ptr{BlasInt}, Ptr{BlasInt}, Ptr{BlasInt}, Ptr{$elty}, - Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, Ptr{$relty}, - Ptr{$relty}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, - Ptr{$relty}, Ptr{BlasInt}, Ptr{BlasInt}), - &m, &n, &size(B,2), A, &max(1,stride(A,2)), - newB, &max(1,stride(B,2),n), s, &rcond, rnk, work, &lwork, rwork, iwork, info) - chklapackerror(info[]) - if i == 1 - lwork = BlasInt(real(work[1])) - work = Vector{$elty}(lwork) - rwork = Vector{$relty}(BlasInt(rwork[1])) - iwork = Vector{BlasInt}(iwork[1]) - end - end - subsetrows(B, newB, n), rnk[1] - end - - # SUBROUTINE ZGELSY( M, N, NRHS, A, LDA, B, LDB, JPVT, RCOND, RANK, - # $ WORK, LWORK, RWORK, INFO ) - # * .. Scalar Arguments .. - # INTEGER INFO, LDA, LDB, LWORK, M, N, NRHS, RANK - # DOUBLE PRECISION RCOND - # * .. - # * .. Array Arguments .. - # INTEGER JPVT( * ) - # DOUBLE PRECISION RWORK( * ) - # COMPLEX*16 A( LDA, * ), B( LDB, * ), WORK( * ) - function gelsy!(A::StridedMatrix{$elty}, B::StridedVecOrMat{$elty}, rcond::Real=eps($relty)) - chkstride1(A, B) - m, n = size(A) - nrhs = size(B, 2) - if size(B, 1) != m - throw(DimensionMismatch("B has leading dimension $(size(B,1)) but needs $m")) - end - newB = [B; zeros($elty, max(0, n - size(B, 1)), size(B, 2))] - lda = max(1, m) - ldb = max(1, m, n) - jpvt = zeros(BlasInt, n) - rcond = convert($relty, rcond) - rnk = Vector{BlasInt}(1) - work = Vector{$elty}(1) - lwork = BlasInt(-1) - rwork = Vector{$relty}(2n) - info = Ref{BlasInt}() - for i = 1:2 - ccall((@blasfunc($gelsy), liblapack), Void, - (Ptr{BlasInt}, Ptr{BlasInt}, Ptr{BlasInt}, Ptr{$elty}, - Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, Ptr{BlasInt}, - Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, - Ptr{$relty}, Ptr{BlasInt}), - &m, &n, &nrhs, A, - &lda, newB, &ldb, jpvt, - &rcond, rnk, work, &lwork, - rwork, info) - chklapackerror(info[]) - if i == 1 - lwork = BlasInt(real(work[1])) - work = Vector{$elty}(lwork) - end - end - subsetrows(B, newB, n), rnk[1] - end - end -end - -""" - gelsd!(A, B, rcond) -> (B, rnk) - -Computes the least norm solution of `A * X = B` by finding the `SVD` -factorization of `A`, then dividing-and-conquering the problem. `B` -is overwritten with the solution `X`. Singular values below `rcond` -will be treated as zero. Returns the solution in `B` and the effective rank -of `A` in `rnk`. -""" -gelsd!(A::StridedMatrix, B::StridedVecOrMat, rcond::Real) - -""" - gelsy!(A, B, rcond) -> (B, rnk) - -Computes the least norm solution of `A * X = B` by finding the full `QR` -factorization of `A`, then dividing-and-conquering the problem. `B` -is overwritten with the solution `X`. Singular values below `rcond` -will be treated as zero. Returns the solution in `B` and the effective rank -of `A` in `rnk`. -""" -gelsy!(A::StridedMatrix, B::StridedVecOrMat, rcond::Real) - -for (gglse, elty) in ((:dgglse_, :Float64), - (:sgglse_, :Float32), - (:zgglse_, :Complex128), - (:cgglse_, :Complex64)) - @eval begin - # SUBROUTINE DGGLSE( M, N, P, A, LDA, B, LDB, C, D, X, WORK, LWORK, - # $ INFO ) - # * .. Scalar Arguments .. - # INTEGER INFO, LDA, LDB, LWORK, M, N, P - # * .. - # * .. Array Arguments .. - # DOUBLE PRECISION A( LDA, * ), B( LDB, * ), C( * ), D( * ), - # $ WORK( * ), X( * ) - function gglse!(A::StridedMatrix{$elty}, c::StridedVector{$elty}, - B::StridedMatrix{$elty}, d::StridedVector{$elty}) - chkstride1(A, B) - m, n = size(A) - p = size(B, 1) - if size(B, 2) != n - throw(DimensionMismatch("B has second dimension $(size(B,2)), needs $n")) - end - if length(c) != m - throw(DimensionMismatch("c has length $(length(c)), needs $m")) - end - if length(d) != p - throw(DimensionMismatch("d has length $(length(d)), needs $p")) - end - X = zeros($elty, n) - info = Ref{BlasInt}() - work = Vector{$elty}(1) - lwork = BlasInt(-1) - for i = 1:2 - ccall((@blasfunc($gglse), liblapack), Void, - (Ptr{BlasInt}, Ptr{BlasInt}, Ptr{BlasInt}, Ptr{$elty}, - Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, - Ptr{$elty}, Ptr{$elty}, Ptr{$elty}, Ptr{BlasInt}, - Ptr{BlasInt}), - &m, &n, &p, A, &max(1,stride(A,2)), B, &max(1,stride(B,2)), c, d, X, - work, &lwork, info) - chklapackerror(info[]) - if i == 1 - lwork = BlasInt(real(work[1])) - work = Vector{$elty}(lwork) - end - end - X, dot(view(c, n - p + 1:m), view(c, n - p + 1:m)) - end - end -end - -""" - gglse!(A, c, B, d) -> (X,res) - -Solves the equation `A * x = c` where `x` is subject to the equality -constraint `B * x = d`. Uses the formula `||c - A*x||^2 = 0` to solve. -Returns `X` and the residual sum-of-squares. -""" -gglse!(A::StridedMatrix, c::StridedVector, B::StridedMatrix, d::StridedVector) - -# (GE) general matrices eigenvalue-eigenvector and singular value decompositions -for (geev, gesvd, gesdd, ggsvd, elty, relty) in - ((:dgeev_,:dgesvd_,:dgesdd_,:dggsvd_,:Float64,:Float64), - (:sgeev_,:sgesvd_,:sgesdd_,:sggsvd_,:Float32,:Float32), - (:zgeev_,:zgesvd_,:zgesdd_,:zggsvd_,:Complex128,:Float64), - (:cgeev_,:cgesvd_,:cgesdd_,:cggsvd_,:Complex64,:Float32)) - @eval begin - # SUBROUTINE DGEEV( JOBVL, JOBVR, N, A, LDA, WR, WI, VL, LDVL, VR, - # $ LDVR, WORK, LWORK, INFO ) - # * .. Scalar Arguments .. - # CHARACTER JOBVL, JOBVR - # INTEGER INFO, LDA, LDVL, LDVR, LWORK, N - # * .. Array Arguments .. - # DOUBLE PRECISION A( LDA, * ), VL( LDVL, * ), VR( LDVR, * ), - # $ WI( * ), WORK( * ), WR( * ) - function geev!(jobvl::Char, jobvr::Char, A::StridedMatrix{$elty}) - chkstride1(A) - n = checksquare(A) - chkfinite(A) # balancing routines don't support NaNs and Infs - lvecs = jobvl == 'V' - rvecs = jobvr == 'V' - VL = similar(A, $elty, (n, lvecs ? n : 0)) - VR = similar(A, $elty, (n, rvecs ? n : 0)) - cmplx = eltype(A) <: Complex - if cmplx - W = similar(A, $elty, n) - rwork = similar(A, $relty, 2n) - else - WR = similar(A, $elty, n) - WI = similar(A, $elty, n) - end - work = Vector{$elty}(1) - lwork = BlasInt(-1) - info = Ref{BlasInt}() - for i = 1:2 - if cmplx - ccall((@blasfunc($geev), liblapack), Void, - (Ptr{UInt8}, Ptr{UInt8}, Ptr{BlasInt}, Ptr{$elty}, - Ptr{BlasInt}, Ptr{$elty}, Ptr{$elty}, Ptr{BlasInt}, - Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, - Ptr{$relty}, Ptr{BlasInt}), - &jobvl, &jobvr, &n, A, &max(1,stride(A,2)), W, VL, &n, VR, &n, - work, &lwork, rwork, info) - else - ccall((@blasfunc($geev), liblapack), Void, - (Ptr{UInt8}, Ptr{UInt8}, Ptr{BlasInt}, Ptr{$elty}, - Ptr{BlasInt}, Ptr{$elty}, Ptr{$elty}, Ptr{$elty}, - Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, - Ptr{BlasInt}, Ptr{BlasInt}), - &jobvl, &jobvr, &n, A, &max(1,stride(A,2)), WR, WI, VL, &n, - VR, &n, work, &lwork, info) - end - chklapackerror(info[]) - if i == 1 - lwork = BlasInt(real(work[1])) - work = Vector{$elty}(lwork) - end - end - cmplx ? (W, VL, VR) : (WR, WI, VL, VR) - end - - # SUBROUTINE DGESDD( JOBZ, M, N, A, LDA, S, U, LDU, VT, LDVT, WORK, - # LWORK, IWORK, INFO ) - #* .. Scalar Arguments .. - # CHARACTER JOBZ - # INTEGER INFO, LDA, LDU, LDVT, LWORK, M, N - #* .. - #* .. Array Arguments .. - # INTEGER IWORK( * ) - # DOUBLE PRECISION A( LDA, * ), S( * ), U( LDU, * ), - # VT( LDVT, * ), WORK( * ) - function gesdd!(job::Char, A::StridedMatrix{$elty}) - chkstride1(A) - m, n = size(A) - minmn = min(m, n) - if job == 'A' - U = similar(A, $elty, (m, m)) - VT = similar(A, $elty, (n, n)) - elseif job == 'S' - U = similar(A, $elty, (m, minmn)) - VT = similar(A, $elty, (minmn, n)) - elseif job == 'O' - U = similar(A, $elty, (m, m >= n ? 0 : m)) - VT = similar(A, $elty, (n, m >= n ? n : 0)) - else - U = similar(A, $elty, (m, 0)) - VT = similar(A, $elty, (n, 0)) - end - work = Vector{$elty}(1) - lwork = BlasInt(-1) - S = similar(A, $relty, minmn) - cmplx = eltype(A)<:Complex - if cmplx - rwork = Array{$relty}(job == 'N' ? 7*minmn : - minmn*max(5*minmn+7, 2*max(m,n)+2*minmn+1)) - end - iwork = Vector{BlasInt}(8*minmn) - info = Ref{BlasInt}() - for i = 1:2 - if cmplx - ccall((@blasfunc($gesdd), liblapack), Void, - (Ptr{UInt8}, Ptr{BlasInt}, Ptr{BlasInt}, Ptr{$elty}, - Ptr{BlasInt}, Ptr{$relty}, Ptr{$elty}, Ptr{BlasInt}, - Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, - Ptr{$relty}, Ptr{BlasInt}, Ptr{BlasInt}), - &job, &m, &n, A, &max(1,stride(A,2)), S, U, &max(1,stride(U,2)), VT, &max(1,stride(VT,2)), - work, &lwork, rwork, iwork, info) - else - ccall((@blasfunc($gesdd), liblapack), Void, - (Ptr{UInt8}, Ptr{BlasInt}, Ptr{BlasInt}, Ptr{$elty}, - Ptr{BlasInt}, Ptr{$elty}, Ptr{$elty}, Ptr{BlasInt}, - Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, - Ptr{BlasInt}, Ptr{BlasInt}), - &job, &m, &n, A, &max(1,stride(A,2)), S, U, &max(1,stride(U,2)), VT, &max(1,stride(VT,2)), - work, &lwork, iwork, info) - end - chklapackerror(info[]) - if i == 1 - # Work around issue with truncated Float32 representation of lwork in - # sgesdd by using nextfloat. See - # http://icl.cs.utk.edu/lapack-forum/viewtopic.php?f=13&t=4587&p=11036&hilit=sgesdd#p11036 - # and - # https://github.com/scipy/scipy/issues/5401 - lwork = round(BlasInt, nextfloat(real(work[1]))) - work = Vector{$elty}(lwork) - end - end - if job == 'O' - if m >= n - return (A, S, VT) - else - # ()__ - # ||::Z__ - # ||::|:::Z____ - # ||::|:::|====| - # ||==|===|====| - # ||""|===|====| - # || `"""|====| - # || `""""` - return (U, S, A) - end - end - return (U, S, VT) - end - - # SUBROUTINE DGESVD( JOBU, JOBVT, M, N, A, LDA, S, U, LDU, VT, LDVT, WORK, LWORK, INFO ) - # * .. Scalar Arguments .. - # CHARACTER JOBU, JOBVT - # INTEGER INFO, LDA, LDU, LDVT, LWORK, M, N - # * .. Array Arguments .. - # DOUBLE PRECISION A( LDA, * ), S( * ), U( LDU, * ), - # $ VT( LDVT, * ), WORK( * ) - function gesvd!(jobu::Char, jobvt::Char, A::StridedMatrix{$elty}) - chkstride1(A) - m, n = size(A) - minmn = min(m, n) - S = similar(A, $relty, minmn) - U = similar(A, $elty, jobu == 'A'? (m, m):(jobu == 'S'? (m, minmn) : (m, 0))) - VT = similar(A, $elty, jobvt == 'A'? (n, n):(jobvt == 'S'? (minmn, n) : (n, 0))) - work = Vector{$elty}(1) - cmplx = eltype(A) <: Complex - if cmplx - rwork = Vector{$relty}(5minmn) - end - lwork = BlasInt(-1) - info = Ref{BlasInt}() - for i in 1:2 - if cmplx - ccall((@blasfunc($gesvd), liblapack), Void, - (Ptr{UInt8}, Ptr{UInt8}, Ptr{BlasInt}, Ptr{BlasInt}, - Ptr{$elty}, Ptr{BlasInt}, Ptr{$relty}, Ptr{$elty}, - Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, - Ptr{BlasInt}, Ptr{$relty}, Ptr{BlasInt}), - &jobu, &jobvt, &m, &n, A, &max(1,stride(A,2)), S, U, &max(1,stride(U,2)), VT, &max(1,stride(VT,2)), - work, &lwork, rwork, info) - else - ccall((@blasfunc($gesvd), liblapack), Void, - (Ptr{UInt8}, Ptr{UInt8}, Ptr{BlasInt}, Ptr{BlasInt}, - Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, Ptr{$elty}, - Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, - Ptr{BlasInt}, Ptr{BlasInt}), - &jobu, &jobvt, &m, &n, A, &max(1,stride(A,2)), S, U, &max(1,stride(U,2)), VT, &max(1,stride(VT,2)), - work, &lwork, info) - end - chklapackerror(info[]) - if i == 1 - lwork = BlasInt(real(work[1])) - work = Vector{$elty}(lwork) - end - end - if jobu == 'O' - return (A, S, VT) - elseif jobvt == 'O' - # =============|===========|() - # # # #:::::: - # # # #:::::: - # # # #:::::: - # # # #:::::: - # # # # # # # - # # # # # # # - # # # # # # # - return (U, S, A) # # # # # # # - else # # # # # # # - return (U, S, VT) # # # # # # # - - end - end - - # SUBROUTINE ZGGSVD( JOBU, JOBV, JOBQ, M, N, P, K, L, A, LDA, B, - # $ LDB, ALPHA, BETA, U, LDU, V, LDV, Q, LDQ, WORK, - # $ RWORK, IWORK, INFO ) - # * .. Scalar Arguments .. - # CHARACTER JOBQ, JOBU, JOBV - # INTEGER INFO, K, L, LDA, LDB, LDQ, LDU, LDV, M, N, P - # * .. - # * .. Array Arguments .. - # INTEGER IWORK( * ) - # DOUBLE PRECISION ALPHA( * ), BETA( * ), RWORK( * ) - # COMPLEX*16 A( LDA, * ), B( LDB, * ), Q( LDQ, * ), - # $ U( LDU, * ), V( LDV, * ), WORK( * ) - function ggsvd!(jobu::Char, jobv::Char, jobq::Char, A::StridedMatrix{$elty}, B::StridedMatrix{$elty}) - chkstride1(A, B) - m, n = size(A) - if size(B, 2) != n - throw(DimensionMismatch("B has second dimension $(size(B,2)) but needs $n")) - end - p = size(B, 1) - k = Vector{BlasInt}(1) - l = Vector{BlasInt}(1) - lda = max(1,stride(A, 2)) - ldb = max(1,stride(B, 2)) - alpha = similar(A, $relty, n) - beta = similar(A, $relty, n) - ldu = max(1, m) - U = jobu == 'U' ? similar(A, $elty, ldu, m) : similar(A, $elty, 0) - ldv = max(1, p) - V = jobv == 'V' ? similar(A, $elty, ldv, p) : similar(A, $elty, 0) - ldq = max(1, n) - Q = jobq == 'Q' ? similar(A, $elty, ldq, n) : similar(A, $elty, 0) - work = Vector{$elty}(max(3n, m, p) + n) - cmplx = eltype(A) <: Complex - if cmplx - rwork = Vector{$relty}(2n) - end - iwork = Vector{BlasInt}(n) - info = Ref{BlasInt}() - if cmplx - ccall((@blasfunc($ggsvd), liblapack), Void, - (Ptr{UInt8}, Ptr{UInt8}, Ptr{UInt8}, Ptr{BlasInt}, - Ptr{BlasInt}, Ptr{BlasInt}, Ptr{BlasInt}, Ptr{BlasInt}, - Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, - Ptr{$relty}, Ptr{$relty}, Ptr{$elty}, Ptr{BlasInt}, - Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, - Ptr{$elty}, Ptr{$relty}, Ptr{BlasInt}, Ptr{BlasInt}), - &jobu, &jobv, &jobq, &m, - &n, &p, k, l, - A, &lda, B, &ldb, - alpha, beta, U, &ldu, - V, &ldv, Q, &ldq, - work, rwork, iwork, info) - else - ccall((@blasfunc($ggsvd), liblapack), Void, - (Ptr{UInt8}, Ptr{UInt8}, Ptr{UInt8}, Ptr{BlasInt}, - Ptr{BlasInt}, Ptr{BlasInt}, Ptr{BlasInt}, Ptr{BlasInt}, - Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, - Ptr{$relty}, Ptr{$relty}, Ptr{$elty}, Ptr{BlasInt}, - Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, - Ptr{$elty}, Ptr{BlasInt}, Ptr{BlasInt}), - &jobu, &jobv, &jobq, &m, - &n, &p, k, l, - A, &lda, B, &ldb, - alpha, beta, U, &ldu, - V, &ldv, Q, &ldq, - work, iwork, info) - end - chklapackerror(info[]) - if m - k[1] - l[1] >= 0 - R = triu(A[1:k[1] + l[1],n - k[1] - l[1] + 1:n]) - else - R = triu([A[1:m, n - k[1] - l[1] + 1:n]; B[m - k[1] + 1:l[1], n - k[1] - l[1] + 1:n]]) - end - U, V, Q, alpha, beta, k[1], l[1], R - end - end -end - -""" - geev!(jobvl, jobvr, A) -> (W, VL, VR) - -Finds the eigensystem of `A`. If `jobvl = N`, the left eigenvectors of -`A` aren't computed. If `jobvr = N`, the right eigenvectors of `A` -aren't computed. If `jobvl = V` or `jobvr = V`, the corresponding -eigenvectors are computed. Returns the eigenvalues in `W`, the right -eigenvectors in `VR`, and the left eigenvectors in `VL`. -""" -geev!(jobvl::Char, jobvr::Char, A::StridedMatrix) - -""" - gesdd!(job, A) -> (U, S, VT) - -Finds the singular value decomposition of `A`, `A = U * S * V'`, -using a divide and conquer approach. If `job = A`, all the columns of `U` and -the rows of `V'` are computed. If `job = N`, no columns of `U` or rows of `V'` -are computed. If `job = O`, `A` is overwritten with the columns of (thin) `U` -and the rows of (thin) `V'`. If `job = S`, the columns of (thin) `U` and the -rows of (thin) `V'` are computed and returned separately. -""" -gesdd!(job::Char, A::StridedMatrix) - -""" - gesvd!(jobu, jobvt, A) -> (U, S, VT) - -Finds the singular value decomposition of `A`, `A = U * S * V'`. -If `jobu = A`, all the columns of `U` are computed. If `jobvt = A` all the rows -of `V'` are computed. If `jobu = N`, no columns of `U` are computed. If -`jobvt = N` no rows of `V'` are computed. If `jobu = O`, `A` is overwritten with -the columns of (thin) `U`. If `jobvt = O`, `A` is overwritten with the rows -of (thin) `V'`. If `jobu = S`, the columns of (thin) `U` are computed -and returned separately. If `jobvt = S` the rows of (thin) `V'` are -computed and returned separately. `jobu` and `jobvt` can't both be `O`. - -Returns `U`, `S`, and `Vt`, where `S` are the singular values of `A`. -""" -gesvd!(jobu::Char, jobvt::Char, A::StridedMatrix) - -""" - ggsvd!(jobu, jobv, jobq, A, B) -> (U, V, Q, alpha, beta, k, l, R) - -Finds the generalized singular value decomposition of `A` and `B`, `U'*A*Q = D1*R` -and `V'*B*Q = D2*R`. `D1` has `alpha` on its diagonal and `D2` has `beta` on its -diagonal. If `jobu = U`, the orthogonal/unitary matrix `U` is computed. If -`jobv = V` the orthogonal/unitary matrix `V` is computed. If `jobq = Q`, -the orthogonal/unitary matrix `Q` is computed. If `jobu`, `jobv` or `jobq` is -`N`, that matrix is not computed. This function is only available in LAPACK -versions prior to 3.6.0. -""" -ggsvd!(jobu::Char, jobv::Char, jobq::Char, A::StridedMatrix, B::StridedMatrix) - - -for (f, elty) in ((:dggsvd3_, :Float64), - (:sggsvd3_, :Float32)) - @eval begin - function ggsvd3!(jobu::Char, jobv::Char, jobq::Char, A::StridedMatrix{$elty}, B::StridedMatrix{$elty}) - chkstride1(A, B) - m, n = size(A) - if size(B, 2) != n - throw(DimensionMismatch("B has second dimension $(size(B,2)) but needs $n")) - end - p = size(B, 1) - k = Ref{BlasInt}() - l = Ref{BlasInt}() - lda = max(1, stride(A, 2)) - ldb = max(1, stride(B, 2)) - alpha = similar(A, $elty, n) - beta = similar(A, $elty, n) - ldu = max(1, m) - U = jobu == 'U' ? similar(A, $elty, ldu, m) : similar(A, $elty, 0) - ldv = max(1, p) - V = jobv == 'V' ? similar(A, $elty, ldv, p) : similar(A, $elty, 0) - ldq = max(1, n) - Q = jobq == 'Q' ? similar(A, $elty, ldq, n) : similar(A, $elty, 0) - work = Vector{$elty}(1) - lwork = BlasInt(-1) - iwork = Vector{BlasInt}(n) - info = Ref{BlasInt}() - for i = 1:2 - ccall((@blasfunc($f), liblapack), Void, - (Ptr{UInt8}, Ptr{UInt8}, Ptr{UInt8}, Ptr{BlasInt}, - Ptr{BlasInt}, Ptr{BlasInt}, Ref{BlasInt}, Ref{BlasInt}, - Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, - Ptr{$elty}, Ptr{$elty}, Ptr{$elty}, Ptr{BlasInt}, - Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, - Ptr{$elty}, Ptr{BlasInt}, Ptr{BlasInt}, Ref{BlasInt}), - &jobu, &jobv, &jobq, &m, - &n, &p, k, l, - A, &lda, B, &ldb, - alpha, beta, U, &ldu, - V, &ldv, Q, &ldq, - work, &lwork, iwork, info) - chklapackerror(info[]) - if i == 1 - lwork = BlasInt(work[1]) - resize!(work, lwork) - end - end - if m - k[] - l[] >= 0 - R = triu(A[1:k[] + l[],n - k[] - l[] + 1:n]) - else - R = triu([A[1:m, n - k[] - l[] + 1:n]; B[m - k[] + 1:l[], n - k[] - l[] + 1:n]]) - end - return U, V, Q, alpha, beta, k[], l[], R - end - end -end - -for (f, elty, relty) in ((:zggsvd3_, :Complex128, :Float64), - (:cggsvd3_, :Complex64, :Float32)) - @eval begin - function ggsvd3!(jobu::Char, jobv::Char, jobq::Char, A::StridedMatrix{$elty}, B::StridedMatrix{$elty}) - chkstride1(A, B) - m, n = size(A) - if size(B, 2) != n - throw(DimensionMismatch("B has second dimension $(size(B,2)) but needs $n")) - end - p = size(B, 1) - k = Vector{BlasInt}(1) - l = Vector{BlasInt}(1) - lda = max(1,stride(A, 2)) - ldb = max(1,stride(B, 2)) - alpha = similar(A, $relty, n) - beta = similar(A, $relty, n) - ldu = max(1, m) - U = jobu == 'U' ? similar(A, $elty, ldu, m) : similar(A, $elty, 0) - ldv = max(1, p) - V = jobv == 'V' ? similar(A, $elty, ldv, p) : similar(A, $elty, 0) - ldq = max(1, n) - Q = jobq == 'Q' ? similar(A, $elty, ldq, n) : similar(A, $elty, 0) - work = Vector{$elty}(1) - lwork = BlasInt(-1) - rwork = Vector{$relty}(2n) - iwork = Vector{BlasInt}(n) - info = Ref{BlasInt}() - for i = 1:2 - ccall((@blasfunc($f), liblapack), Void, - (Ptr{UInt8}, Ptr{UInt8}, Ptr{UInt8}, Ptr{BlasInt}, - Ptr{BlasInt}, Ptr{BlasInt}, Ptr{BlasInt}, Ptr{BlasInt}, - Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, - Ptr{$relty}, Ptr{$relty}, Ptr{$elty}, Ptr{BlasInt}, - Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, - Ptr{$elty}, Ptr{BlasInt}, Ptr{$relty}, Ptr{BlasInt}, - Ptr{BlasInt}), - &jobu, &jobv, &jobq, &m, - &n, &p, k, l, - A, &lda, B, &ldb, - alpha, beta, U, &ldu, - V, &ldv, Q, &ldq, - work, &lwork, rwork, iwork, - info) - chklapackerror(info[]) - if i == 1 - lwork = BlasInt(work[1]) - work = Vector{$elty}(lwork) - end - end - if m - k[1] - l[1] >= 0 - R = triu(A[1:k[1] + l[1],n - k[1] - l[1] + 1:n]) - else - R = triu([A[1:m, n - k[1] - l[1] + 1:n]; B[m - k[1] + 1:l[1], n - k[1] - l[1] + 1:n]]) - end - return U, V, Q, alpha, beta, k[1], l[1], R - end - end -end - -""" - ggsvd3!(jobu, jobv, jobq, A, B) -> (U, V, Q, alpha, beta, k, l, R) - -Finds the generalized singular value decomposition of `A` and `B`, `U'*A*Q = D1*R` -and `V'*B*Q = D2*R`. `D1` has `alpha` on its diagonal and `D2` has `beta` on its -diagonal. If `jobu = U`, the orthogonal/unitary matrix `U` is computed. If -`jobv = V` the orthogonal/unitary matrix `V` is computed. If `jobq = Q`, -the orthogonal/unitary matrix `Q` is computed. If `jobu`, `jobv`, or `jobq` is -`N`, that matrix is not computed. This function requires LAPACK 3.6.0. -""" -ggsvd3! - -## Expert driver and generalized eigenvalue problem -for (geevx, ggev, elty) in - ((:dgeevx_,:dggev_,:Float64), - (:sgeevx_,:sggev_,:Float32)) - @eval begin - # SUBROUTINE DGEEVX( BALANC, JOBVL, JOBVR, SENSE, N, A, LDA, WR, WI, - # VL, LDVL, VR, LDVR, ILO, IHI, SCALE, ABNRM, - # RCONDE, RCONDV, WORK, LWORK, IWORK, INFO ) - # - # .. Scalar Arguments .. - # CHARACTER BALANC, JOBVL, JOBVR, SENSE - # INTEGER IHI, ILO, INFO, LDA, LDVL, LDVR, LWORK, N - # DOUBLE PRECISION ABNRM - # .. - # .. Array Arguments .. - # INTEGER IWORK( * ) - # DOUBLE PRECISION A( LDA, * ), RCONDE( * ), RCONDV( * ), - # $ SCALE( * ), VL( LDVL, * ), VR( LDVR, * ), - # $ WI( * ), WORK( * ), WR( * ) - function geevx!(balanc::Char, jobvl::Char, jobvr::Char, sense::Char, A::StridedMatrix{$elty}) - n = checksquare(A) - chkfinite(A) # balancing routines don't support NaNs and Infs - lda = max(1,stride(A,2)) - wr = similar(A, $elty, n) - wi = similar(A, $elty, n) - if balanc ∉ ['N', 'P', 'S', 'B'] - throw(ArgumentError("balanc must be 'N', 'P', 'S', or 'B', but $balanc was passed")) - end - ldvl = 0 - if jobvl == 'V' - ldvl = n - elseif jobvl == 'N' - ldvl = 0 - else - throw(ArgumentError("jobvl must be 'V' or 'N', but $jobvl was passed")) - end - VL = similar(A, $elty, ldvl, n) - ldvr = 0 - if jobvr == 'V' - ldvr = n - elseif jobvr == 'N' - ldvr = 0 - else - throw(ArgumentError("jobvr must be 'V' or 'N', but $jobvr was passed")) - end - VR = similar(A, $elty, ldvr, n) - ilo = Ref{BlasInt}() - ihi = Ref{BlasInt}() - scale = similar(A, $elty, n) - abnrm = Ref{$elty}() - rconde = similar(A, $elty, n) - rcondv = similar(A, $elty, n) - work = Vector{$elty}(1) - lwork = BlasInt(-1) - iworksize = 0 - if sense == 'N' || sense == 'E' - iworksize = 0 - elseif sense == 'V' || sense == 'B' - iworksize = 2*n - 2 - else - throw(ArgumentError("sense must be 'N', 'E', 'V' or 'B', but $sense was passed")) - end - iwork = Vector{BlasInt}(iworksize) - info = Ref{BlasInt}() - for i = 1:2 - ccall((@blasfunc($geevx), liblapack), Void, - (Ptr{UInt8}, Ptr{UInt8}, Ptr{UInt8}, Ptr{UInt8}, - Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, - Ptr{$elty}, Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, - Ptr{BlasInt}, Ptr{BlasInt}, Ptr{BlasInt}, Ptr{$elty}, - Ptr{$elty}, Ptr{$elty}, Ptr{$elty}, Ptr{$elty}, - Ptr{BlasInt}, Ptr{BlasInt}, Ptr{BlasInt}), - &balanc, &jobvl, &jobvr, &sense, - &n, A, &lda, wr, - wi, VL, &max(1,ldvl), VR, - &max(1,ldvr), ilo, ihi, scale, - abnrm, rconde, rcondv, work, - &lwork, iwork, info) - chklapackerror(info[]) - if i == 1 - lwork = BlasInt(work[1]) - work = Vector{$elty}(lwork) - end - end - A, wr, wi, VL, VR, ilo[], ihi[], scale, abnrm[], rconde, rcondv - end - - # SUBROUTINE DGGEV( JOBVL, JOBVR, N, A, LDA, B, LDB, ALPHAR, ALPHAI, - # $ BETA, VL, LDVL, VR, LDVR, WORK, LWORK, INFO ) - # * .. Scalar Arguments .. - # CHARACTER JOBVL, JOBVR - # INTEGER INFO, LDA, LDB, LDVL, LDVR, LWORK, N - # * .. - # * .. Array Arguments .. - # DOUBLE PRECISION A( LDA, * ), ALPHAI( * ), ALPHAR( * ), - # $ B( LDB, * ), BETA( * ), VL( LDVL, * ), - # $ VR( LDVR, * ), WORK( * ) - function ggev!(jobvl::Char, jobvr::Char, A::StridedMatrix{$elty}, B::StridedMatrix{$elty}) - chkstride1(A,B) - n, m = checksquare(A,B) - if n != m - throw(DimensionMismatch("A has dimensions $(size(A)), and B has dimensions $(size(B)), but A and B must have the same size")) - end - lda = max(1, stride(A, 2)) - ldb = max(1, stride(B, 2)) - alphar = similar(A, $elty, n) - alphai = similar(A, $elty, n) - beta = similar(A, $elty, n) - ldvl = 0 - if jobvl == 'V' - ldvl = n - elseif jobvl == 'N' - ldvl = 1 - else - throw(ArgumentError("jobvl must be 'V' or 'N', but $jobvl was passed")) - end - vl = similar(A, $elty, ldvl, n) - ldvr = 0 - if jobvr == 'V' - ldvr = n - elseif jobvr == 'N' - ldvr = 1 - else - throw(ArgumentError("jobvr must be 'V' or 'N', but $jobvr was passed")) - end - vr = similar(A, $elty, ldvr, n) - work = Vector{$elty}(1) - lwork = BlasInt(-1) - info = Ref{BlasInt}() - for i = 1:2 - ccall((@blasfunc($ggev), liblapack), Void, - (Ptr{UInt8}, Ptr{UInt8}, Ptr{BlasInt}, Ptr{$elty}, - Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, - Ptr{$elty}, Ptr{$elty}, Ptr{$elty}, Ptr{BlasInt}, - Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, - Ptr{BlasInt}), - &jobvl, &jobvr, &n, A, - &lda, B, &ldb, alphar, - alphai, beta, vl, &ldvl, - vr, &ldvr, work, &lwork, - info) - chklapackerror(info[]) - if i == 1 - lwork = BlasInt(work[1]) - work = Vector{$elty}(lwork) - end - end - alphar, alphai, beta, vl, vr - end - end -end - -for (geevx, ggev, elty, relty) in - ((:zgeevx_,:zggev_,:Complex128,:Float64), - (:cgeevx_,:cggev_,:Complex64,:Float32)) - @eval begin - # SUBROUTINE ZGEEVX( BALANC, JOBVL, JOBVR, SENSE, N, A, LDA, W, VL, - # LDVL, VR, LDVR, ILO, IHI, SCALE, ABNRM, RCONDE, - # RCONDV, WORK, LWORK, RWORK, INFO ) - # - # .. Scalar Arguments .. - # CHARACTER BALANC, JOBVL, JOBVR, SENSE - # INTEGER IHI, ILO, INFO, LDA, LDVL, LDVR, LWORK, N - # DOUBLE PRECISION ABNRM - # .. - # .. Array Arguments .. - # DOUBLE PRECISION RCONDE( * ), RCONDV( * ), RWORK( * ), - # $ SCALE( * ) - # COMPLEX*16 A( LDA, * ), VL( LDVL, * ), VR( LDVR, * ), - # $ W( * ), WORK( * ) - function geevx!(balanc::Char, jobvl::Char, jobvr::Char, sense::Char, A::StridedMatrix{$elty}) - n = checksquare(A) - chkfinite(A) # balancing routines don't support NaNs and Infs - lda = max(1,stride(A,2)) - w = similar(A, $elty, n) - if balanc ∉ ['N', 'P', 'S', 'B'] - throw(ArgumentError("balanc must be 'N', 'P', 'S', or 'B', but $balanc was passed")) - end - ldvl = 0 - if jobvl == 'V' - ldvl = n - elseif jobvl == 'N' - ldvl = 0 - else - throw(ArgumentError("jobvl must be 'V' or 'N', but $jobvl was passed")) - end - VL = similar(A, $elty, ldvl, n) - ldvr = 0 - if jobvr == 'V' - ldvr = n - elseif jobvr == 'N' - ldvr = 0 - else - throw(ArgumentError("jobvr must be 'V' or 'N', but $jobvr was passed")) - end - if sense ∉ ['N','E','V','B'] - throw(ArgumentError("sense must be 'N', 'E', 'V' or 'B', but $sense was passed")) - end - VR = similar(A, $elty, ldvr, n) - ilo = Ref{BlasInt}() - ihi = Ref{BlasInt}() - scale = similar(A, $relty, n) - abnrm = Ref{$relty}() - rconde = similar(A, $relty, n) - rcondv = similar(A, $relty, n) - work = Vector{$elty}(1) - lwork = BlasInt(-1) - rwork = Vector{$relty}(2n) - info = Ref{BlasInt}() - for i = 1:2 - ccall((@blasfunc($geevx), liblapack), Void, - (Ptr{UInt8}, Ptr{UInt8}, Ptr{UInt8}, Ptr{UInt8}, - Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, - Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, - Ptr{BlasInt}, Ptr{BlasInt}, Ptr{$relty}, Ptr{$relty}, - Ptr{$relty}, Ptr{$relty}, Ptr{$elty}, Ptr{BlasInt}, - Ptr{$relty}, Ptr{BlasInt}), - &balanc, &jobvl, &jobvr, &sense, - &n, A, &lda, w, - VL, &max(1,ldvl), VR, &max(1,ldvr), - ilo, ihi, scale, abnrm, - rconde, rcondv, work, &lwork, - rwork, info) - chklapackerror(info[]) - if i == 1 - lwork = BlasInt(work[1]) - work = Vector{$elty}(lwork) - end - end - A, w, VL, VR, ilo[], ihi[], scale, abnrm[], rconde, rcondv - end - - # SUBROUTINE ZGGEV( JOBVL, JOBVR, N, A, LDA, B, LDB, ALPHA, BETA, - # $ VL, LDVL, VR, LDVR, WORK, LWORK, RWORK, INFO ) - # * .. Scalar Arguments .. - # CHARACTER JOBVL, JOBVR - # INTEGER INFO, LDA, LDB, LDVL, LDVR, LWORK, N - # * .. - # * .. Array Arguments .. - # DOUBLE PRECISION RWORK( * ) - # COMPLEX*16 A( LDA, * ), ALPHA( * ), B( LDB, * ), - # $ BETA( * ), VL( LDVL, * ), VR( LDVR, * ), - # $ WORK( * ) - function ggev!(jobvl::Char, jobvr::Char, A::StridedMatrix{$elty}, B::StridedMatrix{$elty}) - chkstride1(A, B) - n, m = checksquare(A, B) - if n != m - throw(DimensionMismatch("A has dimensions $(size(A)), and B has dimensions $(size(B)), but A and B must have the same size")) - end - lda = max(1, stride(A, 2)) - ldb = max(1, stride(B, 2)) - alpha = similar(A, $elty, n) - beta = similar(A, $elty, n) - ldvl = 0 - if jobvl == 'V' - ldvl = n - elseif jobvl == 'N' - ldvl = 1 - else - throw(ArgumentError("jobvl must be 'V' or 'N', but $jobvl was passed")) - end - vl = similar(A, $elty, ldvl, n) - ldvr = 0 - if jobvr == 'V' - ldvr = n - elseif jobvr == 'N' - ldvr = 1 - else - throw(ArgumentError("jobvr must be 'V' or 'N', but $jobvr was passed")) - end - vr = similar(A, $elty, ldvr, n) - work = Vector{$elty}(1) - lwork = BlasInt(-1) - rwork = Vector{$relty}(8n) - info = Ref{BlasInt}() - for i = 1:2 - ccall((@blasfunc($ggev), liblapack), Void, - (Ptr{UInt8}, Ptr{UInt8}, Ptr{BlasInt}, Ptr{$elty}, - Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, - Ptr{$elty}, Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, - Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, Ptr{$relty}, - Ptr{BlasInt}), - &jobvl, &jobvr, &n, A, - &lda, B, &ldb, alpha, - beta, vl, &ldvl, vr, - &ldvr, work, &lwork, rwork, - info) - chklapackerror(info[]) - if i == 1 - lwork = BlasInt(work[1]) - work = Vector{$elty}(lwork) - end - end - alpha, beta, vl, vr - end - end -end - -""" - geevx!(balanc, jobvl, jobvr, sense, A) -> (A, w, VL, VR, ilo, ihi, scale, abnrm, rconde, rcondv) - -Finds the eigensystem of `A` with matrix balancing. If `jobvl = N`, the -left eigenvectors of `A` aren't computed. If `jobvr = N`, the right -eigenvectors of `A` aren't computed. If `jobvl = V` or `jobvr = V`, the -corresponding eigenvectors are computed. If `balanc = N`, no balancing is -performed. If `balanc = P`, `A` is permuted but not scaled. If -`balanc = S`, `A` is scaled but not permuted. If `balanc = B`, `A` is -permuted and scaled. If `sense = N`, no reciprocal condition numbers are -computed. If `sense = E`, reciprocal condition numbers are computed for -the eigenvalues only. If `sense = V`, reciprocal condition numbers are -computed for the right eigenvectors only. If `sense = B`, reciprocal -condition numbers are computed for the right eigenvectors and the -eigenvectors. If `sense = E,B`, the right and left eigenvectors must be -computed. -""" -geevx!(balanc::Char, jobvl::Char, jobvr::Char, sense::Char, A::StridedMatrix) - -""" - ggev!(jobvl, jobvr, A, B) -> (alpha, beta, vl, vr) - -Finds the generalized eigendecomposition of `A` and `B`. If `jobvl = N`, -the left eigenvectors aren't computed. If `jobvr = N`, the right -eigenvectors aren't computed. If `jobvl = V` or `jobvr = V`, the -corresponding eigenvectors are computed. -""" -ggev!(jobvl::Char, jobvr::Char, A::StridedMatrix, B::StridedMatrix) - -# One step incremental condition estimation of max/min singular values -for (laic1, elty) in - ((:dlaic1_,:Float64), - (:slaic1_,:Float32)) - @eval begin - # SUBROUTINE DLAIC1( JOB, J, X, SEST, W, GAMMA, SESTPR, S, C ) - # - # .. Scalar Arguments .. - # INTEGER J, JOB - # DOUBLE PRECISION C, GAMMA, S, SEST, SESTPR - # .. - # .. Array Arguments .. - # DOUBLE PRECISION W( J ), X( J ) - function laic1!(job::Integer, x::StridedVector{$elty}, - sest::$elty, w::StridedVector{$elty}, gamma::$elty) - j = length(x) - if j != length(w) - throw(DimensionMismatch("vectors must have same length, but length of x is $j and length of w is $(length(w))")) - end - sestpr = Vector{$elty}(1) - s = Vector{$elty}(1) - c = Vector{$elty}(1) - ccall((@blasfunc($laic1), liblapack), Void, - (Ptr{BlasInt}, Ptr{BlasInt}, Ptr{$elty}, Ptr{$elty}, - Ptr{$elty}, Ptr{$elty}, Ptr{$elty}, Ptr{$elty}, - Ptr{$elty}), - &job, &j, x, &sest, - w, &gamma, sestpr, s, - c) - sestpr[1], s[1], c[1] - end - end -end -for (laic1, elty, relty) in - ((:zlaic1_,:Complex128,:Float64), - (:claic1_,:Complex64,:Float32)) - @eval begin - # SUBROUTINE ZLAIC1( JOB, J, X, SEST, W, GAMMA, SESTPR, S, C ) - # - # .. Scalar Arguments .. - # INTEGER J, JOB - # DOUBLE PRECISION SEST, SESTPR - # COMPLEX*16 C, GAMMA, S - # .. - # .. Array Arguments .. - # COMPLEX*16 W( J ), X( J ) - function laic1!(job::Integer, x::StridedVector{$elty}, - sest::$relty, w::StridedVector{$elty}, gamma::$elty) - j = length(x) - if j != length(w) - throw(DimensionMismatch("vectors must have same length, but length of x is $j and length of w is $(length(w))")) - end - sestpr = Vector{$relty}(1) - s = Vector{$elty}(1) - c = Vector{$elty}(1) - ccall((@blasfunc($laic1), liblapack), Void, - (Ptr{BlasInt}, Ptr{BlasInt}, Ptr{$elty}, Ptr{$relty}, - Ptr{$elty}, Ptr{$elty}, Ptr{$relty}, Ptr{$elty}, - Ptr{$elty}), - &job, &j, x, &sest, - w, &gamma, sestpr, s, - c) - sestpr[1], s[1], c[1] - end - end -end - -# (GT) General tridiagonal, decomposition, solver and direct solver -for (gtsv, gttrf, gttrs, elty) in - ((:dgtsv_,:dgttrf_,:dgttrs_,:Float64), - (:sgtsv_,:sgttrf_,:sgttrs_,:Float32), - (:zgtsv_,:zgttrf_,:zgttrs_,:Complex128), - (:cgtsv_,:cgttrf_,:cgttrs_,:Complex64)) - @eval begin - # SUBROUTINE DGTSV( N, NRHS, DL, D, DU, B, LDB, INFO ) - # .. Scalar Arguments .. - # INTEGER INFO, LDB, N, NRHS - # .. Array Arguments .. - # DOUBLE PRECISION B( LDB, * ), D( * ), DL( * ), DU( * ) - function gtsv!(dl::StridedVector{$elty}, d::StridedVector{$elty}, du::StridedVector{$elty}, - B::StridedVecOrMat{$elty}) - chkstride1(B, dl, d, du) - n = length(d) - if !(n >= length(dl) >= n - 1) - throw(DimensionMismatch("subdiagonal has length $(length(dl)), but should be $n or $(n - 1)")) - end - if !(n >= length(du) >= n - 1) - throw(DimensionMismatch("superdiagonal has length $(length(du)), but should be $n or $(n - 1)")) - end - if n != size(B,1) - throw(DimensionMismatch("B has leading dimension $(size(B,1)), but should have $n")) - end - if n == 0 - return B # Early exit if possible - end - info = Ref{BlasInt}() - ccall((@blasfunc($gtsv), liblapack), Void, - (Ptr{BlasInt}, Ptr{BlasInt}, Ptr{$elty}, Ptr{$elty}, Ptr{$elty}, - Ptr{$elty}, Ptr{BlasInt}, Ptr{BlasInt}), - &n, &size(B,2), dl, d, du, B, &max(1,stride(B,2)), info) - chklapackerror(info[]) - B - end - - # SUBROUTINE DGTTRF( N, DL, D, DU, DU2, IPIV, INFO ) - # .. Scalar Arguments .. - # INTEGER INFO, N - # .. Array Arguments .. - # INTEGER IPIV( * ) - # DOUBLE PRECISION D( * ), DL( * ), DU( * ), DU2( * ) - function gttrf!(dl::StridedVector{$elty}, d::StridedVector{$elty}, du::StridedVector{$elty}) - chkstride1(dl,d,du) - n = length(d) - if length(dl) != n - 1 - throw(DimensionMismatch("subdiagonal has length $(length(dl)), but should be $(n - 1)")) - end - if length(du) != n - 1 - throw(DimensionMismatch("superdiagonal has length $(length(du)), but should be $(n - 1)")) - end - du2 = similar(d, $elty, n-2) - ipiv = similar(d, BlasInt, n) - info = Ref{BlasInt}() - ccall((@blasfunc($gttrf), liblapack), Void, - (Ptr{BlasInt}, Ptr{$elty}, Ptr{$elty}, Ptr{$elty}, Ptr{$elty}, - Ptr{BlasInt}, Ptr{BlasInt}), - &n, dl, d, du, du2, ipiv, info) - chklapackerror(info[]) - dl, d, du, du2, ipiv - end - - # SUBROUTINE DGTTRS( TRANS, N, NRHS, DL, D, DU, DU2, IPIV, B, LDB, INFO ) - # .. Scalar Arguments .. - # CHARACTER TRANS - # INTEGER INFO, LDB, N, NRHS - # .. Array Arguments .. - # INTEGER IPIV( * ) - # DOUBLE PRECISION B( LDB, * ), D( * ), DL( * ), DU( * ), DU2( * ) - function gttrs!(trans::Char, dl::StridedVector{$elty}, d::StridedVector{$elty}, - du::StridedVector{$elty}, du2::StridedVector{$elty}, ipiv::StridedVector{BlasInt}, - B::StridedVecOrMat{$elty}) - chktrans(trans) - chkstride1(B, ipiv, dl, d, du, du2) - n = length(d) - if length(dl) != n - 1 - throw(DimensionMismatch("subdiagonal has length $(length(dl)), but should be $(n - 1)")) - end - if length(du) != n - 1 - throw(DimensionMismatch("superdiagonal has length $(length(du)), but should be $(n - 1)")) - end - if n != size(B,1) - throw(DimensionMismatch("B has leading dimension $(size(B,1)), but should have $n")) - end - info = Ref{BlasInt}() - ccall((@blasfunc($gttrs), liblapack), Void, - (Ptr{UInt8}, Ptr{BlasInt}, Ptr{BlasInt}, - Ptr{$elty}, Ptr{$elty}, Ptr{$elty}, Ptr{$elty}, - Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, Ptr{BlasInt}), - &trans, &n, &size(B,2), dl, d, du, du2, ipiv, B, &max(1,stride(B,2)), info) - chklapackerror(info[]) - B - end - end -end - -""" - gtsv!(dl, d, du, B) - -Solves the equation `A * X = B` where `A` is a tridiagonal matrix with -`dl` on the subdiagonal, `d` on the diagonal, and `du` on the -superdiagonal. - -Overwrites `B` with the solution `X` and returns it. -""" -gtsv!(dl::StridedVector, d::StridedVector, du::StridedVector, B::StridedVecOrMat) - -""" - gttrf!(dl, d, du) -> (dl, d, du, du2, ipiv) - -Finds the `LU` factorization of a tridiagonal matrix with `dl` on the -subdiagonal, `d` on the diagonal, and `du` on the superdiagonal. - -Modifies `dl`, `d`, and `du` in-place and returns them and the second -superdiagonal `du2` and the pivoting vector `ipiv`. -""" -gttrf!(dl::StridedVector, d::StridedVector, du::StridedVector) - -""" - gttrs!(trans, dl, d, du, du2, ipiv, B) - -Solves the equation `A * X = B` (`trans = N`), `A.' * X = B` (`trans = T`), -or `A' * X = B` (`trans = C`) using the `LU` factorization computed by -`gttrf!`. `B` is overwritten with the solution `X`. -""" -gttrs!(trans::Char, dl::StridedVector, d::StridedVector, du::StridedVector, du2::StridedVector, - ipiv::StridedVector{BlasInt}, B::StridedVecOrMat) - -## (OR) orthogonal (or UN, unitary) matrices, extractors and multiplication -for (orglq, orgqr, orgql, orgrq, ormlq, ormqr, ormql, ormrq, gemqrt, elty) in - ((:dorglq_,:dorgqr_,:dorgql_,:dorgrq_,:dormlq_,:dormqr_,:dormql_,:dormrq_,:dgemqrt_,:Float64), - (:sorglq_,:sorgqr_,:sorgql_,:sorgrq_,:sormlq_,:sormqr_,:sormql_,:sormrq_,:sgemqrt_,:Float32), - (:zunglq_,:zungqr_,:zungql_,:zungrq_,:zunmlq_,:zunmqr_,:zunmql_,:zunmrq_,:zgemqrt_,:Complex128), - (:cunglq_,:cungqr_,:cungql_,:cungrq_,:cunmlq_,:cunmqr_,:cunmql_,:cunmrq_,:cgemqrt_,:Complex64)) - @eval begin - # SUBROUTINE DORGLQ( M, N, K, A, LDA, TAU, WORK, LWORK, INFO ) - # * .. Scalar Arguments .. - # INTEGER INFO, K, LDA, LWORK, M, N - # * .. Array Arguments .. - # DOUBLE PRECISION A( LDA, * ), TAU( * ), WORK( * ) - function orglq!(A::StridedMatrix{$elty}, tau::StridedVector{$elty}, k::Integer = length(tau)) - chkstride1(A,tau) - n = size(A, 2) - m = min(n, size(A, 1)) - if k > m - throw(DimensionMismatch("invalid number of reflectors: k = $k should be <= m = $m")) - end - work = Vector{$elty}(1) - lwork = BlasInt(-1) - info = Ref{BlasInt}() - for i = 1:2 - ccall((@blasfunc($orglq), liblapack), Void, - (Ptr{BlasInt}, Ptr{BlasInt}, Ptr{BlasInt}, Ptr{$elty}, - Ptr{BlasInt}, Ptr{$elty}, Ptr{$elty}, Ptr{BlasInt}, Ptr{BlasInt}), - &m, &n, &k, A, &max(1,stride(A,2)), tau, work, &lwork, info) - chklapackerror(info[]) - if i == 1 - lwork = BlasInt(real(work[1])) - work = Vector{$elty}(lwork) - end - end - if m < size(A,1) - A[1:m,:] - else - A - end - end - - # SUBROUTINE DORGQR( M, N, K, A, LDA, TAU, WORK, LWORK, INFO ) - # * .. Scalar Arguments .. - # INTEGER INFO, K, LDA, LWORK, M, N - # * .. Array Arguments .. - # DOUBLE PRECISION A( LDA, * ), TAU( * ), WORK( * ) - function orgqr!(A::StridedMatrix{$elty}, tau::StridedVector{$elty}, k::Integer = length(tau)) - chkstride1(A,tau) - m = size(A, 1) - n = min(m, size(A, 2)) - if k > n - throw(DimensionMismatch("invalid number of reflectors: k = $k should be <= n = $n")) - end - work = Vector{$elty}(1) - lwork = BlasInt(-1) - info = Ref{BlasInt}() - for i = 1:2 - ccall((@blasfunc($orgqr), liblapack), Void, - (Ptr{BlasInt}, Ptr{BlasInt}, Ptr{BlasInt}, Ptr{$elty}, - Ptr{BlasInt}, Ptr{$elty}, Ptr{$elty}, Ptr{BlasInt}, Ptr{BlasInt}), - &m, &n, &k, A, - &max(1,stride(A,2)), tau, work, &lwork, - info) - chklapackerror(info[]) - if i == 1 - lwork = BlasInt(real(work[1])) - work = Vector{$elty}(lwork) - end - end - if n < size(A,2) - A[:,1:n] - else - A - end - end - - # SUBROUTINE DORGQL( M, N, K, A, LDA, TAU, WORK, LWORK, INFO ) - # * .. Scalar Arguments .. - # INTEGER INFO, K, LDA, LWORK, M, N - # * .. Array Arguments .. - # DOUBLE PRECISION A( LDA, * ), TAU( * ), WORK( * ) - function orgql!(A::StridedMatrix{$elty}, tau::StridedVector{$elty}, k::Integer = length(tau)) - chkstride1(A,tau) - m = size(A, 1) - n = min(m, size(A, 2)) - if k > n - throw(DimensionMismatch("invalid number of reflectors: k = $k should be <= n = $n")) - end - work = Vector{$elty}(1) - lwork = BlasInt(-1) - info = Ref{BlasInt}() - for i = 1:2 - ccall((@blasfunc($orgql), liblapack), Void, - (Ptr{BlasInt}, Ptr{BlasInt}, Ptr{BlasInt}, Ptr{$elty}, - Ptr{BlasInt}, Ptr{$elty}, Ptr{$elty}, Ptr{BlasInt}, Ptr{BlasInt}), - &m, &n, &k, A, - &max(1,stride(A,2)), tau, work, &lwork, - info) - chklapackerror(info[]) - if i == 1 - lwork = BlasInt(real(work[1])) - work = Vector{$elty}(lwork) - end - end - if n < size(A,2) - A[:,1:n] - else - A - end - end - - # SUBROUTINE DORGRQ( M, N, K, A, LDA, TAU, WORK, LWORK, INFO ) - # * .. Scalar Arguments .. - # INTEGER INFO, K, LDA, LWORK, M, N - # * .. Array Arguments .. - # DOUBLE PRECISION A( LDA, * ), TAU( * ), WORK( * ) - function orgrq!(A::StridedMatrix{$elty}, tau::StridedVector{$elty}, k::Integer = length(tau)) - chkstride1(A,tau) - m = size(A, 1) - n = min(m, size(A, 2)) - if k > n - throw(DimensionMismatch("invalid number of reflectors: k = $k should be <= n = $n")) - end - work = Vector{$elty}(1) - lwork = BlasInt(-1) - info = Ref{BlasInt}() - for i = 1:2 - ccall((@blasfunc($orgrq), liblapack), Void, - (Ptr{BlasInt}, Ptr{BlasInt}, Ptr{BlasInt}, Ptr{$elty}, - Ptr{BlasInt}, Ptr{$elty}, Ptr{$elty}, Ptr{BlasInt}, Ptr{BlasInt}), - &m, &n, &k, A, - &max(1,stride(A,2)), tau, work, &lwork, - info) - chklapackerror(info[]) - if i == 1 - lwork = BlasInt(real(work[1])) - work = Vector{$elty}(lwork) - end - end - if n < size(A,2) - A[:,1:n] - else - A - end - end - - # SUBROUTINE DORMLQ( SIDE, TRANS, M, N, K, A, LDA, TAU, C, LDC, - # WORK, LWORK, INFO ) - # .. Scalar Arguments .. - # CHARACTER SIDE, TRANS - # INTEGER INFO, K, LDA, LDC, LWORK, M, N - # .. Array Arguments .. - # DOUBLE PRECISION A( LDA, * ), C( LDC, * ), TAU( * ), WORK( * ) - function ormlq!(side::Char, trans::Char, A::StridedMatrix{$elty}, - tau::StridedVector{$elty}, C::StridedVecOrMat{$elty}) - chktrans(trans) - chkside(side) - chkstride1(A, C, tau) - m,n = ndims(C) == 2 ? size(C) : (size(C, 1), 1) - mA, nA = size(A) - k = length(tau) - if side == 'L' && m != nA - throw(DimensionMismatch("for a left-sided multiplication, the first dimension of C, $m, must equal the second dimension of A, $nA")) - end - if side == 'R' && n != mA - throw(DimensionMismatch("for a right-sided multiplication, the second dimension of C, $n, must equal the first dimension of A, $mA")) - end - if side == 'L' && k > m - throw(DimensionMismatch("invalid number of reflectors: k = $k should be <= m = $m")) - end - if side == 'R' && k > n - throw(DimensionMismatch("invalid number of reflectors: k = $k should be <= n = $n")) - end - work = Vector{$elty}(1) - lwork = BlasInt(-1) - info = Ref{BlasInt}() - for i = 1:2 - ccall((@blasfunc($ormlq), liblapack), Void, - (Ptr{UInt8}, Ptr{UInt8}, Ptr{BlasInt}, Ptr{BlasInt}, Ptr{BlasInt}, - Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, Ptr{$elty}, Ptr{BlasInt}, - Ptr{$elty}, Ptr{BlasInt}, Ptr{BlasInt}), - &side, &trans, &m, &n, &k, A, &max(1,stride(A,2)), tau, - C, &max(1,stride(C,2)), work, &lwork, info) - chklapackerror(info[]) - if i == 1 - lwork = BlasInt(real(work[1])) - work = Vector{$elty}(lwork) - end - end - C - end - - # SUBROUTINE DORMQR( SIDE, TRANS, M, N, K, A, LDA, TAU, C, LDC, - # WORK, INFO ) - # .. Scalar Arguments .. - # CHARACTER SIDE, TRANS - # INTEGER INFO, K, LDA, LDC, M, N - # .. Array Arguments .. - # DOUBLE PRECISION A( LDA, * ), C( LDC, * ), TAU( * ), WORK( * ) - function ormqr!(side::Char, trans::Char, A::StridedMatrix{$elty}, - tau::StridedVector{$elty}, C::StridedVecOrMat{$elty}) - chktrans(trans) - chkside(side) - chkstride1(A, C, tau) - m,n = ndims(C) == 2 ? size(C) : (size(C, 1), 1) - mA = size(A, 1) - k = length(tau) - if side == 'L' && m != mA - throw(DimensionMismatch("for a left-sided multiplication, the first dimension of C, $m, must equal the second dimension of A, $mA")) - end - if side == 'R' && n != mA - throw(DimensionMismatch("for a right-sided multiplication, the second dimension of C, $m, must equal the second dimension of A, $mA")) - end - if side == 'L' && k > m - throw(DimensionMismatch("invalid number of reflectors: k = $k should be <= m = $m")) - end - if side == 'R' && k > n - throw(DimensionMismatch("invalid number of reflectors: k = $k should be <= n = $n")) - end - work = Vector{$elty}(1) - lwork = BlasInt(-1) - info = Ref{BlasInt}() - for i = 1:2 - ccall((@blasfunc($ormqr), liblapack), Void, - (Ptr{UInt8}, Ptr{UInt8}, Ptr{BlasInt}, Ptr{BlasInt}, - Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, - Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, - Ptr{BlasInt}), - &side, &trans, &m, &n, - &k, A, &max(1,stride(A,2)), tau, - C, &max(1, stride(C,2)), work, &lwork, - info) - chklapackerror(info[]) - if i == 1 - lwork = BlasInt(real(work[1])) - work = Vector{$elty}(lwork) - end - end - C - end - - # SUBROUTINE DORMQL( SIDE, TRANS, M, N, K, A, LDA, TAU, C, LDC, - # WORK, INFO ) - # .. Scalar Arguments .. - # CHARACTER SIDE, TRANS - # INTEGER INFO, K, LDA, LDC, M, N - # .. Array Arguments .. - # DOUBLE PRECISION A( LDA, * ), C( LDC, * ), TAU( * ), WORK( * ) - function ormql!(side::Char, trans::Char, A::StridedMatrix{$elty}, - tau::StridedVector{$elty}, C::StridedVecOrMat{$elty}) - chktrans(trans) - chkside(side) - chkstride1(A, C, tau) - m,n = ndims(C) == 2 ? size(C) : (size(C, 1), 1) - mA = size(A, 1) - k = length(tau) - if side == 'L' && m != mA - throw(DimensionMismatch("for a left-sided multiplication, the first dimension of C, $m, must equal the second dimension of A, $mA")) - end - if side == 'R' && n != mA - throw(DimensionMismatch("for a right-sided multiplication, the second dimension of C, $m, must equal the second dimension of A, $mA")) - end - if side == 'L' && k > m - throw(DimensionMismatch("invalid number of reflectors: k = $k should be <= m = $m")) - end - if side == 'R' && k > n - throw(DimensionMismatch("invalid number of reflectors: k = $k should be <= n = $n")) - end - work = Vector{$elty}(1) - lwork = BlasInt(-1) - info = Ref{BlasInt}() - for i = 1:2 - ccall((@blasfunc($ormql), liblapack), Void, - (Ptr{UInt8}, Ptr{UInt8}, Ptr{BlasInt}, Ptr{BlasInt}, - Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, - Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, - Ptr{BlasInt}), - &side, &trans, &m, &n, - &k, A, &max(1,stride(A,2)), tau, - C, &max(1, stride(C,2)), work, &lwork, - info) - chklapackerror(info[]) - if i == 1 - lwork = BlasInt(real(work[1])) - work = Vector{$elty}(lwork) - end - end - C - end - - # SUBROUTINE DORMRQ( SIDE, TRANS, M, N, K, A, LDA, TAU, C, LDC, - # WORK, LWORK, INFO ) - # .. Scalar Arguments .. - # CHARACTER SIDE, TRANS - # INTEGER INFO, K, LDA, LDC, LWORK, M, N - # .. Array Arguments .. - # DOUBLE PRECISION A( LDA, * ), C( LDC, * ), TAU( * ), WORK( * ) - function ormrq!(side::Char, trans::Char, A::StridedMatrix{$elty}, - tau::StridedVector{$elty}, C::StridedVecOrMat{$elty}) - chktrans(trans) - chkside(side) - chkstride1(A, C, tau) - m,n = ndims(C) == 2 ? size(C) : (size(C, 1), 1) - nA = size(A, 2) - k = length(tau) - if side == 'L' && m != nA - throw(DimensionMismatch("for a left-sided multiplication, the first dimension of C, $m, must equal the second dimension of A, $nA")) - end - if side == 'R' && n != nA - throw(DimensionMismatch("for a right-sided multiplication, the second dimension of C, $m, must equal the second dimension of A, $nA")) - end - if side == 'L' && k > m - throw(DimensionMismatch("invalid number of reflectors: k = $k should be <= m = $m")) - end - if side == 'R' && k > n - throw(DimensionMismatch("invalid number of reflectors: k = $k should be <= n = $n")) - end - work = Vector{$elty}(1) - lwork = BlasInt(-1) - info = Ref{BlasInt}() - for i = 1:2 - ccall((@blasfunc($ormrq), liblapack), Void, - (Ptr{UInt8}, Ptr{UInt8}, Ptr{BlasInt}, Ptr{BlasInt}, Ptr{BlasInt}, - Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, Ptr{$elty}, Ptr{BlasInt}, - Ptr{$elty}, Ptr{BlasInt}, Ptr{BlasInt}), - &side, &trans, &m, &n, &k, A, &max(1,stride(A,2)), tau, - C, &max(1,stride(C,2)), work, &lwork, info) - chklapackerror(info[]) - if i == 1 - lwork = BlasInt(real(work[1])) - work = Vector{$elty}(lwork) - end - end - C - end - - function gemqrt!(side::Char, trans::Char, V::StridedMatrix{$elty}, T::StridedMatrix{$elty}, C::StridedVecOrMat{$elty}) - chktrans(trans) - chkside(side) - chkstride1(V, T, C) - m,n = ndims(C) == 2 ? size(C) : (size(C, 1), 1) - nb, k = size(T) - if k == 0 - return C - end - if side == 'L' - if !(0 <= k <= m) - throw(DimensionMismatch("wrong value for k = $k: must be between 0 and $m")) - end - if m != size(V,1) - throw(DimensionMismatch("first dimensions of C, $m, and V, $(size(V,1)) must match")) - end - ldv = stride(V,2) - if ldv < max(1, m) - throw(DimensionMismatch("Q and C don't fit! The stride of V, $ldv, is too small")) - end - wss = n*k - elseif side == 'R' - if !(0 <= k <= n) - throw(DimensionMismatch("wrong value for k = $k: must be between 0 and $n")) - end - if n != size(V,1) - throw(DimensionMismatch("second dimension of C, $n, and first dimension of V, $(size(V,1)) must match")) - end - ldv = stride(V,2) - if ldv < max(1, n) - throw(DimensionMismatch("Q and C don't fit! The stride of V, $ldv, is too small")) - end - wss = m*k - end - if !(1 <= nb <= k) - throw(DimensionMismatch("wrong value for nb = $nb, which must be between 1 and $k")) - end - ldc = stride(C, 2) - work = Vector{$elty}(wss) - info = Ref{BlasInt}() - ccall((@blasfunc($gemqrt), liblapack), Void, - (Ptr{UInt8}, Ptr{UInt8}, Ptr{BlasInt}, Ptr{BlasInt}, - Ptr{BlasInt}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, - Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, - Ptr{$elty}, Ptr{BlasInt}), - &side, &trans, &m, &n, - &k, &nb, V, &ldv, - T, &max(1,stride(T,2)), C, &max(1,ldc), - work, info) - chklapackerror(info[]) - return C - end - end -end - -""" - orglq!(A, tau, k = length(tau)) - -Explicitly finds the matrix `Q` of a `LQ` factorization after calling -`gelqf!` on `A`. Uses the output of `gelqf!`. `A` is overwritten by `Q`. -""" -orglq!(A::StridedMatrix, tau::StridedVector, k::Integer = length(tau)) - -""" - orgqr!(A, tau, k = length(tau)) - -Explicitly finds the matrix `Q` of a `QR` factorization after calling -`geqrf!` on `A`. Uses the output of `geqrf!`. `A` is overwritten by `Q`. -""" -orgqr!(A::StridedMatrix, tau::StridedVector, k::Integer = length(tau)) - -""" - orgql!(A, tau, k = length(tau)) - -Explicitly finds the matrix `Q` of a `QL` factorization after calling -`geqlf!` on `A`. Uses the output of `geqlf!`. `A` is overwritten by `Q`. -""" -orgql!(A::StridedMatrix, tau::StridedVector, k::Integer = length(tau)) - -""" - orgrq!(A, tau, k = length(tau)) - -Explicitly finds the matrix `Q` of a `RQ` factorization after calling -`gerqf!` on `A`. Uses the output of `gerqf!`. `A` is overwritten by `Q`. -""" -orgrq!(A::StridedMatrix, tau::StridedVector, k::Integer = length(tau)) - -""" - ormlq!(side, trans, A, tau, C) - -Computes `Q * C` (`trans = N`), `Q.' * C` (`trans = T`), `Q' * C` -(`trans = C`) for `side = L` or the equivalent right-sided multiplication -for `side = R` using `Q` from a `LQ` factorization of `A` computed using -`gelqf!`. `C` is overwritten. -""" -ormlq!(side::Char, trans::Char, A::StridedMatrix, tau::StridedVector, C::StridedVecOrMat) - -""" - ormqr!(side, trans, A, tau, C) - -Computes `Q * C` (`trans = N`), `Q.' * C` (`trans = T`), `Q' * C` -(`trans = C`) for `side = L` or the equivalent right-sided multiplication -for `side = R` using `Q` from a `QR` factorization of `A` computed using -`geqrf!`. `C` is overwritten. -""" -ormqr!(side::Char, trans::Char, A::StridedMatrix, tau::StridedVector, C::StridedVecOrMat) - -""" - ormql!(side, trans, A, tau, C) - -Computes `Q * C` (`trans = N`), `Q.' * C` (`trans = T`), `Q' * C` -(`trans = C`) for `side = L` or the equivalent right-sided multiplication -for `side = R` using `Q` from a `QL` factorization of `A` computed using -`geqlf!`. `C` is overwritten. -""" -ormql!(side::Char, trans::Char, A::StridedMatrix, tau::StridedVector, C::StridedVecOrMat) - -""" - ormrq!(side, trans, A, tau, C) - -Computes `Q * C` (`trans = N`), `Q.' * C` (`trans = T`), `Q' * C` -(`trans = C`) for `side = L` or the equivalent right-sided multiplication -for `side = R` using `Q` from a `RQ` factorization of `A` computed using -`gerqf!`. `C` is overwritten. -""" -ormrq!(side::Char, trans::Char, A::StridedMatrix, tau::StridedVector, C::StridedVecOrMat) - -""" - gemqrt!(side, trans, V, T, C) - -Computes `Q * C` (`trans = N`), `Q.' * C` (`trans = T`), `Q' * C` -(`trans = C`) for `side = L` or the equivalent right-sided multiplication -for `side = R` using `Q` from a `QR` factorization of `A` computed using -`geqrt!`. `C` is overwritten. -""" -gemqrt!(side::Char, trans::Char, V::StridedMatrix, T::StridedMatrix, C::StridedVecOrMat) - -# (PO) positive-definite symmetric matrices, -for (posv, potrf, potri, potrs, pstrf, elty, rtyp) in - ((:dposv_,:dpotrf_,:dpotri_,:dpotrs_,:dpstrf_,:Float64,:Float64), - (:sposv_,:spotrf_,:spotri_,:spotrs_,:spstrf_,:Float32,:Float32), - (:zposv_,:zpotrf_,:zpotri_,:zpotrs_,:zpstrf_,:Complex128,:Float64), - (:cposv_,:cpotrf_,:cpotri_,:cpotrs_,:cpstrf_,:Complex64,:Float32)) - @eval begin - # SUBROUTINE DPOSV( UPLO, N, NRHS, A, LDA, B, LDB, INFO ) - #* .. Scalar Arguments .. - # CHARACTER UPLO - # INTEGER INFO, LDA, LDB, N, NRHS - # .. Array Arguments .. - # DOUBLE PRECISION A( LDA, * ), B( LDB, * ) - function posv!(uplo::Char, A::StridedMatrix{$elty}, B::StridedVecOrMat{$elty}) - chkstride1(A, B) - n = checksquare(A) - chkuplo(uplo) - if size(B,1) != n - throw(DimensionMismatch("first dimension of B, $(size(B,1)), and size of A, ($n,$n), must match!")) - end - info = Ref{BlasInt}() - ccall((@blasfunc($posv), liblapack), Void, - (Ptr{UInt8}, Ptr{BlasInt}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, - Ptr{$elty}, Ptr{BlasInt}, Ptr{BlasInt}), - &uplo, &n, &size(B,2), A, &max(1,stride(A,2)), B, &max(1,stride(B,2)), info) - chkargsok(info[]) - chkposdef(info[]) - A, B - end - - # SUBROUTINE DPOTRF( UPLO, N, A, LDA, INFO ) - # * .. Scalar Arguments .. - # CHARACTER UPLO - # INTEGER INFO, LDA, N - # * .. Array Arguments .. - # DOUBLE PRECISION A( LDA, * ) - function potrf!(uplo::Char, A::StridedMatrix{$elty}) - chkstride1(A) - checksquare(A) - chkuplo(uplo) - lda = max(1,stride(A,2)) - if lda == 0 - return A, 0 - end - info = Ref{BlasInt}() - ccall((@blasfunc($potrf), liblapack), Void, - (Ptr{UInt8}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, Ptr{BlasInt}), - &uplo, &size(A,1), A, &lda, info) - chkargsok(info[]) - #info[1]>0 means the leading minor of order info[i] is not positive definite - #ordinarily, throw Exception here, but return error code here - #this simplifies isposdef! and factorize - return A, info[] - end - - # SUBROUTINE DPOTRI( UPLO, N, A, LDA, INFO ) - # .. Scalar Arguments .. - # CHARACTER UPLO - # INTEGER INFO, LDA, N - # .. Array Arguments .. - # DOUBLE PRECISION A( LDA, * ) - function potri!(uplo::Char, A::StridedMatrix{$elty}) - chkstride1(A) - chkuplo(uplo) - info = Ref{BlasInt}() - ccall((@blasfunc($potri), liblapack), Void, - (Ptr{UInt8}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, Ptr{BlasInt}), - &uplo, &size(A,1), A, &max(1,stride(A,2)), info) - chkargsok(info[]) - chknonsingular(info[]) - A - end - - # SUBROUTINE DPOTRS( UPLO, N, NRHS, A, LDA, B, LDB, INFO ) - # .. Scalar Arguments .. - # CHARACTER UPLO - # INTEGER INFO, LDA, LDB, N, NRHS - # .. Array Arguments .. - # DOUBLE PRECISION A( LDA, * ), B( LDB, * ) - function potrs!(uplo::Char, A::StridedMatrix{$elty}, B::StridedVecOrMat{$elty}) - chkstride1(A, B) - n = checksquare(A) - chkuplo(uplo) - nrhs = size(B,2) - if size(B,1) != n - throw(DimensionMismatch("first dimension of B, $(size(B,1)), and size of A, ($n,$n), must match!")) - end - lda = max(1,stride(A,2)) - if lda == 0 || nrhs == 0 - return B - end - ldb = max(1,stride(B,2)) - info = Ref{BlasInt}() - ccall((@blasfunc($potrs), liblapack), Void, - (Ptr{UInt8}, Ptr{BlasInt}, Ptr{BlasInt}, Ptr{$elty}, - Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, Ptr{BlasInt}), - &uplo, &n, &nrhs, A, - &lda, B, &ldb, info) - chklapackerror(info[]) - return B - end - - # SUBROUTINE DPSTRF( UPLO, N, A, LDA, PIV, RANK, TOL, WORK, INFO ) - # .. Scalar Arguments .. - # DOUBLE PRECISION TOL - # INTEGER INFO, LDA, N, RANK - # CHARACTER UPLO - # .. Array Arguments .. - # DOUBLE PRECISION A( LDA, * ), WORK( 2*N ) - # INTEGER PIV( N ) - function pstrf!(uplo::Char, A::StridedMatrix{$elty}, tol::Real) - chkstride1(A) - n = checksquare(A) - chkuplo(uplo) - piv = similar(A, BlasInt, n) - rank = Vector{BlasInt}(1) - work = Vector{$rtyp}(2n) - info = Ref{BlasInt}() - ccall((@blasfunc($pstrf), liblapack), Void, - (Ptr{UInt8}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, Ptr{BlasInt}, - Ptr{BlasInt}, Ptr{$rtyp}, Ptr{$rtyp}, Ptr{BlasInt}), - &uplo, &n, A, &max(1,stride(A,2)), piv, rank, &tol, work, info) - chkargsok(info[]) - A, piv, rank[1], info[] #Stored in PivotedCholesky - end - end -end - -""" - posv!(uplo, A, B) -> (A, B) - -Finds the solution to `A * X = B` where `A` is a symmetric or Hermitian -positive definite matrix. If `uplo = U` the upper Cholesky decomposition -of `A` is computed. If `uplo = L` the lower Cholesky decomposition of `A` -is computed. `A` is overwritten by its Cholesky decomposition. `B` is -overwritten with the solution `X`. -""" -posv!(uplo::Char, A::StridedMatrix, B::StridedVecOrMat) - -""" - potrf!(uplo, A) - -Computes the Cholesky (upper if `uplo = U`, lower if `uplo = L`) -decomposition of positive-definite matrix `A`. `A` is overwritten and -returned with an info code. -""" -potrf!(uplo::Char, A::StridedMatrix) - -""" - potri!(uplo, A) - -Computes the inverse of positive-definite matrix `A` after calling -`potrf!` to find its (upper if `uplo = U`, lower if `uplo = L`) Cholesky -decomposition. - -`A` is overwritten by its inverse and returned. -""" -potri!(uplo::Char, A::StridedMatrix) - -""" - potrs!(uplo, A, B) - -Finds the solution to `A * X = B` where `A` is a symmetric or Hermitian -positive definite matrix whose Cholesky decomposition was computed by -`potrf!`. If `uplo = U` the upper Cholesky decomposition of `A` was -computed. If `uplo = L` the lower Cholesky decomposition of `A` was -computed. `B` is overwritten with the solution `X`. -""" -potrs!(uplo::Char, A::StridedMatrix, B::StridedVecOrMat) - -""" - pstrf!(uplo, A, tol) -> (A, piv, rank, info) - -Computes the (upper if `uplo = U`, lower if `uplo = L`) pivoted Cholesky -decomposition of positive-definite matrix `A` with a user-set tolerance -`tol`. `A` is overwritten by its Cholesky decomposition. - -Returns `A`, the pivots `piv`, the rank of `A`, and an `info` code. If `info = 0`, -the factorization succeeded. If `info = i > 0 `, then `A` is indefinite or -rank-deficient. -""" -pstrf!(uplo::Char, A::StridedMatrix, tol::Real) - -# (PT) positive-definite, symmetric, tri-diagonal matrices -# Direct solvers for general tridiagonal and symmetric positive-definite tridiagonal -for (ptsv, pttrf, elty, relty) in - ((:dptsv_,:dpttrf_,:Float64,:Float64), - (:sptsv_,:spttrf_,:Float32,:Float32), - (:zptsv_,:zpttrf_,:Complex128,:Float64), - (:cptsv_,:cpttrf_,:Complex64,:Float32)) - @eval begin - # SUBROUTINE DPTSV( N, NRHS, D, E, B, LDB, INFO ) - # .. Scalar Arguments .. - # INTEGER INFO, LDB, N, NRHS - # .. Array Arguments .. - # DOUBLE PRECISION B( LDB, * ), D( * ), E( * ) - function ptsv!(D::StridedVector{$relty}, E::StridedVector{$elty}, B::StridedVecOrMat{$elty}) - chkstride1(B, D, E) - n = length(D) - if length(E) != n - 1 - throw(DimensionMismatch("E has length $(length(E)), but needs $(n - 1)")) - end - if n != size(B,1) - throw(DimensionMismatch("B has first dimension $(size(B,1)) but needs $n")) - end - info = Ref{BlasInt}() - ccall((@blasfunc($ptsv), liblapack), Void, - (Ptr{BlasInt}, Ptr{BlasInt}, Ptr{$relty}, Ptr{$elty}, - Ptr{$elty}, Ptr{BlasInt}, Ptr{BlasInt}), - &n, &size(B,2), D, E, B, &max(1,stride(B,2)), info) - chklapackerror(info[]) - B - end - - # SUBROUTINE DPTTRF( N, D, E, INFO ) - # .. Scalar Arguments .. - # INTEGER INFO, N - # .. Array Arguments .. - # DOUBLE PRECISION D( * ), E( * ) - function pttrf!(D::StridedVector{$relty}, E::StridedVector{$elty}) - chkstride1(D, E) - n = length(D) - if length(E) != n - 1 - throw(DimensionMismatch("E has length $(length(E)), but needs $(n - 1)")) - end - info = Ref{BlasInt}() - ccall((@blasfunc($pttrf), liblapack), Void, - (Ptr{BlasInt}, Ptr{$relty}, Ptr{$elty}, Ptr{BlasInt}), - &n, D, E, info) - chklapackerror(info[]) - D, E - end - end -end - -""" - ptsv!(D, E, B) - -Solves `A * X = B` for positive-definite tridiagonal `A`. `D` is the -diagonal of `A` and `E` is the off-diagonal. `B` is overwritten with the -solution `X` and returned. -""" -ptsv!(D::StridedVector, E::StridedVector, B::StridedVecOrMat) - -""" - pttrf!(D, E) - -Computes the LDLt factorization of a positive-definite tridiagonal matrix -with `D` as diagonal and `E` as off-diagonal. `D` and `E` are overwritten -and returned. -""" -pttrf!(D::StridedVector, E::StridedVector) - -for (pttrs, elty, relty) in - ((:dpttrs_,:Float64,:Float64), - (:spttrs_,:Float32,:Float32)) - @eval begin - # SUBROUTINE DPTTRS( N, NRHS, D, E, B, LDB, INFO ) - # .. Scalar Arguments .. - # INTEGER INFO, LDB, N, NRHS - # .. Array Arguments .. - # DOUBLE PRECISION B( LDB, * ), D( * ), E( * ) - function pttrs!(D::StridedVector{$relty}, E::StridedVector{$elty}, B::StridedVecOrMat{$elty}) - chkstride1(B, D, E) - n = length(D) - if length(E) != n - 1 - throw(DimensionMismatch("E has length $(length(E)), but needs $(n - 1)")) - end - if n != size(B,1) - throw(DimensionMismatch("B has first dimension $(size(B,1)) but needs $n")) - end - info = Ref{BlasInt}() - ccall((@blasfunc($pttrs), liblapack), Void, - (Ptr{BlasInt}, Ptr{BlasInt}, Ptr{$relty}, Ptr{$elty}, - Ptr{$elty}, Ptr{BlasInt}, Ptr{BlasInt}), - &n, &size(B,2), D, E, B, &max(1,stride(B,2)), info) - chklapackerror(info[]) - B - end - end -end - -for (pttrs, elty, relty) in - ((:zpttrs_,:Complex128,:Float64), - (:cpttrs_,:Complex64,:Float32)) - @eval begin - # SUBROUTINE ZPTTRS( UPLO, N, NRHS, D, E, B, LDB, INFO ) - # * .. Scalar Arguments .. - # CHARACTER UPLO - # INTEGER INFO, LDB, N, NRHS - # * .. - # * .. Array Arguments .. - # DOUBLE PRECISION D( * ) - # COMPLEX*16 B( LDB, * ), E( * ) - function pttrs!(uplo::Char, D::StridedVector{$relty}, E::StridedVector{$elty}, B::StridedVecOrMat{$elty}) - chkstride1(B, D, E) - chkuplo(uplo) - n = length(D) - if length(E) != n - 1 - throw(DimensionMismatch("E has length $(length(E)), but needs $(n - 1)")) - end - if n != size(B,1) - throw(DimensionMismatch("B has first dimension $(size(B,1)) but needs $n")) - end - info = Ref{BlasInt}() - ccall((@blasfunc($pttrs), liblapack), Void, - (Ptr{UInt8}, Ptr{BlasInt}, Ptr{BlasInt}, Ptr{$relty}, Ptr{$elty}, - Ptr{$elty}, Ptr{BlasInt}, Ptr{BlasInt}), - &uplo, &n, &size(B,2), D, E, B, &max(1,stride(B,2)), info) - chklapackerror(info[]) - B - end - end -end - -""" - pttrs!(D, E, B) - -Solves `A * X = B` for positive-definite tridiagonal `A` with diagonal -`D` and off-diagonal `E` after computing `A`'s LDLt factorization using -`pttrf!`. `B` is overwritten with the solution `X`. -""" -pttrs!(D::StridedVector, E::StridedVector, B::StridedVecOrMat) - -## (TR) triangular matrices: solver and inverse -for (trtri, trtrs, elty) in - ((:dtrtri_,:dtrtrs_,:Float64), - (:strtri_,:strtrs_,:Float32), - (:ztrtri_,:ztrtrs_,:Complex128), - (:ctrtri_,:ctrtrs_,:Complex64)) - @eval begin - # SUBROUTINE DTRTRI( UPLO, DIAG, N, A, LDA, INFO ) - #* .. Scalar Arguments .. - # CHARACTER DIAG, UPLO - # INTEGER INFO, LDA, N - # .. Array Arguments .. - # DOUBLE PRECISION A( LDA, * ) - function trtri!(uplo::Char, diag::Char, A::StridedMatrix{$elty}) - chkstride1(A) - n = checksquare(A) - chkuplo(uplo) - chkdiag(diag) - lda = max(1,stride(A, 2)) - info = Ref{BlasInt}() - ccall((@blasfunc($trtri), liblapack), Void, - (Ptr{UInt8}, Ptr{UInt8}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, - Ptr{BlasInt}), - &uplo, &diag, &n, A, &lda, info) - chklapackerror(info[]) - A - end - - # SUBROUTINE DTRTRS( UPLO, TRANS, DIAG, N, NRHS, A, LDA, B, LDB, INFO ) - # * .. Scalar Arguments .. - # CHARACTER DIAG, TRANS, UPLO - # INTEGER INFO, LDA, LDB, N, NRHS - # * .. Array Arguments .. - # DOUBLE PRECISION A( LDA, * ), B( LDB, * ) - function trtrs!(uplo::Char, trans::Char, diag::Char, - A::StridedMatrix{$elty}, B::StridedVecOrMat{$elty}) - chktrans(trans) - chkdiag(diag) - chkstride1(A) - n = checksquare(A) - chkuplo(uplo) - if n != size(B,1) - throw(DimensionMismatch("B has first dimension $(size(B,1)) but needs $n")) - end - info = Ref{BlasInt}() - ccall((@blasfunc($trtrs), liblapack), Void, - (Ptr{UInt8}, Ptr{UInt8}, Ptr{UInt8}, Ptr{BlasInt}, Ptr{BlasInt}, - Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, Ptr{BlasInt}), - &uplo, &trans, &diag, &n, &size(B,2), A, &max(1,stride(A,2)), - B, &max(1,stride(B,2)), info) - chklapackerror(info[]) - B - end - end -end - -""" - trtri!(uplo, diag, A) - -Finds the inverse of (upper if `uplo = U`, lower if `uplo = L`) -triangular matrix `A`. If `diag = N`, `A` has non-unit diagonal elements. -If `diag = U`, all diagonal elements of `A` are one. `A` is overwritten -with its inverse. -""" -trtri!(uplo::Char, diag::Char, A::StridedMatrix) - -""" - trtrs!(uplo, trans, diag, A, B) - -Solves `A * X = B` (`trans = N`), `A.' * X = B` (`trans = T`), or -`A' * X = B` (`trans = C`) for (upper if `uplo = U`, lower if `uplo = L`) -triangular matrix `A`. If `diag = N`, `A` has non-unit diagonal elements. -If `diag = U`, all diagonal elements of `A` are one. `B` is overwritten -with the solution `X`. -""" -trtrs!(uplo::Char, trans::Char, diag::Char, A::StridedMatrix, B::StridedVecOrMat) - -#Eigenvector computation and condition number estimation -for (trcon, trevc, trrfs, elty) in - ((:dtrcon_,:dtrevc_,:dtrrfs_,:Float64), - (:strcon_,:strevc_,:strrfs_,:Float32)) - @eval begin - # SUBROUTINE DTRCON( NORM, UPLO, DIAG, N, A, LDA, RCOND, WORK, - # IWORK, INFO ) - # .. Scalar Arguments .. - # CHARACTER DIAG, NORM, UPLO - # INTEGER INFO, LDA, N - # DOUBLE PRECISION RCOND - # .. Array Arguments .. - # INTEGER IWORK( * ) - # DOUBLE PRECISION A( LDA, * ), WORK( * ) - function trcon!(norm::Char, uplo::Char, diag::Char, A::StridedMatrix{$elty}) - chkstride1(A) - chkdiag(diag) - n = checksquare(A) - chkuplo(uplo) - rcond = Vector{$elty}(1) - work = Vector{$elty}(3n) - iwork = Vector{BlasInt}(n) - info = Ref{BlasInt}() - ccall((@blasfunc($trcon), liblapack), Void, - (Ptr{UInt8}, Ptr{UInt8}, Ptr{UInt8}, Ptr{BlasInt}, - Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, Ptr{$elty}, Ptr{BlasInt}, Ptr{BlasInt}), - &norm, &uplo, &diag, &n, - A, &max(1,stride(A,2)), rcond, work, iwork, info) - chklapackerror(info[]) - rcond[1] - end - - # SUBROUTINE DTREVC( SIDE, HOWMNY, SELECT, N, T, LDT, VL, LDVL, VR, - # LDVR, MM, M, WORK, INFO ) - # - # .. Scalar Arguments .. - # CHARACTER HOWMNY, SIDE - # INTEGER INFO, LDT, LDVL, LDVR, M, MM, N - # .. - # .. Array Arguments .. - # LOGICAL SELECT( * ) - # DOUBLE PRECISION T( LDT, * ), VL( LDVL, * ), VR( LDVR, * ), - #$ WORK( * ) - function trevc!(side::Char, howmny::Char, select::StridedVector{BlasInt}, T::StridedMatrix{$elty}, - VL::StridedMatrix{$elty} = similar(T), - VR::StridedMatrix{$elty} = similar(T)) - # Extract - if side ∉ ['L','R','B'] - throw(ArgumentError("side argument must be 'L' (left eigenvectors), 'R' (right eigenvectors), or 'B' (both), got $side")) - end - n, mm = checksquare(T), size(VL, 2) - ldt, ldvl, ldvr = stride(T, 2), stride(VL, 2), stride(VR, 2) - - # Check - chkstride1(T, select) - - # Allocate - m = Ref{BlasInt}() - work = Vector{$elty}(3n) - info = Ref{BlasInt}() - - ccall((@blasfunc($trevc), liblapack), Void, - (Ptr{UInt8}, Ptr{UInt8}, Ptr{BlasInt}, Ptr{BlasInt}, - Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, - Ptr{$elty}, Ptr{BlasInt},Ptr{BlasInt}, Ptr{BlasInt}, - Ptr{$elty}, Ptr{BlasInt}), - &side, &howmny, select, &n, - T, &ldt, VL, &ldvl, - VR, &ldvr, &mm, m, - work, info) - chklapackerror(info[]) - - #Decide what exactly to return - if howmny == 'S' #compute selected eigenvectors - if side == 'L' #left eigenvectors only - return select, VL[:,1:m[]] - elseif side == 'R' #right eigenvectors only - return select, VR[:,1:m[]] - else #side == 'B' #both eigenvectors - return select, VL[:,1:m[]], VR[:,1:m[]] - end - else #compute all eigenvectors - if side == 'L' #left eigenvectors only - return VL[:,1:m[]] - elseif side == 'R' #right eigenvectors only - return VR[:,1:m[]] - else #side == 'B' #both eigenvectors - return VL[:,1:m[]], VR[:,1:m[]] - end - end - end - - # SUBROUTINE DTRRFS( UPLO, TRANS, DIAG, N, NRHS, A, LDA, B, LDB, X, - # LDX, FERR, BERR, WORK, IWORK, INFO ) - # .. Scalar Arguments .. - # CHARACTER DIAG, TRANS, UPLO - # INTEGER INFO, LDA, LDB, LDX, N, NRHS - # .. Array Arguments .. - # INTEGER IWORK( * ) - # DOUBLE PRECISION A( LDA, * ), B( LDB, * ), BERR( * ), FERR( * ), - #$ WORK( * ), X( LDX, * ) - function trrfs!(uplo::Char, trans::Char, diag::Char, - A::StridedMatrix{$elty}, B::StridedVecOrMat{$elty}, X::StridedVecOrMat{$elty}, - Ferr::StridedVector{$elty} = similar(B, $elty, size(B,2)), - Berr::StridedVector{$elty} = similar(B, $elty, size(B,2))) - chktrans(trans) - chkuplo(uplo) - chkdiag(diag) - n = size(A,2) - nrhs = size(B,2) - if nrhs != size(X,2) - throw(DimensionMismatch("second dimensions of B, $nrhs, and X, $(size(X,2)), must match")) - end - work = Vector{$elty}(3n) - iwork = Vector{BlasInt}(n) - info = Ref{BlasInt}() - ccall((@blasfunc($trrfs), liblapack), Void, - (Ptr{UInt8}, Ptr{UInt8}, Ptr{UInt8}, Ptr{BlasInt}, - Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, - Ptr{$elty}, Ptr{$elty}, Ptr{$elty}, Ptr{BlasInt}, Ptr{BlasInt}), - &uplo, &trans, &diag, &n, - &nrhs, A, &max(1,stride(A,2)), B, &max(1,stride(B,2)), X, &max(1,stride(X,2)), - Ferr, Berr, work, iwork, info) - chklapackerror(info[]) - Ferr, Berr - end - end -end - -for (trcon, trevc, trrfs, elty, relty) in - ((:ztrcon_,:ztrevc_,:ztrrfs_,:Complex128,:Float64), - (:ctrcon_,:ctrevc_,:ctrrfs_,:Complex64, :Float32)) - @eval begin - # SUBROUTINE ZTRCON( NORM, UPLO, DIAG, N, A, LDA, RCOND, WORK, - # RWORK, INFO ) - # .. Scalar Arguments .. - # CHARACTER DIAG, NORM, UPLO - # INTEGER INFO, LDA, N - # DOUBLE PRECISION RCOND - # .. Array Arguments .. - # DOUBLE PRECISION RWORK( * ) - # COMPLEX*16 A( LDA, * ), WORK( * ) - function trcon!(norm::Char, uplo::Char, diag::Char, A::StridedMatrix{$elty}) - chkstride1(A) - n = checksquare(A) - chkuplo(uplo) - chkdiag(diag) - rcond = Vector{$relty}(1) - work = Vector{$elty}(2n) - rwork = Vector{$relty}(n) - info = Ref{BlasInt}() - ccall((@blasfunc($trcon), liblapack), Void, - (Ptr{UInt8}, Ptr{UInt8}, Ptr{UInt8}, Ptr{BlasInt}, - Ptr{$elty}, Ptr{BlasInt}, Ptr{$relty}, Ptr{$elty}, Ptr{$relty}, Ptr{BlasInt}), - &norm, &uplo, &diag, &n, - A, &max(1,stride(A,2)), rcond, work, rwork, info) - chklapackerror(info[]) - rcond[1] - end - - # SUBROUTINE ZTREVC( SIDE, HOWMNY, SELECT, N, T, LDT, VL, LDVL, VR, - # LDVR, MM, M, WORK, RWORK, INFO ) - # - # .. Scalar Arguments .. - # CHARACTER HOWMNY, SIDE - # INTEGER INFO, LDT, LDVL, LDVR, M, MM, N - # .. - # .. Array Arguments .. - # LOGICAL SELECT( * ) - # DOUBLE PRECISION RWORK( * ) - # COMPLEX*16 T( LDT, * ), VL( LDVL, * ), VR( LDVR, * ), - #$ WORK( * ) - function trevc!(side::Char, howmny::Char, select::StridedVector{BlasInt}, T::StridedMatrix{$elty}, - VL::StridedMatrix{$elty} = similar(T), - VR::StridedMatrix{$elty} = similar(T)) - # Extract - n, mm = checksquare(T), size(VL, 2) - ldt, ldvl, ldvr = stride(T, 2), stride(VL, 2), stride(VR, 2) - - # Check - chkstride1(T, select) - if side ∉ ['L','R','B'] - throw(ArgumentError("side argument must be 'L' (left eigenvectors), 'R' (right eigenvectors), or 'B' (both), got $side")) - end - - # Allocate - m = Ref{BlasInt}() - work = Vector{$elty}(2n) - rwork = Vector{$relty}(n) - info = Ref{BlasInt}() - ccall((@blasfunc($trevc), liblapack), Void, - (Ptr{UInt8}, Ptr{UInt8}, Ptr{BlasInt}, Ptr{BlasInt}, - Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, - Ptr{$elty}, Ptr{BlasInt}, Ptr{BlasInt}, Ptr{BlasInt}, - Ptr{$elty}, Ptr{$relty}, Ptr{BlasInt}), - &side, &howmny, select, &n, - T, &ldt, VL, &ldvl, - VR, &ldvr, &mm, m, - work, rwork, info) - chklapackerror(info[]) - - #Decide what exactly to return - if howmny == 'S' #compute selected eigenvectors - if side == 'L' #left eigenvectors only - return select, VL[:,1:m[]] - elseif side == 'R' #right eigenvectors only - return select, VR[:,1:m[]] - else #side=='B' #both eigenvectors - return select, VL[:,1:m[]], VR[:,1:m[]] - end - else #compute all eigenvectors - if side == 'L' #left eigenvectors only - return VL[:,1:m[]] - elseif side == 'R' #right eigenvectors only - return VR[:,1:m[]] - else #side=='B' #both eigenvectors - return VL[:,1:m[]], VR[:,1:m[]] - end - end - end - - # SUBROUTINE ZTRRFS( UPLO, TRANS, DIAG, N, NRHS, A, LDA, B, LDB, X, - # LDX, FERR, BERR, WORK, IWORK, INFO ) - # .. Scalar Arguments .. - # CHARACTER DIAG, TRANS, UPLO - # INTEGER INFO, LDA, LDB, LDX, N, NRHS - # .. Array Arguments .. - # INTEGER IWORK( * ) - # DOUBLE PRECISION A( LDA, * ), B( LDB, * ), BERR( * ), FERR( * ), - #$ WORK( * ), X( LDX, * ) - function trrfs!(uplo::Char, trans::Char, diag::Char, - A::StridedMatrix{$elty}, B::StridedVecOrMat{$elty}, X::StridedVecOrMat{$elty}, - Ferr::StridedVector{$relty} = similar(B, $relty, size(B,2)), - Berr::StridedVector{$relty} = similar(B, $relty, size(B,2))) - chktrans(trans) - chkuplo(uplo) - chkdiag(diag) - n = size(A,2) - nrhs = size(B,2) - if nrhs != size(X,2) - throw(DimensionMismatch("second dimensions of B, $nrhs, and X, $(size(X,2)), must match")) - end - work = Vector{$elty}(2n) - rwork = Vector{$relty}(n) - info = Ref{BlasInt}() - ccall((@blasfunc($trrfs), liblapack), Void, - (Ptr{UInt8}, Ptr{UInt8}, Ptr{UInt8}, Ptr{BlasInt}, - Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, - Ptr{$relty}, Ptr{$relty}, Ptr{$elty}, Ptr{$relty}, Ptr{BlasInt}), - &uplo, &trans, &diag, &n, - &nrhs, A, &max(1,stride(A,2)), B, &max(1,stride(B,2)), X, &max(1,stride(X,2)), - Ferr, Berr, work, rwork, info) - chklapackerror(info[]) - Ferr, Berr - end - end -end - -""" - trcon!(norm, uplo, diag, A) - -Finds the reciprocal condition number of (upper if `uplo = U`, lower if -`uplo = L`) triangular matrix `A`. If `diag = N`, `A` has non-unit -diagonal elements. If `diag = U`, all diagonal elements of `A` are one. -If `norm = I`, the condition number is found in the infinity norm. If -`norm = O` or `1`, the condition number is found in the one norm. -""" -trcon!(norm::Char, uplo::Char, diag::Char, A::StridedMatrix) - -""" - trevc!(side, howmny, select, T, VL = similar(T), VR = similar(T)) - -Finds the eigensystem of an upper triangular matrix `T`. If `side = R`, -the right eigenvectors are computed. If `side = L`, the left -eigenvectors are computed. If `side = B`, both sets are computed. If -`howmny = A`, all eigenvectors are found. If `howmny = B`, all -eigenvectors are found and backtransformed using `VL` and `VR`. If -`howmny = S`, only the eigenvectors corresponding to the values in -`select` are computed. -""" -trevc!(side::Char, howmny::Char, select::StridedVector{BlasInt}, T::StridedMatrix, - VL::StridedMatrix = similar(T), VR::StridedMatrix = similar(T)) - -""" - trrfs!(uplo, trans, diag, A, B, X, Ferr, Berr) -> (Ferr, Berr) - -Estimates the error in the solution to `A * X = B` (`trans = N`), -`A.' * X = B` (`trans = T`), `A' * X = B` (`trans = C`) for `side = L`, -or the equivalent equations a right-handed `side = R` `X * A` after -computing `X` using `trtrs!`. If `uplo = U`, `A` is upper triangular. -If `uplo = L`, `A` is lower triangular. If `diag = N`, `A` has non-unit -diagonal elements. If `diag = U`, all diagonal elements of `A` are one. -`Ferr` and `Berr` are optional inputs. `Ferr` is the forward error and -`Berr` is the backward error, each component-wise. -""" -trrfs!(uplo::Char, trans::Char, diag::Char, A::StridedMatrix, B::StridedVecOrMat, - X::StridedVecOrMat, Ferr::StridedVector, Berr::StridedVector) - -## (ST) Symmetric tridiagonal - eigendecomposition -for (stev, stebz, stegr, stein, elty) in - ((:dstev_,:dstebz_,:dstegr_,:dstein_,:Float64), - (:sstev_,:sstebz_,:sstegr_,:sstein_,:Float32) -# , (:zstev_,:Complex128) Need to rewrite for ZHEEV, rwork, etc. -# , (:cstev_,:Complex64) - ) - @eval begin - function stev!(job::Char, dv::StridedVector{$elty}, ev::StridedVector{$elty}) - chkstride1(dv, ev) - n = length(dv) - if length(ev) != n - 1 - throw(DimensionMismatch("ev has length $(length(ev)) but needs one less than dv's length, $n)")) - end - Zmat = similar(dv, $elty, (n, job != 'N' ? n : 0)) - work = Vector{$elty}(max(1, 2n-2)) - info = Ref{BlasInt}() - ccall((@blasfunc($stev), liblapack), Void, - (Ptr{UInt8}, Ptr{BlasInt}, Ptr{$elty}, Ptr{$elty}, Ptr{$elty}, - Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}), - &job, &n, dv, ev, Zmat, &n, work, info) - chklapackerror(info[]) - dv, Zmat - end - - #* DSTEBZ computes the eigenvalues of a symmetric tridiagonal - #* matrix T. The user may ask for all eigenvalues, all eigenvalues - #* in the half-open interval (VL, VU], or the IL-th through IU-th - #* eigenvalues. - function stebz!(range::Char, order::Char, vl::$elty, vu::$elty, il::Integer, iu::Integer, abstol::Real, dv::StridedVector{$elty}, ev::StridedVector{$elty}) - chkstride1(dv, ev) - n = length(dv) - if length(ev) != n - 1 - throw(DimensionMismatch("ev has length $(length(ev)) but needs one less than dv's length, $n)")) - end - m = Ref{BlasInt}() - nsplit = Vector{BlasInt}(1) - w = similar(dv, $elty, n) - tmp = 0.0 - iblock = similar(dv, BlasInt,n) - isplit = similar(dv, BlasInt,n) - work = Vector{$elty}(4*n) - iwork = Vector{BlasInt}(3*n) - info = Ref{BlasInt}() - ccall((@blasfunc($stebz), liblapack), Void, - (Ptr{UInt8}, Ptr{UInt8}, Ptr{BlasInt}, Ptr{$elty}, - Ptr{$elty}, Ptr{BlasInt}, Ptr{BlasInt}, Ptr{$elty}, - Ptr{$elty}, Ptr{$elty}, Ptr{BlasInt}, Ptr{BlasInt}, - Ptr{$elty}, Ptr{BlasInt}, Ptr{BlasInt}, Ptr{$elty}, - Ptr{BlasInt}, Ptr{BlasInt}), - &range, &order, &n, &vl, - &vu, &il, &iu, &abstol, - dv, ev, m, nsplit, - w, iblock, isplit, work, - iwork, info) - chklapackerror(info[]) - w[1:m[]], iblock[1:m[]], isplit[1:nsplit[1]] - end - - function stegr!(jobz::Char, range::Char, dv::StridedVector{$elty}, ev::StridedVector{$elty}, vl::Real, vu::Real, il::Integer, iu::Integer) - chkstride1(dv, ev) - n = length(dv) - if length(ev) != n - 1 - throw(DimensionMismatch("ev has length $(length(ev)) but needs one less than dv's length, $n)")) - end - eev = [ev; zero($elty)] - abstol = Vector{$elty}(1) - m = Ref{BlasInt}() - w = similar(dv, $elty, n) - ldz = jobz == 'N' ? 1 : n - Z = similar(dv, $elty, ldz, range == 'I' ? iu-il+1 : n) - isuppz = similar(dv, BlasInt, 2*size(Z, 2)) - work = Vector{$elty}(1) - lwork = BlasInt(-1) - iwork = Vector{BlasInt}(1) - liwork = BlasInt(-1) - info = Ref{BlasInt}() - for i = 1:2 - ccall((@blasfunc($stegr), liblapack), Void, - (Ptr{UInt8}, Ptr{UInt8}, Ptr{BlasInt}, Ptr{$elty}, - Ptr{$elty}, Ptr{$elty}, Ptr{$elty}, Ptr{BlasInt}, - Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, - Ptr{$elty}, Ptr{BlasInt}, Ptr{BlasInt}, Ptr{$elty}, - Ptr{BlasInt}, Ptr{BlasInt}, Ptr{BlasInt}, Ptr{BlasInt}), - &jobz, &range, &n, dv, - eev, &vl, &vu, &il, - &iu, abstol, m, w, - Z, &ldz, isuppz, work, - &lwork, iwork, &liwork, info) - chklapackerror(info[]) - if i == 1 - lwork = BlasInt(work[1]) - work = Vector{$elty}(lwork) - liwork = iwork[1] - iwork = Vector{BlasInt}(liwork) - end - end - m[] == length(w) ? w : w[1:m[]], m[] == size(Z, 2) ? Z : Z[:,1:m[]] - end - - function stein!(dv::StridedVector{$elty}, ev_in::StridedVector{$elty}, w_in::StridedVector{$elty}, iblock_in::StridedVector{BlasInt}, isplit_in::StridedVector{BlasInt}) - chkstride1(dv, ev_in, w_in, iblock_in, isplit_in) - n = length(dv) - if length(ev_in) != n - 1 - throw(DimensionMismatch("ev_in has length $(length(ev_in)) but needs one less than dv's length, $n)")) - end - ev = [ev_in; zeros($elty,1)] - ldz = n #Leading dimension - #Number of eigenvalues to find - if !(1 <= length(w_in) <= n) - throw(DimensionMismatch("w_in has length $(length(w_in)), but needs to be between 1 and $n")) - end - m = length(w_in) - #If iblock and isplit are invalid input, assume worst-case block paritioning, - # i.e. set the block scheme to be the entire matrix - iblock = similar(dv, BlasInt,n) - isplit = similar(dv, BlasInt,n) - w = similar(dv, $elty,n) - if length(iblock_in) < m #Not enough block specifications - iblock[1:m] = ones(BlasInt, m) - w[1:m] = sort(w_in) - else - iblock[1:m] = iblock_in - w[1:m] = w_in #Assume user has sorted the eigenvalues properly - end - if length(isplit_in) < 1 #Not enough block specifications - isplit[1] = n - else - isplit[1:length(isplit_in)] = isplit_in - end - z = similar(dv, $elty,(n,m)) - work = Vector{$elty}(5*n) - iwork = Vector{BlasInt}(n) - ifail = Vector{BlasInt}(m) - info = Ref{BlasInt}() - ccall((@blasfunc($stein), liblapack), Void, - (Ptr{BlasInt}, Ptr{$elty}, Ptr{$elty}, Ptr{BlasInt}, - Ptr{$elty}, Ptr{BlasInt}, Ptr{BlasInt}, Ptr{$elty}, - Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, Ptr{BlasInt}, - Ptr{BlasInt}), - &n, dv, ev, &m, w, iblock, isplit, z, &ldz, work, iwork, ifail, info) - chklapackerror(info[]) - if any(ifail .!= 0) - # TODO: better error message / type - error("failed to converge eigenvectors:\n$(nonzeros(ifail))") - end - z - end - end -end -stegr!(jobz::Char, dv::StridedVector, ev::StridedVector) = stegr!(jobz, 'A', dv, ev, 0.0, 0.0, 0, 0) - -# Allow user to skip specification of iblock and isplit -stein!(dv::StridedVector, ev::StridedVector, w_in::StridedVector)=stein!(dv, ev, w_in, zeros(BlasInt,0), zeros(BlasInt,0)) -# Allow user to specify just one eigenvector to get in stein! -stein!(dv::StridedVector, ev::StridedVector, eval::Real)=stein!(dv, ev, [eval], zeros(BlasInt,0), zeros(BlasInt,0)) - -""" - stev!(job, dv, ev) -> (dv, Zmat) - -Computes the eigensystem for a symmetric tridiagonal matrix with `dv` as -diagonal and `ev` as off-diagonal. If `job = N` only the eigenvalues are -found and returned in `dv`. If `job = V` then the eigenvectors are also found -and returned in `Zmat`. -""" -stev!(job::Char, dv::StridedVector, ev::StridedVector) - -""" - stebz!(range, order, vl, vu, il, iu, abstol, dv, ev) -> (dv, iblock, isplit) - -Computes the eigenvalues for a symmetric tridiagonal matrix with `dv` as -diagonal and `ev` as off-diagonal. If `range = A`, all the eigenvalues -are found. If `range = V`, the eigenvalues in the half-open interval -`(vl, vu]` are found. If `range = I`, the eigenvalues with indices between -`il` and `iu` are found. If `order = B`, eigvalues are ordered within a -block. If `order = E`, they are ordered across all the blocks. -`abstol` can be set as a tolerance for convergence. -""" -stebz!(range::Char, order::Char, vl, vu, il::Integer, iu::Integer, abstol::Real, dv::StridedVector, ev::StridedVector) - -""" - stegr!(jobz, range, dv, ev, vl, vu, il, iu) -> (w, Z) - -Computes the eigenvalues (`jobz = N`) or eigenvalues and eigenvectors -(`jobz = V`) for a symmetric tridiagonal matrix with `dv` as diagonal -and `ev` as off-diagonal. If `range = A`, all the eigenvalues -are found. If `range = V`, the eigenvalues in the half-open interval -`(vl, vu]` are found. If `range = I`, the eigenvalues with indices between -`il` and `iu` are found. The eigenvalues are returned in `w` and the eigenvectors -in `Z`. -""" -stegr!(jobz::Char, range::Char, dv::StridedVector, ev::StridedVector, vl::Real, vu::Real, il::Integer, iu::Integer) - -""" - stein!(dv, ev_in, w_in, iblock_in, isplit_in) - -Computes the eigenvectors for a symmetric tridiagonal matrix with `dv` -as diagonal and `ev_in` as off-diagonal. `w_in` specifies the input -eigenvalues for which to find corresponding eigenvectors. `iblock_in` -specifies the submatrices corresponding to the eigenvalues in `w_in`. -`isplit_in` specifies the splitting points between the submatrix blocks. -""" -stein!(dv::StridedVector, ev_in::StridedVector, w_in::StridedVector, iblock_in::StridedVector{BlasInt}, isplit_in::StridedVector{BlasInt}) - -## (SY) symmetric real matrices - Bunch-Kaufman decomposition, -## solvers (direct and factored) and inverse. -for (syconv, sysv, sytrf, sytri, sytrs, elty) in - ((:dsyconv_,:dsysv_,:dsytrf_,:dsytri_,:dsytrs_,:Float64), - (:ssyconv_,:ssysv_,:ssytrf_,:ssytri_,:ssytrs_,:Float32)) - @eval begin - # SUBROUTINE DSYCONV( UPLO, WAY, N, A, LDA, IPIV, WORK, INFO ) - # * .. Scalar Arguments .. - # CHARACTER UPLO, WAY - # INTEGER INFO, LDA, N - # * .. Array Arguments .. - # INTEGER IPIV( * ) - # DOUBLE PRECISION A( LDA, * ), WORK( * ) - function syconv!(uplo::Char, A::StridedMatrix{$elty}, ipiv::StridedVector{BlasInt}) - chkstride1(A, ipiv) - n = checksquare(A) - chkuplo(uplo) - work = Vector{$elty}(n) - info = Ref{BlasInt}() - ccall((@blasfunc($syconv), liblapack), Void, - (Ptr{UInt8}, Ptr{UInt8}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, - Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}), - &uplo, &'C', &n, A, &max(1,stride(A,2)), ipiv, work, info) - chklapackerror(info[]) - A, work - end - - # SUBROUTINE DSYSV( UPLO, N, NRHS, A, LDA, IPIV, B, LDB, WORK, - # LWORK, INFO ) - # .. Scalar Arguments .. - # CHARACTER UPLO - # INTEGER INFO, LDA, LDB, LWORK, N, NRHS - # .. Array Arguments .. - # INTEGER IPIV( * ) - # DOUBLE PRECISION A( LDA, * ), B( LDB, * ), WORK( * ) - function sysv!(uplo::Char, A::StridedMatrix{$elty}, B::StridedVecOrMat{$elty}) - chkstride1(A,B) - n = checksquare(A) - chkuplo(uplo) - if n != size(B,1) - throw(DimensionMismatch("B has first dimension $(size(B,1)), but needs $n")) - end - ipiv = similar(A, BlasInt, n) - work = Vector{$elty}(1) - lwork = BlasInt(-1) - info = Ref{BlasInt}() - for i = 1:2 - ccall((@blasfunc($sysv), liblapack), Void, - (Ptr{UInt8}, Ptr{BlasInt}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, Ptr{BlasInt}, - Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, Ptr{BlasInt}), - &uplo, &n, &size(B,2), A, &max(1,stride(A,2)), ipiv, B, &max(1,stride(B,2)), - work, &lwork, info) - chkargsok(info[]) - chknonsingular(info[]) - if i == 1 - lwork = BlasInt(real(work[1])) - work = Vector{$elty}(lwork) - end - end - B, A, ipiv - end - - # SUBROUTINE DSYTRF( UPLO, N, A, LDA, IPIV, WORK, LWORK, INFO ) - # * .. Scalar Arguments .. - # CHARACTER UPLO - # INTEGER INFO, LDA, LWORK, N - # * .. Array Arguments .. - # INTEGER IPIV( * ) - # DOUBLE PRECISION A( LDA, * ), WORK( * ) - function sytrf!(uplo::Char, A::StridedMatrix{$elty}) - chkstride1(A) - n = checksquare(A) - chkuplo(uplo) - ipiv = similar(A, BlasInt, n) - if n == 0 - return A, ipiv, zero(BlasInt) - end - work = Vector{$elty}(1) - lwork = BlasInt(-1) - info = Ref{BlasInt}() - for i = 1:2 - ccall((@blasfunc($sytrf), liblapack), Void, - (Ptr{UInt8}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, - Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, Ptr{BlasInt}), - &uplo, &n, A, &stride(A,2), ipiv, work, &lwork, info) - chkargsok(info[]) - if i == 1 - lwork = BlasInt(real(work[1])) - work = Vector{$elty}(lwork) - end - end - return A, ipiv, info[] - end - - # SUBROUTINE DSYTRI2( UPLO, N, A, LDA, IPIV, WORK, LWORK, INFO ) - # * .. Scalar Arguments .. - # CHARACTER UPLO - # INTEGER INFO, LDA, LWORK, N - # * .. Array Arguments .. - # INTEGER IPIV( * ) - # DOUBLE PRECISION A( LDA, * ), WORK( * ) -# function sytri!(uplo::Char, A::StridedMatrix{$elty}, ipiv::Vector{BlasInt}) -# chkstride1(A) -# n = checksquare(A) -# chkuplo(uplo) -# work = Vector{$elty}(1) -# lwork = BlasInt(-1) -# info = Ref{BlasInt}() -# for i in 1:2 -# ccall((@blasfunc($sytri), liblapack), Void, -# (Ptr{UInt8}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, -# Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, Ptr{BlasInt}), -# &uplo, &n, A, &max(1,stride(A,2)), ipiv, work, &lwork, info) -# @assertargsok -# chknonsingular(info[]) -# if lwork < 0 -# lwork = BlasInt(real(work[1])) -# work = Vector{$elty}(lwork) -# end -# end -# A -# end - - # SUBROUTINE DSYTRI( UPLO, N, A, LDA, IPIV, WORK, INFO ) - # .. Scalar Arguments .. - # CHARACTER UPLO - # INTEGER INFO, LDA, N - # .. Array Arguments .. - # INTEGER IPIV( * ) - # DOUBLE PRECISION A( LDA, * ), WORK( * ) - function sytri!(uplo::Char, A::StridedMatrix{$elty}, ipiv::StridedVector{BlasInt}) - chkstride1(A, ipiv) - n = checksquare(A) - chkuplo(uplo) - work = Vector{$elty}(n) - info = Ref{BlasInt}() - ccall((@blasfunc($sytri), liblapack), Void, - (Ptr{UInt8}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, - Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}), - &uplo, &n, A, &max(1,stride(A,2)), ipiv, work, info) - chkargsok(info[]) - chknonsingular(info[]) - A - end - - # SUBROUTINE DSYTRS( UPLO, N, NRHS, A, LDA, IPIV, B, LDB, INFO ) - # - # .. Scalar Arguments .. - # CHARACTER UPLO - # INTEGER INFO, LDA, LDB, N, NRHS - # .. Array Arguments .. - # INTEGER IPIV( * ) - # DOUBLE PRECISION A( LDA, * ), B( LDB, * ) - function sytrs!(uplo::Char, A::StridedMatrix{$elty}, - ipiv::StridedVector{BlasInt}, B::StridedVecOrMat{$elty}) - chkstride1(A,B,ipiv) - n = checksquare(A) - chkuplo(uplo) - if n != size(B,1) - throw(DimensionMismatch("B has first dimension $(size(B,1)), but needs $n")) - end - info = Ref{BlasInt}() - ccall((@blasfunc($sytrs), liblapack), Void, - (Ptr{UInt8}, Ptr{BlasInt}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, - Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, Ptr{BlasInt}), - &uplo, &n, &size(B,2), A, &max(1,stride(A,2)), ipiv, B, &max(1,stride(B,2)), info) - chklapackerror(info[]) - B - end - end -end - -# Rook-pivoting variants of symmetric-matrix algorithms -for (sysv, sytrf, sytri, sytrs, elty) in - ((:dsysv_rook_,:dsytrf_rook_,:dsytri_rook_,:dsytrs_rook_,:Float64), - (:ssysv_rook_,:ssytrf_rook_,:ssytri_rook_,:ssytrs_rook_,:Float32)) - @eval begin - # SUBROUTINE DSYSV_ROOK(UPLO, N, NRHS, A, LDA, IPIV, B, LDB, WORK, - # LWORK, INFO ) - # .. Scalar Arguments .. - # CHARACTER UPLO - # INTEGER INFO, LDA, LDB, LWORK, N, NRHS - # .. Array Arguments .. - # INTEGER IPIV( * ) - # DOUBLE PRECISION A( LDA, * ), B( LDB, * ), WORK( * ) - function sysv_rook!(uplo::Char, A::StridedMatrix{$elty}, B::StridedVecOrMat{$elty}) - chkstride1(A,B) - n = checksquare(A) - chkuplo(uplo) - if n != size(B,1) - throw(DimensionMismatch("B has first dimension $(size(B,1)), but needs $n")) - end - ipiv = similar(A, BlasInt, n) - work = Vector{$elty}(1) - lwork = BlasInt(-1) - info = Ref{BlasInt}() - for i = 1:2 - ccall((@blasfunc($sysv), liblapack), Void, - (Ptr{UInt8}, Ptr{BlasInt}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, Ptr{BlasInt}, - Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, Ptr{BlasInt}), - &uplo, &n, &size(B,2), A, &max(1,stride(A,2)), ipiv, B, &max(1,stride(B,2)), - work, &lwork, info) - chkargsok(info[]) - chknonsingular(info[]) - if i == 1 - lwork = BlasInt(real(work[1])) - work = Vector{$elty}(lwork) - end - end - B, A, ipiv - end - - # SUBROUTINE DSYTRF_ROOK(UPLO, N, A, LDA, IPIV, WORK, LWORK, INFO ) - # * .. Scalar Arguments .. - # CHARACTER UPLO - # INTEGER INFO, LDA, LWORK, N - # * .. Array Arguments .. - # INTEGER IPIV( * ) - # DOUBLE PRECISION A( LDA, * ), WORK( * ) - function sytrf_rook!(uplo::Char, A::StridedMatrix{$elty}) - chkstride1(A) - n = checksquare(A) - chkuplo(uplo) - ipiv = similar(A, BlasInt, n) - if n == 0 - return A, ipiv, zero(BlasInt) - end - work = Vector{$elty}(1) - lwork = BlasInt(-1) - info = Ref{BlasInt}() - for i = 1:2 - ccall((@blasfunc($sytrf), liblapack), Void, - (Ptr{UInt8}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, - Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, Ptr{BlasInt}), - &uplo, &n, A, &stride(A,2), ipiv, work, &lwork, info) - chkargsok(info[]) - if i == 1 - lwork = BlasInt(real(work[1])) - work = Vector{$elty}(lwork) - end - end - return A, ipiv, info[] - end - - # SUBROUTINE DSYTRI_ROOK( UPLO, N, A, LDA, IPIV, WORK, INFO ) - # .. Scalar Arguments .. - # CHARACTER UPLO - # INTEGER INFO, LDA, N - # .. Array Arguments .. - # INTEGER IPIV( * ) - # DOUBLE PRECISION A( LDA, * ), WORK( * ) - function sytri_rook!(uplo::Char, A::StridedMatrix{$elty}, ipiv::StridedVector{BlasInt}) - chkstride1(A, ipiv) - n = checksquare(A) - chkuplo(uplo) - work = Vector{$elty}(n) - info = Ref{BlasInt}() - ccall((@blasfunc($sytri), liblapack), Void, - (Ptr{UInt8}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, - Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}), - &uplo, &n, A, &max(1,stride(A,2)), ipiv, work, info) - chkargsok(info[]) - chknonsingular(info[]) - A - end - - # SUBROUTINE DSYTRS_ROOK( UPLO, N, NRHS, A, LDA, IPIV, B, LDB, INFO ) - # - # .. Scalar Arguments .. - # CHARACTER UPLO - # INTEGER INFO, LDA, LDB, N, NRHS - # .. Array Arguments .. - # INTEGER IPIV( * ) - # DOUBLE PRECISION A( LDA, * ), B( LDB, * ) - function sytrs_rook!(uplo::Char, A::StridedMatrix{$elty}, - ipiv::StridedVector{BlasInt}, B::StridedVecOrMat{$elty}) - chkstride1(A,B,ipiv) - n = checksquare(A) - chkuplo(uplo) - if n != size(B,1) - throw(DimensionMismatch("B has first dimension $(size(B,1)), but needs $n")) - end - info = Ref{BlasInt}() - ccall((@blasfunc($sytrs), liblapack), Void, - (Ptr{UInt8}, Ptr{BlasInt}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, - Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, Ptr{BlasInt}), - &uplo, &n, &size(B,2), A, &max(1,stride(A,2)), ipiv, B, &max(1,stride(B,2)), info) - chklapackerror(info[]) - B - end - end -end - -## (SY) hermitian matrices - eigendecomposition, Bunch-Kaufman decomposition, -## solvers (direct and factored) and inverse. -for (syconv, hesv, hetrf, hetri, hetrs, elty, relty) in - ((:zsyconv_,:zhesv_,:zhetrf_,:zhetri_,:zhetrs_,:Complex128, :Float64), - (:csyconv_,:chesv_,:chetrf_,:chetri_,:chetrs_,:Complex64, :Float32)) - @eval begin - # SUBROUTINE ZSYCONV( UPLO, WAY, N, A, LDA, IPIV, WORK, INFO ) - # - # .. Scalar Arguments .. - # CHARACTER UPLO, WAY - # INTEGER INFO, LDA, N - # .. - # .. Array Arguments .. - # INTEGER IPIV( * ) - # COMPLEX*16 A( LDA, * ), WORK( * ) - function syconv!(uplo::Char, A::StridedMatrix{$elty}, ipiv::StridedVector{BlasInt}) - chkstride1(A,ipiv) - n = checksquare(A) - chkuplo(uplo) - work = Vector{$elty}(n) - info = Ref{BlasInt}() - ccall((@blasfunc($syconv), liblapack), Void, - (Ptr{UInt8}, Ptr{UInt8}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, - Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}), - &uplo, &'C', &n, A, &max(1,stride(A,2)), ipiv, work, info) - chklapackerror(info[]) - A, work - end - - # SUBROUTINE ZHESV( UPLO, N, NRHS, A, LDA, IPIV, B, LDB, WORK, - # * .. Scalar Arguments .. - # CHARACTER UPLO - # INTEGER INFO, LDA, LDB, LWORK, N, NRHS - # * .. - # * .. Array Arguments .. - # INTEGER IPIV( * ) - # COMPLEX*16 A( LDA, * ), B( LDB, * ), WORK( * ) - function hesv!(uplo::Char, A::StridedMatrix{$elty}, B::StridedVecOrMat{$elty}) - chkstride1(A,B) - n = checksquare(A) - chkuplo(uplo) - if n != size(B,1) - throw(DimensionMismatch("B has first dimension $(size(B,1)), but needs $n")) - end - ipiv = similar(A, BlasInt, n) - work = Vector{$elty}(1) - lwork = BlasInt(-1) - info = Ref{BlasInt}() - for i = 1:2 - ccall((@blasfunc($hesv), liblapack), Void, - (Ptr{UInt8}, Ptr{BlasInt}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, Ptr{BlasInt}, - Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, Ptr{BlasInt}), - &uplo, &n, &size(B,2), A, &max(1,stride(A,2)), ipiv, B, &max(1,stride(B,2)), - work, &lwork, info) - chklapackerror(info[]) - if i == 1 - lwork = BlasInt(real(work[1])) - work = Vector{$elty}(lwork) - end - end - B, A, ipiv - end - - # SUBROUTINE ZHETRF( UPLO, N, A, LDA, IPIV, WORK, LWORK, INFO ) - # * .. Scalar Arguments .. - # CHARACTER UPLO - # INTEGER INFO, LDA, LWORK, N - # * .. - # * .. Array Arguments .. - # INTEGER IPIV( * ) - # COMPLEX*16 A( LDA, * ), WORK( * ) - function hetrf!(uplo::Char, A::StridedMatrix{$elty}) - chkstride1(A) - n = checksquare(A) - chkuplo(uplo) - ipiv = similar(A, BlasInt, n) - work = Vector{$elty}(1) - lwork = BlasInt(-1) - info = Ref{BlasInt}() - for i in 1:2 - ccall((@blasfunc($hetrf), liblapack), Void, - (Ptr{UInt8}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, - Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, Ptr{BlasInt}), - &uplo, &n, A, &max(1,stride(A,2)), ipiv, work, &lwork, info) - chkargsok(info[]) - if i == 1 - lwork = BlasInt(real(work[1])) - work = Vector{$elty}(lwork) - end - end - A, ipiv, info[] - end - -# SUBROUTINE ZHETRI2( UPLO, N, A, LDA, IPIV, WORK, LWORK, INFO ) -# * .. Scalar Arguments .. -# CHARACTER UPLO -# INTEGER INFO, LDA, LWORK, N -# * .. -# * .. Array Arguments .. -# INTEGER IPIV( * ) -# COMPLEX*16 A( LDA, * ), WORK( * ) -# function hetri!(uplo::Char, A::StridedMatrix{$elty}, ipiv::Vector{BlasInt}) -# chkstride1(A) -# n = checksquare(A) -# chkuplo(uplo) -# work = Vector{$elty}(1) -# lwork = BlasInt(-1) -# info = Ref{BlasInt}() -# for i in 1:2 -# ccall((@blasfunc($hetri), liblapack), Void, -# (Ptr{UInt8}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, -# Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, Ptr{BlasInt}), -# &uplo, &n, A, &max(1,stride(A,2)), ipiv, work, &lwork, info) -# chklapackerror(info[]) -# if lwork < 0 -# lwork = BlasInt(real(work[1])) -# work = Vector{$elty}(lwork) -# end -# end -# A -# end - - - # SUBROUTINE ZHETRI( UPLO, N, A, LDA, IPIV, WORK, INFO ) - # * .. Scalar Arguments .. - # CHARACTER UPLO - # INTEGER INFO, LDA, N - # * .. - # * .. Array Arguments .. - # INTEGER IPIV( * ) - # COMPLEX*16 A( LDA, * ), WORK( * ) - function hetri!(uplo::Char, A::StridedMatrix{$elty}, ipiv::StridedVector{BlasInt}) - chkstride1(A, ipiv) - n = checksquare(A) - chkuplo(uplo) - work = Vector{$elty}(n) - info = Ref{BlasInt}() - ccall((@blasfunc($hetri), liblapack), Void, - (Ptr{UInt8}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, - Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}), - &uplo, &n, A, &max(1,stride(A,2)), ipiv, work, info) - chklapackerror(info[]) - A - end - - # SUBROUTINE ZHETRS( UPLO, N, NRHS, A, LDA, IPIV, B, LDB, INFO ) - # * .. Scalar Arguments .. - # CHARACTER UPLO - # INTEGER INFO, LDA, LDB, N, NRHS - # * .. - # * .. Array Arguments .. - # INTEGER IPIV( * ) - # COMPLEX*16 A( LDA, * ), B( LDB, * ) - function hetrs!(uplo::Char, A::StridedMatrix{$elty}, - ipiv::StridedVector{BlasInt}, B::StridedVecOrMat{$elty}) - chkstride1(A,B,ipiv) - n = checksquare(A) - if n != size(B,1) - throw(DimensionMismatch("B has first dimension $(size(B,1)), but needs $n")) - end - info = Ref{BlasInt}() - ccall((@blasfunc($hetrs), liblapack), Void, - (Ptr{UInt8}, Ptr{BlasInt}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, - Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, Ptr{BlasInt}), - &uplo, &n, &size(B,2), A, &max(1,stride(A,2)), ipiv, B, &max(1,stride(B,2)), info) - chklapackerror(info[]) - B - end - end -end - -for (hesv, hetrf, hetri, hetrs, elty, relty) in - ((:zhesv_rook_,:zhetrf_rook_,:zhetri_rook_,:zhetrs_rook_,:Complex128, :Float64), - (:chesv_rook_,:chetrf_rook_,:chetri_rook_,:chetrs_rook_,:Complex64, :Float32)) - @eval begin - # SUBROUTINE ZHESV_ROOK( UPLO, N, NRHS, A, LDA, IPIV, B, LDB, WORK, - # * .. Scalar Arguments .. - # CHARACTER UPLO - # INTEGER INFO, LDA, LDB, LWORK, N, NRHS - # * .. - # * .. Array Arguments .. - # INTEGER IPIV( * ) - # COMPLEX*16 A( LDA, * ), B( LDB, * ), WORK( * ) - function hesv_rook!(uplo::Char, A::StridedMatrix{$elty}, B::StridedVecOrMat{$elty}) - chkstride1(A,B) - n = checksquare(A) - chkuplo(uplo) - if n != size(B,1) - throw(DimensionMismatch("B has first dimension $(size(B,1)), but needs $n")) - end - ipiv = similar(A, BlasInt, n) - work = Vector{$elty}(1) - lwork = BlasInt(-1) - info = Ref{BlasInt}() - for i = 1:2 - ccall((@blasfunc($hesv), liblapack), Void, - (Ptr{UInt8}, Ptr{BlasInt}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, Ptr{BlasInt}, - Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, Ptr{BlasInt}), - &uplo, &n, &size(B,2), A, &max(1,stride(A,2)), ipiv, B, &max(1,stride(B,2)), - work, &lwork, info) - chklapackerror(info[]) - if i == 1 - lwork = BlasInt(real(work[1])) - work = Vector{$elty}(lwork) - end - end - B, A, ipiv - end - - # SUBROUTINE ZHETRF_ROOK( UPLO, N, A, LDA, IPIV, WORK, LWORK, INFO ) - # * .. Scalar Arguments .. - # CHARACTER UPLO - # INTEGER INFO, LDA, LWORK, N - # * .. - # * .. Array Arguments .. - # INTEGER IPIV( * ) - # COMPLEX*16 A( LDA, * ), WORK( * ) - function hetrf_rook!(uplo::Char, A::StridedMatrix{$elty}) - chkstride1(A) - n = checksquare(A) - chkuplo(uplo) - ipiv = similar(A, BlasInt, n) - work = Vector{$elty}(1) - lwork = BlasInt(-1) - info = Ref{BlasInt}() - for i in 1:2 - ccall((@blasfunc($hetrf), liblapack), Void, - (Ptr{UInt8}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, - Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, Ptr{BlasInt}), - &uplo, &n, A, &max(1,stride(A,2)), ipiv, work, &lwork, info) - chkargsok(info[]) - if i == 1 - lwork = BlasInt(real(work[1])) - work = Vector{$elty}(lwork) - end - end - A, ipiv, info[] - end - - # SUBROUTINE ZHETRI_ROOK( UPLO, N, A, LDA, IPIV, WORK, INFO ) - # * .. Scalar Arguments .. - # CHARACTER UPLO - # INTEGER INFO, LDA, N - # * .. - # * .. Array Arguments .. - # INTEGER IPIV( * ) - # COMPLEX*16 A( LDA, * ), WORK( * ) - function hetri_rook!(uplo::Char, A::StridedMatrix{$elty}, ipiv::StridedVector{BlasInt}) - chkstride1(A,ipiv) - n = checksquare(A) - chkuplo(uplo) - work = Vector{$elty}(n) - info = Ref{BlasInt}() - ccall((@blasfunc($hetri), liblapack), Void, - (Ptr{UInt8}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, - Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}), - &uplo, &n, A, &max(1,stride(A,2)), ipiv, work, info) - chklapackerror(info[]) - A - end - - # SUBROUTINE ZHETRS_ROOK( UPLO, N, NRHS, A, LDA, IPIV, B, LDB, INFO ) - # * .. Scalar Arguments .. - # CHARACTER UPLO - # INTEGER INFO, LDA, LDB, N, NRHS - # * .. - # * .. Array Arguments .. - # INTEGER IPIV( * ) - # COMPLEX*16 A( LDA, * ), B( LDB, * ) - function hetrs_rook!(uplo::Char, A::StridedMatrix{$elty}, - ipiv::StridedVector{BlasInt}, B::StridedVecOrMat{$elty}) - chkstride1(A,B,ipiv) - n = checksquare(A) - if n != size(B,1) - throw(DimensionMismatch("B has first dimension $(size(B,1)), but needs $n")) - end - info = Ref{BlasInt}() - ccall((@blasfunc($hetrs), liblapack), Void, - (Ptr{UInt8}, Ptr{BlasInt}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, - Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, Ptr{BlasInt}), - &uplo, &n, &size(B,2), A, &max(1,stride(A,2)), ipiv, B, &max(1,stride(B,2)), info) - chklapackerror(info[]) - B - end - end -end - -for (sysv, sytrf, sytri, sytrs, elty, relty) in - ((:zsysv_,:zsytrf_,:zsytri_,:zsytrs_,:Complex128, :Float64), - (:csysv_,:csytrf_,:csytri_,:csytrs_,:Complex64, :Float32)) - @eval begin - # SUBROUTINE ZSYSV( UPLO, N, NRHS, A, LDA, IPIV, B, LDB, WORK, - # $ LWORK, INFO ) - # * .. Scalar Arguments .. - # CHARACTER UPLO - # INTEGER INFO, LDA, LDB, LWORK, N, NRHS - # * .. - # * .. Array Arguments .. - # INTEGER IPIV( * ) - # COMPLEX*16 A( LDA, * ), B( LDB, * ), WORK( * ) - function sysv!(uplo::Char, A::StridedMatrix{$elty}, B::StridedVecOrMat{$elty}) - chkstride1(A,B) - n = checksquare(A) - chkuplo(uplo) - if n != size(B,1) - throw(DimensionMismatch("B has first dimension $(size(B,1)), but needs $n")) - end - ipiv = similar(A, BlasInt, n) - work = Vector{$elty}(1) - lwork = BlasInt(-1) - info = Ref{BlasInt}() - for i = 1:2 - ccall((@blasfunc($sysv), liblapack), Void, - (Ptr{UInt8}, Ptr{BlasInt}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, Ptr{BlasInt}, - Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, Ptr{BlasInt}), - &uplo, &n, &size(B,2), A, &max(1,stride(A,2)), ipiv, B, &max(1,stride(B,2)), - work, &lwork, info) - chkargsok(info[]) - chknonsingular(info[]) - if i == 1 - lwork = BlasInt(real(work[1])) - work = Vector{$elty}(lwork) - end - end - B, A, ipiv - end - - # SUBROUTINE ZSYTRF( UPLO, N, A, LDA, IPIV, WORK, LWORK, INFO ) - # * .. Scalar Arguments .. - # CHARACTER UPLO - # INTEGER INFO, LDA, LWORK, N - # * .. - # * .. Array Arguments .. - # INTEGER IPIV( * ) - # COMPLEX*16 A( LDA, * ), WORK( * ) - function sytrf!(uplo::Char, A::StridedMatrix{$elty}) - chkstride1(A) - n = checksquare(A) - chkuplo(uplo) - ipiv = similar(A, BlasInt, n) - if n == 0 - return A, ipiv, zero(BlasInt) - end - work = Vector{$elty}(1) - lwork = BlasInt(-1) - info = Ref{BlasInt}() - for i = 1:2 - ccall((@blasfunc($sytrf), liblapack), Void, - (Ptr{UInt8}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, - Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, Ptr{BlasInt}), - &uplo, &n, A, &max(1,stride(A,2)), ipiv, work, &lwork, info) - chkargsok(info[]) - if i == 1 - lwork = BlasInt(real(work[1])) - work = Vector{$elty}(lwork) - end - end - A, ipiv, info[] - end - -# SUBROUTINE ZSYTRI2( UPLO, N, A, LDA, IPIV, WORK, LWORK, INFO ) -# * .. Scalar Arguments .. -# CHARACTER UPLO -# INTEGER INFO, LDA, LWORK, N -# * .. -# * .. Array Arguments .. -# INTEGER IPIV( * ) -# COMPLEX*16 A( LDA, * ), WORK( * ) -# function sytri!(uplo::Char, A::StridedMatrix{$elty}, ipiv::Vector{BlasInt}) -# chkstride1(A) -# n = checksquare(A) -# chkuplo(uplo) -# work = Vector{$elty}(1) -# lwork = BlasInt(-1) -# info = Ref{BlasInt}() -# for i in 1:2 -# ccall((@blasfunc($sytri), liblapack), Void, -# (Ptr{UInt8}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, -# Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, Ptr{BlasInt}), -# &uplo, &n, A, &max(1,stride(A,2)), ipiv, work, &lwork, info) -# chklapackerror(info[]) -# if lwork < 0 -# lwork = BlasInt(real(work[1])) -# work = Vector{$elty}(lwork) -# end -# end -# A -# end - - # SUBROUTINE ZSYTRI( UPLO, N, A, LDA, IPIV, WORK, INFO ) - # * .. Scalar Arguments .. - # CHARACTER UPLO - # INTEGER INFO, LDA, N - # * .. - # * .. Array Arguments .. - # INTEGER IPIV( * ) - # COMPLEX*16 A( LDA, * ), WORK( * ) - function sytri!(uplo::Char, A::StridedMatrix{$elty}, ipiv::StridedVector{BlasInt}) - chkstride1(A, ipiv) - n = checksquare(A) - chkuplo(uplo) - work = Vector{$elty}(n) - info = Ref{BlasInt}() - ccall((@blasfunc($sytri), liblapack), Void, - (Ptr{UInt8}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, - Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}), - &uplo, &n, A, &max(1,stride(A,2)), ipiv, work, info) - chklapackerror(info[]) - A - end - - # SUBROUTINE ZSYTRS( UPLO, N, NRHS, A, LDA, IPIV, B, LDB, INFO ) - # * .. Scalar Arguments .. - # CHARACTER UPLO - # INTEGER INFO, LDA, LDB, N, NRHS - # * .. - # * .. Array Arguments .. - # INTEGER IPIV( * ) - # COMPLEX*16 A( LDA, * ), B( LDB, * ) - function sytrs!(uplo::Char, A::StridedMatrix{$elty}, - ipiv::StridedVector{BlasInt}, B::StridedVecOrMat{$elty}) - chkstride1(A,B,ipiv) - n = checksquare(A) - chkuplo(uplo) - if n != size(B,1) - throw(DimensionMismatch("B has first dimension $(size(B,1)), but needs $n")) - end - info = Ref{BlasInt}() - ccall((@blasfunc($sytrs), liblapack), Void, - (Ptr{UInt8}, Ptr{BlasInt}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, - Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, Ptr{BlasInt}), - &uplo, &n, &size(B,2), A, &max(1,stride(A,2)), ipiv, B, &max(1,stride(B,2)), info) - chklapackerror(info[]) - B - end - end -end - -for (sysv, sytrf, sytri, sytrs, elty, relty) in - ((:zsysv_rook_,:zsytrf_rook_,:zsytri_rook_,:zsytrs_rook_,:Complex128, :Float64), - (:csysv_rook_,:csytrf_rook_,:csytri_rook_,:csytrs_rook_,:Complex64, :Float32)) - @eval begin - # SUBROUTINE ZSYSV_ROOK(UPLO, N, NRHS, A, LDA, IPIV, B, LDB, WORK, - # $ LWORK, INFO ) - # * .. Scalar Arguments .. - # CHARACTER UPLO - # INTEGER INFO, LDA, LDB, LWORK, N, NRHS - # * .. - # * .. Array Arguments .. - # INTEGER IPIV( * ) - # COMPLEX*16 A( LDA, * ), B( LDB, * ), WORK( * ) - function sysv_rook!(uplo::Char, A::StridedMatrix{$elty}, B::StridedVecOrMat{$elty}) - chkstride1(A,B) - n = checksquare(A) - chkuplo(uplo) - if n != size(B,1) - throw(DimensionMismatch("B has first dimension $(size(B,1)), but needs $n")) - end - ipiv = similar(A, BlasInt, n) - work = Vector{$elty}(1) - lwork = BlasInt(-1) - info = Ref{BlasInt}() - for i = 1:2 - ccall((@blasfunc($sysv), liblapack), Void, - (Ptr{UInt8}, Ptr{BlasInt}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, Ptr{BlasInt}, - Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, Ptr{BlasInt}), - &uplo, &n, &size(B,2), A, &max(1,stride(A,2)), ipiv, B, &max(1,stride(B,2)), - work, &lwork, info) - chkargsok(info[]) - chknonsingular(info[]) - if i == 1 - lwork = BlasInt(real(work[1])) - work = Vector{$elty}(lwork) - end - end - B, A, ipiv - end - - # SUBROUTINE ZSYTRF_ROOK( UPLO, N, A, LDA, IPIV, WORK, LWORK, INFO ) - # * .. Scalar Arguments .. - # CHARACTER UPLO - # INTEGER INFO, LDA, LWORK, N - # * .. - # * .. Array Arguments .. - # INTEGER IPIV( * ) - # COMPLEX*16 A( LDA, * ), WORK( * ) - function sytrf_rook!(uplo::Char, A::StridedMatrix{$elty}) - chkstride1(A) - n = checksquare(A) - chkuplo(uplo) - ipiv = similar(A, BlasInt, n) - if n == 0 - return A, ipiv, zero(BlasInt) - end - work = Vector{$elty}(1) - lwork = BlasInt(-1) - info = Ref{BlasInt}() - for i = 1:2 - ccall((@blasfunc($sytrf), liblapack), Void, - (Ptr{UInt8}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, - Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, Ptr{BlasInt}), - &uplo, &n, A, &max(1,stride(A,2)), ipiv, work, &lwork, info) - chkargsok(info[]) - if i == 1 - lwork = BlasInt(real(work[1])) - work = Vector{$elty}(lwork) - end - end - A, ipiv, info[] - end - - # SUBROUTINE ZSYTRI_ROOK( UPLO, N, A, LDA, IPIV, WORK, INFO ) - # * .. Scalar Arguments .. - # CHARACTER UPLO - # INTEGER INFO, LDA, N - # * .. - # * .. Array Arguments .. - # INTEGER IPIV( * ) - # COMPLEX*16 A( LDA, * ), WORK( * ) - function sytri_rook!(uplo::Char, A::StridedMatrix{$elty}, ipiv::StridedVector{BlasInt}) - chkstride1(A, ipiv) - n = checksquare(A) - chkuplo(uplo) - work = Vector{$elty}(n) - info = Ref{BlasInt}() - ccall((@blasfunc($sytri), liblapack), Void, - (Ptr{UInt8}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, - Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}), - &uplo, &n, A, &max(1,stride(A,2)), ipiv, work, info) - chklapackerror(info[]) - A - end - - # SUBROUTINE ZSYTRS_ROOK( UPLO, N, NRHS, A, LDA, IPIV, B, LDB, INFO ) - # * .. Scalar Arguments .. - # CHARACTER UPLO - # INTEGER INFO, LDA, LDB, N, NRHS - # * .. - # * .. Array Arguments .. - # INTEGER IPIV( * ) - # COMPLEX*16 A( LDA, * ), B( LDB, * ) - function sytrs_rook!(uplo::Char, A::StridedMatrix{$elty}, - ipiv::StridedVector{BlasInt}, B::StridedVecOrMat{$elty}) - chkstride1(A,B,ipiv) - n = checksquare(A) - chkuplo(uplo) - if n != size(B,1) - throw(DimensionMismatch("B has first dimension $(size(B,1)), but needs $n")) - end - info = Ref{BlasInt}() - ccall((@blasfunc($sytrs), liblapack), Void, - (Ptr{UInt8}, Ptr{BlasInt}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, - Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, Ptr{BlasInt}), - &uplo, &n, &size(B,2), A, &max(1,stride(A,2)), ipiv, B, &max(1,stride(B,2)), info) - chklapackerror(info[]) - B - end - end -end - -""" - syconv!(uplo, A, ipiv) -> (A, work) - -Converts a symmetric matrix `A` (which has been factorized into a -triangular matrix) into two matrices `L` and `D`. If `uplo = U`, `A` -is upper triangular. If `uplo = L`, it is lower triangular. `ipiv` is -the pivot vector from the triangular factorization. `A` is overwritten -by `L` and `D`. -""" -syconv!(uplo::Char, A::StridedMatrix, ipiv::StridedVector{BlasInt}) - -""" - sysv!(uplo, A, B) -> (B, A, ipiv) - -Finds the solution to `A * X = B` for symmetric matrix `A`. If `uplo = U`, -the upper half of `A` is stored. If `uplo = L`, the lower half is stored. -`B` is overwritten by the solution `X`. `A` is overwritten by its -Bunch-Kaufman factorization. `ipiv` contains pivoting information about the -factorization. -""" -sysv!(uplo::Char, A::StridedMatrix, B::StridedVecOrMat) - -""" - sytrf!(uplo, A) -> (A, ipiv, info) - -Computes the Bunch-Kaufman factorization of a symmetric matrix `A`. If -`uplo = U`, the upper half of `A` is stored. If `uplo = L`, the lower -half is stored. - -Returns `A`, overwritten by the factorization, a pivot vector `ipiv`, and -the error code `info` which is a non-negative integer. If `info` is positive -the matrix is singular and the diagonal part of the factorization is exactly -zero at position `info`. -""" -sytrf!(uplo::Char, A::StridedMatrix) - -""" - sytri!(uplo, A, ipiv) - -Computes the inverse of a symmetric matrix `A` using the results of -`sytrf!`. If `uplo = U`, the upper half of `A` is stored. If `uplo = L`, -the lower half is stored. `A` is overwritten by its inverse. -""" -sytri!(uplo::Char, A::StridedMatrix, ipiv::StridedVector{BlasInt}) - -""" - sytrs!(uplo, A, ipiv, B) - -Solves the equation `A * X = B` for a symmetric matrix `A` using the -results of `sytrf!`. If `uplo = U`, the upper half of `A` is stored. -If `uplo = L`, the lower half is stored. `B` is overwritten by the -solution `X`. -""" -sytrs!(uplo::Char, A::StridedMatrix, ipiv::StridedVector{BlasInt}, B::StridedVecOrMat) - - -""" - hesv!(uplo, A, B) -> (B, A, ipiv) - -Finds the solution to `A * X = B` for Hermitian matrix `A`. If `uplo = U`, -the upper half of `A` is stored. If `uplo = L`, the lower half is stored. -`B` is overwritten by the solution `X`. `A` is overwritten by its -Bunch-Kaufman factorization. `ipiv` contains pivoting information about the -factorization. -""" -hesv!(uplo::Char, A::StridedMatrix, B::StridedVecOrMat) - -""" - hetrf!(uplo, A) -> (A, ipiv, info) - -Computes the Bunch-Kaufman factorization of a Hermitian matrix `A`. If -`uplo = U`, the upper half of `A` is stored. If `uplo = L`, the lower -half is stored. - -Returns `A`, overwritten by the factorization, a pivot vector `ipiv`, and -the error code `info` which is a non-negative integer. If `info` is positive -the matrix is singular and the diagonal part of the factorization is exactly -zero at position `info`. -""" -hetrf!(uplo::Char, A::StridedMatrix) - -""" - hetri!(uplo, A, ipiv) - -Computes the inverse of a Hermitian matrix `A` using the results of -`sytrf!`. If `uplo = U`, the upper half of `A` is stored. If `uplo = L`, -the lower half is stored. `A` is overwritten by its inverse. -""" -hetri!(uplo::Char, A::StridedMatrix, ipiv::StridedVector{BlasInt}) - -""" - hetrs!(uplo, A, ipiv, B) - -Solves the equation `A * X = B` for a Hermitian matrix `A` using the -results of `sytrf!`. If `uplo = U`, the upper half of `A` is stored. -If `uplo = L`, the lower half is stored. `B` is overwritten by the -solution `X`. -""" -hetrs!(uplo::Char, A::StridedMatrix, ipiv::StridedVector{BlasInt}, B::StridedVecOrMat) - -# Symmetric (real) eigensolvers -for (syev, syevr, sygvd, elty) in - ((:dsyev_,:dsyevr_,:dsygvd_,:Float64), - (:ssyev_,:ssyevr_,:ssygvd_,:Float32)) - @eval begin - # SUBROUTINE DSYEV( JOBZ, UPLO, N, A, LDA, W, WORK, LWORK, INFO ) - # * .. Scalar Arguments .. - # CHARACTER JOBZ, UPLO - # INTEGER INFO, LDA, LWORK, N - # * .. Array Arguments .. - # DOUBLE PRECISION A( LDA, * ), W( * ), WORK( * ) - function syev!(jobz::Char, uplo::Char, A::StridedMatrix{$elty}) - chkstride1(A) - n = checksquare(A) - W = similar(A, $elty, n) - work = Vector{$elty}(1) - lwork = BlasInt(-1) - info = Ref{BlasInt}() - for i = 1:2 - ccall((@blasfunc($syev), liblapack), Void, - (Ptr{UInt8}, Ptr{UInt8}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, - Ptr{$elty}, Ptr{$elty}, Ptr{BlasInt}, Ptr{BlasInt}), - &jobz, &uplo, &n, A, &max(1,stride(A,2)), W, work, &lwork, info) - chklapackerror(info[]) - if i == 1 - lwork = BlasInt(real(work[1])) - work = Vector{$elty}(lwork) - end - end - jobz == 'V' ? (W, A) : W - end - - # SUBROUTINE DSYEVR( JOBZ, RANGE, UPLO, N, A, LDA, VL, VU, IL, IU, - # $ ABSTOL, M, W, Z, LDZ, ISUPPZ, WORK, LWORK, - # $ IWORK, LIWORK, INFO ) - # * .. Scalar Arguments .. - # CHARACTER JOBZ, RANGE, UPLO - # INTEGER IL, INFO, IU, LDA, LDZ, LIWORK, LWORK, M, N - # DOUBLE PRECISION ABSTOL, VL, VU - # * .. - # * .. Array Arguments .. - # INTEGER ISUPPZ( * ), IWORK( * ) - # DOUBLE PRECISION A( LDA, * ), W( * ), WORK( * ), Z( LDZ, * ) - function syevr!(jobz::Char, range::Char, uplo::Char, A::StridedMatrix{$elty}, - vl::AbstractFloat, vu::AbstractFloat, il::Integer, iu::Integer, abstol::AbstractFloat) - chkstride1(A) - n = checksquare(A) - if range == 'I' && !(1 <= il <= iu <= n) - throw(ArgumentError("illegal choice of eigenvalue indices (il = $il, iu = $iu), which must be between 1 and n = $n")) - end - if range == 'V' && vl >= vu - throw(ArgumentError("lower boundary, $vl, must be less than upper boundary, $vu")) - end - lda = stride(A,2) - m = Ref{BlasInt}() - w = similar(A, $elty, n) - ldz = n - if jobz == 'N' - Z = similar(A, $elty, ldz, 0) - elseif jobz == 'V' - Z = similar(A, $elty, ldz, n) - end - isuppz = similar(A, BlasInt, 2*n) - work = Vector{$elty}(1) - lwork = BlasInt(-1) - iwork = Vector{BlasInt}(1) - liwork = BlasInt(-1) - info = Ref{BlasInt}() - for i = 1:2 - ccall((@blasfunc($syevr), liblapack), Void, - (Ptr{UInt8}, Ptr{UInt8}, Ptr{UInt8}, Ptr{BlasInt}, - Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, Ptr{$elty}, - Ptr{BlasInt}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, - Ptr{$elty}, Ptr{$elty}, Ptr{BlasInt}, Ptr{BlasInt}, - Ptr{$elty}, Ptr{BlasInt}, Ptr{BlasInt}, Ptr{BlasInt}, - Ptr{BlasInt}), - &jobz, &range, &uplo, &n, - A, &max(1,lda), &vl, &vu, - &il, &iu, &abstol, m, - w, Z, &max(1,ldz), isuppz, - work, &lwork, iwork, &liwork, - info) - chklapackerror(info[]) - if i == 1 - lwork = BlasInt(real(work[1])) - work = Vector{$elty}(lwork) - liwork = iwork[1] - iwork = Vector{BlasInt}(liwork) - end - end - w[1:m[]], Z[:,1:(jobz == 'V' ? m[] : 0)] - end - syevr!(jobz::Char, A::StridedMatrix{$elty}) = - syevr!(jobz, 'A', 'U', A, 0.0, 0.0, 0, 0, -1.0) - - # Generalized eigenproblem - # SUBROUTINE DSYGVD( ITYPE, JOBZ, UPLO, N, A, LDA, B, LDB, W, WORK, - # $ LWORK, IWORK, LIWORK, INFO ) - # * .. Scalar Arguments .. - # CHARACTER JOBZ, UPLO - # INTEGER INFO, ITYPE, LDA, LDB, LIWORK, LWORK, N - # * .. - # * .. Array Arguments .. - # INTEGER IWORK( * ) - # DOUBLE PRECISION A( LDA, * ), B( LDB, * ), W( * ), WORK( * ) - function sygvd!(itype::Integer, jobz::Char, uplo::Char, A::StridedMatrix{$elty}, B::StridedMatrix{$elty}) - chkstride1(A, B) - n, m = checksquare(A, B) - if n != m - throw(DimensionMismatch("dimensions of A, ($n,$n), and B, ($m,$m), must match")) - end - lda = max(1, stride(A, 2)) - ldb = max(1, stride(B, 2)) - w = similar(A, $elty, n) - work = Vector{$elty}(1) - lwork = BlasInt(-1) - iwork = Vector{BlasInt}(1) - liwork = BlasInt(-1) - info = Ref{BlasInt}() - for i = 1:2 - ccall((@blasfunc($sygvd), liblapack), Void, - (Ptr{BlasInt}, Ptr{UInt8}, Ptr{UInt8}, Ptr{BlasInt}, - Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, - Ptr{$elty}, Ptr{$elty}, Ptr{BlasInt}, Ptr{BlasInt}, - Ptr{BlasInt}, Ptr{BlasInt}), - &itype, &jobz, &uplo, &n, - A, &lda, B, &ldb, - w, work, &lwork, iwork, - &liwork, info) - chkargsok(info[]) - if i == 1 - lwork = BlasInt(work[1]) - work = Vector{$elty}(lwork) - liwork = iwork[1] - iwork = Vector{BlasInt}(liwork) - end - end - chkposdef(info[]) - w, A, B - end - end -end -# Hermitian eigensolvers -for (syev, syevr, sygvd, elty, relty) in - ((:zheev_,:zheevr_,:zhegvd_,:Complex128,:Float64), - (:cheev_,:cheevr_,:chegvd_,:Complex64,:Float32)) - @eval begin - # SUBROUTINE ZHEEV( JOBZ, UPLO, N, A, LDA, W, WORK, LWORK, RWORK, INFO ) - # * .. Scalar Arguments .. - # CHARACTER JOBZ, UPLO - # INTEGER INFO, LDA, LWORK, N - # * .. - # * .. Array Arguments .. - # DOUBLE PRECISION RWORK( * ), W( * ) - # COMPLEX*16 A( LDA, * ), WORK( * ) - function syev!(jobz::Char, uplo::Char, A::StridedMatrix{$elty}) - chkstride1(A) - n = checksquare(A) - W = similar(A, $relty, n) - work = Vector{$elty}(1) - lwork = BlasInt(-1) - rwork = Vector{$relty}(max(1, 3n-2)) - info = Ref{BlasInt}() - for i = 1:2 - ccall((@blasfunc($syev), liblapack), Void, - (Ptr{UInt8}, Ptr{UInt8}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, - Ptr{$relty}, Ptr{$elty}, Ptr{BlasInt}, Ptr{$relty}, Ptr{BlasInt}), - &jobz, &uplo, &n, A, &stride(A,2), W, work, &lwork, rwork, info) - chklapackerror(info[]) - if i == 1 - lwork = BlasInt(real(work[1])) - work = Vector{$elty}(lwork) - end - end - jobz == 'V' ? (W, A) : W - end - - # SUBROUTINE ZHEEVR( JOBZ, RANGE, UPLO, N, A, LDA, VL, VU, IL, IU, - # $ ABSTOL, M, W, Z, LDZ, ISUPPZ, WORK, LWORK, - # $ RWORK, LRWORK, IWORK, LIWORK, INFO ) - # * .. Scalar Arguments .. - # CHARACTER JOBZ, RANGE, UPLO - # INTEGER IL, INFO, IU, LDA, LDZ, LIWORK, LRWORK, LWORK, - # $ M, N - # DOUBLE PRECISION ABSTOL, VL, VU - # * .. - # * .. Array Arguments .. - # INTEGER ISUPPZ( * ), IWORK( * ) - # DOUBLE PRECISION RWORK( * ), W( * ) - # COMPLEX*16 A( LDA, * ), WORK( * ), Z( LDZ, * ) - function syevr!(jobz::Char, range::Char, uplo::Char, A::StridedMatrix{$elty}, - vl::AbstractFloat, vu::AbstractFloat, il::Integer, iu::Integer, abstol::AbstractFloat) - chkstride1(A) - n = checksquare(A) - if range == 'I' && !(1 <= il <= iu <= n) - throw(ArgumentError("illegal choice of eigenvalue indices (il = $il, iu=$iu), which must be between 1 and n = $n")) - end - if range == 'V' && vl >= vu - throw(ArgumentError("lower boundary, $vl, must be less than upper boundary, $vu")) - end - lda = max(1,stride(A,2)) - m = Ref{BlasInt}() - w = similar(A, $relty, n) - if jobz == 'N' - ldz = 1 - Z = similar(A, $elty, ldz, 0) - elseif jobz == 'V' - ldz = n - Z = similar(A, $elty, ldz, n) - end - isuppz = similar(A, BlasInt, 2*n) - work = Vector{$elty}(1) - lwork = BlasInt(-1) - rwork = Vector{$relty}(1) - lrwork = BlasInt(-1) - iwork = Vector{BlasInt}(1) - liwork = BlasInt(-1) - info = Ref{BlasInt}() - for i = 1:2 - ccall((@blasfunc($syevr), liblapack), Void, - (Ptr{UInt8}, Ptr{UInt8}, Ptr{UInt8}, Ptr{BlasInt}, - Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, Ptr{$elty}, - Ptr{BlasInt}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, - Ptr{$relty}, Ptr{$elty}, Ptr{BlasInt}, Ptr{BlasInt}, - Ptr{$elty}, Ptr{BlasInt}, Ptr{$relty}, Ptr{BlasInt}, - Ptr{BlasInt}, Ptr{BlasInt}, Ptr{BlasInt}), - &jobz, &range, &uplo, &n, - A, &lda, &vl, &vu, - &il, &iu, &abstol, m, - w, Z, &ldz, isuppz, - work, &lwork, rwork, &lrwork, - iwork, &liwork, info) - chklapackerror(info[]) - if i == 1 - lwork = BlasInt(real(work[1])) - work = Vector{$elty}(lwork) - lrwork = BlasInt(rwork[1]) - rwork = Vector{$relty}(lrwork) - liwork = iwork[1] - iwork = Vector{BlasInt}(liwork) - end - end - w[1:m[]], Z[:,1:(jobz == 'V' ? m[] : 0)] - end - syevr!(jobz::Char, A::StridedMatrix{$elty}) = - syevr!(jobz, 'A', 'U', A, 0.0, 0.0, 0, 0, -1.0) - - # SUBROUTINE ZHEGVD( ITYPE, JOBZ, UPLO, N, A, LDA, B, LDB, W, WORK, - # $ LWORK, RWORK, LRWORK, IWORK, LIWORK, INFO ) - # * .. Scalar Arguments .. - # CHARACTER JOBZ, UPLO - # INTEGER INFO, ITYPE, LDA, LDB, LIWORK, LRWORK, LWORK, N - # * .. - # * .. Array Arguments .. - # INTEGER IWORK( * ) - # DOUBLE PRECISION RWORK( * ), W( * ) - # COMPLEX*16 A( LDA, * ), B( LDB, * ), WORK( * ) - function sygvd!(itype::Integer, jobz::Char, uplo::Char, A::StridedMatrix{$elty}, B::StridedMatrix{$elty}) - chkstride1(A, B) - n, m = checksquare(A, B) - if n != m - throw(DimensionMismatch("dimensions of A, ($n,$n), and B, ($m,$m), must match")) - end - lda = max(1, stride(A, 2)) - ldb = max(1, stride(B, 2)) - w = similar(A, $relty, n) - work = Vector{$elty}(1) - lwork = BlasInt(-1) - iwork = Vector{BlasInt}(1) - liwork = BlasInt(-1) - rwork = Array{$relty,0}() - lrwork = BlasInt(-1) - info = Ref{BlasInt}() - for i = 1:2 - ccall((@blasfunc($sygvd), liblapack), Void, - (Ptr{BlasInt}, Ptr{UInt8}, Ptr{UInt8}, Ptr{BlasInt}, - Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, - Ptr{$relty}, Ptr{$elty}, Ptr{BlasInt}, Ptr{$relty}, - Ptr{BlasInt}, Ptr{BlasInt}, Ptr{BlasInt}, Ptr{BlasInt}), - &itype, &jobz, &uplo, &n, - A, &lda, B, &ldb, - w, work, &lwork, rwork, - &lrwork, iwork, &liwork, info) - chkargsok(info[]) - if i == 1 - lwork = BlasInt(real(work[1])) - work = Vector{$elty}(lwork) - liwork = iwork[1] - iwork = Vector{BlasInt}(liwork) - lrwork = BlasInt(rwork[1]) - rwork = Vector{$relty}(lrwork) - end - end - chkposdef(info[]) - w, A, B - end - end -end - -""" - syev!(jobz, uplo, A) - -Finds the eigenvalues (`jobz = N`) or eigenvalues and eigenvectors -(`jobz = V`) of a symmetric matrix `A`. If `uplo = U`, the upper triangle -of `A` is used. If `uplo = L`, the lower triangle of `A` is used. -""" -syev!(jobz::Char, uplo::Char, A::StridedMatrix) - -""" - syevr!(jobz, range, uplo, A, vl, vu, il, iu, abstol) -> (W, Z) - -Finds the eigenvalues (`jobz = N`) or eigenvalues and eigenvectors -(`jobz = V`) of a symmetric matrix `A`. If `uplo = U`, the upper triangle -of `A` is used. If `uplo = L`, the lower triangle of `A` is used. If -`range = A`, all the eigenvalues are found. If `range = V`, the -eigenvalues in the half-open interval `(vl, vu]` are found. -If `range = I`, the eigenvalues with indices between `il` and `iu` are -found. `abstol` can be set as a tolerance for convergence. - -The eigenvalues are returned in `W` and the eigenvectors in `Z`. -""" -syevr!(jobz::Char, range::Char, uplo::Char, A::StridedMatrix, - vl::AbstractFloat, vu::AbstractFloat, il::Integer, iu::Integer, abstol::AbstractFloat) - -""" - sygvd!(itype, jobz, uplo, A, B) -> (w, A, B) - -Finds the generalized eigenvalues (`jobz = N`) or eigenvalues and -eigenvectors (`jobz = V`) of a symmetric matrix `A` and symmetric -positive-definite matrix `B`. If `uplo = U`, the upper triangles -of `A` and `B` are used. If `uplo = L`, the lower triangles of `A` and -`B` are used. If `itype = 1`, the problem to solve is -`A * x = lambda * B * x`. If `itype = 2`, the problem to solve is -`A * B * x = lambda * x`. If `itype = 3`, the problem to solve is -`B * A * x = lambda * x`. -""" -sygvd!(itype::Integer, jobz::Char, uplo::Char, A::StridedMatrix, B::StridedMatrix) - -## (BD) Bidiagonal matrices - singular value decomposition -for (bdsqr, relty, elty) in - ((:dbdsqr_,:Float64,:Float64), - (:sbdsqr_,:Float32,:Float32), - (:zbdsqr_,:Float64,:Complex128), - (:cbdsqr_,:Float32,:Complex64)) - @eval begin - function bdsqr!(uplo::Char, d::StridedVector{$relty}, e_::StridedVector{$relty}, - Vt::StridedMatrix{$elty}, U::StridedMatrix{$elty}, C::StridedMatrix{$elty}) - chkstride1(d, e_) - # Extract number - n = length(d) - ncvt, nru, ncc = size(Vt, 2), size(U, 1), size(C, 2) - ldvt, ldu, ldc = max(1, stride(Vt,2)), max(1, stride(U, 2)), max(1, stride(C,2)) - # Do checks - chkuplo(uplo) - if length(e_) != n - 1 - throw(DimensionMismatch("off-diagonal has length $(length(e_)) but should have length $(n - 1)")) - end - if ncvt > 0 && ldvt < n - throw(DimensionMismatch("leading dimension of Vt, $ldvt, must be at least $n")) - end - if ldu < nru - throw(DimensionMismatch("leading dimension of U, $ldu, must be at least $nru")) - end - if size(U, 2) != n - throw(DimensionMismatch("U must have $n columns but has $(size(U, 2))")) - end - if ncc > 0 && ldc < n - throw(DimensionMismatch("leading dimension of C, $ldc, must be at least $n")) - end - # Allocate - work = Vector{$relty}(4n) - info = Ref{BlasInt}() - ccall((@blasfunc($bdsqr), liblapack), Void, - (Ptr{UInt8}, Ptr{BlasInt}, Ptr{BlasInt}, Ptr{BlasInt}, - Ptr{BlasInt}, Ptr{$relty}, Ptr{$relty}, Ptr{$elty}, - Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, - Ptr{BlasInt}, Ptr{$relty}, Ptr{BlasInt}), - &uplo, &n, &ncvt, &nru, - &ncc, d, e_, Vt, - &ldvt, U, &ldu, C, - &ldc, work, info) - chklapackerror(info[]) - d, Vt, U, C #singular values in descending order, P**T * VT, U * Q, Q**T * C - end - end -end - -""" - bdsqr!(uplo, d, e_, Vt, U, C) -> (d, Vt, U, C) - -Computes the singular value decomposition of a bidiagonal matrix with -`d` on the diagonal and `e_` on the off-diagonal. If `uplo = U`, `e_` is -the superdiagonal. If `uplo = L`, `e_` is the subdiagonal. Can optionally also -compute the product `Q' * C`. - -Returns the singular values in `d`, and the matrix `C` overwritten with `Q' * C`. -""" -bdsqr!(uplo::Char, d::StridedVector, e_::StridedVector, Vt::StridedMatrix, U::StridedMatrix, C::StridedMatrix) - -#Defined only for real types -for (bdsdc, elty) in - ((:dbdsdc_,:Float64), - (:sbdsdc_,:Float32)) - @eval begin - #* DBDSDC computes the singular value decomposition (SVD) of a real - #* N-by-N (upper or lower) bidiagonal matrix B: B = U * S * VT, - #* using a divide and conquer method - #* .. Scalar Arguments .. - # CHARACTER COMPQ, UPLO - # INTEGER INFO, LDU, LDVT, N - #* .. - #* .. Array Arguments .. - # INTEGER IQ( * ), IWORK( * ) - # DOUBLE PRECISION D( * ), E( * ), Q( * ), U( LDU, * ), - # $ VT( LDVT, * ), WORK( * ) - function bdsdc!(uplo::Char, compq::Char, d::StridedVector{$elty}, e_::StridedVector{$elty}) - chkstride1(d, e_) - n, ldiq, ldq, ldu, ldvt = length(d), 1, 1, 1, 1 - chkuplo(uplo) - if compq == 'N' - lwork = 6*n - elseif compq == 'P' - warn("COMPQ='P' is not tested") - #TODO turn this into an actual LAPACK call - #smlsiz=ilaenv(9, $elty==:Float64 ? 'dbdsqr' : 'sbdsqr', string(uplo, compq), n,n,n,n) - smlsiz=100 #For now, completely overkill - ldq = n*(11+2*smlsiz+8*round(Int,log((n/(smlsiz+1)))/log(2))) - ldiq = n*(3+3*round(Int,log(n/(smlsiz+1))/log(2))) - lwork = 6*n - elseif compq == 'I' - ldvt=ldu=max(1, n) - lwork=3*n^2 + 4*n - else - throw(ArgumentError("COMPQ argument must be 'N', 'P' or 'I', got $(repr(compq))")) - end - u = similar(d, $elty, (ldu, n)) - vt = similar(d, $elty, (ldvt, n)) - q = similar(d, $elty, ldq) - iq = similar(d, BlasInt, ldiq) - work = Vector{$elty}(lwork) - iwork = Vector{BlasInt}(8n) - info = Ref{BlasInt}() - ccall((@blasfunc($bdsdc), liblapack), Void, - (Ptr{UInt8}, Ptr{UInt8}, Ptr{BlasInt}, Ptr{$elty}, Ptr{$elty}, - Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, - Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, Ptr{BlasInt}), - &uplo, &compq, &n, d, e_, - u, &ldu, vt, &ldvt, - q, iq, work, iwork, info) - chklapackerror(info[]) - d, e, u, vt, q, iq - end - end -end - -""" - bdsdc!(uplo, compq, d, e_) -> (d, e, u, vt, q, iq) - -Computes the singular value decomposition of a bidiagonal matrix with `d` on the -diagonal and `e_` on the off-diagonal using a divide and conqueq method. -If `uplo = U`, `e_` is the superdiagonal. If `uplo = L`, `e_` is the subdiagonal. -If `compq = N`, only the singular values are found. If `compq = I`, the singular -values and vectors are found. If `compq = P`, the singular values -and vectors are found in compact form. Only works for real types. - -Returns the singular values in `d`, and if `compq = P`, the compact singular -vectors in `iq`. -""" -bdsdc!(uplo::Char, compq::Char, d::StridedVector, e_::StridedVector) - -for (gecon, elty) in - ((:dgecon_,:Float64), - (:sgecon_,:Float32)) - @eval begin - # SUBROUTINE DGECON( NORM, N, A, LDA, ANORM, RCOND, WORK, IWORK, - # $ INFO ) - # * .. Scalar Arguments .. - # CHARACTER NORM - # INTEGER INFO, LDA, N - # DOUBLE PRECISION ANORM, RCOND - # * .. - # * .. Array Arguments .. - # INTEGER IWORK( * ) - # DOUBLE PRECISION A( LDA, * ), WORK( * ) - function gecon!(normtype::Char, A::StridedMatrix{$elty}, anorm::$elty) - chkstride1(A) - n = checksquare(A) - lda = max(1, stride(A, 2)) - rcond = Vector{$elty}(1) - work = Vector{$elty}(4n) - iwork = Vector{BlasInt}(n) - info = Ref{BlasInt}() - ccall((@blasfunc($gecon), liblapack), Void, - (Ptr{UInt8}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, - Ptr{$elty}, Ptr{$elty}, Ptr{$elty}, Ptr{BlasInt}, - Ptr{BlasInt}), - &normtype, &n, A, &lda, &anorm, rcond, work, iwork, - info) - chklapackerror(info[]) - rcond[1] - end - end -end - -for (gecon, elty, relty) in - ((:zgecon_,:Complex128,:Float64), - (:cgecon_,:Complex64, :Float32)) - @eval begin - # SUBROUTINE ZGECON( NORM, N, A, LDA, ANORM, RCOND, WORK, RWORK, - # $ INFO ) - # * .. Scalar Arguments .. - # CHARACTER NORM - # INTEGER INFO, LDA, N - # DOUBLE PRECISION ANORM, RCOND - # * .. - # * .. Array Arguments .. - # DOUBLE PRECISION RWORK( * ) - # COMPLEX*16 A( LDA, * ), WORK( * ) - function gecon!(normtype::Char, A::StridedMatrix{$elty}, anorm::$relty) - chkstride1(A) - n = checksquare(A) - lda = max(1, stride(A, 2)) - rcond = Vector{$relty}(1) - work = Vector{$elty}(2n) - rwork = Vector{$relty}(2n) - info = Ref{BlasInt}() - ccall((@blasfunc($gecon), liblapack), Void, - (Ptr{UInt8}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, - Ptr{$relty}, Ptr{$relty}, Ptr{$elty}, Ptr{$relty}, - Ptr{BlasInt}), - &normtype, &n, A, &lda, &anorm, rcond, work, rwork, - info) - chklapackerror(info[]) - rcond[1] - end - end -end - -""" - gecon!(normtype, A, anorm) - -Finds the reciprocal condition number of matrix `A`. If `normtype = I`, -the condition number is found in the infinity norm. If `normtype = O` or -`1`, the condition number is found in the one norm. `A` must be the -result of `getrf!` and `anorm` is the norm of `A` in the relevant norm. -""" -gecon!(normtype::Char, A::StridedMatrix, anorm) - -for (gehrd, elty) in - ((:dgehrd_,:Float64), - (:sgehrd_,:Float32), - (:zgehrd_,:Complex128), - (:cgehrd_,:Complex64)) - @eval begin - - # .. Scalar Arguments .. - # INTEGER IHI, ILO, INFO, LDA, LWORK, N - # * .. - # * .. Array Arguments .. - # DOUBLE PRECISION A( LDA, * ), TAU( * ), WORK( * ) - function gehrd!(ilo::Integer, ihi::Integer, A::StridedMatrix{$elty}) - chkstride1(A) - n = checksquare(A) - chkfinite(A) # balancing routines don't support NaNs and Infs - tau = similar(A, $elty, max(0,n - 1)) - work = Vector{$elty}(1) - lwork = BlasInt(-1) - info = Ref{BlasInt}() - for i = 1:2 - ccall((@blasfunc($gehrd), liblapack), Void, - (Ptr{BlasInt}, Ptr{BlasInt}, Ptr{BlasInt}, Ptr{$elty}, - Ptr{BlasInt}, Ptr{$elty}, Ptr{$elty}, Ptr{BlasInt}, - Ptr{BlasInt}), - &n, &ilo, &ihi, A, - &max(1, stride(A, 2)), tau, work, &lwork, - info) - chklapackerror(info[]) - if i == 1 - lwork = BlasInt(real(work[1])) - work = Vector{$elty}(lwork) - end - end - A, tau - end - end -end -gehrd!(A::StridedMatrix) = gehrd!(1, size(A, 1), A) - -""" - gehrd!(ilo, ihi, A) -> (A, tau) - -Converts a matrix `A` to Hessenberg form. If `A` is balanced with `gebal!` -then `ilo` and `ihi` are the outputs of `gebal!`. Otherwise they should be -`ilo = 1` and `ihi = size(A,2)`. `tau` contains the elementary reflectors of -the factorization. -""" -gehrd!(ilo::Integer, ihi::Integer, A::StridedMatrix) - -for (orghr, elty) in - ((:dorghr_,:Float64), - (:sorghr_,:Float32), - (:zunghr_,:Complex128), - (:cunghr_,:Complex64)) - @eval begin - # * .. Scalar Arguments .. - # INTEGER IHI, ILO, INFO, LDA, LWORK, N - # * .. - # * .. Array Arguments .. - # DOUBLE PRECISION A( LDA, * ), TAU( * ), WORK( * ) - function orghr!(ilo::Integer, ihi::Integer, A::StridedMatrix{$elty}, tau::StridedVector{$elty}) - chkstride1(A, tau) - n = checksquare(A) - if n - length(tau) != 1 - throw(DimensionMismatch("tau has length $(length(tau)), needs $(n - 1)")) - end - work = Vector{$elty}(1) - lwork = BlasInt(-1) - info = Ref{BlasInt}() - for i = 1:2 - ccall((@blasfunc($orghr), liblapack), Void, - (Ptr{BlasInt}, Ptr{BlasInt}, Ptr{BlasInt}, Ptr{$elty}, - Ptr{BlasInt}, Ptr{$elty}, Ptr{$elty}, Ptr{BlasInt}, - Ptr{BlasInt}), - &n, &ilo, &ihi, A, - &max(1, stride(A, 2)), tau, work, &lwork, - info) - chklapackerror(info[]) - if i == 1 - lwork = BlasInt(real(work[1])) - work = Vector{$elty}(lwork) - end - end - A - end - end -end - -""" - orghr!(ilo, ihi, A, tau) - -Explicitly finds `Q`, the orthogonal/unitary matrix from `gehrd!`. `ilo`, -`ihi`, `A`, and `tau` must correspond to the input/output to `gehrd!`. -""" -orghr!(ilo::Integer, ihi::Integer, A::StridedMatrix, tau::StridedVector) - -for (ormhr, elty) in - ((:dormhr_,:Float64), - (:sormhr_,:Float32), - (:zunmhr_,:Complex128), - (:cunmhr_,:Complex64)) - @eval begin - # .. Scalar Arguments .. - # CHARACTER side, trans - # INTEGER ihi, ilo, info, lda, ldc, lwork, m, n - # .. - # .. Array Arguments .. - # DOUBLE PRECISION a( lda, * ), c( ldc, * ), tau( * ), work( * ) - function ormhr!(side::Char, trans::Char, ilo::Integer, ihi::Integer, A::StridedMatrix{$elty}, - tau::StridedVector{$elty}, C::StridedVecOrMat{$elty}) - - chkstride1(A, tau) - n = checksquare(A) - mC, nC = size(C, 1), size(C, 2) - - if n - length(tau) != 1 - throw(DimensionMismatch("tau has length $(length(tau)), needs $(n - 1)")) - end - if (side == 'L' && mC != n) || (side == 'R' && nC != n) - throw(DimensionMismatch("A and C matrices are not conformable")) - end - - work = Vector{$elty}(1) - lwork = BlasInt(-1) - info = Ref{BlasInt}() - for i = 1:2 - ccall((@blasfunc($ormhr), liblapack), Void, - (Ptr{UInt8}, Ptr{UInt8}, Ptr{BlasInt}, Ptr{BlasInt}, - Ptr{BlasInt}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, - Ptr{$elty}, Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, - Ptr{BlasInt}, Ptr{BlasInt}), - &side, &trans, &mC, &nC, - &ilo, &ihi, A, &max(1, stride(A, 2)), - tau, C, &max(1, stride(C, 2)), work, - &lwork, info) - chklapackerror(info[]) - if i == 1 - lwork = BlasInt(real(work[1])) - work = Vector{$elty}(lwork) - end - end - C - end - end -end - -for (gees, gges, elty) in - ((:dgees_,:dgges_,:Float64), - (:sgees_,:sgges_,:Float32)) - @eval begin - # .. Scalar Arguments .. - # CHARACTER JOBVS, SORT - # INTEGER INFO, LDA, LDVS, LWORK, N, SDIM - # .. - # .. Array Arguments .. - # LOGICAL BWORK( * ) - # DOUBLE PRECISION A( LDA, * ), VS( LDVS, * ), WI( * ), WORK( * ), - # $ WR( * ) - function gees!(jobvs::Char, A::StridedMatrix{$elty}) - chkstride1(A) - n = checksquare(A) - sdim = Vector{BlasInt}(1) - wr = similar(A, $elty, n) - wi = similar(A, $elty, n) - vs = similar(A, $elty, jobvs == 'V' ? n : 0, n) - ldvs = max(size(vs, 1), 1) - work = Vector{$elty}(1) - lwork = BlasInt(-1) - info = Ref{BlasInt}() - for i = 1:2 - ccall((@blasfunc($gees), liblapack), Void, - (Ptr{UInt8}, Ptr{UInt8}, Ptr{Void}, Ptr{BlasInt}, - Ptr{$elty}, Ptr{BlasInt}, Ptr{BlasInt}, Ptr{$elty}, - Ptr{$elty}, Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, - Ptr{BlasInt}, Ptr{Void}, Ptr{BlasInt}), - &jobvs, &'N', C_NULL, &n, - A, &max(1, stride(A, 2)), sdim, wr, - wi, vs, &ldvs, work, - &lwork, C_NULL, info) - chklapackerror(info[]) - if i == 1 - lwork = BlasInt(real(work[1])) - work = Vector{$elty}(lwork) - end - end - A, vs, iszero(wi) ? wr : complex.(wr, wi) - end - - # * .. Scalar Arguments .. - # CHARACTER JOBVSL, JOBVSR, SORT - # INTEGER INFO, LDA, LDB, LDVSL, LDVSR, LWORK, N, SDIM - # * .. - # * .. Array Arguments .. - # LOGICAL BWORK( * ) - # DOUBLE PRECISION A( LDA, * ), ALPHAI( * ), ALPHAR( * ), - # $ B( LDB, * ), BETA( * ), VSL( LDVSL, * ), - # $ VSR( LDVSR, * ), WORK( * ) - function gges!(jobvsl::Char, jobvsr::Char, A::StridedMatrix{$elty}, B::StridedMatrix{$elty}) - chkstride1(A, B) - n, m = checksquare(A, B) - if n != m - throw(DimensionMismatch("dimensions of A, ($n,$n), and B, ($m,$m), must match")) - end - sdim = BlasInt(0) - alphar = similar(A, $elty, n) - alphai = similar(A, $elty, n) - beta = similar(A, $elty, n) - ldvsl = jobvsl == 'V' ? n : 1 - vsl = similar(A, $elty, ldvsl, n) - ldvsr = jobvsr == 'V' ? n : 1 - vsr = similar(A, $elty, ldvsr, n) - work = Vector{$elty}(1) - lwork = BlasInt(-1) - info = Ref{BlasInt}() - for i = 1:2 - ccall((@blasfunc($gges), liblapack), Void, - (Ptr{UInt8}, Ptr{UInt8}, Ptr{UInt8}, Ptr{Void}, - Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, - Ptr{BlasInt}, Ptr{BlasInt}, Ptr{$elty}, Ptr{$elty}, - Ptr{$elty}, Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, - Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, Ptr{Void}, - Ptr{BlasInt}), - &jobvsl, &jobvsr, &'N', C_NULL, - &n, A, &max(1,stride(A, 2)), B, - &max(1,stride(B, 2)), &sdim, alphar, alphai, - beta, vsl, &ldvsl, vsr, - &ldvsr, work, &lwork, C_NULL, - info) - chklapackerror(info[]) - if i == 1 - lwork = BlasInt(real(work[1])) - work = Vector{$elty}(lwork) - end - end - A, B, complex.(alphar, alphai), beta, vsl[1:(jobvsl == 'V' ? n : 0),:], vsr[1:(jobvsr == 'V' ? n : 0),:] - end - end -end - -for (gees, gges, elty, relty) in - ((:zgees_,:zgges_,:Complex128,:Float64), - (:cgees_,:cgges_,:Complex64,:Float32)) - @eval begin - # * .. Scalar Arguments .. - # CHARACTER JOBVS, SORT - # INTEGER INFO, LDA, LDVS, LWORK, N, SDIM - # * .. - # * .. Array Arguments .. - # LOGICAL BWORK( * ) - # DOUBLE PRECISION RWORK( * ) - # COMPLEX*16 A( LDA, * ), VS( LDVS, * ), W( * ), WORK( * ) - function gees!(jobvs::Char, A::StridedMatrix{$elty}) - chkstride1(A) - n = checksquare(A) - sort = 'N' - sdim = BlasInt(0) - w = similar(A, $elty, n) - vs = similar(A, $elty, jobvs == 'V' ? n : 1, n) - ldvs = max(size(vs, 1), 1) - work = Vector{$elty}(1) - lwork = BlasInt(-1) - rwork = Vector{$relty}(n) - info = Ref{BlasInt}() - for i = 1:2 - ccall((@blasfunc($gees), liblapack), Void, - (Ptr{UInt8}, Ptr{UInt8}, Ptr{Void}, Ptr{BlasInt}, - Ptr{$elty}, Ptr{BlasInt}, Ptr{BlasInt}, Ptr{$elty}, - Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, - Ptr{$relty}, Ptr{Void}, Ptr{BlasInt}), - &jobvs, &sort, C_NULL, &n, - A, &max(1, stride(A, 2)), &sdim, w, - vs, &ldvs, work, &lwork, - rwork, C_NULL, info) - chklapackerror(info[]) - if i == 1 - lwork = BlasInt(real(work[1])) - work = Vector{$elty}(lwork) - end - end - A, vs, w - end - - # * .. Scalar Arguments .. - # CHARACTER JOBVSL, JOBVSR, SORT - # INTEGER INFO, LDA, LDB, LDVSL, LDVSR, LWORK, N, SDIM - # * .. - # * .. Array Arguments .. - # LOGICAL BWORK( * ) - # DOUBLE PRECISION RWORK( * ) - # COMPLEX*16 A( LDA, * ), ALPHA( * ), B( LDB, * ), - # $ BETA( * ), VSL( LDVSL, * ), VSR( LDVSR, * ), - # $ WORK( * ) - function gges!(jobvsl::Char, jobvsr::Char, A::StridedMatrix{$elty}, B::StridedMatrix{$elty}) - chkstride1(A, B) - n, m = checksquare(A, B) - if n != m - throw(DimensionMismatch("dimensions of A, ($n,$n), and B, ($m,$m), must match")) - end - sdim = BlasInt(0) - alpha = similar(A, $elty, n) - beta = similar(A, $elty, n) - ldvsl = jobvsl == 'V' ? n : 1 - vsl = similar(A, $elty, ldvsl, n) - ldvsr = jobvsr == 'V' ? n : 1 - vsr = similar(A, $elty, ldvsr, n) - work = Vector{$elty}(1) - lwork = BlasInt(-1) - rwork = Vector{$relty}(8n) - info = Ref{BlasInt}() - for i = 1:2 - ccall((@blasfunc($gges), liblapack), Void, - (Ptr{UInt8}, Ptr{UInt8}, Ptr{UInt8}, Ptr{Void}, - Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, - Ptr{BlasInt}, Ptr{BlasInt}, Ptr{$elty}, Ptr{$elty}, - Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, - Ptr{$elty}, Ptr{BlasInt}, Ptr{$relty}, Ptr{Void}, - Ptr{BlasInt}), - &jobvsl, &jobvsr, &'N', C_NULL, - &n, A, &max(1, stride(A, 2)), B, - &max(1, stride(B, 2)), &sdim, alpha, beta, - vsl, &ldvsl, vsr, &ldvsr, - work, &lwork, rwork, C_NULL, - info) - chklapackerror(info[]) - if i == 1 - lwork = BlasInt(real(work[1])) - work = Vector{$elty}(lwork) - end - end - A, B, alpha, beta, vsl[1:(jobvsl == 'V' ? n : 0),:], vsr[1:(jobvsr == 'V' ? n : 0),:] - end - end -end - -""" - gees!(jobvs, A) -> (A, vs, w) - -Computes the eigenvalues (`jobvs = N`) or the eigenvalues and Schur -vectors (`jobvs = V`) of matrix `A`. `A` is overwritten by its Schur form. - -Returns `A`, `vs` containing the Schur vectors, and `w`, containing the -eigenvalues. -""" -gees!(jobvs::Char, A::StridedMatrix) - - -""" - gges!(jobvsl, jobvsr, A, B) -> (A, B, alpha, beta, vsl, vsr) - -Computes the generalized eigenvalues, generalized Schur form, left Schur -vectors (`jobsvl = V`), or right Schur vectors (`jobvsr = V`) of `A` and -`B`. - -The generalized eigenvalues are returned in `alpha` and `beta`. The left Schur -vectors are returned in `vsl` and the right Schur vectors are returned in `vsr`. -""" -gges!(jobvsl::Char, jobvsr::Char, A::StridedMatrix, B::StridedMatrix) - -for (trexc, trsen, tgsen, elty) in - ((:dtrexc_, :dtrsen_, :dtgsen_, :Float64), - (:strexc_, :strsen_, :stgsen_, :Float32)) - @eval begin - # * .. Scalar Arguments .. - # CHARACTER COMPQ - # INTEGER IFST, ILST, INFO, LDQ, LDT, N - # * .. - # * .. Array Arguments .. - # DOUBLE PRECISION Q( LDQ, * ), T( LDT, * ), WORK( * ) - function trexc!(compq::Char, ifst::BlasInt, ilst::BlasInt, T::StridedMatrix{$elty}, Q::StridedMatrix{$elty}) - chkstride1(T, Q) - n = checksquare(T) - ldt = max(1, stride(T, 2)) - ldq = max(1, stride(Q, 2)) - work = Vector{$elty}(n) - info = Ref{BlasInt}() - ccall((@blasfunc($trexc), liblapack), Void, - (Ptr{UInt8}, Ptr{BlasInt}, - Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, - Ptr{BlasInt}, Ptr{BlasInt}, - Ptr{$elty}, Ptr{BlasInt}), - &compq, &n, - T, &ldt, Q, &ldq, - &ifst, &ilst, - work, info) - chklapackerror(info[]) - T, Q - end - trexc!(ifst::BlasInt, ilst::BlasInt, T::StridedMatrix{$elty}, Q::StridedMatrix{$elty}) = - trexc!('V', ifst, ilst, T, Q) - - # * .. Scalar Arguments .. - # CHARACTER COMPQ, JOB - # INTEGER INFO, LDQ, LDT, LIWORK, LWORK, M, N - # DOUBLE PRECISION S, SEP - # * .. - # * .. Array Arguments .. - # LOGICAL SELECT( * ) - # INTEGER IWORK( * ) - # DOUBLE PRECISION Q( LDQ, * ), T( LDT, * ), WI( * ), WORK( * ), WR( * ) - function trsen!(compq::Char, job::Char, select::StridedVector{BlasInt}, - T::StridedMatrix{$elty}, Q::StridedMatrix{$elty}) - chkstride1(T, Q, select) - n = checksquare(T) - ldt = max(1, stride(T, 2)) - ldq = max(1, stride(Q, 2)) - wr = similar(T, $elty, n) - wi = similar(T, $elty, n) - m = sum(select) - work = Vector{$elty}(1) - lwork = BlasInt(-1) - iwork = Vector{BlasInt}(1) - liwork = BlasInt(-1) - info = Ref{BlasInt}() - select = convert(Array{BlasInt}, select) - for i = 1:2 - ccall((@blasfunc($trsen), liblapack), Void, - (Ptr{UInt8}, Ptr{UInt8}, Ptr{BlasInt}, Ptr{BlasInt}, - Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, - Ptr{$elty}, Ptr{$elty}, Ptr{BlasInt}, Ptr{Void}, Ptr{Void}, - Ptr{$elty}, Ptr{BlasInt}, Ptr{BlasInt}, Ptr{BlasInt}, - Ptr{BlasInt}), - &compq, &job, select, &n, - T, &ldt, Q, &ldq, - wr, wi, &m, C_NULL, C_NULL, - work, &lwork, iwork, &liwork, - info) - chklapackerror(info[]) - if i == 1 # only estimated optimal lwork, liwork - lwork = BlasInt(real(work[1])) - liwork = BlasInt(real(iwork[1])) - work = Vector{$elty}(lwork) - iwork = Vector{BlasInt}(liwork) - end - end - T, Q, iszero(wi) ? wr : complex.(wr, wi) - end - trsen!(select::StridedVector{BlasInt}, T::StridedMatrix{$elty}, Q::StridedMatrix{$elty}) = - trsen!('N', 'V', select, T, Q) - - # .. Scalar Arguments .. - # LOGICAL WANTQ, WANTZ - # INTEGER IJOB, INFO, LDA, LDB, LDQ, LDZ, LIWORK, LWORK, - # $ M, N - # DOUBLE PRECISION PL, PR - # .. - # .. Array Arguments .. - # LOGICAL SELECT( * ) - # INTEGER IWORK( * ) - # DOUBLE PRECISION A( LDA, * ), ALPHAI( * ), ALPHAR( * ), - # $ B( LDB, * ), BETA( * ), DIF( * ), Q( LDQ, * ), - # $ WORK( * ), Z( LDZ, * ) - # .. - function tgsen!(select::StridedVector{BlasInt}, S::StridedMatrix{$elty}, T::StridedMatrix{$elty}, - Q::StridedMatrix{$elty}, Z::StridedMatrix{$elty}) - chkstride1(select, S, T, Q, Z) - n, nt, nq, nz = checksquare(S, T, Q, Z) - if n != nt - throw(DimensionMismatch("dimensions of S, ($n,$n), and T, ($nt,$nt), must match")) - end - if n != nq - throw(DimensionMismatch("dimensions of S, ($n,$n), and Q, ($nq,$nq), must match")) - end - if n != nz - throw(DimensionMismatch("dimensions of S, ($n,$n), and Z, ($nz,$nz), must match")) - end - lds = max(1, stride(S, 2)) - ldt = max(1, stride(T, 2)) - ldq = max(1, stride(Q, 2)) - ldz = max(1, stride(Z, 2)) - m = sum(select) - alphai = similar(T, $elty, n) - alphar = similar(T, $elty, n) - beta = similar(T, $elty, n) - lwork = BlasInt(-1) - work = Vector{$elty}(1) - liwork = BlasInt(-1) - iwork = Vector{BlasInt}(1) - info = Ref{BlasInt}() - select = convert(Array{BlasInt}, select) - for i = 1:2 - ccall((@blasfunc($tgsen), liblapack), Void, - (Ptr{BlasInt}, Ptr{BlasInt}, Ptr{BlasInt}, Ptr{BlasInt}, - Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, - Ptr{BlasInt}, Ptr{$elty}, Ptr{$elty}, Ptr{$elty}, - Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, - Ptr{BlasInt}, Ptr{Void}, Ptr{Void}, Ptr{Void}, - Ptr{$elty}, Ptr{BlasInt}, Ptr{BlasInt}, Ptr{BlasInt}, - Ptr{BlasInt}), - &0, &1, &1, select, - &n, S, &lds, T, - &ldt, alphar, alphai, beta, - Q, &ldq, Z, &ldz, - &m, C_NULL, C_NULL, C_NULL, - work, &lwork, iwork, &liwork, - info) - chklapackerror(info[]) - if i == 1 # only estimated optimal lwork, liwork - lwork = BlasInt(real(work[1])) - work = Vector{$elty}(lwork) - liwork = BlasInt(real(iwork[1])) - iwork = Vector{BlasInt}(liwork) - end - end - S, T, complex.(alphar, alphai), beta, Q, Z - end - end -end - -for (trexc, trsen, tgsen, elty) in - ((:ztrexc_, :ztrsen_, :ztgsen_, :Complex128), - (:ctrexc_, :ctrsen_, :ctgsen_, :Complex64)) - @eval begin - # .. Scalar Arguments .. - # CHARACTER COMPQ - # INTEGER IFST, ILST, INFO, LDQ, LDT, N - # .. - # .. Array Arguments .. - # DOUBLE PRECISION Q( LDQ, * ), T( LDT, * ), WORK( * ) - function trexc!(compq::Char, ifst::BlasInt, ilst::BlasInt, T::StridedMatrix{$elty}, Q::StridedMatrix{$elty}) - chkstride1(T, Q) - n = checksquare(T) - ldt = max(1, stride(T, 2)) - ldq = max(1, stride(Q, 2)) - info = Ref{BlasInt}() - ccall((@blasfunc($trexc), liblapack), Void, - (Ptr{UInt8}, Ptr{BlasInt}, - Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, - Ptr{BlasInt}, Ptr{BlasInt}, - Ptr{BlasInt}), - &compq, &n, - T, &ldt, Q, &ldq, - &ifst, &ilst, - info) - chklapackerror(info[]) - T, Q - end - trexc!(ifst::BlasInt, ilst::BlasInt, T::StridedMatrix{$elty}, Q::StridedMatrix{$elty}) = - trexc!('V', ifst, ilst, T, Q) - - # .. Scalar Arguments .. - # CHARACTER COMPQ, JOB - # INTEGER INFO, LDQ, LDT, LWORK, M, N - # DOUBLE PRECISION S, SEP - # .. - # .. Array Arguments .. - # LOGICAL SELECT( * ) - # COMPLEX Q( LDQ, * ), T( LDT, * ), W( * ), WORK( * ) - function trsen!(compq::Char, job::Char, select::StridedVector{BlasInt}, - T::StridedMatrix{$elty}, Q::StridedMatrix{$elty}) - chkstride1(select, T, Q) - n = checksquare(T) - ldt = max(1, stride(T, 2)) - ldq = max(1, stride(Q, 2)) - w = similar(T, $elty, n) - m = sum(select) - work = Vector{$elty}(1) - lwork = BlasInt(-1) - info = Ref{BlasInt}() - select = convert(Array{BlasInt}, select) - for i = 1:2 - ccall((@blasfunc($trsen), liblapack), Void, - (Ptr{UInt8}, Ptr{UInt8}, Ptr{BlasInt}, Ptr{BlasInt}, - Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, - Ptr{$elty}, Ptr{BlasInt}, Ptr{Void}, Ptr{Void}, - Ptr{$elty}, Ptr{BlasInt}, - Ptr{BlasInt}), - &compq, &job, select, &n, - T, &ldt, Q, &ldq, - w, &m, C_NULL, C_NULL, - work, &lwork, - info) - chklapackerror(info[]) - if i == 1 # only estimated optimal lwork, liwork - lwork = BlasInt(real(work[1])) - work = Vector{$elty}(lwork) - end - end - T, Q, w - end - trsen!(select::StridedVector{BlasInt}, T::StridedMatrix{$elty}, Q::StridedMatrix{$elty}) = - trsen!('N', 'V', select, T, Q) - - # .. Scalar Arguments .. - # LOGICAL WANTQ, WANTZ - # INTEGER IJOB, INFO, LDA, LDB, LDQ, LDZ, LIWORK, LWORK, - # $ M, N - # DOUBLE PRECISION PL, PR - # .. - # .. Array Arguments .. - # LOGICAL SELECT( * ) - # INTEGER IWORK( * ) - # DOUBLE PRECISION DIF( * ) - # COMPLEX*16 A( LDA, * ), ALPHA( * ), B( LDB, * ), - # $ BETA( * ), Q( LDQ, * ), WORK( * ), Z( LDZ, * ) - # .. - function tgsen!(select::StridedVector{BlasInt}, S::StridedMatrix{$elty}, T::StridedMatrix{$elty}, - Q::StridedMatrix{$elty}, Z::StridedMatrix{$elty}) - chkstride1(select, S, T, Q, Z) - n, nt, nq, nz = checksquare(S, T, Q, Z) - if n != nt - throw(DimensionMismatch("dimensions of S, ($n,$n), and T, ($nt,$nt), must match")) - end - if n != nq - throw(DimensionMismatch("dimensions of S, ($n,$n), and Q, ($nq,$nq), must match")) - end - if n != nz - throw(DimensionMismatch("dimensions of S, ($n,$n), and Z, ($nz,$nz), must match")) - end - lds = max(1, stride(S, 2)) - ldt = max(1, stride(T, 2)) - ldq = max(1, stride(Q, 2)) - ldz = max(1, stride(Z, 2)) - m = sum(select) - alpha = similar(T, $elty, n) - beta = similar(T, $elty, n) - lwork = BlasInt(-1) - work = Vector{$elty}(1) - liwork = BlasInt(-1) - iwork = Vector{BlasInt}(1) - info = Ref{BlasInt}() - select = convert(Array{BlasInt}, select) - for i = 1:2 - ccall((@blasfunc($tgsen), liblapack), Void, - (Ptr{BlasInt}, Ptr{BlasInt}, Ptr{BlasInt}, Ptr{BlasInt}, - Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, - Ptr{BlasInt}, Ptr{$elty}, Ptr{$elty}, - Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, - Ptr{BlasInt}, Ptr{Void}, Ptr{Void}, Ptr{Void}, - Ptr{$elty}, Ptr{BlasInt}, Ptr{BlasInt}, Ptr{BlasInt}, - Ptr{BlasInt}), - &0, &1, &1, select, - &n, S, &lds, T, - &ldt, alpha, beta, - Q, &ldq, Z, &ldz, - &m, C_NULL, C_NULL, C_NULL, - work, &lwork, iwork, &liwork, - info) - chklapackerror(info[]) - if i == 1 # only estimated optimal lwork, liwork - lwork = BlasInt(real(work[1])) - work = Vector{$elty}(lwork) - liwork = BlasInt(real(iwork[1])) - iwork = Vector{BlasInt}(liwork) - end - end - S, T, alpha, beta, Q, Z - end - end -end - -""" - trexc!(compq, ifst, ilst, T, Q) -> (T, Q) - -Reorder the Schur factorization of a matrix. If `compq = V`, the Schur -vectors `Q` are reordered. If `compq = N` they are not modified. `ifst` -and `ilst` specify the reordering of the vectors. -""" -trexc!(compq::Char, ifst::BlasInt, ilst::BlasInt, T::StridedMatrix, Q::StridedMatrix) - -""" - trsen!(compq, job, select, T, Q) -> (T, Q, w) - -Reorder the Schur factorization of a matrix and optionally finds reciprocal -condition numbers. If `job = N`, no condition numbers are found. If `job = E`, -only the condition number for this cluster of eigenvalues is found. If -`job = V`, only the condition number for the invariant subspace is found. -If `job = B` then the condition numbers for the cluster and subspace are -found. If `compq = V` the Schur vectors `Q` are updated. If `compq = N` -the Schur vectors are not modified. `select` determines which -eigenvalues are in the cluster. - -Returns `T`, `Q`, and reordered eigenvalues in `w`. -""" -trsen!(compq::Char, job::Char, select::StridedVector{BlasInt}, T::StridedMatrix, Q::StridedMatrix) - -""" - tgsen!(select, S, T, Q, Z) -> (S, T, alpha, beta, Q, Z) - -Reorders the vectors of a generalized Schur decomposition. `select` specifices -the eigenvalues in each cluster. -""" -tgsen!(select::StridedVector{BlasInt}, S::StridedMatrix, T::StridedMatrix, Q::StridedMatrix, Z::StridedMatrix) - -for (fn, elty, relty) in ((:dtrsyl_, :Float64, :Float64), - (:strsyl_, :Float32, :Float32), - (:ztrsyl_, :Complex128, :Float64), - (:ctrsyl_, :Complex64, :Float32)) - @eval begin - function trsyl!(transa::Char, transb::Char, A::StridedMatrix{$elty}, - B::StridedMatrix{$elty}, C::StridedMatrix{$elty}, isgn::Int=1) - chkstride1(A, B, C) - m, n = checksquare(A, B) - lda = max(1, stride(A, 2)) - ldb = max(1, stride(B, 2)) - m1, n1 = size(C) - if m != m1 || n != n1 - throw(DimensionMismatch("dimensions of A, ($m,$n), and C, ($m1,$n1), must match")) - end - ldc = max(1, stride(C, 2)) - scale = Vector{$relty}(1) - info = Ref{BlasInt}() - ccall((@blasfunc($fn), liblapack), Void, - (Ptr{UInt8}, Ptr{UInt8}, Ptr{BlasInt}, Ptr{BlasInt}, Ptr{BlasInt}, - Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, Ptr{$elty}, Ptr{BlasInt}, - Ptr{$relty}, Ptr{BlasInt}), - &transa, &transb, &isgn, &m, &n, - A, &lda, B, &ldb, C, &ldc, - scale, info) - chklapackerror(info[]) - C, scale[1] - end - end -end - -""" - trsyl!(transa, transb, A, B, C, isgn=1) -> (C, scale) - -Solves the Sylvester matrix equation `A * X +/- X * B = scale*C` where `A` and -`B` are both quasi-upper triangular. If `transa = N`, `A` is not modified. -If `transa = T`, `A` is transposed. If `transa = C`, `A` is conjugate -transposed. Similarly for `transb` and `B`. If `isgn = 1`, the equation -`A * X + X * B = scale * C` is solved. If `isgn = -1`, the equation -`A * X - X * B = scale * C` is solved. - -Returns `X` (overwriting `C`) and `scale`. -""" -trsyl!(transa::Char, transb::Char, A::StridedMatrix, B::StridedMatrix, C::StridedMatrix, isgn::Int=1) - -end # module diff --git a/julia-0.6.3/share/julia/base/linalg/ldlt.jl b/julia-0.6.3/share/julia/base/linalg/ldlt.jl deleted file mode 100644 index 53414b0..0000000 --- a/julia-0.6.3/share/julia/base/linalg/ldlt.jl +++ /dev/null @@ -1,91 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -struct LDLt{T,S<:AbstractMatrix} <: Factorization{T} - data::S -end - -size(S::LDLt) = size(S.data) -size(S::LDLt, i::Integer) = size(S.data, i) - -convert(::Type{LDLt{T,S}}, F::LDLt) where {T,S} = LDLt{T,S}(convert(S, F.data)) -# NOTE: the annotaion <:AbstractMatrix shouldn't be necessary, it is introduced -# to avoid an ambiguity warning (see issue #6383) -convert(::Type{LDLt{T}}, F::LDLt{S,U}) where {T,S,U<:AbstractMatrix} = convert(LDLt{T,U}, F) - -convert(::Type{Factorization{T}}, F::LDLt{T}) where {T} = F -convert(::Type{Factorization{T}}, F::LDLt{S,U}) where {T,S,U} = convert(LDLt{T,U}, F) - -# SymTridiagonal -""" - ldltfact!(S::SymTridiagonal) -> LDLt - -Same as [`ldltfact`](@ref), but saves space by overwriting the input `A`, instead of creating a copy. -""" -function ldltfact!(S::SymTridiagonal{T}) where T<:Real - n = size(S,1) - d = S.dv - e = S.ev - @inbounds @simd for i = 1:n-1 - e[i] /= d[i] - d[i+1] -= abs2(e[i])*d[i] - end - return LDLt{T,SymTridiagonal{T}}(S) -end - -""" - ldltfact(S::SymTridiagonal) -> LDLt - -Compute an `LDLt` factorization of a real symmetric tridiagonal matrix such that `A = L*Diagonal(d)*L'` -where `L` is a unit lower triangular matrix and `d` is a vector. The main use of an `LDLt` -factorization `F = ldltfact(A)` is to solve the linear system of equations `Ax = b` with `F\\b`. -""" -function ldltfact(M::SymTridiagonal{T}) where T - S = typeof(zero(T)/one(T)) - return S == T ? ldltfact!(copy(M)) : ldltfact!(convert(SymTridiagonal{S}, M)) -end - -factorize(S::SymTridiagonal) = ldltfact(S) - -function A_ldiv_B!(S::LDLt{T,SymTridiagonal{T}}, B::AbstractVecOrMat{T}) where T - n, nrhs = size(B, 1), size(B, 2) - if size(S,1) != n - throw(DimensionMismatch("Matrix has dimensions $(size(S)) but right hand side has first dimension $n")) - end - d = S.data.dv - l = S.data.ev - @inbounds begin - for i = 2:n - li1 = l[i-1] - @simd for j = 1:nrhs - B[i,j] -= li1*B[i-1,j] - end - end - dn = d[n] - @simd for j = 1:nrhs - B[n,j] /= dn - end - for i = n-1:-1:1 - di = d[i] - li = l[i] - @simd for j = 1:nrhs - B[i,j] /= di - B[i,j] -= li*B[i+1,j] - end - end - end - return B -end - -# Conversion methods -function convert(::Type{SymTridiagonal}, F::LDLt) - e = copy(F.data.ev) - d = copy(F.data.dv) - e .*= d[1:end-1] - d[2:end] += e .* F.data.ev - SymTridiagonal(d, e) -end -convert(::Type{AbstractMatrix}, F::LDLt) = convert(SymTridiagonal, F) -convert(::Type{AbstractArray}, F::LDLt) = convert(AbstractMatrix, F) -convert(::Type{Matrix}, F::LDLt) = convert(Array, convert(AbstractArray, F)) -convert(::Type{Array}, F::LDLt) = convert(Matrix, F) -full(F::LDLt) = convert(AbstractArray, F) diff --git a/julia-0.6.3/share/julia/base/linalg/linalg.jl b/julia-0.6.3/share/julia/base/linalg/linalg.jl deleted file mode 100644 index ffc97a3..0000000 --- a/julia-0.6.3/share/julia/base/linalg/linalg.jl +++ /dev/null @@ -1,294 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -module LinAlg - -import Base: \, /, *, ^, +, -, == -import Base: A_mul_Bt, At_ldiv_Bt, A_rdiv_Bc, At_ldiv_B, Ac_mul_Bc, A_mul_Bc, Ac_mul_B, - Ac_ldiv_B, Ac_ldiv_Bc, At_mul_Bt, A_rdiv_Bt, At_mul_B -import Base: USE_BLAS64, abs, big, broadcast, ceil, conj, convert, copy, copy!, - ctranspose, eltype, eye, findmax, findmin, fill!, floor, full, getindex, - hcat, imag, indices, inv, isapprox, kron, length, IndexStyle, map, - ndims, oneunit, parent, power_by_squaring, print_matrix, promote_rule, real, round, - setindex!, show, similar, size, transpose, trunc, typed_hcat -using Base: promote_op, _length, iszero, @pure, @propagate_inbounds, IndexLinear, - reduce, hvcat_fill, typed_vcat, promote_typeof -# We use `_length` because of non-1 indices; releases after julia 0.5 -# can go back to `length`. `_length(A)` is equivalent to `length(linearindices(A))`. - -export -# Modules - LAPACK, - BLAS, - -# Types - RowVector, - ConjArray, - ConjVector, - ConjMatrix, - SymTridiagonal, - Tridiagonal, - Bidiagonal, - Factorization, - BunchKaufman, - Cholesky, - CholeskyPivoted, - Eigen, - GeneralizedEigen, - GeneralizedSVD, - GeneralizedSchur, - Hessenberg, - LU, - LDLt, - QR, - QRPivoted, - LQ, - Schur, - SVD, - Hermitian, - Symmetric, - LowerTriangular, - UpperTriangular, - Diagonal, - UniformScaling, - -# Functions - axpy!, - bkfact, - bkfact!, - chol, - cholfact, - cholfact!, - cond, - condskeel, - copy!, - copy_transpose!, - cross, - ctranspose, - ctranspose!, - det, - diag, - diagind, - diagm, - diff, - dot, - eig, - eigfact, - eigfact!, - eigmax, - eigmin, - eigs, - eigvals, - eigvals!, - eigvecs, - expm, - eye, - factorize, - givens, - gradient, - hessfact, - hessfact!, - isdiag, - ishermitian, - isposdef, - isposdef!, - issymmetric, - istril, - istriu, - kron, - ldltfact!, - ldltfact, - linreg, - logabsdet, - logdet, - logm, - lu, - lufact, - lufact!, - lyap, - norm, - normalize, - normalize!, - nullspace, - ordschur!, - ordschur, - peakflops, - pinv, - qr, - qrfact!, - qrfact, - lq, - lqfact!, - lqfact, - rank, - scale!, - schur, - schurfact!, - schurfact, - sqrtm, - svd, - svdfact!, - svdfact, - svds, - svdvals!, - svdvals, - sylvester, - trace, - transpose, - transpose!, - transpose_type, - tril, - triu, - tril!, - triu!, - vecdot, - vecnorm, - -# Operators - \, - /, - A_ldiv_B!, - A_ldiv_Bc, - A_ldiv_Bt, - A_mul_B!, - A_mul_Bc, - A_mul_Bc!, - A_mul_Bt, - A_mul_Bt!, - A_rdiv_Bc, - A_rdiv_Bt, - Ac_ldiv_B, - Ac_ldiv_Bc, - Ac_ldiv_B!, - Ac_mul_B, - Ac_mul_B!, - Ac_mul_Bc, - Ac_mul_Bc!, - Ac_rdiv_B, - Ac_rdiv_Bc, - At_ldiv_B, - At_ldiv_Bt, - At_ldiv_B!, - At_mul_B, - At_mul_B!, - At_mul_Bt, - At_mul_Bt!, - At_rdiv_B, - At_rdiv_Bt, - -# Constants - I - -const BlasFloat = Union{Float64,Float32,Complex128,Complex64} -const BlasReal = Union{Float64,Float32} -const BlasComplex = Union{Complex128,Complex64} - -if USE_BLAS64 - const BlasInt = Int64 -else - const BlasInt = Int32 -end - -# Check that stride of matrix/vector is 1 -# Writing like this to avoid splatting penalty when called with multiple arguments, -# see PR 16416 -@inline chkstride1(A...) = _chkstride1(true, A...) -@noinline _chkstride1(ok::Bool) = ok || error("matrix does not have contiguous columns") -@inline _chkstride1(ok::Bool, A, B...) = _chkstride1(ok & (stride(A, 1) == 1), B...) - -""" - LinAlg.checksquare(A) - -Check that a matrix is square, then return its common dimension. -For multiple arguments, return a vector. - -# Example - -```jldoctest -julia> A = ones(4,4); B = zeros(5,5); - -julia> LinAlg.checksquare(A, B) -2-element Array{Int64,1}: - 4 - 5 -``` -""" -function checksquare(A) - m,n = size(A) - m == n || throw(DimensionMismatch("matrix is not square: dimensions are $(size(A))")) - m -end - -function checksquare(A...) - sizes = Int[] - for a in A - size(a,1)==size(a,2) || throw(DimensionMismatch("matrix is not square: dimensions are $(size(a))")) - push!(sizes, size(a,1)) - end - return sizes -end - -function char_uplo(uplo::Symbol) - if uplo == :U - 'U' - elseif uplo == :L - 'L' - else - throw(ArgumentError("uplo argument must be either :U (upper) or :L (lower)")) - end -end - -copy_oftype(A::AbstractArray{T}, ::Type{T}) where {T} = copy(A) -copy_oftype(A::AbstractArray{T,N}, ::Type{S}) where {T,N,S} = convert(AbstractArray{S,N}, A) - -include("conjarray.jl") -include("transpose.jl") -include("rowvector.jl") - -include("exceptions.jl") -include("generic.jl") - -include("blas.jl") -import .BLAS: gemv! # consider renaming gemv! in matmul -include("matmul.jl") -include("lapack.jl") - -include("dense.jl") -include("tridiag.jl") -include("triangular.jl") - -include("factorization.jl") -include("qr.jl") -include("hessenberg.jl") -include("lq.jl") -include("eigen.jl") -include("svd.jl") -include("symmetric.jl") -include("cholesky.jl") -include("lu.jl") -include("bunchkaufman.jl") -include("diagonal.jl") -include("bidiag.jl") -include("uniformscaling.jl") -include("givens.jl") -include("special.jl") -include("bitarray.jl") -include("ldlt.jl") -include("schur.jl") - - -include("arpack.jl") -include("arnoldi.jl") - -function __init__() - try - BLAS.check() - if BLAS.vendor() == :mkl - ccall((:MKL_Set_Interface_Layer, Base.libblas_name), Void, (Cint,), USE_BLAS64 ? 1 : 0) - end - catch ex - Base.showerror_nostdio(ex, - "WARNING: Error during initialization of module LinAlg") - end -end - -end # module LinAlg diff --git a/julia-0.6.3/share/julia/base/linalg/lq.jl b/julia-0.6.3/share/julia/base/linalg/lq.jl deleted file mode 100644 index fd4f95f..0000000 --- a/julia-0.6.3/share/julia/base/linalg/lq.jl +++ /dev/null @@ -1,231 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -# LQ Factorizations - -struct LQ{T,S<:AbstractMatrix} <: Factorization{T} - factors::S - τ::Vector{T} - LQ{T,S}(factors::AbstractMatrix{T}, τ::Vector{T}) where {T,S<:AbstractMatrix} = new(factors, τ) -end - -struct LQPackedQ{T,S<:AbstractMatrix} <: AbstractMatrix{T} - factors::Matrix{T} - τ::Vector{T} - LQPackedQ{T,S}(factors::AbstractMatrix{T}, τ::Vector{T}) where {T,S<:AbstractMatrix} = new(factors, τ) -end - -LQ(factors::AbstractMatrix{T}, τ::Vector{T}) where {T} = LQ{T,typeof(factors)}(factors, τ) -LQPackedQ(factors::AbstractMatrix{T}, τ::Vector{T}) where {T} = LQPackedQ{T,typeof(factors)}(factors, τ) - -""" - lqfact!(A) -> LQ - -Compute the LQ factorization of `A`, using the input -matrix as a workspace. See also [`lq`](@ref). -""" -lqfact!(A::StridedMatrix{<:BlasFloat}) = LQ(LAPACK.gelqf!(A)...) -""" - lqfact(A) -> LQ - -Compute the LQ factorization of `A`. See also [`lq`](@ref). -""" -lqfact(A::StridedMatrix{<:BlasFloat}) = lqfact!(copy(A)) -lqfact(x::Number) = lqfact(fill(x,1,1)) - -""" - lq(A; [thin=true]) -> L, Q - -Perform an LQ factorization of `A` such that `A = L*Q`. The -default is to compute a thin factorization. The LQ factorization -is the QR factorization of `A.'`. `L` is not extended with -zeros if the full `Q` is requested. -""" -function lq(A::Union{Number, AbstractMatrix}; thin::Bool=true) - F = lqfact(A) - F[:L], full(F[:Q], thin=thin) -end - -copy(A::LQ) = LQ(copy(A.factors), copy(A.τ)) - -convert(::Type{LQ{T}},A::LQ) where {T} = LQ(convert(AbstractMatrix{T}, A.factors), convert(Vector{T}, A.τ)) -convert(::Type{Factorization{T}}, A::LQ{T}) where {T} = A -convert(::Type{Factorization{T}}, A::LQ) where {T} = convert(LQ{T}, A) -convert(::Type{AbstractMatrix}, A::LQ) = A[:L]*A[:Q] -convert(::Type{AbstractArray}, A::LQ) = convert(AbstractMatrix, A) -convert(::Type{Matrix}, A::LQ) = convert(Array, convert(AbstractArray, A)) -convert(::Type{Array}, A::LQ) = convert(Matrix, A) -full(A::LQ) = convert(AbstractArray, A) - -ctranspose(A::LQ{T}) where {T} = QR{T,typeof(A.factors)}(A.factors', A.τ) - -function getindex(A::LQ, d::Symbol) - m, n = size(A) - if d == :L - return tril!(A.factors[1:m, 1:min(m,n)]) - elseif d == :Q - return LQPackedQ(A.factors,A.τ) - else - throw(KeyError(d)) - end -end - -getindex(A::LQPackedQ, i::Integer, j::Integer) = - A_mul_B!(A, setindex!(zeros(eltype(A), size(A, 2)), 1, j))[i] - -getq(A::LQ) = LQPackedQ(A.factors, A.τ) - -function show(io::IO, C::LQ) - println(io, "$(typeof(C)) with factors L and Q:") - show(io, C[:L]) - println(io) - show(io, C[:Q]) -end - -convert(::Type{LQPackedQ{T}}, Q::LQPackedQ) where {T} = LQPackedQ(convert(AbstractMatrix{T}, Q.factors), convert(Vector{T}, Q.τ)) -convert(::Type{AbstractMatrix{T}}, Q::LQPackedQ) where {T} = convert(LQPackedQ{T}, Q) -convert(::Type{Matrix}, A::LQPackedQ) = LAPACK.orglq!(copy(A.factors),A.τ) -convert(::Type{Array}, A::LQPackedQ) = convert(Matrix, A) -function full{T}(A::LQPackedQ{T}; thin::Bool = true) - #= We construct the full eye here, even though it seems inefficient, because - every element in the output matrix is a function of all the elements of - the input matrix. The eye is modified by the elementary reflectors held - in A, so this is not just an indexing operation. Note that in general - explicitly constructing Q, rather than using the ldiv or mult methods, - may be a wasteful allocation. =# - if thin - convert(Array, A) - else - A_mul_B!(A, eye(T, size(A.factors,2), size(A.factors,1))) - end -end - -size(A::LQ, dim::Integer) = size(A.factors, dim) -size(A::LQ) = size(A.factors) -function size(A::LQPackedQ, dim::Integer) - if 0 < dim && dim <= 2 - return size(A.factors, dim) - elseif 0 < dim && dim > 2 - return 1 - else - throw(BoundsError()) - end -end - -size(A::LQPackedQ) = size(A.factors) - -## Multiplication by LQ -A_mul_B!(A::LQ{T}, B::StridedVecOrMat{T}) where {T<:BlasFloat} = A[:L]*LAPACK.ormlq!('L','N',A.factors,A.τ,B) -A_mul_B!(A::LQ{T}, B::QR{T}) where {T<:BlasFloat} = A[:L]*LAPACK.ormlq!('L','N',A.factors,A.τ,full(B)) -A_mul_B!(A::QR{T}, B::LQ{T}) where {T<:BlasFloat} = A_mul_B!(zeros(full(A)), full(A), full(B)) -function *(A::LQ{TA}, B::StridedVecOrMat{TB}) where {TA,TB} - TAB = promote_type(TA, TB) - A_mul_B!(convert(Factorization{TAB},A), copy_oftype(B, TAB)) -end -function *(A::LQ{TA},B::QR{TB}) where {TA,TB} - TAB = promote_type(TA, TB) - A_mul_B!(convert(Factorization{TAB},A), convert(Factorization{TAB},B)) -end -function *(A::QR{TA},B::LQ{TB}) where {TA,TB} - TAB = promote_type(TA, TB) - A_mul_B!(convert(Factorization{TAB},A), convert(Factorization{TAB},B)) -end - -## Multiplication by Q -### QB -A_mul_B!(A::LQPackedQ{T}, B::StridedVecOrMat{T}) where {T<:BlasFloat} = LAPACK.ormlq!('L','N',A.factors,A.τ,B) -function (*)(A::LQPackedQ, B::StridedVecOrMat) - TAB = promote_type(eltype(A), eltype(B)) - A_mul_B!(convert(AbstractMatrix{TAB}, A), copy_oftype(B, TAB)) -end - -### QcB -Ac_mul_B!(A::LQPackedQ{T}, B::StridedVecOrMat{T}) where {T<:BlasReal} = LAPACK.ormlq!('L','T',A.factors,A.τ,B) -Ac_mul_B!(A::LQPackedQ{T}, B::StridedVecOrMat{T}) where {T<:BlasComplex} = LAPACK.ormlq!('L','C',A.factors,A.τ,B) -function Ac_mul_B(A::LQPackedQ, B::StridedVecOrMat) - TAB = promote_type(eltype(A), eltype(B)) - if size(B,1) == size(A.factors,2) - Ac_mul_B!(convert(AbstractMatrix{TAB}, A), copy_oftype(B, TAB)) - elseif size(B,1) == size(A.factors,1) - Ac_mul_B!(convert(AbstractMatrix{TAB}, A), [B; zeros(TAB, size(A.factors, 2) - size(A.factors, 1), size(B, 2))]) - else - throw(DimensionMismatch("first dimension of B, $(size(B,1)), must equal one of the dimensions of A, $(size(A))")) - end -end - -### QBc/QcBc -for (f1, f2) in ((:A_mul_Bc, :A_mul_B!), - (:Ac_mul_Bc, :Ac_mul_B!)) - @eval begin - function ($f1)(A::LQPackedQ, B::StridedVecOrMat) - TAB = promote_type(eltype(A), eltype(B)) - BB = similar(B, TAB, (size(B, 2), size(B, 1))) - ctranspose!(BB, B) - return ($f2)(A, BB) - end - end -end - -### AQ -A_mul_B!(A::StridedMatrix{T}, B::LQPackedQ{T}) where {T<:BlasFloat} = LAPACK.ormlq!('R', 'N', B.factors, B.τ, A) -function *(A::StridedMatrix{TA}, B::LQPackedQ{TB}) where {TA,TB} - TAB = promote_type(TA,TB) - if size(B.factors,2) == size(A,2) - A_mul_B!(copy_oftype(A, TAB),convert(AbstractMatrix{TAB},B)) - elseif size(B.factors,1) == size(A,2) - A_mul_B!( [A zeros(TAB, size(A,1), size(B.factors,2)-size(B.factors,1))], convert(AbstractMatrix{TAB},B)) - else - throw(DimensionMismatch("second dimension of A, $(size(A,2)), must equal one of the dimensions of B, $(size(B))")) - end -end - -### AQc -A_mul_Bc!(A::StridedMatrix{T}, B::LQPackedQ{T}) where {T<:BlasReal} = LAPACK.ormlq!('R','T',B.factors,B.τ,A) -A_mul_Bc!(A::StridedMatrix{T}, B::LQPackedQ{T}) where {T<:BlasComplex} = LAPACK.ormlq!('R','C',B.factors,B.τ,A) -function A_mul_Bc(A::StridedVecOrMat{TA}, B::LQPackedQ{TB}) where {TA<:Number,TB<:Number} - TAB = promote_type(TA,TB) - A_mul_Bc!(copy_oftype(A, TAB), convert(AbstractMatrix{TAB},(B))) -end - -### AcQ/AcQc -for (f1, f2) in ((:Ac_mul_B, :A_mul_B!), - (:Ac_mul_Bc, :A_mul_Bc!)) - @eval begin - function ($f1)(A::StridedMatrix, B::LQPackedQ) - TAB = promote_type(eltype(A), eltype(B)) - AA = similar(A, TAB, (size(A, 2), size(A, 1))) - ctranspose!(AA, A) - return ($f2)(AA, B) - end - end -end - -function (\)(A::LQ{TA}, b::StridedVector{Tb}) where {TA,Tb} - S = promote_type(TA,Tb) - m = checksquare(A) - m == length(b) || throw(DimensionMismatch("left hand side has $m rows, but right hand side has length $(length(b))")) - AA = convert(Factorization{S}, A) - x = A_ldiv_B!(AA, copy_oftype(b, S)) - return x -end -function (\)(A::LQ{TA},B::StridedMatrix{TB}) where {TA,TB} - S = promote_type(TA,TB) - m = checksquare(A) - m == size(B,1) || throw(DimensionMismatch("left hand side has $m rows, but right hand side has $(size(B,1)) rows")) - AA = convert(Factorization{S}, A) - X = A_ldiv_B!(AA, copy_oftype(B, S)) - return X -end -# With a real lhs and complex rhs with the same precision, we can reinterpret -# the complex rhs as a real rhs with twice the number of columns -function (\)(F::LQ{T}, B::VecOrMat{Complex{T}}) where T<:BlasReal - c2r = reshape(transpose(reinterpret(T, B, (2, length(B)))), size(B, 1), 2*size(B, 2)) - x = A_ldiv_B!(F, c2r) - return reinterpret(Complex{T}, transpose(reshape(x, div(length(x), 2), 2)), - isa(B, AbstractVector) ? (size(F,2),) : (size(F,2), size(B,2))) -end - - -function A_ldiv_B!(A::LQ{T}, B::StridedVecOrMat{T}) where T - Ac_mul_B!(A[:Q], A_ldiv_B!(LowerTriangular(A[:L]),B)) - return B -end diff --git a/julia-0.6.3/share/julia/base/linalg/lu.jl b/julia-0.6.3/share/julia/base/linalg/lu.jl deleted file mode 100644 index 7105bf3..0000000 --- a/julia-0.6.3/share/julia/base/linalg/lu.jl +++ /dev/null @@ -1,563 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -#################### -# LU Factorization # -#################### -struct LU{T,S<:AbstractMatrix} <: Factorization{T} - factors::S - ipiv::Vector{BlasInt} - info::BlasInt - LU{T,S}(factors::AbstractMatrix{T}, ipiv::Vector{BlasInt}, info::BlasInt) where {T,S} = new(factors, ipiv, info) -end -LU(factors::AbstractMatrix{T}, ipiv::Vector{BlasInt}, info::BlasInt) where {T} = LU{T,typeof(factors)}(factors, ipiv, info) - -# StridedMatrix -function lufact!(A::StridedMatrix{T}, pivot::Union{Type{Val{false}}, Type{Val{true}}} = Val{true}) where T<:BlasFloat - if pivot === Val{false} - return generic_lufact!(A, pivot) - end - lpt = LAPACK.getrf!(A) - return LU{T,typeof(A)}(lpt[1], lpt[2], lpt[3]) -end - -""" - lufact!(A, pivot=Val{true}) -> LU - -`lufact!` is the same as [`lufact`](@ref), but saves space by overwriting the -input `A`, instead of creating a copy. An [`InexactError`](@ref) -exception is thrown if the factorization produces a number not representable by the -element type of `A`, e.g. for integer types. -""" -lufact!(A::StridedMatrix, pivot::Union{Type{Val{false}}, Type{Val{true}}} = Val{true}) = generic_lufact!(A, pivot) -function generic_lufact!(A::StridedMatrix{T}, ::Type{Val{Pivot}} = Val{true}) where {T,Pivot} - m, n = size(A) - minmn = min(m,n) - info = 0 - ipiv = Vector{BlasInt}(minmn) - @inbounds begin - for k = 1:minmn - # find index max - kp = k - if Pivot - amax = real(zero(T)) - for i = k:m - absi = abs(A[i,k]) - if absi > amax - kp = i - amax = absi - end - end - end - ipiv[k] = kp - if A[kp,k] != 0 - if k != kp - # Interchange - for i = 1:n - tmp = A[k,i] - A[k,i] = A[kp,i] - A[kp,i] = tmp - end - end - # Scale first column - Akkinv = inv(A[k,k]) - for i = k+1:m - A[i,k] *= Akkinv - end - elseif info == 0 - info = k - end - # Update the rest - for j = k+1:n - for i = k+1:m - A[i,j] -= A[i,k]*A[k,j] - end - end - end - end - LU{T,typeof(A)}(A, ipiv, convert(BlasInt, info)) -end - -# floating point types doesn't have to be promoted for LU, but should default to pivoting -lufact(A::Union{AbstractMatrix{T}, AbstractMatrix{Complex{T}}}, - pivot::Union{Type{Val{false}}, Type{Val{true}}} = Val{true}) where {T<:AbstractFloat} = - lufact!(copy(A), pivot) - -# for all other types we must promote to a type which is stable under division -""" - lufact(A [,pivot=Val{true}]) -> F::LU - -Compute the LU factorization of `A`. - -In most cases, if `A` is a subtype `S` of `AbstractMatrix{T}` with an element -type `T` supporting `+`, `-`, `*` and `/`, the return type is `LU{T,S{T}}`. If -pivoting is chosen (default) the element type should also support `abs` and -`<`. - -The individual components of the factorization `F` can be accessed by indexing: - -| Component | Description | -|:----------|:------------------------------------| -| `F[:L]` | `L` (lower triangular) part of `LU` | -| `F[:U]` | `U` (upper triangular) part of `LU` | -| `F[:p]` | (right) permutation `Vector` | -| `F[:P]` | (right) permutation `Matrix` | - -The relationship between `F` and `A` is - -`F[:L]*F[:U] == A[F[:p], :]` - -`F` further supports the following functions: - -| Supported function | `LU` | `LU{T,Tridiagonal{T}}` | -|:---------------------------------|:-----|:-----------------------| -| [`/`](@ref) | ✓ | | -| [`\\`](@ref) | ✓ | ✓ | -| [`cond`](@ref) | ✓ | | -| [`inv`](@ref) | ✓ | ✓ | -| [`det`](@ref) | ✓ | ✓ | -| [`logdet`](@ref) | ✓ | ✓ | -| [`logabsdet`](@ref) | ✓ | ✓ | -| [`size`](@ref) | ✓ | ✓ | - -# Example - -```jldoctest -julia> A = [4 3; 6 3] -2×2 Array{Int64,2}: - 4 3 - 6 3 - -julia> F = lufact(A) -Base.LinAlg.LU{Float64,Array{Float64,2}} with factors L and U: -[1.0 0.0; 1.5 1.0] -[4.0 3.0; 0.0 -1.5] - -julia> F[:L] * F[:U] == A[F[:p], :] -true -``` -""" -function lufact(A::AbstractMatrix{T}, pivot::Union{Type{Val{false}}, Type{Val{true}}}) where T - S = typeof(zero(T)/one(T)) - AA = similar(A, S, size(A)) - copy!(AA, A) - lufact!(AA, pivot) -end -# We can't assume an ordered field so we first try without pivoting -function lufact(A::AbstractMatrix{T}) where T - S = typeof(zero(T)/one(T)) - AA = similar(A, S, size(A)) - copy!(AA, A) - F = lufact!(AA, Val{false}) - if F.info == 0 - return F - else - AA = similar(A, S, size(A)) - copy!(AA, A) - return lufact!(AA, Val{true}) - end -end - -lufact(x::Number) = LU(fill(x, 1, 1), BlasInt[1], x == 0 ? one(BlasInt) : zero(BlasInt)) -lufact(F::LU) = F - -lu(x::Number) = (one(x), x, 1) - -""" - lu(A, pivot=Val{true}) -> L, U, p - -Compute the LU factorization of `A`, such that `A[p,:] = L*U`. -By default, pivoting is used. This can be overridden by passing -`Val{false}` for the second argument. - -See also [`lufact`](@ref). - -# Example - -```jldoctest -julia> A = [4. 3.; 6. 3.] -2×2 Array{Float64,2}: - 4.0 3.0 - 6.0 3.0 - -julia> L, U, p = lu(A) -([1.0 0.0; 0.666667 1.0], [6.0 3.0; 0.0 1.0], [2, 1]) - -julia> A[p, :] == L * U -true -``` -""" -function lu(A::AbstractMatrix, pivot::Union{Type{Val{false}}, Type{Val{true}}} = Val{true}) - F = lufact(A, pivot) - F[:L], F[:U], F[:p] -end - -function convert(::Type{LU{T}}, F::LU) where T - M = convert(AbstractMatrix{T}, F.factors) - LU{T,typeof(M)}(M, F.ipiv, F.info) -end -convert(::Type{LU{T,S}}, F::LU) where {T,S} = LU{T,S}(convert(S, F.factors), F.ipiv, F.info) -convert(::Type{Factorization{T}}, F::LU{T}) where {T} = F -convert(::Type{Factorization{T}}, F::LU) where {T} = convert(LU{T}, F) - - -size(A::LU) = size(A.factors) -size(A::LU,n) = size(A.factors,n) - -function ipiv2perm(v::AbstractVector{T}, maxi::Integer) where T - p = T[1:maxi;] - @inbounds for i in 1:length(v) - p[i], p[v[i]] = p[v[i]], p[i] - end - return p -end - -function getindex(F::LU{T,<:StridedMatrix}, d::Symbol) where T - m, n = size(F) - if d == :L - L = tril!(F.factors[1:m, 1:min(m,n)]) - for i = 1:min(m,n); L[i,i] = one(T); end - return L - elseif d == :U - return triu!(F.factors[1:min(m,n), 1:n]) - elseif d == :p - return ipiv2perm(F.ipiv, m) - elseif d == :P - return eye(T, m)[:,invperm(F[:p])] - else - throw(KeyError(d)) - end -end - -function show(io::IO, C::LU) - println(io, "$(typeof(C)) with factors L and U:") - show(io, C[:L]) - println(io) - show(io, C[:U]) -end - -A_ldiv_B!(A::LU{T,<:StridedMatrix}, B::StridedVecOrMat{T}) where {T<:BlasFloat} = - @assertnonsingular LAPACK.getrs!('N', A.factors, A.ipiv, B) A.info -A_ldiv_B!(A::LU{<:Any,<:StridedMatrix}, b::StridedVector) = - A_ldiv_B!(UpperTriangular(A.factors), - A_ldiv_B!(UnitLowerTriangular(A.factors), b[ipiv2perm(A.ipiv, length(b))])) -A_ldiv_B!(A::LU{<:Any,<:StridedMatrix}, B::StridedMatrix) = - A_ldiv_B!(UpperTriangular(A.factors), - A_ldiv_B!(UnitLowerTriangular(A.factors), B[ipiv2perm(A.ipiv, size(B, 1)),:])) - -At_ldiv_B!(A::LU{T,<:StridedMatrix}, B::StridedVecOrMat{T}) where {T<:BlasFloat} = - @assertnonsingular LAPACK.getrs!('T', A.factors, A.ipiv, B) A.info -At_ldiv_B!(A::LU{<:Any,<:StridedMatrix}, b::StridedVector) = - At_ldiv_B!(UnitLowerTriangular(A.factors), - At_ldiv_B!(UpperTriangular(A.factors), b))[invperm(ipiv2perm(A.ipiv, length(b)))] -At_ldiv_B!(A::LU{<:Any,<:StridedMatrix}, B::StridedMatrix) = - At_ldiv_B!(UnitLowerTriangular(A.factors), - At_ldiv_B!(UpperTriangular(A.factors), B))[invperm(ipiv2perm(A.ipiv, size(B,1))),:] - -Ac_ldiv_B!(F::LU{T,<:StridedMatrix}, B::StridedVecOrMat{T}) where {T<:Real} = - At_ldiv_B!(F, B) -Ac_ldiv_B!(A::LU{T,<:StridedMatrix}, B::StridedVecOrMat{T}) where {T<:BlasComplex} = - @assertnonsingular LAPACK.getrs!('C', A.factors, A.ipiv, B) A.info -Ac_ldiv_B!(A::LU{<:Any,<:StridedMatrix}, b::StridedVector) = - Ac_ldiv_B!(UnitLowerTriangular(A.factors), - Ac_ldiv_B!(UpperTriangular(A.factors), b))[invperm(ipiv2perm(A.ipiv, length(b)))] -Ac_ldiv_B!(A::LU{<:Any,<:StridedMatrix}, B::StridedMatrix) = - Ac_ldiv_B!(UnitLowerTriangular(A.factors), - Ac_ldiv_B!(UpperTriangular(A.factors), B))[invperm(ipiv2perm(A.ipiv, size(B,1))),:] - -At_ldiv_Bt(A::LU{T,<:StridedMatrix}, B::StridedVecOrMat{T}) where {T<:BlasFloat} = - @assertnonsingular LAPACK.getrs!('T', A.factors, A.ipiv, transpose(B)) A.info -At_ldiv_Bt(A::LU, B::StridedVecOrMat) = At_ldiv_B(A, transpose(B)) - -Ac_ldiv_Bc(A::LU{T,<:StridedMatrix}, B::StridedVecOrMat{T}) where {T<:BlasComplex} = - @assertnonsingular LAPACK.getrs!('C', A.factors, A.ipiv, ctranspose(B)) A.info -Ac_ldiv_Bc(A::LU, B::StridedVecOrMat) = Ac_ldiv_B(A, ctranspose(B)) - -function det(A::LU{T}) where T - n = checksquare(A) - A.info > 0 && return zero(T) - P = one(T) - c = 0 - @inbounds for i = 1:n - P *= A.factors[i,i] - if A.ipiv[i] != i - c += 1 - end - end - s = (isodd(c) ? -one(T) : one(T)) - return P * s -end - -function logabsdet(A::LU{T}) where T # return log(abs(det)) and sign(det) - n = checksquare(A) - A.info > 0 && return log(zero(real(T))), log(one(T)) - c = 0 - P = one(T) - abs_det = zero(real(T)) - @inbounds for i = 1:n - dg_ii = A.factors[i,i] - P *= sign(dg_ii) - if A.ipiv[i] != i - c += 1 - end - abs_det += log(abs(dg_ii)) - end - s = ifelse(isodd(c), -one(real(T)), one(real(T))) * P - abs_det, s -end - -inv!(A::LU{<:BlasFloat,<:StridedMatrix}) = - @assertnonsingular LAPACK.getri!(A.factors, A.ipiv) A.info -inv(A::LU{<:BlasFloat,<:StridedMatrix}) = - inv!(LU(copy(A.factors), copy(A.ipiv), copy(A.info))) - -cond(A::LU{<:BlasFloat,<:StridedMatrix}, p::Number) = - inv(LAPACK.gecon!(p == 1 ? '1' : 'I', A.factors, norm((A[:L]*A[:U])[A[:p],:], p))) -cond(A::LU, p::Number) = norm(A[:L]*A[:U],p)*norm(inv(A),p) - -# Tridiagonal - -# See dgttrf.f -function lufact!(A::Tridiagonal{T}, pivot::Union{Type{Val{false}}, Type{Val{true}}} = Val{true}) where T - n = size(A, 1) - info = 0 - ipiv = Vector{BlasInt}(n) - dl = A.dl - d = A.d - du = A.du - du2 = A.du2 - - @inbounds begin - for i = 1:n - ipiv[i] = i - end - for i = 1:n-2 - # pivot or not? - if pivot === Val{false} || abs(d[i]) >= abs(dl[i]) - # No interchange - if d[i] != 0 - fact = dl[i]/d[i] - dl[i] = fact - d[i+1] -= fact*du[i] - du2[i] = 0 - end - else - # Interchange - fact = d[i]/dl[i] - d[i] = dl[i] - dl[i] = fact - tmp = du[i] - du[i] = d[i+1] - d[i+1] = tmp - fact*d[i+1] - du2[i] = du[i+1] - du[i+1] = -fact*du[i+1] - ipiv[i] = i+1 - end - end - if n > 1 - i = n-1 - if pivot === Val{false} || abs(d[i]) >= abs(dl[i]) - if d[i] != 0 - fact = dl[i]/d[i] - dl[i] = fact - d[i+1] -= fact*du[i] - end - else - fact = d[i]/dl[i] - d[i] = dl[i] - dl[i] = fact - tmp = du[i] - du[i] = d[i+1] - d[i+1] = tmp - fact*d[i+1] - ipiv[i] = i+1 - end - end - # check for a zero on the diagonal of U - for i = 1:n - if d[i] == 0 - info = i - break - end - end - end - LU{T,Tridiagonal{T}}(A, ipiv, convert(BlasInt, info)) -end - -factorize(A::Tridiagonal) = lufact(A) - -function getindex(F::Base.LinAlg.LU{T,Tridiagonal{T}}, d::Symbol) where T - m, n = size(F) - if d == :L - L = Array(Bidiagonal(ones(T, n), F.factors.dl, false)) - for i = 2:n - tmp = L[F.ipiv[i], 1:i - 1] - L[F.ipiv[i], 1:i - 1] = L[i, 1:i - 1] - L[i, 1:i - 1] = tmp - end - return L - elseif d == :U - U = Array(Bidiagonal(F.factors.d, F.factors.du, true)) - for i = 1:n - 2 - U[i,i + 2] = F.factors.du2[i] - end - return U - elseif d == :p - return ipiv2perm(F.ipiv, m) - elseif d == :P - return eye(T, m)[:,invperm(F[:p])] - end - throw(KeyError(d)) -end - -# See dgtts2.f -function A_ldiv_B!(A::LU{T,Tridiagonal{T}}, B::AbstractVecOrMat) where T - n = size(A,1) - if n != size(B,1) - throw(DimensionMismatch("matrix has dimensions ($n,$n) but right hand side has $(size(B,1)) rows")) - end - nrhs = size(B,2) - dl = A.factors.dl - d = A.factors.d - du = A.factors.du - du2 = A.factors.du2 - ipiv = A.ipiv - @inbounds begin - for j = 1:nrhs - for i = 1:n-1 - ip = ipiv[i] - tmp = B[i+1-ip+i,j] - dl[i]*B[ip,j] - B[i,j] = B[ip,j] - B[i+1,j] = tmp - end - B[n,j] /= d[n] - if n > 1 - B[n-1,j] = (B[n-1,j] - du[n-1]*B[n,j])/d[n-1] - end - for i = n-2:-1:1 - B[i,j] = (B[i,j] - du[i]*B[i+1,j] - du2[i]*B[i+2,j])/d[i] - end - end - end - return B -end - -function At_ldiv_B!(A::LU{T,Tridiagonal{T}}, B::AbstractVecOrMat) where T - n = size(A,1) - if n != size(B,1) - throw(DimensionMismatch("matrix has dimensions ($n,$n) but right hand side has $(size(B,1)) rows")) - end - nrhs = size(B,2) - dl = A.factors.dl - d = A.factors.d - du = A.factors.du - du2 = A.factors.du2 - ipiv = A.ipiv - @inbounds begin - for j = 1:nrhs - B[1,j] /= d[1] - if n > 1 - B[2,j] = (B[2,j] - du[1]*B[1,j])/d[2] - end - for i = 3:n - B[i,j] = (B[i,j] - du[i-1]*B[i-1,j] - du2[i-2]*B[i-2,j])/d[i] - end - for i = n-1:-1:1 - if ipiv[i] == i - B[i,j] = B[i,j] - dl[i]*B[i+1,j] - else - tmp = B[i+1,j] - B[i+1,j] = B[i,j] - dl[i]*tmp - B[i,j] = tmp - end - end - end - end - return B -end - -# Ac_ldiv_B!(A::LU{T,Tridiagonal{T}}, B::AbstractVecOrMat) where {T<:Real} = At_ldiv_B!(A,B) -function Ac_ldiv_B!(A::LU{T,Tridiagonal{T}}, B::AbstractVecOrMat) where T - n = size(A,1) - if n != size(B,1) - throw(DimensionMismatch("matrix has dimensions ($n,$n) but right hand side has $(size(B,1)) rows")) - end - nrhs = size(B,2) - dl = A.factors.dl - d = A.factors.d - du = A.factors.du - du2 = A.factors.du2 - ipiv = A.ipiv - @inbounds begin - for j = 1:nrhs - B[1,j] /= conj(d[1]) - if n > 1 - B[2,j] = (B[2,j] - conj(du[1])*B[1,j])/conj(d[2]) - end - for i = 3:n - B[i,j] = (B[i,j] - conj(du[i-1])*B[i-1,j] - conj(du2[i-2])*B[i-2,j])/conj(d[i]) - end - for i = n-1:-1:1 - if ipiv[i] == i - B[i,j] = B[i,j] - conj(dl[i])*B[i+1,j] - else - tmp = B[i+1,j] - B[i+1,j] = B[i,j] - conj(dl[i])*tmp - B[i,j] = tmp - end - end - end - end - return B -end - -/(B::AbstractMatrix,A::LU) = At_ldiv_Bt(A,B).' - -# Conversions -convert(::Type{AbstractMatrix}, F::LU) = (F[:L] * F[:U])[invperm(F[:p]),:] -convert(::Type{AbstractArray}, F::LU) = convert(AbstractMatrix, F) -convert(::Type{Matrix}, F::LU) = convert(Array, convert(AbstractArray, F)) -convert(::Type{Array}, F::LU) = convert(Matrix, F) -full(F::LU) = convert(AbstractArray, F) - -function convert(::Type{Tridiagonal}, F::Base.LinAlg.LU{T,Tridiagonal{T}}) where T - n = size(F, 1) - - dl = copy(F.factors.dl) - d = copy(F.factors.d) - du = copy(F.factors.du) - du2 = copy(F.factors.du2) - - for i = n - 1:-1:1 - li = dl[i] - dl[i] = li*d[i] - d[i + 1] += li*du[i] - if i < n - 1 - du[i + 1] += li*du2[i] - end - - if F.ipiv[i] != i - tmp = dl[i] - dl[i] = d[i] - d[i] = tmp - - tmp = d[i + 1] - d[i + 1] = du[i] - du[i] = tmp - - if i < n - 1 - tmp = du[i + 1] - du[i + 1] = du2[i] - du2[i] = tmp - end - end - end - return Tridiagonal(dl, d, du) -end -convert(::Type{AbstractMatrix}, F::Base.LinAlg.LU{T,Tridiagonal{T}}) where {T} = - convert(Tridiagonal, F) -convert(::Type{AbstractArray}, F::Base.LinAlg.LU{T,Tridiagonal{T}}) where {T} = - convert(AbstractMatrix, F) -convert(::Type{Matrix}, F::Base.LinAlg.LU{T,Tridiagonal{T}}) where {T} = - convert(Array, convert(AbstractArray, F)) -convert(::Type{Array}, F::Base.LinAlg.LU{T,Tridiagonal{T}}) where {T} = - convert(Matrix, F) -full(F::Base.LinAlg.LU{T,Tridiagonal{T}}) where {T} = convert(AbstractArray, F) diff --git a/julia-0.6.3/share/julia/base/linalg/matmul.jl b/julia-0.6.3/share/julia/base/linalg/matmul.jl deleted file mode 100644 index 0fce02c..0000000 --- a/julia-0.6.3/share/julia/base/linalg/matmul.jl +++ /dev/null @@ -1,738 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -# matmul.jl: Everything to do with dense matrix multiplication - -matprod(x, y) = x*y + x*y - -# multiply by diagonal matrix as vector -function scale!(C::AbstractMatrix, A::AbstractMatrix, b::AbstractVector) - m, n = size(A) - if size(A) != size(C) - throw(DimensionMismatch("size of A, $(size(A)), does not match size of C, $(size(C))")) - end - if n != length(b) - throw(DimensionMismatch("second dimension of A, $n, does not match length of b, $(length(b))")) - end - @inbounds for j = 1:n - bj = b[j] - for i = 1:m - C[i,j] = A[i,j]*bj - end - end - C -end - -function scale!(C::AbstractMatrix, b::AbstractVector, A::AbstractMatrix) - m, n = size(A) - if size(A) != size(C) - throw(DimensionMismatch("size of A, $(size(A)), does not match size of C, $(size(C))")) - end - if m != length(b) - throw(DimensionMismatch("first dimension of A, $m, does not match length of b, $(length(b))")) - end - @inbounds for j = 1:n, i = 1:m - C[i,j] = A[i,j]*b[i] - end - C -end - -# Dot products - -vecdot(x::Union{DenseArray{T},StridedVector{T}}, y::Union{DenseArray{T},StridedVector{T}}) where {T<:BlasReal} = BLAS.dot(x, y) -vecdot(x::Union{DenseArray{T},StridedVector{T}}, y::Union{DenseArray{T},StridedVector{T}}) where {T<:BlasComplex} = BLAS.dotc(x, y) - -function dot(x::Vector{T}, rx::Union{UnitRange{TI},Range{TI}}, y::Vector{T}, ry::Union{UnitRange{TI},Range{TI}}) where {T<:BlasReal,TI<:Integer} - if length(rx) != length(ry) - throw(DimensionMismatch("length of rx, $(length(rx)), does not equal length of ry, $(length(ry))")) - end - if minimum(rx) < 1 || maximum(rx) > length(x) - throw(BoundsError(x, rx)) - end - if minimum(ry) < 1 || maximum(ry) > length(y) - throw(BoundsError(y, ry)) - end - BLAS.dot(length(rx), pointer(x)+(first(rx)-1)*sizeof(T), step(rx), pointer(y)+(first(ry)-1)*sizeof(T), step(ry)) -end - -function dot(x::Vector{T}, rx::Union{UnitRange{TI},Range{TI}}, y::Vector{T}, ry::Union{UnitRange{TI},Range{TI}}) where {T<:BlasComplex,TI<:Integer} - if length(rx) != length(ry) - throw(DimensionMismatch("length of rx, $(length(rx)), does not equal length of ry, $(length(ry))")) - end - if minimum(rx) < 1 || maximum(rx) > length(x) - throw(BoundsError(x, rx)) - end - if minimum(ry) < 1 || maximum(ry) > length(y) - throw(BoundsError(y, ry)) - end - BLAS.dotc(length(rx), pointer(x)+(first(rx)-1)*sizeof(T), step(rx), pointer(y)+(first(ry)-1)*sizeof(T), step(ry)) -end - -At_mul_B(x::StridedVector{T}, y::StridedVector{T}) where {T<:BlasComplex} = BLAS.dotu(x, y) - -# Matrix-vector multiplication -function (*)(A::StridedMatrix{T}, x::StridedVector{S}) where {T<:BlasFloat,S} - TS = promote_op(matprod, T, S) - A_mul_B!(similar(x, TS, size(A,1)), A, convert(AbstractVector{TS}, x)) -end -function (*)(A::AbstractMatrix{T}, x::AbstractVector{S}) where {T,S} - TS = promote_op(matprod, T, S) - A_mul_B!(similar(x,TS,size(A,1)),A,x) -end - -# these will throw a DimensionMismatch unless B has 1 row (or 1 col for transposed case): -A_mul_Bt(a::AbstractVector, B::AbstractMatrix) = A_mul_Bt(reshape(a,length(a),1),B) -A_mul_Bt(A::AbstractMatrix, b::AbstractVector) = A_mul_Bt(A,reshape(b,length(b),1)) -A_mul_Bc(a::AbstractVector, B::AbstractMatrix) = A_mul_Bc(reshape(a,length(a),1),B) -A_mul_Bc(A::AbstractMatrix, b::AbstractVector) = A_mul_Bc(A,reshape(b,length(b),1)) -(*)(a::AbstractVector, B::AbstractMatrix) = reshape(a,length(a),1)*B - -A_mul_B!(y::StridedVector{T}, A::StridedVecOrMat{T}, x::StridedVector{T}) where {T<:BlasFloat} = gemv!(y, 'N', A, x) -for elty in (Float32,Float64) - @eval begin - function A_mul_B!(y::StridedVector{Complex{$elty}}, A::StridedVecOrMat{Complex{$elty}}, x::StridedVector{$elty}) - Afl = reinterpret($elty,A,(2size(A,1),size(A,2))) - yfl = reinterpret($elty,y) - gemv!(yfl,'N',Afl,x) - return y - end - end -end -A_mul_B!(y::AbstractVector, A::AbstractVecOrMat, x::AbstractVector) = generic_matvecmul!(y, 'N', A, x) - -function At_mul_B(A::StridedMatrix{T}, x::StridedVector{S}) where {T<:BlasFloat,S} - TS = promote_op(matprod, T, S) - At_mul_B!(similar(x,TS,size(A,2)), A, convert(AbstractVector{TS}, x)) -end -function At_mul_B(A::AbstractMatrix{T}, x::AbstractVector{S}) where {T,S} - TS = promote_op(matprod, T, S) - At_mul_B!(similar(x,TS,size(A,2)), A, x) -end -At_mul_B!(y::StridedVector{T}, A::StridedVecOrMat{T}, x::StridedVector{T}) where {T<:BlasFloat} = gemv!(y, 'T', A, x) -At_mul_B!(y::AbstractVector, A::AbstractVecOrMat, x::AbstractVector) = generic_matvecmul!(y, 'T', A, x) - -function Ac_mul_B(A::StridedMatrix{T}, x::StridedVector{S}) where {T<:BlasFloat,S} - TS = promote_op(matprod, T, S) - Ac_mul_B!(similar(x,TS,size(A,2)),A,convert(AbstractVector{TS},x)) -end -function Ac_mul_B(A::AbstractMatrix{T}, x::AbstractVector{S}) where {T,S} - TS = promote_op(matprod, T, S) - Ac_mul_B!(similar(x,TS,size(A,2)), A, x) -end - -Ac_mul_B!(y::StridedVector{T}, A::StridedVecOrMat{T}, x::StridedVector{T}) where {T<:BlasReal} = At_mul_B!(y, A, x) -Ac_mul_B!(y::StridedVector{T}, A::StridedVecOrMat{T}, x::StridedVector{T}) where {T<:BlasComplex} = gemv!(y, 'C', A, x) -Ac_mul_B!(y::AbstractVector, A::AbstractVecOrMat, x::AbstractVector) = generic_matvecmul!(y, 'C', A, x) - -# Matrix-matrix multiplication - -""" -``` -*(A::AbstractMatrix, B::AbstractMatrix) -``` - -Matrix multiplication. - -# Example - -```jldoctest -julia> [1 1; 0 1] * [1 0; 1 1] -2×2 Array{Int64,2}: - 2 1 - 1 1 -``` -""" -function (*)(A::AbstractMatrix{T}, B::AbstractMatrix{S}) where {T,S} - TS = promote_op(matprod, T, S) - A_mul_B!(similar(B, TS, (size(A,1), size(B,2))), A, B) -end -A_mul_B!(C::StridedMatrix{T}, A::StridedVecOrMat{T}, B::StridedVecOrMat{T}) where {T<:BlasFloat} = gemm_wrapper!(C, 'N', 'N', A, B) -for elty in (Float32,Float64) - @eval begin - function A_mul_B!(C::StridedMatrix{Complex{$elty}}, A::StridedVecOrMat{Complex{$elty}}, B::StridedVecOrMat{$elty}) - Afl = reinterpret($elty, A, (2size(A,1), size(A,2))) - Cfl = reinterpret($elty, C, (2size(C,1), size(C,2))) - gemm_wrapper!(Cfl, 'N', 'N', Afl, B) - return C - end - end -end - -""" - A_mul_B!(Y, A, B) -> Y - -Calculates the matrix-matrix or matrix-vector product ``A⋅B`` and stores the result in `Y`, -overwriting the existing value of `Y`. Note that `Y` must not be aliased with either `A` or -`B`. - -# Example - -```jldoctest -julia> A=[1.0 2.0; 3.0 4.0]; B=[1.0 1.0; 1.0 1.0]; Y = similar(B); A_mul_B!(Y, A, B); - -julia> Y -2×2 Array{Float64,2}: - 3.0 3.0 - 7.0 7.0 -``` -""" -A_mul_B!(C::AbstractMatrix, A::AbstractVecOrMat, B::AbstractVecOrMat) = generic_matmatmul!(C, 'N', 'N', A, B) - -function At_mul_B(A::AbstractMatrix{T}, B::AbstractMatrix{S}) where {T,S} - TS = promote_op(matprod, T, S) - At_mul_B!(similar(B, TS, (size(A,2), size(B,2))), A, B) -end -At_mul_B!(C::StridedMatrix{T}, A::StridedVecOrMat{T}, B::StridedVecOrMat{T}) where {T<:BlasFloat} = A===B ? syrk_wrapper!(C, 'T', A) : gemm_wrapper!(C, 'T', 'N', A, B) -At_mul_B!(C::AbstractMatrix, A::AbstractVecOrMat, B::AbstractVecOrMat) = generic_matmatmul!(C, 'T', 'N', A, B) - -function A_mul_Bt(A::AbstractMatrix{T}, B::AbstractMatrix{S}) where {T,S} - TS = promote_op(matprod, T, S) - A_mul_Bt!(similar(B, TS, (size(A,1), size(B,1))), A, B) -end -A_mul_Bt!(C::StridedMatrix{T}, A::StridedVecOrMat{T}, B::StridedVecOrMat{T}) where {T<:BlasFloat} = A===B ? syrk_wrapper!(C, 'N', A) : gemm_wrapper!(C, 'N', 'T', A, B) -for elty in (Float32,Float64) - @eval begin - function A_mul_Bt!(C::StridedMatrix{Complex{$elty}}, A::StridedVecOrMat{Complex{$elty}}, B::StridedVecOrMat{$elty}) - Afl = reinterpret($elty, A, (2size(A,1), size(A,2))) - Cfl = reinterpret($elty, C, (2size(C,1), size(C,2))) - gemm_wrapper!(Cfl, 'N', 'T', Afl, B) - return C - end - end -end -A_mul_Bt!(C::AbstractVecOrMat, A::AbstractVecOrMat, B::AbstractVecOrMat) = generic_matmatmul!(C, 'N', 'T', A, B) - -function At_mul_Bt(A::AbstractMatrix{T}, B::AbstractVecOrMat{S}) where {T,S} - TS = promote_op(matprod, T, S) - At_mul_Bt!(similar(B, TS, (size(A,2), size(B,1))), A, B) -end -At_mul_Bt!(C::StridedMatrix{T}, A::StridedVecOrMat{T}, B::StridedVecOrMat{T}) where {T<:BlasFloat} = gemm_wrapper!(C, 'T', 'T', A, B) -At_mul_Bt!(C::AbstractMatrix, A::AbstractVecOrMat, B::AbstractVecOrMat) = generic_matmatmul!(C, 'T', 'T', A, B) - -Ac_mul_B(A::StridedMatrix{T}, B::StridedMatrix{T}) where {T<:BlasReal} = At_mul_B(A, B) -Ac_mul_B!(C::StridedMatrix{T}, A::StridedVecOrMat{T}, B::StridedVecOrMat{T}) where {T<:BlasReal} = At_mul_B!(C, A, B) -function Ac_mul_B(A::AbstractMatrix{T}, B::AbstractMatrix{S}) where {T,S} - TS = promote_op(matprod, T, S) - Ac_mul_B!(similar(B, TS, (size(A,2), size(B,2))), A, B) -end -Ac_mul_B!(C::StridedMatrix{T}, A::StridedVecOrMat{T}, B::StridedVecOrMat{T}) where {T<:BlasComplex} = A===B ? herk_wrapper!(C,'C',A) : gemm_wrapper!(C,'C', 'N', A, B) -Ac_mul_B!(C::AbstractMatrix, A::AbstractVecOrMat, B::AbstractVecOrMat) = generic_matmatmul!(C, 'C', 'N', A, B) - -A_mul_Bc(A::StridedMatrix{<:BlasFloat}, B::StridedMatrix{<:BlasReal}) = A_mul_Bt(A, B) -A_mul_Bc!(C::StridedMatrix{T}, A::StridedVecOrMat{T}, B::StridedVecOrMat{<:BlasReal}) where {T<:BlasFloat} = A_mul_Bt!(C, A, B) -function A_mul_Bc(A::AbstractMatrix{T}, B::AbstractMatrix{S}) where {T,S} - TS = promote_op(matprod, T, S) - A_mul_Bc!(similar(B,TS,(size(A,1),size(B,1))),A,B) -end -A_mul_Bc!(C::StridedMatrix{T}, A::StridedVecOrMat{T}, B::StridedVecOrMat{T}) where {T<:BlasComplex} = A===B ? herk_wrapper!(C, 'N', A) : gemm_wrapper!(C, 'N', 'C', A, B) -A_mul_Bc!(C::AbstractMatrix, A::AbstractVecOrMat, B::AbstractVecOrMat) = generic_matmatmul!(C, 'N', 'C', A, B) - -Ac_mul_Bc(A::AbstractMatrix{T}, B::AbstractMatrix{S}) where {T,S} = - Ac_mul_Bc!(similar(B, promote_op(matprod, T, S), (size(A,2), size(B,1))), A, B) -Ac_mul_Bc!(C::StridedMatrix{T}, A::StridedVecOrMat{T}, B::StridedVecOrMat{T}) where {T<:BlasFloat} = gemm_wrapper!(C, 'C', 'C', A, B) -Ac_mul_Bc!(C::AbstractMatrix, A::AbstractVecOrMat, B::AbstractVecOrMat) = generic_matmatmul!(C, 'C', 'C', A, B) -Ac_mul_Bt!(C::AbstractMatrix, A::AbstractVecOrMat, B::AbstractVecOrMat) = generic_matmatmul!(C, 'C', 'T', A, B) -# Supporting functions for matrix multiplication - -function copytri!(A::AbstractMatrix, uplo::Char, conjugate::Bool=false) - n = checksquare(A) - if uplo == 'U' - for i = 1:(n-1), j = (i+1):n - A[j,i] = conjugate ? conj(A[i,j]) : A[i,j] - end - elseif uplo == 'L' - for i = 1:(n-1), j = (i+1):n - A[i,j] = conjugate ? conj(A[j,i]) : A[j,i] - end - else - throw(ArgumentError("uplo argument must be 'U' (upper) or 'L' (lower), got $uplo")) - end - A -end - -function gemv!(y::StridedVector{T}, tA::Char, A::StridedVecOrMat{T}, x::StridedVector{T}) where T<:BlasFloat - mA, nA = lapack_size(tA, A) - if nA != length(x) - throw(DimensionMismatch("second dimension of A, $nA, does not match length of x, $(length(x))")) - end - if mA != length(y) - throw(DimensionMismatch("first dimension of A, $mA, does not match length of y, $(length(y))")) - end - if mA == 0 - return y - end - if nA == 0 - return fill!(y,0) - end - stride(A, 1) == 1 && stride(A, 2) >= size(A, 1) && return BLAS.gemv!(tA, one(T), A, x, zero(T), y) - return generic_matvecmul!(y, tA, A, x) -end - -function syrk_wrapper!(C::StridedMatrix{T}, tA::Char, A::StridedVecOrMat{T}) where T<:BlasFloat - nC = checksquare(C) - if tA == 'T' - (nA, mA) = size(A,1), size(A,2) - tAt = 'N' - else - (mA, nA) = size(A,1), size(A,2) - tAt = 'T' - end - if nC != mA - throw(DimensionMismatch("output matrix has size: $(nC), but should have size $(mA)")) - end - if mA == 0 || nA == 0 - return fill!(C,0) - end - if mA == 2 && nA == 2 - return matmul2x2!(C,tA,tAt,A,A) - end - if mA == 3 && nA == 3 - return matmul3x3!(C,tA,tAt,A,A) - end - - if stride(A, 1) == stride(C, 1) == 1 && stride(A, 2) >= size(A, 1) && stride(C, 2) >= size(C, 1) - return copytri!(BLAS.syrk!('U', tA, one(T), A, zero(T), C), 'U') - end - return generic_matmatmul!(C, tA, tAt, A, A) -end - -function herk_wrapper!(C::Union{StridedMatrix{T}, StridedMatrix{Complex{T}}}, tA::Char, A::Union{StridedVecOrMat{T}, StridedVecOrMat{Complex{T}}}) where T<:BlasReal - nC = checksquare(C) - if tA == 'C' - (nA, mA) = size(A,1), size(A,2) - tAt = 'N' - else - (mA, nA) = size(A,1), size(A,2) - tAt = 'C' - end - if nC != mA - throw(DimensionMismatch("output matrix has size: $(nC), but should have size $(mA)")) - end - if mA == 0 || nA == 0 - return fill!(C,0) - end - if mA == 2 && nA == 2 - return matmul2x2!(C,tA,tAt,A,A) - end - if mA == 3 && nA == 3 - return matmul3x3!(C,tA,tAt,A,A) - end - - # Result array does not need to be initialized as long as beta==0 - # C = Matrix{T}(mA, mA) - - if stride(A, 1) == stride(C, 1) == 1 && stride(A, 2) >= size(A, 1) && stride(C, 2) >= size(C, 1) - return copytri!(BLAS.herk!('U', tA, one(T), A, zero(T), C), 'U', true) - end - return generic_matmatmul!(C,tA, tAt, A, A) -end - -function gemm_wrapper(tA::Char, tB::Char, - A::StridedVecOrMat{T}, - B::StridedVecOrMat{T}) where T<:BlasFloat - mA, nA = lapack_size(tA, A) - mB, nB = lapack_size(tB, B) - C = similar(B, T, mA, nB) - gemm_wrapper!(C, tA, tB, A, B) -end - -function gemm_wrapper!(C::StridedVecOrMat{T}, tA::Char, tB::Char, - A::StridedVecOrMat{T}, - B::StridedVecOrMat{T}) where T<:BlasFloat - mA, nA = lapack_size(tA, A) - mB, nB = lapack_size(tB, B) - - if nA != mB - throw(DimensionMismatch("A has dimensions ($mA,$nA) but B has dimensions ($mB,$nB)")) - end - - if C === A || B === C - throw(ArgumentError("output matrix must not be aliased with input matrix")) - end - - if mA == 0 || nA == 0 || nB == 0 - if size(C) != (mA, nB) - throw(DimensionMismatch("C has dimensions $(size(C)), should have ($mA,$nB)")) - end - return fill!(C,0) - end - - if mA == 2 && nA == 2 && nB == 2 - return matmul2x2!(C,tA,tB,A,B) - end - if mA == 3 && nA == 3 && nB == 3 - return matmul3x3!(C,tA,tB,A,B) - end - - if stride(A, 1) == stride(B, 1) == stride(C, 1) == 1 && stride(A, 2) >= size(A, 1) && stride(B, 2) >= size(B, 1) && stride(C, 2) >= size(C, 1) - return BLAS.gemm!(tA, tB, one(T), A, B, zero(T), C) - end - generic_matmatmul!(C, tA, tB, A, B) -end - -# blas.jl defines matmul for floats; other integer and mixed precision -# cases are handled here - -lapack_size(t::Char, M::AbstractVecOrMat) = (size(M, t=='N' ? 1:2), size(M, t=='N' ? 2:1)) - -function copy!(B::AbstractVecOrMat, ir_dest::UnitRange{Int}, jr_dest::UnitRange{Int}, tM::Char, M::AbstractVecOrMat, ir_src::UnitRange{Int}, jr_src::UnitRange{Int}) - if tM == 'N' - copy!(B, ir_dest, jr_dest, M, ir_src, jr_src) - else - Base.copy_transpose!(B, ir_dest, jr_dest, M, jr_src, ir_src) - tM == 'C' && conj!(B) - end - B -end - -function copy_transpose!(B::AbstractMatrix, ir_dest::UnitRange{Int}, jr_dest::UnitRange{Int}, tM::Char, M::AbstractVecOrMat, ir_src::UnitRange{Int}, jr_src::UnitRange{Int}) - if tM == 'N' - Base.copy_transpose!(B, ir_dest, jr_dest, M, ir_src, jr_src) - else - copy!(B, ir_dest, jr_dest, M, jr_src, ir_src) - tM == 'C' && conj!(B) - end - B -end - -# TODO: It will be faster for large matrices to convert to float, -# call BLAS, and convert back to required type. - -# NOTE: the generic version is also called as fallback for -# strides != 1 cases - -function generic_matvecmul!(C::AbstractVector{R}, tA, A::AbstractVecOrMat, B::AbstractVector) where R - mB = length(B) - mA, nA = lapack_size(tA, A) - if mB != nA - throw(DimensionMismatch("matrix A has dimensions ($mA,$nA), vector B has length $mB")) - end - if mA != length(C) - throw(DimensionMismatch("result C has length $(length(C)), needs length $mA")) - end - - Astride = size(A, 1) - - if tA == 'T' # fastest case - for k = 1:mA - aoffs = (k-1)*Astride - if mB == 0 - s = zero(R) - else - s = zero(A[aoffs + 1]*B[1] + A[aoffs + 1]*B[1]) - end - for i = 1:nA - s += A[aoffs+i].'B[i] - end - C[k] = s - end - elseif tA == 'C' - for k = 1:mA - aoffs = (k-1)*Astride - if mB == 0 - s = zero(R) - else - s = zero(A[aoffs + 1]*B[1] + A[aoffs + 1]*B[1]) - end - for i = 1:nA - s += A[aoffs + i]'B[i] - end - C[k] = s - end - else # tA == 'N' - for i = 1:mA - if mB == 0 - C[i] = zero(R) - else - C[i] = zero(A[i]*B[1] + A[i]*B[1]) - end - end - for k = 1:mB - aoffs = (k-1)*Astride - b = B[k] - for i = 1:mA - C[i] += A[aoffs + i] * b - end - end - end - C -end - -function generic_matmatmul(tA, tB, A::AbstractVecOrMat{T}, B::AbstractMatrix{S}) where {T,S} - mA, nA = lapack_size(tA, A) - mB, nB = lapack_size(tB, B) - C = similar(B, promote_op(matprod, T, S), mA, nB) - generic_matmatmul!(C, tA, tB, A, B) -end - -const tilebufsize = 10800 # Approximately 32k/3 -const Abuf = Vector{UInt8}(tilebufsize) -const Bbuf = Vector{UInt8}(tilebufsize) -const Cbuf = Vector{UInt8}(tilebufsize) - -function generic_matmatmul!(C::AbstractMatrix, tA, tB, A::AbstractMatrix, B::AbstractMatrix) - mA, nA = lapack_size(tA, A) - mB, nB = lapack_size(tB, B) - mC, nC = size(C) - - if mA == nA == mB == nB == mC == nC == 2 - return matmul2x2!(C, tA, tB, A, B) - end - if mA == nA == mB == nB == mC == nC == 3 - return matmul3x3!(C, tA, tB, A, B) - end - _generic_matmatmul!(C, tA, tB, A, B) -end - -generic_matmatmul!(C::AbstractVecOrMat, tA, tB, A::AbstractVecOrMat, B::AbstractVecOrMat) = _generic_matmatmul!(C, tA, tB, A, B) - -function _generic_matmatmul!(C::AbstractVecOrMat{R}, tA, tB, A::AbstractVecOrMat{T}, B::AbstractVecOrMat{S}) where {T,S,R} - mA, nA = lapack_size(tA, A) - mB, nB = lapack_size(tB, B) - if mB != nA - throw(DimensionMismatch("matrix A has dimensions ($mA,$nA), matrix B has dimensions ($mB,$nB)")) - end - if size(C,1) != mA || size(C,2) != nB - throw(DimensionMismatch("result C has dimensions $(size(C)), needs ($mA,$nB)")) - end - if isempty(A) || isempty(B) - return fill!(C, zero(R)) - end - - tile_size = 0 - if isbits(R) && isbits(T) && isbits(S) && (tA == 'N' || tB != 'N') - tile_size = floor(Int, sqrt(tilebufsize / max(sizeof(R), sizeof(S), sizeof(T)))) - end - @inbounds begin - if tile_size > 0 - sz = (tile_size, tile_size) - Atile = unsafe_wrap(Array, convert(Ptr{T}, pointer(Abuf)), sz) - Btile = unsafe_wrap(Array, convert(Ptr{S}, pointer(Bbuf)), sz) - - z1 = zero(A[1, 1]*B[1, 1] + A[1, 1]*B[1, 1]) - z = convert(promote_type(typeof(z1), R), z1) - - if mA < tile_size && nA < tile_size && nB < tile_size - Base.copy_transpose!(Atile, 1:nA, 1:mA, tA, A, 1:mA, 1:nA) - copy!(Btile, 1:mB, 1:nB, tB, B, 1:mB, 1:nB) - for j = 1:nB - boff = (j-1)*tile_size - for i = 1:mA - aoff = (i-1)*tile_size - s = z - for k = 1:nA - s += Atile[aoff+k] * Btile[boff+k] - end - C[i,j] = s - end - end - else - Ctile = unsafe_wrap(Array, convert(Ptr{R}, pointer(Cbuf)), sz) - for jb = 1:tile_size:nB - jlim = min(jb+tile_size-1,nB) - jlen = jlim-jb+1 - for ib = 1:tile_size:mA - ilim = min(ib+tile_size-1,mA) - ilen = ilim-ib+1 - fill!(Ctile, z) - for kb = 1:tile_size:nA - klim = min(kb+tile_size-1,mB) - klen = klim-kb+1 - Base.copy_transpose!(Atile, 1:klen, 1:ilen, tA, A, ib:ilim, kb:klim) - copy!(Btile, 1:klen, 1:jlen, tB, B, kb:klim, jb:jlim) - for j=1:jlen - bcoff = (j-1)*tile_size - for i = 1:ilen - aoff = (i-1)*tile_size - s = z - for k = 1:klen - s += Atile[aoff+k] * Btile[bcoff+k] - end - Ctile[bcoff+i] += s - end - end - end - copy!(C, ib:ilim, jb:jlim, Ctile, 1:ilen, 1:jlen) - end - end - end - else - # Multiplication for non-plain-data uses the naive algorithm - - if tA == 'N' - if tB == 'N' - for i = 1:mA, j = 1:nB - z2 = zero(A[i, 1]*B[1, j] + A[i, 1]*B[1, j]) - Ctmp = convert(promote_type(R, typeof(z2)), z2) - for k = 1:nA - Ctmp += A[i, k]*B[k, j] - end - C[i,j] = Ctmp - end - elseif tB == 'T' - for i = 1:mA, j = 1:nB - z2 = zero(A[i, 1]*B[j, 1] + A[i, 1]*B[j, 1]) - Ctmp = convert(promote_type(R, typeof(z2)), z2) - for k = 1:nA - Ctmp += A[i, k]*B[j, k].' - end - C[i,j] = Ctmp - end - else - for i = 1:mA, j = 1:nB - z2 = zero(A[i, 1]*B[j, 1] + A[i, 1]*B[j, 1]) - Ctmp = convert(promote_type(R, typeof(z2)), z2) - for k = 1:nA - Ctmp += A[i, k]*B[j, k]' - end - C[i,j] = Ctmp - end - end - elseif tA == 'T' - if tB == 'N' - for i = 1:mA, j = 1:nB - z2 = zero(A[1, i]*B[1, j] + A[1, i]*B[1, j]) - Ctmp = convert(promote_type(R, typeof(z2)), z2) - for k = 1:nA - Ctmp += A[k, i].'B[k, j] - end - C[i,j] = Ctmp - end - elseif tB == 'T' - for i = 1:mA, j = 1:nB - z2 = zero(A[1, i]*B[j, 1] + A[1, i]*B[j, 1]) - Ctmp = convert(promote_type(R, typeof(z2)), z2) - for k = 1:nA - Ctmp += A[k, i].'B[j, k].' - end - C[i,j] = Ctmp - end - else - for i = 1:mA, j = 1:nB - z2 = zero(A[1, i]*B[j, 1] + A[1, i]*B[j, 1]) - Ctmp = convert(promote_type(R, typeof(z2)), z2) - for k = 1:nA - Ctmp += A[k, i].'B[j, k]' - end - C[i,j] = Ctmp - end - end - else - if tB == 'N' - for i = 1:mA, j = 1:nB - z2 = zero(A[1, i]*B[1, j] + A[1, i]*B[1, j]) - Ctmp = convert(promote_type(R, typeof(z2)), z2) - for k = 1:nA - Ctmp += A[k, i]'B[k, j] - end - C[i,j] = Ctmp - end - elseif tB == 'T' - for i = 1:mA, j = 1:nB - z2 = zero(A[1, i]*B[j, 1] + A[1, i]*B[j, 1]) - Ctmp = convert(promote_type(R, typeof(z2)), z2) - for k = 1:nA - Ctmp += A[k, i]'B[j, k].' - end - C[i,j] = Ctmp - end - else - for i = 1:mA, j = 1:nB - z2 = zero(A[1, i]*B[j, 1] + A[1, i]*B[j, 1]) - Ctmp = convert(promote_type(R, typeof(z2)), z2) - for k = 1:nA - Ctmp += A[k, i]'B[j, k]' - end - C[i,j] = Ctmp - end - end - end - end - end # @inbounds - C -end - - -# multiply 2x2 matrices -function matmul2x2(tA, tB, A::AbstractMatrix{T}, B::AbstractMatrix{S}) where {T,S} - matmul2x2!(similar(B, promote_op(matprod, T, S), 2, 2), tA, tB, A, B) -end - -function matmul2x2!(C::AbstractMatrix, tA, tB, A::AbstractMatrix, B::AbstractMatrix) - if !(size(A) == size(B) == size(C) == (2,2)) - throw(DimensionMismatch("A has size $(size(A)), B has size $(size(B)), C has size $(size(C))")) - end - @inbounds begin - if tA == 'T' - A11 = transpose(A[1,1]); A12 = transpose(A[2,1]); A21 = transpose(A[1,2]); A22 = transpose(A[2,2]) - elseif tA == 'C' - A11 = ctranspose(A[1,1]); A12 = ctranspose(A[2,1]); A21 = ctranspose(A[1,2]); A22 = ctranspose(A[2,2]) - else - A11 = A[1,1]; A12 = A[1,2]; A21 = A[2,1]; A22 = A[2,2] - end - if tB == 'T' - B11 = transpose(B[1,1]); B12 = transpose(B[2,1]); B21 = transpose(B[1,2]); B22 = transpose(B[2,2]) - elseif tB == 'C' - B11 = ctranspose(B[1,1]); B12 = ctranspose(B[2,1]); B21 = ctranspose(B[1,2]); B22 = ctranspose(B[2,2]) - else - B11 = B[1,1]; B12 = B[1,2]; B21 = B[2,1]; B22 = B[2,2] - end - C[1,1] = A11*B11 + A12*B21 - C[1,2] = A11*B12 + A12*B22 - C[2,1] = A21*B11 + A22*B21 - C[2,2] = A21*B12 + A22*B22 - end # inbounds - C -end - -# Multiply 3x3 matrices -function matmul3x3(tA, tB, A::AbstractMatrix{T}, B::AbstractMatrix{S}) where {T,S} - matmul3x3!(similar(B, promote_op(matprod, T, S), 3, 3), tA, tB, A, B) -end - -function matmul3x3!(C::AbstractMatrix, tA, tB, A::AbstractMatrix, B::AbstractMatrix) - if !(size(A) == size(B) == size(C) == (3,3)) - throw(DimensionMismatch("A has size $(size(A)), B has size $(size(B)), C has size $(size(C))")) - end - @inbounds begin - if tA == 'T' - A11 = transpose(A[1,1]); A12 = transpose(A[2,1]); A13 = transpose(A[3,1]) - A21 = transpose(A[1,2]); A22 = transpose(A[2,2]); A23 = transpose(A[3,2]) - A31 = transpose(A[1,3]); A32 = transpose(A[2,3]); A33 = transpose(A[3,3]) - elseif tA == 'C' - A11 = ctranspose(A[1,1]); A12 = ctranspose(A[2,1]); A13 = ctranspose(A[3,1]) - A21 = ctranspose(A[1,2]); A22 = ctranspose(A[2,2]); A23 = ctranspose(A[3,2]) - A31 = ctranspose(A[1,3]); A32 = ctranspose(A[2,3]); A33 = ctranspose(A[3,3]) - else - A11 = A[1,1]; A12 = A[1,2]; A13 = A[1,3] - A21 = A[2,1]; A22 = A[2,2]; A23 = A[2,3] - A31 = A[3,1]; A32 = A[3,2]; A33 = A[3,3] - end - - if tB == 'T' - B11 = transpose(B[1,1]); B12 = transpose(B[2,1]); B13 = transpose(B[3,1]) - B21 = transpose(B[1,2]); B22 = transpose(B[2,2]); B23 = transpose(B[3,2]) - B31 = transpose(B[1,3]); B32 = transpose(B[2,3]); B33 = transpose(B[3,3]) - elseif tB == 'C' - B11 = ctranspose(B[1,1]); B12 = ctranspose(B[2,1]); B13 = ctranspose(B[3,1]) - B21 = ctranspose(B[1,2]); B22 = ctranspose(B[2,2]); B23 = ctranspose(B[3,2]) - B31 = ctranspose(B[1,3]); B32 = ctranspose(B[2,3]); B33 = ctranspose(B[3,3]) - else - B11 = B[1,1]; B12 = B[1,2]; B13 = B[1,3] - B21 = B[2,1]; B22 = B[2,2]; B23 = B[2,3] - B31 = B[3,1]; B32 = B[3,2]; B33 = B[3,3] - end - - C[1,1] = A11*B11 + A12*B21 + A13*B31 - C[1,2] = A11*B12 + A12*B22 + A13*B32 - C[1,3] = A11*B13 + A12*B23 + A13*B33 - - C[2,1] = A21*B11 + A22*B21 + A23*B31 - C[2,2] = A21*B12 + A22*B22 + A23*B32 - C[2,3] = A21*B13 + A22*B23 + A23*B33 - - C[3,1] = A31*B11 + A32*B21 + A33*B31 - C[3,2] = A31*B12 + A32*B22 + A33*B32 - C[3,3] = A31*B13 + A32*B23 + A33*B33 - end # inbounds - C -end diff --git a/julia-0.6.3/share/julia/base/linalg/qr.jl b/julia-0.6.3/share/julia/base/linalg/qr.jl deleted file mode 100644 index 4425c67..0000000 --- a/julia-0.6.3/share/julia/base/linalg/qr.jl +++ /dev/null @@ -1,847 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -# QR and Hessenberg Factorizations -""" - QR <: Factorization - -A QR matrix factorization stored in a packed format, typically obtained from -[`qrfact`](@ref). If ``A`` is an `m`×`n` matrix, then - -```math -A = Q R -``` - -where ``Q`` is an orthogonal/unitary matrix and ``R`` is upper triangular. -The matrix ``Q`` is stored as a sequence of Householder reflectors ``v_i`` -and coefficients ``\\tau_i`` where: - -```math -Q = \\prod_{i=1}^{\\min(m,n)} (I - \\tau_i v_i v_i^T). -``` - -The object has two fields: - -* `factors` is an `m`×`n` matrix. - - - The upper triangular part contains the elements of ``R``, that is `R = - triu(F.factors)` for a `QR` object `F`. - - - The subdiagonal part contains the reflectors ``v_i`` stored in a packed format where - ``v_i`` is the ``i``th column of the matrix `V = eye(m,n) + tril(F.factors,-1)`. - -* `τ` is a vector of length `min(m,n)` containing the coefficients ``\tau_i``. - -""" -struct QR{T,S<:AbstractMatrix} <: Factorization{T} - factors::S - τ::Vector{T} - QR{T,S}(factors::AbstractMatrix{T}, τ::Vector{T}) where {T,S<:AbstractMatrix} = new(factors, τ) -end -QR(factors::AbstractMatrix{T}, τ::Vector{T}) where {T} = QR{T,typeof(factors)}(factors, τ) - -# Note. For QRCompactWY factorization without pivoting, the WY representation based method introduced in LAPACK 3.4 -""" - QRCompactWY <: Factorization - -A QR matrix factorization stored in a compact blocked format, typically obtained from -[`qrfact`](@ref). If ``A`` is an `m`×`n` matrix, then - -```math -A = Q R -``` - -where ``Q`` is an orthogonal/unitary matrix and ``R`` is upper triangular. It is similar -to the [`QR`](@ref) format except that the orthogonal/unitary matrix ``Q`` is stored in -*Compact WY* format [^Schreiber1989], as a lower trapezoidal matrix ``V`` and an upper -triangular matrix ``T`` where - -```math -Q = \\prod_{i=1}^{\\min(m,n)} (I - \\tau_i v_i v_i^T) = I - V T V^T -``` - -such that ``v_i`` is the ``i``th column of ``V``, and ``\tau_i`` is the ``i``th diagonal -element of ``T``. - -The object has two fields: - -* `factors`, as in the [`QR`](@ref) type, is an `m`×`n` matrix. - - - The upper triangular part contains the elements of ``R``, that is `R = - triu(F.factors)` for a `QR` object `F`. - - - The subdiagonal part contains the reflectors ``v_i`` stored in a packed format such - that `V = eye(m,n) + tril(F.factors,-1)`. - -* `T` is a square matrix with `min(m,n)` columns, whose upper triangular part gives the - matrix ``T`` above (the subdiagonal elements are ignored). - -!!! note - - This format should not to be confused with the older *WY* representation - [^Bischof1987]. - - -[^Bischof1987]: C Bischof and C Van Loan, "The WY representation for products of Householder matrices", SIAM J Sci Stat Comput 8 (1987), s2-s13. [doi:10.1137/0908009](http://dx.doi.org/10.1137/0908009) - -[^Schreiber1989]: R Schreiber and C Van Loan, "A storage-efficient WY representation for products of Householder transformations", SIAM J Sci Stat Comput 10 (1989), 53-57. [doi:10.1137/0910005](http://dx.doi.org/10.1137/0910005) -""" -struct QRCompactWY{S,M<:AbstractMatrix} <: Factorization{S} - factors::M - T::Matrix{S} - QRCompactWY{S,M}(factors::AbstractMatrix{S}, T::AbstractMatrix{S}) where {S,M<:AbstractMatrix} = new(factors, T) -end -QRCompactWY(factors::AbstractMatrix{S}, T::AbstractMatrix{S}) where {S} = QRCompactWY{S,typeof(factors)}(factors, T) - -""" - QRPivoted <: Factorization - -A QR matrix factorization with column pivoting in a packed format, typically obtained from -[`qrfact`](@ref). If ``A`` is an `m`×`n` matrix, then - -```math -A P = Q R -``` - -where ``P`` is a permutation matrix, ``Q`` is an orthogonal/unitary matrix and ``R`` is -upper triangular. The matrix ``Q`` is stored as a sequence of Householder reflectors: - -```math -Q = \\prod_{i=1}^{\\min(m,n)} (I - \\tau_i v_i v_i^T). -``` - -The object has three fields: - -* `factors` is an `m`×`n` matrix. - - - The upper triangular part contains the elements of ``R``, that is `R = - triu(F.factors)` for a `QR` object `F`. - - - The subdiagonal part contains the reflectors ``v_i`` stored in a packed format where - ``v_i`` is the ``i``th column of the matrix `V = eye(m,n) + tril(F.factors,-1)`. - -* `τ` is a vector of length `min(m,n)` containing the coefficients ``\tau_i``. - -* `jpvt` is an integer vector of length `n` corresponding to the permutation ``P``. -""" -struct QRPivoted{T,S<:AbstractMatrix} <: Factorization{T} - factors::S - τ::Vector{T} - jpvt::Vector{BlasInt} - QRPivoted{T,S}(factors::AbstractMatrix{T}, τ::Vector{T}, jpvt::Vector{BlasInt}) where {T,S<:AbstractMatrix} = - new(factors, τ, jpvt) -end -QRPivoted(factors::AbstractMatrix{T}, τ::Vector{T}, jpvt::Vector{BlasInt}) where {T} = - QRPivoted{T,typeof(factors)}(factors, τ, jpvt) - -function qrfactUnblocked!(A::AbstractMatrix{T}) where {T} - m, n = size(A) - τ = zeros(T, min(m,n)) - for k = 1:min(m - 1 + !(T<:Real), n) - x = view(A, k:m, k) - τk = reflector!(x) - τ[k] = τk - reflectorApply!(x, τk, view(A, k:m, k + 1:n)) - end - QR(A, τ) -end - -# Find index for columns with largest two norm -function indmaxcolumn(A::StridedMatrix) - mm = norm(view(A, :, 1)) - ii = 1 - for i = 2:size(A, 2) - mi = norm(view(A, :, i)) - if abs(mi) > mm - mm = mi - ii = i - end - end - return ii -end - -function qrfactPivotedUnblocked!(A::StridedMatrix) - m, n = size(A) - piv = collect(UnitRange{BlasInt}(1,n)) - τ = Vector{eltype(A)}(min(m,n)) - for j = 1:min(m,n) - - # Find column with maximum norm in trailing submatrix - jm = indmaxcolumn(view(A, j:m, j:n)) + j - 1 - - if jm != j - # Flip elements in pivoting vector - tmpp = piv[jm] - piv[jm] = piv[j] - piv[j] = tmpp - - # Update matrix with - for i = 1:m - tmp = A[i,jm] - A[i,jm] = A[i,j] - A[i,j] = tmp - end - end - - # Compute reflector of columns j - x = view(A, j:m, j) - τj = LinAlg.reflector!(x) - τ[j] = τj - - # Update trailing submatrix with reflector - LinAlg.reflectorApply!(x, τj, view(A, j:m, j+1:n)) - end - return LinAlg.QRPivoted{eltype(A), typeof(A)}(A, τ, piv) -end - -# LAPACK version -qrfact!(A::StridedMatrix{<:BlasFloat}, ::Type{Val{false}}) = QRCompactWY(LAPACK.geqrt!(A, min(minimum(size(A)), 36))...) -qrfact!(A::StridedMatrix{<:BlasFloat}, ::Type{Val{true}}) = QRPivoted(LAPACK.geqp3!(A)...) -qrfact!(A::StridedMatrix{<:BlasFloat}) = qrfact!(A, Val{false}) - -# Generic fallbacks - -""" - qrfact!(A, pivot=Val{false}) - -`qrfact!` is the same as [`qrfact`](@ref) when `A` is a subtype of -`StridedMatrix`, but saves space by overwriting the input `A`, instead of creating a copy. -An [`InexactError`](@ref) exception is thrown if the factorization produces a number not -representable by the element type of `A`, e.g. for integer types. -""" -qrfact!(A::StridedMatrix, ::Type{Val{false}}) = qrfactUnblocked!(A) -qrfact!(A::StridedMatrix, ::Type{Val{true}}) = qrfactPivotedUnblocked!(A) -qrfact!(A::StridedMatrix) = qrfact!(A, Val{false}) - -""" - qrfact(A, pivot=Val{false}) -> F - -Compute the QR factorization of the matrix `A`: an orthogonal (or unitary if `A` is -complex-valued) matrix `Q`, and an upper triangular matrix `R` such that - -```math -A = Q R -``` - -The returned object `F` stores the factorization in a packed format: - - - if `pivot == Val{true}` then `F` is a [`QRPivoted`](@ref) object, - - - otherwise if the element type of `A` is a BLAS type ([`Float32`](@ref), [`Float64`](@ref), - `Complex64` or `Complex128`), then `F` is a [`QRCompactWY`](@ref) object, - - - otherwise `F` is a [`QR`](@ref) object. - -The individual components of the factorization `F` can be accessed by indexing with a symbol: - - - `F[:Q]`: the orthogonal/unitary matrix `Q` - - `F[:R]`: the upper triangular matrix `R` - - `F[:p]`: the permutation vector of the pivot ([`QRPivoted`](@ref) only) - - `F[:P]`: the permutation matrix of the pivot ([`QRPivoted`](@ref) only) - -The following functions are available for the `QR` objects: [`inv`](@ref), [`size`](@ref), -and [`\\`](@ref). When `A` is rectangular, `\\` will return a least squares -solution and if the solution is not unique, the one with smallest norm is returned. - -Multiplication with respect to either thin or full `Q` is allowed, i.e. both `F[:Q]*F[:R]` -and `F[:Q]*A` are supported. A `Q` matrix can be converted into a regular matrix with -[`full`](@ref) which has a named argument `thin`. - -# Example - -```jldoctest -julia> A = [3.0 -6.0; 4.0 -8.0; 0.0 1.0] -3×2 Array{Float64,2}: - 3.0 -6.0 - 4.0 -8.0 - 0.0 1.0 - -julia> F = qrfact(A) -Base.LinAlg.QRCompactWY{Float64,Array{Float64,2}} with factors Q and R: -[-0.6 0.0 0.8; -0.8 0.0 -0.6; 0.0 -1.0 0.0] -[-5.0 10.0; 0.0 -1.0] - -julia> F[:Q] * F[:R] == A -true -``` - -!!! note - `qrfact` returns multiple types because LAPACK uses several representations - that minimize the memory storage requirements of products of Householder - elementary reflectors, so that the `Q` and `R` matrices can be stored - compactly rather as two separate dense matrices. -""" -function qrfact(A::AbstractMatrix{T}, arg) where T - AA = similar(A, typeof(zero(T)/norm(one(T))), size(A)) - copy!(AA, A) - return qrfact!(AA, arg) -end -function qrfact(A::AbstractMatrix{T}) where T - AA = similar(A, typeof(zero(T)/norm(one(T))), size(A)) - copy!(AA, A) - return qrfact!(AA) -end -qrfact(x::Number) = qrfact(fill(x,1,1)) - -""" - qr(A, pivot=Val{false}; thin::Bool=true) -> Q, R, [p] - -Compute the (pivoted) QR factorization of `A` such that either `A = Q*R` or `A[:,p] = Q*R`. -Also see [`qrfact`](@ref). -The default is to compute a thin factorization. Note that `R` is not -extended with zeros when the full `Q` is requested. -""" -qr(A::Union{Number, AbstractMatrix}, pivot::Union{Type{Val{false}}, Type{Val{true}}}=Val{false}; thin::Bool=true) = - _qr(A, pivot, thin=thin) -function _qr(A::Union{Number, AbstractMatrix}, ::Type{Val{false}}; thin::Bool=true) - F = qrfact(A, Val{false}) - full(getq(F), thin=thin), F[:R]::Matrix{eltype(F)} -end -function _qr(A::Union{Number, AbstractMatrix}, ::Type{Val{true}}; thin::Bool=true) - F = qrfact(A, Val{true}) - full(getq(F), thin=thin), F[:R]::Matrix{eltype(F)}, F[:p]::Vector{BlasInt} -end - -""" - qr(v::AbstractVector) -> w, r - -Computes the polar decomposition of a vector. -Returns `w`, a unit vector in the direction of `v`, and -`r`, the norm of `v`. - -See also [`normalize`](@ref), [`normalize!`](@ref), -and [`LinAlg.qr!`](@ref). - -# Example - -```jldoctest -julia> v = [1; 2] -2-element Array{Int64,1}: - 1 - 2 - -julia> w, r = qr(v) -([0.447214, 0.894427], 2.23606797749979) - -julia> w*r == v -true -``` -""" -function qr(v::AbstractVector) - nrm = norm(v) - if !isempty(v) - vv = copy_oftype(v, typeof(v[1]/nrm)) - return __normalize!(vv, nrm), nrm - else - T = typeof(zero(eltype(v))/nrm) - return T[], oneunit(T) - end -end - -""" - LinAlg.qr!(v::AbstractVector) -> w, r - -Computes the polar decomposition of a vector. Instead of returning a new vector -as `qr(v::AbstractVector)`, this function mutates the input vector `v` in place. -Returns `w`, a unit vector in the direction of `v` (this is a mutation of `v`), -and `r`, the norm of `v`. - -See also [`normalize`](@ref), [`normalize!`](@ref), -and [`qr`](@ref). -""" -function qr!(v::AbstractVector) - nrm = norm(v) - __normalize!(v, nrm), nrm -end - -# Conversions -convert(::Type{QR{T}}, A::QR) where {T} = QR(convert(AbstractMatrix{T}, A.factors), convert(Vector{T}, A.τ)) -convert(::Type{Factorization{T}}, A::QR{T}) where {T} = A -convert(::Type{Factorization{T}}, A::QR) where {T} = convert(QR{T}, A) -convert(::Type{QRCompactWY{T}}, A::QRCompactWY) where {T} = QRCompactWY(convert(AbstractMatrix{T}, A.factors), convert(AbstractMatrix{T}, A.T)) -convert(::Type{Factorization{T}}, A::QRCompactWY{T}) where {T} = A -convert(::Type{Factorization{T}}, A::QRCompactWY) where {T} = convert(QRCompactWY{T}, A) -convert(::Type{AbstractMatrix}, F::Union{QR,QRCompactWY}) = F[:Q] * F[:R] -convert(::Type{AbstractArray}, F::Union{QR,QRCompactWY}) = convert(AbstractMatrix, F) -convert(::Type{Matrix}, F::Union{QR,QRCompactWY}) = convert(Array, convert(AbstractArray, F)) -convert(::Type{Array}, F::Union{QR,QRCompactWY}) = convert(Matrix, F) -full(F::Union{QR,QRCompactWY}) = convert(AbstractArray, F) -convert(::Type{QRPivoted{T}}, A::QRPivoted) where {T} = QRPivoted(convert(AbstractMatrix{T}, A.factors), convert(Vector{T}, A.τ), A.jpvt) -convert(::Type{Factorization{T}}, A::QRPivoted{T}) where {T} = A -convert(::Type{Factorization{T}}, A::QRPivoted) where {T} = convert(QRPivoted{T}, A) -convert(::Type{AbstractMatrix}, F::QRPivoted) = (F[:Q] * F[:R])[:,invperm(F[:p])] -convert(::Type{AbstractArray}, F::QRPivoted) = convert(AbstractMatrix, F) -convert(::Type{Matrix}, F::QRPivoted) = convert(Array, convert(AbstractArray, F)) -convert(::Type{Array}, F::QRPivoted) = convert(Matrix, F) -full(F::QRPivoted) = convert(AbstractArray, F) - -function show(io::IO, F::Union{QR, QRCompactWY, QRPivoted}) - println(io, "$(typeof(F)) with factors Q and R:") - show(io, F[:Q]) - println(io) - show(io, F[:R]) -end - -function getindex(A::QR, d::Symbol) - m, n = size(A) - if d == :R - return triu!(A.factors[1:min(m,n), 1:n]) - elseif d == :Q - return getq(A) - else - throw(KeyError(d)) - end -end -function getindex(A::QRCompactWY, d::Symbol) - m, n = size(A) - if d == :R - return triu!(A.factors[1:min(m,n), 1:n]) - elseif d == :Q - return getq(A) - else - throw(KeyError(d)) - end -end -function getindex(A::QRPivoted{T}, d::Symbol) where T - m, n = size(A) - if d == :R - return triu!(A.factors[1:min(m,n), 1:n]) - elseif d == :Q - return getq(A) - elseif d == :p - return A.jpvt - elseif d == :P - p = A[:p] - n = length(p) - P = zeros(T, n, n) - for i in 1:n - P[p[i],i] = one(T) - end - return P - else - throw(KeyError(d)) - end -end - -# Type-stable interface to get Q -getq(A::QRCompactWY) = QRCompactWYQ(A.factors,A.T) -getq(A::Union{QR, QRPivoted}) = QRPackedQ(A.factors,A.τ) - -""" - QRPackedQ <: AbstractMatrix - -The orthogonal/unitary ``Q`` matrix of a QR factorization stored in [`QR`](@ref) or -[`QRPivoted`](@ref) format. -""" -struct QRPackedQ{T,S<:AbstractMatrix} <: AbstractMatrix{T} - factors::S - τ::Vector{T} - QRPackedQ{T,S}(factors::AbstractMatrix{T}, τ::Vector{T}) where {T,S<:AbstractMatrix} = new(factors, τ) -end -QRPackedQ(factors::AbstractMatrix{T}, τ::Vector{T}) where {T} = QRPackedQ{T,typeof(factors)}(factors, τ) - -""" - QRCompactWYQ <: AbstractMatrix - -The orthogonal/unitary ``Q`` matrix of a QR factorization stored in [`QRCompactWY`](@ref) -format. -""" -struct QRCompactWYQ{S, M<:AbstractMatrix} <: AbstractMatrix{S} - factors::M - T::Matrix{S} - QRCompactWYQ{S,M}(factors::AbstractMatrix{S}, T::Matrix{S}) where {S,M<:AbstractMatrix} = new(factors, T) -end -QRCompactWYQ(factors::AbstractMatrix{S}, T::Matrix{S}) where {S} = QRCompactWYQ{S,typeof(factors)}(factors, T) - -convert(::Type{QRPackedQ{T}}, Q::QRPackedQ) where {T} = QRPackedQ(convert(AbstractMatrix{T}, Q.factors), convert(Vector{T}, Q.τ)) -convert(::Type{AbstractMatrix{T}}, Q::QRPackedQ{T}) where {T} = Q -convert(::Type{AbstractMatrix{T}}, Q::QRPackedQ) where {T} = convert(QRPackedQ{T}, Q) -convert(::Type{QRCompactWYQ{S}}, Q::QRCompactWYQ) where {S} = QRCompactWYQ(convert(AbstractMatrix{S}, Q.factors), convert(AbstractMatrix{S}, Q.T)) -convert(::Type{AbstractMatrix{S}}, Q::QRCompactWYQ{S}) where {S} = Q -convert(::Type{AbstractMatrix{S}}, Q::QRCompactWYQ) where {S} = convert(QRCompactWYQ{S}, Q) -convert(::Type{Matrix}, A::Union{QRPackedQ{T},QRCompactWYQ{T}}) where {T} = A_mul_B!(A, eye(T, size(A.factors, 1), minimum(size(A.factors)))) -convert(::Type{Array}, A::Union{QRPackedQ,QRCompactWYQ}) = convert(Matrix, A) - -""" - full(A::Union{QRPackedQ,QRCompactWYQ}; thin::Bool=true) -> Matrix - -Converts an orthogonal or unitary matrix stored as a `QRCompactWYQ` object, i.e. in the -compact WY format [^Bischof1987], or in the `QRPackedQ` format, to a dense matrix. - -Optionally takes a `thin` Boolean argument, which if `true` omits the columns that span the -rows of `R` in the QR factorization that are zero. The resulting matrix is the `Q` in a thin -QR factorization (sometimes called the reduced QR factorization). If `false`, returns a `Q` -that spans all rows of `R` in its corresponding QR factorization. -""" -function full{T}(A::Union{QRPackedQ{T},QRCompactWYQ{T}}; thin::Bool = true) - if thin - convert(Array, A) - else - A_mul_B!(A, eye(T, size(A.factors, 1))) - end -end - -size(A::Union{QR,QRCompactWY,QRPivoted}, dim::Integer) = size(A.factors, dim) -size(A::Union{QR,QRCompactWY,QRPivoted}) = size(A.factors) -size(A::Union{QRPackedQ,QRCompactWYQ}, dim::Integer) = 0 < dim ? (dim <= 2 ? size(A.factors, 1) : 1) : throw(BoundsError()) -size(A::Union{QRPackedQ,QRCompactWYQ}) = size(A, 1), size(A, 2) - - -function getindex(A::Union{QRPackedQ,QRCompactWYQ}, i::Integer, j::Integer) - x = zeros(eltype(A), size(A, 1)) - x[i] = 1 - y = zeros(eltype(A), size(A, 2)) - y[j] = 1 - return dot(x, A_mul_B!(A, y)) -end - -## Multiplication by Q -### QB -A_mul_B!(A::QRCompactWYQ{T}, B::StridedVecOrMat{T}) where {T<:BlasFloat} = LAPACK.gemqrt!('L','N',A.factors,A.T,B) -A_mul_B!(A::QRPackedQ{T}, B::StridedVecOrMat{T}) where {T<:BlasFloat} = LAPACK.ormqr!('L','N',A.factors,A.τ,B) -function A_mul_B!(A::QRPackedQ, B::AbstractVecOrMat) - mA, nA = size(A.factors) - mB, nB = size(B,1), size(B,2) - if mA != mB - throw(DimensionMismatch("matrix A has dimensions ($mA,$nA) but B has dimensions ($mB, $nB)")) - end - Afactors = A.factors - @inbounds begin - for k = min(mA,nA):-1:1 - for j = 1:nB - vBj = B[k,j] - for i = k+1:mB - vBj += conj(Afactors[i,k])*B[i,j] - end - vBj = A.τ[k]*vBj - B[k,j] -= vBj - for i = k+1:mB - B[i,j] -= Afactors[i,k]*vBj - end - end - end - end - B -end - -function (*)(A::Union{QRPackedQ,QRCompactWYQ}, b::StridedVector) - TAb = promote_type(eltype(A), eltype(b)) - Anew = convert(AbstractMatrix{TAb}, A) - if size(A.factors, 1) == length(b) - bnew = copy_oftype(b, TAb) - elseif size(A.factors, 2) == length(b) - bnew = [b; zeros(TAb, size(A.factors, 1) - length(b))] - else - throw(DimensionMismatch("vector must have length either $(size(A.factors, 1)) or $(size(A.factors, 2))")) - end - A_mul_B!(Anew, bnew) -end -function (*)(A::Union{QRPackedQ,QRCompactWYQ}, B::StridedMatrix) - TAB = promote_type(eltype(A), eltype(B)) - Anew = convert(AbstractMatrix{TAB}, A) - if size(A.factors, 1) == size(B, 1) - Bnew = copy_oftype(B, TAB) - elseif size(A.factors, 2) == size(B, 1) - Bnew = [B; zeros(TAB, size(A.factors, 1) - size(B,1), size(B, 2))] - else - throw(DimensionMismatch("first dimension of matrix must have size either $(size(A.factors, 1)) or $(size(A.factors, 2))")) - end - A_mul_B!(Anew, Bnew) -end - -### QcB -Ac_mul_B!(A::QRCompactWYQ{T}, B::StridedVecOrMat{T}) where {T<:BlasReal} = LAPACK.gemqrt!('L','T',A.factors,A.T,B) -Ac_mul_B!(A::QRCompactWYQ{T}, B::StridedVecOrMat{T}) where {T<:BlasComplex} = LAPACK.gemqrt!('L','C',A.factors,A.T,B) -Ac_mul_B!(A::QRPackedQ{T}, B::StridedVecOrMat{T}) where {T<:BlasReal} = LAPACK.ormqr!('L','T',A.factors,A.τ,B) -Ac_mul_B!(A::QRPackedQ{T}, B::StridedVecOrMat{T}) where {T<:BlasComplex} = LAPACK.ormqr!('L','C',A.factors,A.τ,B) -function Ac_mul_B!(A::QRPackedQ, B::AbstractVecOrMat) - mA, nA = size(A.factors) - mB, nB = size(B,1), size(B,2) - if mA != mB - throw(DimensionMismatch("matrix A has dimensions ($mA,$nA) but B has dimensions ($mB, $nB)")) - end - Afactors = A.factors - @inbounds begin - for k = 1:min(mA,nA) - for j = 1:nB - vBj = B[k,j] - for i = k+1:mB - vBj += conj(Afactors[i,k])*B[i,j] - end - vBj = conj(A.τ[k])*vBj - B[k,j] -= vBj - for i = k+1:mB - B[i,j] -= Afactors[i,k]*vBj - end - end - end - end - B -end -function Ac_mul_B(Q::Union{QRPackedQ,QRCompactWYQ}, B::StridedVecOrMat) - TQB = promote_type(eltype(Q), eltype(B)) - return Ac_mul_B!(convert(AbstractMatrix{TQB}, Q), copy_oftype(B, TQB)) -end - -### QBc/QcBc -for (f1, f2) in ((:A_mul_Bc, :A_mul_B!), - (:Ac_mul_Bc, :Ac_mul_B!)) - @eval begin - function ($f1)(Q::Union{QRPackedQ,QRCompactWYQ}, B::StridedVecOrMat) - TQB = promote_type(eltype(Q), eltype(B)) - Bc = similar(B, TQB, (size(B, 2), size(B, 1))) - ctranspose!(Bc, B) - return ($f2)(convert(AbstractMatrix{TQB}, Q), Bc) - end - end -end - -### AQ -A_mul_B!(A::StridedVecOrMat{T}, B::QRCompactWYQ{T}) where {T<:BlasFloat} = LAPACK.gemqrt!('R','N', B.factors, B.T, A) -A_mul_B!(A::StridedVecOrMat{T}, B::QRPackedQ{T}) where {T<:BlasFloat} = LAPACK.ormqr!('R', 'N', B.factors, B.τ, A) -function A_mul_B!(A::StridedMatrix,Q::QRPackedQ) - mQ, nQ = size(Q.factors) - mA, nA = size(A,1), size(A,2) - if nA != mQ - throw(DimensionMismatch("matrix A has dimensions ($mA,$nA) but matrix Q has dimensions ($mQ, $nQ)")) - end - Qfactors = Q.factors - @inbounds begin - for k = 1:min(mQ,nQ) - for i = 1:mA - vAi = A[i,k] - for j = k+1:mQ - vAi += A[i,j]*Qfactors[j,k] - end - vAi = vAi*Q.τ[k] - A[i,k] -= vAi - for j = k+1:nA - A[i,j] -= vAi*conj(Qfactors[j,k]) - end - end - end - end - A -end - -function (*)(A::StridedMatrix, Q::Union{QRPackedQ,QRCompactWYQ}) - TAQ = promote_type(eltype(A), eltype(Q)) - return A_mul_B!(copy_oftype(A, TAQ), convert(AbstractMatrix{TAQ}, Q)) -end - -### AQc -A_mul_Bc!(A::StridedVecOrMat{T}, B::QRCompactWYQ{T}) where {T<:BlasReal} = LAPACK.gemqrt!('R','T',B.factors,B.T,A) -A_mul_Bc!(A::StridedVecOrMat{T}, B::QRCompactWYQ{T}) where {T<:BlasComplex} = LAPACK.gemqrt!('R','C',B.factors,B.T,A) -A_mul_Bc!(A::StridedVecOrMat{T}, B::QRPackedQ{T}) where {T<:BlasReal} = LAPACK.ormqr!('R','T',B.factors,B.τ,A) -A_mul_Bc!(A::StridedVecOrMat{T}, B::QRPackedQ{T}) where {T<:BlasComplex} = LAPACK.ormqr!('R','C',B.factors,B.τ,A) -function A_mul_Bc!(A::AbstractMatrix,Q::QRPackedQ) - mQ, nQ = size(Q.factors) - mA, nA = size(A,1), size(A,2) - if nA != mQ - throw(DimensionMismatch("matrix A has dimensions ($mA,$nA) but matrix Q has dimensions ($mQ, $nQ)")) - end - Qfactors = Q.factors - @inbounds begin - for k = min(mQ,nQ):-1:1 - for i = 1:mA - vAi = A[i,k] - for j = k+1:mQ - vAi += A[i,j]*Qfactors[j,k] - end - vAi = vAi*conj(Q.τ[k]) - A[i,k] -= vAi - for j = k+1:nA - A[i,j] -= vAi*conj(Qfactors[j,k]) - end - end - end - end - A -end -function A_mul_Bc(A::AbstractMatrix, B::Union{QRCompactWYQ,QRPackedQ}) - TAB = promote_type(eltype(A),eltype(B)) - BB = convert(AbstractMatrix{TAB}, B) - if size(A,2) == size(B.factors, 1) - AA = similar(A, TAB, size(A)) - copy!(AA, A) - return A_mul_Bc!(AA, BB) - elseif size(A,2) == size(B.factors,2) - return A_mul_Bc!([A zeros(TAB, size(A, 1), size(B.factors, 1) - size(B.factors, 2))], BB) - else - throw(DimensionMismatch("matrix A has dimensions $(size(A)) but matrix B has dimensions $(size(B))")) - end -end -@inline A_mul_Bc(rowvec::RowVector, B::Union{LinAlg.QRCompactWYQ,LinAlg.QRPackedQ}) = ctranspose(B*ctranspose(rowvec)) - - -### AcQ/AcQc -for (f1, f2) in ((:Ac_mul_B, :A_mul_B!), - (:Ac_mul_Bc, :A_mul_Bc!)) - @eval begin - function ($f1)(A::StridedVecOrMat, Q::Union{QRPackedQ,QRCompactWYQ}) - TAQ = promote_type(eltype(A), eltype(Q)) - Ac = similar(A, TAQ, (size(A, 2), size(A, 1))) - ctranspose!(Ac, A) - return ($f2)(Ac, convert(AbstractMatrix{TAQ}, Q)) - end - end -end - -A_ldiv_B!(A::QRCompactWY{T}, b::StridedVector{T}) where {T<:BlasFloat} = (A_ldiv_B!(UpperTriangular(A[:R]), view(Ac_mul_B!(A[:Q], b), 1:size(A, 2))); b) -A_ldiv_B!(A::QRCompactWY{T}, B::StridedMatrix{T}) where {T<:BlasFloat} = (A_ldiv_B!(UpperTriangular(A[:R]), view(Ac_mul_B!(A[:Q], B), 1:size(A, 2), 1:size(B, 2))); B) - -# Julia implementation similarly to xgelsy -function A_ldiv_B!(A::QRPivoted{T}, B::StridedMatrix{T}, rcond::Real) where T<:BlasFloat - mA, nA = size(A.factors) - nr = min(mA,nA) - nrhs = size(B, 2) - if nr == 0 - return B, 0 - end - ar = abs(A.factors[1]) - if ar == 0 - B[1:nA, :] = 0 - return B, 0 - end - rnk = 1 - xmin = ones(T, 1) - xmax = ones(T, 1) - tmin = tmax = ar - while rnk < nr - tmin, smin, cmin = LAPACK.laic1!(2, xmin, tmin, view(A.factors, 1:rnk, rnk + 1), A.factors[rnk + 1, rnk + 1]) - tmax, smax, cmax = LAPACK.laic1!(1, xmax, tmax, view(A.factors, 1:rnk, rnk + 1), A.factors[rnk + 1, rnk + 1]) - tmax*rcond > tmin && break - push!(xmin, cmin) - push!(xmax, cmax) - for i = 1:rnk - xmin[i] *= smin - xmax[i] *= smax - end - rnk += 1 - end - C, τ = LAPACK.tzrzf!(A.factors[1:rnk,:]) - A_ldiv_B!(UpperTriangular(C[1:rnk,1:rnk]),view(Ac_mul_B!(getq(A),view(B, 1:mA, 1:nrhs)),1:rnk,1:nrhs)) - B[rnk+1:end,:] = zero(T) - LAPACK.ormrz!('L', eltype(B)<:Complex ? 'C' : 'T', C, τ, view(B,1:nA,1:nrhs)) - B[1:nA,:] = view(B, 1:nA, :)[invperm(A[:p]::Vector{BlasInt}),:] - return B, rnk -end -A_ldiv_B!(A::QRPivoted{T}, B::StridedVector{T}) where {T<:BlasFloat} = vec(A_ldiv_B!(A,reshape(B,length(B),1))) -A_ldiv_B!(A::QRPivoted{T}, B::StridedVecOrMat{T}) where {T<:BlasFloat} = A_ldiv_B!(A, B, maximum(size(A))*eps(real(float(one(eltype(B))))))[1] -function A_ldiv_B!(A::QR{T}, B::StridedMatrix{T}) where T - m, n = size(A) - minmn = min(m,n) - mB, nB = size(B) - Ac_mul_B!(A[:Q], view(B, 1:m, :)) - R = A[:R] - @inbounds begin - if n > m # minimum norm solution - τ = zeros(T,m) - for k = m:-1:1 # Trapezoid to triangular by elementary operation - x = view(R, k, [k; m + 1:n]) - τk = reflector!(x) - τ[k] = τk' - for i = 1:k - 1 - vRi = R[i,k] - for j = m + 1:n - vRi += R[i,j]*x[j - m + 1]' - end - vRi *= τk - R[i,k] -= vRi - for j = m + 1:n - R[i,j] -= vRi*x[j - m + 1] - end - end - end - end - Base.A_ldiv_B!(UpperTriangular(view(R, :, 1:minmn)), view(B, 1:minmn, :)) - if n > m # Apply elementary transformation to solution - B[m + 1:mB,1:nB] = zero(T) - for j = 1:nB - for k = 1:m - vBj = B[k,j] - for i = m + 1:n - vBj += B[i,j]*R[k,i]' - end - vBj *= τ[k] - B[k,j] -= vBj - for i = m + 1:n - B[i,j] -= R[k,i]*vBj - end - end - end - end - end - return B -end -A_ldiv_B!(A::QR, B::StridedVector) = A_ldiv_B!(A, reshape(B, length(B), 1))[:] -function A_ldiv_B!(A::QRPivoted, b::StridedVector) - A_ldiv_B!(QR(A.factors,A.τ), b) - b[1:size(A.factors, 2)] = view(b, 1:size(A.factors, 2))[invperm(A.jpvt)] - b -end -function A_ldiv_B!(A::QRPivoted, B::StridedMatrix) - A_ldiv_B!(QR(A.factors, A.τ), B) - B[1:size(A.factors, 2),:] = view(B, 1:size(A.factors, 2), :)[invperm(A.jpvt),:] - B -end - -# convenience methods -## return only the solution of a least squares problem while avoiding promoting -## vectors to matrices. -_cut_B(x::AbstractVector, r::UnitRange) = length(x) > length(r) ? x[r] : x -_cut_B(X::AbstractMatrix, r::UnitRange) = size(X, 1) > length(r) ? X[r,:] : X - -## append right hand side with zeros if necessary -_zeros(::Type{T}, b::AbstractVector, n::Integer) where {T} = zeros(T, max(length(b), n)) -_zeros(::Type{T}, B::AbstractMatrix, n::Integer) where {T} = zeros(T, max(size(B, 1), n), size(B, 2)) - -function (\)(A::Union{QR{TA},QRCompactWY{TA},QRPivoted{TA}}, B::AbstractVecOrMat{TB}) where {TA,TB} - S = promote_type(TA,TB) - m, n = size(A) - m == size(B,1) || throw(DimensionMismatch("left hand side has $m rows, but right hand side has $(size(B,1)) rows")) - - AA = convert(Factorization{S}, A) - - X = _zeros(S, B, n) - X[1:size(B, 1), :] = B - - A_ldiv_B!(AA, X) - - return _cut_B(X, 1:n) -end - -# With a real lhs and complex rhs with the same precision, we can reinterpret the complex -# rhs as a real rhs with twice the number of columns. - -# convenience methods to compute the return size correctly for vectors and matrices -_ret_size(A::Factorization, b::AbstractVector) = (max(size(A, 2), length(b)),) -_ret_size(A::Factorization, B::AbstractMatrix) = (max(size(A, 2), size(B, 1)), size(B, 2)) - -function (\)(A::Union{QR{T},QRCompactWY{T},QRPivoted{T}}, BIn::VecOrMat{Complex{T}}) where T<:BlasReal - m, n = size(A) - m == size(BIn, 1) || throw(DimensionMismatch("left hand side has $m rows, but right hand side has $(size(BIn,1)) rows")) - -# |z1|z3| reinterpret |x1|x2|x3|x4| transpose |x1|y1| reshape |x1|y1|x3|y3| -# |z2|z4| -> |y1|y2|y3|y4| -> |x2|y2| -> |x2|y2|x4|y4| -# |x3|y3| -# |x4|y4| - B = reshape(transpose(reinterpret(T, BIn, (2, length(BIn)))), size(BIn, 1), 2*size(BIn, 2)) - - X = _zeros(T, B, n) - X[1:size(B, 1), :] = B - - A_ldiv_B!(A, X) - -# |z1|z3| reinterpret |x1|x2|x3|x4| transpose |x1|y1| reshape |x1|y1|x3|y3| -# |z2|z4| <- |y1|y2|y3|y4| <- |x2|y2| <- |x2|y2|x4|y4| -# |x3|y3| -# |x4|y4| - XX = reinterpret(Complex{T}, transpose(reshape(X, div(length(X), 2), 2)), _ret_size(A, BIn)) - return _cut_B(XX, 1:n) -end - -##TODO: Add methods for rank(A::QRP{T}) and adjust the (\) method accordingly -## Add rcond methods for Cholesky, LU, QR and QRP types -## Lower priority: Add LQ, QL and RQ factorizations - -# FIXME! Should add balancing option through xgebal diff --git a/julia-0.6.3/share/julia/base/linalg/rowvector.jl b/julia-0.6.3/share/julia/base/linalg/rowvector.jl deleted file mode 100644 index 77fed7c..0000000 --- a/julia-0.6.3/share/julia/base/linalg/rowvector.jl +++ /dev/null @@ -1,242 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -""" - RowVector(vector) - -A lazy-view wrapper of an `AbstractVector`, which turns a length-`n` vector into a `1×n` -shaped row vector and represents the transpose of a vector (the elements are also transposed -recursively). This type is usually constructed (and unwrapped) via the [`transpose`](@ref) -function or `.'` operator (or related [`ctranspose`](@ref) or `'` operator). - -By convention, a vector can be multiplied by a matrix on its left (`A * v`) whereas a row -vector can be multiplied by a matrix on its right (such that `v.' * A = (A.' * v).'`). It -differs from a `1×n`-sized matrix by the facts that its transpose returns a vector and the -inner product `v1.' * v2` returns a scalar, but will otherwise behave similarly. -""" -struct RowVector{T,V<:AbstractVector} <: AbstractMatrix{T} - vec::V - function RowVector{T,V}(v::V) where V<:AbstractVector where T - check_types(T,v) - new(v) - end -end - -@inline check_types(::Type{T1}, ::AbstractVector{T2}) where {T1,T2} = check_types(T1, T2) -@pure check_types(::Type{T1}, ::Type{T2}) where {T1,T2} = T1 === transpose_type(T2) ? nothing : - error("Element type mismatch. Tried to create a `RowVector{$T1}` from an `AbstractVector{$T2}`") - -const ConjRowVector{T,CV<:ConjVector} = RowVector{T,CV} - -# The element type may be transformed as transpose is recursive -@inline transpose_type{T}(::Type{T}) = promote_op(transpose, T) - -# Constructors that take a vector -@inline RowVector(vec::AbstractVector{T}) where {T} = RowVector{transpose_type(T),typeof(vec)}(vec) -@inline RowVector{T}(vec::AbstractVector{T}) where {T} = RowVector{T,typeof(vec)}(vec) - -# Constructors that take a size and default to Array -@inline RowVector{T}(n::Int) where {T} = RowVector{T}(Vector{transpose_type(T)}(n)) -@inline RowVector{T}(n1::Int, n2::Int) where {T} = n1 == 1 ? - RowVector{T}(Vector{transpose_type(T)}(n2)) : - error("RowVector expects 1×N size, got ($n1,$n2)") -@inline RowVector{T}(n::Tuple{Int}) where {T} = RowVector{T}(Vector{transpose_type(T)}(n[1])) -@inline RowVector{T}(n::Tuple{Int,Int}) where {T} = n[1] == 1 ? - RowVector{T}(Vector{transpose_type(T)}(n[2])) : - error("RowVector expects 1×N size, got $n") - -# Conversion of underlying storage -convert(::Type{RowVector{T,V}}, rowvec::RowVector) where {T,V<:AbstractVector} = - RowVector{T,V}(convert(V,rowvec.vec)) - -# similar tries to maintain the RowVector wrapper and the parent type -@inline similar(rowvec::RowVector) = RowVector(similar(parent(rowvec))) -@inline similar(rowvec::RowVector, ::Type{T}) where {T} = RowVector(similar(parent(rowvec), transpose_type(T))) - -# Resizing similar currently loses its RowVector property. -@inline similar(rowvec::RowVector, ::Type{T}, dims::Dims{N}) where {T,N} = similar(parent(rowvec), T, dims) - -# Basic methods -""" - transpose(v::AbstractVector) - -The transposition operator (`.'`). - -# Example - -```jldoctest -julia> v = [1,2,3] -3-element Array{Int64,1}: - 1 - 2 - 3 - -julia> transpose(v) -1×3 RowVector{Int64,Array{Int64,1}}: - 1 2 3 -``` -""" -@inline transpose(vec::AbstractVector) = RowVector(vec) -@inline ctranspose(vec::AbstractVector) = RowVector(_conj(vec)) - -@inline transpose(rowvec::RowVector) = rowvec.vec -@inline transpose(rowvec::ConjRowVector) = copy(rowvec.vec) # remove the ConjArray wrapper from any raw vector -@inline ctranspose(rowvec::RowVector) = conj(rowvec.vec) -@inline ctranspose(rowvec::RowVector{<:Real}) = rowvec.vec - -parent(rowvec::RowVector) = rowvec.vec - -""" - conj(v::RowVector) - -Returns a [`ConjArray`](@ref) lazy view of the input, where each element is conjugated. - -### Example - -```jldoctest -julia> v = [1+im, 1-im].' -1×2 RowVector{Complex{Int64},Array{Complex{Int64},1}}: - 1+1im 1-1im - -julia> conj(v) -1×2 RowVector{Complex{Int64},ConjArray{Complex{Int64},1,Array{Complex{Int64},1}}}: - 1-1im 1+1im -``` -""" -@inline conj(rowvec::RowVector) = RowVector(_conj(rowvec.vec)) -@inline conj(rowvec::RowVector{<:Real}) = rowvec - -# AbstractArray interface -@inline length(rowvec::RowVector) = length(rowvec.vec) -@inline size(rowvec::RowVector) = (1, length(rowvec.vec)) -@inline size(rowvec::RowVector, d) = ifelse(d==2, length(rowvec.vec), 1) -@inline indices(rowvec::RowVector) = (Base.OneTo(1), indices(rowvec.vec)[1]) -@inline indices(rowvec::RowVector, d) = ifelse(d == 2, indices(rowvec.vec)[1], Base.OneTo(1)) -IndexStyle(::RowVector) = IndexLinear() -IndexStyle(::Type{<:RowVector}) = IndexLinear() - -@propagate_inbounds getindex(rowvec::RowVector, i) = transpose(rowvec.vec[i]) -@propagate_inbounds setindex!(rowvec::RowVector, v, i) = (setindex!(rowvec.vec, transpose(v), i); rowvec) - -# Cartesian indexing is distorted by getindex -# Furthermore, Cartesian indexes don't have to match shape, apparently! -@inline function getindex(rowvec::RowVector, i::CartesianIndex) - @boundscheck if !(i.I[1] == 1 && i.I[2] ∈ indices(rowvec.vec)[1] && check_tail_indices(i.I...)) - throw(BoundsError(rowvec, i.I)) - end - @inbounds return transpose(rowvec.vec[i.I[2]]) -end -@inline function setindex!(rowvec::RowVector, v, i::CartesianIndex) - @boundscheck if !(i.I[1] == 1 && i.I[2] ∈ indices(rowvec.vec)[1] && check_tail_indices(i.I...)) - throw(BoundsError(rowvec, i.I)) - end - @inbounds rowvec.vec[i.I[2]] = transpose(v) -end - -@propagate_inbounds getindex(rowvec::RowVector, ::CartesianIndex{0}) = getindex(rowvec) -@propagate_inbounds getindex(rowvec::RowVector, i::CartesianIndex{1}) = getindex(rowvec, i.I[1]) - -@propagate_inbounds setindex!(rowvec::RowVector, v, ::CartesianIndex{0}) = setindex!(rowvec, v) -@propagate_inbounds setindex!(rowvec::RowVector, v, i::CartesianIndex{1}) = setindex!(rowvec, v, i.I[1]) - -@inline check_tail_indices(i1, i2) = true -@inline check_tail_indices(i1, i2, i3, is...) = i3 == 1 ? check_tail_indices(i1, i2, is...) : false - -# helper function for below -@inline to_vec(rowvec::RowVector) = map(transpose, transpose(rowvec)) -@inline to_vec(x::Number) = x -@inline to_vecs(rowvecs...) = (map(to_vec, rowvecs)...) - -# map: Preserve the RowVector by un-wrapping and re-wrapping, but note that `f` -# expects to operate within the transposed domain, so to_vec transposes the elements -@inline map(f, rowvecs::RowVector...) = RowVector(map(transpose∘f, to_vecs(rowvecs...)...)) - -# broacast (other combinations default to higher-dimensional array) -@inline broadcast(f, rowvecs::Union{Number,RowVector}...) = - RowVector(broadcast(transpose∘f, to_vecs(rowvecs...)...)) - -# Horizontal concatenation # - -@inline hcat(X::RowVector...) = transpose(vcat(map(transpose, X)...)) -@inline hcat(X::Union{RowVector,Number}...) = transpose(vcat(map(transpose, X)...)) - -@inline typed_hcat(::Type{T}, X::RowVector...) where {T} = - transpose(typed_vcat(T, map(transpose, X)...)) -@inline typed_hcat(::Type{T}, X::Union{RowVector,Number}...) where {T} = - transpose(typed_vcat(T, map(transpose, X)...)) - -# Multiplication # - -# inner product -> dot product specializations -@inline *(rowvec::RowVector{T}, vec::AbstractVector{T}) where {T<:Real} = dot(parent(rowvec), vec) -@inline *(rowvec::ConjRowVector{T}, vec::AbstractVector{T}) where {T<:Real} = dot(rowvec', vec) -@inline *(rowvec::ConjRowVector, vec::AbstractVector) = dot(rowvec', vec) - -# Generic behavior -@inline function *(rowvec::RowVector, vec::AbstractVector) - if length(rowvec) != length(vec) - throw(DimensionMismatch("A has dimensions $(size(rowvec)) but B has dimensions $(size(vec))")) - end - sum(@inbounds(return rowvec[i]*vec[i]) for i = 1:length(vec)) -end -@inline *(rowvec::RowVector, mat::AbstractMatrix) = transpose(mat.' * transpose(rowvec)) -*(::RowVector, ::RowVector) = throw(DimensionMismatch("Cannot multiply two transposed vectors")) -@inline *(vec::AbstractVector, rowvec::RowVector) = vec .* rowvec -*(vec::AbstractVector, rowvec::AbstractVector) = throw(DimensionMismatch("Cannot multiply two vectors")) - -# Transposed forms -A_mul_Bt(::RowVector, ::AbstractVector) = throw(DimensionMismatch("Cannot multiply two transposed vectors")) -@inline A_mul_Bt(rowvec::RowVector, mat::AbstractMatrix) = transpose(mat * transpose(rowvec)) -@inline A_mul_Bt(rowvec1::RowVector, rowvec2::RowVector) = rowvec1*transpose(rowvec2) -A_mul_Bt(vec::AbstractVector, rowvec::RowVector) = throw(DimensionMismatch("Cannot multiply two vectors")) -@inline A_mul_Bt(vec1::AbstractVector, vec2::AbstractVector) = vec1 * transpose(vec2) -@inline A_mul_Bt(mat::AbstractMatrix, rowvec::RowVector) = mat * transpose(rowvec) - -@inline At_mul_Bt(rowvec::RowVector, vec::AbstractVector) = transpose(rowvec) * transpose(vec) -@inline At_mul_Bt(vec::AbstractVector, mat::AbstractMatrix) = transpose(mat * vec) -At_mul_Bt(rowvec1::RowVector, rowvec2::RowVector) = throw(DimensionMismatch("Cannot multiply two vectors")) -@inline At_mul_Bt(vec::AbstractVector, rowvec::RowVector) = transpose(vec)*transpose(rowvec) -At_mul_Bt(vec::AbstractVector, rowvec::AbstractVector) = throw(DimensionMismatch( - "Cannot multiply two transposed vectors")) -@inline At_mul_Bt(mat::AbstractMatrix, rowvec::RowVector) = mat.' * transpose(rowvec) - -At_mul_B(::RowVector, ::AbstractVector) = throw(DimensionMismatch("Cannot multiply two vectors")) -@inline At_mul_B(vec::AbstractVector, mat::AbstractMatrix) = transpose(At_mul_B(mat,vec)) -@inline At_mul_B(rowvec1::RowVector, rowvec2::RowVector) = transpose(rowvec1) * rowvec2 -At_mul_B(vec::AbstractVector, rowvec::RowVector) = throw(DimensionMismatch( - "Cannot multiply two transposed vectors")) -@inline At_mul_B(vec1::AbstractVector{T}, vec2::AbstractVector{T}) where {T<:Real} = - reduce(+, map(At_mul_B, vec1, vec2)) # Seems to be overloaded... -@inline At_mul_B(vec1::AbstractVector, vec2::AbstractVector) = transpose(vec1) * vec2 - -# Conjugated forms -A_mul_Bc(::RowVector, ::AbstractVector) = throw(DimensionMismatch("Cannot multiply two transposed vectors")) -@inline A_mul_Bc(rowvec::RowVector, mat::AbstractMatrix) = ctranspose(mat * ctranspose(rowvec)) -@inline A_mul_Bc(rowvec1::RowVector, rowvec2::RowVector) = rowvec1 * ctranspose(rowvec2) -A_mul_Bc(vec::AbstractVector, rowvec::RowVector) = throw(DimensionMismatch("Cannot multiply two vectors")) -@inline A_mul_Bc(vec1::AbstractVector, vec2::AbstractVector) = vec1 * ctranspose(vec2) -@inline A_mul_Bc(mat::AbstractMatrix, rowvec::RowVector) = mat * ctranspose(rowvec) - -@inline Ac_mul_Bc(rowvec::RowVector, vec::AbstractVector) = ctranspose(rowvec) * ctranspose(vec) -@inline Ac_mul_Bc(vec::AbstractVector, mat::AbstractMatrix) = ctranspose(mat * vec) -Ac_mul_Bc(rowvec1::RowVector, rowvec2::RowVector) = throw(DimensionMismatch("Cannot multiply two vectors")) -@inline Ac_mul_Bc(vec::AbstractVector, rowvec::RowVector) = ctranspose(vec)*ctranspose(rowvec) -Ac_mul_Bc(vec::AbstractVector, rowvec::AbstractVector) = throw(DimensionMismatch("Cannot multiply two transposed vectors")) -@inline Ac_mul_Bc(mat::AbstractMatrix, rowvec::RowVector) = mat' * ctranspose(rowvec) - -Ac_mul_B(::RowVector, ::AbstractVector) = throw(DimensionMismatch("Cannot multiply two vectors")) -@inline Ac_mul_B(vec::AbstractVector, mat::AbstractMatrix) = ctranspose(Ac_mul_B(mat,vec)) -@inline Ac_mul_B(rowvec1::RowVector, rowvec2::RowVector) = ctranspose(rowvec1) * rowvec2 -Ac_mul_B(vec::AbstractVector, rowvec::RowVector) = throw(DimensionMismatch("Cannot multiply two transposed vectors")) -@inline Ac_mul_B(vec1::AbstractVector, vec2::AbstractVector) = ctranspose(vec1)*vec2 - -# Left Division # - -\(mat::AbstractMatrix, rowvec::RowVector) = throw(DimensionMismatch("Cannot left-divide transposed vector by matrix")) -At_ldiv_B(mat::AbstractMatrix, rowvec::RowVector) = throw(DimensionMismatch("Cannot left-divide transposed vector by matrix")) -Ac_ldiv_B(mat::AbstractMatrix, rowvec::RowVector) = throw(DimensionMismatch("Cannot left-divide transposed vector by matrix")) - -# Right Division # - -@inline /(rowvec::RowVector, mat::AbstractMatrix) = transpose(transpose(mat) \ transpose(rowvec)) -@inline A_rdiv_Bt(rowvec::RowVector, mat::AbstractMatrix) = transpose(mat \ transpose(rowvec)) -@inline A_rdiv_Bc(rowvec::RowVector, mat::AbstractMatrix) = ctranspose(mat \ ctranspose(rowvec)) diff --git a/julia-0.6.3/share/julia/base/linalg/schur.jl b/julia-0.6.3/share/julia/base/linalg/schur.jl deleted file mode 100644 index be0cc01..0000000 --- a/julia-0.6.3/share/julia/base/linalg/schur.jl +++ /dev/null @@ -1,289 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -# Schur decomposition -struct Schur{Ty,S<:AbstractMatrix} <: Factorization{Ty} - T::S - Z::S - values::Vector - Schur{Ty,S}(T::AbstractMatrix{Ty}, Z::AbstractMatrix{Ty}, values::Vector) where {Ty,S} = new(T, Z, values) -end -Schur(T::AbstractMatrix{Ty}, Z::AbstractMatrix{Ty}, values::Vector) where {Ty} = Schur{Ty, typeof(T)}(T, Z, values) - -""" - schurfact!(A::StridedMatrix) -> F::Schur - -Same as [`schurfact`](@ref) but uses the input argument as workspace. -""" -schurfact!(A::StridedMatrix{<:BlasFloat}) = Schur(LinAlg.LAPACK.gees!('V', A)...) - -""" - schurfact(A::StridedMatrix) -> F::Schur - -Computes the Schur factorization of the matrix `A`. The (quasi) triangular Schur factor can -be obtained from the `Schur` object `F` with either `F[:Schur]` or `F[:T]` and the -orthogonal/unitary Schur vectors can be obtained with `F[:vectors]` or `F[:Z]` such that -`A = F[:vectors]*F[:Schur]*F[:vectors]'`. The eigenvalues of `A` can be obtained with `F[:values]`. - -# Example - -```jldoctest -julia> A = [-2. 1. 3.; 2. 1. -1.; -7. 2. 7.] -3×3 Array{Float64,2}: - -2.0 1.0 3.0 - 2.0 1.0 -1.0 - -7.0 2.0 7.0 - -julia> F = schurfact(A) -Base.LinAlg.Schur{Float64,Array{Float64,2}} with factors T and Z: -[2.0 0.801792 6.63509; -8.55988e-11 2.0 8.08286; 0.0 0.0 1.99999] -[0.577351 0.154299 -0.801784; 0.577346 -0.77152 0.267262; 0.577354 0.617211 0.534522] -and values: -Complex{Float64}[2.0+8.28447e-6im, 2.0-8.28447e-6im, 1.99999+0.0im] - -julia> F[:vectors] * F[:Schur] * F[:vectors]' -3×3 Array{Float64,2}: - -2.0 1.0 3.0 - 2.0 1.0 -1.0 - -7.0 2.0 7.0 -``` -""" -schurfact(A::StridedMatrix{<:BlasFloat}) = schurfact!(copy(A)) -function schurfact{T}(A::StridedMatrix{T}) - S = promote_type(Float32, typeof(one(T)/norm(one(T)))) - return schurfact!(copy_oftype(A, S)) -end - -function getindex(F::Schur, d::Symbol) - if d == :T || d == :Schur - return F.T - elseif d == :Z || d == :vectors - return F.Z - elseif d == :values - return F.values - else - throw(KeyError(d)) - end -end - -function show(io::IO, F::Schur) - println(io, "$(typeof(F)) with factors T and Z:") - show(io, F[:T]) - println(io) - show(io, F[:Z]) - println(io) - println(io, "and values:") - show(io, F[:values]) -end - -""" - schur(A::StridedMatrix) -> T::Matrix, Z::Matrix, λ::Vector - -Computes the Schur factorization of the matrix `A`. The methods return the (quasi) -triangular Schur factor `T` and the orthogonal/unitary Schur vectors `Z` such that -`A = Z*T*Z'`. The eigenvalues of `A` are returned in the vector `λ`. - -See [`schurfact`](@ref). - -# Example - -```jldoctest -julia> A = [-2. 1. 3.; 2. 1. -1.; -7. 2. 7.] -3×3 Array{Float64,2}: - -2.0 1.0 3.0 - 2.0 1.0 -1.0 - -7.0 2.0 7.0 - -julia> T, Z, lambda = schur(A) -([2.0 0.801792 6.63509; -8.55988e-11 2.0 8.08286; 0.0 0.0 1.99999], [0.577351 0.154299 -0.801784; 0.577346 -0.77152 0.267262; 0.577354 0.617211 0.534522], Complex{Float64}[2.0+8.28447e-6im, 2.0-8.28447e-6im, 1.99999+0.0im]) - -julia> Z * T * Z' -3×3 Array{Float64,2}: - -2.0 1.0 3.0 - 2.0 1.0 -1.0 - -7.0 2.0 7.0 -``` -""" -function schur(A::StridedMatrix) - SchurF = schurfact(A) - SchurF[:T], SchurF[:Z], SchurF[:values] -end -schur(A::Symmetric) = schur(full(A)) -schur(A::Hermitian) = schur(full(A)) -schur(A::UpperTriangular) = schur(full(A)) -schur(A::LowerTriangular) = schur(full(A)) -schur(A::Tridiagonal) = schur(full(A)) - - -""" - ordschur!(F::Schur, select::Union{Vector{Bool},BitVector}) -> F::Schur - -Same as [`ordschur`](@ref) but overwrites the factorization `F`. -""" -function ordschur!(schur::Schur, select::Union{Vector{Bool},BitVector}) - _, _, vals = ordschur!(schur.T, schur.Z, select) - schur[:values][:] = vals - return schur -end - -""" - ordschur(F::Schur, select::Union{Vector{Bool},BitVector}) -> F::Schur - -Reorders the Schur factorization `F` of a matrix `A = Z*T*Z'` according to the logical array -`select` returning the reordered factorization `F` object. The selected eigenvalues appear -in the leading diagonal of `F[:Schur]` and the corresponding leading columns of -`F[:vectors]` form an orthogonal/unitary basis of the corresponding right invariant -subspace. In the real case, a complex conjugate pair of eigenvalues must be either both -included or both excluded via `select`. -""" -ordschur(schur::Schur, select::Union{Vector{Bool},BitVector}) = - Schur(ordschur(schur.T, schur.Z, select)...) - -""" - ordschur!(T::StridedMatrix, Z::StridedMatrix, select::Union{Vector{Bool},BitVector}) -> T::StridedMatrix, Z::StridedMatrix, λ::Vector - -Same as [`ordschur`](@ref) but overwrites the input arguments. -""" -ordschur!(T::StridedMatrix{Ty}, Z::StridedMatrix{Ty}, select::Union{Vector{Bool},BitVector}) where {Ty<:BlasFloat} = - LinAlg.LAPACK.trsen!(convert(Vector{BlasInt}, select), T, Z) - -""" - ordschur(T::StridedMatrix, Z::StridedMatrix, select::Union{Vector{Bool},BitVector}) -> T::StridedMatrix, Z::StridedMatrix, λ::Vector - -Reorders the Schur factorization of a real matrix `A = Z*T*Z'` according to the logical -array `select` returning the reordered matrices `T` and `Z` as well as the vector of -eigenvalues `λ`. The selected eigenvalues appear in the leading diagonal of `T` and the -corresponding leading columns of `Z` form an orthogonal/unitary basis of the corresponding -right invariant subspace. In the real case, a complex conjugate pair of eigenvalues must be -either both included or both excluded via `select`. -""" -ordschur(T::StridedMatrix{Ty}, Z::StridedMatrix{Ty}, select::Union{Vector{Bool},BitVector}) where {Ty<:BlasFloat} = - ordschur!(copy(T), copy(Z), select) - -struct GeneralizedSchur{Ty,M<:AbstractMatrix} <: Factorization{Ty} - S::M - T::M - alpha::Vector - beta::Vector{Ty} - Q::M - Z::M - function GeneralizedSchur{Ty,M}(S::AbstractMatrix{Ty}, T::AbstractMatrix{Ty}, alpha::Vector, - beta::Vector{Ty}, Q::AbstractMatrix{Ty}, Z::AbstractMatrix{Ty}) where {Ty,M} - new(S, T, alpha, beta, Q, Z) - end -end -function GeneralizedSchur(S::AbstractMatrix{Ty}, T::AbstractMatrix{Ty}, alpha::Vector, - beta::Vector{Ty}, Q::AbstractMatrix{Ty}, Z::AbstractMatrix{Ty}) where Ty - GeneralizedSchur{Ty, typeof(S)}(S, T, alpha, beta, Q, Z) -end - -""" - schurfact!(A::StridedMatrix, B::StridedMatrix) -> F::GeneralizedSchur - -Same as [`schurfact`](@ref) but uses the input matrices `A` and `B` as workspace. -""" -schurfact!(A::StridedMatrix{T}, B::StridedMatrix{T}) where {T<:BlasFloat} = - GeneralizedSchur(LinAlg.LAPACK.gges!('V', 'V', A, B)...) - -""" - schurfact(A::StridedMatrix, B::StridedMatrix) -> F::GeneralizedSchur - -Computes the Generalized Schur (or QZ) factorization of the matrices `A` and `B`. The -(quasi) triangular Schur factors can be obtained from the `Schur` object `F` with `F[:S]` -and `F[:T]`, the left unitary/orthogonal Schur vectors can be obtained with `F[:left]` or -`F[:Q]` and the right unitary/orthogonal Schur vectors can be obtained with `F[:right]` or -`F[:Z]` such that `A=F[:left]*F[:S]*F[:right]'` and `B=F[:left]*F[:T]*F[:right]'`. The -generalized eigenvalues of `A` and `B` can be obtained with `F[:alpha]./F[:beta]`. -""" -schurfact(A::StridedMatrix{T},B::StridedMatrix{T}) where {T<:BlasFloat} = schurfact!(copy(A),copy(B)) -function schurfact(A::StridedMatrix{TA}, B::StridedMatrix{TB}) where {TA,TB} - S = promote_type(Float32, typeof(one(TA)/norm(one(TA))), TB) - return schurfact!(copy_oftype(A, S), copy_oftype(B, S)) -end - -""" - ordschur!(F::GeneralizedSchur, select::Union{Vector{Bool},BitVector}) -> F::GeneralizedSchur - -Same as `ordschur` but overwrites the factorization `F`. -""" -function ordschur!(gschur::GeneralizedSchur, select::Union{Vector{Bool},BitVector}) - _, _, α, β, _, _ = ordschur!(gschur.S, gschur.T, gschur.Q, gschur.Z, select) - gschur[:alpha][:] = α - gschur[:beta][:] = β - return gschur -end - -""" - ordschur(F::GeneralizedSchur, select::Union{Vector{Bool},BitVector}) -> F::GeneralizedSchur - -Reorders the Generalized Schur factorization `F` of a matrix pair `(A, B) = (Q*S*Z', Q*T*Z')` -according to the logical array `select` and returns a GeneralizedSchur object `F`. The -selected eigenvalues appear in the leading diagonal of both `F[:S]` and `F[:T]`, and the -left and right orthogonal/unitary Schur vectors are also reordered such that -`(A, B) = F[:Q]*(F[:S], F[:T])*F[:Z]'` still holds and the generalized eigenvalues of `A` -and `B` can still be obtained with `F[:alpha]./F[:beta]`. -""" -ordschur(gschur::GeneralizedSchur, select::Union{Vector{Bool},BitVector}) = - GeneralizedSchur(ordschur(gschur.S, gschur.T, gschur.Q, gschur.Z, select)...) - -""" - ordschur!(S::StridedMatrix, T::StridedMatrix, Q::StridedMatrix, Z::StridedMatrix, select) -> S::StridedMatrix, T::StridedMatrix, Q::StridedMatrix, Z::StridedMatrix, α::Vector, β::Vector - -Same as [`ordschur`](@ref) but overwrites the factorization the input arguments. -""" -ordschur!(S::StridedMatrix{Ty}, T::StridedMatrix{Ty}, Q::StridedMatrix{Ty}, - Z::StridedMatrix{Ty}, select::Union{Vector{Bool},BitVector}) where {Ty<:BlasFloat} = - LinAlg.LAPACK.tgsen!(convert(Vector{BlasInt}, select), S, T, Q, Z) - -""" - ordschur(S::StridedMatrix, T::StridedMatrix, Q::StridedMatrix, Z::StridedMatrix, select) -> S::StridedMatrix, T::StridedMatrix, Q::StridedMatrix, Z::StridedMatrix, α::Vector, β::Vector - -Reorders the Generalized Schur factorization of a matrix pair `(A, B) = (Q*S*Z', Q*T*Z')` -according to the logical array `select` and returns the matrices `S`, `T`, `Q`, `Z` and -vectors `α` and `β`. The selected eigenvalues appear in the leading diagonal of both `S` -and `T`, and the left and right unitary/orthogonal Schur vectors are also reordered such -that `(A, B) = Q*(S, T)*Z'` still holds and the generalized eigenvalues of `A` and `B` can -still be obtained with `α./β`. -""" -ordschur(S::StridedMatrix{Ty}, T::StridedMatrix{Ty}, Q::StridedMatrix{Ty}, - Z::StridedMatrix{Ty}, select::Union{Vector{Bool},BitVector}) where {Ty<:BlasFloat} = - ordschur!(copy(S), copy(T), copy(Q), copy(Z), select) - -function getindex(F::GeneralizedSchur, d::Symbol) - if d == :S - return F.S - elseif d == :T - return F.T - elseif d == :alpha - return F.alpha - elseif d == :beta - return F.beta - elseif d == :values - return F.alpha./F.beta - elseif d == :Q || d == :left - return F.Q - elseif d == :Z || d == :right - return F.Z - else - throw(KeyError(d)) - end -end - -""" - schur(A::StridedMatrix, B::StridedMatrix) -> S::StridedMatrix, T::StridedMatrix, Q::StridedMatrix, Z::StridedMatrix, α::Vector, β::Vector - -See [`schurfact`](@ref). -""" -function schur(A::StridedMatrix, B::StridedMatrix) - SchurF = schurfact(A, B) - SchurF[:S], SchurF[:T], SchurF[:Q], SchurF[:Z], SchurF[:alpha], SchurF[:beta] -end - -# Conversion -convert(::Type{AbstractMatrix}, F::Schur) = (F.Z * F.T) * F.Z' -convert(::Type{AbstractArray}, F::Schur) = convert(AbstractMatrix, F) -convert(::Type{Matrix}, F::Schur) = convert(Array, convert(AbstractArray, F)) -convert(::Type{Array}, F::Schur) = convert(Matrix, F) -full(F::Schur) = convert(AbstractArray, F) - -copy(F::Schur) = Schur(copy(F.T), copy(F.Z), copy(F.values)) -copy(F::GeneralizedSchur) = GeneralizedSchur(copy(F.S), copy(F.T), copy(F.alpha), copy(F.beta), copy(F.Q), copy(F.Z)) diff --git a/julia-0.6.3/share/julia/base/linalg/special.jl b/julia-0.6.3/share/julia/base/linalg/special.jl deleted file mode 100644 index fd1bd6b..0000000 --- a/julia-0.6.3/share/julia/base/linalg/special.jl +++ /dev/null @@ -1,158 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -# Methods operating on different special matrix types - -# Interconversion between special matrix types -convert(::Type{Bidiagonal}, A::Diagonal{T}) where {T} = - Bidiagonal(A.diag, zeros(T, size(A.diag,1)-1), true) -convert(::Type{SymTridiagonal}, A::Diagonal{T}) where {T} = - SymTridiagonal(A.diag, zeros(T, size(A.diag,1)-1)) -convert(::Type{Tridiagonal}, A::Diagonal{T}) where {T} = - Tridiagonal(zeros(T, size(A.diag,1)-1), A.diag, zeros(T, size(A.diag,1)-1)) - -function convert(::Type{Diagonal}, A::Union{Bidiagonal, SymTridiagonal}) - if !iszero(A.ev) - throw(ArgumentError("matrix cannot be represented as Diagonal")) - end - Diagonal(A.dv) -end - -function convert(::Type{SymTridiagonal}, A::Bidiagonal) - if !iszero(A.ev) - throw(ArgumentError("matrix cannot be represented as SymTridiagonal")) - end - SymTridiagonal(A.dv, A.ev) -end - -convert(::Type{Tridiagonal}, A::Bidiagonal{T}) where {T} = - Tridiagonal(A.isupper ? zeros(T, size(A.dv,1)-1) : A.ev, A.dv, - A.isupper ? A.ev:zeros(T, size(A.dv,1)-1)) - -function convert(::Type{Bidiagonal}, A::SymTridiagonal) - if !iszero(A.ev) - throw(ArgumentError("matrix cannot be represented as Bidiagonal")) - end - Bidiagonal(A.dv, A.ev, true) -end - -function convert(::Type{Diagonal}, A::Tridiagonal) - if !(iszero(A.dl) && iszero(A.du)) - throw(ArgumentError("matrix cannot be represented as Diagonal")) - end - Diagonal(A.d) -end - -function convert(::Type{Bidiagonal}, A::Tridiagonal) - if iszero(A.dl) - return Bidiagonal(A.d, A.du, true) - elseif iszero(A.du) - return Bidiagonal(A.d, A.dl, false) - else - throw(ArgumentError("matrix cannot be represented as Bidiagonal")) - end -end - -function convert(::Type{SymTridiagonal}, A::Tridiagonal) - if A.dl != A.du - throw(ArgumentError("matrix cannot be represented as SymTridiagonal")) - end - SymTridiagonal(A.d, A.dl) -end - -function convert(::Type{Tridiagonal}, A::SymTridiagonal) - Tridiagonal(copy(A.ev), A.dv, A.ev) -end - -function convert(::Type{Diagonal}, A::AbstractTriangular) - if full(A) != diagm(diag(A)) - throw(ArgumentError("matrix cannot be represented as Diagonal")) - end - Diagonal(diag(A)) -end - -function convert(::Type{Bidiagonal}, A::AbstractTriangular) - fA = full(A) - if fA == diagm(diag(A)) + diagm(diag(fA, 1), 1) - return Bidiagonal(diag(A), diag(fA,1), true) - elseif fA == diagm(diag(A)) + diagm(diag(fA, -1), -1) - return Bidiagonal(diag(A), diag(fA,-1), false) - else - throw(ArgumentError("matrix cannot be represented as Bidiagonal")) - end -end - -convert(::Type{SymTridiagonal}, A::AbstractTriangular) = - convert(SymTridiagonal, convert(Tridiagonal, A)) - -function convert(::Type{Tridiagonal}, A::AbstractTriangular) - fA = full(A) - if fA == diagm(diag(A)) + diagm(diag(fA, 1), 1) + diagm(diag(fA, -1), -1) - return Tridiagonal(diag(fA, -1), diag(A), diag(fA,1)) - else - throw(ArgumentError("matrix cannot be represented as Tridiagonal")) - end -end - -# Constructs two method definitions taking into account (assumed) commutativity -# e.g. @commutative f{S,T}(x::S, y::T) = x+y is the same is defining -# f{S,T}(x::S, y::T) = x+y -# f{S,T}(y::T, x::S) = f(x, y) -macro commutative(myexpr) - @assert myexpr.head===:(=) || myexpr.head===:function # Make sure it is a function definition - y = copy(myexpr.args[1].args[2:end]) - reverse!(y) - reversed_call = Expr(:(=), Expr(:call,myexpr.args[1].args[1],y...), myexpr.args[1]) - esc(Expr(:block, myexpr, reversed_call)) -end - -for op in (:+, :-) - SpecialMatrices = [:Diagonal, :Bidiagonal, :Tridiagonal, :Matrix] - for (idx, matrixtype1) in enumerate(SpecialMatrices) # matrixtype1 is the sparser matrix type - for matrixtype2 in SpecialMatrices[idx+1:end] # matrixtype2 is the denser matrix type - @eval begin # TODO quite a few of these conversions are NOT defined - ($op)(A::($matrixtype1), B::($matrixtype2)) = ($op)(convert(($matrixtype2), A), B) - ($op)(A::($matrixtype2), B::($matrixtype1)) = ($op)(A, convert(($matrixtype2), B)) - end - end - end - - for matrixtype1 in (:SymTridiagonal,) # matrixtype1 is the sparser matrix type - for matrixtype2 in (:Tridiagonal, :Matrix) # matrixtype2 is the denser matrix type - @eval begin - ($op)(A::($matrixtype1), B::($matrixtype2)) = ($op)(convert(($matrixtype2), A), B) - ($op)(A::($matrixtype2), B::($matrixtype1)) = ($op)(A, convert(($matrixtype2), B)) - end - end - end - - for matrixtype1 in (:Diagonal, :Bidiagonal) # matrixtype1 is the sparser matrix type - for matrixtype2 in (:SymTridiagonal,) # matrixtype2 is the denser matrix type - @eval begin - ($op)(A::($matrixtype1), B::($matrixtype2)) = ($op)(convert(($matrixtype2), A), B) - ($op)(A::($matrixtype2), B::($matrixtype1)) = ($op)(A, convert(($matrixtype2), B)) - end - end - end - - for matrixtype1 in (:Diagonal,) - for (matrixtype2,matrixtype3) in ((:UpperTriangular,:UpperTriangular), - (:UnitUpperTriangular,:UpperTriangular), - (:LowerTriangular,:LowerTriangular), - (:UnitLowerTriangular,:LowerTriangular)) - @eval begin - ($op)(A::($matrixtype1), B::($matrixtype2)) = ($op)(($matrixtype3)(A), B) - ($op)(A::($matrixtype2), B::($matrixtype1)) = ($op)(A, ($matrixtype3)(B)) - end - end - end - for matrixtype in (:SymTridiagonal,:Tridiagonal,:Bidiagonal,:Matrix) - @eval begin - ($op)(A::AbstractTriangular, B::($matrixtype)) = ($op)(full(A), B) - ($op)(A::($matrixtype), B::AbstractTriangular) = ($op)(A, full(B)) - end - end -end - -A_mul_Bc!(A::AbstractTriangular, B::QRCompactWYQ) = A_mul_Bc!(full!(A),B) -A_mul_Bc!(A::AbstractTriangular, B::QRPackedQ) = A_mul_Bc!(full!(A),B) -A_mul_Bc(A::AbstractTriangular, B::Union{QRCompactWYQ,QRPackedQ}) = A_mul_Bc(full(A), B) diff --git a/julia-0.6.3/share/julia/base/linalg/svd.jl b/julia-0.6.3/share/julia/base/linalg/svd.jl deleted file mode 100644 index 94b1424..0000000 --- a/julia-0.6.3/share/julia/base/linalg/svd.jl +++ /dev/null @@ -1,314 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -# Singular Value Decomposition -struct SVD{T,Tr,M<:AbstractArray} <: Factorization{T} - U::M - S::Vector{Tr} - Vt::M - SVD{T,Tr,M}(U::AbstractArray{T}, S::Vector{Tr}, Vt::AbstractArray{T}) where {T,Tr,M} = - new(U, S, Vt) -end -SVD(U::AbstractArray{T}, S::Vector{Tr}, Vt::AbstractArray{T}) where {T,Tr} = SVD{T,Tr,typeof(U)}(U, S, Vt) - -""" - svdfact!(A, thin::Bool=true) -> SVD - -`svdfact!` is the same as [`svdfact`](@ref), but saves space by -overwriting the input `A`, instead of creating a copy. -""" -function svdfact!(A::StridedMatrix{T}; thin::Bool=true) where T<:BlasFloat - m,n = size(A) - if m == 0 || n == 0 - u,s,vt = (eye(T, m, thin ? n : m), real(zeros(T,0)), eye(T,n,n)) - else - u,s,vt = LAPACK.gesdd!(thin ? 'S' : 'A', A) - end - SVD(u,s,vt) -end - -""" - svdfact(A; thin::Bool=true) -> SVD - -Compute the singular value decomposition (SVD) of `A` and return an `SVD` object. - -`U`, `S`, `V` and `Vt` can be obtained from the factorization `F` with `F[:U]`, -`F[:S]`, `F[:V]` and `F[:Vt]`, such that `A = U*diagm(S)*Vt`. -The algorithm produces `Vt` and hence `Vt` is more efficient to extract than `V`. -The singular values in `S` are sorted in descending order. - -If `thin=true` (default), a thin SVD is returned. For a ``M \\times N`` matrix -`A`, `U` is ``M \\times M`` for a full SVD (`thin=false`) and -``M \\times \\min(M, N)`` for a thin SVD. - -# Example -```jldoctest -julia> A = [1. 0. 0. 0. 2.; 0. 0. 3. 0. 0.; 0. 0. 0. 0. 0.; 0. 2. 0. 0. 0.] -4×5 Array{Float64,2}: - 1.0 0.0 0.0 0.0 2.0 - 0.0 0.0 3.0 0.0 0.0 - 0.0 0.0 0.0 0.0 0.0 - 0.0 2.0 0.0 0.0 0.0 - -julia> F = svdfact(A) -Base.LinAlg.SVD{Float64,Float64,Array{Float64,2}}([0.0 1.0 0.0 0.0; 1.0 0.0 0.0 0.0; 0.0 0.0 0.0 -1.0; 0.0 0.0 1.0 0.0], [3.0, 2.23607, 2.0, 0.0], [-0.0 0.0 … -0.0 0.0; 0.447214 0.0 … 0.0 0.894427; -0.0 1.0 … -0.0 0.0; 0.0 0.0 … 1.0 0.0]) - -julia> F[:U] * diagm(F[:S]) * F[:Vt] -4×5 Array{Float64,2}: - 1.0 0.0 0.0 0.0 2.0 - 0.0 0.0 3.0 0.0 0.0 - 0.0 0.0 0.0 0.0 0.0 - 0.0 2.0 0.0 0.0 0.0 -``` -""" -function svdfact(A::StridedVecOrMat{T}; thin::Bool = true) where T - S = promote_type(Float32, typeof(one(T)/norm(one(T)))) - svdfact!(copy_oftype(A, S), thin = thin) -end -svdfact(x::Number; thin::Bool=true) = SVD(x == 0 ? fill(one(x), 1, 1) : fill(x/abs(x), 1, 1), [abs(x)], fill(one(x), 1, 1)) -svdfact(x::Integer; thin::Bool=true) = svdfact(float(x), thin=thin) - -""" - svd(A; thin::Bool=true) -> U, S, V - -Computes the SVD of `A`, returning `U`, vector `S`, and `V` such that -`A == U*diagm(S)*V'`. The singular values in `S` are sorted in descending order. - -If `thin=true` (default), a thin SVD is returned. For a ``M \\times N`` matrix -`A`, `U` is ``M \\times M`` for a full SVD (`thin=false`) and -``M \\times \\min(M, N)`` for a thin SVD. - -`svd` is a wrapper around [`svdfact`](@ref), extracting all parts -of the `SVD` factorization to a tuple. Direct use of `svdfact` is therefore more -efficient. - -# Example - -```jldoctest -julia> A = [1. 0. 0. 0. 2.; 0. 0. 3. 0. 0.; 0. 0. 0. 0. 0.; 0. 2. 0. 0. 0.] -4×5 Array{Float64,2}: - 1.0 0.0 0.0 0.0 2.0 - 0.0 0.0 3.0 0.0 0.0 - 0.0 0.0 0.0 0.0 0.0 - 0.0 2.0 0.0 0.0 0.0 - -julia> U, S, V = svd(A) -([0.0 1.0 0.0 0.0; 1.0 0.0 0.0 0.0; 0.0 0.0 0.0 -1.0; 0.0 0.0 1.0 0.0], [3.0, 2.23607, 2.0, 0.0], [-0.0 0.447214 -0.0 0.0; 0.0 0.0 1.0 0.0; … ; -0.0 0.0 -0.0 1.0; 0.0 0.894427 0.0 0.0]) - -julia> U*diagm(S)*V' -4×5 Array{Float64,2}: - 1.0 0.0 0.0 0.0 2.0 - 0.0 0.0 3.0 0.0 0.0 - 0.0 0.0 0.0 0.0 0.0 - 0.0 2.0 0.0 0.0 0.0 -``` -""" -function svd(A::Union{Number, AbstractArray}; thin::Bool=true) - F = svdfact(A, thin=thin) - F.U, F.S, F.Vt' -end - -function getindex(F::SVD, d::Symbol) - if d == :U - return F.U - elseif d == :S - return F.S - elseif d == :Vt - return F.Vt - elseif d == :V - return F.Vt' - else - throw(KeyError(d)) - end -end - -""" - svdvals!(A) - -Returns the singular values of `A`, saving space by overwriting the input. -See also [`svdvals`](@ref). -""" -svdvals!(A::StridedMatrix{T}) where {T<:BlasFloat} = findfirst(size(A), 0) > 0 ? zeros(T, 0) : LAPACK.gesdd!('N', A)[2] -svdvals(A::AbstractMatrix{<:BlasFloat}) = svdvals!(copy(A)) - -""" - svdvals(A) - -Returns the singular values of `A` in descending order. - -# Example - -```jldoctest -julia> A = [1. 0. 0. 0. 2.; 0. 0. 3. 0. 0.; 0. 0. 0. 0. 0.; 0. 2. 0. 0. 0.] -4×5 Array{Float64,2}: - 1.0 0.0 0.0 0.0 2.0 - 0.0 0.0 3.0 0.0 0.0 - 0.0 0.0 0.0 0.0 0.0 - 0.0 2.0 0.0 0.0 0.0 - -julia> svdvals(A) -4-element Array{Float64,1}: - 3.0 - 2.23607 - 2.0 - 0.0 -``` -""" -function svdvals(A::AbstractMatrix{T}) where T - S = promote_type(Float32, typeof(one(T)/norm(one(T)))) - svdvals!(copy_oftype(A, S)) -end -svdvals(x::Number) = abs(x) -svdvals(S::SVD{<:Any,T}) where {T} = (S[:S])::Vector{T} - -# SVD least squares -function A_ldiv_B!{T}(A::SVD{T}, B::StridedVecOrMat) - k = searchsortedlast(A.S, eps(real(T))*A.S[1], rev=true) - view(A.Vt,1:k,:)' * (view(A.S,1:k) .\ (view(A.U,:,1:k)' * B)) -end - -# Generalized svd -struct GeneralizedSVD{T,S} <: Factorization{T} - U::S - V::S - Q::S - a::Vector - b::Vector - k::Int - l::Int - R::S - function GeneralizedSVD{T,S}(U::AbstractMatrix{T}, V::AbstractMatrix{T}, Q::AbstractMatrix{T}, - a::Vector, b::Vector, k::Int, l::Int, R::AbstractMatrix{T}) where {T,S} - new(U, V, Q, a, b, k, l, R) - end -end -function GeneralizedSVD(U::AbstractMatrix{T}, V::AbstractMatrix{T}, Q::AbstractMatrix{T}, - a::Vector, b::Vector, k::Int, l::Int, R::AbstractMatrix{T}) where T - GeneralizedSVD{T,typeof(U)}(U, V, Q, a, b, k, l, R) -end - -""" - svdfact!(A, B) -> GeneralizedSVD - -`svdfact!` is the same as [`svdfact`](@ref), but modifies the arguments -`A` and `B` in-place, instead of making copies. -""" -function svdfact!(A::StridedMatrix{T}, B::StridedMatrix{T}) where T<:BlasFloat - # xggsvd3 replaced xggsvd in LAPACK 3.6.0 - if LAPACK.laver() < (3, 6, 0) - U, V, Q, a, b, k, l, R = LAPACK.ggsvd!('U', 'V', 'Q', A, B) - else - U, V, Q, a, b, k, l, R = LAPACK.ggsvd3!('U', 'V', 'Q', A, B) - end - GeneralizedSVD(U, V, Q, a, b, Int(k), Int(l), R) -end -svdfact(A::StridedMatrix{T}, B::StridedMatrix{T}) where {T<:BlasFloat} = svdfact!(copy(A),copy(B)) - -""" - svdfact(A, B) -> GeneralizedSVD - -Compute the generalized SVD of `A` and `B`, returning a `GeneralizedSVD` factorization -object `F`, such that `A = F[:U]*F[:D1]*F[:R0]*F[:Q]'` and `B = F[:V]*F[:D2]*F[:R0]*F[:Q]'`. - -For an M-by-N matrix `A` and P-by-N matrix `B`, - -- `F[:U]` is a M-by-M orthogonal matrix, -- `F[:V]` is a P-by-P orthogonal matrix, -- `F[:Q]` is a N-by-N orthogonal matrix, -- `F[:R0]` is a (K+L)-by-N matrix whose rightmost (K+L)-by-(K+L) block is - nonsingular upper block triangular, -- `F[:D1]` is a M-by-(K+L) diagonal matrix with 1s in the first K entries, -- `F[:D2]` is a P-by-(K+L) matrix whose top right L-by-L block is diagonal, - -`K+L` is the effective numerical rank of the matrix `[A; B]`. - -The entries of `F[:D1]` and `F[:D2]` are related, as explained in the LAPACK -documentation for the -[generalized SVD](http://www.netlib.org/lapack/lug/node36.html) and the -[xGGSVD3](http://www.netlib.org/lapack/explore-html/d6/db3/dggsvd3_8f.html) -routine which is called underneath (in LAPACK 3.6.0 and newer). -""" -function svdfact(A::StridedMatrix{TA}, B::StridedMatrix{TB}) where {TA,TB} - S = promote_type(Float32, typeof(one(TA)/norm(one(TA))),TB) - return svdfact!(copy_oftype(A, S), copy_oftype(B, S)) -end - -""" - svd(A, B) -> U, V, Q, D1, D2, R0 - -Wrapper around [`svdfact`](@ref) extracting all parts of the -factorization to a tuple. Direct use of -`svdfact` is therefore generally more efficient. The function returns the generalized SVD of -`A` and `B`, returning `U`, `V`, `Q`, `D1`, `D2`, and `R0` such that `A = U*D1*R0*Q'` and `B = -V*D2*R0*Q'`. -""" -function svd(A::AbstractMatrix, B::AbstractMatrix) - F = svdfact(A, B) - F[:U], F[:V], F[:Q], F[:D1], F[:D2], F[:R0] -end - -function getindex(obj::GeneralizedSVD{T}, d::Symbol) where T - if d == :U - return obj.U - elseif d == :V - return obj.V - elseif d == :Q - return obj.Q - elseif d == :alpha || d == :a - return obj.a - elseif d == :beta || d == :b - return obj.b - elseif d == :vals || d == :S - return obj.a[1:obj.k + obj.l] ./ obj.b[1:obj.k + obj.l] - elseif d == :D1 - m = size(obj.U, 1) - if m - obj.k - obj.l >= 0 - return [eye(T, obj.k) zeros(T, obj.k, obj.l); zeros(T, obj.l, obj.k) diagm(obj.a[obj.k + 1:obj.k + obj.l]); zeros(T, m - obj.k - obj.l, obj.k + obj.l)] - else - return [eye(T, m, obj.k) [zeros(T, obj.k, m - obj.k); diagm(obj.a[obj.k + 1:m])] zeros(T, m, obj.k + obj.l - m)] - end - elseif d == :D2 - m = size(obj.U, 1) - p = size(obj.V, 1) - if m - obj.k - obj.l >= 0 - return [zeros(T, obj.l, obj.k) diagm(obj.b[obj.k + 1:obj.k + obj.l]); zeros(T, p - obj.l, obj.k + obj.l)] - else - return [zeros(T, p, obj.k) [diagm(obj.b[obj.k + 1:m]); zeros(T, obj.k + p - m, m - obj.k)] [zeros(T, m - obj.k, obj.k + obj.l - m); eye(T, obj.k + p - m, obj.k + obj.l - m)]] - end - elseif d == :R - return obj.R - elseif d == :R0 - n = size(obj.Q, 1) - return [zeros(T, obj.k + obj.l, n - obj.k - obj.l) obj.R] - else - throw(KeyError(d)) - end -end - -function svdvals!(A::StridedMatrix{T}, B::StridedMatrix{T}) where T<:BlasFloat - # xggsvd3 replaced xggsvd in LAPACK 3.6.0 - if LAPACK.laver() < (3, 6, 0) - _, _, _, a, b, k, l, _ = LAPACK.ggsvd!('N', 'N', 'N', A, B) - else - _, _, _, a, b, k, l, _ = LAPACK.ggsvd3!('N', 'N', 'N', A, B) - end - a[1:k + l] ./ b[1:k + l] -end -svdvals(A::StridedMatrix{T},B::StridedMatrix{T}) where {T<:BlasFloat} = svdvals!(copy(A),copy(B)) - -""" - svdvals(A, B) - -Return the generalized singular values from the generalized singular value -decomposition of `A` and `B`. See also [`svdfact`](@ref). -""" -function svdvals(A::StridedMatrix{TA}, B::StridedMatrix{TB}) where {TA,TB} - S = promote_type(Float32, typeof(one(TA)/norm(one(TA))), TB) - return svdvals!(copy_oftype(A, S), copy_oftype(B, S)) -end - -# Conversion -convert(::Type{AbstractMatrix}, F::SVD) = (F.U * Diagonal(F.S)) * F.Vt -convert(::Type{AbstractArray}, F::SVD) = convert(AbstractMatrix, F) -convert(::Type{Matrix}, F::SVD) = convert(Array, convert(AbstractArray, F)) -convert(::Type{Array}, F::SVD) = convert(Matrix, F) -full(F::SVD) = convert(AbstractArray, F) diff --git a/julia-0.6.3/share/julia/base/linalg/symmetric.jl b/julia-0.6.3/share/julia/base/linalg/symmetric.jl deleted file mode 100644 index c101d6a..0000000 --- a/julia-0.6.3/share/julia/base/linalg/symmetric.jl +++ /dev/null @@ -1,560 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -# Symmetric and Hermitian matrices -struct Symmetric{T,S<:AbstractMatrix} <: AbstractMatrix{T} - data::S - uplo::Char -end -""" - Symmetric(A, uplo=:U) - -Construct a `Symmetric` view of the upper (if `uplo = :U`) or lower (if `uplo = :L`) -triangle of the matrix `A`. - -# Example - -```jldoctest -julia> A = [1 0 2 0 3; 0 4 0 5 0; 6 0 7 0 8; 0 9 0 1 0; 2 0 3 0 4] -5×5 Array{Int64,2}: - 1 0 2 0 3 - 0 4 0 5 0 - 6 0 7 0 8 - 0 9 0 1 0 - 2 0 3 0 4 - -julia> Supper = Symmetric(A) -5×5 Symmetric{Int64,Array{Int64,2}}: - 1 0 2 0 3 - 0 4 0 5 0 - 2 0 7 0 8 - 0 5 0 1 0 - 3 0 8 0 4 - -julia> Slower = Symmetric(A, :L) -5×5 Symmetric{Int64,Array{Int64,2}}: - 1 0 6 0 2 - 0 4 0 9 0 - 6 0 7 0 3 - 0 9 0 1 0 - 2 0 3 0 4 -``` - -Note that `Supper` will not be equal to `Slower` unless `A` is itself symmetric (e.g. if `A == A.'`). -""" -Symmetric(A::AbstractMatrix, uplo::Symbol=:U) = (checksquare(A); Symmetric{eltype(A),typeof(A)}(A, char_uplo(uplo))) -Symmetric(A::Symmetric) = A -function Symmetric(A::Symmetric, uplo::Symbol) - if A.uplo == char_uplo(uplo) - return A - else - throw(ArgumentError("Cannot construct Symmetric; uplo doesn't match")) - end -end - -struct Hermitian{T,S<:AbstractMatrix} <: AbstractMatrix{T} - data::S - uplo::Char -end -""" - Hermitian(A, uplo=:U) - -Construct a `Hermitian` view of the upper (if `uplo = :U`) or lower (if `uplo = :L`) -triangle of the matrix `A`. - -# Example - -```jldoctest -julia> A = [1 0 2+2im 0 3-3im; 0 4 0 5 0; 6-6im 0 7 0 8+8im; 0 9 0 1 0; 2+2im 0 3-3im 0 4]; - -julia> Hupper = Hermitian(A) -5×5 Hermitian{Complex{Int64},Array{Complex{Int64},2}}: - 1+0im 0+0im 2+2im 0+0im 3-3im - 0+0im 4+0im 0+0im 5+0im 0+0im - 2-2im 0+0im 7+0im 0+0im 8+8im - 0+0im 5+0im 0+0im 1+0im 0+0im - 3+3im 0+0im 8-8im 0+0im 4+0im - -julia> Hlower = Hermitian(A, :L) -5×5 Hermitian{Complex{Int64},Array{Complex{Int64},2}}: - 1+0im 0+0im 6+6im 0+0im 2-2im - 0+0im 4+0im 0+0im 9+0im 0+0im - 6-6im 0+0im 7+0im 0+0im 3+3im - 0+0im 9+0im 0+0im 1+0im 0+0im - 2+2im 0+0im 3-3im 0+0im 4+0im -``` - -Note that `Hupper` will not be equal to `Hlower` unless `A` is itself Hermitian (e.g. if `A == A'`). -""" -function Hermitian(A::AbstractMatrix, uplo::Symbol=:U) - n = checksquare(A) - for i=1:n - isreal(A[i, i]) || throw(ArgumentError( - "Cannot construct Hermitian from matrix with nonreal diagonals")) - end - Hermitian{eltype(A),typeof(A)}(A, char_uplo(uplo)) -end -Hermitian(A::Hermitian) = A -function Hermitian(A::Hermitian, uplo::Symbol) - if A.uplo == char_uplo(uplo) - return A - else - throw(ArgumentError("Cannot construct Hermitian; uplo doesn't match")) - end -end - -const HermOrSym{T,S} = Union{Hermitian{T,S}, Symmetric{T,S}} -const RealHermSymComplexHerm{T<:Real,S} = Union{Hermitian{T,S}, Symmetric{T,S}, Hermitian{Complex{T},S}} - -size(A::HermOrSym, d) = size(A.data, d) -size(A::HermOrSym) = size(A.data) -@inline function getindex(A::Symmetric, i::Integer, j::Integer) - @boundscheck checkbounds(A, i, j) - @inbounds r = (A.uplo == 'U') == (i < j) ? A.data[i, j] : A.data[j, i] - r -end -@inline function getindex(A::Hermitian, i::Integer, j::Integer) - @boundscheck checkbounds(A, i, j) - @inbounds r = (A.uplo == 'U') == (i < j) ? A.data[i, j] : conj(A.data[j, i]) - r -end - -function setindex!(A::Symmetric, v, i::Integer, j::Integer) - i == j || throw(ArgumentError("Cannot set a non-diagonal index in a symmetric matrix")) - setindex!(A.data, v, i, j) -end - -function setindex!(A::Hermitian, v, i::Integer, j::Integer) - if i != j - throw(ArgumentError("Cannot set a non-diagonal index in a Hermitian matrix")) - elseif !isreal(v) - throw(ArgumentError("Cannot set a diagonal entry in a Hermitian matrix to a nonreal value")) - else - setindex!(A.data, v, i, j) - end -end - -similar(A::Symmetric, ::Type{T}) where {T} = Symmetric(similar(A.data, T)) -# Hermitian version can be simplified when check for imaginary part of -# diagonal in Hermitian has been removed -function similar(A::Hermitian, ::Type{T}) where T - B = similar(A.data, T) - for i = 1:size(A,1) - B[i,i] = 0 - end - return Hermitian(B) -end - -# Conversion -convert(::Type{Matrix}, A::Symmetric) = copytri!(convert(Matrix, copy(A.data)), A.uplo) -convert(::Type{Matrix}, A::Hermitian) = copytri!(convert(Matrix, copy(A.data)), A.uplo, true) -convert(::Type{Array}, A::Union{Symmetric,Hermitian}) = convert(Matrix, A) -full(A::Union{Symmetric,Hermitian}) = convert(Array, A) -parent(A::HermOrSym) = A.data -convert(::Type{Symmetric{T,S}},A::Symmetric{T,S}) where {T,S<:AbstractMatrix} = A -convert(::Type{Symmetric{T,S}},A::Symmetric) where {T,S<:AbstractMatrix} = Symmetric{T,S}(convert(S,A.data),A.uplo) -convert(::Type{AbstractMatrix{T}}, A::Symmetric) where {T} = Symmetric(convert(AbstractMatrix{T}, A.data), Symbol(A.uplo)) -convert(::Type{Hermitian{T,S}},A::Hermitian{T,S}) where {T,S<:AbstractMatrix} = A -convert(::Type{Hermitian{T,S}},A::Hermitian) where {T,S<:AbstractMatrix} = Hermitian{T,S}(convert(S,A.data),A.uplo) -convert(::Type{AbstractMatrix{T}}, A::Hermitian) where {T} = Hermitian(convert(AbstractMatrix{T}, A.data), Symbol(A.uplo)) - -copy(A::Symmetric{T,S}) where {T,S} = (B = copy(A.data); Symmetric{T,typeof(B)}(B,A.uplo)) -copy(A::Hermitian{T,S}) where {T,S} = (B = copy(A.data); Hermitian{T,typeof(B)}(B,A.uplo)) - -function copy!(dest::Symmetric, src::Symmetric) - if src.uplo == dest.uplo - copy!(dest.data, src.data) - else - transpose!(dest.data, src.data) - end - return dest -end - -function copy!(dest::Hermitian, src::Hermitian) - if src.uplo == dest.uplo - copy!(dest.data, src.data) - else - ctranspose!(dest.data, src.data) - end - return dest -end - -ishermitian(A::Hermitian) = true -ishermitian(A::Symmetric{<:Real}) = true -ishermitian(A::Symmetric{<:Complex}) = isreal(A.data) -issymmetric(A::Hermitian{<:Real}) = true -issymmetric(A::Hermitian{<:Complex}) = isreal(A.data) -issymmetric(A::Symmetric) = true -transpose(A::Symmetric) = A -ctranspose(A::Symmetric{<:Real}) = A -function ctranspose(A::Symmetric) - AC = ctranspose(A.data) - return Symmetric(AC, ifelse(A.uplo == 'U', :L, :U)) -end -function transpose(A::Hermitian) - AT = transpose(A.data) - return Hermitian(AT, ifelse(A.uplo == 'U', :L, :U)) -end -ctranspose(A::Hermitian) = A -trace(A::Hermitian) = real(trace(A.data)) - -Base.conj(A::HermOrSym) = typeof(A)(conj(A.data), A.uplo) -Base.conj!(A::HermOrSym) = typeof(A)(conj!(A.data), A.uplo) - -# tril/triu -function tril(A::Hermitian, k::Integer=0) - if A.uplo == 'U' && k <= 0 - return tril!(A.data',k) - elseif A.uplo == 'U' && k > 0 - return tril!(A.data',-1) + tril!(triu(A.data),k) - elseif A.uplo == 'L' && k <= 0 - return tril(A.data,k) - else - return tril(A.data,-1) + tril!(triu!(A.data'),k) - end -end - -function tril(A::Symmetric, k::Integer=0) - if A.uplo == 'U' && k <= 0 - return tril!(A.data.',k) - elseif A.uplo == 'U' && k > 0 - return tril!(A.data.',-1) + tril!(triu(A.data),k) - elseif A.uplo == 'L' && k <= 0 - return tril(A.data,k) - else - return tril(A.data,-1) + tril!(triu!(A.data.'),k) - end -end - -function triu(A::Hermitian, k::Integer=0) - if A.uplo == 'U' && k >= 0 - return triu(A.data,k) - elseif A.uplo == 'U' && k < 0 - return triu(A.data,1) + triu!(tril!(A.data'),k) - elseif A.uplo == 'L' && k >= 0 - return triu!(A.data',k) - else - return triu!(A.data',1) + triu!(tril(A.data),k) - end -end - -function triu(A::Symmetric, k::Integer=0) - if A.uplo == 'U' && k >= 0 - return triu(A.data,k) - elseif A.uplo == 'U' && k < 0 - return triu(A.data,1) + triu!(tril!(A.data.'),k) - elseif A.uplo == 'L' && k >= 0 - return triu!(A.data.',k) - else - return triu!(A.data.',1) + triu!(tril(A.data),k) - end -end - -(-)(A::Symmetric{Tv,S}) where {Tv,S<:AbstractMatrix} = Symmetric{Tv,S}(-A.data, A.uplo) - -## Matvec -A_mul_B!(y::StridedVector{T}, A::Symmetric{T,<:StridedMatrix}, x::StridedVector{T}) where {T<:BlasFloat} = - BLAS.symv!(A.uplo, one(T), A.data, x, zero(T), y) -A_mul_B!(y::StridedVector{T}, A::Hermitian{T,<:StridedMatrix}, x::StridedVector{T}) where {T<:BlasComplex} = - BLAS.hemv!(A.uplo, one(T), A.data, x, zero(T), y) -## Matmat -A_mul_B!(C::StridedMatrix{T}, A::Symmetric{T,<:StridedMatrix}, B::StridedMatrix{T}) where {T<:BlasFloat} = - BLAS.symm!('L', A.uplo, one(T), A.data, B, zero(T), C) -A_mul_B!(C::StridedMatrix{T}, A::StridedMatrix{T}, B::Symmetric{T,<:StridedMatrix}) where {T<:BlasFloat} = - BLAS.symm!('R', B.uplo, one(T), B.data, A, zero(T), C) -A_mul_B!(C::StridedMatrix{T}, A::Hermitian{T,<:StridedMatrix}, B::StridedMatrix{T}) where {T<:BlasComplex} = - BLAS.hemm!('L', A.uplo, one(T), A.data, B, zero(T), C) -A_mul_B!(C::StridedMatrix{T}, A::StridedMatrix{T}, B::Hermitian{T,<:StridedMatrix}) where {T<:BlasComplex} = - BLAS.hemm!('R', B.uplo, one(T), B.data, A, zero(T), C) - -*(A::HermOrSym, B::HermOrSym) = full(A)*full(B) -*(A::StridedMatrix, B::HermOrSym) = A*full(B) - -for T in (:Symmetric, :Hermitian), op in (:+, :-, :*, :/) - # Deal with an ambiguous case - @eval ($op)(A::$T, x::Bool) = ($T)(($op)(A.data, x), Symbol(A.uplo)) - S = T == :Hermitian ? :Real : :Number - @eval ($op)(A::$T, x::$S) = ($T)(($op)(A.data, x), Symbol(A.uplo)) -end - -bkfact(A::HermOrSym) = bkfact(A.data, Symbol(A.uplo), issymmetric(A)) -factorize(A::HermOrSym) = bkfact(A) - -det(A::RealHermSymComplexHerm) = real(det(bkfact(A))) -det(A::Symmetric{<:Real}) = det(bkfact(A)) -det(A::Symmetric) = det(bkfact(A)) - -\(A::HermOrSym{<:Any,<:StridedMatrix}, B::StridedVecOrMat) = \(bkfact(A.data, Symbol(A.uplo), issymmetric(A)), B) - -inv(A::Hermitian{T,S}) where {T<:BlasFloat,S<:StridedMatrix} = Hermitian{T,S}(inv(bkfact(A)), A.uplo) -inv(A::Symmetric{T,S}) where {T<:BlasFloat,S<:StridedMatrix} = Symmetric{T,S}(inv(bkfact(A)), A.uplo) - -isposdef!(A::HermOrSym{<:BlasFloat,<:StridedMatrix}) = ishermitian(A) && LAPACK.potrf!(A.uplo, A.data)[2] == 0 - -eigfact!(A::RealHermSymComplexHerm{<:BlasReal,<:StridedMatrix}) = Eigen(LAPACK.syevr!('V', 'A', A.uplo, A.data, 0.0, 0.0, 0, 0, -1.0)...) - -function eigfact(A::RealHermSymComplexHerm) - T = eltype(A) - S = promote_type(Float32, typeof(zero(T)/norm(one(T)))) - eigfact!(S != T ? convert(AbstractMatrix{S}, A) : copy(A)) -end - -eigfact!(A::RealHermSymComplexHerm{<:BlasReal,<:StridedMatrix}, irange::UnitRange) = Eigen(LAPACK.syevr!('V', 'I', A.uplo, A.data, 0.0, 0.0, irange.start, irange.stop, -1.0)...) - -""" - eigfact(A::Union{SymTridiagonal, Hermitian, Symmetric}, irange::UnitRange) -> Eigen - -Computes the eigenvalue decomposition of `A`, returning an `Eigen` factorization object `F` -which contains the eigenvalues in `F[:values]` and the eigenvectors in the columns of the -matrix `F[:vectors]`. (The `k`th eigenvector can be obtained from the slice `F[:vectors][:, k]`.) - -The following functions are available for `Eigen` objects: [`inv`](@ref), [`det`](@ref), and [`isposdef`](@ref). - -The `UnitRange` `irange` specifies indices of the sorted eigenvalues to search for. - -!!! note - If `irange` is not `1:n`, where `n` is the dimension of `A`, then the returned factorization - will be a *truncated* factorization. -""" -function eigfact(A::RealHermSymComplexHerm, irange::UnitRange) - T = eltype(A) - S = promote_type(Float32, typeof(zero(T)/norm(one(T)))) - eigfact!(S != T ? convert(AbstractMatrix{S}, A) : copy(A), irange) -end - -eigfact!(A::RealHermSymComplexHerm{T,<:StridedMatrix}, vl::Real, vh::Real) where {T<:BlasReal} = - Eigen(LAPACK.syevr!('V', 'V', A.uplo, A.data, convert(T, vl), convert(T, vh), 0, 0, -1.0)...) - -""" - eigfact(A::Union{SymTridiagonal, Hermitian, Symmetric}, vl::Real, vu::Real) -> Eigen - -Computes the eigenvalue decomposition of `A`, returning an `Eigen` factorization object `F` -which contains the eigenvalues in `F[:values]` and the eigenvectors in the columns of the -matrix `F[:vectors]`. (The `k`th eigenvector can be obtained from the slice `F[:vectors][:, k]`.) - -The following functions are available for `Eigen` objects: [`inv`](@ref), [`det`](@ref), and [`isposdef`](@ref). - -`vl` is the lower bound of the window of eigenvalues to search for, and `vu` is the upper bound. - -!!! note - If [`vl`, `vu`] does not contain all eigenvalues of `A`, then the returned factorization - will be a *truncated* factorization. -""" -function eigfact(A::RealHermSymComplexHerm, vl::Real, vh::Real) - T = eltype(A) - S = promote_type(Float32, typeof(zero(T)/norm(one(T)))) - eigfact!(S != T ? convert(AbstractMatrix{S}, A) : copy(A), vl, vh) -end - -eigvals!(A::RealHermSymComplexHerm{<:BlasReal,<:StridedMatrix}) = - LAPACK.syevr!('N', 'A', A.uplo, A.data, 0.0, 0.0, 0, 0, -1.0)[1] - -function eigvals(A::RealHermSymComplexHerm) - T = eltype(A) - S = promote_type(Float32, typeof(zero(T)/norm(one(T)))) - eigvals!(S != T ? convert(AbstractMatrix{S}, A) : copy(A)) -end - -""" - eigvals!(A::Union{SymTridiagonal, Hermitian, Symmetric}, irange::UnitRange) -> values - -Same as [`eigvals`](@ref), but saves space by overwriting the input `A`, instead of creating a copy. -`irange` is a range of eigenvalue *indices* to search for - for instance, the 2nd to 8th eigenvalues. -""" -eigvals!(A::RealHermSymComplexHerm{<:BlasReal,<:StridedMatrix}, irange::UnitRange) = - LAPACK.syevr!('N', 'I', A.uplo, A.data, 0.0, 0.0, irange.start, irange.stop, -1.0)[1] - -""" - eigvals(A::Union{SymTridiagonal, Hermitian, Symmetric}, irange::UnitRange) -> values - -Returns the eigenvalues of `A`. It is possible to calculate only a subset of the -eigenvalues by specifying a `UnitRange` `irange` covering indices of the sorted eigenvalues, -e.g. the 2nd to 8th eigenvalues. - -```jldoctest -julia> A = SymTridiagonal([1.; 2.; 1.], [2.; 3.]) -3×3 SymTridiagonal{Float64}: - 1.0 2.0 ⋅ - 2.0 2.0 3.0 - ⋅ 3.0 1.0 - -julia> eigvals(A, 2:2) -1-element Array{Float64,1}: - 1.0 - -julia> eigvals(A) -3-element Array{Float64,1}: - -2.14005 - 1.0 - 5.14005 -``` -""" -function eigvals(A::RealHermSymComplexHerm, irange::UnitRange) - T = eltype(A) - S = promote_type(Float32, typeof(zero(T)/norm(one(T)))) - eigvals!(S != T ? convert(AbstractMatrix{S}, A) : copy(A), irange) -end - -""" - eigvals!(A::Union{SymTridiagonal, Hermitian, Symmetric}, vl::Real, vu::Real) -> values - -Same as [`eigvals`](@ref), but saves space by overwriting the input `A`, instead of creating a copy. -`vl` is the lower bound of the interval to search for eigenvalues, and `vu` is the upper bound. -""" -eigvals!(A::RealHermSymComplexHerm{T,<:StridedMatrix}, vl::Real, vh::Real) where {T<:BlasReal} = - LAPACK.syevr!('N', 'V', A.uplo, A.data, convert(T, vl), convert(T, vh), 0, 0, -1.0)[1] - -""" - eigvals(A::Union{SymTridiagonal, Hermitian, Symmetric}, vl::Real, vu::Real) -> values - -Returns the eigenvalues of `A`. It is possible to calculate only a subset of the eigenvalues -by specifying a pair `vl` and `vu` for the lower and upper boundaries of the eigenvalues. - -```jldoctest -julia> A = SymTridiagonal([1.; 2.; 1.], [2.; 3.]) -3×3 SymTridiagonal{Float64}: - 1.0 2.0 ⋅ - 2.0 2.0 3.0 - ⋅ 3.0 1.0 - -julia> eigvals(A, -1, 2) -1-element Array{Float64,1}: - 1.0 - -julia> eigvals(A) -3-element Array{Float64,1}: - -2.14005 - 1.0 - 5.14005 -``` -""" -function eigvals(A::RealHermSymComplexHerm, vl::Real, vh::Real) - T = eltype(A) - S = promote_type(Float32, typeof(zero(T)/norm(one(T)))) - eigvals!(S != T ? convert(AbstractMatrix{S}, A) : copy(A), vl, vh) -end - -eigmax(A::RealHermSymComplexHerm{<:Real,<:StridedMatrix}) = eigvals(A, size(A, 1):size(A, 1))[1] -eigmin(A::RealHermSymComplexHerm{<:Real,<:StridedMatrix}) = eigvals(A, 1:1)[1] - -function eigfact!(A::HermOrSym{T,S}, B::HermOrSym{T,S}) where {T<:BlasReal,S<:StridedMatrix} - vals, vecs, _ = LAPACK.sygvd!(1, 'V', A.uplo, A.data, B.uplo == A.uplo ? B.data : B.data') - GeneralizedEigen(vals, vecs) -end -function eigfact!(A::Hermitian{T,S}, B::Hermitian{T,S}) where {T<:BlasComplex,S<:StridedMatrix} - vals, vecs, _ = LAPACK.sygvd!(1, 'V', A.uplo, A.data, B.uplo == A.uplo ? B.data : B.data') - GeneralizedEigen(vals, vecs) -end - -eigvals!(A::HermOrSym{T,S}, B::HermOrSym{T,S}) where {T<:BlasReal,S<:StridedMatrix} = - LAPACK.sygvd!(1, 'N', A.uplo, A.data, B.uplo == A.uplo ? B.data : B.data')[1] -eigvals!(A::Hermitian{T,S}, B::Hermitian{T,S}) where {T<:BlasComplex,S<:StridedMatrix} = - LAPACK.sygvd!(1, 'N', A.uplo, A.data, B.uplo == A.uplo ? B.data : B.data')[1] - -eigvecs(A::HermOrSym) = eigvecs(eigfact(A)) - -function svdvals!(A::RealHermSymComplexHerm) - vals = eigvals!(A) - for i = 1:length(vals) - vals[i] = abs(vals[i]) - end - return sort!(vals, rev = true) -end - -# Matrix functions -function ^(A::Symmetric{T}, p::Integer) where T<:Real - if p < 0 - return Symmetric(Base.power_by_squaring(inv(A), -p)) - else - return Symmetric(Base.power_by_squaring(A, p)) - end -end -function ^(A::Symmetric{T}, p::Real) where T<:Real - F = eigfact(A) - if all(λ -> λ ≥ 0, F.values) - retmat = (F.vectors * Diagonal((F.values).^p)) * F.vectors' - else - retmat = (F.vectors * Diagonal((complex(F.values)).^p)) * F.vectors' - end - return Symmetric(retmat) -end -function ^(A::Hermitian, p::Integer) - n = checksquare(A) - if p < 0 - retmat = Base.power_by_squaring(inv(A), -p) - else - retmat = Base.power_by_squaring(A, p) - end - for i = 1:n - retmat[i,i] = real(retmat[i,i]) - end - return Hermitian(retmat) -end -function ^(A::Hermitian{T}, p::Real) where T - n = checksquare(A) - F = eigfact(A) - if all(λ -> λ ≥ 0, F.values) - retmat = (F.vectors * Diagonal((F.values).^p)) * F.vectors' - if T <: Real - return Hermitian(retmat) - else - for i = 1:n - retmat[i,i] = real(retmat[i,i]) - end - return Hermitian(retmat) - end - else - retmat = (F.vectors * Diagonal((complex(F.values).^p))) * F.vectors' - return retmat - end -end - -function expm(A::Symmetric) - F = eigfact(A) - return Symmetric((F.vectors * Diagonal(exp.(F.values))) * F.vectors') -end -function expm(A::Hermitian{T}) where T - n = checksquare(A) - F = eigfact(A) - retmat = (F.vectors * Diagonal(exp.(F.values))) * F.vectors' - if T <: Real - return real(Hermitian(retmat)) - else - for i = 1:n - retmat[i,i] = real(retmat[i,i]) - end - return Hermitian(retmat) - end -end - -for (funm, func) in ([:logm,:log], [:sqrtm,:sqrt]) - @eval begin - function ($funm)(A::Symmetric{T}) where T<:Real - F = eigfact(A) - if all(λ -> λ ≥ 0, F.values) - retmat = (F.vectors * Diagonal(($func).(F.values))) * F.vectors' - else - retmat = (F.vectors * Diagonal(($func).(complex.(F.values)))) * F.vectors' - end - return Symmetric(retmat) - end - - function ($funm)(A::Hermitian{T}) where T - n = checksquare(A) - F = eigfact(A) - if all(λ -> λ ≥ 0, F.values) - retmat = (F.vectors * Diagonal(($func).(F.values))) * F.vectors' - if T <: Real - return Hermitian(retmat) - else - for i = 1:n - retmat[i,i] = real(retmat[i,i]) - end - return Hermitian(retmat) - end - else - retmat = (F.vectors * Diagonal(($func).(complex(F.values)))) * F.vectors' - return retmat - end - end - end -end diff --git a/julia-0.6.3/share/julia/base/linalg/transpose.jl b/julia-0.6.3/share/julia/base/linalg/transpose.jl deleted file mode 100644 index d2b51e7..0000000 --- a/julia-0.6.3/share/julia/base/linalg/transpose.jl +++ /dev/null @@ -1,154 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -ctranspose(a::AbstractArray) = error("ctranspose not defined for $(typeof(a)). Consider using `permutedims` for higher-dimensional arrays.") -transpose(a::AbstractArray) = error("transpose not defined for $(typeof(a)). Consider using `permutedims` for higher-dimensional arrays.") - -## Matrix transposition ## - -""" - transpose!(dest,src) - -Transpose array `src` and store the result in the preallocated array `dest`, which should -have a size corresponding to `(size(src,2),size(src,1))`. No in-place transposition is -supported and unexpected results will happen if `src` and `dest` have overlapping memory -regions. -""" -transpose!(B::AbstractMatrix, A::AbstractMatrix) = transpose_f!(transpose, B, A) - -""" - ctranspose!(dest,src) - -Conjugate transpose array `src` and store the result in the preallocated array `dest`, which -should have a size corresponding to `(size(src,2),size(src,1))`. No in-place transposition -is supported and unexpected results will happen if `src` and `dest` have overlapping memory -regions. -""" -ctranspose!(B::AbstractMatrix, A::AbstractMatrix) = transpose_f!(ctranspose, B, A) -function transpose!(B::AbstractVector, A::AbstractMatrix) - indices(B,1) == indices(A,2) && indices(A,1) == 1:1 || throw(DimensionMismatch("transpose")) - copy!(B, A) -end -function transpose!(B::AbstractMatrix, A::AbstractVector) - indices(B,2) == indices(A,1) && indices(B,1) == 1:1 || throw(DimensionMismatch("transpose")) - copy!(B, A) -end -function ctranspose!(B::AbstractVector, A::AbstractMatrix) - indices(B,1) == indices(A,2) && indices(A,1) == 1:1 || throw(DimensionMismatch("transpose")) - ccopy!(B, A) -end -function ctranspose!(B::AbstractMatrix, A::AbstractVector) - indices(B,2) == indices(A,1) && indices(B,1) == 1:1 || throw(DimensionMismatch("transpose")) - ccopy!(B, A) -end - -const transposebaselength=64 -function transpose_f!(f, B::AbstractMatrix, A::AbstractMatrix) - inds = indices(A) - indices(B,1) == inds[2] && indices(B,2) == inds[1] || throw(DimensionMismatch(string(f))) - - m, n = length(inds[1]), length(inds[2]) - if m*n<=4*transposebaselength - @inbounds begin - for j = inds[2] - for i = inds[1] - B[j,i] = f(A[i,j]) - end - end - end - else - transposeblock!(f,B,A,m,n,first(inds[1])-1,first(inds[2])-1) - end - return B -end -function transposeblock!(f, B::AbstractMatrix, A::AbstractMatrix, m::Int, n::Int, offseti::Int, offsetj::Int) - if m*n<=transposebaselength - @inbounds begin - for j = offsetj+(1:n) - for i = offseti+(1:m) - B[j,i] = f(A[i,j]) - end - end - end - elseif m>n - newm=m>>1 - transposeblock!(f,B,A,newm,n,offseti,offsetj) - transposeblock!(f,B,A,m-newm,n,offseti+newm,offsetj) - else - newn=n>>1 - transposeblock!(f,B,A,m,newn,offseti,offsetj) - transposeblock!(f,B,A,m,n-newn,offseti,offsetj+newn) - end - return B -end - -function ccopy!(B, A) - RB, RA = eachindex(B), eachindex(A) - if RB == RA - for i = RB - B[i] = ctranspose(A[i]) - end - else - for (i,j) = zip(RB, RA) - B[i] = ctranspose(A[j]) - end - end -end - -""" - transpose(A::AbstractMatrix) - -The transposition operator (`.'`). - -# Example - -```jldoctest -julia> A = [1 2 3; 4 5 6; 7 8 9] -3×3 Array{Int64,2}: - 1 2 3 - 4 5 6 - 7 8 9 - -julia> transpose(A) -3×3 Array{Int64,2}: - 1 4 7 - 2 5 8 - 3 6 9 -``` -""" -function transpose(A::AbstractMatrix) - ind1, ind2 = indices(A) - B = similar(A, (ind2, ind1)) - transpose!(B, A) -end -function ctranspose(A::AbstractMatrix) - ind1, ind2 = indices(A) - B = similar(A, (ind2, ind1)) - ctranspose!(B, A) -end - -@inline ctranspose(A::AbstractVector{<:Real}) = transpose(A) -@inline ctranspose(A::AbstractMatrix{<:Real}) = transpose(A) - -function copy_transpose!(B::AbstractVecOrMat, ir_dest::Range{Int}, jr_dest::Range{Int}, - A::AbstractVecOrMat, ir_src::Range{Int}, jr_src::Range{Int}) - if length(ir_dest) != length(jr_src) - throw(ArgumentError(string("source and destination must have same size (got ", - length(jr_src)," and ",length(ir_dest),")"))) - end - if length(jr_dest) != length(ir_src) - throw(ArgumentError(string("source and destination must have same size (got ", - length(ir_src)," and ",length(jr_dest),")"))) - end - @boundscheck checkbounds(B, ir_dest, jr_dest) - @boundscheck checkbounds(A, ir_src, jr_src) - idest = first(ir_dest) - for jsrc in jr_src - jdest = first(jr_dest) - for isrc in ir_src - B[idest,jdest] = A[isrc,jsrc] - jdest += step(jr_dest) - end - idest += step(ir_dest) - end - return B -end diff --git a/julia-0.6.3/share/julia/base/linalg/triangular.jl b/julia-0.6.3/share/julia/base/linalg/triangular.jl deleted file mode 100644 index 8c95da6..0000000 --- a/julia-0.6.3/share/julia/base/linalg/triangular.jl +++ /dev/null @@ -1,2208 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -## Triangular - -# could be renamed to Triangular when that name has been fully deprecated -abstract type AbstractTriangular{T,S<:AbstractMatrix} <: AbstractMatrix{T} end - -# First loop through all methods that don't need special care for upper/lower and unit diagonal -for t in (:LowerTriangular, :UnitLowerTriangular, :UpperTriangular, - :UnitUpperTriangular) - @eval begin - struct $t{T,S<:AbstractMatrix} <: AbstractTriangular{T,S} - data::S - end - $t(A::$t) = A - function $t(A::AbstractMatrix) - Base.LinAlg.checksquare(A) - return $t{eltype(A), typeof(A)}(A) - end - - size(A::$t, d) = size(A.data, d) - size(A::$t) = size(A.data) - - convert(::Type{$t{T}}, A::$t{T}) where {T} = A - function convert(::Type{$t{T}}, A::$t) where T - Anew = convert(AbstractMatrix{T}, A.data) - $t(Anew) - end - convert(::Type{AbstractMatrix{T}}, A::$t{T}) where {T} = A - convert(::Type{AbstractMatrix{T}}, A::$t) where {T} = convert($t{T}, A) - convert(::Type{Matrix}, A::$t{T}) where {T} = convert(Matrix{T}, A) - - function similar(A::$t, ::Type{T}) where T - B = similar(A.data, T) - return $t(B) - end - - copy(A::$t) = $t(copy(A.data)) - - broadcast(::typeof(big), A::$t) = $t(big.(A.data)) - - real(A::$t{<:Real}) = A - real(A::$t{<:Complex}) = (B = real(A.data); $t(B)) - broadcast(::typeof(abs), A::$t) = $t(abs.(A.data)) - end -end - -LowerTriangular(U::UpperTriangular) = throw(ArgumentError( - "cannot create a LowerTriangular matrix from an UpperTriangular input")) -UpperTriangular(U::LowerTriangular) = throw(ArgumentError( - "cannot create an UpperTriangular matrix from a LowerTriangular input")) - -""" - LowerTriangular(A::AbstractMatrix) - -Construct a `LowerTriangular` view of the the matrix `A`. - -# Example - -```jldoctest -julia> A = [1.0 2.0 3.0; 4.0 5.0 6.0; 7.0 8.0 9.0] -3×3 Array{Float64,2}: - 1.0 2.0 3.0 - 4.0 5.0 6.0 - 7.0 8.0 9.0 - -julia> LowerTriangular(A) -3×3 LowerTriangular{Float64,Array{Float64,2}}: - 1.0 ⋅ ⋅ - 4.0 5.0 ⋅ - 7.0 8.0 9.0 -``` -""" -LowerTriangular -""" - UpperTriangular(A::AbstractMatrix) - -Construct an `UpperTriangular` view of the the matrix `A`. - -# Example - -```jldoctest -julia> A = [1.0 2.0 3.0; 4.0 5.0 6.0; 7.0 8.0 9.0] -3×3 Array{Float64,2}: - 1.0 2.0 3.0 - 4.0 5.0 6.0 - 7.0 8.0 9.0 - -julia> UpperTriangular(A) -3×3 UpperTriangular{Float64,Array{Float64,2}}: - 1.0 2.0 3.0 - ⋅ 5.0 6.0 - ⋅ ⋅ 9.0 -``` -""" -UpperTriangular - -imag(A::UpperTriangular) = UpperTriangular(imag(A.data)) -imag(A::LowerTriangular) = LowerTriangular(imag(A.data)) -imag(A::UnitLowerTriangular) = LowerTriangular(tril!(imag(A.data),-1)) -imag(A::UnitUpperTriangular) = UpperTriangular(triu!(imag(A.data),1)) - -convert(::Type{Array}, A::AbstractTriangular) = convert(Matrix, A) -full(A::AbstractTriangular) = convert(Array, A) -parent(A::AbstractTriangular) = A.data - -# then handle all methods that requires specific handling of upper/lower and unit diagonal - -function convert(::Type{Matrix{T}}, A::LowerTriangular) where T - B = Matrix{T}(size(A, 1), size(A, 1)) - copy!(B, A.data) - tril!(B) - B -end -function convert(::Type{Matrix{T}}, A::UnitLowerTriangular) where T - B = Matrix{T}(size(A, 1), size(A, 1)) - copy!(B, A.data) - tril!(B) - for i = 1:size(B,1) - B[i,i] = 1 - end - B -end -function convert(::Type{Matrix{T}}, A::UpperTriangular) where T - B = Matrix{T}(size(A, 1), size(A, 1)) - copy!(B, A.data) - triu!(B) - B -end -function convert(::Type{Matrix{T}}, A::UnitUpperTriangular) where T - B = Matrix{T}(size(A, 1), size(A, 1)) - copy!(B, A.data) - triu!(B) - for i = 1:size(B,1) - B[i,i] = 1 - end - B -end - -function full!(A::LowerTriangular) - B = A.data - tril!(B) - B -end -function full!(A::UnitLowerTriangular) - B = A.data - tril!(B) - for i = 1:size(A,1) - B[i,i] = 1 - end - B -end -function full!(A::UpperTriangular) - B = A.data - triu!(B) - B -end -function full!(A::UnitUpperTriangular) - B = A.data - triu!(B) - for i = 1:size(A,1) - B[i,i] = 1 - end - B -end - -getindex(A::UnitLowerTriangular{T}, i::Integer, j::Integer) where {T} = - i > j ? A.data[i,j] : ifelse(i == j, oneunit(T), zero(T)) -getindex(A::LowerTriangular, i::Integer, j::Integer) = - i >= j ? A.data[i,j] : zero(A.data[j,i]) -getindex(A::UnitUpperTriangular{T}, i::Integer, j::Integer) where {T} = - i < j ? A.data[i,j] : ifelse(i == j, oneunit(T), zero(T)) -getindex(A::UpperTriangular, i::Integer, j::Integer) = - i <= j ? A.data[i,j] : zero(A.data[j,i]) - -function setindex!(A::UpperTriangular, x, i::Integer, j::Integer) - if i > j - x == 0 || throw(ArgumentError("cannot set index in the lower triangular part " * - "($i, $j) of an UpperTriangular matrix to a nonzero value ($x)")) - else - A.data[i,j] = x - end - return A -end - -function setindex!(A::UnitUpperTriangular, x, i::Integer, j::Integer) - if i > j - x == 0 || throw(ArgumentError("cannot set index in the lower triangular part " * - "($i, $j) of a UnitUpperTriangular matrix to a nonzero value ($x)")) - elseif i == j - x == 1 || throw(ArgumentError("cannot set index on the diagonal ($i, $j) " * - "of a UnitUpperTriangular matrix to a non-unit value ($x)")) - else - A.data[i,j] = x - end - return A -end - -function setindex!(A::LowerTriangular, x, i::Integer, j::Integer) - if i < j - x == 0 || throw(ArgumentError("cannot set index in the upper triangular part " * - "($i, $j) of a LowerTriangular matrix to a nonzero value ($x)")) - else - A.data[i,j] = x - end - return A -end - -function setindex!(A::UnitLowerTriangular, x, i::Integer, j::Integer) - if i < j - x == 0 || throw(ArgumentError("cannot set index in the upper triangular part " * - "($i, $j) of a UnitLowerTriangular matrix to a nonzero value ($x)")) - elseif i == j - x == 1 || throw(ArgumentError("cannot set index on the diagonal ($i, $j) " * - "of a UnitLowerTriangular matrix to a non-unit value ($x)")) - else - A.data[i,j] = x - end - return A -end - - -## structured matrix methods ## -function Base.replace_in_print_matrix(A::UpperTriangular,i::Integer,j::Integer,s::AbstractString) - i<=j ? s : Base.replace_with_centered_mark(s) -end -function Base.replace_in_print_matrix(A::LowerTriangular,i::Integer,j::Integer,s::AbstractString) - i>=j ? s : Base.replace_with_centered_mark(s) -end - - -istril(A::LowerTriangular) = true -istril(A::UnitLowerTriangular) = true -istriu(A::UpperTriangular) = true -istriu(A::UnitUpperTriangular) = true - -function tril!(A::UpperTriangular, k::Integer=0) - n = size(A,1) - if abs(k) > n - throw(ArgumentError("requested diagonal, $k, out of bounds in matrix of size ($n,$n)")) - elseif k < 0 - fill!(A.data,0) - return A - elseif k == 0 - for j in 1:n, i in 1:j-1 - A.data[i,j] = 0 - end - return A - else - return UpperTriangular(tril!(A.data,k)) - end -end -triu!(A::UpperTriangular, k::Integer=0) = UpperTriangular(triu!(A.data,k)) - -function tril!(A::UnitUpperTriangular{T}, k::Integer=0) where T - n = size(A,1) - if abs(k) > n - throw(ArgumentError("requested diagonal, $k, out of bounds in matrix of size ($n,$n)")) - elseif k < 0 - fill!(A.data, zero(T)) - return UpperTriangular(A.data) - elseif k == 0 - fill!(A.data, zero(T)) - for i in diagind(A) - A.data[i] = oneunit(T) - end - return UpperTriangular(A.data) - else - for i in diagind(A) - A.data[i] = oneunit(T) - end - return UpperTriangular(tril!(A.data,k)) - end -end - -function triu!(A::UnitUpperTriangular, k::Integer=0) - for i in diagind(A) - A.data[i] = oneunit(eltype(A)) - end - return triu!(UpperTriangular(A.data),k) -end - -function triu!(A::LowerTriangular, k::Integer=0) - n = size(A,1) - if abs(k) > n - throw(ArgumentError("requested diagonal, $k, out of bounds in matrix of size ($n,$n)")) - elseif k > 0 - fill!(A.data,0) - return A - elseif k == 0 - for j in 1:n, i in j+1:n - A.data[i,j] = 0 - end - return A - else - return LowerTriangular(triu!(A.data,k)) - end -end - -tril!(A::LowerTriangular, k::Integer=0) = LowerTriangular(tril!(A.data,k)) - -function triu!(A::UnitLowerTriangular{T}, k::Integer=0) where T - n = size(A,1) - if abs(k) > n - throw(ArgumentError("requested diagonal, $k, out of bounds in matrix of size ($n,$n)")) - elseif k > 0 - fill!(A.data, zero(T)) - return LowerTriangular(A.data) - elseif k == 0 - fill!(A.data, zero(T)) - for i in diagind(A) - A.data[i] = oneunit(T) - end - return LowerTriangular(A.data) - else - for i in diagind(A) - A.data[i] = oneunit(T) - end - return LowerTriangular(triu!(A.data,k)) - end -end - -function tril!(A::UnitLowerTriangular, k::Integer=0) - for i in diagind(A) - A.data[i] = oneunit(eltype(A)) - end - return tril!(LowerTriangular(A.data),k) -end - -transpose(A::LowerTriangular) = UpperTriangular(transpose(A.data)) -transpose(A::UnitLowerTriangular) = UnitUpperTriangular(transpose(A.data)) -transpose(A::UpperTriangular) = LowerTriangular(transpose(A.data)) -transpose(A::UnitUpperTriangular) = UnitLowerTriangular(transpose(A.data)) -ctranspose(A::LowerTriangular) = UpperTriangular(ctranspose(A.data)) -ctranspose(A::UnitLowerTriangular) = UnitUpperTriangular(ctranspose(A.data)) -ctranspose(A::UpperTriangular) = LowerTriangular(ctranspose(A.data)) -ctranspose(A::UnitUpperTriangular) = UnitLowerTriangular(ctranspose(A.data)) - -transpose!(A::LowerTriangular) = UpperTriangular(copytri!(A.data, 'L')) -transpose!(A::UnitLowerTriangular) = UnitUpperTriangular(copytri!(A.data, 'L')) -transpose!(A::UpperTriangular) = LowerTriangular(copytri!(A.data, 'U')) -transpose!(A::UnitUpperTriangular) = UnitLowerTriangular(copytri!(A.data, 'U')) -ctranspose!(A::LowerTriangular) = UpperTriangular(copytri!(A.data, 'L' , true)) -ctranspose!(A::UnitLowerTriangular) = UnitUpperTriangular(copytri!(A.data, 'L' , true)) -ctranspose!(A::UpperTriangular) = LowerTriangular(copytri!(A.data, 'U' , true)) -ctranspose!(A::UnitUpperTriangular) = UnitLowerTriangular(copytri!(A.data, 'U' , true)) - -diag(A::LowerTriangular) = diag(A.data) -diag(A::UnitLowerTriangular) = ones(eltype(A), size(A,1)) -diag(A::UpperTriangular) = diag(A.data) -diag(A::UnitUpperTriangular) = ones(eltype(A), size(A,1)) - -# Unary operations --(A::LowerTriangular) = LowerTriangular(-A.data) --(A::UpperTriangular) = UpperTriangular(-A.data) -function -(A::UnitLowerTriangular) - Anew = -A.data - for i = 1:size(A, 1) - Anew[i, i] = -1 - end - LowerTriangular(Anew) -end -function -(A::UnitUpperTriangular) - Anew = -A.data - for i = 1:size(A, 1) - Anew[i, i] = -1 - end - UpperTriangular(Anew) -end - -# copy and scale -function copy!(A::T, B::T) where T<:Union{UpperTriangular,UnitUpperTriangular} - n = size(B,1) - for j = 1:n - for i = 1:(isa(B, UnitUpperTriangular)?j-1:j) - @inbounds A[i,j] = B[i,j] - end - end - return A -end -function copy!(A::T, B::T) where T<:Union{LowerTriangular,UnitLowerTriangular} - n = size(B,1) - for j = 1:n - for i = (isa(B, UnitLowerTriangular)?j+1:j):n - @inbounds A[i,j] = B[i,j] - end - end - return A -end - -function scale!(A::UpperTriangular, B::Union{UpperTriangular,UnitUpperTriangular}, c::Number) - n = checksquare(B) - for j = 1:n - if isa(B, UnitUpperTriangular) - @inbounds A[j,j] = c - end - for i = 1:(isa(B, UnitUpperTriangular)?j-1:j) - @inbounds A[i,j] = c * B[i,j] - end - end - return A -end -function scale!(A::LowerTriangular, B::Union{LowerTriangular,UnitLowerTriangular}, c::Number) - n = checksquare(B) - for j = 1:n - if isa(B, UnitLowerTriangular) - @inbounds A[j,j] = c - end - for i = (isa(B, UnitLowerTriangular)?j+1:j):n - @inbounds A[i,j] = c * B[i,j] - end - end - return A -end -scale!(A::Union{UpperTriangular,LowerTriangular}, c::Number) = scale!(A,A,c) -scale!(c::Number, A::Union{UpperTriangular,LowerTriangular}) = scale!(A,c) - -# Binary operations -+(A::UpperTriangular, B::UpperTriangular) = UpperTriangular(A.data + B.data) -+(A::LowerTriangular, B::LowerTriangular) = LowerTriangular(A.data + B.data) -+(A::UpperTriangular, B::UnitUpperTriangular) = UpperTriangular(A.data + triu(B.data, 1) + I) -+(A::LowerTriangular, B::UnitLowerTriangular) = LowerTriangular(A.data + tril(B.data, -1) + I) -+(A::UnitUpperTriangular, B::UpperTriangular) = UpperTriangular(triu(A.data, 1) + B.data + I) -+(A::UnitLowerTriangular, B::LowerTriangular) = LowerTriangular(tril(A.data, -1) + B.data + I) -+(A::UnitUpperTriangular, B::UnitUpperTriangular) = UpperTriangular(triu(A.data, 1) + triu(B.data, 1) + 2I) -+(A::UnitLowerTriangular, B::UnitLowerTriangular) = LowerTriangular(tril(A.data, -1) + tril(B.data, -1) + 2I) -+(A::AbstractTriangular, B::AbstractTriangular) = full(A) + full(B) - --(A::UpperTriangular, B::UpperTriangular) = UpperTriangular(A.data - B.data) --(A::LowerTriangular, B::LowerTriangular) = LowerTriangular(A.data - B.data) --(A::UpperTriangular, B::UnitUpperTriangular) = UpperTriangular(A.data - triu(B.data, 1) - I) --(A::LowerTriangular, B::UnitLowerTriangular) = LowerTriangular(A.data - tril(B.data, -1) - I) --(A::UnitUpperTriangular, B::UpperTriangular) = UpperTriangular(triu(A.data, 1) - B.data + I) --(A::UnitLowerTriangular, B::LowerTriangular) = LowerTriangular(tril(A.data, -1) - B.data + I) --(A::UnitUpperTriangular, B::UnitUpperTriangular) = UpperTriangular(triu(A.data, 1) - triu(B.data, 1)) --(A::UnitLowerTriangular, B::UnitLowerTriangular) = LowerTriangular(tril(A.data, -1) - tril(B.data, -1)) --(A::AbstractTriangular, B::AbstractTriangular) = full(A) - full(B) - -###################### -# BlasFloat routines # -###################### - -A_mul_B!(A::Tridiagonal, B::AbstractTriangular) = A*full!(B) -A_mul_B!(C::AbstractMatrix, A::AbstractTriangular, B::Tridiagonal) = A_mul_B!(C, full(A), B) -A_mul_B!(C::AbstractMatrix, A::Tridiagonal, B::AbstractTriangular) = A_mul_B!(C, A, full(B)) -A_mul_B!(C::AbstractVector, A::AbstractTriangular, B::AbstractVector) = A_mul_B!(A, copy!(C, B)) -A_mul_B!(C::AbstractMatrix, A::AbstractTriangular, B::AbstractVecOrMat) = A_mul_B!(A, copy!(C, B)) -A_mul_B!(C::AbstractVecOrMat, A::AbstractTriangular, B::AbstractVecOrMat) = A_mul_B!(A, copy!(C, B)) -A_mul_Bt!(C::AbstractVecOrMat, A::AbstractTriangular, B::AbstractVecOrMat) = A_mul_B!(A, transpose!(C, B)) -A_mul_Bc!(C::AbstractMatrix, A::AbstractTriangular, B::AbstractVecOrMat) = A_mul_B!(A, ctranspose!(C, B)) -A_mul_Bc!(C::AbstractVecOrMat, A::AbstractTriangular, B::AbstractVecOrMat) = A_mul_B!(A, ctranspose!(C, B)) - -for (t, uploc, isunitc) in ((:LowerTriangular, 'L', 'N'), - (:UnitLowerTriangular, 'L', 'U'), - (:UpperTriangular, 'U', 'N'), - (:UnitUpperTriangular, 'U', 'U')) - @eval begin - # Vector multiplication - A_mul_B!(A::$t{T,<:StridedMatrix}, b::StridedVector{T}) where {T<:BlasFloat} = - BLAS.trmv!($uploc, 'N', $isunitc, A.data, b) - At_mul_B!(A::$t{T,<:StridedMatrix}, b::StridedVector{T}) where {T<:BlasFloat} = - BLAS.trmv!($uploc, 'T', $isunitc, A.data, b) - Ac_mul_B!(A::$t{T,<:StridedMatrix}, b::StridedVector{T}) where {T<:BlasReal} = - BLAS.trmv!($uploc, 'T', $isunitc, A.data, b) - Ac_mul_B!(A::$t{T,<:StridedMatrix}, b::StridedVector{T}) where {T<:BlasComplex} = - BLAS.trmv!($uploc, 'C', $isunitc, A.data, b) - - # Matrix multiplication - A_mul_B!(A::$t{T,<:StridedMatrix}, B::StridedMatrix{T}) where {T<:BlasFloat} = - BLAS.trmm!('L', $uploc, 'N', $isunitc, one(T), A.data, B) - A_mul_B!(A::StridedMatrix{T}, B::$t{T,<:StridedMatrix}) where {T<:BlasFloat} = - BLAS.trmm!('R', $uploc, 'N', $isunitc, one(T), B.data, A) - - At_mul_B!(A::$t{T,<:StridedMatrix}, B::StridedMatrix{T}) where {T<:BlasFloat} = - BLAS.trmm!('L', $uploc, 'T', $isunitc, one(T), A.data, B) - Ac_mul_B!(A::$t{T,<:StridedMatrix}, B::StridedMatrix{T}) where {T<:BlasComplex} = - BLAS.trmm!('L', $uploc, 'C', $isunitc, one(T), A.data, B) - Ac_mul_B!(A::$t{T,<:StridedMatrix}, B::StridedMatrix{T}) where {T<:BlasReal} = - BLAS.trmm!('L', $uploc, 'T', $isunitc, one(T), A.data, B) - - A_mul_Bt!(A::StridedMatrix{T}, B::$t{T,<:StridedMatrix}) where {T<:BlasFloat} = - BLAS.trmm!('R', $uploc, 'T', $isunitc, one(T), B.data, A) - A_mul_Bc!(A::StridedMatrix{T}, B::$t{T,<:StridedMatrix}) where {T<:BlasComplex} = - BLAS.trmm!('R', $uploc, 'C', $isunitc, one(T), B.data, A) - A_mul_Bc!(A::StridedMatrix{T}, B::$t{T,<:StridedMatrix}) where {T<:BlasReal} = - BLAS.trmm!('R', $uploc, 'T', $isunitc, one(T), B.data, A) - - # Left division - A_ldiv_B!(A::$t{T,<:StridedMatrix}, B::StridedVecOrMat{T}) where {T<:BlasFloat} = - LAPACK.trtrs!($uploc, 'N', $isunitc, A.data, B) - At_ldiv_B!(A::$t{T,<:StridedMatrix}, B::StridedVecOrMat{T}) where {T<:BlasFloat} = - LAPACK.trtrs!($uploc, 'T', $isunitc, A.data, B) - Ac_ldiv_B!(A::$t{T,<:StridedMatrix}, B::StridedVecOrMat{T}) where {T<:BlasReal} = - LAPACK.trtrs!($uploc, 'T', $isunitc, A.data, B) - Ac_ldiv_B!(A::$t{T,<:StridedMatrix}, B::StridedVecOrMat{T}) where {T<:BlasComplex} = - LAPACK.trtrs!($uploc, 'C', $isunitc, A.data, B) - - # Right division - A_rdiv_B!(A::StridedMatrix{T}, B::$t{T,<:StridedMatrix}) where {T<:BlasFloat} = - BLAS.trsm!('R', $uploc, 'N', $isunitc, one(T), B.data, A) - A_rdiv_Bt!(A::StridedMatrix{T}, B::$t{T,<:StridedMatrix}) where {T<:BlasFloat} = - BLAS.trsm!('R', $uploc, 'T', $isunitc, one(T), B.data, A) - A_rdiv_Bc!(A::StridedMatrix{T}, B::$t{T,<:StridedMatrix}) where {T<:BlasReal} = - BLAS.trsm!('R', $uploc, 'T', $isunitc, one(T), B.data, A) - A_rdiv_Bc!(A::StridedMatrix{T}, B::$t{T,<:StridedMatrix}) where {T<:BlasComplex} = - BLAS.trsm!('R', $uploc, 'C', $isunitc, one(T), B.data, A) - - # Matrix inverse - inv!(A::$t{T,S}) where {T<:BlasFloat,S<:StridedMatrix} = - $t{T,S}(LAPACK.trtri!($uploc, $isunitc, A.data)) - - # Error bounds for triangular solve - errorbounds(A::$t{T,<:StridedMatrix}, X::StridedVecOrMat{T}, B::StridedVecOrMat{T}) where {T<:BlasFloat} = - LAPACK.trrfs!($uploc, 'N', $isunitc, A.data, B, X) - - # Condition numbers - function cond(A::$t{<:BlasFloat}, p::Real=2) - checksquare(A) - if p == 1 - return inv(LAPACK.trcon!('O', $uploc, $isunitc, A.data)) - elseif p == Inf - return inv(LAPACK.trcon!('I', $uploc, $isunitc, A.data)) - else # use fallback - return cond(full(A), p) - end - end - end -end - -function inv(A::LowerTriangular{T}) where T - S = typeof((zero(T)*one(T) + zero(T))/one(T)) - LowerTriangular(A_ldiv_B!(convert(AbstractArray{S}, A), eye(S, size(A, 1)))) -end -function inv(A::UpperTriangular{T}) where T - S = typeof((zero(T)*one(T) + zero(T))/one(T)) - UpperTriangular(A_ldiv_B!(convert(AbstractArray{S}, A), eye(S, size(A, 1)))) -end -inv(A::UnitUpperTriangular{T}) where {T} = UnitUpperTriangular(A_ldiv_B!(A, eye(T, size(A, 1)))) -inv(A::UnitLowerTriangular{T}) where {T} = UnitLowerTriangular(A_ldiv_B!(A, eye(T, size(A, 1)))) - -errorbounds(A::AbstractTriangular{T,<:StridedMatrix}, X::StridedVecOrMat{T}, B::StridedVecOrMat{T}) where {T<:Union{BigFloat,Complex{BigFloat}}} = - error("not implemented yet! Please submit a pull request.") -function errorbounds(A::AbstractTriangular{TA,<:StridedMatrix}, X::StridedVecOrMat{TX}, B::StridedVecOrMat{TB}) where {TA<:Number,TX<:Number,TB<:Number} - TAXB = promote_type(TA, TB, TX, Float32) - errorbounds(convert(AbstractMatrix{TAXB}, A), convert(AbstractArray{TAXB}, X), convert(AbstractArray{TAXB}, B)) -end - -# Eigensystems -## Notice that trecv works for quasi-triangular matrices and therefore the lower sub diagonal must be zeroed before calling the subroutine -function eigvecs(A::UpperTriangular{<:BlasFloat,<:StridedMatrix}) - LAPACK.trevc!('R', 'A', BlasInt[], triu!(A.data)) -end -function eigvecs(A::UnitUpperTriangular{<:BlasFloat,<:StridedMatrix}) - for i = 1:size(A, 1) - A.data[i,i] = 1 - end - LAPACK.trevc!('R', 'A', BlasInt[], triu!(A.data)) -end -function eigvecs(A::LowerTriangular{<:BlasFloat,<:StridedMatrix}) - LAPACK.trevc!('L', 'A', BlasInt[], tril!(A.data)') -end -function eigvecs(A::UnitLowerTriangular{<:BlasFloat,<:StridedMatrix}) - for i = 1:size(A, 1) - A.data[i,i] = 1 - end - LAPACK.trevc!('L', 'A', BlasInt[], tril!(A.data)') -end - -#################### -# Generic routines # -#################### - -for (t, unitt) in ((UpperTriangular, UnitUpperTriangular), - (LowerTriangular, UnitLowerTriangular)) - @eval begin - (*)(A::$t, x::Number) = $t(A.data*x) - - function (*)(A::$unitt, x::Number) - B = A.data*x - for i = 1:size(A, 1) - B[i,i] = x - end - $t(B) - end - - (*)(x::Number, A::$t) = $t(x*A.data) - - function (*)(x::Number, A::$unitt) - B = x*A.data - for i = 1:size(A, 1) - B[i,i] = x - end - $t(B) - end - - (/)(A::$t, x::Number) = $t(A.data/x) - - function (/)(A::$unitt, x::Number) - B = A.data/x - invx = inv(x) - for i = 1:size(A, 1) - B[i,i] = invx - end - $t(B) - end - - (\)(x::Number, A::$t) = $t(x\A.data) - - function (\)(x::Number, A::$unitt) - B = x\A.data - invx = inv(x) - for i = 1:size(A, 1) - B[i,i] = invx - end - $t(B) - end - end -end - -## Generic triangular multiplication -function A_mul_B!(A::UpperTriangular, B::StridedVecOrMat) - m, n = size(B, 1), size(B, 2) - if m != size(A, 1) - throw(DimensionMismatch("right hand side B needs first dimension of size $(size(A,1)), has size $m")) - end - for j = 1:n - for i = 1:m - Bij = A.data[i,i]*B[i,j] - for k = i + 1:m - Bij += A.data[i,k]*B[k,j] - end - B[i,j] = Bij - end - end - B -end -function A_mul_B!(A::UnitUpperTriangular, B::StridedVecOrMat) - m, n = size(B, 1), size(B, 2) - if m != size(A, 1) - throw(DimensionMismatch("right hand side B needs first dimension of size $(size(A,1)), has size $m")) - end - for j = 1:n - for i = 1:m - Bij = B[i,j] - for k = i + 1:m - Bij += A.data[i,k]*B[k,j] - end - B[i,j] = Bij - end - end - B -end - -function A_mul_B!(A::LowerTriangular, B::StridedVecOrMat) - m, n = size(B, 1), size(B, 2) - if m != size(A, 1) - throw(DimensionMismatch("right hand side B needs first dimension of size $(size(A,1)), has size $m")) - end - for j = 1:n - for i = m:-1:1 - Bij = A.data[i,i]*B[i,j] - for k = 1:i - 1 - Bij += A.data[i,k]*B[k,j] - end - B[i,j] = Bij - end - end - B -end -function A_mul_B!(A::UnitLowerTriangular, B::StridedVecOrMat) - m, n = size(B, 1), size(B, 2) - if m != size(A, 1) - throw(DimensionMismatch("right hand side B needs first dimension of size $(size(A,1)), has size $m")) - end - for j = 1:n - for i = m:-1:1 - Bij = B[i,j] - for k = 1:i - 1 - Bij += A.data[i,k]*B[k,j] - end - B[i,j] = Bij - end - end - B -end - -function Ac_mul_B!(A::UpperTriangular, B::StridedVecOrMat) - m, n = size(B, 1), size(B, 2) - if m != size(A, 1) - throw(DimensionMismatch("right hand side B needs first dimension of size $(size(A,1)), has size $m")) - end - for j = 1:n - for i = m:-1:1 - Bij = A.data[i,i]'B[i,j] - for k = 1:i - 1 - Bij += A.data[k,i]'B[k,j] - end - B[i,j] = Bij - end - end - B -end -function Ac_mul_B!(A::UnitUpperTriangular, B::StridedVecOrMat) - m, n = size(B, 1), size(B, 2) - if m != size(A, 1) - throw(DimensionMismatch("right hand side B needs first dimension of size $(size(A,1)), has size $m")) - end - for j = 1:n - for i = m:-1:1 - Bij = B[i,j] - for k = 1:i - 1 - Bij += A.data[k,i]'B[k,j] - end - B[i,j] = Bij - end - end - B -end - -function Ac_mul_B!(A::LowerTriangular, B::StridedVecOrMat) - m, n = size(B, 1), size(B, 2) - if m != size(A, 1) - throw(DimensionMismatch("right hand side B needs first dimension of size $(size(A,1)), has size $m")) - end - for j = 1:n - for i = 1:m - Bij = A.data[i,i]'B[i,j] - for k = i + 1:m - Bij += A.data[k,i]'B[k,j] - end - B[i,j] = Bij - end - end - B -end -function Ac_mul_B!(A::UnitLowerTriangular, B::StridedVecOrMat) - m, n = size(B, 1), size(B, 2) - if m != size(A, 1) - throw(DimensionMismatch("right hand side B needs first dimension of size $(size(A,1)), has size $m")) - end - for j = 1:n - for i = 1:m - Bij = B[i,j] - for k = i + 1:m - Bij += A.data[k,i]'B[k,j] - end - B[i,j] = Bij - end - end - B -end - -function At_mul_B!(A::UpperTriangular, B::StridedVecOrMat) - m, n = size(B, 1), size(B, 2) - if m != size(A, 1) - throw(DimensionMismatch("right hand side B needs first dimension of size $(size(A,1)), has size $m")) - end - for j = 1:n - for i = m:-1:1 - Bij = A.data[i,i].'B[i,j] - for k = 1:i - 1 - Bij += A.data[k,i].'B[k,j] - end - B[i,j] = Bij - end - end - B -end -function At_mul_B!(A::UnitUpperTriangular, B::StridedVecOrMat) - m, n = size(B, 1), size(B, 2) - if m != size(A, 1) - throw(DimensionMismatch("right hand side B needs first dimension of size $(size(A,1)), has size $m")) - end - for j = 1:n - for i = m:-1:1 - Bij = B[i,j] - for k = 1:i - 1 - Bij += A.data[k,i].'B[k,j] - end - B[i,j] = Bij - end - end - B -end - -function At_mul_B!(A::LowerTriangular, B::StridedVecOrMat) - m, n = size(B, 1), size(B, 2) - if m != size(A, 1) - throw(DimensionMismatch("right hand side B needs first dimension of size $(size(A,1)), has size $m")) - end - for j = 1:n - for i = 1:m - Bij = A.data[i,i].'B[i,j] - for k = i + 1:m - Bij += A.data[k,i].'B[k,j] - end - B[i,j] = Bij - end - end - B -end -function At_mul_B!(A::UnitLowerTriangular, B::StridedVecOrMat) - m, n = size(B, 1), size(B, 2) - if m != size(A, 1) - throw(DimensionMismatch("right hand side B needs first dimension of size $(size(A,1)), has size $m")) - end - for j = 1:n - for i = 1:m - Bij = B[i,j] - for k = i + 1:m - Bij += A.data[k,i].'B[k,j] - end - B[i,j] = Bij - end - end - B -end - -function A_mul_B!(A::StridedMatrix, B::UpperTriangular) - m, n = size(A) - if size(B, 1) != n - throw(DimensionMismatch("right hand side B needs first dimension of size $n, has size $(size(B,1))")) - end - for i = 1:m - for j = n:-1:1 - Aij = A[i,j]*B[j,j] - for k = 1:j - 1 - Aij += A[i,k]*B.data[k,j] - end - A[i,j] = Aij - end - end - A -end -function A_mul_B!(A::StridedMatrix, B::UnitUpperTriangular) - m, n = size(A) - if size(B, 1) != n - throw(DimensionMismatch("right hand side B needs first dimension of size $n, has size $(size(B,1))")) - end - for i = 1:m - for j = n:-1:1 - Aij = A[i,j] - for k = 1:j - 1 - Aij += A[i,k]*B.data[k,j] - end - A[i,j] = Aij - end - end - A -end - -function A_mul_B!(A::StridedMatrix, B::LowerTriangular) - m, n = size(A) - if size(B, 1) != n - throw(DimensionMismatch("right hand side B needs first dimension of size $n, has size $(size(B,1))")) - end - for i = 1:m - for j = 1:n - Aij = A[i,j]*B[j,j] - for k = j + 1:n - Aij += A[i,k]*B.data[k,j] - end - A[i,j] = Aij - end - end - A -end -function A_mul_B!(A::StridedMatrix, B::UnitLowerTriangular) - m, n = size(A) - if size(B, 1) != n - throw(DimensionMismatch("right hand side B needs first dimension of size $n, has size $(size(B,1))")) - end - for i = 1:m - for j = 1:n - Aij = A[i,j] - for k = j + 1:n - Aij += A[i,k]*B.data[k,j] - end - A[i,j] = Aij - end - end - A -end - -function A_mul_Bc!(A::StridedMatrix, B::UpperTriangular) - m, n = size(A) - if size(B, 1) != n - throw(DimensionMismatch("right hand side B needs first dimension of size $n, has size $(size(B,1))")) - end - for i = 1:m - for j = 1:n - Aij = A[i,j]*B.data[j,j]' - for k = j + 1:n - Aij += A[i,k]*B.data[j,k]' - end - A[i,j] = Aij - end - end - A -end -function A_mul_Bc!(A::StridedMatrix, B::UnitUpperTriangular) - m, n = size(A) - if size(B, 1) != n - throw(DimensionMismatch("right hand side B needs first dimension of size $n, has size $(size(B,1))")) - end - for i = 1:m - for j = 1:n - Aij = A[i,j] - for k = j + 1:n - Aij += A[i,k]*B.data[j,k]' - end - A[i,j] = Aij - end - end - A -end - -function A_mul_Bc!(A::StridedMatrix, B::LowerTriangular) - m, n = size(A) - if size(B, 1) != n - throw(DimensionMismatch("right hand side B needs first dimension of size $n, has size $(size(B,1))")) - end - for i = 1:m - for j = n:-1:1 - Aij = A[i,j]*B.data[j,j]' - for k = 1:j - 1 - Aij += A[i,k]*B.data[j,k]' - end - A[i,j] = Aij - end - end - A -end -function A_mul_Bc!(A::StridedMatrix, B::UnitLowerTriangular) - m, n = size(A) - if size(B, 1) != n - throw(DimensionMismatch("right hand side B needs first dimension of size $n, has size $(size(B,1))")) - end - for i = 1:m - for j = n:-1:1 - Aij = A[i,j] - for k = 1:j - 1 - Aij += A[i,k]*B.data[j,k]' - end - A[i,j] = Aij - end - end - A -end - -function A_mul_Bt!(A::StridedMatrix, B::UpperTriangular) - m, n = size(A) - if size(B, 1) != n - throw(DimensionMismatch("right hand side B needs first dimension of size $n, has size $(size(B,1))")) - end - for i = 1:m - for j = 1:n - Aij = A[i,j]*B.data[j,j].' - for k = j + 1:n - Aij += A[i,k]*B.data[j,k].' - end - A[i,j] = Aij - end - end - A -end -function A_mul_Bt!(A::StridedMatrix, B::UnitUpperTriangular) - m, n = size(A) - if size(B, 1) != n - throw(DimensionMismatch("right hand side B needs first dimension of size $n, has size $(size(B,1))")) - end - for i = 1:m - for j = 1:n - Aij = A[i,j] - for k = j + 1:n - Aij += A[i,k]*B.data[j,k].' - end - A[i,j] = Aij - end - end - A -end - -function A_mul_Bt!(A::StridedMatrix, B::LowerTriangular) - m, n = size(A) - if size(B, 1) != n - throw(DimensionMismatch("right hand side B needs first dimension of size $n, has size $(size(B,1))")) - end - for i = 1:m - for j = n:-1:1 - Aij = A[i,j]*B.data[j,j].' - for k = 1:j - 1 - Aij += A[i,k]*B.data[j,k].' - end - A[i,j] = Aij - end - end - A -end -function A_mul_Bt!(A::StridedMatrix, B::UnitLowerTriangular) - m, n = size(A) - if size(B, 1) != n - throw(DimensionMismatch("right hand side B needs first dimension of size $n, has size $(size(B,1))")) - end - for i = 1:m - for j = n:-1:1 - Aij = A[i,j] - for k = 1:j - 1 - Aij += A[i,k]*B.data[j,k].' - end - A[i,j] = Aij - end - end - A -end - -#Generic solver using naive substitution -# manually hoisting x[j] significantly improves performance as of Dec 2015 -# manually eliding bounds checking significantly improves performance as of Dec 2015 -# directly indexing A.data rather than A significantly improves performance as of Dec 2015 -# replacing repeated references to A.data with [Adata = A.data and references to Adata] -# does not significantly impact performance as of Dec 2015 -# replacing repeated references to A.data[j,j] with [Ajj = A.data[j,j] and references to Ajj] -# does not significantly impact performance as of Dec 2015 -function naivesub!(A::UpperTriangular, b::AbstractVector, x::AbstractVector = b) - n = size(A, 2) - if !(n == length(b) == length(x)) - throw(DimensionMismatch("second dimension of left hand side A, $n, length of output x, $(length(x)), and length of right hand side b, $(length(b)), must be equal")) - end - @inbounds for j in n:-1:1 - A.data[j,j] == zero(A.data[j,j]) && throw(SingularException(j)) - xj = x[j] = A.data[j,j] \ b[j] - for i in j-1:-1:1 # counterintuitively 1:j-1 performs slightly better - b[i] -= A.data[i,j] * xj - end - end - x -end -function naivesub!(A::UnitUpperTriangular, b::AbstractVector, x::AbstractVector = b) - n = size(A, 2) - if !(n == length(b) == length(x)) - throw(DimensionMismatch("second dimension of left hand side A, $n, length of output x, $(length(x)), and length of right hand side b, $(length(b)), must be equal")) - end - @inbounds for j in n:-1:1 - xj = x[j] = b[j] - for i in j-1:-1:1 # counterintuitively 1:j-1 performs slightly better - b[i] -= A.data[i,j] * xj - end - end - x -end -function naivesub!(A::LowerTriangular, b::AbstractVector, x::AbstractVector = b) - n = size(A, 2) - if !(n == length(b) == length(x)) - throw(DimensionMismatch("second dimension of left hand side A, $n, length of output x, $(length(x)), and length of right hand side b, $(length(b)), must be equal")) - end - @inbounds for j in 1:n - A.data[j,j] == zero(A.data[j,j]) && throw(SingularException(j)) - xj = x[j] = A.data[j,j] \ b[j] - for i in j+1:n - b[i] -= A.data[i,j] * xj - end - end - x -end -function naivesub!(A::UnitLowerTriangular, b::AbstractVector, x::AbstractVector = b) - n = size(A, 2) - if !(n == length(b) == length(x)) - throw(DimensionMismatch("second dimension of left hand side A, $n, length of output x, $(length(x)), and length of right hand side b, $(length(b)), must be equal")) - end - @inbounds for j in 1:n - xj = x[j] = b[j] - for i in j+1:n - b[i] -= A.data[i,j] * xj - end - end - x -end -# in the following transpose and conjugate transpose naive substitution variants, -# accumulating in z rather than b[j] significantly improves performance as of Dec 2015 -function At_ldiv_B!(A::LowerTriangular, b::AbstractVector, x::AbstractVector = b) - n = size(A, 1) - if !(n == length(b) == length(x)) - throw(DimensionMismatch("first dimension of left hand side A, $n, length of output x, $(length(x)), and length of right hand side b, $(length(b)), must be equal")) - end - @inbounds for j in n:-1:1 - z = b[j] - for i in n:-1:j+1 - z -= A.data[i,j] * x[i] - end - A.data[j,j] == zero(A.data[j,j]) && throw(SingularException(j)) - x[j] = A.data[j,j] \ z - end - x -end -function At_ldiv_B!(A::UnitLowerTriangular, b::AbstractVector, x::AbstractVector = b) - n = size(A, 1) - if !(n == length(b) == length(x)) - throw(DimensionMismatch("first dimension of left hand side A, $n, length of output x, $(length(x)), and length of right hand side b, $(length(b)), must be equal")) - end - @inbounds for j in n:-1:1 - z = b[j] - for i in n:-1:j+1 - z -= A.data[i,j] * x[i] - end - x[j] = z - end - x -end -function At_ldiv_B!(A::UpperTriangular, b::AbstractVector, x::AbstractVector = b) - n = size(A, 1) - if !(n == length(b) == length(x)) - throw(DimensionMismatch("first dimension of left hand side A, $n, length of output x, $(length(x)), and length of right hand side b, $(length(b)), must be equal")) - end - @inbounds for j in 1:n - z = b[j] - for i in 1:j-1 - z -= A.data[i,j] * x[i] - end - A.data[j,j] == zero(A.data[j,j]) && throw(SingularException(j)) - x[j] = A.data[j,j] \ z - end - x -end -function At_ldiv_B!(A::UnitUpperTriangular, b::AbstractVector, x::AbstractVector = b) - n = size(A, 1) - if !(n == length(b) == length(x)) - throw(DimensionMismatch("first dimension of left hand side A, $n, length of output x, $(length(x)), and length of right hand side b, $(length(b)), must be equal")) - end - @inbounds for j in 1:n - z = b[j] - for i in 1:j-1 - z -= A.data[i,j] * x[i] - end - x[j] = z - end - x -end -function Ac_ldiv_B!(A::LowerTriangular, b::AbstractVector, x::AbstractVector = b) - n = size(A, 1) - if !(n == length(b) == length(x)) - throw(DimensionMismatch("first dimension of left hand side A, $n, length of output x, $(length(x)), and length of right hand side b, $(length(b)), must be equal")) - end - @inbounds for j in n:-1:1 - z = b[j] - for i in n:-1:j+1 - z -= A.data[i,j]' * x[i] - end - A.data[j,j] == zero(A.data[j,j]) && throw(SingularException(j)) - x[j] = A.data[j,j]' \ z - end - x -end -function Ac_ldiv_B!(A::UnitLowerTriangular, b::AbstractVector, x::AbstractVector = b) - n = size(A, 1) - if !(n == length(b) == length(x)) - throw(DimensionMismatch("first dimension of left hand side A, $n, length of output x, $(length(x)), and length of right hand side b, $(length(b)), must be equal")) - end - @inbounds for j in n:-1:1 - z = b[j] - for i in n:-1:j+1 - z -= A.data[i,j]' * x[i] - end - x[j] = z - end - x -end -function Ac_ldiv_B!(A::UpperTriangular, b::AbstractVector, x::AbstractVector = b) - n = size(A, 1) - if !(n == length(b) == length(x)) - throw(DimensionMismatch("first dimension of left hand side A, $n, length of output x, $(length(x)), and length of right hand side b, $(length(b)), must be equal")) - end - @inbounds for j in 1:n - z = b[j] - for i in 1:j-1 - z -= A.data[i,j]' * x[i] - end - A.data[j,j] == zero(A.data[j,j]) && throw(SingularException(j)) - x[j] = A.data[j,j]' \ z - end - x -end -function Ac_ldiv_B!(A::UnitUpperTriangular, b::AbstractVector, x::AbstractVector = b) - n = size(A, 1) - if !(n == length(b) == length(x)) - throw(DimensionMismatch("first dimension of left hand side A, $n, length of output x, $(length(x)), and length of right hand side b, $(length(b)), must be equal")) - end - @inbounds for j in 1:n - z = b[j] - for i in 1:j-1 - z -= A.data[i,j]' * x[i] - end - x[j] = z - end - x -end - -function A_rdiv_B!(A::StridedMatrix, B::UpperTriangular) - m, n = size(A) - if size(B, 1) != n - throw(DimensionMismatch("right hand side B needs first dimension of size $n, has size $(size(B,1))")) - end - for i = 1:m - for j = 1:n - Aij = A[i,j] - for k = 1:j - 1 - Aij -= A[i,k]*B.data[k,j] - end - A[i,j] = Aij/B[j,j] - end - end - A -end -function A_rdiv_B!(A::StridedMatrix, B::UnitUpperTriangular) - m, n = size(A) - if size(B, 1) != n - throw(DimensionMismatch("right hand side B needs first dimension of size $n, has size $(size(B,1))")) - end - for i = 1:m - for j = 1:n - Aij = A[i,j] - for k = 1:j - 1 - Aij -= A[i,k]*B.data[k,j] - end - A[i,j] = Aij - end - end - A -end - -function A_rdiv_B!(A::StridedMatrix, B::LowerTriangular) - m, n = size(A) - if size(B, 1) != n - throw(DimensionMismatch("right hand side B needs first dimension of size $n, has size $(size(B,1))")) - end - for i = 1:m - for j = n:-1:1 - Aij = A[i,j] - for k = j + 1:n - Aij -= A[i,k]*B.data[k,j] - end - A[i,j] = Aij/B[j,j] - end - end - A -end -function A_rdiv_B!(A::StridedMatrix, B::UnitLowerTriangular) - m, n = size(A) - if size(B, 1) != n - throw(DimensionMismatch("right hand side B needs first dimension of size $n, has size $(size(B,1))")) - end - for i = 1:m - for j = n:-1:1 - Aij = A[i,j] - for k = j + 1:n - Aij -= A[i,k]*B.data[k,j] - end - A[i,j] = Aij - end - end - A -end - -function A_rdiv_Bc!(A::StridedMatrix, B::UpperTriangular) - m, n = size(A) - if size(B, 1) != n - throw(DimensionMismatch("right hand side B needs first dimension of size $n, has size $(size(B,1))")) - end - for i = 1:m - for j = n:-1:1 - Aij = A[i,j] - for k = j + 1:n - Aij -= A[i,k]*B.data[j,k]' - end - A[i,j] = Aij/B.data[j,j]' - end - end - A -end -function A_rdiv_Bc!(A::StridedMatrix, B::UnitUpperTriangular) - m, n = size(A) - if size(B, 1) != n - throw(DimensionMismatch("right hand side B needs first dimension of size $n, has size $(size(B,1))")) - end - for i = 1:m - for j = n:-1:1 - Aij = A[i,j] - for k = j + 1:n - Aij -= A[i,k]*B.data[j,k]' - end - A[i,j] = Aij - end - end - A -end - -function A_rdiv_Bc!(A::StridedMatrix, B::LowerTriangular) - m, n = size(A) - if size(B, 1) != n - throw(DimensionMismatch("right hand side B needs first dimension of size $n, has size $(size(B,1))")) - end - for i = 1:m - for j = 1:n - Aij = A[i,j] - for k = 1:j - 1 - Aij -= A[i,k]*B.data[j,k]' - end - A[i,j] = Aij/B.data[j,j]' - end - end - A -end -function A_rdiv_Bc!(A::StridedMatrix, B::UnitLowerTriangular) - m, n = size(A) - if size(B, 1) != n - throw(DimensionMismatch("right hand side B needs first dimension of size $n, has size $(size(B,1))")) - end - for i = 1:m - for j = 1:n - Aij = A[i,j] - for k = 1:j - 1 - Aij -= A[i,k]*B.data[j,k]' - end - A[i,j] = Aij - end - end - A -end - -function A_rdiv_Bt!(A::StridedMatrix, B::UpperTriangular) - m, n = size(A) - if size(B, 1) != n - throw(DimensionMismatch("right hand side B needs first dimension of size $n, has size $(size(B,1))")) - end - for i = 1:m - for j = n:-1:1 - Aij = A[i,j] - for k = j + 1:n - Aij -= A[i,k]*B.data[j,k].' - end - A[i,j] = Aij/B.data[j,j].' - end - end - A -end -function A_rdiv_Bt!(A::StridedMatrix, B::UnitUpperTriangular) - m, n = size(A) - if size(B, 1) != n - throw(DimensionMismatch("right hand side B needs first dimension of size $n, has size $(size(B,1))")) - end - for i = 1:m - for j = n:-1:1 - Aij = A[i,j] - for k = j + 1:n - Aij -= A[i,k]*B.data[j,k].' - end - A[i,j] = Aij - end - end - A -end - -function A_rdiv_Bt!(A::StridedMatrix, B::LowerTriangular) - m, n = size(A) - if size(B, 1) != n - throw(DimensionMismatch("right hand side B needs first dimension of size $n, has size $(size(B,1))")) - end - for i = 1:m - for j = 1:n - Aij = A[i,j] - for k = 1:j - 1 - Aij -= A[i,k]*B.data[j,k].' - end - A[i,j] = Aij/B.data[j,j].' - end - end - A -end -function A_rdiv_Bt!(A::StridedMatrix, B::UnitLowerTriangular) - m, n = size(A) - if size(B, 1) != n - throw(DimensionMismatch("right hand side B needs first dimension of size $n, has size $(size(B,1))")) - end - for i = 1:m - for j = 1:n - Aij = A[i,j] - for k = 1:j - 1 - Aij -= A[i,k]*B.data[j,k].' - end - A[i,j] = Aij - end - end - A -end - -for f in (:Ac_mul_B!, :At_mul_B!, :Ac_ldiv_B!, :At_ldiv_B!) - @eval begin - $f(A::Union{LowerTriangular,UnitLowerTriangular}, B::UpperTriangular) = - UpperTriangular($f(A, triu!(B.data))) - $f(A::Union{UpperTriangular,UnitUpperTriangular}, B::LowerTriangular) = - LowerTriangular($f(A, tril!(B.data))) - end -end - -A_rdiv_B!(A::UpperTriangular, B::Union{UpperTriangular,UnitUpperTriangular}) = - UpperTriangular(A_rdiv_B!(triu!(A.data), B)) -A_rdiv_B!(A::LowerTriangular, B::Union{LowerTriangular,UnitLowerTriangular}) = - LowerTriangular(A_rdiv_B!(tril!(A.data), B)) - -for f in (:A_mul_Bc!, :A_mul_Bt!, :A_rdiv_Bc!, :A_rdiv_Bt!) - @eval begin - $f(A::UpperTriangular, B::Union{LowerTriangular,UnitLowerTriangular}) = - UpperTriangular($f(triu!(A.data), B)) - $f(A::LowerTriangular, B::Union{UpperTriangular,UnitUpperTriangular}) = - LowerTriangular($f(tril!(A.data), B)) - end -end - -# Promotion -## Promotion methods in matmul don't apply to triangular multiplication since -## it is inplace. Hence we have to make very similar definitions, but without -## allocation of a result array. For multiplication and unit diagonal division -## the element type doesn't have to be stable under division whereas that is -## necessary in the general triangular solve problem. - -## Some Triangular-Triangular cases. We might want to write taylored methods -## for these cases, but I'm not sure it is worth it. -for t in (UpperTriangular, UnitUpperTriangular, LowerTriangular, UnitLowerTriangular) - @eval begin - (*)(A::Tridiagonal, B::$t) = A_mul_B!(full(A), B) - end -end - -for (f1, f2) in ((:*, :A_mul_B!), (:\, :A_ldiv_B!)) - @eval begin - function ($f1)(A::LowerTriangular, B::LowerTriangular) - TAB = typeof(($f1)(zero(eltype(A)), zero(eltype(B))) + - ($f1)(zero(eltype(A)), zero(eltype(B)))) - BB = similar(B, TAB, size(B)) - copy!(BB, B) - return LowerTriangular($f2(convert(AbstractMatrix{TAB}, A), BB)) - end - - function $(f1)(A::UnitLowerTriangular, B::LowerTriangular) - TAB = typeof((*)(zero(eltype(A)), zero(eltype(B))) + - (*)(zero(eltype(A)), zero(eltype(B)))) - BB = similar(B, TAB, size(B)) - copy!(BB, B) - return LowerTriangular($f2(convert(AbstractMatrix{TAB}, A), BB)) - end - - function ($f1)(A::UpperTriangular, B::UpperTriangular) - TAB = typeof(($f1)(zero(eltype(A)), zero(eltype(B))) + - ($f1)(zero(eltype(A)), zero(eltype(B)))) - BB = similar(B, TAB, size(B)) - copy!(BB, B) - return UpperTriangular($f2(convert(AbstractMatrix{TAB}, A), BB)) - end - - function ($f1)(A::UnitUpperTriangular, B::UpperTriangular) - TAB = typeof((*)(zero(eltype(A)), zero(eltype(B))) + - (*)(zero(eltype(A)), zero(eltype(B)))) - BB = similar(B, TAB, size(B)) - copy!(BB, B) - return UpperTriangular($f2(convert(AbstractMatrix{TAB}, A), BB)) - end - end -end - -for (f1, f2) in ((:Ac_mul_B, :Ac_mul_B!), (:At_mul_B, :At_mul_B!), - (:Ac_ldiv_B, Ac_ldiv_B!), (:At_ldiv_B, :At_ldiv_B!)) - @eval begin - function ($f1)(A::UpperTriangular, B::LowerTriangular) - TAB = typeof(($f1)(zero(eltype(A)), zero(eltype(B))) + - ($f1)(zero(eltype(A)), zero(eltype(B)))) - BB = similar(B, TAB, size(B)) - copy!(BB, B) - return LowerTriangular($f2(convert(AbstractMatrix{TAB}, A), BB)) - end - - function ($f1)(A::UnitUpperTriangular, B::LowerTriangular) - TAB = typeof((*)(zero(eltype(A)), zero(eltype(B))) + - (*)(zero(eltype(A)), zero(eltype(B)))) - BB = similar(B, TAB, size(B)) - copy!(BB, B) - return LowerTriangular($f2(convert(AbstractMatrix{TAB}, A), BB)) - end - - function ($f1)(A::LowerTriangular, B::UpperTriangular) - TAB = typeof(($f1)(zero(eltype(A)), zero(eltype(B))) + - ($f1)(zero(eltype(A)), zero(eltype(B)))) - BB = similar(B, TAB, size(B)) - copy!(BB, B) - return UpperTriangular($f2(convert(AbstractMatrix{TAB}, A), BB)) - end - - function ($f1)(A::UnitLowerTriangular, B::UpperTriangular) - TAB = typeof((*)(zero(eltype(A)), zero(eltype(B))) + - (*)(zero(eltype(A)), zero(eltype(B)))) - BB = similar(B, TAB, size(B)) - copy!(BB, B) - return UpperTriangular($f2(convert(AbstractMatrix{TAB}, A), BB)) - end - end -end - -function (/)(A::LowerTriangular, B::LowerTriangular) - TAB = typeof((/)(zero(eltype(A)), zero(eltype(B))) + - (/)(zero(eltype(A)), zero(eltype(B)))) - AA = similar(A, TAB, size(A)) - copy!(AA, A) - return LowerTriangular(A_rdiv_B!(AA, convert(AbstractMatrix{TAB}, B))) -end -function (/)(A::LowerTriangular, B::UnitLowerTriangular) - TAB = typeof((*)(zero(eltype(A)), zero(eltype(B))) + - (*)(zero(eltype(A)), zero(eltype(B)))) - AA = similar(A, TAB, size(A)) - copy!(AA, A) - return LowerTriangular(A_rdiv_B!(AA, convert(AbstractMatrix{TAB}, B))) -end -function (/)(A::UpperTriangular, B::UpperTriangular) - TAB = typeof((/)(zero(eltype(A)), zero(eltype(B))) + - (/)(zero(eltype(A)), zero(eltype(B)))) - AA = similar(A, TAB, size(A)) - copy!(AA, A) - return UpperTriangular(A_rdiv_B!(AA, convert(AbstractMatrix{TAB}, B))) -end -function (/)(A::UpperTriangular, B::UnitUpperTriangular) - TAB = typeof((*)(zero(eltype(A)), zero(eltype(B))) + - (*)(zero(eltype(A)), zero(eltype(B)))) - AA = similar(A, TAB, size(A)) - copy!(AA, A) - return UpperTriangular(A_rdiv_B!(AA, convert(AbstractMatrix{TAB}, B))) -end - -for (f1, f2) in ((:A_mul_Bc, :A_mul_Bc!), (:A_mul_Bt, :A_mul_Bt!), - (:A_rdiv_Bc, :A_rdiv_Bc!), (:A_rdiv_Bt, :A_rdiv_Bt!)) - @eval begin - function $f1(A::LowerTriangular, B::UpperTriangular) - TAB = typeof(($f1)(zero(eltype(A)), zero(eltype(B))) + - ($f1)(zero(eltype(A)), zero(eltype(B)))) - AA = similar(A, TAB, size(A)) - copy!(AA, A) - return LowerTriangular($f2(AA, convert(AbstractMatrix{TAB}, B))) - end - - function $f1(A::LowerTriangular, B::UnitUpperTriangular) - TAB = typeof((*)(zero(eltype(A)), zero(eltype(B))) + - (*)(zero(eltype(A)), zero(eltype(B)))) - AA = similar(A, TAB, size(A)) - copy!(AA, A) - return LowerTriangular($f2(AA, convert(AbstractMatrix{TAB}, B))) - end - - function $f1(A::UpperTriangular, B::LowerTriangular) - TAB = typeof(($f1)(zero(eltype(A)), zero(eltype(B))) + - ($f1)(zero(eltype(A)), zero(eltype(B)))) - AA = similar(A, TAB, size(A)) - copy!(AA, A) - return UpperTriangular($f2(AA, convert(AbstractMatrix{TAB}, B))) - end - - function $f1(A::UpperTriangular, B::UnitLowerTriangular) - TAB = typeof((*)(zero(eltype(A)), zero(eltype(B))) + - (*)(zero(eltype(A)), zero(eltype(B)))) - AA = similar(A, TAB, size(A)) - copy!(AA, A) - return UpperTriangular($f2(AA, convert(AbstractMatrix{TAB}, B))) - end - end -end - -## The general promotion methods - -for (f, g) in ((:*, :A_mul_B!), (:Ac_mul_B, :Ac_mul_B!), (:At_mul_B, :At_mul_B!)) - @eval begin - function ($f)(A::AbstractTriangular, B::AbstractTriangular) - TAB = typeof(zero(eltype(A))*zero(eltype(B)) + zero(eltype(A))*zero(eltype(B))) - BB = similar(B, TAB, size(B)) - copy!(BB, B) - ($g)(convert(AbstractArray{TAB}, A), BB) - end - end -end -for (f, g) in ((:A_mul_Bc, :A_mul_Bc!), (:A_mul_Bt, :A_mul_Bt!)) - @eval begin - function ($f)(A::AbstractTriangular, B::AbstractTriangular) - TAB = typeof(zero(eltype(A))*zero(eltype(B)) + zero(eltype(A))*zero(eltype(B))) - AA = similar(A, TAB, size(A)) - copy!(AA, A) - ($g)(AA, convert(AbstractArray{TAB}, B)) - end - end -end - -for mat in (:AbstractVector, :AbstractMatrix) - -### Multiplication with triangle to the left and hence rhs cannot be transposed. -for (f, g) in ((:*, :A_mul_B!), (:Ac_mul_B, :Ac_mul_B!), (:At_mul_B, :At_mul_B!)) - @eval begin - function ($f)(A::AbstractTriangular, B::$mat) - TAB = typeof(zero(eltype(A))*zero(eltype(B)) + zero(eltype(A))*zero(eltype(B))) - BB = similar(B, TAB, size(B)) - copy!(BB, B) - ($g)(convert(AbstractArray{TAB}, A), BB) - end - end -end -### Left division with triangle to the left hence rhs cannot be transposed. No quotients. -for (f, g) in ((:\, :A_ldiv_B!), (:Ac_ldiv_B, :Ac_ldiv_B!), (:At_ldiv_B, :At_ldiv_B!)) - @eval begin - function ($f)(A::Union{UnitUpperTriangular,UnitLowerTriangular}, B::$mat) - TAB = typeof(zero(eltype(A))*zero(eltype(B)) + zero(eltype(A))*zero(eltype(B))) - BB = similar(B, TAB, size(B)) - copy!(BB, B) - ($g)(convert(AbstractArray{TAB}, A), BB) - end - end -end -### Left division with triangle to the left hence rhs cannot be transposed. Quotients. -for (f, g) in ((:\, :A_ldiv_B!), (:Ac_ldiv_B, :Ac_ldiv_B!), (:At_ldiv_B, :At_ldiv_B!)) - @eval begin - function ($f)(A::Union{UpperTriangular,LowerTriangular}, B::$mat) - TAB = typeof((zero(eltype(A))*zero(eltype(B)) + zero(eltype(A))*zero(eltype(B)))/one(eltype(A))) - BB = similar(B, TAB, size(B)) - copy!(BB, B) - ($g)(convert(AbstractArray{TAB}, A), BB) - end - end -end -### Multiplication with triangle to the right and hence lhs cannot be transposed. -for (f, g) in ((:*, :A_mul_B!), (:A_mul_Bc, :A_mul_Bc!), (:A_mul_Bt, :A_mul_Bt!)) - mat != :AbstractVector && @eval begin - function ($f)(A::$mat, B::AbstractTriangular) - TAB = typeof(zero(eltype(A))*zero(eltype(B)) + zero(eltype(A))*zero(eltype(B))) - AA = similar(A, TAB, size(A)) - copy!(AA, A) - ($g)(AA, convert(AbstractArray{TAB}, B)) - end - end -end -### Right division with triangle to the right hence lhs cannot be transposed. No quotients. -for (f, g) in ((:/, :A_rdiv_B!), (:A_rdiv_Bc, :A_rdiv_Bc!), (:A_rdiv_Bt, :A_rdiv_Bt!)) - @eval begin - function ($f)(A::$mat, B::Union{UnitUpperTriangular, UnitLowerTriangular}) - TAB = typeof(zero(eltype(A))*zero(eltype(B)) + zero(eltype(A))*zero(eltype(B))) - AA = similar(A, TAB, size(A)) - copy!(AA, A) - ($g)(AA, convert(AbstractArray{TAB}, B)) - end - end -end - -### Right division with triangle to the right hence lhs cannot be transposed. Quotients. -for (f, g) in ((:/, :A_rdiv_B!), (:A_rdiv_Bc, :A_rdiv_Bc!), (:A_rdiv_Bt, :A_rdiv_Bt!)) - @eval begin - function ($f)(A::$mat, B::Union{UpperTriangular,LowerTriangular}) - TAB = typeof((zero(eltype(A))*zero(eltype(B)) + zero(eltype(A))*zero(eltype(B)))/one(eltype(A))) - AA = similar(A, TAB, size(A)) - copy!(AA, A) - ($g)(AA, convert(AbstractArray{TAB}, B)) - end - end -end -end - -# If these are not defined, they will fallback to the versions in matmul.jl -# and dispatch to generic_matmatmul! which is very costly to compile. The methods -# below might compute an unnecessary copy. Eliminating the copy requires adding -# all the promotion logic here once again. Since these methods are probably relatively -# rare, we chose not to bother for now. -Ac_mul_B(A::AbstractMatrix, B::AbstractTriangular) = (*)(ctranspose(A), B) -At_mul_B(A::AbstractMatrix, B::AbstractTriangular) = (*)(transpose(A), B) -A_mul_Bc(A::AbstractTriangular, B::AbstractMatrix) = (*)(A, ctranspose(B)) -A_mul_Bt(A::AbstractTriangular, B::AbstractMatrix) = (*)(A, transpose(B)) -Ac_mul_Bc(A::AbstractTriangular, B::AbstractTriangular) = Ac_mul_B(A, B') -Ac_mul_Bc(A::AbstractTriangular, B::AbstractMatrix) = Ac_mul_B(A, B') -Ac_mul_Bc(A::AbstractMatrix, B::AbstractTriangular) = A_mul_Bc(A', B) -At_mul_Bt(A::AbstractTriangular, B::AbstractTriangular) = At_mul_B(A, B.') -At_mul_Bt(A::AbstractTriangular, B::AbstractMatrix) = At_mul_B(A, B.') -At_mul_Bt(A::AbstractMatrix, B::AbstractTriangular) = A_mul_Bt(A.', B) - -# Specializations for RowVector -@inline *(rowvec::RowVector, A::AbstractTriangular) = transpose(A * transpose(rowvec)) -@inline A_mul_Bt(rowvec::RowVector, A::AbstractTriangular) = transpose(A * transpose(rowvec)) -@inline A_mul_Bt(A::AbstractTriangular, rowvec::RowVector) = A * transpose(rowvec) -@inline At_mul_Bt(A::AbstractTriangular, rowvec::RowVector) = A.' * transpose(rowvec) -@inline A_mul_Bc(rowvec::RowVector, A::AbstractTriangular) = ctranspose(A * ctranspose(rowvec)) -@inline A_mul_Bc(A::AbstractTriangular, rowvec::RowVector) = A * ctranspose(rowvec) -@inline Ac_mul_Bc(A::AbstractTriangular, rowvec::RowVector) = A' * ctranspose(rowvec) - -@inline /(rowvec::RowVector, A::Union{UpperTriangular,LowerTriangular}) = transpose(transpose(A) \ transpose(rowvec)) -@inline /(rowvec::RowVector, A::Union{UnitUpperTriangular,UnitLowerTriangular}) = transpose(transpose(A) \ transpose(rowvec)) - -@inline A_rdiv_Bt(rowvec::RowVector, A::Union{UpperTriangular,LowerTriangular}) = transpose(A \ transpose(rowvec)) -@inline A_rdiv_Bt(rowvec::RowVector, A::Union{UnitUpperTriangular,UnitLowerTriangular}) = transpose(A \ transpose(rowvec)) - -@inline A_rdiv_Bc(rowvec::RowVector, A::Union{UpperTriangular,LowerTriangular}) = ctranspose(A \ ctranspose(rowvec)) -@inline A_rdiv_Bc(rowvec::RowVector, A::Union{UnitUpperTriangular,UnitLowerTriangular}) = ctranspose(A \ ctranspose(rowvec)) - -\(::Union{UpperTriangular,LowerTriangular}, ::RowVector) = throw(DimensionMismatch("Cannot left-divide matrix by transposed vector")) -\(::Union{UnitUpperTriangular,UnitLowerTriangular}, ::RowVector) = throw(DimensionMismatch("Cannot left-divide matrix by transposed vector")) - -At_ldiv_B(::Union{UpperTriangular,LowerTriangular}, ::RowVector) = throw(DimensionMismatch("Cannot left-divide matrix by transposed vector")) -At_ldiv_B(::Union{UnitUpperTriangular,UnitLowerTriangular}, ::RowVector) = throw(DimensionMismatch("Cannot left-divide matrix by transposed vector")) - -Ac_ldiv_B(::Union{UpperTriangular,LowerTriangular}, ::RowVector) = throw(DimensionMismatch("Cannot left-divide matrix by transposed vector")) -Ac_ldiv_B(::Union{UnitUpperTriangular,UnitLowerTriangular}, ::RowVector) = throw(DimensionMismatch("Cannot left-divide matrix by transposed vector")) - -# Complex matrix power for upper triangular factor, see: -# Higham and Lin, "A Schur-Padé algorithm for fractional powers of a Matrix", -# SIAM J. Matrix Anal. & Appl., 32 (3), (2011) 1056–1078. -# Higham and Lin, "An improved Schur-Padé algorithm for fractional powers of -# a matrix and their Fréchet derivatives", SIAM. J. Matrix Anal. & Appl., -# 34(3), (2013) 1341–1360. -function powm!(A0::UpperTriangular{<:BlasFloat}, p::Real) - if abs(p) >= 1 - ArgumentError("p must be a real number in (-1,1), got $p") - end - - normA0 = norm(A0, 1) - scale!(A0, 1/normA0) - - theta = [1.53e-5, 2.25e-3, 1.92e-2, 6.08e-2, 1.25e-1, 2.03e-1, 2.84e-1] - n = checksquare(A0) - - A, m, s = invsquaring(A0, theta) - A = I - A - - # Compute accurate diagonal of I - T - sqrt_diag!(A0, A, s) - for i = 1:n - A[i, i] = -A[i, i] - end - # Compute the Padé approximant - c = 0.5 * (p - m) / (2 * m - 1) - triu!(A) - S = c * A - Stmp = similar(S) - for j = m-1:-1:1 - j4 = 4 * j - c = (-p - j) / (j4 + 2) - for i = 1:n - @inbounds S[i, i] = S[i, i] + 1 - end - copy!(Stmp, S) - scale!(S, A, c) - A_ldiv_B!(Stmp, S.data) - - c = (p - j) / (j4 - 2) - for i = 1:n - @inbounds S[i, i] = S[i, i] + 1 - end - copy!(Stmp, S) - scale!(S, A, c) - A_ldiv_B!(Stmp, S.data) - end - for i = 1:n - S[i, i] = S[i, i] + 1 - end - copy!(Stmp, S) - scale!(S, A, -p) - A_ldiv_B!(Stmp, S.data) - for i = 1:n - @inbounds S[i, i] = S[i, i] + 1 - end - - blockpower!(A0, S, p/(2^s)) - for m = 1:s - A_mul_B!(Stmp.data, S, S) - copy!(S, Stmp) - blockpower!(A0, S, p/(2^(s-m))) - end - scale!(S, normA0^p) - return S -end -powm(A::LowerTriangular, p::Real) = powm(A.', p::Real).' - -# Complex matrix logarithm for the upper triangular factor, see: -# Al-Mohy and Higham, "Improved inverse scaling and squaring algorithms for -# the matrix logarithm", SIAM J. Sci. Comput., 34(4), (2012), pp. C153–C169. -# Al-Mohy, Higham and Relton, "Computing the Frechet derivative of the matrix -# logarithm and estimating the condition number", SIAM J. Sci. Comput., -# 35(4), (2013), C394–C410. -# -# Based on the code available at http://eprints.ma.man.ac.uk/1851/02/logm.zip, -# Copyright (c) 2011, Awad H. Al-Mohy and Nicholas J. Higham -# Julia version relicensed with permission from original authors -function logm(A0::UpperTriangular{T}) where T<:Union{Float64,Complex{Float64}} - maxsqrt = 100 - theta = [1.586970738772063e-005, - 2.313807884242979e-003, - 1.938179313533253e-002, - 6.209171588994762e-002, - 1.276404810806775e-001, - 2.060962623452836e-001, - 2.879093714241194e-001] - tmax = size(theta, 1) - n = size(A0, 1) - A = copy(A0) - p = 0 - m = 0 - - # Compute repeated roots - d = complex(diag(A)) - dm1 = d .- 1 - s = 0 - while norm(dm1, Inf) > theta[tmax] && s < maxsqrt - d .= sqrt.(d) - dm1 .= d .- 1 - s = s + 1 - end - s0 = s - for k = 1:min(s, maxsqrt) - A = sqrtm(A) - end - - AmI = A - I - d2 = sqrt(norm(AmI^2, 1)) - d3 = cbrt(norm(AmI^3, 1)) - alpha2 = max(d2, d3) - foundm = false - if alpha2 <= theta[2] - m = alpha2 <= theta[1] ? 1 : 2 - foundm = true - end - - while !foundm - more = false - if s > s0 - d3 = cbrt(norm(AmI^3, 1)) - end - d4 = norm(AmI^4, 1)^(1/4) - alpha3 = max(d3, d4) - if alpha3 <= theta[tmax] - for j = 3:tmax - if alpha3 <= theta[j] - break - end - end - if j <= 6 - m = j - break - elseif alpha3 / 2 <= theta[5] && p < 2 - more = true - p = p + 1 - end - end - - if !more - d5 = norm(AmI^5, 1)^(1/5) - alpha4 = max(d4, d5) - eta = min(alpha3, alpha4) - if eta <= theta[tmax] - j = 0 - for j = 6:tmax - if eta <= theta[j] - m = j - break - end - end - break - end - end - - if s == maxsqrt - m = tmax - break - end - A = sqrtm(A) - AmI = A - I - s = s + 1 - end - - # Compute accurate superdiagonal of T - p = 1 / 2^s - for k = 1:n-1 - Ak = A0[k,k] - Akp1 = A0[k+1,k+1] - Akp = Ak^p - Akp1p = Akp1^p - A[k,k] = Akp - A[k+1,k+1] = Akp1p - if Ak == Akp1 - A[k,k+1] = p * A0[k,k+1] * Ak^(p-1) - elseif 2 * abs(Ak) < abs(Akp1) || 2 * abs(Akp1) < abs(Ak) - A[k,k+1] = A0[k,k+1] * (Akp1p - Akp) / (Akp1 - Ak) - else - logAk = log(Ak) - logAkp1 = log(Akp1) - w = atanh((Akp1 - Ak)/(Akp1 + Ak)) + im*pi*ceil((imag(logAkp1-logAk)-pi)/(2*pi)) - dd = 2 * exp(p*(logAk+logAkp1)/2) * sinh(p*w) / (Akp1 - Ak) - A[k,k+1] = A0[k,k+1] * dd - end - end - - # Compute accurate diagonal of T - for i = 1:n - a = A0[i,i] - if s == 0 - r = a - 1 - end - s0 = s - if angle(a) >= pi / 2 - a = sqrt(a) - s0 = s - 1 - end - z0 = a - 1 - a = sqrt(a) - r = 1 + a - for j = 1:s0-1 - a = sqrt(a) - r = r * (1 + a) - end - A[i,i] = z0 / r - end - - # Get the Gauss-Legendre quadrature points and weights - R = zeros(Float64, m, m) - for i = 1:m - 1 - R[i,i+1] = i / sqrt((2 * i)^2 - 1) - R[i+1,i] = R[i,i+1] - end - x,V = eig(R) - w = Vector{Float64}(m) - for i = 1:m - x[i] = (x[i] + 1) / 2 - w[i] = V[1,i]^2 - end - - # Compute the Padé approximation - Y = zeros(T, n, n) - for k = 1:m - Y = Y + w[k] * (A / (x[k] * A + I)) - end - - # Scale back - scale!(2^s, Y) - - # Compute accurate diagonal and superdiagonal of log(T) - for k = 1:n-1 - Ak = A0[k,k] - Akp1 = A0[k+1,k+1] - logAk = log(Ak) - logAkp1 = log(Akp1) - Y[k,k] = logAk - Y[k+1,k+1] = logAkp1 - if Ak == Akp1 - Y[k,k+1] = A0[k,k+1] / Ak - elseif 2 * abs(Ak) < abs(Akp1) || 2 * abs(Akp1) < abs(Ak) - Y[k,k+1] = A0[k,k+1] * (logAkp1 - logAk) / (Akp1 - Ak) - else - w = atanh((Akp1 - Ak)/(Akp1 + Ak) + im*pi*(ceil((imag(logAkp1-logAk) - pi)/(2*pi)))) - Y[k,k+1] = 2 * A0[k,k+1] * w / (Akp1 - Ak) - end - end - - return UpperTriangular(Y) -end -logm(A::LowerTriangular) = logm(A.').' - -# Auxiliary functions for logm and matrix power - -# Compute accurate diagonal of A = A0^s - I -# Al-Mohy, "A more accurate Briggs method for the logarithm", -# Numer. Algorithms, 59, (2012), 393–402. -function sqrt_diag!(A0::UpperTriangular, A::UpperTriangular, s) - n = checksquare(A0) - @inbounds for i = 1:n - a = complex(A0[i,i]) - if s == 0 - A[i,i] = a - 1 - else - s0 = s - if imag(a) >= 0 && real(a) <= 0 && a != 0 - a = sqrt(a) - s0 = s - 1 - end - z0 = a - 1 - a = sqrt(a) - r = 1 + a - for j = 1:s0-1 - a = sqrt(a) - r = r * (1 + a) - end - A[i,i] = z0 / r - end - end -end - -# Used only by powm at the moment -# Repeatedly compute the square roots of A so that in the end its -# eigenvalues are close enough to the positive real line -function invsquaring(A0::UpperTriangular, theta) - # assumes theta is in ascending order - maxsqrt = 100 - tmax = size(theta, 1) - n = checksquare(A0) - A = complex(copy(A0)) - p = 0 - m = 0 - - # Compute repeated roots - d = complex(diag(A)) - dm1 = d .- 1 - s = 0 - while norm(dm1, Inf) > theta[tmax] && s < maxsqrt - d .= sqrt.(d) - dm1 .= d .- 1 - s = s + 1 - end - s0 = s - for k = 1:min(s, maxsqrt) - A = sqrtm(A) - end - - AmI = A - I - d2 = sqrt(norm(AmI^2, 1)) - d3 = cbrt(norm(AmI^3, 1)) - alpha2 = max(d2, d3) - foundm = false - if alpha2 <= theta[2] - m = alpha2 <= theta[1] ? 1 : 2 - foundm = true - end - - while !foundm - more = false - if s > s0 - d3 = cbrt(norm(AmI^3, 1)) - end - d4 = norm(AmI^4, 1)^(1/4) - alpha3 = max(d3, d4) - if alpha3 <= theta[tmax] - for j = 3:tmax - if alpha3 <= theta[j] - break - elseif alpha3 / 2 <= theta[5] && p < 2 - more = true - p = p + 1 - end - end - if j <= 6 - m = j - foundm = true - break - elseif alpha3 / 2 <= theta[5] && p < 2 - more = true - p = p + 1 - end - end - - if !more - d5 = norm(AmI^5, 1)^(1/5) - alpha4 = max(d4, d5) - eta = min(alpha3, alpha4) - if eta <= theta[tmax] - j = 0 - for j = 6:tmax - if eta <= theta[j] - m = j - break - end - break - end - end - if s == maxsqrt - m = tmax - break - end - A = sqrtm(A) - AmI = A - I - s = s + 1 - end - end - - # Compute accurate superdiagonal of T - p = 1 / 2^s - A = complex(A) - blockpower!(A, A0, p) - return A,m,s -end - -# Compute accurate diagonal and superdiagonal of A = A0^p -function blockpower!(A::UpperTriangular, A0::UpperTriangular, p) - n = checksquare(A0) - @inbounds for k = 1:n-1 - Ak = complex(A0[k,k]) - Akp1 = complex(A0[k+1,k+1]) - - Akp = Ak^p - Akp1p = Akp1^p - - A[k,k] = Akp - A[k+1,k+1] = Akp1p - - if Ak == Akp1 - A[k,k+1] = p * A0[k,k+1] * Ak^(p-1) - elseif 2 * abs(Ak) < abs(Akp1) || 2 * abs(Akp1) < abs(Ak) - A[k,k+1] = A0[k,k+1] * (Akp1p - Akp) / (Akp1 - Ak) - else - logAk = log(Ak) - logAkp1 = log(Akp1) - w = atanh((Akp1 - Ak)/(Akp1 + Ak)) + im * pi * unw(logAkp1-logAk) - dd = 2 * exp(p*(logAk+logAkp1)/2) * sinh(p*w) / (Akp1 - Ak); - A[k,k+1] = A0[k,k+1] * dd - end - end -end - -# Unwinding number -unw(x::Real) = 0 -unw(x::Number) = ceil((imag(x) - pi) / (2 * pi)) - -# End of auxiliary functions for logm and matrix power - -function sqrtm(A::UpperTriangular) - realmatrix = false - if isreal(A) - realmatrix = true - for i = 1:checksquare(A) - x = real(A[i,i]) - if x < zero(x) - realmatrix = false - break - end - end - end - sqrtm(A,Val{realmatrix}) -end -function sqrtm(A::UpperTriangular{T},::Type{Val{realmatrix}}) where {T,realmatrix} - B = A.data - n = checksquare(B) - t = realmatrix ? typeof(sqrt(zero(T))) : typeof(sqrt(complex(zero(T)))) - R = zeros(t, n, n) - tt = typeof(zero(t)*zero(t)) - @inbounds for j = 1:n - R[j,j] = realmatrix ? sqrt(B[j,j]) : sqrt(complex(B[j,j])) - for i = j-1:-1:1 - r::tt = B[i,j] - @simd for k = i+1:j-1 - r -= R[i,k]*R[k,j] - end - iszero(r) || (R[i,j] = sylvester(R[i,i],R[j,j],-r)) - end - end - return UpperTriangular(R) -end -function sqrtm(A::UnitUpperTriangular{T}) where T - B = A.data - n = checksquare(B) - t = typeof(sqrt(zero(T))) - R = eye(t, n, n) - tt = typeof(zero(t)*zero(t)) - half = inv(R[1,1]+R[1,1]) # for general, algebraic cases. PR#20214 - @inbounds for j = 1:n - for i = j-1:-1:1 - r::tt = B[i,j] - @simd for k = i+1:j-1 - r -= R[i,k]*R[k,j] - end - r==0 || (R[i,j] = half*r) - end - end - return UnitUpperTriangular(R) -end -sqrtm(A::LowerTriangular) = sqrtm(A.').' -sqrtm(A::UnitLowerTriangular) = sqrtm(A.').' - -# Generic eigensystems -eigvals(A::AbstractTriangular) = diag(A) -function eigvecs(A::AbstractTriangular{T}) where T - TT = promote_type(T, Float32) - if TT <: BlasFloat - return eigvecs(convert(AbstractMatrix{TT}, A)) - else - throw(ArgumentError("eigvecs type $(typeof(A)) not supported. Please submit a pull request.")) - end -end -det(A::UnitUpperTriangular{T}) where {T} = one(T) -det(A::UnitLowerTriangular{T}) where {T} = one(T) -logdet(A::UnitUpperTriangular{T}) where {T} = zero(T) -logdet(A::UnitLowerTriangular{T}) where {T} = zero(T) -logabsdet(A::UnitUpperTriangular{T}) where {T} = zero(T), one(T) -logabsdet(A::UnitLowerTriangular{T}) where {T} = zero(T), one(T) -det(A::UpperTriangular) = prod(diag(A.data)) -det(A::LowerTriangular) = prod(diag(A.data)) -function logabsdet(A::Union{UpperTriangular{T},LowerTriangular{T}}) where T - sgn = one(T) - abs_det = zero(real(T)) - @inbounds for i in 1:size(A,1) - diag_i = A.data[i,i] - sgn *= sign(diag_i) - abs_det += log(abs(diag_i)) - end - return abs_det, sgn -end - -eigfact(A::AbstractTriangular) = Eigen(eigvals(A), eigvecs(A)) - -# Generic singular systems -for func in (:svd, :svdfact, :svdfact!, :svdvals) - @eval begin - ($func)(A::AbstractTriangular) = ($func)(full(A)) - end -end - -factorize(A::AbstractTriangular) = A diff --git a/julia-0.6.3/share/julia/base/linalg/tridiag.jl b/julia-0.6.3/share/julia/base/linalg/tridiag.jl deleted file mode 100644 index be3792b..0000000 --- a/julia-0.6.3/share/julia/base/linalg/tridiag.jl +++ /dev/null @@ -1,651 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -#### Specialized matrix types #### - -## (complex) symmetric tridiagonal matrices -struct SymTridiagonal{T} <: AbstractMatrix{T} - dv::Vector{T} # diagonal - ev::Vector{T} # subdiagonal - function SymTridiagonal{T}(dv::Vector{T}, ev::Vector{T}) where T - if !(length(dv) - 1 <= length(ev) <= length(dv)) - throw(DimensionMismatch("subdiagonal has wrong length. Has length $(length(ev)), but should be either $(length(dv) - 1) or $(length(dv)).")) - end - new(dv,ev) - end -end - -""" - SymTridiagonal(dv, ev) - -Construct a symmetric tridiagonal matrix from the diagonal and first sub/super-diagonal, -respectively. The result is of type `SymTridiagonal` and provides efficient specialized -eigensolvers, but may be converted into a regular matrix with -[`convert(Array, _)`](@ref) (or `Array(_)` for short). - -# Example - -```jldoctest -julia> dv = [1; 2; 3; 4] -4-element Array{Int64,1}: - 1 - 2 - 3 - 4 - -julia> ev = [7; 8; 9] -3-element Array{Int64,1}: - 7 - 8 - 9 - -julia> SymTridiagonal(dv, ev) -4×4 SymTridiagonal{Int64}: - 1 7 ⋅ ⋅ - 7 2 8 ⋅ - ⋅ 8 3 9 - ⋅ ⋅ 9 4 -``` -""" -SymTridiagonal(dv::Vector{T}, ev::Vector{T}) where {T} = SymTridiagonal{T}(dv, ev) - -function SymTridiagonal(dv::AbstractVector{Td}, ev::AbstractVector{Te}) where {Td,Te} - T = promote_type(Td,Te) - SymTridiagonal(convert(Vector{T}, dv), convert(Vector{T}, ev)) -end - -function SymTridiagonal(A::AbstractMatrix) - if diag(A,1) == diag(A,-1) - SymTridiagonal(diag(A), diag(A,1)) - else - throw(ArgumentError("matrix is not symmetric; cannot convert to SymTridiagonal")) - end -end - -convert(::Type{SymTridiagonal{T}}, S::SymTridiagonal) where {T} = - SymTridiagonal(convert(Vector{T}, S.dv), convert(Vector{T}, S.ev)) -convert(::Type{AbstractMatrix{T}}, S::SymTridiagonal) where {T} = - SymTridiagonal(convert(Vector{T}, S.dv), convert(Vector{T}, S.ev)) -function convert(::Type{Matrix{T}}, M::SymTridiagonal{T}) where T - n = size(M, 1) - Mf = zeros(T, n, n) - @inbounds begin - @simd for i = 1:n-1 - Mf[i,i] = M.dv[i] - Mf[i+1,i] = M.ev[i] - Mf[i,i+1] = M.ev[i] - end - Mf[n,n] = M.dv[n] - end - return Mf -end -convert(::Type{Matrix}, M::SymTridiagonal{T}) where {T} = convert(Matrix{T}, M) -convert(::Type{Array}, M::SymTridiagonal) = convert(Matrix, M) -full(M::SymTridiagonal) = convert(Array, M) - -size(A::SymTridiagonal) = (length(A.dv), length(A.dv)) -function size(A::SymTridiagonal, d::Integer) - if d < 1 - throw(ArgumentError("dimension must be ≥ 1, got $d")) - elseif d<=2 - return length(A.dv) - else - return 1 - end -end - -similar(S::SymTridiagonal, ::Type{T}) where {T} = SymTridiagonal{T}(similar(S.dv, T), similar(S.ev, T)) - -#Elementary operations -broadcast(::typeof(abs), M::SymTridiagonal) = SymTridiagonal(abs.(M.dv), abs.(M.ev)) -broadcast(::typeof(round), M::SymTridiagonal) = SymTridiagonal(round.(M.dv), round.(M.ev)) -broadcast(::typeof(trunc), M::SymTridiagonal) = SymTridiagonal(trunc.(M.dv), trunc.(M.ev)) -broadcast(::typeof(floor), M::SymTridiagonal) = SymTridiagonal(floor.(M.dv), floor.(M.ev)) -broadcast(::typeof(ceil), M::SymTridiagonal) = SymTridiagonal(ceil.(M.dv), ceil.(M.ev)) -for func in (:conj, :copy, :real, :imag) - @eval ($func)(M::SymTridiagonal) = SymTridiagonal(($func)(M.dv), ($func)(M.ev)) -end -broadcast(::typeof(round), ::Type{T}, M::SymTridiagonal) where {T<:Integer} = SymTridiagonal(round.(T, M.dv), round.(T, M.ev)) -broadcast(::typeof(trunc), ::Type{T}, M::SymTridiagonal) where {T<:Integer} = SymTridiagonal(trunc.(T, M.dv), trunc.(T, M.ev)) -broadcast(::typeof(floor), ::Type{T}, M::SymTridiagonal) where {T<:Integer} = SymTridiagonal(floor.(T, M.dv), floor.(T, M.ev)) -broadcast(::typeof(ceil), ::Type{T}, M::SymTridiagonal) where {T<:Integer} = SymTridiagonal(ceil.(T, M.dv), ceil.(T, M.ev)) - -transpose(M::SymTridiagonal) = M #Identity operation -ctranspose(M::SymTridiagonal) = conj(M) - -function diag(M::SymTridiagonal{T}, n::Integer=0) where T - absn = abs(n) - if absn == 0 - return M.dv - elseif absn==1 - return M.ev - elseif absn 1 ? zero(β[1]) : zero(eltype(β)) - for i = 1:m - 1 - x₋, x₀, x₊ = x₀, x₊, B[i + 1, j] - β₋, β₀ = β₀, β[i] - C[i, j] = β₋*x₋ + α[i]*x₀ + β₀*x₊ - end - C[m, j] = β₀*x₀ + α[m]*x₊ - end - end - - return C -end - -(\)(T::SymTridiagonal, B::StridedVecOrMat) = ldltfact(T)\B - -eigfact!(A::SymTridiagonal{<:BlasReal}) = Eigen(LAPACK.stegr!('V', A.dv, A.ev)...) -function eigfact(A::SymTridiagonal{T}) where T - S = promote_type(Float32, typeof(zero(T)/norm(one(T)))) - eigfact!(copy_oftype(A, S)) -end - -eigfact!(A::SymTridiagonal{<:BlasReal}, irange::UnitRange) = - Eigen(LAPACK.stegr!('V', 'I', A.dv, A.ev, 0.0, 0.0, irange.start, irange.stop)...) -function eigfact(A::SymTridiagonal{T}, irange::UnitRange) where T - S = promote_type(Float32, typeof(zero(T)/norm(one(T)))) - return eigfact!(copy_oftype(A, S), irange) -end - -eigfact!(A::SymTridiagonal{<:BlasReal}, vl::Real, vu::Real) = - Eigen(LAPACK.stegr!('V', 'V', A.dv, A.ev, vl, vu, 0, 0)...) -function eigfact(A::SymTridiagonal{T}, vl::Real, vu::Real) where T - S = promote_type(Float32, typeof(zero(T)/norm(one(T)))) - return eigfact!(copy_oftype(A, S), vl, vu) -end - -eigvals!(A::SymTridiagonal{<:BlasReal}) = LAPACK.stev!('N', A.dv, A.ev)[1] -function eigvals(A::SymTridiagonal{T}) where T - S = promote_type(Float32, typeof(zero(T)/norm(one(T)))) - return eigvals!(copy_oftype(A, S)) -end - -eigvals!(A::SymTridiagonal{<:BlasReal}, irange::UnitRange) = - LAPACK.stegr!('N', 'I', A.dv, A.ev, 0.0, 0.0, irange.start, irange.stop)[1] -function eigvals(A::SymTridiagonal{T}, irange::UnitRange) where T - S = promote_type(Float32, typeof(zero(T)/norm(one(T)))) - return eigvals!(copy_oftype(A, S), irange) -end - -eigvals!(A::SymTridiagonal{<:BlasReal}, vl::Real, vu::Real) = - LAPACK.stegr!('N', 'V', A.dv, A.ev, vl, vu, 0, 0)[1] -function eigvals(A::SymTridiagonal{T}, vl::Real, vu::Real) where T - S = promote_type(Float32, typeof(zero(T)/norm(one(T)))) - return eigvals!(copy_oftype(A, S), vl, vu) -end - -#Computes largest and smallest eigenvalue -eigmax(A::SymTridiagonal) = eigvals(A, size(A, 1):size(A, 1))[1] -eigmin(A::SymTridiagonal) = eigvals(A, 1:1)[1] - -#Compute selected eigenvectors only corresponding to particular eigenvalues -eigvecs(A::SymTridiagonal) = eigfact(A)[:vectors] - -""" - eigvecs(A::SymTridiagonal[, eigvals]) -> Matrix - -Returns a matrix `M` whose columns are the eigenvectors of `A`. (The `k`th eigenvector can -be obtained from the slice `M[:, k]`.) - -If the optional vector of eigenvalues `eigvals` is specified, `eigvecs` -returns the specific corresponding eigenvectors. - -# Example - -```jldoctest -julia> A = SymTridiagonal([1.; 2.; 1.], [2.; 3.]) -3×3 SymTridiagonal{Float64}: - 1.0 2.0 ⋅ - 2.0 2.0 3.0 - ⋅ 3.0 1.0 - -julia> eigvals(A) -3-element Array{Float64,1}: - -2.14005 - 1.0 - 5.14005 - -julia> eigvecs(A) -3×3 Array{Float64,2}: - 0.418304 -0.83205 0.364299 - -0.656749 -7.39009e-16 0.754109 - 0.627457 0.5547 0.546448 - -julia> eigvecs(A, [1.]) -3×1 Array{Float64,2}: - 0.83205 - 4.26351e-17 - -0.5547 -``` -""" -eigvecs(A::SymTridiagonal{<:BlasFloat}, eigvals::Vector{<:Real}) = LAPACK.stein!(A.dv, A.ev, eigvals) - -#tril and triu - -istriu(M::SymTridiagonal) = iszero(M.ev) -istril(M::SymTridiagonal) = iszero(M.ev) - -function tril!(M::SymTridiagonal, k::Integer=0) - n = length(M.dv) - if abs(k) > n - throw(ArgumentError("requested diagonal, $k, out of bounds in matrix of size ($n,$n)")) - elseif k < -1 - fill!(M.ev,0) - fill!(M.dv,0) - return Tridiagonal(M.ev,M.dv,copy(M.ev)) - elseif k == -1 - fill!(M.dv,0) - return Tridiagonal(M.ev,M.dv,zeros(M.ev)) - elseif k == 0 - return Tridiagonal(M.ev,M.dv,zeros(M.ev)) - elseif k >= 1 - return Tridiagonal(M.ev,M.dv,copy(M.ev)) - end -end - -function triu!(M::SymTridiagonal, k::Integer=0) - n = length(M.dv) - if abs(k) > n - throw(ArgumentError("requested diagonal, $k, out of bounds in matrix of size ($n,$n)")) - elseif k > 1 - fill!(M.ev,0) - fill!(M.dv,0) - return Tridiagonal(M.ev,M.dv,copy(M.ev)) - elseif k == 1 - fill!(M.dv,0) - return Tridiagonal(zeros(M.ev),M.dv,M.ev) - elseif k == 0 - return Tridiagonal(zeros(M.ev),M.dv,M.ev) - elseif k <= -1 - return Tridiagonal(M.ev,M.dv,copy(M.ev)) - end -end - -################### -# Generic methods # -################### - -#Needed for inv_usmani() -mutable struct ZeroOffsetVector - data::Vector -end -getindex(a::ZeroOffsetVector, i) = a.data[i+1] -setindex!(a::ZeroOffsetVector, x, i) = a.data[i+1]=x - - -## structured matrix methods ## -function Base.replace_in_print_matrix(A::SymTridiagonal, i::Integer, j::Integer, s::AbstractString) - i==j-1||i==j||i==j+1 ? s : Base.replace_with_centered_mark(s) -end - -#Implements the inverse using the recurrence relation between principal minors -# a, b, c are assumed to be the subdiagonal, diagonal, and superdiagonal of -# a tridiagonal matrix. -#Reference: -# R. Usmani, "Inversion of a tridiagonal Jacobi matrix", -# Linear Algebra and its Applications 212-213 (1994), pp.413-414 -# doi:10.1016/0024-3795(94)90414-6 -function inv_usmani(a::Vector{T}, b::Vector{T}, c::Vector{T}) where T - n = length(b) - θ = ZeroOffsetVector(zeros(T, n+1)) #principal minors of A - θ[0] = 1 - n>=1 && (θ[1] = b[1]) - for i=2:n - θ[i] = b[i]*θ[i-1]-a[i-1]*c[i-1]*θ[i-2] - end - φ = zeros(T, n+1) - φ[n+1] = 1 - n>=1 && (φ[n] = b[n]) - for i=n-1:-1:1 - φ[i] = b[i]*φ[i+1]-a[i]*c[i]*φ[i+2] - end - α = Matrix{T}(n, n) - for i=1:n, j=1:n - sign = (i+j)%2==0 ? (+) : (-) - if ij - α[i,j]=(sign)(prod(a[j:i-1]))*θ[j-1]*φ[i+1]/θ[n] - end - end - α -end - -#Implements the determinant using principal minors -#Inputs and reference are as above for inv_usmani() -function det_usmani(a::Vector{T}, b::Vector{T}, c::Vector{T}) where T - n = length(b) - θa = one(T) - if n == 0 - return θa - end - θb = b[1] - for i=2:n - θb, θa = b[i]*θb-a[i-1]*c[i-1]*θa, θb - end - return θb -end - -inv(A::SymTridiagonal) = inv_usmani(A.ev, A.dv, A.ev) -det(A::SymTridiagonal) = det_usmani(A.ev, A.dv, A.ev) - -function getindex(A::SymTridiagonal{T}, i::Integer, j::Integer) where T - if !(1 <= i <= size(A,2) && 1 <= j <= size(A,2)) - throw(BoundsError(A, (i,j))) - end - if i == j - return A.dv[i] - elseif i == j + 1 - return A.ev[j] - elseif i + 1 == j - return A.ev[i] - else - return zero(T) - end -end - -function setindex!(A::SymTridiagonal, x, i::Integer, j::Integer) - @boundscheck checkbounds(A, i, j) - if i == j - @inbounds A.dv[i] = x - else - throw(ArgumentError("cannot set off-diagonal entry ($i, $j)")) - end - return x -end - -## Tridiagonal matrices ## -struct Tridiagonal{T} <: AbstractMatrix{T} - dl::Vector{T} # sub-diagonal - d::Vector{T} # diagonal - du::Vector{T} # sup-diagonal - du2::Vector{T} # supsup-diagonal for pivoting -end - -""" - Tridiagonal(dl, d, du) - -Construct a tridiagonal matrix from the first subdiagonal, diagonal, and first superdiagonal, -respectively. The result is of type `Tridiagonal` and provides efficient specialized linear -solvers, but may be converted into a regular matrix with -[`convert(Array, _)`](@ref) (or `Array(_)` for short). -The lengths of `dl` and `du` must be one less than the length of `d`. - -# Example - -```jldoctest -julia> dl = [1; 2; 3] -3-element Array{Int64,1}: - 1 - 2 - 3 - -julia> du = [4; 5; 6] -3-element Array{Int64,1}: - 4 - 5 - 6 - -julia> d = [7; 8; 9; 0] -4-element Array{Int64,1}: - 7 - 8 - 9 - 0 - -julia> Tridiagonal(dl, d, du) -4×4 Tridiagonal{Int64}: - 7 4 ⋅ ⋅ - 1 8 5 ⋅ - ⋅ 2 9 6 - ⋅ ⋅ 3 0 -``` -""" -# Basic constructor takes in three dense vectors of same type -function Tridiagonal(dl::Vector{T}, d::Vector{T}, du::Vector{T}) where T - n = length(d) - if (length(dl) != n-1 || length(du) != n-1) - throw(ArgumentError("cannot make Tridiagonal from incompatible lengths of subdiagonal, diagonal and superdiagonal: ($(length(dl)), $(length(d)), $(length(du))")) - end - Tridiagonal(dl, d, du, zeros(T,n-2)) -end - -# Construct from diagonals of any abstract vector, any eltype -function Tridiagonal(dl::AbstractVector{Tl}, d::AbstractVector{Td}, du::AbstractVector{Tu}) where {Tl,Td,Tu} - Tridiagonal(map(v->convert(Vector{promote_type(Tl,Td,Tu)}, v), (dl, d, du))...) -end - -# Provide a constructor Tridiagonal(A) similar to the triangulars, diagonal, symmetric -""" - Tridiagonal(A) - -returns a `Tridiagonal` array based on (abstract) matrix `A`, using its first lower diagonal, -main diagonal, and first upper diagonal. - -# Example - -```jldoctest -julia> A = [1 2 3 4; 1 2 3 4; 1 2 3 4; 1 2 3 4] -4×4 Array{Int64,2}: - 1 2 3 4 - 1 2 3 4 - 1 2 3 4 - 1 2 3 4 - -julia> Tridiagonal(A) -4×4 Tridiagonal{Int64}: - 1 2 ⋅ ⋅ - 1 2 3 ⋅ - ⋅ 2 3 4 - ⋅ ⋅ 3 4 -``` -""" -function Tridiagonal(A::AbstractMatrix) - return Tridiagonal(diag(A,-1), diag(A), diag(A,+1)) -end - -size(M::Tridiagonal) = (length(M.d), length(M.d)) -function size(M::Tridiagonal, d::Integer) - if d < 1 - throw(ArgumentError("dimension d must be ≥ 1, got $d")) - elseif d <= 2 - return length(M.d) - else - return 1 - end -end - -function convert(::Type{Matrix{T}}, M::Tridiagonal{T}) where T - A = zeros(T, size(M)) - for i = 1:length(M.d) - A[i,i] = M.d[i] - end - for i = 1:length(M.d)-1 - A[i+1,i] = M.dl[i] - A[i,i+1] = M.du[i] - end - A -end -convert(::Type{Matrix}, M::Tridiagonal{T}) where {T} = convert(Matrix{T}, M) -convert(::Type{Array}, M::Tridiagonal) = convert(Matrix, M) -full(M::Tridiagonal) = convert(Array, M) -function similar(M::Tridiagonal, ::Type{T}) where T - Tridiagonal{T}(similar(M.dl, T), similar(M.d, T), similar(M.du, T), similar(M.du2, T)) -end - -# Operations on Tridiagonal matrices -copy!(dest::Tridiagonal, src::Tridiagonal) = Tridiagonal(copy!(dest.dl, src.dl), copy!(dest.d, src.d), copy!(dest.du, src.du), copy!(dest.du2, src.du2)) - -#Elementary operations -broadcast(::typeof(abs), M::Tridiagonal) = Tridiagonal(abs.(M.dl), abs.(M.d), abs.(M.du), abs.(M.du2)) -broadcast(::typeof(round), M::Tridiagonal) = Tridiagonal(round.(M.dl), round.(M.d), round.(M.du), round.(M.du2)) -broadcast(::typeof(trunc), M::Tridiagonal) = Tridiagonal(trunc.(M.dl), trunc.(M.d), trunc.(M.du), trunc.(M.du2)) -broadcast(::typeof(floor), M::Tridiagonal) = Tridiagonal(floor.(M.dl), floor.(M.d), floor.(M.du), floor.(M.du2)) -broadcast(::typeof(ceil), M::Tridiagonal) = Tridiagonal(ceil.(M.dl), ceil.(M.d), ceil.(M.du), ceil.(M.du2)) -for func in (:conj, :copy, :real, :imag) - @eval function ($func)(M::Tridiagonal) - Tridiagonal(($func)(M.dl), ($func)(M.d), ($func)(M.du), ($func)(M.du2)) - end -end -broadcast(::typeof(round), ::Type{T}, M::Tridiagonal) where {T<:Integer} = - Tridiagonal(round.(T, M.dl), round.(T, M.d), round.(T, M.du), round.(T, M.du2)) -broadcast(::typeof(trunc), ::Type{T}, M::Tridiagonal) where {T<:Integer} = - Tridiagonal(trunc.(T, M.dl), trunc.(T, M.d), trunc.(T, M.du), trunc.(T, M.du2)) -broadcast(::typeof(floor), ::Type{T}, M::Tridiagonal) where {T<:Integer} = - Tridiagonal(floor.(T, M.dl), floor.(T, M.d), floor.(T, M.du), floor.(T, M.du2)) -broadcast(::typeof(ceil), ::Type{T}, M::Tridiagonal) where {T<:Integer} = - Tridiagonal(ceil.(T, M.dl), ceil.(T, M.d), ceil.(T, M.du), ceil.(T, M.du2)) - -transpose(M::Tridiagonal) = Tridiagonal(M.du, M.d, M.dl) -ctranspose(M::Tridiagonal) = conj(transpose(M)) - -function diag(M::Tridiagonal{T}, n::Integer=0) where T - if n == 0 - return M.d - elseif n == -1 - return M.dl - elseif n == 1 - return M.du - elseif abs(n) < size(M,1) - return zeros(T,size(M,1)-abs(n)) - else - throw(ArgumentError("$n-th diagonal of a $(size(M)) matrix doesn't exist!")) - end -end - -function getindex(A::Tridiagonal{T}, i::Integer, j::Integer) where T - if !(1 <= i <= size(A,2) && 1 <= j <= size(A,2)) - throw(BoundsError(A, (i,j))) - end - if i == j - return A.d[i] - elseif i == j + 1 - return A.dl[j] - elseif i + 1 == j - return A.du[i] - else - return zero(T) - end -end - -function setindex!(A::Tridiagonal, x, i::Integer, j::Integer) - @boundscheck checkbounds(A, i, j) - if i == j - @inbounds A.d[i] = x - elseif i - j == 1 - @inbounds A.dl[j] = x - elseif j - i == 1 - @inbounds A.du[i] = x - elseif !iszero(x) - throw(ArgumentError(string("cannot set entry ($i, $j) off ", - "the tridiagonal band to a nonzero value ($x)"))) - end - return x -end - -## structured matrix methods ## -function Base.replace_in_print_matrix(A::Tridiagonal,i::Integer,j::Integer,s::AbstractString) - i==j-1||i==j||i==j+1 ? s : Base.replace_with_centered_mark(s) -end - -#tril and triu - -istriu(M::Tridiagonal) = iszero(M.dl) -istril(M::Tridiagonal) = iszero(M.du) - -function tril!(M::Tridiagonal, k::Integer=0) - n = length(M.d) - if abs(k) > n - throw(ArgumentError("requested diagonal, $k, out of bounds in matrix of size ($n,$n)")) - elseif k < -1 - fill!(M.dl,0) - fill!(M.d,0) - fill!(M.du,0) - elseif k == -1 - fill!(M.d,0) - fill!(M.du,0) - elseif k == 0 - fill!(M.du,0) - end - return M -end - -function triu!(M::Tridiagonal, k::Integer=0) - n = length(M.d) - if abs(k) > n - throw(ArgumentError("requested diagonal, $k, out of bounds in matrix of size ($n,$n)")) - elseif k > 1 - fill!(M.dl,0) - fill!(M.d,0) - fill!(M.du,0) - elseif k == 1 - fill!(M.dl,0) - fill!(M.d,0) - elseif k == 0 - fill!(M.dl,0) - end - return M -end - -################### -# Generic methods # -################### - -+(A::Tridiagonal, B::Tridiagonal) = Tridiagonal(A.dl+B.dl, A.d+B.d, A.du+B.du) --(A::Tridiagonal, B::Tridiagonal) = Tridiagonal(A.dl-B.dl, A.d-B.d, A.du-B.du) -*(A::Tridiagonal, B::Number) = Tridiagonal(A.dl*B, A.d*B, A.du*B) -*(B::Number, A::Tridiagonal) = A*B -/(A::Tridiagonal, B::Number) = Tridiagonal(A.dl/B, A.d/B, A.du/B) - -==(A::Tridiagonal, B::Tridiagonal) = (A.dl==B.dl) && (A.d==B.d) && (A.du==B.du) -==(A::Tridiagonal, B::SymTridiagonal) = (A.dl==A.du==B.ev) && (A.d==B.dv) -==(A::SymTridiagonal, B::Tridiagonal) = (B.dl==B.du==A.ev) && (B.d==A.dv) - -inv(A::Tridiagonal) = inv_usmani(A.dl, A.d, A.du) -det(A::Tridiagonal) = det_usmani(A.dl, A.d, A.du) - -convert(::Type{Tridiagonal{T}},M::Tridiagonal) where {T} = Tridiagonal(convert(Vector{T}, M.dl), convert(Vector{T}, M.d), convert(Vector{T}, M.du), convert(Vector{T}, M.du2)) -convert(::Type{AbstractMatrix{T}},M::Tridiagonal) where {T} = convert(Tridiagonal{T}, M) -convert(::Type{Tridiagonal{T}}, M::SymTridiagonal{T}) where {T} = Tridiagonal(M) -function convert(::Type{SymTridiagonal{T}}, M::Tridiagonal) where T - if M.dl == M.du - return SymTridiagonal(convert(Vector{T},M.d), convert(Vector{T},M.dl)) - else - throw(ArgumentError("Tridiagonal is not symmetric, cannot convert to SymTridiagonal")) - end -end diff --git a/julia-0.6.3/share/julia/base/linalg/uniformscaling.jl b/julia-0.6.3/share/julia/base/linalg/uniformscaling.jl deleted file mode 100644 index bbb1dfa..0000000 --- a/julia-0.6.3/share/julia/base/linalg/uniformscaling.jl +++ /dev/null @@ -1,283 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -import Base: copy, ctranspose, getindex, show, transpose, one, zero, inv, - hcat, vcat, hvcat -import Base.LinAlg: SingularException - -struct UniformScaling{T<:Number} - λ::T -end - -""" - I - -An object of type `UniformScaling`, representing an identity matrix of any size. - -# Example - -```jldoctest -julia> ones(5, 6) * I == ones(5, 6) -true - -julia> [1 2im 3; 1im 2 3] * I -2×3 Array{Complex{Int64},2}: - 1+0im 0+2im 3+0im - 0+1im 2+0im 3+0im -``` -""" -const I = UniformScaling(1) - -eltype(::Type{UniformScaling{T}}) where {T} = T -ndims(J::UniformScaling) = 2 -getindex(J::UniformScaling, i::Integer,j::Integer) = ifelse(i==j,J.λ,zero(J.λ)) - -function show(io::IO, J::UniformScaling) - s = "$(J.λ)" - if ismatch(r"\w+\s*[\+\-]\s*\w+", s) - s = "($s)" - end - print(io, "$(typeof(J))\n$s*I") -end -copy(J::UniformScaling) = UniformScaling(J.λ) - -transpose(J::UniformScaling) = J -ctranspose(J::UniformScaling) = UniformScaling(conj(J.λ)) - -one(::Type{UniformScaling{T}}) where {T} = UniformScaling(one(T)) -one(J::UniformScaling{T}) where {T} = one(UniformScaling{T}) -oneunit(::Type{UniformScaling{T}}) where {T} = UniformScaling(oneunit(T)) -oneunit(J::UniformScaling{T}) where {T} = oneunit(UniformScaling{T}) -zero(::Type{UniformScaling{T}}) where {T} = UniformScaling(zero(T)) -zero(J::UniformScaling{T}) where {T} = zero(UniformScaling{T}) - -istriu(::UniformScaling) = true -istril(::UniformScaling) = true -issymmetric(::UniformScaling) = true -ishermitian(J::UniformScaling) = isreal(J.λ) - -(+)(J1::UniformScaling, J2::UniformScaling) = UniformScaling(J1.λ+J2.λ) -(+)(B::BitArray{2}, J::UniformScaling) = Array(B) + J -(+)(J::UniformScaling, B::BitArray{2}) = J + Array(B) -(+)(J::UniformScaling, A::AbstractMatrix) = A + J - -(-)(J::UniformScaling) = UniformScaling(-J.λ) -(-)(J1::UniformScaling, J2::UniformScaling) = UniformScaling(J1.λ-J2.λ) -(-)(B::BitArray{2}, J::UniformScaling) = Array(B) - J -(-)(J::UniformScaling, B::BitArray{2}) = J - Array(B) - -for (t1, t2) in ((:UnitUpperTriangular, :UpperTriangular), - (:UnitLowerTriangular, :LowerTriangular)) - for op in (:+,:-) - @eval begin - ($op)(UL::$t2, J::UniformScaling) = ($t2)(($op)(UL.data, J)) - - function ($op)(UL::$t1, J::UniformScaling) - ULnew = copy_oftype(UL.data, promote_type(eltype(UL), eltype(J))) - for i = 1:size(ULnew, 1) - ULnew[i,i] = ($op)(1, J.λ) - end - return ($t2)(ULnew) - end - end - end -end - -function (-)(J::UniformScaling, UL::Union{UpperTriangular,UnitUpperTriangular}) - ULnew = similar(full(UL), promote_type(eltype(J), eltype(UL))) - n = size(ULnew, 1) - ULold = UL.data - for j = 1:n - for i = 1:j - 1 - ULnew[i,j] = -ULold[i,j] - end - if isa(UL, UnitUpperTriangular) - ULnew[j,j] = J.λ - 1 - else - ULnew[j,j] = J.λ - ULold[j,j] - end - end - return UpperTriangular(ULnew) -end -function (-)(J::UniformScaling, UL::Union{LowerTriangular,UnitLowerTriangular}) - ULnew = similar(full(UL), promote_type(eltype(J), eltype(UL))) - n = size(ULnew, 1) - ULold = UL.data - for j = 1:n - if isa(UL, UnitLowerTriangular) - ULnew[j,j] = J.λ - 1 - else - ULnew[j,j] = J.λ - ULold[j,j] - end - for i = j + 1:n - ULnew[i,j] = -ULold[i,j] - end - end - return LowerTriangular(ULnew) -end - -function (+)(A::AbstractMatrix{TA}, J::UniformScaling{TJ}) where {TA,TJ} - n = checksquare(A) - B = similar(A, promote_type(TA,TJ)) - copy!(B,A) - @inbounds for i = 1:n - B[i,i] += J.λ - end - B -end - -function (-)(A::AbstractMatrix{TA}, J::UniformScaling{TJ}) where {TA,TJ<:Number} - n = checksquare(A) - B = similar(A, promote_type(TA,TJ)) - copy!(B, A) - @inbounds for i = 1:n - B[i,i] -= J.λ - end - B -end -function (-)(J::UniformScaling{TJ}, A::AbstractMatrix{TA}) where {TA,TJ<:Number} - n = checksquare(A) - B = convert(AbstractMatrix{promote_type(TJ,TA)}, -A) - @inbounds for j = 1:n - B[j,j] += J.λ - end - B -end - -inv(J::UniformScaling) = UniformScaling(inv(J.λ)) - -*(J1::UniformScaling, J2::UniformScaling) = UniformScaling(J1.λ*J2.λ) -*(B::BitArray{2}, J::UniformScaling) = *(Array(B), J::UniformScaling) -*(J::UniformScaling, B::BitArray{2}) = *(J::UniformScaling, Array(B)) -*(A::AbstractMatrix, J::UniformScaling) = A*J.λ -*(J::UniformScaling, A::AbstractVecOrMat) = J.λ*A -*(x::Number, J::UniformScaling) = UniformScaling(x*J.λ) -*(J::UniformScaling, x::Number) = UniformScaling(J.λ*x) - -/(J1::UniformScaling, J2::UniformScaling) = J2.λ == 0 ? throw(SingularException(1)) : UniformScaling(J1.λ/J2.λ) -/(J::UniformScaling, A::AbstractMatrix) = scale!(J.λ, inv(A)) -/(A::AbstractMatrix, J::UniformScaling) = J.λ == 0 ? throw(SingularException(1)) : A/J.λ - -/(J::UniformScaling, x::Number) = UniformScaling(J.λ/x) - -\(J1::UniformScaling, J2::UniformScaling) = J1.λ == 0 ? throw(SingularException(1)) : UniformScaling(J1.λ\J2.λ) -\(A::Union{Bidiagonal{T},AbstractTriangular{T}}, J::UniformScaling) where {T<:Number} = scale!(inv(A), J.λ) -\(J::UniformScaling, A::AbstractVecOrMat) = J.λ == 0 ? throw(SingularException(1)) : J.λ\A -\(A::AbstractMatrix, J::UniformScaling) = scale!(inv(A), J.λ) - -\(x::Number, J::UniformScaling) = UniformScaling(x\J.λ) - -broadcast(::typeof(*), x::Number,J::UniformScaling) = UniformScaling(x*J.λ) -broadcast(::typeof(*), J::UniformScaling,x::Number) = UniformScaling(J.λ*x) - -broadcast(::typeof(/), J::UniformScaling,x::Number) = UniformScaling(J.λ/x) - -==(J1::UniformScaling,J2::UniformScaling) = (J1.λ == J2.λ) - -function isapprox(J1::UniformScaling{T}, J2::UniformScaling{S}; - rtol::Real=Base.rtoldefault(T,S), atol::Real=0, nans::Bool=false) where {T<:Number,S<:Number} - isapprox(J1.λ, J2.λ, rtol=rtol, atol=atol, nans=nans) -end - -function copy!(A::AbstractMatrix, J::UniformScaling) - size(A,1)==size(A,2) || throw(DimensionMismatch("a UniformScaling can only be copied to a square matrix")) - fill!(A, 0) - λ = J.λ - for i = 1:size(A,1) - @inbounds A[i,i] = λ - end - return A -end - -function cond(J::UniformScaling{T}) where T - onereal = inv(one(real(J.λ))) - return J.λ ≠ zero(T) ? onereal : oftype(onereal, Inf) -end - -# promote_to_arrays(n,k, T, A...) promotes any UniformScaling matrices -# in A to matrices of type T and sizes given by n[k:end]. n is an array -# so that the same promotion code can be used for hvcat. We pass the type T -# so that we can re-use this code for sparse-matrix hcat etcetera. -promote_to_arrays_(n::Int, ::Type{Matrix}, J::UniformScaling{T}) where {T} = copy!(Matrix{T}(n,n), J) -promote_to_arrays_(n::Int, ::Type, A::AbstractVecOrMat) = A -promote_to_arrays(n,k, ::Type) = () -promote_to_arrays(n,k, ::Type{T}, A) where {T} = (promote_to_arrays_(n[k], T, A),) -promote_to_arrays(n,k, ::Type{T}, A, B) where {T} = - (promote_to_arrays_(n[k], T, A), promote_to_arrays_(n[k+1], T, B)) -promote_to_arrays(n,k, ::Type{T}, A, B, C) where {T} = - (promote_to_arrays_(n[k], T, A), promote_to_arrays_(n[k+1], T, B), promote_to_arrays_(n[k+2], T, C)) -promote_to_arrays(n,k, ::Type{T}, A, B, Cs...) where {T} = - (promote_to_arrays_(n[k], T, A), promote_to_arrays_(n[k+1], T, B), promote_to_arrays(n,k+2, T, Cs...)...) -promote_to_array_type(A::Tuple{Vararg{Union{AbstractVecOrMat,UniformScaling}}}) = Matrix - -for (f,dim,name) in ((:hcat,1,"rows"), (:vcat,2,"cols")) - @eval begin - function $f(A::Union{AbstractVecOrMat,UniformScaling}...) - n = 0 - for a in A - if !isa(a, UniformScaling) - na = size(a,$dim) - n > 0 && n != na && - throw(DimensionMismatch(string("number of ", $name, - " of each array must match (got ", n, " and ", na, ")"))) - n = na - end - end - n == 0 && throw(ArgumentError($("$f of only UniformScaling objects cannot determine the matrix size"))) - return $f(promote_to_arrays(fill(n,length(A)),1, promote_to_array_type(A), A...)...) - end - end -end - - -function hvcat(rows::Tuple{Vararg{Int}}, A::Union{AbstractVecOrMat,UniformScaling}...) - nr = length(rows) - sum(rows) == length(A) || throw(ArgumentError("mismatch between row sizes and number of arguments")) - n = zeros(Int, length(A)) - needcols = false # whether we also need to infer some sizes from the column count - j = 0 - for i = 1:nr # infer UniformScaling sizes from row counts, if possible: - ni = 0 # number of rows in this block-row - for k = 1:rows[i] - if !isa(A[j+k], UniformScaling) - na = size(A[j+k], 1) - ni > 0 && ni != na && - throw(DimensionMismatch("mismatch in number of rows")) - ni = na - end - end - if ni > 0 - for k = 1:rows[i] - n[j+k] = ni - end - else # row consisted only of UniformScaling objects - needcols = true - end - j += rows[i] - end - if needcols # some sizes still unknown, try to infer from column count - nc = j = 0 - for i = 1:nr - nci = 0 - rows[i] > 0 && n[j+1] == 0 && continue # column count unknown in this row - for k = 1:rows[i] - nci += isa(A[j+k], UniformScaling) ? n[j+k] : size(A[j+k], 2) - end - nc > 0 && nc != nci && throw(DimensionMismatch("mismatch in number of columns")) - nc = nci - j += rows[i] - end - nc == 0 && throw(ArgumentError("sizes of UniformScalings could not be inferred")) - j = 0 - for i = 1:nr - if rows[i] > 0 && n[j+1] == 0 # this row consists entirely of UniformScalings - nci = nc ÷ rows[i] - nci * rows[i] != nc && throw(DimensionMismatch("indivisible UniformScaling sizes")) - for k = 1:rows[i] - n[j+k] = nci - end - end - j += rows[i] - end - end - return hvcat(rows, promote_to_arrays(n,1, promote_to_array_type(A), A...)...) -end diff --git a/julia-0.6.3/share/julia/base/loading.jl b/julia-0.6.3/share/julia/base/loading.jl deleted file mode 100644 index 113b4e5..0000000 --- a/julia-0.6.3/share/julia/base/loading.jl +++ /dev/null @@ -1,832 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -# Base.require is the implementation for the `import` statement - -# Cross-platform case-sensitive path canonicalization - -if is_unix() && !is_apple() - # assume case-sensitive filesystems, don't have to do anything - isfile_casesensitive(path) = isfile(path) -elseif is_windows() - # GetLongPathName Win32 function returns the case-preserved filename on NTFS. - function isfile_casesensitive(path) - isfile(path) || return false # Fail fast - basename(Filesystem.longpath(path)) == basename(path) - end -elseif is_apple() - # HFS+ filesystem is case-preserving. The getattrlist API returns - # a case-preserved filename. In the rare event that HFS+ is operating - # in case-sensitive mode, this will still work but will be redundant. - - # Constants from - const ATRATTR_BIT_MAP_COUNT = 5 - const ATTR_CMN_NAME = 1 - const BITMAPCOUNT = 1 - const COMMONATTR = 5 - const FSOPT_NOFOLLOW = 1 # Don't follow symbolic links - - const attr_list = zeros(UInt8, 24) - attr_list[BITMAPCOUNT] = ATRATTR_BIT_MAP_COUNT - attr_list[COMMONATTR] = ATTR_CMN_NAME - - # This essentially corresponds to the following C code: - # attrlist attr_list; - # memset(&attr_list, 0, sizeof(attr_list)); - # attr_list.bitmapcount = ATTR_BIT_MAP_COUNT; - # attr_list.commonattr = ATTR_CMN_NAME; - # struct Buffer { - # u_int32_t total_length; - # u_int32_t filename_offset; - # u_int32_t filename_length; - # char filename[max_filename_length]; - # }; - # Buffer buf; - # getattrpath(path, &attr_list, &buf, sizeof(buf), FSOPT_NOFOLLOW); - function isfile_casesensitive(path) - isfile(path) || return false - path_basename = String(basename(path)) - local casepreserved_basename - const header_size = 12 - buf = Vector{UInt8}(length(path_basename) + header_size + 1) - while true - ret = ccall(:getattrlist, Cint, - (Cstring, Ptr{Void}, Ptr{Void}, Csize_t, Culong), - path, attr_list, buf, sizeof(buf), FSOPT_NOFOLLOW) - systemerror(:getattrlist, ret ≠ 0) - filename_length = unsafe_load( - convert(Ptr{UInt32}, pointer(buf) + 8)) - if (filename_length + header_size) > length(buf) - resize!(buf, filename_length + header_size) - continue - end - casepreserved_basename = - view(buf, (header_size+1):(header_size+filename_length-1)) - break - end - # Hack to compensate for inability to create a string from a subarray with no allocations. - Vector{UInt8}(path_basename) == casepreserved_basename && return true - - # If there is no match, it's possible that the file does exist but HFS+ - # performed unicode normalization. See https://developer.apple.com/library/mac/qa/qa1235/_index.html. - isascii(path_basename) && return false - Vector{UInt8}(normalize_string(path_basename, :NFD)) == casepreserved_basename - end -else - # Generic fallback that performs a slow directory listing. - function isfile_casesensitive(path) - isfile(path) || return false - dir, filename = splitdir(path) - any(readdir(dir) .== filename) - end -end - -function load_hook(prefix::String, name::String, ::Void) - name_jl = "$name.jl" - path = joinpath(prefix, name_jl) - isfile_casesensitive(path) && return abspath(path) - path = joinpath(prefix, name_jl, "src", name_jl) - isfile_casesensitive(path) && return abspath(path) - path = joinpath(prefix, name, "src", name_jl) - isfile_casesensitive(path) && return abspath(path) - return nothing -end -load_hook(prefix::String, name::String, path::String) = path -load_hook(prefix, name::String, ::Any) = - throw(ArgumentError("unrecognized custom loader in LOAD_PATH: $prefix")) - -_str(x::AbstractString) = String(x) -_str(x) = x - -# `wd` is a working directory to search. defaults to current working directory. -# if `wd === nothing`, no extra path is searched. -function find_in_path(name::String, wd::Union{Void,String}) - isabspath(name) && return name - base = name - if endswith(name,".jl") - base = name[1:end-3] - else - name = string(base,".jl") - end - if wd !== nothing - isfile_casesensitive(joinpath(wd,name)) && return joinpath(wd,name) - end - path = nothing - path = _str(load_hook(_str(Pkg.dir()), base, path)) - for dir in LOAD_PATH - path = _str(load_hook(_str(dir), base, path)) - end - return path -end -find_in_path(name::AbstractString, wd::AbstractString = pwd()) = - find_in_path(String(name), String(wd)) - -function find_in_node_path(name::String, srcpath, node::Int=1) - if myid() == node - return find_in_path(name, srcpath) - else - return remotecall_fetch(find_in_path, node, name, srcpath) - end -end - -function find_source_file(file::String) - (isabspath(file) || isfile(file)) && return file - file2 = find_in_path(file) - file2 !== nothing && return file2 - file2 = joinpath(JULIA_HOME, DATAROOTDIR, "julia", "base", file) - return isfile(file2) ? file2 : nothing -end - -function find_all_in_cache_path(mod::Symbol) - name = string(mod) - paths = String[] - for prefix in LOAD_CACHE_PATH - path = joinpath(prefix, name*".ji") - if isfile_casesensitive(path) - push!(paths, path) - end - end - return paths -end - -# these return either the array of modules loaded from the path / content given -# or an Exception that describes why it couldn't be loaded -function _include_from_serialized(content::Vector{UInt8}) - return ccall(:jl_restore_incremental_from_buf, Any, (Ptr{UInt8}, Int), content, sizeof(content)) -end -function _include_from_serialized(path::String) - return ccall(:jl_restore_incremental, Any, (Cstring,), path) -end - -# returns an array of modules loaded, or an Exception that describes why it failed -# and also attempts to load the same file across all nodes (if toplevel_node and myid() == master) -# and it reconnects the Base.Docs.META -function _require_from_serialized(node::Int, mod::Symbol, path_to_try::String, toplevel_load::Bool) - local restored = nothing - local content::Vector{UInt8} - if toplevel_load && myid() == 1 && nprocs() > 1 - # broadcast top-level import/using from node 1 (only) - if node == myid() - content = open(read, path_to_try) - else - content = remotecall_fetch(open, node, read, path_to_try) - end - restored = _include_from_serialized(content) - isa(restored, Exception) && return restored - - results = sizehint!(Vector{Tuple{Int,Any}}(), nprocs()) - @sync for p in procs() - if p != myid() - @async begin - result = remotecall_fetch(p) do - let m = try - _include_from_serialized(content) - catch ex - isa(ex, Exception) ? ex : ErrorException(string(ex)) - end - isa(m, Exception) ? m : nothing - end - end - push!(results, (p, result)) - end - end - end - for (id, m) in results - if m !== nothing - warn("Node state is inconsistent: node $id failed to load cache from $path_to_try. Got:") - warn(m, prefix="WARNING: ") - end - end - elseif node == myid() - restored = _include_from_serialized(path_to_try) - else - content = remotecall_fetch(open, node, read, path_to_try) - restored = _include_from_serialized(content) - end - - if !isa(restored, Exception) - for M in restored::Vector{Any} - if isdefined(M, Base.Docs.META) - push!(Base.Docs.modules, M) - end - end - end - return restored -end - -# returns `true` if require found a precompile cache for this mod, but couldn't load it -# returns `false` if the module isn't known to be precompilable -# returns the set of modules restored if the cache load succeeded -function _require_search_from_serialized(node::Int, mod::Symbol, sourcepath::String, toplevel_load::Bool) - if node == myid() - paths = find_all_in_cache_path(mod) - else - paths = @fetchfrom node find_all_in_cache_path(mod) - end - - for path_to_try in paths::Vector{String} - if node == myid() - if stale_cachefile(sourcepath, path_to_try) - continue - end - else - if @fetchfrom node stale_cachefile(sourcepath, path_to_try) - continue - end - end - restored = _require_from_serialized(node, mod, path_to_try, toplevel_load) - if isa(restored, Exception) - if isa(restored, ErrorException) && endswith(restored.msg, " uuid did not match cache file.") - # can't use this cache due to a module uuid mismatch, - # defer reporting error until after trying all of the possible matches - DEBUG_LOADING[] && info("JL_DEBUG_LOADING: Failed to load $path_to_try because $(restored.msg)") - continue - end - warn("Deserialization checks failed while attempting to load cache from $path_to_try.") - throw(restored) - else - return restored - end - end - return !isempty(paths) -end - -# this value is set by `require` based on whether JULIA_DEBUG_LOADING -# is presently defined as an environment variable -# and makes the logic in this file noisier about what it is doing and why -const DEBUG_LOADING = Ref(false) - -# to synchronize multiple tasks trying to import/using something -const package_locks = Dict{Symbol,Condition}() - -# to notify downstream consumers that a module was successfully loaded -# Callbacks take the form (mod::Symbol) -> nothing. -# WARNING: This is an experimental feature and might change later, without deprecation. -const package_callbacks = Any[] - -# used to optionally track dependencies when requiring a module: -const _concrete_dependencies = Any[] # these dependency versions are "set in stone", and the process should try to avoid invalidating them -const _require_dependencies = Any[] # a list of (path, mtime) tuples that are the file dependencies of the module currently being precompiled -const _track_dependencies = Ref(false) # set this to true to track the list of file dependencies -function _include_dependency(_path::AbstractString) - prev = source_path(nothing) - if prev === nothing - if myid() == 1 - path = abspath(_path) - else - path = joinpath(remotecall_fetch(abspath, 1, "."), _path) - end - else - path = joinpath(dirname(prev), _path) - end - if myid() == 1 && _track_dependencies[] - push!(_require_dependencies, (path, mtime(path))) - end - return path, prev -end - -""" - include_dependency(path::AbstractString) - -In a module, declare that the file specified by `path` (relative or absolute) is a -dependency for precompilation; that is, the module will need to be recompiled if this file -changes. - -This is only needed if your module depends on a file that is not used via `include`. It has -no effect outside of compilation. -""" -function include_dependency(path::AbstractString) - _include_dependency(path) - return nothing -end - -# We throw PrecompilableError(true) when a module wants to be precompiled but isn't, -# and PrecompilableError(false) when a module doesn't want to be precompiled but is -struct PrecompilableError <: Exception - isprecompilable::Bool -end -function show(io::IO, ex::PrecompilableError) - if ex.isprecompilable - print(io, "Declaring __precompile__(true) is only allowed in module files being imported.") - else - print(io, "Declaring __precompile__(false) is not allowed in files that are being precompiled.") - end -end -precompilableerror(ex::PrecompilableError, c) = ex.isprecompilable == c -precompilableerror(ex::WrappedException, c) = precompilableerror(ex.error, c) -precompilableerror(ex, c) = false - -# Call __precompile__ at the top of a file to force it to be precompiled (true), or -# to be prevent it from being precompiled (false). __precompile__(true) is -# ignored except within "require" call. -""" - __precompile__(isprecompilable::Bool=true) - -Specify whether the file calling this function is precompilable. If `isprecompilable` is -`true`, then `__precompile__` throws an exception when the file is loaded by -`using`/`import`/`require` *unless* the file is being precompiled, and in a module file it -causes the module to be automatically precompiled when it is imported. Typically, -`__precompile__()` should occur before the `module` declaration in the file, or better yet -`VERSION >= v"0.4" && __precompile__()` in order to be backward-compatible with Julia 0.3. - -If a module or file is *not* safely precompilable, it should call `__precompile__(false)` in -order to throw an error if Julia attempts to precompile it. - -`__precompile__()` should *not* be used in a module unless all of its dependencies are also -using `__precompile__()`. Failure to do so can result in a runtime error when loading the module. -""" -function __precompile__(isprecompilable::Bool=true) - if (myid() == 1 && - JLOptions().use_compilecache != 0 && - isprecompilable != (0 != ccall(:jl_generating_output, Cint, ())) && - !(isprecompilable && toplevel_load::Bool)) - throw(PrecompilableError(isprecompilable)) - end -end - -function require_modname(name::AbstractString) - # This function can be deleted when the deprecation for `require` - # is deleted. - # While we could also strip off the absolute path, the user may be - # deliberately directing to a different file than what got - # cached. So this takes a conservative approach. - if Bool(JLOptions().use_compilecache) - if endswith(name, ".jl") - tmp = name[1:end-3] - for prefix in LOAD_CACHE_PATH - path = joinpath(prefix, tmp*".ji") - if isfile(path) - return tmp - end - end - end - end - return name -end - -""" - reload(name::AbstractString) - -Force reloading of a package, even if it has been loaded before. This is intended for use -during package development as code is modified. -""" -function reload(name::AbstractString) - if isfile(name) || contains(name,Filesystem.path_separator) - # for reload("path/file.jl") just ask for include instead - error("use `include` instead of `reload` to load source files") - else - # reload("Package") is ok - require(Symbol(require_modname(name))) - end -end - -# require always works in Main scope and loads files from node 1 -toplevel_load = true - -""" - require(module::Symbol) - -This function is part of the implementation of `using` / `import`, if a module is not -already defined in `Main`. It can also be called directly to force reloading a module, -regardless of whether it has been loaded before (for example, when interactively developing -libraries). - -Loads a source file, in the context of the `Main` module, on every active node, searching -standard locations for files. `require` is considered a top-level operation, so it sets the -current `include` path but does not use it to search for files (see help for `include`). -This function is typically used to load library code, and is implicitly called by `using` to -load packages. - -When searching for files, `require` first looks for package code under `Pkg.dir()`, -then tries paths in the global array `LOAD_PATH`. `require` is case-sensitive on -all platforms, including those with case-insensitive filesystems like macOS and -Windows. -""" -function require(mod::Symbol) - _require(mod::Symbol) - # After successfully loading notify downstream consumers - for callback in package_callbacks - invokelatest(callback, mod) - end -end - -function _require(mod::Symbol) - # dependency-tracking is only used for one top-level include(path), - # and is not applied recursively to imported modules: - old_track_dependencies = _track_dependencies[] - _track_dependencies[] = false - DEBUG_LOADING[] = haskey(ENV, "JULIA_DEBUG_LOADING") - - global toplevel_load - loading = get(package_locks, mod, false) - if loading !== false - # load already in progress for this module - wait(loading) - return - end - package_locks[mod] = Condition() - - last = toplevel_load::Bool - try - toplevel_load = false - # perform the search operation to select the module file require intends to load - name = string(mod) - path = find_in_node_path(name, nothing, 1) - if path === nothing - throw(ArgumentError("Module $name not found in current path.\nRun `Pkg.add(\"$name\")` to install the $name package.")) - end - - # attempt to load the module file via the precompile cache locations - doneprecompile = false - if JLOptions().use_compilecache != 0 - doneprecompile = _require_search_from_serialized(1, mod, path, last) - if !isa(doneprecompile, Bool) - return # success - end - end - - # if the module being required was supposed to have a particular version - # but it was not handled by the precompile loader, complain - for (concrete_mod, concrete_uuid) in _concrete_dependencies - if mod === concrete_mod - warn("""Module $mod with uuid $concrete_uuid is missing from the cache. - This may mean module $mod does not support precompilation but is imported by a module that does.""") - if JLOptions().incremental != 0 - # during incremental precompilation, this should be fail-fast - throw(PrecompilableError(false)) - end - end - end - - if doneprecompile === true || JLOptions().incremental != 0 - # spawn off a new incremental pre-compile task from node 1 for recursive `require` calls - # or if the require search declared it was pre-compiled before (and therefore is expected to still be pre-compilable) - cachefile = compilecache(mod) - m = _require_from_serialized(1, mod, cachefile, last) - if isa(m, Exception) - warn("The call to compilecache failed to create a usable precompiled cache file for module $name. Got:") - warn(m, prefix="WARNING: ") - # fall-through, TODO: disable __precompile__(true) error so that the normal include will succeed - else - return # success - end - end - - # just load the file normally via include - # for unknown dependencies - try - if last && myid() == 1 && nprocs() > 1 - # include on node 1 first to check for PrecompilableErrors - eval(Main, :(Base.include_from_node1($path))) - - # broadcast top-level import/using from node 1 (only) - @sync begin - for p in filter(x -> x != 1, procs()) - @async remotecall_fetch(p) do - eval(Main, :(Base.include_from_node1($path); nothing)) - end - end - end - else - eval(Main, :(Base.include_from_node1($path))) - end - catch ex - if doneprecompile === true || JLOptions().use_compilecache == 0 || !precompilableerror(ex, true) - rethrow() # rethrow non-precompilable=true errors - end - # the file requested `__precompile__`, so try to build a cache file and use that - cachefile = compilecache(mod) - m = _require_from_serialized(1, mod, cachefile, last) - if isa(m, Exception) - warn(m, prefix="WARNING: ") - # TODO: disable __precompile__(true) error and do normal include instead of error - error("Module $mod declares __precompile__(true) but require failed to create a usable precompiled cache file.") - end - end - finally - toplevel_load = last - loading = pop!(package_locks, mod) - notify(loading, all=true) - _track_dependencies[] = old_track_dependencies - end - nothing -end - -# remote/parallel load - -""" - include_string(code::AbstractString, filename::AbstractString="string") - -Like `include`, except reads code from the given string rather than from a file. Since there -is no file path involved, no path processing or fetching from node 1 is done. -""" -include_string(txt::String, fname::String) = - ccall(:jl_load_file_string, Any, (Ptr{UInt8},Csize_t,Cstring), - txt, sizeof(txt), fname) - -include_string(txt::AbstractString, fname::AbstractString="string") = - include_string(String(txt), String(fname)) - -function source_path(default::Union{AbstractString,Void}="") - t = current_task() - while true - s = t.storage - if s !== nothing && haskey(s, :SOURCE_PATH) - return s[:SOURCE_PATH] - end - if t === t.parent - return default - end - t = t.parent - end -end - -function source_dir() - p = source_path(nothing) - p === nothing ? p : dirname(p) -end - -""" - @__FILE__ -> AbstractString - -`@__FILE__` expands to a string with the absolute file path of the file containing the -macro. Returns `nothing` if run from a REPL or an empty string if evaluated by -`julia -e `. Alternatively see [`PROGRAM_FILE`](@ref). -""" -macro __FILE__() source_path() end - -""" - @__DIR__ -> AbstractString - -`@__DIR__` expands to a string with the directory part of the absolute path of the file -containing the macro. Returns `nothing` if run from a REPL or an empty string if -evaluated by `julia -e `. -""" -macro __DIR__() source_dir() end - -include_from_node1(path::AbstractString) = include_from_node1(String(path)) -function include_from_node1(_path::String) - path, prev = _include_dependency(_path) - tls = task_local_storage() - tls[:SOURCE_PATH] = path - local result - try - if myid()==1 - # sleep a bit to process file requests from other nodes - nprocs()>1 && sleep(0.005) - result = Core.include(path) - nprocs()>1 && sleep(0.005) - else - result = include_string(remotecall_fetch(readstring, 1, path), path) - end - finally - if prev === nothing - delete!(tls, :SOURCE_PATH) - else - tls[:SOURCE_PATH] = prev - end - end - result -end - -""" - include(path::AbstractString) - -Evaluate the contents of the input source file in the current context. Returns the result -of the last evaluated expression of the input file. During including, a task-local include -path is set to the directory containing the file. Nested calls to `include` will search -relative to that path. All paths refer to files on node 1 when running in parallel, and -files will be fetched from node 1. This function is typically used to load source -interactively, or to combine files in packages that are broken into multiple source files. -""" -include # defined in sysimg.jl - -""" - evalfile(path::AbstractString, args::Vector{String}=String[]) - -Load the file using [`include`](@ref), evaluate all expressions, -and return the value of the last one. -""" -function evalfile(path::AbstractString, args::Vector{String}=String[]) - return eval(Module(:__anon__), - Expr(:toplevel, - :(const ARGS = $args), - :(eval(x) = Main.Core.eval(__anon__,x)), - :(eval(m,x) = Main.Core.eval(m,x)), - :(Main.Base.include($path)))) -end -evalfile(path::AbstractString, args::Vector) = evalfile(path, String[args...]) - -function create_expr_cache(input::String, output::String, concrete_deps::Vector{Any}) - rm(output, force=true) # Remove file if it exists - code_object = """ - while !eof(STDIN) - eval(Main, deserialize(STDIN)) - end - """ - io, pobj = open(pipeline(detach(`$(julia_cmd()) -O0 - --output-ji $output --output-incremental=yes - --startup-file=no --history-file=no - --color=$(have_color ? "yes" : "no") - --eval $code_object`), stderr=STDERR), - "w", STDOUT) - try - serialize(io, quote - empty!(Base.LOAD_PATH) - append!(Base.LOAD_PATH, $LOAD_PATH) - empty!(Base.LOAD_CACHE_PATH) - append!(Base.LOAD_CACHE_PATH, $LOAD_CACHE_PATH) - empty!(Base.DL_LOAD_PATH) - append!(Base.DL_LOAD_PATH, $DL_LOAD_PATH) - empty!(Base._concrete_dependencies) - append!(Base._concrete_dependencies, $concrete_deps) - Base._track_dependencies[] = true - end) - source = source_path(nothing) - if source !== nothing - serialize(io, quote - task_local_storage()[:SOURCE_PATH] = $(source) - end) - end - serialize(io, :(Base.include($(abspath(input))))) - if source !== nothing - serialize(io, :(delete!(task_local_storage(), :SOURCE_PATH))) - end - close(io) - wait(pobj) - return pobj - catch - kill(pobj) - close(io) - rethrow() - end -end - -compilecache(mod::Symbol) = compilecache(string(mod)) - -""" - Base.compilecache(module::String) - -Creates a precompiled cache file for -a module and all of its dependencies. -This can be used to reduce package load times. Cache files are stored in -`LOAD_CACHE_PATH[1]`, which defaults to `~/.julia/lib/VERSION`. See -[Module initialization and precompilation](@ref) -for important notes. -""" -function compilecache(name::String) - myid() == 1 || error("can only precompile from node 1") - # decide where to get the source file from - path = find_in_path(name, nothing) - path === nothing && throw(ArgumentError("$name not found in path")) - path = String(path) - # decide where to put the resulting cache file - cachepath = LOAD_CACHE_PATH[1] - if !isdir(cachepath) - mkpath(cachepath) - end - cachefile::String = abspath(cachepath, name*".ji") - # build up the list of modules that we want the precompile process to preserve - concrete_deps = copy(_concrete_dependencies) - for existing in names(Main) - if isdefined(Main, existing) - mod = getfield(Main, existing) - if isa(mod, Module) && !(mod === Main || mod === Core || mod === Base) - mod = mod::Module - if module_parent(mod) === Main && module_name(mod) === existing - push!(concrete_deps, (existing, module_uuid(mod))) - end - end - end - end - # run the expression and cache the result - if isinteractive() || DEBUG_LOADING[] - if isfile(cachefile) - info("Recompiling stale cache file $cachefile for module $name.") - else - info("Precompiling module $name.") - end - end - if !success(create_expr_cache(path, cachefile, concrete_deps)) - error("Failed to precompile $name to $cachefile.") - end - return cachefile -end - -module_uuid(m::Module) = ccall(:jl_module_uuid, UInt64, (Any,), m) - -isvalid_cache_header(f::IOStream) = 0 != ccall(:jl_read_verify_header, Cint, (Ptr{Void},), f.ios) - -function parse_cache_header(f::IO) - modules = Dict{Symbol,UInt64}() - while true - n = ntoh(read(f, Int32)) - n == 0 && break - sym = Symbol(read(f, n)) # module symbol - uuid = ntoh(read(f, UInt64)) # module UUID (mostly just a timestamp) - modules[sym] = uuid - end - totbytes = ntoh(read(f, Int64)) # total bytes for file dependencies - # read the list of files - files = Tuple{String,Float64}[] - while true - n = ntoh(read(f, Int32)) - n == 0 && break - totbytes -= 4 + n + 8 - @assert n >= 0 "EOF while reading cache header" # probably means this wasn't a valid file to be read by Base.parse_cache_header - push!(files, (String(read(f, n)), ntoh(read(f, Float64)))) - end - @assert totbytes == 4 "header of cache file appears to be corrupt" - # read the list of modules that are required to be present during loading - required_modules = Dict{Symbol,UInt64}() - while true - n = ntoh(read(f, Int32)) - n == 0 && break - sym = Symbol(read(f, n)) # module symbol - uuid = ntoh(read(f, UInt64)) # module UUID - required_modules[sym] = uuid - end - return modules, files, required_modules -end - -function parse_cache_header(cachefile::String) - io = open(cachefile, "r") - try - !isvalid_cache_header(io) && throw(ArgumentError("Invalid header in cache file $cachefile.")) - return parse_cache_header(io) - finally - close(io) - end -end - -function cache_dependencies(f::IO) - defs, files, modules = parse_cache_header(f) - return modules, files -end - -function cache_dependencies(cachefile::String) - io = open(cachefile, "r") - try - !isvalid_cache_header(io) && throw(ArgumentError("Invalid header in cache file $cachefile.")) - return cache_dependencies(io) - finally - close(io) - end -end - -function stale_cachefile(modpath::String, cachefile::String) - io = open(cachefile, "r") - try - if !isvalid_cache_header(io) - DEBUG_LOADING[] && info("JL_DEBUG_LOADING: Rejecting cache file $cachefile due to it containing an invalid cache header.") - return true # invalid cache file - end - modules, files, required_modules = parse_cache_header(io) - - # Check if transitive dependencies can be fullfilled - for mod in keys(required_modules) - if mod == :Main || mod == :Core || mod == :Base - continue - # Module is already loaded - elseif isbindingresolved(Main, mod) - continue - end - name = string(mod) - path = find_in_node_path(name, nothing, 1) - if path === nothing - return true # Won't be able to fullfill dependency - end - end - - # check if this file is going to provide one of our concrete dependencies - # or if it provides a version that conflicts with our concrete dependencies - # or neither - for (mod, uuid_req) in _concrete_dependencies - uuid = get(modules, mod, UInt64(0)) - if uuid !== UInt64(0) - if uuid === uuid_req - return false # this is the file we want - end - DEBUG_LOADING[] && info("JL_DEBUG_LOADING: Rejecting cache file $cachefile because it provides the wrong uuid (got $uuid) for $mod (want $uuid_req).") - return true # cachefile doesn't provide the required version of the dependency - end - end - - # now check if this file is fresh relative to its source files - if !samefile(files[1][1], modpath) - DEBUG_LOADING[] && info("JL_DEBUG_LOADING: Rejecting cache file $cachefile because it is for file $(files[1][1])) not file $modpath.") - return true # cache file was compiled from a different path - end - for (f, ftime_req) in files - # Issue #13606: compensate for Docker images rounding mtimes - # Issue #20837: compensate for GlusterFS truncating mtimes to microseconds - ftime = mtime(f) - if ftime != ftime_req && ftime != floor(ftime_req) && ftime != trunc(ftime_req, 6) - DEBUG_LOADING[] && info("JL_DEBUG_LOADING: Rejecting stale cache file $cachefile (mtime $ftime_req) because file $f (mtime $ftime) has changed.") - return true - end - end - return false # fresh cachefile - finally - close(io) - end -end diff --git a/julia-0.6.3/share/julia/base/lock.jl b/julia-0.6.3/share/julia/base/lock.jl deleted file mode 100644 index 533795a..0000000 --- a/julia-0.6.3/share/julia/base/lock.jl +++ /dev/null @@ -1,162 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -# Advisory reentrant lock -""" - ReentrantLock() - -Creates a reentrant lock for synchronizing Tasks. -The same task can acquire the lock as many times as required. -Each `lock` must be matched with an `unlock`. - -This lock is NOT threadsafe. See `Threads.Mutex` for a threadsafe lock. -""" -mutable struct ReentrantLock - locked_by::Nullable{Task} - cond_wait::Condition - reentrancy_cnt::Int - - ReentrantLock() = new(nothing, Condition(), 0) -end - -""" - islocked(the_lock) -> Status (Boolean) - -Check whether the lock is held by any task/thread. -This should not be used for synchronization (see instead `trylock`). -""" -function islocked(rl::ReentrantLock) - return rl.reentrancy_cnt != 0 -end - -""" - trylock(the_lock) -> Success (Boolean) - -Acquires the lock if it is available, -returning `true` if successful. -If the lock is already locked by a different task/thread, -returns `false`. - -Each successful `trylock` must be matched by an `unlock`. -""" -function trylock(rl::ReentrantLock) - t = current_task() - if rl.reentrancy_cnt == 0 - rl.locked_by = t - rl.reentrancy_cnt = 1 - return true - elseif t == get(rl.locked_by) - rl.reentrancy_cnt += 1 - return true - end - return false -end - -""" - lock(the_lock) - -Acquires the lock when it becomes available. -If the lock is already locked by a different task/thread, -it waits for it to become available. - -Each `lock` must be matched by an `unlock`. -""" -function lock(rl::ReentrantLock) - t = current_task() - while true - if rl.reentrancy_cnt == 0 - rl.locked_by = t - rl.reentrancy_cnt = 1 - return - elseif t == get(rl.locked_by) - rl.reentrancy_cnt += 1 - return - end - wait(rl.cond_wait) - end -end - -""" - unlock(the_lock) - -Releases ownership of the lock. - -If this is a recursive lock which has been acquired before, it -just decrements an internal counter and returns immediately. -""" -function unlock(rl::ReentrantLock) - if rl.reentrancy_cnt == 0 - error("unlock count must match lock count") - end - rl.reentrancy_cnt -= 1 - if rl.reentrancy_cnt == 0 - rl.locked_by = nothing - notify(rl.cond_wait) - end - return -end - -function lock(f, l) - lock(l) - try - return f() - finally - unlock(l) - end -end - -function trylock(f, l) - if trylock(l) - try - return f() - finally - unlock(l) - end - end - return false -end - -""" - Semaphore(sem_size) - -Creates a counting semaphore that allows at most `sem_size` -acquires to be in use at any time. -Each acquire must be mached with a release. - -This construct is NOT threadsafe. -""" -mutable struct Semaphore - sem_size::Int - curr_cnt::Int - cond_wait::Condition - Semaphore(sem_size) = sem_size > 0 ? new(sem_size, 0, Condition()) : throw(ArgumentError("Semaphore size must be > 0")) -end - -""" - acquire(s::Semaphore) - -Wait for one of the `sem_size` permits to be available, -blocking until one can be acquired. -""" -function acquire(s::Semaphore) - while true - if s.curr_cnt < s.sem_size - s.curr_cnt = s.curr_cnt + 1 - return - else - wait(s.cond_wait) - end - end -end - -""" - release(s::Semaphore) - -Return one permit to the pool, -possibly allowing another task to acquire it -and resume execution. -""" -function release(s::Semaphore) - @assert s.curr_cnt > 0 "release count must match acquire count" - s.curr_cnt -= 1 - notify(s.cond_wait; all=false) -end diff --git a/julia-0.6.3/share/julia/base/locks.jl b/julia-0.6.3/share/julia/base/locks.jl deleted file mode 100644 index e674d5d..0000000 --- a/julia-0.6.3/share/julia/base/locks.jl +++ /dev/null @@ -1,238 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -import Base: _uv_hook_close, unsafe_convert, - lock, trylock, unlock, islocked - -export SpinLock, RecursiveSpinLock, Mutex - - -########################################## -# Atomic Locks -########################################## - -""" - AbstractLock - -Abstract supertype describing types that -implement the thread-safe synchronization primitives: -`lock`, `trylock`, `unlock`, and `islocked` -""" -abstract type AbstractLock end - -# Test-and-test-and-set spin locks are quickest up to about 30ish -# contending threads. If you have more contention than that, perhaps -# a lock is the wrong way to synchronize. -""" - TatasLock() - -See SpinLock. -""" -struct TatasLock <: AbstractLock - handle::Atomic{Int} - TatasLock() = new(Atomic{Int}(0)) -end - -""" - SpinLock() - -Creates a non-reentrant lock. -Recursive use will result in a deadlock. -Each `lock` must be matched with an `unlock`. - -Test-and-test-and-set spin locks are quickest up to about 30ish -contending threads. If you have more contention than that, perhaps -a lock is the wrong way to synchronize. - -See also RecursiveSpinLock for a version that permits recursion. - -See also Mutex for a more efficient version on one core or if the lock may be held for a considerable length of time. -""" -const SpinLock = TatasLock - -function lock(l::TatasLock) - while true - if l.handle[] == 0 - p = atomic_xchg!(l.handle, 1) - if p == 0 - return - end - end - ccall(:jl_cpu_pause, Void, ()) - # Temporary solution before we have gc transition support in codegen. - ccall(:jl_gc_safepoint, Void, ()) - end -end - -function trylock(l::TatasLock) - if l.handle[] == 0 - return atomic_xchg!(l.handle, 1) == 0 - end - return false -end - -function unlock(l::TatasLock) - l.handle[] = 0 - ccall(:jl_cpu_wake, Void, ()) - return -end - -function islocked(l::TatasLock) - return l.handle[] != 0 -end - - -""" - RecursiveTatasLock() - -See RecursiveSpinLock. -""" -struct RecursiveTatasLock <: AbstractLock - ownertid::Atomic{Int16} - handle::Atomic{Int} - RecursiveTatasLock() = new(Atomic{Int16}(0), Atomic{Int}(0)) -end - -""" - RecursiveSpinLock() - -Creates a reentrant lock. -The same thread can acquire the lock as many times as required. -Each `lock` must be matched with an `unlock`. - -See also SpinLock for a slightly faster version. - -See also Mutex for a more efficient version on one core or if the lock may be held for a considerable length of time. -""" -const RecursiveSpinLock = RecursiveTatasLock - -function lock(l::RecursiveTatasLock) - if l.ownertid[] == threadid() - l.handle[] += 1 - return - end - while true - if l.handle[] == 0 - if atomic_cas!(l.handle, 0, 1) == 0 - l.ownertid[] = threadid() - return - end - end - ccall(:jl_cpu_pause, Void, ()) - # Temporary solution before we have gc transition support in codegen. - ccall(:jl_gc_safepoint, Void, ()) - end -end - -function trylock(l::RecursiveTatasLock) - if l.ownertid[] == threadid() - l.handle[] += 1 - return true - end - if l.handle[] == 0 - if atomic_cas!(l.handle, 0, 1) == 0 - l.ownertid[] = threadid() - return true - end - return false - end - return false -end - -function unlock(l::RecursiveTatasLock) - @assert(l.ownertid[] == threadid(), "unlock from wrong thread") - @assert(l.handle[] != 0, "unlock count must match lock count") - if l.handle[] == 1 - l.ownertid[] = 0 - l.handle[] = 0 - ccall(:jl_cpu_wake, Void, ()) - else - l.handle[] -= 1 - end - return -end - -function islocked(l::RecursiveTatasLock) - return l.handle[] != 0 -end - - -########################################## -# System Mutexes -########################################## - -# These are mutexes from libuv. We're doing some error checking (and -# paying for it in overhead), but regardless, in some situations, -# passing a bad parameter will cause an abort. - -# TODO: how defensive to get, and how to turn it off? -# TODO: how to catch an abort? - -const UV_MUTEX_SIZE = ccall(:jl_sizeof_uv_mutex, Cint, ()) - -""" - Mutex() - -These are standard system mutexes for locking critical sections of logic. - -On Windows, this is a critical section object, -on pthreads, this is a `pthread_mutex_t`. - -See also SpinLock for a lighter-weight lock. -""" -mutable struct Mutex <: AbstractLock - ownertid::Int16 - handle::Ptr{Void} - function Mutex() - m = new(zero(Int16), Libc.malloc(UV_MUTEX_SIZE)) - ccall(:uv_mutex_init, Void, (Ptr{Void},), m.handle) - finalizer(m, _uv_hook_close) - return m - end -end - -unsafe_convert(::Type{Ptr{Void}}, m::Mutex) = m.handle - -function _uv_hook_close(x::Mutex) - h = x.handle - if h != C_NULL - x.handle = C_NULL - ccall(:uv_mutex_destroy, Void, (Ptr{Void},), h) - Libc.free(h) - nothing - end -end - -function lock(m::Mutex) - if m.ownertid == threadid() - return - end - # Temporary solution before we have gc transition support in codegen. - # This could mess up gc state when we add codegen support. - gc_state = ccall(:jl_gc_safe_enter, Int8, ()) - ccall(:uv_mutex_lock, Void, (Ptr{Void},), m) - ccall(:jl_gc_safe_leave, Void, (Int8,), gc_state) - m.ownertid = threadid() - return -end - -function trylock(m::Mutex) - if m.ownertid == threadid() - return true - end - r = ccall(:uv_mutex_trylock, Cint, (Ptr{Void},), m) - if r == 0 - m.ownertid = threadid() - end - return r == 0 -end - -function unlock(m::Mutex) - @assert(m.ownertid == threadid(), "unlock from wrong thread") - m.ownertid = 0 - ccall(:uv_mutex_unlock, Void, (Ptr{Void},), m) - return -end - -function islocked(m::Mutex) - return m.ownertid != 0 -end diff --git a/julia-0.6.3/share/julia/base/markdown/Common/Common.jl b/julia-0.6.3/share/julia/base/markdown/Common/Common.jl deleted file mode 100644 index 10e4e7b..0000000 --- a/julia-0.6.3/share/julia/base/markdown/Common/Common.jl +++ /dev/null @@ -1,11 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -include("block.jl") -include("inline.jl") - -@flavor common [list, indentcode, blockquote, admonition, footnote, hashheader, horizontalrule, - paragraph, - - linebreak, escapes, inline_code, - asterisk_bold, asterisk_italic, image, footnote_link, link, autolink] - diff --git a/julia-0.6.3/share/julia/base/markdown/Common/block.jl b/julia-0.6.3/share/julia/base/markdown/Common/block.jl deleted file mode 100644 index a0c4a09..0000000 --- a/julia-0.6.3/share/julia/base/markdown/Common/block.jl +++ /dev/null @@ -1,356 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -# –––––––––– -# Paragraphs -# –––––––––– - -mutable struct Paragraph - content -end - -Paragraph() = Paragraph([]) - -function paragraph(stream::IO, md::MD) - buffer = IOBuffer() - p = Paragraph() - push!(md, p) - skipwhitespace(stream) - prev_char = '\n' - while !eof(stream) - char = read(stream, Char) - if char == '\n' || char == '\r' - char == '\r' && !eof(stream) && Char(peek(stream)) == '\n' && read(stream, Char) - if prev_char == '\\' - write(buffer, '\n') - elseif blankline(stream) || parse(stream, md, breaking = true) - break - else - write(buffer, ' ') - end - else - write(buffer, char) - end - prev_char = char - end - p.content = parseinline(seek(buffer, 0), md) - return true -end - -# ––––––– -# Headers -# ––––––– - -mutable struct Header{level} - text -end - -Header(s, level::Int) = Header{level}(s) -Header(s) = Header(s, 1) - -@breaking true -> -function hashheader(stream::IO, md::MD) - withstream(stream) do - eatindent(stream) || return false - level = 0 - while startswith(stream, '#') level += 1 end - level < 1 || level > 6 && return false - - c = ' ' - # Allow empty headers, but require a space - !eof(stream) && (c = read(stream, Char); !(c in " \n")) && - return false - - if c != '\n' # Empty header - h = strip(readline(stream)) - h = match(r"(.*?)( +#+)?$", h).captures[1] - buffer = IOBuffer() - print(buffer, h) - push!(md.content, Header(parseinline(seek(buffer, 0), md), level)) - else - push!(md.content, Header("", level)) - end - return true - end -end - -function setextheader(stream::IO, md::MD) - withstream(stream) do - eatindent(stream) || return false - header = strip(readline(stream)) - isempty(header) && return false - - eatindent(stream) || return false - underline = strip(readline(stream)) - length(underline) < 3 && return false - u = underline[1] - u in "-=" || return false - all(c -> c == u, underline) || return false - level = (u == '=') ? 1 : 2 - - push!(md.content, Header(parseinline(header, md), level)) - return true - end -end - -# –––– -# Code -# –––– - -mutable struct Code - language::String - code::String -end - -Code(code) = Code("", code) - -function indentcode(stream::IO, block::MD) - withstream(stream) do - buffer = IOBuffer() - while !eof(stream) - if startswith(stream, " ") || startswith(stream, "\t") - write(buffer, readline(stream, chomp=false)) - elseif blankline(stream) - write(buffer, '\n') - else - break - end - end - code = String(take!(buffer)) - !isempty(code) && (push!(block, Code(rstrip(code))); return true) - return false - end -end - -# -------- -# Footnote -# -------- - -mutable struct Footnote - id::String - text -end - -function footnote(stream::IO, block::MD) - withstream(stream) do - regex = r"^\[\^(\w+)\]:" - str = startswith(stream, regex) - if isempty(str) - return false - else - ref = match(regex, str).captures[1] - buffer = IOBuffer() - write(buffer, readline(stream, chomp=false)) - while !eof(stream) - if startswith(stream, " ") - write(buffer, readline(stream, chomp=false)) - elseif blankline(stream) - write(buffer, '\n') - else - break - end - end - content = parse(seekstart(buffer)).content - push!(block, Footnote(ref, content)) - return true - end - end -end - -# –––––– -# Quotes -# –––––– - -mutable struct BlockQuote - content -end - -BlockQuote() = BlockQuote([]) - -# TODO: Laziness -@breaking true -> -function blockquote(stream::IO, block::MD) - withstream(stream) do - buffer = IOBuffer() - empty = true - while eatindent(stream) && startswith(stream, '>') - startswith(stream, " ") - write(buffer, readline(stream, chomp=false)) - empty = false - end - empty && return false - - md = String(take!(buffer)) - push!(block, BlockQuote(parse(md, flavor = config(block)).content)) - return true - end -end - -# ----------- -# Admonitions -# ----------- - -mutable struct Admonition - category::String - title::String - content::Vector -end - -@breaking true -> -function admonition(stream::IO, block::MD) - withstream(stream) do - # Admonition syntax: - # - # !!! category "optional explicit title within double quotes" - # Any number of other indented markdown elements. - # - # This is the second paragraph. - # - startswith(stream, "!!! ") || return false - # Extract the category of admonition and its title: - category, title = - let untitled = r"^([a-z]+)$", # !!! - titled = r"^([a-z]+) \"(.*)\"$", # !!! "" - line = strip(readline(stream)) - if ismatch(untitled, line) - m = match(untitled, line) - # When no title is provided we use CATEGORY_NAME, capitalising it. - m.captures[1], ucfirst(m.captures[1]) - elseif ismatch(titled, line) - m = match(titled, line) - # To have a blank TITLE provide an explicit empty string as TITLE. - m.captures[1], m.captures[2] - else - # Admonition header is invalid so we give up parsing here and move - # on to the next parser. - return false - end - end - # Consume the following indented (4 spaces) block. - buffer = IOBuffer() - while !eof(stream) - if startswith(stream, " ") - write(buffer, readline(stream, chomp=false)) - elseif blankline(stream) - write(buffer, '\n') - else - break - end - end - # Parse the nested block as markdown and create a new Admonition block. - nested = parse(String(take!(buffer)), flavor = config(block)) - push!(block, Admonition(category, title, nested.content)) - return true - end -end - -# ––––– -# Lists -# ––––– - -mutable struct List - items::Vector{Any} - ordered::Int # `-1` is unordered, `>= 0` is ordered. - - List(x::AbstractVector, b::Integer) = new(x, b) - List(x::AbstractVector) = new(x, -1) - List(b::Integer) = new(Any[], b) -end - -List(xs...) = List(vcat(xs...)) - -isordered(list::List) = list.ordered >= 0 - -const BULLETS = r"^ {0,3}(\*|\+|-)( |$)" -const NUM_OR_BULLETS = r"^ {0,3}(\*|\+|-|\d+(\.|\)))( |$)" - -@breaking true -> -function list(stream::IO, block::MD) - withstream(stream) do - bullet = startswith(stream, NUM_OR_BULLETS; eat = false) - indent = isempty(bullet) ? (return false) : length(bullet) - # Calculate the starting number and regex to use for bullet matching. - initial, regex = - if ismatch(BULLETS, bullet) - # An unordered list. Use `-1` to flag the list as unordered. - -1, BULLETS - elseif ismatch(r"^ {0,3}\d+(\.|\))( |$)", bullet) - # An ordered list. Either with `1. ` or `1) ` style numbering. - r = contains(bullet, ".") ? r"^ {0,3}(\d+)\.( |$)" : r"^ {0,3}(\d+)\)( |$)" - Base.parse(Int, match(r, bullet).captures[1]), r - else - # Failed to match any bullets. This branch shouldn't actually be needed - # since the `NUM_OR_BULLETS` regex should cover this, but we include it - # simply for thoroughness. - return false - end - - # Initialise the empty list object: either ordered or unordered. - list = List(initial) - - buffer = IOBuffer() # For capturing nested text for recursive parsing. - newline = false # For checking if we have two consecutive newlines: end of list. - count = 0 # Count of list items. Used to check if we need to push remaining - # content in `buffer` after leaving the `while` loop. - while !eof(stream) - if startswith(stream, "\n") - if newline - # Double newline ends the current list. - pushitem!(list, buffer) - break - else - newline = true - println(buffer) - end - else - newline = false - if startswith(stream, " "^indent) - # Indented text that is part of the current list item. - print(buffer, readline(stream, chomp=false)) - else - matched = startswith(stream, regex) - if isempty(matched) - # Unindented text meaning we have left the current list. - pushitem!(list, buffer) - break - else - # Start of a new list item. - count += 1 - count > 1 && pushitem!(list, buffer) - print(buffer, readline(stream, chomp=false)) - end - end - end - end - count == length(list.items) || pushitem!(list, buffer) - push!(block, list) - return true - end -end -pushitem!(list, buffer) = push!(list.items, parse(String(take!(buffer))).content) - -# –––––––––––––– -# HorizontalRule -# –––––––––––––– - -mutable struct HorizontalRule -end - -function horizontalrule(stream::IO, block::MD) - withstream(stream) do - n, rule = 0, ' ' - while !eof(stream) - char = read(stream, Char) - char == '\n' && break - isspace(char) && continue - if n==0 || char==rule - rule = char - n += 1 - else - return false - end - end - is_hr = (n ≥ 3 && rule in "*-") - is_hr && push!(block, HorizontalRule()) - return is_hr - end -end diff --git a/julia-0.6.3/share/julia/base/markdown/Common/inline.jl b/julia-0.6.3/share/julia/base/markdown/Common/inline.jl deleted file mode 100644 index 276504c..0000000 --- a/julia-0.6.3/share/julia/base/markdown/Common/inline.jl +++ /dev/null @@ -1,175 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -# –––––––– -# Emphasis -# –––––––– - -mutable struct Italic - text -end - -@trigger '*' -> -function asterisk_italic(stream::IO, md::MD) - result = parse_inline_wrapper(stream, "*") - return result === nothing ? nothing : Italic(parseinline(result, md)) -end - -mutable struct Bold - text -end - -@trigger '*' -> -function asterisk_bold(stream::IO, md::MD) - result = parse_inline_wrapper(stream, "**") - return result === nothing ? nothing : Bold(parseinline(result, md)) -end - -# –––– -# Code -# –––– - -@trigger '`' -> -function inline_code(stream::IO, md::MD) - withstream(stream) do - ticks = startswith(stream, r"^(`+)") - result = readuntil(stream, ticks) - if result === nothing - nothing - else - result = strip(result) - # An odd number of backticks wrapping the text will produce a `Code` node, while - # an even number will result in a `LaTeX` node. This allows for arbitary - # backtick combinations to be embedded inside the resulting node, i.e. - # - # `a`, ``a``, `` `a` ``, ``` ``a`` ```, ``` `a` ```, etc. - # ^ ^ ^ ^ ^ - # C L L C C with C=Code and L=LaTeX. - # - isodd(length(ticks)) ? Code(result) : LaTeX(result) - end - end -end - -# –––––––––––––– -# Images & Links -# –––––––––––––– - -mutable struct Image - url::String - alt::String -end - -@trigger '!' -> -function image(stream::IO, md::MD) - withstream(stream) do - startswith(stream, "![") || return - alt = readuntil(stream, ']', match = '[') - alt ≡ nothing && return - skipwhitespace(stream) - startswith(stream, '(') || return - url = readuntil(stream, ')', match = '(') - url ≡ nothing && return - return Image(url, alt) - end -end - -mutable struct Link - text - url::String -end - -@trigger '[' -> -function link(stream::IO, md::MD) - withstream(stream) do - startswith(stream, '[') || return - text = readuntil(stream, ']', match = '[') - text ≡ nothing && return - skipwhitespace(stream) - startswith(stream, '(') || return - url = readuntil(stream, ')', match = '(') - url ≡ nothing && return - return Link(parseinline(text, md), url) - end -end - -@trigger '[' -> -function footnote_link(stream::IO, md::MD) - withstream(stream) do - regex = r"^\[\^(\w+)\]" - str = startswith(stream, regex) - if isempty(str) - return - else - ref = match(regex, str).captures[1] - return Footnote(ref, nothing) - end - end -end - -@trigger '<' -> -function autolink(stream::IO, md::MD) - withstream(stream) do - startswith(stream, '<') || return - url = readuntil(stream, '>') - url ≡ nothing && return - _is_link(url) && return Link(url, url) - _is_mailto(url) && return Link(url, url) - return - end -end - -# This list is taken from the commonmark spec -# http://spec.commonmark.org/0.19/#absolute-uri -const _allowable_schemes = Set(split("coap doi javascript aaa aaas about acap cap cid crid data dav dict dns file ftp geo go gopher h323 http https iax icap im imap info ipp iris iris.beep iris.xpc iris.xpcs iris.lwz ldap mailto mid msrp msrps mtqp mupdate news nfs ni nih nntp opaquelocktoken pop pres rtsp service session shttp sieve sip sips sms snmp,soap.beep soap.beeps tag tel telnet tftp thismessage tn3270 tip tv urn vemmi ws wss xcon xcon-userid xmlrpc.beep xmlrpc.beeps xmpp z39.50r z39.50s -adiumxtra afp afs aim apt,attachment aw beshare bitcoin bolo callto chrome,chrome-extension com-eventbrite-attendee content cvs,dlna-playsingle dlna-playcontainer dtn dvb ed2k facetime feed finger fish gg git gizmoproject gtalk hcp icon ipn irc irc6 ircs itms jar jms keyparc lastfm ldaps magnet maps market,message mms ms-help msnim mumble mvn notes oid palm paparazzi platform proxy psyc query res resource rmi rsync rtmp secondlife sftp sgn skype smb soldat spotify ssh steam svn teamspeak -things udp unreal ut2004 ventrilo view-source webcal wtai wyciwyg xfire xri ymsgr")) - -function _is_link(s::AbstractString) - '<' in s && return false - - m = match(r"^(.*)://(\S+?)(:\S*)?$", s) - m ≡ nothing && return false - scheme = lowercase(m.captures[1]) - return scheme in _allowable_schemes -end - -# non-normative regex from the HTML5 spec -const _email_regex = r"^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$" - -function _is_mailto(s::AbstractString) - length(s) < 6 && return false - # slicing strings is a bit risky, but this equality check is safe - lowercase(s[1:6]) == "mailto:" || return false - return ismatch(_email_regex, s[6:end]) -end - -# ––––––––––– -# Punctuation -# ––––––––––– - -mutable struct LineBreak end - -@trigger '\\' -> -function linebreak(stream::IO, md::MD) - if startswith(stream, "\\\n") - return LineBreak() - end -end - -@trigger '-' -> -function en_dash(stream::IO, md::MD) - if startswith(stream, "--") - return "–" - end -end - -const escape_chars = "\\`*_#+-.!{}[]()\$" - -@trigger '\\' -> -function escapes(stream::IO, md::MD) - withstream(stream) do - if startswith(stream, "\\") && !eof(stream) && (c = read(stream, Char)) in escape_chars - return string(c) - end - end -end diff --git a/julia-0.6.3/share/julia/base/markdown/GitHub/GitHub.jl b/julia-0.6.3/share/julia/base/markdown/GitHub/GitHub.jl deleted file mode 100644 index ae2cfd1..0000000 --- a/julia-0.6.3/share/julia/base/markdown/GitHub/GitHub.jl +++ /dev/null @@ -1,66 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -include("table.jl") - -@breaking true -> -function fencedcode(stream::IO, block::MD) - withstream(stream) do - startswith(stream, "~~~", padding = true) || startswith(stream, "```", padding = true) || return false - skip(stream, -1) - ch = read(stream, Char) - trailing = strip(readline(stream)) - flavor = lstrip(trailing, ch) - n = 3 + length(trailing) - length(flavor) - - # inline code block - ch in flavor && return false - - buffer = IOBuffer() - while !eof(stream) - line_start = position(stream) - if startswith(stream, string(ch) ^ n) - if !startswith(stream, string(ch)) - if flavor == "math" - push!(block, LaTeX(String(take!(buffer)) |> chomp)) - else - push!(block, Code(flavor, String(take!(buffer)) |> chomp)) - end - return true - else - seek(stream, line_start) - end - end - write(buffer, readline(stream, chomp=false)) - end - return false - end -end - -function github_paragraph(stream::IO, md::MD) - skipwhitespace(stream) - buffer = IOBuffer() - p = Paragraph() - push!(md, p) - while !eof(stream) - char = read(stream, Char) - if char == '\n' - eof(stream) && break - if blankline(stream) || parse(stream, md, breaking = true) - break - else - write(buffer, '\n') - end - else - write(buffer, char) - end - end - p.content = parseinline(seek(buffer, 0), md) - return true -end - -@flavor github [list, indentcode, blockquote, admonition, footnote, fencedcode, hashheader, - github_table, github_paragraph, - - linebreak, escapes, en_dash, inline_code, asterisk_bold, - asterisk_italic, image, footnote_link, link, autolink] - diff --git a/julia-0.6.3/share/julia/base/markdown/GitHub/table.jl b/julia-0.6.3/share/julia/base/markdown/GitHub/table.jl deleted file mode 100644 index a8313e3..0000000 --- a/julia-0.6.3/share/julia/base/markdown/GitHub/table.jl +++ /dev/null @@ -1,168 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -mutable struct Table - rows::Vector{Vector{Any}} - align::Vector{Symbol} -end - -function parserow(stream::IO) - withstream(stream) do - line = readline(stream) - row = split(line, r"(?<!\\)\|") - length(row) == 1 && return - isempty(row[1]) && shift!(row) - map!(x -> strip(replace(x, "\\|", "|")), row, row) - isempty(row[end]) && pop!(row) - return row - end -end - -function rowlength!(row, len) - while length(row) < len push!(row, "") end - while length(row) > len pop!(row) end - return row -end - -const default_align = :r - -function parsealign(row) - align = Symbol[] - for s in row - (length(s) ≥ 3 && s ⊆ Set("-:")) || return - push!(align, - s[1] == ':' ? (s[end] == ':' ? :c : :l) : - s[end] == ':' ? :r : - default_align) - end - return align -end - -function github_table(stream::IO, md::MD) - withstream(stream) do - skipblank(stream) - rows = [] - cols = 0 - align = nothing - while (row = parserow(stream)) !== nothing - if length(rows) == 0 - isempty(row[1]) && return false - cols = length(row) - end - if align === nothing && length(rows) == 1 # Must have a --- row - align = parsealign(row) - (align === nothing || length(align) != cols) && return false - else - push!(rows, map(x -> parseinline(x, md), rowlength!(row, cols))) - end - end - length(rows) <= 1 && return false - push!(md, Table(rows, align)) - return true - end -end - -function html(io::IO, md::Table) - withtag(io, :table) do - for (i, row) in enumerate(md.rows) - withtag(io, :tr) do - for c in md.rows[i] - withtag(io, i == 1 ? :th : :td) do - htmlinline(io, c) - end - end - end - end - end -end - -mapmap(f, xss) = map(xs->map(f, xs), xss) - -colwidths(rows; len = length, min = 0) = - reduce((x,y) -> max.(x,y), [min; convert(Vector{Vector{Int}}, mapmap(len, rows))]) - -padding(width, twidth, a) = - a == :l ? (0, twidth - width) : - a == :r ? (twidth - width, 0) : - a == :c ? (floor(Int, (twidth-width)/2), ceil(Int, (twidth-width)/2)) : - error("Invalid alignment $a") - -function padcells!(rows, align; len = length, min = 0) - widths = colwidths(rows, len = len, min = min) - for i = 1:length(rows), j = indices(rows[1],1) - cell = rows[i][j] - lpad, rpad = padding(len(cell), widths[j], align[j]) - rows[i][j] = " "^lpad * cell * " "^rpad - end - return rows -end - -_dash(width, align) = - align == :l ? ":" * "-"^width * " " : - align == :r ? " " * "-"^width * ":" : - align == :c ? ":" * "-"^width * ":" : - throw(ArgumentError("Invalid alignment $align")) - -function plain(io::IO, md::Table) - cells = mapmap(md.rows) do each - replace(plaininline(each), "|", "\\|") - end - padcells!(cells, md.align, len = length, min = 3) - for i = indices(cells,1) - print(io, "| ") - join(io, cells[i], " | ") - println(io, " |") - if i == 1 - print(io, "|") - join(io, [_dash(length(cells[i][j]), md.align[j]) for j = indices(cells[1],1)], "|") - println(io, "|") - end - end -end - -function rst(io::IO, md::Table) - cells = mapmap(rstinline, md.rows) - padcells!(cells, md.align, len = length, min = 3) - single = ["-"^length(c) for c in cells[1]] - double = ["="^length(c) for c in cells[1]] - function print_row(row, row_sep, col_sep) - print(io, col_sep, row_sep) - join(io, row, string(row_sep, col_sep, row_sep)) - println(io, row_sep, col_sep) - end - print_row(single, '-', '+') - for i = 1:length(cells) - print_row(cells[i], ' ', '|') - i ≡ 1 ? print_row(double, '=', '+') : - print_row(single, '-', '+') - end -end - -function term(io::IO, md::Table, columns) - cells = mapmap(terminline, md.rows) - padcells!(cells, md.align, len = ansi_length) - for i = 1:length(cells) - join(io, cells[i], " ") - println(io) - if i == 1 - join(io, ["–"^ansi_length(cells[i][j]) for j = 1:length(cells[1])], " ") - println(io) - end - end -end - -function latex(io::IO, md::Table) - wrapblock(io, "tabular") do - align = md.align - println(io, "{$(join(align, " | "))}") - for (i, row) in enumerate(md.rows) - for (j, cell) in enumerate(row) - j != 1 && print(io, " & ") - latexinline(io, cell) - end - println(io, " \\\\") - if i == 1 - println("\\hline") - end - end - end -end diff --git a/julia-0.6.3/share/julia/base/markdown/IPython/IPython.jl b/julia-0.6.3/share/julia/base/markdown/IPython/IPython.jl deleted file mode 100644 index 665c45b..0000000 --- a/julia-0.6.3/share/julia/base/markdown/IPython/IPython.jl +++ /dev/null @@ -1,35 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -mutable struct LaTeX - formula::String -end - -@trigger '$' -> -function tex(stream::IO, md::MD) - result = parse_inline_wrapper(stream, "\$", rep = true) - return result === nothing ? nothing : LaTeX(result) -end - -function blocktex(stream::IO, md::MD) - withstream(stream) do - ex = tex(stream, md) - if ex ≡ nothing - return false - else - push!(md, ex) - return true - end - end -end - -show(io::IO, tex::LaTeX) = - print(io, '$', tex.formula, '$') - -latex(io::IO, tex::LaTeX) = - println(io, "\$\$", tex.formula, "\$\$") - -latexinline(io::IO, tex::LaTeX) = - print(io, '$', tex.formula, '$') - -term(io::IO, tex::LaTeX, cols) = println_with_format(:magenta, io, tex.formula) -terminline(io::IO, tex::LaTeX) = print_with_format(:magenta, io, tex.formula) diff --git a/julia-0.6.3/share/julia/base/markdown/Julia/Julia.jl b/julia-0.6.3/share/julia/base/markdown/Julia/Julia.jl deleted file mode 100644 index abc4b84..0000000 --- a/julia-0.6.3/share/julia/base/markdown/Julia/Julia.jl +++ /dev/null @@ -1,15 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -# This file contains markdown extensions designed to make documenting -# Julia easy peasy. -# -# We start by borrowing GitHub's `fencedcode` extension – more to follow. - -include("interp.jl") - -@flavor julia [blocktex, blockinterp, hashheader, list, indentcode, fencedcode, - blockquote, admonition, footnote, github_table, horizontalrule, setextheader, paragraph, - - linebreak, escapes, tex, interp, en_dash, inline_code, - asterisk_bold, asterisk_italic, image, footnote_link, link, autolink] - diff --git a/julia-0.6.3/share/julia/base/markdown/Julia/interp.jl b/julia-0.6.3/share/julia/base/markdown/Julia/interp.jl deleted file mode 100644 index b41ec5f..0000000 --- a/julia-0.6.3/share/julia/base/markdown/Julia/interp.jl +++ /dev/null @@ -1,48 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -function Base.parse(stream::IO; greedy::Bool = true, raise::Bool = true) - pos = position(stream) - ex, Δ = Base.parse(readstring(stream), 1, greedy = greedy, raise = raise) - seek(stream, pos + Δ - 1) - return ex -end - -function interpinner(stream::IO, greedy = false) - startswith(stream, '$') || return - (eof(stream) || Char(peek(stream)) in whitespace) && return - try - return Base.parse(stream::IOBuffer, greedy = greedy) - catch e - return - end -end - -@trigger '$' -> -function interp(stream::IO, md::MD) - withstream(stream) do - ex = interpinner(stream) - return ex - end -end - -function blockinterp(stream::IO, md::MD) - withstream(stream) do - ex = interpinner(stream) - if ex ≡ nothing - return false - else - push!(md, ex) - return true - end - end -end - -toexpr(x) = x - -toexpr(xs::Vector{Any}) = Expr(:call, GlobalRef(Base,:vector_any), map(toexpr, xs)...) - -for T in Any[MD, Paragraph, Header, Link, Bold, Italic] - @eval function toexpr(md::$T) - Expr(:call, typeof(md), $(map(x->:(toexpr(md.$x)), fieldnames(Base.unwrap_unionall(T)))...)) - end -end diff --git a/julia-0.6.3/share/julia/base/markdown/Markdown.jl b/julia-0.6.3/share/julia/base/markdown/Markdown.jl deleted file mode 100644 index d32ae9f..0000000 --- a/julia-0.6.3/share/julia/base/markdown/Markdown.jl +++ /dev/null @@ -1,67 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -module Markdown - -import Base: show, == -import Core: @doc_str - -include(joinpath("parse", "config.jl")) -include(joinpath("parse", "util.jl")) -include(joinpath("parse", "parse.jl")) - -include(joinpath("Common", "Common.jl")) -include(joinpath("GitHub", "GitHub.jl")) -include(joinpath("IPython", "IPython.jl")) -include(joinpath("Julia", "Julia.jl")) - -include(joinpath("render", "plain.jl")) -include(joinpath("render", "html.jl")) -include(joinpath("render", "latex.jl")) -include(joinpath("render", "rst.jl")) - -include(joinpath("render", "terminal", "render.jl")) - -export readme, license, @md_str, @doc_str - -parse(markdown::AbstractString; flavor = julia) = parse(IOBuffer(markdown), flavor = flavor) -parse_file(file::AbstractString; flavor = julia) = parse(readstring(file), flavor = flavor) - -readme(pkg::AbstractString; flavor = github) = parse_file(Pkg.dir(pkg, "README.md"), flavor = flavor) -readme(pkg::Module; flavor = github) = readme(string(pkg), flavor = flavor) - -license(pkg::AbstractString; flavor = github) = parse_file(Pkg.dir(pkg, "LICENSE.md"), flavor = flavor) -license(pkg::Module; flavor = github) = license(string(pkg), flavor = flavor) - -function mdexpr(s, flavor = :julia) - md = parse(s, flavor = Symbol(flavor)) - esc(toexpr(md)) -end - -function docexpr(s, flavor = :julia) - quote - let md = $(mdexpr(s, flavor)) - md.meta[:path] = @__FILE__ - md.meta[:module] = current_module() - md - end - end -end - -macro md_str(s, t...) - mdexpr(s, t...) -end - -doc_str(md, file, mod) = (md.meta[:path] = file; md.meta[:module] = mod; md) -doc_str(md::AbstractString, file, mod) = doc_str(parse(md), file, mod) - -macro doc_str(s::AbstractString, t...) - :($(doc_str)($(mdexpr(s, t...)), $(Base).@__FILE__, $(current_module)())) -end - -function Base.display(d::Base.REPL.REPLDisplay, md::Vector{MD}) - for md in md - display(d, md) - end -end - -end diff --git a/julia-0.6.3/share/julia/base/markdown/parse/config.jl b/julia-0.6.3/share/julia/base/markdown/parse/config.jl deleted file mode 100644 index 14d3a7a..0000000 --- a/julia-0.6.3/share/julia/base/markdown/parse/config.jl +++ /dev/null @@ -1,82 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -const InnerConfig = Dict{Char, Vector{Function}} - -mutable struct Config - breaking::Vector{Function} - regular::Vector{Function} - inner::InnerConfig -end - -Config() = Config(Function[], Function[], InnerConfig()) - -const META = Dict{Function, Dict{Symbol, Any}}() - -getset(coll, key, default) = coll[key] = get(coll, key, default) - -meta(f) = getset(META, f, Dict{Symbol, Any}()) - -breaking!(f) = meta(f)[:breaking] = true -breaking(f) = get(meta(f), :breaking, false) - -triggers!(f, ts) = meta(f)[:triggers] = Set{Char}(ts) -triggers(f) = get(meta(f), :triggers, Set{Char}()) - -# Macros - -isexpr(x::Expr, ts...) = x.head in ts -isexpr(x::T, ts...) where {T} = T in ts - -macro breaking(ex) - isexpr(ex, :->) || error("invalid @breaking form, use ->") - b, def = ex.args - if b - quote - f = $(esc(def)) - breaking!(f) - f - end - else - esc(def) - end -end - -macro trigger(ex) - isexpr(ex, :->) || error("invalid @triggers form, use ->") - ts, def = ex.args - quote - f = $(esc(def)) - triggers!(f, $ts) - f - end -end - -# Construction - -function config(parsers::Function...) - c = Config() - for parser in parsers - ts = triggers(parser) - if breaking(parser) - push!(c.breaking, parser) - elseif !isempty(ts) - for t in ts - push!(getset(c.inner, t, Function[]), parser) - end - else - push!(c.regular, parser) - end - end - return c -end - -# Flavour definitions - -const flavors = Dict{Symbol, Config}() - -macro flavor(name, features) - quote - const $(esc(name)) = config($(map(esc,features.args)...)) - flavors[$(Expr(:quote, name))] = $(esc(name)) - end -end diff --git a/julia-0.6.3/share/julia/base/markdown/parse/parse.jl b/julia-0.6.3/share/julia/base/markdown/parse/parse.jl deleted file mode 100644 index b9a2f9c..0000000 --- a/julia-0.6.3/share/julia/base/markdown/parse/parse.jl +++ /dev/null @@ -1,96 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -mutable struct MD - content::Vector{Any} - meta::Dict{Any, Any} - - MD(content::AbstractVector, meta::Dict = Dict()) = - new(content, meta) -end - -MD(xs...) = MD(vcat(xs...)) - -function MD(cfg::Config, xs...) - md = MD(xs...) - md.meta[:config] = cfg - return md -end - -config(md::MD) = md.meta[:config]::Config - -# Forward some array methods - -Base.push!(md::MD, x) = push!(md.content, x) -Base.getindex(md::MD, args...) = md.content[args...] -Base.setindex!(md::MD, args...) = setindex!(md.content, args...) -Base.endof(md::MD) = endof(md.content) -Base.length(md::MD) = length(md.content) -Base.isempty(md::MD) = isempty(md.content) - -==(a::MD, b::MD) = (html(a) == html(b)) - -# Parser functions: -# md – should be modified appropriately -# return – basically, true if parse was successful -# false uses the next parser in the queue, true -# goes back to the beginning -# -# Inner parsers: -# return – element to use or nothing - -# Inner parsing - -function parseinline(stream::IO, md::MD, parsers::Vector{Function}) - for parser in parsers - inner = parser(stream, md) - inner ≡ nothing || return inner - end -end - -function parseinline(stream::IO, md::MD, config::Config) - content = [] - buffer = IOBuffer() - while !eof(stream) - # FIXME: this is broken if we're looking for non-ASCII - # characters because peek only returns a single byte. - char = Char(peek(stream)) - if haskey(config.inner, char) && - (inner = parseinline(stream, md, config.inner[char])) !== nothing - c = String(take!(buffer)) - !isempty(c) && push!(content, c) - buffer = IOBuffer() - push!(content, inner) - else - write(buffer, read(stream, Char)) - end - end - c = String(take!(buffer)) - !isempty(c) && push!(content, c) - return content -end - -parseinline(s::AbstractString, md::MD, c::Config) = - parseinline(IOBuffer(s), md, c) - -parseinline(s, md::MD) = parseinline(s, md, config(md)) - -# Block parsing - -function parse(stream::IO, block::MD, config::Config; breaking = false) - skipblank(stream) - eof(stream) && return false - for parser in (breaking ? config.breaking : [config.breaking; config.regular]) - parser(stream, block) && return true - end - return false -end - -parse(stream::IO, block::MD; breaking = false) = - parse(stream, block, config(block), breaking = breaking) - -function parse(stream::IO; flavor = julia) - isa(flavor, Symbol) && (flavor = flavors[flavor]) - markdown = MD(flavor) - while parse(stream, markdown, flavor) end - return markdown -end diff --git a/julia-0.6.3/share/julia/base/markdown/parse/util.jl b/julia-0.6.3/share/julia/base/markdown/parse/util.jl deleted file mode 100644 index 38f1a38..0000000 --- a/julia-0.6.3/share/julia/base/markdown/parse/util.jl +++ /dev/null @@ -1,206 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -import Base: peek - -macro dotimes(n, body) - quote - for i = 1:$(esc(n)) - $(esc(body)) - end - end -end - -const whitespace = " \t\r" - -""" -Skip any leading whitespace. Returns io. -""" -function skipwhitespace(io::IO; newlines = true) - while !eof(io) && (Char(peek(io)) in whitespace || (newlines && peek(io) == UInt8('\n'))) - read(io, Char) - end - return io -end - -""" -Skip any leading blank lines. Returns the number skipped. -""" -function skipblank(io::IO) - start = position(io) - i = 0 - while !eof(io) - c = read(io, Char) - c == '\n' && (start = position(io); i+=1; continue) - c == '\r' && (start = position(io); i+=1; continue) - c in whitespace || break - end - seek(io, start) - return i -end - -""" -Returns true if the line contains only (and, unless allowempty, -at least one of) the characters given. -""" -function linecontains(io::IO, chars; allow_whitespace = true, - eat = true, - allowempty = false) - start = position(io) - l = readline(io) - length(l) == 0 && return allowempty - - result = allowempty - for c in l - c in whitespace && (allow_whitespace ? continue : (result = false; break)) - c in chars && (result = true; continue) - result = false; break - end - !(result && eat) && seek(io, start) - return result -end - -blankline(io::IO; eat = true) = - linecontains(io, "", - allow_whitespace = true, - allowempty = true, - eat = eat) - -""" -Test if the stream starts with the given string. -`eat` specifies whether to advance on success (true by default). -`padding` specifies whether leading whitespace should be ignored. -""" -function startswith(stream::IO, s::AbstractString; eat = true, padding = false, newlines = true) - start = position(stream) - padding && skipwhitespace(stream, newlines = newlines) - result = true - for char in s - !eof(stream) && read(stream, Char) == char || - (result = false; break) - end - !(result && eat) && seek(stream, start) - return result -end - -function startswith(stream::IO, c::Char; eat = true) - if !eof(stream) && peek(stream) == UInt8(c) - eat && read(stream, Char) - return true - else - return false - end -end - -function startswith(stream::IO, ss::Vector{<:AbstractString}; kws...) - any(s->startswith(stream, s; kws...), ss) -end - -function startswith(stream::IO, r::Regex; eat = true, padding = false) - @assert Base.startswith(r.pattern, "^") - start = position(stream) - padding && skipwhitespace(stream) - line = readline(stream) - seek(stream, start) - m = match(r, line) - m === nothing && return "" - eat && @dotimes length(m.match) read(stream, Char) - return m.match -end - -""" -Executes the block of code, and if the return value is `nothing`, -returns the stream to its initial position. -""" -function withstream(f, stream) - pos = position(stream) - result = f() - (result ≡ nothing || result ≡ false) && seek(stream, pos) - return result -end - -""" -Consume the standard allowed markdown indent of -three spaces. Returns false if there are more than -three present. -""" -function eatindent(io::IO, n = 3) - withstream(io) do - m = 0 - while startswith(io, ' ') m += 1 end - return m <= n - end -end - -""" -Read the stream until startswith(stream, delim) -The delimiter is consumed but not included. -Returns nothing and resets the stream if delim is -not found. -""" -function readuntil(stream::IO, delimiter; newlines = false, match = nothing) - withstream(stream) do - buffer = IOBuffer() - count = 0 - while !eof(stream) - if startswith(stream, delimiter) - if count == 0 - return String(take!(buffer)) - else - count -= 1 - write(buffer, delimiter) - continue - end - end - char = read(stream, Char) - char == match && (count += 1) - !newlines && char == '\n' && break - write(buffer, char) - end - end -end - -# TODO: refactor this. If we're going to assume -# the delimiter is a single character + a minimum -# repeat we may as well just pass that into the -# function. - -""" -Parse a symmetrical delimiter which wraps words. -i.e. `*word word*` but not `*word * word`. -`repeat` specifies whether the delimiter can be repeated. -Escaped delimiters are not yet supported. -""" -function parse_inline_wrapper(stream::IO, delimiter::AbstractString; rep = false) - delimiter, nmin = string(delimiter[1]), length(delimiter) - withstream(stream) do - if position(stream) >= 1 - # check the previous byte isn't a delimiter - skip(stream, -1) - (read(stream, Char) in delimiter) && return nothing - end - n = nmin - startswith(stream, delimiter^n) || return nothing - while startswith(stream, delimiter); n += 1; end - !rep && n > nmin && return nothing - !eof(stream) && Char(peek(stream)) in whitespace && return nothing - - buffer = IOBuffer() - while !eof(stream) - char = read(stream, Char) - write(buffer, char) - if !(char in whitespace || char == '\n' || char in delimiter) && startswith(stream, delimiter^n) - trailing = 0 - while startswith(stream, delimiter); trailing += 1; end - trailing == 0 && return String(take!(buffer)) - write(buffer, delimiter ^ (n + trailing)) - end - end - end -end - -function showrest(io::IO) - start = position(io) - show(readstring(io)) - println() - seek(io, start) -end diff --git a/julia-0.6.3/share/julia/base/markdown/render/html.jl b/julia-0.6.3/share/julia/base/markdown/render/html.jl deleted file mode 100644 index ae74794..0000000 --- a/julia-0.6.3/share/julia/base/markdown/render/html.jl +++ /dev/null @@ -1,191 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -include("rich.jl") - -# Utils - -function withtag(f, io::IO, tag, attrs...) - print(io, "<$tag") - for (attr, value) in attrs - print(io, " ") - htmlesc(io, attr) - print(io, "=\"") - htmlesc(io, value) - print(io, "\"") - end - f === nothing && return print(io, " />") - - print(io, ">") - f() - print(io, "</$tag>") -end - -tag(io::IO, tag, attrs...) = withtag(nothing, io, tag, attrs...) - -const _htmlescape_chars = Dict('<'=>"<", '>'=>">", - '"'=>""", '&'=>"&", - # ' '=>" ", - ) -for ch in "'`!\$\%()=+{}[]" - _htmlescape_chars[ch] = "&#$(Int(ch));" -end - -function htmlesc(io::IO, s::AbstractString) - # s1 = replace(s, r"&(?!(\w+|\#\d+);)", "&") - for ch in s - print(io, get(_htmlescape_chars, ch, ch)) - end -end -function htmlesc(io::IO, s::Symbol) - htmlesc(io, string(s)) -end -function htmlesc(io::IO, xs::Union{AbstractString,Symbol}...) - for s in xs - htmlesc(io, s) - end -end -function htmlesc(s::Union{AbstractString,Symbol}) - sprint(htmlesc, s) -end - -# Block elements - -function html(io::IO, content::Vector) - for md in content - html(io, md) - println(io) - end -end - -html(io::IO, md::MD) = html(io, md.content) - -function html{l}(io::IO, header::Header{l}) - withtag(io, "h$l") do - htmlinline(io, header.text) - end -end - -function html(io::IO, code::Code) - withtag(io, :pre) do - maybe_lang = !isempty(code.language) ? Any[:class=>"language-$(code.language)"] : [] - withtag(io, :code, maybe_lang...) do - htmlesc(io, code.code) - # TODO should print newline if this is longer than one line ? - end - end -end - -function html(io::IO, md::Paragraph) - withtag(io, :p) do - htmlinline(io, md.content) - end -end - -function html(io::IO, md::BlockQuote) - withtag(io, :blockquote) do - println(io) - html(io, md.content) - end -end - -function html(io::IO, f::Footnote) - withtag(io, :div, :class => "footnote", :id => "footnote-$(f.id)") do - withtag(io, :p, :class => "footnote-title") do - print(io, f.id) - end - html(io, f.text) - end -end - -function html(io::IO, md::Admonition) - withtag(io, :div, :class => "admonition $(md.category)") do - withtag(io, :p, :class => "admonition-title") do - print(io, md.title) - end - html(io, md.content) - end -end - -function html(io::IO, md::List) - maybe_attr = md.ordered > 1 ? Any[:start => string(md.ordered)] : [] - withtag(io, isordered(md) ? :ol : :ul, maybe_attr...) do - for item in md.items - println(io) - withtag(io, :li) do - html(io, item) - end - end - println(io) - end -end - -function html(io::IO, md::HorizontalRule) - tag(io, :hr) -end - -html(io::IO, x) = tohtml(io, x) - -# Inline elements - -function htmlinline(io::IO, content::Vector) - for x in content - htmlinline(io, x) - end -end - -function htmlinline(io::IO, code::Code) - withtag(io, :code) do - htmlesc(io, code.code) - end -end - -function htmlinline(io::IO, md::Union{Symbol,AbstractString}) - htmlesc(io, md) -end - -function htmlinline(io::IO, md::Bold) - withtag(io, :strong) do - htmlinline(io, md.text) - end -end - -function htmlinline(io::IO, md::Italic) - withtag(io, :em) do - htmlinline(io, md.text) - end -end - -function htmlinline(io::IO, md::Image) - tag(io, :img, :src=>md.url, :alt=>md.alt) -end - - -function htmlinline(io::IO, f::Footnote) - withtag(io, :a, :href => "#footnote-$(f.id)", :class => "footnote") do - print(io, "[", f.id, "]") - end -end - -function htmlinline(io::IO, link::Link) - withtag(io, :a, :href=>link.url) do - htmlinline(io, link.text) - end -end - -function htmlinline(io::IO, br::LineBreak) - tag(io, :br) -end - -htmlinline(io::IO, x) = tohtml(io, x) - -# API - -export html - -html(md) = sprint(html, md) - -function show(io::IO, ::MIME"text/html", md::MD) - withtag(io, :div, :class=>"markdown") do - html(io, md) - end -end diff --git a/julia-0.6.3/share/julia/base/markdown/render/latex.jl b/julia-0.6.3/share/julia/base/markdown/render/latex.jl deleted file mode 100644 index e41f4b5..0000000 --- a/julia-0.6.3/share/julia/base/markdown/render/latex.jl +++ /dev/null @@ -1,172 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -export latex - -function wrapblock(f, io, env) - println(io, "\\begin{", env, "}") - f() - println(io, "\\end{", env, "}") -end - -function wrapinline(f, io, cmd) - print(io, "\\", cmd, "{") - f() - print(io, "}") -end - -# Block elements - -latex(io::IO, md::MD) = latex(io, md.content) - -function latex(io::IO, content::Vector) - for c in content - latex(io, c) - end -end - -function latex{l}(io::IO, header::Header{l}) - tag = l < 4 ? "sub"^(l-1) * "section" : "sub"^(l-4) * "paragraph" - wrapinline(io, tag) do - latexinline(io, header.text) - end - println(io) -end - -function latex(io::IO, code::Code) - wrapblock(io, "verbatim") do - # TODO latex escape - println(io, code.code) - end -end - -function latexinline(io::IO, code::Code) - wrapinline(io, "texttt") do - print(io, latexesc(code.code)) - end -end - -function latex(io::IO, md::Paragraph) - for md in md.content - latexinline(io, md) - end - println(io) - println(io) -end - -function latex(io::IO, md::BlockQuote) - wrapblock(io, "quote") do - latex(io, md.content) - end -end - - -function latex(io::IO, f::Footnote) - print(io, "\\footnotetext[", f.id, "]{") - latex(io, f.text) - println(io, "}") -end - -function latex(io::IO, md::Admonition) - wrapblock(io, "quote") do - wrapinline(io, "textbf") do - print(io, md.category) - end - println(io, "\n\n", md.title, "\n") - latex(io, md.content) - end -end - -function latex(io::IO, md::List) - # `\begin{itemize}` is used here for both ordered and unordered lists since providing - # custom starting numbers for enumerated lists is simpler to do by manually assigning - # each number to `\item` ourselves rather than using `\setcounter{enumi}{<start>}`. - # - # For an ordered list starting at 5 the following will be generated: - # - # \begin{itemize} - # \item[5. ] ... - # \item[6. ] ... - # ... - # \end{itemize} - # - pad = ndigits(md.ordered + length(md.items)) + 2 - fmt = n -> (isordered(md) ? "[$(rpad("$(n + md.ordered - 1).", pad))]" : "") - wrapblock(io, "itemize") do - for (n, item) in enumerate(md.items) - print(io, "\\item$(fmt(n)) ") - latex(io, item) - n < length(md.items) && println(io) - end - end -end - -function show(io::IO, ::MIME"text/latex", md::HorizontalRule) - println(io, "\\rule{\\textwidth}{1pt}") -end - -# Inline elements - -function latexinline(io::IO, md::Vector) - for c in md - latexinline(io, c) - end -end - -function latexinline(io::IO, md::AbstractString) - latexesc(io, md) -end - -function latexinline(io::IO, md::Bold) - wrapinline(io, "textbf") do - latexinline(io, md.text) - end -end - -function latexinline(io::IO, md::Italic) - wrapinline(io, "emph") do - latexinline(io, md.text) - end -end - -function latexinline(io::IO, md::Image) - wrapblock(io, "figure") do - println(io, "\\centering") - wrapinline(io, "includegraphics") do - print(io, md.url) - end - println(io) - wrapinline(io, "caption") do - latexinline(io, md.alt) - end - println(io) - end -end - -latexinline(io::IO, f::Footnote) = print(io, "\\footnotemark[", f.id, "]") - -function latexinline(io::IO, md::Link) - wrapinline(io, "href") do - print(io, md.url) - end - print(io, "{") - latexinline(io, md.text) - print(io, "}") -end - -const _latexescape_chars = Dict{Char, AbstractString}( - '~'=>"{\\sim}", '^'=>"\\^{}", '\\'=>"{\\textbackslash}") -for ch in "&%\$#_{}" - _latexescape_chars[ch] = "\\$ch" -end - -function latexesc(io, s::AbstractString) - for ch in s - print(io, get(_latexescape_chars, ch, ch)) - end -end - -latex(md) = sprint(latex, md) -latexinline(md) = sprint(latexinline, md) -latexesc(s) = sprint(latexesc, s) - -show(io::IO, ::MIME"text/latex", md::MD) = latex(io, md) diff --git a/julia-0.6.3/share/julia/base/markdown/render/plain.jl b/julia-0.6.3/share/julia/base/markdown/render/plain.jl deleted file mode 100644 index 5d50b5c..0000000 --- a/julia-0.6.3/share/julia/base/markdown/render/plain.jl +++ /dev/null @@ -1,140 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -plain(x) = sprint(plain, x) - -function plain(io::IO, content::Vector) - isempty(content) && return - for md in content[1:end-1] - plain(io, md) - println(io) - end - plain(io, content[end]) -end - -plain(io::IO, md::MD) = plain(io, md.content) - -function plain(io::IO, header::Header{l}) where l - print(io, "#"^l*" ") - plaininline(io, header.text) - println(io) -end - -function plain(io::IO, code::Code) - # If the code includes a fenced block this will break parsing, - # so it must be enclosed by a longer ````-sequence. - n = mapreduce(length, max, 2, matchall(r"^`+"m, code.code)) + 1 - println(io, "`" ^ n, code.language) - println(io, code.code) - println(io, "`" ^ n) -end - -function plain(io::IO, p::Paragraph) - plaininline(io, p.content) - println(io) -end - -function plain(io::IO, list::List) - for (i, item) in enumerate(list.items) - print(io, isordered(list) ? "$(i + list.ordered - 1). " : " * ") - lines = split(rstrip(sprint(plain, item)), "\n") - for (n, line) in enumerate(lines) - print(io, (n == 1 || isempty(line)) ? "" : " ", line) - n < length(lines) && println(io) - end - println(io) - end -end - -function plain(io::IO, q::BlockQuote) - s = sprint(plain, q.content) - for line in split(rstrip(s), "\n") - println(io, isempty(line) ? ">" : "> ", line) - end - println(io) -end - -function plain(io::IO, f::Footnote) - print(io, "[^", f.id, "]:") - s = sprint(plain, f.text) - lines = split(rstrip(s), "\n") - # Single line footnotes are printed on the same line as their label - # rather than taking up an additional line. - if length(lines) == 1 - println(io, " ", lines[1]) - else - println(io) - for line in lines - println(io, isempty(line) ? "" : " ", line) - end - println(io) - end -end - -function plain(io::IO, md::Admonition) - s = sprint(plain, md.content) - title = md.title == ucfirst(md.category) ? "" : " \"$(md.title)\"" - println(io, "!!! ", md.category, title) - for line in split(rstrip(s), "\n") - println(io, isempty(line) ? "" : " ", line) - end - println(io) -end - -function plain(io::IO, md::HorizontalRule) - println(io, "-" ^ 3) -end - -function plain(io::IO, l::LaTeX) - println(io, '$', '$') - println(io, l.formula) - println(io, '$', '$') -end - -function plain(io::IO, md) - show(io, MIME"text/plain"(), md) - println(io) -end - -# Inline elements - -plaininline(x) = sprint(plaininline, x) - -function plaininline(io::IO, md...) - for el in md - plaininline(io, el) - end -end - -plaininline(io::IO, md::Vector) = !isempty(md) && plaininline(io, md...) - -plaininline(io::IO, f::Footnote) = print(io, "[^", f.id, "]") - -plaininline(io::IO, link::Link) = plaininline(io, "[", link.text, "](", link.url, ")") - -plaininline(io::IO, md::Image) = plaininline(io, "![", md.alt, "](", md.url, ")") - -plaininline(io::IO, s::AbstractString) = print(io, s) - -plaininline(io::IO, md::Bold) = plaininline(io, "**", md.text, "**") - -plaininline(io::IO, md::Italic) = plaininline(io, "*", md.text, "*") - -function plaininline(io::IO, md::Code) - if contains(md.code, "`") - n = maximum(length(m) for m in matchall(r"(`+)", md.code)) - s = "`"^((iseven(n) ? 1 : 2) + n) - print(io, s, Base.startswith(md.code, "`") ? " " : "") - print(io, md.code, endswith(md.code, "`") ? " " : "", s) - else - print(io, "`", md.code, "`") - end -end - -plaininline(io::IO, br::LineBreak) = println(io) - -plaininline(io::IO, x) = show(io, MIME"text/plain"(), x) - -# show - -Base.show(io::IO, md::MD) = plain(io, md) -Base.show(io::IO, ::MIME"text/markdown", md::MD) = plain(io, md) diff --git a/julia-0.6.3/share/julia/base/markdown/render/rich.jl b/julia-0.6.3/share/julia/base/markdown/render/rich.jl deleted file mode 100644 index c604a80..0000000 --- a/julia-0.6.3/share/julia/base/markdown/render/rich.jl +++ /dev/null @@ -1,30 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -function tohtml(io::IO, m::MIME"text/html", x) - show(io, m, x) -end - -function tohtml(io::IO, m::MIME"text/plain", x) - htmlesc(io, sprint(show, m, x)) -end - -function tohtml(io::IO, m::MIME"image/png", img) - print(io, """<img src="data:image/png;base64,""") - print(io, stringmime(m, img)) - print(io, "\" />") -end - -function tohtml(io::IO, m::MIME"image/svg+xml", img) - show(io, m, img) -end - -# Display infrastructure - -function bestmime(val) - for mime in ("text/html", "image/svg+xml", "image/png", "text/plain") - mimewritable(mime, val) && return MIME(Symbol(mime)) - end - error("Cannot render $val to Markdown.") -end - -tohtml(io::IO, x) = tohtml(io, bestmime(x), x) diff --git a/julia-0.6.3/share/julia/base/markdown/render/rst.jl b/julia-0.6.3/share/julia/base/markdown/render/rst.jl deleted file mode 100644 index 58269df..0000000 --- a/julia-0.6.3/share/julia/base/markdown/render/rst.jl +++ /dev/null @@ -1,145 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -rst(x) = sprint(rst, x) - -function rst(io::IO, content::Vector) - isempty(content) && return - for md in content[1:end-1] - rst(io, md) - println(io) - end - rst(io, content[end]) -end - -rst(io::IO, md::MD) = rst(io, md.content) - -function rst{l}(io::IO, header::Header{l}) - s = rstinline(header.text) - println(io, s) - println(io, string("*=-~:.^"[l])^length(s)) - println(io) -end - -function rst(io::IO, code::Code) - if code.language == "jldoctest" - println(io, ".. doctest::\n") - elseif code.language != "rst" - println(io, ".. code-block:: julia\n") - end - for l in lines(code.code) - println(io, " ", l) - end -end - -function rst(io::IO, p::Paragraph) - rstinline(io, p.content) - println(io) -end - -function rst(io::IO, list::List) - for (i, item) in enumerate(list.items) - bullet = isordered(list) ? "$(i + list.ordered - 1). " : "* " - print(io, bullet) - lines = split(rstrip(sprint(rst, item)), '\n') - for (n, line) in enumerate(lines) - print(io, (n == 1 || isempty(line)) ? "" : " "^length(bullet), line) - n < length(lines) && println(io) - end - println(io) - end -end - -function rst(io::IO, q::BlockQuote) - s = sprint(rst, q.content) - for line in split(rstrip(s), "\n") - println(io, " ", line) - end - println(io) -end - -function rst(io::IO, f::Footnote) - print(io, ".. [", f.id, "]") - s = sprint(rst, f.text) - lines = split(rstrip(s), "\n") - # Single line footnotes are printed on the same line as their label - # rather than taking up an additional line. - if length(lines) == 1 - println(io, " ", lines[1]) - else - println(io) - for line in lines - println(io, isempty(line) ? "" : " ", rstrip(line)) - end - println(io) - end -end - -function rst(io::IO, md::Admonition) - s = sprint(rst, md.content) - title = md.title == ucfirst(md.category) ? "" : md.title - println(io, ".. ", md.category, "::", isempty(title) ? "" : " $title") - for line in split(rstrip(s), "\n") - println(io, isempty(line) ? "" : " ", line) - end - println(io) -end - -function rst(io::IO, md::HorizontalRule) - println(io, "–" ^ 5) -end - -function rst(io::IO, l::LaTeX) - println(io, ".. math::\n") - for l in lines(l.formula) - println(io, " ", l) - end -end - -rst(io::IO, md) = show(io, "text/rst", md) - -# Inline elements - -rstinline(x) = sprint(rstinline, x) - -function rstinline(io::IO, md...) - wasCode = false - for el in md - wasCode && isa(el, AbstractString) && !Base.startswith(el, " ") && print(io, "\\ ") - wasCode = (isa(el, Code) || isa(el, LaTeX) || isa(el, Link)) && (wasCode = true) - rstinline(io, el) - end -end - -rstinline(io::IO, md::Vector) = !isempty(md) && rstinline(io, md...) - -# rstinline(io::IO, md::Image) = rstinline(io, ".. image:: ", md.url) - -function rstinline(io::IO, md::Link) - if ismatch(r":(func|obj|ref|exc|class|const|data):`\.*", md.url) - rstinline(io, md.url) - else - rstinline(io, "`", md.text, " <", md.url, ">`_") - end -end - -rstinline(io::IO, f::Footnote) = print(io, "[", f.id, "]_") - -rstescape(s) = replace(s, "\\", "\\\\") - -rstinline(io::IO, s::AbstractString) = print(io, rstescape(s)) - -rstinline(io::IO, md::Bold) = rstinline(io, "**", md.text, "**") - -rstinline(io::IO, md::Italic) = rstinline(io, "*", md.text, "*") - -rstinline(io::IO, md::Code) = print(io, "``", md.code, "``") - -rstinline(io::IO, br::LineBreak) = println(io) - -rstinline(io::IO, l::LaTeX) = print(io, ":math:`", l.formula, "`") - -rstinline(io::IO, x) = show(io, MIME"text/rst"(), x) - -# show - -Base.show(io::IO, ::MIME"text/rst", md::MD) = rst(io, md) diff --git a/julia-0.6.3/share/julia/base/markdown/render/terminal/formatting.jl b/julia-0.6.3/share/julia/base/markdown/render/terminal/formatting.jl deleted file mode 100644 index 36a4d39..0000000 --- a/julia-0.6.3/share/julia/base/markdown/render/terminal/formatting.jl +++ /dev/null @@ -1,107 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -# Styles - -const text_formats = Dict( - :black => ("\e[30m", "\e[39m"), - :red => ("\e[31m", "\e[39m"), - :green => ("\e[32m", "\e[39m"), - :yellow => ("\e[33m", "\e[39m"), - :blue => ("\e[34m", "\e[39m"), - :magenta => ("\e[35m", "\e[39m"), - :cyan => ("\e[36m", "\e[39m"), - :white => ("\e[37m", "\e[39m"), - :reset => ("\e[0m", "\e[0m"), - :bold => ("\e[1m", "\e[22m"), - :underline => ("\e[4m", "\e[24m"), - :blink => ("\e[5m", "\e[25m"), - :negative => ("\e[7m", "\e[27m")) - -function with_output_format(f::Function, formats::Vector{Symbol}, io::IO, args...) - Base.have_color && for format in formats - haskey(text_formats, format) && - print(io, text_formats[format][1]) - end - try f(io, args...) - finally - Base.have_color && for format in formats - haskey(text_formats, format) && - print(io, text_formats[format][2]) - end - end -end - -with_output_format(f::Function, format::Symbol, args...) = - with_output_format(f, [format], args...) - -with_output_format(format, f::Function, args...) = - with_output_format(f, format, args...) - -function print_with_format(format, io::IO, x) - with_output_format(format, io) do io - print(io, x) - end -end - -function println_with_format(format, io::IO, x) - print_with_format(format, io, x) - println(io) -end - -# Wrapping - -function ansi_length(s) - replace(s, r"\e\[[0-9]+m", "") |> length -end - -words(s) = split(s, " ") -lines(s) = split(s, "\n") - -# This could really be more efficient -function wrapped_lines(s::AbstractString; width = 80, i = 0) - if ismatch(r"\n", s) - return vcat(map(s->wrapped_lines(s, width = width, i = i), split(s, "\n"))...) - end - ws = words(s) - lines = AbstractString[ws[1]] - i += ws[1] |> ansi_length - for word in ws[2:end] - word_length = ansi_length(word) - if i + word_length + 1 > width - i = word_length - push!(lines, word) - else - i += word_length + 1 - lines[end] *= " " * word - end - end - return lines -end - -wrapped_lines(f::Function, args...; width = 80, i = 0) = - wrapped_lines(sprint(f, args...), width = width, i = 0) - -function print_wrapped(io::IO, s...; width = 80, pre = "", i = 0) - lines = wrapped_lines(s..., width = width, i = i) - println(io, lines[1]) - for line in lines[2:end] - println(io, pre, line) - end - length(lines), length(pre) + ansi_length(lines[end]) -end - -print_wrapped(f::Function, io::IO, args...; kws...) = print_wrapped(io, f, args...; kws...) - -function print_centred(io::IO, s...; columns = 80, width = columns) - lines = wrapped_lines(s..., width = width) - for line in lines - print(io, " "^(div(columns-ansi_length(line), 2))) - println(io, line) - end - length(lines), length(pre) + length(lines[end]) -end - -function centred(s, columns) - pad = div(columns - ansi_length(s), 2) - " "^pad * s -end diff --git a/julia-0.6.3/share/julia/base/markdown/render/terminal/render.jl b/julia-0.6.3/share/julia/base/markdown/render/terminal/render.jl deleted file mode 100644 index 76be8ec..0000000 --- a/julia-0.6.3/share/julia/base/markdown/render/terminal/render.jl +++ /dev/null @@ -1,148 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -include("formatting.jl") - -const margin = 2 -cols(io) = displaysize(io)[2] - -function term(io::IO, content::Vector, cols) - isempty(content) && return - for md in content[1:end-1] - term(io, md, cols) - println(io) - end - term(io, content[end], cols) -end - -term(io::IO, md::MD, columns = cols(io)) = term(io, md.content, columns) - -function term(io::IO, md::Paragraph, columns) - print(io, " "^margin) - print_wrapped(io, width = columns-2margin, pre = " "^margin) do io - terminline(io, md.content) - end -end - -function term(io::IO, md::BlockQuote, columns) - s = sprint(term, md.content, columns - 10) - for line in split(rstrip(s), "\n") - println(io, " "^margin, "|", line) - end -end - -function term(io::IO, md::Admonition, columns) - print(io, " "^margin, "| ") - with_output_format(:bold, print, io, isempty(md.title) ? md.category : md.title) - println(io, "\n", " "^margin, "|") - s = sprint(term, md.content, columns - 10) - for line in split(rstrip(s), "\n") - println(io, " "^margin, "|", line) - end -end - -function term(io::IO, f::Footnote, columns) - print(io, " "^margin, "| ") - with_output_format(:bold, print, io, "[^$(f.id)]") - println(io, "\n", " "^margin, "|") - s = sprint(term, f.text, columns - 10) - for line in split(rstrip(s), "\n") - println(io, " "^margin, "|", line) - end -end - -function term(io::IO, md::List, columns) - for (i, point) in enumerate(md.items) - print(io, " "^2margin, isordered(md) ? "$(i + md.ordered - 1). " : "• ") - print_wrapped(io, width = columns-(4margin+2), pre = " "^(2margin+2), - i = 2margin+2) do io - term(io, point, columns - 10) - end - end -end - -function _term_header(io::IO, md, char, columns) - text = terminline(md.text) - with_output_format(:bold, io) do io - print(io, " "^(2margin), " ") - line_no, lastline_width = print_wrapped(io, text, - width=columns - 4margin; pre=" ") - line_width = min(1 + lastline_width, columns) - if line_no > 1 - line_width = max(line_width, div(columns, 3)) - end - char != ' ' && println(io, " "^(2margin), string(char) ^ line_width) - end -end - -const _header_underlines = collect("≡=–-⋅ ") -# TODO settle on another option with unicode e.g. "≡=≃–∼⋅" ? - -function term{l}(io::IO, md::Header{l}, columns) - underline = _header_underlines[l] - _term_header(io, md, underline, columns) -end - -function term(io::IO, md::Code, columns) - with_output_format(:cyan, io) do io - for line in lines(md.code) - print(io, " "^margin) - println(io, line) - end - end -end - -function term(io::IO, br::LineBreak, columns) - println(io) -end - -function term(io::IO, br::HorizontalRule, columns) - println(io, " " ^ margin, "-" ^ (columns - 2margin)) -end - -term(io::IO, x, _) = show(io, MIME"text/plain"(), x) - -# Inline Content - -terminline(md) = sprint(terminline, md) - -function terminline(io::IO, content::Vector) - for md in content - terminline(io, md) - end -end - -function terminline(io::IO, md::AbstractString) - print(io, replace(md, r"[\s\t\n]+", " ")) -end - -function terminline(io::IO, md::Bold) - with_output_format(:bold, terminline, io, md.text) -end - -function terminline(io::IO, md::Italic) - with_output_format(:underline, terminline, io, md.text) -end - -function terminline(io::IO, md::LineBreak) - println(io) -end - -function terminline(io::IO, md::Image) - terminline(io, "(Image: $(md.alt))") -end - -terminline(io::IO, f::Footnote) = with_output_format(:bold, terminline, io, "[^$(f.id)]") - -function terminline(io::IO, md::Link) - terminline(io, md.text) -end - -function terminline(io::IO, code::Code) - print_with_format(:cyan, io, code.code) -end - -terminline(io::IO, x) = show(io, MIME"text/plain"(), x) - -# Show in terminal - -Base.display(d::Base.REPL.REPLDisplay, md::MD) = term(Base.REPL.outstream(d.repl), md) diff --git a/julia-0.6.3/share/julia/base/math.jl b/julia-0.6.3/share/julia/base/math.jl deleted file mode 100644 index dc00a54..0000000 --- a/julia-0.6.3/share/julia/base/math.jl +++ /dev/null @@ -1,972 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -module Math - -export sin, cos, tan, sinh, cosh, tanh, asin, acos, atan, - asinh, acosh, atanh, sec, csc, cot, asec, acsc, acot, - sech, csch, coth, asech, acsch, acoth, - sinpi, cospi, sinc, cosc, - cosd, cotd, cscd, secd, sind, tand, - acosd, acotd, acscd, asecd, asind, atand, atan2, - rad2deg, deg2rad, - log, log2, log10, log1p, exponent, exp, exp2, exp10, expm1, - cbrt, sqrt, significand, - lgamma, hypot, gamma, lfact, max, min, minmax, ldexp, frexp, - clamp, clamp!, modf, ^, mod2pi, rem2pi, - beta, lbeta, @evalpoly - -import Base: log, exp, sin, cos, tan, sinh, cosh, tanh, asin, - acos, atan, asinh, acosh, atanh, sqrt, log2, log10, - max, min, minmax, ^, exp2, muladd, rem, - exp10, expm1, log1p - -using Base: sign_mask, exponent_mask, exponent_one, - exponent_half, fpinttype, significand_mask - -using Core.Intrinsics: sqrt_llvm - -const IEEEFloat = Union{Float16, Float32, Float64} - -for T in (Float16, Float32, Float64) - @eval significand_bits(::Type{$T}) = $(trailing_ones(significand_mask(T))) - @eval exponent_bits(::Type{$T}) = $(sizeof(T)*8 - significand_bits(T) - 1) - @eval exponent_bias(::Type{$T}) = $(Int(exponent_one(T) >> significand_bits(T))) - # maximum float exponent - @eval exponent_max(::Type{$T}) = $(Int(exponent_mask(T) >> significand_bits(T)) - exponent_bias(T)) - # maximum float exponent without bias - @eval exponent_raw_max(::Type{$T}) = $(Int(exponent_mask(T) >> significand_bits(T))) -end - -# non-type specific math functions - -""" - clamp(x, lo, hi) - -Return `x` if `lo <= x <= hi`. If `x < lo`, return `lo`. If `x > hi`, return `hi`. Arguments -are promoted to a common type. - -```jldoctest -julia> clamp.([pi, 1.0, big(10.)], 2., 9.) -3-element Array{BigFloat,1}: - 3.141592653589793238462643383279502884197169399375105820974944592307816406286198 - 2.000000000000000000000000000000000000000000000000000000000000000000000000000000 - 9.000000000000000000000000000000000000000000000000000000000000000000000000000000 -``` -""" -clamp(x::X, lo::L, hi::H) where {X,L,H} = - ifelse(x > hi, convert(promote_type(X,L,H), hi), - ifelse(x < lo, - convert(promote_type(X,L,H), lo), - convert(promote_type(X,L,H), x))) - -""" - clamp!(array::AbstractArray, lo, hi) - -Restrict values in `array` to the specified range, in-place. -See also [`clamp`](@ref). -""" -function clamp!(x::AbstractArray, lo, hi) - @inbounds for i in eachindex(x) - x[i] = clamp(x[i], lo, hi) - end - x -end - -# evaluate p[1] + x * (p[2] + x * (....)), i.e. a polynomial via Horner's rule -macro horner(x, p...) - ex = esc(p[end]) - for i = length(p)-1:-1:1 - ex = :(muladd(t, $ex, $(esc(p[i])))) - end - Expr(:block, :(t = $(esc(x))), ex) -end - -# Evaluate p[1] + z*p[2] + z^2*p[3] + ... + z^(n-1)*p[n]. This uses -# Horner's method if z is real, but for complex z it uses a more -# efficient algorithm described in Knuth, TAOCP vol. 2, section 4.6.4, -# equation (3). - -""" - @evalpoly(z, c...) - -Evaluate the polynomial ``\\sum_k c[k] z^{k-1}`` for the coefficients `c[1]`, `c[2]`, ...; -that is, the coefficients are given in ascending order by power of `z`. This macro expands -to efficient inline code that uses either Horner's method or, for complex `z`, a more -efficient Goertzel-like algorithm. - -```jldoctest -julia> @evalpoly(3, 1, 0, 1) -10 - -julia> @evalpoly(2, 1, 0, 1) -5 - -julia> @evalpoly(2, 1, 1, 1) -7 -``` -""" -macro evalpoly(z, p...) - a = :($(esc(p[end]))) - b = :($(esc(p[end-1]))) - as = [] - for i = length(p)-2:-1:1 - ai = Symbol("a", i) - push!(as, :($ai = $a)) - a = :(muladd(r, $ai, $b)) - b = :($(esc(p[i])) - s * $ai) # see issue #15985 on fused mul-subtract - end - ai = :a0 - push!(as, :($ai = $a)) - C = Expr(:block, - :(x = real(tt)), - :(y = imag(tt)), - :(r = x + x), - :(s = muladd(x, x, y*y)), - as..., - :(muladd($ai, tt, $b))) - R = Expr(:macrocall, Symbol("@horner"), :tt, map(esc, p)...) - :(let tt = $(esc(z)) - isa(tt, Complex) ? $C : $R - end) -end - -""" - rad2deg(x) - -Convert `x` from radians to degrees. - -```jldoctest -julia> rad2deg(pi) -180.0 -``` -""" -rad2deg(z::AbstractFloat) = z * (180 / oftype(z, pi)) - -""" - deg2rad(x) - -Convert `x` from degrees to radians. - -```jldoctest -julia> deg2rad(90) -1.5707963267948966 -``` -""" -deg2rad(z::AbstractFloat) = z * (oftype(z, pi) / 180) -rad2deg(z::Real) = rad2deg(float(z)) -deg2rad(z::Real) = deg2rad(float(z)) - -log(b::T, x::T) where {T<:Number} = log(x)/log(b) - -""" - log(b,x) - -Compute the base `b` logarithm of `x`. Throws [`DomainError`](@ref) for negative -[`Real`](@ref) arguments. - -```jldoctest -julia> log(4,8) -1.5 - -julia> log(4,2) -0.5 -``` - -!!! note - If `b` is a power of 2 or 10, [`log2`](@ref) or [`log10`](@ref) should be used, as these will - typically be faster and more accurate. For example, - - ```jldoctest - julia> log(100,1000000) - 2.9999999999999996 - - julia> log10(1000000)/2 - 3.0 - ``` -""" -log(b::Number, x::Number) = log(promote(b,x)...) - -# type specific math functions - -const libm = Base.libm_name -const openspecfun = "libopenspecfun" - -# functions with no domain error -""" - sinh(x) - -Compute hyperbolic sine of `x`. -""" -sinh(x) - -""" - cosh(x) - -Compute hyperbolic cosine of `x`. -""" -cosh(x) - -""" - tanh(x) - -Compute hyperbolic tangent of `x`. -""" -tanh(x) - -""" - atan(x) - -Compute the inverse tangent of `x`, where the output is in radians. -""" -atan(x) - -""" - asinh(x) - -Compute the inverse hyperbolic sine of `x`. -""" -asinh(x) - -""" - expm1(x) - -Accurately compute ``e^x-1``. -""" -expm1(x) -for f in (:cbrt, :sinh, :cosh, :tanh, :atan, :asinh, :exp2, :expm1) - @eval begin - ($f)(x::Float64) = ccall(($(string(f)),libm), Float64, (Float64,), x) - ($f)(x::Float32) = ccall(($(string(f,"f")),libm), Float32, (Float32,), x) - ($f)(x::Real) = ($f)(float(x)) - end -end -exp(x::Real) = exp(float(x)) - -# fallback definitions to prevent infinite loop from $f(x::Real) def above - -""" - cbrt(x::Real) - -Return the cube root of `x`, i.e. ``x^{1/3}``. Negative values are accepted -(returning the negative real root when ``x < 0``). - -The prefix operator `∛` is equivalent to `cbrt`. - -```jldoctest -julia> cbrt(big(27)) -3.000000000000000000000000000000000000000000000000000000000000000000000000000000 -``` -""" -cbrt(x::AbstractFloat) = x < 0 ? -(-x)^(1//3) : x^(1//3) - -""" - exp2(x) - -Compute ``2^x``. - -```jldoctest -julia> exp2(5) -32.0 -``` -""" -exp2(x::AbstractFloat) = 2^x -for f in (:sinh, :cosh, :tanh, :atan, :asinh, :exp, :expm1) - @eval ($f)(x::AbstractFloat) = error("not implemented for ", typeof(x)) -end - -# functions with special cases for integer arguments -@inline function exp2(x::Base.BitInteger) - if x > 1023 - Inf64 - elseif x <= -1023 - # if -1073 < x <= -1023 then Result will be a subnormal number - # Hex literal with padding must be used to work on 32bit machine - reinterpret(Float64, 0x0000_0000_0000_0001 << ((x + 1074)) % UInt) - else - # We will cast everything to Int64 to avoid errors in case of Int128 - # If x is a Int128, and is outside the range of Int64, then it is not -1023<x<=1023 - reinterpret(Float64, (exponent_bias(Float64) + (x % Int64)) << (significand_bits(Float64)) % UInt) - end -end - -# TODO: GNU libc has exp10 as an extension; should openlibm? -exp10(x::Float64) = 10.0^x -exp10(x::Float32) = 10.0f0^x -exp10(x::Real) = exp10(float(x)) - -# utility for converting NaN return to DomainError -# the branch in nan_dom_err prevents its callers from inlining, so be sure to force it -# until the heuristics can be improved -@inline nan_dom_err(f, x) = isnan(f) & !isnan(x) ? throw(DomainError()) : f - -# functions that return NaN on non-NaN argument for domain error -""" - sin(x) - -Compute sine of `x`, where `x` is in radians. -""" -sin(x) - -""" - cos(x) - -Compute cosine of `x`, where `x` is in radians. -""" -cos(x) - -""" - tan(x) - -Compute tangent of `x`, where `x` is in radians. -""" -tan(x) - -""" - asin(x) - -Compute the inverse sine of `x`, where the output is in radians. -""" -asin(x) - -""" - acos(x) - -Compute the inverse cosine of `x`, where the output is in radians -""" -acos(x) - -""" - acosh(x) - -Compute the inverse hyperbolic cosine of `x`. -""" -acosh(x) - -""" - atanh(x) - -Compute the inverse hyperbolic tangent of `x`. -""" -atanh(x) - -""" - log(x) - -Compute the natural logarithm of `x`. Throws [`DomainError`](@ref) for negative -[`Real`](@ref) arguments. Use complex negative arguments to obtain complex results. - -There is an experimental variant in the `Base.Math.JuliaLibm` module, which is typically -faster and more accurate. -""" -log(x) - -""" - log2(x) - -Compute the logarithm of `x` to base 2. Throws [`DomainError`](@ref) for negative -[`Real`](@ref) arguments. - -# Example -```jldoctest -julia> log2(4) -2.0 - -julia> log2(10) -3.321928094887362 -``` -""" -log2(x) - -""" - log10(x) - -Compute the logarithm of `x` to base 10. -Throws [`DomainError`](@ref) for negative [`Real`](@ref) arguments. - -# Example -```jldoctest -julia> log10(100) -2.0 - -julia> log10(2) -0.3010299956639812 -``` -""" -log10(x) - -""" - log1p(x) - -Accurate natural logarithm of `1+x`. Throws [`DomainError`](@ref) for [`Real`](@ref) -arguments less than -1. - -There is an experimental variant in the `Base.Math.JuliaLibm` module, which is typically -faster and more accurate. - -# Examples -```jldoctest -julia> log1p(-0.5) --0.6931471805599453 - -julia> log1p(0) -0.0 -``` -""" -log1p(x) -for f in (:sin, :cos, :tan, :asin, :acos, :acosh, :atanh, :log, :log2, :log10, - :lgamma, :log1p) - @eval begin - @inline ($f)(x::Float64) = nan_dom_err(ccall(($(string(f)), libm), Float64, (Float64,), x), x) - @inline ($f)(x::Float32) = nan_dom_err(ccall(($(string(f, "f")), libm), Float32, (Float32,), x), x) - @inline ($f)(x::Real) = ($f)(float(x)) - end -end - -sqrt(x::Float64) = sqrt_llvm(x) -sqrt(x::Float32) = sqrt_llvm(x) - -""" - sqrt(x) - -Return ``\\sqrt{x}``. Throws [`DomainError`](@ref) for negative [`Real`](@ref) arguments. -Use complex negative arguments instead. The prefix operator `√` is equivalent to `sqrt`. -""" -sqrt(x::Real) = sqrt(float(x)) - -""" - hypot(x, y) - -Compute the hypotenuse ``\\sqrt{x^2+y^2}`` avoiding overflow and underflow. - -# Examples -```jldoctest -julia> a = 10^10; - -julia> hypot(a, a) -1.4142135623730951e10 - -julia> √(a^2 + a^2) # a^2 overflows -ERROR: DomainError: -sqrt will only return a complex result if called with a complex argument. Try sqrt(complex(x)). -Stacktrace: - [1] sqrt(::Int64) at ./math.jl:434 -``` -""" -hypot(x::Number, y::Number) = hypot(promote(x, y)...) -function hypot(x::T, y::T) where T<:Number - ax = abs(x) - ay = abs(y) - if ax < ay - ax, ay = ay, ax - end - if ax == 0 - r = ay / one(ax) - else - r = ay / ax - end - - rr = ax * sqrt(1 + r * r) - - # Use type of rr to make sure that return type is the same for - # all branches - if isnan(r) - isinf(ax) && return oftype(rr, Inf) - isinf(ay) && return oftype(rr, Inf) - return oftype(rr, r) - else - return rr - end -end - -""" - hypot(x...) - -Compute the hypotenuse ``\\sqrt{\\sum x_i^2}`` avoiding overflow and underflow. -""" -hypot(x::Number...) = vecnorm(x) - -""" - atan2(y, x) - -Compute the inverse tangent of `y/x`, using the signs of both `x` and `y` to determine the -quadrant of the return value. -""" -atan2(y::Real, x::Real) = atan2(promote(float(y),float(x))...) -atan2(y::T, x::T) where {T<:AbstractFloat} = Base.no_op_err("atan2", T) - -atan2(y::Float64, x::Float64) = ccall((:atan2,libm), Float64, (Float64, Float64,), y, x) -atan2(y::Float32, x::Float32) = ccall((:atan2f,libm), Float32, (Float32, Float32), y, x) - -max(x::T, y::T) where {T<:AbstractFloat} = ifelse((y > x) | (signbit(y) < signbit(x)), - ifelse(isnan(x), x, y), ifelse(isnan(y), y, x)) - - -min(x::T, y::T) where {T<:AbstractFloat} = ifelse((y < x) | (signbit(y) > signbit(x)), - ifelse(isnan(x), x, y), ifelse(isnan(y), y, x)) - -minmax(x::T, y::T) where {T<:AbstractFloat} = - ifelse(isnan(x) | isnan(y), ifelse(isnan(x), (x,x), (y,y)), - ifelse((y > x) | (signbit(x) > signbit(y)), (x,y), (y,x))) - - -""" - ldexp(x, n) - -Compute ``x \\times 2^n``. - -# Example -```jldoctest -julia> ldexp(5., 2) -20.0 -``` -""" -function ldexp(x::T, e::Integer) where T<:IEEEFloat - xu = reinterpret(Unsigned, x) - xs = xu & ~sign_mask(T) - xs >= exponent_mask(T) && return x # NaN or Inf - k = Int(xs >> significand_bits(T)) - if k == 0 # x is subnormal - xs == 0 && return x # +-0 - m = leading_zeros(xs) - exponent_bits(T) - ys = xs << unsigned(m) - xu = ys | (xu & sign_mask(T)) - k = 1 - m - # underflow, otherwise may have integer underflow in the following n + k - e < -50000 && return flipsign(T(0.0), x) - end - # For cases where e of an Integer larger than Int make sure we properly - # overflow/underflow; this is optimized away otherwise. - if e > typemax(Int) - return flipsign(T(Inf), x) - elseif e < typemin(Int) - return flipsign(T(0.0), x) - end - n = e % Int - k += n - # overflow, if k is larger than maximum posible exponent - if k >= exponent_raw_max(T) - return flipsign(T(Inf), x) - end - if k > 0 # normal case - xu = (xu & ~exponent_mask(T)) | (rem(k, fpinttype(T)) << significand_bits(T)) - return reinterpret(T, xu) - else # subnormal case - if k <= -significand_bits(T) # underflow - # overflow, for the case of integer overflow in n + k - e > 50000 && return flipsign(T(Inf), x) - return flipsign(T(0.0), x) - end - k += significand_bits(T) - z = T(2.0)^-significand_bits(T) - xu = (xu & ~exponent_mask(T)) | (rem(k, fpinttype(T)) << significand_bits(T)) - return z*reinterpret(T, xu) - end -end -ldexp(x::Float16, q::Integer) = Float16(ldexp(Float32(x), q)) - -""" - exponent(x) -> Int - -Get the exponent of a normalized floating-point number. -""" -function exponent(x::T) where T<:IEEEFloat - xs = reinterpret(Unsigned, x) & ~sign_mask(T) - xs >= exponent_mask(T) && return throw(DomainError()) # NaN or Inf - k = Int(xs >> significand_bits(T)) - if k == 0 # x is subnormal - xs == 0 && throw(DomainError()) - m = leading_zeros(xs) - exponent_bits(T) - k = 1 - m - end - return k - exponent_bias(T) -end - -""" - significand(x) - -Extract the `significand(s)` (a.k.a. mantissa), in binary representation, of a -floating-point number. If `x` is a non-zero finite number, then the result will be -a number of the same type on the interval ``[1,2)``. Otherwise `x` is returned. - -# Examples -```jldoctest -julia> significand(15.2)/15.2 -0.125 - -julia> significand(15.2)*8 -15.2 -``` -""" -function significand(x::T) where T<:IEEEFloat - xu = reinterpret(Unsigned, x) - xs = xu & ~sign_mask(T) - xs >= exponent_mask(T) && return x # NaN or Inf - if xs <= (~exponent_mask(T) & ~sign_mask(T)) # x is subnormal - xs == 0 && return x # +-0 - m = unsigned(leading_zeros(xs) - exponent_bits(T)) - xs <<= m - xu = xs | (xu & sign_mask(T)) - end - xu = (xu & ~exponent_mask(T)) | exponent_one(T) - return reinterpret(T, xu) -end - -""" - frexp(val) - -Return `(x,exp)` such that `x` has a magnitude in the interval ``[1/2, 1)`` or 0, -and `val` is equal to ``x \\times 2^{exp}``. -""" -function frexp(x::T) where T<:IEEEFloat - xu = reinterpret(Unsigned, x) - xs = xu & ~sign_mask(T) - xs >= exponent_mask(T) && return x, 0 # NaN or Inf - k = Int(xs >> significand_bits(T)) - if k == 0 # x is subnormal - xs == 0 && return x, 0 # +-0 - m = leading_zeros(xs) - exponent_bits(T) - xs <<= unsigned(m) - xu = xs | (xu & sign_mask(T)) - k = 1 - m - end - k -= (exponent_bias(T) - 1) - xu = (xu & ~exponent_mask(T)) | exponent_half(T) - return reinterpret(T, xu), k -end - -""" - rem(x, y, r::RoundingMode) - -Compute the remainder of `x` after integer division by `y`, with the quotient rounded -according to the rounding mode `r`. In other words, the quantity - - x - y*round(x/y,r) - -without any intermediate rounding. - -- if `r == RoundNearest`, then the result is exact, and in the interval - ``[-|y|/2, |y|/2]``. - -- if `r == RoundToZero` (default), then the result is exact, and in the interval - ``[0, |y|)`` if `x` is positive, or ``(-|y|, 0]`` otherwise. - -- if `r == RoundDown`, then the result is in the interval ``[0, y)`` if `y` is positive, or - ``(y, 0]`` otherwise. The result may not be exact if `x` and `y` have different signs, and - `abs(x) < abs(y)`. - -- if `r == RoundUp`, then the result is in the interval `(-y,0]` if `y` is positive, or - `[0,-y)` otherwise. The result may not be exact if `x` and `y` have the same sign, and - `abs(x) < abs(y)`. - -""" -rem(x, y, ::RoundingMode{:ToZero}) = rem(x,y) -rem(x, y, ::RoundingMode{:Down}) = mod(x,y) -rem(x, y, ::RoundingMode{:Up}) = mod(x,-y) - -rem(x::Float64, y::Float64, ::RoundingMode{:Nearest}) = - ccall((:remainder, libm),Float64,(Float64,Float64),x,y) -rem(x::Float32, y::Float32, ::RoundingMode{:Nearest}) = - ccall((:remainderf, libm),Float32,(Float32,Float32),x,y) -rem(x::Float16, y::Float16, r::RoundingMode{:Nearest}) = Float16(rem(Float32(x), Float32(y), r)) - - -""" - modf(x) - -Return a tuple (fpart,ipart) of the fractional and integral parts of a number. Both parts -have the same sign as the argument. - -# Example -```jldoctest -julia> modf(3.5) -(0.5, 3.0) -``` -""" -modf(x) = rem(x,one(x)), trunc(x) - -const _modff_temp = Ref{Float32}() -function modf(x::Float32) - f = ccall((:modff,libm), Float32, (Float32,Ptr{Float32}), x, _modff_temp) - f, _modff_temp[] -end - -const _modf_temp = Ref{Float64}() -function modf(x::Float64) - f = ccall((:modf,libm), Float64, (Float64,Ptr{Float64}), x, _modf_temp) - f, _modf_temp[] -end - -@inline ^(x::Float64, y::Float64) = nan_dom_err(ccall("llvm.pow.f64", llvmcall, Float64, (Float64, Float64), x, y), x + y) -@inline ^(x::Float32, y::Float32) = nan_dom_err(ccall("llvm.pow.f32", llvmcall, Float32, (Float32, Float32), x, y), x + y) -@inline ^(x::Float64, y::Integer) = x ^ Float64(y) -@inline ^(x::Float32, y::Integer) = x ^ Float32(y) -@inline ^(x::Float16, y::Integer) = Float16(Float32(x) ^ Float32(y)) -@inline literal_pow(::typeof(^), x::Float16, ::Type{Val{p}}) where {p} = Float16(literal_pow(^,Float32(x),Val{p})) - -function angle_restrict_symm(theta) - const P1 = 4 * 7.8539812564849853515625e-01 - const P2 = 4 * 3.7748947079307981766760e-08 - const P3 = 4 * 2.6951514290790594840552e-15 - - y = 2*floor(theta/(2*pi)) - r = ((theta - y*P1) - y*P2) - y*P3 - if (r > pi) - r -= (2*pi) - end - return r -end - -## rem2pi-related calculations ## - -function add22condh(xh::Float64, xl::Float64, yh::Float64, yl::Float64) - # as above, but only compute and return high double - r = xh+yh - s = (abs(xh) > abs(yh)) ? (xh-r+yh+yl+xl) : (yh-r+xh+xl+yl) - zh = r+s - return zh -end - -function ieee754_rem_pio2(x::Float64) - # rem_pio2 essentially computes x mod pi/2 (ie within a quarter circle) - # and returns the result as - # y between + and - pi/4 (for maximal accuracy (as the sign bit is exploited)), and - # n, where n specifies the integer part of the division, or, at any rate, - # in which quadrant we are. - # The invariant fulfilled by the returned values seems to be - # x = y + n*pi/2 (where y = y1+y2 is a double-double and y2 is the "tail" of y). - # Note: for very large x (thus n), the invariant might hold only modulo 2pi - # (in other words, n might be off by a multiple of 4, or a multiple of 100) - - # this is just wrapping up - # https://github.com/JuliaLang/openspecfun/blob/master/rem_pio2/e_rem_pio2.c - - y = [0.0,0.0] - n = ccall((:__ieee754_rem_pio2, openspecfun), Cint, (Float64,Ptr{Float64}), x, y) - return (n,y) -end - -# multiples of pi/2, as double-double (ie with "tail") -const pi1o2_h = 1.5707963267948966 # convert(Float64, pi * BigFloat(1/2)) -const pi1o2_l = 6.123233995736766e-17 # convert(Float64, pi * BigFloat(1/2) - pi1o2_h) - -const pi2o2_h = 3.141592653589793 # convert(Float64, pi * BigFloat(1)) -const pi2o2_l = 1.2246467991473532e-16 # convert(Float64, pi * BigFloat(1) - pi2o2_h) - -const pi3o2_h = 4.71238898038469 # convert(Float64, pi * BigFloat(3/2)) -const pi3o2_l = 1.8369701987210297e-16 # convert(Float64, pi * BigFloat(3/2) - pi3o2_h) - -const pi4o2_h = 6.283185307179586 # convert(Float64, pi * BigFloat(2)) -const pi4o2_l = 2.4492935982947064e-16 # convert(Float64, pi * BigFloat(2) - pi4o2_h) - -""" - rem2pi(x, r::RoundingMode) - -Compute the remainder of `x` after integer division by `2π`, with the quotient rounded -according to the rounding mode `r`. In other words, the quantity - - x - 2π*round(x/(2π),r) - -without any intermediate rounding. This internally uses a high precision approximation of -2π, and so will give a more accurate result than `rem(x,2π,r)` - -- if `r == RoundNearest`, then the result is in the interval ``[-π, π]``. This will generally - be the most accurate result. - -- if `r == RoundToZero`, then the result is in the interval ``[0, 2π]`` if `x` is positive,. - or ``[-2π, 0]`` otherwise. - -- if `r == RoundDown`, then the result is in the interval ``[0, 2π]``. - -- if `r == RoundUp`, then the result is in the interval ``[-2π, 0]``. - -# Example -```jldoctest -julia> rem2pi(7pi/4, RoundNearest) --0.7853981633974485 - -julia> rem2pi(7pi/4, RoundDown) -5.497787143782138 -``` -""" -function rem2pi end -function rem2pi(x::Float64, ::RoundingMode{:Nearest}) - abs(x) < pi && return x - - (n,y) = ieee754_rem_pio2(x) - - if iseven(n) - if n & 2 == 2 # n % 4 == 2: add/subtract pi - if y[1] <= 0 - return add22condh(y[1],y[2],pi2o2_h,pi2o2_l) - else - return add22condh(y[1],y[2],-pi2o2_h,-pi2o2_l) - end - else # n % 4 == 0: add 0 - return y[1] - end - else - if n & 2 == 2 # n % 4 == 3: subtract pi/2 - return add22condh(y[1],y[2],-pi1o2_h,-pi1o2_l) - else # n % 4 == 1: add pi/2 - return add22condh(y[1],y[2],pi1o2_h,pi1o2_l) - end - end -end -function rem2pi(x::Float64, ::RoundingMode{:ToZero}) - ax = abs(x) - ax <= 2*Float64(pi,RoundDown) && return x - - (n,y) = ieee754_rem_pio2(ax) - - if iseven(n) - if n & 2 == 2 # n % 4 == 2: add pi - z = add22condh(y[1],y[2],pi2o2_h,pi2o2_l) - else # n % 4 == 0: add 0 or 2pi - if y[1] > 0 - z = y[1] - else # negative: add 2pi - z = add22condh(y[1],y[2],pi4o2_h,pi4o2_l) - end - end - else - if n & 2 == 2 # n % 4 == 3: add 3pi/2 - z = add22condh(y[1],y[2],pi3o2_h,pi3o2_l) - else # n % 4 == 1: add pi/2 - z = add22condh(y[1],y[2],pi1o2_h,pi1o2_l) - end - end - copysign(z,x) -end -function rem2pi(x::Float64, ::RoundingMode{:Down}) - if x < pi4o2_h - if x >= 0 - return x - elseif x > -pi4o2_h - return add22condh(x,0.0,pi4o2_h,pi4o2_l) - end - end - - (n,y) = ieee754_rem_pio2(x) - - if iseven(n) - if n & 2 == 2 # n % 4 == 2: add pi - return add22condh(y[1],y[2],pi2o2_h,pi2o2_l) - else # n % 4 == 0: add 0 or 2pi - if y[1] > 0 - return y[1] - else # negative: add 2pi - return add22condh(y[1],y[2],pi4o2_h,pi4o2_l) - end - end - else - if n & 2 == 2 # n % 4 == 3: add 3pi/2 - return add22condh(y[1],y[2],pi3o2_h,pi3o2_l) - else # n % 4 == 1: add pi/2 - return add22condh(y[1],y[2],pi1o2_h,pi1o2_l) - end - end -end -function rem2pi(x::Float64, ::RoundingMode{:Up}) - if x > -pi4o2_h - if x <= 0 - return x - elseif x < pi4o2_h - return add22condh(x,0.0,-pi4o2_h,-pi4o2_l) - end - end - - (n,y) = ieee754_rem_pio2(x) - - if iseven(n) - if n & 2 == 2 # n % 4 == 2: sub pi - return add22condh(y[1],y[2],-pi2o2_h,-pi2o2_l) - else # n % 4 == 0: sub 0 or 2pi - if y[1] < 0 - return y[1] - else # positive: sub 2pi - return add22condh(y[1],y[2],-pi4o2_h,-pi4o2_l) - end - end - else - if n & 2 == 2 # n % 4 == 3: sub pi/2 - return add22condh(y[1],y[2],-pi1o2_h,-pi1o2_l) - else # n % 4 == 1: sub 3pi/2 - return add22condh(y[1],y[2],-pi3o2_h,-pi3o2_l) - end - end -end - -rem2pi(x::Float32, r::RoundingMode) = Float32(rem2pi(Float64(x), r)) -rem2pi(x::Float16, r::RoundingMode) = Float16(rem2pi(Float64(x), r)) -rem2pi(x::Int32, r::RoundingMode) = rem2pi(Float64(x), r) -function rem2pi(x::Int64, r::RoundingMode) - fx = Float64(x) - fx == x || throw(ArgumentError("Int64 argument to rem2pi is too large: $x")) - rem2pi(fx, r) -end - -""" - mod2pi(x) - -Modulus after division by `2π`, returning in the range ``[0,2π)``. - -This function computes a floating point representation of the modulus after division by -numerically exact `2π`, and is therefore not exactly the same as `mod(x,2π)`, which would -compute the modulus of `x` relative to division by the floating-point number `2π`. - -# Example -```jldoctest -julia> mod2pi(9*pi/4) -0.7853981633974481 -``` -""" -mod2pi(x) = rem2pi(x,RoundDown) - -# generic fallback; for number types, promotion.jl does promotion - -""" - muladd(x, y, z) - -Combined multiply-add, computes `x*y+z` in an efficient manner. This may on some systems be -equivalent to `x*y+z`, or to `fma(x,y,z)`. `muladd` is used to improve performance. -See [`fma`](@ref). - -# Example -```jldoctest -julia> muladd(3, 2, 1) -7 - -julia> 3 * 2 + 1 -7 -``` -""" -muladd(x,y,z) = x*y+z - -# Float16 definitions - -for func in (:sin,:cos,:tan,:asin,:acos,:atan,:sinh,:cosh,:tanh,:asinh,:acosh, - :atanh,:exp,:log,:log2,:log10,:sqrt,:lgamma,:log1p) - @eval begin - $func(a::Float16) = Float16($func(Float32(a))) - $func(a::Complex32) = Complex32($func(Complex64(a))) - end -end - -for func in (:atan2,:hypot) - @eval begin - $func(a::Float16,b::Float16) = Float16($func(Float32(a),Float32(b))) - end -end - -cbrt(a::Float16) = Float16(cbrt(Float32(a))) - -# More special functions -include(joinpath("special", "exp.jl")) -include(joinpath("special", "trig.jl")) -include(joinpath("special", "gamma.jl")) - -module JuliaLibm -include(joinpath("special", "log.jl")) -end - -end # module diff --git a/julia-0.6.3/share/julia/base/meta.jl b/julia-0.6.3/share/julia/base/meta.jl deleted file mode 100644 index bbe4c3f..0000000 --- a/julia-0.6.3/share/julia/base/meta.jl +++ /dev/null @@ -1,48 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -module Meta -# -# convenience functions for metaprogramming -# - -export quot, - isexpr, - show_sexpr - -quot(ex) = Expr(:quote, ex) - -isexpr(ex::Expr, head) = ex.head === head -isexpr(ex::Expr, heads::Union{Set,Vector,Tuple}) = in(ex.head, heads) -isexpr(ex, head) = false - -isexpr(ex, head, n::Int) = isexpr(ex, head) && length(ex.args) == n - - -# ---- show_sexpr: print an AST as an S-expression ---- - -show_sexpr(ex) = show_sexpr(STDOUT, ex) -show_sexpr(io::IO, ex) = show_sexpr(io, ex, 0) -show_sexpr(io::IO, ex, indent::Int) = show(io, ex) - -const sexpr_indent_width = 2 - -function show_sexpr(io::IO, ex::QuoteNode, indent::Int) - inner = indent + sexpr_indent_width - print(io, "(:quote, #QuoteNode\n", " "^inner) - show_sexpr(io, ex.value, inner) - print(io, '\n', " "^indent, ')') -end -function show_sexpr(io::IO, ex::Expr, indent::Int) - inner = indent + sexpr_indent_width - print(io, '(') - show_sexpr(io, ex.head, inner) - for arg in ex.args - print(io, ex.head === :block ? ",\n"*" "^inner : ", ") - show_sexpr(io, arg, inner) - end - if isempty(ex.args); print(io, ",)") - else print(io, (ex.head === :block ? "\n"*" "^indent : ""), ')') - end -end - -end # module diff --git a/julia-0.6.3/share/julia/base/methodshow.jl b/julia-0.6.3/share/julia/base/methodshow.jl deleted file mode 100644 index 9db6922..0000000 --- a/julia-0.6.3/share/julia/base/methodshow.jl +++ /dev/null @@ -1,302 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -# Method and method table pretty-printing - -function argtype_decl(env, n, sig::DataType, i::Int, nargs, isva::Bool) # -> (argname, argtype) - t = sig.parameters[i] - if i == nargs && isva && !isvarargtype(t) - t = Vararg{t,length(sig.parameters)-nargs+1} - end - if isa(n,Expr) - n = n.args[1] # handle n::T in arg list - end - s = string(n) - i = search(s,'#') - if i > 0 - s = s[1:i-1] - end - if t === Any && !isempty(s) - return s, "" - end - if isvarargtype(t) - v1, v2 = nothing, nothing - if isa(t, UnionAll) - v1 = t.var - t = t.body - if isa(t, UnionAll) - v2 = t.var - t = t.body - end - end - ut = unwrap_unionall(t) - tt, tn = ut.parameters[1], ut.parameters[2] - if isa(tn, TypeVar) && (tn === v1 || tn === v2) - if tt === Any || (isa(tt, TypeVar) && (tt === v1 || tt === v2)) - return string(s, "..."), "" - else - return s, string_with_env(env, tt) * "..." - end - end - return s, string_with_env(env, "Vararg{", tt, ",", tn, "}") - end - return s, string_with_env(env, t) -end - -function arg_decl_parts(m::Method) - tv = Any[] - sig = m.sig - while isa(sig, UnionAll) - push!(tv, sig.var) - sig = sig.body - end - file = m.file - line = m.line - if isdefined(m, :source) - argnames = Vector{Any}(m.nargs) - ccall(:jl_fill_argnames, Void, (Any, Any), m.source, argnames) - show_env = ImmutableDict{Symbol, Any}() - for t in tv - show_env = ImmutableDict(show_env, :unionall_env => t) - end - decls = Any[argtype_decl(show_env, argnames[i], sig, i, m.nargs, m.isva) - for i = 1:m.nargs] - else - decls = Any[("", "") for i = 1:length(sig.parameters)] - end - return tv, decls, file, line -end - -function kwarg_decl(m::Method, kwtype::DataType) - sig = rewrap_unionall(Tuple{kwtype, Core.AnyVector, unwrap_unionall(m.sig).parameters...}, m.sig) - kwli = ccall(:jl_methtable_lookup, Any, (Any, Any, UInt), kwtype.name.mt, sig, typemax(UInt)) - if kwli !== nothing - kwli = kwli::Method - src = uncompressed_ast(kwli, kwli.source) - kws = filter(x -> !('#' in string(x)), src.slotnames[(kwli.nargs + 1):end]) - # ensure the kwarg... is always printed last. The order of the arguments are not - # necessarily the same as defined in the function - i = findfirst(x -> endswith(string(x), "..."), kws) - i == 0 && return kws - push!(kws, kws[i]) - return deleteat!(kws, i) - end - return () -end - -function show_method_params(io::IO, tv) - if !isempty(tv) - print(io, " where ") - if length(tv) == 1 - show(io, tv[1]) - else - show_delim_array(io, tv, '{', ',', '}', false) - end - end -end - -function show(io::IO, m::Method; kwtype::Nullable{DataType}=Nullable{DataType}()) - tv, decls, file, line = arg_decl_parts(m) - sig = unwrap_unionall(m.sig) - ft0 = sig.parameters[1] - ft = unwrap_unionall(ft0) - d1 = decls[1] - if sig === Tuple - print(io, m.name) - decls = Any[(), ("...", "")] - elseif ft <: Function && isa(ft, DataType) && - isdefined(ft.name.module, ft.name.mt.name) && - # TODO: more accurate test? (tn.name === "#" name) - ft0 === typeof(getfield(ft.name.module, ft.name.mt.name)) - print(io, ft.name.mt.name) - elseif isa(ft, DataType) && ft.name === Type.body.name && isleaftype(ft) - f = ft.parameters[1] - if isa(f, DataType) && isempty(f.parameters) - print(io, f) - else - print(io, "(", d1[1], "::", d1[2], ")") - end - else - print(io, "(", d1[1], "::", d1[2], ")") - end - print(io, "(") - join(io, [isempty(d[2]) ? d[1] : d[1]*"::"*d[2] for d in decls[2:end]], - ", ", ", ") - if !isnull(kwtype) - kwargs = kwarg_decl(m, get(kwtype)) - if !isempty(kwargs) - print(io, "; ") - join(io, kwargs, ", ", ", ") - end - end - print(io, ")") - show_method_params(io, tv) - print(io, " in ", m.module) - if line > 0 - print(io, " at ", file, ":", line) - end -end - -function show_method_table(io::IO, ms::MethodList, max::Int=-1, header::Bool=true) - mt = ms.mt - name = mt.name - isself = isdefined(mt.module, name) && - typeof(getfield(mt.module, name)) <: Function - n = length(ms) - if header - m = n==1 ? "method" : "methods" - ns = isself ? string(name) : string("(::", name, ")") - what = startswith(ns, '@') ? "macro" : "generic function" - print(io, "# $n $m for ", what, " \"", ns, "\":") - end - kwtype = isdefined(mt, :kwsorter) ? Nullable{DataType}(typeof(mt.kwsorter)) : Nullable{DataType}() - n = rest = 0 - local last - for meth in ms - if max==-1 || n<max - println(io) - show(io, meth; kwtype=kwtype) - n += 1 - else - rest += 1 - last = meth - end - end - if rest > 0 - println(io) - if rest == 1 - show(io, last; kwtype=kwtype) - else - print(io,"... $rest methods not shown (use methods($name) to see them all)") - end - end -end - -show(io::IO, ms::MethodList) = show_method_table(io, ms) -show(io::IO, mt::MethodTable) = show_method_table(io, MethodList(mt)) - -function inbase(m::Module) - if m == Base - true - else - parent = module_parent(m) - parent === m ? false : inbase(parent) - end -end -fileurl(file) = let f = find_source_file(file); f === nothing ? "" : "file://"*f; end - -function url(m::Method) - M = m.module - (m.file == :null || m.file == :string) && return "" - file = string(m.file) - line = m.line - line <= 0 || ismatch(r"In\[[0-9]+\]", file) && return "" - is_windows() && (file = replace(file, '\\', '/')) - if inbase(M) - if isempty(Base.GIT_VERSION_INFO.commit) - # this url will only work if we're on a tagged release - return "https://github.com/JuliaLang/julia/tree/v$VERSION/base/$file#L$line" - else - return "https://github.com/JuliaLang/julia/tree/$(Base.GIT_VERSION_INFO.commit)/base/$file#L$line" - end - else - try - d = dirname(file) - return LibGit2.with(LibGit2.GitRepoExt(d)) do repo - LibGit2.with(LibGit2.GitConfig(repo)) do cfg - u = LibGit2.get(cfg, "remote.origin.url", "") - u = match(LibGit2.GITHUB_REGEX,u).captures[1] - commit = string(LibGit2.head_oid(repo)) - root = LibGit2.path(repo) - if startswith(file, root) || startswith(realpath(file), root) - "https://github.com/$u/tree/$commit/"*file[length(root)+1:end]*"#L$line" - else - fileurl(file) - end - end - end - catch - return fileurl(file) - end - end -end - -function show(io::IO, ::MIME"text/html", m::Method; kwtype::Nullable{DataType}=Nullable{DataType}()) - tv, decls, file, line = arg_decl_parts(m) - sig = unwrap_unionall(m.sig) - ft0 = sig.parameters[1] - ft = unwrap_unionall(ft0) - d1 = decls[1] - if ft <: Function && isa(ft, DataType) && - isdefined(ft.name.module, ft.name.mt.name) && - ft0 === typeof(getfield(ft.name.module, ft.name.mt.name)) - print(io, ft.name.mt.name) - elseif isa(ft, DataType) && ft.name === Type.body.name && isleaftype(ft) - f = ft.parameters[1] - if isa(f, DataType) && isempty(f.parameters) - print(io, f) - else - print(io, "(", d1[1], "::<b>", d1[2], "</b>)") - end - else - print(io, "(", d1[1], "::<b>", d1[2], "</b>)") - end - if !isempty(tv) - print(io,"<i>") - show_delim_array(io, tv, '{', ',', '}', false) - print(io,"</i>") - end - print(io, "(") - join(io, [isempty(d[2]) ? d[1] : d[1]*"::<b>"*d[2]*"</b>" - for d in decls[2:end]], ", ", ", ") - if !isnull(kwtype) - kwargs = kwarg_decl(m, get(kwtype)) - if !isempty(kwargs) - print(io, "; <i>") - join(io, kwargs, ", ", ", ") - print(io, "</i>") - end - end - print(io, ")") - if line > 0 - u = url(m) - if isempty(u) - print(io, " at ", file, ":", line) - else - print(io, """ at <a href="$u" target="_blank">""", - file, ":", line, "</a>") - end - end -end - -function show(io::IO, mime::MIME"text/html", ms::MethodList) - mt = ms.mt - name = mt.name - n = length(ms) - meths = n==1 ? "method" : "methods" - ns = string(name) - what = startswith(ns, '@') ? "macro" : "generic function" - print(io, "$n $meths for ", what, " <b>$ns</b>:<ul>") - kwtype = isdefined(mt, :kwsorter) ? Nullable{DataType}(typeof(mt.kwsorter)) : Nullable{DataType}() - for meth in ms - print(io, "<li> ") - show(io, mime, meth; kwtype=kwtype) - print(io, "</li> ") - end - print(io, "</ul>") -end - -show(io::IO, mime::MIME"text/html", mt::MethodTable) = show(io, mime, MethodList(mt)) - -# pretty-printing of Vector{Method} for output of methodswith: - -function show(io::IO, mime::MIME"text/html", mt::AbstractVector{Method}) - print(io, summary(mt)) - if !isempty(mt) - print(io, ":<ul>") - for d in mt - print(io, "<li> ") - show(io, mime, d) - end - print(io, "</ul>") - end -end diff --git a/julia-0.6.3/share/julia/base/mmap.jl b/julia-0.6.3/share/julia/base/mmap.jl deleted file mode 100644 index eaac57e..0000000 --- a/julia-0.6.3/share/julia/base/mmap.jl +++ /dev/null @@ -1,220 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -module Mmap - -const PAGESIZE = Int(is_unix() ? ccall(:jl_getpagesize, Clong, ()) : ccall(:jl_getallocationgranularity, Clong, ())) - -# for mmaps not backed by files -mutable struct Anonymous <: IO - name::AbstractString - readonly::Bool - create::Bool -end - -Anonymous() = Anonymous("",false,true) -Base.isopen(::Anonymous) = true -Base.isreadable(::Anonymous) = true -Base.iswritable(a::Anonymous) = !a.readonly - -const INVALID_HANDLE_VALUE = -1 -# const used for zeroed, anonymous memory; same value on Windows & Unix; say what?! -gethandle(io::Anonymous) = INVALID_HANDLE_VALUE - -# platform-specific mmap utilities -if is_unix() - -const PROT_READ = Cint(1) -const PROT_WRITE = Cint(2) -const MAP_SHARED = Cint(1) -const MAP_PRIVATE = Cint(2) -const MAP_ANONYMOUS = Cint(is_bsd() ? 0x1000 : 0x20) -const F_GETFL = Cint(3) - -gethandle(io::IO) = fd(io) - -# Determine a stream's read/write mode, and return prot & flags appropriate for mmap -function settings(s::Int, shared::Bool) - flags = shared ? MAP_SHARED : MAP_PRIVATE - if s == INVALID_HANDLE_VALUE - flags |= MAP_ANONYMOUS - prot = PROT_READ | PROT_WRITE - else - mode = ccall(:fcntl,Cint,(Cint,Cint),s,F_GETFL) - systemerror("fcntl F_GETFL", mode == -1) - mode = mode & 3 - prot = mode == 0 ? PROT_READ : mode == 1 ? PROT_WRITE : PROT_READ | PROT_WRITE - if prot & PROT_READ == 0 - throw(ArgumentError("mmap requires read permissions on the file (choose r+)")) - end - end - return prot, flags, (prot & PROT_WRITE) > 0 -end - -# Before mapping, grow the file to sufficient size -# Note: a few mappable streams do not support lseek. When Julia -# supports structures in ccall, switch to fstat. -grow!(::Anonymous,o::Integer,l::Integer) = return -function grow!(io::IO, offset::Integer, len::Integer) - pos = position(io) - filelen = filesize(io) - if filelen < offset + len - failure = ccall(:jl_ftruncate, Cint, (Cint, Int64), fd(io), offset+len) - Base.systemerror(:ftruncate, failure != 0) - end - seek(io, pos) - return -end - -elseif is_windows() - -const DWORD = Culong - -const PAGE_READONLY = DWORD(0x02) -const PAGE_READWRITE = DWORD(0x04) -const PAGE_WRITECOPY = DWORD(0x08) -const PAGE_EXECUTE_READ = DWORD(0x20) -const PAGE_EXECUTE_READWRITE = DWORD(0x40) -const PAGE_EXECUTE_WRITECOPY = DWORD(0x80) -const FILE_MAP_COPY = DWORD(0x01) -const FILE_MAP_WRITE = DWORD(0x02) -const FILE_MAP_READ = DWORD(0x04) -const FILE_MAP_EXECUTE = DWORD(0x20) - -function gethandle(io::IO) - handle = Libc._get_osfhandle(RawFD(fd(io))).handle - systemerror("could not get handle for file to map: $(Libc.FormatMessage())", handle == -1) - return Int(handle) -end - -settings(sh::Anonymous) = sh.name, sh.readonly, sh.create -settings(io::IO) = Ptr{Cwchar_t}(0), isreadonly(io), true - -else - error("mmap not defined for this OS") -end # os-test - -# core implementation of mmap -function mmap(io::IO, - ::Type{Array{T,N}}=Vector{UInt8}, - dims::NTuple{N,Integer}=(div(filesize(io)-position(io),sizeof(T)),), - offset::Integer=position(io); grow::Bool=true, shared::Bool=true) where {T,N} - # check inputs - isopen(io) || throw(ArgumentError("$io must be open to mmap")) - isbits(T) || throw(ArgumentError("unable to mmap $T; must satisfy isbits(T) == true")) - - len = prod(dims) * sizeof(T) - len >= 0 || throw(ArgumentError("requested size must be ≥ 0, got $len")) - len == 0 && return Array{T}(ntuple(x->0,Val{N})) - len < typemax(Int) - PAGESIZE || throw(ArgumentError("requested size must be < $(typemax(Int)-PAGESIZE), got $len")) - - offset >= 0 || throw(ArgumentError("requested offset must be ≥ 0, got $offset")) - - # shift `offset` to start of page boundary - offset_page::Int64 = div(offset, PAGESIZE) * PAGESIZE - # add (offset - offset_page) to `len` to get total length of memory-mapped region - mmaplen = (offset - offset_page) + len - - file_desc = gethandle(io) - # platform-specific mmapping - @static if is_unix() - prot, flags, iswrite = settings(file_desc, shared) - iswrite && grow && grow!(io, offset, len) - # mmap the file - ptr = ccall(:jl_mmap, Ptr{Void}, (Ptr{Void}, Csize_t, Cint, Cint, Cint, Int64), C_NULL, mmaplen, prot, flags, file_desc, offset_page) - systemerror("memory mapping failed", reinterpret(Int,ptr) == -1) - else - name, readonly, create = settings(io) - szfile = convert(Csize_t, len + offset) - readonly && szfile > filesize(io) && throw(ArgumentError("unable to increase file size to $szfile due to read-only permissions")) - handle = create ? ccall(:CreateFileMappingW, stdcall, Ptr{Void}, (Cptrdiff_t, Ptr{Void}, DWORD, DWORD, DWORD, Cwstring), - file_desc, C_NULL, readonly ? PAGE_READONLY : PAGE_READWRITE, szfile >> 32, szfile & typemax(UInt32), name) : - ccall(:OpenFileMappingW, stdcall, Ptr{Void}, (DWORD, Cint, Cwstring), - readonly ? FILE_MAP_READ : FILE_MAP_WRITE, true, name) - handle == C_NULL && error("could not create file mapping: $(Libc.FormatMessage())") - ptr = ccall(:MapViewOfFile, stdcall, Ptr{Void}, (Ptr{Void}, DWORD, DWORD, DWORD, Csize_t), - handle, readonly ? FILE_MAP_READ : FILE_MAP_WRITE, offset_page >> 32, offset_page & typemax(UInt32), (offset - offset_page) + len) - ptr == C_NULL && error("could not create mapping view: $(Libc.FormatMessage())") - end # os-test - # convert mmapped region to Julia Array at `ptr + (offset - offset_page)` since file was mapped at offset_page - A = unsafe_wrap(Array, convert(Ptr{T}, UInt(ptr) + UInt(offset - offset_page)), dims) - finalizer(A, function(x) - @static if is_unix() - systemerror("munmap", ccall(:munmap, Cint, (Ptr{Void}, Int), ptr, mmaplen) != 0) - else - status = ccall(:UnmapViewOfFile, stdcall, Cint, (Ptr{Void},), ptr)!=0 - status |= ccall(:CloseHandle, stdcall, Cint, (Ptr{Void},), handle)!=0 - status || error("could not unmap view: $(Libc.FormatMessage())") - end - end) - return A -end - -mmap(file::AbstractString, - ::Type{T}=Vector{UInt8}, - dims::NTuple{N,Integer}=(div(filesize(file),sizeof(eltype(T))),), - offset::Integer=Int64(0); grow::Bool=true, shared::Bool=true) where {T<:Array,N} = - open(io->mmap(io, T, dims, offset; grow=grow, shared=shared), file, isfile(file) ? "r+" : "w+")::Array{eltype(T),N} - -# using a length argument instead of dims -mmap(io::IO, ::Type{T}, len::Integer, offset::Integer=position(io); grow::Bool=true, shared::Bool=true) where {T<:Array} = - mmap(io, T, (len,), offset; grow=grow, shared=shared) -mmap(file::AbstractString, ::Type{T}, len::Integer, offset::Integer=Int64(0); grow::Bool=true, shared::Bool=true) where {T<:Array} = - open(io->mmap(io, T, (len,), offset; grow=grow, shared=shared), file, isfile(file) ? "r+" : "w+")::Vector{eltype(T)} - -# constructors for non-file-backed (anonymous) mmaps -mmap(::Type{T}, dims::NTuple{N,Integer}; shared::Bool=true) where {T<:Array,N} = mmap(Anonymous(), T, dims, Int64(0); shared=shared) -mmap(::Type{T}, i::Integer...; shared::Bool=true) where {T<:Array} = mmap(Anonymous(), T, convert(Tuple{Vararg{Int}},i), Int64(0); shared=shared) - -function mmap(io::IOStream, ::Type{<:BitArray}, dims::NTuple{N,Integer}, - offset::Int64=position(io); grow::Bool=true, shared::Bool=true) where N - n = prod(dims) - nc = Base.num_bit_chunks(n) - chunks = mmap(io, Vector{UInt64}, (nc,), offset; grow=grow, shared=shared) - if !isreadonly(io) - chunks[end] &= Base._msk_end(n) - else - if chunks[end] != chunks[end] & Base._msk_end(n) - throw(ArgumentError("the given file does not contain a valid BitArray of size $(join(dims, 'x')) (open with \"r+\" mode to override)")) - end - end - B = BitArray{N}(ntuple(i->0,Val{N})...) - B.chunks = chunks - B.len = n - if N != 1 - B.dims = dims - end - return B -end - -mmap(file::AbstractString, ::Type{T}, dims::NTuple{N,Integer}, offset::Integer=Int64(0);grow::Bool=true, shared::Bool=true) where {T<:BitArray,N} = - open(io->mmap(io, T, dims, offset; grow=grow, shared=shared), file, isfile(file) ? "r+" : "w+")::BitArray{N} - -# using a length argument instead of dims -mmap(io::IO, ::Type{T}, len::Integer, offset::Integer=position(io); grow::Bool=true, shared::Bool=true) where {T<:BitArray} = - mmap(io, T, (len,), offset; grow=grow, shared=shared) -mmap(file::AbstractString, ::Type{T}, len::Integer, offset::Integer=Int64(0); grow::Bool=true, shared::Bool=true) where {T<:BitArray} = - open(io->mmap(io, T, (len,), offset; grow=grow, shared=shared), file, isfile(file) ? "r+" : "w+")::BitVector - -# constructors for non-file-backed (anonymous) mmaps -mmap(::Type{T}, dims::NTuple{N,Integer}; shared::Bool=true) where {T<:BitArray,N} = mmap(Anonymous(), T, dims, Int64(0); shared=shared) -mmap(::Type{T}, i::Integer...; shared::Bool=true) where {T<:BitArray} = mmap(Anonymous(), T, convert(Tuple{Vararg{Int}},i), Int64(0); shared=shared) - -# msync flags for unix -const MS_ASYNC = 1 -const MS_INVALIDATE = 2 -const MS_SYNC = 4 - -function sync!(m::Array{T}, flags::Integer=MS_SYNC) where T - offset = rem(UInt(pointer(m)), PAGESIZE) - ptr = pointer(m) - offset - @static if is_unix() - systemerror("msync", - ccall(:msync, Cint, (Ptr{Void}, Csize_t, Cint), ptr, length(m) * sizeof(T), flags) != 0) - else - systemerror("could not FlushViewOfFile: $(Libc.FormatMessage())", - ccall(:FlushViewOfFile, stdcall, Cint, (Ptr{Void}, Csize_t), ptr, length(m)) == 0) - end -end -sync!(B::BitArray, flags::Integer=MS_SYNC) = sync!(B.chunks, flags) - -end # module diff --git a/julia-0.6.3/share/julia/base/mpfr.jl b/julia-0.6.3/share/julia/base/mpfr.jl deleted file mode 100644 index ccc4931..0000000 --- a/julia-0.6.3/share/julia/base/mpfr.jl +++ /dev/null @@ -1,940 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -module MPFR - -export - BigFloat, - setprecision - -import - Base: (*), +, -, /, <, <=, ==, >, >=, ^, ceil, cmp, convert, copysign, div, - exp, exp2, exponent, factorial, floor, fma, hypot, isinteger, - isfinite, isinf, isnan, ldexp, log, log2, log10, max, min, mod, modf, - nextfloat, prevfloat, promote_rule, rem, rem2pi, round, show, - sum, sqrt, string, print, trunc, precision, exp10, expm1, - gamma, lgamma, log1p, - eps, signbit, sin, cos, tan, sec, csc, cot, acos, asin, atan, - cosh, sinh, tanh, sech, csch, coth, acosh, asinh, atanh, atan2, - cbrt, typemax, typemin, unsafe_trunc, realmin, realmax, rounding, - setrounding, maxintfloat, widen, significand, frexp, tryparse, iszero - -import Base.Rounding: rounding_raw, setrounding_raw - -import Base.GMP: ClongMax, CulongMax, CdoubleMax, Limb - -import Base.Math.lgamma_r - -function __init__() - try - # set exponent to full range by default - set_emin!(get_emin_min()) - set_emax!(get_emax_max()) - catch ex - Base.showerror_nostdio(ex, - "WARNING: Error during initialization of module MPFR") - end -end - -const ROUNDING_MODE = Ref{Cint}(0) -const DEFAULT_PRECISION = [256] - -# Basic type and initialization definitions - -""" - BigFloat <: AbstractFloat - -Arbitrary precision floating point number type. -""" -mutable struct BigFloat <: AbstractFloat - prec::Clong - sign::Cint - exp::Clong - d::Ptr{Limb} - - function BigFloat() - prec = precision(BigFloat) - z = new(zero(Clong), zero(Cint), zero(Clong), C_NULL) - ccall((:mpfr_init2,:libmpfr), Void, (Ptr{BigFloat}, Clong), &z, prec) - finalizer(z, cglobal((:mpfr_clear, :libmpfr))) - return z - end - - # Not recommended for general use: - function BigFloat(prec::Clong, sign::Cint, exp::Clong, d::Ptr{Void}) - new(prec, sign, exp, d) - end -end - -""" - BigFloat(x) - -Create an arbitrary precision floating point number. `x` may be an [`Integer`](@ref), a -[`Float64`](@ref) or a [`BigInt`](@ref). The usual mathematical operators are defined for -this type, and results are promoted to a [`BigFloat`](@ref). - -Note that because decimal literals are converted to floating point numbers when parsed, -`BigFloat(2.1)` may not yield what you expect. You may instead prefer to initialize -constants from strings via [`parse`](@ref), or using the `big` string literal. - -```jldoctest -julia> BigFloat(2.1) -2.100000000000000088817841970012523233890533447265625000000000000000000000000000 - -julia> big"2.1" -2.099999999999999999999999999999999999999999999999999999999999999999999999999986 -``` -""" -BigFloat(x) - -widen(::Type{Float64}) = BigFloat -widen(::Type{BigFloat}) = BigFloat - -convert(::Type{BigFloat}, x::BigFloat) = x - -# convert to BigFloat -for (fJ, fC) in ((:si,:Clong), (:ui,:Culong), (:d,:Float64)) - @eval begin - function convert(::Type{BigFloat}, x::($fC)) - z = BigFloat() - ccall(($(string(:mpfr_set_,fJ)), :libmpfr), Int32, (Ptr{BigFloat}, ($fC), Int32), &z, x, ROUNDING_MODE[]) - return z - end - end -end - -function convert(::Type{BigFloat}, x::BigInt) - z = BigFloat() - ccall((:mpfr_set_z, :libmpfr), Int32, (Ptr{BigFloat}, Ptr{BigInt}, Int32), &z, &x, ROUNDING_MODE[]) - return z -end - -convert(::Type{BigFloat}, x::Integer) = BigFloat(BigInt(x)) - -convert(::Type{BigFloat}, x::Union{Bool,Int8,Int16,Int32}) = BigFloat(convert(Clong,x)) -convert(::Type{BigFloat}, x::Union{UInt8,UInt16,UInt32}) = BigFloat(convert(Culong,x)) - -convert(::Type{BigFloat}, x::Union{Float16,Float32}) = BigFloat(Float64(x)) -convert(::Type{BigFloat}, x::Rational) = BigFloat(numerator(x)) / BigFloat(denominator(x)) - -function tryparse(::Type{BigFloat}, s::AbstractString, base::Int=0) - z = BigFloat() - err = ccall((:mpfr_set_str, :libmpfr), Int32, (Ptr{BigFloat}, Cstring, Int32, Int32), &z, s, base, ROUNDING_MODE[]) - err == 0 ? Nullable(z) : Nullable{BigFloat}() -end - -convert(::Type{Rational}, x::BigFloat) = convert(Rational{BigInt}, x) -convert(::Type{AbstractFloat}, x::BigInt) = BigFloat(x) - -# generic constructor with arbitrary precision: -""" - BigFloat(x, prec::Int) - -Create a representation of `x` as a [`BigFloat`](@ref) with precision `prec`. -""" -function BigFloat(x, prec::Int) - setprecision(BigFloat, prec) do - BigFloat(x) - end -end - -""" - BigFloat(x, prec::Int, rounding::RoundingMode) - -Create a representation of `x` as a [`BigFloat`](@ref) with precision `prec` and -rounding mode `rounding`. -""" -function BigFloat(x, prec::Int, rounding::RoundingMode) - setrounding(BigFloat, rounding) do - BigFloat(x, prec) - end -end - -""" - BigFloat(x, rounding::RoundingMode) - -Create a representation of `x` as a [`BigFloat`](@ref) with the current global precision -and rounding mode `rounding`. -""" -function BigFloat(x::Union{Integer, AbstractFloat, String}, rounding::RoundingMode) - BigFloat(x, precision(BigFloat), rounding) -end - -""" - BigFloat(x::String) - -Create a representation of the string `x` as a [`BigFloat`](@ref). -""" -BigFloat(x::String) = parse(BigFloat, x) - - -## BigFloat -> Integer -function unsafe_cast(::Type{Int64}, x::BigFloat, ri::Cint) - ccall((:__gmpfr_mpfr_get_sj,:libmpfr), Cintmax_t, - (Ptr{BigFloat}, Cint), &x, ri) -end -function unsafe_cast(::Type{UInt64}, x::BigFloat, ri::Cint) - ccall((:__gmpfr_mpfr_get_uj,:libmpfr), Cuintmax_t, - (Ptr{BigFloat}, Cint), &x, ri) -end - -function unsafe_cast(::Type{T}, x::BigFloat, ri::Cint) where T<:Signed - unsafe_cast(Int64, x, ri) % T -end -function unsafe_cast(::Type{T}, x::BigFloat, ri::Cint) where T<:Unsigned - unsafe_cast(UInt64, x, ri) % T -end - -function unsafe_cast(::Type{BigInt}, x::BigFloat, ri::Cint) - # actually safe, just keep naming consistent - z = BigInt() - ccall((:mpfr_get_z, :libmpfr), Int32, (Ptr{BigInt}, Ptr{BigFloat}, Int32), - &z, &x, ri) - z -end -unsafe_cast(::Type{Int128}, x::BigFloat, ri::Cint) = Int128(unsafe_cast(BigInt,x,ri)) -unsafe_cast(::Type{UInt128}, x::BigFloat, ri::Cint) = UInt128(unsafe_cast(BigInt,x,ri)) -unsafe_cast(::Type{T}, x::BigFloat, r::RoundingMode) where {T<:Integer} = unsafe_cast(T,x,to_mpfr(r)) - -unsafe_trunc(::Type{T}, x::BigFloat) where {T<:Integer} = unsafe_cast(T,x,RoundToZero) - -function trunc{T<:Union{Signed,Unsigned}}(::Type{T}, x::BigFloat) - (typemin(T) <= x <= typemax(T)) || throw(InexactError()) - unsafe_cast(T,x,RoundToZero) -end -function floor(::Type{T}, x::BigFloat) where T<:Union{Signed,Unsigned} - (typemin(T) <= x <= typemax(T)) || throw(InexactError()) - unsafe_cast(T,x,RoundDown) -end -function ceil(::Type{T}, x::BigFloat) where T<:Union{Signed,Unsigned} - (typemin(T) <= x <= typemax(T)) || throw(InexactError()) - unsafe_cast(T,x,RoundUp) -end - -function round(::Type{T}, x::BigFloat) where T<:Union{Signed,Unsigned} - (typemin(T) <= x <= typemax(T)) || throw(InexactError()) - unsafe_cast(T,x,ROUNDING_MODE[]) -end - -trunc(::Type{BigInt}, x::BigFloat) = unsafe_cast(BigInt, x, RoundToZero) -floor(::Type{BigInt}, x::BigFloat) = unsafe_cast(BigInt, x, RoundDown) -ceil(::Type{BigInt}, x::BigFloat) = unsafe_cast(BigInt, x, RoundUp) -round(::Type{BigInt}, x::BigFloat) = unsafe_cast(BigInt, x, ROUNDING_MODE[]) - -# convert/round/trunc/floor/ceil(Integer, x) should return a BigInt -trunc(::Type{Integer}, x::BigFloat) = trunc(BigInt, x) -floor(::Type{Integer}, x::BigFloat) = floor(BigInt, x) -ceil(::Type{Integer}, x::BigFloat) = ceil(BigInt, x) -round(::Type{Integer}, x::BigFloat) = round(BigInt, x) - -convert(::Type{Bool}, x::BigFloat) = x==0 ? false : x==1 ? true : throw(InexactError()) -function convert(::Type{BigInt},x::BigFloat) - isinteger(x) || throw(InexactError()) - trunc(BigInt,x) -end - -function convert(::Type{Integer}, x::BigFloat) - isinteger(x) || throw(InexactError()) - trunc(Integer,x) -end -function convert(::Type{T},x::BigFloat) where T<:Integer - isinteger(x) || throw(InexactError()) - trunc(T,x) -end - -## BigFloat -> AbstractFloat -convert(::Type{Float64}, x::BigFloat) = - ccall((:mpfr_get_d,:libmpfr), Float64, (Ptr{BigFloat}, Int32), &x, ROUNDING_MODE[]) -convert(::Type{Float32}, x::BigFloat) = - ccall((:mpfr_get_flt,:libmpfr), Float32, (Ptr{BigFloat}, Int32), &x, ROUNDING_MODE[]) -# TODO: avoid double rounding -convert(::Type{Float16}, x::BigFloat) = convert(Float16, convert(Float32, x)) - -Float64(x::BigFloat, r::RoundingMode) = - ccall((:mpfr_get_d,:libmpfr), Float64, (Ptr{BigFloat}, Int32), &x, to_mpfr(r)) -Float32(x::BigFloat, r::RoundingMode) = - ccall((:mpfr_get_flt,:libmpfr), Float32, (Ptr{BigFloat}, Int32), &x, to_mpfr(r)) -# TODO: avoid double rounding -Float16(x::BigFloat, r::RoundingMode) = - convert(Float16, Float32(x, r)) - -promote_rule(::Type{BigFloat}, ::Type{<:Real}) = BigFloat -promote_rule(::Type{BigInt}, ::Type{<:AbstractFloat}) = BigFloat -promote_rule(::Type{BigFloat}, ::Type{<:AbstractFloat}) = BigFloat - -function convert(::Type{Rational{BigInt}}, x::AbstractFloat) - if isnan(x); return zero(BigInt)//zero(BigInt); end - if isinf(x); return copysign(one(BigInt),x)//zero(BigInt); end - if x == 0; return zero(BigInt) // one(BigInt); end - s = max(precision(x) - exponent(x), 0) - BigInt(ldexp(x,s)) // (BigInt(1) << s) -end - -# Basic arithmetic without promotion -for (fJ, fC) in ((:+,:add), (:*,:mul)) - @eval begin - # BigFloat - function ($fJ)(x::BigFloat, y::BigFloat) - z = BigFloat() - ccall(($(string(:mpfr_,fC)),:libmpfr), Int32, (Ptr{BigFloat}, Ptr{BigFloat}, Ptr{BigFloat}, Int32), &z, &x, &y, ROUNDING_MODE[]) - return z - end - - # Unsigned Integer - function ($fJ)(x::BigFloat, c::CulongMax) - z = BigFloat() - ccall(($(string(:mpfr_,fC,:_ui)), :libmpfr), Int32, (Ptr{BigFloat}, Ptr{BigFloat}, Culong, Int32), &z, &x, c, ROUNDING_MODE[]) - return z - end - ($fJ)(c::CulongMax, x::BigFloat) = ($fJ)(x,c) - - # Signed Integer - function ($fJ)(x::BigFloat, c::ClongMax) - z = BigFloat() - ccall(($(string(:mpfr_,fC,:_si)), :libmpfr), Int32, (Ptr{BigFloat}, Ptr{BigFloat}, Clong, Int32), &z, &x, c, ROUNDING_MODE[]) - return z - end - ($fJ)(c::ClongMax, x::BigFloat) = ($fJ)(x,c) - - # Float32/Float64 - function ($fJ)(x::BigFloat, c::CdoubleMax) - z = BigFloat() - ccall(($(string(:mpfr_,fC,:_d)), :libmpfr), Int32, (Ptr{BigFloat}, Ptr{BigFloat}, Cdouble, Int32), &z, &x, c, ROUNDING_MODE[]) - return z - end - ($fJ)(c::CdoubleMax, x::BigFloat) = ($fJ)(x,c) - - # BigInt - function ($fJ)(x::BigFloat, c::BigInt) - z = BigFloat() - ccall(($(string(:mpfr_,fC,:_z)), :libmpfr), Int32, (Ptr{BigFloat}, Ptr{BigFloat}, Ptr{BigInt}, Int32), &z, &x, &c, ROUNDING_MODE[]) - return z - end - ($fJ)(c::BigInt, x::BigFloat) = ($fJ)(x,c) - end -end - -for (fJ, fC) in ((:-,:sub), (:/,:div)) - @eval begin - # BigFloat - function ($fJ)(x::BigFloat, y::BigFloat) - z = BigFloat() - ccall(($(string(:mpfr_,fC)),:libmpfr), Int32, (Ptr{BigFloat}, Ptr{BigFloat}, Ptr{BigFloat}, Int32), &z, &x, &y, ROUNDING_MODE[]) - return z - end - - # Unsigned Int - function ($fJ)(x::BigFloat, c::CulongMax) - z = BigFloat() - ccall(($(string(:mpfr_,fC,:_ui)), :libmpfr), Int32, (Ptr{BigFloat}, Ptr{BigFloat}, Culong, Int32), &z, &x, c, ROUNDING_MODE[]) - return z - end - function ($fJ)(c::CulongMax, x::BigFloat) - z = BigFloat() - ccall(($(string(:mpfr_,:ui_,fC)), :libmpfr), Int32, (Ptr{BigFloat}, Culong, Ptr{BigFloat}, Int32), &z, c, &x, ROUNDING_MODE[]) - return z - end - - # Signed Integer - function ($fJ)(x::BigFloat, c::ClongMax) - z = BigFloat() - ccall(($(string(:mpfr_,fC,:_si)), :libmpfr), Int32, (Ptr{BigFloat}, Ptr{BigFloat}, Clong, Int32), &z, &x, c, ROUNDING_MODE[]) - return z - end - function ($fJ)(c::ClongMax, x::BigFloat) - z = BigFloat() - ccall(($(string(:mpfr_,:si_,fC)), :libmpfr), Int32, (Ptr{BigFloat}, Clong, Ptr{BigFloat}, Int32), &z, c, &x, ROUNDING_MODE[]) - return z - end - - # Float32/Float64 - function ($fJ)(x::BigFloat, c::CdoubleMax) - z = BigFloat() - ccall(($(string(:mpfr_,fC,:_d)), :libmpfr), Int32, (Ptr{BigFloat}, Ptr{BigFloat}, Cdouble, Int32), &z, &x, c, ROUNDING_MODE[]) - return z - end - function ($fJ)(c::CdoubleMax, x::BigFloat) - z = BigFloat() - ccall(($(string(:mpfr_,:d_,fC)), :libmpfr), Int32, (Ptr{BigFloat}, Cdouble, Ptr{BigFloat}, Int32), &z, c, &x, ROUNDING_MODE[]) - return z - end - - # BigInt - function ($fJ)(x::BigFloat, c::BigInt) - z = BigFloat() - ccall(($(string(:mpfr_,fC,:_z)), :libmpfr), Int32, (Ptr{BigFloat}, Ptr{BigFloat}, Ptr{BigInt}, Int32), &z, &x, &c, ROUNDING_MODE[]) - return z - end - # no :mpfr_z_div function - end -end - -function -(c::BigInt, x::BigFloat) - z = BigFloat() - ccall((:mpfr_z_sub, :libmpfr), Int32, (Ptr{BigFloat}, Ptr{BigInt}, Ptr{BigFloat}, Int32), &z, &c, &x, ROUNDING_MODE[]) - return z -end - -function fma(x::BigFloat, y::BigFloat, z::BigFloat) - r = BigFloat() - ccall(("mpfr_fma",:libmpfr), Int32, (Ptr{BigFloat}, Ptr{BigFloat}, Ptr{BigFloat}, Ptr{BigFloat}, Int32), &r, &x, &y, &z, ROUNDING_MODE[]) - return r -end - -# div -# BigFloat -function div(x::BigFloat, y::BigFloat) - z = BigFloat() - ccall((:mpfr_div,:libmpfr), Int32, (Ptr{BigFloat}, Ptr{BigFloat}, Ptr{BigFloat}, Int32), &z, &x, &y, to_mpfr(RoundToZero)) - ccall((:mpfr_trunc, :libmpfr), Int32, (Ptr{BigFloat}, Ptr{BigFloat}), &z, &z) - return z -end - -# Unsigned Int -function div(x::BigFloat, c::CulongMax) - z = BigFloat() - ccall((:mpfr_div_ui, :libmpfr), Int32, (Ptr{BigFloat}, Ptr{BigFloat}, Culong, Int32), &z, &x, c, to_mpfr(RoundToZero)) - ccall((:mpfr_trunc, :libmpfr), Int32, (Ptr{BigFloat}, Ptr{BigFloat}), &z, &z) - return z -end -function div(c::CulongMax, x::BigFloat) - z = BigFloat() - ccall((:mpfr_ui_div, :libmpfr), Int32, (Ptr{BigFloat}, Culong, Ptr{BigFloat}, Int32), &z, c, &x, to_mpfr(RoundToZero)) - ccall((:mpfr_trunc, :libmpfr), Int32, (Ptr{BigFloat}, Ptr{BigFloat}), &z, &z) - return z -end - -# Signed Integer -function div(x::BigFloat, c::ClongMax) - z = BigFloat() - ccall((:mpfr_div_si, :libmpfr), Int32, (Ptr{BigFloat}, Ptr{BigFloat}, Clong, Int32), &z, &x, c, to_mpfr(RoundToZero)) - ccall((:mpfr_trunc, :libmpfr), Int32, (Ptr{BigFloat}, Ptr{BigFloat}), &z, &z) - return z -end -function div(c::ClongMax, x::BigFloat) - z = BigFloat() - ccall((:mpfr_si_div, :libmpfr), Int32, (Ptr{BigFloat}, Clong, Ptr{BigFloat}, Int32), &z, c, &x, to_mpfr(RoundToZero)) - ccall((:mpfr_trunc, :libmpfr), Int32, (Ptr{BigFloat}, Ptr{BigFloat}), &z, &z) - return z -end - -# Float32/Float64 -function div(x::BigFloat, c::CdoubleMax) - z = BigFloat() - ccall((:mpfr_div_d, :libmpfr), Int32, (Ptr{BigFloat}, Ptr{BigFloat}, Cdouble, Int32), &z, &x, c, to_mpfr(RoundToZero)) - ccall((:mpfr_trunc, :libmpfr), Int32, (Ptr{BigFloat}, Ptr{BigFloat}), &z, &z) - return z -end -function div(c::CdoubleMax, x::BigFloat) - z = BigFloat() - ccall((:mpfr_d_div, :libmpfr), Int32, (Ptr{BigFloat}, Cdouble, Ptr{BigFloat}, Int32), &z, c, &x, to_mpfr(RoundToZero)) - ccall((:mpfr_trunc, :libmpfr), Int32, (Ptr{BigFloat}, Ptr{BigFloat}), &z, &z) - return z -end - -# BigInt -function div(x::BigFloat, c::BigInt) - z = BigFloat() - ccall((:mpfr_div_z, :libmpfr), Int32, (Ptr{BigFloat}, Ptr{BigFloat}, Ptr{BigInt}, Int32), &z, &x, &c, to_mpfr(RoundToZero)) - ccall((:mpfr_trunc, :libmpfr), Int32, (Ptr{BigFloat}, Ptr{BigFloat}), &z, &z) - return z -end - - -# More efficient commutative operations -for (fJ, fC, fI) in ((:+, :add, 0), (:*, :mul, 1)) - @eval begin - function ($fJ)(a::BigFloat, b::BigFloat, c::BigFloat) - z = BigFloat() - ccall(($(string(:mpfr_,fC)), :libmpfr), Int32, (Ptr{BigFloat}, Ptr{BigFloat}, Ptr{BigFloat}, Int32), &z, &a, &b, ROUNDING_MODE[]) - ccall(($(string(:mpfr_,fC)), :libmpfr), Int32, (Ptr{BigFloat}, Ptr{BigFloat}, Ptr{BigFloat}, Int32), &z, &z, &c, ROUNDING_MODE[]) - return z - end - function ($fJ)(a::BigFloat, b::BigFloat, c::BigFloat, d::BigFloat) - z = BigFloat() - ccall(($(string(:mpfr_,fC)), :libmpfr), Int32, (Ptr{BigFloat}, Ptr{BigFloat}, Ptr{BigFloat}, Int32), &z, &a, &b, ROUNDING_MODE[]) - ccall(($(string(:mpfr_,fC)), :libmpfr), Int32, (Ptr{BigFloat}, Ptr{BigFloat}, Ptr{BigFloat}, Int32), &z, &z, &c, ROUNDING_MODE[]) - ccall(($(string(:mpfr_,fC)), :libmpfr), Int32, (Ptr{BigFloat}, Ptr{BigFloat}, Ptr{BigFloat}, Int32), &z, &z, &d, ROUNDING_MODE[]) - return z - end - function ($fJ)(a::BigFloat, b::BigFloat, c::BigFloat, d::BigFloat, e::BigFloat) - z = BigFloat() - ccall(($(string(:mpfr_,fC)), :libmpfr), Int32, (Ptr{BigFloat}, Ptr{BigFloat}, Ptr{BigFloat}, Int32), &z, &a, &b, ROUNDING_MODE[]) - ccall(($(string(:mpfr_,fC)), :libmpfr), Int32, (Ptr{BigFloat}, Ptr{BigFloat}, Ptr{BigFloat}, Int32), &z, &z, &c, ROUNDING_MODE[]) - ccall(($(string(:mpfr_,fC)), :libmpfr), Int32, (Ptr{BigFloat}, Ptr{BigFloat}, Ptr{BigFloat}, Int32), &z, &z, &d, ROUNDING_MODE[]) - ccall(($(string(:mpfr_,fC)), :libmpfr), Int32, (Ptr{BigFloat}, Ptr{BigFloat}, Ptr{BigFloat}, Int32), &z, &z, &e, ROUNDING_MODE[]) - return z - end - end -end - -function -(x::BigFloat) - z = BigFloat() - ccall((:mpfr_neg, :libmpfr), Int32, (Ptr{BigFloat}, Ptr{BigFloat}, Int32), &z, &x, ROUNDING_MODE[]) - return z -end - -function sqrt(x::BigFloat) - isnan(x) && return x - z = BigFloat() - ccall((:mpfr_sqrt, :libmpfr), Int32, (Ptr{BigFloat}, Ptr{BigFloat}, Int32), &z, &x, ROUNDING_MODE[]) - if isnan(z) - throw(DomainError()) - end - return z -end - -sqrt(x::BigInt) = sqrt(BigFloat(x)) - -function ^(x::BigFloat, y::BigFloat) - z = BigFloat() - ccall((:mpfr_pow, :libmpfr), Int32, (Ptr{BigFloat}, Ptr{BigFloat}, Ptr{BigFloat}, Int32), &z, &x, &y, ROUNDING_MODE[]) - return z -end - -function ^(x::BigFloat, y::CulongMax) - z = BigFloat() - ccall((:mpfr_pow_ui, :libmpfr), Int32, (Ptr{BigFloat}, Ptr{BigFloat}, Culong, Int32), &z, &x, y, ROUNDING_MODE[]) - return z -end - -function ^(x::BigFloat, y::ClongMax) - z = BigFloat() - ccall((:mpfr_pow_si, :libmpfr), Int32, (Ptr{BigFloat}, Ptr{BigFloat}, Clong, Int32), &z, &x, y, ROUNDING_MODE[]) - return z -end - -function ^(x::BigFloat, y::BigInt) - z = BigFloat() - ccall((:mpfr_pow_z, :libmpfr), Int32, (Ptr{BigFloat}, Ptr{BigFloat}, Ptr{BigInt}, Int32), &z, &x, &y, ROUNDING_MODE[]) - return z -end - -^(x::BigFloat, y::Integer) = typemin(Clong) <= y <= typemax(Clong) ? x^Clong(y) : x^BigInt(y) -^(x::BigFloat, y::Unsigned) = typemin(Culong) <= y <= typemax(Culong) ? x^Culong(y) : x^BigInt(y) - -for f in (:exp, :exp2, :exp10, :expm1, :cosh, :sinh, :tanh, :sech, :csch, :coth, :cbrt) - @eval function $f(x::BigFloat) - z = BigFloat() - ccall(($(string(:mpfr_,f)), :libmpfr), Int32, (Ptr{BigFloat}, Ptr{BigFloat}, Int32), &z, &x, ROUNDING_MODE[]) - return z - end -end - -# return log(2) -function big_ln2() - c = BigFloat() - ccall((:mpfr_const_log2, :libmpfr), Cint, (Ptr{BigFloat}, Int32), - &c, MPFR.ROUNDING_MODE[]) - return c -end - -function ldexp(x::BigFloat, n::Clong) - z = BigFloat() - ccall((:mpfr_mul_2si, :libmpfr), Int32, (Ptr{BigFloat}, Ptr{BigFloat}, Clong, Int32), &z, &x, n, ROUNDING_MODE[]) - return z -end -function ldexp(x::BigFloat, n::Culong) - z = BigFloat() - ccall((:mpfr_mul_2ui, :libmpfr), Int32, (Ptr{BigFloat}, Ptr{BigFloat}, Culong, Int32), &z, &x, n, ROUNDING_MODE[]) - return z -end -ldexp(x::BigFloat, n::ClongMax) = ldexp(x, convert(Clong, n)) -ldexp(x::BigFloat, n::CulongMax) = ldexp(x, convert(Culong, n)) -ldexp(x::BigFloat, n::Integer) = x*exp2(BigFloat(n)) - -function factorial(x::BigFloat) - if x < 0 || !isinteger(x) - throw(DomainError()) - end - ui = convert(Culong, x) - z = BigFloat() - ccall((:mpfr_fac_ui, :libmpfr), Int32, (Ptr{BigFloat}, Culong, Int32), &z, ui, ROUNDING_MODE[]) - return z -end - -function hypot(x::BigFloat, y::BigFloat) - z = BigFloat() - ccall((:mpfr_hypot, :libmpfr), Int32, (Ptr{BigFloat}, Ptr{BigFloat}, Ptr{BigFloat}, Int32), &z, &x, &y, ROUNDING_MODE[]) - return z -end - -for f in (:log, :log2, :log10) - @eval function $f(x::BigFloat) - if x < 0 - throw(DomainError()) - end - z = BigFloat() - ccall(($(string(:mpfr_,f)), :libmpfr), Int32, (Ptr{BigFloat}, Ptr{BigFloat}, Int32), &z, &x, ROUNDING_MODE[]) - return z - end -end - -function log1p(x::BigFloat) - if x < -1 - throw(DomainError()) - end - z = BigFloat() - ccall((:mpfr_log1p, :libmpfr), Int32, (Ptr{BigFloat}, Ptr{BigFloat}, Int32), &z, &x, ROUNDING_MODE[]) - return z -end - -function max(x::BigFloat, y::BigFloat) - isnan(x) && return x - isnan(y) && return y - z = BigFloat() - ccall((:mpfr_max, :libmpfr), Int32, (Ptr{BigFloat}, Ptr{BigFloat}, Ptr{BigFloat}, Int32), &z, &x, &y, ROUNDING_MODE[]) - return z -end - -function min(x::BigFloat, y::BigFloat) - isnan(x) && return x - isnan(y) && return y - z = BigFloat() - ccall((:mpfr_min, :libmpfr), Int32, (Ptr{BigFloat}, Ptr{BigFloat}, Ptr{BigFloat}, Int32), &z, &x, &y, ROUNDING_MODE[]) - return z -end - -function modf(x::BigFloat) - if isinf(x) - return (BigFloat(NaN), x) - end - zint = BigFloat() - zfloat = BigFloat() - ccall((:mpfr_modf, :libmpfr), Int32, (Ptr{BigFloat}, Ptr{BigFloat}, Ptr{BigFloat}, Int32), &zint, &zfloat, &x, ROUNDING_MODE[]) - return (zfloat, zint) -end - -function rem(x::BigFloat, y::BigFloat) - z = BigFloat() - ccall((:mpfr_fmod, :libmpfr), Int32, (Ptr{BigFloat}, Ptr{BigFloat}, Ptr{BigFloat}, Int32), &z, &x, &y, ROUNDING_MODE[]) - return z -end - -function rem(x::BigFloat, y::BigFloat, ::RoundingMode{:Nearest}) - z = BigFloat() - ccall((:mpfr_remainder, :libmpfr), Int32, (Ptr{BigFloat}, Ptr{BigFloat}, Ptr{BigFloat}, Int32), &z, &x, &y, ROUNDING_MODE[]) - return z -end - -# TODO: use a higher-precision BigFloat(pi) here? -rem2pi(x::BigFloat, r::RoundingMode) = rem(x, 2*BigFloat(pi), r) - -function sum(arr::AbstractArray{BigFloat}) - z = BigFloat(0) - for i in arr - ccall((:mpfr_add, :libmpfr), Int32, - (Ptr{BigFloat}, Ptr{BigFloat}, Ptr{BigFloat}, Cint), - &z, &z, &i, 0) - end - return z -end - -# Functions for which NaN results are converted to DomainError, following Base -for f in (:sin,:cos,:tan,:sec,:csc, - :acos,:asin,:atan,:acosh,:asinh,:atanh, :gamma) - @eval begin - function ($f)(x::BigFloat) - if isnan(x) - return x - end - z = BigFloat() - ccall(($(string(:mpfr_,f)), :libmpfr), Int32, (Ptr{BigFloat}, Ptr{BigFloat}, Int32), &z, &x, ROUNDING_MODE[]) - if isnan(z) - throw(DomainError()) - end - return z - end - end -end - -# log of absolute value of gamma function -const lgamma_signp = Ref{Cint}() -function lgamma(x::BigFloat) - z = BigFloat() - ccall((:mpfr_lgamma,:libmpfr), Cint, (Ptr{BigFloat}, Ptr{Cint}, Ptr{BigFloat}, Int32), &z, lgamma_signp, &x, ROUNDING_MODE[]) - return z -end - -lgamma_r(x::BigFloat) = (lgamma(x), lgamma_signp[]) - -function atan2(y::BigFloat, x::BigFloat) - z = BigFloat() - ccall((:mpfr_atan2, :libmpfr), Int32, (Ptr{BigFloat}, Ptr{BigFloat}, Ptr{BigFloat}, Int32), &z, &y, &x, ROUNDING_MODE[]) - return z -end - -# Utility functions -==(x::BigFloat, y::BigFloat) = ccall((:mpfr_equal_p, :libmpfr), Int32, (Ptr{BigFloat}, Ptr{BigFloat}), &x, &y) != 0 -<=(x::BigFloat, y::BigFloat) = ccall((:mpfr_lessequal_p, :libmpfr), Int32, (Ptr{BigFloat}, Ptr{BigFloat}), &x, &y) != 0 ->=(x::BigFloat, y::BigFloat) = ccall((:mpfr_greaterequal_p, :libmpfr), Int32, (Ptr{BigFloat}, Ptr{BigFloat}), &x, &y) != 0 -<(x::BigFloat, y::BigFloat) = ccall((:mpfr_less_p, :libmpfr), Int32, (Ptr{BigFloat}, Ptr{BigFloat}), &x, &y) != 0 ->(x::BigFloat, y::BigFloat) = ccall((:mpfr_greater_p, :libmpfr), Int32, (Ptr{BigFloat}, Ptr{BigFloat}), &x, &y) != 0 - -function cmp(x::BigFloat, y::BigInt) - isnan(x) && throw(DomainError()) - ccall((:mpfr_cmp_z, :libmpfr), Int32, (Ptr{BigFloat}, Ptr{BigInt}), &x, &y) -end -function cmp(x::BigFloat, y::ClongMax) - isnan(x) && throw(DomainError()) - ccall((:mpfr_cmp_si, :libmpfr), Int32, (Ptr{BigFloat}, Clong), &x, y) -end -function cmp(x::BigFloat, y::CulongMax) - isnan(x) && throw(DomainError()) - ccall((:mpfr_cmp_ui, :libmpfr), Int32, (Ptr{BigFloat}, Culong), &x, y) -end -cmp(x::BigFloat, y::Integer) = cmp(x,big(y)) -cmp(x::Integer, y::BigFloat) = -cmp(y,x) - -function cmp(x::BigFloat, y::CdoubleMax) - (isnan(x) || isnan(y)) && throw(DomainError()) - ccall((:mpfr_cmp_d, :libmpfr), Int32, (Ptr{BigFloat}, Cdouble), &x, y) -end -cmp(x::CdoubleMax, y::BigFloat) = -cmp(y,x) - -==(x::BigFloat, y::Integer) = !isnan(x) && cmp(x,y) == 0 -==(x::Integer, y::BigFloat) = y == x -==(x::BigFloat, y::CdoubleMax) = !isnan(x) && !isnan(y) && cmp(x,y) == 0 -==(x::CdoubleMax, y::BigFloat) = y == x - -<(x::BigFloat, y::Integer) = !isnan(x) && cmp(x,y) < 0 -<(x::Integer, y::BigFloat) = !isnan(y) && cmp(y,x) > 0 -<(x::BigFloat, y::CdoubleMax) = !isnan(x) && !isnan(y) && cmp(x,y) < 0 -<(x::CdoubleMax, y::BigFloat) = !isnan(x) && !isnan(y) && cmp(y,x) > 0 - -<=(x::BigFloat, y::Integer) = !isnan(x) && cmp(x,y) <= 0 -<=(x::Integer, y::BigFloat) = !isnan(y) && cmp(y,x) >= 0 -<=(x::BigFloat, y::CdoubleMax) = !isnan(x) && !isnan(y) && cmp(x,y) <= 0 -<=(x::CdoubleMax, y::BigFloat) = !isnan(x) && !isnan(y) && cmp(y,x) >= 0 - -signbit(x::BigFloat) = ccall((:mpfr_signbit, :libmpfr), Int32, (Ptr{BigFloat},), &x) != 0 - -function precision(x::BigFloat) # precision of an object of type BigFloat - return ccall((:mpfr_get_prec, :libmpfr), Clong, (Ptr{BigFloat},), &x) -end - -""" - precision(BigFloat) - -Get the precision (in bits) currently used for [`BigFloat`](@ref) arithmetic. -""" -precision(::Type{BigFloat}) = DEFAULT_PRECISION[end] # precision of the type BigFloat itself - -""" - setprecision([T=BigFloat,] precision::Int) - -Set the precision (in bits) to be used for `T` arithmetic. -""" -function setprecision(::Type{BigFloat}, precision::Int) - if precision < 2 - throw(DomainError()) - end - DEFAULT_PRECISION[end] = precision -end - -setprecision(precision::Int) = setprecision(BigFloat, precision) - -maxintfloat(x::BigFloat) = BigFloat(2)^precision(x) -maxintfloat(::Type{BigFloat}) = BigFloat(2)^precision(BigFloat) - -to_mpfr(::RoundingMode{:Nearest}) = Cint(0) -to_mpfr(::RoundingMode{:ToZero}) = Cint(1) -to_mpfr(::RoundingMode{:Up}) = Cint(2) -to_mpfr(::RoundingMode{:Down}) = Cint(3) -to_mpfr(::RoundingMode{:FromZero}) = Cint(4) - -function from_mpfr(c::Integer) - if c == 0 - return RoundNearest - elseif c == 1 - return RoundToZero - elseif c == 2 - return RoundUp - elseif c == 3 - return RoundDown - elseif c == 4 - return RoundFromZero - else - throw(ArgumentError("invalid MPFR rounding mode code: $c")) - end - RoundingMode(c) -end - -rounding_raw(::Type{BigFloat}) = ROUNDING_MODE[] -setrounding_raw(::Type{BigFloat},i::Integer) = ROUNDING_MODE[] = i - -rounding(::Type{BigFloat}) = from_mpfr(rounding_raw(BigFloat)) -setrounding(::Type{BigFloat},r::RoundingMode) = setrounding_raw(BigFloat,to_mpfr(r)) - -function copysign(x::BigFloat, y::BigFloat) - z = BigFloat() - ccall((:mpfr_copysign, :libmpfr), Int32, (Ptr{BigFloat}, Ptr{BigFloat}, Ptr{BigFloat}, Int32), &z, &x, &y, ROUNDING_MODE[]) - return z -end - -function exponent(x::BigFloat) - if x == 0 || !isfinite(x) - throw(DomainError()) - end - # The '- 1' is to make it work as Base.exponent - return ccall((:mpfr_get_exp, :libmpfr), Clong, (Ptr{BigFloat},), &x) - 1 -end - -function frexp(x::BigFloat) - z = BigFloat() - c = Ref{Clong}() - ccall((:mpfr_frexp, :libmpfr), Int32, (Ptr{Clong}, Ptr{BigFloat}, Ptr{BigFloat}, Cint), c, &z, &x, ROUNDING_MODE[]) - return (z, c[]) -end - -function significand(x::BigFloat) - z = BigFloat() - c = Ref{Clong}() - ccall((:mpfr_frexp, :libmpfr), Int32, (Ptr{Clong}, Ptr{BigFloat}, Ptr{BigFloat}, Cint), c, &z, &x, ROUNDING_MODE[]) - # Double the significand to make it work as Base.significand - ccall((:mpfr_mul_si, :libmpfr), Int32, (Ptr{BigFloat}, Ptr{BigFloat}, Clong, Int32), &z, &z, 2, ROUNDING_MODE[]) - return z -end - -function isinteger(x::BigFloat) - return ccall((:mpfr_integer_p, :libmpfr), Int32, (Ptr{BigFloat},), &x) != 0 -end - -for f in (:ceil, :floor, :trunc) - @eval begin - function ($f)(x::BigFloat) - z = BigFloat() - ccall(($(string(:mpfr_,f)), :libmpfr), Int32, (Ptr{BigFloat}, Ptr{BigFloat}), &z, &x) - return z - end - end -end - -function round(x::BigFloat) - z = BigFloat() - ccall((:mpfr_rint, :libmpfr), Int32, (Ptr{BigFloat}, Ptr{BigFloat}, Cint), &z, &x, ROUNDING_MODE[]) - return z -end -function round(x::BigFloat,::RoundingMode{:NearestTiesAway}) - z = BigFloat() - ccall((:mpfr_round, :libmpfr), Int32, (Ptr{BigFloat}, Ptr{BigFloat}), &z, &x) - return z -end - -function isinf(x::BigFloat) - return ccall((:mpfr_inf_p, :libmpfr), Int32, (Ptr{BigFloat},), &x) != 0 -end - -function isnan(x::BigFloat) - return ccall((:mpfr_nan_p, :libmpfr), Int32, (Ptr{BigFloat},), &x) != 0 -end - -isfinite(x::BigFloat) = !isinf(x) && !isnan(x) - -iszero(x::BigFloat) = x == Clong(0) - -@eval typemax(::Type{BigFloat}) = $(BigFloat( Inf)) -@eval typemin(::Type{BigFloat}) = $(BigFloat(-Inf)) - -function nextfloat(x::BigFloat) - z = BigFloat() - ccall((:mpfr_set, :libmpfr), Int32, (Ptr{BigFloat}, Ptr{BigFloat}, Int32), - &z, &x, ROUNDING_MODE[]) - ccall((:mpfr_nextabove, :libmpfr), Int32, (Ptr{BigFloat},), &z) != 0 - return z -end - -function prevfloat(x::BigFloat) - z = BigFloat() - ccall((:mpfr_set, :libmpfr), Int32, (Ptr{BigFloat}, Ptr{BigFloat}, Int32), - &z, &x, ROUNDING_MODE[]) - ccall((:mpfr_nextbelow, :libmpfr), Int32, (Ptr{BigFloat},), &z) != 0 - return z -end - -eps(::Type{BigFloat}) = nextfloat(BigFloat(1)) - BigFloat(1) - -realmin(::Type{BigFloat}) = nextfloat(zero(BigFloat)) -realmax(::Type{BigFloat}) = prevfloat(BigFloat(Inf)) - -""" - setprecision(f::Function, [T=BigFloat,] precision::Integer) - -Change the `T` arithmetic precision (in bits) for the duration of `f`. -It is logically equivalent to: - - old = precision(BigFloat) - setprecision(BigFloat, precision) - f() - setprecision(BigFloat, old) - -Often used as `setprecision(T, precision) do ... end` -""" -function setprecision(f::Function, ::Type{T}, prec::Integer) where T - old_prec = precision(T) - setprecision(T, prec) - try - return f() - finally - setprecision(T, old_prec) - end -end - -setprecision(f::Function, precision::Integer) = setprecision(f, BigFloat, precision) - -function string(x::BigFloat) - if isnan(x) || isinf(x) - return string("BigFloat(", Float64(x), ", ", precision(x), ")") - end - - # In general, the number of decimal places needed to read back the number exactly - # is, excluding the most significant, ceil(log(10, 2^precision(x))) - k = ceil(Int32, precision(x) * 0.3010299956639812) - lng = k + Int32(8) # Add space for the sign, the most significand digit, the dot and the exponent - buf = Base.StringVector(lng + 1) - # format strings are guaranteed to contain no NUL, so we don't use Cstring - lng = ccall((:mpfr_snprintf,:libmpfr), Int32, (Ptr{UInt8}, Culong, Ptr{UInt8}, Ptr{BigFloat}...), buf, lng + 1, "%.Re", &x) - if lng < k + 5 # print at least k decimal places - lng = ccall((:mpfr_sprintf,:libmpfr), Int32, (Ptr{UInt8}, Ptr{UInt8}, Ptr{BigFloat}...), buf, "%.$(k)Re", &x) - elseif lng > k + 8 - buf = Base.StringVector(lng + 1) - lng = ccall((:mpfr_snprintf,:libmpfr), Int32, (Ptr{UInt8}, Culong, Ptr{UInt8}, Ptr{BigFloat}...), buf, lng + 1, "%.Re", &x) - end - n = (1 <= x < 10 || -10 < x <= -1 || x == 0) ? lng - 4 : lng - return String(resize!(buf,n)) -end - -print(io::IO, b::BigFloat) = print(io, string(b)) -show(io::IO, b::BigFloat) = print(io, string(b)) - -# get/set exponent min/max -get_emax() = ccall((:mpfr_get_emax, :libmpfr), Clong, ()) -get_emax_min() = ccall((:mpfr_get_emax_min, :libmpfr), Clong, ()) -get_emax_max() = ccall((:mpfr_get_emax_max, :libmpfr), Clong, ()) - -get_emin() = ccall((:mpfr_get_emin, :libmpfr), Clong, ()) -get_emin_min() = ccall((:mpfr_get_emin_min, :libmpfr), Clong, ()) -get_emin_max() = ccall((:mpfr_get_emin_max, :libmpfr), Clong, ()) - -set_emax!(x) = ccall((:mpfr_set_emax, :libmpfr), Void, (Clong,), x) -set_emin!(x) = ccall((:mpfr_set_emin, :libmpfr), Void, (Clong,), x) - -function Base.deepcopy_internal(x::BigFloat, stackdict::ObjectIdDict) - if haskey(stackdict, x) - return stackdict[x] - end - N = precision(x) - y = BigFloat(zero(Clong), zero(Cint), zero(Clong), C_NULL) - ccall((:mpfr_init2,:libmpfr), Void, (Ptr{BigFloat}, Clong), &y, N) - finalizer(y, cglobal((:mpfr_clear, :libmpfr))) - ccall((:mpfr_set, :libmpfr), Int32, (Ptr{BigFloat}, Ptr{BigFloat}, Int32), - &y, &x, ROUNDING_MODE[]) - stackdict[x] = y - return y -end - -function Base.lerpi(j::Integer, d::Integer, a::BigFloat, b::BigFloat) - t = BigFloat(j)/d - fma(t, b, fma(-t, a, a)) -end - -end #module diff --git a/julia-0.6.3/share/julia/base/multidimensional.jl b/julia-0.6.3/share/julia/base/multidimensional.jl deleted file mode 100644 index bb9bdaf..0000000 --- a/julia-0.6.3/share/julia/base/multidimensional.jl +++ /dev/null @@ -1,1516 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -### Multidimensional iterators -module IteratorsMD - import Base: eltype, length, size, start, done, next, last, in, getindex, - setindex!, IndexStyle, min, max, zero, one, isless, eachindex, - ndims, iteratorsize, convert - - importall ..Base.Operators - import Base: simd_outer_range, simd_inner_length, simd_index - using Base: IndexLinear, IndexCartesian, AbstractCartesianIndex, fill_to_length, tail - - export CartesianIndex, CartesianRange - - """ - CartesianIndex(i, j, k...) -> I - CartesianIndex((i, j, k...)) -> I - - Create a multidimensional index `I`, which can be used for - indexing a multidimensional array `A`. In particular, `A[I]` is - equivalent to `A[i,j,k...]`. One can freely mix integer and - `CartesianIndex` indices; for example, `A[Ipre, i, Ipost]` (where - `Ipre` and `Ipost` are `CartesianIndex` indices and `i` is an - `Int`) can be a useful expression when writing algorithms that - work along a single dimension of an array of arbitrary - dimensionality. - - A `CartesianIndex` is sometimes produced by [`eachindex`](@ref), and - always when iterating with an explicit [`CartesianRange`](@ref). - - # Example - - ```jldoctest - julia> A = reshape(collect(1:16), (2, 2, 2, 2)) - 2×2×2×2 Array{Int64,4}: - [:, :, 1, 1] = - 1 3 - 2 4 - - [:, :, 2, 1] = - 5 7 - 6 8 - - [:, :, 1, 2] = - 9 11 - 10 12 - - [:, :, 2, 2] = - 13 15 - 14 16 - - julia> A[CartesianIndex((1, 1, 1, 1))] - 1 - - julia> A[CartesianIndex((1, 1, 1, 2))] - 9 - - julia> A[CartesianIndex((1, 1, 2, 1))] - 5 - ``` - """ - struct CartesianIndex{N} <: AbstractCartesianIndex{N} - I::NTuple{N,Int} - CartesianIndex{N}(index::NTuple{N,Integer}) where {N} = new(index) - end - - CartesianIndex(index::NTuple{N,Integer}) where {N} = CartesianIndex{N}(index) - CartesianIndex(index::Integer...) = CartesianIndex(index) - CartesianIndex{N}(index::Vararg{Integer,N}) where {N} = CartesianIndex{N}(index) - # Allow passing tuples smaller than N - CartesianIndex{N}(index::Tuple) where {N} = CartesianIndex{N}(fill_to_length(index, 1, Val{N})) - CartesianIndex{N}(index::Integer...) where {N} = CartesianIndex{N}(index) - CartesianIndex{N}() where {N} = CartesianIndex{N}(()) - # Un-nest passed CartesianIndexes - CartesianIndex(index::Union{Integer, CartesianIndex}...) = CartesianIndex(flatten(index)) - flatten(I::Tuple{}) = I - flatten(I::Tuple{Any}) = I - flatten(I::Tuple{<:CartesianIndex}) = I[1].I - @inline flatten(I) = _flatten(I...) - @inline _flatten() = () - @inline _flatten(i, I...) = (i, _flatten(I...)...) - @inline _flatten(i::CartesianIndex, I...) = (i.I..., _flatten(I...)...) - CartesianIndex(index::Tuple{Vararg{Union{Integer, CartesianIndex}}}) = CartesianIndex(index...) - - # length - length(::CartesianIndex{N}) where {N} = N - length(::Type{CartesianIndex{N}}) where {N} = N - - # indexing - getindex(index::CartesianIndex, i::Integer) = index.I[i] - - # zeros and ones - zero(::CartesianIndex{N}) where {N} = zero(CartesianIndex{N}) - zero(::Type{CartesianIndex{N}}) where {N} = CartesianIndex(ntuple(x -> 0, Val{N})) - one(::CartesianIndex{N}) where {N} = one(CartesianIndex{N}) - one(::Type{CartesianIndex{N}}) where {N} = CartesianIndex(ntuple(x -> 1, Val{N})) - - # arithmetic, min/max - @inline (-)(index::CartesianIndex{N}) where {N} = - CartesianIndex{N}(map(-, index.I)) - @inline (+)(index1::CartesianIndex{N}, index2::CartesianIndex{N}) where {N} = - CartesianIndex{N}(map(+, index1.I, index2.I)) - @inline (-)(index1::CartesianIndex{N}, index2::CartesianIndex{N}) where {N} = - CartesianIndex{N}(map(-, index1.I, index2.I)) - @inline min(index1::CartesianIndex{N}, index2::CartesianIndex{N}) where {N} = - CartesianIndex{N}(map(min, index1.I, index2.I)) - @inline max(index1::CartesianIndex{N}, index2::CartesianIndex{N}) where {N} = - CartesianIndex{N}(map(max, index1.I, index2.I)) - - @inline (+)(i::Integer, index::CartesianIndex) = index+i - @inline (+)(index::CartesianIndex{N}, i::Integer) where {N} = CartesianIndex{N}(map(x->x+i, index.I)) - @inline (-)(index::CartesianIndex{N}, i::Integer) where {N} = CartesianIndex{N}(map(x->x-i, index.I)) - @inline (-)(i::Integer, index::CartesianIndex{N}) where {N} = CartesianIndex{N}(map(x->i-x, index.I)) - @inline (*)(a::Integer, index::CartesianIndex{N}) where {N} = CartesianIndex{N}(map(x->a*x, index.I)) - @inline (*)(index::CartesianIndex, a::Integer) = *(a,index) - - # comparison - @inline isless(I1::CartesianIndex{N}, I2::CartesianIndex{N}) where {N} = _isless(0, I1.I, I2.I) - @inline function _isless(ret, I1::NTuple{N,Int}, I2::NTuple{N,Int}) where N - newret = ifelse(ret==0, icmp(I1[N], I2[N]), ret) - _isless(newret, Base.front(I1), Base.front(I2)) - end - _isless(ret, ::Tuple{}, ::Tuple{}) = ifelse(ret==1, true, false) - icmp(a, b) = ifelse(isless(a,b), 1, ifelse(a==b, 0, -1)) - - # hashing - const cartindexhash_seed = UInt == UInt64 ? 0xd60ca92f8284b8b0 : 0xf2ea7c2e - function Base.hash(ci::CartesianIndex, h::UInt) - h += cartindexhash_seed - for i in ci.I - h = hash(i, h) - end - return h - end - - # Iteration - """ - CartesianRange(Istart::CartesianIndex, Istop::CartesianIndex) -> R - CartesianRange(sz::Dims) -> R - CartesianRange(istart:istop, jstart:jstop, ...) -> R - - Define a region `R` spanning a multidimensional rectangular range - of integer indices. These are most commonly encountered in the - context of iteration, where `for I in R ... end` will return - [`CartesianIndex`](@ref) indices `I` equivalent to the nested loops - - for j = jstart:jstop - for i = istart:istop - ... - end - end - - Consequently these can be useful for writing algorithms that - work in arbitrary dimensions. - - ```jldoctest - julia> foreach(println, CartesianRange((2, 2, 2))) - CartesianIndex{3}((1, 1, 1)) - CartesianIndex{3}((2, 1, 1)) - CartesianIndex{3}((1, 2, 1)) - CartesianIndex{3}((2, 2, 1)) - CartesianIndex{3}((1, 1, 2)) - CartesianIndex{3}((2, 1, 2)) - CartesianIndex{3}((1, 2, 2)) - CartesianIndex{3}((2, 2, 2)) - ``` - """ - struct CartesianRange{I<:CartesianIndex} - start::I - stop::I - end - - CartesianRange(index::CartesianIndex) = CartesianRange(one(index), index) - CartesianRange(::Tuple{}) = CartesianRange{CartesianIndex{0}}(CartesianIndex{0}(()),CartesianIndex{0}(())) - CartesianRange{N}(sz::NTuple{N,Int}) = CartesianRange(CartesianIndex(sz)) - CartesianRange{N}(rngs::NTuple{N,Union{Integer,AbstractUnitRange}}) = - CartesianRange(CartesianIndex(map(first, rngs)), CartesianIndex(map(last, rngs))) - - convert(::Type{NTuple{N,UnitRange{Int}}}, R::CartesianRange{CartesianIndex{N}}) where {N} = - map((f,l)->f:l, first(R).I, last(R).I) - convert(::Type{NTuple{N,UnitRange}}, R::CartesianRange) where {N} = - convert(NTuple{N,UnitRange{Int}}, R) - convert(::Type{Tuple{Vararg{UnitRange{Int}}}}, R::CartesianRange{CartesianIndex{N}}) where {N} = - convert(NTuple{N,UnitRange{Int}}, R) - convert(::Type{Tuple{Vararg{UnitRange}}}, R::CartesianRange) = - convert(Tuple{Vararg{UnitRange{Int}}}, R) - - ndims(R::CartesianRange) = length(R.start) - ndims(::Type{CartesianRange{I}}) where {I<:CartesianIndex} = length(I) - - eachindex(::IndexCartesian, A::AbstractArray) = CartesianRange(indices(A)) - - @inline eachindex(::IndexCartesian, A::AbstractArray, B::AbstractArray...) = - CartesianRange(maxsize((), A, B...)) - maxsize(sz) = sz - @inline maxsize(sz, A, B...) = maxsize(maxt(sz, size(A)), B...) - @inline maxt(a::Tuple{}, b::Tuple{}) = () - @inline maxt(a::Tuple{}, b::Tuple) = b - @inline maxt(a::Tuple, b::Tuple{}) = a - @inline maxt(a::Tuple, b::Tuple) = (max(a[1], b[1]), maxt(tail(a), tail(b))...) - - eltype(::Type{CartesianRange{I}}) where {I} = I - iteratorsize(::Type{<:CartesianRange}) = Base.HasShape() - - @inline function start(iter::CartesianRange{<:CartesianIndex}) - if any(map(>, iter.start.I, iter.stop.I)) - return iter.stop+1 - end - iter.start - end - @inline function next(iter::CartesianRange{I}, state) where I<:CartesianIndex - state, I(inc(state.I, iter.start.I, iter.stop.I)) - end - # increment & carry - @inline inc(::Tuple{}, ::Tuple{}, ::Tuple{}) = () - @inline inc(state::Tuple{Int}, start::Tuple{Int}, stop::Tuple{Int}) = (state[1]+1,) - @inline function inc(state, start, stop) - if state[1] < stop[1] - return (state[1]+1,tail(state)...) - end - newtail = inc(tail(state), tail(start), tail(stop)) - (start[1], newtail...) - end - @inline done(iter::CartesianRange{<:CartesianIndex}, state) = state.I[end] > iter.stop.I[end] - - # 0-d cartesian ranges are special-cased to iterate once and only once - start(iter::CartesianRange{<:CartesianIndex{0}}) = false - next(iter::CartesianRange{<:CartesianIndex{0}}, state) = iter.start, true - done(iter::CartesianRange{<:CartesianIndex{0}}, state) = state - - size(iter::CartesianRange{<:CartesianIndex}) = map(dimlength, iter.start.I, iter.stop.I) - dimlength(start, stop) = stop-start+1 - - length(iter::CartesianRange) = prod(size(iter)) - - last(iter::CartesianRange) = iter.stop - - @inline function in(i::I, r::CartesianRange{I}) where I<:CartesianIndex - _in(true, i.I, r.start.I, r.stop.I) - end - _in(b, ::Tuple{}, ::Tuple{}, ::Tuple{}) = b - @inline _in(b, i, start, stop) = _in(b & (start[1] <= i[1] <= stop[1]), tail(i), tail(start), tail(stop)) - - simd_outer_range(iter::CartesianRange{CartesianIndex{0}}) = iter - function simd_outer_range(iter::CartesianRange) - start = CartesianIndex(tail(iter.start.I)) - stop = CartesianIndex(tail(iter.stop.I)) - CartesianRange(start, stop) - end - - simd_inner_length(iter::CartesianRange{<:CartesianIndex{0}}, ::CartesianIndex) = 1 - simd_inner_length(iter::CartesianRange, I::CartesianIndex) = iter.stop[1]-iter.start[1]+1 - - simd_index(iter::CartesianRange{<:CartesianIndex{0}}, ::CartesianIndex, I1::Int) = iter.start - @inline function simd_index(iter::CartesianRange, Ilast::CartesianIndex, I1::Int) - CartesianIndex((I1+iter.start[1], Ilast.I...)) - end - - # Split out the first N elements of a tuple - @inline split(t, V::Type{<:Val}) = _split((), t, V) - @inline _split(tN, trest, V) = _split((tN..., trest[1]), tail(trest), V) - # exit either when we've exhausted the input tuple or when tN has length N - @inline _split(tN::NTuple{N,Any}, ::Tuple{}, ::Type{Val{N}}) where {N} = tN, () # ambig. - @inline _split(tN, ::Tuple{}, ::Type{Val{N}}) where {N} = tN, () - @inline _split(tN::NTuple{N,Any}, trest, ::Type{Val{N}}) where {N} = tN, trest - - @inline function split(I::CartesianIndex, V::Type{<:Val}) - i, j = split(I.I, V) - CartesianIndex(i), CartesianIndex(j) - end - function split(R::CartesianRange, V::Type{<:Val}) - istart, jstart = split(first(R), V) - istop, jstop = split(last(R), V) - CartesianRange(istart, istop), CartesianRange(jstart, jstop) - end -end # IteratorsMD - - -using .IteratorsMD - -## Bounds-checking with CartesianIndex -# Disallow linear indexing with CartesianIndex -function checkbounds(::Type{Bool}, A::AbstractArray, i::Union{CartesianIndex, AbstractArray{<:CartesianIndex}}) - @_inline_meta - checkbounds_indices(Bool, indices(A), (i,)) -end - -@inline checkbounds_indices(::Type{Bool}, ::Tuple{}, I::Tuple{CartesianIndex,Vararg{Any}}) = - checkbounds_indices(Bool, (), (I[1].I..., tail(I)...)) -@inline checkbounds_indices(::Type{Bool}, IA::Tuple{Any}, I::Tuple{CartesianIndex,Vararg{Any}}) = - checkbounds_indices(Bool, IA, (I[1].I..., tail(I)...)) -@inline checkbounds_indices(::Type{Bool}, IA::Tuple, I::Tuple{CartesianIndex,Vararg{Any}}) = - checkbounds_indices(Bool, IA, (I[1].I..., tail(I)...)) - -# Indexing into Array with mixtures of Integers and CartesianIndices is -# extremely performance-sensitive. While the abstract fallbacks support this, -# codegen has extra support for SIMDification that sub2ind doesn't (yet) support -@propagate_inbounds getindex(A::Array, i1::Union{Integer, CartesianIndex}, I::Union{Integer, CartesianIndex}...) = - A[to_indices(A, (i1, I...))...] -@propagate_inbounds setindex!(A::Array, v, i1::Union{Integer, CartesianIndex}, I::Union{Integer, CartesianIndex}...) = - (A[to_indices(A, (i1, I...))...] = v; A) - -# Support indexing with an array of CartesianIndex{N}s -# Here we try to consume N of the indices (if there are that many available) -# The first two simply handle ambiguities -@inline function checkbounds_indices(::Type{Bool}, ::Tuple{}, - I::Tuple{AbstractArray{CartesianIndex{N}},Vararg{Any}}) where N - checkindex(Bool, (), I[1]) & checkbounds_indices(Bool, (), tail(I)) -end -@inline function checkbounds_indices(::Type{Bool}, IA::Tuple{Any}, - I::Tuple{AbstractArray{CartesianIndex{0}},Vararg{Any}}) - checkbounds_indices(Bool, IA, tail(I)) -end -@inline function checkbounds_indices(::Type{Bool}, IA::Tuple{Any}, - I::Tuple{AbstractArray{CartesianIndex{N}},Vararg{Any}}) where N - checkindex(Bool, IA, I[1]) & checkbounds_indices(Bool, (), tail(I)) -end -@inline function checkbounds_indices(::Type{Bool}, IA::Tuple, - I::Tuple{AbstractArray{CartesianIndex{N}},Vararg{Any}}) where N - IA1, IArest = IteratorsMD.split(IA, Val{N}) - checkindex(Bool, IA1, I[1]) & checkbounds_indices(Bool, IArest, tail(I)) -end - -function checkindex(::Type{Bool}, inds::Tuple, I::AbstractArray{<:CartesianIndex}) - b = true - for i in I - b &= checkbounds_indices(Bool, inds, (i,)) - end - b -end - -# combined count of all indices, including CartesianIndex and -# AbstractArray{CartesianIndex} -# rather than returning N, it returns an NTuple{N,Bool} so the result is inferrable -@inline index_ndims(i1, I...) = (true, index_ndims(I...)...) -@inline function index_ndims(i1::CartesianIndex, I...) - (map(x->true, i1.I)..., index_ndims(I...)...) -end -@inline function index_ndims(i1::AbstractArray{CartesianIndex{N}}, I...) where N - (ntuple(x->true, Val{N})..., index_ndims(I...)...) -end -index_ndims() = () - -# combined dimensionality of all indices -# rather than returning N, it returns an NTuple{N,Bool} so the result is inferrable -@inline index_dimsum(i1, I...) = (index_dimsum(I...)...) -@inline index_dimsum(::Colon, I...) = (true, index_dimsum(I...)...) -@inline index_dimsum(::AbstractArray{Bool}, I...) = (true, index_dimsum(I...)...) -@inline function index_dimsum(::AbstractArray{<:Any,N}, I...) where N - (ntuple(x->true, Val{N})..., index_dimsum(I...)...) -end -index_dimsum() = () - -# Recursively compute the lengths of a list of indices, without dropping scalars -index_lengths() = () -@inline index_lengths(::Real, rest...) = (1, index_lengths(rest...)...) -@inline index_lengths(A::AbstractArray, rest...) = (length(A), index_lengths(rest...)...) -@inline index_lengths(A::Slice, rest...) = (length(indices1(A)), index_lengths(rest...)...) - -# shape of array to create for getindex() with indexes I, dropping scalars -# returns a Tuple{Vararg{AbstractUnitRange}} of indices -index_shape() = () -@inline index_shape(::Real, rest...) = index_shape(rest...) -@inline index_shape(A::AbstractArray, rest...) = (indices(A)..., index_shape(rest...)...) - -""" - LogicalIndex(mask) - -The `LogicalIndex` type is a special vector that simply contains all indices I -where `mask[I]` is true. This specialized type does not support indexing -directly as doing so would require O(n) lookup time. `AbstractArray{Bool}` are -wrapped with `LogicalIndex` upon calling `to_indices`. -""" -struct LogicalIndex{T, A<:AbstractArray{Bool}} <: AbstractVector{T} - mask::A - sum::Int - LogicalIndex{T,A}(mask::A) where {T,A<:AbstractArray{Bool}} = new(mask, countnz(mask)) -end -LogicalIndex(mask::AbstractVector{Bool}) = LogicalIndex{Int, typeof(mask)}(mask) -LogicalIndex(mask::AbstractArray{Bool, N}) where {N} = LogicalIndex{CartesianIndex{N}, typeof(mask)}(mask) -(::Type{LogicalIndex{Int}})(mask::AbstractArray) = LogicalIndex{Int, typeof(mask)}(mask) -size(L::LogicalIndex) = (L.sum,) -length(L::LogicalIndex) = L.sum -collect(L::LogicalIndex) = [i for i in L] -show(io::IO, r::LogicalIndex) = print(io, "Base.LogicalIndex(", r.mask, ")") -# Iteration over LogicalIndex is very performance-critical, but it also must -# support arbitrary AbstractArray{Bool}s with both Int and CartesianIndex. -# Thus the iteration state contains an index iterator and its state. We also -# keep track of the count of elements since we already know how many there -# should be -- this way we don't need to look at future indices to check done. -@inline function start(L::LogicalIndex{Int}) - r = linearindices(L.mask) - return (r, start(r), 1) -end -@inline function start(L::LogicalIndex{<:CartesianIndex}) - r = CartesianRange(indices(L.mask)) - return (r, start(r), 1) -end -@inline function next(L::LogicalIndex, s) - # We're looking for the n-th true element, using iterator r at state i - r, i, n = s - while true - done(r, i) # Call done(r, i) for the iteration protocol, but trust done(L, s) was called - idx, i = next(r, i) - L.mask[idx] && return (idx, (r, i, n+1)) - end -end -done(L::LogicalIndex, s) = s[3] > length(L) -# When wrapping a BitArray, lean heavily upon its internals -- this is a common -# case. Just use the Int index and count as its state. -@inline start(L::LogicalIndex{Int,<:BitArray}) = (0, 1) -@inline function next(L::LogicalIndex{Int,<:BitArray}, s) - i, n = s - Bc = L.mask.chunks - while true - if Bc[_div64(i)+1] & (UInt64(1)<<_mod64(i)) != 0 - i += 1 - return (i, (i, n+1)) - end - i += 1 - end -end -@inline done(L::LogicalIndex{Int,<:BitArray}, s) = s[2] > length(L) - -# Checking bounds with LogicalIndex{Int} is tricky since we allow linear indexing over trailing dimensions -@inline checkbounds_indices(::Type{Bool},IA::Tuple{},I::Tuple{LogicalIndex{Int,AbstractArray{Bool,N}}}) where {N} = - checkindex(Bool, IA, I[1]) -@inline checkbounds_indices(::Type{Bool},IA::Tuple{Any},I::Tuple{LogicalIndex{Int,AbstractArray{Bool,N}}}) where {N} = - checkindex(Bool, IA[1], I[1]) -@inline function checkbounds_indices(::Type{Bool}, IA::Tuple, I::Tuple{LogicalIndex{Int,AbstractArray{Bool,N}}}) where N - IA1, IArest = IteratorsMD.split(IA, Val{N}) - checkindex(Bool, IA1, I[1]) -end -@inline checkbounds(::Type{Bool}, A::AbstractArray, I::LogicalIndex{<:Any,<:AbstractArray{Bool,1}}) = - linearindices(A) == linearindices(I.mask) -@inline checkbounds(::Type{Bool}, A::AbstractArray, I::LogicalIndex) = indices(A) == indices(I.mask) -@inline checkindex(::Type{Bool}, indx::AbstractUnitRange, I::LogicalIndex) = (indx,) == indices(I.mask) -checkindex(::Type{Bool}, inds::Tuple, I::LogicalIndex) = false - -ensure_indexable(I::Tuple{}) = () -@inline ensure_indexable(I::Tuple{Any, Vararg{Any}}) = (I[1], ensure_indexable(tail(I))...) -@inline ensure_indexable(I::Tuple{LogicalIndex, Vararg{Any}}) = (collect(I[1]), ensure_indexable(tail(I))...) - -# In simple cases, we know that we don't need to use indices(A). Optimize those -# until Julia gets smart enough to elide the call on its own: -to_indices(A, I::Tuple{}) = () -@inline to_indices(A, I::Tuple{Vararg{Union{Integer, CartesianIndex}}}) = to_indices(A, (), I) -# But some index types require more context spanning multiple indices -# CartesianIndexes are simple; they just splat out -@inline to_indices(A, inds, I::Tuple{CartesianIndex, Vararg{Any}}) = - to_indices(A, inds, (I[1].I..., tail(I)...)) -# But for arrays of CartesianIndex, we just skip the appropriate number of inds -@inline function to_indices(A, inds, I::Tuple{AbstractArray{CartesianIndex{N}}, Vararg{Any}}) where N - _, indstail = IteratorsMD.split(inds, Val{N}) - (to_index(A, I[1]), to_indices(A, indstail, tail(I))...) -end -# And boolean arrays behave similarly; they also skip their number of dimensions -@inline function to_indices(A, inds, I::Tuple{AbstractArray{Bool, N}, Vararg{Any}}) where N - _, indstail = IteratorsMD.split(inds, Val{N}) - (to_index(A, I[1]), to_indices(A, indstail, tail(I))...) -end -# As an optimization, we allow trailing Array{Bool} and BitArray to be linear over trailing dimensions -@inline to_indices(A, inds, I::Tuple{Union{Array{Bool,N}, BitArray{N}}}) where {N} = - (_maybe_linear_logical_index(IndexStyle(A), A, I[1]),) -_maybe_linear_logical_index(::IndexStyle, A, i) = to_index(A, i) -_maybe_linear_logical_index(::IndexLinear, A, i) = LogicalIndex{Int}(i) - -# Colons get converted to slices by `uncolon` -@inline to_indices(A, inds, I::Tuple{Colon, Vararg{Any}}) = - (uncolon(inds, I), to_indices(A, _maybetail(inds), tail(I))...) - -const CI0 = Union{CartesianIndex{0}, AbstractArray{CartesianIndex{0}}} -uncolon(inds::Tuple{}, I::Tuple{Colon}) = Slice(OneTo(1)) -uncolon(inds::Tuple{}, I::Tuple{Colon, Vararg{Any}}) = Slice(OneTo(1)) -uncolon(inds::Tuple{}, I::Tuple{Colon, Vararg{CI0}}) = Slice(OneTo(1)) -uncolon(inds::Tuple{Any}, I::Tuple{Colon}) = Slice(inds[1]) -uncolon(inds::Tuple{Any}, I::Tuple{Colon, Vararg{Any}}) = Slice(inds[1]) -uncolon(inds::Tuple{Any}, I::Tuple{Colon, Vararg{CI0}}) = Slice(inds[1]) -uncolon(inds::Tuple, I::Tuple{Colon, Vararg{Any}}) = Slice(inds[1]) -uncolon(inds::Tuple, I::Tuple{Colon}) = Slice(OneTo(trailingsize(inds))) -uncolon(inds::Tuple, I::Tuple{Colon, Vararg{CI0}}) = Slice(OneTo(trailingsize(inds))) - -### From abstractarray.jl: Internal multidimensional indexing definitions ### -getindex(x::Number, i::CartesianIndex{0}) = x -getindex(t::Tuple, i::CartesianIndex{1}) = getindex(t, i.I[1]) - -# These are not defined on directly on getindex to avoid -# ambiguities for AbstractArray subtypes. See the note in abstractarray.jl - -@generated function _getindex(l::IndexStyle, A::AbstractArray, I::Union{Real, AbstractArray}...) - N = length(I) - quote - @_inline_meta - @boundscheck checkbounds(A, I...) - _unsafe_getindex(l, _maybe_reshape(l, A, I...), I...) - end -end -# But we can speed up IndexCartesian arrays by reshaping them to the appropriate dimensionality: -_maybe_reshape(::IndexLinear, A::AbstractArray, I...) = A -_maybe_reshape(::IndexCartesian, A::AbstractVector, I...) = A -@inline _maybe_reshape(::IndexCartesian, A::AbstractArray, I...) = __maybe_reshape(A, index_ndims(I...)) -@inline __maybe_reshape(A::AbstractArray{T,N}, ::NTuple{N,Any}) where {T,N} = A -@inline __maybe_reshape(A::AbstractArray, ::NTuple{N,Any}) where {N} = reshape(A, Val{N}) - -@generated function _unsafe_getindex(::IndexStyle, A::AbstractArray, I::Union{Real, AbstractArray}...) - N = length(I) - quote - # This is specifically not inlined to prevent exessive allocations in type unstable code - @nexprs $N d->(I_d = I[d]) - shape = @ncall $N index_shape I - dest = similar(A, shape) - map(unsafe_length, indices(dest)) == map(unsafe_length, shape) || throw_checksize_error(dest, shape) - @ncall $N _unsafe_getindex! dest A I - end -end - -# Always index with the exactly indices provided. -@generated function _unsafe_getindex!(dest::AbstractArray, src::AbstractArray, I::Union{Real, AbstractArray}...) - N = length(I) - quote - $(Expr(:meta, :inline)) - @nexprs $N d->(J_d = I[d]) - D = eachindex(dest) - Ds = start(D) - @inbounds @nloops $N j d->J_d begin - d, Ds = next(D, Ds) - dest[d] = @ncall $N getindex src j - end - dest - end -end - -@noinline throw_checksize_error(A, sz) = throw(DimensionMismatch("output array is the wrong size; expected $sz, got $(size(A))")) - -## setindex! ## -@generated function _setindex!(l::IndexStyle, A::AbstractArray, x, I::Union{Real, AbstractArray}...) - N = length(I) - quote - @_inline_meta - @boundscheck checkbounds(A, I...) - _unsafe_setindex!(l, _maybe_reshape(l, A, I...), x, I...) - A - end -end - -_iterable(v::AbstractArray) = v -_iterable(v) = Iterators.repeated(v) -@generated function _unsafe_setindex!(::IndexStyle, A::AbstractArray, x, I::Union{Real,AbstractArray}...) - N = length(I) - quote - X = _iterable(x) - @nexprs $N d->(I_d = I[d]) - idxlens = @ncall $N index_lengths I - @ncall $N setindex_shape_check X (d->idxlens[d]) - Xs = start(X) - @inbounds @nloops $N i d->I_d begin - v, Xs = next(X, Xs) - @ncall $N setindex! A v i - end - A - end -end - -## - -@generated function findn(A::AbstractArray{T,N}) where {T,N} - quote - nnzA = countnz(A) - @nexprs $N d->(I_d = Vector{Int}(nnzA)) - k = 1 - @nloops $N i A begin - @inbounds if (@nref $N A i) != zero(T) - @nexprs $N d->(I_d[k] = i_d) - k += 1 - end - end - @ntuple $N I - end -end - - -# see discussion in #18364 ... we try not to widen type of the resulting array -# from cumsum or cumprod, but in some cases (+, Bool) we may not have a choice. -rcum_promote_type(op, ::Type{T}, ::Type{S}) where {T,S<:Number} = promote_op(op, T, S) -rcum_promote_type(op, ::Type{T}) where {T<:Number} = rcum_promote_type(op, T,T) -rcum_promote_type(op, ::Type{T}) where {T} = T - -# handle sums of Vector{Bool} and similar. it would be nice to handle -# any AbstractArray here, but it's not clear how that would be possible -rcum_promote_type(op, ::Type{Array{T,N}}) where {T,N} = Array{rcum_promote_type(op,T), N} - -# accumulate_pairwise slightly slower then accumulate, but more numerically -# stable in certain situations (e.g. sums). -# it does double the number of operations compared to accumulate, -# though for cheap operations like + this does not have much impact (20%) -function _accumulate_pairwise!(op::Op, c::AbstractVector{T}, v::AbstractVector, s, i1, n)::T where {T,Op} - @inbounds if n < 128 - s_ = v[i1] - c[i1] = op(s, s_) - for i = i1+1:i1+n-1 - s_ = op(s_, v[i]) - c[i] = op(s, s_) - end - else - n2 = n >> 1 - s_ = _accumulate_pairwise!(op, c, v, s, i1, n2) - s_ = op(s_, _accumulate_pairwise!(op, c, v, op(s, s_), i1+n2, n-n2)) - end - return s_ -end - -function accumulate_pairwise!(op::Op, result::AbstractVector, v::AbstractVector) where Op - li = linearindices(v) - li != linearindices(result) && throw(DimensionMismatch("input and output array sizes and indices must match")) - n = length(li) - n == 0 && return result - i1 = first(li) - @inbounds result[i1] = v1 = v[i1] - n == 1 && return result - _accumulate_pairwise!(op, result, v, v1, i1+1, n-1) - return result -end - -function accumulate_pairwise(op, v::AbstractVector{T}) where T - out = similar(v, rcum_promote_type(op, T)) - return accumulate_pairwise!(op, out, v) -end - -function cumsum!(out, v::AbstractVector, axis::Integer=1) - # for types prone to numerical stability issues, we want - # accumulate_pairwise. - axis == 1 ? accumulate_pairwise!(+, out, v) : copy!(out,v) -end - -function cumsum!(out, v::AbstractVector{<:Integer}, axis::Integer=1) - axis == 1 ? accumulate!(+, out, v) : copy!(out,v) -end - -""" - cumsum(A, dim=1) - -Cumulative sum along a dimension `dim` (defaults to 1). See also [`cumsum!`](@ref) -to use a preallocated output array, both for performance and to control the precision of the -output (e.g. to avoid overflow). - -```jldoctest -julia> a = [1 2 3; 4 5 6] -2×3 Array{Int64,2}: - 1 2 3 - 4 5 6 - -julia> cumsum(a,1) -2×3 Array{Int64,2}: - 1 2 3 - 5 7 9 - -julia> cumsum(a,2) -2×3 Array{Int64,2}: - 1 3 6 - 4 9 15 -``` -""" -function cumsum(A::AbstractArray{T}, axis::Integer=1) where T - out = similar(A, rcum_promote_type(+, T)) - cumsum!(out, A, axis) -end - -""" - cumsum!(B, A, dim::Integer=1) - -Cumulative sum of `A` along a dimension, storing the result in `B`. The dimension defaults -to 1. See also [`cumsum`](@ref). -""" -cumsum!(B, A, axis::Integer=1) = accumulate!(+, B, A, axis) - -""" - cumprod(A, dim=1) - -Cumulative product along a dimension `dim` (defaults to 1). See also -[`cumprod!`](@ref) to use a preallocated output array, both for performance and -to control the precision of the output (e.g. to avoid overflow). - -```jldoctest -julia> a = [1 2 3; 4 5 6] -2×3 Array{Int64,2}: - 1 2 3 - 4 5 6 - -julia> cumprod(a,1) -2×3 Array{Int64,2}: - 1 2 3 - 4 10 18 - -julia> cumprod(a,2) -2×3 Array{Int64,2}: - 1 2 6 - 4 20 120 -``` -""" -cumprod(A::AbstractArray, axis::Integer=1) = accumulate(*, A, axis) - -""" - cumprod!(B, A, dim::Integer=1) - -Cumulative product of `A` along a dimension, storing the result in `B`. The dimension defaults to 1. -See also [`cumprod`](@ref). -""" -cumprod!(B, A, axis::Integer=1) = accumulate!(*, B, A, axis) - -""" - accumulate(op, A, dim=1) - -Cumulative operation `op` along a dimension `dim` (defaults to 1). See also -[`accumulate!`](@ref) to use a preallocated output array, both for performance and -to control the precision of the output (e.g. to avoid overflow). For common operations -there are specialized variants of `accumulate`, see: -[`cumsum`](@ref), [`cumprod`](@ref) - -```jldoctest -julia> accumulate(+, [1,2,3]) -3-element Array{Int64,1}: - 1 - 3 - 6 - -julia> accumulate(*, [1,2,3]) -3-element Array{Int64,1}: - 1 - 2 - 6 -``` -""" -function accumulate(op, A, axis::Integer=1) - out = similar(A, rcum_promote_type(op, eltype(A))) - accumulate!(op, out, A, axis) -end - - -""" - accumulate(op, v0, A) - -Like `accumulate`, but using a starting element `v0`. The first entry of the result will be -`op(v0, first(A))`. For example: - -```jldoctest -julia> accumulate(+, 100, [1,2,3]) -3-element Array{Int64,1}: - 101 - 103 - 106 - -julia> accumulate(min, 0, [1,2,-1]) -3-element Array{Int64,1}: - 0 - 0 - -1 -``` -""" -function accumulate(op, v0, A, axis::Integer=1) - T = rcum_promote_type(op, typeof(v0), eltype(A)) - out = similar(A, T) - accumulate!(op, out, v0, A, 1) -end - -function accumulate!(op::Op, B, A::AbstractVector, axis::Integer=1) where Op - isempty(A) && return B - v1 = first(A) - _accumulate1!(op, B, v1, A, axis) -end - -function accumulate!(op, B, v0, A::AbstractVector, axis::Integer=1) - isempty(A) && return B - v1 = op(v0, first(A)) - _accumulate1!(op, B, v1, A, axis) -end - - -function _accumulate1!(op, B, v1, A::AbstractVector, axis::Integer=1) - axis > 0 || throw(ArgumentError("axis must be a positive integer")) - inds = linearindices(A) - inds == linearindices(B) || throw(DimensionMismatch("linearindices of A and B don't match")) - axis > 1 && return copy!(B, A) - i1 = inds[1] - cur_val = v1 - B[i1] = cur_val - @inbounds for i in inds[2:end] - cur_val = op(cur_val, A[i]) - B[i] = cur_val - end - return B -end - -""" - accumulate!(op, B, A, dim=1) - -Cumulative operation `op` on `A` along a dimension, storing the result in `B`. -The dimension defaults to 1. See also [`accumulate`](@ref). -""" -function accumulate!(op, B, A, axis::Integer=1) - axis > 0 || throw(ArgumentError("axis must be a positive integer")) - inds_t = indices(A) - indices(B) == inds_t || throw(DimensionMismatch("shape of B must match A")) - axis > ndims(A) && return copy!(B, A) - isempty(inds_t[axis]) && return B - if axis == 1 - # We can accumulate to a temporary variable, which allows - # register usage and will be slightly faster - ind1 = inds_t[1] - @inbounds for I in CartesianRange(tail(inds_t)) - tmp = convert(eltype(B), A[first(ind1), I]) - B[first(ind1), I] = tmp - for i_1 = first(ind1)+1:last(ind1) - tmp = op(tmp, A[i_1, I]) - B[i_1, I] = tmp - end - end - else - R1 = CartesianRange(indices(A)[1:axis-1]) # not type-stable - R2 = CartesianRange(indices(A)[axis+1:end]) - _accumulate!(op, B, A, R1, inds_t[axis], R2) # use function barrier - end - return B -end - -@noinline function _accumulate!(op, B, A, R1, ind, R2) - # Copy the initial element in each 1d vector along dimension `axis` - i = first(ind) - @inbounds for J in R2, I in R1 - B[I, i, J] = A[I, i, J] - end - # Accumulate - @inbounds for J in R2, i in first(ind)+1:last(ind), I in R1 - B[I, i, J] = op(B[I, i-1, J], A[I, i, J]) - end - B -end - -### from abstractarray.jl - -function fill!(A::AbstractArray{T}, x) where T - xT = convert(T, x) - for I in eachindex(A) - @inbounds A[I] = xT - end - A -end - -""" - copy!(dest, src) -> dest - -Copy all elements from collection `src` to array `dest`. -""" -copy!(dest, src) - -function copy!(dest::AbstractArray{T,N}, src::AbstractArray{T,N}) where {T,N} - @boundscheck checkbounds(dest, indices(src)...) - for I in eachindex(IndexStyle(src,dest), src) - @inbounds dest[I] = src[I] - end - dest -end - -@generated function copy!{T1,T2,N}(dest::AbstractArray{T1,N}, - Rdest::CartesianRange{CartesianIndex{N}}, - src::AbstractArray{T2,N}, - Rsrc::CartesianRange{CartesianIndex{N}}) - quote - isempty(Rdest) && return dest - if size(Rdest) != size(Rsrc) - throw(ArgumentError("source and destination must have same size (got $(size(Rsrc)) and $(size(Rdest)))")) - end - @boundscheck checkbounds(dest, Rdest.start) - @boundscheck checkbounds(dest, Rdest.stop) - @boundscheck checkbounds(src, Rsrc.start) - @boundscheck checkbounds(src, Rsrc.stop) - ΔI = Rdest.start - Rsrc.start - # TODO: restore when #9080 is fixed - # for I in Rsrc - # @inbounds dest[I+ΔI] = src[I] - @nloops $N i (n->Rsrc.start[n]:Rsrc.stop[n]) begin - @inbounds @nref($N,dest,n->i_n+ΔI[n]) = @nref($N,src,i) - end - dest - end -end - -""" - copy!(dest, Rdest::CartesianRange, src, Rsrc::CartesianRange) -> dest - -Copy the block of `src` in the range of `Rsrc` to the block of `dest` -in the range of `Rdest`. The sizes of the two regions must match. -""" -copy!(::AbstractArray, ::CartesianRange, ::AbstractArray, ::CartesianRange) - -# circshift! -circshift!(dest::AbstractArray, src, ::Tuple{}) = copy!(dest, src) -""" - circshift!(dest, src, shifts) - -Circularly shift the data in `src`, storing the result in -`dest`. `shifts` specifies the amount to shift in each dimension. - -The `dest` array must be distinct from the `src` array (they cannot -alias each other). - -See also [`circshift`](@ref). -""" -@noinline function circshift!(dest::AbstractArray{T,N}, src, shiftamt::DimsInteger) where {T,N} - dest === src && throw(ArgumentError("dest and src must be separate arrays")) - inds = indices(src) - indices(dest) == inds || throw(ArgumentError("indices of src and dest must match (got $inds and $(indices(dest)))")) - _circshift!(dest, (), src, (), inds, fill_to_length(shiftamt, 0, Val{N})) -end -circshift!(dest::AbstractArray, src, shiftamt) = circshift!(dest, src, (shiftamt...,)) - -# For each dimension, we copy the first half of src to the second half -# of dest, and the second half of src to the first half of dest. This -# uses a recursive bifurcation strategy so that these splits can be -# encoded by ranges, which means that we need only one call to `mod` -# per dimension rather than one call per index. -# `rdest` and `rsrc` are tuples-of-ranges that grow one dimension at a -# time; when all the dimensions have been filled in, you call `copy!` -# for that block. In other words, in two dimensions schematically we -# have the following call sequence (--> means a call): -# circshift!(dest, src, shiftamt) --> -# _circshift!(dest, src, ("first half of dim1",)) --> -# _circshift!(dest, src, ("first half of dim1", "first half of dim2")) --> copy! -# _circshift!(dest, src, ("first half of dim1", "second half of dim2")) --> copy! -# _circshift!(dest, src, ("second half of dim1",)) --> -# _circshift!(dest, src, ("second half of dim1", "first half of dim2")) --> copy! -# _circshift!(dest, src, ("second half of dim1", "second half of dim2")) --> copy! -@inline function _circshift!(dest, rdest, src, rsrc, - inds::Tuple{AbstractUnitRange,Vararg{Any}}, - shiftamt::Tuple{Integer,Vararg{Any}}) - ind1, d = inds[1], shiftamt[1] - s = mod(d, length(ind1)) - sf, sl = first(ind1)+s, last(ind1)-s - r1, r2 = first(ind1):sf-1, sf:last(ind1) - r3, r4 = first(ind1):sl, sl+1:last(ind1) - tinds, tshiftamt = tail(inds), tail(shiftamt) - _circshift!(dest, (rdest..., r1), src, (rsrc..., r4), tinds, tshiftamt) - _circshift!(dest, (rdest..., r2), src, (rsrc..., r3), tinds, tshiftamt) -end -# At least one of inds, shiftamt is empty -function _circshift!(dest, rdest, src, rsrc, inds, shiftamt) - copy!(dest, CartesianRange(rdest), src, CartesianRange(rsrc)) -end - -# circcopy! -""" - circcopy!(dest, src) - -Copy `src` to `dest`, indexing each dimension modulo its length. -`src` and `dest` must have the same size, but can be offset in -their indices; any offset results in a (circular) wraparound. If the -arrays have overlapping indices, then on the domain of the overlap -`dest` agrees with `src`. - -# Example -```julia-repl -julia> src = reshape(collect(1:16), (4,4)) -4×4 Array{Int64,2}: - 1 5 9 13 - 2 6 10 14 - 3 7 11 15 - 4 8 12 16 - -julia> dest = OffsetArray{Int}((0:3,2:5)) - -julia> circcopy!(dest, src) -OffsetArrays.OffsetArray{Int64,2,Array{Int64,2}} with indices 0:3×2:5: - 8 12 16 4 - 5 9 13 1 - 6 10 14 2 - 7 11 15 3 - -julia> dest[1:3,2:4] == src[1:3,2:4] -true -``` -""" -function circcopy!(dest, src) - dest === src && throw(ArgumentError("dest and src must be separate arrays")) - indssrc, indsdest = indices(src), indices(dest) - if (szsrc = map(length, indssrc)) != (szdest = map(length, indsdest)) - throw(DimensionMismatch("src and dest must have the same sizes (got $szsrc and $szdest)")) - end - shift = map((isrc, idest)->first(isrc)-first(idest), indssrc, indsdest) - all(x->x==0, shift) && return copy!(dest, src) - _circcopy!(dest, (), indsdest, src, (), indssrc) -end - -# This uses the same strategy described above for _circshift! -@inline function _circcopy!(dest, rdest, indsdest::Tuple{AbstractUnitRange,Vararg{Any}}, - src, rsrc, indssrc::Tuple{AbstractUnitRange,Vararg{Any}}) - indd1, inds1 = indsdest[1], indssrc[1] - l = length(indd1) - s = mod(first(inds1)-first(indd1), l) - sdf = first(indd1)+s - rd1, rd2 = first(indd1):sdf-1, sdf:last(indd1) - ssf = last(inds1)-s - rs1, rs2 = first(inds1):ssf, ssf+1:last(inds1) - tindsd, tindss = tail(indsdest), tail(indssrc) - _circcopy!(dest, (rdest..., rd1), tindsd, src, (rsrc..., rs2), tindss) - _circcopy!(dest, (rdest..., rd2), tindsd, src, (rsrc..., rs1), tindss) -end - -# At least one of indsdest, indssrc are empty (and both should be, since we've checked) -function _circcopy!(dest, rdest, indsdest, src, rsrc, indssrc) - copy!(dest, CartesianRange(rdest), src, CartesianRange(rsrc)) -end - -### BitArrays - -## getindex - -# contiguous multidimensional indexing: if the first dimension is a range, -# we can get some performance from using copy_chunks! -@inline function _unsafe_getindex!(X::BitArray, B::BitArray, I0::Union{UnitRange{Int},Slice}) - copy_chunks!(X.chunks, 1, B.chunks, indexoffset(I0)+1, length(I0)) - return X -end - -# Optimization where the inner dimension is contiguous improves perf dramatically -@generated function _unsafe_getindex!(X::BitArray, B::BitArray, - I0::Union{Slice,UnitRange{Int}}, I::Union{Int,UnitRange{Int},Slice}...) - N = length(I) - quote - $(Expr(:meta, :inline)) - @nexprs $N d->(I_d = I[d]) - - idxlens = @ncall $N index_lengths I0 I - - f0 = indexoffset(I0)+1 - l0 = idxlens[1] - - gap_lst_1 = 0 - @nexprs $N d->(gap_lst_{d+1} = idxlens[d+1]) - stride = 1 - ind = f0 - @nexprs $N d->begin - stride *= size(B, d) - stride_lst_d = stride - ind += stride * indexoffset(I_d) - gap_lst_{d+1} *= stride - end - - storeind = 1 - Xc, Bc = X.chunks, B.chunks - @nloops($N, i, d->(1:idxlens[d+1]), - d->nothing, # PRE - d->(ind += stride_lst_d - gap_lst_d), # POST - begin # BODY - copy_chunks!(Xc, storeind, Bc, ind, l0) - storeind += l0 - end) - return X - end -end - -# in the general multidimensional non-scalar case, can we do about 10% better -# in most cases by manually hoisting the bitarray chunks access out of the loop -# (This should really be handled by the compiler or with an immutable BitArray) -@generated function _unsafe_getindex!(X::BitArray, B::BitArray, I::Union{Int,AbstractArray{Int}}...) - N = length(I) - quote - $(Expr(:meta, :inline)) - stride_1 = 1 - @nexprs $N d->(stride_{d+1} = stride_d*size(B, d)) - $(Symbol(:offset_, N)) = 1 - ind = 0 - Xc, Bc = X.chunks, B.chunks - @nloops $N i d->I[d] d->(@inbounds offset_{d-1} = offset_d + (i_d-1)*stride_d) begin - ind += 1 - unsafe_bitsetindex!(Xc, unsafe_bitgetindex(Bc, offset_0), ind) - end - return X - end -end - -## setindex! - -function copy_to_bitarray_chunks!(Bc::Vector{UInt64}, pos_d::Int, C::StridedArray, pos_s::Int, numbits::Int) - bind = pos_d - cind = pos_s - lastind = pos_d + numbits - 1 - @inbounds while bind ≤ lastind - unsafe_bitsetindex!(Bc, Bool(C[cind]), bind) - bind += 1 - cind += 1 - end -end - -# Note: the next two functions rely on the following definition of the conversion to Bool: -# convert(::Type{Bool}, x::Real) = x==0 ? false : x==1 ? true : throw(InexactError()) -# they're used to pre-emptively check in bulk when possible, which is much faster. -# Also, the functions can be overloaded for custom types T<:Real : -# a) in the unlikely eventuality that they use a different logic for Bool conversion -# b) to skip the check if not necessary -@inline try_bool_conversion(x::Real) = x == 0 || x == 1 || throw(InexactError()) -@inline unchecked_bool_convert(x::Real) = x == 1 - -function copy_to_bitarray_chunks!(Bc::Vector{UInt64}, pos_d::Int, C::StridedArray{<:Real}, pos_s::Int, numbits::Int) - @inbounds for i = (1:numbits) + pos_s - 1 - try_bool_conversion(C[i]) - end - - kd0, ld0 = get_chunks_id(pos_d) - kd1, ld1 = get_chunks_id(pos_d + numbits - 1) - - delta_kd = kd1 - kd0 - - u = _msk64 - if delta_kd == 0 - msk_d0 = msk_d1 = ~(u << ld0) | (u << (ld1+1)) - lt0 = ld1 - else - msk_d0 = ~(u << ld0) - msk_d1 = (u << (ld1+1)) - lt0 = 63 - end - - bind = kd0 - ind = pos_s - @inbounds if ld0 > 0 - c = UInt64(0) - for j = ld0:lt0 - c |= (UInt64(unchecked_bool_convert(C[ind])) << j) - ind += 1 - end - Bc[kd0] = (Bc[kd0] & msk_d0) | (c & ~msk_d0) - bind += 1 - end - - nc = _div64(numbits - ind + pos_s) - @inbounds for i = 1:nc - c = UInt64(0) - for j = 0:63 - c |= (UInt64(unchecked_bool_convert(C[ind])) << j) - ind += 1 - end - Bc[bind] = c - bind += 1 - end - - @inbounds if bind ≤ kd1 - @assert bind == kd1 - c = UInt64(0) - for j = 0:ld1 - c |= (UInt64(unchecked_bool_convert(C[ind])) << j) - ind += 1 - end - Bc[kd1] = (Bc[kd1] & msk_d1) | (c & ~msk_d1) - end -end - -# contiguous multidimensional indexing: if the first dimension is a range, -# we can get some performance from using copy_chunks! - -@inline function setindex!(B::BitArray, X::StridedArray, J0::Union{Colon,UnitRange{Int}}) - I0 = to_indices(B, (J0,))[1] - @boundscheck checkbounds(B, I0) - l0 = length(I0) - setindex_shape_check(X, l0) - l0 == 0 && return B - f0 = indexoffset(I0)+1 - copy_to_bitarray_chunks!(B.chunks, f0, X, 1, l0) - return B -end - -@inline function setindex!(B::BitArray, X::StridedArray, - I0::Union{Colon,UnitRange{Int}}, I::Union{Int,UnitRange{Int},Colon}...) - J = to_indices(B, (I0, I...)) - @boundscheck checkbounds(B, J...) - _unsafe_setindex!(B, X, J...) -end -@generated function _unsafe_setindex!(B::BitArray, X::StridedArray, - I0::Union{Slice,UnitRange{Int}}, I::Union{Int,UnitRange{Int},Slice}...) - N = length(I) - quote - idxlens = @ncall $N index_lengths I0 d->I[d] - @ncall $N setindex_shape_check X idxlens[1] d->idxlens[d+1] - isempty(X) && return B - f0 = indexoffset(I0)+1 - l0 = idxlens[1] - - gap_lst_1 = 0 - @nexprs $N d->(gap_lst_{d+1} = idxlens[d+1]) - stride = 1 - ind = f0 - @nexprs $N d->begin - stride *= size(B, d) - stride_lst_d = stride - ind += stride * indexoffset(I[d]) - gap_lst_{d+1} *= stride - end - - refind = 1 - Bc = B.chunks - @nloops($N, i, d->I[d], - d->nothing, # PRE - d->(ind += stride_lst_d - gap_lst_d), # POST - begin # BODY - copy_to_bitarray_chunks!(Bc, ind, X, refind, l0) - refind += l0 - end) - - return B - end -end - -@inline function setindex!(B::BitArray, x, - I0::Union{Colon,UnitRange{Int}}, I::Union{Int,UnitRange{Int},Colon}...) - J = to_indices(B, (I0, I...)) - @boundscheck checkbounds(B, J...) - _unsafe_setindex!(B, x, J...) -end -@generated function _unsafe_setindex!(B::BitArray, x, - I0::Union{Slice,UnitRange{Int}}, I::Union{Int,UnitRange{Int},Slice}...) - N = length(I) - quote - y = Bool(x) - idxlens = @ncall $N index_lengths I0 d->I[d] - - f0 = indexoffset(I0)+1 - l0 = idxlens[1] - l0 == 0 && return B - @nexprs $N d->(isempty(I[d]) && return B) - - gap_lst_1 = 0 - @nexprs $N d->(gap_lst_{d+1} = idxlens[d+1]) - stride = 1 - ind = f0 - @nexprs $N d->begin - stride *= size(B, d) - stride_lst_d = stride - ind += stride * indexoffset(I[d]) - gap_lst_{d+1} *= stride - end - - @nloops($N, i, d->I[d], - d->nothing, # PRE - d->(ind += stride_lst_d - gap_lst_d), # POST - fill_chunks!(B.chunks, y, ind, l0) # BODY - ) - - return B - end -end - -## findn - -@generated function findn(B::BitArray{N}) where N - quote - nnzB = countnz(B) - I = ntuple(x->Vector{Int}(nnzB), Val{$N}) - if nnzB > 0 - count = 1 - @nloops $N i B begin - if (@nref $N B i) # TODO: should avoid bounds checking - @nexprs $N d->(I[d][count] = i_d) - count += 1 - end - end - end - return I - end -end - -## isassigned - -@generated function isassigned(B::BitArray, I_0::Int, I::Int...) - N = length(I) - quote - @nexprs $N d->(I_d = I[d]) - stride = 1 - index = I_0 - @nexprs $N d->begin - l = size(B,d) - stride *= l - 1 <= I_{d-1} <= l || return false - index += (I_d - 1) * stride - end - return isassigned(B, index) - end -end - -## permutedims - -## Permute array dims ## - -function permutedims(B::StridedArray, perm) - dimsB = size(B) - ndimsB = length(dimsB) - (ndimsB == length(perm) && isperm(perm)) || throw(ArgumentError("no valid permutation of dimensions")) - dimsP = ntuple(i->dimsB[perm[i]], ndimsB)::typeof(dimsB) - P = similar(B, dimsP) - permutedims!(P, B, perm) -end - -function checkdims_perm{TP,TB,N}(P::AbstractArray{TP,N}, B::AbstractArray{TB,N}, perm) - indsB = indices(B) - length(perm) == N || throw(ArgumentError("expected permutation of size $N, but length(perm)=$(length(perm))")) - isperm(perm) || throw(ArgumentError("input is not a permutation")) - indsP = indices(P) - for i = 1:length(perm) - indsP[i] == indsB[perm[i]] || throw(DimensionMismatch("destination tensor of incorrect size")) - end - nothing -end - -for (V, PT, BT) in [((:N,), BitArray, BitArray), ((:T,:N), Array, StridedArray)] - @eval @generated function permutedims!(P::$PT{$(V...)}, B::$BT{$(V...)}, perm) where $(V...) - quote - checkdims_perm(P, B, perm) - - #calculates all the strides - strides_1 = 0 - @nexprs $N d->(strides_{d+1} = stride(B, perm[d])) - - #Creates offset, because indexing starts at 1 - offset = 1 - sum(@ntuple $N d->strides_{d+1}) - - if isa(B, SubArray) - offset += first_index(B::SubArray) - 1 - B = B.parent - end - - ind = 1 - @nexprs 1 d->(counts_{$N+1} = strides_{$N+1}) # a trick to set counts_($N+1) - @nloops($N, i, P, - d->(counts_d = strides_d), # PRE - d->(counts_{d+1} += strides_{d+1}), # POST - begin # BODY - sumc = sum(@ntuple $N d->counts_{d+1}) - @inbounds P[ind] = B[sumc+offset] - ind += 1 - end) - - return P - end - end -end - -## unique across dim - -# TODO: this doesn't fit into the new hashing scheme in any obvious way - -struct Prehashed - hash::UInt -end -hash(x::Prehashed) = x.hash - -""" - unique(itr[, dim]) - -Returns an array containing only the unique elements of the iterable `itr`, in -the order that the first of each set of equivalent elements originally appears. -If `dim` is specified, returns unique regions of the array `itr` along `dim`. - -```jldoctest -julia> A = map(isodd, reshape(collect(1:8), (2,2,2))) -2×2×2 Array{Bool,3}: -[:, :, 1] = - true true - false false - -[:, :, 2] = - true true - false false - -julia> unique(A) -2-element Array{Bool,1}: - true - false - -julia> unique(A, 2) -2×1×2 Array{Bool,3}: -[:, :, 1] = - true - false - -[:, :, 2] = - true - false - -julia> unique(A, 3) -2×2×1 Array{Bool,3}: -[:, :, 1] = - true true - false false -``` -""" -@generated function unique(A::AbstractArray{T,N}, dim::Int) where {T,N} - inds = inds -> zeros(UInt, inds) - quote - 1 <= dim <= $N || return copy(A) - hashes = similar($inds, indices(A, dim)) - - # Compute hash for each row - k = 0 - @nloops $N i A d->(if d == dim; k = i_d; end) begin - @inbounds hashes[k] = hash(hashes[k], hash((@nref $N A i))) - end - - # Collect index of first row for each hash - uniquerow = similar(Array{Int}, indices(A, dim)) - firstrow = Dict{Prehashed,Int}() - for k = indices(A, dim) - uniquerow[k] = get!(firstrow, Prehashed(hashes[k]), k) - end - uniquerows = collect(values(firstrow)) - - # Check for collisions - collided = similar(falses, indices(A, dim)) - @inbounds begin - @nloops $N i A d->(if d == dim - k = i_d - j_d = uniquerow[k] - else - j_d = i_d - end) begin - if (@nref $N A j) != (@nref $N A i) - collided[k] = true - end - end - end - - if any(collided) - nowcollided = similar(BitArray, indices(A, dim)) - while any(collided) - # Collect index of first row for each collided hash - empty!(firstrow) - for j = indices(A, dim) - collided[j] || continue - uniquerow[j] = get!(firstrow, Prehashed(hashes[j]), j) - end - for v in values(firstrow) - push!(uniquerows, v) - end - - # Check for collisions - fill!(nowcollided, false) - @nloops $N i A d->begin - if d == dim - k = i_d - j_d = uniquerow[k] - (!collided[k] || j_d == k) && continue - else - j_d = i_d - end - end begin - if (@nref $N A j) != (@nref $N A i) - nowcollided[k] = true - end - end - (collided, nowcollided) = (nowcollided, collided) - end - end - - @nref $N A d->d == dim ? sort!(uniquerows) : (indices(A, d)) - end -end - -""" - extrema(A, dims) -> Array{Tuple} - -Compute the minimum and maximum elements of an array over the given dimensions. - -# Example -```jldoctest -julia> A = reshape(collect(1:2:16), (2,2,2)) -2×2×2 Array{Int64,3}: -[:, :, 1] = - 1 5 - 3 7 - -[:, :, 2] = - 9 13 - 11 15 - -julia> extrema(A, (1,2)) -1×1×2 Array{Tuple{Int64,Int64},3}: -[:, :, 1] = - (1, 7) - -[:, :, 2] = - (9, 15) -``` -""" -function extrema(A::AbstractArray, dims) - sz = [size(A)...] - sz[[dims...]] = 1 - B = Array{Tuple{eltype(A),eltype(A)}}(sz...) - return extrema!(B, A) -end - -@noinline function extrema!(B, A) - sA = size(A) - sB = size(B) - for I in CartesianRange(sB) - AI = A[I] - B[I] = (AI, AI) - end - Bmax = CartesianIndex(sB) - @inbounds @simd for I in CartesianRange(sA) - J = min(Bmax,I) - BJ = B[J] - AI = A[I] - if AI < BJ[1] - B[J] = (AI, BJ[2]) - elseif AI > BJ[2] - B[J] = (BJ[1], AI) - end - end - return B -end diff --git a/julia-0.6.3/share/julia/base/multimedia.jl b/julia-0.6.3/share/julia/base/multimedia.jl deleted file mode 100644 index 3bfcc5b..0000000 --- a/julia-0.6.3/share/julia/base/multimedia.jl +++ /dev/null @@ -1,294 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -module Multimedia - -export Display, display, pushdisplay, popdisplay, displayable, redisplay, - MIME, @MIME_str, reprmime, stringmime, istextmime, - mimewritable, TextDisplay - -########################################################################### -# We define a singleton type MIME{mime symbol} for each MIME type, so -# that Julia's dispatch and overloading mechanisms can be used to -# dispatch show and to add conversions for new types. - -# defined in sysimg.jl for bootstrapping: -# struct MIME{mime} end -# macro MIME_str(s) -import Base: MIME, @MIME_str - -import Base: show, print, string, convert -MIME(s) = MIME{Symbol(s)}() -show(io::IO, ::MIME{mime}) where {mime} = print(io, "MIME type ", string(mime)) -print(io::IO, ::MIME{mime}) where {mime} = print(io, mime) - -########################################################################### -# For any type T one can define show(io, ::MIME"type", x::T) = ... -# in order to provide a way to export T as a given mime type. - -""" - mimewritable(mime, x) - -Returns a boolean value indicating whether or not the object `x` can be written as the given -`mime` type. (By default, this is determined automatically by the existence of the -corresponding [`show`](@ref) method for `typeof(x)`.) -""" -mimewritable(::MIME{mime}, x) where {mime} = - method_exists(show, Tuple{IO, MIME{mime}, typeof(x)}) - -# it is convenient to accept strings instead of ::MIME -show(io::IO, m::AbstractString, x) = show(io, MIME(m), x) -mimewritable(m::AbstractString, x) = mimewritable(MIME(m), x) - -verbose_show(io, m, x) = show(IOContext(io, :limit => false), m, x) - -""" - reprmime(mime, x) - -Returns an `AbstractString` or `Vector{UInt8}` containing the representation of -`x` in the requested `mime` type, as written by `show` (throwing a -`MethodError` if no appropriate `show` is available). An `AbstractString` is -returned for MIME types with textual representations (such as `"text/html"` or -`"application/postscript"`), whereas binary data is returned as -`Vector{UInt8}`. (The function `istextmime(mime)` returns whether or not Julia -treats a given `mime` type as text.) - -As a special case, if `x` is an `AbstractString` (for textual MIME types) or a -`Vector{UInt8}` (for binary MIME types), the `reprmime` function assumes that -`x` is already in the requested `mime` format and simply returns `x`. This -special case does not apply to the `"text/plain"` MIME type. This is useful so -that raw data can be passed to `display(m::MIME, x)`. -""" -reprmime(m::MIME, x) = istextmime(m) ? _textreprmime(m, x) : _binreprmime(m, x) - -# strings are shown escaped for text/plain -_textreprmime(m::MIME, x) = sprint(verbose_show, m, x) -_textreprmime(::MIME, x::AbstractString) = x -_textreprmime(m::MIME"text/plain", x::AbstractString) = - sprint(verbose_show, m, x) - -function _binreprmime(m::MIME, x) - s = IOBuffer() - verbose_show(s, m, x) - take!(s) -end -_binreprmime(m::MIME, x::Vector{UInt8}) = x - -""" - stringmime(mime, x) - -Returns an `AbstractString` containing the representation of `x` in the -requested `mime` type. This is similar to [`reprmime`](@ref) except -that binary data is base64-encoded as an ASCII string. -""" -stringmime(m::MIME, x) = istextmime(m) ? reprmime(m, x) : _binstringmime(m, x) - -_binstringmime(m::MIME, x) = base64encode(verbose_show, m, x) -_binstringmime(m::MIME, x::Vector{UInt8}) = base64encode(write, x) - -""" - istextmime(m::MIME) - -Determine whether a MIME type is text data. MIME types are assumed to be binary -data except for a set of types known to be text data (possibly Unicode). -""" -istextmime(m::MIME) = startswith(string(m), "text/") - -# it is convenient to accept strings instead of ::MIME -istextmime(m::AbstractString) = istextmime(MIME(m)) -reprmime(m::AbstractString, x) = reprmime(MIME(m), x) -stringmime(m::AbstractString, x) = stringmime(MIME(m), x) - -for mime in ["application/atom+xml", "application/ecmascript", - "application/javascript", "application/julia", - "application/json", "application/postscript", - "application/rdf+xml", "application/rss+xml", - "application/x-latex", "application/xhtml+xml", "application/xml", - "application/xml-dtd", "image/svg+xml", "model/vrml", - "model/x3d+vrml", "model/x3d+xml"] - istextmime(::MIME{Symbol(mime)}) = true -end - -########################################################################### -# We have an abstract Display class that can be subclassed in order to -# define new rich-display output devices. A typical subclass should -# overload display(d::Display, m::MIME, x) for supported MIME types m, -# (typically using reprmime or stringmime to get the MIME -# representation of x) and should also overload display(d::Display, x) -# to display x in whatever MIME type is preferred by the Display and -# is writable by x. display(..., x) should throw a MethodError if x -# cannot be displayed. The return value of display(...) is up to the -# Display type. - -abstract type Display end - -# it is convenient to accept strings instead of ::MIME -display(d::Display, mime::AbstractString, x) = display(d, MIME(mime), x) -display(mime::AbstractString, x) = display(MIME(mime), x) - -""" - displayable(mime) -> Bool - displayable(d::Display, mime) -> Bool - -Returns a boolean value indicating whether the given `mime` type (string) is displayable by -any of the displays in the current display stack, or specifically by the display `d` in the -second variant. -""" -displayable(d::Display, mime::AbstractString) = displayable(d, MIME(mime)) -displayable(mime::AbstractString) = displayable(MIME(mime)) - -# simplest display, which only knows how to display text/plain - -""" - TextDisplay(io::IO) - -Returns a `TextDisplay <: Display`, which displays any object as the text/plain MIME type -(by default), writing the text representation to the given I/O stream. (This is how -objects are printed in the Julia REPL.) -""" -struct TextDisplay <: Display - io::IO -end -display(d::TextDisplay, M::MIME"text/plain", x) = show(d.io, M, x) -display(d::TextDisplay, x) = display(d, MIME"text/plain"(), x) - -# if you explicitly call display("text/foo", x), it should work on a TextDisplay: -displayable(d::TextDisplay, M::MIME) = istextmime(M) -function display(d::TextDisplay, M::MIME, x) - displayable(d, M) || throw(MethodError(display, (d, M, x))) - show(d.io, M, x) -end - -import Base: close, flush -flush(d::TextDisplay) = flush(d.io) -close(d::TextDisplay) = close(d.io) - -########################################################################### -# We keep a stack of Displays, and calling display(x) uses the topmost -# Display that is capable of displaying x (doesn't throw an error) - -const displays = Display[] -function pushdisplay(d::Display) - global displays - push!(displays, d) -end -popdisplay() = pop!(displays) -function popdisplay(d::Display) - for i = length(displays):-1:1 - if d == displays[i] - return splice!(displays, i) - end - end - throw(KeyError(d)) -end -function reinit_displays() - empty!(displays) - pushdisplay(TextDisplay(STDOUT)) -end - -xdisplayable(D::Display, args...) = applicable(display, D, args...) - -""" - display(x) - display(d::Display, x) - display(mime, x) - display(d::Display, mime, x) - -Display `x` using the topmost applicable display in the display stack, typically using the -richest supported multimedia output for `x`, with plain-text [`STDOUT`](@ref) output as a fallback. -The `display(d, x)` variant attempts to display `x` on the given display `d` only, throwing -a [`MethodError`](@ref) if `d` cannot display objects of this type. - -In general, you cannot assume that `display` output goes to `STDOUT` (unlike [`print(x)`](@ref) or -[`show(x)`](@ref)). For example, `display(x)` may open up a separate window with an image. -`display(x)` means "show `x` in the best way you can for the current output device(s)." -If you want REPL-like text output that is guaranteed to go to `STDOUT`, use -[`show(STDOUT, "text/plain", x)`](@ref) instead. - -There are also two variants with a `mime` argument (a MIME type string, such as -`"image/png"`), which attempt to display `x` using the requested MIME type *only*, throwing -a `MethodError` if this type is not supported by either the display(s) or by `x`. With these -variants, one can also supply the "raw" data in the requested MIME type by passing -`x::AbstractString` (for MIME types with text-based storage, such as text/html or -application/postscript) or `x::Vector{UInt8}` (for binary MIME types). -""" -function display(x) - for i = length(displays):-1:1 - if xdisplayable(displays[i], x) - try - return display(displays[i], x) - catch e - isa(e, MethodError) && e.f in (display, show) || - rethrow() - end - end - end - throw(MethodError(display, (x,))) -end - -function display(m::MIME, x) - for i = length(displays):-1:1 - if xdisplayable(displays[i], m, x) - try - return display(displays[i], m, x) - catch e - isa(e, MethodError) && e.f == display || - rethrow() - end - end - end - throw(MethodError(display, (m, x))) -end - -displayable(d::D, ::MIME{mime}) where {D<:Display,mime} = - method_exists(display, Tuple{D,MIME{mime},Any}) - -function displayable(m::MIME) - for d in displays - displayable(d, m) && return true - end - return false -end - -########################################################################### -# The redisplay method can be overridden by a Display in order to -# update an existing display (instead of, for example, opening a new -# window), and is used by the IJulia interface to defer display -# until the next interactive prompt. This is especially useful -# for Matlab/Pylab-like stateful plotting interfaces, where -# a plot is created and then modified many times (xlabel, title, etc.). - -function redisplay(x) - for i = length(displays):-1:1 - if xdisplayable(displays[i], x) - try - return redisplay(displays[i], x) - catch e - isa(e, MethodError) && e.f in (redisplay, display, show) || - rethrow() - end - end - end - throw(MethodError(redisplay, (x,))) -end - -function redisplay(m::Union{MIME,AbstractString}, x) - for i = length(displays):-1:1 - if xdisplayable(displays[i], m, x) - try - return redisplay(displays[i], m, x) - catch e - isa(e, MethodError) && e.f in (redisplay, display) || - rethrow() - end - end - end - throw(MethodError(redisplay, (m, x))) -end - -# default redisplay is simply to call display -redisplay(d::Display, x) = display(d, x) -redisplay(d::Display, m::Union{MIME,AbstractString}, x) = display(d, m, x) - -########################################################################### - -end # module diff --git a/julia-0.6.3/share/julia/base/multinverses.jl b/julia-0.6.3/share/julia/base/multinverses.jl deleted file mode 100644 index 5b60e76..0000000 --- a/julia-0.6.3/share/julia/base/multinverses.jl +++ /dev/null @@ -1,159 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -module MultiplicativeInverses - -import Base: div, divrem, rem, unsigned -using Base: IndexLinear, IndexCartesian, tail -export multiplicativeinverse - -unsigned(::Type{Int8}) = UInt8 -unsigned(::Type{Int16}) = UInt16 -unsigned(::Type{Int32}) = UInt32 -unsigned(::Type{Int64}) = UInt64 -unsigned(::Type{Int128}) = UInt128 -unsigned{T<:Unsigned}(::Type{T}) = T - -abstract type MultiplicativeInverse{T} end - -# Computes integer division by a constant using multiply, add, and bitshift. - -# The idea here is to compute floor(n/d) as floor(m*n/2^p) and then -# implement division by 2^p as a right bitshift. The trick is finding -# m (the "magic number") and p. Roughly speaking, one can think of this as -# floor(n/d) = floor((n/2^p) * (2^p/d)) -# so that m is effectively 2^p/d. -# -# A few examples are illustrative: -# Division of Int32 by 3: -# floor((2^32+2)/3 * n/2^32) = floor(n/3 + 2n/(3*2^32)) -# The correction term, 2n/(3*2^32), is strictly less than 1/3 for any -# nonnegative n::Int32, so this divides any nonnegative Int32 by 3. -# (When n < 0, we add 1, and one can show that this computes -# ceil(n/d) = -floor(abs(n)/d).) -# -# Division of Int32 by 5 uses a magic number (2^33+3)/5 and then -# right-shifts by 33 rather than 32. Consequently, the size of the -# shift depends on the specific denominator. -# -# Division of Int32 by 7 would be problematic, because a viable magic -# number of (2^34+5)/7 is too big to represent as an Int32 (the -# unsigned representation needs 32 bits). We can exploit wrap-around -# and use (2^34+5)/7 - 2^32 (an Int32 < 0), and then correct the -# 64-bit product with an add (the `addmul` field below). -# -# Further details can be found in Hacker's Delight, Chapter 10. - -struct SignedMultiplicativeInverse{T<:Signed} <: MultiplicativeInverse{T} - divisor::T - multiplier::T - addmul::Int8 - shift::UInt8 - - function SignedMultiplicativeInverse{T}(d::T) where T<:Signed - d == 0 && throw(ArgumentError("cannot compute magic for d == $d")) - signedmin = unsigned(typemin(T)) - UT = unsigned(T) - - # Algorithm from Hacker's Delight, section 10-4 - ad = unsigned(abs(d)) - t = signedmin + signbit(d) - anc = t - one(UT) - rem(t, ad) # absolute value of nc - p = sizeof(d)*8 - 1 - q1, r1 = divrem(signedmin, anc) - q2, r2 = divrem(signedmin, ad) - while true - p += 1 # loop until we find a satisfactory p - # update q1, r1 = divrem(2^p, abs(nc)) - q1 = q1<<1 - r1 = r1<<1 - if r1 >= anc # must be unsigned comparison - q1 += one(UT) - r1 -= anc - end - # update q2, r2 = divrem(2^p, abs(d)) - q2 = q2<<1 - r2 = r2<<1 - if r2 >= ad - q2 += one(UT) - r2 -= ad - end - delta = ad - r2 - (q1 < delta || (q1 == delta && r1 == 0)) || break - end - - m = flipsign((q2 + one(UT)) % T, d) # resulting magic number - s = p - sizeof(d)*8 # resulting shift - new(d, m, d > 0 && m < 0 ? Int8(1) : d < 0 && m > 0 ? Int8(-1) : Int8(0), UInt8(s)) - end -end -SignedMultiplicativeInverse(x::Signed) = SignedMultiplicativeInverse{typeof(x)}(x) - -struct UnsignedMultiplicativeInverse{T<:Unsigned} <: MultiplicativeInverse{T} - divisor::T - multiplier::T - add::Bool - shift::UInt8 - - function UnsignedMultiplicativeInverse{T}(d::T) where T<:Unsigned - d == 0 && throw(ArgumentError("cannot compute magic for d == $d")) - u2 = convert(T, 2) - add = false - signedmin = one(d) << (sizeof(d)*8-1) - signedmax = signedmin - one(T) - allones = (zero(d) - 1) % T - - nc = allones - rem(convert(T, allones - d), d) - p = 8*sizeof(d) - 1 - q1, r1 = divrem(signedmin, nc) - q2, r2 = divrem(signedmax, d) - while true - p += 1 - if r1 >= convert(T, nc - r1) - q1 = q1 + q1 + one(T) - r1 = r1 + r1 - nc - else - q1 = q1 + q1 - r1 = r1 + r1 - end - if convert(T, r2 + one(T)) >= convert(T, d - r2) - add |= q2 >= signedmax - q2 = q2 + q2 + one(T) - r2 = r2 + r2 + one(T) - d - else - add |= q2 >= signedmin - q2 = q2 + q2 - r2 = r2 + r2 + one(T) - end - delta = d - one(T) - r2 - (p < sizeof(d)*16 && (q1 < delta || (q1 == delta && r1 == 0))) || break - end - m = q2 + one(T) # resulting magic number - s = p - sizeof(d)*8 - add # resulting shift - new(d, m, add, s % UInt8) - end -end -UnsignedMultiplicativeInverse(x::Unsigned) = UnsignedMultiplicativeInverse{typeof(x)}(x) - -function div(a::T, b::SignedMultiplicativeInverse{T}) where T - x = ((widen(a)*b.multiplier) >>> sizeof(a)*8) % T - x += (a*b.addmul) % T - ifelse(abs(b.divisor) == 1, a*b.divisor, (signbit(x) + (x >> b.shift)) % T) -end -function div(a::T, b::UnsignedMultiplicativeInverse{T}) where T - x = ((widen(a)*b.multiplier) >>> sizeof(a)*8) % T - x = ifelse(b.add, convert(T, convert(T, (convert(T, a - x) >>> 1)) + x), x) - ifelse(b.divisor == 1, a, x >>> b.shift) -end - -rem(a::T, b::MultiplicativeInverse{T}) where {T} = - a - div(a, b)*b.divisor - -function divrem(a::T, b::MultiplicativeInverse{T}) where T - d = div(a, b) - (d, a - d*b.divisor) -end - -multiplicativeinverse(x::Signed) = SignedMultiplicativeInverse(x) -multiplicativeinverse(x::Unsigned) = UnsignedMultiplicativeInverse(x) - -end diff --git a/julia-0.6.3/share/julia/base/nofloat_hashing.jl b/julia-0.6.3/share/julia/base/nofloat_hashing.jl deleted file mode 100644 index 3ef707d..0000000 --- a/julia-0.6.3/share/julia/base/nofloat_hashing.jl +++ /dev/null @@ -1,10 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -## hashing small, built-in numeric types -## for a system image built without floating point support - -hx(a::UInt64, b::UInt64, h::UInt) = hash_uint64(3a + b - h) - -hash(x::UInt64, h::UInt) = hx(x, x, h) -hash(x::Int64, h::UInt) = hx(reinterpret(UInt64,abs(x)), reinterpret(UInt64,x), h) -hash(x::Union{Bool,Char,Int8,UInt8,Int16,UInt16,Int32,UInt32}, h::UInt) = hash(Int64(x), h) diff --git a/julia-0.6.3/share/julia/base/nullable.jl b/julia-0.6.3/share/julia/base/nullable.jl deleted file mode 100644 index 9762cfd..0000000 --- a/julia-0.6.3/share/julia/base/nullable.jl +++ /dev/null @@ -1,330 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -struct NullException <: Exception -end - -""" - Nullable(x, hasvalue::Bool=true) - -Wrap value `x` in an object of type `Nullable`, which indicates whether a value is present. -`Nullable(x)` yields a non-empty wrapper and `Nullable{T}()` yields an empty instance of a -wrapper that might contain a value of type `T`. - -`Nullable(x, false)` yields `Nullable{typeof(x)}()` with `x` stored in the result's `value` -field. - -# Examples - -```jldoctest -julia> Nullable(1) -Nullable{Int64}(1) - -julia> Nullable{Int64}() -Nullable{Int64}() - -julia> Nullable(1, false) -Nullable{Int64}() - -julia> dump(Nullable(1, false)) -Nullable{Int64} - hasvalue: Bool false - value: Int64 1 -``` -""" -Nullable{T}(value::T, hasvalue::Bool=true) = Nullable{T}(value, hasvalue) -Nullable() = Nullable{Union{}}() - -eltype(::Type{Nullable{T}}) where {T} = T - -convert(::Type{Nullable{T}}, x::Nullable{T}) where {T} = x -convert(::Type{Nullable }, x::Nullable ) = x - -convert(t::Type{Nullable{T}}, x::Any) where {T} = convert(t, convert(T, x)) - -function convert(::Type{Nullable{T}}, x::Nullable) where T - return isnull(x) ? Nullable{T}() : Nullable{T}(convert(T, get(x))) -end - -convert(::Type{Nullable{T}}, x::T) where {T<:Nullable} = Nullable{T}(x) -convert(::Type{Nullable{T}}, x::T) where {T} = Nullable{T}(x) -convert(::Type{Nullable }, x::T) where {T} = Nullable{T}(x) - -convert(::Type{Nullable{T}}, ::Void) where {T} = Nullable{T}() -convert(::Type{Nullable }, ::Void) = Nullable{Union{}}() - -promote_rule(::Type{Nullable{S}}, ::Type{T}) where {S,T} = Nullable{promote_type(S, T)} -promote_rule(::Type{Nullable{S}}, ::Type{Nullable{T}}) where {S,T} = Nullable{promote_type(S, T)} -promote_op(op::Any, ::Type{Nullable{S}}, ::Type{Nullable{T}}) where {S,T} = Nullable{promote_op(op, S, T)} -promote_op(op::Type, ::Type{Nullable{S}}, ::Type{Nullable{T}}) where {S,T} = Nullable{promote_op(op, S, T)} - -function show(io::IO, x::Nullable) - if get(io, :compact, false) - if isnull(x) - print(io, "#NULL") - else - show(io, x.value) - end - else - print(io, "Nullable{") - showcompact(io, eltype(x)) - print(io, "}(") - if !isnull(x) - showcompact(io, x.value) - end - print(io, ')') - end -end - -""" - get(x::Nullable[, y]) - -Attempt to access the value of `x`. Returns the value if it is present; -otherwise, returns `y` if provided, or throws a `NullException` if not. -""" -@inline function get(x::Nullable{T}, y) where T - if isbits(T) - ifelse(isnull(x), y, x.value) - else - isnull(x) ? y : x.value - end -end - -get(x::Nullable) = isnull(x) ? throw(NullException()) : x.value - -""" - unsafe_get(x) - -Return the value of `x` for [`Nullable`](@ref) `x`; return `x` for -all other `x`. - -This method does not check whether or not `x` is null before attempting to -access the value of `x` for `x::Nullable` (hence "unsafe"). - -```jldoctest -julia> x = Nullable(1) -Nullable{Int64}(1) - -julia> unsafe_get(x) -1 - -julia> x = Nullable{String}() -Nullable{String}() - -julia> unsafe_get(x) -ERROR: UndefRefError: access to undefined reference -Stacktrace: - [1] unsafe_get(::Nullable{String}) at ./nullable.jl:125 - -julia> x = 1 -1 - -julia> unsafe_get(x) -1 -``` -""" -unsafe_get(x::Nullable) = x.value -unsafe_get(x) = x - -""" - isnull(x) - -Return whether or not `x` is null for [`Nullable`](@ref) `x`; return -`false` for all other `x`. - -# Examples - -```jldoctest -julia> x = Nullable(1, false) -Nullable{Int64}() - -julia> isnull(x) -true - -julia> x = Nullable(1, true) -Nullable{Int64}(1) - -julia> isnull(x) -false - -julia> x = 1 -1 - -julia> isnull(x) -false -``` -""" -isnull(x::Nullable) = !x.hasvalue -isnull(x) = false - -## Operators - -""" - null_safe_op(f::Any, ::Type, ::Type...)::Bool - -Returns whether an operation `f` can safely be applied to any value of the passed type(s). -Returns `false` by default. - -Custom types should implement methods for some or all operations `f` when applicable: -returning `true` means that the operation may be called on any bit pattern without -throwing an error (though returning invalid or nonsensical results is not a problem). -In particular, this means that the operation can be applied on the whole domain of the -type *and on uninitialized objects*. As a general rule, these properties are only true for -safe operations on `isbits` types. - -Types declared as safe can benefit from higher performance for operations on nullable: by -always computing the result even for null values, a branch is avoided, which helps -vectorization. -""" -null_safe_op(f::Any, ::Type, ::Type...) = false - -const NullSafeSignedInts = Union{Type{Int128}, Type{Int16}, Type{Int32}, - Type{Int64}, Type{Int8}} -const NullSafeUnsignedInts = Union{Type{Bool}, Type{UInt128}, Type{UInt16}, - Type{UInt32}, Type{UInt64}, Type{UInt8}} -const NullSafeInts = Union{NullSafeSignedInts, NullSafeUnsignedInts} -const NullSafeFloats = Union{Type{Float16}, Type{Float32}, Type{Float64}} -const NullSafeTypes = Union{NullSafeInts, NullSafeFloats} -const EqualOrLess = Union{typeof(isequal), typeof(isless)} - -null_safe_op(::typeof(identity), ::Type{T}) where {T} = isbits(T) - -null_safe_op(f::EqualOrLess, ::NullSafeTypes, ::NullSafeTypes) = true -null_safe_op(f::EqualOrLess, ::Type{Rational{S}}, ::Type{T}) where {S,T} = - null_safe_op(f, T, S) -# complex numbers can be compared for equality but not in general ordered -null_safe_op(::typeof(isequal), ::Type{Complex{S}}, ::Type{T}) where {S,T} = - null_safe_op(isequal, T, S) - -""" - isequal(x::Nullable, y::Nullable) - -If neither `x` nor `y` is null, compare them according to their values -(i.e. `isequal(get(x), get(y))`). Else, return `true` if both arguments are null, -and `false` if one is null but not the other: nulls are considered equal. -""" -@inline function isequal(x::Nullable{S}, y::Nullable{T}) where {S,T} - if null_safe_op(isequal, S, T) - (isnull(x) & isnull(y)) | (!isnull(x) & !isnull(y) & isequal(x.value, y.value)) - else - (isnull(x) & isnull(y)) || (!isnull(x) & !isnull(y) && isequal(x.value, y.value)) - end -end - -isequal(x::Nullable{Union{}}, y::Nullable{Union{}}) = true -isequal(x::Nullable{Union{}}, y::Nullable) = isnull(y) -isequal(x::Nullable, y::Nullable{Union{}}) = isnull(x) - -""" - isless(x::Nullable, y::Nullable) - -If neither `x` nor `y` is null, compare them according to their values -(i.e. `isless(get(x), get(y))`). Else, return `true` if only `y` is null, and `false` -otherwise: nulls are always considered greater than non-nulls, but not greater than -another null. -""" -@inline function isless(x::Nullable{S}, y::Nullable{T}) where {S,T} - # NULL values are sorted last - if null_safe_op(isless, S, T) - (!isnull(x) & isnull(y)) | (!isnull(x) & !isnull(y) & isless(x.value, y.value)) - else - (!isnull(x) & isnull(y)) || (!isnull(x) & !isnull(y) && isless(x.value, y.value)) - end -end - -isless(x::Nullable{Union{}}, y::Nullable{Union{}}) = false -isless(x::Nullable{Union{}}, y::Nullable) = false -isless(x::Nullable, y::Nullable{Union{}}) = !isnull(x) - -==(x::Nullable, y::Nullable) = throw(NullException()) - -const nullablehash_seed = UInt === UInt64 ? 0x932e0143e51d0171 : 0xe51d0171 - -function hash(x::Nullable, h::UInt) - if isnull(x) - return h + nullablehash_seed - else - return hash(x.value, h + nullablehash_seed) - end -end - -# higher-order functions -""" - filter(p, x::Nullable) - -Return null if either `x` is null or `p(get(x))` is false, and `x` otherwise. -""" -function filter(p, x::Nullable{T}) where T - if isbits(T) - val = unsafe_get(x) - Nullable{T}(val, !isnull(x) && p(val)) - else - isnull(x) || p(unsafe_get(x)) ? x : Nullable{T}() - end -end - -""" -Return the given type if it is concrete, and `Union{}` otherwise. -""" -nullable_returntype(::Type{T}) where {T} = isleaftype(T) ? T : Union{} - -""" - map(f, x::Nullable) - -Return `f` applied to the value of `x` if it has one, as a `Nullable`. If `x` -is null, then return a null value of type `Nullable{S}`. `S` is guaranteed to -be either `Union{}` or a concrete type. Whichever of these is chosen is an -implementation detail, but typically the choice that maximizes performance -would be used. If `x` has a value, then the return type is guaranteed to be of -type `Nullable{typeof(f(x))}`. -""" -function map(f, x::Nullable{T}) where T - S = promote_op(f, T) - if isleaftype(S) && null_safe_op(f, T) - Nullable(f(unsafe_get(x)), !isnull(x)) - else - if isnull(x) - Nullable{nullable_returntype(S)}() - else - Nullable(f(unsafe_get(x))) - end - end -end - -# We need the following function and specializations because LLVM cannot -# optimize !any(isnull, t) without further guidance. -hasvalue(x::Nullable) = x.hasvalue -hasvalue(x) = true -all(f::typeof(hasvalue), t::Tuple) = f(t[1]) & all(f, tail(t)) -all(f::typeof(hasvalue), t::Tuple{}) = true - -# Overloads of null_safe_op -# Unary operators - -# Note this list does not include sqrt since it can raise a DomainError -for op in (+, -, abs, abs2) - null_safe_op(::typeof(op), ::NullSafeTypes) = true - null_safe_op(::typeof(op), ::Type{Complex{S}}) where {S} = null_safe_op(op, S) - null_safe_op(::typeof(op), ::Type{Rational{S}}) where {S} = null_safe_op(op, S) -end - -null_safe_op(::typeof(~), ::NullSafeInts) = true -null_safe_op(::typeof(!), ::Type{Bool}) = true - -# Binary operators - -# Note this list does not include ^, ÷ and % -# Operations between signed and unsigned types are not safe: promotion to unsigned -# gives an InexactError for negative numbers -for op in (+, -, *, /, &, |, <<, >>, >>>, - scalarmin, scalarmax) - # to fix ambiguities - null_safe_op(::typeof(op), ::NullSafeFloats, ::NullSafeFloats) = true - null_safe_op(::typeof(op), ::NullSafeSignedInts, ::NullSafeSignedInts) = true - null_safe_op(::typeof(op), ::NullSafeUnsignedInts, ::NullSafeUnsignedInts) = true -end -for op in (+, -, *, /) - null_safe_op(::typeof(op), ::Type{Complex{S}}, ::Type{T}) where {S,T} = - null_safe_op(op, T, S) - null_safe_op(::typeof(op), ::Type{Rational{S}}, ::Type{T}) where {S,T} = - null_safe_op(op, T, S) -end diff --git a/julia-0.6.3/share/julia/base/number.jl b/julia-0.6.3/share/julia/base/number.jl deleted file mode 100644 index 75abda0..0000000 --- a/julia-0.6.3/share/julia/base/number.jl +++ /dev/null @@ -1,239 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -## generic operations on numbers ## -""" - isinteger(x) -> Bool - -Test whether `x` is numerically equal to some integer. - -```jldoctest -julia> isinteger(4.0) -true -``` -""" -isinteger(x::Integer) = true - -""" - iszero(x) - -Return `true` if `x == zero(x)`; if `x` is an array, this checks whether -all of the elements of `x` are zero. -""" -iszero(x) = x == zero(x) # fallback method - -size(x::Number) = () -size(x::Number,d) = convert(Int,d)<1 ? throw(BoundsError()) : 1 -indices(x::Number) = () -indices(x::Number,d) = convert(Int,d)<1 ? throw(BoundsError()) : OneTo(1) -eltype(::Type{T}) where {T<:Number} = T -ndims(x::Number) = 0 -ndims(::Type{<:Number}) = 0 -length(x::Number) = 1 -endof(x::Number) = 1 -iteratorsize(::Type{<:Number}) = HasShape() - -getindex(x::Number) = x -function getindex(x::Number, i::Integer) - @_inline_meta - @boundscheck i == 1 || throw(BoundsError()) - x -end -function getindex(x::Number, I::Integer...) - @_inline_meta - @boundscheck all([i == 1 for i in I]) || throw(BoundsError()) - x -end -first(x::Number) = x -last(x::Number) = x -copy(x::Number) = x # some code treats numbers as collection-like - -""" - divrem(x, y) - -The quotient and remainder from Euclidean division. Equivalent to `(div(x,y), rem(x,y))` or -`(x÷y, x%y)`. - -```jldoctest -julia> divrem(3,7) -(0, 3) - -julia> divrem(7,3) -(2, 1) -``` -""" -divrem(x,y) = (div(x,y),rem(x,y)) - -""" - fldmod(x, y) - -The floored quotient and modulus after division. Equivalent to `(fld(x,y), mod(x,y))`. -""" -fldmod(x,y) = (fld(x,y),mod(x,y)) -signbit(x::Real) = x < 0 - -""" - sign(x) - -Return zero if `x==0` and ``x/|x|`` otherwise (i.e., ±1 for real `x`). -""" -sign(x::Number) = x == 0 ? x/abs(oneunit(x)) : x/abs(x) -sign(x::Real) = ifelse(x < 0, oftype(one(x),-1), ifelse(x > 0, one(x), typeof(one(x))(x))) -sign(x::Unsigned) = ifelse(x > 0, one(x), oftype(one(x),0)) -abs(x::Real) = ifelse(signbit(x), -x, x) - -""" - abs2(x) - -Squared absolute value of `x`. - -```jldoctest -julia> abs2(-3) -9 -``` -""" -abs2(x::Real) = x*x - -""" - flipsign(x, y) - -Return `x` with its sign flipped if `y` is negative. For example `abs(x) = flipsign(x,x)`. - -```jldoctest -julia> flipsign(5, 3) -5 - -julia> flipsign(5, -3) --5 -``` -""" -flipsign(x::Real, y::Real) = ifelse(signbit(y), -x, x) -copysign(x::Real, y::Real) = ifelse(signbit(x)!=signbit(y), -x, x) - -conj(x::Real) = x -transpose(x::Number) = x -ctranspose(x::Number) = conj(x) -inv(x::Number) = one(x)/x -angle(z::Real) = atan2(zero(z), z) - -""" - widemul(x, y) - -Multiply `x` and `y`, giving the result as a larger type. - -```jldoctest -julia> widemul(Float32(3.), 4.) -1.200000000000000000000000000000000000000000000000000000000000000000000000000000e+01 -``` -""" -widemul(x::Number, y::Number) = widen(x)*widen(y) - -start(x::Number) = false -next(x::Number, state) = (x, true) -done(x::Number, state) = state -isempty(x::Number) = false -in(x::Number, y::Number) = x == y - -map(f, x::Number, ys::Number...) = f(x, ys...) - -""" - zero(x) - -Get the additive identity element for the type of `x` (`x` can also specify the type itself). - -```jldoctest -julia> zero(1) -0 - -julia> zero(big"2.0") -0.000000000000000000000000000000000000000000000000000000000000000000000000000000 - -julia> zero(rand(2,2)) -2×2 Array{Float64,2}: - 0.0 0.0 - 0.0 0.0 -``` -""" -zero(x::Number) = oftype(x,0) -zero(::Type{T}) where {T<:Number} = convert(T,0) - -""" - one(x) - one(T::type) - -Return a multiplicative identity for `x`: a value such that -`one(x)*x == x*one(x) == x`. Alternatively `one(T)` can -take a type `T`, in which case `one` returns a multiplicative -identity for any `x` of type `T`. - -If possible, `one(x)` returns a value of the same type as `x`, -and `one(T)` returns a value of type `T`. However, this may -not be the case for types representing dimensionful quantities -(e.g. time in days), since the multiplicative -identity must be dimensionless. In that case, `one(x)` -should return an identity value of the same precision -(and shape, for matrices) as `x`. - -If you want a quantity that is of the same type as `x`, or of type `T`, -even if `x` is dimensionful, use [`oneunit`](@ref) instead. -```jldoctest -julia> one(3.7) -1.0 - -julia> one(Int) -1 - -julia> one(Dates.Day(1)) -1 -``` -""" -one(::Type{T}) where {T<:Number} = convert(T,1) -one(x::T) where {T<:Number} = one(T) -# note that convert(T, 1) should throw an error if T is dimensionful, -# so this fallback definition should be okay. - -""" - oneunit(x::T) - oneunit(T::Type) - -Returns `T(one(x))`, where `T` is either the type of the argument or -(if a type is passed) the argument. This differs from [`one`](@ref) for -dimensionful quantities: `one` is dimensionless (a multiplicative identity) -while `oneunit` is dimensionful (of the same type as `x`, or of type `T`). - -```jldoctest -julia> oneunit(3.7) -1.0 - -julia> oneunit(Dates.Day) -1 day -``` -""" -oneunit(x::T) where {T} = T(one(x)) -oneunit(::Type{T}) where {T} = T(one(T)) - -_default_type(::Type{Number}) = Int - -""" - factorial(n) - -Factorial of `n`. If `n` is an [`Integer`](@ref), the factorial is computed as an -integer (promoted to at least 64 bits). Note that this may overflow if `n` is not small, -but you can use `factorial(big(n))` to compute the result exactly in arbitrary precision. -If `n` is not an `Integer`, `factorial(n)` is equivalent to [`gamma(n+1)`](@ref). - -```jldoctest -julia> factorial(6) -720 - -julia> factorial(21) -ERROR: OverflowError() -[...] - -julia> factorial(21.0) -5.109094217170944e19 - -julia> factorial(big(21)) -51090942171709440000 -``` -""" -factorial(x::Number) = gamma(x + 1) # fallback for x not Integer diff --git a/julia-0.6.3/share/julia/base/operators.jl b/julia-0.6.3/share/julia/base/operators.jl deleted file mode 100644 index c0ba000..0000000 --- a/julia-0.6.3/share/julia/base/operators.jl +++ /dev/null @@ -1,975 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -## types ## - -""" - <:(T1, T2) - -Subtype operator, equivalent to `issubtype(T1, T2)`. - -```jldoctest -julia> Float64 <: AbstractFloat -true - -julia> Vector{Int} <: AbstractArray -true - -julia> Matrix{Float64} <: Matrix{AbstractFloat} -false -``` -""" -const (<:) = issubtype - -""" - >:(T1, T2) - -Supertype operator, equivalent to `issubtype(T2, T1)`. -""" -const (>:)(a::ANY, b::ANY) = issubtype(b, a) - -""" - supertype(T::DataType) - -Return the supertype of DataType `T`. - -```jldoctest -julia> supertype(Int32) -Signed -``` -""" -function supertype(T::DataType) - @_pure_meta - T.super -end - -function supertype(T::UnionAll) - @_pure_meta - UnionAll(T.var, supertype(T.body)) -end - -## generic comparison ## - -==(x, y) = x === y - -""" - isequal(x, y) - -Similar to `==`, except treats all floating-point `NaN` values as equal to each other, and -treats `-0.0` as unequal to `0.0`. The default implementation of `isequal` calls `==`, so if -you have a type that doesn't have these floating-point subtleties then you probably only -need to define `==`. - -`isequal` is the comparison function used by hash tables (`Dict`). `isequal(x,y)` must imply -that `hash(x) == hash(y)`. - -This typically means that if you define your own `==` function then you must define a -corresponding `hash` (and vice versa). Collections typically implement `isequal` by calling -`isequal` recursively on all contents. - -Scalar types generally do not need to implement `isequal` separate from `==`, unless they -represent floating-point numbers amenable to a more efficient implementation than that -provided as a generic fallback (based on `isnan`, `signbit`, and `==`). - -```jldoctest -julia> isequal([1., NaN], [1., NaN]) -true - -julia> [1., NaN] == [1., NaN] -false - -julia> 0.0 == -0.0 -true - -julia> isequal(0.0, -0.0) -false -``` -""" -isequal(x, y) = x == y - -signequal(x, y) = signbit(x)::Bool == signbit(y)::Bool -signless(x, y) = signbit(x)::Bool & !signbit(y)::Bool - -isequal(x::AbstractFloat, y::AbstractFloat) = (isnan(x) & isnan(y)) | signequal(x, y) & (x == y) -isequal(x::Real, y::AbstractFloat) = (isnan(x) & isnan(y)) | signequal(x, y) & (x == y) -isequal(x::AbstractFloat, y::Real ) = (isnan(x) & isnan(y)) | signequal(x, y) & (x == y) - -isless(x::AbstractFloat, y::AbstractFloat) = (!isnan(x) & isnan(y)) | signless(x, y) | (x < y) -isless(x::Real, y::AbstractFloat) = (!isnan(x) & isnan(y)) | signless(x, y) | (x < y) -isless(x::AbstractFloat, y::Real ) = (!isnan(x) & isnan(y)) | signless(x, y) | (x < y) - - -function ==(T::Type, S::Type) - @_pure_meta - typeseq(T, S) -end -function !=(T::Type, S::Type) - @_pure_meta - !(T == S) -end -==(T::TypeVar, S::Type) = false -==(T::Type, S::TypeVar) = false - -## comparison fallbacks ## - -""" - !=(x, y) - ≠(x,y) - -Not-equals comparison operator. Always gives the opposite answer as `==`. New types should -generally not implement this, and rely on the fallback definition `!=(x,y) = !(x==y)` instead. - -```jldoctest -julia> 3 != 2 -true - -julia> "foo" ≠ "foo" -false -``` -""" -!=(x, y) = !(x == y)::Bool -const ≠ = != - -""" - ===(x,y) -> Bool - ≡(x,y) -> Bool - -Determine whether `x` and `y` are identical, in the sense that no program could distinguish -them. Compares mutable objects by address in memory, and compares immutable objects (such as -numbers) by contents at the bit level. This function is sometimes called `egal`. - -```jldoctest -julia> a = [1, 2]; b = [1, 2]; - -julia> a == b -true - -julia> a === b -false - -julia> a === a -true -``` -""" -=== -const ≡ = === - -""" - !==(x, y) - ≢(x,y) - -Equivalent to `!(x === y)`. - -```jldoctest -julia> a = [1, 2]; b = [1, 2]; - -julia> a ≢ b -true - -julia> a ≢ a -false -``` -""" -!==(x, y) = !(x === y) -const ≢ = !== - -""" - <(x, y) - -Less-than comparison operator. New numeric types should implement this function for two -arguments of the new type. Because of the behavior of floating-point NaN values, `<` -implements a partial order. Types with a canonical partial order should implement `<`, and -types with a canonical total order should implement `isless`. - -```jldoctest -julia> 'a' < 'b' -true - -julia> "abc" < "abd" -true - -julia> 5 < 3 -false -``` -""" -<(x, y) = isless(x, y) - -""" - >(x, y) - -Greater-than comparison operator. Generally, new types should implement `<` instead of this -function, and rely on the fallback definition `>(x, y) = y < x`. - -```jldoctest -julia> 'a' > 'b' -false - -julia> 7 > 3 > 1 -true - -julia> "abc" > "abd" -false - -julia> 5 > 3 -true -``` -""" ->(x, y) = y < x - -""" - <=(x, y) - ≤(x,y) - -Less-than-or-equals comparison operator. - -```jldoctest -julia> 'a' <= 'b' -true - -julia> 7 ≤ 7 ≤ 9 -true - -julia> "abc" ≤ "abc" -true - -julia> 5 <= 3 -false -``` -""" -<=(x, y) = !(y < x) -const ≤ = <= - -""" - >=(x, y) - ≥(x,y) - -Greater-than-or-equals comparison operator. - -```jldoctest -julia> 'a' >= 'b' -false - -julia> 7 ≥ 7 ≥ 3 -true - -julia> "abc" ≥ "abc" -true - -julia> 5 >= 3 -true -``` -""" ->=(x, y) = (y <= x) -const ≥ = >= - -# this definition allows Number types to implement < instead of isless, -# which is more idiomatic: -isless(x::Real, y::Real) = x<y -lexcmp(x::Real, y::Real) = isless(x,y) ? -1 : ifelse(isless(y,x), 1, 0) - -""" - ifelse(condition::Bool, x, y) - -Return `x` if `condition` is `true`, otherwise return `y`. This differs from `?` or `if` in -that it is an ordinary function, so all the arguments are evaluated first. In some cases, -using `ifelse` instead of an `if` statement can eliminate the branch in generated code and -provide higher performance in tight loops. - -```jldoctest -julia> ifelse(1 > 2, 1, 2) -2 -``` -""" -ifelse(c::Bool, x, y) = select_value(c, x, y) - -""" - cmp(x,y) - -Return -1, 0, or 1 depending on whether `x` is less than, equal to, or greater than `y`, -respectively. Uses the total order implemented by `isless`. For floating-point numbers, uses `<` -but throws an error for unordered arguments. - -```jldoctest -julia> cmp(1, 2) --1 - -julia> cmp(2, 1) -1 - -julia> cmp(2+im, 3-im) -ERROR: MethodError: no method matching isless(::Complex{Int64}, ::Complex{Int64}) -[...] -``` -""" -cmp(x, y) = isless(x, y) ? -1 : ifelse(isless(y, x), 1, 0) - -""" - lexcmp(x, y) - -Compare `x` and `y` lexicographically and return -1, 0, or 1 depending on whether `x` is -less than, equal to, or greater than `y`, respectively. This function should be defined for -lexicographically comparable types, and `lexless` will call `lexcmp` by default. - -```jldoctest -julia> lexcmp("abc", "abd") --1 - -julia> lexcmp("abc", "abc") -0 -``` -""" -lexcmp(x, y) = cmp(x, y) - -""" - lexless(x, y) - -Determine whether `x` is lexicographically less than `y`. - -```jldoctest -julia> lexless("abc", "abd") -true -``` -""" -lexless(x, y) = lexcmp(x,y) < 0 - -# cmp returns -1, 0, +1 indicating ordering -cmp(x::Integer, y::Integer) = ifelse(isless(x, y), -1, ifelse(isless(y, x), 1, 0)) - -""" - max(x, y, ...) - -Return the maximum of the arguments. See also the [`maximum`](@ref) function -to take the maximum element from a collection. - -```jldoctest -julia> max(2, 5, 1) -5 -``` -""" -max(x, y) = ifelse(y < x, x, y) - -""" - min(x, y, ...) - -Return the minimum of the arguments. See also the [`minimum`](@ref) function -to take the minimum element from a collection. - -```jldoctest -julia> min(2, 5, 1) -1 -``` -""" -min(x,y) = ifelse(y < x, y, x) - -""" - minmax(x, y) - -Return `(min(x,y), max(x,y))`. See also: [`extrema`](@ref) that returns `(minimum(x), maximum(x))`. - -```jldoctest -julia> minmax('c','b') -('b', 'c') -``` -""" -minmax(x,y) = y < x ? (y, x) : (x, y) - -scalarmax(x,y) = max(x,y) -scalarmax(x::AbstractArray, y::AbstractArray) = throw(ArgumentError("ordering is not well-defined for arrays")) -scalarmax(x , y::AbstractArray) = throw(ArgumentError("ordering is not well-defined for arrays")) -scalarmax(x::AbstractArray, y ) = throw(ArgumentError("ordering is not well-defined for arrays")) - -scalarmin(x,y) = min(x,y) -scalarmin(x::AbstractArray, y::AbstractArray) = throw(ArgumentError("ordering is not well-defined for arrays")) -scalarmin(x , y::AbstractArray) = throw(ArgumentError("ordering is not well-defined for arrays")) -scalarmin(x::AbstractArray, y ) = throw(ArgumentError("ordering is not well-defined for arrays")) - -## definitions providing basic traits of arithmetic operators ## - -""" - identity(x) - -The identity function. Returns its argument. - -```jldoctest -julia> identity("Well, what did you expect?") -"Well, what did you expect?" -``` -""" -identity(x) = x - -+(x::Number) = x -*(x::Number) = x -(&)(x::Integer) = x -(|)(x::Integer) = x -xor(x::Integer) = x - -const ⊻ = xor - -# foldl for argument lists. expand recursively up to a point, then -# switch to a loop. this allows small cases like `a+b+c+d` to be inlined -# efficiently, without a major slowdown for `+(x...)` when `x` is big. -afoldl(op,a) = a -afoldl(op,a,b) = op(a,b) -afoldl(op,a,b,c...) = afoldl(op, op(a,b), c...) -function afoldl(op,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,qs...) - y = op(op(op(op(op(op(op(op(op(op(op(op(op(op(op(a,b),c),d),e),f),g),h),i),j),k),l),m),n),o),p) - for x in qs; y = op(y,x); end - y -end - -for op in (:+, :*, :&, :|, :xor, :min, :max, :kron) - @eval begin - # note: these definitions must not cause a dispatch loop when +(a,b) is - # not defined, and must only try to call 2-argument definitions, so - # that defining +(a,b) is sufficient for full functionality. - ($op)(a, b, c, xs...) = afoldl($op, ($op)(($op)(a,b),c), xs...) - # a further concern is that it's easy for a type like (Int,Int...) - # to match many definitions, so we need to keep the number of - # definitions down to avoid losing type information. - end -end - -""" - \\(x, y) - -Left division operator: multiplication of `y` by the inverse of `x` on the left. Gives -floating-point results for integer arguments. - -```jldoctest -julia> 3 \\ 6 -2.0 - -julia> inv(3) * 6 -2.0 - -julia> A = [1 2; 3 4]; x = [5, 6]; - -julia> A \\ x -2-element Array{Float64,1}: - -4.0 - 4.5 - -julia> inv(A) * x -2-element Array{Float64,1}: - -4.0 - 4.5 -``` -""" -\(x,y) = (y'/x')' - -# Core <<, >>, and >>> take either Int or UInt as second arg. Signed shift -# counts can shift in either direction, and are translated here to unsigned -# counts. Integer datatypes only need to implement the unsigned version. - -""" - <<(x, n) - -Left bit shift operator, `x << n`. For `n >= 0`, the result is `x` shifted left -by `n` bits, filling with `0`s. This is equivalent to `x * 2^n`. For `n < 0`, -this is equivalent to `x >> -n`. - -```jldoctest -julia> Int8(3) << 2 -12 - -julia> bits(Int8(3)) -"00000011" - -julia> bits(Int8(12)) -"00001100" -``` -See also [`>>`](@ref), [`>>>`](@ref). -""" -function <<(x::Integer, c::Integer) - @_inline_meta - typemin(Int) <= c <= typemax(Int) && return x << (c % Int) - (x >= 0 || c >= 0) && return zero(x) - oftype(x, -1) -end -<<(x::Integer, c::Unsigned) = c <= typemax(UInt) ? x << (c % UInt) : zero(x) -<<(x::Integer, c::Int) = c >= 0 ? x << unsigned(c) : x >> unsigned(-c) - -""" - >>(x, n) - -Right bit shift operator, `x >> n`. For `n >= 0`, the result is `x` shifted -right by `n` bits, where `n >= 0`, filling with `0`s if `x >= 0`, `1`s if `x < -0`, preserving the sign of `x`. This is equivalent to `fld(x, 2^n)`. For `n < -0`, this is equivalent to `x << -n`. - - -```jldoctest -julia> Int8(13) >> 2 -3 - -julia> bits(Int8(13)) -"00001101" - -julia> bits(Int8(3)) -"00000011" - -julia> Int8(-14) >> 2 --4 - -julia> bits(Int8(-14)) -"11110010" - -julia> bits(Int8(-4)) -"11111100" -``` -See also [`>>>`](@ref), [`<<`](@ref). -""" -function >>(x::Integer, c::Integer) - @_inline_meta - typemin(Int) <= c <= typemax(Int) && return x >> (c % Int) - (x >= 0 || c < 0) && return zero(x) - oftype(x, -1) -end ->>(x::Integer, c::Unsigned) = c <= typemax(UInt) ? x >> (c % UInt) : zero(x) ->>(x::Integer, c::Int) = c >= 0 ? x >> unsigned(c) : x << unsigned(-c) - -""" - >>>(x, n) - -Unsigned right bit shift operator, `x >>> n`. For `n >= 0`, the result is `x` -shifted right by `n` bits, where `n >= 0`, filling with `0`s. For `n < 0`, this -is equivalent to `x << -n`. - -For [`Unsigned`](@ref) integer types, this is equivalent to [`>>`](@ref). For -[`Signed`](@ref) integer types, this is equivalent to `signed(unsigned(x) >> n)`. - -```jldoctest -julia> Int8(-14) >>> 2 -60 - -julia> bits(Int8(-14)) -"11110010" - -julia> bits(Int8(60)) -"00111100" -``` - -[`BigInt`](@ref)s are treated as if having infinite size, so no filling is required and this -is equivalent to [`>>`](@ref). - -See also [`>>`](@ref), [`<<`](@ref). -""" -function >>>(x::Integer, c::Integer) - @_inline_meta - typemin(Int) <= c <= typemax(Int) ? x >>> (c % Int) : zero(x) -end ->>>(x::Integer, c::Unsigned) = c <= typemax(UInt) ? x >>> (c % UInt) : zero(x) ->>>(x::Integer, c::Int) = c >= 0 ? x >>> unsigned(c) : x << unsigned(-c) - -# fallback div, fld, and cld implementations -# NOTE: C89 fmod() and x87 FPREM implicitly provide truncating float division, -# so it is used here as the basis of float div(). -div{T<:Real}(x::T, y::T) = convert(T,round((x-rem(x,y))/y)) - -""" - fld(x, y) - -Largest integer less than or equal to `x/y`. - -```jldoctest -julia> fld(7.3,5.5) -1.0 -``` -""" -fld{T<:Real}(x::T, y::T) = convert(T,round((x-mod(x,y))/y)) - -""" - cld(x, y) - -Smallest integer larger than or equal to `x/y`. -```jldoctest -julia> cld(5.5,2.2) -3.0 -``` -""" -cld{T<:Real}(x::T, y::T) = convert(T,round((x-modCeil(x,y))/y)) -#rem{T<:Real}(x::T, y::T) = convert(T,x-y*trunc(x/y)) -#mod{T<:Real}(x::T, y::T) = convert(T,x-y*floor(x/y)) -modCeil{T<:Real}(x::T, y::T) = convert(T,x-y*ceil(x/y)) - -# operator alias - -""" - rem(x, y) - %(x, y) - -Remainder from Euclidean division, returning a value of the same sign as `x`, and smaller in -magnitude than `y`. This value is always exact. - -```jldoctest -julia> x = 15; y = 4; - -julia> x % y -3 - -julia> x == div(x, y) * y + rem(x, y) -true -``` -""" -rem -const % = rem - -""" - div(x, y) - ÷(x, y) - -The quotient from Euclidean division. Computes `x/y`, truncated to an integer. - -```jldoctest -julia> 9 ÷ 4 -2 - -julia> -5 ÷ 3 --1 -``` -""" -div -const ÷ = div - -""" - mod1(x, y) - -Modulus after flooring division, returning a value `r` such that `mod(r, y) == mod(x, y)` -in the range ``(0, y]`` for positive `y` and in the range ``[y,0)`` for negative `y`. - -```jldoctest -julia> mod1(4, 2) -2 - -julia> mod1(4, 3) -1 -``` -""" -mod1{T<:Real}(x::T, y::T) = (m = mod(x, y); ifelse(m == 0, y, m)) -# efficient version for integers -mod1{T<:Integer}(x::T, y::T) = (@_inline_meta; mod(x + y - T(1), y) + T(1)) - - -""" - fld1(x, y) - -Flooring division, returning a value consistent with `mod1(x,y)` - -See also: [`mod1`](@ref). - -```jldoctest -julia> x = 15; y = 4; - -julia> fld1(x, y) -4 - -julia> x == fld(x, y) * y + mod(x, y) -true - -julia> x == (fld1(x, y) - 1) * y + mod1(x, y) -true -``` -""" -fld1(x::T, y::T) where {T<:Real} = (m=mod(x,y); fld(x-m,y)) -# efficient version for integers -fld1(x::T, y::T) where {T<:Integer} = fld(x+y-T(1),y) - -""" - fldmod1(x, y) - -Return `(fld1(x,y), mod1(x,y))`. - -See also: [`fld1`](@ref), [`mod1`](@ref). -""" -fldmod1(x::T, y::T) where {T<:Real} = (fld1(x,y), mod1(x,y)) -# efficient version for integers -fldmod1(x::T, y::T) where {T<:Integer} = (fld1(x,y), mod1(x,y)) - -# transpose - -""" - ctranspose(A) - -The conjugate transposition operator (`'`). - -# Example - -```jldoctest -julia> A = [3+2im 9+2im; 8+7im 4+6im] -2×2 Array{Complex{Int64},2}: - 3+2im 9+2im - 8+7im 4+6im - -julia> ctranspose(A) -2×2 Array{Complex{Int64},2}: - 3-2im 8-7im - 9-2im 4-6im -``` -""" -ctranspose(x) = conj(transpose(x)) -conj(x) = x - -# transposed multiply - -""" - Ac_mul_B(A, B) - -For matrices or vectors ``A`` and ``B``, calculates ``Aᴴ⋅B``. -""" -Ac_mul_B(a,b) = ctranspose(a)*b - -""" - A_mul_Bc(A, B) - -For matrices or vectors ``A`` and ``B``, calculates ``A⋅Bᴴ``. -""" -A_mul_Bc(a,b) = a*ctranspose(b) - -""" - Ac_mul_Bc(A, B) - -For matrices or vectors ``A`` and ``B``, calculates ``Aᴴ Bᴴ``. -""" -Ac_mul_Bc(a,b) = ctranspose(a)*ctranspose(b) - -""" - At_mul_B(A, B) - -For matrices or vectors ``A`` and ``B``, calculates ``Aᵀ⋅B``. -""" -At_mul_B(a,b) = transpose(a)*b - -""" - A_mul_Bt(A, B) - -For matrices or vectors ``A`` and ``B``, calculates ``A⋅Bᵀ``. -""" -A_mul_Bt(a,b) = a*transpose(b) - -""" - At_mul_Bt(A, B) - -For matrices or vectors ``A`` and ``B``, calculates ``Aᵀ⋅Bᵀ``. -""" -At_mul_Bt(a,b) = transpose(a)*transpose(b) - -# transposed divide - -""" - Ac_rdiv_B(A, B) - -For matrices or vectors ``A`` and ``B``, calculates ``Aᴴ / B``. -""" -Ac_rdiv_B(a,b) = ctranspose(a)/b - -""" - A_rdiv_Bc(A, B) - -For matrices or vectors ``A`` and ``B``, calculates ``A / Bᴴ``. -""" -A_rdiv_Bc(a,b) = a/ctranspose(b) - -""" - Ac_rdiv_Bc(A, B) - -For matrices or vectors ``A`` and ``B``, calculates ``Aᴴ / Bᴴ``. -""" -Ac_rdiv_Bc(a,b) = ctranspose(a)/ctranspose(b) - -""" - At_rdiv_B(A, B) - -For matrices or vectors ``A`` and ``B``, calculates ``Aᵀ / B``. -""" -At_rdiv_B(a,b) = transpose(a)/b - -""" - A_rdiv_Bt(A, B) - -For matrices or vectors ``A`` and ``B``, calculates ``A / Bᵀ``. -""" -A_rdiv_Bt(a,b) = a/transpose(b) - -""" - At_rdiv_Bt(A, B) - -For matrices or vectors ``A`` and ``B``, calculates ``Aᵀ / Bᵀ``. -""" -At_rdiv_Bt(a,b) = transpose(a)/transpose(b) - -""" - Ac_ldiv_B(A, B) - -For matrices or vectors ``A`` and ``B``, calculates ``Aᴴ`` \\ ``B``. -""" -Ac_ldiv_B(a,b) = ctranspose(a)\b - -""" - A_ldiv_Bc(A, B) - -For matrices or vectors ``A`` and ``B``, calculates ``A`` \\ ``Bᴴ``. -""" -A_ldiv_Bc(a,b) = a\ctranspose(b) - -""" - Ac_ldiv_Bc(A, B) - -For matrices or vectors ``A`` and ``B``, calculates ``Aᴴ`` \\ ``Bᴴ``. -""" -Ac_ldiv_Bc(a,b) = ctranspose(a)\ctranspose(b) - -""" - At_ldiv_B(A, B) - -For matrices or vectors ``A`` and ``B``, calculates ``Aᵀ`` \\ ``B``. -""" -At_ldiv_B(a,b) = transpose(a)\b - -""" - A_ldiv_Bt(A, B) - -For matrices or vectors ``A`` and ``B``, calculates ``A`` \\ ``Bᵀ``. -""" -A_ldiv_Bt(a,b) = a\transpose(b) - -""" - At_ldiv_Bt(A, B) - -For matrices or vectors ``A`` and ``B``, calculates ``Aᵀ`` \\ ``Bᵀ``. -""" -At_ldiv_Bt(a,b) = At_ldiv_B(a,transpose(b)) - -""" - Ac_ldiv_Bt(A, B) - -For matrices or vectors ``A`` and ``B``, calculates ``Aᴴ`` \\ ``Bᵀ``. -""" -Ac_ldiv_Bt(a,b) = Ac_ldiv_B(a,transpose(b)) - -widen(x::T) where {T<:Number} = convert(widen(T), x) - -# function pipelining - -""" - |>(x, f) - -Applies a function to the preceding argument. This allows for easy function chaining. - -```jldoctest -julia> [1:5;] |> x->x.^2 |> sum |> inv -0.01818181818181818 -``` -""" -|>(x, f) = f(x) - -# function composition - -""" - f ∘ g - -Compose functions: i.e. `(f ∘ g)(args...)` means `f(g(args...))`. The `∘` symbol can be -entered in the Julia REPL (and most editors, appropriately configured) by typing `\\circ<tab>`. -Example: - -```jldoctest -julia> map(uppercase∘hex, 250:255) -6-element Array{String,1}: - "FA" - "FB" - "FC" - "FD" - "FE" - "FF" -``` -""" -∘(f, g) = (x...)->f(g(x...)) - - -""" - !f::Function - -Predicate function negation: when the argument of `!` is a function, it returns a -function which computes the boolean negation of `f`. Example: - -```jldoctest -julia> str = "∀ ε > 0, ∃ δ > 0: |x-y| < δ ⇒ |f(x)-f(y)| < ε" -"∀ ε > 0, ∃ δ > 0: |x-y| < δ ⇒ |f(x)-f(y)| < ε" - -julia> filter(isalpha, str) -"εδxyδfxfyε" - -julia> filter(!isalpha, str) -"∀ > 0, ∃ > 0: |-| < ⇒ |()-()| < " -``` -""" -!(f::Function) = (x...)->!f(x...) - -# some operators not defined yet -global //, >:, <|, hcat, hvcat, ⋅, ×, ∈, ∉, ∋, ∌, ⊆, ⊈, ⊊, ∩, ∪, √, ∛ - -this_module = current_module() -baremodule Operators - -export - !, - !=, - !==, - ===, - xor, - %, - ÷, - &, - *, - +, - -, - /, - //, - <, - <:, - >:, - <<, - <=, - ==, - >, - >=, - ≥, - ≤, - ≠, - >>, - >>>, - \, - ^, - |, - |>, - <|, - ~, - ⋅, - ×, - ∈, - ∉, - ∋, - ∌, - ⊆, - ⊈, - ⊊, - ∩, - ∪, - √, - ∛, - ⊻, - ∘, - colon, - hcat, - vcat, - hvcat, - getindex, - setindex!, - transpose, - ctranspose - -import ..this_module: !, !=, xor, %, ÷, &, *, +, -, - /, //, <, <:, <<, <=, ==, >, >=, >>, >>>, - <|, |>, \, ^, |, ~, !==, ===, >:, colon, hcat, vcat, hvcat, getindex, setindex!, - transpose, ctranspose, - ≥, ≤, ≠, ⋅, ×, ∈, ∉, ∋, ∌, ⊆, ⊈, ⊊, ∩, ∪, √, ∛, ⊻, ∘ - -end diff --git a/julia-0.6.3/share/julia/base/options.jl b/julia-0.6.3/share/julia/base/options.jl deleted file mode 100644 index ef3c88b..0000000 --- a/julia-0.6.3/share/julia/base/options.jl +++ /dev/null @@ -1,54 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -# NOTE: This type needs to be kept in sync with jl_options in src/julia.h -struct JLOptions - quiet::Int8 - julia_home::Ptr{UInt8} - julia_bin::Ptr{UInt8} - eval::Ptr{UInt8} - print::Ptr{UInt8} - load::Ptr{UInt8} - image_file::Ptr{UInt8} - cpu_target::Ptr{UInt8} - nprocs::Int32 - machinefile::Ptr{UInt8} - isinteractive::Int8 - color::Int8 - historyfile::Int8 - startupfile::Int8 - compile_enabled::Int8 - code_coverage::Int8 - malloc_log::Int8 - opt_level::Int8 - debug_level::Int8 - check_bounds::Int8 - depwarn::Int8 - can_inline::Int8 - polly::Int8 - fast_math::Int8 - worker::Ptr{UInt8} - handle_signals::Int8 - use_precompiled::Int8 - use_compilecache::Int8 - bindto::Ptr{UInt8} - outputbc::Ptr{UInt8} - outputo::Ptr{UInt8} - outputji::Ptr{UInt8} - incremental::Int8 -end - -JLOptions() = unsafe_load(cglobal(:jl_options, JLOptions)) - -function show(io::IO, opt::JLOptions) - print(io, "JLOptions(") - fields = fieldnames(opt) - nfields = length(fields) - for (i, f) in enumerate(fields) - v = getfield(opt, i) - if isa(v, Ptr{UInt8}) - v = (v != C_NULL) ? unsafe_string(v) : "" - end - print(io, f, " = ", repr(v), i < nfields ? ", " : "") - end - print(io, ")") -end diff --git a/julia-0.6.3/share/julia/base/ordering.jl b/julia-0.6.3/share/julia/base/ordering.jl deleted file mode 100644 index 95b86f4..0000000 --- a/julia-0.6.3/share/julia/base/ordering.jl +++ /dev/null @@ -1,75 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -module Order - -## notions of element ordering ## - -export # not exported by Base - Ordering, Forward, Reverse, Lexicographic, - By, Lt, Perm, - ReverseOrdering, ForwardOrdering, LexicographicOrdering, - DirectOrdering, - lt, ord, ordtype - -abstract type Ordering end - -struct ForwardOrdering <: Ordering end -struct ReverseOrdering{Fwd<:Ordering} <: Ordering - fwd::Fwd -end - -ReverseOrdering(rev::ReverseOrdering) = rev.fwd -ReverseOrdering(fwd::Fwd) where {Fwd} = ReverseOrdering{Fwd}(fwd) - -const DirectOrdering = Union{ForwardOrdering,ReverseOrdering{ForwardOrdering}} - -const Forward = ForwardOrdering() -const Reverse = ReverseOrdering(Forward) - -struct LexicographicOrdering <: Ordering end -const Lexicographic = LexicographicOrdering() - -struct By{T} <: Ordering - by::T -end - -struct Lt{T} <: Ordering - lt::T -end - -struct Perm{O<:Ordering,V<:AbstractVector} <: Ordering - order::O - data::V -end - -lt(o::ForwardOrdering, a, b) = isless(a,b) -lt(o::ReverseOrdering, a, b) = lt(o.fwd,b,a) -lt(o::By, a, b) = isless(o.by(a),o.by(b)) -lt(o::Lt, a, b) = o.lt(a,b) -lt(o::LexicographicOrdering, a, b) = lexcmp(a,b) < 0 - -function lt(p::Perm, a::Integer, b::Integer) - da = p.data[a] - db = p.data[b] - lt(p.order, da, db) | (!lt(p.order, db, da) & (a < b)) -end -function lt(p::Perm{LexicographicOrdering}, a::Integer, b::Integer) - c = lexcmp(p.data[a], p.data[b]) - c != 0 ? c < 0 : a < b -end - -ordtype(o::ReverseOrdering, vs::AbstractArray) = ordtype(o.fwd, vs) -ordtype(o::Perm, vs::AbstractArray) = ordtype(o.order, o.data) -# TODO: here, we really want the return type of o.by, without calling it -ordtype(o::By, vs::AbstractArray) = try typeof(o.by(vs[1])) catch; Any end -ordtype(o::Ordering, vs::AbstractArray) = eltype(vs) - -function ord(lt, by, rev::Bool, order::Ordering=Forward) - o = (lt===isless) & (by===identity) ? order : - (lt===isless) & (by!==identity) ? By(by) : - (lt!==isless) & (by===identity) ? Lt(lt) : - Lt((x,y)->lt(by(x),by(y))) - rev ? ReverseOrdering(o) : o -end - -end diff --git a/julia-0.6.3/share/julia/base/osutils.jl b/julia-0.6.3/share/julia/base/osutils.jl deleted file mode 100644 index 4a133a4..0000000 --- a/julia-0.6.3/share/julia/base/osutils.jl +++ /dev/null @@ -1,86 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -""" - is_unix([os]) - -Predicate for testing if the OS provides a Unix-like interface. -See documentation in [Handling Operating System Variation](@ref). -""" -function is_unix(os::Symbol) - if is_windows(os) - return false - elseif is_linux(os) || is_bsd(os) - return true - else - throw(ArgumentError("unknown operating system \"$os\"")) - end -end - -""" - is_linux([os]) - -Predicate for testing if the OS is a derivative of Linux. -See documentation in [Handling Operating System Variation](@ref). -""" -is_linux(os::Symbol) = (os == :Linux) - -""" - is_bsd([os]) - -Predicate for testing if the OS is a derivative of BSD. -See documentation in [Handling Operating System Variation](@ref). -""" -is_bsd(os::Symbol) = (os == :FreeBSD || os == :OpenBSD || os == :NetBSD || os == :DragonFly || os == :Darwin || os == :Apple) - -""" - is_windows([os]) - -Predicate for testing if the OS is a derivative of Microsoft Windows NT. -See documentation in [Handling Operating System Variation](@ref). -""" -is_windows(os::Symbol) = (os == :Windows || os == :NT) - -""" - is_apple([os]) - -Predicate for testing if the OS is a derivative of Apple Macintosh OS X or Darwin. -See documentation in [Handling Operating System Variation](@ref). -""" -is_apple(os::Symbol) = (os == :Apple || os == :Darwin) - -""" - @static - -Partially evaluates an expression at parse time. - -For example, `@static is_windows() ? foo : bar` will evaluate `is_windows()` and insert either `foo` or `bar` into the expression. -This is useful in cases where a construct would be invalid on other platforms, -such as a `ccall` to a non-existent function. -`@static if is_apple() foo end` and `@static foo <&&,||> bar` are also valid syntax. -""" -macro static(ex) - if isa(ex, Expr) - if ex.head === :if || ex.head === :&& || ex.head === :|| - cond = eval(current_module(), ex.args[1]) - if xor(cond, ex.head === :||) - return esc(ex.args[2]) - elseif length(ex.args) == 3 - return esc(ex.args[3]) - elseif ex.head === :if - return nothing - else - return cond - end - end - end - throw(ArgumentError("invalid @static macro")) -end - -let KERNEL = ccall(:jl_get_UNAME, Any, ()) - # evaluate the zero-argument form of each of these functions - # as a function returning a static constant based on the build-time - # operating-system kernel - for f in (:is_unix, :is_linux, :is_bsd, :is_apple, :is_windows) - @eval $f() = $(getfield(current_module(),f)(KERNEL)) - end -end diff --git a/julia-0.6.3/share/julia/base/pair.jl b/julia-0.6.3/share/julia/base/pair.jl deleted file mode 100644 index 338f554..0000000 --- a/julia-0.6.3/share/julia/base/pair.jl +++ /dev/null @@ -1,39 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -struct Pair{A,B} - first::A - second::B -end - -const => = Pair - -start(p::Pair) = 1 -done(p::Pair, i) = i>2 -next(p::Pair, i) = (getfield(p,i), i+1) -eltype(p::Pair{A,B}) where {A,B} = Union{A,B} - -indexed_next(p::Pair, i::Int, state) = (getfield(p,i), i+1) - -hash(p::Pair, h::UInt) = hash(p.second, hash(p.first, h)) - -==(p::Pair, q::Pair) = (p.first==q.first) & (p.second==q.second) -isequal(p::Pair, q::Pair) = isequal(p.first,q.first) & isequal(p.second,q.second) - -isless(p::Pair, q::Pair) = ifelse(!isequal(p.first,q.first), isless(p.first,q.first), - isless(p.second,q.second)) -getindex(p::Pair,i::Int) = getfield(p,i) -getindex(p::Pair,i::Real) = getfield(p, convert(Int, i)) -reverse{A,B}(p::Pair{A,B}) = Pair{B,A}(p.second, p.first) - -endof(p::Pair) = 2 -length(p::Pair) = 2 -first(p::Pair) = p.first -last(p::Pair) = p.second - -convert(::Type{Pair{A,B}}, x::Pair{A,B}) where {A,B} = x -function convert(::Type{Pair{A,B}}, x::Pair) where {A,B} - Pair{A,B}(convert(A, x[1]), convert(B, x[2])) -end - -promote_rule(::Type{Pair{A1,B1}}, ::Type{Pair{A2,B2}}) where {A1,B1,A2,B2} = - Pair{promote_type(A1, A2), promote_type(B1, B2)} diff --git a/julia-0.6.3/share/julia/base/parse.jl b/julia-0.6.3/share/julia/base/parse.jl deleted file mode 100644 index 754d670..0000000 --- a/julia-0.6.3/share/julia/base/parse.jl +++ /dev/null @@ -1,241 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -import Base.Checked: add_with_overflow, mul_with_overflow - -## string to integer functions ## - -function parse(::Type{T}, c::Char, base::Integer=36) where T<:Integer - a::Int = (base <= 36 ? 10 : 36) - 2 <= base <= 62 || throw(ArgumentError("invalid base: base must be 2 ≤ base ≤ 62, got $base")) - d = '0' <= c <= '9' ? c-'0' : - 'A' <= c <= 'Z' ? c-'A'+10 : - 'a' <= c <= 'z' ? c-'a'+a : throw(ArgumentError("invalid digit: $(repr(c))")) - d < base || throw(ArgumentError("invalid base $base digit $(repr(c))")) - convert(T, d) -end - -function parseint_next(s::AbstractString, startpos::Int, endpos::Int) - (0 < startpos <= endpos) || (return Char(0), 0, 0) - j = startpos - c, startpos = next(s,startpos) - c, startpos, j -end - -function parseint_preamble(signed::Bool, base::Int, s::AbstractString, startpos::Int, endpos::Int) - c, i, j = parseint_next(s, startpos, endpos) - - while isspace(c) - c, i, j = parseint_next(s,i,endpos) - end - (j == 0) && (return 0, 0, 0) - - sgn = 1 - if signed - if c == '-' || c == '+' - (c == '-') && (sgn = -1) - c, i, j = parseint_next(s,i,endpos) - end - end - - while isspace(c) - c, i, j = parseint_next(s,i,endpos) - end - (j == 0) && (return 0, 0, 0) - - if base == 0 - if c == '0' && !done(s,i) - c, i = next(s,i) - base = c=='b' ? 2 : c=='o' ? 8 : c=='x' ? 16 : 10 - if base != 10 - c, i, j = parseint_next(s,i,endpos) - end - else - base = 10 - end - end - return sgn, base, j -end - -function tryparse_internal(::Type{T}, s::AbstractString, startpos::Int, endpos::Int, base_::Integer, raise::Bool) where T<:Integer - _n = Nullable{T}() - sgn, base, i = parseint_preamble(T<:Signed, Int(base_), s, startpos, endpos) - if sgn == 0 && base == 0 && i == 0 - raise && throw(ArgumentError("input string is empty or only contains whitespace")) - return _n - end - if !(2 <= base <= 62) - raise && throw(ArgumentError("invalid base: base must be 2 ≤ base ≤ 62, got $base")) - return _n - end - if i == 0 - raise && throw(ArgumentError("premature end of integer: $(repr(SubString(s,startpos,endpos)))")) - return _n - end - c, i = parseint_next(s,i,endpos) - if i == 0 - raise && throw(ArgumentError("premature end of integer: $(repr(SubString(s,startpos,endpos)))")) - return _n - end - - base = convert(T,base) - m::T = div(typemax(T)-base+1,base) - n::T = 0 - a::Int = base <= 36 ? 10 : 36 - while n <= m - d::T = '0' <= c <= '9' ? c-'0' : - 'A' <= c <= 'Z' ? c-'A'+10 : - 'a' <= c <= 'z' ? c-'a'+a : base - if d >= base - raise && throw(ArgumentError("invalid base $base digit $(repr(c)) in $(repr(SubString(s,startpos,endpos)))")) - return _n - end - n *= base - n += d - if i > endpos - n *= sgn - return Nullable{T}(n) - end - c, i = next(s,i) - isspace(c) && break - end - (T <: Signed) && (n *= sgn) - while !isspace(c) - d::T = '0' <= c <= '9' ? c-'0' : - 'A' <= c <= 'Z' ? c-'A'+10 : - 'a' <= c <= 'z' ? c-'a'+a : base - if d >= base - raise && throw(ArgumentError("invalid base $base digit $(repr(c)) in $(repr(SubString(s,startpos,endpos)))")) - return _n - end - (T <: Signed) && (d *= sgn) - - n, ov_mul = mul_with_overflow(n, base) - n, ov_add = add_with_overflow(n, d) - if ov_mul | ov_add - raise && throw(OverflowError()) - return _n - end - (i > endpos) && return Nullable{T}(n) - c, i = next(s,i) - end - while i <= endpos - c, i = next(s,i) - if !isspace(c) - raise && throw(ArgumentError("extra characters after whitespace in $(repr(SubString(s,startpos,endpos)))")) - return _n - end - end - return Nullable{T}(n) -end - -function tryparse_internal(::Type{Bool}, sbuff::Union{String,SubString}, - startpos::Int, endpos::Int, base::Integer, raise::Bool) - if isempty(sbuff) - raise && throw(ArgumentError("input string is empty")) - return Nullable{Bool}() - end - - orig_start = startpos - orig_end = endpos - - # Ignore leading and trailing whitespace - while isspace(sbuff[startpos]) && startpos <= endpos - startpos = nextind(sbuff, startpos) - end - while isspace(sbuff[endpos]) && endpos >= startpos - endpos = prevind(sbuff, endpos) - end - - len = endpos - startpos + 1 - p = pointer(sbuff) + startpos - 1 - (len == 4) && (0 == ccall(:memcmp, Int32, (Ptr{UInt8}, Ptr{UInt8}, UInt), - p, "true", 4)) && (return Nullable(true)) - (len == 5) && (0 == ccall(:memcmp, Int32, (Ptr{UInt8}, Ptr{UInt8}, UInt), - p, "false", 5)) && (return Nullable(false)) - - if raise - substr = SubString(sbuff, orig_start, orig_end) # show input string in the error to avoid confusion - if all(isspace, substr) - throw(ArgumentError("input string only contains whitespace")) - else - throw(ArgumentError("invalid Bool representation: $(repr(substr))")) - end - end - return Nullable{Bool}() -end - -@inline function check_valid_base(base) - if 2 <= base <= 62 - return base - end - throw(ArgumentError("invalid base: base must be 2 ≤ base ≤ 62, got $base")) -end - -tryparse(::Type{T}, s::AbstractString, base::Integer) where {T<:Integer} = - tryparse_internal(T, s, start(s), endof(s), check_valid_base(base), false) -tryparse(::Type{T}, s::AbstractString) where {T<:Integer} = - tryparse_internal(T, s, start(s), endof(s), 0, false) - -function parse(::Type{T}, s::AbstractString, base::Integer) where T<:Integer - get(tryparse_internal(T, s, start(s), endof(s), check_valid_base(base), true)) -end - -function parse(::Type{T}, s::AbstractString) where T<:Integer - get(tryparse_internal(T, s, start(s), endof(s), 0, true)) # Zero means, "figure it out" -end - - -## string to float functions ## - -tryparse(::Type{Float64}, s::String) = ccall(:jl_try_substrtod, Nullable{Float64}, (Ptr{UInt8},Csize_t,Csize_t), s, 0, sizeof(s)) -tryparse(::Type{Float64}, s::SubString{String}) = ccall(:jl_try_substrtod, Nullable{Float64}, (Ptr{UInt8},Csize_t,Csize_t), s.string, s.offset, s.endof) - -tryparse(::Type{Float32}, s::String) = ccall(:jl_try_substrtof, Nullable{Float32}, (Ptr{UInt8},Csize_t,Csize_t), s, 0, sizeof(s)) -tryparse(::Type{Float32}, s::SubString{String}) = ccall(:jl_try_substrtof, Nullable{Float32}, (Ptr{UInt8},Csize_t,Csize_t), s.string, s.offset, s.endof) - -tryparse(::Type{T}, s::AbstractString) where {T<:Union{Float32,Float64}} = tryparse(T, String(s)) - -tryparse(::Type{Float16}, s::AbstractString) = convert(Nullable{Float16}, tryparse(Float32, s)) - -function parse(::Type{T}, s::AbstractString) where T<:AbstractFloat - result = tryparse(T, s) - if isnull(result) - throw(ArgumentError("cannot parse $(repr(s)) as $T")) - end - return unsafe_get(result) -end - -float(x::AbstractString) = parse(Float64,x) - -float(a::AbstractArray{<:AbstractString}) = map!(float, similar(a,typeof(float(0))), a) - -## interface to parser ## - -function parse(str::AbstractString, pos::Int; greedy::Bool=true, raise::Bool=true) - # pos is one based byte offset. - # returns (expr, end_pos). expr is () in case of parse error. - bstr = String(str) - ex, pos = ccall(:jl_parse_string, Any, - (Ptr{UInt8}, Csize_t, Int32, Int32), - bstr, sizeof(bstr), pos-1, greedy ? 1:0) - if raise && isa(ex,Expr) && ex.head === :error - throw(ParseError(ex.args[1])) - end - if ex === () - raise && throw(ParseError("end of input")) - ex = Expr(:error, "end of input") - end - return ex, pos+1 # C is zero-based, Julia is 1-based -end - -function parse(str::AbstractString; raise::Bool=true) - ex, pos = parse(str, 1, greedy=true, raise=raise) - if isa(ex,Expr) && ex.head === :error - return ex - end - if !done(str, pos) - raise && throw(ParseError("extra token after end of expression")) - return Expr(:error, "extra token after end of expression") - end - return ex -end diff --git a/julia-0.6.3/share/julia/base/path.jl b/julia-0.6.3/share/julia/base/path.jl deleted file mode 100644 index 940ae4c..0000000 --- a/julia-0.6.3/share/julia/base/path.jl +++ /dev/null @@ -1,390 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -export - abspath, - basename, - dirname, - expanduser, - homedir, - isabspath, - isdirpath, - joinpath, - normpath, - realpath, - relpath, - splitdir, - splitdrive, - splitext - -if is_unix() - const path_separator = "/" - const path_separator_re = r"/+" - const path_directory_re = r"(?:^|/)\.{0,2}$" - const path_dir_splitter = r"^(.*?)(/+)([^/]*)$" - const path_ext_splitter = r"^((?:.*/)?(?:\.|[^/\.])[^/]*?)(\.[^/\.]*|)$" - - splitdrive(path::String) = ("",path) -elseif is_windows() - const path_separator = "\\" - const path_separator_re = r"[/\\]+" - const path_absolute_re = r"^(?:\w+:)?[/\\]" - const path_directory_re = r"(?:^|[/\\])\.{0,2}$" - const path_dir_splitter = r"^(.*?)([/\\]+)([^/\\]*)$" - const path_ext_splitter = r"^((?:.*[/\\])?(?:\.|[^/\\\.])[^/\\]*?)(\.[^/\\\.]*|)$" - - function splitdrive(path::String) - m = match(r"^([^\\]+:|\\\\[^\\]+\\[^\\]+|\\\\\?\\UNC\\[^\\]+\\[^\\]+|\\\\\?\\[^\\]+:|)(.*)$", path) - String(m.captures[1]), String(m.captures[2]) - end -else - error("path primitives for this OS need to be defined") -end - - -""" - splitdrive(path::AbstractString) -> (AbstractString, AbstractString) - -On Windows, split a path into the drive letter part and the path part. On Unix systems, the -first component is always the empty string. -""" -splitdrive(path::AbstractString) - -""" - homedir() -> AbstractString - -Return the current user's home directory. - -!!! note - `homedir` determines the home directory via `libuv`'s `uv_os_homedir`. For details - (for example on how to specify the home directory via environment variables), see the - [`uv_os_homedir` documentation](http://docs.libuv.org/en/v1.x/misc.html#c.uv_os_homedir). -""" -function homedir() - path_max = 1024 - buf = Vector{UInt8}(path_max) - sz = Ref{Csize_t}(path_max + 1) - while true - rc = ccall(:uv_os_homedir, Cint, (Ptr{UInt8}, Ptr{Csize_t}), buf, sz) - if rc == 0 - resize!(buf, sz[]) - return String(buf) - elseif rc == Base.UV_ENOBUFS - resize!(buf, sz[] - 1) - else - error("unable to retrieve home directory") - end - end -end - - -if is_windows() - isabspath(path::String) = ismatch(path_absolute_re, path) -else - isabspath(path::String) = startswith(path, '/') -end - -""" - isabspath(path::AbstractString) -> Bool - -Determines whether a path is absolute (begins at the root directory). - -```jldoctest -julia> isabspath("/home") -true - -julia> isabspath("home") -false -``` -""" -isabspath(path::AbstractString) - -""" - isdirpath(path::AbstractString) -> Bool - -Determines whether a path refers to a directory (for example, ends with a path separator). - -```jldoctest -julia> isdirpath("/home") -false - -julia> isdirpath("/home/") -true -``` -""" -isdirpath(path::String) = ismatch(path_directory_re, splitdrive(path)[2]) - -""" - splitdir(path::AbstractString) -> (AbstractString, AbstractString) - -Split a path into a tuple of the directory name and file name. - -```jldoctest -julia> splitdir("/home/myuser") -("/home", "myuser") -``` -""" -function splitdir(path::String) - a, b = splitdrive(path) - m = match(path_dir_splitter,b) - m === nothing && return (a,b) - a = string(a, isempty(m.captures[1]) ? m.captures[2][1] : m.captures[1]) - a, String(m.captures[3]) -end - -""" - dirname(path::AbstractString) -> AbstractString - -Get the directory part of a path. - -```jldoctest -julia> dirname("/home/myuser") -"/home" -``` - -See also: [`basename`](@ref) -""" - dirname(path::AbstractString) = splitdir(path)[1] - -""" - basename(path::AbstractString) -> AbstractString - -Get the file name part of a path. - - ```jldoctest -julia> basename("/home/myuser/example.jl") -"example.jl" -``` - -See also: [`dirname`](@ref) -""" -basename(path::AbstractString) = splitdir(path)[2] - -""" - splitext(path::AbstractString) -> (AbstractString, AbstractString) - -If the last component of a path contains a dot, split the path into everything before the -dot and everything including and after the dot. Otherwise, return a tuple of the argument -unmodified and the empty string. - -```jldoctest -julia> splitext("/home/myuser/example.jl") -("/home/myuser/example", ".jl") - -julia> splitext("/home/myuser/example") -("/home/myuser/example", "") -``` -""" -function splitext(path::String) - a, b = splitdrive(path) - m = match(path_ext_splitter, b) - m === nothing && return (path,"") - a*m.captures[1], String(m.captures[2]) -end - -function pathsep(paths::AbstractString...) - for path in paths - m = match(path_separator_re, String(path)) - m !== nothing && return m.match[1:1] - end - return path_separator -end - -joinpath(a::AbstractString) = a - -""" - joinpath(parts...) -> AbstractString - -Join path components into a full path. If some argument is an absolute path, then prior -components are dropped. - -```jldoctest -julia> joinpath("/home/myuser","example.jl") -"/home/myuser/example.jl" -``` -""" -joinpath(a::AbstractString, b::AbstractString, c::AbstractString...) = joinpath(joinpath(a,b), c...) - -function joinpath(a::String, b::String) - isabspath(b) && return b - A, a = splitdrive(a) - B, b = splitdrive(b) - !isempty(B) && A != B && throw(ArgumentError("drive mismatch: $A$a $B$b")) - C = isempty(B) ? A : B - isempty(a) ? string(C,b) : - ismatch(path_separator_re, a[end:end]) ? string(C,a,b) : - string(C,a,pathsep(a,b),b) -end -joinpath(a::AbstractString, b::AbstractString) = joinpath(String(a), String(b)) - -""" - normpath(path::AbstractString) -> AbstractString - -Normalize a path, removing "." and ".." entries. - -```jldoctest -julia> normpath("/home/myuser/../example.jl") -"/home/example.jl" -``` -""" -function normpath(path::String) - isabs = isabspath(path) - isdir = isdirpath(path) - drive, path = splitdrive(path) - parts = split(path, path_separator_re) - filter!(x->!isempty(x) && x!=".", parts) - while true - clean = true - for j = 1:length(parts)-1 - if parts[j] != ".." && parts[j+1] == ".." - deleteat!(parts, j:j+1) - clean = false - break - end - end - clean && break - end - if isabs - while !isempty(parts) && parts[1] == ".." - shift!(parts) - end - elseif isempty(parts) - push!(parts, ".") - end - path = join(parts, path_separator) - if isabs - path = path_separator*path - end - if isdir && !isdirpath(path) - path *= path_separator - end - string(drive,path) -end -normpath(a::AbstractString, b::AbstractString...) = normpath(joinpath(a,b...)) - -""" - abspath(path::AbstractString) -> AbstractString - -Convert a path to an absolute path by adding the current directory if necessary. -""" -abspath(a::String) = normpath(isabspath(a) ? a : joinpath(pwd(),a)) - -""" - abspath(path::AbstractString, paths::AbstractString...) -> AbstractString - -Convert a set of paths to an absolute path by joining them together and adding the -current directory if necessary. Equivalent to `abspath(joinpath(path, paths...))`. -""" -abspath(a::AbstractString, b::AbstractString...) = abspath(joinpath(a,b...)) - -if is_windows() -function realpath(path::AbstractString) - p = cwstring(path) - buf = zeros(UInt16, length(p)) - while true - n = ccall((:GetFullPathNameW, "kernel32"), stdcall, - UInt32, (Ptr{UInt16}, UInt32, Ptr{UInt16}, Ptr{Void}), - p, length(buf), buf, C_NULL) - systemerror(:realpath, n == 0) - x = n < length(buf) # is the buffer big enough? - resize!(buf, n) # shrink if x, grow if !x - x && return transcode(String, buf) - end -end - -function longpath(path::AbstractString) - p = cwstring(path) - buf = zeros(UInt16, length(p)) - while true - n = ccall((:GetLongPathNameW, "kernel32"), stdcall, - UInt32, (Ptr{UInt16}, Ptr{UInt16}, UInt32), - p, buf, length(buf)) - systemerror(:longpath, n == 0) - x = n < length(buf) # is the buffer big enough? - resize!(buf, n) # shrink if x, grow if !x - x && return transcode(String, buf) - end -end - -else # !windows -function realpath(path::AbstractString) - p = ccall(:realpath, Ptr{UInt8}, (Cstring, Ptr{UInt8}), path, C_NULL) - systemerror(:realpath, p == C_NULL) - str = unsafe_string(p) - Libc.free(p) - return str -end -end # os-test - - -""" - realpath(path::AbstractString) -> AbstractString - -Canonicalize a path by expanding symbolic links and removing "." and ".." entries. -""" -realpath(path::AbstractString) - - -if is_windows() -expanduser(path::AbstractString) = path # on windows, ~ means "temporary file" -else -function expanduser(path::AbstractString) - i = start(path) - c, i = next(path,i) - if c != '~' return path end - if done(path,i) return homedir() end - c, j = next(path,i) - if c == '/' return homedir()*path[i:end] end - throw(ArgumentError("~user tilde expansion not yet implemented")) -end -end - - -""" - expanduser(path::AbstractString) -> AbstractString - -On Unix systems, replace a tilde character at the start of a path with the current user's home directory. -""" -expanduser(path::AbstractString) - - -""" - relpath(path::AbstractString, startpath::AbstractString = ".") -> AbstractString - -Return a relative filepath to `path` either from the current directory or from an optional -start directory. This is a path computation: the filesystem is not accessed to confirm the -existence or nature of `path` or `startpath`. -""" -function relpath(path::String, startpath::String = ".") - isempty(path) && throw(ArgumentError("`path` must be specified")) - isempty(startpath) && throw(ArgumentError("`startpath` must be specified")) - curdir = "." - pardir = ".." - path == startpath && return curdir - path_arr = split(abspath(path), path_separator_re) - start_arr = split(abspath(startpath), path_separator_re) - i = 0 - while i < min(length(path_arr), length(start_arr)) - i += 1 - if path_arr[i] != start_arr[i] - i -= 1 - break - end - end - pathpart = join(path_arr[i+1:findlast(x -> !isempty(x), path_arr)], path_separator) - prefix_num = findlast(x -> !isempty(x), start_arr) - i - 1 - if prefix_num >= 0 - prefix = pardir * path_separator - relpath_ = isempty(pathpart) ? - (prefix^prefix_num) * pardir : - (prefix^prefix_num) * pardir * path_separator * pathpart - else - relpath_ = pathpart - end - return isempty(relpath_) ? curdir : relpath_ -end -relpath(path::AbstractString, startpath::AbstractString) = - relpath(String(path), String(startpath)) - -for f in (:isabspath, :isdirpath, :splitdir, :splitdrive, :splitext, :normpath, :abspath) - @eval $f(path::AbstractString) = $f(String(path)) -end diff --git a/julia-0.6.3/share/julia/base/pcre.jl b/julia-0.6.3/share/julia/base/pcre.jl deleted file mode 100644 index 316a582..0000000 --- a/julia-0.6.3/share/julia/base/pcre.jl +++ /dev/null @@ -1,184 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -## low-level pcre2 interface ## - -module PCRE - -include(string(length(Core.ARGS)>=2?Core.ARGS[2]:"","pcre_h.jl")) # include($BUILDROOT/base/pcre_h.jl) - -const PCRE_LIB = "libpcre2-8" - -const JIT_STACK = Ref{Ptr{Void}}(C_NULL) -const MATCH_CONTEXT = Ref{Ptr{Void}}(C_NULL) - -function __init__() - try - JIT_STACK_START_SIZE = 32768 - JIT_STACK_MAX_SIZE = 1048576 - JIT_STACK[] = ccall((:pcre2_jit_stack_create_8, PCRE_LIB), Ptr{Void}, - (Cint, Cint, Ptr{Void}), - JIT_STACK_START_SIZE, JIT_STACK_MAX_SIZE, C_NULL) - MATCH_CONTEXT[] = ccall((:pcre2_match_context_create_8, PCRE_LIB), - Ptr{Void}, (Ptr{Void},), C_NULL) - ccall((:pcre2_jit_stack_assign_8, PCRE_LIB), Void, - (Ptr{Void}, Ptr{Void}, Ptr{Void}), MATCH_CONTEXT[], C_NULL, JIT_STACK[]) - catch ex - Base.showerror_nostdio(ex, - "WARNING: Error during initialization of module PCRE") - end -end - -# supported options for different use cases - -const COMPILE_MASK = - ANCHORED | - CASELESS | - DOLLAR_ENDONLY | - DOTALL | - EXTENDED | - FIRSTLINE | - MULTILINE | - NEWLINE_ANY | - NEWLINE_ANYCRLF | - NEWLINE_CR | - NEWLINE_CRLF | - NEWLINE_LF | - NO_AUTO_CAPTURE | - NO_START_OPTIMIZE | - NO_UTF_CHECK | - UNGREEDY | - UTF - -const EXECUTE_MASK = - NEWLINE_ANY | - NEWLINE_ANYCRLF | - NEWLINE_CR | - NEWLINE_CRLF | - NEWLINE_LF | - NOTBOL | - NOTEMPTY | - NOTEMPTY_ATSTART | - NOTEOL | - NO_START_OPTIMIZE | - NO_UTF_CHECK | - PARTIAL_HARD | - PARTIAL_SOFT - - -const OPTIONS_MASK = COMPILE_MASK | EXECUTE_MASK - -const UNSET = ~Csize_t(0) # Indicates that an output vector element is unset - -function info(regex::Ptr{Void}, what::Integer, ::Type{T}) where T - buf = Ref{T}() - ret = ccall((:pcre2_pattern_info_8, PCRE_LIB), Int32, - (Ptr{Void}, Int32, Ptr{Void}), - regex, what, buf) - if ret != 0 - error(ret == ERROR_NULL ? "NULL regex object" : - ret == ERROR_BADMAGIC ? "invalid regex object" : - ret == ERROR_BADOPTION ? "invalid option flags" : - "unknown error $ret") - end - buf[] -end - -function get_ovec(match_data) - ptr = ccall((:pcre2_get_ovector_pointer_8, PCRE_LIB), Ptr{Csize_t}, - (Ptr{Void},), match_data) - n = ccall((:pcre2_get_ovector_count_8, PCRE_LIB), UInt32, - (Ptr{Void},), match_data) - unsafe_wrap(Array, ptr, 2n, false) -end - -function compile(pattern::AbstractString, options::Integer) - errno = Ref{Cint}(0) - erroff = Ref{Csize_t}(0) - re_ptr = ccall((:pcre2_compile_8, PCRE_LIB), Ptr{Void}, - (Ptr{UInt8}, Csize_t, UInt32, Ref{Cint}, Ref{Csize_t}, Ptr{Void}), - pattern, sizeof(pattern), options, errno, erroff, C_NULL) - re_ptr == C_NULL && error("PCRE compilation error: $(err_message(errno[])) at offset $(erroff[])") - re_ptr -end - -function jit_compile(regex::Ptr{Void}) - errno = ccall((:pcre2_jit_compile_8, PCRE_LIB), Cint, - (Ptr{Void}, UInt32), regex, JIT_COMPLETE) - errno == 0 || error("PCRE JIT error: $(err_message(errno))") -end - -free_match_data(match_data) = - ccall((:pcre2_match_data_free_8, PCRE_LIB), Void, (Ptr{Void},), match_data) - -free_re(re) = - ccall((:pcre2_code_free_8, PCRE_LIB), Void, (Ptr{Void},), re) - -free_jit_stack(stack) = - ccall((:pcre2_jit_stack_free_8, PCRE_LIB), Void, (Ptr{Void},), stack) - -free_match_context(context) = - ccall((:pcre2_match_context_free_8, PCRE_LIB), Void, (Ptr{Void},), context) - -function err_message(errno) - buffer = Vector{UInt8}(256) - ccall((:pcre2_get_error_message_8, PCRE_LIB), Void, - (Int32, Ptr{UInt8}, Csize_t), errno, buffer, sizeof(buffer)) - unsafe_string(pointer(buffer)) -end - -function exec(re,subject,offset,options,match_data) - rc = ccall((:pcre2_match_8, PCRE_LIB), Cint, - (Ptr{Void}, Ptr{UInt8}, Csize_t, Csize_t, Cuint, Ptr{Void}, Ptr{Void}), - re, subject, sizeof(subject), offset, options, match_data, MATCH_CONTEXT[]) - # rc == -1 means no match, -2 means partial match. - rc < -2 && error("PCRE.exec error: $(err_message(rc))") - rc >= 0 -end - -function create_match_data(re) - ccall((:pcre2_match_data_create_from_pattern_8, PCRE_LIB), - Ptr{Void}, (Ptr{Void}, Ptr{Void}), re, C_NULL) -end - -function substring_number_from_name(re, name) - ccall((:pcre2_substring_number_from_name_8, PCRE_LIB), Cint, - (Ptr{Void}, Cstring), re, name) -end - -function substring_length_bynumber(match_data, number) - s = Ref{Csize_t}() - rc = ccall((:pcre2_substring_length_bynumber_8, PCRE_LIB), Cint, - (Ptr{Void}, UInt32, Ref{Csize_t}), match_data, number, s) - rc < 0 && error("PCRE error: $(err_message(rc))") - convert(Int, s[]) -end - -function substring_copy_bynumber(match_data, number, buf, buf_size) - s = Ref{Csize_t}(buf_size) - rc = ccall((:pcre2_substring_copy_bynumber_8, PCRE_LIB), Cint, - (Ptr{Void}, UInt32, Ptr{UInt8}, Ref{Csize_t}), - match_data, number, buf, s) - rc < 0 && error("PCRE error: $(err_message(rc))") - convert(Int, s[]) -end - -function capture_names(re) - name_count = info(re, INFO_NAMECOUNT, UInt32) - name_entry_size = info(re, INFO_NAMEENTRYSIZE, UInt32) - nametable_ptr = info(re, INFO_NAMETABLE, Ptr{UInt8}) - names = Dict{Int, String}() - for i=1:name_count - offset = (i-1)*name_entry_size + 1 - # The capture group index corresponding to name 'i' is stored as a - # big-endian 16-bit value. - high_byte = UInt16(unsafe_load(nametable_ptr, offset)) - low_byte = UInt16(unsafe_load(nametable_ptr, offset+1)) - idx = (high_byte << 8) | low_byte - # The capture group name is a null-terminated string located directly - # after the index. - names[idx] = unsafe_string(nametable_ptr+offset+1) - end - names -end - -end # module diff --git a/julia-0.6.3/share/julia/base/permuteddimsarray.jl b/julia-0.6.3/share/julia/base/permuteddimsarray.jl deleted file mode 100644 index fee5d3a..0000000 --- a/julia-0.6.3/share/julia/base/permuteddimsarray.jl +++ /dev/null @@ -1,193 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -module PermutedDimsArrays - -export permutedims, PermutedDimsArray - -# Some day we will want storage-order-aware iteration, so put perm in the parameters -struct PermutedDimsArray{T,N,perm,iperm,AA<:AbstractArray} <: AbstractArray{T,N} - parent::AA - - function PermutedDimsArray{T,N,perm,iperm,AA}(data::AA) where {T,N,perm,iperm,AA<:AbstractArray} - (isa(perm, NTuple{N,Int}) && isa(iperm, NTuple{N,Int})) || error("perm and iperm must both be NTuple{$N,Int}") - isperm(perm) || throw(ArgumentError(string(perm, " is not a valid permutation of dimensions 1:", N))) - all(map(d->iperm[perm[d]]==d, 1:N)) || throw(ArgumentError(string(perm, " and ", iperm, " must be inverses"))) - new(data) - end -end - -""" - PermutedDimsArray(A, perm) -> B - -Given an AbstractArray `A`, create a view `B` such that the -dimensions appear to be permuted. Similar to `permutedims`, except -that no copying occurs (`B` shares storage with `A`). - -See also: [`permutedims`](@ref). - -# Example - -```jldoctest -julia> A = rand(3,5,4); - -julia> B = PermutedDimsArray(A, (3,1,2)); - -julia> size(B) -(4, 3, 5) - -julia> B[3,1,2] == A[1,2,3] -true -``` -""" -function PermutedDimsArray(data::AbstractArray{T,N}, perm) where {T,N} - length(perm) == N || throw(ArgumentError(string(perm, " is not a valid permutation of dimensions 1:", N))) - iperm = invperm(perm) - PermutedDimsArray{T,N,(perm...,),(iperm...,),typeof(data)}(data) -end - -Base.parent(A::PermutedDimsArray) = A.parent -Base.size(A::PermutedDimsArray{T,N,perm}) where {T,N,perm} = genperm(size(parent(A)), perm) -Base.indices(A::PermutedDimsArray{T,N,perm}) where {T,N,perm} = genperm(indices(parent(A)), perm) - -Base.unsafe_convert(::Type{Ptr{T}}, A::PermutedDimsArray{T}) where {T} = Base.unsafe_convert(Ptr{T}, parent(A)) - -# It's OK to return a pointer to the first element, and indeed quite -# useful for wrapping C routines that require a different storage -# order than used by Julia. But for an array with unconventional -# storage order, a linear offset is ambiguous---is it a memory offset -# or a linear index? -Base.pointer(A::PermutedDimsArray, i::Integer) = throw(ArgumentError("pointer(A, i) is deliberately unsupported for PermutedDimsArray")) - -function Base.strides(A::PermutedDimsArray{T,N,perm}) where {T,N,perm} - s = strides(parent(A)) - ntuple(d->s[perm[d]], Val{N}) -end - -@inline function Base.getindex(A::PermutedDimsArray{T,N,perm,iperm}, I::Vararg{Int,N}) where {T,N,perm,iperm} - @boundscheck checkbounds(A, I...) - @inbounds val = getindex(A.parent, genperm(I, iperm)...) - val -end -@inline function Base.setindex!(A::PermutedDimsArray{T,N,perm,iperm}, val, I::Vararg{Int,N}) where {T,N,perm,iperm} - @boundscheck checkbounds(A, I...) - @inbounds setindex!(A.parent, val, genperm(I, iperm)...) - val -end - -# For some reason this is faster than ntuple(d->I[perm[d]], Val{N}) (#15276?) -@inline genperm(I::NTuple{N,Any}, perm::Dims{N}) where {N} = _genperm((), I, perm...) -_genperm(out, I) = out -@inline _genperm(out, I, p, perm...) = _genperm((out..., I[p]), I, perm...) -@inline genperm(I, perm::AbstractVector{Int}) = genperm(I, (perm...,)) - -""" - permutedims(A, perm) - -Permute the dimensions of array `A`. `perm` is a vector specifying a permutation of length -`ndims(A)`. This is a generalization of transpose for multi-dimensional arrays. Transpose is -equivalent to `permutedims(A, [2,1])`. - -See also: [`PermutedDimsArray`](@ref). - -# Example -```jldoctest -julia> A = reshape(collect(1:8), (2,2,2)) -2×2×2 Array{Int64,3}: -[:, :, 1] = - 1 3 - 2 4 - -[:, :, 2] = - 5 7 - 6 8 - -julia> permutedims(A, [3, 2, 1]) -2×2×2 Array{Int64,3}: -[:, :, 1] = - 1 3 - 5 7 - -[:, :, 2] = - 2 4 - 6 8 -``` -""" -function Base.permutedims(A::AbstractArray, perm) - dest = similar(A, genperm(indices(A), perm)) - permutedims!(dest, A, perm) -end - -""" - permutedims!(dest, src, perm) - -Permute the dimensions of array `src` and store the result in the array `dest`. `perm` is a -vector specifying a permutation of length `ndims(src)`. The preallocated array `dest` should -have `size(dest) == size(src)[perm]` and is completely overwritten. No in-place permutation -is supported and unexpected results will happen if `src` and `dest` have overlapping memory -regions. - -See also [`permutedims`](@ref). -""" -function Base.permutedims!(dest, src::AbstractArray, perm) - Base.checkdims_perm(dest, src, perm) - P = PermutedDimsArray(dest, invperm(perm)) - _copy!(P, src) - return dest -end - -function Base.copy!(dest::PermutedDimsArray{T,N}, src::AbstractArray{T,N}) where {T,N} - checkbounds(dest, indices(src)...) - _copy!(dest, src) -end -Base.copy!(dest::PermutedDimsArray, src::AbstractArray) = _copy!(dest, src) - -function _copy!(P::PermutedDimsArray{T,N,perm}, src) where {T,N,perm} - # If dest/src are "close to dense," then it pays to be cache-friendly. - # Determine the first permuted dimension - d = 0 # d+1 will hold the first permuted dimension of src - while d < ndims(src) && perm[d+1] == d+1 - d += 1 - end - if d == ndims(src) - copy!(parent(P), src) # it's not permuted - else - R1 = CartesianRange(indices(src)[1:d]) - d1 = findfirst(perm, d+1) # first permuted dim of dest - R2 = CartesianRange(indices(src)[d+2:d1-1]) - R3 = CartesianRange(indices(src)[d1+1:end]) - _permutedims!(P, src, R1, R2, R3, d+1, d1) - end - return P -end - -@noinline function _permutedims!(P::PermutedDimsArray, src, R1::CartesianRange{CartesianIndex{0}}, R2, R3, ds, dp) - ip, is = indices(src, dp), indices(src, ds) - for jo in first(ip):8:last(ip), io in first(is):8:last(is) - for I3 in R3, I2 in R2 - for j in jo:min(jo+7, last(ip)) - for i in io:min(io+7, last(is)) - @inbounds P[i, I2, j, I3] = src[i, I2, j, I3] - end - end - end - end - P -end - -@noinline function _permutedims!(P::PermutedDimsArray, src, R1, R2, R3, ds, dp) - ip, is = indices(src, dp), indices(src, ds) - for jo in first(ip):8:last(ip), io in first(is):8:last(is) - for I3 in R3, I2 in R2 - for j in jo:min(jo+7, last(ip)) - for i in io:min(io+7, last(is)) - for I1 in R1 - @inbounds P[I1, i, I2, j, I3] = src[I1, i, I2, j, I3] - end - end - end - end - end - P -end - -end diff --git a/julia-0.6.3/share/julia/base/pkg/cache.jl b/julia-0.6.3/share/julia/base/pkg/cache.jl deleted file mode 100644 index b453557..0000000 --- a/julia-0.6.3/share/julia/base/pkg/cache.jl +++ /dev/null @@ -1,93 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -module Cache - -import ...LibGit2, ..Dir, ...Pkg.PkgError -using ..Types - -rewrite_url_to = "https" - -const GITHUB_REGEX = - r"^(?:git@|git://|https://(?:[\w\.\+\-]+@)?)github.com[:/](([^/].+)/(.+?))(?:\.git)?$"i - -path(pkg::AbstractString) = abspath(".cache", pkg) - -function mkcachedir() - cache = joinpath(realpath("."), ".cache") - if isdir(cache) - return - end - - @static if is_unix() - if Dir.isversioned(pwd()) - rootcache = joinpath(realpath(".."), ".cache") - if !isdir(rootcache) - mkdir(rootcache) - end - symlink(rootcache, cache) - return - end - end - mkdir(cache) -end - -function prefetch(pkg::AbstractString, url::AbstractString, sha1s::Vector) - isdir(".cache") || mkcachedir() - - cache = path(pkg) - normalized_url = normalize_url(url) - - repo = if isdir(cache) - LibGit2.GitRepo(cache) # open repo, free it at the end - else - info("Cloning cache of $pkg from $normalized_url") - try - # clone repo, free it at the end - LibGit2.clone(normalized_url, cache, isbare = true, remote_cb = LibGit2.mirror_cb()) - catch err - errmsg = if isa(err, LibGit2.Error.GitError) - "Cannot clone $pkg from $normalized_url. $(err.msg)" - elseif isa(err, InterruptException) - "Package `$pkg` prefetching was interrupted." - else - "Unknown error: $err" - end - isdir(cache) && rm(cache, recursive=true) - throw(PkgError(errmsg)) - end - end - try - LibGit2.set_remote_url(repo, normalized_url) - in_cache = BitArray(map(sha1->LibGit2.iscommit(sha1, repo), sha1s)) - if !all(in_cache) - info("Updating cache of $pkg...") - LibGit2.fetch(repo) - in_cache = BitArray(map(sha1->LibGit2.iscommit(sha1, repo), sha1s)) - end - sha1s[.!in_cache] - finally - close(repo) # closing repo opened/created above - end -end -prefetch(pkg::AbstractString, url::AbstractString, sha1::AbstractString...) = - prefetch(pkg, url, AbstractString[sha1...]) - -function setprotocol!(proto::AbstractString) - global rewrite_url_to - - if length(proto) == 0 - rewrite_url_to = nothing - else - rewrite_url_to = proto - end -end - -function normalize_url(url::AbstractString) - global rewrite_url_to - - m = match(GITHUB_REGEX,url) - (m === nothing || rewrite_url_to === nothing) ? - url : "$rewrite_url_to://github.com/$(m.captures[1]).git" -end - -end # module diff --git a/julia-0.6.3/share/julia/base/pkg/dir.jl b/julia-0.6.3/share/julia/base/pkg/dir.jl deleted file mode 100644 index 76b8b57..0000000 --- a/julia-0.6.3/share/julia/base/pkg/dir.jl +++ /dev/null @@ -1,82 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -module Dir - -import ..Pkg: DEFAULT_META, META_BRANCH, PkgError -import ...LibGit2, ...LibGit2.with - -const DIR_NAME = ".julia" - -_pkgroot() = abspath(get(ENV,"JULIA_PKGDIR",joinpath(homedir(),DIR_NAME))) -isversioned(p::AbstractString) = ((x,y) = (VERSION.major, VERSION.minor); basename(p) == "v$x.$y") - -function path() - b = _pkgroot() - x, y = VERSION.major, VERSION.minor - d = joinpath(b,"v$x.$y") - if isdir(d) || !isdir(b) || !isdir(joinpath(b, "METADATA")) - return d - end - return b -end -path(pkg::AbstractString...) = normpath(path(),pkg...) - -function cd(f::Function, args...; kws...) - dir = path() - metadata_dir = joinpath(dir, "METADATA") - if !isdir(metadata_dir) - !haskey(ENV,"JULIA_PKGDIR") ? init() : - throw(PkgError("Package metadata directory $metadata_dir doesn't exist; run Pkg.init() to initialize it.")) - end - if haskey(ENV,"JULIA_PKGDIR") - withenv("JULIA_PKGDIR" => abspath(ENV["JULIA_PKGDIR"])) do - Base.cd(()->f(args...; kws...), dir) - end - else - Base.cd(()->f(args...; kws...), dir) - end -end - -function init(meta::AbstractString=DEFAULT_META, branch::AbstractString=META_BRANCH) - dir = path() - info("Initializing package repository $dir") - metadata_dir = joinpath(dir, "METADATA") - if isdir(metadata_dir) - info("Package directory $dir is already initialized.") - LibGit2.set_remote_url(metadata_dir, meta) - return - end - local temp_dir = "" - try - mkpath(dir) - temp_dir = mktempdir(dir) - Base.cd(temp_dir) do - info("Cloning METADATA from $meta") - with(LibGit2.clone(meta, "METADATA", branch = branch)) do metadata_repo - LibGit2.set_remote_url(metadata_repo, meta) - end - touch("REQUIRE") - touch("META_BRANCH") - write("META_BRANCH", branch) - end - #Move TEMP to METADATA - Base.mv(joinpath(temp_dir,"METADATA"), metadata_dir) - Base.mv(joinpath(temp_dir,"REQUIRE"), joinpath(dir,"REQUIRE")) - Base.mv(joinpath(temp_dir,"META_BRANCH"), joinpath(dir,"META_BRANCH")) - rm(temp_dir, recursive=true) - catch err - ispath(metadata_dir) && rm(metadata_dir, recursive=true) - ispath(temp_dir) && rm(temp_dir, recursive=true) - rethrow(err) - end -end - -function getmetabranch() - try - readline(joinpath(path(),"META_BRANCH")) - catch err - META_BRANCH - end -end - -end # module diff --git a/julia-0.6.3/share/julia/base/pkg/entry.jl b/julia-0.6.3/share/julia/base/pkg/entry.jl deleted file mode 100644 index 596dc70..0000000 --- a/julia-0.6.3/share/julia/base/pkg/entry.jl +++ /dev/null @@ -1,765 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -module Entry - -import Base: thispatch, nextpatch, nextminor, nextmajor, check_new_version -import ..Reqs, ..Read, ..Query, ..Resolve, ..Cache, ..Write, ..Dir -import ...LibGit2 -importall ...LibGit2 -import ...Pkg.PkgError -using ..Types - -macro recover(ex) - quote - try $(esc(ex)) - catch err - show(err) - print('\n') - end - end -end - -function edit(f::Function, pkg::AbstractString, args...) - r = Reqs.read("REQUIRE") - reqs = Reqs.parse(r) - avail = Read.available() - !haskey(avail,pkg) && !haskey(reqs,pkg) && return false - rʹ = f(r,pkg,args...) - rʹ == r && return false - reqsʹ = Reqs.parse(rʹ) - reqsʹ != reqs && resolve(reqsʹ,avail) - Reqs.write("REQUIRE",rʹ) - info("Package database updated") - return true -end - -function edit() - editor = get(ENV,"VISUAL",get(ENV,"EDITOR",nothing)) - editor !== nothing || - throw(PkgError("set the EDITOR environment variable to an edit command")) - editor = Base.shell_split(editor) - reqs = Reqs.parse("REQUIRE") - run(`$editor REQUIRE`) - reqsʹ = Reqs.parse("REQUIRE") - reqs == reqsʹ && return info("Nothing to be done") - info("Computing changes...") - resolve(reqsʹ) -end - -function add(pkg::AbstractString, vers::VersionSet) - outdated = :maybe - @sync begin - @async if !edit(Reqs.add,pkg,vers) - ispath(pkg) || throw(PkgError("unknown package $pkg")) - info("Package $pkg is already installed") - end - branch = Dir.getmetabranch() - outdated = with(GitRepo, "METADATA") do repo - if LibGit2.branch(repo) == branch - if LibGit2.isdiff(repo, "origin/$branch") - outdated = :yes - else - try - LibGit2.fetch(repo) - outdated = LibGit2.isdiff(repo, "origin/$branch") ? (:yes) : (:no) - end - end - else - :no # user is doing something funky with METADATA - end - end - end - if outdated != :no - is = outdated == :yes ? "is" : "might be" - info("METADATA $is out-of-date — you may not have the latest version of $pkg") - info("Use `Pkg.update()` to get the latest versions of your packages") - end -end -add(pkg::AbstractString, vers::VersionNumber...) = add(pkg,VersionSet(vers...)) - -function rm(pkg::AbstractString) - edit(Reqs.rm,pkg) && return - ispath(pkg) || return info("Package $pkg is not installed") - info("Removing $pkg (unregistered)") - Write.remove(pkg) -end - -function available() - all_avail = Read.available() - avail = AbstractString[] - for (pkg, vers) in all_avail - any(x->Types.satisfies("julia", VERSION, x[2].requires), vers) && push!(avail, pkg) - end - sort!(avail, by=lowercase) -end - -function available(pkg::AbstractString) - avail = Read.available(pkg) - if !isempty(avail) || Read.isinstalled(pkg) - return sort!(collect(keys(avail))) - end - throw(PkgError("$pkg is not a package (not registered or installed)")) -end - -function installed() - pkgs = Dict{String,VersionNumber}() - for (pkg,(ver,fix)) in Read.installed() - pkgs[pkg] = ver - end - return pkgs -end - -function installed(pkg::AbstractString) - avail = Read.available(pkg) - if Read.isinstalled(pkg) - res = typemin(VersionNumber) - if ispath(joinpath(pkg,".git")) - LibGit2.with(GitRepo, pkg) do repo - res = Read.installed_version(pkg, repo, avail) - end - end - return res - end - isempty(avail) && throw(PkgError("$pkg is not a package (not registered or installed)")) - return nothing # registered but not installed -end - -function status(io::IO; pkgname::AbstractString = "") - showpkg(pkg) = isempty(pkgname) ? true : (pkg == pkgname) - reqs = Reqs.parse("REQUIRE") - instd = Read.installed() - required = sort!(collect(keys(reqs))) - if !isempty(required) - showpkg("") && println(io, "$(length(required)) required packages:") - for pkg in required - if !haskey(instd, pkg) - showpkg(pkg) && status(io,pkg,"not found") - else - ver,fix = pop!(instd,pkg) - showpkg(pkg) && status(io,pkg,ver,fix) - end - end - end - additional = sort!(collect(keys(instd))) - if !isempty(additional) - showpkg("") && println(io, "$(length(additional)) additional packages:") - for pkg in additional - ver,fix = instd[pkg] - showpkg(pkg) && status(io,pkg,ver,fix) - end - end - if isempty(required) && isempty(additional) - println(io, "No packages installed") - end -end - -status(io::IO, pkg::AbstractString) = status(io, pkgname = pkg) - -function status(io::IO, pkg::AbstractString, ver::VersionNumber, fix::Bool) - @printf io " - %-29s " pkg - fix || return println(io,ver) - @printf io "%-19s" ver - if ispath(pkg,".git") - prepo = GitRepo(pkg) - try - with(LibGit2.head(prepo)) do phead - if LibGit2.isattached(prepo) - print(io, LibGit2.shortname(phead)) - else - print(io, string(LibGit2.GitHash(phead))[1:8]) - end - end - attrs = AbstractString[] - isfile("METADATA",pkg,"url") || push!(attrs,"unregistered") - LibGit2.isdirty(prepo) && push!(attrs,"dirty") - isempty(attrs) || print(io, " (",join(attrs,", "),")") - catch err - print_with_color(Base.error_color(), io, " broken-repo (unregistered)") - finally - close(prepo) - end - else - print_with_color(Base.warn_color(), io, "non-repo (unregistered)") - end - println(io) -end - -function status(io::IO, pkg::AbstractString, msg::AbstractString) - @printf io " - %-29s %-19s\n" pkg msg -end - -function clone(url::AbstractString, pkg::AbstractString) - info("Cloning $pkg from $url") - ispath(pkg) && throw(PkgError("$pkg already exists")) - try - LibGit2.with(LibGit2.clone(url, pkg)) do repo - LibGit2.set_remote_url(repo, url) - end - catch err - isdir(pkg) && Base.rm(pkg, recursive=true) - rethrow(err) - end - info("Computing changes...") - if !edit(Reqs.add, pkg) - isempty(Reqs.parse("$pkg/REQUIRE")) && return - resolve() - end -end - -function url_and_pkg(url_or_pkg::AbstractString) - if !(':' in url_or_pkg) - # no colon, could be a package name - url_file = joinpath("METADATA", url_or_pkg, "url") - isfile(url_file) && return readchomp(url_file), url_or_pkg - end - # try to parse as URL or local path - m = match(r"(?:^|[/\\])(\w+?)(?:\.jl)?(?:\.git)?$", url_or_pkg) - m === nothing && throw(PkgError("can't determine package name from URL: $url_or_pkg")) - return url_or_pkg, m.captures[1] -end - -clone(url_or_pkg::AbstractString) = clone(url_and_pkg(url_or_pkg)...) - -function checkout(pkg::AbstractString, branch::AbstractString, do_merge::Bool, do_pull::Bool) - ispath(pkg,".git") || throw(PkgError("$pkg is not a git repo")) - info("Checking out $pkg $branch...") - with(GitRepo, pkg) do r - LibGit2.transact(r) do repo - LibGit2.isdirty(repo) && throw(PkgError("$pkg is dirty, bailing")) - LibGit2.branch!(repo, branch, track=LibGit2.Consts.REMOTE_ORIGIN) - do_merge && LibGit2.merge!(repo, fastforward=true) # merge changes - if do_pull - info("Pulling $pkg latest $branch...") - LibGit2.fetch(repo) - LibGit2.merge!(repo, fastforward=true) - end - resolve() - end - end -end - -function free(pkg::AbstractString) - ispath(pkg,".git") || throw(PkgError("$pkg is not a git repo")) - Read.isinstalled(pkg) || throw(PkgError("$pkg cannot be freed – not an installed package")) - avail = Read.available(pkg) - isempty(avail) && throw(PkgError("$pkg cannot be freed – not a registered package")) - with(GitRepo, pkg) do repo - LibGit2.isdirty(repo) && throw(PkgError("$pkg cannot be freed – repo is dirty")) - info("Freeing $pkg") - vers = sort!(collect(keys(avail)), rev=true) - while true - for ver in vers - sha1 = avail[ver].sha1 - LibGit2.iscommit(sha1, repo) || continue - return LibGit2.transact(repo) do r - LibGit2.isdirty(repo) && throw(PkgError("$pkg is dirty, bailing")) - LibGit2.checkout!(repo, sha1) - resolve() - end - end - isempty(Cache.prefetch(pkg, Read.url(pkg), [a.sha1 for (v,a)=avail])) && continue - throw(PkgError("can't find any registered versions of $pkg to checkout")) - end - end -end - -function free(pkgs) - try - for pkg in pkgs - ispath(pkg,".git") || throw(PkgError("$pkg is not a git repo")) - Read.isinstalled(pkg) || throw(PkgError("$pkg cannot be freed – not an installed package")) - avail = Read.available(pkg) - isempty(avail) && throw(PkgError("$pkg cannot be freed – not a registered package")) - with(GitRepo, pkg) do repo - LibGit2.isdirty(repo) && throw(PkgError("$pkg cannot be freed – repo is dirty")) - info("Freeing $pkg") - vers = sort!(collect(keys(avail)), rev=true) - for ver in vers - sha1 = avail[ver].sha1 - LibGit2.iscommit(sha1, repo) || continue - LibGit2.checkout!(repo, sha1) - break - end - end - isempty(Cache.prefetch(pkg, Read.url(pkg), [a.sha1 for (v,a)=avail])) && continue - throw(PkgError("Can't find any registered versions of $pkg to checkout")) - end - finally - resolve() - end -end - -function pin(pkg::AbstractString, head::AbstractString) - ispath(pkg,".git") || throw(PkgError("$pkg is not a git repo")) - should_resolve = true - with(GitRepo, pkg) do repo - id = if isempty(head) # get HEAD commit - # no need to resolve, branch will be from HEAD - should_resolve = false - LibGit2.head_oid(repo) - else - LibGit2.revparseid(repo, head) - end - commit = LibGit2.GitCommit(repo, id) - try - # note: changing the following naming scheme requires a corresponding change in Read.ispinned() - branch = "pinned.$(string(id)[1:8]).tmp" - if LibGit2.isattached(repo) && LibGit2.branch(repo) == branch - info("Package $pkg is already pinned" * (isempty(head) ? "" : " to the selected commit")) - should_resolve = false - return - end - ref = LibGit2.lookup_branch(repo, branch) - try - if !isnull(ref) - if LibGit2.revparseid(repo, branch) != id - throw(PkgError("Package $pkg: existing branch $branch has " * - "been edited and doesn't correspond to its original commit")) - end - info("Package $pkg: checking out existing branch $branch") - else - info("Creating $pkg branch $branch") - ref = Nullable(LibGit2.create_branch(repo, branch, commit)) - end - - # checkout selected branch - with(LibGit2.peel(LibGit2.GitTree, get(ref))) do btree - LibGit2.checkout_tree(repo, btree) - end - # switch head to the branch - LibGit2.head!(repo, get(ref)) - finally - close(get(ref)) - end - finally - close(commit) - end - end - should_resolve && resolve() - nothing -end -pin(pkg::AbstractString) = pin(pkg, "") - -function pin(pkg::AbstractString, ver::VersionNumber) - ispath(pkg,".git") || throw(PkgError("$pkg is not a git repo")) - Read.isinstalled(pkg) || throw(PkgError("$pkg cannot be pinned – not an installed package")) - avail = Read.available(pkg) - isempty(avail) && throw(PkgError("$pkg cannot be pinned – not a registered package")) - haskey(avail,ver) || throw(PkgError("$pkg – $ver is not a registered version")) - pin(pkg, avail[ver].sha1) -end - -function update(branch::AbstractString, upkgs::Set{String}) - info("Updating METADATA...") - with(GitRepo, "METADATA") do repo - try - with(LibGit2.head(repo)) do h - if LibGit2.branch(h) != branch - if LibGit2.isdirty(repo) - throw(PkgError("METADATA is dirty and not on $branch, bailing")) - end - if !LibGit2.isattached(repo) - throw(PkgError("METADATA is detached not on $branch, bailing")) - end - LibGit2.fetch(repo) - LibGit2.checkout_head(repo) - LibGit2.branch!(repo, branch, track="refs/remotes/origin/$branch") - LibGit2.merge!(repo) - end - end - - LibGit2.fetch(repo) - ff_succeeded = LibGit2.merge!(repo, fastforward=true) - if !ff_succeeded - LibGit2.rebase!(repo, "origin/$branch") - end - catch err - cex = CapturedException(err, catch_backtrace()) - throw(PkgError("METADATA cannot be updated. Resolve problems manually in " * - Pkg.dir("METADATA") * ".", cex)) - end - end - deferred_errors = CompositeException() - avail = Read.available() - # this has to happen before computing free/fixed - for pkg in filter(Read.isinstalled, collect(keys(avail))) - try - Cache.prefetch(pkg, Read.url(pkg), [a.sha1 for (v,a)=avail[pkg]]) - catch err - cex = CapturedException(err, catch_backtrace()) - push!(deferred_errors, PkgError("Package $pkg: unable to update cache.", cex)) - end - end - instd = Read.installed(avail) - reqs = Reqs.parse("REQUIRE") - if !isempty(upkgs) - for (pkg, (v,f)) in instd - satisfies(pkg, v, reqs) || throw(PkgError("Package $pkg: current " * - "package status does not satisfy the requirements, cannot do " * - "a partial update; use `Pkg.update()`")) - end - end - dont_update = Query.partial_update_mask(instd, avail, upkgs) - free = Read.free(instd,dont_update) - for (pkg,ver) in free - try - Cache.prefetch(pkg, Read.url(pkg), [a.sha1 for (v,a)=avail[pkg]]) - catch err - cex = CapturedException(err, catch_backtrace()) - push!(deferred_errors, PkgError("Package $pkg: unable to update cache.", cex)) - end - end - fixed = Read.fixed(avail,instd,dont_update) - creds = LibGit2.CachedCredentials() - try - stopupdate = false - for (pkg,ver) in fixed - ispath(pkg,".git") || continue - pkg in dont_update && continue - with(GitRepo, pkg) do repo - if LibGit2.isattached(repo) - if LibGit2.isdirty(repo) - warn("Package $pkg: skipping update (dirty)...") - elseif Read.ispinned(repo) - info("Package $pkg: skipping update (pinned)...") - else - prev_sha = string(LibGit2.head_oid(repo)) - success = true - try - LibGit2.fetch(repo, payload = Nullable(creds)) - LibGit2.reset!(creds) - LibGit2.merge!(repo, fastforward=true) - catch err - cex = CapturedException(err, catch_backtrace()) - push!(deferred_errors, PkgError("Package $pkg cannot be updated.", cex)) - success = false - stopupdate = isa(err, InterruptException) - end - if success - post_sha = string(LibGit2.head_oid(repo)) - branch = LibGit2.branch(repo) - info("Updating $pkg $branch...", - prev_sha != post_sha ? " $(prev_sha[1:8]) → $(post_sha[1:8])" : "") - end - end - end - end - stopupdate && break - if haskey(avail,pkg) - try - Cache.prefetch(pkg, Read.url(pkg), [a.sha1 for (v,a)=avail[pkg]]) - catch err - cex = CapturedException(err, catch_backtrace()) - push!(deferred_errors, PkgError("Package $pkg: unable to update cache.", cex)) - end - end - end - finally - Base.securezero!(creds) - end - info("Computing changes...") - resolve(reqs, avail, instd, fixed, free, upkgs) - # Don't use instd here since it may have changed - updatehook(sort!(collect(keys(installed())))) - - # Print deferred errors - length(deferred_errors) > 0 && throw(PkgError("Update finished with errors.", deferred_errors)) - nothing -end - - -function resolve( - reqs :: Dict = Reqs.parse("REQUIRE"), - avail :: Dict = Read.available(), - instd :: Dict = Read.installed(avail), - fixed :: Dict = Read.fixed(avail, instd), - have :: Dict = Read.free(instd), - upkgs :: Set{String} = Set{String}() -) - bktrc = Query.init_resolve_backtrace(reqs, fixed) - orig_reqs = deepcopy(reqs) - Query.check_fixed(reqs, fixed, avail) - Query.propagate_fixed!(reqs, bktrc, fixed) - deps, conflicts = Query.dependencies(avail, fixed) - - for pkg in keys(reqs) - if !haskey(deps,pkg) - if "julia" in conflicts[pkg] - throw(PkgError("$pkg can't be installed because it has no versions that support $VERSION " * - "of julia. You may need to update METADATA by running `Pkg.update()`")) - else - sconflicts = join(conflicts[pkg], ", ", " and ") - throw(PkgError("$pkg's requirements can't be satisfied because " * - "of the following fixed packages: $sconflicts")) - end - end - end - - Query.check_requirements(reqs, deps, fixed) - - deps = Query.prune_dependencies(reqs, deps, bktrc) - want = Resolve.resolve(reqs, deps) - - if !isempty(upkgs) - orig_deps, _ = Query.dependencies(avail) - Query.check_partial_updates(orig_reqs, orig_deps, want, fixed, upkgs) - end - - # compare what is installed with what should be - changes = Query.diff(have, want, avail, fixed) - isempty(changes) && return info("No packages to install, update or remove") - - # prefetch phase isolates network activity, nothing to roll back - missing = [] - for (pkg,(ver1,ver2)) in changes - vers = String[] - ver1 !== nothing && push!(vers,LibGit2.head(pkg)) - ver2 !== nothing && push!(vers,Read.sha1(pkg,ver2)) - append!(missing, - map(sha1->(pkg,(ver1,ver2),sha1), - Cache.prefetch(pkg, Read.url(pkg), vers))) - end - if !isempty(missing) - msg = "Missing package versions (possible metadata misconfiguration):" - for (pkg,ver,sha1) in missing - msg *= " $pkg v$ver [$sha1[1:10]]\n" - end - throw(PkgError(msg)) - end - - # try applying changes, roll back everything if anything fails - changed = [] - imported = String[] - try - for (pkg,(ver1,ver2)) in changes - if ver1 === nothing - info("Installing $pkg v$ver2") - Write.install(pkg, Read.sha1(pkg,ver2)) - elseif ver2 === nothing - info("Removing $pkg v$ver1") - Write.remove(pkg) - else - up = ver1 <= ver2 ? "Up" : "Down" - info("$(up)grading $pkg: v$ver1 => v$ver2") - Write.update(pkg, Read.sha1(pkg,ver2)) - pkgsym = Symbol(pkg) - if Base.isbindingresolved(Main, pkgsym) && isa(getfield(Main, pkgsym), Module) - push!(imported, "- $pkg") - end - end - push!(changed,(pkg,(ver1,ver2))) - end - catch err - for (pkg,(ver1,ver2)) in reverse!(changed) - if ver1 === nothing - info("Rolling back install of $pkg") - @recover Write.remove(pkg) - elseif ver2 === nothing - info("Rolling back deleted $pkg to v$ver1") - @recover Write.install(pkg, Read.sha1(pkg,ver1)) - else - info("Rolling back $pkg from v$ver2 to v$ver1") - @recover Write.update(pkg, Read.sha1(pkg,ver1)) - end - end - rethrow(err) - end - if !isempty(imported) - warn(join(["The following packages have been updated but were already imported:", - imported..., "Restart Julia to use the updated versions."], "\n")) - end - # re/build all updated/installed packages - build(map(x->x[1], filter(x -> x[2][2] !== nothing, changes))) -end - -function warnbanner(msg...; label="[ WARNING ]", prefix="") - cols = Base.displaysize(STDERR)[2] - warn(prefix="", Base.cpad(label,cols,"=")) - println(STDERR) - warn(prefix=prefix, msg...) - println(STDERR) - warn(prefix="", "="^cols) -end - -function build(pkg::AbstractString, build_file::AbstractString, errfile::AbstractString) - # To isolate the build from the running Julia process, we execute each build.jl file in - # a separate process. Errors are serialized to errfile for later reporting. - # TODO: serialize the same way the load cache does, not with strings - LOAD_PATH = filter(x -> x isa AbstractString, Base.LOAD_PATH) - code = """ - empty!(Base.LOAD_PATH) - append!(Base.LOAD_PATH, $(repr(LOAD_PATH))) - empty!(Base.LOAD_CACHE_PATH) - append!(Base.LOAD_CACHE_PATH, $(repr(Base.LOAD_CACHE_PATH))) - empty!(Base.DL_LOAD_PATH) - append!(Base.DL_LOAD_PATH, $(repr(Base.DL_LOAD_PATH))) - open("$(escape_string(errfile))", "a") do f - pkg, build_file = "$pkg", "$(escape_string(build_file))" - try - info("Building \$pkg") - cd(dirname(build_file)) do - evalfile(build_file) - end - catch err - Base.Pkg.Entry.warnbanner(err, label="[ ERROR: \$pkg ]") - serialize(f, pkg) - serialize(f, err) - end - end - """ - cmd = ``` - $(Base.julia_cmd()) -O0 - --compilecache=$(Bool(Base.JLOptions().use_compilecache) ? "yes" : "no") - --history-file=no - --color=$(Base.have_color ? "yes" : "no") - --eval $code - ``` - - success(pipeline(cmd, stdout=STDOUT, stderr=STDERR)) -end - -function build!(pkgs::Vector, seen::Set, errfile::AbstractString) - for pkg in pkgs - pkg == "julia" && continue - pkg in seen ? continue : push!(seen,pkg) - Read.isinstalled(pkg) || throw(PkgError("$pkg is not an installed package")) - build!(Read.requires_list(pkg), seen, errfile) - path = abspath(pkg,"deps","build.jl") - isfile(path) || continue - build(pkg, path, errfile) || error("Build process failed.") - end -end - -function build!(pkgs::Vector, errs::Dict, seen::Set=Set()) - errfile = tempname() - touch(errfile) # create empty file - try - build!(pkgs, seen, errfile) - open(errfile, "r") do f - while !eof(f) - pkg = deserialize(f) - err = deserialize(f) - errs[pkg] = err - end - end - finally - isfile(errfile) && Base.rm(errfile) - end -end - -function build(pkgs::Vector) - errs = Dict() - build!(pkgs,errs) - isempty(errs) && return - println(STDERR) - warnbanner(label="[ BUILD ERRORS ]", """ - WARNING: $(join(keys(errs),", "," and ")) had build errors. - - - packages with build errors remain installed in $(pwd()) - - build the package(s) and all dependencies with `Pkg.build("$(join(keys(errs),"\", \""))")` - - build a single package by running its `deps/build.jl` script - """) -end -build() = build(sort!(collect(keys(installed())))) - -function updatehook!(pkgs::Vector, errs::Dict, seen::Set=Set()) - for pkg in pkgs - pkg in seen && continue - updatehook!(Read.requires_list(pkg),errs,push!(seen,pkg)) - path = abspath(pkg,"deps","update.jl") - isfile(path) || continue - info("Running update script for $pkg") - cd(dirname(path)) do - try evalfile(path) - catch err - warnbanner(err, label="[ ERROR: $pkg ]") - errs[pkg] = err - end - end - end -end - -function updatehook(pkgs::Vector) - errs = Dict() - updatehook!(pkgs,errs) - isempty(errs) && return - println(STDERR) - warnbanner(label="[ UPDATE ERRORS ]", """ - WARNING: $(join(keys(errs),", "," and ")) had update errors. - - - Unrelated packages are unaffected - - To retry, run Pkg.update() again - """) -end - -function test!(pkg::AbstractString, - errs::Vector{AbstractString}, - nopkgs::Vector{AbstractString}, - notests::Vector{AbstractString}; coverage::Bool=false) - reqs_path = abspath(pkg,"test","REQUIRE") - if isfile(reqs_path) - tests_require = Reqs.parse(reqs_path) - if (!isempty(tests_require)) - info("Computing test dependencies for $pkg...") - resolve(merge(Reqs.parse("REQUIRE"), tests_require)) - end - end - test_path = abspath(pkg,"test","runtests.jl") - if !isdir(pkg) - push!(nopkgs, pkg) - elseif !isfile(test_path) - push!(notests, pkg) - else - info("Testing $pkg") - cd(dirname(test_path)) do - try - color = Base.have_color? "--color=yes" : "--color=no" - codecov = coverage? ["--code-coverage=user"] : ["--code-coverage=none"] - compilecache = "--compilecache=" * (Bool(Base.JLOptions().use_compilecache) ? "yes" : "no") - julia_exe = Base.julia_cmd() - run(`$julia_exe --check-bounds=yes $codecov $color $compilecache $test_path`) - info("$pkg tests passed") - catch err - warnbanner(err, label="[ ERROR: $pkg ]") - push!(errs,pkg) - end - end - end - isfile(reqs_path) && resolve() -end - -mutable struct PkgTestError <: Exception - msg::String -end - -function Base.showerror(io::IO, ex::PkgTestError, bt; backtrace=true) - print_with_color(Base.error_color(), io, ex.msg) -end - -function test(pkgs::Vector{AbstractString}; coverage::Bool=false) - errs = AbstractString[] - nopkgs = AbstractString[] - notests = AbstractString[] - for pkg in pkgs - test!(pkg,errs,nopkgs,notests; coverage=coverage) - end - if !all(isempty, (errs, nopkgs, notests)) - messages = AbstractString[] - if !isempty(errs) - push!(messages, "$(join(errs,", "," and ")) had test errors") - end - if !isempty(nopkgs) - msg = length(nopkgs) > 1 ? " are not installed packages" : - " is not an installed package" - push!(messages, string(join(nopkgs,", ", " and "), msg)) - end - if !isempty(notests) - push!(messages, "$(join(notests,", "," and ")) did not provide a test/runtests.jl file") - end - throw(PkgTestError(join(messages, "and"))) - end -end - -test(;coverage::Bool=false) = test(sort!(AbstractString[keys(installed())...]); coverage=coverage) - -end # module diff --git a/julia-0.6.3/share/julia/base/pkg/pkg.jl b/julia-0.6.3/share/julia/base/pkg/pkg.jl deleted file mode 100644 index 2614c8d..0000000 --- a/julia-0.6.3/share/julia/base/pkg/pkg.jl +++ /dev/null @@ -1,319 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -""" - Pkg - -The `Pkg` module provides package management for Julia. -Use -`Pkg.status()` for a list of installed packages, -`Pkg.add("<pkg name>")` to add a package, -`Pkg.update()` to update the installed packages. - -Please see the manual section on packages for more information. -""" -module Pkg - -export Dir, Types, Reqs, Cache, Read, Query, Resolve, Write, Entry -export dir, init, rm, add, available, installed, status, clone, checkout, - update, resolve, test, build, free, pin, PkgError, setprotocol! - -const DEFAULT_META = "https://github.com/JuliaLang/METADATA.jl" -const META_BRANCH = "metadata-v2" - -mutable struct PkgError <: Exception - msg::AbstractString - ex::Nullable{Exception} -end -PkgError(msg::AbstractString) = PkgError(msg, Nullable{Exception}()) -function Base.showerror(io::IO, pkgerr::PkgError) - print(io, pkgerr.msg) - if !isnull(pkgerr.ex) - pkgex = get(pkgerr.ex) - if isa(pkgex, CompositeException) - for cex in pkgex - print(io, "\n=> ") - showerror(io, cex) - end - else - print(io, "\n") - showerror(io, pkgex) - end - end -end - -for file in split("dir types reqs cache read query resolve write entry") - include("$file.jl") -end -const cd = Dir.cd - -dir(path...) = Dir.path(path...) - -# remove extension .jl -const PKGEXT = ".jl" -splitjl(pkg::AbstractString) = endswith(pkg, PKGEXT) ? pkg[1:(end-length(PKGEXT))] : pkg - -""" - dir() -> AbstractString - -Returns the absolute path of the package directory. This defaults to -`joinpath(homedir(),".julia","v\$(VERSION.major).\$(VERSION.minor)")` on all platforms (i.e. -`~/.julia/v$(VERSION.major).$(VERSION.minor)` in UNIX shell syntax). If the `JULIA_PKGDIR` -environment variable is set, then that path is used in the returned value as -`joinpath(ENV["JULIA_PKGDIR"],"v\$(VERSION.major).\$(VERSION.minor)")`. If `JULIA_PKGDIR` is -a relative path, it is interpreted relative to whatever the current working directory is. -""" -dir() - -""" - dir(names...) -> AbstractString - -Equivalent to `normpath(Pkg.dir(),names...)` – i.e. it appends path components to the -package directory and normalizes the resulting path. In particular, `Pkg.dir(pkg)` returns -the path to the package `pkg`. -""" -dir(names...) - -""" - init(meta::AbstractString=DEFAULT_META, branch::AbstractString=META_BRANCH) - -Initialize `Pkg.dir()` as a package directory. This will be done automatically when the -`JULIA_PKGDIR` is not set and `Pkg.dir()` uses its default value. As part of this process, -clones a local METADATA git repository from the site and branch specified by its arguments, -which are typically not provided. Explicit (non-default) arguments can be used to support a -custom METADATA setup. -""" -init(meta::AbstractString=DEFAULT_META, branch::AbstractString=META_BRANCH) = Dir.init(meta,branch) - -function __init__() - vers = "v$(VERSION.major).$(VERSION.minor)" - vers = ccall(:jl_uses_cpuid_tag, Cint, ()) == 0 ? vers : - joinpath(vers,hex(ccall(:jl_cpuid_tag, UInt64, ()), 2*sizeof(UInt64))) - unshift!(Base.LOAD_CACHE_PATH, abspath(Dir._pkgroot(), "lib", vers)) -end - -""" - edit() - -Opens `Pkg.dir("REQUIRE")` in the editor specified by the `VISUAL` or `EDITOR` environment -variables; when the editor command returns, it runs `Pkg.resolve()` to determine and install -a new optimal set of installed package versions. -""" -edit() = cd(Entry.edit) - -""" - rm(pkg) - -Remove all requirement entries for `pkg` from `Pkg.dir("REQUIRE")` and call `Pkg.resolve()`. -""" -rm(pkg::AbstractString) = cd(Entry.rm,splitjl(pkg)) - -""" - add(pkg, vers...) - -Add a requirement entry for `pkg` to `Pkg.dir("REQUIRE")` and call `Pkg.resolve()`. If -`vers` are given, they must be `VersionNumber` objects and they specify acceptable version -intervals for `pkg`. -""" -add(pkg::AbstractString, vers::VersionNumber...) = cd(Entry.add,splitjl(pkg),vers...) - -""" - available() -> Vector{String} - -Returns the names of available packages. -""" -available() = cd(Entry.available) - -""" - available(pkg) -> Vector{VersionNumber} - -Returns the version numbers available for package `pkg`. -""" -available(pkg::AbstractString) = cd(Entry.available,splitjl(pkg)) - -""" - installed() -> Dict{String,VersionNumber} - -Returns a dictionary mapping installed package names to the installed version number of each -package. -""" -installed() = cd(Entry.installed) - -""" - installed(pkg) -> Void | VersionNumber - -If `pkg` is installed, return the installed version number. If `pkg` is registered, -but not installed, return `nothing`. -""" -installed(pkg::AbstractString) = cd(Entry.installed,splitjl(pkg)) - -""" - status() - -Prints out a summary of what packages are installed and what version and state they're in. -""" -status(io::IO=STDOUT) = cd(Entry.status,io) - -""" - status(pkg) - -Prints out a summary of what version and state `pkg`, specifically, is in. -""" -status(pkg::AbstractString, io::IO=STDOUT) = cd(Entry.status,io,splitjl(pkg)) - -""" - clone(pkg) - -If `pkg` has a URL registered in `Pkg.dir("METADATA")`, clone it from that URL on the -default branch. The package does not need to have any registered versions. -""" -clone(url_or_pkg::AbstractString) = cd(Entry.clone,url_or_pkg) - -""" - clone(url, [pkg]) - -Clone a package directly from the git URL `url`. The package does not need to be registered -in `Pkg.dir("METADATA")`. The package repo is cloned by the name `pkg` if provided; if not -provided, `pkg` is determined automatically from `url`. -""" -clone(url::AbstractString, pkg::AbstractString) = cd(Entry.clone,url,splitjl(pkg)) - -""" - checkout(pkg, [branch="master"]; merge=true, pull=true) - -Checkout the `Pkg.dir(pkg)` repo to the branch `branch`. Defaults to checking out the -"master" branch. To go back to using the newest compatible released version, use -`Pkg.free(pkg)`. Changes are merged (fast-forward only) if the keyword argument `merge == -true`, and the latest version is pulled from the upstream repo if `pull == true`. -""" -checkout(pkg::AbstractString, branch::AbstractString="master"; merge::Bool=true, pull::Bool=true) = - cd(Entry.checkout,splitjl(pkg),branch,merge,pull) - -""" - free(pkg) - -Free the package `pkg` to be managed by the package manager again. It calls `Pkg.resolve()` -to determine optimal package versions after. This is an inverse for both `Pkg.checkout` and -`Pkg.pin`. - -You can also supply an iterable collection of package names, e.g., `Pkg.free(("Pkg1", -"Pkg2"))` to free multiple packages at once. -""" -free(pkg) = cd(Entry.free,splitjl.(pkg)) - -""" - pin(pkg) - -Pin `pkg` at the current version. To go back to using the newest compatible released -version, use `Pkg.free(pkg)` -""" -pin(pkg::AbstractString) = cd(Entry.pin,splitjl(pkg)) - -""" - pin(pkg, version) - -Pin `pkg` at registered version `version`. -""" -pin(pkg::AbstractString, ver::VersionNumber) = cd(Entry.pin,splitjl(pkg),ver) - -""" - update(pkgs...) - -Update the metadata repo – kept in `Pkg.dir("METADATA")` – then update any fixed packages -that can safely be pulled from their origin; then call `Pkg.resolve()` to determine a new -optimal set of packages versions. - -Without arguments, updates all installed packages. When one or more package names are provided as -arguments, only those packages and their dependencies are updated. -""" -update(upkgs::AbstractString...) = cd(Entry.update,Dir.getmetabranch(),Set{String}(splitjl.([upkgs...]))) - -""" - resolve() - -Determines an optimal, consistent set of package versions to install or upgrade to. The -optimal set of package versions is based on the contents of `Pkg.dir("REQUIRE")` and the -state of installed packages in `Pkg.dir()`, Packages that are no longer required are moved -into `Pkg.dir(".trash")`. -""" -resolve() = cd(Entry.resolve) - -""" - build() - -Run the build scripts for all installed packages in depth-first recursive order. -""" -build() = cd(Entry.build) - -""" - build(pkgs...) - -Run the build script in `deps/build.jl` for each package in `pkgs` and all of their -dependencies in depth-first recursive order. This is called automatically by `Pkg.resolve()` -on all installed or updated packages. -""" -build(pkgs::AbstractString...) = cd(Entry.build,[splitjl.(pkgs)...]) - -""" - test(; coverage=false) - -Run the tests for all installed packages ensuring that each package's test dependencies are -installed for the duration of the test. A package is tested by running its -`test/runtests.jl` file and test dependencies are specified in `test/REQUIRE`. -Coverage statistics for the packages may be generated by passing `coverage=true`. -The default behavior is not to run coverage. -""" -test(;coverage::Bool=false) = cd(Entry.test; coverage=coverage) - -""" - test(pkgs...; coverage=false) - -Run the tests for each package in `pkgs` ensuring that each package's test dependencies are -installed for the duration of the test. A package is tested by running its -`test/runtests.jl` file and test dependencies are specified in `test/REQUIRE`. -Coverage statistics for the packages may be generated by passing `coverage=true`. -The default behavior is not to run coverage. -""" -test(pkgs::AbstractString...; coverage::Bool=false) = cd(Entry.test,AbstractString[splitjl.(pkgs)...]; coverage=coverage) - -""" - dependents(pkg) - -List the packages that have `pkg` as a dependency. -""" -dependents(pkg::AbstractString) = Reqs.dependents(splitjl(pkg)) - -""" - setprotocol!(proto) - -Set the protocol used to access GitHub-hosted packages. Defaults to 'https', with a blank -`proto` delegating the choice to the package developer. -""" -setprotocol!(proto::AbstractString) = Cache.setprotocol!(proto) - - -# point users to PkgDev -register(args...) = - error("Pkg.register(pkg,[url]) has been moved to the package PkgDev.jl.\n", - "Run Pkg.add(\"PkgDev\") to install PkgDev on Julia v0.5-") - -tag(pkg, ver=nothing, commit=nothing) = - error("Pkg.tag(pkg, [ver, [commit]]) has been moved to the package PkgDev.jl.\n", - "Run Pkg.add(\"PkgDev\") to install PkgDev on Julia v0.5-") - -publish() = - error("Pkg.publish() has been moved to the package PkgDev.jl.\n", - "Run Pkg.add(\"PkgDev\") to install PkgDev on Julia v0.5-") - -generate(pkg, license) = - error("Pkg.generate(pkg, license) has been moved to the package PkgDev.jl.\n", - "Run Pkg.add(\"PkgDev\") to install PkgDev on Julia v0.5-") - -license(lic=nothing) = - error("Pkg.license([lic]) has been moved to the package PkgDev.jl.\n", - "Run Pkg.add(\"PkgDev\") to install PkgDev on Julia v0.5-") - -submit(pkg, commit=nothing) = - error("Pkg.submit(pkg[, commit]) has been moved to the package PkgDev.jl.\n", - "Run Pkg.add(\"PkgDev\") to install PkgDev on Julia v0.5-") - -end # module diff --git a/julia-0.6.3/share/julia/base/pkg/query.jl b/julia-0.6.3/share/julia/base/pkg/query.jl deleted file mode 100644 index ec512b6..0000000 --- a/julia-0.6.3/share/julia/base/pkg/query.jl +++ /dev/null @@ -1,588 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -module Query - -import ...Pkg.PkgError -using ..Types - -function init_resolve_backtrace(reqs::Requires, fix::Dict{String,Fixed} = Dict{String,Fixed}()) - bktrc = ResolveBacktrace() - for (p,f) in fix - bktrc[p] = ResolveBacktraceItem(:fixed, f.version) - end - for (p,vs) in reqs - bktrcp = get!(bktrc, p) do; ResolveBacktraceItem() end - push!(bktrcp, :required, vs) - end - return bktrc -end - -function check_fixed(reqs::Requires, fix::Dict{String,Fixed}, avail::Dict) - for (p1,f1) in fix - for p2 in keys(f1.requires) - haskey(avail, p2) || haskey(fix, p2) || throw(PkgError("unknown package $p2 required by $p1")) - end - satisfies(p1, f1.version, reqs) || - warn("$p1 is fixed at $(f1.version) conflicting with top-level requirement: $(reqs[p1])") - for (p2,f2) in fix - satisfies(p1, f1.version, f2.requires) || - warn("$p1 is fixed at $(f1.version) conflicting with requirement for $p2: $(f2.requires[p1])") - end - end -end - -function propagate_fixed!(reqs::Requires, bktrc::ResolveBacktrace, fix::Dict{String,Fixed}) - for (p,f) in fix - merge_requires!(reqs, f.requires) - for (rp,rvs) in f.requires - bktrcp = get!(bktrc, rp) do; ResolveBacktraceItem() end - push!(bktrcp, p=>bktrc[p], rvs) - end - end - for (p,f) in fix - delete!(reqs, p) - end - reqs -end - -# Specialized copy for the avail argument below because the deepcopy is slow -function availcopy(avail) - new_avail = similar(avail) - for (pkg, vers_avail) in avail - new_vers_avail = similar(vers_avail) - for (version, pkg_avail) in vers_avail - new_vers_avail[version] = copy(pkg_avail) - end - new_avail[pkg] = new_vers_avail - end - return new_avail -end - -# Generate a reverse dependency graph (package names only) -function gen_backdeps(avail::Dict) - backdeps = Dict{String,Set{String}}() - for (ap,av) in avail, (v,a) in av, rp in keys(a.requires) - s = get!(backdeps, rp) do; Set{String}() end - push!(s, ap) - end - return backdeps -end - -function dependencies(avail::Dict, fix::Dict = Dict{String,Fixed}("julia"=>Fixed(VERSION))) - avail = availcopy(avail) - conflicts = Dict{String,Set{String}}() - to_expunge = VersionNumber[] - emptied = String[] - backdeps = gen_backdeps(avail) - - for (fp,fx) in fix - delete!(avail, fp) - haskey(backdeps, fp) || continue - # for (ap,av) in avail - for ap in backdeps[fp] - haskey(avail, ap) || continue - av = avail[ap] - empty!(to_expunge) - for (v,a) in av - if satisfies(fp, fx.version, a.requires) - delete!(a.requires, fp) - else - conflicts_ap = get!(conflicts, ap) do; Set{String}() end - push!(conflicts_ap, fp) - # don't delete v from av right away so as not to screw up iteration - push!(to_expunge, v) - end - end - for v in to_expunge - delete!(av, v) - end - isempty(av) && push!(emptied, ap) - end - end - while !isempty(emptied) - deleted_pkgs = String[] - for ap in emptied - delete!(avail, ap) - push!(deleted_pkgs, ap) - end - empty!(emptied) - - for dp in deleted_pkgs - haskey(backdeps, dp) || continue - for ap in backdeps[dp] - haskey(avail, ap) || continue - av = avail[ap] - empty!(to_expunge) - for (v,a) in av - haskey(a.requires, dp) || continue - conflicts_ap = get!(conflicts, ap) do; Set{String}() end - union!(conflicts_ap, conflicts[dp]) - push!(to_expunge, v) - end - for v in to_expunge - delete!(av, v) - end - isempty(av) && push!(emptied, ap) - end - end - end - avail, conflicts -end - -function partial_update_mask(instd::Dict{String,Tuple{VersionNumber,Bool}}, - avail::Dict{String,Dict{VersionNumber,Available}}, upkgs::Set{String}) - dont_update = Set{String}() - isempty(upkgs) && return dont_update - avail_new = deepcopy(avail) - for p in upkgs - haskey(instd, p) || throw(PkgError("Package $p is not installed")) - v = instd[p][1] - if haskey(avail, p) - for vn in keys(avail[p]) - vn < v && delete!(avail_new[p], vn) - end - end - end - avail_new = dependencies_subset(avail_new, upkgs) - - for p in keys(avail) - !haskey(avail_new, p) && push!(dont_update, p) - end - for p in keys(instd) - !haskey(avail_new, p) && p ∉ upkgs && push!(dont_update, p) - end - return dont_update -end - -# Try to produce some helpful message in case of a partial update which does not go all the way -# (Does not do a full analysis, it only checks requirements and direct dependents.) -function check_partial_updates(reqs::Requires, - deps::Dict{String,Dict{VersionNumber,Available}}, - want::Dict{String,VersionNumber}, - fixed::Dict{String,Fixed}, - upkgs::Set{String}) - for p in upkgs - if !haskey(want, p) - if !haskey(fixed, p) - warn("Something went wrong with the update of package $p, please submit a bug report") - continue - end - v = fixed[p].version - else - v = want[p] - if haskey(fixed, p) && v != fixed[p].version - warn("Something went wrong with the update of package $p, please submit a bug report") - continue - end - end - haskey(deps, p) || continue - vers = sort!(collect(keys(deps[p]))) - higher_vers = vers[vers .> v] - isempty(higher_vers) && continue # package p has been set to the highest available version - - # Determine if there are packages which depend on `p` and somehow prevent its update to - # the latest version - blocking_parents = Set{String}() - for (p1,d1) in deps - p1 in upkgs && continue # package `p1` is among the ones to be updated, skip the check - haskey(fixed, p1) || continue # if package `p1` is not fixed, it can't be blocking - r1 = fixed[p1].requires # get `p1` requirements - haskey(r1, p) || continue # check if package `p1` requires `p` - vs1 = r1[p] # get the versions of `p` allowed by `p1` requirements - any(hv in vs1 for hv in higher_vers) && continue # package `p1` would allow some of the higher versions, - # therefore it's not responsible for blocking `p` - push!(blocking_parents, p1) # package `p1` is blocking the update of `p` - end - - # Determine if the update of `p` is prevented by explicit user-provided requirements - blocking_reqs = (haskey(reqs, p) && all(hv ∉ reqs[p] for hv in higher_vers)) - - # Determine if the update of `p` is prevented by it being fixed (e.g. it's dirty, or pinned...) - isfixed = haskey(fixed, p) - - msg = "Package $p was set to version $v, but a higher version $(vers[end]) exists.\n" - if isfixed - msg *= " The package is fixed. You can try using `Pkg.free(\"$p\")` to update it." - elseif blocking_reqs - msg *= " The update is prevented by explicit requirements constraints. Edit your REQUIRE file to change this." - elseif !isempty(blocking_parents) - msg *= string(" To install the latest version, you could try updating these packages as well: ", join(blocking_parents, ", ", " and "), ".") - else - msg *= " To install the latest version, you could try doing a full update with `Pkg.update()`." - end - info(msg) - end -end - -const PackageState = Union{Void,VersionNumber} - -function diff(have::Dict, want::Dict, avail::Dict, fixed::Dict) - change = Vector{Tuple{String,Tuple{PackageState,PackageState}}}(0) - remove = Vector{Tuple{String,Tuple{PackageState,PackageState}}}(0) - - for pkg in collect(union(keys(have),keys(want))) - h, w = haskey(have,pkg), haskey(want,pkg) - if h && w - if have[pkg] != want[pkg] - push!(change, (pkg,(have[pkg], want[pkg]))) - end - elseif h - push!(remove, (pkg,(have[pkg],nothing))) - elseif w - push!(change, (pkg,(nothing,want[pkg]))) - end - end - append!(sort!(change), sort!(remove)) -end - -function check_requirements(reqs::Requires, deps::Dict{String,Dict{VersionNumber,Available}}, fix::Dict) - for (p,vs) in reqs - if !any(vn->(vn in vs), keys(deps[p])) - remaining_vs = VersionSet() - err_msg = "fixed packages introduce conflicting requirements for $p: \n" - available_list = sort!(collect(keys(deps[p]))) - for (p1,f1) in fix - f1r = f1.requires - haskey(f1r, p) || continue - err_msg *= " $p1 requires versions $(f1r[p])" - if !any([vn in f1r[p] for vn in available_list]) - err_msg *= " [none of the available versions can satisfy this requirement]" - end - err_msg *= "\n" - remaining_vs = intersect(remaining_vs, f1r[p]) - end - if isempty(remaining_vs) - err_msg *= " the requirements are unsatisfiable because their intersection is empty" - else - err_msg *= " available versions are $(join(available_list, ", ", " and "))" - end - throw(PkgError(err_msg)) - end - end -end - -# If there are explicitly required packages, dicards all versions outside -# the allowed range. -# It also propagates requirements: when all allowed versions of a required package -# require some other package, this creates a new implicit requirement. -# The propagation is tracked so that in case a contradiction is detected the error -# message allows to determine the cause. -# This is a pre-pruning step, so it also creates some structures which are later used by pruning -function filter_versions(reqs::Requires, deps::Dict{String,Dict{VersionNumber,Available}}, bktrc::ResolveBacktrace) - allowed = Dict{String,Dict{VersionNumber,Bool}}() - staged = copy(reqs) - while !isempty(staged) - staged_next = Requires() - for (p,vs) in staged - # Parse requirements and store allowed versions. - depsp = deps[p] - if !haskey(allowed, p) - allowedp = Dict{VersionNumber,Bool}(vn=>true for vn in keys(depsp)) - allowed[p] = allowedp - seen = false - else - allowedp = allowed[p] - oldallowedp = copy(allowedp) - seen = true - end - for vn in keys(depsp) - allowedp[vn] &= vn ∈ vs - end - @assert !isempty(allowedp) - if !any(values(allowedp)) - err_msg = "Unsatisfiable requirements detected for package $p:\n" - err_msg *= string(bktrc[p]) - err_msg *= """The intersection of the requirements is $(bktrc[p].versionreq). - None of the available versions can satisfy this requirement.""" - throw(PkgError(err_msg)) - end - - # If we've seen this package already and nothing has changed since - # the last time, we stop here. - seen && allowedp == oldallowedp && continue - - # Propagate requirements: - # if all allowed versions of a required package require some other package, - # then compute the union of the allowed versions for that other package, and - # treat that as a new requirement. - # Start by filtering out the non-allowed versions - fdepsp = Dict{VersionNumber,Available}(vn=>depsp[vn] for vn in keys(depsp) if allowedp[vn]) - # Collect all required packages - isreq = Dict{String,Bool}(rp=>true for a in values(fdepsp) for rp in keys(a.requires)) - # Compute whether a required package appears in all requirements - for rp in keys(isreq) - isreq[rp] = all(haskey(a.requires, rp) for a in values(fdepsp)) - end - - # Create a list of candidates for new implicit requirements - staged_new = Set{String}() - for a in values(fdepsp), (rp,rvs) in a.requires - # Skip packages that may not be required - isreq[rp] || continue - # Compute the union of the version sets - if haskey(staged_next, rp) - snvs = staged_next[rp] - union!(snvs, rvs) - else - snvs = copy(rvs) - staged_next[rp] = snvs - end - push!(staged_new, rp) - end - for rp in staged_new - @assert isreq[rp] - srvs = staged_next[rp] - bktrcp = get!(bktrc, rp) do; ResolveBacktraceItem(); end - push!(bktrcp, p=>bktrc[p], srvs) - if isa(bktrcp.versionreq, VersionSet) && isempty(bktrcp.versionreq) - err_msg = "Unsatisfiable requirements detected for package $rp:\n" - err_msg *= string(bktrcp) - err_msg *= "The intersection of the requirements is empty." - throw(PkgError(err_msg)) - end - end - end - staged = staged_next - end - - filtered_deps = Dict{String,Dict{VersionNumber,Available}}() - for (p,depsp) in deps - filtered_deps[p] = Dict{VersionNumber,Available}() - allowedp = get(allowed, p) do; Dict{VersionNumber,Bool}() end - fdepsp = filtered_deps[p] - for (vn,a) in depsp - get(allowedp, vn, true) || continue - fdepsp[vn] = a - end - end - - return filtered_deps, allowed -end - -# Reduce the number of versions by creating equivalence classes, and retaining -# only the highest version for each equivalence class. -# Two versions are equivalent if: -# 1) They appear together as dependecies of another package (i.e. for each -# dependency relation, they are both required or both not required) -# 2) They have the same dependencies -# Preliminarily calls filter_versions. -function prune_versions(reqs::Requires, deps::Dict{String,Dict{VersionNumber,Available}}, bktrc::ResolveBacktrace) - filtered_deps, allowed = filter_versions(reqs, deps, bktrc) - if !isempty(reqs) - filtered_deps = dependencies_subset(filtered_deps, Set{String}(keys(reqs))) - end - - # To each version in each package, we associate a BitVector. - # It is going to hold a pattern such that all versions with - # the same pattern are equivalent. - vmask = Dict{String,Dict{VersionNumber, BitVector}}() - - # For each package, we examine the dependencies of its versions - # and put together those which are equal. - # While we're at it, we also collect all dependencies into alldeps - alldeps = Dict{String,Set{VersionSet}}() - for (p,fdepsp) in filtered_deps - # Extract unique dependencies lists (aka classes), thereby - # assigning an index to each class. - uniqdepssets = unique(a.requires for a in values(fdepsp)) - - # Store all dependencies seen so far for later use - for r in uniqdepssets, (rp,rvs) in r - get!(alldeps, rp) do; Set{VersionSet}() end - push!(alldeps[rp], rvs) - end - - # If the package has just one version, it's uninteresting - length(deps[p]) == 1 && continue - - # Grow the pattern by the number of classes - luds = length(uniqdepssets) - @assert !haskey(vmask, p) - vmask[p] = Dict{VersionNumber,BitVector}() - vmaskp = vmask[p] - for vn in keys(fdepsp) - vmaskp[vn] = falses(luds) - end - for (vn,a) in fdepsp - vmind = findfirst(uniqdepssets, a.requires) - @assert vmind > 0 - vm = vmaskp[vn] - vm[vmind] = true - end - end - - # Produce dependency patterns. - for (p,vss) in alldeps, vs in vss - # packages with just one version, or dependencies - # which do not distiguish between versions, are not - # interesting - (length(deps[p]) == 1 || vs == VersionSet()) && continue - - # Store the dependency info in the patterns - @assert haskey(vmask, p) - for (vn,vm) in vmask[p] - push!(vm, vn in vs) - end - end - - # At this point, the vmask patterns are computed. We divide them into - # classes so that we can keep just one version for each class. - pruned_vers = Dict{String,Vector{VersionNumber}}() - eq_classes = Dict{String,Dict{VersionNumber,Vector{VersionNumber}}}() - for (p, vmaskp) in vmask - vmask0_uniq = unique(values(vmaskp)) - nc = length(vmask0_uniq) - classes = [VersionNumber[] for c0 = 1:nc] - for (vn,vm) in vmaskp - c0 = findfirst(vmask0_uniq, vm) - push!(classes[c0], vn) - end - map(sort!, classes) - - # For each nonempty class, we store only the highest version) - pruned_vers[p] = VersionNumber[] - prunedp = pruned_vers[p] - eq_classes[p] = Dict{VersionNumber,Vector{VersionNumber}}() - eqclassp = eq_classes[p] - for cl in classes - if !isempty(cl) - vtop = maximum(cl) - push!(prunedp, vtop) - @assert !haskey(eqclassp, vtop) - eqclassp[vtop] = cl - end - end - sort!(prunedp) - end - # Put non-allowed versions into eq_classes - for (p, allowedp) in allowed - haskey(eq_classes, p) || continue - eqclassp = eq_classes[p] - for (vn, a) in allowedp - a && continue - eqclassp[vn] = [vn] - end - end - # Put all remaining packages into eq_classes - for (p, depsp) in deps - haskey(eq_classes, p) && continue - eq_classes[p] = Dict{VersionNumber,Vector{VersionNumber}}() - eqclassp = eq_classes[p] - for vn in keys(depsp) - eqclassp[vn] = [vn] - end - end - - - # Recompute deps. We could simplify them, but it's not worth it - new_deps = Dict{String,Dict{VersionNumber,Available}}() - - for (p,depsp) in filtered_deps - @assert !haskey(new_deps, p) - if !haskey(pruned_vers, p) - new_deps[p] = depsp - continue - end - new_deps[p] = Dict{VersionNumber,Available}() - pruned_versp = pruned_vers[p] - for (vn,a) in depsp - vn ∈ pruned_versp || continue - new_deps[p][vn] = a - end - end - - #println("pruning stats:") - #numvers = 0 - #numdeps = 0 - #for (p,d) in deps, (vn,a) in d - # numvers += 1 - # for r in a.requires - # numdeps += 1 - # end - #end - #numnewvers = 0 - #numnewdeps = 0 - #for (p,d) in new_deps, (vn,a) in d - # numnewvers += 1 - # for r in a.requires - # numnewdeps += 1 - # end - #end - #println(" before: vers=$numvers deps=$numdeps") - #println(" after: vers=$numnewvers deps=$numnewdeps") - #println() - - return new_deps, eq_classes -end -prune_versions(deps::Dict{String,Dict{VersionNumber,Available}}) = - prune_versions(Dict{String,VersionSet}(), deps, ResolveBacktrace()) -prune_versions(deps::Dict{String,Dict{VersionNumber,Available}}, bktrc::ResolveBacktrace) = - prune_versions(Dict{String,VersionSet}(), deps, bktrc) - -# Build a graph restricted to a subset of the packages -function subdeps(deps::Dict{String,Dict{VersionNumber,Available}}, pkgs::Set{String}) - sub_deps = Dict{String,Dict{VersionNumber,Available}}() - for p in pkgs - haskey(sub_deps, p) || (sub_deps[p] = Dict{VersionNumber,Available}()) - sub_depsp = sub_deps[p] - for (vn,a) in deps[p] - sub_depsp[vn] = a - end - end - - return sub_deps -end - -# Build a subgraph incuding only the (direct and indirect) dependencies -# of a given package set -function dependencies_subset(deps::Dict{String,Dict{VersionNumber,Available}}, pkgs::Set{String}) - staged::Set{String} = filter(p->p in keys(deps), pkgs) - allpkgs = copy(staged) - while !isempty(staged) - staged_next = Set{String}() - for p in staged, a in values(get(deps, p, Dict{VersionNumber,Available}())), rp in keys(a.requires) - rp ∉ allpkgs && rp ≠ "julia" && push!(staged_next, rp) - end - union!(allpkgs, staged_next) - staged = staged_next - end - - return subdeps(deps, allpkgs) -end - -# Build a subgraph incuding only the (direct and indirect) dependencies and dependants -# of a given package set -function undirected_dependencies_subset(deps::Dict{String,Dict{VersionNumber,Available}}, pkgs::Set{String}) - graph = Dict{String, Set{String}}() - - for (p,d) in deps - haskey(graph, p) || (graph[p] = Set{String}()) - for a in values(d), rp in keys(a.requires) - push!(graph[p], rp) - haskey(graph, rp) || (graph[rp] = Set{String}()) - push!(graph[rp], p) - end - end - - staged = pkgs - allpkgs = copy(pkgs) - while !isempty(staged) - staged_next = Set{String}() - for p in staged, rp in graph[p] - rp ∉ allpkgs && push!(staged_next, rp) - end - union!(allpkgs, staged_next) - staged = staged_next - end - - return subdeps(deps, allpkgs) -end - -function prune_dependencies(reqs::Requires, - deps::Dict{String,Dict{VersionNumber,Available}}, - bktrc::ResolveBacktrace = init_resolve_backtrace(reqs)) - deps, _ = prune_versions(reqs, deps, bktrc) - return deps -end - -end # module diff --git a/julia-0.6.3/share/julia/base/pkg/read.jl b/julia-0.6.3/share/julia/base/pkg/read.jl deleted file mode 100644 index dc4046f..0000000 --- a/julia-0.6.3/share/julia/base/pkg/read.jl +++ /dev/null @@ -1,251 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -module Read - -import ...LibGit2, ..Cache, ..Reqs, ...Pkg.PkgError, ..Dir -using ..Types - -readstrip(path...) = strip(readstring(joinpath(path...))) - -url(pkg::AbstractString) = readstrip(Dir.path("METADATA"), pkg, "url") -sha1(pkg::AbstractString, ver::VersionNumber) = - readstrip(Dir.path("METADATA"), pkg, "versions", string(ver), "sha1") - -function available(names=readdir("METADATA")) - pkgs = Dict{String,Dict{VersionNumber,Available}}() - for pkg in names - isfile("METADATA", pkg, "url") || continue - versdir = joinpath("METADATA", pkg, "versions") - isdir(versdir) || continue - for ver in readdir(versdir) - ismatch(Base.VERSION_REGEX, ver) || continue - isfile(versdir, ver, "sha1") || continue - haskey(pkgs,pkg) || (pkgs[pkg] = Dict{VersionNumber,Available}()) - pkgs[pkg][convert(VersionNumber,ver)] = Available( - readchomp(joinpath(versdir,ver,"sha1")), - Reqs.parse(joinpath(versdir,ver,"requires")) - ) - end - end - return pkgs -end -available(pkg::AbstractString) = get(available([pkg]),pkg,Dict{VersionNumber,Available}()) - -function latest(names=readdir("METADATA")) - pkgs = Dict{String,Available}() - for pkg in names - isfile("METADATA", pkg, "url") || continue - versdir = joinpath("METADATA", pkg, "versions") - isdir(versdir) || continue - pkgversions = VersionNumber[] - for ver in readdir(versdir) - ismatch(Base.VERSION_REGEX, ver) || continue - isfile(versdir, ver, "sha1") || continue - push!(pkgversions, convert(VersionNumber,ver)) - end - isempty(pkgversions) && continue - ver = string(maximum(pkgversions)) - pkgs[pkg] = Available( - readchomp(joinpath(versdir,ver,"sha1")), - Reqs.parse(joinpath(versdir,ver,"requires")) - ) - end - return pkgs -end - -isinstalled(pkg::AbstractString) = - pkg != "METADATA" && pkg != "REQUIRE" && pkg[1] != '.' && isdir(pkg) - -function isfixed(pkg::AbstractString, prepo::LibGit2.GitRepo, avail::Dict=available(pkg)) - isinstalled(pkg) || throw(PkgError("$pkg is not an installed package.")) - isfile("METADATA", pkg, "url") || return true - ispath(pkg, ".git") || return true - - LibGit2.isdirty(prepo) && return true - LibGit2.isattached(prepo) && return true - LibGit2.need_update(prepo) - if isnull(find("REQUIRE", LibGit2.GitIndex(prepo))) - isfile(pkg,"REQUIRE") && return true - end - head = string(LibGit2.head_oid(prepo)) - for (ver,info) in avail - head == info.sha1 && return false - end - - cache = Cache.path(pkg) - cache_has_head = if isdir(cache) - crepo = LibGit2.GitRepo(cache) - LibGit2.iscommit(head, crepo) - else - false - end - res = true - try - for (ver,info) in avail - if cache_has_head && LibGit2.iscommit(info.sha1, crepo) - if LibGit2.is_ancestor_of(head, info.sha1, crepo) - res = false - break - end - elseif LibGit2.iscommit(info.sha1, prepo) - if LibGit2.is_ancestor_of(head, info.sha1, prepo) - res = false - break - end - else - Base.warn_once("unknown $pkg commit $(info.sha1[1:8]), metadata may be ahead of package cache") - end - end - finally - cache_has_head && LibGit2.close(crepo) - end - return res -end - -function ispinned(pkg::AbstractString) - ispath(pkg,".git") || return false - LibGit2.with(LibGit2.GitRepo, pkg) do repo - return ispinned(repo) - end -end - -function ispinned(prepo::LibGit2.GitRepo) - LibGit2.isattached(prepo) || return false - br = LibGit2.branch(prepo) - # note: regex is based on the naming scheme used in Entry.pin() - return ismatch(r"^pinned\.[0-9a-f]{8}\.tmp$", br) -end - -function installed_version(pkg::AbstractString, prepo::LibGit2.GitRepo, avail::Dict=available(pkg)) - ispath(pkg,".git") || return typemin(VersionNumber) - - # get package repo head hash - local head - try - head = string(LibGit2.head_oid(prepo)) - catch ex - # refs/heads/master does not exist - if isa(ex,LibGit2.GitError) && - ex.code == LibGit2.Error.EUNBORNBRANCH - head = "" - else - rethrow(ex) - end - end - isempty(head) && return typemin(VersionNumber) - - vers = collect(keys(filter((ver,info)->info.sha1==head, avail))) - !isempty(vers) && return maximum(vers) - - cache = Cache.path(pkg) - cache_has_head = if isdir(cache) - crepo = LibGit2.GitRepo(cache) - LibGit2.iscommit(head, crepo) - else - false - end - ancestors = VersionNumber[] - descendants = VersionNumber[] - try - for (ver,info) in avail - sha1 = info.sha1 - base = if cache_has_head && LibGit2.iscommit(sha1, crepo) - LibGit2.merge_base(crepo, head, sha1) - elseif LibGit2.iscommit(sha1, prepo) - LibGit2.merge_base(prepo, head, sha1) - else - Base.warn_once("unknown $pkg commit $(sha1[1:8]), metadata may be ahead of package cache") - continue - end - string(base) == sha1 && push!(ancestors,ver) - string(base) == head && push!(descendants,ver) - end - finally - cache_has_head && LibGit2.close(crepo) - end - both = sort!(intersect(ancestors,descendants)) - isempty(both) || warn("$pkg: some versions are both ancestors and descendants of head: $both") - if !isempty(descendants) - v = minimum(descendants) - return VersionNumber(v.major, v.minor, v.patch, ("",), ()) - elseif !isempty(ancestors) - v = maximum(ancestors) - return VersionNumber(v.major, v.minor, v.patch, (), ("",)) - else - return typemin(VersionNumber) - end -end - -function requires_path(pkg::AbstractString, avail::Dict=available(pkg)) - pkgreq = joinpath(pkg,"REQUIRE") - ispath(pkg,".git") || return pkgreq - repo = LibGit2.GitRepo(pkg) - head = LibGit2.with(LibGit2.GitRepo, pkg) do repo - LibGit2.isdirty(repo, "REQUIRE") && return pkgreq - LibGit2.need_update(repo) - if isnull(find("REQUIRE", LibGit2.GitIndex(repo))) - isfile(pkgreq) && return pkgreq - end - string(LibGit2.head_oid(repo)) - end - for (ver,info) in avail - if head == info.sha1 - return joinpath("METADATA", pkg, "versions", string(ver), "requires") - end - end - return pkgreq -end - -requires_list(pkg::AbstractString, avail::Dict=available(pkg)) = - collect(keys(Reqs.parse(requires_path(pkg,avail)))) - -requires_dict(pkg::AbstractString, avail::Dict=available(pkg)) = - Reqs.parse(requires_path(pkg,avail)) - -function installed(avail::Dict=available()) - pkgs = Dict{String,Tuple{VersionNumber,Bool}}() - for pkg in readdir() - isinstalled(pkg) || continue - ap = get(avail,pkg,Dict{VersionNumber,Available}()) - if ispath(pkg,".git") - LibGit2.with(LibGit2.GitRepo, pkg) do repo - ver = installed_version(pkg, repo, ap) - fixed = isfixed(pkg, repo, ap) - pkgs[pkg] = (ver, fixed) - end - else - pkgs[pkg] = (typemin(VersionNumber), true) - end - end - return pkgs -end - -function fixed(avail::Dict=available(), inst::Dict=installed(avail), dont_update::Set{String}=Set{String}(), - julia_version::VersionNumber=VERSION) - pkgs = Dict{String,Fixed}() - for (pkg,(ver,fix)) in inst - (fix || pkg in dont_update) || continue - ap = get(avail,pkg,Dict{VersionNumber,Available}()) - pkgs[pkg] = Fixed(ver,requires_dict(pkg,ap)) - end - pkgs["julia"] = Fixed(julia_version) - return pkgs -end - -function free(inst::Dict=installed(), dont_update::Set{String}=Set{String}()) - pkgs = Dict{String,VersionNumber}() - for (pkg,(ver,fix)) in inst - (fix || pkg in dont_update) && continue - pkgs[pkg] = ver - end - return pkgs -end - -function issue_url(pkg::AbstractString) - ispath(pkg,".git") || return "" - m = match(LibGit2.GITHUB_REGEX, url(pkg)) - m === nothing && return "" - return "https://github.com/" * m.captures[1] * "/issues" -end - -end # module diff --git a/julia-0.6.3/share/julia/base/pkg/reqs.jl b/julia-0.6.3/share/julia/base/pkg/reqs.jl deleted file mode 100644 index 286f64d..0000000 --- a/julia-0.6.3/share/julia/base/pkg/reqs.jl +++ /dev/null @@ -1,145 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -module Reqs - -import Base: == -import ...Pkg.PkgError -using ..Types - -# representing lines of REQUIRE files - -abstract type Line end -struct Comment <: Line - content::AbstractString -end -struct Requirement <: Line - content::AbstractString - package::AbstractString - versions::VersionSet - system::Vector{AbstractString} - - function Requirement(content::AbstractString) - fields = split(replace(content, r"#.*$", "")) - system = AbstractString[] - while !isempty(fields) && fields[1][1] == '@' - push!(system,shift!(fields)[2:end]) - end - isempty(fields) && throw(PkgError("invalid requires entry: $content")) - package = shift!(fields) - all(field->ismatch(Base.VERSION_REGEX, field), fields) || - throw(PkgError("invalid requires entry for $package: $content")) - versions = VersionNumber[fields...] - issorted(versions) || throw(PkgError("invalid requires entry for $package: $content")) - new(content, package, VersionSet(versions), system) - end - function Requirement(package::AbstractString, versions::VersionSet, system::Vector{AbstractString}=AbstractString[]) - content = "" - for os in system - content *= "@$os " - end - content *= package - if versions != VersionSet() - for ival in versions.intervals - (content *= " $(ival.lower)") - ival.upper < typemax(VersionNumber) && - (content *= " $(ival.upper)") - end - end - new(content, package, versions, system) - end -end - -==(a::Line, b::Line) = a.content == b.content -hash(s::Line, h::UInt) = hash(s.content, h + (0x3f5a631add21cb1a % UInt)) - -# general machinery for parsing REQUIRE files - -function read(readable::Vector{<:AbstractString}) - lines = Line[] - for line in readable - line = chomp(line) - push!(lines, ismatch(r"^\s*(?:#|$)", line) ? Comment(line) : Requirement(line)) - end - return lines -end - -function read(readable::Union{IO,Base.AbstractCmd}) - lines = Line[] - for line in eachline(readable) - push!(lines, ismatch(r"^\s*(?:#|$)", line) ? Comment(line) : Requirement(line)) - end - return lines -end -read(file::AbstractString) = isfile(file) ? open(read,file) : Line[] - -function write(io::IO, lines::Vector{Line}) - for line in lines - println(io, line.content) - end -end -function write(io::IO, reqs::Requires) - for pkg in sort!(collect(keys(reqs)), by=lowercase) - println(io, Requirement(pkg, reqs[pkg]).content) - end -end -write(file::AbstractString, r::Union{Vector{Line},Requires}) = open(io->write(io,r), file, "w") - -function parse(lines::Vector{Line}) - reqs = Requires() - for line in lines - if isa(line,Requirement) - if !isempty(line.system) - applies = false - if is_windows(); applies |= ("windows" in line.system); end - if is_unix(); applies |= ("unix" in line.system); end - if is_apple(); applies |= ("osx" in line.system); end - if is_linux(); applies |= ("linux" in line.system); end - if is_bsd(); applies |= ("bsd" in line.system); end - if is_windows(); applies &= !("!windows" in line.system); end - if is_unix(); applies &= !("!unix" in line.system); end - if is_apple(); applies &= !("!osx" in line.system); end - if is_linux(); applies &= !("!linux" in line.system); end - if is_bsd(); applies &= !("!bsd" in line.system); end - applies || continue - end - reqs[line.package] = haskey(reqs, line.package) ? - intersect(reqs[line.package], line.versions) : line.versions - end - end - return reqs -end -parse(x) = parse(read(x)) - -function dependents(packagename::AbstractString) - pkgs = AbstractString[] - cd(Pkg.dir()) do - for (pkg,latest) in Pkg.Read.latest() - if haskey(latest.requires, packagename) - push!(pkgs, pkg) - end - end - end - pkgs -end - -# add & rm – edit the content a requires file - -function add(lines::Vector{Line}, pkg::AbstractString, versions::VersionSet=VersionSet()) - v = VersionSet[] - filtered = filter(lines) do line - if !isa(line,Comment) && line.package == pkg && isempty(line.system) - push!(v, line.versions) - return false - end - return true - end - length(v) == 1 && v[1] == intersect(v[1],versions) && return copy(lines) - versions = reduce(intersect, versions, v) - push!(filtered, Requirement(pkg, versions)) -end - -rm(lines::Vector{Line}, pkg::AbstractString) = filter(lines) do line - isa(line,Comment) || line.package != pkg -end - -end # module diff --git a/julia-0.6.3/share/julia/base/pkg/resolve.jl b/julia-0.6.3/share/julia/base/pkg/resolve.jl deleted file mode 100644 index c6c20c7..0000000 --- a/julia-0.6.3/share/julia/base/pkg/resolve.jl +++ /dev/null @@ -1,164 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -module Resolve - -include(joinpath("resolve", "versionweight.jl")) -include(joinpath("resolve", "interface.jl")) -include(joinpath("resolve", "maxsum.jl")) - -using ..Types, ..Query, .PkgToMaxSumInterface, .MaxSum -import ...Pkg.PkgError - -export resolve, sanity_check - -# Use the max-sum algorithm to resolve packages dependencies -function resolve(reqs::Requires, deps::Dict{String,Dict{VersionNumber,Available}}) - # init interface structures - interface = Interface(reqs, deps) - - # attempt trivial solution first - ok, sol = greedysolver(interface) - if !ok - # trivial solution failed, use maxsum solver - graph = Graph(interface) - msgs = Messages(interface, graph) - - try - sol = maxsum(graph, msgs) - catch err - isa(err, UnsatError) || rethrow(err) - p = interface.pkgs[err.info] - # TODO: build tools to analyze the problem, and suggest to use them here. - msg = - """ - resolve is unable to satisfy package requirements. - The problem was detected when trying to find a feasible version - for package $p. - However, this only means that package $p is involved in an - unsatisfiable or difficult dependency relation, and the root of - the problem may be elsewhere. - """ - if msgs.num_nondecimated != graph.np - msg *= """ - (you may try increasing the value of the JULIA_PKGRESOLVE_ACCURACY - environment variable) - """ - end - ## info("ERROR MESSAGE:\n" * msg) - throw(PkgError(msg)) - end - - # verify solution (debug code) and enforce its optimality - @assert verify_solution(sol, interface) - enforce_optimality!(sol, interface) - @assert verify_solution(sol, interface) - end - - # return the solution as a Dict mapping package_name => sha1 - return compute_output_dict(sol, interface) -end - -# Scan dependencies for (explicit or implicit) contradictions -function sanity_check(deps::Dict{String,Dict{VersionNumber,Available}}, - pkgs::Set{String} = Set{String}()) - isempty(pkgs) || (deps = Query.undirected_dependencies_subset(deps, pkgs)) - - deps, eq_classes = Query.prune_versions(deps) - - ndeps = Dict{String,Dict{VersionNumber,Int}}() - - for (p,depsp) in deps - ndeps[p] = ndepsp = Dict{VersionNumber,Int}() - for (vn,a) in depsp - ndepsp[vn] = length(a.requires) - end - end - - vers = [(p,vn) for (p,d) in deps for vn in keys(d)] - sort!(vers, by=pvn->(-ndeps[pvn[1]][pvn[2]])) - - nv = length(vers) - - svdict = Dict{Tuple{String,VersionNumber},Int}(vers[i][1:2]=>i for i = 1:nv) - - checked = falses(nv) - - problematic = Vector{Tuple{String,VersionNumber,String}}(0) - - i = 1 - for (p,vn) in vers - ndeps[p][vn] == 0 && break - checked[i] && (i += 1; continue) - - fixed = Dict{String,Fixed}(p=>Fixed(vn, deps[p][vn].requires), "julia"=>Fixed(VERSION)) - sub_reqs = Dict{String,VersionSet}() - bktrc = Query.init_resolve_backtrace(sub_reqs, fixed) - Query.propagate_fixed!(sub_reqs, bktrc, fixed) - sub_deps = Query.dependencies_subset(deps, Set{String}([p])) - sub_deps, conflicts = Query.dependencies(sub_deps, fixed) - - try - for pkg in keys(sub_reqs) - if !haskey(sub_deps, pkg) - if "julia" in conflicts[pkg] - throw(PkgError("$pkg can't be installed because it has no versions that support $VERSION " * - "of julia. You may need to update METADATA by running `Pkg.update()`")) - else - sconflicts = join(conflicts[pkg], ", ", " and ") - throw(PkgError("$pkg's requirements can't be satisfied because " * - "of the following fixed packages: $sconflicts")) - end - end - end - Query.check_requirements(sub_reqs, sub_deps, fixed) - sub_deps = Query.prune_dependencies(sub_reqs, sub_deps, bktrc) - catch err - isa(err, PkgError) || rethrow(err) - ## info("ERROR MESSAGE:\n" * err.msg) - for vneq in eq_classes[p][vn] - push!(problematic, (p, vneq, "")) - end - i += 1 - continue - end - interface = Interface(sub_reqs, sub_deps) - - red_pkgs = interface.pkgs - red_np = interface.np - red_spp = interface.spp - red_pvers = interface.pvers - - ok, sol = greedysolver(interface) - - if !ok - try - graph = Graph(interface) - msgs = Messages(interface, graph) - sol = maxsum(graph, msgs) - ok = verify_solution(sol, interface) - @assert ok - catch err - isa(err, UnsatError) || rethrow(err) - pp = red_pkgs[err.info] - for vneq in eq_classes[p][vn] - push!(problematic, (p, vneq, pp)) - end - end - end - if ok - for p0 = 1:red_np - s0 = sol[p0] - if s0 != red_spp[p0] - j = svdict[(red_pkgs[p0], red_pvers[p0][s0])] - checked[j] = true - end - end - checked[i] = true - end - i += 1 - end - - return sort!(problematic) -end - -end # module diff --git a/julia-0.6.3/share/julia/base/pkg/resolve/fieldvalue.jl b/julia-0.6.3/share/julia/base/pkg/resolve/fieldvalue.jl deleted file mode 100644 index 1e153c0..0000000 --- a/julia-0.6.3/share/julia/base/pkg/resolve/fieldvalue.jl +++ /dev/null @@ -1,129 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -module FieldValues - -using ...VersionWeights -importall .....Base.Operators - -export FieldValue, Field, validmax, secondmax - -# FieldValue is a hierarchical numeric type with 6 levels. -# When summing two FieldValues, the levels are summed independently. -# When comparing them, lower levels take precedence. -# The levels are used as such: -# l0 : for hard constraints (dependencies and requirements) -# l1 : for favoring higher versions of the explicitly required -# packages -# l2 : for favoring higher versions of all other packages -# l3 : for favoring uninstallation of non-needed packages -# l4 : for favoring dependants over dependencies -# l5 : for symmetry-breaking random noise -# -struct FieldValue - l0::Int - l1::VersionWeight - l2::VersionWeight - l3::Int - l4::Int - l5::Int128 -end -FieldValue(l0::Integer, l1::VersionWeight, l2::VersionWeight, l3::Integer, l4::Integer) = FieldValue(l0, l1, l2, l3, l4, Int128(0)) -FieldValue(l0::Integer, l1::VersionWeight, l2::VersionWeight, l3::Integer) = FieldValue(l0, l1, l2, l3, 0) -FieldValue(l0::Integer, l1::VersionWeight, l2::VersionWeight) = FieldValue(l0, l1, l2, 0) -FieldValue(l0::Integer, l1::VersionWeight) = FieldValue(l0, l1, zero(VersionWeight)) -FieldValue(l0::Integer) = FieldValue(l0, zero(VersionWeight)) -FieldValue() = FieldValue(0) - -# This isn't nice, but it's for debugging only anyway -function Base.show(io::IO, a::FieldValue) - print(io, a.l0) - a == FieldValue(a.l0) && return - print(io, ".", a.l1) - a == FieldValue(a.l0, a.l1) && return - print(io, ".", a.l2) - a == FieldValue(a.l0, a.l1, a.l2) && return - print(io, ".", a.l3) - a == FieldValue(a.l0, a.l1, a.l2, a.l3) && return - print(io, ".", a.l4) - a == FieldValue(a.l0, a.l1, a.l2, a.l3, a.l4) && return - print(io, ".", a.l5) - return -end - -const Field = Vector{FieldValue} - -Base.zero(::Type{FieldValue}) = FieldValue() - -Base.typemin(::Type{FieldValue}) = (x=typemin(Int); y=typemin(VersionWeight); FieldValue(x, y, y, x, x, typemin(Int128))) - -Base.:-(a::FieldValue, b::FieldValue) = FieldValue(a.l0-b.l0, a.l1-b.l1, a.l2-b.l2, a.l3-b.l3, a.l4-b.l4, a.l5-b.l5) -Base.:+(a::FieldValue, b::FieldValue) = FieldValue(a.l0+b.l0, a.l1+b.l1, a.l2+b.l2, a.l3+b.l3, a.l4+b.l4, a.l5+b.l5) - -function Base.isless(a::FieldValue, b::FieldValue) - a.l0 < b.l0 && return true - a.l0 > b.l0 && return false - c = cmp(a.l1, b.l1) - c < 0 && return true - c > 0 && return false - c = cmp(a.l2, b.l2) - c < 0 && return true - c > 0 && return false - a.l3 < b.l3 && return true - a.l3 > b.l3 && return false - a.l4 < b.l4 && return true - a.l4 > b.l4 && return false - a.l5 < b.l5 && return true - return false -end - -Base.:(==)(a::FieldValue, b::FieldValue) = - a.l0 == b.l0 && a.l1 == b.l1 && a.l2 == b.l2 && a.l3 == b.l3 && a.l4 == b.l4 && a.l5 == b.l5 - -Base.abs(a::FieldValue) = FieldValue(abs(a.l0), abs(a.l1), abs(a.l2), abs(a.l3), abs(a.l4), abs(a.l5)) - -Base.copy(a::FieldValue) = FieldValue(a.l0, copy(a.l1), copy(a.l2), a.l3, a.l4, a.l5) - -function Base.unsafe_copy!(dest::Field, doffs, src::Field, soffs, n) - for i = 1:n - dest[doffs+i-1] = copy(src[soffs+i-1]) - end - return dest -end - -# if the maximum field has l0 < 0, it means that -# some hard constraint is being violated -validmax(a::FieldValue) = a.l0 >= 0 - -# like usual indmax, but favors the highest indices -# in case of a tie -function Base.indmax(f::Field) - m = typemin(FieldValue) - mi = 0 - for j = length(f):-1:1 - if f[j] > m - m = f[j] - mi = j - end - end - @assert mi != 0 - return mi -end - -# secondmax returns the (normalized) value of the second maximum in a -# field. It's used to determine the most polarized field. -function secondmax(f::Field) - m = typemin(FieldValue) - m2 = typemin(FieldValue) - for i = 1:length(f) - a = f[i] - if a > m - m2 = m - m = a - elseif a > m2 - m2 = a - end - end - return m2 - m -end - -end diff --git a/julia-0.6.3/share/julia/base/pkg/resolve/interface.jl b/julia-0.6.3/share/julia/base/pkg/resolve/interface.jl deleted file mode 100644 index 1bdd086..0000000 --- a/julia-0.6.3/share/julia/base/pkg/resolve/interface.jl +++ /dev/null @@ -1,364 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -module PkgToMaxSumInterface - -using ...Types, ...Query, ..VersionWeights - -export Interface, compute_output_dict, greedysolver, - verify_solution, enforce_optimality! - -# A collection of objects which allow interfacing external (Pkg) and -# internal (MaxSum) representation -mutable struct Interface - # requirements and dependencies, in external representation - reqs::Requires - deps::Dict{String,Dict{VersionNumber,Available}} - - # packages list - pkgs::Vector{String} - - # number of packages - np::Int - - # states per package: one per version + uninstalled - spp::Vector{Int} - - # pakage dict: associates an index to each package name - pdict::Dict{String,Int} - - # package versions: for each package, keep the list of the - # possible version numbers; this defines a - # mapping from version numbers of a package - # to indices - pvers::Vector{Vector{VersionNumber}} - - # versions dict: associates a version index to each package - # version; such that - # pvers[p0][vdict[p0][vn]] = vn - vdict::Vector{Dict{VersionNumber,Int}} - - # version weights: the weight for each version of each package - # (versions include the uninstalled state; the - # higher the weight, the more favored the version) - vweight::Vector{Vector{VersionWeight}} - - function Interface(reqs::Requires, deps::Dict{String,Dict{VersionNumber,Available}}) - # generate pkgs - pkgs = sort!(String[keys(deps)...]) - - np = length(pkgs) - - # generate pdict - pdict = Dict{String,Int}(pkgs[i] => i for i = 1:np) - - # generate spp and pvers - spp = Vector{Int}(np) - - pvers = [VersionNumber[] for i = 1:np] - - for (p,depsp) in deps, vn in keys(depsp) - p0 = pdict[p] - push!(pvers[p0], vn) - end - for p0 = 1:np - sort!(pvers[p0]) - spp[p0] = length(pvers[p0]) + 1 - end - - # generate vdict - vdict = [Dict{VersionNumber,Int}() for p0 = 1:np] - for (p,depsp) in deps - p0 = pdict[p] - vdict0 = vdict[p0] - pvers0 = pvers[p0] - for vn in keys(depsp) - for v0 in 1:length(pvers0) - if pvers0[v0] == vn - vdict0[vn] = v0 - break - end - end - end - end - - ## generate wveights: - vweight = Vector{Vector{VersionWeight}}(np) - for p0 = 1:np - pvers0 = pvers[p0] - spp0 = spp[p0] - vweight0 = vweight[p0] = Vector{VersionWeight}(spp0) - for v0 = 1:spp0-1 - vweight0[v0] = VersionWeight(pvers0[v0]) - end - vweight0[spp0] = VersionWeight(v"0") # last version means uninstalled - end - - return new(reqs, deps, pkgs, np, spp, pdict, pvers, vdict, vweight) - end -end - -# The output format is a Dict which associates a VersionNumber to each installed package name -function compute_output_dict(sol::Vector{Int}, interface::Interface) - pkgs = interface.pkgs - np = interface.np - pvers = interface.pvers - spp = interface.spp - - want = Dict{String,VersionNumber}() - for p0 = 1:np - p = pkgs[p0] - s = sol[p0] - if s != spp[p0] - v = pvers[p0][s] - want[p] = v - end - end - - return want -end - -# Produce a trivial solution: try to maximize each version; -# bail out as soon as some non-trivial requirements are detected. -function greedysolver(interface::Interface) - reqs = interface.reqs - deps = interface.deps - spp = interface.spp - pdict = interface.pdict - pvers = interface.pvers - np = interface.np - - # initialize solution: all uninstalled - sol = [spp[p0] for p0 = 1:np] - - # set up required packages to their highest allowed versions - for (rp,rvs) in reqs - rp0 = pdict[rp] - # look for the highest version which satisfies the requirements - rv = spp[rp0] - 1 - while rv > 0 - rvn = pvers[rp0][rv] - rvn ∈ rvs && break - rv -= 1 - end - @assert rv > 0 - sol[rp0] = rv - end - - # we start from required packages and explore the graph - # following dependencies - staged = Set{String}(keys(reqs)) - seen = copy(staged) - - while !isempty(staged) - staged_next = Set{String}() - for p in staged - p0 = pdict[p] - @assert sol[p0] < spp[p0] - vn = pvers[p0][sol[p0]] - a = deps[p][vn] - - # scan dependencies - for (rp,rvs) in a.requires - rp0 = pdict[rp] - # look for the highest version which satisfies the requirements - rv = spp[rp0] - 1 - while rv > 0 - rvn = pvers[rp0][rv] - rvn ∈ rvs && break - rv -= 1 - end - # if we found a version, and the package was uninstalled - # or the same version was already selected, we're ok; - # otherwise we can't be sure what the optimal configuration is - # and we bail out - if rv > 0 && (sol[rp0] == spp[rp0] || sol[rp0] == rv) - sol[rp0] = rv - else - return (false, Int[]) - end - - rp ∈ seen || push!(staged_next, rp) - end - end - union!(seen, staged_next) - staged = staged_next - end - - @assert verify_solution(sol, interface) - - return true, sol -end - -# verifies that the solution fulfills all hard constraints -# (requirements and dependencies) -function verify_solution(sol::Vector{Int}, interface::Interface) - reqs = interface.reqs - deps = interface.deps - spp = interface.spp - pdict = interface.pdict - pvers = interface.pvers - vdict = interface.vdict - - # verify requirements - for (p,vs) in reqs - p0 = pdict[p] - sol[p0] != spp[p0] || return false - vn = pvers[p0][sol[p0]] - vn ∈ vs || return false - end - - # verify dependencies - for (p,d) in deps - p0 = pdict[p] - vdict0 = vdict[p0] - for (vn,a) in d - v0 = vdict0[vn] - if sol[p0] == v0 - for (rp, rvs) in a.requires - p1 = pdict[rp] - if sol[p1] == spp[p1] - println(""" - VERIFICATION ERROR: REQUIRED DEPENDENCY NOT INSTALLED - package p=$p (p0=$p0) version=$vn (v0=$v0) requires package rp=$rp in version set rvs=$rvs - but package $rp is not being installed (p1=$p1 sol[p1]=$(sol[p1]) == spp[p1]=$(spp[p1])) - """) - return false - end - vn1 = pvers[p1][sol[p1]] - if vn1 ∉ rvs - println(""" - VERIFICATION ERROR: INVALID VERSION - package p=$p (p0=$p0) version=$vn (v0=$v0) requires package rp=$rp in version set rvs=$rvs - but package $rp version is being set to $vn1 (p1=$p1 sol[p1]=$(sol[p1]) spp[p1]=$(spp[p1])) - """) - return false - end - end - end - end - end - return true -end - -# Push the given solution to a local optimium if needed -function enforce_optimality!(sol::Vector{Int}, interface::Interface) - np = interface.np - - reqs = interface.reqs - deps = interface.deps - pkgs = interface.pkgs - spp = interface.spp - pdict = interface.pdict - pvers = interface.pvers - vdict = interface.vdict - - # prepare some useful structures - # pdeps[p0][v0] has all dependencies of package p0 version v0 - pdeps = [Vector{Requires}(spp[p0]-1) for p0 = 1:np] - # prevdeps[p1][p0][v0] is the VersionSet of package p1 which package p0 version v0 - # depends upon - prevdeps = [Dict{Int,Dict{Int,VersionSet}}() for p0 = 1:np] - - for (p,d) in deps - p0 = pdict[p] - vdict0 = vdict[p0] - for (vn,a) in d - v0 = vdict0[vn] - pdeps[p0][v0] = a.requires - for (rp, rvs) in a.requires - p1 = pdict[rp] - if !haskey(prevdeps[p1], p0) - prevdeps[p1][p0] = Dict{Int,VersionSet}() - end - prevdeps[p1][p0][v0] = rvs - end - end - end - - restart = true - while restart - restart = false - for p0 = 1:np - s0 = sol[p0] - if s0 >= spp[p0] - 1 - # either the package is not installed, - # or it's already at the maximum version - continue - end - viol = false - # check if the higher version has a depencency which - # would be violated by the state of the remaining packages - for (p,vs) in pdeps[p0][s0+1] - p1 = pdict[p] - if sol[p1] == spp[p1] - # the dependency is violated because - # the other package is not being installed - viol = true - break - end - vn = pvers[p1][sol[p1]] - if vn ∉ vs - # the dependency is violated because - # the other package version is invalid - viol = true - break - end - end - viol && continue - - # check if bumping the version would violate some - # dependency of another package - for (p1,d) in prevdeps[p0] - vs = get(d, sol[p1], nothing) - vs === nothing && continue - vn = pvers[p0][s0+1] - if vn ∉ vs - # bumping the version would violate - # the dependency - viol = true - break - end - end - viol && continue - # So the solution is non-optimal: we bump it manually - #warn("nonoptimal solution for package $(interface.pkgs[p0]): sol=$s0") - sol[p0] += 1 - restart = true - end - end - - # Finally uninstall unneeded packages: - # start from the required ones and keep only - # the packages reachable from them along the graph - uninst = trues(np) - staged = Set{String}(keys(reqs)) - seen = copy(staged) - - while !isempty(staged) - staged_next = Set{String}() - for p in staged - p0 = pdict[p] - uninst[p0] = false - @assert sol[p0] < spp[p0] - vn = pvers[p0][sol[p0]] - a = deps[p][vn] - - # scan dependencies - for (rp,rvs) in a.requires - rp0 = pdict[rp] - @assert sol[rp0] < spp[rp0] && pvers[rp0][sol[rp0]] ∈ rvs - rp ∈ seen || push!(staged_next, rp) - end - end - union!(seen, staged_next) - staged = staged_next - end - - for p0 in find(uninst) - sol[p0] = spp[p0] - end - - return -end - -end diff --git a/julia-0.6.3/share/julia/base/pkg/resolve/maxsum.jl b/julia-0.6.3/share/julia/base/pkg/resolve/maxsum.jl deleted file mode 100644 index ac8ff5b..0000000 --- a/julia-0.6.3/share/julia/base/pkg/resolve/maxsum.jl +++ /dev/null @@ -1,524 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -module MaxSum - -include("fieldvalue.jl") - -using .FieldValues, ..VersionWeights, ..PkgToMaxSumInterface - -export UnsatError, Graph, Messages, maxsum - -# An exception type used internally to signal that an unsatisfiable -# constraint was detected -mutable struct UnsatError <: Exception - info -end - -# Some parameters to drive the decimation process -mutable struct MaxSumParams - nondec_iterations # number of initial iterations before starting - # decimation - dec_interval # number of iterations between decimations - dec_fraction # fraction of nodes to decimate at every decimation - # step - - function MaxSumParams() - accuracy = parse(Int, get(ENV, "JULIA_PKGRESOLVE_ACCURACY", "1")) - if accuracy <= 0 - error("JULIA_PKGRESOLVE_ACCURACY must be > 0") - end - nondec_iterations = accuracy * 20 - dec_interval = accuracy * 10 - dec_fraction = 0.05 / accuracy - return new(nondec_iterations, dec_interval, dec_fraction) - end -end - -# Graph holds the graph structure onto which max-sum is run, in -# sparse format -mutable struct Graph - # adjacency matrix: - # for each package, has the list of neighbors - # indices (both dependencies and dependants) - gadj::Vector{Vector{Int}} - - # compatibility mask: - # for each package p0 has a list of bool masks. - # Each entry in the list gmsk[p0] is relative to the - # package p1 as read from gadj[p0]. - # Each mask has dimension spp1 x spp0, where - # spp0 is the number of states of p0, and - # spp1 is the number of states of p1. - gmsk::Vector{Vector{BitMatrix}} - - # dependency direction: - # keeps track of which direction the dependency goes - # takes 3 values: - # 1 = dependant - # -1 = dependency - # 0 = both - # Used to break symmetry between dependants and - # dependencies (introduces a FieldValue at level l3). - # The "both" case is for when there are dependency - # relations which go both ways, in which case the - # noise is left to discriminate in case of ties - gdir::Vector{Vector{Int}} - - # adjacency dict: - # allows one to retrieve the indices in gadj, so that - # gadj[p0][adjdict[p1][p0]] = p1 - # ("At which index does package p1 appear in gadj[p0]?") - adjdict::Vector{Dict{Int,Int}} - - # states per package: same as in Interface - spp::Vector{Int} - - # update order: shuffled at each iteration - perm::Vector{Int} - - # number of packages (all Vectors above have this length) - np::Int - - function Graph(interface::Interface) - deps = interface.deps - np = interface.np - - spp = interface.spp - pdict = interface.pdict - pvers = interface.pvers - vdict = interface.vdict - - gadj = [Int[] for i = 1:np] - gmsk = [BitMatrix[] for i = 1:np] - gdir = [Int[] for i = 1:np] - adjdict = [Dict{Int,Int}() for i = 1:np] - - for (p,d) in deps - p0 = pdict[p] - vdict0 = vdict[p0] - for (vn,a) in d - v0 = vdict0[vn] - for (rp, rvs) in a.requires - p1 = pdict[rp] - - j0 = 1 - while j0 <= length(gadj[p0]) && gadj[p0][j0] != p1 - j0 += 1 - end - j1 = 1 - while j1 <= length(gadj[p1]) && gadj[p1][j1] != p0 - j1 += 1 - end - @assert (j0 > length(gadj[p0]) && j1 > length(gadj[p1])) || - (j0 <= length(gadj[p0]) && j1 <= length(gadj[p1])) - - if j0 > length(gadj[p0]) - push!(gadj[p0], p1) - push!(gadj[p1], p0) - j0 = length(gadj[p0]) - j1 = length(gadj[p1]) - - adjdict[p1][p0] = j0 - adjdict[p0][p1] = j1 - - bm = trues(spp[p1], spp[p0]) - bmt = bm' - - push!(gmsk[p0], bm) - push!(gmsk[p1], bmt) - - push!(gdir[p0], 1) - push!(gdir[p1], -1) - else - bm = gmsk[p0][j0] - bmt = gmsk[p1][j1] - if gdir[p0][j0] == -1 - gdir[p0][j0] = 0 - gdir[p1][j1] = 0 - end - end - - for v1 = 1:length(pvers[p1]) - if pvers[p1][v1] ∉ rvs - bm[v1, v0] = false - bmt[v0, v1] = false - end - end - bm[end,v0] = false - bmt[v0,end] = false - end - end - end - - perm = [1:np;] - - return new(gadj, gmsk, gdir, adjdict, spp, perm, np) - end -end - -# Messages has the cavity messages and the total fields, and -# gets updated iteratively (and occasionally decimated) until -# convergence -mutable struct Messages - # cavity incoming messages: for each package p0, - # for each neighbor p1 of p0, - # msg[p0][p1] is a vector of length spp[p0] - # messages are normalized (i.e. the max is always 0) - msg::Vector{Vector{Field}} - - # overall fields: for each package p0, - # fld[p0] is a vector of length spp[p0] - # fields are not normalized - fld::Vector{Field} - - # backup of the initial value of fld, to be used when resetting - initial_fld::Vector{Field} - - # keep track of which variables have been decimated - decimated::BitVector - num_nondecimated::Int - - function Messages(interface::Interface, graph::Graph) - reqs = interface.reqs - pkgs = interface.pkgs - np = interface.np - spp = interface.spp - pvers = interface.pvers - pdict = interface.pdict - vweight = interface.vweight - - # a "deterministic noise" function based on hashes - function noise(p0::Int, v0::Int) - s = pkgs[p0] * string(v0 == spp[p0] ? "UNINST" : pvers[p0][v0]) - Int128(hash(s)) - end - - # external fields: there are 2 terms, a noise to break potential symmetries - # and one to favor newest versions over older, and no-version over all - fld = [[FieldValue(0, zero(VersionWeight), vweight[p0][v0], (v0==spp[p0]), 0, noise(p0,v0)) for v0 = 1:spp[p0]] for p0 = 1:np] - - # enforce requirements - for (rp, rvs) in reqs - p0 = pdict[rp] - pvers0 = pvers[p0] - fld0 = fld[p0] - for v0 = 1:spp[p0]-1 - vn = pvers0[v0] - if !in(vn, rvs) - # the state is forbidden by requirements - fld0[v0] = FieldValue(-1) - else - # the state is one of those explicitly requested: - # favor it at a higer level than normal (upgrade - # FieldValue from l2 to l1) - fld0[v0] += FieldValue(0, vweight[p0][v0], -vweight[p0][v0]) - end - end - # the uninstalled state is forbidden by requirements - fld0[spp[p0]] = FieldValue(-1) - end - # normalize fields - for p0 = 1:np - m = maximum(fld[p0]) - for v0 = 1:spp[p0] - fld[p0][v0] -= m - end - end - - initial_fld = deepcopy(fld) - - # initialize cavity messages to 0 - gadj = graph.gadj - msg = [[zeros(FieldValue, spp[p0]) for p1 = 1:length(gadj[p0])] for p0 = 1:np] - - return new(msg, fld, initial_fld, falses(np), np) - end -end - -function getsolution(msgs::Messages) - # the solution is just the location of the maximum in - # each field - - fld = msgs.fld - np = length(fld) - sol = Vector{Int}(np) - for p0 = 1:np - fld0 = fld[p0] - s0 = indmax(fld0) - if !validmax(fld0[s0]) - throw(UnsatError(p0)) - end - sol[p0] = s0 - end - return sol -end - -# This is the core of the max-sum solver: -# for a given node p0 (i.e. a package) updates all -# input cavity messages and fields of its neighbors -function update(p0::Int, graph::Graph, msgs::Messages) - gadj = graph.gadj - gmsk = graph.gmsk - gdir = graph.gdir - adjdict = graph.adjdict - spp = graph.spp - np = graph.np - msg = msgs.msg - fld = msgs.fld - decimated = msgs.decimated - - maxdiff = zero(FieldValue) - - gadj0 = gadj[p0] - msg0 = msg[p0] - fld0 = fld[p0] - spp0 = spp[p0] - adjdict0 = adjdict[p0] - - # iterate over all neighbors of p0 - for j0 in 1:length(gadj0) - - p1 = gadj0[j0] - decimated[p1] && continue - j1 = adjdict0[p1] - #@assert j0 == adjdict[p1][p0] - bm1 = gmsk[p1][j1] - dir1 = gdir[p1][j1] - spp1 = spp[p1] - msg1 = msg[p1] - - # compute the output cavity message p0->p1 - cavmsg = fld0 - msg0[j0] - - if dir1 == -1 - # p0 depends on p1 - for v0 = 1:spp0-1 - cavmsg[v0] += FieldValue(0, VersionWeight(0), VersionWeight(0), 0, v0) - end - end - - # keep the old input cavity message p0->p1 - oldmsg = msg1[j1] - - # init the new message to minus infinity - newmsg = [FieldValue(-1) for v1 = 1:spp1] - - # compute the new message by passing cavmsg - # through the constraint encoded in the bitmask - # (nearly equivalent to: - # newmsg = [maximum(cavmsg[bm1[:,v1]]) for v1 = 1:spp1] - # except for the gnrg term) - m = FieldValue(-1) - for v1 = 1:spp1 - for v0 = 1:spp0 - if bm1[v0, v1] - newmsg[v1] = max(newmsg[v1], cavmsg[v0]) - end - end - if dir1 == 1 && v1 != spp1 - # p1 depends on p0 - newmsg[v1] += FieldValue(0, VersionWeight(0), VersionWeight(0), 0, v1) - end - m = max(m, newmsg[v1]) - end - if !validmax(m) - # No state available without violating some - # hard constraint - throw(UnsatError(p1)) - end - - # normalize the new message - for v1 = 1:spp1 - newmsg[v1] -= m - end - - diff = newmsg - oldmsg - maxdiff = max(maxdiff, maximum(abs.(diff))) - - # update the field of p1 - fld1 = fld[p1] - for v1 = 1:spp1 - fld1[v1] += diff[v1] - end - - # put the newly computed message in place - msg1[j1] = newmsg - end - return maxdiff -end - -# A simple shuffling machinery for the update order in iterate() -# (woulnd't pass any random quality test but it's arguably enough) -let step=1 -global shuffleperm, shuffleperminit -shuffleperminit() = (step = 1) -function shuffleperm(graph::Graph) - perm = graph.perm - np = graph.np - for j = np:-1:2 - k = mod(step,j)+1 - perm[j], perm[k] = perm[k], perm[j] - step += isodd(j) ? 1 : k - end - #@assert isperm(perm) -end -end - -# Call update for all nodes (i.e. packages) in -# random order -function iterate(graph::Graph, msgs::Messages) - np = graph.np - - maxdiff = zero(FieldValue) - shuffleperm(graph) - perm = graph.perm - for p0 in perm - maxdiff0 = update(p0, graph, msgs) - maxdiff = max(maxdiff, maxdiff0) - end - return maxdiff -end - -function decimate1(p0::Int, graph::Graph, msgs::Messages) - decimated = msgs.decimated - fld = msgs.fld - adjdict = graph.adjdict - gmsk = graph.gmsk - - @assert !decimated[p0] - fld0 = fld[p0] - s0 = indmax(fld0) - # only do the decimation if it is consistent with - # the previously decimated nodes - for p1 in find(decimated) - haskey(adjdict[p0], p1) || continue - s1 = indmax(fld[p1]) - j1 = adjdict[p0][p1] - gmsk[p1][j1][s0,s1] || return false - end - #println("DECIMATING $p0 (s0=$s0 fld=$fld0)") - for v0 = 1:length(fld0) - v0 == s0 && continue - fld0[v0] = FieldValue(-1) - end - msgs.decimated[p0] = true - msgs.num_nondecimated -= 1 - return true -end - -function reset_messages!(msgs::Messages) - msg = msgs.msg - fld = msgs.fld - initial_fld = msgs.initial_fld - decimated = msgs.decimated - np = length(fld) - for p0 = 1:np - map(m->fill!(m, zero(FieldValue)), msg[p0]) - decimated[p0] && continue - fld[p0] = copy(initial_fld[p0]) - end - return msgs -end - -# If normal convergence fails (or is too slow) fix the most -# polarized packages by adding extra infinite fields on every state -# but the maximum -function decimate(n::Int, graph::Graph, msgs::Messages) - #println("DECIMATING $n NODES") - adjdict = graph.adjdict - fld = msgs.fld - decimated = msgs.decimated - fldorder = sortperm(fld, by=secondmax) - did_dec = false - for p0 in fldorder - decimated[p0] && continue - did_dec |= decimate1(p0, graph, msgs) - n -= 1 - n == 0 && break - end - @assert n == 0 - if !did_dec - # did not succeed in decimating anything; - # try to decimate at least one node - for p0 in fldorder - decimated[p0] && continue - if decimate1(p0, graph, msgs) - did_dec = true - break - end - end - end - if !did_dec - # still didn't succeed, give up - p0 = first(fldorder[.~(decimated)]) - throw(UnsatError(p0)) - end - - reset_messages!(msgs) - return -end - -# In case ties still exist at convergence, break them and -# keep converging -function break_ties(msgs::Messages) - fld = msgs.fld - unbroken_ties = Int[] - for p0 = 1:length(fld) - fld0 = fld[p0] - z = 0 - m = typemin(FieldValue) - for v0 = 1:length(fld0) - if fld0[v0] > m - m = fld0[v0] - z = 1 - elseif fld0[v0] == m - z += 1 - end - end - if z > 1 - #println("TIE! p0=$p0") - decimate1(p0, msgs) && return false - push!(unbroken_ties, p0) - end - end - # If there were ties, but none were broken, bail out - isempty(unbroken_ties) || throw(PkgError(first(unbroken_ties))) - return true -end - -# Iterative solver: run iterate() until convergence -# (occasionally calling decimate()) -function maxsum(graph::Graph, msgs::Messages) - params = MaxSumParams() - - it = 0 - shuffleperminit() - while true - it += 1 - maxdiff = iterate(graph, msgs) - #println("it = $it maxdiff = $maxdiff") - - if maxdiff == zero(FieldValue) - break_ties(msgs) && break - continue - end - if it >= params.nondec_iterations && - (it - params.nondec_iterations) % params.dec_interval == 0 - numdec = clamp(floor(Int, params.dec_fraction * graph.np), 1, msgs.num_nondecimated) - decimate(numdec, graph, msgs) - msgs.num_nondecimated == 0 && break - end - end - - # Finally, decimate everything just to - # check against inconsistencies - # (old_numnondec is saved just to prevent - # wrong messages about accuracy) - old_numnondec = msgs.num_nondecimated - decimate(msgs.num_nondecimated, graph, msgs) - msgs.num_nondecimated = old_numnondec - - return getsolution(msgs) -end - -end diff --git a/julia-0.6.3/share/julia/base/pkg/resolve/versionweight.jl b/julia-0.6.3/share/julia/base/pkg/resolve/versionweight.jl deleted file mode 100644 index b04e488..0000000 --- a/julia-0.6.3/share/julia/base/pkg/resolve/versionweight.jl +++ /dev/null @@ -1,230 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -module VersionWeights - -importall ....Base.Operators - -export VersionWeight - -struct HierarchicalValue{T} - v::Vector{T} - rest::T -end - -HierarchicalValue{T}(v::Vector{T}) = HierarchicalValue{T}(v, zero(T)) -HierarchicalValue(T::Type) = HierarchicalValue(T[]) - -Base.zero(::Type{HierarchicalValue{T}}) where {T} = HierarchicalValue(T) - -Base.typemin(::Type{HierarchicalValue{T}}) where {T} = HierarchicalValue(T[], typemin(T)) - -for f in (:-, :+) - @eval function Base.$f(a::HierarchicalValue{T}, b::HierarchicalValue{T}) where T - av = a.v - bv = b.v - la = length(a.v) - lb = length(b.v) - l0 = min(la, lb) - l1 = max(la, lb) - ld = la - lb - rv = Vector{T}(l1) - rf = ($f)(a.rest, b.rest) - @inbounds for i = 1:l0 - rv[i] = ($f)(av[i], bv[i]) - end - @inbounds for i = l0+1:l0+ld - rv[i] = ($f)(av[i], b.rest) - end - @inbounds for i = l0+1:l0-ld - rv[i] = ($f)(a.rest, bv[i]) - end - return HierarchicalValue(rv, rf) - end -end - -Base.:-(a::HierarchicalValue) = HierarchicalValue(-a.v, -a.rest) - -function Base.cmp(a::HierarchicalValue{T}, b::HierarchicalValue{T}) where T - av = a.v - bv = b.v - la = length(a.v) - lb = length(b.v) - l0 = min(la, lb) - l1 = max(la, lb) - ld = la - lb - @inbounds for i = 1:l0 - c = cmp(av[i], bv[i]); c != 0 && return c - end - @inbounds for i = l0+1:l0+ld - c = cmp(av[i], b.rest); c != 0 && return c - end - @inbounds for i = l0+1:l0-ld - c = cmp(a.rest, bv[i]); c != 0 && return c - end - return cmp(a.rest, b.rest) -end -Base.isless(a::HierarchicalValue{T}, b::HierarchicalValue{T}) where {T} = cmp(a,b) < 0 -Base.:(==)(a::HierarchicalValue{T}, b::HierarchicalValue{T}) where {T} = cmp(a,b) == 0 - -Base.abs(a::HierarchicalValue{T}) where {T} = HierarchicalValue(T[abs(x) for x in a.v], abs(a.rest)) - -Base.copy(a::HierarchicalValue{T}) where {T} = HierarchicalValue(T[copy(x) for x in a.v], copy(a.rest)) - -struct VWPreBuildItem - nonempty::Int - s::HierarchicalValue{Int} - i::Int -end -VWPreBuildItem() = VWPreBuildItem(0, HierarchicalValue(Int), 0) -VWPreBuildItem(i::Int) = VWPreBuildItem(1, HierarchicalValue(Int), i) -VWPreBuildItem(s::String) = VWPreBuildItem(1, HierarchicalValue(Int[s...]), 0) - -Base.zero(::Type{VWPreBuildItem}) = VWPreBuildItem() - -Base.typemin(::Type{VWPreBuildItem}) = (x=typemin(Int); VWPreBuildItem(x, typemin(HierarchicalValue{Int}), x)) - -Base.:-(a::VWPreBuildItem, b::VWPreBuildItem) = VWPreBuildItem(a.nonempty-b.nonempty, a.s-b.s, a.i-b.i) -Base.:+(a::VWPreBuildItem, b::VWPreBuildItem) = VWPreBuildItem(a.nonempty+b.nonempty, a.s+b.s, a.i+b.i) - -Base.:-(a::VWPreBuildItem) = VWPreBuildItem(-a.nonempty, -a.s, -a.i) - -function Base.cmp(a::VWPreBuildItem, b::VWPreBuildItem) - c = cmp(a.nonempty, b.nonempty); c != 0 && return c - c = cmp(a.s, b.s); c != 0 && return c - return cmp(a.i, b.i) -end -Base.isless(a::VWPreBuildItem, b::VWPreBuildItem) = cmp(a,b) < 0 -Base.:(==)(a::VWPreBuildItem, b::VWPreBuildItem) = cmp(a,b) == 0 - -Base.abs(a::VWPreBuildItem) = VWPreBuildItem(abs(a.nonempty), abs(a.s), abs(a.i)) - -Base.copy(a::VWPreBuildItem) = VWPreBuildItem(a.nonempty, copy(a.s), a.i) - -struct VWPreBuild - nonempty::Int - w::HierarchicalValue{VWPreBuildItem} -end - -const _vwprebuild_zero = VWPreBuild(0, HierarchicalValue(VWPreBuildItem)) - -function VWPreBuild(ispre::Bool, desc::Tuple{Vararg{Union{Int,String}}}) - isempty(desc) && return _vwprebuild_zero - desc == ("",) && return VWPreBuild(ispre ? -1 : 1, HierarchicalValue(VWPreBuildItem[])) - hv = HierarchicalValue([VWPreBuildItem(item) for item in desc]) - return VWPreBuild(ispre ? -1 : 0, hv) -end -VWPreBuild() = _vwprebuild_zero - -Base.zero(::Type{VWPreBuild}) = VWPreBuild() - -const _vwprebuild_min = VWPreBuild(typemin(Int), typemin(HierarchicalValue{VWPreBuildItem})) -Base.typemin(::Type{VWPreBuild}) = _vwprebuild_min - -function Base.:(-)(a::VWPreBuild, b::VWPreBuild) - b === _vwprebuild_zero && return a - a === _vwprebuild_zero && return -b - VWPreBuild(a.nonempty-b.nonempty, a.w-b.w) -end -function Base.:(+)(a::VWPreBuild, b::VWPreBuild) - b === _vwprebuild_zero && return a - a === _vwprebuild_zero && return b - VWPreBuild(a.nonempty+b.nonempty, a.w+b.w) -end - -function Base.:(-)(a::VWPreBuild) - a === _vwprebuild_zero && return a - VWPreBuild(-a.nonempty, -a.w) -end - -@inline function Base.cmp(a::VWPreBuild, b::VWPreBuild) - a === _vwprebuild_zero && b === _vwprebuild_zero && return 0 - c = cmp(a.nonempty, b.nonempty); c != 0 && return c - return cmp(a.w, b.w) -end -Base.isless(a::VWPreBuild, b::VWPreBuild) = cmp(a,b) < 0 -Base.:(==)(a::VWPreBuild, b::VWPreBuild) = cmp(a,b) == 0 - -function Base.abs(a::VWPreBuild) - a === _vwprebuild_zero && return a - VWPreBuild(abs(a.nonempty), abs(a.w)) -end - -function Base.copy(a::VWPreBuild) - a === _vwprebuild_zero && return a - VWPreBuild(a.nonempty, copy(a.w)) -end - -function Base.deepcopy_internal(a::VWPreBuild, dict::ObjectIdDict) - haskey(dict, a) && return dict[a] - b = (a === _vwprebuild_zero) ? _vwprebuild_zero : VWPreBuild(a.nonempty, Base.deepcopy_internal(a.w, dict)) - dict[a] = b - return b -end - -# The numeric type used to determine how the different -# versions of a package should be weighed -struct VersionWeight - major::Int - minor::Int - patch::Int - prerelease::VWPreBuild - build::VWPreBuild -end -VersionWeight(major::Int, minor::Int, patch::Int, prerelease::VWPreBuild) = VersionWeight(major, minor, patch, prerelease, zero(VWPreBuild)) -VersionWeight(major::Int, minor::Int, patch::Int) = VersionWeight(major, minor, patch, zero(VWPreBuild)) -VersionWeight(major::Int, minor::Int) = VersionWeight(major, minor, 0) -VersionWeight(major::Int) = VersionWeight(major, 0) -VersionWeight() = VersionWeight(0) - -VersionWeight(vn::VersionNumber) = - VersionWeight(vn.major, vn.minor, vn.patch, - VWPreBuild(true, vn.prerelease), VWPreBuild(false, vn.build)) - -Base.zero(::Type{VersionWeight}) = VersionWeight() - -Base.typemin(::Type{VersionWeight}) = (x=typemin(Int); y=typemin(VWPreBuild); VersionWeight(x, x, x, y, y)) - -Base.:(-)(a::VersionWeight, b::VersionWeight) = - VersionWeight(a.major-b.major, a.minor-b.minor, a.patch-b.patch, - a.prerelease-b.prerelease, a.build-b.build) - -Base.:(+)(a::VersionWeight, b::VersionWeight) = - VersionWeight(a.major+b.major, a.minor+b.minor, a.patch+b.patch, - a.prerelease+b.prerelease, a.build+b.build) - -Base.:(-)(a::VersionWeight) = - VersionWeight(-a.major, -a.minor, -a.patch, - -a.prerelease, -a.build) - -function Base.cmp(a::VersionWeight, b::VersionWeight) - c = cmp(a.major, b.major); c != 0 && return c - c = cmp(a.minor, b.minor); c != 0 && return c - c = cmp(a.patch, b.patch); c != 0 && return c - c = cmp(a.prerelease, b.prerelease); c != 0 && return c - return cmp(a.build, b.build) -end -Base.isless(a::VersionWeight, b::VersionWeight) = cmp(a,b) < 0 -Base.:(==)(a::VersionWeight, b::VersionWeight) = cmp(a,b) == 0 - -Base.abs(a::VersionWeight) = - VersionWeight(abs(a.major), abs(a.minor), abs(a.patch), - abs(a.prerelease), abs(a.build)) - -Base.copy(a::VersionWeight) = - VersionWeight(a.major, a.minor, a.patch, - copy(a.prerelease), copy(a.build)) - -# This isn't nice, but it's for debugging only anyway -function Base.show(io::IO, a::VersionWeight) - print(io, "(", a.major) - a == VersionWeight(a.major) && @goto done - print(io, ".", a.minor) - a == VersionWeight(a.major, a.minor) && @goto done - print(io, ".", a.patch) - a.prerelease ≠ _vwprebuild_zero && print(io, "-", a.prerelease) - a.build ≠ _vwprebuild_zero && print(io, "+", a.build) - @label done - print(io, ")") -end - -end diff --git a/julia-0.6.3/share/julia/base/pkg/types.jl b/julia-0.6.3/share/julia/base/pkg/types.jl deleted file mode 100644 index 1e55a0b..0000000 --- a/julia-0.6.3/share/julia/base/pkg/types.jl +++ /dev/null @@ -1,256 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -module Types - -export VersionInterval, VersionSet, Requires, Available, Fixed, merge_requires!, satisfies, - ResolveBacktraceItem, ResolveBacktrace -import Base: show, isempty, in, intersect, union!, union, ==, hash, copy, deepcopy_internal, push! - -struct VersionInterval - lower::VersionNumber - upper::VersionNumber -end -VersionInterval(lower::VersionNumber) = VersionInterval(lower,typemax(VersionNumber)) -VersionInterval() = VersionInterval(typemin(VersionNumber)) - -show(io::IO, i::VersionInterval) = print(io, "[$(i.lower),$(i.upper))") -isempty(i::VersionInterval) = i.upper <= i.lower -in(v::VersionNumber, i::VersionInterval) = i.lower <= v < i.upper -intersect(a::VersionInterval, b::VersionInterval) = VersionInterval(max(a.lower,b.lower), min(a.upper,b.upper)) -==(a::VersionInterval, b::VersionInterval) = a.lower == b.lower && a.upper == b.upper -hash(i::VersionInterval, h::UInt) = hash((i.lower, i.upper), h + (0x0f870a92db508386 % UInt)) - -function normalize!(ivals::Vector{VersionInterval}) - # VersionSet internal normalization: - # removes empty intervals and fuses intervals without gaps - # e.g.: - # [0.0.0,1.0.0) ∪ [1.0.0,1.5.0) ∪ [1.6.0,1.6.0) ∪ [2.0.0,∞) - # becomes: - # [0.0.0,1.5.0) ∪ [2.0.0,∞) - # (still assumes that lower bounds are sorted, and intervals do - # not overlap) - l = length(ivals) - l == 0 && return ivals - - lo, up, k0 = ivals[1].lower, ivals[1].upper, 1 - fusing = false - for k = 2:l - lo1, up1 = ivals[k].lower, ivals[k].upper - if lo1 == up - up = up1 - fusing = true - continue - end - if lo < up - # The only purpose of the "fusing" check is to avoid - # extra allocations - ivals[k0] = fusing ? VersionInterval(lo, up) : ivals[k-1] - k0 += 1 - end - fusing = false - lo, up = lo1, up1 - end - if lo < up - ivals[k0] = fusing ? VersionInterval(lo, up) : ivals[l] - k0 += 1 - end - resize!(ivals, k0 - 1) - return ivals -end - -struct VersionSet - intervals::Vector{VersionInterval} - VersionSet(intervals::Vector{VersionInterval}) = new(normalize!(intervals)) - # copy is defined inside the struct block to call `new` directly - # without going through `normalize!` - Base.copy(vset::VersionSet) = new(copy(vset.intervals)) -end -function VersionSet(versions::Vector{VersionNumber}) - intervals = VersionInterval[] - if isempty(versions) - push!(intervals, VersionInterval()) - else - isodd(length(versions)) && push!(versions, typemax(VersionNumber)) - while !isempty(versions) - push!(intervals, VersionInterval(shift!(versions), shift!(versions))) - end - end - VersionSet(intervals) -end -VersionSet(versions::VersionNumber...) = VersionSet(VersionNumber[versions...]) - -const empty_versionset = VersionSet(VersionInterval[]) - -# Windows console doesn't like Unicode -const _empty_symbol = @static is_windows() ? "empty" : "∅" -const _union_symbol = @static is_windows() ? " or " : " ∪ " -show(io::IO, s::VersionSet) = isempty(s) ? print(io, _empty_symbol) : - join(io, s.intervals, _union_symbol) -isempty(s::VersionSet) = all(isempty, s.intervals) -in(v::VersionNumber, s::VersionSet) = any(i->in(v,i), s.intervals) -function intersect(A::VersionSet, B::VersionSet) - (isempty(A) || isempty(B)) && return copy(empty_versionset) - ivals = [intersect(a,b) for a in A.intervals for b in B.intervals] - sort!(ivals, by=i->i.lower) - VersionSet(ivals) -end - -union(A::VersionSet, B::VersionSet) = union!(copy(A), B) -function union!(A::VersionSet, B::VersionSet) - A == B && return A - ivals = A.intervals - for intB in B.intervals - lB, uB = intB.lower, intB.upper - k0 = findfirst(i->(i.upper > lB), ivals) - if k0 == 0 - push!(ivals, intB) - continue - end - lB = min(lB, ivals[k0].lower) - for k1 = k0:length(ivals) - intA = ivals[k1] - if uB < intA.lower - splice!(ivals, k0:(k1-1), (VersionInterval(lB, uB),)) - break - elseif uB ∈ intA || k1 == length(ivals) - splice!(ivals, k0:k1, (VersionInterval(lB, max(uB, intA.upper)),)) - break - end - end - end - normalize!(ivals) - return A -end - -==(A::VersionSet, B::VersionSet) = A.intervals == B.intervals -hash(s::VersionSet, h::UInt) = hash(s.intervals, h + (0x2fd2ca6efa023f44 % UInt)) -deepcopy_internal(vs::VersionSet, ::ObjectIdDict) = copy(vs) - -const Requires = Dict{String,VersionSet} - -function merge_requires!(A::Requires, B::Requires) - for (pkg,vers) in B - A[pkg] = haskey(A,pkg) ? intersect(A[pkg],vers) : vers - end - return A -end - -satisfies(pkg::AbstractString, ver::VersionNumber, reqs::Requires) = - !haskey(reqs, pkg) || in(ver, reqs[pkg]) - -struct Available - sha1::String - requires::Requires -end - -==(a::Available, b::Available) = a.sha1 == b.sha1 && a.requires == b.requires -hash(a::Available, h::UInt) = hash((a.sha1, a.requires), h + (0xbc8ae0de9d11d972 % UInt)) -copy(a::Available) = Available(a.sha1, copy(a.requires)) - -show(io::IO, a::Available) = isempty(a.requires) ? - print(io, "Available(", repr(a.sha1), ")") : - print(io, "Available(", repr(a.sha1), ",", a.requires, ")") - -struct Fixed - version::VersionNumber - requires::Requires -end -Fixed(v::VersionNumber) = Fixed(v,Requires()) - -==(a::Fixed, b::Fixed) = a.version == b.version && a.requires == b.requires -hash(f::Fixed, h::UInt) = hash((f.version, f.requires), h + (0x68628b809fd417ca % UInt)) - -show(io::IO, f::Fixed) = isempty(f.requires) ? - print(io, "Fixed(", repr(f.version), ")") : - print(io, "Fixed(", repr(f.version), ",", f.requires, ")") - -# TODO: Available & Fixed are almost the same – merge them? -# Free could include the same information too, it just isn't -# required by anything that processes these things. - - -const VersionReq = Union{VersionNumber,VersionSet} -const WhyReq = Tuple{VersionReq,Any} - -# This is used to keep track of dependency relations when propagating -# requirements, so as to emit useful information in case of unsatisfiable -# conditions. -# The `versionreq` field keeps track of the remaining allowed versions, -# intersecting all requirements. -# The `why` field is a Vector which keeps track of the requirements. Each -# entry is a Tuple of two elements: -# 1) the first element is the version requirement (can be a single VersionNumber -# or a VersionSet). -# 2) the second element can be either :fixed (for requirements induced by -# fixed packages), :required (for requirements induced by explicitly -# required packages), or a Pair p=>backtrace_item (for requirements induced -# indirectly, where `p` is the package name and `backtrace_item` is -# another ResolveBacktraceItem. -mutable struct ResolveBacktraceItem - versionreq::VersionReq - why::Vector{WhyReq} - ResolveBacktraceItem() = new(VersionSet(), WhyReq[]) - ResolveBacktraceItem(reason, versionreq::VersionReq) = new(versionreq, WhyReq[(versionreq,reason)]) -end - -function push!(ritem::ResolveBacktraceItem, reason, versionset::VersionSet) - if isa(ritem.versionreq, VersionSet) - ritem.versionreq = ritem.versionreq ∩ versionset - elseif ritem.versionreq ∉ versionset - ritem.versionreq = copy(empty_versionset) - end - push!(ritem.why, (versionset,reason)) -end - -function push!(ritem::ResolveBacktraceItem, reason, version::VersionNumber) - if isa(ritem.versionreq, VersionSet) - if version ∈ ritem.versionreq - ritem.versionreq = version - else - ritem.versionreq = copy(empty_versionset) - end - elseif ritem.versionreq ≠ version - ritem.versionreq = copy(empty_versionset) - end - push!(ritem.why, (version,reason)) -end - - -show(io::IO, ritem::ResolveBacktraceItem) = _show(io, ritem, "", Set{ResolveBacktraceItem}([ritem])) - -function _show(io::IO, ritem::ResolveBacktraceItem, indent::String, seen::Set{ResolveBacktraceItem}) - l = length(ritem.why) - for (i,(vs,w)) in enumerate(ritem.why) - print(io, indent, (i==l ? '└' : '├'), '─') - if w ≡ :fixed - @assert isa(vs, VersionNumber) - println(io, "version $vs set by fixed requirement (package is checked out, dirty or pinned)") - elseif w ≡ :required - @assert isa(vs, VersionSet) - println(io, "version range $vs set by an explicit requirement") - else - @assert isa(w, Pair{<:AbstractString,ResolveBacktraceItem}) - if isa(vs, VersionNumber) - print(io, "version $vs ") - else - print(io, "version range $vs ") - end - print(io, "required by package $(w[1]), ") - if isa(w[2].versionreq, VersionSet) - println(io, "whose allowed version range is $(w[2].versionreq):") - else - println(io, "whose only allowed version is $(w[2].versionreq):") - end - if w[2] ∈ seen - println(io, (i==l ? " " : "│ ") * indent, "└─[see above for $(w[1]) backtrace]") - continue - end - push!(seen, w[2]) - _show(io, w[2], (i==l ? " " : "│ ") * indent, seen) - end - end -end - -const ResolveBacktrace = Dict{AbstractString,ResolveBacktraceItem} - -end # module diff --git a/julia-0.6.3/share/julia/base/pkg/write.jl b/julia-0.6.3/share/julia/base/pkg/write.jl deleted file mode 100644 index 635ef6a..0000000 --- a/julia-0.6.3/share/julia/base/pkg/write.jl +++ /dev/null @@ -1,64 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -module Write - -import ...LibGit2, ..Cache, ..Read, ...Pkg.PkgError -importall ...LibGit2 - -function prefetch(pkg::AbstractString, sha1::AbstractString) - isempty(Cache.prefetch(pkg, Read.url(pkg), sha1)) && return - throw(PkgError("$pkg: couldn't find commit $(sha1[1:10])")) -end - -function fetch(repo::GitRepo, pkg::AbstractString, sha1::AbstractString) - cache = Cache.path(pkg) - LibGit2.fetch(repo, remoteurl=cache, refspecs=["+refs/*:refs/remotes/cache/*"]) - LibGit2.need_update(repo) - LibGit2.iscommit(sha1, repo) && return - f = with(GitRepo, cache) do repo - LibGit2.iscommit(sha1, repo) - end ? "fetch" : "prefetch" - url = Read.issue_url(pkg) - if isempty(url) - throw(PkgError("$pkg: $f failed to get commit $(sha1[1:10]), please file a bug report with the package author.")) - else - throw(PkgError("$pkg: $f failed to get commit $(sha1[1:10]), please file an issue at $url")) - end -end - -function checkout(repo::GitRepo, pkg::AbstractString, sha1::AbstractString) - LibGit2.set_remote_url(repo, Cache.normalize_url(Read.url(pkg))) - LibGit2.checkout!(repo, sha1) -end - -function install(pkg::AbstractString, sha1::AbstractString) - prefetch(pkg, sha1) - repo = if isdir(".trash/$pkg") - mv(".trash/$pkg", "./$pkg") #TODO check for newer version in cache before moving - GitRepo(pkg) - else - LibGit2.clone(Cache.path(pkg), pkg) - end - try - fetch(repo, pkg, sha1) - checkout(repo, pkg, sha1) - finally - close(repo) - end -end - -function update(pkg::AbstractString, sha1::AbstractString) - prefetch(pkg, sha1) - with(GitRepo, pkg) do repo - fetch(repo, pkg, sha1) - checkout(repo, pkg, sha1) - end -end - -function remove(pkg::AbstractString) - isdir(".trash") || mkdir(".trash") - ispath(".trash/$pkg") && rm(".trash/$pkg", recursive=true) - mv(pkg, ".trash/$pkg") -end - -end # module diff --git a/julia-0.6.3/share/julia/base/pointer.jl b/julia-0.6.3/share/julia/base/pointer.jl deleted file mode 100644 index 9ef25eb..0000000 --- a/julia-0.6.3/share/julia/base/pointer.jl +++ /dev/null @@ -1,128 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -""" - Ptr{T} - -A memory address referring to data of type `T`. However, there is no guarantee that the -memory is actually valid, or that it actually represents data of the specified type. -""" -Ptr - -## converting pointers to an appropriate unsigned ## - -""" - C_NULL - -The C null pointer constant, sometimes used when calling external code. -""" -const C_NULL = bitcast(Ptr{Void}, 0) - -# TODO: deprecate these conversions. C doesn't even allow them. - -# pointer to integer -convert(::Type{T}, x::Ptr) where {T<:Union{Int,UInt}} = bitcast(T, x) -convert(::Type{T}, x::Ptr) where {T<:Integer} = convert(T, convert(UInt, x)) - -# integer to pointer -convert(::Type{Ptr{T}}, x::UInt) where {T} = bitcast(Ptr{T}, x) -convert(::Type{Ptr{T}}, x::Int) where {T} = bitcast(Ptr{T}, x) - -# pointer to pointer -convert(::Type{Ptr{T}}, p::Ptr{T}) where {T} = p -convert(::Type{Ptr{T}}, p::Ptr) where {T} = bitcast(Ptr{T}, p) - -# object to pointer (when used with ccall) -unsafe_convert(::Type{Ptr{UInt8}}, x::Symbol) = ccall(:jl_symbol_name, Ptr{UInt8}, (Any,), x) -unsafe_convert(::Type{Ptr{Int8}}, x::Symbol) = ccall(:jl_symbol_name, Ptr{Int8}, (Any,), x) -unsafe_convert(::Type{Ptr{UInt8}}, s::String) = convert(Ptr{UInt8}, pointer_from_objref(s)+sizeof(Int)) -unsafe_convert(::Type{Ptr{Int8}}, s::String) = convert(Ptr{Int8}, pointer_from_objref(s)+sizeof(Int)) -# convert strings to String etc. to pass as pointers -cconvert(::Type{Ptr{UInt8}}, s::AbstractString) = String(s) -cconvert(::Type{Ptr{Int8}}, s::AbstractString) = String(s) - -unsafe_convert(::Type{Ptr{T}}, a::Array{T}) where {T} = ccall(:jl_array_ptr, Ptr{T}, (Any,), a) -unsafe_convert(::Type{Ptr{S}}, a::AbstractArray{T}) where {S,T} = convert(Ptr{S}, unsafe_convert(Ptr{T}, a)) -unsafe_convert(::Type{Ptr{T}}, a::AbstractArray{T}) where {T} = error("conversion to pointer not defined for $(typeof(a))") - -# unsafe pointer to array conversions -""" - unsafe_wrap(Array, pointer::Ptr{T}, dims, own=false) - -Wrap a Julia `Array` object around the data at the address given by `pointer`, -without making a copy. The pointer element type `T` determines the array -element type. `dims` is either an integer (for a 1d array) or a tuple of the array dimensions. -`own` optionally specifies whether Julia should take ownership of the memory, -calling `free` on the pointer when the array is no longer referenced. - -This function is labelled "unsafe" because it will crash if `pointer` is not -a valid memory address to data of the requested length. -""" -function unsafe_wrap(::Union{Type{Array},Type{Array{T}},Type{Array{T,N}}}, - p::Ptr{T}, dims::NTuple{N,Int}, own::Bool=false) where {T,N} - ccall(:jl_ptr_to_array, Array{T,N}, (Any, Ptr{Void}, Any, Int32), - Array{T,N}, p, dims, own) -end -function unsafe_wrap(::Union{Type{Array},Type{Array{T}},Type{Array{T,1}}}, - p::Ptr{T}, d::Integer, own::Bool=false) where {T} - ccall(:jl_ptr_to_array_1d, Array{T,1}, - (Any, Ptr{Void}, Csize_t, Cint), Array{T,1}, p, d, own) -end -unsafe_wrap(Atype::Type, p::Ptr, dims::NTuple{N,<:Integer}, own::Bool=false) where {N} = - unsafe_wrap(Atype, p, convert(Tuple{Vararg{Int}}, dims), own) - -""" - unsafe_load(p::Ptr{T}, i::Integer=1) - -Load a value of type `T` from the address of the `i`th element (1-indexed) starting at `p`. -This is equivalent to the C expression `p[i-1]`. - -The `unsafe` prefix on this function indicates that no validation is performed on the -pointer `p` to ensure that it is valid. Incorrect usage may segfault your program or return -garbage answers, in the same manner as C. -""" -unsafe_load(p::Ptr, i::Integer=1) = pointerref(p, Int(i), 1) - -""" - unsafe_store!(p::Ptr{T}, x, i::Integer=1) - -Store a value of type `T` to the address of the `i`th element (1-indexed) starting at `p`. -This is equivalent to the C expression `p[i-1] = x`. - -The `unsafe` prefix on this function indicates that no validation is performed on the -pointer `p` to ensure that it is valid. Incorrect usage may corrupt or segfault your -program, in the same manner as C. -""" -unsafe_store!(p::Ptr{Any}, x::ANY, i::Integer=1) = pointerset(p, x, Int(i), 1) -unsafe_store!(p::Ptr{T}, x, i::Integer=1) where {T} = pointerset(p, convert(T,x), Int(i), 1) - -# convert a raw Ptr to an object reference, and vice-versa -""" - unsafe_pointer_to_objref(p::Ptr) - -Convert a `Ptr` to an object reference. Assumes the pointer refers to a valid heap-allocated -Julia object. If this is not the case, undefined behavior results, hence this function is -considered "unsafe" and should be used with care. -""" -unsafe_pointer_to_objref(x::Ptr) = ccall(:jl_value_ptr, Any, (Ptr{Void},), x) - -""" - pointer_from_objref(x) - -Get the memory address of a Julia object as a `Ptr`. The existence of the resulting `Ptr` -will not protect the object from garbage collection, so you must ensure that the object -remains referenced for the whole time that the `Ptr` will be used. -""" -pointer_from_objref(x::ANY) = ccall(:jl_value_ptr, Ptr{Void}, (Any,), x) -data_pointer_from_objref(x::ANY) = pointer_from_objref(x)::Ptr{Void} - -eltype(::Type{Ptr{T}}) where {T} = T - -## limited pointer arithmetic & comparison ## - -==(x::Ptr, y::Ptr) = UInt(x) == UInt(y) -isless(x::Ptr, y::Ptr) = isless(UInt(x), UInt(y)) --(x::Ptr, y::Ptr) = UInt(x) - UInt(y) - -+(x::Ptr, y::Integer) = oftype(x, (UInt(x) + (y % UInt) % UInt)) --(x::Ptr, y::Integer) = oftype(x, (UInt(x) - (y % UInt) % UInt)) -+(x::Integer, y::Ptr) = y + x diff --git a/julia-0.6.3/share/julia/base/poll.jl b/julia-0.6.3/share/julia/base/poll.jl deleted file mode 100644 index 3e02d49..0000000 --- a/julia-0.6.3/share/julia/base/poll.jl +++ /dev/null @@ -1,556 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -# filesystem operations - -export - watch_file, - poll_fd, - poll_file, - FileMonitor, - PollingFileWatcher, - FDWatcher - -import Base: @handle_as, wait, close, uvfinalize, eventloop, notify_error, stream_wait, - _sizeof_uv_poll, _sizeof_uv_fs_poll, _sizeof_uv_fs_event, _uv_hook_close, - associate_julia_struct, disassociate_julia_struct, | -if is_windows() - import Base.WindowsRawSocket -end - -# libuv file watching event flags -const UV_RENAME = 1 -const UV_CHANGE = 2 -struct FileEvent - renamed::Bool - changed::Bool - timedout::Bool -end -FileEvent() = FileEvent(false, false, false) -FileEvent(flags::Integer) = FileEvent((flags & UV_RENAME) != 0, - (flags & UV_CHANGE) != 0, - (flags & FD_TIMEDOUT) != 0) -fetimeout() = FileEvent(false, false, true) - -struct FDEvent - readable::Bool - writable::Bool - disconnect::Bool - timedout::Bool -end -# libuv file descriptor event flags -const UV_READABLE = 1 -const UV_WRITABLE = 2 -const UV_DISCONNECT = 4 -const FD_TIMEDOUT = 8 - -isreadable(f::FDEvent) = f.readable -iswritable(f::FDEvent) = f.writable -FDEvent() = FDEvent(false, false, false, false) -FDEvent(flags::Integer) = FDEvent((flags & UV_READABLE) != 0, - (flags & UV_WRITABLE) != 0, - (flags & UV_DISCONNECT) != 0, - (flags & FD_TIMEDOUT) != 0) -fdtimeout() = FDEvent(false, false, false, true) -|(a::FDEvent, b::FDEvent) = - FDEvent(a.readable | b.readable, - a.writable | b.writable, - a.disconnect | b.disconnect, - a.timedout | b.timedout) - -mutable struct FileMonitor - handle::Ptr{Void} - file::String - notify::Condition - active::Bool - function FileMonitor(file::AbstractString) - handle = Libc.malloc(_sizeof_uv_fs_event) - this = new(handle, file, Condition(), false) - associate_julia_struct(handle, this) - err = ccall(:uv_fs_event_init, Cint, (Ptr{Void}, Ptr{Void}), eventloop(), handle) - if err != 0 - Libc.free(handle) - throw(UVError("FileMonitor", err)) - end - finalizer(this, uvfinalize) - return this - end -end - -mutable struct PollingFileWatcher - handle::Ptr{Void} - file::String - interval::UInt32 - notify::Condition - active::Bool - function PollingFileWatcher(file::AbstractString, interval::Float64=5.007) # same default as nodejs - handle = Libc.malloc(_sizeof_uv_fs_poll) - this = new(handle, file, round(UInt32, interval * 1000), Condition(), false) - associate_julia_struct(handle, this) - err = ccall(:uv_fs_poll_init, Int32, (Ptr{Void}, Ptr{Void}), eventloop(), handle) - if err != 0 - Libc.free(handle) - throw(UVError("PollingFileWatcher", err)) - end - finalizer(this, uvfinalize) - return this - end -end - -mutable struct _FDWatcher - handle::Ptr{Void} - fdnum::Int # this is NOT the file descriptor - refcount::Tuple{Int, Int} - notify::Condition - active::Tuple{Bool, Bool} - events::Int32 - - let FDWatchers = Vector{Any}() - global _FDWatcher - @static if is_unix() - function _FDWatcher(fd::RawFD, readable::Bool, writable::Bool) - if !readable && !writable - throw(ArgumentError("must specify at least one of readable or writable to create a FDWatcher")) - end - fdnum = fd.fd + 1 - if fdnum > length(FDWatchers) - old_len = length(FDWatchers) - resize!(FDWatchers, fdnum) - FDWatchers[(old_len + 1):fdnum] = nothing - elseif FDWatchers[fdnum] !== nothing - this = FDWatchers[fdnum]::_FDWatcher - this.refcount = (this.refcount[1] + Int(readable), this.refcount[2] + Int(writable)) - return this - end - if ccall(:jl_uv_unix_fd_is_watched, Int32, (Int32, Ptr{Void}, Ptr{Void}), fd.fd, C_NULL, eventloop()) == 1 - throw(ArgumentError("file descriptor $(fd.fd) is already being watched by libuv")) - end - - handle = Libc.malloc(_sizeof_uv_poll) - this = new( - handle, - fdnum, - (Int(readable), Int(writable)), - Condition(), - (false, false), - 0) - associate_julia_struct(handle, this) - err = ccall(:uv_poll_init, Int32, (Ptr{Void}, Ptr{Void}, Int32), eventloop(), handle, fd.fd) - if err != 0 - Libc.free(handle) - throw(UVError("FDWatcher", err)) - end - finalizer(this, uvfinalize) - FDWatchers[fdnum] = this - return this - end - end - - global uvfinalize - function uvfinalize(t::_FDWatcher) - if t.handle != C_NULL - disassociate_julia_struct(t) - ccall(:jl_close_uv, Void, (Ptr{Void},), t.handle) - t.handle = C_NULL - end - t.refcount = (0, 0) - t.active = (false, false) - @static if is_unix() - if FDWatchers[t.fdnum] == t - FDWatchers[t.fdnum] = nothing - end - end - notify(t.notify, fdtimeout()) - nothing - end - end - - @static if is_windows() - function _FDWatcher(fd::RawFD, readable::Bool, writable::Bool) - handle = Libc._get_osfhandle(fd) - return _FDWatcher(handle, readable, writable) - end - function _FDWatcher(fd::WindowsRawSocket, readable::Bool, writable::Bool) - if !readable && !writable - throw(ArgumentError("must specify at least one of readable or writable to create a FDWatcher")) - end - - handle = Libc.malloc(_sizeof_uv_poll) - this = new( - handle, - 0, - (Int(readable), Int(writable)), - Condition(), - (false, false), - 0) - associate_julia_struct(handle, this) - err = ccall(:uv_poll_init_socket, Int32, (Ptr{Void}, Ptr{Void}, Ptr{Void}), - eventloop(), handle, fd.handle) - if err != 0 - Libc.free(handle) - throw(UVError("FDWatcher", err)) - end - finalizer(this, uvfinalize) - return this - end - end -end - -mutable struct FDWatcher - watcher::_FDWatcher - readable::Bool - writable::Bool - # WARNING: make sure `close` has been manually called on this watcher before closing / destroying `fd` - function FDWatcher(fd::RawFD, readable::Bool, writable::Bool) - this = new(_FDWatcher(fd, readable, writable), readable, writable) - finalizer(this, close) - return this - end - @static if is_windows() - function FDWatcher(fd::WindowsRawSocket, readable::Bool, writable::Bool) - this = new(_FDWatcher(fd, readable, writable), readable, writable) - finalizer(this, close) - return this - end - end -end - - -function close(t::_FDWatcher, readable::Bool, writable::Bool) - if t.refcount != (0, 0) - t.refcount = (t.refcount[1] - Int(readable), t.refcount[2] - Int(writable)) - end - if t.refcount == (0, 0) - uvfinalize(t) - end -end - -function close(t::FDWatcher) - r, w = t.readable, t.writable - t.readable = t.writable = false - close(t.watcher, r, w) -end - -function uvfinalize(uv::Union{FileMonitor, PollingFileWatcher}) - disassociate_julia_struct(uv) - close(uv) -end - -function close(t::Union{FileMonitor, PollingFileWatcher}) - if t.handle != C_NULL - ccall(:jl_close_uv, Void, (Ptr{Void},), t.handle) - end -end - -function _uv_hook_close(uv::_FDWatcher) - # fyi: jl_atexit_hook can cause this to get called too - uv.handle = C_NULL - uvfinalize(uv) - nothing -end - -function _uv_hook_close(uv::PollingFileWatcher) - uv.handle = C_NULL - uv.active = false - notify(uv.notify, (StatStruct(), StatStruct())) - nothing -end - -function _uv_hook_close(uv::FileMonitor) - uv.handle = C_NULL - uv.active = false - notify(uv.notify, ("", FileEvent())) - nothing -end - -function __init__() - global uv_jl_pollcb = cfunction(uv_pollcb, Void, Tuple{Ptr{Void}, Cint, Cint}) - global uv_jl_fspollcb = cfunction(uv_fspollcb, Void, Tuple{Ptr{Void}, Cint, Ptr{Void}, Ptr{Void}}) - global uv_jl_fseventscb = cfunction(uv_fseventscb, Void, Tuple{Ptr{Void}, Ptr{Int8}, Int32, Int32}) -end - -function uv_fseventscb(handle::Ptr{Void}, filename::Ptr, events::Int32, status::Int32) - t = @handle_as handle FileMonitor - fname = filename == C_NULL ? "" : unsafe_string(convert(Ptr{UInt8}, filename)) - if status != 0 - notify_error(t.notify, UVError("FileMonitor", status)) - else - notify(t.notify, (fname, FileEvent(events))) - end - nothing -end - -function uv_pollcb(handle::Ptr{Void}, status::Int32, events::Int32) - t = @handle_as handle _FDWatcher - if status != 0 - notify_error(t.notify, UVError("FDWatcher", status)) - else - t.events |= events - if t.active[1] || t.active[2] - if isempty(t.notify.waitq) - # if we keep hearing about events when nobody appears to be listening, - # stop the poll to save cycles - t.active = (false, false) - ccall(:uv_poll_stop, Int32, (Ptr{Void},), t.handle) - end - end - notify(t.notify, FDEvent(events)) - end - nothing -end - -function uv_fspollcb(handle::Ptr{Void}, status::Int32, prev::Ptr, curr::Ptr) - t = @handle_as handle PollingFileWatcher - if status != 0 - notify_error(t.notify, UVError("PollingFileWatcher", status)) - else - prev_stat = StatStruct(convert(Ptr{UInt8}, prev)) - curr_stat = StatStruct(convert(Ptr{UInt8}, curr)) - notify(t.notify, (prev_stat, curr_stat)) - end - nothing -end - - -function start_watching(t::_FDWatcher) - readable = t.refcount[1] > 0 - writable = t.refcount[2] > 0 - if t.active[1] != readable || t.active[2] != writable - # make sure the READABLE / WRITEABLE state is updated - uv_error("start_watching (File Handle)", - ccall(:uv_poll_start, Int32, (Ptr{Void}, Int32, Ptr{Void}), - t.handle, - (readable ? UV_READABLE : 0) | (writable ? UV_WRITABLE : 0), - uv_jl_pollcb::Ptr{Void})) - t.active = (readable, writable) - end - nothing -end - -function start_watching(t::PollingFileWatcher) - if !t.active - uv_error("start_watching (File Path)", - ccall(:uv_fs_poll_start, Int32, (Ptr{Void}, Ptr{Void}, Cstring, UInt32), - t.handle, uv_jl_fspollcb::Ptr{Void}, t.file, t.interval)) - t.active = true - end - nothing -end - -function stop_watching(t::PollingFileWatcher) - if t.active && isempty(t.notify.waitq) - t.active = false - uv_error("stop_watching (File Path)", - ccall(:uv_fs_poll_stop, Int32, (Ptr{Void},), t.handle)) - end - nothing -end - -function start_watching(t::FileMonitor) - if !t.active - uv_error("start_watching (File Monitor)", - ccall(:uv_fs_event_start, Int32, (Ptr{Void}, Ptr{Void}, Cstring, Int32), - t.handle, uv_jl_fseventscb::Ptr{Void}, t.file, 0)) - t.active = true - end - nothing -end - -function stop_watching(t::FileMonitor) - if t.active && isempty(t.notify.waitq) - t.active = false - uv_error("stop_watching (File Monitor)", - ccall(:uv_fs_event_stop, Int32, (Ptr{Void},), t.handle)) - end - nothing -end - -function wait(fdw::FDWatcher) - return wait(fdw.watcher, readable = fdw.readable, writable = fdw.writable) -end -function wait(fdw::_FDWatcher; readable=true, writable=true) - events = FDEvent() - while true - if isa(events, FDEvent) - events = events::FDEvent - events |= FDEvent(fdw.events) - haveevent = false - if readable && isreadable(events) - fdw.events &= ~UV_READABLE - haveevent = true - end - if writable && iswritable(events) - fdw.events &= ~UV_WRITABLE - haveevent = true - end - if haveevent - return events - end - else - throw(events) - end - if fdw.refcount == (0, 0) # !open - events = EOFError() - else - start_watching(fdw) # make sure the poll is active - events = wait(fdw.notify) - end - end -end - -function wait(fd::RawFD; readable=false, writable=false) - fdw = _FDWatcher(fd, readable, writable) - try - return wait(fdw, readable=readable, writable=writable) - finally - close(fdw, readable, writable) - end -end - -if is_windows() - function wait(socket::WindowsRawSocket; readable=false, writable=false) - fdw = _FDWatcher(socket, readable, writable) - try - return wait(fdw, readable=readable, writable=writable) - finally - close(fdw, readable, writable) - end - end -end - -function wait(pfw::PollingFileWatcher) - start_watching(pfw) - prevstat, currstat = stream_wait(pfw, pfw.notify) - stop_watching(pfw) - return prevstat, currstat -end - -function wait(m::FileMonitor) - start_watching(m) - filename, events = stream_wait(m, m.notify) - stop_watching(m) - return filename, events -end - -""" - poll_fd(fd, timeout_s::Real=-1; readable=false, writable=false) - -Monitor a file descriptor `fd` for changes in the read or write availability, and with a -timeout given by `timeout_s` seconds. - -The keyword arguments determine which of read and/or write status should be monitored; at -least one of them must be set to `true`. - -The returned value is an object with boolean fields `readable`, `writable`, and `timedout`, -giving the result of the polling. -""" -function poll_fd(s::Union{RawFD, is_windows() ? WindowsRawSocket : Union{}}, timeout_s::Real=-1; readable=false, writable=false) - wt = Condition() - fdw = _FDWatcher(s, readable, writable) - try - if timeout_s >= 0 - result::FDEvent = fdtimeout() - - @schedule begin - try - result = wait(fdw, readable=readable, writable=writable) - catch e - notify_error(wt, e) - return - end - notify(wt) - end - @schedule (sleep(timeout_s); notify(wt)) - - wait(wt) - return result - else - return wait(fdw, readable=readable, writable=writable) - end - finally - close(fdw, readable, writable) - end -end - -""" - watch_file(path::AbstractString, timeout_s::Real=-1) - -Watch file or directory `path` for changes until a change occurs or `timeout_s` seconds have -elapsed. - -The returned value is an object with boolean fields `changed`, `renamed`, and `timedout`, -giving the result of watching the file. - -This behavior of this function varies slightly across platforms. See -<https://nodejs.org/api/fs.html#fs_caveats> for more detailed information. -""" -function watch_file(s::AbstractString, timeout_s::Real=-1) - wt = Condition() - fm = FileMonitor(s) - try - if timeout_s >= 0 - result = fetimeout() - - @schedule begin - try - _, result = wait(fm) - catch e - notify_error(wt, e) - return - end - notify(wt) - end - @schedule (sleep(timeout_s); notify(wt)) - - wait(wt) - return result - else - return wait(fm)[2] - end - finally - close(fm) - end -end - -""" - poll_file(path::AbstractString, interval_s::Real=5.007, timeout_s::Real=-1) -> (previous::StatStruct, current::StatStruct) - -Monitor a file for changes by polling every `interval_s` seconds until a change occurs or -`timeout_s` seconds have elapsed. The `interval_s` should be a long period; the default is -5.007 seconds. - -Returns a pair of `StatStruct` objects `(previous, current)` when a change is detected. - -To determine when a file was modified, compare `mtime(prev) != mtime(current)` to detect -notification of changes. However, using [`watch_file`](@ref) for this operation is preferred, since -it is more reliable and efficient, although in some situations it may not be available. -""" -function poll_file(s::AbstractString, interval_seconds::Real=5.007, timeout_s::Real=-1) - wt = Condition() - pfw = PollingFileWatcher(s, Float64(interval_seconds)) - try - if timeout_s >= 0 - result = :timeout - - @schedule begin - try - result = wait(pfw) - catch e - notify_error(wt, e) - return - end - notify(wt) - end - @schedule (sleep(timeout_s); notify(wt)) - - wait(wt) - if result === :timeout - return (StatStruct(), StatStruct()) - end - return result - else - return wait(pfw) - end - finally - close(pfw) - end -end diff --git a/julia-0.6.3/share/julia/base/precompile.jl b/julia-0.6.3/share/julia/base/precompile.jl deleted file mode 100644 index a604830..0000000 --- a/julia-0.6.3/share/julia/base/precompile.jl +++ /dev/null @@ -1,1882 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -# Steps to regenerate this file: -# 1. Remove all `precompile` calls -# 2. Rebuild system image -# 3. Enable TRACE_COMPILE in options.h and rebuild -# 4. Run `./julia 2> precompiles.txt` and do various things. -# 5. Run `grep -v '#[0-9]' precompiles.txt >> base/precompile.jl` (filters out closures, which -# might have different generated names in different environments) - -precompile(Tuple{typeof(Base.pointer), Array{UInt8, 1}, UInt64}) -precompile(Tuple{typeof(Base.convert), Type{Ptr{Int32}}, Ptr{UInt8}}) -if USE_GPL_LIBS -precompile(Tuple{typeof(Base.SparseArrays.CHOLMOD.set_print_level), Array{UInt8, 1}, Int64}) -end -precompile(Tuple{Type{Base.Multimedia.TextDisplay}, Base.TTY}) -precompile(Tuple{typeof(Base._start)}) -precompile(Tuple{typeof(Base.copy!), Array{String, 1}, Int64, Array{Any, 1}, Int64, Int64}) -precompile(Tuple{typeof(Base.empty!), Base.Dict{Int64, Union{Base.Distributed.Worker, Base.Distributed.LocalProcess}}}) -precompile(Tuple{typeof(Core.Inference.isbits), Base.Distributed.DefaultClusterManager}) -precompile(Tuple{typeof(Base.Distributed.init_worker), String, Base.Distributed.DefaultClusterManager}) -precompile(Tuple{typeof(Base.finalizer), Base.TCPServer, typeof(Base.uvfinalize)}) -precompile(Tuple{Type{Base.TCPServer}, Ptr{Void}, Int64}) -precompile(Tuple{typeof(Base.show), Base.IOContext{Base.AbstractIOBuffer{Array{UInt8, 1}}}, Int32}) -precompile(Tuple{typeof(Base.print), Base.AbstractIOBuffer{Array{UInt8, 1}}, Base.Libc.RawFD}) -precompile(Tuple{typeof(Base.uv_status_string), Base.TCPServer}) -precompile(Tuple{typeof(Base._fd), Base.TCPServer}) -precompile(Tuple{typeof(Base.print), Base.AbstractIOBuffer{Array{UInt8, 1}}, Type{Base.TCPServer}, String, Base.Libc.RawFD, String, String, String}) -precompile(Tuple{typeof(Base.print), Base.AbstractIOBuffer{Array{UInt8, 1}}, Base.TCPServer}) -precompile(Tuple{typeof(Base.isopen), Base.TCPServer}) -precompile(Tuple{typeof(Base.check_open), Base.TCPServer}) -precompile(Tuple{typeof(Base.unpreserve_handle), Base.TCPServer}) -precompile(Tuple{typeof(Base.stream_wait), Base.TCPServer, Base.Condition}) -precompile(Tuple{Type{Base.TCPServer}}) -precompile(Tuple{typeof(Base.close), Base.TCPServer}) -precompile(Tuple{getfield(Base, Symbol("#kw##listen")), Array{Any, 1}, typeof(Base.listen), Base.TCPServer}) -precompile(Tuple{getfield(Base, Symbol("#kw##listen")), Array{Any, 1}, typeof(Base.listen), Base.InetAddr{Base.IPv4}}) -precompile(Tuple{typeof(Base.ndigits0z), UInt16}) -precompile(Tuple{typeof(Base.dec), UInt16, Int64, Bool}) -precompile(Tuple{typeof(Base.Libc.strerror), Int32}) -precompile(Tuple{typeof(Base.copy!), Array{Any, 1}, Base.KeyIterator{Base.Dict{Any, Any}}}) -precompile(Tuple{typeof(Base.promoteK), Type{Any}}) -precompile(Tuple{typeof(Core.Inference.length), Tuple{Core.Inference.Const, DataType, Core.Inference.Const, Core.Inference.Const}}) -precompile(Tuple{typeof(Core.Inference.getindex), Tuple{Core.Inference.Const, DataType, Core.Inference.Const, Core.Inference.Const}, Int64}) -precompile(Tuple{typeof(Base.sync_add), Task}) -precompile(Tuple{typeof(Core.Inference.getindex), Tuple{Int64, Tuple{Int64, Tuple{}}}, Int64}) -precompile(Tuple{typeof(Base.Distributed.local_remotecall_thunk), typeof(Base.Distributed.set_valid_processes), Tuple{Array{Int64, 1}}, Array{Any, 1}}) -precompile(Tuple{typeof(Base.Distributed.remote_do), typeof(Base.Distributed.set_valid_processes), Base.Distributed.Worker, Array{Int64, 1}}) -precompile(Tuple{typeof(Base.Distributed.remote_do), typeof(Base.Distributed.set_valid_processes), Base.Distributed.LocalProcess, Array{Int64, 1}}) -precompile(Tuple{getfield(Base.Distributed, Symbol("#kw##remote_do")), Array{Any, 1}, typeof(Base.Distributed.remote_do), typeof(Base.Distributed.set_valid_processes), Base.Distributed.Worker, Array{Int64, 1}}) -precompile(Tuple{getfield(Base.Distributed, Symbol("#kw##remote_do")), Array{Any, 1}, typeof(Base.Distributed.remote_do), typeof(Base.Distributed.set_valid_processes), Base.Distributed.LocalProcess, Array{Int64, 1}}) -precompile(Tuple{typeof(Base.Sort.Float.isnan), Base.Order.ForwardOrdering, Float32}) -precompile(Tuple{typeof(Base.Sort.Float.isnan), Base.Order.ForwardOrdering, Float64}) -precompile(Tuple{typeof(Base.Sort.Float.isnan), Base.Order.ReverseOrdering{Base.Order.ForwardOrdering}, Float32}) -precompile(Tuple{typeof(Base.Sort.Float.isnan), Base.Order.ReverseOrdering{Base.Order.ForwardOrdering}, Float64}) -precompile(Tuple{typeof(Base.Sort.Float.issignleft), Base.Order.ForwardOrdering, Float32}) -precompile(Tuple{typeof(Base.Sort.Float.issignleft), Base.Order.ReverseOrdering{Base.Order.ForwardOrdering}, Float32}) -precompile(Tuple{typeof(Base.Sort.Float.issignleft), Base.Order.ForwardOrdering, Float64}) -precompile(Tuple{typeof(Base.Sort.Float.issignleft), Base.Order.ReverseOrdering{Base.Order.ForwardOrdering}, Float64}) -precompile(Tuple{typeof(Core.Inference.isbits), Base.Sort.Float.Left}) -precompile(Tuple{typeof(Base.Sort.Float.left), Base.Order.ForwardOrdering}) -precompile(Tuple{typeof(Base.Sort.Float.left), Base.Order.ReverseOrdering{Base.Order.ForwardOrdering}}) -precompile(Tuple{typeof(Core.Inference.isbits), Base.Sort.Float.Right}) -precompile(Tuple{typeof(Base.Sort.Float.right), Base.Order.ForwardOrdering}) -precompile(Tuple{typeof(Base.Sort.Float.right), Base.Order.ReverseOrdering{Base.Order.ForwardOrdering}}) -precompile(Tuple{typeof(Base.stat), Int64}) -precompile(Tuple{typeof(Base.readbytes_all!), Base.IOStream, Array{UInt8, 1}, Int64}) -precompile(Tuple{typeof(Base.read), Base.IOStream}) -precompile(Tuple{typeof(Base.open), typeof(Base.readstring), String}) -precompile(Tuple{typeof(Base.rstrip), Base.SubString{String}, Array{Char, 1}}) -precompile(Tuple{typeof(Base.lstrip), Base.SubString{String}, Array{Char, 1}}) -precompile(Tuple{getfield(Base, Symbol("#kw##split")), Array{Any, 1}, typeof(Base.split), String, Char}) -precompile(Tuple{getfield(Base, Symbol("#kw##split")), Array{Any, 1}, typeof(Base.split), Base.SubString{String}, Char}) -precompile(Tuple{typeof(Base.map!), typeof(Base.strip), Array{Base.SubString{String}, 1}, Array{Base.SubString{String}, 1}}) -precompile(Tuple{typeof(Base.UTF8proc.isnumber), Base.SubString{String}}) -precompile(Tuple{Type{Core.Inference.Generator{I, F} where F where I}, Type{Core.Inference.Const}, Tuple{Tuple{Base.DevNullStream, Base.DevNullStream, Base.DevNullStream}}}) -precompile(Tuple{Type{Core.Inference.Generator{Tuple{Tuple{Base.DevNullStream, Base.DevNullStream, Base.DevNullStream}}, Type{Core.Inference.Const}}}, Type{Core.Inference.Const}, Tuple{Tuple{Base.DevNullStream, Base.DevNullStream, Base.DevNullStream}}}) -precompile(Tuple{typeof(Core.Inference.convert), Type{Tuple{Tuple{Base.DevNullStream, Base.DevNullStream, Base.DevNullStream}}}, Tuple{Tuple{Base.DevNullStream, Base.DevNullStream, Base.DevNullStream}}}) -precompile(Tuple{typeof(Core.Inference.collect), Type{Any}, Core.Inference.Generator{Tuple{Tuple{Base.DevNullStream, Base.DevNullStream, Base.DevNullStream}}, Type{Core.Inference.Const}}}) -precompile(Tuple{typeof(Core.Inference.iteratorsize), Core.Inference.Generator{Tuple{Tuple{Base.DevNullStream, Base.DevNullStream, Base.DevNullStream}}, Type{Core.Inference.Const}}}) -precompile(Tuple{typeof(Core.Inference.iteratorsize), Type{Core.Inference.Generator{Tuple{Tuple{Base.DevNullStream, Base.DevNullStream, Base.DevNullStream}}, Type{Core.Inference.Const}}}}) -precompile(Tuple{typeof(Core.Inference.iteratorsize), Type{Tuple{Tuple{Base.DevNullStream, Base.DevNullStream, Base.DevNullStream}}}}) -precompile(Tuple{typeof(Core.Inference._collect), Type{Any}, Core.Inference.Generator{Tuple{Tuple{Base.DevNullStream, Base.DevNullStream, Base.DevNullStream}}, Type{Core.Inference.Const}}, Core.Inference.HasLength}) -precompile(Tuple{typeof(Core.Inference.length), Core.Inference.Generator{Tuple{Tuple{Base.DevNullStream, Base.DevNullStream, Base.DevNullStream}}, Type{Core.Inference.Const}}}) -precompile(Tuple{typeof(Core.Inference.length), Tuple{Tuple{Base.DevNullStream, Base.DevNullStream, Base.DevNullStream}}}) -precompile(Tuple{typeof(Core.Inference.copy!), Array{Any, 1}, Core.Inference.Generator{Tuple{Tuple{Base.DevNullStream, Base.DevNullStream, Base.DevNullStream}}, Type{Core.Inference.Const}}}) -precompile(Tuple{typeof(Core.Inference.start), Core.Inference.Generator{Tuple{Tuple{Base.DevNullStream, Base.DevNullStream, Base.DevNullStream}}, Type{Core.Inference.Const}}}) -precompile(Tuple{typeof(Core.Inference.start), Tuple{Tuple{Base.DevNullStream, Base.DevNullStream, Base.DevNullStream}}}) -precompile(Tuple{typeof(Core.Inference.done), Core.Inference.Generator{Tuple{Tuple{Base.DevNullStream, Base.DevNullStream, Base.DevNullStream}}, Type{Core.Inference.Const}}, Int64}) -precompile(Tuple{typeof(Core.Inference.done), Tuple{Tuple{Base.DevNullStream, Base.DevNullStream, Base.DevNullStream}}, Int64}) -precompile(Tuple{typeof(Core.Inference.next), Core.Inference.Generator{Tuple{Tuple{Base.DevNullStream, Base.DevNullStream, Base.DevNullStream}}, Type{Core.Inference.Const}}, Int64}) -precompile(Tuple{typeof(Core.Inference.next), Tuple{Tuple{Base.DevNullStream, Base.DevNullStream, Base.DevNullStream}}, Int64}) -precompile(Tuple{typeof(Core.Inference.getindex), Tuple{Tuple{Base.DevNullStream, Base.DevNullStream, Base.DevNullStream}}, Int64}) -precompile(Tuple{typeof(Core.Inference.start), Tuple{Tuple{Base.DevNullStream, Base.DevNullStream, Base.DevNullStream}, Int64}}) -precompile(Tuple{typeof(Core.Inference.indexed_next), Tuple{Tuple{Base.DevNullStream, Base.DevNullStream, Base.DevNullStream}, Int64}, Int64, Int64}) -precompile(Tuple{typeof(Core.Inference.getindex), Tuple{Tuple{Base.DevNullStream, Base.DevNullStream, Base.DevNullStream}, Int64}, Int64}) -precompile(Tuple{typeof(Core.Inference.isbits), Tuple{Base.DevNullStream, Base.DevNullStream, Base.DevNullStream}}) -precompile(Tuple{typeof(Core.Inference.isbits), Tuple{Tuple{Base.DevNullStream, Base.DevNullStream, Base.DevNullStream}}}) -precompile(Tuple{Type{Core.Inference.Generator{I, F} where F where I}, Type{QuoteNode}, Tuple{Tuple{Base.DevNullStream, Base.DevNullStream, Base.DevNullStream}}}) -precompile(Tuple{Type{Core.Inference.Generator{Tuple{Tuple{Base.DevNullStream, Base.DevNullStream, Base.DevNullStream}}, Type{QuoteNode}}}, Type{QuoteNode}, Tuple{Tuple{Base.DevNullStream, Base.DevNullStream, Base.DevNullStream}}}) -precompile(Tuple{typeof(Core.Inference.iteratorsize), Type{Core.Inference.Generator{Tuple{Tuple{Base.DevNullStream, Base.DevNullStream, Base.DevNullStream}}, Type{QuoteNode}}}}) -precompile(Tuple{typeof(Core.Inference._collect), Type{Any}, Core.Inference.Generator{Tuple{Tuple{Base.DevNullStream, Base.DevNullStream, Base.DevNullStream}}, Type{QuoteNode}}, Core.Inference.HasLength}) -precompile(Tuple{typeof(Core.Inference.length), Core.Inference.Generator{Tuple{Tuple{Base.DevNullStream, Base.DevNullStream, Base.DevNullStream}}, Type{QuoteNode}}}) -precompile(Tuple{typeof(Core.Inference.copy!), Array{Any, 1}, Core.Inference.Generator{Tuple{Tuple{Base.DevNullStream, Base.DevNullStream, Base.DevNullStream}}, Type{QuoteNode}}}) -precompile(Tuple{typeof(Core.Inference.start), Core.Inference.Generator{Tuple{Tuple{Base.DevNullStream, Base.DevNullStream, Base.DevNullStream}}, Type{QuoteNode}}}) -precompile(Tuple{typeof(Core.Inference.done), Core.Inference.Generator{Tuple{Tuple{Base.DevNullStream, Base.DevNullStream, Base.DevNullStream}}, Type{QuoteNode}}, Int64}) -precompile(Tuple{typeof(Core.Inference.next), Core.Inference.Generator{Tuple{Tuple{Base.DevNullStream, Base.DevNullStream, Base.DevNullStream}}, Type{QuoteNode}}, Int64}) -precompile(Tuple{typeof(Core.Inference.isbits), Base.DevNullStream}) -precompile(Tuple{typeof(Base.finalizer), Base.Process, typeof(Base.uvfinalize)}) -precompile(Tuple{typeof(Core.Inference.isbits), Tuple{Base.DevNullStream, Bool}}) -precompile(Tuple{Type{Ref{Base.Cstring}}, Array{String, 1}}) -precompile(Tuple{typeof(Core.Inference.eltype), Type{Array{String, 1}}}) -precompile(Tuple{typeof(Base.string), Void, String, DataType}) -precompile(Tuple{typeof(Base.print), Base.IOContext{Base.AbstractIOBuffer{Array{UInt8, 1}}}, String, Char}) -precompile(Tuple{typeof(Base.throw_boundserror), Base.UnitRange{Int64}, Tuple{Base.UnitRange{Int64}}}) -precompile(Tuple{typeof(Core.Inference.convert), Type{DataType}, Type{Bool}}) -precompile(Tuple{typeof(Core.Inference.convert), Type{DataType}, Type{Base.OneTo{Int64}}}) -precompile(Tuple{typeof(Core.Inference.length), Tuple{DataType, DataType, typeof(Type), Core.Inference.Const, Core.Inference.Const}}) -precompile(Tuple{typeof(Core.Inference.getindex), Tuple{DataType, DataType, typeof(Type), Core.Inference.Const, Core.Inference.Const}, Int64}) -precompile(Tuple{Type{Core.Inference.Generator{I, F} where F where I}, Type{Core.Inference.Const}, Tuple{Tuple{}, Tuple{}, Int64}}) -precompile(Tuple{Type{Core.Inference.Generator{Tuple{Tuple{}, Tuple{}, Int64}, Type{Core.Inference.Const}}}, Type{Core.Inference.Const}, Tuple{Tuple{}, Tuple{}, Int64}}) -precompile(Tuple{typeof(Core.Inference.convert), Type{Tuple{Tuple{}, Tuple{}, Int64}}, Tuple{Tuple{}, Tuple{}, Int64}}) -precompile(Tuple{typeof(Core.Inference.collect), Type{Any}, Core.Inference.Generator{Tuple{Tuple{}, Tuple{}, Int64}, Type{Core.Inference.Const}}}) -precompile(Tuple{typeof(Core.Inference.iteratorsize), Core.Inference.Generator{Tuple{Tuple{}, Tuple{}, Int64}, Type{Core.Inference.Const}}}) -precompile(Tuple{typeof(Core.Inference.iteratorsize), Type{Core.Inference.Generator{Tuple{Tuple{}, Tuple{}, Int64}, Type{Core.Inference.Const}}}}) -precompile(Tuple{typeof(Core.Inference.iteratorsize), Type{Tuple{Tuple{}, Tuple{}, Int64}}}) -precompile(Tuple{typeof(Core.Inference._collect), Type{Any}, Core.Inference.Generator{Tuple{Tuple{}, Tuple{}, Int64}, Type{Core.Inference.Const}}, Core.Inference.HasLength}) -precompile(Tuple{typeof(Core.Inference.length), Core.Inference.Generator{Tuple{Tuple{}, Tuple{}, Int64}, Type{Core.Inference.Const}}}) -precompile(Tuple{typeof(Core.Inference.length), Tuple{Tuple{}, Tuple{}, Int64}}) -precompile(Tuple{typeof(Core.Inference.copy!), Array{Any, 1}, Core.Inference.Generator{Tuple{Tuple{}, Tuple{}, Int64}, Type{Core.Inference.Const}}}) -precompile(Tuple{typeof(Core.Inference.start), Core.Inference.Generator{Tuple{Tuple{}, Tuple{}, Int64}, Type{Core.Inference.Const}}}) -precompile(Tuple{typeof(Core.Inference.start), Tuple{Tuple{}, Tuple{}, Int64}}) -precompile(Tuple{typeof(Core.Inference.done), Core.Inference.Generator{Tuple{Tuple{}, Tuple{}, Int64}, Type{Core.Inference.Const}}, Int64}) -precompile(Tuple{typeof(Core.Inference.done), Tuple{Tuple{}, Tuple{}, Int64}, Int64}) -precompile(Tuple{typeof(Core.Inference.next), Core.Inference.Generator{Tuple{Tuple{}, Tuple{}, Int64}, Type{Core.Inference.Const}}, Int64}) -precompile(Tuple{typeof(Core.Inference.next), Tuple{Tuple{}, Tuple{}, Int64}, Int64}) -precompile(Tuple{typeof(Core.Inference.getindex), Tuple{Tuple{}, Tuple{}, Int64}, Int64}) -precompile(Tuple{typeof(Core.Inference.isbits), Tuple{Tuple{}, Tuple{}, Int64}}) -precompile(Tuple{Type{Core.Inference.Generator{I, F} where F where I}, Type{QuoteNode}, Tuple{Tuple{}, Tuple{}, Int64}}) -precompile(Tuple{Type{Core.Inference.Generator{Tuple{Tuple{}, Tuple{}, Int64}, Type{QuoteNode}}}, Type{QuoteNode}, Tuple{Tuple{}, Tuple{}, Int64}}) -precompile(Tuple{typeof(Core.Inference.iteratorsize), Type{Core.Inference.Generator{Tuple{Tuple{}, Tuple{}, Int64}, Type{QuoteNode}}}}) -precompile(Tuple{typeof(Core.Inference._collect), Type{Any}, Core.Inference.Generator{Tuple{Tuple{}, Tuple{}, Int64}, Type{QuoteNode}}, Core.Inference.HasLength}) -precompile(Tuple{typeof(Core.Inference.length), Core.Inference.Generator{Tuple{Tuple{}, Tuple{}, Int64}, Type{QuoteNode}}}) -precompile(Tuple{typeof(Core.Inference.copy!), Array{Any, 1}, Core.Inference.Generator{Tuple{Tuple{}, Tuple{}, Int64}, Type{QuoteNode}}}) -precompile(Tuple{typeof(Core.Inference.start), Core.Inference.Generator{Tuple{Tuple{}, Tuple{}, Int64}, Type{QuoteNode}}}) -precompile(Tuple{typeof(Core.Inference.done), Core.Inference.Generator{Tuple{Tuple{}, Tuple{}, Int64}, Type{QuoteNode}}, Int64}) -precompile(Tuple{typeof(Core.Inference.next), Core.Inference.Generator{Tuple{Tuple{}, Tuple{}, Int64}, Type{QuoteNode}}, Int64}) -precompile(Tuple{Type{Core.Inference.Generator{I, F} where F where I}, Type{Core.Inference.Const}, Tuple{Tuple{}, Tuple{}}}) -precompile(Tuple{Type{Core.Inference.Generator{Tuple{Tuple{}, Tuple{}}, Type{Core.Inference.Const}}}, Type{Core.Inference.Const}, Tuple{Tuple{}, Tuple{}}}) -precompile(Tuple{typeof(Core.Inference.convert), Type{Tuple{Tuple{}, Tuple{}}}, Tuple{Tuple{}, Tuple{}}}) -precompile(Tuple{typeof(Core.Inference.collect), Type{Any}, Core.Inference.Generator{Tuple{Tuple{}, Tuple{}}, Type{Core.Inference.Const}}}) -precompile(Tuple{typeof(Core.Inference.iteratorsize), Core.Inference.Generator{Tuple{Tuple{}, Tuple{}}, Type{Core.Inference.Const}}}) -precompile(Tuple{typeof(Core.Inference.iteratorsize), Type{Core.Inference.Generator{Tuple{Tuple{}, Tuple{}}, Type{Core.Inference.Const}}}}) -precompile(Tuple{typeof(Core.Inference.iteratorsize), Type{Tuple{Tuple{}, Tuple{}}}}) -precompile(Tuple{typeof(Core.Inference._collect), Type{Any}, Core.Inference.Generator{Tuple{Tuple{}, Tuple{}}, Type{Core.Inference.Const}}, Core.Inference.HasLength}) -precompile(Tuple{typeof(Core.Inference.length), Core.Inference.Generator{Tuple{Tuple{}, Tuple{}}, Type{Core.Inference.Const}}}) -precompile(Tuple{typeof(Core.Inference.length), Tuple{Tuple{}, Tuple{}}}) -precompile(Tuple{typeof(Core.Inference.copy!), Array{Any, 1}, Core.Inference.Generator{Tuple{Tuple{}, Tuple{}}, Type{Core.Inference.Const}}}) -precompile(Tuple{typeof(Core.Inference.start), Core.Inference.Generator{Tuple{Tuple{}, Tuple{}}, Type{Core.Inference.Const}}}) -precompile(Tuple{typeof(Core.Inference.start), Tuple{Tuple{}, Tuple{}}}) -precompile(Tuple{typeof(Core.Inference.done), Core.Inference.Generator{Tuple{Tuple{}, Tuple{}}, Type{Core.Inference.Const}}, Int64}) -precompile(Tuple{typeof(Core.Inference.done), Tuple{Tuple{}, Tuple{}}, Int64}) -precompile(Tuple{typeof(Core.Inference.next), Core.Inference.Generator{Tuple{Tuple{}, Tuple{}}, Type{Core.Inference.Const}}, Int64}) -precompile(Tuple{typeof(Core.Inference.next), Tuple{Tuple{}, Tuple{}}, Int64}) -precompile(Tuple{typeof(Core.Inference.getindex), Tuple{Tuple{}, Tuple{}}, Int64}) -precompile(Tuple{Type{Core.Inference.Generator{I, F} where F where I}, Type{QuoteNode}, Tuple{Tuple{}, Tuple{}}}) -precompile(Tuple{Type{Core.Inference.Generator{Tuple{Tuple{}, Tuple{}}, Type{QuoteNode}}}, Type{QuoteNode}, Tuple{Tuple{}, Tuple{}}}) -precompile(Tuple{typeof(Core.Inference.iteratorsize), Type{Core.Inference.Generator{Tuple{Tuple{}, Tuple{}}, Type{QuoteNode}}}}) -precompile(Tuple{typeof(Core.Inference._collect), Type{Any}, Core.Inference.Generator{Tuple{Tuple{}, Tuple{}}, Type{QuoteNode}}, Core.Inference.HasLength}) -precompile(Tuple{typeof(Core.Inference.length), Core.Inference.Generator{Tuple{Tuple{}, Tuple{}}, Type{QuoteNode}}}) -precompile(Tuple{typeof(Core.Inference.copy!), Array{Any, 1}, Core.Inference.Generator{Tuple{Tuple{}, Tuple{}}, Type{QuoteNode}}}) -precompile(Tuple{typeof(Core.Inference.start), Core.Inference.Generator{Tuple{Tuple{}, Tuple{}}, Type{QuoteNode}}}) -precompile(Tuple{typeof(Core.Inference.done), Core.Inference.Generator{Tuple{Tuple{}, Tuple{}}, Type{QuoteNode}}, Int64}) -precompile(Tuple{typeof(Core.Inference.next), Core.Inference.Generator{Tuple{Tuple{}, Tuple{}}, Type{QuoteNode}}, Int64}) -precompile(Tuple{typeof(Core.Inference.length), Tuple{DataType, DataType, DataType, Core.Inference.Const, Core.Inference.Const}}) -precompile(Tuple{typeof(Core.Inference.getindex), Tuple{DataType, DataType, DataType, Core.Inference.Const, Core.Inference.Const}, Int64}) -precompile(Tuple{typeof(Core.Inference.length), Tuple{DataType, DataType, typeof(Type), typeof(Type), Core.Inference.Const}}) -precompile(Tuple{typeof(Core.Inference.getindex), Tuple{DataType, DataType, typeof(Type), typeof(Type), Core.Inference.Const}, Int64}) -precompile(Tuple{typeof(Core.Inference.length), Tuple{DataType, DataType, DataType, DataType, Core.Inference.Const}}) -precompile(Tuple{typeof(Core.Inference.getindex), Tuple{DataType, DataType, DataType, DataType, Core.Inference.Const}, Int64}) -precompile(Tuple{typeof(Base.unpreserve_handle), Base.Process}) -precompile(Tuple{typeof(Base.stream_wait), Base.Process, Base.Condition}) -precompile(Tuple{typeof(Base.kill), Base.Process, Int64}) -precompile(Tuple{typeof(Base.banner), Base.Terminals.TTYTerminal}) -precompile(Tuple{typeof(Core.Inference.isbits), Base.Dict{Any, Any}}) -precompile(Tuple{typeof(Base.answer_color)}) -precompile(Tuple{typeof(Base.input_color)}) -precompile(Tuple{typeof(Base.show_circular), Base.IOContext{Base.AbstractIOBuffer{Array{UInt8, 1}}}, Tuple{}}) -precompile(Tuple{typeof(Base.show_delim_array), Base.IOContext{Base.AbstractIOBuffer{Array{UInt8, 1}}}, Tuple{}, Char, Char, Char, Bool, Int64, Int64}) -precompile(Tuple{typeof(Base.throw_boundserror), Array{Base.StackTraces.StackFrame, 1}, Tuple{Base.UnitRange{Int64}}}) -precompile(Tuple{typeof(Base.splice!), Array{Base.StackTraces.StackFrame, 1}, Base.UnitRange{Int64}, Array{Any, 1}}) -precompile(Tuple{typeof(Base.REPL.ip_matches_func), Ptr{Void}, Symbol}) -precompile(Tuple{typeof(Base.throw_boundserror), Array{Ptr{Void}, 1}, Tuple{Base.UnitRange{Int64}}}) -precompile(Tuple{typeof(Base.unsafe_copy!), Array{Ptr{Void}, 1}, Int64, Array{Ptr{Void}, 1}, Int64, Int64}) -precompile(Tuple{Type{Base.Channel{Any}}, Int64}) -precompile(Tuple{typeof(Base.rsearch), String, UInt8, Int64}) -precompile(Tuple{typeof(Base.rsearch), String, Char, Int64}) -precompile(Tuple{typeof(Base.rsearch), Array{UInt8, 1}, UInt8, Int64}) -precompile(Tuple{typeof(Base._rsearchindex), Array{UInt8, 1}, Array{UInt8, 1}, Int64}) -precompile(Tuple{typeof(Base._rsearch), Array{UInt8, 1}, Array{UInt8, 1}, Int64}) -precompile(Tuple{typeof(Base.rsearch), Array{Int8, 1}, UInt8, Int64}) -precompile(Tuple{typeof(Base._rsearchindex), Array{Int8, 1}, Array{UInt8, 1}, Int64}) -precompile(Tuple{typeof(Base._rsearch), Array{Int8, 1}, Array{UInt8, 1}, Int64}) -precompile(Tuple{typeof(Base.rsearch), Array{UInt8, 1}, Char, Int64}) -precompile(Tuple{typeof(Base.rsearch), Array{Int8, 1}, Char, Int64}) -precompile(Tuple{typeof(Base.splice!), Array{Base.Multimedia.Display, 1}, Int64, Array{Any, 1}}) -precompile(Tuple{typeof(Core.Inference.isbits), Base.LineEdit.EmptyCompletionProvider}) -precompile(Tuple{typeof(Core.Inference.isbits), Base.LineEdit.EmptyHistoryProvider}) -precompile(Tuple{typeof(Base._setindex!), Base.Dict{Symbol, Any}, Base.LineEdit.Prompt, Symbol, Int64}) -precompile(Tuple{typeof(Base.sizehint!), Base.Dict{Symbol, Any}, Int64}) -precompile(Tuple{typeof(Base.setindex!), Base.Dict{Symbol, Any}, Base.LineEdit.Prompt, Symbol}) -precompile(Tuple{typeof(Base.copy!), Base.IndexLinear, Array{Symbol, 1}, Base.IndexLinear, Array{UInt8, 1}}) -precompile(Tuple{getfield(Base, Symbol("#kw##readline")), Array{Any, 1}, typeof(Base.readline), Base.IOStream}) -precompile(Tuple{Type{Core.Inference.Generator{I, F} where F where I}, Type{Core.Inference.Const}, Tuple{Void}}) -precompile(Tuple{Type{Core.Inference.Generator{Tuple{Void}, Type{Core.Inference.Const}}}, Type{Core.Inference.Const}, Tuple{Void}}) -precompile(Tuple{typeof(Core.Inference.convert), Type{Tuple{Void}}, Tuple{Void}}) -precompile(Tuple{typeof(Core.Inference.collect), Type{Any}, Core.Inference.Generator{Tuple{Void}, Type{Core.Inference.Const}}}) -precompile(Tuple{typeof(Core.Inference.iteratorsize), Core.Inference.Generator{Tuple{Void}, Type{Core.Inference.Const}}}) -precompile(Tuple{typeof(Core.Inference.iteratorsize), Type{Core.Inference.Generator{Tuple{Void}, Type{Core.Inference.Const}}}}) -precompile(Tuple{typeof(Core.Inference.iteratorsize), Type{Tuple{Void}}}) -precompile(Tuple{typeof(Core.Inference._collect), Type{Any}, Core.Inference.Generator{Tuple{Void}, Type{Core.Inference.Const}}, Core.Inference.HasLength}) -precompile(Tuple{typeof(Core.Inference.length), Core.Inference.Generator{Tuple{Void}, Type{Core.Inference.Const}}}) -precompile(Tuple{typeof(Core.Inference.length), Tuple{Void}}) -precompile(Tuple{typeof(Core.Inference.copy!), Array{Any, 1}, Core.Inference.Generator{Tuple{Void}, Type{Core.Inference.Const}}}) -precompile(Tuple{typeof(Core.Inference.start), Core.Inference.Generator{Tuple{Void}, Type{Core.Inference.Const}}}) -precompile(Tuple{typeof(Core.Inference.start), Tuple{Void}}) -precompile(Tuple{typeof(Core.Inference.done), Core.Inference.Generator{Tuple{Void}, Type{Core.Inference.Const}}, Int64}) -precompile(Tuple{typeof(Core.Inference.done), Tuple{Void}, Int64}) -precompile(Tuple{typeof(Core.Inference.next), Core.Inference.Generator{Tuple{Void}, Type{Core.Inference.Const}}, Int64}) -precompile(Tuple{typeof(Core.Inference.next), Tuple{Void}, Int64}) -precompile(Tuple{typeof(Core.Inference.getindex), Tuple{Void}, Int64}) -precompile(Tuple{typeof(Base.join), Base.AbstractIOBuffer{Array{UInt8, 1}}, Array{String, 1}, Char}) -precompile(Tuple{Type{Core.Inference.Generator{I, F} where F where I}, Type{Core.Inference.Const}, Tuple{String, typeof(Base.info)}}) -precompile(Tuple{Type{Core.Inference.Generator{Tuple{String, typeof(Base.info)}, Type{Core.Inference.Const}}}, Type{Core.Inference.Const}, Tuple{String, typeof(Base.info)}}) -precompile(Tuple{typeof(Core.Inference.convert), Type{Tuple{String, typeof(Base.info)}}, Tuple{String, typeof(Base.info)}}) -precompile(Tuple{typeof(Core.Inference.collect), Type{Any}, Core.Inference.Generator{Tuple{String, typeof(Base.info)}, Type{Core.Inference.Const}}}) -precompile(Tuple{typeof(Core.Inference.iteratorsize), Core.Inference.Generator{Tuple{String, typeof(Base.info)}, Type{Core.Inference.Const}}}) -precompile(Tuple{typeof(Core.Inference.iteratorsize), Type{Core.Inference.Generator{Tuple{String, typeof(Base.info)}, Type{Core.Inference.Const}}}}) -precompile(Tuple{typeof(Core.Inference.iteratorsize), Type{Tuple{String, typeof(Base.info)}}}) -precompile(Tuple{typeof(Core.Inference._collect), Type{Any}, Core.Inference.Generator{Tuple{String, typeof(Base.info)}, Type{Core.Inference.Const}}, Core.Inference.HasLength}) -precompile(Tuple{typeof(Core.Inference.length), Core.Inference.Generator{Tuple{String, typeof(Base.info)}, Type{Core.Inference.Const}}}) -precompile(Tuple{typeof(Core.Inference.length), Tuple{String, typeof(Base.info)}}) -precompile(Tuple{typeof(Core.Inference.copy!), Array{Any, 1}, Core.Inference.Generator{Tuple{String, typeof(Base.info)}, Type{Core.Inference.Const}}}) -precompile(Tuple{typeof(Core.Inference.start), Core.Inference.Generator{Tuple{String, typeof(Base.info)}, Type{Core.Inference.Const}}}) -precompile(Tuple{typeof(Core.Inference.start), Tuple{String, typeof(Base.info)}}) -precompile(Tuple{typeof(Core.Inference.done), Core.Inference.Generator{Tuple{String, typeof(Base.info)}, Type{Core.Inference.Const}}, Int64}) -precompile(Tuple{typeof(Core.Inference.done), Tuple{String, typeof(Base.info)}, Int64}) -precompile(Tuple{typeof(Core.Inference.next), Core.Inference.Generator{Tuple{String, typeof(Base.info)}, Type{Core.Inference.Const}}, Int64}) -precompile(Tuple{typeof(Core.Inference.next), Tuple{String, typeof(Base.info)}, Int64}) -precompile(Tuple{typeof(Core.Inference.getindex), Tuple{String, typeof(Base.info)}, Int64}) -precompile(Tuple{typeof(Core.Inference.start), Tuple{String, Int64}}) -precompile(Tuple{typeof(Core.Inference.start), Tuple{typeof(Base.info), Int64}}) -precompile(Tuple{typeof(Core.Inference.indexed_next), Tuple{typeof(Base.info), Int64}, Int64, Int64}) -precompile(Tuple{typeof(Core.Inference.getindex), Tuple{typeof(Base.info), Int64}, Int64}) -precompile(Tuple{typeof(Base.print), Base.IOContext{Base.AbstractIOBuffer{Array{UInt8, 1}}}, Base.SubString{String}, Char}) -precompile(Tuple{typeof(Base.sizehint!), Base.Dict{Any, Any}, Int64}) -precompile(Tuple{typeof(Base.LineEdit.getEntry), Base.Dict{Char, Any}, Char}) -precompile(Tuple{typeof(Base.LineEdit.getEntry), Base.Dict{Char, Any}, String}) -precompile(Tuple{typeof(Base.unsafe_copy!), Array{Base.Dict{Any, Any}, 1}, Int64, Array{Base.Dict{Any, Any}, 1}, Int64, Int64}) -precompile(Tuple{typeof(Base.copy!), Array{Base.Dict{Any, Any}, 1}, Int64, Array{Base.Dict{Any, Any}, 1}, Int64, Int64}) -precompile(Tuple{typeof(Base.promote_type), Type{Base.LineEdit.HistoryPrompt{Base.REPL.REPLHistoryProvider}}, Type{Base.LineEdit.PrefixHistoryPrompt{Base.REPL.REPLHistoryProvider}}}) -precompile(Tuple{typeof(Base.promote_rule), Type{Base.LineEdit.HistoryPrompt{Base.REPL.REPLHistoryProvider}}, Type{Base.LineEdit.PrefixHistoryPrompt{Base.REPL.REPLHistoryProvider}}}) -precompile(Tuple{typeof(Base.promote_rule), Type{Base.LineEdit.PrefixHistoryPrompt{Base.REPL.REPLHistoryProvider}}, Type{Base.LineEdit.HistoryPrompt{Base.REPL.REPLHistoryProvider}}}) -precompile(Tuple{typeof(Base.promote_result), Type{Base.LineEdit.HistoryPrompt{Base.REPL.REPLHistoryProvider}}, Type{Base.LineEdit.PrefixHistoryPrompt{Base.REPL.REPLHistoryProvider}}, Type{Union{}}, Type{Union{}}}) -precompile(Tuple{typeof(Base.promote_type), Type{Base.LineEdit.Prompt}, Type{Base.LineEdit.TextInterface}}) -precompile(Tuple{typeof(Base.promote_rule), Type{Base.LineEdit.Prompt}, Type{Base.LineEdit.TextInterface}}) -precompile(Tuple{typeof(Base.promote_rule), Type{Base.LineEdit.TextInterface}, Type{Base.LineEdit.Prompt}}) -precompile(Tuple{typeof(Base.promote_result), Type{Base.LineEdit.Prompt}, Type{Base.LineEdit.TextInterface}, Type{Union{}}, Type{Union{}}}) -precompile(Tuple{typeof(Base.setindex!), Array{Base.LineEdit.TextInterface, 1}, Base.LineEdit.Prompt, Int64}) -precompile(Tuple{typeof(Base.setindex!), Array{Base.LineEdit.TextInterface, 1}, Base.LineEdit.HistoryPrompt{Base.REPL.REPLHistoryProvider}, Int64}) -precompile(Tuple{typeof(Base.setindex!), Array{Base.LineEdit.TextInterface, 1}, Base.LineEdit.PrefixHistoryPrompt{Base.REPL.REPLHistoryProvider}, Int64}) -precompile(Tuple{typeof(Base.copy!), Array{Base.LineEdit.TextInterface, 1}, Tuple{Base.LineEdit.Prompt, Base.LineEdit.Prompt, Base.LineEdit.Prompt, Base.LineEdit.HistoryPrompt{Base.REPL.REPLHistoryProvider}, Base.LineEdit.PrefixHistoryPrompt{Base.REPL.REPLHistoryProvider}}}) -precompile(Tuple{typeof(Base.print), Base.AbstractIOBuffer{Array{UInt8, 1}}, String, Int64, String, Bool}) -precompile(Tuple{typeof(Base.uv_status_string), Base.UDPSocket}) -precompile(Tuple{typeof(Base.Terminals.cmove_up), Base.Terminals.TerminalBuffer, Int64}) -precompile(Tuple{typeof(Base.Terminals.cmove_down), Base.Terminals.TerminalBuffer, Int64}) -precompile(Tuple{typeof(Base.readuntil), Base.AbstractIOBuffer{Array{UInt8, 1}}, UInt8}) -precompile(Tuple{typeof(Base.Terminals.cmove_right), Base.Terminals.TerminalBuffer, Int64}) -precompile(Tuple{typeof(Base.LineEdit._clear_input_area), Base.Terminals.TerminalBuffer, Base.LineEdit.InputAreaState}) -precompile(Tuple{typeof(Base.seek), Base.AbstractIOBuffer{Array{UInt8, 1}}, Int64}) -precompile(Tuple{getfield(Base, Symbol("#kw##readline")), Array{Any, 1}, typeof(Base.readline), Base.AbstractIOBuffer{Array{UInt8, 1}}}) -precompile(Tuple{typeof(Base.endswith), String, String}) -precompile(Tuple{getfield(Base, Symbol("#kw##readline")), Array{Any, 1}, typeof(Base.readline), Base.Terminals.TerminalBuffer}) -precompile(Tuple{typeof(Base.LineEdit.write_prompt), Base.Terminals.TerminalBuffer, Base.LineEdit.Prompt}) -precompile(Tuple{getfield(Base.LineEdit, Symbol("#kw##refresh_multi_line")), Array{Any, 1}, typeof(Base.LineEdit.refresh_multi_line), Base.Terminals.TerminalBuffer, Base.Terminals.TerminalBuffer, Base.Terminals.TerminalBuffer, Base.LineEdit.InputAreaState, String}) -precompile(Tuple{typeof(Base.:(==)), Array{Char, 1}, Array{Char, 1}}) -precompile(Tuple{typeof(Base.LineEdit.update_key_repeats), Base.LineEdit.MIState, Array{Char, 1}}) -precompile(Tuple{typeof(Base.LineEdit.reset_state), Base.LineEdit.MIState}) -precompile(Tuple{Type{Base.Dict{Any, Any}}, Array{Any, 1}}) -precompile(Tuple{typeof(Base.Distributed.default_addprocs_params)}) -precompile(Tuple{typeof(Base.Distributed.topology), Symbol}) -precompile(Tuple{typeof(Base.shift!), Array{Base.Distributed.WorkerConfig, 1}}) -precompile(Tuple{typeof(Base.sync_end)}) -precompile(Tuple{typeof(Base.wait), Task}) -precompile(Tuple{typeof(Base.Distributed.workers)}) -precompile(Tuple{typeof(Base.sort!), Array{Int64, 1}}) -precompile(Tuple{typeof(Base.lock), Base.ReentrantLock}) -precompile(Tuple{getfield(Base.Distributed, Symbol("#kw##addprocs_locked")), Array{Any, 1}, typeof(Base.Distributed.addprocs_locked), Base.Distributed.SSHManager}) -precompile(Tuple{typeof(Base.unlock), Base.ReentrantLock}) -precompile(Tuple{typeof(Base.Distributed.check_addprocs_args), Array{Any, 1}}) -precompile(Tuple{Type{Base.Distributed.SSHManager}, Array{Any, 1}}) -precompile(Tuple{getfield(Base.Distributed, Symbol("#kw##addprocs")), Array{Any, 1}, typeof(Base.Distributed.addprocs), Base.Distributed.SSHManager}) -precompile(Tuple{typeof(Base.cmd_gen), Tuple{Tuple{}}}) -precompile(Tuple{typeof(Base.extrema), Array{Int64, 1}}) -precompile(Tuple{typeof(Base.Sort.sort_int_range!), Array{Int64, 1}, Int64, Int64}) -precompile(Tuple{typeof(Core.Inference.isbits), Base.Sort.QuickSortAlg}) -precompile(Tuple{getfield(Base.Distributed, Symbol("#kw##addprocs_locked")), Array{Any, 1}, typeof(Base.Distributed.addprocs_locked), Base.Distributed.LocalManager}) -precompile(Tuple{typeof(Base.ht_keyindex2), Base.Dict{Any, Any}, Symbol}) -precompile(Tuple{typeof(Base._setindex!), Base.Dict{Any, Any}, Symbol, Symbol, Int64}) -precompile(Tuple{Type{Base.Dict{Any, Any}}, Base.Pair{Symbol, Symbol}, Base.Pair{Symbol, String}, Base.Pair{Symbol, String}, Base.Pair{Symbol, Base.Cmd}, Base.Pair{Symbol, Bool}}) -precompile(Tuple{getfield(Base.Distributed, Symbol("#kw##addprocs")), Array{Any, 1}, typeof(Base.Distributed.addprocs), Base.Distributed.LocalManager}) -precompile(Tuple{typeof(Base.listenany), Base.IPv4, UInt16}) -precompile(Tuple{typeof(Base.Distributed.check_master_connect)}) -precompile(Tuple{typeof(Base.load_machine_file), String}) -precompile(Tuple{typeof(Base.load_juliarc)}) -precompile(Tuple{typeof(Base.shift!), Array{String, 1}}) -precompile(Tuple{typeof(Base.print), Base.IOContext{Base.AbstractIOBuffer{Array{UInt8, 1}}}, String, String, Char}) -precompile(Tuple{typeof(Base.read), Base.AbstractIOBuffer{Array{UInt8, 1}}, Type{Char}}) -precompile(Tuple{typeof(Base.write), Base.Terminals.TerminalBuffer, Array{UInt8, 1}}) -precompile(Tuple{typeof(Base.LineEdit.keymap), Array{Base.Dict{Any, Any}, 1}}) -precompile(Tuple{typeof(Base.LineEdit.add_specialisations), Base.Dict{Char, Any}, Base.Dict{Char, Any}, Int64}) -precompile(Tuple{typeof(Base.setindex!), Base.Dict{Char, Any}, Base.Dict{Char, Any}, Char}) -precompile(Tuple{typeof(Base.ht_keyindex2), Base.Dict{Char, Any}, Char}) -precompile(Tuple{typeof(Base._setindex!), Base.Dict{Char, Any}, Base.Dict{Char, Any}, Char, Int64}) -precompile(Tuple{typeof(Base.setdiff), Base.KeyIterator{Base.Dict{Any, Any}}, Base.KeyIterator{Base.Dict{Any, Any}}}) -precompile(Tuple{typeof(Base.LineEdit.keymap_merge), Base.Dict{Char, Any}, Base.Dict{Any, Any}}) -precompile(Tuple{typeof(Base.LineEdit.postprocess!), Base.Dict{Char, Any}}) -precompile(Tuple{typeof(Base.LineEdit.keymap_unify), Array{Base.Dict{Any, Any}, 1}}) -precompile(Tuple{typeof(Base.LineEdit.validate_keymap), Base.Dict{Char, Any}}) -precompile(Tuple{Type{Expr}, Symbol, GlobalRef, SSAValue, SSAValue, SSAValue, SSAValue, SSAValue, SSAValue, SSAValue, SSAValue, SSAValue, SSAValue, SSAValue, SSAValue, SSAValue, SSAValue, SSAValue, SSAValue, SSAValue, SSAValue, SSAValue, SSAValue, SSAValue, SSAValue, SSAValue, SSAValue, SSAValue, SSAValue, SSAValue, SSAValue, SSAValue, SSAValue, SSAValue, SSAValue, SSAValue, SSAValue, SSAValue, SSAValue, SSAValue, SSAValue, SSAValue}) -precompile(Tuple{typeof(Core.Inference.isbits), Tuple{String, typeof(Base.info)}}) -precompile(Tuple{typeof(Base.:(==)), Void, String}) -precompile(Tuple{Type{Symbol}, Void}) -precompile(Tuple{Type{Symbol}, Base.SubString{String}}) -precompile(Tuple{typeof(Core.Inference.isbits), Base.REPL.REPLCompletionProvider}) -precompile(Tuple{getfield(Core, Symbol("#kw#Type")), Array{Any, 1}, Type{Base.LineEdit.Prompt}, String}) -precompile(Tuple{typeof(Core.Inference.isbits), Base.REPL.ShellCompletionProvider}) -precompile(Tuple{Type{Base.Dict{Symbol, Any}}, Base.Pair{Symbol, Base.LineEdit.Prompt}, Base.Pair{Symbol, Base.LineEdit.Prompt}, Base.Pair{Symbol, Base.LineEdit.Prompt}}) -precompile(Tuple{Type{Base.REPL.REPLHistoryProvider}, Base.Dict{Symbol, Any}}) -precompile(Tuple{typeof(Base.REPL.find_hist_file)}) -precompile(Tuple{typeof(Base.REPL.history_reset_state), Base.REPL.REPLHistoryProvider}) -precompile(Tuple{typeof(Base.LineEdit.setup_search_keymap), Base.REPL.REPLHistoryProvider}) -precompile(Tuple{typeof(Core.Inference.isbits), Base.REPL.LatexCompletions}) -precompile(Tuple{typeof(Base.LineEdit.setup_prefix_keymap), Base.REPL.REPLHistoryProvider, Base.LineEdit.Prompt}) -precompile(Tuple{typeof(Base.getindex), Type{Base.Dict{Any, Any}}, Base.Dict{Any, Any}, Base.Dict{Any, Any}, Base.Dict{Any, Any}, Base.Dict{Any, Any}, Base.Dict{Any, Any}, Base.Dict{Any, Any}}) -precompile(Tuple{typeof(Base.prepend!), Array{Base.Dict{Any, Any}, 1}, Array{Base.Dict{Any, Any}, 1}}) -precompile(Tuple{typeof(Base.REPL.mode_keymap), Base.LineEdit.Prompt}) -precompile(Tuple{typeof(Core.Inference.isbits), Array{Base.Multimedia.Display, 1}}) -precompile(Tuple{typeof(Base.Multimedia.popdisplay), Base.REPL.REPLDisplay{Base.REPL.LineEditREPL}}) -precompile(Tuple{Type{String}, Base.BitArray{1}}) -precompile(Tuple{typeof(Base.REPL.ends_with_semicolon), String}) -precompile(Tuple{typeof(Core.Inference.isbits), Tuple{Void, Int64}}) -precompile(Tuple{typeof(Base.Multimedia.popdisplay), Base.REPL.REPLDisplay{Base.REPL.BasicREPL}}) -precompile(Tuple{typeof(Base.Multimedia.popdisplay), Base.REPL.REPLDisplay{Base.REPL.StreamREPL}}) -precompile(Tuple{typeof(Base.REPL.start_repl_backend), Base.Channel{Any}, Base.Channel{Any}}) -precompile(Tuple{typeof(Base._collect), Array{Ptr{Void}, 1}, Base.Generator{Array{Ptr{Void}, 1}, typeof(Base.StackTraces.lookup)}, Base.EltypeUnknown, Base.HasShape}) -precompile(Tuple{typeof(Base.shift!), Array{Base.StackTraces.StackFrame, 1}}) -precompile(Tuple{typeof(Base.StackTraces.stacktrace), Array{Ptr{Void}, 1}, Bool}) -precompile(Tuple{typeof(Base.success), Base.Process}) -precompile(Tuple{typeof(Base.mapreduce_impl), typeof(Base.success), typeof(Base.:(&)), Array{Base.Process, 1}, Int64, Int64, Int64}) -precompile(Tuple{typeof(Base.string), Base.Cmd}) -precompile(Tuple{typeof(Base.test_success), Base.Process}) -precompile(Tuple{typeof(Base._mapreduce), typeof(Base.success), typeof(Base.:(&)), Base.IndexLinear, Array{Base.Process, 1}}) -precompile(Tuple{typeof(Core.Inference.isbits), Tuple{String, String, String}}) -precompile(Tuple{getfield(Base, Symbol("#kw##shell_escape")), Array{Any, 1}, typeof(Base.shell_escape), Base.Cmd}) -precompile(Tuple{typeof(Base.show), Base.AbstractIOBuffer{Array{UInt8, 1}}, Base.Cmd}) -precompile(Tuple{typeof(Base.print), Base.AbstractIOBuffer{Array{UInt8, 1}}, Base.Cmd}) -precompile(Tuple{typeof(Core.Inference.isbits), Ptr{Void}}) -precompile(Tuple{typeof(Base.cconvert), Type{Ptr{Base.Cstring}}, Ptr{Void}}) -precompile(Tuple{typeof(Base.cconvert), Type{Ptr{Base.Cstring}}, Void}) -precompile(Tuple{typeof(Base.cconvert), Type{Base.Cstring}, Ptr{Void}}) -precompile(Tuple{typeof(Base.unsafe_convert), Type{Ptr{Base.Cstring}}, Ptr{Void}}) -precompile(Tuple{typeof(Base.unsafe_convert), Type{Ptr{Base.Cstring}}, Base.RefArray{Base.Cstring, Array{Base.Cstring, 1}, Any}}) -precompile(Tuple{Type{Base.Process}, Base.Cmd, Ptr{Void}, Base.DevNullStream, Base.DevNullStream, Base.DevNullStream}) -precompile(Tuple{getfield(Base, Symbol("#kw##spawn")), Array{Any, 1}, typeof(Base.spawn), Base.Cmd, Tuple{Base.DevNullStream, Base.DevNullStream, Base.DevNullStream}}) -precompile(Tuple{typeof(Core.Inference.isbits), Tuple{Tuple{String}, Tuple{String}, Tuple{String}}}) -precompile(Tuple{typeof(Base.cmd_gen), Tuple{Tuple{String}, Tuple{String}, Tuple{String}}}) -precompile(Tuple{typeof(Base.append!), Array{String, 1}, Array{Any, 1}}) -precompile(Tuple{typeof(Base.process_options), Base.JLOptions}) -precompile(Tuple{typeof(Base.Terminals.hascolor), Base.Terminals.TTYTerminal}) -precompile(Tuple{Type{Base.REPL.LineEditREPL}, Base.Terminals.TTYTerminal, Bool}) -precompile(Tuple{typeof(Base.close), Base.IOStream}) -precompile(Tuple{typeof(Base._atexit)}) -precompile(Tuple{typeof(Base.Distributed.terminate_all_workers)}) -precompile(Tuple{getfield(Base, Symbol("#kw##notify")), Array{Any, 1}, typeof(Base.notify), Base.Condition, Void}) -precompile(Tuple{typeof(Base.Distributed.local_remotecall_thunk), typeof(Base.exit), Tuple{}, Array{Any, 1}}) -precompile(Tuple{typeof(Base.Distributed.remote_do), typeof(Base.exit), Base.Distributed.Worker}) -precompile(Tuple{typeof(Base.Distributed.remote_do), typeof(Base.exit), Base.Distributed.LocalProcess}) -precompile(Tuple{getfield(Base.Distributed, Symbol("#kw##remote_do")), Array{Any, 1}, typeof(Base.Distributed.remote_do), typeof(Base.exit), Base.Distributed.Worker}) -precompile(Tuple{getfield(Base.Distributed, Symbol("#kw##remote_do")), Array{Any, 1}, typeof(Base.Distributed.remote_do), typeof(Base.exit), Base.Distributed.LocalProcess}) -precompile(Tuple{typeof(Base.Distributed.set_worker_state), Base.Distributed.Worker, Base.Distributed.WorkerState}) -precompile(Tuple{typeof(Base.Distributed.set_worker_state), Base.Distributed.LocalProcess, Base.Distributed.WorkerState}) -precompile(Tuple{getfield(Base.Distributed, Symbol("#kw##rmprocs")), Array{Any, 1}, typeof(Base.Distributed.rmprocs), Array{Int64, 1}}) -precompile(Tuple{typeof(Base.Distributed.interrupt), Array{Int64, 1}}) -precompile(Tuple{typeof(Base.uvfinalize), Base.TTY}) -precompile(Tuple{typeof(Base.uv_status_string), Base.TTY}) -precompile(Tuple{typeof(Base._fd), Base.TTY}) -precompile(Tuple{typeof(Base.print), Base.AbstractIOBuffer{Array{UInt8, 1}}, Base.TTY}) -precompile(Tuple{typeof(Base.unpreserve_handle), Base.TTY}) -precompile(Tuple{typeof(Base.isopen), Base.TTY}) -precompile(Tuple{typeof(Base.stream_wait), Base.TTY, Base.Condition}) -precompile(Tuple{typeof(Base.close), Base.TTY}) -precompile(Tuple{typeof(Base.unsafe_store!), Ptr{Int32}, Int64}) -precompile(Tuple{Type{Base.Terminals.TTYTerminal}, String, Base.TTY, Base.TTY, Base.IOStream}) -precompile(Tuple{typeof(Base.unsafe_write), Base.TTY, Ptr{UInt8}, UInt64}) -precompile(Tuple{typeof(Base.unpreserve_handle), Task}) -precompile(Tuple{typeof(Base.check_open), Base.TTY}) -precompile(Tuple{typeof(Base.stream_wait), Task}) -precompile(Tuple{typeof(Base.uv_write), Base.TTY, Ptr{UInt8}, UInt64}) -precompile(Tuple{typeof(Base.flush), Base.TTY}) -precompile(Tuple{typeof(Base.Distributed.flush_gc_msgs)}) -precompile(Tuple{typeof(Base.__atreplinit), Base.REPL.LineEditREPL}) -precompile(Tuple{typeof(Base.:(==)), Base.Multimedia.TextDisplay, Base.REPL.REPLDisplay{Base.REPL.LineEditREPL}}) -precompile(Tuple{typeof(Base.:(==)), Base.REPL.REPLDisplay{Base.REPL.LineEditREPL}, Base.REPL.REPLDisplay{Base.REPL.LineEditREPL}}) -precompile(Tuple{typeof(Base.REPL.hist_from_file), Base.REPL.REPLHistoryProvider, Base.IOStream, String}) -precompile(Tuple{typeof(Base.REPL.hist_getline), Base.IOStream}) -precompile(Tuple{typeof(Base.push!), Array{String, 1}, Base.SubString{String}}) -precompile(Tuple{typeof(Base.setindex!), Base.Dict{Any, Any}, Char, Char}) -precompile(Tuple{typeof(Base._setindex!), Base.Dict{Any, Any}, Char, Char, Int64}) -precompile(Tuple{typeof(Base.setindex!), Base.Dict{Any, Any}, Base.LineEdit.KeyAlias, Int64}) -precompile(Tuple{typeof(Base.ht_keyindex2), Base.Dict{Any, Any}, Int64}) -precompile(Tuple{typeof(Base._setindex!), Base.Dict{Any, Any}, Base.LineEdit.KeyAlias, Int64, Int64}) -precompile(Tuple{typeof(Base.setindex!), Base.Dict{Any, Any}, String, String}) -precompile(Tuple{typeof(Base._setindex!), Base.Dict{Any, Any}, String, String, Int64}) -precompile(Tuple{typeof(Base.setindex!), Base.Dict{Any, Any}, Void, String}) -precompile(Tuple{typeof(Base._setindex!), Base.Dict{Any, Any}, Void, String, Int64}) -precompile(Tuple{typeof(Base.setindex!), Base.Dict{Any, Any}, Base.LineEdit.KeyAlias, String}) -precompile(Tuple{typeof(Base._setindex!), Base.Dict{Any, Any}, Base.LineEdit.KeyAlias, String, Int64}) -precompile(Tuple{typeof(Base.setindex!), Base.Dict{Any, Any}, Char, String}) -precompile(Tuple{typeof(Base._setindex!), Base.Dict{Any, Any}, Char, String, Int64}) -precompile(Tuple{getfield(Base.LineEdit, Symbol("#kw##add_nested_key!")), Array{Any, 1}, typeof(Base.LineEdit.add_nested_key!), Base.Dict{Char, Any}, String, Void}) -precompile(Tuple{typeof(Base._setindex!), Base.Dict{Char, Any}, Void, Char, Int64}) -precompile(Tuple{typeof(Base.setindex!), Base.Dict{Char, Any}, Void, Char}) -precompile(Tuple{getfield(Base.LineEdit, Symbol("#kw##add_nested_key!")), Array{Any, 1}, typeof(Base.LineEdit.add_nested_key!), Base.Dict{Char, Any}, String, Base.LineEdit.KeyAlias}) -precompile(Tuple{typeof(Base._setindex!), Base.Dict{Char, Any}, Base.LineEdit.KeyAlias, Char, Int64}) -precompile(Tuple{typeof(Base.setindex!), Base.Dict{Char, Any}, Base.LineEdit.KeyAlias, Char}) -precompile(Tuple{typeof(Base.setindex!), Base.Dict{Any, Void}, Void, String}) -precompile(Tuple{typeof(Base.ht_keyindex2), Base.Dict{Any, Void}, String}) -precompile(Tuple{typeof(Base._setindex!), Base.Dict{Any, Void}, Void, String, Int64}) -precompile(Tuple{typeof(Base.LineEdit.fixup_keymaps!), Base.Dict{Char, Any}, Int64, Char, Void}) -precompile(Tuple{typeof(Base.LineEdit.run_interface), Base.Terminals.TTYTerminal, Base.LineEdit.ModalInterface}) -precompile(Tuple{getfield(Base.LineEdit, Symbol("#kw##refresh_multi_line")), Array{Any, 1}, typeof(Base.LineEdit.refresh_multi_line), Base.Terminals.TerminalBuffer, Base.Terminals.TTYTerminal, Base.AbstractIOBuffer{Array{UInt8, 1}}, Base.LineEdit.InputAreaState, Base.LineEdit.PromptState}) -precompile(Tuple{getfield(Base.LineEdit, Symbol("#kw##refresh_multi_line")), Array{Any, 1}, typeof(Base.LineEdit.refresh_multi_line), Base.Terminals.TerminalBuffer, Base.Terminals.TTYTerminal, Base.AbstractIOBuffer{Array{UInt8, 1}}, Base.LineEdit.InputAreaState, Base.LineEdit.PrefixSearchState}) -precompile(Tuple{typeof(Base.write), Base.Terminals.TTYTerminal, Array{UInt8, 1}}) -precompile(Tuple{typeof(Base.LineEdit.init_state), Base.Terminals.TTYTerminal, Base.LineEdit.ModalInterface}) -precompile(Tuple{typeof(Base.LineEdit.prompt!), Base.Terminals.TTYTerminal, Base.LineEdit.ModalInterface, Base.LineEdit.MIState}) -precompile(Tuple{typeof(Base.getindex), Array{Base.LineEdit.TextInterface, 1}, Int64}) -precompile(Tuple{typeof(Base.start), Array{Base.LineEdit.TextInterface, 1}}) -precompile(Tuple{typeof(Base.done), Array{Base.LineEdit.TextInterface, 1}, Int64}) -precompile(Tuple{typeof(Base.next), Array{Base.LineEdit.TextInterface, 1}, Int64}) -precompile(Tuple{typeof(Base.LineEdit.init_state), Base.Terminals.TTYTerminal, Base.LineEdit.Prompt}) -precompile(Tuple{typeof(Base.setindex!), Base.Dict{Any, Any}, Base.LineEdit.PromptState, Base.LineEdit.Prompt}) -precompile(Tuple{typeof(Base.ht_keyindex2), Base.Dict{Any, Any}, Base.LineEdit.Prompt}) -precompile(Tuple{typeof(Base._setindex!), Base.Dict{Any, Any}, Base.LineEdit.PromptState, Base.LineEdit.Prompt, Int64}) -precompile(Tuple{typeof(Base.LineEdit.init_state), Base.Terminals.TTYTerminal, Base.LineEdit.HistoryPrompt{Base.REPL.REPLHistoryProvider}}) -precompile(Tuple{typeof(Base.setindex!), Base.Dict{Any, Any}, Base.LineEdit.SearchState, Base.LineEdit.HistoryPrompt{Base.REPL.REPLHistoryProvider}}) -precompile(Tuple{typeof(Base.ht_keyindex2), Base.Dict{Any, Any}, Base.LineEdit.HistoryPrompt{Base.REPL.REPLHistoryProvider}}) -precompile(Tuple{typeof(Base._setindex!), Base.Dict{Any, Any}, Base.LineEdit.SearchState, Base.LineEdit.HistoryPrompt{Base.REPL.REPLHistoryProvider}, Int64}) -precompile(Tuple{typeof(Base.LineEdit.init_state), Base.Terminals.TTYTerminal, Base.LineEdit.PrefixHistoryPrompt{Base.REPL.REPLHistoryProvider}}) -precompile(Tuple{typeof(Base.setindex!), Base.Dict{Any, Any}, Base.LineEdit.PrefixSearchState, Base.LineEdit.PrefixHistoryPrompt{Base.REPL.REPLHistoryProvider}}) -precompile(Tuple{typeof(Base.ht_keyindex2), Base.Dict{Any, Any}, Base.LineEdit.PrefixHistoryPrompt{Base.REPL.REPLHistoryProvider}}) -precompile(Tuple{typeof(Base._setindex!), Base.Dict{Any, Any}, Base.LineEdit.PrefixSearchState, Base.LineEdit.PrefixHistoryPrompt{Base.REPL.REPLHistoryProvider}, Int64}) -precompile(Tuple{typeof(Core.Inference.isbits), Tuple{Tuple{}, Void}}) -precompile(Tuple{typeof(Base.take!), Base.Channel{Any}}) -precompile(Tuple{typeof(Base.n_avail), Base.Channel{Any}}) -precompile(Tuple{typeof(Base.check_channel_state), Base.Channel{Any}}) -precompile(Tuple{typeof(Base.wait_impl), Base.Channel{Any}}) -precompile(Tuple{typeof(Base.wait_unbuffered), Base.Channel{Any}}) -precompile(Tuple{typeof(Base.wait), Base.Channel{Any}}) -precompile(Tuple{typeof(Base.take_unbuffered), Base.Channel{Any}}) -precompile(Tuple{typeof(Base.LineEdit.activate), Base.LineEdit.Prompt, Base.LineEdit.MIState, Base.Terminals.TTYTerminal, Base.Terminals.TTYTerminal}) -precompile(Tuple{typeof(Base.:(==)), Base.LineEdit.Prompt, Base.LineEdit.Prompt}) -precompile(Tuple{typeof(Base.getindex), Base.Dict{Any, Any}, Base.LineEdit.Prompt}) -precompile(Tuple{typeof(Base.ht_keyindex), Base.Dict{Any, Any}, Base.LineEdit.Prompt}) -precompile(Tuple{typeof(Base.LineEdit.activate), Base.LineEdit.Prompt, Base.LineEdit.PromptState, Base.Terminals.TTYTerminal, Base.Terminals.TTYTerminal}) -precompile(Tuple{typeof(Base.LineEdit.refresh_multi_line), Base.Terminals.TerminalBuffer, Base.Terminals.TerminalBuffer, Base.Terminals.TTYTerminal, Base.LineEdit.PromptState}) -precompile(Tuple{getfield(Base.LineEdit, Symbol("#kw##refresh_multi_line")), Array{Any, 1}, typeof(Base.LineEdit.refresh_multi_line), Base.Terminals.TerminalBuffer, Base.Terminals.TerminalBuffer, Base.Terminals.TTYTerminal, Base.LineEdit.PromptState}) -precompile(Tuple{getfield(Base.LineEdit, Symbol("#kw##refresh_multi_line")), Array{Any, 1}, typeof(Base.LineEdit.refresh_multi_line), Base.Terminals.TerminalBuffer, Base.Terminals.TTYTerminal, Base.LineEdit.PromptState}) -precompile(Tuple{typeof(Base.LineEdit.refresh_multi_line), Base.Terminals.TerminalBuffer, Base.Terminals.TTYTerminal, Base.LineEdit.PromptState}) -precompile(Tuple{typeof(Base.displaysize), Base.TTY}) -precompile(Tuple{typeof(Base.divrem), Int64, Int64}) -precompile(Tuple{typeof(Base.LineEdit.match_input), Base.Dict{Char, Any}, Base.LineEdit.MIState}) -precompile(Tuple{typeof(Base.LineEdit.match_input), Base.Dict{Char, Any}, Base.LineEdit.MIState, Base.AbstractIOBuffer{Array{UInt8, 1}}, Array{Char, 1}, Base.Dict{Char, Any}}) -precompile(Tuple{typeof(Base.LineEdit.terminal), Base.LineEdit.PromptState}) -precompile(Tuple{typeof(Base.LineEdit.match_input), Base.Dict{Char, Any}, Base.LineEdit.MIState, Base.Terminals.TTYTerminal, Array{Char, 1}, Base.Dict{Char, Any}}) -precompile(Tuple{typeof(Base.read), Base.Terminals.TTYTerminal, Type{Char}}) -precompile(Tuple{typeof(Base.eof), Base.TTY}) -precompile(Tuple{typeof(Base.isreadable), Base.TTY}) -precompile(Tuple{typeof(Base.start_reading), Base.TTY}) -precompile(Tuple{typeof(Base.wait_readnb), Base.TTY, Int64}) -precompile(Tuple{typeof(Base.alloc_buf_hook), Base.TTY, UInt64}) -precompile(Tuple{typeof(Base.read), Base.TTY, Type{UInt8}}) -precompile(Tuple{typeof(Base.throw_boundserror), Array{UInt8, 1}, Tuple{Base.UnitRange{Int64}}}) -precompile(Tuple{typeof(Base.deleteat!), Array{UInt8, 1}, Base.UnitRange{Int64}}) -precompile(Tuple{typeof(Base.splice!), Array{UInt8, 1}, Base.UnitRange{Int64}, Array{UInt8, 1}}) -precompile(Tuple{typeof(Base.LineEdit.splice_buffer!), Base.AbstractIOBuffer{Array{UInt8, 1}}, Base.UnitRange{Int64}, String}) -precompile(Tuple{typeof(Base.LineEdit.refresh_multi_line), Base.Terminals.TerminalBuffer, Base.LineEdit.PromptState}) -precompile(Tuple{typeof(Base.LineEdit.edit_insert), Base.AbstractIOBuffer{Array{UInt8, 1}}, String}) -precompile(Tuple{typeof(Base.LineEdit.edit_insert), Base.LineEdit.PromptState, String}) -precompile(Tuple{typeof(Base.Terminals.width), Base.Terminals.TTYTerminal}) -precompile(Tuple{Type{Base.Libc.TmStruct}, Float64}) -precompile(Tuple{typeof(Base.Libc.strftime), String, Base.Libc.TmStruct}) -precompile(Tuple{typeof(Base.replace), String, Base.Regex, String, Int64}) -precompile(Tuple{typeof(Base.REPL.mode_idx), Base.REPL.REPLHistoryProvider, Base.LineEdit.Prompt}) -precompile(Tuple{typeof(Base.LineEdit.commit_line), Base.LineEdit.MIState}) -precompile(Tuple{typeof(Base.LineEdit.on_enter), Base.LineEdit.PromptState}) -precompile(Tuple{typeof(Base.REPL.return_callback), Base.LineEdit.PromptState}) -precompile(Tuple{typeof(Base.LineEdit.refresh_multi_line), Base.LineEdit.PromptState}) -precompile(Tuple{typeof(Base.LineEdit.refresh_multi_line), Base.Terminals.TTYTerminal, Base.LineEdit.PromptState}) -precompile(Tuple{typeof(Base.println), Base.Terminals.TTYTerminal}) -precompile(Tuple{typeof(Base.write), Base.Terminals.TTYTerminal, Char}) -precompile(Tuple{typeof(Base.write), Base.TTY, UInt8}) -precompile(Tuple{typeof(Base.unsafe_write), Base.TTY, Base.RefValue{UInt8}, Int64}) -precompile(Tuple{typeof(Base.LineEdit.add_history), Base.LineEdit.PromptState}) -precompile(Tuple{typeof(Base.LineEdit.add_history), Base.REPL.REPLHistoryProvider, Base.LineEdit.PromptState}) -precompile(Tuple{typeof(Base.start), Base.Pair{Symbol, Any}}) -precompile(Tuple{typeof(Base.print), Base.IOStream, String}) -precompile(Tuple{typeof(Base.unsafe_write), Base.IOStream, Ptr{UInt8}, UInt64}) -precompile(Tuple{typeof(Base.flush), Base.IOStream}) -precompile(Tuple{typeof(Base.LineEdit.mode), Base.LineEdit.PromptState}) -precompile(Tuple{typeof(Base.REPL.reset), Base.REPL.LineEditREPL}) -precompile(Tuple{getfield(Base, Symbol("#kw##parse_input_line")), Array{Any, 1}, typeof(Base.parse_input_line), String}) -precompile(Tuple{typeof(Base.put!), Base.Channel{Any}, Tuple{Expr, Int64}}) -precompile(Tuple{typeof(Base.put_buffered), Base.Channel{Any}, Tuple{Expr, Int64}}) -precompile(Tuple{typeof(Base.put_unbuffered), Base.Channel{Any}, Tuple{Expr, Int64}}) -precompile(Tuple{typeof(Base.REPL.eval_user_input), Expr, Base.REPL.REPLBackend}) -precompile(Tuple{typeof(Base.put!), Base.Channel{Any}, Tuple{Int64, Void}}) -precompile(Tuple{typeof(Base.put_buffered), Base.Channel{Any}, Tuple{Int64, Void}}) -precompile(Tuple{typeof(Base.put_unbuffered), Base.Channel{Any}, Tuple{Int64, Void}}) -precompile(Tuple{typeof(Base.start), Tuple{Int64, Void}}) -precompile(Tuple{typeof(Base.REPL.print_response), Base.REPL.LineEditREPL, Int64, Void, Bool, Bool}) -precompile(Tuple{typeof(Base.REPL.print_response), Base.Terminals.TTYTerminal, Int64, Void, Bool, Bool, Void}) -precompile(Tuple{typeof(Base.print), Base.Terminals.TTYTerminal, DataType}) -precompile(Tuple{typeof(Base.print), Base.Terminals.TTYTerminal, Char}) -precompile(Tuple{typeof(Base.print), Base.Terminals.TTYTerminal, String, DataType, String, Char}) -precompile(Tuple{typeof(Base.print), Base.Terminals.TTYTerminal, String, Char}) -precompile(Tuple{Type{Base.IOContext{Base.Terminals.TTYTerminal}}, Base.Terminals.TTYTerminal, Base.ImmutableDict{Symbol, Any}}) -precompile(Tuple{getfield(Base, Symbol("#kw##with_output_color")), Array{Any, 1}, typeof(Base.with_output_color), typeof(Base.print), Symbol, Base.IOContext{Base.Terminals.TTYTerminal}, String}) -precompile(Tuple{getfield(Base, Symbol("#kw##with_output_color")), Array{Any, 1}, typeof(Base.with_output_color), typeof(Base.print), Int64, Base.IOContext{Base.Terminals.TTYTerminal}, String}) -precompile(Tuple{typeof(Base.write), Base.IOContext{Base.Terminals.TTYTerminal}, Symbol}) -precompile(Tuple{typeof(Base.show), Base.IOContext{Base.Terminals.TTYTerminal}, Module}) -precompile(Tuple{typeof(Base.print), Base.IOContext{Base.Terminals.TTYTerminal}, String}) -precompile(Tuple{typeof(Base.print), Base.IOContext{Base.Terminals.TTYTerminal}, Module}) -precompile(Tuple{typeof(Base.show), Base.IOContext{Base.Terminals.TTYTerminal}, Int32}) -precompile(Tuple{typeof(Base.print), Base.IOContext{Base.Terminals.TTYTerminal}, Symbol}) -precompile(Tuple{typeof(Base.print), Base.IOContext{Base.Terminals.TTYTerminal}, Int32}) -precompile(Tuple{typeof(Base.show), Base.IOContext{Base.Terminals.TTYTerminal}, Int64}) -precompile(Tuple{typeof(Base.print), Base.IOContext{Base.Terminals.TTYTerminal}, Int64}) -precompile(Tuple{typeof(Base.print), Base.IOContext{Base.Terminals.TTYTerminal}, String, Int64, String}) -precompile(Tuple{typeof(Base.write), Base.IOContext{Base.Terminals.TTYTerminal}, Char}) -precompile(Tuple{typeof(Base.show_circular), Base.IOContext{Base.Terminals.TTYTerminal}, Array{Any, 1}}) -precompile(Tuple{typeof(Base.show_delim_array), Base.IOContext{Base.Terminals.TTYTerminal}, Array{Any, 1}, Char, Char, Char, Bool, Int64, Int64}) -precompile(Tuple{typeof(Base.join), Base.IOContext{Base.Terminals.TTYTerminal}, Array{Any, 1}, String, String}) -precompile(Tuple{typeof(Base.join), Base.IOContext{Base.Terminals.TTYTerminal}, Tuple{}, String, String}) -precompile(Tuple{typeof(Base.show_method_params), Base.IOContext{Base.Terminals.TTYTerminal}, Array{Any, 1}}) -precompile(Tuple{typeof(Base.print), Base.IOContext{Base.Terminals.TTYTerminal}, String, Module}) -precompile(Tuple{typeof(Base.print), Base.IOContext{Base.Terminals.TTYTerminal}, String, Symbol, String, Int32}) -precompile(Tuple{typeof(Base.show_tuple_as_call), Base.IOContext{Base.Terminals.TTYTerminal}, Symbol, Type}) -precompile(Tuple{typeof(Base.print_with_color), Symbol, Base.IOContext{Base.Terminals.TTYTerminal}, String}) -precompile(Tuple{typeof(Base.print_with_color), Int64, Base.IOContext{Base.Terminals.TTYTerminal}, String}) -precompile(Tuple{typeof(Base.show), Base.IOContext{Base.Terminals.TTYTerminal}, Core.MethodInstance}) -precompile(Tuple{typeof(Base.StackTraces.show_spec_linfo), Base.IOContext{Base.Terminals.TTYTerminal}, Base.StackTraces.StackFrame}) -precompile(Tuple{getfield(Base, Symbol("#kw##show")), Array{Any, 1}, typeof(Base.show), Base.IOContext{Base.Terminals.TTYTerminal}, Base.StackTraces.StackFrame}) -precompile(Tuple{getfield(Base, Symbol("#kw##show_trace_entry")), Array{Any, 1}, typeof(Base.show_trace_entry), Base.IOContext{Base.Terminals.TTYTerminal}, Base.StackTraces.StackFrame, Int64}) -precompile(Tuple{typeof(Base.show_backtrace), Base.Terminals.TTYTerminal, Array{Ptr{Void}, 1}}) -precompile(Tuple{typeof(Base.Multimedia.display), Int64}) -precompile(Tuple{typeof(Core.Inference.isbits), Base.MIME{Symbol("text/plain")}}) -precompile(Tuple{typeof(Core.Inference.isbits), Tuple{typeof(Base.Multimedia.display), typeof(Base.show)}}) -precompile(Tuple{typeof(Base.Multimedia.display), Base.REPL.REPLDisplay{Base.REPL.LineEditREPL}, Int64}) -precompile(Tuple{Type{Base.MIME{Symbol("text/plain")}}}) -precompile(Tuple{typeof(Base.Multimedia.display), Base.REPL.REPLDisplay{Base.REPL.LineEditREPL}, Base.MIME{Symbol("text/plain")}, Int64}) -precompile(Tuple{typeof(Base.start), Base.Pair{Any, Any}}) -precompile(Tuple{typeof(Base.LineEdit.reset_state), Base.LineEdit.PromptState}) -precompile(Tuple{typeof(Base.LineEdit.reset_state), Base.LineEdit.SearchState}) -precompile(Tuple{typeof(Base.LineEdit.reset_state), Base.REPL.REPLHistoryProvider}) -precompile(Tuple{typeof(Base.LineEdit.reset_state), Base.LineEdit.PrefixSearchState}) -precompile(Tuple{typeof(Base.haskey), Base.Dict{Any, Any}, Base.LineEdit.Prompt}) -precompile(Tuple{typeof(Base.LineEdit.deactivate), Base.LineEdit.Prompt, Base.LineEdit.PromptState, Base.Terminals.TerminalBuffer, Base.Terminals.TTYTerminal}) -precompile(Tuple{typeof(Base.LineEdit.activate), Base.LineEdit.Prompt, Base.LineEdit.PromptState, Base.Terminals.TerminalBuffer, Base.Terminals.TTYTerminal}) -precompile(Tuple{typeof(Base.LineEdit.commit_changes), Base.Terminals.TTYTerminal, Base.Terminals.TerminalBuffer}) -precompile(Tuple{typeof(Base.LineEdit.complete_line), Base.LineEdit.PromptState, Int64}) -precompile(Tuple{typeof(Base.LineEdit.input_string_newlines_aftercursor), Base.LineEdit.PromptState}) -precompile(Tuple{typeof(Base.LineEdit.complete_line), Base.REPL.REPLCompletionProvider, Base.LineEdit.PromptState}) -precompile(Tuple{getfield(Base, Symbol("#kw##parse")), Array{Any, 1}, typeof(Base.parse), String}) -precompile(Tuple{typeof(Base.isvalid), Base.RevString{String}, Int64}) -precompile(Tuple{typeof(Base.nextind), Base.RevString{String}, Int64}) -precompile(Tuple{typeof(Base.search), Base.RevString{String}, Array{Char, 1}, Int64}) -precompile(Tuple{typeof(Base.rsearch), String, Array{Char, 1}, Int64}) -precompile(Tuple{getfield(Base.REPLCompletions, Symbol("#kw##find_start_brace")), Array{Any, 1}, typeof(Base.REPLCompletions.find_start_brace), String}) -precompile(Tuple{typeof(Core.Inference.isbits), Tuple{Void, Void, Void}}) -precompile(Tuple{typeof(Base.isidentifier), Base.SubString{String}}) -precompile(Tuple{typeof(Core.Inference.isbits), Tuple{Bool, Void, Void}}) -precompile(Tuple{typeof(Base.Filesystem.readdir), String}) -precompile(Tuple{typeof(Base.cmp), String, Base.SubString{String}}) -precompile(Tuple{typeof(Base.skip_deleted), Base.Dict{String, Void}, Int64}) -precompile(Tuple{typeof(Base.PCRE.exec), Ptr{Void}, String, UInt32, UInt32, Ptr{Void}}) -precompile(Tuple{typeof(Base.PCRE.exec), Ptr{Void}, String, UInt64, UInt32, Ptr{Void}}) -precompile(Tuple{typeof(Base.nextind), String, UInt64}) -precompile(Tuple{typeof(Base.matchall), Base.Regex, String, Bool}) -precompile(Tuple{typeof(Base.skip_deleted), Base.Dict{String, String}, Int64}) -precompile(Tuple{typeof(Base.reverse), String}) -precompile(Tuple{typeof(Core.Inference.isbits), Tuple{Void, Bool}}) -precompile(Tuple{typeof(Base._convert), Type{Array{Method, 1}}, Base.BitArray{1}}) -precompile(Tuple{typeof(Base.unsafe_copy!), Array{Method, 1}, Int64, Array{Method, 1}, Int64, Int64}) -precompile(Tuple{typeof(Base.copy!), Array{Method, 1}, Int64, Array{Method, 1}, Int64, Int64}) -precompile(Tuple{typeof(Core.Inference.length), Tuple{Core.Inference.PartialTypeVar}}) -precompile(Tuple{typeof(Core.Inference.getindex), Tuple{Core.Inference.PartialTypeVar}, Int64}) -precompile(Tuple{typeof(Base.show_delim_array), Base.AbstractIOBuffer{Array{UInt8, 1}}, Array{Any, 1}, Char, Char, Char, Bool, Int64, Int64}) -precompile(Tuple{typeof(Base.join), Base.AbstractIOBuffer{Array{UInt8, 1}}, Array{Any, 1}, String, String}) -precompile(Tuple{typeof(Base.join), Base.AbstractIOBuffer{Array{UInt8, 1}}, Tuple{}, String, String}) -precompile(Tuple{typeof(Base.show_method_params), Base.AbstractIOBuffer{Array{UInt8, 1}}, Array{Any, 1}}) -precompile(Tuple{typeof(Base.print), Base.AbstractIOBuffer{Array{UInt8, 1}}, String, Module}) -precompile(Tuple{typeof(Base.print), Base.AbstractIOBuffer{Array{UInt8, 1}}, String, Symbol, String, Int32}) -precompile(Tuple{typeof(Base.reverseind), String, Int64}) -precompile(Tuple{typeof(Base.Pkg.Dir.path)}) -precompile(Tuple{typeof(Base.promote_type), Type{String}, Type{Union{}}}) -precompile(Tuple{typeof(Base.promote_type), Type{Any}, Type{String}}) -precompile(Tuple{typeof(Base.promote_rule), Type{Any}, Type{String}}) -precompile(Tuple{typeof(Base.promote_rule), Type{String}, Type{Any}}) -precompile(Tuple{typeof(Base.promote_result), Type{Any}, Type{String}, Type{Union{}}, Type{Union{}}}) -precompile(Tuple{typeof(Base.promote_type), Type{String}, Type{Any}}) -precompile(Tuple{typeof(Base.promote_result), Type{String}, Type{Any}, Type{Union{}}, Type{Union{}}}) -precompile(Tuple{typeof(Base.cat_indices), String, Int64}) -precompile(Tuple{typeof(Base.cat_size), String, Int64}) -precompile(Tuple{typeof(Base.setindex!), Array{Any, 1}, String, Base.UnitRange{Int64}}) -precompile(Tuple{typeof(Base._cat), Array{Any, 1}, Tuple{Int64}, Tuple{Bool}, String, Array{Any, 1}, String}) -precompile(Tuple{typeof(Base.cat_t), Type{Base.Val{1}}, Type{Any}, String, Array{Any, 1}, String}) -precompile(Tuple{typeof(Base.Sort.searchsortedfirst), Array{String, 1}, String, Int64, Int64, Base.Order.ForwardOrdering}) -precompile(Tuple{typeof(Base.Sort.searchsortedlast), Array{String, 1}, String, Int64, Int64, Base.Order.ForwardOrdering}) -precompile(Tuple{typeof(Base.Sort.searchsorted), Array{String, 1}, String, Int64, Int64, Base.Order.ForwardOrdering}) -precompile(Tuple{typeof(Base.Sort.searchsorted), Array{String, 1}, String, Base.Order.ForwardOrdering}) -precompile(Tuple{typeof(Base.throw_boundserror), Array{String, 1}, Tuple{Base.UnitRange{Int64}}}) -precompile(Tuple{typeof(Core.Inference.precise_container_type), String, Core.Inference.Const, Array{Any, 1}, Core.Inference.InferenceState}) -precompile(Tuple{typeof(Base._rsearchindex), String, String, Int64}) -precompile(Tuple{typeof(Base.deleteat!), Array{Symbol, 1}, Base.UnitRange{Int64}}) -precompile(Tuple{typeof(Base.copy!), Array{String, 1}, Base.Generator{Array{Symbol, 1}, typeof(Base.string)}}) -precompile(Tuple{typeof(Base.deleteat!), Array{String, 1}, Base.UnitRange{Int64}}) -precompile(Tuple{typeof(Base.ht_keyindex), Base.Dict{String, Void}, String}) -precompile(Tuple{typeof(Base.push!), Base.Set{String}, String}) -precompile(Tuple{typeof(Base.isstructtype), DataType}) -precompile(Tuple{typeof(Base.start), Array{Int64, 1}}) -precompile(Tuple{typeof(Base.to_tuple_type), Type{Tuple}}) -precompile(Tuple{typeof(Base.append!), Array{Any, 1}, Array{Any, 1}}) -precompile(Tuple{typeof(Core.Inference.isbits), Tuple{DataType, Bool}}) -precompile(Tuple{typeof(Base.is_default_method), Method}) -precompile(Tuple{getfield(Base, Symbol("#kw##show")), Array{Any, 1}, typeof(Base.show), Base.AbstractIOBuffer{Array{UInt8, 1}}, Method}) -precompile(Tuple{typeof(Base.sort!), Array{String, 1}}) -precompile(Tuple{typeof(Base.rehash!), Base.Dict{String, Void}, Int64}) -precompile(Tuple{typeof(Base.ht_keyindex2), Base.Dict{String, Void}, String}) -precompile(Tuple{typeof(Base._setindex!), Base.Dict{String, Void}, Void, String, Int64}) -precompile(Tuple{typeof(Base.setindex!), Base.Dict{String, Void}, Void, String}) -precompile(Tuple{typeof(Base.Filesystem.realpath), Base.SubString{String}}) -precompile(Tuple{typeof(Base.Filesystem.readdir), Base.SubString{String}}) -precompile(Tuple{typeof(Base.REPLCompletions.dict_identifier_key), String, Symbol}) -precompile(Tuple{typeof(Base.Filesystem.expanduser), String}) -precompile(Tuple{typeof(Base.REPLCompletions.bslash_completions), String, Int64}) -precompile(Tuple{typeof(Base.REPLCompletions.should_method_complete), String}) -precompile(Tuple{typeof(Base.REPLCompletions.afterusing), String, Int64}) -precompile(Tuple{typeof(Base.REPLCompletions.complete_keyword), String}) -precompile(Tuple{typeof(Base.in), Char, Array{Any, 1}}) -precompile(Tuple{typeof(Base.string), Char, Char}) -precompile(Tuple{typeof(Base.unique), Array{String, 1}}) -precompile(Tuple{typeof(Base.REPL.beforecursor), Base.AbstractIOBuffer{Array{UInt8, 1}}}) -precompile(Tuple{typeof(Base.REPLCompletions.completions), String, Int64}) -precompile(Tuple{typeof(Base.incomplete_tag), Symbol}) -precompile(Tuple{typeof(Base.rsearchindex), String, String, Int64}) -precompile(Tuple{typeof(Base._rsearch), String, String, Int64}) -precompile(Tuple{typeof(Base.unshift!), Array{Base.SubString{String}, 1}, Base.SubString{String}}) -precompile(Tuple{typeof(Base.startswith), String, Base.SubString{String}}) -precompile(Tuple{typeof(Base.rsearch), String, Array{Char, 1}}) -precompile(Tuple{getfield(Base, Symbol("#kw##rsplit")), Array{Any, 1}, typeof(Base.rsplit), String, String}) -precompile(Tuple{typeof(Base.sort!), Array{String, 1}, Base.Sort.MergeSortAlg, Base.Order.ForwardOrdering}) -precompile(Tuple{typeof(Base.sort!), Array{String, 1}, Int64, Int64, Base.Sort.InsertionSortAlg, Base.Order.ForwardOrdering}) -precompile(Tuple{typeof(Base.sort!), Array{String, 1}, Int64, Int64, Base.Sort.MergeSortAlg, Base.Order.ForwardOrdering, Array{String, 1}}) -precompile(Tuple{typeof(Base.start), Tuple{Array{String, 1}, String, Bool}}) -precompile(Tuple{typeof(Base.indexed_next), Tuple{Array{String, 1}, String, Bool}, Int64, Int64}) -precompile(Tuple{typeof(Base.LineEdit.common_prefix), Array{String, 1}}) -precompile(Tuple{typeof(Base.LineEdit.show_completions), Base.LineEdit.PromptState, Array{String, 1}}) -precompile(Tuple{typeof(Base.collect_to!), Array{Int64, 1}, Base.Generator{Array{String, 1}, typeof(Base.length)}, Int64, Int64}) -precompile(Tuple{typeof(Base._collect), Array{String, 1}, Base.Generator{Array{String, 1}, typeof(Base.length)}, Base.EltypeUnknown, Base.HasShape}) -precompile(Tuple{typeof(Base.mapreduce_impl), typeof(Base.identity), typeof(Base.scalarmax), Array{Int64, 1}, Int64, Int64}) -precompile(Tuple{typeof(Base._mapreduce), typeof(Base.identity), typeof(Base.scalarmax), Base.IndexLinear, Array{Int64, 1}}) -precompile(Tuple{typeof(Base.Terminals.cmove_down), Base.Terminals.TTYTerminal, Int64}) -precompile(Tuple{typeof(Base.Terminals.cmove_col), Base.Terminals.TTYTerminal, Int64}) -precompile(Tuple{typeof(Base.Terminals.cmove_right), Base.Terminals.TTYTerminal, Int64}) -precompile(Tuple{typeof(Base.write), Base.TTY, Char}) -precompile(Tuple{typeof(Base.LineEdit.match_input), Base.LineEdit.KeyAlias, Base.LineEdit.MIState, Base.Terminals.TTYTerminal, Array{Char, 1}, Base.Dict{Char, Any}}) -precompile(Tuple{typeof(Base.peek), Base.AbstractIOBuffer{Array{UInt8, 1}}}) -precompile(Tuple{typeof(Base.LineEdit.char_move_left), Base.AbstractIOBuffer{Array{UInt8, 1}}}) -precompile(Tuple{typeof(Base.LineEdit.edit_backspace), Base.AbstractIOBuffer{Array{UInt8, 1}}}) -precompile(Tuple{typeof(Base.LineEdit.edit_backspace), Base.LineEdit.PromptState}) -precompile(Tuple{typeof(Base.Terminals.beep), Base.Terminals.TTYTerminal}) -precompile(Tuple{typeof(Base.LineEdit.edit_move_down), Base.AbstractIOBuffer{Array{UInt8, 1}}}) -precompile(Tuple{typeof(Core.Inference.length), Tuple{Core.Inference.Const, Core.Inference.Const, Core.Inference.Const, DataType}}) -precompile(Tuple{typeof(Core.Inference.getindex), Tuple{Core.Inference.Const, Core.Inference.Const, Core.Inference.Const, DataType}, Int64}) -precompile(Tuple{typeof(Base.LineEdit.replace_line), Base.LineEdit.PrefixSearchState, String}) -precompile(Tuple{typeof(Base.LineEdit.refresh_multi_line), Base.Terminals.TerminalBuffer, Base.LineEdit.PrefixSearchState}) -precompile(Tuple{typeof(Base.copy), Base.AbstractIOBuffer{Array{UInt8, 1}}}) -precompile(Tuple{typeof(Base.REPL.history_move), Base.LineEdit.PrefixSearchState, Base.REPL.REPLHistoryProvider, Int64, Int64}) -precompile(Tuple{typeof(Base.LineEdit.edit_move_down), Base.LineEdit.MIState}) -precompile(Tuple{typeof(Base.LineEdit.enter_prefix_search), Base.LineEdit.MIState, Base.LineEdit.PrefixHistoryPrompt{Base.REPL.REPLHistoryProvider}, Bool}) -precompile(Tuple{typeof(Base.haskey), Base.Dict{Any, Any}, Base.LineEdit.PrefixHistoryPrompt{Base.REPL.REPLHistoryProvider}}) -precompile(Tuple{typeof(Base.ht_keyindex), Base.Dict{Any, Any}, Base.LineEdit.PrefixHistoryPrompt{Base.REPL.REPLHistoryProvider}}) -precompile(Tuple{typeof(Base.getindex), Base.Dict{Any, Any}, Base.LineEdit.PrefixHistoryPrompt{Base.REPL.REPLHistoryProvider}}) -precompile(Tuple{typeof(Base.LineEdit.copybuf!), Base.AbstractIOBuffer{Array{UInt8, 1}}, Base.AbstractIOBuffer{Array{UInt8, 1}}}) -precompile(Tuple{typeof(Base.LineEdit.activate), Base.LineEdit.PrefixHistoryPrompt{Base.REPL.REPLHistoryProvider}, Base.LineEdit.PrefixSearchState, Base.Terminals.TerminalBuffer, Base.Terminals.TTYTerminal}) -precompile(Tuple{typeof(Base.LineEdit.refresh_multi_line), Base.Terminals.TerminalBuffer, Base.Terminals.TTYTerminal, Base.LineEdit.PrefixSearchState}) -precompile(Tuple{typeof(Base.LineEdit.history_next_prefix), Base.LineEdit.PrefixSearchState, Base.REPL.REPLHistoryProvider, String}) -precompile(Tuple{typeof(Base.REPL.history_move_prefix), Base.LineEdit.PrefixSearchState, Base.REPL.REPLHistoryProvider, String, Bool, Int64}) -precompile(Tuple{typeof(Base.LineEdit.keymap), Base.LineEdit.PrefixSearchState, Base.LineEdit.PrefixHistoryPrompt{Base.REPL.REPLHistoryProvider}}) -precompile(Tuple{typeof(Base.LineEdit.terminal), Base.LineEdit.PrefixSearchState}) -precompile(Tuple{typeof(Base.LineEdit.keymap_data), Base.LineEdit.PrefixSearchState, Base.LineEdit.PrefixHistoryPrompt{Base.REPL.REPLHistoryProvider}}) -precompile(Tuple{typeof(Base.LineEdit.history_prev_prefix), Base.LineEdit.PrefixSearchState, Base.REPL.REPLHistoryProvider, String}) -precompile(Tuple{typeof(Base.getindex), Base.Dict{Symbol, Any}, Symbol}) -precompile(Tuple{typeof(Base.LineEdit.transition), Base.LineEdit.MIState, Base.LineEdit.Prompt}) -precompile(Tuple{typeof(Base.LineEdit.deactivate), Base.LineEdit.PrefixHistoryPrompt{Base.REPL.REPLHistoryProvider}, Base.LineEdit.PrefixSearchState, Base.Terminals.TerminalBuffer, Base.Terminals.TTYTerminal}) -precompile(Tuple{typeof(Base.LineEdit.refresh_multi_line), Base.Terminals.TTYTerminal, Base.LineEdit.PrefixSearchState}) -precompile(Tuple{typeof(Base.LineEdit.refresh_multi_line), Base.Terminals.TerminalBuffer, Base.Terminals.TerminalBuffer, Base.Terminals.TTYTerminal, Base.LineEdit.PrefixSearchState}) -precompile(Tuple{getfield(Base.LineEdit, Symbol("#kw##refresh_multi_line")), Array{Any, 1}, typeof(Base.LineEdit.refresh_multi_line), Base.Terminals.TerminalBuffer, Base.Terminals.TerminalBuffer, Base.Terminals.TTYTerminal, Base.LineEdit.PrefixSearchState}) -precompile(Tuple{getfield(Base.LineEdit, Symbol("#kw##refresh_multi_line")), Array{Any, 1}, typeof(Base.LineEdit.refresh_multi_line), Base.Terminals.TerminalBuffer, Base.Terminals.TTYTerminal, Base.LineEdit.PrefixSearchState}) -precompile(Tuple{typeof(Base.LineEdit.replace_line), Base.LineEdit.PrefixSearchState, Base.AbstractIOBuffer{Array{UInt8, 1}}}) -precompile(Tuple{typeof(Base.LineEdit.accept_result), Base.LineEdit.MIState, Base.LineEdit.PrefixHistoryPrompt{Base.REPL.REPLHistoryProvider}}) -precompile(Tuple{typeof(Core.Inference.length), Tuple{Core.Inference.Const, Core.Inference.Const, DataType}}) -precompile(Tuple{typeof(Core.Inference.getindex), Tuple{Core.Inference.Const, Core.Inference.Const, DataType}, Int64}) -precompile(Tuple{typeof(Base.LineEdit.replace_line), Base.LineEdit.PromptState, Base.AbstractIOBuffer{Array{UInt8, 1}}}) -precompile(Tuple{typeof(Base.LineEdit.match_input), Base.Dict{Char, Any}, Base.LineEdit.MIState, Base.AbstractIOBuffer{Array{UInt8, 1}}}) -precompile(Tuple{typeof(Base.LineEdit.edit_move_left), Base.AbstractIOBuffer{Array{UInt8, 1}}}) -precompile(Tuple{typeof(Base.LineEdit.edit_move_left), Base.LineEdit.PromptState}) -precompile(Tuple{typeof(Base.LineEdit.edit_move_right), Base.AbstractIOBuffer{Array{UInt8, 1}}}) -precompile(Tuple{typeof(Base.LineEdit.edit_move_right), Base.LineEdit.PromptState}) -precompile(Tuple{typeof(Base.LineEdit.move_line_start), Base.LineEdit.MIState}) -precompile(Tuple{typeof(Base.LineEdit.move_line_end), Base.AbstractIOBuffer{Array{UInt8, 1}}}) -precompile(Tuple{typeof(Base.LineEdit.move_line_end), Base.LineEdit.MIState}) -precompile(Tuple{typeof(Base.LineEdit.edit_move_up), Base.AbstractIOBuffer{Array{UInt8, 1}}}) -precompile(Tuple{typeof(Base.LineEdit.edit_move_up), Base.LineEdit.MIState}) -precompile(Tuple{typeof(Base.:(==)), Symbol, Base.LineEdit.Prompt}) -precompile(Tuple{typeof(Base.isempty), Base.LineEdit.PromptState}) -precompile(Tuple{typeof(Base.LineEdit.default_enter_cb), Base.LineEdit.PromptState}) -precompile(Tuple{typeof(Base.Docs.helpmode), String}) -precompile(Tuple{typeof(Base.ht_keyindex), Base.Dict{Symbol, Base.Docs.DocStr}, Symbol}) -precompile(Tuple{typeof(Base.Docs.helpmode), Base.TTY, String}) -precompile(Tuple{getfield(Base.Docs, Symbol("#@repl")), Base.TTY, Symbol}) -precompile(Tuple{typeof(Base.Docs.repl), Base.TTY, Symbol}) -precompile(Tuple{typeof(Base.Docs._repl), Symbol}) -precompile(Tuple{getfield(Core, Symbol("#@doc")), Symbol}) -precompile(Tuple{typeof(Base.Docs.docm), Symbol}) -precompile(Tuple{typeof(Base._setindex!), Base.Dict{Any, Any}, Base.Markdown.Config, Symbol, Int64}) -precompile(Tuple{Type{Base.Markdown.MD}}) -precompile(Tuple{typeof(Base.setindex!), Base.Dict{Any, Any}, Base.Markdown.Config, Symbol}) -precompile(Tuple{typeof(Base.Markdown.skipblank), Base.AbstractIOBuffer{Array{UInt8, 1}}}) -precompile(Tuple{typeof(Base.vcat), Array{Function, 1}, Array{Function, 1}}) -precompile(Tuple{typeof(Base.Docs.formatdoc), Base.Docs.DocStr}) -precompile(Tuple{typeof(Base.Docs.parsedoc), Base.Docs.DocStr}) -precompile(Tuple{typeof(Base.Docs.repl_latex), Base.TTY, String}) -precompile(Tuple{typeof(Base.ht_keyindex), Base.Dict{String, String}, String}) -precompile(Tuple{typeof(Base.ht_keyindex), Base.Dict{Symbol, Tuple{String, String}}, Symbol}) -precompile(Tuple{typeof(Base.print), Base.TTY, Char, Char}) -precompile(Tuple{typeof(Base.rehash!), Base.Dict{String, String}, Int64}) -precompile(Tuple{typeof(Base.ht_keyindex2), Base.Dict{String, String}, String}) -precompile(Tuple{typeof(Base._setindex!), Base.Dict{String, String}, String, String, Int64}) -precompile(Tuple{typeof(Core.Inference.isbits), Base.Dict{String, String}}) -precompile(Tuple{typeof(Base.setindex!), Base.Dict{String, String}, String, String}) -precompile(Tuple{typeof(Base.Docs.symbol_latex), String}) -precompile(Tuple{typeof(Base.Docs.repl_search), Base.TTY, String}) -precompile(Tuple{typeof(Base.print), Base.TTY, String}) -precompile(Tuple{typeof(Base.print), Base.TTY, Char}) -precompile(Tuple{typeof(Base.print), Base.TTY, String, Char}) -precompile(Tuple{typeof(Base.mapreduce_impl), typeof(Base.identity), typeof(Base.:(+)), Array{Int64, 1}, Int64, Int64, Int64}) -precompile(Tuple{typeof(Base._mapreduce), typeof(Base.identity), typeof(Base.:(+)), Base.IndexLinear, Array{Int64, 1}}) -precompile(Tuple{typeof(Base.shift!), Array{Char, 1}}) -precompile(Tuple{typeof(Base.Docs.avgdistance), Array{Int64, 1}}) -precompile(Tuple{typeof(Core.Inference.isbits), Tuple{Array{String, 1}}}) -precompile(Tuple{typeof(Base.Docs.accessible), Module}) -precompile(Tuple{Type{Base.Generator{I, F} where F where I}, typeof(Base.names), Array{Any, 1}}) -precompile(Tuple{typeof(Base.iteratoreltype), Type{Base.Generator{Array{Any, 1}, typeof(Base.names)}}}) -precompile(Tuple{typeof(Base.iteratorsize), Type{Base.Generator{Array{Any, 1}, typeof(Base.names)}}}) -precompile(Tuple{typeof(Base._collect), Array{Any, 1}, Base.Generator{Array{Any, 1}, typeof(Base.names)}, Base.EltypeUnknown, Base.HasShape}) -precompile(Tuple{typeof(Base.collect_to!), Array{Array{Symbol, 1}, 1}, Base.Generator{Array{Any, 1}, typeof(Base.names)}, Int64, Int64}) -precompile(Tuple{typeof(Base.names), Module}) -precompile(Tuple{typeof(Base.vcat), Array{Symbol, 1}, Array{Symbol, 1}, Array{Symbol, 1}, Array{String, 1}}) -precompile(Tuple{typeof(Base.throw_boundserror), Array{Symbol, 2}, Tuple{Base.UnitRange{Int64}}}) -precompile(Tuple{typeof(Base.unsafe_copy!), Array{Symbol, 2}, Int64, Array{Symbol, 1}, Int64, Int64}) -precompile(Tuple{typeof(Base.promote_eltype), Array{Symbol, 1}, Array{Symbol, 1}, Array{Symbol, 1}, Array{String, 1}}) -precompile(Tuple{typeof(Base.promote_eltype), Array{Symbol, 1}, Array{String, 1}}) -precompile(Tuple{typeof(Base.promote_eltype), Array{String, 1}}) -precompile(Tuple{typeof(Base.promote_type), Type{Symbol}, Type{String}}) -precompile(Tuple{typeof(Base.promote_rule), Type{Symbol}, Type{String}}) -precompile(Tuple{typeof(Base.promote_rule), Type{String}, Type{Symbol}}) -precompile(Tuple{typeof(Base.promote_result), Type{Symbol}, Type{String}, Type{Union{}}, Type{Union{}}}) -precompile(Tuple{typeof(Base.typed_vcat), Type{Any}, Array{Symbol, 1}, Array{Symbol, 1}, Array{Symbol, 1}, Array{String, 1}}) -precompile(Tuple{typeof(Base.setindex!), Array{Any, 1}, Array{Symbol, 1}, Base.UnitRange{Int64}}) -precompile(Tuple{typeof(Base.setindex!), Array{Any, 1}, Array{String, 1}, Base.UnitRange{Int64}}) -precompile(Tuple{typeof(Base.throw_setindex_mismatch), Array{String, 1}, Tuple{Int64}}) -precompile(Tuple{typeof(Base.setindex_shape_check), Array{String, 1}, Int64}) -precompile(Tuple{typeof(Base.unique), Array{Any, 1}}) -precompile(Tuple{typeof(Base.getindex), Type{Symbol}, Symbol}) -precompile(Tuple{Type{Base.Set{Symbol}}, Tuple{Symbol}}) -precompile(Tuple{typeof(Base.union!), Base.Set{Symbol}, Tuple{Symbol}}) -precompile(Tuple{typeof(Base.unique_from), Array{Any, 1}, Array{Symbol, 1}, Base.Set{Symbol}, Int64}) -precompile(Tuple{typeof(Base.convert), Type{Base.Set{Any}}, Base.Set{Symbol}}) -precompile(Tuple{typeof(Base.ht_keyindex2), Base.Dict{Any, Void}, Symbol}) -precompile(Tuple{typeof(Base._setindex!), Base.Dict{Any, Void}, Void, Symbol, Int64}) -precompile(Tuple{typeof(Base.setindex!), Base.Dict{Any, Void}, Void, Symbol}) -precompile(Tuple{typeof(Base.union!), Base.Set{Any}, Base.Set{Symbol}}) -precompile(Tuple{typeof(Base.convert), Type{Array{Any, 1}}, Array{Symbol, 1}}) -precompile(Tuple{typeof(Base.copy!), Base.IndexLinear, Array{Any, 1}, Base.IndexLinear, Array{Symbol, 1}}) -precompile(Tuple{typeof(Base.:(==)), String, Symbol}) -precompile(Tuple{typeof(Base.unique_from), Array{Any, 1}, Array{Any, 1}, Base.Set{Any}, Int64}) -precompile(Tuple{Type{Base.Generator{I, F} where F where I}, typeof(Base.string), Array{Any, 1}}) -precompile(Tuple{typeof(Base.iteratoreltype), Type{Base.Generator{Array{Any, 1}, typeof(Base.string)}}}) -precompile(Tuple{typeof(Base.iteratorsize), Type{Base.Generator{Array{Any, 1}, typeof(Base.string)}}}) -precompile(Tuple{typeof(Base._collect), Array{Any, 1}, Base.Generator{Array{Any, 1}, typeof(Base.string)}, Base.EltypeUnknown, Base.HasShape}) -precompile(Tuple{typeof(Base.similar), Array{Any, 1}, Type{String}, Tuple{Base.OneTo{Int64}}}) -precompile(Tuple{typeof(Base.collect_to!), Array{String, 1}, Base.Generator{Array{Any, 1}, typeof(Base.string)}, Int64, Int64}) -precompile(Tuple{typeof(Base.UTF8proc.isalpha), Char}) -precompile(Tuple{getfield(Base.Docs, Symbol("#kw##matchinds")), Array{Any, 1}, typeof(Base.Docs.matchinds), String, String}) -precompile(Tuple{typeof(Base.Docs.bestmatch), String, String}) -precompile(Tuple{typeof(Base.length), Tuple{DataType, DataType}}) -precompile(Tuple{Type{BoundsError}, Array{Int64, 2}, Tuple{Base.UnitRange{Int64}, Int64}}) -precompile(Tuple{typeof(Base.throw_boundserror), Array{Int64, 2}, Tuple{Base.UnitRange{Int64}, Int64}}) -precompile(Tuple{getfield(Base.Cartesian, Symbol("#@nexprs")), Int64, Expr}) -precompile(Tuple{typeof(Base.Cartesian._nexprs), Int64, Expr}) -precompile(Tuple{typeof(Core.Inference.findnext), Array{Function, 1}, typeof(===), Int64}) -precompile(Tuple{typeof(Core.Inference.builtin_tfunction), typeof(===), Array{Any, 1}, Core.Inference.InferenceState, Core.Inference.InferenceParams}) -precompile(Tuple{typeof(Core.Inference.typeinf_frame), Core.MethodInstance, Bool, Bool, Core.Inference.InferenceParams}) -precompile(Tuple{typeof(Core.Inference.typeinf), Core.Inference.InferenceState}) -precompile(Tuple{typeof(Base.Cartesian.inlineanonymous), Expr, Int64}) -precompile(Tuple{typeof(Base.Cartesian.lreplace), Expr, Symbol, Int64}) -precompile(Tuple{typeof(Base.copy), Expr}) -precompile(Tuple{typeof(Base.copy_exprargs), Array{Any, 1}}) -precompile(Tuple{typeof(Base.collect), Type{Any}, Base.Generator{Array{Any, 1}, typeof(Base.copy_exprs)}}) -precompile(Tuple{typeof(Base._collect), Type{Any}, Base.Generator{Array{Any, 1}, typeof(Base.copy_exprs)}, Base.HasShape}) -precompile(Tuple{typeof(Base.copy!), Array{Any, 1}, Base.Generator{Array{Any, 1}, typeof(Base.copy_exprs)}}) -precompile(Tuple{typeof(Base.next), Base.Generator{Array{Any, 1}, typeof(Base.copy_exprs)}, Int64}) -precompile(Tuple{typeof(Base.copy_exprs), Expr}) -precompile(Tuple{typeof(Base.Cartesian.lreplace!), Expr, Base.Cartesian.LReplace{String}}) -precompile(Tuple{typeof(Base.Cartesian.lreplace!), Symbol, Base.Cartesian.LReplace{String}}) -precompile(Tuple{typeof(Base.Cartesian.lreplace!), String, Base.Cartesian.LReplace{String}}) -precompile(Tuple{typeof(Base.Cartesian.exprresolve), Expr}) -precompile(Tuple{Type{BoundsError}, Array{Expr, 1}, Base.UnitRange{Int64}}) -precompile(Tuple{getfield(Base.Cartesian, Symbol("#@ncall")), Int64, Symbol, Symbol}) -precompile(Tuple{typeof(Base.Cartesian._ncall), Int64, Symbol, Symbol}) -precompile(Tuple{typeof(Base.getindex), Tuple{Symbol}, Base.UnitRange{Int64}}) -precompile(Tuple{getfield(Base.Cartesian, Symbol("#@ncall")), Int64, Symbol, Symbol, Expr}) -precompile(Tuple{typeof(Base.Cartesian._ncall), Int64, Symbol, Symbol, Expr}) -precompile(Tuple{typeof(Base.endof), Tuple{Symbol, Expr}}) -precompile(Tuple{typeof(Base.getindex), Tuple{Symbol, Expr}, Base.UnitRange{Int64}}) -precompile(Tuple{getfield(Base.Cartesian, Symbol("#@nloops")), Int64, Symbol, Expr, Expr}) -precompile(Tuple{typeof(Base.Cartesian._nloops), Int64, Symbol, Expr, Expr}) -precompile(Tuple{typeof(Base.endof), Tuple{Expr}}) -precompile(Tuple{typeof(Base.endof), Tuple{Symbol, Symbol, Symbol}}) -precompile(Tuple{typeof(Base.getindex), Tuple{Symbol, Symbol, Symbol}, Base.UnitRange{Int64}}) -precompile(Tuple{Type{Expr}, Symbol, Symbol, Symbol, Symbol, Symbol, Symbol}) -precompile(Tuple{typeof(Base.join), Base.AbstractIOBuffer{Array{UInt8, 1}}, Tuple{String, String}, Char}) -precompile(Tuple{typeof(Base.dims2string), Tuple{Int64, Int64}}) -precompile(Tuple{typeof(Base.throw_setindex_mismatch), Base.UnitRange{Int64}, Tuple{Int64, Int64}}) -precompile(Tuple{typeof(Base.setindex_shape_check), Base.UnitRange{Int64}, Int64, Int64}) -precompile(Tuple{typeof(Base._unsafe_setindex!), Base.IndexLinear, Array{Int64, 2}, Base.UnitRange{Int64}, Base.UnitRange{Int64}, Int64}) -precompile(Tuple{Type{BoundsError}, Array{Int64, 2}, Tuple{Int64, Base.UnitRange{Int64}}}) -precompile(Tuple{typeof(Base.throw_boundserror), Array{Int64, 2}, Tuple{Int64, Base.UnitRange{Int64}}}) -precompile(Tuple{typeof(Base._unsafe_setindex!), Base.IndexLinear, Array{Int64, 2}, Base.UnitRange{Int64}, Int64, Base.UnitRange{Int64}}) -precompile(Tuple{typeof(Base.Docs.levenshtein), String, String}) -precompile(Tuple{typeof(Base.Docs.fuzzyscore), String, String}) -precompile(Tuple{typeof(Core.Inference.copy_exprargs), Array{Any, 1}}) -precompile(Tuple{typeof(Core.Inference.copy), Expr}) -precompile(Tuple{typeof(Core.Inference.copy!), Array{Any, 1}, Core.Inference.Generator{Array{Any, 1}, typeof(Core.Inference.copy_exprs)}}) -precompile(Tuple{typeof(Core.Inference._widen_all_consts!), Expr, Array{Bool, 1}}) -precompile(Tuple{typeof(Core.Inference._delete!), Core.Inference.IntSet, Int64}) -precompile(Tuple{typeof(Core.Inference.promote_type), Type{Float16}, Type{Int64}}) -precompile(Tuple{typeof(Core.Inference.mk_tuplecall), Array{Any, 1}, Core.Inference.InferenceState}) -precompile(Tuple{typeof(Core.Inference.inlining_pass), Expr, Core.Inference.InferenceState, Array{Any, 1}, Int64}) -precompile(Tuple{typeof(Core.Inference.annotate_slot_load!), Expr, Array{Any, 1}, Core.Inference.InferenceState, Array{Bool, 1}}) -precompile(Tuple{typeof(Core.Inference.record_slot_assign!), Core.Inference.InferenceState}) -precompile(Tuple{typeof(Core.Inference.type_annotate!), Core.Inference.InferenceState}) -precompile(Tuple{typeof(Core.Inference.inlining_pass!), Core.Inference.InferenceState}) -precompile(Tuple{typeof(Core.Inference.alloc_elim_pass!), Core.Inference.InferenceState}) -precompile(Tuple{typeof(Core.Inference.getfield_elim_pass!), Core.Inference.InferenceState}) -precompile(Tuple{typeof(Core.Inference.popmeta!), Array{Any, 1}, Symbol}) -precompile(Tuple{typeof(Core.Inference.widen_all_consts!), CodeInfo}) -precompile(Tuple{typeof(Core.Inference.stupdate!), Array{Any, 1}, Array{Any, 1}}) -precompile(Tuple{typeof(Core.Inference.push!), Core.Inference.IntSet, Int64}) -precompile(Tuple{typeof(Core.Inference.abstract_eval_call), Expr, Array{Any, 1}, Core.Inference.InferenceState}) -precompile(Tuple{typeof(Core.Inference.return_type_tfunc), Array{Any, 1}, Array{Any, 1}, Core.Inference.InferenceState}) -precompile(Tuple{typeof(Core.Inference.abstract_call), typeof(===), Tuple{}, Array{Any, 1}, Array{Any, 1}, Core.Inference.InferenceState}) -precompile(Tuple{typeof(Core.Inference.abstract_call), typeof(===), Array{Any, 1}, Array{Any, 1}, Array{Any, 1}, Core.Inference.InferenceState}) -precompile(Tuple{typeof(Core.Inference.type_too_complex), TypeVar, Int64}) -precompile(Tuple{typeof(Core.Inference.abstract_eval), Expr, Array{Any, 1}, Core.Inference.InferenceState}) -precompile(Tuple{typeof(Core.Inference._setint!), Core.Inference.IntSet, Int64, Bool}) -precompile(Tuple{typeof(Core.Inference.stupdate1!), Array{Any, 1}, Core.Inference.StateUpdate}) -precompile(Tuple{typeof(Core.Inference.optimize), Core.Inference.InferenceState}) -precompile(Tuple{typeof(Core.Inference.deleteat!), Core.Inference.BitArray{1}, Core.Inference.UnitRange{Int64}}) -precompile(Tuple{typeof(Core.Inference.resize!), Core.Inference.BitArray{1}, Int64}) -precompile(Tuple{typeof(Core.Inference.copy_chunks!), Array{UInt64, 1}, Int64, Array{UInt64, 1}, Int64, Int64}) -precompile(Tuple{typeof(Core.Inference.copy_chunks_rtol!), Array{UInt64, 1}, Int64, Int64, Int64}) -precompile(Tuple{typeof(Core.Inference.find_ssavalue_uses), Array{Any, 1}}) -precompile(Tuple{typeof(Base.sortperm), Array{Tuple{Float64, Int64}, 1}}) -precompile(Tuple{Type{Base.Order.Perm{O, V} where V<:(AbstractArray{T, 1} where T) where O<:Base.Order.Ordering}, Base.Order.ForwardOrdering, Array{Tuple{Float64, Int64}, 1}}) -precompile(Tuple{typeof(Base.sort!), Array{Int64, 1}, Base.Sort.QuickSortAlg, Base.Order.Perm{Base.Order.ForwardOrdering, Array{Tuple{Float64, Int64}, 1}}}) -precompile(Tuple{typeof(Base.isequal), Float64, Float64}) -precompile(Tuple{typeof(Base.isequal), Int64, Float64}) -precompile(Tuple{typeof(Base.isequal), Float64, Int64}) -precompile(Tuple{typeof(Base.isless), Int64, Float64}) -precompile(Tuple{typeof(Base.isless), Float64, Int64}) -precompile(Tuple{typeof(Base.isless), Tuple{Float64, Int64}, Tuple{Float64, Int64}}) -precompile(Tuple{typeof(Base.sort!), Array{Int64, 1}, Int64, Int64, Base.Sort.InsertionSortAlg, Base.Order.Perm{Base.Order.ForwardOrdering, Array{Tuple{Float64, Int64}, 1}}}) -precompile(Tuple{typeof(Base.Sort.partition!), Array{Int64, 1}, Int64, Int64, Base.Order.Perm{Base.Order.ForwardOrdering, Array{Tuple{Float64, Int64}, 1}}}) -precompile(Tuple{typeof(Base.sort!), Array{Int64, 1}, Int64, Int64, Base.Sort.QuickSortAlg, Base.Order.Perm{Base.Order.ForwardOrdering, Array{Tuple{Float64, Int64}, 1}}}) -precompile(Tuple{typeof(Base.getindex), Array{String, 1}, Array{Int64, 1}}) -precompile(Tuple{typeof(Base.throw_boundserror), Array{String, 1}, Tuple{Array{Int64, 1}}}) -precompile(Tuple{typeof(Base.throw_checksize_error), Array{String, 1}, Tuple{Base.OneTo{Int64}}}) -precompile(Tuple{typeof(Base._unsafe_getindex), Base.IndexLinear, Array{String, 1}, Array{Int64, 1}}) -precompile(Tuple{typeof(Base.reverse), Array{String, 1}}) -precompile(Tuple{typeof(Base.reverse), Array{String, 1}, Int64, Int64}) -precompile(Tuple{getfield(Base.Docs, Symbol("#kw##printmatches")), Array{Any, 1}, typeof(Base.Docs.printmatches), Base.TTY, String, Array{String, 1}}) -precompile(Tuple{typeof(Base.Docs.printmatch), Base.TTY, String, String}) -precompile(Tuple{typeof(Base.Markdown.with_output_format), typeof(Base.print), Array{Symbol, 1}, Base.TTY, Char}) -precompile(Tuple{typeof(Base.Docs.doc), Base.Docs.Binding}) -precompile(Tuple{typeof(Base.print), Base.AbstractIOBuffer{Array{UInt8, 1}}, String, Base.Docs.Binding, String, String, String, Char}) -precompile(Tuple{typeof(Base.show_method_table), Base.AbstractIOBuffer{Array{UInt8, 1}}, Base.MethodList, Int64, Bool}) -precompile(Tuple{typeof(Base.print), Base.AbstractIOBuffer{Array{UInt8, 1}}, Base.MethodList}) -precompile(Tuple{typeof(Base.print), Base.AbstractIOBuffer{Array{UInt8, 1}}, String, Base.MethodList, String, Char}) -precompile(Tuple{typeof(Base.print), Base.AbstractIOBuffer{Array{UInt8, 1}}, String, String, DataType, String, DataType, Char}) -precompile(Tuple{typeof(Base.print), Base.AbstractIOBuffer{Array{UInt8, 1}}, DataType, Char}) -precompile(Tuple{typeof(Base.print), Base.AbstractIOBuffer{Array{UInt8, 1}}, typeof(Type), Char}) -precompile(Tuple{typeof(Base.print), Base.AbstractIOBuffer{Array{UInt8, 1}}, String, Module, String, Char}) -precompile(Tuple{typeof(Base.Pkg.dir), String, String}) -precompile(Tuple{typeof(Base._setindex!), Base.Dict{Any, Any}, Array{Base.Docs.DocStr, 1}, Symbol, Int64}) -precompile(Tuple{typeof(Base._setindex!), Base.Dict{Any, Any}, Base.Docs.Binding, Symbol, Int64}) -precompile(Tuple{typeof(Base._setindex!), Base.Dict{Any, Any}, Type{Union{}}, Symbol, Int64}) -precompile(Tuple{typeof(Base._collect), Array{Base.Docs.DocStr, 1}, Base.Generator{Array{Base.Docs.DocStr, 1}, typeof(Base.Docs.parsedoc)}, Base.EltypeUnknown, Base.HasShape}) -precompile(Tuple{typeof(Base.ht_keyindex2), Base.Dict{Union{DataType, typeof(Type)}, Void}, typeof(Type)}) -precompile(Tuple{typeof(Base._setindex!), Base.Dict{Union{DataType, typeof(Type)}, Void}, Void, typeof(Type), Int64}) -precompile(Tuple{typeof(Base.ht_keyindex2), Base.Dict{Union{DataType, typeof(Type)}, Void}, DataType}) -precompile(Tuple{typeof(Base._setindex!), Base.Dict{Union{DataType, typeof(Type)}, Void}, Void, DataType, Int64}) -precompile(Tuple{typeof(Base.setindex!), Base.Dict{Union{DataType, typeof(Type)}, Void}, Void, DataType}) -precompile(Tuple{typeof(Base.setindex!), Base.Dict{Union{DataType, typeof(Type)}, Void}, Void, typeof(Type)}) -precompile(Tuple{typeof(Base.rehash!), Base.Dict{Union{DataType, typeof(Type)}, Void}, Int64}) -precompile(Tuple{typeof(Base._subtypes), Module, DataType, Base.Set{Union{DataType, typeof(Type)}}, Base.Set{Module}}) -precompile(Tuple{typeof(Base._subtypes), Module, DataType}) -precompile(Tuple{typeof(Base.isempty), Array{Int64, 1}}) -precompile(Tuple{typeof(Base.Iterators.zip), Array{Int64, 1}, SimpleVector}) -precompile(Tuple{typeof(Base.Iterators.zip), Array{Symbol, 1}, SimpleVector}) -precompile(Tuple{typeof(Base.start), Base.Iterators.Zip2{Array{Int64, 1}, SimpleVector}}) -precompile(Tuple{typeof(Base.start), Base.Iterators.Zip2{Array{Symbol, 1}, SimpleVector}}) -precompile(Tuple{typeof(Base.done), Base.Iterators.Zip2{Array{Int64, 1}, SimpleVector}, Tuple{Int64, Int64}}) -precompile(Tuple{typeof(Base.done), Base.Iterators.Zip2{Array{Symbol, 1}, SimpleVector}, Tuple{Int64, Int64}}) -precompile(Tuple{typeof(Base.next), Base.Iterators.Zip2{Array{Int64, 1}, SimpleVector}, Tuple{Int64, Int64}}) -precompile(Tuple{typeof(Base.next), Base.Iterators.Zip2{Array{Symbol, 1}, SimpleVector}, Tuple{Int64, Int64}}) -precompile(Tuple{typeof(Base.println), Base.AbstractIOBuffer{Array{UInt8, 1}}, DataType}) -precompile(Tuple{typeof(Base.println), Base.AbstractIOBuffer{Array{UInt8, 1}}, typeof(Type)}) -precompile(Tuple{typeof(Base.setindex!), Base.Dict{Any, Any}, Array{Base.Docs.DocStr, 1}, Symbol}) -precompile(Tuple{typeof(Base.setindex!), Base.Dict{Any, Any}, Base.Docs.Binding, Symbol}) -precompile(Tuple{typeof(Base.setindex!), Base.Dict{Any, Any}, Type{Union{}}, Symbol}) -precompile(Tuple{typeof(Base.Docs.aliasof), Base.Docs.Binding}) -precompile(Tuple{typeof(Base.Docs.summarize), Base.Docs.Binding, Type{Union{}}}) -precompile(Tuple{typeof(Base.Docs.doc), Base.Docs.Binding, Type{Union{}}}) -precompile(Tuple{typeof(Base.haskey), Base.ObjectIdDict, Base.Docs.Binding}) -precompile(Tuple{typeof(Base.getindex), Base.ObjectIdDict, Base.Docs.Binding}) -precompile(Tuple{typeof(Base.push!), Array{Base.Docs.MultiDoc, 1}, Base.Docs.MultiDoc}) -precompile(Tuple{typeof(Base.start), Array{Type{T} where T, 1}}) -precompile(Tuple{typeof(Base.done), Array{Type{T} where T, 1}, Int64}) -precompile(Tuple{typeof(Base.next), Array{Type{T} where T, 1}, Int64}) -precompile(Tuple{typeof(Base.getindex), Base.ObjectIdDict, Type{Tuple{Any}}}) -precompile(Tuple{typeof(Base.push!), Array{Base.Docs.DocStr, 1}, Base.Docs.DocStr}) -precompile(Tuple{typeof(Base.Docs.formatdoc), Base.AbstractIOBuffer{Array{UInt8, 1}}, Base.Docs.DocStr, String}) -precompile(Tuple{typeof(Base.Markdown.hashheader), Base.AbstractIOBuffer{Array{UInt8, 1}}, Base.Markdown.MD}) -precompile(Tuple{typeof(Base.Markdown.parseinline), Base.AbstractIOBuffer{Array{UInt8, 1}}, Base.Markdown.MD, Array{Function, 1}}) -precompile(Tuple{typeof(Base.Markdown.config), Base.Markdown.MD}) -precompile(Tuple{typeof(Base.Markdown.parseinline), Base.AbstractIOBuffer{Array{UInt8, 1}}, Base.Markdown.MD, Base.Markdown.Config}) -precompile(Tuple{typeof(Base.Markdown.list), Base.AbstractIOBuffer{Array{UInt8, 1}}, Base.Markdown.MD}) -precompile(Tuple{typeof(Base.searchindex), String, String}) -precompile(Tuple{typeof(Base._searchindex), Base.SubString{String}, String, Int64}) -precompile(Tuple{getfield(Base.Markdown, Symbol("#kw##skipwhitespace")), Array{Any, 1}, typeof(Base.Markdown.skipwhitespace), Base.AbstractIOBuffer{Array{UInt8, 1}}}) -precompile(Tuple{typeof(Base.ht_keyindex), Base.Dict{Symbol, Base.Markdown.Config}, Symbol}) -precompile(Tuple{getfield(Base.Markdown, Symbol("#kw##parse")), Array{Any, 1}, typeof(Base.Markdown.parse), Base.AbstractIOBuffer{Array{UInt8, 1}}}) -precompile(Tuple{getfield(Base.Markdown, Symbol("#kw##startswith")), Array{Any, 1}, typeof(Base.Markdown.startswith), Base.AbstractIOBuffer{Array{UInt8, 1}}, Base.Regex}) -precompile(Tuple{typeof(Core.Inference.isbits), Tuple{Int64, Base.Regex}}) -precompile(Tuple{typeof(Base.contains), String, String}) -precompile(Tuple{typeof(Base.contains), Base.SubString{String}, String}) -precompile(Tuple{typeof(Base.Markdown.pushitem!), Base.Markdown.List, Base.AbstractIOBuffer{Array{UInt8, 1}}}) -precompile(Tuple{typeof(Base.Markdown.fencedcode), Base.AbstractIOBuffer{Array{UInt8, 1}}, Base.Markdown.MD}) -precompile(Tuple{getfield(Base.Markdown, Symbol("#kw##startswith")), Array{Any, 1}, typeof(Base.Markdown.startswith), Base.AbstractIOBuffer{Array{UInt8, 1}}, String}) -precompile(Tuple{typeof(Base.skip), Base.AbstractIOBuffer{Array{UInt8, 1}}, Int64}) -precompile(Tuple{typeof(Base.lstrip), String, Char}) -precompile(Tuple{typeof(Base.Markdown.blockquote), Base.AbstractIOBuffer{Array{UInt8, 1}}, Base.Markdown.MD}) -precompile(Tuple{getfield(Base.Markdown, Symbol("#kw##parse")), Array{Any, 1}, typeof(Base.Markdown.parse), String}) -precompile(Tuple{typeof(Base.Markdown.admonition), Base.AbstractIOBuffer{Array{UInt8, 1}}, Base.Markdown.MD}) -precompile(Tuple{typeof(Base.UTF8proc.isupper), Char}) -precompile(Tuple{getfield(Base.Markdown, Symbol("#kw##linecontains")), Array{Any, 1}, typeof(Base.Markdown.linecontains), Base.AbstractIOBuffer{Array{UInt8, 1}}, String}) -precompile(Tuple{typeof(Base.ucfirst), Base.SubString{String}}) -precompile(Tuple{typeof(Base.Markdown.blocktex), Base.AbstractIOBuffer{Array{UInt8, 1}}, Base.Markdown.MD}) -precompile(Tuple{typeof(Core.Inference.length), Tuple{DataType, Core.Inference.Const, DataType}}) -precompile(Tuple{typeof(Core.Inference.getindex), Tuple{DataType, Core.Inference.Const, DataType}, Int64}) -precompile(Tuple{getfield(Base.Markdown, Symbol("#kw##parse_inline_wrapper")), Array{Any, 1}, typeof(Base.Markdown.parse_inline_wrapper), Base.AbstractIOBuffer{Array{UInt8, 1}}, String}) -precompile(Tuple{typeof(Base.Markdown.startswith), Base.AbstractIOBuffer{Array{UInt8, 1}}, String}) -precompile(Tuple{typeof(Base.Markdown.blockinterp), Base.AbstractIOBuffer{Array{UInt8, 1}}, Base.Markdown.MD}) -precompile(Tuple{getfield(Base, Symbol("#kw##parse")), Array{Any, 1}, typeof(Base.parse), Base.AbstractIOBuffer{Array{UInt8, 1}}}) -precompile(Tuple{typeof(Base.Markdown.interpinner), Base.AbstractIOBuffer{Array{UInt8, 1}}, Bool}) -precompile(Tuple{typeof(Base.Markdown.indentcode), Base.AbstractIOBuffer{Array{UInt8, 1}}, Base.Markdown.MD}) -precompile(Tuple{typeof(Base.Markdown.footnote), Base.AbstractIOBuffer{Array{UInt8, 1}}, Base.Markdown.MD}) -precompile(Tuple{Type{Base.Markdown.Footnote}, Void, Array{Any, 1}}) -precompile(Tuple{Type{Base.Markdown.Footnote}, Base.SubString{String}, Array{Any, 1}}) -precompile(Tuple{typeof(Base.Markdown.github_table), Base.AbstractIOBuffer{Array{UInt8, 1}}, Base.Markdown.MD}) -precompile(Tuple{typeof(Base.replace), String, String, String, Int64}) -precompile(Tuple{typeof(Base.pop!), Array{Base.SubString{String}, 1}}) -precompile(Tuple{typeof(Base.union!), Base.Set{Char}, String}) -precompile(Tuple{typeof(Base.ht_keyindex), Base.Dict{Char, Void}, Char}) -precompile(Tuple{typeof(Base.issubset), Base.SubString{String}, Base.Set{Char}}) -precompile(Tuple{typeof(Core.Inference.length), Tuple{Core.Inference.Const, Core.Inference.Const, Core.Inference.Const, Core.Inference.Const, Core.Inference.Const}}) -precompile(Tuple{typeof(Core.Inference.getindex), Tuple{Core.Inference.Const, Core.Inference.Const, Core.Inference.Const, Core.Inference.Const, Core.Inference.Const}, Int64}) -precompile(Tuple{typeof(Base.throw_boundserror), Base.SubArray{UInt8, 1, Array{UInt8, 1}, Tuple{Base.UnitRange{Int64}}, true}, Tuple{Int64}}) -precompile(Tuple{typeof(Base.peek), Base.AbstractIOBuffer{Base.SubArray{UInt8, 1, Array{UInt8, 1}, Tuple{Base.UnitRange{Int64}}, true}}}) -precompile(Tuple{typeof(Base.Markdown.parseinline), Base.AbstractIOBuffer{Base.SubArray{UInt8, 1, Array{UInt8, 1}, Tuple{Base.UnitRange{Int64}}, true}}, Base.Markdown.MD, Array{Function, 1}}) -precompile(Tuple{typeof(Base.read), Base.AbstractIOBuffer{Base.SubArray{UInt8, 1, Array{UInt8, 1}, Tuple{Base.UnitRange{Int64}}, true}}, Type{Char}}) -precompile(Tuple{typeof(Base.Markdown.parseinline), Base.AbstractIOBuffer{Base.SubArray{UInt8, 1, Array{UInt8, 1}, Tuple{Base.UnitRange{Int64}}, true}}, Base.Markdown.MD, Base.Markdown.Config}) -precompile(Tuple{typeof(Base.copy!), Base.IndexLinear, Array{Array{Any, 1}, 1}, Base.IndexLinear, Array{Any, 1}}) -precompile(Tuple{typeof(Base.Markdown.parsealign), Void}) -precompile(Tuple{typeof(Base.Markdown.parsealign), Array{Base.SubString{String}, 1}}) -precompile(Tuple{typeof(Base.Markdown.rowlength!), Void, Int64}) -precompile(Tuple{typeof(Base.Markdown.rowlength!), Array{Base.SubString{String}, 1}, Int64}) -precompile(Tuple{Type{Base.Markdown.Table}, Array{Any, 1}, Void}) -precompile(Tuple{Type{Base.Markdown.Table}, Array{Any, 1}, Array{Symbol, 1}}) -precompile(Tuple{typeof(Base.Markdown.horizontalrule), Base.AbstractIOBuffer{Array{UInt8, 1}}, Base.Markdown.MD}) -precompile(Tuple{typeof(Core.Inference.isbits), Base.Markdown.HorizontalRule}) -precompile(Tuple{typeof(Base.Markdown.setextheader), Base.AbstractIOBuffer{Array{UInt8, 1}}, Base.Markdown.MD}) -precompile(Tuple{typeof(Base.Markdown.paragraph), Base.AbstractIOBuffer{Array{UInt8, 1}}, Base.Markdown.MD}) -precompile(Tuple{getfield(Base.Markdown, Symbol("#kw##parse")), Array{Any, 1}, typeof(Base.Markdown.parse), Base.AbstractIOBuffer{Array{UInt8, 1}}, Base.Markdown.MD, Base.Markdown.Config}) -precompile(Tuple{getfield(Base.Markdown, Symbol("#kw##parse")), Array{Any, 1}, typeof(Base.Markdown.parse), Base.AbstractIOBuffer{Array{UInt8, 1}}, Base.Markdown.MD}) -precompile(Tuple{typeof(Base.Markdown.inline_code), Base.AbstractIOBuffer{Array{UInt8, 1}}, Base.Markdown.MD}) -precompile(Tuple{typeof(Base.Markdown.readuntil), Base.AbstractIOBuffer{Array{UInt8, 1}}, String}) -precompile(Tuple{typeof(Base.Markdown.readuntil), Base.AbstractIOBuffer{Array{UInt8, 1}}, Base.SubString{String}}) -precompile(Tuple{typeof(Base.setindex!), Base.Dict{Any, Any}, Module, Symbol}) -precompile(Tuple{typeof(Base._setindex!), Base.Dict{Any, Any}, Module, Symbol, Int64}) -precompile(Tuple{typeof(Base.setindex!), Base.Dict{Any, Any}, String, Symbol}) -precompile(Tuple{typeof(Base._setindex!), Base.Dict{Any, Any}, String, Symbol, Int64}) -precompile(Tuple{typeof(Base.similar), Array{Base.Docs.DocStr, 1}, Type{Base.Markdown.MD}, Tuple{Base.OneTo{Int64}}}) -precompile(Tuple{typeof(Base.setindex!), Array{Base.Markdown.MD, 1}, Base.Markdown.MD, Int64}) -precompile(Tuple{typeof(Base.collect_to!), Array{Base.Markdown.MD, 1}, Base.Generator{Array{Base.Docs.DocStr, 1}, typeof(Base.Docs.parsedoc)}, Int64, Int64}) -precompile(Tuple{typeof(Base.unsafe_copy!), Array{Base.Markdown.MD, 1}, Int64, Array{Base.Markdown.MD, 1}, Int64, Int64}) -precompile(Tuple{typeof(Base.Docs.catdoc), Base.Markdown.MD}) -precompile(Tuple{typeof(Base.copy!), Base.IndexLinear, Array{Any, 1}, Base.IndexLinear, Array{Base.Markdown.MD, 1}}) -precompile(Tuple{Type{Base.Markdown.MD}, Array{Base.Markdown.MD, 1}}) -precompile(Tuple{Type{Base.Markdown.MD}, Base.Markdown.MD}) -precompile(Tuple{typeof(Base.vcat), Base.Markdown.MD}) -precompile(Tuple{typeof(Base.put!), Base.Channel{Any}, Tuple{Base.Markdown.MD, Void}}) -precompile(Tuple{typeof(Base.put_buffered), Base.Channel{Any}, Tuple{Base.Markdown.MD, Void}}) -precompile(Tuple{typeof(Base.put_unbuffered), Base.Channel{Any}, Tuple{Base.Markdown.MD, Void}}) -precompile(Tuple{typeof(Base.start), Tuple{Base.Markdown.MD, Void}}) -precompile(Tuple{typeof(Base.indexed_next), Tuple{Base.Markdown.MD, Void}, Int64, Int64}) -precompile(Tuple{typeof(Base.Multimedia.display), Base.Markdown.MD}) -precompile(Tuple{typeof(Base.Multimedia.display), Base.REPL.REPLDisplay{Base.REPL.LineEditREPL}, Base.Markdown.MD}) -precompile(Tuple{typeof(Base.displaysize), Base.Terminals.TTYTerminal}) -precompile(Tuple{typeof(Base.Markdown.term), Base.Terminals.TTYTerminal, Array{Any, 1}, Int64}) -precompile(Tuple{typeof(Base.Markdown.term), Base.Terminals.TTYTerminal, Base.Markdown.MD, Int64}) -precompile(Tuple{typeof(Base.Markdown.term), Base.Terminals.TTYTerminal, Base.Markdown.Code, Int64}) -precompile(Tuple{typeof(Base.write), Base.Terminals.TTYTerminal, Base.SubString{String}}) -precompile(Tuple{typeof(Base.print), Base.Terminals.TTYTerminal, Base.SubString{String}}) -precompile(Tuple{typeof(Base.print), Base.Terminals.TTYTerminal, Base.SubString{String}, Char}) -precompile(Tuple{typeof(Base.Markdown.term), Base.Terminals.TTYTerminal, Base.Markdown.Paragraph, Int64}) -precompile(Tuple{typeof(Core.Inference.eltype), Type{Array{T, 2} where T}}) -precompile(Tuple{getfield(Base.Markdown, Symbol("#kw##wrapped_lines")), Array{Any, 1}, typeof(Base.Markdown.wrapped_lines), String}) -precompile(Tuple{typeof(Base.start), Tuple{Symbol, String}}) -precompile(Tuple{typeof(Base.Markdown.terminline), Base.AbstractIOBuffer{Array{UInt8, 1}}, Array{Any, 1}}) -precompile(Tuple{typeof(Base.Markdown.terminline), Base.AbstractIOBuffer{Array{UInt8, 1}}, String}) -precompile(Tuple{typeof(Base.Markdown.terminline), Base.AbstractIOBuffer{Array{UInt8, 1}}, Base.Markdown.Code}) -precompile(Tuple{typeof(Base._search), Base.SubString{String}, String, Int64}) -precompile(Tuple{typeof(Base._split), Base.SubString{String}, String, Int64, Bool, Array{Base.SubString{String}, 1}}) -precompile(Tuple{getfield(Base.Markdown, Symbol("#kw##wrapped_lines")), Array{Any, 1}, typeof(Base.Markdown.wrapped_lines), Base.SubString{String}}) -precompile(Tuple{typeof(Base.endof), Array{AbstractString, 1}}) -precompile(Tuple{typeof(Base.getindex), Array{AbstractString, 1}, Base.UnitRange{Int64}}) -precompile(Tuple{typeof(Base.throw_boundserror), Array{AbstractString, 1}, Tuple{Base.UnitRange{Int64}}}) -precompile(Tuple{typeof(Base.unsafe_copy!), Array{AbstractString, 1}, Int64, Array{AbstractString, 1}, Int64, Int64}) -precompile(Tuple{typeof(Base.start), Array{AbstractString, 1}}) -precompile(Tuple{typeof(Base.done), Array{AbstractString, 1}, Int64}) -precompile(Tuple{typeof(Base.replace), String, Base.Regex, String}) -precompile(Tuple{typeof(Base.Distributed.addprocs), Int64}) -precompile(Tuple{typeof(Base.setindex!), Base.Dict{Any, Any}, Base.Cmd, Symbol}) -precompile(Tuple{typeof(Base._setindex!), Base.Dict{Any, Any}, Base.Cmd, Symbol, Int64}) -precompile(Tuple{typeof(Base.setindex!), Base.Dict{Any, Any}, Bool, Symbol}) -precompile(Tuple{typeof(Base._setindex!), Base.Dict{Any, Any}, Bool, Symbol, Int64}) -precompile(Tuple{typeof(Base.merge!), Base.Dict{Any, Any}, Base.Dict{Any, Any}, Base.Dict{Any, Any}}) -precompile(Tuple{Type{Symbol}, Symbol}) -precompile(Tuple{typeof(Core.Inference.mk_getfield), TypedSlot, Int64, Type{String}}) -precompile(Tuple{getfield(Core, Symbol("#kw#Type")), Array{Any, 1}, Type{Base.Cmd}, Base.Cmd}) -precompile(Tuple{typeof(Base.uv_status_string), Base.PipeEndpoint}) -precompile(Tuple{typeof(Base._fd), Base.PipeEndpoint}) -precompile(Tuple{typeof(Base.print), Base.AbstractIOBuffer{Array{UInt8, 1}}, Base.PipeEndpoint}) -precompile(Tuple{typeof(Base.unpreserve_handle), Base.PipeEndpoint}) -precompile(Tuple{typeof(Base.isopen), Base.PipeEndpoint}) -precompile(Tuple{typeof(Base.stream_wait), Base.PipeEndpoint, Base.Condition}) -precompile(Tuple{typeof(Base.close), Base.PipeEndpoint}) -precompile(Tuple{getfield(Base, Symbol("#kw##setenv")), Array{Any, 1}, typeof(Base.setenv), Base.Cmd}) -precompile(Tuple{Type{Base.Distributed.WorkerConfig}}) -precompile(Tuple{typeof(Base.Distributed.launch), Base.Distributed.LocalManager, Base.Dict{Any, Any}, Array{Base.Distributed.WorkerConfig, 1}, Base.Condition}) -precompile(Tuple{typeof(Base.julia_cmd), String}) -precompile(Tuple{typeof(Base.cmd_gen), Tuple{Tuple{String}, Tuple{String, String}, Tuple{String, String}, Tuple{String, String}, Tuple{String, String}}}) -precompile(Tuple{typeof(Base.arg_gen), String, String}) -precompile(Tuple{typeof(Base.cmd_gen), Tuple{Tuple{Base.Cmd}, Tuple{Base.Cmd}, Tuple{String}, Tuple{Base.Cmd}, Tuple{String}, Tuple{String}}}) -precompile(Tuple{typeof(Base.arg_gen), Base.Cmd}) -precompile(Tuple{typeof(Base.promote_type), Type{Bool}, Type{UInt8}}) -precompile(Tuple{typeof(Base.promote_rule), Type{UInt8}, Type{Bool}}) -precompile(Tuple{typeof(Base.promote_result), Type{Bool}, Type{UInt8}, Type{UInt8}, Type{Union{}}}) -precompile(Tuple{typeof(Base.promote_type), Type{UInt8}, Type{Union{}}}) -precompile(Tuple{typeof(Base.detach), Base.Cmd}) -precompile(Tuple{typeof(Base.open), Base.CmdRedirect, String, Base.DevNullStream}) -precompile(Tuple{typeof(Base.spawn), Base.CmdRedirect, Tuple{Base.DevNullStream, Base.Pipe, Base.IOStream}}) -precompile(Tuple{getfield(Base, Symbol("#kw##spawn")), Array{Any, 1}, typeof(Base.spawn), Base.Cmd, Tuple{Base.DevNullStream, Base.Pipe, Base.IOStream}}) -precompile(Tuple{getfield(Base, Symbol("#kw##init_pipe!")), Array{Any, 1}, typeof(Base.init_pipe!), Base.PipeEndpoint}) -precompile(Tuple{typeof(Base._link_pipe), Ptr{Void}, Ptr{Void}}) -precompile(Tuple{typeof(Base.link_pipe), Base.PipeEndpoint, Bool, Base.PipeEndpoint, Bool}) -precompile(Tuple{typeof(Base.close), Base.Filesystem.File}) -precompile(Tuple{typeof(Base.setup_stdio), Base.Pipe, Bool}) -precompile(Tuple{typeof(Base.setup_stdio), Base.IOStream, Bool}) -precompile(Tuple{Type{Base.Process}, Base.Cmd, Ptr{Void}, Base.DevNullStream, Base.Pipe, Base.IOStream}) -precompile(Tuple{typeof(Base._jl_spawn), String, Array{String, 1}, Ptr{Void}, Base.Process, Base.DevNullStream, Base.PipeEndpoint, Base.Filesystem.File}) -precompile(Tuple{Type{Base.Timer}, Int64, Float64}) -precompile(Tuple{typeof(Base.sleep), Int64}) -precompile(Tuple{typeof(Base._uv_hook_close), Base.PipeEndpoint}) -precompile(Tuple{typeof(Base.eltype), Type{Base.Nullable{IO}}}) -precompile(Tuple{Type{Base.Nullable{IO}}}) -precompile(Tuple{typeof(Base.eltype), Type{Base.Nullable{AbstractString}}}) -precompile(Tuple{Type{Base.Nullable{AbstractString}}}) -precompile(Tuple{typeof(Base.eltype), Type{Base.Nullable{Integer}}}) -precompile(Tuple{Type{Base.Nullable{Integer}}}) -precompile(Tuple{typeof(Base.eltype), Type{Base.Nullable{Union{Int64, Symbol}}}}) -precompile(Tuple{Type{Base.Nullable{Union{Int64, Symbol}}}}) -precompile(Tuple{typeof(Base.eltype), Type{Base.Nullable{Base.Cmd}}}) -precompile(Tuple{Type{Base.Nullable{Base.Cmd}}}) -precompile(Tuple{typeof(Base.eltype), Type{Base.Nullable{Any}}}) -precompile(Tuple{Type{Base.Nullable{Any}}}) -precompile(Tuple{typeof(Base.eltype), Type{Base.Nullable{Bool}}}) -precompile(Tuple{Type{Base.Nullable{Bool}}}) -precompile(Tuple{typeof(Base.eltype), Type{Base.Nullable{Base.Process}}}) -precompile(Tuple{Type{Base.Nullable{Base.Process}}}) -precompile(Tuple{typeof(Base.eltype), Type{Base.Nullable{Base.Dict{K, V} where V where K}}}) -precompile(Tuple{Type{Base.Nullable{Base.Dict{K, V} where V where K}}}) -precompile(Tuple{typeof(Base.eltype), Type{Base.Nullable{Array{T, N} where N where T}}}) -precompile(Tuple{Type{Base.Nullable{Array{T, N} where N where T}}}) -precompile(Tuple{typeof(Base.convert), Type{Base.Nullable{Base.Process}}, Base.Process}) -precompile(Tuple{typeof(Base.convert), Type{Base.Nullable{Bool}}, Bool}) -precompile(Tuple{typeof(Base.task_done_hook), Task}) -precompile(Tuple{typeof(Base.getindex), Tuple{Array{Any, 1}, Tuple{}}, Int64}) -precompile(Tuple{Type{Base.TCPSocket}}) -precompile(Tuple{typeof(Base.getsockname), Base.TCPSocket}) -precompile(Tuple{typeof(Base.unsafe_store!), Ptr{Int32}, Int64}) -precompile(Tuple{Type{Base.Multimedia.TextDisplay}, Base.PipeEndpoint}) -precompile(Tuple{typeof(Base.Distributed.start_worker), Base.PipeEndpoint, String}) -precompile(Tuple{typeof(Core.Inference.isbits), OutOfMemoryError}) -precompile(Tuple{typeof(Core.Inference.isbits), Tuple{Int64, Int64, Int64, Int64, Int64, Int64, Int64, Int64, Int64, Int64, Int64, Int64, Int64}}) -precompile(Tuple{typeof(Base.getaddrinfo), String}) -precompile(Tuple{typeof(Base.uv_status_string), Base.PipeEndpoint}) -precompile(Tuple{typeof(Base._fd), Base.PipeEndpoint}) -precompile(Tuple{typeof(Base.print), Base.AbstractIOBuffer{Array{UInt8, 1}}, Base.PipeEndpoint}) -precompile(Tuple{typeof(Base.print), Base.AbstractIOBuffer{Array{UInt8, 1}}, UInt16}) -precompile(Tuple{typeof(Base.isopen), Base.PipeEndpoint}) -precompile(Tuple{typeof(Base.unpreserve_handle), Task}) -precompile(Tuple{typeof(Base.check_open), Base.PipeEndpoint}) -precompile(Tuple{typeof(Base.stream_wait), Task}) -precompile(Tuple{typeof(Base.uv_write), Base.PipeEndpoint, Ptr{UInt8}, UInt64}) -precompile(Tuple{typeof(Base.flush), Base.PipeEndpoint}) -precompile(Tuple{typeof(Base.unsafe_write), Base.PipeEndpoint, Ptr{UInt8}, UInt64}) -precompile(Tuple{typeof(Base.unsafe_write), Base.PipeEndpoint, Base.RefValue{UInt8}, Int64}) -precompile(Tuple{typeof(Base.uv_status_string), Base.TCPSocket}) -precompile(Tuple{typeof(Base._fd), Base.TCPSocket}) -precompile(Tuple{typeof(Base.print), Base.PipeEndpoint, String}) -precompile(Tuple{typeof(Base.print), Base.PipeEndpoint, Char}) -precompile(Tuple{typeof(Base.print), Base.PipeEndpoint, String, Char}) -precompile(Tuple{typeof(Base.print), Base.AbstractIOBuffer{Array{UInt8, 1}}, Base.TCPSocket}) -precompile(Tuple{typeof(Base.write), Base.PipeEndpoint, Char}) -precompile(Tuple{typeof(Base.isopen), Base.TCPSocket}) -precompile(Tuple{typeof(Base.unpreserve_handle), Base.TCPSocket}) -precompile(Tuple{typeof(Base.check_open), Base.TCPSocket}) -precompile(Tuple{typeof(Base.stream_wait), Base.TCPSocket, Base.Condition}) -precompile(Tuple{typeof(Base.wait_connected), Base.TCPSocket}) -precompile(Tuple{typeof(Base.print), Base.AbstractIOBuffer{Array{UInt8, 1}}, String, Base.IPv4, String}) -precompile(Tuple{typeof(Base.print), Base.AbstractIOBuffer{Array{UInt8, 1}}, String, Base.IPv6, String}) -precompile(Tuple{typeof(Base.Distributed.socket_reuse_port)}) -precompile(Tuple{typeof(Base.promote_type), Type{Int64}, Type{Int16}}) -precompile(Tuple{typeof(Base.promote_rule), Type{Int16}, Type{Int64}}) -precompile(Tuple{typeof(Base.promote_result), Type{Int64}, Type{Int16}, Type{Int64}, Type{Union{}}}) -precompile(Tuple{typeof(Base.Distributed.flush_gc_msgs)}) -precompile(Tuple{typeof(Base.show), Base.AbstractIOBuffer{Array{UInt8, 1}}, Int16}) -precompile(Tuple{typeof(Base.print), Base.AbstractIOBuffer{Array{UInt8, 1}}, Int16}) -precompile(Tuple{typeof(Base.uv_status_string), Base.PipeServer}) -precompile(Tuple{typeof(Base._fd), Base.PipeServer}) -precompile(Tuple{typeof(Base.convert), Type{Int16}, Int16}) -precompile(Tuple{typeof(Base.string), String, Int16, String, String, String, String}) -precompile(Tuple{typeof(Base.print), Base.AbstractIOBuffer{Array{UInt8, 1}}, Base.PipeServer}) -precompile(Tuple{typeof(Base.unpreserve_handle), Base.PipeServer}) -precompile(Tuple{typeof(Base.isopen), Base.PipeServer}) -precompile(Tuple{typeof(Base.accept_nonblock), Base.PipeServer, Base.PipeEndpoint}) -precompile(Tuple{typeof(Base.stream_wait), Base.PipeServer, Base.Condition}) -precompile(Tuple{getfield(Base, Symbol("#kw##init_pipe!")), Array{Any, 1}, typeof(Base.init_pipe!), Base.PipeEndpoint}) -precompile(Tuple{typeof(Base.accept), Base.PipeServer, Base.PipeEndpoint}) -precompile(Tuple{typeof(Base.accept_nonblock), Base.TCPServer, Base.TCPSocket}) -precompile(Tuple{Type{Base.TCPSocket}}) -precompile(Tuple{typeof(Base.accept), Base.TCPServer, Base.TCPSocket}) -precompile(Tuple{typeof(Base.accept), Base.TCPServer}) -precompile(Tuple{typeof(Base.tryparse_internal), Type{Int16}, Base.SubString{String}, Int64, Int64, Int64, Bool}) -precompile(Tuple{typeof(Base.parse), Type{Int16}, Base.SubString{String}}) -precompile(Tuple{typeof(Base.write), Base.PipeEndpoint, String}) -precompile(Tuple{typeof(Base.Distributed.disable_nagle), Base.TCPServer}) -precompile(Tuple{typeof(Base.Distributed.next_tunnel_port)}) -precompile(Tuple{typeof(Core.Inference.isbits), Tuple{Tuple{String}, Tuple{String}, Tuple{String}, Tuple{String}, Tuple{String}, Tuple{String}}}) -precompile(Tuple{typeof(Base.cmd_gen), Tuple{Tuple{String}, Tuple{String}, Tuple{String}, Tuple{String}, Tuple{String}, Tuple{String}}}) -precompile(Tuple{typeof(Base._delete!), Base.Dict{Int64, Union{Base.Distributed.Worker, Base.Distributed.LocalProcess}}, Int64}) -precompile(Tuple{typeof(Base.ndigits0z), UInt8}) -precompile(Tuple{typeof(Base.dec), UInt8, Int64, Bool}) -precompile(Tuple{typeof(Core.Inference.length), Tuple{Core.Inference.Const, typeof(Type), Core.Inference.Const}}) -precompile(Tuple{typeof(Core.Inference.getindex), Tuple{Core.Inference.Const, typeof(Type), Core.Inference.Const}, Int64}) -precompile(Tuple{typeof(Base.Distributed.send_msg_), Base.Distributed.Worker, Base.Distributed.MsgHeader, Base.Distributed.JoinPGRPMsg, Bool}) -precompile(Tuple{typeof(Base.Distributed.send_msg_now), Base.Distributed.Worker, Base.Distributed.MsgHeader, Base.Distributed.JoinPGRPMsg}) -precompile(Tuple{typeof(Base.rehash!), Base.Dict{Int64, Void}, Int64}) -precompile(Tuple{typeof(Base.ht_keyindex2), Base.Dict{Int64, Void}, Int64}) -precompile(Tuple{typeof(Base._setindex!), Base.Dict{Int64, Void}, Void, Int64, Int64}) -precompile(Tuple{typeof(Base.rehash!), Base.Dict{AbstractString, Base.Semaphore}, Int64}) -precompile(Tuple{typeof(Base.resize!), Array{Base.Semaphore, 1}, Int64}) -precompile(Tuple{typeof(Base.Distributed.connect_w2w), Int64, Base.Distributed.WorkerConfig}) -precompile(Tuple{typeof(Base.acquire), Base.Semaphore}) -precompile(Tuple{typeof(Base.release), Base.Semaphore}) -precompile(Tuple{typeof(Base.Distributed.create_worker), Base.Distributed.LocalManager, Base.Distributed.WorkerConfig}) -precompile(Tuple{typeof(Base.Distributed.setup_launched_worker), Base.Distributed.LocalManager, Base.Distributed.WorkerConfig, Array{Int64, 1}}) -precompile(Tuple{typeof(Base.connect), Base.Distributed.LocalManager, Int64, Base.Distributed.WorkerConfig}) -precompile(Tuple{typeof(Base.Distributed.read_worker_host_port), Base.Pipe}) -precompile(Tuple{typeof(Base.isreadable), Base.PipeEndpoint}) -precompile(Tuple{typeof(Base.search), Base.AbstractIOBuffer{Array{UInt8, 1}}, UInt8}) -precompile(Tuple{typeof(Base.start_reading), Base.PipeEndpoint}) -precompile(Tuple{typeof(Base.wait_readbyte), Base.PipeEndpoint, UInt8}) -precompile(Tuple{typeof(Base.readuntil), Base.PipeEndpoint, UInt8}) -precompile(Tuple{typeof(Base.alloc_buf_hook), Base.PipeEndpoint, UInt64}) -precompile(Tuple{typeof(Base._uv_hook_close), Base.Timer}) -precompile(Tuple{typeof(Base.notify), Base.Condition, Base.EOFError, Bool, Bool}) -precompile(Tuple{typeof(Base.unpreserve_handle), Base.Timer}) -precompile(Tuple{typeof(Base.disassociate_julia_struct), Base.Timer}) -precompile(Tuple{typeof(Base.Distributed.parse_connection_info), String}) -precompile(Tuple{typeof(Base._uv_hook_close), Base.Timer}) -precompile(Tuple{typeof(Base.notify), Base.Condition, Base.EOFError, Bool, Bool}) -precompile(Tuple{typeof(Base.unpreserve_handle), Base.Timer}) -precompile(Tuple{typeof(Base.disassociate_julia_struct), Base.Timer}) -precompile(Tuple{typeof(Base.convert), Type{Base.Nullable{AbstractString}}, Base.SubString{String}}) -precompile(Tuple{typeof(Base.Distributed.connect_to_worker), Base.SubString{String}, Int16}) -precompile(Tuple{typeof(Base.connect!), Base.TCPSocket, Base.SubString{String}, UInt16}) -precompile(Tuple{typeof(Base.notify), Base.Condition, Base.IPv4, Bool, Bool}) -precompile(Tuple{typeof(Base.schedule), Task, Base.IPv4}) -precompile(Tuple{typeof(Base.connect!), Base.TCPSocket, Base.IPv4, UInt16}) -precompile(Tuple{typeof(Base.Distributed.process_messages), Base.TCPSocket, Base.TCPSocket, Bool}) -precompile(Tuple{typeof(Base.uv_status_string), Base.TCPSocket}) -precompile(Tuple{typeof(Base._fd), Base.TCPSocket}) -precompile(Tuple{typeof(Base.print), Base.AbstractIOBuffer{Array{UInt8, 1}}, Base.TCPSocket}) -precompile(Tuple{typeof(Base.isopen), Base.TCPSocket}) -precompile(Tuple{typeof(Base.convert), Type{Base.Nullable{AbstractString}}, String}) -precompile(Tuple{typeof(Base.unpreserve_handle), Base.TCPSocket}) -precompile(Tuple{typeof(Base.check_open), Base.TCPSocket}) -precompile(Tuple{typeof(Base.stream_wait), Base.TCPSocket, Base.Condition}) -precompile(Tuple{getfield(Core, Symbol("#kw#Type")), Array{Any, 1}, Type{Base.Distributed.Worker}, Int64, Base.TCPSocket, Base.TCPSocket, Base.Distributed.LocalManager}) -precompile(Tuple{typeof(Base.read_sub), Base.AbstractIOBuffer{Array{UInt8, 1}}, Array{UInt8, 1}, Int64, Int64}) -precompile(Tuple{typeof(Base.isreadable), Base.TCPSocket}) -precompile(Tuple{typeof(Base.start_reading), Base.TCPSocket}) -precompile(Tuple{typeof(Base.write_sub), Base.AbstractIOBuffer{Array{UInt8, 1}}, Array{UInt8, 1}, Int64, Int64}) -precompile(Tuple{typeof(Base.readbytes!), Base.AbstractIOBuffer{Array{UInt8, 1}}, Array{UInt8, 1}, Int64}) -precompile(Tuple{typeof(Base.wait_readnb), Base.TCPSocket, Int64}) -precompile(Tuple{typeof(Base.write), Base.AbstractIOBuffer{Array{UInt8, 1}}, Base.AbstractIOBuffer{Array{UInt8, 1}}}) -precompile(Tuple{typeof(Base.readbytes!), Base.TCPSocket, Array{UInt8, 1}, Int64}) -precompile(Tuple{typeof(Base.read), Base.TCPSocket, Int64}) -precompile(Tuple{typeof(Base.Distributed.worker_id_from_socket), Base.TCPSocket}) -precompile(Tuple{Type{Base.Distributed.ClusterSerializer{Base.TCPSocket}}, Base.TCPSocket}) -precompile(Tuple{typeof(Base.unsafe_read), Base.TCPSocket, Ptr{UInt8}, UInt64}) -precompile(Tuple{typeof(Base.read!), Base.TCPSocket, Array{Int64, 1}}) -precompile(Tuple{typeof(Base.read), Base.TCPSocket, Type{UInt8}}) -precompile(Tuple{typeof(Base.Distributed.send_msg_), Base.Distributed.Worker, Base.Distributed.MsgHeader, Base.Distributed.ResultMsg, Bool}) -precompile(Tuple{typeof(Base.Distributed.send_msg_now), Base.Distributed.Worker, Base.Distributed.MsgHeader, Base.Distributed.ResultMsg}) -precompile(Tuple{Type{Core.Inference.Generator{I, F} where F where I}, Type{Core.Inference.Const}, Tuple{Int64, typeof(Base.Distributed.rmprocs)}}) -precompile(Tuple{Type{Core.Inference.Generator{Tuple{Int64, typeof(Base.Distributed.rmprocs)}, Type{Core.Inference.Const}}}, Type{Core.Inference.Const}, Tuple{Int64, typeof(Base.Distributed.rmprocs)}}) -precompile(Tuple{typeof(Core.Inference.convert), Type{Tuple{Int64, typeof(Base.Distributed.rmprocs)}}, Tuple{Int64, typeof(Base.Distributed.rmprocs)}}) -precompile(Tuple{typeof(Core.Inference.collect), Type{Any}, Core.Inference.Generator{Tuple{Int64, typeof(Base.Distributed.rmprocs)}, Type{Core.Inference.Const}}}) -precompile(Tuple{typeof(Core.Inference.iteratorsize), Core.Inference.Generator{Tuple{Int64, typeof(Base.Distributed.rmprocs)}, Type{Core.Inference.Const}}}) -precompile(Tuple{typeof(Core.Inference.iteratorsize), Type{Core.Inference.Generator{Tuple{Int64, typeof(Base.Distributed.rmprocs)}, Type{Core.Inference.Const}}}}) -precompile(Tuple{typeof(Core.Inference.iteratorsize), Type{Tuple{Int64, typeof(Base.Distributed.rmprocs)}}}) -precompile(Tuple{typeof(Core.Inference._collect), Type{Any}, Core.Inference.Generator{Tuple{Int64, typeof(Base.Distributed.rmprocs)}, Type{Core.Inference.Const}}, Core.Inference.HasLength}) -precompile(Tuple{typeof(Core.Inference.length), Core.Inference.Generator{Tuple{Int64, typeof(Base.Distributed.rmprocs)}, Type{Core.Inference.Const}}}) -precompile(Tuple{typeof(Core.Inference.length), Tuple{Int64, typeof(Base.Distributed.rmprocs)}}) -precompile(Tuple{typeof(Core.Inference.copy!), Array{Any, 1}, Core.Inference.Generator{Tuple{Int64, typeof(Base.Distributed.rmprocs)}, Type{Core.Inference.Const}}}) -precompile(Tuple{typeof(Core.Inference.start), Core.Inference.Generator{Tuple{Int64, typeof(Base.Distributed.rmprocs)}, Type{Core.Inference.Const}}}) -precompile(Tuple{typeof(Core.Inference.start), Tuple{Int64, typeof(Base.Distributed.rmprocs)}}) -precompile(Tuple{typeof(Core.Inference.done), Core.Inference.Generator{Tuple{Int64, typeof(Base.Distributed.rmprocs)}, Type{Core.Inference.Const}}, Int64}) -precompile(Tuple{typeof(Core.Inference.done), Tuple{Int64, typeof(Base.Distributed.rmprocs)}, Int64}) -precompile(Tuple{typeof(Core.Inference.next), Core.Inference.Generator{Tuple{Int64, typeof(Base.Distributed.rmprocs)}, Type{Core.Inference.Const}}, Int64}) -precompile(Tuple{typeof(Core.Inference.next), Tuple{Int64, typeof(Base.Distributed.rmprocs)}, Int64}) -precompile(Tuple{typeof(Core.Inference.getindex), Tuple{Int64, typeof(Base.Distributed.rmprocs)}, Int64}) -precompile(Tuple{typeof(Core.Inference.start), Tuple{typeof(Base.Distributed.rmprocs), Int64}}) -precompile(Tuple{typeof(Core.Inference.indexed_next), Tuple{typeof(Base.Distributed.rmprocs), Int64}, Int64, Int64}) -precompile(Tuple{typeof(Core.Inference.getindex), Tuple{typeof(Base.Distributed.rmprocs), Int64}, Int64}) -precompile(Tuple{typeof(Base.Distributed.register_worker_streams), Base.Distributed.Worker}) -precompile(Tuple{typeof(Base.Distributed.register_worker_streams), Base.Distributed.LocalProcess}) -precompile(Tuple{typeof(Base.convert), Type{IO}, Base.TCPSocket}) -precompile(Tuple{Type{Base.Distributed.ClusterSerializer{Base.TCPSocket}}, Base.TCPSocket}) -precompile(Tuple{typeof(Base.Distributed.worker_id_from_socket), Base.TCPSocket}) -precompile(Tuple{typeof(Base.convert), Type{Base.Distributed.ClusterSerializer{I} where I<:IO}, Base.Distributed.ClusterSerializer{Base.TCPSocket}}) -precompile(Tuple{typeof(Base.convert), Type{Base.Distributed.ClusterManager}, Base.Distributed.LocalManager}) -precompile(Tuple{typeof(Base.convert), Type{Base.Distributed.WorkerConfig}, Base.Distributed.WorkerConfig}) -precompile(Tuple{typeof(Base.convert), Type{Base.Nullable{Base.VersionNumber}}, Base.Nullable{Base.VersionNumber}}) -precompile(Tuple{typeof(Base.join), Base.AbstractIOBuffer{Array{UInt8, 1}}, Tuple{Int64}, Char}) -precompile(Tuple{typeof(Base.get), Base.Dict{Any, Any}, Base.Distributed.RRID, Bool}) -precompile(Tuple{typeof(Base.ht_keyindex), Base.Dict{Any, Any}, Base.Distributed.RRID}) -precompile(Tuple{typeof(Core.Inference.isbits), Tuple{Int64, typeof(Base.Distributed.rmprocs)}}) -precompile(Tuple{Type{Core.Inference.Generator{I, F} where F where I}, Type{QuoteNode}, Tuple{Int64, typeof(Base.Distributed.rmprocs)}}) -precompile(Tuple{Type{Core.Inference.Generator{Tuple{Int64, typeof(Base.Distributed.rmprocs)}, Type{QuoteNode}}}, Type{QuoteNode}, Tuple{Int64, typeof(Base.Distributed.rmprocs)}}) -precompile(Tuple{typeof(Core.Inference.iteratorsize), Type{Core.Inference.Generator{Tuple{Int64, typeof(Base.Distributed.rmprocs)}, Type{QuoteNode}}}}) -precompile(Tuple{typeof(Core.Inference._collect), Type{Any}, Core.Inference.Generator{Tuple{Int64, typeof(Base.Distributed.rmprocs)}, Type{QuoteNode}}, Core.Inference.HasLength}) -precompile(Tuple{typeof(Core.Inference.length), Core.Inference.Generator{Tuple{Int64, typeof(Base.Distributed.rmprocs)}, Type{QuoteNode}}}) -precompile(Tuple{typeof(Core.Inference.copy!), Array{Any, 1}, Core.Inference.Generator{Tuple{Int64, typeof(Base.Distributed.rmprocs)}, Type{QuoteNode}}}) -precompile(Tuple{typeof(Core.Inference.start), Core.Inference.Generator{Tuple{Int64, typeof(Base.Distributed.rmprocs)}, Type{QuoteNode}}}) -precompile(Tuple{typeof(Core.Inference.done), Core.Inference.Generator{Tuple{Int64, typeof(Base.Distributed.rmprocs)}, Type{QuoteNode}}, Int64}) -precompile(Tuple{typeof(Core.Inference.next), Core.Inference.Generator{Tuple{Int64, typeof(Base.Distributed.rmprocs)}, Type{QuoteNode}}, Int64}) -precompile(Tuple{typeof(Base.Distributed.local_remotecall_thunk), typeof(Base.Distributed.rmprocs), Tuple{Int64}, Array{Any, 1}}) -precompile(Tuple{typeof(Base.Distributed.remote_do), typeof(Base.Distributed.rmprocs), Base.Distributed.Worker, Int64}) -precompile(Tuple{typeof(Base.Distributed.remote_do), typeof(Base.Distributed.rmprocs), Base.Distributed.LocalProcess, Int64}) -precompile(Tuple{getfield(Base.Distributed, Symbol("#kw##remote_do")), Array{Any, 1}, typeof(Base.Distributed.remote_do), typeof(Base.Distributed.rmprocs), Base.Distributed.Worker, Int64}) -precompile(Tuple{getfield(Base.Distributed, Symbol("#kw##remote_do")), Array{Any, 1}, typeof(Base.Distributed.remote_do), typeof(Base.Distributed.rmprocs), Base.Distributed.LocalProcess, Int64}) -precompile(Tuple{Type{Base.Distributed.ResultMsg}, Base.Distributed.RemoteException}) -precompile(Tuple{Type{Base.Distributed.ResultMsg}, Symbol}) -precompile(Tuple{typeof(Base.Distributed.send_msg_now), Base.TCPSocket, Base.Distributed.MsgHeader, Base.Distributed.ResultMsg}) -precompile(Tuple{typeof(Base.close), Base.TCPSocket}) -precompile(Tuple{typeof(Base._delete!), Base.Dict{Int64, Union{Base.Distributed.Worker, Base.Distributed.LocalProcess}}, Int64}) -precompile(Tuple{typeof(Base.Distributed.def_rv_channel)}) -precompile(Tuple{typeof(Base.convert), Type{Base.AbstractChannel}, Base.Channel{Any}}) -precompile(Tuple{typeof(Base.ndigits0z), UInt8}) -precompile(Tuple{typeof(Base.setindex!), Base.Dict{Any, Any}, Base.Distributed.RemoteValue, Base.Distributed.RRID}) -precompile(Tuple{typeof(Base.dec), UInt8, Int64, Bool}) -precompile(Tuple{typeof(Core.Inference.mk_getfield), TypedSlot, Int64, Type{Integer}}) -precompile(Tuple{typeof(Base.ht_keyindex2), Base.Dict{Any, Any}, Base.Distributed.RRID}) -precompile(Tuple{typeof(Base._setindex!), Base.Dict{Any, Any}, Base.Distributed.RemoteValue, Base.Distributed.RRID, Int64}) -precompile(Tuple{typeof(Core.Inference.length), Tuple{Core.Inference.Const, DataType, Core.Inference.Const}}) -precompile(Tuple{typeof(Core.Inference.getindex), Tuple{Core.Inference.Const, DataType, Core.Inference.Const}, Int64}) -precompile(Tuple{typeof(Base.notify), Base.Condition, Base.Distributed.ProcessExitedException, Bool, Bool}) -precompile(Tuple{typeof(Base.rehash!), Base.Dict{Int64, Void}, Int64}) -precompile(Tuple{typeof(Base.Distributed.process_messages), Base.TCPSocket, Base.TCPSocket, Bool}) -precompile(Tuple{typeof(Base.ht_keyindex2), Base.Dict{Int64, Void}, Int64}) -precompile(Tuple{typeof(Base._setindex!), Base.Dict{Int64, Void}, Void, Int64, Int64}) -precompile(Tuple{typeof(Base.setindex!), Base.Dict{Int64, Void}, Void, Int64}) -precompile(Tuple{typeof(Base.pop!), Base.Dict{Int64, Union{Base.Distributed.Worker, Base.Distributed.LocalProcess}}, Int64, Void}) -precompile(Tuple{typeof(Base.Distributed.send_connection_hdr), Base.Distributed.Worker, Bool}) -precompile(Tuple{typeof(Base.Distributed.deregister_worker), Base.Distributed.ProcessGroup, Int64}) -precompile(Tuple{typeof(Base.Distributed.process_hdr), Base.TCPSocket, Bool}) -precompile(Tuple{typeof(Base.Distributed.deserialize_msg), Base.Distributed.ClusterSerializer{Base.TCPSocket}}) -precompile(Tuple{typeof(Base.Distributed.null_id), Base.Distributed.RRID}) -precompile(Tuple{typeof(Base.Distributed.deliver_result), Base.TCPSocket, Symbol, Base.Distributed.RRID, Base.Distributed.RemoteException}) -precompile(Tuple{typeof(Base.Distributed.disable_nagle), Base.TCPSocket}) -precompile(Tuple{typeof(Base.wait_connected), Base.TCPSocket}) -precompile(Tuple{typeof(Base.Distributed.message_handler_loop), Base.TCPSocket, Base.TCPSocket, Bool}) -precompile(Tuple{typeof(Base.Distributed.process_tcp_streams), Base.TCPSocket, Base.TCPSocket, Bool}) -precompile(Tuple{typeof(Base.write), Base.TCPSocket, String}) -precompile(Tuple{typeof(Base.uv_write), Base.TCPSocket, Ptr{UInt8}, UInt64}) -precompile(Tuple{typeof(Base.flush), Base.TCPSocket}) -precompile(Tuple{typeof(Base.unsafe_write), Base.TCPSocket, Ptr{UInt8}, UInt64}) -precompile(Tuple{Type{Base.Distributed.JoinPGRPMsg}, Int64, Array{Union{Tuple{Any, Int64}, Tuple{Tuple{}, Any, Bool}}, 1}, Symbol, Bool}) -precompile(Tuple{typeof(Base.write), Base.TCPSocket, Int64, Int64, Int64, Int64}) -precompile(Tuple{typeof(Base.unsafe_write), Base.TCPSocket, Base.RefValue{Int64}, Int64}) -precompile(Tuple{typeof(Base.Serializer.serialize), Base.Distributed.ClusterSerializer{Base.TCPSocket}, Base.Distributed.JoinPGRPMsg}) -precompile(Tuple{typeof(Base.unsafe_write), Base.TCPSocket, Base.RefValue{UInt8}, Int64}) -precompile(Tuple{typeof(Base.Serializer.serialize), Base.Distributed.ClusterSerializer{Base.TCPSocket}, Int64}) -precompile(Tuple{typeof(Base.Serializer.serialize), Base.Distributed.ClusterSerializer{Base.TCPSocket}, Array{Union{Tuple{Any, Int64}, Tuple{Tuple{}, Any, Bool}}, 1}}) -precompile(Tuple{typeof(Core.Inference.length), Tuple{Core.Inference.Const, DataType, Core.Inference.Const}}) -precompile(Tuple{typeof(Core.Inference.getindex), Tuple{Core.Inference.Const, DataType, Core.Inference.Const}, Int64}) -precompile(Tuple{typeof(Base.unsafe_write), Base.TCPSocket, Base.RefValue{Int32}, Int64}) -precompile(Tuple{typeof(Base.Serializer.write_as_tag), Base.TCPSocket, Int32}) -precompile(Tuple{typeof(Base.copy!), Array{Any, 1}, Base.MethodList}) -precompile(Tuple{typeof(Base.Serializer.should_send_whole_type), Base.Distributed.ClusterSerializer{Base.TCPSocket}, Type{Any}}) -precompile(Tuple{typeof(Base.Serializer.serialize), Base.Distributed.ClusterSerializer{Base.TCPSocket}, SimpleVector}) -precompile(Tuple{typeof(Base.Serializer.serialize_type_data), Base.Distributed.ClusterSerializer{Base.TCPSocket}, Type{Any}, Bool}) -precompile(Tuple{typeof(Base.Serializer.serialize), Base.Distributed.ClusterSerializer{Base.TCPSocket}, Type{Any}}) -precompile(Tuple{typeof(Base.Serializer.serialize), Base.Distributed.ClusterSerializer{Base.TCPSocket}, Tuple{Int64}}) -precompile(Tuple{typeof(Base.ht_keyindex), Base.Dict{UInt64, UInt64}, UInt64}) -precompile(Tuple{typeof(Base.unique), Array{Symbol, 1}}) -precompile(Tuple{typeof(Base.Serializer.serialize_cycle), Base.Distributed.ClusterSerializer{Base.TCPSocket}, Type{Union{Tuple{Any, Int64}, Tuple{Tuple{}, Any, Bool}}}}) -precompile(Tuple{typeof(Base.Serializer.serialize_type), Base.Distributed.ClusterSerializer{Base.TCPSocket}, DataType}) -precompile(Tuple{typeof(Base.rehash!), Base.Dict{UInt64, UInt64}, Int64}) -precompile(Tuple{typeof(Base.resize!), Array{UInt64, 1}, Int64}) -precompile(Tuple{typeof(Base.ht_keyindex2), Base.Dict{UInt64, UInt64}, UInt64}) -precompile(Tuple{typeof(Base.Serializer.serialize), Base.Distributed.ClusterSerializer{Base.TCPSocket}, Bool}) -precompile(Tuple{typeof(Base.Distributed.serialize_global_from_main), Base.Distributed.ClusterSerializer{Base.TCPSocket}, Symbol}) -precompile(Tuple{typeof(Base.Serializer.serialize_mod_names), Base.Distributed.ClusterSerializer{Base.TCPSocket}, Module}) -precompile(Tuple{typeof(Base.Serializer.serialize), Base.Distributed.ClusterSerializer{Base.TCPSocket}, Symbol}) -precompile(Tuple{typeof(Core.Inference.isbits), Symbol}) -precompile(Tuple{typeof(Base.Serializer.serialize), Base.Distributed.ClusterSerializer{Base.TCPSocket}, Module}) -precompile(Tuple{typeof(Base.isassigned), Array{Symbol, 1}, Int64}) -precompile(Tuple{typeof(Base.rehash!), Base.Dict{UInt64, Void}, Int64}) -precompile(Tuple{typeof(Base.ht_keyindex2), Base.Dict{UInt64, Void}, UInt64}) -precompile(Tuple{typeof(Base._setindex!), Base.Dict{UInt64, Void}, Void, UInt64, Int64}) -precompile(Tuple{typeof(Base.Serializer.serialize), Base.Distributed.ClusterSerializer{Base.TCPSocket}, Array{Any, 1}}) -precompile(Tuple{typeof(Base.ht_keyindex), Base.Dict{WeakRef, Any}, TypeName}) -precompile(Tuple{typeof(Base.Serializer.serialize_cycle), Base.Distributed.ClusterSerializer{Base.TCPSocket}, TypeName}) -precompile(Tuple{typeof(Base.Serializer.object_number), TypeName}) -precompile(Tuple{typeof(Base.Serializer.serialize_typename), Base.Distributed.ClusterSerializer{Base.TCPSocket}, TypeName}) -precompile(Tuple{typeof(Base.Serializer.serialize), Base.Distributed.ClusterSerializer{Base.TCPSocket}, Array{Symbol, 1}}) -precompile(Tuple{typeof(Base.Serializer.serialize), Base.Distributed.ClusterSerializer{Base.TCPSocket}, TypeName}) -precompile(Tuple{typeof(Base.Serializer.serialize_cycle_header), Base.Distributed.ClusterSerializer{Base.TCPSocket}, Type{Union{Tuple{Any, Int64}, Tuple{Tuple{}, Any, Bool}}}}) -precompile(Tuple{typeof(Base.Serializer.serialize_any), Base.Distributed.ClusterSerializer{Base.TCPSocket}, Type{Union{Tuple{Any, Int64}, Tuple{Tuple{}, Any, Bool}}}}) -precompile(Tuple{typeof(Base.isassigned), Array{Union{Tuple{Any, Int64}, Tuple{Tuple{}, Any, Bool}}, 1}, Int64}) -precompile(Tuple{typeof(Base.uvfinalize), Base.TCPSocket}) -precompile(Tuple{typeof(Base.close), Base.TCPSocket}) -precompile(Tuple{typeof(Base.write), Base.TCPSocket, Array{UInt8, 1}}) -precompile(Tuple{typeof(Base.wait_readnb), Base.PipeEndpoint, Int64}) -precompile(Tuple{typeof(Base.eof), Base.PipeEndpoint}) -precompile(Tuple{typeof(Base.unsafe_read), Base.TCPSocket, Base.RefValue{Int32}, Int64}) -precompile(Tuple{typeof(Base.unsafe_read), Base.TCPSocket, Base.RefValue{Int64}, Int64}) -precompile(Tuple{typeof(Base.read!), Base.TCPSocket, Array{UInt8, 1}}) -precompile(Tuple{typeof(Base.read_sub), Base.AbstractIOBuffer{Array{UInt8, 1}}, Array{UInt8, 1}, Int64, Int64}) -precompile(Tuple{typeof(Base.isreadable), Base.TCPSocket}) -precompile(Tuple{typeof(Base.start_reading), Base.TCPSocket}) -precompile(Tuple{typeof(Base.write_sub), Base.AbstractIOBuffer{Array{UInt8, 1}}, Array{UInt8, 1}, Int64, Int64}) -precompile(Tuple{typeof(Base.readbytes!), Base.AbstractIOBuffer{Array{UInt8, 1}}, Array{UInt8, 1}, Int64}) -precompile(Tuple{typeof(Base.wait_readnb), Base.TCPSocket, Int64}) -precompile(Tuple{typeof(Base.write), Base.AbstractIOBuffer{Array{UInt8, 1}}, Base.AbstractIOBuffer{Array{UInt8, 1}}}) -precompile(Tuple{typeof(Base.readbytes!), Base.TCPSocket, Array{UInt8, 1}, Int64}) -precompile(Tuple{typeof(Base.read), Base.TCPSocket, Int64}) -precompile(Tuple{typeof(Base.promote_type), Type{Int64}, Type{UInt8}}) -precompile(Tuple{typeof(Base.promote_rule), Type{Int64}, Type{UInt8}}) -precompile(Tuple{typeof(Base.promote_result), Type{Int64}, Type{UInt8}, Type{Union{}}, Type{Int64}}) -precompile(Tuple{typeof(Base.read!), Base.TCPSocket, Array{UInt64, 1}}) -precompile(Tuple{typeof(Base.unsafe_read), Base.TCPSocket, Ptr{UInt8}, UInt64}) -precompile(Tuple{typeof(Base.read!), Base.TCPSocket, Array{Int64, 1}}) -precompile(Tuple{typeof(Base.read), Base.TCPSocket, Type{UInt8}}) -precompile(Tuple{typeof(Base.Distributed.send_msg_), Base.Distributed.Worker, Base.Distributed.MsgHeader, Base.Distributed.ResultMsg, Bool}) -precompile(Tuple{typeof(Base.Distributed.send_msg_now), Base.Distributed.Worker, Base.Distributed.MsgHeader, Base.Distributed.ResultMsg}) -precompile(Tuple{Type{Core.Inference.Generator{I, F} where F where I}, Type{Core.Inference.Const}, Tuple{Int64, typeof(Base.Distributed.rmprocs)}}) -precompile(Tuple{Type{Core.Inference.Generator{Tuple{Int64, typeof(Base.Distributed.rmprocs)}, Type{Core.Inference.Const}}}, Type{Core.Inference.Const}, Tuple{Int64, typeof(Base.Distributed.rmprocs)}}) -precompile(Tuple{typeof(Core.Inference.convert), Type{Tuple{Int64, typeof(Base.Distributed.rmprocs)}}, Tuple{Int64, typeof(Base.Distributed.rmprocs)}}) -precompile(Tuple{typeof(Core.Inference.collect), Type{Any}, Core.Inference.Generator{Tuple{Int64, typeof(Base.Distributed.rmprocs)}, Type{Core.Inference.Const}}}) -precompile(Tuple{typeof(Core.Inference.iteratorsize), Core.Inference.Generator{Tuple{Int64, typeof(Base.Distributed.rmprocs)}, Type{Core.Inference.Const}}}) -precompile(Tuple{typeof(Core.Inference.iteratorsize), Type{Core.Inference.Generator{Tuple{Int64, typeof(Base.Distributed.rmprocs)}, Type{Core.Inference.Const}}}}) -precompile(Tuple{typeof(Core.Inference.iteratorsize), Type{Tuple{Int64, typeof(Base.Distributed.rmprocs)}}}) -precompile(Tuple{typeof(Core.Inference._collect), Type{Any}, Core.Inference.Generator{Tuple{Int64, typeof(Base.Distributed.rmprocs)}, Type{Core.Inference.Const}}, Core.Inference.HasLength}) -precompile(Tuple{typeof(Core.Inference.length), Core.Inference.Generator{Tuple{Int64, typeof(Base.Distributed.rmprocs)}, Type{Core.Inference.Const}}}) -precompile(Tuple{typeof(Core.Inference.length), Tuple{Int64, typeof(Base.Distributed.rmprocs)}}) -precompile(Tuple{typeof(Core.Inference.copy!), Array{Any, 1}, Core.Inference.Generator{Tuple{Int64, typeof(Base.Distributed.rmprocs)}, Type{Core.Inference.Const}}}) -precompile(Tuple{typeof(Core.Inference.start), Core.Inference.Generator{Tuple{Int64, typeof(Base.Distributed.rmprocs)}, Type{Core.Inference.Const}}}) -precompile(Tuple{typeof(Core.Inference.start), Tuple{Int64, typeof(Base.Distributed.rmprocs)}}) -precompile(Tuple{typeof(Core.Inference.done), Core.Inference.Generator{Tuple{Int64, typeof(Base.Distributed.rmprocs)}, Type{Core.Inference.Const}}, Int64}) -precompile(Tuple{typeof(Core.Inference.done), Tuple{Int64, typeof(Base.Distributed.rmprocs)}, Int64}) -precompile(Tuple{typeof(Core.Inference.next), Core.Inference.Generator{Tuple{Int64, typeof(Base.Distributed.rmprocs)}, Type{Core.Inference.Const}}, Int64}) -precompile(Tuple{typeof(Core.Inference.next), Tuple{Int64, typeof(Base.Distributed.rmprocs)}, Int64}) -precompile(Tuple{typeof(Core.Inference.getindex), Tuple{Int64, typeof(Base.Distributed.rmprocs)}, Int64}) -precompile(Tuple{typeof(Core.Inference.start), Tuple{typeof(Base.Distributed.rmprocs), Int64}}) -precompile(Tuple{typeof(Core.Inference.indexed_next), Tuple{typeof(Base.Distributed.rmprocs), Int64}, Int64, Int64}) -precompile(Tuple{typeof(Core.Inference.getindex), Tuple{typeof(Base.Distributed.rmprocs), Int64}, Int64}) -precompile(Tuple{typeof(Base.Serializer.deserialize), Base.Distributed.ClusterSerializer{Base.TCPSocket}}) -precompile(Tuple{typeof(Base.Serializer.deserialize_cycle), Base.Distributed.ClusterSerializer{Base.TCPSocket}, Expr}) -precompile(Tuple{typeof(Base.Serializer.handle_deserialize), Base.Distributed.ClusterSerializer{Base.TCPSocket}, Int32}) -precompile(Tuple{typeof(Base._array_for), Type{Union{}}, Base.UnitRange{Int64}, Base.HasShape}) -precompile(Tuple{typeof(Base.Serializer.deserialize_array), Base.Distributed.ClusterSerializer{Base.TCPSocket}}) -precompile(Tuple{typeof(Base.Serializer.deserialize_datatype), Base.Distributed.ClusterSerializer{Base.TCPSocket}}) -precompile(Tuple{typeof(Base.Serializer.deserialize_expr), Base.Distributed.ClusterSerializer{Base.TCPSocket}, Int64}) -precompile(Tuple{typeof(Base.join), Base.AbstractIOBuffer{Array{UInt8, 1}}, Tuple{Int64}, Char}) -precompile(Tuple{typeof(Core.Inference.isbits), Tuple{Int64, typeof(Base.Distributed.rmprocs)}}) -precompile(Tuple{Type{Core.Inference.Generator{I, F} where F where I}, Type{QuoteNode}, Tuple{Int64, typeof(Base.Distributed.rmprocs)}}) -precompile(Tuple{Type{Core.Inference.Generator{Tuple{Int64, typeof(Base.Distributed.rmprocs)}, Type{QuoteNode}}}, Type{QuoteNode}, Tuple{Int64, typeof(Base.Distributed.rmprocs)}}) -precompile(Tuple{typeof(Core.Inference.iteratorsize), Type{Core.Inference.Generator{Tuple{Int64, typeof(Base.Distributed.rmprocs)}, Type{QuoteNode}}}}) -precompile(Tuple{typeof(Core.Inference._collect), Type{Any}, Core.Inference.Generator{Tuple{Int64, typeof(Base.Distributed.rmprocs)}, Type{QuoteNode}}, Core.Inference.HasLength}) -precompile(Tuple{typeof(Core.Inference.length), Core.Inference.Generator{Tuple{Int64, typeof(Base.Distributed.rmprocs)}, Type{QuoteNode}}}) -precompile(Tuple{typeof(Core.Inference.copy!), Array{Any, 1}, Core.Inference.Generator{Tuple{Int64, typeof(Base.Distributed.rmprocs)}, Type{QuoteNode}}}) -precompile(Tuple{typeof(Core.Inference.start), Core.Inference.Generator{Tuple{Int64, typeof(Base.Distributed.rmprocs)}, Type{QuoteNode}}}) -precompile(Tuple{typeof(Core.Inference.done), Core.Inference.Generator{Tuple{Int64, typeof(Base.Distributed.rmprocs)}, Type{QuoteNode}}, Int64}) -precompile(Tuple{typeof(Core.Inference.next), Core.Inference.Generator{Tuple{Int64, typeof(Base.Distributed.rmprocs)}, Type{QuoteNode}}, Int64}) -precompile(Tuple{typeof(Base.Distributed.local_remotecall_thunk), typeof(Base.Distributed.rmprocs), Tuple{Int64}, Array{Any, 1}}) -precompile(Tuple{typeof(Base.Distributed.remote_do), typeof(Base.Distributed.rmprocs), Base.Distributed.Worker, Int64}) -precompile(Tuple{typeof(Base.Distributed.remote_do), typeof(Base.Distributed.rmprocs), Base.Distributed.LocalProcess, Int64}) -precompile(Tuple{getfield(Base.Distributed, Symbol("#kw##remote_do")), Array{Any, 1}, typeof(Base.Distributed.remote_do), typeof(Base.Distributed.rmprocs), Base.Distributed.Worker, Int64}) -precompile(Tuple{getfield(Base.Distributed, Symbol("#kw##remote_do")), Array{Any, 1}, typeof(Base.Distributed.remote_do), typeof(Base.Distributed.rmprocs), Base.Distributed.LocalProcess, Int64}) -precompile(Tuple{Type{Base.Distributed.ResultMsg}, Base.Distributed.RemoteException}) -precompile(Tuple{Type{Base.Distributed.ResultMsg}, Symbol}) -precompile(Tuple{typeof(Base.Distributed.send_msg_now), Base.TCPSocket, Base.Distributed.MsgHeader, Base.Distributed.ResultMsg}) -precompile(Tuple{typeof(Base.setindex!), Base.Dict{Int64, Void}, Void, Int64}) -precompile(Tuple{typeof(Base.notify), Base.Condition, Base.Distributed.ProcessExitedException, Bool, Bool}) -precompile(Tuple{typeof(Base.pop!), Base.Dict{Int64, Union{Base.Distributed.Worker, Base.Distributed.LocalProcess}}, Int64, Void}) -precompile(Tuple{typeof(Base.Distributed.deregister_worker), Base.Distributed.ProcessGroup, Int64}) -precompile(Tuple{typeof(Base.Distributed.process_hdr), Base.TCPSocket, Bool}) -precompile(Tuple{typeof(Base.Distributed.null_id), Base.Distributed.RRID}) -precompile(Tuple{typeof(Base.Distributed.deliver_result), Base.TCPSocket, Symbol, Base.Distributed.RRID, Base.Distributed.RemoteException}) -precompile(Tuple{typeof(Base.Distributed.disable_nagle), Base.TCPSocket}) -precompile(Tuple{typeof(Base.Distributed.message_handler_loop), Base.TCPSocket, Base.TCPSocket, Bool}) -precompile(Tuple{typeof(Base.Distributed.process_tcp_streams), Base.TCPSocket, Base.TCPSocket, Bool}) -precompile(Tuple{typeof(Base.Serializer.deserialize), Base.Distributed.ClusterSerializer{Base.TCPSocket}, Type{Union}}) -precompile(Tuple{typeof(Base.Serializer.deserialize), Base.Distributed.ClusterSerializer{Base.TCPSocket}, Type{Module}}) -precompile(Tuple{typeof(Base.Serializer.deserialize), Base.Distributed.ClusterSerializer{Base.TCPSocket}, Type{SimpleVector}}) -precompile(Tuple{Type{Array{Union{Tuple{Any, Int64}, Tuple{Tuple{}, Any, Bool}}, 1}}, Tuple{Int64}}) -precompile(Tuple{typeof(Base.eachindex), Array{Union{Tuple{Any, Int64}, Tuple{Tuple{}, Any, Bool}}, 1}}) -precompile(Tuple{Type{Base.Distributed.JoinPGRPMsg}, Int64, Array{Union{Tuple{Any, Int64}, Tuple{Tuple{}, Any, Bool}}, 1}, Symbol, Bool}) -precompile(Tuple{typeof(Base.Distributed.handle_msg), Base.Distributed.JoinPGRPMsg, Base.Distributed.MsgHeader, Base.TCPSocket, Base.TCPSocket, Base.VersionNumber}) -precompile(Tuple{Type{Base.Distributed.WorkerConfig}}) -precompile(Tuple{typeof(Base.LinAlg.BLAS.set_num_threads), Int64}) -precompile(Tuple{typeof(Base.Distributed.send_msg_), Base.Distributed.Worker, Base.Distributed.MsgHeader, Base.Distributed.JoinCompleteMsg, Bool}) -precompile(Tuple{typeof(Base.Distributed.send_msg_now), Base.Distributed.Worker, Base.Distributed.MsgHeader, Base.Distributed.JoinCompleteMsg}) -precompile(Tuple{getfield(Core, Symbol("#kw#Type")), Array{Any, 1}, Type{Base.Distributed.Worker}, Int64, Base.TCPSocket, Base.TCPSocket, Base.Distributed.DefaultClusterManager}) -precompile(Tuple{typeof(Base.eltype), Type{Base.Nullable{IO}}}) -precompile(Tuple{Type{Base.Nullable{IO}}}) -precompile(Tuple{typeof(Base.eltype), Type{Base.Nullable{AbstractString}}}) -precompile(Tuple{Type{Base.Nullable{AbstractString}}}) -precompile(Tuple{typeof(Base.eltype), Type{Base.Nullable{Integer}}}) -precompile(Tuple{Type{Base.Nullable{Integer}}}) -precompile(Tuple{typeof(Base.eltype), Type{Base.Nullable{Union{Int64, Symbol}}}}) -precompile(Tuple{Type{Base.Nullable{Union{Int64, Symbol}}}}) -precompile(Tuple{typeof(Base.eltype), Type{Base.Nullable{Base.Cmd}}}) -precompile(Tuple{Type{Base.Nullable{Base.Cmd}}}) -precompile(Tuple{typeof(Base.eltype), Type{Base.Nullable{Any}}}) -precompile(Tuple{Type{Base.Nullable{Any}}}) -precompile(Tuple{typeof(Base.eltype), Type{Base.Nullable{Bool}}}) -precompile(Tuple{Type{Base.Nullable{Bool}}}) -precompile(Tuple{typeof(Base.eltype), Type{Base.Nullable{Base.Process}}}) -precompile(Tuple{Type{Base.Nullable{Base.Process}}}) -precompile(Tuple{typeof(Base.eltype), Type{Base.Nullable{Base.Dict{K, V} where V where K}}}) -precompile(Tuple{Type{Base.Nullable{Base.Dict{K, V} where V where K}}}) -precompile(Tuple{typeof(Base.eltype), Type{Base.Nullable{Array{T, N} where N where T}}}) -precompile(Tuple{Type{Base.Nullable{Array{T, N} where N where T}}}) -precompile(Tuple{typeof(Base.Distributed.register_worker_streams), Base.Distributed.Worker}) -precompile(Tuple{typeof(Base.Distributed.register_worker_streams), Base.Distributed.LocalProcess}) -precompile(Tuple{typeof(Base.convert), Type{IO}, Base.TCPSocket}) -precompile(Tuple{typeof(Base.convert), Type{Base.Distributed.ClusterSerializer{I} where I<:IO}, Base.Distributed.ClusterSerializer{Base.TCPSocket}}) -precompile(Tuple{typeof(Base.convert), Type{Base.Distributed.ClusterManager}, Base.Distributed.DefaultClusterManager}) -precompile(Tuple{typeof(Base.convert), Type{Base.Distributed.WorkerConfig}, Base.Distributed.WorkerConfig}) -precompile(Tuple{typeof(Base.convert), Type{Base.Nullable{Base.VersionNumber}}, Base.VersionNumber}) -precompile(Tuple{typeof(Base.Distributed.send_connection_hdr), Base.Distributed.Worker, Bool}) -precompile(Tuple{typeof(Base.unsafe_write), Base.TCPSocket, Ptr{UInt8}, UInt64}) -precompile(Tuple{typeof(Base.Distributed.manage), Base.Distributed.LocalManager, Int64, Base.Distributed.WorkerConfig, Symbol}) -precompile(Tuple{typeof(Base.uv_write), Base.TCPSocket, Ptr{UInt8}, UInt64}) -precompile(Tuple{typeof(Base.flush), Base.TCPSocket}) -precompile(Tuple{typeof(Base.write), Base.TCPSocket, Int64, Int64, Int64, Int64}) -precompile(Tuple{typeof(Base.unsafe_write), Base.TCPSocket, Base.RefValue{Int64}, Int64}) -precompile(Tuple{typeof(Base.Serializer.serialize), Base.Distributed.ClusterSerializer{Base.TCPSocket}, Base.Distributed.JoinCompleteMsg}) -precompile(Tuple{typeof(Base.unsafe_write), Base.TCPSocket, Base.RefValue{UInt8}, Int64}) -precompile(Tuple{typeof(Base.Serializer.serialize), Base.Distributed.ClusterSerializer{Base.TCPSocket}, Int64}) -precompile(Tuple{typeof(Base.write), Base.TCPSocket, Array{UInt8, 1}}) -precompile(Tuple{typeof(Base.unsafe_read), Base.TCPSocket, Base.RefValue{Int32}, Int64}) -precompile(Tuple{typeof(Base.unsafe_read), Base.TCPSocket, Base.RefValue{Int64}, Int64}) -precompile(Tuple{typeof(Base.read!), Base.TCPSocket, Array{UInt8, 1}}) -precompile(Tuple{typeof(Base.promote_type), Type{Int64}, Type{UInt8}}) -precompile(Tuple{typeof(Base.promote_rule), Type{Int64}, Type{UInt8}}) -precompile(Tuple{typeof(Base.promote_result), Type{Int64}, Type{UInt8}, Type{Union{}}, Type{Int64}}) -precompile(Tuple{typeof(Base.read!), Base.TCPSocket, Array{UInt64, 1}}) -precompile(Tuple{typeof(Base.Serializer.deserialize), Base.Distributed.ClusterSerializer{Base.TCPSocket}}) -precompile(Tuple{typeof(Base.Serializer.deserialize_cycle), Base.Distributed.ClusterSerializer{Base.TCPSocket}, Expr}) -precompile(Tuple{typeof(Base.Serializer.handle_deserialize), Base.Distributed.ClusterSerializer{Base.TCPSocket}, Int32}) -precompile(Tuple{typeof(Base._array_for), Type{Union{}}, Base.UnitRange{Int64}, Base.HasShape}) -precompile(Tuple{typeof(Base.Serializer.deserialize_array), Base.Distributed.ClusterSerializer{Base.TCPSocket}}) -precompile(Tuple{typeof(Base.Serializer.deserialize_datatype), Base.Distributed.ClusterSerializer{Base.TCPSocket}}) -precompile(Tuple{typeof(Base.Serializer.deserialize_expr), Base.Distributed.ClusterSerializer{Base.TCPSocket}, Int64}) -precompile(Tuple{typeof(Base.Serializer.deserialize), Base.Distributed.ClusterSerializer{Base.TCPSocket}, Type{Int64}}) -precompile(Tuple{typeof(Base.read), Base.TCPSocket, Type{Int64}}) -precompile(Tuple{Type{Base.Distributed.JoinCompleteMsg}, Int64, Int64}) -precompile(Tuple{typeof(Base.Distributed.handle_msg), Base.Distributed.JoinCompleteMsg, Base.Distributed.MsgHeader, Base.TCPSocket, Base.TCPSocket, Base.VersionNumber}) -precompile(Tuple{typeof(Base.hash), Base.Distributed.RemoteChannel{Base.Channel{Any}}, UInt64}) -precompile(Tuple{typeof(Base.ht_keyindex), Base.Dict{WeakRef, Void}, Base.Distributed.RemoteChannel{Base.Channel{Any}}}) -precompile(Tuple{typeof(Base.Distributed.remotecall_fetch), typeof(Base.Distributed.put_ref), Base.Distributed.Worker, Base.Distributed.RRID, Base.Distributed.WorkerPool}) -precompile(Tuple{typeof(Base.Distributed.remotecall_fetch), typeof(Base.Distributed.put_ref), Base.Distributed.LocalProcess, Base.Distributed.RRID, Base.Distributed.WorkerPool}) -precompile(Tuple{getfield(Base.Distributed, Symbol("#kw##remotecall_fetch")), Array{Any, 1}, typeof(Base.Distributed.remotecall_fetch), typeof(Base.Distributed.put_ref), Base.Distributed.Worker, Base.Distributed.RRID, Base.Distributed.WorkerPool}) -precompile(Tuple{getfield(Base.Distributed, Symbol("#kw##remotecall_fetch")), Array{Any, 1}, typeof(Base.Distributed.remotecall_fetch), typeof(Base.Distributed.put_ref), Base.Distributed.LocalProcess, Base.Distributed.RRID, Base.Distributed.WorkerPool}) -precompile(Tuple{typeof(Base.rehash!), Base.Dict{WeakRef, Void}, Int64}) -precompile(Tuple{typeof(Base.ht_keyindex2), Base.Dict{WeakRef, Void}, WeakRef}) -precompile(Tuple{typeof(Base._setindex!), Base.Dict{WeakRef, Void}, Void, WeakRef, Int64}) -precompile(Tuple{typeof(Base.setindex!), Base.Dict{WeakRef, Void}, Void, WeakRef}) -precompile(Tuple{typeof(Base.finalizer), Base.Distributed.RemoteChannel{Base.Channel{Any}}, typeof(Base.Distributed.finalize_ref)}) -precompile(Tuple{typeof(Base.Distributed.test_existing_ref), Base.Distributed.RemoteChannel{Base.Channel{Any}}}) -precompile(Tuple{Type{Base.Distributed.RemoteChannel{T} where T<:Base.AbstractChannel}, Int64}) -precompile(Tuple{Type{Base.Channel{Int64}}, Int64}) -precompile(Tuple{Type{Base.Distributed.WorkerPool}}) -precompile(Tuple{typeof(Base.Distributed.default_worker_pool)}) -precompile(Tuple{typeof(Base.get), Base.Nullable{Base.Dict{K, V} where V where K}, Base.Dict{Any, Any}}) -precompile(Tuple{typeof(Base.setindex!), Base.Dict{Any, Any}, Int64, Symbol}) -precompile(Tuple{typeof(Base._setindex!), Base.Dict{Any, Any}, Int64, Symbol, Int64}) -precompile(Tuple{typeof(Base.convert), Type{Base.Nullable{Base.Dict{K, V} where V where K}}, Base.Dict{Any, Any}}) -precompile(Tuple{typeof(Base.convert), Type{Base.Nullable{Integer}}, Int64}) -precompile(Tuple{typeof(Base.convert), Type{Base.Nullable{Base.VersionNumber}}, Base.VersionNumber}) -precompile(Tuple{typeof(Base.put!), Base.Channel{Any}, Int64}) -precompile(Tuple{typeof(Base.put_buffered), Base.Channel{Any}, Int64}) -precompile(Tuple{typeof(Base.put_unbuffered), Base.Channel{Any}, Int64}) -precompile(Tuple{typeof(Base.Distributed.call_on_owner), typeof(Base.Distributed.put_ref), Base.Distributed.RemoteChannel{Base.Channel{Any}}, Base.Distributed.WorkerPool}) -precompile(Tuple{typeof(Base.Distributed.put_ref), Base.Distributed.RRID, Base.Distributed.WorkerPool}) -precompile(Tuple{typeof(Base.put!), Base.Distributed.RemoteValue, Base.Distributed.WorkerPool}) -precompile(Tuple{typeof(Base.put!), Base.Channel{Any}, Base.Distributed.WorkerPool}) -precompile(Tuple{typeof(Base.put_buffered), Base.Channel{Any}, Base.Distributed.WorkerPool}) -precompile(Tuple{typeof(Base.put_unbuffered), Base.Channel{Any}, Base.Distributed.WorkerPool}) -precompile(Tuple{typeof(Base.push!), Base.Distributed.WorkerPool, Int64}) -precompile(Tuple{typeof(Base.check_channel_state), Base.Channel{Int64}}) -precompile(Tuple{typeof(Base.put_buffered), Base.Channel{Int64}, Int64}) -precompile(Tuple{typeof(Base.put_unbuffered), Base.Channel{Int64}, Int64}) -precompile(Tuple{typeof(Base.put!), Base.Channel{Int64}, Int64}) -precompile(Tuple{typeof(Base._delete!), Base.Dict{Any, Any}, Int64}) -precompile(Tuple{typeof(Base.Serializer.serialize), Base.Distributed.ClusterSerializer{Base.TCPSocket}, Base.Distributed.RemoteDoMsg}) -precompile(Tuple{typeof(Base.Serializer.serialize), Base.Distributed.ClusterSerializer{Base.TCPSocket}, typeof(Base.Distributed.set_valid_processes)}) -precompile(Tuple{typeof(Base.Serializer.serialize), Base.Distributed.ClusterSerializer{Base.TCPSocket}, Tuple{Array{Int64, 1}}}) -precompile(Tuple{typeof(Base.write), Base.TCPSocket, Array{Int64, 1}}) -precompile(Tuple{typeof(Base.Serializer.serialize_array_data), Base.TCPSocket, Array{Int64, 1}}) -precompile(Tuple{typeof(Base.Serializer.serialize), Base.Distributed.ClusterSerializer{Base.TCPSocket}, Array{Int64, 1}}) -precompile(Tuple{typeof(Base.sort!), Array{Int64, 1}, Int64, Int64, Base.Sort.InsertionSortAlg, Base.Order.ForwardOrdering}) -precompile(Tuple{typeof(Base.Sort.partition!), Array{Int64, 1}, Int64, Int64, Base.Order.ForwardOrdering}) -precompile(Tuple{typeof(Base.sort!), Array{Int64, 1}, Int64, Int64, Base.Sort.QuickSortAlg, Base.Order.ForwardOrdering}) -precompile(Tuple{typeof(Base.Serializer.deserialize), Base.Distributed.ClusterSerializer{Base.TCPSocket}, Type{typeof(Base.Distributed.set_valid_processes)}}) -precompile(Tuple{typeof(Base.Distributed.handle_msg), Base.Distributed.RemoteDoMsg, Base.Distributed.MsgHeader, Base.TCPSocket, Base.TCPSocket, Base.VersionNumber}) -precompile(Tuple{typeof(Base.put!), Base.Channel{Any}, Tuple{Array{Int64, 1}, Void}}) -precompile(Tuple{typeof(Base.put_buffered), Base.Channel{Any}, Tuple{Array{Int64, 1}, Void}}) -precompile(Tuple{typeof(Base.put_unbuffered), Base.Channel{Any}, Tuple{Array{Int64, 1}, Void}}) -precompile(Tuple{typeof(Base.Distributed.set_valid_processes), Array{Int64, 1}}) -precompile(Tuple{typeof(Base.promote_type), Type{Int64}, Type{Int64}}) -precompile(Tuple{typeof(Base.sizehint!), Base.Dict{Int64, Void}, Int64}) -precompile(Tuple{typeof(Base.union!), Base.Set{Int64}, Array{Int64, 1}}) -precompile(Tuple{typeof(Base.start), Tuple{Array{Int64, 1}, Void}}) -precompile(Tuple{typeof(Base.indexed_next), Tuple{Array{Int64, 1}, Void}, Int64, Int64}) -precompile(Tuple{typeof(Base.setdiff), Array{Int64, 1}, Array{Int64, 1}}) -precompile(Tuple{typeof(Base.Multimedia.display), Array{Int64, 1}}) -precompile(Tuple{typeof(Base.isassigned), Array{Int64, 1}, Int64}) -precompile(Tuple{typeof(Base.array_eltype_show_how), Array{Int64, 1}}) -precompile(Tuple{typeof(Base._summary), Array{Int64, 1}, Tuple{Base.OneTo{Int64}}}) -precompile(Tuple{typeof(Base.isassigned), Array{Int64, 1}, Int64, Int64}) -precompile(Tuple{typeof(Base.isassigned), Array{Int64, 1}}) -precompile(Tuple{typeof(Base.Multimedia.display), Base.REPL.REPLDisplay{Base.REPL.LineEditREPL}, Array{Int64, 1}}) -precompile(Tuple{typeof(Base.Multimedia.display), Base.REPL.REPLDisplay{Base.REPL.LineEditREPL}, Base.MIME{Symbol("text/plain")}, Array{Int64, 1}}) -precompile(Tuple{typeof(Base.show_delim_array), Base.IOContext{Base.Terminals.TTYTerminal}, Array{Int64, 1}, String, String, String, Bool, Int64, Int64}) -precompile(Tuple{typeof(Base.print), Base.IOContext{Base.Terminals.TTYTerminal}, Char}) -precompile(Tuple{typeof(Base.print), Base.IOContext{Base.Terminals.TTYTerminal}, String, Char}) -precompile(Tuple{typeof(Base.print), Base.IOContext{Base.Terminals.TTYTerminal}, String, String}) -precompile(Tuple{typeof(Base.print), Base.IOContext{Base.Terminals.TTYTerminal}, String, String, Char}) -precompile(Tuple{typeof(Base.show_vector), Base.IOContext{Base.Terminals.TTYTerminal}, Array{Int64, 1}, String, String}) -precompile(Tuple{typeof(Base.print_matrix_repr), Base.IOContext{Base.Terminals.TTYTerminal}, Array{Int64, 1}}) -precompile(Tuple{typeof(Base.show_nd), Base.IOContext{Base.Terminals.TTYTerminal}, Array{Int64, 1}, typeof(Base.print_matrix_repr), Bool}) -precompile(Tuple{typeof(Base.repremptyarray), Base.IOContext{Base.Terminals.TTYTerminal}, Array{Int64, 1}}) -precompile(Tuple{typeof(Base.print_matrix), Base.IOContext{Base.Terminals.TTYTerminal}, Array{Int64, 1}, String, String, String}) -precompile(Tuple{typeof(Base.getindex), Base.ImmutableDict{Symbol, Any}, Symbol}) -precompile(Tuple{typeof(Base.vcat), Base.OneTo{Int64}}) -precompile(Tuple{typeof(Base.collect_to!), Array{Int64, 1}, Base.Generator{Array{Tuple{Int64, Int64}, 1}, typeof(Base.sum)}, Int64, Int64}) -precompile(Tuple{typeof(Base._collect), Array{Tuple{Int64, Int64}, 1}, Base.Generator{Array{Tuple{Int64, Int64}, 1}, typeof(Base.sum)}, Base.EltypeUnknown, Base.HasShape}) -precompile(Tuple{typeof(Base.pop!), Array{Tuple{Int64, Int64}, 1}}) -precompile(Tuple{typeof(Base.reverse), Array{Tuple{Int64, Int64}, 1}, Int64, Int64}) -precompile(Tuple{typeof(Base.print_matrix_vdots), Base.IOContext{Base.Terminals.TTYTerminal}, String, Array{Tuple{Int64, Int64}, 1}, String, Int64, Int64}) -precompile(Tuple{typeof(Base.print_matrix), Base.IOContext{Base.Terminals.TTYTerminal}, Array{Int64, 1}, String, String, String, String, String, String, Int64, Int64}) -precompile(Tuple{typeof(Base.alignment), Base.IOContext{Base.Terminals.TTYTerminal}, Array{Int64, 1}, Array{Int64, 1}, Array{Int64, 1}, Int64, Int64, Int64}) -precompile(Tuple{getfield(Base, Symbol("#kw##sprint")), Array{Any, 1}, typeof(Base.sprint), Int64, typeof(Base.show), Int64}) -precompile(Tuple{typeof(Base.sub2ind), Tuple{Int64}, Int64, Int64}) -precompile(Tuple{typeof(Base._sub2ind), Tuple{Int64}, Int64, Int64, Int64, Int64}) -precompile(Tuple{typeof(Base._sub2ind), Tuple{}, Int64, Int64, Int64}) -precompile(Tuple{typeof(Base.first), Array{Int64, 1}}) -precompile(Tuple{typeof(Base.print_matrix_row), Base.IOContext{Base.Terminals.TTYTerminal}, Array{Int64, 1}, Array{Tuple{Int64, Int64}, 1}, Int64, Array{Int64, 1}, String}) -precompile(Tuple{typeof(Base.print), Base.AbstractIOBuffer{Array{UInt8, 1}}, Base.OneTo{Int64}}) -precompile(Tuple{typeof(Base.last), Array{Int64, 1}}) -precompile(Tuple{typeof(Base.LineEdit.edit_delete), Base.AbstractIOBuffer{Array{UInt8, 1}}}) -precompile(Tuple{typeof(Base.print), String}) -precompile(Tuple{typeof(Base.vcat), Array{Int64, 1}}) -precompile(Tuple{typeof(Base.Distributed._rmprocs), Array{Int64, 1}, Float64}) -precompile(Tuple{typeof(Core.Inference.eltype), Type{Array{Int64, 1}}}) -precompile(Tuple{typeof(Base.vcat), Int64}) -precompile(Tuple{typeof(Base.kill), Base.Distributed.LocalManager, Int64, Base.Distributed.WorkerConfig}) -precompile(Tuple{typeof(Base.Serializer.serialize), Base.Distributed.ClusterSerializer{Base.TCPSocket}, typeof(Base.exit)}) -precompile(Tuple{typeof(Base.Serializer.serialize), Base.Distributed.ClusterSerializer{Base.TCPSocket}, Tuple{}}) -precompile(Tuple{typeof(Base.Serializer.deserialize), Base.Distributed.ClusterSerializer{Base.TCPSocket}, Type{typeof(Base.exit)}}) -precompile(Tuple{typeof(Base.uvfinalize), Base.PipeEndpoint}) -precompile(Tuple{typeof(Base.unpreserve_handle), Base.PipeEndpoint}) -precompile(Tuple{typeof(Base.stream_wait), Base.PipeEndpoint, Base.Condition}) -precompile(Tuple{typeof(Base.close), Base.PipeEndpoint}) -precompile(Tuple{typeof(Base.uvfinalize), Base.TCPServer}) -precompile(Tuple{typeof(Base.uvfinalize), Base.TCPSocket}) -precompile(Tuple{typeof(Base._uv_hook_close), Base.TCPSocket}) -precompile(Tuple{typeof(Base.in), Int64, Base.IntSet}) -precompile(Tuple{typeof(Base._uv_hook_close), Base.Process}) -precompile(Tuple{typeof(Base.Distributed.finalize_ref), Base.Distributed.RemoteChannel{Base.Channel{Any}}}) -precompile(Tuple{typeof(Base._delete!), Base.Dict{WeakRef, Void}, Int64}) -precompile(Tuple{typeof(Base.Distributed.send_del_client), Base.Distributed.RemoteChannel{Base.Channel{Any}}}) -precompile(Tuple{typeof(Base.:(==)), Base.Distributed.RemoteChannel{Base.Channel{Any}}, Base.Distributed.RemoteChannel{Base.Channel{Any}}}) -precompile(Tuple{typeof(Base.delete!), Base.IntSet, Int64}) -precompile(Tuple{typeof(Base.isempty), Base.IntSet}) -precompile(Tuple{typeof(Base.any), Base.BitArray{1}}) -precompile(Tuple{typeof(Base.uvfinalize), Base.PipeEndpoint}) -precompile(Tuple{typeof(Base.uvfinalize), Base.Process}) -precompile(Tuple{getfield(Base.Distributed, Symbol("#kw##remotecall_fetch")), Array{Any, 1}, typeof(Base.Distributed.remotecall_fetch), typeof(Base.find_in_path), Base.Distributed.LocalProcess, String, Void}) -precompile(Tuple{getfield(Base.Distributed, Symbol("#kw##remotecall_fetch")), Array{Any, 1}, typeof(Base.Distributed.remotecall_fetch), typeof(Base.find_in_path), Base.Distributed.Worker, String, Void}) -precompile(Tuple{getfield(Base.Distributed, Symbol("#kw##remotecall_fetch")), Array{Any, 1}, typeof(Base.Distributed.remotecall_fetch), typeof(Base.open), Base.Distributed.LocalProcess, typeof(Base.read), String}) -precompile(Tuple{getfield(Base.Distributed, Symbol("#kw##remotecall_fetch")), Array{Any, 1}, typeof(Base.Distributed.remotecall_fetch), typeof(Base.open), Base.Distributed.Worker, typeof(Base.read), String}) -precompile(Tuple{getfield(Base.Distributed, Symbol("#kw##remote_do")), Array{Any, 1}, typeof(Base.Distributed.remote_do), typeof(Base.exit), Base.Distributed.Worker}) -precompile(Tuple{getfield(Base.Distributed, Symbol("#kw##rmprocs")), Array{Any, 1}, typeof(Base.Distributed.rmprocs), Array{Int64, 1}}) -precompile(Tuple{getfield(Base.Filesystem, Symbol("#kw##rm")), Array{Any, 1}, typeof(Base.Filesystem.rm), String}) -precompile(Tuple{getfield(Base, Symbol("#kw##info")), Array{Any, 1}, typeof(Base.info), Base.IOStream, String}) -precompile(Tuple{getfield(Base, Symbol("#kw##print_with_color")), Array{Any, 1}, typeof(Base.print_with_color), Symbol, Base.IOStream, String}) -precompile(Tuple{getfield(Base, Symbol("#kw##readbytes!")), Array{Any, 1}, typeof(Base.readbytes!), Base.IOStream, Array{UInt8, 1}, Int32}) -precompile(Tuple{getfield(Base, Symbol("#kw##spawn")), Array{Any, 1}, typeof(Base.spawn), Base.Cmd, Tuple{Base.Pipe, Base.TTY, Base.IOStream}}) -precompile(Tuple{getfield(Base, Symbol("#kw##systemerror")), Array{Any, 1}, typeof(Base.systemerror), Symbol, Bool}) -precompile(Tuple{getfield(Base, Symbol("#kw##with_output_color")), Array{Any, 1}, typeof(Base.with_output_color), typeof(Base.println), Symbol, Base.IOStream, Base.SubString{String}}) -precompile(Tuple{getfield(Base, Symbol("#kw##with_output_color")), Array{Any, 1}, typeof(Base.with_output_color), typeof(Base.print), Symbol, Base.IOStream, String}) -precompile(Tuple{Type{Base.Distributed.Future}, Int64}) -precompile(Tuple{Type{Base.Process}, Base.Cmd, Ptr{Void}, Base.Pipe, Base.TTY, Base.IOStream}) -precompile(Tuple{Type{Base.Set{Tuple{String, Float64}}}, Tuple{Tuple{String, Float64}}}) -precompile(Tuple{Type{Base.VersionNumber}, Int64, Int64, Int64, Tuple{String, Int64}, Tuple{}}) -precompile(Tuple{Type{Base.VersionNumber}, Int64, Int64, Int64, Tuple{String}, Tuple{Int64}}) -precompile(Tuple{Type{Core.Inference.Generator{I, F} where F where I}, Type{Core.Inference.Const}, Tuple{Symbol, Expr}}) -precompile(Tuple{Type{Core.Inference.Generator{Tuple{Symbol, Expr}, Type{Core.Inference.Const}}}, Type{Core.Inference.Const}, Tuple{Symbol, Expr}}) -precompile(Tuple{typeof(Base.cmd_gen), Tuple{Tuple{Base.Cmd}, Tuple{String}, Tuple{String}, Tuple{String}, Tuple{String}, Tuple{String}, Tuple{String}, Tuple{String, String}, Tuple{String}, Tuple{String}}}) -precompile(Tuple{typeof(Base._collect), Array{Any, 1}, Base.Generator{Array{Any, 1}, typeof(Base.FastMath.make_fastmath)}, Base.EltypeUnknown, Base.HasShape}) -precompile(Tuple{typeof(Base._collect), Array{Base.Process, 1}, Base.Generator{Array{Base.Process, 1}, typeof(Base.kill)}, Base.EltypeUnknown, Base.HasShape}) -precompile(Tuple{typeof(Base.collect_to!), Array{Any, 1}, Base.Generator{Array{Any, 1}, typeof(Base.FastMath.make_fastmath)}, Int64, Int64}) -precompile(Tuple{typeof(Base.collect_to!), Array{Expr, 1}, Base.Generator{Array{Any, 1}, typeof(Base.FastMath.make_fastmath)}, Int64, Int64}) -precompile(Tuple{typeof(Base.collect_to!), Array{Int32, 1}, Base.Generator{Array{Base.Process, 1}, typeof(Base.kill)}, Int64, Int64}) -precompile(Tuple{typeof(Base.collect_to!), Array{Symbol, 1}, Base.Generator{Array{Any, 1}, typeof(Base.FastMath.make_fastmath)}, Int64, Int64}) -precompile(Tuple{typeof(Base.compilecache), String}) -precompile(Tuple{typeof(Base.copy!), Array{Tuple{String, Float64}, 1}, Int64, Array{Tuple{String, Float64}, 1}, Int64, Int64}) -precompile(Tuple{typeof(Base.create_expr_cache), String, String, Array{Any, 1}}) -precompile(Tuple{typeof(Base._delete!), Base.Dict{Symbol, Base.Condition}, Int64}) -precompile(Tuple{typeof(Base.Distributed.flush_gc_msgs), Base.Distributed.Worker}) -precompile(Tuple{typeof(Base.Distributed.remotecall_fetch), typeof(Base.find_in_path), Base.Distributed.LocalProcess, String, Void}) -precompile(Tuple{typeof(Base.Distributed.remotecall_fetch), typeof(Base.find_in_path), Base.Distributed.Worker, String, Void}) -precompile(Tuple{typeof(Base.Distributed.remotecall_fetch), typeof(Base.open), Base.Distributed.LocalProcess, typeof(Base.read), String}) -precompile(Tuple{typeof(Base.Distributed.remotecall_fetch), typeof(Base.open), Base.Distributed.Worker, typeof(Base.read), String}) -precompile(Tuple{typeof(Base.Distributed.remote_do), typeof(Base.exit), Base.Distributed.Worker}) -precompile(Tuple{typeof(Base.Distributed.send_del_client), Base.Distributed.Future}) -precompile(Tuple{typeof(Base.Distributed.send_msg), Base.Distributed.Worker, Base.Distributed.MsgHeader, Base.Distributed.CallMsg{:call}}) -precompile(Tuple{typeof(Base.Distributed.send_msg_), Base.Distributed.Worker, Base.Distributed.MsgHeader, Base.Distributed.CallMsg{:call}, Bool}) -precompile(Tuple{typeof(Base.Distributed.send_msg), Base.Distributed.Worker, Base.Distributed.MsgHeader, Base.Distributed.CallMsg{:call_fetch}}) -precompile(Tuple{typeof(Base.Distributed.send_msg_), Base.Distributed.Worker, Base.Distributed.MsgHeader, Base.Distributed.CallMsg{:call_fetch}, Bool}) -precompile(Tuple{typeof(Base.Distributed.send_msg), Base.Distributed.Worker, Base.Distributed.MsgHeader, Base.Distributed.RemoteDoMsg}) -precompile(Tuple{typeof(Base.Distributed.send_msg_), Base.Distributed.Worker, Base.Distributed.MsgHeader, Base.Distributed.RemoteDoMsg, Bool}) -precompile(Tuple{typeof(Base.Distributed.terminate_all_workers)}) -precompile(Tuple{typeof(Base.Distributed.test_existing_ref), Base.Distributed.Future}) -precompile(Tuple{typeof(Base.Docs.docm), String, Expr}) -precompile(Tuple{typeof(Base.Docs.docm), String, Expr, Bool}) -precompile(Tuple{typeof(Base.Docs.keyworddoc), String, Base.BaseDocs.Keyword}) -precompile(Tuple{typeof(Base.Docs.objectdoc), String, Expr, Expr, Expr}) -precompile(Tuple{typeof(Base.FastMath.make_fastmath), Expr}) -precompile(Tuple{typeof(Base.Filesystem.lstat), String}) -precompile(Tuple{typeof(Base.Filesystem.mkdir), String, UInt16}) -precompile(Tuple{typeof(Base.Filesystem.mkpath), String, UInt16}) -precompile(Tuple{typeof(Base.Filesystem.samefile), String, String}) -precompile(Tuple{typeof(Base.Filesystem.unlink), String}) -precompile(Tuple{typeof(Base.finalizer), Base.Distributed.Future, typeof(Base.Distributed.finalize_ref)}) -precompile(Tuple{typeof(Base.find_all_in_cache_path), Symbol}) -precompile(Tuple{typeof(Base.find_in_node_path), String, Void, Int64}) -precompile(Tuple{typeof(Base.find_in_path), String, Void}) -precompile(Tuple{typeof(Base.getindex), Base.ObjectIdDict, Symbol}) -precompile(Tuple{typeof(Base.getindex), Type{Tuple{String, Float64}}, Tuple{String, Float64}}) -precompile(Tuple{typeof(Base.Grisu._show), Base.IOContext{Base.AbstractIOBuffer{Array{UInt8, 1}}}, Float64, Int64, Int64, Bool, Bool}) -precompile(Tuple{typeof(Base.hash), Base.Distributed.Future, UInt64}) -precompile(Tuple{typeof(Base.hash), Tuple{String, Float64}, UInt64}) -precompile(Tuple{typeof(Base.ht_keyindex2), Base.Dict{Symbol, Base.Condition}, Symbol}) -precompile(Tuple{typeof(Base.ht_keyindex2), Base.Dict{Symbol, UInt64}, Symbol}) -precompile(Tuple{typeof(Base.ht_keyindex2), Base.Dict{Tuple{String, Float64}, Void}, Tuple{String, Float64}}) -precompile(Tuple{typeof(Base.ht_keyindex), Base.Dict{Symbol, Base.Condition}, Symbol}) -precompile(Tuple{typeof(Base.ht_keyindex), Base.Dict{Symbol, UInt64}, Symbol}) -precompile(Tuple{typeof(Base.ht_keyindex), Base.Dict{Tuple{String, Float64}, Void}, Tuple{String, Float64}}) -precompile(Tuple{typeof(Base.ht_keyindex), Base.Dict{WeakRef, Void}, Base.Distributed.Future}) -precompile(Tuple{typeof(Base.ident_cmp), Tuple{String, String, Int64}, Tuple{String, Int64}}) -precompile(Tuple{typeof(Base.include_from_node1), String}) -precompile(Tuple{typeof(Base._include_from_serialized), String}) -precompile(Tuple{typeof(Base.indexed_next), Tuple{Symbol, UInt64}, Int64, Int64}) -precompile(Tuple{typeof(Base.indexed_next), Tuple{Void, Void}, Int64, Int64}) -precompile(Tuple{typeof(Base.isassigned), Array{String, 1}, Int64}) -precompile(Tuple{typeof(Base.isempty), Tuple{String, Int64}}) -precompile(Tuple{typeof(Base.isequal), Float64, String}) -precompile(Tuple{typeof(Base.isequal), String, Float64}) -precompile(Tuple{typeof(Base.isequal), Tuple{String, Float64}, Tuple{String, Float64}}) -precompile(Tuple{typeof(Base._jl_spawn), String, Array{String, 1}, Ptr{Void}, Base.Process, Base.PipeEndpoint, Base.TTY, Base.Filesystem.File}) -precompile(Tuple{typeof(Base.julia_cmd)}) -precompile(Tuple{typeof(Base.load_hook), String, String, String}) -precompile(Tuple{typeof(Base.load_hook), String, String, Void}) -precompile(Tuple{typeof(Base.next), Base.Generator{Array{Any, 1}, typeof(Base.FastMath.make_fastmath)}, Int64}) -precompile(Tuple{typeof(Base.open), Base.CmdRedirect, String, Base.TTY}) -precompile(Tuple{typeof(Base.open), String, String}) -precompile(Tuple{typeof(Base.open), typeof(Base.read), String}) -precompile(Tuple{typeof(Base.parse_cache_header), Base.IOStream}) -precompile(Tuple{typeof(Base.pop!), Base.Dict{Symbol, Base.Condition}, Symbol}) -precompile(Tuple{typeof(Base.precompilableerror), Base.LoadError, Bool}) -precompile(Tuple{typeof(Base.precompilableerror), Base.PrecompilableError, Bool}) -precompile(Tuple{typeof(Base.__precompile__)}) -precompile(Tuple{typeof(Base.__precompile__), Bool}) -precompile(Tuple{typeof(Base.println_with_color), Symbol, Base.IOStream, Base.SubString{String}}) -precompile(Tuple{typeof(Base.push!), Array{Tuple{String, Float64}, 1}, Tuple{String, Float64}}) -precompile(Tuple{typeof(Base.put!), Base.Channel{Any}, Tuple{Void, Void}}) -precompile(Tuple{typeof(Base.put_buffered), Base.Channel{Any}, Tuple{Void, Void}}) -precompile(Tuple{typeof(Base.put_unbuffered), Base.Channel{Any}, Tuple{Void, Void}}) -precompile(Tuple{typeof(Base.read), Base.IOStream, Type{Int32}}) -precompile(Tuple{typeof(Base.read), Base.IOStream, Type{Int64}}) -precompile(Tuple{typeof(Base.read), Base.IOStream, Type{UInt64}}) -precompile(Tuple{typeof(Base.read!), Base.PipeEndpoint, Array{UInt64, 1}}) -precompile(Tuple{typeof(Base.read!), Base.PipeEndpoint, Array{UInt8, 1}}) -precompile(Tuple{typeof(Base.read), Base.PipeEndpoint, Type{Int64}}) -precompile(Tuple{typeof(Base.read), Base.PipeEndpoint, Type{UInt64}}) -precompile(Tuple{typeof(Base.read), Base.PipeEndpoint, Type{UInt8}}) -precompile(Tuple{typeof(Base.readbytes_all!), Base.IOStream, Array{UInt8, 1}, Int32}) -precompile(Tuple{typeof(Base.readbytes_some!), Base.IOStream, Array{UInt8, 1}, Int32}) -precompile(Tuple{typeof(Base._redirect), Base.IOStream, Base.Dict{Tuple{Union{Module, Void}, Union{Symbol, Void}}, IO}, Base.StackTraces.StackFrame}) -precompile(Tuple{typeof(Base._redirect), Base.IOStream, Base.Dict{Tuple{Union{Module, Void}, Union{Symbol, Void}}, IO}, Symbol}) -precompile(Tuple{typeof(Base.rehash!), Base.Dict{Symbol, Base.Condition}, Int64}) -precompile(Tuple{typeof(Base.rehash!), Base.Dict{Symbol, UInt64}, Int64}) -precompile(Tuple{typeof(Base.rehash!), Base.Dict{Tuple{String, Float64}, Void}, Int64}) -precompile(Tuple{typeof(Base.remove_linenums!), Module}) -precompile(Tuple{typeof(Base._require_from_serialized), Int64, Symbol, String, Bool}) -precompile(Tuple{typeof(Base._require_search_from_serialized), Int64, Symbol, String, Bool}) -precompile(Tuple{typeof(Base.require), Symbol}) -precompile(Tuple{typeof(Base.resize!), Array{Base.Condition, 1}, Int64}) -precompile(Tuple{typeof(Base.resize!), Array{Tuple{String, Float64}, 1}, Int64}) -precompile(Tuple{typeof(Base.resize!), Array{UInt8, 1}, Int32}) -precompile(Tuple{typeof(Base.Serializer.deserialize_array), Base.Serializer.SerializationState{Base.PipeEndpoint}}) -precompile(Tuple{typeof(Base.Serializer.deserialize), Base.PipeEndpoint}) -precompile(Tuple{typeof(Base.Serializer.deserialize), Base.Serializer.SerializationState{Base.PipeEndpoint}}) -precompile(Tuple{typeof(Base.Serializer.deserialize), Base.Serializer.SerializationState{Base.PipeEndpoint}, Type{Int64}}) -precompile(Tuple{typeof(Base.Serializer.deserialize), Base.Serializer.SerializationState{Base.PipeEndpoint}, Type{QuoteNode}}) -precompile(Tuple{typeof(Base.Serializer.deserialize), Base.Serializer.SerializationState{Base.PipeEndpoint}, Type{String}}) -precompile(Tuple{typeof(Base.Serializer.deserialize), Base.Serializer.SerializationState{Base.PipeEndpoint}, Type{UInt64}}) -precompile(Tuple{typeof(Base.Serializer.deserialize_cycle), Base.Serializer.SerializationState{Base.PipeEndpoint}, Expr}) -precompile(Tuple{typeof(Base.Serializer.deserialize_datatype), Base.Serializer.SerializationState{Base.PipeEndpoint}}) -precompile(Tuple{typeof(Base.Serializer.deserialize_expr), Base.Serializer.SerializationState{Base.PipeEndpoint}, Int64}) -precompile(Tuple{typeof(Base.Serializer.handle_deserialize), Base.Serializer.SerializationState{Base.PipeEndpoint}, Int32}) -precompile(Tuple{typeof(Base.Serializer.serialize_any), Base.Serializer.SerializationState{Base.Pipe}, QuoteNode}) -precompile(Tuple{typeof(Base.Serializer.serialize), Base.Serializer.SerializationState{Base.Pipe}, Array{Any, 1}}) -precompile(Tuple{typeof(Base.Serializer.serialize), Base.Serializer.SerializationState{Base.Pipe}, Array{String, 1}}) -precompile(Tuple{typeof(Base.Serializer.serialize), Base.Serializer.SerializationState{Base.Pipe}, Bool}) -precompile(Tuple{typeof(Base.Serializer.serialize), Base.Serializer.SerializationState{Base.Pipe}, Expr}) -precompile(Tuple{typeof(Base.Serializer.serialize), Base.Serializer.SerializationState{Base.Pipe}, Int64}) -precompile(Tuple{typeof(Base.Serializer.serialize), Base.Serializer.SerializationState{Base.Pipe}, Module}) -precompile(Tuple{typeof(Base.Serializer.serialize), Base.Serializer.SerializationState{Base.Pipe}, QuoteNode}) -precompile(Tuple{typeof(Base.Serializer.serialize), Base.Serializer.SerializationState{Base.Pipe}, SimpleVector}) -precompile(Tuple{typeof(Base.Serializer.serialize), Base.Serializer.SerializationState{Base.Pipe}, String}) -precompile(Tuple{typeof(Base.Serializer.serialize), Base.Serializer.SerializationState{Base.Pipe}, Symbol}) -precompile(Tuple{typeof(Base.Serializer.serialize), Base.Serializer.SerializationState{Base.Pipe}, Tuple{Int64}}) -precompile(Tuple{typeof(Base.Serializer.serialize), Base.Serializer.SerializationState{Base.Pipe}, Tuple{Symbol, UInt64}}) -precompile(Tuple{typeof(Base.Serializer.serialize), Base.Serializer.SerializationState{Base.Pipe}, Type{Any}}) -precompile(Tuple{typeof(Base.Serializer.serialize), Base.Serializer.SerializationState{Base.Pipe}, TypeName}) -precompile(Tuple{typeof(Base.Serializer.serialize), Base.Serializer.SerializationState{Base.Pipe}, UInt64}) -precompile(Tuple{typeof(Base.Serializer.serialize_cycle), Base.Serializer.SerializationState{Base.Pipe}, Expr}) -precompile(Tuple{typeof(Base.Serializer.serialize_cycle), Base.Serializer.SerializationState{Base.Pipe}, TypeName}) -precompile(Tuple{typeof(Base.Serializer.serialize_cycle), Base.Serializer.SerializationState{Base.Pipe}, UInt64}) -precompile(Tuple{typeof(Base.Serializer.serialize_cycle_header), Base.Serializer.SerializationState{Base.Pipe}, QuoteNode}) -precompile(Tuple{typeof(Base.Serializer.serialize_mod_names), Base.Serializer.SerializationState{Base.Pipe}, Module}) -precompile(Tuple{typeof(Base.Serializer.serialize_type), Base.Serializer.SerializationState{Base.Pipe}, DataType}) -precompile(Tuple{typeof(Base.Serializer.serialize_type_data), Base.Serializer.SerializationState{Base.Pipe}, Type{Any}, Bool}) -precompile(Tuple{typeof(Base.Serializer.serialize_typename), Base.Serializer.SerializationState{Base.Pipe}, TypeName}) -precompile(Tuple{typeof(Base.Serializer.should_send_whole_type), Base.Serializer.SerializationState{Base.Pipe}, Type{Any}}) -precompile(Tuple{typeof(Base.Serializer.write_as_tag), Base.Pipe, Int32}) -precompile(Tuple{typeof(Base.setindex!), Base.Dict{Symbol, Base.Condition}, Base.Condition, Symbol}) -precompile(Tuple{typeof(Base._setindex!), Base.Dict{Symbol, Base.Condition}, Base.Condition, Symbol, Int64}) -precompile(Tuple{typeof(Base.setindex!), Base.Dict{Symbol, UInt64}, UInt64, Symbol}) -precompile(Tuple{typeof(Base._setindex!), Base.Dict{Symbol, UInt64}, UInt64, Symbol, Int64}) -precompile(Tuple{typeof(Base.setindex!), Base.Dict{Tuple{String, Float64}, Void}, Void, Tuple{String, Float64}}) -precompile(Tuple{typeof(Base._setindex!), Base.Dict{Tuple{String, Float64}, Void}, Void, Tuple{String, Float64}, Int64}) -precompile(Tuple{typeof(Base.show), Base.IOContext{Base.AbstractIOBuffer{Array{UInt8, 1}}}, Float64}) -precompile(Tuple{typeof(Base.show_delim_array), Base.AbstractIOBuffer{Array{UInt8, 1}}, Tuple{String, Float64}, Char, Char, Char, Bool, Int64, Int64}) -precompile(Tuple{typeof(Base.show_unquoted), Base.AbstractIOBuffer{Array{UInt8, 1}}, Expr}) -precompile(Tuple{typeof(Base.skip_deleted), Base.Dict{Tuple{String, Float64}, Void}, Int64}) -precompile(Tuple{typeof(Base.spawn), Base.CmdRedirect, Tuple{Base.Pipe, Base.TTY, Base.IOStream}}) -precompile(Tuple{typeof(Base.stale_cachefile), String, String}) -precompile(Tuple{typeof(Base.start), Tuple{Symbol, UInt64}}) -precompile(Tuple{typeof(Base.start), Tuple{Void, Void}}) -precompile(Tuple{typeof(Base.:(>)), String, String}) -precompile(Tuple{typeof(Base._str), String}) -precompile(Tuple{typeof(Base._str), Void}) -precompile(Tuple{typeof(Base.sync_add), Base.Distributed.Future}) -precompile(Tuple{typeof(Base.trunc), Float64, Int64, Int64}) -precompile(Tuple{typeof(Base.union!), Base.Set{Tuple{String, Float64}}, Tuple{Tuple{String, Float64}}}) -precompile(Tuple{typeof(Base.unique_from), Array{Any, 1}, Array{Tuple{String, Float64}, 1}, Base.Set{Tuple{String, Float64}}, Int64}) -precompile(Tuple{typeof(Base.unsafe_copy!), Array{Tuple{String, Float64}, 1}, Int64, Array{Tuple{String, Float64}, 1}, Int64, Int64}) -precompile(Tuple{typeof(Base.unsafe_read), Base.IOStream, Base.RefValue{Float64}, Int64}) -precompile(Tuple{typeof(Base.unsafe_read), Base.PipeEndpoint, Base.RefValue{Int32}, Int64}) -precompile(Tuple{typeof(Base.unsafe_read), Base.PipeEndpoint, Base.RefValue{Int64}, Int64}) -precompile(Tuple{typeof(Base.unsafe_read), Base.PipeEndpoint, Base.RefValue{UInt64}, Int64}) -precompile(Tuple{typeof(Base.unsafe_read), Base.PipeEndpoint, Ptr{UInt8}, UInt64}) -precompile(Tuple{typeof(Base.unsafe_write), Base.Pipe, Base.RefValue{Int32}, Int64}) -precompile(Tuple{typeof(Base.unsafe_write), Base.Pipe, Base.RefValue{Int64}, Int64}) -precompile(Tuple{typeof(Base.unsafe_write), Base.Pipe, Base.RefValue{UInt64}, Int64}) -precompile(Tuple{typeof(Base.write), Base.Pipe, UInt64}) -precompile(Tuple{typeof(Core.Inference.collect), Type{Any}, Core.Inference.Generator{Tuple{Symbol, Expr}, Type{Core.Inference.Const}}}) -precompile(Tuple{typeof(Core.Inference._collect), Type{Any}, Core.Inference.Generator{Tuple{Symbol, Expr}, Type{Core.Inference.Const}}, Core.Inference.HasLength}) -precompile(Tuple{typeof(Core.Inference.convert), Type{Tuple{Symbol, Expr}}, Tuple{Symbol, Expr}}) -precompile(Tuple{typeof(Core.Inference.copy!), Array{Any, 1}, Core.Inference.Generator{Tuple{Symbol, Expr}, Type{Core.Inference.Const}}}) -precompile(Tuple{typeof(Core.Inference.done), Core.Inference.Generator{Tuple{Symbol, Expr}, Type{Core.Inference.Const}}, Int64}) -precompile(Tuple{typeof(Core.Inference.done), Tuple{Symbol, Expr}, Int64}) -precompile(Tuple{typeof(Core.Inference.getindex), Tuple{Symbol, Expr}, Int64}) -precompile(Tuple{typeof(Core.Inference.isbits), Array{Module, 1}}) -precompile(Tuple{typeof(Core.Inference.iteratorsize), Core.Inference.Generator{Tuple{Symbol, Expr}, Type{Core.Inference.Const}}}) -precompile(Tuple{typeof(Core.Inference.iteratorsize), Type{Core.Inference.Generator{Tuple{Symbol, Expr}, Type{Core.Inference.Const}}}}) -precompile(Tuple{typeof(Core.Inference.iteratorsize), Type{Tuple{Symbol, Expr}}}) -precompile(Tuple{typeof(Core.Inference.length), Core.Inference.Generator{Tuple{Symbol, Expr}, Type{Core.Inference.Const}}}) -precompile(Tuple{typeof(Core.Inference.length), Tuple{Symbol, Expr}}) -precompile(Tuple{typeof(Core.Inference.next), Core.Inference.Generator{Tuple{Symbol, Expr}, Type{Core.Inference.Const}}, Int64}) -precompile(Tuple{typeof(Core.Inference.next), Tuple{Symbol, Expr}, Int64}) -precompile(Tuple{typeof(Core.Inference.start), Core.Inference.Generator{Tuple{Symbol, Expr}, Type{Core.Inference.Const}}}) -precompile(Tuple{typeof(Core.Inference.start), Tuple{Expr, Int64}}) -precompile(Tuple{typeof(Core.Inference.start), Tuple{Symbol, Expr}}) -precompile(Tuple{Type{Union{}}, Base.Distributed.RRID}) diff --git a/julia-0.6.3/share/julia/base/printf.jl b/julia-0.6.3/share/julia/base/printf.jl deleted file mode 100644 index 035b190..0000000 --- a/julia-0.6.3/share/julia/base/printf.jl +++ /dev/null @@ -1,1252 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -module Printf -using Base.Grisu -export @printf, @sprintf - -### printf formatter generation ### -const SmallFloatingPoint = Union{Float64,Float32,Float16} -const SmallNumber = Union{SmallFloatingPoint,Base.BitInteger} - -function gen(s::AbstractString) - args = [] - blk = Expr(:block, :(local neg, pt, len, exp, do_out, args)) - for x in parse(s) - if isa(x,AbstractString) - push!(blk.args, :(write(out, $(length(x)==1 ? x[1] : x)))) - else - c = lowercase(x[end]) - f = c=='f' ? gen_f : - c=='e' ? gen_e : - c=='a' ? gen_a : - c=='g' ? gen_g : - c=='c' ? gen_c : - c=='s' ? gen_s : - c=='p' ? gen_p : - gen_d - arg, ex = f(x...) - push!(args, arg) - push!(blk.args, ex) - end - end - push!(blk.args, :nothing) - return args, blk -end - -### printf format string parsing ### - -function parse(s::AbstractString) - # parse format string in to stings and format tuples - list = [] - i = j = start(s) - while !done(s,j) - c, k = next(s,j) - if c == '%' - isempty(s[i:j-1]) || push!(list, s[i:j-1]) - flags, width, precision, conversion, k = parse1(s,k) - '\'' in flags && error("printf format flag ' not yet supported") - conversion == 'n' && error("printf feature %n not supported") - push!(list, conversion == '%' ? "%" : (flags,width,precision,conversion)) - i = j = k - else - j = k - end - end - isempty(s[i:end]) || push!(list, s[i:end]) - # coalesce adjacent strings - i = 1 - while i < length(list) - if isa(list[i],AbstractString) - for j = i+1:length(list) - if !isa(list[j],AbstractString) - j -= 1 - break - end - list[i] *= list[j] - end - deleteat!(list,i+1:j) - end - i += 1 - end - return list -end - -## parse a single printf specifier ## - -# printf specifiers: -# % # start -# (\d+\$)? # arg (not supported) -# [\-\+#0' ]* # flags -# (\d+)? # width -# (\.\d*)? # precision -# (h|hh|l|ll|L|j|t|z|q)? # modifier (ignored) -# [diouxXeEfFgGaAcCsSp%] # conversion - -next_or_die(s::AbstractString, k) = !done(s,k) ? next(s,k) : - throw(ArgumentError("invalid printf format string: $(repr(s))")) - -function parse1(s::AbstractString, k::Integer) - j = k - width = 0 - precision = -1 - c, k = next_or_die(s,k) - # handle %% - if c == '%' - return "", width, precision, c, k - end - # parse flags - while c in "#0- + '" - c, k = next_or_die(s,k) - end - flags = String(s[j:k-2]) - # parse width - while '0' <= c <= '9' - width = 10*width + c-'0' - c, k = next_or_die(s,k) - end - # parse precision - if c == '.' - c, k = next_or_die(s,k) - if '0' <= c <= '9' - precision = 0 - while '0' <= c <= '9' - precision = 10*precision + c-'0' - c, k = next_or_die(s,k) - end - end - end - # parse length modifer (ignored) - if c == 'h' || c == 'l' - prev = c - c, k = next_or_die(s,k) - if c == prev - c, k = next_or_die(s,k) - end - elseif c in "Ljqtz" - c, k = next_or_die(s,k) - end - # validate conversion - if !(c in "diouxXDOUeEfFgGaAcCsSpn") - throw(ArgumentError("invalid printf format string: $(repr(s))")) - end - # TODO: warn about silly flag/conversion combinations - flags, width, precision, c, k -end - -### printf formatter generation ### - -function special_handler(flags::String, width::Int) - @gensym x - blk = Expr(:block) - pad = '-' in flags ? rpad : lpad - pos = '+' in flags ? "+" : - ' ' in flags ? " " : "" - abn = quote - isnan($x) ? $(pad("NaN", width)) : - $x < 0 ? $(pad("-Inf", width)) : - $(pad("$(pos)Inf", width)) - end - ex = :(isfinite($x) ? $blk : write(out, $abn)) - x, ex, blk -end - -function pad(m::Int, n, c::Char) - if m <= 1 - :($n > 0 && write(out,$c)) - else - @gensym i - quote - $i = $n - while $i > 0 - write(out,$c) - $i -= 1 - end - end - end -end - -function dynamic_pad(m, val, c::Char) - @gensym i - quote - if $m <= 1 - $val > 0 && write(out,$c) - else - $i = $val - while $i > 0 - write(out,$c) - $i -= 1 - end - end - end -end - -function print_fixed(out, precision, pt, ndigits, trailingzeros=true) - pdigits = pointer(DIGITS) - if pt <= 0 - # 0.0dddd0 - write(out, '0') - write(out, '.') - precision += pt - while pt < 0 - write(out, '0') - pt += 1 - end - unsafe_write(out, pdigits, ndigits) - precision -= ndigits - elseif ndigits <= pt - # dddd000.000000 - unsafe_write(out, pdigits, ndigits) - while ndigits < pt - write(out, '0') - ndigits += 1 - end - if trailingzeros - write(out, '.') - end - else # 0 < pt < ndigits - # dd.dd0000 - ndigits -= pt - unsafe_write(out, pdigits, pt) - write(out, '.') - unsafe_write(out, pdigits+pt, ndigits) - precision -= ndigits - end - if trailingzeros - while precision > 0 - write(out, '0') - precision -= 1 - end - end -end - -function print_exp_e(out, exp::Integer) - write(out, exp < 0 ? '-' : '+') - exp = abs(exp) - d = div(exp,100) - if d > 0 - if d >= 10 - print(out, exp) - return - end - write(out, Char('0'+d)) - end - exp = rem(exp,100) - write(out, Char('0'+div(exp,10))) - write(out, Char('0'+rem(exp,10))) -end - -function print_exp_a(out, exp::Integer) - write(out, exp < 0 ? '-' : '+') - exp = abs(exp) - print(out, exp) -end - - -function gen_d(flags::String, width::Int, precision::Int, c::Char) - # print integer: - # [dDiu]: print decimal digits - # [o]: print octal digits - # [x]: print hex digits, lowercase - # [X]: print hex digits, uppercase - # - # flags: - # (#): prefix hex with 0x/0X; octal leads with 0 - # (0): pad left with zeros - # (-): left justify - # ( ): precede non-negative values with " " - # (+): precede non-negative values with "+" - # - x, ex, blk = special_handler(flags,width) - # interpret the number - prefix = "" - if lowercase(c)=='o' - fn = '#' in flags ? :decode_0ct : :decode_oct - elseif c=='x' - '#' in flags && (prefix = "0x") - fn = :decode_hex - elseif c=='X' - '#' in flags && (prefix = "0X") - fn = :decode_HEX - else - fn = :decode_dec - end - push!(blk.args, :((do_out, args) = $fn(out, $x, $flags, $width, $precision, $c))) - ifblk = Expr(:if, :do_out, Expr(:block)) - push!(blk.args, ifblk) - blk = ifblk.args[2] - push!(blk.args, :((len, pt, neg) = args)) - # calculate padding - width -= length(prefix) - space_pad = width > max(1,precision) && '-' in flags || - precision < 0 && width > 1 && !('0' in flags) || - precision >= 0 && width > precision - padding = nothing - if precision < 1; precision = 1; end - if space_pad - if '+' in flags || ' ' in flags - width -= 1 - if width > precision - padding = :($width-(pt > $precision ? pt : $precision)) - end - else - if width > precision - padding = :($width-neg-(pt > $precision ? pt : $precision)) - end - end - end - # print space padding - if padding !== nothing && !('-' in flags) - push!(blk.args, pad(width-precision, padding, ' ')) - end - # print sign - '+' in flags ? push!(blk.args, :(write(out, neg?'-':'+'))) : - ' ' in flags ? push!(blk.args, :(write(out, neg?'-':' '))) : - push!(blk.args, :(neg && write(out, '-'))) - # print prefix - for ch in prefix - push!(blk.args, :(write(out, $ch))) - end - # print zero padding & leading zeros - if space_pad && precision > 1 - push!(blk.args, pad(precision-1, :($precision-pt), '0')) - elseif !space_pad && width > 1 - zeros = '+' in flags || ' ' in flags ? :($(width-1)-pt) : :($width-neg-pt) - push!(blk.args, pad(width-1, zeros, '0')) - end - # print integer - push!(blk.args, :(unsafe_write(out, pointer(DIGITS), pt))) - # print padding - if padding !== nothing && '-' in flags - push!(blk.args, pad(width-precision, padding, ' ')) - end - # return arg, expr - :(($x)::Real), ex -end - -function gen_f(flags::String, width::Int, precision::Int, c::Char) - # print to fixed trailing precision - # [fF]: the only choice - # - # flags - # (#): always print a decimal point - # (0): pad left with zeros - # (-): left justify - # ( ): precede non-negative values with " " - # (+): precede non-negative values with "+" - # - x, ex, blk = special_handler(flags,width) - # interpret the number - if precision < 0; precision = 6; end - push!(blk.args, :((do_out, args) = fix_dec(out, $x, $flags, $width, $precision, $c))) - ifblk = Expr(:if, :do_out, Expr(:block)) - push!(blk.args, ifblk) - blk = ifblk.args[2] - push!(blk.args, :((len, pt, neg) = args)) - # calculate padding - padding = nothing - if precision > 0 || '#' in flags - width -= precision+1 - end - if '+' in flags || ' ' in flags - width -= 1 - if width > 1 - padding = :($width-(pt > 0 ? pt : 1)) - end - else - if width > 1 - padding = :($width-(pt > 0 ? pt : 1)-neg) - end - end - # print space padding - if padding !== nothing && !('-' in flags) && !('0' in flags) - push!(blk.args, pad(width-1, padding, ' ')) - end - # print sign - '+' in flags ? push!(blk.args, :(write(out, neg?'-':'+'))) : - ' ' in flags ? push!(blk.args, :(write(out, neg?'-':' '))) : - push!(blk.args, :(neg && write(out, '-'))) - # print zero padding - if padding !== nothing && !('-' in flags) && '0' in flags - push!(blk.args, pad(width-1, padding, '0')) - end - # print digits - if precision > 0 - push!(blk.args, :(print_fixed(out,$precision,pt,len))) - else - push!(blk.args, :(unsafe_write(out, pointer(DIGITS), len))) - push!(blk.args, :(while pt >= (len+=1) write(out,'0') end)) - '#' in flags && push!(blk.args, :(write(out, '.'))) - end - # print space padding - if padding !== nothing && '-' in flags - push!(blk.args, pad(width-1, padding, ' ')) - end - # return arg, expr - :(($x)::Real), ex -end - -function gen_e(flags::String, width::Int, precision::Int, c::Char, inside_g::Bool=false) - # print float in scientific form: - # [e]: use 'e' to introduce exponent - # [E]: use 'E' to introduce exponent - # - # flags: - # (#): always print a decimal point - # (0): pad left with zeros - # (-): left justify - # ( ): precede non-negative values with " " - # (+): precede non-negative values with "+" - # - x, ex, blk = if inside_g - @gensym x - blk = Expr(:block) - x, blk, blk - else - special_handler(flags,width) - end - # interpret the number - if precision < 0; precision = 6; end - ndigits = min(precision+1,length(DIGITS)-1) - push!(blk.args, :((do_out, args) = ini_dec(out,$x,$ndigits, $flags, $width, $precision, $c))) - ifblk = Expr(:if, :do_out, Expr(:block)) - push!(blk.args, ifblk) - blk = ifblk.args[2] - push!(blk.args, :((len, pt, neg) = args)) - push!(blk.args, :(exp = pt-1)) - expmark = isupper(c) ? "E" : "e" - if precision==0 && '#' in flags - expmark = string(".",expmark) - end - # calculate padding - padding = nothing - width -= precision+length(expmark)+(precision>0)+4 - # 4 = leading + expsign + 2 exp digits - if '+' in flags || ' ' in flags - width -= 1 # for the sign indicator - if width > 0 - padding = quote - padn=$width - if (exp<=-100)|(100<=exp) - if isa($x,SmallNumber) - padn -= 1 - else - padn -= Base.ndigits0z(exp) - 2 - end - end - padn - end - end - else - if width > 0 - padding = quote - padn=$width-neg - if (exp<=-100)|(100<=exp) - if isa($x,SmallNumber) - padn -= 1 - else - padn -= Base.ndigits0z(exp) - 2 - end - end - padn - end - end - end - # print space padding - if padding !== nothing && !('-' in flags) && !('0' in flags) - push!(blk.args, pad(width, padding, ' ')) - end - # print sign - '+' in flags ? push!(blk.args, :(write(out, neg?'-':'+'))) : - ' ' in flags ? push!(blk.args, :(write(out, neg?'-':' '))) : - push!(blk.args, :(neg && write(out, '-'))) - # print zero padding - if padding !== nothing && !('-' in flags) && '0' in flags - push!(blk.args, pad(width, padding, '0')) - end - # print digits - push!(blk.args, :(write(out, DIGITS[1]))) - if precision > 0 - if inside_g && !('#' in flags) - push!(blk.args, :(endidx = $ndigits; - while endidx > 1 && DIGITS[endidx] == UInt8('0') - endidx -= 1 - end; - if endidx > 1 - write(out, '.') - unsafe_write(out, pointer(DIGITS)+1, endidx-1) - end - )) - else - push!(blk.args, :(write(out, '.'))) - push!(blk.args, :(unsafe_write(out, pointer(DIGITS)+1, $(ndigits-1)))) - if ndigits < precision+1 - n = precision+1-ndigits - push!(blk.args, pad(n, n, '0')) - end - end - end - for ch in expmark - push!(blk.args, :(write(out, $ch))) - end - push!(blk.args, :(print_exp_e(out, exp))) - # print space padding - if padding !== nothing && '-' in flags - push!(blk.args, pad(width, padding, ' ')) - end - # return arg, expr - :(($x)::Real), ex -end - -function gen_a(flags::String, width::Int, precision::Int, c::Char) - # print float in hexadecimal format - # [a]: lowercase hex float, e.g. -0x1.cfp-2 - # [A]: uppercase hex float, e.g. -0X1.CFP-2 - # - # flags: - # (#): always print a decimal point - # (0): pad left with zeros - # (-): left justify - # ( ): precede non-negative values with " " - # (+): precede non-negative values with "+" - # - x, ex, blk = special_handler(flags,width) - if c == 'A' - hexmark, expmark = "0X", "P" - fn = :ini_HEX - else - hexmark, expmark = "0x", "p" - fn = :ini_hex - end - # if no precision, print max non-zero - if precision < 0 - push!(blk.args, :((do_out, args) = $fn(out,$x, $flags, $width, $precision, $c))) - else - ndigits = min(precision+1,length(DIGITS)-1) - push!(blk.args, :((do_out, args) = $fn(out,$x,$ndigits, $flags, $width, $precision, $c))) - end - ifblk = Expr(:if, :do_out, Expr(:block)) - push!(blk.args, ifblk) - blk = ifblk.args[2] - push!(blk.args, :((len, exp, neg) = args)) - if precision==0 && '#' in flags - expmark = string(".",expmark) - end - # calculate padding - padding = nothing - if precision > 0 - width -= precision+length(hexmark)+length(expmark)+4 - # 4 = leading + expsign + 1 exp digit + decimal - else - width -= length(hexmark)+length(expmark)+3+(precision<0 && '#' in flags) - # 3 = leading + expsign + 1 exp digit - end - if '+' in flags || ' ' in flags - width -= 1 # for the sign indicator - if width > 0 - padding = :($(width+1) - Base.ndigits(exp)) - end - else - if width > 0 - padding = :($(width+1) - neg - Base.ndigits(exp)) - end - end - if precision < 0 && width > 0 - if '#' in flags - padding = :($padding - (len-1)) - else - padding = :($padding - (len>1?len:0)) - end - end - # print space padding - if padding !== nothing && !('-' in flags) && !('0' in flags) - push!(blk.args, pad(width, padding, ' ')) - end - # print sign - '+' in flags ? push!(blk.args, :(write(out, neg?'-':'+'))) : - ' ' in flags ? push!(blk.args, :(write(out, neg?'-':' '))) : - push!(blk.args, :(neg && write(out, '-'))) - # hex prefix - for ch in hexmark - push!(blk.args, :(write(out, $ch))) - end - # print zero padding - if padding !== nothing && !('-' in flags) && '0' in flags - push!(blk.args, pad(width, padding, '0')) - end - # print digits - push!(blk.args, :(write(out, DIGITS[1]))) - if precision > 0 - push!(blk.args, :(write(out, '.'))) - push!(blk.args, :(unsafe_write(out, pointer(DIGITS)+1, $(ndigits-1)))) - if ndigits < precision+1 - n = precision+1-ndigits - push!(blk.args, pad(n, n, '0')) - end - elseif precision < 0 - ifvpblk = Expr(:if, :(len > 1), Expr(:block)) - vpblk = ifvpblk.args[2] - if '#' in flags - push!(blk.args, :(write(out, '.'))) - else - push!(vpblk.args, :(write(out, '.'))) - end - push!(vpblk.args, :(unsafe_write(out, pointer(DIGITS)+1, len-1))) - push!(blk.args, ifvpblk) - end - for ch in expmark - push!(blk.args, :(write(out, $ch))) - end - push!(blk.args, :(print_exp_a(out, exp))) - # print space padding - if padding !== nothing && '-' in flags - push!(blk.args, pad(width, padding, ' ')) - end - # return arg, expr - :(($x)::Real), ex -end - -function gen_c(flags::String, width::Int, precision::Int, c::Char) - # print a character: - # [cC]: both the same for us (Unicode) - # - # flags: - # (0): pad left with zeros - # (-): left justify - # - @gensym x - blk = Expr(:block, :($x = Char($x))) - if width > 1 && !('-' in flags) - p = '0' in flags ? '0' : ' ' - push!(blk.args, pad(width-1, :($width-charwidth($x)), p)) - end - push!(blk.args, :(write(out, $x))) - if width > 1 && '-' in flags - push!(blk.args, pad(width-1, :($width-charwidth($x)), ' ')) - end - :(($x)::Integer), blk -end - -function _limit(s, prec) - prec >= sizeof(s) && return s - p = prevind(s, prec+1) - n = nextind(s, p)-1 - s[1:(prec>=n?n:prevind(s,p))] -end - -function gen_s(flags::String, width::Int, precision::Int, c::Char) - # print a string: - # [sS]: both the same for us (Unicode) - # - # flags: - # (-): left justify - # - @gensym x - blk = Expr(:block) - if width > 0 - if !('#' in flags) - push!(blk.args, :($x = string($x))) - else - push!(blk.args, :($x = repr($x))) - end - if precision!=-1 - push!(blk.args, :($x = _limit($x, $precision))) - end - if !('-' in flags) - push!(blk.args, pad(width, :($width-strwidth($x)), ' ')) - end - push!(blk.args, :(write(out, $x))) - if '-' in flags - push!(blk.args, pad(width, :($width-strwidth($x)), ' ')) - end - else - if precision!=-1 - push!(blk.args, :(io = IOBuffer())) - else - push!(blk.args, :(io = out)) - end - if !('#' in flags) - push!(blk.args, :(print(io, $x))) - else - push!(blk.args, :(show(io, $x))) - end - if precision!=-1 - push!(blk.args, :(write(out, _limit(String(take!(io)), $precision)))) - end - end - :(($x)::Any), blk -end - -# TODO: faster pointer printing. - -function gen_p(flags::String, width::Int, precision::Int, c::Char) - # print pointer: - # [p]: the only option - # - @gensym x - blk = Expr(:block) - ptrwidth = Sys.WORD_SIZE>>2 - width -= ptrwidth+2 - if width > 0 && !('-' in flags) - push!(blk.args, pad(width, width, ' ')) - end - push!(blk.args, :(write(out, '0'))) - push!(blk.args, :(write(out, 'x'))) - push!(blk.args, :(write(out, String(hex(unsigned($x), $ptrwidth))))) - if width > 0 && '-' in flags - push!(blk.args, pad(width, width, ' ')) - end - :(($x)::Ptr), blk -end - -function gen_g(flags::String, width::Int, precision::Int, c::Char) - # print to fixed trailing precision - # [g]: lower case e on scientific - # [G]: Upper case e on scientific - # - # flags - # (#): always print a decimal point - # (0): pad left with zeros - # (-): left justify - # ( ): precede non-negative values with " " - # (+): precede non-negative values with "+" - # - x, ex, blk = special_handler(flags,width) - if precision < 0; precision = 6; end - ndigits = min(precision+1,length(DIGITS)-1) - # See if anyone else wants to handle it - push!(blk.args, :((do_out, args) = ini_dec(out,$x,$ndigits, $flags, $width, $precision, $c))) - ifblk = Expr(:if, :do_out, Expr(:block)) - push!(blk.args, ifblk) - blk = ifblk.args[2] - push!(blk.args, :((len, pt, neg) = args)) - push!(blk.args, :(exp = pt-1)) - push!(blk.args, :(do_f = $precision > exp >= -4)) # Should we interpret like %f or %e? - feblk = Expr(:if, :do_f, Expr(:block), Expr(:block)) - push!(blk.args, feblk) - fblk = feblk.args[2] - eblk = feblk.args[3] - - ### %f branch - # Follow the same logic as gen_f() but more work has to be deferred until runtime - # because precision is unknown until then. - push!(fblk.args, :(fprec = $precision - (exp+1))) - push!(fblk.args, :((do_out, args) = fix_dec(out, $x, $flags, $width, fprec, $c - 1))) - fifblk = Expr(:if, :do_out, Expr(:block)) - push!(fblk.args, fifblk) - blk = fifblk.args[2] - push!(blk.args, :((len, pt, neg) = args)) - push!(blk.args, :(padding = nothing)) - push!(blk.args, :(width = $width)) - # need to compute value before left-padding since trailing zeros are elided - push!(blk.args, :(tmpout = IOBuffer())) - push!(blk.args, :(print_fixed(tmpout,fprec,pt,len,$('#' in flags)))) - push!(blk.args, :(tmpstr = String(take!(tmpout)))) - push!(blk.args, :(width -= length(tmpstr))) - if '+' in flags || ' ' in flags - push!(blk.args, :(width -= 1)) - else - push!(blk.args, :(if neg width -= 1; end)) - end - push!(blk.args, :(if width >= 1 padding = width; end)) - # print space padding - if !('-' in flags) && !('0' in flags) - padexpr = dynamic_pad(:width, :padding, ' ') - push!(blk.args, :(if padding !== nothing - $padexpr; end)) - end - # print sign - '+' in flags ? push!(blk.args, :(write(out, neg?'-':'+'))) : - ' ' in flags ? push!(blk.args, :(write(out, neg?'-':' '))) : - push!(blk.args, :(neg && write(out, '-'))) - # print zero padding - if !('-' in flags) && '0' in flags - padexpr = dynamic_pad(:width, :padding, '0') - push!(blk.args, :(if padding !== nothing - $padexpr; end)) - end - # finally print value - push!(blk.args, :(write(out,tmpstr))) - # print space padding - if '-' in flags - padexpr = dynamic_pad(:width, :padding, ' ') - push!(blk.args, :(if padding !== nothing - $padexpr; end)) - end - - ### %e branch - # Here we can do all the work at macro expansion time - var, eex = gen_e(flags, width, precision-1, c, true) - push!(eblk.args, :($(var.args[1]) = $x)) - push!(eblk.args, eex) - - :(($x)::Real), ex -end - -### core unsigned integer decoding functions ### - -macro handle_zero(ex) - quote - if $(esc(ex)) == 0 - DIGITS[1] = '0' - return Int32(1), Int32(1), $(esc(:neg)) - end - end -end - -decode_oct(out, d, flags::String, width::Int, precision::Int, c::Char) = (true, decode_oct(d)) -decode_0ct(out, d, flags::String, width::Int, precision::Int, c::Char) = (true, decode_0ct(d)) -decode_dec(out, d, flags::String, width::Int, precision::Int, c::Char) = (true, decode_dec(d)) -decode_hex(out, d, flags::String, width::Int, precision::Int, c::Char) = (true, decode_hex(d)) -decode_HEX(out, d, flags::String, width::Int, precision::Int, c::Char) = (true, decode_HEX(d)) -fix_dec(out, d, flags::String, width::Int, precision::Int, c::Char) = (true, fix_dec(d, precision)) -ini_dec(out, d, ndigits::Int, flags::String, width::Int, precision::Int, c::Char) = (true, ini_dec(d, ndigits)) -ini_hex(out, d, ndigits::Int, flags::String, width::Int, precision::Int, c::Char) = (true, ini_hex(d, ndigits)) -ini_HEX(out, d, ndigits::Int, flags::String, width::Int, precision::Int, c::Char) = (true, ini_HEX(d, ndigits)) -ini_hex(out, d, flags::String, width::Int, precision::Int, c::Char) = (true, ini_hex(d)) -ini_HEX(out, d, flags::String, width::Int, precision::Int, c::Char) = (true, ini_HEX(d)) - - -# fallbacks for Real types without explicit decode_* implementation -decode_oct(d::Real) = decode_oct(Integer(d)) -decode_0ct(d::Real) = decode_0ct(Integer(d)) -decode_dec(d::Real) = decode_dec(Integer(d)) -decode_hex(d::Real) = decode_hex(Integer(d)) -decode_HEX(d::Real) = decode_HEX(Integer(d)) - -handlenegative(d::Unsigned) = (false, d) -function handlenegative(d::Integer) - if d < 0 - return true, unsigned(oftype(d,-d)) - else - return false, unsigned(d) - end -end - -function decode_oct(d::Integer) - neg, x = handlenegative(d) - @handle_zero x - pt = i = div((sizeof(x)<<3)-leading_zeros(x)+2,3) - while i > 0 - DIGITS[i] = '0'+(x&0x7) - x >>= 3 - i -= 1 - end - return Int32(pt), Int32(pt), neg -end - -function decode_0ct(d::Integer) - neg, x = handlenegative(d) - # doesn't need special handling for zero - pt = i = div((sizeof(x)<<3)-leading_zeros(x)+5,3) - while i > 0 - DIGITS[i] = '0'+(x&0x7) - x >>= 3 - i -= 1 - end - return Int32(pt), Int32(pt), neg -end - -function decode_dec(d::Integer) - neg, x = handlenegative(d) - @handle_zero x - pt = i = Base.ndigits0z(x) - while i > 0 - DIGITS[i] = '0'+rem(x,10) - x = div(x,10) - i -= 1 - end - return Int32(pt), Int32(pt), neg -end - -function decode_hex(d::Integer, symbols::Array{UInt8,1}) - neg, x = handlenegative(d) - @handle_zero x - pt = i = (sizeof(x)<<1)-(leading_zeros(x)>>2) - while i > 0 - DIGITS[i] = symbols[(x&0xf)+1] - x >>= 4 - i -= 1 - end - return Int32(pt), Int32(pt), neg -end - -const hex_symbols = b"0123456789abcdef" -const HEX_symbols = b"0123456789ABCDEF" - -decode_hex(x::Integer) = decode_hex(x,hex_symbols) -decode_HEX(x::Integer) = decode_hex(x,HEX_symbols) - -function decode(b::Int, x::BigInt) - neg = x.size < 0 - pt = Base.ndigits(x, abs(b)) - length(DIGITS) < pt+1 && resize!(DIGITS, pt+1) - neg && (x.size = -x.size) - ccall((:__gmpz_get_str, :libgmp), Cstring, - (Ptr{UInt8}, Cint, Ptr{BigInt}), DIGITS, b, &x) - neg && (x.size = -x.size) - return Int32(pt), Int32(pt), neg -end -decode_oct(x::BigInt) = decode(8, x) -decode_dec(x::BigInt) = decode(10, x) -decode_hex(x::BigInt) = decode(16, x) -decode_HEX(x::BigInt) = decode(-16, x) - -function decode_0ct(x::BigInt) - neg = x.size < 0 - DIGITS[1] = '0' - if x.size == 0 - return Int32(1), Int32(1), neg - end - pt = Base.ndigits0z(x, 8) + 1 - length(DIGITS) < pt+1 && resize!(DIGITS, pt+1) - neg && (x.size = -x.size) - p = convert(Ptr{UInt8}, DIGITS) + 1 - ccall((:__gmpz_get_str, :libgmp), Cstring, - (Ptr{UInt8}, Cint, Ptr{BigInt}), p, 8, &x) - neg && (x.size = -x.size) - return neg, Int32(pt), Int32(pt) -end - -### decoding functions directly used by printf generated code ### - -# decode_*(x)=> fixed precision, to 0th place, filled out -# fix_*(x,n) => fixed precision, to nth place, not filled out -# ini_*(x,n) => n initial digits, filled out - -# alternate versions: -# *_0ct(x,n) => ensure that the first octal digits is zero -# *_HEX(x,n) => use uppercase digits for hexadecimal - -# - returns (len, point, neg) -# - implies len = point -# - -function decode_dec(x::SmallFloatingPoint) - if x == 0.0 - DIGITS[1] = '0' - return (Int32(1), Int32(1), false) - end - len,pt,neg = grisu(x,Grisu.FIXED,0) - if len == 0 - DIGITS[1] = '0' - return (Int32(1), Int32(1), false) - else - for i = len+1:pt - DIGITS[i] = '0' - end - end - return Int32(len), Int32(pt), neg -end -# TODO: implement decode_oct, decode_0ct, decode_hex, decode_HEX for SmallFloatingPoint - -## fix decoding functions ## -# -# - returns (neg, point, len) -# - if len less than point, trailing zeros implied -# - -# fallback for Real types without explicit fix_dec implementation -fix_dec(x::Real, n::Int) = fix_dec(float(x),n) - -fix_dec(x::Integer, n::Int) = decode_dec(x) - -function fix_dec(x::SmallFloatingPoint, n::Int) - if n > length(DIGITS)-1; n = length(DIGITS)-1; end - len,pt,neg = grisu(x,Grisu.FIXED,n) - if len == 0 - DIGITS[1] = '0' - return (Int32(1), Int32(1), neg) - end - return Int32(len), Int32(pt), neg -end - -## ini decoding functions ## -# -# - returns (neg, point, len) -# - implies len = n (requested digits) -# - -# fallback for Real types without explicit fix_dec implementation -ini_dec(x::Real, n::Int) = ini_dec(float(x),n) - -function ini_dec(d::Integer, n::Int) - neg, x = handlenegative(d) - k = ndigits(x) - if k <= n - pt = k - for i = k:-1:1 - DIGITS[i] = '0'+rem(x,10) - x = div(x,10) - end - for i = k+1:n - DIGITS[i] = '0' - end - else - p = Base.powers_of_ten[k-n+1] - r = rem(x,p) - if r >= (p>>1) - x += p - if x >= Base.powers_of_ten[k+1] - p *= 10 - k += 1 - end - end - pt = k - x = div(x,p) - for i = n:-1:1 - DIGITS[i] = '0'+rem(x,10) - x = div(x,10) - end - end - return n, pt, neg -end - -function ini_dec(x::SmallFloatingPoint, n::Int) - if x == 0.0 - ccall(:memset, Ptr{Void}, (Ptr{Void}, Cint, Csize_t), DIGITS, '0', n) - return Int32(1), Int32(1), signbit(x) - else - len,pt,neg = grisu(x,Grisu.PRECISION,n) - end - return Int32(len), Int32(pt), neg -end - -function ini_dec(x::BigInt, n::Int) - if x.size == 0 - ccall(:memset, Ptr{Void}, (Ptr{Void}, Cint, Csize_t), DIGITS, '0', n) - return Int32(1), Int32(1), false - end - d = Base.ndigits0z(x) - if d <= n - info = decode_dec(x) - d == n && return info - p = convert(Ptr{Void}, DIGITS) + info[2] - ccall(:memset, Ptr{Void}, (Ptr{Void}, Cint, Csize_t), p, '0', n - info[2]) - return info - end - return (n, d, decode_dec(round(BigInt,x/big(10)^(d-n)))[3]) -end - - -ini_hex(x::Real, n::Int) = ini_hex(x,n,hex_symbols) -ini_HEX(x::Real, n::Int) = ini_hex(x,n,HEX_symbols) - -ini_hex(x::Real) = ini_hex(x,hex_symbols) -ini_HEX(x::Real) = ini_hex(x,HEX_symbols) - -ini_hex(x::Real, n::Int, symbols::Array{UInt8,1}) = ini_hex(float(x), n, symbols) -ini_hex(x::Real, symbols::Array{UInt8,1}) = ini_hex(float(x), symbols) - -function ini_hex(x::SmallFloatingPoint, n::Int, symbols::Array{UInt8,1}) - x = Float64(x) - if x == 0.0 - ccall(:memset, Ptr{Void}, (Ptr{Void}, Cint, Csize_t), DIGITS, '0', n) - return Int32(1), Int32(0), signbit(x) - else - s, p = frexp(x) - sigbits = 4*min(n-1,13) - s = 0.25*round(ldexp(s,1+sigbits)) - # ensure last 2 exponent bits either 01 or 10 - u = (reinterpret(UInt64,s) & 0x003f_ffff_ffff_ffff) >> (52-sigbits) - if n > 14 - ccall(:memset, Ptr{Void}, (Ptr{Void}, Cint, Csize_t), DIGITS, '0', n) - end - i = (sizeof(u)<<1)-(leading_zeros(u)>>2) - while i > 0 - DIGITS[i] = symbols[(u&0xf)+1] - u >>= 4 - i -= 1 - end - # pt is the binary exponent - return Int32(n), Int32(p-1), x < 0.0 - end -end - -function ini_hex(x::SmallFloatingPoint, symbols::Array{UInt8,1}) - x = Float64(x) - if x == 0.0 - ccall(:memset, Ptr{Void}, (Ptr{Void}, Cint, Csize_t), DIGITS, '0', 1) - return Int32(1), Int32(0), signbit(x) - else - s, p = frexp(x) - s *= 2.0 - u = (reinterpret(UInt64,s) & 0x001f_ffff_ffff_ffff) - t = (trailing_zeros(u) >> 2) - u >>= (t<<2) - n = 14-t - for i = n:-1:1 - DIGITS[i] = symbols[(u&0xf)+1] - u >>= 4 - end - # pt is the binary exponent - return Int32(n), Int32(p-1), x < 0.0 - end -end - -function ini_hex(x::Integer) - len,pt,neg = decode_hex(x) - pt = (len-1)<<2 - len,pt,neg -end -function ini_HEX(x::Integer) - len,pt,neg = decode_HEX(x) - pt = (len-1)<<2 - len,pt,neg -end - -# not implemented -ini_hex(x::Integer,ndigits::Int) = throw(MethodError(ini_hex,(x,ndigits))) - -#BigFloat -fix_dec(out, d::BigFloat, flags::String, width::Int, precision::Int, c::Char) = bigfloat_printf(out, d, flags, width, precision, c) -ini_dec(out, d::BigFloat, ndigits::Int, flags::String, width::Int, precision::Int, c::Char) = bigfloat_printf(out, d, flags, width, precision, c) -ini_hex(out, d::BigFloat, ndigits::Int, flags::String, width::Int, precision::Int, c::Char) = bigfloat_printf(out, d, flags, width, precision, c) -ini_HEX(out, d::BigFloat, ndigits::Int, flags::String, width::Int, precision::Int, c::Char) = bigfloat_printf(out, d, flags, width, precision, c) -ini_hex(out, d::BigFloat, flags::String, width::Int, precision::Int, c::Char) = bigfloat_printf(out, d, flags, width, precision, c) -ini_HEX(out, d::BigFloat, flags::String, width::Int, precision::Int, c::Char) = bigfloat_printf(out, d, flags, width, precision, c) -function bigfloat_printf(out, d, flags::String, width::Int, precision::Int, c::Char) - fmt_len = sizeof(flags)+4 - if width > 0 - fmt_len += ndigits(width) - end - if precision >= 0 - fmt_len += ndigits(precision)+1 - end - fmt = IOBuffer(fmt_len) - write(fmt, '%') - write(fmt, flags) - if width > 0 - print(fmt, width) - end - if precision == 0 - write(fmt, '.') - write(fmt, '0') - elseif precision > 0 - write(fmt, '.') - print(fmt, precision) - end - write(fmt, 'R') - write(fmt, c) - write(fmt, UInt8(0)) - printf_fmt = take!(fmt) - @assert length(printf_fmt) == fmt_len - bufsiz = length(DIGITS) - lng = ccall((:mpfr_snprintf,:libmpfr), Int32, - (Ptr{UInt8}, Culong, Ptr{UInt8}, Ptr{BigFloat}...), - DIGITS, bufsiz, printf_fmt, &d) - lng > 0 || error("invalid printf formatting for BigFloat") - unsafe_write(out, pointer(DIGITS), min(lng, bufsiz-1)) - return (false, ()) -end - -### external printf interface ### - -is_str_expr(ex) = - isa(ex,Expr) && (ex.head == :string || (ex.head == :macrocall && isa(ex.args[1],Symbol) && - endswith(string(ex.args[1]),"str"))) - -function _printf(macroname, io, fmt, args) - isa(fmt, AbstractString) || throw(ArgumentError("$macroname: format must be a plain static string (no interpolation or prefix)")) - sym_args, blk = gen(fmt) - - has_splatting = false - for arg in args - if isa(arg, Expr) && arg.head == :... - has_splatting = true - break - end - end - - # - # Immediately check for corresponding arguments if there is no splatting - # - if !has_splatting && length(sym_args) != length(args) - throw(ArgumentError("$macroname: wrong number of arguments ($(length(args))) should be ($(length(sym_args)))")) - end - - for i = length(sym_args):-1:1 - var = sym_args[i].args[1] - if has_splatting - unshift!(blk.args, :($var = G[$i])) - else - unshift!(blk.args, :($var = $(esc(args[i])))) - end - end - - # - # Delay generation of argument list and check until evaluation time instead of macro - # expansion time if there is splatting. - # - if has_splatting - x = Expr(:call,:tuple,args...) - unshift!(blk.args, - quote - G = $(esc(x)) - if length(G) != $(length(sym_args)) - throw(ArgumentError($macroname,": wrong number of arguments (",length(G),") should be (",$(length(sym_args)),")")) - end - end - ) - end - - unshift!(blk.args, :(out = $io)) - Expr(:let, blk) -end - -""" - @printf([io::IOStream], "%Fmt", args...) - -Print `args` using C `printf()` style format specification string, with some caveats: -`Inf` and `NaN` are printed consistently as `Inf` and `NaN` for flags `%a`, `%A`, -`%e`, `%E`, `%f`, `%F`, `%g`, and `%G`. Furthermore, if a floating point number is -equally close to the numeric values of two possible output strings, the output -string further away from zero is chosen. - -Optionally, an `IOStream` -may be passed as the first argument to redirect output. - -# Examples - -```jldoctest -julia> @printf("%f %F %f %F\\n", Inf, Inf, NaN, NaN) -Inf Inf NaN NaN\n - -julia> @printf "%.0f %.1f %f\\n" 0.5 0.025 -0.0078125 -1 0.0 -0.007813 -``` -""" -macro printf(args...) - isempty(args) && throw(ArgumentError("@printf: called with no arguments")) - if isa(args[1], AbstractString) || is_str_expr(args[1]) - _printf("@printf", :STDOUT, args[1], args[2:end]) - else - (length(args) >= 2 && (isa(args[2], AbstractString) || is_str_expr(args[2]))) || - throw(ArgumentError("@printf: first or second argument must be a format string")) - _printf("@printf", esc(args[1]), args[2], args[3:end]) - end -end - -""" - @sprintf("%Fmt", args...) - -Return `@printf` formatted output as string. - -# Examples - -```jldoctest -julia> s = @sprintf "this is a %s %15.1f" "test" 34.567; - -julia> println(s) -this is a test 34.6 -``` -""" -macro sprintf(args...) - isempty(args) && throw(ArgumentError("@sprintf: called with zero arguments")) - isa(args[1], AbstractString) || is_str_expr(args[1]) || - throw(ArgumentError("@sprintf: first argument must be a format string")) - letexpr = _printf("@sprintf", :(IOBuffer()), args[1], args[2:end]) - push!(letexpr.args[1].args, :(String(take!(out)))) - letexpr -end - -end # module diff --git a/julia-0.6.3/share/julia/base/process.jl b/julia-0.6.3/share/julia/base/process.jl deleted file mode 100644 index d7dff2f..0000000 --- a/julia-0.6.3/share/julia/base/process.jl +++ /dev/null @@ -1,802 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -abstract type AbstractCmd end - -# libuv process option flags -const UV_PROCESS_WINDOWS_VERBATIM_ARGUMENTS = UInt8(1 << 2) -const UV_PROCESS_DETACHED = UInt8(1 << 3) -const UV_PROCESS_WINDOWS_HIDE = UInt8(1 << 4) - -struct Cmd <: AbstractCmd - exec::Vector{String} - ignorestatus::Bool - flags::UInt32 # libuv process flags - env::Union{Array{String},Void} - dir::String - Cmd(exec::Vector{String}) = - new(exec, false, 0x00, nothing, "") - Cmd(cmd::Cmd, ignorestatus, flags, env, dir) = - new(cmd.exec, ignorestatus, flags, env, - dir === cmd.dir ? dir : cstr(dir)) - function Cmd(cmd::Cmd; ignorestatus::Bool=cmd.ignorestatus, env=cmd.env, dir::AbstractString=cmd.dir, - detach::Bool = 0 != cmd.flags & UV_PROCESS_DETACHED, - windows_verbatim::Bool = 0 != cmd.flags & UV_PROCESS_WINDOWS_VERBATIM_ARGUMENTS, - windows_hide::Bool = 0 != cmd.flags & UV_PROCESS_WINDOWS_HIDE) - flags = detach*UV_PROCESS_DETACHED | - windows_verbatim*UV_PROCESS_WINDOWS_VERBATIM_ARGUMENTS | - windows_hide*UV_PROCESS_WINDOWS_HIDE - new(cmd.exec, ignorestatus, flags, byteenv(env), - dir === cmd.dir ? dir : cstr(dir)) - end -end - -""" - Cmd(cmd::Cmd; ignorestatus, detach, windows_verbatim, windows_hide, env, dir) - -Construct a new `Cmd` object, representing an external program and arguments, from `cmd`, -while changing the settings of the optional keyword arguments: - -* `ignorestatus::Bool`: If `true` (defaults to `false`), then the `Cmd` will not throw an - error if the return code is nonzero. -* `detach::Bool`: If `true` (defaults to `false`), then the `Cmd` will be run in a new - process group, allowing it to outlive the `julia` process and not have Ctrl-C passed to - it. -* `windows_verbatim::Bool`: If `true` (defaults to `false`), then on Windows the `Cmd` will - send a command-line string to the process with no quoting or escaping of arguments, even - arguments containing spaces. (On Windows, arguments are sent to a program as a single - "command-line" string, and programs are responsible for parsing it into arguments. By - default, empty arguments and arguments with spaces or tabs are quoted with double quotes - `"` in the command line, and `\\` or `"` are preceded by backslashes. - `windows_verbatim=true` is useful for launching programs that parse their command line in - nonstandard ways.) Has no effect on non-Windows systems. -* `windows_hide::Bool`: If `true` (defaults to `false`), then on Windows no new console - window is displayed when the `Cmd` is executed. This has no effect if a console is - already open or on non-Windows systems. -* `env`: Set environment variables to use when running the `Cmd`. `env` is either a - dictionary mapping strings to strings, an array of strings of the form `"var=val"`, an - array or tuple of `"var"=>val` pairs, or `nothing`. In order to modify (rather than - replace) the existing environment, create `env` by `copy(ENV)` and then set - `env["var"]=val` as desired. -* `dir::AbstractString`: Specify a working directory for the command (instead - of the current directory). - -For any keywords that are not specified, the current settings from `cmd` are used. Normally, -to create a `Cmd` object in the first place, one uses backticks, e.g. - - Cmd(`echo "Hello world"`, ignorestatus=true, detach=false) -""" -Cmd - -hash(x::Cmd, h::UInt) = hash(x.exec, hash(x.env, hash(x.ignorestatus, hash(x.dir, hash(x.flags, h))))) -==(x::Cmd, y::Cmd) = x.exec == y.exec && x.env == y.env && x.ignorestatus == y.ignorestatus && - x.dir == y.dir && isequal(x.flags, y.flags) - -struct OrCmds <: AbstractCmd - a::AbstractCmd - b::AbstractCmd - OrCmds(a::AbstractCmd, b::AbstractCmd) = new(a, b) -end - -struct ErrOrCmds <: AbstractCmd - a::AbstractCmd - b::AbstractCmd - ErrOrCmds(a::AbstractCmd, b::AbstractCmd) = new(a, b) -end - -struct AndCmds <: AbstractCmd - a::AbstractCmd - b::AbstractCmd - AndCmds(a::AbstractCmd, b::AbstractCmd) = new(a, b) -end - -hash(x::AndCmds, h::UInt) = hash(x.a, hash(x.b, h)) -==(x::AndCmds, y::AndCmds) = x.a == y.a && x.b == y.b - -shell_escape(cmd::Cmd; special::AbstractString="") = - shell_escape(cmd.exec..., special=special) - -function show(io::IO, cmd::Cmd) - print_env = cmd.env !== nothing - print_dir = !isempty(cmd.dir) - (print_env || print_dir) && print(io, "setenv(") - esc = shell_escape(cmd, special=shell_special) - print(io, '`') - for c in esc - if c == '`' - print(io, '\\') - end - print(io, c) - end - print(io, '`') - print_env && (print(io, ","); show(io, cmd.env)) - print_dir && (print(io, "; dir="); show(io, cmd.dir)) - (print_dir || print_env) && print(io, ")") -end - -function show(io::IO, cmds::Union{OrCmds,ErrOrCmds}) - print(io, "pipeline(") - show(io, cmds.a) - print(io, ", ") - print(io, isa(cmds, ErrOrCmds) ? "stderr=" : "stdout=") - show(io, cmds.b) - print(io, ")") -end - -function show(io::IO, cmds::AndCmds) - show(io, cmds.a) - print(io, " & ") - show(io, cmds.b) -end - -const STDIN_NO = 0 -const STDOUT_NO = 1 -const STDERR_NO = 2 - -struct FileRedirect - filename::AbstractString - append::Bool - function FileRedirect(filename, append) - if lowercase(filename) == (@static is_windows() ? "nul" : "/dev/null") - warn_once("for portability use DevNull instead of a file redirect") - end - new(filename, append) - end -end - -uvhandle(::DevNullStream) = C_NULL -uvtype(::DevNullStream) = UV_STREAM - -uvhandle(x::Ptr) = x -uvtype(::Ptr) = UV_STREAM - -# Not actually a pointer, but that's how we pass it through the C API so it's fine -uvhandle(x::RawFD) = convert(Ptr{Void}, x.fd % UInt) -uvtype(x::RawFD) = UV_RAW_FD - -const Redirectable = Union{IO, FileRedirect, RawFD} -const StdIOSet = NTuple{3, Union{Redirectable, Ptr{Void}}} # XXX: remove Ptr{Void} once libuv is refactored to use upstream release - -struct CmdRedirect <: AbstractCmd - cmd::AbstractCmd - handle::Redirectable - stream_no::Int -end - -function show(io::IO, cr::CmdRedirect) - print(io, "pipeline(") - show(io, cr.cmd) - print(io, ", ") - if cr.stream_no == STDOUT_NO - print(io, "stdout=") - elseif cr.stream_no == STDERR_NO - print(io, "stderr=") - elseif cr.stream_no == STDIN_NO - print(io, "stdin=") - end - show(io, cr.handle) - print(io, ")") -end - -""" - ignorestatus(command) - -Mark a command object so that running it will not throw an error if the result code is non-zero. -""" -ignorestatus(cmd::Cmd) = Cmd(cmd, ignorestatus=true) -ignorestatus(cmd::Union{OrCmds,AndCmds}) = - typeof(cmd)(ignorestatus(cmd.a), ignorestatus(cmd.b)) - -""" - detach(command) - -Mark a command object so that it will be run in a new process group, allowing it to outlive the julia process, and not have Ctrl-C interrupts passed to it. -""" -detach(cmd::Cmd) = Cmd(cmd; detach=true) - -# like String(s), but throw an error if s contains NUL, since -# libuv requires NUL-terminated strings -function cstr(s) - if Base.containsnul(s) - throw(ArgumentError("strings containing NUL cannot be passed to spawned processes")) - end - return String(s) -end - -# convert various env representations into an array of "key=val" strings -byteenv(env::AbstractArray{<:AbstractString}) = - String[cstr(x) for x in env] -byteenv(env::Associative) = - String[cstr(string(k)*"="*string(v)) for (k,v) in env] -byteenv(env::Void) = nothing -byteenv{T<:AbstractString}(env::Union{AbstractVector{Pair{T}}, Tuple{Vararg{Pair{T}}}}) = - String[cstr(k*"="*string(v)) for (k,v) in env] - -""" - setenv(command::Cmd, env; dir="") - -Set environment variables to use when running the given `command`. `env` is either a -dictionary mapping strings to strings, an array of strings of the form `"var=val"`, or zero -or more `"var"=>val` pair arguments. In order to modify (rather than replace) the existing -environment, create `env` by `copy(ENV)` and then setting `env["var"]=val` as desired, or -use `withenv`. - -The `dir` keyword argument can be used to specify a working directory for the command. -""" -setenv(cmd::Cmd, env; dir="") = Cmd(cmd; env=byteenv(env), dir=dir) -setenv(cmd::Cmd, env::Pair{<:AbstractString}...; dir="") = - setenv(cmd, env; dir=dir) -setenv(cmd::Cmd; dir="") = Cmd(cmd; dir=dir) - -(&)(left::AbstractCmd, right::AbstractCmd) = AndCmds(left, right) -redir_out(src::AbstractCmd, dest::AbstractCmd) = OrCmds(src, dest) -redir_err(src::AbstractCmd, dest::AbstractCmd) = ErrOrCmds(src, dest) -Base.mr_empty(f, op::typeof(&), T::Type{<:Base.AbstractCmd}) = - throw(ArgumentError("reducing over an empty collection of type $T with operator & is not allowed")) - -# Stream Redirects -redir_out(dest::Redirectable, src::AbstractCmd) = CmdRedirect(src, dest, STDIN_NO) -redir_out(src::AbstractCmd, dest::Redirectable) = CmdRedirect(src, dest, STDOUT_NO) -redir_err(src::AbstractCmd, dest::Redirectable) = CmdRedirect(src, dest, STDERR_NO) - -# File redirects -redir_out(src::AbstractCmd, dest::AbstractString) = CmdRedirect(src, FileRedirect(dest, false), STDOUT_NO) -redir_out(src::AbstractString, dest::AbstractCmd) = CmdRedirect(dest, FileRedirect(src, false), STDIN_NO) -redir_err(src::AbstractCmd, dest::AbstractString) = CmdRedirect(src, FileRedirect(dest, false), STDERR_NO) -redir_out_append(src::AbstractCmd, dest::AbstractString) = CmdRedirect(src, FileRedirect(dest, true), STDOUT_NO) -redir_err_append(src::AbstractCmd, dest::AbstractString) = CmdRedirect(src, FileRedirect(dest, true), STDERR_NO) - -""" - pipeline(command; stdin, stdout, stderr, append=false) - -Redirect I/O to or from the given `command`. Keyword arguments specify which of the -command's streams should be redirected. `append` controls whether file output appends to the -file. This is a more general version of the 2-argument `pipeline` function. -`pipeline(from, to)` is equivalent to `pipeline(from, stdout=to)` when `from` is a command, -and to `pipeline(to, stdin=from)` when `from` is another kind of data source. - -**Examples**: - -```julia -run(pipeline(`dothings`, stdout="out.txt", stderr="errs.txt")) -run(pipeline(`update`, stdout="log.txt", append=true)) -``` -""" -function pipeline(cmd::AbstractCmd; stdin=nothing, stdout=nothing, stderr=nothing, append::Bool=false) - if append && stdout === nothing && stderr === nothing - error("append set to true, but no output redirections specified") - end - if stdin !== nothing - cmd = redir_out(stdin, cmd) - end - if stdout !== nothing - cmd = append ? redir_out_append(cmd, stdout) : redir_out(cmd, stdout) - end - if stderr !== nothing - cmd = append ? redir_err_append(cmd, stderr) : redir_err(cmd, stderr) - end - return cmd -end - -pipeline(cmd::AbstractCmd, dest) = pipeline(cmd, stdout=dest) -pipeline(src::Union{Redirectable,AbstractString}, cmd::AbstractCmd) = pipeline(cmd, stdin=src) - -""" - pipeline(from, to, ...) - -Create a pipeline from a data source to a destination. The source and destination can be -commands, I/O streams, strings, or results of other `pipeline` calls. At least one argument -must be a command. Strings refer to filenames. When called with more than two arguments, -they are chained together from left to right. For example `pipeline(a,b,c)` is equivalent to -`pipeline(pipeline(a,b),c)`. This provides a more concise way to specify multi-stage -pipelines. - -**Examples**: - -```julia -run(pipeline(`ls`, `grep xyz`)) -run(pipeline(`ls`, "out.txt")) -run(pipeline("out.txt", `grep xyz`)) -``` -""" -pipeline(a, b, c, d...) = pipeline(pipeline(a,b), c, d...) - -mutable struct Process <: AbstractPipe - cmd::Cmd - handle::Ptr{Void} - in::IO - out::IO - err::IO - exitcode::Int64 - termsignal::Int32 - exitnotify::Condition - closenotify::Condition - function Process(cmd::Cmd, handle::Ptr{Void}, - in::Union{Redirectable, Ptr{Void}}, - out::Union{Redirectable, Ptr{Void}}, - err::Union{Redirectable, Ptr{Void}}) - if !isa(in, IO) - in = DevNull - end - if !isa(out, IO) - out = DevNull - end - if !isa(err, IO) - err = DevNull - end - this = new(cmd, handle, in, out, err, - typemin(fieldtype(Process, :exitcode)), - typemin(fieldtype(Process, :termsignal)), - Condition(), Condition()) - finalizer(this, uvfinalize) - return this - end -end -pipe_reader(p::Process) = p.out -pipe_writer(p::Process) = p.in - -struct ProcessChain <: AbstractPipe - processes::Vector{Process} - in::Redirectable - out::Redirectable - err::Redirectable - ProcessChain(stdios::StdIOSet) = new(Process[], stdios[1], stdios[2], stdios[3]) -end -pipe_reader(p::ProcessChain) = p.out -pipe_writer(p::ProcessChain) = p.in - -function _jl_spawn(cmd, argv, loop::Ptr{Void}, pp::Process, - in, out, err) - proc = Libc.malloc(_sizeof_uv_process) - disassociate_julia_struct(proc) - error = ccall(:jl_spawn, Int32, - (Cstring, Ptr{Cstring}, Ptr{Void}, Ptr{Void}, Any, Int32, - Ptr{Void}, Int32, Ptr{Void}, Int32, Ptr{Void}, Int32, Ptr{Cstring}, Cstring, Ptr{Void}), - cmd, argv, loop, proc, pp, uvtype(in), - uvhandle(in), uvtype(out), uvhandle(out), uvtype(err), uvhandle(err), - pp.cmd.flags, pp.cmd.env === nothing ? C_NULL : pp.cmd.env, isempty(pp.cmd.dir) ? C_NULL : pp.cmd.dir, - uv_jl_return_spawn::Ptr{Void}) - if error != 0 - ccall(:jl_forceclose_uv, Void, (Ptr{Void},), proc) - throw(UVError("could not spawn "*string(pp.cmd), error)) - end - associate_julia_struct(proc, pp) - return proc -end - -function uvfinalize(proc::Process) - if proc.handle != C_NULL - disassociate_julia_struct(proc.handle) - ccall(:jl_close_uv, Void, (Ptr{Void},), proc.handle) - proc.handle = C_NULL - end - nothing -end - -function uv_return_spawn(p::Ptr{Void}, exit_status::Int64, termsignal::Int32) - data = ccall(:jl_uv_process_data, Ptr{Void}, (Ptr{Void},), p) - data == C_NULL && return - proc = unsafe_pointer_to_objref(data)::Process - proc.exitcode = exit_status - proc.termsignal = termsignal - ccall(:jl_close_uv, Void, (Ptr{Void},), proc.handle) - notify(proc.exitnotify) - nothing -end - -function _uv_hook_close(proc::Process) - proc.handle = C_NULL - notify(proc.closenotify) -end - -function spawn(redirect::CmdRedirect, stdios::StdIOSet; chain::Nullable{ProcessChain}=Nullable{ProcessChain}()) - spawn(redirect.cmd, - (redirect.stream_no == STDIN_NO ? redirect.handle : stdios[1], - redirect.stream_no == STDOUT_NO ? redirect.handle : stdios[2], - redirect.stream_no == STDERR_NO ? redirect.handle : stdios[3]), - chain=chain) -end - -function spawn(cmds::OrCmds, stdios::StdIOSet; chain::Nullable{ProcessChain}=Nullable{ProcessChain}()) - out_pipe = Libc.malloc(_sizeof_uv_named_pipe) - in_pipe = Libc.malloc(_sizeof_uv_named_pipe) - link_pipe(in_pipe, false, out_pipe, false) - if isnull(chain) - chain = Nullable(ProcessChain(stdios)) - end - try - spawn(cmds.a, (stdios[1], out_pipe, stdios[3]), chain=chain) - spawn(cmds.b, (in_pipe, stdios[2], stdios[3]), chain=chain) - finally - close_pipe_sync(out_pipe) - close_pipe_sync(in_pipe) - Libc.free(out_pipe) - Libc.free(in_pipe) - end - get(chain) -end - -function spawn(cmds::ErrOrCmds, stdios::StdIOSet; chain::Nullable{ProcessChain}=Nullable{ProcessChain}()) - out_pipe = Libc.malloc(_sizeof_uv_named_pipe) - in_pipe = Libc.malloc(_sizeof_uv_named_pipe) - link_pipe(in_pipe, false, out_pipe, false) - if isnull(chain) - chain = Nullable(ProcessChain(stdios)) - end - try - spawn(cmds.a, (stdios[1], stdios[2], out_pipe), chain=chain) - spawn(cmds.b, (in_pipe, stdios[2], stdios[3]), chain=chain) - finally - close_pipe_sync(out_pipe) - close_pipe_sync(in_pipe) - Libc.free(out_pipe) - Libc.free(in_pipe) - end - get(chain) -end - -function setup_stdio(stdio::PipeEndpoint, readable::Bool) - closeafter = false - if stdio.status == StatusUninit - if readable - link_pipe(io, false, stdio, true) - else - link_pipe(stdio, true, io, false) - end - closeafter = true - end - return (stdio.handle, closeafter) -end - -function setup_stdio(stdio::Pipe, readable::Bool) - if stdio.in.status == StatusUninit && stdio.out.status == StatusUninit - link_pipe(stdio) - end - io = readable ? stdio.out : stdio.in - return (io, false) -end - -function setup_stdio(stdio::IOStream, readable::Bool) - io = Filesystem.File(RawFD(fd(stdio))) - return (io, false) -end - -function setup_stdio(stdio::FileRedirect, readable::Bool) - if readable - attr = JL_O_RDONLY - perm = zero(S_IRUSR) - else - attr = JL_O_WRONLY | JL_O_CREAT - attr |= stdio.append ? JL_O_APPEND : JL_O_TRUNC - perm = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH - end - io = Filesystem.open(stdio.filename, attr, perm) - return (io, true) -end - -function setup_stdio(io, readable::Bool) - # if there is no specialization, - # assume that uvhandle and uvtype are defined for it - return io, false -end - -function setup_stdio(stdio::Ptr{Void}, readable::Bool) - return (stdio, false) -end - -function close_stdio(stdio::Ptr{Void}) - close_pipe_sync(stdio) - Libc.free(stdio) -end - -function close_stdio(stdio) - close(stdio) -end - -function setup_stdio(anon::Function, stdio::StdIOSet) - in, close_in = setup_stdio(stdio[1], true) - out, close_out = setup_stdio(stdio[2], false) - err, close_err = setup_stdio(stdio[3], false) - anon(in, out, err) - close_in && close_stdio(in) - close_out && close_stdio(out) - close_err && close_stdio(err) -end - -function spawn(cmd::Cmd, stdios::StdIOSet; chain::Nullable{ProcessChain}=Nullable{ProcessChain}()) - if isempty(cmd.exec) - throw(ArgumentError("cannot spawn empty command")) - end - loop = eventloop() - pp = Process(cmd, C_NULL, stdios[1], stdios[2], stdios[3]) - setup_stdio(stdios) do in, out, err - pp.handle = _jl_spawn(cmd.exec[1], cmd.exec, loop, pp, - in, out, err) - end - if !isnull(chain) - push!(get(chain).processes, pp) - end - pp -end - -function spawn(cmds::AndCmds, stdios::StdIOSet; chain::Nullable{ProcessChain}=Nullable{ProcessChain}()) - if isnull(chain) - chain = Nullable(ProcessChain(stdios)) - end - setup_stdio(stdios) do in, out, err - spawn(cmds.a, (in,out,err), chain=chain) - spawn(cmds.b, (in,out,err), chain=chain) - end - get(chain) -end - -# INTERNAL -# returns stdios: -# A set of up to 256 stdio instructions, where each entry can be either: -# | - An IO to be passed to the child -# | - DevNull to pass /dev/null -# | - An Filesystem.File object to redirect the output to -# \ - A string specifying a filename to be opened - -spawn_opts_swallow(stdios::StdIOSet) = (stdios,) -spawn_opts_swallow(in::Redirectable=DevNull, out::Redirectable=DevNull, err::Redirectable=DevNull, args...) = - ((in, out, err), args...) -spawn_opts_inherit(stdios::StdIOSet) = (stdios,) -# pass original descriptors to child processes by default, because we might -# have already exhausted and closed the libuv object for our standard streams. -# this caused issue #8529. -spawn_opts_inherit(in::Redirectable=RawFD(0), out::Redirectable=RawFD(1), err::Redirectable=RawFD(2), args...) = - ((in, out, err), args...) - -spawn(cmds::AbstractCmd, args...; chain::Nullable{ProcessChain}=Nullable{ProcessChain}()) = - spawn(cmds, spawn_opts_swallow(args...)...; chain=chain) - -function eachline(cmd::AbstractCmd, stdin; chomp::Bool=true) - stdout = Pipe() - processes = spawn(cmd, (stdin,stdout,STDERR)) - close(stdout.in) - out = stdout.out - # implicitly close after reading lines, since we opened - return EachLine(out, chomp=chomp, - ondone=()->(close(out); success(processes) || pipeline_error(processes)))::EachLine -end -eachline(cmd::AbstractCmd; chomp::Bool=true) = eachline(cmd, DevNull, chomp=chomp) - -# return a Process object to read-to/write-from the pipeline -""" - open(command, mode::AbstractString="r", stdio=DevNull) - -Start running `command` asynchronously, and return a tuple `(stream,process)`. If `mode` is -`"r"`, then `stream` reads from the process's standard output and `stdio` optionally -specifies the process's standard input stream. If `mode` is `"w"`, then `stream` writes to -the process's standard input and `stdio` optionally specifies the process's standard output -stream. -""" -function open(cmds::AbstractCmd, mode::AbstractString="r", other::Redirectable=DevNull) - if mode == "r" - in = other - out = io = Pipe() - processes = spawn(cmds, (in,out,STDERR)) - close(out.in) - elseif mode == "w" - in = io = Pipe() - out = other - processes = spawn(cmds, (in,out,STDERR)) - close(in.out) - else - throw(ArgumentError("mode must be \"r\" or \"w\", not \"$mode\"")) - end - return (io, processes) -end - -""" - open(f::Function, command, mode::AbstractString="r", stdio=DevNull) - -Similar to `open(command, mode, stdio)`, but calls `f(stream)` on the resulting read or -write stream, then closes the stream and waits for the process to complete. Returns the -value returned by `f`. -""" -function open(f::Function, cmds::AbstractCmd, args...) - io, P = open(cmds, args...) - ret = try - f(io) - catch - kill(P) - rethrow() - finally - close(io) - end - success(P) || pipeline_error(P) - return ret -end - -# TODO: deprecate this - -""" - readandwrite(command) - -Starts running a command asynchronously, and returns a tuple (stdout,stdin,process) of the -output stream and input stream of the process, and the process object itself. -""" -function readandwrite(cmds::AbstractCmd) - in = Pipe() - out, processes = open(cmds, "r", in) - (out, in, processes) -end - -function read(cmd::AbstractCmd, stdin::Redirectable=DevNull) - out, procs = open(cmd, "r", stdin) - bytes = read(out) - !success(procs) && pipeline_error(procs) - return bytes -end - -function readstring(cmd::AbstractCmd, stdin::Redirectable=DevNull) - return String(read(cmd, stdin)) -end - -function writeall(cmd::AbstractCmd, stdin::AbstractString, stdout::Redirectable=DevNull) - open(cmd, "w", stdout) do io - write(io, stdin) - end -end - -""" - run(command, args...) - -Run a command object, constructed with backticks. Throws an error if anything goes wrong, -including the process exiting with a non-zero status. -""" -function run(cmds::AbstractCmd, args...) - ps = spawn(cmds, spawn_opts_inherit(args...)...) - success(ps) ? nothing : pipeline_error(ps) -end - -const SIGPIPE = 13 -function test_success(proc::Process) - assert(process_exited(proc)) - if proc.exitcode < 0 - #TODO: this codepath is not currently tested - throw(UVError("could not start process $(string(proc.cmd))", proc.exitcode)) - end - proc.exitcode == 0 && (proc.termsignal == 0 || proc.termsignal == SIGPIPE) -end - -function success(x::Process) - wait(x) - kill(x) - test_success(x) -end -success(procs::Vector{Process}) = mapreduce(success, &, procs) -success(procs::ProcessChain) = success(procs.processes) - -""" - success(command) - -Run a command object, constructed with backticks, and tell whether it was successful (exited -with a code of 0). An exception is raised if the process cannot be started. -""" -success(cmd::AbstractCmd) = success(spawn(cmd)) - -function pipeline_error(proc::Process) - if !proc.cmd.ignorestatus - error("failed process: ", proc, " [", proc.exitcode, "]") - end - nothing -end - -function pipeline_error(procs::ProcessChain) - failed = Process[] - for p = procs.processes - if !test_success(p) && !p.cmd.ignorestatus - push!(failed, p) - end - end - isempty(failed) && return nothing - length(failed) == 1 && pipeline_error(failed[1]) - msg = "failed processes:" - for proc in failed - msg = string(msg, "\n ", proc, " [", proc.exitcode, "]") - end - error(msg) -end - -_jl_kill(p::Process, signum::Integer) = ccall(:uv_process_kill, Int32, (Ptr{Void},Int32), p.handle, signum) - -""" - kill(p::Process, signum=SIGTERM) - -Send a signal to a process. The default is to terminate the process. -""" -function kill(p::Process, signum::Integer) - if process_running(p) - @assert p.handle != C_NULL - _jl_kill(p, signum) - else - Int32(-1) - end -end -kill(ps::Vector{Process}) = map(kill, ps) -kill(ps::ProcessChain) = map(kill, ps.processes) -kill(p::Process) = kill(p, 15) #SIGTERM - -function _contains_newline(bufptr::Ptr{Void}, len::Int32) - return (ccall(:memchr, Ptr{Void}, (Ptr{Void},Int32,Csize_t), bufptr, '\n', len) != C_NULL) -end - -## process status ## - -""" - process_running(p::Process) - -Determine whether a process is currently running. -""" -process_running(s::Process) = s.exitcode == typemin(fieldtype(Process, :exitcode)) -process_running(s::Vector{Process}) = any(process_running, s) -process_running(s::ProcessChain) = process_running(s.processes) - -""" - process_exited(p::Process) - -Determine whether a process has exited. -""" -process_exited(s::Process) = !process_running(s) -process_exited(s::Vector{Process}) = all(process_exited, s) -process_exited(s::ProcessChain) = process_exited(s.processes) - -process_signaled(s::Process) = (s.termsignal > 0) - -#process_stopped (s::Process) = false #not supported by libuv. Do we need this? -#process_stop_signal(s::Process) = false #not supported by libuv. Do we need this? - -function process_status(s::Process) - process_running(s) ? "ProcessRunning" : - process_signaled(s) ? "ProcessSignaled("*string(s.termsignal)*")" : - #process_stopped(s) ? "ProcessStopped("*string(process_stop_signal(s))*")" : - process_exited(s) ? "ProcessExited("*string(s.exitcode)*")" : - error("process status error") -end - -## implementation of `cmd` syntax ## - -arg_gen() = String[] -arg_gen(x::AbstractString) = String[cstr(x)] -arg_gen(cmd::Cmd) = cmd.exec - -function arg_gen(head) - if applicable(start, head) - vals = String[] - for x in head - push!(vals, cstr(string(x))) - end - return vals - else - return String[cstr(string(head))] - end -end - -function arg_gen(head, tail...) - head = arg_gen(head) - tail = arg_gen(tail...) - vals = String[] - for h = head, t = tail - push!(vals, cstr(string(h,t))) - end - return vals -end - -function cmd_gen(parsed) - args = String[] - for arg in parsed - append!(args, arg_gen(arg...)) - end - return Cmd(args) -end - -macro cmd(str) - return :(cmd_gen($(esc(shell_parse(str, special=shell_special)[1])))) -end - -wait(x::Process) = if !process_exited(x); stream_wait(x, x.exitnotify); end -wait(x::ProcessChain) = for p in x.processes; wait(p); end - -show(io::IO, p::Process) = print(io, "Process(", p.cmd, ", ", process_status(p), ")") diff --git a/julia-0.6.3/share/julia/base/profile.jl b/julia-0.6.3/share/julia/base/profile.jl deleted file mode 100644 index a5afcb3..0000000 --- a/julia-0.6.3/share/julia/base/profile.jl +++ /dev/null @@ -1,681 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -module Profile - -import Base.StackTraces: lookup, UNKNOWN, show_spec_linfo -using Base: iszero - -export @profile - -""" - @profile - -`@profile <expression>` runs your expression while taking periodic backtraces. These are -appended to an internal buffer of backtraces. -""" -macro profile(ex) - quote - try - status = start_timer() - if status < 0 - error(error_codes[status]) - end - $(esc(ex)) - finally - stop_timer() - end - end -end - -#### -#### User-level functions -#### - -""" - init(; n::Integer, delay::Float64) - -Configure the `delay` between backtraces (measured in seconds), and the number `n` of -instruction pointers that may be stored. Each instruction pointer corresponds to a single -line of code; backtraces generally consist of a long list of instruction pointers. Default -settings can be obtained by calling this function with no arguments, and each can be set -independently using keywords or in the order `(n, delay)`. -""" -function init(; n::Union{Void,Integer} = nothing, delay::Union{Void,Float64} = nothing) - n_cur = ccall(:jl_profile_maxlen_data, Csize_t, ()) - delay_cur = ccall(:jl_profile_delay_nsec, UInt64, ())/10^9 - if n === nothing && delay === nothing - return Int(n_cur), delay_cur - end - nnew = (n === nothing) ? n_cur : n - delaynew = (delay === nothing) ? delay_cur : delay - init(nnew, delaynew) -end - -function init(n::Integer, delay::Float64) - status = ccall(:jl_profile_init, Cint, (Csize_t, UInt64), n, round(UInt64,10^9*delay)) - if status == -1 - error("could not allocate space for ", n, " instruction pointers") - end -end - -# init with default values -# Use a max size of 1M profile samples, and fire timer every 1ms -if is_windows() - __init__() = init(1_000_000, 0.01) -else - __init__() = init(1_000_000, 0.001) -end - -""" - clear() - -Clear any existing backtraces from the internal buffer. -""" -clear() = ccall(:jl_profile_clear_data, Void, ()) - -const LineInfoDict = Dict{UInt64, Vector{StackFrame}} -const LineInfoFlatDict = Dict{UInt64, StackFrame} - -struct ProfileFormat - maxdepth::Int - mincount::Int - noisefloor::Float64 - sortedby::Symbol - combine::Bool - C::Bool - function ProfileFormat(; - C = false, - combine = true, - maxdepth::Int = typemax(Int), - mincount::Int = 0, - noisefloor = 0, - sortedby::Symbol = :filefuncline) - return new(maxdepth, mincount, noisefloor, sortedby, combine, C) - end -end - -""" - print([io::IO = STDOUT,] [data::Vector]; kwargs...) - -Prints profiling results to `io` (by default, `STDOUT`). If you do not -supply a `data` vector, the internal buffer of accumulated backtraces -will be used. - -The keyword arguments can be any combination of: - - - `format` -- Determines whether backtraces are printed with (default, `:tree`) or without (`:flat`) - indentation indicating tree structure. - - - `C` -- If `true`, backtraces from C and Fortran code are shown (normally they are excluded). - - - `combine` -- If `true` (default), instruction pointers are merged that correspond to the same line of code. - - - `maxdepth` -- Limits the depth higher than `maxdepth` in the `:tree` format. - - - `sortedby` -- Controls the order in `:flat` format. `:filefuncline` (default) sorts by the source - line, whereas `:count` sorts in order of number of collected samples. - - - `noisefloor` -- Limits frames that exceed the heuristic noise floor of the sample (only applies to format `:tree`). - A suggested value to try for this is 2.0 (the default is 0). This parameter hides samples for which `n <= noisefloor * √N`, - where `n` is the number of samples on this line, and `N` is the number of samples for the callee. - - - `mincount` -- Limits the printout to only those lines with at least `mincount` occurrences. -""" -function print(io::IO, data::Vector{<:Unsigned} = fetch(), lidict::LineInfoDict = getdict(data); - format = :tree, - C = false, - combine = true, - maxdepth::Int = typemax(Int), - mincount::Int = 0, - noisefloor = 0, - sortedby::Symbol = :filefuncline) - print(io, data, lidict, ProfileFormat(C = C, - combine = combine, - maxdepth = maxdepth, - mincount = mincount, - noisefloor = noisefloor, - sortedby = sortedby), - format) -end - -function print(io::IO, data::Vector{<:Unsigned}, lidict::LineInfoDict, fmt::ProfileFormat, format::Symbol) - cols::Int = Base.displaysize(io)[2] - if format == :tree - tree(io, data, lidict, cols, fmt) - elseif format == :flat - flat(io, data, lidict, cols, fmt) - else - throw(ArgumentError("output format $(repr(format)) not recognized")) - end -end - -""" - print([io::IO = STDOUT,] data::Vector, lidict::LineInfoDict; kwargs...) - -Prints profiling results to `io`. This variant is used to examine results exported by a -previous call to [`retrieve`](@ref). Supply the vector `data` of backtraces and -a dictionary `lidict` of line information. - -See `Profile.print([io], data)` for an explanation of the valid keyword arguments. -""" -print(data::Vector{<:Unsigned} = fetch(), lidict::LineInfoDict = getdict(data); kwargs...) = - print(STDOUT, data, lidict; kwargs...) - -""" - retrieve() -> data, lidict - -"Exports" profiling results in a portable format, returning the set of all backtraces -(`data`) and a dictionary that maps the (session-specific) instruction pointers in `data` to -`LineInfo` values that store the file name, function name, and line number. This function -allows you to save profiling results for future analysis. -""" -function retrieve() - data = fetch() - return (copy(data), getdict(data)) -end - -function getdict(data::Vector{UInt}) - uip = unique(data) - return LineInfoDict(UInt64(ip)=>lookup(ip) for ip in uip) -end - -""" - flatten(btdata, lidict) -> (newdata::Vector{UInt64}, newdict::LineInfoFlatDict) - -Produces "flattened" backtrace data. Individual instruction pointers -sometimes correspond to a multi-frame backtrace due to inlining; in -such cases, this function inserts fake instruction pointers for the -inlined calls, and returns a dictionary that is a 1-to-1 mapping -between instruction pointers and a single StackFrame. -""" -function flatten(data::Vector, lidict::LineInfoDict) - # Makes fake instruction pointers, counting down from typemax(UInt) - newip = typemax(UInt64) - 1 - taken = Set(keys(lidict)) # make sure we don't pick one that's already used - newdict = Dict{UInt64,StackFrame}() - newmap = Dict{UInt64,Vector{UInt64}}() - for (ip, trace) in lidict - if length(trace) == 1 - newdict[ip] = trace[1] - else - newm = UInt64[] - for sf in trace - while newip ∈ taken && newip > 0 - newip -= 1 - end - newip == 0 && error("all possible instruction pointers used") - push!(newm, newip) - newdict[newip] = sf - newip -= 1 - end - newmap[ip] = newm - end - end - newdata = UInt64[] - for ip in data - local ip::UInt64 - if haskey(newmap, ip) - append!(newdata, newmap[ip]) - else - push!(newdata, ip) - end - end - return (newdata, newdict) -end - -""" - callers(funcname, [data, lidict], [filename=<filename>], [linerange=<start:stop>]) -> Vector{Tuple{count, lineinfo}} - -Given a previous profiling run, determine who called a particular function. Supplying the -filename (and optionally, range of line numbers over which the function is defined) allows -you to disambiguate an overloaded method. The returned value is a vector containing a count -of the number of calls and line information about the caller. One can optionally supply -backtrace `data` obtained from [`retrieve`](@ref); otherwise, the current internal -profile buffer is used. -""" -function callers end - -function callers(funcname::String, bt::Vector, lidict::LineInfoDict; filename = nothing, linerange = nothing) - if filename === nothing && linerange === nothing - return callersf(li -> li.func == funcname, bt, lidict) - end - filename === nothing && throw(ArgumentError("if supplying linerange, you must also supply the filename")) - if linerange === nothing - return callersf(li -> li.func == funcname && li.file == filename, bt, lidict) - else - return callersf(li -> li.func == funcname && li.file == filename && - in(li.line, linerange), bt, lidict) - end -end - -callers(funcname::String; kwargs...) = callers(funcname, retrieve()...; kwargs...) -callers(func::Function, bt::Vector, lidict::LineInfoDict; kwargs...) = - callers(string(func), bt, lidict; kwargs...) -callers(func::Function; kwargs...) = callers(string(func), retrieve()...; kwargs...) - -## -## For --track-allocation -## -# Reset the malloc log. Used to avoid counting memory allocated during -# compilation. - -""" - clear_malloc_data() - -Clears any stored memory allocation data when running julia with `--track-allocation`. -Execute the command(s) you want to test (to force JIT-compilation), then call -[`clear_malloc_data`](@ref). Then execute your command(s) again, quit -Julia, and examine the resulting `*.mem` files. -""" -clear_malloc_data() = ccall(:jl_clear_malloc_data, Void, ()) - -# C wrappers -start_timer() = ccall(:jl_profile_start_timer, Cint, ()) - -stop_timer() = ccall(:jl_profile_stop_timer, Void, ()) - -is_running() = ccall(:jl_profile_is_running, Cint, ())!=0 - -get_data_pointer() = convert(Ptr{UInt}, ccall(:jl_profile_get_data, Ptr{UInt8}, ())) - -len_data() = convert(Int, ccall(:jl_profile_len_data, Csize_t, ())) - -maxlen_data() = convert(Int, ccall(:jl_profile_maxlen_data, Csize_t, ())) - -error_codes = Dict( - -1=>"cannot specify signal action for profiling", - -2=>"cannot create the timer for profiling", - -3=>"cannot start the timer for profiling", - -4=>"cannot unblock SIGUSR1") - - -""" - fetch() -> data - -Returns a reference to the internal buffer of backtraces. Note that subsequent operations, -like [`clear`](@ref), can affect `data` unless you first make a copy. Note that the -values in `data` have meaning only on this machine in the current session, because it -depends on the exact memory addresses used in JIT-compiling. This function is primarily for -internal use; [`retrieve`](@ref) may be a better choice for most users. -""" -function fetch() - len = len_data() - maxlen = maxlen_data() - if (len == maxlen) - warn("""The profile data buffer is full; profiling probably terminated - before your program finished. To profile for longer runs, call Profile.init - with a larger buffer and/or larger delay.""") - end - return unsafe_wrap(Array, get_data_pointer(), (len,)) -end - - -# Number of backtrace "steps" that are triggered by taking the backtrace, e.g., inside profile_bt -# TODO: may be platform-specific? -const btskip = 0 - -## Print as a flat list -# Counts the number of times each line appears, at any nesting level -function count_flat(data::Vector{T}) where T<:Unsigned - linecount = Dict{T,Int}() - toskip = btskip - for ip in data - if toskip > 0 - toskip -= 1 - continue - end - if ip == 0 - toskip = btskip - continue - end - linecount[ip] = get(linecount, ip, 0)+1 - end - iplist = Vector{T}(0) - n = Vector{Int}(0) - for (k,v) in linecount - push!(iplist, k) - push!(n, v) - end - return (iplist, n) -end - -function parse_flat(iplist, n, lidict::LineInfoFlatDict, C::Bool) - # Convert instruction pointers to names & line numbers - lilist = [lidict[ip] for ip in iplist] - # Keep only the interpretable ones - # The ones with no line number might appear multiple times in a single - # backtrace, giving the wrong impression about the total number of backtraces. - # Delete them too. - keep = .!Bool[x == UNKNOWN || x.line == 0 || (x.from_c && !C) for x in lilist] - n = n[keep] - lilist = lilist[keep] - return (lilist, n) -end - -function flat(io::IO, data::Vector, lidict::LineInfoFlatDict, cols::Int, fmt::ProfileFormat) - if !fmt.C - data = purgeC(data, lidict) - end - iplist, n = count_flat(data) - if isempty(n) - warning_empty() - return - end - lilist, n = parse_flat(iplist, n, lidict, fmt.C) - print_flat(io, lilist, n, cols, fmt) - nothing -end - -function flat(io::IO, data::Vector, lidict::LineInfoDict, cols::Int, fmt::ProfileFormat) - newdata, newdict = flatten(data, lidict) - flat(io, newdata, newdict, cols, fmt) - nothing -end - -function print_flat(io::IO, lilist::Vector{StackFrame}, n::Vector{Int}, - cols::Int, fmt::ProfileFormat) - p = liperm(lilist) - lilist = lilist[p] - n = n[p] - if fmt.combine - j = 1 - for i = 2:length(lilist) - if lilist[i] == lilist[j] - n[j] += n[i] - n[i] = 0 - else - j = i - end - end - keep = n .> 0 - n = n[keep] - lilist = lilist[keep] - end - if fmt.sortedby == :count - p = sortperm(n) - n = n[p] - lilist = lilist[p] - end - wcounts = max(6, ndigits(maximum(n))) - maxline = 0 - maxfile = 6 - maxfunc = 10 - for li in lilist - maxline = max(maxline, li.line) - maxfile = max(maxfile, length(string(li.file))) - maxfunc = max(maxfunc, length(string(li.func))) - end - wline = max(5, ndigits(maxline)) - ntext = cols - wcounts - wline - 3 - maxfunc += 25 - if maxfile + maxfunc <= ntext - wfile = maxfile - wfunc = maxfunc - else - wfile = floor(Integer, 2*ntext/5) - wfunc = floor(Integer, 3*ntext/5) - end - println(io, lpad("Count", wcounts, " "), " ", rpad("File", wfile, " "), " ", - lpad("Line", wline, " "), " ", rpad("Function", wfunc, " ")) - for i = 1:length(n) - n[i] < fmt.mincount && continue - li = lilist[i] - Base.print(io, lpad(string(n[i]), wcounts, " "), " ") - Base.print(io, rpad(rtruncto(string(li.file), wfile), wfile, " "), " ") - Base.print(io, lpad(string(li.line), wline, " "), " ") - fname = string(li.func) - if !li.from_c && !isnull(li.linfo) - fname = sprint(show_spec_linfo, li) - end - Base.print(io, rpad(ltruncto(fname, wfunc), wfunc, " ")) - println(io) - end - nothing -end - -## A tree representation -# Identify and counts repetitions of all unique backtraces -function tree_aggregate(data::Vector{UInt64}) - iz = find(iszero, data) # find the breaks between backtraces - treecount = Dict{Vector{UInt64},Int}() - istart = 1 + btskip - for iend in iz - tmp = data[iend - 1 : -1 : istart] - treecount[tmp] = get(treecount, tmp, 0) + 1 - istart = iend + 1 + btskip - end - bt = Vector{Vector{UInt64}}(0) - counts = Vector{Int}(0) - for (k, v) in treecount - if !isempty(k) - push!(bt, k) - push!(counts, v) - end - end - return (bt, counts) -end - -tree_format_linewidth(x::StackFrame) = ndigits(x.line) + 6 - -function tree_format(lilist::Vector{StackFrame}, counts::Vector{Int}, level::Int, cols::Int) - nindent = min(cols>>1, level) - ndigcounts = ndigits(maximum(counts)) - ndigline = maximum([tree_format_linewidth(x) for x in lilist]) - ntext = cols - nindent - ndigcounts - ndigline - 5 - widthfile = floor(Integer, 0.4ntext) - widthfunc = floor(Integer, 0.6ntext) - strs = Vector{String}(length(lilist)) - showextra = false - if level > nindent - nextra = level - nindent - nindent -= ndigits(nextra) + 2 - showextra = true - end - for i = 1:length(lilist) - li = lilist[i] - if li != UNKNOWN - base = " "^nindent - if showextra - base = string(base, "+", nextra, " ") - end - if li.line == li.pointer - strs[i] = string(base, - rpad(string(counts[i]), ndigcounts, " "), - " ", - "unknown function (pointer: 0x", - hex(li.pointer,2*sizeof(Ptr{Void})), - ")") - else - fname = string(li.func) - if !li.from_c && !isnull(li.linfo) - fname = sprint(show_spec_linfo, li) - end - strs[i] = string(base, - rpad(string(counts[i]), ndigcounts, " "), - " ", - rtruncto(string(li.file), widthfile), - ":", - li.line == -1 ? "?" : string(li.line), - "; ", - ltruncto(fname, widthfunc)) - end - else - strs[i] = "" - end - end - return strs -end - -# Print a "branch" starting at a particular level. This gets called recursively. -function tree(io::IO, bt::Vector{Vector{UInt64}}, counts::Vector{Int}, - lidict::LineInfoFlatDict, level::Int, cols::Int, fmt::ProfileFormat, noisefloor::Int) - if level > fmt.maxdepth - return - end - # Organize backtraces into groups that are identical up to this level - if fmt.combine - # Combine based on the line information - d = Dict{StackFrame,Vector{Int}}() - for i = 1:length(bt) - ip = bt[i][level + 1] - key = lidict[ip] - indx = Base.ht_keyindex(d, key) - if haskey(d, key) - push!(d[key], i) - else - d[key] = [i] - end - end - # Generate counts - dlen = length(d) - lilist = Vector{StackFrame}(dlen) - group = Vector{Vector{Int}}(dlen) - n = Vector{Int}(dlen) - i = 1 - for (key, v) in d - lilist[i] = key - group[i] = v - n[i] = sum(counts[v]) - i += 1 - end - else - # Combine based on the instruction pointer - d = Dict{UInt64,Vector{Int}}() - for i = 1:length(bt) - key = bt[i][level+1] - if haskey(d, key) - push!(d[key], i) - else - d[key] = [i] - end - end - # Generate counts, and do the code lookup - dlen = length(d) - lilist = Vector{StackFrame}(dlen) - group = Vector{Vector{Int}}(dlen) - n = Vector{Int}(dlen) - i = 1 - for (key, v) in d - lilist[i] = lidict[key] - group[i] = v - n[i] = sum(counts[v]) - i += 1 - end - end - # Order the line information - if length(lilist) > 1 - p = liperm(lilist) - lilist = lilist[p] - group = group[p] - n = n[p] - end - # Generate the string for each line - strs = tree_format(lilist, n, level, cols) - # Recurse to the next level - len = Int[length(x) for x in bt] - for i = 1:length(lilist) - n[i] < fmt.mincount && continue - n[i] < noisefloor && continue - if !isempty(strs[i]) - println(io, strs[i]) - end - idx = group[i] - keep = len[idx] .> level+1 - if any(keep) - idx = idx[keep] - tree(io, bt[idx], counts[idx], lidict, level + 1, cols, fmt, fmt.noisefloor > 0 ? floor(Int, fmt.noisefloor * sqrt(n[i])) : 0) - end - end - nothing -end - -function tree(io::IO, data::Vector{UInt64}, lidict::LineInfoFlatDict, cols::Int, fmt::ProfileFormat) - if !fmt.C - data = purgeC(data, lidict) - end - bt, counts = tree_aggregate(data) - if isempty(counts) - warning_empty() - return - end - level = 0 - len = Int[length(x) for x in bt] - keep = len .> 0 - tree(io, bt[keep], counts[keep], lidict, level, cols, fmt, 0) - nothing -end - -function tree(io::IO, data::Vector, lidict::LineInfoDict, cols::Int, fmt::ProfileFormat) - newdata, newdict = flatten(data, lidict) - tree(io, newdata, newdict, cols, fmt) - nothing -end - -function callersf(matchfunc::Function, bt::Vector, lidict::LineInfoDict) - counts = Dict{StackFrame, Int}() - lastmatched = false - for id in bt - if id == 0 - lastmatched = false - continue - end - li = lidict[id] - if lastmatched - if haskey(counts, li) - counts[li] += 1 - else - counts[li] = 1 - end - end - lastmatched = matchfunc(li) - end - k = collect(keys(counts)) - v = collect(values(counts)) - p = sortperm(v, rev=true) - return [(v[i], k[i]) for i in p] -end - -# Utilities -function rtruncto(str::String, w::Int) - if length(str) <= w - return str - else - return string("...", str[end-w+4:end]) - end -end -function ltruncto(str::String, w::Int) - if length(str) <= w - return str - else - return string(str[1:w-4], "...") - end -end - - -truncto(str::Symbol, w::Int) = truncto(string(str), w) - -# Order alphabetically (file, function) and then by line number -function liperm(lilist::Vector{StackFrame}) - comb = Vector{String}(length(lilist)) - for i = 1:length(lilist) - li = lilist[i] - if li != UNKNOWN - comb[i] = @sprintf("%s:%s:%06d", li.file, li.func, li.line) - else - comb[i] = "zzz" - end - end - return sortperm(comb) -end - -warning_empty() = warn(""" - There were no samples collected. Run your program longer (perhaps by - running it multiple times), or adjust the delay between samples with - Profile.init().""") - -function purgeC(data::Vector{UInt64}, lidict::LineInfoFlatDict) - keep = Bool[d == 0 || lidict[d].from_c == false for d in data] - return data[keep] -end - -end # module diff --git a/julia-0.6.3/share/julia/base/promotion.jl b/julia-0.6.3/share/julia/base/promotion.jl deleted file mode 100644 index 2972a7d..0000000 --- a/julia-0.6.3/share/julia/base/promotion.jl +++ /dev/null @@ -1,362 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -## type join (closest common ancestor, or least upper bound) ## - -typejoin() = (@_pure_meta; Bottom) -typejoin(t::ANY) = (@_pure_meta; t) -typejoin(t::ANY, ts...) = (@_pure_meta; typejoin(t, typejoin(ts...))) -function typejoin(a::ANY, b::ANY) - @_pure_meta - if a <: b - return b - elseif b <: a - return a - elseif isa(a,UnionAll) - return UnionAll(a.var, typejoin(a.body, b)) - elseif isa(b,UnionAll) - return UnionAll(b.var, typejoin(a, b.body)) - elseif isa(a,TypeVar) - return typejoin(a.ub, b) - elseif isa(b,TypeVar) - return typejoin(a, b.ub) - elseif isa(a,Union) - return typejoin(typejoin(a.a,a.b), b) - elseif isa(b,Union) - return typejoin(a, typejoin(b.a,b.b)) - elseif a <: Tuple - if !(b <: Tuple) - return Any - end - ap, bp = a.parameters, b.parameters - lar = length(ap)::Int; lbr = length(bp)::Int - laf, afixed = full_va_len(ap) - lbf, bfixed = full_va_len(bp) - if lar==0 || lbr==0 - return Tuple - end - if laf < lbf - if isvarargtype(ap[lar]) && !afixed - c = Vector{Any}(laf) - c[laf] = Vararg{typejoin(unwrapva(ap[lar]), tailjoin(bp,laf))} - n = laf-1 - else - c = Vector{Any}(laf+1) - c[laf+1] = Vararg{tailjoin(bp,laf+1)} - n = laf - end - elseif lbf < laf - if isvarargtype(bp[lbr]) && !bfixed - c = Vector{Any}(lbf) - c[lbf] = Vararg{typejoin(unwrapva(bp[lbr]), tailjoin(ap,lbf))} - n = lbf-1 - else - c = Vector{Any}(lbf+1) - c[lbf+1] = Vararg{tailjoin(ap,lbf+1)} - n = lbf - end - else - c = Vector{Any}(laf) - n = laf - end - for i = 1:n - ai = ap[min(i,lar)]; bi = bp[min(i,lbr)] - ci = typejoin(unwrapva(ai),unwrapva(bi)) - c[i] = i == length(c) && (isvarargtype(ai) || isvarargtype(bi)) ? Vararg{ci} : ci - end - return Tuple{c...} - elseif b <: Tuple - return Any - end - while b !== Any - if a <: b.name.wrapper - while a.name !== b.name - a = supertype(a) - end - aprimary = unwrap_unionall(a.name.wrapper) - # join on parameters - n = length(a.parameters) - if n == 0 - return aprimary - end - p = Vector{Any}(n) - for i = 1:n - ai, bi = a.parameters[i], b.parameters[i] - if ai === bi || (isa(ai,Type) && isa(bi,Type) && typeseq(ai,bi)) - p[i] = ai - else - p[i] = aprimary.parameters[i] - end - end - return rewrap_unionall(a.name.wrapper{p...}, a.name.wrapper) - end - b = supertype(b) - end - return Any -end - -# Returns length, isfixed -function full_va_len(p) - isempty(p) && return 0, true - last = p[end] - if isvarargtype(last) - N = unwrap_unionall(last).parameters[2] - if isa(N, Integer) - return (length(p) + N - 1)::Int, true - end - return length(p)::Int, false - end - return length(p)::Int, true -end - -# reduce typejoin over A[i:end] -function tailjoin(A, i) - if i > length(A) - return unwrapva(A[end]) - end - t = Bottom - for j = i:length(A) - t = typejoin(t, unwrapva(A[j])) - end - return t -end - -## promotion mechanism ## - -promote_type() = Bottom -promote_type(T) = T -promote_type(T, S, U, V...) = (@_inline_meta; promote_type(T, promote_type(S, U, V...))) - -promote_type(::Type{Bottom}, ::Type{Bottom}) = Bottom -promote_type(::Type{T}, ::Type{T}) where {T} = T -promote_type(::Type{T}, ::Type{Bottom}) where {T} = T -promote_type(::Type{Bottom}, ::Type{T}) where {T} = T - -""" - promote_type(type1, type2) - -Determine a type big enough to hold values of each argument type without loss, whenever -possible. In some cases, where no type exists to which both types can be promoted -losslessly, some loss is tolerated; for example, `promote_type(Int64, Float64)` returns -[`Float64`](@ref) even though strictly, not all [`Int64`](@ref) values can be represented -exactly as `Float64` values. - -```jldoctest -julia> promote_type(Int64, Float64) -Float64 - -julia> promote_type(Int32, Int64) -Int64 - -julia> promote_type(Float32, BigInt) -BigFloat -``` -""" -function promote_type(::Type{T}, ::Type{S}) where {T,S} - @_inline_meta - # Try promote_rule in both orders. Typically only one is defined, - # and there is a fallback returning Bottom below, so the common case is - # promote_type(T, S) => - # promote_result(T, S, result, Bottom) => - # typejoin(result, Bottom) => result - promote_result(T, S, promote_rule(T,S), promote_rule(S,T)) -end - -promote_rule(::Type{<:Any}, ::Type{<:Any}) = Bottom - -promote_result(::Type{<:Any},::Type{<:Any},::Type{T},::Type{S}) where {T,S} = (@_inline_meta; promote_type(T,S)) -# If no promote_rule is defined, both directions give Bottom. In that -# case use typejoin on the original types instead. -promote_result(::Type{T},::Type{S},::Type{Bottom},::Type{Bottom}) where {T,S} = (@_inline_meta; typejoin(T, S)) - -promote() = () -promote(x) = (x,) -function promote(x::T, y::S) where {T,S} - @_inline_meta - (convert(promote_type(T,S),x), convert(promote_type(T,S),y)) -end -promote_typeof(x) = typeof(x) -promote_typeof(x, xs...) = (@_inline_meta; promote_type(typeof(x), promote_typeof(xs...))) -function promote(x, y, z) - @_inline_meta - (convert(promote_typeof(x,y,z), x), - convert(promote_typeof(x,y,z), y), - convert(promote_typeof(x,y,z), z)) -end -function promote(x, y, zs...) - @_inline_meta - (convert(promote_typeof(x,y,zs...), x), - convert(promote_typeof(x,y,zs...), y), - convert(Tuple{Vararg{promote_typeof(x,y,zs...)}}, zs)...) -end -# TODO: promote{T}(x::T, ys::T...) here to catch all circularities? - -## promotions in arithmetic, etc. ## - -# Because of the promoting fallback definitions for Number, we need -# a special case for undefined promote_rule on numeric types. -# Otherwise, typejoin(T,S) is called (returning Number) so no conversion -# happens, and +(promote(x,y)...) is called again, causing a stack -# overflow. -function promote_result(::Type{T},::Type{S},::Type{Bottom},::Type{Bottom}) where {T<:Number,S<:Number} - @_inline_meta - promote_to_supertype(T, S, typejoin(T,S)) -end - -# promote numeric types T and S to typejoin(T,S) if T<:S or S<:T -# for example this makes promote_type(Integer,Real) == Real without -# promoting arbitrary pairs of numeric types to Number. -promote_to_supertype(::Type{T}, ::Type{T}, ::Type{T}) where {T<:Number} = (@_inline_meta; T) -promote_to_supertype(::Type{T}, ::Type{S}, ::Type{T}) where {T<:Number,S<:Number} = (@_inline_meta; T) -promote_to_supertype(::Type{T}, ::Type{S}, ::Type{S}) where {T<:Number,S<:Number} = (@_inline_meta; S) -promote_to_supertype(::Type{T}, ::Type{S}, ::Type) where {T<:Number,S<:Number} = - error("no promotion exists for ", T, " and ", S) - -# promotion with a check for circularity. Can be used to catch what -# would otherwise become StackOverflowErrors. -function promote_noncircular(x, y) - @_inline_meta - px, py = promote(x, y) - not_all_sametype((x,px), (y,py)) - px, py -end -function promote_noncircular(x, y, z) - @_inline_meta - px, py, pz = promote(x, y, z) - not_all_sametype((x,px), (y,py), (z,pz)) - px, py, pz -end -function promote_noncircular(x, y, z, a...) - p = promote(x, y, z, a...) - not_all_sametype(map(identity, (x, y, z, a...), p)) - p -end -not_all_sametype(x, y) = nothing -not_all_sametype(x, y, z) = nothing -not_all_sametype(x::Tuple{S,S}, y::Tuple{T,T}) where {S,T} = sametype_error(x[1], y[1]) -not_all_sametype(x::Tuple{R,R}, y::Tuple{S,S}, z::Tuple{T,T}) where {R,S,T} = sametype_error(x[1], y[1], z[1]) -function not_all_sametype(::Tuple{R,R}, y::Tuple{S,S}, z::Tuple{T,T}, args...) where {R,S,T} - @_inline_meta - not_all_sametype(y, z, args...) -end -not_all_sametype() = error("promotion failed to change any input types") -function sametype_error(input...) - @_noinline_meta - error("circular method definition: promotion of types ", - join(map(x->string(typeof(x)), input), ", ", " and "), - " failed to change any input types") -end - -+(x::Number, y::Number) = +(promote(x,y)...) -*(x::Number, y::Number) = *(promote(x,y)...) --(x::Number, y::Number) = -(promote(x,y)...) -/(x::Number, y::Number) = /(promote(x,y)...) - -""" - ^(x, y) - -Exponentiation operator. If `x` is a matrix, computes matrix exponentiation. - -If `y` is an `Int` literal (e.g. `2` in `x^2` or `-3` in `x^-3`), the Julia code -`x^y` is transformed by the compiler to `Base.literal_pow(^, x, Val{y})`, to -enable compile-time specialization on the value of the exponent. -(As a default fallback we have `Base.literal_pow(^, x, Val{y}) = ^(x,y)`, -where usually `^ == Base.^` unless `^` has been defined in the calling -namespace.) - -```jldoctest -julia> 3^5 -243 - -julia> A = [1 2; 3 4] -2×2 Array{Int64,2}: - 1 2 - 3 4 - -julia> A^3 -2×2 Array{Int64,2}: - 37 54 - 81 118 -``` -""" -^(x::Number, y::Number) = ^(promote(x,y)...) - -fma(x::Number, y::Number, z::Number) = fma(promote(x,y,z)...) -muladd(x::Number, y::Number, z::Number) = muladd(promote(x,y,z)...) - -(&)(x::Integer, y::Integer) = (&)(promote(x,y)...) -(|)(x::Integer, y::Integer) = (|)(promote(x,y)...) -xor(x::Integer, y::Integer) = xor(promote(x,y)...) - -==(x::Number, y::Number) = (==)(promote(x,y)...) -<( x::Real, y::Real) = (< )(promote(x,y)...) -<=(x::Real, y::Real) = (<=)(promote(x,y)...) - -div(x::Real, y::Real) = div(promote(x,y)...) -fld(x::Real, y::Real) = fld(promote(x,y)...) -cld(x::Real, y::Real) = cld(promote(x,y)...) -rem(x::Real, y::Real) = rem(promote(x,y)...) -mod(x::Real, y::Real) = mod(promote(x,y)...) - -mod1(x::Real, y::Real) = mod1(promote(x,y)...) -fld1(x::Real, y::Real) = fld1(promote(x,y)...) - -max(x::Real, y::Real) = max(promote(x,y)...) -min(x::Real, y::Real) = min(promote(x,y)...) -minmax(x::Real, y::Real) = minmax(promote(x, y)...) - -# "Promotion" that takes a function into account and tries to preserve -# non-concrete types. These are meant to be used mainly by elementwise -# operations, so it is advised against overriding them -_default_type(T::Type) = (@_inline_meta; T) - -if isdefined(Core, :Inference) - const _return_type = Core.Inference.return_type -else - _return_type(f::ANY, t::ANY) = Any -end - -promote_op(::Any...) = (@_inline_meta; Any) -function promote_op{S}(f, ::Type{S}) - @_inline_meta - T = _return_type(f, Tuple{_default_type(S)}) - isleaftype(S) && return isleaftype(T) ? T : Any - return typejoin(S, T) -end -function promote_op{R,S}(f, ::Type{R}, ::Type{S}) - @_inline_meta - T = _return_type(f, Tuple{_default_type(R), _default_type(S)}) - isleaftype(R) && isleaftype(S) && return isleaftype(T) ? T : Any - return typejoin(R, S, T) -end - -## catch-alls to prevent infinite recursion when definitions are missing ## - -no_op_err(name, T) = error(name," not defined for ",T) -(+)(x::T, y::T) where {T<:Number} = no_op_err("+", T) -(*)(x::T, y::T) where {T<:Number} = no_op_err("*", T) -(-)(x::T, y::T) where {T<:Number} = no_op_err("-", T) -(/)(x::T, y::T) where {T<:Number} = no_op_err("/", T) -(^)(x::T, y::T) where {T<:Number} = no_op_err("^", T) - -fma(x::T, y::T, z::T) where {T<:Number} = no_op_err("fma", T) -fma(x::Integer, y::Integer, z::Integer) = x*y+z -muladd(x::T, y::T, z::T) where {T<:Number} = x*y+z - -(&)(x::T, y::T) where {T<:Integer} = no_op_err("&", T) -(|)(x::T, y::T) where {T<:Integer} = no_op_err("|", T) -xor(x::T, y::T) where {T<:Integer} = no_op_err("xor", T) - -(==)(x::T, y::T) where {T<:Number} = x === y -(< )(x::T, y::T) where {T<:Real} = no_op_err("<" , T) -(<=)(x::T, y::T) where {T<:Real} = no_op_err("<=", T) - -rem(x::T, y::T) where {T<:Real} = no_op_err("rem", T) -mod(x::T, y::T) where {T<:Real} = no_op_err("mod", T) - -min(x::Real) = x -max(x::Real) = x -minmax(x::Real) = (x, x) - -max(x::T, y::T) where {T<:Real} = select_value(y < x, x, y) -min(x::T, y::T) where {T<:Real} = select_value(y < x, y, x) -minmax(x::T, y::T) where {T<:Real} = y < x ? (y, x) : (x, y) diff --git a/julia-0.6.3/share/julia/base/random.jl b/julia-0.6.3/share/julia/base/random.jl deleted file mode 100644 index 80c2763..0000000 --- a/julia-0.6.3/share/julia/base/random.jl +++ /dev/null @@ -1,1744 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -module Random - -using Base.dSFMT -using Base.GMP: GMP_VERSION, Limb -import Base: copymutable, copy, copy!, == - -export srand, - rand, rand!, - randn, randn!, - randexp, randexp!, - bitrand, - randstring, - randsubseq,randsubseq!, - shuffle,shuffle!, - randperm, randcycle, - AbstractRNG, MersenneTwister, RandomDevice, - GLOBAL_RNG, randjump - - -abstract type AbstractRNG end - -abstract type FloatInterval end -mutable struct CloseOpen <: FloatInterval end -mutable struct Close1Open2 <: FloatInterval end - - -## RandomDevice - -if is_windows() - - struct RandomDevice <: AbstractRNG - buffer::Vector{UInt128} - - RandomDevice() = new(Vector{UInt128}(1)) - end - - function rand{T<:Union{Bool, Base.BitInteger}}(rd::RandomDevice, ::Type{T}) - win32_SystemFunction036!(rd.buffer) - @inbounds return rd.buffer[1] % T - end - - rand!(rd::RandomDevice, A::Array{<:Union{Bool, Base.BitInteger}}) = (win32_SystemFunction036!(A); A) -else # !windows - struct RandomDevice <: AbstractRNG - file::IOStream - unlimited::Bool - - RandomDevice(unlimited::Bool=true) = new(open(unlimited ? "/dev/urandom" : "/dev/random"), unlimited) - end - - rand{T<:Union{Bool, Base.BitInteger}}(rd::RandomDevice, ::Type{T}) = read( rd.file, T) - rand!(rd::RandomDevice, A::Array{<:Union{Bool, Base.BitInteger}}) = read!(rd.file, A) -end # os-test - - -""" - RandomDevice() - -Create a `RandomDevice` RNG object. Two such objects will always generate different streams of random numbers. -""" -RandomDevice - - -rand(rng::RandomDevice, ::Type{Close1Open2}) = - reinterpret(Float64, 0x3ff0000000000000 | rand(rng, UInt64) & 0x000fffffffffffff) - -rand(rng::RandomDevice, ::Type{CloseOpen}) = rand(rng, Close1Open2) - 1.0 - - -## MersenneTwister - -const MTCacheLength = dsfmt_get_min_array_size() - -mutable struct MersenneTwister <: AbstractRNG - seed::Vector{UInt32} - state::DSFMT_state - vals::Vector{Float64} - idx::Int - - function MersenneTwister(seed, state, vals, idx) - length(vals) == MTCacheLength && 0 <= idx <= MTCacheLength || throw(DomainError()) - new(seed, state, vals, idx) - end -end - -MersenneTwister(seed::Vector{UInt32}, state::DSFMT_state) = - MersenneTwister(seed, state, zeros(Float64, MTCacheLength), MTCacheLength) - -""" - MersenneTwister(seed) - -Create a `MersenneTwister` RNG object. Different RNG objects can have their own seeds, which -may be useful for generating different streams of random numbers. - -# Example -```jldoctest -julia> rng = MersenneTwister(1234); -``` -""" -MersenneTwister(seed) = srand(MersenneTwister(Vector{UInt32}(), DSFMT_state()), seed) - -function copy!(dst::MersenneTwister, src::MersenneTwister) - copy!(resize!(dst.seed, length(src.seed)), src.seed) - copy!(dst.state, src.state) - copy!(dst.vals, src.vals) - dst.idx = src.idx - dst -end - -copy(src::MersenneTwister) = - MersenneTwister(copy(src.seed), copy(src.state), copy(src.vals), src.idx) - -==(r1::MersenneTwister, r2::MersenneTwister) = - r1.seed == r2.seed && r1.state == r2.state && isequal(r1.vals, r2.vals) && r1.idx == r2.idx - - -## Low level API for MersenneTwister - -@inline mt_avail(r::MersenneTwister) = MTCacheLength - r.idx -@inline mt_empty(r::MersenneTwister) = r.idx == MTCacheLength -@inline mt_setfull!(r::MersenneTwister) = r.idx = 0 -@inline mt_setempty!(r::MersenneTwister) = r.idx = MTCacheLength -@inline mt_pop!(r::MersenneTwister) = @inbounds return r.vals[r.idx+=1] - -function gen_rand(r::MersenneTwister) - dsfmt_fill_array_close1_open2!(r.state, pointer(r.vals), length(r.vals)) - mt_setfull!(r) -end - -@inline reserve_1(r::MersenneTwister) = mt_empty(r) && gen_rand(r) -# `reserve` allows one to call `rand_inbounds` n times -# precondition: n <= MTCacheLength -@inline reserve(r::MersenneTwister, n::Int) = mt_avail(r) < n && gen_rand(r) - -# precondition: !mt_empty(r) -@inline rand_inbounds(r::MersenneTwister, ::Type{Close1Open2}) = mt_pop!(r) -@inline rand_inbounds(r::MersenneTwister, ::Type{CloseOpen}) = rand_inbounds(r, Close1Open2) - 1.0 -@inline rand_inbounds(r::MersenneTwister) = rand_inbounds(r, CloseOpen) - -# produce Float64 values -@inline rand{I<:FloatInterval}(r::MersenneTwister, ::Type{I}) = (reserve_1(r); rand_inbounds(r, I)) - -@inline rand_ui52_raw_inbounds(r::MersenneTwister) = reinterpret(UInt64, rand_inbounds(r, Close1Open2)) -@inline rand_ui52_raw(r::MersenneTwister) = (reserve_1(r); rand_ui52_raw_inbounds(r)) -@inline rand_ui2x52_raw(r::MersenneTwister) = rand_ui52_raw(r) % UInt128 << 64 | rand_ui52_raw(r) - -function srand(r::MersenneTwister, seed::Vector{UInt32}) - copy!(resize!(r.seed, length(seed)), seed) - dsfmt_init_by_array(r.state, r.seed) - mt_setempty!(r) - return r -end - -# MersenneTwister jump - -""" - randjump(r::MersenneTwister, jumps::Integer, [jumppoly::AbstractString=dSFMT.JPOLY1e21]) -> Vector{MersenneTwister} - -Create an array of the size `jumps` of initialized `MersenneTwister` RNG objects. The -first RNG object given as a parameter and following `MersenneTwister` RNGs in the array are -initialized such that a state of the RNG object in the array would be moved forward (without -generating numbers) from a previous RNG object array element on a particular number of steps -encoded by the jump polynomial `jumppoly`. - -Default jump polynomial moves forward `MersenneTwister` RNG state by `10^20` steps. -""" -function randjump(mt::MersenneTwister, jumps::Integer, jumppoly::AbstractString) - mts = MersenneTwister[] - push!(mts, mt) - for i in 1:jumps-1 - cmt = mts[end] - push!(mts, MersenneTwister(cmt.seed, dSFMT.dsfmt_jump(cmt.state, jumppoly))) - end - return mts -end -randjump(r::MersenneTwister, jumps::Integer) = randjump(r, jumps, dSFMT.JPOLY1e21) - -## initialization - -function __init__() - try - srand() - catch ex - Base.showerror_nostdio(ex, - "WARNING: Error during initialization of module Random") - end -end - - -## make_seed() -# make_seed methods produce values of type Array{UInt32}, suitable for MersenneTwister seeding - -function make_seed() - try - return rand(RandomDevice(), UInt32, 4) - catch - println(STDERR, "Entropy pool not available to seed RNG; using ad-hoc entropy sources.") - seed = reinterpret(UInt64, time()) - seed = hash(seed, UInt64(getpid())) - try - seed = hash(seed, parse(UInt64, readstring(pipeline(`ifconfig`, `sha1sum`))[1:40], 16)) - end - return make_seed(seed) - end -end - -function make_seed(n::Integer) - n < 0 && throw(DomainError()) - seed = UInt32[] - while true - push!(seed, n & 0xffffffff) - n >>= 32 - if n == 0 - return seed - end - end -end - -function make_seed(filename::AbstractString, n::Integer) - read!(filename, Vector{UInt32}(Int(n))) -end - -## srand() - -""" - srand([rng=GLOBAL_RNG], [seed]) -> rng - srand([rng=GLOBAL_RNG], filename, n=4) -> rng - -Reseed the random number generator. If a `seed` is provided, the RNG will give a -reproducible sequence of numbers, otherwise Julia will get entropy from the system. For -`MersenneTwister`, the `seed` may be a non-negative integer, a vector of [`UInt32`](@ref) integers -or a filename, in which case the seed is read from a file (`4n` bytes are read from the file, -where `n` is an optional argument). `RandomDevice` does not support seeding. -""" -srand(r::MersenneTwister) = srand(r, make_seed()) -srand(r::MersenneTwister, n::Integer) = srand(r, make_seed(n)) -srand(r::MersenneTwister, filename::AbstractString, n::Integer=4) = srand(r, make_seed(filename, n)) - - -function dsfmt_gv_srand() - # Temporary fix for #8874 and #9124: update global RNG for Rmath - dsfmt_gv_init_by_array(GLOBAL_RNG.seed+UInt32(1)) - return GLOBAL_RNG -end - -function srand() - srand(GLOBAL_RNG) - dsfmt_gv_srand() -end - -function srand(seed::Union{Integer, Vector{UInt32}}) - srand(GLOBAL_RNG, seed) - dsfmt_gv_srand() -end - -function srand(filename::AbstractString, n::Integer=4) - srand(GLOBAL_RNG, filename, n) - dsfmt_gv_srand() -end - -## Global RNG - -const GLOBAL_RNG = MersenneTwister(0) -globalRNG() = GLOBAL_RNG - -# rand: a non-specified RNG defaults to GLOBAL_RNG - -""" - rand([rng=GLOBAL_RNG], [S], [dims...]) - -Pick a random element or array of random elements from the set of values specified by `S`; `S` can be - -* an indexable collection (for example `1:n` or `['x','y','z']`), or -* a type: the set of values to pick from is then equivalent to `typemin(S):typemax(S)` for - integers (this is not applicable to [`BigInt`](@ref)), and to ``[0, 1)`` for floating - point numbers; - -`S` defaults to [`Float64`](@ref). -""" -@inline rand() = rand(GLOBAL_RNG, CloseOpen) -@inline rand(T::Type) = rand(GLOBAL_RNG, T) -rand(dims::Dims) = rand(GLOBAL_RNG, dims) -rand(dims::Integer...) = rand(convert(Tuple{Vararg{Int}}, dims)) -rand(T::Type, dims::Dims) = rand(GLOBAL_RNG, T, dims) -rand(T::Type, d1::Integer, dims::Integer...) = rand(T, tuple(Int(d1), convert(Tuple{Vararg{Int}}, dims)...)) -rand!(A::AbstractArray) = rand!(GLOBAL_RNG, A) - -rand(r::AbstractArray) = rand(GLOBAL_RNG, r) - -""" - rand!([rng=GLOBAL_RNG], A, [coll]) - -Populate the array `A` with random values. If the indexable collection `coll` is specified, -the values are picked randomly from `coll`. This is equivalent to `copy!(A, rand(rng, coll, size(A)))` -or `copy!(A, rand(rng, eltype(A), size(A)))` but without allocating a new array. - -# Example - -```jldoctest -julia> rng = MersenneTwister(1234); - -julia> rand!(rng, zeros(5)) -5-element Array{Float64,1}: - 0.590845 - 0.766797 - 0.566237 - 0.460085 - 0.794026 -``` -""" -rand!(A::AbstractArray, r::AbstractArray) = rand!(GLOBAL_RNG, A, r) - -rand(r::AbstractArray, dims::Dims) = rand(GLOBAL_RNG, r, dims) -rand(r::AbstractArray, dims::Integer...) = rand(GLOBAL_RNG, r, convert(Tuple{Vararg{Int}}, dims)) - -## random floating point values - -@inline rand(r::AbstractRNG) = rand(r, CloseOpen) - -# MersenneTwister & RandomDevice -@inline rand(r::Union{RandomDevice,MersenneTwister}, ::Type{Float64}) = rand(r, CloseOpen) - -rand_ui10_raw(r::MersenneTwister) = rand_ui52_raw(r) -rand_ui23_raw(r::MersenneTwister) = rand_ui52_raw(r) -rand_ui10_raw(r::AbstractRNG) = rand(r, UInt16) -rand_ui23_raw(r::AbstractRNG) = rand(r, UInt32) - -rand(r::Union{RandomDevice,MersenneTwister}, ::Type{Float16}) = - Float16(reinterpret(Float32, (rand_ui10_raw(r) % UInt32 << 13) & 0x007fe000 | 0x3f800000) - 1) - -rand(r::Union{RandomDevice,MersenneTwister}, ::Type{Float32}) = - reinterpret(Float32, rand_ui23_raw(r) % UInt32 & 0x007fffff | 0x3f800000) - 1 - - -## random integers - -@inline rand_ui52_raw(r::AbstractRNG) = reinterpret(UInt64, rand(r, Close1Open2)) -@inline rand_ui52(r::AbstractRNG) = rand_ui52_raw(r) & 0x000fffffffffffff - -# MersenneTwister - -@inline rand{T<:Union{Bool, Int8, UInt8, Int16, UInt16, Int32, UInt32}}(r::MersenneTwister, ::Type{T}) = rand_ui52_raw(r) % T - -function rand(r::MersenneTwister, ::Type{UInt64}) - reserve(r, 2) - rand_ui52_raw_inbounds(r) << 32 ⊻ rand_ui52_raw_inbounds(r) -end - -function rand(r::MersenneTwister, ::Type{UInt128}) - reserve(r, 3) - xor(rand_ui52_raw_inbounds(r) % UInt128 << 96, - rand_ui52_raw_inbounds(r) % UInt128 << 48, - rand_ui52_raw_inbounds(r)) -end - -rand(r::MersenneTwister, ::Type{Int64}) = reinterpret(Int64, rand(r, UInt64)) -rand(r::MersenneTwister, ::Type{Int128}) = reinterpret(Int128, rand(r, UInt128)) - -## random Complex values - -rand{T<:Real}(r::AbstractRNG, ::Type{Complex{T}}) = complex(rand(r, T), rand(r, T)) - -# random Char values -# returns a random valid Unicode scalar value (i.e. 0 - 0xd7ff, 0xe000 - # 0x10ffff) -function rand(r::AbstractRNG, ::Type{Char}) - c = rand(r, 0x00000000:0x0010f7ff) - (c < 0xd800) ? Char(c) : Char(c+0x800) -end - -# random values from Dict or Set (for efficiency) -function rand(r::AbstractRNG, t::Dict) - isempty(t) && throw(ArgumentError("dict must be non-empty")) - n = length(t.slots) - while true - i = rand(r, 1:n) - Base.isslotfilled(t, i) && return (t.keys[i] => t.vals[i]) - end -end -rand(t::Dict) = rand(GLOBAL_RNG, t) -rand(r::AbstractRNG, s::Set) = rand(r, s.dict).first -rand(s::Set) = rand(GLOBAL_RNG, s) - -## Arrays of random numbers - -rand(r::AbstractRNG, dims::Dims) = rand(r, Float64, dims) -rand(r::AbstractRNG, dims::Integer...) = rand(r, convert(Tuple{Vararg{Int}}, dims)) - -rand(r::AbstractRNG, T::Type, dims::Dims) = rand!(r, Array{T}(dims)) -rand(r::AbstractRNG, T::Type, d1::Integer, dims::Integer...) = rand(r, T, tuple(Int(d1), convert(Tuple{Vararg{Int}}, dims)...)) -# note: the above method would trigger an ambiguity warning if d1 was not separated out: -# rand(r, ()) would match both this method and rand(r, dims::Dims) -# moreover, a call like rand(r, NotImplementedType()) would be an infinite loop - -function rand!{T}(r::AbstractRNG, A::AbstractArray{T}) - for i in eachindex(A) - @inbounds A[i] = rand(r, T) - end - A -end - -# MersenneTwister - -function rand_AbstractArray_Float64!{I<:FloatInterval}(r::MersenneTwister, A::AbstractArray{Float64}, n=length(A), ::Type{I}=CloseOpen) - # what follows is equivalent to this simple loop but more efficient: - # for i=1:n - # @inbounds A[i] = rand(r, I) - # end - m = 0 - while m < n - s = mt_avail(r) - if s == 0 - gen_rand(r) - s = mt_avail(r) - end - m2 = min(n, m+s) - for i=m+1:m2 - @inbounds A[i] = rand_inbounds(r, I) - end - m = m2 - end - A -end - -rand!(r::MersenneTwister, A::AbstractArray{Float64}) = rand_AbstractArray_Float64!(r, A) - -fill_array!(s::DSFMT_state, A::Ptr{Float64}, n::Int, ::Type{CloseOpen}) = dsfmt_fill_array_close_open!(s, A, n) -fill_array!(s::DSFMT_state, A::Ptr{Float64}, n::Int, ::Type{Close1Open2}) = dsfmt_fill_array_close1_open2!(s, A, n) - -function rand!{I<:FloatInterval}(r::MersenneTwister, A::Array{Float64}, n::Int=length(A), ::Type{I}=CloseOpen) - # depending on the alignment of A, the data written by fill_array! may have - # to be left-shifted by up to 15 bytes (cf. unsafe_copy! below) for - # reproducibility purposes; - # so, even for well aligned arrays, fill_array! is used to generate only - # the n-2 first values (or n-3 if n is odd), and the remaining values are - # generated by the scalar version of rand - if n > length(A) - throw(BoundsError(A,n)) - end - n2 = (n-2) ÷ 2 * 2 - if n2 < dsfmt_get_min_array_size() - rand_AbstractArray_Float64!(r, A, n, I) - else - pA = pointer(A) - align = Csize_t(pA) % 16 - if align > 0 - pA2 = pA + 16 - align - fill_array!(r.state, pA2, n2, I) # generate the data in-place, but shifted - unsafe_copy!(pA, pA2, n2) # move the data to the beginning of the array - else - fill_array!(r.state, pA, n2, I) - end - for i=n2+1:n - @inbounds A[i] = rand(r, I) - end - end - A -end - -@inline mask128(u::UInt128, ::Type{Float16}) = (u & 0x03ff03ff03ff03ff03ff03ff03ff03ff) | 0x3c003c003c003c003c003c003c003c00 -@inline mask128(u::UInt128, ::Type{Float32}) = (u & 0x007fffff007fffff007fffff007fffff) | 0x3f8000003f8000003f8000003f800000 - -function rand!{T<:Union{Float16, Float32}}(r::MersenneTwister, A::Array{T}, ::Type{Close1Open2}) - n = length(A) - n128 = n * sizeof(T) ÷ 16 - rand!(r, unsafe_wrap(Array, convert(Ptr{Float64}, pointer(A)), 2*n128), 2*n128, Close1Open2) - A128 = unsafe_wrap(Array, convert(Ptr{UInt128}, pointer(A)), n128) - @inbounds for i in 1:n128 - u = A128[i] - u ⊻= u << 26 - # at this point, the 64 low bits of u, "k" being the k-th bit of A128[i] and "+" the bit xor, are: - # [..., 58+32,..., 53+27, 52+26, ..., 33+7, 32+6, ..., 27+1, 26, ..., 1] - # the bits needing to be random are - # [1:10, 17:26, 33:42, 49:58] (for Float16) - # [1:23, 33:55] (for Float32) - # this is obviously satisfied on the 32 low bits side, and on the high side, the entropy comes - # from bits 33:52 of A128[i] and then from bits 27:32 (which are discarded on the low side) - # this is similar for the 64 high bits of u - A128[i] = mask128(u, T) - end - for i in 16*n128÷sizeof(T)+1:n - @inbounds A[i] = rand(r, T) + oneunit(T) - end - A -end - -function rand!{T<:Union{Float16, Float32}}(r::MersenneTwister, A::Array{T}, ::Type{CloseOpen}) - rand!(r, A, Close1Open2) - I32 = one(Float32) - for i in eachindex(A) - @inbounds A[i] = T(Float32(A[i])-I32) # faster than "A[i] -= one(T)" for T==Float16 - end - A -end - -rand!(r::MersenneTwister, A::Array{<:Union{Float16, Float32}}) = rand!(r, A, CloseOpen) - - -function rand!(r::MersenneTwister, A::Array{UInt128}, n::Int=length(A)) - if n > length(A) - throw(BoundsError(A,n)) - end - Af = unsafe_wrap(Array, convert(Ptr{Float64}, pointer(A)), 2n) - i = n - while true - rand!(r, Af, 2i, Close1Open2) - n < 5 && break - i = 0 - @inbounds while n-i >= 5 - u = A[i+=1] - A[n] ⊻= u << 48 - A[n-=1] ⊻= u << 36 - A[n-=1] ⊻= u << 24 - A[n-=1] ⊻= u << 12 - n-=1 - end - end - if n > 0 - u = rand_ui2x52_raw(r) - for i = 1:n - @inbounds A[i] ⊻= u << 12*i - end - end - A -end - -function rand!{T<:Union{Int8, UInt8, Int16, UInt16, Int32, UInt32, Int64, UInt64, Int128}}(r::MersenneTwister, A::Array{T}) - n=length(A) - n128 = n * sizeof(T) ÷ 16 - rand!(r, unsafe_wrap(Array, convert(Ptr{UInt128}, pointer(A)), n128)) - for i = 16*n128÷sizeof(T)+1:n - @inbounds A[i] = rand(r, T) - end - A -end - -## Generate random integer within a range - -# remainder function according to Knuth, where rem_knuth(a, 0) = a -rem_knuth(a::UInt, b::UInt) = a % (b + (b == 0)) + a * (b == 0) -rem_knuth(a::T, b::T) where {T<:Unsigned} = b != 0 ? a % b : a - -# maximum multiple of k <= 2^bits(T) decremented by one, -# that is 0xFFFF...FFFF if k = typemax(T) - typemin(T) with intentional underflow -# see http://stackoverflow.com/questions/29182036/integer-arithmetic-add-1-to-uint-max-and-divide-by-n-without-overflow -maxmultiple(k::T) where {T<:Unsigned} = (div(typemax(T) - k + oneunit(k), k + (k == 0))*k + k - oneunit(k))::T - -# maximum multiple of k within 1:2^32 or 1:2^64 decremented by one, depending on size -maxmultiplemix(k::UInt64) = if k >> 32 != 0; maxmultiple(k); else (div(0x0000000100000000, k + (k == 0))*k - oneunit(k))::UInt64; end - -abstract type RangeGenerator end - -struct RangeGeneratorInt{T<:Integer,U<:Unsigned} <: RangeGenerator - a::T # first element of the range - k::U # range length or zero for full range - u::U # rejection threshold -end -# generators with 32, 128 bits entropy -RangeGeneratorInt(a::T, k::U) where {T,U<:Union{UInt32,UInt128}} = RangeGeneratorInt{T,U}(a, k, maxmultiple(k)) -# mixed 32/64 bits entropy generator -RangeGeneratorInt(a::T, k::UInt64) where {T} = RangeGeneratorInt{T,UInt64}(a, k, maxmultiplemix(k)) -# generator for ranges -function RangeGenerator(r::UnitRange{T}) where T<:Unsigned - if isempty(r) - throw(ArgumentError("range must be non-empty")) - end - RangeGeneratorInt(first(r), last(r) - first(r) + oneunit(T)) -end - -# specialized versions -for (T, U) in [(UInt8, UInt32), (UInt16, UInt32), - (Int8, UInt32), (Int16, UInt32), (Int32, UInt32), (Int64, UInt64), (Int128, UInt128), - (Bool, UInt32)] - - @eval RangeGenerator(r::UnitRange{$T}) = begin - if isempty(r) - throw(ArgumentError("range must be non-empty")) - end - RangeGeneratorInt(first(r), convert($U, unsigned(last(r) - first(r)) + one($U))) # overflow ok - end -end - -if GMP_VERSION.major >= 6 - struct RangeGeneratorBigInt <: RangeGenerator - a::BigInt # first - m::BigInt # range length - 1 - nlimbs::Int # number of limbs in generated BigInt's - mask::Limb # applied to the highest limb - end - -else - struct RangeGeneratorBigInt <: RangeGenerator - a::BigInt # first - m::BigInt # range length - 1 - limbs::Vector{Limb} # buffer to be copied into generated BigInt's - mask::Limb # applied to the highest limb - - RangeGeneratorBigInt(a, m, nlimbs, mask) = new(a, m, Vector{Limb}(nlimbs), mask) - end -end - - -function RangeGenerator(r::UnitRange{BigInt}) - m = last(r) - first(r) - m < 0 && throw(ArgumentError("range must be non-empty")) - nd = ndigits(m, 2) - nlimbs, highbits = divrem(nd, 8*sizeof(Limb)) - highbits > 0 && (nlimbs += 1) - mask = highbits == 0 ? ~zero(Limb) : one(Limb)<<highbits - one(Limb) - return RangeGeneratorBigInt(first(r), m, nlimbs, mask) -end - - -# this function uses 32 bit entropy for small ranges of length <= typemax(UInt32) + 1 -# RangeGeneratorInt is responsible for providing the right value of k -function rand{T<:Union{UInt64, Int64}}(rng::AbstractRNG, g::RangeGeneratorInt{T,UInt64}) - local x::UInt64 - if (g.k - 1) >> 32 == 0 - x = rand(rng, UInt32) - while x > g.u - x = rand(rng, UInt32) - end - else - x = rand(rng, UInt64) - while x > g.u - x = rand(rng, UInt64) - end - end - return reinterpret(T, reinterpret(UInt64, g.a) + rem_knuth(x, g.k)) -end - -function rand{T<:Integer, U<:Unsigned}(rng::AbstractRNG, g::RangeGeneratorInt{T,U}) - x = rand(rng, U) - while x > g.u - x = rand(rng, U) - end - (unsigned(g.a) + rem_knuth(x, g.k)) % T -end - -if GMP_VERSION.major >= 6 - # mpz_limbs_write and mpz_limbs_finish are available only in GMP version 6 - function rand(rng::AbstractRNG, g::RangeGeneratorBigInt) - x = BigInt() - while true - # note: on CRAY computers, the second argument may be of type Cint (48 bits) and not Clong - xd = ccall((:__gmpz_limbs_write, :libgmp), Ptr{Limb}, (Ptr{BigInt}, Clong), &x, g.nlimbs) - limbs = unsafe_wrap(Array, xd, g.nlimbs) - rand!(rng, limbs) - limbs[end] &= g.mask - ccall((:__gmpz_limbs_finish, :libgmp), Void, (Ptr{BigInt}, Clong), &x, g.nlimbs) - x <= g.m && break - end - ccall((:__gmpz_add, :libgmp), Void, (Ptr{BigInt}, Ptr{BigInt}, Ptr{BigInt}), &x, &x, &g.a) - return x - end -else - function rand(rng::AbstractRNG, g::RangeGeneratorBigInt) - x = BigInt() - while true - rand!(rng, g.limbs) - g.limbs[end] &= g.mask - ccall((:__gmpz_import, :libgmp), Void, - (Ptr{BigInt}, Csize_t, Cint, Csize_t, Cint, Csize_t, Ptr{Limb}), - &x, length(g.limbs), -1, sizeof(Limb), 0, 0, g.limbs) - x <= g.m && break - end - ccall((:__gmpz_add, :libgmp), Void, (Ptr{BigInt}, Ptr{BigInt}, Ptr{BigInt}), &x, &x, &g.a) - return x - end -end - -rand(rng::AbstractRNG, r::UnitRange{<:Union{Signed,Unsigned,BigInt,Bool}}) = rand(rng, RangeGenerator(r)) - - -# Randomly draw a sample from an AbstractArray r -# (e.g. r is a range 0:2:8 or a vector [2, 3, 5, 7]) -rand(rng::AbstractRNG, r::AbstractArray) = @inbounds return r[rand(rng, 1:length(r))] - -function rand!(rng::AbstractRNG, A::AbstractArray, g::RangeGenerator) - for i in eachindex(A) - @inbounds A[i] = rand(rng, g) - end - return A -end - -rand!(rng::AbstractRNG, A::AbstractArray, r::UnitRange{<:Union{Signed,Unsigned,BigInt,Bool,Char}}) = rand!(rng, A, RangeGenerator(r)) - -function rand!(rng::AbstractRNG, A::AbstractArray, r::AbstractArray) - g = RangeGenerator(1:(length(r))) - for i in eachindex(A) - @inbounds A[i] = r[rand(rng, g)] - end - return A -end - -rand{T}(rng::AbstractRNG, r::AbstractArray{T}, dims::Dims) = rand!(rng, Array{T}(dims), r) -rand(rng::AbstractRNG, r::AbstractArray, dims::Int...) = rand(rng, r, dims) - -## random BitArrays (AbstractRNG) - -function rand!(rng::AbstractRNG, B::BitArray) - isempty(B) && return B - Bc = B.chunks - rand!(rng, Bc) - Bc[end] &= Base._msk_end(B) - return B -end - -""" - bitrand([rng=GLOBAL_RNG], [dims...]) - -Generate a `BitArray` of random boolean values. - -# Example - -```jldoctest -julia> rng = MersenneTwister(1234); - -julia> bitrand(rng, 10) -10-element BitArray{1}: - true - true - true - false - true - false - false - true - false - true -``` -""" -bitrand(r::AbstractRNG, dims::Dims) = rand!(r, BitArray(dims)) -bitrand(r::AbstractRNG, dims::Int...) = rand!(r, BitArray(dims)) - -bitrand(dims::Dims) = rand!(BitArray(dims)) -bitrand(dims::Int...) = rand!(BitArray(dims)) - -## randn() - Normally distributed random numbers using Ziggurat algorithm - -# The Ziggurat Method for generating random variables - Marsaglia and Tsang -# Paper and reference code: http://www.jstatsoft.org/v05/i08/ - -# randmtzig (covers also exponential variates) -## Tables for normal variates -const ki = - UInt64[0x0007799ec012f7b2,0x0000000000000000,0x0006045f4c7de363,0x0006d1aa7d5ec0a5, - 0x000728fb3f60f777,0x0007592af4e9fbc0,0x000777a5c0bf655d,0x00078ca3857d2256, - 0x00079bf6b0ffe58b,0x0007a7a34ab092ad,0x0007b0d2f20dd1cb,0x0007b83d3aa9cb52, - 0x0007be597614224d,0x0007c3788631abe9,0x0007c7d32bc192ee,0x0007cb9263a6e86d, - 0x0007ced483edfa84,0x0007d1b07ac0fd39,0x0007d437ef2da5fc,0x0007d678b069aa6e, - 0x0007d87db38c5c87,0x0007da4fc6a9ba62,0x0007dbf611b37f3b,0x0007dd7674d0f286, - 0x0007ded5ce8205f6,0x0007e018307fb62b,0x0007e141081bd124,0x0007e2533d712de8, - 0x0007e3514bbd7718,0x0007e43d54944b52,0x0007e5192f25ef42,0x0007e5e67481118d, - 0x0007e6a6897c1ce2,0x0007e75aa6c7f64c,0x0007e803df8ee498,0x0007e8a326eb6272, - 0x0007e93954717a28,0x0007e9c727f8648f,0x0007ea4d4cc85a3c,0x0007eacc5c4907a9, - 0x0007eb44e0474cf6,0x0007ebb754e47419,0x0007ec242a3d8474,0x0007ec8bc5d69645, - 0x0007ecee83d3d6e9,0x0007ed4cb8082f45,0x0007eda6aee0170f,0x0007edfcae2dfe68, - 0x0007ee4ef5dccd3e,0x0007ee9dc08c394e,0x0007eee9441a17c7,0x0007ef31b21b4fb1, - 0x0007ef773846a8a7,0x0007efba00d35a17,0x0007effa32ccf69f,0x0007f037f25e1278, - 0x0007f0736112d12c,0x0007f0ac9e145c25,0x0007f0e3c65e1fcc,0x0007f118f4ed8e54, - 0x0007f14c42ed0dc8,0x0007f17dc7daa0c3,0x0007f1ad99aac6a5,0x0007f1dbcce80015, - 0x0007f20874cf56bf,0x0007f233a36a3b9a,0x0007f25d69a604ad,0x0007f285d7694a92, - 0x0007f2acfba75e3b,0x0007f2d2e4720909,0x0007f2f79f09c344,0x0007f31b37ec883b, - 0x0007f33dbae36abc,0x0007f35f330f08d5,0x0007f37faaf2fa79,0x0007f39f2c805380, - 0x0007f3bdc11f4f1c,0x0007f3db71b83850,0x0007f3f846bba121,0x0007f4144829f846, - 0x0007f42f7d9a8b9d,0x0007f449ee420432,0x0007f463a0f8675e,0x0007f47c9c3ea77b, - 0x0007f494e643cd8e,0x0007f4ac84e9c475,0x0007f4c37dc9cd50,0x0007f4d9d638a432, - 0x0007f4ef934a5b6a,0x0007f504b9d5f33d,0x0007f5194e78b352,0x0007f52d55994a96, - 0x0007f540d36aba0c,0x0007f553cbef0e77,0x0007f56642f9ec8f,0x0007f5783c32f31e, - 0x0007f589bb17f609,0x0007f59ac2ff1525,0x0007f5ab5718b15a,0x0007f5bb7a71427c, - 0x0007f5cb2ff31009,0x0007f5da7a67cebe,0x0007f5e95c7a24e7,0x0007f5f7d8b7171e, - 0x0007f605f18f5ef4,0x0007f613a958ad0a,0x0007f621024ed7e9,0x0007f62dfe94f8cb, - 0x0007f63aa036777a,0x0007f646e928065a,0x0007f652db488f88,0x0007f65e786213ff, - 0x0007f669c22a7d8a,0x0007f674ba446459,0x0007f67f623fc8db,0x0007f689bb9ac294, - 0x0007f693c7c22481,0x0007f69d881217a6,0x0007f6a6fdd6ac36,0x0007f6b02a4c61ee, - 0x0007f6b90ea0a7f4,0x0007f6c1abf254c0,0x0007f6ca03521664,0x0007f6d215c2db82, - 0x0007f6d9e43a3559,0x0007f6e16fa0b329,0x0007f6e8b8d23729,0x0007f6efc09e4569, - 0x0007f6f687c84cbf,0x0007f6fd0f07ea09,0x0007f703570925e2,0x0007f709606cad03, - 0x0007f70f2bc8036f,0x0007f714b9a5b292,0x0007f71a0a85725d,0x0007f71f1edc4d9e, - 0x0007f723f714c179,0x0007f728938ed843,0x0007f72cf4a03fa0,0x0007f7311a945a16, - 0x0007f73505ac4bf8,0x0007f738b61f03bd,0x0007f73c2c193dc0,0x0007f73f67bd835c, - 0x0007f74269242559,0x0007f745305b31a1,0x0007f747bd666428,0x0007f74a103f12ed, - 0x0007f74c28d414f5,0x0007f74e0709a42d,0x0007f74faab939f9,0x0007f75113b16657, - 0x0007f75241b5a155,0x0007f753347e16b8,0x0007f753ebb76b7c,0x0007f75467027d05, - 0x0007f754a5f4199d,0x0007f754a814b207,0x0007f7546ce003ae,0x0007f753f3c4bb29, - 0x0007f7533c240e92,0x0007f75245514f41,0x0007f7510e91726c,0x0007f74f971a9012, - 0x0007f74dde135797,0x0007f74be2927971,0x0007f749a39e051c,0x0007f747202aba8a, - 0x0007f744571b4e3c,0x0007f741473f9efe,0x0007f73def53dc43,0x0007f73a4dff9bff, - 0x0007f73661d4deaf,0x0007f732294f003f,0x0007f72da2d19444,0x0007f728cca72bda, - 0x0007f723a5000367,0x0007f71e29f09627,0x0007f7185970156b,0x0007f7123156c102, - 0x0007f70baf5c1e2c,0x0007f704d1150a23,0x0007f6fd93f1a4e5,0x0007f6f5f53b10b6, - 0x0007f6edf211023e,0x0007f6e587671ce9,0x0007f6dcb2021679,0x0007f6d36e749c64, - 0x0007f6c9b91bf4c6,0x0007f6bf8e1c541b,0x0007f6b4e95ce015,0x0007f6a9c68356ff, - 0x0007f69e20ef5211,0x0007f691f3b517eb,0x0007f6853997f321,0x0007f677ed03ff19, - 0x0007f66a08075bdc,0x0007f65b844ab75a,0x0007f64c5b091860,0x0007f63c8506d4bc, - 0x0007f62bfa8798fe,0x0007f61ab34364b0,0x0007f608a65a599a,0x0007f5f5ca4737e8, - 0x0007f5e214d05b48,0x0007f5cd7af7066e,0x0007f5b7f0e4c2a1,0x0007f5a169d68fcf, - 0x0007f589d80596a5,0x0007f5712c8d0174,0x0007f557574c912b,0x0007f53c46c77193, - 0x0007f51fe7feb9f2,0x0007f5022646ecfb,0x0007f4e2eb17ab1d,0x0007f4c21dd4a3d1, - 0x0007f49fa38ea394,0x0007f47b5ebb62eb,0x0007f4552ee27473,0x0007f42cf03d58f5, - 0x0007f4027b48549f,0x0007f3d5a44119df,0x0007f3a63a8fb552,0x0007f37408155100, - 0x0007f33ed05b55ec,0x0007f3064f9c183e,0x0007f2ca399c7ba1,0x0007f28a384bb940, - 0x0007f245ea1b7a2b,0x0007f1fcdffe8f1b,0x0007f1ae9af758cd,0x0007f15a8917f27e, - 0x0007f10001ccaaab,0x0007f09e413c418a,0x0007f034627733d7,0x0007efc15815b8d5, - 0x0007ef43e2bf7f55,0x0007eeba84e31dfe,0x0007ee237294df89,0x0007ed7c7c170141, - 0x0007ecc2f0d95d3a,0x0007ebf377a46782,0x0007eb09d6deb285,0x0007ea00a4f17808, - 0x0007e8d0d3da63d6,0x0007e771023b0fcf,0x0007e5d46c2f08d8,0x0007e3e937669691, - 0x0007e195978f1176,0x0007deb2c0e05c1c,0x0007db0362002a19,0x0007d6202c151439, - 0x0007cf4b8f00a2cb,0x0007c4fd24520efd,0x0007b362fbf81816,0x00078d2d25998e24] -const wi = - [1.7367254121602630e-15,9.5586603514556339e-17,1.2708704834810623e-16, - 1.4909740962495474e-16,1.6658733631586268e-16,1.8136120810119029e-16, - 1.9429720153135588e-16,2.0589500628482093e-16,2.1646860576895422e-16, - 2.2622940392218116e-16,2.3532718914045892e-16,2.4387234557428771e-16, - 2.5194879829274225e-16,2.5962199772528103e-16,2.6694407473648285e-16, - 2.7395729685142446e-16,2.8069646002484804e-16,2.8719058904113930e-16, - 2.9346417484728883e-16,2.9953809336782113e-16,3.0543030007192440e-16, - 3.1115636338921572e-16,3.1672988018581815e-16,3.2216280350549905e-16, - 3.2746570407939751e-16,3.3264798116841710e-16,3.3771803417353232e-16, - 3.4268340353119356e-16,3.4755088731729758e-16,3.5232663846002031e-16, - 3.5701624633953494e-16,3.6162480571598339e-16,3.6615697529653540e-16, - 3.7061702777236077e-16,3.7500889278747798e-16,3.7933619401549554e-16, - 3.8360228129677279e-16,3.8781025861250247e-16,3.9196300853257678e-16, - 3.9606321366256378e-16,4.0011337552546690e-16,4.0411583124143332e-16, - 4.0807276830960448e-16,4.1198623774807442e-16,4.1585816580828064e-16, - 4.1969036444740733e-16,4.2348454071520708e-16,4.2724230518899761e-16, - 4.3096517957162941e-16,4.3465460355128760e-16,4.3831194100854571e-16, - 4.4193848564470665e-16,4.4553546609579137e-16,4.4910405058828750e-16, - 4.5264535118571397e-16,4.5616042766900381e-16,4.5965029108849407e-16, - 4.6311590702081647e-16,4.6655819856008752e-16,4.6997804906941950e-16, - 4.7337630471583237e-16,4.7675377680908526e-16,4.8011124396270155e-16, - 4.8344945409350080e-16,4.8676912627422087e-16,4.9007095245229938e-16, - 4.9335559904654139e-16,4.9662370843221783e-16,4.9987590032409088e-16, - 5.0311277306593187e-16,5.0633490483427195e-16,5.0954285476338923e-16, - 5.1273716399787966e-16,5.1591835667857364e-16,5.1908694086703434e-16, - 5.2224340941340417e-16,5.2538824077194543e-16,5.2852189976823820e-16, - 5.3164483832166176e-16,5.3475749612647295e-16,5.3786030129452348e-16, - 5.4095367096239933e-16,5.4403801186554671e-16,5.4711372088173611e-16, - 5.5018118554603362e-16,5.5324078453927836e-16,5.5629288815190902e-16, - 5.5933785872484621e-16,5.6237605106900435e-16,5.6540781286489604e-16, - 5.6843348504368141e-16,5.7145340215092040e-16,5.7446789269419609e-16, - 5.7747727947569648e-16,5.8048187991076857e-16,5.8348200633338921e-16, - 5.8647796628943653e-16,5.8947006281858718e-16,5.9245859472561339e-16, - 5.9544385684180598e-16,5.9842614027720281e-16,6.0140573266426640e-16, - 6.0438291839361250e-16,6.0735797884236057e-16,6.1033119259564394e-16, - 6.1330283566179110e-16,6.1627318168165963e-16,6.1924250213258470e-16, - 6.2221106652737879e-16,6.2517914260879998e-16,6.2814699653988953e-16, - 6.3111489309056042e-16,6.3408309582080600e-16,6.3705186726088149e-16, - 6.4002146908880247e-16,6.4299216230548961e-16,6.4596420740788321e-16, - 6.4893786456033965e-16,6.5191339376461587e-16,6.5489105502874154e-16, - 6.5787110853507413e-16,6.6085381480782587e-16,6.6383943488035057e-16, - 6.6682823046247459e-16,6.6982046410815579e-16,6.7281639938375311e-16, - 6.7581630103719006e-16,6.7882043516829803e-16,6.8182906940062540e-16, - 6.8484247305500383e-16,6.8786091732516637e-16,6.9088467545571690e-16, - 6.9391402292275690e-16,6.9694923761748294e-16,6.9999060003307640e-16, - 7.0303839345521508e-16,7.0609290415654822e-16,7.0915442159548734e-16, - 7.1222323861967788e-16,7.1529965167453030e-16,7.1838396101720629e-16, - 7.2147647093647067e-16,7.2457748997883870e-16,7.2768733118146927e-16, - 7.3080631231227429e-16,7.3393475611774048e-16,7.3707299057898310e-16, - 7.4022134917657997e-16,7.4338017116476479e-16,7.4654980185558890e-16, - 7.4973059291369793e-16,7.5292290266240584e-16,7.5612709640179217e-16, - 7.5934354673958895e-16,7.6257263393567558e-16,7.6581474626104873e-16, - 7.6907028037219191e-16,7.7233964170182985e-16,7.7562324486711744e-16, - 7.7892151409638524e-16,7.8223488367564108e-16,7.8556379841610841e-16, - 7.8890871414417552e-16,7.9227009821522709e-16,7.9564843005293662e-16, - 7.9904420171571300e-16,8.0245791849212591e-16,8.0589009952726568e-16, - 8.0934127848215009e-16,8.1281200422845008e-16,8.1630284158098775e-16, - 8.1981437207065329e-16,8.2334719476060504e-16,8.2690192710884700e-16, - 8.3047920588053737e-16,8.3407968811366288e-16,8.3770405214202216e-16, - 8.4135299867980282e-16,8.4502725197240968e-16,8.4872756101861549e-16, - 8.5245470086955962e-16,8.5620947401062333e-16,8.5999271183276646e-16, - 8.6380527620052589e-16,8.6764806112455816e-16,8.7152199454736980e-16, - 8.7542804025171749e-16,8.7936719990210427e-16,8.8334051523084080e-16, - 8.8734907038131345e-16,8.9139399442240861e-16,8.9547646404950677e-16, - 8.9959770648910994e-16,9.0375900262601175e-16,9.0796169037400680e-16, - 9.1220716831348461e-16,9.1649689962191353e-16,9.2083241632623076e-16, - 9.2521532390956933e-16,9.2964730630864167e-16,9.3413013134252651e-16, - 9.3866565661866598e-16,9.4325583596767065e-16,9.4790272646517382e-16, - 9.5260849610662787e-16,9.5737543220974496e-16,9.6220595062948384e-16, - 9.6710260588230542e-16,9.7206810229016259e-16,9.7710530627072088e-16, - 9.8221725991905411e-16,9.8740719604806711e-16,9.9267855488079765e-16, - 9.9803500261836449e-16,1.0034804521436181e-15,1.0090190861637457e-15, - 1.0146553831467086e-15,1.0203941464683124e-15,1.0262405372613567e-15, - 1.0322001115486456e-15,1.0382788623515399e-15,1.0444832676000471e-15, - 1.0508203448355195e-15,1.0572977139009890e-15,1.0639236690676801e-15, - 1.0707072623632994e-15,1.0776584002668106e-15,1.0847879564403425e-15, - 1.0921079038149563e-15,1.0996314701785628e-15,1.1073733224935752e-15, - 1.1153497865853155e-15,1.1235791107110833e-15,1.1320817840164846e-15, - 1.1408809242582780e-15,1.1500027537839792e-15,1.1594771891449189e-15, - 1.1693385786910960e-15,1.1796266352955801e-15,1.1903876299282890e-15, - 1.2016759392543819e-15,1.2135560818666897e-15,1.2261054417450561e-15, - 1.2394179789163251e-15,1.2536093926602567e-15,1.2688244814255010e-15, - 1.2852479319096109e-15,1.3031206634689985e-15,1.3227655770195326e-15, - 1.3446300925011171e-15,1.3693606835128518e-15,1.3979436672775240e-15, - 1.4319989869661328e-15,1.4744848603597596e-15,1.5317872741611144e-15, - 1.6227698675312968e-15] -const fi = - [1.0000000000000000e+00,9.7710170126767082e-01,9.5987909180010600e-01, - 9.4519895344229909e-01,9.3206007595922991e-01,9.1999150503934646e-01, - 9.0872644005213032e-01,8.9809592189834297e-01,8.8798466075583282e-01, - 8.7830965580891684e-01,8.6900868803685649e-01,8.6003362119633109e-01, - 8.5134625845867751e-01,8.4291565311220373e-01,8.3471629298688299e-01, - 8.2672683394622093e-01,8.1892919160370192e-01,8.1130787431265572e-01, - 8.0384948317096383e-01,7.9654233042295841e-01,7.8937614356602404e-01, - 7.8234183265480195e-01,7.7543130498118662e-01,7.6863731579848571e-01, - 7.6195334683679483e-01,7.5537350650709567e-01,7.4889244721915638e-01, - 7.4250529634015061e-01,7.3620759812686210e-01,7.2999526456147568e-01, - 7.2386453346862967e-01,7.1781193263072152e-01,7.1183424887824798e-01, - 7.0592850133275376e-01,7.0009191813651117e-01,6.9432191612611627e-01, - 6.8861608300467136e-01,6.8297216164499430e-01,6.7738803621877308e-01, - 6.7186171989708166e-01,6.6639134390874977e-01,6.6097514777666277e-01, - 6.5561147057969693e-01,6.5029874311081637e-01,6.4503548082082196e-01, - 6.3982027745305614e-01,6.3465179928762327e-01,6.2952877992483625e-01, - 6.2445001554702606e-01,6.1941436060583399e-01,6.1442072388891344e-01, - 6.0946806492577310e-01,6.0455539069746733e-01,5.9968175261912482e-01, - 5.9484624376798689e-01,5.9004799633282545e-01,5.8528617926337090e-01, - 5.8055999610079034e-01,5.7586868297235316e-01,5.7121150673525267e-01, - 5.6658776325616389e-01,5.6199677581452390e-01,5.5743789361876550e-01, - 5.5291049042583185e-01,5.4841396325526537e-01,5.4394773119002582e-01, - 5.3951123425695158e-01,5.3510393238045717e-01,5.3072530440366150e-01, - 5.2637484717168403e-01,5.2205207467232140e-01,5.1775651722975591e-01, - 5.1348772074732651e-01,5.0924524599574761e-01,5.0502866794346790e-01, - 5.0083757512614835e-01,4.9667156905248933e-01,4.9253026364386815e-01, - 4.8841328470545758e-01,4.8432026942668288e-01,4.8025086590904642e-01, - 4.7620473271950547e-01,4.7218153846772976e-01,4.6818096140569321e-01, - 4.6420268904817391e-01,4.6024641781284248e-01,4.5631185267871610e-01, - 4.5239870686184824e-01,4.4850670150720273e-01,4.4463556539573912e-01, - 4.4078503466580377e-01,4.3695485254798533e-01,4.3314476911265209e-01, - 4.2935454102944126e-01,4.2558393133802180e-01,4.2183270922949573e-01, - 4.1810064983784795e-01,4.1438753404089090e-01,4.1069314827018799e-01, - 4.0701728432947315e-01,4.0335973922111429e-01,3.9972031498019700e-01, - 3.9609881851583223e-01,3.9249506145931540e-01,3.8890886001878855e-01, - 3.8534003484007706e-01,3.8178841087339344e-01,3.7825381724561896e-01, - 3.7473608713789086e-01,3.7123505766823922e-01,3.6775056977903225e-01, - 3.6428246812900372e-01,3.6083060098964775e-01,3.5739482014578022e-01, - 3.5397498080007656e-01,3.5057094148140588e-01,3.4718256395679348e-01, - 3.4380971314685055e-01,3.4045225704452164e-01,3.3711006663700588e-01, - 3.3378301583071823e-01,3.3047098137916342e-01,3.2717384281360129e-01, - 3.2389148237639104e-01,3.2062378495690530e-01,3.1737063802991350e-01, - 3.1413193159633707e-01,3.1090755812628634e-01,3.0769741250429189e-01, - 3.0450139197664983e-01,3.0131939610080288e-01,2.9815132669668531e-01, - 2.9499708779996164e-01,2.9185658561709499e-01,2.8872972848218270e-01, - 2.8561642681550159e-01,2.8251659308370741e-01,2.7943014176163772e-01, - 2.7635698929566810e-01,2.7329705406857691e-01,2.7025025636587519e-01, - 2.6721651834356114e-01,2.6419576399726080e-01,2.6118791913272082e-01, - 2.5819291133761890e-01,2.5521066995466168e-01,2.5224112605594190e-01, - 2.4928421241852824e-01,2.4633986350126363e-01,2.4340801542275012e-01, - 2.4048860594050039e-01,2.3758157443123795e-01,2.3468686187232990e-01, - 2.3180441082433859e-01,2.2893416541468023e-01,2.2607607132238020e-01, - 2.2323007576391746e-01,2.2039612748015194e-01,2.1757417672433113e-01, - 2.1476417525117358e-01,2.1196607630703015e-01,2.0917983462112499e-01, - 2.0640540639788071e-01,2.0364274931033485e-01,2.0089182249465656e-01, - 1.9815258654577511e-01,1.9542500351413428e-01,1.9270903690358912e-01, - 1.9000465167046496e-01,1.8731181422380025e-01,1.8463049242679927e-01, - 1.8196065559952254e-01,1.7930227452284767e-01,1.7665532144373500e-01, - 1.7401977008183875e-01,1.7139559563750595e-01,1.6878277480121151e-01, - 1.6618128576448205e-01,1.6359110823236570e-01,1.6101222343751107e-01, - 1.5844461415592431e-01,1.5588826472447920e-01,1.5334316106026283e-01, - 1.5080929068184568e-01,1.4828664273257453e-01,1.4577520800599403e-01, - 1.4327497897351341e-01,1.4078594981444470e-01,1.3830811644855071e-01, - 1.3584147657125373e-01,1.3338602969166913e-01,1.3094177717364430e-01, - 1.2850872227999952e-01,1.2608687022018586e-01,1.2367622820159654e-01, - 1.2127680548479021e-01,1.1888861344290998e-01,1.1651166562561080e-01, - 1.1414597782783835e-01,1.1179156816383801e-01,1.0944845714681163e-01, - 1.0711666777468364e-01,1.0479622562248690e-01,1.0248715894193508e-01, - 1.0018949876880981e-01,9.7903279038862284e-02,9.5628536713008819e-02, - 9.3365311912690860e-02,9.1113648066373634e-02,8.8873592068275789e-02, - 8.6645194450557961e-02,8.4428509570353374e-02,8.2223595813202863e-02, - 8.0030515814663056e-02,7.7849336702096039e-02,7.5680130358927067e-02, - 7.3522973713981268e-02,7.1377949058890375e-02,6.9245144397006769e-02, - 6.7124653827788497e-02,6.5016577971242842e-02,6.2921024437758113e-02, - 6.0838108349539864e-02,5.8767952920933758e-02,5.6710690106202902e-02, - 5.4666461324888914e-02,5.2635418276792176e-02,5.0617723860947761e-02, - 4.8613553215868521e-02,4.6623094901930368e-02,4.4646552251294443e-02, - 4.2684144916474431e-02,4.0736110655940933e-02,3.8802707404526113e-02, - 3.6884215688567284e-02,3.4980941461716084e-02,3.3093219458578522e-02, - 3.1221417191920245e-02,2.9365939758133314e-02,2.7527235669603082e-02, - 2.5705804008548896e-02,2.3902203305795882e-02,2.2117062707308864e-02, - 2.0351096230044517e-02,1.8605121275724643e-02,1.6880083152543166e-02, - 1.5177088307935325e-02,1.3497450601739880e-02,1.1842757857907888e-02, - 1.0214971439701471e-02,8.6165827693987316e-03,7.0508754713732268e-03, - 5.5224032992509968e-03,4.0379725933630305e-03,2.6090727461021627e-03, - 1.2602859304985975e-03] - -## Tables for exponential variates -const ke = - UInt64[0x000e290a13924be3,0x0000000000000000,0x0009beadebce18bf,0x000c377ac71f9e08, - 0x000d4ddb99075857,0x000de893fb8ca23e,0x000e4a8e87c4328d,0x000e8dff16ae1cb9, - 0x000ebf2deab58c59,0x000ee49a6e8b9638,0x000f0204efd64ee4,0x000f19bdb8ea3c1b, - 0x000f2d458bbe5bd1,0x000f3da104b78236,0x000f4b86d784571f,0x000f577ad8a7784f, - 0x000f61de83da32ab,0x000f6afb7843cce7,0x000f730a57372b44,0x000f7a37651b0e68, - 0x000f80a5bb6eea52,0x000f867189d3cb5b,0x000f8bb1b4f8fbbd,0x000f9079062292b8, - 0x000f94d70ca8d43a,0x000f98d8c7dcaa99,0x000f9c8928abe083,0x000f9ff175b734a6, - 0x000fa319996bc47d,0x000fa6085f8e9d07,0x000fa8c3a62e1991,0x000fab5084e1f660, - 0x000fadb36c84cccb,0x000faff041086846,0x000fb20a6ea22bb9,0x000fb404fb42cb3c, - 0x000fb5e295158173,0x000fb7a59e99727a,0x000fb95038c8789d,0x000fbae44ba684eb, - 0x000fbc638d822e60,0x000fbdcf89209ffa,0x000fbf29a303cfc5,0x000fc0731df1089c, - 0x000fc1ad1ed6c8b1,0x000fc2d8b02b5c89,0x000fc3f6c4d92131,0x000fc5083ac9ba7d, - 0x000fc60ddd1e9cd6,0x000fc7086622e825,0x000fc7f881009f0b,0x000fc8decb41ac70, - 0x000fc9bbd623d7ec,0x000fca9027c5b26d,0x000fcb5c3c319c49,0x000fcc20864b4449, - 0x000fccdd70a35d40,0x000fcd935e34bf80,0x000fce42ab0db8bd,0x000fceebace7ec01, - 0x000fcf8eb3b0d0e7,0x000fd02c0a049b60,0x000fd0c3f59d199c,0x000fd156b7b5e27e, - 0x000fd1e48d670341,0x000fd26daff73551,0x000fd2f2552684be,0x000fd372af7233c1, - 0x000fd3eeee528f62,0x000fd4673e73543a,0x000fd4dbc9e72ff7,0x000fd54cb856dc2c, - 0x000fd5ba2f2c4119,0x000fd62451ba02c2,0x000fd68b415fcff4,0x000fd6ef1dabc160, - 0x000fd75004790eb6,0x000fd7ae120c583f,0x000fd809612dbd09,0x000fd8620b40effa, - 0x000fd8b8285b78fd,0x000fd90bcf594b1d,0x000fd95d15efd425,0x000fd9ac10bfa70c, - 0x000fd9f8d364df06,0x000fda437086566b,0x000fda8bf9e3c9fe,0x000fdad28062fed5, - 0x000fdb17141bff2c,0x000fdb59c4648085,0x000fdb9a9fda83cc,0x000fdbd9b46e3ed4, - 0x000fdc170f6b5d04,0x000fdc52bd81a3fb,0x000fdc8ccacd07ba,0x000fdcc542dd3902, - 0x000fdcfc30bcb793,0x000fdd319ef77143,0x000fdd6597a0f60b,0x000fdd98245a48a2, - 0x000fddc94e575271,0x000fddf91e64014f,0x000fde279ce914ca,0x000fde54d1f0a06a, - 0x000fde80c52a47cf,0x000fdeab7def394e,0x000fded50345eb35,0x000fdefd5be59fa0, - 0x000fdf248e39b26f,0x000fdf4aa064b4af,0x000fdf6f98435894,0x000fdf937b6f30ba, - 0x000fdfb64f414571,0x000fdfd818d48262,0x000fdff8dd07fed8,0x000fe018a08122c4, - 0x000fe03767adaa59,0x000fe05536c58a13,0x000fe07211ccb4c5,0x000fe08dfc94c532, - 0x000fe0a8fabe8ca1,0x000fe0c30fbb87a5,0x000fe0dc3ecf3a5a,0x000fe0f48b107521, - 0x000fe10bf76a82ef,0x000fe122869e41ff,0x000fe1383b4327e1,0x000fe14d17c83187, - 0x000fe1611e74c023,0x000fe1745169635a,0x000fe186b2a09176,0x000fe19843ef4e07, - 0x000fe1a90705bf63,0x000fe1b8fd6fb37c,0x000fe1c828951443,0x000fe1d689ba4bfd, - 0x000fe1e4220099a4,0x000fe1f0f26655a0,0x000fe1fcfbc726d4,0x000fe2083edc2830, - 0x000fe212bc3bfeb4,0x000fe21c745adfe3,0x000fe225678a8895,0x000fe22d95fa23f4, - 0x000fe234ffb62282,0x000fe23ba4a800d9,0x000fe2418495fddc,0x000fe2469f22bffb, - 0x000fe24af3cce90d,0x000fe24e81ee9858,0x000fe25148bcda19,0x000fe253474703fe, - 0x000fe2547c75fdc6,0x000fe254e70b754f,0x000fe25485a0fd1a,0x000fe25356a71450, - 0x000fe2515864173a,0x000fe24e88f316f1,0x000fe24ae64296fa,0x000fe2466e132f60, - 0x000fe2411df611bd,0x000fe23af34b6f73,0x000fe233eb40bf41,0x000fe22c02cee01b, - 0x000fe22336b81710,0x000fe2198385e5cc,0x000fe20ee586b707,0x000fe20358cb5dfb, - 0x000fe1f6d92465b1,0x000fe1e9621f2c9e,0x000fe1daef02c8da,0x000fe1cb7accb0a6, - 0x000fe1bb002d22c9,0x000fe1a9798349b8,0x000fe196e0d9140c,0x000fe1832fdebc44, - 0x000fe16e5fe5f931,0x000fe15869dccfcf,0x000fe1414647fe78,0x000fe128ed3cf8b2, - 0x000fe10f565b69cf,0x000fe0f478c633ab,0x000fe0d84b1bdd9e,0x000fe0bac36e6688, - 0x000fe09bd73a6b5b,0x000fe07b7b5d920a,0x000fe059a40c26d2,0x000fe03644c5d7f8, - 0x000fe011504979b2,0x000fdfeab887b95c,0x000fdfc26e94a447,0x000fdf986297e305, - 0x000fdf6c83bb8663,0x000fdf3ec0193eed,0x000fdf0f04a5d30a,0x000fdedd3d1aa204, - 0x000fdea953dcfc13,0x000fde7331e3100d,0x000fde3abe9626f2,0x000fddffdfb1dbd5, - 0x000fddc2791ff351,0x000fdd826cd068c6,0x000fdd3f9a8d3856,0x000fdcf9dfc95b0c, - 0x000fdcb1176a55fe,0x000fdc65198ba50b,0x000fdc15bb3b2daa,0x000fdbc2ce2dc4ae, - 0x000fdb6c206aaaca,0x000fdb117becb4a1,0x000fdab2a6379bf0,0x000fda4f5fdfb4e9, - 0x000fd9e76401f3a3,0x000fd97a67a9ce1f,0x000fd90819221429,0x000fd8901f2d4b02, - 0x000fd812182170e1,0x000fd78d98e23cd3,0x000fd7022bb3f082,0x000fd66f4edf96b9, - 0x000fd5d473200305,0x000fd530f9ccff94,0x000fd48432b7b351,0x000fd3cd59a8469e, - 0x000fd30b9368f90a,0x000fd23dea45f500,0x000fd16349e2e04a,0x000fd07a7a3ef98a, - 0x000fcf8219b5df05,0x000fce7895bcfcde,0x000fcd5c220ad5e2,0x000fcc2aadbc17dc, - 0x000fcae1d5e81fbc,0x000fc97ed4e778f9,0x000fc7fe6d4d720e,0x000fc65ccf39c2fc, - 0x000fc4957623cb03,0x000fc2a2fc826dc7,0x000fc07ee19b01cd,0x000fbe213c1cf493, - 0x000fbb8051ac1566,0x000fb890078d120e,0x000fb5411a5b9a95,0x000fb18000547133, - 0x000fad334827f1e2,0x000fa839276708b9,0x000fa263b32e37ed,0x000f9b72d1c52cd1, - 0x000f930a1a281a05,0x000f889f023d820a,0x000f7b577d2be5f3,0x000f69c650c40a8f, - 0x000f51530f0916d8,0x000f2cb0e3c5933e,0x000eeefb15d605d8,0x000e6da6ecf27460] - -const we = - [1.9311480126418366e-15,1.4178028487910829e-17,2.3278824993382448e-17, - 3.0487830247064320e-17,3.6665697714474878e-17,4.2179302189289733e-17, - 4.7222561556862764e-17,5.1911915446217879e-17,5.6323471083955047e-17, - 6.0510082606427647e-17,6.4510165096727506e-17,6.8352646803700541e-17, - 7.2059939574689050e-17,7.5649815537392981e-17,7.9136643961951065e-17, - 8.2532235563518929e-17,8.5846436168850513e-17,8.9087554865647428e-17, - 9.2262679629663719e-17,9.5377914505292719e-17,9.8438560874559257e-17, - 1.0144925809006294e-16,1.0441409405585343e-16,1.0733669323436384e-16, - 1.1022028745670189e-16,1.1306777346479334e-16,1.1588176009705533e-16, - 1.1866460730417886e-16,1.2141845865694359e-16,1.2414526862326387e-16, - 1.2684682560606153e-16,1.2952477151912284e-16,1.3218061851538810e-16, - 1.3481576335745444e-16,1.3743149982367625e-16,1.4002902946807859e-16, - 1.4260947099321287e-16,1.4517386844829297e-16,1.4772319842763584e-16, - 1.5025837641447456e-16,1.5278026239101652e-16,1.5528966581595696e-16, - 1.5778735005459581e-16,1.6027403633350909e-16,1.6275040728083524e-16, - 1.6521711010420076e-16,1.6767475945078279e-16,1.7012393998770646e-16, - 1.7256520873568226e-16,1.7499909718432365e-16,1.7742611321380505e-16, - 1.7984674284430714e-16,1.8226145183195818e-16,1.8467068712763576e-16, - 1.8707487821298258e-16,1.8947443832625899e-16,1.9186976558915995e-16, - 1.9426124404443042e-16,1.9664924461299023e-16,1.9903412597830144e-16, - 2.0141623540485899e-16,2.0379590949693882e-16,2.0617347490308439e-16, - 2.0854924897123771e-16,2.1092354035891528e-16,2.1329664960238294e-16, - 2.1566886964838970e-16,2.1804048635167009e-16,2.2041177894111562e-16, - 2.2278302045723950e-16,2.2515447816331350e-16,2.2752641393233694e-16, - 2.2989908461180186e-16,2.3227274236804366e-16,2.3464763501180916e-16, - 2.3702400630653389e-16,2.3940209626069303e-16,2.4178214140547710e-16, - 2.4416437505894123e-16,2.4654902757768304e-16,2.4893632659702250e-16, - 2.5132649726057970e-16,2.5371976244007951e-16,2.5611634294614988e-16, - 2.5851645773082391e-16,2.6092032408240577e-16,2.6332815781331452e-16, - 2.6574017344147618e-16,2.6815658436579989e-16,2.7057760303623509e-16, - 2.7300344111887955e-16,2.7543430965657619e-16,2.7787041922541278e-16, - 2.8031198008751431e-16,2.8275920234049704e-16,2.8521229606393309e-16, - 2.8767147146315804e-16,2.9013693901073754e-16,2.9260890958589514e-16, - 2.9508759461219033e-16,2.9757320619372521e-16,3.0006595725014739e-16, - 3.0256606165070789e-16,3.0507373434762511e-16,3.0758919150899939e-16, - 3.1011265065151543e-16,3.1264433077316750e-16,3.1518445248623523e-16, - 3.1773323815073683e-16,3.2029091200858335e-16,3.2285770031865573e-16, - 3.2543383149302610e-16,3.2801953623454359e-16,3.3061504767600738e-16, - 3.3322060152114841e-16,3.3583643618764577e-16,3.3846279295240445e-16, - 3.4109991609932597e-16,3.4374805306980633e-16,3.4640745461620167e-16, - 3.4907837495850680e-16,3.5176107194449828e-16,3.5445580721360130e-16, - 3.5716284636474652e-16,3.5988245912849274e-16,3.6261491954370031e-16, - 3.6536050613905045e-16,3.6811950211971757e-16,3.7089219555951389e-16, - 3.7367887959883854e-16,3.7647985264877841e-16,3.7929541860172334e-16, - 3.8212588704887531e-16,3.8497157350504876e-16,3.8783279964117988e-16, - 3.9070989352498183e-16,3.9360318987020748e-16,3.9651303029500381e-16, - 3.9943976358986842e-16,4.0238374599574693e-16,4.0534534149283966e-16, - 4.0832492210071775e-16,4.1132286819038357e-16,4.1433956880894741e-16, - 4.1737542201763194e-16,4.2043083524385856e-16,4.2350622564821518e-16, - 4.2660202050715582e-16,4.2971865761233266e-16,4.3285658568752094e-16, - 4.3601626482415681e-16,4.3919816693657415e-16,4.4240277623809919e-16, - 4.4563058973923611e-16,4.4888211776926172e-16,4.5215788452263475e-16, - 4.5545842863172421e-16,4.5878430376746227e-16,4.6213607926964266e-16, - 4.6551434080870692e-16,4.6891969108099157e-16,4.7235275053955480e-16, - 4.7581415816285534e-16,4.7930457226372470e-16,4.8282467134125866e-16, - 4.8637515497845119e-16,4.8995674478861404e-16,4.9357018541385775e-16, - 4.9721624557917034e-16,5.0089571920591141e-16,5.0460942658884340e-16, - 5.0835821564116245e-16,5.1214296321235415e-16,5.1596457648410618e-16, - 5.1982399444994938e-16,5.2372218948478484e-16,5.2766016901098856e-16, - 5.3163897726836902e-16,5.3565969719590503e-16,5.3972345243389779e-16, - 5.4383140945596370e-16,5.4798477984116296e-16,5.5218482269752343e-16, - 5.5643284724928722e-16,5.6073021560139669e-16,5.6507834569605064e-16, - 5.6947871447763482e-16,5.7393286128396354e-16,5.7844239148359912e-16, - 5.8300898038105864e-16,5.8763437741400573e-16,5.9232041066909314e-16, - 5.9706899174600906e-16,6.0188212100252363e-16,6.0676189321700068e-16, - 6.1171050370897217e-16,6.1673025496306200e-16,6.2182356380685327e-16, - 6.2699296919933262e-16,6.3224114069342115e-16,6.3757088764394262e-16, - 6.4298516924135947e-16,6.4848710546189033e-16,6.5407998903644809e-16, - 6.5976729855445663e-16,6.6555271283433428e-16,6.7144012671064882e-16, - 6.7743366840910103e-16,6.8353771870512740e-16,6.8975693209068478e-16, - 6.9609626020748846e-16,7.0256097784459588e-16,7.0915671184495837e-16, - 7.1588947332085531e-16,7.2276569364381212e-16,7.2979226475290851e-16, - 7.3697658441912426e-16,7.4432660721604146e-16,7.5185090208325131e-16, - 7.5955871753377488e-16,7.6746005575784274e-16,7.7556575712157906e-16, - 7.8388759686228577e-16,7.9243839615735500e-16,8.0123215021130834e-16, - 8.1028417659131464e-16,8.1961128778061250e-16,8.2923199285818092e-16, - 8.3916673441467979e-16,8.4943816836487701e-16,8.6007149633349414e-16, - 8.7109486293879040e-16,8.8253983380721398e-16,8.9444197485198646e-16, - 9.0684155971316690e-16,9.1978444098118649e-16,9.3332313294229516e-16, - 9.4751817065249841e-16,9.6243983456584759e-16,9.7817036547844198e-16, - 9.9480684723838795e-16,1.0124650144288319e-15,1.0312843657756166e-15, - 1.0514351604044550e-15,1.0731281954224043e-15,1.0966288068517408e-15, - 1.1222774909350319e-15,1.1505212963006663e-15,1.1819635283304206e-15, - 1.2174462832361815e-15,1.2581958069755114e-15,1.3060984107128082e-15, - 1.3642786158057857e-15,1.4384889932178723e-15,1.5412190700064194e-15, - 1.7091034077168055e-15] -const fe = - [1.0000000000000000e+00,9.3814368086217470e-01,9.0046992992574648e-01, - 8.7170433238120359e-01,8.4778550062398961e-01,8.2699329664305032e-01, - 8.0842165152300838e-01,7.9152763697249562e-01,7.7595685204011555e-01, - 7.6146338884989628e-01,7.4786862198519510e-01,7.3503809243142348e-01, - 7.2286765959357202e-01,7.1127476080507601e-01,7.0019265508278816e-01, - 6.8956649611707799e-01,6.7935057226476536e-01,6.6950631673192473e-01, - 6.6000084107899970e-01,6.5080583341457110e-01,6.4189671642726609e-01, - 6.3325199421436607e-01,6.2485273870366598e-01,6.1668218091520766e-01, - 6.0872538207962201e-01,6.0096896636523223e-01,5.9340090169173343e-01, - 5.8601031847726803e-01,5.7878735860284503e-01,5.7172304866482582e-01, - 5.6480919291240017e-01,5.5803828226258745e-01,5.5140341654064129e-01, - 5.4489823767243961e-01,5.3851687200286191e-01,5.3225388026304332e-01, - 5.2610421398361973e-01,5.2006317736823360e-01,5.1412639381474856e-01, - 5.0828977641064288e-01,5.0254950184134772e-01,4.9690198724154955e-01, - 4.9134386959403253e-01,4.8587198734188491e-01,4.8048336393045421e-01, - 4.7517519303737737e-01,4.6994482528395998e-01,4.6478975625042618e-01, - 4.5970761564213769e-01,4.5469615747461550e-01,4.4975325116275500e-01, - 4.4487687341454851e-01,4.4006510084235390e-01,4.3531610321563657e-01, - 4.3062813728845883e-01,4.2599954114303434e-01,4.2142872899761658e-01, - 4.1691418643300288e-01,4.1245446599716118e-01,4.0804818315203240e-01, - 4.0369401253053028e-01,3.9939068447523107e-01,3.9513698183329016e-01, - 3.9093173698479711e-01,3.8677382908413765e-01,3.8266218149600983e-01, - 3.7859575940958079e-01,3.7457356761590216e-01,3.7059464843514600e-01, - 3.6665807978151416e-01,3.6276297335481777e-01,3.5890847294874978e-01, - 3.5509375286678746e-01,3.5131801643748334e-01,3.4758049462163698e-01, - 3.4388044470450241e-01,3.4021714906678002e-01,3.3658991402867761e-01, - 3.3299806876180899e-01,3.2944096426413633e-01,3.2591797239355619e-01, - 3.2242848495608917e-01,3.1897191284495724e-01,3.1554768522712895e-01, - 3.1215524877417955e-01,3.0879406693456019e-01,3.0546361924459026e-01, - 3.0216340067569353e-01,2.9889292101558179e-01,2.9565170428126120e-01, - 2.9243928816189257e-01,2.8925522348967775e-01,2.8609907373707683e-01, - 2.8297041453878075e-01,2.7986883323697292e-01,2.7679392844851736e-01, - 2.7374530965280297e-01,2.7072259679906002e-01,2.6772541993204479e-01, - 2.6475341883506220e-01,2.6180624268936298e-01,2.5888354974901623e-01, - 2.5598500703041538e-01,2.5311029001562946e-01,2.5025908236886230e-01, - 2.4743107566532763e-01,2.4462596913189211e-01,2.4184346939887721e-01, - 2.3908329026244918e-01,2.3634515245705964e-01,2.3362878343743335e-01, - 2.3093391716962741e-01,2.2826029393071670e-01,2.2560766011668407e-01, - 2.2297576805812019e-01,2.2036437584335949e-01,2.1777324714870053e-01, - 2.1520215107537868e-01,2.1265086199297828e-01,2.1011915938898826e-01, - 2.0760682772422204e-01,2.0511365629383771e-01,2.0263943909370902e-01, - 2.0018397469191127e-01,1.9774706610509887e-01,1.9532852067956322e-01, - 1.9292814997677135e-01,1.9054576966319539e-01,1.8818119940425432e-01, - 1.8583426276219711e-01,1.8350478709776746e-01,1.8119260347549629e-01, - 1.7889754657247831e-01,1.7661945459049488e-01,1.7435816917135349e-01, - 1.7211353531532006e-01,1.6988540130252766e-01,1.6767361861725019e-01, - 1.6547804187493600e-01,1.6329852875190182e-01,1.6113493991759203e-01, - 1.5898713896931421e-01,1.5685499236936523e-01,1.5473836938446808e-01, - 1.5263714202744286e-01,1.5055118500103989e-01,1.4848037564386679e-01, - 1.4642459387834494e-01,1.4438372216063478e-01,1.4235764543247220e-01, - 1.4034625107486245e-01,1.3834942886358020e-01,1.3636707092642886e-01, - 1.3439907170221363e-01,1.3244532790138752e-01,1.3050573846833077e-01, - 1.2858020454522817e-01,1.2666862943751067e-01,1.2477091858083096e-01, - 1.2288697950954514e-01,1.2101672182667483e-01,1.1916005717532768e-01, - 1.1731689921155557e-01,1.1548716357863353e-01,1.1367076788274431e-01, - 1.1186763167005630e-01,1.1007767640518538e-01,1.0830082545103380e-01, - 1.0653700405000166e-01,1.0478613930657017e-01,1.0304816017125772e-01, - 1.0132299742595363e-01,9.9610583670637132e-02,9.7910853311492199e-02, - 9.6223742550432798e-02,9.4549189376055859e-02,9.2887133556043541e-02, - 9.1237516631040155e-02,8.9600281910032858e-02,8.7975374467270218e-02, - 8.6362741140756913e-02,8.4762330532368119e-02,8.3174093009632383e-02, - 8.1597980709237419e-02,8.0033947542319905e-02,7.8481949201606421e-02, - 7.6941943170480503e-02,7.5413888734058410e-02,7.3897746992364746e-02, - 7.2393480875708738e-02,7.0901055162371829e-02,6.9420436498728755e-02, - 6.7951593421936601e-02,6.6494496385339774e-02,6.5049117786753749e-02, - 6.3615431999807334e-02,6.2193415408540995e-02,6.0783046445479633e-02, - 5.9384305633420266e-02,5.7997175631200659e-02,5.6621641283742877e-02, - 5.5257689676697037e-02,5.3905310196046087e-02,5.2564494593071692e-02, - 5.1235237055126281e-02,4.9917534282706372e-02,4.8611385573379497e-02, - 4.7316792913181548e-02,4.6033761076175170e-02,4.4762297732943282e-02, - 4.3502413568888183e-02,4.2254122413316234e-02,4.1017441380414819e-02, - 3.9792391023374125e-02,3.8578995503074857e-02,3.7377282772959361e-02, - 3.6187284781931423e-02,3.5009037697397410e-02,3.3842582150874330e-02, - 3.2687963508959535e-02,3.1545232172893609e-02,3.0414443910466604e-02, - 2.9295660224637393e-02,2.8188948763978636e-02,2.7094383780955800e-02, - 2.6012046645134217e-02,2.4942026419731783e-02,2.3884420511558171e-02, - 2.2839335406385240e-02,2.1806887504283581e-02,2.0787204072578117e-02, - 1.9780424338009743e-02,1.8786700744696030e-02,1.7806200410911362e-02, - 1.6839106826039948e-02,1.5885621839973163e-02,1.4945968011691148e-02, - 1.4020391403181938e-02,1.3109164931254991e-02,1.2212592426255381e-02, - 1.1331013597834597e-02,1.0464810181029979e-02,9.6144136425022099e-03, - 8.7803149858089753e-03,7.9630774380170400e-03,7.1633531836349839e-03, - 6.3819059373191791e-03,5.6196422072054830e-03,4.8776559835423923e-03, - 4.1572951208337953e-03,3.4602647778369040e-03,2.7887987935740761e-03, - 2.1459677437189063e-03,1.5362997803015724e-03,9.6726928232717454e-04, - 4.5413435384149677e-04] - - -const ziggurat_nor_r = 3.6541528853610087963519472518 -const ziggurat_nor_inv_r = inv(ziggurat_nor_r) -const ziggurat_exp_r = 7.6971174701310497140446280481 - -""" - randn([rng=GLOBAL_RNG], [T=Float64], [dims...]) - -Generate a normally-distributed random number of type `T` with mean 0 and standard deviation 1. -Optionally generate an array of normally-distributed random numbers. -The `Base` module currently provides an implementation for the types -[`Float16`](@ref), [`Float32`](@ref), and [`Float64`](@ref) (the default). - -# Examples - -```jldoctest -julia> rng = MersenneTwister(1234); - -julia> randn(rng, Float64) -0.8673472019512456 - -julia> randn(rng, Float32, (2, 4)) -2×4 Array{Float32,2}: - -0.901744 -0.902914 2.21188 -0.271735 - -0.494479 0.864401 0.532813 0.502334 -``` -""" -@inline function randn(rng::AbstractRNG=GLOBAL_RNG) - @inbounds begin - r = rand_ui52(rng) - rabs = Int64(r>>1) # One bit for the sign - idx = rabs & 0xFF - x = ifelse(r % Bool, -rabs, rabs)*wi[idx+1] - rabs < ki[idx+1] && return x # 99.3% of the time we return here 1st try - return randn_unlikely(rng, idx, rabs, x) - end -end - -# this unlikely branch is put in a separate function for better efficiency -function randn_unlikely(rng, idx, rabs, x) - @inbounds if idx == 0 - while true - xx = -ziggurat_nor_inv_r*log(rand(rng)) - yy = -log(rand(rng)) - yy+yy > xx*xx && return (rabs >> 8) % Bool ? -ziggurat_nor_r-xx : ziggurat_nor_r+xx - end - elseif (fi[idx] - fi[idx+1])*rand(rng) + fi[idx+1] < exp(-0.5*x*x) - return x # return from the triangular area - else - return randn(rng) - end -end - -""" - randexp([rng=GLOBAL_RNG], [T=Float64], [dims...]) - -Generate a random number of type `T` according to the exponential distribution with scale 1. -Optionally generate an array of such random numbers. -The `Base` module currently provides an implementation for the types -[`Float16`](@ref), [`Float32`](@ref), and [`Float64`](@ref) (the default). - -# Examples - -```jldoctest -julia> rng = MersenneTwister(1234); - -julia> randexp(rng, Float32) -2.4835055f0 - -julia> randexp(rng, 3, 3) -3×3 Array{Float64,2}: - 1.5167 1.30652 0.344435 - 0.604436 2.78029 0.418516 - 0.695867 0.693292 0.643644 -``` -""" -@inline function randexp(rng::AbstractRNG=GLOBAL_RNG) - @inbounds begin - ri = rand_ui52(rng) - idx = ri & 0xFF - x = ri*we[idx+1] - ri < ke[idx+1] && return x # 98.9% of the time we return here 1st try - return randexp_unlikely(rng, idx, x) - end -end - -function randexp_unlikely(rng, idx, x) - @inbounds if idx == 0 - return ziggurat_exp_r - log(rand(rng)) - elseif (fe[idx] - fe[idx+1])*rand(rng) + fe[idx+1] < exp(-x) - return x # return from the triangular area - else - return randexp(rng) - end -end - -""" - randn!([rng=GLOBAL_RNG], A::AbstractArray) -> A - -Fill the array `A` with normally-distributed (mean 0, standard deviation 1) random numbers. -Also see the [`rand`](@ref) function. - -# Example - -```jldoctest -julia> rng = MersenneTwister(1234); - -julia> randn!(rng, zeros(5)) -5-element Array{Float64,1}: - 0.867347 - -0.901744 - -0.494479 - -0.902914 - 0.864401 -``` -""" -function randn! end - -""" - randexp!([rng=GLOBAL_RNG], A::AbstractArray) -> A - -Fill the array `A` with random numbers following the exponential distribution (with scale 1). - -# Example - -```jldoctest -julia> rng = MersenneTwister(1234); - -julia> randexp!(rng, zeros(5)) -5-element Array{Float64,1}: - 2.48351 - 1.5167 - 0.604436 - 0.695867 - 1.30652 -``` -""" -function randexp! end - -let Floats = Union{Float16,Float32,Float64} - for randfun in [:randn, :randexp] - randfun! = Symbol(randfun, :!) - @eval begin - # scalars - $randfun(rng::AbstractRNG, ::Type{T}) where {T<:$Floats} = convert(T, $randfun(rng)) - $randfun(::Type{T}) where {T} = $randfun(GLOBAL_RNG, T) - - # filling arrays - function $randfun!(rng::AbstractRNG, A::AbstractArray{T}) where T - for i in eachindex(A) - @inbounds A[i] = $randfun(rng, T) - end - A - end - - $randfun!(A::AbstractArray) = $randfun!(GLOBAL_RNG, A) - - # generating arrays - $randfun(rng::AbstractRNG, ::Type{T}, dims::Dims ) where {T} = $randfun!(rng, Array{T}(dims)) - # Note that this method explicitly does not define $randfun(rng, T), in order to prevent an infinite recursion. - $randfun(rng::AbstractRNG, ::Type{T}, dim1::Integer, dims::Integer...) where {T} = $randfun!(rng, Array{T}(dim1, dims...)) - $randfun( ::Type{T}, dims::Dims ) where {T} = $randfun(GLOBAL_RNG, T, dims) - $randfun( ::Type{T}, dims::Integer... ) where {T} = $randfun(GLOBAL_RNG, T, dims...) - $randfun(rng::AbstractRNG, dims::Dims ) = $randfun(rng, Float64, dims) - $randfun(rng::AbstractRNG, dims::Integer... ) = $randfun(rng, Float64, dims...) - $randfun( dims::Dims ) = $randfun(GLOBAL_RNG, Float64, dims) - $randfun( dims::Integer... ) = $randfun(GLOBAL_RNG, Float64, dims...) - end - end -end - -## random UUID generation - -struct UUID - value::UInt128 - - UUID(u::UInt128) = new(u) -end - -""" - uuid1([rng::AbstractRNG=GLOBAL_RNG]) -> UUID - -Generates a version 1 (time-based) universally unique identifier (UUID), as specified -by RFC 4122. Note that the Node ID is randomly generated (does not identify the host) -according to section 4.5 of the RFC. - -# Example - -```jldoctest -julia> rng = MersenneTwister(1234); - -julia> Base.Random.uuid1(rng) -2cc938da-5937-11e7-196e-0f4ef71aa64b -``` -""" -function uuid1(rng::AbstractRNG=GLOBAL_RNG) - u = rand(rng, UInt128) - - # mask off clock sequence and node - u &= 0x00000000000000003fffffffffffffff - - # set the unicast/multicast bit and version - u |= 0x00000000000010000000010000000000 - - # 0x01b21dd213814000 is the number of 100 nanosecond intervals - # between the UUID epoch and Unix epoch - timestamp = round(UInt64, time() * 1e7) + 0x01b21dd213814000 - ts_low = timestamp & typemax(UInt32) - ts_mid = (timestamp >> 32) & typemax(UInt16) - ts_hi = (timestamp >> 48) & 0x0fff - - u |= UInt128(ts_low) << 96 - u |= UInt128(ts_mid) << 80 - u |= UInt128(ts_hi) << 64 - - UUID(u) -end - -""" - uuid4([rng::AbstractRNG=GLOBAL_RNG]) -> UUID - -Generates a version 4 (random or pseudo-random) universally unique identifier (UUID), -as specified by RFC 4122. - -# Example -```jldoctest -julia> rng = MersenneTwister(1234); - -julia> Base.Random.uuid4(rng) -82015f10-44cc-4827-996e-0f4ef71aa64b -``` -""" -function uuid4(rng::AbstractRNG=GLOBAL_RNG) - u = rand(rng, UInt128) - u &= 0xffffffffffff0fff3fffffffffffffff - u |= 0x00000000000040008000000000000000 - UUID(u) -end - -""" - uuid_version(u::UUID) -> Integer - -Inspects the given UUID and returns its version (see RFC 4122). - -# Example - -```jldoctest -julia> rng = MersenneTwister(1234); - -julia> Base.Random.uuid_version(Base.Random.uuid4(rng)) -4 -``` -""" -function uuid_version(u::UUID) - Int((u.value >> 76) & 0xf) -end - -Base.convert(::Type{UInt128}, u::UUID) = u.value - -function Base.convert(::Type{UUID}, s::AbstractString) - s = lowercase(s) - - if !ismatch(r"^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$", s) - throw(ArgumentError("Malformed UUID string")) - end - - u = UInt128(0) - for i in [1:8; 10:13; 15:18; 20:23; 25:36] - u <<= 4 - d = s[i]-'0' - u |= 0xf & (d-39*(d>9)) - end - return UUID(u) -end - -function Base.repr(u::UUID) - u = u.value - a = Vector{UInt8}(36) - for i = [36:-1:25; 23:-1:20; 18:-1:15; 13:-1:10; 8:-1:1] - d = u & 0xf - a[i] = '0'+d+39*(d>9) - u >>= 4 - end - a[[24,19,14,9]] = '-' - - return String(a) -end - -Base.show(io::IO, u::UUID) = write(io, Base.repr(u)) - -# return a random string (often useful for temporary filenames/dirnames) -let b = UInt8['0':'9';'A':'Z';'a':'z'] - global randstring - randstring(r::AbstractRNG, n::Int) = String(b[rand(r, 1:length(b), n)]) - randstring(r::AbstractRNG) = randstring(r,8) - randstring(n::Int) = randstring(GLOBAL_RNG, n) - randstring() = randstring(GLOBAL_RNG) -end - - -# Fill S (resized as needed) with a random subsequence of A, where -# each element of A is included in S with independent probability p. -# (Note that this is different from the problem of finding a random -# size-m subset of A where m is fixed!) -function randsubseq!(r::AbstractRNG, S::AbstractArray, A::AbstractArray, p::Real) - 0 <= p <= 1 || throw(ArgumentError("probability $p not in [0,1]")) - n = length(A) - p == 1 && return copy!(resize!(S, n), A) - empty!(S) - p == 0 && return S - nexpected = p * length(A) - sizehint!(S, round(Int,nexpected + 5*sqrt(nexpected))) - if p > 0.15 # empirical threshold for trivial O(n) algorithm to be better - for i = 1:n - rand(r) <= p && push!(S, A[i]) - end - else - # Skip through A, in order, from each element i to the next element i+s - # included in S. The probability that the next included element is - # s==k (k > 0) is (1-p)^(k-1) * p, and hence the probability (CDF) that - # s is in {1,...,k} is 1-(1-p)^k = F(k). Thus, we can draw the skip s - # from this probability distribution via the discrete inverse-transform - # method: s = ceil(F^{-1}(u)) where u = rand(), which is simply - # s = ceil(log(rand()) / log1p(-p)). - # -log(rand()) is an exponential variate, so can use randexp(). - L = -1 / log1p(-p) # L > 0 - i = 0 - while true - s = randexp(r) * L - s >= n - i && return S # compare before ceil to avoid overflow - push!(S, A[i += ceil(Int,s)]) - end - # [This algorithm is similar in spirit to, but much simpler than, - # the one by Vitter for a related problem in "Faster methods for - # random sampling," Comm. ACM Magazine 7, 703-718 (1984).] - end - return S -end -randsubseq!(S::AbstractArray, A::AbstractArray, p::Real) = randsubseq!(GLOBAL_RNG, S, A, p) - -randsubseq(r::AbstractRNG, A::AbstractArray{T}, p::Real) where {T} = randsubseq!(r, T[], A, p) - -""" - randsubseq(A, p) -> Vector - -Return a vector consisting of a random subsequence of the given array `A`, where each -element of `A` is included (in order) with independent probability `p`. (Complexity is -linear in `p*length(A)`, so this function is efficient even if `p` is small and `A` is -large.) Technically, this process is known as "Bernoulli sampling" of `A`. -""" -randsubseq(A::AbstractArray, p::Real) = randsubseq(GLOBAL_RNG, A, p) - -"Return a random `Int` (masked with `mask`) in ``[0, n)``, when `n <= 2^52`." -@inline function rand_lt(r::AbstractRNG, n::Int, mask::Int=nextpow2(n)-1) - # this duplicates the functionality of RangeGenerator objects, - # to optimize this special case - while true - x = (rand_ui52_raw(r) % Int) & mask - x < n && return x - end -end - -""" - shuffle!([rng=GLOBAL_RNG,] v) - -In-place version of [`shuffle`](@ref): randomly permute the array `v` in-place, -optionally supplying the random-number generator `rng`. - -# Example - -```jldoctest -julia> rng = MersenneTwister(1234); - -julia> shuffle!(rng, collect(1:16)) -16-element Array{Int64,1}: - 2 - 15 - 5 - 14 - 1 - 9 - 10 - 6 - 11 - 3 - 16 - 7 - 4 - 12 - 8 - 13 -``` -""" -function shuffle!(r::AbstractRNG, a::AbstractVector) - n = length(a) - @assert n <= Int64(2)^52 - mask = nextpow2(n) - 1 - for i = n:-1:2 - (mask >> 1) == i && (mask >>= 1) - j = 1 + rand_lt(r, i, mask) - a[i], a[j] = a[j], a[i] - end - return a -end - -shuffle!(a::AbstractVector) = shuffle!(GLOBAL_RNG, a) - -""" - shuffle([rng=GLOBAL_RNG,] v) - -Return a randomly permuted copy of `v`. The optional `rng` argument specifies a random -number generator (see [Random Numbers](@ref)). -To permute `v` in-place, see [`shuffle!`](@ref). To obtain randomly permuted -indices, see [`randperm`](@ref). - -# Example - -```jldoctest -julia> rng = MersenneTwister(1234); - -julia> shuffle(rng, collect(1:10)) -10-element Array{Int64,1}: - 6 - 1 - 10 - 2 - 3 - 9 - 5 - 7 - 4 - 8 -``` -""" -shuffle(r::AbstractRNG, a::AbstractVector) = shuffle!(r, copymutable(a)) -shuffle(a::AbstractVector) = shuffle(GLOBAL_RNG, a) - -""" - randperm([rng=GLOBAL_RNG,] n::Integer) - -Construct a random permutation of length `n`. The optional `rng` argument specifies a random -number generator (see [Random Numbers](@ref)). -To randomly permute a arbitrary vector, see [`shuffle`](@ref) -or [`shuffle!`](@ref). - -# Example - -```jldoctest -julia> rng = MersenneTwister(1234); - -julia> randperm(rng, 4) -4-element Array{Int64,1}: - 2 - 1 - 4 - 3 -``` -""" -function randperm(r::AbstractRNG, n::Integer) - a = Vector{typeof(n)}(n) - @assert n <= Int64(2)^52 - if n == 0 - return a - end - a[1] = 1 - mask = 3 - @inbounds for i = 2:Int(n) - j = 1 + rand_lt(r, i, mask) - if i != j # a[i] is uninitialized (and could be #undef) - a[i] = a[j] - end - a[j] = i - i == 1+mask && (mask = 2mask + 1) - end - return a -end -randperm(n::Integer) = randperm(GLOBAL_RNG, n) - -""" - randcycle([rng=GLOBAL_RNG,] n::Integer) - -Construct a random cyclic permutation of length `n`. The optional `rng` -argument specifies a random number generator, see [Random Numbers](@ref). - -# Example - -```jldoctest -julia> rng = MersenneTwister(1234); - -julia> randcycle(rng, 6) -6-element Array{Int64,1}: - 3 - 5 - 4 - 6 - 1 - 2 -``` -""" -function randcycle(r::AbstractRNG, n::Integer) - a = Vector{typeof(n)}(n) - n == 0 && return a - @assert n <= Int64(2)^52 - a[1] = 1 - mask = 3 - @inbounds for i = 2:Int(n) - j = 1 + rand_lt(r, i-1, mask) - a[i] = a[j] - a[j] = i - i == 1+mask && (mask = 2mask + 1) - end - return a -end -randcycle(n::Integer) = randcycle(GLOBAL_RNG, n) - -end # module diff --git a/julia-0.6.3/share/julia/base/range.jl b/julia-0.6.3/share/julia/base/range.jl deleted file mode 100644 index eded200..0000000 --- a/julia-0.6.3/share/julia/base/range.jl +++ /dev/null @@ -1,911 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -colon(a::Real, b::Real) = colon(promote(a,b)...) - -colon(start::T, stop::T) where {T<:Real} = UnitRange{T}(start, stop) - -range(a::Real, len::Integer) = UnitRange{typeof(a)}(a, oftype(a, a+len-1)) - -colon(start::T, stop::T) where {T} = colon(start, oftype(stop-start, 1), stop) - -range(a, len::Integer) = range(a, oftype(a-a, 1), len) - -# first promote start and stop, leaving step alone -colon(start::A, step, stop::C) where {A<:Real,C<:Real} = - colon(convert(promote_type(A,C),start), step, convert(promote_type(A,C),stop)) -colon(start::T, step::Real, stop::T) where {T<:Real} = colon(promote(start, step, stop)...) - -""" - colon(start, [step], stop) - -Called by `:` syntax for constructing ranges. - -```jldoctest -julia> colon(1, 2, 5) -1:2:5 -``` -""" -colon(start::T, step::T, stop::T) where {T<:AbstractFloat} = - _colon(TypeOrder(T), TypeArithmetic(T), start, step, stop) -colon(start::T, step::T, stop::T) where {T<:Real} = - _colon(TypeOrder(T), TypeArithmetic(T), start, step, stop) -_colon(::HasOrder, ::Any, start::T, step, stop::T) where {T} = StepRange(start, step, stop) -# for T<:Union{Float16,Float32,Float64} see twiceprecision.jl -_colon(::HasOrder, ::ArithmeticRounds, start::T, step, stop::T) where {T} = - StepRangeLen(start, step, floor(Int, (stop-start)/step)+1) -_colon(::Any, ::Any, start::T, step, stop::T) where {T} = - StepRangeLen(start, step, floor(Int, (stop-start)/step)+1) - -""" - :(start, [step], stop) - -Range operator. `a:b` constructs a range from `a` to `b` with a step size of 1, and `a:s:b` -is similar but uses a step size of `s`. These syntaxes call the function `colon`. The colon -is also used in indexing to select whole dimensions. -""" -colon(start::T, step, stop::T) where {T} = _colon(start, step, stop) -colon(start::T, step, stop::T) where {T<:Real} = _colon(start, step, stop) -# without the second method above, the first method above is ambiguous with -# colon{A<:Real,C<:Real}(start::A, step, stop::C) -function _colon(start::T, step, stop::T) where T - T′ = typeof(start+step) - StepRange(convert(T′,start), step, convert(T′,stop)) -end - -""" - range(start, [step], length) - -Construct a range by length, given a starting value and optional step (defaults to 1). -""" -range(a::T, step, len::Integer) where {T} = _range(TypeOrder(T), TypeArithmetic(T), a, step, len) -_range(::HasOrder, ::ArithmeticOverflows, a::T, step::S, len::Integer) where {T,S} = - StepRange{T,S}(a, step, convert(T, a+step*(len-1))) -_range(::Any, ::Any, a::T, step::S, len::Integer) where {T,S} = - StepRangeLen{typeof(a+0*step),T,S}(a, step, len) - -# AbstractFloat specializations -colon(a::T, b::T) where {T<:AbstractFloat} = colon(a, T(1), b) -range(a::AbstractFloat, len::Integer) = range(a, oftype(a, 1), len) - -colon(a::T, b::AbstractFloat, c::T) where {T<:Real} = colon(promote(a,b,c)...) -colon(a::T, b::AbstractFloat, c::T) where {T<:AbstractFloat} = colon(promote(a,b,c)...) -colon(a::T, b::Real, c::T) where {T<:AbstractFloat} = colon(promote(a,b,c)...) - -range(a::AbstractFloat, st::AbstractFloat, len::Integer) = range(promote(a, st)..., len) -range(a::Real, st::AbstractFloat, len::Integer) = range(float(a), st, len) -range(a::AbstractFloat, st::Real, len::Integer) = range(a, float(st), len) - -## 1-dimensional ranges ## - -abstract type Range{T} <: AbstractArray{T,1} end - -## ordinal ranges - -abstract type OrdinalRange{T,S} <: Range{T} end -abstract type AbstractUnitRange{T} <: OrdinalRange{T,Int} end - -struct StepRange{T,S} <: OrdinalRange{T,S} - start::T - step::S - stop::T - - function StepRange{T,S}(start::T, step::S, stop::T) where {T,S} - new(start, step, steprange_last(start,step,stop)) - end -end - -# to make StepRange constructor inlineable, so optimizer can see `step` value -function steprange_last(start::T, step, stop) where T - if isa(start,AbstractFloat) || isa(step,AbstractFloat) - throw(ArgumentError("StepRange should not be used with floating point")) - end - z = zero(step) - step == z && throw(ArgumentError("step cannot be zero")) - - if stop == start - last = stop - else - if (step > z) != (stop > start) - last = steprange_last_empty(start, step, stop) - else - diff = stop - start - if T<:Signed && (diff > zero(diff)) != (stop > start) - # handle overflowed subtraction with unsigned rem - if diff > zero(diff) - remain = -convert(T, unsigned(-diff) % step) - else - remain = convert(T, unsigned(diff) % step) - end - else - remain = steprem(start,stop,step) - end - last = stop - remain - end - end - last -end - -function steprange_last_empty(start::Integer, step, stop) - # empty range has a special representation where stop = start-1 - # this is needed to avoid the wrap-around that can happen computing - # start - step, which leads to a range that looks very large instead - # of empty. - if step > zero(step) - last = start - oneunit(stop-start) - else - last = start + oneunit(stop-start) - end - last -end -# For types where x+oneunit(x) may not be well-defined -steprange_last_empty(start, step, stop) = start - step - -steprem(start,stop,step) = (stop-start) % step - -StepRange(start::T, step::S, stop::T) where {T,S} = StepRange{T,S}(start, step, stop) - -struct UnitRange{T<:Real} <: AbstractUnitRange{T} - start::T - stop::T - UnitRange{T}(start, stop) where {T<:Real} = new(start, unitrange_last(start,stop)) -end -UnitRange(start::T, stop::T) where {T<:Real} = UnitRange{T}(start, stop) - -unitrange_last(::Bool, stop::Bool) = stop -unitrange_last(start::T, stop::T) where {T<:Integer} = - ifelse(stop >= start, stop, convert(T,start-oneunit(stop-start))) -unitrange_last(start::T, stop::T) where {T} = - ifelse(stop >= start, convert(T,start+floor(stop-start)), - convert(T,start-oneunit(stop-start))) - -if isdefined(Main, :Base) - getindex(t::Tuple, r::AbstractUnitRange{<:Real}) = - (o = first(r) - 1; ntuple(n -> t[o + n], length(r))) -end - -""" - Base.OneTo(n) - -Define an `AbstractUnitRange` that behaves like `1:n`, with the added -distinction that the lower limit is guaranteed (by the type system) to -be 1. -""" -struct OneTo{T<:Integer} <: AbstractUnitRange{T} - stop::T - OneTo{T}(stop) where {T<:Integer} = new(max(zero(T), stop)) -end -OneTo(stop::T) where {T<:Integer} = OneTo{T}(stop) - -## Step ranges parametrized by length - -""" - StepRangeLen{T,R,S}(ref::R, step::S, len, [offset=1]) - -A range `r` where `r[i]` produces values of type `T`, parametrized by -a `ref`erence value, a `step`, and the `len`gth. By default `ref` is -the starting value `r[1]`, but alternatively you can supply it as the -value of `r[offset]` for some other index `1 <= offset <= len`. In -conjunction with `TwicePrecision` this can be used to implement ranges -that are free of roundoff error. -""" -struct StepRangeLen{T,R,S} <: Range{T} - ref::R # reference value (might be smallest-magnitude value in the range) - step::S # step value - len::Int # length of the range - offset::Int # the index of ref - - function StepRangeLen{T,R,S}(ref::R, step::S, len::Integer, offset::Integer = 1) where {T,R,S} - len >= 0 || throw(ArgumentError("length cannot be negative, got $len")) - 1 <= offset <= max(1,len) || throw(ArgumentError("StepRangeLen: offset must be in [1,$len], got $offset")) - new(ref, step, len, offset) - end -end - -StepRangeLen(ref::R, step::S, len::Integer, offset::Integer = 1) where {R,S} = - StepRangeLen{typeof(ref+0*step),R,S}(ref, step, len, offset) - -## linspace and logspace - -struct LinSpace{T} <: Range{T} - start::T - stop::T - len::Int - lendiv::Int - - function LinSpace{T}(start,stop,len) where T - len >= 0 || throw(ArgumentError("linspace($start, $stop, $len): negative length")) - if len == 1 - start == stop || throw(ArgumentError("linspace($start, $stop, $len): endpoints differ")) - return new(start, stop, 1, 1) - end - new(start,stop,len,max(len-1,1)) - end -end - -function LinSpace(start, stop, len::Integer) - T = typeof((stop-start)/len) - LinSpace{T}(start, stop, len) -end - -""" - linspace(start, stop, n=50) - -Construct a range of `n` linearly spaced elements from `start` to `stop`. - -```jldoctest -julia> linspace(1.3,2.9,9) -1.3:0.2:2.9 -``` -""" -linspace(start, stop, len::Real=50) = linspace(promote_noncircular(start, stop)..., Int(len)) -linspace(start::T, stop::T, len::Real=50) where {T} = linspace(start, stop, Int(len)) - -linspace(start::Real, stop::Real, len::Integer) = linspace(promote(start, stop)..., len) -linspace(start::T, stop::T, len::Integer) where {T<:Integer} = linspace(Float64, start, stop, len, 1) -# for Float16, Float32, and Float64 see twiceprecision.jl -linspace(start::T, stop::T, len::Integer) where {T<:Real} = LinSpace{T}(start, stop, len) -linspace(start::T, stop::T, len::Integer) where {T} = LinSpace{T}(start, stop, len) - -function show(io::IO, r::LinSpace) - print(io, "linspace(") - show(io, first(r)) - print(io, ',') - show(io, last(r)) - print(io, ',') - show(io, length(r)) - print(io, ')') -end - -""" -`print_range(io, r)` prints out a nice looking range r in terms of its elements -as if it were `collect(r)`, dependent on the size of the -terminal, and taking into account whether compact numbers should be shown. -It figures out the width in characters of each element, and if they -end up too wide, it shows the first and last elements separated by a -horizontal elipsis. Typical output will look like `1.0,2.0,3.0,…,4.0,5.0,6.0`. - -`print_range(io, r, pre, sep, post, hdots)` uses optional -parameters `pre` and `post` characters for each printed row, -`sep` separator string between printed elements, -`hdots` string for the horizontal ellipsis. -""" -function print_range(io::IO, r::Range, - pre::AbstractString = " ", - sep::AbstractString = ",", - post::AbstractString = "", - hdots::AbstractString = ",\u2026,") # horiz ellipsis - # This function borrows from print_matrix() in show.jl - # and should be called by show and display - limit = get(io, :limit, false) - sz = displaysize(io) - if !haskey(io, :compact) - io = IOContext(io, :compact => true) - end - screenheight, screenwidth = sz[1] - 4, sz[2] - screenwidth -= length(pre) + length(post) - postsp = "" - sepsize = length(sep) - m = 1 # treat the range as a one-row matrix - n = length(r) - # Figure out spacing alignments for r, but only need to examine the - # left and right edge columns, as many as could conceivably fit on the - # screen, with the middle columns summarized by horz, vert, or diag ellipsis - maxpossiblecols = div(screenwidth, 1+sepsize) # assume each element is at least 1 char + 1 separator - colsr = n <= maxpossiblecols ? (1:n) : [1:div(maxpossiblecols,2)+1; (n-div(maxpossiblecols,2)):n] - rowmatrix = reshape(r[colsr], 1, length(colsr)) # treat the range as a one-row matrix for print_matrix_row - A = alignment(io, rowmatrix, 1:m, 1:length(rowmatrix), screenwidth, screenwidth, sepsize) # how much space range takes - if n <= length(A) # cols fit screen, so print out all elements - print(io, pre) # put in pre chars - print_matrix_row(io,rowmatrix,A,1,1:n,sep) # the entire range - print(io, post) # add the post characters - else # cols don't fit so put horiz ellipsis in the middle - # how many chars left after dividing width of screen in half - # and accounting for the horiz ellipsis - c = div(screenwidth-length(hdots)+1,2)+1 # chars remaining for each side of rowmatrix - alignR = reverse(alignment(io, rowmatrix, 1:m, length(rowmatrix):-1:1, c, c, sepsize)) # which cols of rowmatrix to put on the right - c = screenwidth - sum(map(sum,alignR)) - (length(alignR)-1)*sepsize - length(hdots) - alignL = alignment(io, rowmatrix, 1:m, 1:length(rowmatrix), c, c, sepsize) # which cols of rowmatrix to put on the left - print(io, pre) # put in pre chars - print_matrix_row(io, rowmatrix,alignL,1,1:length(alignL),sep) # left part of range - print(io, hdots) # horizontal ellipsis - print_matrix_row(io, rowmatrix,alignR,1,length(rowmatrix)-length(alignR)+1:length(rowmatrix),sep) # right part of range - print(io, post) # post chars - end -end - -""" - logspace(start::Real, stop::Real, n::Integer=50) - -Construct a vector of `n` logarithmically spaced numbers from `10^start` to `10^stop`. - -```jldoctest -julia> logspace(1.,10.,5) -5-element Array{Float64,1}: - 10.0 - 1778.28 - 3.16228e5 - 5.62341e7 - 1.0e10 -``` -""" -logspace(start::Real, stop::Real, n::Integer=50) = 10.^linspace(start, stop, n) - -## interface implementations - -size(r::Range) = (length(r),) - -isempty(r::StepRange) = - (r.start != r.stop) & ((r.step > zero(r.step)) != (r.stop > r.start)) -isempty(r::AbstractUnitRange) = first(r) > last(r) -isempty(r::StepRangeLen) = length(r) == 0 -isempty(r::LinSpace) = length(r) == 0 - -""" - step(r) - -Get the step size of a `Range` object. -```jldoctest -julia> step(1:10) -1 - -julia> step(1:2:10) -2 - -julia> step(2.5:0.3:10.9) -0.3 - -julia> step(linspace(2.5,10.9,85)) -0.1 -``` -""" -step(r::StepRange) = r.step -step(r::AbstractUnitRange) = 1 -step(r::StepRangeLen) = r.step -step(r::LinSpace) = (last(r)-first(r))/r.lendiv - -unsafe_length(r::Range) = length(r) # generic fallback - -function unsafe_length(r::StepRange) - n = Integer(div(r.stop+r.step - r.start, r.step)) - isempty(r) ? zero(n) : n -end -length(r::StepRange) = unsafe_length(r) -unsafe_length(r::AbstractUnitRange) = Integer(last(r) - first(r) + 1) -unsafe_length(r::OneTo) = r.stop -length(r::AbstractUnitRange) = unsafe_length(r) -length(r::OneTo) = unsafe_length(r) -length(r::StepRangeLen) = r.len -length(r::LinSpace) = r.len - -function length{T<:Union{Int,UInt,Int64,UInt64}}(r::StepRange{T}) - isempty(r) && return zero(T) - if r.step > 1 - return checked_add(convert(T, div(unsigned(r.stop - r.start), r.step)), one(T)) - elseif r.step < -1 - return checked_add(convert(T, div(unsigned(r.start - r.stop), -r.step)), one(T)) - else - checked_add(div(checked_sub(r.stop, r.start), r.step), one(T)) - end -end - -function length{T<:Union{Int,Int64}}(r::AbstractUnitRange{T}) - @_inline_meta - checked_add(checked_sub(last(r), first(r)), one(T)) -end -length{T<:Union{Int,Int64}}(r::OneTo{T}) = T(r.stop) - -length{T<:Union{UInt,UInt64}}(r::AbstractUnitRange{T}) = - r.stop < r.start ? zero(T) : checked_add(last(r) - first(r), one(T)) - -# some special cases to favor default Int type -let smallint = (Int === Int64 ? - Union{Int8,UInt8,Int16,UInt16,Int32,UInt32} : - Union{Int8,UInt8,Int16,UInt16}) - global length - - function length(r::StepRange{<:smallint}) - isempty(r) && return Int(0) - div(Int(r.stop)+Int(r.step) - Int(r.start), Int(r.step)) - end - - length(r::AbstractUnitRange{<:smallint}) = Int(last(r)) - Int(first(r)) + 1 - length(r::OneTo{<:smallint}) = Int(r.stop) -end - -first(r::OrdinalRange{T}) where {T} = convert(T, r.start) -first(r::OneTo{T}) where {T} = oneunit(T) -first(r::StepRangeLen) = unsafe_getindex(r, 1) -first(r::LinSpace) = r.start - -last(r::OrdinalRange{T}) where {T} = convert(T, r.stop) -last(r::StepRangeLen) = unsafe_getindex(r, length(r)) -last(r::LinSpace) = r.stop - -minimum(r::AbstractUnitRange) = isempty(r) ? throw(ArgumentError("range must be non-empty")) : first(r) -maximum(r::AbstractUnitRange) = isempty(r) ? throw(ArgumentError("range must be non-empty")) : last(r) -minimum(r::Range) = isempty(r) ? throw(ArgumentError("range must be non-empty")) : min(first(r), last(r)) -maximum(r::Range) = isempty(r) ? throw(ArgumentError("range must be non-empty")) : max(first(r), last(r)) - -# Ranges are immutable -copy(r::Range) = r - - -## iteration - -start(r::LinSpace) = 1 -done(r::LinSpace, i::Int) = length(r) < i -function next(r::LinSpace, i::Int) - @_inline_meta - unsafe_getindex(r, i), i+1 -end - -start(r::StepRange) = oftype(r.start + r.step, r.start) -next(r::StepRange{T}, i) where {T} = (convert(T,i), i+r.step) -done(r::StepRange, i) = isempty(r) | (i < min(r.start, r.stop)) | (i > max(r.start, r.stop)) -done(r::StepRange, i::Integer) = - isempty(r) | (i == oftype(i, r.stop) + r.step) - -# see also twiceprecision.jl -start(r::StepRangeLen) = (unsafe_getindex(r, 1), 1) -next(r::StepRangeLen{T}, s) where {T} = s[1], (T(s[1]+r.step), s[2]+1) -done(r::StepRangeLen, s) = s[2] > length(r) - -start(r::UnitRange{T}) where {T} = oftype(r.start + oneunit(T), r.start) -next(r::AbstractUnitRange{T}, i) where {T} = (convert(T, i), i + oneunit(T)) -done(r::AbstractUnitRange{T}, i) where {T} = i == oftype(i, r.stop) + oneunit(T) - -start(r::OneTo{T}) where {T} = oneunit(T) - -# some special cases to favor default Int type to avoid overflow -let smallint = (Int === Int64 ? - Union{Int8,UInt8,Int16,UInt16,Int32,UInt32} : - Union{Int8,UInt8,Int16,UInt16}) - global start - global next - start(r::StepRange{<:smallint}) = convert(Int, r.start) - next(r::StepRange{T}, i) where {T<:smallint} = (i % T, i + r.step) - start(r::UnitRange{<:smallint}) = convert(Int, r.start) - next(r::AbstractUnitRange{T}, i) where {T<:smallint} = (i % T, i + 1) - start(r::OneTo{<:smallint}) = 1 -end - -## indexing - -function getindex(v::UnitRange{T}, i::Integer) where T - @_inline_meta - ret = convert(T, first(v) + i - 1) - @boundscheck ((i > 0) & (ret <= v.stop) & (ret >= v.start)) || throw_boundserror(v, i) - ret -end - -function getindex(v::OneTo{T}, i::Integer) where T - @_inline_meta - @boundscheck ((i > 0) & (i <= v.stop)) || throw_boundserror(v, i) - convert(T, i) -end - -function getindex(v::Range{T}, i::Integer) where T - @_inline_meta - ret = convert(T, first(v) + (i - 1)*step(v)) - ok = ifelse(step(v) > zero(step(v)), - (ret <= v.stop) & (ret >= v.start), - (ret <= v.start) & (ret >= v.stop)) - @boundscheck ((i > 0) & ok) || throw_boundserror(v, i) - ret -end - -function getindex(r::Union{StepRangeLen,LinSpace}, i::Integer) - @_inline_meta - @boundscheck checkbounds(r, i) - unsafe_getindex(r, i) -end - -# This is separate to make it useful even when running with --check-bounds=yes -function unsafe_getindex(r::StepRangeLen{T}, i::Integer) where T - u = i - r.offset - T(r.ref + u*r.step) -end - -function unsafe_getindex(r::LinSpace, i::Integer) - lerpi.(i-1, r.lendiv, r.start, r.stop) -end - -function lerpi{T}(j::Integer, d::Integer, a::T, b::T) - @_inline_meta - t = j/d - T((1-t)*a + t*b) -end - -getindex(r::Range, ::Colon) = copy(r) - -function getindex(r::AbstractUnitRange, s::AbstractUnitRange{<:Integer}) - @_inline_meta - @boundscheck checkbounds(r, s) - f = first(r) - st = oftype(f, f + first(s)-1) - range(st, length(s)) -end - -function getindex(r::OneTo{T}, s::OneTo) where T - @_inline_meta - @boundscheck checkbounds(r, s) - OneTo(T(s.stop)) -end - -function getindex(r::AbstractUnitRange, s::StepRange{<:Integer}) - @_inline_meta - @boundscheck checkbounds(r, s) - st = oftype(first(r), first(r) + s.start-1) - range(st, step(s), length(s)) -end - -function getindex(r::StepRange, s::Range{<:Integer}) - @_inline_meta - @boundscheck checkbounds(r, s) - st = oftype(r.start, r.start + (first(s)-1)*step(r)) - range(st, step(r)*step(s), length(s)) -end - -function getindex(r::StepRangeLen, s::OrdinalRange{<:Integer}) - @_inline_meta - @boundscheck checkbounds(r, s) - vfirst = unsafe_getindex(r, first(s)) - return StepRangeLen(vfirst, r.step*step(s), length(s)) -end - -function getindex(r::LinSpace, s::OrdinalRange{<:Integer}) - @_inline_meta - @boundscheck checkbounds(r, s) - vfirst = unsafe_getindex(r, first(s)) - vlast = unsafe_getindex(r, last(s)) - return LinSpace(vfirst, vlast, length(s)) -end - -show(io::IO, r::Range) = print(io, repr(first(r)), ':', repr(step(r)), ':', repr(last(r))) -show(io::IO, r::UnitRange) = print(io, repr(first(r)), ':', repr(last(r))) -show(io::IO, r::OneTo) = print(io, "Base.OneTo(", r.stop, ")") - -==(r::T, s::T) where {T<:Range} = - (first(r) == first(s)) & (step(r) == step(s)) & (last(r) == last(s)) -==(r::OrdinalRange, s::OrdinalRange) = - (first(r) == first(s)) & (step(r) == step(s)) & (last(r) == last(s)) -==(r::T, s::T) where {T<:Union{StepRangeLen,LinSpace}} = - (first(r) == first(s)) & (length(r) == length(s)) & (last(r) == last(s)) -==(r::Union{StepRange{T},StepRangeLen{T,T}}, s::Union{StepRange{T},StepRangeLen{T,T}}) where {T} = - (first(r) == first(s)) & (last(r) == last(s)) & (step(r) == step(s)) - -function ==(r::Range, s::Range) - lr = length(r) - if lr != length(s) - return false - end - u, v = start(r), start(s) - while !done(r, u) - x, u = next(r, u) - y, v = next(s, v) - if x != y - return false - end - end - return true -end - -intersect(r::OneTo, s::OneTo) = OneTo(min(r.stop,s.stop)) - -intersect(r::AbstractUnitRange{<:Integer}, s::AbstractUnitRange{<:Integer}) = max(first(r),first(s)):min(last(r),last(s)) - -intersect(i::Integer, r::AbstractUnitRange{<:Integer}) = - i < first(r) ? (first(r):i) : - i > last(r) ? (i:last(r)) : (i:i) - -intersect(r::AbstractUnitRange{<:Integer}, i::Integer) = intersect(i, r) - -function intersect(r::AbstractUnitRange{<:Integer}, s::StepRange{<:Integer}) - if isempty(s) - range(first(r), 0) - elseif step(s) == 0 - intersect(first(s), r) - elseif step(s) < 0 - intersect(r, reverse(s)) - else - sta = first(s) - ste = step(s) - sto = last(s) - lo = first(r) - hi = last(r) - i0 = max(sta, lo + mod(sta - lo, ste)) - i1 = min(sto, hi - mod(hi - sta, ste)) - i0:ste:i1 - end -end - -function intersect(r::StepRange{<:Integer}, s::AbstractUnitRange{<:Integer}) - if step(r) < 0 - reverse(intersect(s, reverse(r))) - else - intersect(s, r) - end -end - -function intersect(r::StepRange, s::StepRange) - if isempty(r) || isempty(s) - return range(first(r), step(r), 0) - elseif step(s) < 0 - return intersect(r, reverse(s)) - elseif step(r) < 0 - return reverse(intersect(reverse(r), s)) - end - - start1 = first(r) - step1 = step(r) - stop1 = last(r) - start2 = first(s) - step2 = step(s) - stop2 = last(s) - a = lcm(step1, step2) - - # if a == 0 - # # One or both ranges have step 0. - # if step1 == 0 && step2 == 0 - # return start1 == start2 ? r : Range(start1, 0, 0) - # elseif step1 == 0 - # return start2 <= start1 <= stop2 && rem(start1 - start2, step2) == 0 ? r : Range(start1, 0, 0) - # else - # return start1 <= start2 <= stop1 && rem(start2 - start1, step1) == 0 ? (start2:step1:start2) : Range(start1, step1, 0) - # end - # end - - g, x, y = gcdx(step1, step2) - - if rem(start1 - start2, g) != 0 - # Unaligned, no overlap possible. - return range(start1, a, 0) - end - - z = div(start1 - start2, g) - b = start1 - x * z * step1 - # Possible points of the intersection of r and s are - # ..., b-2a, b-a, b, b+a, b+2a, ... - # Determine where in the sequence to start and stop. - m = max(start1 + mod(b - start1, a), start2 + mod(b - start2, a)) - n = min(stop1 - mod(stop1 - b, a), stop2 - mod(stop2 - b, a)) - m:a:n -end - -function intersect(r1::Range, r2::Range, r3::Range, r::Range...) - i = intersect(intersect(r1, r2), r3) - for t in r - i = intersect(i, t) - end - i -end - -# findin (the index of intersection) -function _findin(r::Range{<:Integer}, span::AbstractUnitRange{<:Integer}) - local ifirst - local ilast - fspan = first(span) - lspan = last(span) - fr = first(r) - lr = last(r) - sr = step(r) - if sr > 0 - ifirst = fr >= fspan ? 1 : ceil(Integer,(fspan-fr)/sr)+1 - ilast = lr <= lspan ? length(r) : length(r) - ceil(Integer,(lr-lspan)/sr) - elseif sr < 0 - ifirst = fr <= lspan ? 1 : ceil(Integer,(lspan-fr)/sr)+1 - ilast = lr >= fspan ? length(r) : length(r) - ceil(Integer,(lr-fspan)/sr) - else - ifirst = fr >= fspan ? 1 : length(r)+1 - ilast = fr <= lspan ? length(r) : 0 - end - ifirst, ilast -end - -function findin(r::AbstractUnitRange{<:Integer}, span::AbstractUnitRange{<:Integer}) - ifirst, ilast = _findin(r, span) - ifirst:ilast -end - -function findin(r::Range{<:Integer}, span::AbstractUnitRange{<:Integer}) - ifirst, ilast = _findin(r, span) - ifirst:1:ilast -end - -## linear operations on ranges ## - --(r::OrdinalRange) = range(-first(r), -step(r), length(r)) --(r::StepRangeLen) = StepRangeLen(-r.ref, -r.step, length(r), r.offset) --(r::LinSpace) = LinSpace(-r.start, -r.stop, length(r)) - -+(x::Real, r::AbstractUnitRange) = range(x + first(r), length(r)) -# For #18336 we need to prevent promotion of the step type: -+(x::Number, r::AbstractUnitRange) = range(x + first(r), step(r), length(r)) -+(x::Number, r::Range) = (x+first(r)):step(r):(x+last(r)) -function +(x::Number, r::StepRangeLen) - newref = x + r.ref - StepRangeLen{eltype(newref),typeof(newref),typeof(r.step)}(newref, r.step, length(r), r.offset) -end -function +(x::Number, r::LinSpace) - LinSpace(x + r.start, x + r.stop, r.len) -end -+(r::Range, x::Number) = x + r # assumes addition is commutative - --(x::Number, r::Range) = (x-first(r)):-step(r):(x-last(r)) --(x::Number, r::StepRangeLen) = +(x, -r) -function -(x::Number, r::LinSpace) - LinSpace(x - r.start, x - r.stop, r.len) -end - --(r::Range, x::Number) = +(-x, r) - -*(x::Number, r::Range) = range(x*first(r), x*step(r), length(r)) -*(x::Number, r::StepRangeLen) = StepRangeLen(x*r.ref, x*r.step, length(r), r.offset) -*(x::Number, r::LinSpace) = LinSpace(x * r.start, x * r.stop, r.len) -# separate in case of noncommutative multiplication -*(r::Range, x::Number) = range(first(r)*x, step(r)*x, length(r)) -*(r::StepRangeLen, x::Number) = StepRangeLen(r.ref*x, r.step*x, length(r), r.offset) -*(r::LinSpace, x::Number) = LinSpace(r.start * x, r.stop * x, r.len) - -/(r::Range, x::Number) = range(first(r)/x, step(r)/x, length(r)) -/(r::StepRangeLen, x::Number) = StepRangeLen(r.ref/x, r.step/x, length(r), r.offset) -/(r::LinSpace, x::Number) = LinSpace(r.start / x, r.stop / x, r.len) - -/(x::Number, r::Range) = [ x/y for y=r ] - -promote_rule(::Type{UnitRange{T1}},::Type{UnitRange{T2}}) where {T1,T2} = - UnitRange{promote_type(T1,T2)} -convert(::Type{UnitRange{T}}, r::UnitRange{T}) where {T<:Real} = r -convert(::Type{UnitRange{T}}, r::UnitRange) where {T<:Real} = UnitRange{T}(r.start, r.stop) - -promote_rule(::Type{OneTo{T1}},::Type{OneTo{T2}}) where {T1,T2} = - OneTo{promote_type(T1,T2)} -convert(::Type{OneTo{T}}, r::OneTo{T}) where {T<:Real} = r -convert(::Type{OneTo{T}}, r::OneTo) where {T<:Real} = OneTo{T}(r.stop) - -promote_rule(::Type{UnitRange{T1}}, ::Type{UR}) where {T1,UR<:AbstractUnitRange} = - UnitRange{promote_type(T1,eltype(UR))} -convert(::Type{UnitRange{T}}, r::AbstractUnitRange) where {T<:Real} = UnitRange{T}(first(r), last(r)) -convert(::Type{UnitRange}, r::AbstractUnitRange) = UnitRange(first(r), last(r)) - -promote_rule(::Type{StepRange{T1a,T1b}},::Type{StepRange{T2a,T2b}}) where {T1a,T1b,T2a,T2b} = - StepRange{promote_type(T1a,T2a),promote_type(T1b,T2b)} -convert(::Type{StepRange{T1,T2}}, r::StepRange{T1,T2}) where {T1,T2} = r - -promote_rule(::Type{StepRange{T1a,T1b}},::Type{UR}) where {T1a,T1b,UR<:AbstractUnitRange} = - StepRange{promote_type(T1a,eltype(UR)),promote_type(T1b,eltype(UR))} -convert(::Type{StepRange{T1,T2}}, r::Range) where {T1,T2} = - StepRange{T1,T2}(convert(T1, first(r)), convert(T2, step(r)), convert(T1, last(r))) -convert(::Type{StepRange}, r::AbstractUnitRange{T}) where {T} = - StepRange{T,T}(first(r), step(r), last(r)) - -promote_rule(::Type{StepRangeLen{T1,R1,S1}},::Type{StepRangeLen{T2,R2,S2}}) where {T1,T2,R1,R2,S1,S2} = - StepRangeLen{promote_type(T1,T2), promote_type(R1,R2), promote_type(S1,S2)} -convert(::Type{StepRangeLen{T,R,S}}, r::StepRangeLen{T,R,S}) where {T,R,S} = r -convert(::Type{StepRangeLen{T,R,S}}, r::StepRangeLen) where {T,R,S} = - StepRangeLen{T,R,S}(convert(R, r.ref), convert(S, r.step), length(r), r.offset) -convert(::Type{StepRangeLen{T}}, r::StepRangeLen) where {T} = - StepRangeLen(convert(T, r.ref), convert(T, r.step), length(r), r.offset) - -promote_rule(::Type{StepRangeLen{T,R,S}}, ::Type{OR}) where {T,R,S,OR<:Range} = - StepRangeLen{promote_type(T,eltype(OR)),promote_type(R,eltype(OR)),promote_type(S,eltype(OR))} -convert(::Type{StepRangeLen{T,R,S}}, r::Range) where {T,R,S} = - StepRangeLen{T,R,S}(R(first(r)), S(step(r)), length(r)) -convert(::Type{StepRangeLen{T}}, r::Range) where {T} = - StepRangeLen(T(first(r)), T(step(r)), length(r)) -convert(::Type{StepRangeLen}, r::Range) = convert(StepRangeLen{eltype(r)}, r) - -promote_rule(::Type{LinSpace{T1}},::Type{LinSpace{T2}}) where {T1,T2} = - LinSpace{promote_type(T1,T2)} -convert(::Type{LinSpace{T}}, r::LinSpace{T}) where {T} = r -convert(::Type{LinSpace{T}}, r::Range) where {T} = - LinSpace{T}(first(r), last(r), length(r)) -convert(::Type{LinSpace}, r::Range{T}) where {T} = - convert(LinSpace{T}, r) - -promote_rule(::Type{LinSpace{T}}, ::Type{OR}) where {T,OR<:OrdinalRange} = - LinSpace{promote_type(T,eltype(OR))} - -promote_rule(::Type{LinSpace{L}}, ::Type{StepRangeLen{T,R,S}}) where {L,T,R,S} = - StepRangeLen{promote_type(L,T),promote_type(L,R),promote_type(L,S)} - -# +/- of ranges is defined in operators.jl (to be able to use @eval etc.) - -## concatenation ## - -function vcat(rs::Range{T}...) where T - n::Int = 0 - for ra in rs - n += length(ra) - end - a = Vector{T}(n) - i = 1 - for ra in rs, x in ra - @inbounds a[i] = x - i += 1 - end - return a -end - -convert(::Type{Array{T,1}}, r::Range{T}) where {T} = vcat(r) -collect(r::Range) = vcat(r) - -reverse(r::OrdinalRange) = colon(last(r), -step(r), first(r)) -reverse(r::StepRangeLen) = StepRangeLen(r.ref, -r.step, length(r), length(r)-r.offset+1) -reverse(r::LinSpace) = LinSpace(r.stop, r.start, length(r)) - -## sorting ## - -issorted(r::AbstractUnitRange) = true -issorted(r::Range) = length(r) <= 1 || step(r) >= zero(step(r)) - -sort(r::AbstractUnitRange) = r -sort!(r::AbstractUnitRange) = r - -sort(r::Range) = issorted(r) ? r : reverse(r) - -sortperm(r::AbstractUnitRange) = 1:length(r) -sortperm(r::Range) = issorted(r) ? (1:1:length(r)) : (length(r):-1:1) - -function sum(r::Range{<:Real}) - l = length(r) - # note that a little care is required to avoid overflow in l*(l-1)/2 - return l * first(r) + (iseven(l) ? (step(r) * (l-1)) * (l>>1) - : (step(r) * l) * ((l-1)>>1)) -end - -function mean(r::Range{<:Real}) - isempty(r) && throw(ArgumentError("mean of an empty range is undefined")) - (first(r) + last(r)) / 2 -end - -median(r::Range{<:Real}) = mean(r) - -function in(x, r::Range) - n = step(r) == 0 ? 1 : round(Integer,(x-first(r))/step(r))+1 - n >= 1 && n <= length(r) && r[n] == x -end - -in(x::Integer, r::AbstractUnitRange{<:Integer}) = (first(r) <= x) & (x <= last(r)) -in(x, r::Range{T}) where {T<:Integer} = - isinteger(x) && !isempty(r) && x >= minimum(r) && x <= maximum(r) && - (mod(convert(T,x),step(r))-mod(first(r),step(r)) == 0) -in(x::Char, r::Range{Char}) = - !isempty(r) && x >= minimum(r) && x <= maximum(r) && - (mod(Int(x) - Int(first(r)), step(r)) == 0) - -# Addition/subtraction of ranges - -function _define_range_op(f::ANY) - @eval begin - function $f(r1::OrdinalRange, r2::OrdinalRange) - r1l = length(r1) - (r1l == length(r2) || - throw(DimensionMismatch("argument dimensions must match"))) - range($f(first(r1),first(r2)), $f(step(r1),step(r2)), r1l) - end - - function $f(r1::LinSpace{T}, r2::LinSpace{T}) where T - len = r1.len - (len == r2.len || - throw(DimensionMismatch("argument dimensions must match"))) - linspace(convert(T, $f(first(r1), first(r2))), - convert(T, $f(last(r1), last(r2))), len) - end - - $f(r1::Union{StepRangeLen, OrdinalRange, LinSpace}, - r2::Union{StepRangeLen, OrdinalRange, LinSpace}) = - $f(promote_noncircular(r1, r2)...) - end -end -_define_range_op(:+) -_define_range_op(:-) - -function +(r1::StepRangeLen{T,S}, r2::StepRangeLen{T,S}) where {T,S} - len = length(r1) - (len == length(r2) || - throw(DimensionMismatch("argument dimensions must match"))) - StepRangeLen(first(r1)+first(r2), step(r1)+step(r2), len) -end - --(r1::StepRangeLen, r2::StepRangeLen) = +(r1, -r2) diff --git a/julia-0.6.3/share/julia/base/rational.jl b/julia-0.6.3/share/julia/base/rational.jl deleted file mode 100644 index 803d0c2..0000000 --- a/julia-0.6.3/share/julia/base/rational.jl +++ /dev/null @@ -1,436 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -""" - Rational{T<:Integer} <: Real - -Rational number type, with numerator and denominator of type `T`. -""" -struct Rational{T<:Integer} <: Real - num::T - den::T - - function Rational{T}(num::Integer, den::Integer) where T<:Integer - num == den == zero(T) && throw(ArgumentError("invalid rational: zero($T)//zero($T)")) - g = den < 0 ? -gcd(den, num) : gcd(den, num) - new(div(num, g), div(den, g)) - end -end -Rational(n::T, d::T) where {T<:Integer} = Rational{T}(n,d) -Rational(n::Integer, d::Integer) = Rational(promote(n,d)...) -Rational(n::Integer) = Rational(n,one(n)) - -function divgcd(x::Integer,y::Integer) - g = gcd(x,y) - div(x,g), div(y,g) -end - -""" - //(num, den) - -Divide two integers or rational numbers, giving a [`Rational`](@ref) result. - -```jldoctest -julia> 3 // 5 -3//5 - -julia> (3 // 5) // (2 // 1) -3//10 -``` -""" -//(n::Integer, d::Integer ) = Rational(n,d) - -function //(x::Rational, y::Integer ) - xn,yn = divgcd(x.num,y) - xn//checked_mul(x.den,yn) -end -function //(x::Integer, y::Rational) - xn,yn = divgcd(x,y.num) - checked_mul(xn,y.den)//yn -end -function //(x::Rational, y::Rational) - xn,yn = divgcd(x.num,y.num) - xd,yd = divgcd(x.den,y.den) - checked_mul(xn,yd)//checked_mul(xd,yn) -end - -//(x::Complex, y::Real) = complex(real(x)//y,imag(x)//y) -//(x::Number, y::Complex) = x*y'//abs2(y) - - -//(X::AbstractArray, y::Number) = X .// y - -function show(io::IO, x::Rational) - show(io, numerator(x)) - print(io, "//") - show(io, denominator(x)) -end - -function read(s::IO, ::Type{Rational{T}}) where T<:Integer - r = read(s,T) - i = read(s,T) - r//i -end -function write(s::IO, z::Rational) - write(s,numerator(z),denominator(z)) -end - -convert(::Type{Rational{T}}, x::Rational) where {T<:Integer} = Rational{T}(convert(T,x.num),convert(T,x.den)) -convert(::Type{Rational{T}}, x::Integer) where {T<:Integer} = Rational{T}(convert(T,x), convert(T,1)) - -convert(::Type{Rational}, x::Rational) = x -convert(::Type{Rational}, x::Integer) = convert(Rational{typeof(x)},x) - -convert(::Type{Bool}, x::Rational) = x==0 ? false : x==1 ? true : throw(InexactError()) # to resolve ambiguity -convert(::Type{Integer}, x::Rational) = (isinteger(x) ? convert(Integer, x.num) : throw(InexactError())) -convert(::Type{T}, x::Rational) where {T<:Integer} = (isinteger(x) ? convert(T, x.num) : throw(InexactError())) - -convert(::Type{AbstractFloat}, x::Rational) = float(x.num)/float(x.den) -function convert(::Type{T}, x::Rational{S}) where T<:AbstractFloat where S - P = promote_type(T,S) - convert(T, convert(P,x.num)/convert(P,x.den)) -end - -function convert(::Type{Rational{T}}, x::AbstractFloat) where T<:Integer - r = rationalize(T, x, tol=0) - x == convert(typeof(x), r) || throw(InexactError()) - r -end -convert(::Type{Rational}, x::Float64) = convert(Rational{Int64}, x) -convert(::Type{Rational}, x::Float32) = convert(Rational{Int}, x) - -big(z::Complex{<:Rational{<:Integer}}) = Complex{Rational{BigInt}}(z) - -promote_rule(::Type{Rational{T}}, ::Type{S}) where {T<:Integer,S<:Integer} = Rational{promote_type(T,S)} -promote_rule(::Type{Rational{T}}, ::Type{Rational{S}}) where {T<:Integer,S<:Integer} = Rational{promote_type(T,S)} -promote_rule(::Type{Rational{T}}, ::Type{S}) where {T<:Integer,S<:AbstractFloat} = promote_type(T,S) - -widen(::Type{Rational{T}}) where {T} = Rational{widen(T)} - -""" - rationalize([T<:Integer=Int,] x; tol::Real=eps(x)) - -Approximate floating point number `x` as a [`Rational`](@ref) number with components -of the given integer type. The result will differ from `x` by no more than `tol`. -If `T` is not provided, it defaults to `Int`. - -```jldoctest -julia> rationalize(5.6) -28//5 - -julia> a = rationalize(BigInt, 10.3) -103//10 - -julia> typeof(numerator(a)) -BigInt -``` -""" -function rationalize(::Type{T}, x::AbstractFloat, tol::Real) where T<:Integer - if tol < 0 - throw(ArgumentError("negative tolerance $tol")) - end - isnan(x) && return zero(T)//zero(T) - isinf(x) && return (x < 0 ? -one(T) : one(T))//zero(T) - - p, q = (x < 0 ? -one(T) : one(T)), zero(T) - pp, qq = zero(T), one(T) - - x = abs(x) - a = trunc(x) - r = x-a - y = one(x) - - tolx = oftype(x, tol) - nt, t, tt = tolx, zero(tolx), tolx - ia = np = nq = zero(T) - - # compute the successive convergents of the continued fraction - # np // nq = (p*a + pp) // (q*a + qq) - while r > nt - try - ia = convert(T,a) - - np = checked_add(checked_mul(ia,p),pp) - nq = checked_add(checked_mul(ia,q),qq) - p, pp = np, p - q, qq = nq, q - catch e - isa(e,InexactError) || isa(e,OverflowError) || rethrow(e) - return p // q - end - - # naive approach of using - # x = 1/r; a = trunc(x); r = x - a - # is inexact, so we store x as x/y - x, y = y, r - a, r = divrem(x,y) - - # maintain - # x0 = (p + (-1)^i * r) / q - t, tt = nt, t - nt = a*t+tt - end - - # find optimal semiconvergent - # smallest a such that x-a*y < a*t+tt - a = cld(x-tt,y+t) - try - ia = convert(T,a) - np = checked_add(checked_mul(ia,p),pp) - nq = checked_add(checked_mul(ia,q),qq) - return np // nq - catch e - isa(e,InexactError) || isa(e,OverflowError) || rethrow(e) - return p // q - end -end -rationalize(::Type{T}, x::AbstractFloat; tol::Real = eps(x)) where {T<:Integer} = rationalize(T, x, tol)::Rational{T} -rationalize(x::AbstractFloat; kvs...) = rationalize(Int, x; kvs...) - -""" - numerator(x) - -Numerator of the rational representation of `x`. - -```jldoctest -julia> numerator(2//3) -2 - -julia> numerator(4) -4 -``` -""" -numerator(x::Integer) = x -numerator(x::Rational) = x.num - -""" - denominator(x) - -Denominator of the rational representation of `x`. - -```jldoctest -julia> denominator(2//3) -3 - -julia> denominator(4) -1 -``` -""" -denominator(x::Integer) = one(x) -denominator(x::Rational) = x.den - -sign(x::Rational) = oftype(x, sign(x.num)) -signbit(x::Rational) = signbit(x.num) -copysign(x::Rational, y::Real) = copysign(x.num,y) // x.den -copysign(x::Rational, y::Rational) = copysign(x.num,y.num) // x.den - -typemin(::Type{Rational{T}}) where {T<:Integer} = -one(T)//zero(T) -typemax(::Type{Rational{T}}) where {T<:Integer} = one(T)//zero(T) - -isinteger(x::Rational) = x.den == 1 - --(x::Rational) = (-x.num) // x.den -function -(x::Rational{T}) where T<:Signed - x.num == typemin(T) && throw(OverflowError()) - (-x.num) // x.den -end -function -(x::Rational{T}) where T<:Unsigned - x.num != zero(T) && throw(OverflowError()) - x -end - -for (op,chop) in ((:+,:checked_add), (:-,:checked_sub), - (:rem,:rem), (:mod,:mod)) - @eval begin - function ($op)(x::Rational, y::Rational) - xd, yd = divgcd(x.den, y.den) - Rational(($chop)(checked_mul(x.num,yd), checked_mul(y.num,xd)), checked_mul(x.den,yd)) - end - end -end - -function *(x::Rational, y::Rational) - xn,yd = divgcd(x.num,y.den) - xd,yn = divgcd(x.den,y.num) - checked_mul(xn,yn) // checked_mul(xd,yd) -end -/(x::Rational, y::Rational) = x//y -/(x::Rational, y::Complex{<:Union{Integer,Rational}}) = x//y - -fma(x::Rational, y::Rational, z::Rational) = x*y+z - -==(x::Rational, y::Rational) = (x.den == y.den) & (x.num == y.num) -<( x::Rational, y::Rational) = x.den == y.den ? x.num < y.num : - widemul(x.num,y.den) < widemul(x.den,y.num) -<=(x::Rational, y::Rational) = x.den == y.den ? x.num <= y.num : - widemul(x.num,y.den) <= widemul(x.den,y.num) - - -==(x::Rational, y::Integer ) = (x.den == 1) & (x.num == y) -==(x::Integer , y::Rational) = y == x -<( x::Rational, y::Integer ) = x.num < widemul(x.den,y) -<( x::Integer , y::Rational) = widemul(x,y.den) < y.num -<=(x::Rational, y::Integer ) = x.num <= widemul(x.den,y) -<=(x::Integer , y::Rational) = widemul(x,y.den) <= y.num - -function ==(x::AbstractFloat, q::Rational) - if isfinite(x) - (count_ones(q.den) == 1) & (x*q.den == q.num) - else - x == q.num/q.den - end -end - -==(q::Rational, x::AbstractFloat) = x == q - -for rel in (:<,:<=,:cmp) - for (Tx,Ty) in ((Rational,AbstractFloat), (AbstractFloat,Rational)) - @eval function ($rel)(x::$Tx, y::$Ty) - if isnan(x) || isnan(y) - $(rel == :cmp ? :(throw(DomainError())) : :(return false)) - end - - xn, xp, xd = decompose(x) - yn, yp, yd = decompose(y) - - if xd < 0 - xn = -xn - xd = -xd - end - if yd < 0 - yn = -yn - yd = -yd - end - - xc, yc = widemul(xn,yd), widemul(yn,xd) - xs, ys = sign(xc), sign(yc) - - if xs != ys - return ($rel)(xs,ys) - elseif xs == 0 - # both are zero or ±Inf - return ($rel)(xn,yn) - end - - xb, yb = ndigits0z(xc,2) + xp, ndigits0z(yc,2) + yp - - if xb == yb - xc, yc = promote(xc,yc) - if xp > yp - xc = (xc<<(xp-yp)) - else - yc = (yc<<(yp-xp)) - end - return ($rel)(xc,yc) - else - return xc > 0 ? ($rel)(xb,yb) : ($rel)(yb,xb) - end - end - end -end - -# needed to avoid ambiguity between ==(x::Real, z::Complex) and ==(x::Rational, y::Number) -==(z::Complex , x::Rational) = isreal(z) & (real(z) == x) -==(x::Rational, z::Complex ) = isreal(z) & (real(z) == x) - -for op in (:div, :fld, :cld) - @eval begin - function ($op)(x::Rational, y::Integer ) - xn,yn = divgcd(x.num,y) - ($op)(xn, checked_mul(x.den,yn)) - end - function ($op)(x::Integer, y::Rational) - xn,yn = divgcd(x,y.num) - ($op)(checked_mul(xn,y.den), yn) - end - function ($op)(x::Rational, y::Rational) - xn,yn = divgcd(x.num,y.num) - xd,yd = divgcd(x.den,y.den) - ($op)(checked_mul(xn,yd), checked_mul(xd,yn)) - end - end -end - -trunc(::Type{T}, x::Rational) where {T} = convert(T,div(x.num,x.den)) -floor(::Type{T}, x::Rational) where {T} = convert(T,fld(x.num,x.den)) -ceil(::Type{T}, x::Rational) where {T} = convert(T,cld(x.num,x.den)) - - -function round(::Type{T}, x::Rational{Tr}, ::RoundingMode{:Nearest}) where {T,Tr} - if denominator(x) == zero(Tr) && T <: Integer - throw(DivideError()) - elseif denominator(x) == zero(Tr) - return convert(T, copysign(one(Tr)//zero(Tr), numerator(x))) - end - q,r = divrem(numerator(x), denominator(x)) - s = q - if abs(r) >= abs((denominator(x)-copysign(Tr(4), numerator(x))+one(Tr)+iseven(q))>>1 + copysign(Tr(2), numerator(x))) - s += copysign(one(Tr),numerator(x)) - end - convert(T, s) -end - -round(::Type{T}, x::Rational) where {T} = round(T, x, RoundNearest) - -function round(::Type{T}, x::Rational{Tr}, ::RoundingMode{:NearestTiesAway}) where {T,Tr} - if denominator(x) == zero(Tr) && T <: Integer - throw(DivideError()) - elseif denominator(x) == zero(Tr) - return convert(T, copysign(one(Tr)//zero(Tr), numerator(x))) - end - q,r = divrem(numerator(x), denominator(x)) - s = q - if abs(r) >= abs((denominator(x)-copysign(Tr(4), numerator(x))+one(Tr))>>1 + copysign(Tr(2), numerator(x))) - s += copysign(one(Tr),numerator(x)) - end - convert(T, s) -end - -function round(::Type{T}, x::Rational{Tr}, ::RoundingMode{:NearestTiesUp}) where {T,Tr} - if denominator(x) == zero(Tr) && T <: Integer - throw(DivideError()) - elseif denominator(x) == zero(Tr) - return convert(T, copysign(one(Tr)//zero(Tr), numerator(x))) - end - q,r = divrem(numerator(x), denominator(x)) - s = q - if abs(r) >= abs((denominator(x)-copysign(Tr(4), numerator(x))+one(Tr)+(numerator(x)<0))>>1 + copysign(Tr(2), numerator(x))) - s += copysign(one(Tr),numerator(x)) - end - convert(T, s) -end - -function round(::Type{T}, x::Rational{Bool}) where T - if denominator(x) == false && issubtype(T, Union{Integer, Bool}) - throw(DivideError()) - end - convert(T, x) -end - -round(::Type{T}, x::Rational{Bool}, ::RoundingMode{:Nearest}) where {T} = round(T, x) -round(::Type{T}, x::Rational{Bool}, ::RoundingMode{:NearestTiesAway}) where {T} = round(T, x) -round(::Type{T}, x::Rational{Bool}, ::RoundingMode{:NearestTiesUp}) where {T} = round(T, x) -round(::Type{T}, x::Rational{Bool}, ::RoundingMode) where {T} = round(T, x) - -trunc(x::Rational{T}) where {T} = Rational(trunc(T,x)) -floor(x::Rational{T}) where {T} = Rational(floor(T,x)) -ceil(x::Rational{T}) where {T} = Rational(ceil(T,x)) -round(x::Rational{T}) where {T} = Rational(round(T,x)) - -function ^(x::Rational, n::Integer) - n >= 0 ? power_by_squaring(x,n) : power_by_squaring(inv(x),-n) -end - -^(x::Number, y::Rational) = x^(y.num/y.den) -^(x::T, y::Rational) where {T<:AbstractFloat} = x^convert(T,y) -^(x::Complex{T}, y::Rational) where {T<:AbstractFloat} = x^convert(T,y) - -^(z::Complex{<:Rational}, n::Bool) = n ? z : one(z) # to resolve ambiguity -function ^(z::Complex{<:Rational}, n::Integer) - n >= 0 ? power_by_squaring(z,n) : power_by_squaring(inv(z),-n) -end - -iszero(x::Rational) = iszero(numerator(x)) - -function lerpi(j::Integer, d::Integer, a::Rational, b::Rational) - ((d-j)*a)/d + (j*b)/d -end diff --git a/julia-0.6.3/share/julia/base/reduce.jl b/julia-0.6.3/share/julia/base/reduce.jl deleted file mode 100644 index a8b3e80..0000000 --- a/julia-0.6.3/share/julia/base/reduce.jl +++ /dev/null @@ -1,722 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -## reductions ## - -###### Generic (map)reduce functions ###### - -if Int === Int32 -const SmallSigned = Union{Int8,Int16} -const SmallUnsigned = Union{UInt8,UInt16} -else -const SmallSigned = Union{Int8,Int16,Int32} -const SmallUnsigned = Union{UInt8,UInt16,UInt32} -end - -const CommonReduceResult = Union{UInt64,UInt128,Int64,Int128,Float32,Float64} -const WidenReduceResult = Union{SmallSigned, SmallUnsigned, Float16} - -# r_promote_type: promote T to the type of reduce(op, ::Array{T}) -# (some "extra" methods are required here to avoid ambiguity warnings) -r_promote_type(op, ::Type{T}) where {T} = T -r_promote_type(op, ::Type{T}) where {T<:WidenReduceResult} = widen(T) -r_promote_type(::typeof(+), ::Type{T}) where {T<:WidenReduceResult} = widen(T) -r_promote_type(::typeof(*), ::Type{T}) where {T<:WidenReduceResult} = widen(T) -r_promote_type(::typeof(+), ::Type{T}) where {T<:Number} = typeof(zero(T)+zero(T)) -r_promote_type(::typeof(*), ::Type{T}) where {T<:Number} = typeof(one(T)*one(T)) -r_promote_type(::typeof(scalarmax), ::Type{T}) where {T<:WidenReduceResult} = T -r_promote_type(::typeof(scalarmin), ::Type{T}) where {T<:WidenReduceResult} = T -r_promote_type(::typeof(max), ::Type{T}) where {T<:WidenReduceResult} = T -r_promote_type(::typeof(min), ::Type{T}) where {T<:WidenReduceResult} = T - -# r_promote: promote x to the type of reduce(op, [x]) -r_promote(op, x::T) where {T} = convert(r_promote_type(op, T), x) - -## foldl && mapfoldl - -function mapfoldl_impl(f, op, v0, itr, i) - # Unroll the while loop once; if v0 is known, the call to op may - # be evaluated at compile time - if done(itr, i) - return r_promote(op, v0) - else - (x, i) = next(itr, i) - v = op(r_promote(op, v0), f(x)) - while !done(itr, i) - @inbounds (x, i) = next(itr, i) - v = op(v, f(x)) - end - return v - end -end - -""" - mapfoldl(f, op, v0, itr) - -Like [`mapreduce`](@ref), but with guaranteed left associativity, as in [`foldl`](@ref). -`v0` will be used exactly once. -""" -mapfoldl(f, op, v0, itr) = mapfoldl_impl(f, op, v0, itr, start(itr)) - -""" - mapfoldl(f, op, itr) - -Like `mapfoldl(f, op, v0, itr)`, but using the first element of `itr` as `v0`. In general, -this cannot be used with empty collections (see `reduce(op, itr)`). -""" -function mapfoldl(f, op, itr) - i = start(itr) - if done(itr, i) - return Base.mr_empty_iter(f, op, itr, iteratoreltype(itr)) - end - (x, i) = next(itr, i) - v0 = f(x) - mapfoldl_impl(f, op, v0, itr, i) -end - -""" - foldl(op, v0, itr) - -Like [`reduce`](@ref), but with guaranteed left associativity. `v0` will be used -exactly once. - -```jldoctest -julia> foldl(-, 1, 2:5) --13 -``` -""" -foldl(op, v0, itr) = mapfoldl(identity, op, v0, itr) - -""" - foldl(op, itr) - -Like `foldl(op, v0, itr)`, but using the first element of `itr` as `v0`. In general, this -cannot be used with empty collections (see `reduce(op, itr)`). - -```jldoctest -julia> foldl(-, 2:5) --10 -``` -""" -foldl(op, itr) = mapfoldl(identity, op, itr) - -## foldr & mapfoldr - -function mapfoldr_impl(f, op, v0, itr, i::Integer) - # Unroll the while loop once; if v0 is known, the call to op may - # be evaluated at compile time - if isempty(itr) || i == 0 - return r_promote(op, v0) - else - x = itr[i] - v = op(f(x), r_promote(op, v0)) - while i > 1 - x = itr[i -= 1] - v = op(f(x), v) - end - return v - end -end - -""" - mapfoldr(f, op, v0, itr) - -Like [`mapreduce`](@ref), but with guaranteed right associativity, as in [`foldr`](@ref). -`v0` will be used exactly once. -""" -mapfoldr(f, op, v0, itr) = mapfoldr_impl(f, op, v0, itr, endof(itr)) - -""" - mapfoldr(f, op, itr) - -Like `mapfoldr(f, op, v0, itr)`, but using the first element of `itr` as `v0`. In general, -this cannot be used with empty collections (see `reduce(op, itr)`). -""" -function mapfoldr(f, op, itr) - i = endof(itr) - if isempty(itr) - return Base.mr_empty_iter(f, op, itr, iteratoreltype(itr)) - end - return mapfoldr_impl(f, op, f(itr[i]), itr, i-1) -end - -""" - foldr(op, v0, itr) - -Like [`reduce`](@ref), but with guaranteed right associativity. `v0` will be used -exactly once. - -```jldoctest -julia> foldr(-, 1, 2:5) --1 -``` -""" -foldr(op, v0, itr) = mapfoldr(identity, op, v0, itr) - -""" - foldr(op, itr) - -Like `foldr(op, v0, itr)`, but using the last element of `itr` as `v0`. In general, this -cannot be used with empty collections (see `reduce(op, itr)`). - -```jldoctest -julia> foldr(-, 2:5) --2 -``` -""" -foldr(op, itr) = mapfoldr(identity, op, itr) - -## reduce & mapreduce - -# `mapreduce_impl()` is called by `mapreduce()` (via `_mapreduce()`, when `A` -# supports linear indexing) and does actual calculations (for `A[ifirst:ilast]` subset). -# For efficiency, no parameter validity checks are done, it's the caller's responsibility. -# `ifirst:ilast` range is assumed to be a valid non-empty subset of `A` indices. - -# This is a generic implementation of `mapreduce_impl()`, -# certain `op` (e.g. `min` and `max`) may have their own specialized versions. -function mapreduce_impl(f, op, A::AbstractArray, ifirst::Integer, ilast::Integer, blksize::Int=pairwise_blocksize(f, op)) - if ifirst == ilast - @inbounds a1 = A[ifirst] - return r_promote(op, f(a1)) - elseif ifirst + blksize > ilast - # sequential portion - @inbounds a1 = A[ifirst] - @inbounds a2 = A[ifirst+1] - v = op(r_promote(op, f(a1)), r_promote(op, f(a2))) - @simd for i = ifirst + 2 : ilast - @inbounds ai = A[i] - v = op(v, f(ai)) - end - return v - else - # pairwise portion - imid = (ifirst + ilast) >> 1 - v1 = mapreduce_impl(f, op, A, ifirst, imid, blksize) - v2 = mapreduce_impl(f, op, A, imid+1, ilast, blksize) - return op(v1, v2) - end -end - -""" - mapreduce(f, op, itr) - -Like `mapreduce(f, op, v0, itr)`. In general, this cannot be used with empty collections -(see `reduce(op, itr)`). -""" -mapreduce(f, op, itr) = mapfoldl(f, op, itr) - -""" - mapreduce(f, op, v0, itr) - -Apply function `f` to each element in `itr`, and then reduce the result using the binary -function `op`. `v0` must be a neutral element for `op` that will be returned for empty -collections. It is unspecified whether `v0` is used for non-empty collections. - -[`mapreduce`](@ref) is functionally equivalent to calling `reduce(op, v0, -map(f, itr))`, but will in general execute faster since no intermediate collection needs to -be created. See documentation for [`reduce`](@ref) and [`map`](@ref). - -```jldoctest -julia> mapreduce(x->x^2, +, [1:3;]) # == 1 + 4 + 9 -14 -``` - -The associativity of the reduction is implementation-dependent. Additionally, some -implementations may reuse the return value of `f` for elements that appear multiple times in -`itr`. Use [`mapfoldl`](@ref) or [`mapfoldr`](@ref) instead for -guaranteed left or right associativity and invocation of `f` for every value. -""" -mapreduce(f, op, v0, itr) = mapfoldl(f, op, v0, itr) - -# Note: sum_seq usually uses four or more accumulators after partial -# unrolling, so each accumulator gets at most 256 numbers -pairwise_blocksize(f, op) = 1024 - -# This combination appears to show a benefit from a larger block size -pairwise_blocksize(::typeof(abs2), ::typeof(+)) = 4096 - - -# handling empty arrays -_empty_reduce_error() = throw(ArgumentError("reducing over an empty collection is not allowed")) -mr_empty(f, op, T) = _empty_reduce_error() -# use zero(T)::T to improve type information when zero(T) is not defined -mr_empty(::typeof(identity), op::typeof(+), T) = r_promote(op, zero(T)::T) -mr_empty(::typeof(abs), op::typeof(+), T) = r_promote(op, abs(zero(T)::T)) -mr_empty(::typeof(abs2), op::typeof(+), T) = r_promote(op, abs2(zero(T)::T)) -mr_empty(::typeof(identity), op::typeof(*), T) = r_promote(op, one(T)::T) -mr_empty(::typeof(abs), op::typeof(scalarmax), T) = abs(zero(T)::T) -mr_empty(::typeof(abs2), op::typeof(scalarmax), T) = abs2(zero(T)::T) -mr_empty(::typeof(abs), op::typeof(max), T) = mr_empty(abs, scalarmax, T) -mr_empty(::typeof(abs2), op::typeof(max), T) = mr_empty(abs2, scalarmax, T) -mr_empty(f, op::typeof(&), T) = true -mr_empty(f, op::typeof(|), T) = false - -mr_empty_iter(f, op, itr, ::HasEltype) = mr_empty(f, op, eltype(itr)) -mr_empty_iter(f, op::typeof(&), itr, ::EltypeUnknown) = true -mr_empty_iter(f, op::typeof(|), itr, ::EltypeUnknown) = false -mr_empty_iter(f, op, itr, ::EltypeUnknown) = _empty_reduce_error() - -_mapreduce(f, op, A::AbstractArray) = _mapreduce(f, op, IndexStyle(A), A) - -function _mapreduce(f, op, ::IndexLinear, A::AbstractArray{T}) where T - inds = linearindices(A) - n = length(inds) - if n == 0 - return mr_empty(f, op, T) - elseif n == 1 - @inbounds a1 = A[inds[1]] - return r_promote(op, f(a1)) - elseif n < 16 # process short array here, avoid mapreduce_impl() compilation - @inbounds i = inds[1] - @inbounds a1 = A[i] - @inbounds a2 = A[i+=1] - s = op(r_promote(op, f(a1)), r_promote(op, f(a2))) - while i < last(inds) - @inbounds Ai = A[i+=1] - s = op(s, f(Ai)) - end - return s - else - return mapreduce_impl(f, op, A, first(inds), last(inds)) - end -end - -_mapreduce(f, op, ::IndexCartesian, A::AbstractArray) = mapfoldl(f, op, A) - -mapreduce(f, op, A::AbstractArray) = _mapreduce(f, op, IndexStyle(A), A) -mapreduce(f, op, a::Number) = f(a) - -""" - reduce(op, v0, itr) - -Reduce the given collection `ìtr` with the given binary operator `op`. `v0` must be a -neutral element for `op` that will be returned for empty collections. It is unspecified -whether `v0` is used for non-empty collections. - -Reductions for certain commonly-used operators have special implementations which should be -used instead: `maximum(itr)`, `minimum(itr)`, `sum(itr)`, `prod(itr)`, `any(itr)`, -`all(itr)`. - -The associativity of the reduction is implementation dependent. This means that you can't -use non-associative operations like `-` because it is undefined whether `reduce(-,[1,2,3])` -should be evaluated as `(1-2)-3` or `1-(2-3)`. Use [`foldl`](@ref) or -[`foldr`](@ref) instead for guaranteed left or right associativity. - -Some operations accumulate error, and parallelism will also be easier if the reduction can -be executed in groups. Future versions of Julia might change the algorithm. Note that the -elements are not reordered if you use an ordered collection. - -# Examples - -```jldoctest -julia> reduce(*, 1, [2; 3; 4]) -24 -``` -""" -reduce(op, v0, itr) = mapreduce(identity, op, v0, itr) - -""" - reduce(op, itr) - -Like `reduce(op, v0, itr)`. This cannot be used with empty collections, except for some -special cases (e.g. when `op` is one of `+`, `*`, `max`, `min`, `&`, `|`) when Julia can -determine the neutral element of `op`. - -```jldoctest -julia> reduce(*, [2; 3; 4]) -24 -``` -""" -reduce(op, itr) = mapreduce(identity, op, itr) -reduce(op, a::Number) = a - -###### Specific reduction functions ###### - -## sum - -""" - sum(f, itr) - -Sum the results of calling function `f` on each element of `itr`. - -```jldoctest -julia> sum(abs2, [2; 3; 4]) -29 -``` -""" -sum(f::Callable, a) = mapreduce(f, +, a) - -""" - sum(itr) - -Returns the sum of all elements in a collection. - -```jldoctest -julia> sum(1:20) -210 -``` -""" -sum(a) = mapreduce(identity, +, a) -sum(a::AbstractArray{Bool}) = countnz(a) - - -# Kahan (compensated) summation: O(1) error growth, at the expense -# of a considerable increase in computational expense. - -""" - sum_kbn(A) - -Returns the sum of all elements of `A`, using the Kahan-Babuska-Neumaier compensated -summation algorithm for additional accuracy. -""" -function sum_kbn(A) - T = _default_eltype(typeof(A)) - c = r_promote(+, zero(T)::T) - i = start(A) - if done(A, i) - return c - end - Ai, i = next(A, i) - s = Ai - c - while !(done(A, i)) - Ai, i = next(A, i) - t = s + Ai - if abs(s) >= abs(Ai) - c -= ((s-t) + Ai) - else - c -= ((Ai-t) + s) - end - s = t - end - s - c -end - -## prod -""" - prod(f, itr) - -Returns the product of `f` applied to each element of `itr`. - -```jldoctest -julia> prod(abs2, [2; 3; 4]) -576 -``` -""" -prod(f::Callable, a) = mapreduce(f, *, a) - -""" - prod(itr) - -Returns the product of all elements of a collection. - -```jldoctest -julia> prod(1:20) -2432902008176640000 -``` -""" -prod(a) = mapreduce(identity, *, a) - -## maximum & minimum - -function mapreduce_impl(f, op::Union{typeof(scalarmax), - typeof(scalarmin), - typeof(max), - typeof(min)}, - A::AbstractArray, first::Int, last::Int) - # locate the first non NaN number - @inbounds a1 = A[first] - v = f(a1) - i = first + 1 - while (v == v) && (i <= last) - @inbounds ai = A[i] - v = op(v, f(ai)) - i += 1 - end - v -end - -maximum(f::Callable, a) = mapreduce(f, scalarmax, a) -minimum(f::Callable, a) = mapreduce(f, scalarmin, a) - -""" - maximum(itr) - -Returns the largest element in a collection. - -```jldoctest -julia> maximum(-20.5:10) -9.5 - -julia> maximum([1,2,3]) -3 -``` -""" -maximum(a) = mapreduce(identity, scalarmax, a) - -""" - minimum(itr) - -Returns the smallest element in a collection. - -```jldoctest -julia> minimum(-20.5:10) --20.5 - -julia> minimum([1,2,3]) -1 -``` -""" -minimum(a) = mapreduce(identity, scalarmin, a) - -## extrema - -extrema(r::Range) = (minimum(r), maximum(r)) -extrema(x::Real) = (x, x) - -""" - extrema(itr) -> Tuple - -Compute both the minimum and maximum element in a single pass, and return them as a 2-tuple. - -```jldoctest -julia> extrema(2:10) -(2, 10) - -julia> extrema([9,pi,4.5]) -(3.141592653589793, 9.0) -``` -""" -function extrema(itr) - s = start(itr) - done(itr, s) && throw(ArgumentError("collection must be non-empty")) - (v, s) = next(itr, s) - vmin = vmax = v - while !done(itr, s) - (x, s) = next(itr, s) - vmax = max(x, vmax) - vmin = min(x, vmin) - end - return (vmin, vmax) -end - -## all & any - -""" - any(itr) -> Bool - -Test whether any elements of a boolean collection are `true`, returning `true` as -soon as the first `true` value in `itr` is encountered (short-circuiting). - -```jldoctest -julia> a = [true,false,false,true] -4-element Array{Bool,1}: - true - false - false - true - -julia> any(a) -true - -julia> any((println(i); v) for (i, v) in enumerate(a)) -1 -true -``` -""" -any(itr) = any(identity, itr) - -""" - all(itr) -> Bool - -Test whether all elements of a boolean collection are `true`, returning `false` as -soon as the first `false` value in `itr` is encountered (short-circuiting). - -```jldoctest -julia> a = [true,false,false,true] -4-element Array{Bool,1}: - true - false - false - true - -julia> all(a) -false - -julia> all((println(i); v) for (i, v) in enumerate(a)) -1 -2 -false -``` -""" -all(itr) = all(identity, itr) - -""" - any(p, itr) -> Bool - -Determine whether predicate `p` returns `true` for any elements of `itr`, returning -`true` as soon as the first item in `itr` for which `p` returns `true` is encountered -(short-circuiting). - -```jldoctest -julia> any(i->(4<=i<=6), [3,5,7]) -true - -julia> any(i -> (println(i); i > 3), 1:10) -1 -2 -3 -4 -true -``` -""" -function any(f, itr) - for x in itr - f(x) && return true - end - return false -end - -""" - all(p, itr) -> Bool - -Determine whether predicate `p` returns `true` for all elements of `itr`, returning -`false` as soon as the first item in `itr` for which `p` returns `false` is encountered -(short-circuiting). - -```jldoctest -julia> all(i->(4<=i<=6), [4,5,6]) -true - -julia> all(i -> (println(i); i < 3), 1:10) -1 -2 -3 -false -``` -""" -function all(f, itr) - for x in itr - f(x) || return false - end - return true -end - -## in & contains - -""" - in(item, collection) -> Bool - ∈(item,collection) -> Bool - ∋(collection,item) -> Bool - ∉(item,collection) -> Bool - ∌(collection,item) -> Bool - -Determine whether an item is in the given collection, in the sense that it is `==` to one of -the values generated by iterating over the collection. Some collections need a slightly -different definition; for example [`Set`](@ref)s check whether the item -[`isequal`](@ref) to one of the elements. [`Dict`](@ref)s look for -`(key,value)` pairs, and the key is compared using [`isequal`](@ref). To test for -the presence of a key in a dictionary, use [`haskey`](@ref) or `k in keys(dict)`. - -```jldoctest -julia> a = 1:3:20 -1:3:19 - -julia> 4 in a -true - -julia> 5 in a -false -``` -""" -in(x, itr) = any(y -> y == x, itr) - -const ∈ = in -∉(x, itr)=!∈(x, itr) -∋(itr, x)= ∈(x, itr) -∌(itr, x)=!∋(itr, x) - -""" - contains(fun, itr, x) -> Bool - -Returns `true` if there is at least one element `y` in `itr` such that `fun(y,x)` is `true`. - -```jldoctest -julia> vec = [10, 100, 200] -3-element Array{Int64,1}: - 10 - 100 - 200 - -julia> contains(==, vec, 200) -true - -julia> contains(==, vec, 300) -false - -julia> contains(>, vec, 100) -true - -julia> contains(>, vec, 200) -false -``` -""" -function contains(eq::Function, itr, x) - for y in itr - eq(y, x) && return true - end - return false -end - - -## countnz & count - -""" - count(p, itr) -> Integer - count(itr) -> Integer - -Count the number of elements in `itr` for which predicate `p` returns `true`. -If `p` is omitted, counts the number of `true` elements in `itr` (which -should be a collection of boolean values). - -```jldoctest -julia> count(i->(4<=i<=6), [2,3,4,5,6]) -3 - -julia> count([true, false, true, true]) -3 -``` -""" -function count(pred, itr) - n = 0 - for x in itr - n += pred(x)::Bool - end - return n -end -function count(pred, a::AbstractArray) - n = 0 - for i in eachindex(a) - @inbounds n += pred(a[i])::Bool - end - return n -end -count(itr) = count(identity, itr) - -""" - countnz(A) -> Integer - -Counts the number of nonzero values in array `A` (dense or sparse). Note that this is not a constant-time operation. -For sparse matrices, one should usually use [`nnz`](@ref), which returns the number of stored values. - -```jldoctest -julia> A = [1 2 4; 0 0 1; 1 1 0] -3×3 Array{Int64,2}: - 1 2 4 - 0 0 1 - 1 1 0 - -julia> countnz(A) -6 -``` -""" -countnz(a) = count(x -> x != 0, a) diff --git a/julia-0.6.3/share/julia/base/reducedim.jl b/julia-0.6.3/share/julia/base/reducedim.jl deleted file mode 100644 index e857f57..0000000 --- a/julia-0.6.3/share/julia/base/reducedim.jl +++ /dev/null @@ -1,715 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -## Functions to compute the reduced shape - -# for reductions that expand 0 dims to 1 -reduced_indices(a::AbstractArray, region) = reduced_indices(indices(a), region) - -# for reductions that keep 0 dims as 0 -reduced_indices0(a::AbstractArray, region) = reduced_indices0(indices(a), region) - -function reduced_indices(inds::Indices{N}, d::Int, rd::AbstractUnitRange) where N - d < 1 && throw(ArgumentError("dimension must be ≥ 1, got $d")) - if d == 1 - return (oftype(inds[1], rd), tail(inds)...) - elseif 1 < d <= N - return tuple(inds[1:d-1]..., oftype(inds[d], rd), inds[d+1:N]...)::typeof(inds) - else - return inds - end -end -reduced_indices(inds::Indices, d::Int) = reduced_indices(inds, d, OneTo(1)) - -function reduced_indices0(inds::Indices{N}, d::Int) where N - d < 1 && throw(ArgumentError("dimension must be ≥ 1, got $d")) - if d <= N - return reduced_indices(inds, d, (inds[d] == OneTo(0) ? OneTo(0) : OneTo(1))) - else - return inds - end -end - -function reduced_indices(inds::Indices{N}, region) where N - rinds = [inds...] - for i in region - isa(i, Integer) || throw(ArgumentError("reduced dimension(s) must be integers")) - d = Int(i) - if d < 1 - throw(ArgumentError("region dimension(s) must be ≥ 1, got $d")) - elseif d <= N - rinds[d] = oftype(rinds[d], OneTo(1)) - end - end - tuple(rinds...)::typeof(inds) -end - -function reduced_indices0(inds::Indices{N}, region) where N - rinds = [inds...] - for i in region - isa(i, Integer) || throw(ArgumentError("reduced dimension(s) must be integers")) - d = Int(i) - if d < 1 - throw(ArgumentError("region dimension(s) must be ≥ 1, got $d")) - elseif d <= N - rinds[d] = oftype(rinds[d], (rinds[d] == OneTo(0) ? OneTo(0) : OneTo(1))) - end - end - tuple(rinds...)::typeof(inds) -end - - -###### Generic reduction functions ##### - -## initialization - -for (Op, initfun) in ((:(typeof(+)), :zero), (:(typeof(*)), :one), (:(typeof(scalarmax)), :typemin), (:(typeof(scalarmin)), :typemax), (:(typeof(max)), :typemin), (:(typeof(min)), :typemax)) - @eval initarray!{T}(a::AbstractArray{T}, ::$(Op), init::Bool) = (init && fill!(a, $(initfun)(T)); a) -end - -for (Op, initval) in ((:(typeof(&)), true), (:(typeof(|)), false)) - @eval initarray!(a::AbstractArray, ::$(Op), init::Bool) = (init && fill!(a, $initval); a) -end - -reducedim_initarray(A::AbstractArray, region, v0, ::Type{R}) where {R} = fill!(similar(A,R,reduced_indices(A,region)), v0) -reducedim_initarray(A::AbstractArray, region, v0::T) where {T} = reducedim_initarray(A, region, v0, T) - -reducedim_initarray0(A::AbstractArray, region, v0, ::Type{R}) where {R} = fill!(similar(A,R,reduced_indices0(A,region)), v0) -reducedim_initarray0(A::AbstractArray, region, v0::T) where {T} = reducedim_initarray0(A, region, v0, T) - -# TODO: better way to handle reducedim initialization -# -# The current scheme is basically following Steven G. Johnson's original implementation -# -promote_union(T::Union) = promote_type(promote_union(T.a), promote_union(T.b)) -promote_union(T) = T - -function reducedim_init(f, op::typeof(+), A::AbstractArray, region) - _reducedim_init(f, op, zero, sum, A, region) -end -function reducedim_init(f, op::typeof(*), A::AbstractArray, region) - _reducedim_init(f, op, one, prod, A, region) -end -function _reducedim_init(f, op, fv, fop, A, region) - T = promote_union(eltype(A)) - if method_exists(zero, Tuple{Type{T}}) - x = f(zero(T)) - z = op(fv(x), fv(x)) - Tr = typeof(z) == typeof(x) && !isbits(T) ? T : typeof(z) - else - z = fv(fop(f, A)) - Tr = typeof(z) - end - return reducedim_initarray(A, region, z, Tr) -end - -reducedim_init(f, op::typeof(max), A::AbstractArray, region) = reducedim_init(f, scalarmax, A, region) -reducedim_init(f, op::typeof(min), A::AbstractArray, region) = reducedim_init(f, scalarmin, A, region) -reducedim_init(f::Union{typeof(abs),typeof(abs2)}, op::typeof(max), A::AbstractArray, region) = reducedim_init(f, scalarmax, A, region) - -reducedim_init(f, op::typeof(scalarmax), A::AbstractArray{T}, region) where {T} = reducedim_initarray0(A, region, typemin(f(zero(T)))) -reducedim_init(f, op::typeof(scalarmin), A::AbstractArray{T}, region) where {T} = reducedim_initarray0(A, region, typemax(f(zero(T)))) -reducedim_init(f::Union{typeof(abs),typeof(abs2)}, op::typeof(scalarmax), A::AbstractArray{T}, region) where {T} = - reducedim_initarray(A, region, zero(f(zero(T)))) - -reducedim_init(f, op::typeof(&), A::AbstractArray, region) = reducedim_initarray(A, region, true) -reducedim_init(f, op::typeof(|), A::AbstractArray, region) = reducedim_initarray(A, region, false) - -# specialize to make initialization more efficient for common cases - -for (IT, RT) in ((CommonReduceResult, :(eltype(A))), (SmallSigned, :Int), (SmallUnsigned, :UInt)) - T = Union{[AbstractArray{t} for t in uniontypes(IT)]..., [AbstractArray{Complex{t}} for t in uniontypes(IT)]...} - @eval begin - reducedim_init(f::typeof(identity), op::typeof(+), A::$T, region) = - reducedim_initarray(A, region, zero($RT)) - reducedim_init(f::typeof(identity), op::typeof(*), A::$T, region) = - reducedim_initarray(A, region, one($RT)) - reducedim_init(f::Union{typeof(abs),typeof(abs2)}, op::typeof(+), A::$T, region) = - reducedim_initarray(A, region, real(zero($RT))) - reducedim_init(f::Union{typeof(abs),typeof(abs2)}, op::typeof(*), A::$T, region) = - reducedim_initarray(A, region, real(one($RT))) - end -end -reducedim_init(f::Union{typeof(identity),typeof(abs),typeof(abs2)}, op::typeof(+), A::AbstractArray{Bool}, region) = - reducedim_initarray(A, region, 0) - - -## generic (map)reduction - -has_fast_linear_indexing(a::AbstractArray) = false -has_fast_linear_indexing(a::Array) = true - -function check_reducedims(R, A) - # Check whether R has compatible dimensions w.r.t. A for reduction - # - # It returns an integer value (useful for choosing implementation) - # - If it reduces only along leading dimensions, e.g. sum(A, 1) or sum(A, (1, 2)), - # it returns the length of the leading slice. For the two examples above, - # it will be size(A, 1) or size(A, 1) * size(A, 2). - # - Otherwise, e.g. sum(A, 2) or sum(A, (1, 3)), it returns 0. - # - ndims(R) <= ndims(A) || throw(DimensionMismatch("cannot reduce $(ndims(A))-dimensional array to $(ndims(R)) dimensions")) - lsiz = 1 - had_nonreduc = false - for i = 1:ndims(A) - Ri, Ai = indices(R, i), indices(A, i) - sRi, sAi = length(Ri), length(Ai) - if sRi == 1 - if sAi > 1 - if had_nonreduc - lsiz = 0 # to reduce along i, but some previous dimensions were non-reducing - else - lsiz *= sAi # if lsiz was set to zero, it will stay to be zero - end - end - else - Ri == Ai || throw(DimensionMismatch("reduction on array with indices $(indices(A)) with output with indices $(indices(R))")) - had_nonreduc = true - end - end - return lsiz -end - -function _mapreducedim!(f, op, R::AbstractArray, A::AbstractArray) - lsiz = check_reducedims(R,A) - isempty(A) && return R - - if has_fast_linear_indexing(A) && lsiz > 16 - # use mapreduce_impl, which is probably better tuned to achieve higher performance - nslices = div(_length(A), lsiz) - ibase = first(linearindices(A))-1 - for i = 1:nslices - @inbounds R[i] = op(R[i], mapreduce_impl(f, op, A, ibase+1, ibase+lsiz)) - ibase += lsiz - end - return R - end - indsAt, indsRt = safe_tail(indices(A)), safe_tail(indices(R)) # handle d=1 manually - keep, Idefault = Broadcast.shapeindexer(indsAt, indsRt) - if reducedim1(R, A) - # keep the accumulator as a local variable when reducing along the first dimension - i1 = first(indices1(R)) - @inbounds for IA in CartesianRange(indsAt) - IR = Broadcast.newindex(IA, keep, Idefault) - r = R[i1,IR] - @simd for i in indices(A, 1) - r = op(r, f(A[i, IA])) - end - R[i1,IR] = r - end - else - @inbounds for IA in CartesianRange(indsAt) - IR = Broadcast.newindex(IA, keep, Idefault) - @simd for i in indices(A, 1) - R[i,IR] = op(R[i,IR], f(A[i,IA])) - end - end - end - return R -end - -mapreducedim!(f, op, R::AbstractArray, A::AbstractArray) = - (_mapreducedim!(f, op, R, A); R) - -reducedim!(op, R::AbstractArray{RT}, A::AbstractArray) where {RT} = - mapreducedim!(identity, op, R, A, zero(RT)) - -""" - mapreducedim(f, op, A, region[, v0]) - -Evaluates to the same as `reducedim(op, map(f, A), region, f(v0))`, but is generally -faster because the intermediate array is avoided. - -# Examples -```jldoctest -julia> a = reshape(collect(1:16), (4,4)) -4×4 Array{Int64,2}: - 1 5 9 13 - 2 6 10 14 - 3 7 11 15 - 4 8 12 16 - -julia> mapreducedim(isodd, *, a, 1) -1×4 Array{Bool,2}: - false false false false - -julia> mapreducedim(isodd, |, a, 1, true) -1×4 Array{Bool,2}: - true true true true -``` -""" -mapreducedim(f, op, A::AbstractArray, region, v0) = - mapreducedim!(f, op, reducedim_initarray(A, region, v0), A) -mapreducedim(f, op, A::AbstractArray, region) = - mapreducedim!(f, op, reducedim_init(f, op, A, region), A) - -""" - reducedim(f, A, region[, v0]) - -Reduce 2-argument function `f` along dimensions of `A`. `region` is a vector specifying the -dimensions to reduce, and `v0` is the initial value to use in the reductions. For `+`, `*`, -`max` and `min` the `v0` argument is optional. - -The associativity of the reduction is implementation-dependent; if you need a particular -associativity, e.g. left-to-right, you should write your own loop. See documentation for -[`reduce`](@ref). - -# Examples -```jldoctest -julia> a = reshape(collect(1:16), (4,4)) -4×4 Array{Int64,2}: - 1 5 9 13 - 2 6 10 14 - 3 7 11 15 - 4 8 12 16 - -julia> reducedim(max, a, 2) -4×1 Array{Int64,2}: - 13 - 14 - 15 - 16 - -julia> reducedim(max, a, 1) -1×4 Array{Int64,2}: - 4 8 12 16 -``` -""" -reducedim(op, A::AbstractArray, region, v0) = mapreducedim(identity, op, A, region, v0) -reducedim(op, A::AbstractArray, region) = mapreducedim(identity, op, A, region) - - -##### Specific reduction functions ##### -""" - sum(A, dims) - -Sum elements of an array over the given dimensions. - -# Examples -```jldoctest -julia> A = [1 2; 3 4] -2×2 Array{Int64,2}: - 1 2 - 3 4 - -julia> sum(A, 1) -1×2 Array{Int64,2}: - 4 6 - -julia> sum(A, 2) -2×1 Array{Int64,2}: - 3 - 7 -``` -""" -sum(A, dims) - -""" - sum!(r, A) - -Sum elements of `A` over the singleton dimensions of `r`, and write results to `r`. - -# Examples -```jldoctest -julia> A = [1 2; 3 4] -2×2 Array{Int64,2}: - 1 2 - 3 4 - -julia> sum!([1; 1], A) -2-element Array{Int64,1}: - 3 - 7 - -julia> sum!([1 1], A) -1×2 Array{Int64,2}: - 4 6 -``` -""" -sum!(r, A) - -""" - prod(A, dims) - -Multiply elements of an array over the given dimensions. - -# Examples -```jldoctest -julia> A = [1 2; 3 4] -2×2 Array{Int64,2}: - 1 2 - 3 4 - -julia> prod(A, 1) -1×2 Array{Int64,2}: - 3 8 - -julia> prod(A, 2) -2×1 Array{Int64,2}: - 2 - 12 -``` -""" -prod(A, dims) - -""" - prod!(r, A) - -Multiply elements of `A` over the singleton dimensions of `r`, and write results to `r`. - -# Examples -```jldoctest -julia> A = [1 2; 3 4] -2×2 Array{Int64,2}: - 1 2 - 3 4 - -julia> prod!([1; 1], A) -2-element Array{Int64,1}: - 2 - 12 - -julia> prod!([1 1], A) -1×2 Array{Int64,2}: - 3 8 -``` -""" -prod!(r, A) - -""" - maximum(A, dims) - -Compute the maximum value of an array over the given dimensions. See also the -[`max(a,b)`](@ref) function to take the maximum of two or more arguments, -which can be applied elementwise to arrays via `max.(a,b)`. - -```jldoctest -julia> A = [1 2; 3 4] -2×2 Array{Int64,2}: - 1 2 - 3 4 - -julia> maximum(A, 1) -1×2 Array{Int64,2}: - 3 4 - -julia> maximum(A, 2) -2×1 Array{Int64,2}: - 2 - 4 -``` -""" -maximum(A, dims) - -""" - maximum!(r, A) - -Compute the maximum value of `A` over the singleton dimensions of `r`, and write results to `r`. - -# Examples -```jldoctest -julia> A = [1 2; 3 4] -2×2 Array{Int64,2}: - 1 2 - 3 4 - -julia> maximum!([1; 1], A) -2-element Array{Int64,1}: - 2 - 4 - -julia> maximum!([1 1], A) -1×2 Array{Int64,2}: - 3 4 -``` -""" -maximum!(r, A) - -""" - minimum(A, dims) - -Compute the minimum value of an array over the given dimensions. See also the -[`min(a,b)`](@ref) function to take the minimum of two or more arguments, -which can be applied elementwise to arrays via `min.(a,b)`. - -# Examples -```jldoctest -julia> A = [1 2; 3 4] -2×2 Array{Int64,2}: - 1 2 - 3 4 - -julia> minimum(A, 1) -1×2 Array{Int64,2}: - 1 2 - -julia> minimum(A, 2) -2×1 Array{Int64,2}: - 1 - 3 -``` -""" -minimum(A, dims) - -""" - minimum!(r, A) - -Compute the minimum value of `A` over the singleton dimensions of `r`, and write results to `r`. - -# Examples -```jldoctest -julia> A = [1 2; 3 4] -2×2 Array{Int64,2}: - 1 2 - 3 4 - -julia> minimum!([1; 1], A) -2-element Array{Int64,1}: - 1 - 3 - -julia> minimum!([1 1], A) -1×2 Array{Int64,2}: - 1 2 -``` -""" -minimum!(r, A) - -""" - all(A, dims) - -Test whether all values along the given dimensions of an array are `true`. - -# Examples -```jldoctest -julia> A = [true false; true true] -2×2 Array{Bool,2}: - true false - true true - -julia> all(A, 1) -1×2 Array{Bool,2}: - true false - -julia> all(A, 2) -2×1 Array{Bool,2}: - false - true -``` -""" -all(A::AbstractArray, dims) - -""" - all!(r, A) - -Test whether all values in `A` along the singleton dimensions of `r` are `true`, and write results to `r`. - -# Examples -```jldoctest -julia> A = [true false; true false] -2×2 Array{Bool,2}: - true false - true false - -julia> all!([1; 1], A) -2-element Array{Int64,1}: - 0 - 0 - -julia> all!([1 1], A) -1×2 Array{Int64,2}: - 1 0 -``` -""" -all!(r, A) - -""" - any(A, dims) - -Test whether any values along the given dimensions of an array are `true`. - -# Examples -```jldoctest -julia> A = [true false; true false] -2×2 Array{Bool,2}: - true false - true false - -julia> any(A, 1) -1×2 Array{Bool,2}: - true false - -julia> any(A, 2) -2×1 Array{Bool,2}: - true - true -``` -""" -any(::AbstractArray,dims) - -""" - any!(r, A) - -Test whether any values in `A` along the singleton dimensions of `r` are `true`, and write -results to `r`. - -# Examples -```jldoctest -julia> A = [true false; true false] -2×2 Array{Bool,2}: - true false - true false - -julia> any!([1; 1], A) -2-element Array{Int64,1}: - 1 - 1 - -julia> any!([1 1], A) -1×2 Array{Int64,2}: - 1 0 -``` -""" -any!(r, A) - -for (fname, op) in [(:sum, :+), (:prod, :*), - (:maximum, :scalarmax), (:minimum, :scalarmin), - (:all, :&), (:any, :|)] - fname! = Symbol(fname, '!') - @eval begin - $(fname!)(f::Function, r::AbstractArray, A::AbstractArray; init::Bool=true) = - mapreducedim!(f, $(op), initarray!(r, $(op), init), A) - $(fname!)(r::AbstractArray, A::AbstractArray; init::Bool=true) = $(fname!)(identity, r, A; init=init) - - $(fname)(f::Function, A::AbstractArray, region) = - mapreducedim(f, $(op), A, region) - $(fname)(A::AbstractArray, region) = $(fname)(identity, A, region) - end -end - - -##### findmin & findmax ##### - -function findminmax!(f, Rval, Rind, A::AbstractArray{T,N}) where {T,N} - (isempty(Rval) || isempty(A)) && return Rval, Rind - lsiz = check_reducedims(Rval, A) - for i = 1:N - indices(Rval, i) == indices(Rind, i) || throw(DimensionMismatch("Find-reduction: outputs must have the same indices")) - end - # If we're reducing along dimension 1, for efficiency we can make use of a temporary. - # Otherwise, keep the result in Rval/Rind so that we traverse A in storage order. - indsAt, indsRt = safe_tail(indices(A)), safe_tail(indices(Rval)) - keep, Idefault = Broadcast.shapeindexer(indsAt, indsRt) - k = 0 - if reducedim1(Rval, A) - i1 = first(indices1(Rval)) - @inbounds for IA in CartesianRange(indsAt) - IR = Broadcast.newindex(IA, keep, Idefault) - tmpRv = Rval[i1,IR] - tmpRi = Rind[i1,IR] - for i in indices(A,1) - k += 1 - tmpAv = A[i,IA] - if f(tmpAv, tmpRv) - tmpRv = tmpAv - tmpRi = k - end - end - Rval[i1,IR] = tmpRv - Rind[i1,IR] = tmpRi - end - else - @inbounds for IA in CartesianRange(indsAt) - IR = Broadcast.newindex(IA, keep, Idefault) - for i in indices(A, 1) - k += 1 - tmpAv = A[i,IA] - if f(tmpAv, Rval[i,IR]) - Rval[i,IR] = tmpAv - Rind[i,IR] = k - end - end - end - end - Rval, Rind -end - - -""" - findmin!(rval, rind, A, [init=true]) -> (minval, index) - -Find the minimum of `A` and the corresponding linear index along singleton -dimensions of `rval` and `rind`, and store the results in `rval` and `rind`. -""" -function findmin!(rval::AbstractArray, rind::AbstractArray, A::AbstractArray; - init::Bool=true) - findminmax!(<, initarray!(rval, scalarmin, init), rind, A) -end - -""" - findmin(A, region) -> (minval, index) - -For an array input, returns the value and index of the minimum over the given region. - -# Examples -```jldoctest -julia> A = [1 2; 3 4] -2×2 Array{Int64,2}: - 1 2 - 3 4 - -julia> findmin(A, 1) -([1 2], [1 3]) - -julia> findmin(A, 2) -([1; 3], [1; 2]) -``` -""" -function findmin(A::AbstractArray{T}, region) where T - if isempty(A) - return (similar(A, reduced_indices0(A, region)), - similar(dims->zeros(Int, dims), reduced_indices0(A, region))) - end - return findminmax!(<, reducedim_initarray0(A, region, typemax(T)), - similar(dims->zeros(Int, dims), reduced_indices0(A, region)), A) -end - -""" - findmax!(rval, rind, A, [init=true]) -> (maxval, index) - -Find the maximum of `A` and the corresponding linear index along singleton -dimensions of `rval` and `rind`, and store the results in `rval` and `rind`. -""" -function findmax!(rval::AbstractArray, rind::AbstractArray, A::AbstractArray; - init::Bool=true) - findminmax!(>, initarray!(rval, scalarmax, init), rind, A) -end - -""" - findmax(A, region) -> (maxval, index) - -For an array input, returns the value and index of the maximum over the given region. - -# Examples -```jldoctest -julia> A = [1 2; 3 4] -2×2 Array{Int64,2}: - 1 2 - 3 4 - -julia> findmax(A,1) -([3 4], [2 4]) - -julia> findmax(A,2) -([2; 4], [3; 4]) -``` -""" -function findmax(A::AbstractArray{T}, region) where T - if isempty(A) - return (similar(A, reduced_indices0(A,region)), - similar(dims->zeros(Int, dims), reduced_indices0(A,region))) - end - return findminmax!(>, reducedim_initarray0(A, region, typemin(T)), - similar(dims->zeros(Int, dims), reduced_indices0(A, region)), A) -end - -reducedim1(R, A) = length(indices1(R)) == 1 diff --git a/julia-0.6.3/share/julia/base/reflection.jl b/julia-0.6.3/share/julia/base/reflection.jl deleted file mode 100644 index 85ddf9c..0000000 --- a/julia-0.6.3/share/julia/base/reflection.jl +++ /dev/null @@ -1,1006 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -# name and module reflection - -""" - module_name(m::Module) -> Symbol - -Get the name of a `Module` as a `Symbol`. - -```jldoctest -julia> module_name(Base.LinAlg) -:LinAlg -``` -""" -module_name(m::Module) = ccall(:jl_module_name, Ref{Symbol}, (Any,), m) - -""" - module_parent(m::Module) -> Module - -Get a module's enclosing `Module`. `Main` is its own parent, as is `LastMain` after `workspace()`. - -```jldoctest -julia> module_parent(Main) -Main - -julia> module_parent(Base.LinAlg.BLAS) -Base.LinAlg -``` -""" -module_parent(m::Module) = ccall(:jl_module_parent, Ref{Module}, (Any,), m) - -""" - current_module() -> Module - -Get the *dynamically* current `Module`, which is the `Module` code is currently being read -from. In general, this is not the same as the module containing the call to this function. -""" -current_module() = ccall(:jl_get_current_module, Ref{Module}, ()) - -""" - fullname(m::Module) - -Get the fully-qualified name of a module as a tuple of symbols. For example, - -```jldoctest -julia> fullname(Base.Pkg) -(:Base, :Pkg) - -julia> fullname(Main) -() -``` -""" -function fullname(m::Module) - m === Main && return () - m === Base && return (:Base,) # issue #10653 - mn = module_name(m) - mp = module_parent(m) - if mp === m - # not Main, but is its own parent, means a prior Main module - n = () - this = Main - while this !== m - if isdefined(this, :LastMain) - n = tuple(n..., :LastMain) - this = this.LastMain - else - error("no reference to module ", mn) - end - end - return n - end - return tuple(fullname(mp)..., mn) -end - -""" - names(x::Module, all::Bool=false, imported::Bool=false) - -Get an array of the names exported by a `Module`, excluding deprecated names. -If `all` is true, then the list also includes non-exported names defined in the module, -deprecated names, and compiler-generated names. -If `imported` is true, then names explicitly imported from other modules -are also included. - -As a special case, all names defined in `Main` are considered \"exported\", -since it is not idiomatic to explicitly export names from `Main`. -""" -names(m::Module, all::Bool=false, imported::Bool=false) = sort!(ccall(:jl_module_names, Array{Symbol,1}, (Any, Cint, Cint), m, all, imported)) - -isexported(m::Module, s::Symbol) = ccall(:jl_module_exports_p, Cint, (Any, Any), m, s) != 0 -isdeprecated(m::Module, s::Symbol) = ccall(:jl_is_binding_deprecated, Cint, (Any, Any), m, s) != 0 -isbindingresolved(m::Module, var::Symbol) = ccall(:jl_binding_resolved_p, Cint, (Any, Any), m, var) != 0 - -binding_module(s::Symbol) = binding_module(current_module(), s) -function binding_module(m::Module, s::Symbol) - p = ccall(:jl_get_module_of_binding, Ptr{Void}, (Any, Any), m, s) - p == C_NULL && return m - return unsafe_pointer_to_objref(p)::Module -end - -function resolve(g::GlobalRef; force::Bool=false) - if force || isbindingresolved(g.mod, g.name) - return GlobalRef(binding_module(g.mod, g.name), g.name) - end - return g -end - -""" - fieldname(x::DataType, i::Integer) - -Get the name of field `i` of a `DataType`. - -```jldoctest -julia> fieldname(SparseMatrixCSC,1) -:m - -julia> fieldname(SparseMatrixCSC,5) -:nzval -``` -""" -fieldname(t::DataType, i::Integer) = t.name.names[i]::Symbol -fieldname(t::UnionAll, i::Integer) = fieldname(unwrap_unionall(t), i) -fieldname(t::Type{<:Tuple}, i::Integer) = i < 1 || i > nfields(t) ? throw(BoundsError(t, i)) : Int(i) - -""" - fieldnames(x::DataType) - -Get an array of the fields of a `DataType`. - -```jldoctest -julia> fieldnames(Hermitian) -2-element Array{Symbol,1}: - :data - :uplo -``` -""" -function fieldnames(v) - t = typeof(v) - if !isa(t,DataType) - throw(ArgumentError("cannot call fieldnames() on a non-composite type")) - end - return fieldnames(t) -end -fieldnames(t::DataType) = Symbol[fieldname(t, n) for n in 1:nfields(t)] -fieldnames(t::UnionAll) = fieldnames(unwrap_unionall(t)) -fieldnames(t::Type{<:Tuple}) = Int[n for n in 1:nfields(t)] - -""" - Base.datatype_name(t) -> Symbol - -Get the name of a (potentially UnionAll-wrapped) `DataType` (without its parent module) as a symbol. -""" -datatype_name(t::DataType) = t.name.name -datatype_name(t::UnionAll) = datatype_name(unwrap_unionall(t)) - -""" - Base.datatype_module(t::DataType) -> Module - -Determine the module containing the definition of a `DataType`. -""" -datatype_module(t::DataType) = t.name.module - -isconst(s::Symbol) = ccall(:jl_is_const, Cint, (Ptr{Void}, Any), C_NULL, s) != 0 - -""" - isconst([m::Module], s::Symbol) -> Bool - -Determine whether a global is declared `const` in a given `Module`. The default `Module` -argument is [`current_module()`](@ref). -""" -isconst(m::Module, s::Symbol) = - ccall(:jl_is_const, Cint, (Any, Any), m, s) != 0 - -# return an integer such that object_id(x)==object_id(y) if x===y -object_id(x::ANY) = ccall(:jl_object_id, UInt, (Any,), x) - -struct DataTypeLayout - nfields::UInt32 - alignment::UInt32 - # alignment : 28; - # haspadding : 1; - # pointerfree : 1; - # fielddesc_type : 2; -end - - -# type predicates -datatype_alignment(dt::DataType) = dt.layout == C_NULL ? throw(UndefRefError()) : - Int(unsafe_load(convert(Ptr{DataTypeLayout}, dt.layout)).alignment & 0x1FF) - -datatype_haspadding(dt::DataType) = dt.layout == C_NULL ? throw(UndefRefError()) : - (unsafe_load(convert(Ptr{DataTypeLayout}, dt.layout)).alignment >> 9) & 1 == 1 - -datatype_pointerfree(dt::DataType) = dt.layout == C_NULL ? throw(UndefRefError()) : - (unsafe_load(convert(Ptr{DataTypeLayout}, dt.layout)).alignment >> 10) & 0xFFFFF == 0 - -datatype_fielddesc_type(dt::DataType) = dt.layout == C_NULL ? throw(UndefRefError()) : - (unsafe_load(convert(Ptr{DataTypeLayout}, dt.layout)).alignment >> 30) & 3 - -""" - isimmutable(v) - -Return `true` iff value `v` is immutable. See [Mutable Composite Types](@ref) -for a discussion of immutability. Note that this function works on values, so if you give it -a type, it will tell you that a value of `DataType` is mutable. - -```jldoctest -julia> isimmutable(1) -true - -julia> isimmutable([1,2]) -false -``` -""" -isimmutable(x::ANY) = (@_pure_meta; (isa(x,Tuple) || !typeof(x).mutable)) -isstructtype(t::DataType) = (@_pure_meta; nfields(t) != 0 || (t.size==0 && !t.abstract)) -isstructtype(x) = (@_pure_meta; false) - -""" - isbits(T) - -Return `true` if `T` is a "plain data" type, meaning it is immutable and contains no -references to other values. Typical examples are numeric types such as [`UInt8`](@ref), -[`Float64`](@ref), and [`Complex{Float64}`](@ref). - -```jldoctest -julia> isbits(Complex{Float64}) -true - -julia> isbits(Complex) -false -``` -""" -isbits(t::DataType) = (@_pure_meta; !t.mutable & (t.layout != C_NULL) && datatype_pointerfree(t)) -isbits(t::Type) = (@_pure_meta; false) -isbits(x) = (@_pure_meta; isbits(typeof(x))) - -""" - isleaftype(T) - -Determine whether `T`'s only subtypes are itself and `Union{}`. This means `T` is -a concrete type that can have instances. - -```jldoctest -julia> isleaftype(Complex) -false - -julia> isleaftype(Complex{Float32}) -true - -julia> isleaftype(Vector{Complex}) -true - -julia> isleaftype(Vector{Complex{Float32}}) -true -``` -""" -isleaftype(t::ANY) = (@_pure_meta; isa(t, DataType) && t.isleaftype) - -""" - Base.isabstract(T) - -Determine whether `T` was declared as an abstract type (i.e. using the -`abstract` keyword). - -```jldoctest -julia> Base.isabstract(AbstractArray) -true - -julia> Base.isabstract(Vector) -false -``` -""" -function isabstract(t::ANY) - @_pure_meta - t = unwrap_unionall(t) - isa(t,DataType) && t.abstract -end - -""" - Base.parameter_upper_bound(t::UnionAll, idx) - -Determine the upper bound of a type parameter in the underlying type. E.g.: - -```jldoctest -julia> struct Foo{T<:AbstractFloat, N} - x::Tuple{T, N} - end - -julia> Base.parameter_upper_bound(Foo, 1) -AbstractFloat - -julia> Base.parameter_upper_bound(Foo, 2) -Any -``` -""" -function parameter_upper_bound(t::UnionAll, idx) - @_pure_meta - rewrap_unionall(unwrap_unionall(t).parameters[idx], t) -end - -""" - typeintersect(T, S) - -Compute a type that contains the intersection of `T` and `S`. Usually this will be the -smallest such type or one close to it. -""" -typeintersect(a::ANY,b::ANY) = (@_pure_meta; ccall(:jl_type_intersection, Any, (Any,Any), a, b)) -typeseq(a::ANY,b::ANY) = (@_pure_meta; a<:b && b<:a) - -""" - fieldoffset(type, i) - -The byte offset of field `i` of a type relative to the data start. For example, we could -use it in the following manner to summarize information about a struct: - -```jldoctest -julia> structinfo(T) = [(fieldoffset(T,i), fieldname(T,i), fieldtype(T,i)) for i = 1:nfields(T)]; - -julia> structinfo(Base.Filesystem.StatStruct) -12-element Array{Tuple{UInt64,Symbol,DataType},1}: - (0x0000000000000000, :device, UInt64) - (0x0000000000000008, :inode, UInt64) - (0x0000000000000010, :mode, UInt64) - (0x0000000000000018, :nlink, Int64) - (0x0000000000000020, :uid, UInt64) - (0x0000000000000028, :gid, UInt64) - (0x0000000000000030, :rdev, UInt64) - (0x0000000000000038, :size, Int64) - (0x0000000000000040, :blksize, Int64) - (0x0000000000000048, :blocks, Int64) - (0x0000000000000050, :mtime, Float64) - (0x0000000000000058, :ctime, Float64) -``` -""" -fieldoffset(x::DataType, idx::Integer) = (@_pure_meta; ccall(:jl_get_field_offset, Csize_t, (Any, Cint), x, idx)) - -""" - fieldtype(T, name::Symbol | index::Int) - -Determine the declared type of a field (specified by name or index) in a composite DataType `T`. - -```jldoctest -julia> struct Foo - x::Int64 - y::String - end - -julia> fieldtype(Foo, :x) -Int64 - -julia> fieldtype(Foo, 2) -String -``` -""" -fieldtype - -""" - fieldindex(T, name::Symbol, err:Bool=true) - -Get the index of a named field, throwing an error if the field does not exist (when err==true) -or returning 0 (when err==false). - -```jldoctest -julia> struct Foo - x::Int64 - y::String - end - -julia> Base.fieldindex(Foo, :z) -ERROR: type Foo has no field z -Stacktrace: - [1] fieldindex at ./reflection.jl:319 [inlined] (repeats 2 times) - -julia> Base.fieldindex(Foo, :z, false) -0 -``` -""" -function fieldindex(T::DataType, name::Symbol, err::Bool=true) - return Int(ccall(:jl_field_index, Cint, (Any, Any, Cint), T, name, err)+1) -end - -type_alignment(x::DataType) = (@_pure_meta; ccall(:jl_get_alignment, Csize_t, (Any,), x)) - -# return all instances, for types that can be enumerated - -""" - instances(T::Type) - -Return a collection of all instances of the given type, if applicable. Mostly used for -enumerated types (see `@enum`). - -```jldoctest -julia> @enum Color red blue green - -julia> instances(Color) -(red::Color = 0, blue::Color = 1, green::Color = 2) -``` -""" -function instances end - -# subtypes -function _subtypes(m::Module, x::Union{DataType,UnionAll}, - sts=Set{Union{DataType,UnionAll}}(), visited=Set{Module}()) - push!(visited, m) - xt = unwrap_unionall(x) - if !isa(xt, DataType) - return sts - end - xt = xt::DataType - for s in names(m, true) - if isdefined(m, s) && !isdeprecated(m, s) - t = getfield(m, s) - if isa(t, DataType) - t = t::DataType - if t.name.name === s && supertype(t).name == xt.name - ti = typeintersect(t, x) - ti != Bottom && push!(sts, ti) - end - elseif isa(t, UnionAll) - t = t::UnionAll - tt = unwrap_unionall(t) - isa(tt, DataType) || continue - tt = tt::DataType - if tt.name.name === s && supertype(tt).name == xt.name - ti = typeintersect(t, x) - ti != Bottom && push!(sts, ti) - end - elseif isa(t, Module) - t = t::Module - in(t, visited) || _subtypes(t, x, sts, visited) - end - end - end - return sts -end -function subtypes(m::Module, x::Union{DataType,UnionAll}) - if isabstract(x) - sort!(collect(_subtypes(m, x)), by=string) - else - # Fast path - Union{DataType,UnionAll}[] - end -end - -""" - subtypes(T::DataType) - -Return a list of immediate subtypes of DataType `T`. Note that all currently loaded subtypes -are included, including those not visible in the current module. - -```jldoctest -julia> subtypes(Integer) -4-element Array{Union{DataType, UnionAll},1}: - BigInt - Bool - Signed - Unsigned -``` -""" -subtypes(x::Union{DataType,UnionAll}) = subtypes(Main, x) - -function to_tuple_type(t::ANY) - @_pure_meta - if isa(t,Tuple) || isa(t,AbstractArray) || isa(t,SimpleVector) - t = Tuple{t...} - end - if isa(t,Type) && t<:Tuple - if !all(p->(isa(p,Type)||isa(p,TypeVar)), t.parameters) - error("argument tuple type must contain only types") - end - else - error("expected tuple type") - end - t -end - -tt_cons(t::ANY, tup::ANY) = (@_pure_meta; Tuple{t, (isa(tup, Type) ? tup.parameters : tup)...}) - -""" - code_lowered(f, types) - -Returns an array of lowered ASTs for the methods matching the given generic function and type signature. -""" -function code_lowered(f::ANY, t::ANY=Tuple) - asts = map(methods(f, t)) do m - return uncompressed_ast(m::Method) - end - return asts -end - -# low-level method lookup functions used by the compiler - -unionlen(x::Union) = unionlen(x.a) + unionlen(x.b) -unionlen(x::ANY) = 1 - -_uniontypes(x::Union, ts) = (_uniontypes(x.a,ts); _uniontypes(x.b,ts); ts) -_uniontypes(x::ANY, ts) = (push!(ts, x); ts) -uniontypes(x::ANY) = _uniontypes(x, Any[]) - -function _methods(f::ANY, t::ANY, lim::Int, world::UInt) - ft = isa(f,Type) ? Type{f} : typeof(f) - tt = isa(t,Type) ? Tuple{ft, t.parameters...} : Tuple{ft, t...} - return _methods_by_ftype(tt, lim, world) -end - -function _methods_by_ftype(t::ANY, lim::Int, world::UInt) - return _methods_by_ftype(t, lim, world, UInt[typemin(UInt)], UInt[typemax(UInt)]) -end -function _methods_by_ftype(t::ANY, lim::Int, world::UInt, min::Array{UInt,1}, max::Array{UInt,1}) - tp = unwrap_unionall(t).parameters::SimpleVector - nu = 1 - for ti in tp - if isa(ti, Union) - nu *= unionlen(ti::Union) - end - end - if 1 < nu <= 64 - return _methods_by_ftype(Any[tp...], t, length(tp), lim, [], world, min, max) - end - # XXX: the following can return incorrect answers that the above branch would have corrected - return ccall(:jl_matching_methods, Any, (Any, Cint, Cint, UInt, Ptr{UInt}, Ptr{UInt}), t, lim, 0, world, min, max) -end - -function _methods_by_ftype(t::Array, origt::ANY, i, lim::Integer, matching::Array{Any,1}, - world::UInt, min::Array{UInt,1}, max::Array{UInt,1}) - if i == 0 - world = typemax(UInt) - new = ccall(:jl_matching_methods, Any, (Any, Cint, Cint, UInt, Ptr{UInt}, Ptr{UInt}), - rewrap_unionall(Tuple{t...}, origt), lim, 0, world, min, max) - new === false && return false - append!(matching, new::Array{Any,1}) - else - ti = t[i] - if isa(ti, Union) - for ty in uniontypes(ti::Union) - t[i] = ty - if _methods_by_ftype(t, origt, i - 1, lim, matching, world, min, max) === false - t[i] = ti - return false - end - end - t[i] = ti - else - return _methods_by_ftype(t, origt, i - 1, lim, matching, world, min, max) - end - end - return matching -end - -# high-level, more convenient method lookup functions - -# type for reflecting and pretty-printing a subset of methods -mutable struct MethodList - ms::Array{Method,1} - mt::MethodTable -end - -length(m::MethodList) = length(m.ms) -isempty(m::MethodList) = isempty(m.ms) -start(m::MethodList) = start(m.ms) -done(m::MethodList, s) = done(m.ms, s) -next(m::MethodList, s) = next(m.ms, s) - -function MethodList(mt::MethodTable) - ms = Method[] - visit(mt) do m - push!(ms, m) - end - return MethodList(ms, mt) -end - -""" - methods(f, [types]) - -Returns the method table for `f`. - -If `types` is specified, returns an array of methods whose types match. -""" -function methods(f::ANY, t::ANY) - if isa(f, Core.Builtin) - throw(ArgumentError("argument is not a generic function")) - end - t = to_tuple_type(t) - world = typemax(UInt) - return MethodList(Method[m[3] for m in _methods(f, t, -1, world)], typeof(f).name.mt) -end - -methods(f::Core.Builtin) = MethodList(Method[], typeof(f).name.mt) - -function methods_including_ambiguous(f::ANY, t::ANY) - ft = isa(f,Type) ? Type{f} : typeof(f) - tt = isa(t,Type) ? Tuple{ft, t.parameters...} : Tuple{ft, t...} - world = typemax(UInt) - min = UInt[typemin(UInt)] - max = UInt[typemax(UInt)] - ms = ccall(:jl_matching_methods, Any, (Any, Cint, Cint, UInt, Ptr{UInt}, Ptr{UInt}), tt, -1, 1, world, min, max)::Array{Any,1} - return MethodList(Method[m[3] for m in ms], typeof(f).name.mt) -end -function methods(f::ANY) - # return all matches - return methods(f, Tuple{Vararg{Any}}) -end - -function visit(f, mt::MethodTable) - mt.defs !== nothing && visit(f, mt.defs) - nothing -end -function visit(f, mc::TypeMapLevel) - if mc.targ !== nothing - e = mc.targ::Vector{Any} - for i in 1:length(e) - isassigned(e, i) && visit(f, e[i]) - end - end - if mc.arg1 !== nothing - e = mc.arg1::Vector{Any} - for i in 1:length(e) - isassigned(e, i) && visit(f, e[i]) - end - end - mc.list !== nothing && visit(f, mc.list) - mc.any !== nothing && visit(f, mc.any) - nothing -end -function visit(f, d::TypeMapEntry) - while d !== nothing - f(d.func) - d = d.next - end - nothing -end - -function length(mt::MethodTable) - n = 0 - visit(mt) do m - n += 1 - end - return n::Int -end -isempty(mt::MethodTable) = (mt.defs === nothing) - -uncompressed_ast(m::Method) = uncompressed_ast(m, m.source) -uncompressed_ast(m::Method, s::CodeInfo) = s -uncompressed_ast(m::Method, s::Array{UInt8,1}) = ccall(:jl_uncompress_ast, Any, (Any, Any), m, s)::CodeInfo - -# this type mirrors jl_cghooks_t (documented in julia.h) -struct CodegenHooks - module_setup::Ptr{Void} - module_activation::Ptr{Void} - raise_exception::Ptr{Void} - - CodegenHooks(;module_setup=nothing, module_activation=nothing, raise_exception=nothing) = - new(pointer_from_objref(module_setup), - pointer_from_objref(module_activation), - pointer_from_objref(raise_exception)) -end - -# this type mirrors jl_cgparams_t (documented in julia.h) -struct CodegenParams - cached::Cint - - runtime::Cint - exceptions::Cint - track_allocations::Cint - code_coverage::Cint - static_alloc::Cint - dynamic_alloc::Cint - - hooks::CodegenHooks - - CodegenParams(;cached::Bool=true, - runtime::Bool=true, exceptions::Bool=true, - track_allocations::Bool=true, code_coverage::Bool=true, - static_alloc::Bool=true, dynamic_alloc::Bool=true, - hooks::CodegenHooks=CodegenHooks()) = - new(Cint(cached), - Cint(runtime), Cint(exceptions), - Cint(track_allocations), Cint(code_coverage), - Cint(static_alloc), Cint(dynamic_alloc), - hooks) -end - -# Printing code representations in IR and assembly -function _dump_function(f::ANY, t::ANY, native::Bool, wrapper::Bool, - strip_ir_metadata::Bool, dump_module::Bool, syntax::Symbol=:att, - optimize::Bool=true, params::CodegenParams=CodegenParams()) - ccall(:jl_is_in_pure_context, Bool, ()) && error("code reflection cannot be used from generated functions") - if isa(f, Core.Builtin) - throw(ArgumentError("argument is not a generic function")) - end - # get the MethodInstance for the method match - world = typemax(UInt) - meth = which(f, t) - t = to_tuple_type(t) - ft = isa(f, Type) ? Type{f} : typeof(f) - tt = Tuple{ft, t.parameters...} - (ti, env) = ccall(:jl_match_method, Any, (Any, Any), tt, meth.sig)::SimpleVector - meth = func_for_method_checked(meth, tt) - linfo = ccall(:jl_specializations_get_linfo, Ref{Core.MethodInstance}, (Any, Any, Any, UInt), meth, tt, env, world) - # get the code for it - return _dump_function_linfo(linfo, world, native, wrapper, strip_ir_metadata, dump_module, syntax, optimize, params) -end - -function _dump_function_linfo(linfo::Core.MethodInstance, world::UInt, native::Bool, wrapper::Bool, - strip_ir_metadata::Bool, dump_module::Bool, syntax::Symbol=:att, - optimize::Bool=true, params::CodegenParams=CodegenParams()) - if syntax != :att && syntax != :intel - throw(ArgumentError("'syntax' must be either :intel or :att")) - end - if native - llvmf = ccall(:jl_get_llvmf_decl, Ptr{Void}, (Any, UInt, Bool, CodegenParams), linfo, world, wrapper, params) - else - llvmf = ccall(:jl_get_llvmf_defn, Ptr{Void}, (Any, UInt, Bool, Bool, CodegenParams), linfo, world, wrapper, optimize, params) - end - if llvmf == C_NULL - error("could not compile the specified method") - end - - if native - str = ccall(:jl_dump_function_asm, Ref{String}, - (Ptr{Void}, Cint, Ptr{UInt8}), llvmf, 0, syntax) - else - str = ccall(:jl_dump_function_ir, Ref{String}, - (Ptr{Void}, Bool, Bool), llvmf, strip_ir_metadata, dump_module) - end - - # TODO: use jl_is_cacheable_sig instead of isleaftype - isleaftype(linfo.specTypes) || (str = "; WARNING: This code may not match what actually runs.\n" * str) - return str -end - -""" - code_llvm([io], f, types) - -Prints the LLVM bitcodes generated for running the method matching the given generic -function and type signature to `io` which defaults to `STDOUT`. - -All metadata and dbg.* calls are removed from the printed bitcode. Use code_llvm_raw for the full IR. -""" -code_llvm(io::IO, f::ANY, types::ANY=Tuple, strip_ir_metadata=true, dump_module=false) = - print(io, _dump_function(f, types, false, false, strip_ir_metadata, dump_module)) -code_llvm(f::ANY, types::ANY=Tuple) = code_llvm(STDOUT, f, types) -code_llvm_raw(f::ANY, types::ANY=Tuple) = code_llvm(STDOUT, f, types, false) - -""" - code_native([io], f, types, [syntax]) - -Prints the native assembly instructions generated for running the method matching the given -generic function and type signature to `io` which defaults to `STDOUT`. -Switch assembly syntax using `syntax` symbol parameter set to `:att` for AT&T syntax or `:intel` for Intel syntax. Output is AT&T syntax by default. -""" -code_native(io::IO, f::ANY, types::ANY=Tuple, syntax::Symbol=:att) = - print(io, _dump_function(f, types, true, false, false, false, syntax)) -code_native(f::ANY, types::ANY=Tuple, syntax::Symbol=:att) = code_native(STDOUT, f, types, syntax) -code_native(::IO, ::ANY, ::Symbol) = error("illegal code_native call") # resolve ambiguous call - -# give a decent error message if we try to instantiate a staged function on non-leaf types -function func_for_method_checked(m::Method, types::ANY) - if m.isstaged && !isleaftype(types) - error("cannot call @generated function `", m, "` ", - "with abstract argument types: ", types) - end - return m -end - -""" - code_typed(f, types; optimize=true) - -Returns an array of lowered and type-inferred ASTs for the methods matching the given -generic function and type signature. The keyword argument `optimize` controls whether -additional optimizations, such as inlining, are also applied. -""" -function code_typed(f::ANY, types::ANY=Tuple; optimize=true) - ccall(:jl_is_in_pure_context, Bool, ()) && error("code reflection cannot be used from generated functions") - if isa(f, Core.Builtin) - throw(ArgumentError("argument is not a generic function")) - end - types = to_tuple_type(types) - asts = [] - world = ccall(:jl_get_world_counter, UInt, ()) - params = Core.Inference.InferenceParams(world) - for x in _methods(f, types, -1, world) - meth = func_for_method_checked(x[3], types) - (_, code, ty) = Core.Inference.typeinf_code(meth, x[1], x[2], optimize, optimize, params) - code === nothing && error("inference not successful") # Inference disabled? - push!(asts, uncompressed_ast(meth, code) => ty) - end - return asts -end - -function return_types(f::ANY, types::ANY=Tuple) - ccall(:jl_is_in_pure_context, Bool, ()) && error("code reflection cannot be used from generated functions") - if isa(f, Core.Builtin) - throw(ArgumentError("argument is not a generic function")) - end - types = to_tuple_type(types) - rt = [] - world = ccall(:jl_get_world_counter, UInt, ()) - params = Core.Inference.InferenceParams(world) - for x in _methods(f, types, -1, world) - meth = func_for_method_checked(x[3], types) - ty = Core.Inference.typeinf_type(meth, x[1], x[2], true, params) - ty === nothing && error("inference not successful") # Inference disabled? - push!(rt, ty) - end - return rt -end - -""" - which(f, types) - -Returns the method of `f` (a `Method` object) that would be called for arguments of the given `types`. - -If `types` is an abstract type, then the method that would be called by `invoke` is returned. -""" -function which(f::ANY, t::ANY) - if isa(f, Core.Builtin) - throw(ArgumentError("argument is not a generic function")) - end - t = to_tuple_type(t) - if isleaftype(t) - ms = methods(f, t) - isempty(ms) && error("no method found for the specified argument types") - length(ms)!=1 && error("no unique matching method for the specified argument types") - return first(ms) - else - ft = isa(f,Type) ? Type{f} : typeof(f) - tt = Tuple{ft, t.parameters...} - m = ccall(:jl_gf_invoke_lookup, Any, (Any, UInt), tt, typemax(UInt)) - if m === nothing - error("no method found for the specified argument types") - end - meth = m.func::Method - if ccall(:jl_has_call_ambiguities, Cint, (Any, Any), tt, meth) != 0 - error("method match is ambiguous for the specified argument types") - end - return meth - end -end - -""" - which(symbol) - -Return the module in which the binding for the variable referenced by `symbol` was created. -""" -which(s::Symbol) = which_module(current_module(), s) -# TODO: making this a method of which() causes a strange error -function which_module(m::Module, s::Symbol) - if !isdefined(m, s) - error("\"$s\" is not defined in module $m") - end - return binding_module(m, s) -end - -# function reflection -""" - Base.function_name(f::Function) -> Symbol - -Get the name of a generic `Function` as a symbol, or `:anonymous`. -""" -function_name(f::Function) = typeof(f).name.mt.name - -functionloc(m::Core.MethodInstance) = functionloc(m.def) - -""" - functionloc(m::Method) - -Returns a tuple `(filename,line)` giving the location of a `Method` definition. -""" -function functionloc(m::Method) - ln = m.line - if ln <= 0 - error("could not determine location of method definition") - end - return (find_source_file(string(m.file)), ln) -end - -""" - functionloc(f::Function, types) - -Returns a tuple `(filename,line)` giving the location of a generic `Function` definition. -""" -functionloc(f::ANY, types::ANY) = functionloc(which(f,types)) - -function functionloc(f::ANY) - mt = methods(f) - if isempty(mt) - if isa(f, Function) - error("function has no definitions") - else - error("object is not callable") - end - end - if length(mt) > 1 - error("function has multiple methods; please specify a type signature") - end - return functionloc(first(mt)) -end - -""" - Base.function_module(f::Function) -> Module - -Determine the module containing the (first) definition of a generic -function. -""" -function_module(f::Function) = datatype_module(typeof(f)) - -""" - Base.function_module(f::Function, types) -> Module - -Determine the module containing a given definition of a generic function. -""" -function function_module(f::ANY, types::ANY) - m = methods(f, types) - if isempty(m) - error("no matching methods") - end - return first(m).module -end - -""" - method_exists(f, Tuple type, world=typemax(UInt)) -> Bool - -Determine whether the given generic function has a method matching the given -`Tuple` of argument types with the upper bound of world age given by `world`. - -```jldoctest -julia> method_exists(length, Tuple{Array}) -true -``` -""" -function method_exists(f::ANY, t::ANY, world=typemax(UInt)) - t = to_tuple_type(t) - t = Tuple{isa(f,Type) ? Type{f} : typeof(f), t.parameters...} - return ccall(:jl_method_exists, Cint, (Any, Any, UInt), typeof(f).name.mt, t, world) != 0 -end - -""" - isambiguous(m1, m2; ambiguous_bottom=false) -> Bool - -Determine whether two methods `m1` and `m2` (typically of the same -function) are ambiguous. This test is performed in the context of -other methods of the same function; in isolation, `m1` and `m2` might -be ambiguous, but if a third method resolving the ambiguity has been -defined, this returns `false`. - -For parametric types, the `ambiguous_bottom` keyword argument controls whether -`Union{}` counts as an ambiguous intersection of type parameters – when `true`, -it is considered ambiguous, when `false` it is not. For example: - -```jldoctest -julia> foo(x::Complex{<:Integer}) = 1 -foo (generic function with 1 method) - -julia> foo(x::Complex{<:Rational}) = 2 -foo (generic function with 2 methods) - -julia> m1, m2 = collect(methods(foo)); - -julia> typeintersect(m1.sig, m2.sig) -Tuple{#foo,Complex{Union{}}} - -julia> Base.isambiguous(m1, m2, ambiguous_bottom=true) -true - -julia> Base.isambiguous(m1, m2, ambiguous_bottom=false) -false -``` -""" -function isambiguous(m1::Method, m2::Method; ambiguous_bottom::Bool=false) - ti = typeintersect(m1.sig, m2.sig) - ti === Bottom && return false - if !ambiguous_bottom - has_bottom_parameter(ti) && return false - end - ml = _methods_by_ftype(ti, -1, typemax(UInt)) - isempty(ml) && return true - for m in ml - if ti <: m[3].sig - return false - end - end - return true -end - -""" - has_bottom_parameter(t) -> Bool - -Determine whether `t` is a Type for which one or more of its parameters is `Union{}`. -""" -function has_bottom_parameter(t::Type) - ret = false - for p in t.parameters - ret |= (p == Bottom) || has_bottom_parameter(p) - end - ret -end -has_bottom_parameter(t::UnionAll) = has_bottom_parameter(unwrap_unionall(t)) -has_bottom_parameter(t::Union) = has_bottom_parameter(t.a) & has_bottom_parameter(t.b) -has_bottom_parameter(t::TypeVar) = has_bottom_parameter(t.ub) -has_bottom_parameter(::Any) = false - -min_world(m::Method) = reinterpret(UInt, m.min_world) -max_world(m::Method) = typemax(UInt) -min_world(m::Core.MethodInstance) = reinterpret(UInt, m.min_world) -max_world(m::Core.MethodInstance) = reinterpret(UInt, m.max_world) diff --git a/julia-0.6.3/share/julia/base/refpointer.jl b/julia-0.6.3/share/julia/base/refpointer.jl deleted file mode 100644 index 087a6e0..0000000 --- a/julia-0.6.3/share/julia/base/refpointer.jl +++ /dev/null @@ -1,124 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -""" - Ref{T} - -An object that safely references data of type `T`. This type is guaranteed to point to -valid, Julia-allocated memory of the correct type. The underlying data is protected from -freeing by the garbage collector as long as the `Ref` itself is referenced. - -When passed as a `ccall` argument (either as a `Ptr` or `Ref` type), a `Ref` object will be -converted to a native pointer to the data it references. - -There is no invalid (NULL) `Ref`. -""" -Ref - -# C NUL-terminated string pointers; these can be used in ccall -# instead of Ptr{Cchar} and Ptr{Cwchar_t}, respectively, to enforce -# a check for embedded NUL chars in the string (to avoid silent truncation). -if Int === Int64 - primitive type Cstring 64 end - primitive type Cwstring 64 end -else - primitive type Cstring 32 end - primitive type Cwstring 32 end -end - -### General Methods for Ref{T} type - -eltype(x::Type{Ref{T}}) where {T} = T -convert(::Type{Ref{T}}, x::Ref{T}) where {T} = x - -# create Ref objects for general object conversion -unsafe_convert(::Type{Ref{T}}, x::Ref{T}) where {T} = unsafe_convert(Ptr{T}, x) -unsafe_convert(::Type{Ref{T}}, x) where {T} = unsafe_convert(Ptr{T}, x) - -### Methods for a Ref object that can store a single value of any type - -mutable struct RefValue{T} <: Ref{T} - x::T - RefValue{T}() where {T} = new() - RefValue{T}(x) where {T} = new(x) -end -RefValue(x::T) where {T} = RefValue{T}(x) -isassigned(x::RefValue) = isdefined(x, :x) - -Ref(x::Ref) = x -Ref(x::Any) = RefValue(x) -Ref(x::Ptr{T}, i::Integer=1) where {T} = x + (i-1)*Core.sizeof(T) -Ref(x, i::Integer) = (i != 1 && error("Object only has one element"); Ref(x)) -Ref{T}() where {T} = RefValue{T}() # Ref{T}() -Ref{T}(x) where {T} = RefValue{T}(x) # Ref{T}(x) -convert(::Type{Ref{T}}, x) where {T} = RefValue{T}(x) - -function unsafe_convert(P::Type{Ptr{T}}, b::RefValue{T}) where T - if isbits(T) - return convert(P, data_pointer_from_objref(b)) - else - return convert(P, data_pointer_from_objref(b.x)) - end -end -function unsafe_convert(P::Type{Ptr{Any}}, b::RefValue{Any}) - return convert(P, data_pointer_from_objref(b)) -end -unsafe_convert(::Type{Ptr{Void}}, b::RefValue{T}) where {T} = convert(Ptr{Void}, unsafe_convert(Ptr{T}, b)) - -### Methods for a Ref object that is backed by an array at index i -struct RefArray{T,A<:AbstractArray{T},R} <: Ref{T} - x::A - i::Int - roots::R # should be either ::Void or ::Any - RefArray{T,A,R}(x,i,roots=nothing) where {T,A<:AbstractArray{T},R} = new(x,i,roots) -end -RefArray(x::AbstractArray{T}, i::Int, roots::Any) where {T} = RefArray{T,typeof(x),Any}(x, i, roots) -RefArray(x::AbstractArray{T}, i::Int=1, roots::Void=nothing) where {T} = RefArray{T,typeof(x),Void}(x, i, nothing) -convert(::Type{Ref{T}}, x::AbstractArray{T}) where {T} = RefArray(x, 1) -Ref(x::AbstractArray, i::Integer=1) = RefArray(x, i) - -function unsafe_convert(P::Type{Ptr{T}}, b::RefArray{T}) where T - if isbits(T) - convert(P, pointer(b.x, b.i)) - else - convert(P, data_pointer_from_objref(b.x[b.i])) - end -end -function unsafe_convert(P::Type{Ptr{Any}}, b::RefArray{Any}) - return convert(P, pointer(b.x, b.i)) -end -unsafe_convert(::Type{Ptr{Void}}, b::RefArray{T}) where {T} = convert(Ptr{Void}, unsafe_convert(Ptr{T}, b)) - -# convert Arrays to pointer arrays for ccall -function Ref{P}(a::Array{<:Union{Ptr,Cwstring,Cstring}}) where P<:Union{Ptr,Cwstring,Cstring} - return RefArray(a) # effectively a no-op -end -function Ref{P}(a::Array{T}) where P<:Union{Ptr,Cwstring,Cstring} where T - if (!isbits(T) && T <: eltype(P)) - # this Array already has the right memory layout for the requested Ref - return RefArray(a,1,false) # root something, so that this function is type-stable - else - ptrs = Vector{P}(length(a)+1) - roots = Vector{Any}(length(a)) - for i = 1:length(a) - root = cconvert(P, a[i]) - ptrs[i] = unsafe_convert(P, root)::P - roots[i] = root - end - ptrs[length(a)+1] = C_NULL - return RefArray(ptrs,1,roots) - end -end -cconvert(::Type{Ptr{P}}, a::Array{<:Ptr}) where {P<:Ptr} = a -cconvert(::Type{Ref{P}}, a::Array{<:Ptr}) where {P<:Ptr} = a -cconvert(::Type{Ptr{P}}, a::Array) where {P<:Union{Ptr,Cwstring,Cstring}} = Ref{P}(a) -cconvert(::Type{Ref{P}}, a::Array) where {P<:Union{Ptr,Cwstring,Cstring}} = Ref{P}(a) - -### - -getindex(b::RefValue) = b.x -getindex(b::RefArray) = b.x[b.i] - -setindex!(b::RefValue, x) = (b.x = x; b) -setindex!(b::RefArray, x) = (b.x[b.i] = x; b) - -### diff --git a/julia-0.6.3/share/julia/base/regex.jl b/julia-0.6.3/share/julia/base/regex.jl deleted file mode 100644 index e547716..0000000 --- a/julia-0.6.3/share/julia/base/regex.jl +++ /dev/null @@ -1,380 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -## object-oriented Regex interface ## - -include("pcre.jl") - -const DEFAULT_COMPILER_OPTS = PCRE.UTF | PCRE.NO_UTF_CHECK | PCRE.ALT_BSUX -const DEFAULT_MATCH_OPTS = PCRE.NO_UTF_CHECK - -mutable struct Regex - pattern::String - compile_options::UInt32 - match_options::UInt32 - regex::Ptr{Void} - extra::Ptr{Void} - ovec::Vector{Csize_t} - match_data::Ptr{Void} - - function Regex(pattern::AbstractString, compile_options::Integer, - match_options::Integer) - pattern = String(pattern) - compile_options = UInt32(compile_options) - match_options = UInt32(match_options) - if (compile_options & ~PCRE.COMPILE_MASK) != 0 - throw(ArgumentError("invalid regex compile options: $compile_options")) - end - if (match_options & ~PCRE.EXECUTE_MASK) !=0 - throw(ArgumentError("invalid regex match options: $match_options")) - end - re = compile(new(pattern, compile_options, match_options, C_NULL, - C_NULL, Csize_t[], C_NULL)) - finalizer(re, re->begin - re.regex == C_NULL || PCRE.free_re(re.regex) - re.match_data == C_NULL || PCRE.free_match_data(re.match_data) - end) - re - end -end - -function Regex(pattern::AbstractString, flags::AbstractString) - options = DEFAULT_COMPILER_OPTS - for f in flags - options |= f=='i' ? PCRE.CASELESS : - f=='m' ? PCRE.MULTILINE : - f=='s' ? PCRE.DOTALL : - f=='x' ? PCRE.EXTENDED : - throw(ArgumentError("unknown regex flag: $f")) - end - Regex(pattern, options, DEFAULT_MATCH_OPTS) -end -Regex(pattern::AbstractString) = Regex(pattern, DEFAULT_COMPILER_OPTS, DEFAULT_MATCH_OPTS) - -function compile(regex::Regex) - if regex.regex == C_NULL - regex.regex = PCRE.compile(regex.pattern, regex.compile_options) - PCRE.jit_compile(regex.regex) - regex.match_data = PCRE.create_match_data(regex.regex) - regex.ovec = PCRE.get_ovec(regex.match_data) - end - regex -end - -""" - @r_str -> Regex - -Construct a regex, such as `r"^[a-z]*\$"`. The regex also accepts one or more flags, listed -after the ending quote, to change its behaviour: - -- `i` enables case-insensitive matching -- `m` treats the `^` and `\$` tokens as matching the start and end of individual lines, as - opposed to the whole string. -- `s` allows the `.` modifier to match newlines. -- `x` enables "comment mode": whitespace is enabled except when escaped with `\\`, and `#` - is treated as starting a comment. - -For example, this regex has all three flags enabled: - -```jldoctest -julia> match(r"a+.*b+.*?d\$"ism, "Goodbye,\\nOh, angry,\\nBad world\\n") -RegexMatch("angry,\\nBad world") -``` -""" -macro r_str(pattern, flags...) Regex(pattern, flags...) end - -function show(io::IO, re::Regex) - imsx = PCRE.CASELESS|PCRE.MULTILINE|PCRE.DOTALL|PCRE.EXTENDED - opts = re.compile_options - if (opts & ~imsx) == DEFAULT_COMPILER_OPTS - print(io, 'r') - print_quoted_literal(io, re.pattern) - if (opts & PCRE.CASELESS ) != 0; print(io, 'i'); end - if (opts & PCRE.MULTILINE) != 0; print(io, 'm'); end - if (opts & PCRE.DOTALL ) != 0; print(io, 's'); end - if (opts & PCRE.EXTENDED ) != 0; print(io, 'x'); end - else - print(io, "Regex(") - show(io, re.pattern) - print(io, ',') - show(io, opts) - print(io, ')') - end -end - -# TODO: map offsets into strings in other encodings back to original indices. -# or maybe it's better to just fail since that would be quite slow - -struct RegexMatch - match::SubString{String} - captures::Vector{Union{Void,SubString{String}}} - offset::Int - offsets::Vector{Int} - regex::Regex -end - -function show(io::IO, m::RegexMatch) - print(io, "RegexMatch(") - show(io, m.match) - idx_to_capture_name = PCRE.capture_names(m.regex.regex) - if !isempty(m.captures) - print(io, ", ") - for i = 1:length(m.captures) - # If the capture group is named, show the name. - # Otherwise show its index. - capture_name = get(idx_to_capture_name, i, i) - print(io, capture_name, "=") - show(io, m.captures[i]) - if i < length(m.captures) - print(io, ", ") - end - end - end - print(io, ")") -end - -# Capture group extraction -getindex(m::RegexMatch, idx::Integer) = m.captures[idx] -function getindex(m::RegexMatch, name::Symbol) - idx = PCRE.substring_number_from_name(m.regex.regex, name) - idx <= 0 && error("no capture group named $name found in regex") - m[idx] -end -getindex(m::RegexMatch, name::AbstractString) = m[Symbol(name)] - -function ismatch(r::Regex, s::AbstractString, offset::Integer=0) - compile(r) - return PCRE.exec(r.regex, String(s), offset, r.match_options, - r.match_data) -end - -function ismatch(r::Regex, s::SubString, offset::Integer=0) - compile(r) - return PCRE.exec(r.regex, s, offset, r.match_options, - r.match_data) -end - -(r::Regex)(s) = ismatch(r, s) - -function match(re::Regex, str::Union{SubString{String}, String}, idx::Integer, add_opts::UInt32=UInt32(0)) - compile(re) - opts = re.match_options | add_opts - if !PCRE.exec(re.regex, str, idx-1, opts, re.match_data) - return nothing - end - ovec = re.ovec - n = div(length(ovec),2) - 1 - mat = SubString(str, ovec[1]+1, ovec[2]) - cap = Union{Void,SubString{String}}[ - ovec[2i+1] == PCRE.UNSET ? nothing : SubString(str, ovec[2i+1]+1, ovec[2i+2]) for i=1:n ] - off = Int[ ovec[2i+1]+1 for i=1:n ] - RegexMatch(mat, cap, ovec[1]+1, off, re) -end - -match(r::Regex, s::AbstractString) = match(r, s, start(s)) -match(r::Regex, s::AbstractString, i::Integer) = throw(ArgumentError( - "regex matching is only available for the String type; use String(s) to convert" -)) - -function matchall(re::Regex, str::String, overlap::Bool=false) - regex = compile(re).regex - n = sizeof(str) - matches = SubString{String}[] - offset = UInt32(0) - opts = re.match_options - opts_nonempty = opts | PCRE.ANCHORED | PCRE.NOTEMPTY_ATSTART - prevempty = false - ovec = re.ovec - while true - result = PCRE.exec(regex, str, offset, prevempty ? opts_nonempty : opts, re.match_data) - if !result - if prevempty && offset < n - offset = UInt32(nextind(str, offset + 1) - 1) - prevempty = false - continue - else - break - end - end - - push!(matches, SubString(str, ovec[1]+1, ovec[2])) - prevempty = offset == ovec[2] - if overlap - if !prevempty - offset = UInt32(ovec[1]+1) - end - else - offset = ovec[2] - end - end - matches -end - -matchall(re::Regex, str::SubString, overlap::Bool=false) = - matchall(re, String(str), overlap) - -function search(str::Union{String,SubString}, re::Regex, idx::Integer) - if idx > nextind(str,endof(str)) - throw(BoundsError()) - end - opts = re.match_options - compile(re) - PCRE.exec(re.regex, str, idx-1, opts, re.match_data) ? - ((Int(re.ovec[1])+1):prevind(str,Int(re.ovec[2])+1)) : (0:-1) -end -search(s::AbstractString, r::Regex, idx::Integer) = throw(ArgumentError( - "regex search is only available for the String type; use String(s) to convert" -)) -search(s::AbstractString, r::Regex) = search(s,r,start(s)) - -struct SubstitutionString{T<:AbstractString} <: AbstractString - string::T -end - -endof(s::SubstitutionString) = endof(s.string) -next(s::SubstitutionString, idx::Int) = next(s.string, idx) -function show(io::IO, s::SubstitutionString) - print(io, "s") - show(io, s.string) -end - -macro s_str(string) SubstitutionString(string) end - -replace_err(repl) = error("Bad replacement string: $repl") - -function _write_capture(io, re, group) - len = PCRE.substring_length_bynumber(re.match_data, group) - ensureroom(io, len+1) - PCRE.substring_copy_bynumber(re.match_data, group, - pointer(io.data, io.ptr), len+1) - io.ptr += len - io.size = max(io.size, io.ptr - 1) -end - -function _replace(io, repl_s::SubstitutionString, str, r, re) - const SUB_CHAR = '\\' - const GROUP_CHAR = 'g' - const LBRACKET = '<' - const RBRACKET = '>' - repl = repl_s.string - i = start(repl) - e = endof(repl) - while i <= e - if repl[i] == SUB_CHAR - next_i = nextind(repl, i) - next_i > e && replace_err(repl) - if repl[next_i] == SUB_CHAR - write(io, SUB_CHAR) - i = nextind(repl, next_i) - elseif isnumber(repl[next_i]) - group = parse(Int, repl[next_i]) - i = nextind(repl, next_i) - while i <= e - if isnumber(repl[i]) - group = 10group + parse(Int, repl[i]) - i = nextind(repl, i) - else - break - end - end - _write_capture(io, re, group) - elseif repl[next_i] == GROUP_CHAR - i = nextind(repl, next_i) - if i > e || repl[i] != LBRACKET - replace_err(repl) - end - i = nextind(repl, i) - i > e && replace_err(repl) - groupstart = i - while repl[i] != RBRACKET - i = nextind(repl, i) - i > e && replace_err(repl) - end - # TODO: avoid this allocation - groupname = SubString(repl, groupstart, prevind(repl, i)) - if all(isnumber,groupname) - _write_capture(io, re, parse(Int, groupname)) - else - group = PCRE.substring_number_from_name(re.regex, groupname) - group < 0 && replace_err("Group $groupname not found in regex $re") - _write_capture(io, re, group) - end - i = nextind(repl, i) - else - replace_err(repl) - end - else - write(io, repl[i]) - i = nextind(repl, i) - end - end -end - -struct RegexMatchIterator - regex::Regex - string::String - overlap::Bool - - function RegexMatchIterator(regex::Regex, string::AbstractString, ovr::Bool=false) - new(regex, string, ovr) - end -end -compile(itr::RegexMatchIterator) = (compile(itr.regex); itr) -eltype(::Type{RegexMatchIterator}) = RegexMatch -start(itr::RegexMatchIterator) = match(itr.regex, itr.string, 1, UInt32(0)) -done(itr::RegexMatchIterator, prev_match) = (prev_match === nothing) -iteratorsize(::Type{RegexMatchIterator}) = SizeUnknown() - -# Assumes prev_match is not nothing -function next(itr::RegexMatchIterator, prev_match) - prevempty = isempty(prev_match.match) - - if itr.overlap - if !prevempty - offset = nextind(itr.string, prev_match.offset) - else - offset = prev_match.offset - end - else - offset = prev_match.offset + sizeof(prev_match.match) - end - - opts_nonempty = UInt32(PCRE.ANCHORED | PCRE.NOTEMPTY_ATSTART) - while true - mat = match(itr.regex, itr.string, offset, - prevempty ? opts_nonempty : UInt32(0)) - - if mat === nothing - if prevempty && offset <= sizeof(itr.string) - offset = nextind(itr.string, offset) - prevempty = false - continue - else - break - end - else - return (prev_match, mat) - end - end - (prev_match, nothing) -end - -function eachmatch(re::Regex, str::AbstractString, ovr::Bool) - RegexMatchIterator(re,str,ovr) -end - -eachmatch(re::Regex, str::AbstractString) = RegexMatchIterator(re,str) - -## comparison ## - -function ==(a::Regex, b::Regex) - a.pattern == b.pattern && a.compile_options == b.compile_options && a.match_options == b.match_options -end - -## hash ## -const hashre_seed = UInt === UInt64 ? 0x67e195eb8555e72d : 0xe32373e4 -function hash(r::Regex, h::UInt) - h += hashre_seed - h = hash(r.pattern, h) - h = hash(r.compile_options, h) - h = hash(r.match_options, h) -end diff --git a/julia-0.6.3/share/julia/base/replutil.jl b/julia-0.6.3/share/julia/base/replutil.jl deleted file mode 100644 index f18f807..0000000 --- a/julia-0.6.3/share/julia/base/replutil.jl +++ /dev/null @@ -1,695 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -# fallback text/plain representation of any type: -show(io::IO, ::MIME"text/plain", x) = show(io, x) - -# multiline show functions for types defined before multimedia.jl: -function show(io::IO, ::MIME"text/plain", iter::Union{KeyIterator,ValueIterator}) - print(io, summary(iter)) - isempty(iter) && return - print(io, ". ", isa(iter,KeyIterator) ? "Keys" : "Values", ":") - limit::Bool = get(io, :limit, false) - if limit - sz = displaysize(io) - rows, cols = sz[1] - 3, sz[2] - rows < 2 && (print(io, " …"); return) - cols < 4 && (cols = 4) - cols -= 2 # For prefix " " - rows -= 2 # For summary and final ⋮ continuation lines - else - rows = cols = 0 - end - - for (i, v) in enumerate(iter) - print(io, "\n ") - limit && i >= rows && (print(io, "⋮"); break) - - if limit - str = sprint(0, show, v, env=io) - str = _truncate_at_width_or_chars(str, cols, "\r\n") - print(io, str) - else - show(io, v) - end - end -end - -function show(io::IO, ::MIME"text/plain", t::Associative{K,V}) where {K,V} - # show more descriptively, with one line per key/value pair - recur_io = IOContext(io, :SHOWN_SET => t) - limit::Bool = get(io, :limit, false) - if !haskey(io, :compact) - recur_io = IOContext(recur_io, :compact => true) - end - - print(io, summary(t)) - isempty(t) && return - print(io, ":\n ") - show_circular(io, t) && return - if limit - sz = displaysize(io) - rows, cols = sz[1] - 3, sz[2] - rows < 2 && (print(io, " …"); return) - cols < 12 && (cols = 12) # Minimum widths of 2 for key, 4 for value - cols -= 6 # Subtract the widths of prefix " " separator " => " - rows -= 2 # Subtract the summary and final ⋮ continuation lines - - # determine max key width to align the output, caching the strings - ks = Vector{AbstractString}(min(rows, length(t))) - vs = Vector{AbstractString}(min(rows, length(t))) - keylen = 0 - vallen = 0 - for (i, (k, v)) in enumerate(t) - i > rows && break - ks[i] = sprint(0, show, k, env=recur_io) - vs[i] = sprint(0, show, v, env=recur_io) - keylen = clamp(length(ks[i]), keylen, cols) - vallen = clamp(length(vs[i]), vallen, cols) - end - if keylen > max(div(cols, 2), cols - vallen) - keylen = max(cld(cols, 3), cols - vallen) - end - else - rows = cols = 0 - end - - first = true - for (i, (k, v)) in enumerate(t) - first || print(io, "\n ") - first = false - limit && i > rows && (print(io, rpad("⋮", keylen), " => ⋮"); break) - - if limit - key = rpad(_truncate_at_width_or_chars(ks[i], keylen, "\r\n"), keylen) - else - key = sprint(0, show, k, env=recur_io) - end - print(recur_io, key) - print(io, " => ") - - if limit - val = _truncate_at_width_or_chars(vs[i], cols - keylen, "\r\n") - print(io, val) - else - show(recur_io, v) - end - end -end - -function show(io::IO, ::MIME"text/plain", f::Function) - ft = typeof(f) - mt = ft.name.mt - if isa(f, Core.IntrinsicFunction) - show(io, f) - id = Core.Intrinsics.bitcast(Int32, f) - print(io, " (intrinsic function #$id)") - elseif isa(f, Core.Builtin) - print(io, mt.name, " (built-in function)") - else - name = mt.name - isself = isdefined(ft.name.module, name) && - ft == typeof(getfield(ft.name.module, name)) - n = length(methods(f)) - m = n==1 ? "method" : "methods" - ns = isself ? string(name) : string("(::", name, ")") - what = startswith(ns, '@') ? "macro" : "generic function" - print(io, ns, " (", what, " with $n $m)") - end -end - -function show(io::IO, ::MIME"text/plain", r::LinSpace) - # show for linspace, e.g. - # linspace(1,3,7) - # 7-element LinSpace{Float64}: - # 1.0,1.33333,1.66667,2.0,2.33333,2.66667,3.0 - print(io, summary(r)) - if !isempty(r) - println(io, ":") - print_range(io, r) - end -end - -function show(io::IO, ::MIME"text/plain", t::Task) - show(io, t) - if t.state == :failed - println(io) - showerror(io, CapturedException(t.result, t.backtrace)) - end -end - -show(io::IO, ::MIME"text/plain", X::AbstractArray) = showarray(io, X, false) -show(io::IO, ::MIME"text/plain", r::Range) = show(io, r) # always use the compact form for printing ranges - -# display something useful even for strings containing arbitrary -# (non-UTF8) binary data: -function show(io::IO, ::MIME"text/plain", s::String) - if isvalid(s) - show(io, s) - else - println(io, sizeof(s), "-byte String of invalid UTF-8 data:") - showarray(io, Vector{UInt8}(s), false; header=false) - end -end - -function show(io::IO, ::MIME"text/plain", opt::JLOptions) - println(io, "JLOptions(") - fields = fieldnames(opt) - nfields = length(fields) - for (i, f) in enumerate(fields) - v = getfield(opt, i) - if isa(v, Ptr{UInt8}) - v = (v != C_NULL) ? unsafe_string(v) : "" - end - println(io, " ", f, " = ", repr(v), i < nfields ? "," : "") - end - print(io, ")") -end - - -# showing exception objects as descriptive error messages - -showerror(io::IO, ex) = show(io, ex) - -function showerror(io::IO, ex::BoundsError) - print(io, "BoundsError") - if isdefined(ex, :a) - print(io, ": attempt to access ") - if isa(ex.a, AbstractArray) - print(io, summary(ex.a)) - else - show(io, MIME"text/plain"(), ex.a) - end - if isdefined(ex, :i) - !isa(ex.a, AbstractArray) && print(io, "\n ") - print(io, " at index [") - if isa(ex.i, Range) - print(io, ex.i) - else - join(io, ex.i, ", ") - end - print(io, ']') - end - end -end - -function showerror(io::IO, ex::TypeError) - print(io, "TypeError: ") - ctx = isempty(ex.context) ? "" : "in $(ex.context), " - if ex.expected === Bool - print(io, "non-boolean ($(typeof(ex.got))) used in boolean context") - else - if isa(ex.got, Type) - tstr = "Type{$(ex.got)}" - else - tstr = string(typeof(ex.got)) - end - print(io, "$(ex.func): $(ctx)expected $(ex.expected), got $tstr") - end -end - -function showerror(io::IO, ex, bt; backtrace=true) - try - with_output_color(have_color ? error_color() : :nothing, io) do io - showerror(io, ex) - end - finally - backtrace && show_backtrace(io, bt) - end -end - -function showerror(io::IO, ex::LoadError, bt; backtrace=true) - print(io, "LoadError: ") - showerror(io, ex.error, bt, backtrace=backtrace) - print(io, "\nwhile loading $(ex.file), in expression starting on line $(ex.line)") -end -showerror(io::IO, ex::LoadError) = showerror(io, ex, []) - -function showerror(io::IO, ex::InitError, bt; backtrace=true) - print(io, "InitError: ") - showerror(io, ex.error, bt, backtrace=backtrace) - print(io, "\nduring initialization of module $(ex.mod)") -end -showerror(io::IO, ex::InitError) = showerror(io, ex, []) - -function showerror(io::IO, ex::DomainError, bt; backtrace=true) - print(io, "DomainError:") - for b in bt - for code in StackTraces.lookup(b) - if code.from_c - continue - elseif code.func === :nan_dom_err - continue - elseif code.func in (:log, :log2, :log10, :sqrt) - print(io, "\n$(code.func) will only return a complex result if called ", - "with a complex argument. Try $(string(code.func))(complex(x)).") - elseif (code.func === :^ && - (code.file === Symbol("intfuncs.jl") || code.file === Symbol(joinpath(".", "intfuncs.jl")))) || - code.func === :power_by_squaring #3024 - print(io, "\nCannot raise an integer x to a negative power -n. ", - "\nMake x a float by adding a zero decimal (e.g. 2.0^-n instead ", - "of 2^-n), or write 1/x^n, float(x)^-n, or (x//1)^-n.") - elseif code.func === :^ && - (code.file === Symbol("math.jl") || code.file === Symbol(joinpath(".", "math.jl"))) - print(io, "\nExponentiation yielding a complex result requires a complex ", - "argument.\nReplace x^y with (x+0im)^y, Complex(x)^y, or similar.") - end - @goto showbacktrace - end - end - @label showbacktrace - backtrace && show_backtrace(io, bt) - nothing -end - -function showerror(io::IO, ex::SystemError) - if ex.extrainfo === nothing - print(io, "SystemError: $(ex.prefix): $(Libc.strerror(ex.errnum))") - else - print(io, "SystemError (with $(ex.extrainfo)): $(ex.prefix): $(Libc.strerror(ex.errnum))") - end -end -showerror(io::IO, ::DivideError) = print(io, "DivideError: integer division error") -showerror(io::IO, ::StackOverflowError) = print(io, "StackOverflowError:") -showerror(io::IO, ::UndefRefError) = print(io, "UndefRefError: access to undefined reference") -showerror(io::IO, ::EOFError) = print(io, "EOFError: read end of file") -function showerror(io::IO, ex::ErrorException) - print(io, ex.msg) - if ex.msg == "type String has no field data" - println(io) - print(io, "Use `Vector{UInt8}(str)` instead.") - end -end -showerror(io::IO, ex::KeyError) = print(io, "KeyError: key $(repr(ex.key)) not found") -showerror(io::IO, ex::InterruptException) = print(io, "InterruptException:") -showerror(io::IO, ex::ArgumentError) = print(io, "ArgumentError: $(ex.msg)") -showerror(io::IO, ex::AssertionError) = print(io, "AssertionError: $(ex.msg)") - -function showerror(io::IO, ex::UndefVarError) - if ex.var in [:UTF16String, :UTF32String, :WString, :utf16, :utf32, :wstring, :RepString] - return showerror(io, ErrorException(""" - `$(ex.var)` has been moved to the package LegacyStrings.jl: - Run Pkg.add("LegacyStrings") to install LegacyStrings on Julia v0.5-; - Then do `using LegacyStrings` to get `$(ex.var)`. - """)) - end - print(io, "UndefVarError: $(ex.var) not defined") -end - -function showerror(io::IO, ex::MethodError) - # ex.args is a tuple type if it was thrown from `invoke` and is - # a tuple of the arguments otherwise. - is_arg_types = isa(ex.args, DataType) - arg_types = is_arg_types ? ex.args : typesof(ex.args...) - f = ex.f - meth = methods_including_ambiguous(f, arg_types) - if length(meth) > 1 - return showerror_ambiguous(io, meth, f, arg_types) - end - arg_types_param::SimpleVector = arg_types.parameters - print(io, "MethodError: ") - ft = typeof(f) - name = ft.name.mt.name - f_is_function = false - kwargs = Any[] - if startswith(string(ft.name.name), "#kw#") - f = ex.args[2] - ft = typeof(f) - name = ft.name.mt.name - arg_types_param = arg_types_param[3:end] - temp = ex.args[1] - kwargs = Any[(temp[i*2-1], temp[i*2]) for i in 1:(length(temp) ÷ 2)] - ex = MethodError(f, ex.args[3:end]) - end - if f == Base.convert && length(arg_types_param) == 2 && !is_arg_types - f_is_function = true - # See #13033 - T = striptype(ex.args[1]) - if T === nothing - print(io, "First argument to `convert` must be a Type, got ", ex.args[1]) - else - print(io, "Cannot `convert` an object of type ", arg_types_param[2], " to an object of type ", T) - end - elseif isempty(methods(f)) && !isa(f, Function) - print(io, "objects of type $ft are not callable") - else - if ft <: Function && isempty(ft.parameters) && - isdefined(ft.name.module, name) && - ft == typeof(getfield(ft.name.module, name)) - f_is_function = true - print(io, "no method matching ", name) - elseif isa(f, Type) - if isa(f, DataType) && f.abstract - # Print a more appropriate message if the only method - # on the type is the default one from sysimg.jl. - ms = methods(f) - if length(ms) == 1 - m = first(ms) - if Base.is_default_method(m) - print(io, "no constructors have been defined for $f") - return - end - end - end - print(io, "no method matching ", f) - else - print(io, "no method matching (::", ft, ")") - end - print(io, "(") - for (i, typ) in enumerate(arg_types_param) - print(io, "::$typ") - i == length(arg_types_param) || print(io, ", ") - end - if !isempty(kwargs) - print(io, "; ") - for (i, (k, v)) in enumerate(kwargs) - print(io, k, "=") - show(IOContext(io, :limit=>true), v) - i == length(kwargs) || print(io, ", ") - end - end - print(io, ")") - end - if ft <: AbstractArray - print(io, "\nUse square brackets [] for indexing an Array.") - end - # Check for local functions that shadow methods in Base - if f_is_function && isdefined(Base, name) - basef = getfield(Base, name) - if basef !== ex.f && method_exists(basef, arg_types) - println(io) - print(io, "You may have intended to import Base.", name) - end - end - if (ex.world != typemax(UInt) && method_exists(ex.f, arg_types) && - !method_exists(ex.f, arg_types, ex.world)) - curworld = ccall(:jl_get_world_counter, UInt, ()) - println(io) - print(io, "The applicable method may be too new: running in world age $(ex.world), while current world is $(curworld).") - end - if !is_arg_types - # Check for row vectors used where a column vector is intended. - vec_args = [] - hasrows = false - for arg in ex.args - isrow = isa(arg,Array) && ndims(arg)==2 && size(arg,1)==1 - hasrows |= isrow - push!(vec_args, isrow ? vec(arg) : arg) - end - if hasrows && applicable(f, vec_args...) - print(io, "\n\nYou might have used a 2d row vector where a 1d column vector was required.", - "\nNote the difference between 1d column vector [1,2,3] and 2d row vector [1 2 3].", - "\nYou can convert to a column vector with the vec() function.") - end - end - # Give a helpful error message if the user likely called a type constructor - # and sees a no method error for convert - if (f === Base.convert && !isempty(arg_types_param) && !is_arg_types && - isa(arg_types_param[1], DataType) && - arg_types_param[1].name === Type.body.name) - construct_type = arg_types_param[1].parameters[1] - println(io) - print(io, "This may have arisen from a call to the constructor $construct_type(...),", - "\nsince type constructors fall back to convert methods.") - end - try - show_method_candidates(io, ex, kwargs) - catch - warn(io, "Error showing method candidates, aborted") - end -end - -striptype(::Type{T}) where {T} = T -striptype(::Any) = nothing - -function showerror_ambiguous(io::IO, meth, f, args) - print(io, "MethodError: ", f, "(") - p = args.parameters - for (i,a) in enumerate(p) - print(io, "::", a) - i < length(p) && print(io, ", ") - end - print(io, ") is ambiguous. Candidates:") - sigfix = Any - for m in meth - print(io, "\n ", m) - sigfix = typeintersect(m.sig, sigfix) - end - if isa(unwrap_unionall(sigfix), DataType) && sigfix <: Tuple - print(io, "\nPossible fix, define\n ") - Base.show_tuple_as_call(io, :function, sigfix) - end - nothing -end - -#Show an error by directly calling jl_printf. -#Useful in Base submodule __init__ functions where STDERR isn't defined yet. -function showerror_nostdio(err, msg::AbstractString) - stderr_stream = ccall(:jl_stderr_stream, Ptr{Void}, ()) - ccall(:jl_printf, Cint, (Ptr{Void},Cstring), stderr_stream, msg) - ccall(:jl_printf, Cint, (Ptr{Void},Cstring), stderr_stream, ":\n") - ccall(:jl_static_show, Csize_t, (Ptr{Void},Any), stderr_stream, err) - ccall(:jl_printf, Cint, (Ptr{Void},Cstring), stderr_stream, "\n") -end - -function show_method_candidates(io::IO, ex::MethodError, kwargs::Vector=Any[]) - is_arg_types = isa(ex.args, DataType) - arg_types = is_arg_types ? ex.args : typesof(ex.args...) - arg_types_param = Any[arg_types.parameters...] - # Displays the closest candidates of the given function by looping over the - # functions methods and counting the number of matching arguments. - f = ex.f - ft = typeof(f) - lines = [] - # These functions are special cased to only show if first argument is matched. - special = f in [convert, getindex, setindex!] - funcs = Any[(f, arg_types_param)] - - # An incorrect call method produces a MethodError for convert. - # It also happens that users type convert when they mean call. So - # pool MethodErrors for these two functions. - if f === convert && !isempty(arg_types_param) - at1 = arg_types_param[1] - if isa(at1,DataType) && (at1::DataType).name === Type.body.name && isleaftype(at1) - push!(funcs, (at1.parameters[1], arg_types_param[2:end])) - end - end - - for (func,arg_types_param) in funcs - for method in methods(func) - buf = IOBuffer() - tv = Any[] - sig0 = method.sig - if Base.is_default_method(method) - continue - end - while isa(sig0, UnionAll) - push!(tv, sig0.var) - sig0 = sig0.body - end - s1 = sig0.parameters[1] - sig = sig0.parameters[2:end] - print(buf, " ") - if !isa(func, s1) - # function itself doesn't match - return - else - # TODO: use the methodshow logic here - use_constructor_syntax = isa(func, Type) - print(buf, use_constructor_syntax ? func : typeof(func).name.mt.name) - end - print(buf, "(") - t_i = copy(arg_types_param) - right_matches = 0 - for i = 1 : min(length(t_i), length(sig)) - i > 1 && print(buf, ", ") - # If isvarargtype then it checks whether the rest of the input arguments matches - # the varargtype - if Base.isvarargtype(sig[i]) - sigstr = string(unwrap_unionall(sig[i]).parameters[1], "...") - j = length(t_i) - else - sigstr = string(sig[i]) - j = i - end - # Checks if the type of arg 1:i of the input intersects with the current method - t_in = typeintersect(rewrap_unionall(Tuple{sig[1:i]...}, method.sig), - rewrap_unionall(Tuple{t_i[1:j]...}, method.sig)) - # If the function is one of the special cased then it should break the loop if - # the type of the first argument is not matched. - t_in === Union{} && special && i == 1 && break - if t_in === Union{} - if Base.have_color - Base.with_output_color(Base.error_color(), buf) do buf - print(buf, "::$sigstr") - end - else - print(buf, "!Matched::$sigstr") - end - # If there is no typeintersect then the type signature from the method is - # inserted in t_i this ensures if the type at the next i matches the type - # signature then there will be a type intersect - t_i[i] = sig[i] - else - right_matches += j==i ? 1 : 0 - print(buf, "::$sigstr") - end - end - special && right_matches==0 && return # continue the do-block - - if length(t_i) > length(sig) && !isempty(sig) && Base.isvarargtype(sig[end]) - # It ensures that methods like f(a::AbstractString...) gets the correct - # number of right_matches - for t in arg_types_param[length(sig):end] - if t <: rewrap_unionall(unwrap_unionall(sig[end]).parameters[1], method.sig) - right_matches += 1 - end - end - end - - if right_matches > 0 || length(ex.args) < 2 - if length(t_i) < length(sig) - # If the methods args is longer than input then the method - # arguments is printed as not a match - for (k, sigtype) in enumerate(sig[length(t_i)+1:end]) - sigtype = isvarargtype(sigtype) ? unwrap_unionall(sigtype) : sigtype - if Base.isvarargtype(sigtype) - sigstr = string(sigtype.parameters[1], "...") - else - sigstr = string(sigtype) - end - if !((min(length(t_i), length(sig)) == 0) && k==1) - print(buf, ", ") - end - if Base.have_color - Base.with_output_color(Base.error_color(), buf) do buf - print(buf, "::$sigstr") - end - else - print(buf, "!Matched::$sigstr") - end - end - end - kwords = Symbol[] - if isdefined(ft.name.mt, :kwsorter) - kwsorter_t = typeof(ft.name.mt.kwsorter) - kwords = kwarg_decl(method, kwsorter_t) - length(kwords) > 0 && print(buf, "; ", join(kwords, ", ")) - end - print(buf, ")") - show_method_params(buf, tv) - print(buf, " at ", method.file, ":", method.line) - if !isempty(kwargs) - unexpected = Symbol[] - if isempty(kwords) || !(any(endswith(string(kword), "...") for kword in kwords)) - for (k, v) in kwargs - if !(k in kwords) - push!(unexpected, k) - end - end - end - if !isempty(unexpected) - Base.with_output_color(Base.error_color(), buf) do buf - plur = length(unexpected) > 1 ? "s" : "" - print(buf, " got unsupported keyword argument$plur \"", join(unexpected, "\", \""), "\"") - end - end - end - if ex.world < min_world(method) - print(buf, " (method too new to be called from this world context.)") - end - # TODO: indicate if it's in the wrong world - push!(lines, (buf, right_matches)) - end - end - end - - if !isempty(lines) # Display up to three closest candidates - Base.with_output_color(:normal, io) do io - println(io) - print(io, "Closest candidates are:") - sort!(lines, by = x -> -x[2]) - i = 0 - for line in lines - println(io) - if i >= 3 - print(io, " ...") - break - end - i += 1 - print(io, String(take!(line[1]))) - end - end - end -end - -function show_trace_entry(io, frame, n; prefix = "") - print(io, "\n", prefix) - show(io, frame, full_path=true) - n > 1 && print(io, " (repeats ", n, " times)") -end - -# Contains file name and file number. Gets set when a backtrace -# is shown. Used by the REPL to make it possible to open -# the location of a stackframe in the edítor. -global LAST_BACKTRACE_LINE_INFOS = Tuple{String, Int}[] - -function show_backtrace(io::IO, t::Vector) - n_frames = 0 - frame_counter = 0 - resize!(LAST_BACKTRACE_LINE_INFOS, 0) - process_backtrace((a,b) -> n_frames += 1, t) - n_frames != 0 && print(io, "\nStacktrace:") - process_entry = (last_frame, n) -> begin - frame_counter += 1 - show_trace_entry(IOContext(io, :backtrace => true), last_frame, n, prefix = string(" [", frame_counter, "] ")) - push!(LAST_BACKTRACE_LINE_INFOS, (string(last_frame.file), last_frame.line)) - end - process_backtrace(process_entry, t) -end - -function show_backtrace(io::IO, t::Vector{Any}) - for entry in t - show_trace_entry(io, entry...) - end -end - -# call process_func on each frame in a backtrace -function process_backtrace(process_func::Function, t::Vector, limit::Int=typemax(Int); skipC = true) - n = 0 - last_frame = StackTraces.UNKNOWN - count = 0 - for i = eachindex(t) - lkups = StackTraces.lookup(t[i]) - for lkup in lkups - if lkup === StackTraces.UNKNOWN - continue - end - - if lkup.from_c && skipC; continue; end - if i == 1 && lkup.func == :error; continue; end - count += 1 - if count > limit; break; end - - if lkup.file != last_frame.file || lkup.line != last_frame.line || lkup.func != last_frame.func - if n > 0 - process_func(last_frame, n) - end - n = 1 - last_frame = lkup - else - n += 1 - end - end - end - if n > 0 - process_func(last_frame, n) - end -end - -""" -Determines whether a method is the default method which is provided to all types from sysimg.jl. -Such a method is usually undesirable to be displayed to the user in the REPL. -""" -function is_default_method(m::Method) - return m.module == Base && m.file == Symbol("sysimg.jl") && m.sig == Tuple{Type{T},Any} where T -end diff --git a/julia-0.6.3/share/julia/base/reshapedarray.jl b/julia-0.6.3/share/julia/base/reshapedarray.jl deleted file mode 100644 index 5109359..0000000 --- a/julia-0.6.3/share/julia/base/reshapedarray.jl +++ /dev/null @@ -1,237 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -using Base.MultiplicativeInverses: SignedMultiplicativeInverse - -struct ReshapedArray{T,N,P<:AbstractArray,MI<:Tuple{Vararg{SignedMultiplicativeInverse{Int}}}} <: AbstractArray{T,N} - parent::P - dims::NTuple{N,Int} - mi::MI -end -ReshapedArray{T,N}(parent::AbstractArray{T}, dims::NTuple{N,Int}, mi) = ReshapedArray{T,N,typeof(parent),typeof(mi)}(parent, dims, mi) - -# IndexLinear ReshapedArray -const ReshapedArrayLF{T,N,P<:AbstractArray} = ReshapedArray{T,N,P,Tuple{}} - -# Fast iteration on ReshapedArrays: use the parent iterator -struct ReshapedArrayIterator{I,M} - iter::I - mi::NTuple{M,SignedMultiplicativeInverse{Int}} -end -ReshapedArrayIterator(A::ReshapedArray) = _rs_iterator(parent(A), A.mi) -function _rs_iterator(P, mi::NTuple{M}) where M - iter = eachindex(P) - ReshapedArrayIterator{typeof(iter),M}(iter, mi) -end - -struct ReshapedIndex{T} - parentindex::T -end - -# eachindex(A::ReshapedArray) = ReshapedArrayIterator(A) # TODO: uncomment this line -start(R::ReshapedArrayIterator) = start(R.iter) -@inline done(R::ReshapedArrayIterator, i) = done(R.iter, i) -@inline function next(R::ReshapedArrayIterator, i) - item, inext = next(R.iter, i) - ReshapedIndex(item), inext -end -length(R::ReshapedArrayIterator) = length(R.iter) - -""" - reshape(A, dims...) -> R - reshape(A, dims) -> R - -Return an array `R` with the same data as `A`, but with different -dimension sizes or number of dimensions. The two arrays share the same -underlying data, so that setting elements of `R` alters the values of -`A` and vice versa. - -The new dimensions may be specified either as a list of arguments or -as a shape tuple. At most one dimension may be specified with a `:`, -in which case its length is computed such that its product with all -the specified dimensions is equal to the length of the original array -`A`. The total number of elements must not change. - -```jldoctest -julia> A = collect(1:16) -16-element Array{Int64,1}: - 1 - 2 - 3 - 4 - 5 - 6 - 7 - 8 - 9 - 10 - 11 - 12 - 13 - 14 - 15 - 16 - -julia> reshape(A, (4, 4)) -4×4 Array{Int64,2}: - 1 5 9 13 - 2 6 10 14 - 3 7 11 15 - 4 8 12 16 - -julia> reshape(A, 2, :) -2×8 Array{Int64,2}: - 1 3 5 7 9 11 13 15 - 2 4 6 8 10 12 14 16 -``` - -""" -reshape - -reshape(parent::AbstractArray, dims::IntOrInd...) = reshape(parent, dims) -reshape(parent::AbstractArray, shp::NeedsShaping) = reshape(parent, to_shape(shp)) -reshape(parent::AbstractArray, dims::Dims) = _reshape(parent, dims) - -# Allow missing dimensions with Colon(): -reshape(parent::AbstractArray, dims::Int...) = reshape(parent, dims) -reshape(parent::AbstractArray, dims::Union{Int,Colon}...) = reshape(parent, dims) -reshape(parent::AbstractArray, dims::Tuple{Vararg{Union{Int,Colon}}}) = _reshape(parent, _reshape_uncolon(parent, dims)) -@inline function _reshape_uncolon(A, dims) - pre, post = _split_at_colon((), dims...) - if any(d -> d isa Colon, post) - throw(DimensionMismatch("new dimensions $(dims) may have at most one omitted dimension specified by Colon()")) - end - sz, remainder = divrem(length(A), prod(pre)*prod(post)) - remainder == 0 || _throw_reshape_colon_dimmismatch(A, dims) - (pre..., sz, post...) -end -@inline _split_at_colon(pre, dim::Any, tail...) = _split_at_colon((pre..., dim), tail...) -@inline _split_at_colon(pre, ::Colon, tail...) = (pre, tail) -_throw_reshape_colon_dimmismatch(A, dims) = - throw(DimensionMismatch("array size $(length(A)) must be divisible by the product of the new dimensions $dims")) - -reshape(parent::AbstractArray{T,N}, ndims::Type{Val{N}}) where {T,N} = parent -function reshape(parent::AbstractArray, ndims::Type{Val{N}}) where N - reshape(parent, rdims((), indices(parent), Val{N})) -end -# Move elements from inds to out until out reaches the desired -# dimensionality N, either filling with OneTo(1) or collapsing the -# product of trailing dims into the last element -@pure rdims(out::NTuple{N,Any}, inds::Tuple{}, ::Type{Val{N}}) where {N} = out -@pure function rdims(out::NTuple{N,Any}, inds::Tuple{Any, Vararg{Any}}, ::Type{Val{N}}) where N - l = length(last(out)) * prod(map(length, inds)) - (front(out)..., OneTo(l)) -end -@pure rdims(out::Tuple, inds::Tuple{}, ::Type{Val{N}}) where {N} = rdims((out..., OneTo(1)), (), Val{N}) -@pure rdims(out::Tuple, inds::Tuple{Any, Vararg{Any}}, ::Type{Val{N}}) where {N} = rdims((out..., first(inds)), tail(inds), Val{N}) - -# _reshape on Array returns an Array -_reshape(parent::Vector, dims::Dims{1}) = parent -_reshape(parent::Array, dims::Dims{1}) = reshape(parent, dims) -_reshape(parent::Array, dims::Dims) = reshape(parent, dims) - -# When reshaping Vector->Vector, don't wrap with a ReshapedArray -function _reshape(v::AbstractVector, dims::Dims{1}) - len = dims[1] - len == length(v) || throw(DimensionMismatch("parent has $(length(v)) elements, which is incompatible with length $len")) - v -end -# General reshape -function _reshape(parent::AbstractArray, dims::Dims) - n = _length(parent) - prod(dims) == n || throw(DimensionMismatch("parent has $n elements, which is incompatible with size $dims")) - __reshape((parent, IndexStyle(parent)), dims) -end - -# Reshaping a ReshapedArray -_reshape(v::ReshapedArray{<:Any,1}, dims::Dims{1}) = _reshape(v.parent, dims) -_reshape(R::ReshapedArray, dims::Dims) = _reshape(R.parent, dims) - -function __reshape(p::Tuple{AbstractArray,IndexCartesian}, dims::Dims) - parent = p[1] - strds = front(size_strides(parent)) - strds1 = map(s->max(1,s), strds) # for resizing empty arrays - mi = map(SignedMultiplicativeInverse, strds1) - ReshapedArray(parent, dims, reverse(mi)) -end - -function __reshape(p::Tuple{AbstractArray,IndexLinear}, dims::Dims) - parent = p[1] - ReshapedArray(parent, dims, ()) -end - -@inline size_strides(A::AbstractArray) = tail(size_strides((1,), size(A)...)) -size_strides(out::Tuple) = out -@inline size_strides(out, s, sz...) = size_strides((out..., out[end]*s), sz...) - -size(A::ReshapedArray) = A.dims -similar(A::ReshapedArray, eltype::Type, dims::Dims) = similar(parent(A), eltype, dims) -IndexStyle(::Type{<:ReshapedArrayLF}) = IndexLinear() -parent(A::ReshapedArray) = A.parent -parentindexes(A::ReshapedArray) = map(s->1:s, size(parent(A))) -reinterpret(::Type{T}, A::ReshapedArray, dims::Dims) where {T} = reinterpret(T, parent(A), dims) - -@inline ind2sub_rs(::Tuple{}, i::Int) = i -@inline ind2sub_rs(strds, i) = ind2sub_rs((), strds, i-1) -@inline ind2sub_rs(out, ::Tuple{}, ind) = (ind+1, out...) -@inline function ind2sub_rs(out, strds, ind) - d, r = divrem(ind, strds[1]) - ind2sub_rs((d+1, out...), tail(strds), r) -end - -@inline function getindex(A::ReshapedArrayLF, index::Int) - @boundscheck checkbounds(A, index) - @inbounds ret = parent(A)[index] - ret -end -@inline function getindex(A::ReshapedArray, indexes::Int...) - @boundscheck checkbounds(A, indexes...) - _unsafe_getindex(A, indexes...) -end -@inline function getindex(A::ReshapedArray, index::ReshapedIndex) - @boundscheck checkbounds(parent(A), index.parentindex) - @inbounds ret = parent(A)[index.parentindex] - ret -end - -@inline function _unsafe_getindex(A::ReshapedArray, indexes::Int...) - @inbounds ret = parent(A)[ind2sub_rs(A.mi, sub2ind(size(A), indexes...))...] - ret -end -@inline function _unsafe_getindex(A::ReshapedArrayLF, indexes::Int...) - @inbounds ret = parent(A)[sub2ind(size(A), indexes...)] - ret -end - -@inline function setindex!(A::ReshapedArrayLF, val, index::Int) - @boundscheck checkbounds(A, index) - @inbounds parent(A)[index] = val - val -end -@inline function setindex!(A::ReshapedArray, val, indexes::Int...) - @boundscheck checkbounds(A, indexes...) - _unsafe_setindex!(A, val, indexes...) -end -@inline function setindex!(A::ReshapedArray, val, index::ReshapedIndex) - @boundscheck checkbounds(parent(A), index.parentindex) - @inbounds parent(A)[index.parentindex] = val - val -end - -@inline function _unsafe_setindex!(A::ReshapedArray, val, indexes::Int...) - @inbounds parent(A)[ind2sub_rs(A.mi, sub2ind(size(A), indexes...))...] = val - val -end -@inline function _unsafe_setindex!(A::ReshapedArrayLF, val, indexes::Int...) - @inbounds parent(A)[sub2ind(size(A), indexes...)] = val - val -end - -# helpful error message for a common failure case -const ReshapedRange{T,N,A<:Range} = ReshapedArray{T,N,A,Tuple{}} -setindex!(A::ReshapedRange, val, index::Int) = _rs_setindex!_err() -setindex!(A::ReshapedRange, val, indexes::Int...) = _rs_setindex!_err() -setindex!(A::ReshapedRange, val, index::ReshapedIndex) = _rs_setindex!_err() - -_rs_setindex!_err() = error("indexed assignment fails for a reshaped range; consider calling collect") - -unsafe_convert(::Type{Ptr{T}}, a::ReshapedArray{T}) where {T} = unsafe_convert(Ptr{T}, parent(a)) diff --git a/julia-0.6.3/share/julia/base/rounding.jl b/julia-0.6.3/share/julia/base/rounding.jl deleted file mode 100644 index bcb9b63..0000000 --- a/julia-0.6.3/share/julia/base/rounding.jl +++ /dev/null @@ -1,243 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -module Rounding - -let fenv_consts = Vector{Cint}(9) - ccall(:jl_get_fenv_consts, Void, (Ptr{Cint},), fenv_consts) - global const JL_FE_INEXACT = fenv_consts[1] - global const JL_FE_UNDERFLOW = fenv_consts[2] - global const JL_FE_OVERFLOW = fenv_consts[3] - global const JL_FE_DIVBYZERO = fenv_consts[4] - global const JL_FE_INVALID = fenv_consts[5] - - global const JL_FE_TONEAREST = fenv_consts[6] - global const JL_FE_UPWARD = fenv_consts[7] - global const JL_FE_DOWNWARD = fenv_consts[8] - global const JL_FE_TOWARDZERO = fenv_consts[9] -end - -export - RoundingMode, RoundNearest, RoundToZero, RoundUp, RoundDown, RoundFromZero, - RoundNearestTiesAway, RoundNearestTiesUp, - rounding, setrounding, - get_zero_subnormals, set_zero_subnormals - -## rounding modes ## -""" - RoundingMode - -A type used for controlling the rounding mode of floating point operations (via -[`rounding`](@ref)/[`setrounding`](@ref) functions), or as -optional arguments for rounding to the nearest integer (via the [`round`](@ref) -function). - -Currently supported rounding modes are: - -- [`RoundNearest`](@ref) (default) -- [`RoundNearestTiesAway`](@ref) -- [`RoundNearestTiesUp`](@ref) -- [`RoundToZero`](@ref) -- `RoundFromZero` ([`BigFloat`](@ref) only) -- [`RoundUp`](@ref) -- [`RoundDown`](@ref) -""" -struct RoundingMode{T} end - -""" - RoundNearest - -The default rounding mode. Rounds to the nearest integer, with ties (fractional values of -0.5) being rounded to the nearest even integer. -""" -const RoundNearest = RoundingMode{:Nearest}() - -""" - RoundToZero - -[`round`](@ref) using this rounding mode is an alias for [`trunc`](@ref). -""" -const RoundToZero = RoundingMode{:ToZero}() - -""" - RoundUp - -[`round`](@ref) using this rounding mode is an alias for [`ceil`](@ref). -""" -const RoundUp = RoundingMode{:Up}() - -""" - RoundDown - -[`round`](@ref) using this rounding mode is an alias for [`floor`](@ref). -""" -const RoundDown = RoundingMode{:Down}() - -const RoundFromZero = RoundingMode{:FromZero}() # mpfr only - -""" - RoundNearestTiesAway - -Rounds to nearest integer, with ties rounded away from zero (C/C++ -[`round`](@ref) behaviour). -""" -const RoundNearestTiesAway = RoundingMode{:NearestTiesAway}() - -""" - RoundNearestTiesUp - -Rounds to nearest integer, with ties rounded toward positive infinity (Java/JavaScript -[`round`](@ref) behaviour). -""" -const RoundNearestTiesUp = RoundingMode{:NearestTiesUp}() - -to_fenv(::RoundingMode{:Nearest}) = JL_FE_TONEAREST -to_fenv(::RoundingMode{:ToZero}) = JL_FE_TOWARDZERO -to_fenv(::RoundingMode{:Up}) = JL_FE_UPWARD -to_fenv(::RoundingMode{:Down}) = JL_FE_DOWNWARD - -function from_fenv(r::Integer) - if r == JL_FE_TONEAREST - return RoundNearest - elseif r == JL_FE_DOWNWARD - return RoundDown - elseif r == JL_FE_UPWARD - return RoundUp - elseif r == JL_FE_TOWARDZERO - return RoundToZero - else - throw(ArgumentError("invalid rounding mode code: $r")) - end -end - -""" - setrounding(T, mode) - -Set the rounding mode of floating point type `T`, controlling the rounding of basic -arithmetic functions ([`+`](@ref), [`-`](@ref), [`*`](@ref), -[`/`](@ref) and [`sqrt`](@ref)) and type conversion. Other numerical -functions may give incorrect or invalid values when using rounding modes other than the -default `RoundNearest`. - -Note that this may affect other types, for instance changing the rounding mode of -[`Float64`](@ref) will change the rounding mode of [`Float32`](@ref). -See [`RoundingMode`](@ref) for available modes. - -!!! warning - - This feature is still experimental, and may give unexpected or incorrect values. -""" -setrounding(T::Type, mode) - -""" - rounding(T) - -Get the current floating point rounding mode for type `T`, controlling the rounding of basic -arithmetic functions ([`+`](@ref), [`-`](@ref), [`*`](@ref), [`/`](@ref) -and [`sqrt`](@ref)) and type conversion. - -See [`RoundingMode`](@ref) for available modes. -""" -:rounding - -setrounding_raw(::Type{<:Union{Float32,Float64}}, i::Integer) = ccall(:fesetround, Int32, (Int32,), i) -rounding_raw(::Type{<:Union{Float32,Float64}}) = ccall(:fegetround, Int32, ()) - -setrounding(::Type{T}, r::RoundingMode) where {T<:Union{Float32,Float64}} = setrounding_raw(T,to_fenv(r)) -rounding(::Type{T}) where {T<:Union{Float32,Float64}} = from_fenv(rounding_raw(T)) - -""" - setrounding(f::Function, T, mode) - -Change the rounding mode of floating point type `T` for the duration of `f`. It is logically -equivalent to: - - old = rounding(T) - setrounding(T, mode) - f() - setrounding(T, old) - -See [`RoundingMode`](@ref) for available rounding modes. - -!!! warning - - This feature is still experimental, and may give unexpected or incorrect values. A - known problem is the interaction with compiler optimisations, e.g. - - julia> setrounding(Float64,RoundDown) do - 1.1 + 0.1 - end - 1.2000000000000002 - - Here the compiler is *constant folding*, that is evaluating a known constant - expression at compile time, however the rounding mode is only changed at runtime, so - this is not reflected in the function result. This can be avoided by moving constants - outside the expression, e.g. - - julia> x = 1.1; y = 0.1; - - julia> setrounding(Float64,RoundDown) do - x + y - end - 1.2 -""" -function setrounding(f::Function, ::Type{T}, rounding::RoundingMode) where T - old_rounding_raw = rounding_raw(T) - setrounding(T,rounding) - try - return f() - finally - setrounding_raw(T,old_rounding_raw) - end -end - - -# Should be equivalent to: -# setrounding(Float64,r) do -# convert(T,x) -# end -# but explicit checks are currently quicker (~20x). -# Assumes conversion is performed by rounding to nearest value. - -# To avoid ambiguous dispatch with methods in mpfr.jl: -(::Type{T})(x::Real, r::RoundingMode) where {T<:AbstractFloat} = _convert_rounding(T,x,r) - -_convert_rounding(::Type{T}, x::Real, r::RoundingMode{:Nearest}) where {T<:AbstractFloat} = convert(T,x) -function _convert_rounding(::Type{T}, x::Real, r::RoundingMode{:Down}) where T<:AbstractFloat - y = convert(T,x) - y > x ? prevfloat(y) : y -end -function _convert_rounding(::Type{T}, x::Real, r::RoundingMode{:Up}) where T<:AbstractFloat - y = convert(T,x) - y < x ? nextfloat(y) : y -end -function _convert_rounding(::Type{T}, x::Real, r::RoundingMode{:ToZero}) where T<:AbstractFloat - y = convert(T,x) - if x > 0.0 - y > x ? prevfloat(y) : y - else - y < x ? nextfloat(y) : y - end -end - -""" - set_zero_subnormals(yes::Bool) -> Bool - -If `yes` is `false`, subsequent floating-point operations follow rules for IEEE arithmetic -on subnormal values ("denormals"). Otherwise, floating-point operations are permitted (but -not required) to convert subnormal inputs or outputs to zero. Returns `true` unless -`yes==true` but the hardware does not support zeroing of subnormal numbers. - -`set_zero_subnormals(true)` can speed up some computations on some hardware. However, it can -break identities such as `(x-y==0) == (x==y)`. -""" -set_zero_subnormals(yes::Bool) = ccall(:jl_set_zero_subnormals,Int32,(Int8,),yes)==0 - -""" - get_zero_subnormals() -> Bool - -Returns `false` if operations on subnormal floating-point values ("denormals") obey rules -for IEEE arithmetic, and `true` if they might be converted to zeros. -""" -get_zero_subnormals() = ccall(:jl_get_zero_subnormals,Int32,())!=0 - -end #module diff --git a/julia-0.6.3/share/julia/base/serialize.jl b/julia-0.6.3/share/julia/base/serialize.jl deleted file mode 100644 index b3f3f9d..0000000 --- a/julia-0.6.3/share/julia/base/serialize.jl +++ /dev/null @@ -1,1119 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -module Serializer - -import Base: GMP, Bottom, unsafe_convert, uncompressed_ast -import Core: svec -using Base: ViewIndex, Slice, index_lengths, unwrap_unionall - -export serialize, deserialize, SerializationState - -mutable struct SerializationState{I<:IO} <: AbstractSerializer - io::I - counter::Int - table::ObjectIdDict - pending_refs::Vector{Int} - known_object_data::Dict{UInt64,Any} - SerializationState{I}(io::I) where I<:IO = new(io, 0, ObjectIdDict(), Int[], Dict{UInt64,Any}()) -end - -SerializationState(io::IO) = SerializationState{typeof(io)}(io) - -## serializing values ## - -# types AbstractSerializer and Serializer # defined in dict.jl - -const n_int_literals = 33 -const n_reserved_slots = 12 - -const TAGS = Any[ - Symbol, Int8, UInt8, Int16, UInt16, Int32, UInt32, Int64, UInt64, Int128, UInt128, - Float16, Float32, Float64, Char, DataType, Union, UnionAll, TypeName, Tuple, - Array, Expr, LineNumberNode, LabelNode, GotoNode, QuoteNode, CodeInfo, TypeVar, - Core.Box, Core.MethodInstance, Module, Task, String, SimpleVector, Method, - GlobalRef, SlotNumber, TypedSlot, NewvarNode, SSAValue, - - # dummy entries for tags that don't correspond directly to types - Symbol, # UNDEFREF_TAG - Symbol, # BACKREF_TAG - Symbol, # LONGBACKREF_TAG - Symbol, # SHORTBACKREF_TAG - Symbol, # LONGTUPLE_TAG - Symbol, # LONGSYMBOL_TAG - Symbol, # LONGEXPR_TAG - Symbol, # LONGSTRING_TAG - Symbol, # SHORTINT64_TAG - Symbol, # FULL_DATATYPE_TAG - Symbol, # WRAPPER_DATATYPE_TAG - Symbol, # OBJECT_TAG - Symbol, # REF_OBJECT_TAG - Symbol, # FULL_GLOBALREF_TAG - - (), Bool, Any, Bottom, Core.TypeofBottom, Type, svec(), Tuple{}, false, true, nothing, - :Any, :Array, :TypeVar, :Box, :Tuple, :Ptr, :return, :call, Symbol("::"), :Function, - :(=), :(==), :(===), :gotoifnot, :A, :B, :C, :M, :N, :T, :S, :X, :Y, :a, :b, :c, :d, :e, :f, - :g, :h, :i, :j, :k, :l, :m, :n, :o, :p, :q, :r, :s, :t, :u, :v, :w, :x, :y, :z, :add_int, - :sub_int, :mul_int, :add_float, :sub_float, :new, :mul_float, :bitcast, :start, :done, :next, - :indexed_next, :getfield, :meta, :eq_int, :slt_int, :sle_int, :ne_int, :push_loc, :pop_loc, - :pop, :arrayset, :arrayref, :apply_type, :inbounds, :getindex, :setindex!, :Core, :!, :+, - :Base, :static_parameter, :convert, :colon, Symbol("#self#"), Symbol("#temp#"), :tuple, - - fill(:_reserved_, n_reserved_slots)..., - - (Int32(0):Int32(n_int_literals-1))..., - (Int64(0):Int64(n_int_literals-1))... -] - -@assert length(TAGS) <= 255 - -const ser_version = 6 # do not make changes without bumping the version #! - -const NTAGS = length(TAGS) - -function sertag(v::ANY) - ptr = pointer_from_objref(v) - ptags = convert(Ptr{Ptr{Void}}, pointer(TAGS)) - # note: constant ints & reserved slots never returned here - @inbounds for i in 1:(NTAGS-(n_reserved_slots+2*n_int_literals)) - ptr == unsafe_load(ptags,i) && return i%Int32 - end - return Int32(-1) -end -desertag(i::Int32) = TAGS[i] - -# tags >= this just represent themselves, their whole representation is 1 byte -const VALUE_TAGS = sertag(()) -const ZERO32_TAG = Int32(NTAGS-(2*n_int_literals-1)) -const ZERO64_TAG = Int64(NTAGS-(n_int_literals-1)) -const TRUE_TAG = sertag(true) -const FALSE_TAG = sertag(false) -const EMPTYTUPLE_TAG = sertag(()) -const TUPLE_TAG = sertag(Tuple) -const SIMPLEVECTOR_TAG = sertag(SimpleVector) -const SYMBOL_TAG = sertag(Symbol) -const ARRAY_TAG = sertag(Array) -const EXPR_TAG = sertag(Expr) -const MODULE_TAG = sertag(Module) -const METHODINSTANCE_TAG = sertag(Core.MethodInstance) -const METHOD_TAG = sertag(Method) -const TASK_TAG = sertag(Task) -const DATATYPE_TAG = sertag(DataType) -const TYPENAME_TAG = sertag(TypeName) -const INT32_TAG = sertag(Int32) -const INT64_TAG = sertag(Int64) -const GLOBALREF_TAG = sertag(GlobalRef) -const BOTTOM_TAG = sertag(Bottom) -const UNIONALL_TAG = sertag(UnionAll) -const STRING_TAG = sertag(String) -const o0 = sertag(SSAValue) -const UNDEFREF_TAG = Int32(o0+1) -const BACKREF_TAG = Int32(o0+2) -const LONGBACKREF_TAG = Int32(o0+3) -const SHORTBACKREF_TAG = Int32(o0+4) -const LONGTUPLE_TAG = Int32(o0+5) -const LONGSYMBOL_TAG = Int32(o0+6) -const LONGEXPR_TAG = Int32(o0+7) -const LONGSTRING_TAG = Int32(o0+8) -const SHORTINT64_TAG = Int32(o0+9) -const FULL_DATATYPE_TAG = Int32(o0+10) -const WRAPPER_DATATYPE_TAG = Int32(o0+11) -const OBJECT_TAG = Int32(o0+12) -const REF_OBJECT_TAG = Int32(o0+13) -const FULL_GLOBALREF_TAG = Int32(o0+14) - -writetag(s::IO, tag) = write(s, UInt8(tag)) - -function write_as_tag(s::IO, tag) - tag < VALUE_TAGS && write(s, UInt8(0)) - write(s, UInt8(tag)) -end - -# cycle handling -function serialize_cycle(s::AbstractSerializer, x) - offs = get(s.table, x, -1)::Int - if offs != -1 - if offs <= typemax(UInt16) - writetag(s.io, SHORTBACKREF_TAG) - write(s.io, UInt16(offs)) - elseif offs <= typemax(Int32) - writetag(s.io, BACKREF_TAG) - write(s.io, Int32(offs)) - else - writetag(s.io, LONGBACKREF_TAG) - write(s.io, Int64(offs)) - end - return true - end - s.table[x] = s.counter - s.counter += 1 - return false -end - -function serialize_cycle_header(s::AbstractSerializer, x::ANY) - serialize_cycle(s, x) && return true - serialize_type(s, typeof(x), true) - return false -end - -function reset_state(s::AbstractSerializer) - s.counter = 0 - empty!(s.table) - empty!(s.pending_refs) - s -end - -serialize(s::AbstractSerializer, x::Bool) = x ? writetag(s.io, TRUE_TAG) : - writetag(s.io, FALSE_TAG) - -serialize(s::AbstractSerializer, p::Ptr) = serialize_any(s, oftype(p, C_NULL)) - -serialize(s::AbstractSerializer, ::Tuple{}) = writetag(s.io, EMPTYTUPLE_TAG) - -function serialize(s::AbstractSerializer, t::Tuple) - l = length(t) - if l <= 255 - writetag(s.io, TUPLE_TAG) - write(s.io, UInt8(l)) - else - writetag(s.io, LONGTUPLE_TAG) - write(s.io, Int32(l)) - end - for x in t - serialize(s, x) - end -end - -function serialize(s::AbstractSerializer, v::SimpleVector) - writetag(s.io, SIMPLEVECTOR_TAG) - write(s.io, Int32(length(v))) - for x in v - serialize(s, x) - end -end - -function serialize(s::AbstractSerializer, x::Symbol) - tag = sertag(x) - if tag > 0 - return write_as_tag(s.io, tag) - end - pname = unsafe_convert(Ptr{UInt8}, x) - len = Int(ccall(:strlen, Csize_t, (Cstring,), pname)) - if len > 7 - serialize_cycle(s, x) && return - end - if len <= 255 - writetag(s.io, SYMBOL_TAG) - write(s.io, UInt8(len)) - else - writetag(s.io, LONGSYMBOL_TAG) - write(s.io, Int32(len)) - end - unsafe_write(s.io, pname, len) -end - -function serialize_array_data(s::IO, a) - isempty(a) && return 0 - if eltype(a) === Bool - last = a[1] - count = 1 - for i = 2:length(a) - if a[i] != last || count == 127 - write(s, UInt8((UInt8(last) << 7) | count)) - last = a[i] - count = 1 - else - count += 1 - end - end - write(s, UInt8((UInt8(last) << 7) | count)) - else - write(s, a) - end -end - -function serialize(s::AbstractSerializer, a::Array) - serialize_cycle(s, a) && return - elty = eltype(a) - writetag(s.io, ARRAY_TAG) - if elty !== UInt8 - serialize(s, elty) - end - if ndims(a) != 1 - serialize(s, size(a)) - else - serialize(s, length(a)) - end - if isbits(elty) - serialize_array_data(s.io, a) - else - sizehint!(s.table, div(length(a),4)) # prepare for lots of pointers - @inbounds for i in eachindex(a) - if isassigned(a, i) - serialize(s, a[i]) - else - writetag(s.io, UNDEFREF_TAG) - end - end - end -end - -function serialize(s::AbstractSerializer, a::SubArray{T,N,A}) where {T,N,A<:Array} - b = trimmedsubarray(a) - serialize_any(s, b) -end - -function trimmedsubarray(V::SubArray{T,N,A}) where {T,N,A<:Array} - dest = Array{eltype(V)}(trimmedsize(V)) - copy!(dest, V) - _trimmedsubarray(dest, V, (), V.indexes...) -end - -trimmedsize(V) = index_lengths(V.indexes...) - -function _trimmedsubarray(A, V::SubArray{T,N,P,I,LD}, newindexes) where {T,N,P,I,LD} - LD && return SubArray{T,N,P,I,LD}(A, newindexes, Base.compute_offset1(A, 1, newindexes), 1) - SubArray{T,N,P,I,LD}(A, newindexes, 0, 0) -end -_trimmedsubarray(A, V, newindexes, index::ViewIndex, indexes...) = _trimmedsubarray(A, V, (newindexes..., trimmedindex(V.parent, length(newindexes)+1, index)), indexes...) - -trimmedindex(P, d, i::Real) = oftype(i, 1) -trimmedindex(P, d, i::Colon) = i -trimmedindex(P, d, i::Slice) = i -trimmedindex(P, d, i::AbstractArray) = oftype(i, reshape(linearindices(i), indices(i))) - -function serialize(s::AbstractSerializer, ss::String) - len = sizeof(ss) - if len <= 255 - writetag(s.io, STRING_TAG) - write(s.io, UInt8(len)) - else - writetag(s.io, LONGSTRING_TAG) - write(s.io, Int64(len)) - end - write(s.io, ss) -end - -function serialize(s::AbstractSerializer, ss::SubString{T}) where T<:AbstractString - # avoid saving a copy of the parent string, keeping the type of ss - serialize_any(s, convert(SubString{T}, convert(T,ss))) -end - -# Don't serialize the pointers -function serialize(s::AbstractSerializer, r::Regex) - serialize_type(s, typeof(r)) - serialize(s, r.pattern) - serialize(s, r.compile_options) - serialize(s, r.match_options) -end - -function serialize(s::AbstractSerializer, n::BigInt) - serialize_type(s, BigInt) - serialize(s, base(62,n)) -end - -function serialize(s::AbstractSerializer, n::BigFloat) - serialize_type(s, BigFloat) - serialize(s, string(n)) -end - -function serialize(s::AbstractSerializer, ex::Expr) - serialize_cycle(s, ex) && return - l = length(ex.args) - if l <= 255 - writetag(s.io, EXPR_TAG) - write(s.io, UInt8(l)) - else - writetag(s.io, LONGEXPR_TAG) - write(s.io, Int32(l)) - end - serialize(s, ex.head) - serialize(s, ex.typ) - for a in ex.args - serialize(s, a) - end -end - -function serialize(s::AbstractSerializer, d::Dict) - serialize_cycle_header(s, d) && return - write(s.io, Int32(length(d))) - for (k,v) in d - serialize(s, k) - serialize(s, v) - end -end - -function serialize_mod_names(s::AbstractSerializer, m::Module) - p = module_parent(m) - if m !== p - serialize_mod_names(s, p) - serialize(s, module_name(m)) - end -end - -function serialize(s::AbstractSerializer, m::Module) - writetag(s.io, MODULE_TAG) - serialize_mod_names(s, m) - writetag(s.io, EMPTYTUPLE_TAG) -end - -# TODO: make this bidirectional, so objects can be sent back via the same key -const object_numbers = WeakKeyDict() -const obj_number_salt = Ref(0) -function object_number(l::ANY) - global obj_number_salt, object_numbers - if haskey(object_numbers, l) - return object_numbers[l] - end - # a hash function that always gives the same number to the same - # object on the same machine, and is unique over all machines. - ln = obj_number_salt[]+(UInt64(myid())<<44) - obj_number_salt[] += 1 - object_numbers[l] = ln - return ln::UInt64 -end - -lookup_object_number(s::AbstractSerializer, n::UInt64) = nothing - -remember_object(s::AbstractSerializer, o::ANY, n::UInt64) = nothing - -function lookup_object_number(s::SerializationState, n::UInt64) - return get(s.known_object_data, n, nothing) -end - -function remember_object(s::SerializationState, o::ANY, n::UInt64) - s.known_object_data[n] = o - return nothing -end - -function serialize(s::AbstractSerializer, meth::Method) - serialize_cycle(s, meth) && return - writetag(s.io, METHOD_TAG) - write(s.io, object_number(meth)) - serialize(s, meth.module) - serialize(s, meth.name) - serialize(s, meth.file) - serialize(s, meth.line) - serialize(s, meth.sig) - serialize(s, meth.sparam_syms) - serialize(s, meth.ambig) - serialize(s, meth.nargs) - serialize(s, meth.isva) - serialize(s, meth.isstaged) - serialize(s, uncompressed_ast(meth, meth.source)) - nothing -end - -function serialize(s::AbstractSerializer, linfo::Core.MethodInstance) - serialize_cycle(s, linfo) && return - isdefined(linfo, :def) && error("can only serialize toplevel MethodInstance objects") - writetag(s.io, METHODINSTANCE_TAG) - serialize(s, linfo.inferred) - if isdefined(linfo, :inferred_const) - serialize(s, linfo.inferred_const) - else - writetag(s.io, UNDEFREF_TAG) - end - serialize(s, linfo.sparam_vals) - serialize(s, linfo.rettype) - serialize(s, linfo.specTypes) -end - -function serialize(s::AbstractSerializer, t::Task) - serialize_cycle(s, t) && return - if istaskstarted(t) && !istaskdone(t) - error("cannot serialize a running Task") - end - state = [t.code, - t.storage, - t.state == :queued || t.state == :runnable ? (:runnable) : t.state, - t.result, - t.exception] - writetag(s.io, TASK_TAG) - for fld in state - serialize(s, fld) - end -end - -function serialize(s::AbstractSerializer, g::GlobalRef) - if (g.mod === __deserialized_types__ ) || - (g.mod === Main && isdefined(g.mod, g.name) && isconst(g.mod, g.name)) - - v = getfield(g.mod, g.name) - unw = unwrap_unionall(v) - if isa(unw,DataType) && v === unw.name.wrapper && should_send_whole_type(s, unw) - # handle references to types in Main by sending the whole type. - # needed to be able to send nested functions (#15451). - writetag(s.io, FULL_GLOBALREF_TAG) - serialize(s, v) - return - end - end - writetag(s.io, GLOBALREF_TAG) - serialize(s, g.mod) - serialize(s, g.name) -end - -function serialize(s::AbstractSerializer, t::TypeName) - serialize_cycle(s, t) && return - writetag(s.io, TYPENAME_TAG) - write(s.io, object_number(t)) - serialize_typename(s, t) -end - -function serialize_typename(s::AbstractSerializer, t::TypeName) - serialize(s, t.name) - serialize(s, t.names) - primary = unwrap_unionall(t.wrapper) - serialize(s, primary.super) - serialize(s, primary.parameters) - serialize(s, primary.types) - serialize(s, isdefined(primary, :instance)) - serialize(s, primary.abstract) - serialize(s, primary.mutable) - serialize(s, primary.ninitialized) - if isdefined(t, :mt) - serialize(s, t.mt.name) - serialize(s, collect(Base.MethodList(t.mt))) - serialize(s, t.mt.max_args) - if isdefined(t.mt, :kwsorter) - serialize(s, t.mt.kwsorter) - else - writetag(s.io, UNDEFREF_TAG) - end - else - writetag(s.io, UNDEFREF_TAG) - end - nothing -end - -# decide whether to send all data for a type (instead of just its name) -function should_send_whole_type(s, t::DataType) - tn = t.name - if isdefined(tn, :mt) - # TODO improve somehow - # send whole type for anonymous functions in Main - name = tn.mt.name - mod = tn.module - isanonfunction = mod === Main && # only Main - t.super === Function && # only Functions - unsafe_load(unsafe_convert(Ptr{UInt8}, tn.name)) == UInt8('#') && # hidden type - (!isdefined(mod, name) || t != typeof(getfield(mod, name))) # XXX: 95% accurate test for this being an inner function - # TODO: more accurate test? (tn.name !== "#" name) - #TODO: iskw = startswith(tn.name, "#kw#") && ??? - #TODO: iskw && return send-as-kwftype - return mod === __deserialized_types__ || isanonfunction - end - return false -end - -function serialize_type_data(s, t::DataType) - whole = should_send_whole_type(s, t) - iswrapper = (t === unwrap_unionall(t.name.wrapper)) - if whole && iswrapper - writetag(s.io, WRAPPER_DATATYPE_TAG) - serialize(s, t.name) - return - end - serialize_cycle(s, t) && return - if whole - writetag(s.io, FULL_DATATYPE_TAG) - serialize(s, t.name) - else - writetag(s.io, DATATYPE_TAG) - tname = t.name.name - serialize(s, tname) - mod = t.name.module - serialize(s, mod) - end - if !isempty(t.parameters) - if iswrapper - write(s.io, Int32(0)) - else - write(s.io, Int32(length(t.parameters))) - for p in t.parameters - serialize(s, p) - end - end - end -end - -function serialize(s::AbstractSerializer, t::DataType) - tag = sertag(t) - tag > 0 && return write_as_tag(s.io, tag) - if t === Tuple - # `sertag` is not able to find types === to `Tuple` because they - # will not have been hash-consed. Plus `serialize_type_data` does not - # handle this case correctly, since Tuple{} != Tuple. `Tuple` is the - # only type with this property. issue #15849 - return write_as_tag(s.io, TUPLE_TAG) - end - serialize_type_data(s, t) -end - -function serialize_type(s::AbstractSerializer, t::DataType, ref::Bool = false) - tag = sertag(t) - tag > 0 && return writetag(s.io, tag) - writetag(s.io, ref ? REF_OBJECT_TAG : OBJECT_TAG) - serialize_type_data(s, t) -end - -function serialize(s::AbstractSerializer, n::Int32) - if 0 <= n <= (n_int_literals-1) - write(s.io, UInt8(ZERO32_TAG+n)) - else - writetag(s.io, INT32_TAG) - write(s.io, n) - end -end - -function serialize(s::AbstractSerializer, n::Int64) - if 0 <= n <= (n_int_literals-1) - write(s.io, UInt8(ZERO64_TAG+n)) - elseif typemin(Int32) <= n <= typemax(Int32) - writetag(s.io, SHORTINT64_TAG) - write(s.io, Int32(n)) - else - writetag(s.io, INT64_TAG) - write(s.io, n) - end -end - -serialize(s::AbstractSerializer, ::Type{Bottom}) = write_as_tag(s.io, BOTTOM_TAG) - -function serialize(s::AbstractSerializer, u::UnionAll) - writetag(s.io, UNIONALL_TAG) - n = 0; t = u - while isa(t, UnionAll) - t = t.body - n += 1 - end - if isa(t, DataType) && t === unwrap_unionall(t.name.wrapper) - write(s.io, UInt8(1)) - write(s.io, Int16(n)) - serialize(s, t) - else - write(s.io, UInt8(0)) - serialize(s, u.var) - serialize(s, u.body) - end -end - -serialize(s::AbstractSerializer, x::ANY) = serialize_any(s, x) - -function serialize_any(s::AbstractSerializer, x::ANY) - tag = sertag(x) - if tag > 0 - return write_as_tag(s.io, tag) - end - t = typeof(x)::DataType - nf = nfields(t) - if nf == 0 && t.size > 0 - serialize_type(s, t) - write(s.io, x) - else - if t.mutable && nf > 0 - serialize_cycle(s, x) && return - serialize_type(s, t, true) - else - serialize_type(s, t, false) - end - for i in 1:nf - if isdefined(x, i) - serialize(s, getfield(x, i)) - else - writetag(s.io, UNDEFREF_TAG) - end - end - end -end - -serialize(s::IO, x) = serialize(SerializationState(s), x) - -## deserializing values ## - -deserialize(s::IO) = deserialize(SerializationState(s)) - -function deserialize(s::AbstractSerializer) - handle_deserialize(s, Int32(read(s.io, UInt8)::UInt8)) -end - -function deserialize_cycle(s::AbstractSerializer, x::ANY) - slot = pop!(s.pending_refs) - s.table[slot] = x - nothing -end - -# optimized version of: -# slot = s.counter; s.counter += 1 -# push!(s.pending_refs, slot) -# slot = pop!(s.pending_refs) -# s.table[slot] = x -function resolve_ref_immediately(s::AbstractSerializer, x::ANY) - s.table[s.counter] = x - s.counter += 1 - nothing -end - -# deserialize_ is an internal function to dispatch on the tag -# describing the serialized representation. the number of -# representations is fixed, so deserialize_ does not get extended. -function handle_deserialize(s::AbstractSerializer, b::Int32) - if b == 0 - return desertag(Int32(read(s.io, UInt8)::UInt8)) - end - if b >= VALUE_TAGS - return desertag(b) - elseif b == TUPLE_TAG - return deserialize_tuple(s, Int(read(s.io, UInt8)::UInt8)) - elseif b == SHORTBACKREF_TAG - id = read(s.io, UInt16)::UInt16 - return s.table[Int(id)] - elseif b == BACKREF_TAG - id = read(s.io, Int32)::Int32 - return s.table[Int(id)] - elseif b == ARRAY_TAG - return deserialize_array(s) - elseif b == DATATYPE_TAG - return deserialize_datatype(s, false) - elseif b == FULL_DATATYPE_TAG - return deserialize_datatype(s, true) - elseif b == WRAPPER_DATATYPE_TAG - tname = deserialize(s)::TypeName - return unwrap_unionall(tname.wrapper) - elseif b == OBJECT_TAG - t = deserialize(s) - return deserialize(s, t) - elseif b == REF_OBJECT_TAG - slot = s.counter; s.counter += 1 - push!(s.pending_refs, slot) - t = deserialize(s) - return deserialize(s, t) - elseif b == SYMBOL_TAG - return deserialize_symbol(s, Int(read(s.io, UInt8)::UInt8)) - elseif b == SHORTINT64_TAG - return Int64(read(s.io, Int32)::Int32) - elseif b == EXPR_TAG - return deserialize_expr(s, Int(read(s.io, UInt8)::UInt8)) - elseif b == MODULE_TAG - return deserialize_module(s) - elseif b == STRING_TAG - return deserialize_string(s, Int(read(s.io, UInt8)::UInt8)) - elseif b == LONGSTRING_TAG - return deserialize_string(s, Int(read(s.io, Int64)::Int64)) - elseif b == SIMPLEVECTOR_TAG - return deserialize_svec(s) - elseif b == GLOBALREF_TAG - return GlobalRef(deserialize(s)::Module, deserialize(s)::Symbol) - elseif b == FULL_GLOBALREF_TAG - ty = deserialize(s) - tn = unwrap_unionall(ty).name - return GlobalRef(tn.module, tn.name) - elseif b == LONGTUPLE_TAG - return deserialize_tuple(s, Int(read(s.io, Int32)::Int32)) - elseif b == LONGEXPR_TAG - return deserialize_expr(s, Int(read(s.io, Int32)::Int32)) - elseif b == LONGBACKREF_TAG - id = read(s.io, Int64)::Int64 - return s.table[Int(id)] - elseif b == LONGSYMBOL_TAG - return deserialize_symbol(s, Int(read(s.io, Int32)::Int32)) - end - t = desertag(b) - if t.mutable && nfields(t) > 0 - slot = s.counter; s.counter += 1 - push!(s.pending_refs, slot) - end - return deserialize(s, t) -end - -function deserialize_symbol(s::AbstractSerializer, len::Int) - str = Base._string_n(len) - unsafe_read(s.io, pointer(str), len) - sym = Symbol(str) - if len > 7 - resolve_ref_immediately(s, sym) - end - return sym -end - -deserialize_tuple(s::AbstractSerializer, len) = ntuple(i->deserialize(s), len) - -function deserialize_svec(s::AbstractSerializer) - n = read(s.io, Int32) - svec(Any[ deserialize(s) for i=1:n ]...) -end - -function deserialize_module(s::AbstractSerializer) - path = deserialize(s) - m = Main - if isa(path,Tuple) && path !== () - # old version - for mname in path - m = getfield(m,mname)::Module - end - else - mname = path - while mname !== () - m = getfield(m,mname)::Module - mname = deserialize(s) - end - end - m -end - -function deserialize(s::AbstractSerializer, ::Type{Method}) - lnumber = read(s.io, UInt64) - meth = lookup_object_number(s, lnumber) - if meth !== nothing - meth = meth::Method - makenew = false - else - meth = ccall(:jl_new_method_uninit, Ref{Method}, ()) - makenew = true - end - deserialize_cycle(s, meth) - mod = deserialize(s)::Module - name = deserialize(s)::Symbol - file = deserialize(s)::Symbol - line = deserialize(s)::Int32 - sig = deserialize(s)::Type - sparam_syms = deserialize(s)::SimpleVector - ambig = deserialize(s)::Union{Array{Any,1}, Void} - nargs = deserialize(s)::Int32 - isva = deserialize(s)::Bool - isstaged = deserialize(s)::Bool - template = deserialize(s)::CodeInfo - if makenew - meth.module = mod - meth.name = name - meth.file = file - meth.line = line - meth.sig = sig - meth.sparam_syms = sparam_syms - meth.ambig = ambig - meth.isstaged = isstaged - meth.nargs = nargs - meth.isva = isva - # TODO: compress template - meth.source = template - meth.pure = template.pure - if isstaged - linfo = ccall(:jl_new_method_instance_uninit, Ref{Core.MethodInstance}, ()) - linfo.specTypes = Tuple - linfo.inferred = template - meth.generator = linfo - end - ftype = ccall(:jl_first_argument_datatype, Any, (Any,), sig)::DataType - if isdefined(ftype.name, :mt) && nothing === ccall(:jl_methtable_lookup, Any, (Any, Any, UInt), ftype.name.mt, sig, typemax(UInt)) - ccall(:jl_method_table_insert, Void, (Any, Any, Ptr{Void}), ftype.name.mt, meth, C_NULL) - end - remember_object(s, meth, lnumber) - end - return meth -end - -function deserialize(s::AbstractSerializer, ::Type{Core.MethodInstance}) - linfo = ccall(:jl_new_method_instance_uninit, Ref{Core.MethodInstance}, (Ptr{Void},), C_NULL) - deserialize_cycle(s, linfo) - linfo.inferred = deserialize(s)::CodeInfo - tag = Int32(read(s.io, UInt8)::UInt8) - if tag != UNDEFREF_TAG - linfo.inferred_const = handle_deserialize(s, tag) - end - linfo.sparam_vals = deserialize(s)::SimpleVector - linfo.rettype = deserialize(s) - linfo.specTypes = deserialize(s) - return linfo -end - -function deserialize_array(s::AbstractSerializer) - slot = s.counter; s.counter += 1 - d1 = deserialize(s) - if isa(d1, Type) - elty = d1 - d1 = deserialize(s) - else - elty = UInt8 - end - if isa(d1, Integer) - if elty !== Bool && isbits(elty) - a = Array{elty, 1}(d1) - s.table[slot] = a - return read!(s.io, a) - end - dims = (Int(d1),) - else - dims = convert(Dims, d1)::Dims - end - if isbits(elty) - n = prod(dims)::Int - if elty === Bool && n > 0 - A = Array{Bool, length(dims)}(dims) - i = 1 - while i <= n - b = read(s.io, UInt8)::UInt8 - v = (b >> 7) != 0 - count = b & 0x7f - nxt = i + count - while i < nxt - A[i] = v - i += 1 - end - end - else - A = read(s.io, elty, dims) - end - s.table[slot] = A - return A - end - A = Array{elty, length(dims)}(dims) - s.table[slot] = A - sizehint!(s.table, s.counter + div(length(A),4)) - for i = eachindex(A) - tag = Int32(read(s.io, UInt8)::UInt8) - if tag != UNDEFREF_TAG - @inbounds A[i] = handle_deserialize(s, tag) - end - end - return A -end - -function deserialize_expr(s::AbstractSerializer, len) - e = Expr(:temp) - resolve_ref_immediately(s, e) - e.head = deserialize(s)::Symbol - ty = deserialize(s) - e.args = Any[ deserialize(s) for i = 1:len ] - e.typ = ty - e -end - -module __deserialized_types__ end - -function deserialize(s::AbstractSerializer, ::Type{TypeName}) - number = read(s.io, UInt64) - return deserialize_typename(s, number) -end - -function deserialize_typename(s::AbstractSerializer, number) - name = deserialize(s)::Symbol - tn = lookup_object_number(s, number) - if tn !== nothing - makenew = false - else - # reuse the same name for the type, if possible, for nicer debugging - tn_name = isdefined(__deserialized_types__, name) ? gensym() : name - tn = ccall(:jl_new_typename_in, Ref{TypeName}, (Any, Any), - tn_name, __deserialized_types__) - makenew = true - end - remember_object(s, tn, number) - deserialize_cycle(s, tn) - - names = deserialize(s)::SimpleVector - super = deserialize(s)::Type - parameters = deserialize(s)::SimpleVector - types = deserialize(s)::SimpleVector - has_instance = deserialize(s)::Bool - abstr = deserialize(s)::Bool - mutabl = deserialize(s)::Bool - ninitialized = deserialize(s)::Int32 - - if makenew - tn.names = names - # TODO: there's an unhanded cycle in the dependency graph at this point: - # while deserializing super and/or types, we may have encountered - # tn.wrapper and throw UndefRefException before we get to this point - ndt = ccall(:jl_new_datatype, Any, (Any, Any, Any, Any, Any, Cint, Cint, Cint), - tn, super, parameters, names, types, - abstr, mutabl, ninitialized) - tn.wrapper = ndt.name.wrapper - ccall(:jl_set_const, Void, (Any, Any, Any), tn.module, tn.name, tn.wrapper) - ty = tn.wrapper - if has_instance && !isdefined(ty, :instance) - # use setfield! directly to avoid `fieldtype` lowering expecting to see a Singleton object already on ty - Core.setfield!(ty, :instance, ccall(:jl_new_struct, Any, (Any, Any...), ty)) - end - end - - tag = Int32(read(s.io, UInt8)::UInt8) - if tag != UNDEFREF_TAG - mtname = handle_deserialize(s, tag) - defs = deserialize(s) - maxa = deserialize(s)::Int - if makenew - tn.mt = ccall(:jl_new_method_table, Any, (Any, Any), name, tn.module) - tn.mt.name = mtname - tn.mt.max_args = maxa - for def in defs - if isdefined(def, :sig) - ccall(:jl_method_table_insert, Void, (Any, Any, Ptr{Void}), tn.mt, def, C_NULL) - end - end - end - tag = Int32(read(s.io, UInt8)::UInt8) - if tag != UNDEFREF_TAG - kws = handle_deserialize(s, tag) - if makenew - tn.mt.kwsorter = kws - end - end - end - return tn::TypeName -end - -function deserialize_datatype(s::AbstractSerializer, full::Bool) - slot = s.counter; s.counter += 1 - if full - tname = deserialize(s)::TypeName - ty = tname.wrapper - else - name = deserialize(s)::Symbol - mod = deserialize(s)::Module - ty = getfield(mod,name) - end - if isa(ty,DataType) && isempty(ty.parameters) - t = ty - else - np = Int(read(s.io, Int32)::Int32) - if np == 0 - t = unwrap_unionall(ty) - elseif ty === Tuple - # note np==0 has its own tag - if np == 1 - t = Tuple{deserialize(s)} - elseif np == 2 - t = Tuple{deserialize(s), deserialize(s)} - elseif np == 3 - t = Tuple{deserialize(s), deserialize(s), deserialize(s)} - elseif np == 4 - t = Tuple{deserialize(s), deserialize(s), deserialize(s), deserialize(s)} - else - t = Tuple{Any[ deserialize(s) for i=1:np ]...} - end - else - t = ty - for i = 1:np - t = t{deserialize(s)} - end - end - end - s.table[slot] = t - return t -end - -function deserialize(s::AbstractSerializer, ::Type{UnionAll}) - form = read(s.io, UInt8) - if form == 0 - var = deserialize(s) - body = deserialize(s) - return UnionAll(var, body) - else - n = read(s.io, Int16) - t = deserialize(s)::DataType - w = t.name.wrapper - k = 0 - while isa(w, UnionAll) - w = w.body - k += 1 - end - w = t.name.wrapper - k -= n - while k > 0 - w = w.body - k -= 1 - end - return w - end -end - -function deserialize(s::AbstractSerializer, ::Type{Task}) - t = Task(()->nothing) - deserialize_cycle(s, t) - t.code = deserialize(s) - t.storage = deserialize(s) - t.state = deserialize(s) - t.result = deserialize(s) - t.exception = deserialize(s) - t -end - -function deserialize_string(s::AbstractSerializer, len::Int) - out = ccall(:jl_alloc_string, Ref{String}, (Csize_t,), len) - unsafe_read(s.io, pointer(out), len) - return out -end - -# default DataType deserializer -function deserialize(s::AbstractSerializer, t::DataType) - nf = nfields(t) - if nf == 0 && t.size > 0 - # bits type - return read(s.io, t) - end - if nf == 0 - return ccall(:jl_new_struct, Any, (Any,Any...), t) - elseif isbits(t) - if nf == 1 - f1 = deserialize(s) - return ccall(:jl_new_struct, Any, (Any,Any...), t, f1) - elseif nf == 2 - f1 = deserialize(s) - f2 = deserialize(s) - return ccall(:jl_new_struct, Any, (Any,Any...), t, f1, f2) - elseif nf == 3 - f1 = deserialize(s) - f2 = deserialize(s) - f3 = deserialize(s) - return ccall(:jl_new_struct, Any, (Any,Any...), t, f1, f2, f3) - else - flds = Any[ deserialize(s) for i = 1:nf ] - return ccall(:jl_new_structv, Any, (Any,Ptr{Void},UInt32), t, flds, nf) - end - else - x = ccall(:jl_new_struct_uninit, Any, (Any,), t) - t.mutable && deserialize_cycle(s, x) - for i in 1:nf - tag = Int32(read(s.io, UInt8)::UInt8) - if tag != UNDEFREF_TAG - ccall(:jl_set_nth_field, Void, (Any, Csize_t, Any), x, i-1, handle_deserialize(s, tag)) - end - end - return x - end -end - -function deserialize(s::AbstractSerializer, T::Type{Dict{K,V}}) where {K,V} - n = read(s.io, Int32) - t = T(); sizehint!(t, n) - deserialize_cycle(s, t) - for i = 1:n - k = deserialize(s) - v = deserialize(s) - t[k] = v - end - return t -end - -deserialize(s::AbstractSerializer, ::Type{BigFloat}) = parse(BigFloat, deserialize(s)) - -deserialize(s::AbstractSerializer, ::Type{BigInt}) = parse(BigInt, deserialize(s), 62) - -function deserialize(s::AbstractSerializer, t::Type{Regex}) - pattern = deserialize(s) - compile_options = deserialize(s) - match_options = deserialize(s) - Regex(pattern, compile_options, match_options) -end - -if !is_windows() - function serialize(s::AbstractSerializer, rd::RandomDevice) - serialize_type(s, typeof(rd)) - serialize(s, rd.unlimited) - end - function deserialize(s::AbstractSerializer, t::Type{RandomDevice}) - unlimited = deserialize(s) - return RandomDevice(unlimited) - end -end -end diff --git a/julia-0.6.3/share/julia/base/set.jl b/julia-0.6.3/share/julia/base/set.jl deleted file mode 100644 index 411c23e..0000000 --- a/julia-0.6.3/share/julia/base/set.jl +++ /dev/null @@ -1,256 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -mutable struct Set{T} <: AbstractSet{T} - dict::Dict{T,Void} - - Set{T}() where {T} = new(Dict{T,Void}()) - Set{T}(itr) where {T} = union!(new(Dict{T,Void}()), itr) -end -Set() = Set{Any}() -Set(itr) = Set{eltype(itr)}(itr) -function Set(g::Generator) - T = _default_eltype(typeof(g)) - (isleaftype(T) || T === Union{}) || return grow_to!(Set{T}(), g) - return Set{T}(g) -end - -eltype(::Type{Set{T}}) where {T} = T -similar(s::Set{T}) where {T} = Set{T}() -similar(s::Set, T::Type) = Set{T}() - -function show(io::IO, s::Set) - print(io,"Set") - if isempty(s) - print(io,"{",eltype(s),"}()") - return - end - print(io,"(") - show_vector(io,s,"[","]") - print(io,")") -end - -isempty(s::Set) = isempty(s.dict) -length(s::Set) = length(s.dict) -in(x, s::Set) = haskey(s.dict, x) -push!(s::Set, x) = (s.dict[x] = nothing; s) -pop!(s::Set, x) = (pop!(s.dict, x); x) -pop!(s::Set, x, deflt) = x in s ? pop!(s, x) : deflt -pop!(s::Set) = (idx = start(s.dict); val = s.dict.keys[idx]; _delete!(s.dict, idx); val) -delete!(s::Set, x) = (delete!(s.dict, x); s) - -copy(s::Set) = union!(similar(s), s) - -sizehint!(s::Set, newsz) = (sizehint!(s.dict, newsz); s) -empty!(s::Set) = (empty!(s.dict); s) -rehash!(s::Set) = (rehash!(s.dict); s) - -start(s::Set) = start(s.dict) -done(s::Set, state) = done(s.dict, state) -# NOTE: manually optimized to take advantage of Dict representation -next(s::Set, i) = (s.dict.keys[i], skip_deleted(s.dict,i+1)) - -union() = Set() -union(s::Set) = copy(s) -function union(s::Set, sets::Set...) - u = Set{join_eltype(s, sets...)}() - union!(u,s) - for t in sets - union!(u,t) - end - return u -end -const ∪ = union -union!(s::Set, xs) = (for x=xs; push!(s,x); end; s) -union!(s::Set, xs::AbstractArray) = (sizehint!(s,length(xs));for x=xs; push!(s,x); end; s) -join_eltype() = Bottom -join_eltype(v1, vs...) = typejoin(eltype(v1), join_eltype(vs...)) - -intersect(s::Set) = copy(s) -function intersect(s::Set, sets::Set...) - i = similar(s) - for x in s - inall = true - for t in sets - if !in(x,t) - inall = false - break - end - end - inall && push!(i, x) - end - return i -end -const ∩ = intersect - -function setdiff(a::Set, b::Set) - d = similar(a) - for x in a - if !(x in b) - push!(d, x) - end - end - d -end -setdiff!(s::Set, xs) = (for x=xs; delete!(s,x); end; s) - -==(l::Set, r::Set) = (length(l) == length(r)) && (l <= r) -<( l::Set, r::Set) = (length(l) < length(r)) && (l <= r) -<=(l::Set, r::Set) = issubset(l, r) - -function issubset(l, r) - for elt in l - if !in(elt, r) - return false - end - end - return true -end -const ⊆ = issubset -⊊(l::Set, r::Set) = <(l, r) -⊈(l::Set, r::Set) = !⊆(l, r) -⊇(l, r) = issubset(r, l) -⊉(l::Set, r::Set) = !⊇(l, r) -⊋(l::Set, r::Set) = <(r, l) - -""" - unique(itr) - -Returns an array containing one value from `itr` for each unique value, -as determined by [`isequal`](@ref). - -```jldoctest -julia> unique([1; 2; 2; 6]) -3-element Array{Int64,1}: - 1 - 2 - 6 -``` -""" -function unique(itr) - T = _default_eltype(typeof(itr)) - out = Vector{T}() - seen = Set{T}() - i = start(itr) - if done(itr, i) - return out - end - x, i = next(itr, i) - if !isleaftype(T) - S = typeof(x) - return _unique_from(itr, S[x], Set{S}((x,)), i) - end - push!(seen, x) - push!(out, x) - return unique_from(itr, out, seen, i) -end - -_unique_from(itr, out, seen, i) = unique_from(itr, out, seen, i) -@inline function unique_from{T}(itr, out::Vector{T}, seen, i) - while !done(itr, i) - x, i = next(itr, i) - S = typeof(x) - if !(S === T || S <: T) - R = typejoin(S, T) - seenR = convert(Set{R}, seen) - outR = convert(Vector{R}, out) - if !in(x, seenR) - push!(seenR, x) - push!(outR, x) - end - return _unique_from(itr, outR, seenR, i) - end - if !in(x, seen) - push!(seen, x) - push!(out, x) - end - end - return out -end - -""" - unique(f, itr) - -Returns an array containing one value from `itr` for each unique value produced by `f` -applied to elements of `itr`. - -```jldoctest -julia> unique(isodd, [1; 2; 2; 6]) -2-element Array{Int64,1}: - 1 - 2 -``` -""" -function unique(f::Callable, C) - out = Vector{eltype(C)}() - seen = Set() - for x in C - y = f(x) - if !in(y, seen) - push!(seen, y) - push!(out, x) - end - end - out -end - -""" - allunique(itr) -> Bool - -Return `true` if all values from `itr` are distinct when compared with [`isequal`](@ref). - -```jldoctest -julia> a = [1; 2; 3] -3-element Array{Int64,1}: - 1 - 2 - 3 - -julia> allunique([a, a]) -false -``` -""" -function allunique(C) - seen = Set{eltype(C)}() - for x in C - if in(x, seen) - return false - else - push!(seen, x) - end - end - true -end - -allunique(::Set) = true - -allunique(r::Range{T}) where {T} = (step(r) != zero(T)) || (length(r) <= 1) - -function filter(f, s::Set) - u = similar(s) - for x in s - if f(x) - push!(u, x) - end - end - return u -end -function filter!(f, s::Set) - for x in s - if !f(x) - delete!(s, x) - end - end - return s -end - -const hashs_seed = UInt === UInt64 ? 0x852ada37cfe8e0ce : 0xcfe8e0ce -function hash(s::Set, h::UInt) - h = hash(hashs_seed, h) - for x in s - h ⊻= hash(x) - end - return h -end - -convert(::Type{Set{T}}, s::Set{T}) where {T} = s -convert(::Type{Set{T}}, x::Set) where {T} = Set{T}(x) diff --git a/julia-0.6.3/share/julia/base/sharedarray.jl b/julia-0.6.3/share/julia/base/sharedarray.jl deleted file mode 100644 index 6ef1647..0000000 --- a/julia-0.6.3/share/julia/base/sharedarray.jl +++ /dev/null @@ -1,668 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -import .Serializer: serialize_cycle_header, serialize_type, writetag, UNDEFREF_TAG -import .Distributed: RRID - -mutable struct SharedArray{T,N} <: DenseArray{T,N} - id::RRID - dims::NTuple{N,Int} - pids::Vector{Int} - refs::Vector - - # The segname is currently used only in the test scripts to ensure that - # the shmem segment has been unlinked. - segname::String - - # Fields below are not to be serialized - # Local shmem map. - s::Array{T,N} - - # idx of current worker's pid in the pids vector, 0 if this shared array is not mapped locally. - pidx::Int - - # the local partition into the array when viewed as a single dimensional array. - # this can be removed when @parallel or its equivalent supports looping on - # a subset of workers. - loc_subarr_1d::SubArray{T,1,Array{T,1},Tuple{UnitRange{Int}},true} - - function SharedArray{T,N}(d,p,r,sn,s) where {T,N} - S = new(RRID(),d,p,r,sn,s,0,view(Array{T}(ntuple(d->0,N)), 1:0)) - sa_refs[S.id] = WeakRef(S) - S - end -end - -const sa_refs = Dict{RRID, WeakRef}() - -""" - SharedArray{T}(dims::NTuple; init=false, pids=Int[]) - SharedArray{T,N}(...) - -Construct a `SharedArray` of a bits type `T` and size `dims` across the -processes specified by `pids` - all of which have to be on the same -host. If `N` is specified by calling `SharedArray{T,N}(dims)`, then -`N` must match the length of `dims`. - -If `pids` is left unspecified, the shared array will be mapped across all processes on the -current host, including the master. But, `localindexes` and `indexpids` will only refer to -worker processes. This facilitates work distribution code to use workers for actual -computation with the master process acting as a driver. - -If an `init` function of the type `initfn(S::SharedArray)` is specified, it is called on all -the participating workers. - -The shared array is valid as long as a reference to the `SharedArray` object exists on the node -which created the mapping. - - SharedArray{T}(filename::AbstractString, dims::NTuple, [offset=0]; mode=nothing, init=false, pids=Int[]) - SharedArray{T,N}(...) - -Construct a `SharedArray` backed by the file `filename`, with element -type `T` (must be a bits type) and size `dims`, across the processes -specified by `pids` - all of which have to be on the same host. This -file is mmapped into the host memory, with the following consequences: - -- The array data must be represented in binary format (e.g., an ASCII - format like CSV cannot be supported) - -- Any changes you make to the array values (e.g., `A[3] = 0`) will - also change the values on disk - -If `pids` is left unspecified, the shared array will be mapped across -all processes on the current host, including the master. But, -`localindexes` and `indexpids` will only refer to worker -processes. This facilitates work distribution code to use workers for -actual computation with the master process acting as a driver. - -`mode` must be one of `"r"`, `"r+"`, `"w+"`, or `"a+"`, and defaults -to `"r+"` if the file specified by `filename` already exists, or -`"w+"` if not. If an `init` function of the type -`initfn(S::SharedArray)` is specified, it is called on all the -participating workers. You cannot specify an `init` function if the -file is not writable. - -`offset` allows you to skip the specified number of bytes at the -beginning of the file. -""" -SharedArray - -function SharedArray{T,N}(dims::Dims{N}; init=false, pids=Int[]) where {T,N} - isbits(T) || throw(ArgumentError("type of SharedArray elements must be bits types, got $(T)")) - - pids, onlocalhost = shared_pids(pids) - - local shm_seg_name = "" - local s = Array{T}(ntuple(d->0,N)) - local S - local shmmem_create_pid - try - # On OSX, the shm_seg_name length must be <= 31 characters (including the terminating NULL character) - shm_seg_name = @sprintf("/jl%06u%s", getpid() % 10^6, randstring(20)) - if onlocalhost - shmmem_create_pid = myid() - s = shm_mmap_array(T, dims, shm_seg_name, JL_O_CREAT | JL_O_RDWR) - else - # The shared array is created on a remote machine - shmmem_create_pid = pids[1] - remotecall_fetch(pids[1]) do - shm_mmap_array(T, dims, shm_seg_name, JL_O_CREAT | JL_O_RDWR) - nothing - end - end - - func_mapshmem = () -> shm_mmap_array(T, dims, shm_seg_name, JL_O_RDWR) - - refs = Vector{Future}(length(pids)) - for (i, p) in enumerate(pids) - refs[i] = remotecall(func_mapshmem, p) - end - - # Wait till all the workers have mapped the segment - for ref in refs - wait(ref) - end - - # All good, immediately unlink the segment. - if (prod(dims) > 0) && (sizeof(T) > 0) - if onlocalhost - rc = shm_unlink(shm_seg_name) - else - rc = remotecall_fetch(shm_unlink, shmmem_create_pid, shm_seg_name) - end - systemerror("Error unlinking shmem segment " * shm_seg_name, rc != 0) - end - S = SharedArray{T,N}(dims, pids, refs, shm_seg_name, s) - initialize_shared_array(S, onlocalhost, init, pids) - shm_seg_name = "" - - finally - if !isempty(shm_seg_name) - remotecall_fetch(shm_unlink, shmmem_create_pid, shm_seg_name) - end - end - S -end - -SharedArray{T,N}(I::Integer...; kwargs...) where {T,N} = - SharedArray{T,N}(I; kwargs...) -SharedArray{T}(d::NTuple; kwargs...) where {T} = - SharedArray{T,length(d)}(d; kwargs...) -SharedArray{T}(I::Integer...; kwargs...) where {T} = - SharedArray{T,length(I)}(I; kwargs...) -SharedArray{T}(m::Integer; kwargs...) where {T} = - SharedArray{T,1}(m; kwargs...) -SharedArray{T}(m::Integer, n::Integer; kwargs...) where {T} = - SharedArray{T,2}(m, n; kwargs...) -SharedArray{T}(m::Integer, n::Integer, o::Integer; kwargs...) where {T} = - SharedArray{T,3}(m, n, o; kwargs...) - -function SharedArray{T,N}(filename::AbstractString, dims::NTuple{N,Int}, offset::Integer=0; - mode=nothing, init=false, pids::Vector{Int}=Int[]) where {T,N} - if !isabspath(filename) - throw(ArgumentError("$filename is not an absolute path; try abspath(filename)?")) - end - if !isbits(T) - throw(ArgumentError("type of SharedArray elements must be bits types, got $(T)")) - end - - pids, onlocalhost = shared_pids(pids) - - # If not supplied, determine the appropriate mode - have_file = onlocalhost ? isfile(filename) : remotecall_fetch(isfile, pids[1], filename) - if mode === nothing - mode = have_file ? "r+" : "w+" - end - workermode = mode == "w+" ? "r+" : mode # workers don't truncate! - - # Ensure the file will be readable - if !(mode in ("r", "r+", "w+", "a+")) - throw(ArgumentError("mode must be readable, but $mode is not")) - end - if init !== false - typeassert(init, Function) - if !(mode in ("r+", "w+", "a+")) - throw(ArgumentError("cannot initialize unwritable array (mode = $mode)")) - end - end - if mode == "r" && !isfile(filename) - throw(ArgumentError("file $filename does not exist, but mode $mode cannot create it")) - end - - # Create the file if it doesn't exist, map it if it does - refs = Vector{Future}(length(pids)) - func_mmap = mode -> open(filename, mode) do io - Mmap.mmap(io, Array{T,N}, dims, offset; shared=true) - end - s = Array{T}(ntuple(d->0,N)) - if onlocalhost - s = func_mmap(mode) - refs[1] = remotecall(pids[1]) do - func_mmap(workermode) - end - else - refs[1] = remotecall_wait(pids[1]) do - func_mmap(mode) - end - end - - # Populate the rest of the workers - for i = 2:length(pids) - refs[i] = remotecall(pids[i]) do - func_mmap(workermode) - end - end - - # Wait till all the workers have mapped the segment - for ref in refs - wait(ref) - end - - S = SharedArray{T,N}(dims, pids, refs, filename, s) - initialize_shared_array(S, onlocalhost, init, pids) - S -end - -SharedArray{T}(filename::AbstractString, dims::NTuple{N,Int}, offset::Integer=0; - mode=nothing, init=false, pids::Vector{Int}=Int[]) where {T,N} = - SharedArray{T,N}(filename, dims, offset; mode=mode, init=init, pids=pids) - -function initialize_shared_array(S, onlocalhost, init, pids) - if onlocalhost - init_loc_flds(S) - else - S.pidx = 0 - end - - # if present, init function is called on each of the parts - if isa(init, Function) - @sync begin - for p in pids - @async remotecall_wait(init, p, S) - end - end - end - - finalizer(S, finalize_refs) - S -end - -function finalize_refs(S::SharedArray{T,N}) where T where N - if length(S.pids) > 0 - for r in S.refs - finalize(r) - end - empty!(S.pids) - empty!(S.refs) - init_loc_flds(S) - S.s = Array{T}(ntuple(d->0,N)) - delete!(sa_refs, S.id) - end - S -end - - -const SharedVector{T} = SharedArray{T,1} -const SharedMatrix{T} = SharedArray{T,2} - -length(S::SharedArray) = prod(S.dims) -size(S::SharedArray) = S.dims -ndims(S::SharedArray) = length(S.dims) -IndexStyle(::Type{<:SharedArray}) = IndexLinear() - -function reshape(a::SharedArray{T}, dims::NTuple{N,Int}) where {T,N} - if length(a) != prod(dims) - throw(DimensionMismatch("dimensions must be consistent with array size")) - end - refs = Array{Future}(length(a.pids)) - for (i, p) in enumerate(a.pids) - refs[i] = remotecall(p, a.refs[i], dims) do r,d - reshape(fetch(r),d) - end - end - - A = SharedArray{T,N}(dims, a.pids, refs, a.segname, reshape(a.s, dims)) - init_loc_flds(A) - A -end - -""" - procs(S::SharedArray) - -Get the vector of processes mapping the shared array. -""" -procs(S::SharedArray) = S.pids - -""" - indexpids(S::SharedArray) - -Returns the current worker's index in the list of workers -mapping the `SharedArray` (i.e. in the same list returned by `procs(S)`), or -0 if the `SharedArray` is not mapped locally. -""" -indexpids(S::SharedArray) = S.pidx - -""" - sdata(S::SharedArray) - -Returns the actual `Array` object backing `S`. -""" -sdata(S::SharedArray) = S.s -sdata(A::AbstractArray) = A - -""" - localindexes(S::SharedArray) - -Returns a range describing the "default" indexes to be handled by the -current process. This range should be interpreted in the sense of -linear indexing, i.e., as a sub-range of `1:length(S)`. In -multi-process contexts, returns an empty range in the parent process -(or any process for which [`indexpids`](@ref) returns 0). - -It's worth emphasizing that `localindexes` exists purely as a -convenience, and you can partition work on the array among workers any -way you wish. For a `SharedArray`, all indexes should be equally fast -for each worker process. -""" -localindexes(S::SharedArray) = S.pidx > 0 ? range_1dim(S, S.pidx) : 1:0 - -unsafe_convert(::Type{Ptr{T}}, S::SharedArray{T}) where {T} = unsafe_convert(Ptr{T}, sdata(S)) -unsafe_convert(::Type{Ptr{T}}, S::SharedArray ) where {T} = unsafe_convert(Ptr{T}, sdata(S)) - -function convert(::Type{SharedArray}, A::Array) - S = SharedArray{eltype(A),ndims(A)}(size(A)) - copy!(S, A) -end -function convert(::Type{SharedArray{T}}, A::Array) where T - S = SharedArray{T,ndims(A)}(size(A)) - copy!(S, A) -end -function convert(::Type{SharedArray{TS,N}}, A::Array{TA,N}) where {TS,TA,N} - S = SharedArray{TS,ndims(A)}(size(A)) - copy!(S, A) -end - -function deepcopy_internal(S::SharedArray, stackdict::ObjectIdDict) - haskey(stackdict, S) && return stackdict[S] - R = SharedArray{eltype(S),ndims(S)}(size(S); pids = S.pids) - copy!(sdata(R), sdata(S)) - stackdict[S] = R - return R -end - -function shared_pids(pids) - if isempty(pids) - # only use workers on the current host - pids = procs(myid()) - if length(pids) > 1 - pids = filter(x -> x != 1, pids) - end - - onlocalhost = true - else - if !check_same_host(pids) - throw(ArgumentError("SharedArray requires all requested processes to be on the same machine.")) - end - - onlocalhost = myid() in procs(pids[1]) - end - pids, onlocalhost -end - -function range_1dim(S::SharedArray, pidx) - l = length(S) - nw = length(S.pids) - partlen = div(l, nw) - - if l < nw - if pidx <= l - return pidx:pidx - else - return 1:0 - end - elseif pidx == nw - return (((pidx-1) * partlen) + 1):l - else - return (((pidx-1) * partlen) + 1):(pidx*partlen) - end -end - -sub_1dim(S::SharedArray, pidx) = view(S.s, range_1dim(S, pidx)) - -function init_loc_flds(S::SharedArray{T,N}, empty_local=false) where T where N - if myid() in S.pids - S.pidx = findfirst(S.pids, myid()) - if isa(S.refs[1], Future) - refid = remoteref_id(S.refs[S.pidx]) - else - refid = S.refs[S.pidx] - end - c = channel_from_id(refid) - S.s = fetch(c) - S.loc_subarr_1d = sub_1dim(S, S.pidx) - else - S.pidx = 0 - if empty_local - S.s = Array{T}(ntuple(d->0,N)) - end - S.loc_subarr_1d = view(Array{T}(ntuple(d->0,N)), 1:0) - end -end - - -# Don't serialize s (it is the complete array) and -# pidx, which is relevant to the current process only -function serialize(s::AbstractSerializer, S::SharedArray) - serialize_cycle_header(s, S) && return - - destpid = worker_id_from_socket(s.io) - if S.id.whence == destpid - # The shared array was created from destpid, hence a reference to it - # must be available at destpid. - serialize(s, true) - serialize(s, S.id.whence) - serialize(s, S.id.id) - return - end - serialize(s, false) - for n in fieldnames(SharedArray) - if n in [:s, :pidx, :loc_subarr_1d] - writetag(s.io, UNDEFREF_TAG) - elseif n == :refs - v = getfield(S, n) - if isa(v[1], Future) - # convert to ids to avoid distributed GC overhead - ids = [remoteref_id(x) for x in v] - serialize(s, ids) - else - serialize(s, v) - end - else - serialize(s, getfield(S, n)) - end - end -end - -function deserialize(s::AbstractSerializer, t::Type{<:SharedArray}) - ref_exists = deserialize(s) - if ref_exists - sref = sa_refs[RRID(deserialize(s), deserialize(s))] - if sref.value !== nothing - return sref.value - end - error("Expected reference to shared array instance not found") - end - - S = invoke(deserialize, Tuple{AbstractSerializer,DataType}, s, t) - init_loc_flds(S, true) - return S -end - -function show(io::IO, S::SharedArray) - if length(S.s) > 0 - invoke(show, Tuple{IO,DenseArray}, io, S) - else - show(io, remotecall_fetch(sharr->sharr.s, S.pids[1], S)) - end -end - -function show(io::IO, mime::MIME"text/plain", S::SharedArray) - if length(S.s) > 0 - invoke(show, Tuple{IO,MIME"text/plain",DenseArray}, io, MIME"text/plain"(), S) - else - # retrieve from the first worker mapping the array. - println(io, summary(S), ":") - showarray(io, remotecall_fetch(sharr->sharr.s, S.pids[1], S), false; header=false) - end -end - -convert(::Type{Array}, S::SharedArray) = S.s - -# pass through getindex and setindex! - unlike DArrays, these always work on the complete array -getindex(S::SharedArray, i::Real) = getindex(S.s, i) - -setindex!(S::SharedArray, x, i::Real) = setindex!(S.s, x, i) - -function fill!(S::SharedArray, v) - vT = convert(eltype(S), v) - f = S->fill!(S.loc_subarr_1d, vT) - @sync for p in procs(S) - @async remotecall_wait(f, p, S) - end - return S -end - -function rand!(S::SharedArray{T}) where T - f = S->map!(x -> rand(T), S.loc_subarr_1d, S.loc_subarr_1d) - @sync for p in procs(S) - @async remotecall_wait(f, p, S) - end - return S -end - -function randn!(S::SharedArray) - f = S->map!(x -> randn(), S.loc_subarr_1d, S.loc_subarr_1d) - @sync for p in procs(S) - @async remotecall_wait(f, p, S) - end - return S -end - -# convenience constructors -function shmem_fill(v, dims; kwargs...) - SharedArray{typeof(v),length(dims)}(dims; init = S->fill!(S.loc_subarr_1d, v), kwargs...) -end -shmem_fill(v, I::Int...; kwargs...) = shmem_fill(v, I; kwargs...) - -# rand variant with range -function shmem_rand(TR::Union{DataType, UnitRange}, dims; kwargs...) - if isa(TR, UnitRange) - SharedArray{Int,length(dims)}(dims; init = S -> map!(x -> rand(TR), S.loc_subarr_1d, S.loc_subarr_1d), kwargs...) - else - SharedArray{TR,length(dims)}(dims; init = S -> map!(x -> rand(TR), S.loc_subarr_1d, S.loc_subarr_1d), kwargs...) - end -end -shmem_rand(TR::Union{DataType, UnitRange}, i::Int; kwargs...) = shmem_rand(TR, (i,); kwargs...) -shmem_rand(TR::Union{DataType, UnitRange}, I::Int...; kwargs...) = shmem_rand(TR, I; kwargs...) - -shmem_rand(dims; kwargs...) = shmem_rand(Float64, dims; kwargs...) -shmem_rand(I::Int...; kwargs...) = shmem_rand(I; kwargs...) - -function shmem_randn(dims; kwargs...) - SharedArray{Float64,length(dims)}(dims; init = S-> map!(x -> randn(), S.loc_subarr_1d, S.loc_subarr_1d), kwargs...) -end -shmem_randn(I::Int...; kwargs...) = shmem_randn(I; kwargs...) - -similar(S::SharedArray, T::Type, dims::Dims) = similar(S.s, T, dims) -similar(S::SharedArray, T::Type) = similar(S.s, T, size(S)) -similar(S::SharedArray, dims::Dims) = similar(S.s, eltype(S), dims) -similar(S::SharedArray) = similar(S.s, eltype(S), size(S)) - -reduce(f, S::SharedArray) = - mapreduce(fetch, f, Any[ @spawnat p reduce(f, S.loc_subarr_1d) for p in procs(S) ]) - - -function map!(f, S::SharedArray, Q::SharedArray) - if (S !== Q) && (procs(S) != procs(Q) || localindexes(S) != localindexes(Q)) - throw(ArgumentError("incompatible source and destination arguments")) - end - @sync for p in procs(S) - @spawnat p begin - for idx in localindexes(S) - S.s[idx] = f(Q.s[idx]) - end - end - end - return S -end - -copy!(S::SharedArray, A::Array) = (copy!(S.s, A); S) - -function copy!(S::SharedArray, R::SharedArray) - length(S) == length(R) || throw(BoundsError()) - ps = intersect(procs(S), procs(R)) - isempty(ps) && throw(ArgumentError("source and destination arrays don't share any process")) - l = length(S) - length(ps) > l && (ps = ps[1:l]) - nw = length(ps) - partlen = div(l, nw) - - @sync for i = 1:nw - p = ps[i] - idx = i < nw ? ((i-1)*partlen+1:i*partlen) : ((i-1)*partlen+1:l) - @spawnat p begin - S.s[idx] = R.s[idx] - end - end - - return S -end - -function print_shmem_limits(slen) - try - if is_linux() - pfx = "kernel" - elseif is_apple() - pfx = "kern.sysv" - elseif Sys.KERNEL == :FreeBSD || Sys.KERNEL == :DragonFly - pfx = "kern.ipc" - elseif Sys.KERNEL == :OpenBSD - pfx = "kern.shminfo" - else - # seems NetBSD does not have *.shmall - return - end - - shmmax_MB = div(parse(Int, split(readstring(`sysctl $(pfx).shmmax`))[end]), 1024*1024) - page_size = parse(Int, split(readstring(`getconf PAGE_SIZE`))[end]) - shmall_MB = div(parse(Int, split(readstring(`sysctl $(pfx).shmall`))[end]) * page_size, 1024*1024) - - println("System max size of single shmem segment(MB) : ", shmmax_MB, - "\nSystem max size of all shmem segments(MB) : ", shmall_MB, - "\nRequested size(MB) : ", div(slen, 1024*1024), - "\nPlease ensure requested size is within system limits.", - "\nIf not, increase system limits and try again." - ) - catch e - nothing # Ignore any errors in this - end -end - -# utilities -function shm_mmap_array(T, dims, shm_seg_name, mode) - local s = nothing - local A = nothing - - if (prod(dims) == 0) || (sizeof(T) == 0) - return Array{T}(dims) - end - - try - A = _shm_mmap_array(T, dims, shm_seg_name, mode) - catch e - print_shmem_limits(prod(dims)*sizeof(T)) - rethrow(e) - - finally - if s !== nothing - close(s) - end - end - A -end - - -# platform-specific code - -if is_windows() -function _shm_mmap_array(T, dims, shm_seg_name, mode) - readonly = !((mode & JL_O_RDWR) == JL_O_RDWR) - create = (mode & JL_O_CREAT) == JL_O_CREAT - s = Mmap.Anonymous(shm_seg_name, readonly, create) - Mmap.mmap(s, Array{T,length(dims)}, dims, zero(Int64)) -end - -# no-op in windows -shm_unlink(shm_seg_name) = 0 - -else # !windows -function _shm_mmap_array(T, dims, shm_seg_name, mode) - fd_mem = shm_open(shm_seg_name, mode, S_IRUSR | S_IWUSR) - systemerror("shm_open() failed for " * shm_seg_name, fd_mem < 0) - - s = fdio(fd_mem, true) - - # On OSX, ftruncate must to used to set size of segment, just lseek does not work. - # and only at creation time - if (mode & JL_O_CREAT) == JL_O_CREAT - rc = ccall(:jl_ftruncate, Cint, (Cint, Int64), fd_mem, prod(dims)*sizeof(T)) - systemerror("ftruncate() failed for shm segment " * shm_seg_name, rc != 0) - end - - Mmap.mmap(s, Array{T,length(dims)}, dims, zero(Int64); grow=false) -end - -shm_unlink(shm_seg_name) = ccall(:shm_unlink, Cint, (Cstring,), shm_seg_name) -shm_open(shm_seg_name, oflags, permissions) = ccall(:shm_open, Cint, - (Cstring, Cint, Cmode_t), shm_seg_name, oflags, permissions) - -end # os-test diff --git a/julia-0.6.3/share/julia/base/shell.jl b/julia-0.6.3/share/julia/base/shell.jl deleted file mode 100644 index 8418657..0000000 --- a/julia-0.6.3/share/julia/base/shell.jl +++ /dev/null @@ -1,193 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -## shell-like command parsing ## - -const shell_special = "#{}()[]<>|&*?~;" - -# needs to be factored out so depwarn only warns once -@noinline warn_shell_special(special) = - depwarn("special characters \"$special\" should now be quoted in commands", :warn_shell_special) - -function shell_parse(str::AbstractString, interpolate::Bool=true; - special::AbstractString="") - s = lstrip(str) - # strips the end but respects the space when the string ends with "\\ " - r = RevString(s) - i = start(r) - c_old = nothing - while !done(r,i) - c, j = next(r,i) - if c == '\\' && c_old == ' ' - i -= 1 - break - elseif !(c in _default_delims) - break - end - i = j - c_old = c - end - s = s[1:end-i+1] - - last_parse = 0:-1 - isempty(s) && return interpolate ? (Expr(:tuple,:()),last_parse) : ([],last_parse) - - in_single_quotes = false - in_double_quotes = false - - args::Vector{Any} = [] - arg::Vector{Any} = [] - i = start(s) - j = i - - function update_arg(x) - if !isa(x,AbstractString) || !isempty(x) - push!(arg, x) - end - end - function append_arg() - if isempty(arg); arg = Any["",]; end - push!(args, arg) - arg = [] - end - - while !done(s,j) - c, k = next(s,j) - if !in_single_quotes && !in_double_quotes && isspace(c) - update_arg(s[i:j-1]) - append_arg() - j = k - while !done(s,j) - c, k = next(s,j) - if !isspace(c) - i = j - break - end - j = k - end - elseif interpolate && !in_single_quotes && c == '$' - update_arg(s[i:j-1]); i = k; j = k - if done(s,k) - error("\$ right before end of command") - end - if isspace(s[k]) - error("space not allowed right after \$") - end - stpos = j - ex, j = parse(s,j,greedy=false) - last_parse = stpos:j - update_arg(ex); i = j - else - if !in_double_quotes && c == '\'' - in_single_quotes = !in_single_quotes - update_arg(s[i:j-1]); i = k - elseif !in_single_quotes && c == '"' - in_double_quotes = !in_double_quotes - update_arg(s[i:j-1]); i = k - elseif c == '\\' - if in_double_quotes - if done(s,k) - error("unterminated double quote") - end - if s[k] == '"' || s[k] == '$' || s[k] == '\\' - update_arg(s[i:j-1]); i = k - c, k = next(s,k) - end - elseif !in_single_quotes - if done(s,k) - error("dangling backslash") - end - update_arg(s[i:j-1]); i = k - c, k = next(s,k) - end - elseif !in_single_quotes && !in_double_quotes && c in special - warn_shell_special(special) # noinline depwarn - end - j = k - end - end - - if in_single_quotes; error("unterminated single quote"); end - if in_double_quotes; error("unterminated double quote"); end - - update_arg(s[i:end]) - append_arg() - - interpolate || return args, last_parse - - # construct an expression - ex = Expr(:tuple) - for arg in args - push!(ex.args, Expr(:tuple, arg...)) - end - return ex, last_parse -end - -function shell_split(s::AbstractString) - parsed = shell_parse(s, false)[1] - args = String[] - for arg in parsed - push!(args, string(arg...)) - end - args -end - -function print_shell_word(io::IO, word::AbstractString, special::AbstractString = "") - if isempty(word) - print(io, "''") - end - has_single = false - has_special = false - for c in word - if isspace(c) || c=='\\' || c=='\'' || c=='"' || c=='$' || c in special - has_special = true - if c == '\'' - has_single = true - end - end - end - if !has_special - print(io, word) - elseif !has_single - print(io, '\'', word, '\'') - else - print(io, '"') - for c in word - if c == '"' || c == '$' - print(io, '\\') - end - print(io, c) - end - print(io, '"') - end -end - -function print_shell_escaped(io::IO, cmd::AbstractString, args::AbstractString...; - special::AbstractString="") - print_shell_word(io, cmd, special) - for arg in args - print(io, ' ') - print_shell_word(io, arg, special) - end -end -print_shell_escaped(io::IO; special::String="") = nothing - -""" - shell_escape(args::Union{Cmd,AbstractString...}; special::AbstractString="") - -The unexported `shell_escape` function is the inverse of the unexported `shell_split` function: -it takes a string or command object and escapes any special characters in such a way that calling -`shell_split` on it would give back the array of words in the original command. The `special` -keyword argument controls what characters in addition to whitespace, backslashes, quotes and -dollar signs are considered to be special (default: none). - -# Examples -```jldoctest -julia> Base.shell_escape("cat", "/foo/bar baz", "&&", "echo", "done") -"cat '/foo/bar baz' && echo done" - -julia> Base.shell_escape("echo", "this", "&&", "that") -"echo this && that" -``` -""" -shell_escape(args::AbstractString...; special::AbstractString="") = - sprint(io->print_shell_escaped(io, args..., special=special)) diff --git a/julia-0.6.3/share/julia/base/show.jl b/julia-0.6.3/share/julia/base/show.jl deleted file mode 100644 index 0d09148..0000000 --- a/julia-0.6.3/share/julia/base/show.jl +++ /dev/null @@ -1,1792 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -print(io::IO, s::Symbol) = (write(io,s); nothing) - -""" - IOContext - -`IOContext` provides a mechanism for passing output configuration settings among [`show`](@ref) methods. - -In short, it is an immutable dictionary that is a subclass of `IO`. It supports standard -dictionary operations such as [`getindex`](@ref), and can also be used as an I/O stream. -""" -struct IOContext{IO_t <: IO} <: AbstractPipe - io::IO_t - dict::ImmutableDict{Symbol, Any} - - function IOContext{IO_t}(io::IO_t, dict::ImmutableDict{Symbol, Any}) where IO_t<:IO - assert(!(IO_t <: IOContext)) - return new(io, dict) - end -end - -""" - IOContext(io::IO; properties...) - -The same as `IOContext(io::IO, KV::Pair)`, but accepting properties as keyword arguments. -""" -IOContext(io::IO; kws...) = IOContext(convert(IOContext, io); kws...) -function IOContext(io::IOContext; kws...) - for (k, v) in kws - io = IOContext(io, k, v) - end - return io -end - -convert(::Type{IOContext}, io::IOContext) = io -convert(::Type{IOContext}, io::IO) = IOContext(io, ImmutableDict{Symbol, Any}()) - -IOContext(io::IOContext, dict::ImmutableDict) = typeof(io)(io.io, dict) -IOContext(io::IO, dict::ImmutableDict) = IOContext{typeof(io)}(io, dict) - -IOContext(io::IOContext, key, value) = IOContext(io.io, ImmutableDict{Symbol, Any}(io.dict, key, value)) -IOContext(io::IO, key, value) = IOContext(io, ImmutableDict{Symbol, Any}(key, value)) - -IOContext(io::IO, context::IO) = convert(IOContext, io) - -""" - IOContext(io::IO, context::IOContext) - -Create an `IOContext` that wraps an alternate `IO` but inherits the properties of `context`. -""" -IOContext(io::IO, context::IOContext) = IOContext(io, context.dict) - -""" - IOContext(io::IO, KV::Pair) - -Create an `IOContext` that wraps a given stream, adding the specified `key=>value` pair to -the properties of that stream (note that `io` can itself be an `IOContext`). - - - use `(key => value) in dict` to see if this particular combination is in the properties set - - use `get(dict, key, default)` to retrieve the most recent value for a particular key - -The following properties are in common use: - - - `:compact`: Boolean specifying that small values should be printed more compactly, e.g. - that numbers should be printed with fewer digits. This is set when printing array - elements. - - `:limit`: Boolean specifying that containers should be truncated, e.g. showing `…` in - place of most elements. - - `:displaysize`: A `Tuple{Int,Int}` giving the size in rows and columns to use for text - output. This can be used to override the display size for called functions, but to - get the size of the screen use the `displaysize` function. - -```jldoctest -julia> function f(io::IO) - if get(io, :short, false) - print(io, "short") - else - print(io, "loooooong") - end - end -f (generic function with 1 method) - -julia> f(STDOUT) -loooooong -julia> f(IOContext(STDOUT, :short => true)) -short -``` -""" -IOContext(io::IO, KV::Pair) = IOContext(io, KV[1], KV[2]) - -show(io::IO, ctx::IOContext) = (print(io, "IOContext("); show(io, ctx.io); print(io, ")")) - -pipe_reader(io::IOContext) = io.io -pipe_writer(io::IOContext) = io.io -lock(io::IOContext) = lock(io.io) -unlock(io::IOContext) = unlock(io.io) - -in(key_value::Pair, io::IOContext) = in(key_value, io.dict, ===) -in(key_value::Pair, io::IO) = false -haskey(io::IOContext, key) = haskey(io.dict, key) -haskey(io::IO, key) = false -getindex(io::IOContext, key) = getindex(io.dict, key) -getindex(io::IO, key) = throw(KeyError(key)) -get(io::IOContext, key, default) = get(io.dict, key, default) -get(io::IO, key, default) = default - -displaysize(io::IOContext) = haskey(io, :displaysize) ? io[:displaysize] : displaysize(io.io) - -show_circular(io::IO, x::ANY) = false -function show_circular(io::IOContext, x::ANY) - d = 1 - for (k, v) in io.dict - if k === :SHOWN_SET - if v === x - print(io, "#= circular reference @-$d =#") - return true - end - d += 1 - end - end - return false -end - -show(io::IO, x::ANY) = show_default(io, x) -function show_default(io::IO, x::ANY) - t = typeof(x)::DataType - show(io, t) - print(io, '(') - nf = nfields(t) - nb = sizeof(x) - if nf != 0 || nb == 0 - if !show_circular(io, x) - recur_io = IOContext(io, :SHOWN_SET => x) - for i in 1:nf - f = fieldname(t, i) - if !isdefined(x, f) - print(io, undef_ref_str) - else - show(recur_io, getfield(x, f)) - end - if i < nf - print(io, ", ") - end - end - end - else - print(io, "0x") - p = data_pointer_from_objref(x) - for i in (nb - 1):-1:0 - print(io, hex(unsafe_load(convert(Ptr{UInt8}, p + i)), 2)) - end - end - print(io,')') -end - -# Check if a particular symbol is exported from a standard library module -function is_exported_from_stdlib(name::Symbol, mod::Module) - !isdefined(mod, name) && return false - orig = getfield(mod, name) - while !(mod === Base || mod === Core) - parent = module_parent(mod) - if mod === Main || mod === parent || parent === Main - return false - end - mod = parent - end - return isexported(mod, name) && isdefined(mod, name) && !isdeprecated(mod, name) && getfield(mod, name) === orig -end - -function show(io::IO, f::Function) - ft = typeof(f) - mt = ft.name.mt - if !isdefined(mt, :module) || is_exported_from_stdlib(mt.name, mt.module) || mt.module === Main - print(io, mt.name) - else - print(io, mt.module, ".", mt.name) - end -end - -function show(io::IO, x::Core.IntrinsicFunction) - name = ccall(:jl_intrinsic_name, Cstring, (Core.IntrinsicFunction,), x) - print(io, unsafe_string(name)) -end - -show(io::IO, ::Core.TypeofBottom) = print(io, "Union{}") - -function show(io::IO, x::Union) - print(io, "Union") - sorted_types = sort!(uniontypes(x); by=string) - show_comma_array(io, sorted_types, '{', '}') -end - -function print_without_params(x::ANY) - if isa(x,UnionAll) - b = unwrap_unionall(x) - return isa(b,DataType) && b.name.wrapper === x - end - return false -end - -function show(io::IO, x::UnionAll) - if print_without_params(x) - return show(io, unwrap_unionall(x).name) - end - show(IOContext(io, :unionall_env => x.var), x.body) - print(io, " where ") - show(io, x.var) -end - -show(io::IO, x::DataType) = show_datatype(io, x) - -function show_datatype(io::IO, x::DataType) - istuple = x.name === Tuple.name - if (!isempty(x.parameters) || istuple) && x !== Tuple - n = length(x.parameters) - - # Print homogeneous tuples with more than 3 elements compactly as NTuple{N, T} - if istuple && n > 3 && all(i -> (x.parameters[1] === i), x.parameters) - print(io, "NTuple{", n, ',', x.parameters[1], "}") - else - show(io, x.name) - # Do not print the type parameters for the primary type if we are - # printing a method signature or type parameter. - # Always print the type parameter if we are printing the type directly - # since this information is still useful. - print(io, '{') - for (i, p) in enumerate(x.parameters) - show(io, p) - i < n && print(io, ',') - end - print(io, '}') - end - else - show(io, x.name) - end -end - -macro show(exs...) - blk = Expr(:block) - for ex in exs - push!(blk.args, :(println($(sprint(show_unquoted,ex)*" = "), - repr(begin value=$(esc(ex)) end)))) - end - if !isempty(exs); push!(blk.args, :value); end - return blk -end - -function show(io::IO, tn::TypeName) - if is_exported_from_stdlib(tn.name, tn.module) || tn.module === Main - print(io, tn.name) - else - print(io, tn.module, '.', tn.name) - end -end - -show(io::IO, ::Void) = print(io, "nothing") -show(io::IO, b::Bool) = print(io, b ? "true" : "false") -show(io::IO, n::Signed) = (write(io, dec(n)); nothing) -show(io::IO, n::Unsigned) = print(io, "0x", hex(n,sizeof(n)<<1)) -print(io::IO, n::Unsigned) = print(io, dec(n)) - -show(io::IO, p::Ptr) = print(io, typeof(p), " @0x$(hex(UInt(p), Sys.WORD_SIZE>>2))") - -function show(io::IO, p::Pair) - if typeof(p.first) != typeof(p).parameters[1] || - typeof(p.second) != typeof(p).parameters[2] - return show_default(io, p) - end - - isa(p.first,Pair) && print(io, "(") - show(io, p.first) - isa(p.first,Pair) && print(io, ")") - print(io, "=>") - isa(p.second,Pair) && print(io, "(") - show(io, p.second) - isa(p.second,Pair) && print(io, ")") - nothing -end - -function show(io::IO, m::Module) - if m === Main - print(io, "Main") - else - print(io, join(fullname(m),".")) - end -end - -function sourceinfo_slotnames(src::CodeInfo) - slotnames = src.slotnames - isa(slotnames, Array) || return String[] - names = Dict{String,Int}() - printnames = Vector{String}(length(slotnames)) - for i in eachindex(slotnames) - name = string(slotnames[i]) - idx = get!(names, name, i) - if idx != i - printname = "$name@_$i" - idx > 0 && (printnames[idx] = "$name@_$idx") - names[name] = 0 - else - printname = name - end - printnames[i] = printname - end - return printnames -end - -function show(io::IO, l::Core.MethodInstance) - if isdefined(l, :def) - if l.def.isstaged && l === l.def.generator - print(io, "MethodInstance generator for ") - show(io, l.def) - else - print(io, "MethodInstance for ") - show_tuple_as_call(io, l.def.name, l.specTypes) - end - else - print(io, "Toplevel MethodInstance thunk") - end -end - -function show(io::IO, src::CodeInfo) - # Fix slot names and types in function body - print(io, "CodeInfo(") - lambda_io = IOContext(io, :SOURCEINFO => src) - if src.slotnames !== nothing - lambda_io = IOContext(lambda_io, :SOURCE_SLOTNAMES => sourceinfo_slotnames(src)) - end - body = Expr(:body) - body.args = src.code - show(lambda_io, body) - print(io, ")") -end - -function show_delim_array(io::IO, itr::Union{AbstractArray,SimpleVector}, op, delim, cl, - delim_one, i1=first(linearindices(itr)), l=last(linearindices(itr))) - print(io, op) - if !show_circular(io, itr) - recur_io = IOContext(io, :SHOWN_SET => itr) - if !haskey(io, :compact) - recur_io = IOContext(recur_io, :compact => true) - end - first = true - i = i1 - if l >= i1 - while true - if !isassigned(itr, i) - print(io, undef_ref_str) - else - x = itr[i] - show(recur_io, x) - end - i += 1 - if i > l - delim_one && first && print(io, delim) - break - end - first = false - print(io, delim) - print(io, ' ') - end - end - end - print(io, cl) -end - -function show_delim_array(io::IO, itr, op, delim, cl, delim_one, i1=1, n=typemax(Int)) - print(io, op) - if !show_circular(io, itr) - recur_io = IOContext(io, :SHOWN_SET => itr) - state = start(itr) - first = true - while i1 > 1 && !done(itr, state) - _, state = next(itr, state) - i1 -= 1 - end - if !done(itr, state) - while true - x, state = next(itr, state) - show(recur_io, x) - i1 += 1 - if done(itr, state) || i1 > n - delim_one && first && print(io, delim) - break - end - first = false - print(io, delim) - print(io, ' ') - end - end - end - print(io, cl) -end - -show_comma_array(io::IO, itr, o, c) = show_delim_array(io, itr, o, ',', c, false) -show(io::IO, t::Tuple) = show_delim_array(io, t, '(', ',', ')', true) -show(io::IO, v::SimpleVector) = show_delim_array(io, v, "svec(", ',', ')', false) - -show(io::IO, s::Symbol) = show_unquoted_quote_expr(io, s, 0, 0) - -## Abstract Syntax Tree (AST) printing ## - -# Summary: -# print(io, ex) defers to show_unquoted(io, ex) -# show(io, ex) defers to show_unquoted(io, QuoteNode(ex)) -# show_unquoted(io, ex) does the heavy lifting -# -# AST printing should follow two rules: -# 1. parse(string(ex)) == ex -# 2. eval(parse(repr(ex))) == ex -# -# Rule 1 means that printing an expression should generate Julia code which -# could be reparsed to obtain the original expression. This code should be -# unambiguous and as readable as possible. -# -# Rule 2 means that showing an expression should generate a quoted version of -# print’s output. Parsing and then evaling this output should return the -# original expression. -# -# This is consistent with many other show methods, i.e.: -# show(Set([1,2,3])) # ==> "Set{Int64}([2,3,1])" -# eval(parse("Set{Int64}([2,3,1])”) # ==> An actual set -# While this isn’t true of ALL show methods, it is of all ASTs. - -const ExprNode = Union{Expr, QuoteNode, Slot, LineNumberNode, - LabelNode, GotoNode, GlobalRef} -# Operators have precedence levels from 1-N, and show_unquoted defaults to a -# precedence level of 0 (the fourth argument). The top-level print and show -# methods use a precedence of -1 to specially allow space-separated macro syntax -print( io::IO, ex::ExprNode) = (show_unquoted(io, ex, 0, -1); nothing) -show( io::IO, ex::ExprNode) = show_unquoted_quote_expr(io, ex, 0, -1) -show_unquoted(io::IO, ex) = show_unquoted(io, ex, 0, 0) -show_unquoted(io::IO, ex, indent::Int) = show_unquoted(io, ex, indent, 0) -show_unquoted(io::IO, ex, ::Int,::Int) = show(io, ex) - -## AST printing constants ## - -const indent_width = 4 -const quoted_syms = Set{Symbol}([:(:),:(::),:(:=),:(=),:(==),:(!=),:(===),:(!==),:(=>),:(>=),:(<=)]) -const uni_ops = Set{Symbol}([:(+), :(-), :(!), :(¬), :(~), :(<:), :(>:), :(√), :(∛), :(∜)]) -const expr_infix_wide = Set{Symbol}([ - :(=), :(+=), :(-=), :(*=), :(/=), :(\=), :(^=), :(&=), :(|=), :(÷=), :(%=), :(>>>=), :(>>=), :(<<=), - :(.=), :(.+=), :(.-=), :(.*=), :(./=), :(.\=), :(.^=), :(.&=), :(.|=), :(.÷=), :(.%=), :(.>>>=), :(.>>=), :(.<<=), - :(&&), :(||), :(<:), :($=), :(⊻=)]) # `$=` should be removed after deprecation is removed, issue #18977 -const expr_infix = Set{Symbol}([:(:), :(->), Symbol("::")]) -const expr_infix_any = union(expr_infix, expr_infix_wide) -const all_ops = union(quoted_syms, uni_ops, expr_infix_any) -const expr_calls = Dict(:call => ('(',')'), :calldecl => ('(',')'), - :ref => ('[',']'), :curly => ('{','}'), :(.) => ('(',')')) -const expr_parens = Dict(:tuple=>('(',')'), :vcat=>('[',']'), - :hcat =>('[',']'), :row =>('[',']'), :vect=>('[',']')) - -## AST decoding helpers ## - -is_id_start_char(c::Char) = ccall(:jl_id_start_char, Cint, (UInt32,), c) != 0 -is_id_char(c::Char) = ccall(:jl_id_char, Cint, (UInt32,), c) != 0 -function isidentifier(s::AbstractString) - i = start(s) - done(s, i) && return false - (c, i) = next(s, i) - is_id_start_char(c) || return false - while !done(s, i) - (c, i) = next(s, i) - is_id_char(c) || return false - end - return true -end -isidentifier(s::Symbol) = isidentifier(string(s)) - -isoperator(s::Symbol) = ccall(:jl_is_operator, Cint, (Cstring,), s) != 0 - -""" - operator_precedence(s::Symbol) - -Return an integer representing the precedence of operator `s`, relative to -other operators. Higher-numbered operators take precedence over lower-numbered -operators. Return `0` if `s` is not a valid operator. - -# Examples - -```jldoctest -julia> Base.operator_precedence(:+), Base.operator_precedence(:*), Base.operator_precedence(:.) -(9,11,15) - -julia> Base.operator_precedence(:+=), Base.operator_precedence(:(=)) # (Note the necessary parens on `:(=)`) -(1,1) -``` -""" -operator_precedence(s::Symbol) = Int(ccall(:jl_operator_precedence, Cint, (Cstring,), s)) -operator_precedence(x::Any) = 0 # fallback for generic expression nodes -const prec_power = operator_precedence(:(^)) -const prec_decl = operator_precedence(:(::)) - -is_expr(ex, head::Symbol) = (isa(ex, Expr) && (ex.head == head)) -is_expr(ex, head::Symbol, n::Int) = is_expr(ex, head) && length(ex.args) == n - -is_linenumber(ex::LineNumberNode) = true -is_linenumber(ex::Expr) = (ex.head == :line) -is_linenumber(ex) = false - -is_quoted(ex) = false -is_quoted(ex::QuoteNode) = true -is_quoted(ex::Expr) = is_expr(ex, :quote, 1) || is_expr(ex, :inert, 1) - -unquoted(ex::QuoteNode) = ex.value -unquoted(ex::Expr) = ex.args[1] - -## AST printing helpers ## - -typeemphasize(io::IO) = get(io, :TYPEEMPHASIZE, false) === true - -const indent_width = 4 - -function show_expr_type(io::IO, ty::ANY, emph::Bool) - if ty === Function - print(io, "::F") - elseif ty === Core.IntrinsicFunction - print(io, "::I") - else - if emph && (!isleaftype(ty) || ty == Core.Box) - emphasize(io, "::$ty") - else - print(io, "::$ty") - end - end -end - -emphasize(io, str::AbstractString) = have_color ? print_with_color(Base.error_color(), io, str; bold = true) : print(io, uppercase(str)) - -show_linenumber(io::IO, line) = print(io," # line ",line,':') -show_linenumber(io::IO, line, file) = print(io," # ", file,", line ",line,':') - -# show a block, e g if/for/etc -function show_block(io::IO, head, args::Vector, body, indent::Int) - print(io, head, ' ') - show_list(io, args, ", ", indent) - - ind = head === :module || head === :baremodule ? indent : indent + indent_width - exs = (is_expr(body, :block) || is_expr(body, :body)) ? body.args : Any[body] - for ex in exs - if !is_linenumber(ex); print(io, '\n', " "^ind); end - show_unquoted(io, ex, ind, -1) - end - print(io, '\n', " "^indent) -end -show_block(io::IO,head, block,i::Int) = show_block(io,head, [], block,i) -function show_block(io::IO, head, arg, block, i::Int) - if is_expr(arg, :block) - show_block(io, head, arg.args, block, i) - else - show_block(io, head, Any[arg], block, i) - end -end - -# show an indented list -function show_list(io::IO, items, sep, indent::Int, prec::Int=0, enclose_operators::Bool=false) - n = length(items) - if n == 0; return end - indent += indent_width - first = true - for item in items - !first && print(io, sep) - parens = enclose_operators && isa(item,Symbol) && isoperator(item) - parens && print(io, '(') - show_unquoted(io, item, indent, prec) - parens && print(io, ')') - first = false - end -end -# show an indented list inside the parens (op, cl) -function show_enclosed_list(io::IO, op, items, sep, cl, indent, prec=0, encl_ops=false) - print(io, op) - show_list(io, items, sep, indent, prec, encl_ops) - print(io, cl) -end - -# show a normal (non-operator) function call, e.g. f(x, y) or A[z] -function show_call(io::IO, head, func, func_args, indent) - op, cl = expr_calls[head] - if isa(func, Symbol) || (isa(func, Expr) && - (func.head == :. || func.head == :curly)) - show_unquoted(io, func, indent) - else - print(io, '(') - show_unquoted(io, func, indent) - print(io, ')') - end - if head == :(.) - print(io, '.') - end - if !isempty(func_args) && isa(func_args[1], Expr) && func_args[1].head === :parameters - print(io, op) - show_list(io, func_args[2:end], ", ", indent) - print(io, "; ") - show_list(io, func_args[1].args, ", ", indent) - print(io, cl) - else - show_enclosed_list(io, op, func_args, ", ", cl, indent) - end -end - -## AST printing ## - -show_unquoted(io::IO, sym::Symbol, ::Int, ::Int) = print(io, sym) -show_unquoted(io::IO, ex::LineNumberNode, ::Int, ::Int) = show_linenumber(io, ex.line) -show_unquoted(io::IO, ex::LabelNode, ::Int, ::Int) = print(io, ex.label, ": ") -show_unquoted(io::IO, ex::GotoNode, ::Int, ::Int) = print(io, "goto ", ex.label) -show_unquoted(io::IO, ex::GlobalRef, ::Int, ::Int) = print(io, ex.mod, '.', ex.name) - -function show_unquoted(io::IO, ex::Slot, ::Int, ::Int) - typ = isa(ex,TypedSlot) ? ex.typ : Any - slotid = ex.id - src = get(io, :SOURCEINFO, false) - if isa(src, CodeInfo) - slottypes = (src::CodeInfo).slottypes - if isa(slottypes, Array) && slotid <= length(slottypes::Array) - slottype = slottypes[slotid] - # The Slot in assignment can somehow have an Any type - if isa(slottype, Type) && isa(typ, Type) && slottype <: typ - typ = slottype - end - end - end - slotnames = get(io, :SOURCE_SLOTNAMES, false) - if (isa(slotnames, Vector{String}) && - slotid <= length(slotnames::Vector{String})) - print(io, (slotnames::Vector{String})[slotid]) - else - print(io, "_", slotid) - end - emphstate = typeemphasize(io) - if emphstate || (typ !== Any && isa(ex,TypedSlot)) - show_expr_type(io, typ, emphstate) - end -end - -function show_unquoted(io::IO, ex::QuoteNode, indent::Int, prec::Int) - if isa(ex.value, Symbol) - show_unquoted_quote_expr(io, ex.value, indent, prec) - else - print(io, "\$(QuoteNode(") - show(io, ex.value) - print(io, "))") - end -end - -function show_unquoted_quote_expr(io::IO, value, indent::Int, prec::Int) - if isa(value, Symbol) && !(value in quoted_syms) - s = string(value) - if isidentifier(s) || isoperator(value) - print(io, ":") - print(io, value) - else - print(io, "Symbol(\"", escape_string(s), "\")") - end - else - if isa(value,Expr) && value.head === :block - show_block(io, "quote", value, indent) - print(io, "end") - else - print(io, ":(") - show_unquoted(io, value, indent+indent_width, -1) - print(io, ")") - end - end -end - -function show_generator(io, ex, indent) - if ex.head === :flatten - fg = ex - ranges = Any[] - while isa(fg, Expr) && fg.head === :flatten - push!(ranges, fg.args[1].args[2:end]) - fg = fg.args[1].args[1] - end - push!(ranges, fg.args[2:end]) - show_unquoted(io, fg.args[1], indent) - for r in ranges - print(io, " for ") - show_list(io, r, ", ", indent) - end - else - show_unquoted(io, ex.args[1], indent) - print(io, " for ") - show_list(io, ex.args[2:end], ", ", indent) - end -end - -# TODO: implement interpolated strings -function show_unquoted(io::IO, ex::Expr, indent::Int, prec::Int) - head, args, nargs = ex.head, ex.args, length(ex.args) - emphstate = typeemphasize(io) - show_type = true - if (ex.head == :(=) || ex.head == :line || - ex.head == :boundscheck || - ex.head == :gotoifnot || - ex.head == :return) - show_type = false - end - if !emphstate && ex.typ === Any - show_type = false - end - # dot (i.e. "x.y"), but not compact broadcast exps - if head === :(.) && !is_expr(args[2], :tuple) - show_unquoted(io, args[1], indent + indent_width) - print(io, '.') - if is_quoted(args[2]) - show_unquoted(io, unquoted(args[2]), indent + indent_width) - else - print(io, '(') - show_unquoted(io, args[2], indent + indent_width) - print(io, ')') - end - - # infix (i.e. "x <: y" or "x = y") - elseif (head in expr_infix_any && nargs==2) || (head === :(:) && nargs==3) - func_prec = operator_precedence(head) - head_ = head in expr_infix_wide ? " $head " : head - if func_prec <= prec - show_enclosed_list(io, '(', args, head_, ')', indent, func_prec, true) - else - show_list(io, args, head_, indent, func_prec, true) - end - - # list (i.e. "(1, 2, 3)" or "[1, 2, 3]") - elseif haskey(expr_parens, head) # :tuple/:vcat - op, cl = expr_parens[head] - if head === :vcat - sep = "; " - elseif head === :hcat || head === :row - sep = " " - else - sep = ", " - end - head !== :row && print(io, op) - show_list(io, args, sep, indent) - if nargs == 1 - if head === :tuple - print(io, ',') - elseif head === :vcat - print(io, ';') - end - end - head !== :row && print(io, cl) - - # function call - elseif head === :call && nargs >= 1 - func = args[1] - fname = isa(func,GlobalRef) ? func.name : func - func_prec = operator_precedence(fname) - if func_prec > 0 || fname in uni_ops - func = fname - end - func_args = args[2:end] - - if (in(ex.args[1], (GlobalRef(Base, :bitcast), :throw)) || - ismodulecall(ex)) - show_type = false - end - if show_type - prec = prec_decl - end - - # scalar multiplication (i.e. "100x") - if (func === :* && - length(func_args)==2 && isa(func_args[1], Real) && isa(func_args[2], Symbol)) - if func_prec <= prec - show_enclosed_list(io, '(', func_args, "", ')', indent, func_prec) - else - show_list(io, func_args, "", indent, func_prec) - end - - # unary operator (i.e. "!z") - elseif isa(func,Symbol) && func in uni_ops && length(func_args) == 1 - show_unquoted(io, func, indent) - if isa(func_args[1], Expr) || func_args[1] in all_ops - show_enclosed_list(io, '(', func_args, ", ", ')', indent, func_prec) - else - show_unquoted(io, func_args[1]) - end - - # binary operator (i.e. "x + y") - elseif func_prec > 0 # is a binary operator - na = length(func_args) - if (na == 2 || (na > 2 && func in (:+, :++, :*))) && - all(!isa(a, Expr) || a.head !== :... for a in func_args) - sep = " $func " - if func_prec <= prec - show_enclosed_list(io, '(', func_args, sep, ')', indent, func_prec, true) - else - show_list(io, func_args, sep, indent, func_prec, true) - end - elseif na == 1 - # 1-argument call to normally-binary operator - op, cl = expr_calls[head] - print(io, "(") - show_unquoted(io, func, indent) - print(io, ")") - show_enclosed_list(io, op, func_args, ", ", cl, indent) - else - show_call(io, head, func, func_args, indent) - end - - # normal function (i.e. "f(x,y)") - else - show_call(io, head, func, func_args, indent) - end - - # other call-like expressions ("A[1,2]", "T{X,Y}", "f.(X,Y)") - elseif haskey(expr_calls, head) && nargs >= 1 # :ref/:curly/:calldecl/:(.) - funcargslike = head == :(.) ? ex.args[2].args : ex.args[2:end] - show_call(io, head, ex.args[1], funcargslike, indent) - - # comprehensions - elseif head === :typed_comprehension && length(args) == 2 - show_unquoted(io, args[1], indent) - print(io, '[') - show_generator(io, args[2], indent) - print(io, ']') - - elseif head === :comprehension && length(args) == 1 - print(io, '[') - show_generator(io, args[1], indent) - print(io, ']') - - elseif (head === :generator && length(args) >= 2) || (head === :flatten && length(args) == 1) - print(io, '(') - show_generator(io, ex, indent) - print(io, ')') - - elseif head === :filter && length(args) == 2 - show_unquoted(io, args[2], indent) - print(io, " if ") - show_unquoted(io, args[1], indent) - - # comparison (i.e. "x < y < z") - elseif head === :comparison && nargs >= 3 && (nargs&1==1) - comp_prec = minimum(operator_precedence, args[2:2:end]) - if comp_prec <= prec - show_enclosed_list(io, '(', args, " ", ')', indent, comp_prec) - else - show_list(io, args, " ", indent, comp_prec) - end - - # function calls need to transform the function from :call to :calldecl - # so that operators are printed correctly - elseif head === :function && nargs==2 && is_expr(args[1], :call) - show_block(io, head, Expr(:calldecl, args[1].args...), args[2], indent) - print(io, "end") - - elseif head === :function && nargs == 1 - print(io, "function ", args[1], " end") - - # block with argument - elseif head in (:for,:while,:function,:if) && nargs==2 - show_block(io, head, args[1], args[2], indent) - print(io, "end") - - elseif head === :module && nargs==3 && isa(args[1],Bool) - show_block(io, args[1] ? :module : :baremodule, args[2], args[3], indent) - print(io, "end") - - # type declaration - elseif head === :type && nargs==3 - show_block(io, args[1] ? Symbol("mutable struct") : Symbol("struct"), args[2], args[3], indent) - print(io, "end") - - elseif head === :bitstype && nargs == 2 - print(io, "primitive type ") - show_list(io, reverse(args), ' ', indent) - print(io, " end") - - elseif head === :abstract && nargs == 1 - print(io, "abstract type ") - show_list(io, args, ' ', indent) - print(io, " end") - - # empty return (i.e. "function f() return end") - elseif head === :return && nargs == 1 && args[1] === nothing - print(io, head) - - # type annotation (i.e. "::Int") - elseif head === Symbol("::") && nargs == 1 - print(io, "::") - show_unquoted(io, args[1], indent) - - # var-arg declaration or expansion - # (i.e. "function f(L...) end" or "f(B...)") - elseif head === :(...) && nargs == 1 - show_unquoted(io, args[1], indent) - print(io, "...") - - elseif (nargs == 0 && head in (:break, :continue)) - print(io, head) - - elseif (nargs == 1 && head in (:return, :const)) || - head in (:local, :global, :export) - print(io, head, ' ') - show_list(io, args, ", ", indent) - - elseif head === :macrocall && nargs >= 1 - # Use the functional syntax unless specifically designated with prec=-1 - if prec >= 0 - show_call(io, :call, ex.args[1], ex.args[2:end], indent) - else - show_list(io, args, ' ', indent) - end - - elseif head === :line && 1 <= nargs <= 2 - show_linenumber(io, args...) - - elseif head === :if && nargs == 3 # if/else - show_block(io, "if", args[1], args[2], indent) - show_block(io, "else", args[3], indent) - print(io, "end") - - elseif head === :try && 3 <= nargs <= 4 - show_block(io, "try", args[1], indent) - if is_expr(args[3], :block) - show_block(io, "catch", args[2] === false ? Any[] : args[2], args[3], indent) - end - if nargs >= 4 && is_expr(args[4], :block) - show_block(io, "finally", Any[], args[4], indent) - end - print(io, "end") - - elseif head === :let && nargs >= 1 - show_block(io, "let", args[2:end], args[1], indent); print(io, "end") - - elseif head === :block || head === :body - show_block(io, "begin", ex, indent); print(io, "end") - - elseif head === :quote && nargs == 1 && isa(args[1],Symbol) - show_unquoted_quote_expr(io, args[1], indent, 0) - - elseif head === :gotoifnot && nargs == 2 - print(io, "unless ") - show_list(io, args, " goto ", indent) - - elseif head === :string && nargs == 1 && isa(args[1], AbstractString) - show(io, args[1]) - - elseif head === :null - print(io, "nothing") - - elseif head === :kw && length(args)==2 - show_unquoted(io, args[1], indent+indent_width) - print(io, '=') - show_unquoted(io, args[2], indent+indent_width) - - elseif head === :string - print(io, '"') - for x in args - if !isa(x,AbstractString) - print(io, "\$(") - if isa(x,Symbol) && !(x in quoted_syms) - print(io, x) - else - show_unquoted(io, x) - end - print(io, ")") - else - escape_string(io, x, "\"\$") - end - end - print(io, '"') - - elseif (head === :&#= || head === :$=#) && length(args) == 1 - print(io, head) - a1 = args[1] - parens = (isa(a1,Expr) && a1.head !== :tuple) || (isa(a1,Symbol) && isoperator(a1)) - parens && print(io, "(") - show_unquoted(io, a1) - parens && print(io, ")") - - # transpose - elseif (head === Symbol('\'') || head === Symbol(".'")) && length(args) == 1 - if isa(args[1], Symbol) - show_unquoted(io, args[1]) - else - print(io, "(") - show_unquoted(io, args[1]) - print(io, ")") - end - print(io, head) - - # `where` syntax - elseif head === :where && length(args) > 1 - parens = 1 <= prec - parens && print(io, "(") - show_unquoted(io, args[1], indent, operator_precedence(:(::))) - print(io, " where ") - if nargs == 2 - show_unquoted(io, args[2], indent, 1) - else - print(io, "{") - show_list(io, args[2:end], ", ", indent) - print(io, "}") - end - parens && print(io, ")") - - elseif head === :import || head === :importall || head === :using - print(io, head) - first = true - for a = args - if first - print(io, ' ') - first = false - else - print(io, '.') - end - if a !== :. - print(io, a) - end - end - elseif head === :meta && length(args) >= 2 && args[1] === :push_loc - print(io, "# meta: location ", join(args[2:end], " ")) - show_type = false - elseif head === :meta && length(args) == 1 && args[1] === :pop_loc - print(io, "# meta: pop location") - show_type = false - # print anything else as "Expr(head, args...)" - else - show_type = false - if emphstate && ex.head !== :lambda && ex.head !== :method - io = IOContext(io, :TYPEEMPHASIZE => false) - emphstate = false - end - print(io, "\$(Expr(") - show(io, ex.head) - for arg in args - print(io, ", ") - show(io, arg) - end - print(io, "))") - end - show_type && show_expr_type(io, ex.typ, emphstate) - nothing -end - -function show_tuple_as_call(io::IO, name::Symbol, sig::Type) - # print a method signature tuple for a lambda definition - color = have_color && get(io, :backtrace, false) ? stackframe_function_color() : :nothing - if sig === Tuple - Base.print_with_color(color, io, name, "(...)") - return - end - sig = unwrap_unionall(sig).parameters - Base.with_output_color(color, io) do io - ft = sig[1] - uw = unwrap_unionall(ft) - if ft <: Function && isa(uw,DataType) && isempty(uw.parameters) && - isdefined(uw.name.module, uw.name.mt.name) && - ft == typeof(getfield(uw.name.module, uw.name.mt.name)) - print(io, uw.name.mt.name) - elseif isa(ft, DataType) && ft.name === Type.body.name && isleaftype(ft) - f = ft.parameters[1] - print(io, f) - else - print(io, "(::", ft, ")") - end - end - first = true - print_style = have_color && get(io, :backtrace, false) ? :bold : :nothing - print_with_color(print_style, io, "(") - for i = 2:length(sig) # fixme (iter): `eachindex` with offset? - first || print(io, ", ") - first = false - print(io, "::", sig[i]) - end - print_with_color(print_style, io, ")") - nothing -end - -function ismodulecall(ex::Expr) - return ex.head == :call && (ex.args[1] === GlobalRef(Base,:getfield) || - ex.args[1] === GlobalRef(Core,:getfield)) && - isa(ex.args[2], Symbol) && - isdefined(current_module(), ex.args[2]) && - isa(getfield(current_module(), ex.args[2]), Module) -end - -function show(io::IO, tv::TypeVar) - # If we are in the `unionall_env`, the type-variable is bound - # and the type constraints are already printed. - # We don't need to print it again. - # Otherwise, the lower bound should be printed if it is not `Bottom` - # and the upper bound should be printed if it is not `Any`. - in_env = (:unionall_env => tv) in io - function show_bound(io::IO, b::ANY) - parens = isa(b,UnionAll) && !print_without_params(b) - parens && print(io, "(") - show(io, b) - parens && print(io, ")") - end - lb, ub = tv.lb, tv.ub - if !in_env && lb !== Bottom - if ub === Any - write(io, tv.name) - print(io, ">:") - show_bound(io, lb) - else - show_bound(io, lb) - print(io, "<:") - write(io, tv.name) - end - else - write(io, tv.name) - end - if !in_env && ub !== Any - print(io, "<:") - show_bound(io, ub) - end - nothing -end - -function dump(io::IO, x::SimpleVector, n::Int, indent) - if isempty(x) - print(io, "empty SimpleVector") - return - end - print(io, "SimpleVector") - if n > 0 - for i = 1:length(x) - println(io) - print(io, indent, " ", i, ": ") - if isassigned(x,i) - dump(io, x[i], n - 1, string(indent, " ")) - else - print(io, undef_ref_str) - end - end - end - nothing -end - -function dump(io::IO, x::ANY, n::Int, indent) - T = typeof(x) - if isa(x, Function) - print(io, x, " (function of type ", T, ")") - else - print(io, T) - end - if nfields(T) > 0 - if n > 0 - for field in (isa(x,Tuple) ? (1:length(x)) : fieldnames(T)) - println(io) - print(io, indent, " ", field, ": ") - if isdefined(x,field) - dump(io, getfield(x, field), n - 1, string(indent, " ")) - else - print(io, undef_ref_str) - end - end - end - else - !isa(x,Function) && print(io, " ", x) - end - nothing -end - -dump(io::IO, x::Module, n::Int, indent) = print(io, "Module ", x) -dump(io::IO, x::String, n::Int, indent) = (print(io, "String "); show(io, x)) -dump(io::IO, x::Symbol, n::Int, indent) = print(io, typeof(x), " ", x) -dump(io::IO, x::Union, n::Int, indent) = print(io, x) - -function dump_elts(io::IO, x::Array, n::Int, indent, i0, i1) - for i in i0:i1 - print(io, indent, " ", i, ": ") - if !isassigned(x,i) - print(io, undef_ref_str) - else - dump(io, x[i], n - 1, string(indent, " ")) - end - i < i1 && println(io) - end -end - -function dump(io::IO, x::Array, n::Int, indent) - print(io, "Array{$(eltype(x))}($(size(x)))") - if eltype(x) <: Number - print(io, " ") - show(io, x) - else - if n > 0 && !isempty(x) - println(io) - if get(io, :limit, false) - dump_elts(io, x, n, indent, 1, (length(x) <= 10 ? length(x) : 5)) - if length(x) > 10 - println(io) - println(io, indent, " ...") - dump_elts(io, x, n, indent, length(x)-4, length(x)) - end - else - dump_elts(io, x, n, indent, 1, length(x)) - end - end - end - nothing -end - -# Types -function dump(io::IO, x::DataType, n::Int, indent) - print(io, x) - if x !== Any - print(io, " <: ", supertype(x)) - end - if n > 0 && !(x <: Tuple) - tvar_io::IOContext = io - for tparam in x.parameters - # approximately recapture the list of tvar parameterization - # that may be used by the internal fields - if isa(tparam, TypeVar) - tvar_io = IOContext(tvar_io, :unionall_env => tparam) - end - end - fields = fieldnames(x) - fieldtypes = x.types - for idx in 1:length(fields) - println(io) - print(io, indent, " ", fields[idx], "::") - print(tvar_io, fieldtypes[idx]) - end - end - nothing -end - -# dumptype is for displaying abstract type hierarchies, -# based on Jameson Nash's examples/typetree.jl -function dumptype(io::IO, x::ANY, n::Int, indent) - print(io, x) - n == 0 && return # too deeply nested - isa(x, DataType) && x.abstract && dumpsubtypes(io, x, Main, n, indent) - nothing -end - -directsubtype(a::DataType, b::DataType) = supertype(a).name === b.name -directsubtype(a::UnionAll, b::DataType) = directsubtype(a.body, b) -directsubtype(a::Union, b::DataType) = directsubtype(a.a, b) || directsubtype(a.b, b) -# Fallback to handle TypeVar's -directsubtype(a, b::DataType) = false -function dumpsubtypes(io::IO, x::DataType, m::Module, n::Int, indent) - for s in names(m, true) - if isdefined(m, s) && !isdeprecated(m, s) - t = getfield(m, s) - if t === x || t === m - continue - elseif isa(t, Module) && module_name(t) === s && module_parent(t) === m - # recurse into primary module bindings - dumpsubtypes(io, x, t, n, indent) - elseif isa(t, UnionAll) && directsubtype(t::UnionAll, x) - dt = unwrap_unionall(t) - println(io) - if isa(dt, DataType) && dt.name.wrapper === t - # primary type binding - print(io, indent, " ") - dumptype(io, dt, n - 1, string(indent, " ")) - else - # aliases to types - print(io, indent, " ", m, ".", s, "{") - tvar_io::IOContext = io - tp = t - while true - show(tvar_io, tp.var) - tvar_io = IOContext(tvar_io, :unionall_env, tp.var) - tp = tp.body - if isa(tp, UnionAll) - print(io, ", ") - else - print(io, "} = ") - break - end - end - show(tvar_io, tp) - end - elseif isa(t, Union) && directsubtype(t::Union, x) - println(io) - print(io, indent, " ", m, ".", s, " = ", t) - elseif isa(t, DataType) && directsubtype(t::DataType, x) - println(io) - if t.name.module !== m || t.name.name != s - # aliases to types - print(io, indent, " ", m, ".", s, " = ") - show(io, t) - else - # primary type binding - print(io, indent, " ") - dumptype(io, t, n - 1, string(indent, " ")) - end - end - end - end - nothing -end - - -# For abstract types, use _dumptype only if it's a form that will be called -# interactively. -dump(io::IO, x::DataType; maxdepth=8) = ((x.abstract ? dumptype : dump)(io, x, maxdepth, ""); println(io)) - -dump(io::IO, arg; maxdepth=8) = (dump(io, arg, maxdepth, ""); println(io)) -dump(arg; maxdepth=8) = dump(IOContext(STDOUT::IO, :limit => true), arg; maxdepth=maxdepth) - - -""" -`alignment(X)` returns a tuple (left,right) showing how many characters are -needed on either side of an alignment feature such as a decimal point. -""" -alignment(io::IO, x::Any) = (0, length(sprint(0, show, x, env=io))) -alignment(io::IO, x::Number) = (length(sprint(0, show, x, env=io)), 0) -"`alignment(42)` yields (2,0)" -alignment(io::IO, x::Integer) = (length(sprint(0, show, x, env=io)), 0) -"`alignment(4.23)` yields (1,3) for `4` and `.23`" -function alignment(io::IO, x::Real) - m = match(r"^(.*?)((?:[\.eE].*)?)$", sprint(0, show, x, env=io)) - m === nothing ? (length(sprint(0, show, x, env=io)), 0) : - (length(m.captures[1]), length(m.captures[2])) -end -"`alignment(1 + 10im)` yields (3,5) for `1 +` and `_10im` (plus sign on left, space on right)" -function alignment(io::IO, x::Complex) - m = match(r"^(.*[^e][\+\-])(.*)$", sprint(0, show, x, env=io)) - m === nothing ? (length(sprint(0, show, x, env=io)), 0) : - (length(m.captures[1]), length(m.captures[2])) -end -function alignment(io::IO, x::Rational) - m = match(r"^(.*?/)(/.*)$", sprint(0, show, x, env=io)) - m === nothing ? (length(sprint(0, show, x, env=io)), 0) : - (length(m.captures[1]), length(m.captures[2])) -end - -const undef_ref_str = "#undef" -const undef_ref_alignment = (3,3) - -""" -`alignment(X, rows, cols, cols_if_complete, cols_otherwise, sep)` returns the -alignment for specified parts of array `X`, returning the (left,right) info. -It will look in X's `rows`, `cols` (both lists of indices) -and figure out what's needed to be fully aligned, for example looking all -the way down a column and finding out the maximum size of each element. -Parameter `sep::Integer` is number of spaces to put between elements. -`cols_if_complete` and `cols_otherwise` indicate screen width to use. -Alignment is reported as a vector of (left,right) tuples, one for each -column going across the screen. -""" -function alignment(io::IO, X::AbstractVecOrMat, - rows::AbstractVector, cols::AbstractVector, - cols_if_complete::Integer, cols_otherwise::Integer, sep::Integer) - a = Tuple{Int, Int}[] - for j in cols # need to go down each column one at a time - l = r = 0 - for i in rows # plumb down and see what largest element sizes are - if isassigned(X,i,j) - aij = alignment(io, X[i,j]) - else - aij = undef_ref_alignment - end - l = max(l, aij[1]) # left characters - r = max(r, aij[2]) # right characters - end - push!(a, (l, r)) # one tuple per column of X, pruned to screen width - if length(a) > 1 && sum(map(sum,a)) + sep*length(a) >= cols_if_complete - pop!(a) # remove this latest tuple if we're already beyond screen width - break - end - end - if 1 < length(a) < length(indices(X,2)) - while sum(map(sum,a)) + sep*length(a) >= cols_otherwise - pop!(a) - end - end - return a -end - -""" -Unexported convenience function used in body of `replace_in_print_matrix` -methods. By default returns a string of the same width as original with a -centered cdot, used in printing of structural zeros of structured matrices. -Accept keyword args `c` for alternate single character marker. -""" -function replace_with_centered_mark(s::AbstractString;c::Char = '⋅') - N = length(s) - return join(setindex!([" " for i=1:N],string(c),ceil(Int,N/2))) -end - -""" -`print_matrix_row(io, X, A, i, cols, sep)` produces the aligned output for -a single matrix row X[i, cols] where the desired list of columns is given. -The corresponding alignment A is used, and the separation between elements -is specified as string sep. -`print_matrix_row` will also respect compact output for elements. -""" -function print_matrix_row(io::IO, - X::AbstractVecOrMat, A::Vector, - i::Integer, cols::AbstractVector, sep::AbstractString) - isempty(A) || first(indices(cols,1)) == 1 || throw(DimensionMismatch("indices of cols ($(indices(cols,1))) must start at 1")) - for k = 1:length(A) - j = cols[k] - if isassigned(X,Int(i),Int(j)) # isassigned accepts only `Int` indices - x = X[i,j] - a = alignment(io, x) - sx = sprint(0, show, x, env=io) - else - a = undef_ref_alignment - sx = undef_ref_str - end - l = repeat(" ", A[k][1]-a[1]) # pad on left and right as needed - r = repeat(" ", A[k][2]-a[2]) - prettysx = replace_in_print_matrix(X,i,j,sx) - print(io, l, prettysx, r) - if k < length(A); print(io, sep); end - end -end - -""" -`print_matrix_vdots` is used to show a series of vertical ellipsis instead -of a bunch of rows for long matrices. Not only is the string vdots shown -but it also repeated every M elements if desired. -""" -function print_matrix_vdots(io::IO, vdots::AbstractString, - A::Vector, sep::AbstractString, M::Integer, m::Integer) - for k = 1:length(A) - w = A[k][1] + A[k][2] - if k % M == m - l = repeat(" ", max(0, A[k][1]-length(vdots))) - r = repeat(" ", max(0, w-length(vdots)-length(l))) - print(io, l, vdots, r) - else - print(io, repeat(" ", w)) - end - if k < length(A); print(io, sep); end - end -end - -""" - print_matrix(io::IO, mat, pre, sep, post, hdots, vdots, ddots, hmod, vmod) - -Prints a matrix with limited output size. If `io` sets `:limit` to true, -then only the corners of the matrix are printed, separated with vertical, -horizontal, and diagonal ellipses as appropriate. -Optional arguments are string pre (printed before the matrix, e.g. an opening bracket) -which will cause a corresponding same-size indent on following rows, and -string post (printed at the end of the last row of the matrix). -Also options to use different ellipsis characters hdots, vdots, ddots. -These are repeated every hmod or vmod elements. -""" -function print_matrix(io::IO, X::AbstractVecOrMat, - pre::AbstractString = " ", # pre-matrix string - sep::AbstractString = " ", # separator between elements - post::AbstractString = "", # post-matrix string - hdots::AbstractString = " \u2026 ", - vdots::AbstractString = "\u22ee", - ddots::AbstractString = " \u22f1 ", - hmod::Integer = 5, vmod::Integer = 5) - if !get(io, :limit, false) - screenheight = screenwidth = typemax(Int) - else - sz = displaysize(io) - screenheight, screenwidth = sz[1] - 4, sz[2] - end - screenwidth -= length(pre) + length(post) - presp = repeat(" ", length(pre)) # indent each row to match pre string - postsp = "" - @assert strwidth(hdots) == strwidth(ddots) - sepsize = length(sep) - rowsA, colsA = indices(X,1), indices(X,2) - m, n = length(rowsA), length(colsA) - # To figure out alignments, only need to look at as many rows as could - # fit down screen. If screen has at least as many rows as A, look at A. - # If not, then we only need to look at the first and last chunks of A, - # each half a screen height in size. - halfheight = div(screenheight,2) - if m > screenheight - rowsA = [rowsA[1:halfheight]; rowsA[m-div(screenheight-1,2)+1:m]] - end - # Similarly for columns, only necessary to get alignments for as many - # columns as could conceivably fit across the screen - maxpossiblecols = div(screenwidth, 1+sepsize) - if n > maxpossiblecols - colsA = [colsA[1:maxpossiblecols]; colsA[(n-maxpossiblecols+1):n]] - end - A = alignment(io, X, rowsA, colsA, screenwidth, screenwidth, sepsize) - # Nine-slicing is accomplished using print_matrix_row repeatedly - if m <= screenheight # rows fit vertically on screen - if n <= length(A) # rows and cols fit so just print whole matrix in one piece - for i in rowsA - print(io, i == first(rowsA) ? pre : presp) - print_matrix_row(io, X,A,i,colsA,sep) - print(io, i == last(rowsA) ? post : postsp) - if i != last(rowsA); println(io); end - end - else # rows fit down screen but cols don't, so need horizontal ellipsis - c = div(screenwidth-length(hdots)+1,2)+1 # what goes to right of ellipsis - Ralign = reverse(alignment(io, X, rowsA, reverse(colsA), c, c, sepsize)) # alignments for right - c = screenwidth - sum(map(sum,Ralign)) - (length(Ralign)-1)*sepsize - length(hdots) - Lalign = alignment(io, X, rowsA, colsA, c, c, sepsize) # alignments for left of ellipsis - for i in rowsA - print(io, i == first(rowsA) ? pre : presp) - print_matrix_row(io, X,Lalign,i,colsA[1:length(Lalign)],sep) - print(io, (i - first(rowsA)) % hmod == 0 ? hdots : repeat(" ", length(hdots))) - print_matrix_row(io, X,Ralign,i,n-length(Ralign)+colsA,sep) - print(io, i == last(rowsA) ? post : postsp) - if i != last(rowsA); println(io); end - end - end - else # rows don't fit so will need vertical ellipsis - if n <= length(A) # rows don't fit, cols do, so only vertical ellipsis - for i in rowsA - print(io, i == first(rowsA) ? pre : presp) - print_matrix_row(io, X,A,i,colsA,sep) - print(io, i == last(rowsA) ? post : postsp) - if i != rowsA[end]; println(io); end - if i == rowsA[halfheight] - print(io, i == first(rowsA) ? pre : presp) - print_matrix_vdots(io, vdots,A,sep,vmod,1) - println(io, i == last(rowsA) ? post : postsp) - end - end - else # neither rows nor cols fit, so use all 3 kinds of dots - c = div(screenwidth-length(hdots)+1,2)+1 - Ralign = reverse(alignment(io, X, rowsA, reverse(colsA), c, c, sepsize)) - c = screenwidth - sum(map(sum,Ralign)) - (length(Ralign)-1)*sepsize - length(hdots) - Lalign = alignment(io, X, rowsA, colsA, c, c, sepsize) - r = mod((length(Ralign)-n+1),vmod) # where to put dots on right half - for i in rowsA - print(io, i == first(rowsA) ? pre : presp) - print_matrix_row(io, X,Lalign,i,colsA[1:length(Lalign)],sep) - print(io, (i - first(rowsA)) % hmod == 0 ? hdots : repeat(" ", length(hdots))) - print_matrix_row(io, X,Ralign,i,n-length(Ralign)+colsA,sep) - print(io, i == last(rowsA) ? post : postsp) - if i != rowsA[end]; println(io); end - if i == rowsA[halfheight] - print(io, i == first(rowsA) ? pre : presp) - print_matrix_vdots(io, vdots,Lalign,sep,vmod,1) - print(io, ddots) - print_matrix_vdots(io, vdots,Ralign,sep,vmod,r) - println(io, i == last(rowsA) ? post : postsp) - end - end - end - end -end - -""" - summary(x) - -Return a string giving a brief description of a value. By default returns -`string(typeof(x))`, e.g. [`Int64`](@ref). - -For arrays, returns a string of size and type info, -e.g. `10-element Array{Int64,1}`. - -```jldoctest -julia> summary(1) -"Int64" - -julia> summary(zeros(2)) -"2-element Array{Float64,1}" -``` -""" -summary(x) = string(typeof(x)) # e.g. Int64 - -# sizes such as 0-dimensional, 4-dimensional, 2x3 -dims2string(d::Dims) = isempty(d) ? "0-dimensional" : - length(d) == 1 ? "$(d[1])-element" : - join(map(string,d), '×') - -inds2string(inds::Indices) = join(map(string,inds), '×') - -# anything array-like gets summarized e.g. 10-element Array{Int64,1} -summary(a::AbstractArray) = _summary(a, indices(a)) -_summary(a, inds::Tuple{Vararg{OneTo}}) = string(dims2string(length.(inds)), " ", typeof(a)) -_summary(a, inds) = string(typeof(a), " with indices ", inds2string(inds)) - -# n-dimensional arrays -function show_nd(io::IO, a::AbstractArray, print_matrix, label_slices) - limit::Bool = get(io, :limit, false) - if isempty(a) - return - end - tailinds = tail(tail(indices(a))) - nd = ndims(a)-2 - for I in CartesianRange(tailinds) - idxs = I.I - if limit - for i = 1:nd - ii = idxs[i] - ind = tailinds[i] - if length(ind) > 10 - if ii == ind[4] && all(d->idxs[d]==first(tailinds[d]),1:i-1) - for j=i+1:nd - szj = length(indices(a, j+2)) - indj = tailinds[j] - if szj>10 && first(indj)+2 < idxs[j] <= last(indj)-3 - @goto skip - end - end - #println(io, idxs) - print(io, "...\n\n") - @goto skip - end - if ind[3] < ii <= ind[end-3] - @goto skip - end - end - end - end - if label_slices - print(io, "[:, :, ") - for i = 1:(nd-1); print(io, "$(idxs[i]), "); end - println(io, idxs[end], "] =") - end - slice = view(a, indices(a,1), indices(a,2), idxs...) - print_matrix(io, slice) - print(io, idxs == map(last,tailinds) ? "" : "\n\n") - @label skip - end -end - -""" -`print_matrix_repr(io, X)` prints matrix X with opening and closing square brackets. -""" -function print_matrix_repr(io, X::AbstractArray) - limit = get(io, :limit, false)::Bool - compact, prefix = array_eltype_show_how(X) - if compact && !haskey(io, :compact) - io = IOContext(io, :compact => compact) - end - indr, indc = indices(X,1), indices(X,2) - nr, nc = length(indr), length(indc) - rdots, cdots = false, false - rr1, rr2 = UnitRange{Int}(indr), 1:0 - cr1, cr2 = UnitRange{Int}(indc), 1:0 - if limit - if nr > 4 - rr1, rr2 = rr1[1:2], rr1[nr-1:nr] - rdots = true - end - if nc > 4 - cr1, cr2 = cr1[1:2], cr1[nc-1:nc] - cdots = true - end - end - print(io, prefix, "[") - for rr in (rr1, rr2) - for i in rr - for cr in (cr1, cr2) - for j in cr - j > first(cr) && print(io, " ") - if !isassigned(X,i,j) - print(io, undef_ref_str) - else - el = X[i,j] - show(io, el) - end - end - if last(cr) == last(indc) - i < last(indr) && print(io, "; ") - elseif cdots - print(io, " \u2026 ") - end - end - end - last(rr) != nr && rdots && print(io, "\u2026 ; ") - end - print(io, "]") -end - -show(io::IO, X::AbstractArray) = showarray(io, X, true) - -repremptyarray(io::IO, X::Array{T}) where {T} = print(io, "Array{$T}(", join(size(X),','), ')') -repremptyarray(io, X) = nothing # by default, we don't know this constructor - -function showarray(io::IO, X::AbstractArray, repr::Bool = true; header = true) - if repr && ndims(X) == 1 - return show_vector(io, X, "[", "]") - end - if !haskey(io, :compact) - io = IOContext(io, :compact => true) - end - if !repr && get(io, :limit, false) && eltype(X) === Method - # override usual show method for Vector{Method}: don't abbreviate long lists - io = IOContext(io, :limit => false) - end - (!repr && header) && print(io, summary(X)) - if !isempty(X) - (!repr && header) && println(io, ":") - if ndims(X) == 0 - if isassigned(X) - return show(io, X[]) - else - return print(io, undef_ref_str) - end - end - if repr - if ndims(X) <= 2 - print_matrix_repr(io, X) - else - show_nd(io, X, print_matrix_repr, false) - end - else - punct = (" ", " ", "") - if ndims(X) <= 2 - print_matrix(io, X, punct...) - else - show_nd(io, X, - (io, slice) -> print_matrix(io, slice, punct...), - !repr) - end - end - elseif repr - repremptyarray(io, X) - end -end - -showall(x) = showall(STDOUT, x) -function showall(io::IO, x) - if !get(io, :limit, false) - show(io, x) - else - show(IOContext(io, :limit => false), x) - end -end - -showcompact(x) = showcompact(STDOUT, x) -function showcompact(io::IO, x) - if get(io, :compact, false) - show(io, x) - else - show(IOContext(io, :compact => true), x) - end -end - -# returns compact, prefix -function array_eltype_show_how(X) - e = eltype(X) - if print_without_params(e) - str = string(unwrap_unionall(e).name) # Print "Array" rather than "Array{T,N}" - else - str = string(e) - end - # Types hard-coded here are those which are created by default for a given syntax - isleaftype(e), (!isempty(X) && (e===Float64 || e===Int || e===Char) ? "" : str) -end - -function show_vector(io::IO, v, opn, cls) - compact, prefix = array_eltype_show_how(v) - limited = get(io, :limit, false) - if compact && !haskey(io, :compact) - io = IOContext(io, :compact => compact) - end - print(io, prefix) - if limited && _length(v) > 20 - inds = indices1(v) - show_delim_array(io, v, opn, ",", "", false, inds[1], inds[1]+9) - print(io, " \u2026 ") - show_delim_array(io, v, "", ",", cls, false, inds[end-9], inds[end]) - else - show_delim_array(io, v, opn, ",", cls, false) - end -end - -# printing BitArrays - -# (following functions not exported - mainly intended for debug) - -function print_bit_chunk(io::IO, c::UInt64, l::Integer = 64) - for s = 0:l-1 - d = (c >>> s) & 1 - print(io, "01"[d + 1]) - if (s + 1) & 7 == 0 - print(io, " ") - end - end -end - -print_bit_chunk(c::UInt64, l::Integer) = print_bit_chunk(STDOUT, c, l) -print_bit_chunk(c::UInt64) = print_bit_chunk(STDOUT, c) - -function bitshow(io::IO, B::BitArray) - isempty(B) && return - Bc = B.chunks - for i = 1:length(Bc)-1 - print_bit_chunk(io, Bc[i]) - print(io, ": ") - end - l = _mod64(length(B)-1) + 1 - print_bit_chunk(io, Bc[end], l) -end -bitshow(B::BitArray) = bitshow(STDOUT, B) - -bitstring(B::BitArray) = sprint(bitshow, B) diff --git a/julia-0.6.3/share/julia/base/simdloop.jl b/julia-0.6.3/share/julia/base/simdloop.jl deleted file mode 100644 index d83f519..0000000 --- a/julia-0.6.3/share/julia/base/simdloop.jl +++ /dev/null @@ -1,92 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -# Support for @simd for - -module SimdLoop - -export @simd, simd_outer_range, simd_inner_length, simd_index - -# Error thrown from ill-formed uses of @simd -mutable struct SimdError <: Exception - msg::String -end - -# Parse iteration space expression -# symbol '=' range -# symbol 'in' range -function parse_iteration_space(x) - (isa(x, Expr) && (x.head == :(=) || x.head == :in)) || throw(SimdError("= or in expected")) - length(x.args) == 2 || throw(SimdError("simd range syntax is wrong")) - isa(x.args[1], Symbol) || throw(SimdError("simd loop index must be a symbol")) - x.args # symbol, range -end - -# reject invalid control flow statements in @simd loop body -function check_body!(x::Expr) - if x.head === :break || x.head == :continue - throw(SimdError("$(x.head) is not allowed inside a @simd loop body")) - elseif x.head === :macrocall && x.args[1] === Symbol("@goto") - throw(SimdError("$(x.args[1]) is not allowed inside a @simd loop body")) - end - for arg in x.args - check_body!(arg) - end - return true -end -check_body!(x::QuoteNode) = check_body!(x.value) -check_body!(x) = true - -# @simd splits a for loop into two loops: an outer scalar loop and -# an inner loop marked with :simdloop. The simd_... functions define -# the splitting. - -# Get range for outer loop. -simd_outer_range(r) = 0:0 - -# Get trip count for inner loop. -@inline simd_inner_length(r,j::Int) = length(r) - -# Construct user-level element from original range, outer loop index j, and inner loop index i. -@inline simd_index(r,j::Int,i) = (@inbounds ret = r[i+1]; ret) - -# Compile Expr x in context of @simd. -function compile(x) - (isa(x, Expr) && x.head == :for) || throw(SimdError("for loop expected")) - length(x.args) == 2 || throw(SimdError("1D for loop expected")) - check_body!(x) - - var,range = parse_iteration_space(x.args[1]) - r = gensym("r") # Range value - j = gensym("i") # Iteration variable for outer loop - n = gensym("n") # Trip count for inner loop - i = gensym("i") # Trip index for inner loop - quote - # Evaluate range value once, to enhance type and data flow analysis by optimizers. - let $r = $range - for $j in Base.simd_outer_range($r) - let $n = Base.simd_inner_length($r,$j) - if zero($n) < $n - # Lower loop in way that seems to work best for LLVM 3.3 vectorizer. - let $i = zero($n) - while $i < $n - local $var = Base.simd_index($r,$j,$i) - $(x.args[2]) # Body of loop - $i += 1 - $(Expr(:simdloop)) # Mark loop as SIMD loop - end - end - # Set index to last value just like a regular for loop would - $var = last($r) - end - end - end - end - nothing - end -end - -macro simd(forloop) - esc(compile(forloop)) -end - -end # module SimdLoop diff --git a/julia-0.6.3/share/julia/base/socket.jl b/julia-0.6.3/share/julia/base/socket.jl deleted file mode 100644 index e104b40..0000000 --- a/julia-0.6.3/share/julia/base/socket.jl +++ /dev/null @@ -1,895 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -## IP ADDRESS HANDLING ## -abstract type IPAddr end - -Base.isless{T<:IPAddr}(a::T, b::T) = isless(a.host, b.host) -Base.convert(dt::Type{<:Integer}, ip::IPAddr) = dt(ip.host) - -struct IPv4 <: IPAddr - host::UInt32 - IPv4(host::UInt32) = new(host) - IPv4(a::UInt8,b::UInt8,c::UInt8,d::UInt8) = new(UInt32(a)<<24| - UInt32(b)<<16| - UInt32(c)<<8| - d) - function IPv4(a::Integer,b::Integer,c::Integer,d::Integer) - if !(0<=a<=255 && 0<=b<=255 && 0<=c<=255 && 0<=d<=255) - throw(ArgumentError("IPv4 field out of range (must be 0-255)")) - end - IPv4(UInt8(a),UInt8(b),UInt8(c),UInt8(d)) - end -end - -""" - IPv4(host::Integer) -> IPv4 - -Returns an IPv4 object from ip address `host` formatted as an [`Integer`](@ref). - -```jldoctest -julia> IPv4(3223256218) -ip"192.30.252.154" -``` -""" -function IPv4(host::Integer) - if host < 0 - throw(ArgumentError("IPv4 address must be positive")) - elseif typemax(typeof(host)) > typemax(UInt32) && host > typemax(UInt32) - throw(ArgumentError("IPv4 address must fit within 32 bits")) - else - return IPv4(UInt32(host)) - end -end - -# constructor: ("1.2.3.4") -IPv4(str::AbstractString) = parse(IPv4, str) - -show(io::IO,ip::IPv4) = print(io,"ip\"",ip,"\"") -print(io::IO,ip::IPv4) = print(io,dec((ip.host&(0xFF000000))>>24),".", - dec((ip.host&(0xFF0000))>>16),".", - dec((ip.host&(0xFF00))>>8),".", - dec(ip.host&0xFF)) - -struct IPv6 <: IPAddr - host::UInt128 - IPv6(host::UInt128) = new(host) - IPv6(a::UInt16,b::UInt16,c::UInt16,d::UInt16, - e::UInt16,f::UInt16,g::UInt16,h::UInt16) = new(UInt128(a)<<(7*16)| - UInt128(b)<<(6*16)| - UInt128(c)<<(5*16)| - UInt128(d)<<(4*16)| - UInt128(e)<<(3*16)| - UInt128(f)<<(2*16)| - UInt128(g)<<(1*16)| - h) - function IPv6(a::Integer,b::Integer,c::Integer,d::Integer, - e::Integer,f::Integer,g::Integer,h::Integer) - if !(0<=a<=0xFFFF && 0<=b<=0xFFFF && 0<=c<=0xFFFF && 0<=d<=0xFFFF && - 0<=e<=0xFFFF && 0<=f<=0xFFFF && 0<=g<=0xFFFF && 0<=h<=0xFFFF) - throw(ArgumentError("IPv6 field out of range (must be 0-65535)")) - end - IPv6(UInt16(a),UInt16(b),UInt16(c),UInt16(d), - UInt16(e),UInt16(f),UInt16(g),UInt16(h)) - end -end - -""" - IPv6(host::Integer) -> IPv6 - -Returns an IPv6 object from ip address `host` formatted as an [`Integer`](@ref). - -```jldoctest -julia> IPv6(3223256218) -ip"::c01e:fc9a" -``` -""" -function IPv6(host::Integer) - if host < 0 - throw(ArgumentError("IPv6 address must be positive")) - # We allow passing bigger integer types, but need to be careful to avoid overflow - # Let's hope promotion rules are sensible - elseif typemax(typeof(host)) > typemax(UInt128) && host > typemax(UInt128) - throw(ArgumentError("IPv6 address must fit within 128 bits")) - else - return IPv6(UInt128(host)) - end -end - -IPv6(str::AbstractString) = parse(IPv6, str) - -# Suppress leading '0's and "0x" -print_ipv6_field(io,field::UInt16) = print(io,hex(field)) - -print_ipv6_field(io,ip,i) = print_ipv6_field(io,ipv6_field(ip,i)) -function ipv6_field(ip::IPv6,i) - if i < 0 || i > 7 - throw(BoundsError()) - end - UInt16(ip.host&(UInt128(0xFFFF)<<(i*16))>>(i*16)) -end - -show(io::IO, ip::IPv6) = print(io,"ip\"",ip,"\"") -# RFC 5952 compliant show function -# http://tools.ietf.org/html/rfc5952 -function print(io::IO,ip::IPv6) - i = 8 - m = 0 - longest_sub_i = -1 - while i!=0 - i-=1 - field = ipv6_field(ip,i) - if field == 0 && longest_sub_i == -1 - # Find longest subsequence of 0 - longest_sub_i,j,m,c = i,i,1,1 - while j != 0 - j-=1 - if ipv6_field(ip,j) == 0 - c += 1 - else - c = 0 - end - if c > m - if j+c != longest_sub_i+1 - longest_sub_i = j+c-1 - end - m = c - end - end - # Prevent single 0 from contracting to :: as required - if m == 1 - longest_sub_i = 9 - end - end - if i == longest_sub_i - print(io,":") - i -= m-1 - if i == 0 - print(io,":") - break - end - else - if i != 7 - print(io,":") - end - print_ipv6_field(io,field) - end - end -end - -# Parsing - -const ipv4_leading_zero_error = """ -Leading zeros in IPv4 addresses are disallowed due to ambiguity. -If the address is in octal or hexadecimal, convert it to decimal, otherwise remove the leading zero. -""" - -function parse(::Type{IPv4}, str::AbstractString) - fields = split(str,'.') - i = 1 - ret = 0 - for f in fields - if isempty(f) - throw(ArgumentError("empty field in IPv4 address")) - end - if length(f) > 1 && f[1] == '0' - throw(ArgumentError(ipv4_leading_zero_error)) - else - r = parse(Int,f,10) - end - if i != length(fields) - if r < 0 || r > 255 - throw(ArgumentError("IPv4 field out of range (must be 0-255)")) - end - ret |= UInt32(r) << ((4-i)*8) - else - if r > ((UInt64(1)<<((5-length(fields))*8))-1) - throw(ArgumentError("IPv4 field too large")) - end - ret |= r - end - i+=1 - end - IPv4(ret) -end - -function parseipv6fields(fields,num_fields) - if length(fields) > num_fields - throw(ArgumentError("too many fields in IPv6 address")) - end - cf = 7 - ret = UInt128(0) - for f in fields - if isempty(f) - # ::abc:... and ..:abc:: - if cf != 7 && cf != 0 - cf -= num_fields-length(fields) - end - cf -= 1 - continue - end - ret |= UInt128(parse(Int,f,16))<<(cf*16) - cf -= 1 - end - ret -end -parseipv6fields(fields) = parseipv6fields(fields,8) - -function parse(::Type{IPv6}, str::AbstractString) - fields = split(str,':') - if length(fields) > 8 - throw(ArgumentError("too many fields in IPv6 address")) - elseif length(fields) == 8 - return IPv6(parseipv6fields(fields)) - elseif in('.',fields[end]) - return IPv6((parseipv6fields(fields[1:(end-1)],6)) - | parse(IPv4, fields[end]).host ) - else - return IPv6(parseipv6fields(fields)) - end -end - -# -# This support IPv4 addresses in the common dot (IPv4) or colon (IPv6) -# separated formats. Most other common formats use a standard integer encoding -# of the appropriate size and should use the appropriate constructor -# - -function parse(::Type{IPAddr}, str::AbstractString) - if ':' in str - return parse(IPv6, str) - else - return parse(IPv4, str) - end -end - -macro ip_str(str) - return parse(IPAddr, str) -end - -struct InetAddr{T<:IPAddr} - host::T - port::UInt16 -end - -InetAddr(ip::IPAddr, port) = InetAddr{typeof(ip)}(ip, port) - -## SOCKETS ## - -mutable struct TCPSocket <: LibuvStream - handle::Ptr{Void} - status::Int - buffer::IOBuffer - readnotify::Condition - connectnotify::Condition - closenotify::Condition - sendbuf::Nullable{IOBuffer} - lock::ReentrantLock - throttle::Int - - function TCPSocket(handle::Ptr{Void}, status) - tcp = new( - handle, - status, - PipeBuffer(), - Condition(), - Condition(), - Condition(), - nothing, - ReentrantLock(), - DEFAULT_READ_BUFFER_SZ) - associate_julia_struct(tcp.handle, tcp) - finalizer(tcp, uvfinalize) - return tcp - end -end - -# kw arg "delay": if true, libuv delays creation of the socket fd till the first bind call -function TCPSocket(; delay=true) - tcp = TCPSocket(Libc.malloc(_sizeof_uv_tcp), StatusUninit) - af_spec = delay ? 0 : 2 # AF_UNSPEC is 0, AF_INET is 2 - - err = ccall(:uv_tcp_init_ex, Cint, (Ptr{Void}, Ptr{Void}, Cuint), - eventloop(), tcp.handle, af_spec) - uv_error("failed to create tcp socket", err) - tcp.status = StatusInit - return tcp -end - -mutable struct TCPServer <: LibuvServer - handle::Ptr{Void} - status::Int - connectnotify::Condition - closenotify::Condition - - function TCPServer(handle::Ptr{Void}, status) - tcp = new( - handle, - status, - Condition(), - Condition()) - associate_julia_struct(tcp.handle, tcp) - finalizer(tcp, uvfinalize) - return tcp - end -end -function TCPServer() - tcp = TCPServer(Libc.malloc(_sizeof_uv_tcp), StatusUninit) - err = ccall(:uv_tcp_init, Cint, (Ptr{Void}, Ptr{Void}), - eventloop(), tcp.handle) - uv_error("failed to create tcp server", err) - tcp.status = StatusInit - return tcp -end - -isreadable(io::TCPSocket) = isopen(io) || nb_available(io) > 0 -iswritable(io::TCPSocket) = isopen(io) && io.status != StatusClosing - -## VARIOUS METHODS TO BE MOVED TO BETTER LOCATION - -_jl_connect_raw(sock::TCPSocket, sockaddr::Ptr{Void}) = - ccall(:jl_connect_raw, Int32, (Ptr{Void}, Ptr{Void}, Ptr{Void}), sock.handle, sockaddr, uv_jl_connectcb::Ptr{Void}) -_jl_sockaddr_from_addrinfo(addrinfo::Ptr{Void}) = - ccall(:jl_sockaddr_from_addrinfo, Ptr{Void}, (Ptr{Void},), addrinfo) -_jl_sockaddr_set_port(ptr::Ptr{Void}, port::UInt16) = - ccall(:jl_sockaddr_set_port, Void, (Ptr{Void}, UInt16), ptr, port) - -accept(server::TCPServer) = accept(server, TCPSocket()) - -# Libuv will internally reset the readable and writable flags on -# this pipe after it has successfully accepted the connection, to -# remember that before that this is an invalid pipe -accept(server::PipeServer) = accept(server, init_pipe!(PipeEndpoint(); - readable=false, writable=false, julia_only=true)) - -# UDP - -mutable struct UDPSocket <: LibuvStream - handle::Ptr{Void} - status::Int - recvnotify::Condition - sendnotify::Condition - closenotify::Condition - - function UDPSocket(handle::Ptr{Void}, status) - udp = new( - handle, - status, - Condition(), - Condition(), - Condition()) - associate_julia_struct(udp.handle, udp) - finalizer(udp, uvfinalize) - return udp - end -end -function UDPSocket() - this = UDPSocket(Libc.malloc(_sizeof_uv_udp), StatusUninit) - err = ccall(:uv_udp_init, Cint, (Ptr{Void}, Ptr{Void}), - eventloop(), this.handle) - uv_error("failed to create udp socket", err) - this.status = StatusInit - return this -end - -show(io::IO, stream::UDPSocket) = print(io, typeof(stream), "(", uv_status_string(stream), ")") - -function _uv_hook_close(sock::UDPSocket) - sock.handle = C_NULL - sock.status = StatusClosed - notify(sock.closenotify) - notify(sock.sendnotify) - notify_error(sock.recvnotify,EOFError()) -end - -# Disables dual stack mode. -const UV_TCP_IPV6ONLY = 1 - -# Disables dual stack mode. Only available when using ipv6 binf -const UV_UDP_IPV6ONLY = 1 - -# Indicates message was truncated because read buffer was too small. The -# remainder was discarded by the OS. -const UV_UDP_PARTIAL = 2 - -# Indicates if SO_REUSEADDR will be set when binding the handle in uv_udp_bind. This sets -# the SO_REUSEPORT socket flag on the BSDs and OS X. On other Unix platforms, it sets the -# SO_REUSEADDR flag. What that means is that multiple threads or processes can bind to the -# same address without error (provided they all set the flag) but only the last one to bind -# will receive any traffic, in effect "stealing" the port from the previous listener. -const UV_UDP_REUSEADDR = 4 - -## - -_bind(sock::TCPServer, host::IPv4, port::UInt16, flags::UInt32 = UInt32(0)) = ccall(:jl_tcp_bind, Int32, (Ptr{Void}, UInt16, UInt32, Cuint), - sock.handle, hton(port), hton(host.host), flags) - -_bind(sock::TCPServer, host::IPv6, port::UInt16, flags::UInt32 = UInt32(0)) = ccall(:jl_tcp_bind6, Int32, (Ptr{Void}, UInt16, Ptr{UInt128}, Cuint), - sock.handle, hton(port), Ref(hton(host.host)), flags) - -_bind(sock::UDPSocket, host::IPv4, port::UInt16, flags::UInt32 = UInt32(0)) = ccall(:jl_udp_bind, Int32, (Ptr{Void}, UInt16, UInt32, UInt32), - sock.handle, hton(port), hton(host.host), flags) - -_bind(sock::UDPSocket, host::IPv6, port::UInt16, flags::UInt32 = UInt32(0)) = ccall(:jl_udp_bind6, Int32, (Ptr{Void}, UInt16, Ptr{UInt128}, UInt32), - sock.handle, hton(port), Ref(hton(host.host)), flags) - -""" - bind(socket::Union{UDPSocket, TCPSocket}, host::IPAddr, port::Integer; ipv6only=false, reuseaddr=false, kws...) - -Bind `socket` to the given `host:port`. Note that `0.0.0.0` will listen on all devices. - -* The `ipv6only` parameter disables dual stack mode. If `ipv6only=true`, only an IPv6 stack is created. -* If `reuseaddr=true`, multiple threads or processes can bind to the same address without error - if they all set `reuseaddr=true`, but only the last to bind will receive any traffic. -""" -function bind(sock::Union{TCPServer, UDPSocket}, host::IPAddr, port::Integer; ipv6only = false, reuseaddr = false, kws...) - if sock.status != StatusInit - error("$(typeof(sock)) is not in initialization state") - end - flags = 0 - if isa(host,IPv6) && ipv6only - flags |= isa(sock, UDPSocket) ? UV_UDP_IPV6ONLY : UV_TCP_IPV6ONLY - end - if isa(sock, UDPSocket) && reuseaddr - flags |= UV_UDP_REUSEADDR - end - err = _bind(sock, host, UInt16(port), UInt32(flags)) - if err < 0 - if err != UV_EADDRINUSE && err != UV_EACCES && err != UV_EADDRNOTAVAIL - #TODO: this codepath is not currently tested - throw(UVError("bind", err)) - else - return false - end - end - sock.status = StatusOpen - isa(sock, UDPSocket) && setopt(sock; kws...) - return true -end - -bind(sock::TCPServer, addr::InetAddr) = bind(sock, addr.host, addr.port) - -""" - setopt(sock::UDPSocket; multicast_loop = nothing, multicast_ttl=nothing, enable_broadcast=nothing, ttl=nothing) - -Set UDP socket options. - -* `multicast_loop`: loopback for multicast packets (default: `true`). -* `multicast_ttl`: TTL for multicast packets (default: `nothing`). -* `enable_broadcast`: flag must be set to `true` if socket will be used for broadcast - messages, or else the UDP system will return an access error (default: `false`). -* `ttl`: Time-to-live of packets sent on the socket (default: `nothing`). -""" -function setopt(sock::UDPSocket; multicast_loop = nothing, multicast_ttl=nothing, enable_broadcast=nothing, ttl=nothing) - if sock.status == StatusUninit - error("Cannot set options on uninitialized socket") - end - if multicast_loop !== nothing - uv_error("multicast_loop",ccall(:uv_udp_set_multicast_loop,Cint,(Ptr{Void},Cint),sock.handle,multicast_loop) < 0) - end - if multicast_ttl !== nothing - uv_error("multicast_ttl",ccall(:uv_udp_set_multicast_ttl,Cint,(Ptr{Void},Cint),sock.handle,multicast_ttl)) - end - if enable_broadcast !== nothing - uv_error("enable_broadcast",ccall(:uv_udp_set_broadcast,Cint,(Ptr{Void},Cint),sock.handle,enable_broadcast)) - end - if ttl !== nothing - uv_error("ttl",ccall(:uv_udp_set_ttl,Cint,(Ptr{Void},Cint),sock.handle,ttl)) - end -end - -""" - recv(socket::UDPSocket) - -Read a UDP packet from the specified socket, and return the bytes received. This call blocks. -""" -function recv(sock::UDPSocket) - addr, data = recvfrom(sock) - return data -end - -""" - recvfrom(socket::UDPSocket) -> (address, data) - -Read a UDP packet from the specified socket, returning a tuple of `(address, data)`, where -`address` will be either IPv4 or IPv6 as appropriate. -""" -function recvfrom(sock::UDPSocket) - # If the socket has not been bound, it will be bound implicitly to ::0 and a random port - if sock.status != StatusInit && sock.status != StatusOpen && sock.status != StatusActive - error("UDPSocket is not initialized and open") - end - if ccall(:uv_is_active, Cint, (Ptr{Void},), sock.handle) == 0 - uv_error("recv_start", ccall(:uv_udp_recv_start, Cint, (Ptr{Void}, Ptr{Void}, Ptr{Void}), - sock.handle, uv_jl_alloc_buf::Ptr{Void}, uv_jl_recvcb::Ptr{Void})) - end - sock.status = StatusActive - return stream_wait(sock, sock.recvnotify)::Tuple{Union{IPv4, IPv6}, Vector{UInt8}} -end - -alloc_buf_hook(sock::UDPSocket, size::UInt) = (Libc.malloc(size), size) - -function uv_recvcb(handle::Ptr{Void}, nread::Cssize_t, buf::Ptr{Void}, addr::Ptr{Void}, flags::Cuint) - # C signature documented as (*uv_udp_recv_cb)(...) - sock = @handle_as handle UDPSocket - if nread < 0 - Libc.free(buf_addr) - notify_error(sock.recvnotify, UVError("recv", nread)) - elseif flags & UV_UDP_PARTIAL > 0 - Libc.free(buf_addr) - notify_error(sock.recvnotify, "Partial message received") - else - buf_addr = ccall(:jl_uv_buf_base, Ptr{Void}, (Ptr{Void},), buf) - buf_size = ccall(:jl_uv_buf_len, Csize_t, (Ptr{Void},), buf) - # need to check the address type in order to convert to a Julia IPAddr - addrout = if addr == C_NULL - IPv4(0) - elseif ccall(:jl_sockaddr_in_is_ip4, Cint, (Ptr{Void},), addr) == 1 - IPv4(ntoh(ccall(:jl_sockaddr_host4, UInt32, (Ptr{Void},), addr))) - else - tmp = [UInt128(0)] - ccall(:jl_sockaddr_host6, UInt32, (Ptr{Void}, Ptr{UInt8}), addr, pointer(tmp)) - IPv6(ntoh(tmp[1])) - end - buf = unsafe_wrap(Array, convert(Ptr{UInt8}, buf_addr), Int(nread), true) - notify(sock.recvnotify, (addrout, buf)) - end - ccall(:uv_udp_recv_stop, Cint, (Ptr{Void},), sock.handle) - sock.status = StatusOpen - nothing -end - -function _send(sock::UDPSocket, ipaddr::IPv4, port::UInt16, buf) - ccall(:jl_udp_send, Cint, (Ptr{Void}, UInt16, UInt32, Ptr{UInt8}, Csize_t, Ptr{Void}), - sock.handle, hton(port), hton(ipaddr.host), buf, sizeof(buf), uv_jl_sendcb::Ptr{Void}) -end - -function _send(sock::UDPSocket, ipaddr::IPv6, port::UInt16, buf) - ccall(:jl_udp_send6, Cint, (Ptr{Void}, UInt16, Ptr{UInt128}, Ptr{UInt8}, Csize_t, Ptr{Void}), - sock.handle, hton(port), &hton(ipaddr.host), buf, sizeof(buf), uv_jl_sendcb::Ptr{Void}) -end - -""" - send(socket::UDPSocket, host, port::Integer, msg) - -Send `msg` over `socket` to `host:port`. -""" -function send(sock::UDPSocket,ipaddr,port,msg) - # If the socket has not been bound, it will be bound implicitly to ::0 and a random port - if sock.status != StatusInit && sock.status != StatusOpen && sock.status != StatusActive - error("UDPSocket is not initialized and open") - end - uv_error("send", _send(sock, ipaddr, UInt16(port), msg)) - stream_wait(sock, sock.sendnotify) - nothing -end - -function uv_sendcb(handle::Ptr{Void}, status::Cint) - sock = @handle_as handle UDPSocket - if status < 0 - notify_error(sock.sendnotify, UVError("UDP send failed", status)) - end - notify(sock.sendnotify) - Libc.free(handle) - nothing -end - -## - -mutable struct DNSError <: Exception - host::AbstractString - code::Int32 -end - -function show(io::IO, err::DNSError) - print(io, "DNSError: ", err.host, ", ", struverror(err.code), - " (", uverrorname(err.code), ")") -end - -callback_dict = ObjectIdDict() - -function uv_getaddrinfocb(req::Ptr{Void}, status::Cint, addrinfo::Ptr{Void}) - data = ccall(:jl_uv_getaddrinfo_data, Ptr{Void}, (Ptr{Void},), req) - data == C_NULL && return - cb = unsafe_pointer_to_objref(data)::Function - pop!(callback_dict,cb) # using pop forces an error if cb not in callback_dict - if status != 0 || addrinfo == C_NULL - invokelatest(cb, UVError("uv_getaddrinfocb received an unexpected status code", status)) - else - freeaddrinfo = addrinfo - while addrinfo != C_NULL - sockaddr = ccall(:jl_sockaddr_from_addrinfo, Ptr{Void}, (Ptr{Void},), addrinfo) - if ccall(:jl_sockaddr_is_ip4, Int32, (Ptr{Void},), sockaddr) == 1 - invokelatest(cb, IPv4(ntoh(ccall(:jl_sockaddr_host4, UInt32, (Ptr{Void},), sockaddr)))) - break - #elseif ccall(:jl_sockaddr_is_ip6, Int32, (Ptr{Void},), sockaddr) == 1 - # host = Vector{UInt128}(1) - # scope_id = ccall(:jl_sockaddr_host6, UInt32, (Ptr{Void}, Ptr{UInt128}), sockaddr, host) - # invokelatest(cb, IPv6(ntoh(host[1]))) - # break - end - addrinfo = ccall(:jl_next_from_addrinfo, Ptr{Void}, (Ptr{Void},), addrinfo) - end - ccall(:uv_freeaddrinfo, Void, (Ptr{Void},), freeaddrinfo) - end - Libc.free(req) - nothing -end - -function getaddrinfo(cb::Function, host::String) - isascii(host) || error("non-ASCII hostname: $host") - callback_dict[cb] = cb - status = ccall(:jl_getaddrinfo, Int32, (Ptr{Void}, Cstring, Ptr{UInt8}, Any, Ptr{Void}), - eventloop(), host, C_NULL, cb, uv_jl_getaddrinfocb::Ptr{Void}) - if status == UV_EINVAL - throw(ArgumentError("Invalid uv_getaddrinfo() agument")) - elseif status in [UV_ENOMEM, UV_ENOBUFS] - throw(OutOfMemoryError()) - elseif status < 0 - throw(UVError("uv_getaddrinfo returned an unexpected error code", status)) - end - return nothing -end -getaddrinfo(cb::Function, host::AbstractString) = getaddrinfo(cb, String(host)) - -""" - getaddrinfo(host::AbstractString) -> IPAddr - -Gets the IP address of the `host` (may have to do a DNS lookup) -""" -function getaddrinfo(host::String) - c = Condition() - getaddrinfo(host) do IP - notify(c,IP) - end - r = wait(c) - if isa(r, UVError) - r = r::UVError - code = r.code - if code in (UV_EAI_ADDRFAMILY, UV_EAI_AGAIN, UV_EAI_BADFLAGS, - UV_EAI_BADHINTS, UV_EAI_CANCELED, UV_EAI_FAIL, - UV_EAI_FAMILY, UV_EAI_NODATA, UV_EAI_NONAME, - UV_EAI_OVERFLOW, UV_EAI_PROTOCOL, UV_EAI_SERVICE, - UV_EAI_SOCKTYPE) - throw(DNSError(host, code)) - elseif code == UV_EAI_MEMORY - throw(OutOfMemoryError()) - else - throw(SystemError("uv_getaddrinfocb", -code)) - end - end - return r::IPAddr -end -getaddrinfo(host::AbstractString) = getaddrinfo(String(host)) - -const _sizeof_uv_interface_address = ccall(:jl_uv_sizeof_interface_address,Int32,()) - -""" - getipaddr() -> IPAddr - -Get the IP address of the local machine. -""" -function getipaddr() - addr_ref = Ref{Ptr{UInt8}}(C_NULL) - count_ref = Ref{Int32}(1) - lo_present = false - err = ccall(:jl_uv_interface_addresses, Int32, (Ref{Ptr{UInt8}}, Ref{Int32}), addr_ref, count_ref) - uv_error("getlocalip", err) - addr, count = addr_ref[], count_ref[] - for i = 0:(count-1) - current_addr = addr + i*_sizeof_uv_interface_address - if 1 == ccall(:jl_uv_interface_address_is_internal, Int32, (Ptr{UInt8},), current_addr) - lo_present = true - continue - end - sockaddr = ccall(:jl_uv_interface_address_sockaddr, Ptr{Void}, (Ptr{UInt8},), current_addr) - if ccall(:jl_sockaddr_in_is_ip4, Int32, (Ptr{Void},), sockaddr) == 1 - rv = IPv4(ntoh(ccall(:jl_sockaddr_host4, UInt32, (Ptr{Void},), sockaddr))) - ccall(:uv_free_interface_addresses, Void, (Ptr{UInt8}, Int32), addr, count) - return rv - # Uncomment to enbable IPv6 - #elseif ccall(:jl_sockaddr_in_is_ip6, Int32, (Ptr{Void},), sockaddr) == 1 - # host = Vector{UInt128}(1) - # ccall(:jl_sockaddr_host6, UInt32, (Ptr{Void}, Ptr{UInt128}), sockaddrr, host) - # return IPv6(ntoh(host[1])) - end - end - ccall(:uv_free_interface_addresses, Void, (Ptr{UInt8}, Int32), addr, count) - return lo_present ? ip"127.0.0.1" : error("No networking interface available") -end - -## - -function connect!(sock::TCPSocket, host::IPv4, port::Integer) - if sock.status != StatusInit - error("TCPSocket is not in initialization state") - end - if !(0 <= port <= typemax(UInt16)) - throw(ArgumentError("port out of range, must be 0 ≤ port ≤ 65535, got $port")) - end - uv_error("connect", ccall(:jl_tcp4_connect, Int32, (Ptr{Void}, UInt32, UInt16, Ptr{Void}), - sock.handle, hton(host.host), hton(UInt16(port)), uv_jl_connectcb::Ptr{Void})) - sock.status = StatusConnecting - nothing -end - -function connect!(sock::TCPSocket, host::IPv6, port::Integer) - if sock.status != StatusInit - error("TCPSocket is not in initialization state") - end - if !(0 <= port <= typemax(UInt16)) - throw(ArgumentError("port out of range, must be 0 ≤ port ≤ 65535, got $port")) - end - uv_error("connect", ccall(:jl_tcp6_connect, Int32, (Ptr{Void}, Ptr{UInt128}, UInt16, Ptr{Void}), - sock.handle, &hton(host.host), hton(UInt16(port)), uv_jl_connectcb::Ptr{Void})) - sock.status = StatusConnecting - nothing -end - -connect!(sock::TCPSocket, addr::InetAddr) = connect!(sock, addr.host, addr.port) - -# Default Host to localhost - -""" - connect([host], port::Integer) -> TCPSocket - -Connect to the host `host` on port `port`. -""" -connect(sock::TCPSocket, port::Integer) = connect(sock,IPv4(127,0,0,1), port) -connect(port::Integer) = connect(IPv4(127,0,0,1), port) - -# Valid connect signatures for TCP -connect(host::AbstractString, port::Integer) = connect(TCPSocket(), host, port) -connect(addr::IPAddr, port::Integer) = connect(TCPSocket(), addr, port) -connect(addr::InetAddr) = connect(TCPSocket(), addr) - -default_connectcb(sock,status) = nothing - -function connect!(sock::TCPSocket, host::AbstractString, port::Integer) - if sock.status != StatusInit - error("TCPSocket is not in initialization state") - end - ipaddr = getaddrinfo(host) - sock.status = StatusInit - connect!(sock,ipaddr,port) - sock.status = StatusConnecting - return sock -end - -## - -""" - listen([addr, ]port::Integer; backlog::Integer=BACKLOG_DEFAULT) -> TCPServer - -Listen on port on the address specified by `addr`. -By default this listens on `localhost` only. -To listen on all interfaces pass `IPv4(0)` or `IPv6(0)` as appropriate. -`backlog` determines how many connections can be pending (not having -called [`accept`](@ref)) before the server will begin to -reject them. The default value of `backlog` is 511. -""" -function listen(addr; backlog::Integer=BACKLOG_DEFAULT) - sock = TCPServer() - !bind(sock, addr) && error("cannot bind to port; may already be in use or access denied") - listen(sock; backlog=backlog) - return sock -end -listen(port::Integer; backlog::Integer=BACKLOG_DEFAULT) = listen(IPv4(UInt32(0)), port; backlog=backlog) -listen(host::IPAddr, port::Integer; backlog::Integer=BACKLOG_DEFAULT) = listen(InetAddr(host, port); backlog=backlog) - -function listen(callback, server::Union{TCPSocket, UDPSocket}) - @async begin - local client = TCPSocket() - while isopen(server) - err = accept_nonblock(server, client) - if err == 0 - callback(client) - client = TCPSocket() - elseif err != UV_EAGAIN - uv_error("accept", err) - else - stream_wait(server, server.connectnotify) - end - end - end - return sock -end - -## - -function accept_nonblock(server::TCPServer, client::TCPSocket) - if client.status != StatusInit - error("client TCPSocket is not in initialization state") - end - err = ccall(:uv_accept, Int32, (Ptr{Void}, Ptr{Void}), server.handle, client.handle) - if err == 0 - client.status = StatusOpen - end - return err -end - -function accept_nonblock(server::TCPServer) - client = TCPSocket() - uv_error("accept", accept_nonblock(server, client)) - return client -end - -## Utility functions - -""" - listenany([host::IPAddr,] port_hint) -> (UInt16, TCPServer) - -Create a `TCPServer` on any port, using hint as a starting point. Returns a tuple of the -actual port that the server was created on and the server itself. -""" -function listenany(host::IPAddr, default_port) - addr = InetAddr(host, default_port) - while true - sock = TCPServer() - if bind(sock, addr) && trylisten(sock) == 0 - if default_port == 0 - _addr, port = _sockname(sock, true) - return (port, sock) - end - return (addr.port, sock) - end - close(sock) - addr = InetAddr(addr.host, addr.port + 1) - if addr.port == default_port - error("no ports available") - end - end -end - -listenany(default_port) = listenany(IPv4(UInt32(0)), default_port) - -""" - getsockname(sock::Union{TCPServer, TCPSocket}) -> (IPAddr, UInt16) - -Get the IP address and the port that the given `TCPSocket` is connected to -(or bound to, in the case of `TCPServer`). -""" -getsockname(sock::Union{TCPServer, TCPSocket}) = _sockname(sock, isa(sock, TCPServer)) - -function _sockname(sock, self) - rport = Ref{Cushort}(0) - raddress = zeros(UInt8, 16) - rfamily = Ref{Cuint}(0) - if self - r = ccall(:jl_tcp_getsockname, Int32, - (Ptr{Void}, Ref{Cushort}, Ptr{Void}, Ref{Cuint}), - sock.handle, rport, raddress, rfamily) - else - r = ccall(:jl_tcp_getpeername, Int32, - (Ptr{Void}, Ref{Cushort}, Ptr{Void}, Ref{Cuint}), - sock.handle, rport, raddress, rfamily) - end - uv_error("cannot obtain socket name", r) - if r == 0 - port = ntoh(rport[]) - af_inet6 = @static if is_windows() # AF_INET6 in <sys/socket.h> - 23 - elseif is_apple() - 30 - elseif Sys.KERNEL ∈ (:FreeBSD, :DragonFly) - 28 - elseif Sys.KERNEL ∈ (:NetBSD, :OpenBSD) - 24 - else - 10 - end - - if rfamily[] == 2 # AF_INET - addrv4 = raddress[1:4] - naddr = ntoh(unsafe_load(Ptr{Cuint}(pointer(addrv4)), 1)) - addr = IPv4(naddr) - elseif rfamily[] == af_inet6 - naddr = ntoh(unsafe_load(Ptr{UInt128}(pointer(raddress)), 1)) - addr = IPv6(naddr) - else - error("unsupported address family: $(getindex(rfamily))") - end - else - error("cannot obtain socket name") - end - return addr, port -end diff --git a/julia-0.6.3/share/julia/base/sort.jl b/julia-0.6.3/share/julia/base/sort.jl deleted file mode 100644 index cc71c26..0000000 --- a/julia-0.6.3/share/julia/base/sort.jl +++ /dev/null @@ -1,931 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -module Sort - -using Base: Order, Checked, copymutable, linearindices, IndexStyle, viewindexing, IndexLinear, _length - -import - Base.sort, - Base.sort!, - Base.issorted, - Base.sortperm, - Base.Slice, - Base.to_indices - -export # also exported by Base - # order-only: - issorted, - select, - select!, - searchsorted, - searchsortedfirst, - searchsortedlast, - # order & algorithm: - sort, - sort!, - selectperm, - selectperm!, - sortperm, - sortperm!, - sortrows, - sortcols, - # algorithms: - InsertionSort, - QuickSort, - MergeSort, - PartialQuickSort - -export # not exported by Base - Algorithm, - DEFAULT_UNSTABLE, - DEFAULT_STABLE, - SMALL_ALGORITHM, - SMALL_THRESHOLD - - -## functions requiring only ordering ## - -function issorted(itr, order::Ordering) - state = start(itr) - done(itr,state) && return true - prev, state = next(itr, state) - while !done(itr, state) - this, state = next(itr, state) - lt(order, this, prev) && return false - prev = this - end - return true -end - -""" - issorted(v, lt=isless, by=identity, rev:Bool=false, order::Ordering=Forward) - -Test whether a vector is in sorted order. The `lt`, `by` and `rev` keywords modify what -order is considered to be sorted just as they do for [`sort`](@ref). - -# Examples -```jldoctest -julia> issorted([1, 2, 3]) -true - -julia> issorted([(1, "b"), (2, "a")], by = x -> x[1]) -true - -julia> issorted([(1, "b"), (2, "a")], by = x -> x[2]) -false - -julia> issorted([(1, "b"), (2, "a")], by = x -> x[2], rev=true) -true -``` -""" -issorted(itr; - lt=isless, by=identity, rev::Bool=false, order::Ordering=Forward) = - issorted(itr, ord(lt,by,rev,order)) - -function select!(v::AbstractVector, k::Union{Int,OrdinalRange}, o::Ordering) - inds = indices(v, 1) - sort!(v, first(inds), last(inds), PartialQuickSort(k), o) - v[k] -end -select!(v::AbstractVector, k::Union{Int,OrdinalRange}; - lt=isless, by=identity, rev::Bool=false, order::Ordering=Forward) = - select!(v, k, ord(lt,by,rev,order)) - -select(v::AbstractVector, k::Union{Int,OrdinalRange}; kws...) = select!(copymutable(v), k; kws...) - - -# reference on sorted binary search: -# http://www.tbray.org/ongoing/When/200x/2003/03/22/Binary - -# index of the first value of vector a that is greater than or equal to x; -# returns length(v)+1 if x is greater than all values in v. -function searchsortedfirst(v::AbstractVector, x, lo::Int, hi::Int, o::Ordering) - lo = lo-1 - hi = hi+1 - @inbounds while lo < hi-1 - m = (lo+hi)>>>1 - if lt(o, v[m], x) - lo = m - else - hi = m - end - end - return hi -end - -# index of the last value of vector a that is less than or equal to x; -# returns 0 if x is less than all values of v. -function searchsortedlast(v::AbstractVector, x, lo::Int, hi::Int, o::Ordering) - lo = lo-1 - hi = hi+1 - @inbounds while lo < hi-1 - m = (lo+hi)>>>1 - if lt(o, x, v[m]) - hi = m - else - lo = m - end - end - return lo -end - -# returns the range of indices of v equal to x -# if v does not contain x, returns a 0-length range -# indicating the insertion point of x -function searchsorted(v::AbstractVector, x, ilo::Int, ihi::Int, o::Ordering) - lo = ilo-1 - hi = ihi+1 - @inbounds while lo < hi-1 - m = (lo+hi)>>>1 - if lt(o, v[m], x) - lo = m - elseif lt(o, x, v[m]) - hi = m - else - a = searchsortedfirst(v, x, max(lo,ilo), m, o) - b = searchsortedlast(v, x, m, min(hi,ihi), o) - return a : b - end - end - return (lo + 1) : (hi - 1) -end - -function searchsortedlast(a::Range{<:Real}, x::Real, o::DirectOrdering) - if step(a) == 0 - lt(o, x, first(a)) ? 0 : length(a) - else - n = round(Integer, clamp((x - first(a)) / step(a) + 1, 1, length(a))) - lt(o, x, a[n]) ? n - 1 : n - end -end - -function searchsortedfirst(a::Range{<:Real}, x::Real, o::DirectOrdering) - if step(a) == 0 - lt(o, first(a), x) ? length(a) + 1 : 1 - else - n = round(Integer, clamp((x - first(a)) / step(a) + 1, 1, length(a))) - lt(o, a[n] ,x) ? n + 1 : n - end -end - -function searchsortedlast(a::Range{<:Integer}, x::Real, o::DirectOrdering) - if step(a) == 0 - lt(o, x, first(a)) ? 0 : length(a) - else - clamp( fld(floor(Integer, x) - first(a), step(a)) + 1, 0, length(a)) - end -end - -function searchsortedfirst(a::Range{<:Integer}, x::Real, o::DirectOrdering) - if step(a) == 0 - lt(o, first(a), x) ? length(a)+1 : 1 - else - clamp(-fld(floor(Integer, -x) + first(a), step(a)) + 1, 1, length(a) + 1) - end -end - -function searchsortedfirst(a::Range{<:Integer}, x::Unsigned, o::DirectOrdering) - if lt(o, first(a), x) - if step(a) == 0 - length(a) + 1 - else - min(cld(x - first(a), step(a)), length(a)) + 1 - end - else - 1 - end -end - -function searchsortedlast(a::Range{<:Integer}, x::Unsigned, o::DirectOrdering) - if lt(o, x, first(a)) - 0 - elseif step(a) == 0 - length(a) - else - min(fld(x - first(a), step(a)) + 1, length(a)) - end -end - -searchsorted(a::Range{<:Real}, x::Real, o::DirectOrdering) = - searchsortedfirst(a, x, o) : searchsortedlast(a, x, o) - -for s in [:searchsortedfirst, :searchsortedlast, :searchsorted] - @eval begin - $s(v::AbstractVector, x, o::Ordering) = (inds = indices(v, 1); $s(v,x,first(inds),last(inds),o)) - $s(v::AbstractVector, x; - lt=isless, by=identity, rev::Bool=false, order::Ordering=Forward) = - $s(v,x,ord(lt,by,rev,order)) - $s(v::AbstractVector, x) = $s(v, x, Forward) - end -end - -## sorting algorithms ## - -abstract type Algorithm end - -struct InsertionSortAlg <: Algorithm end -struct QuickSortAlg <: Algorithm end -struct MergeSortAlg <: Algorithm end - -struct PartialQuickSort{T <: Union{Int,OrdinalRange}} <: Algorithm - k::T -end - -Base.first(a::PartialQuickSort{Int}) = 1 -Base.last(a::PartialQuickSort{Int}) = a.k -Base.first(a::PartialQuickSort) = first(a.k) -Base.last(a::PartialQuickSort) = last(a.k) - -const InsertionSort = InsertionSortAlg() -const QuickSort = QuickSortAlg() -const MergeSort = MergeSortAlg() - -const DEFAULT_UNSTABLE = QuickSort -const DEFAULT_STABLE = MergeSort -const SMALL_ALGORITHM = InsertionSort -const SMALL_THRESHOLD = 20 - -function sort!(v::AbstractVector, lo::Int, hi::Int, ::InsertionSortAlg, o::Ordering) - @inbounds for i = lo+1:hi - j = i - x = v[i] - while j > lo - if lt(o, x, v[j-1]) - v[j] = v[j-1] - j -= 1 - continue - end - break - end - v[j] = x - end - return v -end - -# selectpivot! -# -# Given 3 locations in an array (lo, mi, and hi), sort v[lo], v[mi], v[hi]) and -# choose the middle value as a pivot -# -# Upon return, the pivot is in v[lo], and v[hi] is guaranteed to be -# greater than the pivot - -@inline function selectpivot!(v::AbstractVector, lo::Int, hi::Int, o::Ordering) - @inbounds begin - mi = (lo+hi)>>>1 - - # sort the values in v[lo], v[mi], v[hi] - - if lt(o, v[mi], v[lo]) - v[mi], v[lo] = v[lo], v[mi] - end - if lt(o, v[hi], v[mi]) - if lt(o, v[hi], v[lo]) - v[lo], v[mi], v[hi] = v[hi], v[lo], v[mi] - else - v[hi], v[mi] = v[mi], v[hi] - end - end - - # move v[mi] to v[lo] and use it as the pivot - v[lo], v[mi] = v[mi], v[lo] - pivot = v[lo] - end - - # return the pivot - return pivot -end - -# partition! -# -# select a pivot, and partition v according to the pivot - -function partition!(v::AbstractVector, lo::Int, hi::Int, o::Ordering) - pivot = selectpivot!(v, lo, hi, o) - # pivot == v[lo], v[hi] > pivot - i, j = lo, hi - @inbounds while true - i += 1; j -= 1 - while lt(o, v[i], pivot); i += 1; end; - while lt(o, pivot, v[j]); j -= 1; end; - i >= j && break - v[i], v[j] = v[j], v[i] - end - v[j], v[lo] = pivot, v[j] - - # v[j] == pivot - # v[k] >= pivot for k > j - # v[i] <= pivot for i < j - return j -end - -function sort!(v::AbstractVector, lo::Int, hi::Int, a::QuickSortAlg, o::Ordering) - @inbounds while lo < hi - hi-lo <= SMALL_THRESHOLD && return sort!(v, lo, hi, SMALL_ALGORITHM, o) - j = partition!(v, lo, hi, o) - if j-lo < hi-j - # recurse on the smaller chunk - # this is necessary to preserve O(log(n)) - # stack space in the worst case (rather than O(n)) - lo < (j-1) && sort!(v, lo, j-1, a, o) - lo = j+1 - else - j+1 < hi && sort!(v, j+1, hi, a, o) - hi = j-1 - end - end - return v -end - -function sort!(v::AbstractVector, lo::Int, hi::Int, a::MergeSortAlg, o::Ordering, t=similar(v,0)) - @inbounds if lo < hi - hi-lo <= SMALL_THRESHOLD && return sort!(v, lo, hi, SMALL_ALGORITHM, o) - - m = (lo+hi)>>>1 - (length(t) < m-lo+1) && resize!(t, m-lo+1) - - sort!(v, lo, m, a, o, t) - sort!(v, m+1, hi, a, o, t) - - i, j = 1, lo - while j <= m - t[i] = v[j] - i += 1 - j += 1 - end - - i, k = 1, lo - while k < j <= hi - if lt(o, v[j], t[i]) - v[k] = v[j] - j += 1 - else - v[k] = t[i] - i += 1 - end - k += 1 - end - while k < j - v[k] = t[i] - k += 1 - i += 1 - end - end - - return v -end - -## TODO: When PartialQuickSort is parameterized by an Int, this version of sort -## has one less comparison per loop than the version below, but enabling -## it causes return type inference to fail for sort/sort! (#12833) -## -# function sort!(v::AbstractVector, lo::Int, hi::Int, a::PartialQuickSort{Int}, -# o::Ordering) -# @inbounds while lo < hi -# hi-lo <= SMALL_THRESHOLD && return sort!(v, lo, hi, SMALL_ALGORITHM, o) -# j = partition!(v, lo, hi, o) -# if j >= a.k -# # we don't need to sort anything bigger than j -# hi = j-1 -# elseif j-lo < hi-j -# # recurse on the smaller chunk -# # this is necessary to preserve O(log(n)) -# # stack space in the worst case (rather than O(n)) -# lo < (j-1) && sort!(v, lo, j-1, a, o) -# lo = j+1 -# else -# (j+1) < hi && sort!(v, j+1, hi, a, o) -# hi = j-1 -# end -# end -# return v -# end - - -function sort!(v::AbstractVector, lo::Int, hi::Int, a::PartialQuickSort, - o::Ordering) - @inbounds while lo < hi - hi-lo <= SMALL_THRESHOLD && return sort!(v, lo, hi, SMALL_ALGORITHM, o) - j = partition!(v, lo, hi, o) - - if j <= first(a) - lo = j+1 - elseif j >= last(a) - hi = j-1 - else - if j-lo < hi-j - lo < (j-1) && sort!(v, lo, j-1, a, o) - lo = j+1 - else - hi > (j+1) && sort!(v, j+1, hi, a, o) - hi = j-1 - end - end - end - return v -end - - -## generic sorting methods ## - -defalg(v::AbstractArray) = DEFAULT_STABLE -defalg(v::AbstractArray{<:Number}) = DEFAULT_UNSTABLE - -function sort!(v::AbstractVector, alg::Algorithm, order::Ordering) - inds = indices(v,1) - sort!(v,first(inds),last(inds),alg,order) -end - -""" - sort!(v; alg::Algorithm=defalg(v), lt=isless, by=identity, rev::Bool=false, order::Ordering=Forward) - -Sort the vector `v` in place. `QuickSort` is used by default for numeric arrays while -`MergeSort` is used for other arrays. You can specify an algorithm to use via the `alg` -keyword (see Sorting Algorithms for available algorithms). The `by` keyword lets you provide -a function that will be applied to each element before comparison; the `lt` keyword allows -providing a custom "less than" function; use `rev=true` to reverse the sorting order. These -options are independent and can be used together in all possible combinations: if both `by` -and `lt` are specified, the `lt` function is applied to the result of the `by` function; -`rev=true` reverses whatever ordering specified via the `by` and `lt` keywords. - -# Examples - -```jldoctest -julia> v = [3, 1, 2]; sort!(v); v -3-element Array{Int64,1}: - 1 - 2 - 3 - -julia> v = [3, 1, 2]; sort!(v, rev = true); v -3-element Array{Int64,1}: - 3 - 2 - 1 - -julia> v = [(1, "c"), (3, "a"), (2, "b")]; sort!(v, by = x -> x[1]); v -3-element Array{Tuple{Int64,String},1}: - (1, "c") - (2, "b") - (3, "a") - -julia> v = [(1, "c"), (3, "a"), (2, "b")]; sort!(v, by = x -> x[2]); v -3-element Array{Tuple{Int64,String},1}: - (3, "a") - (2, "b") - (1, "c") -``` -""" -function sort!(v::AbstractVector; - alg::Algorithm=defalg(v), - lt=isless, - by=identity, - rev::Bool=false, - order::Ordering=Forward) - ordr = ord(lt,by,rev,order) - if ordr === Forward && isa(v,Vector) && eltype(v)<:Integer - n = _length(v) - if n > 1 - min, max = extrema(v) - (diff, o1) = sub_with_overflow(max, min) - (rangelen, o2) = add_with_overflow(diff, oneunit(diff)) - if !o1 && !o2 && rangelen < div(n,2) - return sort_int_range!(v, rangelen, min) - end - end - end - sort!(v, alg, ordr) -end - -# sort! for vectors of few unique integers -function sort_int_range!(x::Vector{<:Integer}, rangelen, minval) - offs = 1 - minval - n = length(x) - - where = fill(0, rangelen) - @inbounds for i = 1:n - where[x[i] + offs] += 1 - end - - idx = 1 - @inbounds for i = 1:rangelen - lastidx = idx + where[i] - 1 - val = i-offs - for j = idx:lastidx - x[j] = val - end - idx = lastidx + 1 - end - - return x -end - -""" - sort(v; alg::Algorithm=defalg(v), lt=isless, by=identity, rev::Bool=false, order::Ordering=Forward) - -Variant of [`sort!`](@ref) that returns a sorted copy of `v` leaving `v` itself unmodified. - -# Examples - -```jldoctest -julia> v = [3, 1, 2]; - -julia> sort(v) -3-element Array{Int64,1}: - 1 - 2 - 3 - -julia> v -3-element Array{Int64,1}: - 3 - 1 - 2 -``` -""" -sort(v::AbstractVector; kws...) = sort!(copymutable(v); kws...) - -## selectperm: the permutation to sort the first k elements of an array ## - -selectperm(v::AbstractVector, k::Union{Integer,OrdinalRange}; kwargs...) = - selectperm!(similar(Vector{eltype(k)}, indices(v,1)), v, k; kwargs..., initialized=false) - -function selectperm!(ix::AbstractVector{<:Integer}, v::AbstractVector, - k::Union{Int, OrdinalRange}; - lt::Function=isless, - by::Function=identity, - rev::Bool=false, - order::Ordering=Forward, - initialized::Bool=false) - if !initialized - @inbounds for i = indices(ix,1) - ix[i] = i - end - end - - # do partial quicksort - sort!(ix, PartialQuickSort(k), Perm(ord(lt, by, rev, order), v)) - return ix[k] -end - -## sortperm: the permutation to sort an array ## - -""" - sortperm(v; alg::Algorithm=DEFAULT_UNSTABLE, lt=isless, by=identity, rev::Bool=false, order::Ordering=Forward) - -Return a permutation vector of indices of `v` that puts it in sorted order. Specify `alg` to -choose a particular sorting algorithm (see Sorting Algorithms). `MergeSort` is used by -default, and since it is stable, the resulting permutation will be the lexicographically -first one that puts the input array into sorted order – i.e. indices of equal elements -appear in ascending order. If you choose a non-stable sorting algorithm such as `QuickSort`, -a different permutation that puts the array into order may be returned. The order is -specified using the same keywords as `sort!`. - -See also [`sortperm!`](@ref). - -# Examples - -```jldoctest -julia> v = [3, 1, 2]; - -julia> p = sortperm(v) -3-element Array{Int64,1}: - 2 - 3 - 1 - -julia> v[p] -3-element Array{Int64,1}: - 1 - 2 - 3 -``` -""" -function sortperm(v::AbstractVector; - alg::Algorithm=DEFAULT_UNSTABLE, - lt=isless, - by=identity, - rev::Bool=false, - order::Ordering=Forward) - ordr = ord(lt,by,rev,order) - if ordr === Forward && isa(v,Vector) && eltype(v)<:Integer - n = _length(v) - if n > 1 - min, max = extrema(v) - (diff, o1) = sub_with_overflow(max, min) - (rangelen, o2) = add_with_overflow(diff, oneunit(diff)) - if !o1 && !o2 && rangelen < div(n,2) - return sortperm_int_range(v, rangelen, min) - end - end - end - p = similar(Vector{Int}, indices(v, 1)) - for (i,ind) in zip(eachindex(p), indices(v, 1)) - p[i] = ind - end - sort!(p, alg, Perm(ordr,v)) -end - - -""" - sortperm!(ix, v; alg::Algorithm=DEFAULT_UNSTABLE, lt=isless, by=identity, rev::Bool=false, order::Ordering=Forward, initialized::Bool=false) - -Like [`sortperm`](@ref), but accepts a preallocated index vector `ix`. If `initialized` is `false` -(the default), `ix` is initialized to contain the values `1:length(v)`. - -# Examples - -```jldoctest -julia> v = [3, 1, 2]; p = zeros(Int, 3); - -julia> sortperm!(p, v); p -3-element Array{Int64,1}: - 2 - 3 - 1 - -julia> v[p] -3-element Array{Int64,1}: - 1 - 2 - 3 -``` -""" -function sortperm!(x::AbstractVector{<:Integer}, v::AbstractVector; - alg::Algorithm=DEFAULT_UNSTABLE, - lt=isless, - by=identity, - rev::Bool=false, - order::Ordering=Forward, - initialized::Bool=false) - if indices(x,1) != indices(v,1) - throw(ArgumentError("index vector must have the same indices as the source vector, $(indices(x,1)) != $(indices(v,1))")) - end - if !initialized - @inbounds for i = indices(v,1) - x[i] = i - end - end - sort!(x, alg, Perm(ord(lt,by,rev,order),v)) -end - -# sortperm for vectors of few unique integers -function sortperm_int_range(x::Vector{<:Integer}, rangelen, minval) - offs = 1 - minval - n = length(x) - - where = fill(0, rangelen+1) - where[1] = 1 - @inbounds for i = 1:n - where[x[i] + offs + 1] += 1 - end - cumsum!(where, where) - - P = Vector{Int}(n) - @inbounds for i = 1:n - label = x[i] + offs - P[where[label]] = i - where[label] += 1 - end - - return P -end - -## sorting multi-dimensional arrays ## - -""" - sort(A, dim::Integer; alg::Algorithm=DEFAULT_UNSTABLE, lt=isless, by=identity, rev::Bool=false, order::Ordering=Forward, initialized::Bool=false) - -Sort a multidimensional array `A` along the given dimension. -See [`sort!`](@ref) for a description of possible -keyword arguments. - -# Examples - -```jldoctest -julia> A = [4 3; 1 2] -2×2 Array{Int64,2}: - 4 3 - 1 2 - -julia> sort(A, 1) -2×2 Array{Int64,2}: - 1 2 - 4 3 - -julia> sort(A, 2) -2×2 Array{Int64,2}: - 3 4 - 1 2 -``` -""" -function sort(A::AbstractArray, dim::Integer; - alg::Algorithm=DEFAULT_UNSTABLE, - lt=isless, - by=identity, - rev::Bool=false, - order::Ordering=Forward, - initialized::Bool=false) - order = ord(lt,by,rev,order) - n = length(indices(A, dim)) - if dim != 1 - pdims = (dim, setdiff(1:ndims(A), dim)...) # put the selected dimension first - Ap = permutedims(A, pdims) - Av = vec(Ap) - sort_chunks!(Av, n, alg, order) - permutedims(Ap, invperm(pdims)) - else - Av = A[:] - sort_chunks!(Av, n, alg, order) - reshape(Av, indices(A)) - end -end - -@noinline function sort_chunks!(Av, n, alg, order) - inds = linearindices(Av) - for s = first(inds):n:last(inds) - sort!(Av, s, s+n-1, alg, order) - end - Av -end - - -""" - sortrows(A; alg::Algorithm=DEFAULT_UNSTABLE, lt=isless, by=identity, rev::Bool=false, order::Ordering=Forward) - -Sort the rows of matrix `A` lexicographically. -See [`sort!`](@ref) for a description of possible -keyword arguments. - -# Examples - -```jldoctest -julia> sortrows([7 3 5; -1 6 4; 9 -2 8]) -3×3 Array{Int64,2}: - -1 6 4 - 7 3 5 - 9 -2 8 - -julia> sortrows([7 3 5; -1 6 4; 9 -2 8], lt=(x,y)->isless(x[2],y[2])) -3×3 Array{Int64,2}: - 9 -2 8 - 7 3 5 - -1 6 4 - -julia> sortrows([7 3 5; -1 6 4; 9 -2 8], rev=true) -3×3 Array{Int64,2}: - 9 -2 8 - 7 3 5 - -1 6 4 -``` -""" -function sortrows(A::AbstractMatrix; kws...) - inds = indices(A,1) - T = slicetypeof(A, inds, :) - rows = similar(Vector{T}, indices(A, 1)) - for i in inds - rows[i] = view(A, i, :) - end - p = sortperm(rows; kws..., order=Lexicographic) - A[p,:] -end - -""" - sortcols(A; alg::Algorithm=DEFAULT_UNSTABLE, lt=isless, by=identity, rev::Bool=false, order::Ordering=Forward) - -Sort the columns of matrix `A` lexicographically. -See [`sort!`](@ref) for a description of possible -keyword arguments. - -# Examples - -```jldoctest -julia> sortcols([7 3 5; 6 -1 -4; 9 -2 8]) -3×3 Array{Int64,2}: - 3 5 7 - -1 -4 6 - -2 8 9 - -julia> sortcols([7 3 5; 6 -1 -4; 9 -2 8], alg=InsertionSort, lt=(x,y)->isless(x[2],y[2])) -3×3 Array{Int64,2}: - 5 3 7 - -4 -1 6 - 8 -2 9 - -julia> sortcols([7 3 5; 6 -1 -4; 9 -2 8], rev=true) -3×3 Array{Int64,2}: - 7 5 3 - 6 -4 -1 - 9 8 -2 -``` -""" -function sortcols(A::AbstractMatrix; kws...) - inds = indices(A,2) - T = slicetypeof(A, :, inds) - cols = similar(Vector{T}, indices(A, 2)) - for i in inds - cols[i] = view(A, :, i) - end - p = sortperm(cols; kws..., order=Lexicographic) - A[:,p] -end - -function slicetypeof(A::AbstractArray{T}, i1, i2) where T - I = map(slice_dummy, to_indices(A, (i1, i2))) - fast = isa(IndexStyle(viewindexing(I), IndexStyle(A)), IndexLinear) - SubArray{T,1,typeof(A),typeof(I),fast} -end -slice_dummy(S::Slice) = S -slice_dummy(::AbstractUnitRange{T}) where {T} = oneunit(T) - -## fast clever sorting for floats ## - -module Float -using ..Sort -using ...Order - -import Core.Intrinsics: slt_int -import ..Sort: sort! -import ...Order: lt, DirectOrdering - -const Floats = Union{Float32,Float64} - -struct Left <: Ordering end -struct Right <: Ordering end - -left(::DirectOrdering) = Left() -right(::DirectOrdering) = Right() - -left(o::Perm) = Perm(left(o.order), o.data) -right(o::Perm) = Perm(right(o.order), o.data) - -lt(::Left, x::T, y::T) where {T<:Floats} = slt_int(y, x) -lt(::Right, x::T, y::T) where {T<:Floats} = slt_int(x, y) - -isnan(o::DirectOrdering, x::Floats) = (x!=x) -isnan(o::Perm, i::Int) = isnan(o.order,o.data[i]) - -function nans2left!(v::AbstractVector, o::Ordering, lo::Int=first(indices(v,1)), hi::Int=last(indices(v,1))) - i = lo - @inbounds while i <= hi && isnan(o,v[i]) - i += 1 - end - j = i + 1 - @inbounds while j <= hi - if isnan(o,v[j]) - v[i], v[j] = v[j], v[i] - i += 1 - end - j += 1 - end - return i, hi -end -function nans2right!(v::AbstractVector, o::Ordering, lo::Int=first(indices(v,1)), hi::Int=last(indices(v,1))) - i = hi - @inbounds while lo <= i && isnan(o,v[i]) - i -= 1 - end - j = i - 1 - @inbounds while lo <= j - if isnan(o,v[j]) - v[i], v[j] = v[j], v[i] - i -= 1 - end - j -= 1 - end - return lo, i -end - -nans2end!(v::AbstractVector, o::ForwardOrdering) = nans2right!(v,o) -nans2end!(v::AbstractVector, o::ReverseOrdering) = nans2left!(v,o) -nans2end!(v::AbstractVector{Int}, o::Perm{<:ForwardOrdering}) = nans2right!(v,o) -nans2end!(v::AbstractVector{Int}, o::Perm{<:ReverseOrdering}) = nans2left!(v,o) - -issignleft(o::ForwardOrdering, x::Floats) = lt(o, x, zero(x)) -issignleft(o::ReverseOrdering, x::Floats) = lt(o, x, -zero(x)) -issignleft(o::Perm, i::Int) = issignleft(o.order, o.data[i]) - -function fpsort!(v::AbstractVector, a::Algorithm, o::Ordering) - i, j = lo, hi = nans2end!(v,o) - @inbounds while true - while i <= j && issignleft(o,v[i]); i += 1; end - while i <= j && !issignleft(o,v[j]); j -= 1; end - i <= j || break - v[i], v[j] = v[j], v[i] - i += 1; j -= 1 - end - sort!(v, lo, j, a, left(o)) - sort!(v, i, hi, a, right(o)) - return v -end - - -fpsort!(v::AbstractVector, a::Sort.PartialQuickSort, o::Ordering) = - sort!(v, first(indices(v,1)), last(indices(v,1)), a, o) - -sort!(v::AbstractVector{<:Floats}, a::Algorithm, o::DirectOrdering) = fpsort!(v,a,o) -sort!(v::Vector{Int}, a::Algorithm, o::Perm{<:DirectOrdering,<:Vector{<:Floats}}) = fpsort!(v,a,o) - -end # module Sort.Float - -end # module Sort diff --git a/julia-0.6.3/share/julia/base/sparse/abstractsparse.jl b/julia-0.6.3/share/julia/base/sparse/abstractsparse.jl deleted file mode 100644 index e17d3be..0000000 --- a/julia-0.6.3/share/julia/base/sparse/abstractsparse.jl +++ /dev/null @@ -1,23 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -abstract type AbstractSparseArray{Tv,Ti,N} <: AbstractArray{Tv,N} end - -const AbstractSparseVector{Tv,Ti} = AbstractSparseArray{Tv,Ti,1} -const AbstractSparseMatrix{Tv,Ti} = AbstractSparseArray{Tv,Ti,2} - -""" - issparse(S) - -Returns `true` if `S` is sparse, and `false` otherwise. -""" -issparse(A::AbstractArray) = false -issparse(S::AbstractSparseArray) = true - -issparse(S::Symmetric{<:Any,<:AbstractSparseMatrix}) = true -issparse(S::Hermitian{<:Any,<:AbstractSparseMatrix}) = true -issparse(S::LowerTriangular{<:Any,<:AbstractSparseMatrix}) = true -issparse(S::LinAlg.UnitLowerTriangular{<:Any,<:AbstractSparseMatrix}) = true -issparse(S::UpperTriangular{<:Any,<:AbstractSparseMatrix}) = true -issparse(S::LinAlg.UnitUpperTriangular{<:Any,<:AbstractSparseMatrix}) = true - -indtype(S::AbstractSparseArray{<:Any,Ti}) where {Ti} = Ti diff --git a/julia-0.6.3/share/julia/base/sparse/cholmod.jl b/julia-0.6.3/share/julia/base/sparse/cholmod.jl deleted file mode 100644 index 9ea5bd3..0000000 --- a/julia-0.6.3/share/julia/base/sparse/cholmod.jl +++ /dev/null @@ -1,1725 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -module CHOLMOD - -import Base: (*), convert, copy, eltype, get, getindex, show, size, - IndexStyle, IndexLinear, IndexCartesian, ctranspose - -import Base.LinAlg: (\), A_mul_Bc, A_mul_Bt, Ac_ldiv_B, Ac_mul_B, At_ldiv_B, At_mul_B, - cholfact, cholfact!, det, diag, ishermitian, isposdef, - issymmetric, ldltfact, ldltfact!, logdet - -importall ..SparseArrays - -export - Dense, - Factor, - Sparse - -import ..SparseArrays: AbstractSparseMatrix, SparseMatrixCSC, increment, indtype - -######### -# Setup # -######### - -include("cholmod_h.jl") - -const CHOLMOD_MIN_VERSION = v"2.1.1" - -### These offsets are defined in SuiteSparse_wrapper.c -const common_size = ccall((:jl_cholmod_common_size,:libsuitesparse_wrapper),Int,()) - -const cholmod_com_offsets = Vector{Csize_t}(19) -ccall((:jl_cholmod_common_offsets, :libsuitesparse_wrapper), - Void, (Ptr{Csize_t},), cholmod_com_offsets) - -## macro to generate the name of the C function according to the integer type -macro cholmod_name(nm, typ) - string("cholmod_", eval(typ) == SuiteSparse_long ? "l_" : "", nm) -end - -function start(a::Vector{UInt8}) - @isok ccall((@cholmod_name("start", SuiteSparse_long), :libcholmod), - Cint, (Ptr{UInt8},), a) - return a -end - -function finish(a::Vector{UInt8}) - @isok ccall((@cholmod_name("finish", SuiteSparse_long), :libcholmod), - Cint, (Ptr{UInt8},), a) - return a -end - -function defaults(a::Vector{UInt8}) - @isok ccall((@cholmod_name("defaults", SuiteSparse_long), :libcholmod), - Cint, (Ptr{UInt8},), a) - return a -end - -common() = commonStruct - -const build_version_array = Vector{Cint}(3) -ccall((:jl_cholmod_version, :libsuitesparse_wrapper), Cint, (Ptr{Cint},), build_version_array) -const build_version = VersionNumber(build_version_array...) - -function __init__() - try - ### Check if the linked library is compatible with the Julia code - if Libdl.dlsym_e(Libdl.dlopen("libcholmod"), :cholmod_version) != C_NULL - current_version_array = Vector{Cint}(3) - ccall((:cholmod_version, :libcholmod), Cint, (Ptr{Cint},), current_version_array) - current_version = VersionNumber(current_version_array...) - else # CHOLMOD < 2.1.1 does not include cholmod_version() - current_version = v"0.0.0" - end - - - if current_version < CHOLMOD_MIN_VERSION - warn(""" - - CHOLMOD version incompatibility - - Julia was compiled with CHOLMOD version $build_version. It is - currently linked with a version older than - $(CHOLMOD_MIN_VERSION). This might cause Julia to - terminate when working with sparse matrix factorizations, - e.g. solving systems of equations with \\. - - It is recommended that you use Julia with a recent version - of CHOLMOD, or download the generic binaries - from www.julialang.org, which ship with the correct - versions of all dependencies. - """) - elseif build_version_array[1] != current_version_array[1] - warn(""" - - CHOLMOD version incompatibility - - Julia was compiled with CHOLMOD version $build_version. It is - currently linked with version $current_version. - This might cause Julia to terminate when working with - sparse matrix factorizations, e.g. solving systems of - equations with \\. - - It is recommended that you use Julia with the same major - version of CHOLMOD as the one used during the build, or - download the generic binaries from www.julialang.org, - which ship with the correct versions of all dependencies. - """) - end - - intsize = Int(ccall((:jl_cholmod_sizeof_long,:libsuitesparse_wrapper),Csize_t,())) - if intsize != 4length(IndexTypes) - warn(""" - - CHOLMOD integer size incompatibility - - Julia was compiled with a version of CHOLMOD that - supported $(32length(IndexTypes)) bit integers. It is - currently linked with version that supports $(8intsize) - integers. This might cause Julia to terminate when - working with sparse matrix factorizations, e.g. solving - systems of equations with \\. - - This problem can be fixed by modifying the Julia build - configuration or by downloading the OS X or generic - Linux binary from www.julialang.org, which include - the correct versions of all dependencies. - """) - end - - ### Initiate CHOLMOD - ### The common struct. Controls the type of factorization and keeps pointers - ### to temporary memory. - global const commonStruct = fill(0xff, common_size) - - global const common_supernodal = - convert(Ptr{Cint}, pointer(commonStruct, cholmod_com_offsets[4] + 1)) - global const common_final_ll = - convert(Ptr{Cint}, pointer(commonStruct, cholmod_com_offsets[7] + 1)) - global const common_print = - convert(Ptr{Cint}, pointer(commonStruct, cholmod_com_offsets[13] + 1)) - global const common_itype = - convert(Ptr{Cint}, pointer(commonStruct, cholmod_com_offsets[18] + 1)) - global const common_dtype = - convert(Ptr{Cint}, pointer(commonStruct, cholmod_com_offsets[19] + 1)) - global const common_nmethods = - convert(Ptr{Cint}, pointer(commonStruct, cholmod_com_offsets[15] + 1)) - global const common_postorder = - convert(Ptr{Cint}, pointer(commonStruct, cholmod_com_offsets[17] + 1)) - - start(commonStruct) # initializes CHOLMOD - set_print_level(commonStruct, 0) # no printing from CHOLMOD by default - - # Register gc tracked allocator if CHOLMOD is new enough - if current_version >= v"3.0.0" - cnfg = cglobal((:SuiteSparse_config, :libsuitesparseconfig), Ptr{Void}) - unsafe_store!(cnfg, cglobal(:jl_malloc, Ptr{Void}), 1) - unsafe_store!(cnfg, cglobal(:jl_calloc, Ptr{Void}), 2) - unsafe_store!(cnfg, cglobal(:jl_realloc, Ptr{Void}), 3) - unsafe_store!(cnfg, cglobal(:jl_free, Ptr{Void}), 4) - end - - catch ex - Base.showerror_nostdio(ex, - "WARNING: Error during initialization of module CHOLMOD") - end -end - -function set_print_level(cm::Array{UInt8}, lev::Integer) - global common_print - unsafe_store!(common_print, lev) -end - -#################### -# Type definitions # -#################### - -abstract type SuiteSparseStruct end - -# The three core data types for CHOLMOD: Dense, Sparse and Factor. -# CHOLMOD manages the memory, so the Julia versions only wrap a -# pointer to a struct. Therefore finalizers should be registered each -# time a pointer is returned from CHOLMOD. - -# Dense -struct C_Dense{T<:VTypes} <: SuiteSparseStruct - nrow::Csize_t - ncol::Csize_t - nzmax::Csize_t - d::Csize_t - x::Ptr{T} - z::Ptr{Void} - xtype::Cint - dtype::Cint -end - -mutable struct Dense{T<:VTypes} <: DenseMatrix{T} - p::Ptr{C_Dense{T}} -end - -# Sparse -struct C_Sparse{Tv<:VTypes} <: SuiteSparseStruct - nrow::Csize_t - ncol::Csize_t - nzmax::Csize_t - p::Ptr{SuiteSparse_long} - i::Ptr{SuiteSparse_long} - nz::Ptr{SuiteSparse_long} - x::Ptr{Tv} - z::Ptr{Void} - stype::Cint - itype::Cint - xtype::Cint - dtype::Cint - sorted::Cint - packed::Cint -end - -# Corresponds to the exact definition of cholmod_sparse_struct in the library. -# Useful when reading matrices of unknown type from files as in -# cholmod_read_sparse -struct C_SparseVoid <: SuiteSparseStruct - nrow::Csize_t - ncol::Csize_t - nzmax::Csize_t - p::Ptr{Void} - i::Ptr{Void} - nz::Ptr{Void} - x::Ptr{Void} - z::Ptr{Void} - stype::Cint - itype::Cint - xtype::Cint - dtype::Cint - sorted::Cint - packed::Cint -end - -mutable struct Sparse{Tv<:VTypes} <: AbstractSparseMatrix{Tv,SuiteSparse_long} - p::Ptr{C_Sparse{Tv}} - function Sparse{Tv}(p::Ptr{C_Sparse{Tv}}) where Tv<:VTypes - if p == C_NULL - throw(ArgumentError("sparse matrix construction failed for " * - "unknown reasons. Please submit a bug report.")) - end - new(p) - end -end -Sparse(p::Ptr{C_Sparse{Tv}}) where {Tv<:VTypes} = Sparse{Tv}(p) - -# Factor - -if build_version >= v"2.1.0" # CHOLMOD version 2.1.0 or later - struct C_Factor{Tv<:VTypes} <: SuiteSparseStruct - n::Csize_t - minor::Csize_t - Perm::Ptr{SuiteSparse_long} - ColCount::Ptr{SuiteSparse_long} - IPerm::Ptr{SuiteSparse_long} # this pointer was added in verison 2.1.0 - nzmax::Csize_t - p::Ptr{SuiteSparse_long} - i::Ptr{SuiteSparse_long} - x::Ptr{Tv} - z::Ptr{Void} - nz::Ptr{SuiteSparse_long} - next::Ptr{SuiteSparse_long} - prev::Ptr{SuiteSparse_long} - nsuper::Csize_t - ssize::Csize_t - xsize::Csize_t - maxcsize::Csize_t - maxesize::Csize_t - super::Ptr{SuiteSparse_long} - pi::Ptr{SuiteSparse_long} - px::Ptr{SuiteSparse_long} - s::Ptr{SuiteSparse_long} - ordering::Cint - is_ll::Cint - is_super::Cint - is_monotonic::Cint - itype::Cint - xtype::Cint - dtype::Cint - end -else - struct C_Factor{Tv<:VTypes} <: SuiteSparseStruct - n::Csize_t - minor::Csize_t - Perm::Ptr{SuiteSparse_long} - ColCount::Ptr{SuiteSparse_long} - nzmax::Csize_t - p::Ptr{SuiteSparse_long} - i::Ptr{SuiteSparse_long} - x::Ptr{Tv} - z::Ptr{Void} - nz::Ptr{SuiteSparse_long} - next::Ptr{SuiteSparse_long} - prev::Ptr{SuiteSparse_long} - nsuper::Csize_t - ssize::Csize_t - xsize::Csize_t - maxcsize::Csize_t - maxesize::Csize_t - super::Ptr{SuiteSparse_long} - pi::Ptr{SuiteSparse_long} - px::Ptr{SuiteSparse_long} - s::Ptr{SuiteSparse_long} - ordering::Cint - is_ll::Cint - is_super::Cint - is_monotonic::Cint - itype::Cint - xtype::Cint - dtype::Cint - end -end - -mutable struct Factor{Tv} <: Factorization{Tv} - p::Ptr{C_Factor{Tv}} - function Factor{Tv}(p::Ptr{C_Factor{Tv}}) where Tv - if p == C_NULL - throw(ArgumentError("factorization construction failed for " * - "unknown reasons. Please submit a bug report.")) - end - new(p) - end -end -Factor(p::Ptr{C_Factor{Tv}}) where {Tv<:VTypes} = Factor{Tv}(p) - -# Define get similar to get(Nullable) to check pointers. All pointer loads -# should be wrapped in get to make sure that SuiteSparse is not called with -# a C_NULL pointer which could cause a segfault. Pointers are set to null -# when serialized so this can happen when mutiple processes are in use. -function get(p::Ptr{T}) where T<:SuiteSparseStruct - if p == C_NULL - throw(ArgumentError("pointer to the $T object is null. This can " * - "happen if the object has been serialized.")) - else - return p - end -end - -# FactorComponent, for encoding particular factors from a factorization -mutable struct FactorComponent{Tv,S} <: AbstractMatrix{Tv} - F::Factor{Tv} - - function FactorComponent{Tv,S}(F::Factor{Tv}) where {Tv,S} - s = unsafe_load(get(F.p)) - if s.is_ll != 0 - if !(S == :L || S == :U || S == :PtL || S == :UP) - throw(CHOLMODException(string(S, " not supported for sparse ", - "LLt matrices; try :L, :U, :PtL, or :UP"))) - end - elseif !(S == :L || S == :U || S == :PtL || S == :UP || - S == :D || S == :LD || S == :DU || S == :PtLD || S == :DUP) - throw(CHOLMODException(string(S, " not supported for sparse LDLt ", - "matrices; try :L, :U, :PtL, :UP, :D, :LD, :DU, :PtLD, or :DUP"))) - end - new(F) - end -end -function FactorComponent(F::Factor{Tv}, sym::Symbol) where Tv - FactorComponent{Tv,sym}(F) -end - -Factor(FC::FactorComponent) = Factor(FC.F) - -################# -# Thin wrappers # -################# - -# Dense wrappers -## Note! Integer type defaults to Cint, but this is actually not necessary, but -## making this a choice would require another type parameter in the Dense type - -### cholmod_core_h ### -function allocate_dense(nrow::Integer, ncol::Integer, d::Integer, ::Type{Float64}) - d = Dense(ccall((:cholmod_l_allocate_dense, :libcholmod), Ptr{C_Dense{Float64}}, - (Csize_t, Csize_t, Csize_t, Cint, Ptr{Void}), - nrow, ncol, d, REAL, common())) - finalizer(d, free!) - d -end -function allocate_dense(nrow::Integer, ncol::Integer, d::Integer, ::Type{Complex{Float64}}) - d = Dense(ccall((:cholmod_l_allocate_dense, :libcholmod), Ptr{C_Dense{Complex{Float64}}}, - (Csize_t, Csize_t, Csize_t, Cint, Ptr{Void}), - nrow, ncol, d, COMPLEX, common())) - finalizer(d, free!) - d -end - -free_dense!(p::Ptr{C_Dense{T}}) where {T} = ccall((:cholmod_l_free_dense, :libcholmod), - Cint, (Ref{Ptr{C_Dense{T}}}, Ptr{Void}), p, common()) - -function zeros(m::Integer, n::Integer, ::Type{T}) where T<:VTypes - d = Dense(ccall((:cholmod_l_zeros, :libcholmod), Ptr{C_Dense{T}}, - (Csize_t, Csize_t, Cint, Ptr{UInt8}), - m, n, xtyp(T), common())) - finalizer(d, free!) - d -end -zeros(m::Integer, n::Integer) = zeros(m, n, Float64) - -function ones(m::Integer, n::Integer, ::Type{T}) where T<:VTypes - d = Dense(ccall((:cholmod_l_ones, :libcholmod), Ptr{C_Dense{T}}, - (Csize_t, Csize_t, Cint, Ptr{UInt8}), - m, n, xtyp(T), common())) - finalizer(d, free!) - d -end -ones(m::Integer, n::Integer) = ones(m, n, Float64) - -function eye(m::Integer, n::Integer, ::Type{T}) where T<:VTypes - d = Dense(ccall((:cholmod_l_eye, :libcholmod), Ptr{C_Dense{T}}, - (Csize_t, Csize_t, Cint, Ptr{UInt8}), - m, n, xtyp(T), common())) - finalizer(d, free!) - d -end -eye(m::Integer, n::Integer) = eye(m, n, Float64) -eye(n::Integer) = eye(n, n, Float64) - -function copy_dense(A::Dense{Tv}) where Tv<:VTypes - d = Dense(ccall((:cholmod_l_copy_dense, :libcholmod), Ptr{C_Dense{Tv}}, - (Ptr{C_Dense{Tv}}, Ptr{UInt8}), - get(A.p), common())) - finalizer(d, free!) - d -end - -function sort!(S::Sparse{Tv}) where Tv<:VTypes - @isok ccall((:cholmod_l_sort, :libcholmod), SuiteSparse_long, - (Ptr{C_Sparse{Tv}}, Ptr{UInt8}), - get(S.p), common()) - return S -end - -### cholmod_matrixops.h ### -function norm_dense(D::Dense{Tv}, p::Integer) where Tv<:VTypes - s = unsafe_load(get(D.p)) - if p == 2 - if s.ncol > 1 - throw(ArgumentError("2 norm only supported when matrix has one column")) - end - elseif p != 0 && p != 1 - throw(ArgumentError("second argument must be either 0 (Inf norm), 1, or 2")) - end - ccall((:cholmod_l_norm_dense, :libcholmod), Cdouble, - (Ptr{C_Dense{Tv}}, Cint, Ptr{UInt8}), - get(D.p), p, common()) -end - -### cholmod_check.h ### -function check_dense(A::Dense{T}) where T<:VTypes - ccall((:cholmod_l_check_dense, :libcholmod), Cint, - (Ptr{C_Dense{T}}, Ptr{UInt8}), - A.p, common())!=0 -end - -# Non-Dense wrappers -### cholmod_core.h ### -function allocate_sparse(nrow::Integer, ncol::Integer, nzmax::Integer, - sorted::Bool, packed::Bool, stype::Integer, ::Type{Float64}) - s = Sparse(ccall((@cholmod_name("allocate_sparse", SuiteSparse_long), :libcholmod), - Ptr{C_Sparse{Float64}}, - (Csize_t, Csize_t, Csize_t, Cint, - Cint, Cint, Cint, Ptr{Void}), - nrow, ncol, nzmax, sorted, - packed, stype, REAL, common())) - finalizer(s, free!) - s -end -function allocate_sparse(nrow::Integer, ncol::Integer, nzmax::Integer, - sorted::Bool, packed::Bool, stype::Integer, ::Type{Complex{Float64}}) - s = Sparse(ccall((@cholmod_name("allocate_sparse", SuiteSparse_long), :libcholmod), - Ptr{C_Sparse{Complex{Float64}}}, - (Csize_t, Csize_t, Csize_t, Cint, - Cint, Cint, Cint, Ptr{Void}), - nrow, ncol, nzmax, sorted, - packed, stype, COMPLEX, common())) - finalizer(s, free!) - s -end -function free_sparse!(ptr::Ptr{C_Sparse{Tv}}) where Tv<:VTypes - @isok ccall((@cholmod_name("free_sparse", SuiteSparse_long), :libcholmod), Cint, - (Ptr{Ptr{C_Sparse{Tv}}}, Ptr{UInt8}), - &ptr, common()) -end - -function free_sparse!(ptr::Ptr{C_SparseVoid}) - @isok ccall((@cholmod_name("free_sparse", SuiteSparse_long), :libcholmod), Cint, - (Ptr{Ptr{C_SparseVoid}}, Ptr{UInt8}), - &ptr, common()) -end - -function free_factor!(ptr::Ptr{C_Factor{Tv}}) where Tv<:VTypes - # Warning! Important that finalizer doesn't modify the global Common struct. - @isok ccall((@cholmod_name("free_factor", SuiteSparse_long), :libcholmod), Cint, - (Ptr{Ptr{C_Factor{Tv}}}, Ptr{Void}), - &ptr, common()) -end - -function aat(A::Sparse{Tv}, fset::Vector{SuiteSparse_long}, mode::Integer) where Tv<:VRealTypes - s = Sparse(ccall((@cholmod_name("aat", SuiteSparse_long), :libcholmod), - Ptr{C_Sparse{Tv}}, - (Ptr{C_Sparse{Tv}}, Ptr{SuiteSparse_long}, Csize_t, Cint, Ptr{UInt8}), - get(A.p), fset, length(fset), mode, common())) - finalizer(s, free!) - s -end - -function sparse_to_dense(A::Sparse{Tv}) where Tv<:VTypes - d = Dense(ccall((@cholmod_name("sparse_to_dense", SuiteSparse_long),:libcholmod), - Ptr{C_Dense{Tv}}, - (Ptr{C_Sparse{Tv}}, Ptr{UInt8}), - get(A.p), common())) - finalizer(d, free!) - d -end -function dense_to_sparse(D::Dense{Tv}, ::Type{SuiteSparse_long}) where Tv<:VTypes - s = Sparse(ccall((@cholmod_name("dense_to_sparse", SuiteSparse_long),:libcholmod), - Ptr{C_Sparse{Tv}}, - (Ptr{C_Dense{Tv}}, Cint, Ptr{UInt8}), - get(D.p), true, common())) - finalizer(s, free!) - s -end - -function factor_to_sparse!(F::Factor{Tv}) where Tv<:VTypes - ss = unsafe_load(F.p) - ss.xtype > PATTERN || throw(CHOLMODException("only numeric factors are supported")) - s = Sparse(ccall((@cholmod_name("factor_to_sparse", SuiteSparse_long),:libcholmod), - Ptr{C_Sparse{Tv}}, - (Ptr{C_Factor{Tv}}, Ptr{UInt8}), - get(F.p), common())) - finalizer(s, free!) - s -end - -function change_factor!(::Type{Float64}, to_ll::Bool, - to_super::Bool, to_packed::Bool, to_monotonic::Bool, F::Factor{Tv}) where Tv<:VTypes - @isok ccall((@cholmod_name("change_factor", SuiteSparse_long),:libcholmod), Cint, - (Cint, Cint, Cint, Cint, Cint, Ptr{C_Factor{Tv}}, Ptr{UInt8}), - REAL, to_ll, to_super, to_packed, to_monotonic, get(F.p), common()) - Factor{Float64}(F.p) -end - -function change_factor!(::Type{Complex{Float64}}, to_ll::Bool, - to_super::Bool, to_packed::Bool, to_monotonic::Bool, F::Factor{Tv}) where Tv<:VTypes - @isok ccall((@cholmod_name("change_factor", SuiteSparse_long),:libcholmod), Cint, - (Cint, Cint, Cint, Cint, Cint, Ptr{C_Factor{Tv}}, Ptr{UInt8}), - COMPLEX, to_ll, to_super, to_packed, to_monotonic, get(F.p), common()) - Factor{Complex{Float64}}(F.p) -end - -function check_sparse(A::Sparse{Tv}) where Tv<:VTypes - ccall((@cholmod_name("check_sparse", SuiteSparse_long),:libcholmod), Cint, - (Ptr{C_Sparse{Tv}}, Ptr{UInt8}), - get(A.p), common())!=0 -end - -function check_factor(F::Factor{Tv}) where Tv<:VTypes - ccall((@cholmod_name("check_factor", SuiteSparse_long),:libcholmod), Cint, - (Ptr{C_Factor{Tv}}, Ptr{UInt8}), - get(F.p), common())!=0 -end - -function nnz{Tv<:VTypes}(A::Sparse{Tv}) - ccall((@cholmod_name("nnz", SuiteSparse_long),:libcholmod), Int, - (Ptr{C_Sparse{Tv}}, Ptr{UInt8}), - get(A.p), common()) -end - -function speye(m::Integer, n::Integer, ::Type{Tv}) where Tv<:VTypes - s = Sparse(ccall((@cholmod_name("speye", SuiteSparse_long), :libcholmod), - Ptr{C_Sparse{Tv}}, - (Csize_t, Csize_t, Cint, Ptr{UInt8}), - m, n, xtyp(Tv), common())) - finalizer(s, free!) - s -end - -function spzeros(m::Integer, n::Integer, nzmax::Integer, ::Type{Tv}) where Tv<:VTypes - s = Sparse(ccall((@cholmod_name("spzeros", SuiteSparse_long), :libcholmod), - Ptr{C_Sparse{Tv}}, - (Csize_t, Csize_t, Csize_t, Cint, Ptr{UInt8}), - m, n, nzmax, xtyp(Tv), common())) - finalizer(s, free!) - s -end - -function transpose_(A::Sparse{Tv}, values::Integer) where Tv<:VTypes - s = Sparse(ccall((@cholmod_name("transpose", SuiteSparse_long),:libcholmod), - Ptr{C_Sparse{Tv}}, - (Ptr{C_Sparse{Tv}}, Cint, Ptr{UInt8}), - get(A.p), values, common())) - finalizer(s, free!) - s -end - -function copy_factor(F::Factor{Tv}) where Tv<:VTypes - f = Factor(ccall((@cholmod_name("copy_factor", SuiteSparse_long),:libcholmod), - Ptr{C_Factor{Tv}}, - (Ptr{C_Factor{Tv}}, Ptr{UInt8}), - get(F.p), common())) - finalizer(f, free!) - f -end -function copy_sparse(A::Sparse{Tv}) where Tv<:VTypes - s = Sparse(ccall((@cholmod_name("copy_sparse", SuiteSparse_long),:libcholmod), - Ptr{C_Sparse{Tv}}, - (Ptr{C_Sparse{Tv}}, Ptr{UInt8}), - get(A.p), common())) - finalizer(s, free!) - s -end -function copy(A::Sparse{Tv}, stype::Integer, mode::Integer) where Tv<:VRealTypes - s = Sparse(ccall((@cholmod_name("copy", SuiteSparse_long),:libcholmod), - Ptr{C_Sparse{Tv}}, - (Ptr{C_Sparse{Tv}}, Cint, Cint, Ptr{UInt8}), - get(A.p), stype, mode, common())) - finalizer(s, free!) - s -end - -### cholmod_check.h ### -function print_sparse(A::Sparse{Tv}, name::String) where Tv<:VTypes - isascii(name) || error("non-ASCII name: $name") - cm = common() - set_print_level(cm, 3) - @isok ccall((@cholmod_name("print_sparse", SuiteSparse_long),:libcholmod), Cint, - (Ptr{C_Sparse{Tv}}, Ptr{UInt8}, Ptr{UInt8}), - get(A.p), name, cm) - nothing -end -function print_factor(F::Factor{Tv}, name::String) where Tv<:VTypes - cm = common() - set_print_level(cm, 3) - @isok ccall((@cholmod_name("print_factor", SuiteSparse_long),:libcholmod), Cint, - (Ptr{C_Factor{Tv}}, Ptr{UInt8}, Ptr{UInt8}), - get(F.p), name, cm) - nothing -end - -### cholmod_matrixops.h ### -function ssmult(A::Sparse{Tv}, B::Sparse{Tv}, stype::Integer, - values::Bool, sorted::Bool) where Tv<:VRealTypes - lA = unsafe_load(get(A.p)) - lB = unsafe_load(get(B.p)) - if lA.ncol != lB.nrow - throw(DimensionMismatch("inner matrix dimensions do not fit")) - end - s = Sparse(ccall((@cholmod_name("ssmult", SuiteSparse_long),:libcholmod), - Ptr{C_Sparse{Tv}}, - (Ptr{C_Sparse{Tv}}, Ptr{C_Sparse{Tv}}, Cint, Cint, - Cint, Ptr{UInt8}), - get(A.p), get(B.p), stype, values, - sorted, common())) - finalizer(s, free!) - s -end - -function norm_sparse(A::Sparse{Tv}, norm::Integer) where Tv<:VTypes - if norm != 0 && norm != 1 - throw(ArgumentError("norm argument must be either 0 or 1")) - end - ccall((@cholmod_name("norm_sparse", SuiteSparse_long), :libcholmod), Cdouble, - (Ptr{C_Sparse{Tv}}, Cint, Ptr{UInt8}), - get(A.p), norm, common()) -end - -function horzcat(A::Sparse{Tv}, B::Sparse{Tv}, values::Bool) where Tv<:VRealTypes - s = Sparse(ccall((@cholmod_name("horzcat", SuiteSparse_long), :libcholmod), - Ptr{C_Sparse{Tv}}, - (Ptr{C_Sparse{Tv}}, Ptr{C_Sparse{Tv}}, Cint, Ptr{UInt8}), - get(A.p), get(B.p), values, common())) - finalizer(s, free!) - s -end - -function scale!(S::Dense{Tv}, scale::Integer, A::Sparse{Tv}) where Tv<:VRealTypes - sS = unsafe_load(get(S.p)) - sA = unsafe_load(get(A.p)) - if sS.ncol != 1 && sS.nrow != 1 - throw(DimensionMismatch("first argument must be a vector")) - end - if scale == SCALAR && sS.nrow != 1 - throw(DimensionMismatch("scaling argument must have length one")) - elseif scale == ROW && sS.nrow*sS.ncol != sA.nrow - throw(DimensionMismatch("scaling vector has length $(sS.nrow*sS.ncol), " * - "but matrix has $(sA.nrow) rows.")) - elseif scale == COL && sS.nrow*sS.ncol != sA.ncol - throw(DimensionMismatch("scaling vector has length $(sS.nrow*sS.ncol), " * - "but matrix has $(sA.ncol) columns")) - elseif scale == SYM - if sA.nrow != sA.ncol - throw(DimensionMismatch("matrix must be square")) - elseif sS.nrow*sS.ncol != sA.nrow - throw(DimensionMismatch("scaling vector has length $(sS.nrow*sS.ncol), " * - "but matrix has $(sA.ncol) columns and rows")) - end - end - - sA = unsafe_load(get(A.p)) - @isok ccall((@cholmod_name("scale",SuiteSparse_long),:libcholmod), Cint, - (Ptr{C_Dense{Tv}}, Cint, Ptr{C_Sparse{Tv}}, Ptr{UInt8}), - get(S.p), scale, get(A.p), common()) - A -end - -function sdmult!(A::Sparse{Tv}, transpose::Bool, - α::Number, β::Number, X::Dense{Tv}, Y::Dense{Tv}) where Tv<:VTypes - m, n = size(A) - nc = transpose ? m : n - nr = transpose ? n : m - if nc != size(X, 1) - throw(DimensionMismatch("incompatible dimensions, $nc and $(size(X,1))")) - end - @isok ccall((@cholmod_name("sdmult", SuiteSparse_long),:libcholmod), Cint, - (Ptr{C_Sparse{Tv}}, Cint, - Ref{Complex128}, Ref{Complex128}, - Ptr{C_Dense{Tv}}, Ptr{C_Dense{Tv}}, Ptr{UInt8}), - get(A.p), transpose, α, β, get(X.p), get(Y.p), common()) - Y -end - -function vertcat(A::Sparse{Tv}, B::Sparse{Tv}, values::Bool) where Tv<:VRealTypes - s = Sparse(ccall((@cholmod_name("vertcat", SuiteSparse_long), :libcholmod), - Ptr{C_Sparse{Tv}}, - (Ptr{C_Sparse{Tv}}, Ptr{C_Sparse{Tv}}, Cint, Ptr{UInt8}), - get(A.p), get(B.p), values, common())) - finalizer(s, free!) - s -end - -function symmetry(A::Sparse{Tv}, option::Integer) where Tv<:VTypes - xmatched = Ref{SuiteSparse_long}() - pmatched = Ref{SuiteSparse_long}() - nzoffdiag = Ref{SuiteSparse_long}() - nzdiag = Ref{SuiteSparse_long}() - rv = ccall((@cholmod_name("symmetry", SuiteSparse_long), :libcholmod), Cint, - (Ptr{C_Sparse{Tv}}, Cint, Ptr{SuiteSparse_long}, Ptr{SuiteSparse_long}, - Ptr{SuiteSparse_long}, Ptr{SuiteSparse_long}, Ptr{UInt8}), - get(A.p), option, xmatched, pmatched, - nzoffdiag, nzdiag, common()) - rv, xmatched[], pmatched[], nzoffdiag[], nzdiag[] -end - -# cholmod_cholesky.h -# For analyze, analyze_p, and factorize_p!, the Common argument must be -# supplied in order to control if the factorization is LLt or LDLt -function analyze{Tv<:VTypes}(A::Sparse{Tv}, cmmn::Vector{UInt8}) - f = Factor(ccall((@cholmod_name("analyze", SuiteSparse_long),:libcholmod), - Ptr{C_Factor{Tv}}, - (Ptr{C_Sparse{Tv}}, Ptr{UInt8}), - get(A.p), cmmn)) - finalizer(f, free!) - f -end -function analyze_p{Tv<:VTypes}(A::Sparse{Tv}, perm::Vector{SuiteSparse_long}, - cmmn::Vector{UInt8}) - length(perm) != size(A,1) && throw(BoundsError()) - f = Factor(ccall((@cholmod_name("analyze_p", SuiteSparse_long),:libcholmod), - Ptr{C_Factor{Tv}}, - (Ptr{C_Sparse{Tv}}, Ptr{SuiteSparse_long}, Ptr{SuiteSparse_long}, - Csize_t, Ptr{UInt8}), - get(A.p), perm, C_NULL, 0, cmmn)) - finalizer(f, free!) - f -end -function factorize!(A::Sparse{Tv}, F::Factor{Tv}, cmmn::Vector{UInt8}) where Tv<:VTypes - @isok ccall((@cholmod_name("factorize", SuiteSparse_long),:libcholmod), Cint, - (Ptr{C_Sparse{Tv}}, Ptr{C_Factor{Tv}}, Ptr{UInt8}), - get(A.p), get(F.p), cmmn) - F -end -function factorize_p!(A::Sparse{Tv}, β::Real, F::Factor{Tv}, cmmn::Vector{UInt8}) where Tv<:VTypes - # note that β is passed as a complex number (double beta[2]), - # but the CHOLMOD manual says that only beta[0] (real part) is used - @isok ccall((@cholmod_name("factorize_p", SuiteSparse_long),:libcholmod), Cint, - (Ptr{C_Sparse{Tv}}, Ref{Complex128}, Ptr{SuiteSparse_long}, Csize_t, - Ptr{C_Factor{Tv}}, Ptr{UInt8}), - get(A.p), β, C_NULL, 0, get(F.p), cmmn) - F -end - -function solve(sys::Integer, F::Factor{Tv}, B::Dense{Tv}) where Tv<:VTypes - if size(F,1) != size(B,1) - throw(DimensionMismatch("LHS and RHS should have the same number of rows. " * - "LHS has $(size(F,1)) rows, but RHS has $(size(B,1)) rows.")) - end - d = Dense(ccall((@cholmod_name("solve", SuiteSparse_long),:libcholmod), Ptr{C_Dense{Tv}}, - (Cint, Ptr{C_Factor{Tv}}, Ptr{C_Dense{Tv}}, Ptr{UInt8}), - sys, get(F.p), get(B.p), common())) - finalizer(d, free!) - d -end - -function spsolve(sys::Integer, F::Factor{Tv}, B::Sparse{Tv}) where Tv<:VTypes - if size(F,1) != size(B,1) - throw(DimensionMismatch("LHS and RHS should have the same number of rows. " * - "LHS has $(size(F,1)) rows, but RHS has $(size(B,1)) rows.")) - end - s = Sparse(ccall((@cholmod_name("spsolve", SuiteSparse_long),:libcholmod), - Ptr{C_Sparse{Tv}}, - (Cint, Ptr{C_Factor{Tv}}, Ptr{C_Sparse{Tv}}, Ptr{UInt8}), - sys, get(F.p), get(B.p), common())) - finalizer(s, free!) - s -end - -# Autodetects the types -function read_sparse(file::Libc.FILE, ::Type{SuiteSparse_long}) - ptr = ccall((@cholmod_name("read_sparse", SuiteSparse_long), :libcholmod), - Ptr{C_SparseVoid}, - (Ptr{Void}, Ptr{UInt8}), - file.ptr, common()) - if ptr == C_NULL - throw(ArgumentError("sparse matrix construction failed. Check that input file is valid.")) - end - s = Sparse(ptr) - finalizer(s, free!) - s -end - -function read_sparse(file::IO, T) - cfile = Libc.FILE(file) - try return read_sparse(cfile, T) - finally close(cfile) - end -end - -function get_perm(F::Factor) - s = unsafe_load(get(F.p)) - p = unsafe_wrap(Array, s.Perm, s.n, false) - p+1 -end -get_perm(FC::FactorComponent) = get_perm(Factor(FC)) - -######################### -# High level interfaces # -######################### - -# Convertion/construction -function convert(::Type{Dense{T}}, A::StridedVecOrMat) where T<:VTypes - d = allocate_dense(size(A, 1), size(A, 2), stride(A, 2), T) - s = unsafe_load(d.p) - for i in eachindex(A) - unsafe_store!(s.x, A[i], i) - end - d -end -function convert(::Type{Dense}, A::StridedVecOrMat) - T = promote_type(eltype(A), Float64) - return convert(Dense{T}, A) -end -convert(::Type{Dense}, A::Sparse) = sparse_to_dense(A) - -# This constructior assumes zero based colptr and rowval -function Sparse(m::Integer, n::Integer, - colptr0::Vector{SuiteSparse_long}, rowval0::Vector{SuiteSparse_long}, - nzval::Vector{Tv}, stype) where Tv<:VTypes - # checks - ## length of input - if length(colptr0) <= n - throw(ArgumentError("length of colptr0 must be at least n + 1 = $(n + 1) but was $(length(colptr0))")) - end - if colptr0[n + 1] > length(rowval0) - throw(ArgumentError("length of rowval0 is $(length(rowval0)) but value of colptr0 requires length to be at least $(colptr0[n + 1])")) - end - if colptr0[n + 1] > length(nzval) - throw(ArgumentError("length of nzval is $(length(nzval)) but value of colptr0 requires length to be at least $(colptr0[n + 1])")) - end - ## columns are sorted - iss = true - for i = 2:length(colptr0) - if !issorted(view(rowval0, colptr0[i - 1] + 1:colptr0[i])) - iss = false - break - end - end - - o = allocate_sparse(m, n, colptr0[n + 1], iss, true, stype, Tv) - s = unsafe_load(o.p) - - unsafe_copy!(s.p, pointer(colptr0), n + 1) - unsafe_copy!(s.i, pointer(rowval0), colptr0[n + 1]) - unsafe_copy!(s.x, pointer(nzval) , colptr0[n + 1]) - - @isok check_sparse(o) - - return o -end - -function Sparse(m::Integer, n::Integer, - colptr0::Vector{SuiteSparse_long}, - rowval0::Vector{SuiteSparse_long}, - nzval::Vector{<:VTypes}) - o = Sparse(m, n, colptr0, rowval0, nzval, 0) - - # sort indices - sort!(o) - - # check if array is symmetric and change stype if it is - if ishermitian(o) - change_stype!(o, -1) - end - o -end - -function Sparse(A::SparseMatrixCSC{Tv,SuiteSparse_long}, stype::Integer) where Tv<:VTypes - ## Check length of input. This should never fail but see #20024 - if length(A.colptr) <= A.n - throw(ArgumentError("length of colptr must be at least size(A,2) + 1 = $(A.n + 1) but was $(length(A.colptr))")) - end - if nnz(A) > length(A.rowval) - throw(ArgumentError("length of rowval is $(length(A.rowval)) but value of colptr requires length to be at least $(nnz(A))")) - end - if nnz(A) > length(A.nzval) - throw(ArgumentError("length of nzval is $(length(A.nzval)) but value of colptr requires length to be at least $(nnz(A))")) - end - - o = allocate_sparse(A.m, A.n, nnz(A), true, true, stype, Tv) - s = unsafe_load(o.p) - for i = 1:(A.n + 1) - unsafe_store!(s.p, A.colptr[i] - 1, i) - end - for i = 1:nnz(A) - unsafe_store!(s.i, A.rowval[i] - 1, i) - end - unsafe_copy!(s.x, pointer(A.nzval), nnz(A)) - - @isok check_sparse(o) - - return o -end - -# convert SparseVectors into CHOLMOD Sparse types through a mx1 CSC matrix -convert(::Type{Sparse}, A::SparseVector{<:VTypes,SuiteSparse_long}) = - convert(Sparse, convert(SparseMatrixCSC, A)) -function convert(::Type{Sparse}, A::SparseMatrixCSC{<:VTypes,<:ITypes}) - o = Sparse(A, 0) - # check if array is symmetric and change stype if it is - if ishermitian(o) - change_stype!(o, -1) - end - o -end -convert(::Type{Sparse}, A::SparseMatrixCSC{Complex{Float32},<:ITypes}) = - convert(Sparse, convert(SparseMatrixCSC{Complex{Float64},SuiteSparse_long}, A)) -convert(::Type{Sparse}, A::Symmetric{Float64,SparseMatrixCSC{Float64,SuiteSparse_long}}) = - Sparse(A.data, A.uplo == 'L' ? -1 : 1) -convert(::Type{Sparse}, A::Hermitian{Tv,SparseMatrixCSC{Tv,SuiteSparse_long}}) where {Tv<:VTypes} = - Sparse(A.data, A.uplo == 'L' ? -1 : 1) -function convert{Ti<:ITypes}(::Type{Sparse}, - A::Union{SparseMatrixCSC{BigFloat,Ti}, - Symmetric{BigFloat,SparseMatrixCSC{BigFloat,Ti}}, - Hermitian{Complex{BigFloat},SparseMatrixCSC{Complex{BigFloat},Ti}}}, - args...) - throw(MethodError(convert, (Sparse, A))) -end -function convert(::Type{Sparse}, - A::Union{SparseMatrixCSC{T,Ti}, - Symmetric{T,SparseMatrixCSC{T,Ti}}, - Hermitian{T,SparseMatrixCSC{T,Ti}}}, - args...) where T where Ti<:ITypes - return Sparse(convert(AbstractMatrix{promote_type(Float64, T)}, A), args...) -end - -# Useful when reading in files, but not type stable -function convert(::Type{Sparse}, p::Ptr{C_SparseVoid}) - if p == C_NULL - throw(ArgumentError("sparse matrix construction failed for " * - "unknown reasons. Please submit a bug report.")) - end - - s = unsafe_load(p) - - # Check integer type - if s.itype == INT - free_sparse!(p) - throw(CHOLMODException("the value of itype was $s.itype. " * - "Only integer type of $SuiteSparse_long is supported.")) - elseif s.itype == INTLONG - free_sparse!(p) - throw(CHOLMODException("the value of itype was $s.itype. This combination " * - "of integer types shouldn't happen. Please submit a bug report.")) - elseif s.itype != LONG # must be s.itype == LONG - free_sparse!(p) - throw(CHOLMODException("illegal value of itype: $s.itype")) - end - - # Check for double or single precision - if s.dtype == DOUBLE - Tv = Float64 - elseif s.dtype == SINGLE - # Tv = Float32 # this should be supported at some point - free_sparse!(p) - throw(CHOLMODException("single precision not supported yet")) - else - free_sparse!(p) - throw(CHOLMODException("illegal value of dtype: $s.dtype")) - end - - # Check for real or complex - if s.xtype == COMPLEX - Tv = Complex{Tv} - elseif s.xtype != REAL - free_sparse!(p) - throw(CHOLMODException("illegal value of xtype: $s.xtype")) - end - - return Sparse(convert(Ptr{C_Sparse{Tv}}, p)) -end - -convert(::Type{Sparse}, A::Dense) = dense_to_sparse(A, SuiteSparse_long) -convert(::Type{Sparse}, L::Factor) = factor_to_sparse!(copy(L)) -function (::Type{Sparse})(filename::String) - open(filename) do f - return read_sparse(f, SuiteSparse_long) - end -end - -## convertion back to base Julia types -function convert(::Type{Matrix{T}}, D::Dense{T}) where T - s = unsafe_load(D.p) - a = Matrix{T}(s.nrow, s.ncol) - copy!(a, D) -end - -Base.copy!(dest::Base.PermutedDimsArrays.PermutedDimsArray, src::Dense) = _copy!(dest, src) # ambig -Base.copy!(dest::Dense{T}, D::Dense{T}) where {T<:VTypes} = _copy!(dest, D) -Base.copy!(dest::AbstractArray{T}, D::Dense{T}) where {T<:VTypes} = _copy!(dest, D) -Base.copy!(dest::AbstractArray{T,2}, D::Dense{T}) where {T<:VTypes} = _copy!(dest, D) -Base.copy!(dest::AbstractArray, D::Dense) = _copy!(dest, D) - -function _copy!(dest::AbstractArray, D::Dense) - s = unsafe_load(D.p) - n = s.nrow*s.ncol - n <= length(dest) || throw(BoundsError(dest, n)) - if s.d == s.nrow && isa(dest, Array) - unsafe_copy!(pointer(dest), s.x, s.d*s.ncol) - else - k = 0 - for j = 1:s.ncol - for i = 1:s.nrow - dest[k+=1] = unsafe_load(s.x, i + (j - 1)*s.d) - end - end - end - dest -end -convert(::Type{Matrix}, D::Dense{T}) where {T} = convert(Matrix{T}, D) -function convert(::Type{Vector{T}}, D::Dense{T}) where T - if size(D, 2) > 1 - throw(DimensionMismatch("input must be a vector but had $(size(D, 2)) columns")) - end - copy!(Vector{T}(size(D, 1)), D) -end -convert(::Type{Vector}, D::Dense{T}) where {T} = convert(Vector{T}, D) - -function convert(::Type{SparseMatrixCSC{Tv,SuiteSparse_long}}, A::Sparse{Tv}) where Tv - s = unsafe_load(A.p) - if s.stype != 0 - throw(ArgumentError("matrix has stype != 0. Convert to matrix " * - "with stype == 0 before converting to SparseMatrixCSC")) - end - - B = SparseMatrixCSC(s.nrow, s.ncol, - increment(unsafe_wrap(Array, s.p, (s.ncol + 1,), false)), - increment(unsafe_wrap(Array, s.i, (s.nzmax,), false)), - copy(unsafe_wrap(Array, s.x, (s.nzmax,), false))) - - if s.sorted == 0 - return SparseArrays.sortSparseMatrixCSC!(B) - else - return B - end -end -function convert(::Type{Symmetric{Float64,SparseMatrixCSC{Float64,SuiteSparse_long}}}, A::Sparse{Float64}) - s = unsafe_load(A.p) - if !issymmetric(A) - throw(ArgumentError("matrix is not symmetric")) - end - - B = Symmetric(SparseMatrixCSC(s.nrow, s.ncol, - increment(unsafe_wrap(Array, s.p, (s.ncol + 1,), false)), - increment(unsafe_wrap(Array, s.i, (s.nzmax,), false)), - copy(unsafe_wrap(Array, s.x, (s.nzmax,), false))), s.stype > 0 ? :U : :L) - - if s.sorted == 0 - return SparseArrays.sortSparseMatrixCSC!(B.data) - else - return B - end -end -function convert(::Type{Hermitian{Tv,SparseMatrixCSC{Tv,SuiteSparse_long}}}, A::Sparse{Tv}) where Tv<:VTypes - s = unsafe_load(A.p) - if !ishermitian(A) - throw(ArgumentError("matrix is not Hermitian")) - end - - B = Hermitian(SparseMatrixCSC(s.nrow, s.ncol, - increment(unsafe_wrap(Array, s.p, (s.ncol + 1,), false)), - increment(unsafe_wrap(Array, s.i, (s.nzmax,), false)), - copy(unsafe_wrap(Array, s.x, (s.nzmax,), false))), s.stype > 0 ? :U : :L) - - if s.sorted == 0 - return SparseArrays.sortSparseMatrixCSC!(B.data) - else - return B - end -end -function sparse(A::Sparse{Float64}) # Notice! Cannot be type stable because of stype - s = unsafe_load(A.p) - if s.stype == 0 - return convert(SparseMatrixCSC{Float64,SuiteSparse_long}, A) - end - return convert(Symmetric{Float64,SparseMatrixCSC{Float64,SuiteSparse_long}}, A) -end -function sparse(A::Sparse{Complex{Float64}}) # Notice! Cannot be type stable because of stype - s = unsafe_load(A.p) - if s.stype == 0 - return convert(SparseMatrixCSC{Complex{Float64},SuiteSparse_long}, A) - end - return convert(Hermitian{Complex{Float64},SparseMatrixCSC{Complex{Float64},SuiteSparse_long}}, A) -end -function sparse(F::Factor) - s = unsafe_load(F.p) - if s.is_ll != 0 - L = Sparse(F) - A = sparse(L*L') - else - LD = sparse(F[:LD]) - L, d = getLd!(LD) - A = (L * Diagonal(d)) * L' - end - SparseArrays.sortSparseMatrixCSC!(A) - p = get_perm(F) - if p != [1:s.n;] - pinv = Vector{Int}(length(p)) - for k = 1:length(p) - pinv[p[k]] = k - end - A = A[pinv,pinv] - end - A -end - -sparse(D::Dense) = sparse(Sparse(D)) - -function sparse(FC::FactorComponent{Tv,:L}) where Tv - F = Factor(FC) - s = unsafe_load(F.p) - if s.is_ll == 0 - throw(CHOLMODException("sparse: supported only for :LD on LDLt factorizations")) - end - sparse(Sparse(F)) -end -sparse(FC::FactorComponent{Tv,:LD}) where {Tv} = sparse(Sparse(Factor(FC))) - -# Calculate the offset into the stype field of the cholmod_sparse_struct and -# change the value -let offset = fieldoffset(C_Sparse{Float64}, findfirst(name -> name === :stype, fieldnames(C_Sparse{Float64}))) - global change_stype! - function change_stype!(A::Sparse, i::Integer) - unsafe_store!(convert(Ptr{Cint}, A.p), i, div(offset, 4) + 1) - return A - end -end - -free!(A::Dense) = free_dense!(A.p) -free!(A::Sparse) = free_sparse!(A.p) -free!(F::Factor) = free_factor!(F.p) - -eltype(::Type{Dense{T}}) where {T<:VTypes} = T -eltype(::Type{Factor{T}}) where {T<:VTypes} = T -eltype(::Type{Sparse{T}}) where {T<:VTypes} = T - -nnz(F::Factor) = nnz(Sparse(F)) - -function show(io::IO, F::Factor) - println(io, typeof(F)) - showfactor(io, F) -end - -function show(io::IO, FC::FactorComponent) - println(io, typeof(FC)) - showfactor(io, Factor(FC)) -end - -function showfactor(io::IO, F::Factor) - s = unsafe_load(get(F.p)) - @printf(io, "type: %12s\n", s.is_ll!=0 ? "LLt" : "LDLt") - @printf(io, "method: %10s\n", s.is_super!=0 ? "supernodal" : "simplicial") - @printf(io, "maxnnz: %10d\n", Int(s.nzmax)) - @printf(io, "nnz: %13d\n", nnz(F)) -end - -# getindex not defined for these, so don't use the normal array printer -show(io::IO, ::MIME"text/plain", FC::FactorComponent) = show(io, FC) -show(io::IO, ::MIME"text/plain", F::Factor) = show(io, F) - -isvalid(A::Dense) = check_dense(A) -isvalid(A::Sparse) = check_sparse(A) -isvalid(A::Factor) = check_factor(A) - -copy(A::Dense) = copy_dense(A) -copy(A::Sparse) = copy_sparse(A) -copy(A::Factor) = copy_factor(A) - -function size(A::Union{Dense,Sparse}) - s = unsafe_load(get(A.p)) - return (Int(s.nrow), Int(s.ncol)) -end -function size(F::Factor, i::Integer) - if i < 1 - throw(ArgumentError("dimension must be positive")) - end - s = unsafe_load(get(F.p)) - if i <= 2 - return Int(s.n) - end - return 1 -end -size(F::Factor) = (size(F, 1), size(F, 2)) - -IndexStyle(::Dense) = IndexLinear() - -size(FC::FactorComponent, i::Integer) = size(FC.F, i) -size(FC::FactorComponent) = size(FC.F) - -ctranspose(FC::FactorComponent{Tv,:L}) where {Tv} = FactorComponent{Tv,:U}(FC.F) -ctranspose(FC::FactorComponent{Tv,:U}) where {Tv} = FactorComponent{Tv,:L}(FC.F) -ctranspose(FC::FactorComponent{Tv,:PtL}) where {Tv} = FactorComponent{Tv,:UP}(FC.F) -ctranspose(FC::FactorComponent{Tv,:UP}) where {Tv} = FactorComponent{Tv,:PtL}(FC.F) -ctranspose(FC::FactorComponent{Tv,:D}) where {Tv} = FC -ctranspose(FC::FactorComponent{Tv,:LD}) where {Tv} = FactorComponent{Tv,:DU}(FC.F) -ctranspose(FC::FactorComponent{Tv,:DU}) where {Tv} = FactorComponent{Tv,:LD}(FC.F) -ctranspose(FC::FactorComponent{Tv,:PtLD}) where {Tv} = FactorComponent{Tv,:DUP}(FC.F) -ctranspose(FC::FactorComponent{Tv,:DUP}) where {Tv} = FactorComponent{Tv,:PtLD}(FC.F) - -function getindex(A::Dense, i::Integer) - s = unsafe_load(get(A.p)) - 0 < i <= s.nrow*s.ncol || throw(BoundsError()) - unsafe_load(s.x, i) -end - -IndexStyle(::Sparse) = IndexCartesian() -function getindex(A::Sparse{T}, i0::Integer, i1::Integer) where T - s = unsafe_load(get(A.p)) - !(1 <= i0 <= s.nrow && 1 <= i1 <= s.ncol) && throw(BoundsError()) - s.stype < 0 && i0 < i1 && return conj(A[i1,i0]) - s.stype > 0 && i0 > i1 && return conj(A[i1,i0]) - - r1 = Int(unsafe_load(s.p, i1) + 1) - r2 = Int(unsafe_load(s.p, i1 + 1)) - (r1 > r2) && return zero(T) - r1 = Int(searchsortedfirst(unsafe_wrap(Array, s.i, (s.nzmax,), false), - i0 - 1, r1, r2, Base.Order.Forward)) - ((r1 > r2) || (unsafe_load(s.i, r1) + 1 != i0)) ? zero(T) : unsafe_load(s.x, r1) -end - -function getindex(F::Factor, sym::Symbol) - sym == :p && return get_perm(F) - FactorComponent(F, sym) -end - -function getLd!(S::SparseMatrixCSC) - d = Vector{eltype(S)}(size(S, 1)) - fill!(d, 0) - col = 1 - for k = 1:nnz(S) - while k >= S.colptr[col+1] - col += 1 - end - if S.rowval[k] == col - d[col] = S.nzval[k] - S.nzval[k] = 1 - end - end - S, d -end - -## Multiplication -(*)(A::Sparse, B::Sparse) = ssmult(A, B, 0, true, true) -(*)(A::Sparse, B::Dense) = sdmult!(A, false, 1., 0., B, zeros(size(A, 1), size(B, 2))) -(*)(A::Sparse, B::VecOrMat) = (*)(A, Dense(B)) - -function A_mul_Bc(A::Sparse{Tv}, B::Sparse{Tv}) where Tv<:VRealTypes - cm = common() - - if A !== B - aa1 = transpose_(B, 2) - ## result of ssmult will have stype==0, contain numerical values and be sorted - return ssmult(A, aa1, 0, true, true) - end - - ## The A*A' case is handled by cholmod_aat. This routine requires - ## A->stype == 0 (storage of upper and lower parts). If neccesary - ## the matrix A is first converted to stype == 0 - s = unsafe_load(A.p) - if s.stype != 0 - aa1 = copy(A, 0, 1) - return aat(aa1, SuiteSparse_long[0:s.ncol-1;], 1) - else - return aat(A, SuiteSparse_long[0:s.ncol-1;], 1) - end -end - -function Ac_mul_B(A::Sparse, B::Sparse) - aa1 = transpose_(A, 2) - if A === B - return A_mul_Bc(aa1, aa1) - end - ## result of ssmult will have stype==0, contain numerical values and be sorted - return ssmult(aa1, B, 0, true, true) -end - -Ac_mul_B(A::Sparse, B::Dense) = sdmult!(A, true, 1., 0., B, zeros(size(A, 2), size(B, 2))) -Ac_mul_B(A::Sparse, B::VecOrMat) = Ac_mul_B(A, Dense(B)) - - -## Factorization methods - -## Compute that symbolic factorization only -function fact_(A::Sparse{<:VTypes}, cm::Array{UInt8}; - perm::AbstractVector{SuiteSparse_long}=SuiteSparse_long[], - postorder::Bool=true, userperm_only::Bool=true) - - sA = unsafe_load(get(A.p)) - sA.stype == 0 && throw(ArgumentError("sparse matrix is not symmetric/Hermitian")) - - if !postorder - unsafe_store!(common_postorder, 0) - end - - if isempty(perm) - F = analyze(A, cm) - else # user permutation provided - if userperm_only # use perm even if it is worse than AMD - unsafe_store!(common_nmethods, 1) - end - F = analyze_p(A, SuiteSparse_long[p-1 for p in perm], cm) - end - - return F -end - -function cholfact!(F::Factor{Tv}, A::Sparse{Tv}; shift::Real=0.0) where Tv - cm = common() - - # Makes it an LLt - unsafe_store!(common_final_ll, 1) - - # Compute the numerical factorization - factorize_p!(A, shift, F, cm) - - s = unsafe_load(get(F.p)) - s.minor < size(A, 1) && throw(Base.LinAlg.PosDefException(s.minor)) - return F -end - -""" - cholfact!(F::Factor, A; shift = 0.0) -> CHOLMOD.Factor - -Compute the Cholesky (``LL'``) factorization of `A`, reusing the symbolic -factorization `F`. `A` must be a [`SparseMatrixCSC`](@ref) or a [`Symmetric`](@ref)/ -[`Hermitian`](@ref) view of a `SparseMatrixCSC`. Note that even if `A` doesn't -have the type tag, it must still be symmetric or Hermitian. - -See also [`cholfact`](@ref). - -!!! note - This method uses the CHOLMOD library from SuiteSparse, which only supports - doubles or complex doubles. Input matrices not of those element types will - be converted to `SparseMatrixCSC{Float64}` or `SparseMatrixCSC{Complex128}` - as appropriate. -""" -cholfact!(F::Factor, A::Union{SparseMatrixCSC{T}, - SparseMatrixCSC{Complex{T}}, - Symmetric{T,SparseMatrixCSC{T,SuiteSparse_long}}, - Hermitian{Complex{T},SparseMatrixCSC{Complex{T},SuiteSparse_long}}, - Hermitian{T,SparseMatrixCSC{T,SuiteSparse_long}}}; - shift = 0.0) where {T<:Real} = - cholfact!(F, Sparse(A); shift = shift) - -function cholfact(A::Sparse; shift::Real=0.0, - perm::AbstractVector{SuiteSparse_long}=SuiteSparse_long[]) - - cm = defaults(common()) - set_print_level(cm, 0) - - # Compute the symbolic factorization - F = fact_(A, cm; perm = perm) - - # Compute the numerical factorization - cholfact!(F, A; shift = shift) - - s = unsafe_load(get(F.p)) - s.minor < size(A, 1) && throw(Base.LinAlg.PosDefException(s.minor)) - return F -end - -""" - cholfact(A; shift = 0.0, perm = Int[]) -> CHOLMOD.Factor - -Compute the Cholesky factorization of a sparse positive definite matrix `A`. -`A` must be a [`SparseMatrixCSC`](@ref) or a [`Symmetric`](@ref)/[`Hermitian`](@ref) -view of a `SparseMatrixCSC`. Note that even if `A` doesn't -have the type tag, it must still be symmetric or Hermitian. -A fill-reducing permutation is used. -`F = cholfact(A)` is most frequently used to solve systems of equations with `F\\b`, -but also the methods [`diag`](@ref), [`det`](@ref), and -[`logdet`](@ref) are defined for `F`. -You can also extract individual factors from `F`, using `F[:L]`. -However, since pivoting is on by default, the factorization is internally -represented as `A == P'*L*L'*P` with a permutation matrix `P`; -using just `L` without accounting for `P` will give incorrect answers. -To include the effects of permutation, -it's typically preferable to extract "combined" factors like `PtL = F[:PtL]` -(the equivalent of `P'*L`) and `LtP = F[:UP]` (the equivalent of `L'*P`). - -Setting the optional `shift` keyword argument computes the factorization of -`A+shift*I` instead of `A`. If the `perm` argument is nonempty, -it should be a permutation of `1:size(A,1)` giving the ordering to use -(instead of CHOLMOD's default AMD ordering). - -!!! note - This method uses the CHOLMOD library from SuiteSparse, which only supports - doubles or complex doubles. Input matrices not of those element types will - be converted to `SparseMatrixCSC{Float64}` or `SparseMatrixCSC{Complex128}` - as appropriate. - - Many other functions from CHOLMOD are wrapped but not exported from the - `Base.SparseArrays.CHOLMOD` module. -""" -cholfact(A::Union{SparseMatrixCSC{T}, SparseMatrixCSC{Complex{T}}, - Symmetric{T,SparseMatrixCSC{T,SuiteSparse_long}}, - Hermitian{Complex{T},SparseMatrixCSC{Complex{T},SuiteSparse_long}}, - Hermitian{T,SparseMatrixCSC{T,SuiteSparse_long}}}; - kws...) where {T<:Real} = cholfact(Sparse(A); kws...) - - -function ldltfact!(F::Factor{Tv}, A::Sparse{Tv}; shift::Real=0.0) where Tv - cm = common() - - # Compute the numerical factorization - factorize_p!(A, shift, F, cm) - - s = unsafe_load(get(F.p)) - s.minor < size(A, 1) && throw(Base.LinAlg.ArgumentError("matrix has one or more zero pivots")) - return F -end - -""" - ldltfact!(F::Factor, A; shift = 0.0) -> CHOLMOD.Factor - -Compute the ``LDL'`` factorization of `A`, reusing the symbolic factorization `F`. -`A` must be a [`SparseMatrixCSC`](@ref) or a [`Symmetric`](@ref)/[`Hermitian`](@ref) -view of a `SparseMatrixCSC`. Note that even if `A` doesn't -have the type tag, it must still be symmetric or Hermitian. - -See also [`ldltfact`](@ref). - -!!! note - This method uses the CHOLMOD library from SuiteSparse, which only supports - doubles or complex doubles. Input matrices not of those element types will - be converted to `SparseMatrixCSC{Float64}` or `SparseMatrixCSC{Complex128}` - as appropriate. -""" -ldltfact!(F::Factor, A::Union{SparseMatrixCSC{T}, - SparseMatrixCSC{Complex{T}}, - Symmetric{T,SparseMatrixCSC{T,SuiteSparse_long}}, - Hermitian{Complex{T},SparseMatrixCSC{Complex{T},SuiteSparse_long}}, - Hermitian{T,SparseMatrixCSC{T,SuiteSparse_long}}}; - shift = 0.0) where {T<:Real} = - ldltfact!(F, Sparse(A), shift = shift) - -function ldltfact(A::Sparse; shift::Real=0.0, - perm::AbstractVector{SuiteSparse_long}=SuiteSparse_long[]) - - cm = defaults(common()) - set_print_level(cm, 0) - - # Makes it an LDLt - unsafe_store!(common_final_ll, 0) - # Really make sure it's an LDLt by avoiding supernodal factorization - unsafe_store!(common_supernodal, 0) - - # Compute the symbolic factorization - F = fact_(A, cm; perm = perm) - - # Compute the numerical factorization - ldltfact!(F, A; shift = shift) - - s = unsafe_load(get(F.p)) - if s.minor < size(A, 1) - throw(Base.LinAlg.ArgumentError("matrix has one or more zero pivots")) - end - return F -end - -""" - ldltfact(A; shift = 0.0, perm=Int[]) -> CHOLMOD.Factor - -Compute the ``LDL'`` factorization of a sparse matrix `A`. -`A` must be a [`SparseMatrixCSC`](@ref) or a [`Symmetric`](@ref)/[`Hermitian`](@ref) -view of a `SparseMatrixCSC`. Note that even if `A` doesn't -have the type tag, it must still be symmetric or Hermitian. -A fill-reducing permutation is used. `F = ldltfact(A)` is most frequently -used to solve systems of equations `A*x = b` with `F\\b`. The returned -factorization object `F` also supports the methods [`diag`](@ref), -[`det`](@ref), [`logdet`](@ref), and [`inv`](@ref). -You can extract individual factors from `F` using `F[:L]`. -However, since pivoting is on by default, the factorization is internally -represented as `A == P'*L*D*L'*P` with a permutation matrix `P`; -using just `L` without accounting for `P` will give incorrect answers. -To include the effects of permutation, it is typically preferable to extract -"combined" factors like `PtL = F[:PtL]` (the equivalent of -`P'*L`) and `LtP = F[:UP]` (the equivalent of `L'*P`). -The complete list of supported factors is `:L, :PtL, :D, :UP, :U, :LD, :DU, :PtLD, :DUP`. - -Setting the optional `shift` keyword argument computes the factorization of -`A+shift*I` instead of `A`. If the `perm` argument is nonempty, -it should be a permutation of `1:size(A,1)` giving the ordering to use -(instead of CHOLMOD's default AMD ordering). - -!!! note - This method uses the CHOLMOD library from SuiteSparse, which only supports - doubles or complex doubles. Input matrices not of those element types will - be converted to `SparseMatrixCSC{Float64}` or `SparseMatrixCSC{Complex128}` - as appropriate. - - Many other functions from CHOLMOD are wrapped but not exported from the - `Base.SparseArrays.CHOLMOD` module. -""" -ldltfact(A::Union{SparseMatrixCSC{T},SparseMatrixCSC{Complex{T}}, - Symmetric{T,SparseMatrixCSC{T,SuiteSparse_long}}, - Hermitian{Complex{T},SparseMatrixCSC{Complex{T},SuiteSparse_long}}, - Hermitian{T,SparseMatrixCSC{T,SuiteSparse_long}}}; - kws...) where {T<:Real} = ldltfact(Sparse(A); kws...) - -## Solvers - -for (T, f) in ((:Dense, :solve), (:Sparse, :spsolve)) - @eval begin - # Solve Lx = b and L'x=b where A = L*L' - function (\)(L::FactorComponent{T,:L}, B::$T) where T - ($f)(CHOLMOD_L, Factor(L), B) - end - function (\)(L::FactorComponent{T,:U}, B::$T) where T - ($f)(CHOLMOD_Lt, Factor(L), B) - end - # Solve PLx = b and L'P'x=b where A = P*L*L'*P' - function (\)(L::FactorComponent{T,:PtL}, B::$T) where T - F = Factor(L) - ($f)(CHOLMOD_L, F, ($f)(CHOLMOD_P, F, B)) # Confusingly, CHOLMOD_P solves P'x = b - end - function (\)(L::FactorComponent{T,:UP}, B::$T) where T - F = Factor(L) - ($f)(CHOLMOD_Pt, F, ($f)(CHOLMOD_Lt, F, B)) - end - # Solve various equations for A = L*D*L' and A = P*L*D*L'*P' - function (\)(L::FactorComponent{T,:D}, B::$T) where T - ($f)(CHOLMOD_D, Factor(L), B) - end - function (\)(L::FactorComponent{T,:LD}, B::$T) where T - ($f)(CHOLMOD_LD, Factor(L), B) - end - function (\)(L::FactorComponent{T,:DU}, B::$T) where T - ($f)(CHOLMOD_DLt, Factor(L), B) - end - function (\)(L::FactorComponent{T,:PtLD}, B::$T) where T - F = Factor(L) - ($f)(CHOLMOD_LD, F, ($f)(CHOLMOD_P, F, B)) - end - function (\)(L::FactorComponent{T,:DUP}, B::$T) where T - F = Factor(L) - ($f)(CHOLMOD_Pt, F, ($f)(CHOLMOD_DLt, F, B)) - end - end -end - -SparseVecOrMat{Tv,Ti} = Union{SparseVector{Tv,Ti}, SparseMatrixCSC{Tv,Ti}} - -function (\)(L::FactorComponent, b::Vector) - reshape(convert(Matrix, L\Dense(b)), length(b)) -end -function (\)(L::FactorComponent, B::Matrix) - convert(Matrix, L\Dense(B)) -end -function (\)(L::FactorComponent, B::SparseVecOrMat) - sparse(L\Sparse(B,0)) -end - -Ac_ldiv_B(L::FactorComponent, B) = ctranspose(L)\B -Ac_ldiv_B(L::FactorComponent, B::RowVector) = ctranspose(L)\B # ambiguity - -(\)(L::Factor{T}, B::Dense{T}) where {T<:VTypes} = solve(CHOLMOD_A, L, B) -# Explicit typevars are necessary to avoid ambiguities with defs in linalg/factorizations.jl -# Likewise the two following explicit Vector and Matrix defs (rather than a single VecOrMat) -(\)(L::Factor{T}, B::Vector{Complex{T}}) where {T<:Float64} = complex.(L\real(B), L\imag(B)) -(\)(L::Factor{T}, B::Matrix{Complex{T}}) where {T<:Float64} = complex.(L\real(B), L\imag(B)) -(\)(L::Factor{T}, b::StridedVector) where {T<:VTypes} = Vector(L\convert(Dense{T}, b)) -(\)(L::Factor{T}, B::StridedMatrix) where {T<:VTypes} = Matrix(L\convert(Dense{T}, B)) -(\)(L::Factor, B::Sparse) = spsolve(CHOLMOD_A, L, B) -# When right hand side is sparse, we have to ensure that the rhs is not marked as symmetric. -(\)(L::Factor, B::SparseVecOrMat) = sparse(spsolve(CHOLMOD_A, L, Sparse(B, 0))) - -Ac_ldiv_B(L::Factor, B::Dense) = solve(CHOLMOD_A, L, B) -Ac_ldiv_B(L::Factor, B::VecOrMat) = convert(Matrix, solve(CHOLMOD_A, L, Dense(B))) -Ac_ldiv_B(L::Factor, B::Sparse) = spsolve(CHOLMOD_A, L, B) -Ac_ldiv_B(L::Factor, B::SparseVecOrMat) = Ac_ldiv_B(L, Sparse(B)) - -for f in (:\, :Ac_ldiv_B) - @eval function ($f)(A::Union{Symmetric{Float64,SparseMatrixCSC{Float64,SuiteSparse_long}}, - Hermitian{Float64,SparseMatrixCSC{Float64,SuiteSparse_long}}, - Hermitian{Complex{Float64},SparseMatrixCSC{Complex{Float64},SuiteSparse_long}}}, B::StridedVecOrMat) - try - return ($f)(cholfact(A), B) - catch e - isa(e, LinAlg.PosDefException) || rethrow(e) - return ($f)(ldltfact(A) , B) - end - end -end - -## Other convenience methods -function diag(F::Factor{Tv}) where Tv - f = unsafe_load(get(F.p)) - fsuper = f.super - fpi = f.pi - res = Base.zeros(Tv, Int(f.n)) - xv = f.x - if f.is_super!=0 - px = f.px - pos = 1 - for i in 1:f.nsuper - base = unsafe_load(px, i) + 1 - res[pos] = unsafe_load(xv, base) - pos += 1 - for j in 1:unsafe_load(fsuper, i + 1) - unsafe_load(fsuper, i) - 1 - res[pos] = unsafe_load(xv, base + j*(unsafe_load(fpi, i + 1) - - unsafe_load(fpi, i) + 1)) - pos += 1 - end - end - else - c0 = f.p - r0 = f.i - xv = f.x - for j in 1:f.n - jj = unsafe_load(c0, j) + 1 - assert(unsafe_load(r0, jj) == j - 1) - res[j] = unsafe_load(xv, jj) - end - end - res -end - -function logdet(F::Factor{Tv}) where Tv<:VTypes - f = unsafe_load(get(F.p)) - res = zero(Tv) - for d in diag(F); res += log(abs(d)) end - f.is_ll!=0 ? 2res : res -end - -det(L::Factor) = exp(logdet(L)) - -function isposdef(A::SparseMatrixCSC{<:VTypes,SuiteSparse_long}) - if !ishermitian(A) - return false - end - try - f = cholfact(A) - catch e - isa(e, LinAlg.PosDefException) || rethrow(e) - return false - end - true -end - -function ishermitian(A::Sparse{Float64}) - s = unsafe_load(A.p) - if s.stype != 0 - return true - else - i = symmetry(A, 1)[1] - if i < 0 - throw(CHOLMODException("negative value returned from CHOLMOD's symmetry function. This - is either because the indices are not sorted or because of a memory error")) - end - return i == MM_SYMMETRIC || i == MM_SYMMETRIC_POSDIAG - end -end -function ishermitian(A::Sparse{Complex{Float64}}) - s = unsafe_load(A.p) - if s.stype != 0 - return true - else - i = symmetry(A, 1)[1] - if i < 0 - throw(CHOLMODException("negative value returned from CHOLMOD's symmetry function. This - is either because the indices are not sorted or because of a memory error")) - end - return i == MM_HERMITIAN || i == MM_HERMITIAN_POSDIAG - end -end - -(*)(A::Symmetric{Float64,SparseMatrixCSC{Float64,Ti}}, - B::SparseVecOrMat{Float64,Ti}) where {Ti} = sparse(Sparse(A)*Sparse(B)) -(*)(A::Hermitian{Complex{Float64},SparseMatrixCSC{Complex{Float64},Ti}}, - B::SparseVecOrMat{Complex{Float64},Ti}) where {Ti} = sparse(Sparse(A)*Sparse(B)) -(*)(A::Hermitian{Float64,SparseMatrixCSC{Float64,Ti}}, - B::SparseVecOrMat{Float64,Ti}) where {Ti} = sparse(Sparse(A)*Sparse(B)) - -(*)(A::SparseVecOrMat{Float64,Ti}, - B::Symmetric{Float64,SparseMatrixCSC{Float64,Ti}}) where {Ti} = sparse(Sparse(A)*Sparse(B)) -(*)(A::SparseVecOrMat{Complex{Float64},Ti}, - B::Hermitian{Complex{Float64},SparseMatrixCSC{Complex{Float64},Ti}}) where {Ti} = sparse(Sparse(A)*Sparse(B)) -(*)(A::SparseVecOrMat{Float64,Ti}, - B::Hermitian{Float64,SparseMatrixCSC{Float64,Ti}}) where {Ti} = sparse(Sparse(A)*Sparse(B)) - -end #module diff --git a/julia-0.6.3/share/julia/base/sparse/cholmod_h.jl b/julia-0.6.3/share/julia/base/sparse/cholmod_h.jl deleted file mode 100644 index 7b7b110..0000000 --- a/julia-0.6.3/share/julia/base/sparse/cholmod_h.jl +++ /dev/null @@ -1,79 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -## CHOLMOD -const TRUE = Int32(1) -const FALSE = Int32(0) - -## itype defines the types of integer used: -const INT = Int32(0) # all integer arrays are int -const INTLONG = Int32(1) # most are int, some are SuiteSparse_long -const LONG = Int32(2) # all integer arrays are SuiteSparse_long -ityp(::Type{Int32}) = INT -ityp(::Type{Int64}) = LONG - -## dtype defines what the numerical type is (double or float): -const DOUBLE = Int32(0) # all numerical values are double -const SINGLE = Int32(1) # all numerical values are float -dtyp(::Type{Float32}) = SINGLE -dtyp(::Type{Float64}) = DOUBLE -dtyp(::Type{Complex64}) = SINGLE -dtyp(::Type{Complex128}) = DOUBLE - -## xtype defines the kind of numerical values used: -const PATTERN = Int32(0) # pattern only, no numerical values -const REAL = Int32(1) # a real matrix -const COMPLEX = Int32(2) # a complex matrix (ANSI C99 compatible) -const ZOMPLEX = Int32(3) # a complex matrix (MATLAB compatible) -xtyp(::Type{Float32}) = REAL -xtyp(::Type{Float64}) = REAL -xtyp(::Type{Complex64}) = COMPLEX -xtyp(::Type{Complex128}) = COMPLEX - -## Scaling modes, selected by the scale input parameter: -const SCALAR = Int32(0) # A = s*A -const ROW = Int32(1) # A = diag(s)*A -const COL = Int32(2) # A = A*diag(s) -const SYM = Int32(3) # A = diag(s)*A*diag(s) - -## Types of systems to solve -const CHOLMOD_A = Int32(0) # solve Ax=b -const CHOLMOD_LDLt = Int32(1) # solve LDL'x=b -const CHOLMOD_LD = Int32(2) # solve LDx=b -const CHOLMOD_DLt = Int32(3) # solve DL'x=b -const CHOLMOD_L = Int32(4) # solve Lx=b -const CHOLMOD_Lt = Int32(5) # solve L'x=b -const CHOLMOD_D = Int32(6) # solve Dx=b -const CHOLMOD_P = Int32(7) # permute x=Px -const CHOLMOD_Pt = Int32(8) # permute x=P'x - -# Symmetry types -const EMPTY =-1 -const MM_RECTANGULAR = 1 -const MM_UNSYMMETRIC = 2 -const MM_SYMMETRIC = 3 -const MM_HERMITIAN = 4 -const MM_SKEW_SYMMETRIC = 5 -const MM_SYMMETRIC_POSDIAG = 6 -const MM_HERMITIAN_POSDIAG = 7 - -# check the size of SuiteSparse_long -if Int(ccall((:jl_cholmod_sizeof_long, :libsuitesparse_wrapper),Csize_t,())) == 4 - const SuiteSparse_long = Int32 - const IndexTypes = (:Int32,) - const ITypes = Union{Int32} -else - const SuiteSparse_long = Int64 - const IndexTypes = (:Int32, :Int64) - const ITypes = Union{Int32, Int64} -end - -const VTypes = Union{Complex128, Float64} -const VRealTypes = Union{Float64} - -mutable struct CHOLMODException <: Exception - msg::AbstractString -end - -macro isok(A) - :($(esc(A)) == TRUE || throw(CHOLMODException(""))) -end diff --git a/julia-0.6.3/share/julia/base/sparse/higherorderfns.jl b/julia-0.6.3/share/julia/base/sparse/higherorderfns.jl deleted file mode 100644 index 3e70ec2..0000000 --- a/julia-0.6.3/share/julia/base/sparse/higherorderfns.jl +++ /dev/null @@ -1,1127 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -module HigherOrderFns - -# This module provides higher order functions specialized for sparse arrays, -# particularly map[!]/broadcast[!] for SparseVectors and SparseMatrixCSCs at present. -import Base: map, map!, broadcast, broadcast! -import Base.Broadcast: _containertype, promote_containertype, - broadcast_indices, broadcast_c, broadcast_c! - -using Base: front, tail, to_shape -using ..SparseArrays: SparseVector, SparseMatrixCSC, AbstractSparseVector, - AbstractSparseMatrix, AbstractSparseArray, indtype - -# This module is organized as follows: -# (1) Define a common interface to SparseVectors and SparseMatrixCSCs sufficient for -# map[!]/broadcast[!]'s purposes. The methods below are written against this interface. -# (2) Define entry points for map[!] (short children of _map_[not]zeropres!). -# (3) Define entry points for broadcast[!] (short children of _broadcast_[not]zeropres!). -# (4) Define _map_[not]zeropres! specialized for a single (input) sparse vector/matrix. -# (5) Define _map_[not]zeropres! specialized for a pair of (input) sparse vectors/matrices. -# (6) Define general _map_[not]zeropres! capable of handling >2 (input) sparse vectors/matrices. -# (7) Define _broadcast_[not]zeropres! specialized for a single (input) sparse vector/matrix. -# (8) Define _broadcast_[not]zeropres! specialized for a pair of (input) sparse vectors/matrices. -# (9) Define general _broadcast_[not]zeropres! capable of handling >2 (input) sparse vectors/matrices. -# (10) Define (broadcast[!]) methods handling combinations of broadcast scalars and sparse vectors/matrices. -# (11) Define (broadcast[!]) methods handling combinations of scalars, sparse vectors/matrices, -# structured matrices, and one- and two-dimensional Arrays. -# (12) Define (map[!]) methods handling combinations of sparse and structured matrices. - - -# (1) The definitions below provide a common interface to sparse vectors and matrices -# sufficient for the purposes of map[!]/broadcast[!]. This interface treats sparse vectors -# as n-by-one sparse matrices which, though technically incorrect, is how broacast[!] views -# sparse vectors in practice. -SparseVecOrMat = Union{SparseVector,SparseMatrixCSC} -@inline numrows(A::SparseVector) = A.n -@inline numrows(A::SparseMatrixCSC) = A.m -@inline numcols(A::SparseVector) = 1 -@inline numcols(A::SparseMatrixCSC) = A.n -# numrows and numcols respectively yield size(A, 1) and size(A, 2), but avoid a branch -@inline columns(A::SparseVector) = 1 -@inline columns(A::SparseMatrixCSC) = 1:A.n -@inline colrange(A::SparseVector, j) = 1:length(A.nzind) -@inline colrange(A::SparseMatrixCSC, j) = nzrange(A, j) -@inline colstartind(A::SparseVector, j) = one(indtype(A)) -@inline colboundind(A::SparseVector, j) = convert(indtype(A), length(A.nzind) + 1) -@inline colstartind(A::SparseMatrixCSC, j) = A.colptr[j] -@inline colboundind(A::SparseMatrixCSC, j) = A.colptr[j + 1] -@inline storedinds(A::SparseVector) = A.nzind -@inline storedinds(A::SparseMatrixCSC) = A.rowval -@inline storedvals(A::SparseVecOrMat) = A.nzval -@inline setcolptr!(A::SparseVector, j, val) = val -@inline setcolptr!(A::SparseMatrixCSC, j, val) = A.colptr[j] = val -function trimstorage!(A::SparseVecOrMat, maxstored) - resize!(storedinds(A), maxstored) - resize!(storedvals(A), maxstored) - return maxstored -end -function expandstorage!(A::SparseVecOrMat, maxstored) - length(storedinds(A)) < maxstored && resize!(storedinds(A), maxstored) - length(storedvals(A)) < maxstored && resize!(storedvals(A), maxstored) - return maxstored -end - - -# (2) map[!] entry points -map(f::Tf, A::SparseVector) where {Tf} = _noshapecheck_map(f, A) -map(f::Tf, A::SparseMatrixCSC) where {Tf} = _noshapecheck_map(f, A) -map(f::Tf, A::SparseMatrixCSC, Bs::Vararg{SparseMatrixCSC,N}) where {Tf,N} = - (_checksameshape(A, Bs...); _noshapecheck_map(f, A, Bs...)) -map(f::Tf, A::SparseVecOrMat, Bs::Vararg{SparseVecOrMat,N}) where {Tf,N} = - (_checksameshape(A, Bs...); _noshapecheck_map(f, A, Bs...)) -map!(f::Tf, C::SparseMatrixCSC, A::SparseMatrixCSC, Bs::Vararg{SparseMatrixCSC,N}) where {Tf,N} = - (_checksameshape(C, A, Bs...); _noshapecheck_map!(f, C, A, Bs...)) -map!(f::Tf, C::SparseVecOrMat, A::SparseVecOrMat, Bs::Vararg{SparseVecOrMat,N}) where {Tf,N} = - (_checksameshape(C, A, Bs...); _noshapecheck_map!(f, C, A, Bs...)) -function _noshapecheck_map!(f::Tf, C::SparseVecOrMat, A::SparseVecOrMat, Bs::Vararg{SparseVecOrMat,N}) where {Tf,N} - fofzeros = f(_zeros_eltypes(A, Bs...)...) - fpreszeros = _iszero(fofzeros) - return fpreszeros ? _map_zeropres!(f, C, A, Bs...) : - _map_notzeropres!(f, fofzeros, C, A, Bs...) -end -function _noshapecheck_map(f::Tf, A::SparseVecOrMat, Bs::Vararg{SparseVecOrMat,N}) where {Tf,N} - fofzeros = f(_zeros_eltypes(A, Bs...)...) - fpreszeros = _iszero(fofzeros) - maxnnzC = fpreszeros ? min(length(A), _sumnnzs(A, Bs...)) : length(A) - entrytypeC = Base.Broadcast._broadcast_eltype(f, A, Bs...) - indextypeC = _promote_indtype(A, Bs...) - C = _allocres(size(A), indextypeC, entrytypeC, maxnnzC) - return fpreszeros ? _map_zeropres!(f, C, A, Bs...) : - _map_notzeropres!(f, fofzeros, C, A, Bs...) -end -# (3) broadcast[!] entry points -broadcast(f::Tf, A::SparseVector) where {Tf} = _noshapecheck_map(f, A) -broadcast(f::Tf, A::SparseMatrixCSC) where {Tf} = _noshapecheck_map(f, A) -function broadcast!(f::Tf, C::SparseVecOrMat) where Tf - isempty(C) && return _finishempty!(C) - fofnoargs = f() - if _iszero(fofnoargs) # f() is zero, so empty C - trimstorage!(C, 0) - _finishempty!(C) - else # f() is nonzero, so densify C and fill with independent calls to f() - _densestructure!(C) - storedvals(C)[1] = fofnoargs - broadcast!(f, view(storedvals(C), 2:length(storedvals(C)))) - end - return C -end -function broadcast!(f::Tf, C::SparseVecOrMat, A::SparseVecOrMat, Bs::Vararg{SparseVecOrMat,N}) where {Tf,N} - _aresameshape(C, A, Bs...) && return _noshapecheck_map!(f, C, A, Bs...) - Base.Broadcast.check_broadcast_indices(indices(C), A, Bs...) - fofzeros = f(_zeros_eltypes(A, Bs...)...) - fpreszeros = _iszero(fofzeros) - return fpreszeros ? _broadcast_zeropres!(f, C, A, Bs...) : - _broadcast_notzeropres!(f, fofzeros, C, A, Bs...) -end -# the following three similar defs are necessary for type stability in the mixed vector/matrix case -broadcast(f::Tf, A::SparseVector, Bs::Vararg{SparseVector,N}) where {Tf,N} = - _aresameshape(A, Bs...) ? _noshapecheck_map(f, A, Bs...) : _diffshape_broadcast(f, A, Bs...) -broadcast(f::Tf, A::SparseMatrixCSC, Bs::Vararg{SparseMatrixCSC,N}) where {Tf,N} = - _aresameshape(A, Bs...) ? _noshapecheck_map(f, A, Bs...) : _diffshape_broadcast(f, A, Bs...) -broadcast(f::Tf, A::SparseVecOrMat, Bs::Vararg{SparseVecOrMat,N}) where {Tf,N} = - _diffshape_broadcast(f, A, Bs...) -function _diffshape_broadcast(f::Tf, A::SparseVecOrMat, Bs::Vararg{SparseVecOrMat,N}) where {Tf,N} - fofzeros = f(_zeros_eltypes(A, Bs...)...) - fpreszeros = _iszero(fofzeros) - indextypeC = _promote_indtype(A, Bs...) - entrytypeC = Base.Broadcast._broadcast_eltype(f, A, Bs...) - shapeC = to_shape(Base.Broadcast.broadcast_indices(A, Bs...)) - maxnnzC = fpreszeros ? _checked_maxnnzbcres(shapeC, A, Bs...) : _densennz(shapeC) - C = _allocres(shapeC, indextypeC, entrytypeC, maxnnzC) - return fpreszeros ? _broadcast_zeropres!(f, C, A, Bs...) : - _broadcast_notzeropres!(f, fofzeros, C, A, Bs...) -end -# helper functions for map[!]/broadcast[!] entry points (and related methods below) -@inline _sumnnzs(A) = nnz(A) -@inline _sumnnzs(A, Bs...) = nnz(A) + _sumnnzs(Bs...) -@inline _iszero(x) = x == 0 -@inline _iszero(x::Number) = Base.iszero(x) -@inline _iszero(x::AbstractArray) = Base.iszero(x) -@inline _zeros_eltypes(A) = (zero(eltype(A)),) -@inline _zeros_eltypes(A, Bs...) = (zero(eltype(A)), _zeros_eltypes(Bs...)...) -@inline _promote_indtype(A) = indtype(A) -@inline _promote_indtype(A, Bs...) = promote_type(indtype(A), _promote_indtype(Bs...)) -@inline _aresameshape(A) = true -@inline _aresameshape(A, B) = size(A) == size(B) -@inline _aresameshape(A, B, Cs...) = _aresameshape(A, B) ? _aresameshape(B, Cs...) : false -@inline _checksameshape(As...) = _aresameshape(As...) || throw(DimensionMismatch("argument shapes must match")) -@inline _densennz(shape::NTuple{1}) = shape[1] -@inline _densennz(shape::NTuple{2}) = shape[1] * shape[2] -_maxnnzfrom(shape::NTuple{1}, A) = nnz(A) * div(shape[1], A.n) -_maxnnzfrom(shape::NTuple{2}, A::SparseVector) = nnz(A) * div(shape[1], A.n) * shape[2] -_maxnnzfrom(shape::NTuple{2}, A::SparseMatrixCSC) = nnz(A) * div(shape[1], A.m) * div(shape[2], A.n) -@inline _maxnnzfrom_each(shape, ::Tuple{}) = () -@inline _maxnnzfrom_each(shape, As) = (_maxnnzfrom(shape, first(As)), _maxnnzfrom_each(shape, tail(As))...) -@inline _unchecked_maxnnzbcres(shape, As::Tuple) = min(_densennz(shape), sum(_maxnnzfrom_each(shape, As))) -@inline _unchecked_maxnnzbcres(shape, As...) = _unchecked_maxnnzbcres(shape, As) -@inline _checked_maxnnzbcres(shape::NTuple{1}, As...) = shape[1] != 0 ? _unchecked_maxnnzbcres(shape, As) : 0 -@inline _checked_maxnnzbcres(shape::NTuple{2}, As...) = shape[1] != 0 && shape[2] != 0 ? _unchecked_maxnnzbcres(shape, As) : 0 -@inline function _allocres(shape::NTuple{1}, indextype, entrytype, maxnnz) - storedinds = Vector{indextype}(maxnnz) - storedvals = Vector{entrytype}(maxnnz) - return SparseVector(shape..., storedinds, storedvals) -end -@inline function _allocres(shape::NTuple{2}, indextype, entrytype, maxnnz) - pointers = Vector{indextype}(shape[2] + 1) - storedinds = Vector{indextype}(maxnnz) - storedvals = Vector{entrytype}(maxnnz) - return SparseMatrixCSC(shape..., pointers, storedinds, storedvals) -end -# Ambiguity killers, TODO: nix conflicting specializations -ambiguityfunnel(f::Tf, x, y) where {Tf} = _aresameshape(x, y) ? _noshapecheck_map(f, x, y) : _diffshape_broadcast(f, x, y) -broadcast(::typeof(+), x::SparseVector, y::SparseVector) = ambiguityfunnel(+, x, y) # base/sparse/sparsevectors.jl:1266 -broadcast(::typeof(-), x::SparseVector, y::SparseVector) = ambiguityfunnel(-, x, y) # base/sparse/sparsevectors.jl:1266 -broadcast(::typeof(*), x::SparseVector, y::SparseVector) = ambiguityfunnel(*, x, y) # base/sparse/sparsevectors.jl:1266 - - -# (4) _map_zeropres!/_map_notzeropres! specialized for a single sparse vector/matrix -"Stores only the nonzero entries of `map(f, Array(A))` in `C`." -function _map_zeropres!(f::Tf, C::SparseVecOrMat, A::SparseVecOrMat) where Tf - spaceC::Int = min(length(storedinds(C)), length(storedvals(C))) - Ck = 1 - @inbounds for j in columns(C) - setcolptr!(C, j, Ck) - for Ak in colrange(A, j) - Cx = f(storedvals(A)[Ak]) - if !_iszero(Cx) - Ck > spaceC && (spaceC = expandstorage!(C, Ck + nnz(A) - (Ak - 1))) - storedinds(C)[Ck] = storedinds(A)[Ak] - storedvals(C)[Ck] = Cx - Ck += 1 - end - end - end - @inbounds setcolptr!(C, numcols(C) + 1, Ck) - trimstorage!(C, Ck - 1) - return C -end -""" -Densifies `C`, storing `fillvalue` in place of each unstored entry in `A` and -`f(A[i])`/`f(A[i,j])` in place of each stored entry `A[i]`/`A[i,j]` in `A`. -""" -function _map_notzeropres!(f::Tf, fillvalue, C::SparseVecOrMat, A::SparseVecOrMat) where Tf - # Build dense matrix structure in C, expanding storage if necessary - _densestructure!(C) - # Populate values - fill!(storedvals(C), fillvalue) - @inbounds for (j, jo) in zip(columns(C), _densecoloffsets(C)) - for Ak in colrange(A, j) - Cx = f(storedvals(A)[Ak]) - Cx != fillvalue && (storedvals(C)[jo + storedinds(A)[Ak]] = Cx) - end - end - # NOTE: Combining the fill! above into the loop above to avoid multiple sweeps over / - # nonsequential access of storedvals(C) does not appear to improve performance. - return C -end -# helper functions for these methods and some of those below -@inline _densecoloffsets(A::SparseVector) = 0 -@inline _densecoloffsets(A::SparseMatrixCSC) = 0:A.m:(A.m*(A.n - 1)) -function _densestructure!(A::SparseVector) - expandstorage!(A, A.n) - copy!(A.nzind, 1:A.n) - return A -end -function _densestructure!(A::SparseMatrixCSC) - nnzA = A.m * A.n - expandstorage!(A, nnzA) - copy!(A.colptr, 1:A.m:(nnzA + 1)) - for k in _densecoloffsets(A) - copy!(A.rowval, k + 1, 1:A.m) - end - return A -end - - -# (5) _map_zeropres!/_map_notzeropres! specialized for a pair of sparse vectors/matrices -function _map_zeropres!(f::Tf, C::SparseVecOrMat, A::SparseVecOrMat, B::SparseVecOrMat) where Tf - spaceC::Int = min(length(storedinds(C)), length(storedvals(C))) - rowsentinelA = convert(indtype(A), numrows(C) + 1) - rowsentinelB = convert(indtype(B), numrows(C) + 1) - Ck = 1 - @inbounds for j in columns(C) - setcolptr!(C, j, Ck) - Ak, stopAk = colstartind(A, j), colboundind(A, j) - Bk, stopBk = colstartind(B, j), colboundind(B, j) - Ai = Ak < stopAk ? storedinds(A)[Ak] : rowsentinelA - Bi = Bk < stopBk ? storedinds(B)[Bk] : rowsentinelB - while true - if Ai == Bi - Ai == rowsentinelA && break # column complete - Cx, Ci::indtype(C) = f(storedvals(A)[Ak], storedvals(B)[Bk]), Ai - Ak += oneunit(Ak); Ai = Ak < stopAk ? storedinds(A)[Ak] : rowsentinelA - Bk += oneunit(Bk); Bi = Bk < stopBk ? storedinds(B)[Bk] : rowsentinelB - elseif Ai < Bi - Cx, Ci = f(storedvals(A)[Ak], zero(eltype(B))), Ai - Ak += oneunit(Ak); Ai = Ak < stopAk ? storedinds(A)[Ak] : rowsentinelA - else # Bi < Ai - Cx, Ci = f(zero(eltype(A)), storedvals(B)[Bk]), Bi - Bk += oneunit(Bk); Bi = Bk < stopBk ? storedinds(B)[Bk] : rowsentinelB - end - # NOTE: The ordering of the conditional chain above impacts which matrices this - # method performs best for. In the map situation (arguments have same shape, and - # likely same or similar stored entry pattern), the Ai == Bi and termination - # cases are equally or more likely than the Ai < Bi and Bi < Ai cases. Hence - # the ordering of the conditional chain above differs from that in the - # corresponding broadcast code (below). - if !_iszero(Cx) - Ck > spaceC && (spaceC = expandstorage!(C, Ck + (nnz(A) - (Ak - 1)) + (nnz(B) - (Bk - 1)))) - storedinds(C)[Ck] = Ci - storedvals(C)[Ck] = Cx - Ck += 1 - end - end - end - @inbounds setcolptr!(C, numcols(C) + 1, Ck) - trimstorage!(C, Ck - 1) - return C -end -function _map_notzeropres!(f::Tf, fillvalue, C::SparseVecOrMat, A::SparseVecOrMat, B::SparseVecOrMat) where Tf - # Build dense matrix structure in C, expanding storage if necessary - _densestructure!(C) - # Populate values - fill!(storedvals(C), fillvalue) - # NOTE: Combining this fill! into the loop below to avoid multiple sweeps over / - # nonsequential access of storedvals(C) does not appear to improve performance. - rowsentinelA = convert(indtype(A), numrows(A) + 1) - rowsentinelB = convert(indtype(B), numrows(B) + 1) - @inbounds for (j, jo) in zip(columns(C), _densecoloffsets(C)) - Ak, stopAk = colstartind(A, j), colboundind(A, j) - Bk, stopBk = colstartind(B, j), colboundind(B, j) - Ai = Ak < stopAk ? storedinds(A)[Ak] : rowsentinelA - Bi = Bk < stopBk ? storedinds(B)[Bk] : rowsentinelB - while true - if Ai == Bi - Ai == rowsentinelA && break # column complete - Cx, Ci::indtype(C) = f(storedvals(A)[Ak], storedvals(B)[Bk]), Ai - Ak += oneunit(Ak); Ai = Ak < stopAk ? storedinds(A)[Ak] : rowsentinelA - Bk += oneunit(Bk); Bi = Bk < stopBk ? storedinds(B)[Bk] : rowsentinelB - elseif Ai < Bi - Cx, Ci = f(storedvals(A)[Ak], zero(eltype(B))), Ai - Ak += oneunit(Ak); Ai = Ak < stopAk ? storedinds(A)[Ak] : rowsentinelA - else # Bi < Ai - Cx, Ci = f(zero(eltype(A)), storedvals(B)[Bk]), Bi - Bk += oneunit(Bk); Bi = Bk < stopBk ? storedinds(B)[Bk] : rowsentinelB - end - Cx != fillvalue && (storedvals(C)[jo + Ci] = Cx) - end - end - return C -end - - -# (6) _map_zeropres!/_map_notzeropres! for more than two sparse matrices / vectors -function _map_zeropres!(f::Tf, C::SparseVecOrMat, As::Vararg{SparseVecOrMat,N}) where {Tf,N} - spaceC::Int = min(length(storedinds(C)), length(storedvals(C))) - rowsentinel = numrows(C) + 1 - Ck = 1 - stopks = _colstartind_all(1, As) - @inbounds for j in columns(C) - setcolptr!(C, j, Ck) - ks = stopks - stopks = _colboundind_all(j, As) - rows = _rowforind_all(rowsentinel, ks, stopks, As) - activerow = min(rows...) - while activerow < rowsentinel - # activerows = _isactiverow_all(activerow, rows) - # Cx = f(_gatherargs(activerows, ks, As)...) - # ks = _updateind_all(activerows, ks) - # rows = _updaterow_all(rowsentinel, activerows, rows, ks, stopks, As) - vals, ks, rows = _fusedupdate_all(rowsentinel, activerow, rows, ks, stopks, As) - Cx = f(vals...) - if !_iszero(Cx) - Ck > spaceC && (spaceC = expandstorage!(C, Ck + min(length(C), _sumnnzs(As...)) - (sum(ks) - N))) - storedinds(C)[Ck] = activerow - storedvals(C)[Ck] = Cx - Ck += 1 - end - activerow = min(rows...) - end - end - @inbounds setcolptr!(C, numcols(C) + 1, Ck) - trimstorage!(C, Ck - 1) - return C -end -function _map_notzeropres!(f::Tf, fillvalue, C::SparseVecOrMat, As::Vararg{SparseVecOrMat,N}) where {Tf,N} - # Build dense matrix structure in C, expanding storage if necessary - _densestructure!(C) - # Populate values - fill!(storedvals(C), fillvalue) - # NOTE: Combining this fill! into the loop below to avoid multiple sweeps over / - # nonsequential access of C.nzval does not appear to improve performance. - rowsentinel = numrows(C) + 1 - stopks = _colstartind_all(1, As) - @inbounds for (j, jo) in zip(columns(C), _densecoloffsets(C)) - ks = stopks - stopks = _colboundind_all(j, As) - rows = _rowforind_all(rowsentinel, ks, stopks, As) - activerow = min(rows...) - while activerow < rowsentinel - # activerows = _isactiverow_all(activerow, rows) - # Cx = f(_gatherargs(activerows, ks, As)...) - # ks = _updateind_all(activerows, ks) - # rows = _updaterow_all(rowsentinel, activerows, rows, ks, stopks, As) - vals, ks, rows = _fusedupdate_all(rowsentinel, activerow, rows, ks, stopks, As) - Cx = f(vals...) - Cx != fillvalue && (storedvals(C)[jo + activerow] = Cx) - activerow = min(rows...) - end - end - return C -end -# helper methods for map/map! methods just above -@inline _colstartind(j, A) = colstartind(A, j) -@inline _colstartind_all(j, ::Tuple{}) = () -@inline _colstartind_all(j, As) = ( - _colstartind(j, first(As)), - _colstartind_all(j, tail(As))...) -@inline _colboundind(j, A) = colboundind(A, j) -@inline _colboundind_all(j, ::Tuple{}) = () -@inline _colboundind_all(j, As) = ( - _colboundind(j, first(As)), - _colboundind_all(j, tail(As))...) -@inline _rowforind(rowsentinel, k, stopk, A) = - k < stopk ? storedinds(A)[k] : convert(indtype(A), rowsentinel) -@inline _rowforind_all(rowsentinel, ::Tuple{}, ::Tuple{}, ::Tuple{}) = () -@inline _rowforind_all(rowsentinel, ks, stopks, As) = ( - _rowforind(rowsentinel, first(ks), first(stopks), first(As)), - _rowforind_all(rowsentinel, tail(ks), tail(stopks), tail(As))...) -# fusing the following defs. avoids a few branches, yielding 5-30% runtime reduction -# @inline _isactiverow(activerow, row) = row == activerow -# @inline _isactiverow_all(activerow, ::Tuple{}) = () -# @inline _isactiverow_all(activerow, rows) = ( -# _isactiverow(activerow, first(rows)), -# _isactiverow_all(activerow, tail(rows))...) -# @inline _gatherarg(isactiverow, k, A) = isactiverow ? storedvals(A)[k] : zero(eltype(A)) -# @inline _gatherargs(::Tuple{}, ::Tuple{}, ::Tuple{}) = () -# @inline _gatherargs(activerows, ks, As) = ( -# _gatherarg(first(activerows), first(ks), first(As)), -# _gatherargs(tail(activerows), tail(ks), tail(As))...) -# @inline _updateind(isactiverow, k) = isactiverow ? (k + oneunit(k)) : k -# @inline _updateind_all(::Tuple{}, ::Tuple{}) = () -# @inline _updateind_all(activerows, ks) = ( -# _updateind(first(activerows), first(ks)), -# _updateind_all(tail(activerows), tail(ks))...) -# @inline _updaterow(rowsentinel, isrowactive, presrow, k, stopk, A) = -# isrowactive ? (k < stopk ? storedinds(A)[k] : oftype(presrow, rowsentinel)) : presrow -# @inline _updaterow_all(rowsentinel, ::Tuple{}, ::Tuple{}, ::Tuple{}, ::Tuple{}, ::Tuple{}) = () -# @inline _updaterow_all(rowsentinel, activerows, rows, ks, stopks, As) = ( -# _updaterow(rowsentinel, first(activerows), first(rows), first(ks), first(stopks), first(As)), -# _updaterow_all(rowsentinel, tail(activerows), tail(rows), tail(ks), tail(stopks), tail(As))...) -@inline function _fusedupdate(rowsentinel, activerow, row, k, stopk, A) - # returns (val, nextk, nextrow) - if row == activerow - nextk = k + oneunit(k) - (storedvals(A)[k], nextk, (nextk < stopk ? storedinds(A)[nextk] : oftype(row, rowsentinel))) - else - (zero(eltype(A)), k, row) - end -end -@inline _fusedupdate_all(rowsentinel, activerow, rows, ks, stopks, As) = - _fusedupdate_all((#=vals=#), (#=nextks=#), (#=nextrows=#), rowsentinel, activerow, rows, ks, stopks, As) -@inline _fusedupdate_all(vals, nextks, nextrows, rowsent, activerow, ::Tuple{}, ::Tuple{}, ::Tuple{}, ::Tuple{}) = - (vals, nextks, nextrows) -@inline function _fusedupdate_all(vals, nextks, nextrows, rowsentinel, activerow, rows, ks, stopks, As) - val, nextk, nextrow = _fusedupdate(rowsentinel, activerow, first(rows), first(ks), first(stopks), first(As)) - return _fusedupdate_all((vals..., val), (nextks..., nextk), (nextrows..., nextrow), - rowsentinel, activerow, tail(rows), tail(ks), tail(stopks), tail(As)) -end - - -# (7) _broadcast_zeropres!/_broadcast_notzeropres! specialized for a single (input) sparse vector/matrix -function _broadcast_zeropres!(f::Tf, C::SparseVecOrMat, A::SparseVecOrMat) where Tf - isempty(C) && return _finishempty!(C) - spaceC::Int = min(length(storedinds(C)), length(storedvals(C))) - # C and A cannot have the same shape, as we directed that case to map in broadcast's - # entry point; here we need efficiently handle only heterogeneous C-A combinations where - # one or both of C and A has at least one singleton dimension. - # - # We first divide the cases into two groups: those in which the input argument does not - # expand vertically, and those in which the input argument expands vertically. - # - # Cases without vertical expansion - Ck = 1 - if numrows(A) == numrows(C) - @inbounds for j in columns(C) - setcolptr!(C, j, Ck) - bccolrangejA = numcols(A) == 1 ? colrange(A, 1) : colrange(A, j) - for Ak in bccolrangejA - Cx = f(storedvals(A)[Ak]) - if !_iszero(Cx) - Ck > spaceC && (spaceC = expandstorage!(C, _unchecked_maxnnzbcres(size(C), A))) - storedinds(C)[Ck] = storedinds(A)[Ak] - storedvals(C)[Ck] = Cx - Ck += 1 - end - end - end - # Cases with vertical expansion - else # numrows(A) != numrows(C) (=> numrows(A) == 1) - @inbounds for j in columns(C) - setcolptr!(C, j, Ck) - Ak, stopAk = numcols(A) == 1 ? (colstartind(A, 1), colboundind(A, 1)) : (colstartind(A, j), colboundind(A, j)) - Ax = Ak < stopAk ? storedvals(A)[Ak] : zero(eltype(A)) - fofAx = f(Ax) - # if fofAx is zero, then either A's jth column is empty, or A's jth column - # contains a nonzero value x but f(Ax) is nonetheless zero, so we need store - # nothing in C's jth column. if to the contrary fofAx is nonzero, then we must - # densely populate C's jth column with fofAx. - if !_iszero(fofAx) - for Ci::indtype(C) in 1:numrows(C) - Ck > spaceC && (spaceC = expandstorage!(C, _unchecked_maxnnzbcres(size(C), A))) - storedinds(C)[Ck] = Ci - storedvals(C)[Ck] = fofAx - Ck += 1 - end - end - end - end - @inbounds setcolptr!(C, numcols(C) + 1, Ck) - trimstorage!(C, Ck - 1) - return C -end -function _broadcast_notzeropres!(f::Tf, fillvalue, C::SparseVecOrMat, A::SparseVecOrMat) where Tf - # For information on this code, see comments in similar code in _broadcast_zeropres! above - # Build dense matrix structure in C, expanding storage if necessary - _densestructure!(C) - # Populate values - fill!(storedvals(C), fillvalue) - # Cases without vertical expansion - if numrows(A) == numrows(C) - @inbounds for (j, jo) in zip(columns(C), _densecoloffsets(C)) - bccolrangejA = numcols(A) == 1 ? colrange(A, 1) : colrange(A, j) - for Ak in bccolrangejA - Cx, Ci = f(storedvals(A)[Ak]), storedinds(A)[Ak] - Cx != fillvalue && (storedvals(C)[jo + Ci] = Cx) - end - end - # Cases with vertical expansion - else # numrows(A) != numrows(C) (=> numrows(A) == 1) - @inbounds for (j, jo) in zip(columns(C), _densecoloffsets(C)) - Ak, stopAk = numcols(A) == 1 ? (colstartind(A, 1), colboundind(A, 1)) : (colstartind(A, j), colboundind(A, j)) - Ax = Ak < stopAk ? storedvals(A)[Ak] : zero(eltype(A)) - fofAx = f(Ax) - fofAx != fillvalue && (storedvals(C)[(jo + 1):(jo + numrows(C))] = fofAx) - end - end - return C -end - - -# (8) _broadcast_zeropres!/_broadcast_notzeropres! specialized for a pair of (input) sparse vectors/matrices -function _broadcast_zeropres!(f::Tf, C::SparseVecOrMat, A::SparseVecOrMat, B::SparseVecOrMat) where Tf - isempty(C) && return _finishempty!(C) - spaceC::Int = min(length(storedinds(C)), length(storedvals(C))) - rowsentinelA = convert(indtype(A), numrows(C) + 1) - rowsentinelB = convert(indtype(B), numrows(C) + 1) - # C, A, and B cannot all have the same shape, as we directed that case to map in broadcast's - # entry point; here we need efficiently handle only heterogeneous combinations of mats/vecs - # with no singleton dimensions, one singleton dimension, and two singleton dimensions. - # Cases involving objects with two singleton dimensions should be rare and optimizing - # that case complicates the code appreciably, so we largely ignore that case's - # performance below. - # - # We first divide the cases into two groups: those in which neither input argument - # expands vertically, and those in which at least one argument expands vertically. - # - # NOTE: Placing the loops over columns outside the conditional chain segregating - # argument shape combinations eliminates some code replication but unfortunately - # hurts performance appreciably in some cases. - # - # Cases without vertical expansion - Ck = 1 - if numrows(A) == numrows(B) == numrows(C) - @inbounds for j in columns(C) - setcolptr!(C, j, Ck) - Ak, stopAk = numcols(A) == 1 ? (colstartind(A, 1), colboundind(A, 1)) : (colstartind(A, j), colboundind(A, j)) - Bk, stopBk = numcols(B) == 1 ? (colstartind(B, 1), colboundind(B, 1)) : (colstartind(B, j), colboundind(B, j)) - # Restructuring this k/stopk code to avoid unnecessary colptr retrievals does - # not improve performance signicantly. Leave in this less complex form. - Ai = Ak < stopAk ? storedinds(A)[Ak] : rowsentinelA - Bi = Bk < stopBk ? storedinds(B)[Bk] : rowsentinelB - while true - if Ai != Bi - if Ai < Bi - Cx, Ci = f(storedvals(A)[Ak], zero(eltype(B))), Ai - Ak += oneunit(Ak); Ai = Ak < stopAk ? storedinds(A)[Ak] : rowsentinelA - else # Ai > Bi - Cx, Ci = f(zero(eltype(A)), storedvals(B)[Bk]), Bi - Bk += oneunit(Bk); Bi = Bk < stopBk ? storedinds(B)[Bk] : rowsentinelB - end - elseif #= Ai == Bi && =# Ai == rowsentinelA - break # column complete - else #= Ai == Bi != rowsentinel =# - Cx, Ci::indtype(C) = f(storedvals(A)[Ak], storedvals(B)[Bk]), Ai - Ak += oneunit(Ak); Ai = Ak < stopAk ? storedinds(A)[Ak] : rowsentinelA - Bk += oneunit(Bk); Bi = Bk < stopBk ? storedinds(B)[Bk] : rowsentinelB - end - # NOTE: The ordering of the conditional chain above impacts which matrices - # this method perform best for. In contrast to the map situation (arguments - # have same shape, and likely same or similar stored entry pattern), where - # the Ai == Bi and termination cases are equally or more likely than the - # Ai < Bi and Bi < Ai cases, in the broadcast situation (arguments have - # different shape, and likely largely disjoint expanded stored entry - # pattern) the Ai < Bi and Bi < Ai cases are equally or more likely than the - # Ai == Bi and termination cases. Hence the ordering of the conditional - # chain above differs from that in the corresponding map code. - if !_iszero(Cx) - Ck > spaceC && (spaceC = expandstorage!(C, _unchecked_maxnnzbcres(size(C), A, B))) - storedinds(C)[Ck] = Ci - storedvals(C)[Ck] = Cx - Ck += 1 - end - end - end - # Cases with vertical expansion - elseif numrows(A) == numrows(B) == 1 # && numrows(C) != 1, vertically expand both A and B - @inbounds for j in columns(C) - setcolptr!(C, j, Ck) - Ak, stopAk = numcols(A) == 1 ? (colstartind(A, 1), colboundind(A, 1)) : (colstartind(A, j), colboundind(A, j)) - Bk, stopBk = numcols(B) == 1 ? (colstartind(B, 1), colboundind(B, 1)) : (colstartind(B, j), colboundind(B, j)) - Ax = Ak < stopAk ? storedvals(A)[Ak] : zero(eltype(A)) - Bx = Bk < stopBk ? storedvals(B)[Bk] : zero(eltype(B)) - Cx = f(Ax, Bx) - if !_iszero(Cx) - for Ci::indtype(C) in 1:numrows(C) - Ck > spaceC && (spaceC = expandstorage!(C, _unchecked_maxnnzbcres(size(C), A, B))) - storedinds(C)[Ck] = Ci - storedvals(C)[Ck] = Cx - Ck += 1 - end - end - end - elseif numrows(A) == 1 # && numrows(B) == numrows(C) != 1 , vertically expand only A - @inbounds for j in columns(C) - setcolptr!(C, j, Ck) - Ak, stopAk = numcols(A) == 1 ? (colstartind(A, 1), colboundind(A, 1)) : (colstartind(A, j), colboundind(A, j)) - Bk, stopBk = numcols(B) == 1 ? (colstartind(B, 1), colboundind(B, 1)) : (colstartind(B, j), colboundind(B, j)) - Ax = Ak < stopAk ? storedvals(A)[Ak] : zero(eltype(A)) - fvAzB = f(Ax, zero(eltype(B))) - if _iszero(fvAzB) - # either A's jth column is empty, or A's jth column contains a nonzero value - # Ax but f(Ax, zero(eltype(B))) is nonetheless zero, so we can scan through - # B's jth column without storing every entry in C's jth column - while Bk < stopBk - Cx = f(Ax, storedvals(B)[Bk]) - if !_iszero(Cx) - Ck > spaceC && (spaceC = expandstorage!(C, _unchecked_maxnnzbcres(size(C), A, B))) - storedinds(C)[Ck] = storedinds(B)[Bk] - storedvals(C)[Ck] = Cx - Ck += 1 - end - Bk += oneunit(Bk) - end - else - # A's jth column is nonempty and f(Ax, zero(eltype(B))) is not zero, so - # we must store (likely) every entry in C's jth column - Bi = Bk < stopBk ? storedinds(B)[Bk] : rowsentinelB - for Ci::indtype(C) in 1:numrows(C) - if Bi == Ci - Cx = f(Ax, storedvals(B)[Bk]) - Bk += oneunit(Bk); Bi = Bk < stopBk ? storedinds(B)[Bk] : rowsentinelB - else - Cx = fvAzB - end - if !_iszero(Cx) - Ck > spaceC && (spaceC = expandstorage!(C, _unchecked_maxnnzbcres(size(C), A, B))) - storedinds(C)[Ck] = Ci - storedvals(C)[Ck] = Cx - Ck += 1 - end - end - end - end - else # numrows(B) == 1 && numrows(A) == numrows(C) != 1, vertically expand only B - @inbounds for j in columns(C) - setcolptr!(C, j, Ck) - Ak, stopAk = numcols(A) == 1 ? (colstartind(A, 1), colboundind(A, 1)) : (colstartind(A, j), colboundind(A, j)) - Bk, stopBk = numcols(B) == 1 ? (colstartind(B, 1), colboundind(B, 1)) : (colstartind(B, j), colboundind(B, j)) - Bx = Bk < stopBk ? storedvals(B)[Bk] : zero(eltype(B)) - fzAvB = f(zero(eltype(A)), Bx) - if _iszero(fzAvB) - # either B's jth column is empty, or B's jth column contains a nonzero value - # Bx but f(zero(eltype(A)), Bx) is nonetheless zero, so we can scan through - # A's jth column without storing every entry in C's jth column - while Ak < stopAk - Cx = f(storedvals(A)[Ak], Bx) - if !_iszero(Cx) - Ck > spaceC && (spaceC = expandstorage!(C, _unchecked_maxnnzbcres(size(C), A, B))) - storedinds(C)[Ck] = storedinds(A)[Ak] - storedvals(C)[Ck] = Cx - Ck += 1 - end - Ak += oneunit(Ak) - end - else - # B's jth column is nonempty and f(zero(eltype(A)), Bx) is not zero, so - # we must store (likely) every entry in C's jth column - Ai = Ak < stopAk ? storedinds(A)[Ak] : rowsentinelA - for Ci::indtype(C) in 1:numrows(C) - if Ai == Ci - Cx = f(storedvals(A)[Ak], Bx) - Ak += oneunit(Ak); Ai = Ak < stopAk ? storedinds(A)[Ak] : rowsentinelA - else - Cx = fzAvB - end - if !_iszero(Cx) - Ck > spaceC && (spaceC = expandstorage!(C, _unchecked_maxnnzbcres(size(C), A, B))) - storedinds(C)[Ck] = Ci - storedvals(C)[Ck] = Cx - Ck += 1 - end - end - end - end - end - @inbounds setcolptr!(C, numcols(C) + 1, Ck) - trimstorage!(C, Ck - 1) - return C -end -function _broadcast_notzeropres!(f::Tf, fillvalue, C::SparseVecOrMat, A::SparseVecOrMat, B::SparseVecOrMat) where Tf - # For information on this code, see comments in similar code in _broadcast_zeropres! above - # Build dense matrix structure in C, expanding storage if necessary - _densestructure!(C) - # Populate values - fill!(storedvals(C), fillvalue) - rowsentinelA = convert(indtype(A), numrows(C) + 1) - rowsentinelB = convert(indtype(B), numrows(C) + 1) - # Cases without vertical expansion - if numrows(A) == numrows(B) == numrows(C) - @inbounds for (j, jo) in zip(columns(C), _densecoloffsets(C)) - Ak, stopAk = numcols(A) == 1 ? (colstartind(A, 1), colboundind(A, 1)) : (colstartind(A, j), colboundind(A, j)) - Bk, stopBk = numcols(B) == 1 ? (colstartind(B, 1), colboundind(B, 1)) : (colstartind(B, j), colboundind(B, j)) - Ai = Ak < stopAk ? storedinds(A)[Ak] : rowsentinelA - Bi = Bk < stopBk ? storedinds(B)[Bk] : rowsentinelB - while true - if Ai < Bi - Cx, Ci = f(storedvals(A)[Ak], zero(eltype(B))), Ai - Ak += oneunit(Ak); Ai = Ak < stopAk ? storedinds(A)[Ak] : rowsentinelA - elseif Ai > Bi - Cx, Ci = f(zero(eltype(A)), storedvals(B)[Bk]), Bi - Bk += oneunit(Bk); Bi = Bk < stopBk ? storedinds(B)[Bk] : rowsentinelB - elseif #= Ai == Bi && =# Ai == rowsentinelA - break # column complete - else #= Ai == Bi != rowsentinel =# - Cx, Ci::indtype(C) = f(storedvals(A)[Ak], storedvals(B)[Bk]), Ai - Ak += oneunit(Ak); Ai = Ak < stopAk ? storedinds(A)[Ak] : rowsentinelA - Bk += oneunit(Bk); Bi = Bk < stopBk ? storedinds(B)[Bk] : rowsentinelB - end - Cx != fillvalue && (storedvals(C)[jo + Ci] = Cx) - end - end - # Cases with vertical expansion - elseif numrows(A) == numrows(B) == 1 # && numrows(C) != 1, vertically expand both A and B - @inbounds for (j, jo) in zip(columns(C), _densecoloffsets(C)) - Ak, stopAk = numcols(A) == 1 ? (colstartind(A, 1), colboundind(A, 1)) : (colstartind(A, j), colboundind(A, j)) - Bk, stopBk = numcols(B) == 1 ? (colstartind(B, 1), colboundind(B, 1)) : (colstartind(B, j), colboundind(B, j)) - Ax = Ak < stopAk ? storedvals(A)[Ak] : zero(eltype(A)) - Bx = Bk < stopBk ? storedvals(B)[Bk] : zero(eltype(B)) - Cx = f(Ax, Bx) - if Cx != fillvalue - for Ck::Int in (jo + 1):(jo + numrows(C)) - storedvals(C)[Ck] = Cx - end - end - end - elseif numrows(A) == 1 # && numrows(B) == numrows(C) != 1, vertically expand only A - @inbounds for (j, jo) in zip(columns(C), _densecoloffsets(C)) - Ak, stopAk = numcols(A) == 1 ? (colstartind(A, 1), colboundind(A, 1)) : (colstartind(A, j), colboundind(A, j)) - Bk, stopBk = numcols(B) == 1 ? (colstartind(B, 1), colboundind(B, 1)) : (colstartind(B, j), colboundind(B, j)) - Ax = Ak < stopAk ? storedvals(A)[Ak] : zero(eltype(A)) - fvAzB = f(Ax, zero(eltype(B))) - if _iszero(fvAzB) - while Bk < stopBk - Cx = f(Ax, storedvals(B)[Bk]) - Cx != fillvalue && (storedvals(C)[jo + storedinds(B)[Bk]] = Cx) - Bk += oneunit(Bk) - end - else - Bi = Bk < stopBk ? storedinds(B)[Bk] : rowsentinelB - for Ci::indtype(C) in 1:numrows(C) - if Bi == Ci - Cx = f(Ax, storedvals(B)[Bk]) - Bk += oneunit(Bk); Bi = Bk < stopBk ? storedinds(B)[Bk] : rowsentinelB - else - Cx = fvAzB - end - Cx != fillvalue && (storedvals(C)[jo + Ci] = Cx) - end - end - end - else # numrows(B) == 1 && numrows(A) == numrows(C) != 1, vertically expand only B - @inbounds for (j, jo) in zip(columns(C), _densecoloffsets(C)) - Ak, stopAk = numcols(A) == 1 ? (colstartind(A, 1), colboundind(A, 1)) : (colstartind(A, j), colboundind(A, j)) - Bk, stopBk = numcols(B) == 1 ? (colstartind(B, 1), colboundind(B, 1)) : (colstartind(B, j), colboundind(B, j)) - Bx = Bk < stopBk ? storedvals(B)[Bk] : zero(eltype(B)) - fzAvB = f(zero(eltype(A)), Bx) - if _iszero(fzAvB) - while Ak < stopAk - Cx = f(storedvals(A)[Ak], Bx) - Cx != fillvalue && (storedvals(C)[jo + storedinds(A)[Ak]] = Cx) - Ak += oneunit(Ak) - end - else - Ai = Ak < stopAk ? storedinds(A)[Ak] : rowsentinelA - for Ci::indtype(C) in 1:numrows(C) - if Ai == Ci - Cx = f(storedvals(A)[Ak], Bx) - Ak += oneunit(Ak); Ai = Ak < stopAk ? storedinds(A)[Ak] : rowsentinelA - else - Cx = fzAvB - end - Cx != fillvalue && (storedvals(C)[jo + Ci] = Cx) - end - end - end - end - return C -end -_finishempty!(C::SparseVector) = C -_finishempty!(C::SparseMatrixCSC) = (fill!(C.colptr, 1); C) - - -# (9) _broadcast_zeropres!/_broadcast_notzeropres! for more than two (input) sparse vectors/matrices -function _broadcast_zeropres!(f::Tf, C::SparseVecOrMat, As::Vararg{SparseVecOrMat,N}) where {Tf,N} - isempty(C) && return _finishempty!(C) - spaceC::Int = min(length(storedinds(C)), length(storedvals(C))) - expandsverts = _expandsvert_all(C, As) - expandshorzs = _expandshorz_all(C, As) - rowsentinel = numrows(C) + 1 - Ck = 1 - @inbounds for j in columns(C) - setcolptr!(C, j, Ck) - ks = _startindforbccol_all(j, expandshorzs, As) - stopks = _stopindforbccol_all(j, expandshorzs, As) - # Neither fusing ks and stopks construction, nor restructuring them to avoid repeated - # colptr lookups, improves performance significantly. So keep the less complex approach here. - isemptys = _isemptycol_all(ks, stopks) - defargs = _defargforcol_all(j, isemptys, expandsverts, ks, As) - rows = _initrowforcol_all(j, rowsentinel, isemptys, expandsverts, ks, As) - defaultCx = f(defargs...) - activerow = min(rows...) - if _iszero(defaultCx) # zero-preserving column scan - while activerow < rowsentinel - # activerows = _isactiverow_all(activerow, rows) - # Cx = f(_gatherbcargs(activerows, defargs, ks, As)...) - # ks = _updateind_all(activerows, ks) - # rows = _updaterow_all(rowsentinel, activerows, rows, ks, stopks, As) - args, ks, rows = _fusedupdatebc_all(rowsentinel, activerow, rows, defargs, ks, stopks, As) - Cx = f(args...) - if !_iszero(Cx) - Ck > spaceC && (spaceC = expandstorage!(C, _unchecked_maxnnzbcres(size(C), As))) - storedinds(C)[Ck] = activerow - storedvals(C)[Ck] = Cx - Ck += 1 - end - activerow = min(rows...) - end - else # zero-non-preserving column scan - for Ci in 1:numrows(C) - if Ci == activerow - # activerows = _isactiverow_all(activerow, rows) - # Cx = f(_gatherbcargs(activerows, defargs, ks, As)...) - # ks = _updateind_all(activerows, ks) - # rows = _updaterow_all(rowsentinel, activerows, rows, ks, stopks, As) - args, ks, rows = _fusedupdatebc_all(rowsentinel, activerow, rows, defargs, ks, stopks, As) - Cx = f(args...) - activerow = min(rows...) - else - Cx = defaultCx - end - if !_iszero(Cx) - Ck > spaceC && (spaceC = expandstorage!(C, _unchecked_maxnnzbcres(size(C), As))) - storedinds(C)[Ck] = Ci - storedvals(C)[Ck] = Cx - Ck += 1 - end - end - end - end - @inbounds setcolptr!(C, numcols(C) + 1, Ck) - trimstorage!(C, Ck - 1) - return C -end -function _broadcast_notzeropres!(f::Tf, fillvalue, C::SparseVecOrMat, As::Vararg{SparseVecOrMat,N}) where {Tf,N} - isempty(C) && return _finishempty!(C) - # Build dense matrix structure in C, expanding storage if necessary - _densestructure!(C) - # Populate values - fill!(storedvals(C), fillvalue) - expandsverts = _expandsvert_all(C, As) - expandshorzs = _expandshorz_all(C, As) - rowsentinel = numrows(C) + 1 - @inbounds for (j, jo) in zip(columns(C), _densecoloffsets(C)) - ks = _startindforbccol_all(j, expandshorzs, As) - stopks = _stopindforbccol_all(j, expandshorzs, As) - # Neither fusing ks and stopks construction, nor restructuring them to avoid repeated - # colptr lookups, improves performance significantly. So keep the less complex approach here. - isemptys = _isemptycol_all(ks, stopks) - defargs = _defargforcol_all(j, isemptys, expandsverts, ks, As) - rows = _initrowforcol_all(j, rowsentinel, isemptys, expandsverts, ks, As) - defaultCx = f(defargs...) - activerow = min(rows...) - if defaultCx == fillvalue # fillvalue-preserving column scan - while activerow < rowsentinel - # activerows = _isactiverow_all(activerow, rows) - # Cx = f(_gatherbcargs(activerows, defargs, ks, As)...) - # ks = _updateind_all(activerows, ks) - # rows = _updaterow_all(rowsentinel, activerows, rows, ks, stopks, As) - args, ks, rows = _fusedupdatebc_all(rowsentinel, activerow, rows, defargs, ks, stopks, As) - Cx = f(args...) - Cx != fillvalue && (storedvals(C)[jo + activerow] = Cx) - activerow = min(rows...) - end - else # fillvalue-non-preserving column scan - for Ci in 1:numrows(C) - if Ci == activerow - # activerows = _isactiverow_all(activerow, rows) - # Cx = f(_gatherbcargs(activerows, defargs, ks, As)...) - # ks = _updateind_all(activerows, ks) - # rows = _updaterow_all(rowsentinel, activerows, rows, ks, stopks, As) - args, ks, rows = _fusedupdatebc_all(rowsentinel, activerow, rows, defargs, ks, stopks, As) - Cx = f(args...) - activerow = min(rows...) - else - Cx = defaultCx - end - Cx != fillvalue && (storedvals(C)[jo + Ci] = Cx) - end - end - end - return C -end -# helper method for broadcast/broadcast! methods just above -@inline _expandsvert(C, A) = numrows(A) != numrows(C) -@inline _expandsvert_all(C, ::Tuple{}) = () -@inline _expandsvert_all(C, As) = (_expandsvert(C, first(As)), _expandsvert_all(C, tail(As))...) -@inline _expandshorz(C, A) = numcols(A) != numcols(C) -@inline _expandshorz_all(C, ::Tuple{}) = () -@inline _expandshorz_all(C, As) = (_expandshorz(C, first(As)), _expandshorz_all(C, tail(As))...) -@inline _startindforbccol(j, expandshorz, A) = expandshorz ? colstartind(A, 1) : colstartind(A, j) -@inline _startindforbccol_all(j, ::Tuple{}, ::Tuple{}) = () -@inline _startindforbccol_all(j, expandshorzs, As) = ( - _startindforbccol(j, first(expandshorzs), first(As)), - _startindforbccol_all(j, tail(expandshorzs), tail(As))...) -@inline _stopindforbccol(j, expandshorz, A) = expandshorz ? colboundind(A, 1) : colboundind(A, j) -@inline _stopindforbccol_all(j, ::Tuple{}, ::Tuple{}) = () -@inline _stopindforbccol_all(j, expandshorzs, As) = ( - _stopindforbccol(j, first(expandshorzs), first(As)), - _stopindforbccol_all(j, tail(expandshorzs), tail(As))...) -@inline _isemptycol(k, stopk) = k == stopk -@inline _isemptycol_all(::Tuple{}, ::Tuple{}) = () -@inline _isemptycol_all(ks, stopks) = ( - _isemptycol(first(ks), first(stopks)), - _isemptycol_all(tail(ks), tail(stopks))...) -@inline _initrowforcol(j, rowsentinel, isempty, expandsvert, k, A) = - expandsvert || isempty ? convert(indtype(A), rowsentinel) : storedinds(A)[k] -@inline _initrowforcol_all(j, rowsentinel, ::Tuple{}, ::Tuple{}, ::Tuple{}, ::Tuple{}) = () -@inline _initrowforcol_all(j, rowsentinel, isemptys, expandsverts, ks, As) = ( - _initrowforcol(j, rowsentinel, first(isemptys), first(expandsverts), first(ks), first(As)), - _initrowforcol_all(j, rowsentinel, tail(isemptys), tail(expandsverts), tail(ks), tail(As))...) -@inline _defargforcol(j, isempty, expandsvert, k, A) = - expandsvert && !isempty ? storedvals(A)[k] : zero(eltype(A)) -@inline _defargforcol_all(j, ::Tuple{}, ::Tuple{}, ::Tuple{}, ::Tuple{}) = () -@inline _defargforcol_all(j, isemptys, expandsverts, ks, As) = ( - _defargforcol(j, first(isemptys), first(expandsverts), first(ks), first(As)), - _defargforcol_all(j, tail(isemptys), tail(expandsverts), tail(ks), tail(As))...) -# fusing the following defs. avoids a few branches and construction of a tuple, yielding 1-20% runtime reduction -# @inline _isactiverow(activerow, row) = row == activerow -# @inline _isactiverow_all(activerow, ::Tuple{}) = () -# @inline _isactiverow_all(activerow, rows) = ( -# _isactiverow(activerow, first(rows)), -# _isactiverow_all(activerow, tail(rows))...) -# @inline _gatherbcarg(isactiverow, defarg, k, A) = isactiverow ? storedvals(A)[k] : defarg -# @inline _gatherbcargs(::Tuple{}, ::Tuple{}, ::Tuple{}, ::Tuple{}) = () -# @inline _gatherbcargs(activerows, defargs, ks, As) = ( -# _gatherbcarg(first(activerows), first(defargs), first(ks), first(As)), -# _gatherbcargs(tail(activerows), tail(defargs), tail(ks), tail(As))...) -# @inline _updateind(isactiverow, k) = isactiverow ? (k + oneunit(k)) : k -# @inline _updateind_all(::Tuple{}, ::Tuple{}) = () -# @inline _updateind_all(activerows, ks) = ( -# _updateind(first(activerows), first(ks)), -# _updateind_all(tail(activerows), tail(ks))...) -# @inline _updaterow(rowsentinel, isrowactive, presrow, k, stopk, A) = -# isrowactive ? (k < stopk ? storedinds(A)[k] : oftype(presrow, rowsentinel)) : presrow -# @inline _updaterow_all(rowsentinel, ::Tuple{}, ::Tuple{}, ::Tuple{}, ::Tuple{}, ::Tuple{}) = () -# @inline _updaterow_all(rowsentinel, activerows, rows, ks, stopks, As) = ( -# _updaterow(rowsentinel, first(activerows), first(rows), first(ks), first(stopks), first(As)), -# _updaterow_all(rowsentinel, tail(activerows), tail(rows), tail(ks), tail(stopks), tail(As))...) -@inline function _fusedupdatebc(rowsentinel, activerow, row, defarg, k, stopk, A) - # returns (val, nextk, nextrow) - if row == activerow - nextk = k + oneunit(k) - (storedvals(A)[k], nextk, (nextk < stopk ? storedinds(A)[nextk] : oftype(row, rowsentinel))) - else - (defarg, k, row) - end -end -@inline _fusedupdatebc_all(rowsentinel, activerow, rows, defargs, ks, stopks, As) = - _fusedupdatebc_all((#=vals=#), (#=nextks=#), (#=nextrows=#), rowsentinel, activerow, rows, defargs, ks, stopks, As) -@inline _fusedupdatebc_all(vals, nextks, nextrows, rowsent, activerow, ::Tuple{}, ::Tuple{}, ::Tuple{}, ::Tuple{}, ::Tuple{}) = - (vals, nextks, nextrows) -@inline function _fusedupdatebc_all(vals, nextks, nextrows, rowsentinel, activerow, rows, defargs, ks, stopks, As) - val, nextk, nextrow = _fusedupdatebc(rowsentinel, activerow, first(rows), first(defargs), first(ks), first(stopks), first(As)) - return _fusedupdatebc_all((vals..., val), (nextks..., nextk), (nextrows..., nextrow), - rowsentinel, activerow, tail(rows), tail(defargs), tail(ks), tail(stopks), tail(As)) -end - - -# (10) broadcast[!] over combinations of broadcast scalars and sparse vectors/matrices - -# broadcast shape promotion for combinations of sparse arrays and other types -broadcast_indices(::Type{AbstractSparseArray}, A) = indices(A) -# broadcast container type promotion for combinations of sparse arrays and other types -_containertype(::Type{<:SparseVecOrMat}) = AbstractSparseArray -# combinations of sparse arrays with broadcast scalars should yield sparse arrays -promote_containertype(::Type{Any}, ::Type{AbstractSparseArray}) = AbstractSparseArray -promote_containertype(::Type{AbstractSparseArray}, ::Type{Any}) = AbstractSparseArray -# combinations of sparse arrays with tuples should divert to the generic AbstractArray broadcast code -# (we handle combinations involving dense vectors/matrices below) -promote_containertype(::Type{Tuple}, ::Type{AbstractSparseArray}) = Array -promote_containertype(::Type{AbstractSparseArray}, ::Type{Tuple}) = Array - -# broadcast[!] entry points for combinations of sparse arrays and other (scalar) types -@inline function broadcast_c(f, ::Type{AbstractSparseArray}, mixedargs::Vararg{Any,N}) where N - parevalf, passedargstup = capturescalars(f, mixedargs) - return broadcast(parevalf, passedargstup...) -end -@inline function broadcast_c!(f, ::Type{AbstractSparseArray}, dest::SparseVecOrMat, mixedsrcargs::Vararg{Any,N}) where N - parevalf, passedsrcargstup = capturescalars(f, mixedsrcargs) - return broadcast!(parevalf, dest, passedsrcargstup...) -end -# capturescalars takes a function (f) and a tuple of mixed sparse vectors/matrices and -# broadcast scalar arguments (mixedargs), and returns a function (parevalf, i.e. partially -# evaluated f) and a reduced argument tuple (passedargstup) containing only the sparse -# vectors/matrices in mixedargs in their orginal order, and such that the result of -# broadcast(parevalf, passedargstup...) is broadcast(f, mixedargs...) -@inline capturescalars(f, mixedargs) = - capturescalars((passed, tofill) -> f(tofill...), (), mixedargs...) -# Recursion cases for capturescalars -@inline capturescalars(f, passedargstup, scalararg, mixedargs...) = - capturescalars(capturescalar(f, scalararg), passedargstup, mixedargs...) -@inline capturescalars(f, passedargstup, nonscalararg::SparseVecOrMat, mixedargs...) = - capturescalars(passnonscalar(f), (passedargstup..., nonscalararg), mixedargs...) -@inline passnonscalar(f) = (passed, tofill) -> f(Base.front(passed), (last(passed), tofill...)) -@inline capturescalar(f, scalararg) = (passed, tofill) -> f(passed, (scalararg, tofill...)) -# Base cases for capturescalars -@inline capturescalars(f, passedargstup, scalararg) = - (capturelastscalar(f, scalararg), passedargstup) -@inline capturescalars(f, passedargstup, nonscalararg::SparseVecOrMat) = - (passlastnonscalar(f), (passedargstup..., nonscalararg)) -@inline passlastnonscalar(f) = (passed...) -> f(Base.front(passed), (last(passed),)) -@inline capturelastscalar(f, scalararg) = (passed...) -> f(passed, (scalararg,)) - -# NOTE: The following two method definitions work around #19096. -broadcast(f::Tf, ::Type{T}, A::SparseMatrixCSC) where {Tf,T} = broadcast(y -> f(T, y), A) -broadcast(f::Tf, A::SparseMatrixCSC, ::Type{T}) where {Tf,T} = broadcast(x -> f(x, T), A) - - -# (11) broadcast[!] over combinations of scalars, sparse vectors/matrices, structured matrices, -# and one- and two-dimensional Arrays (via promotion of structured matrices and Arrays) -# -# for combinations involving only scalars, sparse arrays, structured matrices, and dense -# vectors/matrices, promote all structured matrices and dense vectors/matrices to sparse -# and rebroadcast. otherwise, divert to generic AbstractArray broadcast code. -# -# this requires three steps: segregate combinations to promote to sparse via Broadcast's -# containertype promotion and dispatch layer (broadcast_c[!], containertype, -# promote_containertype), separate ambiguous cases from the preceding dispatch -# layer in sparse broadcast's internal containertype promotion and dispatch layer -# (spbroadcast_c[!], spcontainertype, promote_spcontainertype), and then promote -# arguments to sparse as appropriate and rebroadcast. - - -# first (Broadcast containertype) dispatch layer's promotion logic -struct PromoteToSparse end - -# broadcast containertype definitions for structured matrices -StructuredMatrix = Union{Diagonal,Bidiagonal,Tridiagonal,SymTridiagonal} -_containertype(::Type{<:StructuredMatrix}) = PromoteToSparse -broadcast_indices(::Type{PromoteToSparse}, A) = indices(A) - -# combinations explicitly involving Tuples and PromoteToSparse collections -# divert to the generic AbstractArray broadcast code -promote_containertype(::Type{PromoteToSparse}, ::Type{Tuple}) = Array -promote_containertype(::Type{Tuple}, ::Type{PromoteToSparse}) = Array -# combinations involving scalars and PromoteToSparse collections continue in the promote-to-sparse funnel -promote_containertype(::Type{PromoteToSparse}, ::Type{Any}) = PromoteToSparse -promote_containertype(::Type{Any}, ::Type{PromoteToSparse}) = PromoteToSparse -# combinations involving sparse arrays and PromoteToSparse collections continue in the promote-to-sparse funnel -promote_containertype(::Type{PromoteToSparse}, ::Type{AbstractSparseArray}) = PromoteToSparse -promote_containertype(::Type{AbstractSparseArray}, ::Type{PromoteToSparse}) = PromoteToSparse -# combinations involving Arrays and PromoteToSparse collections continue in the promote-to-sparse funnel -promote_containertype(::Type{PromoteToSparse}, ::Type{Array}) = PromoteToSparse -promote_containertype(::Type{Array}, ::Type{PromoteToSparse}) = PromoteToSparse -# combinations involving Arrays and sparse arrays continue in the promote-to-sparse funnel -promote_containertype(::Type{AbstractSparseArray}, ::Type{Array}) = PromoteToSparse -promote_containertype(::Type{Array}, ::Type{AbstractSparseArray}) = PromoteToSparse - -# second (internal sparse broadcast containertype) dispatch layer's promotion logic -# mostly just disambiguates Array from the main containertype promotion mechanism -# AbstractArray serves as a marker to shunt to the generic AbstractArray broadcast code -_spcontainertype(x) = _containertype(x) -_spcontainertype(::Type{<:Vector}) = Vector -_spcontainertype(::Type{<:Matrix}) = Matrix -_spcontainertype(::Type{<:RowVector}) = Matrix -_spcontainertype(::Type{<:Ref}) = AbstractArray -_spcontainertype(::Type{<:AbstractArray}) = AbstractArray -# need the following two methods to override the immediately preceding method -_spcontainertype(::Type{<:StructuredMatrix}) = PromoteToSparse -_spcontainertype(::Type{<:SparseVecOrMat}) = AbstractSparseArray -spcontainertype(x) = _spcontainertype(typeof(x)) -spcontainertype(ct1, ct2) = promote_spcontainertype(spcontainertype(ct1), spcontainertype(ct2)) -@inline spcontainertype(ct1, ct2, cts...) = promote_spcontainertype(spcontainertype(ct1), spcontainertype(ct2, cts...)) - -promote_spcontainertype(::Type{T}, ::Type{T}) where {T} = T -# combinations involving AbstractArrays and/or Tuples divert to the generic AbstractArray broadcast code -DivertToAbsArrayBC = Union{Type{AbstractArray},Type{Tuple}} -promote_spcontainertype(::DivertToAbsArrayBC, ct) = AbstractArray -promote_spcontainertype(ct, ::DivertToAbsArrayBC) = AbstractArray -promote_spcontainertype(::DivertToAbsArrayBC, ::DivertToAbsArrayBC) = AbstractArray -# combinations involving scalars, sparse arrays, structured matrices (PromoteToSparse), -# dense vectors/matrices, and PromoteToSparse collections continue in the promote-to-sparse funnel -FunnelToSparseBC = Union{Type{Any},Type{Vector},Type{Matrix},Type{PromoteToSparse},Type{AbstractSparseArray}} -promote_spcontainertype(::FunnelToSparseBC, ::FunnelToSparseBC) = PromoteToSparse - - -# first (Broadcast containertype) dispatch layer -# (broadcast_c[!], containertype, promote_containertype) -@inline broadcast_c(f, ::Type{PromoteToSparse}, As::Vararg{Any,N}) where {N} = - spbroadcast_c(f, spcontainertype(As...), As...) -@inline broadcast_c!(f, ::Type{AbstractSparseArray}, ::Type{PromoteToSparse}, C, B, As::Vararg{Any,N}) where {N} = - spbroadcast_c!(f, AbstractSparseArray, spcontainertype(B, As...), C, B, As...) -# where destination C is not an AbstractSparseArray, divert to generic AbstractArray broadcast code -@inline broadcast_c!(f, CT::Type, ::Type{PromoteToSparse}, C, B, As::Vararg{Any,N}) where {N} = - broadcast_c!(f, CT, Array, C, B, As...) - -# second (internal sparse broadcast containertype) dispatch layer -# (spbroadcast_c[!], spcontainertype, promote_spcontainertype) -@inline spbroadcast_c(f, ::Type{PromoteToSparse}, As::Vararg{Any,N}) where {N} = - broadcast(f, map(_sparsifystructured, As)...) -@inline spbroadcast_c(f, ::Type{AbstractArray}, As::Vararg{Any,N}) where {N} = - broadcast_c(f, Array, As...) -@inline spbroadcast_c!(f, ::Type{AbstractSparseArray}, ::Type{PromoteToSparse}, C, B, As::Vararg{Any,N}) where {N} = - broadcast!(f, C, _sparsifystructured(B), map(_sparsifystructured, As)...) -@inline spbroadcast_c!(f, ::Type{AbstractSparseArray}, ::Type{AbstractArray}, C, B, As::Vararg{Any,N}) where {N} = - broadcast_c!(f, Array, Array, C, B, As...) - -@inline _sparsifystructured(M::AbstractMatrix) = SparseMatrixCSC(M) -@inline _sparsifystructured(V::AbstractVector) = SparseVector(V) -@inline _sparsifystructured(M::AbstractSparseMatrix) = SparseMatrixCSC(M) -@inline _sparsifystructured(V::AbstractSparseVector) = SparseVector(V) -@inline _sparsifystructured(S::SparseVecOrMat) = S -@inline _sparsifystructured(x) = x - - -# (12) map[!] over combinations of sparse and structured matrices -StructuredMatrix = Union{Diagonal,Bidiagonal,Tridiagonal,SymTridiagonal} -SparseOrStructuredMatrix = Union{SparseMatrixCSC,StructuredMatrix} -map(f::Tf, A::StructuredMatrix) where {Tf} = _noshapecheck_map(f, _sparsifystructured(A)) -map(f::Tf, A::SparseOrStructuredMatrix, Bs::Vararg{SparseOrStructuredMatrix,N}) where {Tf,N} = - (_checksameshape(A, Bs...); _noshapecheck_map(f, _sparsifystructured(A), map(_sparsifystructured, Bs)...)) -map!(f::Tf, C::SparseMatrixCSC, A::SparseOrStructuredMatrix, Bs::Vararg{SparseOrStructuredMatrix,N}) where {Tf,N} = - (_checksameshape(C, A, Bs...); _noshapecheck_map!(f, C, _sparsifystructured(A), map(_sparsifystructured, Bs)...)) - -end diff --git a/julia-0.6.3/share/julia/base/sparse/linalg.jl b/julia-0.6.3/share/julia/base/sparse/linalg.jl deleted file mode 100644 index 695f25f..0000000 --- a/julia-0.6.3/share/julia/base/sparse/linalg.jl +++ /dev/null @@ -1,925 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -import Base.LinAlg: checksquare - -## Functions to switch to 0-based indexing to call external sparse solvers - -# Convert from 1-based to 0-based indices -function decrement!(A::AbstractArray{T}) where T<:Integer - for i in 1:length(A); A[i] -= oneunit(T) end - A -end -decrement(A::AbstractArray{<:Integer}) = decrement!(copy(A)) - -# Convert from 0-based to 1-based indices -function increment!(A::AbstractArray{T}) where T<:Integer - for i in 1:length(A); A[i] += oneunit(T) end - A -end -increment(A::AbstractArray{<:Integer}) = increment!(copy(A)) - -## sparse matrix multiplication - -function (*)(A::SparseMatrixCSC{TvA,TiA}, B::SparseMatrixCSC{TvB,TiB}) where {TvA,TiA,TvB,TiB} - (*)(sppromote(A, B)...) -end -for f in (:A_mul_Bt, :A_mul_Bc, - :At_mul_B, :Ac_mul_B, - :At_mul_Bt, :Ac_mul_Bc) - @eval begin - function ($f)(A::SparseMatrixCSC{TvA,TiA}, B::SparseMatrixCSC{TvB,TiB}) where {TvA,TiA,TvB,TiB} - ($f)(sppromote(A, B)...) - end - end -end - -function sppromote(A::SparseMatrixCSC{TvA,TiA}, B::SparseMatrixCSC{TvB,TiB}) where {TvA,TiA,TvB,TiB} - Tv = promote_type(TvA, TvB) - Ti = promote_type(TiA, TiB) - A = convert(SparseMatrixCSC{Tv,Ti}, A) - B = convert(SparseMatrixCSC{Tv,Ti}, B) - A, B -end - -# In matrix-vector multiplication, the correct orientation of the vector is assumed. - -for (f, op, transp) in ((:A_mul_B, :identity, false), - (:Ac_mul_B, :ctranspose, true), - (:At_mul_B, :transpose, true)) - @eval begin - function $(Symbol(f,:!))(α::Number, A::SparseMatrixCSC, B::StridedVecOrMat, β::Number, C::StridedVecOrMat) - if $transp - A.n == size(C, 1) || throw(DimensionMismatch()) - A.m == size(B, 1) || throw(DimensionMismatch()) - else - A.n == size(B, 1) || throw(DimensionMismatch()) - A.m == size(C, 1) || throw(DimensionMismatch()) - end - size(B, 2) == size(C, 2) || throw(DimensionMismatch()) - nzv = A.nzval - rv = A.rowval - if β != 1 - β != 0 ? scale!(C, β) : fill!(C, zero(eltype(C))) - end - for k = 1:size(C, 2) - for col = 1:A.n - if $transp - tmp = zero(eltype(C)) - @inbounds for j = A.colptr[col]:(A.colptr[col + 1] - 1) - tmp += $(op)(nzv[j])*B[rv[j],k] - end - C[col,k] += α*tmp - else - αxj = α*B[col,k] - @inbounds for j = A.colptr[col]:(A.colptr[col + 1] - 1) - C[rv[j], k] += nzv[j]*αxj - end - end - end - end - C - end - - function $(f)(A::SparseMatrixCSC{TA,S}, x::StridedVector{Tx}) where {TA,S,Tx} - T = promote_type(TA, Tx) - $(Symbol(f,:!))(one(T), A, x, zero(T), similar(x, T, A.n)) - end - function $(f)(A::SparseMatrixCSC{TA,S}, B::StridedMatrix{Tx}) where {TA,S,Tx} - T = promote_type(TA, Tx) - $(Symbol(f,:!))(one(T), A, B, zero(T), similar(B, T, (A.n, size(B, 2)))) - end - end -end - -# For compatibility with dense multiplication API. Should be deleted when dense multiplication -# API is updated to follow BLAS API. -A_mul_B!(C::StridedVecOrMat, A::SparseMatrixCSC, B::StridedVecOrMat) = A_mul_B!(one(eltype(B)), A, B, zero(eltype(C)), C) -Ac_mul_B!(C::StridedVecOrMat, A::SparseMatrixCSC, B::StridedVecOrMat) = Ac_mul_B!(one(eltype(B)), A, B, zero(eltype(C)), C) -At_mul_B!(C::StridedVecOrMat, A::SparseMatrixCSC, B::StridedVecOrMat) = At_mul_B!(one(eltype(B)), A, B, zero(eltype(C)), C) - - -function (*)(X::StridedMatrix{TX}, A::SparseMatrixCSC{TvA,TiA}) where {TX,TvA,TiA} - mX, nX = size(X) - nX == A.m || throw(DimensionMismatch()) - Y = zeros(promote_type(TX,TvA), mX, A.n) - rowval = A.rowval - nzval = A.nzval - @inbounds for multivec_row=1:mX, col = 1:A.n, k=A.colptr[col]:(A.colptr[col+1]-1) - Y[multivec_row, col] += X[multivec_row, rowval[k]] * nzval[k] - end - Y -end - -function (*)(D::Diagonal, A::SparseMatrixCSC) - T = Base.promote_op(*, eltype(D), eltype(A)) - scale!(LinAlg.copy_oftype(A, T), D.diag, A) -end -function (*)(A::SparseMatrixCSC, D::Diagonal) - T = Base.promote_op(*, eltype(D), eltype(A)) - scale!(LinAlg.copy_oftype(A, T), A, D.diag) -end - -# Sparse matrix multiplication as described in [Gustavson, 1978]: -# http://dl.acm.org/citation.cfm?id=355796 - -(*)(A::SparseMatrixCSC{Tv,Ti}, B::SparseMatrixCSC{Tv,Ti}) where {Tv,Ti} = spmatmul(A,B) -for (f, opA, opB) in ((:A_mul_Bt, :identity, :transpose), - (:A_mul_Bc, :identity, :ctranspose), - (:At_mul_B, :transpose, :identity), - (:Ac_mul_B, :ctranspose, :identity), - (:At_mul_Bt, :transpose, :transpose), - (:Ac_mul_Bc, :ctranspose, :ctranspose)) - @eval begin - function ($f)(A::SparseMatrixCSC{Tv,Ti}, B::SparseMatrixCSC{Tv,Ti}) where {Tv,Ti} - spmatmul(($opA)(A), ($opB)(B)) - end - end -end - -function spmatmul(A::SparseMatrixCSC{Tv,Ti}, B::SparseMatrixCSC{Tv,Ti}; - sortindices::Symbol = :sortcols) where {Tv,Ti} - mA, nA = size(A) - mB, nB = size(B) - nA==mB || throw(DimensionMismatch()) - - colptrA = A.colptr; rowvalA = A.rowval; nzvalA = A.nzval - colptrB = B.colptr; rowvalB = B.rowval; nzvalB = B.nzval - # TODO: Need better estimation of result space - nnzC = min(mA*nB, length(nzvalA) + length(nzvalB)) - colptrC = Vector{Ti}(nB+1) - rowvalC = Vector{Ti}(nnzC) - nzvalC = Vector{Tv}(nnzC) - - @inbounds begin - ip = 1 - xb = zeros(Ti, mA) - x = zeros(Tv, mA) - for i in 1:nB - if ip + mA - 1 > nnzC - resize!(rowvalC, nnzC + max(nnzC,mA)) - resize!(nzvalC, nnzC + max(nnzC,mA)) - nnzC = length(nzvalC) - end - colptrC[i] = ip - for jp in colptrB[i]:(colptrB[i+1] - 1) - nzB = nzvalB[jp] - j = rowvalB[jp] - for kp in colptrA[j]:(colptrA[j+1] - 1) - nzC = nzvalA[kp] * nzB - k = rowvalA[kp] - if xb[k] != i - rowvalC[ip] = k - ip += 1 - xb[k] = i - x[k] = nzC - else - x[k] += nzC - end - end - end - for vp in colptrC[i]:(ip - 1) - nzvalC[vp] = x[rowvalC[vp]] - end - end - colptrC[nB+1] = ip - end - - deleteat!(rowvalC, colptrC[end]:length(rowvalC)) - deleteat!(nzvalC, colptrC[end]:length(nzvalC)) - - # The Gustavson algorithm does not guarantee the product to have sorted row indices. - Cunsorted = SparseMatrixCSC(mA, nB, colptrC, rowvalC, nzvalC) - C = SparseArrays.sortSparseMatrixCSC!(Cunsorted, sortindices=sortindices) - return C -end - -## solvers -function fwdTriSolve!(A::SparseMatrixCSC, B::AbstractVecOrMat) -# forward substitution for CSC matrices - nrowB, ncolB = size(B, 1), size(B, 2) - ncol = LinAlg.checksquare(A) - if nrowB != ncol - throw(DimensionMismatch("A is $(ncol) columns and B has $(nrowB) rows")) - end - - aa = A.nzval - ja = A.rowval - ia = A.colptr - - joff = 0 - for k = 1:ncolB - for j = 1:nrowB - i1 = ia[j] - i2 = ia[j + 1] - 1 - - # loop through the structural zeros - ii = i1 - jai = ja[ii] - while ii <= i2 && jai < j - ii += 1 - jai = ja[ii] - end - - # check for zero pivot and divide with pivot - if jai == j - bj = B[joff + jai]/aa[ii] - B[joff + jai] = bj - ii += 1 - else - throw(LinAlg.SingularException(j)) - end - - # update remaining part - for i = ii:i2 - B[joff + ja[i]] -= bj*aa[i] - end - end - joff += nrowB - end - B -end - -function bwdTriSolve!(A::SparseMatrixCSC, B::AbstractVecOrMat) -# backward substitution for CSC matrices - nrowB, ncolB = size(B, 1), size(B, 2) - ncol = LinAlg.checksquare(A) - if nrowB != ncol - throw(DimensionMismatch("A is $(ncol) columns and B has $(nrowB) rows")) - end - - aa = A.nzval - ja = A.rowval - ia = A.colptr - - joff = 0 - for k = 1:ncolB - for j = nrowB:-1:1 - i1 = ia[j] - i2 = ia[j + 1] - 1 - - # loop through the structural zeros - ii = i2 - jai = ja[ii] - while ii >= i1 && jai > j - ii -= 1 - jai = ja[ii] - end - - # check for zero pivot and divide with pivot - if jai == j - bj = B[joff + jai]/aa[ii] - B[joff + jai] = bj - ii -= 1 - else - throw(LinAlg.SingularException(j)) - end - - # update remaining part - for i = ii:-1:i1 - B[joff + ja[i]] -= bj*aa[i] - end - end - joff += nrowB - end - B -end - -A_ldiv_B!(L::LowerTriangular{T,<:SparseMatrixCSC{T}}, B::StridedVecOrMat) where {T} = fwdTriSolve!(L.data, B) -A_ldiv_B!(U::UpperTriangular{T,<:SparseMatrixCSC{T}}, B::StridedVecOrMat) where {T} = bwdTriSolve!(U.data, B) - -(\)(L::LowerTriangular{T,<:SparseMatrixCSC{T}}, B::SparseMatrixCSC) where {T} = A_ldiv_B!(L, Array(B)) -(\)(U::UpperTriangular{T,<:SparseMatrixCSC{T}}, B::SparseMatrixCSC) where {T} = A_ldiv_B!(U, Array(B)) - -## triu, tril - -function triu(S::SparseMatrixCSC{Tv,Ti}, k::Integer=0) where {Tv,Ti} - m,n = size(S) - if (k > 0 && k > n) || (k < 0 && -k > m) - throw(BoundsError()) - end - colptr = Vector{Ti}(n+1) - nnz = 0 - for col = 1 : min(max(k+1,1), n+1) - colptr[col] = 1 - end - for col = max(k+1,1) : n - for c1 = S.colptr[col] : S.colptr[col+1]-1 - S.rowval[c1] > col - k && break - nnz += 1 - end - colptr[col+1] = nnz+1 - end - rowval = Vector{Ti}(nnz) - nzval = Vector{Tv}(nnz) - A = SparseMatrixCSC(m, n, colptr, rowval, nzval) - for col = max(k+1,1) : n - c1 = S.colptr[col] - for c2 = A.colptr[col] : A.colptr[col+1]-1 - A.rowval[c2] = S.rowval[c1] - A.nzval[c2] = S.nzval[c1] - c1 += 1 - end - end - A -end - -function tril(S::SparseMatrixCSC{Tv,Ti}, k::Integer=0) where {Tv,Ti} - m,n = size(S) - if (k > 0 && k > n) || (k < 0 && -k > m) - throw(BoundsError()) - end - colptr = Vector{Ti}(n+1) - nnz = 0 - colptr[1] = 1 - for col = 1 : min(n, m+k) - l1 = S.colptr[col+1]-1 - for c1 = 0 : (l1 - S.colptr[col]) - S.rowval[l1 - c1] < col - k && break - nnz += 1 - end - colptr[col+1] = nnz+1 - end - for col = max(min(n, m+k)+2,1) : n+1 - colptr[col] = nnz+1 - end - rowval = Vector{Ti}(nnz) - nzval = Vector{Tv}(nnz) - A = SparseMatrixCSC(m, n, colptr, rowval, nzval) - for col = 1 : min(n, m+k) - c1 = S.colptr[col+1]-1 - l2 = A.colptr[col+1]-1 - for c2 = 0 : l2 - A.colptr[col] - A.rowval[l2 - c2] = S.rowval[c1] - A.nzval[l2 - c2] = S.nzval[c1] - c1 -= 1 - end - end - A -end - -## diff - -function sparse_diff1(S::SparseMatrixCSC{Tv,Ti}) where {Tv,Ti} - m,n = size(S) - m > 1 || return SparseMatrixCSC(0, n, ones(Ti,n+1), Ti[], Tv[]) - colptr = Vector{Ti}(n+1) - numnz = 2 * nnz(S) # upper bound; will shrink later - rowval = Vector{Ti}(numnz) - nzval = Vector{Tv}(numnz) - numnz = 0 - colptr[1] = 1 - for col = 1 : n - last_row = 0 - last_val = 0 - for k = S.colptr[col] : S.colptr[col+1]-1 - row = S.rowval[k] - val = S.nzval[k] - if row > 1 - if row == last_row + 1 - nzval[numnz] += val - nzval[numnz]==zero(Tv) && (numnz -= 1) - else - numnz += 1 - rowval[numnz] = row - 1 - nzval[numnz] = val - end - end - if row < m - numnz += 1 - rowval[numnz] = row - nzval[numnz] = -val - end - last_row = row - last_val = val - end - colptr[col+1] = numnz+1 - end - deleteat!(rowval, numnz+1:length(rowval)) - deleteat!(nzval, numnz+1:length(nzval)) - return SparseMatrixCSC(m-1, n, colptr, rowval, nzval) -end - -function sparse_diff2(a::SparseMatrixCSC{Tv,Ti}) where {Tv,Ti} - m,n = size(a) - colptr = Vector{Ti}(max(n,1)) - numnz = 2 * nnz(a) # upper bound; will shrink later - rowval = Vector{Ti}(numnz) - nzval = Vector{Tv}(numnz) - - z = zero(Tv) - - colptr_a = a.colptr - rowval_a = a.rowval - nzval_a = a.nzval - - ptrS = 1 - colptr[1] = 1 - - n == 0 && return SparseMatrixCSC(m, n, colptr, rowval, nzval) - - startA = colptr_a[1] - stopA = colptr_a[2] - - rA = startA : stopA - 1 - rowvalA = rowval_a[rA] - nzvalA = nzval_a[rA] - lA = stopA - startA - - for col = 1:n-1 - startB, stopB = startA, stopA - startA = colptr_a[col+1] - stopA = colptr_a[col+2] - - rowvalB = rowvalA - nzvalB = nzvalA - lB = lA - - rA = startA : stopA - 1 - rowvalA = rowval_a[rA] - nzvalA = nzval_a[rA] - lA = stopA - startA - - ptrB = 1 - ptrA = 1 - - while ptrA <= lA && ptrB <= lB - rowA = rowvalA[ptrA] - rowB = rowvalB[ptrB] - if rowA < rowB - rowval[ptrS] = rowA - nzval[ptrS] = nzvalA[ptrA] - ptrS += 1 - ptrA += 1 - elseif rowB < rowA - rowval[ptrS] = rowB - nzval[ptrS] = -nzvalB[ptrB] - ptrS += 1 - ptrB += 1 - else - res = nzvalA[ptrA] - nzvalB[ptrB] - if res != z - rowval[ptrS] = rowA - nzval[ptrS] = res - ptrS += 1 - end - ptrA += 1 - ptrB += 1 - end - end - - while ptrA <= lA - rowval[ptrS] = rowvalA[ptrA] - nzval[ptrS] = nzvalA[ptrA] - ptrS += 1 - ptrA += 1 - end - - while ptrB <= lB - rowval[ptrS] = rowvalB[ptrB] - nzval[ptrS] = -nzvalB[ptrB] - ptrS += 1 - ptrB += 1 - end - - colptr[col+1] = ptrS - end - deleteat!(rowval, ptrS:length(rowval)) - deleteat!(nzval, ptrS:length(nzval)) - return SparseMatrixCSC(m, n-1, colptr, rowval, nzval) -end - -diff(a::SparseMatrixCSC, dim::Integer)= dim==1 ? sparse_diff1(a) : sparse_diff2(a) - -## norm and rank -vecnorm(A::SparseMatrixCSC, p::Real=2) = vecnorm(A.nzval, p) - -function norm(A::SparseMatrixCSC,p::Real=2) - m, n = size(A) - if m == 0 || n == 0 || isempty(A) - return float(real(zero(eltype(A)))) - elseif m == 1 || n == 1 - # TODO: compute more efficiently using A.nzval directly - return norm(Array(A), p) - else - Tnorm = typeof(float(real(zero(eltype(A))))) - Tsum = promote_type(Float64,Tnorm) - if p==1 - nA::Tsum = 0 - for j=1:n - colSum::Tsum = 0 - for i = A.colptr[j]:A.colptr[j+1]-1 - colSum += abs(A.nzval[i]) - end - nA = max(nA, colSum) - end - return convert(Tnorm, nA) - elseif p==2 - throw(ArgumentError("2-norm not yet implemented for sparse matrices. Try norm(Array(A)) or norm(A, p) where p=1 or Inf.")) - elseif p==Inf - rowSum = zeros(Tsum,m) - for i=1:length(A.nzval) - rowSum[A.rowval[i]] += abs(A.nzval[i]) - end - return convert(Tnorm, maximum(rowSum)) - end - end - throw(ArgumentError("invalid p-norm p=$p. Valid: 1, Inf")) -end - -# TODO rank - -# cond -function cond(A::SparseMatrixCSC, p::Real=2) - if p == 1 - normAinv = normestinv(A) - normA = norm(A, 1) - return normA * normAinv - elseif p == Inf - normAinv = normestinv(A') - normA = norm(A, Inf) - return normA * normAinv - elseif p == 2 - throw(ArgumentError("2-norm condition number is not implemented for sparse matrices, try cond(Array(A), 2) instead")) - else - throw(ArgumentError("second argument must be either 1 or Inf, got $p")) - end -end - -function normestinv(A::SparseMatrixCSC{T}, t::Integer = min(2,maximum(size(A)))) where T - maxiter = 5 - # Check the input - n = checksquare(A) - F = factorize(A) - if t <= 0 - throw(ArgumentError("number of blocks must be a positive integer")) - end - if t > n - throw(ArgumentError("number of blocks must not be greater than $n")) - end - ind = Vector{Int64}(n) - ind_hist = Vector{Int64}(maxiter * t) - - Ti = typeof(float(zero(T))) - - S = zeros(T <: Real ? Int : Ti, n, t) - - function _rand_pm1!(v) - for i in eachindex(v) - v[i] = rand()<0.5?1:-1 - end - end - - function _any_abs_eq(v,n::Int) - for vv in v - if abs(vv)==n - return true - end - end - return false - end - - # Generate the block matrix - X = Matrix{Ti}(n, t) - X[1:n,1] = 1 - for j = 2:t - while true - _rand_pm1!(view(X,1:n,j)) - yaux = X[1:n,j]' * X[1:n,1:j-1] - if !_any_abs_eq(yaux,n) - break - end - end - end - scale!(X, 1./n) - - iter = 0 - local est - local est_old - est_ind = 0 - while iter < maxiter - iter += 1 - Y = F \ X - est = zero(real(eltype(Y))) - est_ind = 0 - for i = 1:t - y = norm(Y[1:n,i], 1) - if y > est - est = y - est_ind = i - end - end - if iter == 1 - est_old = est - end - if est > est_old || iter == 2 - ind_best = est_ind - end - if iter >= 2 && est <= est_old - est = est_old - break - end - est_old = est - S_old = copy(S) - for j = 1:t - for i = 1:n - S[i,j] = Y[i,j]==0?one(Y[i,j]):sign(Y[i,j]) - end - end - - if T <: Real - # Check whether cols of S are parallel to cols of S or S_old - for j = 1:t - while true - repeated = false - if j > 1 - saux = S[1:n,j]' * S[1:n,1:j-1] - if _any_abs_eq(saux,n) - repeated = true - end - end - if !repeated - saux2 = S[1:n,j]' * S_old[1:n,1:t] - if _any_abs_eq(saux2,n) - repeated = true - end - end - if repeated - _rand_pm1!(view(S,1:n,j)) - else - break - end - end - end - end - - # Use the conjugate transpose - Z = F' \ S - h_max = zero(real(eltype(Z))) - h = zeros(real(eltype(Z)), n) - h_ind = 0 - for i = 1:n - h[i] = norm(Z[i,1:t], Inf) - if h[i] > h_max - h_max = h[i] - h_ind = i - end - ind[i] = i - end - if iter >=2 && ind_best == h_ind - break - end - p = sortperm(h, rev=true) - h = h[p] - permute!(ind, p) - if t > 1 - addcounter = t - elemcounter = 0 - while addcounter > 0 && elemcounter < n - elemcounter = elemcounter + 1 - current_element = ind[elemcounter] - found = false - for i = 1:t * (iter - 1) - if current_element == ind_hist[i] - found = true - break - end - end - if !found - addcounter = addcounter - 1 - for i = 1:current_element - 1 - X[i,t-addcounter] = 0 - end - X[current_element,t-addcounter] = 1 - for i = current_element + 1:n - X[i,t-addcounter] = 0 - end - ind_hist[iter * t - addcounter] = current_element - else - if elemcounter == t && addcounter == t - break - end - end - end - else - ind_hist[1:t] = ind[1:t] - for j = 1:t - for i = 1:ind[j] - 1 - X[i,j] = 0 - end - X[ind[j],j] = 1 - for i = ind[j] + 1:n - X[i,j] = 0 - end - end - end - end - return est -end - -# kron - -function kron(a::SparseMatrixCSC{Tv,Ti}, b::SparseMatrixCSC{Tv,Ti}) where {Tv,Ti} - numnzA = nnz(a) - numnzB = nnz(b) - - numnz = numnzA * numnzB - - mA,nA = size(a) - mB,nB = size(b) - - m,n = mA*mB, nA*nB - - colptr = Vector{Ti}(n+1) - rowval = Vector{Ti}(numnz) - nzval = Vector{Tv}(numnz) - - colptr[1] = 1 - - colptrA = a.colptr - colptrB = b.colptr - rowvalA = a.rowval - rowvalB = b.rowval - nzvalA = a.nzval - nzvalB = b.nzval - - col = 1 - - @inbounds for j = 1:nA - startA = colptrA[j] - stopA = colptrA[j+1]-1 - lA = stopA - startA + 1 - - for i = 1:nB - startB = colptrB[i] - stopB = colptrB[i+1]-1 - lB = stopB - startB + 1 - - ptr_range = (1:lB) + (colptr[col]-1) - - colptr[col+1] = colptr[col] + lA * lB - col += 1 - - for ptrA = startA : stopA - ptrB = startB - for ptr = ptr_range - rowval[ptr] = (rowvalA[ptrA]-1)*mB + rowvalB[ptrB] - nzval[ptr] = nzvalA[ptrA] * nzvalB[ptrB] - ptrB += 1 - end - ptr_range += lB - end - end - end - SparseMatrixCSC(m, n, colptr, rowval, nzval) -end - -function kron(A::SparseMatrixCSC{Tv1,Ti1}, B::SparseMatrixCSC{Tv2,Ti2}) where {Tv1,Ti1,Tv2,Ti2} - Tv_res = promote_type(Tv1, Tv2) - Ti_res = promote_type(Ti1, Ti2) - A = convert(SparseMatrixCSC{Tv_res,Ti_res}, A) - B = convert(SparseMatrixCSC{Tv_res,Ti_res}, B) - return kron(A,B) -end - -kron(A::SparseMatrixCSC, B::VecOrMat) = kron(A, sparse(B)) -kron(A::VecOrMat, B::SparseMatrixCSC) = kron(sparse(A), B) - -## det, inv, cond - -inv(A::SparseMatrixCSC) = error("The inverse of a sparse matrix can often be dense and can cause the computer to run out of memory. If you are sure you have enough memory, please convert your matrix to a dense matrix.") - -# TODO - -## scale methods - -# Copy colptr and rowval from one sparse matrix to another -function copyinds!(C::SparseMatrixCSC, A::SparseMatrixCSC) - if C.colptr !== A.colptr - resize!(C.colptr, length(A.colptr)) - copy!(C.colptr, A.colptr) - end - if C.rowval !== A.rowval - resize!(C.rowval, length(A.rowval)) - copy!(C.rowval, A.rowval) - end -end - -# multiply by diagonal matrix as vector -function scale!(C::SparseMatrixCSC, A::SparseMatrixCSC, b::Vector) - m, n = size(A) - (n==length(b) && size(A)==size(C)) || throw(DimensionMismatch()) - copyinds!(C, A) - Cnzval = C.nzval - Anzval = A.nzval - resize!(Cnzval, length(Anzval)) - for col = 1:n, p = A.colptr[col]:(A.colptr[col+1]-1) - @inbounds Cnzval[p] = Anzval[p] * b[col] - end - C -end - -function scale!(C::SparseMatrixCSC, b::Vector, A::SparseMatrixCSC) - m, n = size(A) - (m==length(b) && size(A)==size(C)) || throw(DimensionMismatch()) - copyinds!(C, A) - Cnzval = C.nzval - Anzval = A.nzval - Arowval = A.rowval - resize!(Cnzval, length(Anzval)) - for col = 1:n, p = A.colptr[col]:(A.colptr[col+1]-1) - @inbounds Cnzval[p] = Anzval[p] * b[Arowval[p]] - end - C -end - -function scale!(C::SparseMatrixCSC, A::SparseMatrixCSC, b::Number) - size(A)==size(C) || throw(DimensionMismatch()) - copyinds!(C, A) - resize!(C.nzval, length(A.nzval)) - scale!(C.nzval, A.nzval, b) - C -end - -function scale!(C::SparseMatrixCSC, b::Number, A::SparseMatrixCSC) - size(A)==size(C) || throw(DimensionMismatch()) - copyinds!(C, A) - resize!(C.nzval, length(A.nzval)) - scale!(C.nzval, b, A.nzval) - C -end - -scale!(A::SparseMatrixCSC, b::Number) = (scale!(A.nzval, b); A) -scale!(b::Number, A::SparseMatrixCSC) = (scale!(b, A.nzval); A) - -for f in (:\, :Ac_ldiv_B, :At_ldiv_B) - @eval begin - function ($f)(A::SparseMatrixCSC, B::AbstractVecOrMat) - m, n = size(A) - if m == n - if istril(A) - if istriu(A) - return ($f)(Diagonal(A), B) - else - return ($f)(LowerTriangular(A), B) - end - elseif istriu(A) - return ($f)(UpperTriangular(A), B) - end - if ishermitian(A) - return ($f)(Hermitian(A), B) - end - return ($f)(lufact(A), B) - else - return ($f)(qrfact(A), B) - end - end - ($f)(::SparseMatrixCSC, ::RowVector) = throw(DimensionMismatch("Cannot left-divide matrix by transposed vector")) - end -end - -function factorize(A::SparseMatrixCSC) - m, n = size(A) - if m == n - if istril(A) - if istriu(A) - return Diagonal(A) - else - return LowerTriangular(A) - end - elseif istriu(A) - return UpperTriangular(A) - end - if ishermitian(A) - try - return cholfact(Hermitian(A)) - catch e - isa(e, PosDefException) || rethrow(e) - return ldltfact(Hermitian(A)) - end - end - return lufact(A) - else - return qrfact(A) - end -end - -function factorize{Ti}(A::Symmetric{Float64,SparseMatrixCSC{Float64,Ti}}) - try - return cholfact(A) - catch e - isa(e, PosDefException) || rethrow(e) - return ldltfact(A) - end -end -function factorize{Ti}(A::Hermitian{Complex{Float64}, SparseMatrixCSC{Complex{Float64},Ti}}) - try - return cholfact(A) - catch e - isa(e, PosDefException) || rethrow(e) - return ldltfact(A) - end -end - -chol(A::SparseMatrixCSC) = error("Use cholfact() instead of chol() for sparse matrices.") -lu(A::SparseMatrixCSC) = error("Use lufact() instead of lu() for sparse matrices.") -eig(A::SparseMatrixCSC) = error("Use eigs() instead of eig() for sparse matrices.") diff --git a/julia-0.6.3/share/julia/base/sparse/sparse.jl b/julia-0.6.3/share/julia/base/sparse/sparse.jl deleted file mode 100644 index 23e7c8c..0000000 --- a/julia-0.6.3/share/julia/base/sparse/sparse.jl +++ /dev/null @@ -1,46 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -module SparseArrays - -using Base: ReshapedArray, promote_op, setindex_shape_check, to_shape, tail -using Base.Sort: Forward -using Base.LinAlg: AbstractTriangular, PosDefException - -import Base: +, -, *, \, /, &, |, xor, == -import Base: A_mul_B!, Ac_mul_B, Ac_mul_B!, At_mul_B, At_mul_B! -import Base: A_mul_Bc, A_mul_Bt, Ac_mul_Bc, At_mul_Bt -import Base: At_ldiv_B, Ac_ldiv_B, A_ldiv_B! -import Base.LinAlg: At_ldiv_B!, Ac_ldiv_B! - -import Base: @get!, acos, acosd, acot, acotd, acsch, asech, asin, asind, asinh, - atan, atand, atanh, broadcast!, chol, conj!, cos, cosc, cosd, cosh, cospi, cot, - cotd, coth, countnz, csc, cscd, csch, ctranspose!, diag, diff, done, dot, eig, - exp10, exp2, eye, findn, floor, hash, indmin, inv, issymmetric, istril, istriu, - log10, log2, lu, next, sec, secd, sech, show, sin, - sinc, sind, sinh, sinpi, squeeze, start, sum, summary, tan, - tand, tanh, trace, transpose!, tril!, triu!, trunc, vecnorm, abs, abs2, - broadcast, ceil, complex, cond, conj, convert, copy, copy!, ctranspose, diagm, - exp, expm1, factorize, find, findmax, findmin, findnz, float, full, getindex, - vcat, hcat, hvcat, cat, imag, indmax, ishermitian, kron, length, log, log1p, max, min, - maximum, minimum, norm, one, promote_eltype, real, reinterpret, reshape, rot180, - rotl90, rotr90, round, scale!, setindex!, similar, size, transpose, tril, - triu, vec, permute!, map, map! - -export AbstractSparseArray, AbstractSparseMatrix, AbstractSparseVector, - SparseMatrixCSC, SparseVector, blkdiag, droptol!, dropzeros!, dropzeros, - issparse, nonzeros, nzrange, rowvals, sparse, sparsevec, spdiagm, speye, spones, - sprand, sprandn, spzeros, nnz, permute - -include("abstractsparse.jl") -include("sparsematrix.jl") -include("sparsevector.jl") -include("higherorderfns.jl") - -include("linalg.jl") -if Base.USE_GPL_LIBS - include("umfpack.jl") - include("cholmod.jl") - include("spqr.jl") -end - -end diff --git a/julia-0.6.3/share/julia/base/sparse/sparsematrix.jl b/julia-0.6.3/share/julia/base/sparse/sparsematrix.jl deleted file mode 100644 index 974c43d..0000000 --- a/julia-0.6.3/share/julia/base/sparse/sparsematrix.jl +++ /dev/null @@ -1,3610 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -# Compressed sparse columns data structure -# Assumes that no zeros are stored in the data structure -# Assumes that row values in rowval for each column are sorted -# issorted(rowval[colptr[i]:(colptr[i+1]-1)]) == true - -""" - SparseMatrixCSC{Tv,Ti<:Integer} <: AbstractSparseMatrix{Tv,Ti} - -Matrix type for storing sparse matrices in the -[Compressed Sparse Column](@ref man-csc) format. -""" -struct SparseMatrixCSC{Tv,Ti<:Integer} <: AbstractSparseMatrix{Tv,Ti} - m::Int # Number of rows - n::Int # Number of columns - colptr::Vector{Ti} # Column i is in colptr[i]:(colptr[i+1]-1) - rowval::Vector{Ti} # Row indices of stored values - nzval::Vector{Tv} # Stored values, typically nonzeros - - function SparseMatrixCSC{Tv,Ti}(m::Integer, n::Integer, colptr::Vector{Ti}, rowval::Vector{Ti}, - nzval::Vector{Tv}) where {Tv,Ti<:Integer} - m < 0 && throw(ArgumentError("number of rows (m) must be ≥ 0, got $m")) - n < 0 && throw(ArgumentError("number of columns (n) must be ≥ 0, got $n")) - new(Int(m), Int(n), colptr, rowval, nzval) - end -end -function SparseMatrixCSC(m::Integer, n::Integer, colptr::Vector, rowval::Vector, nzval::Vector) - Tv = eltype(nzval) - Ti = promote_type(eltype(colptr), eltype(rowval)) - SparseMatrixCSC{Tv,Ti}(m, n, colptr, rowval, nzval) -end - -size(S::SparseMatrixCSC) = (S.m, S.n) - -""" - nnz(A) - -Returns the number of stored (filled) elements in a sparse array. - -# Example -```jldoctest -julia> A = speye(3) -3×3 SparseMatrixCSC{Float64,Int64} with 3 stored entries: - [1, 1] = 1.0 - [2, 2] = 1.0 - [3, 3] = 1.0 - -julia> nnz(A) -3 -``` -""" -nnz(S::SparseMatrixCSC) = Int(S.colptr[S.n + 1]-1) -countnz(S::SparseMatrixCSC) = countnz(S.nzval) -count(S::SparseMatrixCSC) = count(S.nzval) - -""" - nonzeros(A) - -Return a vector of the structural nonzero values in sparse array `A`. This -includes zeros that are explicitly stored in the sparse array. The returned -vector points directly to the internal nonzero storage of `A`, and any -modifications to the returned vector will mutate `A` as well. See -[`rowvals`](@ref) and [`nzrange`](@ref). - -# Example -```jldoctest -julia> A = speye(3) -3×3 SparseMatrixCSC{Float64,Int64} with 3 stored entries: - [1, 1] = 1.0 - [2, 2] = 1.0 - [3, 3] = 1.0 - -julia> nonzeros(A) -3-element Array{Float64,1}: - 1.0 - 1.0 - 1.0 -``` -""" -nonzeros(S::SparseMatrixCSC) = S.nzval - -""" - rowvals(A::SparseMatrixCSC) - -Return a vector of the row indices of `A`. Any modifications to the returned -vector will mutate `A` as well. Providing access to how the row indices are -stored internally can be useful in conjunction with iterating over structural -nonzero values. See also [`nonzeros`](@ref) and [`nzrange`](@ref). - -# Example -```jldoctest -julia> A = speye(3) -3×3 SparseMatrixCSC{Float64,Int64} with 3 stored entries: - [1, 1] = 1.0 - [2, 2] = 1.0 - [3, 3] = 1.0 - -julia> rowvals(A) -3-element Array{Int64,1}: - 1 - 2 - 3 -``` -""" -rowvals(S::SparseMatrixCSC) = S.rowval - -""" - nzrange(A::SparseMatrixCSC, col::Integer) - -Return the range of indices to the structural nonzero values of a sparse matrix -column. In conjunction with [`nonzeros`](@ref) and -[`rowvals`](@ref), this allows for convenient iterating over a sparse matrix : - - A = sparse(I,J,V) - rows = rowvals(A) - vals = nonzeros(A) - m, n = size(A) - for i = 1:n - for j in nzrange(A, i) - row = rows[j] - val = vals[j] - # perform sparse wizardry... - end - end -""" -nzrange(S::SparseMatrixCSC, col::Integer) = S.colptr[col]:(S.colptr[col+1]-1) - -function Base.show(io::IO, ::MIME"text/plain", S::SparseMatrixCSC) - xnnz = nnz(S) - print(io, S.m, "×", S.n, " ", typeof(S), " with ", xnnz, " stored ", - xnnz == 1 ? "entry" : "entries") - if xnnz != 0 - print(io, ":") - show(io, S) - end -end - -Base.show(io::IO, S::SparseMatrixCSC) = Base.show(convert(IOContext, io), S::SparseMatrixCSC) -function Base.show(io::IOContext, S::SparseMatrixCSC) - if nnz(S) == 0 - return show(io, MIME("text/plain"), S) - end - - limit::Bool = get(io, :limit, false) - if limit - rows = displaysize(io)[1] - half_screen_rows = div(rows - 8, 2) - else - half_screen_rows = typemax(Int) - end - pad = ndigits(max(S.m,S.n)) - k = 0 - sep = "\n " - if !haskey(io, :compact) - io = IOContext(io, :compact => true) - end - for col = 1:S.n, k = S.colptr[col] : (S.colptr[col+1]-1) - if k < half_screen_rows || k > nnz(S)-half_screen_rows - print(io, sep, '[', rpad(S.rowval[k], pad), ", ", lpad(col, pad), "] = ") - if isassigned(S.nzval, Int(k)) - show(io, S.nzval[k]) - else - print(io, Base.undef_ref_str) - end - elseif k == half_screen_rows - print(io, sep, '\u22ee') - end - k += 1 - end -end - -## Reinterpret and Reshape - -function reinterpret(::Type{T}, a::SparseMatrixCSC{Tv}) where {T,Tv} - if sizeof(T) != sizeof(Tv) - throw(ArgumentError("SparseMatrixCSC reinterpret is only supported for element types of the same size")) - end - mA, nA = size(a) - colptr = copy(a.colptr) - rowval = copy(a.rowval) - nzval = reinterpret(T, a.nzval) - return SparseMatrixCSC(mA, nA, colptr, rowval, nzval) -end - -function sparse_compute_reshaped_colptr_and_rowval{Ti}(colptrS::Vector{Ti}, rowvalS::Vector{Ti}, mS::Int, nS::Int, colptrA::Vector{Ti}, rowvalA::Vector{Ti}, mA::Int, nA::Int) - lrowvalA = length(rowvalA) - maxrowvalA = (lrowvalA > 0) ? maximum(rowvalA) : zero(Ti) - ((length(colptrA) == (nA+1)) && (maximum(colptrA) <= (lrowvalA+1)) && (maxrowvalA <= mA)) || throw(BoundsError()) - - colptrS[1] = 1 - colA = 1 - colS = 1 - ptr = 1 - - @inbounds while colA <= nA - offsetA = (colA - 1) * mA - while ptr <= colptrA[colA+1]-1 - rowA = rowvalA[ptr] - i = offsetA + rowA - 1 - colSn = div(i, mS) + 1 - rowS = mod(i, mS) + 1 - while colS < colSn - colptrS[colS+1] = ptr - colS += 1 - end - rowvalS[ptr] = rowS - ptr += 1 - end - colA += 1 - end - @inbounds while colS <= nS - colptrS[colS+1] = ptr - colS += 1 - end -end - -function reinterpret(::Type{T}, a::SparseMatrixCSC{Tv,Ti}, dims::NTuple{N,Int}) where {T,Tv,Ti,N} - if sizeof(T) != sizeof(Tv) - throw(ArgumentError("SparseMatrixCSC reinterpret is only supported for element types of the same size")) - end - if prod(dims) != length(a) - throw(DimensionMismatch("new dimensions $(dims) must be consistent with array size $(length(a))")) - end - mS,nS = dims - mA,nA = size(a) - numnz = nnz(a) - colptr = Vector{Ti}(nS+1) - rowval = similar(a.rowval) - nzval = reinterpret(T, a.nzval) - - sparse_compute_reshaped_colptr_and_rowval(colptr, rowval, mS, nS, a.colptr, a.rowval, mA, nA) - - return SparseMatrixCSC(mS, nS, colptr, rowval, nzval) -end - -function copy(ra::ReshapedArray{<:Any,2,<:SparseMatrixCSC}) - mS,nS = size(ra) - a = parent(ra) - mA,nA = size(a) - numnz = nnz(a) - colptr = similar(a.colptr, nS+1) - rowval = similar(a.rowval) - nzval = copy(a.nzval) - - sparse_compute_reshaped_colptr_and_rowval(colptr, rowval, mS, nS, a.colptr, a.rowval, mA, nA) - - return SparseMatrixCSC(mS, nS, colptr, rowval, nzval) -end - -## Constructors - -copy(S::SparseMatrixCSC) = - SparseMatrixCSC(S.m, S.n, copy(S.colptr), copy(S.rowval), copy(S.nzval)) - -function copy!(A::SparseMatrixCSC, B::SparseMatrixCSC) - # If the two matrices have the same length then all the - # elements in A will be overwritten. - if length(A) == length(B) - resize!(A.nzval, length(B.nzval)) - resize!(A.rowval, length(B.rowval)) - if size(A) == size(B) - # Simple case: we can simply copy the internal fields of B to A. - copy!(A.colptr, B.colptr) - copy!(A.rowval, B.rowval) - else - # This is like a "reshape B into A". - sparse_compute_reshaped_colptr_and_rowval(A.colptr, A.rowval, A.m, A.n, B.colptr, B.rowval, B.m, B.n) - end - else - length(A) >= length(B) || throw(BoundsError()) - lB = length(B) - nnzA = nnz(A) - nnzB = nnz(B) - # Up to which col, row, and ptr in rowval/nzval will A be overwritten? - lastmodcolA = div(lB - 1, A.m) + 1 - lastmodrowA = mod(lB - 1, A.m) + 1 - lastmodptrA = A.colptr[lastmodcolA] - while lastmodptrA < A.colptr[lastmodcolA+1] && A.rowval[lastmodptrA] <= lastmodrowA - lastmodptrA += 1 - end - lastmodptrA -= 1 - if lastmodptrA >= nnzB - # A will have fewer non-zero elements; unmodified elements are kept at the end. - deleteat!(A.rowval, nnzB+1:lastmodptrA) - deleteat!(A.nzval, nnzB+1:lastmodptrA) - else - # A will have more non-zero elements; unmodified elements are kept at the end. - resize!(A.rowval, nnzB + nnzA - lastmodptrA) - resize!(A.nzval, nnzB + nnzA - lastmodptrA) - copy!(A.rowval, nnzB+1, A.rowval, lastmodptrA+1, nnzA-lastmodptrA) - copy!(A.nzval, nnzB+1, A.nzval, lastmodptrA+1, nnzA-lastmodptrA) - end - # Adjust colptr accordingly. - @inbounds for i in 2:length(A.colptr) - A.colptr[i] += nnzB - lastmodptrA - end - sparse_compute_reshaped_colptr_and_rowval(A.colptr, A.rowval, A.m, lastmodcolA-1, B.colptr, B.rowval, B.m, B.n) - end - copy!(A.nzval, B.nzval) - return A -end - -function similar(S::SparseMatrixCSC, ::Type{Tv} = eltype(S)) where Tv - SparseMatrixCSC(S.m, S.n, copy(S.colptr), copy(S.rowval), Vector{Tv}(length(S.nzval))) -end - -function similar(S::SparseMatrixCSC, ::Type{Tv}, ::Type{Ti}) where {Tv,Ti} - new_colptr = copy!(similar(S.colptr, Ti), S.colptr) - new_rowval = copy!(similar(S.rowval, Ti), S.rowval) - new_nzval = copy!(similar(S.nzval, Tv), S.nzval) - SparseMatrixCSC(S.m, S.n, new_colptr, new_rowval, new_nzval) -end -@inline similar(S::SparseMatrixCSC, ::Type{Tv}, d::Dims) where {Tv} = spzeros(Tv, d...) - -# convert'ing between SparseMatrixCSC types -convert(::Type{AbstractMatrix{Tv}}, A::SparseMatrixCSC{Tv}) where {Tv} = A -convert(::Type{AbstractMatrix{Tv}}, A::SparseMatrixCSC) where {Tv} = convert(SparseMatrixCSC{Tv}, A) -convert(::Type{SparseMatrixCSC{Tv}}, S::SparseMatrixCSC{Tv}) where {Tv} = S -convert(::Type{SparseMatrixCSC{Tv}}, S::SparseMatrixCSC) where {Tv} = convert(SparseMatrixCSC{Tv,eltype(S.colptr)}, S) -convert(::Type{SparseMatrixCSC{Tv,Ti}}, S::SparseMatrixCSC{Tv,Ti}) where {Tv,Ti} = S -function convert(::Type{SparseMatrixCSC{Tv,Ti}}, S::SparseMatrixCSC) where {Tv,Ti} - eltypeTicolptr = convert(Vector{Ti}, S.colptr) - eltypeTirowval = convert(Vector{Ti}, S.rowval) - eltypeTvnzval = convert(Vector{Tv}, S.nzval) - return SparseMatrixCSC(S.m, S.n, eltypeTicolptr, eltypeTirowval, eltypeTvnzval) -end -# convert'ing from other matrix types to SparseMatrixCSC (also see sparse()) -convert(::Type{SparseMatrixCSC}, M::Matrix) = sparse(M) -convert(::Type{SparseMatrixCSC}, M::AbstractMatrix{Tv}) where {Tv} = convert(SparseMatrixCSC{Tv,Int}, M) -convert(::Type{SparseMatrixCSC{Tv}}, M::AbstractMatrix{Tv}) where {Tv} = convert(SparseMatrixCSC{Tv,Int}, M) -function convert(::Type{SparseMatrixCSC{Tv,Ti}}, M::AbstractMatrix) where {Tv,Ti} - (I, J, V) = findnz(M) - eltypeTiI = convert(Vector{Ti}, I) - eltypeTiJ = convert(Vector{Ti}, J) - eltypeTvV = convert(Vector{Tv}, V) - return sparse_IJ_sorted!(eltypeTiI, eltypeTiJ, eltypeTvV, size(M)...) -end -# convert'ing from SparseMatrixCSC to other matrix types -function convert(::Type{Matrix}, S::SparseMatrixCSC{Tv}) where Tv - # Handle cases where zero(Tv) is not defined but the array is dense. - A = length(S) == nnz(S) ? Matrix{Tv}(S.m, S.n) : zeros(Tv, S.m, S.n) - for Sj in 1:S.n - for Sk in nzrange(S, Sj) - Si = S.rowval[Sk] - Sv = S.nzval[Sk] - A[Si, Sj] = Sv - end - end - return A -end -convert(::Type{Array}, S::SparseMatrixCSC) = convert(Matrix, S) -full(S::SparseMatrixCSC) = convert(Array, S) - -""" - full(S) - -Convert a sparse matrix or vector `S` into a dense matrix or vector. - -# Example -```jldoctest -julia> A = speye(3) -3×3 SparseMatrixCSC{Float64,Int64} with 3 stored entries: - [1, 1] = 1.0 - [2, 2] = 1.0 - [3, 3] = 1.0 - -julia> full(A) -3×3 Array{Float64,2}: - 1.0 0.0 0.0 - 0.0 1.0 0.0 - 0.0 0.0 1.0 -``` -""" -full - -float(S::SparseMatrixCSC) = SparseMatrixCSC(S.m, S.n, copy(S.colptr), copy(S.rowval), float.(S.nzval)) - -complex(S::SparseMatrixCSC) = SparseMatrixCSC(S.m, S.n, copy(S.colptr), copy(S.rowval), complex(copy(S.nzval))) - -# Construct a sparse vector - -# Note that unlike `vec` for arrays, this does not share data -vec(S::SparseMatrixCSC) = S[:] - -""" - sparse(A) - -Convert an AbstractMatrix `A` into a sparse matrix. - -# Example -```jldoctest -julia> A = eye(3) -3×3 Array{Float64,2}: - 1.0 0.0 0.0 - 0.0 1.0 0.0 - 0.0 0.0 1.0 - -julia> sparse(A) -3×3 SparseMatrixCSC{Float64,Int64} with 3 stored entries: - [1, 1] = 1.0 - [2, 2] = 1.0 - [3, 3] = 1.0 -``` -""" -sparse(A::AbstractMatrix{Tv}) where {Tv} = convert(SparseMatrixCSC{Tv,Int}, A) - -sparse(S::SparseMatrixCSC) = copy(S) - -sparse_IJ_sorted!(I,J,V,m,n) = sparse_IJ_sorted!(I,J,V,m,n,+) - -sparse_IJ_sorted!(I,J,V::AbstractVector{Bool},m,n) = sparse_IJ_sorted!(I,J,V,m,n,|) - -function sparse_IJ_sorted!(I::AbstractVector{Ti}, J::AbstractVector{Ti}, - V::AbstractVector, - m::Integer, n::Integer, combine::Function) where Ti<:Integer - m = m < 0 ? 0 : m - n = n < 0 ? 0 : n - if isempty(V); return spzeros(eltype(V),Ti,m,n); end - - cols = zeros(Ti, n+1) - cols[1] = 1 # For cumsum purposes - cols[J[1] + 1] = 1 - - lastdup = 1 - ndups = 0 - I_lastdup = I[1] - J_lastdup = J[1] - L = length(I) - - @inbounds for k=2:L - if I[k] == I_lastdup && J[k] == J_lastdup - V[lastdup] = combine(V[lastdup], V[k]) - ndups += 1 - else - cols[J[k] + 1] += 1 - lastdup = k-ndups - I_lastdup = I[k] - J_lastdup = J[k] - if ndups != 0 - I[lastdup] = I_lastdup - V[lastdup] = V[k] - end - end - end - - colptr = cumsum!(similar(cols), cols) - - # Allow up to 20% slack - if ndups > 0.2*L - numnz = L-ndups - deleteat!(I, (numnz+1):L) - deleteat!(V, (numnz+1):length(V)) - end - - return SparseMatrixCSC(m, n, colptr, I, V) -end - -""" - sparse(I, J, V,[ m, n, combine]) - -Create a sparse matrix `S` of dimensions `m x n` such that `S[I[k], J[k]] = V[k]`. The -`combine` function is used to combine duplicates. If `m` and `n` are not specified, they -are set to `maximum(I)` and `maximum(J)` respectively. If the `combine` function is not -supplied, `combine` defaults to `+` unless the elements of `V` are Booleans in which case -`combine` defaults to `|`. All elements of `I` must satisfy `1 <= I[k] <= m`, and all -elements of `J` must satisfy `1 <= J[k] <= n`. Numerical zeros in (`I`, `J`, `V`) are -retained as structural nonzeros; to drop numerical zeros, use [`dropzeros!`](@ref). - -For additional documentation and an expert driver, see `Base.SparseArrays.sparse!`. - -# Example -```jldoctest -julia> Is = [1; 2; 3]; - -julia> Js = [1; 2; 3]; - -julia> Vs = [1; 2; 3]; - -julia> sparse(Is, Js, Vs) -3×3 SparseMatrixCSC{Int64,Int64} with 3 stored entries: - [1, 1] = 1 - [2, 2] = 2 - [3, 3] = 3 -``` -""" -function sparse(I::AbstractVector{Ti}, J::AbstractVector{Ti}, V::AbstractVector{Tv}, m::Integer, n::Integer, combine) where {Tv,Ti<:Integer} - coolen = length(I) - if length(J) != coolen || length(V) != coolen - throw(ArgumentError(string("the first three arguments' lengths must match, ", - "length(I) (=$(length(I))) == length(J) (= $(length(J))) == length(V) (= ", - "$(length(V)))"))) - end - - if m == 0 || n == 0 || coolen == 0 - if coolen != 0 - if n == 0 - throw(ArgumentError("column indices J[k] must satisfy 1 <= J[k] <= n")) - elseif m == 0 - throw(ArgumentError("row indices I[k] must satisfy 1 <= I[k] <= m")) - end - end - SparseMatrixCSC(m, n, ones(Ti, n+1), Vector{Ti}(), Vector{Tv}()) - else - # Allocate storage for CSR form - csrrowptr = Vector{Ti}(m+1) - csrcolval = Vector{Ti}(coolen) - csrnzval = Vector{Tv}(coolen) - - # Allocate storage for the CSC form's column pointers and a necessary workspace - csccolptr = Vector{Ti}(n+1) - klasttouch = Vector{Ti}(n) - - # Allocate empty arrays for the CSC form's row and nonzero value arrays - # The parent method called below automagically resizes these arrays - cscrowval = Vector{Ti}() - cscnzval = Vector{Tv}() - - sparse!(I, J, V, m, n, combine, klasttouch, - csrrowptr, csrcolval, csrnzval, - csccolptr, cscrowval, cscnzval) - end -end - -sparse(I::AbstractVector, J::AbstractVector, V::AbstractVector, m::Integer, n::Integer, combine) = - sparse(AbstractVector{Int}(I), AbstractVector{Int}(J), V, m, n, combine) - -""" - sparse!{Tv,Ti<:Integer}( - I::AbstractVector{Ti}, J::AbstractVector{Ti}, V::AbstractVector{Tv}, - m::Integer, n::Integer, combine, klasttouch::Vector{Ti}, - csrrowptr::Vector{Ti}, csrcolval::Vector{Ti}, csrnzval::Vector{Tv}, - [csccolptr::Vector{Ti}], [cscrowval::Vector{Ti}, cscnzval::Vector{Tv}] ) - -Parent of and expert driver for [`sparse`](@ref); -see [`sparse`](@ref) for basic usage. This method -allows the user to provide preallocated storage for `sparse`'s intermediate objects and -result as described below. This capability enables more efficient successive construction -of [`SparseMatrixCSC`](@ref)s from coordinate representations, and also enables extraction -of an unsorted-column representation of the result's transpose at no additional cost. - -This method consists of three major steps: (1) Counting-sort the provided coordinate -representation into an unsorted-row CSR form including repeated entries. (2) Sweep through -the CSR form, simultaneously calculating the desired CSC form's column-pointer array, -detecting repeated entries, and repacking the CSR form with repeated entries combined; -this stage yields an unsorted-row CSR form with no repeated entries. (3) Counting-sort the -preceding CSR form into a fully-sorted CSC form with no repeated entries. - -Input arrays `csrrowptr`, `csrcolval`, and `csrnzval` constitute storage for the -intermediate CSR forms and require `length(csrrowptr) >= m + 1`, -`length(csrcolval) >= length(I)`, and `length(csrnzval >= length(I))`. Input -array `klasttouch`, workspace for the second stage, requires `length(klasttouch) >= n`. -Optional input arrays `csccolptr`, `cscrowval`, and `cscnzval` constitute storage for the -returned CSC form `S`. `csccolptr` requires `length(csccolptr) >= n + 1`. If necessary, -`cscrowval` and `cscnzval` are automatically resized to satisfy -`length(cscrowval) >= nnz(S)` and `length(cscnzval) >= nnz(S)`; hence, if `nnz(S)` is -unknown at the outset, passing in empty vectors of the appropriate type (`Vector{Ti}()` -and `Vector{Tv}()` respectively) suffices, or calling the `sparse!` method -neglecting `cscrowval` and `cscnzval`. - -On return, `csrrowptr`, `csrcolval`, and `csrnzval` contain an unsorted-column -representation of the result's transpose. - -You may reuse the input arrays' storage (`I`, `J`, `V`) for the output arrays -(`csccolptr`, `cscrowval`, `cscnzval`). For example, you may call -`sparse!(I, J, V, csrrowptr, csrcolval, csrnzval, I, J, V)`. - -For the sake of efficiency, this method performs no argument checking beyond -`1 <= I[k] <= m` and `1 <= J[k] <= n`. Use with care. Testing with `--check-bounds=yes` -is wise. - -This method runs in `O(m, n, length(I))` time. The HALFPERM algorithm described in -F. Gustavson, "Two fast algorithms for sparse matrices: multiplication and permuted -transposition," ACM TOMS 4(3), 250-269 (1978) inspired this method's use of a pair of -counting sorts. -""" -function sparse!(I::AbstractVector{Ti}, J::AbstractVector{Ti}, - V::AbstractVector{Tv}, m::Integer, n::Integer, combine, klasttouch::Vector{Ti}, - csrrowptr::Vector{Ti}, csrcolval::Vector{Ti}, csrnzval::Vector{Tv}, - csccolptr::Vector{Ti}, cscrowval::Vector{Ti}, cscnzval::Vector{Tv}) where {Tv,Ti<:Integer} - - # Compute the CSR form's row counts and store them shifted forward by one in csrrowptr - fill!(csrrowptr, 0) - coolen = length(I) - @inbounds for k in 1:coolen - Ik = I[k] - if 1 > Ik || m < Ik - throw(ArgumentError("row indices I[k] must satisfy 1 <= I[k] <= m")) - end - csrrowptr[Ik+1] += 1 - end - - # Compute the CSR form's rowptrs and store them shifted forward by one in csrrowptr - countsum = 1 - csrrowptr[1] = 1 - @inbounds for i in 2:(m+1) - overwritten = csrrowptr[i] - csrrowptr[i] = countsum - countsum += overwritten - end - - # Counting-sort the column and nonzero values from J and V into csrcolval and csrnzval - # Tracking write positions in csrrowptr corrects the row pointers - @inbounds for k in 1:coolen - Ik, Jk = I[k], J[k] - if 1 > Jk || n < Jk - throw(ArgumentError("column indices J[k] must satisfy 1 <= J[k] <= n")) - end - csrk = csrrowptr[Ik+1] - csrrowptr[Ik+1] = csrk+1 - csrcolval[csrk] = Jk - csrnzval[csrk] = V[k] - end - # This completes the unsorted-row, has-repeats CSR form's construction - - # Sweep through the CSR form, simultaneously (1) caculating the CSC form's column - # counts and storing them shifted forward by one in csccolptr; (2) detecting repeated - # entries; and (3) repacking the CSR form with the repeated entries combined. - # - # Minimizing extraneous communication and nonlocality of reference, primarily by using - # only a single auxiliary array in this step, is the key to this method's performance. - fill!(csccolptr, 0) - fill!(klasttouch, 0) - writek = 1 - newcsrrowptri = 1 - origcsrrowptri = 1 - origcsrrowptrip1 = csrrowptr[2] - @inbounds for i in 1:m - for readk in origcsrrowptri:(origcsrrowptrip1-1) - j = csrcolval[readk] - if klasttouch[j] < newcsrrowptri - klasttouch[j] = writek - if writek != readk - csrcolval[writek] = j - csrnzval[writek] = csrnzval[readk] - end - writek += 1 - csccolptr[j+1] += 1 - else - klt = klasttouch[j] - csrnzval[klt] = combine(csrnzval[klt], csrnzval[readk]) - end - end - newcsrrowptri = writek - origcsrrowptri = origcsrrowptrip1 - origcsrrowptrip1 != writek && (csrrowptr[i+1] = writek) - i < m && (origcsrrowptrip1 = csrrowptr[i+2]) - end - - # Compute the CSC form's colptrs and store them shifted forward by one in csccolptr - countsum = 1 - csccolptr[1] = 1 - @inbounds for j in 2:(n+1) - overwritten = csccolptr[j] - csccolptr[j] = countsum - countsum += overwritten - end - - # Now knowing the CSC form's entry count, resize cscrowval and cscnzval if necessary - cscnnz = countsum - 1 - length(cscrowval) < cscnnz && resize!(cscrowval, cscnnz) - length(cscnzval) < cscnnz && resize!(cscnzval, cscnnz) - - # Finally counting-sort the row and nonzero values from the CSR form into cscrowval and - # cscnzval. Tracking write positions in csccolptr corrects the column pointers. - @inbounds for i in 1:m - for csrk in csrrowptr[i]:(csrrowptr[i+1]-1) - j = csrcolval[csrk] - x = csrnzval[csrk] - csck = csccolptr[j+1] - csccolptr[j+1] = csck+1 - cscrowval[csck] = i - cscnzval[csck] = x - end - end - - SparseMatrixCSC(m, n, csccolptr, cscrowval, cscnzval) -end -function sparse!(I::AbstractVector{Ti}, J::AbstractVector{Ti}, - V::AbstractVector{Tv}, m::Integer, n::Integer, combine, klasttouch::Vector{Ti}, - csrrowptr::Vector{Ti}, csrcolval::Vector{Ti}, csrnzval::Vector{Tv}, - csccolptr::Vector{Ti}) where {Tv,Ti<:Integer} - sparse!(I, J, V, m, n, combine, klasttouch, - csrrowptr, csrcolval, csrnzval, - csccolptr, Vector{Ti}(), Vector{Tv}()) -end -function sparse!(I::AbstractVector{Ti}, J::AbstractVector{Ti}, - V::AbstractVector{Tv}, m::Integer, n::Integer, combine, klasttouch::Vector{Ti}, - csrrowptr::Vector{Ti}, csrcolval::Vector{Ti}, csrnzval::Vector{Tv}) where {Tv,Ti<:Integer} - sparse!(I, J, V, m, n, combine, klasttouch, - csrrowptr, csrcolval, csrnzval, - Vector{Ti}(n+1), Vector{Ti}(), Vector{Tv}()) -end - -dimlub(I) = isempty(I) ? 0 : Int(maximum(I)) #least upper bound on required sparse matrix dimension - -sparse(I,J,v::Number) = sparse(I, J, fill(v,length(I))) - -sparse(I,J,V::AbstractVector) = sparse(I, J, V, dimlub(I), dimlub(J)) - -sparse(I,J,v::Number,m,n) = sparse(I, J, fill(v,length(I)), Int(m), Int(n)) - -sparse(I,J,V::AbstractVector,m,n) = sparse(I, J, V, Int(m), Int(n), +) - -sparse(I,J,V::AbstractVector{Bool},m,n) = sparse(I, J, V, Int(m), Int(n), |) - -sparse(I,J,v::Number,m,n,combine::Function) = sparse(I, J, fill(v,length(I)), Int(m), Int(n), combine) - -function sparse(T::SymTridiagonal) - m = length(T.dv) - return sparse([1:m;2:m;1:m-1],[1:m;1:m-1;2:m],[T.dv;T.ev;T.ev], Int(m), Int(m)) -end - -function sparse(T::Tridiagonal) - m = length(T.d) - return sparse([1:m;2:m;1:m-1],[1:m;1:m-1;2:m],[T.d;T.dl;T.du], Int(m), Int(m)) -end - -function sparse(B::Bidiagonal) - m = length(B.dv) - B.isupper || return sparse([1:m;2:m],[1:m;1:m-1],[B.dv;B.ev], Int(m), Int(m)) # lower bidiagonal - return sparse([1:m;1:m-1],[1:m;2:m],[B.dv;B.ev], Int(m), Int(m)) # upper bidiagonal -end - -## Transposition and permutation methods - -""" - halfperm!{Tv,Ti}(X::SparseMatrixCSC{Tv,Ti}, A::SparseMatrixCSC{Tv,Ti}, - q::AbstractVector{<:Integer}, f::Function = identity) - -Column-permute and transpose `A`, simultaneously applying `f` to each entry of `A`, storing -the result `(f(A)Q)^T` (`map(f, transpose(A[:,q]))`) in `X`. - -`X`'s dimensions must match those of `transpose(A)` (`X.m == A.n` and `X.n == A.m`), and `X` -must have enough storage to accommodate all allocated entries in `A` (`length(X.rowval) >= nnz(A)` -and `length(X.nzval) >= nnz(A)`). Column-permutation `q`'s length must match `A`'s column -count (`length(q) == A.n`). - -This method is the parent of several methods performing transposition and permutation -operations on [`SparseMatrixCSC`](@ref)s. As this method performs no argument checking, -prefer the safer child methods (`[c]transpose[!]`, `permute[!]`) to direct use. - -This method implements the `HALFPERM` algorithm described in F. Gustavson, "Two fast -algorithms for sparse matrices: multiplication and permuted transposition," ACM TOMS 4(3), -250-269 (1978). The algorithm runs in `O(A.m, A.n, nnz(A))` time and requires no space -beyond that passed in. -""" -function halfperm!(X::SparseMatrixCSC{Tv,Ti}, A::SparseMatrixCSC{Tv,Ti}, - q::AbstractVector{<:Integer}, f::Function = identity) where {Tv,Ti} - _computecolptrs_halfperm!(X, A) - _distributevals_halfperm!(X, A, q, f) - return X -end -""" -Helper method for `halfperm!`. Computes `transpose(A[:,q])`'s column pointers, storing them -shifted one position forward in `X.colptr`; `_distributevals_halfperm!` fixes this shift. -""" -function _computecolptrs_halfperm!(X::SparseMatrixCSC{Tv,Ti}, A::SparseMatrixCSC{Tv,Ti}) where {Tv,Ti} - # Compute `transpose(A[:,q])`'s column counts. Store shifted forward one position in X.colptr. - fill!(X.colptr, 0) - @inbounds for k in 1:nnz(A) - X.colptr[A.rowval[k] + 1] += 1 - end - # Compute `transpose(A[:,q])`'s column pointers. Store shifted forward one position in X.colptr. - X.colptr[1] = 1 - countsum = 1 - @inbounds for k in 2:(A.m + 1) - overwritten = X.colptr[k] - X.colptr[k] = countsum - countsum += overwritten - end -end -""" -Helper method for `halfperm!`. With `transpose(A[:,q])`'s column pointers shifted one -position forward in `X.colptr`, computes `map(f, transpose(A[:,q]))` by appropriately -distributing `A.rowval` and `f`-transformed `A.nzval` into `X.rowval` and `X.nzval` -respectively. Simultaneously fixes the one-position-forward shift in `X.colptr`. -""" -function _distributevals_halfperm!(X::SparseMatrixCSC{Tv,Ti}, - A::SparseMatrixCSC{Tv,Ti}, q::AbstractVector{<:Integer}, f::Function) where {Tv,Ti} - @inbounds for Xi in 1:A.n - Aj = q[Xi] - for Ak in nzrange(A, Aj) - Ai = A.rowval[Ak] - Xk = X.colptr[Ai + 1] - X.rowval[Xk] = Xi - X.nzval[Xk] = f(A.nzval[Ak]) - X.colptr[Ai + 1] += 1 - end - end - return # kill potential type instability -end - -function ftranspose!(X::SparseMatrixCSC{Tv,Ti}, A::SparseMatrixCSC{Tv,Ti}, f::Function) where {Tv,Ti} - # Check compatibility of source argument A and destination argument X - if X.n != A.m - throw(DimensionMismatch(string("destination argument `X`'s column count, ", - "`X.n (= $(X.n))`, must match source argument `A`'s row count, `A.m (= $(A.m))`"))) - elseif X.m != A.n - throw(DimensionMismatch(string("destination argument `X`'s row count, - `X.m (= $(X.m))`, must match source argument `A`'s column count, `A.n (= $(A.n))`"))) - elseif length(X.rowval) < nnz(A) - throw(ArgumentError(string("the length of destination argument `X`'s `rowval` ", - "array, `length(X.rowval) (= $(length(X.rowval)))`, must be greater than or ", - "equal to source argument `A`'s allocated entry count, `nnz(A) (= $(nnz(A)))`"))) - elseif length(X.nzval) < nnz(A) - throw(ArgumentError(string("the length of destination argument `X`'s `nzval` ", - "array, `length(X.nzval) (= $(length(X.nzval)))`, must be greater than or ", - "equal to source argument `A`'s allocated entry count, `nnz(A) (= $(nnz(A)))`"))) - end - halfperm!(X, A, 1:A.n, f) -end -transpose!(X::SparseMatrixCSC{Tv,Ti}, A::SparseMatrixCSC{Tv,Ti}) where {Tv,Ti} = ftranspose!(X, A, identity) -ctranspose!(X::SparseMatrixCSC{Tv,Ti}, A::SparseMatrixCSC{Tv,Ti}) where {Tv,Ti} = ftranspose!(X, A, conj) - -function ftranspose(A::SparseMatrixCSC{Tv,Ti}, f::Function) where {Tv,Ti} - X = SparseMatrixCSC(A.n, A.m, Vector{Ti}(A.m+1), Vector{Ti}(nnz(A)), Vector{Tv}(nnz(A))) - halfperm!(X, A, 1:A.n, f) -end -transpose(A::SparseMatrixCSC) = ftranspose(A, identity) -ctranspose(A::SparseMatrixCSC) = ftranspose(A, conj) - -""" - unchecked_noalias_permute!{Tv,Ti}(X::SparseMatrixCSC{Tv,Ti}, - A::SparseMatrixCSC{Tv,Ti}, p::AbstractVector{<:Integer}, - q::AbstractVector{<:Integer}, C::SparseMatrixCSC{Tv,Ti}) - -See [`permute!`](@ref) for basic usage. Parent of `permute[!]` -methods operating on `SparseMatrixCSC`s that assume none of `X`, `A`, and `C` alias each -other. As this method performs no argument checking, prefer the safer child methods -(`permute[!]`) to direct use. - -This method consists of two major steps: (1) Column-permute (`Q`,`I[:,q]`) and transpose `A` -to generate intermediate result `(AQ)^T` (`transpose(A[:,q])`) in `C`. (2) Column-permute -(`P^T`, I[:,p]) and transpose intermediate result `(AQ)^T` to generate result -`((AQ)^T P^T)^T = PAQ` (`A[p,q]`) in `X`. - -The first step is a call to `halfperm!`, and the second is a variant on `halfperm!` that -avoids an unnecessary length-`nnz(A)` array-sweep and associated recomputation of column -pointers. See [`halfperm!`](:func:Base.SparseArrays.halfperm!) for additional algorithmic -information. - -See also: `unchecked_aliasing_permute!` -""" -function unchecked_noalias_permute!{Tv,Ti}(X::SparseMatrixCSC{Tv,Ti}, - A::SparseMatrixCSC{Tv,Ti}, p::AbstractVector{<:Integer}, - q::AbstractVector{<:Integer}, C::SparseMatrixCSC{Tv,Ti}) - halfperm!(C, A, q) - _computecolptrs_permute!(X, A, q, X.colptr) - _distributevals_halfperm!(X, C, p, identity) - return X -end -""" - unchecked_aliasing_permute!{Tv,Ti}(A::SparseMatrixCSC{Tv,Ti}, - p::AbstractVector{<:Integer}, q::AbstractVector{<:Integer}, - C::SparseMatrixCSC{Tv,Ti}, workcolptr::Vector{Ti}) - -See [`permute!`](@ref) for basic usage. Parent of `permute!` -methods operating on [`SparseMatrixCSC`](@ref)s where the source and destination matrices -are the same. See `unchecked_noalias_permute!` -for additional information; these methods are identical but for this method's requirement of -the additional `workcolptr`, `length(workcolptr) >= A.n + 1`, which enables efficient -handling of the source-destination aliasing. -""" -function unchecked_aliasing_permute!{Tv,Ti}(A::SparseMatrixCSC{Tv,Ti}, - p::AbstractVector{<:Integer}, q::AbstractVector{<:Integer}, - C::SparseMatrixCSC{Tv,Ti}, workcolptr::Vector{Ti}) - halfperm!(C, A, q) - _computecolptrs_permute!(A, A, q, workcolptr) - _distributevals_halfperm!(A, C, p, identity) - return A -end -""" -Helper method for `unchecked_noalias_permute!` and `unchecked_aliasing_permute!`. -Computes `PAQ`'s column pointers, storing them shifted one position forward in `X.colptr`; -`_distributevals_halfperm!` fixes this shift. Saves some work relative to -`_computecolptrs_halfperm!` as described in `uncheckednoalias_permute!`'s documentation. -""" -function _computecolptrs_permute!{Tv,Ti}(X::SparseMatrixCSC{Tv,Ti}, - A::SparseMatrixCSC{Tv,Ti}, q::AbstractVector{<:Integer}, workcolptr::Vector{Ti}) - # Compute `A[p,q]`'s column counts. Store shifted forward one position in workcolptr. - @inbounds for k in 1:A.n - workcolptr[k+1] = A.colptr[q[k] + 1] - A.colptr[q[k]] - end - # Compute `A[p,q]`'s column pointers. Store shifted forward one position in X.colptr. - X.colptr[1] = 1 - countsum = 1 - @inbounds for k in 2:(X.n + 1) - overwritten = workcolptr[k] - X.colptr[k] = countsum - countsum += overwritten - end -end - -""" -Helper method for `permute` and `permute!` methods operating on `SparseMatrixCSC`s. -Checks compatibility of source argument `A`, row-permutation argument `p`, and -column-permutation argument `q`. -""" -function _checkargs_sourcecompatperms_permute!(A::SparseMatrixCSC, - p::AbstractVector{<:Integer}, q::AbstractVector{<:Integer}) - if length(q) != A.n - throw(DimensionMismatch(string("the length of column-permutation argument `q`, ", - "`length(q) (= $(length(q)))`, must match source argument `A`'s column ", - "count, `A.n (= $(A.n))`"))) - elseif length(p) != A.m - throw(DimensionMismatch(string("the length of row-permutation argument `p`, ", - "`length(p) (= $(length(p)))`, must match source argument `A`'s row count, ", - "`A.m (= $(A.m))`"))) - end -end -""" -Helper method for `permute` and `permute!` methods operating on `SparseMatrixCSC`s. -Checks whether row- and column- permutation arguments `p` and `q` are valid permutations. -""" -function _checkargs_permutationsvalid_permute!{Ti<:Integer}( - p::AbstractVector{<:Integer}, pcheckspace::Vector{Ti}, - q::AbstractVector{<:Integer}, qcheckspace::Vector{Ti}) - if !_ispermutationvalid_permute!(p, pcheckspace) - throw(ArgumentError("row-permutation argument `p` must be a valid permutation")) - elseif !_ispermutationvalid_permute!(q, qcheckspace) - throw(ArgumentError("column-permutation argument `q` must be a valid permutation")) - end -end -function _ispermutationvalid_permute!(perm::AbstractVector{<:Integer}, - checkspace::Vector{<:Integer}) - n = length(perm) - checkspace[1:n] = 0 - for k in perm - (0 < k ≤ n) && ((checkspace[k] ⊻= 1) == 1) || return false - end - return true -end -""" -Helper method for `permute` and `permute!` methods operating on `SparseMatrixCSC`s. -Checks compatibility of source argument `A` and destination argument `X`. -""" -function _checkargs_sourcecompatdest_permute!(A::SparseMatrixCSC{Tv,Ti}, - X::SparseMatrixCSC{Tv,Ti}) where {Tv,Ti} - if X.m != A.m - throw(DimensionMismatch(string("destination argument `X`'s row count, ", - "`X.m (= $(X.m))`, must match source argument `A`'s row count, `A.m (= $(A.m))`"))) - elseif X.n != A.n - throw(DimensionMismatch(string("destination argument `X`'s column count, ", - "`X.n (= $(X.n))`, must match source argument `A`'s column count, `A.n (= $(A.n))`"))) - elseif length(X.rowval) < nnz(A) - throw(ArgumentError(string("the length of destination argument `X`'s `rowval` ", - "array, `length(X.rowval) (= $(length(X.rowval)))`, must be greater than or ", - "equal to source argument `A`'s allocated entry count, `nnz(A) (= $(nnz(A)))`"))) - elseif length(X.nzval) < nnz(A) - throw(ArgumentError(string("the length of destination argument `X`'s `nzval` ", - "array, `length(X.nzval) (= $(length(X.nzval)))`, must be greater than or ", - "equal to source argument `A`'s allocated entry count, `nnz(A) (= $(nnz(A)))`"))) - end -end -""" -Helper method for `permute` and `permute!` methods operating on `SparseMatrixCSC`s. -Checks compatibility of source argument `A` and intermediate result argument `C`. -""" -function _checkargs_sourcecompatworkmat_permute!(A::SparseMatrixCSC{Tv,Ti}, - C::SparseMatrixCSC{Tv,Ti}) where {Tv,Ti} - if C.n != A.m - throw(DimensionMismatch(string("intermediate result argument `C`'s column count, ", - "`C.n (= $(C.n))`, must match source argument `A`'s row count, `A.m (= $(A.m))`"))) - elseif C.m != A.n - throw(DimensionMismatch(string("intermediate result argument `C`'s row count, ", - "`C.m (= $(C.m))`, must match source argument `A`'s column count, `A.n (= $(A.n))`"))) - elseif length(C.rowval) < nnz(A) - throw(ArgumentError(string("the length of intermediate result argument `C`'s ", - "`rowval` array, `length(C.rowval) (= $(length(C.rowval)))`, must be greater than ", - "or equal to source argument `A`'s allocated entry count, `nnz(A) (= $(nnz(A)))`"))) - elseif length(C.nzval) < nnz(A) - throw(ArgumentError(string("the length of intermediate result argument `C`'s ", - "`rowval` array, `length(C.nzval) (= $(length(C.nzval)))`, must be greater than ", - "or equal to source argument `A`'s allocated entry count, `nnz(A)` (= $(nnz(A)))"))) - end -end -""" -Helper method for `permute` and `permute!` methods operating on `SparseMatrixCSC`s. -Checks compatibility of source argument `A` and workspace argument `workcolptr`. -""" -function _checkargs_sourcecompatworkcolptr_permute!(A::SparseMatrixCSC{Tv,Ti}, - workcolptr::Vector{Ti}) where {Tv,Ti} - if length(workcolptr) <= A.n - throw(DimensionMismatch(string("argument `workcolptr`'s length, ", - "`length(workcolptr) (= $(length(workcolptr)))`, must exceed source argument ", - "`A`'s column count, `A.n (= $(A.n))`"))) - end -end -""" - permute!{Tv,Ti}(X::SparseMatrixCSC{Tv,Ti}, A::SparseMatrixCSC{Tv,Ti}, - p::AbstractVector{<:Integer}, q::AbstractVector{<:Integer}[, C::SparseMatrixCSC{Tv,Ti}]) - -Bilaterally permute `A`, storing result `PAQ` (`A[p,q]`) in `X`. Stores intermediate result -`(AQ)^T` (`transpose(A[:,q])`) in optional argument `C` if present. Requires that none of -`X`, `A`, and, if present, `C` alias each other; to store result `PAQ` back into `A`, use -the following method lacking `X`: - - permute!{Tv,Ti}(A::SparseMatrixCSC{Tv,Ti}, p::AbstractVector{<:Integer}, - q::AbstractVector{<:Integer}[, C::SparseMatrixCSC{Tv,Ti}[, workcolptr::Vector{Ti}]]) - -`X`'s dimensions must match those of `A` (`X.m == A.m` and `X.n == A.n`), and `X` must -have enough storage to accommodate all allocated entries in `A` (`length(X.rowval) >= nnz(A)` -and `length(X.nzval) >= nnz(A)`). Column-permutation `q`'s length must match `A`'s column -count (`length(q) == A.n`). Row-permutation `p`'s length must match `A`'s row count -(`length(p) == A.m`). - -`C`'s dimensions must match those of `transpose(A)` (`C.m == A.n` and `C.n == A.m`), and `C` -must have enough storage to accommodate all allocated entries in `A` (`length(C.rowval) >= nnz(A)` -and `length(C.nzval) >= nnz(A)`). - -For additional (algorithmic) information, and for versions of these methods that forgo -argument checking, see (unexported) parent methods `unchecked_noalias_permute!` -and `unchecked_aliasing_permute!`. - -See also: [`permute`](@ref). -""" -function permute!{Tv,Ti}(X::SparseMatrixCSC{Tv,Ti}, A::SparseMatrixCSC{Tv,Ti}, - p::AbstractVector{<:Integer}, q::AbstractVector{<:Integer}) - _checkargs_sourcecompatdest_permute!(A, X) - _checkargs_sourcecompatperms_permute!(A, p, q) - C = SparseMatrixCSC(A.n, A.m, Vector{Ti}(A.m + 1), Vector{Ti}(nnz(A)), Vector{Tv}(nnz(A))) - _checkargs_permutationsvalid_permute!(p, C.colptr, q, X.colptr) - unchecked_noalias_permute!(X, A, p, q, C) -end -function permute!{Tv,Ti}(X::SparseMatrixCSC{Tv,Ti}, A::SparseMatrixCSC{Tv,Ti}, - p::AbstractVector{<:Integer}, q::AbstractVector{<:Integer}, - C::SparseMatrixCSC{Tv,Ti}) - _checkargs_sourcecompatdest_permute!(A, X) - _checkargs_sourcecompatperms_permute!(A, p, q) - _checkargs_sourcecompatworkmat_permute!(A, C) - _checkargs_permutationsvalid_permute!(p, C.colptr, q, X.colptr) - unchecked_noalias_permute!(X, A, p, q, C) -end -function permute!{Tv,Ti}(A::SparseMatrixCSC{Tv,Ti}, p::AbstractVector{<:Integer}, - q::AbstractVector{<:Integer}) - _checkargs_sourcecompatperms_permute!(A, p, q) - C = SparseMatrixCSC(A.n, A.m, Vector{Ti}(A.m + 1), Vector{Ti}(nnz(A)), Vector{Tv}(nnz(A))) - workcolptr = Vector{Ti}(A.n + 1) - _checkargs_permutationsvalid_permute!(p, C.colptr, q, workcolptr) - unchecked_aliasing_permute!(A, p, q, C, workcolptr) -end -function permute!{Tv,Ti}(A::SparseMatrixCSC{Tv,Ti}, p::AbstractVector{<:Integer}, - q::AbstractVector{<:Integer}, C::SparseMatrixCSC{Tv,Ti}) - _checkargs_sourcecompatperms_permute!(A, p, q) - _checkargs_sourcecompatworkmat_permute!(A, C) - workcolptr = Vector{Ti}(A.n + 1) - _checkargs_permutationsvalid_permute!(p, C.colptr, q, workcolptr) - unchecked_aliasing_permute!(A, p, q, C, workcolptr) -end -function permute!{Tv,Ti}(A::SparseMatrixCSC{Tv,Ti}, p::AbstractVector{<:Integer}, - q::AbstractVector{<:Integer}, C::SparseMatrixCSC{Tv,Ti}, - workcolptr::Vector{Ti}) - _checkargs_sourcecompatperms_permute!(A, p, q) - _checkargs_sourcecompatworkmat_permute!(A, C) - _checkargs_sourcecompatworkcolptr_permute!(A, workcolptr) - _checkargs_permutationsvalid_permute!(p, C.colptr, q, workcolptr) - unchecked_aliasing_permute!(A, p, q, C, workcolptr) -end -""" - permute{Tv,Ti}(A::SparseMatrixCSC{Tv,Ti}, p::AbstractVector{<:Integer}, - q::AbstractVector{<:Integer}) - -Bilaterally permute `A`, returning `PAQ` (`A[p,q]`). Column-permutation `q`'s length must -match `A`'s column count (`length(q) == A.n`). Row-permutation `p`'s length must match `A`'s -row count (`length(p) == A.m`). - -For expert drivers and additional information, see [`permute!`](@ref). - -# Example -```jldoctest -julia> A = spdiagm([1, 2, 3, 4], 0, 4, 4) + spdiagm([5, 6, 7], 1, 4, 4) -4×4 SparseMatrixCSC{Int64,Int64} with 7 stored entries: - [1, 1] = 1 - [1, 2] = 5 - [2, 2] = 2 - [2, 3] = 6 - [3, 3] = 3 - [3, 4] = 7 - [4, 4] = 4 - -julia> permute(A, [4, 3, 2, 1], [1, 2, 3, 4]) -4×4 SparseMatrixCSC{Int64,Int64} with 7 stored entries: - [4, 1] = 1 - [3, 2] = 2 - [4, 2] = 5 - [2, 3] = 3 - [3, 3] = 6 - [1, 4] = 4 - [2, 4] = 7 - -julia> permute(A, [1, 2, 3, 4], [4, 3, 2, 1]) -4×4 SparseMatrixCSC{Int64,Int64} with 7 stored entries: - [3, 1] = 7 - [4, 1] = 4 - [2, 2] = 6 - [3, 2] = 3 - [1, 3] = 5 - [2, 3] = 2 - [1, 4] = 1 -``` -""" -function permute{Tv,Ti}(A::SparseMatrixCSC{Tv,Ti}, p::AbstractVector{<:Integer}, - q::AbstractVector{<:Integer}) - _checkargs_sourcecompatperms_permute!(A, p, q) - X = SparseMatrixCSC(A.m, A.n, Vector{Ti}(A.n + 1), Vector{Ti}(nnz(A)), Vector{Tv}(nnz(A))) - C = SparseMatrixCSC(A.n, A.m, Vector{Ti}(A.m + 1), Vector{Ti}(nnz(A)), Vector{Tv}(nnz(A))) - _checkargs_permutationsvalid_permute!(p, C.colptr, q, X.colptr) - unchecked_noalias_permute!(X, A, p, q, C) -end - -## fkeep! and children tril!, triu!, droptol!, dropzeros[!] - -""" - fkeep!(A::AbstractSparseArray, f, trim::Bool = true) - -Keep elements of `A` for which test `f` returns `true`. `f`'s signature should be - - f(i::Integer, [j::Integer,] x) -> Bool - -where `i` and `j` are an element's row and column indices and `x` is the element's -value. This method makes a single sweep -through `A`, requiring `O(A.n, nnz(A))`-time for matrices and `O(nnz(A))`-time for vectors -and no space beyond that passed in. If `trim` is `true`, this method trims `A.rowval` or `A.nzind` and -`A.nzval` to length `nnz(A)` after dropping elements. - -# Example -```jldoctest -julia> A = spdiagm([1, 2, 3, 4]) -4×4 SparseMatrixCSC{Int64,Int64} with 4 stored entries: - [1, 1] = 1 - [2, 2] = 2 - [3, 3] = 3 - [4, 4] = 4 - -julia> Base.SparseArrays.fkeep!(A, (i, j, v) -> isodd(v)) -4×4 SparseMatrixCSC{Int64,Int64} with 2 stored entries: - [1, 1] = 1 - [3, 3] = 3 -``` -""" -function fkeep!(A::SparseMatrixCSC, f, trim::Bool = true) - An = A.n - Acolptr = A.colptr - Arowval = A.rowval - Anzval = A.nzval - - # Sweep through columns, rewriting kept elements in their new positions - # and updating the column pointers accordingly as we go. - Awritepos = 1 - oldAcolptrAj = 1 - @inbounds for Aj in 1:An - for Ak in oldAcolptrAj:(Acolptr[Aj+1]-1) - Ai = Arowval[Ak] - Ax = Anzval[Ak] - # If this element should be kept, rewrite in new position - if f(Ai, Aj, Ax) - if Awritepos != Ak - Arowval[Awritepos] = Ai - Anzval[Awritepos] = Ax - end - Awritepos += 1 - end - end - oldAcolptrAj = Acolptr[Aj+1] - Acolptr[Aj+1] = Awritepos - end - - # Trim A's storage if necessary and desired - if trim - Annz = Acolptr[end] - 1 - if length(Arowval) != Annz - resize!(Arowval, Annz) - end - if length(Anzval) != Annz - resize!(Anzval, Annz) - end - end - - A -end - -function tril!(A::SparseMatrixCSC, k::Integer = 0, trim::Bool = true) - if k > A.n-1 || k < 1-A.m - throw(ArgumentError("requested diagonal, $k, out of bounds in matrix of size ($(A.m),$(A.n))")) - end - fkeep!(A, (i, j, x) -> i + k >= j, trim) -end -function triu!(A::SparseMatrixCSC, k::Integer = 0, trim::Bool = true) - if k > A.n-1 || k < 1-A.m - throw(ArgumentError("requested diagonal, $k, out of bounds in matrix of size ($(A.m),$(A.n))")) - end - fkeep!(A, (i, j, x) -> j >= i + k, trim) -end - -droptol!(A::SparseMatrixCSC, tol, trim::Bool = true) = - fkeep!(A, (i, j, x) -> abs(x) > tol, trim) - -""" - dropzeros!(A::SparseMatrixCSC, trim::Bool = true) - -Removes stored numerical zeros from `A`, optionally trimming resulting excess space from -`A.rowval` and `A.nzval` when `trim` is `true`. - -For an out-of-place version, see [`dropzeros`](@ref). For -algorithmic information, see `fkeep!`. -""" -dropzeros!(A::SparseMatrixCSC, trim::Bool = true) = fkeep!(A, (i, j, x) -> x != 0, trim) -""" - dropzeros(A::SparseMatrixCSC, trim::Bool = true) - -Generates a copy of `A` and removes stored numerical zeros from that copy, optionally -trimming excess space from the result's `rowval` and `nzval` arrays when `trim` is `true`. - -For an in-place version and algorithmic information, see [`dropzeros!`](@ref). - -# Example -```jldoctest -julia> A = sparse([1, 2, 3], [1, 2, 3], [1.0, 0.0, 1.0]) -3×3 SparseMatrixCSC{Float64,Int64} with 3 stored entries: - [1, 1] = 1.0 - [2, 2] = 0.0 - [3, 3] = 1.0 - -julia> dropzeros(A) -3×3 SparseMatrixCSC{Float64,Int64} with 2 stored entries: - [1, 1] = 1.0 - [3, 3] = 1.0 -``` -""" -dropzeros(A::SparseMatrixCSC, trim::Bool = true) = dropzeros!(copy(A), trim) - - -## Find methods - -function find(S::SparseMatrixCSC) - sz = size(S) - I, J = findn(S) - return sub2ind(sz, I, J) -end - -function findn(S::SparseMatrixCSC{Tv,Ti}) where {Tv,Ti} - numnz = nnz(S) - I = Vector{Ti}(numnz) - J = Vector{Ti}(numnz) - - count = 1 - @inbounds for col = 1 : S.n, k = S.colptr[col] : (S.colptr[col+1]-1) - if S.nzval[k] != 0 - I[count] = S.rowval[k] - J[count] = col - count += 1 - end - end - - count -= 1 - if numnz != count - deleteat!(I, (count+1):numnz) - deleteat!(J, (count+1):numnz) - end - - return (I, J) -end - -function findnz(S::SparseMatrixCSC{Tv,Ti}) where {Tv,Ti} - numnz = nnz(S) - I = Vector{Ti}(numnz) - J = Vector{Ti}(numnz) - V = Vector{Tv}(numnz) - - count = 1 - @inbounds for col = 1 : S.n, k = S.colptr[col] : (S.colptr[col+1]-1) - if S.nzval[k] != 0 - I[count] = S.rowval[k] - J[count] = col - V[count] = S.nzval[k] - count += 1 - end - end - - count -= 1 - if numnz != count - deleteat!(I, (count+1):numnz) - deleteat!(J, (count+1):numnz) - deleteat!(V, (count+1):numnz) - end - - return (I, J, V) -end - - -import Base.Random.GLOBAL_RNG -function sprand_IJ(r::AbstractRNG, m::Integer, n::Integer, density::AbstractFloat) - ((m < 0) || (n < 0)) && throw(ArgumentError("invalid Array dimensions")) - 0 <= density <= 1 || throw(ArgumentError("$density not in [0,1]")) - N = n*m - - I, J = Vector{Int}(0), Vector{Int}(0) # indices of nonzero elements - sizehint!(I, round(Int,N*density)) - sizehint!(J, round(Int,N*density)) - - # density of nonzero columns: - L = log1p(-density) - coldensity = -expm1(m*L) # = 1 - (1-density)^m - colsparsity = exp(m*L) # = 1 - coldensity - iL = 1/L - - rows = Vector{Int}(0) - for j in randsubseq(r, 1:n, coldensity) - # To get the right statistics, we *must* have a nonempty column j - # even if p*m << 1. To do this, we use an approach similar to - # the one in randsubseq to compute the expected first nonzero row k, - # except given that at least one is nonzero (via Bayes' rule); - # carefully rearranged to avoid excessive roundoff errors. - k = ceil(log(colsparsity + rand(r)*coldensity) * iL) - ik = k < 1 ? 1 : k > m ? m : Int(k) # roundoff-error/underflow paranoia - randsubseq!(r, rows, 1:m-ik, density) - push!(rows, m-ik+1) - append!(I, rows) - nrows = length(rows) - Jlen = length(J) - resize!(J, Jlen+nrows) - @inbounds for i = Jlen+1:length(J) - J[i] = j - end - end - I, J -end - -""" - sprand([rng],[type],m,[n],p::AbstractFloat,[rfn]) - -Create a random length `m` sparse vector or `m` by `n` sparse matrix, in -which the probability of any element being nonzero is independently given by -`p` (and hence the mean density of nonzeros is also exactly `p`). Nonzero -values are sampled from the distribution specified by `rfn` and have the type `type`. The uniform -distribution is used in case `rfn` is not specified. The optional `rng` -argument specifies a random number generator, see [Random Numbers](@ref). - -# Example -```jldoctest -julia> rng = MersenneTwister(1234); - -julia> sprand(rng, Bool, 2, 2, 0.5) -2×2 SparseMatrixCSC{Bool,Int64} with 2 stored entries: - [1, 1] = true - [2, 1] = true - -julia> sprand(rng, Float64, 3, 0.75) -3-element SparseVector{Float64,Int64} with 1 stored entry: - [3] = 0.298614 -``` -""" -function sprand{T}(r::AbstractRNG, m::Integer, n::Integer, density::AbstractFloat, - rfn::Function, ::Type{T}=eltype(rfn(r,1))) - N = m*n - N == 0 && return spzeros(T,m,n) - N == 1 && return rand(r) <= density ? sparse([1], [1], rfn(r,1)) : spzeros(T,1,1) - - I,J = sprand_IJ(r, m, n, density) - sparse_IJ_sorted!(I, J, rfn(r,length(I)), m, n, +) # it will never need to combine -end - -function sprand{T}(m::Integer, n::Integer, density::AbstractFloat, - rfn::Function, ::Type{T}=eltype(rfn(1))) - N = m*n - N == 0 && return spzeros(T,m,n) - N == 1 && return rand() <= density ? sparse([1], [1], rfn(1)) : spzeros(T,1,1) - - I,J = sprand_IJ(GLOBAL_RNG, m, n, density) - sparse_IJ_sorted!(I, J, rfn(length(I)), m, n, +) # it will never need to combine -end - -truebools(r::AbstractRNG, n::Integer) = ones(Bool, n) - -sprand(m::Integer, n::Integer, density::AbstractFloat) = sprand(GLOBAL_RNG,m,n,density) - -sprand(r::AbstractRNG, m::Integer, n::Integer, density::AbstractFloat) = sprand(r,m,n,density,rand,Float64) -sprand(r::AbstractRNG, ::Type{T}, m::Integer, n::Integer, density::AbstractFloat) where {T} = sprand(r,m,n,density,(r, i) -> rand(r, T, i), T) -sprand(r::AbstractRNG, ::Type{Bool}, m::Integer, n::Integer, density::AbstractFloat) = sprand(r,m,n,density, truebools, Bool) -sprand(::Type{T}, m::Integer, n::Integer, density::AbstractFloat) where {T} = sprand(GLOBAL_RNG, T, m, n, density) - - -""" - sprandn([rng], m[,n],p::AbstractFloat) - -Create a random sparse vector of length `m` or sparse matrix of size `m` by `n` -with the specified (independent) probability `p` of any entry being nonzero, -where nonzero values are sampled from the normal distribution. The optional `rng` -argument specifies a random number generator, see [Random Numbers](@ref). - -# Example -```jldoctest -julia> rng = MersenneTwister(1234); - -julia> sprandn(rng, 2, 2, 0.75) -2×2 SparseMatrixCSC{Float64,Int64} with 3 stored entries: - [1, 1] = 0.532813 - [2, 1] = -0.271735 - [2, 2] = 0.502334 -``` -""" -sprandn(r::AbstractRNG, m::Integer, n::Integer, density::AbstractFloat) = sprand(r,m,n,density,randn,Float64) -sprandn(m::Integer, n::Integer, density::AbstractFloat) = sprandn(GLOBAL_RNG,m,n,density) - - -""" - spones(S) - -Create a sparse array with the same structure as that of `S`, but with every nonzero -element having the value `1.0`. - -# Example -```jldoctest -julia> A = sparse([1,2,3,4],[2,4,3,1],[5.,4.,3.,2.]) -4×4 SparseMatrixCSC{Float64,Int64} with 4 stored entries: - [4, 1] = 2.0 - [1, 2] = 5.0 - [3, 3] = 3.0 - [2, 4] = 4.0 - -julia> spones(A) -4×4 SparseMatrixCSC{Float64,Int64} with 4 stored entries: - [4, 1] = 1.0 - [1, 2] = 1.0 - [3, 3] = 1.0 - [2, 4] = 1.0 -``` - -Note the difference from [`speye`](@ref). -""" -spones(S::SparseMatrixCSC{T}) where {T} = - SparseMatrixCSC(S.m, S.n, copy(S.colptr), copy(S.rowval), ones(T, S.colptr[end]-1)) - -""" - spzeros([type,]m[,n]) - -Create a sparse vector of length `m` or sparse matrix of size `m x n`. This -sparse array will not contain any nonzero values. No storage will be allocated -for nonzero values during construction. The type defaults to [`Float64`](@ref) if not -specified. - -# Examples -```jldoctest -julia> spzeros(3, 3) -3×3 SparseMatrixCSC{Float64,Int64} with 0 stored entries - -julia> spzeros(Float32, 4) -4-element SparseVector{Float32,Int64} with 0 stored entries -``` -""" -spzeros(m::Integer, n::Integer) = spzeros(Float64, m, n) -spzeros(::Type{Tv}, m::Integer, n::Integer) where {Tv} = spzeros(Tv, Int, m, n) -function spzeros(::Type{Tv}, ::Type{Ti}, m::Integer, n::Integer) where {Tv, Ti} - ((m < 0) || (n < 0)) && throw(ArgumentError("invalid Array dimensions")) - SparseMatrixCSC(m, n, ones(Ti, n+1), Vector{Ti}(0), Vector{Tv}(0)) -end -# de-splatting variant -function spzeros(::Type{Tv}, ::Type{Ti}, sz::Tuple{Integer,Integer}) where {Tv, Ti} - spzeros(Tv, Ti, sz[1], sz[2]) -end - -speye(n::Integer) = speye(Float64, n) -speye(::Type{T}, n::Integer) where {T} = speye(T, n, n) -speye(m::Integer, n::Integer) = speye(Float64, m, n) - -""" - speye(S) - -Create a sparse identity matrix with the same size as `S`. - -# Example -```jldoctest -julia> A = sparse([1,2,3,4],[2,4,3,1],[5.,4.,3.,2.]) -4×4 SparseMatrixCSC{Float64,Int64} with 4 stored entries: - [4, 1] = 2.0 - [1, 2] = 5.0 - [3, 3] = 3.0 - [2, 4] = 4.0 - -julia> speye(A) -4×4 SparseMatrixCSC{Float64,Int64} with 4 stored entries: - [1, 1] = 1.0 - [2, 2] = 1.0 - [3, 3] = 1.0 - [4, 4] = 1.0 -``` - -Note the difference from [`spones`](@ref). -""" -speye(S::SparseMatrixCSC{T}) where {T} = speye(T, size(S, 1), size(S, 2)) -eye(S::SparseMatrixCSC) = speye(S) - -""" - speye([type,]m[,n]) - -Create a sparse identity matrix of size `m x m`. When `n` is supplied, -create a sparse identity matrix of size `m x n`. The type defaults to [`Float64`](@ref) -if not specified. - -`sparse(I, m, n)` is equivalent to `speye(Int, m, n)`, and -`sparse(α*I, m, n)` can be used to efficiently create a sparse -multiple `α` of the identity matrix. -""" -speye(::Type{T}, m::Integer, n::Integer) where {T} = speye_scaled(T, oneunit(T), m, n) - -function one(S::SparseMatrixCSC{T}) where T - m,n = size(S) - if m != n; throw(DimensionMismatch("multiplicative identity only defined for square matrices")); end - speye(T, m) -end - -speye_scaled(diag, m::Integer, n::Integer) = speye_scaled(typeof(diag), diag, m, n) - -function speye_scaled(::Type{T}, diag, m::Integer, n::Integer) where T - ((m < 0) || (n < 0)) && throw(ArgumentError("invalid array dimensions")) - nnz = min(m,n) - colptr = Vector{Int}(1+n) - colptr[1:nnz+1] = 1:nnz+1 - colptr[nnz+2:end] = nnz+1 - SparseMatrixCSC(Int(m), Int(n), colptr, Vector{Int}(1:nnz), fill!(Vector{T}(nnz), diag)) -end - -sparse(S::UniformScaling, m::Integer, n::Integer=m) = speye_scaled(S.λ, m, n) - - -# TODO: More appropriate location? -conj!(A::SparseMatrixCSC) = (@inbounds broadcast!(conj, A.nzval, A.nzval); A) -(-)(A::SparseMatrixCSC) = SparseMatrixCSC(A.m, A.n, copy(A.colptr), copy(A.rowval), map(-, A.nzval)) - -# the rest of real, conj, imag are handled correctly via AbstractArray methods -conj(A::SparseMatrixCSC{<:Complex}) = - SparseMatrixCSC(A.m, A.n, copy(A.colptr), copy(A.rowval), conj(A.nzval)) -imag(A::SparseMatrixCSC{Tv,Ti}) where {Tv<:Real,Ti} = spzeros(Tv, Ti, A.m, A.n) - -## Binary arithmetic and boolean operators -(+)(A::SparseMatrixCSC, B::SparseMatrixCSC) = map(+, A, B) -(-)(A::SparseMatrixCSC, B::SparseMatrixCSC) = map(-, A, B) - -(+)(A::SparseMatrixCSC, B::Array) = Array(A) + B -(+)(A::Array, B::SparseMatrixCSC) = A + Array(B) -(-)(A::SparseMatrixCSC, B::Array) = Array(A) - B -(-)(A::Array, B::SparseMatrixCSC) = A - Array(B) - -## full equality -function ==(A1::SparseMatrixCSC, A2::SparseMatrixCSC) - size(A1)!=size(A2) && return false - vals1, vals2 = nonzeros(A1), nonzeros(A2) - rows1, rows2 = rowvals(A1), rowvals(A2) - m, n = size(A1) - @inbounds for i = 1:n - nz1,nz2 = nzrange(A1,i), nzrange(A2,i) - j1,j2 = first(nz1), first(nz2) - # step through the rows of both matrices at once: - while j1<=last(nz1) && j2<=last(nz2) - r1,r2 = rows1[j1], rows2[j2] - if r1==r2 - vals1[j1]!=vals2[j2] && return false - j1+=1 - j2+=1 - else - if r1<r2 - vals1[j1]!=0 && return false - j1+=1 - else - vals2[j2]!=0 && return false - j2+=1 - end - end - end - # finish off any left-overs: - for j = j1:last(nz1) - vals1[j]!=0 && return false - end - for j = j2:last(nz2) - vals2[j]!=0 && return false - end - end - return true -end - -## Reductions - -# In general, output of sparse matrix reductions will not be sparse, -# and computing reductions along columns into SparseMatrixCSC is -# non-trivial, so use Arrays for output -Base.reducedim_initarray{R}(A::SparseMatrixCSC, region, v0, ::Type{R}) = - fill!(similar(dims->Array{R}(dims), Base.reduced_indices(A,region)), v0) -Base.reducedim_initarray0{R}(A::SparseMatrixCSC, region, v0, ::Type{R}) = - fill!(similar(dims->Array{R}(dims), Base.reduced_indices0(A,region)), v0) - -# General mapreduce -function _mapreducezeros(f, op, ::Type{T}, nzeros::Int, v0) where T - nzeros == 0 && return v0 - - # Reduce over first zero - zeroval = f(zero(T)) - v = op(v0, zeroval) - isequal(v, v0) && return v - - # Reduce over remaining zeros - for i = 2:nzeros - lastv = v - v = op(v, zeroval) - # Bail out early if we reach a fixed point - isequal(v, lastv) && break - end - - v -end - -function Base._mapreduce{T}(f, op, ::Base.IndexCartesian, A::SparseMatrixCSC{T}) - z = nnz(A) - n = length(A) - if z == 0 - if n == 0 - Base.mr_empty(f, op, T) - else - _mapreducezeros(f, op, T, n-z-1, f(zero(T))) - end - else - _mapreducezeros(f, op, T, n-z, Base._mapreduce(f, op, A.nzval)) - end -end - -# Specialized mapreduce for +/* -_mapreducezeros(f, ::typeof(+), ::Type{T}, nzeros::Int, v0) where {T} = - nzeros == 0 ? v0 : f(zero(T))*nzeros + v0 -_mapreducezeros(f, ::typeof(*), ::Type{T}, nzeros::Int, v0) where {T} = - nzeros == 0 ? v0 : f(zero(T))^nzeros * v0 - -function Base._mapreduce{T}(f, op::typeof(*), A::SparseMatrixCSC{T}) - nzeros = length(A)-nnz(A) - if nzeros == 0 - # No zeros, so don't compute f(0) since it might throw - Base._mapreduce(f, op, A.nzval) - else - v = f(zero(T))^(nzeros) - # Bail out early if initial reduction value is zero - v == zero(T) ? v : v*Base._mapreduce(f, op, A.nzval) - end -end - -# General mapreducedim -function _mapreducerows!{T}(f, op, R::AbstractArray, A::SparseMatrixCSC{T}) - colptr = A.colptr - rowval = A.rowval - nzval = A.nzval - m, n = size(A) - @inbounds for col = 1:n - r = R[1, col] - @simd for j = colptr[col]:colptr[col+1]-1 - r = op(r, f(nzval[j])) - end - R[1, col] = _mapreducezeros(f, op, T, m-(colptr[col+1]-colptr[col]), r) - end - R -end - -function _mapreducecols!{Tv,Ti}(f, op, R::AbstractArray, A::SparseMatrixCSC{Tv,Ti}) - colptr = A.colptr - rowval = A.rowval - nzval = A.nzval - m, n = size(A) - rownz = fill(convert(Ti, n), m) - @inbounds for col = 1:n - @simd for j = colptr[col]:colptr[col+1]-1 - row = rowval[j] - R[row, 1] = op(R[row, 1], f(nzval[j])) - rownz[row] -= 1 - end - end - @inbounds for i = 1:m - R[i, 1] = _mapreducezeros(f, op, Tv, rownz[i], R[i, 1]) - end - R -end - -function Base._mapreducedim!{T}(f, op, R::AbstractArray, A::SparseMatrixCSC{T}) - lsiz = Base.check_reducedims(R,A) - isempty(A) && return R - - if size(R, 1) == size(R, 2) == 1 - # Reduction along both columns and rows - R[1, 1] = mapreduce(f, op, A) - elseif size(R, 1) == 1 - # Reduction along rows - _mapreducerows!(f, op, R, A) - elseif size(R, 2) == 1 - # Reduction along columns - _mapreducecols!(f, op, R, A) - else - # Reduction along a dimension > 2 - # Compute op(R, f(A)) - m, n = size(A) - nzval = A.nzval - if length(nzval) == m*n - # No zeros, so don't compute f(0) since it might throw - for col = 1:n - @simd for row = 1:size(A, 1) - @inbounds R[row, col] = op(R[row, col], f(nzval[(col-1)*m+row])) - end - end - else - colptr = A.colptr - rowval = A.rowval - zeroval = f(zero(T)) - @inbounds for col = 1:n - lastrow = 0 - for j = colptr[col]:colptr[col+1]-1 - row = rowval[j] - @simd for i = lastrow+1:row-1 # Zeros before this nonzero - R[i, col] = op(R[i, col], zeroval) - end - R[row, col] = op(R[row, col], f(nzval[j])) - lastrow = row - end - @simd for i = lastrow+1:m # Zeros at end - R[i, col] = op(R[i, col], zeroval) - end - end - end - end - R -end - -# Specialized mapreducedim for + cols to avoid allocating a -# temporary array when f(0) == 0 -function _mapreducecols!{Tv,Ti}(f, op::typeof(+), R::AbstractArray, A::SparseMatrixCSC{Tv,Ti}) - nzval = A.nzval - m, n = size(A) - if length(nzval) == m*n - # No zeros, so don't compute f(0) since it might throw - for col = 1:n - @simd for row = 1:size(A, 1) - @inbounds R[row, 1] = op(R[row, 1], f(nzval[(col-1)*m+row])) - end - end - else - colptr = A.colptr - rowval = A.rowval - zeroval = f(zero(Tv)) - if isequal(zeroval, zero(Tv)) - # Case where f(0) == 0 - @inbounds for col = 1:size(A, 2) - @simd for j = colptr[col]:colptr[col+1]-1 - R[rowval[j], 1] += f(nzval[j]) - end - end - else - # Case where f(0) != 0 - rownz = fill(convert(Ti, n), m) - @inbounds for col = 1:size(A, 2) - @simd for j = colptr[col]:colptr[col+1]-1 - row = rowval[j] - R[row, 1] += f(nzval[j]) - rownz[row] -= 1 - end - end - for i = 1:m - R[i, 1] += rownz[i]*zeroval - end - end - end - R -end - -# findmax/min and indmax/min methods -function _findz{Tv,Ti}(A::SparseMatrixCSC{Tv,Ti}, rows=1:A.m, cols=1:A.n) - colptr = A.colptr; rowval = A.rowval; nzval = A.nzval - zval = zero(Tv) - col = cols[1]; row = 0 - rowmin = rows[1]; rowmax = rows[end] - allrows = (rows == 1:A.m) - @inbounds while col <= cols[end] - r1::Int = colptr[col] - r2::Int = colptr[col+1] - 1 - if !allrows && (r1 <= r2) - r1 = searchsortedfirst(rowval, rowmin, r1, r2, Forward) - (r1 <= r2 ) && (r2 = searchsortedlast(rowval, rowmax, r1, r2, Forward) + 1) - end - row = rowmin - (r1 > r2) && (return sub2ind(size(A),row,col)) - while (r1 <= r2) && (row == rowval[r1]) && (nzval[r1] != zval) - r1 += 1 - row += 1 - end - (row <= rowmax) && (return sub2ind(size(A),row,col)) - col += 1 - end - return 0 -end - -macro _findr(op, A, region, Tv, Ti) - esc(quote - N = nnz($A) - L = length($A) - (L == 0) && error("array must be non-empty") - - colptr = $A.colptr; rowval = $A.rowval; nzval = $A.nzval; m = $A.m; n = $A.n - zval = zero($Tv) - szA = size($A) - - if $region == 1 || $region == (1,) - (N == 0) && (return (fill(zval,1,n), fill(convert($Ti,1),1,n))) - S = Vector{$Tv}(n); I = Vector{$Ti}(n) - @inbounds for i = 1 : n - Sc = zval; Ic = _findz($A, 1:m, i:i) - if Ic == 0 - j = colptr[i] - Ic = sub2ind(szA, rowval[j], i) - Sc = nzval[j] - end - for j = colptr[i] : colptr[i+1]-1 - if ($op)(nzval[j], Sc) - Sc = nzval[j] - Ic = sub2ind(szA, rowval[j], i) - end - end - S[i] = Sc; I[i] = Ic - end - return(reshape(S,1,n), reshape(I,1,n)) - elseif $region == 2 || $region == (2,) - (N == 0) && (return (fill(zval,m,1), fill(convert($Ti,1),m,1))) - S = Vector{$Tv}(m); I = Vector{$Ti}(m) - @inbounds for row in 1:m - S[row] = zval; I[row] = _findz($A, row:row, 1:n) - if I[row] == 0 - I[row] = sub2ind(szA, row, 1) - S[row] = A[row,1] - end - end - @inbounds for i = 1 : n, j = colptr[i] : colptr[i+1]-1 - row = rowval[j] - if ($op)(nzval[j], S[row]) - S[row] = nzval[j] - I[row] = sub2ind(szA, row, i) - end - end - return (reshape(S,m,1), reshape(I,m,1)) - elseif $region == (1,2) - (N == 0) && (return (fill(zval,1,1), fill(convert($Ti,1),1,1))) - hasz = nnz($A) != length($A) - Sv = hasz ? zval : nzval[1] - Iv::($Ti) = hasz ? _findz($A) : 1 - @inbounds for i = 1 : $A.n, j = colptr[i] : (colptr[i+1]-1) - if ($op)(nzval[j], Sv) - Sv = nzval[j] - Iv = sub2ind(szA, rowval[j], i) - end - end - return (fill(Sv,1,1), fill(Iv,1,1)) - else - throw(ArgumentError("invalid value for region; must be 1, 2, or (1,2)")) - end - end) #quote -end - -findmin(A::SparseMatrixCSC{Tv,Ti}, region) where {Tv,Ti} = @_findr(<, A, region, Tv, Ti) -findmax(A::SparseMatrixCSC{Tv,Ti}, region) where {Tv,Ti} = @_findr(>, A, region, Tv, Ti) -findmin(A::SparseMatrixCSC) = (r=findmin(A,(1,2)); (r[1][1], r[2][1])) -findmax(A::SparseMatrixCSC) = (r=findmax(A,(1,2)); (r[1][1], r[2][1])) - -indmin(A::SparseMatrixCSC) = findmin(A)[2] -indmax(A::SparseMatrixCSC) = findmax(A)[2] - -#all(A::SparseMatrixCSC{Bool}, region) = reducedim(all,A,region,true) -#any(A::SparseMatrixCSC{Bool}, region) = reducedim(any,A,region,false) -#sum(A::SparseMatrixCSC{Bool}, region) = reducedim(+,A,region,0,Int) -#sum(A::SparseMatrixCSC{Bool}) = countnz(A) - -## getindex -function rangesearch(haystack::Range, needle) - (i,rem) = divrem(needle - first(haystack), step(haystack)) - (rem==0 && 1<=i+1<=length(haystack)) ? i+1 : 0 -end - -getindex(A::SparseMatrixCSC, I::Tuple{Integer,Integer}) = getindex(A, I[1], I[2]) - -function getindex(A::SparseMatrixCSC{T}, i0::Integer, i1::Integer) where T - if !(1 <= i0 <= A.m && 1 <= i1 <= A.n); throw(BoundsError()); end - r1 = Int(A.colptr[i1]) - r2 = Int(A.colptr[i1+1]-1) - (r1 > r2) && return zero(T) - r1 = searchsortedfirst(A.rowval, i0, r1, r2, Forward) - ((r1 > r2) || (A.rowval[r1] != i0)) ? zero(T) : A.nzval[r1] -end - -# Colon translation -getindex(A::SparseMatrixCSC, ::Colon, ::Colon) = copy(A) -getindex(A::SparseMatrixCSC, i, ::Colon) = getindex(A, i, 1:size(A, 2)) -getindex(A::SparseMatrixCSC, ::Colon, i) = getindex(A, 1:size(A, 1), i) - -function getindex_cols(A::SparseMatrixCSC{Tv,Ti}, J::AbstractVector) where {Tv,Ti} - # for indexing whole columns - (m, n) = size(A) - nJ = length(J) - - colptrA = A.colptr; rowvalA = A.rowval; nzvalA = A.nzval - - colptrS = Vector{Ti}(nJ+1) - colptrS[1] = 1 - nnzS = 0 - - @inbounds for j = 1:nJ - col = J[j] - 1 <= col <= n || throw(BoundsError()) - nnzS += colptrA[col+1] - colptrA[col] - colptrS[j+1] = nnzS + 1 - end - - rowvalS = Vector{Ti}(nnzS) - nzvalS = Vector{Tv}(nnzS) - ptrS = 0 - - @inbounds for j = 1:nJ - col = J[j] - for k = colptrA[col]:colptrA[col+1]-1 - ptrS += 1 - rowvalS[ptrS] = rowvalA[k] - nzvalS[ptrS] = nzvalA[k] - end - end - return SparseMatrixCSC(m, nJ, colptrS, rowvalS, nzvalS) -end - -function getindex(A::SparseMatrixCSC{Tv,Ti}, I::Range, J::AbstractVector) where {Tv,Ti<:Integer} - # Ranges for indexing rows - (m, n) = size(A) - # whole columns: - if I == 1:m - return getindex_cols(A, J) - end - - nI = length(I) - nI == 0 || (minimum(I) >= 1 && maximum(I) <= m) || throw(BoundsError()) - nJ = length(J) - colptrA = A.colptr; rowvalA = A.rowval; nzvalA = A.nzval - colptrS = Vector{Ti}(nJ+1) - colptrS[1] = 1 - nnzS = 0 - - # Form the structure of the result and compute space - @inbounds for j = 1:nJ - col = J[j] - 1 <= col <= n || throw(BoundsError()) - @simd for k in colptrA[col]:colptrA[col+1]-1 - nnzS += rowvalA[k] in I # `in` is fast for ranges - end - colptrS[j+1] = nnzS+1 - end - - # Populate the values in the result - rowvalS = Vector{Ti}(nnzS) - nzvalS = Vector{Tv}(nnzS) - ptrS = 1 - - @inbounds for j = 1:nJ - col = J[j] - for k = colptrA[col]:colptrA[col+1]-1 - rowA = rowvalA[k] - i = rangesearch(I, rowA) - if i > 0 - rowvalS[ptrS] = i - nzvalS[ptrS] = nzvalA[k] - ptrS += 1 - end - end - end - - return SparseMatrixCSC(nI, nJ, colptrS, rowvalS, nzvalS) -end - -function getindex_I_sorted{Tv,Ti}(A::SparseMatrixCSC{Tv,Ti}, I::AbstractVector, J::AbstractVector) - # Sorted vectors for indexing rows. - # Similar to getindex_general but without the transpose trick. - (m, n) = size(A) - - nI = length(I) - nzA = nnz(A) - avgM = div(nzA,n) - # Heuristics based on experiments discussed in: - # https://github.com/JuliaLang/julia/issues/12860 - # https://github.com/JuliaLang/julia/pull/12934 - alg = ((m > nzA) && (m > nI)) ? 0 : - ((nI - avgM) > 2^8) ? 1 : - ((avgM - nI) > 2^10) ? 0 : 2 - - (alg == 0) ? getindex_I_sorted_bsearch_A(A, I, J) : - (alg == 1) ? getindex_I_sorted_bsearch_I(A, I, J) : - getindex_I_sorted_linear(A, I, J) -end - -function getindex_I_sorted_bsearch_A{Tv,Ti}(A::SparseMatrixCSC{Tv,Ti}, I::AbstractVector, J::AbstractVector) - const nI = length(I) - const nJ = length(J) - - colptrA = A.colptr; rowvalA = A.rowval; nzvalA = A.nzval - colptrS = Vector{Ti}(nJ+1) - colptrS[1] = 1 - - ptrS = 1 - # determine result size - @inbounds for j = 1:nJ - col = J[j] - ptrI::Int = 1 # runs through I - ptrA::Int = colptrA[col] - stopA::Int = colptrA[col+1]-1 - if ptrA <= stopA - while ptrI <= nI - rowI = I[ptrI] - ptrI += 1 - (rowvalA[ptrA] > rowI) && continue - ptrA = searchsortedfirst(rowvalA, rowI, ptrA, stopA, Base.Order.Forward) - (ptrA <= stopA) || break - if rowvalA[ptrA] == rowI - ptrS += 1 - end - end - end - colptrS[j+1] = ptrS - end - - rowvalS = Vector{Ti}(ptrS-1) - nzvalS = Vector{Tv}(ptrS-1) - - # fill the values - ptrS = 1 - @inbounds for j = 1:nJ - col = J[j] - ptrI::Int = 1 # runs through I - ptrA::Int = colptrA[col] - stopA::Int = colptrA[col+1]-1 - if ptrA <= stopA - while ptrI <= nI - rowI = I[ptrI] - if rowvalA[ptrA] <= rowI - ptrA = searchsortedfirst(rowvalA, rowI, ptrA, stopA, Base.Order.Forward) - (ptrA <= stopA) || break - if rowvalA[ptrA] == rowI - rowvalS[ptrS] = ptrI - nzvalS[ptrS] = nzvalA[ptrA] - ptrS += 1 - end - end - ptrI += 1 - end - end - end - return SparseMatrixCSC(nI, nJ, colptrS, rowvalS, nzvalS) -end - -function getindex_I_sorted_linear(A::SparseMatrixCSC{Tv,Ti}, I::AbstractVector, J::AbstractVector) where {Tv,Ti} - const nI = length(I) - const nJ = length(J) - - colptrA = A.colptr; rowvalA = A.rowval; nzvalA = A.nzval - colptrS = Vector{Ti}(nJ+1) - colptrS[1] = 1 - cacheI = zeros(Int, A.m) - - ptrS = 1 - # build the cache and determine result size - @inbounds for j = 1:nJ - col = J[j] - ptrI::Int = 1 # runs through I - ptrA::Int = colptrA[col] - stopA::Int = colptrA[col+1] - while ptrI <= nI && ptrA < stopA - rowA = rowvalA[ptrA] - rowI = I[ptrI] - - if rowI > rowA - ptrA += 1 - elseif rowI < rowA - ptrI += 1 - else - (cacheI[rowA] == 0) && (cacheI[rowA] = ptrI) - ptrS += 1 - ptrI += 1 - end - end - colptrS[j+1] = ptrS - end - - rowvalS = Vector{Ti}(ptrS-1) - nzvalS = Vector{Tv}(ptrS-1) - - # fill the values - ptrS = 1 - @inbounds for j = 1:nJ - col = J[j] - ptrA::Int = colptrA[col] - stopA::Int = colptrA[col+1] - while ptrA < stopA - rowA = rowvalA[ptrA] - ptrI = cacheI[rowA] - if ptrI > 0 - while ptrI <= nI && I[ptrI] == rowA - rowvalS[ptrS] = ptrI - nzvalS[ptrS] = nzvalA[ptrA] - ptrS += 1 - ptrI += 1 - end - end - ptrA += 1 - end - end - return SparseMatrixCSC(nI, nJ, colptrS, rowvalS, nzvalS) -end - -function getindex_I_sorted_bsearch_I(A::SparseMatrixCSC{Tv,Ti}, I::AbstractVector, J::AbstractVector) where {Tv,Ti} - const nI = length(I) - const nJ = length(J) - - colptrA = A.colptr; rowvalA = A.rowval; nzvalA = A.nzval - colptrS = Vector{Ti}(nJ+1) - colptrS[1] = 1 - - m = A.m - - # cacheI is used first to store num occurrences of each row in columns of interest - # and later to store position of first occurrence of each row in I - cacheI = zeros(Int, m) - - # count rows - @inbounds for j = 1:nJ - col = J[j] - for ptrA in colptrA[col]:(colptrA[col+1]-1) - cacheI[rowvalA[ptrA]] += 1 - end - end - - # fill cache and count nnz - ptrS::Int = 0 - ptrI::Int = 1 - @inbounds for j = 1:m - cval = cacheI[j] - (cval == 0) && continue - ptrI = searchsortedfirst(I, j, ptrI, nI, Base.Order.Forward) - cacheI[j] = ptrI - while ptrI <= nI && I[ptrI] == j - ptrS += cval - ptrI += 1 - end - if ptrI > nI - @simd for i=(j+1):m; @inbounds cacheI[i]=ptrI; end - break - end - end - rowvalS = Vector{Ti}(ptrS) - nzvalS = Vector{Tv}(ptrS) - colptrS[nJ+1] = ptrS+1 - - # fill the values - ptrS = 1 - @inbounds for j = 1:nJ - col = J[j] - ptrA::Int = colptrA[col] - stopA::Int = colptrA[col+1] - while ptrA < stopA - rowA = rowvalA[ptrA] - ptrI = cacheI[rowA] - (ptrI > nI) && break - if ptrI > 0 - while I[ptrI] == rowA - rowvalS[ptrS] = ptrI - nzvalS[ptrS] = nzvalA[ptrA] - ptrS += 1 - ptrI += 1 - (ptrI > nI) && break - end - end - ptrA += 1 - end - colptrS[j+1] = ptrS - end - return SparseMatrixCSC(nI, nJ, colptrS, rowvalS, nzvalS) -end - -function permute_rows!(S::SparseMatrixCSC{Tv,Ti}, pI::Vector{Int}) where {Tv,Ti} - (m, n) = size(S) - colptrS = S.colptr; rowvalS = S.rowval; nzvalS = S.nzval - # preallocate temporary sort space - nr = min(nnz(S), m) - rowperm = Vector{Int}(nr) - rowvalTemp = Vector{Ti}(nr) - nzvalTemp = Vector{Tv}(nr) - - @inbounds for j in 1:n - rowrange = colptrS[j]:(colptrS[j+1]-1) - nr = length(rowrange) - (nr > 0) || continue - k = 1 - for i in rowrange - rowA = rowvalS[i] - rowvalTemp[k] = pI[rowA] - nzvalTemp[k] = nzvalS[i] - k += 1 - end - sortperm!(unsafe_wrap(Vector{Int}, pointer(rowperm), nr), unsafe_wrap(Vector{Ti}, pointer(rowvalTemp), nr)) - k = 1 - for i in rowrange - kperm = rowperm[k] - rowvalS[i] = rowvalTemp[kperm] - nzvalS[i] = nzvalTemp[kperm] - k += 1 - end - end - S -end - -function getindex_general(A::SparseMatrixCSC, I::AbstractVector, J::AbstractVector) - pI = sortperm(I) - @inbounds Is = I[pI] - permute_rows!(getindex_I_sorted(A, Is, J), pI) -end - -# the general case: -function getindex(A::SparseMatrixCSC{Tv,Ti}, I::AbstractVector, J::AbstractVector) where {Tv,Ti} - (m, n) = size(A) - - if !isempty(J) - minj, maxj = extrema(J) - ((minj < 1) || (maxj > n)) && throw(BoundsError()) - end - - if !isempty(I) - mini, maxi = extrema(I) - ((mini < 1) || (maxi > m)) && throw(BoundsError()) - end - - if isempty(I) || isempty(J) || (0 == nnz(A)) - return spzeros(Tv, Ti, length(I), length(J)) - end - - if issorted(I) - return getindex_I_sorted(A, I, J) - else - return getindex_general(A, I, J) - end -end - -function getindex(A::SparseMatrixCSC{Tv}, I::AbstractArray) where Tv - szA = size(A) - nA = szA[1]*szA[2] - colptrA = A.colptr - rowvalA = A.rowval - nzvalA = A.nzval - - n = length(I) - outm = size(I,1) - outn = size(I,2) - szB = (outm, outn) - colptrB = zeros(Int, outn+1) - rowvalB = Vector{Int}(n) - nzvalB = Vector{Tv}(n) - - colB = 1 - rowB = 1 - colptrB[colB] = 1 - idxB = 1 - - for i in 1:n - ((I[i] < 1) | (I[i] > nA)) && throw(BoundsError()) - row,col = ind2sub(szA, I[i]) - for r in colptrA[col]:(colptrA[col+1]-1) - @inbounds if rowvalA[r] == row - rowB,colB = ind2sub(szB, i) - colptrB[colB+1] += 1 - rowvalB[idxB] = rowB - nzvalB[idxB] = nzvalA[r] - idxB += 1 - break - end - end - end - colptrB = cumsum(colptrB) - if n > (idxB-1) - deleteat!(nzvalB, idxB:n) - deleteat!(rowvalB, idxB:n) - end - SparseMatrixCSC(outm, outn, colptrB, rowvalB, nzvalB) -end - -# logical getindex -getindex(A::SparseMatrixCSC{<:Any,<:Integer}, I::Range{Bool}, J::AbstractVector{Bool}) = error("Cannot index with Range{Bool}") -getindex(A::SparseMatrixCSC{<:Any,<:Integer}, I::Range{Bool}, J::AbstractVector{<:Integer}) = error("Cannot index with Range{Bool}") - -getindex(A::SparseMatrixCSC, I::Range{<:Integer}, J::AbstractVector{Bool}) = A[I,find(J)] -getindex(A::SparseMatrixCSC, I::Integer, J::AbstractVector{Bool}) = A[I,find(J)] -getindex(A::SparseMatrixCSC, I::AbstractVector{Bool}, J::Integer) = A[find(I),J] -getindex(A::SparseMatrixCSC, I::AbstractVector{Bool}, J::AbstractVector{Bool}) = A[find(I),find(J)] -getindex(A::SparseMatrixCSC, I::AbstractVector{<:Integer}, J::AbstractVector{Bool}) = A[I,find(J)] -getindex(A::SparseMatrixCSC, I::AbstractVector{Bool}, J::AbstractVector{<:Integer}) = A[find(I),J] - -## setindex! -function setindex!(A::SparseMatrixCSC{Tv,Ti}, v, i::Integer, j::Integer) where Tv where Ti - setindex!(A, convert(Tv, v), convert(Ti, i), convert(Ti, j)) -end -function setindex!(A::SparseMatrixCSC{Tv,Ti}, v::Tv, i::Ti, j::Ti) where Tv where Ti<:Integer - if !((1 <= i <= A.m) & (1 <= j <= A.n)) - throw(BoundsError(A, (i,j))) - end - coljfirstk = Int(A.colptr[j]) - coljlastk = Int(A.colptr[j+1] - 1) - searchk = searchsortedfirst(A.rowval, i, coljfirstk, coljlastk, Base.Order.Forward) - if searchk <= coljlastk && A.rowval[searchk] == i - # Column j contains entry A[i,j]. Update and return - A.nzval[searchk] = v - return A - end - # Column j does not contain entry A[i,j]. If v is nonzero, insert entry A[i,j] = v - # and return. If to the contrary v is zero, then simply return. - if v != 0 - insert!(A.rowval, searchk, i) - insert!(A.nzval, searchk, v) - @simd for m in (j + 1):(A.n + 1) - @inbounds A.colptr[m] += 1 - end - end - return A -end - -setindex!(A::SparseMatrixCSC, v::AbstractMatrix, i::Integer, J::AbstractVector{<:Integer}) = setindex!(A, v, [i], J) -setindex!(A::SparseMatrixCSC, v::AbstractMatrix, I::AbstractVector{<:Integer}, j::Integer) = setindex!(A, v, I, [j]) - -setindex!(A::SparseMatrixCSC, x::Number, i::Integer, J::AbstractVector{<:Integer}) = setindex!(A, x, [i], J) -setindex!(A::SparseMatrixCSC, x::Number, I::AbstractVector{<:Integer}, j::Integer) = setindex!(A, x, I, [j]) - -# Colon translation -setindex!(A::SparseMatrixCSC, x, ::Colon) = setindex!(A, x, 1:length(A)) -setindex!(A::SparseMatrixCSC, x, ::Colon, ::Colon) = setindex!(A, x, 1:size(A, 1), 1:size(A,2)) -setindex!(A::SparseMatrixCSC, x, ::Colon, j::Union{Integer, AbstractVector}) = setindex!(A, x, 1:size(A, 1), j) -setindex!(A::SparseMatrixCSC, x, i::Union{Integer, AbstractVector}, ::Colon) = setindex!(A, x, i, 1:size(A, 2)) - -function setindex!{Tv}(A::SparseMatrixCSC{Tv}, x::Number, - I::AbstractVector{<:Integer}, J::AbstractVector{<:Integer}) - if isempty(I) || isempty(J); return A; end - # lt=≤ to check for strict sorting - if !issorted(I, lt=≤); I = sort!(unique(I)); end - if !issorted(J, lt=≤); J = sort!(unique(J)); end - if (I[1] < 1 || I[end] > A.m) || (J[1] < 1 || J[end] > A.n) - throw(BoundsError(A, (I, J))) - end - if x == 0 - _spsetz_setindex!(A, I, J) - else - _spsetnz_setindex!(A, convert(Tv, x), I, J) - end -end -""" -Helper method for immediately preceding setindex! method. For all (i,j) such that i in I and -j in J, assigns zero to A[i,j] if A[i,j] is a presently-stored entry, and otherwise does nothing. -""" -function _spsetz_setindex!(A::SparseMatrixCSC, - I::AbstractVector{<:Integer}, J::AbstractVector{<:Integer}) - lengthI = length(I) - for j in J - coljAfirstk = A.colptr[j] - coljAlastk = A.colptr[j+1] - 1 - coljAfirstk > coljAlastk && continue - kA = coljAfirstk - kI = 1 - entrykArow = A.rowval[kA] - entrykIrow = I[kI] - while true - if entrykArow < entrykIrow - kA += 1 - kA > coljAlastk && break - entrykArow = A.rowval[kA] - elseif entrykArow > entrykIrow - kI += 1 - kI > lengthI && break - entrykIrow = I[kI] - else # entrykArow == entrykIrow - A.nzval[kA] = 0 - kA += 1 - kI += 1 - (kA > coljAlastk || kI > lengthI) && break - entrykArow = A.rowval[kA] - entrykIrow = I[kI] - end - end - end -end -""" -Helper method for immediately preceding setindex! method. For all (i,j) such that i in I -and j in J, assigns x to A[i,j] if A[i,j] is a presently-stored entry, and allocates and -assigns x to A[i,j] if A[i,j] is not presently stored. -""" -function _spsetnz_setindex!(A::SparseMatrixCSC{Tv}, x::Tv, - I::AbstractVector{<:Integer}, J::AbstractVector{<:Integer}) where Tv - m, n = size(A) - lenI = length(I) - - nnzA = nnz(A) + lenI * length(J) - - rowvalA = rowval = A.rowval - nzvalA = nzval = A.nzval - - rowidx = 1 - nadd = 0 - @inbounds for col in 1:n - rrange = nzrange(A, col) - if nadd > 0 - A.colptr[col] = A.colptr[col] + nadd - end - - if col in J - if isempty(rrange) # set new vals only - nincl = lenI - if nadd == 0 - rowval = copy(rowvalA) - nzval = copy(nzvalA) - resize!(rowvalA, nnzA) - resize!(nzvalA, nnzA) - end - r = rowidx:(rowidx+nincl-1) - rowvalA[r] = I - nzvalA[r] = x - rowidx += nincl - nadd += nincl - else # set old + new vals - old_ptr = rrange[1] - old_stop = rrange[end] - new_ptr = 1 - new_stop = lenI - - while true - old_row = rowval[old_ptr] - new_row = I[new_ptr] - if old_row < new_row - rowvalA[rowidx] = old_row - nzvalA[rowidx] = nzval[old_ptr] - rowidx += 1 - old_ptr += 1 - else - if old_row == new_row - old_ptr += 1 - else - if nadd == 0 - rowval = copy(rowvalA) - nzval = copy(nzvalA) - resize!(rowvalA, nnzA) - resize!(nzvalA, nnzA) - end - nadd += 1 - end - rowvalA[rowidx] = new_row - nzvalA[rowidx] = x - rowidx += 1 - new_ptr += 1 - end - - if old_ptr > old_stop - if new_ptr <= new_stop - if nadd == 0 - rowval = copy(rowvalA) - nzval = copy(nzvalA) - resize!(rowvalA, nnzA) - resize!(nzvalA, nnzA) - end - r = rowidx:(rowidx+(new_stop-new_ptr)) - rowvalA[r] = I[new_ptr:new_stop] - nzvalA[r] = x - rowidx += length(r) - nadd += length(r) - end - break - end - - if new_ptr > new_stop - nincl = old_stop-old_ptr+1 - copy!(rowvalA, rowidx, rowval, old_ptr, nincl) - copy!(nzvalA, rowidx, nzval, old_ptr, nincl) - rowidx += nincl - break - end - end - end - elseif !isempty(rrange) # set old vals only - nincl = length(rrange) - copy!(rowvalA, rowidx, rowval, rrange[1], nincl) - copy!(nzvalA, rowidx, nzval, rrange[1], nincl) - rowidx += nincl - end - end - - if nadd > 0 - A.colptr[n+1] = rowidx - deleteat!(rowvalA, rowidx:nnzA) - deleteat!(nzvalA, rowidx:nnzA) - end - return A -end - -setindex!(A::SparseMatrixCSC{Tv,Ti}, S::Matrix, I::AbstractVector{T}, J::AbstractVector{T}) where {Tv,Ti,T<:Integer} = - setindex!(A, convert(SparseMatrixCSC{Tv,Ti}, S), I, J) - -setindex!(A::SparseMatrixCSC, v::AbstractVector, I::AbstractVector{<:Integer}, j::Integer) = setindex!(A, v, I, [j]) -setindex!(A::SparseMatrixCSC, v::AbstractVector, i::Integer, J::AbstractVector{<:Integer}) = setindex!(A, v, [i], J) -setindex!(A::SparseMatrixCSC, v::AbstractVector, I::AbstractVector{T}, J::AbstractVector{T}) where {T<:Integer} = - setindex!(A, reshape(v, length(I), length(J)), I, J) - - -# A[I,J] = B -function setindex!(A::SparseMatrixCSC{Tv,Ti}, B::SparseMatrixCSC{Tv,Ti}, I::AbstractVector{T}, J::AbstractVector{T}) where {Tv,Ti,T<:Integer} - if size(B,1) != length(I) || size(B,2) != length(J) - throw(DimensionMismatch("")) - end - - issortedI = issorted(I) - issortedJ = issorted(J) - - if !issortedI && !issortedJ - pI = sortperm(I); @inbounds I = I[pI] - pJ = sortperm(J); @inbounds J = J[pJ] - B = B[pI, pJ] - elseif !issortedI - pI = sortperm(I); @inbounds I = I[pI] - B = B[pI,:] - else !issortedJ - pJ = sortperm(J); @inbounds J = J[pJ] - B = B[:, pJ] - end - - m, n = size(A) - mB, nB = size(B) - - if (!isempty(I) && (I[1] < 1 || I[end] > m)) || (!isempty(J) && (J[1] < 1 || J[end] > n)) - throw(BoundsError(A, (I, J))) - end - - if isempty(I) || isempty(J) - return A - end - - nI = length(I) - nJ = length(J) - - colptrA = A.colptr; rowvalA = A.rowval; nzvalA = A.nzval - colptrB = B.colptr; rowvalB = B.rowval; nzvalB = B.nzval - - nnzS = nnz(A) + nnz(B) - - colptrS = copy(A.colptr) - rowvalS = copy(A.rowval) - nzvalS = copy(A.nzval) - - resize!(rowvalA, nnzS) - resize!(nzvalA, nnzS) - - colB = 1 - asgn_col = J[colB] - - I_asgn = falses(m) - I_asgn[I] = true - - ptrS = 1 - - @inbounds for col = 1:n - - # Copy column of A if it is not being assigned into - if colB > nJ || col != J[colB] - colptrA[col+1] = colptrA[col] + (colptrS[col+1]-colptrS[col]) - - for k = colptrS[col]:colptrS[col+1]-1 - rowvalA[ptrS] = rowvalS[k] - nzvalA[ptrS] = nzvalS[k] - ptrS += 1 - end - continue - end - - ptrA::Int = colptrS[col] - stopA::Int = colptrS[col+1] - ptrB::Int = colptrB[colB] - stopB::Int = colptrB[colB+1] - - while ptrA < stopA && ptrB < stopB - rowA = rowvalS[ptrA] - rowB = I[rowvalB[ptrB]] - if rowA < rowB - rowvalA[ptrS] = rowA - nzvalA[ptrS] = I_asgn[rowA] ? zero(Tv) : nzvalS[ptrA] - ptrS += 1 - ptrA += 1 - elseif rowB < rowA - if nzvalB[ptrB] != zero(Tv) - rowvalA[ptrS] = rowB - nzvalA[ptrS] = nzvalB[ptrB] - ptrS += 1 - end - ptrB += 1 - else - rowvalA[ptrS] = rowB - nzvalA[ptrS] = nzvalB[ptrB] - ptrS += 1 - ptrB += 1 - ptrA += 1 - end - end - - while ptrA < stopA - rowA = rowvalS[ptrA] - rowvalA[ptrS] = rowA - nzvalA[ptrS] = I_asgn[rowA] ? zero(Tv) : nzvalS[ptrA] - ptrS += 1 - ptrA += 1 - end - - while ptrB < stopB - rowB = I[rowvalB[ptrB]] - if nzvalB[ptrB] != zero(Tv) - rowvalA[ptrS] = rowB - nzvalA[ptrS] = nzvalB[ptrB] - ptrS += 1 - end - ptrB += 1 - end - - colptrA[col+1] = ptrS - colB += 1 - end - - deleteat!(rowvalA, colptrA[end]:length(rowvalA)) - deleteat!(nzvalA, colptrA[end]:length(nzvalA)) - - return A -end - -# Logical setindex! - -setindex!(A::SparseMatrixCSC, x::Matrix, I::Integer, J::AbstractVector{Bool}) = setindex!(A, sparse(x), I, find(J)) -setindex!(A::SparseMatrixCSC, x::Matrix, I::AbstractVector{Bool}, J::Integer) = setindex!(A, sparse(x), find(I), J) -setindex!(A::SparseMatrixCSC, x::Matrix, I::AbstractVector{Bool}, J::AbstractVector{Bool}) = setindex!(A, sparse(x), find(I), find(J)) -setindex!(A::SparseMatrixCSC, x::Matrix, I::AbstractVector{<:Integer}, J::AbstractVector{Bool}) = setindex!(A, sparse(x), I, find(J)) -setindex!(A::SparseMatrixCSC, x::Matrix, I::AbstractVector{Bool}, J::AbstractVector{<:Integer}) = setindex!(A, sparse(x), find(I),J) - -setindex!(A::Matrix, x::SparseMatrixCSC, I::Integer, J::AbstractVector{Bool}) = setindex!(A, Array(x), I, find(J)) -setindex!(A::Matrix, x::SparseMatrixCSC, I::AbstractVector{Bool}, J::Integer) = setindex!(A, Array(x), find(I), J) -setindex!(A::Matrix, x::SparseMatrixCSC, I::AbstractVector{Bool}, J::AbstractVector{Bool}) = setindex!(A, Array(x), find(I), find(J)) -setindex!(A::Matrix, x::SparseMatrixCSC, I::AbstractVector{<:Integer}, J::AbstractVector{Bool}) = setindex!(A, Array(x), I, find(J)) -setindex!(A::Matrix, x::SparseMatrixCSC, I::AbstractVector{Bool}, J::AbstractVector{<:Integer}) = setindex!(A, Array(x), find(I), J) - -setindex!(A::SparseMatrixCSC, x, I::AbstractVector{Bool}) = throw(BoundsError()) -function setindex!(A::SparseMatrixCSC, x, I::AbstractMatrix{Bool}) - checkbounds(A, I) - n = sum(I) - (n == 0) && (return A) - - colptrA = A.colptr; rowvalA = A.rowval; nzvalA = A.nzval - colptrB = colptrA; rowvalB = rowvalA; nzvalB = nzvalA - nadd = 0 - bidx = xidx = 1 - r1 = r2 = 0 - - @inbounds for col in 1:A.n - r1 = Int(colptrA[col]) - r2 = Int(colptrA[col+1]-1) - - for row in 1:A.m - if I[row, col] - v = isa(x, AbstractArray) ? x[xidx] : x - xidx += 1 - - if r1 <= r2 - copylen = searchsortedfirst(rowvalA, row, r1, r2, Forward) - r1 - if (copylen > 0) - if (nadd > 0) - copy!(rowvalB, bidx, rowvalA, r1, copylen) - copy!(nzvalB, bidx, nzvalA, r1, copylen) - end - bidx += copylen - r1 += copylen - end - end - - # 0: no change, 1: update, 2: add new - mode = ((r1 <= r2) && (rowvalA[r1] == row)) ? 1 : ((v == 0) ? 0 : 2) - - if (mode > 1) && (nadd == 0) - # copy storage to take changes - colptrA = copy(colptrB) - memreq = (x == 0) ? 0 : n - # this x == 0 check and approach doesn't jive with use of v above - # and may not make sense generally, as scalar x == 0 probably - # means this section should never be called. also may not be generic. - # TODO: clean this up, maybe separate scalar and array X cases - rowvalA = copy(rowvalB) - nzvalA = copy(nzvalB) - resize!(rowvalB, length(rowvalA)+memreq) - resize!(nzvalB, length(rowvalA)+memreq) - end - if mode == 1 - rowvalB[bidx] = row - nzvalB[bidx] = v - bidx += 1 - r1 += 1 - elseif mode == 2 - rowvalB[bidx] = row - nzvalB[bidx] = v - bidx += 1 - nadd += 1 - end - (xidx > n) && break - end # if I[row, col] - end # for row in 1:A.m - - if (nadd != 0) - l = r2-r1+1 - if l > 0 - copy!(rowvalB, bidx, rowvalA, r1, l) - copy!(nzvalB, bidx, nzvalA, r1, l) - bidx += l - end - colptrB[col+1] = bidx - - if (xidx > n) && (length(colptrB) > (col+1)) - diff = nadd - colptrB[(col+2):end] = colptrA[(col+2):end] .+ diff - r1 = colptrA[col+1] - r2 = colptrA[end]-1 - l = r2-r1+1 - if l > 0 - copy!(rowvalB, bidx, rowvalA, r1, l) - copy!(nzvalB, bidx, nzvalA, r1, l) - bidx += l - end - end - else - bidx = colptrA[col+1] - end - (xidx > n) && break - end # for col in 1:A.n - - if (nadd != 0) - n = length(nzvalB) - if n > (bidx-1) - deleteat!(nzvalB, bidx:n) - deleteat!(rowvalB, bidx:n) - end - end - A -end - - -function setindex!(A::SparseMatrixCSC, x, I::AbstractVector{<:Real}) - n = length(I) - (n == 0) && (return A) - - colptrA = A.colptr; rowvalA = A.rowval; nzvalA = A.nzval; szA = size(A) - colptrB = colptrA; rowvalB = rowvalA; nzvalB = nzvalA - nadd = 0 - bidx = aidx = 1 - - S = issorted(I) ? (1:n) : sortperm(I) - sxidx = r1 = r2 = 0 - - if (!isempty(I) && (I[S[1]] < 1 || I[S[end]] > length(A))) - throw(BoundsError(A, I)) - end - - isa(x, AbstractArray) && setindex_shape_check(x, length(I)) - - lastcol = 0 - (nrowA, ncolA) = szA - @inbounds for xidx in 1:n - sxidx = S[xidx] - (sxidx < n) && (I[sxidx] == I[sxidx+1]) && continue - - row,col = ind2sub(szA, I[sxidx]) - v = isa(x, AbstractArray) ? x[sxidx] : x - - if col > lastcol - r1 = Int(colptrA[col]) - r2 = Int(colptrA[col+1] - 1) - - # copy from last position till current column - if (nadd > 0) - colptrB[(lastcol+1):col] = colptrA[(lastcol+1):col] .+ nadd - copylen = r1 - aidx - if copylen > 0 - copy!(rowvalB, bidx, rowvalA, aidx, copylen) - copy!(nzvalB, bidx, nzvalA, aidx, copylen) - aidx += copylen - bidx += copylen - end - else - aidx = bidx = r1 - end - lastcol = col - end - - if r1 <= r2 - copylen = searchsortedfirst(rowvalA, row, r1, r2, Forward) - r1 - if (copylen > 0) - if (nadd > 0) - copy!(rowvalB, bidx, rowvalA, r1, copylen) - copy!(nzvalB, bidx, nzvalA, r1, copylen) - end - bidx += copylen - r1 += copylen - aidx += copylen - end - end - - # 0: no change, 1: update, 2: add new - mode = ((r1 <= r2) && (rowvalA[r1] == row)) ? 1 : ((v == 0) ? 0 : 2) - - if (mode > 1) && (nadd == 0) - # copy storage to take changes - colptrA = copy(colptrB) - memreq = (x == 0) ? 0 : n - # see comment/TODO for same statement in preceding logical setindex! method - rowvalA = copy(rowvalB) - nzvalA = copy(nzvalB) - resize!(rowvalB, length(rowvalA)+memreq) - resize!(nzvalB, length(rowvalA)+memreq) - end - if mode == 1 - rowvalB[bidx] = row - nzvalB[bidx] = v - bidx += 1 - aidx += 1 - r1 += 1 - elseif mode == 2 - rowvalB[bidx] = row - nzvalB[bidx] = v - bidx += 1 - nadd += 1 - end - end - - # copy the rest - @inbounds if (nadd > 0) - colptrB[(lastcol+1):end] = colptrA[(lastcol+1):end] .+ nadd - r1 = colptrA[end]-1 - copylen = r1 - aidx + 1 - if copylen > 0 - copy!(rowvalB, bidx, rowvalA, aidx, copylen) - copy!(nzvalB, bidx, nzvalA, aidx, copylen) - aidx += copylen - bidx += copylen - end - - n = length(nzvalB) - if n > (bidx-1) - deleteat!(nzvalB, bidx:n) - deleteat!(rowvalB, bidx:n) - end - end - A -end - -## dropstored! methods -""" - dropstored!(A::SparseMatrixCSC, i::Integer, j::Integer) - -Drop entry `A[i,j]` from `A` if `A[i,j]` is stored, and otherwise do nothing. - -```jldoctest -julia> A = sparse([1 2; 0 0]) -2×2 SparseMatrixCSC{Int64,Int64} with 2 stored entries: - [1, 1] = 1 - [1, 2] = 2 - -julia> Base.SparseArrays.dropstored!(A, 1, 2); A -2×2 SparseMatrixCSC{Int64,Int64} with 1 stored entry: - [1, 1] = 1 -``` -""" -function dropstored!(A::SparseMatrixCSC, i::Integer, j::Integer) - if !((1 <= i <= A.m) & (1 <= j <= A.n)) - throw(BoundsError(A, (i,j))) - end - coljfirstk = Int(A.colptr[j]) - coljlastk = Int(A.colptr[j+1] - 1) - searchk = searchsortedfirst(A.rowval, i, coljfirstk, coljlastk, Base.Order.Forward) - if searchk <= coljlastk && A.rowval[searchk] == i - # Entry A[i,j] is stored. Drop and return. - deleteat!(A.rowval, searchk) - deleteat!(A.nzval, searchk) - @simd for m in (j+1):(A.n + 1) - @inbounds A.colptr[m] -= 1 - end - end - return A -end -""" - dropstored!(A::SparseMatrixCSC, I::AbstractVector{<:Integer}, J::AbstractVector{<:Integer}) - -For each `(i,j)` where `i in I` and `j in J`, drop entry `A[i,j]` from `A` if `A[i,j]` is -stored and otherwise do nothing. Derivative forms: - - dropstored!(A::SparseMatrixCSC, i::Integer, J::AbstractVector{<:Integer}) - dropstored!(A::SparseMatrixCSC, I::AbstractVector{<:Integer}, j::Integer) - -# Example -```jldoctest -julia> A = spdiagm([1, 2, 3, 4]) -4×4 SparseMatrixCSC{Int64,Int64} with 4 stored entries: - [1, 1] = 1 - [2, 2] = 2 - [3, 3] = 3 - [4, 4] = 4 - -julia> Base.SparseArrays.dropstored!(A, [1, 2], [1, 1]) -4×4 SparseMatrixCSC{Int64,Int64} with 3 stored entries: - [2, 2] = 2 - [3, 3] = 3 - [4, 4] = 4 -``` -""" -function dropstored!(A::SparseMatrixCSC, - I::AbstractVector{<:Integer}, J::AbstractVector{<:Integer}) - m, n = size(A) - nnzA = nnz(A) - (nnzA == 0) && (return A) - - !issorted(I) && (I = sort(I)) - !issorted(J) && (J = sort(J)) - - if (!isempty(I) && (I[1] < 1 || I[end] > m)) || (!isempty(J) && (J[1] < 1 || J[end] > n)) - throw(BoundsError(A, (I, J))) - end - - if isempty(I) || isempty(J) - return A - end - - rowval = rowvalA = A.rowval - nzval = nzvalA = A.nzval - rowidx = 1 - ndel = 0 - @inbounds for col in 1:n - rrange = nzrange(A, col) - if ndel > 0 - A.colptr[col] = A.colptr[col] - ndel - end - - if isempty(rrange) || !(col in J) - nincl = length(rrange) - if(ndel > 0) && !isempty(rrange) - copy!(rowvalA, rowidx, rowval, rrange[1], nincl) - copy!(nzvalA, rowidx, nzval, rrange[1], nincl) - end - rowidx += nincl - else - for ridx in rrange - if rowval[ridx] in I - if ndel == 0 - rowval = copy(rowvalA) - nzval = copy(nzvalA) - end - ndel += 1 - else - if ndel > 0 - rowvalA[rowidx] = rowval[ridx] - nzvalA[rowidx] = nzval[ridx] - end - rowidx += 1 - end - end - end - end - - if ndel > 0 - A.colptr[n+1] = rowidx - deleteat!(rowvalA, rowidx:nnzA) - deleteat!(nzvalA, rowidx:nnzA) - end - return A -end -dropstored!(A::SparseMatrixCSC, i::Integer, J::AbstractVector{<:Integer}) = dropstored!(A, [i], J) -dropstored!(A::SparseMatrixCSC, I::AbstractVector{<:Integer}, j::Integer) = dropstored!(A, I, [j]) -dropstored!(A::SparseMatrixCSC, ::Colon, j::Union{Integer,AbstractVector}) = dropstored!(A, 1:size(A,1), j) -dropstored!(A::SparseMatrixCSC, i::Union{Integer,AbstractVector}, ::Colon) = dropstored!(A, i, 1:size(A,2)) -dropstored!(A::SparseMatrixCSC, ::Colon, ::Colon) = dropstored!(A, 1:size(A,1), 1:size(A,2)) -dropstored!(A::SparseMatrixCSC, ::Colon) = dropstored!(A, :, :) -# TODO: Several of the preceding methods are optimization candidates. -# TODO: Implement linear indexing methods for dropstored! ? -# TODO: Implement logical indexing methods for dropstored! ? - - -# Sparse concatenation - -function vcat(X::SparseMatrixCSC...) - num = length(X) - mX = Int[ size(x, 1) for x in X ] - nX = Int[ size(x, 2) for x in X ] - m = sum(mX) - n = nX[1] - - for i = 2 : num - if nX[i] != n - throw(DimensionMismatch("All inputs to vcat should have the same number of columns")) - end - end - - Tv = promote_eltype(X...) - Ti = promote_eltype(map(x->x.rowval, X)...) - - nnzX = Int[ nnz(x) for x in X ] - nnz_res = sum(nnzX) - colptr = Vector{Ti}(n+1) - rowval = Vector{Ti}(nnz_res) - nzval = Vector{Tv}(nnz_res) - - colptr[1] = 1 - for c = 1:n - mX_sofar = 0 - ptr_res = colptr[c] - for i = 1 : num - colptrXi = X[i].colptr - col_length = (colptrXi[c + 1] - 1) - colptrXi[c] - ptr_Xi = colptrXi[c] - - stuffcol!(X[i], colptr, rowval, nzval, - ptr_res, ptr_Xi, col_length, mX_sofar) - - ptr_res += col_length + 1 - mX_sofar += mX[i] - end - colptr[c + 1] = ptr_res - end - SparseMatrixCSC(m, n, colptr, rowval, nzval) -end - -@inline function stuffcol!(Xi::SparseMatrixCSC, colptr, rowval, nzval, - ptr_res, ptr_Xi, col_length, mX_sofar) - colptrXi = Xi.colptr - rowvalXi = Xi.rowval - nzvalXi = Xi.nzval - - for k=ptr_res:(ptr_res + col_length) - @inbounds rowval[k] = rowvalXi[ptr_Xi] + mX_sofar - @inbounds nzval[k] = nzvalXi[ptr_Xi] - ptr_Xi += 1 - end -end - - -function hcat(X::SparseMatrixCSC...) - num = length(X) - mX = Int[ size(x, 1) for x in X ] - nX = Int[ size(x, 2) for x in X ] - m = mX[1] - for i = 2 : num - if mX[i] != m; throw(DimensionMismatch("")); end - end - n = sum(nX) - - Tv = promote_eltype(X...) - Ti = promote_eltype(map(x->x.rowval, X)...) - - colptr = Vector{Ti}(n+1) - nnzX = Int[ nnz(x) for x in X ] - nnz_res = sum(nnzX) - rowval = Vector{Ti}(nnz_res) - nzval = Vector{Tv}(nnz_res) - - nnz_sofar = 0 - nX_sofar = 0 - @inbounds for i = 1 : num - XI = X[i] - colptr[(1 : nX[i] + 1) + nX_sofar] = XI.colptr .+ nnz_sofar - if nnzX[i] == length(XI.rowval) - rowval[(1 : nnzX[i]) + nnz_sofar] = XI.rowval - nzval[(1 : nnzX[i]) + nnz_sofar] = XI.nzval - else - rowval[(1 : nnzX[i]) + nnz_sofar] = XI.rowval[1:nnzX[i]] - nzval[(1 : nnzX[i]) + nnz_sofar] = XI.nzval[1:nnzX[i]] - end - nnz_sofar += nnzX[i] - nX_sofar += nX[i] - end - - SparseMatrixCSC(m, n, colptr, rowval, nzval) -end - -""" - blkdiag(A...) - -Concatenate matrices block-diagonally. Currently only implemented for sparse matrices. - -# Example -```jldoctest -julia> blkdiag(speye(3), 2*speye(2)) -5×5 SparseMatrixCSC{Float64,Int64} with 5 stored entries: - [1, 1] = 1.0 - [2, 2] = 1.0 - [3, 3] = 1.0 - [4, 4] = 2.0 - [5, 5] = 2.0 -``` -""" -function blkdiag(X::SparseMatrixCSC...) - num = length(X) - mX = Int[ size(x, 1) for x in X ] - nX = Int[ size(x, 2) for x in X ] - m = sum(mX) - n = sum(nX) - - Tv = promote_type(map(x->eltype(x.nzval), X)...) - Ti = promote_type(map(x->eltype(x.rowval), X)...) - - colptr = Vector{Ti}(n+1) - nnzX = Int[ nnz(x) for x in X ] - nnz_res = sum(nnzX) - rowval = Vector{Ti}(nnz_res) - nzval = Vector{Tv}(nnz_res) - - nnz_sofar = 0 - nX_sofar = 0 - mX_sofar = 0 - for i = 1 : num - colptr[(1 : nX[i] + 1) + nX_sofar] = X[i].colptr .+ nnz_sofar - rowval[(1 : nnzX[i]) + nnz_sofar] = X[i].rowval .+ mX_sofar - nzval[(1 : nnzX[i]) + nnz_sofar] = X[i].nzval - nnz_sofar += nnzX[i] - nX_sofar += nX[i] - mX_sofar += mX[i] - end - - SparseMatrixCSC(m, n, colptr, rowval, nzval) -end - -## Structure query functions -issymmetric(A::SparseMatrixCSC) = is_hermsym(A, identity) - -ishermitian(A::SparseMatrixCSC) = is_hermsym(A, conj) - -function is_hermsym(A::SparseMatrixCSC, check::Function) - m, n = size(A) - if m != n; return false; end - - colptr = A.colptr - rowval = A.rowval - nzval = A.nzval - tracker = copy(A.colptr) - for col = 1:A.n - # `tracker` is updated such that, for symmetric matrices, - # the loop below starts from an element at or below the - # diagonal element of column `col`" - for p = tracker[col]:colptr[col+1]-1 - val = nzval[p] - row = rowval[p] - - # Ignore stored zeros - if val == 0 - continue - end - - # If the matrix was symmetric we should have updated - # the tracker to start at the diagonal or below. Here - # we are above the diagonal so the matrix can't be symmetric. - if row < col - return false - end - - # Diagonal element - if row == col - if val != check(val) - return false - end - else - offset = tracker[row] - - # If the matrix is unsymmetric, there might not exist - # a rowval[offset] - if offset > length(rowval) - return false - end - - row2 = rowval[offset] - - # row2 can be less than col if the tracker didn't - # get updated due to stored zeros in previous elements. - # We therefore "catch up" here while making sure that - # the elements are actually zero. - while row2 < col - if nzval[offset] != 0 - return false - end - offset += 1 - row2 = rowval[offset] - tracker[row] += 1 - end - - # Non zero A[i,j] exists but A[j,i] does not exist - if row2 > col - return false - end - - # A[i,j] and A[j,i] exists - if row2 == col - if val != check(nzval[offset]) - return false - end - tracker[row] += 1 - end - end - end - end - return true -end - -function istriu(A::SparseMatrixCSC) - m, n = size(A) - colptr = A.colptr - rowval = A.rowval - nzval = A.nzval - - for col = 1:min(n, m-1) - l1 = colptr[col+1]-1 - for i = 0 : (l1 - colptr[col]) - if rowval[l1-i] <= col - break - end - if nzval[l1-i] != 0 - return false - end - end - end - return true -end - -function istril(A::SparseMatrixCSC) - m, n = size(A) - colptr = A.colptr - rowval = A.rowval - nzval = A.nzval - - for col = 2:n - for i = colptr[col] : (colptr[col+1]-1) - if rowval[i] >= col - break - end - if nzval[i] != 0 - return false - end - end - end - return true -end - -# Create a sparse diagonal matrix by specifying multiple diagonals -# packed into a tuple, alongside their diagonal offsets and matrix shape - -function spdiagm_internal(B, d) - ndiags = length(d) - if length(B) != ndiags; throw(ArgumentError("first argument should be a tuple of length(d)=$ndiags arrays of diagonals")); end - ncoeffs = 0 - for vec in B - ncoeffs += length(vec) - end - I = Vector{Int}(ncoeffs) - J = Vector{Int}(ncoeffs) - V = Vector{promote_type(map(eltype, B)...)}(ncoeffs) - id = 0 - i = 0 - for vec in B - id += 1 - diag = d[id] - numel = length(vec) - if diag < 0 - row = -diag - col = 0 - elseif diag > 0 - row = 0 - col = diag - else - row = 0 - col = 0 - end - range = 1+i:numel+i - I[range] = row+1:row+numel - J[range] = col+1:col+numel - copy!(view(V, range), vec) - i += numel - end - - return (I,J,V) -end - -""" - spdiagm(B, d[, m, n]) - -Construct a sparse diagonal matrix. `B` is a tuple of vectors containing the diagonals and -`d` is a tuple containing the positions of the diagonals. In the case the input contains only -one diagonal, `B` can be a vector (instead of a tuple) and `d` can be the diagonal position -(instead of a tuple), defaulting to 0 (diagonal). Optionally, `m` and `n` specify the size -of the resulting sparse matrix. - -# Example -```jldoctest -julia> spdiagm(([1,2,3,4],[4,3,2,1]),(-1,1)) -5×5 SparseMatrixCSC{Int64,Int64} with 8 stored entries: - [2, 1] = 1 - [1, 2] = 4 - [3, 2] = 2 - [2, 3] = 3 - [4, 3] = 3 - [3, 4] = 2 - [5, 4] = 4 - [4, 5] = 1 -``` -""" -function spdiagm(B, d, m::Integer, n::Integer) - (I,J,V) = spdiagm_internal(B, d) - return sparse(I,J,V,m,n) -end - -function spdiagm(B, d) - (I,J,V) = spdiagm_internal(B, d) - return sparse(I,J,V) -end - -spdiagm(B::AbstractVector, d::Number, m::Integer, n::Integer) = spdiagm((B,), (d,), m, n) - -spdiagm(B::AbstractVector, d::Number=0) = spdiagm((B,), (d,)) - -## expand a colptr or rowptr into a dense index vector -function expandptr(V::Vector{<:Integer}) - if V[1] != 1 throw(ArgumentError("first index must be one")) end - res = similar(V, (Int64(V[end]-1),)) - for i in 1:(length(V)-1), j in V[i]:(V[i+1] - 1); res[j] = i end - res -end - -## diag and related using an iterator - -mutable struct SpDiagIterator{Tv,Ti} - A::SparseMatrixCSC{Tv,Ti} - n::Int -end -SpDiagIterator(A::SparseMatrixCSC) = SpDiagIterator(A,minimum(size(A))) - -length(d::SpDiagIterator) = d.n -start(d::SpDiagIterator) = 1 -done(d::SpDiagIterator, j) = j > d.n - -function next(d::SpDiagIterator{Tv}, j) where Tv - A = d.A - r1 = Int(A.colptr[j]) - r2 = Int(A.colptr[j+1]-1) - (r1 > r2) && (return (zero(Tv), j+1)) - r1 = searchsortedfirst(A.rowval, j, r1, r2, Forward) - (((r1 > r2) || (A.rowval[r1] != j)) ? zero(Tv) : A.nzval[r1], j+1) -end - -function trace{Tv}(A::SparseMatrixCSC{Tv}) - if size(A,1) != size(A,2) - throw(DimensionMismatch("expected square matrix")) - end - s = zero(Tv) - for d in SpDiagIterator(A) - s += d - end - s -end - -diag{Tv}(A::SparseMatrixCSC{Tv}) = Tv[d for d in SpDiagIterator(A)] - -function diagm{Tv,Ti}(v::SparseMatrixCSC{Tv,Ti}) - if (size(v,1) != 1 && size(v,2) != 1) - throw(DimensionMismatch("input should be nx1 or 1xn")) - end - - n = length(v) - numnz = nnz(v) - colptr = Vector{Ti}(n+1) - rowval = Vector{Ti}(numnz) - nzval = Vector{Tv}(numnz) - - if size(v,1) == 1 - copy!(colptr, 1, v.colptr, 1, n+1) - ptr = 1 - for col = 1:n - if colptr[col] != colptr[col+1] - rowval[ptr] = col - nzval[ptr] = v.nzval[ptr] - ptr += 1 - end - end - else - copy!(rowval, 1, v.rowval, 1, numnz) - copy!(nzval, 1, v.nzval, 1, numnz) - colptr[1] = 1 - ptr = 1 - col = 1 - while col <= n && ptr <= numnz - while rowval[ptr] > col - colptr[col+1] = colptr[col] - col += 1 - end - colptr[col+1] = colptr[col] + 1 - ptr += 1 - col += 1 - end - if col <= n - colptr[(col+1):(n+1)] = colptr[col] - end - end - - return SparseMatrixCSC(n, n, colptr, rowval, nzval) -end - -# Sort all the indices in each column of a CSC sparse matrix -# sortSparseMatrixCSC!(A, sortindices = :sortcols) # Sort each column with sort() -# sortSparseMatrixCSC!(A, sortindices = :doubletranspose) # Sort with a double transpose -function sortSparseMatrixCSC!(A::SparseMatrixCSC{Tv,Ti}; sortindices::Symbol = :sortcols) where {Tv,Ti} - if sortindices == :doubletranspose - nB, mB = size(A) - B = SparseMatrixCSC(mB, nB, Vector{Ti}(nB+1), similar(A.rowval), similar(A.nzval)) - transpose!(B, A) - transpose!(A, B) - return A - end - - m, n = size(A) - colptr = A.colptr; rowval = A.rowval; nzval = A.nzval - - index = zeros(Ti, m) - row = zeros(Ti, m) - val = zeros(Tv, m) - - for i = 1:n - @inbounds col_start = colptr[i] - @inbounds col_end = (colptr[i+1] - 1) - - numrows = col_end - col_start + 1 - if numrows <= 1 - continue - elseif numrows == 2 - f = col_start - s = f+1 - if rowval[f] > rowval[s] - @inbounds rowval[f], rowval[s] = rowval[s], rowval[f] - @inbounds nzval[f], nzval[s] = nzval[s], nzval[f] - end - continue - end - - jj = 1 - @simd for j = col_start:col_end - @inbounds row[jj] = rowval[j] - @inbounds val[jj] = nzval[j] - jj += 1 - end - - sortperm!(unsafe_wrap(Vector{Ti}, pointer(index), numrows), - unsafe_wrap(Vector{Ti}, pointer(row), numrows)) - - jj = 1 - @simd for j = col_start:col_end - @inbounds rowval[j] = row[index[jj]] - @inbounds nzval[j] = val[index[jj]] - jj += 1 - end - end - - return A -end - -## rotations - -function rot180(A::SparseMatrixCSC) - I,J,V = findnz(A) - m,n = size(A) - for i=1:length(I) - I[i] = m - I[i] + 1 - J[i] = n - J[i] + 1 - end - return sparse(I,J,V,m,n) -end - -function rotr90(A::SparseMatrixCSC) - I,J,V = findnz(A) - m,n = size(A) - #old col inds are new row inds - for i=1:length(I) - I[i] = m - I[i] + 1 - end - return sparse(J, I, V, n, m) -end - -function rotl90(A::SparseMatrixCSC) - I,J,V = findnz(A) - m,n = size(A) - #old row inds are new col inds - for i=1:length(J) - J[i] = n - J[i] + 1 - end - return sparse(J, I, V, n, m) -end - -## hashing - -# End the run and return the current hash -@inline function hashrun(val, runlength::Int, h::UInt) - if runlength == 0 - return h - elseif runlength > 1 - h += Base.hashrle_seed - h = hash(runlength, h) - end - hash(val, h) -end - -function hash(A::SparseMatrixCSC{T}, h::UInt) where T - h += Base.hashaa_seed - sz = size(A) - h += hash(sz) - - colptr = A.colptr - rowval = A.rowval - nzval = A.nzval - lastidx = 0 - runlength = 0 - lastnz = zero(T) - @inbounds for col = 1:size(A, 2) - for j = colptr[col]:colptr[col+1]-1 - nz = nzval[j] - isequal(nz, zero(T)) && continue - idx = sub2ind(sz, rowval[j], col) - if idx != lastidx+1 || !isequal(nz, lastnz) # Run is over - h = hashrun(lastnz, runlength, h) # Hash previous run - h = hashrun(0, idx-lastidx-1, h) # Hash intervening zeros - - runlength = 1 - lastnz = nz - else - runlength += 1 - end - lastidx = idx - end - end - h = hashrun(lastnz, runlength, h) # Hash previous run - hashrun(0, length(A)-lastidx, h) # Hash zeros at end -end - -## Statistics - -# This is the function that does the reduction underlying var/std -function Base.centralize_sumabs2!(R::AbstractArray{S}, A::SparseMatrixCSC{Tv,Ti}, means::AbstractArray) where {S,Tv,Ti} - lsiz = Base.check_reducedims(R,A) - size(means) == size(R) || error("size of means must match size of R") - isempty(R) || fill!(R, zero(S)) - isempty(A) && return R - - colptr = A.colptr - rowval = A.rowval - nzval = A.nzval - m = size(A, 1) - n = size(A, 2) - - if size(R, 1) == size(R, 2) == 1 - # Reduction along both columns and rows - R[1, 1] = Base.centralize_sumabs2(A, means[1]) - elseif size(R, 1) == 1 - # Reduction along rows - @inbounds for col = 1:n - mu = means[col] - r = convert(S, (m-colptr[col+1]+colptr[col])*abs2(mu)) - @simd for j = colptr[col]:colptr[col+1]-1 - r += abs2(nzval[j] - mu) - end - R[1, col] = r - end - elseif size(R, 2) == 1 - # Reduction along columns - rownz = fill(convert(Ti, n), m) - @inbounds for col = 1:n - @simd for j = colptr[col]:colptr[col+1]-1 - row = rowval[j] - R[row, 1] += abs2(nzval[j] - means[row]) - rownz[row] -= 1 - end - end - for i = 1:m - R[i, 1] += rownz[i]*abs2(means[i]) - end - else - # Reduction along a dimension > 2 - @inbounds for col = 1:n - lastrow = 0 - @simd for j = colptr[col]:colptr[col+1]-1 - row = rowval[j] - for i = lastrow+1:row-1 - R[i, col] = abs2(means[i, col]) - end - R[row, col] = abs2(nzval[j] - means[row, col]) - lastrow = row - end - for i = lastrow+1:m - R[i, col] = abs2(means[i, col]) - end - end - end - return R -end - -## Uniform matrix arithmetic - -(+)(A::SparseMatrixCSC, J::UniformScaling) = A + J.λ * speye(A) -(-)(A::SparseMatrixCSC, J::UniformScaling) = A - J.λ * speye(A) -(-)(J::UniformScaling, A::SparseMatrixCSC) = J.λ * speye(A) - A diff --git a/julia-0.6.3/share/julia/base/sparse/sparsevector.jl b/julia-0.6.3/share/julia/base/sparse/sparsevector.jl deleted file mode 100644 index 28b8921..0000000 --- a/julia-0.6.3/share/julia/base/sparse/sparsevector.jl +++ /dev/null @@ -1,1994 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -### Common definitions - -import Base: scalarmax, scalarmin, sort, find, findnz -import Base.LinAlg: promote_to_array_type, promote_to_arrays_ - -### The SparseVector - -### Types - -""" - SparseVector{Tv,Ti<:Integer} <: AbstractSparseVector{Tv,Ti} - -Vector type for storing sparse vectors. -""" -struct SparseVector{Tv,Ti<:Integer} <: AbstractSparseVector{Tv,Ti} - n::Int # Length of the sparse vector - nzind::Vector{Ti} # Indices of stored values - nzval::Vector{Tv} # Stored values, typically nonzeros - - function SparseVector{Tv,Ti}(n::Integer, nzind::Vector{Ti}, nzval::Vector{Tv}) where {Tv,Ti<:Integer} - n >= 0 || throw(ArgumentError("The number of elements must be non-negative.")) - length(nzind) == length(nzval) || - throw(ArgumentError("index and value vectors must be the same length")) - new(convert(Int, n), nzind, nzval) - end -end - -SparseVector(n::Integer, nzind::Vector{Ti}, nzval::Vector{Tv}) where {Tv,Ti} = - SparseVector{Tv,Ti}(n, nzind, nzval) - -### Basic properties - -length(x::SparseVector) = x.n -size(x::SparseVector) = (x.n,) -nnz(x::SparseVector) = length(x.nzval) -countnz(x::SparseVector) = countnz(x.nzval) -count(x::SparseVector) = count(x.nzval) -nonzeros(x::SparseVector) = x.nzval -nonzeroinds(x::SparseVector) = x.nzind - -similar(x::SparseVector, Tv::Type=eltype(x)) = SparseVector(x.n, copy(x.nzind), Vector{Tv}(length(x.nzval))) -function similar(x::SparseVector, ::Type{Tv}, ::Type{Ti}) where {Tv,Ti} - return SparseVector(x.n, copy!(similar(x.nzind, Ti), x.nzind), copy!(similar(x.nzval, Tv), x.nzval)) -end -similar(x::SparseVector, ::Type{T}, D::Dims) where {T} = spzeros(T, D...) - -### Construct empty sparse vector - -spzeros(len::Integer) = spzeros(Float64, len) -spzeros(::Type{T}, len::Integer) where {T} = SparseVector(len, Int[], T[]) -spzeros(::Type{Tv}, ::Type{Ti}, len::Integer) where {Tv,Ti<:Integer} = SparseVector(len, Ti[], Tv[]) - -# Construction of same structure, but with all ones -spones(x::SparseVector{T}) where {T} = SparseVector(x.n, copy(x.nzind), ones(T, length(x.nzval))) - -### Construction from lists of indices and values - -function _sparsevector!(I::Vector{<:Integer}, V::Vector, len::Integer) - # pre-condition: no duplicate indexes in I - if !isempty(I) - p = sortperm(I) - permute!(I, p) - permute!(V, p) - end - SparseVector(len, I, V) -end - -function _sparsevector!(I::Vector{<:Integer}, V::Vector, len::Integer, combine::Function) - if !isempty(I) - p = sortperm(I) - permute!(I, p) - permute!(V, p) - m = length(I) - r = 1 - l = 1 # length of processed part - i = I[r] # row-index of current element - - # main loop - while r < m - r += 1 - i2 = I[r] - if i2 == i # accumulate r-th to the l-th entry - V[l] = combine(V[l], V[r]) - else # advance l, and move r-th to l-th - pv = V[l] - l += 1 - i = i2 - if l < r - I[l] = i; V[l] = V[r] - end - end - end - if l < m - resize!(I, l) - resize!(V, l) - end - end - SparseVector(len, I, V) -end - -""" - sparsevec(I, V, [m, combine]) - -Create a sparse vector `S` of length `m` such that `S[I[k]] = V[k]`. -Duplicates are combined using the `combine` function, which defaults to -`+` if no `combine` argument is provided, unless the elements of `V` are Booleans -in which case `combine` defaults to `|`. - -```jldoctest -julia> II = [1, 3, 3, 5]; V = [0.1, 0.2, 0.3, 0.2]; - -julia> sparsevec(II, V) -5-element SparseVector{Float64,Int64} with 3 stored entries: - [1] = 0.1 - [3] = 0.5 - [5] = 0.2 - -julia> sparsevec(II, V, 8, -) -8-element SparseVector{Float64,Int64} with 3 stored entries: - [1] = 0.1 - [3] = -0.1 - [5] = 0.2 - -julia> sparsevec([1, 3, 1, 2, 2], [true, true, false, false, false]) -3-element SparseVector{Bool,Int64} with 3 stored entries: - [1] = true - [2] = false - [3] = true -``` -""" -function sparsevec(I::AbstractVector{<:Integer}, V::AbstractVector, combine::Function) - length(I) == length(V) || - throw(ArgumentError("index and value vectors must be the same length")) - len = 0 - for i in I - i >= 1 || error("Index must be positive.") - if i > len - len = i - end - end - _sparsevector!(collect(I), collect(V), len, combine) -end - -function sparsevec(I::AbstractVector{<:Integer}, V::AbstractVector, len::Integer, combine::Function) - length(I) == length(V) || - throw(ArgumentError("index and value vectors must be the same length")) - for i in I - 1 <= i <= len || throw(ArgumentError("An index is out of bound.")) - end - _sparsevector!(collect(I), collect(V), len, combine) -end - -sparsevec(I::AbstractVector, V::Union{Number, AbstractVector}, args...) = - sparsevec(Vector{Int}(I), V, args...) - -sparsevec(I::AbstractVector, V::Union{Number, AbstractVector}) = - sparsevec(I, V, +) - -sparsevec(I::AbstractVector, V::Union{Number, AbstractVector}, len::Integer) = - sparsevec(I, V, len, +) - -sparsevec(I::AbstractVector, V::Union{Bool, AbstractVector{Bool}}) = - sparsevec(I, V, |) - -sparsevec(I::AbstractVector, V::Union{Bool, AbstractVector{Bool}}, len::Integer) = - sparsevec(I, V, len, |) - -sparsevec(I::AbstractVector, v::Number, combine::Function) = - sparsevec(I, fill(v, length(I)), combine) - -sparsevec(I::AbstractVector, v::Number, len::Integer, combine::Function) = - sparsevec(I, fill(v, length(I)), len, combine) - - -### Construction from dictionary -""" - sparsevec(d::Dict, [m]) - -Create a sparse vector of length `m` where the nonzero indices are keys from -the dictionary, and the nonzero values are the values from the dictionary. - -```jldoctest -julia> sparsevec(Dict(1 => 3, 2 => 2)) -2-element SparseVector{Int64,Int64} with 2 stored entries: - [1] = 3 - [2] = 2 -``` -""" -function sparsevec(dict::Associative{Ti,Tv}) where {Tv,Ti<:Integer} - m = length(dict) - nzind = Vector{Ti}(m) - nzval = Vector{Tv}(m) - - cnt = 0 - len = zero(Ti) - for (k, v) in dict - k >= 1 || throw(ArgumentError("index must be positive.")) - if k > len - len = k - end - cnt += 1 - @inbounds nzind[cnt] = k - @inbounds nzval[cnt] = v - end - resize!(nzind, cnt) - resize!(nzval, cnt) - _sparsevector!(nzind, nzval, len) -end - -function sparsevec(dict::Associative{Ti,Tv}, len::Integer) where {Tv,Ti<:Integer} - m = length(dict) - nzind = Vector{Ti}(m) - nzval = Vector{Tv}(m) - - cnt = 0 - maxk = convert(Ti, len) - for (k, v) in dict - 1 <= k <= maxk || throw(ArgumentError("an index (key) is out of bound.")) - cnt += 1 - @inbounds nzind[cnt] = k - @inbounds nzval[cnt] = v - end - resize!(nzind, cnt) - resize!(nzval, cnt) - _sparsevector!(nzind, nzval, len) -end - - -### Element access - -function setindex!(x::SparseVector{Tv,Ti}, v::Tv, i::Ti) where {Tv,Ti<:Integer} - checkbounds(x, i) - nzind = nonzeroinds(x) - nzval = nonzeros(x) - - m = length(nzind) - k = searchsortedfirst(nzind, i) - if 1 <= k <= m && nzind[k] == i # i found - nzval[k] = v - else # i not found - if v != 0 - insert!(nzind, k, i) - insert!(nzval, k, v) - end - end - x -end - -setindex!(x::SparseVector{Tv,Ti}, v, i::Integer) where {Tv,Ti<:Integer} = - setindex!(x, convert(Tv, v), convert(Ti, i)) - - -### dropstored! -""" - dropstored!(x::SparseVector, i::Integer) - -Drop entry `x[i]` from `x` if `x[i]` is stored and otherwise do nothing. - -# Examples -```jldoctest -julia> x = sparsevec([1, 3], [1.0, 2.0]) -3-element SparseVector{Float64,Int64} with 2 stored entries: - [1] = 1.0 - [3] = 2.0 - -julia> Base.SparseArrays.dropstored!(x, 3) -3-element SparseVector{Float64,Int64} with 1 stored entry: - [1] = 1.0 - -julia> Base.SparseArrays.dropstored!(x, 2) -3-element SparseVector{Float64,Int64} with 1 stored entry: - [1] = 1.0 -``` -""" -function dropstored!(x::SparseVector, i::Integer) - if !(1 <= i <= x.n) - throw(BoundsError(x, i)) - end - searchk = searchsortedfirst(x.nzind, i) - if searchk <= length(x.nzind) && x.nzind[searchk] == i - # Entry x[i] is stored. Drop and return. - deleteat!(x.nzind, searchk) - deleteat!(x.nzval, searchk) - end - return x -end -# TODO: Implement linear collection indexing methods for dropstored! ? -# TODO: Implement logical indexing methods for dropstored! ? - - -### Conversion - -# convert SparseMatrixCSC to SparseVector -function convert(::Type{SparseVector{Tv,Ti}}, s::SparseMatrixCSC{Tv,Ti}) where {Tv,Ti<:Integer} - size(s, 2) == 1 || throw(ArgumentError("The input argument must have a single-column.")) - SparseVector(s.m, s.rowval, s.nzval) -end - -convert(::Type{SparseVector{Tv}}, s::SparseMatrixCSC{Tv,Ti}) where {Tv,Ti} = - convert(SparseVector{Tv,Ti}, s) - -convert(::Type{SparseVector}, s::SparseMatrixCSC{Tv,Ti}) where {Tv,Ti} = - convert(SparseVector{Tv,Ti}, s) - -# convert Vector to SparseVector - -""" - sparsevec(A) - -Convert a vector `A` into a sparse vector of length `m`. - -# Example -```jldoctest -julia> sparsevec([1.0, 2.0, 0.0, 0.0, 3.0, 0.0]) -6-element SparseVector{Float64,Int64} with 3 stored entries: - [1] = 1.0 - [2] = 2.0 - [5] = 3.0 -``` -""" -sparsevec(a::AbstractVector{T}) where {T} = convert(SparseVector{T, Int}, a) -sparsevec(a::AbstractArray) = sparsevec(vec(a)) -sparsevec(a::AbstractSparseArray) = vec(a) -sparsevec(a::AbstractSparseVector) = vec(a) -sparse(a::AbstractVector) = sparsevec(a) - -function _dense2sparsevec(s::AbstractArray{Tv}, initcap::Ti) where {Tv,Ti} - # pre-condition: initcap > 0; the initcap determines the index type - n = length(s) - cap = initcap - nzind = Vector{Ti}(cap) - nzval = Vector{Tv}(cap) - c = 0 - @inbounds for i = 1:n - v = s[i] - if v != 0 - if c >= cap - cap *= 2 - resize!(nzind, cap) - resize!(nzval, cap) - end - c += 1 - nzind[c] = i - nzval[c] = v - end - end - if c < cap - resize!(nzind, c) - resize!(nzval, c) - end - SparseVector(n, nzind, nzval) -end - -convert(::Type{SparseVector{Tv,Ti}}, s::AbstractVector{Tv}) where {Tv,Ti} = - _dense2sparsevec(s, convert(Ti, max(8, div(length(s), 8)))) - -convert(::Type{SparseVector{Tv}}, s::AbstractVector{Tv}) where {Tv} = - convert(SparseVector{Tv,Int}, s) - -convert(::Type{SparseVector}, s::AbstractVector{Tv}) where {Tv} = - convert(SparseVector{Tv,Int}, s) - - -# convert between different types of SparseVector -convert(::Type{SparseVector{Tv}}, s::SparseVector{Tv}) where {Tv} = s -convert(::Type{SparseVector{Tv,Ti}}, s::SparseVector{Tv,Ti}) where {Tv,Ti} = s -convert(::Type{SparseVector{Tv,Ti}}, s::SparseVector) where {Tv,Ti} = - SparseVector{Tv,Ti}(s.n, convert(Vector{Ti}, s.nzind), convert(Vector{Tv}, s.nzval)) - -convert(::Type{SparseVector{Tv}}, s::SparseVector{<:Any,Ti}) where {Tv,Ti} = - SparseVector{Tv,Ti}(s.n, s.nzind, convert(Vector{Tv}, s.nzval)) - - -### copying -function prep_sparsevec_copy_dest!(A::SparseVector, lB, nnzB) - lA = length(A) - lA >= lB || throw(BoundsError()) - # If the two vectors have the same length then all the elements in A will be overwritten. - if length(A) == lB - resize!(A.nzval, nnzB) - resize!(A.nzind, nnzB) - else - nnzA = nnz(A) - - lastmodindA = searchsortedlast(A.nzind, lB) - if lastmodindA >= nnzB - # A will have fewer non-zero elements; unmodified elements are kept at the end. - deleteat!(A.nzind, nnzB+1:lastmodindA) - deleteat!(A.nzval, nnzB+1:lastmodindA) - else - # A will have more non-zero elements; unmodified elements are kept at the end. - resize!(A.nzind, nnzB + nnzA - lastmodindA) - resize!(A.nzval, nnzB + nnzA - lastmodindA) - copy!(A.nzind, nnzB+1, A.nzind, lastmodindA+1, nnzA-lastmodindA) - copy!(A.nzval, nnzB+1, A.nzval, lastmodindA+1, nnzA-lastmodindA) - end - end -end - -function copy!(A::SparseVector, B::SparseVector) - prep_sparsevec_copy_dest!(A, length(B), nnz(B)) - copy!(A.nzind, B.nzind) - copy!(A.nzval, B.nzval) - return A -end - -function copy!(A::SparseVector, B::SparseMatrixCSC) - prep_sparsevec_copy_dest!(A, length(B), nnz(B)) - - ptr = 1 - @assert length(A.nzind) >= length(B.rowval) - maximum(B.colptr)-1 <= length(B.rowval) || throw(BoundsError()) - @inbounds for col=1:length(B.colptr)-1 - offsetA = (col - 1) * B.m - while ptr <= B.colptr[col+1]-1 - A.nzind[ptr] = B.rowval[ptr] + offsetA - ptr += 1 - end - end - copy!(A.nzval, B.nzval) - return A -end - -copy!(A::SparseMatrixCSC, B::SparseVector{TvB,TiB}) where {TvB,TiB} = - copy!(A, SparseMatrixCSC{TvB,TiB}(B.n, 1, TiB[1, length(B.nzind)+1], B.nzind, B.nzval)) - - -### Rand Construction -sprand(n::Integer, p::AbstractFloat, rfn::Function, ::Type{T}) where {T} = sprand(GLOBAL_RNG, n, p, rfn, T) -function sprand(r::AbstractRNG, n::Integer, p::AbstractFloat, rfn::Function, ::Type{T}) where T - I = randsubseq(r, 1:convert(Int, n), p) - V = rfn(r, T, length(I)) - SparseVector(n, I, V) -end - -sprand(n::Integer, p::AbstractFloat, rfn::Function) = sprand(GLOBAL_RNG, n, p, rfn) -function sprand(r::AbstractRNG, n::Integer, p::AbstractFloat, rfn::Function) - I = randsubseq(r, 1:convert(Int, n), p) - V = rfn(r, length(I)) - SparseVector(n, I, V) -end - -sprand(n::Integer, p::AbstractFloat) = sprand(GLOBAL_RNG, n, p, rand) - -sprand(r::AbstractRNG, n::Integer, p::AbstractFloat) = sprand(r, n, p, rand) -sprand(r::AbstractRNG, ::Type{T}, n::Integer, p::AbstractFloat) where {T} = sprand(r, n, p, (r, i) -> rand(r, T, i)) -sprand(r::AbstractRNG, ::Type{Bool}, n::Integer, p::AbstractFloat) = sprand(r, n, p, truebools) -sprand(::Type{T}, n::Integer, p::AbstractFloat) where {T} = sprand(GLOBAL_RNG, T, n, p) - -sprandn(n::Integer, p::AbstractFloat) = sprand(GLOBAL_RNG, n, p, randn) -sprandn(r::AbstractRNG, n::Integer, p::AbstractFloat) = sprand(r, n, p, randn) - -## Indexing into Matrices can return SparseVectors - -# Column slices -function getindex(x::SparseMatrixCSC, ::Colon, j::Integer) - checkbounds(x, :, j) - r1 = convert(Int, x.colptr[j]) - r2 = convert(Int, x.colptr[j+1]) - 1 - SparseVector(x.m, x.rowval[r1:r2], x.nzval[r1:r2]) -end - -function getindex(x::SparseMatrixCSC, I::AbstractUnitRange, j::Integer) - checkbounds(x, I, j) - # Get the selected column - c1 = convert(Int, x.colptr[j]) - c2 = convert(Int, x.colptr[j+1]) - 1 - # Restrict to the selected rows - r1 = searchsortedfirst(x.rowval, first(I), c1, c2, Forward) - r2 = searchsortedlast(x.rowval, last(I), c1, c2, Forward) - SparseVector(length(I), [x.rowval[i] - first(I) + 1 for i = r1:r2], x.nzval[r1:r2]) -end - -# In the general case, we piggy back upon SparseMatrixCSC's optimized solution -@inline function getindex(A::SparseMatrixCSC, I::AbstractVector, J::Integer) - M = A[I, [J]] - SparseVector(M.m, M.rowval, M.nzval) -end - -# Row slices -getindex(A::SparseMatrixCSC, i::Integer, ::Colon) = A[i, 1:end] -function Base.getindex(A::SparseMatrixCSC{Tv,Ti}, i::Integer, J::AbstractVector) where {Tv,Ti} - checkbounds(A, i, J) - nJ = length(J) - colptrA = A.colptr; rowvalA = A.rowval; nzvalA = A.nzval - - nzinds = Vector{Ti}(0) - nzvals = Vector{Tv}(0) - - # adapted from SparseMatrixCSC's sorted_bsearch_A - ptrI = 1 - @inbounds for j = 1:nJ - col = J[j] - rowI = i - ptrA = Int(colptrA[col]) - stopA = Int(colptrA[col+1]-1) - if ptrA <= stopA - if rowvalA[ptrA] <= rowI - ptrA = searchsortedfirst(rowvalA, rowI, ptrA, stopA, Base.Order.Forward) - if ptrA <= stopA && rowvalA[ptrA] == rowI - push!(nzinds, j) - push!(nzvals, nzvalA[ptrA]) - end - end - ptrI += 1 - end - end - return SparseVector(nJ, nzinds, nzvals) -end - - -# Logical and linear indexing into SparseMatrices -getindex(A::SparseMatrixCSC, I::AbstractVector{Bool}) = _logical_index(A, I) # Ambiguities -getindex(A::SparseMatrixCSC, I::AbstractArray{Bool}) = _logical_index(A, I) -function _logical_index(A::SparseMatrixCSC{Tv}, I::AbstractArray{Bool}) where Tv - checkbounds(A, I) - n = sum(I) - nnzB = min(n, nnz(A)) - - colptrA = A.colptr; rowvalA = A.rowval; nzvalA = A.nzval - rowvalB = Vector{Int}(nnzB) - nzvalB = Vector{Tv}(nnzB) - c = 1 - rowB = 1 - - @inbounds for col in 1:A.n - r1 = colptrA[col] - r2 = colptrA[col+1]-1 - - for row in 1:A.m - if I[row, col] - while (r1 <= r2) && (rowvalA[r1] < row) - r1 += 1 - end - if (r1 <= r2) && (rowvalA[r1] == row) - nzvalB[c] = nzvalA[r1] - rowvalB[c] = rowB - c += 1 - end - rowB += 1 - (rowB > n) && break - end - end - (rowB > n) && break - end - if nnzB > (c-1) - deleteat!(nzvalB, c:nnzB) - deleteat!(rowvalB, c:nnzB) - end - SparseVector(n, rowvalB, nzvalB) -end - -# TODO: further optimizations are available for ::Colon and other types of Range -getindex(A::SparseMatrixCSC, ::Colon) = A[1:end] - -function getindex(A::SparseMatrixCSC{Tv}, I::AbstractUnitRange) where Tv - checkbounds(A, I) - szA = size(A) - nA = szA[1]*szA[2] - colptrA = A.colptr - rowvalA = A.rowval - nzvalA = A.nzval - - n = length(I) - nnzB = min(n, nnz(A)) - rowvalB = Vector{Int}(nnzB) - nzvalB = Vector{Tv}(nnzB) - - rowstart,colstart = ind2sub(szA, first(I)) - rowend,colend = ind2sub(szA, last(I)) - - idxB = 1 - @inbounds for col in colstart:colend - minrow = (col == colstart ? rowstart : 1) - maxrow = (col == colend ? rowend : szA[1]) - for r in colptrA[col]:(colptrA[col+1]-1) - rowA = rowvalA[r] - if minrow <= rowA <= maxrow - rowvalB[idxB] = sub2ind(szA, rowA, col) - first(I) + 1 - nzvalB[idxB] = nzvalA[r] - idxB += 1 - end - end - end - if nnzB > (idxB-1) - deleteat!(nzvalB, idxB:nnzB) - deleteat!(rowvalB, idxB:nnzB) - end - SparseVector(n, rowvalB, nzvalB) -end - -function getindex(A::SparseMatrixCSC{Tv}, I::AbstractVector) where Tv - szA = size(A) - nA = szA[1]*szA[2] - colptrA = A.colptr - rowvalA = A.rowval - nzvalA = A.nzval - - n = length(I) - nnzB = min(n, nnz(A)) - rowvalB = Vector{Int}(nnzB) - nzvalB = Vector{Tv}(nnzB) - - idxB = 1 - for i in 1:n - ((I[i] < 1) | (I[i] > nA)) && throw(BoundsError(A, I)) - row,col = ind2sub(szA, I[i]) - for r in colptrA[col]:(colptrA[col+1]-1) - @inbounds if rowvalA[r] == row - if idxB <= nnzB - rowvalB[idxB] = i - nzvalB[idxB] = nzvalA[r] - idxB += 1 - else # this can happen if there are repeated indices in I - push!(rowvalB, i) - push!(nzvalB, nzvalA[r]) - end - break - end - end - end - if nnzB > (idxB-1) - deleteat!(nzvalB, idxB:nnzB) - deleteat!(rowvalB, idxB:nnzB) - end - SparseVector(n, rowvalB, nzvalB) -end - -function find(x::SparseVector{<:Any,Ti}) where Ti - numnz = nnz(x) - I = Vector{Ti}(numnz) - - nzind = x.nzind - nzval = x.nzval - - count = 1 - @inbounds for i = 1 : numnz - if nzval[i] != 0 - I[count] = nzind[i] - count += 1 - end - end - - count -= 1 - if numnz != count - deleteat!(I, (count+1):numnz) - end - - return I -end - -function findnz(x::SparseVector{Tv,Ti}) where {Tv,Ti} - numnz = nnz(x) - - I = Vector{Ti}(numnz) - V = Vector{Tv}(numnz) - - nzind = x.nzind - nzval = x.nzval - - count = 1 - @inbounds for i = 1 : numnz - if nzval[i] != 0 - I[count] = nzind[i] - V[count] = nzval[i] - count += 1 - end - end - - count -= 1 - if numnz != count - deleteat!(I, (count+1):numnz) - deleteat!(V, (count+1):numnz) - end - - return (I, V) -end - -### Generic functions operating on AbstractSparseVector - -### getindex - -function _spgetindex(m::Int, nzind::AbstractVector{Ti}, nzval::AbstractVector{Tv}, i::Integer) where {Tv,Ti} - ii = searchsortedfirst(nzind, convert(Ti, i)) - (ii <= m && nzind[ii] == i) ? nzval[ii] : zero(Tv) -end - -function getindex(x::AbstractSparseVector, i::Integer) - checkbounds(x, i) - _spgetindex(nnz(x), nonzeroinds(x), nonzeros(x), i) -end - -function getindex(x::AbstractSparseVector{Tv,Ti}, I::AbstractUnitRange) where {Tv,Ti} - checkbounds(x, I) - xlen = length(x) - i0 = first(I) - i1 = last(I) - - xnzind = nonzeroinds(x) - xnzval = nonzeros(x) - m = length(xnzind) - - # locate the first j0, s.t. xnzind[j0] >= i0 - j0 = searchsortedfirst(xnzind, i0) - # locate the last j1, s.t. xnzind[j1] <= i1 - j1 = searchsortedlast(xnzind, i1, j0, m, Forward) - - # compute the number of non-zeros - jrgn = j0:j1 - mr = length(jrgn) - rind = Vector{Ti}(mr) - rval = Vector{Tv}(mr) - if mr > 0 - c = 0 - for j in jrgn - c += 1 - rind[c] = convert(Ti, xnzind[j] - i0 + 1) - rval[c] = xnzval[j] - end - end - SparseVector(length(I), rind, rval) -end - -getindex(x::AbstractSparseVector, I::AbstractVector{Bool}) = x[find(I)] -getindex(x::AbstractSparseVector, I::AbstractArray{Bool}) = x[find(I)] -@inline function getindex(x::AbstractSparseVector, I::AbstractVector) - # SparseMatrixCSC has a nicely optimized routine for this; punt - S = SparseMatrixCSC(x.n, 1, [1,length(x.nzind)+1], x.nzind, x.nzval) - S[I, 1] -end - -function getindex(x::AbstractSparseVector, I::AbstractArray) - # punt to SparseMatrixCSC - S = SparseMatrixCSC(x.n, 1, [1,length(x.nzind)+1], x.nzind, x.nzval) - S[I] -end - -getindex(x::AbstractSparseVector, ::Colon) = copy(x) - -### show and friends - -function show(io::IO, ::MIME"text/plain", x::AbstractSparseVector) - xnnz = length(nonzeros(x)) - print(io, length(x), "-element ", typeof(x), " with ", xnnz, - " stored ", xnnz == 1 ? "entry" : "entries") - if xnnz != 0 - println(io, ":") - show(io, x) - end -end - -show(io::IO, x::AbstractSparseVector) = show(convert(IOContext, io), x) -function show(io::IOContext, x::AbstractSparseVector) - # TODO: make this a one-line form - n = length(x) - nzind = nonzeroinds(x) - nzval = nonzeros(x) - xnnz = length(nzind) - if length(nzind) == 0 - return show(io, MIME("text/plain"), x) - end - limit::Bool = get(io, :limit, false) - half_screen_rows = limit ? div(displaysize(io)[1] - 8, 2) : typemax(Int) - pad = ndigits(n) - if !haskey(io, :compact) - io = IOContext(io, :compact => true) - end - for k = 1:length(nzind) - if k < half_screen_rows || k > xnnz - half_screen_rows - print(io, " ", '[', rpad(nzind[k], pad), "] = ") - if isassigned(nzval, Int(k)) - show(io, nzval[k]) - else - print(io, Base.undef_ref_str) - end - k != length(nzind) && println(io) - elseif k == half_screen_rows - println(io, " ", " "^pad, " \u22ee") - end - end -end - -### Conversion to matrix - -function convert(::Type{SparseMatrixCSC{Tv,Ti}}, x::AbstractSparseVector) where {Tv,Ti} - n = length(x) - xnzind = nonzeroinds(x) - xnzval = nonzeros(x) - m = length(xnzind) - colptr = Ti[1, m+1] - # Note that this *cannot* share data like normal array conversions, since - # modifying one would put the other in an inconsistent state - rowval = collect(Ti, xnzind) - nzval = collect(Tv, xnzval) - SparseMatrixCSC(n, 1, colptr, rowval, nzval) -end - -convert(::Type{SparseMatrixCSC{Tv}}, x::AbstractSparseVector{<:Any,Ti}) where {Tv,Ti} = - convert(SparseMatrixCSC{Tv,Ti}, x) - -convert(::Type{SparseMatrixCSC}, x::AbstractSparseVector{Tv,Ti}) where {Tv,Ti} = - convert(SparseMatrixCSC{Tv,Ti}, x) - -function convert(::Type{Vector}, x::AbstractSparseVector{Tv}) where Tv - n = length(x) - n == 0 && return Vector{Tv}(0) - nzind = nonzeroinds(x) - nzval = nonzeros(x) - r = zeros(Tv, n) - for k in 1:nnz(x) - i = nzind[k] - v = nzval[k] - r[i] = v - end - return r -end -convert(::Type{Array}, x::AbstractSparseVector) = convert(Vector, x) -full(x::AbstractSparseVector) = convert(Array, x) - -### Array manipulation - -vec(x::AbstractSparseVector) = x -copy(x::AbstractSparseVector) = - SparseVector(length(x), copy(nonzeroinds(x)), copy(nonzeros(x))) - -function reinterpret(::Type{T}, x::AbstractSparseVector{Tv}) where {T,Tv} - sizeof(T) == sizeof(Tv) || - throw(ArgumentError("reinterpret of sparse vectors only supports element types of the same size.")) - SparseVector(length(x), copy(nonzeroinds(x)), reinterpret(T, nonzeros(x))) -end - -float(x::AbstractSparseVector{<:AbstractFloat}) = x -float(x::AbstractSparseVector) = - SparseVector(length(x), copy(nonzeroinds(x)), float(nonzeros(x))) - -complex(x::AbstractSparseVector{<:Complex}) = x -complex(x::AbstractSparseVector) = - SparseVector(length(x), copy(nonzeroinds(x)), complex(nonzeros(x))) - - -### Concatenation - -# Without the first of these methods, horizontal concatenations of SparseVectors fall -# back to the horizontal concatenation method that ensures that combinations of -# sparse/special/dense matrix/vector types concatenate to SparseMatrixCSCs, instead -# of _absspvec_hcat below. The <:Integer qualifications are necessary for correct dispatch. -hcat(X::SparseVector{Tv,Ti}...) where {Tv,Ti<:Integer} = _absspvec_hcat(X...) -hcat(X::AbstractSparseVector{Tv,Ti}...) where {Tv,Ti<:Integer} = _absspvec_hcat(X...) -function _absspvec_hcat(X::AbstractSparseVector{Tv,Ti}...) where {Tv,Ti} - # check sizes - n = length(X) - m = length(X[1]) - tnnz = nnz(X[1]) - for j = 2:n - length(X[j]) == m || - throw(DimensionMismatch("Inconsistent column lengths.")) - tnnz += nnz(X[j]) - end - - # construction - colptr = Vector{Ti}(n+1) - nzrow = Vector{Ti}(tnnz) - nzval = Vector{Tv}(tnnz) - roff = 1 - @inbounds for j = 1:n - xj = X[j] - xnzind = nonzeroinds(xj) - xnzval = nonzeros(xj) - colptr[j] = roff - copy!(nzrow, roff, xnzind) - copy!(nzval, roff, xnzval) - roff += length(xnzind) - end - colptr[n+1] = roff - SparseMatrixCSC{Tv,Ti}(m, n, colptr, nzrow, nzval) -end - -# Without the first of these methods, vertical concatenations of SparseVectors fall -# back to the vertical concatenation method that ensures that combinations of -# sparse/special/dense matrix/vector types concatenate to SparseMatrixCSCs, instead -# of _absspvec_vcat below. The <:Integer qualifications are necessary for correct dispatch. -vcat(X::SparseVector{Tv,Ti}...) where {Tv,Ti<:Integer} = _absspvec_vcat(X...) -vcat(X::AbstractSparseVector{Tv,Ti}...) where {Tv,Ti<:Integer} = _absspvec_vcat(X...) -function vcat(X::SparseVector...) - commeltype = promote_type(map(eltype, X)...) - commindtype = promote_type(map(indtype, X)...) - vcat(map(x -> SparseVector{commeltype,commindtype}(x), X)...) -end -function _absspvec_vcat(X::AbstractSparseVector{Tv,Ti}...) where {Tv,Ti} - # check sizes - n = length(X) - tnnz = 0 - for j = 1:n - tnnz += nnz(X[j]) - end - - # construction - rnzind = Vector{Ti}(tnnz) - rnzval = Vector{Tv}(tnnz) - ir = 0 - len = 0 - @inbounds for j = 1:n - xj = X[j] - xnzind = nonzeroinds(xj) - xnzval = nonzeros(xj) - xnnz = length(xnzind) - for i = 1:xnnz - rnzind[ir + i] = xnzind[i] + len - end - copy!(rnzval, ir+1, xnzval) - ir += xnnz - len += length(xj) - end - SparseVector(len, rnzind, rnzval) -end - -hcat(Xin::Union{Vector, AbstractSparseVector}...) = hcat(map(sparse, Xin)...) -vcat(Xin::Union{Vector, AbstractSparseVector}...) = vcat(map(sparse, Xin)...) -# Without the following method, vertical concatenations of SparseVectors with Vectors -# fall back to the vertical concatenation method that ensures that combinations of -# sparse/special/dense matrix/vector types concatenate to SparseMatrixCSCs (because -# the vcat method immediately above is less specific, being defined in AbstractSparseVector -# rather than SparseVector). -vcat(X::Union{Vector,SparseVector}...) = vcat(map(sparse, X)...) - - -### Concatenation of un/annotated sparse/special/dense vectors/matrices - -# TODO: These methods and definitions should be moved to a more appropriate location, -# particularly some future equivalent of base/linalg/special.jl dedicated to interactions -# between a broader set of matrix types. - -# TODO: A definition similar to the third exists in base/linalg/bidiag.jl. These definitions -# should be consolidated in a more appropriate location, e.g. base/linalg/special.jl. -const _SparseArrays = Union{SparseVector, SparseMatrixCSC, RowVector{<:Any, <:SparseVector}} -const _SpecialArrays = Union{Diagonal, Bidiagonal, Tridiagonal, SymTridiagonal} -const _SparseConcatArrays = Union{_SpecialArrays, _SparseArrays} - -const _Symmetric_SparseConcatArrays{T,A<:_SparseConcatArrays} = Symmetric{T,A} -const _Hermitian_SparseConcatArrays{T,A<:_SparseConcatArrays} = Hermitian{T,A} -const _Triangular_SparseConcatArrays{T,A<:_SparseConcatArrays} = Base.LinAlg.AbstractTriangular{T,A} -const _Annotated_SparseConcatArrays = Union{_Triangular_SparseConcatArrays, _Symmetric_SparseConcatArrays, _Hermitian_SparseConcatArrays} - -const _Symmetric_DenseArrays{T,A<:Matrix} = Symmetric{T,A} -const _Hermitian_DenseArrays{T,A<:Matrix} = Hermitian{T,A} -const _Triangular_DenseArrays{T,A<:Matrix} = Base.LinAlg.AbstractTriangular{T,A} -const _Annotated_DenseArrays = Union{_Triangular_DenseArrays, _Symmetric_DenseArrays, _Hermitian_DenseArrays} -const _Annotated_Typed_DenseArrays{T} = Union{_Triangular_DenseArrays{T}, _Symmetric_DenseArrays{T}, _Hermitian_DenseArrays{T}} - -const _SparseConcatGroup = Union{Vector, RowVector{<:Any, <:Vector}, Matrix, _SparseConcatArrays, _Annotated_SparseConcatArrays, _Annotated_DenseArrays} -const _DenseConcatGroup = Union{Vector, RowVector{<:Any, <:Vector}, Matrix, _Annotated_DenseArrays} -const _TypedDenseConcatGroup{T} = Union{Vector{T}, RowVector{T,Vector{T}}, Matrix{T}, _Annotated_Typed_DenseArrays{T}} - -# Concatenations involving un/annotated sparse/special matrices/vectors should yield sparse arrays -function cat(catdims, Xin::_SparseConcatGroup...) - X = map(x -> SparseMatrixCSC(issparse(x) ? x : sparse(x)), Xin) - T = promote_eltype(Xin...) - Base.cat_t(catdims, T, X...) -end -function hcat(Xin::_SparseConcatGroup...) - X = map(x -> SparseMatrixCSC(issparse(x) ? x : sparse(x)), Xin) - hcat(X...) -end -function vcat(Xin::_SparseConcatGroup...) - X = map(x -> SparseMatrixCSC(issparse(x) ? x : sparse(x)), Xin) - vcat(X...) -end -function hvcat(rows::Tuple{Vararg{Int}}, X::_SparseConcatGroup...) - nbr = length(rows) # number of block rows - - tmp_rows = Vector{SparseMatrixCSC}(nbr) - k = 0 - @inbounds for i = 1 : nbr - tmp_rows[i] = hcat(X[(1 : rows[i]) + k]...) - k += rows[i] - end - vcat(tmp_rows...) -end - -# make sure UniformScaling objects are converted to sparse matrices for concatenation -promote_to_array_type(A::Tuple{Vararg{Union{_SparseConcatGroup,UniformScaling}}}) = SparseMatrixCSC -promote_to_array_type(A::Tuple{Vararg{Union{_DenseConcatGroup,UniformScaling}}}) = Matrix -promote_to_arrays_(n::Int, ::Type{SparseMatrixCSC}, J::UniformScaling) = sparse(J, n, n) - -# Concatenations strictly involving un/annotated dense matrices/vectors should yield dense arrays -cat(catdims, xs::_DenseConcatGroup...) = Base.cat_t(catdims, promote_eltype(xs...), xs...) -vcat(A::Vector...) = Base.typed_vcat(promote_eltype(A...), A...) -vcat(A::_DenseConcatGroup...) = Base.typed_vcat(promote_eltype(A...), A...) -hcat(A::Vector...) = Base.typed_hcat(promote_eltype(A...), A...) -hcat(A::_DenseConcatGroup...) = Base.typed_hcat(promote_eltype(A...), A...) -hvcat(rows::Tuple{Vararg{Int}}, xs::_DenseConcatGroup...) = Base.typed_hvcat(promote_eltype(xs...), rows, xs...) -# For performance, specially handle the case where the matrices/vectors have homogeneous eltype -cat(catdims, xs::_TypedDenseConcatGroup{T}...) where {T} = Base.cat_t(catdims, T, xs...) -vcat(A::_TypedDenseConcatGroup{T}...) where {T} = Base.typed_vcat(T, A...) -hcat(A::_TypedDenseConcatGroup{T}...) where {T} = Base.typed_hcat(T, A...) -hvcat(rows::Tuple{Vararg{Int}}, xs::_TypedDenseConcatGroup{T}...) where {T} = Base.typed_hvcat(T, rows, xs...) - - -### math functions - -### Unary Map - -# zero-preserving functions (z->z, nz->nz) --(x::SparseVector) = SparseVector(length(x), copy(nonzeroinds(x)), -(nonzeros(x))) - -# functions f, such that -# f(x) can be zero or non-zero when x != 0 -# f(x) = 0 when x == 0 -# -macro unarymap_nz2z_z2z(op, TF) - esc(quote - function $(op)(x::AbstractSparseVector{Tv,Ti}) where Tv<:$(TF) where Ti<:Integer - R = typeof($(op)(zero(Tv))) - xnzind = nonzeroinds(x) - xnzval = nonzeros(x) - m = length(xnzind) - - ynzind = Vector{Ti}(m) - ynzval = Vector{R}(m) - ir = 0 - @inbounds for j = 1:m - i = xnzind[j] - v = $(op)(xnzval[j]) - if v != zero(v) - ir += 1 - ynzind[ir] = i - ynzval[ir] = v - end - end - resize!(ynzind, ir) - resize!(ynzval, ir) - SparseVector(length(x), ynzind, ynzval) - end - end) -end - -# the rest of real, conj, imag are handled correctly via AbstractArray methods -@unarymap_nz2z_z2z real Complex -conj(x::SparseVector{<:Complex}) = SparseVector(length(x), copy(nonzeroinds(x)), conj(nonzeros(x))) -imag(x::AbstractSparseVector{Tv,Ti}) where {Tv<:Real,Ti<:Integer} = SparseVector(length(x), Ti[], Tv[]) -@unarymap_nz2z_z2z imag Complex - -for op in [:floor, :ceil, :trunc, :round] - @eval @unarymap_nz2z_z2z $(op) Real -end - -for op in [:log1p, :expm1, - :sin, :tan, :sinpi, :sind, :tand, - :asin, :atan, :asind, :atand, - :sinh, :tanh, :asinh, :atanh] - @eval @unarymap_nz2z_z2z $(op) Number -end - -# function that does not preserve zeros - -macro unarymap_z2nz(op, TF) - esc(quote - function $(op)(x::AbstractSparseVector{Tv,<:Integer}) where Tv<:$(TF) - v0 = $(op)(zero(Tv)) - R = typeof(v0) - xnzind = nonzeroinds(x) - xnzval = nonzeros(x) - n = length(x) - m = length(xnzind) - y = fill(v0, n) - @inbounds for j = 1:m - y[xnzind[j]] = $(op)(xnzval[j]) - end - y - end - end) -end - -for op in [:exp, :exp2, :exp10, :log, :log2, :log10, - :cos, :csc, :cot, :sec, :cospi, - :cosd, :cscd, :cotd, :secd, - :acos, :acot, :acosd, :acotd, - :cosh, :csch, :coth, :sech, - :acsch, :asech] - @eval @unarymap_z2nz $(op) Number -end - - -### Binary Map - -# mode: -# 0: f(nz, nz) -> nz, f(z, nz) -> z, f(nz, z) -> z -# 1: f(nz, nz) -> z/nz, f(z, nz) -> nz, f(nz, z) -> nz -# 2: f(nz, nz) -> z/nz, f(z, nz) -> z/nz, f(nz, z) -> z/nz - -function _binarymap(f::Function, - x::AbstractSparseVector{Tx}, - y::AbstractSparseVector{Ty}, - mode::Int) where {Tx,Ty} - 0 <= mode <= 2 || throw(ArgumentError("Incorrect mode $mode.")) - R = typeof(f(zero(Tx), zero(Ty))) - n = length(x) - length(y) == n || throw(DimensionMismatch()) - - xnzind = nonzeroinds(x) - xnzval = nonzeros(x) - ynzind = nonzeroinds(y) - ynzval = nonzeros(y) - mx = length(xnzind) - my = length(ynzind) - cap = (mode == 0 ? min(mx, my) : mx + my)::Int - - rind = Vector{Int}(cap) - rval = Vector{R}(cap) - ir = 0 - ix = 1 - iy = 1 - - ir = ( - mode == 0 ? _binarymap_mode_0!(f, mx, my, - xnzind, xnzval, ynzind, ynzval, rind, rval) : - mode == 1 ? _binarymap_mode_1!(f, mx, my, - xnzind, xnzval, ynzind, ynzval, rind, rval) : - _binarymap_mode_2!(f, mx, my, - xnzind, xnzval, ynzind, ynzval, rind, rval) - )::Int - - resize!(rind, ir) - resize!(rval, ir) - return SparseVector(n, rind, rval) -end - -function _binarymap_mode_0!(f::Function, mx::Int, my::Int, - xnzind, xnzval, ynzind, ynzval, rind, rval) - # f(nz, nz) -> nz, f(z, nz) -> z, f(nz, z) -> z - ir = 0; ix = 1; iy = 1 - @inbounds while ix <= mx && iy <= my - jx = xnzind[ix] - jy = ynzind[iy] - if jx == jy - v = f(xnzval[ix], ynzval[iy]) - ir += 1; rind[ir] = jx; rval[ir] = v - ix += 1; iy += 1 - elseif jx < jy - ix += 1 - else - iy += 1 - end - end - return ir -end - -function _binarymap_mode_1!(f::Function, mx::Int, my::Int, - xnzind, xnzval::AbstractVector{Tx}, - ynzind, ynzval::AbstractVector{Ty}, - rind, rval) where {Tx,Ty} - # f(nz, nz) -> z/nz, f(z, nz) -> nz, f(nz, z) -> nz - ir = 0; ix = 1; iy = 1 - @inbounds while ix <= mx && iy <= my - jx = xnzind[ix] - jy = ynzind[iy] - if jx == jy - v = f(xnzval[ix], ynzval[iy]) - if v != zero(v) - ir += 1; rind[ir] = jx; rval[ir] = v - end - ix += 1; iy += 1 - elseif jx < jy - v = f(xnzval[ix], zero(Ty)) - ir += 1; rind[ir] = jx; rval[ir] = v - ix += 1 - else - v = f(zero(Tx), ynzval[iy]) - ir += 1; rind[ir] = jy; rval[ir] = v - iy += 1 - end - end - @inbounds while ix <= mx - v = f(xnzval[ix], zero(Ty)) - ir += 1; rind[ir] = xnzind[ix]; rval[ir] = v - ix += 1 - end - @inbounds while iy <= my - v = f(zero(Tx), ynzval[iy]) - ir += 1; rind[ir] = ynzind[iy]; rval[ir] = v - iy += 1 - end - return ir -end - -function _binarymap_mode_2!(f::Function, mx::Int, my::Int, - xnzind, xnzval::AbstractVector{Tx}, - ynzind, ynzval::AbstractVector{Ty}, - rind, rval) where {Tx,Ty} - # f(nz, nz) -> z/nz, f(z, nz) -> z/nz, f(nz, z) -> z/nz - ir = 0; ix = 1; iy = 1 - @inbounds while ix <= mx && iy <= my - jx = xnzind[ix] - jy = ynzind[iy] - if jx == jy - v = f(xnzval[ix], ynzval[iy]) - if v != zero(v) - ir += 1; rind[ir] = jx; rval[ir] = v - end - ix += 1; iy += 1 - elseif jx < jy - v = f(xnzval[ix], zero(Ty)) - if v != zero(v) - ir += 1; rind[ir] = jx; rval[ir] = v - end - ix += 1 - else - v = f(zero(Tx), ynzval[iy]) - if v != zero(v) - ir += 1; rind[ir] = jy; rval[ir] = v - end - iy += 1 - end - end - @inbounds while ix <= mx - v = f(xnzval[ix], zero(Ty)) - if v != zero(v) - ir += 1; rind[ir] = xnzind[ix]; rval[ir] = v - end - ix += 1 - end - @inbounds while iy <= my - v = f(zero(Tx), ynzval[iy]) - if v != zero(v) - ir += 1; rind[ir] = ynzind[iy]; rval[ir] = v - end - iy += 1 - end - return ir -end - -function _binarymap(f::Function, - x::AbstractVector{Tx}, - y::AbstractSparseVector{Ty}, - mode::Int) where {Tx,Ty} - 0 <= mode <= 2 || throw(ArgumentError("Incorrect mode $mode.")) - R = typeof(f(zero(Tx), zero(Ty))) - n = length(x) - length(y) == n || throw(DimensionMismatch()) - - ynzind = nonzeroinds(y) - ynzval = nonzeros(y) - m = length(ynzind) - - dst = Vector{R}(n) - if mode == 0 - ii = 1 - @inbounds for i = 1:m - j = ynzind[i] - while ii < j - dst[ii] = zero(R); ii += 1 - end - dst[j] = f(x[j], ynzval[i]); ii += 1 - end - @inbounds while ii <= n - dst[ii] = zero(R); ii += 1 - end - else # mode >= 1 - ii = 1 - @inbounds for i = 1:m - j = ynzind[i] - while ii < j - dst[ii] = f(x[ii], zero(Ty)); ii += 1 - end - dst[j] = f(x[j], ynzval[i]); ii += 1 - end - @inbounds while ii <= n - dst[ii] = f(x[ii], zero(Ty)); ii += 1 - end - end - return dst -end - -function _binarymap(f::Function, - x::AbstractSparseVector{Tx}, - y::AbstractVector{Ty}, - mode::Int) where {Tx,Ty} - 0 <= mode <= 2 || throw(ArgumentError("Incorrect mode $mode.")) - R = typeof(f(zero(Tx), zero(Ty))) - n = length(x) - length(y) == n || throw(DimensionMismatch()) - - xnzind = nonzeroinds(x) - xnzval = nonzeros(x) - m = length(xnzind) - - dst = Vector{R}(n) - if mode == 0 - ii = 1 - @inbounds for i = 1:m - j = xnzind[i] - while ii < j - dst[ii] = zero(R); ii += 1 - end - dst[j] = f(xnzval[i], y[j]); ii += 1 - end - @inbounds while ii <= n - dst[ii] = zero(R); ii += 1 - end - else # mode >= 1 - ii = 1 - @inbounds for i = 1:m - j = xnzind[i] - while ii < j - dst[ii] = f(zero(Tx), y[ii]); ii += 1 - end - dst[j] = f(xnzval[i], y[j]); ii += 1 - end - @inbounds while ii <= n - dst[ii] = f(zero(Tx), y[ii]); ii += 1 - end - end - return dst -end - - -### Binary arithmetics: +, -, * - -for (vop, fun, mode) in [(:_vadd, :+, 1), - (:_vsub, :-, 1), - (:_vmul, :*, 0)] - @eval begin - $(vop)(x::AbstractSparseVector, y::AbstractSparseVector) = _binarymap($(fun), x, y, $mode) - $(vop)(x::StridedVector, y::AbstractSparseVector) = _binarymap($(fun), x, y, $mode) - $(vop)(x::AbstractSparseVector, y::StridedVector) = _binarymap($(fun), x, y, $mode) - end -end - -# to workaround the ambiguities with BitVector -broadcast(::typeof(*), x::BitVector, y::AbstractSparseVector{Bool}) = _vmul(x, y) -broadcast(::typeof(*), x::AbstractSparseVector{Bool}, y::BitVector) = _vmul(x, y) - -# definition of operators - -for (op, vop) in [(:+, :_vadd), (:-, :_vsub), (:*, :_vmul)] - op != :* && @eval begin - $(op)(x::AbstractSparseVector, y::AbstractSparseVector) = $(vop)(x, y) - $(op)(x::StridedVector, y::AbstractSparseVector) = $(vop)(x, y) - $(op)(x::AbstractSparseVector, y::StridedVector) = $(vop)(x, y) - end - @eval begin - broadcast(::typeof($op), x::AbstractSparseVector, y::AbstractSparseVector) = $(vop)(x, y) - broadcast(::typeof($op), x::StridedVector, y::AbstractSparseVector) = $(vop)(x, y) - broadcast(::typeof($op), x::AbstractSparseVector, y::StridedVector) = $(vop)(x, y) - end -end - -# definition of other binary functions - -broadcast(::typeof(min), x::SparseVector{<:Real}, y::SparseVector{<:Real}) = _binarymap(min, x, y, 2) -broadcast(::typeof(min), x::AbstractSparseVector{<:Real}, y::AbstractSparseVector{<:Real}) = _binarymap(min, x, y, 2) -broadcast(::typeof(min), x::StridedVector{<:Real}, y::AbstractSparseVector{<:Real}) = _binarymap(min, x, y, 2) -broadcast(::typeof(min), x::AbstractSparseVector{<:Real}, y::StridedVector{<:Real}) = _binarymap(min, x, y, 2) - -broadcast(::typeof(max), x::SparseVector{<:Real}, y::SparseVector{<:Real}) = _binarymap(max, x, y, 2) -broadcast(::typeof(max), x::AbstractSparseVector{<:Real}, y::AbstractSparseVector{<:Real}) = _binarymap(max, x, y, 2) -broadcast(::typeof(max), x::StridedVector{<:Real}, y::AbstractSparseVector{<:Real}) = _binarymap(max, x, y, 2) -broadcast(::typeof(max), x::AbstractSparseVector{<:Real}, y::StridedVector{<:Real}) = _binarymap(max, x, y, 2) - -complex(x::AbstractSparseVector{<:Real}, y::AbstractSparseVector{<:Real}) = _binarymap(complex, x, y, 1) -complex(x::StridedVector{<:Real}, y::AbstractSparseVector{<:Real}) = _binarymap(complex, x, y, 1) -complex(x::AbstractSparseVector{<:Real}, y::StridedVector{<:Real}) = _binarymap(complex, x, y, 1) - -### Reduction - -sum(x::AbstractSparseVector) = sum(nonzeros(x)) - -function maximum(x::AbstractSparseVector{T}) where T<:Real - n = length(x) - n > 0 || throw(ArgumentError("maximum over empty array is not allowed.")) - m = nnz(x) - (m == 0 ? zero(T) : - m == n ? maximum(nonzeros(x)) : - max(zero(T), maximum(nonzeros(x))))::T -end - -function minimum(x::AbstractSparseVector{T}) where T<:Real - n = length(x) - n > 0 || throw(ArgumentError("minimum over empty array is not allowed.")) - m = nnz(x) - (m == 0 ? zero(T) : - m == n ? minimum(nonzeros(x)) : - min(zero(T), minimum(nonzeros(x))))::T -end - -for f in [:sum, :maximum, :minimum], op in [:abs, :abs2] - SV = :AbstractSparseVector - if f == :minimum - @eval ($f)(::typeof($op), x::$SV{T}) where {T<:Number} = nnz(x) < length(x) ? ($op)(zero(T)) : ($f)($op, nonzeros(x)) - else - @eval ($f)(::typeof($op), x::$SV) = ($f)($op, nonzeros(x)) - end -end - -vecnorm(x::AbstractSparseVector, p::Real=2) = vecnorm(nonzeros(x), p) - -### linalg.jl - -# Transpose -# (The only sparse matrix structure in base is CSC, so a one-row sparse matrix is worse than dense) -@inline transpose(sv::SparseVector) = RowVector(sv) -@inline ctranspose(sv::SparseVector) = RowVector(conj(sv)) - -### BLAS Level-1 - -# axpy - -function LinAlg.axpy!(a::Number, x::AbstractSparseVector, y::StridedVector) - length(x) == length(y) || throw(DimensionMismatch()) - nzind = nonzeroinds(x) - nzval = nonzeros(x) - m = length(nzind) - - if a == oneunit(a) - for i = 1:m - @inbounds ii = nzind[i] - @inbounds v = nzval[i] - y[ii] += v - end - elseif a == -oneunit(a) - for i = 1:m - @inbounds ii = nzind[i] - @inbounds v = nzval[i] - y[ii] -= v - end - else - for i = 1:m - @inbounds ii = nzind[i] - @inbounds v = nzval[i] - y[ii] += a * v - end - end - return y -end - - -# scale - -scale!(x::AbstractSparseVector, a::Real) = (scale!(nonzeros(x), a); x) -scale!(x::AbstractSparseVector, a::Complex) = (scale!(nonzeros(x), a); x) -scale!(a::Real, x::AbstractSparseVector) = (scale!(nonzeros(x), a); x) -scale!(a::Complex, x::AbstractSparseVector) = (scale!(nonzeros(x), a); x) - - -(*)(x::AbstractSparseVector, a::Number) = SparseVector(length(x), copy(nonzeroinds(x)), nonzeros(x) * a) -(*)(a::Number, x::AbstractSparseVector) = SparseVector(length(x), copy(nonzeroinds(x)), a * nonzeros(x)) -(/)(x::AbstractSparseVector, a::Number) = SparseVector(length(x), copy(nonzeroinds(x)), nonzeros(x) / a) -broadcast(::typeof(*), x::AbstractSparseVector, a::Number) = x * a -broadcast(::typeof(*), a::Number, x::AbstractSparseVector) = a * x -broadcast(::typeof(/), x::AbstractSparseVector, a::Number) = x / a - -# dot - -function dot(x::StridedVector{Tx}, y::AbstractSparseVector{Ty}) where {Tx<:Number,Ty<:Number} - n = length(x) - length(y) == n || throw(DimensionMismatch()) - nzind = nonzeroinds(y) - nzval = nonzeros(y) - s = zero(Tx) * zero(Ty) - for i = 1:length(nzind) - s += conj(x[nzind[i]]) * nzval[i] - end - return s -end - -function dot(x::AbstractSparseVector{Tx}, y::AbstractVector{Ty}) where {Tx<:Number,Ty<:Number} - n = length(y) - length(x) == n || throw(DimensionMismatch()) - nzind = nonzeroinds(x) - nzval = nonzeros(x) - s = zero(Tx) * zero(Ty) - for i = 1:length(nzind) - s += conj(nzval[i]) * y[nzind[i]] - end - return s -end - -function _spdot(f::Function, - xj::Int, xj_last::Int, xnzind, xnzval, - yj::Int, yj_last::Int, ynzind, ynzval) - # dot product between ranges of non-zeros, - s = zero(eltype(xnzval)) * zero(eltype(ynzval)) - @inbounds while xj <= xj_last && yj <= yj_last - ix = xnzind[xj] - iy = ynzind[yj] - if ix == iy - s += f(xnzval[xj], ynzval[yj]) - xj += 1 - yj += 1 - elseif ix < iy - xj += 1 - else - yj += 1 - end - end - s -end - -function dot(x::AbstractSparseVector{<:Number}, y::AbstractSparseVector{<:Number}) - x === y && return sum(abs2, x) - n = length(x) - length(y) == n || throw(DimensionMismatch()) - - xnzind = nonzeroinds(x) - ynzind = nonzeroinds(y) - xnzval = nonzeros(x) - ynzval = nonzeros(y) - - _spdot(dot, - 1, length(xnzind), xnzind, xnzval, - 1, length(ynzind), ynzind, ynzval) -end - - -### BLAS-2 / dense A * sparse x -> dense y - -# A_mul_B - -function (*)(A::StridedMatrix{Ta}, x::AbstractSparseVector{Tx}) where {Ta,Tx} - m, n = size(A) - length(x) == n || throw(DimensionMismatch()) - Ty = promote_type(Ta, Tx) - y = Vector{Ty}(m) - A_mul_B!(y, A, x) -end - -A_mul_B!(y::StridedVector{Ty}, A::StridedMatrix, x::AbstractSparseVector{Tx}) where {Tx,Ty} = - A_mul_B!(one(Tx), A, x, zero(Ty), y) - -function A_mul_B!(α::Number, A::StridedMatrix, x::AbstractSparseVector, β::Number, y::StridedVector) - m, n = size(A) - length(x) == n && length(y) == m || throw(DimensionMismatch()) - m == 0 && return y - if β != one(β) - β == zero(β) ? fill!(y, zero(eltype(y))) : scale!(y, β) - end - α == zero(α) && return y - - xnzind = nonzeroinds(x) - xnzval = nonzeros(x) - @inbounds for i = 1:length(xnzind) - v = xnzval[i] - if v != zero(v) - j = xnzind[i] - αv = v * α - for r = 1:m - y[r] += A[r,j] * αv - end - end - end - return y -end - -# At_mul_B - -function At_mul_B(A::StridedMatrix{Ta}, x::AbstractSparseVector{Tx}) where {Ta,Tx} - m, n = size(A) - length(x) == m || throw(DimensionMismatch()) - Ty = promote_type(Ta, Tx) - y = Vector{Ty}(n) - At_mul_B!(y, A, x) -end - -At_mul_B!(y::StridedVector{Ty}, A::StridedMatrix, x::AbstractSparseVector{Tx}) where {Tx,Ty} = - At_mul_B!(one(Tx), A, x, zero(Ty), y) - -function At_mul_B!(α::Number, A::StridedMatrix, x::AbstractSparseVector, β::Number, y::StridedVector) - m, n = size(A) - length(x) == m && length(y) == n || throw(DimensionMismatch()) - n == 0 && return y - if β != one(β) - β == zero(β) ? fill!(y, zero(eltype(y))) : scale!(y, β) - end - α == zero(α) && return y - - xnzind = nonzeroinds(x) - xnzval = nonzeros(x) - _nnz = length(xnzind) - _nnz == 0 && return y - - s0 = zero(eltype(A)) * zero(eltype(x)) - @inbounds for j = 1:n - s = zero(s0) - for i = 1:_nnz - s += A[xnzind[i], j] * xnzval[i] - end - y[j] += s * α - end - return y -end - - -### BLAS-2 / sparse A * sparse x -> dense y - -function densemv(A::SparseMatrixCSC, x::AbstractSparseVector; trans::Char='N') - local xlen::Int, ylen::Int - m, n = size(A) - if trans == 'N' || trans == 'n' - xlen = n; ylen = m - elseif trans == 'T' || trans == 't' || trans == 'C' || trans == 'c' - xlen = m; ylen = n - else - throw(ArgumentError("Invalid trans character $trans")) - end - xlen == length(x) || throw(DimensionMismatch()) - T = promote_type(eltype(A), eltype(x)) - y = Vector{T}(ylen) - if trans == 'N' || trans == 'N' - A_mul_B!(y, A, x) - elseif trans == 'T' || trans == 't' - At_mul_B!(y, A, x) - elseif trans == 'C' || trans == 'c' - Ac_mul_B!(y, A, x) - else - throw(ArgumentError("Invalid trans character $trans")) - end - y -end - -# A_mul_B - -A_mul_B!(y::StridedVector{Ty}, A::SparseMatrixCSC, x::AbstractSparseVector{Tx}) where {Tx,Ty} = - A_mul_B!(one(Tx), A, x, zero(Ty), y) - -function A_mul_B!(α::Number, A::SparseMatrixCSC, x::AbstractSparseVector, β::Number, y::StridedVector) - m, n = size(A) - length(x) == n && length(y) == m || throw(DimensionMismatch()) - m == 0 && return y - if β != one(β) - β == zero(β) ? fill!(y, zero(eltype(y))) : scale!(y, β) - end - α == zero(α) && return y - - xnzind = nonzeroinds(x) - xnzval = nonzeros(x) - Acolptr = A.colptr - Arowval = A.rowval - Anzval = A.nzval - - @inbounds for i = 1:length(xnzind) - v = xnzval[i] - if v != zero(v) - αv = v * α - j = xnzind[i] - for r = A.colptr[j]:(Acolptr[j+1]-1) - y[Arowval[r]] += Anzval[r] * αv - end - end - end - return y -end - -# At_mul_B - -At_mul_B!(y::StridedVector{Ty}, A::SparseMatrixCSC, x::AbstractSparseVector{Tx}) where {Tx,Ty} = - At_mul_B!(one(Tx), A, x, zero(Ty), y) - -At_mul_B!(α::Number, A::SparseMatrixCSC, x::AbstractSparseVector, β::Number, y::StridedVector) = - _At_or_Ac_mul_B!(*, α, A, x, β, y) - -Ac_mul_B!(y::StridedVector{Ty}, A::SparseMatrixCSC, x::AbstractSparseVector{Tx}) where {Tx,Ty} = - Ac_mul_B!(one(Tx), A, x, zero(Ty), y) - -Ac_mul_B!(α::Number, A::SparseMatrixCSC, x::AbstractSparseVector, β::Number, y::StridedVector) = - _At_or_Ac_mul_B!(dot, α, A, x, β, y) - -function _At_or_Ac_mul_B!(tfun::Function, - α::Number, A::SparseMatrixCSC, x::AbstractSparseVector, - β::Number, y::StridedVector) - m, n = size(A) - length(x) == m && length(y) == n || throw(DimensionMismatch()) - n == 0 && return y - if β != one(β) - β == zero(β) ? fill!(y, zero(eltype(y))) : scale!(y, β) - end - α == zero(α) && return y - - xnzind = nonzeroinds(x) - xnzval = nonzeros(x) - Acolptr = A.colptr - Arowval = A.rowval - Anzval = A.nzval - mx = length(xnzind) - - for j = 1:n - # s <- dot(A[:,j], x) - s = _spdot(tfun, Acolptr[j], Acolptr[j+1]-1, Arowval, Anzval, - 1, mx, xnzind, xnzval) - @inbounds y[j] += s * α - end - return y -end - - -### BLAS-2 / sparse A * sparse x -> dense y - -function *(A::SparseMatrixCSC, x::AbstractSparseVector) - y = densemv(A, x) - initcap = min(nnz(A), size(A,1)) - _dense2sparsevec(y, initcap) -end - -At_mul_B(A::SparseMatrixCSC, x::AbstractSparseVector) = - _At_or_Ac_mul_B(*, A, x) - -Ac_mul_B(A::SparseMatrixCSC, x::AbstractSparseVector) = - _At_or_Ac_mul_B(dot, A, x) - -function _At_or_Ac_mul_B(tfun::Function, A::SparseMatrixCSC{TvA,TiA}, x::AbstractSparseVector{TvX,TiX}) where {TvA,TiA,TvX,TiX} - m, n = size(A) - length(x) == m || throw(DimensionMismatch()) - Tv = promote_type(TvA, TvX) - Ti = promote_type(TiA, TiX) - - xnzind = nonzeroinds(x) - xnzval = nonzeros(x) - Acolptr = A.colptr - Arowval = A.rowval - Anzval = A.nzval - mx = length(xnzind) - - ynzind = Vector{Ti}(n) - ynzval = Vector{Tv}(n) - - jr = 0 - for j = 1:n - s = _spdot(tfun, Acolptr[j], Acolptr[j+1]-1, Arowval, Anzval, - 1, mx, xnzind, xnzval) - if s != zero(s) - jr += 1 - ynzind[jr] = j - ynzval[jr] = s - end - end - if jr < n - resize!(ynzind, jr) - resize!(ynzval, jr) - end - SparseVector(n, ynzind, ynzval) -end - - -# define matrix division operations involving triangular matrices and sparse vectors -# the valid left-division operations are A[t|c]_ldiv_B[!] and \ -# the valid right-division operations are A(t|c)_rdiv_B[t|c][!] -# see issue #14005 for discussion of these methods -for isunittri in (true, false), islowertri in (true, false) - unitstr = isunittri ? "Unit" : "" - halfstr = islowertri ? "Lower" : "Upper" - tritype = :(Base.LinAlg.$(Symbol(unitstr, halfstr, "Triangular"))) - - # build out-of-place left-division operations - for (istrans, func, ipfunc) in ( - (false, :(\), :(A_ldiv_B!)), - (true, :(At_ldiv_B), :(At_ldiv_B!)), - (true, :(Ac_ldiv_B), :(Ac_ldiv_B!)) ) - - # broad method where elements are Numbers - @eval function ($func)(A::$tritype{TA,<:AbstractMatrix}, b::SparseVector{Tb}) where {TA<:Number,Tb<:Number} - TAb = $(isunittri ? - :(typeof(zero(TA)*zero(Tb) + zero(TA)*zero(Tb))) : - :(typeof((zero(TA)*zero(Tb) + zero(TA)*zero(Tb))/one(TA))) ) - ($ipfunc)(convert(AbstractArray{TAb}, A), convert(Array{TAb}, b)) - end - - # faster method requiring good view support of the - # triangular matrix type. hence the StridedMatrix restriction. - @eval function ($func)(A::$tritype{TA,<:StridedMatrix}, b::SparseVector{Tb}) where {TA<:Number,Tb<:Number} - TAb = $(isunittri ? - :(typeof(zero(TA)*zero(Tb) + zero(TA)*zero(Tb))) : - :(typeof((zero(TA)*zero(Tb) + zero(TA)*zero(Tb))/one(TA))) ) - r = convert(Array{TAb}, b) - # If b has no nonzero entries, then r is necessarily zero. If b has nonzero - # entries, then the operation involves only b[nzrange], so we extract and - # operate on solely b[nzrange] for efficiency. - if nnz(b) != 0 - nzrange = $( (islowertri && !istrans) || (!islowertri && istrans) ? - :(b.nzind[1]:b.n) : - :(1:b.nzind[end]) ) - nzrangeviewr = view(r, nzrange) - nzrangeviewA = $tritype(view(A.data, nzrange, nzrange)) - ($ipfunc)(convert(AbstractArray{TAb}, nzrangeviewA), nzrangeviewr) - end - r - end - - # fallback where elements are not Numbers - @eval ($func)(A::$tritype, b::SparseVector) = ($ipfunc)(A, copy(b)) - end - - # build in-place left-division operations - for (istrans, func) in ( - (false, :(A_ldiv_B!)), - (true, :(At_ldiv_B!)), - (true, :(Ac_ldiv_B!)) ) - - # the generic in-place left-division methods handle these cases, but - # we can achieve greater efficiency where the triangular matrix provides - # good view support. hence the StridedMatrix restriction. - @eval function ($func)(A::$tritype{<:Any,<:StridedMatrix}, b::SparseVector) - # If b has no nonzero entries, the result is necessarily zero and this call - # reduces to a no-op. If b has nonzero entries, then... - if nnz(b) != 0 - # densify the relevant part of b in one shot rather - # than potentially repeatedly reallocating during the solve - $( (islowertri && !istrans) || (!islowertri && istrans) ? - :(_densifyfirstnztoend!(b)) : - :(_densifystarttolastnz!(b)) ) - # this operation involves only the densified section, so - # for efficiency we extract and operate on solely that section - # furthermore we operate on that section as a dense vector - # such that dispatch has a chance to exploit, e.g., tuned BLAS - nzrange = $( (islowertri && !istrans) || (!islowertri && istrans) ? - :(b.nzind[1]:b.n) : - :(1:b.nzind[end]) ) - nzrangeviewbnz = view(b.nzval, nzrange - b.nzind[1] + 1) - nzrangeviewA = $tritype(view(A.data, nzrange, nzrange)) - ($func)(nzrangeviewA, nzrangeviewbnz) - # could strip any miraculous zeros here perhaps - end - b - end - end -end - -# helper functions for in-place matrix division operations defined above -"Densifies `x::SparseVector` from its first nonzero (`x[x.nzind[1]]`) through its end (`x[x.n]`)." -function _densifyfirstnztoend!(x::SparseVector) - # lengthen containers - oldnnz = nnz(x) - newnnz = x.n - x.nzind[1] + 1 - resize!(x.nzval, newnnz) - resize!(x.nzind, newnnz) - # redistribute nonzero values over lengthened container - # initialize now-allocated zero values simultaneously - nextpos = newnnz - @inbounds for oldpos in oldnnz:-1:1 - nzi = x.nzind[oldpos] - nzv = x.nzval[oldpos] - newpos = nzi - x.nzind[1] + 1 - newpos < nextpos && (x.nzval[newpos+1:nextpos] = 0) - newpos == oldpos && break - x.nzval[newpos] = nzv - nextpos = newpos - 1 - end - # finally update lengthened nzinds - x.nzind[2:end] = (x.nzind[1]+1):x.n - x -end -"Densifies `x::SparseVector` from its beginning (`x[1]`) through its last nonzero (`x[x.nzind[end]]`)." -function _densifystarttolastnz!(x::SparseVector) - # lengthen containers - oldnnz = nnz(x) - newnnz = x.nzind[end] - resize!(x.nzval, newnnz) - resize!(x.nzind, newnnz) - # redistribute nonzero values over lengthened container - # initialize now-allocated zero values simultaneously - nextpos = newnnz - @inbounds for oldpos in oldnnz:-1:1 - nzi = x.nzind[oldpos] - nzv = x.nzval[oldpos] - nzi < nextpos && (x.nzval[nzi+1:nextpos] = 0) - nzi == oldpos && (nextpos = 0; break) - x.nzval[nzi] = nzv - nextpos = nzi - 1 - end - nextpos > 0 && (x.nzval[1:nextpos] = 0) - # finally update lengthened nzinds - x.nzind[1:newnnz] = 1:newnnz - x -end - -#sorting -function sort{Tv,Ti}(x::SparseVector{Tv,Ti}; kws...) - allvals = push!(copy(nonzeros(x)),zero(Tv)) - sinds = sortperm(allvals;kws...) - n,k = length(x),length(allvals) - z = findfirst(sinds,k) - newnzind = collect(Ti,1:k-1) - newnzind[z:end]+= n-k+1 - newnzvals = allvals[deleteat!(sinds[1:k],z)] - SparseVector(n,newnzind,newnzvals) -end - -function fkeep!(x::SparseVector, f, trim::Bool = true) - n = x.n - nzind = x.nzind - nzval = x.nzval - - x_writepos = 1 - @inbounds for xk in 1:nnz(x) - xi = nzind[xk] - xv = nzval[xk] - # If this element should be kept, rewrite in new position - if f(xi, xv) - if x_writepos != xk - nzind[x_writepos] = xi - nzval[x_writepos] = xv - end - x_writepos += 1 - end - end - - # Trim x's storage if necessary and desired - if trim - x_nnz = x_writepos - 1 - if length(nzind) != x_nnz - resize!(nzval, x_nnz) - resize!(nzind, x_nnz) - end - end - - x -end - -droptol!(x::SparseVector, tol, trim::Bool = true) = fkeep!(x, (i, x) -> abs(x) > tol, trim) - -""" - dropzeros!(x::SparseVector, trim::Bool = true) - -Removes stored numerical zeros from `x`, optionally trimming resulting excess space from -`x.nzind` and `x.nzval` when `trim` is `true`. - -For an out-of-place version, see [`dropzeros`](@ref). For -algorithmic information, see `fkeep!`. -""" -dropzeros!(x::SparseVector, trim::Bool = true) = fkeep!(x, (i, x) -> x != 0, trim) -""" - dropzeros(x::SparseVector, trim::Bool = true) - -Generates a copy of `x` and removes numerical zeros from that copy, optionally trimming -excess space from the result's `nzind` and `nzval` arrays when `trim` is `true`. - -For an in-place version and algorithmic information, see [`dropzeros!`](@ref). - -# Example -```jldoctest -julia> A = sparsevec([1, 2, 3], [1.0, 0.0, 1.0]) -3-element SparseVector{Float64,Int64} with 3 stored entries: - [1] = 1.0 - [2] = 0.0 - [3] = 1.0 - -julia> dropzeros(A) -3-element SparseVector{Float64,Int64} with 2 stored entries: - [1] = 1.0 - [3] = 1.0 -``` -""" -dropzeros(x::SparseVector, trim::Bool = true) = dropzeros!(copy(x), trim) - - -function _fillnonzero!(arr::SparseMatrixCSC{Tv, Ti}, val) where {Tv,Ti} - m, n = size(arr) - resize!(arr.colptr, n+1) - resize!(arr.rowval, m*n) - resize!(arr.nzval, m*n) - copy!(arr.colptr, 1:m:n*m+1) - fill!(arr.nzval, val) - index = 1 - @inbounds for _ in 1:n - for i in 1:m - arr.rowval[index] = Ti(i) - index += 1 - end - end - arr -end - -function _fillnonzero!(arr::SparseVector{Tv,Ti}, val) where {Tv,Ti} - n = arr.n - resize!(arr.nzind, n) - resize!(arr.nzval, n) - @inbounds for i in 1:n - arr.nzind[i] = Ti(i) - end - fill!(arr.nzval, val) - arr -end - -import Base.fill! -function fill!(A::Union{SparseVector, SparseMatrixCSC}, x) - T = eltype(A) - xT = convert(T, x) - if xT == zero(T) - fill!(A.nzval, xT) - else - _fillnonzero!(A, xT) - end - return A -end diff --git a/julia-0.6.3/share/julia/base/sparse/spqr.jl b/julia-0.6.3/share/julia/base/sparse/spqr.jl deleted file mode 100644 index c7a88f7..0000000 --- a/julia-0.6.3/share/julia/base/sparse/spqr.jl +++ /dev/null @@ -1,184 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -module SPQR - -import Base: \ - -# ordering options */ -const ORDERING_FIXED = Int32(0) -const ORDERING_NATURAL = Int32(1) -const ORDERING_COLAMD = Int32(2) -const ORDERING_GIVEN = Int32(3) # only used for C/C++ interface -const ORDERING_CHOLMOD = Int32(4) # CHOLMOD best-effort (COLAMD, METIS,...) -const ORDERING_AMD = Int32(5) # AMD(A'*A) -const ORDERING_METIS = Int32(6) # metis(A'*A) -const ORDERING_DEFAULT = Int32(7) # SuiteSparseQR default ordering -const ORDERING_BEST = Int32(8) # try COLAMD, AMD, and METIS; pick best -const ORDERING_BESTAMD = Int32(9) # try COLAMD and AMD; pick best# - -# Let [m n] = size of the matrix after pruning singletons. The default -# ordering strategy is to use COLAMD if m <= 2*n. Otherwise, AMD(A'A) is -# tried. If there is a high fill-in with AMD then try METIS(A'A) and take -# the best of AMD and METIS. METIS is not tried if it isn't installed. - -# tol options -const DEFAULT_TOL = Int32(-2) # if tol <= -2, the default tol is used -const NO_TOL = Int32(-1) # if -2 < tol < 0, then no tol is used - -# for qmult, method can be 0,1,2,3: -const QTX = Int32(0) -const QX = Int32(1) -const XQT = Int32(2) -const XQ = Int32(3) - -# system can be 0,1,2,3: Given Q*R=A*E from SuiteSparseQR_factorize: -const RX_EQUALS_B = Int32(0) # solve R*X=B or X = R\B -const RETX_EQUALS_B = Int32(1) # solve R*E'*X=B or X = E*(R\B) -const RTX_EQUALS_B = Int32(2) # solve R'*X=B or X = R'\B -const RTX_EQUALS_ETB = Int32(3) # solve R'*X=E'*B or X = R'\(E'*B) - - -using ..SparseArrays: SparseMatrixCSC -using ..SparseArrays.CHOLMOD: C_Dense, C_Sparse, Dense, ITypes, Sparse, SuiteSparseStruct, VTypes, common - -import Base: size -import Base.LinAlg: qrfact -import ..SparseArrays.CHOLMOD: convert, free! - -struct C_Factorization{Tv<:VTypes} <: SuiteSparseStruct - xtype::Cint - factors::Ptr{Tv} -end - -mutable struct Factorization{Tv<:VTypes} <: Base.LinAlg.Factorization{Tv} - m::Int - n::Int - p::Ptr{C_Factorization{Tv}} - function Factorization{Tv}(m::Integer, n::Integer, p::Ptr{C_Factorization{Tv}}) where Tv<:VTypes - if p == C_NULL - throw(ArgumentError("factorization failed for unknown reasons. Please submit a bug report.")) - end - new(m, n, p) - end -end -Factorization(m::Integer, n::Integer, p::Ptr{C_Factorization{Tv}}) where Tv<:VTypes = Factorization{Tv}(m, n, p) - -size(F::Factorization) = (F.m, F.n) -function size(F::Factorization, i::Integer) - if i < 1 - throw(ArgumentError("dimension must be positive")) - end - if i == 1 - return F.m - elseif i == 2 - return F.n - end - return 1 -end - -function free!(F::Factorization{Tv}) where Tv<:VTypes - ccall((:SuiteSparseQR_C_free, :libspqr), Cint, - (Ptr{Ptr{C_Factorization{Tv}}}, Ptr{Void}), - &F.p, common()) == 1 -end - -function backslash(ordering::Integer, tol::Real, A::Sparse{Tv}, B::Dense{Tv}) where Tv<:VTypes - m, n = size(A) - if m != size(B, 1) - throw(DimensionMismatch("left hand side and right hand side must have same number of rows")) - end - d = Dense(ccall((:SuiteSparseQR_C_backslash, :libspqr), Ptr{C_Dense{Tv}}, - (Cint, Cdouble, Ptr{C_Sparse{Tv}}, Ptr{C_Dense{Tv}}, Ptr{Void}), - ordering, tol, get(A.p), get(B.p), common())) - finalizer(d, free!) - d -end - -function factorize(ordering::Integer, tol::Real, A::Sparse{Tv}) where Tv<:VTypes - s = unsafe_load(A.p) - if s.stype != 0 - throw(ArgumentError("stype must be zero")) - end - f = Factorization(size(A)..., ccall((:SuiteSparseQR_C_factorize, :libspqr), Ptr{C_Factorization{Tv}}, - (Cint, Cdouble, Ptr{Sparse{Tv}}, Ptr{Void}), - ordering, tol, get(A.p), common())) - finalizer(f, free!) - f -end - -function solve(system::Integer, QR::Factorization{Tv}, B::Dense{Tv}) where Tv<:VTypes - m, n = size(QR) - mB = size(B, 1) - if (system == RX_EQUALS_B || system == RETX_EQUALS_B) && m != mB - throw(DimensionMismatch("number of rows in factorized matrix must equal number of rows in right hand side")) - elseif (system == RTX_EQUALS_ETB || system == RTX_EQUALS_B) && n != mB - throw(DimensionMismatch("number of columns in factorized matrix must equal number of rows in right hand side")) - end - d = Dense(ccall((:SuiteSparseQR_C_solve, :libspqr), Ptr{C_Dense{Tv}}, - (Cint, Ptr{C_Factorization{Tv}}, Ptr{C_Dense{Tv}}, Ptr{Void}), - system, get(QR.p), get(B.p), common())) - finalizer(d, free!) - d -end - -function qmult(method::Integer, QR::Factorization{Tv}, X::Dense{Tv}) where Tv<:VTypes - mQR, nQR = size(QR) - mX, nX = size(X) - if (method == QTX || method == QX) && mQR != mX - throw(DimensionMismatch("Q matrix size $mQR and dense matrix has $mX rows")) - elseif (method == XQT || method == XQ) && mQR != nX - throw(DimensionMismatch("Q matrix size $mQR and dense matrix has $nX columns")) - end - d = Dense(ccall((:SuiteSparseQR_C_qmult, :libspqr), Ptr{C_Dense{Tv}}, - (Cint, Ptr{C_Factorization{Tv}}, Ptr{C_Dense{Tv}}, Ptr{Void}), - method, get(QR.p), get(X.p), common())) - finalizer(d, free!) - d -end - - -qrfact(A::SparseMatrixCSC, ::Type{Val{true}}) = factorize(ORDERING_DEFAULT, DEFAULT_TOL, Sparse(A, 0)) - -""" - qrfact(A) -> SPQR.Factorization - -Compute the `QR` factorization of a sparse matrix `A`. A fill-reducing permutation is used. -The main application of this type is to solve least squares problems with [`\\`](@ref). The function -calls the C library SPQR and a few additional functions from the library are wrapped but not -exported. -""" -qrfact(A::SparseMatrixCSC) = qrfact(A, Val{true}) - -# With a real lhs and complex rhs with the same precision, we can reinterpret -# the complex rhs as a real rhs with twice the number of columns -# -# This definition is similar to the definition in factorization.jl except that -# here we have to use \ instead of A_ldiv_B! because of limitations in SPQR - -## Two helper methods -_ret_size(F::Factorization, b::AbstractVector) = (size(F, 2),) -_ret_size(F::Factorization, B::AbstractMatrix) = (size(F, 2), size(B, 2)) - -function (\)(F::Factorization{Float64}, B::VecOrMat{Complex{Float64}}) -# |z1|z3| reinterpret |x1|x2|x3|x4| transpose |x1|y1| reshape |x1|y1|x3|y3| -# |z2|z4| -> |y1|y2|y3|y4| -> |x2|y2| -> |x2|y2|x4|y4| -# |x3|y3| -# |x4|y4| - c2r = reshape(transpose(reinterpret(Float64, B, (2, length(B)))), size(B, 1), 2*size(B, 2)) - x = F\c2r - -# |z1|z3| reinterpret |x1|x2|x3|x4| transpose |x1|y1| reshape |x1|y1|x3|y3| -# |z2|z4| <- |y1|y2|y3|y4| <- |x2|y2| <- |x2|y2|x4|y4| -# |x3|y3| -# |x4|y4| - return reinterpret(Complex{Float64}, transpose(reshape(x, (length(x) >> 1), 2)), _ret_size(F, B)) -end - -function (\)(F::Factorization{T}, B::StridedVecOrMat{T}) where T<:VTypes - QtB = qmult(QTX, F, Dense(B)) - convert(typeof(B), solve(RETX_EQUALS_B, F, QtB)) -end - -(\)(F::Factorization, B::StridedVecOrMat) = F\convert(AbstractArray{eltype(F)}, B) - -end # module diff --git a/julia-0.6.3/share/julia/base/sparse/umfpack.jl b/julia-0.6.3/share/julia/base/sparse/umfpack.jl deleted file mode 100644 index 4c9159f..0000000 --- a/julia-0.6.3/share/julia/base/sparse/umfpack.jl +++ /dev/null @@ -1,522 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -module UMFPACK - -export UmfpackLU - -import Base: (\), Ac_ldiv_B, At_ldiv_B, findnz, getindex, show, size -import Base.LinAlg: A_ldiv_B!, Ac_ldiv_B!, At_ldiv_B!, Factorization, det, lufact - -importall ..SparseArrays -import ..SparseArrays: increment, increment!, decrement, decrement!, nnz - -include("umfpack_h.jl") -mutable struct MatrixIllConditionedException <: Exception - message::AbstractString -end - -function umferror(status::Integer) - if status==UMFPACK_OK - return - elseif status==UMFPACK_WARNING_singular_matrix - throw(LinAlg.SingularException(0)) - elseif status==UMFPACK_WARNING_determinant_underflow - throw(MatrixIllConditionedException("the determinant is nonzero but underflowed")) - elseif status==UMFPACK_WARNING_determinant_overflow - throw(MatrixIllConditionedException("the determinant overflowed")) - elseif status==UMFPACK_ERROR_out_of_memory - throw(OutOfMemoryError()) - elseif status==UMFPACK_ERROR_invalid_Numeric_object - throw(ArgumentError("invalid UMFPack numeric object")) - elseif status==UMFPACK_ERROR_invalid_Symbolic_object - throw(ArgumentError("invalid UMFPack symbolic object")) - elseif status==UMFPACK_ERROR_argument_missing - throw(ArgumentError("a required argument to UMFPack is missing")) - elseif status==UMFPACK_ERROR_n_nonpositive - throw(ArgumentError("the number of rows or columns of the matrix must be greater than zero")) - elseif status==UMFPACK_ERROR_invalid_matrix - throw(ArgumentError("invalid matrix")) - elseif status==UMFPACK_ERROR_different_pattern - throw(ArgumentError("pattern of the matrix changed")) - elseif status==UMFPACK_ERROR_invalid_system - throw(ArgumentError("invalid sys argument provided to UMFPack solver")) - elseif status==UMFPACK_ERROR_invalid_permutation - throw(ArgumentError("invalid permutation")) - elseif status==UMFPACK_ERROR_file_IO - throw(ErrorException("error saving / loading UMFPack decomposition")) - elseif status==UMFPACK_ERROR_ordering_failed - throw(ErrorException("the ordering method failed")) - elseif status==UMFPACK_ERROR_internal_error - throw(ErrorException("an internal error has occurred, of unknown cause")) - else - throw(ErrorException("unknown UMFPack error code: $status")) - end -end - -macro isok(A) - :(umferror($(esc(A)))) -end - -# check the size of SuiteSparse_long -if Int(ccall((:jl_cholmod_sizeof_long,:libsuitesparse_wrapper),Csize_t,())) == 4 - const UmfpackIndexTypes = (:Int32,) - const UMFITypes = Int32 -else - const UmfpackIndexTypes = (:Int32, :Int64) - const UMFITypes = Union{Int32, Int64} -end - -const UMFVTypes = Union{Float64,Complex128} - -## UMFPACK - -# the control and info arrays -const umf_ctrl = Vector{Float64}(UMFPACK_CONTROL) -ccall((:umfpack_dl_defaults,:libumfpack), Void, (Ptr{Float64},), umf_ctrl) -const umf_info = Vector{Float64}(UMFPACK_INFO) - -function show_umf_ctrl(level::Real = 2.0) - old_prt::Float64 = umf_ctrl[1] - umf_ctrl[1] = Float64(level) - ccall((:umfpack_dl_report_control, :libumfpack), Void, (Ptr{Float64},), umf_ctrl) - umf_ctrl[1] = old_prt -end - -function show_umf_info(level::Real = 2.0) - old_prt::Float64 = umf_ctrl[1] - umf_ctrl[1] = Float64(level) - ccall((:umfpack_dl_report_info, :libumfpack), Void, - (Ptr{Float64}, Ptr{Float64}), umf_ctrl, umf_info) - umf_ctrl[1] = old_prt -end - -## Should this type be immutable? -mutable struct UmfpackLU{Tv<:UMFVTypes,Ti<:UMFITypes} <: Factorization{Tv} - symbolic::Ptr{Void} - numeric::Ptr{Void} - m::Int - n::Int - colptr::Vector{Ti} # 0-based column pointers - rowval::Vector{Ti} # 0-based row indices - nzval::Vector{Tv} -end - -""" - lufact(A::SparseMatrixCSC) -> F::UmfpackLU - -Compute the LU factorization of a sparse matrix `A`. - -For sparse `A` with real or complex element type, the return type of `F` is -`UmfpackLU{Tv, Ti}`, with `Tv` = [`Float64`](@ref) or `Complex128` respectively and -`Ti` is an integer type ([`Int32`](@ref) or [`Int64`](@ref)). - -The individual components of the factorization `F` can be accessed by indexing: - -| Component | Description | -|:----------|:------------------------------------| -| `F[:L]` | `L` (lower triangular) part of `LU` | -| `F[:U]` | `U` (upper triangular) part of `LU` | -| `F[:p]` | right permutation `Vector` | -| `F[:q]` | left permutation `Vector` | -| `F[:Rs]` | `Vector` of scaling factors | -| `F[:(:)]` | `(L,U,p,q,Rs)` components | - -The relation between `F` and `A` is - -`F[:L]*F[:U] == (F[:Rs] .* A)[F[:p], F[:q]]` - -`F` further supports the following functions: - -- [`\\`](@ref) -- [`cond`](@ref) -- [`det`](@ref) - -!!! note - `lufact(A::SparseMatrixCSC)` uses the UMFPACK library that is part of - SuiteSparse. As this library only supports sparse matrices with [`Float64`](@ref) or - `Complex128` elements, `lufact` converts `A` into a copy that is of type - `SparseMatrixCSC{Float64}` or `SparseMatrixCSC{Complex128}` as appropriate. -""" -function lufact(S::SparseMatrixCSC{<:UMFVTypes,<:UMFITypes}) - zerobased = S.colptr[1] == 0 - res = UmfpackLU(C_NULL, C_NULL, S.m, S.n, - zerobased ? copy(S.colptr) : decrement(S.colptr), - zerobased ? copy(S.rowval) : decrement(S.rowval), - copy(S.nzval)) - finalizer(res, umfpack_free_symbolic) - umfpack_numeric!(res) -end -lufact{Ti<:UMFITypes}(A::SparseMatrixCSC{<:Union{Float16,Float32},Ti}) = - lufact(convert(SparseMatrixCSC{Float64,Ti}, A)) -lufact{Ti<:UMFITypes}(A::SparseMatrixCSC{<:Union{Complex32,Complex64},Ti}) = - lufact(convert(SparseMatrixCSC{Complex128,Ti}, A)) -lufact{T<:AbstractFloat}(A::Union{SparseMatrixCSC{T},SparseMatrixCSC{Complex{T}}}) = - throw(ArgumentError(string("matrix type ", typeof(A), "not supported. ", - "Try lufact(convert(SparseMatrixCSC{Float64/Complex128,Int}, A)) for ", - "sparse floating point LU using UMFPACK or lufact(Array(A)) for generic ", - "dense LU."))) -lufact(A::SparseMatrixCSC) = lufact(float(A)) - - -size(F::UmfpackLU) = (F.m, F.n) -function size(F::UmfpackLU, dim::Integer) - if dim < 1 - throw(ArgumentError("size: dimension $dim out of range")) - elseif dim == 1 - return Int(F.m) - elseif dim == 2 - return Int(F.n) - else - return 1 - end -end - -function show(io::IO, F::UmfpackLU) - println(io, "UMFPACK LU Factorization of a $(size(F)) sparse matrix") - F.numeric != C_NULL && println(io, F.numeric) -end - -## Wrappers for UMFPACK functions - -# generate the name of the C function according to the value and integer types -umf_nm(nm,Tv,Ti) = "umfpack_" * (Tv == :Float64 ? "d" : "z") * (Ti == :Int64 ? "l_" : "i_") * nm - -for itype in UmfpackIndexTypes - sym_r = umf_nm("symbolic", :Float64, itype) - sym_c = umf_nm("symbolic", :Complex128, itype) - num_r = umf_nm("numeric", :Float64, itype) - num_c = umf_nm("numeric", :Complex128, itype) - sol_r = umf_nm("solve", :Float64, itype) - sol_c = umf_nm("solve", :Complex128, itype) - det_r = umf_nm("get_determinant", :Float64, itype) - det_z = umf_nm("get_determinant", :Complex128, itype) - lunz_r = umf_nm("get_lunz", :Float64, itype) - lunz_z = umf_nm("get_lunz", :Complex128, itype) - get_num_r = umf_nm("get_numeric", :Float64, itype) - get_num_z = umf_nm("get_numeric", :Complex128, itype) - @eval begin - function umfpack_symbolic!(U::UmfpackLU{Float64,$itype}) - if U.symbolic != C_NULL return U end - tmp = Vector{Ptr{Void}}(1) - @isok ccall(($sym_r, :libumfpack), $itype, - ($itype, $itype, Ptr{$itype}, Ptr{$itype}, Ptr{Float64}, Ptr{Void}, - Ptr{Float64}, Ptr{Float64}), - U.m, U.n, U.colptr, U.rowval, U.nzval, tmp, - umf_ctrl, umf_info) - U.symbolic = tmp[1] - return U - end - function umfpack_symbolic!(U::UmfpackLU{Complex128,$itype}) - if U.symbolic != C_NULL return U end - tmp = Vector{Ptr{Void}}(1) - @isok ccall(($sym_c, :libumfpack), $itype, - ($itype, $itype, Ptr{$itype}, Ptr{$itype}, Ptr{Float64}, Ptr{Float64}, Ptr{Void}, - Ptr{Float64}, Ptr{Float64}), - U.m, U.n, U.colptr, U.rowval, real(U.nzval), imag(U.nzval), tmp, - umf_ctrl, umf_info) - U.symbolic = tmp[1] - return U - end - function umfpack_numeric!(U::UmfpackLU{Float64,$itype}) - if U.numeric != C_NULL return U end - if U.symbolic == C_NULL umfpack_symbolic!(U) end - tmp = Vector{Ptr{Void}}(1) - status = ccall(($num_r, :libumfpack), $itype, - (Ptr{$itype}, Ptr{$itype}, Ptr{Float64}, Ptr{Void}, Ptr{Void}, - Ptr{Float64}, Ptr{Float64}), - U.colptr, U.rowval, U.nzval, U.symbolic, tmp, - umf_ctrl, umf_info) - if status != UMFPACK_WARNING_singular_matrix - umferror(status) - end - U.numeric = tmp[1] - return U - end - function umfpack_numeric!(U::UmfpackLU{Complex128,$itype}) - if U.numeric != C_NULL return U end - if U.symbolic == C_NULL umfpack_symbolic!(U) end - tmp = Vector{Ptr{Void}}(1) - status = ccall(($num_c, :libumfpack), $itype, - (Ptr{$itype}, Ptr{$itype}, Ptr{Float64}, Ptr{Float64}, Ptr{Void}, Ptr{Void}, - Ptr{Float64}, Ptr{Float64}), - U.colptr, U.rowval, real(U.nzval), imag(U.nzval), U.symbolic, tmp, - umf_ctrl, umf_info) - if status != UMFPACK_WARNING_singular_matrix - umferror(status) - end - U.numeric = tmp[1] - return U - end - function solve!(x::StridedVector{Float64}, lu::UmfpackLU{Float64,$itype}, b::StridedVector{Float64}, typ::Integer) - if x === b - throw(ArgumentError("output array must not be aliased with input array")) - end - if stride(x, 1) != 1 || stride(b, 1) != 1 - throw(ArgumentError("in and output vectors must have unit strides")) - end - umfpack_numeric!(lu) - (size(b,1) == lu.m) && (size(b) == size(x)) || throw(DimensionMismatch()) - @isok ccall(($sol_r, :libumfpack), $itype, - ($itype, Ptr{$itype}, Ptr{$itype}, Ptr{Float64}, - Ptr{Float64}, Ptr{Float64}, Ptr{Void}, Ptr{Float64}, - Ptr{Float64}), - typ, lu.colptr, lu.rowval, lu.nzval, - x, b, lu.numeric, umf_ctrl, - umf_info) - return x - end - function solve!(x::StridedVector{Complex128}, lu::UmfpackLU{Complex128,$itype}, b::StridedVector{Complex128}, typ::Integer) - if x === b - throw(ArgumentError("output array must not be aliased with input array")) - end - if stride(x, 1) != 1 || stride(b, 1) != 1 - throw(ArgumentError("in and output vectors must have unit strides")) - end - umfpack_numeric!(lu) - (size(b, 1) == lu.m) && (size(b) == size(x)) || throw(DimensionMismatch()) - n = size(b, 1) - @isok ccall(($sol_c, :libumfpack), $itype, - ($itype, Ptr{$itype}, Ptr{$itype}, Ptr{Float64}, - Ptr{Float64}, Ptr{Float64}, Ptr{Float64}, Ptr{Float64}, - Ptr{Float64}, Ptr{Void}, Ptr{Float64}, Ptr{Float64}), - typ, lu.colptr, lu.rowval, lu.nzval, - C_NULL, x, C_NULL, b, - C_NULL, lu.numeric, umf_ctrl, umf_info) - return x - end - function det(lu::UmfpackLU{Float64,$itype}) - mx = Ref{Float64}() - @isok ccall(($det_r,:libumfpack), $itype, - (Ptr{Float64},Ptr{Float64},Ptr{Void},Ptr{Float64}), - mx, C_NULL, lu.numeric, umf_info) - mx[] - end - function det(lu::UmfpackLU{Complex128,$itype}) - mx = Ref{Float64}() - mz = Ref{Float64}() - @isok ccall(($det_z,:libumfpack), $itype, - (Ptr{Float64},Ptr{Float64},Ptr{Float64},Ptr{Void},Ptr{Float64}), - mx, mz, C_NULL, lu.numeric, umf_info) - complex(mx[], mz[]) - end - function umf_lunz(lu::UmfpackLU{Float64,$itype}) - lnz = Ref{$itype}() - unz = Ref{$itype}() - n_row = Ref{$itype}() - n_col = Ref{$itype}() - nz_diag = Ref{$itype}() - @isok ccall(($lunz_r,:libumfpack), $itype, - (Ptr{$itype},Ptr{$itype},Ptr{$itype},Ptr{$itype},Ptr{$itype},Ptr{Void}), - lnz, unz, n_row, n_col, nz_diag, lu.numeric) - (lnz[], unz[], n_row[], n_col[], nz_diag[]) - end - function umf_lunz(lu::UmfpackLU{Complex128,$itype}) - lnz = Ref{$itype}() - unz = Ref{$itype}() - n_row = Ref{$itype}() - n_col = Ref{$itype}() - nz_diag = Ref{$itype}() - @isok ccall(($lunz_z,:libumfpack), $itype, - (Ptr{$itype},Ptr{$itype},Ptr{$itype},Ptr{$itype},Ptr{$itype},Ptr{Void}), - lnz, unz, n_row, n_col, nz_diag, lu.numeric) - (lnz[], unz[], n_row[], n_col[], nz_diag[]) - end - function umf_extract(lu::UmfpackLU{Float64,$itype}) - umfpack_numeric!(lu) # ensure the numeric decomposition exists - (lnz, unz, n_row, n_col, nz_diag) = umf_lunz(lu) - Lp = Vector{$itype}(n_row + 1) - Lj = Vector{$itype}(lnz) # L is returned in CSR (compressed sparse row) format - Lx = Vector{Float64}(lnz) - Up = Vector{$itype}(n_col + 1) - Ui = Vector{$itype}(unz) - Ux = Vector{Float64}(unz) - P = Vector{$itype}(n_row) - Q = Vector{$itype}(n_col) - Rs = Vector{Float64}(n_row) - @isok ccall(($get_num_r,:libumfpack), $itype, - (Ptr{$itype},Ptr{$itype},Ptr{Float64}, - Ptr{$itype},Ptr{$itype},Ptr{Float64}, - Ptr{$itype},Ptr{$itype},Ptr{Void}, - Ptr{$itype},Ptr{Float64},Ptr{Void}), - Lp,Lj,Lx, - Up,Ui,Ux, - P, Q, C_NULL, - &0, Rs, lu.numeric) - (transpose(SparseMatrixCSC(min(n_row, n_col), n_row, increment!(Lp), increment!(Lj), Lx)), - SparseMatrixCSC(min(n_row, n_col), n_col, increment!(Up), increment!(Ui), Ux), - increment!(P), increment!(Q), Rs) - end - function umf_extract(lu::UmfpackLU{Complex128,$itype}) - umfpack_numeric!(lu) # ensure the numeric decomposition exists - (lnz, unz, n_row, n_col, nz_diag) = umf_lunz(lu) - Lp = Vector{$itype}(n_row + 1) - Lj = Vector{$itype}(lnz) # L is returned in CSR (compressed sparse row) format - Lx = Vector{Float64}(lnz) - Lz = Vector{Float64}(lnz) - Up = Vector{$itype}(n_col + 1) - Ui = Vector{$itype}(unz) - Ux = Vector{Float64}(unz) - Uz = Vector{Float64}(unz) - P = Vector{$itype}(n_row) - Q = Vector{$itype}(n_col) - Rs = Vector{Float64}(n_row) - @isok ccall(($get_num_z,:libumfpack), $itype, - (Ptr{$itype},Ptr{$itype},Ptr{Float64},Ptr{Float64}, - Ptr{$itype},Ptr{$itype},Ptr{Float64},Ptr{Float64}, - Ptr{$itype},Ptr{$itype},Ptr{Void}, Ptr{Void}, - Ptr{$itype},Ptr{Float64},Ptr{Void}), - Lp,Lj,Lx,Lz, - Up,Ui,Ux,Uz, - P, Q, C_NULL, C_NULL, - &0, Rs, lu.numeric) - (transpose(SparseMatrixCSC(min(n_row, n_col), n_row, increment!(Lp), increment!(Lj), complex.(Lx, Lz))), - SparseMatrixCSC(min(n_row, n_col), n_col, increment!(Up), increment!(Ui), complex.(Ux, Uz)), - increment!(P), increment!(Q), Rs) - end - end -end - -function nnz(lu::UmfpackLU) - lnz, unz, = umf_lunz(lu) - return Int(lnz + unz) -end - -### Solve with Factorization -A_ldiv_B!{T<:UMFVTypes}(lu::UmfpackLU{T}, B::StridedVecOrMat{T}) = A_ldiv_B!(B, lu, copy(B)) -At_ldiv_B!{T<:UMFVTypes}(lu::UmfpackLU{T}, B::StridedVecOrMat{T}) = At_ldiv_B!(B, lu, copy(B)) -Ac_ldiv_B!{T<:UMFVTypes}(lu::UmfpackLU{T}, B::StridedVecOrMat{T}) = Ac_ldiv_B!(B, lu, copy(B)) -A_ldiv_B!(lu::UmfpackLU{Float64}, B::StridedVecOrMat{<:Complex}) = A_ldiv_B!(B, lu, copy(B)) -At_ldiv_B!(lu::UmfpackLU{Float64}, B::StridedVecOrMat{<:Complex}) = At_ldiv_B!(B, lu, copy(B)) -Ac_ldiv_B!(lu::UmfpackLU{Float64}, B::StridedVecOrMat{<:Complex}) = Ac_ldiv_B!(B, lu, copy(B)) - -A_ldiv_B!{T<:UMFVTypes}(X::StridedVecOrMat{T}, lu::UmfpackLU{T}, B::StridedVecOrMat{T}) = - _Aq_ldiv_B!(X, lu, B, UMFPACK_A) -At_ldiv_B!{T<:UMFVTypes}(X::StridedVecOrMat{T}, lu::UmfpackLU{T}, B::StridedVecOrMat{T}) = - _Aq_ldiv_B!(X, lu, B, UMFPACK_Aat) -Ac_ldiv_B!{T<:UMFVTypes}(X::StridedVecOrMat{T}, lu::UmfpackLU{T}, B::StridedVecOrMat{T}) = - _Aq_ldiv_B!(X, lu, B, UMFPACK_At) -A_ldiv_B!{Tb<:Complex}(X::StridedVecOrMat{Tb}, lu::UmfpackLU{Float64}, B::StridedVecOrMat{Tb}) = - _Aq_ldiv_B!(X, lu, B, UMFPACK_A) -At_ldiv_B!{Tb<:Complex}(X::StridedVecOrMat{Tb}, lu::UmfpackLU{Float64}, B::StridedVecOrMat{Tb}) = - _Aq_ldiv_B!(X, lu, B, UMFPACK_Aat) -Ac_ldiv_B!{Tb<:Complex}(X::StridedVecOrMat{Tb}, lu::UmfpackLU{Float64}, B::StridedVecOrMat{Tb}) = - _Aq_ldiv_B!(X, lu, B, UMFPACK_At) - -function _Aq_ldiv_B!(X::StridedVecOrMat, lu::UmfpackLU, B::StridedVecOrMat, transposeoptype) - if size(X, 2) != size(B, 2) - throw(DimensionMismatch("input and output arrays must have same number of columns")) - end - _AqldivB_kernel!(X, lu, B, transposeoptype) - return X -end -function _AqldivB_kernel!{T<:UMFVTypes}(x::StridedVector{T}, lu::UmfpackLU{T}, - b::StridedVector{T}, transposeoptype) - solve!(x, lu, b, transposeoptype) -end -function _AqldivB_kernel!{T<:UMFVTypes}(X::StridedMatrix{T}, lu::UmfpackLU{T}, - B::StridedMatrix{T}, transposeoptype) - for col in 1:size(X, 2) - solve!(view(X, :, col), lu, view(B, :, col), transposeoptype) - end -end -function _AqldivB_kernel!{Tb<:Complex}(x::StridedVector{Tb}, lu::UmfpackLU{Float64}, - b::StridedVector{Tb}, transposeoptype) - r, i = similar(b, Float64), similar(b, Float64) - solve!(r, lu, Vector{Float64}(real(b)), transposeoptype) - solve!(i, lu, Vector{Float64}(imag(b)), transposeoptype) - map!(complex, x, r, i) -end -function _AqldivB_kernel!{Tb<:Complex}(X::StridedMatrix{Tb}, lu::UmfpackLU{Float64}, - B::StridedMatrix{Tb}, transposeoptype) - r = similar(B, Float64, size(B, 1)) - i = similar(B, Float64, size(B, 1)) - for j in 1:size(B, 2) - solve!(r, lu, Vector{Float64}(real(view(B, :, j))), transposeoptype) - solve!(i, lu, Vector{Float64}(imag(view(B, :, j))), transposeoptype) - map!(complex, view(X, :, j), r, i) - end -end - - -function getindex(lu::UmfpackLU, d::Symbol) - L,U,p,q,Rs = umf_extract(lu) - if d == :L - return L - elseif d == :U - return U - elseif d == :p - return p - elseif d == :q - return q - elseif d == :Rs - return Rs - elseif d == :(:) - return (L,U,p,q,Rs) - else - throw(KeyError(d)) - end -end - -for Tv in (:Float64, :Complex128), Ti in UmfpackIndexTypes - f = Symbol(umf_nm("free_symbolic", Tv, Ti)) - @eval begin - function ($f)(symb::Ptr{Void}) - tmp = [symb] - ccall(($(string(f)), :libumfpack), Void, (Ptr{Void},), tmp) - end - - function umfpack_free_symbolic(lu::UmfpackLU{$Tv,$Ti}) - if lu.symbolic == C_NULL return lu end - umfpack_free_numeric(lu) - ($f)(lu.symbolic) - lu.symbolic = C_NULL - return lu - end - end - - f = Symbol(umf_nm("free_numeric", Tv, Ti)) - @eval begin - function ($f)(num::Ptr{Void}) - tmp = [num] - ccall(($(string(f)), :libumfpack), Void, (Ptr{Void},), tmp) - end - function umfpack_free_numeric(lu::UmfpackLU{$Tv,$Ti}) - if lu.numeric == C_NULL return lu end - ($f)(lu.numeric) - lu.numeric = C_NULL - return lu - end - end -end - -function umfpack_report_symbolic(symb::Ptr{Void}, level::Real) - old_prl::Float64 = umf_ctrl[UMFPACK_PRL] - umf_ctrl[UMFPACK_PRL] = Float64(level) - @isok ccall((:umfpack_dl_report_symbolic, :libumfpack), Int, - (Ptr{Void}, Ptr{Float64}), symb, umf_ctrl) - umf_ctrl[UMFPACK_PRL] = old_prl -end - -umfpack_report_symbolic(symb::Ptr{Void}) = umfpack_report_symbolic(symb, 4.) - -function umfpack_report_symbolic(lu::UmfpackLU, level::Real) - umfpack_report_symbolic(umfpack_symbolic!(lu).symbolic, level) -end - -umfpack_report_symbolic(lu::UmfpackLU) = umfpack_report_symbolic(lu.symbolic,4.) -function umfpack_report_numeric(num::Ptr{Void}, level::Real) - old_prl::Float64 = umf_ctrl[UMFPACK_PRL] - umf_ctrl[UMFPACK_PRL] = Float64(level) - @isok ccall((:umfpack_dl_report_numeric, :libumfpack), Int, - (Ptr{Void}, Ptr{Float64}), num, umf_ctrl) - umf_ctrl[UMFPACK_PRL] = old_prl -end - -umfpack_report_numeric(num::Ptr{Void}) = umfpack_report_numeric(num, 4.) -function umfpack_report_numeric(lu::UmfpackLU, level::Real) - umfpack_report_numeric(umfpack_numeric!(lu).numeric, level) -end - -umfpack_report_numeric(lu::UmfpackLU) = umfpack_report_numeric(lu,4.) - -end # UMFPACK module diff --git a/julia-0.6.3/share/julia/base/sparse/umfpack_h.jl b/julia-0.6.3/share/julia/base/sparse/umfpack_h.jl deleted file mode 100644 index ec3a7c5..0000000 --- a/julia-0.6.3/share/julia/base/sparse/umfpack_h.jl +++ /dev/null @@ -1,43 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -## UMFPACK - -## Type of solve -const UMFPACK_A = 0 # Ax=b -const UMFPACK_At = 1 # A'x=b -const UMFPACK_Aat = 2 # A.'x=b -const UMFPACK_Pt_L = 3 # P'Lx=b -const UMFPACK_L = 4 # Lx=b -const UMFPACK_Lt_P = 5 # L'Px=b -const UMFPACK_Lat_P = 6 # L.'Px=b -const UMFPACK_Lt = 7 # L'x=b -const UMFPACK_Lat = 8 # L.'x=b -const UMFPACK_U_Qt = 9 # UQ'x=b -const UMFPACK_U = 10 # Ux=b -const UMFPACK_Q_Ut = 11 # QU'x=b -const UMFPACK_Q_Uat = 12 # QU.'x=b -const UMFPACK_Ut = 13 # U'x=b -const UMFPACK_Uat = 14 # U.'x=b - -## Sizes of Control and Info arrays for returning information from solver -const UMFPACK_INFO = 90 -const UMFPACK_CONTROL = 20 -const UMFPACK_PRL = 1 - -## Status codes -const UMFPACK_OK = 0 -const UMFPACK_WARNING_singular_matrix = 1 -const UMFPACK_WARNING_determinant_underflow = 2 -const UMFPACK_WARNING_determinant_overflow = 3 -const UMFPACK_ERROR_out_of_memory = -1 -const UMFPACK_ERROR_invalid_Numeric_object = -3 -const UMFPACK_ERROR_invalid_Symbolic_object = -4 -const UMFPACK_ERROR_argument_missing = -5 -const UMFPACK_ERROR_n_nonpositive = -6 -const UMFPACK_ERROR_invalid_matrix = -8 -const UMFPACK_ERROR_different_pattern = -11 -const UMFPACK_ERROR_invalid_system = -13 -const UMFPACK_ERROR_invalid_permutation = -15 -const UMFPACK_ERROR_internal_error = -911 -const UMFPACK_ERROR_file_IO = -17 -const UMFPACK_ERROR_ordering_failed = -18 diff --git a/julia-0.6.3/share/julia/base/special/exp.jl b/julia-0.6.3/share/julia/base/special/exp.jl deleted file mode 100644 index ceafa4e..0000000 --- a/julia-0.6.3/share/julia/base/special/exp.jl +++ /dev/null @@ -1,134 +0,0 @@ -# Based on FreeBSD lib/msun/src/e_exp.c -# which is made available under the following licence - -## Copyright (C) 2004 by Sun Microsystems, Inc. All rights reserved. Permission -## to use, copy, modify, and distribute this software is freely granted, -## provided that this notice is preserved. - -# Method -# 1. Argument reduction: Reduce x to an r so that |r| <= 0.5*ln(2). Given x, -# find r and integer k such that -# x = k*ln(2) + r, |r| <= 0.5*ln(2). -# Here r is represented as r = hi - lo for better accuracy. -# -# 2. Approximate exp(r) by a special rational function on [0, 0.5*ln(2)]: -# R(r^2) = r*(exp(r)+1)/(exp(r)-1) = 2 + r*r/6 - r^4/360 + ... -# -# A special Remez algorithm on [0, 0.5*ln(2)] is used to generate a -# polynomial to approximate R. -# -# The computation of exp(r) thus becomes -# 2*r -# exp(r) = 1 + ---------- -# R(r) - r -# r*c(r) -# = 1 + r + ----------- (for better accuracy) -# 2 - c(r) -# where -# c(r) = r - (P1*r^2 + P2*r^4 + ... + P5*r^10 + ...). -# -# 3. Scale back: exp(x) = 2^k * exp(r) - -# log(2) -const LN2 = 6.931471805599453094172321214581765680755001343602552541206800094933936219696955e-01 -# log2(e) -const LOG2E = 1.442695040888963407359924681001892137426646 - -# log(2) into upper and lower -LN2U(::Type{Float64}) = 6.93147180369123816490e-1 -LN2U(::Type{Float32}) = 6.9313812256f-1 - -LN2L(::Type{Float64}) = 1.90821492927058770002e-10 -LN2L(::Type{Float32}) = 9.0580006145f-6 - -# max and min arguments for exponential fucntions -MAXEXP(::Type{Float64}) = 7.09782712893383996732e2 # log 2^1023*(2-2^-52) -MAXEXP(::Type{Float32}) = 88.72283905206835f0 # log 2^127 *(2-2^-23) - -# one less than the min exponent since we can sqeeze a bit more from the exp function -MINEXP(::Type{Float64}) = -7.451332191019412076235e2 # log 2^-1075 -MINEXP(::Type{Float32}) = -103.97207708f0 # log 2^-150 - -@inline exp_kernel(x::Float64) = @horner(x, 1.66666666666666019037e-1, - -2.77777777770155933842e-3, 6.61375632143793436117e-5, - -1.65339022054652515390e-6, 4.13813679705723846039e-8) - -@inline exp_kernel(x::Float32) = @horner(x, 1.6666625440f-1, -2.7667332906f-3) - -# for values smaller than this threshold just use a Taylor expansion -@eval exp_small_thres(::Type{Float64}) = $(2.0^-28) -@eval exp_small_thres(::Type{Float32}) = $(2.0f0^-13) - -""" - exp(x) - -Compute the natural base exponential of `x`, in other words ``e^x``. -""" -function exp(x::T) where T<:Union{Float32,Float64} - xa = reinterpret(Unsigned, x) & ~sign_mask(T) - xsb = signbit(x) - - # filter out non-finite arguments - if xa > reinterpret(Unsigned, MAXEXP(T)) - if xa >= exponent_mask(T) - xa & significand_mask(T) != 0 && return T(NaN) - return xsb ? T(0.0) : T(Inf) # exp(+-Inf) - end - x > MAXEXP(T) && return T(Inf) - x < MINEXP(T) && return T(0.0) - end - - # This implementation gives 2.7182818284590455 for exp(1.0) when T == - # Float64, which is well within the allowable error; however, - # 2.718281828459045 is closer to the true value so we prefer that answer, - # given that 1.0 is such an important argument value. - if x == T(1.0) && T == Float64 - return 2.718281828459045235360 - end - - if xa > reinterpret(Unsigned, T(0.5)*T(LN2)) # |x| > 0.5 log(2) - # argument reduction - if xa < reinterpret(Unsigned, T(1.5)*T(LN2)) # |x| < 1.5 log(2) - if xsb - k = -1 - hi = x + LN2U(T) - lo = -LN2L(T) - else - k = 1 - hi = x - LN2U(T) - lo = LN2L(T) - end - else - n = round(T(LOG2E)*x) - k = unsafe_trunc(Int,n) - hi = muladd(n, -LN2U(T), x) - lo = n*LN2L(T) - end - r = hi - lo - - # compute approximation on reduced argument - z = r*r - p = r - z*exp_kernel(z) - y = T(1.0) - ((lo - (r*p)/(T(2.0) - p)) - hi) - - # scale back - if k > -significand_bits(T) - # multiply by 2.0 first to prevent overflow, which helps extends the range - k == exponent_max(T) && return y * T(2.0) * T(2.0)^(exponent_max(T) - 1) - twopk = reinterpret(T, rem(exponent_bias(T) + k, fpinttype(T)) << significand_bits(T)) - return y*twopk - else - # add significand_bits(T) + 1 to lift the range outside the subnormals - twopk = reinterpret(T, rem(exponent_bias(T) + significand_bits(T) + 1 + k, fpinttype(T)) << significand_bits(T)) - return y * twopk * T(2.0)^(-significand_bits(T) - 1) - end - elseif xa < reinterpret(Unsigned, exp_small_thres(T)) # |x| < exp_small_thres - # Taylor approximation for small x - return T(1.0) + x - else - # primary range with k = 0, so compute approximation directly - z = x*x - p = x - z*exp_kernel(z) - return T(1.0) - ((x*p)/(p - T(2.0)) - x) - end -end diff --git a/julia-0.6.3/share/julia/base/special/gamma.jl b/julia-0.6.3/share/julia/base/special/gamma.jl deleted file mode 100644 index 7415200..0000000 --- a/julia-0.6.3/share/julia/base/special/gamma.jl +++ /dev/null @@ -1,157 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -gamma(x::Float64) = nan_dom_err(ccall((:tgamma,libm), Float64, (Float64,), x), x) -gamma(x::Float32) = nan_dom_err(ccall((:tgammaf,libm), Float32, (Float32,), x), x) - -""" - gamma(x) - -Compute the gamma function of `x`. -""" -gamma(x::Real) = gamma(float(x)) - -function lgamma_r(x::Float64) - signp = Ref{Int32}() - y = ccall((:lgamma_r,libm), Float64, (Float64, Ptr{Int32}), x, signp) - return y, signp[] -end -function lgamma_r(x::Float32) - signp = Ref{Int32}() - y = ccall((:lgammaf_r,libm), Float32, (Float32, Ptr{Int32}), x, signp) - return y, signp[] -end -lgamma_r(x::Real) = lgamma_r(float(x)) -lgamma_r(x::Number) = lgamma(x), 1 # lgamma does not take abs for non-real x -"`lgamma_r(x)`: return L,s such that `gamma(x) = s * exp(L)`" lgamma_r - -""" - lfact(x) - -Compute the logarithmic factorial of a nonnegative integer `x`. -Equivalent to [`lgamma`](@ref) of `x + 1`, but `lgamma` extends this function -to non-integer `x`. -""" -lfact(x::Integer) = x < 0 ? throw(DomainError()) : lgamma(x + oneunit(x)) - -""" - lgamma(x) - -Compute the logarithm of the absolute value of [`gamma`](@ref) for -[`Real`](@ref) `x`, while for [`Complex`](@ref) `x` compute the -principal branch cut of the logarithm of `gamma(x)` (defined for negative `real(x)` -by analytic continuation from positive `real(x)`). -""" -function lgamma end - -# asymptotic series for log(gamma(z)), valid for sufficiently large real(z) or |imag(z)| -@inline function lgamma_asymptotic(z::Complex{Float64}) - zinv = inv(z) - t = zinv*zinv - # coefficients are bernoulli[2:n+1] .// (2*(1:n).*(2*(1:n) - 1)) - return (z-0.5)*log(z) - z + 9.1893853320467274178032927e-01 + # <-- log(2pi)/2 - zinv*@evalpoly(t, 8.3333333333333333333333368e-02,-2.7777777777777777777777776e-03, - 7.9365079365079365079365075e-04,-5.9523809523809523809523806e-04, - 8.4175084175084175084175104e-04,-1.9175269175269175269175262e-03, - 6.4102564102564102564102561e-03,-2.9550653594771241830065352e-02) -end - -# Compute the logΓ(z) function using a combination of the asymptotic series, -# the Taylor series around z=1 and z=2, the reflection formula, and the shift formula. -# Many details of these techniques are discussed in D. E. G. Hare, -# "Computing the principal branch of log-Gamma," J. Algorithms 25, pp. 221-236 (1997), -# and similar techniques are used (in a somewhat different way) by the -# SciPy loggamma function. The key identities are also described -# at http://functions.wolfram.com/GammaBetaErf/LogGamma/ -function lgamma(z::Complex{Float64}) - x = real(z) - y = imag(z) - yabs = abs(y) - if !isfinite(x) || !isfinite(y) # Inf or NaN - if isinf(x) && isfinite(y) - return Complex(x, x > 0 ? (y == 0 ? y : copysign(Inf, y)) : copysign(Inf, -y)) - elseif isfinite(x) && isinf(y) - return Complex(-Inf, y) - else - return Complex(NaN, NaN) - end - elseif x > 7 || yabs > 7 # use the Stirling asymptotic series for sufficiently large x or |y| - return lgamma_asymptotic(z) - elseif x < 0.1 # use reflection formula to transform to x > 0 - if x == 0 && y == 0 # return Inf with the correct imaginary part for z == 0 - return Complex(Inf, signbit(x) ? copysign(oftype(x, pi), -y) : -y) - end - # the 2pi * floor(...) stuff is to choose the correct branch cut for log(sinpi(z)) - return Complex(1.1447298858494001741434262, # log(pi) - copysign(6.2831853071795864769252842, y) # 2pi - * floor(0.5*x+0.25)) - - log(sinpi(z)) - lgamma(1-z) - elseif abs(x - 1) + yabs < 0.1 - # taylor series around zero at z=1 - # ... coefficients are [-eulergamma; [(-1)^k * zeta(k)/k for k in 2:15]] - w = Complex(x - 1, y) - return w * @evalpoly(w, -5.7721566490153286060651188e-01,8.2246703342411321823620794e-01, - -4.0068563438653142846657956e-01,2.705808084277845478790009e-01, - -2.0738555102867398526627303e-01,1.6955717699740818995241986e-01, - -1.4404989676884611811997107e-01,1.2550966952474304242233559e-01, - -1.1133426586956469049087244e-01,1.000994575127818085337147e-01, - -9.0954017145829042232609344e-02,8.3353840546109004024886499e-02, - -7.6932516411352191472827157e-02,7.1432946295361336059232779e-02, - -6.6668705882420468032903454e-02) - elseif abs(x - 2) + yabs < 0.1 - # taylor series around zero at z=2 - # ... coefficients are [1-eulergamma; [(-1)^k * (zeta(k)-1)/k for k in 2:12]] - w = Complex(x - 2, y) - return w * @evalpoly(w, 4.2278433509846713939348812e-01,3.2246703342411321823620794e-01, - -6.7352301053198095133246196e-02,2.0580808427784547879000897e-02, - -7.3855510286739852662729527e-03,2.8905103307415232857531201e-03, - -1.1927539117032609771139825e-03,5.0966952474304242233558822e-04, - -2.2315475845357937976132853e-04,9.9457512781808533714662972e-05, - -4.4926236738133141700224489e-05,2.0507212775670691553131246e-05) - end - # use recurrence relation lgamma(z) = lgamma(z+1) - log(z) to shift to x > 7 for asymptotic series - shiftprod = Complex(x,yabs) - x += 1 - sb = false # == signbit(imag(shiftprod)) == signbit(yabs) - # To use log(product of shifts) rather than sum(logs of shifts), - # we need to keep track of the number of + to - sign flips in - # imag(shiftprod), as described in Hare (1997), proposition 2.2. - signflips = 0 - while x <= 7 - shiftprod *= Complex(x,yabs) - sb′ = signbit(imag(shiftprod)) - signflips += sb′ & (sb′ != sb) - sb = sb′ - x += 1 - end - shift = log(shiftprod) - if signbit(y) # if y is negative, conjugate the shift - shift = Complex(real(shift), signflips*-6.2831853071795864769252842 - imag(shift)) - else - shift = Complex(real(shift), imag(shift) + signflips*6.2831853071795864769252842) - end - return lgamma_asymptotic(Complex(x,y)) - shift -end -lgamma(z::Complex{T}) where {T<:Union{Integer,Rational}} = lgamma(float(z)) -lgamma(z::Complex{T}) where {T<:Union{Float32,Float16}} = Complex{T}(lgamma(Complex{Float64}(z))) - -gamma(z::Complex) = exp(lgamma(z)) - -""" - beta(x, y) - -Euler integral of the first kind ``\\operatorname{B}(x,y) = \\Gamma(x)\\Gamma(y)/\\Gamma(x+y)``. -""" -function beta(x::Number, w::Number) - yx, sx = lgamma_r(x) - yw, sw = lgamma_r(w) - yxw, sxw = lgamma_r(x+w) - return exp(yx + yw - yxw) * (sx*sw*sxw) -end - -""" - lbeta(x, y) - -Natural logarithm of the absolute value of the [`beta`](@ref) -function ``\\log(|\\operatorname{B}(x,y)|)``. -""" -lbeta(x::Number, w::Number) = lgamma(x)+lgamma(w)-lgamma(x+w) diff --git a/julia-0.6.3/share/julia/base/special/log.jl b/julia-0.6.3/share/julia/base/special/log.jl deleted file mode 100644 index d317101..0000000 --- a/julia-0.6.3/share/julia/base/special/log.jl +++ /dev/null @@ -1,397 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -# Implementation of -# "Table-driven Implementation of the Logarithm Function in IEEE Floating-point Arithmetic" -# Tang, Ping-Tak Peter -# ACM Trans. Math. Softw. (1990), 16(4):378--400 -# http://dx.doi.org/10.1145/98267.98294 - -# Does not currently handle floating point flags (inexact, div-by-zero, etc). - -import Base.unsafe_trunc -import Base.Math.@horner - -# Float64 lookup table. -# to generate values: - # N=39 # (can be up to N=42). - # sN = 2.0^N - # isN = 1.0/sN - # s7 = 2.0^7 - # is7 = 1.0/s7 - # for j=0:128 - # l_big = Base.log(big(1.0+j*is7)) - # l_hi = isN*Float64(round(sN*l_big)) - # l_lo = Float64(l_big-l_hi) - # j % 2 == 0 && print("\n ") - # print("(",l_hi,",",l_lo,"),") - # end - -const t_log_Float64 = [(0.0,0.0),(0.007782140442941454,-8.865052917267247e-13), - (0.015504186536418274,-4.530198941364935e-13),(0.0231670592820592,-5.248209479295644e-13), - (0.03077165866670839,4.529814257790929e-14),(0.0383188643027097,-5.730994833076631e-13), - (0.04580953603181115,-5.16945692881222e-13),(0.053244514518155484,6.567993368985218e-13), - (0.06062462181580486,6.299848199383311e-13),(0.06795066190898069,-4.729424109166329e-13), - (0.07522342123775161,-1.6408301585598662e-13),(0.08244366921098845,8.614512936087814e-14), - (0.08961215869021544,-5.283050530808144e-13),(0.09672962645890948,-3.5836667430094137e-13), - (0.10379679368088546,7.581073923016376e-13),(0.11081436634049169,-2.0157368416016215e-13), - (0.11778303565552051,8.629474042969438e-13),(0.1247034785010328,-7.556920687451337e-14), - (0.1315763577895268,-8.075373495358435e-13),(0.13840232285838283,7.363043577087051e-13), - (0.14518200984457508,-7.718001336828099e-14),(0.15191604202664166,-7.996871607743758e-13), - (0.15860503017574956,8.890223439724663e-13),(0.16524957289584563,-5.384682618788232e-13), - (0.17185025692742784,-7.686134224018169e-13),(0.17840765747314435,-3.2605717931058157e-13), - (0.18492233849428885,-2.7685884310448306e-13),(0.1913948530000198,-3.903387893794952e-13), - (0.1978257433293038,6.160755775588723e-13),(0.20421554142922105,-5.30156516006026e-13), - (0.21056476910780475,-4.55112422774782e-13),(0.21687393830143264,-8.182853292737783e-13), - (0.22314355131493357,-7.238189921749681e-13),(0.22937410106533207,-4.86240001538379e-13), - (0.23556607131286,-9.30945949519689e-14),(0.24171993688651128,6.338907368997553e-13), - (0.24783616390413954,4.4171755371315547e-13),(0.25391520998164196,-6.785208495970588e-13), - (0.25995752443668607,2.3999540484211735e-13),(0.2659635484978935,-7.555569400283742e-13), - (0.27193371548310097,5.407904186145515e-13),(0.2778684510030871,3.692037508208009e-13), - (0.28376817313073843,-9.3834172236637e-14),(0.28963329258294834,9.43339818951269e-14), - (0.29546421289342106,4.148131870425857e-13),(0.3012613305781997,-3.7923164802093147e-14), - (0.3070250352957373,-8.25463138725004e-13),(0.31275571000333,5.668653582900739e-13), - (0.318453731119007,-4.723727821986367e-13),(0.32411946865431673,-1.0475750058776541e-13), - (0.32975328637257917,-1.1118671389559323e-13),(0.33535554192167183,-5.339989292003297e-13), - (0.3409265869704541,1.3912841212197566e-13),(0.3464667673470103,-8.017372713972018e-13), - (0.35197642315688427,2.9391859187648e-13),(0.3574558889213222,4.815896111723205e-13), - (0.3629054936900502,-6.817539406325327e-13),(0.36832556115950865,-8.009990055432491e-13), - (0.3737164097929053,6.787566823158706e-13),(0.37907835293481185,1.5761203773969435e-13), - (0.3844116989112081,-8.760375990774874e-13),(0.38971675114044046,-4.152515806343612e-13), - (0.3949938082405424,3.2655698896907146e-13),(0.40024316412745975,-4.4704265010452445e-13), - (0.4054651081078191,3.452764795203977e-13),(0.4106599249844294,8.390050778518307e-13), - (0.4158278951435932,1.1776978751369214e-13),(0.4209692946442374,-1.0774341461609579e-13), - (0.42608439531068143,2.186334329321591e-13),(0.43117346481813,2.413263949133313e-13), - (0.4362367667745275,3.90574622098307e-13),(0.44127456080423144,6.437879097373207e-13), - (0.44628710262804816,3.713514191959202e-13),(0.45127464413963025,-1.7166921336082432e-13), - (0.4562374334818742,-2.8658285157914353e-13),(0.4611757151214988,6.713692791384601e-13), - (0.46608972992544295,-8.437281040871276e-13),(0.4709797152190731,-2.821014384618127e-13), - (0.4758459048698569,1.0701931762114255e-13),(0.4806885293455707,1.8119346366441111e-13), - (0.4855078157816024,9.840465278232627e-14),(0.49030398804461583,5.780031989454028e-13), - (0.49507726679803454,-1.8302857356041668e-13),(0.4998278695566114,-1.620740015674495e-13), - (0.5045560107519123,4.83033149495532e-13),(0.5092619017905236,-7.156055317238212e-13), - (0.5139457511013461,8.882123951857185e-13),(0.5186077642083546,-3.0900580513238243e-13), - (0.5232481437651586,-6.10765519728515e-13),(0.5278670896204858,3.565996966334783e-13), - (0.532464798869114,3.5782396591276384e-13),(0.5370414658973459,-4.622608700154458e-13), - (0.5415972824321216,6.227976291722515e-13),(0.5461324375974073,7.283894727206574e-13), - (0.5506471179523942,2.680964661521167e-13),(0.5551415075406112,-1.0960825046059278e-13), - (0.5596157879353996,2.3119493838005378e-14),(0.5640701382853877,-5.846905800529924e-13), - (0.5685047353526897,-2.1037482511444942e-14),(0.5729197535620187,-2.332318294558741e-13), - (0.5773153650352469,-4.2333694288141915e-13),(0.5816917396350618,-4.3933937969737843e-13), - (0.5860490450031648,4.1341647073835564e-13),(0.590387446602108,6.841763641591467e-14), - (0.5947071077462169,4.758553400443064e-13),(0.5990081896452466,8.367967867475769e-13), - (0.6032908514389419,-8.576373464665864e-13),(0.6075552502243227,2.1913281229340092e-13), - (0.6118015411066153,-6.224284253643115e-13),(0.6160298772156239,-1.098359432543843e-13), - (0.6202404097512044,6.531043137763365e-13),(0.6244332880123693,-4.758019902171077e-13), - (0.6286086594227527,-3.785425126545704e-13),(0.6327666695706284,4.0939233218678666e-13), - (0.636907462236195,8.742438391485829e-13),(0.6410311794206791,2.521818845684288e-13), - (0.6451379613736208,-3.6081313604225574e-14),(0.649227946625615,-5.05185559242809e-13), - (0.6533012720119586,7.869940332335532e-13),(0.6573580727090302,-6.702087696194906e-13), - (0.6613984822452039,1.6108575753932459e-13),(0.6654226325445052,5.852718843625151e-13), - (0.6694306539429817,-3.5246757297904794e-13),(0.6734226752123504,-1.8372084495629058e-13), - (0.6773988235909201,8.860668981349492e-13),(0.6813592248072382,6.64862680714687e-13), - (0.6853040030982811,6.383161517064652e-13),(0.6892332812385575,2.5144230728376075e-13), - (0.6931471805601177,-1.7239444525614835e-13)] - - -# Float32 lookup table -# to generate values: - # N=16 - # sN = 2f0^N - # isN = 1f0/sN - # s7 = 2.0^7 - # is7 = 1.0/s7 - # for j=0:128 - # j % 4 == 0 && print("\n ") - # print(float64(Base.log(big(1.0+j*is7))),",") - # end - -const t_log_Float32 = [0.0,0.007782140442054949,0.015504186535965254,0.02316705928153438, - 0.030771658666753687,0.0383188643021366,0.0458095360312942,0.053244514518812285, - 0.06062462181643484,0.06795066190850775,0.07522342123758753,0.08244366921107459, - 0.08961215868968714,0.09672962645855111,0.10379679368164356,0.11081436634029011, - 0.11778303565638346,0.12470347850095724,0.13157635778871926,0.13840232285911913, - 0.1451820098444979,0.15191604202584197,0.15860503017663857,0.16524957289530717, - 0.17185025692665923,0.1784076574728183,0.184922338494012,0.19139485299962947, - 0.19782574332991987,0.2042155414286909,0.21056476910734964,0.21687393830061436, - 0.22314355131420976,0.22937410106484582,0.2355660713127669,0.24171993688714516, - 0.24783616390458127,0.25391520998096345,0.25995752443692605,0.26596354849713794, - 0.27193371548364176,0.2778684510034563,0.2837681731306446,0.28963329258304266, - 0.2954642128938359,0.3012613305781618,0.3070250352949119,0.3127557100038969, - 0.3184537311185346,0.324119468654212,0.329753286372468,0.3353555419211378, - 0.3409265869705932,0.34646676734620857,0.3519764231571782,0.3574558889218038, - 0.3629054936893685,0.3683255611587076,0.37371640979358406,0.37907835293496944, - 0.38441169891033206,0.3897167511400252,0.394993808240869,0.4002431641270127, - 0.4054651081081644,0.4106599249852684,0.415827895143711,0.42096929464412963, - 0.4260843953109001,0.4311734648183713,0.43623676677491807,0.4412745608048752, - 0.44628710262841953,0.45127464413945856,0.4562374334815876,0.46117571512217015, - 0.46608972992459924,0.470979715218791,0.4758459048699639,0.4806885293457519, - 0.4855078157817008,0.4903039880451938,0.4950772667978515,0.4998278695564493, - 0.5045560107523953,0.5092619017898079,0.5139457511022343,0.5186077642080457, - 0.5232481437645479,0.5278670896208424,0.5324647988694718,0.5370414658968836, - 0.5415972824327444,0.5461324375981357,0.5506471179526623,0.5551415075405016, - 0.5596157879354227,0.564070138284803,0.5685047353526688,0.5729197535617855, - 0.5773153650348236,0.5816917396346225,0.5860490450035782,0.5903874466021763, - 0.5947071077466928,0.5990081896460834,0.6032908514380843,0.6075552502245418, - 0.6118015411059929,0.616029877215514,0.6202404097518576,0.6244332880118935, - 0.6286086594223741,0.6327666695710378,0.6369074622370692,0.6410311794209312, - 0.6451379613735847,0.6492279466251099,0.6533012720127457,0.65735807270836, - 0.661398482245365,0.6654226325450905,0.6694306539426292,0.6734226752121667, - 0.6773988235918061,0.6813592248079031,0.6853040030989194,0.689233281238809, - 0.6931471805599453] - -# determine if hardware FMA is available -# should probably check with LLVM, see #9855. -const FMA_NATIVE = muladd(nextfloat(1.0),nextfloat(1.0),-nextfloat(1.0,2)) == -4.930380657631324e-32 - -# truncate lower order bits (up to 26) -# ideally, this should be able to use ANDPD instructions, see #9868. -@inline function truncbits(x::Float64) - reinterpret(Float64, reinterpret(UInt64,x) & 0xffff_ffff_f800_0000) -end - - -# Procedure 1 -@inline function log_proc1(y::Float64,mf::Float64,F::Float64,f::Float64,jp::Int) - ## Steps 1 and 2 - @inbounds hi,lo = t_log_Float64[jp] - l_hi = mf* 0.6931471805601177 + hi - l_lo = mf*-1.7239444525614835e-13 + lo - - ## Step 3 - # @inbounds u = f*c_invF[jp] - # u = f/F - # q = u*u*@horner(u, - # -0x1.0_0000_0000_0001p-1, - # +0x1.5_5555_5550_9ba5p-2, - # -0x1.f_ffff_ffeb_6526p-3, - # +0x1.9_99b4_dfed_6fe4p-3, - # -0x1.5_5576_6647_2e04p-3) - - ## Step 3' (alternative) - u = (2.0f)/(y+F) - v = u*u - q = u*v*@horner(v, - 0.08333333333303913, - 0.012500053168098584) - - ## Step 4 - l_hi + (u + (q + l_lo)) -end - -# Procedure 2 -@inline function log_proc2(f::Float64) - ## Step 1 - g = 1.0/(2.0+f) - u = 2.0*f*g - v = u*u - - ## Step 2 - q = u*v*@horner(v, - 0.08333333333333179, - 0.012500000003771751, - 0.0022321399879194482, - 0.0004348877777076146) - - ## Step 3 - # based on: - # 2(f-u) = 2(f(2+f)-2f)/(2+f) = 2f^2/(2+f) = fu - # 2(f-u1-u2) - f*(u1+u2) = 0 - # 2(f-u1) - f*u1 = (2+f)u2 - # u2 = (2(f-u1) - f*u1)/(2+f) - if FMA_NATIVE - return u + fma(fma(-u,f,2(f-u)), g, q) - else - u1 = truncbits(u) # round to 24 bits - f1 = truncbits(f) - f2 = f-f1 - u2 = ((2.0*(f-u1)-u1*f1)-u1*f2)*g - ## Step 4 - return u1 + (u2 + q) - end -end - - -@inline function log_proc1(y::Float32,mf::Float32,F::Float32,f::Float32,jp::Int) - ## Steps 1 and 2 - @inbounds hi = t_log_Float32[jp] - l = mf*0.6931471805599453 + hi - - ## Step 3 - # @inbounds u = f*c_invF[jp] - # q = u*u*@horner(u, - # Float32(-0x1.00006p-1), - # Float32(0x1.55546cp-2)) - - ## Step 3' (alternative) - u = (2f0f)/(y+F) - v = u*u - q = u*v*0.08333351f0 - - ## Step 4 - Float32(l + (u + q)) -end - -@inline function log_proc2(f::Float32) - ## Step 1 - # compute in higher precision - u64 = Float64(2f0*f)/(2.0+f) - u = Float32(u64) - v = u*u - - ## Step 2 - q = u*v*@horner(v, - 0.08333332f0, - 0.012512346f0) - - ## Step 3: not required - - ## Step 4 - Float32(u64 + q) -end - - -function log(x::Float64) - if x > 0.0 - x == Inf && return x - - # Step 2 - if 0.9394130628134757 < x < 1.0644944589178595 - f = x-1.0 - return log_proc2(f) - end - - # Step 3 - xu = reinterpret(UInt64,x) - m = Int(xu >> 52) & 0x07ff - if m == 0 # x is subnormal - x *= 1.8014398509481984e16 # 0x1p54, normalise significand - xu = reinterpret(UInt64,x) - m = Int(xu >> 52) & 0x07ff - 54 - end - m -= 1023 - y = reinterpret(Float64,(xu & 0x000f_ffff_ffff_ffff) | 0x3ff0_0000_0000_0000) - - mf = Float64(m) - F = (y + 3.5184372088832e13) - 3.5184372088832e13 # 0x1p-7*round(0x1p7*y) - f = y-F - jp = unsafe_trunc(Int,128.0*F)-127 - - return log_proc1(y,mf,F,f,jp) - elseif x == 0.0 - -Inf - elseif isnan(x) - NaN - else - throw(DomainError()) - end -end - -function log(x::Float32) - if x > 0f0 - x == Inf32 && return x - - # Step 2 - if 0.939413f0 < x < 1.0644945f0 - f = x-1f0 - return log_proc2(f) - end - - # Step 3 - xu = reinterpret(UInt32,x) - m = Int(xu >> 23) & 0x00ff - if m == 0 # x is subnormal - x *= 3.3554432f7 # 0x1p25, normalise significand - xu = reinterpret(UInt32,x) - m = Int(xu >> 23) & 0x00ff - 25 - end - m -= 127 - y = reinterpret(Float32,(xu & 0x007f_ffff) | 0x3f80_0000) - - mf = Float32(m) - F = (y + 65536.0f0) - 65536.0f0 # 0x1p-7*round(0x1p7*y) - f = y-F - jp = unsafe_trunc(Int,128.0f0*F)-127 - - log_proc1(y,mf,F,f,jp) - elseif x == 0f0 - -Inf32 - elseif isnan(x) - NaN32 - else - throw(DomainError()) - end -end - - -function log1p(x::Float64) - if x > -1.0 - x == Inf && return x - if -1.1102230246251565e-16 < x < 1.1102230246251565e-16 - return x # Inexact - - # Step 2 - elseif -0.06058693718652422 < x < 0.06449445891785943 - return log_proc2(x) - end - - # Step 3 - z = 1.0 + x - zu = reinterpret(UInt64,z) - s = reinterpret(Float64,0x7fe0_0000_0000_0000 - (zu & 0xfff0_0000_0000_0000)) # 2^-m - m = Int(zu >> 52) & 0x07ff - 1023 # z cannot be subnormal - c = m > 0 ? 1.0-(z-x) : x-(z-1.0) # 1+x = z+c exactly - y = reinterpret(Float64,(zu & 0x000f_ffff_ffff_ffff) | 0x3ff0_0000_0000_0000) - - mf = Float64(m) - F = (y + 3.5184372088832e13) - 3.5184372088832e13 # 0x1p-7*round(0x1p7*y) - f = (y - F) + c*s #2^m(F+f) = 1+x = z+c - jp = unsafe_trunc(Int,128.0*F)-127 - - log_proc1(y,mf,F,f,jp) - elseif x == -1.0 - -Inf - elseif isnan(x) - NaN - else - throw(DomainError()) - end -end - -function log1p(x::Float32) - if x > -1f0 - x == Inf32 && return x - if -5.9604645f-8 < x < 5.9604645f-8 - return x # Inexact - # Step 2 - elseif -0.06058694f0 < x < 0.06449446f0 - return log_proc2(x) - end - - # Step 3 - z = 1f0 + x - zu = reinterpret(UInt32,z) - s = reinterpret(Float32,0x7f000000 - (zu & 0xff80_0000)) # 2^-m - m = Int(zu >> 23) & 0x00ff - 127 # z cannot be subnormal - c = m > 0 ? 1f0-(z-x) : x-(z-1f0) # 1+x = z+c - y = reinterpret(Float32,(zu & 0x007f_ffff) | 0x3f80_0000) - - mf = Float32(m) - F = (y + 65536.0f0) - 65536.0f0 # 0x1p-7*round(0x1p7*y) - f = (y - F) + s*c #2^m(F+f) = 1+x = z+c - jp = unsafe_trunc(Int,128.0*F)-127 - - log_proc1(y,mf,F,f,jp) - elseif x == -1f0 - -Inf32 - elseif isnan(x) - NaN32 - else - throw(DomainError()) - end -end - -for f in (:log,:log1p) - @eval begin - ($f)(x::Real) = ($f)(float(x)) - end -end diff --git a/julia-0.6.3/share/julia/base/special/trig.jl b/julia-0.6.3/share/julia/base/special/trig.jl deleted file mode 100644 index e7c342a..0000000 --- a/julia-0.6.3/share/julia/base/special/trig.jl +++ /dev/null @@ -1,428 +0,0 @@ -# This file is a part of Julia. Except for the *_kernel functions (see below), -# license is MIT: https://julialang.org/license - -struct DoubleFloat64 - hi::Float64 - lo::Float64 -end -struct DoubleFloat32 - hi::Float64 -end - -# *_kernel functions are only valid for |x| < pi/4 = 0.7854 -# translated from openlibm code: k_sin.c, k_cos.c, k_sinf.c, k_cosf.c -# which are made available under the following licence: - -## Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. -## -## Developed at SunPro, a Sun Microsystems, Inc. business. -## Permission to use, copy, modify, and distribute this -## software is freely granted, provided that this notice -## is preserved. - -function sin_kernel(x::DoubleFloat64) - S1 = -1.66666666666666324348e-01 - S2 = 8.33333333332248946124e-03 - S3 = -1.98412698298579493134e-04 - S4 = 2.75573137070700676789e-06 - S5 = -2.50507602534068634195e-08 - S6 = 1.58969099521155010221e-10 - - z = x.hi*x.hi - w = z*z - r = S2+z*(S3+z*S4) + z*w*(S5+z*S6) - v = z*x.hi - x.hi-((z*(0.5*x.lo-v*r)-x.lo)-v*S1) -end - -function cos_kernel(x::DoubleFloat64) - C1 = 4.16666666666666019037e-02 - C2 = -1.38888888888741095749e-03 - C3 = 2.48015872894767294178e-05 - C4 = -2.75573143513906633035e-07 - C5 = 2.08757232129817482790e-09 - C6 = -1.13596475577881948265e-11 - - z = x.hi*x.hi - w = z*z - r = z*(C1+z*(C2+z*C3)) + w*w*(C4+z*(C5+z*C6)) - hz = 0.5*z - w = 1.0-hz - w + (((1.0-w)-hz) + (z*r-x.hi*x.lo)) -end - -function sin_kernel(x::DoubleFloat32) - S1 = -0.16666666641626524 - S2 = 0.008333329385889463 - S3 = -0.00019839334836096632 - S4 = 2.718311493989822e-6 - - z = x.hi*x.hi - w = z*z - r = S3+z*S4 - s = z*x.hi - Float32((x.hi + s*(S1+z*S2)) + s*w*r) -end - -function cos_kernel(x::DoubleFloat32) - C0 = -0.499999997251031 - C1 = 0.04166662332373906 - C2 = -0.001388676377460993 - C3 = 2.439044879627741e-5 - - z = x.hi*x.hi - w = z*z - r = C2+z*C3 - Float32(((1.0+z*C0) + w*C1) + (w*z)*r) -end - -# fallback methods -sin_kernel(x::Real) = sin(x) -cos_kernel(x::Real) = cos(x) - -# multiply in extended precision -function mulpi_ext(x::Float64) - m = 3.141592653589793 - m_hi = 3.1415926218032837 - m_lo = 3.178650954705639e-8 - - x_hi = reinterpret(Float64, reinterpret(UInt64,x) & 0xffff_ffff_f800_0000) - x_lo = x-x_hi - - y_hi = m*x - y_lo = x_hi * m_lo + (x_lo* m_hi + ((x_hi*m_hi-y_hi) + x_lo*m_lo)) - - DoubleFloat64(y_hi,y_lo) -end -mulpi_ext(x::Float32) = DoubleFloat32(pi*Float64(x)) -mulpi_ext(x::Rational) = mulpi_ext(float(x)) -mulpi_ext(x::Real) = pi*x # Fallback - -""" - sinpi(x) - -Compute ``\\sin(\\pi x)`` more accurately than `sin(pi*x)`, especially for large `x`. -""" -function sinpi(x::T) where T<:AbstractFloat - if !isfinite(x) - isnan(x) && return x - throw(DomainError()) - end - - ax = abs(x) - s = maxintfloat(T)/2 - ax >= s && return copysign(zero(T),x) # integer-valued - - # reduce to interval [-1,1] - # assumes RoundNearest rounding mode - t = 3*s - rx = x-((x+t)-t) # zeros may be incorrectly signed - arx = abs(rx) - - if (arx == 0) | (arx == 1) - copysign(zero(T),x) - elseif arx < 0.25 - sin_kernel(mulpi_ext(rx)) - elseif arx < 0.75 - y = mulpi_ext(T(0.5) - arx) - copysign(cos_kernel(y),rx) - else - y = mulpi_ext(copysign(one(T),rx) - rx) - sin_kernel(y) - end -end - -# Rationals and other Real types -function sinpi(x::T) where T<:Real - Tf = typeof(float(x)) - if !isfinite(x) - throw(DomainError()) - end - - # until we get an IEEE remainder function (#9283) - rx = rem(x,2) - if rx > 1 - rx -= 2 - elseif rx < -1 - rx += 2 - end - arx = abs(rx) - - if (arx == 0) | (arx == 1) - copysign(zero(Tf),x) - elseif arx < 0.25 - sin_kernel(mulpi_ext(rx)) - elseif arx < 0.75 - y = mulpi_ext(T(0.5) - arx) - copysign(cos_kernel(y),rx) - else - y = mulpi_ext(copysign(one(T),rx) - rx) - sin_kernel(y) - end -end - -""" - cospi(x) - -Compute ``\\cos(\\pi x)`` more accurately than `cos(pi*x)`, especially for large `x`. -""" -function cospi(x::T) where T<:AbstractFloat - if !isfinite(x) - isnan(x) && return x - throw(DomainError()) - end - - ax = abs(x) - s = maxintfloat(T) - ax >= s && return one(T) # even integer-valued - - # reduce to interval [-1,1], then [0,1] - # assumes RoundNearest rounding mode - rx = abs(ax-((ax+s)-s)) - - if rx <= 0.25 - cos_kernel(mulpi_ext(rx)) - elseif rx < 0.75 - y = mulpi_ext(T(0.5) - rx) - sin_kernel(y) - else - y = mulpi_ext(one(T) - rx) - -cos_kernel(y) - end -end - -# Rationals and other Real types -function cospi(x::T) where T<:Real - if !isfinite(x) - throw(DomainError()) - end - - ax = abs(x) - # until we get an IEEE remainder function (#9283) - rx = rem(ax,2) - if rx > 1 - rx = 2-rx - end - - if rx <= 0.25 - cos_kernel(mulpi_ext(rx)) - elseif rx < 0.75 - y = mulpi_ext(T(0.5) - rx) - sin_kernel(y) - else - y = mulpi_ext(one(T) - rx) - -cos_kernel(y) - end -end - -sinpi(x::Integer) = x >= 0 ? zero(float(x)) : -zero(float(x)) -cospi(x::Integer) = isodd(x) ? -one(float(x)) : one(float(x)) - -function sinpi(z::Complex{T}) where T - F = float(T) - zr, zi = reim(z) - if isinteger(zr) - # zr = ...,-2,-1,0,1,2,... - # sin(pi*zr) == ±0 - # cos(pi*zr) == ±1 - # cosh(pi*zi) > 0 - s = copysign(zero(F),zr) - c_pos = isa(zr,Integer) ? iseven(zr) : isinteger(zr/2) - sh = sinh(pi*zi) - Complex(s, c_pos ? sh : -sh) - elseif isinteger(2*zr) - # zr = ...,-1.5,-0.5,0.5,1.5,2.5,... - # sin(pi*zr) == ±1 - # cos(pi*zr) == +0 - # sign(sinh(pi*zi)) == sign(zi) - s_pos = isinteger((2*zr-1)/4) - ch = cosh(pi*zi) - Complex(s_pos ? ch : -ch, isnan(zi) ? zero(F) : copysign(zero(F),zi)) - elseif !isfinite(zr) - if zi == 0 || isinf(zi) - Complex(F(NaN), F(zi)) - else - Complex(F(NaN), F(NaN)) - end - else - pizi = pi*zi - Complex(sinpi(zr)*cosh(pizi), cospi(zr)*sinh(pizi)) - end -end - -function cospi(z::Complex{T}) where T - F = float(T) - zr, zi = reim(z) - if isinteger(zr) - # zr = ...,-2,-1,0,1,2,... - # sin(pi*zr) == ±0 - # cos(pi*zr) == ±1 - # sign(sinh(pi*zi)) == sign(zi) - # cosh(pi*zi) > 0 - s = copysign(zero(F),zr) - c_pos = isa(zr,Integer) ? iseven(zr) : isinteger(zr/2) - ch = cosh(pi*zi) - Complex(c_pos ? ch : -ch, isnan(zi) ? s : -flipsign(s,zi)) - elseif isinteger(2*zr) - # zr = ...,-1.5,-0.5,0.5,1.5,2.5,... - # sin(pi*zr) == ±1 - # cos(pi*zr) == +0 - # sign(sinh(pi*zi)) == sign(zi) - s_pos = isinteger((2*zr-1)/4) - sh = sinh(pi*zi) - Complex(zero(F), s_pos ? -sh : sh) - elseif !isfinite(zr) - if zi == 0 - Complex(F(NaN), isnan(zr) ? zero(F) : -flipsign(F(zi),zr)) - elseif isinf(zi) - Complex(F(Inf), F(NaN)) - else - Complex(F(NaN), F(NaN)) - end - else - pizi = pi*zi - Complex(cospi(zr)*cosh(pizi), -sinpi(zr)*sinh(pizi)) - end -end - -""" - sinc(x) - -Compute ``\\sin(\\pi x) / (\\pi x)`` if ``x \\neq 0``, and ``1`` if ``x = 0``. -""" -sinc(x::Number) = x==0 ? one(x) : oftype(x,sinpi(x)/(pi*x)) -sinc(x::Integer) = x==0 ? one(x) : zero(x) -sinc(x::Complex{T}) where {T<:Integer} = sinc(float(x)) -sinc(x::Real) = x==0 ? one(x) : isinf(x) ? zero(x) : sinpi(x)/(pi*x) - -""" - cosc(x) - -Compute ``\\cos(\\pi x) / x - \\sin(\\pi x) / (\\pi x^2)`` if ``x \\neq 0``, and ``0`` if -``x = 0``. This is the derivative of `sinc(x)`. -""" -cosc(x::Number) = x==0 ? zero(x) : oftype(x,(cospi(x)-sinpi(x)/(pi*x))/x) -cosc(x::Integer) = cosc(float(x)) -cosc(x::Complex{T}) where {T<:Integer} = cosc(float(x)) -cosc(x::Real) = x==0 || isinf(x) ? zero(x) : (cospi(x)-sinpi(x)/(pi*x))/x - -for (finv, f) in ((:sec, :cos), (:csc, :sin), (:cot, :tan), - (:sech, :cosh), (:csch, :sinh), (:coth, :tanh), - (:secd, :cosd), (:cscd, :sind), (:cotd, :tand)) - @eval begin - ($finv){T<:Number}(z::T) = one(T) / (($f)(z)) - end -end - -for (tfa, tfainv, hfa, hfainv, fn) in ((:asec, :acos, :asech, :acosh, "secant"), - (:acsc, :asin, :acsch, :asinh, "cosecant"), - (:acot, :atan, :acoth, :atanh, "cotangent")) - tname = string(tfa) - hname = string(hfa) - @eval begin - @doc """ - $($tname)(x) - Compute the inverse $($fn) of `x`, where the output is in radians. """ ($tfa){T<:Number}(y::T) = ($tfainv)(one(T) / y) - @doc """ - $($hname)(x) - Compute the inverse hyperbolic $($fn) of `x`. """ ($hfa){T<:Number}(y::T) = ($hfainv)(one(T) / y) - end -end - - -# multiply in extended precision -function deg2rad_ext(x::Float64) - m = 0.017453292519943295 - m_hi = 0.01745329238474369 - m_lo = 1.3519960527851425e-10 - - u = 134217729.0*x # 0x1p27 + 1 - x_hi = u-(u-x) - x_lo = x-x_hi - - y_hi = m*x - y_lo = x_hi * m_lo + (x_lo* m_hi + ((x_hi*m_hi-y_hi) + x_lo*m_lo)) - - DoubleFloat64(y_hi,y_lo) -end -deg2rad_ext(x::Float32) = DoubleFloat32(deg2rad(Float64(x))) -deg2rad_ext(x::Real) = deg2rad(x) # Fallback - -function sind(x::Real) - if isinf(x) - return throw(DomainError()) - elseif isnan(x) - return oftype(x,NaN) - end - - rx = copysign(float(rem(x,360)),x) - arx = abs(rx) - - if rx == zero(rx) - return rx - elseif arx < oftype(rx,45) - return sin_kernel(deg2rad_ext(rx)) - elseif arx <= oftype(rx,135) - y = deg2rad_ext(oftype(rx,90) - arx) - return copysign(cos_kernel(y),rx) - elseif arx == oftype(rx,180) - return copysign(zero(rx),rx) - elseif arx < oftype(rx,225) - y = deg2rad_ext((oftype(rx,180) - arx)*sign(rx)) - return sin_kernel(y) - elseif arx <= oftype(rx,315) - y = deg2rad_ext(oftype(rx,270) - arx) - return -copysign(cos_kernel(y),rx) - else - y = deg2rad_ext(rx - copysign(oftype(rx,360),rx)) - return sin_kernel(y) - end -end - -function cosd(x::Real) - if isinf(x) - return throw(DomainError()) - elseif isnan(x) - return oftype(x,NaN) - end - - rx = abs(float(rem(x,360))) - - if rx <= oftype(rx,45) - return cos_kernel(deg2rad_ext(rx)) - elseif rx < oftype(rx,135) - y = deg2rad_ext(oftype(rx,90) - rx) - return sin_kernel(y) - elseif rx <= oftype(rx,225) - y = deg2rad_ext(oftype(rx,180) - rx) - return -cos_kernel(y) - elseif rx < oftype(rx,315) - y = deg2rad_ext(rx - oftype(rx,270)) - return sin_kernel(y) - else - y = deg2rad_ext(oftype(rx,360) - rx) - return cos_kernel(y) - end -end - -tand(x::Real) = sind(x) / cosd(x) - -for (fd, f, fn) in ((:sind, :sin, "sine"), (:cosd, :cos, "cosine"), (:tand, :tan, "tangent")) - name = string(fd) - @eval begin - @doc """ - $($name)(x) - Compute $($fn) of `x`, where `x` is in degrees. """ ($fd)(z) = ($f)(deg2rad(z)) - end -end - -for (fd, f, fn) in ((:asind, :asin, "sine"), (:acosd, :acos, "cosine"), (:atand, :atan, "tangent"), - (:asecd, :asec, "secant"), (:acscd, :acsc, "cosecant"), (:acotd, :acot, "cotangent")) - name = string(fd) - @eval begin - @doc """ - $($name)(x) - - Compute the inverse $($fn) of `x`, where the output is in degrees. """ ($fd)(y) = rad2deg(($f)(y)) - end -end diff --git a/julia-0.6.3/share/julia/base/stacktraces.jl b/julia-0.6.3/share/julia/base/stacktraces.jl deleted file mode 100644 index 82a30cb..0000000 --- a/julia-0.6.3/share/julia/base/stacktraces.jl +++ /dev/null @@ -1,260 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -module StackTraces - - -import Base: hash, ==, show -import Base.Serializer: serialize, deserialize - -export StackTrace, StackFrame, stacktrace, catch_stacktrace - -""" - StackFrame - -Stack information representing execution context, with the following fields: - -- `func::Symbol` - - The name of the function containing the execution context. - -- `linfo::Nullable{Core.MethodInstance}` - - The MethodInstance containing the execution context (if it could be found). - -- `file::Symbol` - - The path to the file containing the execution context. - -- `line::Int` - - The line number in the file containing the execution context. - -- `from_c::Bool` - - True if the code is from C. - -- `inlined::Bool` - - True if the code is from an inlined frame. - -- `pointer::UInt64` - - Representation of the pointer to the execution context as returned by `backtrace`. - -""" -struct StackFrame # this type should be kept platform-agnostic so that profiles can be dumped on one machine and read on another - "the name of the function containing the execution context" - func::Symbol - "the path to the file containing the execution context" - file::Symbol - "the line number in the file containing the execution context" - line::Int - "the MethodInstance containing the execution context (if it could be found)" - linfo::Nullable{Core.MethodInstance} - "true if the code is from C" - from_c::Bool - "true if the code is from an inlined frame" - inlined::Bool - "representation of the pointer to the execution context as returned by `backtrace`" - pointer::UInt64 # Large enough to be read losslessly on 32- and 64-bit machines. -end - -StackFrame(func, file, line) = StackFrame(func, file, line, Nullable{Core.MethodInstance}(), false, false, 0) - -""" - StackTrace - -An alias for `Vector{StackFrame}` provided for convenience; returned by calls to -`stacktrace` and `catch_stacktrace`. -""" -const StackTrace = Vector{StackFrame} - -const empty_sym = Symbol("") -const UNKNOWN = StackFrame(empty_sym, empty_sym, -1, Nullable{Core.MethodInstance}(), true, false, 0) # === lookup(C_NULL) - - -#= -If the StackFrame has function and line information, we consider two of them the same if -they share the same function/line information. -=# -function ==(a::StackFrame, b::StackFrame) - a.line == b.line && a.from_c == b.from_c && a.func == b.func && a.file == b.file && a.inlined == b.inlined -end - -function hash(frame::StackFrame, h::UInt) - h += 0xf4fbda67fe20ce88 % UInt - h = hash(frame.line, h) - h = hash(frame.file, h) - h = hash(frame.func, h) - h = hash(frame.from_c, h) - h = hash(frame.inlined, h) -end - -# provide a custom serializer that skips attempting to serialize the `outer_linfo` -# which is likely to contain complex references, types, and module references -# that may not exist on the receiver end -function serialize(s::AbstractSerializer, frame::StackFrame) - Serializer.serialize_type(s, typeof(frame)) - serialize(s, frame.func) - serialize(s, frame.file) - write(s.io, frame.line) - write(s.io, frame.from_c) - write(s.io, frame.inlined) - write(s.io, frame.pointer) -end - -function deserialize(s::AbstractSerializer, ::Type{StackFrame}) - func = deserialize(s) - file = deserialize(s) - line = read(s.io, Int) - from_c = read(s.io, Bool) - inlined = read(s.io, Bool) - pointer = read(s.io, UInt64) - return StackFrame(func, file, line, Nullable{Core.MethodInstance}(), from_c, inlined, pointer) -end - - -""" - lookup(pointer::Union{Ptr{Void}, UInt}) -> Vector{StackFrame} - -Given a pointer to an execution context (usually generated by a call to `backtrace`), looks -up stack frame context information. Returns an array of frame information for all functions -inlined at that point, innermost function first. -""" -function lookup(pointer::Ptr{Void}) - infos = ccall(:jl_lookup_code_address, Any, (Ptr{Void}, Cint), pointer - 1, false) - isempty(infos) && return [StackFrame(empty_sym, empty_sym, -1, Nullable{Core.MethodInstance}(), true, false, convert(UInt64, pointer))] - res = Vector{StackFrame}(length(infos)) - for i in 1:length(infos) - info = infos[i] - @assert(length(info) == 7) - li = info[4] === nothing ? Nullable{Core.MethodInstance}() : Nullable{Core.MethodInstance}(info[4]) - res[i] = StackFrame(info[1], info[2], info[3], li, info[5], info[6], info[7]) - end - return res -end - -lookup(pointer::UInt) = lookup(convert(Ptr{Void}, pointer)) - -# allow lookup on already-looked-up data for easier handling of pre-processed frames -lookup(s::StackFrame) = StackFrame[s] -lookup(s::Tuple{StackFrame,Int}) = StackFrame[s[1]] - -""" - stacktrace([trace::Vector{Ptr{Void}},] [c_funcs::Bool=false]) -> StackTrace - -Returns a stack trace in the form of a vector of `StackFrame`s. (By default stacktrace -doesn't return C functions, but this can be enabled.) When called without specifying a -trace, `stacktrace` first calls `backtrace`. -""" -function stacktrace(trace::Vector{Ptr{Void}}, c_funcs::Bool=false) - stack = vcat(StackTrace(), map(lookup, trace)...)::StackTrace - - # Remove frames that come from C calls. - if !c_funcs - filter!(frame -> !frame.from_c, stack) - end - - # Remove frame for this function (and any functions called by this function). - remove_frames!(stack, :stacktrace) - - # is there a better way? the func symbol has a number suffix which changes. - # it's possible that no test is needed and we could just shift! all the time. - # this line was added to PR #16213 because otherwise stacktrace() != stacktrace(false). - # not sure why. possibly b/c of re-ordering of base/sysimg.jl - !isempty(stack) && startswith(string(stack[1].func),"jlcall_stacktrace") && shift!(stack) - stack -end - -stacktrace(c_funcs::Bool=false) = stacktrace(backtrace(), c_funcs) - -""" - catch_stacktrace([c_funcs::Bool=false]) -> StackTrace - -Returns the stack trace for the most recent error thrown, rather than the current execution -context. -""" -catch_stacktrace(c_funcs::Bool=false) = stacktrace(catch_backtrace(), c_funcs) - -""" - remove_frames!(stack::StackTrace, name::Symbol) - -Takes a `StackTrace` (a vector of `StackFrames`) and a function name (a `Symbol`) and -removes the `StackFrame` specified by the function name from the `StackTrace` (also removing -all frames above the specified function). Primarily used to remove `StackTraces` functions -from the `StackTrace` prior to returning it. -""" -function remove_frames!(stack::StackTrace, name::Symbol) - splice!(stack, 1:findlast(frame -> frame.func == name, stack)) - return stack -end - -function remove_frames!(stack::StackTrace, names::Vector{Symbol}) - splice!(stack, 1:findlast(frame -> frame.func in names, stack)) - return stack -end - -""" - remove_frames!(stack::StackTrace, m::Module) - -Returns the `StackTrace` with all `StackFrame`s from the provided `Module` removed. -""" -function remove_frames!(stack::StackTrace, m::Module) - filter!(f -> !from(f, m), stack) - return stack -end - -function show_spec_linfo(io::IO, frame::StackFrame) - if isnull(frame.linfo) - if frame.func === empty_sym - @printf(io, "ip:%#x", frame.pointer) - else - print_with_color(Base.have_color && get(io, :backtrace, false) ? Base.stackframe_function_color() : :nothing, io, string(frame.func)) - end - else - linfo = get(frame.linfo) - if isdefined(linfo, :def) - Base.show_tuple_as_call(io, linfo.def.name, linfo.specTypes) - else - Base.show(io, linfo) - end - end -end - -function show(io::IO, frame::StackFrame; full_path::Bool=false) - show_spec_linfo(io, frame) - if frame.file !== empty_sym - file_info = full_path ? string(frame.file) : basename(string(frame.file)) - print(io, " at ") - Base.with_output_color(Base.have_color && get(io, :backtrace, false) ? Base.stackframe_lineinfo_color() : :nothing, io) do io - print(io, file_info, ":") - if frame.line >= 0 - print(io, frame.line) - else - print(io, "?") - end - end - end - if frame.inlined - print(io, " [inlined]") - end -end - -""" - from(frame::StackFrame, filter_mod::Module) -> Bool - -Returns whether the `frame` is from the provided `Module` -""" -function from(frame::StackFrame, m::Module) - finfo = frame.linfo - result = false - - if !isnull(finfo) - frame_m = get(finfo).def.module - result = module_name(frame_m) === module_name(m) - end - - return result -end - -end diff --git a/julia-0.6.3/share/julia/base/stat.jl b/julia-0.6.3/share/julia/base/stat.jl deleted file mode 100644 index 0de651c..0000000 --- a/julia-0.6.3/share/julia/base/stat.jl +++ /dev/null @@ -1,314 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -# filesystem operations - -export - ctime, - filemode, - filesize, - gperm, - isblockdev, - ischardev, - isdir, - isfifo, - isfile, - islink, - ismount, - ispath, - issetgid, - issetuid, - issocket, - issticky, - lstat, - mtime, - operm, - stat, - uperm - -struct StatStruct - device :: UInt - inode :: UInt - mode :: UInt - nlink :: Int - uid :: UInt - gid :: UInt - rdev :: UInt - size :: Int64 - blksize :: Int64 - blocks :: Int64 - mtime :: Float64 - ctime :: Float64 -end - -StatStruct() = StatStruct(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) - -StatStruct(buf::Union{Vector{UInt8},Ptr{UInt8}}) = StatStruct( - ccall(:jl_stat_dev, UInt32, (Ptr{UInt8},), buf), - ccall(:jl_stat_ino, UInt32, (Ptr{UInt8},), buf), - ccall(:jl_stat_mode, UInt32, (Ptr{UInt8},), buf), - ccall(:jl_stat_nlink, UInt32, (Ptr{UInt8},), buf), - ccall(:jl_stat_uid, UInt32, (Ptr{UInt8},), buf), - ccall(:jl_stat_gid, UInt32, (Ptr{UInt8},), buf), - ccall(:jl_stat_rdev, UInt32, (Ptr{UInt8},), buf), - ccall(:jl_stat_size, UInt64, (Ptr{UInt8},), buf), - ccall(:jl_stat_blksize, UInt64, (Ptr{UInt8},), buf), - ccall(:jl_stat_blocks, UInt64, (Ptr{UInt8},), buf), - ccall(:jl_stat_mtime, Float64, (Ptr{UInt8},), buf), - ccall(:jl_stat_ctime, Float64, (Ptr{UInt8},), buf), -) - -show(io::IO, st::StatStruct) = print(io, "StatStruct(mode=0o$(oct(filemode(st),6)), size=$(filesize(st)))") - -# stat & lstat functions - -const stat_buf = Vector{UInt8}(ccall(:jl_sizeof_stat, Int32, ())) -macro stat_call(sym, arg1type, arg) - quote - fill!(stat_buf,0) - r = ccall($(Expr(:quote,sym)), Int32, ($arg1type, Ptr{UInt8}), $(esc(arg)), stat_buf) - r==0 || r==Base.UV_ENOENT || r==Base.UV_ENOTDIR || throw(UVError("stat",r)) - st = StatStruct(stat_buf) - if ispath(st) != (r==0) - error("stat returned zero type for a valid path") - end - st - end -end - -stat(fd::RawFD) = @stat_call jl_fstat Int32 fd.fd -stat(fd::Integer) = @stat_call jl_fstat Int32 fd -stat(path::AbstractString) = @stat_call jl_stat Cstring path -lstat(path::AbstractString) = @stat_call jl_lstat Cstring path - -""" - stat(file) - -Returns a structure whose fields contain information about the file. -The fields of the structure are: - -| Name | Description | -|:--------|:-------------------------------------------------------------------| -| size | The size (in bytes) of the file | -| device | ID of the device that contains the file | -| inode | The inode number of the file | -| mode | The protection mode of the file | -| nlink | The number of hard links to the file | -| uid | The user id of the owner of the file | -| gid | The group id of the file owner | -| rdev | If this file refers to a device, the ID of the device it refers to | -| blksize | The file-system preferred block size for the file | -| blocks | The number of such blocks allocated | -| mtime | Unix timestamp of when the file was last modified | -| ctime | Unix timestamp of when the file was created | - -""" -stat(path...) = stat(joinpath(path...)) - -""" - lstat(file) - -Like [`stat`](@ref), but for symbolic links gets the info for the link -itself rather than the file it refers to. -This function must be called on a file path rather than a file object or a file -descriptor. -""" -lstat(path...) = lstat(joinpath(path...)) - -# some convenience functions - -""" - filemode(file) - -Equivalent to `stat(file).mode` -""" -filemode(st::StatStruct) = st.mode - -""" - filesize(path...) - -Equivalent to `stat(file).size`. -""" -filesize(st::StatStruct) = st.size - -""" - mtime(file) - -Equivalent to `stat(file).mtime`. -""" - mtime(st::StatStruct) = st.mtime - -""" - ctime(file) - -Equivalent to `stat(file).ctime` -""" - ctime(st::StatStruct) = st.ctime - -# mode type predicates - -""" - ispath(path) -> Bool - -Returns `true` if `path` is a valid filesystem path, `false` otherwise. -""" - ispath(st::StatStruct) = filemode(st) & 0xf000 != 0x0000 - -""" - isfifo(path) -> Bool - -Returns `true` if `path` is a FIFO, `false` otherwise. -""" - isfifo(st::StatStruct) = filemode(st) & 0xf000 == 0x1000 - -""" - ischardev(path) -> Bool - -Returns `true` if `path` is a character device, `false` otherwise. -""" - ischardev(st::StatStruct) = filemode(st) & 0xf000 == 0x2000 - - """ - isdir(path) -> Bool - - Returns `true` if `path` is a directory, `false` otherwise. - """ - isdir(st::StatStruct) = filemode(st) & 0xf000 == 0x4000 - - """ - isblockdev(path) -> Bool - - Returns `true` if `path` is a block device, `false` otherwise. - """ -isblockdev(st::StatStruct) = filemode(st) & 0xf000 == 0x6000 - -""" - isfile(path) -> Bool - -Returns `true` if `path` is a regular file, `false` otherwise. -""" - isfile(st::StatStruct) = filemode(st) & 0xf000 == 0x8000 - -""" - islink(path) -> Bool - -Returns `true` if `path` is a symbolic link, `false` otherwise. -""" - islink(st::StatStruct) = filemode(st) & 0xf000 == 0xa000 - -""" - issocket(path) -> Bool - -Returns `true` if `path` is a socket, `false` otherwise. -""" - issocket(st::StatStruct) = filemode(st) & 0xf000 == 0xc000 - -# mode permission predicates - -""" - issetuid(path) -> Bool - -Returns `true` if `path` has the setuid flag set, `false` otherwise. -""" -issetuid(st::StatStruct) = (filemode(st) & 0o4000) > 0 - -""" - issetgid(path) -> Bool - -Returns `true` if `path` has the setgid flag set, `false` otherwise. -""" -issetgid(st::StatStruct) = (filemode(st) & 0o2000) > 0 - -""" - issticky(path) -> Bool - -Returns `true` if `path` has the sticky bit set, `false` otherwise. -""" -issticky(st::StatStruct) = (filemode(st) & 0o1000) > 0 - -""" - uperm(file) - -Gets the permissions of the owner of the file as a bitfield of - -| Value | Description | -|:------|:-------------------| -| 01 | Execute Permission | -| 02 | Write Permission | -| 04 | Read Permission | - -For allowed arguments, see [`stat`](@ref). -""" -uperm(st::StatStruct) = UInt8((filemode(st) >> 6) & 0x7) - -""" - gperm(file) - -Like [`uperm`](@ref) but gets the permissions of the group owning the file. -""" -gperm(st::StatStruct) = UInt8((filemode(st) >> 3) & 0x7) - -""" - operm(file) - -Like [`uperm`](@ref) but gets the permissions for people who neither own the file nor are a member of -the group owning the file -""" -operm(st::StatStruct) = UInt8((filemode(st) ) & 0x7) - -# mode predicate methods for file names - -for f in Symbol[ - :ispath - :isfifo - :ischardev - :isdir - :isblockdev - :isfile - :issocket - :issetuid - :issetgid - :issticky - :uperm - :gperm - :operm - :filemode - :filesize - :mtime - :ctime -] - @eval ($f)(path...) = ($f)(stat(path...)) -end - -islink(path...) = islink(lstat(path...)) - -# samefile can be used for files and directories: #11145#issuecomment-99511194 -samefile(a::StatStruct, b::StatStruct) = a.device==b.device && a.inode==b.inode -function samefile(a::AbstractString, b::AbstractString) - infoa = stat(a) - infob = stat(b) - if ispath(infoa) && ispath(infob) - samefile(infoa, infob) - else - return false - end -end - -""" - ismount(path) -> Bool - -Returns `true` if `path` is a mount point, `false` otherwise. -""" -function ismount(path...) - path = joinpath(path...) - isdir(path) || return false - s1 = lstat(path) - # Symbolic links cannot be mount points - islink(s1) && return false - parent_path = joinpath(path, "..") - s2 = lstat(parent_path) - # If a directory and its parent are on different devices, then the - # directory must be a mount point - (s1.device != s2.device) && return true - (s1.inode == s2.inode) && return true - false -end diff --git a/julia-0.6.3/share/julia/base/statistics.jl b/julia-0.6.3/share/julia/base/statistics.jl deleted file mode 100644 index 2b9969a..0000000 --- a/julia-0.6.3/share/julia/base/statistics.jl +++ /dev/null @@ -1,740 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -##### mean ##### - -""" - mean(f::Function, v) - -Apply the function `f` to each element of `v` and take the mean. - -```jldoctest -julia> mean(√, [1, 2, 3]) -1.3820881233139908 - -julia> mean([√1, √2, √3]) -1.3820881233139908 -``` -""" -function mean(f::Callable, iterable) - state = start(iterable) - if done(iterable, state) - throw(ArgumentError("mean of empty collection undefined: $(repr(iterable))")) - end - count = 1 - value, state = next(iterable, state) - f_value = f(value) - total = f_value + zero(f_value) - while !done(iterable, state) - value, state = next(iterable, state) - total += f(value) - count += 1 - end - return total/count -end -mean(iterable) = mean(identity, iterable) -mean(f::Callable, A::AbstractArray) = sum(f, A) / _length(A) -mean(A::AbstractArray) = sum(A) / _length(A) - -function mean!(R::AbstractArray, A::AbstractArray) - sum!(R, A; init=true) - scale!(R, _length(R) / _length(A)) - return R -end - -momenttype(::Type{T}) where {T} = typeof((zero(T)*zero(T) + zero(T)*zero(T)) / 2) -momenttype(::Type{Float32}) = Float32 -momenttype(::Type{<:Union{Float64,Int32,Int64,UInt32,UInt64}}) = Float64 - -""" - mean(v[, region]) - -Compute the mean of whole array `v`, or optionally along the dimensions in `region`. - -!!! note - Julia does not ignore `NaN` values in the computation. For applications requiring the - handling of missing data, the `DataArrays.jl` package is recommended. -""" -mean(A::AbstractArray{T}, region) where {T} = - mean!(reducedim_initarray(A, region, 0, momenttype(T)), A) - - -##### variances ##### - -# faster computation of real(conj(x)*y) -realXcY(x::Real, y::Real) = x*y -realXcY(x::Complex, y::Complex) = real(x)*real(y) + imag(x)*imag(y) - -function var(iterable; corrected::Bool=true, mean=nothing) - state = start(iterable) - if done(iterable, state) - throw(ArgumentError("variance of empty collection undefined: $(repr(iterable))")) - end - count = 1 - value, state = next(iterable, state) - if mean === nothing - # Use Welford algorithm as seen in (among other places) - # Knuth's TAOCP, Vol 2, page 232, 3rd edition. - M = value / 1 - S = real(zero(M)) - while !done(iterable, state) - value, state = next(iterable, state) - count += 1 - new_M = M + (value - M) / count - S = S + realXcY(value - M, value - new_M) - M = new_M - end - return S / (count - Int(corrected)) - elseif isa(mean, Number) # mean provided - # Cannot use a compensated version, e.g. the one from - # "Updating Formulae and a Pairwise Algorithm for Computing Sample Variances." - # by Chan, Golub, and LeVeque, Technical Report STAN-CS-79-773, - # Department of Computer Science, Stanford University, - # because user can provide mean value that is different to mean(iterable) - sum2 = abs2(value - mean::Number) - while !done(iterable, state) - value, state = next(iterable, state) - count += 1 - sum2 += abs2(value - mean) - end - return sum2 / (count - Int(corrected)) - else - throw(ArgumentError("invalid value of mean, $(mean)::$(typeof(mean))")) - end -end - -centralizedabs2fun(m::Number) = x -> abs2(x - m) -centralize_sumabs2(A::AbstractArray, m::Number) = - mapreduce(centralizedabs2fun(m), +, A) -centralize_sumabs2(A::AbstractArray, m::Number, ifirst::Int, ilast::Int) = - mapreduce_impl(centralizedabs2fun(m), +, A, ifirst, ilast) - -function centralize_sumabs2!(R::AbstractArray{S}, A::AbstractArray, means::AbstractArray) where S - # following the implementation of _mapreducedim! at base/reducedim.jl - lsiz = check_reducedims(R,A) - isempty(R) || fill!(R, zero(S)) - isempty(A) && return R - - if has_fast_linear_indexing(A) && lsiz > 16 - nslices = div(_length(A), lsiz) - ibase = first(linearindices(A))-1 - for i = 1:nslices - @inbounds R[i] = centralize_sumabs2(A, means[i], ibase+1, ibase+lsiz) - ibase += lsiz - end - return R - end - indsAt, indsRt = safe_tail(indices(A)), safe_tail(indices(R)) # handle d=1 manually - keep, Idefault = Broadcast.shapeindexer(indsAt, indsRt) - if reducedim1(R, A) - i1 = first(indices1(R)) - @inbounds for IA in CartesianRange(indsAt) - IR = Broadcast.newindex(IA, keep, Idefault) - r = R[i1,IR] - m = means[i1,IR] - @simd for i in indices(A, 1) - r += abs2(A[i,IA] - m) - end - R[i1,IR] = r - end - else - @inbounds for IA in CartesianRange(indsAt) - IR = Broadcast.newindex(IA, keep, Idefault) - @simd for i in indices(A, 1) - R[i,IR] += abs2(A[i,IA] - means[i,IR]) - end - end - end - return R -end - -function varm(A::AbstractArray{T}, m::Number; corrected::Bool=true) where T - n = _length(A) - n == 0 && return convert(real(momenttype(T)), NaN) - n == 1 && return convert(real(momenttype(T)), abs2(A[1] - m)/(1 - Int(corrected))) - return centralize_sumabs2(A, m) / (n - Int(corrected)) -end - -function varm!(R::AbstractArray{S}, A::AbstractArray, m::AbstractArray; corrected::Bool=true) where S - if isempty(A) - fill!(R, convert(S, NaN)) - else - rn = div(_length(A), _length(R)) - Int(corrected) - scale!(centralize_sumabs2!(R, A, m), convert(S, 1/rn)) - end - return R -end - -""" - varm(v, m[, region]; corrected::Bool=true) - -Compute the sample variance of a collection `v` with known mean(s) `m`, -optionally over `region`. `m` may contain means for each dimension of -`v`. If `corrected` is `true`, then the sum is scaled with `n-1`, -whereas the sum is scaled with `n` if `corrected` is `false` where `n = length(x)`. - -!!! note - Julia does not ignore `NaN` values in the computation. For - applications requiring the handling of missing data, the - `DataArrays.jl` package is recommended. -""" -varm(A::AbstractArray{T}, m::AbstractArray, region; corrected::Bool=true) where {T} = - varm!(reducedim_initarray(A, region, 0, real(momenttype(T))), A, m; corrected=corrected) - - -var(A::AbstractArray{T}; corrected::Bool=true, mean=nothing) where {T} = - convert(real(momenttype(T)), - varm(A, mean === nothing ? Base.mean(A) : mean; corrected=corrected)) - -""" - var(v[, region]; corrected::Bool=true, mean=nothing) - -Compute the sample variance of a vector or array `v`, optionally along dimensions in -`region`. The algorithm will return an estimator of the generative distribution's variance -under the assumption that each entry of `v` is an IID drawn from that generative -distribution. This computation is equivalent to calculating `sum(abs2, v - mean(v)) / -(length(v) - 1)`. If `corrected` is `true`, then the sum is scaled with `n-1`, -whereas the sum is scaled with `n` if `corrected` is `false` where `n = length(x)`. -The mean `mean` over the region may be provided. - -!!! note - Julia does not ignore `NaN` values in the computation. For - applications requiring the handling of missing data, the - `DataArrays.jl` package is recommended. -""" -var(A::AbstractArray, region; corrected::Bool=true, mean=nothing) = - varm(A, mean === nothing ? Base.mean(A, region) : mean, region; corrected=corrected) - -varm(iterable, m::Number; corrected::Bool=true) = - var(iterable, corrected=corrected, mean=m) - -## variances over ranges - -function varm(v::Range, m::Number) - f = first(v) - m - s = step(v) - l = length(v) - vv = f^2 * l / (l - 1) + f * s * l + s^2 * l * (2 * l - 1) / 6 - if l == 0 || l == 1 - return typeof(vv)(NaN) - end - return vv -end - -function var(v::Range) - s = step(v) - l = length(v) - vv = abs2(s) * (l + 1) * l / 12 - if l == 0 || l == 1 - return typeof(vv)(NaN) - end - return vv -end - - -##### standard deviation ##### - -function sqrt!(A::AbstractArray) - for i in eachindex(A) - @inbounds A[i] = sqrt(A[i]) - end - A -end - -stdm(A::AbstractArray, m::Number; corrected::Bool=true) = - sqrt(varm(A, m; corrected=corrected)) - -std(A::AbstractArray; corrected::Bool=true, mean=nothing) = - sqrt(var(A; corrected=corrected, mean=mean)) - -""" - std(v[, region]; corrected::Bool=true, mean=nothing) - -Compute the sample standard deviation of a vector or array `v`, optionally along dimensions -in `region`. The algorithm returns an estimator of the generative distribution's standard -deviation under the assumption that each entry of `v` is an IID drawn from that generative -distribution. This computation is equivalent to calculating `sqrt(sum((v - mean(v)).^2) / -(length(v) - 1))`. A pre-computed `mean` may be provided. If `corrected` is `true`, -then the sum is scaled with `n-1`, whereas the sum is scaled with `n` if `corrected` is -`false` where `n = length(x)`. - -!!! note - Julia does not ignore `NaN` values in the computation. For - applications requiring the handling of missing data, the - `DataArrays.jl` package is recommended. -""" -std(A::AbstractArray, region; corrected::Bool=true, mean=nothing) = - sqrt!(var(A, region; corrected=corrected, mean=mean)) - -std(iterable; corrected::Bool=true, mean=nothing) = - sqrt(var(iterable, corrected=corrected, mean=mean)) - -""" - stdm(v, m::Number; corrected::Bool=true) - -Compute the sample standard deviation of a vector `v` -with known mean `m`. If `corrected` is `true`, -then the sum is scaled with `n-1`, whereas the sum is -scaled with `n` if `corrected` is `false` where `n = length(x)`. - -!!! note - Julia does not ignore `NaN` values in the computation. For - applications requiring the handling of missing data, the - `DataArrays.jl` package is recommended. -""" -stdm(iterable, m::Number; corrected::Bool=true) = - std(iterable, corrected=corrected, mean=m) - - -###### covariance ###### - -# auxiliary functions - -_conj(x::AbstractArray{<:Real}) = x -_conj(x::AbstractArray) = conj(x) - -_getnobs(x::AbstractVector, vardim::Int) = _length(x) -_getnobs(x::AbstractMatrix, vardim::Int) = size(x, vardim) - -function _getnobs(x::AbstractVecOrMat, y::AbstractVecOrMat, vardim::Int) - n = _getnobs(x, vardim) - _getnobs(y, vardim) == n || throw(DimensionMismatch("dimensions of x and y mismatch")) - return n -end - -_vmean(x::AbstractVector, vardim::Int) = mean(x) -_vmean(x::AbstractMatrix, vardim::Int) = mean(x, vardim) - -# core functions - -unscaled_covzm(x::AbstractVector) = sum(abs2, x) -unscaled_covzm(x::AbstractMatrix, vardim::Int) = (vardim == 1 ? _conj(x'x) : x * x') - -unscaled_covzm(x::AbstractVector, y::AbstractVector) = dot(y, x) -unscaled_covzm(x::AbstractVector, y::AbstractMatrix, vardim::Int) = - (vardim == 1 ? At_mul_B(x, _conj(y)) : At_mul_Bt(x, _conj(y))) -unscaled_covzm(x::AbstractMatrix, y::AbstractVector, vardim::Int) = - (c = vardim == 1 ? At_mul_B(x, _conj(y)) : x * _conj(y); reshape(c, length(c), 1)) -unscaled_covzm(x::AbstractMatrix, y::AbstractMatrix, vardim::Int) = - (vardim == 1 ? At_mul_B(x, _conj(y)) : A_mul_Bc(x, y)) - -# covzm (with centered data) - -covzm(x::AbstractVector, corrected::Bool=true) = unscaled_covzm(x) / (_length(x) - Int(corrected)) -covzm(x::AbstractMatrix, vardim::Int=1, corrected::Bool=true) = - scale!(unscaled_covzm(x, vardim), inv(size(x,vardim) - Int(corrected))) -covzm(x::AbstractVector, y::AbstractVector, corrected::Bool=true) = - unscaled_covzm(x, y) / (_length(x) - Int(corrected)) -covzm(x::AbstractVecOrMat, y::AbstractVecOrMat, vardim::Int=1, corrected::Bool=true) = - scale!(unscaled_covzm(x, y, vardim), inv(_getnobs(x, y, vardim) - Int(corrected))) - -# covm (with provided mean) - -covm(x::AbstractVector, xmean, corrected::Bool=true) = - covzm(x .- xmean, corrected) -covm(x::AbstractMatrix, xmean, vardim::Int=1, corrected::Bool=true) = - covzm(x .- xmean, vardim, corrected) -covm(x::AbstractVector, xmean, y::AbstractVector, ymean, corrected::Bool=true) = - covzm(x .- xmean, y .- ymean, corrected) -covm(x::AbstractVecOrMat, xmean, y::AbstractVecOrMat, ymean, vardim::Int=1, corrected::Bool=true) = - covzm(x .- xmean, y .- ymean, vardim, corrected) - -# cov (API) -""" - cov(x[, corrected=true]) - -Compute the variance of the vector `x`. If `corrected` is `true` (the default) then the sum -is scaled with `n-1`, whereas the sum is scaled with `n` if `corrected` is `false` where `n = length(x)`. -""" -cov(x::AbstractVector, corrected::Bool) = covm(x, Base.mean(x), corrected) -# This ugly hack is necessary to make the method below considered more specific than the deprecated method. When the old keyword version has been completely deprecated, these two methods can be merged -cov(x::AbstractVector) = covm(x, Base.mean(x), true) - -""" - cov(X[, vardim=1, corrected=true]) - -Compute the covariance matrix of the matrix `X` along the dimension `vardim`. If `corrected` -is `true` (the default) then the sum is scaled with `n-1`, whereas the sum is scaled with `n` -if `corrected` is `false` where `n = size(X, vardim)`. -""" -cov(X::AbstractMatrix, vardim::Int, corrected::Bool=true) = - covm(X, _vmean(X, vardim), vardim, corrected) -# This ugly hack is necessary to make the method below considered more specific than the deprecated method. When the old keyword version has been completely deprecated, these two methods can be merged -cov(X::AbstractMatrix) = cov(X, 1, true) - -""" - cov(x, y[, corrected=true]) - -Compute the covariance between the vectors `x` and `y`. If `corrected` is `true` (the -default), computes ``\\frac{1}{n-1}\\sum_{i=1}^n (x_i-\\bar x) (y_i-\\bar y)^*`` where -``*`` denotes the complex conjugate and `n = length(x) = length(y)`. If `corrected` is -`false`, computes ``\frac{1}{n}\sum_{i=1}^n (x_i-\\bar x) (y_i-\\bar y)^*``. -""" -cov(x::AbstractVector, y::AbstractVector, corrected::Bool) = - covm(x, Base.mean(x), y, Base.mean(y), corrected) -# This ugly hack is necessary to make the method below considered more specific than the deprecated method. When the old keyword version has been completely deprecated, these two methods can be merged -cov(x::AbstractVector, y::AbstractVector) = - covm(x, Base.mean(x), y, Base.mean(y), true) - -""" - cov(X, Y[, vardim=1, corrected=true]) - -Compute the covariance between the vectors or matrices `X` and `Y` along the dimension -`vardim`. If `corrected` is `true` (the default) then the sum is scaled with `n-1`, whereas -the sum is scaled with `n` if `corrected` is `false` where `n = size(X, vardim) = size(Y, vardim)`. -""" -cov(X::AbstractVecOrMat, Y::AbstractVecOrMat, vardim::Int, corrected::Bool=true) = - covm(X, _vmean(X, vardim), Y, _vmean(Y, vardim), vardim, corrected) -# This ugly hack is necessary to make the method below considered more specific than the deprecated method. When the old keyword version has been completely deprecated, these methods can be merged -cov(x::AbstractVector, Y::AbstractMatrix) = cov(x, Y, 1, true) -cov(X::AbstractMatrix, y::AbstractVector) = cov(X, y, 1, true) -cov(X::AbstractMatrix, Y::AbstractMatrix) = cov(X, Y, 1, true) - -##### correlation ##### - -""" - clampcor(x) - -Clamp a real correlation to between -1 and 1, leaving complex correlations unchanged -""" -clampcor(x::Real) = clamp(x, -1, 1) -clampcor(x) = x - -# cov2cor! - -function cov2cor!(C::AbstractMatrix{T}, xsd::AbstractArray) where T - nx = length(xsd) - size(C) == (nx, nx) || throw(DimensionMismatch("inconsistent dimensions")) - for j = 1:nx - for i = 1:j-1 - C[i,j] = C[j,i]' - end - C[j,j] = oneunit(T) - for i = j+1:nx - C[i,j] = clampcor(C[i,j] / (xsd[i] * xsd[j])) - end - end - return C -end -function cov2cor!(C::AbstractMatrix, xsd::Number, ysd::AbstractArray) - nx, ny = size(C) - length(ysd) == ny || throw(DimensionMismatch("inconsistent dimensions")) - for (j, y) in enumerate(ysd) # fixme (iter): here and in all `cov2cor!` we assume that `C` is efficiently indexed by integers - for i in 1:nx - C[i,j] = clampcor(C[i, j] / (xsd * y)) - end - end - return C -end -function cov2cor!(C::AbstractMatrix, xsd::AbstractArray, ysd::Number) - nx, ny = size(C) - length(xsd) == nx || throw(DimensionMismatch("inconsistent dimensions")) - for j in 1:ny - for (i, x) in enumerate(xsd) - C[i,j] = clampcor(C[i,j] / (x * ysd)) - end - end - return C -end -function cov2cor!(C::AbstractMatrix, xsd::AbstractArray, ysd::AbstractArray) - nx, ny = size(C) - (length(xsd) == nx && length(ysd) == ny) || - throw(DimensionMismatch("inconsistent dimensions")) - for (i, x) in enumerate(xsd) - for (j, y) in enumerate(ysd) - C[i,j] = clampcor(C[i,j] / (x * y)) - end - end - return C -end - -# corzm (non-exported, with centered data) - -corzm(x::AbstractVector{T}) where {T} = one(real(T)) -function corzm(x::AbstractMatrix, vardim::Int=1) - c = unscaled_covzm(x, vardim) - return cov2cor!(c, sqrt!(diag(c))) -end -corzm(x::AbstractVector, y::AbstractMatrix, vardim::Int=1) = - cov2cor!(unscaled_covzm(x, y, vardim), sqrt(sum(abs2, x)), sqrt!(sum(abs2, y, vardim))) -corzm(x::AbstractMatrix, y::AbstractVector, vardim::Int=1) = - cov2cor!(unscaled_covzm(x, y, vardim), sqrt!(sum(abs2, x, vardim)), sqrt(sum(abs2, y))) -corzm(x::AbstractMatrix, y::AbstractMatrix, vardim::Int=1) = - cov2cor!(unscaled_covzm(x, y, vardim), sqrt!(sum(abs2, x, vardim)), sqrt!(sum(abs2, y, vardim))) - -# corm - -corm(x::AbstractVector{T}, xmean) where {T} = one(real(T)) -corm(x::AbstractMatrix, xmean, vardim::Int=1) = corzm(x .- xmean, vardim) -function corm(x::AbstractVector, mx::Number, y::AbstractVector, my::Number) - n = length(x) - length(y) == n || throw(DimensionMismatch("inconsistent lengths")) - n > 0 || throw(ArgumentError("correlation only defined for non-empty vectors")) - - @inbounds begin - # Initialize the accumulators - xx = zero(sqrt(abs2(x[1]))) - yy = zero(sqrt(abs2(y[1]))) - xy = zero(x[1] * y[1]') - - @simd for i in eachindex(x, y) - xi = x[i] - mx - yi = y[i] - my - xx += abs2(xi) - yy += abs2(yi) - xy += xi * yi' - end - end - return clampcor(xy / max(xx, yy) / sqrt(min(xx, yy) / max(xx, yy))) -end - -corm(x::AbstractVecOrMat, xmean, y::AbstractVecOrMat, ymean, vardim::Int=1) = - corzm(x .- xmean, y .- ymean, vardim) - -# cor -""" - cor(x) - -Return the number one. -""" -cor(x::AbstractVector) = one(real(eltype(x))) -# This ugly hack is necessary to make the method below considered more specific than the deprecated method. When the old keyword version has been completely deprecated, these two methods can be merged - -""" - cor(X[, vardim=1]) - -Compute the Pearson correlation matrix of the matrix `X` along the dimension `vardim`. -""" -cor(X::AbstractMatrix, vardim::Int) = corm(X, _vmean(X, vardim), vardim) -# This ugly hack is necessary to make the method below considered more specific than the deprecated method. When the old keyword version has been completely deprecated, these two methods can be merged -cor(X::AbstractMatrix) = cor(X, 1) - -""" - cor(x, y) - -Compute the Pearson correlation between the vectors `x` and `y`. -""" -cor(x::AbstractVector, y::AbstractVector) = corm(x, Base.mean(x), y, Base.mean(y)) -# This ugly hack is necessary to make the method below considered more specific than the deprecated method. When the old keyword version has been completely deprecated, these two methods can be merged - -""" - cor(X, Y[, vardim=1]) - -Compute the Pearson correlation between the vectors or matrices `X` and `Y` along the dimension `vardim`. -""" -cor(x::AbstractVecOrMat, y::AbstractVecOrMat, vardim::Int) = - corm(x, _vmean(x, vardim), y, _vmean(y, vardim), vardim) -# This ugly hack is necessary to make the method below considered more specific than the deprecated method. When the old keyword version has been completely deprecated, these methods can be merged -cor(x::AbstractVector, Y::AbstractMatrix) = cor(x, Y, 1) -cor(X::AbstractMatrix, y::AbstractVector) = cor(X, y, 1) -cor(X::AbstractMatrix, Y::AbstractMatrix) = cor(X, Y, 1) - -##### median & quantiles ##### - -""" - middle(x) - -Compute the middle of a scalar value, which is equivalent to `x` itself, but of the type of `middle(x, x)` for consistency. -""" -# Specialized functions for real types allow for improved performance -middle(x::Union{Bool,Int8,Int16,Int32,Int64,Int128,UInt8,UInt16,UInt32,UInt64,UInt128}) = Float64(x) -middle(x::AbstractFloat) = x -middle(x::Real) = (x + zero(x)) / 1 - -""" - middle(x, y) - -Compute the middle of two reals `x` and `y`, which is -equivalent in both value and type to computing their mean (`(x + y) / 2`). -""" -middle(x::Real, y::Real) = x/2 + y/2 - -""" - middle(range) - -Compute the middle of a range, which consists of computing the mean of its extrema. -Since a range is sorted, the mean is performed with the first and last element. - -```jldoctest -julia> middle(1:10) -5.5 -``` -""" -middle(a::Range) = middle(a[1], a[end]) - -""" - middle(a) - -Compute the middle of an array `a`, which consists of finding its -extrema and then computing their mean. - -```jldoctest -julia> a = [1,2,3.6,10.9] -4-element Array{Float64,1}: - 1.0 - 2.0 - 3.6 - 10.9 - -julia> middle(a) -5.95 -``` -""" -middle(a::AbstractArray) = ((v1, v2) = extrema(a); middle(v1, v2)) - -""" - median!(v) - -Like [`median`](@ref), but may overwrite the input vector. -""" -function median!(v::AbstractVector) - isempty(v) && throw(ArgumentError("median of an empty array is undefined, $(repr(v))")) - if eltype(v)<:AbstractFloat - @inbounds for x in v - isnan(x) && return x - end - end - inds = indices(v, 1) - n = length(inds) - mid = div(first(inds)+last(inds),2) - if isodd(n) - return middle(select!(v,mid)) - else - m = select!(v, mid:mid+1) - return middle(m[1], m[2]) - end -end -median!(v::AbstractArray) = median!(vec(v)) -median{T}(v::AbstractArray{T}) = median!(copy!(Array{T,1}(_length(v)), v)) - -""" - median(v[, region]) - -Compute the median of an entire array `v`, or, optionally, -along the dimensions in `region`. For an even number of -elements no exact median element exists, so the result is -equivalent to calculating mean of two median elements. - -!!! note - Julia does not ignore `NaN` values in the computation. For applications requiring the - handling of missing data, the `DataArrays.jl` package is recommended. -""" -median(v::AbstractArray, region) = mapslices(median!, v, region) - -# for now, use the R/S definition of quantile; may want variants later -# see ?quantile in R -- this is type 7 -""" - quantile!([q, ] v, p; sorted=false) - -Compute the quantile(s) of a vector `v` at the probabilities `p`, with optional output into -array `q` (if not provided, a new output array is created). The keyword argument `sorted` -indicates whether `v` can be assumed to be sorted; if `false` (the default), then the -elements of `v` may be partially sorted. - -The elements of `p` should be on the interval [0,1], and `v` should not have any `NaN` -values. - -Quantiles are computed via linear interpolation between the points `((k-1)/(n-1), v[k])`, -for `k = 1:n` where `n = length(v)`. This corresponds to Definition 7 of Hyndman and Fan -(1996), and is the same as the R default. - -!!! note - Julia does not ignore `NaN` values in the computation. For applications requiring the - handling of missing data, the `DataArrays.jl` package is recommended. `quantile!` will - throw an `ArgumentError` in the presence of `NaN` values in the data array. - -* Hyndman, R.J and Fan, Y. (1996) "Sample Quantiles in Statistical Packages", - *The American Statistician*, Vol. 50, No. 4, pp. 361-365 -""" -function quantile!(q::AbstractArray, v::AbstractVector, p::AbstractArray; - sorted::Bool=false) - if size(p) != size(q) - throw(DimensionMismatch("size of p, $(size(p)), must equal size of q, $(size(q))")) - end - - isempty(v) && throw(ArgumentError("empty data vector")) - - lv = length(v) - if !sorted - minp, maxp = extrema(p) - lo = floor(Int,1+minp*(lv-1)) - hi = ceil(Int,1+maxp*(lv-1)) - - # only need to perform partial sort - sort!(v, 1, lv, PartialQuickSort(lo:hi), Base.Sort.Forward) - end - isnan(v[end]) && throw(ArgumentError("quantiles are undefined in presence of NaNs")) - - for (i, j) in zip(eachindex(p), eachindex(q)) - @inbounds q[j] = _quantile(v,p[i]) - end - return q -end - -quantile!(v::AbstractVector, p::AbstractArray; sorted::Bool=false) = - quantile!(similar(p,float(eltype(v))), v, p; sorted=sorted) - -function quantile!(v::AbstractVector, p::Real; - sorted::Bool=false) - isempty(v) && throw(ArgumentError("empty data vector")) - - lv = length(v) - if !sorted - lo = floor(Int,1+p*(lv-1)) - hi = ceil(Int,1+p*(lv-1)) - - # only need to perform partial sort - sort!(v, 1, lv, PartialQuickSort(lo:hi), Base.Sort.Forward) - end - isnan(v[end]) && throw(ArgumentError("quantiles are undefined in presence of NaNs")) - - return _quantile(v,p) -end - -# Core quantile lookup function: assumes `v` sorted -@inline function _quantile(v::AbstractVector, p::Real) - T = float(eltype(v)) - isnan(p) && return T(NaN) - 0 <= p <= 1 || throw(ArgumentError("input probability out of [0,1] range")) - - lv = length(v) - f0 = (lv-1)*p # 0-based interpolated index - t0 = trunc(f0) - h = f0 - t0 - i = trunc(Int,t0) + 1 - - if h == 0 - return T(v[i]) - else - a = T(v[i]) - b = T(v[i+1]) - if isfinite(a) && isfinite(b) - return a + h*(b-a) - else - return (1-h)*a + h*b - end - end -end - - -""" - quantile(v, p; sorted=false) - -Compute the quantile(s) of a vector `v` at a specified probability or vector `p`. The -keyword argument `sorted` indicates whether `v` can be assumed to be sorted. - -The `p` should be on the interval [0,1], and `v` should not have any `NaN` values. - -Quantiles are computed via linear interpolation between the points `((k-1)/(n-1), v[k])`, -for `k = 1:n` where `n = length(v)`. This corresponds to Definition 7 of Hyndman and Fan -(1996), and is the same as the R default. - -!!! note - Julia does not ignore `NaN` values in the computation. For applications requiring the - handling of missing data, the `DataArrays.jl` package is recommended. `quantile` will - throw an `ArgumentError` in the presence of `NaN` values in the data array. - -- Hyndman, R.J and Fan, Y. (1996) "Sample Quantiles in Statistical Packages", - *The American Statistician*, Vol. 50, No. 4, pp. 361-365 -""" -quantile(v::AbstractVector, p; sorted::Bool=false) = - quantile!(sorted ? v : copymutable(v), p; sorted=sorted) diff --git a/julia-0.6.3/share/julia/base/stream.jl b/julia-0.6.3/share/julia/base/stream.jl deleted file mode 100644 index 4bd1f4c..0000000 --- a/julia-0.6.3/share/julia/base/stream.jl +++ /dev/null @@ -1,1192 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -import .Libc: RawFD, dup -if is_windows() - import .Libc: WindowsRawSocket -end - -## types ## -abstract type IOServer end -abstract type LibuvServer <: IOServer end -abstract type LibuvStream <: IO end - -# IO -# +- AbstractIOBuffer{T<:AbstractArray{UInt8,1}} (not exported) -# +- AbstractPipe (not exported) -# . +- Pipe -# . +- Process (not exported) -# . +- ProcessChain (not exported) -# +- Base64DecodePipe -# +- Base64EncodePipe -# +- BufferStream -# +- DevNullStream (not exported) -# +- Filesystem.File -# +- LibuvStream (not exported) -# . +- PipeEndpoint (not exported) -# . +- TCPSocket -# . +- TTY (not exported) -# . +- UDPSocket -# +- IOBuffer = Base.AbstractIOBuffer{Array{UInt8,1}} -# +- IOStream - -# IOServer -# +- LibuvServer -# . +- PipeServer -# . +- TCPServer - -# Redirectable = Union{IO, FileRedirect, Libc.RawFD} (not exported) - -function stream_wait(x, c...) # for x::LibuvObject - preserve_handle(x) - try - return wait(c...) - finally - unpreserve_handle(x) - end -end - -nb_available(s::LibuvStream) = nb_available(s.buffer) - -function eof(s::LibuvStream) - if isopen(s) # fast path - nb_available(s) > 0 && return false - else - return nb_available(s) <= 0 - end - wait_readnb(s,1) - return !isopen(s) && nb_available(s) <= 0 -end - -const DEFAULT_READ_BUFFER_SZ = 10485760 # 10 MB - -const StatusUninit = 0 # handle is allocated, but not initialized -const StatusInit = 1 # handle is valid, but not connected/active -const StatusConnecting = 2 # handle is in process of connecting -const StatusOpen = 3 # handle is usable -const StatusActive = 4 # handle is listening for read/write/connect events -const StatusClosing = 5 # handle is closing / being closed -const StatusClosed = 6 # handle is closed -const StatusEOF = 7 # handle is a TTY that has seen an EOF event -const StatusPaused = 8 # handle is Active, but not consuming events, and will transition to Open if it receives an event -function uv_status_string(x) - s = x.status - if x.handle == C_NULL - if s == StatusClosed - return "closed" - elseif s == StatusUninit - return "null" - end - return "invalid status" - elseif s == StatusUninit - return "uninit" - elseif s == StatusInit - return "init" - elseif s == StatusConnecting - return "connecting" - elseif s == StatusOpen - return "open" - elseif s == StatusActive - return "active" - elseif s == StatusPaused - return "paused" - elseif s == StatusClosing - return "closing" - elseif s == StatusClosed - return "closed" - elseif s == StatusEOF - return "eof" - end - return "invalid status" -end - -mutable struct PipeEndpoint <: LibuvStream - handle::Ptr{Void} - status::Int - buffer::IOBuffer - readnotify::Condition - connectnotify::Condition - closenotify::Condition - sendbuf::Nullable{IOBuffer} - lock::ReentrantLock - throttle::Int - - PipeEndpoint() = PipeEndpoint(Libc.malloc(_sizeof_uv_named_pipe), StatusUninit) - function PipeEndpoint(handle::Ptr{Void}, status) - p = new(handle, - status, - PipeBuffer(), - Condition(), - Condition(), - Condition(), - nothing, - ReentrantLock(), - DEFAULT_READ_BUFFER_SZ) - associate_julia_struct(handle, p) - finalizer(p, uvfinalize) - return p - end -end - -mutable struct PipeServer <: LibuvServer - handle::Ptr{Void} - status::Int - connectnotify::Condition - closenotify::Condition - function PipeServer(handle::Ptr{Void}, status) - p = new(handle, - status, - Condition(), - Condition()) - associate_julia_struct(p.handle, p) - finalizer(p, uvfinalize) - return p - end -end - -const LibuvPipe = Union{PipeEndpoint, PipeServer} - -function PipeServer() - p = PipeServer(Libc.malloc(_sizeof_uv_named_pipe), StatusUninit) - return init_pipe!(p; readable=true) -end - -mutable struct TTY <: LibuvStream - handle::Ptr{Void} - status::Int - buffer::IOBuffer - readnotify::Condition - closenotify::Condition - sendbuf::Nullable{IOBuffer} - lock::ReentrantLock - throttle::Int - @static if is_windows(); ispty::Bool; end - TTY() = TTY(Libc.malloc(_sizeof_uv_tty), StatusUninit) - function TTY(handle::Ptr{Void}, status) - tty = new( - handle, - status, - PipeBuffer(), - Condition(), - Condition(), - nothing, ReentrantLock(), - DEFAULT_READ_BUFFER_SZ) - associate_julia_struct(handle, tty) - finalizer(tty, uvfinalize) - @static if is_windows() - tty.ispty = ccall(:jl_ispty, Cint, (Ptr{Void},), handle) != 0 - end - return tty - end -end - -function TTY(fd::RawFD; readable::Bool = false) - tty = TTY() - # This needs to go after associate_julia_struct so that there - # is no garbage in the ->data field - err = ccall(:uv_tty_init, Int32, (Ptr{Void}, Ptr{Void}, Int32, Int32), - eventloop(), tty.handle, fd.fd, readable) - uv_error("TTY", err) - tty.status = StatusOpen - return tty -end - -show(io::IO, stream::LibuvServer) = print(io, typeof(stream), "(", - _fd(stream), " ", - uv_status_string(stream), ")") -show(io::IO, stream::LibuvStream) = print(io, typeof(stream), "(", - _fd(stream), " ", - uv_status_string(stream), ", ", - nb_available(stream.buffer)," bytes waiting)") - -# Shared LibuvStream object interface - -function isreadable(io::LibuvStream) - nb_available(io) > 0 && return true - isopen(io) || return false - return ccall(:uv_is_readable, Cint, (Ptr{Void},), io.handle) != 0 -end - -function iswritable(io::LibuvStream) - isopen(io) || return false - io.status == StatusClosing && return false - return ccall(:uv_is_writable, Cint, (Ptr{Void},), io.handle) != 0 -end - -lock(s::LibuvStream) = lock(s.lock) -unlock(s::LibuvStream) = unlock(s.lock) - -uvtype(::LibuvStream) = UV_STREAM -uvhandle(stream::LibuvStream) = stream.handle -unsafe_convert(::Type{Ptr{Void}}, s::Union{LibuvStream, LibuvServer}) = s.handle - -function init_stdio(handle::Ptr{Void}) - t = ccall(:jl_uv_handle_type, Int32, (Ptr{Void},), handle) - if t == UV_FILE - return fdio(ccall(:jl_uv_file_handle, Int32, (Ptr{Void},), handle)) -# Replace ios.c file with libuv file? -# return File(RawFD(ccall(:jl_uv_file_handle,Int32,(Ptr{Void},),handle))) - else - if t == UV_TTY - ret = TTY(handle, StatusOpen) - elseif t == UV_TCP - ret = TCPSocket(handle, StatusOpen) - elseif t == UV_NAMED_PIPE - ret = PipeEndpoint(handle, StatusOpen) - else - throw(ArgumentError("invalid stdio type: $t")) - end - return ret - end -end - -function isopen(x::Union{LibuvStream, LibuvServer}) - if x.status == StatusUninit || x.status == StatusInit - throw(ArgumentError("$x is not initialized")) - end - x.status != StatusClosed && x.status != StatusEOF -end - -function check_open(x::Union{LibuvStream, LibuvServer}) - if !isopen(x) || x.status == StatusClosing - throw(ArgumentError("stream is closed or unusable")) - end -end - -function wait_connected(x::Union{LibuvStream, LibuvServer}) - check_open(x) - while x.status == StatusConnecting - stream_wait(x, x.connectnotify) - check_open(x) - end -end - -function wait_readbyte(x::LibuvStream, c::UInt8) - if isopen(x) # fast path - search(x.buffer, c) > 0 && return - else - return - end - preserve_handle(x) - try - while isopen(x) && search(x.buffer, c) <= 0 - start_reading(x) # ensure we are reading - wait(x.readnotify) - end - finally - if isempty(x.readnotify.waitq) - stop_reading(x) # stop reading iff there are currently no other read clients of the stream - end - unpreserve_handle(x) - end - nothing -end - -function wait_readnb(x::LibuvStream, nb::Int) - if isopen(x) # fast path - nb_available(x.buffer) >= nb && return - else - return - end - oldthrottle = x.throttle - preserve_handle(x) - try - while isopen(x) && nb_available(x.buffer) < nb - x.throttle = max(nb, x.throttle) - start_reading(x) # ensure we are reading - wait(x.readnotify) - end - finally - if isempty(x.readnotify.waitq) - stop_reading(x) # stop reading iff there are currently no other read clients of the stream - end - if oldthrottle <= x.throttle <= nb - x.throttle = oldthrottle - end - unpreserve_handle(x) - end - nothing -end - -function wait_close(x::Union{LibuvStream, LibuvServer}) - if isopen(x) - stream_wait(x, x.closenotify) - end - nothing -end - -function close(stream::Union{LibuvStream, LibuvServer}) - if stream.status == StatusInit - ccall(:jl_forceclose_uv, Void, (Ptr{Void},), stream.handle) - elseif isopen(stream) - if stream.status != StatusClosing - ccall(:jl_close_uv, Void, (Ptr{Void},), stream.handle) - stream.status = StatusClosing - end - if uv_handle_data(stream) != C_NULL - stream_wait(stream, stream.closenotify) - end - end - nothing -end - -function uvfinalize(uv::Union{LibuvStream, LibuvServer}) - if uv.handle != C_NULL - disassociate_julia_struct(uv.handle) # not going to call the usual close hooks - if uv.status != StatusUninit - close(uv) - else - Libc.free(uv.handle) - end - uv.status = StatusClosed - uv.handle = C_NULL - end - nothing -end - -if is_windows() - ispty(s::TTY) = s.ispty - ispty(s::IO) = false -end - -" displaysize(io) -> (lines, columns) -Return the nominal size of the screen that may be used for rendering output to this io object" -displaysize(io::IO) = displaysize() -displaysize() = (parse(Int, get(ENV, "LINES", "24")), - parse(Int, get(ENV, "COLUMNS", "80")))::Tuple{Int, Int} - -function displaysize(io::TTY) - local h::Int, w::Int - default_size = displaysize() - - @static if is_windows() - if ispty(io) - # io is actually a libuv pipe but a cygwin/msys2 pty - try - h, w = map(x -> parse(Int, x), split(readstring(open(Base.Cmd(String["stty", "size"]), "r", io)[1]))) - h > 0 || (h = default_size[1]) - w > 0 || (w = default_size[2]) - return h, w - catch - return default_size - end - end - end - - s1 = Ref{Int32}(0) - s2 = Ref{Int32}(0) - Base.uv_error("size (TTY)", ccall(:uv_tty_get_winsize, - Int32, (Ptr{Void}, Ptr{Int32}, Ptr{Int32}), - io, s1, s2) != 0) - w, h = s1[], s2[] - h > 0 || (h = default_size[1]) - w > 0 || (w = default_size[2]) - return h, w -end - - -### Libuv callbacks ### - -#from `connect` -function uv_connectcb(conn::Ptr{Void}, status::Cint) - hand = ccall(:jl_uv_connect_handle, Ptr{Void}, (Ptr{Void},), conn) - sock = @handle_as hand LibuvStream - @assert sock.status == StatusConnecting - if status >= 0 - sock.status = StatusOpen - notify(sock.connectnotify) - else - sock.status = StatusInit - err = UVError("connect", status) - notify_error(sock.connectnotify, err) - end - Libc.free(conn) - nothing -end - -# from `listen` -function uv_connectioncb(stream::Ptr{Void}, status::Cint) - sock = @handle_as stream LibuvServer - if status >= 0 - notify(sock.connectnotify) - else - err = UVError("connection", status) - notify_error(sock.connectnotify, err) - end - nothing -end - -## BUFFER ## -## Allocate space in buffer (for immediate use) -function alloc_request(buffer::IOBuffer, recommended_size::UInt) - ensureroom(buffer, Int(recommended_size)) - ptr = buffer.append ? buffer.size + 1 : buffer.ptr - nb = length(buffer.data) - ptr + 1 - return (pointer(buffer.data, ptr), nb) -end - -notify_filled(buffer::IOBuffer, nread::Int, base::Ptr{Void}, len::UInt) = notify_filled(buffer, nread) - -function notify_filled(buffer::IOBuffer, nread::Int) - if buffer.append - buffer.size += nread - else - buffer.ptr += nread - end -end - -alloc_buf_hook(stream::LibuvStream, size::UInt) = alloc_request(stream.buffer, UInt(size)) - -function uv_alloc_buf(handle::Ptr{Void}, size::Csize_t, buf::Ptr{Void}) - hd = uv_handle_data(handle) - if hd == C_NULL - ccall(:jl_uv_buf_set_len, Void, (Ptr{Void}, Csize_t), buf, 0) - return nothing - end - stream = unsafe_pointer_to_objref(hd)::LibuvStream - - local data::Ptr{Void}, newsize::Csize_t - if stream.status != StatusActive - data = C_NULL - newsize = 0 - else - (data, newsize) = alloc_buf_hook(stream, UInt(size)) - if data == C_NULL - newsize = 0 - end - end - - ccall(:jl_uv_buf_set_base, Void, (Ptr{Void}, Ptr{Void}), buf, data) - ccall(:jl_uv_buf_set_len, Void, (Ptr{Void}, Csize_t), buf, newsize) - nothing -end - -function uv_readcb(handle::Ptr{Void}, nread::Cssize_t, buf::Ptr{Void}) - stream_unknown_type = @handle_as handle LibuvStream - nrequested = ccall(:jl_uv_buf_len, Csize_t, (Ptr{Void},), buf) - function readcb_specialized(stream::LibuvStream, nread::Int, nrequested::UInt) - if nread < 0 - if nread == UV_ENOBUFS && nrequested == 0 - # remind the client that stream.buffer is full - notify(stream.readnotify) - elseif nread == UV_EOF - if isa(stream, TTY) - stream.status = StatusEOF # libuv called uv_stop_reading already - notify(stream.readnotify) - notify(stream.closenotify) - elseif stream.status != StatusClosing - # begin shutdown of the stream - ccall(:jl_close_uv, Void, (Ptr{Void},), stream.handle) - stream.status = StatusClosing - end - else - # This is a fatal connection error. Shutdown requests as per the usual - # close function won't work and libuv will fail with an assertion failure - ccall(:jl_forceclose_uv, Void, (Ptr{Void},), stream) - notify_error(stream.readnotify, UVError("read", nread)) - end - else - notify_filled(stream.buffer, nread) - notify(stream.readnotify) - end - - # Stop background reading when - # 1) there's nobody paying attention to the data we are reading - # 2) we have accumulated a lot of unread data OR - # 3) we have an alternate buffer that has reached its limit. - if stream.status == StatusPaused || - (stream.status == StatusActive && - ((nb_available(stream.buffer) >= stream.throttle) || - (nb_available(stream.buffer) >= stream.buffer.maxsize))) - # save cycles by stopping kernel notifications from arriving - ccall(:uv_read_stop, Cint, (Ptr{Void},), stream) - stream.status = StatusOpen - end - nothing - end - readcb_specialized(stream_unknown_type, Int(nread), UInt(nrequested)) -end - -function reseteof(x::TTY) - if x.status == StatusEOF - x.status = StatusOpen - end - nothing -end - -function _uv_hook_close(uv::Union{LibuvStream, LibuvServer}) - uv.handle = C_NULL - uv.status = StatusClosed - # notify any listeners that exist on this libuv stream type - notify(uv.closenotify) - isdefined(uv, :readnotify) && notify(uv.readnotify) - isdefined(uv, :connectnotify) && notify(uv.connectnotify) - nothing -end - - -########################################## -# Pipe Abstraction -# (composed of two half-pipes: .in and .out) -########################################## - -mutable struct Pipe <: AbstractPipe - in::PipeEndpoint # writable - out::PipeEndpoint # readable -end -Pipe() = Pipe(PipeEndpoint(), PipeEndpoint()) -pipe_reader(p::Pipe) = p.out -pipe_writer(p::Pipe) = p.in - -function link_pipe(pipe::Pipe; - julia_only_read = false, - julia_only_write = false) - link_pipe(pipe.out, julia_only_read, pipe.in, julia_only_write) -end - -show(io::IO, stream::Pipe) = print(io, - "Pipe(", - _fd(stream.in), " ", - uv_status_string(stream.in), " => ", - _fd(stream.out), " ", - uv_status_string(stream.out), ", ", - nb_available(stream), " bytes waiting)") - - -## Functions for PipeEndpoint and PipeServer ## - -function init_pipe!(pipe::LibuvPipe; - readable::Bool = false, - writable::Bool = false, - julia_only::Bool = true) - if pipe.status != StatusUninit - error("pipe is already initialized") - end - err = ccall(:jl_init_pipe, Cint, - (Ptr{Void}, Int32, Int32, Int32), - pipe.handle, writable, readable, julia_only) - uv_error( - if readable && writable - "init_pipe(ipc)" - elseif readable - "init_pipe(read)" - elseif writable - "init_pipe(write)" - else - "init_pipe(none)" - end, err) - pipe.status = StatusInit - return pipe -end - -function _link_pipe(read_end::Ptr{Void}, write_end::Ptr{Void}) - uv_error("pipe_link", - ccall(:uv_pipe_link, Int32, (Ptr{Void}, Ptr{Void}), read_end, write_end)) - nothing -end - -function link_pipe(read_end::Ptr{Void}, readable_julia_only::Bool, - write_end::Ptr{Void}, writable_julia_only::Bool, - readpipe::PipeEndpoint, writepipe::PipeEndpoint) - #make the pipe an unbuffered stream for now - #TODO: this is probably not freeing memory properly after errors - uv_error("init_pipe(read)", - ccall(:jl_init_pipe, Cint, (Ptr{Void},Int32,Int32,Int32), read_end, 0, 1, readable_julia_only)) - uv_error("init_pipe(write)", - ccall(:jl_init_pipe, Cint, (Ptr{Void},Int32,Int32,Int32), write_end, 1, 0, writable_julia_only)) - _link_pipe(read_end, write_end) - nothing -end - -function link_pipe(read_end::Ptr{Void}, readable_julia_only::Bool, - write_end::Ptr{Void}, writable_julia_only::Bool) - uv_error("init_pipe(read)", - ccall(:jl_init_pipe, Cint, (Ptr{Void},Int32,Int32,Int32), read_end, 0, 1, readable_julia_only)) - uv_error("init_pipe(write)", - ccall(:jl_init_pipe, Cint, (Ptr{Void},Int32,Int32,Int32), write_end, 1, 0, writable_julia_only)) - _link_pipe(read_end,write_end) - nothing -end - -function link_pipe(read_end::PipeEndpoint, readable_julia_only::Bool, - write_end::Ptr{Void}, writable_julia_only::Bool) - init_pipe!(read_end; - readable = true, writable = false, julia_only = readable_julia_only) - uv_error("init_pipe", - ccall(:jl_init_pipe, Cint, (Ptr{Void},Int32,Int32,Int32), write_end, 1, 0, writable_julia_only)) - _link_pipe(read_end.handle, write_end) - read_end.status = StatusOpen - nothing -end - -function link_pipe(read_end::Ptr{Void}, readable_julia_only::Bool, - write_end::PipeEndpoint, writable_julia_only::Bool) - uv_error("init_pipe", - ccall(:jl_init_pipe, Cint, (Ptr{Void},Int32,Int32,Int32), read_end, 0, 1, readable_julia_only)) - init_pipe!(write_end; - readable = false, writable = true, julia_only = writable_julia_only) - _link_pipe(read_end, write_end.handle) - write_end.status = StatusOpen - nothing -end - -function link_pipe(read_end::PipeEndpoint, readable_julia_only::Bool, - write_end::PipeEndpoint, writable_julia_only::Bool) - init_pipe!(read_end; - readable = true, writable = false, julia_only = readable_julia_only) - init_pipe!(write_end; - readable = false, writable = true, julia_only = writable_julia_only) - _link_pipe(read_end.handle, write_end.handle) - write_end.status = StatusOpen - read_end.status = StatusOpen - nothing -end - -function close_pipe_sync(p::PipeEndpoint) - ccall(:uv_pipe_close_sync, Void, (Ptr{Void},), p.handle) - p.status = StatusClosed - nothing -end - -function close_pipe_sync(handle::Ptr{Void}) - return ccall(:uv_pipe_close_sync, Void, (Ptr{Void},), handle) -end - -## Functions for any LibuvStream ## - -# flow control - -function start_reading(stream::LibuvStream) - if stream.status == StatusOpen - if !isreadable(stream) - error("tried to read a stream that is not readable") - end - # libuv may call the alloc callback immediately - # for a TTY on Windows, so ensure the status is set first - stream.status = StatusActive - ret = ccall(:uv_read_start, Cint, (Ptr{Void}, Ptr{Void}, Ptr{Void}), - stream, uv_jl_alloc_buf::Ptr{Void}, uv_jl_readcb::Ptr{Void}) - return ret - elseif stream.status == StatusPaused - stream.status = StatusActive - return Int32(0) - elseif stream.status == StatusActive - return Int32(0) - else - return Int32(-1) - end -end - -if is_windows() - # the low performance version of stop_reading is required - # on Windows due to a NT kernel bug that we can't use a blocking - # stream for non-blocking (overlapped) calls, - # and a ReadFile call blocking on one thread - # causes all other operations on that stream to lockup - function stop_reading(stream::LibuvStream) - if stream.status == StatusActive - stream.status = StatusOpen - ccall(:uv_read_stop, Cint, (Ptr{Void},), stream) - end - nothing - end -else - function stop_reading(stream::LibuvStream) - if stream.status == StatusActive - stream.status = StatusPaused - end - nothing - end -end - -# bulk read / write - -readbytes!(s::LibuvStream, a::Vector{UInt8}, nb = length(a)) = readbytes!(s, a, Int(nb)) -function readbytes!(s::LibuvStream, a::Vector{UInt8}, nb::Int) - sbuf = s.buffer - @assert sbuf.seekable == false - @assert sbuf.maxsize >= nb - - if nb_available(sbuf) >= nb - return readbytes!(sbuf, a, nb) - end - - if nb <= SZ_UNBUFFERED_IO # Under this limit we are OK with copying the array from the stream's buffer - wait_readnb(s, nb) - return readbytes!(sbuf, a, nb) - else - try - stop_reading(s) # Just playing it safe, since we are going to switch buffers. - newbuf = PipeBuffer(a, #=maxsize=# nb) - newbuf.size = 0 # reset the write pointer to the beginning - s.buffer = newbuf - write(newbuf, sbuf) - wait_readnb(s, Int(nb)) - compact(newbuf) - return nb_available(newbuf) - finally - s.buffer = sbuf - if !isempty(s.readnotify.waitq) - start_reading(s) # resume reading iff there are currently other read clients of the stream - end - end - end - @assert false # unreachable -end - -function read(stream::LibuvStream) - wait_readnb(stream, typemax(Int)) - return take!(stream.buffer) -end - -function unsafe_read(s::LibuvStream, p::Ptr{UInt8}, nb::UInt) - sbuf = s.buffer - @assert sbuf.seekable == false - @assert sbuf.maxsize >= nb - - if nb_available(sbuf) >= nb - return unsafe_read(sbuf, p, nb) - end - - if nb <= SZ_UNBUFFERED_IO # Under this limit we are OK with copying the array from the stream's buffer - wait_readnb(s, Int(nb)) - unsafe_read(sbuf, p, nb) - else - try - stop_reading(s) # Just playing it safe, since we are going to switch buffers. - newbuf = PipeBuffer(unsafe_wrap(Array, p, nb), #=maxsize=# Int(nb)) - newbuf.size = 0 # reset the write pointer to the beginning - s.buffer = newbuf - write(newbuf, sbuf) - wait_readnb(s, Int(nb)) - nb == nb_available(newbuf) || throw(EOFError()) - finally - s.buffer = sbuf - if !isempty(s.readnotify.waitq) - start_reading(s) # resume reading iff there are currently other read clients of the stream - end - end - end - nothing -end - -function read(this::LibuvStream, ::Type{UInt8}) - wait_readnb(this, 1) - buf = this.buffer - @assert buf.seekable == false - return read(buf, UInt8) -end - -function readavailable(this::LibuvStream) - wait_readnb(this, 1) - buf = this.buffer - @assert buf.seekable == false - return take!(buf) -end - -function readuntil(this::LibuvStream, c::UInt8) - wait_readbyte(this, c) - buf = this.buffer - @assert buf.seekable == false - return readuntil(buf, c) -end - -uv_write(s::LibuvStream, p::Vector{UInt8}) = uv_write(s, pointer(p), UInt(sizeof(p))) -function uv_write(s::LibuvStream, p::Ptr{UInt8}, n::UInt) - check_open(s) - uvw = Libc.malloc(_sizeof_uv_write) - uv_req_set_data(uvw, C_NULL) # in case we get interrupted before arriving at the wait call - err = ccall(:jl_uv_write, - Int32, - (Ptr{Void}, Ptr{Void}, UInt, Ptr{Void}, Ptr{Void}), - s, p, n, uvw, - uv_jl_writecb_task::Ptr{Void}) - if err < 0 - Libc.free(uvw) - uv_error("write", err) - end - ct = current_task() - preserve_handle(ct) - try - uv_req_set_data(uvw, ct) - wait() - finally - if uv_req_data(uvw) != C_NULL - # uvw is still alive, - # so make sure we don't get spurious notifications later - uv_req_set_data(uvw, C_NULL) - else - # done with uvw - Libc.free(uvw) - end - unpreserve_handle(ct) - end - return Int(n) -end - -# Optimized send -# - smaller writes are buffered, final uv write on flush or when buffer full -# - large isbits arrays are unbuffered and written directly - -function unsafe_write(s::LibuvStream, p::Ptr{UInt8}, n::UInt) - if isnull(s.sendbuf) - return uv_write(s, p, UInt(n)) - end - - buf = get(s.sendbuf) - totb = nb_available(buf) + n - if totb < buf.maxsize - nb = unsafe_write(buf, p, n) - else - flush(s) - if n > buf.maxsize - nb = uv_write(s, p, n) - else - nb = unsafe_write(buf, p, n) - end - end - return nb -end - -function flush(s::LibuvStream) - if isnull(s.sendbuf) - return - end - buf = get(s.sendbuf) - if nb_available(buf) > 0 - arr = take!(buf) # Array of UInt8s - uv_write(s, arr) - end - return -end - -buffer_writes(s::LibuvStream, bufsize) = (s.sendbuf=PipeBuffer(bufsize); s) - -## low-level calls to libuv ## - -function write(s::LibuvStream, b::UInt8) - if !isnull(s.sendbuf) - buf = get(s.sendbuf) - if nb_available(buf) + 1 < buf.maxsize - return write(buf, b) - end - end - return write(s, Ref{UInt8}(b)) -end - -function uv_writecb_task(req::Ptr{Void}, status::Cint) - d = uv_req_data(req) - if d != C_NULL - uv_req_set_data(req, C_NULL) - if status < 0 - err = UVError("write", status) - schedule(unsafe_pointer_to_objref(d)::Task, err, error=true) - else - schedule(unsafe_pointer_to_objref(d)::Task) - end - else - # no owner for this req, safe to just free it - Libc.free(req) - end - nothing -end - -## server functions ## - -function accept_nonblock(server::PipeServer,client::PipeEndpoint) - if client.status != StatusInit - error(client.status == StatusUninit ? - "client is not initialized" : - "client is already in use or has been closed") - end - err = ccall(:uv_accept, Int32, (Ptr{Void}, Ptr{Void}), server.handle, client.handle) - if err == 0 - client.status = StatusOpen - end - return err -end - -function accept_nonblock(server::PipeServer) - client = init_pipe!(PipeEndpoint(); readable=true, writable=true, julia_only=true) - uv_error("accept", accept_nonblock(server, client) != 0) - return client -end - -function accept(server::LibuvServer, client::LibuvStream) - if server.status != StatusActive - throw(ArgumentError("server not connected, make sure \"listen\" has been called")) - end - while isopen(server) - err = accept_nonblock(server, client) - if err == 0 - return client - elseif err != UV_EAGAIN - uv_error("accept", err) - end - stream_wait(server, server.connectnotify) - end - uv_error("accept", UV_ECONNABORTED) -end - -const BACKLOG_DEFAULT = 511 - -function listen(sock::LibuvServer; backlog::Integer=BACKLOG_DEFAULT) - uv_error("listen", trylisten(sock)) - return sock -end - -function trylisten(sock::LibuvServer; backlog::Integer=BACKLOG_DEFAULT) - check_open(sock) - err = ccall(:uv_listen, Cint, (Ptr{Void}, Cint, Ptr{Void}), - sock, backlog, uv_jl_connectioncb::Ptr{Void}) - sock.status = StatusActive - return err -end - -function bind(server::PipeServer, name::AbstractString) - @assert server.status == StatusInit - err = ccall(:uv_pipe_bind, Int32, (Ptr{Void}, Cstring), - server, name) - if err != 0 - if err != UV_EADDRINUSE && err != UV_EACCES - #TODO: this codepath is currently not tested - throw(UVError("bind",err)) - else - return false - end - end - server.status = StatusOpen - return true -end - -""" - listen(path::AbstractString) -> PipeServer - -Create and listen on a named pipe / UNIX domain socket. -""" -function listen(path::AbstractString) - sock = PipeServer() - bind(sock, path) || throw(ArgumentError("could not listen on path $path")) - return listen(sock) -end - -function connect!(sock::PipeEndpoint, path::AbstractString) - @assert sock.status == StatusInit - req = Libc.malloc(_sizeof_uv_connect) - uv_req_set_data(req, C_NULL) - ccall(:uv_pipe_connect, Void, (Ptr{Void}, Ptr{Void}, Cstring, Ptr{Void}), req, sock.handle, path, uv_jl_connectcb::Ptr{Void}) - sock.status = StatusConnecting - return sock -end - -function connect(sock::LibuvStream, args...) - connect!(sock, args...) - wait_connected(sock) - return sock -end - -# Libuv will internally reset read/writability, which is uses to -# mark that this is an invalid pipe. - -""" - connect(path::AbstractString) -> PipeEndpoint - -Connect to the named pipe / UNIX domain socket at `path`. -""" -connect(path::AbstractString) = connect(init_pipe!(PipeEndpoint(); readable=false, writable=false, julia_only=true),path) - -const OS_HANDLE = is_windows() ? WindowsRawSocket : RawFD -const INVALID_OS_HANDLE = is_windows() ? WindowsRawSocket(Ptr{Void}(-1)) : RawFD(-1) -_fd(x::IOStream) = RawFD(fd(x)) -function _fd(x::Union{LibuvStream, LibuvServer}) - fd = Ref{OS_HANDLE}(INVALID_OS_HANDLE) - if x.status != StatusUninit && x.status != StatusClosed - err = ccall(:uv_fileno, Int32, (Ptr{Void}, Ptr{OS_HANDLE}), x.handle, fd) - # handle errors by returning INVALID_OS_HANDLE - end - return fd[] -end - -for (x, writable, unix_fd, c_symbol) in - ((:STDIN, false, 0, :jl_uv_stdin), - (:STDOUT, true, 1, :jl_uv_stdout), - (:STDERR, true, 2, :jl_uv_stderr)) - f = Symbol("redirect_",lowercase(string(x))) - _f = Symbol("_",f) - @eval begin - function ($_f)(stream) - global $x - posix_fd = _fd(stream) - @static if is_windows() - ccall(:SetStdHandle, stdcall, Int32, (Int32, Ptr{Void}), - $(-10 - unix_fd), Libc._get_osfhandle(posix_fd).handle) - end - dup(posix_fd, RawFD($unix_fd)) - $x = stream - nothing - end - function ($f)(handle::Union{LibuvStream,IOStream}) - $(_f)(handle) - unsafe_store!(cglobal($(Expr(:quote,c_symbol)),Ptr{Void}), - handle.handle) - return handle - end - function ($f)() - read, write = (PipeEndpoint(), PipeEndpoint()) - link_pipe(read, $(writable), write, $(!writable)) - ($f)($(writable ? :write : :read)) - return (read, write) - end - end -end - -""" - redirect_stdout([stream]) -> (rd, wr) - -Create a pipe to which all C and Julia level [`STDOUT`](@ref) output -will be redirected. -Returns a tuple `(rd, wr)` representing the pipe ends. -Data written to [`STDOUT`](@ref) may now be read from the `rd` end of -the pipe. The `wr` end is given for convenience in case the old -[`STDOUT`](@ref) object was cached by the user and needs to be replaced -elsewhere. - -!!! note - `stream` must be a `TTY`, a `Pipe`, or a `TCPSocket`. -""" -redirect_stdout - -""" - redirect_stderr([stream]) -> (rd, wr) - -Like [`redirect_stdout`](@ref), but for [`STDERR`](@ref). - -!!! note - `stream` must be a `TTY`, a `Pipe`, or a `TCPSocket`. -""" -redirect_stderr - -""" - redirect_stdin([stream]) -> (rd, wr) - -Like [`redirect_stdout`](@ref), but for [`STDIN`](@ref). -Note that the order of the return tuple is still `(rd, wr)`, -i.e. data to be read from [`STDIN`](@ref) may be written to `wr`. - -!!! note - `stream` must be a `TTY`, a `Pipe`, or a `TCPSocket`. -""" -redirect_stdin - -for (F,S) in ((:redirect_stdin, :STDIN), (:redirect_stdout, :STDOUT), (:redirect_stderr, :STDERR)) - @eval function $F(f::Function, stream) - STDOLD = $S - local ret - $F(stream) - try - ret = f() - finally - $F(STDOLD) - end - ret - end -end - -""" - redirect_stdout(f::Function, stream) - -Run the function `f` while redirecting [`STDOUT`](@ref) to `stream`. -Upon completion, [`STDOUT`](@ref) is restored to its prior setting. - -!!! note - `stream` must be a `TTY`, a `Pipe`, or a `TCPSocket`. -""" -redirect_stdout(f::Function, stream) - -""" - redirect_stderr(f::Function, stream) - -Run the function `f` while redirecting [`STDERR`](@ref) to `stream`. -Upon completion, [`STDERR`](@ref) is restored to its prior setting. - -!!! note - `stream` must be a `TTY`, a `Pipe`, or a `TCPSocket`. -""" -redirect_stderr(f::Function, stream) - -""" - redirect_stdin(f::Function, stream) - -Run the function `f` while redirecting [`STDIN`](@ref) to `stream`. -Upon completion, [`STDIN`](@ref) is restored to its prior setting. - -!!! note - `stream` must be a `TTY`, a `Pipe`, or a `TCPSocket`. -""" -redirect_stdin(f::Function, stream) - -mark(x::LibuvStream) = mark(x.buffer) -unmark(x::LibuvStream) = unmark(x.buffer) -reset(x::LibuvStream) = reset(x.buffer) -ismarked(x::LibuvStream) = ismarked(x.buffer) - -# BufferStream's are non-OS streams, backed by a regular IOBuffer -mutable struct BufferStream <: LibuvStream - buffer::IOBuffer - r_c::Condition - close_c::Condition - is_open::Bool - buffer_writes::Bool - lock::ReentrantLock - - BufferStream() = new(PipeBuffer(), Condition(), Condition(), true, false, ReentrantLock()) -end - -isopen(s::BufferStream) = s.is_open -function close(s::BufferStream) - s.is_open = false - notify(s.r_c) - notify(s.close_c) - nothing -end -uvfinalize(s::BufferStream) = nothing - -read(s::BufferStream, ::Type{UInt8}) = (wait_readnb(s, 1); read(s.buffer, UInt8)) -unsafe_read(s::BufferStream, a::Ptr{UInt8}, nb::UInt) = (wait_readnb(s, Int(nb)); unsafe_read(s.buffer, a, nb)) -nb_available(s::BufferStream) = nb_available(s.buffer) - -isreadable(s::BufferStream) = s.buffer.readable -iswritable(s::BufferStream) = s.buffer.writable - -function wait_readnb(s::BufferStream, nb::Int) - while isopen(s) && nb_available(s.buffer) < nb - wait(s.r_c) - end -end - -show(io::IO, s::BufferStream) = print(io,"BufferStream() bytes waiting:",nb_available(s.buffer),", isopen:", s.is_open) - -function wait_readbyte(s::BufferStream, c::UInt8) - while isopen(s) && search(s.buffer,c) <= 0 - wait(s.r_c) - end -end - -wait_close(s::BufferStream) = if isopen(s); wait(s.close_c); end -start_reading(s::BufferStream) = Int32(0) -stop_reading(s::BufferStream) = nothing - -write(s::BufferStream, b::UInt8) = write(s, Ref{UInt8}(b)) -function unsafe_write(s::BufferStream, p::Ptr{UInt8}, nb::UInt) - rv = unsafe_write(s.buffer, p, nb) - !(s.buffer_writes) && notify(s.r_c) - return rv -end - -function eof(s::BufferStream) - wait_readnb(s, 1) - return !isopen(s) && nb_available(s)<=0 -end - -# If buffer_writes is called, it will delay notifying waiters till a flush is called. -buffer_writes(s::BufferStream, bufsize=0) = (s.buffer_writes=true; s) -flush(s::BufferStream) = (notify(s.r_c); nothing) diff --git a/julia-0.6.3/share/julia/base/strings/basic.jl b/julia-0.6.3/share/julia/base/strings/basic.jl deleted file mode 100644 index d46e490..0000000 --- a/julia-0.6.3/share/julia/base/strings/basic.jl +++ /dev/null @@ -1,500 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -## core string functions ## - -endof(s::AbstractString) = error("you must implement endof(", typeof(s), ")") -next(s::AbstractString, i::Int) = error("you must implement next(", typeof(s), ",Int)") -next(s::DirectIndexString, i::Int) = (s[i],i+1) -next(s::AbstractString, i::Integer) = next(s,Int(i)) - -string() = "" -string(s::AbstractString) = s - -""" - String(s::AbstractString) - -Convert a string to a contiguous byte array representation encoded as UTF-8 bytes. -This representation is often appropriate for passing strings to C. -""" -String(s::AbstractString) = print_to_string(s) - -convert(::Type{Vector{UInt8}}, s::AbstractString) = convert(Vector{UInt8}, String(s)) -convert(::Type{Array{UInt8}}, s::AbstractString) = convert(Vector{UInt8}, s) -convert(::Type{String}, s::AbstractString) = String(s) -convert(::Type{Vector{Char}}, s::AbstractString) = collect(s) -convert(::Type{Symbol}, s::AbstractString) = Symbol(s) -convert(::Type{String}, s::Symbol) = unsafe_string(Cstring(s)) - -## generic supplied functions ## - -start(s::AbstractString) = 1 -done(s::AbstractString,i) = (i > endof(s)) -getindex(s::AbstractString, i::Int) = next(s,i)[1] -getindex(s::AbstractString, i::Integer) = s[Int(i)] -getindex(s::AbstractString, i::Colon) = s -getindex(s::AbstractString, r::UnitRange{<:Integer}) = s[Int(first(r)):Int(last(r))] -# TODO: handle other ranges with stride ±1 specially? -getindex(s::AbstractString, v::AbstractVector{<:Integer}) = - sprint(length(v), io->(for i in v; write(io,s[i]) end)) -getindex(s::AbstractString, v::AbstractVector{Bool}) = - throw(ArgumentError("logical indexing not supported for strings")) - -Symbol(s::AbstractString) = Symbol(String(s)) - -""" - sizeof(s::AbstractString) - -The number of bytes in string `s`. - -# Example - -```jldoctest -julia> sizeof("❤") -3 -``` -""" -sizeof(s::AbstractString) = error("type $(typeof(s)) has no canonical binary representation") - -eltype(::Type{<:AbstractString}) = Char - -""" -``` -*(s::AbstractString, t::AbstractString) -``` - -Concatenate strings. The `*` operator is an alias to this function. - -# Example - -```jldoctest -julia> "Hello " * "world" -"Hello world" -``` -""" -(*)(s1::AbstractString, ss::AbstractString...) = string(s1, ss...) - -one(::Union{T,Type{T}}) where {T<:AbstractString} = convert(T, "") - -length(s::DirectIndexString) = endof(s) - -""" - length(s::AbstractString) - -The number of characters in string `s`. - -# Example - -```jldoctest -julia> length("jμΛIα") -5 -``` -""" -function length(s::AbstractString) - i = start(s) - if done(s,i) - return 0 - end - n = 1 - while true - c, j = next(s,i) - if done(s,j) - return n - end - n += 1 - i = j - end -end - -## string comparison functions ## - -function cmp(a::AbstractString, b::AbstractString) - if a === b - return 0 - end - i = start(a) - j = start(b) - while !done(a,i) - if done(b,j) - return +1 - end - c, i = next(a,i) - d, j = next(b,j) - if c != d - return c < d ? -1 : +1 - end - end - done(b,j) ? 0 : -1 -end - -==(a::AbstractString, b::AbstractString) = cmp(a,b) == 0 -isless(a::AbstractString, b::AbstractString) = cmp(a,b) < 0 - -# faster comparisons for symbols - -cmp(a::Symbol, b::Symbol) = Int(sign(ccall(:strcmp, Int32, (Cstring, Cstring), a, b))) - -isless(a::Symbol, b::Symbol) = cmp(a,b) < 0 - -## Generic validation functions ## - -isvalid(s::DirectIndexString, i::Integer) = (start(s) <= i <= endof(s)) - -""" - isvalid(str::AbstractString, i::Integer) - -Tells whether index `i` is valid for the given string. - -# Examples - -```jldoctest -julia> str = "αβγdef"; - -julia> isvalid(str, 1) -true - -julia> str[1] -'α': Unicode U+03b1 (category Ll: Letter, lowercase) - -julia> isvalid(str, 2) -false - -julia> str[2] -ERROR: UnicodeError: invalid character index -[...] -``` -""" -function isvalid(s::AbstractString, i::Integer) - i < 1 && return false - done(s,i) && return false - try - next(s,i) - true - catch - false - end -end - -## Generic indexing functions ## - -prevind(s::DirectIndexString, i::Integer) = Int(i)-1 -prevind(s::AbstractArray , i::Integer) = Int(i)-1 -nextind(s::DirectIndexString, i::Integer) = Int(i)+1 -nextind(s::AbstractArray , i::Integer) = Int(i)+1 - -""" - prevind(str::AbstractString, i::Integer) - -Get the previous valid string index before `i`. -Returns a value less than `1` at the beginning of the string. - -# Examples - -```jldoctest -julia> prevind("αβγdef", 3) -1 - -julia> prevind("αβγdef", 1) -0 -``` -""" -function prevind(s::AbstractString, i::Integer) - e = endof(s) - if i > e - return e - end - j = Int(i)-1 - while j >= 1 - if isvalid(s,j) - return j - end - j -= 1 - end - return 0 # out of range -end - -""" - nextind(str::AbstractString, i::Integer) - -Get the next valid string index after `i`. -Returns a value greater than `endof(str)` at or after the end of the string. - -# Examples - -```jldoctest -julia> str = "αβγdef"; - -julia> nextind(str, 1) -3 - -julia> endof(str) -9 - -julia> nextind(str, 9) -10 -``` -""" -function nextind(s::AbstractString, i::Integer) - e = endof(s) - if i < 1 - return 1 - end - if i > e - return Int(i)+1 - end - for j = Int(i)+1:e - if isvalid(s,j) - return j - end - end - next(s,e)[2] # out of range -end - -checkbounds(s::AbstractString, i::Integer) = start(s) <= i <= endof(s) || throw(BoundsError(s, i)) -checkbounds(s::AbstractString, r::Range{<:Integer}) = isempty(r) || (minimum(r) >= start(s) && maximum(r) <= endof(s)) || throw(BoundsError(s, r)) -# The following will end up using a deprecated checkbounds, when the covariant parameter is not Integer -checkbounds(s::AbstractString, I::AbstractArray{<:Real}) = all(i -> checkbounds(s, i), I) -checkbounds(s::AbstractString, I::AbstractArray{<:Integer}) = all(i -> checkbounds(s, i), I) - -ind2chr(s::DirectIndexString, i::Integer) = begin checkbounds(s,i); i end -chr2ind(s::DirectIndexString, i::Integer) = begin checkbounds(s,i); i end - - -""" - ind2chr(s::AbstractString, i::Integer) - -Convert a byte index `i` to a character index with -respect to string `s`. - -See also [`chr2ind`](@ref). - -# Example - -```jldoctest -julia> str = "αβγdef"; - -julia> ind2chr(str, 3) -2 - -julia> chr2ind(str, 2) -3 -``` -""" -function ind2chr(s::AbstractString, i::Integer) - s[i] # throws error if invalid - j = 1 - k = start(s) - while true - c, l = next(s,k) - if i <= k - return j - end - j += 1 - k = l - end -end - -""" - chr2ind(s::AbstractString, i::Integer) - -Convert a character index `i` to a byte index. - -See also [`ind2chr`](@ref). - -# Example - -```jldoctest -julia> str = "αβγdef"; - -julia> chr2ind(str, 2) -3 - -julia> ind2chr(str, 3) -2 -``` -""" -function chr2ind(s::AbstractString, i::Integer) - i < start(s) && throw(BoundsError(s, i)) - j = 1 - k = start(s) - while true - c, l = next(s,k) - if i == j - return k - end - j += 1 - k = l - end -end - -struct EachStringIndex{T<:AbstractString} - s::T -end -eachindex(s::AbstractString) = EachStringIndex(s) - -length(e::EachStringIndex) = length(e.s) -start(e::EachStringIndex) = start(e.s) -next(e::EachStringIndex, state) = (state, nextind(e.s, state)) -done(e::EachStringIndex, state) = done(e.s, state) -eltype(::Type{EachStringIndex}) = Int - -## character column width function ## - -""" - strwidth(s::AbstractString) - -Gives the number of columns needed to print a string. - -# Example - -```jldoctest -julia> strwidth("March") -5 -``` -""" -strwidth(s::AbstractString) = (w=0; for c in s; w += charwidth(c); end; w) - -""" - isascii(c::Union{Char,AbstractString}) -> Bool - -Tests whether a character belongs to the ASCII character set, or whether this is true for -all elements of a string. -""" -isascii(c::Char) = c < Char(0x80) -isascii(s::AbstractString) = all(isascii, s) - -## string promotion rules ## - -promote_rule(::Type{<:AbstractString}, ::Type{<:AbstractString}) = String - -""" - isxdigit(c::Char) -> Bool - -Tests whether a character is a valid hexadecimal digit. Note that this does not -include `x` (as in the standard `0x` prefix). - -# Example - -```jldoctest -julia> isxdigit('a') -true - -julia> isxdigit('x') -false -``` -""" -isxdigit(c::Char) = '0'<=c<='9' || 'a'<=c<='f' || 'A'<=c<='F' - -## uppercase, lowercase, and titlecase transformations ## - -""" - uppercase(s::AbstractString) - -Returns `s` with all characters converted to uppercase. - -# Example - -```jldoctest -julia> uppercase("Julia") -"JULIA" -``` -""" -uppercase(s::AbstractString) = map(uppercase, s) - -""" - lowercase(s::AbstractString) - -Returns `s` with all characters converted to lowercase. - -# Example - -```jldoctest -julia> lowercase("STRINGS AND THINGS") -"strings and things" -``` -""" -lowercase(s::AbstractString) = map(lowercase, s) - -""" - titlecase(s::AbstractString) - -Capitalizes the first character of each word in `s`. - -# Example - -```jldoctest -julia> titlecase("the julia programming language") -"The Julia Programming Language" -``` -""" -function titlecase(s::AbstractString) - startword = true - b = IOBuffer() - for c in s - if isspace(c) - print(b, c) - startword = true - else - print(b, startword ? titlecase(c) : c) - startword = false - end - end - return String(take!(b)) -end - -""" - ucfirst(s::AbstractString) - -Returns `string` with the first character converted to uppercase. - -# Example - -```jldoctest -julia> ucfirst("python") -"Python" -``` -""" -function ucfirst(s::AbstractString) - isempty(s) || isupper(s[1]) ? s : string(uppercase(s[1]),s[nextind(s,1):end]) -end - -""" - lcfirst(s::AbstractString) - -Returns `string` with the first character converted to lowercase. - -# Example - -```jldoctest -julia> lcfirst("Julia") -"julia" -``` -""" -function lcfirst(s::AbstractString) - isempty(s) || islower(s[1]) ? s : string(lowercase(s[1]),s[nextind(s,1):end]) -end - -## string map, filter, has ## - -function map(f, s::AbstractString) - out = IOBuffer(StringVector(endof(s)),true,true) - truncate(out,0) - for c in s - c2 = f(c) - if !isa(c2,Char) - throw(ArgumentError("map(f,s::AbstractString) requires f to return Char; try map(f,collect(s)) or a comprehension instead")) - end - write(out, c2::Char) - end - String(take!(out)) -end - -function filter(f, s::AbstractString) - out = IOBuffer(StringVector(endof(s)),true,true) - truncate(out,0) - for c in s - if f(c) - write(out, c) - end - end - String(take!(out)) -end diff --git a/julia-0.6.3/share/julia/base/strings/errors.jl b/julia-0.6.3/share/julia/base/strings/errors.jl deleted file mode 100644 index 308bfd1..0000000 --- a/julia-0.6.3/share/julia/base/strings/errors.jl +++ /dev/null @@ -1,15 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -## Error messages for Unicode / UTF support - -const UTF_ERR_SHORT = "invalid UTF-8 sequence starting at index <<1>> (0x<<2>> missing one or more continuation bytes)" -const UTF_ERR_INVALID_INDEX = "invalid character index <<1>> (0x<<2>> is a continuation byte)" - -mutable struct UnicodeError <: Exception - errmsg::AbstractString ##< A UTF_ERR_ message - errpos::Int32 ##< Position of invalid character - errchr::UInt32 ##< Invalid character -end - -show(io::IO, exc::UnicodeError) = print(io, replace(replace(string("UnicodeError: ",exc.errmsg), - "<<1>>",string(exc.errpos)),"<<2>>",hex(exc.errchr))) diff --git a/julia-0.6.3/share/julia/base/strings/io.jl b/julia-0.6.3/share/julia/base/strings/io.jl deleted file mode 100644 index 89ae793..0000000 --- a/julia-0.6.3/share/julia/base/strings/io.jl +++ /dev/null @@ -1,451 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -## core text I/O ## - - -""" - print(io::IO, x) - -Write to `io` (or to the default output stream [`STDOUT`](@ref) -if `io` is not given) a canonical (un-decorated) text representation -of a value if there is one, otherwise call [`show`](@ref). -The representation used by `print` includes minimal formatting and tries to -avoid Julia-specific details. - -```jldoctest -julia> print("Hello World!") -Hello World! -julia> io = IOBuffer(); - -julia> print(io, "Hello World!") - -julia> String(take!(io)) -"Hello World!" -``` -""" -function print(io::IO, x) - lock(io) - try - show(io, x) - finally - unlock(io) - end - return nothing -end - -function print(io::IO, xs...) - lock(io) - try - for x in xs - print(io, x) - end - finally - unlock(io) - end - return nothing -end - -""" - println(io::IO, xs...) - -Print (using [`print`](@ref)) `xs` followed by a newline. -If `io` is not supplied, prints to [`STDOUT`](@ref). -""" -println(io::IO, xs...) = print(io, xs..., '\n') - -## conversion of general objects to strings ## - -function sprint(size::Integer, f::Function, args...; env=nothing) - s = IOBuffer(StringVector(size), true, true) - # specialized version of truncate(s,0) - s.size = 0 - s.ptr = 1 - if env !== nothing - f(IOContext(s, env), args...) - else - f(s, args...) - end - String(resize!(s.data, s.size)) -end - -""" - sprint(f::Function, args...) - -Call the given function with an I/O stream and the supplied extra arguments. -Everything written to this I/O stream is returned as a string. - -```jldoctest -julia> sprint(showcompact, 66.66666) -"66.6667" -``` -""" -sprint(f::Function, args...) = sprint(0, f, args...) - -tostr_sizehint(x) = 0 -tostr_sizehint(x::AbstractString) = endof(x) -tostr_sizehint(x::Float64) = 20 -tostr_sizehint(x::Float32) = 12 - -function print_to_string(xs...; env=nothing) - # specialized for performance reasons - s = IOBuffer(StringVector(tostr_sizehint(xs[1])), true, true) - # specialized version of truncate(s,0) - s.size = 0 - s.ptr = 1 - if env !== nothing - env_io = IOContext(s, env) - for x in xs - print(env_io, x) - end - else - for x in xs - print(s, x) - end - end - String(resize!(s.data, s.size)) -end - -string_with_env(env, xs...) = print_to_string(xs...; env=env) - -""" - string(xs...) - -Create a string from any values using the [`print`](@ref) function. - -```jldoctest -julia> string("a", 1, true) -"a1true" -``` -""" -string(xs...) = print_to_string(xs...) - -print(io::IO, s::AbstractString) = (write(io, s); nothing) -write(io::IO, s::AbstractString) = (len = 0; for c in s; len += write(io, c); end; len) -show(io::IO, s::AbstractString) = print_quoted(io, s) - -write(to::AbstractIOBuffer, s::SubString{String}) = - s.endof==0 ? 0 : unsafe_write(to, pointer(s.string, s.offset + 1), UInt(nextind(s, s.endof) - 1)) - -## printing literal quoted string data ## - -# this is the inverse of print_unescaped_chars(io, s, "\\\") - -function print_quoted_literal(io, s::AbstractString) - print(io, '"') - for c = s; c == '"' ? print(io, "\\\"") : print(io, c); end - print(io, '"') -end - -""" - repr(x) - -Create a string from any value using the [`showall`](@ref) function. -""" -function repr(x) - s = IOBuffer() - showall(s, x) - String(take!(s)) -end - -# IOBuffer views of a (byte)string: - -""" - IOBuffer(string::String) - -Create a read-only `IOBuffer` on the data underlying the given string. - -```jldoctest -julia> io = IOBuffer("Haho"); - -julia> String(take!(io)) -"Haho" - -julia> String(take!(io)) -"Haho" -``` -""" -IOBuffer(str::String) = IOBuffer(Vector{UInt8}(str)) -IOBuffer(s::SubString{String}) = IOBuffer(view(Vector{UInt8}(s.string), s.offset + 1 : s.offset + sizeof(s))) - -# join is implemented using IO - -""" - join(io::IO, strings, delim, [last]) - -Join an array of `strings` into a single string, inserting the given delimiter between -adjacent strings. If `last` is given, it will be used instead of `delim` between the last -two strings. For example, - -```jldoctest -julia> join(["apples", "bananas", "pineapples"], ", ", " and ") -"apples, bananas and pineapples" -``` - -`strings` can be any iterable over elements `x` which are convertible to strings -via `print(io::IOBuffer, x)`. `strings` will be printed to `io`. -""" -function join(io::IO, strings, delim, last) - i = start(strings) - if done(strings,i) - return - end - str, i = next(strings,i) - print(io, str) - is_done = done(strings,i) - while !is_done - str, i = next(strings,i) - is_done = done(strings,i) - print(io, is_done ? last : delim) - print(io, str) - end -end - -function join(io::IO, strings, delim) - i = start(strings) - is_done = done(strings,i) - while !is_done - str, i = next(strings,i) - is_done = done(strings,i) - print(io, str) - if !is_done - print(io, delim) - end - end -end -join(io::IO, strings) = join(io, strings, "") -join(args...) = sprint(join, args...) - -## string escaping & unescaping ## - -need_full_hex(s::AbstractString, i::Int) = !done(s,i) && isxdigit(next(s,i)[1]) - -escape_nul(s::AbstractString, i::Int) = - !done(s,i) && '0' <= next(s,i)[1] <= '7' ? "\\x00" : "\\0" - -""" - escape_string([io,] str::AbstractString[, esc::AbstractString]) -> AbstractString - -General escaping of traditional C and Unicode escape sequences. -Any characters in `esc` are also escaped (with a backslash). -See also [`unescape_string`](@ref). -""" -function escape_string(io, s::AbstractString, esc::AbstractString) - i = start(s) - while !done(s,i) - c, j = next(s,i) - c == '\0' ? print(io, escape_nul(s,j)) : - c == '\e' ? print(io, "\\e") : - c == '\\' ? print(io, "\\\\") : - c in esc ? print(io, '\\', c) : - '\a' <= c <= '\r' ? print(io, '\\', "abtnvfr"[Int(c)-6]) : - isprint(c) ? print(io, c) : - c <= '\x7f' ? print(io, "\\x", hex(c, 2)) : - c <= '\uffff' ? print(io, "\\u", hex(c, need_full_hex(s,j) ? 4 : 2)) : - print(io, "\\U", hex(c, need_full_hex(s,j) ? 8 : 4)) - i = j - end -end - -escape_string(s::AbstractString) = sprint(endof(s), escape_string, s, "\"") - -function print_quoted(io, s::AbstractString) - print(io, '"') - escape_string(io, s, "\"\$") #"# work around syntax highlighting problem - print(io, '"') -end - -# bare minimum unescaping function unescapes only given characters - -function print_unescaped_chars(io, s::AbstractString, esc::AbstractString) - if !('\\' in esc) - esc = string("\\", esc) - end - i = start(s) - while !done(s,i) - c, i = next(s,i) - if c == '\\' && !done(s,i) && s[i] in esc - c, i = next(s,i) - end - print(io, c) - end -end - -unescape_chars(s::AbstractString, esc::AbstractString) = - sprint(endof(s), print_unescaped_chars, s, esc) - -# general unescaping of traditional C and Unicode escape sequences - -""" - unescape_string([io,] s::AbstractString) -> AbstractString - -General unescaping of traditional C and Unicode escape sequences. Reverse of -[`escape_string`](@ref). -""" -function unescape_string(io, s::AbstractString) - i = start(s) - while !done(s,i) - c, i = next(s,i) - if !done(s,i) && c == '\\' - c, i = next(s,i) - if c == 'x' || c == 'u' || c == 'U' - n = k = 0 - m = c == 'x' ? 2 : - c == 'u' ? 4 : 8 - while (k+=1) <= m && !done(s,i) - c, j = next(s,i) - n = '0' <= c <= '9' ? n<<4 + c-'0' : - 'a' <= c <= 'f' ? n<<4 + c-'a'+10 : - 'A' <= c <= 'F' ? n<<4 + c-'A'+10 : break - i = j - end - if k == 1 - throw(ArgumentError("invalid $(m == 2 ? "hex (\\x)" : - "unicode (\\u)") escape sequence used in $(repr(s))")) - end - if m == 2 # \x escape sequence - write(io, UInt8(n)) - else - print(io, Char(n)) - end - elseif '0' <= c <= '7' - k = 1 - n = c-'0' - while (k+=1) <= 3 && !done(s,i) - c, j = next(s,i) - n = ('0' <= c <= '7') ? n<<3 + c-'0' : break - i = j - end - if n > 255 - throw(ArgumentError("octal escape sequence out of range")) - end - write(io, UInt8(n)) - else - print(io, c == 'a' ? '\a' : - c == 'b' ? '\b' : - c == 't' ? '\t' : - c == 'n' ? '\n' : - c == 'v' ? '\v' : - c == 'f' ? '\f' : - c == 'r' ? '\r' : - c == 'e' ? '\e' : c) - end - else - print(io, c) - end - end -end - -unescape_string(s::AbstractString) = sprint(endof(s), unescape_string, s) - -macro b_str(s); :(Vector{UInt8}($(unescape_string(s)))); end - -macro raw_str(s); s; end - -## multiline strings ## - -""" -Calculate the width of leading blank space, and also return if string is blank - -Returns: - -* width of leading whitespace, flag if string is totally blank -""" -function indentation(str::AbstractString; tabwidth=8) - count = 0 - for ch in str - if ch == ' ' - count += 1 - elseif ch == '\t' - count = div(count + tabwidth, tabwidth) * tabwidth - else - return count, false - end - end - count, true -end - -""" -Removes leading indentation from string - -Returns: - -* `String` of multiline string, with leading indentation of `indent` removed -""" -function unindent(str::AbstractString, indent::Int; tabwidth=8) - indent == 0 && return str - pos = start(str) - endpos = endof(str) - # Note: this loses the type of the original string - buf = IOBuffer(StringVector(endpos), true, true) - truncate(buf,0) - cutting = true - col = 0 # current column (0 based) - while pos <= endpos - ch, pos = next(str,pos) - if cutting - if ch == ' ' - col += 1 - elseif ch == '\t' - col = div(col + tabwidth, tabwidth) * tabwidth - elseif ch == '\n' - # Now we need to output enough indentation - for i = 1:col-indent - write(buf, ' ') - end - col = 0 - write(buf, '\n') - else - cutting = false - # Now we need to output enough indentation to get to - # correct place - for i = 1:col-indent - write(buf, ' ') - end - col += 1 - write(buf, ch) - end - elseif ch == '\t' # Handle internal tabs - upd = div(col + tabwidth, tabwidth) * tabwidth - # output the number of spaces that would have been seen - # with original indentation - for i = 1:(upd-col) - write(buf, ' ') - end - col = upd - elseif ch == '\n' - cutting = true - col = 0 - write(buf, '\n') - else - col += 1 - write(buf, ch) - end - end - # If we were still "cutting" when we hit the end of the string, - # we need to output the right number of spaces for the indentation - if cutting - for i = 1:col-indent - write(buf, ' ') - end - end - String(take!(buf)) -end - -function convert(::Type{String}, chars::AbstractVector{Char}) - sprint(length(chars), io->begin - state = start(chars) - while !done(chars, state) - c, state = next(chars, state) - if '\ud7ff' < c && c + 1024 < '\ue000' - d, state = next(chars, state) - if '\ud7ff' < d - 1024 && d < '\ue000' - c = Char(0x10000 + ((UInt32(c) & 0x03ff) << 10) | (UInt32(d) & 0x03ff)) - else - write(io, c) - c = d - end - end - write(io, c) - end - end) -end diff --git a/julia-0.6.3/share/julia/base/strings/search.jl b/julia-0.6.3/share/julia/base/strings/search.jl deleted file mode 100644 index c57b376..0000000 --- a/julia-0.6.3/share/julia/base/strings/search.jl +++ /dev/null @@ -1,380 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -const Chars = Union{Char,Tuple{Vararg{Char}},AbstractVector{Char},Set{Char}} - -""" - search(string::AbstractString, chars::Chars, [start::Integer]) - -Search for the first occurrence of the given characters within the given string. The second -argument may be a single character, a vector or a set of characters, a string, or a regular -expression (though regular expressions are only allowed on contiguous strings, such as ASCII -or UTF-8 strings). The third argument optionally specifies a starting index. The return -value is a range of indexes where the matching sequence is found, such that `s[search(s,x)] == x`: - -`search(string, "substring")` = `start:end` such that `string[start:end] == "substring"`, or -`0:-1` if unmatched. - -`search(string, 'c')` = `index` such that `string[index] == 'c'`, or `0` if unmatched. - -```jldoctest -julia> search("Hello to the world", "z") -0:-1 - -julia> search("JuliaLang","Julia") -1:5 -``` -""" -function search(s::AbstractString, c::Chars, i::Integer) - if isempty(c) - return 1 <= i <= nextind(s,endof(s)) ? i : - throw(BoundsError(s, i)) - end - if i < 1 || i > nextind(s,endof(s)) - throw(BoundsError(s, i)) - end - while !done(s,i) - d, j = next(s,i) - if d in c - return i - end - i = j - end - return 0 -end -search(s::AbstractString, c::Chars) = search(s,c,start(s)) - -in(c::Char, s::AbstractString) = (search(s,c)!=0) - -function _searchindex(s, t, i) - if isempty(t) - return 1 <= i <= nextind(s,endof(s)) ? i : - throw(BoundsError(s, i)) - end - t1, j2 = next(t,start(t)) - while true - i = search(s,t1,i) - if i == 0 return 0 end - c, ii = next(s,i) - j = j2; k = ii - matched = true - while !done(t,j) - if done(s,k) - matched = false - break - end - c, k = next(s,k) - d, j = next(t,j) - if c != d - matched = false - break - end - end - if matched - return i - end - i = ii - end -end - -function _search_bloom_mask(c) - UInt64(1) << (c & 63) -end - -_nthbyte(s::String, i) = codeunit(s, i) -_nthbyte(a::ByteArray, i) = a[i] - -function _searchindex(s::Union{String,ByteArray}, t::Union{String,ByteArray}, i) - n = sizeof(t) - m = sizeof(s) - - if n == 0 - return 1 <= i <= m+1 ? max(1, i) : 0 - elseif m == 0 - return 0 - elseif n == 1 - return search(s, _nthbyte(t,1), i) - end - - w = m - n - if w < 0 || i - 1 > w - return 0 - end - - bloom_mask = UInt64(0) - skip = n - 1 - tlast = _nthbyte(t,n) - for j in 1:n - bloom_mask |= _search_bloom_mask(_nthbyte(t,j)) - if _nthbyte(t,j) == tlast && j < n - skip = n - j - 1 - end - end - - i -= 1 - while i <= w - if _nthbyte(s,i+n) == tlast - # check candidate - j = 0 - while j < n - 1 - if _nthbyte(s,i+j+1) != _nthbyte(t,j+1) - break - end - j += 1 - end - - # match found - if j == n - 1 - return i+1 - end - - # no match, try to rule out the next character - if i < w && bloom_mask & _search_bloom_mask(_nthbyte(s,i+n+1)) == 0 - i += n - else - i += skip - end - elseif i < w - if bloom_mask & _search_bloom_mask(_nthbyte(s,i+n+1)) == 0 - i += n - end - end - i += 1 - end - - 0 -end - -searchindex(s::ByteArray, t::ByteArray, i) = _searchindex(s,t,i) - -""" - searchindex(s::AbstractString, substring, [start::Integer]) - -Similar to [`search`](@ref), but return only the start index at which -the substring is found, or `0` if it is not. - -```jldoctest -julia> searchindex("Hello to the world", "z") -0 - -julia> searchindex("JuliaLang","Julia") -1 - -julia> searchindex("JuliaLang","Lang") -6 -``` -""" -searchindex(s::AbstractString, t::AbstractString, i::Integer) = _searchindex(s,t,i) -searchindex(s::AbstractString, t::AbstractString) = searchindex(s,t,start(s)) -searchindex(s::AbstractString, c::Char, i::Integer) = _searchindex(s,c,i) -searchindex(s::AbstractString, c::Char) = searchindex(s,c,start(s)) - -function searchindex(s::String, t::String, i::Integer=1) - # Check for fast case of a single byte - # (for multi-byte UTF-8 sequences, use searchindex on byte arrays instead) - if endof(t) == 1 - search(s, t[1], i) - else - _searchindex(s, t, i) - end -end - -function _search(s, t, i::Integer) - idx = searchindex(s,t,i) - if isempty(t) - idx:idx-1 - else - idx:(idx > 0 ? idx + endof(t) - 1 : -1) - end -end - -search(s::AbstractString, t::AbstractString, i::Integer=start(s)) = _search(s, t, i) -search(s::ByteArray, t::ByteArray, i::Integer=start(s)) = _search(s, t, i) - -function rsearch(s::AbstractString, c::Chars) - j = search(RevString(s), c) - j == 0 && return 0 - endof(s)-j+1 -end - -""" - rsearch(s::AbstractString, chars::Chars, [start::Integer]) - -Similar to [`search`](@ref), but returning the last occurrence of the given characters within the -given string, searching in reverse from `start`. - -```jldoctest -julia> rsearch("aaabbb","b") -6:6 -``` -""" -function rsearch(s::AbstractString, c::Chars, i::Integer) - e = endof(s) - j = search(RevString(s), c, e-i+1) - j == 0 && return 0 - e-j+1 -end - -function _rsearchindex(s, t, i) - if isempty(t) - return 1 <= i <= nextind(s,endof(s)) ? i : - throw(BoundsError(s, i)) - end - t = RevString(t) - rs = RevString(s) - l = endof(s) - t1, j2 = next(t,start(t)) - while true - i = rsearch(s,t1,i) - if i == 0 return 0 end - c, ii = next(rs,l-i+1) - j = j2; k = ii - matched = true - while !done(t,j) - if done(rs,k) - matched = false - break - end - c, k = next(rs,k) - d, j = next(t,j) - if c != d - matched = false - break - end - end - if matched - return nextind(s,l-k+1) - end - i = l-ii+1 - end -end - -function _rsearchindex(s::Union{String,ByteArray}, t::Union{String,ByteArray}, k) - n = sizeof(t) - m = sizeof(s) - - if n == 0 - return 0 <= k <= m ? max(k, 1) : 0 - elseif m == 0 - return 0 - elseif n == 1 - return rsearch(s, _nthbyte(t,1), k) - end - - w = m - n - if w < 0 || k <= 0 - return 0 - end - - bloom_mask = UInt64(0) - skip = n - 1 - tfirst = _nthbyte(t,1) - for j in n:-1:1 - bloom_mask |= _search_bloom_mask(_nthbyte(t,j)) - if _nthbyte(t,j) == tfirst && j > 1 - skip = j - 2 - end - end - - i = min(k - n + 1, w + 1) - while i > 0 - if _nthbyte(s,i) == tfirst - # check candidate - j = 1 - while j < n - if _nthbyte(s,i+j) != _nthbyte(t,j+1) - break - end - j += 1 - end - - # match found - if j == n - return i - end - - # no match, try to rule out the next character - if i > 1 && bloom_mask & _search_bloom_mask(_nthbyte(s,i-1)) == 0 - i -= n - else - i -= skip - end - elseif i > 1 - if bloom_mask & _search_bloom_mask(_nthbyte(s,i-1)) == 0 - i -= n - end - end - i -= 1 - end - - 0 -end - -rsearchindex(s::ByteArray, t::ByteArray, i::Integer) = _rsearchindex(s,t,i) - -""" - rsearchindex(s::AbstractString, substring, [start::Integer]) - -Similar to [`rsearch`](@ref), but return only the start index at which the substring is found, or `0` if it is not. - -```jldoctest -julia> rsearchindex("aaabbb","b") -6 - -julia> rsearchindex("aaabbb","a") -3 -``` -""" -rsearchindex(s::AbstractString, t::AbstractString, i::Integer) = _rsearchindex(s,t,i) -rsearchindex(s::AbstractString, t::AbstractString) = (isempty(s) && isempty(t)) ? 1 : rsearchindex(s,t,endof(s)) - -function rsearchindex(s::String, t::String) - # Check for fast case of a single byte - # (for multi-byte UTF-8 sequences, use rsearchindex instead) - if endof(t) == 1 - rsearch(s, t[1]) - else - _rsearchindex(s, t, sizeof(s)) - end -end - -function rsearchindex(s::String, t::String, i::Integer) - # Check for fast case of a single byte - # (for multi-byte UTF-8 sequences, use rsearchindex instead) - if endof(t) == 1 - rsearch(s, t[1], i) - elseif endof(t) != 0 - _rsearchindex(s, t, nextind(s, i)-1) - elseif i > sizeof(s) - return 0 - elseif i == 0 - return 1 - else - return i - end -end - -function _rsearch(s, t, i::Integer) - idx = rsearchindex(s,t,i) - if isempty(t) - idx:idx-1 - else - idx:(idx > 0 ? idx + endof(t) - 1 : -1) - end -end - -rsearch(s::AbstractString, t::AbstractString, i::Integer=endof(s)) = _rsearch(s, t, i) -rsearch(s::ByteArray, t::ByteArray, i::Integer=endof(s)) = _rsearch(s, t, i) - -""" - contains(haystack::AbstractString, needle::AbstractString) - -Determine whether the second argument is a substring of the first. - -```jldoctest -julia> contains("JuliaLang is pretty cool!", "Julia") -true -``` -""" -contains(haystack::AbstractString, needle::AbstractString) = searchindex(haystack,needle)!=0 - -in(::AbstractString, ::AbstractString) = error("use contains(x,y) for string containment") diff --git a/julia-0.6.3/share/julia/base/strings/string.jl b/julia-0.6.3/share/julia/base/strings/string.jl deleted file mode 100644 index 34eb44c..0000000 --- a/julia-0.6.3/share/julia/base/strings/string.jl +++ /dev/null @@ -1,438 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -const ByteArray = Union{Vector{UInt8},Vector{Int8}} - -## constructors and conversions ## - -# String constructor docstring from boot.jl, workaround for #16730 -# and the unavailability of @doc in boot.jl context. -""" - String(v::Vector{UInt8}) - -Create a new `String` from a vector `v` of bytes containing -UTF-8 encoded characters. This function takes "ownership" of -the array, which means that you should not subsequently modify -`v` (since strings are supposed to be immutable in Julia) for -as long as the string exists. - -If you need to subsequently modify `v`, use `String(copy(v))` instead. -""" -function String(v::Array{UInt8,1}) - ccall(:jl_array_to_string, Ref{String}, (Any,), v) -end - -""" - unsafe_string(p::Ptr{UInt8}, [length::Integer]) - -Copy a string from the address of a C-style (NUL-terminated) string encoded as UTF-8. -(The pointer can be safely freed afterwards.) If `length` is specified -(the length of the data in bytes), the string does not have to be NUL-terminated. - -This function is labelled "unsafe" because it will crash if `p` is not -a valid memory address to data of the requested length. -""" -function unsafe_string(p::Union{Ptr{UInt8},Ptr{Int8}}, len::Integer) - p == C_NULL && throw(ArgumentError("cannot convert NULL to string")) - ccall(:jl_pchar_to_string, Ref{String}, (Ptr{UInt8}, Int), p, len) -end -function unsafe_string(p::Union{Ptr{UInt8},Ptr{Int8}}) - p == C_NULL && throw(ArgumentError("cannot convert NULL to string")) - ccall(:jl_cstr_to_string, Ref{String}, (Ptr{UInt8},), p) -end - -_string_n(n::Integer) = ccall(:jl_alloc_string, Ref{String}, (Csize_t,), n) - -convert(::Type{Vector{UInt8}}, s::String) = ccall(:jl_string_to_array, Ref{Vector{UInt8}}, (Any,), s) -convert(::Type{String}, s::String) = s -convert(::Type{String}, v::Vector{UInt8}) = String(v) - -## low-level functions ## - -pointer(s::String) = unsafe_convert(Ptr{UInt8}, s) -pointer(s::String, i::Integer) = pointer(s)+(i-1) - -sizeof(s::String) = s.len - -""" - codeunit(s::AbstractString, i::Integer) - -Get the `i`th code unit of an encoded string. For example, -returns the `i`th byte of the representation of a UTF-8 string. -""" -codeunit(s::AbstractString, i::Integer) - -@inline function codeunit(s::String, i::Integer) - @boundscheck if (i < 1) | (i > s.len) - throw(BoundsError(s,i)) - end - unsafe_load(pointer(s),i) -end - -write(io::IO, s::String) = unsafe_write(io, pointer(s), reinterpret(UInt, s.len)) - -## comparison ## - -function cmp(a::String, b::String) - c = ccall(:memcmp, Int32, (Ptr{UInt8}, Ptr{UInt8}, UInt), - a, b, min(a.len,b.len)) - return c < 0 ? -1 : c > 0 ? +1 : cmp(a.len,b.len) -end - -function ==(a::String, b::String) - a.len == b.len && 0 == ccall(:memcmp, Int32, (Ptr{UInt8}, Ptr{UInt8}, UInt), a, b, a.len) -end - -## prevind and nextind ## - -function prevind(s::String, i::Integer) - j = Int(i) - e = s.len - if j > e - return endof(s) - end - j -= 1 - @inbounds while j > 0 && is_valid_continuation(codeunit(s,j)) - j -= 1 - end - j -end - -function nextind(s::String, i::Integer) - j = Int(i) - if j < 1 - return 1 - end - e = s.len - j += 1 - @inbounds while j <= e && is_valid_continuation(codeunit(s,j)) - j += 1 - end - j -end - -## checking UTF-8 & ACSII validity ## - -byte_string_classify(data::Vector{UInt8}) = - ccall(:u8_isvalid, Int32, (Ptr{UInt8}, Int), data, length(data)) -byte_string_classify(s::String) = - ccall(:u8_isvalid, Int32, (Ptr{UInt8}, Int), s, s.len) - # 0: neither valid ASCII nor UTF-8 - # 1: valid ASCII - # 2: valid UTF-8 - -isvalid(::Type{String}, s::Union{Vector{UInt8},String}) = byte_string_classify(s) != 0 -isvalid(s::String) = isvalid(String, s) - -## basic UTF-8 decoding & iteration ## - -is_surrogate_lead(c::Unsigned) = ((c & ~0x003ff) == 0xd800) -is_surrogate_trail(c::Unsigned) = ((c & ~0x003ff) == 0xdc00) -is_surrogate_codeunit(c::Unsigned) = ((c & ~0x007ff) == 0xd800) -is_valid_continuation(c) = ((c & 0xc0) == 0x80) - -const utf8_offset = [ - 0x00000000, 0x00003080, - 0x000e2080, 0x03c82080, - 0xfa082080, 0x82082080, -] - -const utf8_trailing = [ - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, - 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, - 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, 3,3,3,3,3,3,3,3,4,4,4,4,5,5,5,5, -] - -## required core functionality ## - -function endof(s::String) - p = pointer(s) - i = s.len - while i > 0 && is_valid_continuation(unsafe_load(p,i)) - i -= 1 - end - i -end - -function length(s::String) - p = pointer(s) - cnum = 0 - for i = 1:s.len - cnum += !is_valid_continuation(unsafe_load(p,i)) - end - cnum -end - -@noinline function slow_utf8_next(p::Ptr{UInt8}, b::UInt8, i::Int, l::Int) - if is_valid_continuation(b) - throw(UnicodeError(UTF_ERR_INVALID_INDEX, i, unsafe_load(p,i))) - end - trailing = utf8_trailing[b + 1] - if l < i + trailing - return '\ufffd', i+1 - end - c::UInt32 = 0 - for j = 1:(trailing + 1) - c <<= 6 - c += unsafe_load(p,i) - i += 1 - end - c -= utf8_offset[trailing + 1] - return Char(c), i -end - -# This implementation relies on `next` returning a value past the end of the -# String's underlying data, which is true for valid Strings -done(s::String, state) = state > s.len - -@inline function next(s::String, i::Int) - # function is split into this critical fast-path - # for pure ascii data, such as parsing numbers, - # and a longer function that can handle any utf8 data - @boundscheck if (i < 1) | (i > s.len) - throw(BoundsError(s,i)) - end - p = pointer(s) - b = unsafe_load(p, i) - if b < 0x80 - return Char(b), i + 1 - end - return slow_utf8_next(p, b, i, s.len) -end - -function first_utf8_byte(ch::Char) - c = UInt32(ch) - b = c < 0x80 ? c%UInt8 : - c < 0x800 ? ((c>>6) | 0xc0)%UInt8 : - c < 0x10000 ? ((c>>12) | 0xe0)%UInt8 : - ((c>>18) | 0xf0)%UInt8 - return b -end - -function reverseind(s::String, i::Integer) - j = s.len + 1 - i - p = pointer(s) - while is_valid_continuation(unsafe_load(p,j)) - j -= 1 - end - return j -end - -## overload methods for efficiency ## - -isvalid(s::String, i::Integer) = - (1 <= i <= s.len) && !is_valid_continuation(unsafe_load(pointer(s),i)) - -function getindex(s::String, r::UnitRange{Int}) - isempty(r) && return "" - i, j = first(r), last(r) - l = s.len - if i < 1 || i > l - throw(BoundsError(s, i)) - end - @inbounds si = codeunit(s, i) - if is_valid_continuation(si) - throw(UnicodeError(UTF_ERR_INVALID_INDEX, i, si)) - end - if j > l - throw(BoundsError()) - end - j = nextind(s,j)-1 - unsafe_string(pointer(s,i), j-i+1) -end - -function search(s::String, c::Char, i::Integer = 1) - if i < 1 || i > sizeof(s) - i == sizeof(s) + 1 && return 0 - throw(BoundsError(s, i)) - end - if is_valid_continuation(codeunit(s,i)) - throw(UnicodeError(UTF_ERR_INVALID_INDEX, i, codeunit(s,i))) - end - c < Char(0x80) && return search(s, c%UInt8, i) - while true - i = search(s, first_utf8_byte(c), i) - (i==0 || s[i] == c) && return i - i = next(s,i)[2] - end -end - -function search(a::Union{String,ByteArray}, b::Union{Int8,UInt8}, i::Integer = 1) - if i < 1 - throw(BoundsError(a, i)) - end - n = sizeof(a) - if i > n - return i == n+1 ? 0 : throw(BoundsError(a, i)) - end - p = pointer(a) - q = ccall(:memchr, Ptr{UInt8}, (Ptr{UInt8}, Int32, Csize_t), p+i-1, b, n-i+1) - q == C_NULL ? 0 : Int(q-p+1) -end - -function search(a::ByteArray, b::Char, i::Integer = 1) - if isascii(b) - search(a,UInt8(b),i) - else - search(a,Vector{UInt8}(string(b)),i).start - end -end - -function rsearch(s::String, c::Char, i::Integer = s.len) - c < Char(0x80) && return rsearch(s, c%UInt8, i) - b = first_utf8_byte(c) - while true - i = rsearch(s, b, i) - (i==0 || s[i] == c) && return i - i = prevind(s,i) - end -end - -function rsearch(a::Union{String,ByteArray}, b::Union{Int8,UInt8}, i::Integer = s.len) - if i < 1 - return i == 0 ? 0 : throw(BoundsError(a, i)) - end - n = sizeof(a) - if i > n - return i == n+1 ? 0 : throw(BoundsError(a, i)) - end - p = pointer(a) - q = ccall(:memrchr, Ptr{UInt8}, (Ptr{UInt8}, Int32, Csize_t), p, b, i) - q == C_NULL ? 0 : Int(q-p+1) -end - -function rsearch(a::ByteArray, b::Char, i::Integer = length(a)) - if isascii(b) - rsearch(a,UInt8(b),i) - else - rsearch(a,Vector{UInt8}(string(b)),i).start - end -end - -## optimized concatenation, reverse, repeat ## - -function string(a::String...) - if length(a) == 1 - return a[1]::String - end - n = 0 - for str in a - n += str.len - end - out = _string_n(n) - offs = 1 - for str in a - unsafe_copy!(pointer(out,offs), pointer(str), str.len) - offs += str.len - end - return out -end - -# UTF-8 encoding length of a character -function codelen(d::Char) - c = UInt32(d) - if c < 0x80 - return 1 - elseif c < 0x800 - return 2 - elseif c < 0x10000 - return 3 - elseif c < 0x110000 - return 4 - end - return 3 # '\ufffd' -end - -function string(a::Union{String,Char}...) - n = 0 - for d in a - if isa(d,Char) - n += codelen(d::Char) - else - n += (d::String).len - end - end - out = _string_n(n) - offs = 1 - p = pointer(out) - for d in a - if isa(d,Char) - c = UInt32(d::Char) - if c < 0x80 - unsafe_store!(p, c%UInt8, offs); offs += 1 - elseif c < 0x800 - unsafe_store!(p, (( c >> 6 ) | 0xC0)%UInt8, offs); offs += 1 - unsafe_store!(p, (( c & 0x3F ) | 0x80)%UInt8, offs); offs += 1 - elseif c < 0x10000 - unsafe_store!(p, (( c >> 12 ) | 0xE0)%UInt8, offs); offs += 1 - unsafe_store!(p, (((c >> 6) & 0x3F ) | 0x80)%UInt8, offs); offs += 1 - unsafe_store!(p, (( c & 0x3F ) | 0x80)%UInt8, offs); offs += 1 - elseif c < 0x110000 - unsafe_store!(p, (( c >> 18 ) | 0xF0)%UInt8, offs); offs += 1 - unsafe_store!(p, (((c >> 12) & 0x3F ) | 0x80)%UInt8, offs); offs += 1 - unsafe_store!(p, (((c >> 6) & 0x3F ) | 0x80)%UInt8, offs); offs += 1 - unsafe_store!(p, (( c & 0x3F ) | 0x80)%UInt8, offs); offs += 1 - else - # '\ufffd' - unsafe_store!(p, 0xef, offs); offs += 1 - unsafe_store!(p, 0xbf, offs); offs += 1 - unsafe_store!(p, 0xbd, offs); offs += 1 - end - else - l = (d::String).len - unsafe_copy!(pointer(out,offs), pointer(d::String), l) - offs += l - end - end - return out -end - -function reverse(s::String) - dat = convert(Vector{UInt8},s) - n = length(dat) - n <= 1 && return s - buf = StringVector(n) - out = n - pos = 1 - @inbounds while out > 0 - ch = dat[pos] - if ch > 0xdf - if ch < 0xf0 - (out -= 3) < 0 && throw(UnicodeError(UTF_ERR_SHORT, pos, ch)) - buf[out + 1], buf[out + 2], buf[out + 3] = ch, dat[pos + 1], dat[pos + 2] - pos += 3 - else - (out -= 4) < 0 && throw(UnicodeError(UTF_ERR_SHORT, pos, ch)) - buf[out+1], buf[out+2], buf[out+3], buf[out+4] = ch, dat[pos+1], dat[pos+2], dat[pos+3] - pos += 4 - end - elseif ch > 0x7f - (out -= 2) < 0 && throw(UnicodeError(UTF_ERR_SHORT, pos, ch)) - buf[out + 1], buf[out + 2] = ch, dat[pos + 1] - pos += 2 - else - buf[out] = ch - out -= 1 - pos += 1 - end - end - String(buf) -end - -function repeat(s::String, r::Integer) - r < 0 && throw(ArgumentError("can't repeat a string $r times")) - n = s.len - out = _string_n(n*r) - if n == 1 # common case: repeating a single ASCII char - ccall(:memset, Ptr{Void}, (Ptr{UInt8}, Cint, Csize_t), out, unsafe_load(pointer(s)), r) - else - for i=1:r - unsafe_copy!(pointer(out, 1+(i-1)*n), pointer(s), n) - end - end - return out -end diff --git a/julia-0.6.3/share/julia/base/strings/strings.jl b/julia-0.6.3/share/julia/base/strings/strings.jl deleted file mode 100644 index bc1f302..0000000 --- a/julia-0.6.3/share/julia/base/strings/strings.jl +++ /dev/null @@ -1,10 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -include("strings/errors.jl") -include("strings/types.jl") -include("strings/basic.jl") -include("strings/search.jl") -include("strings/util.jl") -include("strings/io.jl") -include("strings/utf8proc.jl") -importall .UTF8proc diff --git a/julia-0.6.3/share/julia/base/strings/types.jl b/julia-0.6.3/share/julia/base/strings/types.jl deleted file mode 100644 index 587af56..0000000 --- a/julia-0.6.3/share/julia/base/strings/types.jl +++ /dev/null @@ -1,157 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -# SubString and RevString types - -## substrings reference original strings ## - -struct SubString{T<:AbstractString} <: AbstractString - string::T - offset::Int - endof::Int - - function SubString{T}(s::T, i::Int, j::Int) where T<:AbstractString - if i > endof(s) || j<i - return new(s, i-1, 0) - else - if !isvalid(s,i) - throw(ArgumentError("invalid SubString index")) - end - - while !isvalid(s,j) && j > i - j -= 1 - end - - o = i-1 - new(s, o, max(0, j-o)) - end - end -end -SubString(s::T, i::Int, j::Int) where {T<:AbstractString} = SubString{T}(s, i, j) -SubString(s::SubString, i::Int, j::Int) = SubString(s.string, s.offset+i, s.offset+j) -SubString(s::AbstractString, i::Integer, j::Integer) = SubString(s, Int(i), Int(j)) -SubString(s::AbstractString, i::Integer) = SubString(s, i, endof(s)) - -sizeof(s::SubString{String}) = s.endof == 0 ? 0 : nextind(s, s.endof) - 1 - -# TODO: length(s::SubString) = ?? -# default implementation will work but it's slow -# can this be delegated efficiently somehow? -# that may require additional string interfaces -length(s::SubString{<:DirectIndexString}) = endof(s) - -function length(s::SubString{String}) - return s.endof==0 ? 0 : Int(ccall(:u8_charnum, Csize_t, (Ptr{UInt8}, Csize_t), - pointer(s), nextind(s, s.endof) - 1)) -end - -function next(s::SubString, i::Int) - if i < 1 || i > s.endof - throw(BoundsError(s, i)) - end - c, i = next(s.string, i+s.offset) - c, i-s.offset -end - -function getindex(s::SubString, i::Int) - if i < 1 || i > s.endof - throw(BoundsError(s, i)) - end - getindex(s.string, i+s.offset) -end - -endof(s::SubString) = s.endof - -function isvalid(s::SubString, i::Integer) - return (start(s) <= i <= endof(s)) && isvalid(s.string, s.offset+i) -end - -isvalid(s::SubString{<:DirectIndexString}, i::Integer) = (start(s) <= i <= endof(s)) - -ind2chr(s::SubString{<:DirectIndexString}, i::Integer) = begin checkbounds(s,i); i end -chr2ind(s::SubString{<:DirectIndexString}, i::Integer) = begin checkbounds(s,i); i end - -nextind(s::SubString, i::Integer) = nextind(s.string, i+s.offset)-s.offset -prevind(s::SubString, i::Integer) = prevind(s.string, i+s.offset)-s.offset - -convert(::Type{SubString{T}}, s::T) where {T<:AbstractString} = SubString(s, 1, endof(s)) - -String(p::SubString{String}) = - unsafe_string(pointer(p.string, p.offset+1), nextind(p, p.endof)-1) - -function getindex(s::AbstractString, r::UnitRange{Int}) - checkbounds(s, r) || throw(BoundsError(s, r)) - SubString(s, first(r), last(r)) -end - -function cmp(a::SubString{String}, b::SubString{String}) - na = sizeof(a) - nb = sizeof(b) - c = ccall(:memcmp, Int32, (Ptr{UInt8}, Ptr{UInt8}, UInt), - pointer(a), pointer(b), min(na,nb)) - c < 0 ? -1 : c > 0 ? +1 : cmp(na,nb) -end - -# don't make unnecessary copies when passing substrings to C functions -cconvert(::Type{Ptr{UInt8}}, s::SubString{String}) = s -cconvert(::Type{Ptr{Int8}}, s::SubString{String}) = s -function unsafe_convert(::Type{Ptr{R}}, s::SubString{String}) where R<:Union{Int8, UInt8} - convert(Ptr{R}, pointer(s.string)) + s.offset -end - -## reversed strings without data movement ## - -struct RevString{T<:AbstractString} <: AbstractString - string::T -end - -endof(s::RevString) = endof(s.string) -length(s::RevString) = length(s.string) -sizeof(s::RevString) = sizeof(s.string) - -function next(s::RevString, i::Int) - n = endof(s); j = n-i+1 - (s.string[j], n-prevind(s.string,j)+1) -end - -""" - reverse(s::AbstractString) -> AbstractString - -Reverses a string. -```jldoctest -julia> reverse("JuliaLang") -"gnaLailuJ" -``` -""" -reverse(s::AbstractString) = RevString(s) -reverse(s::RevString) = s.string - -## reverse an index i so that reverse(s)[i] == s[reverseind(s,i)] - -reverseind(s::AbstractString, i) = chr2ind(s, length(s) + 1 - ind2chr(reverse(s), i)) -reverseind(s::Union{DirectIndexString,SubString{DirectIndexString}}, i::Integer) = length(s) + 1 - i -reverseind(s::RevString, i::Integer) = endof(s) - i + 1 -reverseind(s::SubString{String}, i::Integer) = - reverseind(s.string, nextind(s.string, endof(s.string))-s.offset-s.endof+i-1) - s.offset - -function repeat(s::AbstractString, r::Integer) - r < 0 ? throw(ArgumentError("can't repeat a string $r times")) : - r == 0 ? "" : - r == 1 ? s : - repeat(convert(String, s), r) -end - -""" - ^(s::AbstractString, n::Integer) - -Repeat `n` times the string `s`. -The [`repeat`](@ref) function is an alias to this operator. - -```jldoctest -julia> "Test "^3 -"Test Test Test " -``` -""" -(^)(s::AbstractString, r::Integer) = repeat(s,r) - -pointer(x::SubString{String}) = pointer(x.string) + x.offset -pointer(x::SubString{String}, i::Integer) = pointer(x.string) + x.offset + (i-1) diff --git a/julia-0.6.3/share/julia/base/strings/utf8proc.jl b/julia-0.6.3/share/julia/base/strings/utf8proc.jl deleted file mode 100644 index a3ebd46..0000000 --- a/julia-0.6.3/share/julia/base/strings/utf8proc.jl +++ /dev/null @@ -1,398 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -# Various Unicode functionality from the utf8proc library -module UTF8proc - -import Base: show, ==, hash, string, Symbol, isless, length, eltype, start, next, done, convert, isvalid, lowercase, uppercase, titlecase - -export isgraphemebreak, category_code, category_abbrev, category_string - -# also exported by Base: -export normalize_string, graphemes, is_assigned_char, charwidth, isvalid, - islower, isupper, isalpha, isdigit, isnumber, isalnum, - iscntrl, ispunct, isspace, isprint, isgraph - -# whether codepoints are valid Unicode scalar values, i.e. 0-0xd7ff, 0xe000-0x10ffff -isvalid(::Type{Char}, ch::Unsigned) = !((ch - 0xd800 < 0x800) | (ch > 0x10ffff)) -isvalid(::Type{Char}, ch::Integer) = isvalid(Char, Unsigned(ch)) -isvalid(::Type{Char}, ch::Char) = isvalid(Char, UInt32(ch)) - -isvalid(ch::Char) = isvalid(Char, ch) - -# utf8 category constants -const UTF8PROC_CATEGORY_CN = 0 -const UTF8PROC_CATEGORY_LU = 1 -const UTF8PROC_CATEGORY_LL = 2 -const UTF8PROC_CATEGORY_LT = 3 -const UTF8PROC_CATEGORY_LM = 4 -const UTF8PROC_CATEGORY_LO = 5 -const UTF8PROC_CATEGORY_MN = 6 -const UTF8PROC_CATEGORY_MC = 7 -const UTF8PROC_CATEGORY_ME = 8 -const UTF8PROC_CATEGORY_ND = 9 -const UTF8PROC_CATEGORY_NL = 10 -const UTF8PROC_CATEGORY_NO = 11 -const UTF8PROC_CATEGORY_PC = 12 -const UTF8PROC_CATEGORY_PD = 13 -const UTF8PROC_CATEGORY_PS = 14 -const UTF8PROC_CATEGORY_PE = 15 -const UTF8PROC_CATEGORY_PI = 16 -const UTF8PROC_CATEGORY_PF = 17 -const UTF8PROC_CATEGORY_PO = 18 -const UTF8PROC_CATEGORY_SM = 19 -const UTF8PROC_CATEGORY_SC = 20 -const UTF8PROC_CATEGORY_SK = 21 -const UTF8PROC_CATEGORY_SO = 22 -const UTF8PROC_CATEGORY_ZS = 23 -const UTF8PROC_CATEGORY_ZL = 24 -const UTF8PROC_CATEGORY_ZP = 25 -const UTF8PROC_CATEGORY_CC = 26 -const UTF8PROC_CATEGORY_CF = 27 -const UTF8PROC_CATEGORY_CS = 28 -const UTF8PROC_CATEGORY_CO = 29 - -# strings corresponding to the category constants -const category_strings = [ - "Other, not assigned", - "Letter, uppercase", - "Letter, lowercase", - "Letter, titlecase", - "Letter, modifier", - "Letter, other", - "Mark, nonspacing", - "Mark, spacing combining", - "Mark, enclosing", - "Number, decimal digit", - "Number, letter", - "Number, other", - "Punctuation, connector", - "Punctuation, dash", - "Punctuation, open", - "Punctuation, close", - "Punctuation, initial quote", - "Punctuation, final quote", - "Punctuation, other", - "Symbol, math", - "Symbol, currency", - "Symbol, modifier", - "Symbol, other", - "Separator, space", - "Separator, line", - "Separator, paragraph", - "Other, control", - "Other, format", - "Other, surrogate", - "Other, private use" -] - -const UTF8PROC_STABLE = (1<<1) -const UTF8PROC_COMPAT = (1<<2) -const UTF8PROC_COMPOSE = (1<<3) -const UTF8PROC_DECOMPOSE = (1<<4) -const UTF8PROC_IGNORE = (1<<5) -const UTF8PROC_REJECTNA = (1<<6) -const UTF8PROC_NLF2LS = (1<<7) -const UTF8PROC_NLF2PS = (1<<8) -const UTF8PROC_NLF2LF = (UTF8PROC_NLF2LS | UTF8PROC_NLF2PS) -const UTF8PROC_STRIPCC = (1<<9) -const UTF8PROC_CASEFOLD = (1<<10) -const UTF8PROC_CHARBOUND = (1<<11) -const UTF8PROC_LUMP = (1<<12) -const UTF8PROC_STRIPMARK = (1<<13) - -############################################################################ - -utf8proc_error(result) = error(unsafe_string(ccall(:utf8proc_errmsg, Cstring, (Cssize_t,), result))) - -function utf8proc_map(str::String, options::Integer) - nwords = ccall(:utf8proc_decompose, Int, (Ptr{UInt8}, Int, Ptr{UInt8}, Int, Cint), - str, sizeof(str), C_NULL, 0, options) - nwords < 0 && utf8proc_error(nwords) - buffer = Base.StringVector(nwords*4) - nwords = ccall(:utf8proc_decompose, Int, (Ptr{UInt8}, Int, Ptr{UInt8}, Int, Cint), - str, sizeof(str), buffer, nwords, options) - nwords < 0 && utf8proc_error(nwords) - nbytes = ccall(:utf8proc_reencode, Int, (Ptr{UInt8}, Int, Cint), buffer, nwords, options) - nbytes < 0 && utf8proc_error(nbytes) - return String(resize!(buffer, nbytes)) -end - -utf8proc_map(s::AbstractString, flags::Integer) = utf8proc_map(String(s), flags) - -function normalize_string(s::AbstractString; stable::Bool=false, compat::Bool=false, compose::Bool=true, decompose::Bool=false, stripignore::Bool=false, rejectna::Bool=false, newline2ls::Bool=false, newline2ps::Bool=false, newline2lf::Bool=false, stripcc::Bool=false, casefold::Bool=false, lump::Bool=false, stripmark::Bool=false) - flags = 0 - stable && (flags = flags | UTF8PROC_STABLE) - compat && (flags = flags | UTF8PROC_COMPAT) - if decompose - flags = flags | UTF8PROC_DECOMPOSE - elseif compose - flags = flags | UTF8PROC_COMPOSE - elseif compat || stripmark - throw(ArgumentError("compat=true or stripmark=true require compose=true or decompose=true")) - end - stripignore && (flags = flags | UTF8PROC_IGNORE) - rejectna && (flags = flags | UTF8PROC_REJECTNA) - newline2ls + newline2ps + newline2lf > 1 && throw(ArgumentError("only one newline conversion may be specified")) - newline2ls && (flags = flags | UTF8PROC_NLF2LS) - newline2ps && (flags = flags | UTF8PROC_NLF2PS) - newline2lf && (flags = flags | UTF8PROC_NLF2LF) - stripcc && (flags = flags | UTF8PROC_STRIPCC) - casefold && (flags = flags | UTF8PROC_CASEFOLD) - lump && (flags = flags | UTF8PROC_LUMP) - stripmark && (flags = flags | UTF8PROC_STRIPMARK) - utf8proc_map(s, flags) -end - -""" - normalize_string(s::AbstractString, normalform::Symbol) - -Normalize the string `s` according to one of the four "normal forms" of the Unicode -standard: `normalform` can be `:NFC`, `:NFD`, `:NFKC`, or `:NFKD`. Normal forms C -(canonical composition) and D (canonical decomposition) convert different visually identical -representations of the same abstract string into a single canonical form, with form C being -more compact. Normal forms KC and KD additionally canonicalize "compatibility equivalents": -they convert characters that are abstractly similar but visually distinct into a single -canonical choice (e.g. they expand ligatures into the individual characters), with form KC -being more compact. - -Alternatively, finer control and additional transformations may be be obtained by calling -`normalize_string(s; keywords...)`, where any number of the following boolean keywords -options (which all default to `false` except for `compose`) are specified: - -* `compose=false`: do not perform canonical composition -* `decompose=true`: do canonical decomposition instead of canonical composition - (`compose=true` is ignored if present) -* `compat=true`: compatibility equivalents are canonicalized -* `casefold=true`: perform Unicode case folding, e.g. for case-insensitive string comparison -* `newline2lf=true`, `newline2ls=true`, or `newline2ps=true`: convert various newline - sequences (LF, CRLF, CR, NEL) into a linefeed (LF), line-separation (LS), or - paragraph-separation (PS) character, respectively -* `stripmark=true`: strip diacritical marks (e.g. accents) -* `stripignore=true`: strip Unicode's "default ignorable" characters (e.g. the soft hyphen - or the left-to-right marker) -* `stripcc=true`: strip control characters; horizontal tabs and form feeds are converted to - spaces; newlines are also converted to spaces unless a newline-conversion flag was - specified -* `rejectna=true`: throw an error if unassigned code points are found -* `stable=true`: enforce Unicode Versioning Stability - -For example, NFKC corresponds to the options `compose=true, compat=true, stable=true`. -""" -function normalize_string(s::AbstractString, nf::Symbol) - utf8proc_map(s, nf == :NFC ? (UTF8PROC_STABLE | UTF8PROC_COMPOSE) : - nf == :NFD ? (UTF8PROC_STABLE | UTF8PROC_DECOMPOSE) : - nf == :NFKC ? (UTF8PROC_STABLE | UTF8PROC_COMPOSE - | UTF8PROC_COMPAT) : - nf == :NFKD ? (UTF8PROC_STABLE | UTF8PROC_DECOMPOSE - | UTF8PROC_COMPAT) : - throw(ArgumentError(":$nf is not one of :NFC, :NFD, :NFKC, :NFKD"))) -end - -############################################################################ - -""" - charwidth(c) - -Gives the number of columns needed to print a character. -""" -charwidth(c::Char) = Int(ccall(:utf8proc_charwidth, Cint, (UInt32,), c)) - -lowercase(c::Char) = isascii(c) ? ('A' <= c <= 'Z' ? c + 0x20 : c) : Char(ccall(:utf8proc_tolower, UInt32, (UInt32,), c)) -uppercase(c::Char) = isascii(c) ? ('a' <= c <= 'z' ? c - 0x20 : c) : Char(ccall(:utf8proc_toupper, UInt32, (UInt32,), c)) -titlecase(c::Char) = isascii(c) ? ('a' <= c <= 'z' ? c - 0x20 : c) : Char(ccall(:utf8proc_totitle, UInt32, (UInt32,), c)) - -############################################################################ - -# returns UTF8PROC_CATEGORY code in 0:30 giving Unicode category -category_code(c) = ccall(:utf8proc_category, Cint, (UInt32,), c) - -# more human-readable representations of the category code -category_abbrev(c) = unsafe_string(ccall(:utf8proc_category_string, Cstring, (UInt32,), c)) -category_string(c) = category_strings[category_code(c)+1] - -""" - is_assigned_char(c) -> Bool - -Returns `true` if the given char or integer is an assigned Unicode code point. -""" -is_assigned_char(c) = category_code(c) != UTF8PROC_CATEGORY_CN - -## libc character class predicates ## - -""" - islower(c::Char) -> Bool - -Tests whether a character is a lowercase letter. -A character is classified as lowercase if it belongs to Unicode category Ll, -Letter: Lowercase. -""" -islower(c::Char) = (category_code(c) == UTF8PROC_CATEGORY_LL) - -# true for Unicode upper and mixed case - -""" - isupper(c::Char) -> Bool - -Tests whether a character is an uppercase letter. -A character is classified as uppercase if it belongs to Unicode category Lu, -Letter: Uppercase, or Lt, Letter: Titlecase. -""" -function isupper(c::Char) - ccode = category_code(c) - return ccode == UTF8PROC_CATEGORY_LU || ccode == UTF8PROC_CATEGORY_LT -end - -""" - isdigit(c::Char) -> Bool - -Tests whether a character is a numeric digit (0-9). -""" -isdigit(c::Char) = ('0' <= c <= '9') - -""" - isalpha(c::Char) -> Bool - -Tests whether a character is alphabetic. -A character is classified as alphabetic if it belongs to the Unicode general -category Letter, i.e. a character whose category code begins with 'L'. -""" -isalpha(c::Char) = (UTF8PROC_CATEGORY_LU <= category_code(c) <= UTF8PROC_CATEGORY_LO) - -""" - isnumber(c::Char) -> Bool - -Tests whether a character is numeric. -A character is classified as numeric if it belongs to the Unicode general category Number, -i.e. a character whose category code begins with 'N'. -""" -isnumber(c::Char) = (UTF8PROC_CATEGORY_ND <= category_code(c) <= UTF8PROC_CATEGORY_NO) - -""" - isalnum(c::Char) -> Bool - -Tests whether a character is alphanumeric. -A character is classified as alphabetic if it belongs to the Unicode general -category Letter or Number, i.e. a character whose category code begins with 'L' or 'N'. -""" -function isalnum(c::Char) - ccode = category_code(c) - return (UTF8PROC_CATEGORY_LU <= ccode <= UTF8PROC_CATEGORY_LO) || - (UTF8PROC_CATEGORY_ND <= ccode <= UTF8PROC_CATEGORY_NO) -end - -# following C++ only control characters from the Latin-1 subset return true - -""" - iscntrl(c::Char) -> Bool - -Tests whether a character is a control character. -Control characters are the non-printing characters of the Latin-1 subset of Unicode. -""" -iscntrl(c::Char) = (c <= Char(0x1f) || Char(0x7f) <= c <= Char(0x9f)) - -""" - ispunct(c::Char) -> Bool - -Tests whether a character belongs to the Unicode general category Punctuation, i.e. a -character whose category code begins with 'P'. -""" -ispunct(c::Char) = (UTF8PROC_CATEGORY_PC <= category_code(c) <= UTF8PROC_CATEGORY_PO) - -# \u85 is the Unicode Next Line (NEL) character - -""" - isspace(c::Char) -> Bool - -Tests whether a character is any whitespace character. Includes ASCII characters '\\t', -'\\n', '\\v', '\\f', '\\r', and ' ', Latin-1 character U+0085, and characters in Unicode -category Zs. -""" -@inline isspace(c::Char) = c == ' ' || '\t' <= c <='\r' || c == '\u85' || '\ua0' <= c && category_code(c) == UTF8PROC_CATEGORY_ZS - -""" - isprint(c::Char) -> Bool - -Tests whether a character is printable, including spaces, but not a control character. -""" -isprint(c::Char) = (UTF8PROC_CATEGORY_LU <= category_code(c) <= UTF8PROC_CATEGORY_ZS) - -# true in principal if a printer would use ink - -""" - isgraph(c::Char) -> Bool - -Tests whether a character is printable, and not a space. -Any character that would cause a printer to use ink should be -classified with `isgraph(c)==true`. -""" -isgraph(c::Char) = (UTF8PROC_CATEGORY_LU <= category_code(c) <= UTF8PROC_CATEGORY_SO) - -############################################################################ -# iterators for grapheme segmentation - -isgraphemebreak(c1::Char, c2::Char) = - ccall(:utf8proc_grapheme_break, Bool, (UInt32, UInt32), c1, c2) - -# Stateful grapheme break required by Unicode-9 rules: the string -# must be processed in sequence, with state initialized to Ref{Int32}(0). -# Requires utf8proc v2.0 or later. -isgraphemebreak!(state::Ref{Int32}, c1::Char, c2::Char) = - ccall(:utf8proc_grapheme_break_stateful, Bool, (UInt32, UInt32, Ref{Int32}), c1, c2, state) - -struct GraphemeIterator{S<:AbstractString} - s::S # original string (for generation of SubStrings) -end - -""" - graphemes(s::AbstractString) -> GraphemeIterator - -Returns an iterator over substrings of `s` that correspond to the extended graphemes in the -string, as defined by Unicode UAX #29. (Roughly, these are what users would perceive as -single characters, even though they may contain more than one codepoint; for example a -letter combined with an accent mark is a single grapheme.) -""" -graphemes(s::AbstractString) = GraphemeIterator{typeof(s)}(s) - -eltype(::Type{GraphemeIterator{S}}) where {S} = SubString{S} -eltype(::Type{GraphemeIterator{SubString{S}}}) where {S} = SubString{S} - -function length(g::GraphemeIterator) - c0 = Char(0x00ad) # soft hyphen (grapheme break always allowed after this) - n = 0 - state = Ref{Int32}(0) - for c in g.s - n += isgraphemebreak!(state, c0, c) - c0 = c - end - return n -end - -start(g::GraphemeIterator) = (start(g.s), Ref{Int32}(0)) -done(g::GraphemeIterator, i) = done(g.s, i[1]) - -function next(g::GraphemeIterator, i_) - s = g.s - i, state = i_ - j = i - c0, k = next(s, i) - while !done(s, k) # loop until next grapheme is s[i:j] - c, ℓ = next(s, k) - isgraphemebreak!(state, c0, c) && break - j = k - k = ℓ - c0 = c - end - return (SubString(s, i, j), (k, state)) -end - -==(g1::GraphemeIterator, g2::GraphemeIterator) = g1.s == g2.s -hash(g::GraphemeIterator, h::UInt) = hash(g.s, h) -isless(g1::GraphemeIterator, g2::GraphemeIterator) = isless(g1.s, g2.s) - -convert(::Type{S}, g::GraphemeIterator) where {S<:AbstractString} = convert(S, g.s) - -show(io::IO, g::GraphemeIterator{S}) where {S} = print(io, "length-$(length(g)) GraphemeIterator{$S} for \"$(g.s)\"") - -############################################################################ - -end # module diff --git a/julia-0.6.3/share/julia/base/strings/util.jl b/julia-0.6.3/share/julia/base/strings/util.jl deleted file mode 100644 index c4c4459..0000000 --- a/julia-0.6.3/share/julia/base/strings/util.jl +++ /dev/null @@ -1,500 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -# starts with and ends with predicates - -""" - startswith(s::AbstractString, prefix::AbstractString) - -Returns `true` if `s` starts with `prefix`. If `prefix` is a vector or set -of characters, tests whether the first character of `s` belongs to that set. - -See also [`endswith`](@ref). - -```jldoctest -julia> startswith("JuliaLang", "Julia") -true -``` -""" -function startswith(a::AbstractString, b::AbstractString) - i = start(a) - j = start(b) - while !done(a,i) && !done(b,i) - c, i = next(a,i) - d, j = next(b,j) - (c != d) && (return false) - end - done(b,i) -end -startswith(str::AbstractString, chars::Chars) = !isempty(str) && first(str) in chars - -""" - endswith(s::AbstractString, suffix::AbstractString) - -Returns `true` if `s` ends with `suffix`. If `suffix` is a vector or set of -characters, tests whether the last character of `s` belongs to that set. - -See also [`startswith`](@ref). - -```jldoctest -julia> endswith("Sunday", "day") -true -``` -""" -function endswith(a::AbstractString, b::AbstractString) - i = endof(a) - j = endof(b) - a1 = start(a) - b1 = start(b) - while a1 <= i && b1 <= j - c = a[i] - d = b[j] - (c != d) && (return false) - i = prevind(a,i) - j = prevind(b,j) - end - j < b1 -end -endswith(str::AbstractString, chars::Chars) = !isempty(str) && last(str) in chars - -startswith(a::String, b::String) = - (a.len >= b.len && ccall(:memcmp, Int32, (Ptr{UInt8}, Ptr{UInt8}, UInt), a, b, b.len) == 0) -startswith(a::Vector{UInt8}, b::Vector{UInt8}) = - (length(a) >= length(b) && ccall(:memcmp, Int32, (Ptr{UInt8}, Ptr{UInt8}, UInt), a, b, length(b)) == 0) - -# TODO: fast endswith - -""" - chop(s::AbstractString) - -Remove the last character from `s`. - -```jldoctest -julia> a = "March" -"March" - -julia> chop(a) -"Marc" -``` -""" -chop(s::AbstractString) = SubString(s, 1, endof(s)-1) - -""" - chomp(s::AbstractString) - -Remove a single trailing newline from a string. - -```jldoctest -julia> chomp("Hello\\n") -"Hello" -``` -""" -function chomp(s::AbstractString) - i = endof(s) - (i < 1 || s[i] != '\n') && (return SubString(s, 1, i)) - j = prevind(s,i) - (j < 1 || s[j] != '\r') && (return SubString(s, 1, i-1)) - return SubString(s, 1, j-1) -end -function chomp(s::String) - i = endof(s) - if i < 1 || codeunit(s,i) != 0x0a - SubString(s, 1, i) - elseif i < 2 || codeunit(s,i-1) != 0x0d - SubString(s, 1, i-1) - else - SubString(s, 1, i-2) - end -end - -# NOTE: use with caution -- breaks the immutable string convention! -# TODO: this is hard to provide with the new representation -#function chomp!(s::String) -# if !isempty(s) && codeunit(s,s.len) == 0x0a -# n = (endof(s) < 2 || s.data[end-1] != 0x0d) ? 1 : 2 -# ccall(:jl_array_del_end, Void, (Any, UInt), s.data, n) -# end -# return s -#end -chomp!(s::AbstractString) = chomp(s) # copying fallback for other string types - -const _default_delims = [' ','\t','\n','\v','\f','\r'] - -""" - lstrip(s::AbstractString[, chars::Chars]) - -Return `s` with any leading whitespace and delimiters removed. -The default delimiters to remove are `' '`, `\\t`, `\\n`, `\\v`, -`\\f`, and `\\r`. -If `chars` (a character, or vector or set of characters) is provided, -instead remove characters contained in it. - -```jldoctest -julia> a = lpad("March", 20) -" March" - -julia> lstrip(a) -"March" -``` -""" -function lstrip(s::AbstractString, chars::Chars=_default_delims) - i = start(s) - while !done(s,i) - c, j = next(s,i) - if !(c in chars) - return s[i:end] - end - i = j - end - s[end+1:end] -end - -""" - rstrip(s::AbstractString[, chars::Chars]) - -Return `s` with any trailing whitespace and delimiters removed. -The default delimiters to remove are `' '`, `\\t`, `\\n`, `\\v`, -`\\f`, and `\\r`. -If `chars` (a character, or vector or set of characters) is provided, -instead remove characters contained in it. - -```jldoctest -julia> a = rpad("March", 20) -"March " - -julia> rstrip(a) -"March" -``` -""" -function rstrip(s::AbstractString, chars::Chars=_default_delims) - r = RevString(s) - i = start(r) - while !done(r,i) - c, j = next(r,i) - if !(c in chars) - return s[1:end-i+1] - end - i = j - end - s[1:0] -end - -""" - strip(s::AbstractString, [chars::Chars]) - -Return `s` with any leading and trailing whitespace removed. -If `chars` (a character, or vector or set of characters) is provided, -instead remove characters contained in it. - -```jldoctest -julia> strip("{3, 5}\\n", ['{', '}', '\\n']) -"3, 5" -``` -""" -strip(s::AbstractString) = lstrip(rstrip(s)) -strip(s::AbstractString, chars::Chars) = lstrip(rstrip(s, chars), chars) - -## string padding functions ## - -function lpad(s::AbstractString, n::Integer, p::AbstractString=" ") - m = n - strwidth(s) - (m <= 0) && (return s) - l = strwidth(p) - if l==1 - return string(p^m, s) - end - q = div(m,l) - r = m - q*l - i = r != 0 ? chr2ind(p, r) : -1 - string(p^q, p[1:i], s) -end - -function rpad(s::AbstractString, n::Integer, p::AbstractString=" ") - m = n - strwidth(s) - (m <= 0) && (return s) - l = strwidth(p) - if l==1 - return string(s, p^m) - end - q = div(m,l) - r = m - q*l - i = r != 0 ? chr2ind(p, r) : -1 - string(s, p^q, p[1:i]) -end - -""" - lpad(s, n::Integer, p::AbstractString=" ") - -Make a string at least `n` columns wide when printed by padding `s` on the left -with copies of `p`. - -```jldoctest -julia> lpad("March",10) -" March" -``` -""" -lpad(s, n::Integer, p=" ") = lpad(string(s),n,string(p)) - -""" - rpad(s, n::Integer, p::AbstractString=" ") - -Make a string at least `n` columns wide when printed by padding `s` on the right -with copies of `p`. - -```jldoctest -julia> rpad("March",20) -"March " -``` -""" -rpad(s, n::Integer, p=" ") = rpad(string(s),n,string(p)) -cpad(s, n::Integer, p=" ") = rpad(lpad(s,div(n+strwidth(s),2),p),n,p) - -# splitter can be a Char, Vector{Char}, AbstractString, Regex, ... -# any splitter that provides search(s::AbstractString, splitter) -split(str::T, splitter; limit::Integer=0, keep::Bool=true) where {T<:SubString} = - _split(str, splitter, limit, keep, T[]) - -""" - split(s::AbstractString, [chars]; limit::Integer=0, keep::Bool=true) - -Return an array of substrings by splitting the given string on occurrences of the given -character delimiters, which may be specified in any of the formats allowed by `search`'s -second argument (i.e. a single character, collection of characters, string, or regular -expression). If `chars` is omitted, it defaults to the set of all space characters, and -`keep` is taken to be `false`. The two keyword arguments are optional: they are a -maximum size for the result and a flag determining whether empty fields should be kept in -the result. - -```jldoctest -julia> a = "Ma.rch" -"Ma.rch" - -julia> split(a,".") -2-element Array{SubString{String},1}: - "Ma" - "rch" -``` -""" -split(str::T, splitter; limit::Integer=0, keep::Bool=true) where {T<:AbstractString} = - _split(str, splitter, limit, keep, SubString{T}[]) -function _split(str::AbstractString, splitter, limit::Integer, keep_empty::Bool, strs::Array) - i = start(str) - n = endof(str) - r = search(str,splitter,i) - j, k = first(r), nextind(str,last(r)) - while 0 < j <= n && length(strs) != limit-1 - if i < k - if keep_empty || i < j - push!(strs, SubString(str,i,prevind(str,j))) - end - i = k - end - (k <= j) && (k = nextind(str,j)) - r = search(str,splitter,k) - j, k = first(r), nextind(str,last(r)) - end - if keep_empty || !done(str,i) - push!(strs, SubString(str,i)) - end - return strs -end - -# a bit oddball, but standard behavior in Perl, Ruby & Python: -split(str::AbstractString) = split(str, _default_delims; limit=0, keep=false) - -rsplit(str::T, splitter; limit::Integer=0, keep::Bool=true) where {T<:SubString} = - _rsplit(str, splitter, limit, keep, T[]) - -""" - rsplit(s::AbstractString, [chars]; limit::Integer=0, keep::Bool=true) - -Similar to [`split`](@ref), but starting from the end of the string. - -```jldoctest -julia> a = "M.a.r.c.h" -"M.a.r.c.h" - -julia> rsplit(a,".") -5-element Array{SubString{String},1}: - "M" - "a" - "r" - "c" - "h" - -julia> rsplit(a,".";limit=1) -1-element Array{SubString{String},1}: - "M.a.r.c.h" - -julia> rsplit(a,".";limit=2) -2-element Array{SubString{String},1}: - "M.a.r.c" - "h" -``` -""" -rsplit(str::T, splitter; limit::Integer=0, keep::Bool=true) where {T<:AbstractString} = - _rsplit(str, splitter, limit, keep, SubString{T}[]) -function _rsplit(str::AbstractString, splitter, limit::Integer, keep_empty::Bool, strs::Array) - i = start(str) - n = endof(str) - r = rsearch(str,splitter) - j = first(r)-1 - k = last(r) - while((0 <= j < n) && (length(strs) != limit-1)) - if i <= k - (keep_empty || (k < n)) && unshift!(strs, SubString(str,k+1,n)) - n = j - end - (k <= j) && (j = prevind(str,j)) - r = rsearch(str,splitter,j) - j = first(r)-1 - k = last(r) - end - (keep_empty || (n > 0)) && unshift!(strs, SubString(str,1,n)) - return strs -end -#rsplit(str::AbstractString) = rsplit(str, _default_delims, 0, false) - -_replace(io, repl, str, r, pattern) = print(io, repl) -_replace(io, repl::Function, str, r, pattern) = - print(io, repl(SubString(str, first(r), last(r)))) - -function replace(str::String, pattern, repl, limit::Integer) - n = 1 - e = endof(str) - i = a = start(str) - r = search(str,pattern,i) - j, k = first(r), last(r) - out = IOBuffer(StringVector(floor(Int, 1.2sizeof(str))), true, true) - out.size = 0 - out.ptr = 1 - while j != 0 - if i == a || i <= k - unsafe_write(out, pointer(str, i), UInt(j-i)) - _replace(out, repl, str, r, pattern) - end - if k<j - i = j - k = nextind(str, j) - else - i = k = nextind(str, k) - end - if j > e - break - end - r = search(str,pattern,k) - j, k = first(r), last(r) - n == limit && break - n += 1 - end - write(out, SubString(str,i)) - String(take!(out)) -end - -""" - replace(string::AbstractString, pat, r[, n::Integer=0]) - -Search for the given pattern `pat`, and replace each occurrence with `r`. If `n` is -provided, replace at most `n` occurrences. As with search, the second argument may be a -single character, a vector or a set of characters, a string, or a regular expression. If `r` -is a function, each occurrence is replaced with `r(s)` where `s` is the matched substring. -If `pat` is a regular expression and `r` is a `SubstitutionString`, then capture group -references in `r` are replaced with the corresponding matched text. -""" -replace(s::AbstractString, pat, f, n::Integer) = replace(String(s), pat, f, n) -replace(s::AbstractString, pat, r) = replace(s, pat, r, 0) - -# hex <-> bytes conversion - -""" - hex2bytes(s::AbstractString) - -Convert an arbitrarily long hexadecimal string to its binary representation. Returns an -`Array{UInt8,1}`, i.e. an array of bytes. - -```jldoctest -julia> a = hex(12345) -"3039" - -julia> hex2bytes(a) -2-element Array{UInt8,1}: - 0x30 - 0x39 -``` -""" -function hex2bytes(s::AbstractString) - a = zeros(UInt8, div(endof(s), 2)) - i, j = start(s), 0 - while !done(s, i) - c, i = next(s, i) - n = '0' <= c <= '9' ? c - '0' : - 'a' <= c <= 'f' ? c - 'a' + 10 : - 'A' <= c <= 'F' ? c - 'A' + 10 : - throw(ArgumentError("not a hexadecimal string: $(repr(s))")) - done(s, i) && - throw(ArgumentError("string length must be even: length($(repr(s))) == $(length(s))")) - c, i = next(s, i) - n = '0' <= c <= '9' ? n << 4 + c - '0' : - 'a' <= c <= 'f' ? n << 4 + c - 'a' + 10 : - 'A' <= c <= 'F' ? n << 4 + c - 'A' + 10 : - throw(ArgumentError("not a hexadecimal string: $(repr(s))")) - a[j += 1] = n - end - resize!(a, j) - return a -end - -""" - bytes2hex(bin_arr::Array{UInt8, 1}) -> String - -Convert an array of bytes to its hexadecimal representation. -All characters are in lower-case. - -```jldoctest -julia> a = hex(12345) -"3039" - -julia> b = hex2bytes(a) -2-element Array{UInt8,1}: - 0x30 - 0x39 - -julia> bytes2hex(b) -"3039" -``` -""" -function bytes2hex(a::AbstractArray{UInt8}) - b = Vector{UInt8}(2*length(a)) - i = 0 - for x in a - b[i += 1] = hex_chars[1 + x >> 4] - b[i += 1] = hex_chars[1 + x & 0xf] - end - return String(b) -end - -# check for pure ASCII-ness - -function ascii(s::String) - for (i, b) in enumerate(Vector{UInt8}(s)) - b < 0x80 || throw(ArgumentError("invalid ASCII at index $i in $(repr(s))")) - end - return s -end - -""" - ascii(s::AbstractString) - -Convert a string to `String` type and check that it contains only ASCII data, otherwise -throwing an `ArgumentError` indicating the position of the first non-ASCII byte. - -```jldoctest -julia> ascii("abcdeγfgh") -ERROR: ArgumentError: invalid ASCII at index 6 in "abcdeγfgh" -Stacktrace: - [1] ascii(::String) at ./strings/util.jl:479 - -julia> ascii("abcdefgh") -"abcdefgh" -``` -""" -ascii(x::AbstractString) = ascii(convert(String, x)) diff --git a/julia-0.6.3/share/julia/base/subarray.jl b/julia-0.6.3/share/julia/base/subarray.jl deleted file mode 100644 index d4348b8..0000000 --- a/julia-0.6.3/share/julia/base/subarray.jl +++ /dev/null @@ -1,542 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -abstract type AbstractCartesianIndex{N} end # This is a hacky forward declaration for CartesianIndex -const ViewIndex = Union{Real, AbstractArray} -const ScalarIndex = Real - -# L is true if the view itself supports fast linear indexing -struct SubArray{T,N,P,I,L} <: AbstractArray{T,N} - parent::P - indexes::I - offset1::Int # for linear indexing and pointer, only valid when L==true - stride1::Int # used only for linear indexing - function SubArray{T,N,P,I,L}(parent, indexes, offset1, stride1) where {T,N,P,I,L} - @_inline_meta - check_parent_index_match(parent, indexes) - new(parent, indexes, offset1, stride1) - end -end -# Compute the linear indexability of the indices, and combine it with the linear indexing of the parent -function SubArray(parent::AbstractArray, indexes::Tuple) - @_inline_meta - SubArray(IndexStyle(viewindexing(indexes), IndexStyle(parent)), parent, ensure_indexable(indexes), index_dimsum(indexes...)) -end -function SubArray(::IndexCartesian, parent::P, indexes::I, ::NTuple{N,Any}) where {P,I,N} - @_inline_meta - SubArray{eltype(P), N, P, I, false}(parent, indexes, 0, 0) -end -function SubArray(::IndexLinear, parent::P, indexes::I, ::NTuple{N,Any}) where {P,I,N} - @_inline_meta - # Compute the stride and offset - stride1 = compute_stride1(parent, indexes) - SubArray{eltype(P), N, P, I, true}(parent, indexes, compute_offset1(parent, stride1, indexes), stride1) -end - -check_parent_index_match(parent, indexes) = check_parent_index_match(parent, index_ndims(indexes...)) -check_parent_index_match(parent::AbstractArray{T,N}, ::NTuple{N, Bool}) where {T,N} = nothing -check_parent_index_match(parent, ::NTuple{N, Bool}) where {N} = - throw(ArgumentError("number of indices ($N) must match the parent dimensionality ($(ndims(parent)))")) - -# This computes the linear indexing compatability for a given tuple of indices -viewindexing() = IndexLinear() -# Leading scalar indexes simply increase the stride -viewindexing(I::Tuple{ScalarIndex, Vararg{Any}}) = (@_inline_meta; viewindexing(tail(I))) -# Slices may begin a section which may be followed by any number of Slices -viewindexing(I::Tuple{Slice, Slice, Vararg{Any}}) = (@_inline_meta; viewindexing(tail(I))) -# A UnitRange can follow Slices, but only if all other indices are scalar -viewindexing(I::Tuple{Slice, UnitRange, Vararg{ScalarIndex}}) = IndexLinear() -# In general, ranges are only fast if all other indices are scalar -viewindexing(I::Tuple{Union{Range, Slice}, Vararg{ScalarIndex}}) = IndexLinear() -# All other index combinations are slow -viewindexing(I::Tuple{Vararg{Any}}) = IndexCartesian() -# Of course, all other array types are slow -viewindexing(I::Tuple{AbstractArray, Vararg{Any}}) = IndexCartesian() - -# Simple utilities -size(V::SubArray) = (@_inline_meta; map(n->Int(unsafe_length(n)), indices(V))) - -similar(V::SubArray, T::Type, dims::Dims) = similar(V.parent, T, dims) - -parent(V::SubArray) = V.parent -parentindexes(V::SubArray) = V.indexes - -parent(a::AbstractArray) = a -""" - parentindexes(A) - -From an array view `A`, returns the corresponding indexes in the parent. -""" -parentindexes(a::AbstractArray) = ntuple(i->OneTo(size(a,i)), ndims(a)) - -## SubArray creation -# We always assume that the dimensionality of the parent matches the number of -# indices that end up getting passed to it, so we store the parent as a -# ReshapedArray view if necessary. The trouble is that arrays of `CartesianIndex` -# can make the number of effective indices not equal to length(I). -_maybe_reshape_parent(A::AbstractArray, ::NTuple{1, Bool}) = reshape(A, Val{1}) -_maybe_reshape_parent(A::AbstractArray{<:Any,1}, ::NTuple{1, Bool}) = reshape(A, Val{1}) -_maybe_reshape_parent(A::AbstractArray{<:Any,N}, ::NTuple{N, Bool}) where {N} = A -_maybe_reshape_parent(A::AbstractArray, ::NTuple{N, Bool}) where {N} = reshape(A, Val{N}) # TODO: DEPRECATE FOR #14770 -""" - view(A, inds...) - -Like [`getindex`](@ref), but returns a view into the parent array `A` with the -given indices instead of making a copy. Calling [`getindex`](@ref) or -[`setindex!`](@ref) on the returned `SubArray` computes the -indices to the parent array on the fly without checking bounds. - -```jldoctest -julia> A = [1 2; 3 4] -2×2 Array{Int64,2}: - 1 2 - 3 4 - -julia> b = view(A, :, 1) -2-element SubArray{Int64,1,Array{Int64,2},Tuple{Base.Slice{Base.OneTo{Int64}},Int64},true}: - 1 - 3 - -julia> fill!(b, 0) -2-element SubArray{Int64,1,Array{Int64,2},Tuple{Base.Slice{Base.OneTo{Int64}},Int64},true}: - 0 - 0 - -julia> A # Note A has changed even though we modified b -2×2 Array{Int64,2}: - 0 2 - 0 4 -``` -""" -function view(A::AbstractArray, I...) - @_inline_meta - J = to_indices(A, I) - @boundscheck checkbounds(A, J...) - unsafe_view(_maybe_reshape_parent(A, index_ndims(J...)), J...) -end - -function unsafe_view(A::AbstractArray, I::ViewIndex...) - @_inline_meta - SubArray(A, I) -end -# When we take the view of a view, it's often possible to "reindex" the parent -# view's indices such that we can "pop" the parent view and keep just one layer -# of indirection. But we can't always do this because arrays of `CartesianIndex` -# might span multiple parent indices, making the reindex calculation very hard. -# So we use _maybe_reindex to figure out if there are any arrays of -# `CartesianIndex`, and if so, we punt and keep two layers of indirection. -unsafe_view(V::SubArray, I::ViewIndex...) = (@_inline_meta; _maybe_reindex(V, I)) -_maybe_reindex(V, I) = (@_inline_meta; _maybe_reindex(V, I, I)) -_maybe_reindex(V, I, ::Tuple{AbstractArray{<:AbstractCartesianIndex}, Vararg{Any}}) = - (@_inline_meta; SubArray(V, I)) -# But allow arrays of CartesianIndex{1}; they behave just like arrays of Ints -_maybe_reindex(V, I, A::Tuple{AbstractArray{<:AbstractCartesianIndex{1}}, Vararg{Any}}) = - (@_inline_meta; _maybe_reindex(V, I, tail(A))) -_maybe_reindex(V, I, A::Tuple{Any, Vararg{Any}}) = (@_inline_meta; _maybe_reindex(V, I, tail(A))) -function _maybe_reindex(V, I, ::Tuple{}) - @_inline_meta - @inbounds idxs = to_indices(V.parent, reindex(V, V.indexes, I)) - SubArray(V.parent, idxs) -end - -## Re-indexing is the heart of a view, transforming A[i, j][x, y] to A[i[x], j[y]] -# -# Recursively look through the heads of the parent- and sub-indexes, considering -# the following cases: -# * Parent index is array -> re-index that with one or more sub-indexes (one per dimension) -# * Parent index is Colon -> just use the sub-index as provided -# * Parent index is scalar -> that dimension was dropped, so skip the sub-index and use the index as is - -AbstractZeroDimArray{T} = AbstractArray{T, 0} - -reindex(V, ::Tuple{}, ::Tuple{}) = () - -# Skip dropped scalars, so simply peel them off the parent indices and continue -reindex(V, idxs::Tuple{ScalarIndex, Vararg{Any}}, subidxs::Tuple{Vararg{Any}}) = - (@_propagate_inbounds_meta; (idxs[1], reindex(V, tail(idxs), subidxs)...)) - -# Slices simply pass their subindexes straight through -reindex(V, idxs::Tuple{Slice, Vararg{Any}}, subidxs::Tuple{Any, Vararg{Any}}) = - (@_propagate_inbounds_meta; (subidxs[1], reindex(V, tail(idxs), tail(subidxs))...)) - -# Re-index into parent vectors with one subindex -reindex(V, idxs::Tuple{AbstractVector, Vararg{Any}}, subidxs::Tuple{Any, Vararg{Any}}) = - (@_propagate_inbounds_meta; (idxs[1][subidxs[1]], reindex(V, tail(idxs), tail(subidxs))...)) - -# Parent matrices are re-indexed with two sub-indices -reindex(V, idxs::Tuple{AbstractMatrix, Vararg{Any}}, subidxs::Tuple{Any, Any, Vararg{Any}}) = - (@_propagate_inbounds_meta; (idxs[1][subidxs[1], subidxs[2]], reindex(V, tail(idxs), tail(tail(subidxs)))...)) - -# In general, we index N-dimensional parent arrays with N indices -@generated function reindex(V, idxs::Tuple{AbstractArray{T,N}, Vararg{Any}}, subidxs::Tuple{Vararg{Any}}) where {T,N} - if length(subidxs.parameters) >= N - subs = [:(subidxs[$d]) for d in 1:N] - tail = [:(subidxs[$d]) for d in N+1:length(subidxs.parameters)] - :(@_propagate_inbounds_meta; (idxs[1][$(subs...)], reindex(V, tail(idxs), ($(tail...),))...)) - else - :(throw(ArgumentError("cannot re-index $(ndims(V)) dimensional SubArray with fewer than $(ndims(V)) indices\nThis should not occur; please submit a bug report."))) - end -end - -# In general, we simply re-index the parent indices by the provided ones -SlowSubArray{T,N,P,I} = SubArray{T,N,P,I,false} -function getindex(V::SlowSubArray{T,N}, I::Vararg{Int,N}) where {T,N} - @_inline_meta - @boundscheck checkbounds(V, I...) - @inbounds r = V.parent[reindex(V, V.indexes, I)...] - r -end - -FastSubArray{T,N,P,I} = SubArray{T,N,P,I,true} -function getindex(V::FastSubArray, i::Int) - @_inline_meta - @boundscheck checkbounds(V, i) - @inbounds r = V.parent[V.offset1 + V.stride1*i] - r -end -# We can avoid a multiplication if the first parent index is a Colon or UnitRange -FastContiguousSubArray{T,N,P,I<:Tuple{Union{Slice, UnitRange}, Vararg{Any}}} = SubArray{T,N,P,I,true} -function getindex(V::FastContiguousSubArray, i::Int) - @_inline_meta - @boundscheck checkbounds(V, i) - @inbounds r = V.parent[V.offset1 + i] - r -end - -function setindex!(V::SlowSubArray{T,N}, x, I::Vararg{Int,N}) where {T,N} - @_inline_meta - @boundscheck checkbounds(V, I...) - @inbounds V.parent[reindex(V, V.indexes, I)...] = x - V -end -function setindex!(V::FastSubArray, x, i::Int) - @_inline_meta - @boundscheck checkbounds(V, i) - @inbounds V.parent[V.offset1 + V.stride1*i] = x - V -end -function setindex!(V::FastContiguousSubArray, x, i::Int) - @_inline_meta - @boundscheck checkbounds(V, i) - @inbounds V.parent[V.offset1 + i] = x - V -end - -IndexStyle(::Type{<:FastSubArray}) = IndexLinear() -IndexStyle(::Type{<:SubArray}) = IndexCartesian() - -# Strides are the distance between adjacent elements in a given dimension, -# so they are well-defined even for non-linear memory layouts -strides(V::SubArray) = substrides(V.parent, V.indexes) - -substrides(parent, I::Tuple) = substrides(1, parent, 1, I) -substrides(s, parent, dim, ::Tuple{}) = () -substrides(s, parent, dim, I::Tuple{ScalarIndex, Vararg{Any}}) = (substrides(s*size(parent, dim), parent, dim+1, tail(I))...) -substrides(s, parent, dim, I::Tuple{Slice, Vararg{Any}}) = (s, substrides(s*size(parent, dim), parent, dim+1, tail(I))...) -substrides(s, parent, dim, I::Tuple{Range, Vararg{Any}}) = (s*step(I[1]), substrides(s*size(parent, dim), parent, dim+1, tail(I))...) -substrides(s, parent, dim, I::Tuple{Any, Vararg{Any}}) = throw(ArgumentError("strides is invalid for SubArrays with indices of type $(typeof(I[1]))")) - -stride(V::SubArray, d::Integer) = d <= ndims(V) ? strides(V)[d] : strides(V)[end] * size(V)[end] - -compute_stride1(parent::AbstractArray, I::NTuple{N,Any}) where {N} = - (@_inline_meta; compute_stride1(1, fill_to_length(indices(parent), OneTo(1), Val{N}), I)) -compute_stride1(s, inds, I::Tuple{}) = s -compute_stride1(s, inds, I::Tuple{ScalarIndex, Vararg{Any}}) = - (@_inline_meta; compute_stride1(s*unsafe_length(inds[1]), tail(inds), tail(I))) -compute_stride1(s, inds, I::Tuple{Range, Vararg{Any}}) = s*step(I[1]) -compute_stride1(s, inds, I::Tuple{Slice, Vararg{Any}}) = s -compute_stride1(s, inds, I::Tuple{Any, Vararg{Any}}) = throw(ArgumentError("invalid strided index type $(typeof(I[1]))")) - -iscontiguous(A::SubArray) = iscontiguous(typeof(A)) -iscontiguous(::Type{<:SubArray}) = false -iscontiguous(::Type{<:FastContiguousSubArray}) = true - -first_index(V::FastSubArray) = V.offset1 + V.stride1 # cached for fast linear SubArrays -function first_index(V::SubArray) - P, I = parent(V), V.indexes - s1 = compute_stride1(P, I) - s1 + compute_offset1(P, s1, I) -end - -# Computing the first index simply steps through the indices, accumulating the -# sum of index each multiplied by the parent's stride. -# The running sum is `f`; the cumulative stride product is `s`. -# If the parent is a vector, then we offset the parent's own indices with parameters of I -compute_offset1(parent::AbstractVector, stride1::Integer, I::Tuple{Range}) = - (@_inline_meta; first(I[1]) - first(indices1(I[1]))*stride1) -# If the result is one-dimensional and it's a Colon, then linear -# indexing uses the indices along the given dimension. Otherwise -# linear indexing always starts with 1. -compute_offset1(parent, stride1::Integer, I::Tuple) = - (@_inline_meta; compute_offset1(parent, stride1, find_extended_dims(I)..., I)) -compute_offset1(parent, stride1::Integer, dims::Tuple{Int}, inds::Tuple{Slice}, I::Tuple) = - (@_inline_meta; compute_linindex(parent, I) - stride1*first(indices(parent, dims[1]))) # index-preserving case -compute_offset1(parent, stride1::Integer, dims, inds, I::Tuple) = - (@_inline_meta; compute_linindex(parent, I) - stride1) # linear indexing starts with 1 - -function compute_linindex(parent, I::NTuple{N,Any}) where N - @_inline_meta - IP = fill_to_length(indices(parent), OneTo(1), Val{N}) - compute_linindex(1, 1, IP, I) -end -function compute_linindex(f, s, IP::Tuple, I::Tuple{ScalarIndex, Vararg{Any}}) - @_inline_meta - Δi = I[1]-first(IP[1]) - compute_linindex(f + Δi*s, s*unsafe_length(IP[1]), tail(IP), tail(I)) -end -function compute_linindex(f, s, IP::Tuple, I::Tuple{Any, Vararg{Any}}) - @_inline_meta - Δi = first(I[1])-first(IP[1]) - compute_linindex(f + Δi*s, s*unsafe_length(IP[1]), tail(IP), tail(I)) -end -compute_linindex(f, s, IP::Tuple, I::Tuple{}) = f - -find_extended_dims(I) = (@_inline_meta; _find_extended_dims((), (), 1, I...)) -_find_extended_dims(dims, inds, dim) = dims, inds -_find_extended_dims(dims, inds, dim, ::ScalarIndex, I...) = - (@_inline_meta; _find_extended_dims(dims, inds, dim+1, I...)) -_find_extended_dims(dims, inds, dim, i1, I...) = - (@_inline_meta; _find_extended_dims((dims..., dim), (inds..., i1), dim+1, I...)) - -unsafe_convert(::Type{Ptr{T}}, V::SubArray{T,N,P,<:Tuple{Vararg{RangeIndex}}}) where {T,N,P} = - unsafe_convert(Ptr{T}, V.parent) + (first_index(V)-1)*sizeof(T) - -pointer(V::FastSubArray, i::Int) = pointer(V.parent, V.offset1 + V.stride1*i) -pointer(V::FastContiguousSubArray, i::Int) = pointer(V.parent, V.offset1 + i) -pointer(V::SubArray, i::Int) = _pointer(V, i) -_pointer(V::SubArray{<:Any,1}, i::Int) = pointer(V, (i,)) -_pointer(V::SubArray, i::Int) = pointer(V, ind2sub(indices(V), i)) - -function pointer(V::SubArray{T,N,<:Array,<:Tuple{Vararg{RangeIndex}}}, is::Tuple{Vararg{Int}}) where {T,N} - index = first_index(V) - strds = strides(V) - for d = 1:length(is) - index += (is[d]-1)*strds[d] - end - return pointer(V.parent, index) -end - -# indices are taken from the range/vector -# Since bounds-checking is performance-critical and uses -# indices, it's worth optimizing these implementations thoroughly -indices(S::SubArray) = (@_inline_meta; _indices_sub(S, S.indexes...)) -_indices_sub(S::SubArray) = () -_indices_sub(S::SubArray, ::Real, I...) = (@_inline_meta; _indices_sub(S, I...)) -function _indices_sub(S::SubArray, i1::AbstractArray, I...) - @_inline_meta - (unsafe_indices(i1)..., _indices_sub(S, I...)...) -end - -## Compatability -# deprecate? -function parentdims(s::SubArray) - nd = ndims(s) - dimindex = Vector{Int}(nd) - sp = strides(s.parent) - sv = strides(s) - j = 1 - for i = 1:ndims(s.parent) - r = s.indexes[i] - if j <= nd && (isa(r,Union{Slice,Range}) ? sp[i]*step(r) : sp[i]) == sv[j] - dimindex[j] = i - j += 1 - end - end - dimindex -end - -""" - replace_ref_end!(ex) - -Recursively replace occurrences of the symbol :end in a "ref" expression (i.e. A[...]) `ex` -with the appropriate function calls (`endof`, `size` or `trailingsize`). Replacement uses -the closest enclosing ref, so - - A[B[end]] - -should transform to - - A[B[endof(B)]] - -""" -replace_ref_end!(ex) = replace_ref_end_!(ex, nothing)[1] -# replace_ref_end_!(ex,withex) returns (new ex, whether withex was used) -function replace_ref_end_!(ex, withex) - used_withex = false - if isa(ex,Symbol) && ex == :end - withex === nothing && error("Invalid use of end") - return withex, true - elseif isa(ex,Expr) - if ex.head == :ref - ex.args[1], used_withex = replace_ref_end_!(ex.args[1],withex) - S = isa(ex.args[1],Symbol) ? ex.args[1]::Symbol : gensym(:S) # temp var to cache ex.args[1] if needed - used_S = false # whether we actually need S - # new :ref, so redefine withex - nargs = length(ex.args)-1 - if nargs == 0 - return ex, used_withex - elseif nargs == 1 - # replace with endof(S) - ex.args[2], used_S = replace_ref_end_!(ex.args[2],:($endof($S))) - else - n = 1 - J = endof(ex.args) - for j = 2:J-1 - exj, used = replace_ref_end_!(ex.args[j],:($size($S,$n))) - used_S |= used - ex.args[j] = exj - if isa(exj,Expr) && exj.head == :... - # splatted object - exjs = exj.args[1] - n = :($n + length($exjs)) - elseif isa(n, Expr) - # previous expression splatted - n = :($n + 1) - else - # an integer - n += 1 - end - end - ex.args[J], used = replace_ref_end_!(ex.args[J],:($trailingsize($S,$n))) - used_S |= used - end - if used_S && S !== ex.args[1] - S0 = ex.args[1] - ex.args[1] = S - ex = Expr(:let, ex, :($S = $S0)) - end - else - # recursive search - for i = eachindex(ex.args) - ex.args[i], used = replace_ref_end_!(ex.args[i],withex) - used_withex |= used - end - end - end - ex, used_withex -end - -""" - @view A[inds...] - -Creates a `SubArray` from an indexing expression. This can only be applied directly to a -reference expression (e.g. `@view A[1,2:end]`), and should *not* be used as the target of -an assignment (e.g. `@view(A[1,2:end]) = ...`). See also [`@views`](@ref) -to switch an entire block of code to use views for slicing. - -```jldoctest -julia> A = [1 2; 3 4] -2×2 Array{Int64,2}: - 1 2 - 3 4 - -julia> b = @view A[:, 1] -2-element SubArray{Int64,1,Array{Int64,2},Tuple{Base.Slice{Base.OneTo{Int64}},Int64},true}: - 1 - 3 - -julia> fill!(b, 0) -2-element SubArray{Int64,1,Array{Int64,2},Tuple{Base.Slice{Base.OneTo{Int64}},Int64},true}: - 0 - 0 - -julia> A -2×2 Array{Int64,2}: - 0 2 - 0 4 -``` -""" -macro view(ex) - if Meta.isexpr(ex, :ref) - ex = replace_ref_end!(ex) - if Meta.isexpr(ex, :ref) - ex = Expr(:call, view, ex.args...) - else # ex replaced by let ...; foo[...]; end - assert(Meta.isexpr(ex, :let) && Meta.isexpr(ex.args[1], :ref)) - ex.args[1] = Expr(:call, view, ex.args[1].args...) - end - Expr(:&&, true, esc(ex)) - else - throw(ArgumentError("Invalid use of @view macro: argument must be a reference expression A[...].")) - end -end - -############################################################################ -# @views macro code: - -# maybeview is like getindex, but returns a view for slicing operations -# (while remaining equivalent to getindex for scalar indices and non-array types) -@propagate_inbounds maybeview(A, args...) = getindex(A, args...) -@propagate_inbounds maybeview(A::AbstractArray, args...) = view(A, args...) -@propagate_inbounds maybeview(A::AbstractArray, args::Number...) = getindex(A, args...) -@propagate_inbounds maybeview(A) = getindex(A) -@propagate_inbounds maybeview(A::AbstractArray) = getindex(A) - -# _views implements the transformation for the @views macro. -# @views calls esc(_views(...)) to work around #20241, -# so any function calls we insert (to maybeview, or to -# size and endof in replace_ref_end!) must be interpolated -# as values rather than as symbols to ensure that they are called -# from Base rather than from the caller's scope. -_views(x) = x -function _views(ex::Expr) - if ex.head in (:(=), :(.=)) - # don't use view for ref on the lhs of an assignment, - # but still use views for the args of the ref: - lhs = ex.args[1] - Expr(ex.head, Meta.isexpr(lhs, :ref) ? - Expr(:ref, _views.(lhs.args)...) : _views(lhs), - _views(ex.args[2])) - elseif ex.head == :ref - Expr(:call, maybeview, _views.(ex.args)...) - else - h = string(ex.head) - # don't use view on the lhs of an op-assignment a[i...] += ... - if last(h) == '=' && Meta.isexpr(ex.args[1], :ref) - lhs = ex.args[1] - - # temp vars to avoid recomputing a and i, - # which will be assigned in a let block: - a = gensym(:a) - i = [gensym(:i) for k = 1:length(lhs.args)-1] - - # for splatted indices like a[i, j...], we need to - # splat the corresponding temp var. - I = similar(i, Any) - for k = 1:length(i) - if Meta.isexpr(lhs.args[k+1], :...) - I[k] = Expr(:..., i[k]) - lhs.args[k+1] = lhs.args[k+1].args[1] # unsplat - else - I[k] = i[k] - end - end - - Expr(:let, - Expr(first(h) == '.' ? :(.=) : :(=), :($a[$(I...)]), - Expr(:call, Symbol(h[1:end-1]), - :($maybeview($a, $(I...))), - _views.(ex.args[2:end])...)), - :($a = $(_views(lhs.args[1]))), - [:($(i[k]) = $(_views(lhs.args[k+1]))) for k=1:length(i)]...) - else - Expr(ex.head, _views.(ex.args)...) - end - end -end - -""" - @views expression - -Convert every array-slicing operation in the given expression -(which may be a `begin`/`end` block, loop, function, etc.) -to return a view. Scalar indices, non-array types, and -explicit `getindex` calls (as opposed to `array[...]`) are -unaffected. - -Note that the `@views` macro only affects `array[...]` expressions -that appear explicitly in the given `expression`, not array slicing that -occurs in functions called by that code. -""" -macro views(x) - esc(_views(replace_ref_end!(x))) -end diff --git a/julia-0.6.3/share/julia/base/summarysize.jl b/julia-0.6.3/share/julia/base/summarysize.jl deleted file mode 100644 index b7e3205..0000000 --- a/julia-0.6.3/share/julia/base/summarysize.jl +++ /dev/null @@ -1,155 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -struct SummarySize - seen::ObjectIdDict - frontier_x::Vector{Any} - frontier_i::Vector{Int} - exclude::Any - chargeall::Any -end - - -""" - Base.summarysize(obj; exclude=Union{...}, chargeall=Union{...}) -> Int - -Compute the amount of memory used by all unique objects reachable from the argument. - -# Keyword Arguments -- `exclude`: specifies the types of objects to exclude from the traversal. -- `chargeall`: specifies the types of objects to always charge the size of all of their - fields, even if those fields would normally be excluded. -""" -function summarysize(obj::ANY; - exclude::ANY = Union{DataType, TypeName, Method}, - chargeall::ANY = Union{TypeMapEntry, Core.MethodInstance}) - ss = SummarySize(ObjectIdDict(), Any[], Int[], exclude, chargeall) - size::Int = ss(obj) - while !isempty(ss.frontier_x) - # DFS heap traversal of everything without a specialization - # BFS heap traversal of anything with a specialization - x = ss.frontier_x[end] - i = ss.frontier_i[end] - val = nothing - if isa(x, SimpleVector) - nf = length(x) - if isassigned(x, i) - val = x[i] - end - elseif isa(x, Array) - nf = length(x) - if ccall(:jl_array_isassigned, Cint, (Any, UInt), x, i - 1) != 0 - val = x[i] - end - else - nf = nfields(x) - ft = typeof(x).types - if !isbits(ft[i]) && isdefined(x, i) - val = getfield(x, i) - end - end - if nf > i - ss.frontier_i[end] = i + 1 - else - pop!(ss.frontier_x) - pop!(ss.frontier_i) - end - if val !== nothing && !isa(val, Module) && (!isa(val, ss.exclude) || isa(x, ss.chargeall)) - size += ss(val)::Int - end - end - return size -end - -(ss::SummarySize)(obj::ANY) = _summarysize(ss, obj) -# define the general case separately to make sure it is not specialized for every type -@noinline function _summarysize(ss::SummarySize, obj::ANY) - key = pointer_from_objref(obj) - haskey(ss.seen, key) ? (return 0) : (ss.seen[key] = true) - if nfields(obj) > 0 - push!(ss.frontier_x, obj) - push!(ss.frontier_i, 1) - end - if isa(obj, UnionAll) - # black-list of items that don't have a Core.sizeof - return 2 * sizeof(Int) - end - return Core.sizeof(obj) -end - -(::SummarySize)(obj::Symbol) = 0 -(::SummarySize)(obj::SummarySize) = 0 -(::SummarySize)(obj::String) = Core.sizeof(Int) + Core.sizeof(obj) - -function (ss::SummarySize)(obj::DataType) - key = pointer_from_objref(obj) - haskey(ss.seen, key) ? (return 0) : (ss.seen[key] = true) - size::Int = 7 * Core.sizeof(Int) + 6 * Core.sizeof(Int32) - size += 4 * nfields(obj) + ifelse(Sys.WORD_SIZE == 64, 4, 0) - size += ss(obj.parameters)::Int - size += ss(obj.types)::Int - return size -end - -function (ss::SummarySize)(obj::TypeName) - key = pointer_from_objref(obj) - haskey(ss.seen, key) ? (return 0) : (ss.seen[key] = true) - return Core.sizeof(obj) + (isdefined(obj, :mt) ? ss(obj.mt) : 0) -end - -function (ss::SummarySize)(obj::Array) - haskey(ss.seen, obj) ? (return 0) : (ss.seen[obj] = true) - size::Int = Core.sizeof(obj) - # TODO: add size of jl_array_t - if !isbits(eltype(obj)) && !isempty(obj) - push!(ss.frontier_x, obj) - push!(ss.frontier_i, 1) - end - return size -end - -function (ss::SummarySize)(obj::SimpleVector) - key = pointer_from_objref(obj) - haskey(ss.seen, key) ? (return 0) : (ss.seen[key] = true) - size::Int = Core.sizeof(obj) - if !isempty(obj) - push!(ss.frontier_x, obj) - push!(ss.frontier_i, 1) - end - return size -end - -function (ss::SummarySize)(obj::Module) - haskey(ss.seen, obj) ? (return 0) : (ss.seen[obj] = true) - size::Int = Core.sizeof(obj) - for binding in names(obj, true) - if isdefined(obj, binding) && !isdeprecated(obj, binding) - value = getfield(obj, binding) - if !isa(value, Module) || module_parent(value) === obj - size += ss(value)::Int - if isa(value, UnionAll) - value = unwrap_unionall(value) - end - if isa(value, DataType) && value.name.module === obj && value.name.name === binding - # charge a TypeName to its module (but not to the type) - size += ss(value.name)::Int - end - end - end - end - return size -end - -function (ss::SummarySize)(obj::Task) - haskey(ss.seen, obj) ? (return 0) : (ss.seen[obj] = true) - size::Int = Core.sizeof(obj) - if isdefined(obj, :code) - size += ss(obj.code)::Int - end - size += ss(obj.storage)::Int - size += ss(obj.backtrace)::Int - size += ss(obj.donenotify)::Int - size += ss(obj.exception)::Int - size += ss(obj.result)::Int - # TODO: add stack size, and possibly traverse stack roots - return size -end diff --git a/julia-0.6.3/share/julia/base/sysimg.jl b/julia-0.6.3/share/julia/base/sysimg.jl deleted file mode 100644 index 0f7b163..0000000 --- a/julia-0.6.3/share/julia/base/sysimg.jl +++ /dev/null @@ -1,411 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -baremodule Base - -using Core.Intrinsics -ccall(:jl_set_istopmod, Void, (Bool,), true) -function include(path::AbstractString) - local result - if INCLUDE_STATE === 1 - result = Core.include(path) - elseif INCLUDE_STATE === 2 - result = _include(path) - elseif INCLUDE_STATE === 3 - result = include_from_node1(path) - end - result -end -INCLUDE_STATE = 1 # include = Core.include - -include("coreio.jl") - -eval(x) = Core.eval(Base, x) -eval(m, x) = Core.eval(m, x) -VecElement{T}(arg) where {T} = VecElement{T}(convert(T, arg)) -convert(::Type{T}, arg) where {T<:VecElement} = T(arg) -convert(::Type{T}, arg::T) where {T<:VecElement} = arg - -# init core docsystem -import Core: @doc, @__doc__, @doc_str -if isdefined(Core, :Inference) - import Core.Inference.CoreDocs - Core.atdoc!(CoreDocs.docm) -end - -include("exports.jl") - -if false - # simple print definitions for debugging. enable these if something - # goes wrong during bootstrap before printing code is available. - # otherwise, they just just eventually get (noisily) overwritten later - global show, print, println - show(io::IO, x::ANY) = Core.show(io, x) - print(io::IO, a::ANY...) = Core.print(io, a...) - println(io::IO, x::ANY...) = Core.println(io, x...) -end - -## Load essential files and libraries -include("essentials.jl") -include("ctypes.jl") -include("base.jl") -include("generator.jl") -include("reflection.jl") -include("options.jl") - -# core operations & types -include("promotion.jl") -include("tuple.jl") -include("pair.jl") -include("traits.jl") -include("range.jl") -include("twiceprecision.jl") -include("expr.jl") -include("error.jl") - -# core numeric operations & types -include("bool.jl") -include("number.jl") -include("int.jl") -include("operators.jl") -include("pointer.jl") -include("refpointer.jl") -include("checked.jl") -importall .Checked - -# buggy handling of ispure in type-inference means this should be -# after re-defining the basic operations that they might try to call -(::Type{T})(arg) where {T} = convert(T, arg)::T # Hidden from the REPL. - -# vararg Symbol constructor -Symbol(x...) = Symbol(string(x...)) - -# Define the broadcast function, which is mostly implemented in -# broadcast.jl, so that we can overload broadcast methods for -# specific array types etc. -# --Here, just define fallback routines for broadcasting with no arguments -broadcast(f) = f() -broadcast!(f, X::AbstractArray) = (@inbounds for I in eachindex(X); X[I] = f(); end; X) - -# array structures -include("indices.jl") -include("array.jl") -include("abstractarray.jl") -include("subarray.jl") - -# Array convenience converting constructors -Array{T}(m::Integer) where {T} = Array{T,1}(Int(m)) -Array{T}(m::Integer, n::Integer) where {T} = Array{T,2}(Int(m), Int(n)) -Array{T}(m::Integer, n::Integer, o::Integer) where {T} = Array{T,3}(Int(m), Int(n), Int(o)) -Array{T}(d::Integer...) where {T} = Array{T}(convert(Tuple{Vararg{Int}}, d)) - -Vector() = Array{Any,1}(0) -Vector{T}(m::Integer) where {T} = Array{T,1}(Int(m)) -Vector(m::Integer) = Array{Any,1}(Int(m)) -Matrix{T}(m::Integer, n::Integer) where {T} = Matrix{T}(Int(m), Int(n)) -Matrix(m::Integer, n::Integer) = Matrix{Any}(Int(m), Int(n)) - -# numeric operations -include("hashing.jl") -include("rounding.jl") -importall .Rounding -include("float.jl") -include("complex.jl") -include("rational.jl") -include("multinverses.jl") -using .MultiplicativeInverses -include("abstractarraymath.jl") -include("arraymath.jl") - -# define MIME"foo/bar" early so that we can overload 3-arg show -struct MIME{mime} end -macro MIME_str(s) - :(MIME{$(Expr(:quote, Symbol(s)))}) -end - -include("char.jl") -include("strings/string.jl") - -# SIMD loops -include("simdloop.jl") -importall .SimdLoop - -# map-reduce operators -include("reduce.jl") - -## core structures -include("reshapedarray.jl") -include("bitarray.jl") -include("intset.jl") -include("associative.jl") -include("dict.jl") -include("set.jl") -include("iterators.jl") -using .Iterators: zip, enumerate -using .Iterators: Flatten, product # for generators - -# Definition of StridedArray -StridedReshapedArray{T,N,A<:Union{DenseArray,FastContiguousSubArray}} = ReshapedArray{T,N,A} -StridedArray{T,N,A<:Union{DenseArray,StridedReshapedArray}, - I<:Tuple{Vararg{Union{RangeIndex, AbstractCartesianIndex}}}} = - Union{DenseArray{T,N}, SubArray{T,N,A,I}, StridedReshapedArray{T,N}} -StridedVector{T,A<:Union{DenseArray,StridedReshapedArray}, - I<:Tuple{Vararg{Union{RangeIndex, AbstractCartesianIndex}}}} = - Union{DenseArray{T,1}, SubArray{T,1,A,I}, StridedReshapedArray{T,1}} -StridedMatrix{T,A<:Union{DenseArray,StridedReshapedArray}, - I<:Tuple{Vararg{Union{RangeIndex, AbstractCartesianIndex}}}} = - Union{DenseArray{T,2}, SubArray{T,2,A,I}, StridedReshapedArray{T,2}} -StridedVecOrMat{T} = Union{StridedVector{T}, StridedMatrix{T}} - -# For OS specific stuff -include(string((length(Core.ARGS)>=2 ? Core.ARGS[2] : ""), "build_h.jl")) # include($BUILDROOT/base/build_h.jl) -include(string((length(Core.ARGS)>=2 ? Core.ARGS[2] : ""), "version_git.jl")) # include($BUILDROOT/base/version_git.jl) - -include("osutils.jl") -include("c.jl") -include("sysinfo.jl") - -if !isdefined(Core, :Inference) - include("docs/core.jl") - Core.atdoc!(CoreDocs.docm) -end - -# Core I/O -include("io.jl") -include("iostream.jl") -include("iobuffer.jl") - -# strings & printing -include("intfuncs.jl") -include("strings/strings.jl") -include("parse.jl") -include("shell.jl") -include("regex.jl") -include("show.jl") - -# multidimensional arrays -include("cartesian.jl") -using .Cartesian -include("multidimensional.jl") -include("permuteddimsarray.jl") -using .PermutedDimsArrays - -# nullable types -include("nullable.jl") - -include("broadcast.jl") -importall .Broadcast - -# base64 conversions (need broadcast) -include("base64.jl") -importall .Base64 - -# version -include("version.jl") - -# system & environment -include("libc.jl") -using .Libc: getpid, gethostname, time -include("libdl.jl") -using .Libdl: DL_LOAD_PATH -include("env.jl") - -# Scheduling -include("libuv.jl") -include("event.jl") -include("task.jl") -include("lock.jl") -include("threads.jl") -include("weakkeydict.jl") - -# I/O -include("stream.jl") -include("socket.jl") -include("filesystem.jl") -importall .Filesystem -include("process.jl") -include("multimedia.jl") -importall .Multimedia -include("grisu/grisu.jl") -import .Grisu.print_shortest -include("methodshow.jl") - -# core math functions -include("floatfuncs.jl") -include("math.jl") -importall .Math -const (√)=sqrt -const (∛)=cbrt - -let SOURCE_PATH = "" - global function _include(path) - prev = SOURCE_PATH - path = joinpath(dirname(prev),path) - SOURCE_PATH = path - Core.include(path) - SOURCE_PATH = prev - end -end -INCLUDE_STATE = 2 # include = _include (from lines above) - -# reduction along dims -include("reducedim.jl") # macros in this file relies on string.jl - -# basic data structures -include("ordering.jl") -importall .Order - -# Combinatorics -include("sort.jl") -importall .Sort - -function deepcopy_internal end - -# BigInts and BigFloats -include("gmp.jl") -importall .GMP -include("mpfr.jl") -importall .MPFR -big(n::Integer) = convert(BigInt,n) -big(x::AbstractFloat) = convert(BigFloat,x) -big(q::Rational) = big(numerator(q))//big(denominator(q)) - -include("combinatorics.jl") - -# more hashing definitions -include("hashing2.jl") - -# random number generation -include("dSFMT.jl") -include("random.jl") -importall .Random - -# (s)printf macros -include("printf.jl") -importall .Printf - -# metaprogramming -include("meta.jl") - -# enums -include("Enums.jl") -importall .Enums - -# concurrency and parallelism -include("serialize.jl") -importall .Serializer -include("channels.jl") - -# memory-mapped and shared arrays -include("mmap.jl") -import .Mmap - -# utilities - timing, help, edit -include("datafmt.jl") -importall .DataFmt -include("deepcopy.jl") -include("interactiveutil.jl") -include("summarysize.jl") -include("replutil.jl") -include("test.jl") -include("i18n.jl") -using .I18n - -# frontend -include("initdefs.jl") -include("Terminals.jl") -include("LineEdit.jl") -include("REPLCompletions.jl") -include("REPL.jl") -include("client.jl") - -# Stack frames and traces -include("stacktraces.jl") -importall .StackTraces - -# misc useful functions & macros -include("util.jl") - -# dense linear algebra -include("linalg/linalg.jl") -importall .LinAlg -const ⋅ = dot -const × = cross - -# statistics -include("statistics.jl") - -# irrational mathematical constants -include("irrationals.jl") - -# signal processing -include("dft.jl") -importall .DFT -include("dsp.jl") -importall .DSP - -# Fast math -include("fastmath.jl") -importall .FastMath - -# libgit2 support -include("libgit2/libgit2.jl") - -# package manager -include("pkg/pkg.jl") - -# profiler -include("profile.jl") -importall .Profile - -# dates -include("dates/Dates.jl") -import .Dates: Date, DateTime, DateFormat, @dateformat_str, now - -# sparse matrices, vectors, and sparse linear algebra -include("sparse/sparse.jl") -importall .SparseArrays - -include("asyncmap.jl") - -include("distributed/Distributed.jl") -importall .Distributed -include("sharedarray.jl") - -# code loading -include("loading.jl") - -# worker threads -include("threadcall.jl") - -# deprecated functions -include("deprecated.jl") - -# Some basic documentation -include("docs/helpdb.jl") -include("docs/basedocs.jl") - -# Documentation -- should always be included last in sysimg. -include("markdown/Markdown.jl") -include("docs/Docs.jl") -using .Docs, .Markdown -isdefined(Core, :Inference) && Docs.loaddocs(Core.Inference.CoreDocs.DOCS) - -function __init__() - # Base library init - reinit_stdio() - Multimedia.reinit_displays() # since Multimedia.displays uses STDOUT as fallback - early_init() - init_load_path() - Distributed.init_parallel() - init_threadcall() -end - -INCLUDE_STATE = 3 # include = include_from_node1 -include("precompile.jl") - -end # baremodule Base - -using Base -importall Base.Operators - -Base.isfile("userimg.jl") && Base.include("userimg.jl") diff --git a/julia-0.6.3/share/julia/base/sysinfo.jl b/julia-0.6.3/share/julia/base/sysinfo.jl deleted file mode 100644 index de533b2..0000000 --- a/julia-0.6.3/share/julia/base/sysinfo.jl +++ /dev/null @@ -1,219 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -module Sys - -export CPU_CORES, - WORD_SIZE, - ARCH, - MACHINE, - KERNEL, - JIT, - cpu_info, - cpu_name, - cpu_summary, - uptime, - loadavg, - free_memory, - total_memory - -import ..Base: show - -global CPU_CORES -""" - Sys.CPU_CORES - -The number of logical CPU cores available in the system. - -See the Hwloc.jl package for extended information, including number of physical cores. -""" -:CPU_CORES - -""" - Sys.ARCH - -A symbol representing the architecture of the build configuration. -""" -const ARCH = ccall(:jl_get_ARCH, Any, ()) - - -""" - Sys.KERNEL - -A symbol representing the name of the operating system, as returned by `uname` of the build configuration. -""" -const KERNEL = ccall(:jl_get_UNAME, Any, ()) - -""" - Sys.MACHINE - -A string containing the build triple. -""" -const MACHINE = Base.MACHINE - -""" - Sys.WORD_SIZE - -Standard word size on the current machine, in bits. -""" -const WORD_SIZE = Core.sizeof(Int) * 8 - -function __init__() - # set CPU core count - global CPU_CORES = - haskey(ENV,"JULIA_CPU_CORES") ? parse(Int,ENV["JULIA_CPU_CORES"]) : - Int(ccall(:jl_cpu_cores, Int32, ())) - global SC_CLK_TCK = ccall(:jl_SC_CLK_TCK, Clong, ()) - global cpu_name = ccall(:jl_get_cpu_name, Ref{String}, ()) - global JIT = ccall(:jl_get_JIT, Ref{String}, ()) -end - -mutable struct UV_cpu_info_t - model::Ptr{UInt8} - speed::Int32 - cpu_times!user::UInt64 - cpu_times!nice::UInt64 - cpu_times!sys::UInt64 - cpu_times!idle::UInt64 - cpu_times!irq::UInt64 -end -mutable struct CPUinfo - model::String - speed::Int32 - cpu_times!user::UInt64 - cpu_times!nice::UInt64 - cpu_times!sys::UInt64 - cpu_times!idle::UInt64 - cpu_times!irq::UInt64 - CPUinfo(model,speed,u,n,s,id,ir)=new(model,speed,u,n,s,id,ir) -end -CPUinfo(info::UV_cpu_info_t) = CPUinfo(unsafe_string(info.model), info.speed, - info.cpu_times!user, info.cpu_times!nice, info.cpu_times!sys, - info.cpu_times!idle, info.cpu_times!irq) - -show(io::IO, info::CPUinfo) = Base._show_cpuinfo(io, info, true, " ") - -function _cpu_summary(io::IO, cpu::AbstractVector{CPUinfo}, i, j) - if j-i < 9 - header = true - for x = i:j - header || println(io) - Base._show_cpuinfo(io, cpu[x], header, "#$(x-i+1) ") - header = false - end - else - summary = CPUinfo(cpu[i].model,0,0,0,0,0,0) - count = j - i + 1 - for x = i:j - summary.speed += cpu[i].speed - summary.cpu_times!user += cpu[x].cpu_times!user - summary.cpu_times!nice += cpu[x].cpu_times!nice - summary.cpu_times!sys += cpu[x].cpu_times!sys - summary.cpu_times!idle += cpu[x].cpu_times!idle - summary.cpu_times!irq += cpu[x].cpu_times!irq - end - summary.speed = div(summary.speed,count) - Base._show_cpuinfo(io, summary, true, "#1-$(count) ") - end - println(io) -end - -function cpu_summary(io::IO=STDOUT, cpu::AbstractVector{CPUinfo} = cpu_info()) - model = cpu[1].model - first = 1 - for i = 2:length(cpu) - if model != cpu[i].model - _cpu_summary(io, cpu, first, i-1) - first = i - end - end - _cpu_summary(io, cpu, first, length(cpu)) -end - -function cpu_info() - UVcpus = Ref{Ptr{UV_cpu_info_t}}() - count = Ref{Int32}() - Base.uv_error("uv_cpu_info",ccall(:uv_cpu_info, Int32, (Ptr{Ptr{UV_cpu_info_t}}, Ptr{Int32}), UVcpus, count)) - cpus = Vector{CPUinfo}(count[]) - for i = 1:length(cpus) - cpus[i] = CPUinfo(unsafe_load(UVcpus[], i)) - end - ccall(:uv_free_cpu_info, Void, (Ptr{UV_cpu_info_t}, Int32), UVcpus[], count[]) - return cpus -end - -""" - Sys.uptime() - -Gets the current system uptime in seconds. -""" -function uptime() - uptime_ = Ref{Float64}() - Base.uv_error("uv_uptime",ccall(:uv_uptime, Int32, (Ptr{Float64},), uptime_)) - return uptime_[] -end - -""" - Sys.loadavg() - -Get the load average. See: https://en.wikipedia.org/wiki/Load_(computing). -""" -function loadavg() - loadavg_ = Vector{Float64}(3) - ccall(:uv_loadavg, Void, (Ptr{Float64},), loadavg_) - return loadavg_ -end - -free_memory() = ccall(:uv_get_free_memory, UInt64, ()) -total_memory() = ccall(:uv_get_total_memory, UInt64, ()) - -""" - Sys.get_process_title() - -Get the process title. On some systems, will always return an empty string. -""" -function get_process_title() - buf = zeros(UInt8, 512) - err = ccall(:uv_get_process_title, Cint, (Ptr{UInt8}, Cint), buf, 512) - Base.uv_error("get_process_title", err) - return unsafe_string(pointer(buf)) -end - -""" - Sys.set_process_title(title::AbstractString) - -Set the process title. No-op on some operating systems. -""" -function set_process_title(title::AbstractString) - err = ccall(:uv_set_process_title, Cint, (Cstring,), title) - Base.uv_error("set_process_title", err) -end - -""" - Sys.maxrss() - -Get the maximum resident set size utilized in bytes. -See also: - - man page of getrusage(2) on Linux and FreeBSD. - - windows api `GetProcessMemoryInfo` -""" -maxrss() = ccall(:jl_maxrss, Csize_t, ()) - -if is_windows() - function windows_version() - verinfo = ccall(:GetVersion, UInt32, ()) - (Int(verinfo & 0xFF), Int((verinfo >> 8) & 0xFF)) - end -else - windows_version() = (0, 0) -end -""" - Sys.windows_version() - -Returns the version number for the Windows NT Kernel as a (major, minor) pair, -or `(0, 0)` if this is not running on Windows. -""" -windows_version - -const WINDOWS_VISTA_VER = (6, 0) - -end # module Sys diff --git a/julia-0.6.3/share/julia/base/task.jl b/julia-0.6.3/share/julia/base/task.jl deleted file mode 100644 index 5639bb4..0000000 --- a/julia-0.6.3/share/julia/base/task.jl +++ /dev/null @@ -1,372 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -## basic task functions and TLS - -# Container for a captured exception and its backtrace. Can be serialized. -mutable struct CapturedException <: Exception - ex::Any - processed_bt::Vector{Any} - - function CapturedException(ex, bt_raw::Vector{Ptr{Void}}) - # bt_raw MUST be an Array of code pointers than can be processed by jl_lookup_code_address - # Typically the result of a catch_backtrace() - - # Process bt_raw so that it can be safely serialized - bt_lines = Any[] - process_func(args...) = push!(bt_lines, args) - process_backtrace(process_func, bt_raw, 100) # Limiting this to 100 lines. - - CapturedException(ex, bt_lines) - end - - CapturedException(ex, processed_bt::Vector{Any}) = new(ex, processed_bt) -end - -function showerror(io::IO, ce::CapturedException) - showerror(io, ce.ex, ce.processed_bt, backtrace=true) -end - -mutable struct CompositeException <: Exception - exceptions::Vector{Any} - CompositeException() = new(Any[]) - CompositeException(exceptions) = new(exceptions) -end -length(c::CompositeException) = length(c.exceptions) -push!(c::CompositeException, ex) = push!(c.exceptions, ex) -isempty(c::CompositeException) = isempty(c.exceptions) -start(c::CompositeException) = start(c.exceptions) -next(c::CompositeException, state) = next(c.exceptions, state) -done(c::CompositeException, state) = done(c.exceptions, state) - -function showerror(io::IO, ex::CompositeException) - if !isempty(ex) - showerror(io, ex.exceptions[1]) - remaining = length(ex) - 1 - if remaining > 0 - print(io, string("\n\n...and ", remaining, " more exception(s).\n")) - end - else - print(io, "CompositeException()\n") - end -end - -function show(io::IO, t::Task) - print(io, "Task ($(t.state)) @0x$(hex(convert(UInt, pointer_from_objref(t)), Sys.WORD_SIZE>>2))") -end - -""" - @task - -Wrap an expression in a [`Task`](@ref) without executing it, and return the [`Task`](@ref). This only -creates a task, and does not run it. - -```jldoctest -julia> a1() = det(rand(1000, 1000)); - -julia> b = @task a1(); - -julia> istaskstarted(b) -false - -julia> schedule(b); - -julia> yield(); - -julia> istaskdone(b) -true -``` -""" -macro task(ex) - :(Task(()->$(esc(ex)))) -end - -""" - current_task() - -Get the currently running [`Task`](@ref). -""" -current_task() = ccall(:jl_get_current_task, Ref{Task}, ()) - -""" - istaskdone(t::Task) -> Bool - -Determine whether a task has exited. - -```jldoctest -julia> a2() = det(rand(1000, 1000)); - -julia> b = Task(a2); - -julia> istaskdone(b) -false - -julia> schedule(b); - -julia> yield(); - -julia> istaskdone(b) -true -``` -""" -istaskdone(t::Task) = ((t.state == :done) | istaskfailed(t)) - -""" - istaskstarted(t::Task) -> Bool - -Determine whether a task has started executing. - -```jldoctest -julia> a3() = det(rand(1000, 1000)); - -julia> b = Task(a3); - -julia> istaskstarted(b) -false -``` -""" -istaskstarted(t::Task) = ccall(:jl_is_task_started, Cint, (Any,), t) != 0 - -istaskfailed(t::Task) = (t.state == :failed) - -task_result(t::Task) = t.result - -task_local_storage() = get_task_tls(current_task()) -function get_task_tls(t::Task) - if t.storage === nothing - t.storage = ObjectIdDict() - end - (t.storage)::ObjectIdDict -end - -""" - task_local_storage(key) - -Look up the value of a key in the current task's task-local storage. -""" -task_local_storage(key) = task_local_storage()[key] - -""" - task_local_storage(key, value) - -Assign a value to a key in the current task's task-local storage. -""" -task_local_storage(key, val) = (task_local_storage()[key] = val) - -""" - task_local_storage(body, key, value) - -Call the function `body` with a modified task-local storage, in which `value` is assigned to -`key`; the previous value of `key`, or lack thereof, is restored afterwards. Useful -for emulating dynamic scoping. -""" -function task_local_storage(body::Function, key, val) - tls = task_local_storage() - hadkey = haskey(tls,key) - old = get(tls,key,nothing) - tls[key] = val - try body() - finally - hadkey ? (tls[key] = old) : delete!(tls,key) - end -end - -# NOTE: you can only wait for scheduled tasks -function wait(t::Task) - if !istaskdone(t) - if t.donenotify === nothing - t.donenotify = Condition() - end - end - while !istaskdone(t) - wait(t.donenotify) - end - if istaskfailed(t) - throw(t.exception) - end - return task_result(t) -end - -suppress_excp_printing(t::Task) = isa(t.storage, ObjectIdDict) ? get(get_task_tls(t), :SUPPRESS_EXCEPTION_PRINTING, false) : false - -function register_taskdone_hook(t::Task, hook) - tls = get_task_tls(t) - push!(get!(tls, :TASKDONE_HOOKS, []), hook) - t -end - -# runtime system hook called when a task finishes -function task_done_hook(t::Task) - # `finish_task` sets `sigatomic` before entering this function - err = istaskfailed(t) - result = task_result(t) - handled = false - if err - t.backtrace = catch_backtrace() - end - - q = t.consumers - t.consumers = nothing - - if isa(t.donenotify, Condition) && !isempty(t.donenotify.waitq) - handled = true - notify(t.donenotify, result, true, err) - end - - # Execute any other hooks registered in the TLS - if isa(t.storage, ObjectIdDict) && haskey(t.storage, :TASKDONE_HOOKS) - foreach(hook -> hook(t), t.storage[:TASKDONE_HOOKS]) - delete!(t.storage, :TASKDONE_HOOKS) - handled = true - end - - #### un-optimized version - #isa(q,Condition) && notify(q, result, error=err) - if isa(q,Task) - handled = true - nexttask = q - nexttask.state = :runnable - if err - nexttask.exception = result - end - yieldto(nexttask, result) # this terminates the task - elseif isa(q,Condition) && !isempty(q.waitq) - handled = true - notify(q, result, error=err) - end - - if err && !handled - if isa(result,InterruptException) && isdefined(Base,:active_repl_backend) && - active_repl_backend.backend_task.state == :runnable && isempty(Workqueue) && - active_repl_backend.in_eval - throwto(active_repl_backend.backend_task, result) # this terminates the task - end - if !suppress_excp_printing(t) - let bt = t.backtrace - # run a new task to print the error for us - @schedule with_output_color(Base.error_color(), STDERR) do io - print(io, "ERROR (unhandled task failure): ") - showerror(io, result, bt) - println(io) - end - end - end - end - # Clear sigatomic before waiting - sigatomic_end() - wait() # this will not return -end - - -## dynamically-scoped waiting for multiple items -sync_begin() = task_local_storage(:SPAWNS, ([], get(task_local_storage(), :SPAWNS, ()))) - -function sync_end() - spawns = get(task_local_storage(), :SPAWNS, ()) - if spawns === () - error("sync_end() without sync_begin()") - end - refs = spawns[1] - task_local_storage(:SPAWNS, spawns[2]) - - c_ex = CompositeException() - for r in refs - try - wait(r) - catch ex - if !isa(r, Task) || (isa(r, Task) && !istaskfailed(r)) - rethrow(ex) - end - finally - if isa(r, Task) && istaskfailed(r) - push!(c_ex, CapturedException(task_result(r), r.backtrace)) - end - end - end - - if !isempty(c_ex) - throw(c_ex) - end - nothing -end - -""" - @sync - -Wait until all dynamically-enclosed uses of `@async`, `@spawn`, `@spawnat` and `@parallel` -are complete. All exceptions thrown by enclosed async operations are collected and thrown as -a `CompositeException`. -""" -macro sync(block) - quote - sync_begin() - v = $(esc(block)) - sync_end() - v - end -end - -function sync_add(r) - spawns = get(task_local_storage(), :SPAWNS, ()) - if spawns !== () - push!(spawns[1], r) - if isa(r, Task) - tls_r = get_task_tls(r) - tls_r[:SUPPRESS_EXCEPTION_PRINTING] = true - end - end - r -end - -function async_run_thunk(thunk) - t = Task(thunk) - sync_add(t) - enq_work(t) - t -end - -""" - @async - -Like `@schedule`, `@async` wraps an expression in a `Task` and adds it to the local -machine's scheduler queue. Additionally it adds the task to the set of items that the -nearest enclosing `@sync` waits for. -""" -macro async(expr) - thunk = esc(:(()->($expr))) - :(async_run_thunk($thunk)) -end - - -""" - timedwait(testcb::Function, secs::Float64; pollint::Float64=0.1) - -Waits until `testcb` returns `true` or for `secs` seconds, whichever is earlier. -`testcb` is polled every `pollint` seconds. -""" -function timedwait(testcb::Function, secs::Float64; pollint::Float64=0.1) - pollint > 0 || throw(ArgumentError("cannot set pollint to $pollint seconds")) - start = time() - done = Channel(1) - timercb(aw) = begin - try - if testcb() - put!(done, :ok) - elseif (time() - start) > secs - put!(done, :timed_out) - end - catch e - put!(done, :error) - finally - isready(done) && close(aw) - end - end - - if !testcb() - t = Timer(timercb, pollint, pollint) - ret = fetch(done) - close(t) - else - ret = :ok - end - ret -end diff --git a/julia-0.6.3/share/julia/base/test.jl b/julia-0.6.3/share/julia/base/test.jl deleted file mode 100644 index aab6812..0000000 --- a/julia-0.6.3/share/julia/base/test.jl +++ /dev/null @@ -1,1189 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -""" -Simple unit testing functionality: - -* `@test` -* `@test_throws` - -All tests belong to a *test set*. There is a default, task-level -test set that throws on the first failure. Users can choose to wrap -their tests in (possibly nested) test sets that will store results -and summarize them at the end of the test set with `@testset`. -""" -module Test - -export @test, @test_throws, @test_broken, @test_skip, @test_warn, @test_nowarn -export @testset -# Legacy approximate testing functions, yet to be included -export @inferred -export detect_ambiguities -export GenericString - -#----------------------------------------------------------------------- - -# Backtrace utility functions -function ip_matches_func_and_name(ip, func::Symbol, dir::String, file::String) - for fr in StackTraces.lookup(ip) - if fr === StackTraces.UNKNOWN || fr.from_c - return false - end - path = string(fr.file) - fr.func == func && dirname(path) == dir && basename(path) == file && return true - end - return false -end - -function scrub_backtrace(bt) - do_test_ind = findfirst(addr->ip_matches_func_and_name(addr, :do_test, ".", "test.jl"), bt) - if do_test_ind != 0 && length(bt) > do_test_ind - bt = bt[do_test_ind + 1:end] - end - name_ind = findfirst(addr->ip_matches_func_and_name(addr, Symbol("macro expansion"), ".", "test.jl"), bt) - if name_ind != 0 && length(bt) != 0 - bt = bt[1:name_ind] - end - return bt -end - -""" - Result - -All tests produce a result object. This object may or may not be -stored, depending on whether the test is part of a test set. -""" -abstract type Result end - -""" - Pass - -The test condition was true, i.e. the expression evaluated to true or -the correct exception was thrown. -""" -struct Pass <: Result - test_type::Symbol - orig_expr - data - value -end -function Base.show(io::IO, t::Pass) - print_with_color(:green, io, "Test Passed"; bold = true) - if !(t.orig_expr === nothing) - print(io, "\n Expression: ", t.orig_expr) - end - if t.test_type == :test_throws - # The correct type of exception was thrown - print(io, "\n Thrown: ", typeof(t.value)) - elseif t.test_type == :test && isa(t.data,Expr) && t.data.head == :comparison - # The test was an expression, so display the term-by-term - # evaluated version as well - print(io, "\n Evaluated: ", t.data) - end -end - -""" - Fail - -The test condition was false, i.e. the expression evaluated to false or -the correct exception was not thrown. -""" -mutable struct Fail <: Result - test_type::Symbol - orig_expr - data - value -end -function Base.show(io::IO, t::Fail) - print_with_color(Base.error_color(), io, "Test Failed\n"; bold = true) - print(io, " Expression: ", t.orig_expr) - if t.test_type == :test_throws_wrong - # An exception was thrown, but it was of the wrong type - print(io, "\n Expected: ", t.data) - print(io, "\n Thrown: ", typeof(t.value)) - elseif t.test_type == :test_throws_nothing - # An exception was expected, but no exception was thrown - print(io, "\n Expected: ", t.data) - print(io, "\n No exception thrown") - elseif t.test_type == :test && isa(t.data,Expr) && t.data.head == :comparison - # The test was an expression, so display the term-by-term - # evaluated version as well - print(io, "\n Evaluated: ", t.data) - end -end - -""" - Error - -The test condition couldn't be evaluated due to an exception, or -it evaluated to something other than a [`Bool`](@ref). -In the case of `@test_broken` it is used to indicate that an -unexpected `Pass` `Result` occurred. -""" -mutable struct Error <: Result - test_type::Symbol - orig_expr - value - backtrace -end -function Base.show(io::IO, t::Error) - print_with_color(Base.error_color(), io, "Error During Test\n"; bold = true) - if t.test_type == :test_nonbool - println(io, " Expression evaluated to non-Boolean") - println(io, " Expression: ", t.orig_expr) - print( io, " Value: ", t.value) - elseif t.test_type == :test_error - println(io, " Test threw an exception of type ", typeof(t.value)) - println(io, " Expression: ", t.orig_expr) - # Capture error message and indent to match - errmsg = sprint(showerror, t.value, scrub_backtrace(t.backtrace)) - print(io, join(map(line->string(" ",line), - split(errmsg, "\n")), "\n")) - elseif t.test_type == :test_unbroken - # A test that was expected to fail did not - println(io, " Unexpected Pass") - println(io, " Expression: ", t.orig_expr) - println(io, " Got correct result, please change to @test if no longer broken.") - elseif t.test_type == :nontest_error - # we had an error outside of a @test - println(io, " Got an exception of type $(typeof(t.value)) outside of a @test") - # Capture error message and indent to match - errmsg = sprint(showerror, t.value, t.backtrace) - print(io, join(map(line->string(" ",line), - split(errmsg, "\n")), "\n")) - end -end - -""" - Broken - -The test condition is the expected (failed) result of a broken test, -or was explicitly skipped with `@test_skip`. -""" -mutable struct Broken <: Result - test_type::Symbol - orig_expr -end -function Base.show(io::IO, t::Broken) - print_with_color(Base.warn_color(), io, "Test Broken\n"; bold = true) - if t.test_type == :skipped && !(t.orig_expr === nothing) - println(io, " Skipped: ", t.orig_expr) - elseif !(t.orig_expr === nothing) - println(io, "Expression: ", t.orig_expr) - end -end - -#----------------------------------------------------------------------- - -abstract type ExecutionResult end - -struct Returned <: ExecutionResult - value - data -end - -struct Threw <: ExecutionResult - exception - backtrace -end - -function eval_comparison(evaluated::Expr, quoted::Expr) - res = true - i = 1 - args = evaluated.args - quoted_args = quoted.args - n = length(args) - while i < n - a, op, b = args[i], args[i+1], args[i+2] - if res - res = op(a, b) === true # Keep `res` type stable - end - quoted_args[i] = a - quoted_args[i+2] = b - i += 2 - end - Returned(res, quoted) -end - -const comparison_prec = Base.operator_precedence(:(==)) - -""" - test_expr!(ex, kws...) - -Preprocess test expressions of function calls with trailing keyword arguments -so that e.g. `@test a ≈ b atol=ε` means `@test ≈(a, b, atol=ε)`. -""" -test_expr!(m, ex) = ex - -function test_expr!(m, ex, kws...) - ex isa Expr && ex.head == :call || @goto fail - for kw in kws - kw isa Expr && kw.head == :(=) || @goto fail - kw.head = :kw - push!(ex.args, kw) - end - return ex -@label fail - error("invalid test macro call: $m $ex $(join(kws," "))") -end - -# @test - check if the expression evaluates to true -""" - @test ex - @test f(args...) key=val ... - -Tests that the expression `ex` evaluates to `true`. -Returns a `Pass` `Result` if it does, a `Fail` `Result` if it is -`false`, and an `Error` `Result` if it could not be evaluated. - -The `@test f(args...) key=val...` form is equivalent to writing -`@test f(args..., key=val...)` which can be useful when the expression -is a call using infix syntax such as approximate comparisons: - - @test a ≈ b atol=ε - -This is equivalent to the uglier test `@test ≈(a, b, atol=ε)`. -It is an error to supply more than one expression unless the first -is a call expression and the rest are assignments (`k=v`). -""" -macro test(ex, kws...) - test_expr!("@test", ex, kws...) - orig_ex = Expr(:inert, ex) - result = get_test_result(ex) - :(do_test($result, $orig_ex)) -end - -""" - @test_broken ex - @test_broken f(args...) key=val ... - -Indicates a test that should pass but currently consistently fails. -Tests that the expression `ex` evaluates to `false` or causes an -exception. Returns a `Broken` `Result` if it does, or an `Error` `Result` -if the expression evaluates to `true`. - -The `@test_broken f(args...) key=val...` form works as for the `@test` macro. -""" -macro test_broken(ex, kws...) - test_expr!("@test_broken", ex, kws...) - orig_ex = Expr(:inert, ex) - result = get_test_result(ex) - # code to call do_test with execution result and original expr - :(do_broken_test($result, $orig_ex)) -end - -""" - @test_skip ex - @test_skip f(args...) key=val ... - -Marks a test that should not be executed but should be included in test -summary reporting as `Broken`. This can be useful for tests that intermittently -fail, or tests of not-yet-implemented functionality. - -The `@test_skip f(args...) key=val...` form works as for the `@test` macro. -""" -macro test_skip(ex, kws...) - test_expr!("@test_skip", ex, kws...) - orig_ex = Expr(:inert, ex) - testres = :(Broken(:skipped, $orig_ex)) - :(record(get_testset(), $testres)) -end - -# An internal function, called by the code generated by the @test -# macro to get results of the test expression. -# In the special case of a comparison, e.g. x == 5, generate code to -# evaluate each term in the comparison individually so the results -# can be displayed nicely. -function get_test_result(ex) - orig_ex = Expr(:inert, ex) - # Normalize non-dot comparison operator calls to :comparison expressions - if isa(ex, Expr) && ex.head == :call && length(ex.args) == 3 && - first(string(ex.args[1])) != '.' && - (ex.args[1] === :(==) || Base.operator_precedence(ex.args[1]) == comparison_prec) - ex = Expr(:comparison, ex.args[2], ex.args[1], ex.args[3]) - end - if isa(ex, Expr) && ex.head == :comparison - # pass all terms of the comparison to `eval_comparison`, as an Expr - escaped_terms = [esc(arg) for arg in ex.args] - quoted_terms = [QuoteNode(arg) for arg in ex.args] - testret = :(eval_comparison( - Expr(:comparison, $(escaped_terms...)), - Expr(:comparison, $(quoted_terms...)), - )) - else - testret = :(Returned($(esc(ex)), nothing)) - end - result = quote - try - $testret - catch _e - Threw(_e, catch_backtrace()) - end - end - Base.remove_linenums!(result) - result -end - -# An internal function, called by the code generated by the @test -# macro to actually perform the evaluation and manage the result. -function do_test(result::ExecutionResult, orig_expr) - # get_testset() returns the most recently added test set - # We then call record() with this test set and the test result - if isa(result, Returned) - # expr, in the case of a comparison, will contain the - # comparison with evaluated values of each term spliced in. - # For anything else, just contains the test expression. - # value is the evaluated value of the whole test expression. - # Ideally it is true, but it may be false or non-Boolean. - value = result.value - testres = if isa(value, Bool) - # a true value Passes - value ? Pass(:test, nothing, nothing, value) : - Fail(:test, orig_expr, result.data, value) - else - # If the result is non-Boolean, this counts as an Error - Error(:test_nonbool, orig_expr, value, nothing) - end - else - # The predicate couldn't be evaluated without throwing an - # exception, so that is an Error and not a Fail - @assert isa(result, Threw) - testres = Error(:test_error, orig_expr, result.exception, result.backtrace) - end - record(get_testset(), testres) -end - -function do_broken_test(result::ExecutionResult, orig_expr) - testres = Broken(:test, orig_expr) - # Assume the test is broken and only change if the result is true - if isa(result, Returned) - value = result.value - if isa(value, Bool) && value - testres = Error(:test_unbroken, orig_expr, value, nothing) - end - end - record(get_testset(), testres) -end - -#----------------------------------------------------------------------- - -""" - @test_throws extype ex - -Tests that the expression `ex` throws an exception of type `extype`. -Note that `@test_throws` does not support a trailing keyword form. -""" -macro test_throws(extype, ex) - orig_ex = Expr(:inert, ex) - result = quote - try - Returned($(esc(ex)), nothing) - catch _e - Threw(_e, nothing) - end - end - Base.remove_linenums!(result) - :(do_test_throws($result, $orig_ex, $(esc(extype)))) -end - -# An internal function, called by the code generated by @test_throws -# to evaluate and catch the thrown exception - if it exists -function do_test_throws(result::ExecutionResult, orig_expr, extype) - if isa(result, Threw) - # Check that the right type of exception was thrown - if isa(result.exception, extype) - testres = Pass(:test_throws, nothing, nothing, result.exception) - else - testres = Fail(:test_throws_wrong, orig_expr, extype, result.exception) - end - else - testres = Fail(:test_throws_nothing, orig_expr, extype, nothing) - end - record(get_testset(), testres) -end - -#----------------------------------------------------------------------- -# Test for warning messages - -ismatch_warn(s::AbstractString, output) = contains(output, s) -ismatch_warn(s::Regex, output) = ismatch(s, output) -ismatch_warn(s::Function, output) = s(output) -ismatch_warn(S::Union{AbstractArray,Tuple}, output) = all(s -> ismatch_warn(s, output), S) - -""" - @test_warn msg expr - -Test whether evaluating `expr` results in [`STDERR`](@ref) output that contains -the `msg` string or matches the `msg` regular expression. If `msg` is -a boolean function, tests whether `msg(output)` returns `true`. If `msg` is a -tuple or array, checks that the error output contains/matches each item in `msg`. -Returns the result of evaluating `expr`. - -See also [`@test_nowarn`](@ref) to check for the absence of error output. -""" -macro test_warn(msg, expr) - quote - let fname = tempname(), have_color = Base.have_color - try - @eval Base have_color = false - ret = open(fname, "w") do f - redirect_stderr(f) do - $(esc(expr)) - end - end - @test ismatch_warn($(esc(msg)), readstring(fname)) - ret - finally - eval(Base, Expr(:(=), :have_color, have_color)) - rm(fname, force=true) - end - end - end -end - -""" - @test_nowarn expr - -Test whether evaluating `expr` results in empty [`STDERR`](@ref) output -(no warnings or other messages). Returns the result of evaluating `expr`. -""" -macro test_nowarn(expr) - quote - @test_warn r"^(?!.)"s $(esc(expr)) - end -end - -#----------------------------------------------------------------------- - -# The AbstractTestSet interface is defined by two methods: -# record(AbstractTestSet, Result) -# Called by do_test after a test is evaluated -# finish(AbstractTestSet) -# Called after the test set has been popped from the test set stack -abstract type AbstractTestSet end - -""" - record(ts::AbstractTestSet, res::Result) - -Record a result to a testset. This function is called by the `@testset` -infrastructure each time a contained `@test` macro completes, and is given the -test result (which could be an `Error`). This will also be called with an `Error` -if an exception is thrown inside the test block but outside of a `@test` context. -""" -function record end - -""" - finish(ts::AbstractTestSet) - -Do any final processing necessary for the given testset. This is called by the -`@testset` infrastructure after a test block executes. One common use for this -function is to record the testset to the parent's results list, using -`get_testset`. -""" -function finish end - -""" - TestSetException - -Thrown when a test set finishes and not all tests passed. -""" -mutable struct TestSetException <: Exception - pass::Int - fail::Int - error::Int - broken::Int - errors_and_fails::Vector{Union{Fail, Error}} -end - -function Base.show(io::IO, ex::TestSetException) - print(io, "Some tests did not pass: ") - print(io, ex.pass, " passed, ") - print(io, ex.fail, " failed, ") - print(io, ex.error, " errored, ") - print(io, ex.broken, " broken.") -end - -function Base.showerror(io::IO, ex::TestSetException, bt; backtrace=true) - print_with_color(Base.error_color(), io, string(ex)) -end - -#----------------------------------------------------------------------- - -""" - FallbackTestSet - -A simple fallback test set that throws immediately on a failure. -""" -struct FallbackTestSet <: AbstractTestSet -end -fallback_testset = FallbackTestSet() - -mutable struct FallbackTestSetException <: Exception - msg::String -end - -function Base.showerror(io::IO, ex::FallbackTestSetException, bt; backtrace=true) - print_with_color(Base.error_color(), io, ex.msg) -end - -# Records nothing, and throws an error immediately whenever a Fail or -# Error occurs. Takes no action in the event of a Pass or Broken result -record(ts::FallbackTestSet, t::Union{Pass,Broken}) = t -function record(ts::FallbackTestSet, t::Union{Fail,Error}) - println(t) - throw(FallbackTestSetException("There was an error during testing")) -end -# We don't need to do anything as we don't record anything -finish(ts::FallbackTestSet) = ts - -#----------------------------------------------------------------------- - -""" - DefaultTestSet - -If using the DefaultTestSet, the test results will be recorded. If there -are any `Fail`s or `Error`s, an exception will be thrown only at the end, -along with a summary of the test results. -""" -mutable struct DefaultTestSet <: AbstractTestSet - description::AbstractString - results::Vector - n_passed::Int - anynonpass::Bool -end -DefaultTestSet(desc) = DefaultTestSet(desc, [], 0, false) - -# For a broken result, simply store the result -record(ts::DefaultTestSet, t::Broken) = (push!(ts.results, t); t) -# For a passed result, do not store the result since it uses a lot of memory -record(ts::DefaultTestSet, t::Pass) = (ts.n_passed += 1; t) - -# For the other result types, immediately print the error message -# but do not terminate. Print a backtrace. -function record(ts::DefaultTestSet, t::Union{Fail, Error}) - if myid() == 1 - print_with_color(:white, ts.description, ": ") - print(t) - # don't print the backtrace for Errors because it gets printed in the show - # method - isa(t, Error) || Base.show_backtrace(STDOUT, scrub_backtrace(backtrace())) - println() - end - push!(ts.results, t) - t, isa(t, Error) || backtrace() -end - -# When a DefaultTestSet finishes, it records itself to its parent -# testset, if there is one. This allows for recursive printing of -# the results at the end of the tests -record(ts::DefaultTestSet, t::AbstractTestSet) = push!(ts.results, t) - -function print_test_errors(ts::DefaultTestSet) - for t in ts.results - if (isa(t, Error) || isa(t, Fail)) && myid() == 1 - println("Error in testset $(ts.description):") - Base.show(STDOUT,t) - println() - elseif isa(t, DefaultTestSet) - print_test_errors(t) - end - end -end - -function print_test_results(ts::DefaultTestSet, depth_pad=0) - # Calculate the overall number for each type so each of - # the test result types are aligned - passes, fails, errors, broken, c_passes, c_fails, c_errors, c_broken = get_test_counts(ts) - total_pass = passes + c_passes - total_fail = fails + c_fails - total_error = errors + c_errors - total_broken = broken + c_broken - dig_pass = total_pass > 0 ? ndigits(total_pass) : 0 - dig_fail = total_fail > 0 ? ndigits(total_fail) : 0 - dig_error = total_error > 0 ? ndigits(total_error) : 0 - dig_broken = total_broken > 0 ? ndigits(total_broken) : 0 - total = total_pass + total_fail + total_error + total_broken - dig_total = total > 0 ? ndigits(total) : 0 - # For each category, take max of digits and header width if there are - # tests of that type - pass_width = dig_pass > 0 ? max(length("Pass"), dig_pass) : 0 - fail_width = dig_fail > 0 ? max(length("Fail"), dig_fail) : 0 - error_width = dig_error > 0 ? max(length("Error"), dig_error) : 0 - broken_width = dig_broken > 0 ? max(length("Broken"), dig_broken) : 0 - total_width = dig_total > 0 ? max(length("Total"), dig_total) : 0 - # Calculate the alignment of the test result counts by - # recursively walking the tree of test sets - align = max(get_alignment(ts, 0), length("Test Summary:")) - # Print the outer test set header once - pad = total == 0 ? "" : " " - print_with_color(:white, rpad("Test Summary:",align," "), " |", pad; bold = true) - if pass_width > 0 - print_with_color(:green, lpad("Pass",pass_width," "), " "; bold = true) - end - if fail_width > 0 - print_with_color(Base.error_color(), lpad("Fail",fail_width," "), " "; bold = true) - end - if error_width > 0 - print_with_color(Base.error_color(), lpad("Error",error_width," "), " "; bold = true) - end - if broken_width > 0 - print_with_color(Base.warn_color(), lpad("Broken",broken_width," "), " "; bold = true) - end - if total_width > 0 - print_with_color(Base.info_color(), lpad("Total",total_width, " "); bold = true) - end - println() - # Recursively print a summary at every level - print_counts(ts, depth_pad, align, pass_width, fail_width, error_width, broken_width, total_width) -end - - -const TESTSET_PRINT_ENABLE = Ref(true) - -# Called at the end of a @testset, behaviour depends on whether -# this is a child of another testset, or the "root" testset -function finish(ts::DefaultTestSet) - # If we are a nested test set, do not print a full summary - # now - let the parent test set do the printing - if get_testset_depth() != 0 - # Attach this test set to the parent test set - parent_ts = get_testset() - record(parent_ts, ts) - return ts - end - passes, fails, errors, broken, c_passes, c_fails, c_errors, c_broken = get_test_counts(ts) - total_pass = passes + c_passes - total_fail = fails + c_fails - total_error = errors + c_errors - total_broken = broken + c_broken - total = total_pass + total_fail + total_error + total_broken - - if TESTSET_PRINT_ENABLE[] - print_test_results(ts) - end - - # Finally throw an error as we are the outermost test set - if total != total_pass + total_broken - # Get all the error/failures and bring them along for the ride - efs = filter_errors(ts) - throw(TestSetException(total_pass,total_fail,total_error, total_broken, efs)) - end - - # return the testset so it is returned from the @testset macro - ts -end - -# Recursive function that finds the column that the result counts -# can begin at by taking into account the width of the descriptions -# and the amount of indentation. If a test set had no failures, and -# no failures in child test sets, there is no need to include those -# in calculating the alignment -function get_alignment(ts::DefaultTestSet, depth::Int) - # The minimum width at this depth is - ts_width = 2*depth + length(ts.description) - # If all passing, no need to look at children - !ts.anynonpass && return ts_width - # Return the maximum of this width and the minimum width - # for all children (if they exist) - isempty(ts.results) && return ts_width - child_widths = map(t->get_alignment(t, depth+1), ts.results) - return max(ts_width, maximum(child_widths)) -end -get_alignment(ts, depth::Int) = 0 - -# Recursive function that fetches backtraces for any and all errors -# or failures the testset and its children encountered -function filter_errors(ts::DefaultTestSet) - efs = [] - for t in ts.results - if isa(t, DefaultTestSet) - append!(efs, filter_errors(t)) - elseif isa(t, Union{Fail, Error}) - append!(efs, [t]) - end - end - efs -end - -# Recursive function that counts the number of test results of each -# type directly in the testset, and totals across the child testsets -function get_test_counts(ts::DefaultTestSet) - passes, fails, errors, broken = ts.n_passed, 0, 0, 0 - c_passes, c_fails, c_errors, c_broken = 0, 0, 0, 0 - for t in ts.results - isa(t, Fail) && (fails += 1) - isa(t, Error) && (errors += 1) - isa(t, Broken) && (broken += 1) - if isa(t, DefaultTestSet) - np, nf, ne, nb, ncp, ncf, nce , ncb = get_test_counts(t) - c_passes += np + ncp - c_fails += nf + ncf - c_errors += ne + nce - c_broken += nb + ncb - end - end - ts.anynonpass = (fails + errors + c_fails + c_errors > 0) - return passes, fails, errors, broken, c_passes, c_fails, c_errors, c_broken -end - -# Recursive function that prints out the results at each level of -# the tree of test sets -function print_counts(ts::DefaultTestSet, depth, align, - pass_width, fail_width, error_width, broken_width, total_width) - # Count results by each type at this level, and recursively - # through any child test sets - passes, fails, errors, broken, c_passes, c_fails, c_errors, c_broken = get_test_counts(ts) - subtotal = passes + fails + errors + broken + c_passes + c_fails + c_errors + c_broken - # Print test set header, with an alignment that ensures all - # the test results appear above each other - print(rpad(string(" "^depth, ts.description), align, " "), " | ") - - np = passes + c_passes - if np > 0 - print_with_color(:green, lpad(string(np), pass_width, " "), " ") - elseif pass_width > 0 - # No passes at this level, but some at another level - print(lpad(" ", pass_width), " ") - end - - nf = fails + c_fails - if nf > 0 - print_with_color(Base.error_color(), lpad(string(nf), fail_width, " "), " ") - elseif fail_width > 0 - # No fails at this level, but some at another level - print(lpad(" ", fail_width), " ") - end - - ne = errors + c_errors - if ne > 0 - print_with_color(Base.error_color(), lpad(string(ne), error_width, " "), " ") - elseif error_width > 0 - # No errors at this level, but some at another level - print(lpad(" ", error_width), " ") - end - - nb = broken + c_broken - if nb > 0 - print_with_color(Base.warn_color(), lpad(string(nb), broken_width, " "), " ") - elseif broken_width > 0 - # None broken at this level, but some at another level - print(lpad(" ", broken_width), " ") - end - - if np == 0 && nf == 0 && ne == 0 && nb == 0 - print_with_color(Base.info_color(), "No tests") - else - print_with_color(Base.info_color(), lpad(string(subtotal), total_width, " ")) - end - println() - - # Only print results at lower levels if we had failures - if np + nb != subtotal - for t in ts.results - if isa(t, DefaultTestSet) - print_counts(t, depth + 1, align, - pass_width, fail_width, error_width, broken_width, total_width) - end - end - end -end - -#----------------------------------------------------------------------- - -""" - @testset [CustomTestSet] [option=val ...] ["description"] begin ... end - @testset [CustomTestSet] [option=val ...] ["description \$v"] for v in (...) ... end - @testset [CustomTestSet] [option=val ...] ["description \$v, \$w"] for v in (...), w in (...) ... end - -Starts a new test set, or multiple test sets if a `for` loop is provided. - -If no custom testset type is given it defaults to creating a `DefaultTestSet`. -`DefaultTestSet` records all the results and, if there are any `Fail`s or -`Error`s, throws an exception at the end of the top-level (non-nested) test set, -along with a summary of the test results. - -Any custom testset type (subtype of `AbstractTestSet`) can be given and it will -also be used for any nested `@testset` invocations. The given options are only -applied to the test set where they are given. The default test set type does -not take any options. - -The description string accepts interpolation from the loop indices. -If no description is provided, one is constructed based on the variables. - -By default the `@testset` macro will return the testset object itself, though -this behavior can be customized in other testset types. If a `for` loop is used -then the macro collects and returns a list of the return values of the `finish` -method, which by default will return a list of the testset objects used in -each iteration. -""" -macro testset(args...) - isempty(args) && error("No arguments to @testset") - - tests = args[end] - - # Determine if a single block or for-loop style - if !isa(tests,Expr) || (tests.head != :for && tests.head != :block) - error("Expected begin/end block or for loop as argument to @testset") - end - - if tests.head == :for - return testset_forloop(args, tests) - else - return testset_beginend(args, tests) - end -end - -""" -Generate the code for a `@testset` with a `begin`/`end` argument -""" -function testset_beginend(args, tests) - desc, testsettype, options = parse_testset_args(args[1:end-1]) - if desc === nothing - desc = "test set" - end - # If we're at the top level we'll default to DefaultTestSet. Otherwise - # default to the type of the parent testset - if testsettype === nothing - testsettype = :(get_testset_depth() == 0 ? DefaultTestSet : typeof(get_testset())) - end - - # Generate a block of code that initializes a new testset, adds - # it to the task local storage, evaluates the test(s), before - # finally removing the testset and giving it a chance to take - # action (such as reporting the results) - quote - ts = $(testsettype)($desc; $options...) - # this empty loop is here to force the block to be compiled, - # which is needed for backtrace scrubbing to work correctly. - while false; end - push_testset(ts) - try - $(esc(tests)) - catch err - # something in the test block threw an error. Count that as an - # error in this test set - record(ts, Error(:nontest_error, :(), err, catch_backtrace())) - end - pop_testset() - finish(ts) - end -end - - -""" -Generate the code for a `@testset` with a `for` loop argument -""" -function testset_forloop(args, testloop) - # Pull out the loop variables. We might need them for generating the - # description and we'll definitely need them for generating the - # comprehension expression at the end - loopvars = Expr[] - if testloop.args[1].head == :(=) - push!(loopvars, testloop.args[1]) - elseif testloop.args[1].head == :block - for loopvar in testloop.args[1].args - push!(loopvars, loopvar) - end - else - error("Unexpected argument to @testset") - end - - desc, testsettype, options = parse_testset_args(args[1:end-1]) - - if desc === nothing - # No description provided. Generate from the loop variable names - v = loopvars[1].args[1] - desc = Expr(:string, "$v = ", esc(v)) # first variable - for l = loopvars[2:end] - v = l.args[1] - push!(desc.args, ", $v = ") - push!(desc.args, esc(v)) - end - end - - if testsettype === nothing - testsettype = :(get_testset_depth() == 0 ? DefaultTestSet : typeof(get_testset())) - end - - # Uses a similar block as for `@testset`, except that it is - # wrapped in the outer loop provided by the user - tests = testloop.args[2] - blk = quote - # Trick to handle `break` and `continue` in the test code before - # they can be handled properly by `finally` lowering. - if !first_iteration - pop_testset() - push!(arr, finish(ts)) - end - ts = $(testsettype)($desc; $options...) - push_testset(ts) - first_iteration = false - try - $(esc(tests)) - catch err - # Something in the test block threw an error. Count that as an - # error in this test set - record(ts, Error(:nontest_error, :(), err, catch_backtrace())) - end - end - quote - arr = Array{Any,1}(0) - first_iteration = true - local ts - try - $(Expr(:for, Expr(:block, [esc(v) for v in loopvars]...), blk)) - finally - # Handle `return` in test body - if !first_iteration - pop_testset() - push!(arr, finish(ts)) - end - end - arr - end -end - -""" -Parse the arguments to the `@testset` macro to pull out the description, -Testset Type, and options. Generally this should be called with all the macro -arguments except the last one, which is the test expression itself. -""" -function parse_testset_args(args) - desc = nothing - testsettype = nothing - options = :(Dict{Symbol, Any}()) - for arg in args - # a standalone symbol is assumed to be the test set we should use - if isa(arg, Symbol) - testsettype = esc(arg) - # a string is the description - elseif isa(arg, AbstractString) || (isa(arg, Expr) && arg.head == :string) - desc = esc(arg) - # an assignment is an option - elseif isa(arg, Expr) && arg.head == :(=) - # we're building up a Dict literal here - key = Expr(:quote, arg.args[1]) - push!(options.args, Expr(:call, :(=>), key, arg.args[2])) - else - error("Unexpected argument $arg to @testset") - end - end - - (desc, testsettype, options) -end - -#----------------------------------------------------------------------- -# Various helper methods for test sets - -""" - get_testset() - -Retrieve the active test set from the task's local storage. If no -test set is active, use the fallback default test set. -""" -function get_testset() - testsets = get(task_local_storage(), :__BASETESTNEXT__, AbstractTestSet[]) - return isempty(testsets) ? fallback_testset : testsets[end] -end - -""" - push_testset(ts::AbstractTestSet) - -Adds the test set to the task_local_storage. -""" -function push_testset(ts::AbstractTestSet) - testsets = get(task_local_storage(), :__BASETESTNEXT__, AbstractTestSet[]) - push!(testsets, ts) - setindex!(task_local_storage(), testsets, :__BASETESTNEXT__) -end - -""" - pop_testset() - -Pops the last test set added to the task_local_storage. If there are no -active test sets, returns the fallback default test set. -""" -function pop_testset() - testsets = get(task_local_storage(), :__BASETESTNEXT__, AbstractTestSet[]) - ret = isempty(testsets) ? fallback_testset : pop!(testsets) - setindex!(task_local_storage(), testsets, :__BASETESTNEXT__) - return ret -end - -""" - get_testset_depth() - -Returns the number of active test sets, not including the defaut test set -""" -function get_testset_depth() - testsets = get(task_local_storage(), :__BASETESTNEXT__, AbstractTestSet[]) - return length(testsets) -end - -_args_and_call(args...; kwargs...) = (args[1:end-1], kwargs, args[end](args[1:end-1]...; kwargs...)) -""" - @inferred f(x) - -Tests that the call expression `f(x)` returns a value of the same type -inferred by the compiler. It is useful to check for type stability. - -`f(x)` can be any call expression. -Returns the result of `f(x)` if the types match, -and an `Error` `Result` if it finds different types. - -```jldoctest -julia> using Base.Test - -julia> f(a,b,c) = b > 1 ? 1 : 1.0 -f (generic function with 1 method) - -julia> typeof(f(1,2,3)) -Int64 - -julia> @code_warntype f(1,2,3) -Variables: - #self# <optimized out> - a <optimized out> - b::Int64 - c <optimized out> - -Body: - begin - unless (Base.slt_int)(1, b::Int64)::Bool goto 3 - return 1 - 3: - return 1.0 - end::UNION{FLOAT64, INT64} - -julia> @inferred f(1,2,3) -ERROR: return type Int64 does not match inferred return type Union{Float64, Int64} -Stacktrace: - [1] error(::String) at ./error.jl:21 - -julia> @inferred max(1,2) -2 -``` -""" -macro inferred(ex) - if Meta.isexpr(ex, :ref) - ex = Expr(:call, :getindex, ex.args...) - end - Meta.isexpr(ex, :call)|| error("@inferred requires a call expression") - - Base.remove_linenums!(quote - let - $(if any(a->(Meta.isexpr(a, :kw) || Meta.isexpr(a, :parameters)), ex.args) - # Has keywords - args = gensym() - kwargs = gensym() - quote - $(esc(args)), $(esc(kwargs)), result = $(esc(Expr(:call, _args_and_call, ex.args[2:end]..., ex.args[1]))) - inftypes = $(Base.gen_call_with_extracted_types(Base.return_types, :($(ex.args[1])($(args)...; $(kwargs)...)))) - end - else - # No keywords - quote - args = ($([esc(ex.args[i]) for i = 2:length(ex.args)]...),) - result = $(esc(ex.args[1]))(args...) - inftypes = Base.return_types($(esc(ex.args[1])), Base.typesof(args...)) - end - end) - @assert length(inftypes) == 1 - rettype = isa(result, Type) ? Type{result} : typeof(result) - rettype == inftypes[1] || error("return type $rettype does not match inferred return type $(inftypes[1])") - result - end - end) -end - -# Test approximate equality of vectors or columns of matrices modulo floating -# point roundoff and phase (sign) differences. -# -# This function is designed to test for equality between vectors of floating point -# numbers when the vectors are defined only up to a global phase or sign, such as -# normalized eigenvectors or singular vectors. The global phase is usually -# defined consistently, but may occasionally change due to small differences in -# floating point rounding noise or rounding modes, or through the use of -# different conventions in different algorithms. As a result, most tests checking -# such vectors have to detect and discard such overall phase differences. -# -# Inputs: -# a, b:: StridedVecOrMat to be compared -# err :: Default: m^3*(eps(S)+eps(T)), where m is the number of rows -# -# Raises an error if any columnwise vector norm exceeds err. Otherwise, returns -# nothing. -function test_approx_eq_modphase(a::StridedVecOrMat{S}, b::StridedVecOrMat{T}, - err = length(indices(a,1))^3*(eps(S)+eps(T))) where {S<:Real,T<:Real} - @test indices(a,1) == indices(b,1) && indices(a,2) == indices(b,2) - for i in indices(a,2) - v1, v2 = a[:, i], b[:, i] - @test min(abs(norm(v1-v2)),abs(norm(v1+v2))) ≈ 0.0 atol=err - end -end - -""" - detect_ambiguities(mod1, mod2...; imported=false, ambiguous_bottom=false) - -Returns a vector of `(Method,Method)` pairs of ambiguous methods -defined in the specified modules. Use `imported=true` if you wish to -also test functions that were imported into these modules from -elsewhere. - -`ambiguous_bottom` controls whether ambiguities triggered only by -`Union{}` type parameters are included; in most cases you probably -want to set this to `false`. See [`Base.isambiguous`](@ref). -""" -function detect_ambiguities(mods...; - imported::Bool = false, - ambiguous_bottom::Bool = false, - allow_bottom::Union{Bool,Void} = nothing) - if allow_bottom !== nothing - Base.depwarn("the `allow_bottom` keyword to detect_ambiguities has been renamed to `ambiguous_bottom`", :detect_ambiguities) - ambiguous_bottom = allow_bottom - end - function sortdefs(m1, m2) - ord12 = m1.file < m2.file - if !ord12 && (m1.file == m2.file) - ord12 = m1.line < m2.line - end - ord12 ? (m1, m2) : (m2, m1) - end - ambs = Set{Tuple{Method,Method}}() - for mod in mods - for n in names(mod, true, imported) - Base.isdeprecated(mod, n) && continue - if !isdefined(mod, n) - println("Skipping ", mod, '.', n) # typically stale exports - continue - end - f = getfield(mod, n) - if isa(f, DataType) && isdefined(f.name, :mt) - mt = Base.MethodList(f.name.mt) - for m in mt - if m.ambig !== nothing - for m2 in m.ambig - if Base.isambiguous(m, m2, ambiguous_bottom=ambiguous_bottom) - push!(ambs, sortdefs(m, m2)) - end - end - end - end - end - end - end - return collect(ambs) -end - -""" -The `GenericString` can be used to test generic string APIs that program to -the `AbstractString` interface, in order to ensure that functions can work -with string types besides the standard `String` type. -""" -struct GenericString <: AbstractString - string::AbstractString -end -Base.convert(::Type{GenericString}, s::AbstractString) = GenericString(s) -Base.endof(s::GenericString) = endof(s.string) -Base.next(s::GenericString, i::Int) = next(s.string, i) - -end # module diff --git a/julia-0.6.3/share/julia/base/threadcall.jl b/julia-0.6.3/share/julia/base/threadcall.jl deleted file mode 100644 index fee9ef8..0000000 --- a/julia-0.6.3/share/julia/base/threadcall.jl +++ /dev/null @@ -1,100 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -const max_ccall_threads = parse(Int, get(ENV, "UV_THREADPOOL_SIZE", "4")) -const thread_notifiers = [Nullable{Condition}() for i in 1:max_ccall_threads] -const threadcall_restrictor = Semaphore(max_ccall_threads) - -function notify_fun(idx) - global thread_notifiers - notify(get(thread_notifiers[idx])) - return -end - -function init_threadcall() - global c_notify_fun = cfunction(notify_fun, Void, Tuple{Cint}) -end - -""" - @threadcall((cfunc, clib), rettype, (argtypes...), argvals...) - -The `@threadcall` macro is called in the same way as [`ccall`](@ref) but does the work -in a different thread. This is useful when you want to call a blocking C -function without causing the main `julia` thread to become blocked. Concurrency -is limited by size of the libuv thread pool, which defaults to 4 threads but -can be increased by setting the `UV_THREADPOOL_SIZE` environment variable and -restarting the `julia` process. - -Note that the called function should never call back into Julia. -""" -macro threadcall(f, rettype, argtypes, argvals...) - # check for usage errors - isa(argtypes,Expr) && argtypes.head == :tuple || - error("threadcall: argument types must be a tuple") - length(argtypes.args) == length(argvals) || - error("threadcall: wrong number of arguments to C function") - - # hygiene escape arguments - f = esc(f) - rettype = esc(rettype) - argtypes = map(esc, argtypes.args) - argvals = map(esc, argvals) - - # construct non-allocating wrapper to call C function - wrapper = :(function wrapper(args_ptr::Ptr{Void}, retval_ptr::Ptr{Void}) - p = args_ptr - end) - body = wrapper.args[2].args - args = Symbol[] - for (i,T) in enumerate(argtypes) - arg = Symbol("arg", i) - push!(body, :($arg = unsafe_load(convert(Ptr{$T}, p)))) - push!(body, :(p += sizeof($T))) - push!(args, arg) - end - push!(body, :(ret = ccall($f, $rettype, ($(argtypes...),), $(args...)))) - push!(body, :(unsafe_store!(convert(Ptr{$rettype}, retval_ptr), ret))) - push!(body, :(return sizeof($rettype))) - - # return code to generate wrapper function and send work request thread queue - :(let - $wrapper - do_threadcall(wrapper, $rettype, Any[$(argtypes...)], Any[$(argvals...)]) - end) -end - -function do_threadcall(wrapper::Function, rettype::Type, argtypes::Vector, argvals::Vector) - # generate function pointer - fun_ptr = cfunction(wrapper, Int, Tuple{Ptr{Void}, Ptr{Void}}) - - # cconvert, root and unsafe_convert arguments - roots = Any[] - args_size = isempty(argtypes) ? 0 : sum(sizeof, argtypes) - args_arr = Vector{UInt8}(args_size) - ptr = pointer(args_arr) - for (T, x) in zip(argtypes, argvals) - y = cconvert(T, x) - push!(roots, y) - unsafe_store!(convert(Ptr{T}, ptr), unsafe_convert(T, y)) - ptr += sizeof(T) - end - - # create return buffer - ret_arr = Vector{UInt8}(sizeof(rettype)) - - # wait for a worker thread to be available - acquire(threadcall_restrictor) - idx = findfirst(isnull, thread_notifiers) - thread_notifiers[idx] = Nullable{Condition}(Condition()) - - # queue up the work to be done - ccall(:jl_queue_work, Void, - (Ptr{Void}, Ptr{UInt8}, Ptr{UInt8}, Ptr{Void}, Cint), - fun_ptr, args_arr, ret_arr, c_notify_fun, idx) - - # wait for a result & return it - wait(get(thread_notifiers[idx])) - thread_notifiers[idx] = Nullable{Condition}() - release(threadcall_restrictor) - - unsafe_load(convert(Ptr{rettype}, pointer(ret_arr))) -end diff --git a/julia-0.6.3/share/julia/base/threadingconstructs.jl b/julia-0.6.3/share/julia/base/threadingconstructs.jl deleted file mode 100644 index 7052ac4..0000000 --- a/julia-0.6.3/share/julia/base/threadingconstructs.jl +++ /dev/null @@ -1,103 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -export threadid, nthreads, @threads - -""" - Threads.threadid() - -Get the ID number of the current thread of execution. The master thread has ID `1`. -""" -threadid() = Int(ccall(:jl_threadid, Int16, ())+1) - -# Inclusive upper bound on threadid() -""" - Threads.nthreads() - -Get the number of threads available to the Julia process. This is the inclusive upper bound -on `threadid()`. -""" -nthreads() = Int(unsafe_load(cglobal(:jl_n_threads, Cint))) - -# Only read/written by the main thread -const in_threaded_loop = Ref(false) - -function _threadsfor(iter,lbody) - lidx = iter.args[1] # index - range = iter.args[2] - quote - local threadsfor_fun - let range = $(esc(range)) - function threadsfor_fun(onethread=false) - r = range # Load into local variable - lenr = length(r) - # divide loop iterations among threads - if onethread - tid = 1 - len, rem = lenr, 0 - else - tid = threadid() - len, rem = divrem(lenr, nthreads()) - end - # not enough iterations for all the threads? - if len == 0 - if tid > rem - return - end - len, rem = 1, 0 - end - # compute this thread's iterations - f = 1 + ((tid-1) * len) - l = f + len - 1 - # distribute remaining iterations evenly - if rem > 0 - if tid <= rem - f = f + (tid-1) - l = l + tid - else - f = f + rem - l = l + rem - end - end - # run this thread's iterations - for i = f:l - local $(esc(lidx)) = Base.unsafe_getindex(r,i) - $(esc(lbody)) - end - end - end - # Hack to make nested threaded loops kinda work - if threadid() != 1 || in_threaded_loop[] - # We are in a nested threaded loop - threadsfor_fun(true) - else - in_threaded_loop[] = true - # the ccall is not expected to throw - ccall(:jl_threading_run, Ref{Void}, (Any,), threadsfor_fun) - in_threaded_loop[] = false - end - nothing - end -end -""" - Threads.@threads - -A macro to parallelize a for-loop to run with multiple threads. This spawns `nthreads()` -number of threads, splits the iteration space amongst them, and iterates in parallel. -A barrier is placed at the end of the loop which waits for all the threads to finish -execution, and the loop returns. -""" -macro threads(args...) - na = length(args) - if na != 1 - throw(ArgumentError("wrong number of arguments in @threads")) - end - ex = args[1] - if !isa(ex, Expr) - throw(ArgumentError("need an expression argument to @threads")) - end - if ex.head === :for - return _threadsfor(ex.args[1],ex.args[2]) - else - throw(ArgumentError("unrecognized argument to @threads")) - end -end diff --git a/julia-0.6.3/share/julia/base/threads.jl b/julia-0.6.3/share/julia/base/threads.jl deleted file mode 100644 index d36cade..0000000 --- a/julia-0.6.3/share/julia/base/threads.jl +++ /dev/null @@ -1,9 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -module Threads - -include("threadingconstructs.jl") -include("atomics.jl") -include("locks.jl") - -end diff --git a/julia-0.6.3/share/julia/base/traits.jl b/julia-0.6.3/share/julia/base/traits.jl deleted file mode 100644 index 3efad15..0000000 --- a/julia-0.6.3/share/julia/base/traits.jl +++ /dev/null @@ -1,22 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -## numeric/object traits -# trait for objects that have an ordering -abstract type TypeOrder end -struct HasOrder <: TypeOrder end -struct Unordered <: TypeOrder end - -TypeOrder(instance) = TypeOrder(typeof(instance)) -TypeOrder(::Type{<:Real}) = HasOrder() -TypeOrder(::Type{<:Any}) = Unordered() - -# trait for objects that support arithmetic -abstract type TypeArithmetic end -struct ArithmeticRounds <: TypeArithmetic end # least significant bits can be lost -struct ArithmeticOverflows <: TypeArithmetic end # most significant bits can be lost -struct ArithmeticUnknown <: TypeArithmetic end - -TypeArithmetic(instance) = TypeArithmetic(typeof(instance)) -TypeArithmetic(::Type{<:AbstractFloat}) = ArithmeticRounds() -TypeArithmetic(::Type{<:Integer}) = ArithmeticOverflows() -TypeArithmetic(::Type{<:Any}) = ArithmeticUnknown() diff --git a/julia-0.6.3/share/julia/base/tuple.jl b/julia-0.6.3/share/julia/base/tuple.jl deleted file mode 100644 index 4c7687f..0000000 --- a/julia-0.6.3/share/julia/base/tuple.jl +++ /dev/null @@ -1,338 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -# Document NTuple here where we have everything needed for the doc system -""" - NTuple{N, T} - -A compact way of representing the type for a tuple of length `N` where all elements are of type `T`. - -```jldoctest -julia> isa((1, 2, 3, 4, 5, 6), NTuple{6, Int}) -true -``` -""" -NTuple - -## indexing ## - -length(t::Tuple) = nfields(t) -endof(t::Tuple) = length(t) -size(t::Tuple, d) = d==1 ? length(t) : throw(ArgumentError("invalid tuple dimension $d")) -getindex(t::Tuple, i::Int) = getfield(t, i) -getindex(t::Tuple, i::Real) = getfield(t, convert(Int, i)) -getindex(t::Tuple, r::AbstractArray{<:Any,1}) = ([t[ri] for ri in r]...) -getindex(t::Tuple, b::AbstractArray{Bool,1}) = length(b) == length(t) ? getindex(t,find(b)) : throw(BoundsError(t, b)) - -# returns new tuple; N.B.: becomes no-op if i is out-of-bounds -setindex(x::Tuple, v, i::Integer) = _setindex((), x, v, i::Integer) -function _setindex(y::Tuple, r::Tuple, v, i::Integer) - @_inline_meta - _setindex((y..., ifelse(length(y) + 1 == i, v, first(r))), tail(r), v, i) -end -_setindex(y::Tuple, r::Tuple{}, v, i::Integer) = y - -## iterating ## - -start(t::Tuple) = 1 -done(t::Tuple, i::Int) = (length(t) < i) -next(t::Tuple, i::Int) = (t[i], i+1) - -eachindex(t::Tuple) = 1:length(t) - -function eachindex(t::Tuple, t2::Tuple...) - @_inline_meta - 1:_maxlength(t, t2...) -end -_maxlength(t::Tuple) = length(t) -function _maxlength(t::Tuple, t2::Tuple, t3::Tuple...) - @_inline_meta - max(length(t), _maxlength(t2, t3...)) -end - -# this allows partial evaluation of bounded sequences of next() calls on tuples, -# while reducing to plain next() for arbitrary iterables. -indexed_next(t::Tuple, i::Int, state) = (t[i], i+1) -indexed_next(a::Array, i::Int, state) = (a[i], i+1) -indexed_next(I, i, state) = done(I,state) ? throw(BoundsError()) : next(I, state) - -# Use dispatch to avoid a branch in first -first(::Tuple{}) = throw(ArgumentError("tuple must be non-empty")) -first(t::Tuple) = t[1] - -# eltype - -eltype(::Type{Tuple{}}) = Bottom -eltype(::Type{<:Tuple{Vararg{E}}}) where {E} = E -function eltype(t::Type{<:Tuple}) - @_pure_meta - t isa Union && return typejoin(eltype(t.a), eltype(t.b)) - t´ = unwrap_unionall(t) - r = Union{} - for ti in t´.parameters - r = typejoin(r, rewrap_unionall(unwrapva(ti), t)) - end - return r -end - -# version of tail that doesn't throw on empty tuples (used in array indexing) -safe_tail(t::Tuple) = tail(t) -safe_tail(t::Tuple{}) = () - -# front (the converse of tail: it skips the last entry) - -function front(t::Tuple) - @_inline_meta - _front((), t...) -end -front(::Tuple{}) = throw(ArgumentError("Cannot call front on an empty tuple")) -_front(out, v) = out -function _front(out, v, t...) - @_inline_meta - _front((out..., v), t...) -end - -## mapping ## - -""" - ntuple(f::Function, n::Integer) - -Create a tuple of length `n`, computing each element as `f(i)`, -where `i` is the index of the element. - -```jldoctest -julia> ntuple(i -> 2*i, 4) -(2, 4, 6, 8) -``` -""" -function ntuple(f::F, n::Integer) where F - t = n <= 0 ? () : - n == 1 ? (f(1),) : - n == 2 ? (f(1), f(2)) : - n == 3 ? (f(1), f(2), f(3)) : - n == 4 ? (f(1), f(2), f(3), f(4)) : - n == 5 ? (f(1), f(2), f(3), f(4), f(5)) : - n == 6 ? (f(1), f(2), f(3), f(4), f(5), f(6)) : - n == 7 ? (f(1), f(2), f(3), f(4), f(5), f(6), f(7)) : - n == 8 ? (f(1), f(2), f(3), f(4), f(5), f(6), f(7), f(8)) : - n == 9 ? (f(1), f(2), f(3), f(4), f(5), f(6), f(7), f(8), f(9)) : - n == 10 ? (f(1), f(2), f(3), f(4), f(5), f(6), f(7), f(8), f(9), f(10)) : - _ntuple(f, n) - return t -end - -_ntuple(f, n) = (@_noinline_meta; ([f(i) for i = 1:n]...)) - -# inferrable ntuple -ntuple(f, ::Type{Val{0}}) = (@_inline_meta; ()) -ntuple(f, ::Type{Val{1}}) = (@_inline_meta; (f(1),)) -ntuple(f, ::Type{Val{2}}) = (@_inline_meta; (f(1), f(2))) -ntuple(f, ::Type{Val{3}}) = (@_inline_meta; (f(1), f(2), f(3))) -ntuple(f, ::Type{Val{4}}) = (@_inline_meta; (f(1), f(2), f(3), f(4))) -ntuple(f, ::Type{Val{5}}) = (@_inline_meta; (f(1), f(2), f(3), f(4), f(5))) -ntuple(f, ::Type{Val{6}}) = (@_inline_meta; (f(1), f(2), f(3), f(4), f(5), f(6))) -ntuple(f, ::Type{Val{7}}) = (@_inline_meta; (f(1), f(2), f(3), f(4), f(5), f(6), f(7))) -ntuple(f, ::Type{Val{8}}) = (@_inline_meta; (f(1), f(2), f(3), f(4), f(5), f(6), f(7), f(8))) -ntuple(f, ::Type{Val{9}}) = (@_inline_meta; (f(1), f(2), f(3), f(4), f(5), f(6), f(7), f(8), f(9))) -ntuple(f, ::Type{Val{10}}) = (@_inline_meta; (f(1), f(2), f(3), f(4), f(5), f(6), f(7), f(8), f(9), f(10))) -ntuple(f, ::Type{Val{11}}) = (@_inline_meta; (f(1), f(2), f(3), f(4), f(5), f(6), f(7), f(8), f(9), f(10), f(11))) -ntuple(f, ::Type{Val{12}}) = (@_inline_meta; (f(1), f(2), f(3), f(4), f(5), f(6), f(7), f(8), f(9), f(10), f(11), f(12))) -ntuple(f, ::Type{Val{13}}) = (@_inline_meta; (f(1), f(2), f(3), f(4), f(5), f(6), f(7), f(8), f(9), f(10), f(11), f(12), f(13))) -ntuple(f, ::Type{Val{14}}) = (@_inline_meta; (f(1), f(2), f(3), f(4), f(5), f(6), f(7), f(8), f(9), f(10), f(11), f(12), f(13), f(14))) -ntuple(f, ::Type{Val{15}}) = (@_inline_meta; (f(1), f(2), f(3), f(4), f(5), f(6), f(7), f(8), f(9), f(10), f(11), f(12), f(13), f(14), f(15))) - -function ntuple(f::F, ::Type{Val{N}}) where {F,N} - Core.typeassert(N, Int) - (N >= 0) || throw(ArgumentError(string("tuple length should be ≥0, got ", N))) - _ntuple((), f, Val{N}) -end - -# Build up the output until it has length N -_ntuple(out::NTuple{N,Any}, f::F, ::Type{Val{N}}) where {F,N} = out -function _ntuple(out::NTuple{M,Any}, f::F, ::Type{Val{N}}) where {F,N,M} - @_inline_meta - _ntuple((out..., f(M+1)), f, Val{N}) -end - -# 1 argument function -map(f, t::Tuple{}) = () -map(f, t::Tuple{Any,}) = (f(t[1]),) -map(f, t::Tuple{Any, Any}) = (f(t[1]), f(t[2])) -map(f, t::Tuple{Any, Any, Any}) = (f(t[1]), f(t[2]), f(t[3])) -map(f, t::Tuple) = (@_inline_meta; (f(t[1]), map(f,tail(t))...)) -# stop inlining after some number of arguments to avoid code blowup -const Any16{N} = Tuple{Any,Any,Any,Any,Any,Any,Any,Any, - Any,Any,Any,Any,Any,Any,Any,Any,Vararg{Any,N}} -const All16{T,N} = Tuple{T,T,T,T,T,T,T,T, - T,T,T,T,T,T,T,T,Vararg{T,N}} -function map(f, t::Any16) - n = length(t) - A = Array{Any,1}(n) - for i=1:n - A[i] = f(t[i]) - end - (A...) -end -# 2 argument function -map(f, t::Tuple{}, s::Tuple{}) = () -map(f, t::Tuple{Any,}, s::Tuple{Any,}) = (f(t[1],s[1]),) -map(f, t::Tuple{Any,Any}, s::Tuple{Any,Any}) = (f(t[1],s[1]), f(t[2],s[2])) -function map(f, t::Tuple, s::Tuple) - @_inline_meta - (f(t[1],s[1]), map(f, tail(t), tail(s))...) -end -function map(f, t::Any16, s::Any16) - n = length(t) - A = Array{Any,1}(n) - for i = 1:n - A[i] = f(t[i], s[i]) - end - (A...) -end -# n argument function -heads(ts::Tuple...) = map(t -> t[1], ts) -tails(ts::Tuple...) = map(tail, ts) -map(f, ::Tuple{}...) = () -function map(f, t1::Tuple, t2::Tuple, ts::Tuple...) - @_inline_meta - (f(heads(t1, t2, ts...)...), map(f, tails(t1, t2, ts...)...)...) -end -function map(f, t1::Any16, t2::Any16, ts::Any16...) - n = length(t1) - A = Array{Any,1}(n) - for i = 1:n - A[i] = f(t1[i], t2[i], map(t -> t[i], ts)...) - end - (A...) -end - - -# type-stable padding -fill_to_length(t::Tuple, val, ::Type{Val{N}}) where {N} = _ftl((), val, Val{N}, t...) -_ftl(out::NTuple{N,Any}, val, ::Type{Val{N}}) where {N} = out -function _ftl(out::NTuple{N,Any}, val, ::Type{Val{N}}, t...) where N - @_inline_meta - throw(ArgumentError("input tuple of length $(N+length(t)), requested $N")) -end -function _ftl(out, val, ::Type{Val{N}}, t1, t...) where N - @_inline_meta - _ftl((out..., t1), val, Val{N}, t...) -end -function _ftl(out, val, ::Type{Val{N}}) where N - @_inline_meta - _ftl((out..., val), val, Val{N}) -end - -# constructing from an iterator - -# only define these in Base, to avoid overwriting the constructors -if isdefined(Main, :Base) - -(::Type{T})(x::Tuple) where {T<:Tuple} = convert(T, x) # still use `convert` for tuples - -# resolve ambiguity between preceding and following methods -All16{E,N}(x::Tuple) where {E,N} = convert(All16{E,N}, x) - -function (T::All16{E,N})(itr) where {E,N} - len = N+16 - elts = collect(E, Iterators.take(itr,len)) - if length(elts) != len - _totuple_err(T) - end - (elts...,) -end - -(::Type{T})(itr) where {T<:Tuple} = _totuple(T, itr, start(itr)) - -_totuple(::Type{Tuple{}}, itr, s) = () - -function _totuple_err(T::ANY) - @_noinline_meta - throw(ArgumentError("too few elements for tuple type $T")) -end - -function _totuple(T, itr, s) - @_inline_meta - done(itr, s) && _totuple_err(T) - v, s = next(itr, s) - (convert(tuple_type_head(T), v), _totuple(tuple_type_tail(T), itr, s)...) -end - -_totuple(::Type{Tuple{Vararg{E}}}, itr, s) where {E} = (collect(E, Iterators.rest(itr,s))...,) - -_totuple(::Type{Tuple}, itr, s) = (collect(Iterators.rest(itr,s))...,) - -end - -## comparison ## - -function isequal(t1::Tuple, t2::Tuple) - if length(t1) != length(t2) - return false - end - for i = 1:length(t1) - if !isequal(t1[i], t2[i]) - return false - end - end - return true -end - -function ==(t1::Tuple, t2::Tuple) - if length(t1) != length(t2) - return false - end - for i = 1:length(t1) - if !(t1[i] == t2[i]) - return false - end - end - return true -end - -const tuplehash_seed = UInt === UInt64 ? 0x77cfa1eef01bca90 : 0xf01bca90 -hash( ::Tuple{}, h::UInt) = h + tuplehash_seed -hash(x::Tuple{Any,}, h::UInt) = hash(x[1], hash((), h)) -hash(x::Tuple{Any,Any}, h::UInt) = hash(x[1], hash(x[2], hash((), h))) -hash(x::Tuple, h::UInt) = hash(x[1], hash(x[2], hash(tail(tail(x)), h))) - -function isless(t1::Tuple, t2::Tuple) - n1, n2 = length(t1), length(t2) - for i = 1:min(n1, n2) - a, b = t1[i], t2[i] - if !isequal(a, b) - return isless(a, b) - end - end - return n1 < n2 -end - -## functions ## - -isempty(x::Tuple{}) = true -isempty(x::Tuple) = false - -revargs() = () -revargs(x, r...) = (revargs(r...)..., x) - -reverse(t::Tuple) = revargs(t...) - -## specialized reduction ## - -# TODO: these definitions cannot yet be combined, since +(x...) -# where x might be any tuple matches too many methods. -sum(x::Tuple{Any, Vararg{Any}}) = +(x...) - -# NOTE: should remove, but often used on array sizes -prod(x::Tuple{}) = 1 -prod(x::Tuple{Any, Vararg{Any}}) = *(x...) - -all(x::Tuple{}) = true -all(x::Tuple{Bool}) = x[1] -all(x::Tuple{Bool, Bool}) = x[1]&x[2] -all(x::Tuple{Bool, Bool, Bool}) = x[1]&x[2]&x[3] -# use generic reductions for the rest - -any(x::Tuple{}) = false -any(x::Tuple{Bool}) = x[1] -any(x::Tuple{Bool, Bool}) = x[1]|x[2] -any(x::Tuple{Bool, Bool, Bool}) = x[1]|x[2]|x[3] diff --git a/julia-0.6.3/share/julia/base/twiceprecision.jl b/julia-0.6.3/share/julia/base/twiceprecision.jl deleted file mode 100644 index afa3916..0000000 --- a/julia-0.6.3/share/julia/base/twiceprecision.jl +++ /dev/null @@ -1,521 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -# Twice-precision arithmetic. - -# Necessary for creating nicely-behaved ranges like r = 0.1:0.1:0.3 -# that return r[3] == 0.3. Otherwise, we have roundoff error due to -# 0.1 + 2*0.1 = 0.30000000000000004 - -""" - TwicePrecision{T}(hi::T, lo::T) - TwicePrecision{T}((num, denom)) - -A number with twice the precision of `T`, e.g., quad-precision if `T = -Float64`. `hi` represents the high bits (most significant bits) and -`lo` the low bits (least significant bits). Rational values -`num//denom` can be approximated conveniently using the syntax -`TwicePrecision{T}((num, denom))`. - -When used with `T<:AbstractFloat` to construct an exact -`StepRangeLen`, `ref` should be the range element with smallest -magnitude and `offset` set to the corresponding index. For -efficiency, multiplication of `step` by the index is not performed at -twice precision: `step.hi` should have enough trailing zeros in its -`bits` representation that `(0:len-1)*step.hi` is exact (has no -roundoff error). If `step` has an exact rational representation -`num//denom`, then you can construct `step` using - - step = TwicePrecision{T}((num, denom), nb) - -where `nb` is the number of trailing zero bits of `step.hi`. For -ranges, you can set `nb = ceil(Int, log2(len-1))`. -""" -struct TwicePrecision{T} - hi::T # most significant bits - lo::T # least significant bits -end - -function TwicePrecision{T}(nd::Tuple{I,I}) where {T,I} - n, d = nd - TwicePrecision{T}(n, zero(T)) / d -end - -function TwicePrecision{T}(nd::Tuple{I,I}, nb::Integer) where {T,I} - twiceprecision(TwicePrecision{T}(nd), nb) -end - -function twiceprecision(val::T, nb::Integer) where T<:Number - hi = truncbits(val, nb) - TwicePrecision{T}(hi, val - hi) -end - -function twiceprecision(val::TwicePrecision{T}, nb::Integer) where T<:Number - hi = truncbits(val.hi, nb) - TwicePrecision{T}(hi, (val.hi - hi) + val.lo) -end - -nbitslen(r::StepRangeLen) = nbitslen(eltype(r), length(r), r.offset) -nbitslen(::Type{Float64}, len, offset) = min(26, nbitslen(len, offset)) -nbitslen(::Type{Float32}, len, offset) = min(12, nbitslen(len, offset)) -nbitslen(::Type{Float16}, len, offset) = min(5, nbitslen(len, offset)) -nbitslen(len, offset) = len < 2 ? 0 : ceil(Int, log2(max(offset-1, len-offset))) - -eltype(::Type{TwicePrecision{T}}) where {T} = T - -promote_rule(::Type{TwicePrecision{R}}, ::Type{TwicePrecision{S}}) where {R,S} = - TwicePrecision{promote_type(R,S)} -promote_rule(::Type{TwicePrecision{R}}, ::Type{S}) where {R,S} = - TwicePrecision{promote_type(R,S)} - -convert(::Type{TwicePrecision{T}}, x::TwicePrecision{T}) where {T} = x -convert(::Type{TwicePrecision{T}}, x::TwicePrecision) where {T} = - TwicePrecision{T}(convert(T, x.hi), convert(T, x.lo)) - -convert(::Type{T}, x::TwicePrecision) where {T<:Number} = convert(T, x.hi + x.lo) -convert(::Type{TwicePrecision{T}}, x::Number) where {T} = TwicePrecision{T}(convert(T, x), zero(T)) - -float(x::TwicePrecision{<:AbstractFloat}) = x -float(x::TwicePrecision) = TwicePrecision(float(x.hi), float(x.lo)) - -big(x::TwicePrecision) = big(x.hi) + big(x.lo) - --(x::TwicePrecision) = TwicePrecision(-x.hi, -x.lo) - -zero(::Type{TwicePrecision{T}}) where {T} = TwicePrecision{T}(0, 0) - -## StepRangeLen - -# If using TwicePrecision numbers, deliberately force user to specify offset -StepRangeLen(ref::TwicePrecision{T}, step::TwicePrecision{T}, len::Integer, offset::Integer) where {T} = - StepRangeLen{T,TwicePrecision{T},TwicePrecision{T}}(ref, step, len, offset) - -# Construct range for rational start=start_n/den, step=step_n/den -function floatrange(::Type{T}, start_n::Integer, step_n::Integer, len::Integer, den::Integer) where T - if len < 2 - return StepRangeLen(TwicePrecision{T}((start_n, den)), - TwicePrecision{T}((step_n, den)), Int(len), 1) - end - # index of smallest-magnitude value - imin = clamp(round(Int, -start_n/step_n+1), 1, Int(len)) - # Compute smallest-magnitude element to 2x precision - ref_n = start_n+(imin-1)*step_n # this shouldn't overflow, so don't check - nb = nbitslen(T, len, imin) - StepRangeLen(TwicePrecision{T}((ref_n, den)), - TwicePrecision{T}((step_n, den), nb), Int(len), imin) -end - -function floatrange(a::AbstractFloat, st::AbstractFloat, len::Real, divisor::AbstractFloat) - T = promote_type(typeof(a), typeof(st), typeof(divisor)) - m = maxintfloat(T, Int) - if abs(a) <= m && abs(st) <= m && abs(divisor) <= m - ia, ist, idivisor = round(Int, a), round(Int, st), round(Int, divisor) - if ia == a && ist == st && idivisor == divisor - # We can return the high-precision range - return floatrange(T, ia, ist, Int(len), idivisor) - end - end - # Fallback (misses the opportunity to set offset different from 1, - # but otherwise this is still high-precision) - StepRangeLen(TwicePrecision{T}((a,divisor)), - TwicePrecision{T}((st,divisor), nbitslen(T, len, 1)), Int(len), 1) -end - -function colon(start::T, step::T, stop::T) where T<:Union{Float16,Float32,Float64} - step == 0 && throw(ArgumentError("range step cannot be zero")) - # see if the inputs have exact rational approximations (and if so, - # perform all computations in terms of the rationals) - step_n, step_d = rat(step) - if step_d != 0 && T(step_n/step_d) == step - start_n, start_d = rat(start) - stop_n, stop_d = rat(stop) - if start_d != 0 && stop_d != 0 && - T(start_n/start_d) == start && T(stop_n/stop_d) == stop - den = lcm(start_d, step_d) # use same denominator for start and step - m = maxintfloat(T, Int) - if den != 0 && abs(start*den) <= m && abs(step*den) <= m && # will round succeed? - rem(den, start_d) == 0 && rem(den, step_d) == 0 # check lcm overflow - start_n = round(Int, start*den) - step_n = round(Int, step*den) - len = max(0, div(den*stop_n - stop_d*start_n + step_n*stop_d, step_n*stop_d)) - # Integer ops could overflow, so check that this makes sense - if isbetween(start, start + (len-1)*step, stop + step/2) && - !isbetween(start, start + len*step, stop) - # Return a 2x precision range - return floatrange(T, start_n, step_n, len, den) - end - end - end - end - # Fallback, taking start and step literally - lf = (stop-start)/step - if lf < 0 - len = 0 - elseif lf == 0 - len = 1 - else - len = round(Int, lf) + 1 - stop′ = start + (len-1)*step - # if we've overshot the end, subtract one: - len -= (start < stop < stop′) + (start > stop > stop′) - end - StepRangeLen(TwicePrecision(start, zero(T)), twiceprecision(step, nbitslen(T, len, 1)), len) -end - -function range(a::T, st::T, len::Integer) where T<:Union{Float16,Float32,Float64} - start_n, start_d = rat(a) - step_n, step_d = rat(st) - if start_d != 0 && step_d != 0 && - T(start_n/start_d) == a && T(step_n/step_d) == st - den = lcm(start_d, step_d) - m = maxintfloat(T, Int) - if abs(den*a) <= m && abs(den*st) <= m && - rem(den, start_d) == 0 && rem(den, step_d) == 0 - start_n = round(Int, den*a) - step_n = round(Int, den*st) - return floatrange(T, start_n, step_n, len, den) - end - end - StepRangeLen(TwicePrecision(a, zero(T)), TwicePrecision(st, zero(T)), len) -end - -step(r::StepRangeLen{T,R,S}) where {T,R,S<:TwicePrecision} = convert(eltype(S), r.step) - -start(r::StepRangeLen{<:Any,<:TwicePrecision,<:TwicePrecision}) = 1 -done(r::StepRangeLen{<:Any,<:TwicePrecision,<:TwicePrecision}, i::Int) = length(r) < i -function next(r::StepRangeLen{<:Any,<:TwicePrecision,<:TwicePrecision}, i::Int) - @_inline_meta - unsafe_getindex(r, i), i+1 -end - -# This assumes that r.step has already been split so that (0:len-1)*r.step.hi is exact -function unsafe_getindex(r::StepRangeLen{T,<:TwicePrecision,<:TwicePrecision}, i::Integer) where T - # Very similar to _getindex_hiprec, but optimized to avoid a 2nd call to add2 - @_inline_meta - u = i - r.offset - shift_hi, shift_lo = u*r.step.hi, u*r.step.lo - x_hi, x_lo = add2(r.ref.hi, shift_hi) - T(x_hi + (x_lo + (shift_lo + r.ref.lo))) -end - -function _getindex_hiprec(r::StepRangeLen{<:Any,<:TwicePrecision,<:TwicePrecision}, i::Integer) - u = i - r.offset - shift_hi, shift_lo = u*r.step.hi, u*r.step.lo - x_hi, x_lo = add2(r.ref.hi, shift_hi) - x_hi, x_lo = add2(x_hi, x_lo + (shift_lo + r.ref.lo)) - TwicePrecision(x_hi, x_lo) -end - -function getindex(r::StepRangeLen{T,<:TwicePrecision,<:TwicePrecision}, s::OrdinalRange{<:Integer}) where T - @_inline_meta - @boundscheck checkbounds(r, s) - soffset = 1 + round(Int, (r.offset - first(s))/step(s)) - soffset = clamp(soffset, 1, length(s)) - ioffset = first(s) + (soffset-1)*step(s) - if step(s) == 1 || length(s) < 2 - newstep = r.step - else - newstep = twiceprecision(r.step*step(s), nbitslen(T, length(s), soffset)) - end - if ioffset == r.offset - StepRangeLen(r.ref, newstep, length(s), max(1,soffset)) - else - StepRangeLen(r.ref + (ioffset-r.offset)*r.step, newstep, length(s), max(1,soffset)) - end -end - -*(x::Real, r::StepRangeLen{<:Real,<:TwicePrecision}) = - StepRangeLen(x*r.ref, twiceprecision(x*r.step, nbitslen(r)), length(r), r.offset) -*(r::StepRangeLen{<:Real,<:TwicePrecision}, x::Real) = x*r -/(r::StepRangeLen{<:Real,<:TwicePrecision}, x::Real) = - StepRangeLen(r.ref/x, twiceprecision(r.step/x, nbitslen(r)), length(r), r.offset) - -convert(::Type{StepRangeLen{T,R,S}}, r::StepRangeLen{T,R,S}) where {T<:AbstractFloat,R<:TwicePrecision,S<:TwicePrecision} = r - -convert(::Type{StepRangeLen{T,R,S}}, r::StepRangeLen) where {T<:AbstractFloat,R<:TwicePrecision,S<:TwicePrecision} = - _convertSRL(StepRangeLen{T,R,S}, r) - -convert(::Type{StepRangeLen{T}}, r::StepRangeLen) where {T<:Union{Float16,Float32,Float64}} = - _convertSRL(StepRangeLen{T,TwicePrecision{T},TwicePrecision{T}}, r) - -convert(::Type{StepRangeLen{T}}, r::Range) where {T<:Union{Float16,Float32,Float64}} = - _convertSRL(StepRangeLen{T,TwicePrecision{T},TwicePrecision{T}}, r) - -function _convertSRL(::Type{StepRangeLen{T,R,S}}, r::StepRangeLen{<:Integer}) where {T,R,S} - StepRangeLen{T,R,S}(R(r.ref), S(r.step), length(r), r.offset) -end - -function _convertSRL(::Type{StepRangeLen{T,R,S}}, r::Range{<:Integer}) where {T,R,S} - StepRangeLen{T,R,S}(R(first(r)), S(step(r)), length(r)) -end - -function _convertSRL(::Type{StepRangeLen{T,R,S}}, r::Range{U}) where {T,R,S,U} - # if start and step have a rational approximation in the old type, - # then we transfer that rational approximation to the new type - f, s = first(r), step(r) - start_n, start_d = rat(f) - step_n, step_d = rat(s) - if start_d != 0 && step_d != 0 && - U(start_n/start_d) == f && U(step_n/step_d) == s - den = lcm(start_d, step_d) - m = maxintfloat(T, Int) - if den != 0 && abs(f*den) <= m && abs(s*den) <= m && - rem(den, start_d) == 0 && rem(den, step_d) == 0 - start_n = round(Int, f*den) - step_n = round(Int, s*den) - return floatrange(T, start_n, step_n, length(r), den) - end - end - __convertSRL(StepRangeLen{T,R,S}, r) -end - -function __convertSRL(::Type{StepRangeLen{T,R,S}}, r::StepRangeLen{U}) where {T,R,S,U} - StepRangeLen{T,R,S}(R(r.ref), S(r.step), length(r), r.offset) -end -function __convertSRL(::Type{StepRangeLen{T,R,S}}, r::Range{U}) where {T,R,S,U} - StepRangeLen{T,R,S}(R(first(r)), S(step(r)), length(r)) -end - -function sum(r::StepRangeLen) - l = length(r) - # Compute the contribution of step over all indexes. - # Indexes on opposite side of r.offset contribute with opposite sign, - # r.step * (sum(1:np) - sum(1:nn)) - np, nn = l - r.offset, r.offset - 1 # positive, negative - # To prevent overflow in sum(1:n), multiply its factors by the step - sp, sn = sumpair(np), sumpair(nn) - tp = _prod(r.step, sp[1], sp[2]) - tn = _prod(r.step, sn[1], sn[2]) - s_hi, s_lo = add2(tp.hi, -tn.hi) - s_lo += tp.lo - tn.lo - # Add in contributions of ref - ref = r.ref * l - sm_hi, sm_lo = add2(s_hi, ref.hi) - add2(sm_hi, sm_lo + ref.lo)[1] -end - -# sum(1:n) as a product of two integers -sumpair(n::Integer) = iseven(n) ? (n+1, n>>1) : (n, (n+1)>>1) - -function +(r1::StepRangeLen{T,R}, r2::StepRangeLen{T,R}) where T where R<:TwicePrecision - len = length(r1) - (len == length(r2) || - throw(DimensionMismatch("argument dimensions must match"))) - if r1.offset == r2.offset - imid = r1.offset - ref = r1.ref + r2.ref - else - imid = round(Int, (r1.offset+r2.offset)/2) - ref1mid = _getindex_hiprec(r1, imid) - ref2mid = _getindex_hiprec(r2, imid) - ref = ref1mid + ref2mid - end - step = twiceprecision(r1.step + r2.step, nbitslen(T, len, imid)) - StepRangeLen{T,typeof(ref),typeof(step)}(ref, step, len, imid) -end - -## LinSpace - -# For Float16, Float32, and Float64, linspace returns a StepRangeLen -function linspace(start::T, stop::T, len::Integer) where T<:Union{Float16,Float32,Float64} - len < 2 && return _linspace1(T, start, stop, len) - if start == stop - return StepRangeLen(TwicePrecision(start,zero(T)), TwicePrecision(zero(T),zero(T)), len) - end - # Attempt to find exact rational approximations - start_n, start_d = rat(start) - stop_n, stop_d = rat(stop) - if start_d != 0 && stop_d != 0 - den = lcm(start_d, stop_d) - m = maxintfloat(T, Int) - if den != 0 && abs(den*start) <= m && abs(den*stop) <= m - start_n = round(Int, den*start) - stop_n = round(Int, den*stop) - if T(start_n/den) == start && T(stop_n/den) == stop - return linspace(T, start_n, stop_n, len, den) - end - end - end - _linspace(start, stop, len) -end - -function _linspace(start::T, stop::T, len::Integer) where T<:Union{Float16,Float32,Float64} - (isfinite(start) && isfinite(stop)) || throw(ArgumentError("start and stop must be finite, got $start and $stop")) - # Find the index that returns the smallest-magnitude element - Δ, Δfac = stop-start, 1 - if !isfinite(Δ) # handle overflow for large endpoints - Δ, Δfac = stop/len - start/len, Int(len) - end - tmin = -(start/Δ)/Δfac # interpolation t such that return value is 0 - imin = round(Int, tmin*(len-1)+1) - if 1 < imin < len - # The smallest-magnitude element is in the interior - t = (imin-1)/(len-1) - ref = T((1-t)*start + t*stop) - step = imin-1 < len-imin ? (ref-start)/(imin-1) : (stop-ref)/(len-imin) - elseif imin <= 1 - imin = 1 - ref = start - step = (Δ/(len-1))*Δfac - else - imin = Int(len) - ref = stop - step = (Δ/(len-1))*Δfac - end - if len == 2 && !isfinite(step) - # For very large endpoints where step overflows, exploit the - # split-representation to handle the overflow - return StepRangeLen(TwicePrecision(start, zero(T)), - TwicePrecision(-start, stop), 2) - end - # 2x calculations to get high precision endpoint matching while also - # preventing overflow in ref_hi+(i-offset)*step_hi - m, k = prevfloat(realmax(T)), max(imin-1, len-imin) - step_hi_pre = clamp(step, max(-(m+ref)/k, (-m+ref)/k), min((m-ref)/k, (m+ref)/k)) - nb = nbitslen(T, len, imin) - step_hi = truncbits(step_hi_pre, nb) - x1_hi, x1_lo = add2((1-imin)*step_hi, ref) - x2_hi, x2_lo = add2((len-imin)*step_hi, ref) - a, b = (start - x1_hi) - x1_lo, (stop - x2_hi) - x2_lo - step_lo = (b - a)/(len - 1) - ref_lo = a - (1 - imin)*step_lo - StepRangeLen(TwicePrecision(ref, ref_lo), TwicePrecision(step_hi, step_lo), Int(len), imin) -end - -# linspace for rational numbers, start = start_n/den, stop = stop_n/den -# Note this returns a StepRangeLen -function linspace(::Type{T}, start_n::Integer, stop_n::Integer, len::Integer, den::Integer) where T - len < 2 && return _linspace1(T, start_n/den, stop_n/den, len) - start_n == stop_n && return StepRangeLen(TwicePrecision{T}((start_n, den)), zero(TwicePrecision{T}), len) - tmin = -start_n/(Float64(stop_n) - Float64(start_n)) - imin = round(Int, tmin*(len-1)+1) - imin = clamp(imin, 1, Int(len)) - # Compute (1-t)*a and t*b separately in 2x precision (itp = interpolant)... - dent = (den, len-1) # represent products as a tuple to eliminate risk of overflow - start_itp = proddiv(T, (len-imin, start_n), dent) - stop_itp = proddiv(T, (imin-1, stop_n), dent) - # ...and then combine them to make ref - ref = start_itp + stop_itp - # Compute step to 2x precision without risking overflow... - rend = proddiv(T, (stop_n,), dent) - rbeg = proddiv(T, (-start_n,), dent) - step = twiceprecision(rbeg + rend, nbitslen(T, len, imin)) # ...and truncate hi-bits as needed - StepRangeLen(ref, step, Int(len), imin) -end - -# For len < 2 -function _linspace1(::Type{T}, start, stop, len::Integer) where T - len >= 0 || throw(ArgumentError("linspace($start, $stop, $len): negative length")) - if len <= 1 - len == 1 && (start == stop || throw(ArgumentError("linspace($start, $stop, $len): endpoints differ"))) - # Ensure that first(r)==start and last(r)==stop even for len==0 - return StepRangeLen(TwicePrecision(start, zero(T)), TwicePrecision(start, -stop), len, 1) - end - throw(ArgumentError("should only be called for len < 2, got $len")) -end - -### Numeric utilities - -# Approximate x with a rational representation. Guaranteed to return, -# but not guaranteed to return a precise answer. -# https://en.wikipedia.org/wiki/Continued_fraction#Best_rational_approximations -function rat(x) - y = x - a = d = 1 - b = c = 0 - m = maxintfloat(narrow(typeof(x)), Int) - while abs(y) <= m - f = trunc(Int,y) - y -= f - a, c = f*a + c, a - b, d = f*b + d, b - max(abs(a), abs(b)) <= convert(Int,m) || return c, d - oftype(x,a)/oftype(x,b) == x && break - y = inv(y) - end - return a, b -end - -narrow(::Type{T}) where {T<:AbstractFloat} = Float64 -narrow(::Type{Float64}) = Float32 -narrow(::Type{Float32}) = Float16 -narrow(::Type{Float16}) = Float16 - -function add2(u::T, v::T) where T<:Number - @_inline_meta - u, v = ifelse(abs(v) > abs(u), (v, u), (u, v)) - w = u + v - w, (u-w) + v -end - -add2(u, v) = _add2(promote(u, v)...) -_add2(u::T, v::T) where {T<:Number} = add2(u, v) -_add2(u, v) = error("$u::$(typeof(u)) and $v::$(typeof(v)) cannot be promoted to a common type") - -function +(x::TwicePrecision, y::Number) - s_hi, s_lo = add2(x.hi, y) - TwicePrecision(s_hi, s_lo+x.lo) -end -+(x::Number, y::TwicePrecision) = y+x - -function +(x::TwicePrecision{T}, y::TwicePrecision{T}) where T - r = x.hi + y.hi - s = abs(x.hi) > abs(y.hi) ? (((x.hi - r) + y.hi) + y.lo) + x.lo : (((y.hi - r) + x.hi) + x.lo) + y.lo - TwicePrecision(r, s) -end -+(x::TwicePrecision, y::TwicePrecision) = _add2(promote(x, y)...) -_add2{T<:TwicePrecision}(x::T, y::T) = x + y -_add2(x::TwicePrecision, y::TwicePrecision) = TwicePrecision(x.hi+y.hi, x.lo+y.lo) - -function *(x::TwicePrecision, v::Integer) - v == 0 && return TwicePrecision(x.hi*v, x.lo*v) - nb = ceil(Int, log2(abs(v))) - u = truncbits(x.hi, nb) - y_hi, y_lo = add2(u*v, ((x.hi-u) + x.lo)*v) - TwicePrecision(y_hi, y_lo) -end - -function _mul2(x::TwicePrecision{T}, v::T) where T<:Union{Float16,Float32,Float64} - v == 0 && return TwicePrecision(T(0), T(0)) - xhh, xhl = splitprec(x.hi) - vh, vl = splitprec(v) - y_hi, y_lo = add2(xhh*vh, xhh*vl + xhl*vh) - TwicePrecision(y_hi, y_lo + xhl*vl + x.lo*v) -end - -_mul2(x::TwicePrecision, v::Number) = TwicePrecision(x.hi*v, x.lo*v) - -function *(x::TwicePrecision{R}, v::S) where R where S<:Number - T = promote_type(R, S) - _mul2(convert(TwicePrecision{T}, x), convert(T, v)) -end - -*(v::Number, x::TwicePrecision) = x*v - -function /(x::TwicePrecision, v::Number) - hi = x.hi/v - w = TwicePrecision(hi, zero(hi)) * v - lo = (((x.hi - w.hi) - w.lo) + x.lo)/v - y_hi, y_lo = add2(hi, lo) - TwicePrecision(y_hi, y_lo) -end - -# hi-precision version of prod(num)/prod(den) -# num and den are tuples to avoid risk of overflow -function proddiv(T, num, den) - @_inline_meta - t = TwicePrecision(T(num[1]), zero(T)) - t = _prod(t, tail(num)...) - _divt(t, den...) -end -function _prod(t::TwicePrecision, x, y...) - @_inline_meta - _prod(t * x, y...) -end -_prod(t::TwicePrecision) = t -function _divt(t::TwicePrecision, x, y...) - @_inline_meta - _divt(t / x, y...) -end -_divt(t::TwicePrecision) = t - -isbetween(a, x, b) = a <= x <= b || b <= x <= a diff --git a/julia-0.6.3/share/julia/base/util.jl b/julia-0.6.3/share/julia/base/util.jl deleted file mode 100644 index e6a014c..0000000 --- a/julia-0.6.3/share/julia/base/util.jl +++ /dev/null @@ -1,857 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -# timing - -# time() in libc.jl - -# high-resolution relative time, in nanoseconds - -""" - time_ns() - -Get the time in nanoseconds. The time corresponding to 0 is undefined, and wraps every 5.8 years. -""" -time_ns() = ccall(:jl_hrtime, UInt64, ()) - -# This type must be kept in sync with the C struct in src/gc.h -struct GC_Num - allocd ::Int64 # GC internal - deferred_alloc::Int64 # GC internal - freed ::Int64 # GC internal - malloc ::UInt64 - realloc ::UInt64 - poolalloc ::UInt64 - bigalloc ::UInt64 - freecall ::UInt64 - total_time ::UInt64 - total_allocd::UInt64 # GC internal - since_sweep ::UInt64 # GC internal - collect ::Csize_t # GC internal - pause ::Cint - full_sweep ::Cint -end - -gc_num() = ccall(:jl_gc_num, GC_Num, ()) - -# This type is to represent differences in the counters, so fields may be negative -struct GC_Diff - allocd ::Int64 # Bytes allocated - malloc ::Int64 # Number of GC aware malloc() - realloc ::Int64 # Number of GC aware realloc() - poolalloc ::Int64 # Number of pool allocation - bigalloc ::Int64 # Number of big (non-pool) allocation - freecall ::Int64 # Number of GC aware free() - total_time ::Int64 # Time spent in garbage collection - pause ::Int64 # Number of GC pauses - full_sweep ::Int64 # Number of GC full collection -end - -gc_total_bytes(gc_num::GC_Num) = - (gc_num.allocd + gc_num.deferred_alloc + - Int64(gc_num.collect) + Int64(gc_num.total_allocd)) - -function GC_Diff(new::GC_Num, old::GC_Num) - # logic from `src/gc.c:jl_gc_total_bytes` - old_allocd = gc_total_bytes(old) - new_allocd = gc_total_bytes(new) - return GC_Diff(new_allocd - old_allocd, - Int64(new.malloc - old.malloc), - Int64(new.realloc - old.realloc), - Int64(new.poolalloc - old.poolalloc), - Int64(new.bigalloc - old.bigalloc), - Int64(new.freecall - old.freecall), - Int64(new.total_time - old.total_time), - new.pause - old.pause, - new.full_sweep - old.full_sweep) -end - -function gc_alloc_count(diff::GC_Diff) - diff.malloc + diff.realloc + diff.poolalloc + diff.bigalloc -end - - -# total time spend in garbage collection, in nanoseconds -gc_time_ns() = ccall(:jl_gc_total_hrtime, UInt64, ()) - -# total number of bytes allocated so far -gc_bytes() = ccall(:jl_gc_total_bytes, Int64, ()) - -""" - tic() - -Set a timer to be read by the next call to [`toc`](@ref) or [`toq`](@ref). The -macro call `@time expr` can also be used to time evaluation. - -```julia-repl -julia> tic() -0x0000c45bc7abac95 - -julia> sleep(0.3) - -julia> toc() -elapsed time: 0.302745944 seconds -0.302745944 -``` -""" -function tic() - t0 = time_ns() - task_local_storage(:TIMERS, (t0, get(task_local_storage(), :TIMERS, ()))) - return t0 -end - -""" - toq() - -Return, but do not print, the time elapsed since the last [`tic`](@ref). The -macro calls `@timed expr` and `@elapsed expr` also return evaluation time. - -```julia-repl -julia> tic() -0x0000c46477a9675d - -julia> sleep(0.3) - -julia> toq() -0.302251004 -``` -""" -function toq() - t1 = time_ns() - timers = get(task_local_storage(), :TIMERS, ()) - if timers === () - error("toc() without tic()") - end - t0 = timers[1]::UInt64 - task_local_storage(:TIMERS, timers[2]) - (t1-t0)/1e9 -end - -""" - toc() - -Print and return the time elapsed since the last [`tic`](@ref). The macro call -`@time expr` can also be used to time evaluation. - -```julia-repl -julia> tic() -0x0000c45bc7abac95 - -julia> sleep(0.3) - -julia> toc() -elapsed time: 0.302745944 seconds -0.302745944 -``` -""" -function toc() - t = toq() - println("elapsed time: ", t, " seconds") - return t -end - -# print elapsed time, return expression value -const _mem_units = ["byte", "KiB", "MiB", "GiB", "TiB", "PiB"] -const _cnt_units = ["", " k", " M", " G", " T", " P"] -function prettyprint_getunits(value, numunits, factor) - if value == 0 || value == 1 - return (value, 1) - end - unit = ceil(Int, log(value) / log(factor)) - unit = min(numunits, unit) - number = value/factor^(unit-1) - return number, unit -end - -function padded_nonzero_print(value,str) - if value != 0 - blanks = " "[1:18-length(str)] - println("$str:$blanks$value") - end -end - -function time_print(elapsedtime, bytes, gctime, allocs) - @printf("%10.6f seconds", elapsedtime/1e9) - if bytes != 0 || allocs != 0 - bytes, mb = prettyprint_getunits(bytes, length(_mem_units), Int64(1024)) - allocs, ma = prettyprint_getunits(allocs, length(_cnt_units), Int64(1000)) - if ma == 1 - @printf(" (%d%s allocation%s: ", allocs, _cnt_units[ma], allocs==1 ? "" : "s") - else - @printf(" (%.2f%s allocations: ", allocs, _cnt_units[ma]) - end - if mb == 1 - @printf("%d %s%s", bytes, _mem_units[mb], bytes==1 ? "" : "s") - else - @printf("%.3f %s", bytes, _mem_units[mb]) - end - if gctime > 0 - @printf(", %.2f%% gc time", 100*gctime/elapsedtime) - end - print(")") - elseif gctime > 0 - @printf(", %.2f%% gc time", 100*gctime/elapsedtime) - end - println() -end - -function timev_print(elapsedtime, diff::GC_Diff) - allocs = gc_alloc_count(diff) - time_print(elapsedtime, diff.allocd, diff.total_time, allocs) - print("elapsed time (ns): $elapsedtime\n") - padded_nonzero_print(diff.total_time, "gc time (ns)") - padded_nonzero_print(diff.allocd, "bytes allocated") - padded_nonzero_print(diff.poolalloc, "pool allocs") - padded_nonzero_print(diff.bigalloc, "non-pool GC allocs") - padded_nonzero_print(diff.malloc, "malloc() calls") - padded_nonzero_print(diff.realloc, "realloc() calls") - padded_nonzero_print(diff.freecall, "free() calls") - padded_nonzero_print(diff.pause, "GC pauses") - padded_nonzero_print(diff.full_sweep, "full collections") -end - -""" - @time - -A macro to execute an expression, printing the time it took to execute, the number of -allocations, and the total number of bytes its execution caused to be allocated, before -returning the value of the expression. - -See also [`@timev`](@ref), [`@timed`](@ref), [`@elapsed`](@ref), and -[`@allocated`](@ref). - -```julia-repl -julia> @time rand(10^6); - 0.001525 seconds (7 allocations: 7.630 MiB) - -julia> @time begin - sleep(0.3) - 1+1 - end - 0.301395 seconds (8 allocations: 336 bytes) -``` -""" -macro time(ex) - quote - local stats = gc_num() - local elapsedtime = time_ns() - local val = $(esc(ex)) - elapsedtime = time_ns() - elapsedtime - local diff = GC_Diff(gc_num(), stats) - time_print(elapsedtime, diff.allocd, diff.total_time, - gc_alloc_count(diff)) - val - end -end - -""" - @timev - -This is a verbose version of the `@time` macro. It first prints the same information as -`@time`, then any non-zero memory allocation counters, and then returns the value of the -expression. - -See also [`@time`](@ref), [`@timed`](@ref), [`@elapsed`](@ref), and -[`@allocated`](@ref). - -```julia-repl -julia> @timev rand(10^6); - 0.001006 seconds (7 allocations: 7.630 MiB) -elapsed time (ns): 1005567 -bytes allocated: 8000256 -pool allocs: 6 -malloc() calls: 1 -``` -""" -macro timev(ex) - quote - local stats = gc_num() - local elapsedtime = time_ns() - local val = $(esc(ex)) - elapsedtime = time_ns() - elapsedtime - timev_print(elapsedtime, GC_Diff(gc_num(), stats)) - val - end -end - -""" - @elapsed - -A macro to evaluate an expression, discarding the resulting value, instead returning the -number of seconds it took to execute as a floating-point number. - -See also [`@time`](@ref), [`@timev`](@ref), [`@timed`](@ref), -and [`@allocated`](@ref). - -```julia-repl -julia> @elapsed sleep(0.3) -0.301391426 -``` -""" -macro elapsed(ex) - quote - local t0 = time_ns() - local val = $(esc(ex)) - (time_ns()-t0)/1e9 - end -end - -# measure bytes allocated without *most* contamination from compilation -# Note: This reports a different value from the @time macros, because -# it wraps the call in a function, however, this means that things -# like: @allocated y = foo() -# will not work correctly, because it will set y in the context of -# the local function made by the macro, not the current function -""" - @allocated - -A macro to evaluate an expression, discarding the resulting value, instead returning the -total number of bytes allocated during evaluation of the expression. Note: the expression is -evaluated inside a local function, instead of the current context, in order to eliminate the -effects of compilation, however, there still may be some allocations due to JIT compilation. -This also makes the results inconsistent with the `@time` macros, which do not try to adjust -for the effects of compilation. - -See also [`@time`](@ref), [`@timev`](@ref), [`@timed`](@ref), -and [`@elapsed`](@ref). - -```julia-repl -julia> @allocated rand(10^6) -8000080 -``` -""" -macro allocated(ex) - quote - let - local f - function f() - b0 = gc_bytes() - $(esc(ex)) - gc_bytes() - b0 - end - f() - end - end -end - -""" - @timed - -A macro to execute an expression, and return the value of the expression, elapsed time, -total bytes allocated, garbage collection time, and an object with various memory allocation -counters. - -See also [`@time`](@ref), [`@timev`](@ref), [`@elapsed`](@ref), and -[`@allocated`](@ref). - -```julia-repl -julia> val, t, bytes, gctime, memallocs = @timed rand(10^6); - -julia> t -0.006634834 - -julia> bytes -8000256 - -julia> gctime -0.0055765 - -julia> fieldnames(typeof(memallocs)) -9-element Array{Symbol,1}: - :allocd - :malloc - :realloc - :poolalloc - :bigalloc - :freecall - :total_time - :pause - :full_sweep - -julia> memallocs.total_time -5576500 -``` -""" -macro timed(ex) - quote - local stats = gc_num() - local elapsedtime = time_ns() - local val = $(esc(ex)) - elapsedtime = time_ns() - elapsedtime - local diff = GC_Diff(gc_num(), stats) - val, elapsedtime/1e9, diff.allocd, diff.total_time/1e9, diff - end -end - -function fftw_vendor() - if Base.libfftw_name in ("libmkl_rt", "mkl_rt") - return :mkl - else - return :fftw - end -end - - -## printing with color ## - -function with_output_color(f::Function, color::Union{Int, Symbol}, io::IO, args...; bold::Bool = false) - buf = IOBuffer() - have_color && bold && print(buf, text_colors[:bold]) - have_color && print(buf, get(text_colors, color, color_normal)) - try f(IOContext(buf, io), args...) - finally - have_color && color != :nothing && print(buf, get(disable_text_style, color, text_colors[:default])) - have_color && (bold || color == :bold) && print(buf, disable_text_style[:bold]) - print(io, String(take!(buf))) - end -end - -""" - print_with_color(color::Union{Symbol, Int}, [io], xs...; bold::Bool = false) - -Print `xs` in a color specified as a symbol. - -`color` may take any of the values $(Base.available_text_colors_docstring) -or an integer between 0 and 255 inclusive. Note that not all terminals support 256 colors. -If the keyword `bold` is given as `true`, the result will be printed in bold. -""" -print_with_color(color::Union{Int, Symbol}, io::IO, msg...; bold::Bool = false) = - with_output_color(print, color, io, msg...; bold = bold) -print_with_color(color::Union{Int, Symbol}, msg...; bold::Bool = false) = - print_with_color(color, STDOUT, msg...; bold = bold) -println_with_color(color::Union{Int, Symbol}, io::IO, msg...; bold::Bool = false) = - with_output_color(println, color, io, msg...; bold = bold) -println_with_color(color::Union{Int, Symbol}, msg...; bold::Bool = false) = - println_with_color(color, STDOUT, msg...; bold = bold) - -## warnings and messages ## - -const log_info_to = Dict{Tuple{Union{Module,Void},Union{Symbol,Void}},IO}() -const log_warn_to = Dict{Tuple{Union{Module,Void},Union{Symbol,Void}},IO}() -const log_error_to = Dict{Tuple{Union{Module,Void},Union{Symbol,Void}},IO}() - -function _redirect(io::IO, log_to::Dict, sf::StackTraces.StackFrame) - isnull(sf.linfo) && return io - mod = get(sf.linfo).def.module - fun = sf.func - if haskey(log_to, (mod,fun)) - return log_to[(mod,fun)] - elseif haskey(log_to, (mod,nothing)) - return log_to[(mod,nothing)] - elseif haskey(log_to, (nothing,nothing)) - return log_to[(nothing,nothing)] - else - return io - end -end - -function _redirect(io::IO, log_to::Dict, fun::Symbol) - clos = string("#",fun,"#") - kw = string("kw##",fun) - local sf - break_next_frame = false - for trace in backtrace() - stack::Vector{StackFrame} = StackTraces.lookup(trace) - filter!(frame -> !frame.from_c, stack) - for frame in stack - isnull(frame.linfo) && continue - sf = frame - break_next_frame && (@goto skip) - get(frame.linfo).def.module == Base || continue - sff = string(frame.func) - if frame.func == fun || startswith(sff, clos) || startswith(sff, kw) - break_next_frame = true - end - end - end - @label skip - _redirect(io, log_to, sf) -end - -@inline function redirect(io::IO, log_to::Dict, arg::Union{Symbol,StackTraces.StackFrame}) - if isempty(log_to) - return io - else - if length(log_to)==1 && haskey(log_to,(nothing,nothing)) - return log_to[(nothing,nothing)] - else - return _redirect(io, log_to, arg) - end - end -end - -""" - logging(io [, m [, f]][; kind=:all]) - logging([; kind=:all]) - -Stream output of informational, warning, and/or error messages to `io`, -overriding what was otherwise specified. Optionally, divert stream only for -module `m`, or specifically function `f` within `m`. `kind` can be `:all` (the -default), `:info`, `:warn`, or `:error`. See `Base.log_{info,warn,error}_to` -for the current set of redirections. Call `logging` with no arguments (or just -the `kind`) to reset everything. -""" -function logging(io::IO, m::Union{Module,Void}=nothing, f::Union{Symbol,Void}=nothing; - kind::Symbol=:all) - (kind==:all || kind==:info) && (log_info_to[(m,f)] = io) - (kind==:all || kind==:warn) && (log_warn_to[(m,f)] = io) - (kind==:all || kind==:error) && (log_error_to[(m,f)] = io) - nothing -end - -function logging(; kind::Symbol=:all) - (kind==:all || kind==:info) && empty!(log_info_to) - (kind==:all || kind==:warn) && empty!(log_warn_to) - (kind==:all || kind==:error) && empty!(log_error_to) - nothing -end - -""" - info([io, ] msg..., [prefix="INFO: "]) - -Display an informational message. -Argument `msg` is a string describing the information to be displayed. -The `prefix` keyword argument can be used to override the default -prepending of `msg`. - -```jldoctest -julia> info("hello world") -INFO: hello world - -julia> info("hello world"; prefix="MY INFO: ") -MY INFO: hello world -``` - -See also [`logging`](@ref). -""" -function info(io::IO, msg...; prefix="INFO: ") - buf = IOBuffer() - iob = redirect(IOContext(buf, io), log_info_to, :info) - print_with_color(info_color(), iob, prefix; bold = true) - println_with_color(info_color(), iob, chomp(string(msg...))) - print(io, String(take!(buf))) - return -end -info(msg...; prefix="INFO: ") = info(STDERR, msg..., prefix=prefix) - -# print a warning only once - -const have_warned = Set() - -warn_once(io::IO, msg...) = warn(io, msg..., once=true) -warn_once(msg...) = warn(STDERR, msg..., once=true) - -""" - warn([io, ] msg..., [prefix="WARNING: ", once=false, key=nothing, bt=nothing, filename=nothing, lineno::Int=0]) - -Display a warning. Argument `msg` is a string describing the warning to be -displayed. Set `once` to true and specify a `key` to only display `msg` the -first time `warn` is called. If `bt` is not `nothing` a backtrace is displayed. -If `filename` is not `nothing` both it and `lineno` are displayed. - -See also [`logging`](@ref). -""" -function warn(io::IO, msg...; - prefix="WARNING: ", once=false, key=nothing, bt=nothing, - filename=nothing, lineno::Int=0) - str = chomp(string(msg...)) - if once - if key === nothing - key = str - end - (key in have_warned) && return - push!(have_warned, key) - end - buf = IOBuffer() - iob = redirect(IOContext(buf, io), log_warn_to, :warn) - print_with_color(warn_color(), iob, prefix; bold = true) - print_with_color(warn_color(), iob, str) - if bt !== nothing - show_backtrace(iob, bt) - end - if filename !== nothing - print(iob, "\nwhile loading $filename, in expression starting on line $lineno") - end - println(iob) - print(io, String(take!(buf))) - return -end - -""" - warn(msg) - -Display a warning. Argument `msg` is a string describing the warning to be displayed. - -```jldoctest -julia> warn("Beep Beep") -WARNING: Beep Beep -``` -""" -warn(msg...; kw...) = warn(STDERR, msg...; kw...) - -warn(io::IO, err::Exception; prefix="ERROR: ", kw...) = - warn(io, sprint(showerror, err), prefix=prefix; kw...) - -warn(err::Exception; prefix="ERROR: ", kw...) = - warn(STDERR, err, prefix=prefix; kw...) - -info(io::IO, err::Exception; prefix="ERROR: ", kw...) = - info(io, sprint(showerror, err), prefix=prefix; kw...) - -info(err::Exception; prefix="ERROR: ", kw...) = - info(STDERR, err, prefix=prefix; kw...) - -function julia_cmd(julia=joinpath(JULIA_HOME, julia_exename())) - opts = JLOptions() - cpu_target = unsafe_string(opts.cpu_target) - image_file = unsafe_string(opts.image_file) - compile = if opts.compile_enabled == 0 - "no" - elseif opts.compile_enabled == 2 - "all" - elseif opts.compile_enabled == 3 - "min" - else - "yes" - end - depwarn = if opts.depwarn == 0 - "no" - elseif opts.depwarn == 2 - "error" - else - "yes" - end - `$julia -C$cpu_target -J$image_file --compile=$compile --depwarn=$depwarn` -end - -function julia_exename() - if ccall(:jl_is_debugbuild, Cint, ()) == 0 - return @static is_windows() ? "julia.exe" : "julia" - else - return @static is_windows() ? "julia-debug.exe" : "julia-debug" - end -end - -""" - securezero!(o) - -`securezero!` fills the memory associated with an object `o` with zeros. -Unlike `fill!(o,0)` and similar code, which might be optimized away by -the compiler for objects about to be discarded, the `securezero!` function -will always be called. -""" -function securezero! end -@noinline securezero!(a::AbstractArray{<:Number}) = fill!(a, 0) -securezero!(s::String) = unsafe_securezero!(pointer(s), sizeof(s)) -@noinline unsafe_securezero!{T}(p::Ptr{T}, len::Integer=1) = - ccall(:memset, Ptr{T}, (Ptr{T}, Cint, Csize_t), p, 0, len*sizeof(T)) -unsafe_securezero!(p::Ptr{Void}, len::Integer=1) = Ptr{Void}(unsafe_securezero!(Ptr{UInt8}(p), len)) - -if is_windows() -function getpass(prompt::AbstractString) - print(prompt) - flush(STDOUT) - p = Vector{UInt8}(128) # mimic Unix getpass in ignoring more than 128-char passwords - # (also avoids any potential memory copies arising from push!) - try - plen = 0 - while true - c = ccall(:_getch, UInt8, ()) - if c == 0xff || c == UInt8('\n') || c == UInt8('\r') - break # EOF or return - elseif c == 0x00 || c == 0xe0 - ccall(:_getch, UInt8, ()) # ignore function/arrow keys - elseif c == UInt8('\b') && plen > 0 - plen -= 1 # delete last character on backspace - elseif !iscntrl(Char(c)) && plen < 128 - p[plen += 1] = c - end - end - return unsafe_string(pointer(p), plen) # use unsafe_string rather than String(p[1:plen]) - # to be absolutely certain we never make an extra copy - finally - securezero!(p) - end - - return "" -end -else -getpass(prompt::AbstractString) = unsafe_string(ccall(:getpass, Cstring, (Cstring,), prompt)) -end - -# Windows authentication prompt -if is_windows() - struct CREDUI_INFO - cbSize::UInt32 - parent::Ptr{Void} - pszMessageText::Ptr{UInt16} - pszCaptionText::Ptr{UInt16} - banner::Ptr{Void} - end - - const CREDUIWIN_GENERIC = 0x0001 - const CREDUIWIN_IN_CRED_ONLY = 0x0020 - const CREDUIWIN_ENUMERATE_CURRENT_USER = 0x0200 - - const CRED_PACK_GENERIC_CREDENTIALS = 0x0004 - - const ERROR_SUCCESS = 0x0000 - const ERROR_CANCELLED = 0x04c7 - - function winprompt(message, caption, default_username; prompt_username = true) - # Step 1: Create an encrypted username/password bundle that will be used to set - # the default username (in theory could also provide a default password) - credbuf = Array{UInt8,1}(1024) - credbufsize = Ref{UInt32}(sizeof(credbuf)) - succeeded = ccall((:CredPackAuthenticationBufferW, "credui.dll"), stdcall, Bool, - (UInt32, Cwstring, Cwstring, Ptr{UInt8}, Ptr{UInt32}), - CRED_PACK_GENERIC_CREDENTIALS, default_username, "", credbuf, credbufsize) - @assert succeeded - - # Step 2: Create the actual dialog - # 2.1: Set up the window - messageArr = Base.cwstring(message) - captionArr = Base.cwstring(caption) - pfSave = Ref{Bool}(false) - cred = Ref{CREDUI_INFO}(CREDUI_INFO(sizeof(CREDUI_INFO), C_NULL, pointer(messageArr), pointer(captionArr), C_NULL)) - dwflags = CREDUIWIN_GENERIC | CREDUIWIN_ENUMERATE_CURRENT_USER - if !prompt_username - # Disable setting anything other than default_username - dwflags |= CREDUIWIN_IN_CRED_ONLY - end - authPackage = Ref{Culong}(0) - outbuf_data = Ref{Ptr{Void}}(C_NULL) - outbuf_size = Ref{Culong}(0) - - # 2.2: Do the actual request - code = ccall((:CredUIPromptForWindowsCredentialsW, "credui.dll"), stdcall, UInt32, (Ptr{CREDUI_INFO}, UInt32, Ptr{Culong}, - Ptr{Void}, Culong, Ptr{Ptr{Void}}, Ptr{Culong}, Ptr{Bool}, UInt32), cred, 0, authPackage, credbuf, credbufsize[], - outbuf_data, outbuf_size, pfSave, dwflags) - - # 2.3: If that failed for any reason other than the user canceling, error out. - # If the user canceled, just return a nullable - if code == ERROR_CANCELLED - return Nullable{Tuple{String,String}}() - elseif code != ERROR_SUCCESS - error(Base.Libc.FormatMessage(code)) - end - - # Step 3: Convert encrypted credentials back to plain text - passbuf = Array{UInt16,1}(1024) - passlen = Ref{UInt32}(length(passbuf)) - usernamebuf = Array{UInt16,1}(1024) - usernamelen = Ref{UInt32}(length(usernamebuf)) - # Need valid buffers for domain, even though we don't care - dummybuf = Array{UInt16,1}(1024) - succeeded = ccall((:CredUnPackAuthenticationBufferW, "credui.dll"), Bool, - (UInt32, Ptr{Void}, UInt32, Ptr{UInt16}, Ptr{UInt32}, Ptr{UInt16}, Ptr{UInt32}, Ptr{UInt16}, Ptr{UInt32}), - 0, outbuf_data[], outbuf_size[], usernamebuf, usernamelen, dummybuf, Ref{UInt32}(1024), passbuf, passlen) - if !succeeded - error(Base.Libc.FormatMessage()) - end - - # Step 4: Free the encrypted buffer - # ccall(:SecureZeroMemory, Ptr{Void}, (Ptr{Void}, Csize_t), outbuf_data[], outbuf_size[]) - not an actual function - unsafe_securezero!(outbuf_data[], outbuf_size[]) - ccall((:CoTaskMemFree, "ole32.dll"), Void, (Ptr{Void},), outbuf_data[]) - - # Done. - passbuf_ = passbuf[1:passlen[]-1] - result = Nullable((String(transcode(UInt8, usernamebuf[1:usernamelen[]-1])), - String(transcode(UInt8, passbuf_)))) - securezero!(passbuf_) - securezero!(passbuf) - - return result - end - -end - -""" - crc32c(data, crc::UInt32=0x00000000) -Compute the CRC-32c checksum of the given `data`, which can be -an `Array{UInt8}` or a `String`. Optionally, you can pass -a starting `crc` integer to be mixed in with the checksum. -(Technically, a little-endian checksum is computed.) -""" -function crc32c end -crc32c(a::Union{Array{UInt8},String}, crc::UInt32=0x00000000) = - ccall(:jl_crc32c, UInt32, (UInt32, Ptr{UInt8}, Csize_t), crc, a, sizeof(a)) - -""" - @kwdef typedef - -This is a helper macro that automatically defines a keyword-based constructor for the type -declared in the expression `typedef`, which must be a `struct` or `mutable struct` -expression. The default argument is supplied by declaring fields of the form `field::T = -default`. If no default is provided then the default is provided by the `kwdef_val(T)` -function. - -```julia -@kwdef struct Foo - a::Cint # implied default Cint(0) - b::Cint = 1 # specified default - z::Cstring # implied default Cstring(C_NULL) - y::Bar # implied default Bar() -end -``` -""" -macro kwdef(expr) - expr = macroexpand(expr) # to expand @static - T = expr.args[2] - params_ex = Expr(:parameters) - call_ex = Expr(:call, T) - _kwdef!(expr.args[3], params_ex, call_ex) - quote - Base.@__doc__($(esc(expr))) - $(esc(Expr(:call,T,params_ex))) = $(esc(call_ex)) - end -end - -# @kwdef helper function -# mutates arguments inplace -function _kwdef!(blk, params_ex, call_ex) - for i in eachindex(blk.args) - ei = blk.args[i] - isa(ei, Expr) || continue - if ei.head == :(=) - # var::Typ = defexpr - dec = ei.args[1] # var::Typ - var = dec.args[1] # var - def = ei.args[2] # defexpr - push!(params_ex.args, Expr(:kw, var, def)) - push!(call_ex.args, var) - blk.args[i] = dec - elseif ei.head == :(::) - dec = ei # var::Typ - var = dec.args[1] # var - def = :(Base.kwdef_val($(ei.args[2]))) - push!(params_ex.args, Expr(:kw, var, def)) - push!(call_ex.args, dec.args[1]) - elseif ei.head == :block - # can arise with use of @static inside type decl - _kwdef!(ei, params_ex, call_ex) - end - end - blk -end - - - -""" - kwdef_val(T) - -The default value for a type for use with the `@kwdef` macro. Returns: - - - null pointer for pointer types (`Ptr{T}`, `Cstring`, `Cwstring`) - - zero for integer types - - no-argument constructor calls (e.g. `T()`) for all other types -""" -function kwdef_val end - -kwdef_val(::Type{Ptr{T}}) where {T} = Ptr{T}(C_NULL) -kwdef_val(::Type{Cstring}) = Cstring(C_NULL) -kwdef_val(::Type{Cwstring}) = Cwstring(C_NULL) - -kwdef_val(::Type{T}) where {T<:Integer} = zero(T) - -kwdef_val(::Type{T}) where {T} = T() diff --git a/julia-0.6.3/share/julia/base/version.jl b/julia-0.6.3/share/julia/base/version.jl deleted file mode 100644 index c05fc42..0000000 --- a/julia-0.6.3/share/julia/base/version.jl +++ /dev/null @@ -1,279 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -## semantic version numbers (http://semver.org) - -struct VersionNumber - major::Int - minor::Int - patch::Int - prerelease::Tuple{Vararg{Union{Int,String}}} - build::Tuple{Vararg{Union{Int,String}}} - - function VersionNumber(major::Int, minor::Int, patch::Int, - pre::Tuple{Vararg{Union{Int,String}}}, - bld::Tuple{Vararg{Union{Int,String}}}) - major >= 0 || throw(ArgumentError("invalid negative major version: $major")) - minor >= 0 || throw(ArgumentError("invalid negative minor version: $minor")) - patch >= 0 || throw(ArgumentError("invalid negative patch version: $patch")) - for ident in pre - if isa(ident,Int) - ident >= 0 || throw(ArgumentError("invalid negative pre-release identifier: $ident")) - else - if !ismatch(r"^(?:|[0-9a-z-]*[a-z-][0-9a-z-]*)$"i, ident) || - isempty(ident) && !(length(pre)==1 && isempty(bld)) - throw(ArgumentError("invalid pre-release identifier: $(repr(ident))")) - end - end - end - for ident in bld - if isa(ident,Int) - ident >= 0 || throw(ArgumentError("invalid negative build identifier: $ident")) - else - if !ismatch(r"^(?:|[0-9a-z-]*[a-z-][0-9a-z-]*)$"i, ident) || - isempty(ident) && length(bld)!=1 - throw(ArgumentError("invalid build identifier: $(repr(ident))")) - end - end - end - new(major, minor, patch, pre, bld) - end -end -VersionNumber(major::Integer, minor::Integer = 0, patch::Integer = 0, - pre::Tuple{Vararg{Union{Integer,AbstractString}}} = (), - bld::Tuple{Vararg{Union{Integer,AbstractString}}} = ()) = - VersionNumber(Int(major), Int(minor), Int(patch), - map(x->isa(x,Integer) ? Int(x) : String(x), pre), - map(x->isa(x,Integer) ? Int(x) : String(x), bld)) - -function print(io::IO, v::VersionNumber) - v == typemax(VersionNumber) && return print(io, "∞") - print(io, v.major) - print(io, '.') - print(io, v.minor) - print(io, '.') - print(io, v.patch) - if !isempty(v.prerelease) - print(io, '-') - join(io, v.prerelease,'.') - end - if !isempty(v.build) - print(io, '+') - join(io, v.build,'.') - end -end -show(io::IO, v::VersionNumber) = print(io, "v\"", v, "\"") - -convert(::Type{VersionNumber}, v::Integer) = VersionNumber(v) -convert(::Type{VersionNumber}, v::Tuple) = VersionNumber(v...) - -const VERSION_REGEX = r"^ - v? # prefix (optional) - (\d+) # major (required) - (?:\.(\d+))? # minor (optional) - (?:\.(\d+))? # patch (optional) - (?:(-)| # pre-release (optional) - ([a-z][0-9a-z-]*(?:\.[0-9a-z-]+)*|-(?:[0-9a-z-]+\.)*[0-9a-z-]+)? - (?:(\+)| - (?:\+((?:[0-9a-z-]+\.)*[0-9a-z-]+))? # build (optional) - )) -$"ix - -function split_idents(s::AbstractString) - idents = split(s, '.') - ntuple(length(idents)) do i - ident = idents[i] - ismatch(r"^\d+$", ident) ? parse(Int, ident) : String(ident) - end -end - -function VersionNumber(v::AbstractString) - m = match(VERSION_REGEX, v) - m === nothing && throw(ArgumentError("invalid version string: $v")) - major, minor, patch, minus, prerl, plus, build = m.captures - major = parse(Int, major) - minor = minor !== nothing ? parse(Int, minor) : 0 - patch = patch !== nothing ? parse(Int, patch) : 0 - if prerl !== nothing && !isempty(prerl) && prerl[1] == '-' - prerl = prerl[2:end] # strip leading '-' - end - prerl = prerl !== nothing ? split_idents(prerl) : minus !== nothing ? ("",) : () - build = build !== nothing ? split_idents(build) : plus !== nothing ? ("",) : () - VersionNumber(major, minor, patch, prerl, build) -end - -convert(::Type{VersionNumber}, v::AbstractString) = VersionNumber(v) - -macro v_str(v); VersionNumber(v); end - -typemin(::Type{VersionNumber}) = v"0-" -typemax(::Type{VersionNumber}) = VersionNumber(typemax(Int),typemax(Int),typemax(Int),(),("",)) - -ident_cmp(a::Int, b::Int) = cmp(a,b) -ident_cmp(a::Int, b::String) = isempty(b) ? +1 : -1 -ident_cmp(a::String, b::Int) = isempty(a) ? -1 : +1 -ident_cmp(a::String, b::String) = cmp(a,b) - -function ident_cmp(A::Tuple{Vararg{Union{Int,String}}}, - B::Tuple{Vararg{Union{Int,String}}}) - i = start(A) - j = start(B) - while !done(A,i) && !done(B,i) - a,i = next(A,i) - b,j = next(B,j) - c = ident_cmp(a,b) - (c != 0) && return c - end - done(A,i) && !done(B,j) ? -1 : - !done(A,i) && done(B,j) ? +1 : 0 -end - -function ==(a::VersionNumber, b::VersionNumber) - (a.major != b.major) && return false - (a.minor != b.minor) && return false - (a.patch != b.patch) && return false - (ident_cmp(a.prerelease,b.prerelease) != 0) && return false - (ident_cmp(a.build,b.build) != 0) && return false - return true -end - -issupbuild(v::VersionNumber) = length(v.build)==1 && isempty(v.build[1]) - -function isless(a::VersionNumber, b::VersionNumber) - (a.major < b.major) && return true - (a.major > b.major) && return false - (a.minor < b.minor) && return true - (a.minor > b.minor) && return false - (a.patch < b.patch) && return true - (a.patch > b.patch) && return false - (!isempty(a.prerelease) && isempty(b.prerelease)) && return true - (isempty(a.prerelease) && !isempty(b.prerelease)) && return false - c = ident_cmp(a.prerelease,b.prerelease) - (c < 0) && return true - (c > 0) && return false - (!issupbuild(a) && issupbuild(b)) && return true - (issupbuild(a) && !issupbuild(b)) && return false - c = ident_cmp(a.build,b.build) - (c < 0) && return true - return false -end - -function hash(v::VersionNumber, h::UInt) - h += 0x8ff4ffdb75f9fede % UInt - h = hash(v.major, h) - h = hash(v.minor, h) - h = hash(v.patch, h) - h = hash(v.prerelease, ~h) - h = hash(v.build, ~h) -end - -lowerbound(v::VersionNumber) = VersionNumber(v.major, v.minor, v.patch, ("",), ()) -upperbound(v::VersionNumber) = VersionNumber(v.major, v.minor, v.patch, (), ("",)) - -thispatch(v::VersionNumber) = VersionNumber(v.major, v.minor, v.patch) -thisminor(v::VersionNumber) = VersionNumber(v.major, v.minor, 0) -thismajor(v::VersionNumber) = VersionNumber(v.major, 0, 0) - -nextpatch(v::VersionNumber) = v < thispatch(v) ? thispatch(v) : VersionNumber(v.major, v.minor, v.patch+1) -nextminor(v::VersionNumber) = v < thisminor(v) ? thisminor(v) : VersionNumber(v.major, v.minor+1, 0) -nextmajor(v::VersionNumber) = v < thismajor(v) ? thismajor(v) : VersionNumber(v.major+1, 0, 0) - -function check_new_version(existing::Vector{VersionNumber}, ver::VersionNumber) - @assert issorted(existing) - if isempty(existing) - for v in [v"0", v"0.0.1", v"0.1", v"1"] - lowerbound(v) <= ver <= v && return - end - error("$ver is not a valid initial version (try 0.0.0, 0.0.1, 0.1 or 1.0)") - end - idx = searchsortedlast(existing,ver) - prv = existing[idx] - ver == prv && error("version $ver already exists") - nxt = thismajor(ver) != thismajor(prv) ? nextmajor(prv) : - thisminor(ver) != thisminor(prv) ? nextminor(prv) : nextpatch(prv) - ver <= nxt || error("$ver skips over $nxt") - thispatch(ver) <= ver && return # regular or build release - idx < length(existing) && thispatch(existing[idx+1]) <= nxt && - error("$ver is a pre-release of existing version $(existing[idx+1])") - return # acceptable new version -end - -## julia version info - -""" - VERSION - -A `VersionNumber` object describing which version of Julia is in use. For details see -[Version Number Literals](@ref man-version-number-literals). -""" -const VERSION = try - ver = convert(VersionNumber, VERSION_STRING) - if !isempty(ver.prerelease) - if GIT_VERSION_INFO.build_number >= 0 - ver = VersionNumber(ver.major, ver.minor, ver.patch, (ver.prerelease..., GIT_VERSION_INFO.build_number), ver.build) - else - println("WARNING: no build number found for pre-release version") - ver = VersionNumber(ver.major, ver.minor, ver.patch, (ver.prerelease..., "unknown"), ver.build) - end - elseif GIT_VERSION_INFO.build_number > 0 - println("WARNING: ignoring non-zero build number for VERSION") - end - ver -catch e - println("while creating Base.VERSION, ignoring error $e") - VersionNumber(0) -end - -function banner(io::IO = STDOUT) - if GIT_VERSION_INFO.tagged_commit - commit_string = TAGGED_RELEASE_BANNER - elseif isempty(GIT_VERSION_INFO.commit) - commit_string = "" - else - days = Int(floor((ccall(:jl_clock_now, Float64, ()) - GIT_VERSION_INFO.fork_master_timestamp) / (60 * 60 * 24))) - days = max(0, days) - unit = days == 1 ? "day" : "days" - distance = GIT_VERSION_INFO.fork_master_distance - commit = GIT_VERSION_INFO.commit_short - - if distance == 0 - commit_string = "Commit $(commit) ($(days) $(unit) old release-0.6)" - else - branch = GIT_VERSION_INFO.branch - commit_string = "$(branch)/$(commit) (fork: $(distance) commits, $(days) $(unit))" - end - end - commit_date = !isempty(GIT_VERSION_INFO.date_string) ? " ($(GIT_VERSION_INFO.date_string))": "" - - if have_color - c = text_colors - tx = c[:normal] # text - jl = c[:normal] # julia - d1 = c[:bold] * c[:blue] # first dot - d2 = c[:bold] * c[:red] # second dot - d3 = c[:bold] * c[:green] # third dot - d4 = c[:bold] * c[:magenta] # fourth dot - - print(io,""" $(d3)_$(tx) - $(d1)_$(tx) $(jl)_$(tx) $(d2)_$(d3)(_)$(d4)_$(tx) | A fresh approach to technical computing - $(d1)(_)$(jl) | $(d2)(_)$(tx) $(d4)(_)$(tx) | Documentation: https://docs.julialang.org - $(jl)_ _ _| |_ __ _$(tx) | Type \"?help\" for help. - $(jl)| | | | | | |/ _` |$(tx) | - $(jl)| | |_| | | | (_| |$(tx) | Version $(VERSION)$(commit_date) - $(jl)_/ |\\__'_|_|_|\\__'_|$(tx) | $(commit_string) - $(jl)|__/$(tx) | $(Sys.MACHINE) - - """) - else - print(io,""" - _ - _ _ _(_)_ | A fresh approach to technical computing - (_) | (_) (_) | Documentation: https://docs.julialang.org - _ _ _| |_ __ _ | Type \"?help\" for help. - | | | | | | |/ _` | | - | | |_| | | | (_| | | Version $(VERSION)$(commit_date) - _/ |\\__'_|_|_|\\__'_| | $(commit_string) - |__/ | $(Sys.MACHINE) - - """) - end -end diff --git a/julia-0.6.3/share/julia/base/weakkeydict.jl b/julia-0.6.3/share/julia/base/weakkeydict.jl deleted file mode 100644 index 9c1c527..0000000 --- a/julia-0.6.3/share/julia/base/weakkeydict.jl +++ /dev/null @@ -1,147 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -# weak key dictionaries - -""" - WeakKeyDict([itr]) - -`WeakKeyDict()` constructs a hash table where the keys are weak -references to objects, and thus may be garbage collected even when -referenced in a hash table. - -See [`Dict`](@ref) for further help. -""" -mutable struct WeakKeyDict{K,V} <: Associative{K,V} - ht::Dict{WeakRef,V} - lock::Threads.RecursiveSpinLock - finalizer::Function - - # Constructors mirror Dict's - function WeakKeyDict{K,V}() where V where K - t = new(Dict{Any,V}(), Threads.RecursiveSpinLock(), identity) - t.finalizer = function (k) - # when a weak key is finalized, remove from dictionary if it is still there - islocked(t) && return finalizer(k, t.finalizer) - delete!(t, k) - end - return t - end -end -function WeakKeyDict{K,V}(kv) where V where K - h = WeakKeyDict{K,V}() - for (k,v) in kv - h[k] = v - end - return h -end -WeakKeyDict{K,V}(p::Pair) where V where K = setindex!(WeakKeyDict{K,V}(), p.second, p.first) -function WeakKeyDict{K,V}(ps::Pair...) where V where K - h = WeakKeyDict{K,V}() - sizehint!(h, length(ps)) - for p in ps - h[p.first] = p.second - end - return h -end -WeakKeyDict() = WeakKeyDict{Any,Any}() - -WeakKeyDict(kv::Tuple{}) = WeakKeyDict() -copy(d::WeakKeyDict) = WeakKeyDict(d) - -WeakKeyDict{K,V}(ps::Pair{K,V}...) = WeakKeyDict{K,V}(ps) -WeakKeyDict{K }(ps::Pair{K}...,) = WeakKeyDict{K,Any}(ps) -WeakKeyDict{V }(ps::(Pair{K,V} where K)...,) = WeakKeyDict{Any,V}(ps) -WeakKeyDict( ps::Pair...) = WeakKeyDict{Any,Any}(ps) - -function WeakKeyDict(kv) - try - Base.associative_with_eltype((K, V) -> WeakKeyDict{K, V}, kv, eltype(kv)) - catch e - if !applicable(start, kv) || !all(x->isa(x,Union{Tuple,Pair}),kv) - throw(ArgumentError("WeakKeyDict(kv): kv needs to be an iterator of tuples or pairs")) - else - rethrow(e) - end - end -end - -similar(d::WeakKeyDict{K,V}) where {K,V} = WeakKeyDict{K,V}() -similar(d::WeakKeyDict, ::Type{Pair{K,V}}) where {K,V} = WeakKeyDict{K,V}() - -# conversion between Dict types -function convert(::Type{WeakKeyDict{K,V}},d::Associative) where V where K - h = WeakKeyDict{K,V}() - for (k,v) in d - ck = convert(K,k) - if !haskey(h,ck) - h[ck] = convert(V,v) - else - error("key collision during dictionary conversion") - end - end - return h -end -convert(::Type{WeakKeyDict{K,V}},d::WeakKeyDict{K,V}) where {K,V} = d - -islocked(wkh::WeakKeyDict) = islocked(wkh.lock) -lock(f, wkh::WeakKeyDict) = lock(f, wkh.lock) -trylock(f, wkh::WeakKeyDict) = trylock(f, wkh.lock) - -function setindex!(wkh::WeakKeyDict{K}, v, key) where K - k = convert(K, key) - finalizer(k, wkh.finalizer) - lock(wkh) do - wkh.ht[WeakRef(k)] = v - end - return wkh -end - -function getkey(wkh::WeakKeyDict{K}, kk, default) where K - return lock(wkh) do - k = getkey(wkh.ht, kk, secret_table_token) - k === secret_table_token && return default - return k.value::K - end -end - -get(wkh::WeakKeyDict{K}, key, default) where {K} = lock(() -> get(wkh.ht, key, default), wkh) -get(default::Callable, wkh::WeakKeyDict{K}, key) where {K} = lock(() -> get(default, wkh.ht, key), wkh) -get!(wkh::WeakKeyDict{K}, key, default) where {K} = lock(() -> get!(wkh.ht, key, default), wkh) -get!(default::Callable, wkh::WeakKeyDict{K}, key) where {K} = lock(() -> get!(default, wkh.ht, key), wkh) -pop!(wkh::WeakKeyDict{K}, key) where {K} = lock(() -> pop!(wkh.ht, key), wkh) -pop!(wkh::WeakKeyDict{K}, key, default) where {K} = lock(() -> pop!(wkh.ht, key, default), wkh) -delete!{K}(wkh::WeakKeyDict{K}, key) = lock(() -> delete!(wkh.ht, key), wkh) -empty!(wkh::WeakKeyDict) = (lock(() -> empty!(wkh.ht), wkh); wkh) -haskey(wkh::WeakKeyDict{K}, key) where {K} = lock(() -> haskey(wkh.ht, key), wkh) -getindex(wkh::WeakKeyDict{K}, key) where {K} = lock(() -> getindex(wkh.ht, key), wkh) -isempty(wkh::WeakKeyDict) = isempty(wkh.ht) -length(t::WeakKeyDict) = length(t.ht) - -function start(t::WeakKeyDict{K,V}) where V where K - gc_token = Ref{Bool}(false) # no keys will be deleted via finalizers until this token is gc'd - finalizer(gc_token, function(r) - if r[] - r[] = false - unlock(t.lock) - end - end) - s = lock(t.lock) - gc_token[] = true - return (start(t.ht), gc_token) -end -done(t::WeakKeyDict, i) = done(t.ht, i[1]) -function next(t::WeakKeyDict{K,V}, i) where V where K - gc_token = i[2] - wkv, i = next(t.ht, i[1]) - kv = Pair{K,V}(wkv[1].value::K, wkv[2]) - return (kv, (i, gc_token)) -end - -function filter!(f, d::WeakKeyDict) - for (k, v) in d - if !f(k, v) - delete!(d, k) - end - end - return d -end diff --git a/julia-0.6.3/share/julia/build_sysimg.jl b/julia-0.6.3/share/julia/build_sysimg.jl deleted file mode 100755 index 7ca643f..0000000 --- a/julia-0.6.3/share/julia/build_sysimg.jl +++ /dev/null @@ -1,201 +0,0 @@ -#!/usr/bin/env julia -# This file is a part of Julia. License is MIT: https://julialang.org/license - -# Build a system image binary at sysimg_path.dlext. Allow insertion of a userimg via -# userimg_path. If sysimg_path.dlext is currently loaded into memory, don't continue -# unless force is set to true. Allow targeting of a CPU architecture via cpu_target. -function default_sysimg_path(debug=false) - if is_unix() - splitext(Libdl.dlpath(debug ? "sys-debug" : "sys"))[1] - else - joinpath(dirname(JULIA_HOME), "lib", "julia", debug ? "sys-debug" : "sys") - end -end - -""" - build_sysimg(sysimg_path=default_sysimg_path(), cpu_target="native", userimg_path=nothing; force=false) - -Rebuild the system image. Store it in `sysimg_path`, which defaults to a file named `sys.ji` -that sits in the same folder as `libjulia.{so,dylib}`, except on Windows where it defaults -to `JULIA_HOME/../lib/julia/sys.ji`. Use the cpu instruction set given by `cpu_target`. -Valid CPU targets are the same as for the `-C` option to `julia`, or the `-march` option to -`gcc`. Defaults to `native`, which means to use all CPU instructions available on the -current processor. Include the user image file given by `userimg_path`, which should contain -directives such as `using MyPackage` to include that package in the new system image. New -system image will not replace an older image unless `force` is set to true. -""" -function build_sysimg(sysimg_path=nothing, cpu_target="native", userimg_path=nothing; force=false, debug=false) - if sysimg_path === nothing - sysimg_path = default_sysimg_path(debug) - end - - # Quit out if a sysimg is already loaded and is in the same spot as sysimg_path, unless forcing - sysimg = Libdl.dlopen_e("sys") - if sysimg != C_NULL - if !force && Base.samefile(Libdl.dlpath(sysimg), "$(sysimg_path).$(Libdl.dlext)") - info("System image already loaded at $(Libdl.dlpath(sysimg)), set force=true to override.") - return nothing - end - end - - # Canonicalize userimg_path before we enter the base_dir - if userimg_path !== nothing - userimg_path = abspath(userimg_path) - end - - # Enter base and setup some useful paths - base_dir = dirname(Base.find_source_file("sysimg.jl")) - cd(base_dir) do - julia = joinpath(JULIA_HOME, debug ? "julia-debug" : "julia") - cc = find_system_compiler() - - # Ensure we have write-permissions to wherever we're trying to write to - try - touch("$sysimg_path.ji") - catch - err_msg = "Unable to modify $sysimg_path.ji, ensure parent directory exists " - err_msg *= "and is writable; absolute paths work best.)" - error(err_msg) - end - - # Copy in userimg.jl if it exists - if userimg_path !== nothing - if !isfile(userimg_path) - error("$userimg_path is not found, ensure it is an absolute path.") - end - if isfile("userimg.jl") - error("$base_dir/userimg.jl already exists, delete manually to continue.") - end - cp(userimg_path, "userimg.jl") - end - try - # Start by building inference.{ji,o} - inference_path = joinpath(dirname(sysimg_path), "inference") - info("Building inference.o") - info("$julia -C $cpu_target --output-ji $inference_path.ji --output-o $inference_path.o coreimg.jl") - run(`$julia -C $cpu_target --output-ji $inference_path.ji --output-o $inference_path.o coreimg.jl`) - - # Bootstrap off of that to create sys.{ji,o} - info("Building sys.o") - info("$julia -C $cpu_target --output-ji $sysimg_path.ji --output-o $sysimg_path.o -J $inference_path.ji --startup-file=no sysimg.jl") - run(`$julia -C $cpu_target --output-ji $sysimg_path.ji --output-o $sysimg_path.o -J $inference_path.ji --startup-file=no sysimg.jl`) - - if cc !== nothing - link_sysimg(sysimg_path, cc, debug) - else - info("System image successfully built at $sysimg_path.ji.") - end - - if !Base.samefile("$(default_sysimg_path(debug)).ji", "$sysimg_path.ji") - if Base.isfile("$sysimg_path.$(Libdl.dlext)") - info("To run Julia with this image loaded, run: `julia -J $sysimg_path.$(Libdl.dlext)`.") - else - info("To run Julia with this image loaded, run: `julia -J $sysimg_path.ji`.") - end - else - info("Julia will automatically load this system image at next startup.") - end - finally - # Cleanup userimg.jl - if userimg_path !== nothing && isfile("userimg.jl") - rm("userimg.jl") - end - end - end -end - -# Search for a compiler to link sys.o into sys.dl_ext. Honor LD environment variable. -function find_system_compiler() - if haskey(ENV, "CC") - if !success(`$(ENV["CC"]) -v`) - warn("Using compiler override $(ENV["CC"]), but unable to run `$(ENV["CC"]) -v`.") - end - return ENV["CC"] - end - - # On Windows, check to see if WinRPM is installed, and if so, see if gcc is installed - if is_windows() - try - eval(Main, :(using WinRPM)) - winrpmgcc = joinpath(WinRPM.installdir, "usr", "$(Sys.ARCH)-w64-mingw32", - "sys-root", "mingw", "bin", "gcc.exe") - if success(`$winrpmgcc --version`) - return winrpmgcc - else - throw() - end - catch - warn("Install GCC via `Pkg.add(\"WinRPM\"); WinRPM.install(\"gcc\")` to generate sys.dll for faster startup times.") - end - end - - - # See if `cc` exists - try - if success(`cc -v`) - return "cc" - end - end - - warn("No supported compiler found; startup times will be longer.") -end - -# Link sys.o into sys.$(dlext) -function link_sysimg(sysimg_path=nothing, cc=find_system_compiler(), debug=false) - if sysimg_path === nothing - sysimg_path = default_sysimg_path(debug) - end - julia_libdir = dirname(Libdl.dlpath(debug ? "libjulia-debug" : "libjulia")) - - FLAGS = ["-L$julia_libdir"] - - push!(FLAGS, "-shared") - push!(FLAGS, debug ? "-ljulia-debug" : "-ljulia") - if is_windows() - push!(FLAGS, "-lssp") - end - - sysimg_file = "$sysimg_path.$(Libdl.dlext)" - info("Linking sys.$(Libdl.dlext)") - info("$cc $(join(FLAGS, ' ')) -o $sysimg_file $sysimg_path.o") - # Windows has difficulties overwriting a file in use so we first link to a temp file - if is_windows() && isfile(sysimg_file) - if success(pipeline(`$cc $FLAGS -o $sysimg_path.tmp $sysimg_path.o`; stdout=STDOUT, stderr=STDERR)) - mv(sysimg_file, "$sysimg_file.old"; remove_destination=true) - mv("$sysimg_path.tmp", sysimg_file; remove_destination=true) - end - else - run(`$cc $FLAGS -o $sysimg_file $sysimg_path.o`) - end - info("System image successfully built at $sysimg_path.$(Libdl.dlext)") -end - -# When running this file as a script, try to do so with default values. If arguments are passed -# in, use them as the arguments to build_sysimg above. -# -# Also check whether we are running `genstdlib.jl`, in which case we don't want to build a -# system image and instead only need `build_sysimg`'s docstring to be available. -if !isdefined(Main, :GenStdLib) && !isinteractive() - if length(ARGS) > 5 || ("--help" in ARGS || "-h" in ARGS) - println("Usage: build_sysimg.jl <sysimg_path> <cpu_target> <usrimg_path.jl> [--force] [--debug] [--help]") - println(" <sysimg_path> is an absolute, extensionless path to store the system image at") - println(" <cpu_target> is an LLVM cpu target to build the system image against") - println(" <usrimg_path.jl> is the path to a user image to be baked into the system image") - println(" --debug Using julia-debug instead of julia to build the system image") - println(" --force Set if you wish to overwrite the default system image") - println(" --help Print out this help text and exit") - println() - println(" Example:") - println(" build_sysimg.jl /usr/local/lib/julia/sys core2 ~/my_usrimg.jl --force") - println() - println(" Running this script with no arguments is equivalent to:") - println(" build_sysimg.jl $(default_sysimg_path()) native") - return 0 - end - - debug_flag = "--debug" in ARGS - filter!(x -> x != "--debug", ARGS) - force_flag = "--force" in ARGS - filter!(x -> x != "--force", ARGS) - build_sysimg(ARGS...; force=force_flag, debug=debug_flag) -end diff --git a/julia-0.6.3/share/julia/cert.pem b/julia-0.6.3/share/julia/cert.pem deleted file mode 100644 index b5f0878..0000000 --- a/julia-0.6.3/share/julia/cert.pem +++ /dev/null @@ -1,15581 +0,0 @@ -# This is a bundle of X.509 certificates of public Certificate -# Authorities. It was generated from the Mozilla root CA list. -# -# Source: nss/lib/ckfw/builtins/certdata.txt -# Source: nss/lib/ckfw/builtins/nssckbi.h -# -# Generated from: -# NSS_BUILTINS_LIBRARY_VERSION "2.14" -# -Certificate: - Data: - Version: 3 (0x2) - Serial Number: - 5e:c3:b7:a6:43:7f:a4:e0 - Signature Algorithm: sha1WithRSAEncryption - Issuer: CN=ACCVRAIZ1, OU=PKIACCV, O=ACCV, C=ES - Validity - Not Before: May 5 09:37:37 2011 GMT - Not After : Dec 31 09:37:37 2030 GMT - Subject: CN=ACCVRAIZ1, OU=PKIACCV, O=ACCV, C=ES - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (4096 bit) - Modulus: - 00:9b:a9:ab:bf:61:4a:97:af:2f:97:66:9a:74:5f: - d0:d9:96:fd:cf:e2:e4:66:ef:1f:1f:47:33:c2:44: - a3:df:9a:de:1f:b5:54:dd:15:7c:69:35:11:6f:bb: - c8:0c:8e:6a:18:1e:d8:8f:d9:16:bc:10:48:36:5c: - f0:63:b3:90:5a:5c:24:37:d7:a3:d6:cb:09:71:b9: - f1:01:72:84:b0:7d:db:4d:80:cd:fc:d3:6f:c9:f8: - da:b6:0e:82:d2:45:85:a8:1b:68:a8:3d:e8:f4:44: - 6c:bd:a1:c2:cb:03:be:8c:3e:13:00:84:df:4a:48: - c0:e3:22:0a:e8:e9:37:a7:18:4c:b1:09:0d:23:56: - 7f:04:4d:d9:17:84:18:a5:c8:da:40:94:73:eb:ce: - 0e:57:3c:03:81:3a:9d:0a:a1:57:43:69:ac:57:6d: - 79:90:78:e5:b5:b4:3b:d8:bc:4c:8d:28:a1:a7:a3: - a7:ba:02:4e:25:d1:2a:ae:ed:ae:03:22:b8:6b:20: - 0f:30:28:54:95:7f:e0:ee:ce:0a:66:9d:d1:40:2d: - 6e:22:af:9d:1a:c1:05:19:d2:6f:c0:f2:9f:f8:7b: - b3:02:42:fb:50:a9:1d:2d:93:0f:23:ab:c6:c1:0f: - 92:ff:d0:a2:15:f5:53:09:71:1c:ff:45:13:84:e6: - 26:5e:f8:e0:88:1c:0a:fc:16:b6:a8:73:06:b8:f0: - 63:84:02:a0:c6:5a:ec:e7:74:df:70:ae:a3:83:25: - ea:d6:c7:97:87:93:a7:c6:8a:8a:33:97:60:37:10: - 3e:97:3e:6e:29:15:d6:a1:0f:d1:88:2c:12:9f:6f: - aa:a4:c6:42:eb:41:a2:e3:95:43:d3:01:85:6d:8e: - bb:3b:f3:23:36:c7:fe:3b:e0:a1:25:07:48:ab:c9: - 89:74:ff:08:8f:80:bf:c0:96:65:f3:ee:ec:4b:68: - bd:9d:88:c3:31:b3:40:f1:e8:cf:f6:38:bb:9c:e4: - d1:7f:d4:e5:58:9b:7c:fa:d4:f3:0e:9b:75:91:e4: - ba:52:2e:19:7e:d1:f5:cd:5a:19:fc:ba:06:f6:fb: - 52:a8:4b:99:04:dd:f8:f9:b4:8b:50:a3:4e:62:89: - f0:87:24:fa:83:42:c1:87:fa:d5:2d:29:2a:5a:71: - 7a:64:6a:d7:27:60:63:0d:db:ce:49:f5:8d:1f:90: - 89:32:17:f8:73:43:b8:d2:5a:93:86:61:d6:e1:75: - 0a:ea:79:66:76:88:4f:71:eb:04:25:d6:0a:5a:7a: - 93:e5:b9:4b:17:40:0f:b1:b6:b9:f5:de:4f:dc:e0: - b3:ac:3b:11:70:60:84:4a:43:6e:99:20:c0:29:71: - 0a:c0:65 - Exponent: 65537 (0x10001) - X509v3 extensions: - Authority Information Access: - CA Issuers - URI:http://www.accv.es/fileadmin/Archivos/certificados/raizaccv1.crt - OCSP - URI:http://ocsp.accv.es - - X509v3 Subject Key Identifier: - D2:87:B4:E3:DF:37:27:93:55:F6:56:EA:81:E5:36:CC:8C:1E:3F:BD - X509v3 Basic Constraints: critical - CA:TRUE - X509v3 Authority Key Identifier: - keyid:D2:87:B4:E3:DF:37:27:93:55:F6:56:EA:81:E5:36:CC:8C:1E:3F:BD - - X509v3 Certificate Policies: - Policy: X509v3 Any Policy - User Notice: - Explicit Text: - CPS: http://www.accv.es/legislacion_c.htm - - X509v3 CRL Distribution Points: - - Full Name: - URI:http://www.accv.es/fileadmin/Archivos/certificados/raizaccv1_der.crl - - X509v3 Key Usage: critical - Certificate Sign, CRL Sign - X509v3 Subject Alternative Name: - email:accv@accv.es - Signature Algorithm: sha1WithRSAEncryption - 97:31:02:9f:e7:fd:43:67:48:44:14:e4:29:87:ed:4c:28:66: - d0:8f:35:da:4d:61:b7:4a:97:4d:b5:db:90:e0:05:2e:0e:c6: - 79:d0:f2:97:69:0f:bd:04:47:d9:be:db:b5:29:da:9b:d9:ae: - a9:99:d5:d3:3c:30:93:f5:8d:a1:a8:fc:06:8d:44:f4:ca:16: - 95:7c:33:dc:62:8b:a8:37:f8:27:d8:09:2d:1b:ef:c8:14:27: - 20:a9:64:44:ff:2e:d6:75:aa:6c:4d:60:40:19:49:43:54:63: - da:e2:cc:ba:66:e5:4f:44:7a:5b:d9:6a:81:2b:40:d5:7f:f9: - 01:27:58:2c:c8:ed:48:91:7c:3f:a6:00:cf:c4:29:73:11:36: - de:86:19:3e:9d:ee:19:8a:1b:d5:b0:ed:8e:3d:9c:2a:c0:0d: - d8:3d:66:e3:3c:0d:bd:d5:94:5c:e2:e2:a7:35:1b:04:00:f6: - 3f:5a:8d:ea:43:bd:5f:89:1d:a9:c1:b0:cc:99:e2:4d:00:0a: - da:c9:27:5b:e7:13:90:5c:e4:f5:33:a2:55:6d:dc:e0:09:4d: - 2f:b1:26:5b:27:75:00:09:c4:62:77:29:08:5f:9e:59:ac:b6: - 7e:ad:9f:54:30:22:03:c1:1e:71:64:fe:f9:38:0a:96:18:dd: - 02:14:ac:23:cb:06:1c:1e:a4:7d:8d:0d:de:27:41:e8:ad:da: - 15:b7:b0:23:dd:2b:a8:d3:da:25:87:ed:e8:55:44:4d:88:f4: - 36:7e:84:9a:78:ac:f7:0e:56:49:0e:d6:33:25:d6:84:50:42: - 6c:20:12:1d:2a:d5:be:bc:f2:70:81:a4:70:60:be:05:b5:9b: - 9e:04:44:be:61:23:ac:e9:a5:24:8c:11:80:94:5a:a2:a2:b9: - 49:d2:c1:dc:d1:a7:ed:31:11:2c:9e:19:a6:ee:e1:55:e1:c0: - ea:cf:0d:84:e4:17:b7:a2:7c:a5:de:55:25:06:ee:cc:c0:87: - 5c:40:da:cc:95:3f:55:e0:35:c7:b8:84:be:b4:5d:cd:7a:83: - 01:72:ee:87:e6:5f:1d:ae:b5:85:c6:26:df:e6:c1:9a:e9:1e: - 02:47:9f:2a:a8:6d:a9:5b:cf:ec:45:77:7f:98:27:9a:32:5d: - 2a:e3:84:ee:c5:98:66:2f:96:20:1d:dd:d8:c3:27:d7:b0:f9: - fe:d9:7d:cd:d0:9f:8f:0b:14:58:51:9f:2f:8b:c3:38:2d:de: - e8:8f:d6:8d:87:a4:f5:56:43:16:99:2c:f4:a4:56:b4:34:b8: - 61:37:c9:c2:58:80:1b:a0:97:a1:fc:59:8d:e9:11:f6:d1:0f: - 4b:55:34:46:2a:8b:86:3b ------BEGIN CERTIFICATE----- -MIIH0zCCBbugAwIBAgIIXsO3pkN/pOAwDQYJKoZIhvcNAQEFBQAwQjESMBAGA1UE -AwwJQUNDVlJBSVoxMRAwDgYDVQQLDAdQS0lBQ0NWMQ0wCwYDVQQKDARBQ0NWMQsw -CQYDVQQGEwJFUzAeFw0xMTA1MDUwOTM3MzdaFw0zMDEyMzEwOTM3MzdaMEIxEjAQ -BgNVBAMMCUFDQ1ZSQUlaMTEQMA4GA1UECwwHUEtJQUNDVjENMAsGA1UECgwEQUND -VjELMAkGA1UEBhMCRVMwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQCb -qau/YUqXry+XZpp0X9DZlv3P4uRm7x8fRzPCRKPfmt4ftVTdFXxpNRFvu8gMjmoY -HtiP2Ra8EEg2XPBjs5BaXCQ316PWywlxufEBcoSwfdtNgM3802/J+Nq2DoLSRYWo -G2ioPej0RGy9ocLLA76MPhMAhN9KSMDjIgro6TenGEyxCQ0jVn8ETdkXhBilyNpA -lHPrzg5XPAOBOp0KoVdDaaxXbXmQeOW1tDvYvEyNKKGno6e6Ak4l0Squ7a4DIrhr -IA8wKFSVf+DuzgpmndFALW4ir50awQUZ0m/A8p/4e7MCQvtQqR0tkw8jq8bBD5L/ -0KIV9VMJcRz/RROE5iZe+OCIHAr8Fraocwa48GOEAqDGWuzndN9wrqODJerWx5eH -k6fGioozl2A3ED6XPm4pFdahD9GILBKfb6qkxkLrQaLjlUPTAYVtjrs78yM2x/47 -4KElB0iryYl0/wiPgL/AlmXz7uxLaL2diMMxs0Dx6M/2OLuc5NF/1OVYm3z61PMO -m3WR5LpSLhl+0fXNWhn8ugb2+1KoS5kE3fj5tItQo05iifCHJPqDQsGH+tUtKSpa -cXpkatcnYGMN285J9Y0fkIkyF/hzQ7jSWpOGYdbhdQrqeWZ2iE9x6wQl1gpaepPl -uUsXQA+xtrn13k/c4LOsOxFwYIRKQ26ZIMApcQrAZQIDAQABo4ICyzCCAscwfQYI -KwYBBQUHAQEEcTBvMEwGCCsGAQUFBzAChkBodHRwOi8vd3d3LmFjY3YuZXMvZmls -ZWFkbWluL0FyY2hpdm9zL2NlcnRpZmljYWRvcy9yYWl6YWNjdjEuY3J0MB8GCCsG -AQUFBzABhhNodHRwOi8vb2NzcC5hY2N2LmVzMB0GA1UdDgQWBBTSh7Tj3zcnk1X2 -VuqB5TbMjB4/vTAPBgNVHRMBAf8EBTADAQH/MB8GA1UdIwQYMBaAFNKHtOPfNyeT -VfZW6oHlNsyMHj+9MIIBcwYDVR0gBIIBajCCAWYwggFiBgRVHSAAMIIBWDCCASIG -CCsGAQUFBwICMIIBFB6CARAAQQB1AHQAbwByAGkAZABhAGQAIABkAGUAIABDAGUA -cgB0AGkAZgBpAGMAYQBjAGkA8wBuACAAUgBhAO0AegAgAGQAZQAgAGwAYQAgAEEA -QwBDAFYAIAAoAEEAZwBlAG4AYwBpAGEAIABkAGUAIABUAGUAYwBuAG8AbABvAGcA -7QBhACAAeQAgAEMAZQByAHQAaQBmAGkAYwBhAGMAaQDzAG4AIABFAGwAZQBjAHQA -cgDzAG4AaQBjAGEALAAgAEMASQBGACAAUQA0ADYAMAAxADEANQA2AEUAKQAuACAA -QwBQAFMAIABlAG4AIABoAHQAdABwADoALwAvAHcAdwB3AC4AYQBjAGMAdgAuAGUA -czAwBggrBgEFBQcCARYkaHR0cDovL3d3dy5hY2N2LmVzL2xlZ2lzbGFjaW9uX2Mu -aHRtMFUGA1UdHwROMEwwSqBIoEaGRGh0dHA6Ly93d3cuYWNjdi5lcy9maWxlYWRt -aW4vQXJjaGl2b3MvY2VydGlmaWNhZG9zL3JhaXphY2N2MV9kZXIuY3JsMA4GA1Ud -DwEB/wQEAwIBBjAXBgNVHREEEDAOgQxhY2N2QGFjY3YuZXMwDQYJKoZIhvcNAQEF -BQADggIBAJcxAp/n/UNnSEQU5CmH7UwoZtCPNdpNYbdKl02125DgBS4OxnnQ8pdp -D70ER9m+27Up2pvZrqmZ1dM8MJP1jaGo/AaNRPTKFpV8M9xii6g3+CfYCS0b78gU -JyCpZET/LtZ1qmxNYEAZSUNUY9rizLpm5U9EelvZaoErQNV/+QEnWCzI7UiRfD+m -AM/EKXMRNt6GGT6d7hmKG9Ww7Y49nCrADdg9ZuM8Db3VlFzi4qc1GwQA9j9ajepD -vV+JHanBsMyZ4k0ACtrJJ1vnE5Bc5PUzolVt3OAJTS+xJlsndQAJxGJ3KQhfnlms -tn6tn1QwIgPBHnFk/vk4CpYY3QIUrCPLBhwepH2NDd4nQeit2hW3sCPdK6jT2iWH -7ehVRE2I9DZ+hJp4rPcOVkkO1jMl1oRQQmwgEh0q1b688nCBpHBgvgW1m54ERL5h -I6zppSSMEYCUWqKiuUnSwdzRp+0xESyeGabu4VXhwOrPDYTkF7eifKXeVSUG7szA -h1xA2syVP1XgNce4hL60Xc16gwFy7ofmXx2utYXGJt/mwZrpHgJHnyqobalbz+xF -d3+YJ5oyXSrjhO7FmGYvliAd3djDJ9ew+f7Zfc3Qn48LFFhRny+Lwzgt3uiP1o2H -pPVWQxaZLPSkVrQ0uGE3ycJYgBugl6H8WY3pEfbRD0tVNEYqi4Y7 ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: - 61:8d:c7:86:3b:01:82:05 - Signature Algorithm: sha1WithRSAEncryption - Issuer: CN=ACEDICOM Root, OU=PKI, O=EDICOM, C=ES - Validity - Not Before: Apr 18 16:24:22 2008 GMT - Not After : Apr 13 16:24:22 2028 GMT - Subject: CN=ACEDICOM Root, OU=PKI, O=EDICOM, C=ES - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (4096 bit) - Modulus: - 00:ff:92:95:e1:68:06:76:b4:2c:c8:58:48:ca:fd: - 80:54:29:55:63:24:ff:90:65:9b:10:75:7b:c3:6a: - db:62:02:01:f2:18:86:b5:7c:5a:38:b1:e4:58:b9: - fb:d3:d8:2d:9f:bd:32:37:bf:2c:15:6d:be:b5:f4: - 21:d2:13:91:d9:07:ad:01:05:d6:f3:bd:77:ce:5f: - 42:81:0a:f9:6a:e3:83:00:a8:2b:2e:55:13:63:81: - ca:47:1c:7b:5c:16:57:7a:1b:83:60:04:3a:3e:65: - c3:cd:01:de:de:a4:d6:0c:ba:8e:de:d9:04:ee:17: - 56:22:9b:8f:63:fd:4d:16:0b:b7:7b:77:8c:f9:25: - b5:d1:6d:99:12:2e:4f:1a:b8:e6:ea:04:92:ae:3d: - 11:b9:51:42:3d:87:b0:31:85:af:79:5a:9c:fe:e7: - 4e:5e:92:4f:43:fc:ab:3a:ad:a5:12:26:66:b9:e2: - 0c:d7:98:ce:d4:58:a5:95:40:0a:b7:44:9d:13:74: - 2b:c2:a5:eb:22:15:98:10:d8:8b:c5:04:9f:1d:8f: - 60:e5:06:1b:9b:cf:b9:79:a0:3d:a2:23:3f:42:3f: - 6b:fa:1c:03:7b:30:8d:ce:6c:c0:bf:e6:1b:5f:bf: - 67:b8:84:19:d5:15:ef:7b:cb:90:36:31:62:c9:bc: - 02:ab:46:5f:9b:fe:1a:68:94:34:3d:90:8e:ad:f6: - e4:1d:09:7f:4a:88:38:3f:be:67:fd:34:96:f5:1d: - bc:30:74:cb:38:ee:d5:6c:ab:d4:fc:f4:00:b7:00: - 5b:85:32:16:76:33:e9:d8:a3:99:9d:05:00:aa:16: - e6:f3:81:7d:6f:7d:aa:86:6d:ad:15:74:d3:c4:a2: - 71:aa:f4:14:7d:e7:32:b8:1f:bc:d5:f1:4e:bd:6f: - 17:02:39:d7:0e:95:42:3a:c7:00:3e:e9:26:63:11: - ea:0b:d1:4a:ff:18:9d:b2:d7:7b:2f:3a:d9:96:fb: - e8:1e:92:ae:13:55:c8:d9:27:f6:dc:48:1b:b0:24: - c1:85:e3:77:9d:9a:a4:f3:0c:11:1d:0d:c8:b4:14: - ee:b5:82:57:09:bf:20:58:7f:2f:22:23:d8:70:cb: - 79:6c:c9:4b:f2:a9:2a:c8:fc:87:2b:d7:1a:50:f8: - 27:e8:2f:43:e3:3a:bd:d8:57:71:fd:ce:a6:52:5b: - f9:dd:4d:ed:e5:f6:6f:89:ed:bb:93:9c:76:21:75: - f0:92:4c:29:f7:2f:9c:01:2e:fe:50:46:9e:64:0c: - 14:b3:07:5b:c5:c2:73:6c:f1:07:5c:45:24:14:35: - ae:83:f1:6a:4d:89:7a:fa:b3:d8:2d:66:f0:36:87: - f5:2b:53 - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Basic Constraints: critical - CA:TRUE - X509v3 Authority Key Identifier: - keyid:A6:B3:E1:2B:2B:49:B6:D7:73:A1:AA:94:F5:01:E7:73:65:4C:AC:50 - - X509v3 Key Usage: critical - Digital Signature, Certificate Sign, CRL Sign - X509v3 Subject Key Identifier: - A6:B3:E1:2B:2B:49:B6:D7:73:A1:AA:94:F5:01:E7:73:65:4C:AC:50 - X509v3 Certificate Policies: - Policy: X509v3 Any Policy - CPS: http://acedicom.edicomgroup.com/doc - - Signature Algorithm: sha1WithRSAEncryption - ce:2c:0b:52:51:62:26:7d:0c:27:83:8f:c5:f6:da:a0:68:7b: - 4f:92:5e:ea:a4:73:32:11:53:44:b2:44:cb:9d:ec:0f:79:42: - b3:10:a6:c7:0d:9d:cb:b6:fa:3f:3a:7c:ea:bf:88:53:1b:3c: - f7:82:fa:05:35:33:e1:35:a8:57:c0:e7:fd:8d:4f:3f:93:32: - 4f:78:66:03:77:07:58:e9:95:c8:7e:3e:d0:79:00:8c:f2:1b: - 51:33:9b:bc:94:e9:3a:7b:6e:52:2d:32:9e:23:a4:45:fb:b6: - 2e:13:b0:8b:18:b1:dd:ce:d5:1d:a7:42:7f:55:be:fb:5b:bb: - 47:d4:fc:24:cd:04:ae:96:05:15:d6:ac:ce:30:f3:ca:0b:c5: - ba:e2:22:e0:a6:ad:22:e4:02:ee:74:11:7f:4c:ff:78:1d:35: - da:e6:02:34:eb:18:12:61:77:06:09:16:63:ea:18:ad:a2:87: - 1f:f2:c7:80:09:09:75:4e:10:a8:8f:3d:86:b8:75:11:c0:24: - 62:8a:96:7b:4a:45:e9:ec:59:c5:be:6b:83:e6:e1:e8:ac:b5: - 30:1e:fe:05:07:80:f9:e1:23:0d:50:8f:05:98:ff:2c:5f:e8: - 3b:b6:ad:cf:81:b5:21:87:ca:08:2a:23:27:30:20:2b:cf:ed: - 94:5b:ac:b2:7a:d2:c7:28:a1:8a:0b:9b:4d:4a:2c:6d:85:3f: - 09:72:3c:67:e2:d9:dc:07:ba:eb:65:7b:5a:01:63:d6:90:5b: - 4f:17:66:3d:7f:0b:19:a3:93:63:10:52:2a:9f:14:16:58:e2: - dc:a5:f4:a1:16:8b:0e:91:8b:81:ca:9b:59:fa:d8:6b:91:07: - 65:55:5f:52:1f:af:3a:fb:90:dd:69:a5:5b:9c:6d:0e:2c:b6: - fa:ce:ac:a5:7c:32:4a:67:40:dc:30:34:23:dd:d7:04:23:66: - f0:fc:55:80:a7:fb:66:19:82:35:67:62:70:39:5e:6f:c7:ea: - 90:40:44:08:1e:b8:b2:d6:db:ee:59:a7:0d:18:79:34:bc:54: - 18:5e:53:ca:34:51:ed:45:0a:e6:8e:c7:82:36:3e:a7:38:63: - a9:30:2c:17:10:60:92:9f:55:87:12:59:10:c2:0f:67:69:11: - cc:4e:1e:7e:4a:9a:ad:af:40:a8:75:ac:56:90:74:b8:a0:9c: - a5:79:6f:dc:e9:1a:c8:69:05:e9:ba:fa:03:b3:7c:e4:e0:4e: - c2:ce:9d:e8:b6:46:0d:6e:7e:57:3a:67:94:c2:cb:1f:9c:77: - 4a:67:4e:69:86:43:93:38:fb:b6:db:4f:83:91:d4:60:7e:4b: - 3e:2b:38:07:55:98:5e:a4 ------BEGIN CERTIFICATE----- -MIIFtTCCA52gAwIBAgIIYY3HhjsBggUwDQYJKoZIhvcNAQEFBQAwRDEWMBQGA1UE -AwwNQUNFRElDT00gUm9vdDEMMAoGA1UECwwDUEtJMQ8wDQYDVQQKDAZFRElDT00x -CzAJBgNVBAYTAkVTMB4XDTA4MDQxODE2MjQyMloXDTI4MDQxMzE2MjQyMlowRDEW -MBQGA1UEAwwNQUNFRElDT00gUm9vdDEMMAoGA1UECwwDUEtJMQ8wDQYDVQQKDAZF -RElDT00xCzAJBgNVBAYTAkVTMIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKC -AgEA/5KV4WgGdrQsyFhIyv2AVClVYyT/kGWbEHV7w2rbYgIB8hiGtXxaOLHkWLn7 -09gtn70yN78sFW2+tfQh0hOR2QetAQXW8713zl9CgQr5auODAKgrLlUTY4HKRxx7 -XBZXehuDYAQ6PmXDzQHe3qTWDLqO3tkE7hdWIpuPY/1NFgu3e3eM+SW10W2ZEi5P -Grjm6gSSrj0RuVFCPYewMYWveVqc/udOXpJPQ/yrOq2lEiZmueIM15jO1FillUAK -t0SdE3QrwqXrIhWYENiLxQSfHY9g5QYbm8+5eaA9oiM/Qj9r+hwDezCNzmzAv+Yb -X79nuIQZ1RXve8uQNjFiybwCq0Zfm/4aaJQ0PZCOrfbkHQl/Sog4P75n/TSW9R28 -MHTLOO7VbKvU/PQAtwBbhTIWdjPp2KOZnQUAqhbm84F9b32qhm2tFXTTxKJxqvQU -fecyuB+81fFOvW8XAjnXDpVCOscAPukmYxHqC9FK/xidstd7LzrZlvvoHpKuE1XI -2Sf23EgbsCTBheN3nZqk8wwRHQ3ItBTutYJXCb8gWH8vIiPYcMt5bMlL8qkqyPyH -K9caUPgn6C9D4zq92Fdx/c6mUlv53U3t5fZvie27k5x2IXXwkkwp9y+cAS7+UEae -ZAwUswdbxcJzbPEHXEUkFDWug/FqTYl6+rPYLWbwNof1K1MCAwEAAaOBqjCBpzAP -BgNVHRMBAf8EBTADAQH/MB8GA1UdIwQYMBaAFKaz4SsrSbbXc6GqlPUB53NlTKxQ -MA4GA1UdDwEB/wQEAwIBhjAdBgNVHQ4EFgQUprPhKytJttdzoaqU9QHnc2VMrFAw -RAYDVR0gBD0wOzA5BgRVHSAAMDEwLwYIKwYBBQUHAgEWI2h0dHA6Ly9hY2VkaWNv -bS5lZGljb21ncm91cC5jb20vZG9jMA0GCSqGSIb3DQEBBQUAA4ICAQDOLAtSUWIm -fQwng4/F9tqgaHtPkl7qpHMyEVNEskTLnewPeUKzEKbHDZ3Ltvo/Onzqv4hTGzz3 -gvoFNTPhNahXwOf9jU8/kzJPeGYDdwdY6ZXIfj7QeQCM8htRM5u8lOk6e25SLTKe -I6RF+7YuE7CLGLHdztUdp0J/Vb77W7tH1PwkzQSulgUV1qzOMPPKC8W64iLgpq0i -5ALudBF/TP94HTXa5gI06xgSYXcGCRZj6hitoocf8seACQl1ThCojz2GuHURwCRi -ipZ7SkXp7FnFvmuD5uHorLUwHv4FB4D54SMNUI8FmP8sX+g7tq3PgbUhh8oIKiMn -MCArz+2UW6yyetLHKKGKC5tNSixthT8Jcjxn4tncB7rrZXtaAWPWkFtPF2Y9fwsZ -o5NjEFIqnxQWWOLcpfShFosOkYuByptZ+thrkQdlVV9SH686+5DdaaVbnG0OLLb6 -zqylfDJKZ0DcMDQj3dcEI2bw/FWAp/tmGYI1Z2JwOV5vx+qQQEQIHriy1tvuWacN -GHk0vFQYXlPKNFHtRQrmjseCNj6nOGOpMCwXEGCSn1WHElkQwg9naRHMTh5+Spqt -r0CodaxWkHS4oJyleW/c6RrIaQXpuvoDs3zk4E7Czp3otkYNbn5XOmeUwssfnHdK -Z05phkOTOPu220+DkdRgfks+KzgHVZhepA== ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: - 5d:93:8d:30:67:36:c8:06:1d:1a:c7:54:84:69:07 - Signature Algorithm: sha256WithRSAEncryption - Issuer: C=ES, O=FNMT-RCM, OU=AC RAIZ FNMT-RCM - Validity - Not Before: Oct 29 15:59:56 2008 GMT - Not After : Jan 1 00:00:00 2030 GMT - Subject: C=ES, O=FNMT-RCM, OU=AC RAIZ FNMT-RCM - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (4096 bit) - Modulus: - 00:ba:71:80:7a:4c:86:6e:7f:c8:13:6d:c0:c6:7d: - 1c:00:97:8f:2c:0c:23:bb:10:9a:40:a9:1a:b7:87: - 88:f8:9b:56:6a:fb:e6:7b:8e:8b:92:8e:a7:25:5d: - 59:11:db:36:2e:b7:51:17:1f:a9:08:1f:04:17:24: - 58:aa:37:4a:18:df:e5:39:d4:57:fd:d7:c1:2c:91: - 01:91:e2:22:d4:03:c0:58:fc:77:47:ec:8f:3e:74: - 43:ba:ac:34:8d:4d:38:76:67:8e:b0:c8:6f:30:33: - 58:71:5c:b4:f5:6b:6e:d4:01:50:b8:13:7e:6c:4a: - a3:49:d1:20:19:ee:bc:c0:29:18:65:a7:de:fe:ef: - dd:0a:90:21:e7:1a:67:92:42:10:98:5f:4f:30:bc: - 3e:1c:45:b4:10:d7:68:40:14:c0:40:fa:e7:77:17: - 7a:e6:0b:8f:65:5b:3c:d9:9a:52:db:b5:bd:9e:46: - cf:3d:eb:91:05:02:c0:96:b2:76:4c:4d:10:96:3b: - 92:fa:9c:7f:0f:99:df:be:23:35:45:1e:02:5c:fe: - b5:a8:9b:99:25:da:5e:f3:22:c3:39:f5:e4:2a:2e: - d3:c6:1f:c4:6c:aa:c5:1c:6a:01:05:4a:2f:d2:c5: - c1:a8:34:26:5d:66:a5:d2:02:21:f9:18:b7:06:f5: - 4e:99:6f:a8:ab:4c:51:e8:cf:50:18:c5:77:c8:39: - 09:2c:49:92:32:99:a8:bb:17:17:79:b0:5a:c5:e6: - a3:c4:59:65:47:35:83:5e:a9:e8:35:0b:99:bb:e4: - cd:20:c6:9b:4a:06:39:b5:68:fc:22:ba:ee:55:8c: - 2b:4e:ea:f3:b1:e3:fc:b6:99:9a:d5:42:fa:71:4d: - 08:cf:87:1e:6a:71:7d:f9:d3:b4:e9:a5:71:81:7b: - c2:4e:47:96:a5:f6:76:85:a3:28:8f:e9:80:6e:81: - 53:a5:6d:5f:b8:48:f9:c2:f9:36:a6:2e:49:ff:b8: - 96:c2:8c:07:b3:9b:88:58:fc:eb:1b:1c:de:2d:70: - e2:97:92:30:a1:89:e3:bc:55:a8:27:d6:4b:ed:90: - ad:8b:fa:63:25:59:2d:a8:35:dd:ca:97:33:bc:e5: - cd:c7:9d:d1:ec:ef:5e:0e:4a:90:06:26:63:ad:b9: - d9:35:2d:07:ba:76:65:2c:ac:57:8f:7d:f4:07:94: - d7:81:02:96:5d:a3:07:49:d5:7a:d0:57:f9:1b:e7: - 53:46:75:aa:b0:79:42:cb:68:71:08:e9:60:bd:39: - 69:ce:f4:af:c3:56:40:c7:ad:52:a2:09:e4:6f:86: - 47:8a:1f:eb:28:27:5d:83:20:af:04:c9:6c:56:9a: - 8b:46:f5 - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Basic Constraints: critical - CA:TRUE - X509v3 Key Usage: critical - Certificate Sign, CRL Sign - X509v3 Subject Key Identifier: - F7:7D:C5:FD:C4:E8:9A:1B:77:64:A7:F5:1D:A0:CC:BF:87:60:9A:6D - X509v3 Certificate Policies: - Policy: X509v3 Any Policy - CPS: http://www.cert.fnmt.es/dpcs/ - - Signature Algorithm: sha256WithRSAEncryption - 07:90:4a:df:f3:23:4e:f0:c3:9c:51:65:9b:9c:22:a2:8a:0c: - 85:f3:73:29:6b:4d:fe:01:e2:a9:0c:63:01:bf:04:67:a5:9d: - 98:5f:fd:01:13:fa:ec:9a:62:e9:86:fe:b6:62:d2:6e:4c:94: - fb:c0:75:45:7c:65:0c:f8:b2:37:cf:ac:0f:cf:8d:6f:f9:19: - f7:8f:ec:1e:f2:70:9e:f0:ca:b8:ef:b7:ff:76:37:76:5b:f6: - 6e:88:f3:af:62:32:22:93:0d:3a:6a:8e:14:66:0c:2d:53:74: - 57:65:1e:d5:b2:dd:23:81:3b:a5:66:23:27:67:09:8f:e1:77: - aa:43:cd:65:51:08:ed:51:58:fe:e6:39:f9:cb:47:84:a4:15: - f1:76:bb:a4:ee:a4:3b:c4:5f:ef:b2:33:96:11:18:b7:c9:65: - be:18:e1:a3:a4:dc:fa:18:f9:d3:bc:13:9b:39:7a:34:ba:d3: - 41:fb:fa:32:8a:2a:b7:2b:86:0b:69:83:38:be:cd:8a:2e:0b: - 70:ad:8d:26:92:ee:1e:f5:01:2b:0a:d9:d6:97:9b:6e:e0:a8: - 19:1c:3a:21:8b:0c:1e:40:ad:03:e7:dd:66:7e:f5:b9:20:0d: - 03:e8:96:f9:82:45:d4:39:e0:a0:00:5d:d7:98:e6:7d:9e:67: - 73:c3:9a:2a:f7:ab:8b:a1:3a:14:ef:34:bc:52:0e:89:98:9a: - 04:40:84:1d:7e:45:69:93:57:ce:eb:ce:f8:50:7c:4f:1c:6e: - 04:43:9b:f9:d6:3b:23:18:e9:ea:8e:d1:4d:46:8d:f1:3b:e4: - 6a:ca:ba:fb:23:b7:9b:fa:99:01:29:5a:58:5a:2d:e3:f9:d4: - 6d:0e:26:ad:c1:6e:34:bc:32:f8:0c:05:fa:65:a3:db:3b:37: - 83:22:e9:d6:dc:72:33:fd:5d:f2:20:bd:76:3c:23:da:28:f7: - f9:1b:eb:59:64:d5:dc:5f:72:7e:20:fc:cd:89:b5:90:67:4d: - 62:7a:3f:4e:ad:1d:c3:39:fe:7a:f4:28:16:df:41:f6:48:80: - 05:d7:0f:51:79:ac:10:ab:d4:ec:03:66:e6:6a:b0:ba:31:92: - 42:40:6a:be:3a:d3:72:e1:6a:37:55:bc:ac:1d:95:b7:69:61: - f2:43:91:74:e6:a0:d3:0a:24:46:a1:08:af:d6:da:45:19:96: - d4:53:1d:5b:84:79:f0:c0:f7:47:ef:8b:8f:c5:06:ae:9d:4c: - 62:9d:ff:46:04:f8:d3:c9:b6:10:25:40:75:fe:16:aa:c9:4a: - 60:86:2f:ba:ef:30:77:e4:54:e2:b8:84:99:58:80:aa:13:8b: - 51:3a:4f:48:f6:8b:b6:b3 ------BEGIN CERTIFICATE----- -MIIFgzCCA2ugAwIBAgIPXZONMGc2yAYdGsdUhGkHMA0GCSqGSIb3DQEBCwUAMDsx -CzAJBgNVBAYTAkVTMREwDwYDVQQKDAhGTk1ULVJDTTEZMBcGA1UECwwQQUMgUkFJ -WiBGTk1ULVJDTTAeFw0wODEwMjkxNTU5NTZaFw0zMDAxMDEwMDAwMDBaMDsxCzAJ -BgNVBAYTAkVTMREwDwYDVQQKDAhGTk1ULVJDTTEZMBcGA1UECwwQQUMgUkFJWiBG -Tk1ULVJDTTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBALpxgHpMhm5/ -yBNtwMZ9HACXjywMI7sQmkCpGreHiPibVmr75nuOi5KOpyVdWRHbNi63URcfqQgf -BBckWKo3Shjf5TnUV/3XwSyRAZHiItQDwFj8d0fsjz50Q7qsNI1NOHZnjrDIbzAz -WHFctPVrbtQBULgTfmxKo0nRIBnuvMApGGWn3v7v3QqQIecaZ5JCEJhfTzC8PhxF -tBDXaEAUwED653cXeuYLj2VbPNmaUtu1vZ5Gzz3rkQUCwJaydkxNEJY7kvqcfw+Z -374jNUUeAlz+taibmSXaXvMiwzn15Cou08YfxGyqxRxqAQVKL9LFwag0Jl1mpdIC -IfkYtwb1TplvqKtMUejPUBjFd8g5CSxJkjKZqLsXF3mwWsXmo8RZZUc1g16p6DUL -mbvkzSDGm0oGObVo/CK67lWMK07q87Hj/LaZmtVC+nFNCM+HHmpxffnTtOmlcYF7 -wk5HlqX2doWjKI/pgG6BU6VtX7hI+cL5NqYuSf+4lsKMB7ObiFj86xsc3i1w4peS -MKGJ47xVqCfWS+2QrYv6YyVZLag13cqXM7zlzced0ezvXg5KkAYmY6252TUtB7p2 -ZSysV4999AeU14ECll2jB0nVetBX+RvnU0Z1qrB5QstocQjpYL05ac70r8NWQMet -UqIJ5G+GR4of6ygnXYMgrwTJbFaai0b1AgMBAAGjgYMwgYAwDwYDVR0TAQH/BAUw -AwEB/zAOBgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYEFPd9xf3E6Jobd2Sn9R2gzL+H -YJptMD4GA1UdIAQ3MDUwMwYEVR0gADArMCkGCCsGAQUFBwIBFh1odHRwOi8vd3d3 -LmNlcnQuZm5tdC5lcy9kcGNzLzANBgkqhkiG9w0BAQsFAAOCAgEAB5BK3/MjTvDD -nFFlm5wioooMhfNzKWtN/gHiqQxjAb8EZ6WdmF/9ARP67Jpi6Yb+tmLSbkyU+8B1 -RXxlDPiyN8+sD8+Nb/kZ94/sHvJwnvDKuO+3/3Y3dlv2bojzr2IyIpMNOmqOFGYM -LVN0V2Ue1bLdI4E7pWYjJ2cJj+F3qkPNZVEI7VFY/uY5+ctHhKQV8Xa7pO6kO8Rf -77IzlhEYt8llvhjho6Tc+hj507wTmzl6NLrTQfv6MooqtyuGC2mDOL7Nii4LcK2N -JpLuHvUBKwrZ1pebbuCoGRw6IYsMHkCtA+fdZn71uSANA+iW+YJF1DngoABd15jm -fZ5nc8OaKveri6E6FO80vFIOiZiaBECEHX5FaZNXzuvO+FB8TxxuBEOb+dY7Ixjp -6o7RTUaN8Tvkasq6+yO3m/qZASlaWFot4/nUbQ4mrcFuNLwy+AwF+mWj2zs3gyLp -1txyM/1d8iC9djwj2ij3+RvrWWTV3F9yfiD8zYm1kGdNYno/Tq0dwzn+evQoFt9B -9kiABdcPUXmsEKvU7ANm5mqwujGSQkBqvjrTcuFqN1W8rB2Vt2lh8kORdOag0wok -RqEIr9baRRmW1FMdW4R58MD3R++Lj8UGrp1MYp3/RgT408m2ECVAdf4WqslKYIYv -uu8wd+RU4riEmViAqhOLUTpPSPaLtrM= ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: - 57:0a:11:97:42:c4:e3:cc - Signature Algorithm: sha256WithRSAEncryption - Issuer: C=IT, L=Milan, O=Actalis S.p.A./03358520967, CN=Actalis Authentication Root CA - Validity - Not Before: Sep 22 11:22:02 2011 GMT - Not After : Sep 22 11:22:02 2030 GMT - Subject: C=IT, L=Milan, O=Actalis S.p.A./03358520967, CN=Actalis Authentication Root CA - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (4096 bit) - Modulus: - 00:a7:c6:c4:a5:29:a4:2c:ef:e5:18:c5:b0:50:a3: - 6f:51:3b:9f:0a:5a:c9:c2:48:38:0a:c2:1c:a0:18: - 7f:91:b5:87:b9:40:3f:dd:1d:68:1f:08:83:d5:2d: - 1e:88:a0:f8:8f:56:8f:6d:99:02:92:90:16:d5:5f: - 08:6c:89:d7:e1:ac:bc:20:c2:b1:e0:83:51:8a:69: - 4d:00:96:5a:6f:2f:c0:44:7e:a3:0e:e4:91:cd:58: - ee:dc:fb:c7:1e:45:47:dd:27:b9:08:01:9f:a6:21: - 1d:f5:41:2d:2f:4c:fd:28:ad:e0:8a:ad:22:b4:56: - 65:8e:86:54:8f:93:43:29:de:39:46:78:a3:30:23: - ba:cd:f0:7d:13:57:c0:5d:d2:83:6b:48:4c:c4:ab: - 9f:80:5a:5b:3a:bd:c9:a7:22:3f:80:27:33:5b:0e: - b7:8a:0c:5d:07:37:08:cb:6c:d2:7a:47:22:44:35: - c5:cc:cc:2e:8e:dd:2a:ed:b7:7d:66:0d:5f:61:51: - 22:55:1b:e3:46:e3:e3:3d:d0:35:62:9a:db:af:14: - c8:5b:a1:cc:89:1b:e1:30:26:fc:a0:9b:1f:81:a7: - 47:1f:04:eb:a3:39:92:06:9f:99:d3:bf:d3:ea:4f: - 50:9c:19:fe:96:87:1e:3c:65:f6:a3:18:24:83:86: - 10:e7:54:3e:a8:3a:76:24:4f:81:21:c5:e3:0f:02: - f8:93:94:47:20:bb:fe:d4:0e:d3:68:b9:dd:c4:7a: - 84:82:e3:53:54:79:dd:db:9c:d2:f2:07:9b:2e:b6: - bc:3e:ed:85:6d:ef:25:11:f2:97:1a:42:61:f7:4a: - 97:e8:8b:b1:10:07:fa:65:81:b2:a2:39:cf:f7:3c: - ff:18:fb:c6:f1:5a:8b:59:e2:02:ac:7b:92:d0:4e: - 14:4f:59:45:f6:0c:5e:28:5f:b0:e8:3f:45:cf:cf: - af:9b:6f:fb:84:d3:77:5a:95:6f:ac:94:84:9e:ee: - bc:c0:4a:8f:4a:93:f8:44:21:e2:31:45:61:50:4e: - 10:d8:e3:35:7c:4c:19:b4:de:05:bf:a3:06:9f:c8: - b5:cd:e4:1f:d7:17:06:0d:7a:95:74:55:0d:68:1a: - fc:10:1b:62:64:9d:6d:e0:95:a0:c3:94:07:57:0d: - 14:e6:bd:05:fb:b8:9f:e6:df:8b:e2:c6:e7:7e:96: - f6:53:c5:80:34:50:28:58:f0:12:50:71:17:30:ba: - e6:78:63:bc:f4:b2:ad:9b:2b:b2:fe:e1:39:8c:5e: - ba:0b:20:94:de:7b:83:b8:ff:e3:56:8d:b7:11:e9: - 3b:8c:f2:b1:c1:5d:9d:a4:0b:4c:2b:d9:b2:18:f5: - b5:9f:4b - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Subject Key Identifier: - 52:D8:88:3A:C8:9F:78:66:ED:89:F3:7B:38:70:94:C9:02:02:36:D0 - X509v3 Basic Constraints: critical - CA:TRUE - X509v3 Authority Key Identifier: - keyid:52:D8:88:3A:C8:9F:78:66:ED:89:F3:7B:38:70:94:C9:02:02:36:D0 - - X509v3 Key Usage: critical - Certificate Sign, CRL Sign - Signature Algorithm: sha256WithRSAEncryption - 0b:7b:72:87:c0:60:a6:49:4c:88:58:e6:1d:88:f7:14:64:48: - a6:d8:58:0a:0e:4f:13:35:df:35:1d:d4:ed:06:31:c8:81:3e: - 6a:d5:dd:3b:1a:32:ee:90:3d:11:d2:2e:f4:8e:c3:63:2e:23: - 66:b0:67:be:6f:b6:c0:13:39:60:aa:a2:34:25:93:75:52:de: - a7:9d:ad:0e:87:89:52:71:6a:16:3c:19:1d:83:f8:9a:29:65: - be:f4:3f:9a:d9:f0:f3:5a:87:21:71:80:4d:cb:e0:38:9b:3f: - bb:fa:e0:30:4d:cf:86:d3:65:10:19:18:d1:97:02:b1:2b:72: - 42:68:ac:a0:bd:4e:5a:da:18:bf:6b:98:81:d0:fd:9a:be:5e: - 15:48:cd:11:15:b9:c0:29:5c:b4:e8:88:f7:3e:36:ae:b7:62: - fd:1e:62:de:70:78:10:1c:48:5b:da:bc:a4:38:ba:67:ed:55: - 3e:5e:57:df:d4:03:40:4c:81:a4:d2:4f:63:a7:09:42:09:14: - fc:00:a9:c2:80:73:4f:2e:c0:40:d9:11:7b:48:ea:7a:02:c0: - d3:eb:28:01:26:58:74:c1:c0:73:22:6d:93:95:fd:39:7d:bb: - 2a:e3:f6:82:e3:2c:97:5f:4e:1f:91:94:fa:fe:2c:a3:d8:76: - 1a:b8:4d:b2:38:4f:9b:fa:1d:48:60:79:26:e2:f3:fd:a9:d0: - 9a:e8:70:8f:49:7a:d6:e5:bd:0a:0e:db:2d:f3:8d:bf:eb:e3: - a4:7d:cb:c7:95:71:e8:da:a3:7c:c5:c2:f8:74:92:04:1b:86: - ac:a4:22:53:40:b6:ac:fe:4c:76:cf:fb:94:32:c0:35:9f:76: - 3f:6e:e5:90:6e:a0:a6:26:a2:b8:2c:be:d1:2b:85:fd:a7:68: - c8:ba:01:2b:b1:6c:74:1d:b8:73:95:e7:ee:b7:c7:25:f0:00: - 4c:00:b2:7e:b6:0b:8b:1c:f3:c0:50:9e:25:b9:e0:08:de:36: - 66:ff:37:a5:d1:bb:54:64:2c:c9:27:b5:4b:92:7e:65:ff:d3: - 2d:e1:b9:4e:bc:7f:a4:41:21:90:41:77:a6:39:1f:ea:9e:e3: - 9f:d0:66:6f:05:ec:aa:76:7e:bf:6b:16:a0:eb:b5:c7:fc:92: - 54:2f:2b:11:27:25:37:78:4c:51:6a:b0:f3:cc:58:5d:14:f1: - 6a:48:15:ff:c2:07:b6:b1:8d:0f:8e:5c:50:46:b3:3d:bf:01: - 98:4f:b2:59:54:47:3e:34:7b:78:6d:56:93:2e:73:ea:66:28: - 78:cd:1d:14:bf:a0:8f:2f:2e:b8:2e:8e:f2:14:8a:cc:e9:b5: - 7c:fb:6c:9d:0c:a5:e1:96 ------BEGIN CERTIFICATE----- -MIIFuzCCA6OgAwIBAgIIVwoRl0LE48wwDQYJKoZIhvcNAQELBQAwazELMAkGA1UE -BhMCSVQxDjAMBgNVBAcMBU1pbGFuMSMwIQYDVQQKDBpBY3RhbGlzIFMucC5BLi8w -MzM1ODUyMDk2NzEnMCUGA1UEAwweQWN0YWxpcyBBdXRoZW50aWNhdGlvbiBSb290 -IENBMB4XDTExMDkyMjExMjIwMloXDTMwMDkyMjExMjIwMlowazELMAkGA1UEBhMC -SVQxDjAMBgNVBAcMBU1pbGFuMSMwIQYDVQQKDBpBY3RhbGlzIFMucC5BLi8wMzM1 -ODUyMDk2NzEnMCUGA1UEAwweQWN0YWxpcyBBdXRoZW50aWNhdGlvbiBSb290IENB -MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAp8bEpSmkLO/lGMWwUKNv -UTufClrJwkg4CsIcoBh/kbWHuUA/3R1oHwiD1S0eiKD4j1aPbZkCkpAW1V8IbInX -4ay8IMKx4INRimlNAJZaby/ARH6jDuSRzVju3PvHHkVH3Se5CAGfpiEd9UEtL0z9 -KK3giq0itFZljoZUj5NDKd45RnijMCO6zfB9E1fAXdKDa0hMxKufgFpbOr3JpyI/ -gCczWw63igxdBzcIy2zSekciRDXFzMwujt0q7bd9Zg1fYVEiVRvjRuPjPdA1Yprb -rxTIW6HMiRvhMCb8oJsfgadHHwTrozmSBp+Z07/T6k9QnBn+locePGX2oxgkg4YQ -51Q+qDp2JE+BIcXjDwL4k5RHILv+1A7TaLndxHqEguNTVHnd25zS8gebLra8Pu2F -be8lEfKXGkJh90qX6IuxEAf6ZYGyojnP9zz/GPvG8VqLWeICrHuS0E4UT1lF9gxe -KF+w6D9Fz8+vm2/7hNN3WpVvrJSEnu68wEqPSpP4RCHiMUVhUE4Q2OM1fEwZtN4F -v6MGn8i1zeQf1xcGDXqVdFUNaBr8EBtiZJ1t4JWgw5QHVw0U5r0F+7if5t+L4sbn -fpb2U8WANFAoWPASUHEXMLrmeGO89LKtmyuy/uE5jF66CyCU3nuDuP/jVo23Eek7 -jPKxwV2dpAtMK9myGPW1n0sCAwEAAaNjMGEwHQYDVR0OBBYEFFLYiDrIn3hm7Ynz -ezhwlMkCAjbQMA8GA1UdEwEB/wQFMAMBAf8wHwYDVR0jBBgwFoAUUtiIOsifeGbt -ifN7OHCUyQICNtAwDgYDVR0PAQH/BAQDAgEGMA0GCSqGSIb3DQEBCwUAA4ICAQAL -e3KHwGCmSUyIWOYdiPcUZEim2FgKDk8TNd81HdTtBjHIgT5q1d07GjLukD0R0i70 -jsNjLiNmsGe+b7bAEzlgqqI0JZN1Ut6nna0Oh4lScWoWPBkdg/iaKWW+9D+a2fDz -WochcYBNy+A4mz+7+uAwTc+G02UQGRjRlwKxK3JCaKygvU5a2hi/a5iB0P2avl4V -SM0RFbnAKVy06Ij3Pjaut2L9HmLecHgQHEhb2rykOLpn7VU+Xlff1ANATIGk0k9j -pwlCCRT8AKnCgHNPLsBA2RF7SOp6AsDT6ygBJlh0wcBzIm2Tlf05fbsq4/aC4yyX -X04fkZT6/iyj2HYauE2yOE+b+h1IYHkm4vP9qdCa6HCPSXrW5b0KDtst842/6+Ok -fcvHlXHo2qN8xcL4dJIEG4aspCJTQLas/kx2z/uUMsA1n3Y/buWQbqCmJqK4LL7R -K4X9p2jIugErsWx0Hbhzlefut8cl8ABMALJ+tguLHPPAUJ4lueAI3jZm/zel0btU -ZCzJJ7VLkn5l/9Mt4blOvH+kQSGQQXemOR/qnuOf0GZvBeyqdn6/axag67XH/JJU -LysRJyU3eExRarDzzFhdFPFqSBX/wge2sY0PjlxQRrM9vwGYT7JZVEc+NHt4bVaT -LnPqZih4zR0Uv6CPLy64Lo7yFIrM6bV8+2ydDKXhlg== ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: 1 (0x1) - Signature Algorithm: sha1WithRSAEncryption - Issuer: C=SE, O=AddTrust AB, OU=AddTrust External TTP Network, CN=AddTrust External CA Root - Validity - Not Before: May 30 10:48:38 2000 GMT - Not After : May 30 10:48:38 2020 GMT - Subject: C=SE, O=AddTrust AB, OU=AddTrust External TTP Network, CN=AddTrust External CA Root - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (2048 bit) - Modulus: - 00:b7:f7:1a:33:e6:f2:00:04:2d:39:e0:4e:5b:ed: - 1f:bc:6c:0f:cd:b5:fa:23:b6:ce:de:9b:11:33:97: - a4:29:4c:7d:93:9f:bd:4a:bc:93:ed:03:1a:e3:8f: - cf:e5:6d:50:5a:d6:97:29:94:5a:80:b0:49:7a:db: - 2e:95:fd:b8:ca:bf:37:38:2d:1e:3e:91:41:ad:70: - 56:c7:f0:4f:3f:e8:32:9e:74:ca:c8:90:54:e9:c6: - 5f:0f:78:9d:9a:40:3c:0e:ac:61:aa:5e:14:8f:9e: - 87:a1:6a:50:dc:d7:9a:4e:af:05:b3:a6:71:94:9c: - 71:b3:50:60:0a:c7:13:9d:38:07:86:02:a8:e9:a8: - 69:26:18:90:ab:4c:b0:4f:23:ab:3a:4f:84:d8:df: - ce:9f:e1:69:6f:bb:d7:42:d7:6b:44:e4:c7:ad:ee: - 6d:41:5f:72:5a:71:08:37:b3:79:65:a4:59:a0:94: - 37:f7:00:2f:0d:c2:92:72:da:d0:38:72:db:14:a8: - 45:c4:5d:2a:7d:b7:b4:d6:c4:ee:ac:cd:13:44:b7: - c9:2b:dd:43:00:25:fa:61:b9:69:6a:58:23:11:b7: - a7:33:8f:56:75:59:f5:cd:29:d7:46:b7:0a:2b:65: - b6:d3:42:6f:15:b2:b8:7b:fb:ef:e9:5d:53:d5:34: - 5a:27 - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Subject Key Identifier: - AD:BD:98:7A:34:B4:26:F7:FA:C4:26:54:EF:03:BD:E0:24:CB:54:1A - X509v3 Key Usage: - Certificate Sign, CRL Sign - X509v3 Basic Constraints: critical - CA:TRUE - X509v3 Authority Key Identifier: - keyid:AD:BD:98:7A:34:B4:26:F7:FA:C4:26:54:EF:03:BD:E0:24:CB:54:1A - DirName:/C=SE/O=AddTrust AB/OU=AddTrust External TTP Network/CN=AddTrust External CA Root - serial:01 - - Signature Algorithm: sha1WithRSAEncryption - b0:9b:e0:85:25:c2:d6:23:e2:0f:96:06:92:9d:41:98:9c:d9: - 84:79:81:d9:1e:5b:14:07:23:36:65:8f:b0:d8:77:bb:ac:41: - 6c:47:60:83:51:b0:f9:32:3d:e7:fc:f6:26:13:c7:80:16:a5: - bf:5a:fc:87:cf:78:79:89:21:9a:e2:4c:07:0a:86:35:bc:f2: - de:51:c4:d2:96:b7:dc:7e:4e:ee:70:fd:1c:39:eb:0c:02:51: - 14:2d:8e:bd:16:e0:c1:df:46:75:e7:24:ad:ec:f4:42:b4:85: - 93:70:10:67:ba:9d:06:35:4a:18:d3:2b:7a:cc:51:42:a1:7a: - 63:d1:e6:bb:a1:c5:2b:c2:36:be:13:0d:e6:bd:63:7e:79:7b: - a7:09:0d:40:ab:6a:dd:8f:8a:c3:f6:f6:8c:1a:42:05:51:d4: - 45:f5:9f:a7:62:21:68:15:20:43:3c:99:e7:7c:bd:24:d8:a9: - 91:17:73:88:3f:56:1b:31:38:18:b4:71:0f:9a:cd:c8:0e:9e: - 8e:2e:1b:e1:8c:98:83:cb:1f:31:f1:44:4c:c6:04:73:49:76: - 60:0f:c7:f8:bd:17:80:6b:2e:e9:cc:4c:0e:5a:9a:79:0f:20: - 0a:2e:d5:9e:63:26:1e:55:92:94:d8:82:17:5a:7b:d0:bc:c7: - 8f:4e:86:04 ------BEGIN CERTIFICATE----- -MIIENjCCAx6gAwIBAgIBATANBgkqhkiG9w0BAQUFADBvMQswCQYDVQQGEwJTRTEU -MBIGA1UEChMLQWRkVHJ1c3QgQUIxJjAkBgNVBAsTHUFkZFRydXN0IEV4dGVybmFs -IFRUUCBOZXR3b3JrMSIwIAYDVQQDExlBZGRUcnVzdCBFeHRlcm5hbCBDQSBSb290 -MB4XDTAwMDUzMDEwNDgzOFoXDTIwMDUzMDEwNDgzOFowbzELMAkGA1UEBhMCU0Ux -FDASBgNVBAoTC0FkZFRydXN0IEFCMSYwJAYDVQQLEx1BZGRUcnVzdCBFeHRlcm5h -bCBUVFAgTmV0d29yazEiMCAGA1UEAxMZQWRkVHJ1c3QgRXh0ZXJuYWwgQ0EgUm9v -dDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALf3GjPm8gAELTngTlvt -H7xsD821+iO2zt6bETOXpClMfZOfvUq8k+0DGuOPz+VtUFrWlymUWoCwSXrbLpX9 -uMq/NzgtHj6RQa1wVsfwTz/oMp50ysiQVOnGXw94nZpAPA6sYapeFI+eh6FqUNzX -mk6vBbOmcZSccbNQYArHE504B4YCqOmoaSYYkKtMsE8jqzpPhNjfzp/haW+710LX -a0Tkx63ubUFfclpxCDezeWWkWaCUN/cALw3CknLa0Dhy2xSoRcRdKn23tNbE7qzN -E0S3ySvdQwAl+mG5aWpYIxG3pzOPVnVZ9c0p10a3CitlttNCbxWyuHv77+ldU9U0 -WicCAwEAAaOB3DCB2TAdBgNVHQ4EFgQUrb2YejS0Jvf6xCZU7wO94CTLVBowCwYD -VR0PBAQDAgEGMA8GA1UdEwEB/wQFMAMBAf8wgZkGA1UdIwSBkTCBjoAUrb2YejS0 -Jvf6xCZU7wO94CTLVBqhc6RxMG8xCzAJBgNVBAYTAlNFMRQwEgYDVQQKEwtBZGRU -cnVzdCBBQjEmMCQGA1UECxMdQWRkVHJ1c3QgRXh0ZXJuYWwgVFRQIE5ldHdvcmsx -IjAgBgNVBAMTGUFkZFRydXN0IEV4dGVybmFsIENBIFJvb3SCAQEwDQYJKoZIhvcN -AQEFBQADggEBALCb4IUlwtYj4g+WBpKdQZic2YR5gdkeWxQHIzZlj7DYd7usQWxH -YINRsPkyPef89iYTx4AWpb9a/IfPeHmJIZriTAcKhjW88t5RxNKWt9x+Tu5w/Rw5 -6wwCURQtjr0W4MHfRnXnJK3s9EK0hZNwEGe6nQY1ShjTK3rMUUKhemPR5ruhxSvC -Nr4TDea9Y355e6cJDUCrat2PisP29owaQgVR1EX1n6diIWgVIEM8med8vSTYqZEX -c4g/VhsxOBi0cQ+azcgOno4uG+GMmIPLHzHxREzGBHNJdmAPx/i9F4BrLunMTA5a -mnkPIAou1Z5jJh5VkpTYghdae9C8x49OhgQ= ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: 1 (0x1) - Signature Algorithm: sha1WithRSAEncryption - Issuer: C=SE, O=AddTrust AB, OU=AddTrust TTP Network, CN=AddTrust Class 1 CA Root - Validity - Not Before: May 30 10:38:31 2000 GMT - Not After : May 30 10:38:31 2020 GMT - Subject: C=SE, O=AddTrust AB, OU=AddTrust TTP Network, CN=AddTrust Class 1 CA Root - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (2048 bit) - Modulus: - 00:96:96:d4:21:49:60:e2:6b:e8:41:07:0c:de:c4: - e0:dc:13:23:cd:c1:35:c7:fb:d6:4e:11:0a:67:5e: - f5:06:5b:6b:a5:08:3b:5b:29:16:3a:e7:87:b2:34: - 06:c5:bc:05:a5:03:7c:82:cb:29:10:ae:e1:88:81: - bd:d6:9e:d3:fe:2d:56:c1:15:ce:e3:26:9d:15:2e: - 10:fb:06:8f:30:04:de:a7:b4:63:b4:ff:b1:9c:ae: - 3c:af:77:b6:56:c5:b5:ab:a2:e9:69:3a:3d:0e:33: - 79:32:3f:70:82:92:99:61:6d:8d:30:08:8f:71:3f: - a6:48:57:19:f8:25:dc:4b:66:5c:a5:74:8f:98:ae: - c8:f9:c0:06:22:e7:ac:73:df:a5:2e:fb:52:dc:b1: - 15:65:20:fa:35:66:69:de:df:2c:f1:6e:bc:30:db: - 2c:24:12:db:eb:35:35:68:90:cb:00:b0:97:21:3d: - 74:21:23:65:34:2b:bb:78:59:a3:d6:e1:76:39:9a: - a4:49:8e:8c:74:af:6e:a4:9a:a3:d9:9b:d2:38:5c: - 9b:a2:18:cc:75:23:84:be:eb:e2:4d:33:71:8e:1a: - f0:c2:f8:c7:1d:a2:ad:03:97:2c:f8:cf:25:c6:f6: - b8:24:31:b1:63:5d:92:7f:63:f0:25:c9:53:2e:1f: - bf:4d - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Subject Key Identifier: - 95:B1:B4:F0:94:B6:BD:C7:DA:D1:11:09:21:BE:C1:AF:49:FD:10:7B - X509v3 Key Usage: - Certificate Sign, CRL Sign - X509v3 Basic Constraints: critical - CA:TRUE - X509v3 Authority Key Identifier: - keyid:95:B1:B4:F0:94:B6:BD:C7:DA:D1:11:09:21:BE:C1:AF:49:FD:10:7B - DirName:/C=SE/O=AddTrust AB/OU=AddTrust TTP Network/CN=AddTrust Class 1 CA Root - serial:01 - - Signature Algorithm: sha1WithRSAEncryption - 2c:6d:64:1b:1f:cd:0d:dd:b9:01:fa:96:63:34:32:48:47:99: - ae:97:ed:fd:72:16:a6:73:47:5a:f4:eb:dd:e9:f5:d6:fb:45: - cc:29:89:44:5d:bf:46:39:3d:e8:ee:bc:4d:54:86:1e:1d:6c: - e3:17:27:43:e1:89:56:2b:a9:6f:72:4e:49:33:e3:72:7c:2a: - 23:9a:bc:3e:ff:28:2a:ed:a3:ff:1c:23:ba:43:57:09:67:4d: - 4b:62:06:2d:f8:ff:6c:9d:60:1e:d8:1c:4b:7d:b5:31:2f:d9: - d0:7c:5d:f8:de:6b:83:18:78:37:57:2f:e8:33:07:67:df:1e: - c7:6b:2a:95:76:ae:8f:57:a3:f0:f4:52:b4:a9:53:08:cf:e0: - 4f:d3:7a:53:8b:fd:bb:1c:56:36:f2:fe:b2:b6:e5:76:bb:d5: - 22:65:a7:3f:fe:d1:66:ad:0b:bc:6b:99:86:ef:3f:7d:f3:18: - 32:ca:7b:c6:e3:ab:64:46:95:f8:26:69:d9:55:83:7b:2c:96: - 07:ff:59:2c:44:a3:c6:e5:e9:a9:dc:a1:63:80:5a:21:5e:21: - cf:53:54:f0:ba:6f:89:db:a8:aa:95:cf:8b:e3:71:cc:1e:1b: - 20:44:08:c0:7a:b6:40:fd:c4:e4:35:e1:1d:16:1c:d0:bc:2b: - 8e:d6:71:d9 ------BEGIN CERTIFICATE----- -MIIEGDCCAwCgAwIBAgIBATANBgkqhkiG9w0BAQUFADBlMQswCQYDVQQGEwJTRTEU -MBIGA1UEChMLQWRkVHJ1c3QgQUIxHTAbBgNVBAsTFEFkZFRydXN0IFRUUCBOZXR3 -b3JrMSEwHwYDVQQDExhBZGRUcnVzdCBDbGFzcyAxIENBIFJvb3QwHhcNMDAwNTMw -MTAzODMxWhcNMjAwNTMwMTAzODMxWjBlMQswCQYDVQQGEwJTRTEUMBIGA1UEChML -QWRkVHJ1c3QgQUIxHTAbBgNVBAsTFEFkZFRydXN0IFRUUCBOZXR3b3JrMSEwHwYD -VQQDExhBZGRUcnVzdCBDbGFzcyAxIENBIFJvb3QwggEiMA0GCSqGSIb3DQEBAQUA -A4IBDwAwggEKAoIBAQCWltQhSWDia+hBBwzexODcEyPNwTXH+9ZOEQpnXvUGW2ul -CDtbKRY654eyNAbFvAWlA3yCyykQruGIgb3WntP+LVbBFc7jJp0VLhD7Bo8wBN6n -tGO0/7Gcrjyvd7ZWxbWroulpOj0OM3kyP3CCkplhbY0wCI9xP6ZIVxn4JdxLZlyl -dI+Yrsj5wAYi56xz36Uu+1LcsRVlIPo1Zmne3yzxbrww2ywkEtvrNTVokMsAsJch -PXQhI2U0K7t4WaPW4XY5mqRJjox0r26kmqPZm9I4XJuiGMx1I4S+6+JNM3GOGvDC -+Mcdoq0Dlyz4zyXG9rgkMbFjXZJ/Y/AlyVMuH79NAgMBAAGjgdIwgc8wHQYDVR0O -BBYEFJWxtPCUtr3H2tERCSG+wa9J/RB7MAsGA1UdDwQEAwIBBjAPBgNVHRMBAf8E -BTADAQH/MIGPBgNVHSMEgYcwgYSAFJWxtPCUtr3H2tERCSG+wa9J/RB7oWmkZzBl -MQswCQYDVQQGEwJTRTEUMBIGA1UEChMLQWRkVHJ1c3QgQUIxHTAbBgNVBAsTFEFk -ZFRydXN0IFRUUCBOZXR3b3JrMSEwHwYDVQQDExhBZGRUcnVzdCBDbGFzcyAxIENB -IFJvb3SCAQEwDQYJKoZIhvcNAQEFBQADggEBACxtZBsfzQ3duQH6lmM0MkhHma6X -7f1yFqZzR1r0693p9db7RcwpiURdv0Y5PejuvE1Uhh4dbOMXJ0PhiVYrqW9yTkkz -43J8KiOavD7/KCrto/8cI7pDVwlnTUtiBi34/2ydYB7YHEt9tTEv2dB8Xfjea4MY -eDdXL+gzB2ffHsdrKpV2ro9Xo/D0UrSpUwjP4E/TelOL/bscVjby/rK25Xa71SJl -pz/+0WatC7xrmYbvP33zGDLKe8bjq2RGlfgmadlVg3sslgf/WSxEo8bl6ancoWOA -WiFeIc9TVPC6b4nbqKqVz4vjccweGyBECMB6tkD9xOQ14R0WHNC8K47Wcdk= ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: 1 (0x1) - Signature Algorithm: sha1WithRSAEncryption - Issuer: C=SE, O=AddTrust AB, OU=AddTrust TTP Network, CN=AddTrust Public CA Root - Validity - Not Before: May 30 10:41:50 2000 GMT - Not After : May 30 10:41:50 2020 GMT - Subject: C=SE, O=AddTrust AB, OU=AddTrust TTP Network, CN=AddTrust Public CA Root - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (2048 bit) - Modulus: - 00:e9:1a:30:8f:83:88:14:c1:20:d8:3c:9b:8f:1b: - 7e:03:74:bb:da:69:d3:46:a5:f8:8e:c2:0c:11:90: - 51:a5:2f:66:54:40:55:ea:db:1f:4a:56:ee:9f:23: - 6e:f4:39:cb:a1:b9:6f:f2:7e:f9:5d:87:26:61:9e: - 1c:f8:e2:ec:a6:81:f8:21:c5:24:cc:11:0c:3f:db: - 26:72:7a:c7:01:97:07:17:f9:d7:18:2c:30:7d:0e: - 7a:1e:62:1e:c6:4b:c0:fd:7d:62:77:d3:44:1e:27: - f6:3f:4b:44:b3:b7:38:d9:39:1f:60:d5:51:92:73: - 03:b4:00:69:e3:f3:14:4e:ee:d1:dc:09:cf:77:34: - 46:50:b0:f8:11:f2:fe:38:79:f7:07:39:fe:51:92: - 97:0b:5b:08:5f:34:86:01:ad:88:97:eb:66:cd:5e: - d1:ff:dc:7d:f2:84:da:ba:77:ad:dc:80:08:c7:a7: - 87:d6:55:9f:97:6a:e8:c8:11:64:ba:e7:19:29:3f: - 11:b3:78:90:84:20:52:5b:11:ef:78:d0:83:f6:d5: - 48:90:d0:30:1c:cf:80:f9:60:fe:79:e4:88:f2:dd: - 00:eb:94:45:eb:65:94:69:40:ba:c0:d5:b4:b8:ba: - 7d:04:11:a8:eb:31:05:96:94:4e:58:21:8e:9f:d0: - 60:fd - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Subject Key Identifier: - 81:3E:37:D8:92:B0:1F:77:9F:5C:B4:AB:73:AA:E7:F6:34:60:2F:FA - X509v3 Key Usage: - Certificate Sign, CRL Sign - X509v3 Basic Constraints: critical - CA:TRUE - X509v3 Authority Key Identifier: - keyid:81:3E:37:D8:92:B0:1F:77:9F:5C:B4:AB:73:AA:E7:F6:34:60:2F:FA - DirName:/C=SE/O=AddTrust AB/OU=AddTrust TTP Network/CN=AddTrust Public CA Root - serial:01 - - Signature Algorithm: sha1WithRSAEncryption - 03:f7:15:4a:f8:24:da:23:56:16:93:76:dd:36:28:b9:ae:1b: - b8:c3:f1:64:ba:20:18:78:95:29:27:57:05:bc:7c:2a:f4:b9: - 51:55:da:87:02:de:0f:16:17:31:f8:aa:79:2e:09:13:bb:af: - b2:20:19:12:e5:93:f9:4b:f9:83:e8:44:d5:b2:41:25:bf:88: - 75:6f:ff:10:fc:4a:54:d0:5f:f0:fa:ef:36:73:7d:1b:36:45: - c6:21:6d:b4:15:b8:4e:cf:9c:5c:a5:3d:5a:00:8e:06:e3:3c: - 6b:32:7b:f2:9f:f0:b6:fd:df:f0:28:18:48:f0:c6:bc:d0:bf: - 34:80:96:c2:4a:b1:6d:8e:c7:90:45:de:2f:67:ac:45:04:a3: - 7a:dc:55:92:c9:47:66:d8:1a:8c:c7:ed:9c:4e:9a:e0:12:bb: - b5:6a:4c:84:e1:e1:22:0d:87:00:64:fe:8c:7d:62:39:65:a6: - ef:42:b6:80:25:12:61:01:a8:24:13:70:00:11:26:5f:fa:35: - 50:c5:48:cc:06:47:e8:27:d8:70:8d:5f:64:e6:a1:44:26:5e: - 22:ec:92:cd:ff:42:9a:44:21:6d:5c:c5:e3:22:1d:5f:47:12: - e7:ce:5f:5d:fa:d8:aa:b1:33:2d:d9:76:f2:4e:3a:33:0c:2b: - b3:2d:90:06 ------BEGIN CERTIFICATE----- -MIIEFTCCAv2gAwIBAgIBATANBgkqhkiG9w0BAQUFADBkMQswCQYDVQQGEwJTRTEU -MBIGA1UEChMLQWRkVHJ1c3QgQUIxHTAbBgNVBAsTFEFkZFRydXN0IFRUUCBOZXR3 -b3JrMSAwHgYDVQQDExdBZGRUcnVzdCBQdWJsaWMgQ0EgUm9vdDAeFw0wMDA1MzAx -MDQxNTBaFw0yMDA1MzAxMDQxNTBaMGQxCzAJBgNVBAYTAlNFMRQwEgYDVQQKEwtB -ZGRUcnVzdCBBQjEdMBsGA1UECxMUQWRkVHJ1c3QgVFRQIE5ldHdvcmsxIDAeBgNV -BAMTF0FkZFRydXN0IFB1YmxpYyBDQSBSb290MIIBIjANBgkqhkiG9w0BAQEFAAOC -AQ8AMIIBCgKCAQEA6Rowj4OIFMEg2Dybjxt+A3S72mnTRqX4jsIMEZBRpS9mVEBV -6tsfSlbunyNu9DnLoblv8n75XYcmYZ4c+OLspoH4IcUkzBEMP9smcnrHAZcHF/nX -GCwwfQ56HmIexkvA/X1id9NEHif2P0tEs7c42TkfYNVRknMDtABp4/MUTu7R3AnP -dzRGULD4EfL+OHn3Bzn+UZKXC1sIXzSGAa2Il+tmzV7R/9x98oTaunet3IAIx6eH -1lWfl2royBFkuucZKT8Rs3iQhCBSWxHveNCD9tVIkNAwHM+A+WD+eeSI8t0A65RF -62WUaUC6wNW0uLp9BBGo6zEFlpROWCGOn9Bg/QIDAQABo4HRMIHOMB0GA1UdDgQW -BBSBPjfYkrAfd59ctKtzquf2NGAv+jALBgNVHQ8EBAMCAQYwDwYDVR0TAQH/BAUw -AwEB/zCBjgYDVR0jBIGGMIGDgBSBPjfYkrAfd59ctKtzquf2NGAv+qFopGYwZDEL -MAkGA1UEBhMCU0UxFDASBgNVBAoTC0FkZFRydXN0IEFCMR0wGwYDVQQLExRBZGRU -cnVzdCBUVFAgTmV0d29yazEgMB4GA1UEAxMXQWRkVHJ1c3QgUHVibGljIENBIFJv -b3SCAQEwDQYJKoZIhvcNAQEFBQADggEBAAP3FUr4JNojVhaTdt02KLmuG7jD8WS6 -IBh4lSknVwW8fCr0uVFV2ocC3g8WFzH4qnkuCRO7r7IgGRLlk/lL+YPoRNWyQSW/ -iHVv/xD8SlTQX/D67zZzfRs2RcYhbbQVuE7PnFylPVoAjgbjPGsye/Kf8Lb93/Ao -GEjwxrzQvzSAlsJKsW2Ox5BF3i9nrEUEo3rcVZLJR2bYGozH7ZxOmuASu7VqTITh -4SINhwBk/ox9Yjllpu9CtoAlEmEBqCQTcAARJl/6NVDFSMwGR+gn2HCNX2TmoUQm -XiLsks3/QppEIW1cxeMiHV9HEufOX1362KqxMy3ZdvJOOjMMK7MtkAY= ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: 1 (0x1) - Signature Algorithm: sha1WithRSAEncryption - Issuer: C=SE, O=AddTrust AB, OU=AddTrust TTP Network, CN=AddTrust Qualified CA Root - Validity - Not Before: May 30 10:44:50 2000 GMT - Not After : May 30 10:44:50 2020 GMT - Subject: C=SE, O=AddTrust AB, OU=AddTrust TTP Network, CN=AddTrust Qualified CA Root - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (2048 bit) - Modulus: - 00:e4:1e:9a:fe:dc:09:5a:87:a4:9f:47:be:11:5f: - af:84:34:db:62:3c:79:78:b7:e9:30:b5:ec:0c:1c: - 2a:c4:16:ff:e0:ec:71:eb:8a:f5:11:6e:ed:4f:0d: - 91:d2:12:18:2d:49:15:01:c2:a4:22:13:c7:11:64: - ff:22:12:9a:b9:8e:5c:2f:08:cf:71:6a:b3:67:01: - 59:f1:5d:46:f3:b0:78:a5:f6:0e:42:7a:e3:7f:1b: - cc:d0:f0:b7:28:fd:2a:ea:9e:b3:b0:b9:04:aa:fd: - f6:c7:b4:b1:b8:2a:a0:fb:58:f1:19:a0:6f:70:25: - 7e:3e:69:4a:7f:0f:22:d8:ef:ad:08:11:9a:29:99: - e1:aa:44:45:9a:12:5e:3e:9d:6d:52:fc:e7:a0:3d: - 68:2f:f0:4b:70:7c:13:38:ad:bc:15:25:f1:d6:ce: - ab:a2:c0:31:d6:2f:9f:e0:ff:14:59:fc:84:93:d9: - 87:7c:4c:54:13:eb:9f:d1:2d:11:f8:18:3a:3a:de: - 25:d9:f7:d3:40:ed:a4:06:12:c4:3b:e1:91:c1:56: - 35:f0:14:dc:65:36:09:6e:ab:a4:07:c7:35:d1:c2: - 03:33:36:5b:75:26:6d:42:f1:12:6b:43:6f:4b:71: - 94:fa:34:1d:ed:13:6e:ca:80:7f:98:2f:6c:b9:65: - d8:e9 - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Subject Key Identifier: - 39:95:8B:62:8B:5C:C9:D4:80:BA:58:0F:97:3F:15:08:43:CC:98:A7 - X509v3 Key Usage: - Certificate Sign, CRL Sign - X509v3 Basic Constraints: critical - CA:TRUE - X509v3 Authority Key Identifier: - keyid:39:95:8B:62:8B:5C:C9:D4:80:BA:58:0F:97:3F:15:08:43:CC:98:A7 - DirName:/C=SE/O=AddTrust AB/OU=AddTrust TTP Network/CN=AddTrust Qualified CA Root - serial:01 - - Signature Algorithm: sha1WithRSAEncryption - 19:ab:75:ea:f8:8b:65:61:95:13:ba:69:04:ef:86:ca:13:a0: - c7:aa:4f:64:1b:3f:18:f6:a8:2d:2c:55:8f:05:b7:30:ea:42: - 6a:1d:c0:25:51:2d:a7:bf:0c:b3:ed:ef:08:7f:6c:3c:46:1a: - ea:18:43:df:76:cc:f9:66:86:9c:2c:68:f5:e9:17:f8:31:b3: - 18:c4:d6:48:7d:23:4c:68:c1:7e:bb:01:14:6f:c5:d9:6e:de: - bb:04:42:6a:f8:f6:5c:7d:e5:da:fa:87:eb:0d:35:52:67:d0: - 9e:97:76:05:93:3f:95:c7:01:e6:69:55:38:7f:10:61:99:c9: - e3:5f:a6:ca:3e:82:63:48:aa:e2:08:48:3e:aa:f2:b2:85:62: - a6:b4:a7:d9:bd:37:9c:68:b5:2d:56:7d:b0:b7:3f:a0:b1:07: - d6:e9:4f:dc:de:45:71:30:32:7f:1b:2e:09:f9:bf:52:a1:ee: - c2:80:3e:06:5c:2e:55:40:c1:1b:f5:70:45:b0:dc:5d:fa:f6: - 72:5a:77:d2:63:cd:cf:58:89:00:42:63:3f:79:39:d0:44:b0: - 82:6e:41:19:e8:dd:e0:c1:88:5a:d1:1e:71:93:1f:24:30:74: - e5:1e:a8:de:3c:27:37:7f:83:ae:9e:77:cf:f0:30:b1:ff:4b: - 99:e8:c6:a1 ------BEGIN CERTIFICATE----- -MIIEHjCCAwagAwIBAgIBATANBgkqhkiG9w0BAQUFADBnMQswCQYDVQQGEwJTRTEU -MBIGA1UEChMLQWRkVHJ1c3QgQUIxHTAbBgNVBAsTFEFkZFRydXN0IFRUUCBOZXR3 -b3JrMSMwIQYDVQQDExpBZGRUcnVzdCBRdWFsaWZpZWQgQ0EgUm9vdDAeFw0wMDA1 -MzAxMDQ0NTBaFw0yMDA1MzAxMDQ0NTBaMGcxCzAJBgNVBAYTAlNFMRQwEgYDVQQK -EwtBZGRUcnVzdCBBQjEdMBsGA1UECxMUQWRkVHJ1c3QgVFRQIE5ldHdvcmsxIzAh -BgNVBAMTGkFkZFRydXN0IFF1YWxpZmllZCBDQSBSb290MIIBIjANBgkqhkiG9w0B -AQEFAAOCAQ8AMIIBCgKCAQEA5B6a/twJWoekn0e+EV+vhDTbYjx5eLfpMLXsDBwq -xBb/4Oxx64r1EW7tTw2R0hIYLUkVAcKkIhPHEWT/IhKauY5cLwjPcWqzZwFZ8V1G -87B4pfYOQnrjfxvM0PC3KP0q6p6zsLkEqv32x7SxuCqg+1jxGaBvcCV+PmlKfw8i -2O+tCBGaKZnhqkRFmhJePp1tUvznoD1oL/BLcHwTOK28FSXx1s6rosAx1i+f4P8U -WfyEk9mHfExUE+uf0S0R+Bg6Ot4l2ffTQO2kBhLEO+GRwVY18BTcZTYJbqukB8c1 -0cIDMzZbdSZtQvESa0NvS3GU+jQd7RNuyoB/mC9suWXY6QIDAQABo4HUMIHRMB0G -A1UdDgQWBBQ5lYtii1zJ1IC6WA+XPxUIQ8yYpzALBgNVHQ8EBAMCAQYwDwYDVR0T -AQH/BAUwAwEB/zCBkQYDVR0jBIGJMIGGgBQ5lYtii1zJ1IC6WA+XPxUIQ8yYp6Fr -pGkwZzELMAkGA1UEBhMCU0UxFDASBgNVBAoTC0FkZFRydXN0IEFCMR0wGwYDVQQL -ExRBZGRUcnVzdCBUVFAgTmV0d29yazEjMCEGA1UEAxMaQWRkVHJ1c3QgUXVhbGlm -aWVkIENBIFJvb3SCAQEwDQYJKoZIhvcNAQEFBQADggEBABmrder4i2VhlRO6aQTv -hsoToMeqT2QbPxj2qC0sVY8FtzDqQmodwCVRLae/DLPt7wh/bDxGGuoYQ992zPlm -hpwsaPXpF/gxsxjE1kh9I0xowX67ARRvxdlu3rsEQmr49lx95dr6h+sNNVJn0J6X -dgWTP5XHAeZpVTh/EGGZyeNfpso+gmNIquIISD6q8rKFYqa0p9m9N5xotS1WfbC3 -P6CxB9bpT9zeRXEwMn8bLgn5v1Kh7sKAPgZcLlVAwRv1cEWw3F369nJad9Jjzc9Y -iQBCYz95OdBEsIJuQRno3eDBiFrRHnGTHyQwdOUeqN48Jzd/g66ed8/wMLH/S5no -xqE= ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: - 77:77:06:27:26:a9:b1:7c - Signature Algorithm: sha256WithRSAEncryption - Issuer: C=US, O=AffirmTrust, CN=AffirmTrust Commercial - Validity - Not Before: Jan 29 14:06:06 2010 GMT - Not After : Dec 31 14:06:06 2030 GMT - Subject: C=US, O=AffirmTrust, CN=AffirmTrust Commercial - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (2048 bit) - Modulus: - 00:f6:1b:4f:67:07:2b:a1:15:f5:06:22:cb:1f:01: - b2:e3:73:45:06:44:49:2c:bb:49:25:14:d6:ce:c3: - b7:ab:2c:4f:c6:41:32:94:57:fa:12:a7:5b:0e:e2: - 8f:1f:1e:86:19:a7:aa:b5:2d:b9:5f:0d:8a:c2:af: - 85:35:79:32:2d:bb:1c:62:37:f2:b1:5b:4a:3d:ca: - cd:71:5f:e9:42:be:94:e8:c8:de:f9:22:48:64:c6: - e5:ab:c6:2b:6d:ad:05:f0:fa:d5:0b:cf:9a:e5:f0: - 50:a4:8b:3b:47:a5:23:5b:7a:7a:f8:33:3f:b8:ef: - 99:97:e3:20:c1:d6:28:89:cf:94:fb:b9:45:ed:e3: - 40:17:11:d4:74:f0:0b:31:e2:2b:26:6a:9b:4c:57: - ae:ac:20:3e:ba:45:7a:05:f3:bd:9b:69:15:ae:7d: - 4e:20:63:c4:35:76:3a:07:02:c9:37:fd:c7:47:ee: - e8:f1:76:1d:73:15:f2:97:a4:b5:c8:7a:79:d9:42: - aa:2b:7f:5c:fe:ce:26:4f:a3:66:81:35:af:44:ba: - 54:1e:1c:30:32:65:9d:e6:3c:93:5e:50:4e:7a:e3: - 3a:d4:6e:cc:1a:fb:f9:d2:37:ae:24:2a:ab:57:03: - 22:28:0d:49:75:7f:b7:28:da:75:bf:8e:e3:dc:0e: - 79:31 - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Subject Key Identifier: - 9D:93:C6:53:8B:5E:CA:AF:3F:9F:1E:0F:E5:99:95:BC:24:F6:94:8F - X509v3 Basic Constraints: critical - CA:TRUE - X509v3 Key Usage: critical - Certificate Sign, CRL Sign - Signature Algorithm: sha256WithRSAEncryption - 58:ac:f4:04:0e:cd:c0:0d:ff:0a:fd:d4:ba:16:5f:29:bd:7b: - 68:99:58:49:d2:b4:1d:37:4d:7f:27:7d:46:06:5d:43:c6:86: - 2e:3e:73:b2:26:7d:4f:93:a9:b6:c4:2a:9a:ab:21:97:14:b1: - de:8c:d3:ab:89:15:d8:6b:24:d4:f1:16:ae:d8:a4:5c:d4:7f: - 51:8e:ed:18:01:b1:93:63:bd:bc:f8:61:80:9a:9e:b1:ce:42: - 70:e2:a9:7d:06:25:7d:27:a1:fe:6f:ec:b3:1e:24:da:e3:4b: - 55:1a:00:3b:35:b4:3b:d9:d7:5d:30:fd:81:13:89:f2:c2:06: - 2b:ed:67:c4:8e:c9:43:b2:5c:6b:15:89:02:bc:62:fc:4e:f2: - b5:33:aa:b2:6f:d3:0a:a2:50:e3:f6:3b:e8:2e:44:c2:db:66: - 38:a9:33:56:48:f1:6d:1b:33:8d:0d:8c:3f:60:37:9d:d3:ca: - 6d:7e:34:7e:0d:9f:72:76:8b:1b:9f:72:fd:52:35:41:45:02: - 96:2f:1c:b2:9a:73:49:21:b1:49:47:45:47:b4:ef:6a:34:11: - c9:4d:9a:cc:59:b7:d6:02:9e:5a:4e:65:b5:94:ae:1b:df:29: - b0:16:f1:bf:00:9e:07:3a:17:64:b5:04:b5:23:21:99:0a:95: - 3b:97:7c:ef ------BEGIN CERTIFICATE----- -MIIDTDCCAjSgAwIBAgIId3cGJyapsXwwDQYJKoZIhvcNAQELBQAwRDELMAkGA1UE -BhMCVVMxFDASBgNVBAoMC0FmZmlybVRydXN0MR8wHQYDVQQDDBZBZmZpcm1UcnVz -dCBDb21tZXJjaWFsMB4XDTEwMDEyOTE0MDYwNloXDTMwMTIzMTE0MDYwNlowRDEL -MAkGA1UEBhMCVVMxFDASBgNVBAoMC0FmZmlybVRydXN0MR8wHQYDVQQDDBZBZmZp -cm1UcnVzdCBDb21tZXJjaWFsMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKC -AQEA9htPZwcroRX1BiLLHwGy43NFBkRJLLtJJRTWzsO3qyxPxkEylFf6EqdbDuKP -Hx6GGaeqtS25Xw2Kwq+FNXkyLbscYjfysVtKPcrNcV/pQr6U6Mje+SJIZMblq8Yr -ba0F8PrVC8+a5fBQpIs7R6UjW3p6+DM/uO+Zl+MgwdYoic+U+7lF7eNAFxHUdPAL -MeIrJmqbTFeurCA+ukV6BfO9m2kVrn1OIGPENXY6BwLJN/3HR+7o8XYdcxXyl6S1 -yHp52UKqK39c/s4mT6NmgTWvRLpUHhwwMmWd5jyTXlBOeuM61G7MGvv50jeuJCqr -VwMiKA1JdX+3KNp1v47j3A55MQIDAQABo0IwQDAdBgNVHQ4EFgQUnZPGU4teyq8/ -nx4P5ZmVvCT2lI8wDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwDQYJ -KoZIhvcNAQELBQADggEBAFis9AQOzcAN/wr91LoWXym9e2iZWEnStB03TX8nfUYG -XUPGhi4+c7ImfU+TqbbEKpqrIZcUsd6M06uJFdhrJNTxFq7YpFzUf1GO7RgBsZNj -vbz4YYCanrHOQnDiqX0GJX0nof5v7LMeJNrjS1UaADs1tDvZ110w/YETifLCBivt -Z8SOyUOyXGsViQK8YvxO8rUzqrJv0wqiUOP2O+guRMLbZjipM1ZI8W0bM40NjD9g -N53Tym1+NH4Nn3J2ixufcv1SNUFFApYvHLKac0khsUlHRUe072o0EclNmsxZt9YC -nlpOZbWUrhvfKbAW8b8Angc6F2S1BLUjIZkKlTuXfO8= ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: - 7c:4f:04:39:1c:d4:99:2d - Signature Algorithm: sha1WithRSAEncryption - Issuer: C=US, O=AffirmTrust, CN=AffirmTrust Networking - Validity - Not Before: Jan 29 14:08:24 2010 GMT - Not After : Dec 31 14:08:24 2030 GMT - Subject: C=US, O=AffirmTrust, CN=AffirmTrust Networking - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (2048 bit) - Modulus: - 00:b4:84:cc:33:17:2e:6b:94:6c:6b:61:52:a0:eb: - a3:cf:79:94:4c:e5:94:80:99:cb:55:64:44:65:8f: - 67:64:e2:06:e3:5c:37:49:f6:2f:9b:84:84:1e:2d: - f2:60:9d:30:4e:cc:84:85:e2:2c:cf:1e:9e:fe:36: - ab:33:77:35:44:d8:35:96:1a:3d:36:e8:7a:0e:d8: - d5:47:a1:6a:69:8b:d9:fc:bb:3a:ae:79:5a:d5:f4: - d6:71:bb:9a:90:23:6b:9a:b7:88:74:87:0c:1e:5f: - b9:9e:2d:fa:ab:53:2b:dc:bb:76:3e:93:4c:08:08: - 8c:1e:a2:23:1c:d4:6a:ad:22:ba:99:01:2e:6d:65: - cb:be:24:66:55:24:4b:40:44:b1:1b:d7:e1:c2:85: - c0:de:10:3f:3d:ed:b8:fc:f1:f1:23:53:dc:bf:65: - 97:6f:d9:f9:40:71:8d:7d:bd:95:d4:ce:be:a0:5e: - 27:23:de:fd:a6:d0:26:0e:00:29:eb:3c:46:f0:3d: - 60:bf:3f:50:d2:dc:26:41:51:9e:14:37:42:04:a3: - 70:57:a8:1b:87:ed:2d:fa:7b:ee:8c:0a:e3:a9:66: - 89:19:cb:41:f9:dd:44:36:61:cf:e2:77:46:c8:7d: - f6:f4:92:81:36:fd:db:34:f1:72:7e:f3:0c:16:bd: - b4:15 - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Subject Key Identifier: - 07:1F:D2:E7:9C:DA:C2:6E:A2:40:B4:B0:7A:50:10:50:74:C4:C8:BD - X509v3 Basic Constraints: critical - CA:TRUE - X509v3 Key Usage: critical - Certificate Sign, CRL Sign - Signature Algorithm: sha1WithRSAEncryption - 89:57:b2:16:7a:a8:c2:fd:d6:d9:9b:9b:34:c2:9c:b4:32:14: - 4d:a7:a4:df:ec:be:a7:be:f8:43:db:91:37:ce:b4:32:2e:50: - 55:1a:35:4e:76:43:71:20:ef:93:77:4e:15:70:2e:87:c3:c1: - 1d:6d:dc:cb:b5:27:d4:2c:56:d1:52:53:3a:44:d2:73:c8:c4: - 1b:05:65:5a:62:92:9c:ee:41:8d:31:db:e7:34:ea:59:21:d5: - 01:7a:d7:64:b8:64:39:cd:c9:ed:af:ed:4b:03:48:a7:a0:99: - 01:80:dc:65:a3:36:ae:65:59:48:4f:82:4b:c8:65:f1:57:1d: - e5:59:2e:0a:3f:6c:d8:d1:f5:e5:09:b4:6c:54:00:0a:e0:15: - 4d:87:75:6d:b7:58:96:5a:dd:6d:d2:00:a0:f4:9b:48:be:c3: - 37:a4:ba:36:e0:7c:87:85:97:1a:15:a2:de:2e:a2:5b:bd:af: - 18:f9:90:50:cd:70:59:f8:27:67:47:cb:c7:a0:07:3a:7d:d1: - 2c:5d:6c:19:3a:66:b5:7d:fd:91:6f:82:b1:be:08:93:db:14: - 47:f1:a2:37:c7:45:9e:3c:c7:77:af:64:a8:93:df:f6:69:83: - 82:60:f2:49:42:34:ed:5a:00:54:85:1c:16:36:92:0c:5c:fa: - a6:ad:bf:db ------BEGIN CERTIFICATE----- -MIIDTDCCAjSgAwIBAgIIfE8EORzUmS0wDQYJKoZIhvcNAQEFBQAwRDELMAkGA1UE -BhMCVVMxFDASBgNVBAoMC0FmZmlybVRydXN0MR8wHQYDVQQDDBZBZmZpcm1UcnVz -dCBOZXR3b3JraW5nMB4XDTEwMDEyOTE0MDgyNFoXDTMwMTIzMTE0MDgyNFowRDEL -MAkGA1UEBhMCVVMxFDASBgNVBAoMC0FmZmlybVRydXN0MR8wHQYDVQQDDBZBZmZp -cm1UcnVzdCBOZXR3b3JraW5nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKC -AQEAtITMMxcua5Rsa2FSoOujz3mUTOWUgJnLVWREZY9nZOIG41w3SfYvm4SEHi3y -YJ0wTsyEheIszx6e/jarM3c1RNg1lho9Nuh6DtjVR6FqaYvZ/Ls6rnla1fTWcbua -kCNrmreIdIcMHl+5ni36q1Mr3Lt2PpNMCAiMHqIjHNRqrSK6mQEubWXLviRmVSRL -QESxG9fhwoXA3hA/Pe24/PHxI1Pcv2WXb9n5QHGNfb2V1M6+oF4nI979ptAmDgAp -6zxG8D1gvz9Q0twmQVGeFDdCBKNwV6gbh+0t+nvujArjqWaJGctB+d1ENmHP4ndG -yH329JKBNv3bNPFyfvMMFr20FQIDAQABo0IwQDAdBgNVHQ4EFgQUBx/S55zawm6i -QLSwelAQUHTEyL0wDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwDQYJ -KoZIhvcNAQEFBQADggEBAIlXshZ6qML91tmbmzTCnLQyFE2npN/svqe++EPbkTfO -tDIuUFUaNU52Q3Eg75N3ThVwLofDwR1t3Mu1J9QsVtFSUzpE0nPIxBsFZVpikpzu -QY0x2+c06lkh1QF612S4ZDnNye2v7UsDSKegmQGA3GWjNq5lWUhPgkvIZfFXHeVZ -Lgo/bNjR9eUJtGxUAArgFU2HdW23WJZa3W3SAKD0m0i+wzekujbgfIeFlxoVot4u -olu9rxj5kFDNcFn4J2dHy8egBzp90SxdbBk6ZrV9/ZFvgrG+CJPbFEfxojfHRZ48 -x3evZKiT3/Zpg4Jg8klCNO1aAFSFHBY2kgxc+qatv9s= ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: - 6d:8c:14:46:b1:a6:0a:ee - Signature Algorithm: sha384WithRSAEncryption - Issuer: C=US, O=AffirmTrust, CN=AffirmTrust Premium - Validity - Not Before: Jan 29 14:10:36 2010 GMT - Not After : Dec 31 14:10:36 2040 GMT - Subject: C=US, O=AffirmTrust, CN=AffirmTrust Premium - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (4096 bit) - Modulus: - 00:c4:12:df:a9:5f:fe:41:dd:dd:f5:9f:8a:e3:f6: - ac:e1:3c:78:9a:bc:d8:f0:7f:7a:a0:33:2a:dc:8d: - 20:5b:ae:2d:6f:e7:93:d9:36:70:6a:68:cf:8e:51: - a3:85:5b:67:04:a0:10:24:6f:5d:28:82:c1:97:57: - d8:48:29:13:b6:e1:be:91:4d:df:85:0c:53:18:9a: - 1e:24:a2:4f:8f:f0:a2:85:0b:cb:f4:29:7f:d2:a4: - 58:ee:26:4d:c9:aa:a8:7b:9a:d9:fa:38:de:44:57: - 15:e5:f8:8c:c8:d9:48:e2:0d:16:27:1d:1e:c8:83: - 85:25:b7:ba:aa:55:41:cc:03:22:4b:2d:91:8d:8b: - e6:89:af:66:c7:e9:ff:2b:e9:3c:ac:da:d2:b3:c3: - e1:68:9c:89:f8:7a:00:56:de:f4:55:95:6c:fb:ba: - 64:dd:62:8b:df:0b:77:32:eb:62:cc:26:9a:9b:bb: - aa:62:83:4c:b4:06:7a:30:c8:29:bf:ed:06:4d:97: - b9:1c:c4:31:2b:d5:5f:bc:53:12:17:9c:99:57:29: - 66:77:61:21:31:07:2e:25:49:9d:18:f2:ee:f3:2b: - 71:8c:b5:ba:39:07:49:77:fc:ef:2e:92:90:05:8d: - 2d:2f:77:7b:ef:43:bf:35:bb:9a:d8:f9:73:a7:2c: - f2:d0:57:ee:28:4e:26:5f:8f:90:68:09:2f:b8:f8: - dc:06:e9:2e:9a:3e:51:a7:d1:22:c4:0a:a7:38:48: - 6c:b3:f9:ff:7d:ab:86:57:e3:ba:d6:85:78:77:ba: - 43:ea:48:7f:f6:d8:be:23:6d:1e:bf:d1:36:6c:58: - 5c:f1:ee:a4:19:54:1a:f5:03:d2:76:e6:e1:8c:bd: - 3c:b3:d3:48:4b:e2:c8:f8:7f:92:a8:76:46:9c:42: - 65:3e:a4:1e:c1:07:03:5a:46:2d:b8:97:f3:b7:d5: - b2:55:21:ef:ba:dc:4c:00:97:fb:14:95:27:33:bf: - e8:43:47:46:d2:08:99:16:60:3b:9a:7e:d2:e6:ed: - 38:ea:ec:01:1e:3c:48:56:49:09:c7:4c:37:00:9e: - 88:0e:c0:73:e1:6f:66:e9:72:47:30:3e:10:e5:0b: - 03:c9:9a:42:00:6c:c5:94:7e:61:c4:8a:df:7f:82: - 1a:0b:59:c4:59:32:77:b3:bc:60:69:56:39:fd:b4: - 06:7b:2c:d6:64:36:d9:bd:48:ed:84:1f:7e:a5:22: - 8f:2a:b8:42:f4:82:b7:d4:53:90:78:4e:2d:1a:fd: - 81:6f:44:d7:3b:01:74:96:42:e0:00:e2:2e:6b:ea: - c5:ee:72:ac:bb:bf:fe:ea:aa:a8:f8:dc:f6:b2:79: - 8a:b6:67 - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Subject Key Identifier: - 9D:C0:67:A6:0C:22:D9:26:F5:45:AB:A6:65:52:11:27:D8:45:AC:63 - X509v3 Basic Constraints: critical - CA:TRUE - X509v3 Key Usage: critical - Certificate Sign, CRL Sign - Signature Algorithm: sha384WithRSAEncryption - b3:57:4d:10:62:4e:3a:e4:ac:ea:b8:1c:af:32:23:c8:b3:49: - 5a:51:9c:76:28:8d:79:aa:57:46:17:d5:f5:52:f6:b7:44:e8: - 08:44:bf:18:84:d2:0b:80:cd:c5:12:fd:00:55:05:61:87:41: - dc:b5:24:9e:3c:c4:d8:c8:fb:70:9e:2f:78:96:83:20:36:de: - 7c:0f:69:13:88:a5:75:36:98:08:a6:c6:df:ac:ce:e3:58:d6: - b7:3e:de:ba:f3:eb:34:40:d8:a2:81:f5:78:3f:2f:d5:a5:fc: - d9:a2:d4:5e:04:0e:17:ad:fe:41:f0:e5:b2:72:fa:44:82:33: - 42:e8:2d:58:f7:56:8c:62:3f:ba:42:b0:9c:0c:5c:7e:2e:65: - 26:5c:53:4f:00:b2:78:7e:a1:0d:99:2d:8d:b8:1d:8e:a2:c4: - b0:fd:60:d0:30:a4:8e:c8:04:62:a9:c4:ed:35:de:7a:97:ed: - 0e:38:5e:92:2f:93:70:a5:a9:9c:6f:a7:7d:13:1d:7e:c6:08: - 48:b1:5e:67:eb:51:08:25:e9:e6:25:6b:52:29:91:9c:d2:39: - 73:08:57:de:99:06:b4:5b:9d:10:06:e1:c2:00:a8:b8:1c:4a: - 02:0a:14:d0:c1:41:ca:fb:8c:35:21:7d:82:38:f2:a9:54:91: - 19:35:93:94:6d:6a:3a:c5:b2:d0:bb:89:86:93:e8:9b:c9:0f: - 3a:a7:7a:b8:a1:f0:78:46:fa:fc:37:2f:e5:8a:84:f3:df:fe: - 04:d9:a1:68:a0:2f:24:e2:09:95:06:d5:95:ca:e1:24:96:eb: - 7c:f6:93:05:bb:ed:73:e9:2d:d1:75:39:d7:e7:24:db:d8:4e: - 5f:43:8f:9e:d0:14:39:bf:55:70:48:99:57:31:b4:9c:ee:4a: - 98:03:96:30:1f:60:06:ee:1b:23:fe:81:60:23:1a:47:62:85: - a5:cc:19:34:80:6f:b3:ac:1a:e3:9f:f0:7b:48:ad:d5:01:d9: - 67:b6:a9:72:93:ea:2d:66:b5:b2:b8:e4:3d:3c:b2:ef:4c:8c: - ea:eb:07:bf:ab:35:9a:55:86:bc:18:a6:b5:a8:5e:b4:83:6c: - 6b:69:40:d3:9f:dc:f1:c3:69:6b:b9:e1:6d:09:f4:f1:aa:50: - 76:0a:7a:7d:7a:17:a1:55:96:42:99:31:09:dd:60:11:8d:05: - 30:7e:e6:8e:46:d1:9d:14:da:c7:17:e4:05:96:8c:c4:24:b5: - 1b:cf:14:07:b2:40:f8:a3:9e:41:86:bc:04:d0:6b:96:c8:2a: - 80:34:fd:bf:ef:06:a3:dd:58:c5:85:3d:3e:8f:fe:9e:29:e0: - b6:b8:09:68:19:1c:18:43 ------BEGIN CERTIFICATE----- -MIIFRjCCAy6gAwIBAgIIbYwURrGmCu4wDQYJKoZIhvcNAQEMBQAwQTELMAkGA1UE -BhMCVVMxFDASBgNVBAoMC0FmZmlybVRydXN0MRwwGgYDVQQDDBNBZmZpcm1UcnVz -dCBQcmVtaXVtMB4XDTEwMDEyOTE0MTAzNloXDTQwMTIzMTE0MTAzNlowQTELMAkG -A1UEBhMCVVMxFDASBgNVBAoMC0FmZmlybVRydXN0MRwwGgYDVQQDDBNBZmZpcm1U -cnVzdCBQcmVtaXVtMIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAxBLf -qV/+Qd3d9Z+K4/as4Tx4mrzY8H96oDMq3I0gW64tb+eT2TZwamjPjlGjhVtnBKAQ -JG9dKILBl1fYSCkTtuG+kU3fhQxTGJoeJKJPj/CihQvL9Cl/0qRY7iZNyaqoe5rZ -+jjeRFcV5fiMyNlI4g0WJx0eyIOFJbe6qlVBzAMiSy2RjYvmia9mx+n/K+k8rNrS -s8PhaJyJ+HoAVt70VZVs+7pk3WKL3wt3MutizCaam7uqYoNMtAZ6MMgpv+0GTZe5 -HMQxK9VfvFMSF5yZVylmd2EhMQcuJUmdGPLu8ytxjLW6OQdJd/zvLpKQBY0tL3d7 -70O/Nbua2Plzpyzy0FfuKE4mX4+QaAkvuPjcBukumj5Rp9EixAqnOEhss/n/fauG -V+O61oV4d7pD6kh/9ti+I20ev9E2bFhc8e6kGVQa9QPSdubhjL08s9NIS+LI+H+S -qHZGnEJlPqQewQcDWkYtuJfzt9WyVSHvutxMAJf7FJUnM7/oQ0dG0giZFmA7mn7S -5u046uwBHjxIVkkJx0w3AJ6IDsBz4W9m6XJHMD4Q5QsDyZpCAGzFlH5hxIrff4Ia -C1nEWTJ3s7xgaVY5/bQGeyzWZDbZvUjthB9+pSKPKrhC9IK31FOQeE4tGv2Bb0TX -OwF0lkLgAOIua+rF7nKsu7/+6qqo+Nz2snmKtmcCAwEAAaNCMEAwHQYDVR0OBBYE -FJ3AZ6YMItkm9UWrpmVSESfYRaxjMA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/ -BAQDAgEGMA0GCSqGSIb3DQEBDAUAA4ICAQCzV00QYk465KzquByvMiPIs0laUZx2 -KI15qldGF9X1Uva3ROgIRL8YhNILgM3FEv0AVQVhh0HctSSePMTYyPtwni94loMg -Nt58D2kTiKV1NpgIpsbfrM7jWNa3Pt668+s0QNiigfV4Py/VpfzZotReBA4Xrf5B -8OWycvpEgjNC6C1Y91aMYj+6QrCcDFx+LmUmXFNPALJ4fqENmS2NuB2OosSw/WDQ -MKSOyARiqcTtNd56l+0OOF6SL5Nwpamcb6d9Ex1+xghIsV5n61EIJenmJWtSKZGc -0jlzCFfemQa0W50QBuHCAKi4HEoCChTQwUHK+4w1IX2COPKpVJEZNZOUbWo6xbLQ -u4mGk+ibyQ86p3q4ofB4Rvr8Ny/lioTz3/4E2aFooC8k4gmVBtWVyuEklut89pMF -u+1z6S3RdTnX5yTb2E5fQ4+e0BQ5v1VwSJlXMbSc7kqYA5YwH2AG7hsj/oFgIxpH -YoWlzBk0gG+zrBrjn/B7SK3VAdlntqlyk+otZrWyuOQ9PLLvTIzq6we/qzWaVYa8 -GKa1qF60g2xraUDTn9zxw2lrueFtCfTxqlB2Cnp9ehehVZZCmTEJ3WARjQUwfuaO -RtGdFNrHF+QFlozEJLUbzxQHskD4o55BhrwE0GuWyCqANP2/7waj3VjFhT0+j/6e -KeC2uAloGRwYQw== ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: - 74:97:25:8a:c7:3f:7a:54 - Signature Algorithm: ecdsa-with-SHA384 - Issuer: C=US, O=AffirmTrust, CN=AffirmTrust Premium ECC - Validity - Not Before: Jan 29 14:20:24 2010 GMT - Not After : Dec 31 14:20:24 2040 GMT - Subject: C=US, O=AffirmTrust, CN=AffirmTrust Premium ECC - Subject Public Key Info: - Public Key Algorithm: id-ecPublicKey - Public-Key: (384 bit) - pub: - 04:0d:30:5e:1b:15:9d:03:d0:a1:79:35:b7:3a:3c: - 92:7a:ca:15:1c:cd:62:f3:9c:26:5c:07:3d:e5:54: - fa:a3:d6:cc:12:ea:f4:14:5f:e8:8e:19:ab:2f:2e: - 48:e6:ac:18:43:78:ac:d0:37:c3:bd:b2:cd:2c:e6: - 47:e2:1a:e6:63:b8:3d:2e:2f:78:c4:4f:db:f4:0f: - a4:68:4c:55:72:6b:95:1d:4e:18:42:95:78:cc:37: - 3c:91:e2:9b:65:2b:29 - ASN1 OID: secp384r1 - X509v3 extensions: - X509v3 Subject Key Identifier: - 9A:AF:29:7A:C0:11:35:35:26:51:30:00:C3:6A:FE:40:D5:AE:D6:3C - X509v3 Basic Constraints: critical - CA:TRUE - X509v3 Key Usage: critical - Certificate Sign, CRL Sign - Signature Algorithm: ecdsa-with-SHA384 - 30:64:02:30:17:09:f3:87:88:50:5a:af:c8:c0:42:bf:47:5f: - f5:6c:6a:86:e0:c4:27:74:e4:38:53:d7:05:7f:1b:34:e3:c6: - 2f:b3:ca:09:3c:37:9d:d7:e7:b8:46:f1:fd:a1:e2:71:02:30: - 42:59:87:43:d4:51:df:ba:d3:09:32:5a:ce:88:7e:57:3d:9c: - 5f:42:6b:f5:07:2d:b5:f0:82:93:f9:59:6f:ae:64:fa:58:e5: - 8b:1e:e3:63:be:b5:81:cd:6f:02:8c:79 ------BEGIN CERTIFICATE----- -MIIB/jCCAYWgAwIBAgIIdJclisc/elQwCgYIKoZIzj0EAwMwRTELMAkGA1UEBhMC -VVMxFDASBgNVBAoMC0FmZmlybVRydXN0MSAwHgYDVQQDDBdBZmZpcm1UcnVzdCBQ -cmVtaXVtIEVDQzAeFw0xMDAxMjkxNDIwMjRaFw00MDEyMzExNDIwMjRaMEUxCzAJ -BgNVBAYTAlVTMRQwEgYDVQQKDAtBZmZpcm1UcnVzdDEgMB4GA1UEAwwXQWZmaXJt -VHJ1c3QgUHJlbWl1bSBFQ0MwdjAQBgcqhkjOPQIBBgUrgQQAIgNiAAQNMF4bFZ0D -0KF5Nbc6PJJ6yhUczWLznCZcBz3lVPqj1swS6vQUX+iOGasvLkjmrBhDeKzQN8O9 -ss0s5kfiGuZjuD0uL3jET9v0D6RoTFVya5UdThhClXjMNzyR4ptlKymjQjBAMB0G -A1UdDgQWBBSaryl6wBE1NSZRMADDav5A1a7WPDAPBgNVHRMBAf8EBTADAQH/MA4G -A1UdDwEB/wQEAwIBBjAKBggqhkjOPQQDAwNnADBkAjAXCfOHiFBar8jAQr9HX/Vs -aobgxCd05DhT1wV/GzTjxi+zygk8N53X57hG8f2h4nECMEJZh0PUUd+60wkyWs6I -flc9nF9Ca/UHLbXwgpP5WW+uZPpY5Yse42O+tYHNbwKMeQ== ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: - 06:6c:9f:cf:99:bf:8c:0a:39:e2:f0:78:8a:43:e6:96:36:5b:ca - Signature Algorithm: sha256WithRSAEncryption - Issuer: C=US, O=Amazon, CN=Amazon Root CA 1 - Validity - Not Before: May 26 00:00:00 2015 GMT - Not After : Jan 17 00:00:00 2038 GMT - Subject: C=US, O=Amazon, CN=Amazon Root CA 1 - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (2048 bit) - Modulus: - 00:b2:78:80:71:ca:78:d5:e3:71:af:47:80:50:74: - 7d:6e:d8:d7:88:76:f4:99:68:f7:58:21:60:f9:74: - 84:01:2f:ac:02:2d:86:d3:a0:43:7a:4e:b2:a4:d0: - 36:ba:01:be:8d:db:48:c8:07:17:36:4c:f4:ee:88: - 23:c7:3e:eb:37:f5:b5:19:f8:49:68:b0:de:d7:b9: - 76:38:1d:61:9e:a4:fe:82:36:a5:e5:4a:56:e4:45: - e1:f9:fd:b4:16:fa:74:da:9c:9b:35:39:2f:fa:b0: - 20:50:06:6c:7a:d0:80:b2:a6:f9:af:ec:47:19:8f: - 50:38:07:dc:a2:87:39:58:f8:ba:d5:a9:f9:48:67: - 30:96:ee:94:78:5e:6f:89:a3:51:c0:30:86:66:a1: - 45:66:ba:54:eb:a3:c3:91:f9:48:dc:ff:d1:e8:30: - 2d:7d:2d:74:70:35:d7:88:24:f7:9e:c4:59:6e:bb: - 73:87:17:f2:32:46:28:b8:43:fa:b7:1d:aa:ca:b4: - f2:9f:24:0e:2d:4b:f7:71:5c:5e:69:ff:ea:95:02: - cb:38:8a:ae:50:38:6f:db:fb:2d:62:1b:c5:c7:1e: - 54:e1:77:e0:67:c8:0f:9c:87:23:d6:3f:40:20:7f: - 20:80:c4:80:4c:3e:3b:24:26:8e:04:ae:6c:9a:c8: - aa:0d - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Basic Constraints: critical - CA:TRUE - X509v3 Key Usage: critical - Digital Signature, Certificate Sign, CRL Sign - X509v3 Subject Key Identifier: - 84:18:CC:85:34:EC:BC:0C:94:94:2E:08:59:9C:C7:B2:10:4E:0A:08 - Signature Algorithm: sha256WithRSAEncryption - 98:f2:37:5a:41:90:a1:1a:c5:76:51:28:20:36:23:0e:ae:e6: - 28:bb:aa:f8:94:ae:48:a4:30:7f:1b:fc:24:8d:4b:b4:c8:a1: - 97:f6:b6:f1:7a:70:c8:53:93:cc:08:28:e3:98:25:cf:23:a4: - f9:de:21:d3:7c:85:09:ad:4e:9a:75:3a:c2:0b:6a:89:78:76: - 44:47:18:65:6c:8d:41:8e:3b:7f:9a:cb:f4:b5:a7:50:d7:05: - 2c:37:e8:03:4b:ad:e9:61:a0:02:6e:f5:f2:f0:c5:b2:ed:5b: - b7:dc:fa:94:5c:77:9e:13:a5:7f:52:ad:95:f2:f8:93:3b:de: - 8b:5c:5b:ca:5a:52:5b:60:af:14:f7:4b:ef:a3:fb:9f:40:95: - 6d:31:54:fc:42:d3:c7:46:1f:23:ad:d9:0f:48:70:9a:d9:75: - 78:71:d1:72:43:34:75:6e:57:59:c2:02:5c:26:60:29:cf:23: - 19:16:8e:88:43:a5:d4:e4:cb:08:fb:23:11:43:e8:43:29:72: - 62:a1:a9:5d:5e:08:d4:90:ae:b8:d8:ce:14:c2:d0:55:f2:86: - f6:c4:93:43:77:66:61:c0:b9:e8:41:d7:97:78:60:03:6e:4a: - 72:ae:a5:d1:7d:ba:10:9e:86:6c:1b:8a:b9:59:33:f8:eb:c4: - 90:be:f1:b9 ------BEGIN CERTIFICATE----- -MIIDQTCCAimgAwIBAgITBmyfz5m/jAo54vB4ikPmljZbyjANBgkqhkiG9w0BAQsF -ADA5MQswCQYDVQQGEwJVUzEPMA0GA1UEChMGQW1hem9uMRkwFwYDVQQDExBBbWF6 -b24gUm9vdCBDQSAxMB4XDTE1MDUyNjAwMDAwMFoXDTM4MDExNzAwMDAwMFowOTEL -MAkGA1UEBhMCVVMxDzANBgNVBAoTBkFtYXpvbjEZMBcGA1UEAxMQQW1hem9uIFJv -b3QgQ0EgMTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALJ4gHHKeNXj -ca9HgFB0fW7Y14h29Jlo91ghYPl0hAEvrAIthtOgQ3pOsqTQNroBvo3bSMgHFzZM -9O6II8c+6zf1tRn4SWiw3te5djgdYZ6k/oI2peVKVuRF4fn9tBb6dNqcmzU5L/qw -IFAGbHrQgLKm+a/sRxmPUDgH3KKHOVj4utWp+UhnMJbulHheb4mjUcAwhmahRWa6 -VOujw5H5SNz/0egwLX0tdHA114gk957EWW67c4cX8jJGKLhD+rcdqsq08p8kDi1L -93FcXmn/6pUCyziKrlA4b9v7LWIbxcceVOF34GfID5yHI9Y/QCB/IIDEgEw+OyQm -jgSubJrIqg0CAwEAAaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMC -AYYwHQYDVR0OBBYEFIQYzIU07LwMlJQuCFmcx7IQTgoIMA0GCSqGSIb3DQEBCwUA -A4IBAQCY8jdaQZChGsV2USggNiMOruYou6r4lK5IpDB/G/wkjUu0yKGX9rbxenDI -U5PMCCjjmCXPI6T53iHTfIUJrU6adTrCC2qJeHZERxhlbI1Bjjt/msv0tadQ1wUs -N+gDS63pYaACbvXy8MWy7Vu33PqUXHeeE6V/Uq2V8viTO96LXFvKWlJbYK8U90vv -o/ufQJVtMVT8QtPHRh8jrdkPSHCa2XV4cdFyQzR1bldZwgJcJmApzyMZFo6IQ6XU -5MsI+yMRQ+hDKXJioaldXgjUkK642M4UwtBV8ob2xJNDd2ZhwLnoQdeXeGADbkpy -rqXRfboQnoZsG4q5WTP468SQvvG5 ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: - 06:6c:9f:d2:96:35:86:9f:0a:0f:e5:86:78:f8:5b:26:bb:8a:37 - Signature Algorithm: sha384WithRSAEncryption - Issuer: C=US, O=Amazon, CN=Amazon Root CA 2 - Validity - Not Before: May 26 00:00:00 2015 GMT - Not After : May 26 00:00:00 2040 GMT - Subject: C=US, O=Amazon, CN=Amazon Root CA 2 - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (4096 bit) - Modulus: - 00:ad:96:9f:2d:9c:4a:4c:4a:81:79:51:99:ec:8a: - cb:6b:60:51:13:bc:4d:6d:06:fc:b0:08:8d:dd:19: - 10:6a:c7:26:0c:35:d8:c0:6f:20:84:e9:94:b1:9b: - 85:03:c3:5b:db:4a:e8:c8:f8:90:76:d9:5b:4f:e3: - 4c:e8:06:36:4d:cc:9a:ac:3d:0c:90:2b:92:d4:06: - 19:60:ac:37:44:79:85:81:82:ad:5a:37:e0:0d:cc: - 9d:a6:4c:52:76:ea:43:9d:b7:04:d1:50:f6:55:e0: - d5:d2:a6:49:85:e9:37:e9:ca:7e:ae:5c:95:4d:48: - 9a:3f:ae:20:5a:6d:88:95:d9:34:b8:52:1a:43:90: - b0:bf:6c:05:b9:b6:78:b7:ea:d0:e4:3a:3c:12:53: - 62:ff:4a:f2:7b:be:35:05:a9:12:34:e3:f3:64:74: - 62:2c:3d:00:49:5a:28:fe:32:44:bb:87:dd:65:27: - 02:71:3b:da:4a:f7:1f:da:cd:f7:21:55:90:4f:0f: - ec:ae:82:e1:9f:6b:d9:45:d3:bb:f0:5f:87:ed:3c: - 2c:39:86:da:3f:de:ec:72:55:eb:79:a3:ad:db:dd: - 7c:b0:ba:1c:ce:fc:de:4f:35:76:cf:0f:f8:78:1f: - 6a:36:51:46:27:61:5b:e9:9e:cf:f0:a2:55:7d:7c: - 25:8a:6f:2f:b4:c5:cf:84:2e:2b:fd:0d:51:10:6c: - fb:5f:1b:bc:1b:7e:c5:ae:3b:98:01:31:92:ff:0b: - 57:f4:9a:b2:b9:57:e9:ab:ef:0d:76:d1:f0:ee:f4: - ce:86:a7:e0:6e:e9:b4:69:a1:df:69:f6:33:c6:69: - 2e:97:13:9e:a5:87:b0:57:10:81:37:c9:53:b3:bb: - 7f:f6:92:d1:9c:d0:18:f4:92:6e:da:83:4f:a6:63: - 99:4c:a5:fb:5e:ef:21:64:7a:20:5f:6c:64:85:15: - cb:37:e9:62:0c:0b:2a:16:dc:01:2e:32:da:3e:4b: - f5:9e:3a:f6:17:40:94:ef:9e:91:08:86:fa:be:63: - a8:5a:33:ec:cb:74:43:95:f9:6c:69:52:36:c7:29: - 6f:fc:55:03:5c:1f:fb:9f:bd:47:eb:e7:49:47:95: - 0b:4e:89:22:09:49:e0:f5:61:1e:f1:bf:2e:8a:72: - 6e:80:59:ff:57:3a:f9:75:32:a3:4e:5f:ec:ed:28: - 62:d9:4d:73:f2:cc:81:17:60:ed:cd:eb:dc:db:a7: - ca:c5:7e:02:bd:f2:54:08:54:fd:b4:2d:09:2c:17: - 54:4a:98:d1:54:e1:51:67:08:d2:ed:6e:7e:6f:3f: - d2:2d:81:59:29:66:cb:90:39:95:11:1e:74:27:fe: - dd:eb:af - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Basic Constraints: critical - CA:TRUE - X509v3 Key Usage: critical - Digital Signature, Certificate Sign, CRL Sign - X509v3 Subject Key Identifier: - B0:0C:F0:4C:30:F4:05:58:02:48:FD:33:E5:52:AF:4B:84:E3:66:52 - Signature Algorithm: sha384WithRSAEncryption - aa:a8:80:8f:0e:78:a3:e0:a2:d4:cd:e6:f5:98:7a:3b:ea:00: - 03:b0:97:0e:93:bc:5a:a8:f6:2c:8c:72:87:a9:b1:fc:7f:73: - fd:63:71:78:a5:87:59:cf:30:e1:0d:10:b2:13:5a:6d:82:f5: - 6a:e6:80:9f:a0:05:0b:68:e4:47:6b:c7:6a:df:b6:fd:77:32: - 72:e5:18:fa:09:f4:a0:93:2c:5d:d2:8c:75:85:76:65:90:0c: - 03:79:b7:31:23:63:ad:78:83:09:86:68:84:ca:ff:f9:cf:26: - 9a:92:79:e7:cd:4b:c5:e7:61:a7:17:cb:f3:a9:12:93:93:6b: - a7:e8:2f:53:92:c4:60:58:b0:cc:02:51:18:5b:85:8d:62:59: - 63:b6:ad:b4:de:9a:fb:26:f7:00:27:c0:5d:55:37:74:99:c9: - 50:7f:e3:59:2e:44:e3:2c:25:ee:ec:4c:32:77:b4:9f:1a:e9: - 4b:5d:20:c5:da:fd:1c:87:16:c6:43:e8:d4:bb:26:9a:45:70: - 5e:a9:0b:37:53:e2:46:7b:27:fd:e0:46:f2:89:b7:cc:42:b6: - cb:28:26:6e:d9:a5:c9:3a:c8:41:13:60:f7:50:8c:15:ae:b2: - 6d:1a:15:1a:57:78:e6:92:2a:d9:65:90:82:3f:6c:02:af:ae: - 12:3a:27:96:36:04:d7:1d:a2:80:63:a9:9b:f1:e5:ba:b4:7c: - 14:b0:4e:c9:b1:1f:74:5f:38:f6:51:ea:9b:fa:2c:a2:11:d4: - a9:2d:27:1a:45:b1:af:b2:4e:71:0d:c0:58:46:d6:69:06:cb: - 53:cb:b3:fe:6b:41:cd:41:7e:7d:4c:0f:7c:72:79:7a:59:cd: - 5e:4a:0e:ac:9b:a9:98:73:79:7c:b4:f4:cc:b9:b8:07:0c:b2: - 74:5c:b8:c7:6f:88:a1:90:a7:f4:aa:f9:bf:67:3a:f4:1a:15: - 62:1e:b7:9f:be:3d:b1:29:af:67:a1:12:f2:58:10:19:53:03: - 30:1b:b8:1a:89:f6:9c:bd:97:03:8e:a3:09:f3:1d:8b:21:f1: - b4:df:e4:1c:d1:9f:65:02:06:ea:5c:d6:13:b3:84:ef:a2:a5: - 5c:8c:77:29:a7:68:c0:6b:ae:40:d2:a8:b4:ea:cd:f0:8d:4b: - 38:9c:19:9a:1b:28:54:b8:89:90:ef:ca:75:81:3e:1e:f2:64: - 24:c7:18:af:4e:ff:47:9e:07:f6:35:65:a4:d3:0a:56:ff:f5: - 17:64:6c:ef:a8:22:25:49:93:b6:df:00:17:da:58:7e:5d:ee: - c5:1b:b0:d1:d1:5f:21:10:c7:f9:f3:ba:02:0a:27:07:c5:f1: - d6:c7:d3:e0:fb:09:60:6c ------BEGIN CERTIFICATE----- -MIIFQTCCAymgAwIBAgITBmyf0pY1hp8KD+WGePhbJruKNzANBgkqhkiG9w0BAQwF -ADA5MQswCQYDVQQGEwJVUzEPMA0GA1UEChMGQW1hem9uMRkwFwYDVQQDExBBbWF6 -b24gUm9vdCBDQSAyMB4XDTE1MDUyNjAwMDAwMFoXDTQwMDUyNjAwMDAwMFowOTEL -MAkGA1UEBhMCVVMxDzANBgNVBAoTBkFtYXpvbjEZMBcGA1UEAxMQQW1hem9uIFJv -b3QgQ0EgMjCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAK2Wny2cSkxK -gXlRmeyKy2tgURO8TW0G/LAIjd0ZEGrHJgw12MBvIITplLGbhQPDW9tK6Mj4kHbZ -W0/jTOgGNk3Mmqw9DJArktQGGWCsN0R5hYGCrVo34A3MnaZMUnbqQ523BNFQ9lXg -1dKmSYXpN+nKfq5clU1Imj+uIFptiJXZNLhSGkOQsL9sBbm2eLfq0OQ6PBJTYv9K -8nu+NQWpEjTj82R0Yiw9AElaKP4yRLuH3WUnAnE72kr3H9rN9yFVkE8P7K6C4Z9r -2UXTu/Bfh+08LDmG2j/e7HJV63mjrdvdfLC6HM783k81ds8P+HgfajZRRidhW+me -z/CiVX18JYpvL7TFz4QuK/0NURBs+18bvBt+xa47mAExkv8LV/SasrlX6avvDXbR -8O70zoan4G7ptGmh32n2M8ZpLpcTnqWHsFcQgTfJU7O7f/aS0ZzQGPSSbtqDT6Zj -mUyl+17vIWR6IF9sZIUVyzfpYgwLKhbcAS4y2j5L9Z469hdAlO+ekQiG+r5jqFoz -7Mt0Q5X5bGlSNscpb/xVA1wf+5+9R+vnSUeVC06JIglJ4PVhHvG/LopyboBZ/1c6 -+XUyo05f7O0oYtlNc/LMgRdg7c3r3NunysV+Ar3yVAhU/bQtCSwXVEqY0VThUWcI -0u1ufm8/0i2BWSlmy5A5lREedCf+3euvAgMBAAGjQjBAMA8GA1UdEwEB/wQFMAMB -Af8wDgYDVR0PAQH/BAQDAgGGMB0GA1UdDgQWBBSwDPBMMPQFWAJI/TPlUq9LhONm -UjANBgkqhkiG9w0BAQwFAAOCAgEAqqiAjw54o+Ci1M3m9Zh6O+oAA7CXDpO8Wqj2 -LIxyh6mx/H9z/WNxeKWHWc8w4Q0QshNabYL1auaAn6AFC2jkR2vHat+2/XcycuUY -+gn0oJMsXdKMdYV2ZZAMA3m3MSNjrXiDCYZohMr/+c8mmpJ5581LxedhpxfL86kS -k5Nrp+gvU5LEYFiwzAJRGFuFjWJZY7attN6a+yb3ACfAXVU3dJnJUH/jWS5E4ywl -7uxMMne0nxrpS10gxdr9HIcWxkPo1LsmmkVwXqkLN1PiRnsn/eBG8om3zEK2yygm -btmlyTrIQRNg91CMFa6ybRoVGld45pIq2WWQgj9sAq+uEjonljYE1x2igGOpm/Hl -urR8FLBOybEfdF849lHqm/osohHUqS0nGkWxr7JOcQ3AWEbWaQbLU8uz/mtBzUF+ -fUwPfHJ5elnNXkoOrJupmHN5fLT0zLm4BwyydFy4x2+IoZCn9Kr5v2c69BoVYh63 -n749sSmvZ6ES8lgQGVMDMBu4Gon2nL2XA46jCfMdiyHxtN/kHNGfZQIG6lzWE7OE -76KlXIx3KadowGuuQNKotOrN8I1LOJwZmhsoVLiJkO/KdYE+HvJkJMcYr07/R54H -9jVlpNMKVv/1F2Rs76giJUmTtt8AF9pYfl3uxRuw0dFfIRDH+fO6AgonB8Xx1sfT -4PsJYGw= ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: - 06:6c:9f:d5:74:97:36:66:3f:3b:0b:9a:d9:e8:9e:76:03:f2:4a - Signature Algorithm: ecdsa-with-SHA256 - Issuer: C=US, O=Amazon, CN=Amazon Root CA 3 - Validity - Not Before: May 26 00:00:00 2015 GMT - Not After : May 26 00:00:00 2040 GMT - Subject: C=US, O=Amazon, CN=Amazon Root CA 3 - Subject Public Key Info: - Public Key Algorithm: id-ecPublicKey - Public-Key: (256 bit) - pub: - 04:29:97:a7:c6:41:7f:c0:0d:9b:e8:01:1b:56:c6: - f2:52:a5:ba:2d:b2:12:e8:d2:2e:d7:fa:c9:c5:d8: - aa:6d:1f:73:81:3b:3b:98:6b:39:7c:33:a5:c5:4e: - 86:8e:80:17:68:62:45:57:7d:44:58:1d:b3:37:e5: - 67:08:eb:66:de - ASN1 OID: prime256v1 - X509v3 extensions: - X509v3 Basic Constraints: critical - CA:TRUE - X509v3 Key Usage: critical - Digital Signature, Certificate Sign, CRL Sign - X509v3 Subject Key Identifier: - AB:B6:DB:D7:06:9E:37:AC:30:86:07:91:70:C7:9C:C4:19:B1:78:C0 - Signature Algorithm: ecdsa-with-SHA256 - 30:46:02:21:00:e0:85:92:a3:17:b7:8d:f9:2b:06:a5:93:ac: - 1a:98:68:61:72:fa:e1:a1:d0:fb:1c:78:60:a6:43:99:c5:b8: - c4:02:21:00:9c:02:ef:f1:94:9c:b3:96:f9:eb:c6:2a:f8:b6: - 2c:fe:3a:90:14:16:d7:8c:63:24:48:1c:df:30:7d:d5:68:3b ------BEGIN CERTIFICATE----- -MIIBtjCCAVugAwIBAgITBmyf1XSXNmY/Owua2eiedgPySjAKBggqhkjOPQQDAjA5 -MQswCQYDVQQGEwJVUzEPMA0GA1UEChMGQW1hem9uMRkwFwYDVQQDExBBbWF6b24g -Um9vdCBDQSAzMB4XDTE1MDUyNjAwMDAwMFoXDTQwMDUyNjAwMDAwMFowOTELMAkG -A1UEBhMCVVMxDzANBgNVBAoTBkFtYXpvbjEZMBcGA1UEAxMQQW1hem9uIFJvb3Qg -Q0EgMzBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABCmXp8ZBf8ANm+gBG1bG8lKl -ui2yEujSLtf6ycXYqm0fc4E7O5hrOXwzpcVOho6AF2hiRVd9RFgdszflZwjrZt6j -QjBAMA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgGGMB0GA1UdDgQWBBSr -ttvXBp43rDCGB5Fwx5zEGbF4wDAKBggqhkjOPQQDAgNJADBGAiEA4IWSoxe3jfkr -BqWTrBqYaGFy+uGh0PsceGCmQ5nFuMQCIQCcAu/xlJyzlvnrxir4tiz+OpAUFteM -YyRIHN8wfdVoOw== ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: - 06:6c:9f:d7:c1:bb:10:4c:29:43:e5:71:7b:7b:2c:c8:1a:c1:0e - Signature Algorithm: ecdsa-with-SHA384 - Issuer: C=US, O=Amazon, CN=Amazon Root CA 4 - Validity - Not Before: May 26 00:00:00 2015 GMT - Not After : May 26 00:00:00 2040 GMT - Subject: C=US, O=Amazon, CN=Amazon Root CA 4 - Subject Public Key Info: - Public Key Algorithm: id-ecPublicKey - Public-Key: (384 bit) - pub: - 04:d2:ab:8a:37:4f:a3:53:0d:fe:c1:8a:7b:4b:a8: - 7b:46:4b:63:b0:62:f6:2d:1b:db:08:71:21:d2:00: - e8:63:bd:9a:27:fb:f0:39:6e:5d:ea:3d:a5:c9:81: - aa:a3:5b:20:98:45:5d:16:db:fd:e8:10:6d:e3:9c: - e0:e3:bd:5f:84:62:f3:70:64:33:a0:cb:24:2f:70: - ba:88:a1:2a:a0:75:f8:81:ae:62:06:c4:81:db:39: - 6e:29:b0:1e:fa:2e:5c - ASN1 OID: secp384r1 - X509v3 extensions: - X509v3 Basic Constraints: critical - CA:TRUE - X509v3 Key Usage: critical - Digital Signature, Certificate Sign, CRL Sign - X509v3 Subject Key Identifier: - D3:EC:C7:3A:65:6E:CC:E1:DA:76:9A:56:FB:9C:F3:86:6D:57:E5:81 - Signature Algorithm: ecdsa-with-SHA384 - 30:65:02:30:3a:8b:21:f1:bd:7e:11:ad:d0:ef:58:96:2f:d6: - eb:9d:7e:90:8d:2b:cf:66:55:c3:2c:e3:28:a9:70:0a:47:0e: - f0:37:59:12:ff:2d:99:94:28:4e:2a:4f:35:4d:33:5a:02:31: - 00:ea:75:00:4e:3b:c4:3a:94:12:91:c9:58:46:9d:21:13:72: - a7:88:9c:8a:e4:4c:4a:db:96:d4:ac:8b:6b:6b:49:12:53:33: - ad:d7:e4:be:24:fc:b5:0a:76:d4:a5:bc:10 ------BEGIN CERTIFICATE----- -MIIB8jCCAXigAwIBAgITBmyf18G7EEwpQ+Vxe3ssyBrBDjAKBggqhkjOPQQDAzA5 -MQswCQYDVQQGEwJVUzEPMA0GA1UEChMGQW1hem9uMRkwFwYDVQQDExBBbWF6b24g -Um9vdCBDQSA0MB4XDTE1MDUyNjAwMDAwMFoXDTQwMDUyNjAwMDAwMFowOTELMAkG -A1UEBhMCVVMxDzANBgNVBAoTBkFtYXpvbjEZMBcGA1UEAxMQQW1hem9uIFJvb3Qg -Q0EgNDB2MBAGByqGSM49AgEGBSuBBAAiA2IABNKrijdPo1MN/sGKe0uoe0ZLY7Bi -9i0b2whxIdIA6GO9mif78DluXeo9pcmBqqNbIJhFXRbb/egQbeOc4OO9X4Ri83Bk -M6DLJC9wuoihKqB1+IGuYgbEgds5bimwHvouXKNCMEAwDwYDVR0TAQH/BAUwAwEB -/zAOBgNVHQ8BAf8EBAMCAYYwHQYDVR0OBBYEFNPsxzplbszh2naaVvuc84ZtV+WB -MAoGCCqGSM49BAMDA2gAMGUCMDqLIfG9fhGt0O9Yli/W651+kI0rz2ZVwyzjKKlw -CkcO8DdZEv8tmZQoTipPNU0zWgIxAOp1AE47xDqUEpHJWEadIRNyp4iciuRMStuW -1KyLa2tJElMzrdfkviT8tQp21KW8EA== ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: - 5c:33:cb:62:2c:5f:b3:32 - Signature Algorithm: sha256WithRSAEncryption - Issuer: CN=Atos TrustedRoot 2011, O=Atos, C=DE - Validity - Not Before: Jul 7 14:58:30 2011 GMT - Not After : Dec 31 23:59:59 2030 GMT - Subject: CN=Atos TrustedRoot 2011, O=Atos, C=DE - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (2048 bit) - Modulus: - 00:95:85:3b:97:6f:2a:3b:2e:3b:cf:a6:f3:29:35: - be:cf:18:ac:3e:aa:d9:f8:4d:a0:3e:1a:47:b9:bc: - 9a:df:f2:fe:cc:3e:47:e8:7a:96:c2:24:8e:35:f4: - a9:0c:fc:82:fd:6d:c1:72:62:27:bd:ea:6b:eb:e7: - 8a:cc:54:3e:90:50:cf:80:d4:95:fb:e8:b5:82:d4: - 14:c5:b6:a9:55:25:57:db:b1:50:f6:b0:60:64:59: - 7a:69:cf:03:b7:6f:0d:be:ca:3e:6f:74:72:ea:aa: - 30:2a:73:62:be:49:91:61:c8:11:fe:0e:03:2a:f7: - 6a:20:dc:02:15:0d:5e:15:6a:fc:e3:82:c1:b5:c5: - 9d:64:09:6c:a3:59:98:07:27:c7:1b:96:2b:61:74: - 71:6c:43:f1:f7:35:89:10:e0:9e:ec:55:a1:37:22: - a2:87:04:05:2c:47:7d:b4:1c:b9:62:29:66:28:ca: - b7:e1:93:f5:a4:94:03:99:b9:70:85:b5:e6:48:ea: - 8d:50:fc:d9:de:cc:6f:07:0e:dd:0b:72:9d:80:30: - 16:07:95:3f:28:0e:fd:c5:75:4f:53:d6:74:9a:b4: - 24:2e:8e:02:91:cf:76:c5:9b:1e:55:74:9c:78:21: - b1:f0:2d:f1:0b:9f:c2:d5:96:18:1f:f0:54:22:7a: - 8c:07 - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Subject Key Identifier: - A7:A5:06:B1:2C:A6:09:60:EE:D1:97:E9:70:AE:BC:3B:19:6C:DB:21 - X509v3 Basic Constraints: critical - CA:TRUE - X509v3 Authority Key Identifier: - keyid:A7:A5:06:B1:2C:A6:09:60:EE:D1:97:E9:70:AE:BC:3B:19:6C:DB:21 - - X509v3 Certificate Policies: - Policy: 1.3.6.1.4.1.6189.3.4.1.1 - - X509v3 Key Usage: critical - Digital Signature, Certificate Sign, CRL Sign - Signature Algorithm: sha256WithRSAEncryption - 26:77:34:db:94:48:86:2a:41:9d:2c:3e:06:90:60:c4:8c:ac: - 0b:54:b8:1f:b9:7b:d3:07:39:e4:fa:3e:7b:b2:3d:4e:ed:9f: - 23:bd:97:f3:6b:5c:ef:ee:fd:40:a6:df:a1:93:a1:0a:86:ac: - ef:20:d0:79:01:bd:78:f7:19:d8:24:31:34:04:01:a6:ba:15: - 9a:c3:27:dc:d8:4f:0f:cc:18:63:ff:99:0f:0e:91:6b:75:16: - e1:21:fc:d8:26:c7:47:b7:a6:cf:58:72:71:7e:ba:e1:4d:95: - 47:3b:c9:af:6d:a1:b4:c1:ec:89:f6:b4:0f:38:b5:e2:64:dc: - 25:cf:a6:db:eb:9a:5c:99:a1:c5:08:de:fd:e6:da:d5:d6:5a: - 45:0c:c4:b7:c2:b5:14:ef:b4:11:ff:0e:15:b5:f5:f5:db:c6: - bd:eb:5a:a7:f0:56:22:a9:3c:65:54:c6:15:a8:bd:86:9e:cd: - 83:96:68:7a:71:81:89:e1:0b:e1:ea:11:1b:68:08:cc:69:9e: - ec:9e:41:9e:44:32:26:7a:e2:87:0a:71:3d:eb:e4:5a:a4:d2: - db:c5:cd:c6:de:60:7f:b9:f3:4f:44:92:ef:2a:b7:18:3e:a7: - 19:d9:0b:7d:b1:37:41:42:b0:ba:60:1d:f2:fe:09:11:b0:f0: - 87:7b:a7:9d ------BEGIN CERTIFICATE----- -MIIDdzCCAl+gAwIBAgIIXDPLYixfszIwDQYJKoZIhvcNAQELBQAwPDEeMBwGA1UE -AwwVQXRvcyBUcnVzdGVkUm9vdCAyMDExMQ0wCwYDVQQKDARBdG9zMQswCQYDVQQG -EwJERTAeFw0xMTA3MDcxNDU4MzBaFw0zMDEyMzEyMzU5NTlaMDwxHjAcBgNVBAMM -FUF0b3MgVHJ1c3RlZFJvb3QgMjAxMTENMAsGA1UECgwEQXRvczELMAkGA1UEBhMC -REUwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCVhTuXbyo7LjvPpvMp -Nb7PGKw+qtn4TaA+Gke5vJrf8v7MPkfoepbCJI419KkM/IL9bcFyYie96mvr54rM -VD6QUM+A1JX76LWC1BTFtqlVJVfbsVD2sGBkWXppzwO3bw2+yj5vdHLqqjAqc2K+ -SZFhyBH+DgMq92og3AIVDV4VavzjgsG1xZ1kCWyjWZgHJ8cblithdHFsQ/H3NYkQ -4J7sVaE3IqKHBAUsR320HLliKWYoyrfhk/WklAOZuXCFteZI6o1Q/NnezG8HDt0L -cp2AMBYHlT8oDv3FdU9T1nSatCQujgKRz3bFmx5VdJx4IbHwLfELn8LVlhgf8FQi -eowHAgMBAAGjfTB7MB0GA1UdDgQWBBSnpQaxLKYJYO7Rl+lwrrw7GWzbITAPBgNV -HRMBAf8EBTADAQH/MB8GA1UdIwQYMBaAFKelBrEspglg7tGX6XCuvDsZbNshMBgG -A1UdIAQRMA8wDQYLKwYBBAGwLQMEAQEwDgYDVR0PAQH/BAQDAgGGMA0GCSqGSIb3 -DQEBCwUAA4IBAQAmdzTblEiGKkGdLD4GkGDEjKwLVLgfuXvTBznk+j57sj1O7Z8j -vZfza1zv7v1Apt+hk6EKhqzvINB5Ab149xnYJDE0BAGmuhWawyfc2E8PzBhj/5kP -DpFrdRbhIfzYJsdHt6bPWHJxfrrhTZVHO8mvbaG0weyJ9rQPOLXiZNwlz6bb65pc -maHFCN795trV1lpFDMS3wrUU77QR/w4VtfX128a961qn8FYiqTxlVMYVqL2Gns2D -lmh6cYGJ4Qvh6hEbaAjMaZ7snkGeRDImeuKHCnE96+RapNLbxc3G3mB/ufNPRJLv -KrcYPqcZ2Qt9sTdBQrC6YB3y/gkRsPCHe6ed ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: - 53:ec:3b:ee:fb:b2:48:5f - Signature Algorithm: sha1WithRSAEncryption - Issuer: C=ES, CN=Autoridad de Certificacion Firmaprofesional CIF A62634068 - Validity - Not Before: May 20 08:38:15 2009 GMT - Not After : Dec 31 08:38:15 2030 GMT - Subject: C=ES, CN=Autoridad de Certificacion Firmaprofesional CIF A62634068 - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (4096 bit) - Modulus: - 00:ca:96:6b:8e:ea:f8:fb:f1:a2:35:e0:7f:4c:da: - e0:c3:52:d7:7d:b6:10:c8:02:5e:b3:43:2a:c4:4f: - 6a:b2:ca:1c:5d:28:9a:78:11:1a:69:59:57:af:b5: - 20:42:e4:8b:0f:e6:df:5b:a6:03:92:2f:f5:11:e4: - 62:d7:32:71:38:d9:04:0c:71:ab:3d:51:7e:0f:07: - df:63:05:5c:e9:bf:94:6f:c1:29:82:c0:b4:da:51: - b0:c1:3c:bb:ad:37:4a:5c:ca:f1:4b:36:0e:24:ab: - bf:c3:84:77:fd:a8:50:f4:b1:e7:c6:2f:d2:2d:59: - 8d:7a:0a:4e:96:69:52:02:aa:36:98:ec:fc:fa:14: - 83:0c:37:1f:c9:92:37:7f:d7:81:2d:e5:c4:b9:e0: - 3e:34:fe:67:f4:3e:66:d1:d3:f4:40:cf:5e:62:34: - 0f:70:06:3e:20:18:5a:ce:f7:72:1b:25:6c:93:74: - 14:93:a3:73:b1:0e:aa:87:10:23:59:5f:20:05:19: - 47:ed:68:8e:92:12:ca:5d:fc:d6:2b:b2:92:3c:20: - cf:e1:5f:af:20:be:a0:76:7f:76:e5:ec:1a:86:61: - 33:3e:e7:7b:b4:3f:a0:0f:8e:a2:b9:6a:6f:b9:87: - 26:6f:41:6c:88:a6:50:fd:6a:63:0b:f5:93:16:1b: - 19:8f:b2:ed:9b:9b:c9:90:f5:01:0c:df:19:3d:0f: - 3e:38:23:c9:2f:8f:0c:d1:02:fe:1b:55:d6:4e:d0: - 8d:3c:af:4f:a4:f3:fe:af:2a:d3:05:9d:79:08:a1: - cb:57:31:b4:9c:c8:90:b2:67:f4:18:16:93:3a:fc: - 47:d8:d1:78:96:31:1f:ba:2b:0c:5f:5d:99:ad:63: - 89:5a:24:20:76:d8:df:fd:ab:4e:a6:22:aa:9d:5e: - e6:27:8a:7d:68:29:a3:e7:8a:b8:da:11:bb:17:2d: - 99:9d:13:24:46:f7:c5:e2:d8:9f:8e:7f:c7:8f:74: - 6d:5a:b2:e8:72:f5:ac:ee:24:10:ad:2f:14:da:ff: - 2d:9a:46:71:47:be:42:df:bb:01:db:f4:7f:d3:28: - 8f:31:59:5b:d3:c9:02:a6:b4:52:ca:6e:97:fb:43: - c5:08:26:6f:8a:f4:bb:fd:9f:28:aa:0d:d5:45:f3: - 13:3a:1d:d8:c0:78:8f:41:67:3c:1e:94:64:ae:7b: - 0b:c5:e8:d9:01:88:39:1a:97:86:64:41:d5:3b:87: - 0c:6e:fa:0f:c6:bd:48:14:bf:39:4d:d4:9e:41:b6: - 8f:96:1d:63:96:93:d9:95:06:78:31:68:9e:37:06: - 3b:80:89:45:61:39:23:c7:1b:44:a3:15:e5:1c:f8: - 92:30:bb - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Basic Constraints: critical - CA:TRUE, pathlen:1 - X509v3 Key Usage: critical - Certificate Sign, CRL Sign - X509v3 Subject Key Identifier: - 65:CD:EB:AB:35:1E:00:3E:7E:D5:74:C0:1C:B4:73:47:0E:1A:64:2F - X509v3 Certificate Policies: - Policy: X509v3 Any Policy - CPS: http://www.firmaprofesional.com/cps - User Notice: - Explicit Text: - - Signature Algorithm: sha1WithRSAEncryption - 17:7d:a0:f9:b4:dd:c5:c5:eb:ad:4b:24:b5:a1:02:ab:dd:a5: - 88:4a:b2:0f:55:4b:2b:57:8c:3b:e5:31:dd:fe:c4:32:f1:e7: - 5b:64:96:36:32:18:ec:a5:32:77:d7:e3:44:b6:c0:11:2a:80: - b9:3d:6a:6e:7c:9b:d3:ad:fc:c3:d6:a3:e6:64:29:7c:d1:e1: - 38:1e:82:2b:ff:27:65:af:fb:16:15:c4:2e:71:84:e5:b5:ff: - fa:a4:47:bd:64:32:bb:f6:25:84:a2:27:42:f5:20:b0:c2:13: - 10:11:cd:10:15:ba:42:90:2a:d2:44:e1:96:26:eb:31:48:12: - fd:2a:da:c9:06:cf:74:1e:a9:4b:d5:87:28:f9:79:34:92:3e: - 2e:44:e8:f6:8f:4f:8f:35:3f:25:b3:39:dc:63:2a:90:6b:20: - 5f:c4:52:12:4e:97:2c:2a:ac:9d:97:de:48:f2:a3:66:db:c2: - d2:83:95:a6:66:a7:9e:25:0f:e9:0b:33:91:65:0a:5a:c3:d9: - 54:12:dd:af:c3:4e:0e:1f:26:5e:0d:dc:b3:8d:ec:d5:81:70: - de:d2:4f:24:05:f3:6c:4e:f5:4c:49:66:8d:d1:ff:d2:0b:25: - 41:48:fe:51:84:c6:42:af:80:04:cf:d0:7e:64:49:e4:f2:df: - a2:ec:b1:4c:c0:2a:1d:e7:b4:b1:65:a2:c4:bc:f1:98:f4:aa: - 70:07:63:b4:b8:da:3b:4c:fa:40:22:30:5b:11:a6:f0:05:0e: - c6:02:03:48:ab:86:9b:85:dd:db:dd:ea:a2:76:80:73:7d:f5: - 9c:04:c4:45:8d:e7:b9:1c:8b:9e:ea:d7:75:d1:72:b1:de:75: - 44:e7:42:7d:e2:57:6b:7d:dc:99:bc:3d:83:28:ea:80:93:8d: - c5:4c:65:c1:70:81:b8:38:fc:43:31:b2:f6:03:34:47:b2:ac: - fb:22:06:cb:1e:dd:17:47:1c:5f:66:b9:d3:1a:a2:da:11:b1: - a4:bc:23:c9:e4:be:87:ff:b9:94:b6:f8:5d:20:4a:d4:5f:e7: - bd:68:7b:65:f2:15:1e:d2:3a:a9:2d:e9:d8:6b:24:ac:97:58: - 44:47:ad:59:18:f1:21:65:70:de:ce:34:60:a8:40:f1:f3:3c: - a4:c3:28:23:8c:fe:27:33:43:40:a0:17:3c:eb:ea:3b:b0:72: - a6:a3:b9:4a:4b:5e:16:48:f4:b2:bc:c8:8c:92:c5:9d:9f:ac: - 72:36:bc:34:80:34:6b:a9:8b:92:c0:b8:17:ed:ec:76:53:f5: - 24:01:8c:b3:22:e8:4b:7c:55:c6:9d:fa:a3:14:bb:65:85:6e: - 6e:4f:12:7e:0a:3c:9d:95 ------BEGIN CERTIFICATE----- -MIIGFDCCA/ygAwIBAgIIU+w77vuySF8wDQYJKoZIhvcNAQEFBQAwUTELMAkGA1UE -BhMCRVMxQjBABgNVBAMMOUF1dG9yaWRhZCBkZSBDZXJ0aWZpY2FjaW9uIEZpcm1h -cHJvZmVzaW9uYWwgQ0lGIEE2MjYzNDA2ODAeFw0wOTA1MjAwODM4MTVaFw0zMDEy -MzEwODM4MTVaMFExCzAJBgNVBAYTAkVTMUIwQAYDVQQDDDlBdXRvcmlkYWQgZGUg -Q2VydGlmaWNhY2lvbiBGaXJtYXByb2Zlc2lvbmFsIENJRiBBNjI2MzQwNjgwggIi -MA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQDKlmuO6vj78aI14H9M2uDDUtd9 -thDIAl6zQyrET2qyyhxdKJp4ERppWVevtSBC5IsP5t9bpgOSL/UR5GLXMnE42QQM -cas9UX4PB99jBVzpv5RvwSmCwLTaUbDBPLutN0pcyvFLNg4kq7/DhHf9qFD0sefG -L9ItWY16Ck6WaVICqjaY7Pz6FIMMNx/Jkjd/14Et5cS54D40/mf0PmbR0/RAz15i -NA9wBj4gGFrO93IbJWyTdBSTo3OxDqqHECNZXyAFGUftaI6SEspd/NYrspI8IM/h -X68gvqB2f3bl7BqGYTM+53u0P6APjqK5am+5hyZvQWyIplD9amML9ZMWGxmPsu2b -m8mQ9QEM3xk9Dz44I8kvjwzRAv4bVdZO0I08r0+k8/6vKtMFnXkIoctXMbScyJCy -Z/QYFpM6/EfY0XiWMR+6KwxfXZmtY4laJCB22N/9q06mIqqdXuYnin1oKaPnirja -EbsXLZmdEyRG98Xi2J+Of8ePdG1asuhy9azuJBCtLxTa/y2aRnFHvkLfuwHb9H/T -KI8xWVvTyQKmtFLKbpf7Q8UIJm+K9Lv9nyiqDdVF8xM6HdjAeI9BZzwelGSuewvF -6NkBiDkal4ZkQdU7hwxu+g/GvUgUvzlN1J5Bto+WHWOWk9mVBngxaJ43BjuAiUVh -OSPHG0SjFeUc+JIwuwIDAQABo4HvMIHsMBIGA1UdEwEB/wQIMAYBAf8CAQEwDgYD -VR0PAQH/BAQDAgEGMB0GA1UdDgQWBBRlzeurNR4APn7VdMActHNHDhpkLzCBpgYD -VR0gBIGeMIGbMIGYBgRVHSAAMIGPMC8GCCsGAQUFBwIBFiNodHRwOi8vd3d3LmZp -cm1hcHJvZmVzaW9uYWwuY29tL2NwczBcBggrBgEFBQcCAjBQHk4AUABhAHMAZQBv -ACAAZABlACAAbABhACAAQgBvAG4AYQBuAG8AdgBhACAANAA3ACAAQgBhAHIAYwBl -AGwAbwBuAGEAIAAwADgAMAAxADcwDQYJKoZIhvcNAQEFBQADggIBABd9oPm03cXF -661LJLWhAqvdpYhKsg9VSytXjDvlMd3+xDLx51tkljYyGOylMnfX40S2wBEqgLk9 -am58m9Ot/MPWo+ZkKXzR4Tgegiv/J2Wv+xYVxC5xhOW1//qkR71kMrv2JYSiJ0L1 -ILDCExARzRAVukKQKtJE4ZYm6zFIEv0q2skGz3QeqUvVhyj5eTSSPi5E6PaPT481 -PyWzOdxjKpBrIF/EUhJOlywqrJ2X3kjyo2bbwtKDlaZmp54lD+kLM5FlClrD2VQS -3a/DTg4fJl4N3LON7NWBcN7STyQF82xO9UxJZo3R/9ILJUFI/lGExkKvgATP0H5k -SeTy36LssUzAKh3ntLFlosS88Zj0qnAHY7S42jtM+kAiMFsRpvAFDsYCA0irhpuF -3dvd6qJ2gHN99ZwExEWN57kci57q13XRcrHedUTnQn3iV2t93Jm8PYMo6oCTjcVM -ZcFwgbg4/EMxsvYDNEeyrPsiBsse3RdHHF9mudMaotoRsaS8I8nkvof/uZS2+F0g -StRf571oe2XyFR7SOqkt6dhrJKyXWERHrVkY8SFlcN7ONGCoQPHzPKTDKCOM/icz -Q0CgFzzr6juwcqajuUpLXhZI9LK8yIySxZ2frHI2vDSANGupi5LAuBft7HZT9SQB -jLMi6Et8Vcad+qMUu2WFbm5PEn4KPJ2V ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: 33554617 (0x20000b9) - Signature Algorithm: sha1WithRSAEncryption - Issuer: C=IE, O=Baltimore, OU=CyberTrust, CN=Baltimore CyberTrust Root - Validity - Not Before: May 12 18:46:00 2000 GMT - Not After : May 12 23:59:00 2025 GMT - Subject: C=IE, O=Baltimore, OU=CyberTrust, CN=Baltimore CyberTrust Root - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (2048 bit) - Modulus: - 00:a3:04:bb:22:ab:98:3d:57:e8:26:72:9a:b5:79: - d4:29:e2:e1:e8:95:80:b1:b0:e3:5b:8e:2b:29:9a: - 64:df:a1:5d:ed:b0:09:05:6d:db:28:2e:ce:62:a2: - 62:fe:b4:88:da:12:eb:38:eb:21:9d:c0:41:2b:01: - 52:7b:88:77:d3:1c:8f:c7:ba:b9:88:b5:6a:09:e7: - 73:e8:11:40:a7:d1:cc:ca:62:8d:2d:e5:8f:0b:a6: - 50:d2:a8:50:c3:28:ea:f5:ab:25:87:8a:9a:96:1c: - a9:67:b8:3f:0c:d5:f7:f9:52:13:2f:c2:1b:d5:70: - 70:f0:8f:c0:12:ca:06:cb:9a:e1:d9:ca:33:7a:77: - d6:f8:ec:b9:f1:68:44:42:48:13:d2:c0:c2:a4:ae: - 5e:60:fe:b6:a6:05:fc:b4:dd:07:59:02:d4:59:18: - 98:63:f5:a5:63:e0:90:0c:7d:5d:b2:06:7a:f3:85: - ea:eb:d4:03:ae:5e:84:3e:5f:ff:15:ed:69:bc:f9: - 39:36:72:75:cf:77:52:4d:f3:c9:90:2c:b9:3d:e5: - c9:23:53:3f:1f:24:98:21:5c:07:99:29:bd:c6:3a: - ec:e7:6e:86:3a:6b:97:74:63:33:bd:68:18:31:f0: - 78:8d:76:bf:fc:9e:8e:5d:2a:86:a7:4d:90:dc:27: - 1a:39 - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Subject Key Identifier: - E5:9D:59:30:82:47:58:CC:AC:FA:08:54:36:86:7B:3A:B5:04:4D:F0 - X509v3 Basic Constraints: critical - CA:TRUE, pathlen:3 - X509v3 Key Usage: critical - Certificate Sign, CRL Sign - Signature Algorithm: sha1WithRSAEncryption - 85:0c:5d:8e:e4:6f:51:68:42:05:a0:dd:bb:4f:27:25:84:03: - bd:f7:64:fd:2d:d7:30:e3:a4:10:17:eb:da:29:29:b6:79:3f: - 76:f6:19:13:23:b8:10:0a:f9:58:a4:d4:61:70:bd:04:61:6a: - 12:8a:17:d5:0a:bd:c5:bc:30:7c:d6:e9:0c:25:8d:86:40:4f: - ec:cc:a3:7e:38:c6:37:11:4f:ed:dd:68:31:8e:4c:d2:b3:01: - 74:ee:be:75:5e:07:48:1a:7f:70:ff:16:5c:84:c0:79:85:b8: - 05:fd:7f:be:65:11:a3:0f:c0:02:b4:f8:52:37:39:04:d5:a9: - 31:7a:18:bf:a0:2a:f4:12:99:f7:a3:45:82:e3:3c:5e:f5:9d: - 9e:b5:c8:9e:7c:2e:c8:a4:9e:4e:08:14:4b:6d:fd:70:6d:6b: - 1a:63:bd:64:e6:1f:b7:ce:f0:f2:9f:2e:bb:1b:b7:f2:50:88: - 73:92:c2:e2:e3:16:8d:9a:32:02:ab:8e:18:dd:e9:10:11:ee: - 7e:35:ab:90:af:3e:30:94:7a:d0:33:3d:a7:65:0f:f5:fc:8e: - 9e:62:cf:47:44:2c:01:5d:bb:1d:b5:32:d2:47:d2:38:2e:d0: - fe:81:dc:32:6a:1e:b5:ee:3c:d5:fc:e7:81:1d:19:c3:24:42: - ea:63:39:a9 ------BEGIN CERTIFICATE----- -MIIDdzCCAl+gAwIBAgIEAgAAuTANBgkqhkiG9w0BAQUFADBaMQswCQYDVQQGEwJJ -RTESMBAGA1UEChMJQmFsdGltb3JlMRMwEQYDVQQLEwpDeWJlclRydXN0MSIwIAYD -VQQDExlCYWx0aW1vcmUgQ3liZXJUcnVzdCBSb290MB4XDTAwMDUxMjE4NDYwMFoX -DTI1MDUxMjIzNTkwMFowWjELMAkGA1UEBhMCSUUxEjAQBgNVBAoTCUJhbHRpbW9y -ZTETMBEGA1UECxMKQ3liZXJUcnVzdDEiMCAGA1UEAxMZQmFsdGltb3JlIEN5YmVy -VHJ1c3QgUm9vdDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAKMEuyKr -mD1X6CZymrV51Cni4eiVgLGw41uOKymaZN+hXe2wCQVt2yguzmKiYv60iNoS6zjr -IZ3AQSsBUnuId9Mcj8e6uYi1agnnc+gRQKfRzMpijS3ljwumUNKoUMMo6vWrJYeK -mpYcqWe4PwzV9/lSEy/CG9VwcPCPwBLKBsua4dnKM3p31vjsufFoREJIE9LAwqSu -XmD+tqYF/LTdB1kC1FkYmGP1pWPgkAx9XbIGevOF6uvUA65ehD5f/xXtabz5OTZy -dc93Uk3zyZAsuT3lySNTPx8kmCFcB5kpvcY67Oduhjprl3RjM71oGDHweI12v/ye -jl0qhqdNkNwnGjkCAwEAAaNFMEMwHQYDVR0OBBYEFOWdWTCCR1jMrPoIVDaGezq1 -BE3wMBIGA1UdEwEB/wQIMAYBAf8CAQMwDgYDVR0PAQH/BAQDAgEGMA0GCSqGSIb3 -DQEBBQUAA4IBAQCFDF2O5G9RaEIFoN27TyclhAO992T9Ldcw46QQF+vaKSm2eT92 -9hkTI7gQCvlYpNRhcL0EYWoSihfVCr3FvDB81ukMJY2GQE/szKN+OMY3EU/t3Wgx -jkzSswF07r51XgdIGn9w/xZchMB5hbgF/X++ZRGjD8ACtPhSNzkE1akxehi/oCr0 -Epn3o0WC4zxe9Z2etciefC7IpJ5OCBRLbf1wbWsaY71k5h+3zvDyny67G7fyUIhz -ksLi4xaNmjICq44Y3ekQEe5+NauQrz4wlHrQMz2nZQ/1/I6eYs9HRCwBXbsdtTLS -R9I4LtD+gdwyah617jzV/OeBHRnDJELqYzmp ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: 2 (0x2) - Signature Algorithm: sha256WithRSAEncryption - Issuer: C=NO, O=Buypass AS-983163327, CN=Buypass Class 2 Root CA - Validity - Not Before: Oct 26 08:38:03 2010 GMT - Not After : Oct 26 08:38:03 2040 GMT - Subject: C=NO, O=Buypass AS-983163327, CN=Buypass Class 2 Root CA - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (4096 bit) - Modulus: - 00:d7:c7:5e:f7:c1:07:d4:77:fb:43:21:f4:f4:f5: - 69:e4:ee:32:01:db:a3:86:1f:e4:59:0d:ba:e7:75: - 83:52:eb:ea:1c:61:15:48:bb:1d:07:ca:8c:ae:b0: - dc:96:9d:ea:c3:60:92:86:82:28:73:9c:56:06:ff: - 4b:64:f0:0c:2a:37:49:b5:e5:cf:0c:7c:ee:f1:4a: - bb:73:30:65:f3:d5:2f:83:b6:7e:e3:e7:f5:9e:ab: - 60:f9:d3:f1:9d:92:74:8a:e4:1c:96:ac:5b:80:e9: - b5:f4:31:87:a3:51:fc:c7:7e:a1:6f:8e:53:77:d4: - 97:c1:55:33:92:3e:18:2f:75:d4:ad:86:49:cb:95: - af:54:06:6c:d8:06:13:8d:5b:ff:e1:26:19:59:c0: - 24:ba:81:71:79:90:44:50:68:24:94:5f:b8:b3:11: - f1:29:41:61:a3:41:cb:23:36:d5:c1:f1:32:50:10: - 4e:7f:f4:86:93:ec:84:d3:8e:bc:4b:bf:5c:01:4e: - 07:3d:dc:14:8a:94:0a:a4:ea:73:fb:0b:51:e8:13: - 07:18:fa:0e:f1:2b:d1:54:15:7d:3c:e1:f7:b4:19: - 42:67:62:5e:77:e0:a2:55:ec:b6:d9:69:17:d5:3a: - af:44:ed:4a:c5:9e:e4:7a:27:7c:e5:75:d7:aa:cb: - 25:e7:df:6b:0a:db:0f:4d:93:4e:a8:a0:cd:7b:2e: - f2:59:01:6a:b7:0d:b8:07:81:7e:8b:38:1b:38:e6: - 0a:57:99:3d:ee:21:e8:a3:f5:0c:16:dd:8b:ec:34: - 8e:9c:2a:1c:00:15:17:8d:68:83:d2:70:9f:18:08: - cd:11:68:d5:c9:6b:52:cd:c4:46:8f:dc:b5:f3:d8: - 57:73:1e:e9:94:39:04:bf:d3:de:38:de:b4:53:ec: - 69:1c:a2:7e:c4:8f:e4:1b:70:ad:f2:a2:f9:fb:f7: - 16:64:66:69:9f:49:51:a2:e2:15:18:67:06:4a:7f: - d5:6c:b5:4d:b3:33:e0:61:eb:5d:be:e9:98:0f:32: - d7:1d:4b:3c:2e:5a:01:52:91:09:f2:df:ea:8d:d8: - 06:40:63:aa:11:e4:fe:c3:37:9e:14:52:3f:f4:e2: - cc:f2:61:93:d1:fd:67:6b:d7:52:ae:bf:68:ab:40: - 43:a0:57:35:53:78:f0:53:f8:61:42:07:64:c6:d7: - 6f:9b:4c:38:0d:63:ac:62:af:36:8b:a2:73:0a:0d: - f5:21:bd:74:aa:4d:ea:72:03:49:db:c7:5f:1d:62: - 63:c7:fd:dd:91:ec:33:ee:f5:6d:b4:6e:30:68:de: - c8:d6:26:b0:75:5e:7b:b4:07:20:98:a1:76:32:b8: - 4d:6c:4f - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Basic Constraints: critical - CA:TRUE - X509v3 Subject Key Identifier: - C9:80:77:E0:62:92:82:F5:46:9C:F3:BA:F7:4C:C3:DE:B8:A3:AD:39 - X509v3 Key Usage: critical - Certificate Sign, CRL Sign - Signature Algorithm: sha256WithRSAEncryption - 53:5f:21:f5:ba:b0:3a:52:39:2c:92:b0:6c:00:c9:ef:ce:20: - ef:06:f2:96:9e:e9:a4:74:7f:7a:16:fc:b7:f5:b6:fb:15:1b: - 3f:ab:a6:c0:72:5d:10:b1:71:ee:bc:4f:e3:ad:ac:03:6d:2e: - 71:2e:af:c4:e3:ad:a3:bd:0c:11:a7:b4:ff:4a:b2:7b:10:10: - 1f:a7:57:41:b2:c0:ae:f4:2c:59:d6:47:10:88:f3:21:51:29: - 30:ca:60:86:af:46:ab:1d:ed:3a:5b:b0:94:de:44:e3:41:08: - a2:c1:ec:1d:d6:fd:4f:b6:d6:47:d0:14:0b:ca:e6:ca:b5:7b: - 77:7e:41:1f:5e:83:c7:b6:8c:39:96:b0:3f:96:81:41:6f:60: - 90:e2:e8:f9:fb:22:71:d9:7d:b3:3d:46:bf:b4:84:af:90:1c: - 0f:8f:12:6a:af:ef:ee:1e:7a:ae:02:4a:8a:17:2b:76:fe:ac: - 54:89:24:2c:4f:3f:b6:b2:a7:4e:8c:a8:91:97:fb:29:c6:7b: - 5c:2d:b9:cb:66:b6:b7:a8:5b:12:51:85:b5:09:7e:62:78:70: - fe:a9:6a:60:b6:1d:0e:79:0c:fd:ca:ea:24:80:72:c3:97:3f: - f2:77:ab:43:22:0a:c7:eb:b6:0c:84:82:2c:80:6b:41:8a:08: - c0:eb:a5:6b:df:99:12:cb:8a:d5:5e:80:0c:91:e0:26:08:36: - 48:c5:fa:38:11:35:ff:25:83:2d:f2:7a:bf:da:fd:8e:fe:a5: - cb:45:2c:1f:c4:88:53:ae:77:0e:d9:9a:76:c5:8e:2c:1d:a3: - ba:d5:ec:32:ae:c0:aa:ac:f7:d1:7a:4d:eb:d4:07:e2:48:f7: - 22:8e:b0:a4:9f:6a:ce:8e:b2:b2:60:f4:a3:22:d0:23:eb:94: - 5a:7a:69:dd:0f:bf:40:57:ac:6b:59:50:d9:a3:99:e1:6e:fe: - 8d:01:79:27:23:15:de:92:9d:7b:09:4d:5a:e7:4b:48:30:5a: - 18:e6:0a:6d:e6:8f:e0:d2:bb:e6:df:7c:6e:21:82:c1:68:39: - 4d:b4:98:58:66:62:cc:4a:90:5e:c3:fa:27:04:b1:79:15:74: - 99:cc:be:ad:20:de:26:60:1c:eb:56:51:a6:a3:ea:e4:a3:3f: - a7:ff:61:dc:f1:5a:4d:6c:32:23:43:ee:ac:a8:ee:ee:4a:12: - 09:3c:5d:71:c2:be:79:fa:c2:87:68:1d:0b:fd:5c:69:cc:06: - d0:9a:7d:54:99:2a:c9:39:1a:19:af:4b:2a:43:f3:63:5d:5a: - 58:e2:2f:e3:1d:e4:a9:d6:d0:0a:d0:9e:bf:d7:81:09:f1:c9: - c7:26:0d:ac:98:16:56:a0 ------BEGIN CERTIFICATE----- -MIIFWTCCA0GgAwIBAgIBAjANBgkqhkiG9w0BAQsFADBOMQswCQYDVQQGEwJOTzEd -MBsGA1UECgwUQnV5cGFzcyBBUy05ODMxNjMzMjcxIDAeBgNVBAMMF0J1eXBhc3Mg -Q2xhc3MgMiBSb290IENBMB4XDTEwMTAyNjA4MzgwM1oXDTQwMTAyNjA4MzgwM1ow -TjELMAkGA1UEBhMCTk8xHTAbBgNVBAoMFEJ1eXBhc3MgQVMtOTgzMTYzMzI3MSAw -HgYDVQQDDBdCdXlwYXNzIENsYXNzIDIgUm9vdCBDQTCCAiIwDQYJKoZIhvcNAQEB -BQADggIPADCCAgoCggIBANfHXvfBB9R3+0Mh9PT1aeTuMgHbo4Yf5FkNuud1g1Lr -6hxhFUi7HQfKjK6w3Jad6sNgkoaCKHOcVgb/S2TwDCo3SbXlzwx87vFKu3MwZfPV -L4O2fuPn9Z6rYPnT8Z2SdIrkHJasW4DptfQxh6NR/Md+oW+OU3fUl8FVM5I+GC91 -1K2GScuVr1QGbNgGE41b/+EmGVnAJLqBcXmQRFBoJJRfuLMR8SlBYaNByyM21cHx -MlAQTn/0hpPshNOOvEu/XAFOBz3cFIqUCqTqc/sLUegTBxj6DvEr0VQVfTzh97QZ -QmdiXnfgolXsttlpF9U6r0TtSsWe5HonfOV116rLJeffawrbD02TTqigzXsu8lkB -arcNuAeBfos4GzjmCleZPe4h6KP1DBbdi+w0jpwqHAAVF41og9JwnxgIzRFo1clr -Us3ERo/ctfPYV3Me6ZQ5BL/T3jjetFPsaRyifsSP5BtwrfKi+fv3FmRmaZ9JUaLi -FRhnBkp/1Wy1TbMz4GHrXb7pmA8y1x1LPC5aAVKRCfLf6o3YBkBjqhHk/sM3nhRS -P/TizPJhk9H9Z2vXUq6/aKtAQ6BXNVN48FP4YUIHZMbXb5tMOA1jrGKvNouicwoN -9SG9dKpN6nIDSdvHXx1iY8f93ZHsM+71bbRuMGjeyNYmsHVee7QHIJihdjK4TWxP -AgMBAAGjQjBAMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFMmAd+BikoL1Rpzz -uvdMw964o605MA4GA1UdDwEB/wQEAwIBBjANBgkqhkiG9w0BAQsFAAOCAgEAU18h -9bqwOlI5LJKwbADJ784g7wbylp7ppHR/ehb8t/W2+xUbP6umwHJdELFx7rxP462s -A20ucS6vxOOto70MEae0/0qyexAQH6dXQbLArvQsWdZHEIjzIVEpMMpghq9Gqx3t -OluwlN5E40EIosHsHdb9T7bWR9AUC8rmyrV7d35BH16Dx7aMOZawP5aBQW9gkOLo -+fsicdl9sz1Gv7SEr5AcD48Saq/v7h56rgJKihcrdv6sVIkkLE8/trKnToyokZf7 -KcZ7XC25y2a2t6hbElGFtQl+Ynhw/qlqYLYdDnkM/crqJIByw5c/8nerQyIKx+u2 -DISCLIBrQYoIwOula9+ZEsuK1V6ADJHgJgg2SMX6OBE1/yWDLfJ6v9r9jv6ly0Us -H8SIU653DtmadsWOLB2jutXsMq7Aqqz30XpN69QH4kj3Io6wpJ9qzo6ysmD0oyLQ -I+uUWnpp3Q+/QFesa1lQ2aOZ4W7+jQF5JyMV3pKdewlNWudLSDBaGOYKbeaP4NK7 -5t98biGCwWg5TbSYWGZizEqQXsP6JwSxeRV0mcy+rSDeJmAc61ZRpqPq5KM/p/9h -3PFaTWwyI0PurKju7koSCTxdccK+efrCh2gdC/1cacwG0Jp9VJkqyTkaGa9LKkPz -Y11aWOIv4x3kqdbQCtCev9eBCfHJxyYNrJgWVqA= ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: 2 (0x2) - Signature Algorithm: sha256WithRSAEncryption - Issuer: C=NO, O=Buypass AS-983163327, CN=Buypass Class 3 Root CA - Validity - Not Before: Oct 26 08:28:58 2010 GMT - Not After : Oct 26 08:28:58 2040 GMT - Subject: C=NO, O=Buypass AS-983163327, CN=Buypass Class 3 Root CA - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (4096 bit) - Modulus: - 00:a5:da:0a:95:16:50:e3:95:f2:5e:9d:76:31:06: - 32:7a:9b:f1:10:76:b8:00:9a:b5:52:36:cd:24:47: - b0:9f:18:64:bc:9a:f6:fa:d5:79:d8:90:62:4c:22: - 2f:de:38:3d:d6:e0:a8:e9:1c:2c:db:78:11:e9:8e: - 68:51:15:72:c7:f3:33:87:e4:a0:5d:0b:5c:e0:57: - 07:2a:30:f5:cd:c4:37:77:28:4d:18:91:e6:bf:d5: - 52:fd:71:2d:70:3e:e7:c6:c4:8a:e3:f0:28:0b:f4: - 76:98:a1:8b:87:55:b2:3a:13:fc:b7:3e:27:37:8e: - 22:e3:a8:4f:2a:ef:60:bb:3d:b7:39:c3:0e:01:47: - 99:5d:12:4f:db:43:fa:57:a1:ed:f9:9d:be:11:47: - 26:5b:13:98:ab:5d:16:8a:b0:37:1c:57:9d:45:ff: - 88:96:36:bf:bb:ca:07:7b:6f:87:63:d7:d0:32:6a: - d6:5d:6c:0c:f1:b3:6e:39:e2:6b:31:2e:39:00:27: - 14:de:38:c0:ec:19:66:86:12:e8:9d:72:16:13:64: - 52:c7:a9:37:1c:fd:82:30:ed:84:18:1d:f4:ae:5c: - ff:70:13:00:eb:b1:f5:33:7a:4b:d6:55:f8:05:8d: - 4b:69:b0:f5:b3:28:36:5c:14:c4:51:73:4d:6b:0b: - f1:34:07:db:17:39:d7:dc:28:7b:6b:f5:9f:f3:2e: - c1:4f:17:2a:10:f3:cc:ca:e8:eb:fd:6b:ab:2e:9a: - 9f:2d:82:6e:04:d4:52:01:93:2d:3d:86:fc:7e:fc: - df:ef:42:1d:a6:6b:ef:b9:20:c6:f7:bd:a0:a7:95: - fd:a7:e6:89:24:d8:cc:8c:34:6c:e2:23:2f:d9:12: - 1a:21:b9:55:91:6f:0b:91:79:19:0c:ad:40:88:0b: - 70:e2:7a:d2:0e:d8:68:48:bb:82:13:39:10:58:e9: - d8:2a:07:c6:12:db:58:db:d2:3b:55:10:47:05:15: - 67:62:7e:18:63:a6:46:3f:09:0e:54:32:5e:bf:0d: - 62:7a:27:ef:80:e8:db:d9:4b:06:5a:37:5a:25:d0: - 08:12:77:d4:6f:09:50:97:3d:c8:1d:c3:df:8c:45: - 30:56:c6:d3:64:ab:66:f3:c0:5e:96:9c:c3:c4:ef: - c3:7c:6b:8b:3a:79:7f:b3:49:cf:3d:e2:89:9f:a0: - 30:4b:85:b9:9c:94:24:79:8f:7d:6b:a9:45:68:0f: - 2b:d0:f1:da:1c:cb:69:b8:ca:49:62:6d:c8:d0:63: - 62:dd:60:0f:58:aa:8f:a1:bc:05:a5:66:a2:cf:1b: - 76:b2:84:64:b1:4c:39:52:c0:30:ba:f0:8c:4b:02: - b0:b6:b7 - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Basic Constraints: critical - CA:TRUE - X509v3 Subject Key Identifier: - 47:B8:CD:FF:E5:6F:EE:F8:B2:EC:2F:4E:0E:F9:25:B0:8E:3C:6B:C3 - X509v3 Key Usage: critical - Certificate Sign, CRL Sign - Signature Algorithm: sha256WithRSAEncryption - 00:20:23:41:35:04:90:c2:40:62:60:ef:e2:35:4c:d7:3f:ac: - e2:34:90:b8:a1:6f:76:fa:16:16:a4:48:37:2c:e9:90:c2:f2: - 3c:f8:0a:9f:d8:81:e5:bb:5b:da:25:2c:a4:a7:55:71:24:32: - f6:c8:0b:f2:bc:6a:f8:93:ac:b2:07:c2:5f:9f:db:cc:c8:8a: - aa:be:6a:6f:e1:49:10:cc:31:d7:80:bb:bb:c8:d8:a2:0e:64: - 57:ea:a2:f5:c2:a9:31:15:d2:20:6a:ec:fc:22:01:28:cf:86: - b8:80:1e:a9:cc:11:a5:3c:f2:16:b3:47:9d:fc:d2:80:21:c4: - cb:d0:47:70:41:a1:ca:83:19:08:2c:6d:f2:5d:77:9c:8a:14: - 13:d4:36:1c:92:f0:e5:06:37:dc:a6:e6:90:9b:38:8f:5c:6b: - 1b:46:86:43:42:5f:3e:01:07:53:54:5d:65:7d:f7:8a:73:a1: - 9a:54:5a:1f:29:43:14:27:c2:85:0f:b5:88:7b:1a:3b:94:b7: - 1d:60:a7:b5:9c:e7:29:69:57:5a:9b:93:7a:43:30:1b:03:d7: - 62:c8:40:a6:aa:fc:64:e4:4a:d7:91:53:01:a8:20:88:6e:9c: - 5f:44:b9:cb:60:81:34:ec:6f:d3:7d:da:48:5f:eb:b4:90:bc: - 2d:a9:1c:0b:ac:1c:d5:a2:68:20:80:04:d6:fc:b1:8f:2f:bb: - 4a:31:0d:4a:86:1c:eb:e2:36:29:26:f5:da:d8:c4:f2:75:61: - cf:7e:ae:76:63:4a:7a:40:65:93:87:f8:1e:80:8c:86:e5:86: - d6:8f:0e:fc:53:2c:60:e8:16:61:1a:a2:3e:43:7b:cd:39:60: - 54:6a:f5:f2:89:26:01:68:83:48:a2:33:e8:c9:04:91:b2:11: - 34:11:3e:ea:d0:43:19:1f:03:93:90:0c:ff:51:3d:57:f4:41: - 6e:e1:cb:a0:be:eb:c9:63:cd:6d:cc:e4:f8:36:aa:68:9d:ed: - bd:5d:97:70:44:0d:b6:0e:35:dc:e1:0c:5d:bb:a0:51:94:cb: - 7e:16:eb:11:2f:a3:92:45:c8:4c:71:d9:bc:c9:99:52:57:46: - 2f:50:cf:bd:35:69:f4:3d:15:ce:06:a5:2c:0f:3e:f6:81:ba: - 94:bb:c3:bb:bf:65:78:d2:86:79:ff:49:3b:1a:83:0c:f0:de: - 78:ec:c8:f2:4d:4c:1a:de:82:29:f8:c1:5a:da:ed:ee:e6:27: - 5e:e8:45:d0:9d:1c:51:a8:68:ab:44:e3:d0:8b:6a:e3:f8:3b: - bb:dc:4d:d7:64:f2:51:be:e6:aa:ab:5a:e9:31:ee:06:bc:73: - bf:13:62:0a:9f:c7:b9:97 ------BEGIN CERTIFICATE----- -MIIFWTCCA0GgAwIBAgIBAjANBgkqhkiG9w0BAQsFADBOMQswCQYDVQQGEwJOTzEd -MBsGA1UECgwUQnV5cGFzcyBBUy05ODMxNjMzMjcxIDAeBgNVBAMMF0J1eXBhc3Mg -Q2xhc3MgMyBSb290IENBMB4XDTEwMTAyNjA4Mjg1OFoXDTQwMTAyNjA4Mjg1OFow -TjELMAkGA1UEBhMCTk8xHTAbBgNVBAoMFEJ1eXBhc3MgQVMtOTgzMTYzMzI3MSAw -HgYDVQQDDBdCdXlwYXNzIENsYXNzIDMgUm9vdCBDQTCCAiIwDQYJKoZIhvcNAQEB -BQADggIPADCCAgoCggIBAKXaCpUWUOOV8l6ddjEGMnqb8RB2uACatVI2zSRHsJ8Y -ZLya9vrVediQYkwiL944PdbgqOkcLNt4EemOaFEVcsfzM4fkoF0LXOBXByow9c3E -N3coTRiR5r/VUv1xLXA+58bEiuPwKAv0dpihi4dVsjoT/Lc+JzeOIuOoTyrvYLs9 -tznDDgFHmV0ST9tD+leh7fmdvhFHJlsTmKtdFoqwNxxXnUX/iJY2v7vKB3tvh2PX -0DJq1l1sDPGzbjniazEuOQAnFN44wOwZZoYS6J1yFhNkUsepNxz9gjDthBgd9K5c -/3ATAOux9TN6S9ZV+AWNS2mw9bMoNlwUxFFzTWsL8TQH2xc519woe2v1n/MuwU8X -KhDzzMro6/1rqy6any2CbgTUUgGTLT2G/H783+9CHaZr77kgxve9oKeV/afmiSTY -zIw0bOIjL9kSGiG5VZFvC5F5GQytQIgLcOJ60g7YaEi7ghM5EFjp2CoHxhLbWNvS -O1UQRwUVZ2J+GGOmRj8JDlQyXr8NYnon74Do29lLBlo3WiXQCBJ31G8JUJc9yB3D -34xFMFbG02SrZvPAXpacw8Tvw3xrizp5f7NJzz3iiZ+gMEuFuZyUJHmPfWupRWgP -K9Dx2hzLabjKSWJtyNBjYt1gD1iqj6G8BaVmos8bdrKEZLFMOVLAMLrwjEsCsLa3 -AgMBAAGjQjBAMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFEe4zf/lb+74suwv -Tg75JbCOPGvDMA4GA1UdDwEB/wQEAwIBBjANBgkqhkiG9w0BAQsFAAOCAgEAACAj -QTUEkMJAYmDv4jVM1z+s4jSQuKFvdvoWFqRINyzpkMLyPPgKn9iB5btb2iUspKdV -cSQy9sgL8rxq+JOssgfCX5/bzMiKqr5qb+FJEMwx14C7u8jYog5kV+qi9cKpMRXS -IGrs/CIBKM+GuIAeqcwRpTzyFrNHnfzSgCHEy9BHcEGhyoMZCCxt8l13nIoUE9Q2 -HJLw5QY33KbmkJs4j1xrG0aGQ0JfPgEHU1RdZX33inOhmlRaHylDFCfChQ+1iHsa -O5S3HWCntZznKWlXWpuTekMwGwPXYshApqr8ZORK15FTAaggiG6cX0S5y2CBNOxv -033aSF/rtJC8LakcC6wc1aJoIIAE1vyxjy+7SjENSoYc6+I2KSb12tjE8nVhz36u -dmNKekBlk4f4HoCMhuWG1o8O/FMsYOgWYRqiPkN7zTlgVGr18okmAWiDSKIz6MkE -kbIRNBE+6tBDGR8Dk5AM/1E9V/RBbuHLoL7ryWPNbczk+DaqaJ3tvV2XcEQNtg41 -3OEMXbugUZTLfhbrES+jkkXITHHZvMmZUldGL1DPvTVp9D0VzgalLA8+9oG6lLvD -u79leNKGef9JOxqDDPDeeOzI8k1MGt6CKfjBWtrt7uYnXuhF0J0cUahoq0Tj0Itq -4/g7u9xN12TyUb7mqqta6THuBrxzvxNiCp/HuZc= ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: - c3:03:9a:ee:50:90:6e:28 - Signature Algorithm: sha1WithRSAEncryption - Issuer: C=SK, L=Bratislava, O=Disig a.s., CN=CA Disig Root R1 - Validity - Not Before: Jul 19 09:06:56 2012 GMT - Not After : Jul 19 09:06:56 2042 GMT - Subject: C=SK, L=Bratislava, O=Disig a.s., CN=CA Disig Root R1 - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (4096 bit) - Modulus: - 00:aa:c3:78:f7:dc:98:a3:a7:5a:5e:77:18:b2:dd: - 04:64:0f:63:fd:9b:96:09:80:d5:e8:aa:a5:e2:9c: - 26:94:3a:e8:99:73:8c:9d:df:d7:df:83:f3:78:4f: - 40:e1:7f:d2:a7:d2:e5:ca:13:93:e7:ed:c6:77:5f: - 36:b5:94:af:e8:38:8e:db:9b:e5:7c:bb:cc:8d:eb: - 75:73:e1:24:cd:e6:a7:2d:19:2e:d8:d6:8a:6b:14: - eb:08:62:0a:d8:dc:b3:00:4d:c3:23:7c:5f:43:08: - 23:32:12:dc:ed:0c:ad:c0:7d:0f:a5:7a:42:d9:5a: - 70:d9:bf:a7:d7:01:1c:f6:9b:ab:8e:b7:4a:86:78: - a0:1e:56:31:ae:ef:82:0a:80:41:f7:1b:c9:ae:ab: - 32:26:d4:2c:6b:ed:7d:6b:e4:e2:5e:22:0a:45:cb: - 84:31:4d:ac:fe:db:d1:47:ba:f9:60:97:39:b1:65: - c7:de:fb:99:e4:0a:22:b1:2d:4d:e5:48:26:69:ab: - e2:aa:f3:fb:fc:92:29:32:e9:b3:3e:4d:1f:27:a1: - cd:8e:b9:17:fb:25:3e:c9:6e:f3:77:da:0d:12:f6: - 5d:c7:bb:36:10:d5:54:d6:f3:e0:e2:47:48:e6:de: - 14:da:61:52:af:26:b4:f5:71:4f:c9:d7:d2:06:df: - 63:ca:ff:21:e8:59:06:e0:08:d5:84:15:53:f7:43: - e5:7c:c5:a0:89:98:6b:73:c6:68:ce:65:de:bd:7f: - 05:f7:b1:ee:f6:57:a1:60:95:c5:cc:ea:93:3a:be: - 99:ae:9b:02:a3:ad:c9:16:b5:ce:dd:5e:99:78:7e: - 1a:39:7e:b2:c0:05:a4:c0:82:a5:a3:47:9e:8c:ea: - 5c:b6:bc:67:db:e6:2a:4d:d2:04:dc:a3:ae:45:f7: - bc:8b:9c:1c:a7:d6:d5:03:dc:08:cb:2e:16:ca:5c: - 40:33:e8:67:c3:2e:e7:a6:44:ea:11:45:1c:35:65: - 2d:1e:45:61:24:1b:82:2e:a5:9d:33:5d:65:f8:41: - f9:2e:cb:94:3f:1f:a3:0c:31:24:44:ed:c7:5e:ad: - 50:ba:c6:41:9b:ac:f0:17:65:c0:f8:5d:6f:5b:a0: - 0a:34:3c:ee:d7:ea:88:9f:98:f9:af:4e:24:fa:97: - b2:64:76:da:ab:f4:ed:e3:c3:60:ef:d5:f9:02:c8: - 2d:9f:83:af:67:69:06:a7:31:55:d5:cf:4b:6f:ff: - 04:05:c7:58:ac:5f:16:1b:e5:d2:a3:eb:31:db:1f: - 33:15:4d:d0:f2:a5:53:f5:cb:e1:3d:4e:68:2d:d8: - 12:dd:aa:f2:e6:4d:9b:49:e5:c5:28:a1:ba:b0:5a: - c6:a0:b5 - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Basic Constraints: critical - CA:TRUE - X509v3 Key Usage: critical - Certificate Sign, CRL Sign - X509v3 Subject Key Identifier: - 89:0A:B4:38:93:1A:E6:AB:EE:9B:91:18:F9:F5:3C:3E:35:D0:D3:82 - Signature Algorithm: sha1WithRSAEncryption - 32:8b:f6:9d:4a:c9:be:14:e5:8c:ac:38:ca:3a:09:d4:1b:ce: - 86:b3:dd:eb:d4:ba:28:be:12:ae:45:2c:04:74:ac:13:51:c5: - 58:18:66:4d:82:da:d5:dc:93:c0:27:e1:be:7c:9f:52:9e:12: - 56:f6:d5:9c:a9:f4:75:9c:fa:37:12:8f:1c:93:ec:57:fe:07: - 0f:ab:d5:12:f7:0f:ae:61:5e:56:80:49:f5:fc:30:f5:9b:4f: - 1f:41:2f:1c:84:d3:89:c7:e2:da:02:76:ed:09:cf:6c:c1:b8: - 1c:83:1c:16:fa:94:cd:7d:a0:c8:18:d2:c8:9d:6e:f5:bd:69: - d4:6d:3d:35:e8:1e:a2:4f:60:d7:07:29:fc:b2:a3:a4:9d:6e: - 15:92:56:19:4c:0a:b0:e9:7c:d2:19:4d:42:46:ec:bd:fd:f6: - 57:5b:dd:98:7e:a4:4d:cc:72:03:83:58:5d:ef:93:3a:41:7a: - 63:aa:7c:3a:a8:f5:ac:a4:d1:dd:a2:2d:b6:2a:fc:9f:01:8e: - e2:10:b1:c4:ca:e4:67:db:55:25:19:3f:fd:e8:36:7e:b3:e1: - e1:81:af:11:16:8b:50:97:60:19:82:00:c0:6b:4d:73:b8:d1: - 13:07:3e:ea:b6:31:4f:f0:42:9a:6d:e2:11:74:e5:94:ac:8d: - 84:95:3c:21:af:c5:da:47:c8:df:39:62:62:cb:5b:50:0b:d7: - 81:40:05:9c:9b:ed:ba:b6:8b:1e:04:6f:96:20:39:ed:a4:7d: - 29:db:48:ce:82:dc:d4:02:8d:1d:04:31:5a:c7:4b:f0:6c:61: - 52:d7:b4:51:c2:81:6c:cd:e1:fb:a7:a1:d2:92:76:cf:b1:0f: - 37:58:a4:f2:52:71:67:3f:0c:88:78:80:89:c1:c8:b5:1f:92: - 63:be:a7:7a:8a:56:2c:1a:a8:a6:9c:b5:5d:b3:63:d0:13:20: - a1:eb:91:6c:d0:8d:7d:af:df:0b:e4:17:b9:86:9e:38:b1:94: - 0c:58:8c:e0:55:aa:3b:63:6d:9a:89:60:b8:64:2a:92:c6:37: - f4:7e:43:43:b7:73:e8:01:e7:7f:97:0f:d7:f2:7b:19:fd:1a: - d7:8f:c9:fa:85:6b:7a:9d:9e:89:b6:a6:28:99:93:88:40:f7: - 3e:cd:51:a3:ca:ea:ef:79:47:21:b5:fe:32:e2:c7:c3:51:6f: - be:80:74:f0:a4:c3:3a:f2:4f:e9:5f:df:19:0a:f2:3b:13:43: - ac:31:a4:b3:e7:eb:fc:18:d6:01:a9:f3:2a:8f:36:0e:eb:b4: - b1:bc:b7:4c:c9:6b:bf:a1:f3:d9:f4:ed:e2:f0:e3:ed:64:9e: - 3d:2f:96:52:4f:80:53:8b ------BEGIN CERTIFICATE----- -MIIFaTCCA1GgAwIBAgIJAMMDmu5QkG4oMA0GCSqGSIb3DQEBBQUAMFIxCzAJBgNV -BAYTAlNLMRMwEQYDVQQHEwpCcmF0aXNsYXZhMRMwEQYDVQQKEwpEaXNpZyBhLnMu -MRkwFwYDVQQDExBDQSBEaXNpZyBSb290IFIxMB4XDTEyMDcxOTA5MDY1NloXDTQy -MDcxOTA5MDY1NlowUjELMAkGA1UEBhMCU0sxEzARBgNVBAcTCkJyYXRpc2xhdmEx -EzARBgNVBAoTCkRpc2lnIGEucy4xGTAXBgNVBAMTEENBIERpc2lnIFJvb3QgUjEw -ggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQCqw3j33Jijp1pedxiy3QRk -D2P9m5YJgNXoqqXinCaUOuiZc4yd39ffg/N4T0Dhf9Kn0uXKE5Pn7cZ3Xza1lK/o -OI7bm+V8u8yN63Vz4STN5qctGS7Y1oprFOsIYgrY3LMATcMjfF9DCCMyEtztDK3A -fQ+lekLZWnDZv6fXARz2m6uOt0qGeKAeVjGu74IKgEH3G8muqzIm1Cxr7X1r5OJe -IgpFy4QxTaz+29FHuvlglzmxZcfe+5nkCiKxLU3lSCZpq+Kq8/v8kiky6bM+TR8n -oc2OuRf7JT7JbvN32g0S9l3HuzYQ1VTW8+DiR0jm3hTaYVKvJrT1cU/J19IG32PK -/yHoWQbgCNWEFVP3Q+V8xaCJmGtzxmjOZd69fwX3se72V6FglcXM6pM6vpmumwKj -rckWtc7dXpl4fho5frLABaTAgqWjR56M6ly2vGfb5ipN0gTco65F97yLnByn1tUD -3AjLLhbKXEAz6GfDLuemROoRRRw1ZS0eRWEkG4IupZ0zXWX4Qfkuy5Q/H6MMMSRE -7cderVC6xkGbrPAXZcD4XW9boAo0PO7X6oifmPmvTiT6l7Jkdtqr9O3jw2Dv1fkC -yC2fg69naQanMVXVz0tv/wQFx1isXxYb5dKj6zHbHzMVTdDypVP1y+E9Tmgt2BLd -qvLmTZtJ5cUoobqwWsagtQIDAQABo0IwQDAPBgNVHRMBAf8EBTADAQH/MA4GA1Ud -DwEB/wQEAwIBBjAdBgNVHQ4EFgQUiQq0OJMa5qvum5EY+fU8PjXQ04IwDQYJKoZI -hvcNAQEFBQADggIBADKL9p1Kyb4U5YysOMo6CdQbzoaz3evUuii+Eq5FLAR0rBNR -xVgYZk2C2tXck8An4b58n1KeElb21Zyp9HWc+jcSjxyT7Ff+Bw+r1RL3D65hXlaA -SfX8MPWbTx9BLxyE04nH4toCdu0Jz2zBuByDHBb6lM19oMgY0sidbvW9adRtPTXo -HqJPYNcHKfyyo6SdbhWSVhlMCrDpfNIZTUJG7L399ldb3Zh+pE3McgODWF3vkzpB -emOqfDqo9ayk0d2iLbYq/J8BjuIQscTK5GfbVSUZP/3oNn6z4eGBrxEWi1CXYBmC -AMBrTXO40RMHPuq2MU/wQppt4hF05ZSsjYSVPCGvxdpHyN85YmLLW1AL14FABZyb -7bq2ix4Eb5YgOe2kfSnbSM6C3NQCjR0EMVrHS/BsYVLXtFHCgWzN4funodKSds+x -DzdYpPJScWc/DIh4gInByLUfkmO+p3qKViwaqKactV2zY9ATIKHrkWzQjX2v3wvk -F7mGnjixlAxYjOBVqjtjbZqJYLhkKpLGN/R+Q0O3c+gB53+XD9fyexn9GtePyfqF -a3qdnom2piiZk4hA9z7NUaPK6u95RyG1/jLix8NRb76AdPCkwzryT+lf3xkK8jsT -Q6wxpLPn6/wY1gGp8yqPNg7rtLG8t0zJa7+h89n07eLw4+1knj0vllJPgFOL ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: - 92:b8:88:db:b0:8a:c1:63 - Signature Algorithm: sha256WithRSAEncryption - Issuer: C=SK, L=Bratislava, O=Disig a.s., CN=CA Disig Root R2 - Validity - Not Before: Jul 19 09:15:30 2012 GMT - Not After : Jul 19 09:15:30 2042 GMT - Subject: C=SK, L=Bratislava, O=Disig a.s., CN=CA Disig Root R2 - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (4096 bit) - Modulus: - 00:a2:a3:c4:00:09:d6:85:5d:2d:6d:14:f6:c2:c3: - 73:9e:35:c2:71:55:7e:81:fb:ab:46:50:e0:c1:7c: - 49:78:e6:ab:79:58:3c:da:ff:7c:1c:9f:d8:97:02: - 78:3e:6b:41:04:e9:41:bd:be:03:2c:45:f6:2f:64: - d4:ab:5d:a3:47:3d:64:9b:e9:68:9a:c6:cc:1b:3f: - ba:be:b2:8b:34:02:2e:98:55:19:fc:8c:6f:aa:5f: - da:4c:ce:4d:03:21:a3:d8:d2:34:93:56:96:cb:4c: - 0c:00:16:3c:5f:1a:cd:c8:c7:6c:a6:ad:d3:31:a7: - bc:e8:e5:e1:66:d6:d2:fb:03:b4:41:65:c9:10:ae: - 0e:05:63:c6:80:6a:69:30:fd:d2:ee:90:ef:0d:27: - df:9f:95:73:f4:e1:25:da:6c:16:de:41:38:34:ea: - 8b:fc:d1:e8:04:14:61:2d:41:7e:ac:c7:77:4e:cb: - 51:54:fb:5e:92:18:1b:04:5a:68:c6:c9:c4:fa:b7: - 13:a0:98:b7:11:2b:b7:d6:57:cc:7c:9e:17:d1:cb: - 25:fe:86:4e:24:2e:56:0c:78:4d:9e:01:12:a6:2b: - a7:01:65:6e:7c:62:1d:84:84:df:ea:c0:6b:b5:a5: - 2a:95:83:c3:53:11:0c:73:1d:0b:b2:46:90:d1:42: - 3a:ce:40:6e:95:ad:ff:c6:94:ad:6e:97:84:8e:7d: - 6f:9e:8a:80:0d:49:6d:73:e2:7b:92:1e:c3:f3:c1: - f3:eb:2e:05:6f:d9:1b:cf:37:76:04:c8:b4:5a:e4: - 17:a7:cb:dd:76:1f:d0:19:76:e8:2c:05:b3:d6:9c: - 34:d8:96:dc:61:87:91:05:e4:44:08:33:c1:da:b9: - 08:65:d4:ae:b2:36:0d:eb:ba:38:ba:0c:e5:9b:9e: - eb:8d:66:dd:99:cf:d6:89:41:f6:04:92:8a:29:29: - 6d:6b:3a:1c:e7:75:7d:02:71:0e:f3:c0:e7:bd:cb: - 19:dd:9d:60:b2:c2:66:60:b6:b1:04:ee:c9:e6:86: - b9:9a:66:40:a8:e7:11:ed:81:45:03:8b:f6:67:59: - e8:c1:06:11:bd:dd:cf:80:02:4f:65:40:78:5c:47: - 50:c8:9b:e6:1f:81:7b:e4:44:a8:5b:85:9a:e2:de: - 5a:d5:c7:f9:3a:44:66:4b:e4:32:54:7c:e4:6c:9c: - b3:0e:3d:17:a2:b2:34:12:d6:7e:b2:a8:49:bb:d1: - 7a:28:40:be:a2:16:1f:df:e4:37:1f:11:73:fb:90: - 0a:65:43:a2:0d:7c:f8:06:01:55:33:7d:b0:0d:b8: - f4:f5:ae:a5:42:57:7c:36:11:8c:7b:5e:c4:03:9d: - 8c:79:9d - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Basic Constraints: critical - CA:TRUE - X509v3 Key Usage: critical - Certificate Sign, CRL Sign - X509v3 Subject Key Identifier: - B5:99:F8:AF:B0:94:F5:E3:20:D6:0A:AD:CE:4E:56:A4:2E:6E:42:ED - Signature Algorithm: sha256WithRSAEncryption - 26:06:5e:70:e7:65:33:c8:82:6e:d9:9c:17:3a:1b:7a:66:b2: - 01:f6:78:3b:69:5e:2f:ea:ff:4e:f9:28:c3:98:2a:61:4c:b4: - 24:12:8a:7d:6d:11:14:f7:9c:b5:ca:e6:bc:9e:27:8e:4c:19: - c8:a9:bd:7a:c0:d7:36:0e:6d:85:72:6e:a8:c6:a2:6d:f6:fa: - 73:63:7f:bc:6e:79:08:1c:9d:8a:9f:1a:8a:53:a6:d8:bb:d9: - 35:55:b1:11:c5:a9:03:b3:56:3b:b9:84:93:22:5e:7e:c1:f6: - 12:52:8b:ea:2c:67:bc:fe:36:4c:f5:b8:cf:d1:b3:49:92:3b: - d3:29:0e:99:1b:96:f7:61:b8:3b:c4:2b:b6:78:6c:b4:23:6f: - f0:fd:d3:b2:5e:75:1f:99:95:a8:ac:f6:da:e1:c5:31:7b:fb: - d1:46:b3:d2:bc:67:b4:62:54:ba:09:f7:63:b0:93:a2:9a:f9: - e9:52:2e:8b:60:12:ab:fc:f5:60:56:ef:10:5c:8b:c4:1a:42: - dc:83:5b:64:0e:cb:b5:bc:d6:4f:c1:7c:3c:6e:8d:13:6d:fb: - 7b:eb:30:d0:dc:4d:af:c5:d5:b6:a5:4c:5b:71:c9:e8:31:be: - e8:38:06:48:a1:1a:e2:ea:d2:de:12:39:58:1a:ff:80:0e:82: - 75:e6:b7:c9:07:6c:0e:ef:ff:38:f1:98:71:c4:b7:7f:0e:15: - d0:25:69:bd:22:9d:2b:ed:05:f6:46:47:ac:ed:c0:f0:d4:3b: - e2:ec:ee:96:5b:90:13:4e:1e:56:3a:eb:b0:ef:96:bb:96:23: - 11:ba:f2:43:86:74:64:95:c8:28:75:df:1d:35:ba:d2:37:83: - 38:53:38:36:3b:cf:6c:e9:f9:6b:0e:d0:fb:04:e8:4f:77:d7: - 65:01:78:86:0c:7a:3e:21:62:f1:7f:63:71:0c:c9:9f:44:db: - a8:27:a2:75:be:6e:81:3e:d7:c0:eb:1b:98:0f:70:5c:34:b2: - 8a:cc:c0:85:18:eb:6e:7a:b3:f7:5a:a1:07:bf:a9:42:92:f3: - 60:22:97:e4:14:a1:07:9b:4e:76:c0:8e:7d:fd:a4:25:c7:47: - ed:ff:1f:73:ac:cc:c3:a5:e9:6f:0a:8e:9b:65:c2:50:85:b5: - a3:a0:53:12:cc:55:87:61:f3:81:ae:10:46:61:bd:44:21:b8: - c2:3d:74:cf:7e:24:35:fa:1c:07:0e:9b:3d:22:ca:ef:31:2f: - 8c:ac:12:bd:ef:40:28:fc:29:67:9f:b2:13:4f:66:24:c4:53: - 19:e9:1e:29:15:ef:e6:6d:b0:7f:2d:67:fd:f3:6c:1b:75:46: - a3:e5:4a:17:e9:a4:d7:0b ------BEGIN CERTIFICATE----- -MIIFaTCCA1GgAwIBAgIJAJK4iNuwisFjMA0GCSqGSIb3DQEBCwUAMFIxCzAJBgNV -BAYTAlNLMRMwEQYDVQQHEwpCcmF0aXNsYXZhMRMwEQYDVQQKEwpEaXNpZyBhLnMu -MRkwFwYDVQQDExBDQSBEaXNpZyBSb290IFIyMB4XDTEyMDcxOTA5MTUzMFoXDTQy -MDcxOTA5MTUzMFowUjELMAkGA1UEBhMCU0sxEzARBgNVBAcTCkJyYXRpc2xhdmEx -EzARBgNVBAoTCkRpc2lnIGEucy4xGTAXBgNVBAMTEENBIERpc2lnIFJvb3QgUjIw -ggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQCio8QACdaFXS1tFPbCw3Oe -NcJxVX6B+6tGUODBfEl45qt5WDza/3wcn9iXAng+a0EE6UG9vgMsRfYvZNSrXaNH -PWSb6WiaxswbP7q+sos0Ai6YVRn8jG+qX9pMzk0DIaPY0jSTVpbLTAwAFjxfGs3I -x2ymrdMxp7zo5eFm1tL7A7RBZckQrg4FY8aAamkw/dLukO8NJ9+flXP04SXabBbe -QTg06ov80egEFGEtQX6sx3dOy1FU+16SGBsEWmjGycT6txOgmLcRK7fWV8x8nhfR -yyX+hk4kLlYMeE2eARKmK6cBZW58Yh2EhN/qwGu1pSqVg8NTEQxzHQuyRpDRQjrO -QG6Vrf/GlK1ul4SOfW+eioANSW1z4nuSHsPzwfPrLgVv2RvPN3YEyLRa5Beny912 -H9AZdugsBbPWnDTYltxhh5EF5EQIM8HauQhl1K6yNg3ruji6DOWbnuuNZt2Zz9aJ -QfYEkoopKW1rOhzndX0CcQ7zwOe9yxndnWCywmZgtrEE7snmhrmaZkCo5xHtgUUD -i/ZnWejBBhG93c+AAk9lQHhcR1DIm+YfgXvkRKhbhZri3lrVx/k6RGZL5DJUfORs -nLMOPReisjQS1n6yqEm70XooQL6iFh/f5DcfEXP7kAplQ6INfPgGAVUzfbANuPT1 -rqVCV3w2EYx7XsQDnYx5nQIDAQABo0IwQDAPBgNVHRMBAf8EBTADAQH/MA4GA1Ud -DwEB/wQEAwIBBjAdBgNVHQ4EFgQUtZn4r7CU9eMg1gqtzk5WpC5uQu0wDQYJKoZI -hvcNAQELBQADggIBACYGXnDnZTPIgm7ZnBc6G3pmsgH2eDtpXi/q/075KMOYKmFM -tCQSin1tERT3nLXK5ryeJ45MGcipvXrA1zYObYVybqjGom32+nNjf7xueQgcnYqf -GopTpti72TVVsRHFqQOzVju5hJMiXn7B9hJSi+osZ7z+Nkz1uM/Rs0mSO9MpDpkb -lvdhuDvEK7Z4bLQjb/D907JedR+Zlais9trhxTF7+9FGs9K8Z7RiVLoJ92Owk6Ka -+elSLotgEqv89WBW7xBci8QaQtyDW2QOy7W81k/BfDxujRNt+3vrMNDcTa/F1bal -TFtxyegxvug4BkihGuLq0t4SOVga/4AOgnXmt8kHbA7v/zjxmHHEt38OFdAlab0i -nSvtBfZGR6ztwPDUO+Ls7pZbkBNOHlY667DvlruWIxG68kOGdGSVyCh13x01utI3 -gzhTODY7z2zp+WsO0PsE6E9312UBeIYMej4hYvF/Y3EMyZ9E26gnonW+boE+18Dr -G5gPcFw0sorMwIUY6256s/daoQe/qUKS82Ail+QUoQebTnbAjn39pCXHR+3/H3Os -zMOl6W8KjptlwlCFtaOgUxLMVYdh84GuEEZhvUQhuMI9dM9+JDX6HAcOmz0iyu8x -L4ysEr3vQCj8KWefshNPZiTEUxnpHikV7+ZtsH8tZ/3zbBt1RqPlShfppNcL ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: - 68:4a:58:70:80:6b:f0:8f:02:fa:f6:de:e8:b0:90:90 - Signature Algorithm: ecdsa-with-SHA384 - Issuer: C=CN, O=WoSign CA Limited, CN=CA WoSign ECC Root - Validity - Not Before: Nov 8 00:58:58 2014 GMT - Not After : Nov 8 00:58:58 2044 GMT - Subject: C=CN, O=WoSign CA Limited, CN=CA WoSign ECC Root - Subject Public Key Info: - Public Key Algorithm: id-ecPublicKey - Public-Key: (384 bit) - pub: - 04:e1:fd:8e:b8:43:24:ab:96:7b:85:c2:ba:0b:ad: - 8d:e0:3a:e3:24:b9:d2:b1:be:88:3a:ca:bf:4a:b8: - f9:ef:2c:2f:af:51:50:3c:47:75:6c:f8:94:b7:9b: - fc:28:1e:c5:54:cc:63:9d:16:4b:53:c1:e7:20:ab: - cd:ac:25:d2:7f:8f:c2:c1:5a:82:5e:30:8b:7a:54: - ce:03:b5:91:7f:aa:94:d0:d1:8a:48:cc:82:05:26: - a1:d5:51:12:d6:7b:36 - ASN1 OID: secp384r1 - X509v3 extensions: - X509v3 Key Usage: critical - Certificate Sign, CRL Sign - X509v3 Basic Constraints: critical - CA:TRUE - X509v3 Subject Key Identifier: - AA:FD:D5:5A:A3:F6:87:8B:32:85:FD:D1:32:5B:80:45:93:F3:03:B8 - Signature Algorithm: ecdsa-with-SHA384 - 30:65:02:31:00:e4:a4:84:b0:81:d5:3d:b0:74:ac:94:a4:e8: - 0e:3d:00:74:4c:a1:97:6b:f9:0d:51:3c:a1:d9:3b:f4:0d:ab: - a9:9f:be:4e:72:ca:85:d4:d9:ec:b5:32:45:18:6f:ab:ad:02: - 30:7d:c7:f7:69:63:2f:a1:e1:98:ef:13:10:d1:79:3f:d1:fe: - ea:3b:7f:de:56:f4:90:b1:15:11:d8:b2:22:15:d0:2f:c3:26: - 2e:6b:f1:91:b2:90:65:f4:9a:e6:90:ee:4a ------BEGIN CERTIFICATE----- -MIICCTCCAY+gAwIBAgIQaEpYcIBr8I8C+vbe6LCQkDAKBggqhkjOPQQDAzBGMQsw -CQYDVQQGEwJDTjEaMBgGA1UEChMRV29TaWduIENBIExpbWl0ZWQxGzAZBgNVBAMT -EkNBIFdvU2lnbiBFQ0MgUm9vdDAeFw0xNDExMDgwMDU4NThaFw00NDExMDgwMDU4 -NThaMEYxCzAJBgNVBAYTAkNOMRowGAYDVQQKExFXb1NpZ24gQ0EgTGltaXRlZDEb -MBkGA1UEAxMSQ0EgV29TaWduIEVDQyBSb290MHYwEAYHKoZIzj0CAQYFK4EEACID -YgAE4f2OuEMkq5Z7hcK6C62N4DrjJLnSsb6IOsq/Srj57ywvr1FQPEd1bPiUt5v8 -KB7FVMxjnRZLU8HnIKvNrCXSf4/CwVqCXjCLelTOA7WRf6qU0NGKSMyCBSah1VES -1ns2o0IwQDAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4E -FgQUqv3VWqP2h4syhf3RMluARZPzA7gwCgYIKoZIzj0EAwMDaAAwZQIxAOSkhLCB -1T2wdKyUpOgOPQB0TKGXa/kNUTyh2Tv0Daupn75OcsqF1NnstTJFGG+rrQIwfcf3 -aWMvoeGY7xMQ0Xk/0f7qO3/eVvSQsRUR2LIiFdAvwyYua/GRspBl9JrmkO5K ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: 407555286 (0x184accd6) - Signature Algorithm: sha256WithRSAEncryption - Issuer: C=CN, O=China Financial Certification Authority, CN=CFCA EV ROOT - Validity - Not Before: Aug 8 03:07:01 2012 GMT - Not After : Dec 31 03:07:01 2029 GMT - Subject: C=CN, O=China Financial Certification Authority, CN=CFCA EV ROOT - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (4096 bit) - Modulus: - 00:d7:5d:6b:cd:10:3f:1f:05:59:d5:05:4d:37:b1: - 0e:ec:98:2b:8e:15:1d:fa:93:4b:17:82:21:71:10: - 52:d7:51:64:70:16:c2:55:69:4d:8e:15:6d:9f:bf: - 0c:1b:c2:e0:a3:67:d6:0c:ac:cf:22:ae:af:77:54: - 2a:4b:4c:8a:53:52:7a:c3:ee:2e:de:b3:71:25:c1: - e9:5d:3d:ee:a1:2f:a3:f7:2a:3c:c9:23:1d:6a:ab: - 1d:a1:a7:f1:f3:ec:a0:d5:44:cf:15:cf:72:2f:1d: - 63:97:e8:99:f9:fd:93:a4:54:80:4c:52:d4:52:ab: - 2e:49:df:90:cd:b8:5f:be:3f:de:a1:ca:4d:20:d4: - 25:e8:84:29:53:b7:b1:88:1f:ff:fa:da:90:9f:0a: - a9:2d:41:3f:b1:f1:18:29:ee:16:59:2c:34:49:1a: - a8:06:d7:a8:88:d2:03:72:7a:32:e2:ea:68:4d:6e: - 2c:96:65:7b:ca:59:fa:f2:e2:dd:ee:30:2c:fb:cc: - 46:ac:c4:63:eb:6f:7f:36:2b:34:73:12:94:7f:df: - cc:26:9e:f1:72:5d:50:65:59:8f:69:b3:87:5e:32: - 6f:c3:18:8a:b5:95:8f:b0:7a:37:de:5a:45:3b:c7: - 36:e1:ef:67:d1:39:d3:97:5b:73:62:19:48:2d:87: - 1c:06:fb:74:98:20:49:73:f0:05:d2:1b:b1:a0:a3: - b7:1b:70:d3:88:69:b9:5a:d6:38:f4:62:dc:25:8b: - 78:bf:f8:e8:7e:b8:5c:c9:95:4f:5f:a7:2d:b9:20: - 6b:cf:6b:dd:f5:0d:f4:82:b7:f4:b2:66:2e:10:28: - f6:97:5a:7b:96:16:8f:01:19:2d:6c:6e:7f:39:58: - 06:64:83:01:83:83:c3:4d:92:dd:32:c6:87:a4:37: - e9:16:ce:aa:2d:68:af:0a:81:65:3a:70:c1:9b:ad: - 4d:6d:54:ca:2a:2d:4b:85:1b:b3:80:e6:70:45:0d: - 6b:5e:35:f0:7f:3b:b8:9c:e4:04:70:89:12:25:93: - da:0a:99:22:60:6a:63:60:4e:76:06:98:4e:bd:83: - ad:1d:58:8a:25:85:d2:c7:65:1e:2d:8e:c6:df:b6: - c6:e1:7f:8a:04:21:15:29:74:f0:3e:9c:90:9d:0c: - 2e:f1:8a:3e:5a:aa:0c:09:1e:c7:d5:3c:a3:ed:97: - c3:1e:34:fa:38:f9:08:0e:e3:c0:5d:2b:83:d1:56: - 6a:c9:b6:a8:54:53:2e:78:32:67:3d:82:7f:74:d0: - fb:e1:b6:05:60:b9:70:db:8e:0b:f9:13:58:6f:71: - 60:10:52:10:b9:c1:41:09:ef:72:1f:67:31:78:ff: - 96:05:8d - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Authority Key Identifier: - keyid:E3:FE:2D:FD:28:D0:0B:B5:BA:B6:A2:C4:BF:06:AA:05:8C:93:FB:2F - - X509v3 Basic Constraints: critical - CA:TRUE - X509v3 Key Usage: critical - Certificate Sign, CRL Sign - X509v3 Subject Key Identifier: - E3:FE:2D:FD:28:D0:0B:B5:BA:B6:A2:C4:BF:06:AA:05:8C:93:FB:2F - Signature Algorithm: sha256WithRSAEncryption - 25:c6:ba:6b:eb:87:cb:de:82:39:96:3d:f0:44:a7:6b:84:73: - 03:de:9d:2b:4f:ba:20:7f:bc:78:b2:cf:97:b0:1b:9c:f3:d7: - 79:2e:f5:48:b6:d2:fb:17:88:e6:d3:7a:3f:ed:53:13:d0:e2: - 2f:6a:79:cb:00:23:28:e6:1e:37:57:35:89:84:c2:76:4f:34: - 36:ad:67:c3:ce:41:06:88:c5:f7:ee:d8:1a:b8:d6:0b:7f:50: - ff:93:aa:17:4b:8c:ec:ed:52:60:b2:a4:06:ea:4e:eb:f4:6b: - 19:fd:eb:f5:1a:e0:25:2a:9a:dc:c7:41:36:f7:c8:74:05:84: - 39:95:39:d6:0b:3b:a4:27:fa:08:d8:5c:1e:f8:04:60:52:11: - 28:28:03:ff:ef:53:66:00:a5:4a:34:16:66:7c:fd:09:a4:ae: - 9e:67:1a:6f:41:0b:6b:06:13:9b:8f:86:71:05:b4:2f:8d:89: - 66:33:29:76:54:9a:11:f8:27:fa:b2:3f:91:e0:ce:0d:1b:f3: - 30:1a:ad:bf:22:5d:1b:d3:bf:25:05:4d:e1:92:1a:7f:99:9f: - 3c:44:93:ca:d4:40:49:6c:80:87:d7:04:3a:c3:32:52:35:0e: - 56:f8:a5:dd:7d:c4:8b:0d:11:1f:53:cb:1e:b2:17:b6:68:77: - 5a:e0:d4:cb:c8:07:ae:f5:3a:2e:8e:37:b7:d0:01:4b:43:29: - 77:8c:39:97:8f:82:5a:f8:51:e5:89:a0:18:e7:68:7f:5d:0a: - 2e:fb:a3:47:0e:3d:a6:23:7a:c6:01:c7:8f:c8:5e:bf:6d:80: - 56:be:8a:24:ba:33:ea:9f:e1:32:11:9e:f1:d2:4f:80:f6:1b: - 40:af:38:9e:11:50:79:73:12:12:cd:e6:6c:9d:2c:88:72:3c: - 30:81:06:91:22:ea:59:ad:da:19:2e:22:c2:8d:b9:8c:87:e0: - 66:bc:73:23:5f:21:64:63:80:48:f5:a0:3c:18:3d:94:c8:48: - 41:1d:40:ba:5e:fe:fe:56:39:a1:c8:cf:5e:9e:19:64:46:10: - da:17:91:b7:05:80:ac:8b:99:92:7d:e7:a2:d8:07:0b:36:27: - e7:48:79:60:8a:c3:d7:13:5c:f8:72:40:df:4a:cb:cf:99:00: - 0a:00:0b:11:95:da:56:45:03:88:0a:9f:67:d0:d5:79:b1:a8: - 8d:40:6d:0d:c2:7a:40:fa:f3:5f:64:47:92:cb:53:b9:bb:59: - ce:4f:fd:d0:15:53:01:d8:df:eb:d9:e6:76:ef:d0:23:bb:3b: - a9:79:b3:d5:02:29:cd:89:a3:96:0f:4a:35:e7:4e:42:c0:75: - cd:07:cf:e6:2c:eb:7b:2e ------BEGIN CERTIFICATE----- -MIIFjTCCA3WgAwIBAgIEGErM1jANBgkqhkiG9w0BAQsFADBWMQswCQYDVQQGEwJD -TjEwMC4GA1UECgwnQ2hpbmEgRmluYW5jaWFsIENlcnRpZmljYXRpb24gQXV0aG9y -aXR5MRUwEwYDVQQDDAxDRkNBIEVWIFJPT1QwHhcNMTIwODA4MDMwNzAxWhcNMjkx -MjMxMDMwNzAxWjBWMQswCQYDVQQGEwJDTjEwMC4GA1UECgwnQ2hpbmEgRmluYW5j -aWFsIENlcnRpZmljYXRpb24gQXV0aG9yaXR5MRUwEwYDVQQDDAxDRkNBIEVWIFJP -T1QwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQDXXWvNED8fBVnVBU03 -sQ7smCuOFR36k0sXgiFxEFLXUWRwFsJVaU2OFW2fvwwbwuCjZ9YMrM8irq93VCpL -TIpTUnrD7i7es3ElweldPe6hL6P3KjzJIx1qqx2hp/Hz7KDVRM8Vz3IvHWOX6Jn5 -/ZOkVIBMUtRSqy5J35DNuF++P96hyk0g1CXohClTt7GIH//62pCfCqktQT+x8Rgp -7hZZLDRJGqgG16iI0gNyejLi6mhNbiyWZXvKWfry4t3uMCz7zEasxGPrb382KzRz -EpR/38wmnvFyXVBlWY9ps4deMm/DGIq1lY+wejfeWkU7xzbh72fROdOXW3NiGUgt -hxwG+3SYIElz8AXSG7Ggo7cbcNOIabla1jj0Ytwli3i/+Oh+uFzJlU9fpy25IGvP -a931DfSCt/SyZi4QKPaXWnuWFo8BGS1sbn85WAZkgwGDg8NNkt0yxoekN+kWzqot -aK8KgWU6cMGbrU1tVMoqLUuFG7OA5nBFDWteNfB/O7ic5ARwiRIlk9oKmSJgamNg -TnYGmE69g60dWIolhdLHZR4tjsbftsbhf4oEIRUpdPA+nJCdDC7xij5aqgwJHsfV -PKPtl8MeNPo4+QgO48BdK4PRVmrJtqhUUy54Mmc9gn900PvhtgVguXDbjgv5E1hv -cWAQUhC5wUEJ73IfZzF4/5YFjQIDAQABo2MwYTAfBgNVHSMEGDAWgBTj/i39KNAL -tbq2osS/BqoFjJP7LzAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIBBjAd -BgNVHQ4EFgQU4/4t/SjQC7W6tqLEvwaqBYyT+y8wDQYJKoZIhvcNAQELBQADggIB -ACXGumvrh8vegjmWPfBEp2uEcwPenStPuiB/vHiyz5ewG5zz13ku9Ui20vsXiObT -ej/tUxPQ4i9qecsAIyjmHjdXNYmEwnZPNDatZ8POQQaIxffu2Bq41gt/UP+TqhdL -jOztUmCypAbqTuv0axn96/Ua4CUqmtzHQTb3yHQFhDmVOdYLO6Qn+gjYXB74BGBS -ESgoA//vU2YApUo0FmZ8/Qmkrp5nGm9BC2sGE5uPhnEFtC+NiWYzKXZUmhH4J/qy -P5Hgzg0b8zAarb8iXRvTvyUFTeGSGn+ZnzxEk8rUQElsgIfXBDrDMlI1Dlb4pd19 -xIsNER9Tyx6yF7Zod1rg1MvIB671Oi6ON7fQAUtDKXeMOZePglr4UeWJoBjnaH9d -Ci77o0cOPaYjesYBx4/IXr9tgFa+iiS6M+qf4TIRnvHST4D2G0CvOJ4RUHlzEhLN -5mydLIhyPDCBBpEi6lmt2hkuIsKNuYyH4Ga8cyNfIWRjgEj1oDwYPZTISEEdQLpe -/v5WOaHIz16eGWRGENoXkbcFgKyLmZJ956LYBws2J+dIeWCKw9cTXPhyQN9Ky8+Z -AAoACxGV2lZFA4gKn2fQ1XmxqI1AbQ3CekD6819kR5LLU7m7Wc5P/dAVUwHY3+vZ -5nbv0CO7O6l5s9UCKc2Jo5YPSjXnTkLAdc0Hz+Ys63su ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: 1228079105 (0x49330001) - Signature Algorithm: sha1WithRSAEncryption - Issuer: C=CN, O=CNNIC, CN=CNNIC ROOT - Validity - Not Before: Apr 16 07:09:14 2007 GMT - Not After : Apr 16 07:09:14 2027 GMT - Subject: C=CN, O=CNNIC, CN=CNNIC ROOT - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (2048 bit) - Modulus: - 00:d3:35:f7:3f:73:77:ad:e8:5b:73:17:c2:d1:6f: - ed:55:bc:6e:ea:e8:a4:79:b2:6c:c3:a3:ef:e1:9f: - b1:3b:48:85:f5:9a:5c:21:22:10:2c:c5:82:ce:da: - e3:9a:6e:37:e1:87:2c:dc:b9:0c:5a:ba:88:55:df: - fd:aa:db:1f:31:ea:01:f1:df:39:01:c1:13:fd:48: - 52:21:c4:55:df:da:d8:b3:54:76:ba:74:b1:b7:7d: - d7:c0:e8:f6:59:c5:4d:c8:bd:ad:1f:14:da:df:58: - 44:25:32:19:2a:c7:7e:7e:8e:ae:38:b0:30:7b:47: - 72:09:31:f0:30:db:c3:1b:76:29:bb:69:76:4e:57: - f9:1b:64:a2:93:56:b7:6f:99:6e:db:0a:04:9c:11: - e3:80:1f:cb:63:94:10:0a:a9:e1:64:82:31:f9:8c: - 27:ed:a6:99:00:f6:70:93:18:f8:a1:34:86:a3:dd: - 7a:c2:18:79:f6:7a:65:35:cf:90:eb:bd:33:93:9f: - 53:ab:73:3b:e6:9b:34:20:2f:1d:ef:a9:1d:63:1a: - a0:80:db:03:2f:f9:26:1a:86:d2:8d:bb:a9:be:52: - 3a:87:67:48:0d:bf:b4:a0:d8:26:be:23:5f:73:37: - 7f:26:e6:92:04:a3:7f:cf:20:a7:b7:f3:3a:ca:cb: - 99:cb - Exponent: 65537 (0x10001) - X509v3 extensions: - Netscape Cert Type: - SSL CA, S/MIME CA, Object Signing CA - X509v3 Authority Key Identifier: - keyid:65:F2:31:AD:2A:F7:F7:DD:52:96:0A:C7:02:C1:0E:EF:A6:D5:3B:11 - - X509v3 Basic Constraints: critical - CA:TRUE - X509v3 Key Usage: - Digital Signature, Non Repudiation, Key Encipherment, Data Encipherment, Key Agreement, Certificate Sign, CRL Sign - X509v3 Subject Key Identifier: - 65:F2:31:AD:2A:F7:F7:DD:52:96:0A:C7:02:C1:0E:EF:A6:D5:3B:11 - Signature Algorithm: sha1WithRSAEncryption - 4b:35:ee:cc:e4:ae:bf:c3:6e:ad:9f:95:3b:4b:3f:5b:1e:df: - 57:29:a2:59:ca:38:e2:b9:1a:ff:9e:e6:6e:32:dd:1e:ae:ea: - 35:b7:f5:93:91:4e:da:42:e1:c3:17:60:50:f2:d1:5c:26:b9: - 82:b7:ea:6d:e4:9c:84:e7:03:79:17:af:98:3d:94:db:c7:ba: - 00:e7:b8:bf:01:57:c1:77:45:32:0c:3b:f1:b4:1c:08:b0:fd: - 51:a0:a1:dd:9a:1d:13:36:9a:6d:b7:c7:3c:b9:e1:c5:d9:17: - fa:83:d5:3d:15:a0:3c:bb:1e:0b:e2:c8:90:3f:a8:86:0c:fc: - f9:8b:5e:85:cb:4f:5b:4b:62:11:47:c5:45:7c:05:2f:41:b1: - 9e:10:69:1b:99:96:e0:55:79:fb:4e:86:99:b8:94:da:86:38: - 6a:93:a3:e7:cb:6e:e5:df:ea:21:55:89:9c:7d:7d:7f:98:f5: - 00:89:ee:e3:84:c0:5c:96:b5:c5:46:ea:46:e0:85:55:b6:1b: - c9:12:d6:c1:cd:cd:80:f3:02:01:3c:c8:69:cb:45:48:63:d8: - 94:d0:ec:85:0e:3b:4e:11:65:f4:82:8c:a6:3d:ae:2e:22:94: - 09:c8:5c:ea:3c:81:5d:16:2a:03:97:16:55:09:db:8a:41:82: - 9e:66:9b:11 ------BEGIN CERTIFICATE----- -MIIDVTCCAj2gAwIBAgIESTMAATANBgkqhkiG9w0BAQUFADAyMQswCQYDVQQGEwJD -TjEOMAwGA1UEChMFQ05OSUMxEzARBgNVBAMTCkNOTklDIFJPT1QwHhcNMDcwNDE2 -MDcwOTE0WhcNMjcwNDE2MDcwOTE0WjAyMQswCQYDVQQGEwJDTjEOMAwGA1UEChMF -Q05OSUMxEzARBgNVBAMTCkNOTklDIFJPT1QwggEiMA0GCSqGSIb3DQEBAQUAA4IB -DwAwggEKAoIBAQDTNfc/c3et6FtzF8LRb+1VvG7q6KR5smzDo+/hn7E7SIX1mlwh -IhAsxYLO2uOabjfhhyzcuQxauohV3/2q2x8x6gHx3zkBwRP9SFIhxFXf2tizVHa6 -dLG3fdfA6PZZxU3Iva0fFNrfWEQlMhkqx35+jq44sDB7R3IJMfAw28Mbdim7aXZO -V/kbZKKTVrdvmW7bCgScEeOAH8tjlBAKqeFkgjH5jCftppkA9nCTGPihNIaj3XrC -GHn2emU1z5DrvTOTn1OrczvmmzQgLx3vqR1jGqCA2wMv+SYahtKNu6m+UjqHZ0gN -v7Sg2Ca+I19zN38m5pIEo3/PIKe38zrKy5nLAgMBAAGjczBxMBEGCWCGSAGG+EIB -AQQEAwIABzAfBgNVHSMEGDAWgBRl8jGtKvf33VKWCscCwQ7vptU7ETAPBgNVHRMB -Af8EBTADAQH/MAsGA1UdDwQEAwIB/jAdBgNVHQ4EFgQUZfIxrSr3991SlgrHAsEO -76bVOxEwDQYJKoZIhvcNAQEFBQADggEBAEs17szkrr/Dbq2flTtLP1se31cpolnK -OOK5Gv+e5m4y3R6u6jW39ZORTtpC4cMXYFDy0VwmuYK36m3knITnA3kXr5g9lNvH -ugDnuL8BV8F3RTIMO/G0HAiw/VGgod2aHRM2mm23xzy54cXZF/qD1T0VoDy7Hgvi -yJA/qIYM/PmLXoXLT1tLYhFHxUV8BS9BsZ4QaRuZluBVeftOhpm4lNqGOGqTo+fL -buXf6iFViZx9fX+Y9QCJ7uOEwFyWtcVG6kbghVW2G8kS1sHNzYDzAgE8yGnLRUhj -2JTQ7IUOO04RZfSCjKY9ri4ilAnIXOo8gV0WKgOXFlUJ24pBgp5mmxE= ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: - 4e:81:2d:8a:82:65:e0:0b:02:ee:3e:35:02:46:e5:3d - Signature Algorithm: sha1WithRSAEncryption - Issuer: C=GB, ST=Greater Manchester, L=Salford, O=COMODO CA Limited, CN=COMODO Certification Authority - Validity - Not Before: Dec 1 00:00:00 2006 GMT - Not After : Dec 31 23:59:59 2029 GMT - Subject: C=GB, ST=Greater Manchester, L=Salford, O=COMODO CA Limited, CN=COMODO Certification Authority - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (2048 bit) - Modulus: - 00:d0:40:8b:8b:72:e3:91:1b:f7:51:c1:1b:54:04: - 98:d3:a9:bf:c1:e6:8a:5d:3b:87:fb:bb:88:ce:0d: - e3:2f:3f:06:96:f0:a2:29:50:99:ae:db:3b:a1:57: - b0:74:51:71:cd:ed:42:91:4d:41:fe:a9:c8:d8:6a: - 86:77:44:bb:59:66:97:50:5e:b4:d4:2c:70:44:cf: - da:37:95:42:69:3c:30:c4:71:b3:52:f0:21:4d:a1: - d8:ba:39:7c:1c:9e:a3:24:9d:f2:83:16:98:aa:16: - 7c:43:9b:15:5b:b7:ae:34:91:fe:d4:62:26:18:46: - 9a:3f:eb:c1:f9:f1:90:57:eb:ac:7a:0d:8b:db:72: - 30:6a:66:d5:e0:46:a3:70:dc:68:d9:ff:04:48:89: - 77:de:b5:e9:fb:67:6d:41:e9:bc:39:bd:32:d9:62: - 02:f1:b1:a8:3d:6e:37:9c:e2:2f:e2:d3:a2:26:8b: - c6:b8:55:43:88:e1:23:3e:a5:d2:24:39:6a:47:ab: - 00:d4:a1:b3:a9:25:fe:0d:3f:a7:1d:ba:d3:51:c1: - 0b:a4:da:ac:38:ef:55:50:24:05:65:46:93:34:4f: - 2d:8d:ad:c6:d4:21:19:d2:8e:ca:05:61:71:07:73: - 47:e5:8a:19:12:bd:04:4d:ce:4e:9c:a5:48:ac:bb: - 26:f7 - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Subject Key Identifier: - 0B:58:E5:8B:C6:4C:15:37:A4:40:A9:30:A9:21:BE:47:36:5A:56:FF - X509v3 Key Usage: critical - Certificate Sign, CRL Sign - X509v3 Basic Constraints: critical - CA:TRUE - X509v3 CRL Distribution Points: - - Full Name: - URI:http://crl.comodoca.com/COMODOCertificationAuthority.crl - - Signature Algorithm: sha1WithRSAEncryption - 3e:98:9e:9b:f6:1b:e9:d7:39:b7:78:ae:1d:72:18:49:d3:87: - e4:43:82:eb:3f:c9:aa:f5:a8:b5:ef:55:7c:21:52:65:f9:d5: - 0d:e1:6c:f4:3e:8c:93:73:91:2e:02:c4:4e:07:71:6f:c0:8f: - 38:61:08:a8:1e:81:0a:c0:2f:20:2f:41:8b:91:dc:48:45:bc: - f1:c6:de:ba:76:6b:33:c8:00:2d:31:46:4c:ed:e7:9d:cf:88: - 94:ff:33:c0:56:e8:24:86:26:b8:d8:38:38:df:2a:6b:dd:12: - cc:c7:3f:47:17:4c:a2:c2:06:96:09:d6:db:fe:3f:3c:46:41: - df:58:e2:56:0f:3c:3b:c1:1c:93:35:d9:38:52:ac:ee:c8:ec: - 2e:30:4e:94:35:b4:24:1f:4b:78:69:da:f2:02:38:cc:95:52: - 93:f0:70:25:59:9c:20:67:c4:ee:f9:8b:57:61:f4:92:76:7d: - 3f:84:8d:55:b7:e8:e5:ac:d5:f1:f5:19:56:a6:5a:fb:90:1c: - af:93:eb:e5:1c:d4:67:97:5d:04:0e:be:0b:83:a6:17:83:b9: - 30:12:a0:c5:33:15:05:b9:0d:fb:c7:05:76:e3:d8:4a:8d:fc: - 34:17:a3:c6:21:28:be:30:45:31:1e:c7:78:be:58:61:38:ac: - 3b:e2:01:65 ------BEGIN CERTIFICATE----- -MIIEHTCCAwWgAwIBAgIQToEtioJl4AsC7j41AkblPTANBgkqhkiG9w0BAQUFADCB -gTELMAkGA1UEBhMCR0IxGzAZBgNVBAgTEkdyZWF0ZXIgTWFuY2hlc3RlcjEQMA4G -A1UEBxMHU2FsZm9yZDEaMBgGA1UEChMRQ09NT0RPIENBIExpbWl0ZWQxJzAlBgNV -BAMTHkNPTU9ETyBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTAeFw0wNjEyMDEwMDAw -MDBaFw0yOTEyMzEyMzU5NTlaMIGBMQswCQYDVQQGEwJHQjEbMBkGA1UECBMSR3Jl -YXRlciBNYW5jaGVzdGVyMRAwDgYDVQQHEwdTYWxmb3JkMRowGAYDVQQKExFDT01P -RE8gQ0EgTGltaXRlZDEnMCUGA1UEAxMeQ09NT0RPIENlcnRpZmljYXRpb24gQXV0 -aG9yaXR5MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA0ECLi3LjkRv3 -UcEbVASY06m/weaKXTuH+7uIzg3jLz8GlvCiKVCZrts7oVewdFFxze1CkU1B/qnI -2GqGd0S7WWaXUF601CxwRM/aN5VCaTwwxHGzUvAhTaHYujl8HJ6jJJ3ygxaYqhZ8 -Q5sVW7euNJH+1GImGEaaP+vB+fGQV+useg2L23IwambV4EajcNxo2f8ESIl33rXp -+2dtQem8Ob0y2WIC8bGoPW43nOIv4tOiJovGuFVDiOEjPqXSJDlqR6sA1KGzqSX+ -DT+nHbrTUcELpNqsOO9VUCQFZUaTNE8tja3G1CEZ0o7KBWFxB3NH5YoZEr0ETc5O -nKVIrLsm9wIDAQABo4GOMIGLMB0GA1UdDgQWBBQLWOWLxkwVN6RAqTCpIb5HNlpW -/zAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/BAUwAwEB/zBJBgNVHR8EQjBAMD6g -PKA6hjhodHRwOi8vY3JsLmNvbW9kb2NhLmNvbS9DT01PRE9DZXJ0aWZpY2F0aW9u -QXV0aG9yaXR5LmNybDANBgkqhkiG9w0BAQUFAAOCAQEAPpiem/Yb6dc5t3iuHXIY -SdOH5EOC6z/JqvWote9VfCFSZfnVDeFs9D6Mk3ORLgLETgdxb8CPOGEIqB6BCsAv -IC9Bi5HcSEW88cbeunZrM8gALTFGTO3nnc+IlP8zwFboJIYmuNg4ON8qa90SzMc/ -RxdMosIGlgnW2/4/PEZB31jiVg88O8EckzXZOFKs7sjsLjBOlDW0JB9LeGna8gI4 -zJVSk/BwJVmcIGfE7vmLV2H0knZ9P4SNVbfo5azV8fUZVqZa+5Acr5Pr5RzUZ5dd -BA6+C4OmF4O5MBKgxTMVBbkN+8cFduPYSo38NBejxiEovjBFMR7HeL5YYTisO+IB -ZQ== ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: - 1f:47:af:aa:62:00:70:50:54:4c:01:9e:9b:63:99:2a - Signature Algorithm: ecdsa-with-SHA384 - Issuer: C=GB, ST=Greater Manchester, L=Salford, O=COMODO CA Limited, CN=COMODO ECC Certification Authority - Validity - Not Before: Mar 6 00:00:00 2008 GMT - Not After : Jan 18 23:59:59 2038 GMT - Subject: C=GB, ST=Greater Manchester, L=Salford, O=COMODO CA Limited, CN=COMODO ECC Certification Authority - Subject Public Key Info: - Public Key Algorithm: id-ecPublicKey - Public-Key: (384 bit) - pub: - 04:03:47:7b:2f:75:c9:82:15:85:fb:75:e4:91:16: - d4:ab:62:99:f5:3e:52:0b:06:ce:41:00:7f:97:e1: - 0a:24:3c:1d:01:04:ee:3d:d2:8d:09:97:0c:e0:75: - e4:fa:fb:77:8a:2a:f5:03:60:4b:36:8b:16:23:16: - ad:09:71:f4:4a:f4:28:50:b4:fe:88:1c:6e:3f:6c: - 2f:2f:09:59:5b:a5:5b:0b:33:99:e2:c3:3d:89:f9: - 6a:2c:ef:b2:d3:06:e9 - ASN1 OID: secp384r1 - X509v3 extensions: - X509v3 Subject Key Identifier: - 75:71:A7:19:48:19:BC:9D:9D:EA:41:47:DF:94:C4:48:77:99:D3:79 - X509v3 Key Usage: critical - Certificate Sign, CRL Sign - X509v3 Basic Constraints: critical - CA:TRUE - Signature Algorithm: ecdsa-with-SHA384 - 30:65:02:31:00:ef:03:5b:7a:ac:b7:78:0a:72:b7:88:df:ff: - b5:46:14:09:0a:fa:a0:e6:7d:08:c6:1a:87:bd:18:a8:73:bd: - 26:ca:60:0c:9d:ce:99:9f:cf:5c:0f:30:e1:be:14:31:ea:02: - 30:14:f4:93:3c:49:a7:33:7a:90:46:47:b3:63:7d:13:9b:4e: - b7:6f:18:37:80:53:fe:dd:20:e0:35:9a:36:d1:c7:01:b9:e6: - dc:dd:f3:ff:1d:2c:3a:16:57:d9:92:39:d6 ------BEGIN CERTIFICATE----- -MIICiTCCAg+gAwIBAgIQH0evqmIAcFBUTAGem2OZKjAKBggqhkjOPQQDAzCBhTEL -MAkGA1UEBhMCR0IxGzAZBgNVBAgTEkdyZWF0ZXIgTWFuY2hlc3RlcjEQMA4GA1UE -BxMHU2FsZm9yZDEaMBgGA1UEChMRQ09NT0RPIENBIExpbWl0ZWQxKzApBgNVBAMT -IkNPTU9ETyBFQ0MgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNMDgwMzA2MDAw -MDAwWhcNMzgwMTE4MjM1OTU5WjCBhTELMAkGA1UEBhMCR0IxGzAZBgNVBAgTEkdy -ZWF0ZXIgTWFuY2hlc3RlcjEQMA4GA1UEBxMHU2FsZm9yZDEaMBgGA1UEChMRQ09N -T0RPIENBIExpbWl0ZWQxKzApBgNVBAMTIkNPTU9ETyBFQ0MgQ2VydGlmaWNhdGlv -biBBdXRob3JpdHkwdjAQBgcqhkjOPQIBBgUrgQQAIgNiAAQDR3svdcmCFYX7deSR -FtSrYpn1PlILBs5BAH+X4QokPB0BBO490o0JlwzgdeT6+3eKKvUDYEs2ixYjFq0J -cfRK9ChQtP6IHG4/bC8vCVlbpVsLM5niwz2J+Wos77LTBumjQjBAMB0GA1UdDgQW -BBR1cacZSBm8nZ3qQUfflMRId5nTeTAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/ -BAUwAwEB/zAKBggqhkjOPQQDAwNoADBlAjEA7wNbeqy3eApyt4jf/7VGFAkK+qDm -fQjGGoe9GKhzvSbKYAydzpmfz1wPMOG+FDHqAjAU9JM8SaczepBGR7NjfRObTrdv -GDeAU/7dIOA1mjbRxwG55tzd8/8dLDoWV9mSOdY= ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: - 4c:aa:f9:ca:db:63:6f:e0:1f:f7:4e:d8:5b:03:86:9d - Signature Algorithm: sha384WithRSAEncryption - Issuer: C=GB, ST=Greater Manchester, L=Salford, O=COMODO CA Limited, CN=COMODO RSA Certification Authority - Validity - Not Before: Jan 19 00:00:00 2010 GMT - Not After : Jan 18 23:59:59 2038 GMT - Subject: C=GB, ST=Greater Manchester, L=Salford, O=COMODO CA Limited, CN=COMODO RSA Certification Authority - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (4096 bit) - Modulus: - 00:91:e8:54:92:d2:0a:56:b1:ac:0d:24:dd:c5:cf: - 44:67:74:99:2b:37:a3:7d:23:70:00:71:bc:53:df: - c4:fa:2a:12:8f:4b:7f:10:56:bd:9f:70:72:b7:61: - 7f:c9:4b:0f:17:a7:3d:e3:b0:04:61:ee:ff:11:97: - c7:f4:86:3e:0a:fa:3e:5c:f9:93:e6:34:7a:d9:14: - 6b:e7:9c:b3:85:a0:82:7a:76:af:71:90:d7:ec:fd: - 0d:fa:9c:6c:fa:df:b0:82:f4:14:7e:f9:be:c4:a6: - 2f:4f:7f:99:7f:b5:fc:67:43:72:bd:0c:00:d6:89: - eb:6b:2c:d3:ed:8f:98:1c:14:ab:7e:e5:e3:6e:fc: - d8:a8:e4:92:24:da:43:6b:62:b8:55:fd:ea:c1:bc: - 6c:b6:8b:f3:0e:8d:9a:e4:9b:6c:69:99:f8:78:48: - 30:45:d5:ad:e1:0d:3c:45:60:fc:32:96:51:27:bc: - 67:c3:ca:2e:b6:6b:ea:46:c7:c7:20:a0:b1:1f:65: - de:48:08:ba:a4:4e:a9:f2:83:46:37:84:eb:e8:cc: - 81:48:43:67:4e:72:2a:9b:5c:bd:4c:1b:28:8a:5c: - 22:7b:b4:ab:98:d9:ee:e0:51:83:c3:09:46:4e:6d: - 3e:99:fa:95:17:da:7c:33:57:41:3c:8d:51:ed:0b: - b6:5c:af:2c:63:1a:df:57:c8:3f:bc:e9:5d:c4:9b: - af:45:99:e2:a3:5a:24:b4:ba:a9:56:3d:cf:6f:aa: - ff:49:58:be:f0:a8:ff:f4:b8:ad:e9:37:fb:ba:b8: - f4:0b:3a:f9:e8:43:42:1e:89:d8:84:cb:13:f1:d9: - bb:e1:89:60:b8:8c:28:56:ac:14:1d:9c:0a:e7:71: - eb:cf:0e:dd:3d:a9:96:a1:48:bd:3c:f7:af:b5:0d: - 22:4c:c0:11:81:ec:56:3b:f6:d3:a2:e2:5b:b7:b2: - 04:22:52:95:80:93:69:e8:8e:4c:65:f1:91:03:2d: - 70:74:02:ea:8b:67:15:29:69:52:02:bb:d7:df:50: - 6a:55:46:bf:a0:a3:28:61:7f:70:d0:c3:a2:aa:2c: - 21:aa:47:ce:28:9c:06:45:76:bf:82:18:27:b4:d5: - ae:b4:cb:50:e6:6b:f4:4c:86:71:30:e9:a6:df:16: - 86:e0:d8:ff:40:dd:fb:d0:42:88:7f:a3:33:3a:2e: - 5c:1e:41:11:81:63:ce:18:71:6b:2b:ec:a6:8a:b7: - 31:5c:3a:6a:47:e0:c3:79:59:d6:20:1a:af:f2:6a: - 98:aa:72:bc:57:4a:d2:4b:9d:bb:10:fc:b0:4c:41: - e5:ed:1d:3d:5e:28:9d:9c:cc:bf:b3:51:da:a7:47: - e5:84:53 - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Subject Key Identifier: - BB:AF:7E:02:3D:FA:A6:F1:3C:84:8E:AD:EE:38:98:EC:D9:32:32:D4 - X509v3 Key Usage: critical - Certificate Sign, CRL Sign - X509v3 Basic Constraints: critical - CA:TRUE - Signature Algorithm: sha384WithRSAEncryption - 0a:f1:d5:46:84:b7:ae:51:bb:6c:b2:4d:41:14:00:93:4c:9c: - cb:e5:c0:54:cf:a0:25:8e:02:f9:fd:b0:a2:0d:f5:20:98:3c: - 13:2d:ac:56:a2:b0:d6:7e:11:92:e9:2e:ba:9e:2e:9a:72:b1: - bd:19:44:6c:61:35:a2:9a:b4:16:12:69:5a:8c:e1:d7:3e:a4: - 1a:e8:2f:03:f4:ae:61:1d:10:1b:2a:a4:8b:7a:c5:fe:05:a6: - e1:c0:d6:c8:fe:9e:ae:8f:2b:ba:3d:99:f8:d8:73:09:58:46: - 6e:a6:9c:f4:d7:27:d3:95:da:37:83:72:1c:d3:73:e0:a2:47: - 99:03:38:5d:d5:49:79:00:29:1c:c7:ec:9b:20:1c:07:24:69: - 57:78:b2:39:fc:3a:84:a0:b5:9c:7c:8d:bf:2e:93:62:27:b7: - 39:da:17:18:ae:bd:3c:09:68:ff:84:9b:3c:d5:d6:0b:03:e3: - 57:9e:14:f7:d1:eb:4f:c8:bd:87:23:b7:b6:49:43:79:85:5c: - ba:eb:92:0b:a1:c6:e8:68:a8:4c:16:b1:1a:99:0a:e8:53:2c: - 92:bb:a1:09:18:75:0c:65:a8:7b:cb:23:b7:1a:c2:28:85:c3: - 1b:ff:d0:2b:62:ef:a4:7b:09:91:98:67:8c:14:01:cd:68:06: - 6a:63:21:75:03:80:88:8a:6e:81:c6:85:f2:a9:a4:2d:e7:f4: - a5:24:10:47:83:ca:cd:f4:8d:79:58:b1:06:9b:e7:1a:2a:d9: - 9d:01:d7:94:7d:ed:03:4a:ca:f0:db:e8:a9:01:3e:f5:56:99: - c9:1e:8e:49:3d:bb:e5:09:b9:e0:4f:49:92:3d:16:82:40:cc: - cc:59:c6:e6:3a:ed:12:2e:69:3c:6c:95:b1:fd:aa:1d:7b:7f: - 86:be:1e:0e:32:46:fb:fb:13:8f:75:7f:4c:8b:4b:46:63:fe: - 00:34:40:70:c1:c3:b9:a1:dd:a6:70:e2:04:b3:41:bc:e9:80: - 91:ea:64:9c:7a:e1:22:03:a9:9c:6e:6f:0e:65:4f:6c:87:87: - 5e:f3:6e:a0:f9:75:a5:9b:40:e8:53:b2:27:9d:4a:b9:c0:77: - 21:8d:ff:87:f2:de:bc:8c:ef:17:df:b7:49:0b:d1:f2:6e:30: - 0b:1a:0e:4e:76:ed:11:fc:f5:e9:56:b2:7d:bf:c7:6d:0a:93: - 8c:a5:d0:c0:b6:1d:be:3a:4e:94:a2:d7:6e:6c:0b:c2:8a:7c: - fa:20:f3:c4:e4:e5:cd:0d:a8:cb:91:92:b1:7c:85:ec:b5:14: - 69:66:0e:82:e7:cd:ce:c8:2d:a6:51:7f:21:c1:35:53:85:06: - 4a:5d:9f:ad:bb:1b:5f:74 ------BEGIN CERTIFICATE----- -MIIF2DCCA8CgAwIBAgIQTKr5yttjb+Af907YWwOGnTANBgkqhkiG9w0BAQwFADCB -hTELMAkGA1UEBhMCR0IxGzAZBgNVBAgTEkdyZWF0ZXIgTWFuY2hlc3RlcjEQMA4G -A1UEBxMHU2FsZm9yZDEaMBgGA1UEChMRQ09NT0RPIENBIExpbWl0ZWQxKzApBgNV -BAMTIkNPTU9ETyBSU0EgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNMTAwMTE5 -MDAwMDAwWhcNMzgwMTE4MjM1OTU5WjCBhTELMAkGA1UEBhMCR0IxGzAZBgNVBAgT -EkdyZWF0ZXIgTWFuY2hlc3RlcjEQMA4GA1UEBxMHU2FsZm9yZDEaMBgGA1UEChMR -Q09NT0RPIENBIExpbWl0ZWQxKzApBgNVBAMTIkNPTU9ETyBSU0EgQ2VydGlmaWNh -dGlvbiBBdXRob3JpdHkwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQCR -6FSS0gpWsawNJN3Fz0RndJkrN6N9I3AAcbxT38T6KhKPS38QVr2fcHK3YX/JSw8X -pz3jsARh7v8Rl8f0hj4K+j5c+ZPmNHrZFGvnnLOFoIJ6dq9xkNfs/Q36nGz637CC -9BR++b7Epi9Pf5l/tfxnQ3K9DADWietrLNPtj5gcFKt+5eNu/Nio5JIk2kNrYrhV -/erBvGy2i/MOjZrkm2xpmfh4SDBF1a3hDTxFYPwyllEnvGfDyi62a+pGx8cgoLEf -Zd5ICLqkTqnyg0Y3hOvozIFIQ2dOciqbXL1MGyiKXCJ7tKuY2e7gUYPDCUZObT6Z -+pUX2nwzV0E8jVHtC7ZcryxjGt9XyD+86V3Em69FmeKjWiS0uqlWPc9vqv9JWL7w -qP/0uK3pN/u6uPQLOvnoQ0IeidiEyxPx2bvhiWC4jChWrBQdnArncevPDt09qZah -SL0896+1DSJMwBGB7FY79tOi4lu3sgQiUpWAk2nojkxl8ZEDLXB0AuqLZxUpaVIC -u9ffUGpVRr+goyhhf3DQw6KqLCGqR84onAZFdr+CGCe01a60y1Dma/RMhnEw6abf -Fobg2P9A3fvQQoh/ozM6LlweQRGBY84YcWsr7KaKtzFcOmpH4MN5WdYgGq/yapiq -crxXStJLnbsQ/LBMQeXtHT1eKJ2czL+zUdqnR+WEUwIDAQABo0IwQDAdBgNVHQ4E -FgQUu69+Aj36pvE8hI6t7jiY7NkyMtQwDgYDVR0PAQH/BAQDAgEGMA8GA1UdEwEB -/wQFMAMBAf8wDQYJKoZIhvcNAQEMBQADggIBAArx1UaEt65Ru2yyTUEUAJNMnMvl -wFTPoCWOAvn9sKIN9SCYPBMtrFaisNZ+EZLpLrqeLppysb0ZRGxhNaKatBYSaVqM -4dc+pBroLwP0rmEdEBsqpIt6xf4FpuHA1sj+nq6PK7o9mfjYcwlYRm6mnPTXJ9OV -2jeDchzTc+CiR5kDOF3VSXkAKRzH7JsgHAckaVd4sjn8OoSgtZx8jb8uk2Intzna -FxiuvTwJaP+EmzzV1gsD41eeFPfR60/IvYcjt7ZJQ3mFXLrrkguhxuhoqEwWsRqZ -CuhTLJK7oQkYdQxlqHvLI7cawiiFwxv/0Cti76R7CZGYZ4wUAc1oBmpjIXUDgIiK -boHGhfKppC3n9KUkEEeDys30jXlYsQab5xoq2Z0B15R97QNKyvDb6KkBPvVWmcke -jkk9u+UJueBPSZI9FoJAzMxZxuY67RIuaTxslbH9qh17f4a+Hg4yRvv7E491f0yL -S0Zj/gA0QHDBw7mh3aZw4gSzQbzpgJHqZJx64SIDqZxubw5lT2yHh17zbqD5daWb -QOhTsiedSrnAdyGN/4fy3ryM7xfft0kL0fJuMAsaDk527RH89elWsn2/x20Kk4yl -0MC2Hb46TpSi125sC8KKfPog88Tk5c0NqMuRkrF8hey1FGlmDoLnzc7ILaZRfyHB -NVOFBkpdn627G190 ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: 0 (0x0) - Signature Algorithm: sha1WithRSAEncryption - Issuer: C=EU, O=AC Camerfirma SA CIF A82743287, OU=http://www.chambersign.org, CN=Chambers of Commerce Root - Validity - Not Before: Sep 30 16:13:43 2003 GMT - Not After : Sep 30 16:13:44 2037 GMT - Subject: C=EU, O=AC Camerfirma SA CIF A82743287, OU=http://www.chambersign.org, CN=Chambers of Commerce Root - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (2048 bit) - Modulus: - 00:b7:36:55:e5:a5:5d:18:30:e0:da:89:54:91:fc: - c8:c7:52:f8:2f:50:d9:ef:b1:75:73:65:47:7d:1b: - 5b:ba:75:c5:fc:a1:88:24:fa:2f:ed:ca:08:4a:39: - 54:c4:51:7a:b5:da:60:ea:38:3c:81:b2:cb:f1:bb: - d9:91:23:3f:48:01:70:75:a9:05:2a:ad:1f:71:f3: - c9:54:3d:1d:06:6a:40:3e:b3:0c:85:ee:5c:1b:79: - c2:62:c4:b8:36:8e:35:5d:01:0c:23:04:47:35:aa: - 9b:60:4e:a0:66:3d:cb:26:0a:9c:40:a1:f4:5d:98: - bf:71:ab:a5:00:68:2a:ed:83:7a:0f:a2:14:b5:d4: - 22:b3:80:b0:3c:0c:5a:51:69:2d:58:18:8f:ed:99: - 9e:f1:ae:e2:95:e6:f6:47:a8:d6:0c:0f:b0:58:58: - db:c3:66:37:9e:9b:91:54:33:37:d2:94:1c:6a:48: - c9:c9:f2:a5:da:a5:0c:23:f7:23:0e:9c:32:55:5e: - 71:9c:84:05:51:9a:2d:fd:e6:4e:2a:34:5a:de:ca: - 40:37:67:0c:54:21:55:77:da:0a:0c:cc:97:ae:80: - dc:94:36:4a:f4:3e:ce:36:13:1e:53:e4:ac:4e:3a: - 05:ec:db:ae:72:9c:38:8b:d0:39:3b:89:0a:3e:77: - fe:75 - Exponent: 3 (0x3) - X509v3 extensions: - X509v3 Basic Constraints: critical - CA:TRUE, pathlen:12 - X509v3 CRL Distribution Points: - - Full Name: - URI:http://crl.chambersign.org/chambersroot.crl - - X509v3 Subject Key Identifier: - E3:94:F5:B1:4D:E9:DB:A1:29:5B:57:8B:4D:76:06:76:E1:D1:A2:8A - X509v3 Key Usage: critical - Certificate Sign, CRL Sign - Netscape Cert Type: - SSL CA, S/MIME CA, Object Signing CA - X509v3 Subject Alternative Name: - email:chambersroot@chambersign.org - X509v3 Issuer Alternative Name: - email:chambersroot@chambersign.org - X509v3 Certificate Policies: - Policy: 1.3.6.1.4.1.17326.10.3.1 - CPS: http://cps.chambersign.org/cps/chambersroot.html - - Signature Algorithm: sha1WithRSAEncryption - 0c:41:97:c2:1a:86:c0:22:7c:9f:fb:90:f3:1a:d1:03:b1:ef: - 13:f9:21:5f:04:9c:da:c9:a5:8d:27:6c:96:87:91:be:41:90: - 01:72:93:e7:1e:7d:5f:f6:89:c6:5d:a7:40:09:3d:ac:49:45: - 45:dc:2e:8d:30:68:b2:09:ba:fb:c3:2f:cc:ba:0b:df:3f:77: - 7b:46:7d:3a:12:24:8e:96:8f:3c:05:0a:6f:d2:94:28:1d:6d: - 0c:c0:2e:88:22:d5:d8:cf:1d:13:c7:f0:48:d7:d7:05:a7:cf: - c7:47:9e:3b:3c:34:c8:80:4f:d4:14:bb:fc:0d:50:f7:fa:b3: - ec:42:5f:a9:dd:6d:c8:f4:75:cf:7b:c1:72:26:b1:01:1c:5c: - 2c:fd:7a:4e:b4:01:c5:05:57:b9:e7:3c:aa:05:d9:88:e9:07: - 46:41:ce:ef:41:81:ae:58:df:83:a2:ae:ca:d7:77:1f:e7:00: - 3c:9d:6f:8e:e4:32:09:1d:4d:78:34:78:34:3c:94:9b:26:ed: - 4f:71:c6:19:7a:bd:20:22:48:5a:fe:4b:7d:03:b7:e7:58:be: - c6:32:4e:74:1e:68:dd:a8:68:5b:b3:3e:ee:62:7d:d9:80:e8: - 0a:75:7a:b7:ee:b4:65:9a:21:90:e0:aa:d0:98:bc:38:b5:73: - 3c:8b:f8:dc ------BEGIN CERTIFICATE----- -MIIEvTCCA6WgAwIBAgIBADANBgkqhkiG9w0BAQUFADB/MQswCQYDVQQGEwJFVTEn -MCUGA1UEChMeQUMgQ2FtZXJmaXJtYSBTQSBDSUYgQTgyNzQzMjg3MSMwIQYDVQQL -ExpodHRwOi8vd3d3LmNoYW1iZXJzaWduLm9yZzEiMCAGA1UEAxMZQ2hhbWJlcnMg -b2YgQ29tbWVyY2UgUm9vdDAeFw0wMzA5MzAxNjEzNDNaFw0zNzA5MzAxNjEzNDRa -MH8xCzAJBgNVBAYTAkVVMScwJQYDVQQKEx5BQyBDYW1lcmZpcm1hIFNBIENJRiBB -ODI3NDMyODcxIzAhBgNVBAsTGmh0dHA6Ly93d3cuY2hhbWJlcnNpZ24ub3JnMSIw -IAYDVQQDExlDaGFtYmVycyBvZiBDb21tZXJjZSBSb290MIIBIDANBgkqhkiG9w0B -AQEFAAOCAQ0AMIIBCAKCAQEAtzZV5aVdGDDg2olUkfzIx1L4L1DZ77F1c2VHfRtb -unXF/KGIJPov7coISjlUxFF6tdpg6jg8gbLL8bvZkSM/SAFwdakFKq0fcfPJVD0d -BmpAPrMMhe5cG3nCYsS4No41XQEMIwRHNaqbYE6gZj3LJgqcQKH0XZi/caulAGgq -7YN6D6IUtdQis4CwPAxaUWktWBiP7Zme8a7ileb2R6jWDA+wWFjbw2Y3npuRVDM3 -0pQcakjJyfKl2qUMI/cjDpwyVV5xnIQFUZot/eZOKjRa3spAN2cMVCFVd9oKDMyX -roDclDZK9D7ONhMeU+SsTjoF7Nuucpw4i9A5O4kKPnf+dQIBA6OCAUQwggFAMBIG -A1UdEwEB/wQIMAYBAf8CAQwwPAYDVR0fBDUwMzAxoC+gLYYraHR0cDovL2NybC5j -aGFtYmVyc2lnbi5vcmcvY2hhbWJlcnNyb290LmNybDAdBgNVHQ4EFgQU45T1sU3p -26EpW1eLTXYGduHRooowDgYDVR0PAQH/BAQDAgEGMBEGCWCGSAGG+EIBAQQEAwIA -BzAnBgNVHREEIDAegRxjaGFtYmVyc3Jvb3RAY2hhbWJlcnNpZ24ub3JnMCcGA1Ud -EgQgMB6BHGNoYW1iZXJzcm9vdEBjaGFtYmVyc2lnbi5vcmcwWAYDVR0gBFEwTzBN -BgsrBgEEAYGHLgoDATA+MDwGCCsGAQUFBwIBFjBodHRwOi8vY3BzLmNoYW1iZXJz -aWduLm9yZy9jcHMvY2hhbWJlcnNyb290Lmh0bWwwDQYJKoZIhvcNAQEFBQADggEB -AAxBl8IahsAifJ/7kPMa0QOx7xP5IV8EnNrJpY0nbJaHkb5BkAFyk+cefV/2icZd -p0AJPaxJRUXcLo0waLIJuvvDL8y6C98/d3tGfToSJI6WjzwFCm/SlCgdbQzALogi -1djPHRPH8EjX1wWnz8dHnjs8NMiAT9QUu/wNUPf6s+xCX6ndbcj0dc97wXImsQEc -XCz9ek60AcUFV7nnPKoF2YjpB0ZBzu9Bga5Y34OirsrXdx/nADydb47kMgkdTXg0 -eDQ8lJsm7U9xxhl6vSAiSFr+S30Dt+dYvsYyTnQeaN2oaFuzPu5ifdmA6Ap1erfu -tGWaIZDgqtCYvDi1czyL+Nw= ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: 0 (0x0) - Signature Algorithm: sha1WithRSAEncryption - Issuer: C=EU, O=AC Camerfirma SA CIF A82743287, OU=http://www.chambersign.org, CN=Global Chambersign Root - Validity - Not Before: Sep 30 16:14:18 2003 GMT - Not After : Sep 30 16:14:18 2037 GMT - Subject: C=EU, O=AC Camerfirma SA CIF A82743287, OU=http://www.chambersign.org, CN=Global Chambersign Root - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (2048 bit) - Modulus: - 00:a2:70:a2:d0:9f:42:ae:5b:17:c7:d8:7d:cf:14: - 83:fc:4f:c9:a1:b7:13:af:8a:d7:9e:3e:04:0a:92: - 8b:60:56:fa:b4:32:2f:88:4d:a1:60:08:f4:b7:09: - 4e:a0:49:2f:49:d6:d3:df:9d:97:5a:9f:94:04:70: - ec:3f:59:d9:b7:cc:66:8b:98:52:28:09:02:df:c5: - 2f:84:8d:7a:97:77:bf:ec:40:9d:25:72:ab:b5:3f: - 32:98:fb:b7:b7:fc:72:84:e5:35:87:f9:55:fa:a3: - 1f:0e:6f:2e:28:dd:69:a0:d9:42:10:c6:f8:b5:44: - c2:d0:43:7f:db:bc:e4:a2:3c:6a:55:78:0a:77:a9: - d8:ea:19:32:b7:2f:fe:5c:3f:1b:ee:b1:98:ec:ca: - ad:7a:69:45:e3:96:0f:55:f6:e6:ed:75:ea:65:e8: - 32:56:93:46:89:a8:25:8a:65:06:ee:6b:bf:79:07: - d0:f1:b7:af:ed:2c:4d:92:bb:c0:a8:5f:a7:67:7d: - 04:f2:15:08:70:ac:92:d6:7d:04:d2:33:fb:4c:b6: - 0b:0b:fb:1a:c9:c4:8d:03:a9:7e:5c:f2:50:ab:12: - a5:a1:cf:48:50:a5:ef:d2:c8:1a:13:fa:b0:7f:b1: - 82:1c:77:6a:0f:5f:dc:0b:95:8f:ef:43:7e:e6:45: - 09:25 - Exponent: 3 (0x3) - X509v3 extensions: - X509v3 Basic Constraints: critical - CA:TRUE, pathlen:12 - X509v3 CRL Distribution Points: - - Full Name: - URI:http://crl.chambersign.org/chambersignroot.crl - - X509v3 Subject Key Identifier: - 43:9C:36:9F:B0:9E:30:4D:C6:CE:5F:AD:10:AB:E5:03:A5:FA:A9:14 - X509v3 Key Usage: critical - Certificate Sign, CRL Sign - Netscape Cert Type: - SSL CA, S/MIME CA, Object Signing CA - X509v3 Subject Alternative Name: - email:chambersignroot@chambersign.org - X509v3 Issuer Alternative Name: - email:chambersignroot@chambersign.org - X509v3 Certificate Policies: - Policy: 1.3.6.1.4.1.17326.10.1.1 - CPS: http://cps.chambersign.org/cps/chambersignroot.html - - Signature Algorithm: sha1WithRSAEncryption - 3c:3b:70:91:f9:04:54:27:91:e1:ed:ed:fe:68:7f:61:5d:e5: - 41:65:4f:32:f1:18:05:94:6a:1c:de:1f:70:db:3e:7b:32:02: - 34:b5:0c:6c:a1:8a:7c:a5:f4:8f:ff:d4:d8:ad:17:d5:2d:04: - d1:3f:58:80:e2:81:59:88:be:c0:e3:46:93:24:fe:90:bd:26: - a2:30:2d:e8:97:26:57:35:89:74:96:18:f6:15:e2:af:24:19: - 56:02:02:b2:ba:0f:14:ea:c6:8a:66:c1:86:45:55:8b:be:92: - be:9c:a4:04:c7:49:3c:9e:e8:29:7a:89:d7:fe:af:ff:68:f5: - a5:17:90:bd:ac:99:cc:a5:86:57:09:67:46:db:d6:16:c2:46: - f1:e4:a9:50:f5:8f:d1:92:15:d3:5f:3e:c6:00:49:3a:6e:58: - b2:d1:d1:27:0d:25:c8:32:f8:20:11:cd:7d:32:33:48:94:54: - 4c:dd:dc:79:c4:30:9f:eb:8e:b8:55:b5:d7:88:5c:c5:6a:24: - 3d:b2:d3:05:03:51:c6:07:ef:cc:14:72:74:3d:6e:72:ce:18: - 28:8c:4a:a0:77:e5:09:2b:45:44:47:ac:b7:67:7f:01:8a:05: - 5a:93:be:a1:c1:ff:f8:e7:0e:67:a4:47:49:76:5d:75:90:1a: - f5:26:8f:f0 ------BEGIN CERTIFICATE----- -MIIExTCCA62gAwIBAgIBADANBgkqhkiG9w0BAQUFADB9MQswCQYDVQQGEwJFVTEn -MCUGA1UEChMeQUMgQ2FtZXJmaXJtYSBTQSBDSUYgQTgyNzQzMjg3MSMwIQYDVQQL -ExpodHRwOi8vd3d3LmNoYW1iZXJzaWduLm9yZzEgMB4GA1UEAxMXR2xvYmFsIENo -YW1iZXJzaWduIFJvb3QwHhcNMDMwOTMwMTYxNDE4WhcNMzcwOTMwMTYxNDE4WjB9 -MQswCQYDVQQGEwJFVTEnMCUGA1UEChMeQUMgQ2FtZXJmaXJtYSBTQSBDSUYgQTgy -NzQzMjg3MSMwIQYDVQQLExpodHRwOi8vd3d3LmNoYW1iZXJzaWduLm9yZzEgMB4G -A1UEAxMXR2xvYmFsIENoYW1iZXJzaWduIFJvb3QwggEgMA0GCSqGSIb3DQEBAQUA -A4IBDQAwggEIAoIBAQCicKLQn0KuWxfH2H3PFIP8T8mhtxOviteePgQKkotgVvq0 -Mi+ITaFgCPS3CU6gSS9J1tPfnZdan5QEcOw/Wdm3zGaLmFIoCQLfxS+EjXqXd7/s -QJ0lcqu1PzKY+7e3/HKE5TWH+VX6ox8Oby4o3Wmg2UIQxvi1RMLQQ3/bvOSiPGpV -eAp3qdjqGTK3L/5cPxvusZjsyq16aUXjlg9V9ubtdepl6DJWk0aJqCWKZQbua795 -B9Dxt6/tLE2Su8CoX6dnfQTyFQhwrJLWfQTSM/tMtgsL+xrJxI0DqX5c8lCrEqWh -z0hQpe/SyBoT+rB/sYIcd2oPX9wLlY/vQ37mRQklAgEDo4IBUDCCAUwwEgYDVR0T -AQH/BAgwBgEB/wIBDDA/BgNVHR8EODA2MDSgMqAwhi5odHRwOi8vY3JsLmNoYW1i -ZXJzaWduLm9yZy9jaGFtYmVyc2lnbnJvb3QuY3JsMB0GA1UdDgQWBBRDnDafsJ4w -TcbOX60Qq+UDpfqpFDAOBgNVHQ8BAf8EBAMCAQYwEQYJYIZIAYb4QgEBBAQDAgAH -MCoGA1UdEQQjMCGBH2NoYW1iZXJzaWducm9vdEBjaGFtYmVyc2lnbi5vcmcwKgYD -VR0SBCMwIYEfY2hhbWJlcnNpZ25yb290QGNoYW1iZXJzaWduLm9yZzBbBgNVHSAE -VDBSMFAGCysGAQQBgYcuCgEBMEEwPwYIKwYBBQUHAgEWM2h0dHA6Ly9jcHMuY2hh -bWJlcnNpZ24ub3JnL2Nwcy9jaGFtYmVyc2lnbnJvb3QuaHRtbDANBgkqhkiG9w0B -AQUFAAOCAQEAPDtwkfkEVCeR4e3t/mh/YV3lQWVPMvEYBZRqHN4fcNs+ezICNLUM -bKGKfKX0j//U2K0X1S0E0T9YgOKBWYi+wONGkyT+kL0mojAt6JcmVzWJdJYY9hXi -ryQZVgICsroPFOrGimbBhkVVi76SvpykBMdJPJ7oKXqJ1/6v/2j1pReQvayZzKWG -VwlnRtvWFsJG8eSpUPWP0ZIV018+xgBJOm5YstHRJw0lyDL4IBHNfTIzSJRUTN3c -ecQwn+uOuFW114hcxWokPbLTBQNRxgfvzBRydD1ucs4YKIxKoHflCStFREest2d/ -AYoFWpO+ocH/+OcOZ6RHSXZddZAa9SaP8A== ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: - 6b:25:da:8a:88:9d:7c:bc:0f:05:b3:b1:7a:61:45:44 - Signature Algorithm: sha256WithRSAEncryption - Issuer: C=CN, O=WoSign CA Limited, CN=Certification Authority of WoSign G2 - Validity - Not Before: Nov 8 00:58:58 2014 GMT - Not After : Nov 8 00:58:58 2044 GMT - Subject: C=CN, O=WoSign CA Limited, CN=Certification Authority of WoSign G2 - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (2048 bit) - Modulus: - 00:be:c5:c4:a0:22:80:49:4f:bf:d9:87:11:c6:53: - e1:bb:0f:bd:60:7f:af:f6:82:0e:1f:dc:b0:8e:3d: - 97:e0:50:3c:8f:3a:ef:66:3b:45:07:9b:20:f8:e3: - d7:25:86:35:90:16:a2:5d:6f:30:19:08:87:0b:7f: - 06:b2:9d:62:8f:de:af:92:a5:60:d4:2b:80:9a:52: - 3f:f5:9a:83:e9:34:5a:cb:d9:d5:62:5c:e6:0e:e0: - df:06:98:0e:80:7c:ca:b4:1d:13:88:6b:0e:a8:24: - 77:03:d0:ee:5b:f3:ca:69:91:35:39:56:c5:6d:e3: - f7:3d:4f:5e:93:38:24:ca:18:e9:24:cb:92:03:dd: - cc:1c:3d:09:70:e4:20:e4:f1:ae:ac:bb:73:69:a3: - 63:3a:0f:45:0f:a1:4a:9a:c2:d1:63:ac:cb:10:f8: - 3d:e6:4e:28:b7:eb:c4:95:b1:ac:fd:5e:ab:fa:41: - cb:5d:9d:4b:dc:f4:7c:76:ef:67:7f:00:7a:8d:d2: - a0:1a:5c:4d:22:e1:b5:da:dd:76:b3:d4:76:df:5e: - b8:8b:98:c8:14:54:cc:6b:17:92:b7:e0:4a:bf:49: - 94:61:0b:38:90:8f:5d:24:6c:25:7b:3b:79:d9:e2: - 7e:9d:ad:9f:98:a1:06:fc:78:14:60:57:f8:ee:80: - 77:b1 - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Key Usage: critical - Certificate Sign, CRL Sign - X509v3 Basic Constraints: critical - CA:TRUE - X509v3 Subject Key Identifier: - FA:60:A9:EB:65:C5:DD:16:14:08:4E:0C:0F:8D:9B:E0:F7:64:AF:67 - Signature Algorithm: sha256WithRSAEncryption - 57:c3:7a:36:82:9c:8d:98:e2:ab:40:aa:47:8f:c7:a7:5b:ed: - 7c:e7:3d:66:5a:3b:31:bb:df:f3:16:33:91:fc:7c:7b:a5:c2: - a6:66:e3:aa:b0:b7:27:98:3f:49:d7:60:67:67:3f:36:4f:4a: - cb:f1:14:fa:5a:87:28:1c:ed:8f:41:32:c6:95:f9:7d:da:bd: - 7b:5b:c2:b0:21:e3:8f:46:dc:21:38:43:74:4c:fb:30:f8:17: - 72:c1:32:fc:c8:91:17:c4:cc:58:37:4e:0b:cc:5a:f7:21:35: - 28:83:6c:60:2d:44:eb:52:8c:50:3d:b5:6c:12:d7:fa:09:bb: - 6c:b2:4a:b1:c5:89:e4:fc:d3:52:d8:61:17:fe:7a:94:84:8f: - 79:b6:33:59:ba:0f:c4:0b:e2:70:a0:4b:78:2e:fa:c8:9f:fd: - af:91:65:0a:78:38:15:e5:97:17:14:dd:f9:e0:2c:34:f8:38: - d0:84:22:00:c0:14:51:18:2b:02:dc:30:5a:f0:e8:01:7c:35: - 3a:23:af:08:e4:af:aa:8e:28:42:49:2e:f0:f5:99:34:be:ed: - 0f:4b:18:e1:d2:24:3c:bb:5d:47:b7:21:f2:8d:d1:0a:99:8e: - e3:6e:3e:ad:70:e0:8f:b9:ca:cc:6e:81:31:f6:7b:9c:7a:79: - e4:67:71:18 ------BEGIN CERTIFICATE----- -MIIDfDCCAmSgAwIBAgIQayXaioidfLwPBbOxemFFRDANBgkqhkiG9w0BAQsFADBY -MQswCQYDVQQGEwJDTjEaMBgGA1UEChMRV29TaWduIENBIExpbWl0ZWQxLTArBgNV -BAMTJENlcnRpZmljYXRpb24gQXV0aG9yaXR5IG9mIFdvU2lnbiBHMjAeFw0xNDEx -MDgwMDU4NThaFw00NDExMDgwMDU4NThaMFgxCzAJBgNVBAYTAkNOMRowGAYDVQQK -ExFXb1NpZ24gQ0EgTGltaXRlZDEtMCsGA1UEAxMkQ2VydGlmaWNhdGlvbiBBdXRo -b3JpdHkgb2YgV29TaWduIEcyMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKC -AQEAvsXEoCKASU+/2YcRxlPhuw+9YH+v9oIOH9ywjj2X4FA8jzrvZjtFB5sg+OPX -JYY1kBaiXW8wGQiHC38Gsp1ij96vkqVg1CuAmlI/9ZqD6TRay9nVYlzmDuDfBpgO -gHzKtB0TiGsOqCR3A9DuW/PKaZE1OVbFbeP3PU9ekzgkyhjpJMuSA93MHD0JcOQg -5PGurLtzaaNjOg9FD6FKmsLRY6zLEPg95k4ot+vElbGs/V6r+kHLXZ1L3PR8du9n -fwB6jdKgGlxNIuG12t12s9R23164i5jIFFTMaxeSt+BKv0mUYQs4kI9dJGwlezt5 -2eJ+na2fmKEG/HgUYFf47oB3sQIDAQABo0IwQDAOBgNVHQ8BAf8EBAMCAQYwDwYD -VR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQU+mCp62XF3RYUCE4MD42b4Pdkr2cwDQYJ -KoZIhvcNAQELBQADggEBAFfDejaCnI2Y4qtAqkePx6db7XznPWZaOzG73/MWM5H8 -fHulwqZm46qwtyeYP0nXYGdnPzZPSsvxFPpahygc7Y9BMsaV+X3avXtbwrAh449G -3CE4Q3RM+zD4F3LBMvzIkRfEzFg3TgvMWvchNSiDbGAtROtSjFA9tWwS1/oJu2yy -SrHFieT801LYYRf+epSEj3m2M1m6D8QL4nCgS3gu+sif/a+RZQp4OBXllxcU3fng -LDT4ONCEIgDAFFEYKwLcMFrw6AF8NTojrwjkr6qOKEJJLvD1mTS+7Q9LGOHSJDy7 -XUe3IfKN0QqZjuNuPq1w4I+5ysxugTH2e5x6eeRncRg= ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: - fe:dc:e3:01:0f:c9:48:ff - Signature Algorithm: sha1WithRSAEncryption - Issuer: C=FR, O=Dhimyotis, CN=Certigna - Validity - Not Before: Jun 29 15:13:05 2007 GMT - Not After : Jun 29 15:13:05 2027 GMT - Subject: C=FR, O=Dhimyotis, CN=Certigna - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (2048 bit) - Modulus: - 00:c8:68:f1:c9:d6:d6:b3:34:75:26:82:1e:ec:b4: - be:ea:5c:e1:26:ed:11:47:61:e1:a2:7c:16:78:40: - 21:e4:60:9e:5a:c8:63:e1:c4:b1:96:92:ff:18:6d: - 69:23:e1:2b:62:f7:dd:e2:36:2f:91:07:b9:48:cf: - 0e:ec:79:b6:2c:e7:34:4b:70:08:25:a3:3c:87:1b: - 19:f2:81:07:0f:38:90:19:d3:11:fe:86:b4:f2:d1: - 5e:1e:1e:96:cd:80:6c:ce:3b:31:93:b6:f2:a0:d0: - a9:95:12:7d:a5:9a:cc:6b:c8:84:56:8a:33:a9:e7: - 22:15:53:16:f0:cc:17:ec:57:5f:e9:a2:0a:98:09: - de:e3:5f:9c:6f:dc:48:e3:85:0b:15:5a:a6:ba:9f: - ac:48:e3:09:b2:f7:f4:32:de:5e:34:be:1c:78:5d: - 42:5b:ce:0e:22:8f:4d:90:d7:7d:32:18:b3:0b:2c: - 6a:bf:8e:3f:14:11:89:20:0e:77:14:b5:3d:94:08: - 87:f7:25:1e:d5:b2:60:00:ec:6f:2a:28:25:6e:2a: - 3e:18:63:17:25:3f:3e:44:20:16:f6:26:c8:25:ae: - 05:4a:b4:e7:63:2c:f3:8c:16:53:7e:5c:fb:11:1a: - 08:c1:46:62:9f:22:b8:f1:c2:8d:69:dc:fa:3a:58: - 06:df - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Basic Constraints: critical - CA:TRUE - X509v3 Subject Key Identifier: - 1A:ED:FE:41:39:90:B4:24:59:BE:01:F2:52:D5:45:F6:5A:39:DC:11 - X509v3 Authority Key Identifier: - keyid:1A:ED:FE:41:39:90:B4:24:59:BE:01:F2:52:D5:45:F6:5A:39:DC:11 - DirName:/C=FR/O=Dhimyotis/CN=Certigna - serial:FE:DC:E3:01:0F:C9:48:FF - - X509v3 Key Usage: critical - Certificate Sign, CRL Sign - Netscape Cert Type: - SSL CA, S/MIME CA, Object Signing CA - Signature Algorithm: sha1WithRSAEncryption - 85:03:1e:92:71:f6:42:af:e1:a3:61:9e:eb:f3:c0:0f:f2:a5: - d4:da:95:e6:d6:be:68:36:3d:7e:6e:1f:4c:8a:ef:d1:0f:21: - 6d:5e:a5:52:63:ce:12:f8:ef:2a:da:6f:eb:37:fe:13:02:c7: - cb:3b:3e:22:6b:da:61:2e:7f:d4:72:3d:dd:30:e1:1e:4c:40: - 19:8c:0f:d7:9c:d1:83:30:7b:98:59:dc:7d:c6:b9:0c:29:4c: - a1:33:a2:eb:67:3a:65:84:d3:96:e2:ed:76:45:70:8f:b5:2b: - de:f9:23:d6:49:6e:3c:14:b5:c6:9f:35:1e:50:d0:c1:8f:6a: - 70:44:02:62:cb:ae:1d:68:41:a7:aa:57:e8:53:aa:07:d2:06: - f6:d5:14:06:0b:91:03:75:2c:6c:72:b5:61:95:9a:0d:8b:b9: - 0d:e7:f5:df:54:cd:de:e6:d8:d6:09:08:97:63:e5:c1:2e:b0: - b7:44:26:c0:26:c0:af:55:30:9e:3b:d5:36:2a:19:04:f4:5c: - 1e:ff:cf:2c:b7:ff:d0:fd:87:40:11:d5:11:23:bb:48:c0:21: - a9:a4:28:2d:fd:15:f8:b0:4e:2b:f4:30:5b:21:fc:11:91:34: - be:41:ef:7b:9d:97:75:ff:97:95:c0:96:58:2f:ea:bb:46:d7: - bb:e4:d9:2e ------BEGIN CERTIFICATE----- -MIIDqDCCApCgAwIBAgIJAP7c4wEPyUj/MA0GCSqGSIb3DQEBBQUAMDQxCzAJBgNV -BAYTAkZSMRIwEAYDVQQKDAlEaGlteW90aXMxETAPBgNVBAMMCENlcnRpZ25hMB4X -DTA3MDYyOTE1MTMwNVoXDTI3MDYyOTE1MTMwNVowNDELMAkGA1UEBhMCRlIxEjAQ -BgNVBAoMCURoaW15b3RpczERMA8GA1UEAwwIQ2VydGlnbmEwggEiMA0GCSqGSIb3 -DQEBAQUAA4IBDwAwggEKAoIBAQDIaPHJ1tazNHUmgh7stL7qXOEm7RFHYeGifBZ4 -QCHkYJ5ayGPhxLGWkv8YbWkj4Sti993iNi+RB7lIzw7sebYs5zRLcAglozyHGxny -gQcPOJAZ0xH+hrTy0V4eHpbNgGzOOzGTtvKg0KmVEn2lmsxryIRWijOp5yIVUxbw -zBfsV1/pogqYCd7jX5xv3EjjhQsVWqa6n6xI4wmy9/Qy3l40vhx4XUJbzg4ij02Q -130yGLMLLGq/jj8UEYkgDncUtT2UCIf3JR7VsmAA7G8qKCVuKj4YYxclPz5EIBb2 -JsglrgVKtOdjLPOMFlN+XPsRGgjBRmKfIrjxwo1p3Po6WAbfAgMBAAGjgbwwgbkw -DwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUGu3+QTmQtCRZvgHyUtVF9lo53BEw -ZAYDVR0jBF0wW4AUGu3+QTmQtCRZvgHyUtVF9lo53BGhOKQ2MDQxCzAJBgNVBAYT -AkZSMRIwEAYDVQQKDAlEaGlteW90aXMxETAPBgNVBAMMCENlcnRpZ25hggkA/tzj -AQ/JSP8wDgYDVR0PAQH/BAQDAgEGMBEGCWCGSAGG+EIBAQQEAwIABzANBgkqhkiG -9w0BAQUFAAOCAQEAhQMeknH2Qq/ho2Ge6/PAD/Kl1NqV5ta+aDY9fm4fTIrv0Q8h -bV6lUmPOEvjvKtpv6zf+EwLHyzs+ImvaYS5/1HI93TDhHkxAGYwP15zRgzB7mFnc -fca5DClMoTOi62c6ZYTTluLtdkVwj7Ur3vkj1kluPBS1xp81HlDQwY9qcEQCYsuu -HWhBp6pX6FOqB9IG9tUUBguRA3UsbHK1YZWaDYu5Def131TN3ubY1gkIl2PlwS6w -t0QmwCbAr1UwnjvVNioZBPRcHv/PLLf/0P2HQBHVESO7SMAhqaQoLf0V+LBOK/Qw -WyH8EZE0vkHve52Xdf+XlcCWWC/qu0bXu+TZLg== ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: 1 (0x1) - Signature Algorithm: sha1WithRSAEncryption - Issuer: C=FR, O=Certinomis, OU=0002 433998903, CN=Certinomis - Autorit\xC3\xA9 Racine - Validity - Not Before: Sep 17 08:28:59 2008 GMT - Not After : Sep 17 08:28:59 2028 GMT - Subject: C=FR, O=Certinomis, OU=0002 433998903, CN=Certinomis - Autorit\xC3\xA9 Racine - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (4096 bit) - Modulus: - 00:9d:85:9f:86:d3:e3:af:c7:b2:6b:6e:33:e0:9e: - b7:42:34:55:9d:f9:81:be:63:d8:23:76:0e:97:54: - cd:99:4c:1a:f1:39:c7:88:d8:17:50:0c:9e:61:da: - c0:4e:55:de:e7:5a:b8:7a:4e:77:87:0d:e5:b8:eb: - fa:9e:5e:7b:1e:c4:cf:28:74:c7:93:f5:14:c6:22: - 28:04:f9:91:c3:ab:27:73:6a:0e:2e:4d:f3:2e:28: - 1f:70:df:55:2f:4e:ed:c7:71:6f:09:72:2e:ed:d5: - 32:97:d0:f1:58:77:d1:60:bc:4e:5e:db:9a:84:f6: - 47:61:45:2b:f6:50:a6:7f:6a:71:27:48:84:35:9e: - ac:fe:69:a9:9e:7a:5e:35:25:fa:b4:a7:49:35:77: - 96:a7:36:5b:e1:cd:df:23:70:d8:5d:4c:a5:08:83: - f1:a6:24:38:13:a8:ec:2f:a8:a1:67:c7:a6:2d:86: - 47:ee:8a:fc:ec:9b:0e:74:f4:2b:49:02:7b:90:75: - 8c:fc:99:39:01:39:d6:4a:89:e5:9e:76:ab:3e:96: - 28:38:26:8b:dd:8d:8c:c0:f6:01:1e:6f:a5:31:12: - 38:7d:95:c2:71:ee:ed:74:ae:e4:36:a2:43:75:d5: - f1:00:9b:e2:e4:d7:cc:42:03:4b:78:7a:e5:7d:bb: - b8:ae:2e:20:93:d3:e4:61:df:71:e1:76:67:97:3f: - b6:df:6a:73:5a:64:22:e5:42:db:cf:81:03:93:d8: - f4:e3:10:e0:72:f6:00:70:ac:f0:c1:7a:0f:05:7f: - cf:34:69:45:b5:93:e4:19:db:52:16:23:05:89:0e: - 8d:48:e4:25:6f:b3:78:bf:62:f5:07:fa:95:24:c2: - 96:b2:e8:a3:23:c2:5d:03:fc:c3:d3:e5:7c:c9:75: - 23:d7:f4:f5:bc:de:e4:df:cd:80:bf:91:88:7d:a7: - 13:b4:39:ba:2c:ba:bd:d1:6b:cc:f3:a5:28:ed:44: - 9e:7d:52:a3:6f:96:2e:19:7e:1c:f3:5b:c7:16:8e: - bb:60:7d:77:66:47:54:82:00:11:60:6c:32:c1:a8: - 38:1b:eb:6e:98:13:d6:ee:38:f5:f0:9f:0e:ef:fe: - 31:81:c1:d2:24:95:2f:53:7a:69:a2:f0:0f:86:45: - 8e:58:82:2b:4c:22:d4:5e:a0:e7:7d:26:27:48:df: - 25:46:8d:4a:28:7c:86:9e:f9:9b:1a:59:b9:65:bf: - 05:dd:b6:42:5d:3d:e6:00:48:82:5e:20:f7:11:82: - de:ca:d8:9f:e6:37:47:26:1e:eb:78:f7:61:c3:41: - 64:58:02:41:f9:da:e0:d1:f8:f9:e8:fd:52:38:b6: - f5:89:df - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Basic Constraints: critical - CA:TRUE - X509v3 Key Usage: critical - Certificate Sign, CRL Sign - X509v3 Subject Key Identifier: - 0D:8C:B6:61:DA:44:B8:D1:14:7D:C3:BE:7D:5E:48:F0:CE:CA:6A:B0 - X509v3 Certificate Policies: - Policy: 1.2.250.1.86.2.2.0.1.1 - - Signature Algorithm: sha1WithRSAEncryption - 24:3e:60:06:7e:1d:ef:3a:3e:db:ea:af:1c:9a:2c:01:0b:f4: - c5:b5:d9:49:31:f4:5d:41:8d:89:0c:4e:ff:6c:a2:fd:ff:e2: - 06:c8:39:9f:f1:5a:a9:dd:22:58:15:a8:8a:d3:b1:e6:32:09: - 82:03:6c:d7:3f:08:c7:f8:b9:ba:00:6d:b9:d6:fc:52:32:5d: - a4:7f:a4:31:94:bb:b6:4c:38:7f:28:30:35:ff:9f:23:53:b7: - b6:ee:14:70:00:40:2b:da:47:ab:34:7e:5e:a7:56:30:61:2b: - 8b:43:ac:fd:b6:88:28:f5:6b:b6:3e:60:4a:ba:42:90:34:67: - 8d:ea:eb:5f:45:54:3b:17:ac:8b:e4:c6:65:0f:ee:d0:8c:5d: - 66:39:ce:32:a7:d8:10:97:c0:7e:34:9c:9f:94:f3:f6:86:1f: - cf:1b:73:ad:94:79:87:68:70:c3:33:a5:70:e7:d8:d5:38:94: - 6f:63:79:eb:bf:0a:0e:08:e7:c5:2f:0f:42:a0:2b:14:40:ff: - 21:e0:05:c5:27:e1:84:11:13:ba:d6:86:1d:41:0b:13:23:89: - d3:c9:0b:e8:8a:ba:7a:a3:a3:73:37:35:80:7d:12:b8:33:77: - 40:38:c0:fa:5e:30:d2:f2:b6:a3:b1:d6:a2:95:97:81:9b:52: - ed:69:4c:ff:80:e4:53:db:54:5b:03:6d:54:5f:b1:b8:ef:24: - bd:6f:9f:11:c3:c7:64:c2:0f:28:62:85:66:5e:1a:7b:b2:b7: - ef:ae:35:c9:19:33:a8:b8:27:db:33:55:bf:68:e1:75:48:44: - 56:fb:cd:d3:48:bb:47:89:3a:ac:69:f5:80:c6:e4:44:50:2f: - 54:c4:aa:43:c5:31:31:58:bd:96:c5:ea:75:6c:9a:75:b1:4d: - f8:f7:97:ff:96:16:f2:97:4d:e8:f6:f3:11:f9:3a:7d:8a:38: - 6e:04:cb:e1:d3:45:15:aa:a5:d1:1d:9d:5d:63:e8:24:e6:36: - 14:e2:87:ad:1b:59:f5:44:9b:fb:d7:77:7c:1f:01:70:62:a1: - 20:1a:a2:c5:1a:28:f4:21:03:ee:2e:d9:c1:80:ea:b9:d9:82: - d6:5b:76:c2:cb:3b:b5:d2:00:f0:a3:0e:e1:ad:6e:40:f7:db: - a0:b4:d0:46:ae:15:d7:44:c2:4d:35:f9:d2:0b:f2:17:f6:ac: - 66:d5:24:b2:4f:d1:1c:99:c0:6e:f5:7d:eb:74:04:b8:f9:4d: - 77:09:d7:b4:cf:07:30:09:f1:b8:00:56:d9:17:16:16:0a:2b: - 86:df:8f:01:19:1a:e5:bb:82:63:ff:be:0b:76:16:5e:37:37: - e6:d8:74:97:a2:99:45:79 ------BEGIN CERTIFICATE----- -MIIFnDCCA4SgAwIBAgIBATANBgkqhkiG9w0BAQUFADBjMQswCQYDVQQGEwJGUjET -MBEGA1UEChMKQ2VydGlub21pczEXMBUGA1UECxMOMDAwMiA0MzM5OTg5MDMxJjAk -BgNVBAMMHUNlcnRpbm9taXMgLSBBdXRvcml0w6kgUmFjaW5lMB4XDTA4MDkxNzA4 -Mjg1OVoXDTI4MDkxNzA4Mjg1OVowYzELMAkGA1UEBhMCRlIxEzARBgNVBAoTCkNl -cnRpbm9taXMxFzAVBgNVBAsTDjAwMDIgNDMzOTk4OTAzMSYwJAYDVQQDDB1DZXJ0 -aW5vbWlzIC0gQXV0b3JpdMOpIFJhY2luZTCCAiIwDQYJKoZIhvcNAQEBBQADggIP -ADCCAgoCggIBAJ2Fn4bT46/HsmtuM+Cet0I0VZ35gb5j2CN2DpdUzZlMGvE5x4jY -F1AMnmHawE5V3udauHpOd4cN5bjr+p5eex7Ezyh0x5P1FMYiKAT5kcOrJ3NqDi5N -8y4oH3DfVS9O7cdxbwlyLu3VMpfQ8Vh30WC8Tl7bmoT2R2FFK/ZQpn9qcSdIhDWe -rP5pqZ56XjUl+rSnSTV3lqc2W+HN3yNw2F1MpQiD8aYkOBOo7C+ooWfHpi2GR+6K -/OybDnT0K0kCe5B1jPyZOQE51kqJ5Z52qz6WKDgmi92NjMD2AR5vpTESOH2VwnHu -7XSu5DaiQ3XV8QCb4uTXzEIDS3h65X27uK4uIJPT5GHfceF2Z5c/tt9qc1pkIuVC -28+BA5PY9OMQ4HL2AHCs8MF6DwV/zzRpRbWT5BnbUhYjBYkOjUjkJW+zeL9i9Qf6 -lSTClrLooyPCXQP8w9PlfMl1I9f09bze5N/NgL+RiH2nE7Q5uiy6vdFrzPOlKO1E -nn1So2+WLhl+HPNbxxaOu2B9d2ZHVIIAEWBsMsGoOBvrbpgT1u449fCfDu/+MYHB -0iSVL1N6aaLwD4ZFjliCK0wi1F6g530mJ0jfJUaNSih8hp75mxpZuWW/Bd22Ql09 -5gBIgl4g9xGC3srYn+Y3RyYe63j3YcNBZFgCQfna4NH4+ej9Uji29YnfAgMBAAGj -WzBZMA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgEGMB0GA1UdDgQWBBQN -jLZh2kS40RR9w759XkjwzspqsDAXBgNVHSAEEDAOMAwGCiqBegFWAgIAAQEwDQYJ -KoZIhvcNAQEFBQADggIBACQ+YAZ+He86PtvqrxyaLAEL9MW12Ukx9F1BjYkMTv9s -ov3/4gbIOZ/xWqndIlgVqIrTseYyCYIDbNc/CMf4uboAbbnW/FIyXaR/pDGUu7ZM -OH8oMDX/nyNTt7buFHAAQCvaR6s0fl6nVjBhK4tDrP22iCj1a7Y+YEq6QpA0Z43q -619FVDsXrIvkxmUP7tCMXWY5zjKn2BCXwH40nJ+U8/aGH88bc62UeYdocMMzpXDn -2NU4lG9jeeu/Cg4I58UvD0KgKxRA/yHgBcUn4YQRE7rWhh1BCxMjidPJC+iKunqj -o3M3NYB9Ergzd0A4wPpeMNLytqOx1qKVl4GbUu1pTP+A5FPbVFsDbVRfsbjvJL1v -nxHDx2TCDyhihWZeGnuyt++uNckZM6i4J9szVb9o4XVIRFb7zdNIu0eJOqxp9YDG -5ERQL1TEqkPFMTFYvZbF6nVsmnWxTfj3l/+WFvKXTej28xH5On2KOG4Ey+HTRRWq -pdEdnV1j6CTmNhTih60bWfVEm/vXd3wfAXBioSAaosUaKPQhA+4u2cGA6rnZgtZb -dsLLO7XSAPCjDuGtbkD326C00EauFddEwk01+dIL8hf2rGbVJLJP0RyZwG71fet0 -BLj5TXcJ17TPBzAJ8bgAVtkXFhYKK4bfjwEZGuW7gmP/vgt2Fl43N+bYdJeimUV5 ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: 1 (0x1) - Signature Algorithm: sha256WithRSAEncryption - Issuer: C=FR, O=Certinomis, OU=0002 433998903, CN=Certinomis - Root CA - Validity - Not Before: Oct 21 09:17:18 2013 GMT - Not After : Oct 21 09:17:18 2033 GMT - Subject: C=FR, O=Certinomis, OU=0002 433998903, CN=Certinomis - Root CA - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (4096 bit) - Modulus: - 00:d4:cc:09:0a:2c:3f:92:f6:7f:14:9e:0b:9c:9a: - 6a:1d:40:30:64:fd:aa:df:0e:1e:06:5b:9f:50:85: - ea:cd:8d:ab:43:67:de:b0:fa:7e:80:96:9e:84:78: - 92:48:d6:e3:39:ee:ce:e4:59:58:97:e5:2e:27:98: - ea:93:a8:77:9b:4a:f0:ef:74:80:2d:eb:30:1f:b5: - d9:c7:80:9c:62:27:91:88:f0:4a:89:dd:dc:88:e6: - 14:f9:d5:03:2f:ff:95:db:bd:9f:ec:2c:fa:14:15: - 59:95:0a:c6:47:7c:69:18:b9:a7:03:f9:ca:76:a9: - cf:c7:6f:b4:5e:05:fe:ee:c1:52:b2:75:32:87:ec: - ed:29:66:3b:f3:4a:16:82:f6:d6:9a:db:72:98:e9: - de:f0:c5:4c:a5:ab:b5:ea:01:e2:8c:2e:64:7f:64: - 6f:fd:a3:25:93:8b:c8:a2:0e:49:8d:34:f0:1f:ec: - 58:45:2e:34:aa:84:50:bd:e7:b2:4a:13:b8:b0:0f: - ae:38:5d:b0:a9:1b:e6:73:c9:5a:a1:d9:66:40:aa: - a9:4d:a6:34:02:ad:84:7e:b2:23:c1:fb:2a:c6:67: - f4:34:b6:b0:95:6a:33:4f:71:44:b5:ad:c0:79:33: - 88:e0:bf:ed:a3:a0:14:b4:9c:09:b0:0a:e3:60:be: - f8:f8:66:88:cd:5b:f1:77:05:e0:b5:73:6e:c1:7d: - 46:2e:8e:4b:27:a6:cd:35:0a:fd:e5:4d:7d:aa:2a: - a3:29:c7:5a:68:04:e8:e5:d6:93:a4:62:c2:c5:e6: - f4:4f:c6:f9:9f:1a:8d:82:49:19:8a:ca:59:43:3a: - e8:0d:32:c1:f4:4c:13:03:6f:6e:a6:3f:91:73:cb: - ca:73:6f:12:20:8b:ee:c0:82:78:de:4b:2e:c2:49: - c3:1d:ed:16:f6:24:f4:27:1b:5c:57:31:dc:55:ee: - a8:1e:6f:6c:ac:e2:45:cc:57:57:8a:75:57:19:e0: - b5:58:99:49:36:31:3c:33:01:6d:16:4a:cd:b8:2a: - 83:84:86:9b:f9:60:d2:1f:6d:91:03:d3:60:a6:d5: - 3d:9a:dd:77:90:3d:35:a4:9f:0f:5e:f5:52:44:69: - b9:c0:ba:dc:cf:7d:df:7c:d9:c4:ac:86:22:32:bc: - 7b:6b:91:ef:7a:f8:17:68:b0:e2:53:55:60:2d:af: - 3e:c2:83:d8:d9:09:2b:f0:c0:64:db:87:8b:91:cc: - 91:eb:04:fd:76:b4:95:9a:e6:14:06:1b:d5:34:1d: - be:d8:ff:74:1c:53:85:99:e0:59:52:4a:61:ed:88: - 9e:6b:49:89:46:7e:20:5a:d9:e7:4a:e5:6a:ee:d2: - 65:11:43 - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Key Usage: critical - Certificate Sign, CRL Sign - X509v3 Basic Constraints: critical - CA:TRUE - X509v3 Subject Key Identifier: - EF:91:4C:F5:A5:C3:30:E8:2F:08:EA:D3:71:22:A4:92:68:78:74:D9 - X509v3 Authority Key Identifier: - keyid:EF:91:4C:F5:A5:C3:30:E8:2F:08:EA:D3:71:22:A4:92:68:78:74:D9 - - Signature Algorithm: sha256WithRSAEncryption - 7e:3d:54:da:22:5d:1a:58:3e:3b:54:27:ba:ba:cc:c8:e3:1a: - 6a:ea:3e:f9:12:eb:56:5f:3d:50:ce:e0:ea:48:26:26:cf:79: - 56:7e:91:1c:99:3f:d0:a1:91:1c:2c:0f:4f:98:95:59:53:bd: - d0:22:d8:88:5d:9c:37:fc:fb:64:c1:78:8c:8b:9a:60:09:ea: - d5:fa:21:5f:d0:74:65:e7:50:c5:bf:2e:b9:0b:0b:ad:b5:b0: - 17:a6:12:8c:d4:62:78:ea:56:6a:ec:0a:d2:40:c3:3c:05:30: - 3e:4d:94:b7:9f:4a:03:d3:7d:27:4b:b6:fe:44:ce:fa:19:33: - 1a:6d:a4:42:d1:dd:cc:c8:c8:d7:16:52:83:4f:35:94:b3:12: - 55:7d:e5:e2:42:eb:e4:9c:93:09:c0:4c:5b:07:ab:c7:6d:11: - a0:50:17:94:23:a8:b5:0a:92:0f:b2:7a:c1:60:2c:38:cc:1a: - a6:5b:ff:f2:0c:e3:aa:1f:1c:dc:b8:a0:93:27:de:63:e3:7f: - 21:9f:3a:e5:9e:fa:e0:13:6a:75:eb:96:5c:62:91:94:8e:67: - 53:b6:89:f8:12:09:cb:6f:52:5b:03:72:86:50:95:08:d4:8d: - 87:86:15:1f:95:24:d8:a4:6f:9a:ce:a4:9d:9b:6d:d2:b2:76: - 06:86:c6:56:08:c5:eb:09:da:36:c2:1b:5b:41:be:61:2a:e3: - 70:e6:b8:a6:f8:b6:5a:c4:bd:21:f7:ff:aa:5f:a1:6c:76:39: - 66:d6:ea:4c:55:e1:00:33:9b:13:98:63:c9:6f:d0:01:20:09: - 37:52:e7:0c:4f:3e:cd:bc:f5:5f:96:27:a7:20:02:95:e0:2e: - e8:07:41:05:1f:15:6e:d6:b0:e4:19:e0:0f:02:93:00:27:72: - c5:8b:d1:54:1f:5d:4a:c3:40:97:7e:55:a6:7c:c1:33:04:14: - 01:1d:49:20:69:0b:19:93:9d:6e:58:22:f7:40:0c:46:0c:23: - 63:f3:39:d2:7f:76:51:a7:f4:c8:a1:f1:0c:76:22:23:46:52: - 29:2d:e2:a3:41:07:56:69:98:d2:05:09:bc:69:c7:5a:61:cd: - 8f:81:60:15:4d:80:dd:90:e2:7d:c4:50:f2:8c:3b:6e:4a:c7: - c6:e6:80:2b:3c:81:bc:11:80:16:10:27:d7:f0:cd:3f:79:cc: - 73:2a:c3:7e:53:91:d6:6e:f8:f5:f3:c7:d0:51:4d:8e:4b:a5: - 5b:e6:19:17:3b:d6:81:09:dc:22:dc:ee:8e:b9:c4:8f:53:e1: - 67:bb:33:b8:88:15:46:cf:ed:69:35:ff:75:0d:46:f3:ce:71: - e1:c5:6b:86:42:06:b9:41 ------BEGIN CERTIFICATE----- -MIIFkjCCA3qgAwIBAgIBATANBgkqhkiG9w0BAQsFADBaMQswCQYDVQQGEwJGUjET -MBEGA1UEChMKQ2VydGlub21pczEXMBUGA1UECxMOMDAwMiA0MzM5OTg5MDMxHTAb -BgNVBAMTFENlcnRpbm9taXMgLSBSb290IENBMB4XDTEzMTAyMTA5MTcxOFoXDTMz -MTAyMTA5MTcxOFowWjELMAkGA1UEBhMCRlIxEzARBgNVBAoTCkNlcnRpbm9taXMx -FzAVBgNVBAsTDjAwMDIgNDMzOTk4OTAzMR0wGwYDVQQDExRDZXJ0aW5vbWlzIC0g -Um9vdCBDQTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBANTMCQosP5L2 -fxSeC5yaah1AMGT9qt8OHgZbn1CF6s2Nq0Nn3rD6foCWnoR4kkjW4znuzuRZWJfl -LieY6pOod5tK8O90gC3rMB+12ceAnGInkYjwSond3IjmFPnVAy//ldu9n+ws+hQV -WZUKxkd8aRi5pwP5ynapz8dvtF4F/u7BUrJ1Mofs7SlmO/NKFoL21prbcpjp3vDF -TKWrteoB4owuZH9kb/2jJZOLyKIOSY008B/sWEUuNKqEUL3nskoTuLAPrjhdsKkb -5nPJWqHZZkCqqU2mNAKthH6yI8H7KsZn9DS2sJVqM09xRLWtwHkziOC/7aOgFLSc -CbAK42C++PhmiM1b8XcF4LVzbsF9Ri6OSyemzTUK/eVNfaoqoynHWmgE6OXWk6Ri -wsXm9E/G+Z8ajYJJGYrKWUM66A0ywfRMEwNvbqY/kXPLynNvEiCL7sCCeN5LLsJJ -wx3tFvYk9CcbXFcx3FXuqB5vbKziRcxXV4p1VxngtViZSTYxPDMBbRZKzbgqg4SG -m/lg0h9tkQPTYKbVPZrdd5A9NaSfD171UkRpucC63M9933zZxKyGIjK8e2uR73r4 -F2iw4lNVYC2vPsKD2NkJK/DAZNuHi5HMkesE/Xa0lZrmFAYb1TQdvtj/dBxThZng -WVJKYe2InmtJiUZ+IFrZ50rlau7SZRFDAgMBAAGjYzBhMA4GA1UdDwEB/wQEAwIB -BjAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBTvkUz1pcMw6C8I6tNxIqSSaHh0 -2TAfBgNVHSMEGDAWgBTvkUz1pcMw6C8I6tNxIqSSaHh02TANBgkqhkiG9w0BAQsF -AAOCAgEAfj1U2iJdGlg+O1QnurrMyOMaauo++RLrVl89UM7g6kgmJs95Vn6RHJk/ -0KGRHCwPT5iVWVO90CLYiF2cN/z7ZMF4jIuaYAnq1fohX9B0ZedQxb8uuQsLrbWw -F6YSjNRieOpWauwK0kDDPAUwPk2Ut59KA9N9J0u2/kTO+hkzGm2kQtHdzMjI1xZS -g081lLMSVX3l4kLr5JyTCcBMWwerx20RoFAXlCOotQqSD7J6wWAsOMwaplv/8gzj -qh8c3LigkyfeY+N/IZ865Z764BNqdeuWXGKRlI5nU7aJ+BIJy29SWwNyhlCVCNSN -h4YVH5Uk2KRvms6knZtt0rJ2BobGVgjF6wnaNsIbW0G+YSrjcOa4pvi2WsS9Iff/ -ql+hbHY5ZtbqTFXhADObE5hjyW/QASAJN1LnDE8+zbz1X5YnpyACleAu6AdBBR8V -btaw5BngDwKTACdyxYvRVB9dSsNAl35VpnzBMwQUAR1JIGkLGZOdblgi90AMRgwj -Y/M50n92Uaf0yKHxDHYiI0ZSKS3io0EHVmmY0gUJvGnHWmHNj4FgFU2A3ZDifcRQ -8ow7bkrHxuaAKzyBvBGAFhAn1/DNP3nMcyrDflOR1m749fPH0FFNjkulW+YZFzvW -gQncItzujrnEj1PhZ7szuIgVRs/taTX/dQ1G885x4cVrhkIGuUE= ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: - 85:bd:4b:f3:d8:da:e3:69:f6:94:d7:5f:c3:a5:44:23 - Signature Algorithm: sha1WithRSAEncryption - Issuer: C=FR, O=Certplus, CN=Class 2 Primary CA - Validity - Not Before: Jul 7 17:05:00 1999 GMT - Not After : Jul 6 23:59:59 2019 GMT - Subject: C=FR, O=Certplus, CN=Class 2 Primary CA - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (2048 bit) - Modulus: - 00:dc:50:96:d0:12:f8:35:d2:08:78:7a:b6:52:70: - fd:6f:ee:cf:b9:11:cb:5d:77:e1:ec:e9:7e:04:8d: - d6:cc:6f:73:43:57:60:ac:33:0a:44:ec:03:5f:1c: - 80:24:91:e5:a8:91:56:12:82:f7:e0:2b:f4:db:ae: - 61:2e:89:10:8d:6b:6c:ba:b3:02:bd:d5:36:c5:48: - 37:23:e2:f0:5a:37:52:33:17:12:e2:d1:60:4d:be: - 2f:41:11:e3:f6:17:25:0c:8b:91:c0:1b:99:7b:99: - 56:0d:af:ee:d2:bc:47:57:e3:79:49:7b:34:89:27: - 24:84:de:b1:ec:e9:58:4e:fe:4e:df:5a:be:41:ad: - ac:08:c5:18:0e:ef:d2:53:ee:6c:d0:9d:12:01:13: - 8d:dc:80:62:f7:95:a9:44:88:4a:71:4e:60:55:9e: - db:23:19:79:56:07:0c:3f:63:0b:5c:b0:e2:be:7e: - 15:fc:94:33:58:41:38:74:c4:e1:8f:8b:df:26:ac: - 1f:b5:8b:3b:b7:43:59:6b:b0:24:a6:6d:90:8b:c4: - 72:ea:5d:33:98:b7:cb:de:5e:7b:ef:94:f1:1b:3e: - ca:c9:21:c1:c5:98:02:aa:a2:f6:5b:77:9b:f5:7e: - 96:55:34:1c:67:69:c0:f1:42:e3:47:ac:fc:28:1c: - 66:55 - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Basic Constraints: - CA:TRUE, pathlen:10 - X509v3 Key Usage: - Certificate Sign, CRL Sign - X509v3 Subject Key Identifier: - E3:73:2D:DF:CB:0E:28:0C:DE:DD:B3:A4:CA:79:B8:8E:BB:E8:30:89 - Netscape Cert Type: - SSL CA, S/MIME CA - X509v3 CRL Distribution Points: - - Full Name: - URI:http://www.certplus.com/CRL/class2.crl - - Signature Algorithm: sha1WithRSAEncryption - a7:54:cf:88:44:19:cb:df:d4:7f:00:df:56:33:62:b5:f7:51: - 01:90:eb:c3:3f:d1:88:44:e9:24:5d:ef:e7:14:bd:20:b7:9a: - 3c:00:fe:6d:9f:db:90:dc:d7:f4:62:d6:8b:70:5d:e7:e5:04: - 48:a9:68:7c:c9:f1:42:f3:6c:7f:c5:7a:7c:1d:51:88:ba:d2: - 0a:3e:27:5d:de:2d:51:4e:d3:13:64:69:e4:2e:e3:d3:e7:9b: - 09:99:a6:e0:95:9b:ce:1a:d7:7f:be:3c:ce:52:b3:11:15:c1: - 0f:17:cd:03:bb:9c:25:15:ba:a2:76:89:fc:06:f1:18:d0:93: - 4b:0e:7c:82:b7:a5:f4:f6:5f:fe:ed:40:a6:9d:84:74:39:b9: - dc:1e:85:16:da:29:1b:86:23:00:c9:bb:89:7e:6e:80:88:1e: - 2f:14:b4:03:24:a8:32:6f:03:9a:47:2c:30:be:56:c6:a7:42: - 02:70:1b:ea:40:d8:ba:05:03:70:07:a4:96:ff:fd:48:33:0a: - e1:dc:a5:81:90:9b:4d:dd:7d:e7:e7:b2:cd:5c:c8:6a:95:f8: - a5:f6:8d:c4:5d:78:08:be:7b:06:d6:49:cf:19:36:50:23:2e: - 08:e6:9e:05:4d:47:18:d5:16:e9:b1:d6:b6:10:d5:bb:97:bf: - a2:8e:b4:54 ------BEGIN CERTIFICATE----- -MIIDkjCCAnqgAwIBAgIRAIW9S/PY2uNp9pTXX8OlRCMwDQYJKoZIhvcNAQEFBQAw -PTELMAkGA1UEBhMCRlIxETAPBgNVBAoTCENlcnRwbHVzMRswGQYDVQQDExJDbGFz -cyAyIFByaW1hcnkgQ0EwHhcNOTkwNzA3MTcwNTAwWhcNMTkwNzA2MjM1OTU5WjA9 -MQswCQYDVQQGEwJGUjERMA8GA1UEChMIQ2VydHBsdXMxGzAZBgNVBAMTEkNsYXNz -IDIgUHJpbWFyeSBDQTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBANxQ -ltAS+DXSCHh6tlJw/W/uz7kRy1134ezpfgSN1sxvc0NXYKwzCkTsA18cgCSR5aiR -VhKC9+Ar9NuuYS6JEI1rbLqzAr3VNsVINyPi8Fo3UjMXEuLRYE2+L0ER4/YXJQyL -kcAbmXuZVg2v7tK8R1fjeUl7NIknJITesezpWE7+Tt9avkGtrAjFGA7v0lPubNCd -EgETjdyAYveVqUSISnFOYFWe2yMZeVYHDD9jC1yw4r5+FfyUM1hBOHTE4Y+L3yas -H7WLO7dDWWuwJKZtkIvEcupdM5i3y95ee++U8Rs+yskhwcWYAqqi9lt3m/V+llU0 -HGdpwPFC40es/CgcZlUCAwEAAaOBjDCBiTAPBgNVHRMECDAGAQH/AgEKMAsGA1Ud -DwQEAwIBBjAdBgNVHQ4EFgQU43Mt38sOKAze3bOkynm4jrvoMIkwEQYJYIZIAYb4 -QgEBBAQDAgEGMDcGA1UdHwQwMC4wLKAqoCiGJmh0dHA6Ly93d3cuY2VydHBsdXMu -Y29tL0NSTC9jbGFzczIuY3JsMA0GCSqGSIb3DQEBBQUAA4IBAQCnVM+IRBnL39R/ -AN9WM2K191EBkOvDP9GIROkkXe/nFL0gt5o8AP5tn9uQ3Nf0YtaLcF3n5QRIqWh8 -yfFC82x/xXp8HVGIutIKPidd3i1RTtMTZGnkLuPT55sJmabglZvOGtd/vjzOUrMR -FcEPF80Du5wlFbqidon8BvEY0JNLDnyCt6X09l/+7UCmnYR0ObncHoUW2ikbhiMA -ybuJfm6AiB4vFLQDJKgybwOaRywwvlbGp0ICcBvqQNi6BQNwB6SW//1IMwrh3KWB -kJtN3X3n57LNXMhqlfil9o3EXXgIvnsG1knPGTZQIy4I5p4FTUcY1Rbpsda2ENW7 -l7+ijrRU ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: - 11:20:55:83:e4:2d:3e:54:56:85:2d:83:37:b7:2c:dc:46:11 - Signature Algorithm: sha512WithRSAEncryption - Issuer: C=FR, O=Certplus, CN=Certplus Root CA G1 - Validity - Not Before: May 26 00:00:00 2014 GMT - Not After : Jan 15 00:00:00 2038 GMT - Subject: C=FR, O=Certplus, CN=Certplus Root CA G1 - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (4096 bit) - Modulus: - 00:da:50:87:b6:da:b8:a9:3e:9d:64:fa:56:33:9a: - 56:3d:16:e5:03:95:b2:34:1c:9a:6d:62:05:d4:d8: - 8f:e7:89:64:9f:ba:db:64:8b:64:e6:79:2a:61:cd: - af:8f:5a:89:91:65:b9:58:fc:b4:03:5f:91:3f:2d: - 10:15:e0:7e:cf:bc:fc:7f:43:67:a8:ad:5e:36:23: - d8:98:b3:4d:f3:43:9e:39:7c:2a:fc:ec:88:d5:88: - ee:70:bd:85:16:2d:ea:4b:89:3c:a3:71:42:fe:1c: - fd:d3:1c:2d:10:b8:86:54:ea:43:b8:db:c6:87:da: - a8:ae:80:25:cf:7a:26:1d:aa:91:b0:48:6f:ae:b5: - de:9e:d8:d7:fa:00:fd:c6:8f:d0:51:bb:62:7d:a4: - b1:8c:b2:ff:20:11:ba:35:63:05:86:47:60:43:33: - 90:f6:47:a2:03:4f:96:4d:9d:4f:c1:ea:ea:9c:a2: - fe:34:2e:de:b7:ca:1b:76:a4:b7:ad:9f:e9:a8:d4: - 78:3f:78:fe:f2:38:09:36:1d:d2:16:02:c8:ec:2a: - 68:af:f5:8e:94:ef:2d:13:7a:1e:42:4a:1d:15:31: - ae:0c:04:57:fc:61:73:f3:31:56:86:31:80:a0:c4: - 11:6e:30:76:e3:94:f0:5f:04:c4:ac:87:72:89:98: - c5:9d:cc:57:08:9a:f4:0c:fc:7d:7a:05:3a:fa:47: - 80:39:b6:cf:84:13:77:6f:27:ea:ff:96:67:17:08: - 6d:e9:0d:d6:23:50:30:b0:15:74:13:3e:e5:2f:ff: - 0e:cd:c4:0b:4a:5d:f0:d8:00:33:49:66:eb:a1:18: - 7c:59:2e:3d:28:b9:61:71:cb:b5:a5:ba:b8:ea:dc: - e2:70:6f:08:6a:dc:87:67:34:ef:df:30:72:dd:f3: - c9:3f:23:ff:35:e1:be:21:29:20:30:81:e4:19:a5: - 20:e9:25:ca:73:31:74:29:be:e2:42:d5:f3:b2:26: - 66:c7:68:fd:19:b3:e7:20:93:99:e8:5d:e0:5e:87: - e7:46:e8:25:9c:0a:29:24:d4:cd:58:86:52:40:24: - b2:7b:0f:98:12:20:24:f6:90:6c:47:c8:0d:bb:18: - 20:2e:d9:fd:fc:8b:f2:29:ea:87:74:95:e0:42:50: - 78:84:04:41:61:b0:f4:21:23:8f:2d:cb:28:21:f2: - 6a:6c:f4:1a:a6:c5:14:b4:37:65:4f:95:fd:80:c8: - f8:72:e5:25:6b:c4:60:b1:7b:6d:8e:4a:8a:73:ce: - 59:fb:70:7a:73:06:13:d9:d3:74:37:24:41:0a:11: - 6f:97:dc:e7:e4:7e:a1:bd:15:f2:ba:87:0f:3d:68: - 8a:16:07 - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Key Usage: critical - Certificate Sign, CRL Sign - X509v3 Basic Constraints: critical - CA:TRUE - X509v3 Subject Key Identifier: - A8:C1:C0:9B:91:A8:43:15:7C:5D:06:27:B4:2A:51:D8:97:0B:81:B1 - X509v3 Authority Key Identifier: - keyid:A8:C1:C0:9B:91:A8:43:15:7C:5D:06:27:B4:2A:51:D8:97:0B:81:B1 - - Signature Algorithm: sha512WithRSAEncryption - 9c:56:6f:01:7e:d1:bd:4c:f5:8a:c6:f0:26:1f:e4:e0:38:18: - cc:32:c3:29:3b:9d:41:29:34:61:c6:d7:f0:00:a1:eb:a4:72: - 8f:94:17:bc:13:2c:75:b4:57:ee:0a:7c:09:7a:dc:d5:ca:a1: - d0:34:13:f8:77:ab:9f:e5:fe:d8:1e:74:8a:85:07:8f:7f:cc: - 79:7a:ca:96:cd:cd:fd:4f:fb:fd:23:0d:90:f5:f4:5e:d3:c6: - 61:7d:9e:11:e0:02:ee:09:04:d9:07:dd:a6:8a:b7:0c:83:24: - bb:83:50:92:fe:60:75:11:3e:d8:9d:b0:8a:7a:b5:e0:9d:9b: - cb:90:52:4b:b0:93:2a:d4:3e:16:33:e5:9e:c6:65:15:3e:64: - 3b:04:3f:db:0c:8f:5f:5c:1d:69:1f:af:f3:e9:21:8c:f3:ef: - 97:f6:9a:b7:19:b6:84:74:9c:a3:54:b5:70:4e:63:d8:57:5d: - 53:21:9b:40:92:43:fa:d6:77:55:33:4f:64:d5:fb:d0:2c:6a: - 8e:6d:25:a6:ef:85:e8:02:c4:53:3e:b9:9e:87:bc:cc:35:1a: - de:a1:e9:8a:63:87:65:1e:11:2a:db:63:77:97:14:be:9a:14: - 99:11:b2:c0:ee:b0:4f:f8:14:21:32:43:4f:9f:ab:a2:cb:a8: - 0f:aa:3b:06:55:c6:12:29:57:08:d4:37:d7:87:27:ad:49:59: - a7:91:ab:44:7a:5e:8d:70:db:97:ce:48:50:b1:73:93:f6:f0: - 83:60:f9:cd:f1:e1:31:fd:5b:7c:71:21:63:14:14:aa:af:c5: - de:93:7e:68:b1:ec:22:a2:aa:90:75:9e:b5:43:72:ea:64:a3: - 84:4b:fd:0c:a8:26:6b:71:97:ee:56:63:66:e8:42:54:f9:c7: - 1d:df:d0:8f:5b:df:c8:30:6f:88:fe:0d:c4:33:1c:53:a8:a3: - fd:48:10:f2:e4:0a:4e:e1:15:57:fc:6e:64:30:c2:55:11:dc: - ea:a9:cd:4a:54:ac:29:63:44:cf:4a:40:a0:d6:68:59:1b:33: - f9:ef:3a:8b:db:20:92:dc:42:84:bf:01:ab:87:c0:d5:20:82: - db:c6:b9:83:85:42:5c:0f:43:3b:6a:49:35:d5:98:f4:15:bf: - fa:61:81:0c:09:20:18:d2:d0:17:0c:cb:48:00:50:e9:76:82: - 8c:64:d7:3a:a0:07:55:cc:1e:31:c0:ef:3a:b4:65:fb:e3:bf: - 42:6b:9e:0f:a8:bd:6b:98:dc:d8:db:cb:8b:a4:dd:d7:59:f4: - 6e:dd:fe:aa:c3:91:d0:2e:42:07:c0:0c:4d:53:cd:24:b1:4c: - 5b:1e:51:f4:df:e9:92:fa ------BEGIN CERTIFICATE----- -MIIFazCCA1OgAwIBAgISESBVg+QtPlRWhS2DN7cs3EYRMA0GCSqGSIb3DQEBDQUA -MD4xCzAJBgNVBAYTAkZSMREwDwYDVQQKDAhDZXJ0cGx1czEcMBoGA1UEAwwTQ2Vy -dHBsdXMgUm9vdCBDQSBHMTAeFw0xNDA1MjYwMDAwMDBaFw0zODAxMTUwMDAwMDBa -MD4xCzAJBgNVBAYTAkZSMREwDwYDVQQKDAhDZXJ0cGx1czEcMBoGA1UEAwwTQ2Vy -dHBsdXMgUm9vdCBDQSBHMTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIB -ANpQh7bauKk+nWT6VjOaVj0W5QOVsjQcmm1iBdTYj+eJZJ+622SLZOZ5KmHNr49a -iZFluVj8tANfkT8tEBXgfs+8/H9DZ6itXjYj2JizTfNDnjl8KvzsiNWI7nC9hRYt -6kuJPKNxQv4c/dMcLRC4hlTqQ7jbxofaqK6AJc96Jh2qkbBIb6613p7Y1/oA/caP -0FG7Yn2ksYyy/yARujVjBYZHYEMzkPZHogNPlk2dT8Hq6pyi/jQu3rfKG3akt62f -6ajUeD94/vI4CTYd0hYCyOwqaK/1jpTvLRN6HkJKHRUxrgwEV/xhc/MxVoYxgKDE -EW4wduOU8F8ExKyHcomYxZ3MVwia9Az8fXoFOvpHgDm2z4QTd28n6v+WZxcIbekN -1iNQMLAVdBM+5S//Ds3EC0pd8NgAM0lm66EYfFkuPSi5YXHLtaW6uOrc4nBvCGrc -h2c0798wct3zyT8j/zXhviEpIDCB5BmlIOklynMxdCm+4kLV87ImZsdo/Rmz5yCT -mehd4F6H50boJZwKKSTUzViGUkAksnsPmBIgJPaQbEfIDbsYIC7Z/fyL8inqh3SV -4EJQeIQEQWGw9CEjjy3LKCHyamz0GqbFFLQ3ZU+V/YDI+HLlJWvEYLF7bY5KinPO -WftwenMGE9nTdDckQQoRb5fc5+R+ob0V8rqHDz1oihYHAgMBAAGjYzBhMA4GA1Ud -DwEB/wQEAwIBBjAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBSowcCbkahDFXxd -Bie0KlHYlwuBsTAfBgNVHSMEGDAWgBSowcCbkahDFXxdBie0KlHYlwuBsTANBgkq -hkiG9w0BAQ0FAAOCAgEAnFZvAX7RvUz1isbwJh/k4DgYzDLDKTudQSk0YcbX8ACh -66Ryj5QXvBMsdbRX7gp8CXrc1cqh0DQT+Hern+X+2B50ioUHj3/MeXrKls3N/U/7 -/SMNkPX0XtPGYX2eEeAC7gkE2Qfdpoq3DIMku4NQkv5gdRE+2J2winq14J2by5BS -S7CTKtQ+FjPlnsZlFT5kOwQ/2wyPX1wdaR+v8+khjPPvl/aatxm2hHSco1S1cE5j -2FddUyGbQJJD+tZ3VTNPZNX70Cxqjm0lpu+F6ALEUz65noe8zDUa3qHpimOHZR4R -Kttjd5cUvpoUmRGywO6wT/gUITJDT5+rosuoD6o7BlXGEilXCNQ314cnrUlZp5Gr -RHpejXDbl85IULFzk/bwg2D5zfHhMf1bfHEhYxQUqq/F3pN+aLHsIqKqkHWetUNy -6mSjhEv9DKgma3GX7lZjZuhCVPnHHd/Qj1vfyDBviP4NxDMcU6ij/UgQ8uQKTuEV -V/xuZDDCVRHc6qnNSlSsKWNEz0pAoNZoWRsz+e86i9sgktxChL8Bq4fA1SCC28a5 -g4VCXA9DO2pJNdWY9BW/+mGBDAkgGNLQFwzLSABQ6XaCjGTXOqAHVcweMcDvOrRl -++O/QmueD6i9a5jc2NvLi6Td11n0bt3+qsOR0C5CB8AMTVPNJLFMWx5R9N/pkvo= ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: - 11:20:d9:91:ce:ae:a3:e8:c5:e7:ff:e9:02:af:cf:73:bc:55 - Signature Algorithm: ecdsa-with-SHA384 - Issuer: C=FR, O=Certplus, CN=Certplus Root CA G2 - Validity - Not Before: May 26 00:00:00 2014 GMT - Not After : Jan 15 00:00:00 2038 GMT - Subject: C=FR, O=Certplus, CN=Certplus Root CA G2 - Subject Public Key Info: - Public Key Algorithm: id-ecPublicKey - Public-Key: (384 bit) - pub: - 04:cd:0f:5b:56:82:df:f0:45:1a:d6:ad:f7:79:f0: - 1d:c9:ac:96:d6:9e:4e:9c:1f:b4:42:11:ca:86:bf: - 6d:fb:85:a3:c5:e5:19:5c:d7:ee:a6:3f:69:67:d8: - 78:e2:a6:c9:c4:db:2d:79:2e:e7:8b:8d:02:6f:31: - 22:4d:06:e3:60:72:45:9d:0e:42:77:9e:ce:cf:e5: - 7f:85:9b:18:e4:fc:cc:2e:72:d3:16:93:4e:ca:99: - 63:5c:a1:05:2a:6c:06 - ASN1 OID: secp384r1 - X509v3 extensions: - X509v3 Key Usage: critical - Certificate Sign, CRL Sign - X509v3 Basic Constraints: critical - CA:TRUE - X509v3 Subject Key Identifier: - DA:83:63:02:79:8E:DA:4C:C6:3C:23:14:D8:8F:C3:20:AB:28:60:59 - X509v3 Authority Key Identifier: - keyid:DA:83:63:02:79:8E:DA:4C:C6:3C:23:14:D8:8F:C3:20:AB:28:60:59 - - Signature Algorithm: ecdsa-with-SHA384 - 30:65:02:30:70:fe:b0:0b:d9:f7:83:97:ec:f3:55:1d:d4:dc: - b3:06:0e:fe:33:98:9d:8b:39:90:6b:94:21:ed:b6:d7:5d:d6: - 4c:d7:21:a7:e7:bf:21:0f:2b:cd:f7:2a:dc:85:07:9d:02:31: - 00:86:14:16:e5:dc:b0:65:c2:c0:8e:14:9f:bf:24:16:68:e5: - bc:f9:79:69:dc:ad:45:2b:f7:b6:31:73:cc:06:a5:53:93:91: - 1a:93:ae:70:6a:67:ba:d7:9e:e5:61:1a:5f ------BEGIN CERTIFICATE----- -MIICHDCCAaKgAwIBAgISESDZkc6uo+jF5//pAq/Pc7xVMAoGCCqGSM49BAMDMD4x -CzAJBgNVBAYTAkZSMREwDwYDVQQKDAhDZXJ0cGx1czEcMBoGA1UEAwwTQ2VydHBs -dXMgUm9vdCBDQSBHMjAeFw0xNDA1MjYwMDAwMDBaFw0zODAxMTUwMDAwMDBaMD4x -CzAJBgNVBAYTAkZSMREwDwYDVQQKDAhDZXJ0cGx1czEcMBoGA1UEAwwTQ2VydHBs -dXMgUm9vdCBDQSBHMjB2MBAGByqGSM49AgEGBSuBBAAiA2IABM0PW1aC3/BFGtat -93nwHcmsltaeTpwftEIRyoa/bfuFo8XlGVzX7qY/aWfYeOKmycTbLXku54uNAm8x -Ik0G42ByRZ0OQneezs/lf4WbGOT8zC5y0xaTTsqZY1yhBSpsBqNjMGEwDgYDVR0P -AQH/BAQDAgEGMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFNqDYwJ5jtpMxjwj -FNiPwyCrKGBZMB8GA1UdIwQYMBaAFNqDYwJ5jtpMxjwjFNiPwyCrKGBZMAoGCCqG -SM49BAMDA2gAMGUCMHD+sAvZ94OX7PNVHdTcswYO/jOYnYs5kGuUIe22113WTNch -p+e/IQ8rzfcq3IUHnQIxAIYUFuXcsGXCwI4Un78kFmjlvPl5adytRSv3tjFzzAal -U5ORGpOucGpnutee5WEaXw== ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: 65568 (0x10020) - Signature Algorithm: sha1WithRSAEncryption - Issuer: C=PL, O=Unizeto Sp. z o.o., CN=Certum CA - Validity - Not Before: Jun 11 10:46:39 2002 GMT - Not After : Jun 11 10:46:39 2027 GMT - Subject: C=PL, O=Unizeto Sp. z o.o., CN=Certum CA - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (2048 bit) - Modulus: - 00:ce:b1:c1:2e:d3:4f:7c:cd:25:ce:18:3e:4f:c4: - 8c:6f:80:6a:73:c8:5b:51:f8:9b:d2:dc:bb:00:5c: - b1:a0:fc:75:03:ee:81:f0:88:ee:23:52:e9:e6:15: - 33:8d:ac:2d:09:c5:76:f9:2b:39:80:89:e4:97:4b: - 90:a5:a8:78:f8:73:43:7b:a4:61:b0:d8:58:cc:e1: - 6c:66:7e:9c:f3:09:5e:55:63:84:d5:a8:ef:f3:b1: - 2e:30:68:b3:c4:3c:d8:ac:6e:8d:99:5a:90:4e:34: - dc:36:9a:8f:81:88:50:b7:6d:96:42:09:f3:d7:95: - 83:0d:41:4b:b0:6a:6b:f8:fc:0f:7e:62:9f:67:c4: - ed:26:5f:10:26:0f:08:4f:f0:a4:57:28:ce:8f:b8: - ed:45:f6:6e:ee:25:5d:aa:6e:39:be:e4:93:2f:d9: - 47:a0:72:eb:fa:a6:5b:af:ca:53:3f:e2:0e:c6:96: - 56:11:6e:f7:e9:66:a9:26:d8:7f:95:53:ed:0a:85: - 88:ba:4f:29:a5:42:8c:5e:b6:fc:85:20:00:aa:68: - 0b:a1:1a:85:01:9c:c4:46:63:82:88:b6:22:b1:ee: - fe:aa:46:59:7e:cf:35:2c:d5:b6:da:5d:f7:48:33: - 14:54:b6:eb:d9:6f:ce:cd:88:d6:ab:1b:da:96:3b: - 1d:59 - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Basic Constraints: critical - CA:TRUE - Signature Algorithm: sha1WithRSAEncryption - b8:8d:ce:ef:e7:14:ba:cf:ee:b0:44:92:6c:b4:39:3e:a2:84: - 6e:ad:b8:21:77:d2:d4:77:82:87:e6:20:41:81:ee:e2:f8:11: - b7:63:d1:17:37:be:19:76:24:1c:04:1a:4c:eb:3d:aa:67:6f: - 2d:d4:cd:fe:65:31:70:c5:1b:a6:02:0a:ba:60:7b:6d:58:c2: - 9a:49:fe:63:32:0b:6b:e3:3a:c0:ac:ab:3b:b0:e8:d3:09:51: - 8c:10:83:c6:34:e0:c5:2b:e0:1a:b6:60:14:27:6c:32:77:8c: - bc:b2:72:98:cf:cd:cc:3f:b9:c8:24:42:14:d6:57:fc:e6:26: - 43:a9:1d:e5:80:90:ce:03:54:28:3e:f7:3f:d3:f8:4d:ed:6a: - 0a:3a:93:13:9b:3b:14:23:13:63:9c:3f:d1:87:27:79:e5:4c: - 51:e3:01:ad:85:5d:1a:3b:b1:d5:73:10:a4:d3:f2:bc:6e:64: - f5:5a:56:90:a8:c7:0e:4c:74:0f:2e:71:3b:f7:c8:47:f4:69: - 6f:15:f2:11:5e:83:1e:9c:7c:52:ae:fd:02:da:12:a8:59:67: - 18:db:bc:70:dd:9b:b1:69:ed:80:ce:89:40:48:6a:0e:35:ca: - 29:66:15:21:94:2c:e8:60:2a:9b:85:4a:40:f3:6b:8a:24:ec: - 06:16:2c:73 ------BEGIN CERTIFICATE----- -MIIDDDCCAfSgAwIBAgIDAQAgMA0GCSqGSIb3DQEBBQUAMD4xCzAJBgNVBAYTAlBM -MRswGQYDVQQKExJVbml6ZXRvIFNwLiB6IG8uby4xEjAQBgNVBAMTCUNlcnR1bSBD -QTAeFw0wMjA2MTExMDQ2MzlaFw0yNzA2MTExMDQ2MzlaMD4xCzAJBgNVBAYTAlBM -MRswGQYDVQQKExJVbml6ZXRvIFNwLiB6IG8uby4xEjAQBgNVBAMTCUNlcnR1bSBD -QTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAM6xwS7TT3zNJc4YPk/E -jG+AanPIW1H4m9LcuwBcsaD8dQPugfCI7iNS6eYVM42sLQnFdvkrOYCJ5JdLkKWo -ePhzQ3ukYbDYWMzhbGZ+nPMJXlVjhNWo7/OxLjBos8Q82KxujZlakE403Daaj4GI -ULdtlkIJ89eVgw1BS7Bqa/j8D35in2fE7SZfECYPCE/wpFcozo+47UX2bu4lXapu -Ob7kky/ZR6By6/qmW6/KUz/iDsaWVhFu9+lmqSbYf5VT7QqFiLpPKaVCjF62/IUg -AKpoC6EahQGcxEZjgoi2IrHu/qpGWX7PNSzVttpd90gzFFS269lvzs2I1qsb2pY7 -HVkCAwEAAaMTMBEwDwYDVR0TAQH/BAUwAwEB/zANBgkqhkiG9w0BAQUFAAOCAQEA -uI3O7+cUus/usESSbLQ5PqKEbq24IXfS1HeCh+YgQYHu4vgRt2PRFze+GXYkHAQa -TOs9qmdvLdTN/mUxcMUbpgIKumB7bVjCmkn+YzILa+M6wKyrO7Do0wlRjBCDxjTg -xSvgGrZgFCdsMneMvLJymM/NzD+5yCRCFNZX/OYmQ6kd5YCQzgNUKD73P9P4Te1q -CjqTE5s7FCMTY5w/0YcneeVMUeMBrYVdGjux1XMQpNPyvG5k9VpWkKjHDkx0Dy5x -O/fIR/RpbxXyEV6DHpx8Uq79AtoSqFlnGNu8cN2bsWntgM6JQEhqDjXKKWYVIZQs -6GAqm4VKQPNriiTsBhYscw== ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: 279744 (0x444c0) - Signature Algorithm: sha1WithRSAEncryption - Issuer: C=PL, O=Unizeto Technologies S.A., OU=Certum Certification Authority, CN=Certum Trusted Network CA - Validity - Not Before: Oct 22 12:07:37 2008 GMT - Not After : Dec 31 12:07:37 2029 GMT - Subject: C=PL, O=Unizeto Technologies S.A., OU=Certum Certification Authority, CN=Certum Trusted Network CA - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (2048 bit) - Modulus: - 00:e3:fb:7d:a3:72:ba:c2:f0:c9:14:87:f5:6b:01: - 4e:e1:6e:40:07:ba:6d:27:5d:7f:f7:5b:2d:b3:5a: - c7:51:5f:ab:a4:32:a6:61:87:b6:6e:0f:86:d2:30: - 02:97:f8:d7:69:57:a1:18:39:5d:6a:64:79:c6:01: - 59:ac:3c:31:4a:38:7c:d2:04:d2:4b:28:e8:20:5f: - 3b:07:a2:cc:4d:73:db:f3:ae:4f:c7:56:d5:5a:a7: - 96:89:fa:f3:ab:68:d4:23:86:59:27:cf:09:27:bc: - ac:6e:72:83:1c:30:72:df:e0:a2:e9:d2:e1:74:75: - 19:bd:2a:9e:7b:15:54:04:1b:d7:43:39:ad:55:28: - c5:e2:1a:bb:f4:c0:e4:ae:38:49:33:cc:76:85:9f: - 39:45:d2:a4:9e:f2:12:8c:51:f8:7c:e4:2d:7f:f5: - ac:5f:eb:16:9f:b1:2d:d1:ba:cc:91:42:77:4c:25: - c9:90:38:6f:db:f0:cc:fb:8e:1e:97:59:3e:d5:60: - 4e:e6:05:28:ed:49:79:13:4b:ba:48:db:2f:f9:72: - d3:39:ca:fe:1f:d8:34:72:f5:b4:40:cf:31:01:c3: - ec:de:11:2d:17:5d:1f:b8:50:d1:5e:19:a7:69:de: - 07:33:28:ca:50:95:f9:a7:54:cb:54:86:50:45:a9: - f9:49 - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Basic Constraints: critical - CA:TRUE - X509v3 Subject Key Identifier: - 08:76:CD:CB:07:FF:24:F6:C5:CD:ED:BB:90:BC:E2:84:37:46:75:F7 - X509v3 Key Usage: critical - Certificate Sign, CRL Sign - Signature Algorithm: sha1WithRSAEncryption - a6:a8:ad:22:ce:01:3d:a6:a3:ff:62:d0:48:9d:8b:5e:72:b0: - 78:44:e3:dc:1c:af:09:fd:23:48:fa:bd:2a:c4:b9:55:04:b5: - 10:a3:8d:27:de:0b:82:63:d0:ee:de:0c:37:79:41:5b:22:b2: - b0:9a:41:5c:a6:70:e0:d4:d0:77:cb:23:d3:00:e0:6c:56:2f: - e1:69:0d:0d:d9:aa:bf:21:81:50:d9:06:a5:a8:ff:95:37:d0: - aa:fe:e2:b3:f5:99:2d:45:84:8a:e5:42:09:d7:74:02:2f:f7: - 89:d8:99:e9:bc:27:d4:47:8d:ba:0d:46:1c:77:cf:14:a4:1c: - b9:a4:31:c4:9c:28:74:03:34:ff:33:19:26:a5:e9:0d:74:b7: - 3e:97:c6:76:e8:27:96:a3:66:dd:e1:ae:f2:41:5b:ca:98:56: - 83:73:70:e4:86:1a:d2:31:41:ba:2f:be:2d:13:5a:76:6f:4e: - e8:4e:81:0e:3f:5b:03:22:a0:12:be:66:58:11:4a:cb:03:c4: - b4:2a:2a:2d:96:17:e0:39:54:bc:48:d3:76:27:9d:9a:2d:06: - a6:c9:ec:39:d2:ab:db:9f:9a:0b:27:02:35:29:b1:40:95:e7: - f9:e8:9c:55:88:19:46:d6:b7:34:f5:7e:ce:39:9a:d9:38:f1: - 51:f7:4f:2c ------BEGIN CERTIFICATE----- -MIIDuzCCAqOgAwIBAgIDBETAMA0GCSqGSIb3DQEBBQUAMH4xCzAJBgNVBAYTAlBM -MSIwIAYDVQQKExlVbml6ZXRvIFRlY2hub2xvZ2llcyBTLkEuMScwJQYDVQQLEx5D -ZXJ0dW0gQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkxIjAgBgNVBAMTGUNlcnR1bSBU -cnVzdGVkIE5ldHdvcmsgQ0EwHhcNMDgxMDIyMTIwNzM3WhcNMjkxMjMxMTIwNzM3 -WjB+MQswCQYDVQQGEwJQTDEiMCAGA1UEChMZVW5pemV0byBUZWNobm9sb2dpZXMg -Uy5BLjEnMCUGA1UECxMeQ2VydHVtIENlcnRpZmljYXRpb24gQXV0aG9yaXR5MSIw -IAYDVQQDExlDZXJ0dW0gVHJ1c3RlZCBOZXR3b3JrIENBMIIBIjANBgkqhkiG9w0B -AQEFAAOCAQ8AMIIBCgKCAQEA4/t9o3K6wvDJFIf1awFO4W5AB7ptJ11/91sts1rH -UV+rpDKmYYe2bg+G0jACl/jXaVehGDldamR5xgFZrDwxSjh80gTSSyjoIF87B6LM -TXPb865Px1bVWqeWifrzq2jUI4ZZJ88JJ7ysbnKDHDBy3+Ci6dLhdHUZvSqeexVU -BBvXQzmtVSjF4hq79MDkrjhJM8x2hZ85RdKknvISjFH4fOQtf/WsX+sWn7Et0brM -kUJ3TCXJkDhv2/DM+44el1k+1WBO5gUo7Ul5E0u6SNsv+XLTOcr+H9g0cvW0QM8x -AcPs3hEtF10fuFDRXhmnad4HMyjKUJX5p1TLVIZQRan5SQIDAQABo0IwQDAPBgNV -HRMBAf8EBTADAQH/MB0GA1UdDgQWBBQIds3LB/8k9sXN7buQvOKEN0Z19zAOBgNV -HQ8BAf8EBAMCAQYwDQYJKoZIhvcNAQEFBQADggEBAKaorSLOAT2mo/9i0Eidi15y -sHhE49wcrwn9I0j6vSrEuVUEtRCjjSfeC4Jj0O7eDDd5QVsisrCaQVymcODU0HfL -I9MA4GxWL+FpDQ3Zqr8hgVDZBqWo/5U30Kr+4rP1mS1FhIrlQgnXdAIv94nYmem8 -J9RHjboNRhx3zxSkHLmkMcScKHQDNP8zGSal6Q10tz6XxnboJ5ajZt3hrvJBW8qY -VoNzcOSGGtIxQbovvi0TWnZvTuhOgQ4/WwMioBK+ZlgRSssDxLQqKi2WF+A5VLxI -03YnnZotBqbJ7DnSq9ufmgsnAjUpsUCV5/nonFWIGUbWtzT1fs45mtk48VH3Tyw= ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: - 21:d6:d0:4a:4f:25:0f:c9:32:37:fc:aa:5e:12:8d:e9 - Signature Algorithm: sha512WithRSAEncryption - Issuer: C=PL, O=Unizeto Technologies S.A., OU=Certum Certification Authority, CN=Certum Trusted Network CA 2 - Validity - Not Before: Oct 6 08:39:56 2011 GMT - Not After : Oct 6 08:39:56 2046 GMT - Subject: C=PL, O=Unizeto Technologies S.A., OU=Certum Certification Authority, CN=Certum Trusted Network CA 2 - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (4096 bit) - Modulus: - 00:bd:f9:78:f8:e6:d5:80:0c:64:9d:86:1b:96:64: - 67:3f:22:3a:1e:75:01:7d:ef:fb:5c:67:8c:c9:cc: - 5c:6b:a9:91:e6:b9:42:e5:20:4b:9b:da:9b:7b:b9: - 99:5d:d9:9b:80:4b:d7:84:40:2b:27:d3:e8:ba:30: - bb:3e:09:1a:a7:49:95:ef:2b:40:24:c2:97:c7:a7: - ee:9b:25:ef:a8:0a:00:97:85:5a:aa:9d:dc:29:c9: - e2:35:07:eb:70:4d:4a:d6:c1:b3:56:b8:a1:41:38: - 9b:d1:fb:31:7f:8f:e0:5f:e1:b1:3f:0f:8e:16:49: - 60:d7:06:8d:18:f9:aa:26:10:ab:2a:d3:d0:d1:67: - 8d:1b:46:be:47:30:d5:2e:72:d1:c5:63:da:e7:63: - 79:44:7e:4b:63:24:89:86:2e:34:3f:29:4c:52:8b: - 2a:a7:c0:e2:91:28:89:b9:c0:5b:f9:1d:d9:e7:27: - ad:ff:9a:02:97:c1:c6:50:92:9b:02:2c:bd:a9:b9: - 34:59:0a:bf:84:4a:ff:df:fe:b3:9f:eb:d9:9e:e0: - 98:23:ec:a6:6b:77:16:2a:db:cc:ad:3b:1c:a4:87: - dc:46:73:5e:19:62:68:45:57:e4:90:82:42:bb:42: - d6:f0:61:e0:c1:a3:3d:66:a3:5d:f4:18:ee:88:c9: - 8d:17:45:29:99:32:75:02:31:ee:29:26:c8:6b:02: - e6:b5:62:45:7f:37:15:5a:23:68:89:d4:3e:de:4e: - 27:b0:f0:40:0c:bc:4d:17:cb:4d:a2:b3:1e:d0:06: - 5a:dd:f6:93:cf:57:75:99:f5:fa:86:1a:67:78:b3: - bf:96:fe:34:dc:bd:e7:52:56:e5:b3:e5:75:7b:d7: - 41:91:05:dc:5d:69:e3:95:0d:43:b9:fc:83:96:39: - 95:7b:6c:80:5a:4f:13:72:c6:d7:7d:29:7a:44:ba: - 52:a4:2a:d5:41:46:09:20:fe:22:a0:b6:5b:30:8d: - bc:89:0c:d5:d7:70:f8:87:52:fd:da:ef:ac:51:2e: - 07:b3:4e:fe:d0:09:da:70:ef:98:fa:56:e6:6d:db: - b5:57:4b:dc:e5:2c:25:15:c8:9e:2e:78:4e:f8:da: - 9c:9e:86:2c:ca:57:f3:1a:e5:c8:92:8b:1a:82:96: - 7a:c3:bc:50:12:69:d8:0e:5a:46:8b:3a:eb:26:fa: - 23:c9:b6:b0:81:be:42:00:a4:f8:d6:fe:30:2e:c7: - d2:46:f6:e5:8e:75:fd:f2:cc:b9:d0:87:5b:cc:06: - 10:60:bb:83:35:b7:5e:67:de:47:ec:99:48:f1:a4: - a1:15:fe:ad:8c:62:8e:39:55:4f:39:16:b9:b1:63: - 9d:ff:b7 - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Basic Constraints: critical - CA:TRUE - X509v3 Subject Key Identifier: - B6:A1:54:39:02:C3:A0:3F:8E:8A:BC:FA:D4:F8:1C:A6:D1:3A:0E:FD - X509v3 Key Usage: critical - Certificate Sign, CRL Sign - Signature Algorithm: sha512WithRSAEncryption - 71:a5:0e:ce:e4:e9:bf:3f:38:d5:89:5a:c4:02:61:fb:4c:c5: - 14:17:2d:8b:4f:53:6b:10:17:fc:65:84:c7:10:49:90:de:db: - c7:26:93:88:26:6f:70:d6:02:5e:39:a0:f7:8f:ab:96:b5:a5: - 13:5c:81:14:6d:0e:81:82:11:1b:8a:4e:c6:4f:a5:dd:62:1e: - 44:df:09:59:f4:5b:77:0b:37:e9:8b:20:c6:f8:0a:4e:2e:58: - 1c:eb:33:d0:cf:86:60:c9:da:fb:80:2f:9e:4c:60:84:78:3d: - 21:64:d6:fb:41:1f:18:0f:e7:c9:75:71:bd:bd:5c:de:34:87: - 3e:41:b0:0e:f6:b9:d6:3f:09:13:96:14:2f:de:9a:1d:5a:b9: - 56:ce:35:3a:b0:5f:70:4d:5e:e3:29:f1:23:28:72:59:b6:ab: - c2:8c:66:26:1c:77:2c:26:76:35:8b:28:a7:69:a0:f9:3b:f5: - 23:dd:85:10:74:c9:90:03:56:91:e7:af:ba:47:d4:12:97:11: - 22:e3:a2:49:94:6c:e7:b7:94:4b:ba:2d:a4:da:33:8b:4c:a6: - 44:ff:5a:3c:c6:1d:64:d8:b5:31:e4:a6:3c:7a:a8:57:0b:db: - ed:61:1a:cb:f1:ce:73:77:63:a4:87:6f:4c:51:38:d6:e4:5f: - c7:9f:b6:81:2a:e4:85:48:79:58:5e:3b:f8:db:02:82:67:c1: - 39:db:c3:74:4b:3d:36:1e:f9:29:93:88:68:5b:a8:44:19:21: - f0:a7:e8:81:0d:2c:e8:93:36:b4:37:b2:ca:b0:1b:26:7a:9a: - 25:1f:9a:9a:80:9e:4b:2a:3f:fb:a3:9a:fe:73:32:71:c2:9e: - c6:72:e1:8a:68:27:f1:e4:0f:b4:c4:4c:a5:61:93:f8:97:10: - 07:2a:30:25:a9:b9:c8:71:b8:ef:68:cc:2d:7e:f5:e0:7e:0f: - 82:a8:6f:b6:ba:6c:83:43:77:cd:8a:92:17:a1:9e:5b:78:16: - 3d:45:e2:33:72:dd:e1:66:ca:99:d3:c9:c5:26:fd:0d:68:04: - 46:ae:b6:d9:9b:8c:be:19:be:b1:c6:f2:19:e3:5c:02:ca:2c: - d8:6f:4a:07:d9:c9:35:da:40:75:f2:c4:a7:19:6f:9e:42:10: - 98:75:e6:95:8b:60:bc:ed:c5:12:d7:8a:ce:d5:98:5c:56:96: - 03:c5:ee:77:06:35:ff:cf:e4:ee:3f:13:61:ee:db:da:2d:85: - f0:cd:ae:9d:b2:18:09:45:c3:92:a1:72:17:fc:47:b6:a0:0b: - 2c:f1:c4:de:43:68:08:6a:5f:3b:f0:76:63:fb:cc:06:2c:a6: - c6:e2:0e:b5:b9:be:24:8f ------BEGIN CERTIFICATE----- -MIIF0jCCA7qgAwIBAgIQIdbQSk8lD8kyN/yqXhKN6TANBgkqhkiG9w0BAQ0FADCB -gDELMAkGA1UEBhMCUEwxIjAgBgNVBAoTGVVuaXpldG8gVGVjaG5vbG9naWVzIFMu -QS4xJzAlBgNVBAsTHkNlcnR1bSBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTEkMCIG -A1UEAxMbQ2VydHVtIFRydXN0ZWQgTmV0d29yayBDQSAyMCIYDzIwMTExMDA2MDgz -OTU2WhgPMjA0NjEwMDYwODM5NTZaMIGAMQswCQYDVQQGEwJQTDEiMCAGA1UEChMZ -VW5pemV0byBUZWNobm9sb2dpZXMgUy5BLjEnMCUGA1UECxMeQ2VydHVtIENlcnRp -ZmljYXRpb24gQXV0aG9yaXR5MSQwIgYDVQQDExtDZXJ0dW0gVHJ1c3RlZCBOZXR3 -b3JrIENBIDIwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQC9+Xj45tWA -DGSdhhuWZGc/IjoedQF97/tcZ4zJzFxrqZHmuULlIEub2pt7uZld2ZuAS9eEQCsn -0+i6MLs+CRqnSZXvK0AkwpfHp+6bJe+oCgCXhVqqndwpyeI1B+twTUrWwbNWuKFB -OJvR+zF/j+Bf4bE/D44WSWDXBo0Y+aomEKsq09DRZ40bRr5HMNUuctHFY9rnY3lE -fktjJImGLjQ/KUxSiyqnwOKRKIm5wFv5HdnnJ63/mgKXwcZQkpsCLL2puTRZCr+E -Sv/f/rOf69me4Jgj7KZrdxYq28ytOxykh9xGc14ZYmhFV+SQgkK7QtbwYeDBoz1m -o130GO6IyY0XRSmZMnUCMe4pJshrAua1YkV/NxVaI2iJ1D7eTiew8EAMvE0Xy02i -sx7QBlrd9pPPV3WZ9fqGGmd4s7+W/jTcvedSVuWz5XV710GRBdxdaeOVDUO5/IOW -OZV7bIBaTxNyxtd9KXpEulKkKtVBRgkg/iKgtlswjbyJDNXXcPiHUv3a76xRLgez -Tv7QCdpw75j6VuZt27VXS9zlLCUVyJ4ueE742pyehizKV/Ma5ciSixqClnrDvFAS -adgOWkaLOusm+iPJtrCBvkIApPjW/jAux9JG9uWOdf3yzLnQh1vMBhBgu4M1t15n -3kfsmUjxpKEV/q2MYo45VU85FrmxY53/twIDAQABo0IwQDAPBgNVHRMBAf8EBTAD -AQH/MB0GA1UdDgQWBBS2oVQ5AsOgP46KvPrU+Bym0ToO/TAOBgNVHQ8BAf8EBAMC -AQYwDQYJKoZIhvcNAQENBQADggIBAHGlDs7k6b8/ONWJWsQCYftMxRQXLYtPU2sQ -F/xlhMcQSZDe28cmk4gmb3DWAl45oPePq5a1pRNcgRRtDoGCERuKTsZPpd1iHkTf -CVn0W3cLN+mLIMb4Ck4uWBzrM9DPhmDJ2vuAL55MYIR4PSFk1vtBHxgP58l1cb29 -XN40hz5BsA72udY/CROWFC/emh1auVbONTqwX3BNXuMp8SMoclm2q8KMZiYcdywm -djWLKKdpoPk79SPdhRB0yZADVpHnr7pH1BKXESLjokmUbOe3lEu6LaTaM4tMpkT/ -WjzGHWTYtTHkpjx6qFcL2+1hGsvxznN3Y6SHb0xRONbkX8eftoEq5IVIeVheO/jb -AoJnwTnbw3RLPTYe+SmTiGhbqEQZIfCn6IENLOiTNrQ3ssqwGyZ6miUfmpqAnksq -P/ujmv5zMnHCnsZy4YpoJ/HkD7TETKVhk/iXEAcqMCWpuchxuO9ozC1+9eB+D4Ko -b7a6bINDd82Kkhehnlt4Fj1F4jNy3eFmypnTycUm/Q1oBEauttmbjL4ZvrHG8hnj -XALKLNhvSgfZyTXaQHXyxKcZb55CEJh15pWLYLztxRLXis7VmFxWlgPF7ncGNf/P -5O4/E2Hu29othfDNrp2yGAlFw5Khchf8R7agCyzxxN5DaAhqXzvwdmP7zAYspsbi -DrW5viSP ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: - a3:da:42:7e:a4:b1:ae:da - Signature Algorithm: sha1WithRSAEncryption - Issuer: C=EU, L=Madrid (see current address at www.camerfirma.com/address)/serialNumber=A82743287, O=AC Camerfirma S.A., CN=Chambers of Commerce Root - 2008 - Validity - Not Before: Aug 1 12:29:50 2008 GMT - Not After : Jul 31 12:29:50 2038 GMT - Subject: C=EU, L=Madrid (see current address at www.camerfirma.com/address)/serialNumber=A82743287, O=AC Camerfirma S.A., CN=Chambers of Commerce Root - 2008 - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (4096 bit) - Modulus: - 00:af:00:cb:70:37:2b:80:5a:4a:3a:6c:78:94:7d: - a3:7f:1a:1f:f6:35:d5:bd:db:cb:0d:44:72:3e:26: - b2:90:52:ba:63:3b:28:58:6f:a5:b3:6d:94:a6:f3: - dd:64:0c:55:f6:f6:e7:f2:22:22:80:5e:e1:62:c6: - b6:29:e1:81:6c:f2:bf:e5:7d:32:6a:54:a0:32:19: - 59:fe:1f:8b:d7:3d:60:86:85:24:6f:e3:11:b3:77: - 3e:20:96:35:21:6b:b3:08:d9:70:2e:64:f7:84:92: - 53:d6:0e:b0:90:8a:8a:e3:87:8d:06:d3:bd:90:0e: - e2:99:a1:1b:86:0e:da:9a:0a:bb:0b:61:50:06:52: - f1:9e:7f:76:ec:cb:0f:d0:1e:0d:cf:99:30:3d:1c: - c4:45:10:58:ac:d6:d3:e8:d7:e5:ea:c5:01:07:77: - d6:51:e6:03:7f:8a:48:a5:4d:68:75:b9:e9:bc:9e: - 4e:19:71:f5:32:4b:9c:6d:60:19:0b:fb:cc:9d:75: - dc:bf:26:cd:8f:93:78:39:79:73:5e:25:0e:ca:5c: - eb:77:12:07:cb:64:41:47:72:93:ab:50:c3:eb:09: - 76:64:34:d2:39:b7:76:11:09:0d:76:45:c4:a9:ae: - 3d:6a:af:b5:7d:65:2f:94:58:10:ec:5c:7c:af:7e: - e2:b6:18:d9:d0:9b:4e:5a:49:df:a9:66:0b:cc:3c: - c6:78:7c:a7:9c:1d:e3:ce:8e:53:be:05:de:60:0f: - 6b:e5:1a:db:3f:e3:e1:21:c9:29:c1:f1:eb:07:9c: - 52:1b:01:44:51:3c:7b:25:d7:c4:e5:52:54:5d:25: - 07:ca:16:20:b8:ad:e4:41:ee:7a:08:fe:99:6f:83: - a6:91:02:b0:6c:36:55:6a:e7:7d:f5:96:e6:ca:81: - d6:97:f1:94:83:e9:ed:b0:b1:6b:12:69:1e:ac:fb: - 5d:a9:c5:98:e9:b4:5b:58:7a:be:3d:a2:44:3a:63: - 59:d4:0b:25:de:1b:4f:bd:e5:01:9e:cd:d2:29:d5: - 9f:17:19:0a:6f:bf:0c:90:d3:09:5f:d9:e3:8a:35: - cc:79:5a:4d:19:37:92:b7:c4:c1:ad:af:f4:79:24: - 9a:b2:01:0b:b1:af:5c:96:f3:80:32:fb:5c:3d:98: - f1:a0:3f:4a:de:be:af:94:2e:d9:55:9a:17:6e:60: - 9d:63:6c:b8:63:c9:ae:81:5c:18:35:e0:90:bb:be: - 3c:4f:37:22:b9:7e:eb:cf:9e:77:21:a6:3d:38:81: - fb:48:da:31:3d:2b:e3:89:f5:d0:b5:bd:7e:e0:50: - c4:12:89:b3:23:9a:10:31:85:db:ae:6f:ef:38:33: - 18:76:11 - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Basic Constraints: critical - CA:TRUE, pathlen:12 - X509v3 Subject Key Identifier: - F9:24:AC:0F:B2:B5:F8:79:C0:FA:60:88:1B:C4:D9:4D:02:9E:17:19 - X509v3 Authority Key Identifier: - keyid:F9:24:AC:0F:B2:B5:F8:79:C0:FA:60:88:1B:C4:D9:4D:02:9E:17:19 - DirName:/C=EU/L=Madrid (see current address at www.camerfirma.com/address)/serialNumber=A82743287/O=AC Camerfirma S.A./CN=Chambers of Commerce Root - 2008 - serial:A3:DA:42:7E:A4:B1:AE:DA - - X509v3 Key Usage: critical - Certificate Sign, CRL Sign - X509v3 Certificate Policies: - Policy: X509v3 Any Policy - CPS: http://policy.camerfirma.com - - Signature Algorithm: sha1WithRSAEncryption - 90:12:af:22:35:c2:a3:39:f0:2e:de:e9:b5:e9:78:7c:48:be: - 3f:7d:45:92:5e:e9:da:b1:19:fc:16:3c:9f:b4:5b:66:9e:6a: - e7:c3:b9:5d:88:e8:0f:ad:cf:23:0f:de:25:3a:5e:cc:4f:a5: - c1:b5:2d:ac:24:d2:58:07:de:a2:cf:69:84:60:33:e8:10:0d: - 13:a9:23:d0:85:e5:8e:7b:a6:9e:3d:72:13:72:33:f5:aa:7d: - c6:63:1f:08:f4:fe:01:7f:24:cf:2b:2c:54:09:de:e2:2b:6d: - 92:c6:39:4f:16:ea:3c:7e:7a:46:d4:45:6a:46:a8:eb:75:82: - 56:a7:ab:a0:7c:68:13:33:f6:9d:30:f0:6f:27:39:24:23:2a: - 90:fd:90:29:35:f2:93:df:34:a5:c6:f7:f8:ef:8c:0f:62:4a: - 7c:ae:d3:f5:54:f8:8d:b6:9a:56:87:16:82:3a:33:ab:5a:22: - 08:f7:82:ba:ea:2e:e0:47:9a:b4:b5:45:a3:05:3b:d9:dc:2e: - 45:40:3b:ea:dc:7f:e8:3b:eb:d1:ec:26:d8:35:a4:30:c5:3a: - ac:57:9e:b3:76:a5:20:7b:f9:1e:4a:05:62:01:a6:28:75:60: - 97:92:0d:6e:3e:4d:37:43:0d:92:15:9c:18:22:cd:51:99:a0: - 29:1a:3c:5f:8a:32:33:5b:30:c7:89:2f:47:98:0f:a3:03:c6: - f6:f1:ac:df:32:f0:d9:81:1a:e4:9c:bd:f6:80:14:f0:d1:2c: - b9:85:f5:d8:a3:b1:c8:a5:21:e5:1c:13:97:ee:0e:bd:df:29: - a9:ef:34:53:5b:d3:e4:6a:13:84:06:b6:32:02:c4:52:ae:22: - d2:dc:b2:21:42:1a:da:40:f0:29:c9:ec:0a:0c:5c:e2:d0:ba: - cc:48:d3:37:0a:cc:12:0a:8a:79:b0:3d:03:7f:69:4b:f4:34: - 20:7d:b3:34:ea:8e:4b:64:f5:3e:fd:b3:23:67:15:0d:04:b8: - f0:2d:c1:09:51:3c:b2:6c:15:f0:a5:23:d7:83:74:e4:e5:2e: - c9:fe:98:27:42:c6:ab:c6:9e:b0:d0:5b:38:a5:9b:50:de:7e: - 18:98:b5:45:3b:f6:79:b4:e8:f7:1a:7b:06:83:fb:d0:8b:da: - bb:c7:bd:18:ab:08:6f:3c:80:6b:40:3f:19:19:ba:65:8a:e6: - be:d5:5c:d3:36:d7:ef:40:52:24:60:38:67:04:31:ec:8f:f3: - 82:c6:de:b9:55:f3:3b:31:91:5a:dc:b5:08:15:ad:76:25:0a: - 0d:7b:2e:87:e2:0c:a6:06:bc:26:10:6d:37:9d:ec:dd:78:8c: - 7c:80:c5:f0:d9:77:48:d0 ------BEGIN CERTIFICATE----- -MIIHTzCCBTegAwIBAgIJAKPaQn6ksa7aMA0GCSqGSIb3DQEBBQUAMIGuMQswCQYD -VQQGEwJFVTFDMEEGA1UEBxM6TWFkcmlkIChzZWUgY3VycmVudCBhZGRyZXNzIGF0 -IHd3dy5jYW1lcmZpcm1hLmNvbS9hZGRyZXNzKTESMBAGA1UEBRMJQTgyNzQzMjg3 -MRswGQYDVQQKExJBQyBDYW1lcmZpcm1hIFMuQS4xKTAnBgNVBAMTIENoYW1iZXJz -IG9mIENvbW1lcmNlIFJvb3QgLSAyMDA4MB4XDTA4MDgwMTEyMjk1MFoXDTM4MDcz -MTEyMjk1MFowga4xCzAJBgNVBAYTAkVVMUMwQQYDVQQHEzpNYWRyaWQgKHNlZSBj -dXJyZW50IGFkZHJlc3MgYXQgd3d3LmNhbWVyZmlybWEuY29tL2FkZHJlc3MpMRIw -EAYDVQQFEwlBODI3NDMyODcxGzAZBgNVBAoTEkFDIENhbWVyZmlybWEgUy5BLjEp -MCcGA1UEAxMgQ2hhbWJlcnMgb2YgQ29tbWVyY2UgUm9vdCAtIDIwMDgwggIiMA0G -CSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQCvAMtwNyuAWko6bHiUfaN/Gh/2NdW9 -28sNRHI+JrKQUrpjOyhYb6WzbZSm891kDFX29ufyIiKAXuFixrYp4YFs8r/lfTJq -VKAyGVn+H4vXPWCGhSRv4xGzdz4gljUha7MI2XAuZPeEklPWDrCQiorjh40G072Q -DuKZoRuGDtqaCrsLYVAGUvGef3bsyw/QHg3PmTA9HMRFEFis1tPo1+XqxQEHd9ZR -5gN/ikilTWh1uem8nk4ZcfUyS5xtYBkL+8ydddy/Js2Pk3g5eXNeJQ7KXOt3EgfL -ZEFHcpOrUMPrCXZkNNI5t3YRCQ12RcSprj1qr7V9ZS+UWBDsXHyvfuK2GNnQm05a -Sd+pZgvMPMZ4fKecHePOjlO+Bd5gD2vlGts/4+EhySnB8esHnFIbAURRPHsl18Tl -UlRdJQfKFiC4reRB7noI/plvg6aRArBsNlVq5331lubKgdaX8ZSD6e2wsWsSaR6s -+12pxZjptFtYer49okQ6Y1nUCyXeG0+95QGezdIp1Z8XGQpvvwyQ0wlf2eOKNcx5 -Wk0ZN5K3xMGtr/R5JJqyAQuxr1yW84Ay+1w9mPGgP0revq+ULtlVmhduYJ1jbLhj -ya6BXBg14JC7vjxPNyK5fuvPnnchpj04gftI2jE9K+OJ9dC1vX7gUMQSibMjmhAx -hduub+84Mxh2EQIDAQABo4IBbDCCAWgwEgYDVR0TAQH/BAgwBgEB/wIBDDAdBgNV -HQ4EFgQU+SSsD7K1+HnA+mCIG8TZTQKeFxkwgeMGA1UdIwSB2zCB2IAU+SSsD7K1 -+HnA+mCIG8TZTQKeFxmhgbSkgbEwga4xCzAJBgNVBAYTAkVVMUMwQQYDVQQHEzpN -YWRyaWQgKHNlZSBjdXJyZW50IGFkZHJlc3MgYXQgd3d3LmNhbWVyZmlybWEuY29t -L2FkZHJlc3MpMRIwEAYDVQQFEwlBODI3NDMyODcxGzAZBgNVBAoTEkFDIENhbWVy -ZmlybWEgUy5BLjEpMCcGA1UEAxMgQ2hhbWJlcnMgb2YgQ29tbWVyY2UgUm9vdCAt -IDIwMDiCCQCj2kJ+pLGu2jAOBgNVHQ8BAf8EBAMCAQYwPQYDVR0gBDYwNDAyBgRV -HSAAMCowKAYIKwYBBQUHAgEWHGh0dHA6Ly9wb2xpY3kuY2FtZXJmaXJtYS5jb20w -DQYJKoZIhvcNAQEFBQADggIBAJASryI1wqM58C7e6bXpeHxIvj99RZJe6dqxGfwW -PJ+0W2aeaufDuV2I6A+tzyMP3iU6XsxPpcG1Lawk0lgH3qLPaYRgM+gQDROpI9CF -5Y57pp49chNyM/WqfcZjHwj0/gF/JM8rLFQJ3uIrbZLGOU8W6jx+ekbURWpGqOt1 -glanq6B8aBMz9p0w8G8nOSQjKpD9kCk18pPfNKXG9/jvjA9iSnyu0/VU+I22mlaH -FoI6M6taIgj3grrqLuBHmrS1RaMFO9ncLkVAO+rcf+g769HsJtg1pDDFOqxXnrN2 -pSB7+R5KBWIBpih1YJeSDW4+TTdDDZIVnBgizVGZoCkaPF+KMjNbMMeJL0eYD6MD -xvbxrN8y8NmBGuScvfaAFPDRLLmF9dijscilIeUcE5fuDr3fKanvNFNb0+RqE4QG -tjICxFKuItLcsiFCGtpA8CnJ7AoMXOLQusxI0zcKzBIKinmwPQN/aUv0NCB9szTq -jktk9T79syNnFQ0EuPAtwQlRPLJsFfClI9eDdOTlLsn+mCdCxqvGnrDQWzilm1De -fhiYtUU79nm06PcaewaD+9CL2rvHvRirCG88gGtAPxkZumWK5r7VXNM21+9AUiRg -OGcEMeyP84LG3rlV8zsxkVrctQgVrXYlCg17LofiDKYGvCYQbTed7N14jHyAxfDZ -d0jQ ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: 1218379777 (0x489f0001) - Signature Algorithm: sha1WithRSAEncryption - Issuer: C=CN, O=China Internet Network Information Center, CN=China Internet Network Information Center EV Certificates Root - Validity - Not Before: Aug 31 07:11:25 2010 GMT - Not After : Aug 31 07:11:25 2030 GMT - Subject: C=CN, O=China Internet Network Information Center, CN=China Internet Network Information Center EV Certificates Root - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (2048 bit) - Modulus: - 00:9b:7e:73:ee:bd:3b:78:aa:64:43:41:f5:50:df: - 94:f2:2e:b2:8d:4a:8e:46:54:d2:21:12:c8:39:32: - 42:06:e9:83:d5:9f:52:ed:e5:67:03:3b:54:c1:8c: - 99:99:cc:e9:c0:0f:ff:0d:d9:84:11:b2:b8:d1:cb: - 5b:dc:1e:f9:68:31:64:e1:9b:fa:74:eb:68:b9:20: - 95:f7:c6:0f:8d:47:ac:5a:06:dd:61:ab:e2:ec:d8: - 9f:17:2d:9c:ca:3c:35:97:55:71:cd:43:85:b1:47: - 16:f5:2c:53:80:76:cf:d3:00:64:bd:40:99:dd:cc: - d8:db:c4:9f:d6:13:5f:41:83:8b:f9:0d:87:92:56: - 34:6c:1a:10:0b:17:d5:5a:1c:97:58:84:3c:84:1a: - 2e:5c:91:34:6e:19:5f:7f:17:69:c5:65:ef:6b:21: - c6:d5:50:3a:bf:61:b9:05:8d:ef:6f:34:3a:b2:6f: - 14:63:bf:16:3b:9b:a9:2a:fd:b7:2b:38:66:06:c5: - 2c:e2:aa:67:1e:45:a7:8d:04:66:42:f6:8f:2b:ef: - 88:20:69:8f:32:8c:14:73:da:2b:86:91:63:22:9a: - f2:a7:db:ce:89:8b:ab:5d:c7:14:c1:5b:30:6a:1f: - b1:b7:9e:2e:81:01:02:ed:cf:96:5e:63:db:a8:e6: - 38:b7 - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Authority Key Identifier: - keyid:7C:72:4B:39:C7:C0:DB:62:A5:4F:9B:AA:18:34:92:A2:CA:83:82:59 - - X509v3 Basic Constraints: critical - CA:TRUE - X509v3 Key Usage: critical - Certificate Sign, CRL Sign - X509v3 Subject Key Identifier: - 7C:72:4B:39:C7:C0:DB:62:A5:4F:9B:AA:18:34:92:A2:CA:83:82:59 - Signature Algorithm: sha1WithRSAEncryption - 2a:c3:c7:43:37:8f:dd:ad:a4:b2:0c:ee:dc:14:6d:8f:28:a4: - 98:49:cb:0c:80:ea:f3:ed:23:66:75:7d:c5:d3:21:67:79:d1: - 73:c5:b5:03:b7:58:ac:0c:54:2f:c6:56:13:0f:31:da:06:e7: - 65:3b:1d:6f:36:db:c8:1d:f9:fd:80:06:ca:a3:3d:66:16:a8: - 9d:4c:16:7d:c0:95:46:b5:51:e4:e2:1f:d7:ea:06:4d:63:8d: - 96:8c:ef:e7:33:57:42:3a:eb:8c:c1:79:c8:4d:76:7d:de:f6: - b1:b7:81:e0:a0:f9:a1:78:46:17:1a:56:98:f0:4e:3d:ab:1c: - ed:ec:39:dc:07:48:f7:63:fe:06:ae:c2:a4:5c:6a:5b:32:88: - c5:c7:33:85:ac:66:42:47:c2:58:24:99:e1:e5:3e:e5:75:2c: - 8e:43:d6:5d:3c:78:1e:a8:95:82:29:50:d1:d1:16:ba:ef:c1: - be:7a:d9:b4:d8:cc:1e:4c:46:e1:77:b1:31:ab:bd:2a:c8:ce: - 8f:6e:a1:5d:7f:03:75:34:e4:ad:89:45:54:5e:be:ae:28:a5: - bb:3f:78:79:eb:73:b3:0a:0d:fd:be:c9:f7:56:ac:f6:b7:ed: - 2f:9b:21:29:c7:38:b6:95:c4:04:f2:c3:2d:fd:14:2a:90:99: - b9:07:cc:9f ------BEGIN CERTIFICATE----- -MIID9zCCAt+gAwIBAgIESJ8AATANBgkqhkiG9w0BAQUFADCBijELMAkGA1UEBhMC -Q04xMjAwBgNVBAoMKUNoaW5hIEludGVybmV0IE5ldHdvcmsgSW5mb3JtYXRpb24g -Q2VudGVyMUcwRQYDVQQDDD5DaGluYSBJbnRlcm5ldCBOZXR3b3JrIEluZm9ybWF0 -aW9uIENlbnRlciBFViBDZXJ0aWZpY2F0ZXMgUm9vdDAeFw0xMDA4MzEwNzExMjVa -Fw0zMDA4MzEwNzExMjVaMIGKMQswCQYDVQQGEwJDTjEyMDAGA1UECgwpQ2hpbmEg -SW50ZXJuZXQgTmV0d29yayBJbmZvcm1hdGlvbiBDZW50ZXIxRzBFBgNVBAMMPkNo -aW5hIEludGVybmV0IE5ldHdvcmsgSW5mb3JtYXRpb24gQ2VudGVyIEVWIENlcnRp -ZmljYXRlcyBSb290MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAm35z -7r07eKpkQ0H1UN+U8i6yjUqORlTSIRLIOTJCBumD1Z9S7eVnAztUwYyZmczpwA// -DdmEEbK40ctb3B75aDFk4Zv6dOtouSCV98YPjUesWgbdYavi7NifFy2cyjw1l1Vx -zUOFsUcW9SxTgHbP0wBkvUCZ3czY28Sf1hNfQYOL+Q2HklY0bBoQCxfVWhyXWIQ8 -hBouXJE0bhlffxdpxWXvayHG1VA6v2G5BY3vbzQ6sm8UY78WO5upKv23KzhmBsUs -4qpnHkWnjQRmQvaPK++IIGmPMowUc9orhpFjIpryp9vOiYurXccUwVswah+xt54u -gQEC7c+WXmPbqOY4twIDAQABo2MwYTAfBgNVHSMEGDAWgBR8cks5x8DbYqVPm6oY -NJKiyoOCWTAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIBBjAdBgNVHQ4E -FgQUfHJLOcfA22KlT5uqGDSSosqDglkwDQYJKoZIhvcNAQEFBQADggEBACrDx0M3 -j92tpLIM7twUbY8opJhJywyA6vPtI2Z1fcXTIWd50XPFtQO3WKwMVC/GVhMPMdoG -52U7HW8228gd+f2ABsqjPWYWqJ1MFn3AlUa1UeTiH9fqBk1jjZaM7+czV0I664zB -echNdn3e9rG3geCg+aF4RhcaVpjwTj2rHO3sOdwHSPdj/gauwqRcalsyiMXHM4Ws -ZkJHwlgkmeHlPuV1LI5D1l08eB6olYIpUNHRFrrvwb562bTYzB5MRuF3sTGrvSrI -zo9uoV1/A3U05K2JRVRevq4opbs/eHnrc7MKDf2+yfdWrPa37S+bISnHOLaVxATy -wy39FCqQmbkHzJ8= ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: 1 (0x1) - Signature Algorithm: sha1WithRSAEncryption - Issuer: C=GB, ST=Greater Manchester, L=Salford, O=Comodo CA Limited, CN=AAA Certificate Services - Validity - Not Before: Jan 1 00:00:00 2004 GMT - Not After : Dec 31 23:59:59 2028 GMT - Subject: C=GB, ST=Greater Manchester, L=Salford, O=Comodo CA Limited, CN=AAA Certificate Services - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (2048 bit) - Modulus: - 00:be:40:9d:f4:6e:e1:ea:76:87:1c:4d:45:44:8e: - be:46:c8:83:06:9d:c1:2a:fe:18:1f:8e:e4:02:fa: - f3:ab:5d:50:8a:16:31:0b:9a:06:d0:c5:70:22:cd: - 49:2d:54:63:cc:b6:6e:68:46:0b:53:ea:cb:4c:24: - c0:bc:72:4e:ea:f1:15:ae:f4:54:9a:12:0a:c3:7a: - b2:33:60:e2:da:89:55:f3:22:58:f3:de:dc:cf:ef: - 83:86:a2:8c:94:4f:9f:68:f2:98:90:46:84:27:c7: - 76:bf:e3:cc:35:2c:8b:5e:07:64:65:82:c0:48:b0: - a8:91:f9:61:9f:76:20:50:a8:91:c7:66:b5:eb:78: - 62:03:56:f0:8a:1a:13:ea:31:a3:1e:a0:99:fd:38: - f6:f6:27:32:58:6f:07:f5:6b:b8:fb:14:2b:af:b7: - aa:cc:d6:63:5f:73:8c:da:05:99:a8:38:a8:cb:17: - 78:36:51:ac:e9:9e:f4:78:3a:8d:cf:0f:d9:42:e2: - 98:0c:ab:2f:9f:0e:01:de:ef:9f:99:49:f1:2d:df: - ac:74:4d:1b:98:b5:47:c5:e5:29:d1:f9:90:18:c7: - 62:9c:be:83:c7:26:7b:3e:8a:25:c7:c0:dd:9d:e6: - 35:68:10:20:9d:8f:d8:de:d2:c3:84:9c:0d:5e:e8: - 2f:c9 - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Subject Key Identifier: - A0:11:0A:23:3E:96:F1:07:EC:E2:AF:29:EF:82:A5:7F:D0:30:A4:B4 - X509v3 Key Usage: critical - Certificate Sign, CRL Sign - X509v3 Basic Constraints: critical - CA:TRUE - X509v3 CRL Distribution Points: - - Full Name: - URI:http://crl.comodoca.com/AAACertificateServices.crl - - Full Name: - URI:http://crl.comodo.net/AAACertificateServices.crl - - Signature Algorithm: sha1WithRSAEncryption - 08:56:fc:02:f0:9b:e8:ff:a4:fa:d6:7b:c6:44:80:ce:4f:c4: - c5:f6:00:58:cc:a6:b6:bc:14:49:68:04:76:e8:e6:ee:5d:ec: - 02:0f:60:d6:8d:50:18:4f:26:4e:01:e3:e6:b0:a5:ee:bf:bc: - 74:54:41:bf:fd:fc:12:b8:c7:4f:5a:f4:89:60:05:7f:60:b7: - 05:4a:f3:f6:f1:c2:bf:c4:b9:74:86:b6:2d:7d:6b:cc:d2:f3: - 46:dd:2f:c6:e0:6a:c3:c3:34:03:2c:7d:96:dd:5a:c2:0e:a7: - 0a:99:c1:05:8b:ab:0c:2f:f3:5c:3a:cf:6c:37:55:09:87:de: - 53:40:6c:58:ef:fc:b6:ab:65:6e:04:f6:1b:dc:3c:e0:5a:15: - c6:9e:d9:f1:59:48:30:21:65:03:6c:ec:e9:21:73:ec:9b:03: - a1:e0:37:ad:a0:15:18:8f:fa:ba:02:ce:a7:2c:a9:10:13:2c: - d4:e5:08:26:ab:22:97:60:f8:90:5e:74:d4:a2:9a:53:bd:f2: - a9:68:e0:a2:6e:c2:d7:6c:b1:a3:0f:9e:bf:eb:68:e7:56:f2: - ae:f2:e3:2b:38:3a:09:81:b5:6b:85:d7:be:2d:ed:3f:1a:b7: - b2:63:e2:f5:62:2c:82:d4:6a:00:41:50:f1:39:83:9f:95:e9: - 36:96:98:6e ------BEGIN CERTIFICATE----- -MIIEMjCCAxqgAwIBAgIBATANBgkqhkiG9w0BAQUFADB7MQswCQYDVQQGEwJHQjEb -MBkGA1UECAwSR3JlYXRlciBNYW5jaGVzdGVyMRAwDgYDVQQHDAdTYWxmb3JkMRow -GAYDVQQKDBFDb21vZG8gQ0EgTGltaXRlZDEhMB8GA1UEAwwYQUFBIENlcnRpZmlj -YXRlIFNlcnZpY2VzMB4XDTA0MDEwMTAwMDAwMFoXDTI4MTIzMTIzNTk1OVowezEL -MAkGA1UEBhMCR0IxGzAZBgNVBAgMEkdyZWF0ZXIgTWFuY2hlc3RlcjEQMA4GA1UE -BwwHU2FsZm9yZDEaMBgGA1UECgwRQ29tb2RvIENBIExpbWl0ZWQxITAfBgNVBAMM -GEFBQSBDZXJ0aWZpY2F0ZSBTZXJ2aWNlczCCASIwDQYJKoZIhvcNAQEBBQADggEP -ADCCAQoCggEBAL5AnfRu4ep2hxxNRUSOvkbIgwadwSr+GB+O5AL686tdUIoWMQua -BtDFcCLNSS1UY8y2bmhGC1Pqy0wkwLxyTurxFa70VJoSCsN6sjNg4tqJVfMiWPPe -3M/vg4aijJRPn2jymJBGhCfHdr/jzDUsi14HZGWCwEiwqJH5YZ92IFCokcdmtet4 -YgNW8IoaE+oxox6gmf049vYnMlhvB/VruPsUK6+3qszWY19zjNoFmag4qMsXeDZR -rOme9Hg6jc8P2ULimAyrL58OAd7vn5lJ8S3frHRNG5i1R8XlKdH5kBjHYpy+g8cm -ez6KJcfA3Z3mNWgQIJ2P2N7Sw4ScDV7oL8kCAwEAAaOBwDCBvTAdBgNVHQ4EFgQU -oBEKIz6W8Qfs4q8p74Klf9AwpLQwDgYDVR0PAQH/BAQDAgEGMA8GA1UdEwEB/wQF -MAMBAf8wewYDVR0fBHQwcjA4oDagNIYyaHR0cDovL2NybC5jb21vZG9jYS5jb20v -QUFBQ2VydGlmaWNhdGVTZXJ2aWNlcy5jcmwwNqA0oDKGMGh0dHA6Ly9jcmwuY29t -b2RvLm5ldC9BQUFDZXJ0aWZpY2F0ZVNlcnZpY2VzLmNybDANBgkqhkiG9w0BAQUF -AAOCAQEACFb8AvCb6P+k+tZ7xkSAzk/ExfYAWMymtrwUSWgEdujm7l3sAg9g1o1Q -GE8mTgHj5rCl7r+8dFRBv/38ErjHT1r0iWAFf2C3BUrz9vHCv8S5dIa2LX1rzNLz -Rt0vxuBqw8M0Ayx9lt1awg6nCpnBBYurDC/zXDrPbDdVCYfeU0BsWO/8tqtlbgT2 -G9w84FoVxp7Z8VlIMCFlA2zs6SFz7JsDoeA3raAVGI/6ugLOpyypEBMs1OUIJqsi -l2D4kF501KKaU73yqWjgom7C12yxow+ev+to51byrvLjKzg6CYG1a4XXvi3tPxq3 -smPi9WIsgtRqAEFQ8TmDn5XpNpaYbg== ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: 1 (0x1) - Signature Algorithm: sha1WithRSAEncryption - Issuer: C=GB, ST=Greater Manchester, L=Salford, O=Comodo CA Limited, CN=Secure Certificate Services - Validity - Not Before: Jan 1 00:00:00 2004 GMT - Not After : Dec 31 23:59:59 2028 GMT - Subject: C=GB, ST=Greater Manchester, L=Salford, O=Comodo CA Limited, CN=Secure Certificate Services - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (2048 bit) - Modulus: - 00:c0:71:33:82:8a:d0:70:eb:73:87:82:40:d5:1d: - e4:cb:c9:0e:42:90:f9:de:34:b9:a1:ba:11:f4:25: - 85:f3:cc:72:6d:f2:7b:97:6b:b3:07:f1:77:24:91: - 5f:25:8f:f6:74:3d:e4:80:c2:f8:3c:0d:f3:bf:40: - ea:f7:c8:52:d1:72:6f:ef:c8:ab:41:b8:6e:2e:17: - 2a:95:69:0c:cd:d2:1e:94:7b:2d:94:1d:aa:75:d7: - b3:98:cb:ac:bc:64:53:40:bc:8f:ac:ac:36:cb:5c: - ad:bb:dd:e0:94:17:ec:d1:5c:d0:bf:ef:a5:95:c9: - 90:c5:b0:ac:fb:1b:43:df:7a:08:5d:b7:b8:f2:40: - 1b:2b:27:9e:50:ce:5e:65:82:88:8c:5e:d3:4e:0c: - 7a:ea:08:91:b6:36:aa:2b:42:fb:ea:c2:a3:39:e5: - db:26:38:ad:8b:0a:ee:19:63:c7:1c:24:df:03:78: - da:e6:ea:c1:47:1a:0b:0b:46:09:dd:02:fc:de:cb: - 87:5f:d7:30:63:68:a1:ae:dc:32:a1:ba:be:fe:44: - ab:68:b6:a5:17:15:fd:bd:d5:a7:a7:9a:e4:44:33: - e9:88:8e:fc:ed:51:eb:93:71:4e:ad:01:e7:44:8e: - ab:2d:cb:a8:fe:01:49:48:f0:c0:dd:c7:68:d8:92: - fe:3d - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Subject Key Identifier: - 3C:D8:93:88:C2:C0:82:09:CC:01:99:06:93:20:E9:9E:70:09:63:4F - X509v3 Key Usage: critical - Certificate Sign, CRL Sign - X509v3 Basic Constraints: critical - CA:TRUE - X509v3 CRL Distribution Points: - - Full Name: - URI:http://crl.comodoca.com/SecureCertificateServices.crl - - Full Name: - URI:http://crl.comodo.net/SecureCertificateServices.crl - - Signature Algorithm: sha1WithRSAEncryption - 87:01:6d:23:1d:7e:5b:17:7d:c1:61:32:cf:8f:e7:f3:8a:94: - 59:66:e0:9e:28:a8:5e:d3:b7:f4:34:e6:aa:39:b2:97:16:c5: - 82:6f:32:a4:e9:8c:e7:af:fd:ef:c2:e8:b9:4b:aa:a3:f4:e6: - da:8d:65:21:fb:ba:80:eb:26:28:85:1a:fe:39:8c:de:5b:04: - 04:b4:54:f9:a3:67:9e:41:fa:09:52:cc:05:48:a8:c9:3f:21: - 04:1e:ce:48:6b:fc:85:e8:c2:7b:af:7f:b7:cc:f8:5f:3a:fd: - 35:c6:0d:ef:97:dc:4c:ab:11:e1:6b:cb:31:d1:6c:fb:48:80: - ab:dc:9c:37:b8:21:14:4b:0d:71:3d:ec:83:33:6e:d1:6e:32: - 16:ec:98:c7:16:8b:59:a6:34:ab:05:57:2d:93:f7:aa:13:cb: - d2:13:e2:b7:2e:3b:cd:6b:50:17:09:68:3e:b5:26:57:ee:b6: - e0:b6:dd:b9:29:80:79:7d:8f:a3:f0:a4:28:a4:15:c4:85:f4: - 27:d4:6b:bf:e5:5c:e4:65:02:76:54:b4:e3:37:66:24:d3:19: - 61:c8:52:10:e5:8b:37:9a:b9:a9:f9:1d:bf:ea:99:92:61:96: - ff:01:cd:a1:5f:0d:bc:71:bc:0e:ac:0b:1d:47:45:1d:c1:ec: - 7c:ec:fd:29 ------BEGIN CERTIFICATE----- -MIIEPzCCAyegAwIBAgIBATANBgkqhkiG9w0BAQUFADB+MQswCQYDVQQGEwJHQjEb -MBkGA1UECAwSR3JlYXRlciBNYW5jaGVzdGVyMRAwDgYDVQQHDAdTYWxmb3JkMRow -GAYDVQQKDBFDb21vZG8gQ0EgTGltaXRlZDEkMCIGA1UEAwwbU2VjdXJlIENlcnRp -ZmljYXRlIFNlcnZpY2VzMB4XDTA0MDEwMTAwMDAwMFoXDTI4MTIzMTIzNTk1OVow -fjELMAkGA1UEBhMCR0IxGzAZBgNVBAgMEkdyZWF0ZXIgTWFuY2hlc3RlcjEQMA4G -A1UEBwwHU2FsZm9yZDEaMBgGA1UECgwRQ29tb2RvIENBIExpbWl0ZWQxJDAiBgNV -BAMMG1NlY3VyZSBDZXJ0aWZpY2F0ZSBTZXJ2aWNlczCCASIwDQYJKoZIhvcNAQEB -BQADggEPADCCAQoCggEBAMBxM4KK0HDrc4eCQNUd5MvJDkKQ+d40uaG6EfQlhfPM -cm3ye5drswfxdySRXyWP9nQ95IDC+DwN879A6vfIUtFyb+/Iq0G4bi4XKpVpDM3S -HpR7LZQdqnXXs5jLrLxkU0C8j6ysNstcrbvd4JQX7NFc0L/vpZXJkMWwrPsbQ996 -CF23uPJAGysnnlDOXmWCiIxe004MeuoIkbY2qitC++rCoznl2yY4rYsK7hljxxwk -3wN42ubqwUcaCwtGCd0C/N7Lh1/XMGNooa7cMqG6vv5Eq2i2pRcV/b3Vp6ea5EQz -6YiO/O1R65NxTq0B50SOqy3LqP4BSUjwwN3HaNiS/j0CAwEAAaOBxzCBxDAdBgNV -HQ4EFgQUPNiTiMLAggnMAZkGkyDpnnAJY08wDgYDVR0PAQH/BAQDAgEGMA8GA1Ud -EwEB/wQFMAMBAf8wgYEGA1UdHwR6MHgwO6A5oDeGNWh0dHA6Ly9jcmwuY29tb2Rv -Y2EuY29tL1NlY3VyZUNlcnRpZmljYXRlU2VydmljZXMuY3JsMDmgN6A1hjNodHRw -Oi8vY3JsLmNvbW9kby5uZXQvU2VjdXJlQ2VydGlmaWNhdGVTZXJ2aWNlcy5jcmww -DQYJKoZIhvcNAQEFBQADggEBAIcBbSMdflsXfcFhMs+P5/OKlFlm4J4oqF7Tt/Q0 -5qo5spcWxYJvMqTpjOev/e/C6LlLqqP05tqNZSH7uoDrJiiFGv45jN5bBAS0VPmj -Z55B+glSzAVIqMk/IQQezkhr/IXownuvf7fM+F86/TXGDe+X3EyrEeFryzHRbPtI -gKvcnDe4IRRLDXE97IMzbtFuMhbsmMcWi1mmNKsFVy2T96oTy9IT4rcuO81rUBcJ -aD61JlfutuC23bkpgHl9j6PwpCikFcSF9CfUa7/lXORlAnZUtOM3ZiTTGWHIUhDl -izeauan5Hb/qmZJhlv8BzaFfDbxxvA6sCx1HRR3B7Hzs/Sk= ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: 1 (0x1) - Signature Algorithm: sha1WithRSAEncryption - Issuer: C=GB, ST=Greater Manchester, L=Salford, O=Comodo CA Limited, CN=Trusted Certificate Services - Validity - Not Before: Jan 1 00:00:00 2004 GMT - Not After : Dec 31 23:59:59 2028 GMT - Subject: C=GB, ST=Greater Manchester, L=Salford, O=Comodo CA Limited, CN=Trusted Certificate Services - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (2048 bit) - Modulus: - 00:df:71:6f:36:58:53:5a:f2:36:54:57:80:c4:74: - 08:20:ed:18:7f:2a:1d:e6:35:9a:1e:25:ac:9c:e5: - 96:7e:72:52:a0:15:42:db:59:dd:64:7a:1a:d0:b8: - 7b:dd:39:15:bc:55:48:c4:ed:3a:00:ea:31:11:ba: - f2:71:74:1a:67:b8:cf:33:cc:a8:31:af:a3:e3:d7: - 7f:bf:33:2d:4c:6a:3c:ec:8b:c3:92:d2:53:77:24: - 74:9c:07:6e:70:fc:bd:0b:5b:76:ba:5f:f2:ff:d7: - 37:4b:4a:60:78:f7:f0:fa:ca:70:b4:ea:59:aa:a3: - ce:48:2f:a9:c3:b2:0b:7e:17:72:16:0c:a6:07:0c: - 1b:38:cf:c9:62:b7:3f:a0:93:a5:87:41:f2:b7:70: - 40:77:d8:be:14:7c:e3:a8:c0:7a:8e:e9:63:6a:d1: - 0f:9a:c6:d2:f4:8b:3a:14:04:56:d4:ed:b8:cc:6e: - f5:fb:e2:2c:58:bd:7f:4f:6b:2b:f7:60:24:58:24: - ce:26:ef:34:91:3a:d5:e3:81:d0:b2:f0:04:02:d7: - 5b:b7:3e:92:ac:6b:12:8a:f9:e4:05:b0:3b:91:49: - 5c:b2:eb:53:ea:f8:9f:47:86:ee:bf:95:c0:c0:06: - 9f:d2:5b:5e:11:1b:f4:c7:04:35:29:d2:55:5c:e4: - ed:eb - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Subject Key Identifier: - C5:7B:58:BD:ED:DA:25:69:D2:F7:59:16:A8:B3:32:C0:7B:27:5B:F4 - X509v3 Key Usage: critical - Certificate Sign, CRL Sign - X509v3 Basic Constraints: critical - CA:TRUE - X509v3 CRL Distribution Points: - - Full Name: - URI:http://crl.comodoca.com/TrustedCertificateServices.crl - - Full Name: - URI:http://crl.comodo.net/TrustedCertificateServices.crl - - Signature Algorithm: sha1WithRSAEncryption - c8:93:81:3b:89:b4:af:b8:84:12:4c:8d:d2:f0:db:70:ba:57: - 86:15:34:10:b9:2f:7f:1e:b0:a8:89:60:a1:8a:c2:77:0c:50: - 4a:9b:00:8b:d8:8b:f4:41:e2:d0:83:8a:4a:1c:14:06:b0:a3: - 68:05:70:31:30:a7:53:9b:0e:e9:4a:a0:58:69:67:0e:ae:9d: - f6:a5:2c:41:bf:3c:06:6b:e4:59:cc:6d:10:f1:96:6f:1f:df: - f4:04:02:a4:9f:45:3e:c8:d8:fa:36:46:44:50:3f:82:97:91: - 1f:28:db:18:11:8c:2a:e4:65:83:57:12:12:8c:17:3f:94:36: - fe:5d:b0:c0:04:77:13:b8:f4:15:d5:3f:38:cc:94:3a:55:d0: - ac:98:f5:ba:00:5f:e0:86:19:81:78:2f:28:c0:7e:d3:cc:42: - 0a:f5:ae:50:a0:d1:3e:c6:a1:71:ec:3f:a0:20:8c:66:3a:89: - b4:8e:d4:d8:b1:4d:25:47:ee:2f:88:c8:b5:e1:05:45:c0:be: - 14:71:de:7a:fd:8e:7b:7d:4d:08:96:a5:12:73:f0:2d:ca:37: - 27:74:12:27:4c:cb:b6:97:e9:d9:ae:08:6d:5a:39:40:dd:05: - 47:75:6a:5a:21:b3:a3:18:cf:4e:f7:2e:57:b7:98:70:5e:c8: - c4:78:b0:62 ------BEGIN CERTIFICATE----- -MIIEQzCCAyugAwIBAgIBATANBgkqhkiG9w0BAQUFADB/MQswCQYDVQQGEwJHQjEb -MBkGA1UECAwSR3JlYXRlciBNYW5jaGVzdGVyMRAwDgYDVQQHDAdTYWxmb3JkMRow -GAYDVQQKDBFDb21vZG8gQ0EgTGltaXRlZDElMCMGA1UEAwwcVHJ1c3RlZCBDZXJ0 -aWZpY2F0ZSBTZXJ2aWNlczAeFw0wNDAxMDEwMDAwMDBaFw0yODEyMzEyMzU5NTla -MH8xCzAJBgNVBAYTAkdCMRswGQYDVQQIDBJHcmVhdGVyIE1hbmNoZXN0ZXIxEDAO -BgNVBAcMB1NhbGZvcmQxGjAYBgNVBAoMEUNvbW9kbyBDQSBMaW1pdGVkMSUwIwYD -VQQDDBxUcnVzdGVkIENlcnRpZmljYXRlIFNlcnZpY2VzMIIBIjANBgkqhkiG9w0B -AQEFAAOCAQ8AMIIBCgKCAQEA33FvNlhTWvI2VFeAxHQIIO0Yfyod5jWaHiWsnOWW -fnJSoBVC21ndZHoa0Lh73TkVvFVIxO06AOoxEbrycXQaZ7jPM8yoMa+j49d/vzMt -TGo87IvDktJTdyR0nAducPy9C1t2ul/y/9c3S0pgePfw+spwtOpZqqPOSC+pw7IL -fhdyFgymBwwbOM/JYrc/oJOlh0Hyt3BAd9i+FHzjqMB6juljatEPmsbS9Is6FARW -1O24zG71++IsWL1/T2sr92AkWCTOJu80kTrV44HQsvAEAtdbtz6SrGsSivnkBbA7 -kUlcsutT6vifR4buv5XAwAaf0lteERv0xwQ1KdJVXOTt6wIDAQABo4HJMIHGMB0G -A1UdDgQWBBTFe1i97doladL3WRaoszLAeydb9DAOBgNVHQ8BAf8EBAMCAQYwDwYD -VR0TAQH/BAUwAwEB/zCBgwYDVR0fBHwwejA8oDqgOIY2aHR0cDovL2NybC5jb21v -ZG9jYS5jb20vVHJ1c3RlZENlcnRpZmljYXRlU2VydmljZXMuY3JsMDqgOKA2hjRo -dHRwOi8vY3JsLmNvbW9kby5uZXQvVHJ1c3RlZENlcnRpZmljYXRlU2VydmljZXMu -Y3JsMA0GCSqGSIb3DQEBBQUAA4IBAQDIk4E7ibSvuIQSTI3S8NtwuleGFTQQuS9/ -HrCoiWChisJ3DFBKmwCL2Iv0QeLQg4pKHBQGsKNoBXAxMKdTmw7pSqBYaWcOrp32 -pSxBvzwGa+RZzG0Q8ZZvH9/0BAKkn0U+yNj6NkZEUD+Cl5EfKNsYEYwq5GWDVxIS -jBc/lDb+XbDABHcTuPQV1T84zJQ6VdCsmPW6AF/ghhmBeC8owH7TzEIK9a5QoNE+ -xqFx7D+gIIxmOom0jtTYsU0lR+4viMi14QVFwL4Ucd56/Y57fU0IlqUSc/Atyjcn -dBInTMu2l+nZrghtWjlA3QVHdWpaIbOjGM9O9y5Xt5hwXsjEeLBi ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: - 04:00:00:00:00:01:0f:85:aa:2d:48 - Signature Algorithm: sha1WithRSAEncryption - Issuer: O=Cybertrust, Inc, CN=Cybertrust Global Root - Validity - Not Before: Dec 15 08:00:00 2006 GMT - Not After : Dec 15 08:00:00 2021 GMT - Subject: O=Cybertrust, Inc, CN=Cybertrust Global Root - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (2048 bit) - Modulus: - 00:f8:c8:bc:bd:14:50:66:13:ff:f0:d3:79:ec:23: - f2:b7:1a:c7:8e:85:f1:12:73:a6:19:aa:10:db:9c: - a2:65:74:5a:77:3e:51:7d:56:f6:dc:23:b6:d4:ed: - 5f:58:b1:37:4d:d5:49:0e:6e:f5:6a:87:d6:d2:8c: - d2:27:c6:e2:ff:36:9f:98:65:a0:13:4e:c6:2a:64: - 9b:d5:90:12:cf:14:06:f4:3b:e3:d4:28:be:e8:0e: - f8:ab:4e:48:94:6d:8e:95:31:10:5c:ed:a2:2d:bd: - d5:3a:6d:b2:1c:bb:60:c0:46:4b:01:f5:49:ae:7e: - 46:8a:d0:74:8d:a1:0c:02:ce:ee:fc:e7:8f:b8:6b: - 66:f3:7f:44:00:bf:66:25:14:2b:dd:10:30:1d:07: - 96:3f:4d:f6:6b:b8:8f:b7:7b:0c:a5:38:eb:de:47: - db:d5:5d:39:fc:88:a7:f3:d7:2a:74:f1:e8:5a:a2: - 3b:9f:50:ba:a6:8c:45:35:c2:50:65:95:dc:63:82: - ef:dd:bf:77:4d:9c:62:c9:63:73:16:d0:29:0f:49: - a9:48:f0:b3:aa:b7:6c:c5:a7:30:39:40:5d:ae:c4: - e2:5d:26:53:f0:ce:1c:23:08:61:a8:94:19:ba:04: - 62:40:ec:1f:38:70:77:12:06:71:a7:30:18:5d:25: - 27:a5 - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Key Usage: critical - Certificate Sign, CRL Sign - X509v3 Basic Constraints: critical - CA:TRUE - X509v3 Subject Key Identifier: - B6:08:7B:0D:7A:CC:AC:20:4C:86:56:32:5E:CF:AB:6E:85:2D:70:57 - X509v3 CRL Distribution Points: - - Full Name: - URI:http://www2.public-trust.com/crl/ct/ctroot.crl - - X509v3 Authority Key Identifier: - keyid:B6:08:7B:0D:7A:CC:AC:20:4C:86:56:32:5E:CF:AB:6E:85:2D:70:57 - - Signature Algorithm: sha1WithRSAEncryption - 56:ef:0a:23:a0:54:4e:95:97:c9:f8:89:da:45:c1:d4:a3:00: - 25:f4:1f:13:ab:b7:a3:85:58:69:c2:30:ad:d8:15:8a:2d:e3: - c9:cd:81:5a:f8:73:23:5a:a7:7c:05:f3:fd:22:3b:0e:d1:06: - c4:db:36:4c:73:04:8e:e5:b0:22:e4:c5:f3:2e:a5:d9:23:e3: - b8:4e:4a:20:a7:6e:02:24:9f:22:60:67:7b:8b:1d:72:09:c5: - 31:5c:e9:79:9f:80:47:3d:ad:a1:0b:07:14:3d:47:ff:03:69: - 1a:0c:0b:44:e7:63:25:a7:7f:b2:c9:b8:76:84:ed:23:f6:7d: - 07:ab:45:7e:d3:df:b3:bf:e9:8a:b6:cd:a8:a2:67:2b:52:d5: - b7:65:f0:39:4c:63:a0:91:79:93:52:0f:54:dd:83:bb:9f:d1: - 8f:a7:53:73:c3:cb:ff:30:ec:7c:04:b8:d8:44:1f:93:5f:71: - 09:22:b7:6e:3e:ea:1c:03:4e:9d:1a:20:61:fb:81:37:ec:5e: - fc:0a:45:ab:d7:e7:17:55:d0:a0:ea:60:9b:a6:f6:e3:8c:5b: - 29:c2:06:60:14:9d:2d:97:4c:a9:93:15:9d:61:c4:01:5f:48: - d6:58:bd:56:31:12:4e:11:c8:21:e0:b3:11:91:65:db:b4:a6: - 88:38:ce:55 ------BEGIN CERTIFICATE----- -MIIDoTCCAomgAwIBAgILBAAAAAABD4WqLUgwDQYJKoZIhvcNAQEFBQAwOzEYMBYG -A1UEChMPQ3liZXJ0cnVzdCwgSW5jMR8wHQYDVQQDExZDeWJlcnRydXN0IEdsb2Jh -bCBSb290MB4XDTA2MTIxNTA4MDAwMFoXDTIxMTIxNTA4MDAwMFowOzEYMBYGA1UE -ChMPQ3liZXJ0cnVzdCwgSW5jMR8wHQYDVQQDExZDeWJlcnRydXN0IEdsb2JhbCBS -b290MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA+Mi8vRRQZhP/8NN5 -7CPytxrHjoXxEnOmGaoQ25yiZXRadz5RfVb23CO21O1fWLE3TdVJDm71aofW0ozS -J8bi/zafmGWgE07GKmSb1ZASzxQG9Dvj1Ci+6A74q05IlG2OlTEQXO2iLb3VOm2y -HLtgwEZLAfVJrn5GitB0jaEMAs7u/OePuGtm839EAL9mJRQr3RAwHQeWP032a7iP -t3sMpTjr3kfb1V05/Iin89cqdPHoWqI7n1C6poxFNcJQZZXcY4Lv3b93TZxiyWNz -FtApD0mpSPCzqrdsxacwOUBdrsTiXSZT8M4cIwhhqJQZugRiQOwfOHB3EgZxpzAY -XSUnpQIDAQABo4GlMIGiMA4GA1UdDwEB/wQEAwIBBjAPBgNVHRMBAf8EBTADAQH/ -MB0GA1UdDgQWBBS2CHsNesysIEyGVjJez6tuhS1wVzA/BgNVHR8EODA2MDSgMqAw -hi5odHRwOi8vd3d3Mi5wdWJsaWMtdHJ1c3QuY29tL2NybC9jdC9jdHJvb3QuY3Js -MB8GA1UdIwQYMBaAFLYIew16zKwgTIZWMl7Pq26FLXBXMA0GCSqGSIb3DQEBBQUA -A4IBAQBW7wojoFROlZfJ+InaRcHUowAl9B8Tq7ejhVhpwjCt2BWKLePJzYFa+HMj -Wqd8BfP9IjsO0QbE2zZMcwSO5bAi5MXzLqXZI+O4Tkogp24CJJ8iYGd7ix1yCcUx -XOl5n4BHPa2hCwcUPUf/A2kaDAtE52Mlp3+yybh2hO0j9n0Hq0V+09+zv+mKts2o -omcrUtW3ZfA5TGOgkXmTUg9U3YO7n9GPp1Nzw8v/MOx8BLjYRB+TX3EJIrduPuoc -A06dGiBh+4E37F78CkWr1+cXVdCg6mCbpvbjjFspwgZgFJ0tl0ypkxWdYcQBX0jW -WL1WMRJOEcgh4LMRkWXbtKaIOM5V ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: 623603 (0x983f3) - Signature Algorithm: sha256WithRSAEncryption - Issuer: C=DE, O=D-Trust GmbH, CN=D-TRUST Root Class 3 CA 2 2009 - Validity - Not Before: Nov 5 08:35:58 2009 GMT - Not After : Nov 5 08:35:58 2029 GMT - Subject: C=DE, O=D-Trust GmbH, CN=D-TRUST Root Class 3 CA 2 2009 - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (2048 bit) - Modulus: - 00:d3:b2:4a:cf:7a:47:ef:75:9b:23:fa:3a:2f:d6: - 50:45:89:35:3a:c6:6b:db:fe:db:00:68:a8:e0:03: - 11:1d:37:50:08:9f:4d:4a:68:94:35:b3:53:d1:94: - 63:a7:20:56:af:de:51:78:ec:2a:3d:f3:48:48:50: - 3e:0a:df:46:55:8b:27:6d:c3:10:4d:0d:91:52:43: - d8:87:e0:5d:4e:36:b5:21:ca:5f:39:40:04:5f:5b: - 7e:cc:a3:c6:2b:a9:40:1e:d9:36:84:d6:48:f3:92: - 1e:34:46:20:24:c1:a4:51:8e:4a:1a:ef:50:3f:69: - 5d:19:7f:45:c3:c7:01:8f:51:c9:23:e8:72:ae:b4: - bc:56:09:7f:12:cb:1c:b1:af:29:90:0a:c9:55:cc: - 0f:d3:b4:1a:ed:47:35:5a:4a:ed:9c:73:04:21:d0: - aa:bd:0c:13:b5:00:ca:26:6c:c4:6b:0c:94:5a:95: - 94:da:50:9a:f1:ff:a5:2b:66:31:a4:c9:38:a0:df: - 1d:1f:b8:09:2e:f3:a7:e8:67:52:ab:95:1f:e0:46: - 3e:d8:a4:c3:ca:5a:c5:31:80:e8:48:9a:9f:94:69: - fe:19:dd:d8:73:7c:81:ca:96:de:8e:ed:b3:32:05: - 65:84:34:e6:e6:fd:57:10:b5:5f:76:bf:2f:b0:10: - 0d:c5 - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Basic Constraints: critical - CA:TRUE - X509v3 Subject Key Identifier: - FD:DA:14:C4:9F:30:DE:21:BD:1E:42:39:FC:AB:63:23:49:E0:F1:84 - X509v3 Key Usage: critical - Certificate Sign, CRL Sign - X509v3 CRL Distribution Points: - - Full Name: - URI:ldap://directory.d-trust.net/CN=D-TRUST%20Root%20Class%203%20CA%202%202009,O=D-Trust%20GmbH,C=DE?certificaterevocationlist - - Full Name: - URI:http://www.d-trust.net/crl/d-trust_root_class_3_ca_2_2009.crl - - Signature Algorithm: sha256WithRSAEncryption - 7f:97:db:30:c8:df:a4:9c:7d:21:7a:80:70:ce:14:12:69:88: - 14:95:60:44:01:ac:b2:e9:30:4f:9b:50:c2:66:d8:7e:8d:30: - b5:70:31:e9:e2:69:c7:f3:70:db:20:15:86:d0:0d:f0:be:ac: - 01:75:84:ce:7e:9f:4d:bf:b7:60:3b:9c:f3:ca:1d:e2:5e:68: - d8:a3:9d:97:e5:40:60:d2:36:21:fe:d0:b4:b8:17:da:74:a3: - 7f:d4:df:b0:98:02:ac:6f:6b:6b:2c:25:24:72:a1:65:ee:25: - 5a:e5:e6:32:e7:f2:df:ab:49:fa:f3:90:69:23:db:04:d9:e7: - 5c:58:fc:65:d4:97:be:cc:fc:2e:0a:cc:25:2a:35:04:f8:60: - 91:15:75:3d:41:ff:23:1f:19:c8:6c:eb:82:53:04:a6:e4:4c: - 22:4d:8d:8c:ba:ce:5b:73:ec:64:54:50:6d:d1:9c:55:fb:69: - c3:36:c3:8c:bc:3c:85:a6:6b:0a:26:0d:e0:93:98:60:ae:7e: - c6:24:97:8a:61:5f:91:8e:66:92:09:87:36:cd:8b:9b:2d:3e: - f6:51:d4:50:d4:59:28:bd:83:f2:cc:28:7b:53:86:6d:d8:26: - 88:70:d7:ea:91:cd:3e:b9:ca:c0:90:6e:5a:c6:5e:74:65:d7: - 5c:fe:a3:e2 ------BEGIN CERTIFICATE----- -MIIEMzCCAxugAwIBAgIDCYPzMA0GCSqGSIb3DQEBCwUAME0xCzAJBgNVBAYTAkRF -MRUwEwYDVQQKDAxELVRydXN0IEdtYkgxJzAlBgNVBAMMHkQtVFJVU1QgUm9vdCBD -bGFzcyAzIENBIDIgMjAwOTAeFw0wOTExMDUwODM1NThaFw0yOTExMDUwODM1NTha -ME0xCzAJBgNVBAYTAkRFMRUwEwYDVQQKDAxELVRydXN0IEdtYkgxJzAlBgNVBAMM -HkQtVFJVU1QgUm9vdCBDbGFzcyAzIENBIDIgMjAwOTCCASIwDQYJKoZIhvcNAQEB -BQADggEPADCCAQoCggEBANOySs96R+91myP6Oi/WUEWJNTrGa9v+2wBoqOADER03 -UAifTUpolDWzU9GUY6cgVq/eUXjsKj3zSEhQPgrfRlWLJ23DEE0NkVJD2IfgXU42 -tSHKXzlABF9bfsyjxiupQB7ZNoTWSPOSHjRGICTBpFGOShrvUD9pXRl/RcPHAY9R -ySPocq60vFYJfxLLHLGvKZAKyVXMD9O0Gu1HNVpK7ZxzBCHQqr0ME7UAyiZsxGsM -lFqVlNpQmvH/pStmMaTJOKDfHR+4CS7zp+hnUquVH+BGPtikw8paxTGA6Eian5Rp -/hnd2HN8gcqW3o7tszIFZYQ05ub9VxC1X3a/L7AQDcUCAwEAAaOCARowggEWMA8G -A1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFP3aFMSfMN4hvR5COfyrYyNJ4PGEMA4G -A1UdDwEB/wQEAwIBBjCB0wYDVR0fBIHLMIHIMIGAoH6gfIZ6bGRhcDovL2RpcmVj -dG9yeS5kLXRydXN0Lm5ldC9DTj1ELVRSVVNUJTIwUm9vdCUyMENsYXNzJTIwMyUy -MENBJTIwMiUyMDIwMDksTz1ELVRydXN0JTIwR21iSCxDPURFP2NlcnRpZmljYXRl -cmV2b2NhdGlvbmxpc3QwQ6BBoD+GPWh0dHA6Ly93d3cuZC10cnVzdC5uZXQvY3Js -L2QtdHJ1c3Rfcm9vdF9jbGFzc18zX2NhXzJfMjAwOS5jcmwwDQYJKoZIhvcNAQEL -BQADggEBAH+X2zDI36ScfSF6gHDOFBJpiBSVYEQBrLLpME+bUMJm2H6NMLVwMeni -acfzcNsgFYbQDfC+rAF1hM5+n02/t2A7nPPKHeJeaNijnZflQGDSNiH+0LS4F9p0 -o3/U37CYAqxva2ssJSRyoWXuJVrl5jLn8t+rSfrzkGkj2wTZ51xY/GXUl77M/C4K -zCUqNQT4YJEVdT1B/yMfGchs64JTBKbkTCJNjYy6zltz7GRUUG3RnFX7acM2w4y8 -PIWmawomDeCTmGCufsYkl4phX5GOZpIJhzbNi5stPvZR1FDUWSi9g/LMKHtThm3Y -Johw1+qRzT65ysCQblrGXnRl11z+o+I= ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: 623604 (0x983f4) - Signature Algorithm: sha256WithRSAEncryption - Issuer: C=DE, O=D-Trust GmbH, CN=D-TRUST Root Class 3 CA 2 EV 2009 - Validity - Not Before: Nov 5 08:50:46 2009 GMT - Not After : Nov 5 08:50:46 2029 GMT - Subject: C=DE, O=D-Trust GmbH, CN=D-TRUST Root Class 3 CA 2 EV 2009 - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (2048 bit) - Modulus: - 00:99:f1:84:34:70:ba:2f:b7:30:a0:8e:bd:7c:04: - cf:be:62:bc:99:fd:82:97:d2:7a:0a:67:96:38:09: - f6:10:4e:95:22:73:99:8d:da:15:2d:e7:05:fc:19: - 73:22:b7:8e:98:00:bc:3c:3d:ac:a1:6c:fb:d6:79: - 25:4b:ad:f0:cc:64:da:88:3e:29:b8:0f:09:d3:34: - dd:33:f5:62:d1:e1:cd:19:e9:ee:18:4f:4c:58:ae: - e2:1e:d6:0c:5b:15:5a:d8:3a:b8:c4:18:64:1e:e3: - 33:b2:b5:89:77:4e:0c:bf:d9:94:6b:13:97:6f:12: - a3:fe:99:a9:04:cc:15:ec:60:68:36:ed:08:7b:b7: - f5:bf:93:ed:66:31:83:8c:c6:71:34:87:4e:17:ea: - af:8b:91:8d:1c:56:41:ae:22:37:5e:37:f2:1d:d9: - d1:2d:0d:2f:69:51:a7:be:66:a6:8a:3a:2a:bd:c7: - 1a:b1:e1:14:f0:be:3a:1d:b9:cf:5b:b1:6a:fe:b4: - b1:46:20:a2:fb:1e:3b:70:ef:93:98:7d:8c:73:96: - f2:c5:ef:85:70:ad:29:26:fc:1e:04:3e:1c:a0:d8: - 0f:cb:52:83:62:7c:ee:8b:53:95:90:a9:57:a2:ea: - 61:05:d8:f9:4d:c4:27:fa:6e:ad:ed:f9:d7:51:f7: - 6b:a5 - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Basic Constraints: critical - CA:TRUE - X509v3 Subject Key Identifier: - D3:94:8A:4C:62:13:2A:19:2E:CC:AF:72:8A:7D:36:D7:9A:1C:DC:67 - X509v3 Key Usage: critical - Certificate Sign, CRL Sign - X509v3 CRL Distribution Points: - - Full Name: - URI:ldap://directory.d-trust.net/CN=D-TRUST%20Root%20Class%203%20CA%202%20EV%202009,O=D-Trust%20GmbH,C=DE?certificaterevocationlist - - Full Name: - URI:http://www.d-trust.net/crl/d-trust_root_class_3_ca_2_ev_2009.crl - - Signature Algorithm: sha256WithRSAEncryption - 34:ed:7b:5a:3c:a4:94:88:ef:1a:11:75:07:2f:b3:fe:3c:fa: - 1e:51:26:eb:87:f6:29:de:e0:f1:d4:c6:24:09:e9:c1:cf:55: - 1b:b4:30:d9:ce:1a:fe:06:51:a6:15:a4:2d:ef:b2:4b:bf:20: - 28:25:49:d1:a6:36:77:34:e8:64:df:52:b1:11:c7:73:7a:cd: - 39:9e:c2:ad:8c:71:21:f2:5a:6b:af:df:3c:4e:55:af:b2:84: - 65:14:89:b9:77:cb:2a:31:be:cf:a3:6d:cf:6f:48:94:32:46: - 6f:e7:71:8c:a0:a6:84:19:37:07:f2:03:45:09:2b:86:75:7c: - df:5f:69:57:00:db:6e:d8:a6:72:22:4b:50:d4:75:98:56:df: - b7:18:ff:43:43:50:ae:7a:44:7b:f0:79:51:d7:43:3d:a7:d3: - 81:d3:f0:c9:4f:b9:da:c6:97:86:d0:82:c3:e4:42:6d:fe:b0: - e2:64:4e:0e:26:e7:40:34:26:b5:08:89:d7:08:63:63:38:27: - 75:1e:33:ea:6e:a8:dd:9f:99:4f:74:4d:81:89:80:4b:dd:9a: - 97:29:5c:2f:be:81:41:b9:8c:ff:ea:7d:60:06:9e:cd:d7:3d: - d3:2e:a3:15:bc:a8:e6:26:e5:6f:c3:dc:b8:03:21:ea:9f:16: - f1:2c:54:b5 ------BEGIN CERTIFICATE----- -MIIEQzCCAyugAwIBAgIDCYP0MA0GCSqGSIb3DQEBCwUAMFAxCzAJBgNVBAYTAkRF -MRUwEwYDVQQKDAxELVRydXN0IEdtYkgxKjAoBgNVBAMMIUQtVFJVU1QgUm9vdCBD -bGFzcyAzIENBIDIgRVYgMjAwOTAeFw0wOTExMDUwODUwNDZaFw0yOTExMDUwODUw -NDZaMFAxCzAJBgNVBAYTAkRFMRUwEwYDVQQKDAxELVRydXN0IEdtYkgxKjAoBgNV -BAMMIUQtVFJVU1QgUm9vdCBDbGFzcyAzIENBIDIgRVYgMjAwOTCCASIwDQYJKoZI -hvcNAQEBBQADggEPADCCAQoCggEBAJnxhDRwui+3MKCOvXwEz75ivJn9gpfSegpn -ljgJ9hBOlSJzmY3aFS3nBfwZcyK3jpgAvDw9rKFs+9Z5JUut8Mxk2og+KbgPCdM0 -3TP1YtHhzRnp7hhPTFiu4h7WDFsVWtg6uMQYZB7jM7K1iXdODL/ZlGsTl28So/6Z -qQTMFexgaDbtCHu39b+T7WYxg4zGcTSHThfqr4uRjRxWQa4iN1438h3Z0S0NL2lR -p75mpoo6Kr3HGrHhFPC+Oh25z1uxav60sUYgovseO3Dvk5h9jHOW8sXvhXCtKSb8 -HgQ+HKDYD8tSg2J87otTlZCpV6LqYQXY+U3EJ/pure3511H3a6UCAwEAAaOCASQw -ggEgMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFNOUikxiEyoZLsyvcop9Ntea -HNxnMA4GA1UdDwEB/wQEAwIBBjCB3QYDVR0fBIHVMIHSMIGHoIGEoIGBhn9sZGFw -Oi8vZGlyZWN0b3J5LmQtdHJ1c3QubmV0L0NOPUQtVFJVU1QlMjBSb290JTIwQ2xh -c3MlMjAzJTIwQ0ElMjAyJTIwRVYlMjAyMDA5LE89RC1UcnVzdCUyMEdtYkgsQz1E -RT9jZXJ0aWZpY2F0ZXJldm9jYXRpb25saXN0MEagRKBChkBodHRwOi8vd3d3LmQt -dHJ1c3QubmV0L2NybC9kLXRydXN0X3Jvb3RfY2xhc3NfM19jYV8yX2V2XzIwMDku -Y3JsMA0GCSqGSIb3DQEBCwUAA4IBAQA07XtaPKSUiO8aEXUHL7P+PPoeUSbrh/Yp -3uDx1MYkCenBz1UbtDDZzhr+BlGmFaQt77JLvyAoJUnRpjZ3NOhk31KxEcdzes05 -nsKtjHEh8lprr988TlWvsoRlFIm5d8sqMb7Po23Pb0iUMkZv53GMoKaEGTcH8gNF -CSuGdXzfX2lXANtu2KZyIktQ1HWYVt+3GP9DQ1CuekR78HlR10M9p9OB0/DJT7na -xpeG0ILD5EJt/rDiZE4OJudANCa1CInXCGNjOCd1HjPqbqjdn5lPdE2BiYBL3ZqX -KVwvvoFBuYz/6n1gBp7N1z3TLqMVvKjmJuVvw9y4AyHqnxbxLFS1 ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: - 0d:5e:99:0a:d6:9d:b7:78:ec:d8:07:56:3b:86:15:d9 - Signature Algorithm: sha1WithRSAEncryption - Issuer: C=US, O=Digital Signature Trust, OU=DST ACES, CN=DST ACES CA X6 - Validity - Not Before: Nov 20 21:19:58 2003 GMT - Not After : Nov 20 21:19:58 2017 GMT - Subject: C=US, O=Digital Signature Trust, OU=DST ACES, CN=DST ACES CA X6 - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (2048 bit) - Modulus: - 00:b9:3d:f5:2c:c9:94:dc:75:8a:95:5d:63:e8:84: - 77:76:66:b9:59:91:5c:46:dd:92:3e:9f:f9:0e:03: - b4:3d:61:92:bd:23:26:b5:63:ee:92:d2:9e:d6:3c: - c8:0d:90:5f:64:81:b1:a8:08:0d:4c:d8:f9:d3:05: - 28:52:b4:01:25:c5:95:1c:0c:7e:3e:10:84:75:cf: - c1:19:91:63:cf:e8:a8:91:88:b9:43:52:bb:80:b1: - 55:89:8b:31:fa:d0:b7:76:be:41:3d:30:9a:a4:22: - 25:17:73:e8:1e:e2:d3:ac:2a:bd:5b:38:21:d5:2a: - 4b:d7:55:7d:e3:3a:55:bd:d7:6d:6b:02:57:6b:e6: - 47:7c:08:c8:82:ba:de:a7:87:3d:a1:6d:b8:30:56: - c2:b3:02:81:5f:2d:f5:e2:9a:30:18:28:b8:66:d3: - cb:01:96:6f:ea:8a:45:55:d6:e0:9d:ff:67:2b:17: - 02:a6:4e:1a:6a:11:0b:7e:b7:7b:e7:98:d6:8c:76: - 6f:c1:3b:db:50:93:7e:e5:d0:8e:1f:37:b8:bd:ba: - c6:9f:6c:e9:7c:33:f2:32:3c:26:47:fa:27:24:02: - c9:7e:1d:5b:88:42:13:6a:35:7c:7d:35:e9:2e:66: - 91:72:93:d5:32:26:c4:74:f5:53:a3:b3:5d:9a:f6: - 09:cb - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Basic Constraints: critical - CA:TRUE - X509v3 Key Usage: critical - Digital Signature, Non Repudiation, Certificate Sign, CRL Sign - X509v3 Subject Alternative Name: - email:pki-ops@trustdst.com - X509v3 Certificate Policies: - Policy: 2.16.840.1.101.3.2.1.1.1 - CPS: http://www.trustdst.com/certificates/policy/ACES-index.html - - X509v3 Subject Key Identifier: - 09:72:06:4E:18:43:0F:E5:D6:CC:C3:6A:8B:31:7B:78:8F:A8:83:B8 - Signature Algorithm: sha1WithRSAEncryption - a3:d8:8e:d6:b2:db:ce:05:e7:32:cd:01:d3:04:03:e5:76:e4: - 56:2b:9c:99:90:e8:08:30:6c:df:7d:3d:ee:e5:bf:b5:24:40: - 84:49:e1:d1:28:ae:c4:c2:3a:53:30:88:f1:f5:77:6e:51:ca: - fa:ff:99:af:24:5f:1b:a0:fd:f2:ac:84:ca:df:a9:f0:5f:04: - 2e:ad:16:bf:21:97:10:81:3d:e3:ff:87:8d:32:dc:94:e5:47: - 8a:5e:6a:13:c9:94:95:3d:d2:ee:c8:34:95:d0:80:d4:ad:32: - 08:80:54:3c:e0:bd:52:53:d7:52:7c:b2:69:3f:7f:7a:cf:6a: - 74:ca:fa:04:2a:9c:4c:5a:06:a5:e9:20:ad:45:66:0f:69:f1: - dd:bf:e9:e3:32:8b:fa:e0:c1:86:4d:72:3c:2e:d8:93:78:0a: - 2a:f8:d8:d2:27:3d:19:89:5f:5a:7b:8a:3b:cc:0c:da:51:ae: - c7:0b:f7:2b:b0:37:05:ec:bc:57:23:e2:38:d2:9b:68:f3:56: - 12:88:4f:42:7c:b8:31:c4:b5:db:e4:c8:21:34:e9:48:11:35: - ee:fa:c7:92:57:c5:9f:34:e4:c7:f6:f7:0e:0b:4c:9c:68:78: - 7b:71:31:c7:eb:1e:e0:67:41:f3:b7:a0:a7:cd:e5:7a:33:36: - 6a:fa:9a:2b ------BEGIN CERTIFICATE----- -MIIECTCCAvGgAwIBAgIQDV6ZCtadt3js2AdWO4YV2TANBgkqhkiG9w0BAQUFADBb -MQswCQYDVQQGEwJVUzEgMB4GA1UEChMXRGlnaXRhbCBTaWduYXR1cmUgVHJ1c3Qx -ETAPBgNVBAsTCERTVCBBQ0VTMRcwFQYDVQQDEw5EU1QgQUNFUyBDQSBYNjAeFw0w -MzExMjAyMTE5NThaFw0xNzExMjAyMTE5NThaMFsxCzAJBgNVBAYTAlVTMSAwHgYD -VQQKExdEaWdpdGFsIFNpZ25hdHVyZSBUcnVzdDERMA8GA1UECxMIRFNUIEFDRVMx -FzAVBgNVBAMTDkRTVCBBQ0VTIENBIFg2MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8A -MIIBCgKCAQEAuT31LMmU3HWKlV1j6IR3dma5WZFcRt2SPp/5DgO0PWGSvSMmtWPu -ktKe1jzIDZBfZIGxqAgNTNj50wUoUrQBJcWVHAx+PhCEdc/BGZFjz+iokYi5Q1K7 -gLFViYsx+tC3dr5BPTCapCIlF3PoHuLTrCq9Wzgh1SpL11V94zpVvddtawJXa+ZH -fAjIgrrep4c9oW24MFbCswKBXy314powGCi4ZtPLAZZv6opFVdbgnf9nKxcCpk4a -ahELfrd755jWjHZvwTvbUJN+5dCOHze4vbrGn2zpfDPyMjwmR/onJALJfh1biEIT -ajV8fTXpLmaRcpPVMibEdPVTo7NdmvYJywIDAQABo4HIMIHFMA8GA1UdEwEB/wQF -MAMBAf8wDgYDVR0PAQH/BAQDAgHGMB8GA1UdEQQYMBaBFHBraS1vcHNAdHJ1c3Rk -c3QuY29tMGIGA1UdIARbMFkwVwYKYIZIAWUDAgEBATBJMEcGCCsGAQUFBwIBFjto -dHRwOi8vd3d3LnRydXN0ZHN0LmNvbS9jZXJ0aWZpY2F0ZXMvcG9saWN5L0FDRVMt -aW5kZXguaHRtbDAdBgNVHQ4EFgQUCXIGThhDD+XWzMNqizF7eI+og7gwDQYJKoZI -hvcNAQEFBQADggEBAKPYjtay284F5zLNAdMEA+V25FYrnJmQ6AgwbN99Pe7lv7Uk -QIRJ4dEorsTCOlMwiPH1d25Ryvr/ma8kXxug/fKshMrfqfBfBC6tFr8hlxCBPeP/ -h40y3JTlR4peahPJlJU90u7INJXQgNStMgiAVDzgvVJT11J8smk/f3rPanTK+gQq -nExaBqXpIK1FZg9p8d2/6eMyi/rgwYZNcjwu2JN4Cir42NInPRmJX1p7ijvMDNpR -rscL9yuwNwXsvFcj4jjSm2jzVhKIT0J8uDHEtdvkyCE06UgRNe76x5JXxZ805Mf2 -9w4LTJxoeHtxMcfrHuBnQfO3oKfN5XozNmr6mis= ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: - 44:af:b0:80:d6:a3:27:ba:89:30:39:86:2e:f8:40:6b - Signature Algorithm: sha1WithRSAEncryption - Issuer: O=Digital Signature Trust Co., CN=DST Root CA X3 - Validity - Not Before: Sep 30 21:12:19 2000 GMT - Not After : Sep 30 14:01:15 2021 GMT - Subject: O=Digital Signature Trust Co., CN=DST Root CA X3 - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (2048 bit) - Modulus: - 00:df:af:e9:97:50:08:83:57:b4:cc:62:65:f6:90: - 82:ec:c7:d3:2c:6b:30:ca:5b:ec:d9:c3:7d:c7:40: - c1:18:14:8b:e0:e8:33:76:49:2a:e3:3f:21:49:93: - ac:4e:0e:af:3e:48:cb:65:ee:fc:d3:21:0f:65:d2: - 2a:d9:32:8f:8c:e5:f7:77:b0:12:7b:b5:95:c0:89: - a3:a9:ba:ed:73:2e:7a:0c:06:32:83:a2:7e:8a:14: - 30:cd:11:a0:e1:2a:38:b9:79:0a:31:fd:50:bd:80: - 65:df:b7:51:63:83:c8:e2:88:61:ea:4b:61:81:ec: - 52:6b:b9:a2:e2:4b:1a:28:9f:48:a3:9e:0c:da:09: - 8e:3e:17:2e:1e:dd:20:df:5b:c6:2a:8a:ab:2e:bd: - 70:ad:c5:0b:1a:25:90:74:72:c5:7b:6a:ab:34:d6: - 30:89:ff:e5:68:13:7b:54:0b:c8:d6:ae:ec:5a:9c: - 92:1e:3d:64:b3:8c:c6:df:bf:c9:41:70:ec:16:72: - d5:26:ec:38:55:39:43:d0:fc:fd:18:5c:40:f1:97: - eb:d5:9a:9b:8d:1d:ba:da:25:b9:c6:d8:df:c1:15: - 02:3a:ab:da:6e:f1:3e:2e:f5:5c:08:9c:3c:d6:83: - 69:e4:10:9b:19:2a:b6:29:57:e3:e5:3d:9b:9f:f0: - 02:5d - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Basic Constraints: critical - CA:TRUE - X509v3 Key Usage: critical - Certificate Sign, CRL Sign - X509v3 Subject Key Identifier: - C4:A7:B1:A4:7B:2C:71:FA:DB:E1:4B:90:75:FF:C4:15:60:85:89:10 - Signature Algorithm: sha1WithRSAEncryption - a3:1a:2c:9b:17:00:5c:a9:1e:ee:28:66:37:3a:bf:83:c7:3f: - 4b:c3:09:a0:95:20:5d:e3:d9:59:44:d2:3e:0d:3e:bd:8a:4b: - a0:74:1f:ce:10:82:9c:74:1a:1d:7e:98:1a:dd:cb:13:4b:b3: - 20:44:e4:91:e9:cc:fc:7d:a5:db:6a:e5:fe:e6:fd:e0:4e:dd: - b7:00:3a:b5:70:49:af:f2:e5:eb:02:f1:d1:02:8b:19:cb:94: - 3a:5e:48:c4:18:1e:58:19:5f:1e:02:5a:f0:0c:f1:b1:ad:a9: - dc:59:86:8b:6e:e9:91:f5:86:ca:fa:b9:66:33:aa:59:5b:ce: - e2:a7:16:73:47:cb:2b:cc:99:b0:37:48:cf:e3:56:4b:f5:cf: - 0f:0c:72:32:87:c6:f0:44:bb:53:72:6d:43:f5:26:48:9a:52: - 67:b7:58:ab:fe:67:76:71:78:db:0d:a2:56:14:13:39:24:31: - 85:a2:a8:02:5a:30:47:e1:dd:50:07:bc:02:09:90:00:eb:64: - 63:60:9b:16:bc:88:c9:12:e6:d2:7d:91:8b:f9:3d:32:8d:65: - b4:e9:7c:b1:57:76:ea:c5:b6:28:39:bf:15:65:1c:c8:f6:77: - 96:6a:0a:8d:77:0b:d8:91:0b:04:8e:07:db:29:b6:0a:ee:9d: - 82:35:35:10 ------BEGIN CERTIFICATE----- -MIIDSjCCAjKgAwIBAgIQRK+wgNajJ7qJMDmGLvhAazANBgkqhkiG9w0BAQUFADA/ -MSQwIgYDVQQKExtEaWdpdGFsIFNpZ25hdHVyZSBUcnVzdCBDby4xFzAVBgNVBAMT -DkRTVCBSb290IENBIFgzMB4XDTAwMDkzMDIxMTIxOVoXDTIxMDkzMDE0MDExNVow -PzEkMCIGA1UEChMbRGlnaXRhbCBTaWduYXR1cmUgVHJ1c3QgQ28uMRcwFQYDVQQD -Ew5EU1QgUm9vdCBDQSBYMzCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEB -AN+v6ZdQCINXtMxiZfaQguzH0yxrMMpb7NnDfcdAwRgUi+DoM3ZJKuM/IUmTrE4O -rz5Iy2Xu/NMhD2XSKtkyj4zl93ewEnu1lcCJo6m67XMuegwGMoOifooUMM0RoOEq -OLl5CjH9UL2AZd+3UWODyOKIYepLYYHsUmu5ouJLGiifSKOeDNoJjj4XLh7dIN9b -xiqKqy69cK3FCxolkHRyxXtqqzTWMIn/5WgTe1QLyNau7Fqckh49ZLOMxt+/yUFw -7BZy1SbsOFU5Q9D8/RhcQPGX69Wam40dutolucbY38EVAjqr2m7xPi71XAicPNaD -aeQQmxkqtilX4+U9m5/wAl0CAwEAAaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAOBgNV -HQ8BAf8EBAMCAQYwHQYDVR0OBBYEFMSnsaR7LHH62+FLkHX/xBVghYkQMA0GCSqG -SIb3DQEBBQUAA4IBAQCjGiybFwBcqR7uKGY3Or+Dxz9LwwmglSBd49lZRNI+DT69 -ikugdB/OEIKcdBodfpga3csTS7MgROSR6cz8faXbauX+5v3gTt23ADq1cEmv8uXr -AvHRAosZy5Q6XkjEGB5YGV8eAlrwDPGxrancWYaLbumR9YbK+rlmM6pZW87ipxZz -R8srzJmwN0jP41ZL9c8PDHIyh8bwRLtTcm1D9SZImlJnt1ir/md2cXjbDaJWFBM5 -JDGFoqgCWjBH4d1QB7wCCZAA62RjYJsWvIjJEubSfZGL+T0yjWW06XyxV3bqxbYo -Ob8VZRzI9neWagqNdwvYkQsEjgfbKbYK7p2CNTUQ ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: 38 (0x26) - Signature Algorithm: sha1WithRSAEncryption - Issuer: C=DE, O=Deutsche Telekom AG, OU=T-TeleSec Trust Center, CN=Deutsche Telekom Root CA 2 - Validity - Not Before: Jul 9 12:11:00 1999 GMT - Not After : Jul 9 23:59:00 2019 GMT - Subject: C=DE, O=Deutsche Telekom AG, OU=T-TeleSec Trust Center, CN=Deutsche Telekom Root CA 2 - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (2048 bit) - Modulus: - 00:ab:0b:a3:35:e0:8b:29:14:b1:14:85:af:3c:10: - e4:39:6f:35:5d:4a:ae:dd:ea:61:8d:95:49:f4:6f: - 64:a3:1a:60:66:a4:a9:40:22:84:d9:d4:a5:e5:78: - 93:0e:68:01:ad:b9:4d:5c:3a:ce:d3:b8:a8:42:40: - df:cf:a3:ba:82:59:6a:92:1b:ac:1c:9a:da:08:2b: - 25:27:f9:69:23:47:f1:e0:eb:2c:7a:9b:f5:13:02: - d0:7e:34:7c:c2:9e:3c:00:59:ab:f5:da:0c:f5:32: - 3c:2b:ac:50:da:d6:c3:de:83:94:ca:a8:0c:99:32: - 0e:08:48:56:5b:6a:fb:da:e1:58:58:01:49:5f:72: - 41:3c:15:06:01:8e:5d:ad:aa:b8:93:b4:cd:9e:eb: - a7:e8:6a:2d:52:34:db:3a:ef:5c:75:51:da:db:f3: - 31:f9:ee:71:98:32:c4:54:15:44:0c:f9:9b:55:ed: - ad:df:18:08:a0:a3:86:8a:49:ee:53:05:8f:19:4c: - d5:de:58:79:9b:d2:6a:1c:42:ab:c5:d5:a7:cf:68: - 0f:96:e4:e1:61:98:76:61:c8:91:7c:d6:3e:00:e2: - 91:50:87:e1:9d:0a:e6:ad:97:d2:1d:c6:3a:7d:cb: - bc:da:03:34:d5:8e:5b:01:f5:6a:07:b7:16:b6:6e: - 4a:7f - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Subject Key Identifier: - 31:C3:79:1B:BA:F5:53:D7:17:E0:89:7A:2D:17:6C:0A:B3:2B:9D:33 - X509v3 Basic Constraints: - CA:TRUE, pathlen:5 - X509v3 Key Usage: critical - Certificate Sign, CRL Sign - Signature Algorithm: sha1WithRSAEncryption - 94:64:59:ad:39:64:e7:29:eb:13:fe:5a:c3:8b:13:57:c8:04: - 24:f0:74:77:c0:60:e3:67:fb:e9:89:a6:83:bf:96:82:7c:6e: - d4:c3:3d:ef:9e:80:6e:bb:29:b4:98:7a:b1:3b:54:eb:39:17: - 47:7e:1a:8e:0b:fc:1f:31:59:31:04:b2:ce:17:f3:2c:c7:62: - 36:55:e2:22:d8:89:55:b4:98:48:aa:64:fa:d6:1c:36:d8:44: - 78:5a:5a:23:3a:57:97:f5:7a:30:4f:ae:9f:6a:4c:4b:2b:8e: - a0:03:e3:3e:e0:a9:d4:d2:7b:d2:b3:a8:e2:72:3c:ad:9e:ff: - 80:59:e4:9b:45:b4:f6:3b:b0:cd:39:19:98:32:e5:ea:21:61: - 90:e4:31:21:8e:34:b1:f7:2f:35:4a:85:10:da:e7:8a:37:21: - be:59:63:e0:f2:85:88:31:53:d4:54:14:85:70:79:f4:2e:06: - 77:27:75:2f:1f:b8:8a:f9:fe:c5:ba:d8:36:e4:83:ec:e7:65: - b7:bf:63:5a:f3:46:af:81:94:37:d4:41:8c:d6:23:d6:1e:cf: - f5:68:1b:44:63:a2:5a:ba:a7:35:59:a1:e5:70:05:9b:0e:23: - 57:99:94:0a:6d:ba:39:63:28:86:92:f3:18:84:d8:fb:d1:cf: - 05:56:64:57 ------BEGIN CERTIFICATE----- -MIIDnzCCAoegAwIBAgIBJjANBgkqhkiG9w0BAQUFADBxMQswCQYDVQQGEwJERTEc -MBoGA1UEChMTRGV1dHNjaGUgVGVsZWtvbSBBRzEfMB0GA1UECxMWVC1UZWxlU2Vj -IFRydXN0IENlbnRlcjEjMCEGA1UEAxMaRGV1dHNjaGUgVGVsZWtvbSBSb290IENB -IDIwHhcNOTkwNzA5MTIxMTAwWhcNMTkwNzA5MjM1OTAwWjBxMQswCQYDVQQGEwJE -RTEcMBoGA1UEChMTRGV1dHNjaGUgVGVsZWtvbSBBRzEfMB0GA1UECxMWVC1UZWxl -U2VjIFRydXN0IENlbnRlcjEjMCEGA1UEAxMaRGV1dHNjaGUgVGVsZWtvbSBSb290 -IENBIDIwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCrC6M14IspFLEU -ha88EOQ5bzVdSq7d6mGNlUn0b2SjGmBmpKlAIoTZ1KXleJMOaAGtuU1cOs7TuKhC -QN/Po7qCWWqSG6wcmtoIKyUn+WkjR/Hg6yx6m/UTAtB+NHzCnjwAWav12gz1Mjwr -rFDa1sPeg5TKqAyZMg4ISFZbavva4VhYAUlfckE8FQYBjl2tqriTtM2e66foai1S -NNs671x1Udrb8zH57nGYMsRUFUQM+ZtV7a3fGAigo4aKSe5TBY8ZTNXeWHmb0moc -QqvF1afPaA+W5OFhmHZhyJF81j4A4pFQh+GdCuatl9Idxjp9y7zaAzTVjlsB9WoH -txa2bkp/AgMBAAGjQjBAMB0GA1UdDgQWBBQxw3kbuvVT1xfgiXotF2wKsyudMzAP -BgNVHRMECDAGAQH/AgEFMA4GA1UdDwEB/wQEAwIBBjANBgkqhkiG9w0BAQUFAAOC -AQEAlGRZrTlk5ynrE/5aw4sTV8gEJPB0d8Bg42f76Ymmg7+Wgnxu1MM9756Abrsp -tJh6sTtU6zkXR34ajgv8HzFZMQSyzhfzLMdiNlXiItiJVbSYSKpk+tYcNthEeFpa -IzpXl/V6ME+un2pMSyuOoAPjPuCp1NJ70rOo4nI8rZ7/gFnkm0W09juwzTkZmDLl -6iFhkOQxIY40sfcvNUqFENrnijchvllj4PKFiDFT1FQUhXB59C4Gdyd1Lx+4ivn+ -xbrYNuSD7Odlt79jWvNGr4GUN9RBjNYj1h7P9WgbRGOiWrqnNVmh5XAFmw4jV5mU -Cm26OWMohpLzGITY+9HPBVZkVw== ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: - 0c:e7:e0:e5:17:d8:46:fe:8f:e5:60:fc:1b:f0:30:39 - Signature Algorithm: sha1WithRSAEncryption - Issuer: C=US, O=DigiCert Inc, OU=www.digicert.com, CN=DigiCert Assured ID Root CA - Validity - Not Before: Nov 10 00:00:00 2006 GMT - Not After : Nov 10 00:00:00 2031 GMT - Subject: C=US, O=DigiCert Inc, OU=www.digicert.com, CN=DigiCert Assured ID Root CA - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (2048 bit) - Modulus: - 00:ad:0e:15:ce:e4:43:80:5c:b1:87:f3:b7:60:f9: - 71:12:a5:ae:dc:26:94:88:aa:f4:ce:f5:20:39:28: - 58:60:0c:f8:80:da:a9:15:95:32:61:3c:b5:b1:28: - 84:8a:8a:dc:9f:0a:0c:83:17:7a:8f:90:ac:8a:e7: - 79:53:5c:31:84:2a:f6:0f:98:32:36:76:cc:de:dd: - 3c:a8:a2:ef:6a:fb:21:f2:52:61:df:9f:20:d7:1f: - e2:b1:d9:fe:18:64:d2:12:5b:5f:f9:58:18:35:bc: - 47:cd:a1:36:f9:6b:7f:d4:b0:38:3e:c1:1b:c3:8c: - 33:d9:d8:2f:18:fe:28:0f:b3:a7:83:d6:c3:6e:44: - c0:61:35:96:16:fe:59:9c:8b:76:6d:d7:f1:a2:4b: - 0d:2b:ff:0b:72:da:9e:60:d0:8e:90:35:c6:78:55: - 87:20:a1:cf:e5:6d:0a:c8:49:7c:31:98:33:6c:22: - e9:87:d0:32:5a:a2:ba:13:82:11:ed:39:17:9d:99: - 3a:72:a1:e6:fa:a4:d9:d5:17:31:75:ae:85:7d:22: - ae:3f:01:46:86:f6:28:79:c8:b1:da:e4:57:17:c4: - 7e:1c:0e:b0:b4:92:a6:56:b3:bd:b2:97:ed:aa:a7: - f0:b7:c5:a8:3f:95:16:d0:ff:a1:96:eb:08:5f:18: - 77:4f - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Key Usage: critical - Digital Signature, Certificate Sign, CRL Sign - X509v3 Basic Constraints: critical - CA:TRUE - X509v3 Subject Key Identifier: - 45:EB:A2:AF:F4:92:CB:82:31:2D:51:8B:A7:A7:21:9D:F3:6D:C8:0F - X509v3 Authority Key Identifier: - keyid:45:EB:A2:AF:F4:92:CB:82:31:2D:51:8B:A7:A7:21:9D:F3:6D:C8:0F - - Signature Algorithm: sha1WithRSAEncryption - a2:0e:bc:df:e2:ed:f0:e3:72:73:7a:64:94:bf:f7:72:66:d8: - 32:e4:42:75:62:ae:87:eb:f2:d5:d9:de:56:b3:9f:cc:ce:14: - 28:b9:0d:97:60:5c:12:4c:58:e4:d3:3d:83:49:45:58:97:35: - 69:1a:a8:47:ea:56:c6:79:ab:12:d8:67:81:84:df:7f:09:3c: - 94:e6:b8:26:2c:20:bd:3d:b3:28:89:f7:5f:ff:22:e2:97:84: - 1f:e9:65:ef:87:e0:df:c1:67:49:b3:5d:eb:b2:09:2a:eb:26: - ed:78:be:7d:3f:2b:f3:b7:26:35:6d:5f:89:01:b6:49:5b:9f: - 01:05:9b:ab:3d:25:c1:cc:b6:7f:c2:f1:6f:86:c6:fa:64:68: - eb:81:2d:94:eb:42:b7:fa:8c:1e:dd:62:f1:be:50:67:b7:6c: - bd:f3:f1:1f:6b:0c:36:07:16:7f:37:7c:a9:5b:6d:7a:f1:12: - 46:60:83:d7:27:04:be:4b:ce:97:be:c3:67:2a:68:11:df:80: - e7:0c:33:66:bf:13:0d:14:6e:f3:7f:1f:63:10:1e:fa:8d:1b: - 25:6d:6c:8f:a5:b7:61:01:b1:d2:a3:26:a1:10:71:9d:ad:e2: - c3:f9:c3:99:51:b7:2b:07:08:ce:2e:e6:50:b2:a7:fa:0a:45: - 2f:a2:f0:f2 ------BEGIN CERTIFICATE----- -MIIDtzCCAp+gAwIBAgIQDOfg5RfYRv6P5WD8G/AwOTANBgkqhkiG9w0BAQUFADBl -MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3 -d3cuZGlnaWNlcnQuY29tMSQwIgYDVQQDExtEaWdpQ2VydCBBc3N1cmVkIElEIFJv -b3QgQ0EwHhcNMDYxMTEwMDAwMDAwWhcNMzExMTEwMDAwMDAwWjBlMQswCQYDVQQG -EwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3d3cuZGlnaWNl -cnQuY29tMSQwIgYDVQQDExtEaWdpQ2VydCBBc3N1cmVkIElEIFJvb3QgQ0EwggEi -MA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCtDhXO5EOAXLGH87dg+XESpa7c -JpSIqvTO9SA5KFhgDPiA2qkVlTJhPLWxKISKityfCgyDF3qPkKyK53lTXDGEKvYP -mDI2dsze3Tyoou9q+yHyUmHfnyDXH+Kx2f4YZNISW1/5WBg1vEfNoTb5a3/UsDg+ -wRvDjDPZ2C8Y/igPs6eD1sNuRMBhNZYW/lmci3Zt1/GiSw0r/wty2p5g0I6QNcZ4 -VYcgoc/lbQrISXwxmDNsIumH0DJaoroTghHtORedmTpyoeb6pNnVFzF1roV9Iq4/ -AUaG9ih5yLHa5FcXxH4cDrC0kqZWs72yl+2qp/C3xag/lRbQ/6GW6whfGHdPAgMB -AAGjYzBhMA4GA1UdDwEB/wQEAwIBhjAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQW -BBRF66Kv9JLLgjEtUYunpyGd823IDzAfBgNVHSMEGDAWgBRF66Kv9JLLgjEtUYun -pyGd823IDzANBgkqhkiG9w0BAQUFAAOCAQEAog683+Lt8ONyc3pklL/3cmbYMuRC -dWKuh+vy1dneVrOfzM4UKLkNl2BcEkxY5NM9g0lFWJc1aRqoR+pWxnmrEthngYTf -fwk8lOa4JiwgvT2zKIn3X/8i4peEH+ll74fg38FnSbNd67IJKusm7Xi+fT8r87cm -NW1fiQG2SVufAQWbqz0lwcy2f8Lxb4bG+mRo64EtlOtCt/qMHt1i8b5QZ7dsvfPx -H2sMNgcWfzd8qVttevESRmCD1ycEvkvOl77DZypoEd+A5wwzZr8TDRRu838fYxAe -+o0bJW1sj6W3YQGx0qMmoRBxna3iw/nDmVG3KwcIzi7mULKn+gpFL6Lw8g== ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: - 0b:93:1c:3a:d6:39:67:ea:67:23:bf:c3:af:9a:f4:4b - Signature Algorithm: sha256WithRSAEncryption - Issuer: C=US, O=DigiCert Inc, OU=www.digicert.com, CN=DigiCert Assured ID Root G2 - Validity - Not Before: Aug 1 12:00:00 2013 GMT - Not After : Jan 15 12:00:00 2038 GMT - Subject: C=US, O=DigiCert Inc, OU=www.digicert.com, CN=DigiCert Assured ID Root G2 - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (2048 bit) - Modulus: - 00:d9:e7:28:2f:52:3f:36:72:49:88:93:34:f3:f8: - 6a:1e:31:54:80:9f:ad:54:41:b5:47:df:96:a8:d4: - af:80:2d:b9:0a:cf:75:fd:89:a5:7d:24:fa:e3:22: - 0c:2b:bc:95:17:0b:33:bf:19:4d:41:06:90:00:bd: - 0c:4d:10:fe:07:b5:e7:1c:6e:22:55:31:65:97:bd: - d3:17:d2:1e:62:f3:db:ea:6c:50:8c:3f:84:0c:96: - cf:b7:cb:03:e0:ca:6d:a1:14:4c:1b:89:dd:ed:00: - b0:52:7c:af:91:6c:b1:38:13:d1:e9:12:08:c0:00: - b0:1c:2b:11:da:77:70:36:9b:ae:ce:79:87:dc:82: - 70:e6:09:74:70:55:69:af:a3:68:9f:bf:dd:b6:79: - b3:f2:9d:70:29:55:f4:ab:ff:95:61:f3:c9:40:6f: - 1d:d1:be:93:bb:d3:88:2a:bb:9d:bf:72:5a:56:71: - 3b:3f:d4:f3:d1:0a:fe:28:ef:a3:ee:d9:99:af:03: - d3:8f:60:b7:f2:92:a1:b1:bd:89:89:1f:30:cd:c3: - a6:2e:62:33:ae:16:02:77:44:5a:e7:81:0a:3c:a7: - 44:2e:79:b8:3f:04:bc:5c:a0:87:e1:1b:af:51:8e: - cd:ec:2c:fa:f8:fe:6d:f0:3a:7c:aa:8b:e4:67:95: - 31:8d - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Basic Constraints: critical - CA:TRUE - X509v3 Key Usage: critical - Digital Signature, Certificate Sign, CRL Sign - X509v3 Subject Key Identifier: - CE:C3:4A:B9:99:55:F2:B8:DB:60:BF:A9:7E:BD:56:B5:97:36:A7:D6 - Signature Algorithm: sha256WithRSAEncryption - ca:a5:55:8c:e3:c8:41:6e:69:27:a7:75:11:ef:3c:86:36:6f: - d2:9d:c6:78:38:1d:69:96:a2:92:69:2e:38:6c:9b:7d:04:d4: - 89:a5:b1:31:37:8a:c9:21:cc:ab:6c:cd:8b:1c:9a:d6:bf:48: - d2:32:66:c1:8a:c0:f3:2f:3a:ef:c0:e3:d4:91:86:d1:50:e3: - 03:db:73:77:6f:4a:39:53:ed:de:26:c7:b5:7d:af:2b:42:d1: - 75:62:e3:4a:2b:02:c7:50:4b:e0:69:e2:96:6c:0e:44:66:10: - 44:8f:ad:05:eb:f8:79:ac:a6:1b:e8:37:34:9d:53:c9:61:aa: - a2:52:af:4a:70:16:86:c2:3a:c8:b1:13:70:36:d8:cf:ee:f4: - 0a:34:d5:5b:4c:fd:07:9c:a2:ba:d9:01:72:5c:f3:4d:c1:dd: - 0e:b1:1c:0d:c4:63:be:ad:f4:14:fb:89:ec:a2:41:0e:4c:cc: - c8:57:40:d0:6e:03:aa:cd:0c:8e:89:99:99:6c:f0:3c:30:af: - 38:df:6f:bc:a3:be:29:20:27:ab:74:ff:13:22:78:de:97:52: - 55:1e:83:b5:54:20:03:ee:ae:c0:4f:56:de:37:cc:c3:7f:aa: - 04:27:bb:d3:77:b8:62:db:17:7c:9c:28:22:13:73:6c:cf:26: - f5:8a:29:e7 ------BEGIN CERTIFICATE----- -MIIDljCCAn6gAwIBAgIQC5McOtY5Z+pnI7/Dr5r0SzANBgkqhkiG9w0BAQsFADBl -MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3 -d3cuZGlnaWNlcnQuY29tMSQwIgYDVQQDExtEaWdpQ2VydCBBc3N1cmVkIElEIFJv -b3QgRzIwHhcNMTMwODAxMTIwMDAwWhcNMzgwMTE1MTIwMDAwWjBlMQswCQYDVQQG -EwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3d3cuZGlnaWNl -cnQuY29tMSQwIgYDVQQDExtEaWdpQ2VydCBBc3N1cmVkIElEIFJvb3QgRzIwggEi -MA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDZ5ygvUj82ckmIkzTz+GoeMVSA -n61UQbVH35ao1K+ALbkKz3X9iaV9JPrjIgwrvJUXCzO/GU1BBpAAvQxNEP4Htecc -biJVMWWXvdMX0h5i89vqbFCMP4QMls+3ywPgym2hFEwbid3tALBSfK+RbLE4E9Hp -EgjAALAcKxHad3A2m67OeYfcgnDmCXRwVWmvo2ifv922ebPynXApVfSr/5Vh88lA -bx3RvpO704gqu52/clpWcTs/1PPRCv4o76Pu2ZmvA9OPYLfykqGxvYmJHzDNw6Yu -YjOuFgJ3RFrngQo8p0Quebg/BLxcoIfhG69Rjs3sLPr4/m3wOnyqi+RnlTGNAgMB -AAGjQjBAMA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgGGMB0GA1UdDgQW -BBTOw0q5mVXyuNtgv6l+vVa1lzan1jANBgkqhkiG9w0BAQsFAAOCAQEAyqVVjOPI -QW5pJ6d1Ee88hjZv0p3GeDgdaZaikmkuOGybfQTUiaWxMTeKySHMq2zNixya1r9I -0jJmwYrA8y8678Dj1JGG0VDjA9tzd29KOVPt3ibHtX2vK0LRdWLjSisCx1BL4Gni -lmwORGYQRI+tBev4eaymG+g3NJ1TyWGqolKvSnAWhsI6yLETcDbYz+70CjTVW0z9 -B5yiutkBclzzTcHdDrEcDcRjvq30FPuJ7KJBDkzMyFdA0G4Dqs0MjomZmWzwPDCv -ON9vvKO+KSAnq3T/EyJ43pdSVR6DtVQgA+6uwE9W3jfMw3+qBCe703e4YtsXfJwo -IhNzbM8m9Yop5w== ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: - 0b:a1:5a:fa:1d:df:a0:b5:49:44:af:cd:24:a0:6c:ec - Signature Algorithm: ecdsa-with-SHA384 - Issuer: C=US, O=DigiCert Inc, OU=www.digicert.com, CN=DigiCert Assured ID Root G3 - Validity - Not Before: Aug 1 12:00:00 2013 GMT - Not After : Jan 15 12:00:00 2038 GMT - Subject: C=US, O=DigiCert Inc, OU=www.digicert.com, CN=DigiCert Assured ID Root G3 - Subject Public Key Info: - Public Key Algorithm: id-ecPublicKey - Public-Key: (384 bit) - pub: - 04:19:e7:bc:ac:44:65:ed:cd:b8:3f:58:fb:8d:b1: - 57:a9:44:2d:05:15:f2:ef:0b:ff:10:74:9f:b5:62: - 52:5f:66:7e:1f:e5:dc:1b:45:79:0b:cc:c6:53:0a: - 9d:8d:5d:02:d9:a9:59:de:02:5a:f6:95:2a:0e:8d: - 38:4a:8a:49:c6:bc:c6:03:38:07:5f:55:da:7e:09: - 6e:e2:7f:5e:d0:45:20:0f:59:76:10:d6:a0:24:f0: - 2d:de:36:f2:6c:29:39 - ASN1 OID: secp384r1 - X509v3 extensions: - X509v3 Basic Constraints: critical - CA:TRUE - X509v3 Key Usage: critical - Digital Signature, Certificate Sign, CRL Sign - X509v3 Subject Key Identifier: - CB:D0:BD:A9:E1:98:05:51:A1:4D:37:A2:83:79:CE:8D:1D:2A:E4:84 - Signature Algorithm: ecdsa-with-SHA384 - 30:64:02:30:25:a4:81:45:02:6b:12:4b:75:74:4f:c8:23:e3: - 70:f2:75:72:de:7c:89:f0:cf:91:72:61:9e:5e:10:92:59:56: - b9:83:c7:10:e7:38:e9:58:26:36:7d:d5:e4:34:86:39:02:30: - 7c:36:53:f0:30:e5:62:63:3a:99:e2:b6:a3:3b:9b:34:fa:1e: - da:10:92:71:5e:91:13:a7:dd:a4:6e:92:cc:32:d6:f5:21:66: - c7:2f:ea:96:63:6a:65:45:92:95:01:b4 ------BEGIN CERTIFICATE----- -MIICRjCCAc2gAwIBAgIQC6Fa+h3foLVJRK/NJKBs7DAKBggqhkjOPQQDAzBlMQsw -CQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3d3cu -ZGlnaWNlcnQuY29tMSQwIgYDVQQDExtEaWdpQ2VydCBBc3N1cmVkIElEIFJvb3Qg -RzMwHhcNMTMwODAxMTIwMDAwWhcNMzgwMTE1MTIwMDAwWjBlMQswCQYDVQQGEwJV -UzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3d3cuZGlnaWNlcnQu -Y29tMSQwIgYDVQQDExtEaWdpQ2VydCBBc3N1cmVkIElEIFJvb3QgRzMwdjAQBgcq -hkjOPQIBBgUrgQQAIgNiAAQZ57ysRGXtzbg/WPuNsVepRC0FFfLvC/8QdJ+1YlJf -Zn4f5dwbRXkLzMZTCp2NXQLZqVneAlr2lSoOjThKiknGvMYDOAdfVdp+CW7if17Q -RSAPWXYQ1qAk8C3eNvJsKTmjQjBAMA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/ -BAQDAgGGMB0GA1UdDgQWBBTL0L2p4ZgFUaFNN6KDec6NHSrkhDAKBggqhkjOPQQD -AwNnADBkAjAlpIFFAmsSS3V0T8gj43DydXLefInwz5FyYZ5eEJJZVrmDxxDnOOlY -JjZ91eQ0hjkCMHw2U/Aw5WJjOpnitqM7mzT6HtoQknFekROn3aRukswy1vUhZscv -6pZjamVFkpUBtA== ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: - 08:3b:e0:56:90:42:46:b1:a1:75:6a:c9:59:91:c7:4a - Signature Algorithm: sha1WithRSAEncryption - Issuer: C=US, O=DigiCert Inc, OU=www.digicert.com, CN=DigiCert Global Root CA - Validity - Not Before: Nov 10 00:00:00 2006 GMT - Not After : Nov 10 00:00:00 2031 GMT - Subject: C=US, O=DigiCert Inc, OU=www.digicert.com, CN=DigiCert Global Root CA - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (2048 bit) - Modulus: - 00:e2:3b:e1:11:72:de:a8:a4:d3:a3:57:aa:50:a2: - 8f:0b:77:90:c9:a2:a5:ee:12:ce:96:5b:01:09:20: - cc:01:93:a7:4e:30:b7:53:f7:43:c4:69:00:57:9d: - e2:8d:22:dd:87:06:40:00:81:09:ce:ce:1b:83:bf: - df:cd:3b:71:46:e2:d6:66:c7:05:b3:76:27:16:8f: - 7b:9e:1e:95:7d:ee:b7:48:a3:08:da:d6:af:7a:0c: - 39:06:65:7f:4a:5d:1f:bc:17:f8:ab:be:ee:28:d7: - 74:7f:7a:78:99:59:85:68:6e:5c:23:32:4b:bf:4e: - c0:e8:5a:6d:e3:70:bf:77:10:bf:fc:01:f6:85:d9: - a8:44:10:58:32:a9:75:18:d5:d1:a2:be:47:e2:27: - 6a:f4:9a:33:f8:49:08:60:8b:d4:5f:b4:3a:84:bf: - a1:aa:4a:4c:7d:3e:cf:4f:5f:6c:76:5e:a0:4b:37: - 91:9e:dc:22:e6:6d:ce:14:1a:8e:6a:cb:fe:cd:b3: - 14:64:17:c7:5b:29:9e:32:bf:f2:ee:fa:d3:0b:42: - d4:ab:b7:41:32:da:0c:d4:ef:f8:81:d5:bb:8d:58: - 3f:b5:1b:e8:49:28:a2:70:da:31:04:dd:f7:b2:16: - f2:4c:0a:4e:07:a8:ed:4a:3d:5e:b5:7f:a3:90:c3: - af:27 - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Key Usage: critical - Digital Signature, Certificate Sign, CRL Sign - X509v3 Basic Constraints: critical - CA:TRUE - X509v3 Subject Key Identifier: - 03:DE:50:35:56:D1:4C:BB:66:F0:A3:E2:1B:1B:C3:97:B2:3D:D1:55 - X509v3 Authority Key Identifier: - keyid:03:DE:50:35:56:D1:4C:BB:66:F0:A3:E2:1B:1B:C3:97:B2:3D:D1:55 - - Signature Algorithm: sha1WithRSAEncryption - cb:9c:37:aa:48:13:12:0a:fa:dd:44:9c:4f:52:b0:f4:df:ae: - 04:f5:79:79:08:a3:24:18:fc:4b:2b:84:c0:2d:b9:d5:c7:fe: - f4:c1:1f:58:cb:b8:6d:9c:7a:74:e7:98:29:ab:11:b5:e3:70: - a0:a1:cd:4c:88:99:93:8c:91:70:e2:ab:0f:1c:be:93:a9:ff: - 63:d5:e4:07:60:d3:a3:bf:9d:5b:09:f1:d5:8e:e3:53:f4:8e: - 63:fa:3f:a7:db:b4:66:df:62:66:d6:d1:6e:41:8d:f2:2d:b5: - ea:77:4a:9f:9d:58:e2:2b:59:c0:40:23:ed:2d:28:82:45:3e: - 79:54:92:26:98:e0:80:48:a8:37:ef:f0:d6:79:60:16:de:ac: - e8:0e:cd:6e:ac:44:17:38:2f:49:da:e1:45:3e:2a:b9:36:53: - cf:3a:50:06:f7:2e:e8:c4:57:49:6c:61:21:18:d5:04:ad:78: - 3c:2c:3a:80:6b:a7:eb:af:15:14:e9:d8:89:c1:b9:38:6c:e2: - 91:6c:8a:ff:64:b9:77:25:57:30:c0:1b:24:a3:e1:dc:e9:df: - 47:7c:b5:b4:24:08:05:30:ec:2d:bd:0b:bf:45:bf:50:b9:a9: - f3:eb:98:01:12:ad:c8:88:c6:98:34:5f:8d:0a:3c:c6:e9:d5: - 95:95:6d:de ------BEGIN CERTIFICATE----- -MIIDrzCCApegAwIBAgIQCDvgVpBCRrGhdWrJWZHHSjANBgkqhkiG9w0BAQUFADBh -MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3 -d3cuZGlnaWNlcnQuY29tMSAwHgYDVQQDExdEaWdpQ2VydCBHbG9iYWwgUm9vdCBD -QTAeFw0wNjExMTAwMDAwMDBaFw0zMTExMTAwMDAwMDBaMGExCzAJBgNVBAYTAlVT -MRUwEwYDVQQKEwxEaWdpQ2VydCBJbmMxGTAXBgNVBAsTEHd3dy5kaWdpY2VydC5j -b20xIDAeBgNVBAMTF0RpZ2lDZXJ0IEdsb2JhbCBSb290IENBMIIBIjANBgkqhkiG -9w0BAQEFAAOCAQ8AMIIBCgKCAQEA4jvhEXLeqKTTo1eqUKKPC3eQyaKl7hLOllsB -CSDMAZOnTjC3U/dDxGkAV53ijSLdhwZAAIEJzs4bg7/fzTtxRuLWZscFs3YnFo97 -nh6Vfe63SKMI2tavegw5BmV/Sl0fvBf4q77uKNd0f3p4mVmFaG5cIzJLv07A6Fpt -43C/dxC//AH2hdmoRBBYMql1GNXRor5H4idq9Joz+EkIYIvUX7Q6hL+hqkpMfT7P -T19sdl6gSzeRntwi5m3OFBqOasv+zbMUZBfHWymeMr/y7vrTC0LUq7dBMtoM1O/4 -gdW7jVg/tRvoSSiicNoxBN33shbyTApOB6jtSj1etX+jkMOvJwIDAQABo2MwYTAO -BgNVHQ8BAf8EBAMCAYYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUA95QNVbR -TLtm8KPiGxvDl7I90VUwHwYDVR0jBBgwFoAUA95QNVbRTLtm8KPiGxvDl7I90VUw -DQYJKoZIhvcNAQEFBQADggEBAMucN6pIExIK+t1EnE9SsPTfrgT1eXkIoyQY/Esr -hMAtudXH/vTBH1jLuG2cenTnmCmrEbXjcKChzUyImZOMkXDiqw8cvpOp/2PV5Adg -06O/nVsJ8dWO41P0jmP6P6fbtGbfYmbW0W5BjfIttep3Sp+dWOIrWcBAI+0tKIJF -PnlUkiaY4IBIqDfv8NZ5YBberOgOzW6sRBc4L0na4UU+Krk2U886UAb3LujEV0ls -YSEY1QSteDwsOoBrp+uvFRTp2InBuThs4pFsiv9kuXclVzDAGySj4dzp30d8tbQk -CAUw7C29C79Fv1C5qfPrmAESrciIxpg0X40KPMbp1ZWVbd4= ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: - 03:3a:f1:e6:a7:11:a9:a0:bb:28:64:b1:1d:09:fa:e5 - Signature Algorithm: sha256WithRSAEncryption - Issuer: C=US, O=DigiCert Inc, OU=www.digicert.com, CN=DigiCert Global Root G2 - Validity - Not Before: Aug 1 12:00:00 2013 GMT - Not After : Jan 15 12:00:00 2038 GMT - Subject: C=US, O=DigiCert Inc, OU=www.digicert.com, CN=DigiCert Global Root G2 - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (2048 bit) - Modulus: - 00:bb:37:cd:34:dc:7b:6b:c9:b2:68:90:ad:4a:75: - ff:46:ba:21:0a:08:8d:f5:19:54:c9:fb:88:db:f3: - ae:f2:3a:89:91:3c:7a:e6:ab:06:1a:6b:cf:ac:2d: - e8:5e:09:24:44:ba:62:9a:7e:d6:a3:a8:7e:e0:54: - 75:20:05:ac:50:b7:9c:63:1a:6c:30:dc:da:1f:19: - b1:d7:1e:de:fd:d7:e0:cb:94:83:37:ae:ec:1f:43: - 4e:dd:7b:2c:d2:bd:2e:a5:2f:e4:a9:b8:ad:3a:d4: - 99:a4:b6:25:e9:9b:6b:00:60:92:60:ff:4f:21:49: - 18:f7:67:90:ab:61:06:9c:8f:f2:ba:e9:b4:e9:92: - 32:6b:b5:f3:57:e8:5d:1b:cd:8c:1d:ab:95:04:95: - 49:f3:35:2d:96:e3:49:6d:dd:77:e3:fb:49:4b:b4: - ac:55:07:a9:8f:95:b3:b4:23:bb:4c:6d:45:f0:f6: - a9:b2:95:30:b4:fd:4c:55:8c:27:4a:57:14:7c:82: - 9d:cd:73:92:d3:16:4a:06:0c:8c:50:d1:8f:1e:09: - be:17:a1:e6:21:ca:fd:83:e5:10:bc:83:a5:0a:c4: - 67:28:f6:73:14:14:3d:46:76:c3:87:14:89:21:34: - 4d:af:0f:45:0c:a6:49:a1:ba:bb:9c:c5:b1:33:83: - 29:85 - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Basic Constraints: critical - CA:TRUE - X509v3 Key Usage: critical - Digital Signature, Certificate Sign, CRL Sign - X509v3 Subject Key Identifier: - 4E:22:54:20:18:95:E6:E3:6E:E6:0F:FA:FA:B9:12:ED:06:17:8F:39 - Signature Algorithm: sha256WithRSAEncryption - 60:67:28:94:6f:0e:48:63:eb:31:dd:ea:67:18:d5:89:7d:3c: - c5:8b:4a:7f:e9:be:db:2b:17:df:b0:5f:73:77:2a:32:13:39: - 81:67:42:84:23:f2:45:67:35:ec:88:bf:f8:8f:b0:61:0c:34: - a4:ae:20:4c:84:c6:db:f8:35:e1:76:d9:df:a6:42:bb:c7:44: - 08:86:7f:36:74:24:5a:da:6c:0d:14:59:35:bd:f2:49:dd:b6: - 1f:c9:b3:0d:47:2a:3d:99:2f:bb:5c:bb:b5:d4:20:e1:99:5f: - 53:46:15:db:68:9b:f0:f3:30:d5:3e:31:e2:8d:84:9e:e3:8a: - da:da:96:3e:35:13:a5:5f:f0:f9:70:50:70:47:41:11:57:19: - 4e:c0:8f:ae:06:c4:95:13:17:2f:1b:25:9f:75:f2:b1:8e:99: - a1:6f:13:b1:41:71:fe:88:2a:c8:4f:10:20:55:d7:f3:14:45: - e5:e0:44:f4:ea:87:95:32:93:0e:fe:53:46:fa:2c:9d:ff:8b: - 22:b9:4b:d9:09:45:a4:de:a4:b8:9a:58:dd:1b:7d:52:9f:8e: - 59:43:88:81:a4:9e:26:d5:6f:ad:dd:0d:c6:37:7d:ed:03:92: - 1b:e5:77:5f:76:ee:3c:8d:c4:5d:56:5b:a2:d9:66:6e:b3:35: - 37:e5:32:b6 ------BEGIN CERTIFICATE----- -MIIDjjCCAnagAwIBAgIQAzrx5qcRqaC7KGSxHQn65TANBgkqhkiG9w0BAQsFADBh -MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3 -d3cuZGlnaWNlcnQuY29tMSAwHgYDVQQDExdEaWdpQ2VydCBHbG9iYWwgUm9vdCBH -MjAeFw0xMzA4MDExMjAwMDBaFw0zODAxMTUxMjAwMDBaMGExCzAJBgNVBAYTAlVT -MRUwEwYDVQQKEwxEaWdpQ2VydCBJbmMxGTAXBgNVBAsTEHd3dy5kaWdpY2VydC5j -b20xIDAeBgNVBAMTF0RpZ2lDZXJ0IEdsb2JhbCBSb290IEcyMIIBIjANBgkqhkiG -9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuzfNNNx7a8myaJCtSnX/RrohCgiN9RlUyfuI -2/Ou8jqJkTx65qsGGmvPrC3oXgkkRLpimn7Wo6h+4FR1IAWsULecYxpsMNzaHxmx -1x7e/dfgy5SDN67sH0NO3Xss0r0upS/kqbitOtSZpLYl6ZtrAGCSYP9PIUkY92eQ -q2EGnI/yuum06ZIya7XzV+hdG82MHauVBJVJ8zUtluNJbd134/tJS7SsVQepj5Wz -tCO7TG1F8PapspUwtP1MVYwnSlcUfIKdzXOS0xZKBgyMUNGPHgm+F6HmIcr9g+UQ -vIOlCsRnKPZzFBQ9RnbDhxSJITRNrw9FDKZJobq7nMWxM4MphQIDAQABo0IwQDAP -BgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIBhjAdBgNVHQ4EFgQUTiJUIBiV -5uNu5g/6+rkS7QYXjzkwDQYJKoZIhvcNAQELBQADggEBAGBnKJRvDkhj6zHd6mcY -1Yl9PMWLSn/pvtsrF9+wX3N3KjITOYFnQoQj8kVnNeyIv/iPsGEMNKSuIEyExtv4 -NeF22d+mQrvHRAiGfzZ0JFrabA0UWTW98kndth/Jsw1HKj2ZL7tcu7XUIOGZX1NG -Fdtom/DzMNU+MeKNhJ7jitralj41E6Vf8PlwUHBHQRFXGU7Aj64GxJUTFy8bJZ91 -8rGOmaFvE7FBcf6IKshPECBV1/MUReXgRPTqh5Uykw7+U0b6LJ3/iyK5S9kJRaTe -pLiaWN0bfVKfjllDiIGknibVb63dDcY3fe0Dkhvld1927jyNxF1WW6LZZm6zNTfl -MrY= ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: - 05:55:56:bc:f2:5e:a4:35:35:c3:a4:0f:d5:ab:45:72 - Signature Algorithm: ecdsa-with-SHA384 - Issuer: C=US, O=DigiCert Inc, OU=www.digicert.com, CN=DigiCert Global Root G3 - Validity - Not Before: Aug 1 12:00:00 2013 GMT - Not After : Jan 15 12:00:00 2038 GMT - Subject: C=US, O=DigiCert Inc, OU=www.digicert.com, CN=DigiCert Global Root G3 - Subject Public Key Info: - Public Key Algorithm: id-ecPublicKey - Public-Key: (384 bit) - pub: - 04:dd:a7:d9:bb:8a:b8:0b:fb:0b:7f:21:d2:f0:be: - be:73:f3:33:5d:1a:bc:34:ea:de:c6:9b:bc:d0:95: - f6:f0:cc:d0:0b:ba:61:5b:51:46:7e:9e:2d:9f:ee: - 8e:63:0c:17:ec:07:70:f5:cf:84:2e:40:83:9c:e8: - 3f:41:6d:3b:ad:d3:a4:14:59:36:78:9d:03:43:ee: - 10:13:6c:72:de:ae:88:a7:a1:6b:b5:43:ce:67:dc: - 23:ff:03:1c:a3:e2:3e - ASN1 OID: secp384r1 - X509v3 extensions: - X509v3 Basic Constraints: critical - CA:TRUE - X509v3 Key Usage: critical - Digital Signature, Certificate Sign, CRL Sign - X509v3 Subject Key Identifier: - B3:DB:48:A4:F9:A1:C5:D8:AE:36:41:CC:11:63:69:62:29:BC:4B:C6 - Signature Algorithm: ecdsa-with-SHA384 - 30:65:02:31:00:ad:bc:f2:6c:3f:12:4a:d1:2d:39:c3:0a:09: - 97:73:f4:88:36:8c:88:27:bb:e6:88:8d:50:85:a7:63:f9:9e: - 32:de:66:93:0f:f1:cc:b1:09:8f:dd:6c:ab:fa:6b:7f:a0:02: - 30:39:66:5b:c2:64:8d:b8:9e:50:dc:a8:d5:49:a2:ed:c7:dc: - d1:49:7f:17:01:b8:c8:86:8f:4e:8c:88:2b:a8:9a:a9:8a:c5: - d1:00:bd:f8:54:e2:9a:e5:5b:7c:b3:27:17 ------BEGIN CERTIFICATE----- -MIICPzCCAcWgAwIBAgIQBVVWvPJepDU1w6QP1atFcjAKBggqhkjOPQQDAzBhMQsw -CQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3d3cu -ZGlnaWNlcnQuY29tMSAwHgYDVQQDExdEaWdpQ2VydCBHbG9iYWwgUm9vdCBHMzAe -Fw0xMzA4MDExMjAwMDBaFw0zODAxMTUxMjAwMDBaMGExCzAJBgNVBAYTAlVTMRUw -EwYDVQQKEwxEaWdpQ2VydCBJbmMxGTAXBgNVBAsTEHd3dy5kaWdpY2VydC5jb20x -IDAeBgNVBAMTF0RpZ2lDZXJ0IEdsb2JhbCBSb290IEczMHYwEAYHKoZIzj0CAQYF -K4EEACIDYgAE3afZu4q4C/sLfyHS8L6+c/MzXRq8NOrexpu80JX28MzQC7phW1FG -fp4tn+6OYwwX7Adw9c+ELkCDnOg/QW07rdOkFFk2eJ0DQ+4QE2xy3q6Ip6FrtUPO -Z9wj/wMco+I+o0IwQDAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIBhjAd -BgNVHQ4EFgQUs9tIpPmhxdiuNkHMEWNpYim8S8YwCgYIKoZIzj0EAwMDaAAwZQIx -AK288mw/EkrRLTnDCgmXc/SINoyIJ7vmiI1Qhadj+Z4y3maTD/HMsQmP3Wyr+mt/ -oAIwOWZbwmSNuJ5Q3KjVSaLtx9zRSX8XAbjIho9OjIgrqJqpisXRAL34VOKa5Vt8 -sycX ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: - 02:ac:5c:26:6a:0b:40:9b:8f:0b:79:f2:ae:46:25:77 - Signature Algorithm: sha1WithRSAEncryption - Issuer: C=US, O=DigiCert Inc, OU=www.digicert.com, CN=DigiCert High Assurance EV Root CA - Validity - Not Before: Nov 10 00:00:00 2006 GMT - Not After : Nov 10 00:00:00 2031 GMT - Subject: C=US, O=DigiCert Inc, OU=www.digicert.com, CN=DigiCert High Assurance EV Root CA - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (2048 bit) - Modulus: - 00:c6:cc:e5:73:e6:fb:d4:bb:e5:2d:2d:32:a6:df: - e5:81:3f:c9:cd:25:49:b6:71:2a:c3:d5:94:34:67: - a2:0a:1c:b0:5f:69:a6:40:b1:c4:b7:b2:8f:d0:98: - a4:a9:41:59:3a:d3:dc:94:d6:3c:db:74:38:a4:4a: - cc:4d:25:82:f7:4a:a5:53:12:38:ee:f3:49:6d:71: - 91:7e:63:b6:ab:a6:5f:c3:a4:84:f8:4f:62:51:be: - f8:c5:ec:db:38:92:e3:06:e5:08:91:0c:c4:28:41: - 55:fb:cb:5a:89:15:7e:71:e8:35:bf:4d:72:09:3d: - be:3a:38:50:5b:77:31:1b:8d:b3:c7:24:45:9a:a7: - ac:6d:00:14:5a:04:b7:ba:13:eb:51:0a:98:41:41: - 22:4e:65:61:87:81:41:50:a6:79:5c:89:de:19:4a: - 57:d5:2e:e6:5d:1c:53:2c:7e:98:cd:1a:06:16:a4: - 68:73:d0:34:04:13:5c:a1:71:d3:5a:7c:55:db:5e: - 64:e1:37:87:30:56:04:e5:11:b4:29:80:12:f1:79: - 39:88:a2:02:11:7c:27:66:b7:88:b7:78:f2:ca:0a: - a8:38:ab:0a:64:c2:bf:66:5d:95:84:c1:a1:25:1e: - 87:5d:1a:50:0b:20:12:cc:41:bb:6e:0b:51:38:b8: - 4b:cb - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Key Usage: critical - Digital Signature, Certificate Sign, CRL Sign - X509v3 Basic Constraints: critical - CA:TRUE - X509v3 Subject Key Identifier: - B1:3E:C3:69:03:F8:BF:47:01:D4:98:26:1A:08:02:EF:63:64:2B:C3 - X509v3 Authority Key Identifier: - keyid:B1:3E:C3:69:03:F8:BF:47:01:D4:98:26:1A:08:02:EF:63:64:2B:C3 - - Signature Algorithm: sha1WithRSAEncryption - 1c:1a:06:97:dc:d7:9c:9f:3c:88:66:06:08:57:21:db:21:47: - f8:2a:67:aa:bf:18:32:76:40:10:57:c1:8a:f3:7a:d9:11:65: - 8e:35:fa:9e:fc:45:b5:9e:d9:4c:31:4b:b8:91:e8:43:2c:8e: - b3:78:ce:db:e3:53:79:71:d6:e5:21:94:01:da:55:87:9a:24: - 64:f6:8a:66:cc:de:9c:37:cd:a8:34:b1:69:9b:23:c8:9e:78: - 22:2b:70:43:e3:55:47:31:61:19:ef:58:c5:85:2f:4e:30:f6: - a0:31:16:23:c8:e7:e2:65:16:33:cb:bf:1a:1b:a0:3d:f8:ca: - 5e:8b:31:8b:60:08:89:2d:0c:06:5c:52:b7:c4:f9:0a:98:d1: - 15:5f:9f:12:be:7c:36:63:38:bd:44:a4:7f:e4:26:2b:0a:c4: - 97:69:0d:e9:8c:e2:c0:10:57:b8:c8:76:12:91:55:f2:48:69: - d8:bc:2a:02:5b:0f:44:d4:20:31:db:f4:ba:70:26:5d:90:60: - 9e:bc:4b:17:09:2f:b4:cb:1e:43:68:c9:07:27:c1:d2:5c:f7: - ea:21:b9:68:12:9c:3c:9c:bf:9e:fc:80:5c:9b:63:cd:ec:47: - aa:25:27:67:a0:37:f3:00:82:7d:54:d7:a9:f8:e9:2e:13:a3: - 77:e8:1f:4a ------BEGIN CERTIFICATE----- -MIIDxTCCAq2gAwIBAgIQAqxcJmoLQJuPC3nyrkYldzANBgkqhkiG9w0BAQUFADBs -MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3 -d3cuZGlnaWNlcnQuY29tMSswKQYDVQQDEyJEaWdpQ2VydCBIaWdoIEFzc3VyYW5j -ZSBFViBSb290IENBMB4XDTA2MTExMDAwMDAwMFoXDTMxMTExMDAwMDAwMFowbDEL -MAkGA1UEBhMCVVMxFTATBgNVBAoTDERpZ2lDZXJ0IEluYzEZMBcGA1UECxMQd3d3 -LmRpZ2ljZXJ0LmNvbTErMCkGA1UEAxMiRGlnaUNlcnQgSGlnaCBBc3N1cmFuY2Ug -RVYgUm9vdCBDQTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAMbM5XPm -+9S75S0tMqbf5YE/yc0lSbZxKsPVlDRnogocsF9ppkCxxLeyj9CYpKlBWTrT3JTW -PNt0OKRKzE0lgvdKpVMSOO7zSW1xkX5jtqumX8OkhPhPYlG++MXs2ziS4wblCJEM -xChBVfvLWokVfnHoNb9Ncgk9vjo4UFt3MRuNs8ckRZqnrG0AFFoEt7oT61EKmEFB -Ik5lYYeBQVCmeVyJ3hlKV9Uu5l0cUyx+mM0aBhakaHPQNAQTXKFx01p8VdteZOE3 -hzBWBOURtCmAEvF5OYiiAhF8J2a3iLd48soKqDirCmTCv2ZdlYTBoSUeh10aUAsg -EsxBu24LUTi4S8sCAwEAAaNjMGEwDgYDVR0PAQH/BAQDAgGGMA8GA1UdEwEB/wQF -MAMBAf8wHQYDVR0OBBYEFLE+w2kD+L9HAdSYJhoIAu9jZCvDMB8GA1UdIwQYMBaA -FLE+w2kD+L9HAdSYJhoIAu9jZCvDMA0GCSqGSIb3DQEBBQUAA4IBAQAcGgaX3Nec -nzyIZgYIVyHbIUf4KmeqvxgydkAQV8GK83rZEWWONfqe/EW1ntlMMUu4kehDLI6z -eM7b41N5cdblIZQB2lWHmiRk9opmzN6cN82oNLFpmyPInngiK3BD41VHMWEZ71jF -hS9OMPagMRYjyOfiZRYzy78aG6A9+MpeizGLYAiJLQwGXFK3xPkKmNEVX58Svnw2 -Yzi9RKR/5CYrCsSXaQ3pjOLAEFe4yHYSkVXySGnYvCoCWw9E1CAx2/S6cCZdkGCe -vEsXCS+0yx5DaMkHJ8HSXPfqIbloEpw8nL+e/IBcm2PN7EeqJSdnoDfzAIJ9VNep -+OkuE6N36B9K ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: - 05:9b:1b:57:9e:8e:21:32:e2:39:07:bd:a7:77:75:5c - Signature Algorithm: sha384WithRSAEncryption - Issuer: C=US, O=DigiCert Inc, OU=www.digicert.com, CN=DigiCert Trusted Root G4 - Validity - Not Before: Aug 1 12:00:00 2013 GMT - Not After : Jan 15 12:00:00 2038 GMT - Subject: C=US, O=DigiCert Inc, OU=www.digicert.com, CN=DigiCert Trusted Root G4 - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (4096 bit) - Modulus: - 00:bf:e6:90:73:68:de:bb:e4:5d:4a:3c:30:22:30: - 69:33:ec:c2:a7:25:2e:c9:21:3d:f2:8a:d8:59:c2: - e1:29:a7:3d:58:ab:76:9a:cd:ae:7b:1b:84:0d:c4: - 30:1f:f3:1b:a4:38:16:eb:56:c6:97:6d:1d:ab:b2: - 79:f2:ca:11:d2:e4:5f:d6:05:3c:52:0f:52:1f:c6: - 9e:15:a5:7e:be:9f:a9:57:16:59:55:72:af:68:93: - 70:c2:b2:ba:75:99:6a:73:32:94:d1:10:44:10:2e: - df:82:f3:07:84:e6:74:3b:6d:71:e2:2d:0c:1b:ee: - 20:d5:c9:20:1d:63:29:2d:ce:ec:5e:4e:c8:93:f8: - 21:61:9b:34:eb:05:c6:5e:ec:5b:1a:bc:eb:c9:cf: - cd:ac:34:40:5f:b1:7a:66:ee:77:c8:48:a8:66:57: - 57:9f:54:58:8e:0c:2b:b7:4f:a7:30:d9:56:ee:ca: - 7b:5d:e3:ad:c9:4f:5e:e5:35:e7:31:cb:da:93:5e: - dc:8e:8f:80:da:b6:91:98:40:90:79:c3:78:c7:b6: - b1:c4:b5:6a:18:38:03:10:8d:d8:d4:37:a4:2e:05: - 7d:88:f5:82:3e:10:91:70:ab:55:82:41:32:d7:db: - 04:73:2a:6e:91:01:7c:21:4c:d4:bc:ae:1b:03:75: - 5d:78:66:d9:3a:31:44:9a:33:40:bf:08:d7:5a:49: - a4:c2:e6:a9:a0:67:dd:a4:27:bc:a1:4f:39:b5:11: - 58:17:f7:24:5c:46:8f:64:f7:c1:69:88:76:98:76: - 3d:59:5d:42:76:87:89:97:69:7a:48:f0:e0:a2:12: - 1b:66:9a:74:ca:de:4b:1e:e7:0e:63:ae:e6:d4:ef: - 92:92:3a:9e:3d:dc:00:e4:45:25:89:b6:9a:44:19: - 2b:7e:c0:94:b4:d2:61:6d:eb:33:d9:c5:df:4b:04: - 00:cc:7d:1c:95:c3:8f:f7:21:b2:b2:11:b7:bb:7f: - f2:d5:8c:70:2c:41:60:aa:b1:63:18:44:95:1a:76: - 62:7e:f6:80:b0:fb:e8:64:a6:33:d1:89:07:e1:bd: - b7:e6:43:a4:18:b8:a6:77:01:e1:0f:94:0c:21:1d: - b2:54:29:25:89:6c:e5:0e:52:51:47:74:be:26:ac: - b6:41:75:de:7a:ac:5f:8d:3f:c9:bc:d3:41:11:12: - 5b:e5:10:50:eb:31:c5:ca:72:16:22:09:df:7c:4c: - 75:3f:63:ec:21:5f:c4:20:51:6b:6f:b1:ab:86:8b: - 4f:c2:d6:45:5f:9d:20:fc:a1:1e:c5:c0:8f:a2:b1: - 7e:0a:26:99:f5:e4:69:2f:98:1d:2d:f5:d9:a9:b2: - 1d:e5:1b - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Basic Constraints: critical - CA:TRUE - X509v3 Key Usage: critical - Digital Signature, Certificate Sign, CRL Sign - X509v3 Subject Key Identifier: - EC:D7:E3:82:D2:71:5D:64:4C:DF:2E:67:3F:E7:BA:98:AE:1C:0F:4F - Signature Algorithm: sha384WithRSAEncryption - bb:61:d9:7d:a9:6c:be:17:c4:91:1b:c3:a1:a2:00:8d:e3:64: - 68:0f:56:cf:77:ae:70:f9:fd:9a:4a:99:b9:c9:78:5c:0c:0c: - 5f:e4:e6:14:29:56:0b:36:49:5d:44:63:e0:ad:9c:96:18:66: - 1b:23:0d:3d:79:e9:6d:6b:d6:54:f8:d2:3c:c1:43:40:ae:1d: - 50:f5:52:fc:90:3b:bb:98:99:69:6b:c7:c1:a7:a8:68:a4:27: - dc:9d:f9:27:ae:30:85:b9:f6:67:4d:3a:3e:8f:59:39:22:53: - 44:eb:c8:5d:03:ca:ed:50:7a:7d:62:21:0a:80:c8:73:66:d1: - a0:05:60:5f:e8:a5:b4:a7:af:a8:f7:6d:35:9c:7c:5a:8a:d6: - a2:38:99:f3:78:8b:f4:4d:d2:20:0b:de:04:ee:8c:9b:47:81: - 72:0d:c0:14:32:ef:30:59:2e:ae:e0:71:f2:56:e4:6a:97:6f: - 92:50:6d:96:8d:68:7a:9a:b2:36:14:7a:06:f2:24:b9:09:11: - 50:d7:08:b1:b8:89:7a:84:23:61:42:29:e5:a3:cd:a2:20:41: - d7:d1:9c:64:d9:ea:26:a1:8b:14:d7:4c:19:b2:50:41:71:3d: - 3f:4d:70:23:86:0c:4a:dc:81:d2:cc:32:94:84:0d:08:09:97: - 1c:4f:c0:ee:6b:20:74:30:d2:e0:39:34:10:85:21:15:01:08: - e8:55:32:de:71:49:d9:28:17:50:4d:e6:be:4d:d1:75:ac:d0: - ca:fb:41:b8:43:a5:aa:d3:c3:05:44:4f:2c:36:9b:e2:fa:e2: - 45:b8:23:53:6c:06:6f:67:55:7f:46:b5:4c:3f:6e:28:5a:79: - 26:d2:a4:a8:62:97:d2:1e:e2:ed:4a:8b:bc:1b:fd:47:4a:0d: - df:67:66:7e:b2:5b:41:d0:3b:e4:f4:3b:f4:04:63:e9:ef:c2: - 54:00:51:a0:8a:2a:c9:ce:78:cc:d5:ea:87:04:18:b3:ce:af: - 49:88:af:f3:92:99:b6:b3:e6:61:0f:d2:85:00:e7:50:1a:e4: - 1b:95:9d:19:a1:b9:9c:b1:9b:b1:00:1e:ef:d0:0f:4f:42:6c: - c9:0a:bc:ee:43:fa:3a:71:a5:c8:4d:26:a5:35:fd:89:5d:bc: - 85:62:1d:32:d2:a0:2b:54:ed:9a:57:c1:db:fa:10:cf:19:b7: - 8b:4a:1b:8f:01:b6:27:95:53:e8:b6:89:6d:5b:bc:68:d4:23: - e8:8b:51:a2:56:f9:f0:a6:80:a0:d6:1e:b3:bc:0f:0f:53:75: - 29:aa:ea:13:77:e4:de:8c:81:21:ad:07:10:47:11:ad:87:3d: - 07:d1:75:bc:cf:f3:66:7e ------BEGIN CERTIFICATE----- -MIIFkDCCA3igAwIBAgIQBZsbV56OITLiOQe9p3d1XDANBgkqhkiG9w0BAQwFADBi -MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3 -d3cuZGlnaWNlcnQuY29tMSEwHwYDVQQDExhEaWdpQ2VydCBUcnVzdGVkIFJvb3Qg -RzQwHhcNMTMwODAxMTIwMDAwWhcNMzgwMTE1MTIwMDAwWjBiMQswCQYDVQQGEwJV -UzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3d3cuZGlnaWNlcnQu -Y29tMSEwHwYDVQQDExhEaWdpQ2VydCBUcnVzdGVkIFJvb3QgRzQwggIiMA0GCSqG -SIb3DQEBAQUAA4ICDwAwggIKAoICAQC/5pBzaN675F1KPDAiMGkz7MKnJS7JIT3y -ithZwuEppz1Yq3aaza57G4QNxDAf8xukOBbrVsaXbR2rsnnyyhHS5F/WBTxSD1If -xp4VpX6+n6lXFllVcq9ok3DCsrp1mWpzMpTREEQQLt+C8weE5nQ7bXHiLQwb7iDV -ySAdYyktzuxeTsiT+CFhmzTrBcZe7FsavOvJz82sNEBfsXpm7nfISKhmV1efVFiO -DCu3T6cw2Vbuyntd463JT17lNecxy9qTXtyOj4DatpGYQJB5w3jHtrHEtWoYOAMQ -jdjUN6QuBX2I9YI+EJFwq1WCQTLX2wRzKm6RAXwhTNS8rhsDdV14Ztk6MUSaM0C/ -CNdaSaTC5qmgZ92kJ7yhTzm1EVgX9yRcRo9k98FpiHaYdj1ZXUJ2h4mXaXpI8OCi -EhtmmnTK3kse5w5jrubU75KSOp493ADkRSWJtppEGSt+wJS00mFt6zPZxd9LBADM -fRyVw4/3IbKyEbe7f/LVjHAsQWCqsWMYRJUadmJ+9oCw++hkpjPRiQfhvbfmQ6QY -uKZ3AeEPlAwhHbJUKSWJbOUOUlFHdL4mrLZBdd56rF+NP8m800ERElvlEFDrMcXK -chYiCd98THU/Y+whX8QgUWtvsauGi0/C1kVfnSD8oR7FwI+isX4KJpn15GkvmB0t -9dmpsh3lGwIDAQABo0IwQDAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIB -hjAdBgNVHQ4EFgQU7NfjgtJxXWRM3y5nP+e6mK4cD08wDQYJKoZIhvcNAQEMBQAD -ggIBALth2X2pbL4XxJEbw6GiAI3jZGgPVs93rnD5/ZpKmbnJeFwMDF/k5hQpVgs2 -SV1EY+CtnJYYZhsjDT156W1r1lT40jzBQ0CuHVD1UvyQO7uYmWlrx8GnqGikJ9yd -+SeuMIW59mdNOj6PWTkiU0TryF0Dyu1Qen1iIQqAyHNm0aAFYF/opbSnr6j3bTWc -fFqK1qI4mfN4i/RN0iAL3gTujJtHgXINwBQy7zBZLq7gcfJW5GqXb5JQbZaNaHqa -sjYUegbyJLkJEVDXCLG4iXqEI2FCKeWjzaIgQdfRnGTZ6iahixTXTBmyUEFxPT9N -cCOGDErcgdLMMpSEDQgJlxxPwO5rIHQw0uA5NBCFIRUBCOhVMt5xSdkoF1BN5r5N -0XWs0Mr7QbhDparTwwVETyw2m+L64kW4I1NsBm9nVX9GtUw/bihaeSbSpKhil9Ie -4u1Ki7wb/UdKDd9nZn6yW0HQO+T0O/QEY+nvwlQAUaCKKsnOeMzV6ocEGLPOr0mI -r/OSmbaz5mEP0oUA51Aa5BuVnRmhuZyxm7EAHu/QD09CbMkKvO5D+jpxpchNJqU1 -/YldvIViHTLSoCtU7ZpXwdv6EM8Zt4tKG48BtieVU+i2iW1bvGjUI+iLUaJW+fCm -gKDWHrO8Dw9TdSmq6hN35N6MgSGtBxBHEa2HPQfRdbzP82Z+ ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: - 6a:68:3e:9c:51:9b:cb:53 - Signature Algorithm: sha256WithRSAEncryption - Issuer: C=TR, L=Ankara, O=E-Tu\xC4\x9Fra EBG Bili\xC5\x9Fim Teknolojileri ve Hizmetleri A.\xC5\x9E., OU=E-Tugra Sertifikasyon Merkezi, CN=E-Tugra Certification Authority - Validity - Not Before: Mar 5 12:09:48 2013 GMT - Not After : Mar 3 12:09:48 2023 GMT - Subject: C=TR, L=Ankara, O=E-Tu\xC4\x9Fra EBG Bili\xC5\x9Fim Teknolojileri ve Hizmetleri A.\xC5\x9E., OU=E-Tugra Sertifikasyon Merkezi, CN=E-Tugra Certification Authority - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (4096 bit) - Modulus: - 00:e2:f5:3f:93:05:51:1e:85:62:54:5e:7a:0b:f5: - 18:07:83:ae:7e:af:7c:f7:d4:8a:6b:a5:63:43:39: - b9:4b:f7:c3:c6:64:89:3d:94:2e:54:80:52:39:39: - 07:4b:4b:dd:85:07:76:87:cc:bf:2f:95:4c:cc:7d: - a7:3d:bc:47:0f:98:70:f8:8c:85:1e:74:8e:92:6d: - 1b:40:d1:99:0d:bb:75:6e:c8:a9:6b:9a:c0:84:31: - af:ca:43:cb:eb:2b:34:e8:8f:97:6b:01:9b:d5:0e: - 4a:08:aa:5b:92:74:85:43:d3:80:ae:a1:88:5b:ae: - b3:ea:5e:cb:16:9a:77:44:c8:a1:f6:54:68:ce:de: - 8f:97:2b:ba:5b:40:02:0c:64:17:c0:b5:93:cd:e1: - f1:13:66:ce:0c:79:ef:d1:91:28:ab:5f:a0:12:52: - 30:73:19:8e:8f:e1:8c:07:a2:c3:bb:4a:f0:ea:1f: - 15:a8:ee:25:cc:a4:46:f8:1b:22:ef:b3:0e:43:ba: - 2c:24:b8:c5:2c:5c:d4:1c:f8:5d:64:bd:c3:93:5e: - 28:a7:3f:27:f1:8e:1e:d3:2a:50:05:a3:55:d9:cb: - e7:39:53:c0:98:9e:8c:54:62:8b:26:b0:f7:7d:8d: - 7c:e4:c6:9e:66:42:55:82:47:e7:b2:58:8d:66:f7: - 07:7c:2e:36:e6:50:1c:3f:db:43:24:c5:bf:86:47: - 79:b3:79:1c:f7:5a:f4:13:ec:6c:f8:3f:e2:59:1f: - 95:ee:42:3e:b9:ad:a8:32:85:49:97:46:fe:4b:31: - 8f:5a:cb:ad:74:47:1f:e9:91:b7:df:28:04:22:a0: - d4:0f:5d:e2:79:4f:ea:6c:85:86:bd:a8:a6:ce:e4: - fa:c3:e1:b3:ae:de:3c:51:ee:cb:13:7c:01:7f:84: - 0e:5d:51:94:9e:13:0c:b6:2e:a5:4c:f9:39:70:36: - 6f:96:ca:2e:0c:44:55:c5:ca:fa:5d:02:a3:df:d6: - 64:8c:5a:b3:01:0a:a9:b5:0a:47:17:ff:ef:91:40: - 2a:8e:a1:46:3a:31:98:e5:11:fc:cc:bb:49:56:8a: - fc:b9:d0:61:9a:6f:65:6c:e6:c3:cb:3e:75:49:fe: - 8f:a7:e2:89:c5:67:d7:9d:46:13:4e:31:76:3b:24: - b3:9e:11:65:86:ab:7f:ef:1d:d4:f8:bc:e7:ac:5a: - 5c:b7:5a:47:5c:55:ce:55:b4:22:71:5b:5b:0b:f0: - cf:dc:a0:61:64:ea:a9:d7:68:0a:63:a7:e0:0d:3f: - a0:af:d3:aa:d2:7e:ef:51:a0:e6:51:2b:55:92:15: - 17:53:cb:b7:66:0e:66:4c:f8:f9:75:4c:90:e7:12: - 70:c7:45 - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Subject Key Identifier: - 2E:E3:DB:B2:49:D0:9C:54:79:5C:FA:27:2A:FE:CC:4E:D2:E8:4E:54 - X509v3 Basic Constraints: critical - CA:TRUE - X509v3 Authority Key Identifier: - keyid:2E:E3:DB:B2:49:D0:9C:54:79:5C:FA:27:2A:FE:CC:4E:D2:E8:4E:54 - - X509v3 Key Usage: critical - Certificate Sign, CRL Sign - Signature Algorithm: sha256WithRSAEncryption - 05:37:3a:f4:4d:b7:45:e2:45:75:24:8f:b6:77:52:e8:1c:d8: - 10:93:65:f3:f2:59:06:a4:3e:1e:29:ec:5d:d1:d0:ab:7c:e0: - 0a:90:48:78:ed:4e:98:03:99:fe:28:60:91:1d:30:1d:b8:63: - 7c:a8:e6:35:b5:fa:d3:61:76:e6:d6:07:4b:ca:69:9a:b2:84: - 7a:77:93:45:17:15:9f:24:d0:98:13:12:ff:bb:a0:2e:fd:4e: - 4c:87:f8:ce:5c:aa:98:1b:05:e0:00:46:4a:82:80:a5:33:8b: - 28:dc:ed:38:d3:df:e5:3e:e9:fe:fb:59:dd:61:84:4f:d2:54: - 96:13:61:13:3e:8f:80:69:be:93:47:b5:35:43:d2:5a:bb:3d: - 5c:ef:b3:42:47:cd:3b:55:13:06:b0:09:db:fd:63:f6:3a:88: - 0a:99:6f:7e:e1:ce:1b:53:6a:44:66:23:51:08:7b:bc:5b:52: - a2:fd:06:37:38:40:61:8f:4a:96:b8:90:37:f8:66:c7:78:90: - 00:15:2e:8b:ad:51:35:53:07:a8:6b:68:ae:f9:4e:3c:07:26: - cd:08:05:70:cc:39:3f:76:bd:a5:d3:67:26:01:86:a6:53:d2: - 60:3b:7c:43:7f:55:8a:bc:95:1a:c1:28:39:4c:1f:43:d2:91: - f4:72:59:8a:b9:56:fc:3f:b4:9d:da:70:9c:76:5a:8c:43:50: - ee:8e:30:72:4d:df:ff:49:f7:c6:a9:67:d9:6d:ac:02:11:e2: - 3a:16:25:a7:58:08:cb:6f:53:41:9c:48:38:47:68:33:d1:d7: - c7:8f:d4:74:21:d4:c3:05:90:7a:ff:ce:96:88:b1:15:29:5d: - 23:ab:d0:60:a1:12:4f:de:f4:17:cd:32:e5:c9:bf:c8:43:ad: - fd:2e:8e:f1:af:e2:f4:98:fa:12:1f:20:d8:c0:a7:0c:85:c5: - 90:f4:3b:2d:96:26:b1:2c:be:4c:ab:eb:b1:d2:8a:c9:db:78: - 13:0f:1e:09:9d:6d:8f:00:9f:02:da:c1:fa:1f:7a:7a:09:c4: - 4a:e6:88:2a:97:9f:89:8b:fd:37:5f:5f:3a:ce:38:59:86:4b: - af:71:0b:b4:d8:f2:70:4f:9f:32:13:e3:b0:a7:57:e5:da:da: - 43:cb:84:34:f2:28:c4:ea:6d:f4:2a:ef:c1:6b:76:da:fb:7e: - bb:85:3c:d2:53:c2:4d:be:71:e1:45:d1:fd:23:67:0d:13:75: - fb:cf:65:67:22:9d:ae:b0:09:d1:09:ff:1d:34:bf:fe:23:97: - 37:d2:39:fa:3d:0d:06:0b:b4:db:3b:a3:ab:6f:5c:1d:b6:7e: - e8:b3:82:34:ed:06:5c:24 ------BEGIN CERTIFICATE----- -MIIGSzCCBDOgAwIBAgIIamg+nFGby1MwDQYJKoZIhvcNAQELBQAwgbIxCzAJBgNV -BAYTAlRSMQ8wDQYDVQQHDAZBbmthcmExQDA+BgNVBAoMN0UtVHXEn3JhIEVCRyBC -aWxpxZ9pbSBUZWtub2xvamlsZXJpIHZlIEhpem1ldGxlcmkgQS7Fni4xJjAkBgNV -BAsMHUUtVHVncmEgU2VydGlmaWthc3lvbiBNZXJrZXppMSgwJgYDVQQDDB9FLVR1 -Z3JhIENlcnRpZmljYXRpb24gQXV0aG9yaXR5MB4XDTEzMDMwNTEyMDk0OFoXDTIz -MDMwMzEyMDk0OFowgbIxCzAJBgNVBAYTAlRSMQ8wDQYDVQQHDAZBbmthcmExQDA+ -BgNVBAoMN0UtVHXEn3JhIEVCRyBCaWxpxZ9pbSBUZWtub2xvamlsZXJpIHZlIEhp -em1ldGxlcmkgQS7Fni4xJjAkBgNVBAsMHUUtVHVncmEgU2VydGlmaWthc3lvbiBN -ZXJrZXppMSgwJgYDVQQDDB9FLVR1Z3JhIENlcnRpZmljYXRpb24gQXV0aG9yaXR5 -MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEA4vU/kwVRHoViVF56C/UY -B4Oufq9899SKa6VjQzm5S/fDxmSJPZQuVIBSOTkHS0vdhQd2h8y/L5VMzH2nPbxH -D5hw+IyFHnSOkm0bQNGZDbt1bsipa5rAhDGvykPL6ys06I+XawGb1Q5KCKpbknSF -Q9OArqGIW66z6l7LFpp3RMih9lRozt6Plyu6W0ACDGQXwLWTzeHxE2bODHnv0ZEo -q1+gElIwcxmOj+GMB6LDu0rw6h8VqO4lzKRG+Bsi77MOQ7osJLjFLFzUHPhdZL3D -k14opz8n8Y4e0ypQBaNV2cvnOVPAmJ6MVGKLJrD3fY185MaeZkJVgkfnsliNZvcH -fC425lAcP9tDJMW/hkd5s3kc91r0E+xs+D/iWR+V7kI+ua2oMoVJl0b+SzGPWsut -dEcf6ZG33ygEIqDUD13ieU/qbIWGvaimzuT6w+Gzrt48Ue7LE3wBf4QOXVGUnhMM -ti6lTPk5cDZvlsouDERVxcr6XQKj39ZkjFqzAQqptQpHF//vkUAqjqFGOjGY5RH8 -zLtJVor8udBhmm9lbObDyz51Sf6Pp+KJxWfXnUYTTjF2OySznhFlhqt/7x3U+Lzn -rFpct1pHXFXOVbQicVtbC/DP3KBhZOqp12gKY6fgDT+gr9Oq0n7vUaDmUStVkhUX -U8u3Zg5mTPj5dUyQ5xJwx0UCAwEAAaNjMGEwHQYDVR0OBBYEFC7j27JJ0JxUeVz6 -Jyr+zE7S6E5UMA8GA1UdEwEB/wQFMAMBAf8wHwYDVR0jBBgwFoAULuPbsknQnFR5 -XPonKv7MTtLoTlQwDgYDVR0PAQH/BAQDAgEGMA0GCSqGSIb3DQEBCwUAA4ICAQAF -Nzr0TbdF4kV1JI+2d1LoHNgQk2Xz8lkGpD4eKexd0dCrfOAKkEh47U6YA5n+KGCR -HTAduGN8qOY1tfrTYXbm1gdLymmasoR6d5NFFxWfJNCYExL/u6Au/U5Mh/jOXKqY -GwXgAEZKgoClM4so3O0409/lPun++1ndYYRP0lSWE2ETPo+Aab6TR7U1Q9Jauz1c -77NCR807VRMGsAnb/WP2OogKmW9+4c4bU2pEZiNRCHu8W1Ki/QY3OEBhj0qWuJA3 -+GbHeJAAFS6LrVE1Uweoa2iu+U48BybNCAVwzDk/dr2l02cmAYamU9JgO3xDf1WK -vJUawSg5TB9D0pH0clmKuVb8P7Sd2nCcdlqMQ1DujjByTd//SffGqWfZbawCEeI6 -FiWnWAjLb1NBnEg4R2gz0dfHj9R0IdTDBZB6/86WiLEVKV0jq9BgoRJP3vQXzTLl -yb/IQ639Lo7xr+L0mPoSHyDYwKcMhcWQ9DstliaxLL5Mq+ux0orJ23gTDx4JnW2P -AJ8C2sH6H3p6CcRK5ogql5+Ji/03X186zjhZhkuvcQu02PJwT58yE+Owp1fl2tpD -y4Q08ijE6m30Ku/Ba3ba+367hTzSU8JNvnHhRdH9I2cNE3X7z2VnIp2usAnRCf8d -NL/+I5c30jn6PQ0GC7TbO6Orb1wdtn7os4I07QZcJA== ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: - (Negative)11:d4:c2:14:2b:de:21:eb:57:9d:53:fb:0c:22:3b:ff - Signature Algorithm: sha1WithRSAEncryption - Issuer: C=ES, O=Agencia Catalana de Certificacio (NIF Q-0801176-I), OU=Serveis Publics de Certificacio, OU=Vegeu https://www.catcert.net/verarrel (c)03, OU=Jerarquia Entitats de Certificacio Catalanes, CN=EC-ACC - Validity - Not Before: Jan 7 23:00:00 2003 GMT - Not After : Jan 7 22:59:59 2031 GMT - Subject: C=ES, O=Agencia Catalana de Certificacio (NIF Q-0801176-I), OU=Serveis Publics de Certificacio, OU=Vegeu https://www.catcert.net/verarrel (c)03, OU=Jerarquia Entitats de Certificacio Catalanes, CN=EC-ACC - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (2048 bit) - Modulus: - 00:b3:22:c7:4f:e2:97:42:95:88:47:83:40:f6:1d: - 17:f3:83:73:24:1e:51:f3:98:8a:c3:92:b8:ff:40: - 90:05:70:87:60:c9:00:a9:b5:94:65:19:22:15:17: - c2:43:6c:66:44:9a:0d:04:3e:39:6f:a5:4b:7a:aa: - 63:b7:8a:44:9d:d9:63:91:84:66:e0:28:0f:ba:42: - e3:6e:8e:f7:14:27:93:69:ee:91:0e:a3:5f:0e:b1: - eb:66:a2:72:4f:12:13:86:65:7a:3e:db:4f:07:f4: - a7:09:60:da:3a:42:99:c7:b2:7f:b3:16:95:1c:c7: - f9:34:b5:94:85:d5:99:5e:a0:48:a0:7e:e7:17:65: - b8:a2:75:b8:1e:f3:e5:42:7d:af:ed:f3:8a:48:64: - 5d:82:14:93:d8:c0:e4:ff:b3:50:72:f2:76:f6:b3: - 5d:42:50:79:d0:94:3e:6b:0c:00:be:d8:6b:0e:4e: - 2a:ec:3e:d2:cc:82:a2:18:65:33:13:77:9e:9a:5d: - 1a:13:d8:c3:db:3d:c8:97:7a:ee:70:ed:a7:e6:7c: - db:71:cf:2d:94:62:df:6d:d6:f5:38:be:3f:a5:85: - 0a:19:b8:a8:d8:09:75:42:70:c4:ea:ef:cb:0e:c8: - 34:a8:12:22:98:0c:b8:13:94:b6:4b:ec:f0:d0:90: - e7:27 - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Subject Alternative Name: - email:ec_acc@catcert.net - X509v3 Basic Constraints: critical - CA:TRUE - X509v3 Key Usage: critical - Certificate Sign, CRL Sign - X509v3 Subject Key Identifier: - A0:C3:8B:44:AA:37:A5:45:BF:97:80:5A:D1:F1:78:A2:9B:E9:5D:8D - X509v3 Certificate Policies: - Policy: 1.3.6.1.4.1.15096.1.3.1.10 - CPS: https://www.catcert.net/verarrel - User Notice: - Explicit Text: Vegeu https://www.catcert.net/verarrel - - Signature Algorithm: sha1WithRSAEncryption - a0:48:5b:82:01:f6:4d:48:b8:39:55:35:9c:80:7a:53:99:d5: - 5a:ff:b1:71:3b:cc:39:09:94:5e:d6:da:ef:be:01:5b:5d:d3: - 1e:d8:fd:7d:4f:cd:a0:41:e0:34:93:bf:cb:e2:86:9c:37:92: - 90:56:1c:dc:eb:29:05:e5:c4:9e:c7:35:df:8a:0c:cd:c5:21: - 43:e9:aa:88:e5:35:c0:19:42:63:5a:02:5e:a4:48:18:3a:85: - 6f:dc:9d:bc:3f:9d:9c:c1:87:b8:7a:61:08:e9:77:0b:7f:70: - ab:7a:dd:d9:97:2c:64:1e:85:bf:bc:74:96:a1:c3:7a:12:ec: - 0c:1a:6e:83:0c:3c:e8:72:46:9f:fb:48:d5:5e:97:e6:b1:a1: - f8:e4:ef:46:25:94:9c:89:db:69:38:be:ec:5c:0e:56:c7:65: - 51:e5:50:88:88:bf:42:d5:2b:3d:e5:f9:ba:9e:2e:b3:ca:f4: - 73:92:02:0b:be:4c:66:eb:20:fe:b9:cb:b5:99:7f:e6:b6:13: - fa:ca:4b:4d:d9:ee:53:46:06:3b:c6:4e:ad:93:5a:81:7e:6c: - 2a:4b:6a:05:45:8c:f2:21:a4:31:90:87:6c:65:9c:9d:a5:60: - 95:3a:52:7f:f5:d1:ab:08:6e:f3:ee:5b:f9:88:3d:7e:b8:6f: - 6e:03:e4:42 ------BEGIN CERTIFICATE----- -MIIFVjCCBD6gAwIBAgIQ7is969Qh3hSoYqwE893EATANBgkqhkiG9w0BAQUFADCB -8zELMAkGA1UEBhMCRVMxOzA5BgNVBAoTMkFnZW5jaWEgQ2F0YWxhbmEgZGUgQ2Vy -dGlmaWNhY2lvIChOSUYgUS0wODAxMTc2LUkpMSgwJgYDVQQLEx9TZXJ2ZWlzIFB1 -YmxpY3MgZGUgQ2VydGlmaWNhY2lvMTUwMwYDVQQLEyxWZWdldSBodHRwczovL3d3 -dy5jYXRjZXJ0Lm5ldC92ZXJhcnJlbCAoYykwMzE1MDMGA1UECxMsSmVyYXJxdWlh -IEVudGl0YXRzIGRlIENlcnRpZmljYWNpbyBDYXRhbGFuZXMxDzANBgNVBAMTBkVD -LUFDQzAeFw0wMzAxMDcyMzAwMDBaFw0zMTAxMDcyMjU5NTlaMIHzMQswCQYDVQQG -EwJFUzE7MDkGA1UEChMyQWdlbmNpYSBDYXRhbGFuYSBkZSBDZXJ0aWZpY2FjaW8g -KE5JRiBRLTA4MDExNzYtSSkxKDAmBgNVBAsTH1NlcnZlaXMgUHVibGljcyBkZSBD -ZXJ0aWZpY2FjaW8xNTAzBgNVBAsTLFZlZ2V1IGh0dHBzOi8vd3d3LmNhdGNlcnQu -bmV0L3ZlcmFycmVsIChjKTAzMTUwMwYDVQQLEyxKZXJhcnF1aWEgRW50aXRhdHMg -ZGUgQ2VydGlmaWNhY2lvIENhdGFsYW5lczEPMA0GA1UEAxMGRUMtQUNDMIIBIjAN -BgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAsyLHT+KXQpWIR4NA9h0X84NzJB5R -85iKw5K4/0CQBXCHYMkAqbWUZRkiFRfCQ2xmRJoNBD45b6VLeqpjt4pEndljkYRm -4CgPukLjbo73FCeTae6RDqNfDrHrZqJyTxIThmV6PttPB/SnCWDaOkKZx7J/sxaV -HMf5NLWUhdWZXqBIoH7nF2W4onW4HvPlQn2v7fOKSGRdghST2MDk/7NQcvJ29rNd -QlB50JQ+awwAvthrDk4q7D7SzIKiGGUzE3eeml0aE9jD2z3Il3rucO2n5nzbcc8t -lGLfbdb1OL4/pYUKGbio2Al1QnDE6u/LDsg0qBIimAy4E5S2S+zw0JDnJwIDAQAB -o4HjMIHgMB0GA1UdEQQWMBSBEmVjX2FjY0BjYXRjZXJ0Lm5ldDAPBgNVHRMBAf8E -BTADAQH/MA4GA1UdDwEB/wQEAwIBBjAdBgNVHQ4EFgQUoMOLRKo3pUW/l4Ba0fF4 -opvpXY0wfwYDVR0gBHgwdjB0BgsrBgEEAfV4AQMBCjBlMCwGCCsGAQUFBwIBFiBo -dHRwczovL3d3dy5jYXRjZXJ0Lm5ldC92ZXJhcnJlbDA1BggrBgEFBQcCAjApGidW -ZWdldSBodHRwczovL3d3dy5jYXRjZXJ0Lm5ldC92ZXJhcnJlbCAwDQYJKoZIhvcN -AQEFBQADggEBAKBIW4IB9k1IuDlVNZyAelOZ1Vr/sXE7zDkJlF7W2u++AVtd0x7Y -/X1PzaBB4DSTv8vihpw3kpBWHNzrKQXlxJ7HNd+KDM3FIUPpqojlNcAZQmNaAl6k -SBg6hW/cnbw/nZzBh7h6YQjpdwt/cKt63dmXLGQehb+8dJahw3oS7AwaboMMPOhy -Rp/7SNVel+axofjk70YllJyJ22k4vuxcDlbHZVHlUIiIv0LVKz3l+bqeLrPK9HOS -Agu+TGbrIP65y7WZf+a2E/rKS03Z7lNGBjvGTq2TWoF+bCpLagVFjPIhpDGQh2xl -nJ2lYJU6Un/10asIbvPuW/mIPX64b24D5EI= ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: - 54:80:f9:a0:73:ed:3f:00:4c:ca:89:d8:e3:71:e6:4a - Signature Algorithm: sha1WithRSAEncryption - Issuer: C=EE, O=AS Sertifitseerimiskeskus, CN=EE Certification Centre Root CA/emailAddress=pki@sk.ee - Validity - Not Before: Oct 30 10:10:30 2010 GMT - Not After : Dec 17 23:59:59 2030 GMT - Subject: C=EE, O=AS Sertifitseerimiskeskus, CN=EE Certification Centre Root CA/emailAddress=pki@sk.ee - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (2048 bit) - Modulus: - 00:c8:20:c0:ec:e0:c5:4b:ab:07:78:95:f3:44:ee: - fb:0b:0c:ff:74:8e:61:bb:b1:62:ea:23:d8:ab:a1: - 65:32:7a:eb:8e:17:4f:96:d8:0a:7b:91:a2:63:6c: - c7:8c:4c:2e:79:bf:a9:05:fc:69:5c:95:8d:62:f9: - b9:70:ed:c3:51:7d:d0:93:e6:6c:eb:30:4b:e1:bc: - 7d:bf:52:9b:ce:6e:7b:65:f2:38:b1:c0:a2:32:ef: - 62:b2:68:e0:61:53:c1:36:95:ff:ec:94:ba:36:ae: - 9c:1c:a7:32:0f:e5:7c:b4:c6:6f:74:fd:7b:18:e8: - ac:57:ed:06:20:4b:32:30:58:5b:fd:cd:a8:e6:a1: - fc:70:bc:8e:92:73:db:97:a7:7c:21:ae:3d:c1:f5: - 48:87:6c:27:bd:9f:25:74:81:55:b0:f7:75:f6:3d: - a4:64:6b:d6:4f:e7:ce:40:ad:0f:dd:32:d3:bc:8a: - 12:53:98:c9:89:fb:10:1d:4d:7e:cd:7e:1f:56:0d: - 21:70:85:f6:20:83:1f:f6:ba:1f:04:8f:ea:77:88: - 35:c4:ff:ea:4e:a1:8b:4d:3f:63:1b:44:c3:44:d4: - 25:76:ca:b7:8d:d7:1e:4a:66:64:cd:5c:c5:9c:83: - e1:c2:08:88:9a:ec:4e:a3:f1:3e:1c:2c:d9:6c:1d: - a1:4b - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Basic Constraints: critical - CA:TRUE - X509v3 Key Usage: critical - Certificate Sign, CRL Sign - X509v3 Subject Key Identifier: - 12:F2:5A:3E:EA:56:1C:BF:CD:06:AC:F1:F1:25:C9:A9:4B:D4:14:99 - X509v3 Extended Key Usage: - TLS Web Client Authentication, TLS Web Server Authentication, Code Signing, E-mail Protection, Time Stamping, OCSP Signing - Signature Algorithm: sha1WithRSAEncryption - 7b:f6:e4:c0:0d:aa:19:47:b7:4d:57:a3:fe:ad:bb:b1:6a:d5: - 0f:9e:db:e4:63:c5:8e:a1:50:56:93:96:b8:38:c0:24:22:66: - bc:53:14:61:95:bf:d0:c7:2a:96:39:3f:7d:28:b3:10:40:21: - 6a:c4:af:b0:52:77:18:e1:96:d8:56:5d:e3:dd:36:5e:1d:a7: - 50:54:a0:c5:2a:e4:aa:8c:94:8a:4f:9d:35:ff:76:a4:06:13: - 91:a2:a2:7d:00:44:3f:55:d3:82:3c:1a:d5:5b:bc:56:4c:22: - 2e:46:43:8a:24:40:2d:f3:12:b8:3b:70:1a:a4:96:b9:1a:af: - 87:41:1a:6a:18:0d:06:4f:c7:3e:6e:b9:29:4d:0d:49:89:11: - 87:32:5b:e6:4b:04:c8:e4:5c:e6:74:73:94:5d:16:98:13:95: - fe:fb:db:b1:44:e5:3a:70:ac:37:6b:e6:b3:33:72:28:c9:b3: - 57:a0:f6:02:16:88:06:0b:b6:a6:4b:20:28:d4:de:3d:8b:ad: - 37:05:53:74:fe:6e:cc:bc:43:17:71:5e:f9:c5:cc:1a:a9:61: - ee:f7:76:0c:f3:72:f4:72:ad:cf:72:02:36:07:47:cf:ef:19: - 50:89:60:cc:e9:24:95:0f:c2:cb:1d:f2:6f:76:90:c7:cc:75: - c1:96:c5:9d ------BEGIN CERTIFICATE----- -MIIEAzCCAuugAwIBAgIQVID5oHPtPwBMyonY43HmSjANBgkqhkiG9w0BAQUFADB1 -MQswCQYDVQQGEwJFRTEiMCAGA1UECgwZQVMgU2VydGlmaXRzZWVyaW1pc2tlc2t1 -czEoMCYGA1UEAwwfRUUgQ2VydGlmaWNhdGlvbiBDZW50cmUgUm9vdCBDQTEYMBYG -CSqGSIb3DQEJARYJcGtpQHNrLmVlMCIYDzIwMTAxMDMwMTAxMDMwWhgPMjAzMDEy -MTcyMzU5NTlaMHUxCzAJBgNVBAYTAkVFMSIwIAYDVQQKDBlBUyBTZXJ0aWZpdHNl -ZXJpbWlza2Vza3VzMSgwJgYDVQQDDB9FRSBDZXJ0aWZpY2F0aW9uIENlbnRyZSBS -b290IENBMRgwFgYJKoZIhvcNAQkBFglwa2lAc2suZWUwggEiMA0GCSqGSIb3DQEB -AQUAA4IBDwAwggEKAoIBAQDIIMDs4MVLqwd4lfNE7vsLDP90jmG7sWLqI9iroWUy -euuOF0+W2Ap7kaJjbMeMTC55v6kF/GlclY1i+blw7cNRfdCT5mzrMEvhvH2/UpvO -bntl8jixwKIy72KyaOBhU8E2lf/slLo2rpwcpzIP5Xy0xm90/XsY6KxX7QYgSzIw -WFv9zajmofxwvI6Sc9uXp3whrj3B9UiHbCe9nyV0gVWw93X2PaRka9ZP585ArQ/d -MtO8ihJTmMmJ+xAdTX7Nfh9WDSFwhfYggx/2uh8Ej+p3iDXE/+pOoYtNP2MbRMNE -1CV2yreN1x5KZmTNXMWcg+HCCIia7E6j8T4cLNlsHaFLAgMBAAGjgYowgYcwDwYD -VR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYEFBLyWj7qVhy/ -zQas8fElyalL1BSZMEUGA1UdJQQ+MDwGCCsGAQUFBwMCBggrBgEFBQcDAQYIKwYB -BQUHAwMGCCsGAQUFBwMEBggrBgEFBQcDCAYIKwYBBQUHAwkwDQYJKoZIhvcNAQEF -BQADggEBAHv25MANqhlHt01Xo/6tu7Fq1Q+e2+RjxY6hUFaTlrg4wCQiZrxTFGGV -v9DHKpY5P30osxBAIWrEr7BSdxjhlthWXePdNl4dp1BUoMUq5KqMlIpPnTX/dqQG -E5Gion0ARD9V04I8GtVbvFZMIi5GQ4okQC3zErg7cBqklrkar4dBGmoYDQZPxz5u -uSlNDUmJEYcyW+ZLBMjkXOZ0c5RdFpgTlf7727FE5TpwrDdr5rMzcijJs1eg9gIW -iAYLtqZLICjU3j2LrTcFU3T+bsy8QxdxXvnFzBqpYe73dgzzcvRyrc9yAjYHR8/v -GVCJYMzpJJUPwssd8m92kMfMdcGWxZ0= ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: 946069240 (0x3863def8) - Signature Algorithm: sha1WithRSAEncryption - Issuer: O=Entrust.net, OU=www.entrust.net/CPS_2048 incorp. by ref. (limits liab.), OU=(c) 1999 Entrust.net Limited, CN=Entrust.net Certification Authority (2048) - Validity - Not Before: Dec 24 17:50:51 1999 GMT - Not After : Jul 24 14:15:12 2029 GMT - Subject: O=Entrust.net, OU=www.entrust.net/CPS_2048 incorp. by ref. (limits liab.), OU=(c) 1999 Entrust.net Limited, CN=Entrust.net Certification Authority (2048) - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (2048 bit) - Modulus: - 00:ad:4d:4b:a9:12:86:b2:ea:a3:20:07:15:16:64: - 2a:2b:4b:d1:bf:0b:4a:4d:8e:ed:80:76:a5:67:b7: - 78:40:c0:73:42:c8:68:c0:db:53:2b:dd:5e:b8:76: - 98:35:93:8b:1a:9d:7c:13:3a:0e:1f:5b:b7:1e:cf: - e5:24:14:1e:b1:81:a9:8d:7d:b8:cc:6b:4b:03:f1: - 02:0c:dc:ab:a5:40:24:00:7f:74:94:a1:9d:08:29: - b3:88:0b:f5:87:77:9d:55:cd:e4:c3:7e:d7:6a:64: - ab:85:14:86:95:5b:97:32:50:6f:3d:c8:ba:66:0c: - e3:fc:bd:b8:49:c1:76:89:49:19:fd:c0:a8:bd:89: - a3:67:2f:c6:9f:bc:71:19:60:b8:2d:e9:2c:c9:90: - 76:66:7b:94:e2:af:78:d6:65:53:5d:3c:d6:9c:b2: - cf:29:03:f9:2f:a4:50:b2:d4:48:ce:05:32:55:8a: - fd:b2:64:4c:0e:e4:98:07:75:db:7f:df:b9:08:55: - 60:85:30:29:f9:7b:48:a4:69:86:e3:35:3f:1e:86: - 5d:7a:7a:15:bd:ef:00:8e:15:22:54:17:00:90:26: - 93:bc:0e:49:68:91:bf:f8:47:d3:9d:95:42:c1:0e: - 4d:df:6f:26:cf:c3:18:21:62:66:43:70:d6:d5:c0: - 07:e1 - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Key Usage: critical - Certificate Sign, CRL Sign - X509v3 Basic Constraints: critical - CA:TRUE - X509v3 Subject Key Identifier: - 55:E4:81:D1:11:80:BE:D8:89:B9:08:A3:31:F9:A1:24:09:16:B9:70 - Signature Algorithm: sha1WithRSAEncryption - 3b:9b:8f:56:9b:30:e7:53:99:7c:7a:79:a7:4d:97:d7:19:95: - 90:fb:06:1f:ca:33:7c:46:63:8f:96:66:24:fa:40:1b:21:27: - ca:e6:72:73:f2:4f:fe:31:99:fd:c8:0c:4c:68:53:c6:80:82: - 13:98:fa:b6:ad:da:5d:3d:f1:ce:6e:f6:15:11:94:82:0c:ee: - 3f:95:af:11:ab:0f:d7:2f:de:1f:03:8f:57:2c:1e:c9:bb:9a: - 1a:44:95:eb:18:4f:a6:1f:cd:7d:57:10:2f:9b:04:09:5a:84: - b5:6e:d8:1d:3a:e1:d6:9e:d1:6c:79:5e:79:1c:14:c5:e3:d0: - 4c:93:3b:65:3c:ed:df:3d:be:a6:e5:95:1a:c3:b5:19:c3:bd: - 5e:5b:bb:ff:23:ef:68:19:cb:12:93:27:5c:03:2d:6f:30:d0: - 1e:b6:1a:ac:de:5a:f7:d1:aa:a8:27:a6:fe:79:81:c4:79:99: - 33:57:ba:12:b0:a9:e0:42:6c:93:ca:56:de:fe:6d:84:0b:08: - 8b:7e:8d:ea:d7:98:21:c6:f3:e7:3c:79:2f:5e:9c:d1:4c:15: - 8d:e1:ec:22:37:cc:9a:43:0b:97:dc:80:90:8d:b3:67:9b:6f: - 48:08:15:56:cf:bf:f1:2b:7c:5e:9a:76:e9:59:90:c5:7c:83: - 35:11:65:51 ------BEGIN CERTIFICATE----- -MIIEKjCCAxKgAwIBAgIEOGPe+DANBgkqhkiG9w0BAQUFADCBtDEUMBIGA1UEChML -RW50cnVzdC5uZXQxQDA+BgNVBAsUN3d3dy5lbnRydXN0Lm5ldC9DUFNfMjA0OCBp -bmNvcnAuIGJ5IHJlZi4gKGxpbWl0cyBsaWFiLikxJTAjBgNVBAsTHChjKSAxOTk5 -IEVudHJ1c3QubmV0IExpbWl0ZWQxMzAxBgNVBAMTKkVudHJ1c3QubmV0IENlcnRp -ZmljYXRpb24gQXV0aG9yaXR5ICgyMDQ4KTAeFw05OTEyMjQxNzUwNTFaFw0yOTA3 -MjQxNDE1MTJaMIG0MRQwEgYDVQQKEwtFbnRydXN0Lm5ldDFAMD4GA1UECxQ3d3d3 -LmVudHJ1c3QubmV0L0NQU18yMDQ4IGluY29ycC4gYnkgcmVmLiAobGltaXRzIGxp -YWIuKTElMCMGA1UECxMcKGMpIDE5OTkgRW50cnVzdC5uZXQgTGltaXRlZDEzMDEG -A1UEAxMqRW50cnVzdC5uZXQgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkgKDIwNDgp -MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEArU1LqRKGsuqjIAcVFmQq -K0vRvwtKTY7tgHalZ7d4QMBzQshowNtTK91euHaYNZOLGp18EzoOH1u3Hs/lJBQe -sYGpjX24zGtLA/ECDNyrpUAkAH90lKGdCCmziAv1h3edVc3kw37XamSrhRSGlVuX -MlBvPci6Zgzj/L24ScF2iUkZ/cCovYmjZy/Gn7xxGWC4LeksyZB2ZnuU4q941mVT -XTzWnLLPKQP5L6RQstRIzgUyVYr9smRMDuSYB3Xbf9+5CFVghTAp+XtIpGmG4zU/ -HoZdenoVve8AjhUiVBcAkCaTvA5JaJG/+EfTnZVCwQ5N328mz8MYIWJmQ3DW1cAH -4QIDAQABo0IwQDAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/BAUwAwEB/zAdBgNV -HQ4EFgQUVeSB0RGAvtiJuQijMfmhJAkWuXAwDQYJKoZIhvcNAQEFBQADggEBADub -j1abMOdTmXx6eadNl9cZlZD7Bh/KM3xGY4+WZiT6QBshJ8rmcnPyT/4xmf3IDExo -U8aAghOY+rat2l098c5u9hURlIIM7j+VrxGrD9cv3h8Dj1csHsm7mhpElesYT6Yf -zX1XEC+bBAlahLVu2B064dae0Wx5XnkcFMXj0EyTO2U87d89vqbllRrDtRnDvV5b -u/8j72gZyxKTJ1wDLW8w0B62GqzeWvfRqqgnpv55gcR5mTNXuhKwqeBCbJPKVt7+ -bYQLCIt+jerXmCHG8+c8eS9enNFMFY3h7CI3zJpDC5fcgJCNs2ebb0gIFVbPv/Er -fF6adulZkMV8gzURZVE= ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: 1164660820 (0x456b5054) - Signature Algorithm: sha1WithRSAEncryption - Issuer: C=US, O=Entrust, Inc., OU=www.entrust.net/CPS is incorporated by reference, OU=(c) 2006 Entrust, Inc., CN=Entrust Root Certification Authority - Validity - Not Before: Nov 27 20:23:42 2006 GMT - Not After : Nov 27 20:53:42 2026 GMT - Subject: C=US, O=Entrust, Inc., OU=www.entrust.net/CPS is incorporated by reference, OU=(c) 2006 Entrust, Inc., CN=Entrust Root Certification Authority - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (2048 bit) - Modulus: - 00:b6:95:b6:43:42:fa:c6:6d:2a:6f:48:df:94:4c: - 39:57:05:ee:c3:79:11:41:68:36:ed:ec:fe:9a:01: - 8f:a1:38:28:fc:f7:10:46:66:2e:4d:1e:1a:b1:1a: - 4e:c6:d1:c0:95:88:b0:c9:ff:31:8b:33:03:db:b7: - 83:7b:3e:20:84:5e:ed:b2:56:28:a7:f8:e0:b9:40: - 71:37:c5:cb:47:0e:97:2a:68:c0:22:95:62:15:db: - 47:d9:f5:d0:2b:ff:82:4b:c9:ad:3e:de:4c:db:90: - 80:50:3f:09:8a:84:00:ec:30:0a:3d:18:cd:fb:fd: - 2a:59:9a:23:95:17:2c:45:9e:1f:6e:43:79:6d:0c: - 5c:98:fe:48:a7:c5:23:47:5c:5e:fd:6e:e7:1e:b4: - f6:68:45:d1:86:83:5b:a2:8a:8d:b1:e3:29:80:fe: - 25:71:88:ad:be:bc:8f:ac:52:96:4b:aa:51:8d:e4: - 13:31:19:e8:4e:4d:9f:db:ac:b3:6a:d5:bc:39:54: - 71:ca:7a:7a:7f:90:dd:7d:1d:80:d9:81:bb:59:26: - c2:11:fe:e6:93:e2:f7:80:e4:65:fb:34:37:0e:29: - 80:70:4d:af:38:86:2e:9e:7f:57:af:9e:17:ae:eb: - 1c:cb:28:21:5f:b6:1c:d8:e7:a2:04:22:f9:d3:da: - d8:cb - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Key Usage: critical - Certificate Sign, CRL Sign - X509v3 Basic Constraints: critical - CA:TRUE - X509v3 Private Key Usage Period: - Not Before: Nov 27 20:23:42 2006 GMT, Not After: Nov 27 20:53:42 2026 GMT - X509v3 Authority Key Identifier: - keyid:68:90:E4:67:A4:A6:53:80:C7:86:66:A4:F1:F7:4B:43:FB:84:BD:6D - - X509v3 Subject Key Identifier: - 68:90:E4:67:A4:A6:53:80:C7:86:66:A4:F1:F7:4B:43:FB:84:BD:6D - 1.2.840.113533.7.65.0: - 0...V7.1:4.0.... - Signature Algorithm: sha1WithRSAEncryption - 93:d4:30:b0:d7:03:20:2a:d0:f9:63:e8:91:0c:05:20:a9:5f: - 19:ca:7b:72:4e:d4:b1:db:d0:96:fb:54:5a:19:2c:0c:08:f7: - b2:bc:85:a8:9d:7f:6d:3b:52:b3:2a:db:e7:d4:84:8c:63:f6: - 0f:cb:26:01:91:50:6c:f4:5f:14:e2:93:74:c0:13:9e:30:3a: - 50:e3:b4:60:c5:1c:f0:22:44:8d:71:47:ac:c8:1a:c9:e9:9b: - 9a:00:60:13:ff:70:7e:5f:11:4d:49:1b:b3:15:52:7b:c9:54: - da:bf:9d:95:af:6b:9a:d8:9e:e9:f1:e4:43:8d:e2:11:44:3a: - bf:af:bd:83:42:73:52:8b:aa:bb:a7:29:cf:f5:64:1c:0a:4d: - d1:bc:aa:ac:9f:2a:d0:ff:7f:7f:da:7d:ea:b1:ed:30:25:c1: - 84:da:34:d2:5b:78:83:56:ec:9c:36:c3:26:e2:11:f6:67:49: - 1d:92:ab:8c:fb:eb:ff:7a:ee:85:4a:a7:50:80:f0:a7:5c:4a: - 94:2e:5f:05:99:3c:52:41:e0:cd:b4:63:cf:01:43:ba:9c:83: - dc:8f:60:3b:f3:5a:b4:b4:7b:ae:da:0b:90:38:75:ef:81:1d: - 66:d2:f7:57:70:36:b3:bf:fc:28:af:71:25:85:5b:13:fe:1e: - 7f:5a:b4:3c ------BEGIN CERTIFICATE----- -MIIEkTCCA3mgAwIBAgIERWtQVDANBgkqhkiG9w0BAQUFADCBsDELMAkGA1UEBhMC -VVMxFjAUBgNVBAoTDUVudHJ1c3QsIEluYy4xOTA3BgNVBAsTMHd3dy5lbnRydXN0 -Lm5ldC9DUFMgaXMgaW5jb3Jwb3JhdGVkIGJ5IHJlZmVyZW5jZTEfMB0GA1UECxMW -KGMpIDIwMDYgRW50cnVzdCwgSW5jLjEtMCsGA1UEAxMkRW50cnVzdCBSb290IENl -cnRpZmljYXRpb24gQXV0aG9yaXR5MB4XDTA2MTEyNzIwMjM0MloXDTI2MTEyNzIw -NTM0MlowgbAxCzAJBgNVBAYTAlVTMRYwFAYDVQQKEw1FbnRydXN0LCBJbmMuMTkw -NwYDVQQLEzB3d3cuZW50cnVzdC5uZXQvQ1BTIGlzIGluY29ycG9yYXRlZCBieSBy -ZWZlcmVuY2UxHzAdBgNVBAsTFihjKSAyMDA2IEVudHJ1c3QsIEluYy4xLTArBgNV -BAMTJEVudHJ1c3QgUm9vdCBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTCCASIwDQYJ -KoZIhvcNAQEBBQADggEPADCCAQoCggEBALaVtkNC+sZtKm9I35RMOVcF7sN5EUFo -Nu3s/poBj6E4KPz3EEZmLk0eGrEaTsbRwJWIsMn/MYszA9u3g3s+IIRe7bJWKKf4 -4LlAcTfFy0cOlypowCKVYhXbR9n10Cv/gkvJrT7eTNuQgFA/CYqEAOwwCj0Yzfv9 -KlmaI5UXLEWeH25DeW0MXJj+SKfFI0dcXv1u5x609mhF0YaDW6KKjbHjKYD+JXGI -rb68j6xSlkuqUY3kEzEZ6E5Nn9uss2rVvDlUccp6en+Q3X0dgNmBu1kmwhH+5pPi -94DkZfs0Nw4pgHBNrziGLp5/V6+eF67rHMsoIV+2HNjnogQi+dPa2MsCAwEAAaOB -sDCBrTAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/BAUwAwEB/zArBgNVHRAEJDAi -gA8yMDA2MTEyNzIwMjM0MlqBDzIwMjYxMTI3MjA1MzQyWjAfBgNVHSMEGDAWgBRo -kORnpKZTgMeGZqTx90tD+4S9bTAdBgNVHQ4EFgQUaJDkZ6SmU4DHhmak8fdLQ/uE -vW0wHQYJKoZIhvZ9B0EABBAwDhsIVjcuMTo0LjADAgSQMA0GCSqGSIb3DQEBBQUA -A4IBAQCT1DCw1wMgKtD5Y+iRDAUgqV8ZyntyTtSx29CW+1RaGSwMCPeyvIWonX9t -O1KzKtvn1ISMY/YPyyYBkVBs9F8U4pN0wBOeMDpQ47RgxRzwIkSNcUesyBrJ6Zua -AGAT/3B+XxFNSRuzFVJ7yVTav52Vr2ua2J7p8eRDjeIRRDq/r72DQnNSi6q7pynP -9WQcCk3RvKqsnyrQ/39/2n3qse0wJcGE2jTSW3iDVuycNsMm4hH2Z0kdkquM++v/ -eu6FSqdQgPCnXEqULl8FmTxSQeDNtGPPAUO6nIPcj2A781q0tHuu2guQOHXvgR1m -0vdXcDazv/wor3ElhVsT/h5/WrQ8 ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: - a6:8b:79:29:00:00:00:00:50:d0:91:f9 - Signature Algorithm: ecdsa-with-SHA384 - Issuer: C=US, O=Entrust, Inc., OU=See www.entrust.net/legal-terms, OU=(c) 2012 Entrust, Inc. - for authorized use only, CN=Entrust Root Certification Authority - EC1 - Validity - Not Before: Dec 18 15:25:36 2012 GMT - Not After : Dec 18 15:55:36 2037 GMT - Subject: C=US, O=Entrust, Inc., OU=See www.entrust.net/legal-terms, OU=(c) 2012 Entrust, Inc. - for authorized use only, CN=Entrust Root Certification Authority - EC1 - Subject Public Key Info: - Public Key Algorithm: id-ecPublicKey - Public-Key: (384 bit) - pub: - 04:84:13:c9:d0:ba:6d:41:7b:e2:6c:d0:eb:55:5f: - 66:02:1a:24:f4:5b:89:69:47:e3:b8:c2:7d:f1:f2: - 02:c5:9f:a0:f6:5b:d5:8b:06:19:86:4f:53:10:6d: - 07:24:27:a1:a0:f8:d5:47:19:61:4c:7d:ca:93:27: - ea:74:0c:ef:6f:96:09:fe:63:ec:70:5d:36:ad:67: - 77:ae:c9:9d:7c:55:44:3a:a2:63:51:1f:f5:e3:62: - d4:a9:47:07:3e:cc:20 - ASN1 OID: secp384r1 - X509v3 extensions: - X509v3 Key Usage: critical - Certificate Sign, CRL Sign - X509v3 Basic Constraints: critical - CA:TRUE - X509v3 Subject Key Identifier: - B7:63:E7:1A:DD:8D:E9:08:A6:55:83:A4:E0:6A:50:41:65:11:42:49 - Signature Algorithm: ecdsa-with-SHA384 - 30:64:02:30:61:79:d8:e5:42:47:df:1c:ae:53:99:17:b6:6f: - 1c:7d:e1:bf:11:94:d1:03:88:75:e4:8d:89:a4:8a:77:46:de: - 6d:61:ef:02:f5:fb:b5:df:cc:fe:4e:ff:fe:a9:e6:a7:02:30: - 5b:99:d7:85:37:06:b5:7b:08:fd:eb:27:8b:4a:94:f9:e1:fa: - a7:8e:26:08:e8:7c:92:68:6d:73:d8:6f:26:ac:21:02:b8:99: - b7:26:41:5b:25:60:ae:d0:48:1a:ee:06 ------BEGIN CERTIFICATE----- -MIIC+TCCAoCgAwIBAgINAKaLeSkAAAAAUNCR+TAKBggqhkjOPQQDAzCBvzELMAkG -A1UEBhMCVVMxFjAUBgNVBAoTDUVudHJ1c3QsIEluYy4xKDAmBgNVBAsTH1NlZSB3 -d3cuZW50cnVzdC5uZXQvbGVnYWwtdGVybXMxOTA3BgNVBAsTMChjKSAyMDEyIEVu -dHJ1c3QsIEluYy4gLSBmb3IgYXV0aG9yaXplZCB1c2Ugb25seTEzMDEGA1UEAxMq -RW50cnVzdCBSb290IENlcnRpZmljYXRpb24gQXV0aG9yaXR5IC0gRUMxMB4XDTEy -MTIxODE1MjUzNloXDTM3MTIxODE1NTUzNlowgb8xCzAJBgNVBAYTAlVTMRYwFAYD -VQQKEw1FbnRydXN0LCBJbmMuMSgwJgYDVQQLEx9TZWUgd3d3LmVudHJ1c3QubmV0 -L2xlZ2FsLXRlcm1zMTkwNwYDVQQLEzAoYykgMjAxMiBFbnRydXN0LCBJbmMuIC0g -Zm9yIGF1dGhvcml6ZWQgdXNlIG9ubHkxMzAxBgNVBAMTKkVudHJ1c3QgUm9vdCBD -ZXJ0aWZpY2F0aW9uIEF1dGhvcml0eSAtIEVDMTB2MBAGByqGSM49AgEGBSuBBAAi -A2IABIQTydC6bUF74mzQ61VfZgIaJPRbiWlH47jCffHyAsWfoPZb1YsGGYZPUxBt -ByQnoaD41UcZYUx9ypMn6nQM72+WCf5j7HBdNq1nd67JnXxVRDqiY1Ef9eNi1KlH -Bz7MIKNCMEAwDgYDVR0PAQH/BAQDAgEGMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0O -BBYEFLdj5xrdjekIplWDpOBqUEFlEUJJMAoGCCqGSM49BAMDA2cAMGQCMGF52OVC -R98crlOZF7ZvHH3hvxGU0QOIdeSNiaSKd0bebWHvAvX7td/M/k7//qnmpwIwW5nX -hTcGtXsI/esni0qU+eH6p44mCOh8kmhtc9hvJqwhAriZtyZBWyVgrtBIGu4G ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: 1246989352 (0x4a538c28) - Signature Algorithm: sha256WithRSAEncryption - Issuer: C=US, O=Entrust, Inc., OU=See www.entrust.net/legal-terms, OU=(c) 2009 Entrust, Inc. - for authorized use only, CN=Entrust Root Certification Authority - G2 - Validity - Not Before: Jul 7 17:25:54 2009 GMT - Not After : Dec 7 17:55:54 2030 GMT - Subject: C=US, O=Entrust, Inc., OU=See www.entrust.net/legal-terms, OU=(c) 2009 Entrust, Inc. - for authorized use only, CN=Entrust Root Certification Authority - G2 - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (2048 bit) - Modulus: - 00:ba:84:b6:72:db:9e:0c:6b:e2:99:e9:30:01:a7: - 76:ea:32:b8:95:41:1a:c9:da:61:4e:58:72:cf:fe: - f6:82:79:bf:73:61:06:0a:a5:27:d8:b3:5f:d3:45: - 4e:1c:72:d6:4e:32:f2:72:8a:0f:f7:83:19:d0:6a: - 80:80:00:45:1e:b0:c7:e7:9a:bf:12:57:27:1c:a3: - 68:2f:0a:87:bd:6a:6b:0e:5e:65:f3:1c:77:d5:d4: - 85:8d:70:21:b4:b3:32:e7:8b:a2:d5:86:39:02:b1: - b8:d2:47:ce:e4:c9:49:c4:3b:a7:de:fb:54:7d:57: - be:f0:e8:6e:c2:79:b2:3a:0b:55:e2:50:98:16:32: - 13:5c:2f:78:56:c1:c2:94:b3:f2:5a:e4:27:9a:9f: - 24:d7:c6:ec:d0:9b:25:82:e3:cc:c2:c4:45:c5:8c: - 97:7a:06:6b:2a:11:9f:a9:0a:6e:48:3b:6f:db:d4: - 11:19:42:f7:8f:07:bf:f5:53:5f:9c:3e:f4:17:2c: - e6:69:ac:4e:32:4c:62:77:ea:b7:e8:e5:bb:34:bc: - 19:8b:ae:9c:51:e7:b7:7e:b5:53:b1:33:22:e5:6d: - cf:70:3c:1a:fa:e2:9b:67:b6:83:f4:8d:a5:af:62: - 4c:4d:e0:58:ac:64:34:12:03:f8:b6:8d:94:63:24: - a4:71 - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Key Usage: critical - Certificate Sign, CRL Sign - X509v3 Basic Constraints: critical - CA:TRUE - X509v3 Subject Key Identifier: - 6A:72:26:7A:D0:1E:EF:7D:E7:3B:69:51:D4:6C:8D:9F:90:12:66:AB - Signature Algorithm: sha256WithRSAEncryption - 79:9f:1d:96:c6:b6:79:3f:22:8d:87:d3:87:03:04:60:6a:6b: - 9a:2e:59:89:73:11:ac:43:d1:f5:13:ff:8d:39:2b:c0:f2:bd: - 4f:70:8c:a9:2f:ea:17:c4:0b:54:9e:d4:1b:96:98:33:3c:a8: - ad:62:a2:00:76:ab:59:69:6e:06:1d:7e:c4:b9:44:8d:98:af: - 12:d4:61:db:0a:19:46:47:f3:eb:f7:63:c1:40:05:40:a5:d2: - b7:f4:b5:9a:36:bf:a9:88:76:88:04:55:04:2b:9c:87:7f:1a: - 37:3c:7e:2d:a5:1a:d8:d4:89:5e:ca:bd:ac:3d:6c:d8:6d:af: - d5:f3:76:0f:cd:3b:88:38:22:9d:6c:93:9a:c4:3d:bf:82:1b: - 65:3f:a6:0f:5d:aa:fc:e5:b2:15:ca:b5:ad:c6:bc:3d:d0:84: - e8:ea:06:72:b0:4d:39:32:78:bf:3e:11:9c:0b:a4:9d:9a:21: - f3:f0:9b:0b:30:78:db:c1:dc:87:43:fe:bc:63:9a:ca:c5:c2: - 1c:c9:c7:8d:ff:3b:12:58:08:e6:b6:3d:ec:7a:2c:4e:fb:83: - 96:ce:0c:3c:69:87:54:73:a4:73:c2:93:ff:51:10:ac:15:54: - 01:d8:fc:05:b1:89:a1:7f:74:83:9a:49:d7:dc:4e:7b:8a:48: - 6f:8b:45:f6 ------BEGIN CERTIFICATE----- -MIIEPjCCAyagAwIBAgIESlOMKDANBgkqhkiG9w0BAQsFADCBvjELMAkGA1UEBhMC -VVMxFjAUBgNVBAoTDUVudHJ1c3QsIEluYy4xKDAmBgNVBAsTH1NlZSB3d3cuZW50 -cnVzdC5uZXQvbGVnYWwtdGVybXMxOTA3BgNVBAsTMChjKSAyMDA5IEVudHJ1c3Qs -IEluYy4gLSBmb3IgYXV0aG9yaXplZCB1c2Ugb25seTEyMDAGA1UEAxMpRW50cnVz -dCBSb290IENlcnRpZmljYXRpb24gQXV0aG9yaXR5IC0gRzIwHhcNMDkwNzA3MTcy -NTU0WhcNMzAxMjA3MTc1NTU0WjCBvjELMAkGA1UEBhMCVVMxFjAUBgNVBAoTDUVu -dHJ1c3QsIEluYy4xKDAmBgNVBAsTH1NlZSB3d3cuZW50cnVzdC5uZXQvbGVnYWwt -dGVybXMxOTA3BgNVBAsTMChjKSAyMDA5IEVudHJ1c3QsIEluYy4gLSBmb3IgYXV0 -aG9yaXplZCB1c2Ugb25seTEyMDAGA1UEAxMpRW50cnVzdCBSb290IENlcnRpZmlj -YXRpb24gQXV0aG9yaXR5IC0gRzIwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEK -AoIBAQC6hLZy254Ma+KZ6TABp3bqMriVQRrJ2mFOWHLP/vaCeb9zYQYKpSfYs1/T -RU4cctZOMvJyig/3gxnQaoCAAEUesMfnmr8SVycco2gvCoe9amsOXmXzHHfV1IWN -cCG0szLni6LVhjkCsbjSR87kyUnEO6fe+1R9V77w6G7CebI6C1XiUJgWMhNcL3hW -wcKUs/Ja5CeanyTXxuzQmyWC48zCxEXFjJd6BmsqEZ+pCm5IO2/b1BEZQvePB7/1 -U1+cPvQXLOZprE4yTGJ36rfo5bs0vBmLrpxR57d+tVOxMyLlbc9wPBr64ptntoP0 -jaWvYkxN4FisZDQSA/i2jZRjJKRxAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAP -BgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBRqciZ60B7vfec7aVHUbI2fkBJmqzAN -BgkqhkiG9w0BAQsFAAOCAQEAeZ8dlsa2eT8ijYfThwMEYGprmi5ZiXMRrEPR9RP/ -jTkrwPK9T3CMqS/qF8QLVJ7UG5aYMzyorWKiAHarWWluBh1+xLlEjZivEtRh2woZ -Rkfz6/djwUAFQKXSt/S1mja/qYh2iARVBCuch38aNzx+LaUa2NSJXsq9rD1s2G2v -1fN2D807iDginWyTmsQ9v4IbZT+mD12q/OWyFcq1rca8PdCE6OoGcrBNOTJ4vz4R -nAuknZoh8/CbCzB428Hch0P+vGOaysXCHMnHjf87ElgI5rY97HosTvuDls4MPGmH -VHOkc8KT/1EQrBVUAdj8BbGJoX90g5pJ19xOe4pIb4tF9g== ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: 144470 (0x23456) - Signature Algorithm: sha1WithRSAEncryption - Issuer: C=US, O=GeoTrust Inc., CN=GeoTrust Global CA - Validity - Not Before: May 21 04:00:00 2002 GMT - Not After : May 21 04:00:00 2022 GMT - Subject: C=US, O=GeoTrust Inc., CN=GeoTrust Global CA - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (2048 bit) - Modulus: - 00:da:cc:18:63:30:fd:f4:17:23:1a:56:7e:5b:df: - 3c:6c:38:e4:71:b7:78:91:d4:bc:a1:d8:4c:f8:a8: - 43:b6:03:e9:4d:21:07:08:88:da:58:2f:66:39:29: - bd:05:78:8b:9d:38:e8:05:b7:6a:7e:71:a4:e6:c4: - 60:a6:b0:ef:80:e4:89:28:0f:9e:25:d6:ed:83:f3: - ad:a6:91:c7:98:c9:42:18:35:14:9d:ad:98:46:92: - 2e:4f:ca:f1:87:43:c1:16:95:57:2d:50:ef:89:2d: - 80:7a:57:ad:f2:ee:5f:6b:d2:00:8d:b9:14:f8:14: - 15:35:d9:c0:46:a3:7b:72:c8:91:bf:c9:55:2b:cd: - d0:97:3e:9c:26:64:cc:df:ce:83:19:71:ca:4e:e6: - d4:d5:7b:a9:19:cd:55:de:c8:ec:d2:5e:38:53:e5: - 5c:4f:8c:2d:fe:50:23:36:fc:66:e6:cb:8e:a4:39: - 19:00:b7:95:02:39:91:0b:0e:fe:38:2e:d1:1d:05: - 9a:f6:4d:3e:6f:0f:07:1d:af:2c:1e:8f:60:39:e2: - fa:36:53:13:39:d4:5e:26:2b:db:3d:a8:14:bd:32: - eb:18:03:28:52:04:71:e5:ab:33:3d:e1:38:bb:07: - 36:84:62:9c:79:ea:16:30:f4:5f:c0:2b:e8:71:6b: - e4:f9 - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Basic Constraints: critical - CA:TRUE - X509v3 Subject Key Identifier: - C0:7A:98:68:8D:89:FB:AB:05:64:0C:11:7D:AA:7D:65:B8:CA:CC:4E - X509v3 Authority Key Identifier: - keyid:C0:7A:98:68:8D:89:FB:AB:05:64:0C:11:7D:AA:7D:65:B8:CA:CC:4E - - Signature Algorithm: sha1WithRSAEncryption - 35:e3:29:6a:e5:2f:5d:54:8e:29:50:94:9f:99:1a:14:e4:8f: - 78:2a:62:94:a2:27:67:9e:d0:cf:1a:5e:47:e9:c1:b2:a4:cf: - dd:41:1a:05:4e:9b:4b:ee:4a:6f:55:52:b3:24:a1:37:0a:eb: - 64:76:2a:2e:2c:f3:fd:3b:75:90:bf:fa:71:d8:c7:3d:37:d2: - b5:05:95:62:b9:a6:de:89:3d:36:7b:38:77:48:97:ac:a6:20: - 8f:2e:a6:c9:0c:c2:b2:99:45:00:c7:ce:11:51:22:22:e0:a5: - ea:b6:15:48:09:64:ea:5e:4f:74:f7:05:3e:c7:8a:52:0c:db: - 15:b4:bd:6d:9b:e5:c6:b1:54:68:a9:e3:69:90:b6:9a:a5:0f: - b8:b9:3f:20:7d:ae:4a:b5:b8:9c:e4:1d:b6:ab:e6:94:a5:c1: - c7:83:ad:db:f5:27:87:0e:04:6c:d5:ff:dd:a0:5d:ed:87:52: - b7:2b:15:02:ae:39:a6:6a:74:e9:da:c4:e7:bc:4d:34:1e:a9: - 5c:4d:33:5f:92:09:2f:88:66:5d:77:97:c7:1d:76:13:a9:d5: - e5:f1:16:09:11:35:d5:ac:db:24:71:70:2c:98:56:0b:d9:17: - b4:d1:e3:51:2b:5e:75:e8:d5:d0:dc:4f:34:ed:c2:05:66:80: - a1:cb:e6:33 ------BEGIN CERTIFICATE----- -MIIDVDCCAjygAwIBAgIDAjRWMA0GCSqGSIb3DQEBBQUAMEIxCzAJBgNVBAYTAlVT -MRYwFAYDVQQKEw1HZW9UcnVzdCBJbmMuMRswGQYDVQQDExJHZW9UcnVzdCBHbG9i -YWwgQ0EwHhcNMDIwNTIxMDQwMDAwWhcNMjIwNTIxMDQwMDAwWjBCMQswCQYDVQQG -EwJVUzEWMBQGA1UEChMNR2VvVHJ1c3QgSW5jLjEbMBkGA1UEAxMSR2VvVHJ1c3Qg -R2xvYmFsIENBMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA2swYYzD9 -9BcjGlZ+W988bDjkcbd4kdS8odhM+KhDtgPpTSEHCIjaWC9mOSm9BXiLnTjoBbdq -fnGk5sRgprDvgOSJKA+eJdbtg/OtppHHmMlCGDUUna2YRpIuT8rxh0PBFpVXLVDv -iS2Aelet8u5fa9IAjbkU+BQVNdnARqN7csiRv8lVK83Qlz6cJmTM386DGXHKTubU -1XupGc1V3sjs0l44U+VcT4wt/lAjNvxm5suOpDkZALeVAjmRCw7+OC7RHQWa9k0+ -bw8HHa8sHo9gOeL6NlMTOdReJivbPagUvTLrGAMoUgRx5aszPeE4uwc2hGKceeoW -MPRfwCvocWvk+QIDAQABo1MwUTAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBTA -ephojYn7qwVkDBF9qn1luMrMTjAfBgNVHSMEGDAWgBTAephojYn7qwVkDBF9qn1l -uMrMTjANBgkqhkiG9w0BAQUFAAOCAQEANeMpauUvXVSOKVCUn5kaFOSPeCpilKIn -Z57QzxpeR+nBsqTP3UEaBU6bS+5Kb1VSsyShNwrrZHYqLizz/Tt1kL/6cdjHPTfS -tQWVYrmm3ok9Nns4d0iXrKYgjy6myQzCsplFAMfOEVEiIuCl6rYVSAlk6l5PdPcF -PseKUgzbFbS9bZvlxrFUaKnjaZC2mqUPuLk/IH2uSrW4nOQdtqvmlKXBx4Ot2/Un -hw4EbNX/3aBd7YdStysVAq45pmp06drE57xNNB6pXE0zX5IJL4hmXXeXxx12E6nV -5fEWCRE11azbJHFwLJhWC9kXtNHjUStedejV0NxPNO3CBWaAocvmMw== ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: 1 (0x1) - Signature Algorithm: sha1WithRSAEncryption - Issuer: C=US, O=GeoTrust Inc., CN=GeoTrust Global CA 2 - Validity - Not Before: Mar 4 05:00:00 2004 GMT - Not After : Mar 4 05:00:00 2019 GMT - Subject: C=US, O=GeoTrust Inc., CN=GeoTrust Global CA 2 - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (2048 bit) - Modulus: - 00:ef:3c:4d:40:3d:10:df:3b:53:00:e1:67:fe:94: - 60:15:3e:85:88:f1:89:0d:90:c8:28:23:99:05:e8: - 2b:20:9d:c6:f3:60:46:d8:c1:b2:d5:8c:31:d9:dc: - 20:79:24:81:bf:35:32:fc:63:69:db:b1:2a:6b:ee: - 21:58:f2:08:e9:78:cb:6f:cb:fc:16:52:c8:91:c4: - ff:3d:73:de:b1:3e:a7:c2:7d:66:c1:f5:7e:52:24: - 1a:e2:d5:67:91:d0:82:10:d7:78:4b:4f:2b:42:39: - bd:64:2d:40:a0:b0:10:d3:38:48:46:88:a1:0c:bb: - 3a:33:2a:62:98:fb:00:9d:13:59:7f:6f:3b:72:aa: - ee:a6:0f:86:f9:05:61:ea:67:7f:0c:37:96:8b:e6: - 69:16:47:11:c2:27:59:03:b3:a6:60:c2:21:40:56: - fa:a0:c7:7d:3a:13:e3:ec:57:c7:b3:d6:ae:9d:89: - 80:f7:01:e7:2c:f6:96:2b:13:0d:79:2c:d9:c0:e4: - 86:7b:4b:8c:0c:72:82:8a:fb:17:cd:00:6c:3a:13: - 3c:b0:84:87:4b:16:7a:29:b2:4f:db:1d:d4:0b:f3: - 66:37:bd:d8:f6:57:bb:5e:24:7a:b8:3c:8b:b9:fa: - 92:1a:1a:84:9e:d8:74:8f:aa:1b:7f:5e:f4:fe:45: - 22:21 - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Basic Constraints: critical - CA:TRUE - X509v3 Subject Key Identifier: - 71:38:36:F2:02:31:53:47:2B:6E:BA:65:46:A9:10:15:58:20:05:09 - X509v3 Authority Key Identifier: - keyid:71:38:36:F2:02:31:53:47:2B:6E:BA:65:46:A9:10:15:58:20:05:09 - - X509v3 Key Usage: critical - Digital Signature, Certificate Sign, CRL Sign - Signature Algorithm: sha1WithRSAEncryption - 03:f7:b5:2b:ab:5d:10:fc:7b:b2:b2:5e:ac:9b:0e:7e:53:78: - 59:3e:42:04:fe:75:a3:ad:ac:81:4e:d7:02:8b:5e:c4:2d:c8: - 52:76:c7:2c:1f:fc:81:32:98:d1:4b:c6:92:93:33:35:31:2f: - fc:d8:1d:44:dd:e0:81:7f:9d:e9:8b:e1:64:91:62:0b:39:08: - 8c:ac:74:9d:59:d9:7a:59:52:97:11:b9:16:7b:6f:45:d3:96: - d9:31:7d:02:36:0f:9c:3b:6e:cf:2c:0d:03:46:45:eb:a0:f4: - 7f:48:44:c6:08:40:cc:de:1b:70:b5:29:ad:ba:8b:3b:34:65: - 75:1b:71:21:1d:2c:14:0a:b0:96:95:b8:d6:ea:f2:65:fb:29: - ba:4f:ea:91:93:74:69:b6:f2:ff:e1:1a:d0:0c:d1:76:85:cb: - 8a:25:bd:97:5e:2c:6f:15:99:26:e7:b6:29:ff:22:ec:c9:02: - c7:56:00:cd:49:b9:b3:6c:7b:53:04:1a:e2:a8:c9:aa:12:05: - 23:c2:ce:e7:bb:04:02:cc:c0:47:a2:e4:c4:29:2f:5b:45:57: - 89:51:ee:3c:eb:52:08:ff:07:35:1e:9f:35:6a:47:4a:56:98: - d1:5a:85:1f:8c:f5:22:bf:ab:ce:83:f3:e2:22:29:ae:7d:83: - 40:a8:ba:6c ------BEGIN CERTIFICATE----- -MIIDZjCCAk6gAwIBAgIBATANBgkqhkiG9w0BAQUFADBEMQswCQYDVQQGEwJVUzEW -MBQGA1UEChMNR2VvVHJ1c3QgSW5jLjEdMBsGA1UEAxMUR2VvVHJ1c3QgR2xvYmFs -IENBIDIwHhcNMDQwMzA0MDUwMDAwWhcNMTkwMzA0MDUwMDAwWjBEMQswCQYDVQQG -EwJVUzEWMBQGA1UEChMNR2VvVHJ1c3QgSW5jLjEdMBsGA1UEAxMUR2VvVHJ1c3Qg -R2xvYmFsIENBIDIwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDvPE1A -PRDfO1MA4Wf+lGAVPoWI8YkNkMgoI5kF6CsgncbzYEbYwbLVjDHZ3CB5JIG/NTL8 -Y2nbsSpr7iFY8gjpeMtvy/wWUsiRxP89c96xPqfCfWbB9X5SJBri1WeR0IIQ13hL -TytCOb1kLUCgsBDTOEhGiKEMuzozKmKY+wCdE1l/bztyqu6mD4b5BWHqZ38MN5aL -5mkWRxHCJ1kDs6ZgwiFAVvqgx306E+PsV8ez1q6diYD3Aecs9pYrEw15LNnA5IZ7 -S4wMcoKK+xfNAGw6EzywhIdLFnopsk/bHdQL82Y3vdj2V7teJHq4PIu5+pIaGoSe -2HSPqht/XvT+RSIhAgMBAAGjYzBhMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYE -FHE4NvICMVNHK266ZUapEBVYIAUJMB8GA1UdIwQYMBaAFHE4NvICMVNHK266ZUap -EBVYIAUJMA4GA1UdDwEB/wQEAwIBhjANBgkqhkiG9w0BAQUFAAOCAQEAA/e1K6td -EPx7srJerJsOflN4WT5CBP51o62sgU7XAotexC3IUnbHLB/8gTKY0UvGkpMzNTEv -/NgdRN3ggX+d6YvhZJFiCzkIjKx0nVnZellSlxG5FntvRdOW2TF9AjYPnDtuzywN -A0ZF66D0f0hExghAzN4bcLUprbqLOzRldRtxIR0sFAqwlpW41uryZfspuk/qkZN0 -abby/+Ea0AzRdoXLiiW9l14sbxWZJue2Kf8i7MkCx1YAzUm5s2x7UwQa4qjJqhIF -I8LO57sEAszAR6LkxCkvW0VXiVHuPOtSCP8HNR6fNWpHSlaY0VqFH4z1Ir+rzoPz -4iIprn2DQKi6bA== ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: - 18:ac:b5:6a:fd:69:b6:15:3a:63:6c:af:da:fa:c4:a1 - Signature Algorithm: sha1WithRSAEncryption - Issuer: C=US, O=GeoTrust Inc., CN=GeoTrust Primary Certification Authority - Validity - Not Before: Nov 27 00:00:00 2006 GMT - Not After : Jul 16 23:59:59 2036 GMT - Subject: C=US, O=GeoTrust Inc., CN=GeoTrust Primary Certification Authority - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (2048 bit) - Modulus: - 00:be:b8:15:7b:ff:d4:7c:7d:67:ad:83:64:7b:c8: - 42:53:2d:df:f6:84:08:20:61:d6:01:59:6a:9c:44: - 11:af:ef:76:fd:95:7e:ce:61:30:bb:7a:83:5f:02: - bd:01:66:ca:ee:15:8d:6f:a1:30:9c:bd:a1:85:9e: - 94:3a:f3:56:88:00:31:cf:d8:ee:6a:96:02:d9:ed: - 03:8c:fb:75:6d:e7:ea:b8:55:16:05:16:9a:f4:e0: - 5e:b1:88:c0:64:85:5c:15:4d:88:c7:b7:ba:e0:75: - e9:ad:05:3d:9d:c7:89:48:e0:bb:28:c8:03:e1:30: - 93:64:5e:52:c0:59:70:22:35:57:88:8a:f1:95:0a: - 83:d7:bc:31:73:01:34:ed:ef:46:71:e0:6b:02:a8: - 35:72:6b:97:9b:66:e0:cb:1c:79:5f:d8:1a:04:68: - 1e:47:02:e6:9d:60:e2:36:97:01:df:ce:35:92:df: - be:67:c7:6d:77:59:3b:8f:9d:d6:90:15:94:bc:42: - 34:10:c1:39:f9:b1:27:3e:7e:d6:8a:75:c5:b2:af: - 96:d3:a2:de:9b:e4:98:be:7d:e1:e9:81:ad:b6:6f: - fc:d7:0e:da:e0:34:b0:0d:1a:77:e7:e3:08:98:ef: - 58:fa:9c:84:b7:36:af:c2:df:ac:d2:f4:10:06:70: - 71:35 - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Basic Constraints: critical - CA:TRUE - X509v3 Key Usage: critical - Certificate Sign, CRL Sign - X509v3 Subject Key Identifier: - 2C:D5:50:41:97:15:8B:F0:8F:36:61:5B:4A:FB:6B:D9:99:C9:33:92 - Signature Algorithm: sha1WithRSAEncryption - 5a:70:7f:2c:dd:b7:34:4f:f5:86:51:a9:26:be:4b:b8:aa:f1: - 71:0d:dc:61:c7:a0:ea:34:1e:7a:77:0f:04:35:e8:27:8f:6c: - 90:bf:91:16:24:46:3e:4a:4e:ce:2b:16:d5:0b:52:1d:fc:1f: - 67:a2:02:45:31:4f:ce:f3:fa:03:a7:79:9d:53:6a:d9:da:63: - 3a:f8:80:d7:d3:99:e1:a5:e1:be:d4:55:71:98:35:3a:be:93: - ea:ae:ad:42:b2:90:6f:e0:fc:21:4d:35:63:33:89:49:d6:9b: - 4e:ca:c7:e7:4e:09:00:f7:da:c7:ef:99:62:99:77:b6:95:22: - 5e:8a:a0:ab:f4:b8:78:98:ca:38:19:99:c9:72:9e:78:cd:4b: - ac:af:19:a0:73:12:2d:fc:c2:41:ba:81:91:da:16:5a:31:b7: - f9:b4:71:80:12:48:99:72:73:5a:59:53:c1:63:52:33:ed:a7: - c9:d2:39:02:70:fa:e0:b1:42:66:29:aa:9b:51:ed:30:54:22: - 14:5f:d9:ab:1d:c1:e4:94:f0:f8:f5:2b:f7:ea:ca:78:46:d6: - b8:91:fd:a6:0d:2b:1a:14:01:3e:80:f0:42:a0:95:07:5e:6d: - cd:cc:4b:a4:45:8d:ab:12:e8:b3:de:5a:e5:a0:7c:e8:0f:22: - 1d:5a:e9:59 ------BEGIN CERTIFICATE----- -MIIDfDCCAmSgAwIBAgIQGKy1av1pthU6Y2yv2vrEoTANBgkqhkiG9w0BAQUFADBY -MQswCQYDVQQGEwJVUzEWMBQGA1UEChMNR2VvVHJ1c3QgSW5jLjExMC8GA1UEAxMo -R2VvVHJ1c3QgUHJpbWFyeSBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTAeFw0wNjEx -MjcwMDAwMDBaFw0zNjA3MTYyMzU5NTlaMFgxCzAJBgNVBAYTAlVTMRYwFAYDVQQK -Ew1HZW9UcnVzdCBJbmMuMTEwLwYDVQQDEyhHZW9UcnVzdCBQcmltYXJ5IENlcnRp -ZmljYXRpb24gQXV0aG9yaXR5MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKC -AQEAvrgVe//UfH1nrYNke8hCUy3f9oQIIGHWAVlqnEQRr+92/ZV+zmEwu3qDXwK9 -AWbK7hWNb6EwnL2hhZ6UOvNWiAAxz9juapYC2e0DjPt1befquFUWBRaa9OBesYjA -ZIVcFU2Ix7e64HXprQU9nceJSOC7KMgD4TCTZF5SwFlwIjVXiIrxlQqD17wxcwE0 -7e9GceBrAqg1cmuXm2bgyxx5X9gaBGgeRwLmnWDiNpcB3841kt++Z8dtd1k7j53W -kBWUvEI0EME5+bEnPn7WinXFsq+W06Lem+SYvn3h6YGttm/81w7a4DSwDRp35+MI -mO9Y+pyEtzavwt+s0vQQBnBxNQIDAQABo0IwQDAPBgNVHRMBAf8EBTADAQH/MA4G -A1UdDwEB/wQEAwIBBjAdBgNVHQ4EFgQULNVQQZcVi/CPNmFbSvtr2ZnJM5IwDQYJ -KoZIhvcNAQEFBQADggEBAFpwfyzdtzRP9YZRqSa+S7iq8XEN3GHHoOo0Hnp3DwQ1 -6CePbJC/kRYkRj5KTs4rFtULUh38H2eiAkUxT87z+gOneZ1TatnaYzr4gNfTmeGl -4b7UVXGYNTq+k+qurUKykG/g/CFNNWMziUnWm07Kx+dOCQD32sfvmWKZd7aVIl6K -oKv0uHiYyjgZmclynnjNS6yvGaBzEi38wkG6gZHaFloxt/m0cYASSJlyc1pZU8Fj -UjPtp8nSOQJw+uCxQmYpqptR7TBUIhRf2asdweSU8Pj1K/fqynhG1riR/aYNKxoU -AT6A8EKglQdebc3MS6RFjasS6LPeWuWgfOgPIh1a6Vk= ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: - 3c:b2:f4:48:0a:00:e2:fe:eb:24:3b:5e:60:3e:c3:6b - Signature Algorithm: ecdsa-with-SHA384 - Issuer: C=US, O=GeoTrust Inc., OU=(c) 2007 GeoTrust Inc. - For authorized use only, CN=GeoTrust Primary Certification Authority - G2 - Validity - Not Before: Nov 5 00:00:00 2007 GMT - Not After : Jan 18 23:59:59 2038 GMT - Subject: C=US, O=GeoTrust Inc., OU=(c) 2007 GeoTrust Inc. - For authorized use only, CN=GeoTrust Primary Certification Authority - G2 - Subject Public Key Info: - Public Key Algorithm: id-ecPublicKey - Public-Key: (384 bit) - pub: - 04:15:b1:e8:fd:03:15:43:e5:ac:eb:87:37:11:62: - ef:d2:83:36:52:7d:45:57:0b:4a:8d:7b:54:3b:3a: - 6e:5f:15:02:c0:50:a6:cf:25:2f:7d:ca:48:b8:c7: - 50:63:1c:2a:21:08:7c:9a:36:d8:0b:fe:d1:26:c5: - 58:31:30:28:25:f3:5d:5d:a3:b8:b6:a5:b4:92:ed: - 6c:2c:9f:eb:dd:43:89:a2:3c:4b:48:91:1d:50:ec: - 26:df:d6:60:2e:bd:21 - ASN1 OID: secp384r1 - X509v3 extensions: - X509v3 Basic Constraints: critical - CA:TRUE - X509v3 Key Usage: critical - Certificate Sign, CRL Sign - X509v3 Subject Key Identifier: - 15:5F:35:57:51:55:FB:25:B2:AD:03:69:FC:01:A3:FA:BE:11:55:D5 - Signature Algorithm: ecdsa-with-SHA384 - 30:64:02:30:64:96:59:a6:e8:09:de:8b:ba:fa:5a:88:88:f0: - 1f:91:d3:46:a8:f2:4a:4c:02:63:fb:6c:5f:38:db:2e:41:93: - a9:0e:e6:9d:dc:31:1c:b2:a0:a7:18:1c:79:e1:c7:36:02:30: - 3a:56:af:9a:74:6c:f6:fb:83:e0:33:d3:08:5f:a1:9c:c2:5b: - 9f:46:d6:b6:cb:91:06:63:a2:06:e7:33:ac:3e:a8:81:12:d0: - cb:ba:d0:92:0b:b6:9e:96:aa:04:0f:8a ------BEGIN CERTIFICATE----- -MIICrjCCAjWgAwIBAgIQPLL0SAoA4v7rJDteYD7DazAKBggqhkjOPQQDAzCBmDEL -MAkGA1UEBhMCVVMxFjAUBgNVBAoTDUdlb1RydXN0IEluYy4xOTA3BgNVBAsTMChj -KSAyMDA3IEdlb1RydXN0IEluYy4gLSBGb3IgYXV0aG9yaXplZCB1c2Ugb25seTE2 -MDQGA1UEAxMtR2VvVHJ1c3QgUHJpbWFyeSBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0 -eSAtIEcyMB4XDTA3MTEwNTAwMDAwMFoXDTM4MDExODIzNTk1OVowgZgxCzAJBgNV -BAYTAlVTMRYwFAYDVQQKEw1HZW9UcnVzdCBJbmMuMTkwNwYDVQQLEzAoYykgMjAw -NyBHZW9UcnVzdCBJbmMuIC0gRm9yIGF1dGhvcml6ZWQgdXNlIG9ubHkxNjA0BgNV -BAMTLUdlb1RydXN0IFByaW1hcnkgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkgLSBH -MjB2MBAGByqGSM49AgEGBSuBBAAiA2IABBWx6P0DFUPlrOuHNxFi79KDNlJ9RVcL -So17VDs6bl8VAsBQps8lL33KSLjHUGMcKiEIfJo22Av+0SbFWDEwKCXzXV2juLal -tJLtbCyf691DiaI8S0iRHVDsJt/WYC69IaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAO -BgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYEFBVfNVdRVfslsq0DafwBo/q+EVXVMAoG -CCqGSM49BAMDA2cAMGQCMGSWWaboCd6LuvpaiIjwH5HTRqjySkwCY/tsXzjbLkGT -qQ7mndwxHLKgpxgceeHHNgIwOlavmnRs9vuD4DPTCF+hnMJbn0bWtsuRBmOiBucz -rD6ogRLQy7rQkgu2npaqBA+K ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: - 15:ac:6e:94:19:b2:79:4b:41:f6:27:a9:c3:18:0f:1f - Signature Algorithm: sha256WithRSAEncryption - Issuer: C=US, O=GeoTrust Inc., OU=(c) 2008 GeoTrust Inc. - For authorized use only, CN=GeoTrust Primary Certification Authority - G3 - Validity - Not Before: Apr 2 00:00:00 2008 GMT - Not After : Dec 1 23:59:59 2037 GMT - Subject: C=US, O=GeoTrust Inc., OU=(c) 2008 GeoTrust Inc. - For authorized use only, CN=GeoTrust Primary Certification Authority - G3 - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (2048 bit) - Modulus: - 00:dc:e2:5e:62:58:1d:33:57:39:32:33:fa:eb:cb: - 87:8c:a7:d4:4a:dd:06:88:ea:64:8e:31:98:a5:38: - 90:1e:98:cf:2e:63:2b:f0:46:bc:44:b2:89:a1:c0: - 28:0c:49:70:21:95:9f:64:c0:a6:93:12:02:65:26: - 86:c6:a5:89:f0:fa:d7:84:a0:70:af:4f:1a:97:3f: - 06:44:d5:c9:eb:72:10:7d:e4:31:28:fb:1c:61:e6: - 28:07:44:73:92:22:69:a7:03:88:6c:9d:63:c8:52: - da:98:27:e7:08:4c:70:3e:b4:c9:12:c1:c5:67:83: - 5d:33:f3:03:11:ec:6a:d0:53:e2:d1:ba:36:60:94: - 80:bb:61:63:6c:5b:17:7e:df:40:94:1e:ab:0d:c2: - 21:28:70:88:ff:d6:26:6c:6c:60:04:25:4e:55:7e: - 7d:ef:bf:94:48:de:b7:1d:dd:70:8d:05:5f:88:a5: - 9b:f2:c2:ee:ea:d1:40:41:6d:62:38:1d:56:06:c5: - 03:47:51:20:19:fc:7b:10:0b:0e:62:ae:76:55:bf: - 5f:77:be:3e:49:01:53:3d:98:25:03:76:24:5a:1d: - b4:db:89:ea:79:e5:b6:b3:3b:3f:ba:4c:28:41:7f: - 06:ac:6a:8e:c1:d0:f6:05:1d:7d:e6:42:86:e3:a5: - d5:47 - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Basic Constraints: critical - CA:TRUE - X509v3 Key Usage: critical - Certificate Sign, CRL Sign - X509v3 Subject Key Identifier: - C4:79:CA:8E:A1:4E:03:1D:1C:DC:6B:DB:31:5B:94:3E:3F:30:7F:2D - Signature Algorithm: sha256WithRSAEncryption - 2d:c5:13:cf:56:80:7b:7a:78:bd:9f:ae:2c:99:e7:ef:da:df: - 94:5e:09:69:a7:e7:6e:68:8c:bd:72:be:47:a9:0e:97:12:b8: - 4a:f1:64:d3:39:df:25:34:d4:c1:cd:4e:81:f0:0f:04:c4:24: - b3:34:96:c6:a6:aa:30:df:68:61:73:d7:f9:8e:85:89:ef:0e: - 5e:95:28:4a:2a:27:8f:10:8e:2e:7c:86:c4:02:9e:da:0c:77: - 65:0e:44:0d:92:fd:fd:b3:16:36:fa:11:0d:1d:8c:0e:07:89: - 6a:29:56:f7:72:f4:dd:15:9c:77:35:66:57:ab:13:53:d8:8e: - c1:40:c5:d7:13:16:5a:72:c7:b7:69:01:c4:7a:b1:83:01:68: - 7d:8d:41:a1:94:18:c1:25:5c:fc:f0:fe:83:02:87:7c:0d:0d: - cf:2e:08:5c:4a:40:0d:3e:ec:81:61:e6:24:db:ca:e0:0e:2d: - 07:b2:3e:56:dc:8d:f5:41:85:07:48:9b:0c:0b:cb:49:3f:7d: - ec:b7:fd:cb:8d:67:89:1a:ab:ed:bb:1e:a3:00:08:08:17:2a: - 82:5c:31:5d:46:8a:2d:0f:86:9b:74:d9:45:fb:d4:40:b1:7a: - aa:68:2d:86:b2:99:22:e1:c1:2b:c7:9c:f8:f3:5f:a8:82:12: - eb:19:11:2d ------BEGIN CERTIFICATE----- -MIID/jCCAuagAwIBAgIQFaxulBmyeUtB9iepwxgPHzANBgkqhkiG9w0BAQsFADCB -mDELMAkGA1UEBhMCVVMxFjAUBgNVBAoTDUdlb1RydXN0IEluYy4xOTA3BgNVBAsT -MChjKSAyMDA4IEdlb1RydXN0IEluYy4gLSBGb3IgYXV0aG9yaXplZCB1c2Ugb25s -eTE2MDQGA1UEAxMtR2VvVHJ1c3QgUHJpbWFyeSBDZXJ0aWZpY2F0aW9uIEF1dGhv -cml0eSAtIEczMB4XDTA4MDQwMjAwMDAwMFoXDTM3MTIwMTIzNTk1OVowgZgxCzAJ -BgNVBAYTAlVTMRYwFAYDVQQKEw1HZW9UcnVzdCBJbmMuMTkwNwYDVQQLEzAoYykg -MjAwOCBHZW9UcnVzdCBJbmMuIC0gRm9yIGF1dGhvcml6ZWQgdXNlIG9ubHkxNjA0 -BgNVBAMTLUdlb1RydXN0IFByaW1hcnkgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkg -LSBHMzCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBANziXmJYHTNXOTIz -+uvLh4yn1ErdBojqZI4xmKU4kB6Yzy5jK/BGvESyiaHAKAxJcCGVn2TAppMSAmUm -hsalifD614SgcK9PGpc/BkTVyetyEH3kMSj7HGHmKAdEc5IiaacDiGydY8hS2pgn -5whMcD60yRLBxWeDXTPzAxHsatBT4tG6NmCUgLthY2xbF37fQJQeqw3CIShwiP/W -JmxsYAQlTlV+fe+/lEjetx3dcI0FX4ilm/LC7urRQEFtYjgdVgbFA0dRIBn8exAL -DmKudlW/X3e+PkkBUz2YJQN2JFodtNuJ6nnltrM7P7pMKEF/BqxqjsHQ9gUdfeZC -huOl1UcCAwEAAaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYw -HQYDVR0OBBYEFMR5yo6hTgMdHNxr2zFblD4/MH8tMA0GCSqGSIb3DQEBCwUAA4IB -AQAtxRPPVoB7eni9n64smefv2t+UXglpp+duaIy9cr5HqQ6XErhK8WTTOd8lNNTB -zU6B8A8ExCSzNJbGpqow32hhc9f5joWJ7w5elShKKiePEI4ufIbEAp7aDHdlDkQN -kv39sxY2+hENHYwOB4lqKVb3cvTdFZx3NWZXqxNT2I7BQMXXExZacse3aQHEerGD -AWh9jUGhlBjBJVz88P6DAod8DQ3PLghcSkANPuyBYeYk28rgDi0Hsj5W3I31QYUH -SJsMC8tJP33st/3LjWeJGqvtux6jAAgIFyqCXDFdRootD4abdNlF+9RAsXqqaC2G -spki4cErx5z481+oghLrGREt ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: 1 (0x1) - Signature Algorithm: sha1WithRSAEncryption - Issuer: C=US, O=GeoTrust Inc., CN=GeoTrust Universal CA - Validity - Not Before: Mar 4 05:00:00 2004 GMT - Not After : Mar 4 05:00:00 2029 GMT - Subject: C=US, O=GeoTrust Inc., CN=GeoTrust Universal CA - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (4096 bit) - Modulus: - 00:a6:15:55:a0:a3:c6:e0:1f:8c:9d:21:50:d7:c1: - be:2b:5b:b5:a4:9e:a1:d9:72:58:bd:00:1b:4c:bf: - 61:c9:14:1d:45:82:ab:c6:1d:80:d6:3d:eb:10:9c: - 3a:af:6d:24:f8:bc:71:01:9e:06:f5:7c:5f:1e:c1: - 0e:55:ca:83:9a:59:30:ae:19:cb:30:48:95:ed:22: - 37:8d:f4:4a:9a:72:66:3e:ad:95:c0:e0:16:00:e0: - 10:1f:2b:31:0e:d7:94:54:d3:42:33:a0:34:1d:1e: - 45:76:dd:4f:ca:18:37:ec:85:15:7a:19:08:fc:d5: - c7:9c:f0:f2:a9:2e:10:a9:92:e6:3d:58:3d:a9:16: - 68:3c:2f:75:21:18:7f:28:77:a5:e1:61:17:b7:a6: - e9:f8:1e:99:db:73:6e:f4:0a:a2:21:6c:ee:da:aa: - 85:92:66:af:f6:7a:6b:82:da:ba:22:08:35:0f:cf: - 42:f1:35:fa:6a:ee:7e:2b:25:cc:3a:11:e4:6d:af: - 73:b2:76:1d:ad:d0:b2:78:67:1a:a4:39:1c:51:0b: - 67:56:83:fd:38:5d:0d:ce:dd:f0:bb:2b:96:1f:de: - 7b:32:52:fd:1d:bb:b5:06:a1:b2:21:5e:a5:d6:95: - 68:7f:f0:99:9e:dc:45:08:3e:e7:d2:09:0d:35:94: - dd:80:4e:53:97:d7:b5:09:44:20:64:16:17:03:02: - 4c:53:0d:68:de:d5:aa:72:4d:93:6d:82:0e:db:9c: - bd:cf:b4:f3:5c:5d:54:7a:69:09:96:d6:db:11:c1: - 8d:75:a8:b4:cf:39:c8:ce:3c:bc:24:7c:e6:62:ca: - e1:bd:7d:a7:bd:57:65:0b:e4:fe:25:ed:b6:69:10: - dc:28:1a:46:bd:01:1d:d0:97:b5:e1:98:3b:c0:37: - 64:d6:3d:94:ee:0b:e1:f5:28:ae:0b:56:bf:71:8b: - 23:29:41:8e:86:c5:4b:52:7b:d8:71:ab:1f:8a:15: - a6:3b:83:5a:d7:58:01:51:c6:4c:41:d9:7f:d8:41: - 67:72:a2:28:df:60:83:a9:9e:c8:7b:fc:53:73:72: - 59:f5:93:7a:17:76:0e:ce:f7:e5:5c:d9:0b:55:34: - a2:aa:5b:b5:6a:54:e7:13:ca:57:ec:97:6d:f4:5e: - 06:2f:45:8b:58:d4:23:16:92:e4:16:6e:28:63:59: - 30:df:50:01:9c:63:89:1a:9f:db:17:94:82:70:37: - c3:24:9e:9a:47:d6:5a:ca:4e:a8:69:89:72:1f:91: - 6c:db:7e:9e:1b:ad:c7:1f:73:dd:2c:4f:19:65:fd: - 7f:93:40:10:2e:d2:f0:ed:3c:9e:2e:28:3e:69:26: - 33:c5:7b - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Basic Constraints: critical - CA:TRUE - X509v3 Subject Key Identifier: - DA:BB:2E:AA:B0:0C:B8:88:26:51:74:5C:6D:03:D3:C0:D8:8F:7A:D6 - X509v3 Authority Key Identifier: - keyid:DA:BB:2E:AA:B0:0C:B8:88:26:51:74:5C:6D:03:D3:C0:D8:8F:7A:D6 - - X509v3 Key Usage: critical - Digital Signature, Certificate Sign, CRL Sign - Signature Algorithm: sha1WithRSAEncryption - 31:78:e6:c7:b5:df:b8:94:40:c9:71:c4:a8:35:ec:46:1d:c2: - 85:f3:28:58:86:b0:0b:fc:8e:b2:39:8f:44:55:ab:64:84:5c: - 69:a9:d0:9a:38:3c:fa:e5:1f:35:e5:44:e3:80:79:94:68:a4: - bb:c4:9f:3d:e1:34:cd:30:46:8b:54:2b:95:a5:ef:f7:3f:99: - 84:fd:35:e6:cf:31:c6:dc:6a:bf:a7:d7:23:08:e1:98:5e:c3: - 5a:08:76:a9:a6:af:77:2f:b7:60:bd:44:46:6a:ef:97:ff:73: - 95:c1:8e:e8:93:fb:fd:31:b7:ec:57:11:11:45:9b:30:f1:1a: - 88:39:c1:4f:3c:a7:00:d5:c7:fc:ab:6d:80:22:70:a5:0c:e0: - 5d:04:29:02:fb:cb:a0:91:d1:7c:d6:c3:7e:50:d5:9d:58:be: - 41:38:eb:b9:75:3c:15:d9:9b:c9:4a:83:59:c0:da:53:fd:33: - bb:36:18:9b:85:0f:15:dd:ee:2d:ac:76:93:b9:d9:01:8d:48: - 10:a8:fb:f5:38:86:f1:db:0a:c6:bd:84:a3:23:41:de:d6:77: - 6f:85:d4:85:1c:50:e0:ae:51:8a:ba:8d:3e:76:e2:b9:ca:27: - f2:5f:9f:ef:6e:59:0d:06:d8:2b:17:a4:d2:7c:6b:bb:5f:14: - 1a:48:8f:1a:4c:e7:b3:47:1c:8e:4c:45:2b:20:ee:48:df:e7: - dd:09:8e:18:a8:da:40:8d:92:26:11:53:61:73:5d:eb:bd:e7: - c4:4d:29:37:61:eb:ac:39:2d:67:2e:16:d6:f5:00:83:85:a1: - cc:7f:76:c4:7d:e4:b7:4b:66:ef:03:45:60:69:b6:0c:52:96: - 92:84:5e:a6:a3:b5:a4:3e:2b:d9:cc:d8:1b:47:aa:f2:44:da: - 4f:f9:03:e8:f0:14:cb:3f:f3:83:de:d0:c1:54:e3:b7:e8:0a: - 37:4d:8b:20:59:03:30:19:a1:2c:c8:bd:11:1f:df:ae:c9:4a: - c5:f3:27:66:66:86:ac:68:91:ff:d9:e6:53:1c:0f:8b:5c:69: - 65:0a:26:c8:1e:34:c3:5d:51:7b:d7:a9:9c:06:a1:36:dd:d5: - 89:94:bc:d9:e4:2d:0c:5e:09:6c:08:97:7c:a3:3d:7c:93:ff: - 3f:a1:14:a7:cf:b5:5d:eb:db:db:1c:c4:76:df:88:b9:bd:45: - 05:95:1b:ae:fc:46:6a:4c:af:48:e3:ce:ae:0f:d2:7e:eb:e6: - 6c:9c:4f:81:6a:7a:64:ac:bb:3e:d5:e7:cb:76:2e:c5:a7:48: - c1:5c:90:0f:cb:c8:3f:fa:e6:32:e1:8d:1b:6f:a4:e6:8e:d8: - f9:29:48:8a:ce:73:fe:2c ------BEGIN CERTIFICATE----- -MIIFaDCCA1CgAwIBAgIBATANBgkqhkiG9w0BAQUFADBFMQswCQYDVQQGEwJVUzEW -MBQGA1UEChMNR2VvVHJ1c3QgSW5jLjEeMBwGA1UEAxMVR2VvVHJ1c3QgVW5pdmVy -c2FsIENBMB4XDTA0MDMwNDA1MDAwMFoXDTI5MDMwNDA1MDAwMFowRTELMAkGA1UE -BhMCVVMxFjAUBgNVBAoTDUdlb1RydXN0IEluYy4xHjAcBgNVBAMTFUdlb1RydXN0 -IFVuaXZlcnNhbCBDQTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAKYV -VaCjxuAfjJ0hUNfBvitbtaSeodlyWL0AG0y/YckUHUWCq8YdgNY96xCcOq9tJPi8 -cQGeBvV8Xx7BDlXKg5pZMK4ZyzBIle0iN430SppyZj6tlcDgFgDgEB8rMQ7XlFTT -QjOgNB0eRXbdT8oYN+yFFXoZCPzVx5zw8qkuEKmS5j1YPakWaDwvdSEYfyh3peFh -F7em6fgemdtzbvQKoiFs7tqqhZJmr/Z6a4LauiIINQ/PQvE1+mrufislzDoR5G2v -c7J2Ha3QsnhnGqQ5HFELZ1aD/ThdDc7d8Lsrlh/eezJS/R27tQahsiFepdaVaH/w -mZ7cRQg+59IJDTWU3YBOU5fXtQlEIGQWFwMCTFMNaN7VqnJNk22CDtucvc+081xd -VHppCZbW2xHBjXWotM85yM48vCR85mLK4b19p71XZQvk/iXttmkQ3CgaRr0BHdCX -teGYO8A3ZNY9lO4L4fUorgtWv3GLIylBjobFS1J72HGrH4oVpjuDWtdYAVHGTEHZ -f9hBZ3KiKN9gg6meyHv8U3NyWfWTehd2Ds735VzZC1U0oqpbtWpU5xPKV+yXbfRe -Bi9Fi1jUIxaS5BZuKGNZMN9QAZxjiRqf2xeUgnA3wySemkfWWspOqGmJch+RbNt+ -nhutxx9z3SxPGWX9f5NAEC7S8O08ni4oPmkmM8V7AgMBAAGjYzBhMA8GA1UdEwEB -/wQFMAMBAf8wHQYDVR0OBBYEFNq7LqqwDLiIJlF0XG0D08DYj3rWMB8GA1UdIwQY -MBaAFNq7LqqwDLiIJlF0XG0D08DYj3rWMA4GA1UdDwEB/wQEAwIBhjANBgkqhkiG -9w0BAQUFAAOCAgEAMXjmx7XfuJRAyXHEqDXsRh3ChfMoWIawC/yOsjmPRFWrZIRc -aanQmjg8+uUfNeVE44B5lGiku8SfPeE0zTBGi1QrlaXv9z+ZhP015s8xxtxqv6fX -IwjhmF7DWgh2qaavdy+3YL1ERmrvl/9zlcGO6JP7/TG37FcREUWbMPEaiDnBTzyn -ANXH/KttgCJwpQzgXQQpAvvLoJHRfNbDflDVnVi+QTjruXU8FdmbyUqDWcDaU/0z -uzYYm4UPFd3uLax2k7nZAY1IEKj79TiG8dsKxr2EoyNB3tZ3b4XUhRxQ4K5RirqN -Pnbiucon8l+f725ZDQbYKxek0nxru18UGkiPGkzns0ccjkxFKyDuSN/n3QmOGKja -QI2SJhFTYXNd673nxE0pN2HrrDktZy4W1vUAg4WhzH92xH3kt0tm7wNFYGm2DFKW -koRepqO1pD4r2czYG0eq8kTaT/kD6PAUyz/zg97QwVTjt+gKN02LIFkDMBmhLMi9 -ER/frslKxfMnZmaGrGiR/9nmUxwPi1xpZQomyB40w11Re9epnAahNt3ViZS82eQt -DF4JbAiXfKM9fJP/P6EUp8+1Xevb2xzEdt+Iub1FBZUbrvxGakyvSOPOrg/Sfuvm -bJxPgWp6ZKy7PtXny3YuxadIwVyQD8vIP/rmMuGNG2+k5o7Y+SlIis5z/iw= ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: 1 (0x1) - Signature Algorithm: sha1WithRSAEncryption - Issuer: C=US, O=GeoTrust Inc., CN=GeoTrust Universal CA 2 - Validity - Not Before: Mar 4 05:00:00 2004 GMT - Not After : Mar 4 05:00:00 2029 GMT - Subject: C=US, O=GeoTrust Inc., CN=GeoTrust Universal CA 2 - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (4096 bit) - Modulus: - 00:b3:54:52:c1:c9:3e:f2:d9:dc:b1:53:1a:59:29: - e7:b1:c3:45:28:e5:d7:d1:ed:c5:c5:4b:a1:aa:74: - 7b:57:af:4a:26:fc:d8:f5:5e:a7:6e:19:db:74:0c: - 4f:35:5b:32:0b:01:e3:db:eb:7a:77:35:ea:aa:5a: - e0:d6:e8:a1:57:94:f0:90:a3:74:56:94:44:30:03: - 1e:5c:4e:2b:85:26:74:82:7a:0c:76:a0:6f:4d:ce: - 41:2d:a0:15:06:14:5f:b7:42:cd:7b:8f:58:61:34: - dc:2a:08:f9:2e:c3:01:a6:22:44:1c:4c:07:82:e6: - 5b:ce:d0:4a:7c:04:d3:19:73:27:f0:aa:98:7f:2e: - af:4e:eb:87:1e:24:77:6a:5d:b6:e8:5b:45:ba:dc: - c3:a1:05:6f:56:8e:8f:10:26:a5:49:c3:2e:d7:41: - 87:22:e0:4f:86:ca:60:b5:ea:a1:63:c0:01:97:10: - 79:bd:00:3c:12:6d:2b:15:b1:ac:4b:b1:ee:18:b9: - 4e:96:dc:dc:76:ff:3b:be:cf:5f:03:c0:fc:3b:e8: - be:46:1b:ff:da:40:c2:52:f7:fe:e3:3a:f7:6a:77: - 35:d0:da:8d:eb:5e:18:6a:31:c7:1e:ba:3c:1b:28: - d6:6b:54:c6:aa:5b:d7:a2:2c:1b:19:cc:a2:02:f6: - 9b:59:bd:37:6b:86:b5:6d:82:ba:d8:ea:c9:56:bc: - a9:36:58:fd:3e:19:f3:ed:0c:26:a9:93:38:f8:4f: - c1:5d:22:06:d0:97:ea:e1:ad:c6:55:e0:81:2b:28: - 83:3a:fa:f4:7b:21:51:00:be:52:38:ce:cd:66:79: - a8:f4:81:56:e2:d0:83:09:47:51:5b:50:6a:cf:db: - 48:1a:5d:3e:f7:cb:f6:65:f7:6c:f1:95:f8:02:3b: - 32:56:82:39:7a:5b:bd:2f:89:1b:bf:a1:b4:e8:ff: - 7f:8d:8c:df:03:f1:60:4e:58:11:4c:eb:a3:3f:10: - 2b:83:9a:01:73:d9:94:6d:84:00:27:66:ac:f0:70: - 40:09:42:92:ad:4f:93:0d:61:09:51:24:d8:92:d5: - 0b:94:61:b2:87:b2:ed:ff:9a:35:ff:85:54:ca:ed: - 44:43:ac:1b:3c:16:6b:48:4a:0a:1c:40:88:1f:92: - c2:0b:00:05:ff:f2:c8:02:4a:a4:aa:a9:cc:99:96: - 9c:2f:58:e0:7d:e1:be:bb:07:dc:5f:04:72:5c:31: - 34:c3:ec:5f:2d:e0:3d:64:90:22:e6:d1:ec:b8:2e: - dd:59:ae:d9:a1:37:bf:54:35:dc:73:32:4f:8c:04: - 1e:33:b2:c9:46:f1:d8:5c:c8:55:50:c9:68:bd:a8: - ba:36:09 - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Basic Constraints: critical - CA:TRUE - X509v3 Subject Key Identifier: - 76:F3:55:E1:FA:A4:36:FB:F0:9F:5C:62:71:ED:3C:F4:47:38:10:2B - X509v3 Authority Key Identifier: - keyid:76:F3:55:E1:FA:A4:36:FB:F0:9F:5C:62:71:ED:3C:F4:47:38:10:2B - - X509v3 Key Usage: critical - Digital Signature, Certificate Sign, CRL Sign - Signature Algorithm: sha1WithRSAEncryption - 66:c1:c6:23:f3:d9:e0:2e:6e:5f:e8:cf:ae:b0:b0:25:4d:2b: - f8:3b:58:9b:40:24:37:5a:cb:ab:16:49:ff:b3:75:79:33:a1: - 2f:6d:70:17:34:91:fe:67:7e:8f:ec:9b:e5:5e:82:a9:55:1f: - 2f:dc:d4:51:07:12:fe:ac:16:3e:2c:35:c6:63:fc:dc:10:eb: - 0d:a3:aa:d0:7c:cc:d1:d0:2f:51:2e:c4:14:5a:de:e8:19:e1: - 3e:c6:cc:a4:29:e7:2e:84:aa:06:30:78:76:54:73:28:98:59: - 38:e0:00:0d:62:d3:42:7d:21:9f:ae:3d:3a:8c:d5:fa:77:0d: - 18:2b:16:0e:5f:36:e1:fc:2a:b5:30:24:cf:e0:63:0c:7b:58: - 1a:fe:99:ba:42:12:b1:91:f4:7c:68:e2:c8:e8:af:2c:ea:c9: - 7e:ae:bb:2a:3d:0d:15:dc:34:95:b6:18:74:a8:6a:0f:c7:b4: - f4:13:c4:e4:5b:ed:0a:d2:a4:97:4c:2a:ed:2f:6c:12:89:3d: - f1:27:70:aa:6a:03:52:21:9f:40:a8:67:50:f2:f3:5a:1f:df: - df:23:f6:dc:78:4e:e6:98:4f:55:3a:53:e3:ef:f2:f4:9f:c7: - 7c:d8:58:af:29:22:97:b8:e0:bd:91:2e:b0:76:ec:57:11:cf: - ef:29:44:f3:e9:85:7a:60:63:e4:5d:33:89:17:d9:31:aa:da: - d6:f3:18:35:72:cf:87:2b:2f:63:23:84:5d:84:8c:3f:57:a0: - 88:fc:99:91:28:26:69:99:d4:8f:97:44:be:8e:d5:48:b1:a4: - 28:29:f1:15:b4:e1:e5:9e:dd:f8:8f:a6:6f:26:d7:09:3c:3a: - 1c:11:0e:a6:6c:37:f7:ad:44:87:2c:28:c7:d8:74:82:b3:d0: - 6f:4a:57:bb:35:29:27:a0:8b:e8:21:a7:87:64:36:5d:cc:d8: - 16:ac:c7:b2:27:40:92:55:38:28:8d:51:6e:dd:14:67:53:6c: - 71:5c:26:84:4d:75:5a:b6:7e:60:56:a9:4d:ad:fb:9b:1e:97: - f3:0d:d9:d2:97:54:77:da:3d:12:b7:e0:1e:ef:08:06:ac:f9: - 85:87:e9:a2:dc:af:7e:18:12:83:fd:56:17:41:2e:d5:29:82: - 7d:99:f4:31:f6:71:a9:cf:2c:01:27:a5:05:b9:aa:b2:48:4e: - 2a:ef:9f:93:52:51:95:3c:52:73:8e:56:4c:17:40:c0:09:28: - e4:8b:6a:48:53:db:ec:cd:55:55:f1:c6:f8:e9:a2:2c:4c:a6: - d1:26:5f:7e:af:5a:4c:da:1f:a6:f2:1c:2c:7e:ae:02:16:d2: - 56:d0:2f:57:53:47:e8:92 ------BEGIN CERTIFICATE----- -MIIFbDCCA1SgAwIBAgIBATANBgkqhkiG9w0BAQUFADBHMQswCQYDVQQGEwJVUzEW -MBQGA1UEChMNR2VvVHJ1c3QgSW5jLjEgMB4GA1UEAxMXR2VvVHJ1c3QgVW5pdmVy -c2FsIENBIDIwHhcNMDQwMzA0MDUwMDAwWhcNMjkwMzA0MDUwMDAwWjBHMQswCQYD -VQQGEwJVUzEWMBQGA1UEChMNR2VvVHJ1c3QgSW5jLjEgMB4GA1UEAxMXR2VvVHJ1 -c3QgVW5pdmVyc2FsIENBIDIwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoIC -AQCzVFLByT7y2dyxUxpZKeexw0Uo5dfR7cXFS6GqdHtXr0om/Nj1XqduGdt0DE81 -WzILAePb63p3NeqqWuDW6KFXlPCQo3RWlEQwAx5cTiuFJnSCegx2oG9NzkEtoBUG -FF+3Qs17j1hhNNwqCPkuwwGmIkQcTAeC5lvO0Ep8BNMZcyfwqph/Lq9O64ceJHdq -XbboW0W63MOhBW9Wjo8QJqVJwy7XQYci4E+GymC16qFjwAGXEHm9ADwSbSsVsaxL -se4YuU6W3Nx2/zu+z18DwPw76L5GG//aQMJS9/7jOvdqdzXQ2o3rXhhqMcceujwb -KNZrVMaqW9eiLBsZzKIC9ptZvTdrhrVtgrrY6slWvKk2WP0+GfPtDCapkzj4T8Fd -IgbQl+rhrcZV4IErKIM6+vR7IVEAvlI4zs1meaj0gVbi0IMJR1FbUGrP20gaXT73 -y/Zl92zxlfgCOzJWgjl6W70viRu/obTo/3+NjN8D8WBOWBFM66M/ECuDmgFz2ZRt -hAAnZqzwcEAJQpKtT5MNYQlRJNiS1QuUYbKHsu3/mjX/hVTK7URDrBs8FmtISgoc -QIgfksILAAX/8sgCSqSqqcyZlpwvWOB94b67B9xfBHJcMTTD7F8t4D1kkCLm0ey4 -Lt1ZrtmhN79UNdxzMk+MBB4zsslG8dhcyFVQyWi9qLo2CQIDAQABo2MwYTAPBgNV -HRMBAf8EBTADAQH/MB0GA1UdDgQWBBR281Xh+qQ2+/CfXGJx7Tz0RzgQKzAfBgNV -HSMEGDAWgBR281Xh+qQ2+/CfXGJx7Tz0RzgQKzAOBgNVHQ8BAf8EBAMCAYYwDQYJ -KoZIhvcNAQEFBQADggIBAGbBxiPz2eAubl/oz66wsCVNK/g7WJtAJDday6sWSf+z -dXkzoS9tcBc0kf5nfo/sm+VegqlVHy/c1FEHEv6sFj4sNcZj/NwQ6w2jqtB8zNHQ -L1EuxBRa3ugZ4T7GzKQp5y6EqgYweHZUcyiYWTjgAA1i00J9IZ+uPTqM1fp3DRgr -Fg5fNuH8KrUwJM/gYwx7WBr+mbpCErGR9Hxo4sjoryzqyX6uuyo9DRXcNJW2GHSo -ag/HtPQTxORb7QrSpJdMKu0vbBKJPfEncKpqA1Ihn0CoZ1Dy81of398j9tx4TuaY -T1U6U+Pv8vSfx3zYWK8pIpe44L2RLrB27FcRz+8pRPPphXpgY+RdM4kX2TGq2tbz -GDVyz4crL2MjhF2EjD9XoIj8mZEoJmmZ1I+XRL6O1UixpCgp8RW04eWe3fiPpm8m -1wk8OhwRDqZsN/etRIcsKMfYdIKz0G9KV7s1KSegi+ghp4dkNl3M2Basx7InQJJV -OCiNUW7dFGdTbHFcJoRNdVq2fmBWqU2t+5sel/MN2dKXVHfaPRK34B7vCAas+YWH -6aLcr34YEoP9VhdBLtUpgn2Z9DH2canPLAEnpQW5qrJITirvn5NSUZU8UnOOVkwX -QMAJKOSLakhT2+zNVVXxxvjpoixMptEmX36vWkzaH6byHCx+rgIW0lbQL1dTR+iS ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: - 2a:38:a4:1c:96:0a:04:de:42:b2:28:a5:0b:e8:34:98:02 - Signature Algorithm: ecdsa-with-SHA256 - Issuer: OU=GlobalSign ECC Root CA - R4, O=GlobalSign, CN=GlobalSign - Validity - Not Before: Nov 13 00:00:00 2012 GMT - Not After : Jan 19 03:14:07 2038 GMT - Subject: OU=GlobalSign ECC Root CA - R4, O=GlobalSign, CN=GlobalSign - Subject Public Key Info: - Public Key Algorithm: id-ecPublicKey - Public-Key: (256 bit) - pub: - 04:b8:c6:79:d3:8f:6c:25:0e:9f:2e:39:19:1c:03: - a4:ae:9a:e5:39:07:09:16:ca:63:b1:b9:86:f8:8a: - 57:c1:57:ce:42:fa:73:a1:f7:65:42:ff:1e:c1:00: - b2:6e:73:0e:ff:c7:21:e5:18:a4:aa:d9:71:3f:a8: - d4:b9:ce:8c:1d - ASN1 OID: prime256v1 - X509v3 extensions: - X509v3 Key Usage: critical - Certificate Sign, CRL Sign - X509v3 Basic Constraints: critical - CA:TRUE - X509v3 Subject Key Identifier: - 54:B0:7B:AD:45:B8:E2:40:7F:FB:0A:6E:FB:BE:33:C9:3C:A3:84:D5 - Signature Algorithm: ecdsa-with-SHA256 - 30:45:02:21:00:dc:92:a1:a0:13:a6:cf:03:b0:e6:c4:21:97: - 90:fa:14:57:2d:03:ec:ee:3c:d3:6e:ca:a8:6c:76:bc:a2:de: - bb:02:20:27:a8:85:27:35:9b:56:c6:a3:f2:47:d2:b7:6e:1b: - 02:00:17:aa:67:a6:15:91:de:fa:94:ec:7b:0b:f8:9f:84 ------BEGIN CERTIFICATE----- -MIIB4TCCAYegAwIBAgIRKjikHJYKBN5CsiilC+g0mAIwCgYIKoZIzj0EAwIwUDEk -MCIGA1UECxMbR2xvYmFsU2lnbiBFQ0MgUm9vdCBDQSAtIFI0MRMwEQYDVQQKEwpH -bG9iYWxTaWduMRMwEQYDVQQDEwpHbG9iYWxTaWduMB4XDTEyMTExMzAwMDAwMFoX -DTM4MDExOTAzMTQwN1owUDEkMCIGA1UECxMbR2xvYmFsU2lnbiBFQ0MgUm9vdCBD -QSAtIFI0MRMwEQYDVQQKEwpHbG9iYWxTaWduMRMwEQYDVQQDEwpHbG9iYWxTaWdu -MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEuMZ5049sJQ6fLjkZHAOkrprlOQcJ -FspjsbmG+IpXwVfOQvpzofdlQv8ewQCybnMO/8ch5RikqtlxP6jUuc6MHaNCMEAw -DgYDVR0PAQH/BAQDAgEGMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFFSwe61F -uOJAf/sKbvu+M8k8o4TVMAoGCCqGSM49BAMCA0gAMEUCIQDckqGgE6bPA7DmxCGX -kPoUVy0D7O48027KqGx2vKLeuwIgJ6iFJzWbVsaj8kfSt24bAgAXqmemFZHe+pTs -ewv4n4Q= ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: - 60:59:49:e0:26:2e:bb:55:f9:0a:77:8a:71:f9:4a:d8:6c - Signature Algorithm: ecdsa-with-SHA384 - Issuer: OU=GlobalSign ECC Root CA - R5, O=GlobalSign, CN=GlobalSign - Validity - Not Before: Nov 13 00:00:00 2012 GMT - Not After : Jan 19 03:14:07 2038 GMT - Subject: OU=GlobalSign ECC Root CA - R5, O=GlobalSign, CN=GlobalSign - Subject Public Key Info: - Public Key Algorithm: id-ecPublicKey - Public-Key: (384 bit) - pub: - 04:47:45:0e:96:fb:7d:5d:bf:e9:39:d1:21:f8:9f: - 0b:b6:d5:7b:1e:92:3a:48:59:1c:f0:62:31:2d:c0: - 7a:28:fe:1a:a7:5c:b3:b6:cc:97:e7:45:d4:58:fa: - d1:77:6d:43:a2:c0:87:65:34:0a:1f:7a:dd:eb:3c: - 33:a1:c5:9d:4d:a4:6f:41:95:38:7f:c9:1e:84:eb: - d1:9e:49:92:87:94:87:0c:3a:85:4a:66:9f:9d:59: - 93:4d:97:61:06:86:4a - ASN1 OID: secp384r1 - X509v3 extensions: - X509v3 Key Usage: critical - Certificate Sign, CRL Sign - X509v3 Basic Constraints: critical - CA:TRUE - X509v3 Subject Key Identifier: - 3D:E6:29:48:9B:EA:07:CA:21:44:4A:26:DE:6E:DE:D2:83:D0:9F:59 - Signature Algorithm: ecdsa-with-SHA384 - 30:65:02:31:00:e5:69:12:c9:6e:db:c6:31:ba:09:41:e1:97: - f8:fb:fd:9a:e2:7d:12:c9:ed:7c:64:d3:cb:05:25:8b:56:d9: - a0:e7:5e:5d:4e:0b:83:9c:5b:76:29:a0:09:26:21:6a:62:02: - 30:71:d2:b5:8f:5c:ea:3b:e1:78:09:85:a8:75:92:3b:c8:5c: - fd:48:ef:0d:74:22:a8:08:e2:6e:c5:49:ce:c7:0c:bc:a7:61: - 69:f1:f7:3b:e1:2a:cb:f9:2b:f3:66:90:37 ------BEGIN CERTIFICATE----- -MIICHjCCAaSgAwIBAgIRYFlJ4CYuu1X5CneKcflK2GwwCgYIKoZIzj0EAwMwUDEk -MCIGA1UECxMbR2xvYmFsU2lnbiBFQ0MgUm9vdCBDQSAtIFI1MRMwEQYDVQQKEwpH -bG9iYWxTaWduMRMwEQYDVQQDEwpHbG9iYWxTaWduMB4XDTEyMTExMzAwMDAwMFoX -DTM4MDExOTAzMTQwN1owUDEkMCIGA1UECxMbR2xvYmFsU2lnbiBFQ0MgUm9vdCBD -QSAtIFI1MRMwEQYDVQQKEwpHbG9iYWxTaWduMRMwEQYDVQQDEwpHbG9iYWxTaWdu -MHYwEAYHKoZIzj0CAQYFK4EEACIDYgAER0UOlvt9Xb/pOdEh+J8LttV7HpI6SFkc -8GIxLcB6KP4ap1yztsyX50XUWPrRd21DosCHZTQKH3rd6zwzocWdTaRvQZU4f8ke -hOvRnkmSh5SHDDqFSmafnVmTTZdhBoZKo0IwQDAOBgNVHQ8BAf8EBAMCAQYwDwYD -VR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUPeYpSJvqB8ohREom3m7e0oPQn1kwCgYI -KoZIzj0EAwMDaAAwZQIxAOVpEslu28YxuglB4Zf4+/2a4n0Sye18ZNPLBSWLVtmg -515dTguDnFt2KaAJJiFqYgIwcdK1j1zqO+F4CYWodZI7yFz9SO8NdCKoCOJuxUnO -xwy8p2Fp8fc74SrL+SvzZpA3 ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: - 04:00:00:00:00:01:15:4b:5a:c3:94 - Signature Algorithm: sha1WithRSAEncryption - Issuer: C=BE, O=GlobalSign nv-sa, OU=Root CA, CN=GlobalSign Root CA - Validity - Not Before: Sep 1 12:00:00 1998 GMT - Not After : Jan 28 12:00:00 2028 GMT - Subject: C=BE, O=GlobalSign nv-sa, OU=Root CA, CN=GlobalSign Root CA - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (2048 bit) - Modulus: - 00:da:0e:e6:99:8d:ce:a3:e3:4f:8a:7e:fb:f1:8b: - 83:25:6b:ea:48:1f:f1:2a:b0:b9:95:11:04:bd:f0: - 63:d1:e2:67:66:cf:1c:dd:cf:1b:48:2b:ee:8d:89: - 8e:9a:af:29:80:65:ab:e9:c7:2d:12:cb:ab:1c:4c: - 70:07:a1:3d:0a:30:cd:15:8d:4f:f8:dd:d4:8c:50: - 15:1c:ef:50:ee:c4:2e:f7:fc:e9:52:f2:91:7d:e0: - 6d:d5:35:30:8e:5e:43:73:f2:41:e9:d5:6a:e3:b2: - 89:3a:56:39:38:6f:06:3c:88:69:5b:2a:4d:c5:a7: - 54:b8:6c:89:cc:9b:f9:3c:ca:e5:fd:89:f5:12:3c: - 92:78:96:d6:dc:74:6e:93:44:61:d1:8d:c7:46:b2: - 75:0e:86:e8:19:8a:d5:6d:6c:d5:78:16:95:a2:e9: - c8:0a:38:eb:f2:24:13:4f:73:54:93:13:85:3a:1b: - bc:1e:34:b5:8b:05:8c:b9:77:8b:b1:db:1f:20:91: - ab:09:53:6e:90:ce:7b:37:74:b9:70:47:91:22:51: - 63:16:79:ae:b1:ae:41:26:08:c8:19:2b:d1:46:aa: - 48:d6:64:2a:d7:83:34:ff:2c:2a:c1:6c:19:43:4a: - 07:85:e7:d3:7c:f6:21:68:ef:ea:f2:52:9f:7f:93: - 90:cf - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Key Usage: critical - Certificate Sign, CRL Sign - X509v3 Basic Constraints: critical - CA:TRUE - X509v3 Subject Key Identifier: - 60:7B:66:1A:45:0D:97:CA:89:50:2F:7D:04:CD:34:A8:FF:FC:FD:4B - Signature Algorithm: sha1WithRSAEncryption - d6:73:e7:7c:4f:76:d0:8d:bf:ec:ba:a2:be:34:c5:28:32:b5: - 7c:fc:6c:9c:2c:2b:bd:09:9e:53:bf:6b:5e:aa:11:48:b6:e5: - 08:a3:b3:ca:3d:61:4d:d3:46:09:b3:3e:c3:a0:e3:63:55:1b: - f2:ba:ef:ad:39:e1:43:b9:38:a3:e6:2f:8a:26:3b:ef:a0:50: - 56:f9:c6:0a:fd:38:cd:c4:0b:70:51:94:97:98:04:df:c3:5f: - 94:d5:15:c9:14:41:9c:c4:5d:75:64:15:0d:ff:55:30:ec:86: - 8f:ff:0d:ef:2c:b9:63:46:f6:aa:fc:df:bc:69:fd:2e:12:48: - 64:9a:e0:95:f0:a6:ef:29:8f:01:b1:15:b5:0c:1d:a5:fe:69: - 2c:69:24:78:1e:b3:a7:1c:71:62:ee:ca:c8:97:ac:17:5d:8a: - c2:f8:47:86:6e:2a:c4:56:31:95:d0:67:89:85:2b:f9:6c:a6: - 5d:46:9d:0c:aa:82:e4:99:51:dd:70:b7:db:56:3d:61:e4:6a: - e1:5c:d6:f6:fe:3d:de:41:cc:07:ae:63:52:bf:53:53:f4:2b: - e9:c7:fd:b6:f7:82:5f:85:d2:41:18:db:81:b3:04:1c:c5:1f: - a4:80:6f:15:20:c9:de:0c:88:0a:1d:d6:66:55:e2:fc:48:c9: - 29:26:69:e0 ------BEGIN CERTIFICATE----- -MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkG -A1UEBhMCQkUxGTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jv -b3QgQ0ExGzAZBgNVBAMTEkdsb2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAw -MDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNVBAYTAkJFMRkwFwYDVQQKExBHbG9i -YWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYDVQQDExJHbG9iYWxT -aWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDaDuaZ -jc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavp -xy0Sy6scTHAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp -1Wrjsok6Vjk4bwY8iGlbKk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdG -snUOhugZitVtbNV4FpWi6cgKOOvyJBNPc1STE4U6G7weNLWLBYy5d4ux2x8gkasJ -U26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrXgzT/LCrBbBlDSgeF59N8 -9iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNVHRMBAf8E -BTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0B -AQUFAAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOz -yj1hTdNGCbM+w6DjY1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE -38NflNUVyRRBnMRddWQVDf9VMOyGj/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymP -AbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhHhm4qxFYxldBniYUr+WymXUad -DKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveCX4XSQRjbgbME -HMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A== ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: - 04:00:00:00:00:01:0f:86:26:e6:0d - Signature Algorithm: sha1WithRSAEncryption - Issuer: OU=GlobalSign Root CA - R2, O=GlobalSign, CN=GlobalSign - Validity - Not Before: Dec 15 08:00:00 2006 GMT - Not After : Dec 15 08:00:00 2021 GMT - Subject: OU=GlobalSign Root CA - R2, O=GlobalSign, CN=GlobalSign - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (2048 bit) - Modulus: - 00:a6:cf:24:0e:be:2e:6f:28:99:45:42:c4:ab:3e: - 21:54:9b:0b:d3:7f:84:70:fa:12:b3:cb:bf:87:5f: - c6:7f:86:d3:b2:30:5c:d6:fd:ad:f1:7b:dc:e5:f8: - 60:96:09:92:10:f5:d0:53:de:fb:7b:7e:73:88:ac: - 52:88:7b:4a:a6:ca:49:a6:5e:a8:a7:8c:5a:11:bc: - 7a:82:eb:be:8c:e9:b3:ac:96:25:07:97:4a:99:2a: - 07:2f:b4:1e:77:bf:8a:0f:b5:02:7c:1b:96:b8:c5: - b9:3a:2c:bc:d6:12:b9:eb:59:7d:e2:d0:06:86:5f: - 5e:49:6a:b5:39:5e:88:34:ec:bc:78:0c:08:98:84: - 6c:a8:cd:4b:b4:a0:7d:0c:79:4d:f0:b8:2d:cb:21: - ca:d5:6c:5b:7d:e1:a0:29:84:a1:f9:d3:94:49:cb: - 24:62:91:20:bc:dd:0b:d5:d9:cc:f9:ea:27:0a:2b: - 73:91:c6:9d:1b:ac:c8:cb:e8:e0:a0:f4:2f:90:8b: - 4d:fb:b0:36:1b:f6:19:7a:85:e0:6d:f2:61:13:88: - 5c:9f:e0:93:0a:51:97:8a:5a:ce:af:ab:d5:f7:aa: - 09:aa:60:bd:dc:d9:5f:df:72:a9:60:13:5e:00:01: - c9:4a:fa:3f:a4:ea:07:03:21:02:8e:82:ca:03:c2: - 9b:8f - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Key Usage: critical - Certificate Sign, CRL Sign - X509v3 Basic Constraints: critical - CA:TRUE - X509v3 Subject Key Identifier: - 9B:E2:07:57:67:1C:1E:C0:6A:06:DE:59:B4:9A:2D:DF:DC:19:86:2E - X509v3 CRL Distribution Points: - - Full Name: - URI:http://crl.globalsign.net/root-r2.crl - - X509v3 Authority Key Identifier: - keyid:9B:E2:07:57:67:1C:1E:C0:6A:06:DE:59:B4:9A:2D:DF:DC:19:86:2E - - Signature Algorithm: sha1WithRSAEncryption - 99:81:53:87:1c:68:97:86:91:ec:e0:4a:b8:44:0b:ab:81:ac: - 27:4f:d6:c1:b8:1c:43:78:b3:0c:9a:fc:ea:2c:3c:6e:61:1b: - 4d:4b:29:f5:9f:05:1d:26:c1:b8:e9:83:00:62:45:b6:a9:08: - 93:b9:a9:33:4b:18:9a:c2:f8:87:88:4e:db:dd:71:34:1a:c1: - 54:da:46:3f:e0:d3:2a:ab:6d:54:22:f5:3a:62:cd:20:6f:ba: - 29:89:d7:dd:91:ee:d3:5c:a2:3e:a1:5b:41:f5:df:e5:64:43: - 2d:e9:d5:39:ab:d2:a2:df:b7:8b:d0:c0:80:19:1c:45:c0:2d: - 8c:e8:f8:2d:a4:74:56:49:c5:05:b5:4f:15:de:6e:44:78:39: - 87:a8:7e:bb:f3:79:18:91:bb:f4:6f:9d:c1:f0:8c:35:8c:5d: - 01:fb:c3:6d:b9:ef:44:6d:79:46:31:7e:0a:fe:a9:82:c1:ff: - ef:ab:6e:20:c4:50:c9:5f:9d:4d:9b:17:8c:0c:e5:01:c9:a0: - 41:6a:73:53:fa:a5:50:b4:6e:25:0f:fb:4c:18:f4:fd:52:d9: - 8e:69:b1:e8:11:0f:de:88:d8:fb:1d:49:f7:aa:de:95:cf:20: - 78:c2:60:12:db:25:40:8c:6a:fc:7e:42:38:40:64:12:f7:9e: - 81:e1:93:2e ------BEGIN CERTIFICATE----- -MIIDujCCAqKgAwIBAgILBAAAAAABD4Ym5g0wDQYJKoZIhvcNAQEFBQAwTDEgMB4G -A1UECxMXR2xvYmFsU2lnbiBSb290IENBIC0gUjIxEzARBgNVBAoTCkdsb2JhbFNp -Z24xEzARBgNVBAMTCkdsb2JhbFNpZ24wHhcNMDYxMjE1MDgwMDAwWhcNMjExMjE1 -MDgwMDAwWjBMMSAwHgYDVQQLExdHbG9iYWxTaWduIFJvb3QgQ0EgLSBSMjETMBEG -A1UEChMKR2xvYmFsU2lnbjETMBEGA1UEAxMKR2xvYmFsU2lnbjCCASIwDQYJKoZI -hvcNAQEBBQADggEPADCCAQoCggEBAKbPJA6+Lm8omUVCxKs+IVSbC9N/hHD6ErPL -v4dfxn+G07IwXNb9rfF73OX4YJYJkhD10FPe+3t+c4isUoh7SqbKSaZeqKeMWhG8 -eoLrvozps6yWJQeXSpkqBy+0Hne/ig+1AnwblrjFuTosvNYSuetZfeLQBoZfXklq -tTleiDTsvHgMCJiEbKjNS7SgfQx5TfC4LcshytVsW33hoCmEofnTlEnLJGKRILzd -C9XZzPnqJworc5HGnRusyMvo4KD0L5CLTfuwNhv2GXqF4G3yYROIXJ/gkwpRl4pa -zq+r1feqCapgvdzZX99yqWATXgAByUr6P6TqBwMhAo6CygPCm48CAwEAAaOBnDCB -mTAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUm+IH -V2ccHsBqBt5ZtJot39wZhi4wNgYDVR0fBC8wLTAroCmgJ4YlaHR0cDovL2NybC5n -bG9iYWxzaWduLm5ldC9yb290LXIyLmNybDAfBgNVHSMEGDAWgBSb4gdXZxwewGoG -3lm0mi3f3BmGLjANBgkqhkiG9w0BAQUFAAOCAQEAmYFThxxol4aR7OBKuEQLq4Gs -J0/WwbgcQ3izDJr86iw8bmEbTUsp9Z8FHSbBuOmDAGJFtqkIk7mpM0sYmsL4h4hO -291xNBrBVNpGP+DTKqttVCL1OmLNIG+6KYnX3ZHu01yiPqFbQfXf5WRDLenVOavS -ot+3i9DAgBkcRcAtjOj4LaR0VknFBbVPFd5uRHg5h6h+u/N5GJG79G+dwfCMNYxd -AfvDbbnvRG15RjF+Cv6pgsH/76tuIMRQyV+dTZsXjAzlAcmgQWpzU/qlULRuJQ/7 -TBj0/VLZjmmx6BEP3ojY+x1J96relc8geMJgEtslQIxq/H5COEBkEveegeGTLg== ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: - 04:00:00:00:00:01:21:58:53:08:a2 - Signature Algorithm: sha256WithRSAEncryption - Issuer: OU=GlobalSign Root CA - R3, O=GlobalSign, CN=GlobalSign - Validity - Not Before: Mar 18 10:00:00 2009 GMT - Not After : Mar 18 10:00:00 2029 GMT - Subject: OU=GlobalSign Root CA - R3, O=GlobalSign, CN=GlobalSign - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (2048 bit) - Modulus: - 00:cc:25:76:90:79:06:78:22:16:f5:c0:83:b6:84: - ca:28:9e:fd:05:76:11:c5:ad:88:72:fc:46:02:43: - c7:b2:8a:9d:04:5f:24:cb:2e:4b:e1:60:82:46:e1: - 52:ab:0c:81:47:70:6c:dd:64:d1:eb:f5:2c:a3:0f: - 82:3d:0c:2b:ae:97:d7:b6:14:86:10:79:bb:3b:13: - 80:77:8c:08:e1:49:d2:6a:62:2f:1f:5e:fa:96:68: - df:89:27:95:38:9f:06:d7:3e:c9:cb:26:59:0d:73: - de:b0:c8:e9:26:0e:83:15:c6:ef:5b:8b:d2:04:60: - ca:49:a6:28:f6:69:3b:f6:cb:c8:28:91:e5:9d:8a: - 61:57:37:ac:74:14:dc:74:e0:3a:ee:72:2f:2e:9c: - fb:d0:bb:bf:f5:3d:00:e1:06:33:e8:82:2b:ae:53: - a6:3a:16:73:8c:dd:41:0e:20:3a:c0:b4:a7:a1:e9: - b2:4f:90:2e:32:60:e9:57:cb:b9:04:92:68:68:e5: - 38:26:60:75:b2:9f:77:ff:91:14:ef:ae:20:49:fc: - ad:40:15:48:d1:02:31:61:19:5e:b8:97:ef:ad:77: - b7:64:9a:7a:bf:5f:c1:13:ef:9b:62:fb:0d:6c:e0: - 54:69:16:a9:03:da:6e:e9:83:93:71:76:c6:69:85: - 82:17 - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Key Usage: critical - Certificate Sign, CRL Sign - X509v3 Basic Constraints: critical - CA:TRUE - X509v3 Subject Key Identifier: - 8F:F0:4B:7F:A8:2E:45:24:AE:4D:50:FA:63:9A:8B:DE:E2:DD:1B:BC - Signature Algorithm: sha256WithRSAEncryption - 4b:40:db:c0:50:aa:fe:c8:0c:ef:f7:96:54:45:49:bb:96:00: - 09:41:ac:b3:13:86:86:28:07:33:ca:6b:e6:74:b9:ba:00:2d: - ae:a4:0a:d3:f5:f1:f1:0f:8a:bf:73:67:4a:83:c7:44:7b:78: - e0:af:6e:6c:6f:03:29:8e:33:39:45:c3:8e:e4:b9:57:6c:aa: - fc:12:96:ec:53:c6:2d:e4:24:6c:b9:94:63:fb:dc:53:68:67: - 56:3e:83:b8:cf:35:21:c3:c9:68:fe:ce:da:c2:53:aa:cc:90: - 8a:e9:f0:5d:46:8c:95:dd:7a:58:28:1a:2f:1d:de:cd:00:37: - 41:8f:ed:44:6d:d7:53:28:97:7e:f3:67:04:1e:15:d7:8a:96: - b4:d3:de:4c:27:a4:4c:1b:73:73:76:f4:17:99:c2:1f:7a:0e: - e3:2d:08:ad:0a:1c:2c:ff:3c:ab:55:0e:0f:91:7e:36:eb:c3: - 57:49:be:e1:2e:2d:7c:60:8b:c3:41:51:13:23:9d:ce:f7:32: - 6b:94:01:a8:99:e7:2c:33:1f:3a:3b:25:d2:86:40:ce:3b:2c: - 86:78:c9:61:2f:14:ba:ee:db:55:6f:df:84:ee:05:09:4d:bd: - 28:d8:72:ce:d3:62:50:65:1e:eb:92:97:83:31:d9:b3:b5:ca: - 47:58:3f:5f ------BEGIN CERTIFICATE----- -MIIDXzCCAkegAwIBAgILBAAAAAABIVhTCKIwDQYJKoZIhvcNAQELBQAwTDEgMB4G -A1UECxMXR2xvYmFsU2lnbiBSb290IENBIC0gUjMxEzARBgNVBAoTCkdsb2JhbFNp -Z24xEzARBgNVBAMTCkdsb2JhbFNpZ24wHhcNMDkwMzE4MTAwMDAwWhcNMjkwMzE4 -MTAwMDAwWjBMMSAwHgYDVQQLExdHbG9iYWxTaWduIFJvb3QgQ0EgLSBSMzETMBEG -A1UEChMKR2xvYmFsU2lnbjETMBEGA1UEAxMKR2xvYmFsU2lnbjCCASIwDQYJKoZI -hvcNAQEBBQADggEPADCCAQoCggEBAMwldpB5BngiFvXAg7aEyiie/QV2EcWtiHL8 -RgJDx7KKnQRfJMsuS+FggkbhUqsMgUdwbN1k0ev1LKMPgj0MK66X17YUhhB5uzsT -gHeMCOFJ0mpiLx9e+pZo34knlTifBtc+ycsmWQ1z3rDI6SYOgxXG71uL0gRgykmm -KPZpO/bLyCiR5Z2KYVc3rHQU3HTgOu5yLy6c+9C7v/U9AOEGM+iCK65TpjoWc4zd -QQ4gOsC0p6Hpsk+QLjJg6VfLuQSSaGjlOCZgdbKfd/+RFO+uIEn8rUAVSNECMWEZ -XriX7613t2Saer9fwRPvm2L7DWzgVGkWqQPabumDk3F2xmmFghcCAwEAAaNCMEAw -DgYDVR0PAQH/BAQDAgEGMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFI/wS3+o -LkUkrk1Q+mOai97i3Ru8MA0GCSqGSIb3DQEBCwUAA4IBAQBLQNvAUKr+yAzv95ZU -RUm7lgAJQayzE4aGKAczymvmdLm6AC2upArT9fHxD4q/c2dKg8dEe3jgr25sbwMp -jjM5RcOO5LlXbKr8EpbsU8Yt5CRsuZRj+9xTaGdWPoO4zzUhw8lo/s7awlOqzJCK -6fBdRoyV3XpYKBovHd7NADdBj+1EbddTKJd+82cEHhXXipa0095MJ6RMG3NzdvQX -mcIfeg7jLQitChws/zyrVQ4PkX4268NXSb7hLi18YIvDQVETI53O9zJrlAGomecs -Mx86OyXShkDOOyyGeMlhLxS67ttVb9+E7gUJTb0o2HLO02JQZR7rkpeDMdmztcpH -WD9f ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: - c9:cd:d3:e9:d5:7d:23:ce - Signature Algorithm: sha1WithRSAEncryption - Issuer: C=EU, L=Madrid (see current address at www.camerfirma.com/address)/serialNumber=A82743287, O=AC Camerfirma S.A., CN=Global Chambersign Root - 2008 - Validity - Not Before: Aug 1 12:31:40 2008 GMT - Not After : Jul 31 12:31:40 2038 GMT - Subject: C=EU, L=Madrid (see current address at www.camerfirma.com/address)/serialNumber=A82743287, O=AC Camerfirma S.A., CN=Global Chambersign Root - 2008 - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (4096 bit) - Modulus: - 00:c0:df:56:d3:e4:3a:9b:76:45:b4:13:db:ff:c1: - b6:19:8b:37:41:18:95:52:47:eb:17:9d:29:88:8e: - 35:6c:06:32:2e:47:62:f3:49:04:bf:7d:44:36:b1: - 71:cc:bd:5a:09:73:d5:d9:85:44:ff:91:57:25:df: - 5e:36:8e:70:d1:5c:71:43:1d:d9:da:ef:5c:d2:fb: - 1b:bd:3a:b5:cb:ad:a3:cc:44:a7:0d:ae:21:15:3f: - b9:7a:5b:92:75:d8:a4:12:38:89:19:8a:b7:80:d2: - e2:32:6f:56:9c:91:d6:88:10:0b:b3:74:64:92:74: - 60:f3:f6:cf:18:4f:60:b2:23:d0:c7:3b:ce:61:4b: - 99:8f:c2:0c:d0:40:b2:98:dc:0d:a8:4e:a3:b9:0a: - ae:60:a0:ad:45:52:63:ba:66:bd:68:e0:f9:be:1a: - a8:81:bb:1e:41:78:75:d3:c1:fe:00:55:b0:87:54: - e8:27:90:35:1d:4c:33:ad:97:fc:97:2e:98:84:bf: - 2c:c9:a3:bf:d1:98:11:14:ed:63:f8:ca:98:88:58: - 17:99:ed:45:03:97:7e:3c:86:1e:88:8c:be:f2:91: - 84:8f:65:34:d8:00:4c:7d:b7:31:17:5a:29:7a:0a: - 18:24:30:a3:37:b5:7a:a9:01:7d:26:d6:f9:0e:8e: - 59:f1:fd:1b:33:b5:29:3b:17:3b:41:b6:21:dd:d4: - c0:3d:a5:9f:9f:1f:43:50:c9:bb:bc:6c:7a:97:98: - ee:cd:8c:1f:fb:9c:51:ae:8b:70:bd:27:9f:71:c0: - 6b:ac:7d:90:66:e8:d7:5d:3a:0d:b0:d5:c2:8d:d5: - c8:9d:9d:c1:6d:d0:d0:bf:51:e4:e3:f8:c3:38:36: - ae:d6:a7:75:e6:af:84:43:5d:93:92:0c:6a:07:de: - 3b:1d:98:22:d6:ac:c1:35:db:a3:a0:25:ff:72:b5: - 76:1d:de:6d:e9:2c:66:2c:52:84:d0:45:92:ce:1c: - e5:e5:33:1d:dc:07:53:54:a3:aa:82:3b:9a:37:2f: - dc:dd:a0:64:e9:e6:dd:bd:ae:fc:64:85:1d:3c:a7: - c9:06:de:84:ff:6b:e8:6b:1a:3c:c5:a2:b3:42:fb: - 8b:09:3e:5f:08:52:c7:62:c4:d4:05:71:bf:c4:64: - e4:f8:a1:83:e8:3e:12:9b:a8:1e:d4:36:4d:2f:71: - f6:8d:28:f6:83:a9:13:d2:61:c1:91:bb:48:c0:34: - 8f:41:8c:4b:4c:db:69:12:ff:50:94:9c:20:83:59: - 73:ed:7c:a1:f2:f1:fd:dd:f7:49:d3:43:58:a0:56: - 63:ca:3d:3d:e5:35:56:59:e9:0e:ca:20:cc:2b:4b: - 93:29:0f - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Basic Constraints: critical - CA:TRUE, pathlen:12 - X509v3 Subject Key Identifier: - B9:09:CA:9C:1E:DB:D3:6C:3A:6B:AE:ED:54:F1:5B:93:06:35:2E:5E - X509v3 Authority Key Identifier: - keyid:B9:09:CA:9C:1E:DB:D3:6C:3A:6B:AE:ED:54:F1:5B:93:06:35:2E:5E - DirName:/C=EU/L=Madrid (see current address at www.camerfirma.com/address)/serialNumber=A82743287/O=AC Camerfirma S.A./CN=Global Chambersign Root - 2008 - serial:C9:CD:D3:E9:D5:7D:23:CE - - X509v3 Key Usage: critical - Certificate Sign, CRL Sign - X509v3 Certificate Policies: - Policy: X509v3 Any Policy - CPS: http://policy.camerfirma.com - - Signature Algorithm: sha1WithRSAEncryption - 80:88:7f:70:de:92:28:d9:05:94:46:ff:90:57:a9:f1:2f:df: - 1a:0d:6b:fa:7c:0e:1c:49:24:79:27:d8:46:aa:6f:29:59:52: - 88:70:12:ea:dd:3d:f5:9b:53:54:6f:e1:60:a2:a8:09:b9:ec: - eb:59:7c:c6:35:f1:dc:18:e9:f1:67:e5:af:ba:45:e0:09:de: - ca:44:0f:c2:17:0e:77:91:45:7a:33:5f:5f:96:2c:68:8b:c1: - 47:8f:98:9b:3d:c0:ec:cb:f5:d5:82:92:84:35:d1:be:36:38: - 56:72:31:5b:47:2d:aa:17:a4:63:51:eb:0a:01:ad:7f:ec:75: - 9e:cb:a1:1f:f1:7f:12:b1:b9:e4:64:7f:67:d6:23:2a:f4:b8: - 39:5d:98:e8:21:a7:e1:bd:3d:42:1a:74:9a:70:af:68:6c:50: - 5d:49:cf:ff:fb:0e:5d:e6:2c:47:d7:81:3a:59:00:b5:73:6b: - 63:20:f6:31:45:08:39:0e:f4:70:7e:40:70:5a:3f:d0:6b:42: - a9:74:3d:28:2f:02:6d:75:72:95:09:8d:48:63:c6:c6:23:57: - 92:93:5e:35:c1:8d:f9:0a:f7:2c:9d:62:1c:f6:ad:7c:dd:a6: - 31:1e:b6:b1:c7:7e:85:26:fa:a4:6a:b5:da:63:30:d1:ef:93: - 37:b2:66:2f:7d:05:f7:e7:b7:4b:98:94:35:c0:d9:3a:29:c1: - 9d:b2:50:33:1d:4a:a9:5a:a6:c9:03:ef:ed:f4:e7:a8:6e:8a: - b4:57:84:eb:a4:3f:d0:ee:aa:aa:87:5b:63:e8:93:e2:6b:a8: - d4:b8:72:78:6b:1b:ed:39:e4:5d:cb:9b:aa:87:d5:4f:4e:00: - fe:d9:6a:9f:3c:31:0f:28:02:01:7d:98:e8:a7:b0:a2:64:9e: - 79:f8:48:f2:15:a9:cc:e6:c8:44:eb:3f:78:99:f2:7b:71:3e: - 3c:f1:98:a7:c5:18:12:3f:e6:bb:28:33:42:e9:45:0a:7c:6d: - f2:86:79:2f:c5:82:19:7d:09:89:7c:b2:54:76:88:ae:de:c1: - f3:cc:e1:6e:db:31:d6:93:ae:99:a0:ef:25:6a:73:98:89:5b: - 3a:2e:13:88:1e:bf:c0:92:94:34:1b:e3:27:b7:8b:1e:6f:42: - ff:e7:e9:37:9b:50:1d:2d:a2:f9:02:ee:cb:58:58:3a:71:bc: - 68:e3:aa:c1:af:1c:28:1f:a2:dc:23:65:3f:81:ea:ae:99:d3: - d8:30:cf:13:0d:4f:15:c9:84:bc:a7:48:2d:f8:30:23:77:d8: - 46:4b:79:6d:f6:8c:ed:3a:7f:60:11:78:f4:e9:9b:ae:d5:54: - c0:74:80:d1:0b:42:9f:c1 ------BEGIN CERTIFICATE----- -MIIHSTCCBTGgAwIBAgIJAMnN0+nVfSPOMA0GCSqGSIb3DQEBBQUAMIGsMQswCQYD -VQQGEwJFVTFDMEEGA1UEBxM6TWFkcmlkIChzZWUgY3VycmVudCBhZGRyZXNzIGF0 -IHd3dy5jYW1lcmZpcm1hLmNvbS9hZGRyZXNzKTESMBAGA1UEBRMJQTgyNzQzMjg3 -MRswGQYDVQQKExJBQyBDYW1lcmZpcm1hIFMuQS4xJzAlBgNVBAMTHkdsb2JhbCBD -aGFtYmVyc2lnbiBSb290IC0gMjAwODAeFw0wODA4MDExMjMxNDBaFw0zODA3MzEx -MjMxNDBaMIGsMQswCQYDVQQGEwJFVTFDMEEGA1UEBxM6TWFkcmlkIChzZWUgY3Vy -cmVudCBhZGRyZXNzIGF0IHd3dy5jYW1lcmZpcm1hLmNvbS9hZGRyZXNzKTESMBAG -A1UEBRMJQTgyNzQzMjg3MRswGQYDVQQKExJBQyBDYW1lcmZpcm1hIFMuQS4xJzAl -BgNVBAMTHkdsb2JhbCBDaGFtYmVyc2lnbiBSb290IC0gMjAwODCCAiIwDQYJKoZI -hvcNAQEBBQADggIPADCCAgoCggIBAMDfVtPkOpt2RbQT2//BthmLN0EYlVJH6xed -KYiONWwGMi5HYvNJBL99RDaxccy9Wglz1dmFRP+RVyXfXjaOcNFccUMd2drvXNL7 -G706tcuto8xEpw2uIRU/uXpbknXYpBI4iRmKt4DS4jJvVpyR1ogQC7N0ZJJ0YPP2 -zxhPYLIj0Mc7zmFLmY/CDNBAspjcDahOo7kKrmCgrUVSY7pmvWjg+b4aqIG7HkF4 -ddPB/gBVsIdU6CeQNR1MM62X/JcumIS/LMmjv9GYERTtY/jKmIhYF5ntRQOXfjyG -HoiMvvKRhI9lNNgATH23MRdaKXoKGCQwoze1eqkBfSbW+Q6OWfH9GzO1KTsXO0G2 -Id3UwD2ln58fQ1DJu7xsepeY7s2MH/ucUa6LcL0nn3HAa6x9kGbo1106DbDVwo3V -yJ2dwW3Q0L9R5OP4wzg2rtandeavhENdk5IMagfeOx2YItaswTXbo6Al/3K1dh3e -beksZixShNBFks4c5eUzHdwHU1SjqoI7mjcv3N2gZOnm3b2u/GSFHTynyQbehP9r -6GsaPMWis0L7iwk+XwhSx2LE1AVxv8Rk5Pihg+g+EpuoHtQ2TS9x9o0o9oOpE9Jh -wZG7SMA0j0GMS0zbaRL/UJScIINZc+18ofLx/d33SdNDWKBWY8o9PeU1VlnpDsog -zCtLkykPAgMBAAGjggFqMIIBZjASBgNVHRMBAf8ECDAGAQH/AgEMMB0GA1UdDgQW -BBS5CcqcHtvTbDprru1U8VuTBjUuXjCB4QYDVR0jBIHZMIHWgBS5CcqcHtvTbDpr -ru1U8VuTBjUuXqGBsqSBrzCBrDELMAkGA1UEBhMCRVUxQzBBBgNVBAcTOk1hZHJp -ZCAoc2VlIGN1cnJlbnQgYWRkcmVzcyBhdCB3d3cuY2FtZXJmaXJtYS5jb20vYWRk -cmVzcykxEjAQBgNVBAUTCUE4Mjc0MzI4NzEbMBkGA1UEChMSQUMgQ2FtZXJmaXJt -YSBTLkEuMScwJQYDVQQDEx5HbG9iYWwgQ2hhbWJlcnNpZ24gUm9vdCAtIDIwMDiC -CQDJzdPp1X0jzjAOBgNVHQ8BAf8EBAMCAQYwPQYDVR0gBDYwNDAyBgRVHSAAMCow -KAYIKwYBBQUHAgEWHGh0dHA6Ly9wb2xpY3kuY2FtZXJmaXJtYS5jb20wDQYJKoZI -hvcNAQEFBQADggIBAICIf3DekijZBZRG/5BXqfEv3xoNa/p8DhxJJHkn2EaqbylZ -UohwEurdPfWbU1Rv4WCiqAm57OtZfMY18dwY6fFn5a+6ReAJ3spED8IXDneRRXoz -X1+WLGiLwUePmJs9wOzL9dWCkoQ10b42OFZyMVtHLaoXpGNR6woBrX/sdZ7LoR/x -fxKxueRkf2fWIyr0uDldmOghp+G9PUIadJpwr2hsUF1Jz//7Dl3mLEfXgTpZALVz -a2Mg9jFFCDkO9HB+QHBaP9BrQql0PSgvAm11cpUJjUhjxsYjV5KTXjXBjfkK9yyd -Yhz2rXzdpjEetrHHfoUm+qRqtdpjMNHvkzeyZi99Bffnt0uYlDXA2TopwZ2yUDMd -SqlapskD7+3056huirRXhOukP9DuqqqHW2Pok+JrqNS4cnhrG+055F3Lm6qH1U9O -AP7Zap88MQ8oAgF9mOinsKJknnn4SPIVqczmyETrP3iZ8ntxPjzxmKfFGBI/5rso -M0LpRQp8bfKGeS/Fghl9CYl8slR2iK7ewfPM4W7bMdaTrpmg7yVqc5iJWzouE4ge -v8CSlDQb4ye3ix5vQv/n6TebUB0tovkC7stYWDpxvGjjqsGvHCgfotwjZT+B6q6Z -09gwzxMNTxXJhLynSC34MCN32EZLeW32jO06f2ARePTpm67VVMB0gNELQp/B ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: 0 (0x0) - Signature Algorithm: sha1WithRSAEncryption - Issuer: C=US, O=The Go Daddy Group, Inc., OU=Go Daddy Class 2 Certification Authority - Validity - Not Before: Jun 29 17:06:20 2004 GMT - Not After : Jun 29 17:06:20 2034 GMT - Subject: C=US, O=The Go Daddy Group, Inc., OU=Go Daddy Class 2 Certification Authority - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (2048 bit) - Modulus: - 00:de:9d:d7:ea:57:18:49:a1:5b:eb:d7:5f:48:86: - ea:be:dd:ff:e4:ef:67:1c:f4:65:68:b3:57:71:a0: - 5e:77:bb:ed:9b:49:e9:70:80:3d:56:18:63:08:6f: - da:f2:cc:d0:3f:7f:02:54:22:54:10:d8:b2:81:d4: - c0:75:3d:4b:7f:c7:77:c3:3e:78:ab:1a:03:b5:20: - 6b:2f:6a:2b:b1:c5:88:7e:c4:bb:1e:b0:c1:d8:45: - 27:6f:aa:37:58:f7:87:26:d7:d8:2d:f6:a9:17:b7: - 1f:72:36:4e:a6:17:3f:65:98:92:db:2a:6e:5d:a2: - fe:88:e0:0b:de:7f:e5:8d:15:e1:eb:cb:3a:d5:e2: - 12:a2:13:2d:d8:8e:af:5f:12:3d:a0:08:05:08:b6: - 5c:a5:65:38:04:45:99:1e:a3:60:60:74:c5:41:a5: - 72:62:1b:62:c5:1f:6f:5f:1a:42:be:02:51:65:a8: - ae:23:18:6a:fc:78:03:a9:4d:7f:80:c3:fa:ab:5a: - fc:a1:40:a4:ca:19:16:fe:b2:c8:ef:5e:73:0d:ee: - 77:bd:9a:f6:79:98:bc:b1:07:67:a2:15:0d:dd:a0: - 58:c6:44:7b:0a:3e:62:28:5f:ba:41:07:53:58:cf: - 11:7e:38:74:c5:f8:ff:b5:69:90:8f:84:74:ea:97: - 1b:af - Exponent: 3 (0x3) - X509v3 extensions: - X509v3 Subject Key Identifier: - D2:C4:B0:D2:91:D4:4C:11:71:B3:61:CB:3D:A1:FE:DD:A8:6A:D4:E3 - X509v3 Authority Key Identifier: - keyid:D2:C4:B0:D2:91:D4:4C:11:71:B3:61:CB:3D:A1:FE:DD:A8:6A:D4:E3 - DirName:/C=US/O=The Go Daddy Group, Inc./OU=Go Daddy Class 2 Certification Authority - serial:00 - - X509v3 Basic Constraints: - CA:TRUE - Signature Algorithm: sha1WithRSAEncryption - 32:4b:f3:b2:ca:3e:91:fc:12:c6:a1:07:8c:8e:77:a0:33:06: - 14:5c:90:1e:18:f7:08:a6:3d:0a:19:f9:87:80:11:6e:69:e4: - 96:17:30:ff:34:91:63:72:38:ee:cc:1c:01:a3:1d:94:28:a4: - 31:f6:7a:c4:54:d7:f6:e5:31:58:03:a2:cc:ce:62:db:94:45: - 73:b5:bf:45:c9:24:b5:d5:82:02:ad:23:79:69:8d:b8:b6:4d: - ce:cf:4c:ca:33:23:e8:1c:88:aa:9d:8b:41:6e:16:c9:20:e5: - 89:9e:cd:3b:da:70:f7:7e:99:26:20:14:54:25:ab:6e:73:85: - e6:9b:21:9d:0a:6c:82:0e:a8:f8:c2:0c:fa:10:1e:6c:96:ef: - 87:0d:c4:0f:61:8b:ad:ee:83:2b:95:f8:8e:92:84:72:39:eb: - 20:ea:83:ed:83:cd:97:6e:08:bc:eb:4e:26:b6:73:2b:e4:d3: - f6:4c:fe:26:71:e2:61:11:74:4a:ff:57:1a:87:0f:75:48:2e: - cf:51:69:17:a0:02:12:61:95:d5:d1:40:b2:10:4c:ee:c4:ac: - 10:43:a6:a5:9e:0a:d5:95:62:9a:0d:cf:88:82:c5:32:0c:e4: - 2b:9f:45:e6:0d:9f:28:9c:b1:b9:2a:5a:57:ad:37:0f:af:1d: - 7f:db:bd:9f ------BEGIN CERTIFICATE----- -MIIEADCCAuigAwIBAgIBADANBgkqhkiG9w0BAQUFADBjMQswCQYDVQQGEwJVUzEh -MB8GA1UEChMYVGhlIEdvIERhZGR5IEdyb3VwLCBJbmMuMTEwLwYDVQQLEyhHbyBE -YWRkeSBDbGFzcyAyIENlcnRpZmljYXRpb24gQXV0aG9yaXR5MB4XDTA0MDYyOTE3 -MDYyMFoXDTM0MDYyOTE3MDYyMFowYzELMAkGA1UEBhMCVVMxITAfBgNVBAoTGFRo -ZSBHbyBEYWRkeSBHcm91cCwgSW5jLjExMC8GA1UECxMoR28gRGFkZHkgQ2xhc3Mg -MiBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTCCASAwDQYJKoZIhvcNAQEBBQADggEN -ADCCAQgCggEBAN6d1+pXGEmhW+vXX0iG6r7d/+TvZxz0ZWizV3GgXne77ZtJ6XCA -PVYYYwhv2vLM0D9/AlQiVBDYsoHUwHU9S3/Hd8M+eKsaA7Ugay9qK7HFiH7Eux6w -wdhFJ2+qN1j3hybX2C32qRe3H3I2TqYXP2WYktsqbl2i/ojgC95/5Y0V4evLOtXi -EqITLdiOr18SPaAIBQi2XKVlOARFmR6jYGB0xUGlcmIbYsUfb18aQr4CUWWoriMY -avx4A6lNf4DD+qta/KFApMoZFv6yyO9ecw3ud72a9nmYvLEHZ6IVDd2gWMZEewo+ -YihfukEHU1jPEX44dMX4/7VpkI+EdOqXG68CAQOjgcAwgb0wHQYDVR0OBBYEFNLE -sNKR1EwRcbNhyz2h/t2oatTjMIGNBgNVHSMEgYUwgYKAFNLEsNKR1EwRcbNhyz2h -/t2oatTjoWekZTBjMQswCQYDVQQGEwJVUzEhMB8GA1UEChMYVGhlIEdvIERhZGR5 -IEdyb3VwLCBJbmMuMTEwLwYDVQQLEyhHbyBEYWRkeSBDbGFzcyAyIENlcnRpZmlj -YXRpb24gQXV0aG9yaXR5ggEAMAwGA1UdEwQFMAMBAf8wDQYJKoZIhvcNAQEFBQAD -ggEBADJL87LKPpH8EsahB4yOd6AzBhRckB4Y9wimPQoZ+YeAEW5p5JYXMP80kWNy -OO7MHAGjHZQopDH2esRU1/blMVgDoszOYtuURXO1v0XJJLXVggKtI3lpjbi2Tc7P -TMozI+gciKqdi0FuFskg5YmezTvacPd+mSYgFFQlq25zheabIZ0KbIIOqPjCDPoQ -HmyW74cNxA9hi63ugyuV+I6ShHI56yDqg+2DzZduCLzrTia2cyvk0/ZM/iZx4mER -dEr/VxqHD3VILs9RaRegAhJhldXRQLIQTO7ErBBDpqWeCtWVYpoNz4iCxTIM5Cuf -ReYNnyicsbkqWletNw+vHX/bvZ8= ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: 0 (0x0) - Signature Algorithm: sha256WithRSAEncryption - Issuer: C=US, ST=Arizona, L=Scottsdale, O=GoDaddy.com, Inc., CN=Go Daddy Root Certificate Authority - G2 - Validity - Not Before: Sep 1 00:00:00 2009 GMT - Not After : Dec 31 23:59:59 2037 GMT - Subject: C=US, ST=Arizona, L=Scottsdale, O=GoDaddy.com, Inc., CN=Go Daddy Root Certificate Authority - G2 - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (2048 bit) - Modulus: - 00:bf:71:62:08:f1:fa:59:34:f7:1b:c9:18:a3:f7: - 80:49:58:e9:22:83:13:a6:c5:20:43:01:3b:84:f1: - e6:85:49:9f:27:ea:f6:84:1b:4e:a0:b4:db:70:98: - c7:32:01:b1:05:3e:07:4e:ee:f4:fa:4f:2f:59:30: - 22:e7:ab:19:56:6b:e2:80:07:fc:f3:16:75:80:39: - 51:7b:e5:f9:35:b6:74:4e:a9:8d:82:13:e4:b6:3f: - a9:03:83:fa:a2:be:8a:15:6a:7f:de:0b:c3:b6:19: - 14:05:ca:ea:c3:a8:04:94:3b:46:7c:32:0d:f3:00: - 66:22:c8:8d:69:6d:36:8c:11:18:b7:d3:b2:1c:60: - b4:38:fa:02:8c:ce:d3:dd:46:07:de:0a:3e:eb:5d: - 7c:c8:7c:fb:b0:2b:53:a4:92:62:69:51:25:05:61: - 1a:44:81:8c:2c:a9:43:96:23:df:ac:3a:81:9a:0e: - 29:c5:1c:a9:e9:5d:1e:b6:9e:9e:30:0a:39:ce:f1: - 88:80:fb:4b:5d:cc:32:ec:85:62:43:25:34:02:56: - 27:01:91:b4:3b:70:2a:3f:6e:b1:e8:9c:88:01:7d: - 9f:d4:f9:db:53:6d:60:9d:bf:2c:e7:58:ab:b8:5f: - 46:fc:ce:c4:1b:03:3c:09:eb:49:31:5c:69:46:b3: - e0:47 - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Basic Constraints: critical - CA:TRUE - X509v3 Key Usage: critical - Certificate Sign, CRL Sign - X509v3 Subject Key Identifier: - 3A:9A:85:07:10:67:28:B6:EF:F6:BD:05:41:6E:20:C1:94:DA:0F:DE - Signature Algorithm: sha256WithRSAEncryption - 99:db:5d:79:d5:f9:97:59:67:03:61:f1:7e:3b:06:31:75:2d: - a1:20:8e:4f:65:87:b4:f7:a6:9c:bc:d8:e9:2f:d0:db:5a:ee: - cf:74:8c:73:b4:38:42:da:05:7b:f8:02:75:b8:fd:a5:b1:d7: - ae:f6:d7:de:13:cb:53:10:7e:8a:46:d1:97:fa:b7:2e:2b:11: - ab:90:b0:27:80:f9:e8:9f:5a:e9:37:9f:ab:e4:df:6c:b3:85: - 17:9d:3d:d9:24:4f:79:91:35:d6:5f:04:eb:80:83:ab:9a:02: - 2d:b5:10:f4:d8:90:c7:04:73:40:ed:72:25:a0:a9:9f:ec:9e: - ab:68:12:99:57:c6:8f:12:3a:09:a4:bd:44:fd:06:15:37:c1: - 9b:e4:32:a3:ed:38:e8:d8:64:f3:2c:7e:14:fc:02:ea:9f:cd: - ff:07:68:17:db:22:90:38:2d:7a:8d:d1:54:f1:69:e3:5f:33: - ca:7a:3d:7b:0a:e3:ca:7f:5f:39:e5:e2:75:ba:c5:76:18:33: - ce:2c:f0:2f:4c:ad:f7:b1:e7:ce:4f:a8:c4:9b:4a:54:06:c5: - 7f:7d:d5:08:0f:e2:1c:fe:7e:17:b8:ac:5e:f6:d4:16:b2:43: - 09:0c:4d:f6:a7:6b:b4:99:84:65:ca:7a:88:e2:e2:44:be:5c: - f7:ea:1c:f5 ------BEGIN CERTIFICATE----- -MIIDxTCCAq2gAwIBAgIBADANBgkqhkiG9w0BAQsFADCBgzELMAkGA1UEBhMCVVMx -EDAOBgNVBAgTB0FyaXpvbmExEzARBgNVBAcTClNjb3R0c2RhbGUxGjAYBgNVBAoT -EUdvRGFkZHkuY29tLCBJbmMuMTEwLwYDVQQDEyhHbyBEYWRkeSBSb290IENlcnRp -ZmljYXRlIEF1dGhvcml0eSAtIEcyMB4XDTA5MDkwMTAwMDAwMFoXDTM3MTIzMTIz -NTk1OVowgYMxCzAJBgNVBAYTAlVTMRAwDgYDVQQIEwdBcml6b25hMRMwEQYDVQQH -EwpTY290dHNkYWxlMRowGAYDVQQKExFHb0RhZGR5LmNvbSwgSW5jLjExMC8GA1UE -AxMoR28gRGFkZHkgUm9vdCBDZXJ0aWZpY2F0ZSBBdXRob3JpdHkgLSBHMjCCASIw -DQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAL9xYgjx+lk09xvJGKP3gElY6SKD -E6bFIEMBO4Tx5oVJnyfq9oQbTqC023CYxzIBsQU+B07u9PpPL1kwIuerGVZr4oAH -/PMWdYA5UXvl+TW2dE6pjYIT5LY/qQOD+qK+ihVqf94Lw7YZFAXK6sOoBJQ7Rnwy -DfMAZiLIjWltNowRGLfTshxgtDj6AozO091GB94KPutdfMh8+7ArU6SSYmlRJQVh -GkSBjCypQ5Yj36w6gZoOKcUcqeldHraenjAKOc7xiID7S13MMuyFYkMlNAJWJwGR -tDtwKj9useiciAF9n9T521NtYJ2/LOdYq7hfRvzOxBsDPAnrSTFcaUaz4EcCAwEA -AaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYE -FDqahQcQZyi27/a9BUFuIMGU2g/eMA0GCSqGSIb3DQEBCwUAA4IBAQCZ21151fmX -WWcDYfF+OwYxdS2hII5PZYe096acvNjpL9DbWu7PdIxztDhC2gV7+AJ1uP2lsdeu -9tfeE8tTEH6KRtGX+rcuKxGrkLAngPnon1rpN5+r5N9ss4UXnT3ZJE95kTXWXwTr -gIOrmgIttRD02JDHBHNA7XIloKmf7J6raBKZV8aPEjoJpL1E/QYVN8Gb5DKj7Tjo -2GTzLH4U/ALqn83/B2gX2yKQOC16jdFU8WnjXzPKej17CuPKf1855eJ1usV2GDPO -LPAvTK33sefOT6jEm0pUBsV/fdUID+Ic/n4XuKxe9tQWskMJDE32p2u0mYRlynqI -4uJEvlz36hz1 ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: 0 (0x0) - Signature Algorithm: ecdsa-with-SHA256 - Issuer: C=GR, L=Athens, O=Hellenic Academic and Research Institutions Cert. Authority, CN=Hellenic Academic and Research Institutions ECC RootCA 2015 - Validity - Not Before: Jul 7 10:37:12 2015 GMT - Not After : Jun 30 10:37:12 2040 GMT - Subject: C=GR, L=Athens, O=Hellenic Academic and Research Institutions Cert. Authority, CN=Hellenic Academic and Research Institutions ECC RootCA 2015 - Subject Public Key Info: - Public Key Algorithm: id-ecPublicKey - Public-Key: (384 bit) - pub: - 04:92:a0:41:e8:4b:82:84:5c:e2:f8:31:11:99:86: - 64:4e:09:25:2f:9d:41:2f:0a:ae:35:4f:74:95:b2: - 51:64:6b:8d:6b:e6:3f:70:95:f0:05:44:47:a6:72: - 38:50:76:95:02:5a:8e:ae:28:9e:f9:2d:4e:99:ef: - 2c:48:6f:4c:25:29:e8:d1:71:5b:df:1d:c1:75:37: - b4:d7:fa:7b:7a:42:9c:6a:0a:56:5a:7c:69:0b:aa: - 80:09:24:6c:7e:c1:46 - ASN1 OID: secp384r1 - X509v3 extensions: - X509v3 Basic Constraints: critical - CA:TRUE - X509v3 Key Usage: critical - Certificate Sign, CRL Sign - X509v3 Subject Key Identifier: - B4:22:0B:82:99:24:01:0E:9C:BB:E4:0E:FD:BF:FB:97:20:93:99:2A - Signature Algorithm: ecdsa-with-SHA256 - 30:64:02:30:67:ce:16:62:38:a2:ac:62:45:a7:a9:95:24:c0: - 1a:27:9c:32:3b:c0:c0:d5:ba:a9:e7:f8:04:43:53:85:ee:52: - 21:de:9d:f5:25:83:3e:9e:58:4b:2f:d7:67:13:0e:21:02:30: - 05:e1:75:01:de:68:ed:2a:1f:4d:4c:09:08:0d:ec:4b:ad:64: - 17:28:e7:75:ce:45:65:72:21:17:cb:22:41:0e:8c:13:98:38: - 9a:54:6d:9b:ca:e2:7c:ea:02:58:22:91 ------BEGIN CERTIFICATE----- -MIICwzCCAkqgAwIBAgIBADAKBggqhkjOPQQDAjCBqjELMAkGA1UEBhMCR1IxDzAN -BgNVBAcTBkF0aGVuczFEMEIGA1UEChM7SGVsbGVuaWMgQWNhZGVtaWMgYW5kIFJl -c2VhcmNoIEluc3RpdHV0aW9ucyBDZXJ0LiBBdXRob3JpdHkxRDBCBgNVBAMTO0hl -bGxlbmljIEFjYWRlbWljIGFuZCBSZXNlYXJjaCBJbnN0aXR1dGlvbnMgRUNDIFJv -b3RDQSAyMDE1MB4XDTE1MDcwNzEwMzcxMloXDTQwMDYzMDEwMzcxMlowgaoxCzAJ -BgNVBAYTAkdSMQ8wDQYDVQQHEwZBdGhlbnMxRDBCBgNVBAoTO0hlbGxlbmljIEFj -YWRlbWljIGFuZCBSZXNlYXJjaCBJbnN0aXR1dGlvbnMgQ2VydC4gQXV0aG9yaXR5 -MUQwQgYDVQQDEztIZWxsZW5pYyBBY2FkZW1pYyBhbmQgUmVzZWFyY2ggSW5zdGl0 -dXRpb25zIEVDQyBSb290Q0EgMjAxNTB2MBAGByqGSM49AgEGBSuBBAAiA2IABJKg -QehLgoRc4vgxEZmGZE4JJS+dQS8KrjVPdJWyUWRrjWvmP3CV8AVER6ZyOFB2lQJa -jq4onvktTpnvLEhvTCUp6NFxW98dwXU3tNf6e3pCnGoKVlp8aQuqgAkkbH7BRqNC -MEAwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYEFLQi -C4KZJAEOnLvkDv2/+5cgk5kqMAoGCCqGSM49BAMCA2cAMGQCMGfOFmI4oqxiRaep -lSTAGiecMjvAwNW6qef4BENThe5SId6d9SWDPp5YSy/XZxMOIQIwBeF1Ad5o7Sof -TUwJCA3sS61kFyjndc5FZXIhF8siQQ6ME5g4mlRtm8rifOoCWCKR ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: 0 (0x0) - Signature Algorithm: sha1WithRSAEncryption - Issuer: C=GR, O=Hellenic Academic and Research Institutions Cert. Authority, CN=Hellenic Academic and Research Institutions RootCA 2011 - Validity - Not Before: Dec 6 13:49:52 2011 GMT - Not After : Dec 1 13:49:52 2031 GMT - Subject: C=GR, O=Hellenic Academic and Research Institutions Cert. Authority, CN=Hellenic Academic and Research Institutions RootCA 2011 - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (2048 bit) - Modulus: - 00:a9:53:00:e3:2e:a6:f6:8e:fa:60:d8:2d:95:3e: - f8:2c:2a:54:4e:cd:b9:84:61:94:58:4f:8f:3d:8b: - e4:43:f3:75:89:8d:51:e4:c3:37:d2:8a:88:4d:79: - 1e:b7:12:dd:43:78:4a:8a:92:e6:d7:48:d5:0f:a4: - 3a:29:44:35:b8:07:f6:68:1d:55:cd:38:51:f0:8c: - 24:31:85:af:83:c9:7d:e9:77:af:ed:1a:7b:9d:17: - f9:b3:9d:38:50:0f:a6:5a:79:91:80:af:37:ae:a6: - d3:31:fb:b5:26:09:9d:3c:5a:ef:51:c5:2b:df:96: - 5d:eb:32:1e:02:da:70:49:ec:6e:0c:c8:9a:37:8d: - f7:f1:36:60:4b:26:2c:82:9e:d0:78:f3:0d:0f:63: - a4:51:30:e1:f9:2b:27:12:07:d8:ea:bd:18:62:98: - b0:59:37:7d:be:ee:f3:20:51:42:5a:83:ef:93:ba: - 69:15:f1:62:9d:9f:99:39:82:a1:b7:74:2e:8b:d4: - c5:0b:7b:2f:f0:c8:0a:da:3d:79:0a:9a:93:1c:a5: - 28:72:73:91:43:9a:a7:d1:4d:85:84:b9:a9:74:8f: - 14:40:c7:dc:de:ac:41:64:6c:b4:19:9b:02:63:6d: - 24:64:8f:44:b2:25:ea:ce:5d:74:0c:63:32:5c:8d: - 87:e5 - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Basic Constraints: critical - CA:TRUE - X509v3 Key Usage: - Certificate Sign, CRL Sign - X509v3 Subject Key Identifier: - A6:91:42:FD:13:61:4A:23:9E:08:A4:29:E5:D8:13:04:23:EE:41:25 - X509v3 Name Constraints: - Permitted: - DNS:.gr - DNS:.eu - DNS:.edu - DNS:.org - email:.gr - email:.eu - email:.edu - email:.org - - Signature Algorithm: sha1WithRSAEncryption - 1f:ef:79:41:e1:7b:6e:3f:b2:8c:86:37:42:4a:4e:1c:37:1e: - 8d:66:ba:24:81:c9:4f:12:0f:21:c0:03:97:86:25:6d:5d:d3: - 22:29:a8:6c:a2:0d:a9:eb:3d:06:5b:99:3a:c7:cc:c3:9a:34: - 7f:ab:0e:c8:4e:1c:e1:fa:e4:dc:cd:0d:be:bf:24:fe:6c:e7: - 6b:c2:0d:c8:06:9e:4e:8d:61:28:a6:6a:fd:e5:f6:62:ea:18: - 3c:4e:a0:53:9d:b2:3a:9c:eb:a5:9c:91:16:b6:4d:82:e0:0c: - 05:48:a9:6c:f5:cc:f8:cb:9d:49:b4:f0:02:a5:fd:70:03:ed: - 8a:21:a5:ae:13:86:49:c3:33:73:be:87:3b:74:8b:17:45:26: - 4c:16:91:83:fe:67:7d:cd:4d:63:67:fa:f3:03:12:96:78:06: - 8d:b1:67:ed:8e:3f:be:9f:4f:02:f5:b3:09:2f:f3:4c:87:df: - 2a:cb:95:7c:01:cc:ac:36:7a:bf:a2:73:7a:f7:8f:c1:b5:9a: - a1:14:b2:8f:33:9f:0d:ef:22:dc:66:7b:84:bd:45:17:06:3d: - 3c:ca:b9:77:34:8f:ca:ea:cf:3f:31:3e:e3:88:e3:80:49:25: - c8:97:b5:9d:9a:99:4d:b0:3c:f8:4a:00:9b:64:dd:9f:39:4b: - d1:27:d7:b8 ------BEGIN CERTIFICATE----- -MIIEMTCCAxmgAwIBAgIBADANBgkqhkiG9w0BAQUFADCBlTELMAkGA1UEBhMCR1Ix -RDBCBgNVBAoTO0hlbGxlbmljIEFjYWRlbWljIGFuZCBSZXNlYXJjaCBJbnN0aXR1 -dGlvbnMgQ2VydC4gQXV0aG9yaXR5MUAwPgYDVQQDEzdIZWxsZW5pYyBBY2FkZW1p -YyBhbmQgUmVzZWFyY2ggSW5zdGl0dXRpb25zIFJvb3RDQSAyMDExMB4XDTExMTIw -NjEzNDk1MloXDTMxMTIwMTEzNDk1MlowgZUxCzAJBgNVBAYTAkdSMUQwQgYDVQQK -EztIZWxsZW5pYyBBY2FkZW1pYyBhbmQgUmVzZWFyY2ggSW5zdGl0dXRpb25zIENl -cnQuIEF1dGhvcml0eTFAMD4GA1UEAxM3SGVsbGVuaWMgQWNhZGVtaWMgYW5kIFJl -c2VhcmNoIEluc3RpdHV0aW9ucyBSb290Q0EgMjAxMTCCASIwDQYJKoZIhvcNAQEB -BQADggEPADCCAQoCggEBAKlTAOMupvaO+mDYLZU++CwqVE7NuYRhlFhPjz2L5EPz -dYmNUeTDN9KKiE15HrcS3UN4SoqS5tdI1Q+kOilENbgH9mgdVc04UfCMJDGFr4PJ -fel3r+0ae50X+bOdOFAPplp5kYCvN66m0zH7tSYJnTxa71HFK9+WXesyHgLacEns -bgzImjeN9/E2YEsmLIKe0HjzDQ9jpFEw4fkrJxIH2Oq9GGKYsFk3fb7u8yBRQlqD -75O6aRXxYp2fmTmCobd0LovUxQt7L/DICto9eQqakxylKHJzkUOap9FNhYS5qXSP -FEDH3N6sQWRstBmbAmNtJGSPRLIl6s5ddAxjMlyNh+UCAwEAAaOBiTCBhjAPBgNV -HRMBAf8EBTADAQH/MAsGA1UdDwQEAwIBBjAdBgNVHQ4EFgQUppFC/RNhSiOeCKQp -5dgTBCPuQSUwRwYDVR0eBEAwPqA8MAWCAy5ncjAFggMuZXUwBoIELmVkdTAGggQu -b3JnMAWBAy5ncjAFgQMuZXUwBoEELmVkdTAGgQQub3JnMA0GCSqGSIb3DQEBBQUA -A4IBAQAf73lB4XtuP7KMhjdCSk4cNx6NZrokgclPEg8hwAOXhiVtXdMiKahsog2p -6z0GW5k6x8zDmjR/qw7IThzh+uTczQ2+vyT+bOdrwg3IBp5OjWEopmr95fZi6hg8 -TqBTnbI6nOulnJEWtk2C4AwFSKls9cz4y51JtPACpf1wA+2KIaWuE4ZJwzNzvoc7 -dIsXRSZMFpGD/md9zU1jZ/rzAxKWeAaNsWftjj++n08C9bMJL/NMh98qy5V8Acys -Nnq/onN694/BtZqhFLKPM58N7yLcZnuEvUUXBj08yrl3NI/K6s8/MT7jiOOASSXI -l7WdmplNsDz4SgCbZN2fOUvRJ9e4 ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: 0 (0x0) - Signature Algorithm: sha256WithRSAEncryption - Issuer: C=GR, L=Athens, O=Hellenic Academic and Research Institutions Cert. Authority, CN=Hellenic Academic and Research Institutions RootCA 2015 - Validity - Not Before: Jul 7 10:11:21 2015 GMT - Not After : Jun 30 10:11:21 2040 GMT - Subject: C=GR, L=Athens, O=Hellenic Academic and Research Institutions Cert. Authority, CN=Hellenic Academic and Research Institutions RootCA 2015 - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (4096 bit) - Modulus: - 00:c2:f8:a9:3f:1b:89:fc:3c:3c:04:5d:3d:90:36: - b0:91:3a:79:3c:66:5a:ef:6d:39:01:49:1a:b4:b7: - cf:7f:4d:23:53:b7:90:00:e3:13:2a:28:a6:31:f1: - 91:00:e3:28:ec:ae:21:41:ce:1f:da:fd:7d:12:5b: - 01:83:0f:b9:b0:5f:99:e1:f2:12:83:80:4d:06:3e: - df:ac:af:e7:a1:88:6b:31:af:f0:8b:d0:18:33:b8: - db:45:6a:34:f4:02:80:24:28:0a:02:15:95:5e:76: - 2a:0d:99:3a:14:5b:f6:cb:cb:53:bc:13:4d:01:88: - 37:94:25:1b:42:bc:22:d8:8e:a3:96:5e:3a:d9:32: - db:3e:e8:f0:10:65:ed:74:e1:2f:a7:7c:af:27:34: - bb:29:7d:9b:b6:cf:09:c8:e5:d3:0a:fc:88:65:65: - 74:0a:dc:73:1c:5c:cd:40:b1:1c:d4:b6:84:8c:4c: - 50:cf:68:8e:a8:59:ae:c2:27:4e:82:a2:35:dd:14: - f4:1f:ff:b2:77:d5:87:2f:aa:6e:7d:24:27:e7:c6: - cb:26:e6:e5:fe:67:07:63:d8:45:0d:dd:3a:59:65: - 39:58:7a:92:99:72:3d:9c:84:5e:88:21:b8:d5:f4: - 2c:fc:d9:70:52:4f:78:b8:bd:3c:2b:8b:95:98:f5: - b3:d1:68:cf:20:14:7e:4c:5c:5f:e7:8b:e5:f5:35: - 81:19:37:d7:11:08:b7:66:be:d3:4a:ce:83:57:00: - 3a:c3:81:f8:17:cb:92:36:5d:d1:a3:d8:75:1b:e1: - 8b:27:ea:7a:48:41:fd:45:19:06:ad:27:99:4e:c1: - 70:47:dd:b5:9f:81:53:12:e5:b1:8c:48:5d:31:43: - 17:e3:8c:c6:7a:63:96:4b:29:30:4e:84:4e:62:19: - 5e:3c:ce:97:90:a5:7f:01:eb:9d:e0:f8:8b:89:dd: - 25:98:3d:92:b6:7e:ef:d9:f1:51:51:7d:2d:26:c8: - 69:59:61:e0:ac:6a:b8:2a:36:11:04:7a:50:bd:32: - 84:be:2f:dc:72:d5:d7:1d:16:47:e4:47:66:20:3f: - f4:96:c5:af:8e:01:7a:a5:0f:7a:64:f5:0d:18:87: - d9:ae:88:d5:fa:84:c1:3a:c0:69:28:2d:f2:0d:68: - 51:aa:e3:a5:77:c6:a4:90:0e:a1:37:8b:31:23:47: - c1:09:08:eb:6e:f7:78:9b:d7:82:fc:84:20:99:49: - 19:b6:12:46:b1:fb:45:55:16:a9:a3:65:ac:9c:07: - 0f:ea:6b:dc:1f:2e:06:72:ec:86:88:12:e4:2d:db: - 5f:05:2f:e4:f0:03:d3:26:33:e7:80:c2:cd:42:a1: - 17:34:0b - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Basic Constraints: critical - CA:TRUE - X509v3 Key Usage: critical - Certificate Sign, CRL Sign - X509v3 Subject Key Identifier: - 71:15:67:C8:C8:C9:BD:75:5D:72:D0:38:18:6A:9D:F3:71:24:54:0B - Signature Algorithm: sha256WithRSAEncryption - 75:bb:6d:54:4b:aa:10:58:46:34:f2:62:d7:16:36:5d:08:5e: - d5:6c:c8:87:bd:b4:2e:46:f2:31:f8:7c:ea:42:b5:93:16:55: - dc:a1:0c:12:a0:da:61:7e:0f:58:58:73:64:72:c7:e8:45:8e: - dc:a9:f2:26:3f:c6:79:8c:b1:53:08:33:81:b0:56:13:be:e6: - 51:5c:d8:9b:0a:4f:4b:9c:56:53:02:e9:4f:f6:0d:60:ea:4d: - 42:55:e8:7c:1b:21:21:d3:1b:3a:cc:77:f2:b8:90:f1:68:c7: - f9:5a:fe:fa:2d:f4:bf:c9:f5:45:1b:ce:38:10:2a:37:8a:79: - a3:b4:e3:09:6c:85:86:93:ff:89:96:27:78:81:8f:67:e3:46: - 74:54:8e:d9:0d:69:e2:4a:f4:4d:74:03:ff:b2:77:ed:95:67: - 97:e4:b1:c5:ab:bf:6a:23:e8:d4:94:e2:44:28:62:c4:4b:e2: - f0:d8:e2:29:6b:1a:70:7e:24:61:93:7b:4f:03:32:25:0d:45: - 24:2b:96:b4:46:6a:bf:4a:0b:f7:9a:8f:c1:ac:1a:c5:67:f3: - 6f:34:d2:fa:73:63:8c:ef:16:b0:a8:a4:46:2a:f8:eb:12:ec: - 72:b4:ef:f8:2b:7e:8c:52:c0:8b:84:54:f9:2f:3e:e3:55:a8: - dc:66:b1:d9:e1:5f:d8:b3:8c:59:34:59:a4:ab:4f:6c:bb:1f: - 18:db:75:ab:d8:cb:92:cd:94:38:61:0e:07:06:1f:4b:46:10: - f1:15:be:8d:85:5c:3b:4a:2b:81:79:0f:b4:69:9f:49:50:97: - 4d:f7:0e:56:5d:c0:95:6a:c2:36:c3:1b:68:c9:f5:2a:dc:47: - 9a:be:b2:ce:c5:25:e8:fa:03:b9:da:f9:16:6e:91:84:f5:1c: - 28:c8:fc:26:cc:d7:1c:90:56:a7:5f:6f:3a:04:bc:cd:78:89: - 0b:8e:0f:2f:a3:aa:4f:a2:1b:12:3d:16:08:40:0f:f1:46:4c: - d7:aa:7b:08:c1:0a:f5:6d:27:de:02:8f:ca:c3:b5:2b:ca:e9: - eb:c8:21:53:38:a5:cc:3b:d8:77:37:30:a2:4f:d9:6f:d1:f2: - 40:ad:41:7a:17:c5:d6:4a:35:89:b7:41:d5:7c:86:7f:55:4d: - 83:4a:a5:73:20:c0:3a:af:90:f1:9a:24:8e:d9:8e:71:ca:7b: - b8:86:da:b2:8f:99:3e:1d:13:0d:12:11:ee:d4:ab:f0:e9:15: - 76:02:e4:e0:df:aa:20:1e:5b:61:85:64:40:a9:90:97:0d:ad: - 53:d2:5a:1d:87:6a:00:97:65:62:b4:be:6f:6a:a7:f5:2c:42: - ed:32:ad:b6:21:9e:be:bc ------BEGIN CERTIFICATE----- -MIIGCzCCA/OgAwIBAgIBADANBgkqhkiG9w0BAQsFADCBpjELMAkGA1UEBhMCR1Ix -DzANBgNVBAcTBkF0aGVuczFEMEIGA1UEChM7SGVsbGVuaWMgQWNhZGVtaWMgYW5k -IFJlc2VhcmNoIEluc3RpdHV0aW9ucyBDZXJ0LiBBdXRob3JpdHkxQDA+BgNVBAMT -N0hlbGxlbmljIEFjYWRlbWljIGFuZCBSZXNlYXJjaCBJbnN0aXR1dGlvbnMgUm9v -dENBIDIwMTUwHhcNMTUwNzA3MTAxMTIxWhcNNDAwNjMwMTAxMTIxWjCBpjELMAkG -A1UEBhMCR1IxDzANBgNVBAcTBkF0aGVuczFEMEIGA1UEChM7SGVsbGVuaWMgQWNh -ZGVtaWMgYW5kIFJlc2VhcmNoIEluc3RpdHV0aW9ucyBDZXJ0LiBBdXRob3JpdHkx -QDA+BgNVBAMTN0hlbGxlbmljIEFjYWRlbWljIGFuZCBSZXNlYXJjaCBJbnN0aXR1 -dGlvbnMgUm9vdENBIDIwMTUwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoIC -AQDC+Kk/G4n8PDwEXT2QNrCROnk8ZlrvbTkBSRq0t89/TSNTt5AA4xMqKKYx8ZEA -4yjsriFBzh/a/X0SWwGDD7mwX5nh8hKDgE0GPt+sr+ehiGsxr/CL0BgzuNtFajT0 -AoAkKAoCFZVedioNmToUW/bLy1O8E00BiDeUJRtCvCLYjqOWXjrZMts+6PAQZe10 -4S+nfK8nNLspfZu2zwnI5dMK/IhlZXQK3HMcXM1AsRzUtoSMTFDPaI6oWa7CJ06C -ojXdFPQf/7J31Ycvqm59JCfnxssm5uX+Zwdj2EUN3TpZZTlYepKZcj2chF6IIbjV -9Cz82XBST3i4vTwri5WY9bPRaM8gFH5MXF/ni+X1NYEZN9cRCLdmvtNKzoNXADrD -gfgXy5I2XdGj2HUb4Ysn6npIQf1FGQatJ5lOwXBH3bWfgVMS5bGMSF0xQxfjjMZ6 -Y5ZLKTBOhE5iGV48zpeQpX8B653g+IuJ3SWYPZK2fu/Z8VFRfS0myGlZYeCsargq -NhEEelC9MoS+L9xy1dcdFkfkR2YgP/SWxa+OAXqlD3pk9Q0Yh9muiNX6hME6wGko -LfINaFGq46V3xqSQDqE3izEjR8EJCOtu93ib14L8hCCZSRm2Ekax+0VVFqmjZayc -Bw/qa9wfLgZy7IaIEuQt218FL+TwA9MmM+eAws1CoRc0CwIDAQABo0IwQDAPBgNV -HRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIBBjAdBgNVHQ4EFgQUcRVnyMjJvXVd -ctA4GGqd83EkVAswDQYJKoZIhvcNAQELBQADggIBAHW7bVRLqhBYRjTyYtcWNl0I -XtVsyIe9tC5G8jH4fOpCtZMWVdyhDBKg2mF+D1hYc2Ryx+hFjtyp8iY/xnmMsVMI -M4GwVhO+5lFc2JsKT0ucVlMC6U/2DWDqTUJV6HwbISHTGzrMd/K4kPFox/la/vot -9L/J9UUbzjgQKjeKeaO04wlshYaT/4mWJ3iBj2fjRnRUjtkNaeJK9E10A/+yd+2V -Z5fkscWrv2oj6NSU4kQoYsRL4vDY4ilrGnB+JGGTe08DMiUNRSQrlrRGar9KC/ea -j8GsGsVn82800vpzY4zvFrCopEYq+OsS7HK07/grfoxSwIuEVPkvPuNVqNxmsdnh -X9izjFk0WaSrT2y7HxjbdavYy5LNlDhhDgcGH0tGEPEVvo2FXDtKK4F5D7Rpn0lQ -l033DlZdwJVqwjbDG2jJ9SrcR5q+ss7FJej6A7na+RZukYT1HCjI/CbM1xyQVqdf -bzoEvM14iQuODy+jqk+iGxI9FghAD/FGTNeqewjBCvVtJ94Cj8rDtSvK6evIIVM4 -pcw72Hc3MKJP2W/R8kCtQXoXxdZKNYm3QdV8hn9VTYNKpXMgwDqvkPGaJI7ZjnHK -e7iG2rKPmT4dEw0SEe7Uq/DpFXYC5ODfqiAeW2GFZECpkJcNrVPSWh2HagCXZWK0 -vm9qp/UsQu0yrbYhnr68 ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: 1000 (0x3e8) - Signature Algorithm: sha1WithRSAEncryption - Issuer: C=HK, O=Hongkong Post, CN=Hongkong Post Root CA 1 - Validity - Not Before: May 15 05:13:14 2003 GMT - Not After : May 15 04:52:29 2023 GMT - Subject: C=HK, O=Hongkong Post, CN=Hongkong Post Root CA 1 - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (2048 bit) - Modulus: - 00:ac:ff:38:b6:e9:66:02:49:e3:a2:b4:e1:90:f9: - 40:8f:79:f9:e2:bd:79:fe:02:bd:ee:24:92:1d:22: - f6:da:85:72:69:fe:d7:3f:09:d4:dd:91:b5:02:9c: - d0:8d:5a:e1:55:c3:50:86:b9:29:26:c2:e3:d9:a0: - f1:69:03:28:20:80:45:22:2d:56:a7:3b:54:95:56: - 22:59:1f:28:df:1f:20:3d:6d:a2:36:be:23:a0:b1: - 6e:b5:b1:27:3f:39:53:09:ea:ab:6a:e8:74:b2:c2: - 65:5c:8e:bf:7c:c3:78:84:cd:9e:16:fc:f5:2e:4f: - 20:2a:08:9f:77:f3:c5:1e:c4:9a:52:66:1e:48:5e: - e3:10:06:8f:22:98:e1:65:8e:1b:5d:23:66:3b:b8: - a5:32:51:c8:86:aa:a1:a9:9e:7f:76:94:c2:a6:6c: - b7:41:f0:d5:c8:06:38:e6:d4:0c:e2:f3:3b:4c:6d: - 50:8c:c4:83:27:c1:13:84:59:3d:9e:75:74:b6:d8: - 02:5e:3a:90:7a:c0:42:36:72:ec:6a:4d:dc:ef:c4: - 00:df:13:18:57:5f:26:78:c8:d6:0a:79:77:bf:f7: - af:b7:76:b9:a5:0b:84:17:5d:10:ea:6f:e1:ab:95: - 11:5f:6d:3c:a3:5c:4d:83:5b:f2:b3:19:8a:80:8b: - 0b:87 - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Basic Constraints: critical - CA:TRUE, pathlen:3 - X509v3 Key Usage: critical - Digital Signature, Non Repudiation, Certificate Sign, CRL Sign - Signature Algorithm: sha1WithRSAEncryption - 0e:46:d5:3c:ae:e2:87:d9:5e:81:8b:02:98:41:08:8c:4c:bc: - da:db:ee:27:1b:82:e7:6a:45:ec:16:8b:4f:85:a0:f3:b2:70: - bd:5a:96:ba:ca:6e:6d:ee:46:8b:6e:e7:2a:2e:96:b3:19:33: - eb:b4:9f:a8:b2:37:ee:98:a8:97:b6:2e:b6:67:27:d4:a6:49: - fd:1c:93:65:76:9e:42:2f:dc:22:6c:9a:4f:f2:5a:15:39:b1: - 71:d7:2b:51:e8:6d:1c:98:c0:d9:2a:f4:a1:82:7b:d5:c9:41: - a2:23:01:74:38:55:8b:0f:b9:2e:67:a2:20:04:37:da:9c:0b: - d3:17:21:e0:8f:97:79:34:6f:84:48:02:20:33:1b:e6:34:44: - 9f:91:70:f4:80:5e:84:43:c2:29:d2:6c:12:14:e4:61:8d:ac: - 10:90:9e:84:50:bb:f0:96:6f:45:9f:8a:f3:ca:6c:4f:fa:11: - 3a:15:15:46:c3:cd:1f:83:5b:2d:41:12:ed:50:67:41:13:3d: - 21:ab:94:8a:aa:4e:7c:c1:b1:fb:a7:d6:b5:27:2f:97:ab:6e: - e0:1d:e2:d1:1c:2c:1f:44:e2:fc:be:91:a1:9c:fb:d6:29:53: - 73:86:9f:53:d8:43:0e:5d:d6:63:82:71:1d:80:74:ca:f6:e2: - 02:6b:d9:5a ------BEGIN CERTIFICATE----- -MIIDMDCCAhigAwIBAgICA+gwDQYJKoZIhvcNAQEFBQAwRzELMAkGA1UEBhMCSEsx -FjAUBgNVBAoTDUhvbmdrb25nIFBvc3QxIDAeBgNVBAMTF0hvbmdrb25nIFBvc3Qg -Um9vdCBDQSAxMB4XDTAzMDUxNTA1MTMxNFoXDTIzMDUxNTA0NTIyOVowRzELMAkG -A1UEBhMCSEsxFjAUBgNVBAoTDUhvbmdrb25nIFBvc3QxIDAeBgNVBAMTF0hvbmdr -b25nIFBvc3QgUm9vdCBDQSAxMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKC -AQEArP84tulmAknjorThkPlAj3n54r15/gK97iSSHSL22oVyaf7XPwnU3ZG1ApzQ -jVrhVcNQhrkpJsLj2aDxaQMoIIBFIi1WpztUlVYiWR8o3x8gPW2iNr4joLFutbEn -PzlTCeqrauh0ssJlXI6/fMN4hM2eFvz1Lk8gKgifd/PFHsSaUmYeSF7jEAaPIpjh -ZY4bXSNmO7ilMlHIhqqhqZ5/dpTCpmy3QfDVyAY45tQM4vM7TG1QjMSDJ8EThFk9 -nnV0ttgCXjqQesBCNnLsak3c78QA3xMYV18meMjWCnl3v/evt3a5pQuEF10Q6m/h -q5URX208o1xNg1vysxmKgIsLhwIDAQABoyYwJDASBgNVHRMBAf8ECDAGAQH/AgED -MA4GA1UdDwEB/wQEAwIBxjANBgkqhkiG9w0BAQUFAAOCAQEADkbVPK7ih9legYsC -mEEIjEy82tvuJxuC52pF7BaLT4Wg87JwvVqWuspube5Gi27nKi6Wsxkz67SfqLI3 -7piol7Yutmcn1KZJ/RyTZXaeQi/cImyaT/JaFTmxcdcrUehtHJjA2Sr0oYJ71clB -oiMBdDhViw+5LmeiIAQ32pwL0xch4I+XeTRvhEgCIDMb5jREn5Fw9IBehEPCKdJs -EhTkYY2sEJCehFC78JZvRZ+K88psT/oROhUVRsPNH4NbLUES7VBnQRM9IauUiqpO -fMGx+6fWtScvl6tu4B3i0RwsH0Ti/L6RoZz71ilTc4afU9hDDl3WY4JxHYB0yvbi -AmvZWg== ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: - 82:10:cf:b0:d2:40:e3:59:44:63:e0:bb:63:82:8b:00 - Signature Algorithm: sha256WithRSAEncryption - Issuer: C=US, O=Internet Security Research Group, CN=ISRG Root X1 - Validity - Not Before: Jun 4 11:04:38 2015 GMT - Not After : Jun 4 11:04:38 2035 GMT - Subject: C=US, O=Internet Security Research Group, CN=ISRG Root X1 - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (4096 bit) - Modulus: - 00:ad:e8:24:73:f4:14:37:f3:9b:9e:2b:57:28:1c: - 87:be:dc:b7:df:38:90:8c:6e:3c:e6:57:a0:78:f7: - 75:c2:a2:fe:f5:6a:6e:f6:00:4f:28:db:de:68:86: - 6c:44:93:b6:b1:63:fd:14:12:6b:bf:1f:d2:ea:31: - 9b:21:7e:d1:33:3c:ba:48:f5:dd:79:df:b3:b8:ff: - 12:f1:21:9a:4b:c1:8a:86:71:69:4a:66:66:6c:8f: - 7e:3c:70:bf:ad:29:22:06:f3:e4:c0:e6:80:ae:e2: - 4b:8f:b7:99:7e:94:03:9f:d3:47:97:7c:99:48:23: - 53:e8:38:ae:4f:0a:6f:83:2e:d1:49:57:8c:80:74: - b6:da:2f:d0:38:8d:7b:03:70:21:1b:75:f2:30:3c: - fa:8f:ae:dd:da:63:ab:eb:16:4f:c2:8e:11:4b:7e: - cf:0b:e8:ff:b5:77:2e:f4:b2:7b:4a:e0:4c:12:25: - 0c:70:8d:03:29:a0:e1:53:24:ec:13:d9:ee:19:bf: - 10:b3:4a:8c:3f:89:a3:61:51:de:ac:87:07:94:f4: - 63:71:ec:2e:e2:6f:5b:98:81:e1:89:5c:34:79:6c: - 76:ef:3b:90:62:79:e6:db:a4:9a:2f:26:c5:d0:10: - e1:0e:de:d9:10:8e:16:fb:b7:f7:a8:f7:c7:e5:02: - 07:98:8f:36:08:95:e7:e2:37:96:0d:36:75:9e:fb: - 0e:72:b1:1d:9b:bc:03:f9:49:05:d8:81:dd:05:b4: - 2a:d6:41:e9:ac:01:76:95:0a:0f:d8:df:d5:bd:12: - 1f:35:2f:28:17:6c:d2:98:c1:a8:09:64:77:6e:47: - 37:ba:ce:ac:59:5e:68:9d:7f:72:d6:89:c5:06:41: - 29:3e:59:3e:dd:26:f5:24:c9:11:a7:5a:a3:4c:40: - 1f:46:a1:99:b5:a7:3a:51:6e:86:3b:9e:7d:72:a7: - 12:05:78:59:ed:3e:51:78:15:0b:03:8f:8d:d0:2f: - 05:b2:3e:7b:4a:1c:4b:73:05:12:fc:c6:ea:e0:50: - 13:7c:43:93:74:b3:ca:74:e7:8e:1f:01:08:d0:30: - d4:5b:71:36:b4:07:ba:c1:30:30:5c:48:b7:82:3b: - 98:a6:7d:60:8a:a2:a3:29:82:cc:ba:bd:83:04:1b: - a2:83:03:41:a1:d6:05:f1:1b:c2:b6:f0:a8:7c:86: - 3b:46:a8:48:2a:88:dc:76:9a:76:bf:1f:6a:a5:3d: - 19:8f:eb:38:f3:64:de:c8:2b:0d:0a:28:ff:f7:db: - e2:15:42:d4:22:d0:27:5d:e1:79:fe:18:e7:70:88: - ad:4e:e6:d9:8b:3a:c6:dd:27:51:6e:ff:bc:64:f5: - 33:43:4f - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Key Usage: critical - Certificate Sign, CRL Sign - X509v3 Basic Constraints: critical - CA:TRUE - X509v3 Subject Key Identifier: - 79:B4:59:E6:7B:B6:E5:E4:01:73:80:08:88:C8:1A:58:F6:E9:9B:6E - Signature Algorithm: sha256WithRSAEncryption - 55:1f:58:a9:bc:b2:a8:50:d0:0c:b1:d8:1a:69:20:27:29:08: - ac:61:75:5c:8a:6e:f8:82:e5:69:2f:d5:f6:56:4b:b9:b8:73: - 10:59:d3:21:97:7e:e7:4c:71:fb:b2:d2:60:ad:39:a8:0b:ea: - 17:21:56:85:f1:50:0e:59:eb:ce:e0:59:e9:ba:c9:15:ef:86: - 9d:8f:84:80:f6:e4:e9:91:90:dc:17:9b:62:1b:45:f0:66:95: - d2:7c:6f:c2:ea:3b:ef:1f:cf:cb:d6:ae:27:f1:a9:b0:c8:ae: - fd:7d:7e:9a:fa:22:04:eb:ff:d9:7f:ea:91:2b:22:b1:17:0e: - 8f:f2:8a:34:5b:58:d8:fc:01:c9:54:b9:b8:26:cc:8a:88:33: - 89:4c:2d:84:3c:82:df:ee:96:57:05:ba:2c:bb:f7:c4:b7:c7: - 4e:3b:82:be:31:c8:22:73:73:92:d1:c2:80:a4:39:39:10:33: - 23:82:4c:3c:9f:86:b2:55:98:1d:be:29:86:8c:22:9b:9e:e2: - 6b:3b:57:3a:82:70:4d:dc:09:c7:89:cb:0a:07:4d:6c:e8:5d: - 8e:c9:ef:ce:ab:c7:bb:b5:2b:4e:45:d6:4a:d0:26:cc:e5:72: - ca:08:6a:a5:95:e3:15:a1:f7:a4:ed:c9:2c:5f:a5:fb:ff:ac: - 28:02:2e:be:d7:7b:bb:e3:71:7b:90:16:d3:07:5e:46:53:7c: - 37:07:42:8c:d3:c4:96:9c:d5:99:b5:2a:e0:95:1a:80:48:ae: - 4c:39:07:ce:cc:47:a4:52:95:2b:ba:b8:fb:ad:d2:33:53:7d: - e5:1d:4d:6d:d5:a1:b1:c7:42:6f:e6:40:27:35:5c:a3:28:b7: - 07:8d:e7:8d:33:90:e7:23:9f:fb:50:9c:79:6c:46:d5:b4:15: - b3:96:6e:7e:9b:0c:96:3a:b8:52:2d:3f:d6:5b:e1:fb:08:c2: - 84:fe:24:a8:a3:89:da:ac:6a:e1:18:2a:b1:a8:43:61:5b:d3: - 1f:dc:3b:8d:76:f2:2d:e8:8d:75:df:17:33:6c:3d:53:fb:7b: - cb:41:5f:ff:dc:a2:d0:61:38:e1:96:b8:ac:5d:8b:37:d7:75: - d5:33:c0:99:11:ae:9d:41:c1:72:75:84:be:02:41:42:5f:67: - 24:48:94:d1:9b:27:be:07:3f:b9:b8:4f:81:74:51:e1:7a:b7: - ed:9d:23:e2:be:e0:d5:28:04:13:3c:31:03:9e:dd:7a:6c:8f: - c6:07:18:c6:7f:de:47:8e:3f:28:9e:04:06:cf:a5:54:34:77: - bd:ec:89:9b:e9:17:43:df:5b:db:5f:fe:8e:1e:57:a2:cd:40: - 9d:7e:62:22:da:de:18:27 ------BEGIN CERTIFICATE----- -MIIFazCCA1OgAwIBAgIRAIIQz7DSQONZRGPgu2OCiwAwDQYJKoZIhvcNAQELBQAw -TzELMAkGA1UEBhMCVVMxKTAnBgNVBAoTIEludGVybmV0IFNlY3VyaXR5IFJlc2Vh -cmNoIEdyb3VwMRUwEwYDVQQDEwxJU1JHIFJvb3QgWDEwHhcNMTUwNjA0MTEwNDM4 -WhcNMzUwNjA0MTEwNDM4WjBPMQswCQYDVQQGEwJVUzEpMCcGA1UEChMgSW50ZXJu -ZXQgU2VjdXJpdHkgUmVzZWFyY2ggR3JvdXAxFTATBgNVBAMTDElTUkcgUm9vdCBY -MTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAK3oJHP0FDfzm54rVygc -h77ct984kIxuPOZXoHj3dcKi/vVqbvYATyjb3miGbESTtrFj/RQSa78f0uoxmyF+ -0TM8ukj13Xnfs7j/EvEhmkvBioZxaUpmZmyPfjxwv60pIgbz5MDmgK7iS4+3mX6U -A5/TR5d8mUgjU+g4rk8Kb4Mu0UlXjIB0ttov0DiNewNwIRt18jA8+o+u3dpjq+sW -T8KOEUt+zwvo/7V3LvSye0rgTBIlDHCNAymg4VMk7BPZ7hm/ELNKjD+Jo2FR3qyH -B5T0Y3HsLuJvW5iB4YlcNHlsdu87kGJ55tukmi8mxdAQ4Q7e2RCOFvu396j3x+UC -B5iPNgiV5+I3lg02dZ77DnKxHZu8A/lJBdiB3QW0KtZB6awBdpUKD9jf1b0SHzUv -KBds0pjBqAlkd25HN7rOrFleaJ1/ctaJxQZBKT5ZPt0m9STJEadao0xAH0ahmbWn -OlFuhjuefXKnEgV4We0+UXgVCwOPjdAvBbI+e0ocS3MFEvzG6uBQE3xDk3SzynTn -jh8BCNAw1FtxNrQHusEwMFxIt4I7mKZ9YIqioymCzLq9gwQbooMDQaHWBfEbwrbw -qHyGO0aoSCqI3Haadr8faqU9GY/rOPNk3sgrDQoo//fb4hVC1CLQJ13hef4Y53CI -rU7m2Ys6xt0nUW7/vGT1M0NPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV -HRMBAf8EBTADAQH/MB0GA1UdDgQWBBR5tFnme7bl5AFzgAiIyBpY9umbbjANBgkq -hkiG9w0BAQsFAAOCAgEAVR9YqbyyqFDQDLHYGmkgJykIrGF1XIpu+ILlaS/V9lZL -ubhzEFnTIZd+50xx+7LSYK05qAvqFyFWhfFQDlnrzuBZ6brJFe+GnY+EgPbk6ZGQ -3BebYhtF8GaV0nxvwuo77x/Py9auJ/GpsMiu/X1+mvoiBOv/2X/qkSsisRcOj/KK -NFtY2PwByVS5uCbMiogziUwthDyC3+6WVwW6LLv3xLfHTjuCvjHIInNzktHCgKQ5 -ORAzI4JMPJ+GslWYHb4phowim57iaztXOoJwTdwJx4nLCgdNbOhdjsnvzqvHu7Ur -TkXWStAmzOVyyghqpZXjFaH3pO3JLF+l+/+sKAIuvtd7u+Nxe5AW0wdeRlN8NwdC -jNPElpzVmbUq4JUagEiuTDkHzsxHpFKVK7q4+63SM1N95R1NbdWhscdCb+ZAJzVc -oyi3B43njTOQ5yOf+1CceWxG1bQVs5ZufpsMljq4Ui0/1lvh+wjChP4kqKOJ2qxq -4RgqsahDYVvTH9w7jXbyLeiNdd8XM2w9U/t7y0Ff/9yi0GE44Za4rF2LN9d11TPA -mRGunUHBcnWEvgJBQl9nJEiU0Zsnvgc/ubhPgXRR4Xq37Z0j4r7g1SgEEzwxA57d -emyPxgcYxn/eR44/KJ4EBs+lVDR3veyJm+kXQ99b21/+jh5Xos1AnX5iItreGCc= ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: - 0a:01:42:80:00:00:01:45:23:c8:44:b5:00:00:00:02 - Signature Algorithm: sha256WithRSAEncryption - Issuer: C=US, O=IdenTrust, CN=IdenTrust Commercial Root CA 1 - Validity - Not Before: Jan 16 18:12:23 2014 GMT - Not After : Jan 16 18:12:23 2034 GMT - Subject: C=US, O=IdenTrust, CN=IdenTrust Commercial Root CA 1 - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (4096 bit) - Modulus: - 00:a7:50:19:de:3f:99:3d:d4:33:46:f1:6f:51:61: - 82:b2:a9:4f:8f:67:89:5d:84:d9:53:dd:0c:28:d9: - d7:f0:ff:ae:95:43:72:99:f9:b5:5d:7c:8a:c1:42: - e1:31:50:74:d1:81:0d:7c:cd:9b:21:ab:43:e2:ac: - ad:5e:86:6e:f3:09:8a:1f:5a:32:bd:a2:eb:94:f9: - e8:5c:0a:ec:ff:98:d2:af:71:b3:b4:53:9f:4e:87: - ef:92:bc:bd:ec:4f:32:30:88:4b:17:5e:57:c4:53: - c2:f6:02:97:8d:d9:62:2b:bf:24:1f:62:8d:df:c3: - b8:29:4b:49:78:3c:93:60:88:22:fc:99:da:36:c8: - c2:a2:d4:2c:54:00:67:35:6e:73:bf:02:58:f0:a4: - dd:e5:b0:a2:26:7a:ca:e0:36:a5:19:16:f5:fd:b7: - ef:ae:3f:40:f5:6d:5a:04:fd:ce:34:ca:24:dc:74: - 23:1b:5d:33:13:12:5d:c4:01:25:f6:30:dd:02:5d: - 9f:e0:d5:47:bd:b4:eb:1b:a1:bb:49:49:d8:9f:5b: - 02:f3:8a:e4:24:90:e4:62:4f:4f:c1:af:8b:0e:74: - 17:a8:d1:72:88:6a:7a:01:49:cc:b4:46:79:c6:17: - b1:da:98:1e:07:59:fa:75:21:85:65:dd:90:56:ce: - fb:ab:a5:60:9d:c4:9d:f9:52:b0:8b:bd:87:f9:8f: - 2b:23:0a:23:76:3b:f7:33:e1:c9:00:f3:69:f9:4b: - a2:e0:4e:bc:7e:93:39:84:07:f7:44:70:7e:fe:07: - 5a:e5:b1:ac:d1:18:cc:f2:35:e5:49:49:08:ca:56: - c9:3d:fb:0f:18:7d:8b:3b:c1:13:c2:4d:8f:c9:4f: - 0e:37:e9:1f:a1:0e:6a:df:62:2e:cb:35:06:51:79: - 2c:c8:25:38:f4:fa:4b:a7:89:5c:9c:d2:e3:0d:39: - 86:4a:74:7c:d5:59:87:c2:3f:4e:0c:5c:52:f4:3d: - f7:52:82:f1:ea:a3:ac:fd:49:34:1a:28:f3:41:88: - 3a:13:ee:e8:de:ff:99:1d:5f:ba:cb:e8:1e:f2:b9: - 50:60:c0:31:d3:73:e5:ef:be:a0:ed:33:0b:74:be: - 20:20:c4:67:6c:f0:08:03:7a:55:80:7f:46:4e:96: - a7:f4:1e:3e:e1:f6:d8:09:e1:33:64:2b:63:d7:32: - 5e:9f:f9:c0:7b:0f:78:6f:97:bc:93:9a:f9:9c:12: - 90:78:7a:80:87:15:d7:72:74:9c:55:74:78:b1:ba: - e1:6e:70:04:ba:4f:a0:ba:68:c3:7b:ff:31:f0:73: - 3d:3d:94:2a:b1:0b:41:0e:a0:fe:4d:88:65:6b:79: - 33:b4:d7 - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Key Usage: critical - Certificate Sign, CRL Sign - X509v3 Basic Constraints: critical - CA:TRUE - X509v3 Subject Key Identifier: - ED:44:19:C0:D3:F0:06:8B:EE:A4:7B:BE:42:E7:26:54:C8:8E:36:76 - Signature Algorithm: sha256WithRSAEncryption - 0d:ae:90:32:f6:a6:4b:7c:44:76:19:61:1e:27:28:cd:5e:54: - ef:25:bc:e3:08:90:f9:29:d7:ae:68:08:e1:94:00:58:ef:2e: - 2e:7e:53:52:8c:b6:5c:07:ea:88:ba:99:8b:50:94:d7:82:80: - df:61:09:00:93:ad:0d:14:e6:ce:c1:f2:37:94:78:b0:5f:9c: - b3:a2:73:b8:8f:05:93:38:cd:8d:3e:b0:b8:fb:c0:cf:b1:f2: - ec:2d:2d:1b:cc:ec:aa:9a:b3:aa:60:82:1b:2d:3b:c3:84:3d: - 57:8a:96:1e:9c:75:b8:d3:30:cd:60:08:83:90:d3:8e:54:f1: - 4d:66:c0:5d:74:03:40:a3:ee:85:7e:c2:1f:77:9c:06:e8:c1: - a7:18:5d:52:95:ed:c9:dd:25:9e:6d:fa:a9:ed:a3:3a:34:d0: - 59:7b:da:ed:50:f3:35:bf:ed:eb:14:4d:31:c7:60:f4:da:f1: - 87:9c:e2:48:e2:c6:c5:37:fb:06:10:fa:75:59:66:31:47:29: - da:76:9a:1c:e9:82:ae:ef:9a:b9:51:f7:88:23:9a:69:95:62: - 3c:e5:55:80:36:d7:54:02:ff:f1:b9:5d:ce:d4:23:6f:d8:45: - 84:4a:5b:65:ef:89:0c:dd:14:a7:20:cb:18:a5:25:b4:0d:f9: - 01:f0:a2:d2:f4:00:c8:74:8e:a1:2a:48:8e:65:db:13:c4:e2: - 25:17:7d:eb:be:87:5b:17:20:54:51:93:4a:53:03:0b:ec:5d: - ca:33:ed:62:fd:45:c7:2f:5b:dc:58:a0:80:39:e6:fa:d7:fe: - 13:14:a6:ed:3d:94:4a:42:74:d4:c3:77:59:73:cd:8f:46:be: - 55:38:ef:fa:e8:91:32:ea:97:58:04:22:de:38:c3:cc:bc:6d: - c9:33:3a:6a:0a:69:3f:a0:c8:ea:72:8f:8c:63:86:23:bd:6d: - 3c:96:9e:95:e0:49:4c:aa:a2:b9:2a:1b:9c:36:81:78:ed:c3: - e8:46:e2:26:59:44:75:1e:d9:75:89:51:cd:10:84:9d:61:60: - cb:5d:f9:97:22:4d:8e:98:e6:e3:7f:f6:5b:bb:ae:cd:ca:4a: - 81:6b:5e:0b:f3:51:e1:74:2b:e9:7e:27:a7:d9:99:49:4e:f8: - a5:80:db:25:0f:1c:63:62:8a:c9:33:67:6b:3c:10:83:c6:ad: - de:a8:cd:16:8e:8d:f0:07:37:71:9f:f2:ab:fc:41:f5:c1:8b: - ec:00:37:5d:09:e5:4e:80:ef:fa:b1:5c:38:06:a5:1b:4a:e1: - dc:38:2d:3c:dc:ab:1f:90:1a:d5:4a:9c:ee:d1:70:6c:cc:ee: - f4:57:f8:18:ba:84:6e:87 ------BEGIN CERTIFICATE----- -MIIFYDCCA0igAwIBAgIQCgFCgAAAAUUjyES1AAAAAjANBgkqhkiG9w0BAQsFADBK -MQswCQYDVQQGEwJVUzESMBAGA1UEChMJSWRlblRydXN0MScwJQYDVQQDEx5JZGVu -VHJ1c3QgQ29tbWVyY2lhbCBSb290IENBIDEwHhcNMTQwMTE2MTgxMjIzWhcNMzQw -MTE2MTgxMjIzWjBKMQswCQYDVQQGEwJVUzESMBAGA1UEChMJSWRlblRydXN0MScw -JQYDVQQDEx5JZGVuVHJ1c3QgQ29tbWVyY2lhbCBSb290IENBIDEwggIiMA0GCSqG -SIb3DQEBAQUAA4ICDwAwggIKAoICAQCnUBneP5k91DNG8W9RYYKyqU+PZ4ldhNlT -3Qwo2dfw/66VQ3KZ+bVdfIrBQuExUHTRgQ18zZshq0PirK1ehm7zCYofWjK9ouuU -+ehcCuz/mNKvcbO0U59Oh++SvL3sTzIwiEsXXlfEU8L2ApeN2WIrvyQfYo3fw7gp -S0l4PJNgiCL8mdo2yMKi1CxUAGc1bnO/AljwpN3lsKImesrgNqUZFvX9t++uP0D1 -bVoE/c40yiTcdCMbXTMTEl3EASX2MN0CXZ/g1Ue9tOsbobtJSdifWwLziuQkkORi -T0/Br4sOdBeo0XKIanoBScy0RnnGF7HamB4HWfp1IYVl3ZBWzvurpWCdxJ35UrCL -vYf5jysjCiN2O/cz4ckA82n5S6LgTrx+kzmEB/dEcH7+B1rlsazRGMzyNeVJSQjK -Vsk9+w8YfYs7wRPCTY/JTw436R+hDmrfYi7LNQZReSzIJTj0+kuniVyc0uMNOYZK -dHzVWYfCP04MXFL0PfdSgvHqo6z9STQaKPNBiDoT7uje/5kdX7rL6B7yuVBgwDHT -c+XvvqDtMwt0viAgxGds8AgDelWAf0ZOlqf0Hj7h9tgJ4TNkK2PXMl6f+cB7D3hv -l7yTmvmcEpB4eoCHFddydJxVdHixuuFucAS6T6C6aMN7/zHwcz09lCqxC0EOoP5N -iGVreTO01wIDAQABo0IwQDAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/BAUwAwEB -/zAdBgNVHQ4EFgQU7UQZwNPwBovupHu+QucmVMiONnYwDQYJKoZIhvcNAQELBQAD -ggIBAA2ukDL2pkt8RHYZYR4nKM1eVO8lvOMIkPkp165oCOGUAFjvLi5+U1KMtlwH -6oi6mYtQlNeCgN9hCQCTrQ0U5s7B8jeUeLBfnLOic7iPBZM4zY0+sLj7wM+x8uwt -LRvM7Kqas6pgghstO8OEPVeKlh6cdbjTMM1gCIOQ045U8U1mwF10A0Cj7oV+wh93 -nAbowacYXVKV7cndJZ5t+qntozo00Fl72u1Q8zW/7esUTTHHYPTa8Yec4kjixsU3 -+wYQ+nVZZjFHKdp2mhzpgq7vmrlR94gjmmmVYjzlVYA211QC//G5Xc7UI2/YRYRK -W2XviQzdFKcgyxilJbQN+QHwotL0AMh0jqEqSI5l2xPE4iUXfeu+h1sXIFRRk0pT -AwvsXcoz7WL9RccvW9xYoIA55vrX/hMUpu09lEpCdNTDd1lzzY9GvlU47/rokTLq -l1gEIt44w8y8bckzOmoKaT+gyOpyj4xjhiO9bTyWnpXgSUyqorkqG5w2gXjtw+hG -4iZZRHUe2XWJUc0QhJ1hYMtd+ZciTY6Y5uN/9lu7rs3KSoFrXgvzUeF0K+l+J6fZ -mUlO+KWA2yUPHGNiiskzZ2s8EIPGrd6ozRaOjfAHN3Gf8qv8QfXBi+wAN10J5U6A -7/qxXDgGpRtK4dw4LTzcqx+QGtVKnO7RcGzM7vRX+Bi6hG6H ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: - 0a:01:42:80:00:00:01:45:23:cf:46:7c:00:00:00:02 - Signature Algorithm: sha256WithRSAEncryption - Issuer: C=US, O=IdenTrust, CN=IdenTrust Public Sector Root CA 1 - Validity - Not Before: Jan 16 17:53:32 2014 GMT - Not After : Jan 16 17:53:32 2034 GMT - Subject: C=US, O=IdenTrust, CN=IdenTrust Public Sector Root CA 1 - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (4096 bit) - Modulus: - 00:b6:22:94:fc:a4:48:af:e8:47:6b:0a:fb:27:76: - e4:f2:3f:8a:3b:7a:4a:2c:31:2a:8c:8d:b0:a9:c3: - 31:6b:a8:77:76:84:26:b6:ac:81:42:0d:08:eb:55: - 58:bb:7a:f8:bc:65:7d:f2:a0:6d:8b:a8:47:e9:62: - 76:1e:11:ee:08:14:d1:b2:44:16:f4:ea:d0:fa:1e: - 2f:5e:db:cb:73:41:ae:bc:00:b0:4a:2b:40:b2:ac: - e1:3b:4b:c2:2d:9d:e4:a1:9b:ec:1a:3a:1e:f0:08: - b3:d0:e4:24:35:07:9f:9c:b4:c9:52:6d:db:07:ca: - 8f:b5:5b:f0:83:f3:4f:c7:2d:a5:c8:ad:cb:95:20: - a4:31:28:57:58:5a:e4:8d:1b:9a:ab:9e:0d:0c:f2: - 0a:33:39:22:39:0a:97:2e:f3:53:77:b9:44:45:fd: - 84:cb:36:20:81:59:2d:9a:6f:6d:48:48:61:ca:4c: - df:53:d1:af:52:bc:44:9f:ab:2f:6b:83:72:ef:75: - 80:da:06:33:1b:5d:c8:da:63:c6:4d:cd:ac:66:31: - cd:d1:de:3e:87:10:36:e1:b9:a4:7a:ef:60:50:b2: - cb:ca:a6:56:e0:37:af:ab:34:13:39:25:e8:39:66: - e4:98:7a:aa:12:98:9c:59:66:86:3e:ad:f1:b0:ca: - 3e:06:0f:7b:f0:11:4b:37:a0:44:6d:7b:cb:a8:8c: - 71:f4:d5:b5:91:36:cc:f0:15:c6:2b:de:51:17:b1: - 97:4c:50:3d:b1:95:59:7c:05:7d:2d:21:d5:00:bf: - 01:67:a2:5e:7b:a6:5c:f2:f7:22:f1:90:0d:93:db: - aa:44:51:66:cc:7d:76:03:eb:6a:a8:2a:38:19:97: - 76:0d:6b:8a:61:f9:bc:f6:ee:76:fd:70:2b:dd:29: - 3c:f8:0a:1e:5b:42:1c:8b:56:2f:55:1b:1c:a1:2e: - b5:c7:16:e6:f8:aa:3c:92:8e:69:b6:01:c1:b5:86: - 9d:89:0f:0b:38:94:54:e8:ea:dc:9e:3d:25:bc:53: - 26:ed:d5:ab:39:aa:c5:40:4c:54:ab:b2:b4:d9:d9: - f8:d7:72:db:1c:bc:6d:bd:65:5f:ef:88:35:2a:66: - 2f:ee:f6:b3:65:f0:33:8d:7c:98:41:69:46:0f:43: - 1c:69:fa:9b:b5:d0:61:6a:cd:ca:4b:d9:4c:90:46: - ab:15:59:a1:47:54:29:2e:83:28:5f:1c:c2:a2:ab: - 72:17:00:06:8e:45:ec:8b:e2:33:3d:7f:da:19:44: - e4:62:72:c3:df:22:c6:f2:56:d4:dd:5f:95:72:ed: - 6d:5f:f7:48:03:5b:fd:c5:2a:a0:f6:73:23:84:10: - 1b:01:e7 - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Key Usage: critical - Certificate Sign, CRL Sign - X509v3 Basic Constraints: critical - CA:TRUE - X509v3 Subject Key Identifier: - E3:71:E0:9E:D8:A7:42:D9:DB:71:91:6B:94:93:EB:C3:A3:D1:14:A3 - Signature Algorithm: sha256WithRSAEncryption - 47:fa:dd:0a:b0:11:91:38:ad:4d:5d:f7:e5:0e:97:54:19:82: - 48:87:54:8c:aa:64:99:d8:5a:fe:88:01:c5:58:a5:99:b1:23: - 54:23:b7:6a:1d:20:57:e5:01:62:41:17:d3:09:db:75:cb:6e: - 54:90:75:fe:1a:9f:81:0a:c2:dd:d7:f7:09:d0:5b:72:15:e4: - 1e:09:6a:3d:33:f3:21:9a:e6:15:7e:ad:51:d5:0d:10:ed:7d: - 42:c0:8f:ee:c0:9a:08:d5:41:d6:5c:0e:21:69:6e:80:61:0e: - 15:c0:b8:cf:c5:49:12:52:cc:be:3a:cc:d4:2e:38:05:de:35: - fd:1f:6f:b8:80:68:98:3d:4d:a0:ca:40:65:d2:73:7c:f5:8b: - d9:0a:95:3f:d8:3f:23:6d:1a:d1:2a:24:19:d9:85:b3:17:ef: - 78:6e:a9:58:d1:23:d3:c7:13:ed:72:25:7f:5d:b1:73:70:d0: - 7f:06:97:09:84:29:80:61:1d:fa:5e:ff:73:ac:a0:e3:89:b8: - 1c:71:15:c6:de:31:7f:12:dc:e1:6d:9b:af:e7:e8:9f:75:78: - 4c:ab:46:3b:9a:ce:bf:05:18:5d:4d:15:3c:16:9a:19:50:04: - 9a:b2:9a:6f:65:8b:52:5f:3c:58:04:28:25:c0:66:61:31:7e: - b9:e0:75:b9:1a:a8:81:d6:72:17:b3:c5:03:31:35:11:78:78: - a2:e0:e9:30:8c:7f:80:df:58:df:3c:ba:27:96:e2:80:34:6d: - e3:98:d3:64:27:ac:48:7e:28:77:5c:c6:25:61:25:f8:85:0c: - 65:fa:c4:32:2f:a5:98:05:e4:f8:0b:67:16:16:c6:82:b8:32: - 19:f9:f9:b9:79:dc:1f:cd:eb:af:ab:0e:dd:1b:db:45:e4:7a: - e7:02:e2:95:5d:fc:69:f0:53:69:61:95:75:79:0b:5e:55:e6: - 38:1c:94:a9:59:33:9e:c8:71:74:79:7f:51:89:b6:c8:6a:b8: - 30:c8:6a:38:c3:6e:9e:e1:37:16:ea:05:62:4c:5b:12:47:ed: - a7:b4:b3:58:56:c7:49:f3:7f:12:68:09:31:71:f0:6d:f8:4e: - 47:fb:d6:85:ee:c5:58:40:19:a4:1d:a7:f9:4b:43:37:dc:68: - 5a:4f:cf:eb:c2:64:74:de:b4:15:d9:f4:54:54:1a:2f:1c:d7: - 97:71:54:90:8e:d9:20:9d:53:2b:7f:ab:8f:e2:ea:30:bc:50: - 37:ef:f1:47:b5:7d:7c:2c:04:ec:68:9d:b4:49:44:10:f4:72: - 4b:1c:64:e7:fc:e6:6b:90:dd:69:7d:69:fd:00:56:a5:b7:ac: - b6:ad:b7:ca:3e:01:ef:9c ------BEGIN CERTIFICATE----- -MIIFZjCCA06gAwIBAgIQCgFCgAAAAUUjz0Z8AAAAAjANBgkqhkiG9w0BAQsFADBN -MQswCQYDVQQGEwJVUzESMBAGA1UEChMJSWRlblRydXN0MSowKAYDVQQDEyFJZGVu -VHJ1c3QgUHVibGljIFNlY3RvciBSb290IENBIDEwHhcNMTQwMTE2MTc1MzMyWhcN -MzQwMTE2MTc1MzMyWjBNMQswCQYDVQQGEwJVUzESMBAGA1UEChMJSWRlblRydXN0 -MSowKAYDVQQDEyFJZGVuVHJ1c3QgUHVibGljIFNlY3RvciBSb290IENBIDEwggIi -MA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQC2IpT8pEiv6EdrCvsnduTyP4o7 -ekosMSqMjbCpwzFrqHd2hCa2rIFCDQjrVVi7evi8ZX3yoG2LqEfpYnYeEe4IFNGy -RBb06tD6Hi9e28tzQa68ALBKK0CyrOE7S8ItneShm+waOh7wCLPQ5CQ1B5+ctMlS -bdsHyo+1W/CD80/HLaXIrcuVIKQxKFdYWuSNG5qrng0M8gozOSI5Cpcu81N3uURF -/YTLNiCBWS2ab21ISGHKTN9T0a9SvESfqy9rg3LvdYDaBjMbXcjaY8ZNzaxmMc3R -3j6HEDbhuaR672BQssvKplbgN6+rNBM5Jeg5ZuSYeqoSmJxZZoY+rfGwyj4GD3vw -EUs3oERte8uojHH01bWRNszwFcYr3lEXsZdMUD2xlVl8BX0tIdUAvwFnol57plzy -9yLxkA2T26pEUWbMfXYD62qoKjgZl3YNa4ph+bz27nb9cCvdKTz4Ch5bQhyLVi9V -GxyhLrXHFub4qjySjmm2AcG1hp2JDws4lFTo6tyePSW8Uybt1as5qsVATFSrsrTZ -2fjXctscvG29ZV/viDUqZi/u9rNl8DONfJhBaUYPQxxp+pu10GFqzcpL2UyQRqsV -WaFHVCkugyhfHMKiq3IXAAaOReyL4jM9f9oZRORicsPfIsbyVtTdX5Vy7W1f90gD -W/3FKqD2cyOEEBsB5wIDAQABo0IwQDAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/ -BAUwAwEB/zAdBgNVHQ4EFgQU43HgntinQtnbcZFrlJPrw6PRFKMwDQYJKoZIhvcN -AQELBQADggIBAEf63QqwEZE4rU1d9+UOl1QZgkiHVIyqZJnYWv6IAcVYpZmxI1Qj -t2odIFflAWJBF9MJ23XLblSQdf4an4EKwt3X9wnQW3IV5B4Jaj0z8yGa5hV+rVHV -DRDtfULAj+7AmgjVQdZcDiFpboBhDhXAuM/FSRJSzL46zNQuOAXeNf0fb7iAaJg9 -TaDKQGXSc3z1i9kKlT/YPyNtGtEqJBnZhbMX73huqVjRI9PHE+1yJX9dsXNw0H8G -lwmEKYBhHfpe/3OsoOOJuBxxFcbeMX8S3OFtm6/n6J91eEyrRjuazr8FGF1NFTwW -mhlQBJqymm9li1JfPFgEKCXAZmExfrngdbkaqIHWchezxQMxNRF4eKLg6TCMf4Df -WN88uieW4oA0beOY02QnrEh+KHdcxiVhJfiFDGX6xDIvpZgF5PgLZxYWxoK4Mhn5 -+bl53B/N66+rDt0b20XkeucC4pVd/GnwU2lhlXV5C15V5jgclKlZM57IcXR5f1GJ -tshquDDIajjDbp7hNxbqBWJMWxJH7ae0s1hWx0nzfxJoCTFx8G34Tkf71oXuxVhA -GaQdp/lLQzfcaFpPz+vCZHTetBXZ9FRUGi8c15dxVJCO2SCdUyt/q4/i6jC8UDfv -8Ue1fXwsBOxonbRJRBD0ckscZOf85muQ3Wl9af0AVqW3rLatt8o+Ae+c ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: - b0:b7:5a:16:48:5f:bf:e1:cb:f5:8b:d7:19:e6:7d - Signature Algorithm: sha256WithRSAEncryption - Issuer: C=ES, O=IZENPE S.A., CN=Izenpe.com - Validity - Not Before: Dec 13 13:08:28 2007 GMT - Not After : Dec 13 08:27:25 2037 GMT - Subject: C=ES, O=IZENPE S.A., CN=Izenpe.com - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (4096 bit) - Modulus: - 00:c9:d3:7a:ca:0f:1e:ac:a7:86:e8:16:65:6a:b1: - c2:1b:45:32:71:95:d9:fe:10:5b:cc:af:e7:a5:79: - 01:8f:89:c3:ca:f2:55:71:f7:77:be:77:94:f3:72: - a4:2c:44:d8:9e:92:9b:14:3a:a1:e7:24:90:0a:0a: - 56:8e:c5:d8:26:94:e1:d9:48:e1:2d:3e:da:0a:72: - dd:a3:99:15:da:81:a2:87:f4:7b:6e:26:77:89:58: - ad:d6:eb:0c:b2:41:7a:73:6e:6d:db:7a:78:41:e9: - 08:88:12:7e:87:2e:66:11:63:6c:54:fb:3c:9d:72: - c0:bc:2e:ff:c2:b7:dd:0d:76:e3:3a:d7:f7:b4:68: - be:a2:f5:e3:81:6e:c1:46:6f:5d:8d:e0:4d:c6:54: - 55:89:1a:33:31:0a:b1:57:b9:a3:8a:98:c3:ec:3b: - 34:c5:95:41:69:7e:75:c2:3c:20:c5:61:ba:51:47: - a0:20:90:93:a1:90:4b:f3:4e:7c:85:45:54:9a:d1: - 05:26:41:b0:b5:4d:1d:33:be:c4:03:c8:25:7c:c1: - 70:db:3b:f4:09:2d:54:27:48:ac:2f:e1:c4:ac:3e: - c8:cb:92:4c:53:39:37:23:ec:d3:01:f9:e0:09:44: - 4d:4d:64:c0:e1:0d:5a:87:22:bc:ad:1b:a3:fe:26: - b5:15:f3:a7:fc:84:19:e9:ec:a1:88:b4:44:69:84: - 83:f3:89:d1:74:06:a9:cc:0b:d6:c2:de:27:85:50: - 26:ca:17:b8:c9:7a:87:56:2c:1a:01:1e:6c:be:13: - ad:10:ac:b5:24:f5:38:91:a1:d6:4b:da:f1:bb:d2: - de:47:b5:f1:bc:81:f6:59:6b:cf:19:53:e9:8d:15: - cb:4a:cb:a9:6f:44:e5:1b:41:cf:e1:86:a7:ca:d0: - 6a:9f:bc:4c:8d:06:33:5a:a2:85:e5:90:35:a0:62: - 5c:16:4e:f0:e3:a2:fa:03:1a:b4:2c:71:b3:58:2c: - de:7b:0b:db:1a:0f:eb:de:21:1f:06:77:06:03:b0: - c9:ef:99:fc:c0:b9:4f:0b:86:28:fe:d2:b9:ea:e3: - da:a5:c3:47:69:12:e0:db:f0:f6:19:8b:ed:7b:70: - d7:02:d6:ed:87:18:28:2c:04:24:4c:77:e4:48:8a: - 1a:c6:3b:9a:d4:0f:ca:fa:75:d2:01:40:5a:8d:79: - bf:8b:cf:4b:cf:aa:16:c1:95:e4:ad:4c:8a:3e:17: - 91:d4:b1:62:e5:82:e5:80:04:a4:03:7e:8d:bf:da: - 7f:a2:0f:97:4f:0c:d3:0d:fb:d7:d1:e5:72:7e:1c: - c8:77:ff:5b:9a:0f:b7:ae:05:46:e5:f1:a8:16:ec: - 47:a4:17 - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Subject Alternative Name: - email:info@izenpe.com, DirName:/O=IZENPE S.A. - CIF A01337260-RMerc.Vitoria-Gasteiz T1055 F62 S8/street=Avda del Mediterraneo Etorbidea 14 - 01010 Vitoria-Gasteiz - X509v3 Basic Constraints: critical - CA:TRUE - X509v3 Key Usage: critical - Certificate Sign, CRL Sign - X509v3 Subject Key Identifier: - 1D:1C:65:0E:A8:F2:25:7B:B4:91:CF:E4:B1:B1:E6:BD:55:74:6C:05 - Signature Algorithm: sha256WithRSAEncryption - 78:a6:0c:16:4a:9f:4c:88:3a:c0:cb:0e:a5:16:7d:9f:b9:48: - 5f:18:8f:0d:62:36:f6:cd:19:6b:ac:ab:d5:f6:91:7d:ae:71: - f3:3f:b3:0e:78:85:9b:95:a4:27:21:47:42:4a:7c:48:3a:f5: - 45:7c:b3:0c:8e:51:78:ac:95:13:de:c6:fd:7d:b8:1a:90:4c: - ab:92:03:c7:ed:42:01:ce:0f:d8:b1:fa:a2:92:e1:60:6d:ae: - 7a:6b:09:aa:c6:29:ee:68:49:67:30:80:24:7a:31:16:39:5b: - 7e:f1:1c:2e:dd:6c:09:ad:f2:31:c1:82:4e:b9:bb:f9:be:bf: - 2a:85:3f:c0:40:a3:3a:59:fc:59:4b:3c:28:24:db:b4:15:75: - ae:0d:88:ba:2e:73:c0:bd:58:87:e5:42:f2:eb:5e:ee:1e:30: - 22:99:cb:37:d1:c4:21:6c:81:ec:be:6d:26:e6:1c:e4:42:20: - 9e:47:b0:ac:83:59:70:2c:35:d6:af:36:34:b4:cd:3b:f8:32: - a8:ef:e3:78:89:fb:8d:45:2c:da:9c:b8:7e:40:1c:61:e7:3e: - a2:92:2c:4b:f2:cd:fa:98:b6:29:ff:f3:f2:7b:a9:1f:2e:a0: - 93:57:2b:de:85:03:f9:69:37:cb:9e:78:6a:05:b4:c5:31:78: - 89:ec:7a:a7:85:e1:b9:7b:3c:de:be:1e:79:84:ce:9f:70:0e: - 59:c2:35:2e:90:2a:31:d9:e4:45:7a:41:a4:2e:13:9b:34:0e: - 66:7b:49:ab:64:97:d0:46:c3:79:9d:72:50:63:a6:98:5b:06: - bd:48:6d:d8:39:83:70:e8:35:f0:05:d1:aa:bc:e3:db:c8:02: - ea:7c:fd:82:da:c2:5b:52:35:ae:98:3a:ad:ba:35:93:23:a7: - 1f:48:dd:35:46:98:b2:10:68:e4:a5:31:c2:0a:58:2e:19:81: - 10:c9:50:75:fc:ea:5a:16:ce:11:d7:ee:ef:50:88:2d:61:ff: - 3f:42:73:05:94:43:d5:8e:3c:4e:01:3a:19:a5:1f:46:4e:77: - d0:5d:e5:81:22:21:87:fe:94:7d:84:d8:93:ad:d6:68:43:48: - b2:db:eb:73:24:e7:91:7f:54:a4:b6:80:3e:9d:a3:3c:4c:72: - c2:57:c4:a0:d4:cc:38:27:ce:d5:06:9e:a2:48:d9:e9:9f:ce: - 82:70:36:93:9a:3b:df:96:21:e3:59:b7:0c:da:91:37:f0:fd: - 59:5a:b3:99:c8:69:6c:43:26:01:35:63:60:55:89:03:3a:75: - d8:ba:4a:d9:54:ff:ee:de:80:d8:2d:d1:38:d5:5e:2d:0b:98: - 7d:3e:6c:db:fc:26:88:c7 ------BEGIN CERTIFICATE----- -MIIF8TCCA9mgAwIBAgIQALC3WhZIX7/hy/WL1xnmfTANBgkqhkiG9w0BAQsFADA4 -MQswCQYDVQQGEwJFUzEUMBIGA1UECgwLSVpFTlBFIFMuQS4xEzARBgNVBAMMCkl6 -ZW5wZS5jb20wHhcNMDcxMjEzMTMwODI4WhcNMzcxMjEzMDgyNzI1WjA4MQswCQYD -VQQGEwJFUzEUMBIGA1UECgwLSVpFTlBFIFMuQS4xEzARBgNVBAMMCkl6ZW5wZS5j -b20wggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQDJ03rKDx6sp4boFmVq -scIbRTJxldn+EFvMr+eleQGPicPK8lVx93e+d5TzcqQsRNiekpsUOqHnJJAKClaO -xdgmlOHZSOEtPtoKct2jmRXagaKH9HtuJneJWK3W6wyyQXpzbm3benhB6QiIEn6H -LmYRY2xU+zydcsC8Lv/Ct90NduM61/e0aL6i9eOBbsFGb12N4E3GVFWJGjMxCrFX -uaOKmMPsOzTFlUFpfnXCPCDFYbpRR6AgkJOhkEvzTnyFRVSa0QUmQbC1TR0zvsQD -yCV8wXDbO/QJLVQnSKwv4cSsPsjLkkxTOTcj7NMB+eAJRE1NZMDhDVqHIrytG6P+ -JrUV86f8hBnp7KGItERphIPzidF0BqnMC9bC3ieFUCbKF7jJeodWLBoBHmy+E60Q -rLUk9TiRodZL2vG70t5HtfG8gfZZa88ZU+mNFctKy6lvROUbQc/hhqfK0GqfvEyN -BjNaooXlkDWgYlwWTvDjovoDGrQscbNYLN57C9saD+veIR8GdwYDsMnvmfzAuU8L -hij+0rnq49qlw0dpEuDb8PYZi+17cNcC1u2HGCgsBCRMd+RIihrGO5rUD8r6ddIB -QFqNeb+Lz0vPqhbBleStTIo+F5HUsWLlguWABKQDfo2/2n+iD5dPDNMN+9fR5XJ+ -HMh3/1uaD7euBUbl8agW7EekFwIDAQABo4H2MIHzMIGwBgNVHREEgagwgaWBD2lu -Zm9AaXplbnBlLmNvbaSBkTCBjjFHMEUGA1UECgw+SVpFTlBFIFMuQS4gLSBDSUYg -QTAxMzM3MjYwLVJNZXJjLlZpdG9yaWEtR2FzdGVpeiBUMTA1NSBGNjIgUzgxQzBB -BgNVBAkMOkF2ZGEgZGVsIE1lZGl0ZXJyYW5lbyBFdG9yYmlkZWEgMTQgLSAwMTAx -MCBWaXRvcmlhLUdhc3RlaXowDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMC -AQYwHQYDVR0OBBYEFB0cZQ6o8iV7tJHP5LGx5r1VdGwFMA0GCSqGSIb3DQEBCwUA -A4ICAQB4pgwWSp9MiDrAyw6lFn2fuUhfGI8NYjb2zRlrrKvV9pF9rnHzP7MOeIWb -laQnIUdCSnxIOvVFfLMMjlF4rJUT3sb9fbgakEyrkgPH7UIBzg/YsfqikuFgba56 -awmqxinuaElnMIAkejEWOVt+8Rwu3WwJrfIxwYJOubv5vr8qhT/AQKM6WfxZSzwo -JNu0FXWuDYi6LnPAvViH5ULy617uHjAimcs30cQhbIHsvm0m5hzkQiCeR7Csg1lw -LDXWrzY0tM07+DKo7+N4ifuNRSzanLh+QBxh5z6ikixL8s36mLYp//Pye6kfLqCT -VyvehQP5aTfLnnhqBbTFMXiJ7HqnheG5ezzevh55hM6fcA5ZwjUukCox2eRFekGk -LhObNA5me0mrZJfQRsN5nXJQY6aYWwa9SG3YOYNw6DXwBdGqvOPbyALqfP2C2sJb -UjWumDqtujWTI6cfSN01RpiyEGjkpTHCClguGYEQyVB1/OpaFs4R1+7vUIgtYf8/ -QnMFlEPVjjxOAToZpR9GTnfQXeWBIiGH/pR9hNiTrdZoQ0iy2+tzJOeRf1SktoA+ -naM8THLCV8Sg1Mw4J87VBp6iSNnpn86CcDaTmjvfliHjWbcM2pE38P1ZWrOZyGls -QyYBNWNgVYkDOnXYukrZVP/u3oDYLdE41V4tC5h9Pmzb/CaIxw== ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: - 0a:7e:a6:df:4b:44:9e:da:6a:24:85:9e:e6:b8:15:d3:16:7f:bb:b1 - Signature Algorithm: sha256WithRSAEncryption - Issuer: C=LU, O=LuxTrust S.A., CN=LuxTrust Global Root 2 - Validity - Not Before: Mar 5 13:21:57 2015 GMT - Not After : Mar 5 13:21:57 2035 GMT - Subject: C=LU, O=LuxTrust S.A., CN=LuxTrust Global Root 2 - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (4096 bit) - Modulus: - 00:d7:85:97:bf:11:98:e9:f0:62:83:4c:3c:87:f9: - 53:6a:37:0b:f2:0f:3c:87:ce:6f:dc:26:29:bd:c5: - 89:ba:c9:83:3d:f7:ee:ca:5b:c6:6d:49:73:b4:c9: - 46:a3:1b:34:13:3f:c1:89:45:57:f4:d9:b1:fb:36: - 65:4b:fb:08:e2:48:71:11:c8:6e:3b:9e:9d:df:89: - 65:37:a6:85:f6:3b:44:18:b6:c6:37:30:62:44:92: - 97:69:7d:42:30:24:e4:0d:0c:89:6b:63:de:c5:e1: - df:4e:a9:14:6c:53:e0:61:ce:f6:17:2f:1d:3c:bd: - e6:22:4c:1d:93:f5:10:c4:a1:76:ec:6a:de:c5:6c: - df:96:b4:56:40:42:c0:62:92:30:a1:2d:15:94:a0: - d2:20:06:09:6e:6a:6d:e5:eb:b7:be:d4:f0:f1:15: - 7c:8b:e6:4e:ba:13:cc:4b:27:5e:99:3c:17:5d:8f: - 81:7f:33:3d:4f:d3:3f:1b:ec:5c:3f:f0:3c:4c:75: - 6e:f2:a6:d5:9d:da:2d:07:63:02:c6:72:e9:94:bc: - 4c:49:95:4f:88:52:c8:db:e8:69:82:f8:cc:34:5b: - 22:f0:86:a7:89:bd:48:0a:6d:66:81:6d:c8:c8:64: - fb:01:e1:f4:e1:de:d9:9e:dd:db:5b:d4:2a:99:26: - 15:1b:1e:4c:92:29:82:9e:d5:92:81:92:41:70:19: - f7:a4:e5:93:4b:bc:77:67:31:dd:1c:fd:31:70:0d: - 17:99:0c:f9:0c:39:19:2a:17:b5:30:71:55:d5:0f: - ae:58:e1:3d:2f:34:9b:cf:9f:f6:78:85:c2:93:7a: - 72:3e:66:8f:9c:16:11:60:8f:9e:89:6f:67:be:e0: - 47:5a:3b:0c:9a:67:8b:cf:46:c6:ae:38:a3:f2:a7: - bc:e6:d6:85:6b:33:24:70:22:4b:cb:08:9b:bb:c8: - f8:02:29:1d:be:20:0c:46:bf:6b:87:9b:b3:2a:66: - 42:35:46:6c:aa:ba:ad:f9:98:7b:e9:50:55:14:31: - bf:b1:da:2d:ed:80:ad:68:24:fb:69:ab:d8:71:13: - 30:e6:67:b3:87:40:fd:89:7e:f2:43:d1:11:df:2f: - 65:2f:64:ce:5f:14:b9:b1:bf:31:bd:87:78:5a:59: - 65:88:aa:fc:59:32:48:86:d6:4c:b9:29:4b:95:d3: - 76:f3:77:25:6d:42:1c:38:83:4d:fd:a3:5f:9b:7f: - 2d:ac:79:1b:0e:42:31:97:63:a4:fb:8a:69:d5:22: - 0d:34:90:30:2e:a8:b4:e0:6d:b6:94:ac:bc:8b:4e: - d7:70:fc:c5:38:8e:64:25:e1:4d:39:90:ce:c9:87: - 84:58:71 - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Basic Constraints: critical - CA:TRUE - X509v3 Certificate Policies: - Policy: 1.3.171.1.1.1.10 - CPS: https://repository.luxtrust.lu - - X509v3 Key Usage: critical - Certificate Sign, CRL Sign - X509v3 Authority Key Identifier: - keyid:FF:18:28:76:F9:48:05:2C:A1:AE:F1:2B:1B:2B:B2:53:F8:4B:7C:B3 - - X509v3 Subject Key Identifier: - FF:18:28:76:F9:48:05:2C:A1:AE:F1:2B:1B:2B:B2:53:F8:4B:7C:B3 - Signature Algorithm: sha256WithRSAEncryption - 6a:19:14:ed:6e:79:c1:2c:87:d4:0d:70:7e:d7:f6:78:c9:0b: - 04:4e:c4:b1:ce:93:70:fe:b0:54:c0:32:cd:99:30:64:17:bf: - 0f:e5:e2:33:fd:07:36:40:72:0e:1a:b6:6a:59:d6:00:e5:68: - 20:dd:2e:72:0d:1f:6a:64:31:20:84:7d:49:a6:5a:37:eb:45: - c9:85:f5:d4:c7:17:99:07:e6:9b:55:e4:0c:e8:a9:b4:ce:8c: - 5b:b5:11:5c:cf:8a:0e:0d:d6:ac:77:81:fe:32:9c:24:9e:72: - ce:54:f3:d0:6f:a2:56:d6:ec:c3:37:2c:65:58:be:57:00:1a: - f2:35:fa:eb:7b:31:5d:c2:c1:12:3d:96:81:88:96:89:c1:59: - 5c:7a:e6:7f:70:34:e7:83:e2:b1:e1:e1:b8:58:ef:d4:95:e4: - 60:9c:f0:96:97:72:8c:eb:84:02:2e:65:8f:a4:b7:d2:7f:67: - dd:c8:d3:9e:5c:aa:a9:a4:a0:25:14:06:9b:ec:4f:7e:2d:0b: - 7f:1d:75:f1:33:d8:ed:ce:b8:75:6d:3e:5b:b9:98:1d:31:0d: - 56:d8:43:0f:30:91:b2:04:6b:dd:56:be:95:80:55:67:be:d8: - cd:83:d9:18:ee:2e:0f:86:2d:92:9e:70:13:ec:de:51:c9:43: - 78:02:a5:4d:c8:f9:5f:c4:91:58:46:16:77:5a:74:aa:40:bc: - 07:9f:30:b9:b1:f7:12:17:dd:e3:ff:24:40:1d:7a:6a:d1:4f: - 18:0a:aa:90:1d:eb:40:1e:df:a1:1e:44:92:10:9a:f2:8d:e1: - d1:4b:46:9e:e8:45:42:97:ea:45:99:f3:ec:66:d5:02:fa:f2: - a6:4a:24:aa:de:ce:b9:ca:f9:3f:93:6f:f9:a3:ba:ea:a5:3e: - 99:ad:fd:ff:7b:99:f5:65:ee:f0:59:28:67:d7:90:95:a4:13: - 84:a9:84:c1:e8:ce:ce:75:93:63:1a:bc:3c:ea:d5:64:1f:2d: - 2a:12:39:c6:c3:5a:32:ed:47:91:16:0e:bc:38:c1:50:de:8f: - ca:2a:90:34:1c:ee:41:94:9c:5e:19:2e:f8:45:49:99:74:91: - b0:04:6f:e3:04:5a:b1:ab:2a:ab:fe:c7:d0:96:b6:da:e1:4a: - 64:06:6e:60:4d:bd:42:4e:ff:78:da:24:ca:1b:b4:d7:96:39: - 6c:ae:f1:0e:aa:a7:7d:48:8b:20:4c:cf:64:d6:b8:97:46:b0: - 4e:d1:2a:56:3a:a0:93:bd:af:80:24:e0:0a:7e:e7:ca:d5:ca: - e8:85:55:dc:36:2a:e1:94:68:93:c7:66:72:44:0f:80:21:32: - 6c:25:c7:23:80:83:0a:eb ------BEGIN CERTIFICATE----- -MIIFwzCCA6ugAwIBAgIUCn6m30tEntpqJIWe5rgV0xZ/u7EwDQYJKoZIhvcNAQEL -BQAwRjELMAkGA1UEBhMCTFUxFjAUBgNVBAoMDUx1eFRydXN0IFMuQS4xHzAdBgNV -BAMMFkx1eFRydXN0IEdsb2JhbCBSb290IDIwHhcNMTUwMzA1MTMyMTU3WhcNMzUw -MzA1MTMyMTU3WjBGMQswCQYDVQQGEwJMVTEWMBQGA1UECgwNTHV4VHJ1c3QgUy5B -LjEfMB0GA1UEAwwWTHV4VHJ1c3QgR2xvYmFsIFJvb3QgMjCCAiIwDQYJKoZIhvcN -AQEBBQADggIPADCCAgoCggIBANeFl78RmOnwYoNMPIf5U2o3C/IPPIfOb9wmKb3F -ibrJgz337spbxm1Jc7TJRqMbNBM/wYlFV/TZsfs2ZUv7COJIcRHIbjuend+JZTem -hfY7RBi2xjcwYkSSl2l9QjAk5A0MiWtj3sXh306pFGxT4GHO9hcvHTy95iJMHZP1 -EMShduxq3sVs35a0VkBCwGKSMKEtFZSg0iAGCW5qbeXrt77U8PEVfIvmTroTzEsn -Xpk8F12PgX8zPU/TPxvsXD/wPEx1bvKm1Z3aLQdjAsZy6ZS8TEmVT4hSyNvoaYL4 -zDRbIvCGp4m9SAptZoFtyMhk+wHh9OHe2Z7d21vUKpkmFRseTJIpgp7VkoGSQXAZ -96Tlk0u8d2cx3Rz9MXANF5kM+Qw5GSoXtTBxVdUPrljhPS80m8+f9niFwpN6cj5m -j5wWEWCPnolvZ77gR1o7DJpni89Gxq44o/KnvObWhWszJHAiS8sIm7vI+AIpHb4g -DEa/a4ebsypmQjVGbKq6rfmYe+lQVRQxv7HaLe2ArWgk+2mr2HETMOZns4dA/Yl+ -8kPREd8vZS9kzl8UubG/Mb2HeFpZZYiq/FkySIbWTLkpS5XTdvN3JW1CHDiDTf2j -X5t/Lax5Gw5CMZdjpPuKadUiDTSQMC6otOBttpSsvItO13D8xTiOZCXhTTmQzsmH -hFhxAgMBAAGjgagwgaUwDwYDVR0TAQH/BAUwAwEB/zBCBgNVHSAEOzA5MDcGByuB -KwEBAQowLDAqBggrBgEFBQcCARYeaHR0cHM6Ly9yZXBvc2l0b3J5Lmx1eHRydXN0 -Lmx1MA4GA1UdDwEB/wQEAwIBBjAfBgNVHSMEGDAWgBT/GCh2+UgFLKGu8SsbK7JT -+Et8szAdBgNVHQ4EFgQU/xgodvlIBSyhrvErGyuyU/hLfLMwDQYJKoZIhvcNAQEL -BQADggIBAGoZFO1uecEsh9QNcH7X9njJCwROxLHOk3D+sFTAMs2ZMGQXvw/l4jP9 -BzZAcg4atmpZ1gDlaCDdLnINH2pkMSCEfUmmWjfrRcmF9dTHF5kH5ptV5AzoqbTO -jFu1EVzPig4N1qx3gf4ynCSecs5U89BvolbW7MM3LGVYvlcAGvI1+ut7MV3CwRI9 -loGIlonBWVx65n9wNOeD4rHh4bhY79SV5GCc8JaXcozrhAIuZY+kt9J/Z93I055c -qqmkoCUUBpvsT34tC38ddfEz2O3OuHVtPlu5mB0xDVbYQw8wkbIEa91WvpWAVWe+ -2M2D2RjuLg+GLZKecBPs3lHJQ3gCpU3I+V/EkVhGFndadKpAvAefMLmx9xIX3eP/ -JEAdemrRTxgKqpAd60Ae36EeRJIQmvKN4dFLRp7oRUKX6kWZ8+xm1QL68qZKJKre -zrnK+T+Tb/mjuuqlPpmt/f97mfVl7vBZKGfXkJWkE4SphMHozs51k2MavDzq1WQf -LSoSOcbDWjLtR5EWDrw4wVDej8oqkDQc7kGUnF4ZLvhFSZl0kbAEb+MEWrGrKqv+ -x9CWttrhSmQGbmBNvUJO/3jaJMobtNeWOWyu8Q6qp31IiyBMz2TWuJdGsE7RKlY6 -oJO9r4Ak4Ap+58rVyuiFVdw2KuGUaJPHZnJED4AhMmwlxyOAgwrr ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: - c2:7e:43:04:4e:47:3f:19 - Signature Algorithm: sha256WithRSAEncryption - Issuer: C=HU, L=Budapest, O=Microsec Ltd., CN=Microsec e-Szigno Root CA 2009/emailAddress=info@e-szigno.hu - Validity - Not Before: Jun 16 11:30:18 2009 GMT - Not After : Dec 30 11:30:18 2029 GMT - Subject: C=HU, L=Budapest, O=Microsec Ltd., CN=Microsec e-Szigno Root CA 2009/emailAddress=info@e-szigno.hu - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (2048 bit) - Modulus: - 00:e9:f8:8f:f3:63:ad:da:86:d8:a7:e0:42:fb:cf: - 91:de:a6:26:f8:99:a5:63:70:ad:9b:ae:ca:33:40: - 7d:6d:96:6e:a1:0e:44:ee:e1:13:9d:94:42:52:9a: - bd:75:85:74:2c:a8:0e:1d:93:b6:18:b7:8c:2c:a8: - cf:fb:5c:71:b9:da:ec:fe:e8:7e:8f:e4:2f:1d:b2: - a8:75:87:d8:b7:a1:e5:3b:cf:99:4a:46:d0:83:19: - 7d:c0:a1:12:1c:95:6d:4a:f4:d8:c7:a5:4d:33:2e: - 85:39:40:75:7e:14:7c:80:12:98:50:c7:41:67:b8: - a0:80:61:54:a6:6c:4e:1f:e0:9d:0e:07:e9:c9:ba: - 33:e7:fe:c0:55:28:2c:02:80:a7:19:f5:9e:dc:55: - 53:03:97:7b:07:48:ff:99:fb:37:8a:24:c4:59:cc: - 50:10:63:8e:aa:a9:1a:b0:84:1a:86:f9:5f:bb:b1: - 50:6e:a4:d1:0a:cc:d5:71:7e:1f:a7:1b:7c:f5:53: - 6e:22:5f:cb:2b:e6:d4:7c:5d:ae:d6:c2:c6:4c:e5: - 05:01:d9:ed:57:fc:c1:23:79:fc:fa:c8:24:83:95: - f3:b5:6a:51:01:d0:77:d6:e9:12:a1:f9:1a:83:fb: - 82:1b:b9:b0:97:f4:76:06:33:43:49:a0:ff:0b:b5: - fa:b5 - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Basic Constraints: critical - CA:TRUE - X509v3 Key Usage: critical - Certificate Sign, CRL Sign - X509v3 Subject Key Identifier: - CB:0F:C6:DF:42:43:CC:3D:CB:B5:48:23:A1:1A:7A:A6:2A:BB:34:68 - X509v3 Authority Key Identifier: - keyid:CB:0F:C6:DF:42:43:CC:3D:CB:B5:48:23:A1:1A:7A:A6:2A:BB:34:68 - - X509v3 Subject Alternative Name: - email:info@e-szigno.hu - Signature Algorithm: sha256WithRSAEncryption - c9:d1:0e:5e:2e:d5:cc:b3:7c:3e:cb:fc:3d:ff:0d:28:95:93: - 04:c8:bf:da:cd:79:b8:43:90:f0:a4:be:ef:f2:ef:21:98:bc: - d4:d4:5d:06:f6:ee:42:ec:30:6c:a0:aa:a9:ca:f1:af:8a:fa: - 3f:0b:73:6a:3e:ea:2e:40:7e:1f:ae:54:61:79:eb:2e:08:37: - d7:23:f3:8c:9f:be:1d:b1:e1:a4:75:db:a0:e2:54:14:b1:ba: - 1c:29:a4:18:f6:12:ba:a2:14:14:e3:31:35:c8:40:ff:b7:e0: - 05:76:57:c1:1c:59:f2:f8:bf:e4:ed:25:62:5c:84:f0:7e:7e: - 1f:b3:be:f9:b7:21:11:cc:03:01:56:70:a7:10:92:1e:1b:34: - 81:1e:ad:9c:1a:c3:04:3c:ed:02:61:d6:1e:06:f3:5f:3a:87: - f2:2b:f1:45:87:e5:3d:ac:d1:c7:57:84:bd:6b:ae:dc:d8:f9: - b6:1b:62:70:0b:3d:36:c9:42:f2:32:d7:7a:61:e6:d2:db:3d: - cf:c8:a9:c9:9b:dc:db:58:44:d7:6f:38:af:7f:78:d3:a3:ad: - 1a:75:ba:1c:c1:36:7c:8f:1e:6d:1c:c3:75:46:ae:35:05:a6: - f6:5c:3d:21:ee:56:f0:c9:82:22:2d:7a:54:ab:70:c3:7d:22: - 65:82:70:96 ------BEGIN CERTIFICATE----- -MIIECjCCAvKgAwIBAgIJAMJ+QwRORz8ZMA0GCSqGSIb3DQEBCwUAMIGCMQswCQYD -VQQGEwJIVTERMA8GA1UEBwwIQnVkYXBlc3QxFjAUBgNVBAoMDU1pY3Jvc2VjIEx0 -ZC4xJzAlBgNVBAMMHk1pY3Jvc2VjIGUtU3ppZ25vIFJvb3QgQ0EgMjAwOTEfMB0G -CSqGSIb3DQEJARYQaW5mb0BlLXN6aWduby5odTAeFw0wOTA2MTYxMTMwMThaFw0y -OTEyMzAxMTMwMThaMIGCMQswCQYDVQQGEwJIVTERMA8GA1UEBwwIQnVkYXBlc3Qx -FjAUBgNVBAoMDU1pY3Jvc2VjIEx0ZC4xJzAlBgNVBAMMHk1pY3Jvc2VjIGUtU3pp -Z25vIFJvb3QgQ0EgMjAwOTEfMB0GCSqGSIb3DQEJARYQaW5mb0BlLXN6aWduby5o -dTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAOn4j/NjrdqG2KfgQvvP -kd6mJviZpWNwrZuuyjNAfW2WbqEORO7hE52UQlKavXWFdCyoDh2Tthi3jCyoz/tc -cbna7P7ofo/kLx2yqHWH2Leh5TvPmUpG0IMZfcChEhyVbUr02MelTTMuhTlAdX4U -fIASmFDHQWe4oIBhVKZsTh/gnQ4H6cm6M+f+wFUoLAKApxn1ntxVUwOXewdI/5n7 -N4okxFnMUBBjjqqpGrCEGob5X7uxUG6k0QrM1XF+H6cbfPVTbiJfyyvm1HxdrtbC -xkzlBQHZ7Vf8wSN5/PrIJIOV87VqUQHQd9bpEqH5GoP7ghu5sJf0dgYzQ0mg/wu1 -+rUCAwEAAaOBgDB+MA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgEGMB0G -A1UdDgQWBBTLD8bfQkPMPcu1SCOhGnqmKrs0aDAfBgNVHSMEGDAWgBTLD8bfQkPM -Pcu1SCOhGnqmKrs0aDAbBgNVHREEFDASgRBpbmZvQGUtc3ppZ25vLmh1MA0GCSqG -SIb3DQEBCwUAA4IBAQDJ0Q5eLtXMs3w+y/w9/w0olZMEyL/azXm4Q5DwpL7v8u8h -mLzU1F0G9u5C7DBsoKqpyvGvivo/C3NqPuouQH4frlRheesuCDfXI/OMn74dseGk -ddug4lQUsbocKaQY9hK6ohQU4zE1yED/t+AFdlfBHFny+L/k7SViXITwfn4fs775 -tyERzAMBVnCnEJIeGzSBHq2cGsMEPO0CYdYeBvNfOofyK/FFh+U9rNHHV4S9a67c -2Pm2G2JwCz02yULyMtd6YebS2z3PyKnJm9zbWETXbzivf3jTo60adbocwTZ8jx5t -HMN1Rq41Bab2XD0h7lbwyYIiLXpUq3DDfSJlgnCW ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: - 49:41:2c:e4:00:10 - Signature Algorithm: sha256WithRSAEncryption - Issuer: C=HU, L=Budapest, O=NetLock Kft., OU=Tan\xC3\xBAs\xC3\xADtv\xC3\xA1nykiad\xC3\xB3k (Certification Services), CN=NetLock Arany (Class Gold) F\xC5\x91tan\xC3\xBAs\xC3\xADtv\xC3\xA1ny - Validity - Not Before: Dec 11 15:08:21 2008 GMT - Not After : Dec 6 15:08:21 2028 GMT - Subject: C=HU, L=Budapest, O=NetLock Kft., OU=Tan\xC3\xBAs\xC3\xADtv\xC3\xA1nykiad\xC3\xB3k (Certification Services), CN=NetLock Arany (Class Gold) F\xC5\x91tan\xC3\xBAs\xC3\xADtv\xC3\xA1ny - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (2048 bit) - Modulus: - 00:c4:24:5e:73:be:4b:6d:14:c3:a1:f4:e3:97:90: - 6e:d2:30:45:1e:3c:ee:67:d9:64:e0:1a:8a:7f:ca: - 30:ca:83:e3:20:c1:e3:f4:3a:d3:94:5f:1a:7c:5b: - 6d:bf:30:4f:84:27:f6:9f:1f:49:bc:c6:99:0a:90: - f2:0f:f5:7f:43:84:37:63:51:8b:7a:a5:70:fc:7a: - 58:cd:8e:9b:ed:c3:46:6c:84:70:5d:da:f3:01:90: - 23:fc:4e:30:a9:7e:e1:27:63:e7:ed:64:3c:a0:b8: - c9:33:63:fe:16:90:ff:b0:b8:fd:d7:a8:c0:c0:94: - 43:0b:b6:d5:59:a6:9e:56:d0:24:1f:70:79:af:db: - 39:54:0d:65:75:d9:15:41:94:01:af:5e:ec:f6:8d: - f1:ff:ad:64:fe:20:9a:d7:5c:eb:fe:a6:1f:08:64: - a3:8b:76:55:ad:1e:3b:28:60:2e:87:25:e8:aa:af: - 1f:c6:64:46:20:b7:70:7f:3c:de:48:db:96:53:b7: - 39:77:e4:1a:e2:c7:16:84:76:97:5b:2f:bb:19:15: - 85:f8:69:85:f5:99:a7:a9:f2:34:a7:a9:b6:a6:03: - fc:6f:86:3d:54:7c:76:04:9b:6b:f9:40:5d:00:34: - c7:2e:99:75:9d:e5:88:03:aa:4d:f8:03:d2:42:76: - c0:1b - Exponent: 43147 (0xa88b) - X509v3 extensions: - X509v3 Basic Constraints: critical - CA:TRUE, pathlen:4 - X509v3 Key Usage: critical - Certificate Sign, CRL Sign - X509v3 Subject Key Identifier: - CC:FA:67:93:F0:B6:B8:D0:A5:C0:1E:F3:53:FD:8C:53:DF:83:D7:96 - Signature Algorithm: sha256WithRSAEncryption - ab:7f:ee:1c:16:a9:9c:3c:51:00:a0:c0:11:08:05:a7:99:e6: - 6f:01:88:54:61:6e:f1:b9:18:ad:4a:ad:fe:81:40:23:94:2f: - fb:75:7c:2f:28:4b:62:24:81:82:0b:f5:61:f1:1c:6e:b8:61: - 38:eb:81:fa:62:a1:3b:5a:62:d3:94:65:c4:e1:e6:6d:82:f8: - 2f:25:70:b2:21:26:c1:72:51:1f:8c:2c:c3:84:90:c3:5a:8f: - ba:cf:f4:a7:65:a5:eb:98:d1:fb:05:b2:46:75:15:23:6a:6f: - 85:63:30:80:f0:d5:9e:1f:29:1c:c2:6c:b0:50:59:5d:90:5b: - 3b:a8:0d:30:cf:bf:7d:7f:ce:f1:9d:83:bd:c9:46:6e:20:a6: - f9:61:51:ba:21:2f:7b:be:a5:15:63:a1:d4:95:87:f1:9e:b9: - f3:89:f3:3d:85:b8:b8:db:be:b5:b9:29:f9:da:37:05:00:49: - 94:03:84:44:e7:bf:43:31:cf:75:8b:25:d1:f4:a6:64:f5:92: - f6:ab:05:eb:3d:e9:a5:0b:36:62:da:cc:06:5f:36:8b:b6:5e: - 31:b8:2a:fb:5e:f6:71:df:44:26:9e:c4:e6:0d:91:b4:2e:75: - 95:80:51:6a:4b:30:a6:b0:62:a1:93:f1:9b:d8:ce:c4:63:75: - 3f:59:47:b1 ------BEGIN CERTIFICATE----- -MIIEFTCCAv2gAwIBAgIGSUEs5AAQMA0GCSqGSIb3DQEBCwUAMIGnMQswCQYDVQQG -EwJIVTERMA8GA1UEBwwIQnVkYXBlc3QxFTATBgNVBAoMDE5ldExvY2sgS2Z0LjE3 -MDUGA1UECwwuVGFuw7pzw610dsOhbnlraWFkw7NrIChDZXJ0aWZpY2F0aW9uIFNl -cnZpY2VzKTE1MDMGA1UEAwwsTmV0TG9jayBBcmFueSAoQ2xhc3MgR29sZCkgRsWR -dGFuw7pzw610dsOhbnkwHhcNMDgxMjExMTUwODIxWhcNMjgxMjA2MTUwODIxWjCB -pzELMAkGA1UEBhMCSFUxETAPBgNVBAcMCEJ1ZGFwZXN0MRUwEwYDVQQKDAxOZXRM -b2NrIEtmdC4xNzA1BgNVBAsMLlRhbsO6c8OtdHbDoW55a2lhZMOzayAoQ2VydGlm -aWNhdGlvbiBTZXJ2aWNlcykxNTAzBgNVBAMMLE5ldExvY2sgQXJhbnkgKENsYXNz -IEdvbGQpIEbFkXRhbsO6c8OtdHbDoW55MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8A -MIIBCgKCAQEAxCRec75LbRTDofTjl5Bu0jBFHjzuZ9lk4BqKf8owyoPjIMHj9DrT -lF8afFttvzBPhCf2nx9JvMaZCpDyD/V/Q4Q3Y1GLeqVw/HpYzY6b7cNGbIRwXdrz -AZAj/E4wqX7hJ2Pn7WQ8oLjJM2P+FpD/sLj916jAwJRDC7bVWaaeVtAkH3B5r9s5 -VA1lddkVQZQBr17s9o3x/61k/iCa11zr/qYfCGSji3ZVrR47KGAuhyXoqq8fxmRG -ILdwfzzeSNuWU7c5d+Qa4scWhHaXWy+7GRWF+GmF9ZmnqfI0p6m2pgP8b4Y9VHx2 -BJtr+UBdADTHLpl1neWIA6pN+APSQnbAGwIDAKiLo0UwQzASBgNVHRMBAf8ECDAG -AQH/AgEEMA4GA1UdDwEB/wQEAwIBBjAdBgNVHQ4EFgQUzPpnk/C2uNClwB7zU/2M -U9+D15YwDQYJKoZIhvcNAQELBQADggEBAKt/7hwWqZw8UQCgwBEIBaeZ5m8BiFRh -bvG5GK1Krf6BQCOUL/t1fC8oS2IkgYIL9WHxHG64YTjrgfpioTtaYtOUZcTh5m2C -+C8lcLIhJsFyUR+MLMOEkMNaj7rP9KdlpeuY0fsFskZ1FSNqb4VjMIDw1Z4fKRzC -bLBQWV2QWzuoDTDPv31/zvGdg73JRm4gpvlhUbohL3u+pRVjodSVh/GeufOJ8z2F -uLjbvrW5KfnaNwUASZQDhETnv0Mxz3WLJdH0pmT1kvarBes96aULNmLazAZfNou2 -XjG4Kvte9nHfRCaexOYNkbQudZWAUWpLMKawYqGT8ZvYzsRjdT9ZR7E= ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: - 57:cb:33:6f:c2:5c:16:e6:47:16:17:e3:90:31:68:e0 - Signature Algorithm: sha1WithRSAEncryption - Issuer: C=US, O=Network Solutions L.L.C., CN=Network Solutions Certificate Authority - Validity - Not Before: Dec 1 00:00:00 2006 GMT - Not After : Dec 31 23:59:59 2029 GMT - Subject: C=US, O=Network Solutions L.L.C., CN=Network Solutions Certificate Authority - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (2048 bit) - Modulus: - 00:e4:bc:7e:92:30:6d:c6:d8:8e:2b:0b:bc:46:ce: - e0:27:96:de:de:f9:fa:12:d3:3c:33:73:b3:04:2f: - bc:71:8c:e5:9f:b6:22:60:3e:5f:5d:ce:09:ff:82: - 0c:1b:9a:51:50:1a:26:89:dd:d5:61:5d:19:dc:12: - 0f:2d:0a:a2:43:5d:17:d0:34:92:20:ea:73:cf:38: - 2c:06:26:09:7a:72:f7:fa:50:32:f8:c2:93:d3:69: - a2:23:ce:41:b1:cc:e4:d5:1f:36:d1:8a:3a:f8:8c: - 63:e2:14:59:69:ed:0d:d3:7f:6b:e8:b8:03:e5:4f: - 6a:e5:98:63:69:48:05:be:2e:ff:33:b6:e9:97:59: - 69:f8:67:19:ae:93:61:96:44:15:d3:72:b0:3f:bc: - 6a:7d:ec:48:7f:8d:c3:ab:aa:71:2b:53:69:41:53: - 34:b5:b0:b9:c5:06:0a:c4:b0:45:f5:41:5d:6e:89: - 45:7b:3d:3b:26:8c:74:c2:e5:d2:d1:7d:b2:11:d4: - fb:58:32:22:9a:80:c9:dc:fd:0c:e9:7f:5e:03:97: - ce:3b:00:14:87:27:70:38:a9:8e:6e:b3:27:76:98: - 51:e0:05:e3:21:ab:1a:d5:85:22:3c:29:b5:9a:16: - c5:80:a8:f4:bb:6b:30:8f:2f:46:02:a2:b1:0c:22: - e0:d3 - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Subject Key Identifier: - 21:30:C9:FB:00:D7:4E:98:DA:87:AA:2A:D0:A7:2E:B1:40:31:A7:4C - X509v3 Key Usage: critical - Certificate Sign, CRL Sign - X509v3 Basic Constraints: critical - CA:TRUE - X509v3 CRL Distribution Points: - - Full Name: - URI:http://crl.netsolssl.com/NetworkSolutionsCertificateAuthority.crl - - Signature Algorithm: sha1WithRSAEncryption - bb:ae:4b:e7:b7:57:eb:7f:aa:2d:b7:73:47:85:6a:c1:e4:a5: - 1d:e4:e7:3c:e9:f4:59:65:77:b5:7a:5b:5a:8d:25:36:e0:7a: - 97:2e:38:c0:57:60:83:98:06:83:9f:b9:76:7a:6e:50:e0:ba: - 88:2c:fc:45:cc:18:b0:99:95:51:0e:ec:1d:b8:88:ff:87:50: - 1c:82:c2:e3:e0:32:80:bf:a0:0b:47:c8:c3:31:ef:99:67:32: - 80:4f:17:21:79:0c:69:5c:de:5e:34:ae:02:b5:26:ea:50:df: - 7f:18:65:2c:c9:f2:63:e1:a9:07:fe:7c:71:1f:6b:33:24:6a: - 1e:05:f7:05:68:c0:6a:12:cb:2e:5e:61:cb:ae:28:d3:7e:c2: - b4:66:91:26:5f:3c:2e:24:5f:cb:58:0f:eb:28:ec:af:11:96: - f3:dc:7b:6f:c0:a7:88:f2:53:77:b3:60:5e:ae:ae:28:da:35: - 2c:6f:34:45:d3:26:e1:de:ec:5b:4f:27:6b:16:7c:bd:44:04: - 18:82:b3:89:79:17:10:71:3d:7a:a2:16:4e:f5:01:cd:a4:6c: - 65:68:a1:49:76:5c:43:c9:d8:bc:36:67:6c:a5:94:b5:d4:cc: - b9:bd:6a:35:56:21:de:d8:c3:eb:fb:cb:a4:60:4c:b0:55:a0: - a0:7b:57:b2 ------BEGIN CERTIFICATE----- -MIID5jCCAs6gAwIBAgIQV8szb8JcFuZHFhfjkDFo4DANBgkqhkiG9w0BAQUFADBi -MQswCQYDVQQGEwJVUzEhMB8GA1UEChMYTmV0d29yayBTb2x1dGlvbnMgTC5MLkMu -MTAwLgYDVQQDEydOZXR3b3JrIFNvbHV0aW9ucyBDZXJ0aWZpY2F0ZSBBdXRob3Jp -dHkwHhcNMDYxMjAxMDAwMDAwWhcNMjkxMjMxMjM1OTU5WjBiMQswCQYDVQQGEwJV -UzEhMB8GA1UEChMYTmV0d29yayBTb2x1dGlvbnMgTC5MLkMuMTAwLgYDVQQDEydO -ZXR3b3JrIFNvbHV0aW9ucyBDZXJ0aWZpY2F0ZSBBdXRob3JpdHkwggEiMA0GCSqG -SIb3DQEBAQUAA4IBDwAwggEKAoIBAQDkvH6SMG3G2I4rC7xGzuAnlt7e+foS0zwz -c7MEL7xxjOWftiJgPl9dzgn/ggwbmlFQGiaJ3dVhXRncEg8tCqJDXRfQNJIg6nPP -OCwGJgl6cvf6UDL4wpPTaaIjzkGxzOTVHzbRijr4jGPiFFlp7Q3Tf2vouAPlT2rl -mGNpSAW+Lv8ztumXWWn4Zxmuk2GWRBXTcrA/vGp97Eh/jcOrqnErU2lBUzS1sLnF -BgrEsEX1QV1uiUV7PTsmjHTC5dLRfbIR1PtYMiKagMnc/Qzpf14Dl847ABSHJ3A4 -qY5usyd2mFHgBeMhqxrVhSI8KbWaFsWAqPS7azCPL0YCorEMIuDTAgMBAAGjgZcw -gZQwHQYDVR0OBBYEFCEwyfsA106Y2oeqKtCnLrFAMadMMA4GA1UdDwEB/wQEAwIB -BjAPBgNVHRMBAf8EBTADAQH/MFIGA1UdHwRLMEkwR6BFoEOGQWh0dHA6Ly9jcmwu -bmV0c29sc3NsLmNvbS9OZXR3b3JrU29sdXRpb25zQ2VydGlmaWNhdGVBdXRob3Jp -dHkuY3JsMA0GCSqGSIb3DQEBBQUAA4IBAQC7rkvnt1frf6ott3NHhWrB5KUd5Oc8 -6fRZZXe1eltajSU24HqXLjjAV2CDmAaDn7l2em5Q4LqILPxFzBiwmZVRDuwduIj/ -h1AcgsLj4DKAv6ALR8jDMe+ZZzKATxcheQxpXN5eNK4CtSbqUN9/GGUsyfJj4akH -/nxxH2szJGoeBfcFaMBqEssuXmHLrijTfsK0ZpEmXzwuJF/LWA/rKOyvEZbz3Htv -wKeI8lN3s2Berq4o2jUsbzRF0ybh3uxbTydrFny9RAQYgrOJeRcQcT16ohZO9QHN -pGxlaKFJdlxDydi8NmdspZS11My5vWo1ViHe2MPr+8ukYEywVaCge1ey ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: - 41:3d:72:c7:f4:6b:1f:81:43:7d:f1:d2:28:54:df:9a - Signature Algorithm: sha1WithRSAEncryption - Issuer: C=CH, O=WISeKey, OU=Copyright (c) 2005, OU=OISTE Foundation Endorsed, CN=OISTE WISeKey Global Root GA CA - Validity - Not Before: Dec 11 16:03:44 2005 GMT - Not After : Dec 11 16:09:51 2037 GMT - Subject: C=CH, O=WISeKey, OU=Copyright (c) 2005, OU=OISTE Foundation Endorsed, CN=OISTE WISeKey Global Root GA CA - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (2048 bit) - Modulus: - 00:cb:4f:b3:00:9b:3d:36:dd:f9:d1:49:6a:6b:10: - 49:1f:ec:d8:2b:b2:c6:f8:32:81:29:43:95:4c:9a: - 19:23:21:15:45:de:e3:c8:1c:51:55:5b:ae:93:e8: - 37:ff:2b:6b:e9:d4:ea:be:2a:dd:a8:51:2b:d7:66: - c3:61:5c:60:02:c8:f5:ce:72:7b:3b:b8:f2:4e:65: - 08:9a:cd:a4:6a:19:c1:01:bb:73:a6:d7:f6:c3:dd: - cd:bc:a4:8b:b5:99:61:b8:01:a2:a3:d4:4d:d4:05: - 3d:91:ad:f8:b4:08:71:64:af:70:f1:1c:6b:7e:f6: - c3:77:9d:24:73:7b:e4:0c:8c:e1:d9:36:e1:99:8b: - 05:99:0b:ed:45:31:09:ca:c2:00:db:f7:72:a0:96: - aa:95:87:d0:8e:c7:b6:61:73:0d:76:66:8c:dc:1b: - b4:63:a2:9f:7f:93:13:30:f1:a1:27:db:d9:ff:2c: - 55:88:91:a0:e0:4f:07:b0:28:56:8c:18:1b:97:44: - 8e:89:dd:e0:17:6e:e7:2a:ef:8f:39:0a:31:84:82: - d8:40:14:49:2e:7a:41:e4:a7:fe:e3:64:cc:c1:59: - 71:4b:2c:21:a7:5b:7d:e0:1d:d1:2e:81:9b:c3:d8: - 68:f7:bd:96:1b:ac:70:b1:16:14:0b:db:60:b9:26: - 01:05 - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Key Usage: - Digital Signature, Certificate Sign, CRL Sign - X509v3 Basic Constraints: critical - CA:TRUE - X509v3 Subject Key Identifier: - B3:03:7E:AE:36:BC:B0:79:D1:DC:94:26:B6:11:BE:21:B2:69:86:94 - 1.3.6.1.4.1.311.21.1: - ... - Signature Algorithm: sha1WithRSAEncryption - 4b:a1:ff:0b:87:6e:b3:f9:c1:43:b1:48:f3:28:c0:1d:2e:c9: - 09:41:fa:94:00:1c:a4:a4:ab:49:4f:8f:3d:1e:ef:4d:6f:bd: - bc:a4:f6:f2:26:30:c9:10:ca:1d:88:fb:74:19:1f:85:45:bd: - b0:6c:51:f9:36:7e:db:f5:4c:32:3a:41:4f:5b:47:cf:e8:0b: - 2d:b6:c4:19:9d:74:c5:47:c6:3b:6a:0f:ac:14:db:3c:f4:73: - 9c:a9:05:df:00:dc:74:78:fa:f8:35:60:59:02:13:18:7c:bc: - fb:4d:b0:20:6d:43:bb:60:30:7a:67:33:5c:c5:99:d1:f8:2d: - 39:52:73:fb:8c:aa:97:25:5c:72:d9:08:1e:ab:4e:3c:e3:81: - 31:9f:03:a6:fb:c0:fe:29:88:55:da:84:d5:50:03:b6:e2:84: - a3:a6:36:aa:11:3a:01:e1:18:4b:d6:44:68:b3:3d:f9:53:74: - 84:b3:46:91:46:96:00:b7:80:2c:b6:e1:e3:10:e2:db:a2:e7: - 28:8f:01:96:62:16:3e:00:e3:1c:a5:36:81:18:a2:4c:52:76: - c0:11:a3:6e:e6:1d:ba:e3:5a:be:36:53:c5:3e:75:8f:86:69: - 29:58:53:b5:9c:bb:6f:9f:5c:c5:18:ec:dd:2f:e1:98:c9:fc: - be:df:0a:0d ------BEGIN CERTIFICATE----- -MIID8TCCAtmgAwIBAgIQQT1yx/RrH4FDffHSKFTfmjANBgkqhkiG9w0BAQUFADCB -ijELMAkGA1UEBhMCQ0gxEDAOBgNVBAoTB1dJU2VLZXkxGzAZBgNVBAsTEkNvcHly -aWdodCAoYykgMjAwNTEiMCAGA1UECxMZT0lTVEUgRm91bmRhdGlvbiBFbmRvcnNl -ZDEoMCYGA1UEAxMfT0lTVEUgV0lTZUtleSBHbG9iYWwgUm9vdCBHQSBDQTAeFw0w -NTEyMTExNjAzNDRaFw0zNzEyMTExNjA5NTFaMIGKMQswCQYDVQQGEwJDSDEQMA4G -A1UEChMHV0lTZUtleTEbMBkGA1UECxMSQ29weXJpZ2h0IChjKSAyMDA1MSIwIAYD -VQQLExlPSVNURSBGb3VuZGF0aW9uIEVuZG9yc2VkMSgwJgYDVQQDEx9PSVNURSBX -SVNlS2V5IEdsb2JhbCBSb290IEdBIENBMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8A -MIIBCgKCAQEAy0+zAJs9Nt350UlqaxBJH+zYK7LG+DKBKUOVTJoZIyEVRd7jyBxR -VVuuk+g3/ytr6dTqvirdqFEr12bDYVxgAsj1znJ7O7jyTmUIms2kahnBAbtzptf2 -w93NvKSLtZlhuAGio9RN1AU9ka34tAhxZK9w8RxrfvbDd50kc3vkDIzh2TbhmYsF -mQvtRTEJysIA2/dyoJaqlYfQjse2YXMNdmaM3Bu0Y6Kff5MTMPGhJ9vZ/yxViJGg -4E8HsChWjBgbl0SOid3gF27nKu+POQoxhILYQBRJLnpB5Kf+42TMwVlxSywhp1t9 -4B3RLoGbw9ho972WG6xwsRYUC9tguSYBBQIDAQABo1EwTzALBgNVHQ8EBAMCAYYw -DwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUswN+rja8sHnR3JQmthG+IbJphpQw -EAYJKwYBBAGCNxUBBAMCAQAwDQYJKoZIhvcNAQEFBQADggEBAEuh/wuHbrP5wUOx -SPMowB0uyQlB+pQAHKSkq0lPjz0e701vvbyk9vImMMkQyh2I+3QZH4VFvbBsUfk2 -ftv1TDI6QU9bR8/oCy22xBmddMVHxjtqD6wU2zz0c5ypBd8A3HR4+vg1YFkCExh8 -vPtNsCBtQ7tgMHpnM1zFmdH4LTlSc/uMqpclXHLZCB6rTjzjgTGfA6b7wP4piFXa -hNVQA7bihKOmNqoROgHhGEvWRGizPflTdISzRpFGlgC3gCy24eMQ4tui5yiPAZZi -Fj4A4xylNoEYokxSdsARo27mHbrjWr42U8U+dY+GaSlYU7Wcu2+fXMUY7N0v4ZjJ -/L7fCg0= ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: - 76:b1:20:52:74:f0:85:87:46:b3:f8:23:1a:f6:c2:c0 - Signature Algorithm: sha256WithRSAEncryption - Issuer: C=CH, O=WISeKey, OU=OISTE Foundation Endorsed, CN=OISTE WISeKey Global Root GB CA - Validity - Not Before: Dec 1 15:00:32 2014 GMT - Not After : Dec 1 15:10:31 2039 GMT - Subject: C=CH, O=WISeKey, OU=OISTE Foundation Endorsed, CN=OISTE WISeKey Global Root GB CA - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (2048 bit) - Modulus: - 00:d8:17:b7:1c:4a:24:2a:d6:97:b1:ca:e2:1e:fb: - 7d:38:ef:98:f5:b2:39:98:4e:27:b8:11:5d:7b:d2: - 25:94:88:82:15:26:6a:1b:31:bb:a8:5b:21:21:2b: - d8:0f:4e:9f:5a:f1:b1:5a:e4:79:d6:32:23:2b:e1: - 53:cc:99:45:5c:7b:4f:ad:bc:bf:87:4a:0b:4b:97: - 5a:a8:f6:48:ec:7d:7b:0d:cd:21:06:df:9e:15:fd: - 41:8a:48:b7:20:f4:a1:7a:1b:57:d4:5d:50:ff:ba: - 67:d8:23:99:1f:c8:3f:e3:de:ff:6f:5b:77:b1:6b: - 6e:b8:c9:64:f7:e1:ca:41:46:0e:29:71:d0:b9:23: - fc:c9:81:5f:4e:f7:6f:df:bf:84:ad:73:64:bb:b7: - 42:8e:69:f6:d4:76:1d:7e:9d:a7:b8:57:8a:51:67: - 72:d7:d4:a8:b8:95:54:40:73:03:f6:ea:f4:eb:fe: - 28:42:77:3f:9d:23:1b:b2:b6:3d:80:14:07:4c:2e: - 4f:f7:d5:0a:16:0d:bd:66:43:37:7e:23:43:79:c3: - 40:86:f5:4c:29:da:8e:9a:ad:0d:a5:04:87:88:1e: - 85:e3:e9:53:d5:9b:c8:8b:03:63:78:eb:e0:19:4a: - 6e:bb:2f:6b:33:64:58:93:ad:69:bf:8f:1b:ef:82: - 48:c7 - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Key Usage: - Digital Signature, Certificate Sign, CRL Sign - X509v3 Basic Constraints: critical - CA:TRUE - X509v3 Subject Key Identifier: - 35:0F:C8:36:63:5E:E2:A3:EC:F9:3B:66:15:CE:51:52:E3:91:9A:3D - 1.3.6.1.4.1.311.21.1: - ... - Signature Algorithm: sha256WithRSAEncryption - 40:4c:fb:87:b2:99:81:90:7e:9d:c5:b0:b0:26:cd:88:7b:2b: - 32:8d:6e:b8:21:71:58:97:7d:ae:37:14:af:3e:e7:f7:9a:e2: - 7d:f6:71:98:99:04:aa:43:74:78:a3:e3:49:61:3e:73:8c:4d: - 94:e0:f9:71:c4:b6:16:0e:53:78:1f:d6:a2:87:2f:02:39:81: - 29:3c:af:15:98:21:30:fe:28:90:00:8c:d1:e1:cb:fa:5e:c8: - fd:f8:10:46:3b:a2:78:42:91:17:74:55:0a:de:50:67:4d:66: - d1:a7:ff:fd:d9:c0:b5:a8:a3:8a:ce:66:f5:0f:43:cd:a7:2b: - 57:7b:63:46:6a:aa:2e:52:d8:f4:ed:e1:6d:ad:29:90:78:48: - ba:e1:23:aa:a3:89:ec:b5:ab:96:c0:b4:4b:a2:1d:97:9e:7a: - f2:6e:40:71:df:68:f1:65:4d:ce:7c:05:df:53:65:a9:a5:f0: - b1:97:04:70:15:46:03:98:d4:d2:bf:54:b4:a0:58:7d:52:6f: - da:56:26:62:d4:d8:db:89:31:6f:1c:f0:22:c2:d3:62:1c:35: - cd:4c:69:15:54:1a:90:98:de:eb:1e:5f:ca:77:c7:cb:8e:3d: - 43:69:9c:9a:58:d0:24:3b:df:1b:40:96:7e:35:ad:81:c7:4e: - 71:ba:88:13 ------BEGIN CERTIFICATE----- -MIIDtTCCAp2gAwIBAgIQdrEgUnTwhYdGs/gjGvbCwDANBgkqhkiG9w0BAQsFADBt -MQswCQYDVQQGEwJDSDEQMA4GA1UEChMHV0lTZUtleTEiMCAGA1UECxMZT0lTVEUg -Rm91bmRhdGlvbiBFbmRvcnNlZDEoMCYGA1UEAxMfT0lTVEUgV0lTZUtleSBHbG9i -YWwgUm9vdCBHQiBDQTAeFw0xNDEyMDExNTAwMzJaFw0zOTEyMDExNTEwMzFaMG0x -CzAJBgNVBAYTAkNIMRAwDgYDVQQKEwdXSVNlS2V5MSIwIAYDVQQLExlPSVNURSBG -b3VuZGF0aW9uIEVuZG9yc2VkMSgwJgYDVQQDEx9PSVNURSBXSVNlS2V5IEdsb2Jh -bCBSb290IEdCIENBMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA2Be3 -HEokKtaXscriHvt9OO+Y9bI5mE4nuBFde9IllIiCFSZqGzG7qFshISvYD06fWvGx -WuR51jIjK+FTzJlFXHtPrby/h0oLS5daqPZI7H17Dc0hBt+eFf1Biki3IPShehtX -1F1Q/7pn2COZH8g/497/b1t3sWtuuMlk9+HKQUYOKXHQuSP8yYFfTvdv37+ErXNk -u7dCjmn21HYdfp2nuFeKUWdy19SouJVUQHMD9ur06/4oQnc/nSMbsrY9gBQHTC5P -99UKFg29ZkM3fiNDecNAhvVMKdqOmq0NpQSHiB6F4+lT1ZvIiwNjeOvgGUpuuy9r -M2RYk61pv48b74JIxwIDAQABo1EwTzALBgNVHQ8EBAMCAYYwDwYDVR0TAQH/BAUw -AwEB/zAdBgNVHQ4EFgQUNQ/INmNe4qPs+TtmFc5RUuORmj0wEAYJKwYBBAGCNxUB -BAMCAQAwDQYJKoZIhvcNAQELBQADggEBAEBM+4eymYGQfp3FsLAmzYh7KzKNbrgh -cViXfa43FK8+5/ea4n32cZiZBKpDdHij40lhPnOMTZTg+XHEthYOU3gf1qKHLwI5 -gSk8rxWYITD+KJAAjNHhy/peyP34EEY7onhCkRd0VQreUGdNZtGn//3ZwLWoo4rO -ZvUPQ82nK1d7Y0Zqqi5S2PTt4W2tKZB4SLrhI6qjiey1q5bAtEuiHZeeevJuQHHf -aPFlTc58Bd9TZaml8LGXBHAVRgOY1NK/VLSgWH1Sb9pWJmLU2NuJMW8c8CLC02Ic -Nc1MaRVUGpCY3useX8p3x8uOPUNpnJpY0CQ73xtAln41rYHHTnG6iBM= ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: - 11:20:b3:90:55:39:7d:7f:36:6d:64:c2:a7:9f:6b:63:8e:67 - Signature Algorithm: sha256WithRSAEncryption - Issuer: C=FR, O=OpenTrust, CN=OpenTrust Root CA G1 - Validity - Not Before: May 26 08:45:50 2014 GMT - Not After : Jan 15 00:00:00 2038 GMT - Subject: C=FR, O=OpenTrust, CN=OpenTrust Root CA G1 - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (4096 bit) - Modulus: - 00:f8:79:46:da:96:c5:30:5e:8a:71:03:2d:70:a4: - bb:b0:c5:08:dc:cd:e6:35:c0:80:a4:11:2d:dd:e6: - 87:ae:5d:3d:91:d2:87:6c:37:b7:da:62:9e:9b:c2: - 24:d7:8f:f1:db:a6:a6:df:46:6f:51:a6:71:cb:3e: - 1b:31:67:62:f7:11:5b:34:27:d5:79:4e:8c:9b:58: - bd:22:10:0d:5c:27:0c:dd:30:e5:a8:d3:5d:21:38: - 74:17:fe:e3:1f:b6:4f:3b:6b:2d:db:7d:60:1f:8c: - 7d:4c:05:c2:eb:01:16:15:98:14:8e:d1:90:77:22: - 3f:ec:c2:39:b8:79:3a:f0:49:24:e2:95:91:dc:61: - 34:92:8c:54:74:ef:b1:7d:8c:01:e2:38:7d:c1:5f: - 6a:5f:24:b2:8e:62:17:ad:79:20:ad:ab:1d:b7:e0: - b4:96:48:4f:66:43:10:06:16:24:03:e1:e0:9c:8e: - c6:46:4f:8e:1a:99:e1:8f:b9:8e:33:6c:69:de:58: - ad:a0:0e:a7:64:54:11:69:44:66:4f:4c:12:a7:8e: - 2c:7d:c4:d4:5b:c5:00:34:30:c1:d9:99:fe:32:ce: - 07:84:b4:4e:cd:0a:ff:36:4d:62:f1:a7:63:57:e4: - db:6a:a7:ae:bf:2b:b9:c9:e6:b2:27:89:e5:7e:9a: - 1c:4d:68:c6:c1:18:de:33:2b:51:46:4b:1c:8e:f7: - 3d:0c:f9:8a:34:14:c4:fb:33:35:23:f1:cc:f1:2a: - c7:a5:bb:b0:a2:ce:fe:53:6b:4d:41:1b:66:28:b2: - 96:fa:a7:ae:0a:4e:b9:39:33:44:9c:74:c1:93:1c: - f8:e0:9e:24:25:43:f1:9b:23:82:aa:df:2c:20:b0: - dc:36:4e:03:b3:7c:02:d4:e6:7b:1a:aa:87:13:bf: - 3e:a1:74:bb:9b:0e:e1:c0:93:9f:d7:a4:66:ca:bb: - 1b:3b:e3:30:f4:33:59:8a:07:72:03:55:e7:73:6a: - 03:31:6e:6f:96:1b:e3:a2:9f:af:92:c7:ed:f5:42: - b7:25:4c:3b:13:04:cf:1c:96:af:1c:22:a3:d0:ab: - 05:b2:4c:12:23:52:dc:fd:19:5b:27:9c:1e:3b:7a: - fd:42:23:db:23:80:13:f0:bc:51:15:54:94:a6:77: - 3e:d0:74:51:bd:51:14:08:39:37:cb:1f:34:a9:30: - 9d:52:84:2e:55:90:b1:ba:df:55:00:0b:d8:56:2d: - b1:49:49:72:80:a9:62:d7:c0:f6:18:11:04:55:cd: - 74:7b:cf:61:70:79:f4:7b:2c:5c:5c:92:fc:e5:b8: - 5a:ab:4c:93:95:a1:27:ee:a5:be:cf:71:23:42:ba: - 9b:76:2d - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Key Usage: critical - Certificate Sign, CRL Sign - X509v3 Basic Constraints: critical - CA:TRUE - X509v3 Subject Key Identifier: - 97:46:21:57:21:35:DA:36:55:C7:F3:F1:37:70:E5:08:F6:93:29:B6 - X509v3 Authority Key Identifier: - keyid:97:46:21:57:21:35:DA:36:55:C7:F3:F1:37:70:E5:08:F6:93:29:B6 - - Signature Algorithm: sha256WithRSAEncryption - 1d:dd:02:60:7c:e0:35:a7:e6:98:7b:ea:44:ce:67:40:4f:f2: - 93:6e:66:d4:39:89:26:ac:d3:4d:04:3c:bb:87:21:3f:37:f4: - 71:25:da:4b:ba:ab:96:82:81:91:b6:ed:d9:b1:a4:65:97:e2: - 6f:64:59:a4:96:ee:60:ca:1f:23:fb:45:ba:ff:8f:24:f0:ca: - a9:31:7f:79:1f:80:b3:2d:32:ba:64:67:60:af:b9:59:cd:df: - 9a:49:d3:a8:82:b1:f9:98:94:8a:cc:e0:bb:e0:04:1b:99:60: - b1:46:65:dc:08:a2:b2:46:9e:44:88:ea:93:7e:57:16:d2:15: - 72:5f:2e:4b:ab:d4:9d:63:b8:e3:48:e5:fe:84:2e:58:0a:9f: - 43:1d:fe:b7:18:92:86:43:4b:0e:9c:32:86:2c:60:f5:e9:48: - ea:95:ed:70:29:f1:d5:2f:fd:35:b4:57:cf:db:85:48:99:b9: - c2:6f:6c:8f:cd:78:95:ac:64:28:fd:56:b0:c3:6f:c3:be:59: - 52:e1:5f:84:8f:80:f2:f4:0d:36:ad:76:b3:a3:b5:e1:64:76: - 3a:58:dc:7d:4f:5e:56:6c:e5:55:59:57:a5:df:f1:8a:66:30: - 8c:d4:52:62:38:77:b4:be:28:d7:ca:36:c4:9b:05:f0:f8:15: - db:db:f1:ef:34:9d:1d:78:4a:88:56:67:6e:60:ff:8f:c8:8b: - e1:8e:bd:42:a9:33:0a:59:42:12:12:2a:fa:b1:9d:43:8e:05: - 9b:99:da:62:ad:57:36:b3:1d:b6:0d:79:2d:96:b8:eb:f2:0c: - 4b:0c:a5:94:c6:30:a7:26:19:2d:ed:4c:06:50:30:f1:fd:58: - 3d:b9:4b:17:5f:19:b4:6a:84:54:b4:38:4f:39:a2:0d:96:68: - c3:28:94:fd:ed:2d:1f:4a:6b:43:96:2e:90:01:10:fb:38:a6: - 81:0b:d0:bf:75:d3:d4:b9:ce:f1:3f:6f:0e:1c:1e:37:71:e5: - 18:87:75:19:3f:50:b9:5e:a4:45:34:ad:b0:ca:e6:e5:13:76: - 0f:31:14:a9:8e:2d:94:d6:d5:85:4d:73:15:4f:4b:f2:b2:3e: - ed:6c:bd:fd:0e:9d:66:73:b0:3d:b4:f7:bf:a8:e0:11:a4:c4: - ae:75:09:4a:63:00:48:20:a6:c6:9d:0b:09:8a:b4:e0:e6:ce: - 3e:c7:3e:26:38:e9:2b:de:a6:08:49:03:04:90:8a:e9:8f:bf: - e8:b6:b4:2a:a3:23:8d:1c:1c:b2:39:92:a8:8f:02:5c:40:39: - 75:d4:73:41:02:77:de:cd:e0:43:87:d6:e4:ba:4a:c3:6c:12: - 7f:fe:2a:e6:23:d6:8c:71 ------BEGIN CERTIFICATE----- -MIIFbzCCA1egAwIBAgISESCzkFU5fX82bWTCp59rY45nMA0GCSqGSIb3DQEBCwUA -MEAxCzAJBgNVBAYTAkZSMRIwEAYDVQQKDAlPcGVuVHJ1c3QxHTAbBgNVBAMMFE9w -ZW5UcnVzdCBSb290IENBIEcxMB4XDTE0MDUyNjA4NDU1MFoXDTM4MDExNTAwMDAw -MFowQDELMAkGA1UEBhMCRlIxEjAQBgNVBAoMCU9wZW5UcnVzdDEdMBsGA1UEAwwU -T3BlblRydXN0IFJvb3QgQ0EgRzEwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIK -AoICAQD4eUbalsUwXopxAy1wpLuwxQjczeY1wICkES3d5oeuXT2R0odsN7faYp6b -wiTXj/HbpqbfRm9RpnHLPhsxZ2L3EVs0J9V5ToybWL0iEA1cJwzdMOWo010hOHQX -/uMftk87ay3bfWAfjH1MBcLrARYVmBSO0ZB3Ij/swjm4eTrwSSTilZHcYTSSjFR0 -77F9jAHiOH3BX2pfJLKOYheteSCtqx234LSWSE9mQxAGFiQD4eCcjsZGT44ameGP -uY4zbGneWK2gDqdkVBFpRGZPTBKnjix9xNRbxQA0MMHZmf4yzgeEtE7NCv82TWLx -p2NX5Ntqp66/K7nJ5rInieV+mhxNaMbBGN4zK1FGSxyO9z0M+Yo0FMT7MzUj8czx -Kselu7Cizv5Ta01BG2Yospb6p64KTrk5M0ScdMGTHPjgniQlQ/GbI4Kq3ywgsNw2 -TgOzfALU5nsaqocTvz6hdLubDuHAk5/XpGbKuxs74zD0M1mKB3IDVedzagMxbm+W -G+Oin6+Sx+31QrclTDsTBM8clq8cIqPQqwWyTBIjUtz9GVsnnB47ev1CI9sjgBPw -vFEVVJSmdz7QdFG9URQIOTfLHzSpMJ1ShC5VkLG631UAC9hWLbFJSXKAqWLXwPYY -EQRVzXR7z2FwefR7LFxckvzluFqrTJOVoSfupb7PcSNCupt2LQIDAQABo2MwYTAO -BgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUl0YhVyE1 -2jZVx/PxN3DlCPaTKbYwHwYDVR0jBBgwFoAUl0YhVyE12jZVx/PxN3DlCPaTKbYw -DQYJKoZIhvcNAQELBQADggIBAB3dAmB84DWn5ph76kTOZ0BP8pNuZtQ5iSas000E -PLuHIT839HEl2ku6q5aCgZG27dmxpGWX4m9kWaSW7mDKHyP7Rbr/jyTwyqkxf3kf -gLMtMrpkZ2CvuVnN35pJ06iCsfmYlIrM4LvgBBuZYLFGZdwIorJGnkSI6pN+VxbS -FXJfLkur1J1juONI5f6ELlgKn0Md/rcYkoZDSw6cMoYsYPXpSOqV7XAp8dUv/TW0 -V8/bhUiZucJvbI/NeJWsZCj9VrDDb8O+WVLhX4SPgPL0DTatdrOjteFkdjpY3H1P -XlZs5VVZV6Xf8YpmMIzUUmI4d7S+KNfKNsSbBfD4Fdvb8e80nR14SohWZ25g/4/I -i+GOvUKpMwpZQhISKvqxnUOOBZuZ2mKtVzazHbYNeS2WuOvyDEsMpZTGMKcmGS3t -TAZQMPH9WD25SxdfGbRqhFS0OE85og2WaMMolP3tLR9Ka0OWLpABEPs4poEL0L91 -09S5zvE/bw4cHjdx5RiHdRk/ULlepEU0rbDK5uUTdg8xFKmOLZTW1YVNcxVPS/Ky -Pu1svf0OnWZzsD2097+o4BGkxK51CUpjAEggpsadCwmKtODmzj7HPiY46SvepghJ -AwSQiumPv+i2tCqjI40cHLI5kqiPAlxAOXXUc0ECd97N4EOH1uS6SsNsEn/+KuYj -1oxx ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: - 11:20:a1:69:1b:bf:bd:b9:bd:52:96:8f:23:e8:48:bf:26:11 - Signature Algorithm: sha512WithRSAEncryption - Issuer: C=FR, O=OpenTrust, CN=OpenTrust Root CA G2 - Validity - Not Before: May 26 00:00:00 2014 GMT - Not After : Jan 15 00:00:00 2038 GMT - Subject: C=FR, O=OpenTrust, CN=OpenTrust Root CA G2 - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (4096 bit) - Modulus: - 00:cc:b6:57:a5:33:94:10:81:32:53:df:61:7e:0f: - 76:39:cf:5c:c2:53:75:1d:49:7a:96:38:dd:a2:73: - 6a:f1:6f:de:5e:a2:5a:b9:71:21:be:36:d9:a1:fc: - bc:ee:6c:a8:7c:34:1a:71:1a:e8:1a:d8:5f:0e:44: - 06:ed:a7:e0:f3:d2:61:0b:e0:32:a2:96:d1:38:f0: - c2:da:01:17:fc:e4:ac:4f:e8:ee:89:1e:74:ab:4f: - bf:1e:09:b6:36:6a:56:f3:e1:ee:96:89:66:24:06: - e4:cd:42:3a:4a:dd:e0:9a:b0:c4:82:45:b3:fe:c9: - ab:5c:7c:3e:c9:eb:17:2f:0c:7d:6e:ae:a5:8f:c8: - ac:25:0a:6f:fa:d5:45:98:d2:35:09:f6:03:43:94: - fe:d9:bf:20:95:79:80:98:8a:d9:89:35:bb:51:1b: - a4:37:7d:fc:99:3b:ab:ff:bf:ac:0d:8f:43:b1:99: - 7b:16:10:7e:1d:6f:47:c4:15:8f:04:96:08:06:42: - 04:f8:84:d6:1d:bc:91:a6:42:be:49:d5:6a:88:3f: - bc:2d:51:d1:9e:8d:e0:52:cc:57:dd:35:35:58:db: - b4:8f:24:88:e4:8b:df:dc:6b:54:d2:81:2b:b2:ce: - 92:4b:1c:1f:46:fa:1d:d8:92:cb:76:67:b5:09:99: - 09:e5:ac:17:14:55:70:c6:3c:a0:56:0a:03:b3:dc: - 62:19:df:c8:b5:30:7f:f5:3c:26:75:11:bd:d7:1b: - b3:87:9e:07:af:65:71:e5:a0:cf:1a:a7:09:10:1d: - 93:89:66:5b:e8:3c:62:32:b5:b5:3a:6e:e9:85:01: - 8b:9e:43:8c:67:73:28:59:5b:eb:e3:dc:2c:cc:a5: - 26:72:62:12:b4:e6:9c:83:44:f6:51:a4:e2:c0:7a: - 24:57:ca:0e:a5:3f:3a:b5:3b:8b:e5:76:ee:70:e6: - 92:de:16:5c:28:5b:97:19:27:92:fe:7a:92:54:ce: - 93:39:0a:16:87:bc:63:b3:f5:b1:93:5c:e0:6e:b7: - d0:ea:f9:62:32:88:44:fb:bf:27:28:b6:30:95:5d: - 12:28:b9:95:be:8f:53:18:e5:a2:18:16:e2:56:a4: - b2:2c:10:f5:1d:37:a6:f8:b7:f6:d0:59:5c:89:f7: - c2:d5:b5:94:74:d1:d5:fe:1b:b6:f0:e6:d6:1e:7b: - d2:3c:cb:a8:e3:f5:18:f3:21:1f:6e:ef:4d:68:06: - 7b:2d:5d:6e:43:89:a6:c0:f9:a0:bf:82:1e:cf:53: - 7f:b4:eb:2c:db:5d:f6:6a:7d:40:24:05:72:89:38: - 01:93:cb:71:c2:39:5d:06:11:f6:6f:78:f8:37:0d: - 39:84:27 - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Key Usage: critical - Certificate Sign, CRL Sign - X509v3 Basic Constraints: critical - CA:TRUE - X509v3 Subject Key Identifier: - 6A:39:FA:42:22:F7:E6:89:00:4D:5E:7D:33:83:CB:B8:6E:77:86:AF - X509v3 Authority Key Identifier: - keyid:6A:39:FA:42:22:F7:E6:89:00:4D:5E:7D:33:83:CB:B8:6E:77:86:AF - - Signature Algorithm: sha512WithRSAEncryption - 98:cb:ab:40:3c:e5:33:02:97:7f:2d:87:a6:8f:d4:5e:4a:af: - b8:1e:e7:bb:71:fb:80:64:25:a9:b3:1a:3e:68:5d:27:26:a7: - ba:2a:e1:f0:57:83:0a:64:4f:1e:22:74:1b:e9:90:5f:f0:ac: - cf:ff:4f:68:7a:38:a4:10:6c:0d:b1:c7:a4:77:80:18:b6:a2: - 28:44:76:a7:34:9d:71:84:2f:ca:59:d2:47:88:99:41:22:c9: - 30:98:61:6e:3d:a8:a8:05:6d:d1:1f:c0:51:44:56:7f:27:35: - 02:dd:5e:98:0a:42:eb:30:bf:8d:a1:9b:51:aa:3b:ea:93:46: - 64:c5:00:79:de:21:6b:f6:57:a0:86:d7:06:72:ec:70:46:4b: - 8b:73:dd:a0:21:75:3e:dc:1d:c0:8f:d3:4f:73:1c:85:d9:fe: - 7f:62:c8:95:6f:b6:d3:7b:8c:ba:53:c2:6f:9b:44:4c:79:d0: - 1d:70:b3:d7:9f:02:f4:b2:07:b0:c7:e5:f8:ad:23:0e:a6:56: - c9:29:12:77:48:d9:2f:46:fd:3b:f0:fc:74:70:92:a5:8e:38: - 08:1f:64:30:b6:b7:4b:fb:36:ac:10:8e:a0:52:33:63:9d:03: - 35:56:c5:69:bd:c6:23:5a:27:94:f6:a4:12:f8:2d:33:3c:a1: - 56:a5:5f:d6:19:e9:ed:7c:08:bd:77:cd:27:64:cc:94:da:4e: - 46:50:87:e0:f9:c1:53:80:1e:bb:ad:fb:47:52:8b:1b:fd:a2: - f9:de:0e:22:b7:3d:33:59:6c:d4:de:f5:95:06:32:0d:51:19: - 41:5c:3e:4f:06:f7:b9:2b:80:27:f6:a3:aa:7a:7c:06:e1:43: - c3:13:39:62:1a:36:bd:e0:28:2e:94:02:e4:29:2e:60:55:ae: - 40:3d:b0:74:92:5e:f0:20:64:96:3f:5f:45:5d:88:b5:8a:da: - 02:a0:5b:45:54:de:38:3d:09:c0:a8:4a:65:46:16:fc:aa:bf: - 54:4e:4d:5b:be:38:43:b7:28:ca:8b:33:aa:1a:25:ba:25:5c: - 29:2f:5b:4a:6e:8c:ea:2d:9c:2a:f6:05:76:e0:77:97:80:88: - dd:67:13:6f:1d:68:24:8b:4f:b7:74:81:e5:f4:60:9f:7a:55: - d7:3e:37:da:16:6b:3e:77:ac:ae:18:70:95:08:79:29:03:8a: - fe:c1:3b:b3:3f:1a:0f:a4:3b:5e:1f:58:a1:95:c9:ab:2f:73: - 4a:d0:2d:6e:9a:59:0f:55:18:78:2d:3c:51:a6:97:8b:e6:bb: - b2:70:aa:4c:11:de:ff:7c:2b:37:d4:7a:d1:77:34:8f:e7:f9: - 42:f7:3c:81:0c:4b:52:0a ------BEGIN CERTIFICATE----- -MIIFbzCCA1egAwIBAgISESChaRu/vbm9UpaPI+hIvyYRMA0GCSqGSIb3DQEBDQUA -MEAxCzAJBgNVBAYTAkZSMRIwEAYDVQQKDAlPcGVuVHJ1c3QxHTAbBgNVBAMMFE9w -ZW5UcnVzdCBSb290IENBIEcyMB4XDTE0MDUyNjAwMDAwMFoXDTM4MDExNTAwMDAw -MFowQDELMAkGA1UEBhMCRlIxEjAQBgNVBAoMCU9wZW5UcnVzdDEdMBsGA1UEAwwU -T3BlblRydXN0IFJvb3QgQ0EgRzIwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIK -AoICAQDMtlelM5QQgTJT32F+D3Y5z1zCU3UdSXqWON2ic2rxb95eolq5cSG+Ntmh -/LzubKh8NBpxGuga2F8ORAbtp+Dz0mEL4DKiltE48MLaARf85KxP6O6JHnSrT78e -CbY2albz4e6WiWYkBuTNQjpK3eCasMSCRbP+yatcfD7J6xcvDH1urqWPyKwlCm/6 -1UWY0jUJ9gNDlP7ZvyCVeYCYitmJNbtRG6Q3ffyZO6v/v6wNj0OxmXsWEH4db0fE -FY8ElggGQgT4hNYdvJGmQr5J1WqIP7wtUdGejeBSzFfdNTVY27SPJIjki9/ca1TS -gSuyzpJLHB9G+h3Ykst2Z7UJmQnlrBcUVXDGPKBWCgOz3GIZ38i1MH/1PCZ1Eb3X -G7OHngevZXHloM8apwkQHZOJZlvoPGIytbU6bumFAYueQ4xncyhZW+vj3CzMpSZy -YhK05pyDRPZRpOLAeiRXyg6lPzq1O4vldu5w5pLeFlwoW5cZJ5L+epJUzpM5ChaH -vGOz9bGTXOBut9Dq+WIyiET7vycotjCVXRIouZW+j1MY5aIYFuJWpLIsEPUdN6b4 -t/bQWVyJ98LVtZR00dX+G7bw5tYee9I8y6jj9RjzIR9u701oBnstXW5DiabA+aC/ -gh7PU3+06yzbXfZqfUAkBXKJOAGTy3HCOV0GEfZvePg3DTmEJwIDAQABo2MwYTAO -BgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUajn6QiL3 -5okATV59M4PLuG53hq8wHwYDVR0jBBgwFoAUajn6QiL35okATV59M4PLuG53hq8w -DQYJKoZIhvcNAQENBQADggIBAJjLq0A85TMCl38th6aP1F5Kr7ge57tx+4BkJamz -Gj5oXScmp7oq4fBXgwpkTx4idBvpkF/wrM//T2h6OKQQbA2xx6R3gBi2oihEdqc0 -nXGEL8pZ0keImUEiyTCYYW49qKgFbdEfwFFEVn8nNQLdXpgKQuswv42hm1GqO+qT -RmTFAHneIWv2V6CG1wZy7HBGS4tz3aAhdT7cHcCP009zHIXZ/n9iyJVvttN7jLpT -wm+bREx50B1ws9efAvSyB7DH5fitIw6mVskpEndI2S9G/Tvw/HRwkqWOOAgfZDC2 -t0v7NqwQjqBSM2OdAzVWxWm9xiNaJ5T2pBL4LTM8oValX9YZ6e18CL13zSdkzJTa -TkZQh+D5wVOAHrut+0dSixv9ovneDiK3PTNZbNTe9ZUGMg1RGUFcPk8G97krgCf2 -o6p6fAbhQ8MTOWIaNr3gKC6UAuQpLmBVrkA9sHSSXvAgZJY/X0VdiLWK2gKgW0VU -3jg9CcCoSmVGFvyqv1ROTVu+OEO3KMqLM6oaJbolXCkvW0pujOotnCr2BXbgd5eA -iN1nE28daCSLT7d0geX0YJ96Vdc+N9oWaz53rK4YcJUIeSkDiv7BO7M/Gg+kO14f -WKGVyasvc0rQLW6aWQ9VGHgtPFGml4vmu7JwqkwR3v98KzfUetF3NI/n+UL3PIEM -S1IK ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: - 11:20:e6:f8:4c:fc:24:b0:be:05:40:ac:da:83:1b:34:60:3f - Signature Algorithm: ecdsa-with-SHA384 - Issuer: C=FR, O=OpenTrust, CN=OpenTrust Root CA G3 - Validity - Not Before: May 26 00:00:00 2014 GMT - Not After : Jan 15 00:00:00 2038 GMT - Subject: C=FR, O=OpenTrust, CN=OpenTrust Root CA G3 - Subject Public Key Info: - Public Key Algorithm: id-ecPublicKey - Public-Key: (384 bit) - pub: - 04:4a:ee:58:ae:4d:ca:66:de:06:3a:a3:11:fc:e0: - 18:f0:6e:1c:ba:2d:30:0c:89:d9:d6:ee:9b:73:83: - a9:23:15:8c:2f:59:8a:5a:dd:14:ea:9d:59:2b:43: - b7:06:ec:32:b6:ba:ee:41:b5:ad:5d:a1:85:cc:ea: - 1d:14:66:a3:67:7e:46:e2:94:f3:e7:b6:56:a1:15: - 59:a1:4f:37:97:b9:22:1e:bd:11:eb:f4:b2:1f:5e: - c3:14:9a:e5:d9:97:99 - ASN1 OID: secp384r1 - X509v3 extensions: - X509v3 Key Usage: critical - Certificate Sign, CRL Sign - X509v3 Basic Constraints: critical - CA:TRUE - X509v3 Subject Key Identifier: - 47:77:C3:14:8B:62:39:0C:C9:6F:E1:50:4D:D0:10:58:DC:95:88:6D - X509v3 Authority Key Identifier: - keyid:47:77:C3:14:8B:62:39:0C:C9:6F:E1:50:4D:D0:10:58:DC:95:88:6D - - Signature Algorithm: ecdsa-with-SHA384 - 30:66:02:31:00:8f:a8:dc:9d:ba:0c:04:17:fa:15:e9:3d:2f: - 29:01:97:bf:81:16:33:40:93:6c:fc:f9:ed:80:70:6f:aa:8f: - db:84:c2:8b:f5:35:ca:06:dc:64:6f:68:16:e1:8f:91:b9:02: - 31:00:d8:4b:a5:cb:c2:d0:08:6c:e9:18:fb:5a:dd:4d:5f:24: - 0b:b0:00:21:25:ef:8f:a7:04:26:71:e2:7c:69:e5:5d:9a:f8: - 41:1f:3b:39:93:93:9d:55:ea:cd:8d:f1:fb:c1 ------BEGIN CERTIFICATE----- -MIICITCCAaagAwIBAgISESDm+Ez8JLC+BUCs2oMbNGA/MAoGCCqGSM49BAMDMEAx -CzAJBgNVBAYTAkZSMRIwEAYDVQQKDAlPcGVuVHJ1c3QxHTAbBgNVBAMMFE9wZW5U -cnVzdCBSb290IENBIEczMB4XDTE0MDUyNjAwMDAwMFoXDTM4MDExNTAwMDAwMFow -QDELMAkGA1UEBhMCRlIxEjAQBgNVBAoMCU9wZW5UcnVzdDEdMBsGA1UEAwwUT3Bl -blRydXN0IFJvb3QgQ0EgRzMwdjAQBgcqhkjOPQIBBgUrgQQAIgNiAARK7liuTcpm -3gY6oxH84Bjwbhy6LTAMidnW7ptzg6kjFYwvWYpa3RTqnVkrQ7cG7DK2uu5Bta1d -oYXM6h0UZqNnfkbilPPntlahFVmhTzeXuSIevRHr9LIfXsMUmuXZl5mjYzBhMA4G -A1UdDwEB/wQEAwIBBjAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBRHd8MUi2I5 -DMlv4VBN0BBY3JWIbTAfBgNVHSMEGDAWgBRHd8MUi2I5DMlv4VBN0BBY3JWIbTAK -BggqhkjOPQQDAwNpADBmAjEAj6jcnboMBBf6Fek9LykBl7+BFjNAk2z8+e2AcG+q -j9uEwov1NcoG3GRvaBbhj5G5AjEA2Euly8LQCGzpGPta3U1fJAuwACEl74+nBCZx -4nxp5V2a+EEfOzmTk51V6s2N8fvB ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: 11 (0xb) - Signature Algorithm: sha256WithRSAEncryption - Issuer: CN=Autoridad de Certificacion Raiz del Estado Venezolano, C=VE, L=Caracas, ST=Distrito Capital, O=Sistema Nacional de Certificacion Electronica, OU=Superintendencia de Servicios de Certificacion Electronica/emailAddress=acraiz@suscerte.gob.ve - Validity - Not Before: Dec 28 16:51:00 2010 GMT - Not After : Dec 25 23:59:59 2020 GMT - Subject: emailAddress=contacto@procert.net.ve, L=Chacao, ST=Miranda, OU=Proveedor de Certificados PROCERT, O=Sistema Nacional de Certificacion Electronica, C=VE, CN=PSCProcert - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (4096 bit) - Modulus: - 00:d5:b7:f4:a3:94:33:a1:46:a9:55:61:49:0d:a8: - 87:73:5e:91:2d:70:c1:06:1a:94:da:3d:ec:15:42: - c1:f5:8c:ae:6a:17:f1:8a:ad:fc:80:95:ea:83:44: - a2:5b:7a:55:ce:4f:a7:a5:d5:ba:b8:1f:a0:27:c0: - 50:53:3e:8d:b9:c0:0e:b8:15:dc:d6:6c:f8:9e:f8: - 04:25:df:80:8f:10:85:dd:7d:2f:7b:80:dd:57:00: - 64:23:f8:6e:c9:be:95:4f:e1:75:ec:e0:7e:5e:95: - cd:b1:ef:be:7a:42:d8:c9:2c:d3:eb:1a:1a:22:8b: - b7:7f:06:89:e5:3c:f5:12:c0:bb:d3:0b:99:5f:90: - 7c:8e:2d:2f:77:33:92:4a:21:46:a8:a9:08:ac:f1: - f6:11:02:d9:95:16:9e:8d:2f:96:e6:02:dd:75:c2: - 14:2a:5a:d6:c9:7d:25:c2:c1:fc:aa:67:85:e2:ec: - be:d1:7c:3c:fa:af:d5:6e:ff:53:41:d4:f5:32:38: - b1:e2:5f:c4:f9:8e:10:ef:06:a9:02:89:ff:e3:0c: - 6e:97:e0:df:9d:db:21:d0:f4:3e:08:69:6c:d8:d4: - e4:36:f8:83:b6:b2:36:8f:9c:ef:3a:37:16:7d:bf: - a2:69:d7:3b:5b:72:d0:af:aa:3f:5c:66:93:ac:0a: - 22:61:b6:d2:a0:99:c8:54:93:5d:a8:b6:d1:bd:5d: - 0a:5e:77:94:a2:2d:c0:82:8e:bc:ca:03:2a:34:ae: - 73:f1:d4:b5:0c:bd:be:67:9b:54:eb:e1:fa:a0:5a: - ec:38:7e:3e:c1:cc:a2:c7:44:31:75:ea:3f:e5:07: - d2:ab:a1:25:96:f6:e6:e4:a0:5d:37:18:39:61:00: - 33:5d:46:d4:00:c4:b4:ca:3c:f1:a2:a3:3e:f3:3a: - ff:69:30:2e:40:dd:f6:9f:9c:26:c9:96:37:ad:e7: - 39:a2:bf:ea:69:db:55:22:95:53:2a:94:b5:df:ad: - 16:38:81:75:66:e3:c7:2c:1b:93:9c:aa:8c:a3:ca: - d9:6c:3c:17:6d:9c:dc:7c:53:e0:20:27:43:36:f9: - 12:e1:3c:5c:bd:66:bf:a2:69:23:38:b8:99:60:99: - 0e:56:53:3a:9c:7e:14:8c:b0:06:6f:f1:86:76:90: - af:fd:af:fe:90:c6:8f:9f:7f:8b:92:23:9c:e7:15: - 76:8f:d5:8b:94:13:72:69:fb:2b:61:63:88:ef:e6: - a4:5e:e6:a3:17:6a:58:47:cb:71:4f:14:0b:5e:c8: - 02:08:26:a2:cb:e9:af:6b:8a:19:c7:cb:14:56:f5: - e1:da:b5:d9:fc:bf:73:38:da:f9:e7:af:6e:a4:37: - e2:07:27 - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Basic Constraints: critical - CA:TRUE, pathlen:1 - X509v3 Issuer Alternative Name: - DNS:suscerte.gob.ve, othername:<unsupported> - X509v3 Subject Key Identifier: - 41:0F:19:38:AA:99:7F:42:0B:A4:D7:27:98:54:A2:17:4C:2D:51:54 - X509v3 Authority Key Identifier: - keyid:AD:BB:22:1D:C6:E0:D2:01:A8:FD:76:50:52:93:ED:98:C1:4D:AE:D3 - DirName:/CN=Autoridad de Certificacion Raiz del Estado Venezolano/C=VE/L=Caracas/ST=Distrito Capital/O=Sistema Nacional de Certificacion Electronica/OU=Superintendencia de Servicios de Certificacion Electronica/emailAddress=acraiz@suscerte.gob.ve - serial:0A - - X509v3 Key Usage: critical - Certificate Sign, CRL Sign - X509v3 Subject Alternative Name: - DNS:procert.net.ve, othername:<unsupported>, othername:<unsupported> - X509v3 CRL Distribution Points: - - Full Name: - URI:http://www.suscerte.gob.ve/lcr/CERTIFICADO-RAIZ-SHA384CRLDER.crl - - Full Name: - URI:ldap://acraiz.suscerte.gob.ve - - Authority Information Access: - OCSP - URI:http://ocsp.suscerte.gob.ve - - X509v3 Certificate Policies: - Policy: 2.16.862.3.1.2 - CPS: http://www.suscerte.gob.ve/dpc - - Signature Algorithm: sha256WithRSAEncryption - 2b:59:eb:22:99:bb:84:aa:4f:de:90:c6:d1:86:71:23:9e:4b: - 03:91:47:70:bb:c0:92:60:ec:e0:d4:e7:6d:c6:d3:ed:67:83: - 77:52:d5:f2:e5:77:a7:36:b2:e3:54:be:d9:bb:0a:9b:11:ef: - 61:f4:c6:99:33:99:f5:af:00:39:8d:83:bf:a6:bd:35:7e:2c: - 5c:31:34:6f:6c:db:f3:64:01:98:aa:94:2c:41:dd:15:86:ca: - 6b:29:4e:16:c0:49:fc:d7:83:48:13:07:51:84:31:52:88:bb: - 86:17:c7:6b:2f:8a:20:ad:c5:0b:8f:70:3e:2a:bb:1b:71:8f: - b9:a4:a0:fd:d8:95:d9:af:59:bf:25:2b:98:e9:63:93:2f:60: - 1e:c4:aa:f8:77:f5:8b:6c:2f:ed:7e:2e:b5:4f:40:0d:ee:bc: - 57:77:e7:d9:b6:d4:3f:95:27:3a:20:d5:e5:ae:ab:6c:35:9f: - c1:a1:1d:59:dc:84:81:ee:4d:07:e2:48:b6:9e:4b:95:2d:41: - b1:e1:e8:de:7e:2f:05:1e:68:ee:bf:bb:90:65:3a:c8:ee:ea: - b1:18:37:1c:62:93:a4:a0:31:ec:71:6c:91:e6:a4:79:89:5a: - 14:a7:14:50:05:4c:a4:00:57:30:2c:c1:b5:61:96:dc:3e:1e: - 84:af:39:42:cf:e5:d0:2c:b1:24:bc:df:40:c3:ed:7f:63:4a: - bd:e1:4f:12:64:86:95:f3:b0:e7:c8:b7:e1:53:bd:92:e6:f3: - 0c:96:b9:eb:e8:e6:92:ed:a7:81:09:14:0b:fc:95:7a:cf:8f: - d6:34:4f:36:12:dc:5e:d1:34:75:c6:46:80:2f:95:04:8c:c7: - 86:c4:a8:26:89:a8:3f:19:9b:81:bb:51:a4:4a:86:ab:0b:11: - 0f:b1:ae:63:53:6d:28:ea:dd:33:56:38:1c:b2:ad:80:d3:d7: - 72:bd:9a:6c:99:63:e8:00:bb:41:76:05:b7:5b:99:18:8a:c3: - b8:12:5c:56:cf:56:0c:7d:e8:e2:cf:ed:bc:74:47:fb:ee:d3: - 17:4e:22:4f:56:ff:50:f3:2e:e6:39:a6:82:d6:71:ca:de:b7: - d5:ba:68:08:ed:99:cc:fd:a2:92:cb:69:b8:9d:f9:0a:a4:a6: - 3e:4f:93:28:2a:61:6c:07:26:00:ff:96:5f:68:86:b8:b8:ce: - ca:55:e0:ab:b1:3d:7f:98:d7:33:0e:5a:3d:d8:78:c2:c4:60: - 2f:c7:62:f0:61:91:d2:38:b0:f6:9e:55:db:40:80:05:12:33: - ce:1d:92:9b:d1:69:b3:ff:bf:f1:92:0a:61:35:3f:dd:fe:86: - f4:bc:e0:1a:71:b3:62:a6 ------BEGIN CERTIFICATE----- -MIIJhjCCB26gAwIBAgIBCzANBgkqhkiG9w0BAQsFADCCAR4xPjA8BgNVBAMTNUF1 -dG9yaWRhZCBkZSBDZXJ0aWZpY2FjaW9uIFJhaXogZGVsIEVzdGFkbyBWZW5lem9s -YW5vMQswCQYDVQQGEwJWRTEQMA4GA1UEBxMHQ2FyYWNhczEZMBcGA1UECBMQRGlz -dHJpdG8gQ2FwaXRhbDE2MDQGA1UEChMtU2lzdGVtYSBOYWNpb25hbCBkZSBDZXJ0 -aWZpY2FjaW9uIEVsZWN0cm9uaWNhMUMwQQYDVQQLEzpTdXBlcmludGVuZGVuY2lh -IGRlIFNlcnZpY2lvcyBkZSBDZXJ0aWZpY2FjaW9uIEVsZWN0cm9uaWNhMSUwIwYJ -KoZIhvcNAQkBFhZhY3JhaXpAc3VzY2VydGUuZ29iLnZlMB4XDTEwMTIyODE2NTEw -MFoXDTIwMTIyNTIzNTk1OVowgdExJjAkBgkqhkiG9w0BCQEWF2NvbnRhY3RvQHBy -b2NlcnQubmV0LnZlMQ8wDQYDVQQHEwZDaGFjYW8xEDAOBgNVBAgTB01pcmFuZGEx -KjAoBgNVBAsTIVByb3ZlZWRvciBkZSBDZXJ0aWZpY2Fkb3MgUFJPQ0VSVDE2MDQG -A1UEChMtU2lzdGVtYSBOYWNpb25hbCBkZSBDZXJ0aWZpY2FjaW9uIEVsZWN0cm9u -aWNhMQswCQYDVQQGEwJWRTETMBEGA1UEAxMKUFNDUHJvY2VydDCCAiIwDQYJKoZI -hvcNAQEBBQADggIPADCCAgoCggIBANW39KOUM6FGqVVhSQ2oh3NekS1wwQYalNo9 -7BVCwfWMrmoX8Yqt/ICV6oNEolt6Vc5Pp6XVurgfoCfAUFM+jbnADrgV3NZs+J74 -BCXfgI8Qhd19L3uA3VcAZCP4bsm+lU/hdezgfl6VzbHvvnpC2Mks0+saGiKLt38G -ieU89RLAu9MLmV+QfI4tL3czkkohRqipCKzx9hEC2ZUWno0vluYC3XXCFCpa1sl9 -JcLB/KpnheLsvtF8PPqv1W7/U0HU9TI4seJfxPmOEO8GqQKJ/+MMbpfg353bIdD0 -PghpbNjU5Db4g7ayNo+c7zo3Fn2/omnXO1ty0K+qP1xmk6wKImG20qCZyFSTXai2 -0b1dCl53lKItwIKOvMoDKjSuc/HUtQy9vmebVOvh+qBa7Dh+PsHMosdEMXXqP+UH -0quhJZb25uSgXTcYOWEAM11G1ADEtMo88aKjPvM6/2kwLkDd9p+cJsmWN63nOaK/ -6mnbVSKVUyqUtd+tFjiBdWbjxywbk5yqjKPK2Ww8F22c3HxT4CAnQzb5EuE8XL1m -v6JpIzi4mWCZDlZTOpx+FIywBm/xhnaQr/2v/pDGj59/i5IjnOcVdo/Vi5QTcmn7 -K2FjiO/mpF7moxdqWEfLcU8UC17IAggmosvpr2uKGcfLFFb14dq12fy/czja+eev -bqQ34gcnAgMBAAGjggMXMIIDEzASBgNVHRMBAf8ECDAGAQH/AgEBMDcGA1UdEgQw -MC6CD3N1c2NlcnRlLmdvYi52ZaAbBgVghl4CAqASDBBSSUYtRy0yMDAwNDAzNi0w -MB0GA1UdDgQWBBRBDxk4qpl/Qguk1yeYVKIXTC1RVDCCAVAGA1UdIwSCAUcwggFD -gBStuyIdxuDSAaj9dlBSk+2YwU2u06GCASakggEiMIIBHjE+MDwGA1UEAxM1QXV0 -b3JpZGFkIGRlIENlcnRpZmljYWNpb24gUmFpeiBkZWwgRXN0YWRvIFZlbmV6b2xh -bm8xCzAJBgNVBAYTAlZFMRAwDgYDVQQHEwdDYXJhY2FzMRkwFwYDVQQIExBEaXN0 -cml0byBDYXBpdGFsMTYwNAYDVQQKEy1TaXN0ZW1hIE5hY2lvbmFsIGRlIENlcnRp -ZmljYWNpb24gRWxlY3Ryb25pY2ExQzBBBgNVBAsTOlN1cGVyaW50ZW5kZW5jaWEg -ZGUgU2VydmljaW9zIGRlIENlcnRpZmljYWNpb24gRWxlY3Ryb25pY2ExJTAjBgkq -hkiG9w0BCQEWFmFjcmFpekBzdXNjZXJ0ZS5nb2IudmWCAQowDgYDVR0PAQH/BAQD -AgEGME0GA1UdEQRGMESCDnByb2NlcnQubmV0LnZloBUGBWCGXgIBoAwMClBTQy0w -MDAwMDKgGwYFYIZeAgKgEgwQUklGLUotMzE2MzUzNzMtNzB2BgNVHR8EbzBtMEag -RKBChkBodHRwOi8vd3d3LnN1c2NlcnRlLmdvYi52ZS9sY3IvQ0VSVElGSUNBRE8t -UkFJWi1TSEEzODRDUkxERVIuY3JsMCOgIaAfhh1sZGFwOi8vYWNyYWl6LnN1c2Nl -cnRlLmdvYi52ZTA3BggrBgEFBQcBAQQrMCkwJwYIKwYBBQUHMAGGG2h0dHA6Ly9v -Y3NwLnN1c2NlcnRlLmdvYi52ZTBBBgNVHSAEOjA4MDYGBmCGXgMBAjAsMCoGCCsG -AQUFBwIBFh5odHRwOi8vd3d3LnN1c2NlcnRlLmdvYi52ZS9kcGMwDQYJKoZIhvcN -AQELBQADggIBACtZ6yKZu4SqT96QxtGGcSOeSwORR3C7wJJg7ODU523G0+1ng3dS -1fLld6c2suNUvtm7CpsR72H0xpkzmfWvADmNg7+mvTV+LFwxNG9s2/NkAZiqlCxB -3RWGymspThbASfzXg0gTB1GEMVKIu4YXx2sviiCtxQuPcD4quxtxj7mkoP3Yldmv -Wb8lK5jpY5MvYB7Eqvh39YtsL+1+LrVPQA3uvFd359m21D+VJzog1eWuq2w1n8Gh -HVnchIHuTQfiSLaeS5UtQbHh6N5+LwUeaO6/u5BlOsju6rEYNxxik6SgMexxbJHm -pHmJWhSnFFAFTKQAVzAswbVhltw+HoSvOULP5dAssSS830DD7X9jSr3hTxJkhpXz -sOfIt+FTvZLm8wyWuevo5pLtp4EJFAv8lXrPj9Y0TzYS3F7RNHXGRoAvlQSMx4bE -qCaJqD8Zm4G7UaRKhqsLEQ+xrmNTbSjq3TNWOByyrYDT13K9mmyZY+gAu0F2Bbdb -mRiKw7gSXFbPVgx96OLP7bx0R/vu0xdOIk9W/1DzLuY5poLWccret9W6aAjtmcz9 -opLLabid+Qqkpj5PkygqYWwHJgD/ll9ohri4zspV4KuxPX+Y1zMOWj3YeMLEYC/H -YvBhkdI4sPaeVdtAgAUSM84dkpvRabP/v/GSCmE1P93+hvS84Bpxs2Km ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: 985026699 (0x3ab6508b) - Signature Algorithm: sha1WithRSAEncryption - Issuer: C=BM, O=QuoVadis Limited, OU=Root Certification Authority, CN=QuoVadis Root Certification Authority - Validity - Not Before: Mar 19 18:33:33 2001 GMT - Not After : Mar 17 18:33:33 2021 GMT - Subject: C=BM, O=QuoVadis Limited, OU=Root Certification Authority, CN=QuoVadis Root Certification Authority - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (2048 bit) - Modulus: - 00:bf:61:b5:95:53:ba:57:fc:fa:f2:67:0b:3a:1a: - df:11:80:64:95:b4:d1:bc:cd:7a:cf:f6:29:96:2e: - 24:54:40:24:38:f7:1a:85:dc:58:4c:cb:a4:27:42: - 97:d0:9f:83:8a:c3:e4:06:03:5b:00:a5:51:1e:70: - 04:74:e2:c1:d4:3a:ab:d7:ad:3b:07:18:05:8e:fd: - 83:ac:ea:66:d9:18:1b:68:8a:f5:57:1a:98:ba:f5: - ed:76:3d:7c:d9:de:94:6a:3b:4b:17:c1:d5:8f:bd: - 65:38:3a:95:d0:3d:55:36:4e:df:79:57:31:2a:1e: - d8:59:65:49:58:20:98:7e:ab:5f:7e:9f:e9:d6:4d: - ec:83:74:a9:c7:6c:d8:ee:29:4a:85:2a:06:14:f9: - 54:e6:d3:da:65:07:8b:63:37:12:d7:d0:ec:c3:7b: - 20:41:44:a3:ed:cb:a0:17:e1:71:65:ce:1d:66:31: - f7:76:01:19:c8:7d:03:58:b6:95:49:1d:a6:12:26: - e8:c6:0c:76:e0:e3:66:cb:ea:5d:a6:26:ee:e5:cc: - 5f:bd:67:a7:01:27:0e:a2:ca:54:c5:b1:7a:95:1d: - 71:1e:4a:29:8a:03:dc:6a:45:c1:a4:19:5e:6f:36: - cd:c3:a2:b0:b7:fe:5c:38:e2:52:bc:f8:44:43:e6: - 90:bb - Exponent: 65537 (0x10001) - X509v3 extensions: - Authority Information Access: - OCSP - URI:https://ocsp.quovadisoffshore.com - - X509v3 Basic Constraints: critical - CA:TRUE - X509v3 Certificate Policies: - Policy: 1.3.6.1.4.1.8024.0.1 - User Notice: - Explicit Text: Reliance on the QuoVadis Root Certificate by any party assumes acceptance of the then applicable standard terms and conditions of use, certification practices, and the QuoVadis Certificate Policy. - CPS: http://www.quovadis.bm - - X509v3 Subject Key Identifier: - 8B:4B:6D:ED:D3:29:B9:06:19:EC:39:39:A9:F0:97:84:6A:CB:EF:DF - X509v3 Authority Key Identifier: - keyid:8B:4B:6D:ED:D3:29:B9:06:19:EC:39:39:A9:F0:97:84:6A:CB:EF:DF - DirName:/C=BM/O=QuoVadis Limited/OU=Root Certification Authority/CN=QuoVadis Root Certification Authority - serial:3A:B6:50:8B - - X509v3 Key Usage: critical - Certificate Sign, CRL Sign - Signature Algorithm: sha1WithRSAEncryption - 8a:d4:14:b5:fe:f4:9a:92:a7:19:d4:a4:7e:72:18:8f:d9:68: - 7c:52:24:dd:67:6f:39:7a:c4:aa:5e:3d:e2:58:b0:4d:70:98: - 84:61:e8:1b:e3:69:18:0e:ce:fb:47:50:a0:4e:ff:f0:24:1f: - bd:b2:ce:f5:27:fc:ec:2f:53:aa:73:7b:03:3d:74:6e:e6:16: - 9e:eb:a5:2e:c4:bf:56:27:50:2b:62:ba:be:4b:1c:3c:55:5c: - 41:1d:24:be:82:20:47:5d:d5:44:7e:7a:16:68:df:7d:4d:51: - 70:78:57:1d:33:1e:fd:02:99:9c:0c:cd:0a:05:4f:c7:bb:8e: - a4:75:fa:4a:6d:b1:80:8e:09:56:b9:9c:1a:60:fe:5d:c1:d7: - 7a:dc:11:78:d0:d6:5d:c1:b7:d5:ad:32:99:03:3a:8a:cc:54: - 25:39:31:81:7b:13:22:51:ba:46:6c:a1:bb:9e:fa:04:6c:49: - 26:74:8f:d2:73:eb:cc:30:a2:e6:ea:59:22:87:f8:97:f5:0e: - fd:ea:cc:92:a4:16:c4:52:18:ea:21:ce:b1:f1:e6:84:81:e5: - ba:a9:86:28:f2:43:5a:5d:12:9d:ac:1e:d9:a8:e5:0a:6a:a7: - 7f:a0:87:29:cf:f2:89:4d:d4:ec:c5:e2:e6:7a:d0:36:23:8a: - 4a:74:36:f9 ------BEGIN CERTIFICATE----- -MIIF0DCCBLigAwIBAgIEOrZQizANBgkqhkiG9w0BAQUFADB/MQswCQYDVQQGEwJC -TTEZMBcGA1UEChMQUXVvVmFkaXMgTGltaXRlZDElMCMGA1UECxMcUm9vdCBDZXJ0 -aWZpY2F0aW9uIEF1dGhvcml0eTEuMCwGA1UEAxMlUXVvVmFkaXMgUm9vdCBDZXJ0 -aWZpY2F0aW9uIEF1dGhvcml0eTAeFw0wMTAzMTkxODMzMzNaFw0yMTAzMTcxODMz -MzNaMH8xCzAJBgNVBAYTAkJNMRkwFwYDVQQKExBRdW9WYWRpcyBMaW1pdGVkMSUw -IwYDVQQLExxSb290IENlcnRpZmljYXRpb24gQXV0aG9yaXR5MS4wLAYDVQQDEyVR -dW9WYWRpcyBSb290IENlcnRpZmljYXRpb24gQXV0aG9yaXR5MIIBIjANBgkqhkiG -9w0BAQEFAAOCAQ8AMIIBCgKCAQEAv2G1lVO6V/z68mcLOhrfEYBklbTRvM16z/Yp -li4kVEAkOPcahdxYTMukJ0KX0J+DisPkBgNbAKVRHnAEdOLB1Dqr1607BxgFjv2D -rOpm2RgbaIr1VxqYuvXtdj182d6UajtLF8HVj71lODqV0D1VNk7feVcxKh7YWWVJ -WCCYfqtffp/p1k3sg3Spx2zY7ilKhSoGFPlU5tPaZQeLYzcS19Dsw3sgQUSj7cug -F+FxZc4dZjH3dgEZyH0DWLaVSR2mEiboxgx24ONmy+pdpibu5cxfvWenAScOospU -xbF6lR1xHkopigPcakXBpBlebzbNw6Kwt/5cOOJSvPhEQ+aQuwIDAQABo4ICUjCC -Ak4wPQYIKwYBBQUHAQEEMTAvMC0GCCsGAQUFBzABhiFodHRwczovL29jc3AucXVv -dmFkaXNvZmZzaG9yZS5jb20wDwYDVR0TAQH/BAUwAwEB/zCCARoGA1UdIASCAREw -ggENMIIBCQYJKwYBBAG+WAABMIH7MIHUBggrBgEFBQcCAjCBxxqBxFJlbGlhbmNl -IG9uIHRoZSBRdW9WYWRpcyBSb290IENlcnRpZmljYXRlIGJ5IGFueSBwYXJ0eSBh -c3N1bWVzIGFjY2VwdGFuY2Ugb2YgdGhlIHRoZW4gYXBwbGljYWJsZSBzdGFuZGFy -ZCB0ZXJtcyBhbmQgY29uZGl0aW9ucyBvZiB1c2UsIGNlcnRpZmljYXRpb24gcHJh -Y3RpY2VzLCBhbmQgdGhlIFF1b1ZhZGlzIENlcnRpZmljYXRlIFBvbGljeS4wIgYI -KwYBBQUHAgEWFmh0dHA6Ly93d3cucXVvdmFkaXMuYm0wHQYDVR0OBBYEFItLbe3T -KbkGGew5Oanwl4Rqy+/fMIGuBgNVHSMEgaYwgaOAFItLbe3TKbkGGew5Oanwl4Rq -y+/foYGEpIGBMH8xCzAJBgNVBAYTAkJNMRkwFwYDVQQKExBRdW9WYWRpcyBMaW1p -dGVkMSUwIwYDVQQLExxSb290IENlcnRpZmljYXRpb24gQXV0aG9yaXR5MS4wLAYD -VQQDEyVRdW9WYWRpcyBSb290IENlcnRpZmljYXRpb24gQXV0aG9yaXR5ggQ6tlCL -MA4GA1UdDwEB/wQEAwIBBjANBgkqhkiG9w0BAQUFAAOCAQEAitQUtf70mpKnGdSk -fnIYj9lofFIk3WdvOXrEql494liwTXCYhGHoG+NpGA7O+0dQoE7/8CQfvbLO9Sf8 -7C9TqnN7Az10buYWnuulLsS/VidQK2K6vkscPFVcQR0kvoIgR13VRH56FmjffU1R -cHhXHTMe/QKZnAzNCgVPx7uOpHX6Sm2xgI4JVrmcGmD+XcHXetwReNDWXcG31a0y -mQM6isxUJTkxgXsTIlG6Rmyhu576BGxJJnSP0nPrzDCi5upZIof4l/UO/erMkqQW -xFIY6iHOsfHmhIHluqmGKPJDWl0Snawe2ajlCmqnf6CHKc/yiU3U7MXi5nrQNiOK -SnQ2+Q== ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: - 78:58:5f:2e:ad:2c:19:4b:e3:37:07:35:34:13:28:b5:96:d4:65:93 - Signature Algorithm: sha256WithRSAEncryption - Issuer: C=BM, O=QuoVadis Limited, CN=QuoVadis Root CA 1 G3 - Validity - Not Before: Jan 12 17:27:44 2012 GMT - Not After : Jan 12 17:27:44 2042 GMT - Subject: C=BM, O=QuoVadis Limited, CN=QuoVadis Root CA 1 G3 - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (4096 bit) - Modulus: - 00:a0:be:50:10:8e:e9:f2:6c:40:b4:04:9c:85:b9: - 31:ca:dc:2d:e4:11:a9:04:3c:1b:55:c1:e7:58:30: - 1d:24:b4:c3:ef:85:de:8c:2c:e1:c1:3d:df:82:e6: - 4f:ad:47:87:6c:ec:5b:49:c1:4a:d5:bb:8f:ec:87: - ac:7f:82:9a:86:ec:3d:03:99:52:01:d2:35:9e:ac: - da:f0:53:c9:66:3c:d4:ac:02:01:da:24:d3:3b:a8: - 02:46:af:a4:1c:e3:f8:73:58:76:b7:f6:0e:90:0d: - b5:f0:cf:cc:fa:f9:c6:4c:e5:c3:86:30:0a:8d:17: - 7e:35:eb:c5:df:bb:0e:9c:c0:8d:87:e3:88:38:85: - 67:fa:3e:c7:ab:e0:13:9c:05:18:98:cf:93:f5:b1: - 92:b4:fc:23:d3:cf:d5:c4:27:49:e0:9e:3c:9b:08: - a3:8b:5d:2a:21:e0:fc:39:aa:53:da:7d:7e:cf:1a: - 09:53:bc:5d:05:04:cf:a1:4a:8f:8b:76:82:0d:a1: - f8:d2:c7:14:77:5b:90:36:07:81:9b:3e:06:fa:52: - 5e:63:c5:a6:00:fe:a5:e9:52:1b:52:b5:92:39:72: - 03:09:62:bd:b0:60:16:6e:a6:dd:25:c2:03:66:dd: - f3:04:d1:40:e2:4e:8b:86:f4:6f:e5:83:a0:27:84: - 5e:04:c1:f5:90:bd:30:3d:c4:ef:a8:69:bc:38:9b: - a4:a4:96:d1:62:da:69:c0:01:96:ae:cb:c4:51:34: - ea:0c:aa:ff:21:8e:59:8f:4a:5c:e4:61:9a:a7:d2: - e9:2a:78:8d:51:3d:3a:15:ee:a2:59:8e:a9:5c:de: - c5:f9:90:22:e5:88:45:71:dd:91:99:6c:7a:9f:3d: - 3d:98:7c:5e:f6:be:16:68:a0:5e:ae:0b:23:fc:5a: - 0f:aa:22:76:2d:c9:a1:10:1d:e4:d3:44:23:90:88: - 9f:c6:2a:e6:d7:f5:9a:b3:58:1e:2f:30:89:08:1b: - 54:a2:b5:98:23:ec:08:77:1c:95:5d:61:d1:cb:89: - 9c:5f:a2:4a:91:9a:ef:21:aa:49:16:08:a8:bd:61: - 28:31:c9:74:ad:85:f6:d9:c5:b1:8b:d1:e5:10:32: - 4d:5f:8b:20:3a:3c:49:1f:33:85:59:0d:db:cb:09: - 75:43:69:73:fb:6b:71:7d:f0:df:c4:4c:7d:c6:a3: - 2e:c8:95:79:cb:73:a2:8e:4e:4d:24:fb:5e:e4:04: - be:72:1b:a6:27:2d:49:5a:99:7a:d7:5c:09:20:b7: - 7f:94:b9:4f:f1:0d:1c:5e:88:42:1b:11:b7:e7:91: - db:9e:6c:f4:6a:df:8c:06:98:03:ad:cc:28:ef:a5: - 47:f3:53 - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Basic Constraints: critical - CA:TRUE - X509v3 Key Usage: critical - Certificate Sign, CRL Sign - X509v3 Subject Key Identifier: - A3:97:D6:F3:5E:A2:10:E1:AB:45:9F:3C:17:64:3C:EE:01:70:9C:CC - Signature Algorithm: sha256WithRSAEncryption - 18:fa:5b:75:fc:3e:7a:c7:5f:77:c7:ca:df:cf:5f:c3:12:c4: - 40:5d:d4:32:aa:b8:6a:d7:d5:15:15:46:98:23:a5:e6:90:5b: - 18:99:4c:e3:ad:42:a3:82:31:36:88:cd:e9:fb:c4:04:96:48: - 8b:01:c7:8d:01:cf:5b:33:06:96:46:66:74:1d:4f:ed:c1:b6: - b9:b4:0d:61:cc:63:7e:d7:2e:77:8c:96:1c:2a:23:68:6b:85: - 57:76:70:33:13:fe:e1:4f:a6:23:77:18:fa:1a:8c:e8:bd:65: - c9:cf:3f:f4:c9:17:dc:eb:c7:bc:c0:04:2e:2d:46:2f:69:66: - c3:1b:8f:fe:ec:3e:d3:ca:94:bf:76:0a:25:0d:a9:7b:02:1c: - a9:d0:3b:5f:0b:c0:81:3a:3d:64:e1:bf:a7:2d:4e:bd:4d:c4: - d8:29:c6:22:18:d0:c5:ac:72:02:82:3f:aa:3a:a2:3a:22:97: - 31:dd:08:63:c3:75:14:b9:60:28:2d:5b:68:e0:16:a9:66:82: - 23:51:f5:eb:53:d8:31:9b:7b:e9:b7:9d:4b:eb:88:16:cf:f9: - 5d:38:8a:49:30:8f:ed:f1:eb:19:f4:77:1a:31:18:4d:67:54: - 6c:2f:6f:65:f9:db:3d:ec:21:ec:5e:f4:f4:8b:ca:60:65:54: - d1:71:64:f4:f9:a6:a3:81:33:36:33:71:f0:a4:78:5f:4e:ad: - 83:21:de:34:49:8d:e8:59:ac:9d:f2:76:5a:36:f2:13:f4:af: - e0:09:c7:61:2a:6c:f7:e0:9d:ae:bb:86:4a:28:6f:2e:ee:b4: - 79:cd:90:33:c3:b3:76:fa:f5:f0:6c:9d:01:90:fa:9e:90:f6: - 9c:72:cf:47:da:c3:1f:e4:35:20:53:f2:54:d1:df:61:83:a6: - 02:e2:25:38:de:85:32:2d:5e:73:90:52:5d:42:c4:ce:3d:4b: - e1:f9:19:84:1d:d5:a2:50:cc:41:fb:41:14:c3:bd:d6:c9:5a: - a3:63:66:02:80:bd:05:3a:3b:47:9c:ec:00:26:4c:f5:88:51: - bf:a8:23:7f:18:07:b0:0b:ed:8b:26:a1:64:d3:61:4a:eb:5c: - 9f:de:b3:af:67:03:b3:1f:dd:6d:5d:69:68:69:ab:5e:3a:ec: - 7c:69:bc:c7:3b:85:4e:9e:15:b9:b4:15:4f:c3:95:7a:58:d7: - c9:6c:e9:6c:b9:f3:29:63:5e:b4:2c:f0:2d:3d:ed:5a:65:e0: - a9:5b:40:c2:48:99:81:6d:9e:1f:06:2a:3c:12:b4:8b:0f:9b: - a2:24:f0:a6:8d:d6:7a:e0:4b:b6:64:96:63:95:84:c2:4a:cd: - 1c:2e:24:87:33:60:e5:c3 ------BEGIN CERTIFICATE----- -MIIFYDCCA0igAwIBAgIUeFhfLq0sGUvjNwc1NBMotZbUZZMwDQYJKoZIhvcNAQEL -BQAwSDELMAkGA1UEBhMCQk0xGTAXBgNVBAoTEFF1b1ZhZGlzIExpbWl0ZWQxHjAc -BgNVBAMTFVF1b1ZhZGlzIFJvb3QgQ0EgMSBHMzAeFw0xMjAxMTIxNzI3NDRaFw00 -MjAxMTIxNzI3NDRaMEgxCzAJBgNVBAYTAkJNMRkwFwYDVQQKExBRdW9WYWRpcyBM -aW1pdGVkMR4wHAYDVQQDExVRdW9WYWRpcyBSb290IENBIDEgRzMwggIiMA0GCSqG -SIb3DQEBAQUAA4ICDwAwggIKAoICAQCgvlAQjunybEC0BJyFuTHK3C3kEakEPBtV -wedYMB0ktMPvhd6MLOHBPd+C5k+tR4ds7FtJwUrVu4/sh6x/gpqG7D0DmVIB0jWe -rNrwU8lmPNSsAgHaJNM7qAJGr6Qc4/hzWHa39g6QDbXwz8z6+cZM5cOGMAqNF341 -68Xfuw6cwI2H44g4hWf6Pser4BOcBRiYz5P1sZK0/CPTz9XEJ0ngnjybCKOLXSoh -4Pw5qlPafX7PGglTvF0FBM+hSo+LdoINofjSxxR3W5A2B4GbPgb6Ul5jxaYA/qXp -UhtStZI5cgMJYr2wYBZupt0lwgNm3fME0UDiTouG9G/lg6AnhF4EwfWQvTA9xO+o -abw4m6SkltFi2mnAAZauy8RRNOoMqv8hjlmPSlzkYZqn0ukqeI1RPToV7qJZjqlc -3sX5kCLliEVx3ZGZbHqfPT2YfF72vhZooF6uCyP8Wg+qInYtyaEQHeTTRCOQiJ/G -KubX9ZqzWB4vMIkIG1SitZgj7Ah3HJVdYdHLiZxfokqRmu8hqkkWCKi9YSgxyXSt -hfbZxbGL0eUQMk1fiyA6PEkfM4VZDdvLCXVDaXP7a3F98N/ETH3Goy7IlXnLc6KO -Tk0k+17kBL5yG6YnLUlamXrXXAkgt3+UuU/xDRxeiEIbEbfnkduebPRq34wGmAOt -zCjvpUfzUwIDAQABo0IwQDAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIB -BjAdBgNVHQ4EFgQUo5fW816iEOGrRZ88F2Q87gFwnMwwDQYJKoZIhvcNAQELBQAD -ggIBABj6W3X8PnrHX3fHyt/PX8MSxEBd1DKquGrX1RUVRpgjpeaQWxiZTOOtQqOC -MTaIzen7xASWSIsBx40Bz1szBpZGZnQdT+3Btrm0DWHMY37XLneMlhwqI2hrhVd2 -cDMT/uFPpiN3GPoajOi9ZcnPP/TJF9zrx7zABC4tRi9pZsMbj/7sPtPKlL92CiUN -qXsCHKnQO18LwIE6PWThv6ctTr1NxNgpxiIY0MWscgKCP6o6ojoilzHdCGPDdRS5 -YCgtW2jgFqlmgiNR9etT2DGbe+m3nUvriBbP+V04ikkwj+3x6xn0dxoxGE1nVGwv -b2X52z3sIexe9PSLymBlVNFxZPT5pqOBMzYzcfCkeF9OrYMh3jRJjehZrJ3ydlo2 -8hP0r+AJx2EqbPfgna67hkooby7utHnNkDPDs3b69fBsnQGQ+p6Q9pxyz0fawx/k -NSBT8lTR32GDpgLiJTjehTItXnOQUl1CxM49S+H5GYQd1aJQzEH7QRTDvdbJWqNj -ZgKAvQU6O0ec7AAmTPWIUb+oI38YB7AL7YsmoWTTYUrrXJ/es69nA7Mf3W1daWhp -q1467HxpvMc7hU6eFbm0FU/DlXpY18ls6Wy58yljXrQs8C097Vpl4KlbQMJImYFt -nh8GKjwStIsPm6Ik8KaN1nrgS7ZklmOVhMJKzRwuJIczYOXD ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: 1289 (0x509) - Signature Algorithm: sha1WithRSAEncryption - Issuer: C=BM, O=QuoVadis Limited, CN=QuoVadis Root CA 2 - Validity - Not Before: Nov 24 18:27:00 2006 GMT - Not After : Nov 24 18:23:33 2031 GMT - Subject: C=BM, O=QuoVadis Limited, CN=QuoVadis Root CA 2 - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (4096 bit) - Modulus: - 00:9a:18:ca:4b:94:0d:00:2d:af:03:29:8a:f0:0f: - 81:c8:ae:4c:19:85:1d:08:9f:ab:29:44:85:f3:2f: - 81:ad:32:1e:90:46:bf:a3:86:26:1a:1e:fe:7e:1c: - 18:3a:5c:9c:60:17:2a:3a:74:83:33:30:7d:61:54: - 11:cb:ed:ab:e0:e6:d2:a2:7e:f5:6b:6f:18:b7:0a: - 0b:2d:fd:e9:3e:ef:0a:c6:b3:10:e9:dc:c2:46:17: - f8:5d:fd:a4:da:ff:9e:49:5a:9c:e6:33:e6:24:96: - f7:3f:ba:5b:2b:1c:7a:35:c2:d6:67:fe:ab:66:50: - 8b:6d:28:60:2b:ef:d7:60:c3:c7:93:bc:8d:36:91: - f3:7f:f8:db:11:13:c4:9c:77:76:c1:ae:b7:02:6a: - 81:7a:a9:45:83:e2:05:e6:b9:56:c1:94:37:8f:48: - 71:63:22:ec:17:65:07:95:8a:4b:df:8f:c6:5a:0a: - e5:b0:e3:5f:5e:6b:11:ab:0c:f9:85:eb:44:e9:f8: - 04:73:f2:e9:fe:5c:98:8c:f5:73:af:6b:b4:7e:cd: - d4:5c:02:2b:4c:39:e1:b2:95:95:2d:42:87:d7:d5: - b3:90:43:b7:6c:13:f1:de:dd:f6:c4:f8:89:3f:d1: - 75:f5:92:c3:91:d5:8a:88:d0:90:ec:dc:6d:de:89: - c2:65:71:96:8b:0d:03:fd:9c:bf:5b:16:ac:92:db: - ea:fe:79:7c:ad:eb:af:f7:16:cb:db:cd:25:2b:e5: - 1f:fb:9a:9f:e2:51:cc:3a:53:0c:48:e6:0e:bd:c9: - b4:76:06:52:e6:11:13:85:72:63:03:04:e0:04:36: - 2b:20:19:02:e8:74:a7:1f:b6:c9:56:66:f0:75:25: - dc:67:c1:0e:61:60:88:b3:3e:d1:a8:fc:a3:da:1d: - b0:d1:b1:23:54:df:44:76:6d:ed:41:d8:c1:b2:22: - b6:53:1c:df:35:1d:dc:a1:77:2a:31:e4:2d:f5:e5: - e5:db:c8:e0:ff:e5:80:d7:0b:63:a0:ff:33:a1:0f: - ba:2c:15:15:ea:97:b3:d2:a2:b5:be:f2:8c:96:1e: - 1a:8f:1d:6c:a4:61:37:b9:86:73:33:d7:97:96:9e: - 23:7d:82:a4:4c:81:e2:a1:d1:ba:67:5f:95:07:a3: - 27:11:ee:16:10:7b:bc:45:4a:4c:b2:04:d2:ab:ef: - d5:fd:0c:51:ce:50:6a:08:31:f9:91:da:0c:8f:64: - 5c:03:c3:3a:8b:20:3f:6e:8d:67:3d:3a:d6:fe:7d: - 5b:88:c9:5e:fb:cc:61:dc:8b:33:77:d3:44:32:35: - 09:62:04:92:16:10:d8:9e:27:47:fb:3b:21:e3:f8: - eb:1d:5b - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Basic Constraints: critical - CA:TRUE - X509v3 Key Usage: - Certificate Sign, CRL Sign - X509v3 Subject Key Identifier: - 1A:84:62:BC:48:4C:33:25:04:D4:EE:D0:F6:03:C4:19:46:D1:94:6B - X509v3 Authority Key Identifier: - keyid:1A:84:62:BC:48:4C:33:25:04:D4:EE:D0:F6:03:C4:19:46:D1:94:6B - DirName:/C=BM/O=QuoVadis Limited/CN=QuoVadis Root CA 2 - serial:05:09 - - Signature Algorithm: sha1WithRSAEncryption - 3e:0a:16:4d:9f:06:5b:a8:ae:71:5d:2f:05:2f:67:e6:13:45: - 83:c4:36:f6:f3:c0:26:0c:0d:b5:47:64:5d:f8:b4:72:c9:46: - a5:03:18:27:55:89:78:7d:76:ea:96:34:80:17:20:dc:e7:83: - f8:8d:fc:07:b8:da:5f:4d:2e:67:b2:84:fd:d9:44:fc:77:50: - 81:e6:7c:b4:c9:0d:0b:72:53:f8:76:07:07:41:47:96:0c:fb: - e0:82:26:93:55:8c:fe:22:1f:60:65:7c:5f:e7:26:b3:f7:32: - 90:98:50:d4:37:71:55:f6:92:21:78:f7:95:79:fa:f8:2d:26: - 87:66:56:30:77:a6:37:78:33:52:10:58:ae:3f:61:8e:f2:6a: - b1:ef:18:7e:4a:59:63:ca:8d:a2:56:d5:a7:2f:bc:56:1f:cf: - 39:c1:e2:fb:0a:a8:15:2c:7d:4d:7a:63:c6:6c:97:44:3c:d2: - 6f:c3:4a:17:0a:f8:90:d2:57:a2:19:51:a5:2d:97:41:da:07: - 4f:a9:50:da:90:8d:94:46:e1:3e:f0:94:fd:10:00:38:f5:3b: - e8:40:e1:b4:6e:56:1a:20:cc:6f:58:8d:ed:2e:45:8f:d6:e9: - 93:3f:e7:b1:2c:df:3a:d6:22:8c:dc:84:bb:22:6f:d0:f8:e4: - c6:39:e9:04:88:3c:c3:ba:eb:55:7a:6d:80:99:24:f5:6c:01: - fb:f8:97:b0:94:5b:eb:fd:d2:6f:f1:77:68:0d:35:64:23:ac: - b8:55:a1:03:d1:4d:42:19:dc:f8:75:59:56:a3:f9:a8:49:79: - f8:af:0e:b9:11:a0:7c:b7:6a:ed:34:d0:b6:26:62:38:1a:87: - 0c:f8:e8:fd:2e:d3:90:7f:07:91:2a:1d:d6:7e:5c:85:83:99: - b0:38:08:3f:e9:5e:f9:35:07:e4:c9:62:6e:57:7f:a7:50:95: - f7:ba:c8:9b:e6:8e:a2:01:c5:d6:66:bf:79:61:f3:3c:1c:e1: - b9:82:5c:5d:a0:c3:e9:d8:48:bd:19:a2:11:14:19:6e:b2:86: - 1b:68:3e:48:37:1a:88:b7:5d:96:5e:9c:c7:ef:27:62:08:e2: - 91:19:5c:d2:f1:21:dd:ba:17:42:82:97:71:81:53:31:a9:9f: - f6:7d:62:bf:72:e1:a3:93:1d:cc:8a:26:5a:09:38:d0:ce:d7: - 0d:80:16:b4:78:a5:3a:87:4c:8d:8a:a5:d5:46:97:f2:2c:10: - b9:bc:54:22:c0:01:50:69:43:9e:f4:b2:ef:6d:f8:ec:da:f1: - e3:b1:ef:df:91:8f:54:2a:0b:25:c1:26:19:c4:52:10:05:65: - d5:82:10:ea:c2:31:cd:2e ------BEGIN CERTIFICATE----- -MIIFtzCCA5+gAwIBAgICBQkwDQYJKoZIhvcNAQEFBQAwRTELMAkGA1UEBhMCQk0x -GTAXBgNVBAoTEFF1b1ZhZGlzIExpbWl0ZWQxGzAZBgNVBAMTElF1b1ZhZGlzIFJv -b3QgQ0EgMjAeFw0wNjExMjQxODI3MDBaFw0zMTExMjQxODIzMzNaMEUxCzAJBgNV -BAYTAkJNMRkwFwYDVQQKExBRdW9WYWRpcyBMaW1pdGVkMRswGQYDVQQDExJRdW9W -YWRpcyBSb290IENBIDIwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQCa -GMpLlA0ALa8DKYrwD4HIrkwZhR0In6spRIXzL4GtMh6QRr+jhiYaHv5+HBg6XJxg -Fyo6dIMzMH1hVBHL7avg5tKifvVrbxi3Cgst/ek+7wrGsxDp3MJGF/hd/aTa/55J -WpzmM+Yklvc/ulsrHHo1wtZn/qtmUIttKGAr79dgw8eTvI02kfN/+NsRE8Scd3bB -rrcCaoF6qUWD4gXmuVbBlDePSHFjIuwXZQeVikvfj8ZaCuWw419eaxGrDPmF60Tp -+ARz8un+XJiM9XOva7R+zdRcAitMOeGylZUtQofX1bOQQ7dsE/He3fbE+Ik/0XX1 -ksOR1YqI0JDs3G3eicJlcZaLDQP9nL9bFqyS2+r+eXyt66/3FsvbzSUr5R/7mp/i -Ucw6UwxI5g69ybR2BlLmEROFcmMDBOAENisgGQLodKcftslWZvB1JdxnwQ5hYIiz -PtGo/KPaHbDRsSNU30R2be1B2MGyIrZTHN81Hdyhdyox5C315eXbyOD/5YDXC2Og -/zOhD7osFRXql7PSorW+8oyWHhqPHWykYTe5hnMz15eWniN9gqRMgeKh0bpnX5UH -oycR7hYQe7xFSkyyBNKr79X9DFHOUGoIMfmR2gyPZFwDwzqLID9ujWc9Otb+fVuI -yV77zGHcizN300QyNQliBJIWENieJ0f7OyHj+OsdWwIDAQABo4GwMIGtMA8GA1Ud -EwEB/wQFMAMBAf8wCwYDVR0PBAQDAgEGMB0GA1UdDgQWBBQahGK8SEwzJQTU7tD2 -A8QZRtGUazBuBgNVHSMEZzBlgBQahGK8SEwzJQTU7tD2A8QZRtGUa6FJpEcwRTEL -MAkGA1UEBhMCQk0xGTAXBgNVBAoTEFF1b1ZhZGlzIExpbWl0ZWQxGzAZBgNVBAMT -ElF1b1ZhZGlzIFJvb3QgQ0EgMoICBQkwDQYJKoZIhvcNAQEFBQADggIBAD4KFk2f -BluornFdLwUvZ+YTRYPENvbzwCYMDbVHZF34tHLJRqUDGCdViXh9duqWNIAXINzn -g/iN/Ae42l9NLmeyhP3ZRPx3UIHmfLTJDQtyU/h2BwdBR5YM++CCJpNVjP4iH2Bl -fF/nJrP3MpCYUNQ3cVX2kiF495V5+vgtJodmVjB3pjd4M1IQWK4/YY7yarHvGH5K -WWPKjaJW1acvvFYfzznB4vsKqBUsfU16Y8Zsl0Q80m/DShcK+JDSV6IZUaUtl0Ha -B0+pUNqQjZRG4T7wlP0QADj1O+hA4bRuVhogzG9Yje0uRY/W6ZM/57Es3zrWIozc -hLsib9D45MY56QSIPMO661V6bYCZJPVsAfv4l7CUW+v90m/xd2gNNWQjrLhVoQPR -TUIZ3Ph1WVaj+ahJefivDrkRoHy3au000LYmYjgahwz46P0u05B/B5EqHdZ+XIWD -mbA4CD/pXvk1B+TJYm5Xf6dQlfe6yJvmjqIBxdZmv3lh8zwc4bmCXF2gw+nYSL0Z -ohEUGW6yhhtoPkg3Goi3XZZenMfvJ2II4pEZXNLxId26F0KCl3GBUzGpn/Z9Yr9y -4aOTHcyKJloJONDO1w2AFrR4pTqHTI2KpdVGl/IsELm8VCLAAVBpQ570su9t+Oza -8eOx79+Rj1QqCyXBJhnEUhAFZdWCEOrCMc0u ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: - 44:57:34:24:5b:81:89:9b:35:f2:ce:b8:2b:3b:5b:a7:26:f0:75:28 - Signature Algorithm: sha256WithRSAEncryption - Issuer: C=BM, O=QuoVadis Limited, CN=QuoVadis Root CA 2 G3 - Validity - Not Before: Jan 12 18:59:32 2012 GMT - Not After : Jan 12 18:59:32 2042 GMT - Subject: C=BM, O=QuoVadis Limited, CN=QuoVadis Root CA 2 G3 - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (4096 bit) - Modulus: - 00:a1:ae:25:b2:01:18:dc:57:88:3f:46:eb:f9:af: - e2:eb:23:71:e2:9a:d1:61:66:21:5f:aa:af:27:51: - e5:6e:1b:16:d4:2d:7d:50:b0:53:77:bd:78:3a:60: - e2:64:02:9b:7c:86:9b:d6:1a:8e:ad:ff:1f:15:7f: - d5:95:1e:12:cb:e6:14:84:04:c1:df:36:b3:16:9f: - 8a:e3:c9:db:98:34:ce:d8:33:17:28:46:fc:a7:c9: - f0:d2:b4:d5:4d:09:72:49:f9:f2:87:e3:a9:da:7d: - a1:7d:6b:b2:3a:25:a9:6d:52:44:ac:f8:be:6e:fb: - dc:a6:73:91:90:61:a6:03:14:20:f2:e7:87:a3:88: - ad:ad:a0:8c:ff:a6:0b:25:52:25:e7:16:01:d5:cb: - b8:35:81:0c:a3:3b:f0:e1:e1:fc:5a:5d:ce:80:71: - 6d:f8:49:ab:3e:3b:ba:b8:d7:80:01:fb:a5:eb:5b: - b3:c5:5e:60:2a:31:a0:af:37:e8:20:3a:9f:a8:32: - 2c:0c:cc:09:1d:d3:9e:8e:5d:bc:4c:98:ee:c5:1a: - 68:7b:ec:53:a6:e9:14:35:a3:df:cd:80:9f:0c:48: - fb:1c:f4:f1:bf:4a:b8:fa:d5:8c:71:4a:c7:1f:ad: - fe:41:9a:b3:83:5d:f2:84:56:ef:a5:57:43:ce:29: - ad:8c:ab:55:bf:c4:fb:5b:01:dd:23:21:a1:58:00: - 8e:c3:d0:6a:13:ed:13:e3:12:2b:80:dc:67:e6:95: - b2:cd:1e:22:6e:2a:f8:41:d4:f2:ca:14:07:8d:8a: - 55:12:c6:69:f5:b8:86:68:2f:53:5e:b0:d2:aa:21: - c1:98:e6:30:e3:67:55:c7:9b:6e:ac:19:a8:55:a6: - 45:06:d0:23:3a:db:eb:65:5d:2a:11:11:f0:3b:4f: - ca:6d:f4:34:c4:71:e4:ff:00:5a:f6:5c:ae:23:60: - 85:73:f1:e4:10:b1:25:ae:d5:92:bb:13:c1:0c:e0: - 39:da:b4:39:57:b5:ab:35:aa:72:21:3b:83:35:e7: - 31:df:7a:21:6e:b8:32:08:7d:1d:32:91:15:4a:62: - 72:cf:e3:77:a1:bc:d5:11:1b:76:01:67:08:e0:41: - 0b:c3:eb:15:6e:f8:a4:19:d9:a2:ab:af:e2:27:52: - 56:2b:02:8a:2c:14:24:f9:bf:42:02:bf:26:c8:c6: - 8f:e0:6e:38:7d:53:2d:e5:ed:98:b3:95:63:68:7f: - f9:35:f4:df:88:c5:60:35:92:c0:7c:69:1c:61:95: - 16:d0:eb:de:0b:af:3e:04:10:45:65:58:50:38:af: - 48:f2:59:b6:16:f2:3c:0d:90:02:c6:70:2e:01:ad: - 3c:15:d7 - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Basic Constraints: critical - CA:TRUE - X509v3 Key Usage: critical - Certificate Sign, CRL Sign - X509v3 Subject Key Identifier: - ED:E7:6F:76:5A:BF:60:EC:49:5B:C6:A5:77:BB:72:16:71:9B:C4:3D - Signature Algorithm: sha256WithRSAEncryption - 91:df:80:3f:43:09:7e:71:c2:f7:eb:b3:88:8f:e1:51:b2:bc: - 3d:75:f9:28:5d:c8:bc:99:9b:7b:5d:aa:e5:ca:e1:0a:f7:e8: - b2:d3:9f:dd:67:31:7e:ba:01:aa:c7:6a:41:3b:90:d4:08:5c: - b2:60:6a:90:f0:c8:ce:03:62:f9:8b:ed:fb:6e:2a:dc:06:4d: - 3c:29:0f:89:16:8a:58:4c:48:0f:e8:84:61:ea:3c:72:a6:77: - e4:42:ae:88:a3:43:58:79:7e:ae:ca:a5:53:0d:a9:3d:70:bd: - 20:19:61:a4:6c:38:fc:43:32:e1:c1:47:ff:f8:ec:f1:11:22: - 32:96:9c:c2:f6:5b:69:96:7b:20:0c:43:41:9a:5b:f6:59:19: - 88:de:55:88:37:51:0b:78:5c:0a:1e:a3:42:fd:c7:9d:88:0f: - c0:f2:78:02:24:54:93:af:89:87:88:c9:4a:80:1d:ea:d0:6e: - 3e:61:2e:36:bb:35:0e:27:96:fd:66:34:3b:61:72:73:f1:16: - 5c:47:06:54:49:00:7a:58:12:b0:0a:ef:85:fd:b1:b8:33:75: - 6a:93:1c:12:e6:60:5e:6f:1d:7f:c9:1f:23:cb:84:61:9f:1e: - 82:44:f9:5f:ad:62:55:24:9a:52:98:ed:51:e7:a1:7e:97:3a: - e6:2f:1f:11:da:53:80:2c:85:9e:ab:35:10:db:22:5f:6a:c5: - 5e:97:53:f2:32:02:09:30:a3:58:f0:0d:01:d5:72:c6:b1:7c: - 69:7b:c3:f5:36:45:cc:61:6e:5e:4c:94:c5:5e:ae:e8:0e:5e: - 8b:bf:f7:cd:e0:ed:a1:0e:1b:33:ee:54:18:fe:0f:be:ef:7e: - 84:6b:43:e3:70:98:db:5d:75:b2:0d:59:07:85:15:23:39:d6: - f1:df:a9:26:0f:d6:48:c7:b3:a6:22:f5:33:37:5a:95:47:9f: - 7b:ba:18:15:6f:ff:d6:14:64:83:49:d2:0a:67:21:db:0f:35: - 63:60:28:22:e3:b1:95:83:cd:85:a6:dd:2f:0f:e7:67:52:6e: - bb:2f:85:7c:f5:4a:73:e7:c5:3e:c0:bd:21:12:05:3f:fc:b7: - 03:49:02:5b:c8:25:e6:e2:54:38:f5:79:87:8c:1d:53:b2:4e: - 85:7b:06:38:c7:2c:f8:f8:b0:72:8d:25:e5:77:52:f4:03:1c: - 48:a6:50:5f:88:20:30:6e:f2:82:43:ab:3d:97:84:e7:53:fb: - 21:c1:4f:0f:22:9a:86:b8:59:2a:f6:47:3d:19:88:2d:e8:85: - e1:9e:ec:85:08:6a:b1:6c:34:c9:1d:ec:48:2b:3b:78:ed:66: - c4:8e:79:69:83:de:7f:8c ------BEGIN CERTIFICATE----- -MIIFYDCCA0igAwIBAgIURFc0JFuBiZs18s64KztbpybwdSgwDQYJKoZIhvcNAQEL -BQAwSDELMAkGA1UEBhMCQk0xGTAXBgNVBAoTEFF1b1ZhZGlzIExpbWl0ZWQxHjAc -BgNVBAMTFVF1b1ZhZGlzIFJvb3QgQ0EgMiBHMzAeFw0xMjAxMTIxODU5MzJaFw00 -MjAxMTIxODU5MzJaMEgxCzAJBgNVBAYTAkJNMRkwFwYDVQQKExBRdW9WYWRpcyBM -aW1pdGVkMR4wHAYDVQQDExVRdW9WYWRpcyBSb290IENBIDIgRzMwggIiMA0GCSqG -SIb3DQEBAQUAA4ICDwAwggIKAoICAQChriWyARjcV4g/Ruv5r+LrI3HimtFhZiFf -qq8nUeVuGxbULX1QsFN3vXg6YOJkApt8hpvWGo6t/x8Vf9WVHhLL5hSEBMHfNrMW -n4rjyduYNM7YMxcoRvynyfDStNVNCXJJ+fKH46nafaF9a7I6JaltUkSs+L5u+9ym -c5GQYaYDFCDy54ejiK2toIz/pgslUiXnFgHVy7g1gQyjO/Dh4fxaXc6AcW34Sas+ -O7q414AB+6XrW7PFXmAqMaCvN+ggOp+oMiwMzAkd056OXbxMmO7FGmh77FOm6RQ1 -o9/NgJ8MSPsc9PG/Srj61YxxSscfrf5BmrODXfKEVu+lV0POKa2Mq1W/xPtbAd0j -IaFYAI7D0GoT7RPjEiuA3GfmlbLNHiJuKvhB1PLKFAeNilUSxmn1uIZoL1NesNKq -IcGY5jDjZ1XHm26sGahVpkUG0CM62+tlXSoREfA7T8pt9DTEceT/AFr2XK4jYIVz -8eQQsSWu1ZK7E8EM4DnatDlXtas1qnIhO4M15zHfeiFuuDIIfR0ykRVKYnLP43eh -vNURG3YBZwjgQQvD6xVu+KQZ2aKrr+InUlYrAoosFCT5v0ICvybIxo/gbjh9Uy3l -7ZizlWNof/k19N+IxWA1ksB8aRxhlRbQ694Lrz4EEEVlWFA4r0jyWbYW8jwNkALG -cC4BrTwV1wIDAQABo0IwQDAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIB -BjAdBgNVHQ4EFgQU7edvdlq/YOxJW8ald7tyFnGbxD0wDQYJKoZIhvcNAQELBQAD -ggIBAJHfgD9DCX5xwvfrs4iP4VGyvD11+ShdyLyZm3tdquXK4Qr36LLTn91nMX66 -AarHakE7kNQIXLJgapDwyM4DYvmL7ftuKtwGTTwpD4kWilhMSA/ohGHqPHKmd+RC -roijQ1h5fq7KpVMNqT1wvSAZYaRsOPxDMuHBR//47PERIjKWnML2W2mWeyAMQ0Ga -W/ZZGYjeVYg3UQt4XAoeo0L9x52ID8DyeAIkVJOviYeIyUqAHerQbj5hLja7NQ4n -lv1mNDthcnPxFlxHBlRJAHpYErAK74X9sbgzdWqTHBLmYF5vHX/JHyPLhGGfHoJE -+V+tYlUkmlKY7VHnoX6XOuYvHxHaU4AshZ6rNRDbIl9qxV6XU/IyAgkwo1jwDQHV -csaxfGl7w/U2Rcxhbl5MlMVerugOXou/983g7aEOGzPuVBj+D77vfoRrQ+NwmNtd -dbINWQeFFSM51vHfqSYP1kjHs6Yi9TM3WpVHn3u6GBVv/9YUZINJ0gpnIdsPNWNg -KCLjsZWDzYWm3S8P52dSbrsvhXz1SnPnxT7AvSESBT/8twNJAlvIJebiVDj1eYeM -HVOyToV7BjjHLPj4sHKNJeV3UvQDHEimUF+IIDBu8oJDqz2XhOdT+yHBTw8imoa4 -WSr2Rz0ZiC3oheGe7IUIarFsNMkd7EgrO3jtZsSOeWmD3n+M ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: 1478 (0x5c6) - Signature Algorithm: sha1WithRSAEncryption - Issuer: C=BM, O=QuoVadis Limited, CN=QuoVadis Root CA 3 - Validity - Not Before: Nov 24 19:11:23 2006 GMT - Not After : Nov 24 19:06:44 2031 GMT - Subject: C=BM, O=QuoVadis Limited, CN=QuoVadis Root CA 3 - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (4096 bit) - Modulus: - 00:cc:57:42:16:54:9c:e6:98:d3:d3:4d:ee:fe:ed: - c7:9f:43:39:4a:65:b3:e8:16:88:34:db:0d:59:91: - 74:cf:92:b8:04:40:ad:02:4b:31:ab:bc:8d:91:68: - d8:20:0e:1a:01:e2:1a:7b:4e:17:5d:e2:8a:b7:3f: - 99:1a:cd:eb:61:ab:c2:65:a6:1f:b7:b7:bd:b7:8f: - fc:fd:70:8f:0b:a0:67:be:01:a2:59:cf:71:e6:0f: - 29:76:ff:b1:56:79:45:2b:1f:9e:7a:54:e8:a3:29: - 35:68:a4:01:4f:0f:a4:2e:37:ef:1b:bf:e3:8f:10: - a8:72:ab:58:57:e7:54:86:c8:c9:f3:5b:da:2c:da: - 5d:8e:6e:3c:a3:3e:da:fb:82:e5:dd:f2:5c:b2:05: - 33:6f:8a:36:ce:d0:13:4e:ff:bf:4a:0c:34:4c:a6: - c3:21:bd:50:04:55:eb:b1:bb:9d:fb:45:1e:64:15: - de:55:01:8c:02:76:b5:cb:a1:3f:42:69:bc:2f:bd: - 68:43:16:56:89:2a:37:61:91:fd:a6:ae:4e:c0:cb: - 14:65:94:37:4b:92:06:ef:04:d0:c8:9c:88:db:0b: - 7b:81:af:b1:3d:2a:c4:65:3a:78:b6:ee:dc:80:b1: - d2:d3:99:9c:3a:ee:6b:5a:6b:b3:8d:b7:d5:ce:9c: - c2:be:a5:4b:2f:16:b1:9e:68:3b:06:6f:ae:7d:9f: - f8:de:ec:cc:29:a7:98:a3:25:43:2f:ef:f1:5f:26: - e1:88:4d:f8:5e:6e:d7:d9:14:6e:19:33:69:a7:3b: - 84:89:93:c4:53:55:13:a1:51:78:40:f8:b8:c9:a2: - ee:7b:ba:52:42:83:9e:14:ed:05:52:5a:59:56:a7: - 97:fc:9d:3f:0a:29:d8:dc:4f:91:0e:13:bc:de:95: - a4:df:8b:99:be:ac:9b:33:88:ef:b5:81:af:1b:c6: - 22:53:c8:f6:c7:ee:97:14:b0:c5:7c:78:52:c8:f0: - ce:6e:77:60:84:a6:e9:2a:76:20:ed:58:01:17:30: - 93:e9:1a:8b:e0:73:63:d9:6a:92:94:49:4e:b4:ad: - 4a:85:c4:a3:22:30:fc:09:ed:68:22:73:a6:88:0c: - 55:21:58:c5:e1:3a:9f:2a:dd:ca:e1:90:e0:d9:73: - ab:6c:80:b8:e8:0b:64:93:a0:9c:8c:19:ff:b3:d2: - 0c:ec:91:26:87:8a:b3:a2:e1:70:8f:2c:0a:e5:cd: - 6d:68:51:eb:da:3f:05:7f:8b:32:e6:13:5c:6b:fe: - 5f:40:e2:22:c8:b4:b4:64:4f:d6:ba:7d:48:3e:a8: - 69:0c:d7:bb:86:71:c9:73:b8:3f:3b:9d:25:4b:da: - ff:40:eb - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Basic Constraints: critical - CA:TRUE - X509v3 Certificate Policies: - Policy: 1.3.6.1.4.1.8024.0.3 - User Notice: - Explicit Text: Any use of this Certificate constitutes acceptance of the QuoVadis Root CA 3 Certificate Policy / Certification Practice Statement. - CPS: http://www.quovadisglobal.com/cps - - X509v3 Key Usage: - Certificate Sign, CRL Sign - X509v3 Subject Key Identifier: - F2:C0:13:E0:82:43:3E:FB:EE:2F:67:32:96:35:5C:DB:B8:CB:02:D0 - X509v3 Authority Key Identifier: - keyid:F2:C0:13:E0:82:43:3E:FB:EE:2F:67:32:96:35:5C:DB:B8:CB:02:D0 - DirName:/C=BM/O=QuoVadis Limited/CN=QuoVadis Root CA 3 - serial:05:C6 - - Signature Algorithm: sha1WithRSAEncryption - 4f:ad:a0:2c:4c:fa:c0:f2:6f:f7:66:55:ab:23:34:ee:e7:29: - da:c3:5b:b6:b0:83:d9:d0:d0:e2:21:fb:f3:60:a7:3b:5d:60: - 53:27:a2:9b:f6:08:22:2a:e7:bf:a0:72:e5:9c:24:6a:31:b1: - 90:7a:27:db:84:11:89:27:a6:77:5a:38:d7:bf:ac:86:fc:ee: - 5d:83:bc:06:c6:d1:77:6b:0f:6d:24:2f:4b:7a:6c:a7:07:96: - ca:e3:84:9f:ad:88:8b:1d:ab:16:8d:5b:66:17:d9:16:f4:8b: - 80:d2:dd:f8:b2:76:c3:fc:38:13:aa:0c:de:42:69:2b:6e:f3: - 3c:eb:80:27:db:f5:a6:44:0d:9f:5a:55:59:0b:d5:0d:52:48: - c5:ae:9f:f2:2f:80:c5:ea:32:50:35:12:97:2e:c1:e1:ff:f1: - 23:88:51:38:9f:f2:66:56:76:e7:0f:51:97:a5:52:0c:4d:49: - 51:95:36:3d:bf:a2:4b:0c:10:1d:86:99:4c:aa:f3:72:11:93: - e4:ea:f6:9b:da:a8:5d:a7:4d:b7:9e:02:ae:73:00:c8:da:23: - 03:e8:f9:ea:19:74:62:00:94:cb:22:20:be:94:a7:59:b5:82: - 6a:be:99:79:7a:a9:f2:4a:24:52:f7:74:fd:ba:4e:e6:a8:1d: - 02:6e:b1:0d:80:44:c1:ae:d3:23:37:5f:bb:85:7c:2b:92:2e: - e8:7e:a5:8b:dd:99:e1:bf:27:6f:2d:5d:aa:7b:87:fe:0a:dd: - 4b:fc:8e:f5:26:e4:6e:70:42:6e:33:ec:31:9e:7b:93:c1:e4: - c9:69:1a:3d:c0:6b:4e:22:6d:ee:ab:58:4d:c6:d0:41:c1:2b: - ea:4f:12:87:5e:eb:45:d8:6c:f5:98:02:d3:a0:d8:55:8a:06: - 99:19:a2:a0:77:d1:30:9e:ac:cc:75:ee:83:f5:b0:62:39:cf: - 6c:57:e2:4c:d2:91:0b:0e:75:28:1b:9a:bf:fd:1a:43:f1:ca: - 77:fb:3b:8f:61:b8:69:28:16:42:04:5e:70:2a:1c:21:d8:8f: - e1:bd:23:5b:2d:74:40:92:d9:63:19:0d:73:dd:69:bc:62:47: - bc:e0:74:2b:b2:eb:7d:be:41:1b:b5:c0:46:c5:a1:22:cb:5f: - 4e:c1:28:92:de:18:ba:d5:2a:28:bb:11:8b:17:93:98:99:60: - 94:5c:23:cf:5a:27:97:5e:0b:05:06:93:37:1e:3b:69:36:eb: - a9:9e:61:1d:8f:32:da:8e:0c:d6:74:3e:7b:09:24:da:01:77: - 47:c4:3b:cd:34:8c:99:f5:ca:e1:25:61:33:b2:59:1b:e2:6e: - d7:37:57:b6:0d:a9:12:da ------BEGIN CERTIFICATE----- -MIIGnTCCBIWgAwIBAgICBcYwDQYJKoZIhvcNAQEFBQAwRTELMAkGA1UEBhMCQk0x -GTAXBgNVBAoTEFF1b1ZhZGlzIExpbWl0ZWQxGzAZBgNVBAMTElF1b1ZhZGlzIFJv -b3QgQ0EgMzAeFw0wNjExMjQxOTExMjNaFw0zMTExMjQxOTA2NDRaMEUxCzAJBgNV -BAYTAkJNMRkwFwYDVQQKExBRdW9WYWRpcyBMaW1pdGVkMRswGQYDVQQDExJRdW9W -YWRpcyBSb290IENBIDMwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQDM -V0IWVJzmmNPTTe7+7cefQzlKZbPoFog02w1ZkXTPkrgEQK0CSzGrvI2RaNggDhoB -4hp7Thdd4oq3P5kazethq8Jlph+3t723j/z9cI8LoGe+AaJZz3HmDyl2/7FWeUUr -H556VOijKTVopAFPD6QuN+8bv+OPEKhyq1hX51SGyMnzW9os2l2ObjyjPtr7guXd -8lyyBTNvijbO0BNO/79KDDRMpsMhvVAEVeuxu537RR5kFd5VAYwCdrXLoT9Cabwv -vWhDFlaJKjdhkf2mrk7AyxRllDdLkgbvBNDInIjbC3uBr7E9KsRlOni27tyAsdLT -mZw67mtaa7ONt9XOnMK+pUsvFrGeaDsGb659n/je7Mwpp5ijJUMv7/FfJuGITfhe -btfZFG4ZM2mnO4SJk8RTVROhUXhA+LjJou57ulJCg54U7QVSWllWp5f8nT8KKdjc -T5EOE7zelaTfi5m+rJsziO+1ga8bxiJTyPbH7pcUsMV8eFLI8M5ud2CEpukqdiDt -WAEXMJPpGovgc2PZapKUSU60rUqFxKMiMPwJ7Wgic6aIDFUhWMXhOp8q3crhkODZ -c6tsgLjoC2SToJyMGf+z0gzskSaHirOi4XCPLArlzW1oUevaPwV/izLmE1xr/l9A -4iLItLRkT9a6fUg+qGkM17uGcclzuD87nSVL2v9A6wIDAQABo4IBlTCCAZEwDwYD -VR0TAQH/BAUwAwEB/zCB4QYDVR0gBIHZMIHWMIHTBgkrBgEEAb5YAAMwgcUwgZMG -CCsGAQUFBwICMIGGGoGDQW55IHVzZSBvZiB0aGlzIENlcnRpZmljYXRlIGNvbnN0 -aXR1dGVzIGFjY2VwdGFuY2Ugb2YgdGhlIFF1b1ZhZGlzIFJvb3QgQ0EgMyBDZXJ0 -aWZpY2F0ZSBQb2xpY3kgLyBDZXJ0aWZpY2F0aW9uIFByYWN0aWNlIFN0YXRlbWVu -dC4wLQYIKwYBBQUHAgEWIWh0dHA6Ly93d3cucXVvdmFkaXNnbG9iYWwuY29tL2Nw -czALBgNVHQ8EBAMCAQYwHQYDVR0OBBYEFPLAE+CCQz777i9nMpY1XNu4ywLQMG4G -A1UdIwRnMGWAFPLAE+CCQz777i9nMpY1XNu4ywLQoUmkRzBFMQswCQYDVQQGEwJC -TTEZMBcGA1UEChMQUXVvVmFkaXMgTGltaXRlZDEbMBkGA1UEAxMSUXVvVmFkaXMg -Um9vdCBDQSAzggIFxjANBgkqhkiG9w0BAQUFAAOCAgEAT62gLEz6wPJv92ZVqyM0 -7ucp2sNbtrCD2dDQ4iH782CnO11gUyeim/YIIirnv6By5ZwkajGxkHon24QRiSem -d1o417+shvzuXYO8BsbRd2sPbSQvS3pspweWyuOEn62Iix2rFo1bZhfZFvSLgNLd -+LJ2w/w4E6oM3kJpK27zPOuAJ9v1pkQNn1pVWQvVDVJIxa6f8i+AxeoyUDUSly7B -4f/xI4hROJ/yZlZ25w9Rl6VSDE1JUZU2Pb+iSwwQHYaZTKrzchGT5Or2m9qoXadN -t54CrnMAyNojA+j56hl0YgCUyyIgvpSnWbWCar6ZeXqp8kokUvd0/bpO5qgdAm6x -DYBEwa7TIzdfu4V8K5Iu6H6li92Z4b8nby1dqnuH/grdS/yO9SbkbnBCbjPsMZ57 -k8HkyWkaPcBrTiJt7qtYTcbQQcEr6k8Sh17rRdhs9ZgC06DYVYoGmRmioHfRMJ6s -zHXug/WwYjnPbFfiTNKRCw51KBuav/0aQ/HKd/s7j2G4aSgWQgRecCocIdiP4b0j -Wy10QJLZYxkNc91pvGJHvOB0K7Lrfb5BG7XARsWhIstfTsEokt4YutUqKLsRixeT -mJlglFwjz1onl14LBQaTNx47aTbrqZ5hHY8y2o4M1nQ+ewkk2gF3R8Q7zTSMmfXK -4SVhM7JZG+Ju1zdXtg2pEto= ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: - 2e:f5:9b:02:28:a7:db:7a:ff:d5:a3:a9:ee:bd:03:a0:cf:12:6a:1d - Signature Algorithm: sha256WithRSAEncryption - Issuer: C=BM, O=QuoVadis Limited, CN=QuoVadis Root CA 3 G3 - Validity - Not Before: Jan 12 20:26:32 2012 GMT - Not After : Jan 12 20:26:32 2042 GMT - Subject: C=BM, O=QuoVadis Limited, CN=QuoVadis Root CA 3 G3 - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (4096 bit) - Modulus: - 00:b3:cb:0e:10:67:8e:ea:14:97:a7:32:2a:0a:56: - 36:7f:68:4c:c7:b3:6f:3a:23:14:91:ff:19:7f:a5: - ca:ac:ee:b3:76:9d:7a:e9:8b:1b:ab:6b:31:db:fa: - 0b:53:4c:af:c5:a5:1a:79:3c:8a:4c:ff:ac:df:25: - de:4e:d9:82:32:0b:44:de:ca:db:8c:ac:a3:6e:16: - 83:3b:a6:64:4b:32:89:fb:16:16:38:7e:eb:43:e2: - d3:74:4a:c2:62:0a:73:0a:dd:49:b3:57:d2:b0:0a: - 85:9d:71:3c:de:a3:cb:c0:32:f3:01:39:20:43:1b: - 35:d1:53:b3:b1:ee:c5:93:69:82:3e:16:b5:28:46: - a1:de:ea:89:09:ed:43:b8:05:46:8a:86:f5:59:47: - be:1b:6f:01:21:10:b9:fd:a9:d2:28:ca:10:39:09: - ca:13:36:cf:9c:ad:ad:40:74:79:2b:02:3f:34:ff: - fa:20:69:7d:d3:ee:61:f5:ba:b3:e7:30:d0:37:23: - 86:72:61:45:29:48:59:68:6f:77:a6:2e:81:be:07: - 4d:6f:af:ce:c4:45:13:91:14:70:06:8f:1f:9f:f8: - 87:69:b1:0e:ef:c3:89:19:eb:ea:1c:61:fc:7a:6c: - 8a:dc:d6:03:0b:9e:26:ba:12:dd:d4:54:39:ab:26: - a3:33:ea:75:81:da:2d:cd:0f:4f:e4:03:d1:ef:15: - 97:1b:6b:90:c5:02:90:93:66:02:21:b1:47:de:8b: - 9a:4a:80:b9:55:8f:b5:a2:2f:c0:d6:33:67:da:7e: - c4:a7:b4:04:44:eb:47:fb:e6:58:b9:f7:0c:f0:7b: - 2b:b1:c0:70:29:c3:40:62:2d:3b:48:69:dc:23:3c: - 48:eb:7b:09:79:a9:6d:da:a8:30:98:cf:80:72:03: - 88:a6:5b:46:ae:72:79:7c:08:03:21:65:ae:b7:e1: - 1c:a5:b1:2a:a2:31:de:66:04:f7:c0:74:e8:71:de: - ff:3d:59:cc:96:26:12:8b:85:95:57:1a:ab:6b:75: - 0b:44:3d:11:28:3c:7b:61:b7:e2:8f:67:4f:e5:ec: - 3c:4c:60:80:69:57:38:1e:01:5b:8d:55:e8:c7:df: - c0:cc:77:23:34:49:75:7c:f6:98:11:eb:2d:de:ed: - 41:2e:14:05:02:7f:e0:fe:20:eb:35:e7:11:ac:22: - ce:57:3d:de:c9:30:6d:10:03:85:cd:f1:ff:8c:16: - b5:c1:b2:3e:88:6c:60:7f:90:4f:95:f7:f6:2d:ad: - 01:39:07:04:fa:75:80:7d:bf:49:50:ed:ef:c9:c4: - 7c:1c:eb:80:7e:db:b6:d0:dd:13:fe:c9:d3:9c:d7: - b2:97:a9 - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Basic Constraints: critical - CA:TRUE - X509v3 Key Usage: critical - Certificate Sign, CRL Sign - X509v3 Subject Key Identifier: - C6:17:D0:BC:A8:EA:02:43:F2:1B:06:99:5D:2B:90:20:B9:D7:9C:E4 - Signature Algorithm: sha256WithRSAEncryption - 34:61:d9:56:b5:12:87:55:4d:dd:a3:35:31:46:bb:a4:07:72: - bc:5f:61:62:e8:a5:fb:0b:37:b1:3c:b6:b3:fa:29:9d:7f:02: - f5:a4:c9:a8:93:b7:7a:71:28:69:8f:73:e1:52:90:da:d5:be: - 3a:e5:b7:76:6a:56:80:21:df:5d:e6:e9:3a:9e:e5:3e:f6:a2: - 69:c7:2a:0a:b0:18:47:dc:20:70:7d:52:a3:3e:59:7c:c1:ba: - c9:c8:15:40:61:ca:72:d6:70:ac:d2:b7:f0:1c:e4:86:29:f0: - ce:ef:68:63:d0:b5:20:8a:15:61:9a:7e:86:98:b4:c9:c2:76: - fb:cc:ba:30:16:cc:a3:61:c6:74:13:e5:6b:ef:a3:15:ea:03: - fe:13:8b:64:e4:d3:c1:d2:e8:84:fb:49:d1:10:4d:79:66:eb: - aa:fd:f4:8d:31:1e:70:14:ad:dc:de:67:13:4c:81:15:61:bc: - b7:d9:91:77:71:19:81:60:bb:f0:58:a5:b5:9c:0b:f7:8f:22: - 55:27:c0:4b:01:6d:3b:99:0d:d4:1d:9b:63:67:2f:d0:ee:0d: - ca:66:bc:94:4f:a6:ad:ed:fc:ee:63:ac:57:3f:65:25:cf:b2: - 86:8f:d0:08:ff:b8:76:14:6e:de:e5:27:ec:ab:78:b5:53:b9: - b6:3f:e8:20:f9:d2:a8:be:61:46:ca:87:8c:84:f3:f9:f1:a0: - 68:9b:22:1e:81:26:9b:10:04:91:71:c0:06:1f:dc:a0:d3:b9: - 56:a7:e3:98:2d:7f:83:9d:df:8c:2b:9c:32:8e:32:94:f0:01: - 3c:22:2a:9f:43:c2:2e:c3:98:39:07:38:7b:fc:5e:00:42:1f: - f3:32:26:79:83:84:f6:e5:f0:c1:51:12:c0:0b:1e:04:23:0c: - 54:a5:4c:2f:49:c5:4a:d1:b6:6e:60:0d:6b:fc:6b:8b:85:24: - 64:b7:89:0e:ab:25:47:5b:3c:cf:7e:49:bd:c7:e9:0a:c6:da: - f7:7e:0e:17:08:d3:48:97:d0:71:92:f0:0f:39:3e:34:6a:1c: - 7d:d8:f2:22:ae:bb:69:f4:33:b4:a6:48:55:d1:0f:0e:26:e8: - ec:b6:0b:2d:a7:85:35:cd:fd:59:c8:9f:d1:cd:3e:5a:29:34: - b9:3d:84:ce:b1:65:d4:59:91:91:56:75:21:c1:77:9e:f9:7a: - e1:60:9d:d3:ad:04:18:f4:7c:eb:5e:93:8f:53:4a:22:29:f8: - 48:2b:3e:4d:86:ac:5b:7f:cb:06:99:59:60:d8:58:65:95:8d: - 44:d1:f7:7f:7e:27:7f:7d:ae:80:f5:07:4c:b6:3e:9c:71:54: - 99:04:4b:fd:58:f9:98:f4 ------BEGIN CERTIFICATE----- -MIIFYDCCA0igAwIBAgIULvWbAiin23r/1aOp7r0DoM8Sah0wDQYJKoZIhvcNAQEL -BQAwSDELMAkGA1UEBhMCQk0xGTAXBgNVBAoTEFF1b1ZhZGlzIExpbWl0ZWQxHjAc -BgNVBAMTFVF1b1ZhZGlzIFJvb3QgQ0EgMyBHMzAeFw0xMjAxMTIyMDI2MzJaFw00 -MjAxMTIyMDI2MzJaMEgxCzAJBgNVBAYTAkJNMRkwFwYDVQQKExBRdW9WYWRpcyBM -aW1pdGVkMR4wHAYDVQQDExVRdW9WYWRpcyBSb290IENBIDMgRzMwggIiMA0GCSqG -SIb3DQEBAQUAA4ICDwAwggIKAoICAQCzyw4QZ47qFJenMioKVjZ/aEzHs286IxSR -/xl/pcqs7rN2nXrpixurazHb+gtTTK/FpRp5PIpM/6zfJd5O2YIyC0TeytuMrKNu -FoM7pmRLMon7FhY4futD4tN0SsJiCnMK3UmzV9KwCoWdcTzeo8vAMvMBOSBDGzXR -U7Ox7sWTaYI+FrUoRqHe6okJ7UO4BUaKhvVZR74bbwEhELn9qdIoyhA5CcoTNs+c -ra1AdHkrAj80//ogaX3T7mH1urPnMNA3I4ZyYUUpSFlob3emLoG+B01vr87ERROR -FHAGjx+f+IdpsQ7vw4kZ6+ocYfx6bIrc1gMLnia6Et3UVDmrJqMz6nWB2i3ND0/k -A9HvFZcba5DFApCTZgIhsUfei5pKgLlVj7WiL8DWM2fafsSntARE60f75li59wzw -eyuxwHApw0BiLTtIadwjPEjrewl5qW3aqDCYz4ByA4imW0aucnl8CAMhZa634Ryl -sSqiMd5mBPfAdOhx3v89WcyWJhKLhZVXGqtrdQtEPREoPHtht+KPZ0/l7DxMYIBp -VzgeAVuNVejH38DMdyM0SXV89pgR6y3e7UEuFAUCf+D+IOs15xGsIs5XPd7JMG0Q -A4XN8f+MFrXBsj6IbGB/kE+V9/YtrQE5BwT6dYB9v0lQ7e/JxHwc64B+27bQ3RP+ -ydOc17KXqQIDAQABo0IwQDAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIB -BjAdBgNVHQ4EFgQUxhfQvKjqAkPyGwaZXSuQILnXnOQwDQYJKoZIhvcNAQELBQAD -ggIBADRh2Va1EodVTd2jNTFGu6QHcrxfYWLopfsLN7E8trP6KZ1/AvWkyaiTt3px -KGmPc+FSkNrVvjrlt3ZqVoAh313m6Tqe5T72omnHKgqwGEfcIHB9UqM+WXzBusnI -FUBhynLWcKzSt/Ac5IYp8M7vaGPQtSCKFWGafoaYtMnCdvvMujAWzKNhxnQT5Wvv -oxXqA/4Ti2Tk08HS6IT7SdEQTXlm66r99I0xHnAUrdzeZxNMgRVhvLfZkXdxGYFg -u/BYpbWcC/ePIlUnwEsBbTuZDdQdm2NnL9DuDcpmvJRPpq3t/O5jrFc/ZSXPsoaP -0Aj/uHYUbt7lJ+yreLVTubY/6CD50qi+YUbKh4yE8/nxoGibIh6BJpsQBJFxwAYf -3KDTuVan45gtf4Od34wrnDKOMpTwATwiKp9Dwi7DmDkHOHv8XgBCH/MyJnmDhPbl -8MFREsALHgQjDFSlTC9JxUrRtm5gDWv8a4uFJGS3iQ6rJUdbPM9+Sb3H6QrG2vd+ -DhcI00iX0HGS8A85PjRqHH3Y8iKuu2n0M7SmSFXRDw4m6Oy2Cy2nhTXN/VnIn9HN -PlopNLk9hM6xZdRZkZFWdSHBd575euFgndOtBBj0fOtek49TSiIp+EgrPk2GrFt/ -ywaZWWDYWGWVjUTR939+J399roD1B0y2PpxxVJkES/1Y+Zj0 ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: - 3e:8a:5d:07:ec:55:d2:32:d5:b7:e3:b6:5f:01:eb:2d:dc:e4:d6:e4 - Signature Algorithm: sha256WithRSAEncryption - Issuer: C=PL, O=Krajowa Izba Rozliczeniowa S.A., CN=SZAFIR ROOT CA2 - Validity - Not Before: Oct 19 07:43:30 2015 GMT - Not After : Oct 19 07:43:30 2035 GMT - Subject: C=PL, O=Krajowa Izba Rozliczeniowa S.A., CN=SZAFIR ROOT CA2 - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (2048 bit) - Modulus: - 00:b7:bc:3e:50:a8:4b:cd:40:b5:ce:61:e7:96:ca: - b4:a1:da:0c:22:b0:fa:b5:7b:76:00:77:8c:0b:cf: - 7d:a8:86:cc:26:51:e4:20:3d:85:0c:d6:58:e3:e7: - f4:2a:18:9d:da:d1:ae:26:ee:eb:53:dc:f4:90:d6: - 13:4a:0c:90:3c:c3:f4:da:d2:8e:0d:92:3a:dc:b1: - b1:ff:38:de:c3:ba:2d:5f:80:b9:02:bd:4a:9d:1b: - 0f:b4:c3:c2:c1:67:03:dd:dc:1b:9c:3d:b3:b0:de: - 00:1e:a8:34:47:bb:9a:eb:fe:0b:14:bd:36:84:da: - 0d:20:bf:fa:5b:cb:a9:16:20:ad:39:60:ee:2f:75: - b6:e7:97:9c:f9:3e:fd:7e:4d:6f:4d:2f:ef:88:0d: - 6a:fa:dd:f1:3d:6e:20:a5:a0:12:b4:4d:70:b9:ce: - d7:72:3b:89:93:a7:80:84:1c:27:49:72:49:b5:ff: - 3b:95:9e:c1:cc:c8:01:ec:e8:0e:8a:0a:96:e7:b3: - a6:87:e5:d6:f9:05:2b:0d:97:40:70:3c:ba:ac:75: - 5a:9c:d5:4d:9d:02:0a:d2:4b:9b:66:4b:46:07:17: - 65:ad:9f:6c:88:00:dc:22:89:e0:e1:64:d4:67:bc: - 31:79:61:3c:bb:ca:41:cd:5c:6a:00:c8:3c:38:8e: - 58:af - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Basic Constraints: critical - CA:TRUE - X509v3 Key Usage: critical - Certificate Sign, CRL Sign - X509v3 Subject Key Identifier: - 2E:16:A9:4A:18:B5:CB:CC:F5:6F:50:F3:23:5F:F8:5D:E7:AC:F0:C8 - Signature Algorithm: sha256WithRSAEncryption - b5:73:f8:03:dc:59:5b:1d:76:e9:a3:2a:7b:90:28:b2:4d:c0: - 33:4f:aa:9a:b1:d4:b8:e4:27:ff:a9:96:99:ce:46:e0:6d:7c: - 4c:a2:38:a4:06:70:f0:f4:41:11:ec:3f:47:8d:3f:72:87:f9: - 3b:fd:a4:6f:2b:53:00:e0:ff:39:b9:6a:07:0e:eb:1d:1c:f6: - a2:72:90:cb:82:3d:11:82:8b:d2:bb:9f:2a:af:21:e6:63:86: - 9d:79:19:ef:f7:bb:0c:35:90:c3:8a:ed:4f:0f:f5:cc:12:d9: - a4:3e:bb:a0:fc:20:95:5f:4f:26:2f:11:23:83:4e:75:07:0f: - bf:9b:d1:b4:1d:e9:10:04:fe:ca:60:8f:a2:4c:b8:ad:cf:e1: - 90:0f:cd:ae:0a:c7:5d:7b:b7:50:d2:d4:61:fa:d5:15:db:d7: - 9f:87:51:54:eb:a5:e3:eb:c9:85:a0:25:20:37:fb:8e:ce:0c: - 34:84:e1:3c:81:b2:77:4e:43:a5:88:5f:86:67:a1:3d:e6:b4: - 5c:61:b6:3e:db:fe:b7:28:c5:a2:07:ae:b5:ca:ca:8d:2a:12: - ef:97:ed:c2:30:a4:c9:2a:7a:fb:f3:4d:23:1b:99:33:34:a0: - 2e:f5:a9:0b:3f:d4:5d:e1:cf:84:9f:e2:19:c2:5f:8a:d6:20: - 1e:e3:73:b7 ------BEGIN CERTIFICATE----- -MIIDcjCCAlqgAwIBAgIUPopdB+xV0jLVt+O2XwHrLdzk1uQwDQYJKoZIhvcNAQEL -BQAwUTELMAkGA1UEBhMCUEwxKDAmBgNVBAoMH0tyYWpvd2EgSXpiYSBSb3psaWN6 -ZW5pb3dhIFMuQS4xGDAWBgNVBAMMD1NaQUZJUiBST09UIENBMjAeFw0xNTEwMTkw -NzQzMzBaFw0zNTEwMTkwNzQzMzBaMFExCzAJBgNVBAYTAlBMMSgwJgYDVQQKDB9L -cmFqb3dhIEl6YmEgUm96bGljemVuaW93YSBTLkEuMRgwFgYDVQQDDA9TWkFGSVIg -Uk9PVCBDQTIwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQC3vD5QqEvN -QLXOYeeWyrSh2gwisPq1e3YAd4wLz32ohswmUeQgPYUM1ljj5/QqGJ3a0a4m7utT -3PSQ1hNKDJA8w/Ta0o4NkjrcsbH/ON7Dui1fgLkCvUqdGw+0w8LBZwPd3BucPbOw -3gAeqDRHu5rr/gsUvTaE2g0gv/pby6kWIK05YO4vdbbnl5z5Pv1+TW9NL++IDWr6 -3fE9biCloBK0TXC5ztdyO4mTp4CEHCdJckm1/zuVnsHMyAHs6A6KCpbns6aH5db5 -BSsNl0BwPLqsdVqc1U2dAgrSS5tmS0YHF2Wtn2yIANwiieDhZNRnvDF5YTy7ykHN -XGoAyDw4jlivAgMBAAGjQjBAMA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQD -AgEGMB0GA1UdDgQWBBQuFqlKGLXLzPVvUPMjX/hd56zwyDANBgkqhkiG9w0BAQsF -AAOCAQEAtXP4A9xZWx126aMqe5Aosk3AM0+qmrHUuOQn/6mWmc5G4G18TKI4pAZw -8PRBEew/R40/cof5O/2kbytTAOD/OblqBw7rHRz2onKQy4I9EYKL0rufKq8h5mOG -nXkZ7/e7DDWQw4rtTw/1zBLZpD67oPwglV9PJi8RI4NOdQcPv5vRtB3pEAT+ymCP -oky4rc/hkA/NrgrHXXu3UNLUYfrVFdvXn4dRVOul4+vJhaAlIDf7js4MNIThPIGy -d05DpYhfhmehPea0XGG2Ptv+tyjFogeutcrKjSoS75ftwjCkySp6+/NNIxuZMzSg -LvWpCz/UXeHPhJ/iGcJfitYgHuNztw== ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: 1 (0x1) - Signature Algorithm: sha1WithRSAEncryption - Issuer: C=JP, O=Japan Certification Services, Inc., CN=SecureSign RootCA11 - Validity - Not Before: Apr 8 04:56:47 2009 GMT - Not After : Apr 8 04:56:47 2029 GMT - Subject: C=JP, O=Japan Certification Services, Inc., CN=SecureSign RootCA11 - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (2048 bit) - Modulus: - 00:fd:77:aa:a5:1c:90:05:3b:cb:4c:9b:33:8b:5a: - 14:45:a4:e7:90:16:d1:df:57:d2:21:10:a4:17:fd: - df:ac:d6:1f:a7:e4:db:7c:f7:ec:df:b8:03:da:94: - 58:fd:5d:72:7c:8c:3f:5f:01:67:74:15:96:e3:02: - 3c:87:db:ae:cb:01:8e:c2:f3:66:c6:85:45:f4:02: - c6:3a:b5:62:b2:af:fa:9c:bf:a4:e6:d4:80:30:98: - f3:0d:b6:93:8f:a9:d4:d8:36:f2:b0:fc:8a:ca:2c: - a1:15:33:95:31:da:c0:1b:f2:ee:62:99:86:63:3f: - bf:dd:93:2a:83:a8:76:b9:13:1f:b7:ce:4e:42:85: - 8f:22:e7:2e:1a:f2:95:09:b2:05:b5:44:4e:77:a1: - 20:bd:a9:f2:4e:0a:7d:50:ad:f5:05:0d:45:4f:46: - 71:fd:28:3e:53:fb:04:d8:2d:d7:65:1d:4a:1b:fa: - cf:3b:b0:31:9a:35:6e:c8:8b:06:d3:00:91:f2:94: - 08:65:4c:b1:34:06:00:7a:89:e2:f0:c7:03:59:cf: - d5:d6:e8:a7:32:b3:e6:98:40:86:c5:cd:27:12:8b: - cc:7b:ce:b7:11:3c:62:60:07:23:3e:2b:40:6e:94: - 80:09:6d:b6:b3:6f:77:6f:35:08:50:fb:02:87:c5: - 3e:89 - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Subject Key Identifier: - 5B:F8:4D:4F:B2:A5:86:D4:3A:D2:F1:63:9A:A0:BE:09:F6:57:B7:DE - X509v3 Key Usage: critical - Certificate Sign, CRL Sign - X509v3 Basic Constraints: critical - CA:TRUE - Signature Algorithm: sha1WithRSAEncryption - a0:a1:38:16:66:2e:a7:56:1f:21:9c:06:fa:1d:ed:b9:22:c5: - 38:26:d8:4e:4f:ec:a3:7f:79:de:46:21:a1:87:77:8f:07:08: - 9a:b2:a4:c5:af:0f:32:98:0b:7c:66:29:b6:9b:7d:25:52:49: - 43:ab:4c:2e:2b:6e:7a:70:af:16:0e:e3:02:6c:fb:42:e6:18: - 9d:45:d8:55:c8:e8:3b:dd:e7:e1:f4:2e:0b:1c:34:5c:6c:58: - 4a:fb:8c:88:50:5f:95:1c:bf:ed:ab:22:b5:65:b3:85:ba:9e: - 0f:b8:ad:e5:7a:1b:8a:50:3a:1d:bd:0d:bc:7b:54:50:0b:b9: - 42:af:55:a0:18:81:ad:65:99:ef:be:e4:9c:bf:c4:85:ab:41: - b2:54:6f:dc:25:cd:ed:78:e2:8e:0c:8d:09:49:dd:63:7b:5a: - 69:96:02:21:a8:bd:52:59:e9:7d:35:cb:c8:52:ca:7f:81:fe: - d9:6b:d3:f7:11:ed:25:df:f8:e7:f9:a4:fa:72:97:84:53:0d: - a5:d0:32:18:51:76:59:14:6c:0f:eb:ec:5f:80:8c:75:43:83: - c3:85:98:ff:4c:9e:2d:0d:e4:77:83:93:4e:b5:96:07:8b:28: - 13:9b:8c:19:8d:41:27:49:40:ee:de:e6:23:44:39:dc:a1:22: - d6:ba:03:f2 ------BEGIN CERTIFICATE----- -MIIDbTCCAlWgAwIBAgIBATANBgkqhkiG9w0BAQUFADBYMQswCQYDVQQGEwJKUDEr -MCkGA1UEChMiSmFwYW4gQ2VydGlmaWNhdGlvbiBTZXJ2aWNlcywgSW5jLjEcMBoG -A1UEAxMTU2VjdXJlU2lnbiBSb290Q0ExMTAeFw0wOTA0MDgwNDU2NDdaFw0yOTA0 -MDgwNDU2NDdaMFgxCzAJBgNVBAYTAkpQMSswKQYDVQQKEyJKYXBhbiBDZXJ0aWZp -Y2F0aW9uIFNlcnZpY2VzLCBJbmMuMRwwGgYDVQQDExNTZWN1cmVTaWduIFJvb3RD -QTExMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA/XeqpRyQBTvLTJsz -i1oURaTnkBbR31fSIRCkF/3frNYfp+TbfPfs37gD2pRY/V1yfIw/XwFndBWW4wI8 -h9uuywGOwvNmxoVF9ALGOrVisq/6nL+k5tSAMJjzDbaTj6nU2DbysPyKyiyhFTOV -MdrAG/LuYpmGYz+/3ZMqg6h2uRMft85OQoWPIucuGvKVCbIFtUROd6EgvanyTgp9 -UK31BQ1FT0Zx/Sg+U/sE2C3XZR1KG/rPO7AxmjVuyIsG0wCR8pQIZUyxNAYAeoni -8McDWc/V1uinMrPmmECGxc0nEovMe863ETxiYAcjPitAbpSACW22s293bzUIUPsC -h8U+iQIDAQABo0IwQDAdBgNVHQ4EFgQUW/hNT7KlhtQ60vFjmqC+CfZXt94wDgYD -VR0PAQH/BAQDAgEGMA8GA1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcNAQEFBQADggEB -AKChOBZmLqdWHyGcBvod7bkixTgm2E5P7KN/ed5GIaGHd48HCJqypMWvDzKYC3xm -KbabfSVSSUOrTC4rbnpwrxYO4wJs+0LmGJ1F2FXI6Dvd5+H0LgscNFxsWEr7jIhQ -X5Ucv+2rIrVls4W6ng+4reV6G4pQOh29Dbx7VFALuUKvVaAYga1lme++5Jy/xIWr -QbJUb9wlze144o4MjQlJ3WN7WmmWAiGovVJZ6X01y8hSyn+B/tlr0/cR7SXf+Of5 -pPpyl4RTDaXQMhhRdlkUbA/r7F+AjHVDg8OFmP9Mni0N5HeDk061lgeLKBObjBmN -QSdJQO7e5iNEOdyhIta6A/I= ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: - 0c:f0:8e:5c:08:16:a5:ad:42:7f:f0:eb:27:18:59:d0 - Signature Algorithm: sha1WithRSAEncryption - Issuer: C=US, O=SecureTrust Corporation, CN=SecureTrust CA - Validity - Not Before: Nov 7 19:31:18 2006 GMT - Not After : Dec 31 19:40:55 2029 GMT - Subject: C=US, O=SecureTrust Corporation, CN=SecureTrust CA - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (2048 bit) - Modulus: - 00:ab:a4:81:e5:95:cd:f5:f6:14:8e:c2:4f:ca:d4: - e2:78:95:58:9c:41:e1:0d:99:40:24:17:39:91:33: - 66:e9:be:e1:83:af:62:5c:89:d1:fc:24:5b:61:b3: - e0:11:11:41:1c:1d:6e:f0:b8:bb:f8:de:a7:81:ba: - a6:48:c6:9f:1d:bd:be:8e:a9:41:3e:b8:94:ed:29: - 1a:d4:8e:d2:03:1d:03:ef:6d:0d:67:1c:57:d7:06: - ad:ca:c8:f5:fe:0e:af:66:25:48:04:96:0b:5d:a3: - ba:16:c3:08:4f:d1:46:f8:14:5c:f2:c8:5e:01:99: - 6d:fd:88:cc:86:a8:c1:6f:31:42:6c:52:3e:68:cb: - f3:19:34:df:bb:87:18:56:80:26:c4:d0:dc:c0:6f: - df:de:a0:c2:91:16:a0:64:11:4b:44:bc:1e:f6:e7: - fa:63:de:66:ac:76:a4:71:a3:ec:36:94:68:7a:77: - a4:b1:e7:0e:2f:81:7a:e2:b5:72:86:ef:a2:6b:8b: - f0:0f:db:d3:59:3f:ba:72:bc:44:24:9c:e3:73:b3: - f7:af:57:2f:42:26:9d:a9:74:ba:00:52:f2:4b:cd: - 53:7c:47:0b:36:85:0e:66:a9:08:97:16:34:57:c1: - 66:f7:80:e3:ed:70:54:c7:93:e0:2e:28:15:59:87: - ba:bb - Exponent: 65537 (0x10001) - X509v3 extensions: - 1.3.6.1.4.1.311.20.2: - ...C.A - X509v3 Key Usage: - Digital Signature, Certificate Sign, CRL Sign - X509v3 Basic Constraints: critical - CA:TRUE - X509v3 Subject Key Identifier: - 42:32:B6:16:FA:04:FD:FE:5D:4B:7A:C3:FD:F7:4C:40:1D:5A:43:AF - X509v3 CRL Distribution Points: - - Full Name: - URI:http://crl.securetrust.com/STCA.crl - - 1.3.6.1.4.1.311.21.1: - ... - Signature Algorithm: sha1WithRSAEncryption - 30:ed:4f:4a:e1:58:3a:52:72:5b:b5:a6:a3:65:18:a6:bb:51: - 3b:77:e9:9d:ea:d3:9f:5c:e0:45:65:7b:0d:ca:5b:e2:70:50: - b2:94:05:14:ae:49:c7:8d:41:07:12:73:94:7e:0c:23:21:fd: - bc:10:7f:60:10:5a:72:f5:98:0e:ac:ec:b9:7f:dd:7a:6f:5d: - d3:1c:f4:ff:88:05:69:42:a9:05:71:c8:b7:ac:26:e8:2e:b4: - 8c:6a:ff:71:dc:b8:b1:df:99:bc:7c:21:54:2b:e4:58:a2:bb: - 57:29:ae:9e:a9:a3:19:26:0f:99:2e:08:b0:ef:fd:69:cf:99: - 1a:09:8d:e3:a7:9f:2b:c9:36:34:7b:24:b3:78:4c:95:17:a4: - 06:26:1e:b6:64:52:36:5f:60:67:d9:9c:c5:05:74:0b:e7:67: - 23:d2:08:fc:88:e9:ae:8b:7f:e1:30:f4:37:7e:fd:c6:32:da: - 2d:9e:44:30:30:6c:ee:07:de:d2:34:fc:d2:ff:40:f6:4b:f4: - 66:46:06:54:a6:f2:32:0a:63:26:30:6b:9b:d1:dc:8b:47:ba: - e1:b9:d5:62:d0:a2:a0:f4:67:05:78:29:63:1a:6f:04:d6:f8: - c6:4c:a3:9a:b1:37:b4:8d:e5:28:4b:1d:9e:2c:c2:b8:68:bc: - ed:02:ee:31 ------BEGIN CERTIFICATE----- -MIIDuDCCAqCgAwIBAgIQDPCOXAgWpa1Cf/DrJxhZ0DANBgkqhkiG9w0BAQUFADBI -MQswCQYDVQQGEwJVUzEgMB4GA1UEChMXU2VjdXJlVHJ1c3QgQ29ycG9yYXRpb24x -FzAVBgNVBAMTDlNlY3VyZVRydXN0IENBMB4XDTA2MTEwNzE5MzExOFoXDTI5MTIz -MTE5NDA1NVowSDELMAkGA1UEBhMCVVMxIDAeBgNVBAoTF1NlY3VyZVRydXN0IENv -cnBvcmF0aW9uMRcwFQYDVQQDEw5TZWN1cmVUcnVzdCBDQTCCASIwDQYJKoZIhvcN -AQEBBQADggEPADCCAQoCggEBAKukgeWVzfX2FI7CT8rU4niVWJxB4Q2ZQCQXOZEz -Zum+4YOvYlyJ0fwkW2Gz4BERQRwdbvC4u/jep4G6pkjGnx29vo6pQT64lO0pGtSO -0gMdA+9tDWccV9cGrcrI9f4Or2YlSASWC12juhbDCE/RRvgUXPLIXgGZbf2IzIao -wW8xQmxSPmjL8xk037uHGFaAJsTQ3MBv396gwpEWoGQRS0S8Hvbn+mPeZqx2pHGj -7DaUaHp3pLHnDi+BeuK1cobvomuL8A/b01k/unK8RCSc43Oz969XL0Imnal0ugBS -8kvNU3xHCzaFDmapCJcWNFfBZveA4+1wVMeT4C4oFVmHursCAwEAAaOBnTCBmjAT -BgkrBgEEAYI3FAIEBh4EAEMAQTALBgNVHQ8EBAMCAYYwDwYDVR0TAQH/BAUwAwEB -/zAdBgNVHQ4EFgQUQjK2FvoE/f5dS3rD/fdMQB1aQ68wNAYDVR0fBC0wKzApoCeg -JYYjaHR0cDovL2NybC5zZWN1cmV0cnVzdC5jb20vU1RDQS5jcmwwEAYJKwYBBAGC -NxUBBAMCAQAwDQYJKoZIhvcNAQEFBQADggEBADDtT0rhWDpSclu1pqNlGKa7UTt3 -6Z3q059c4EVlew3KW+JwULKUBRSuSceNQQcSc5R+DCMh/bwQf2AQWnL1mA6s7Ll/ -3XpvXdMc9P+IBWlCqQVxyLesJugutIxq/3HcuLHfmbx8IVQr5Fiiu1cprp6poxkm -D5kuCLDv/WnPmRoJjeOnnyvJNjR7JLN4TJUXpAYmHrZkUjZfYGfZnMUFdAvnZyPS -CPyI6a6Lf+Ew9Dd+/cYy2i2eRDAwbO4H3tI0/NL/QPZL9GZGBlSm8jIKYyYwa5vR -3ItHuuG51WLQoqD0ZwV4KWMabwTW+MZMo5qxN7SN5ShLHZ4swrhovO0C7jE= ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: - 07:56:22:a4:e8:d4:8a:89:4d:f4:13:c8:f0:f8:ea:a5 - Signature Algorithm: sha1WithRSAEncryption - Issuer: C=US, O=SecureTrust Corporation, CN=Secure Global CA - Validity - Not Before: Nov 7 19:42:28 2006 GMT - Not After : Dec 31 19:52:06 2029 GMT - Subject: C=US, O=SecureTrust Corporation, CN=Secure Global CA - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (2048 bit) - Modulus: - 00:af:35:2e:d8:ac:6c:55:69:06:71:e5:13:68:24: - b3:4f:d8:cc:21:47:f8:f1:60:38:89:89:03:e9:bd: - ea:5e:46:53:09:dc:5c:f5:5a:e8:f7:45:2a:02:eb: - 31:61:d7:29:33:4c:ce:c7:7c:0a:37:7e:0f:ba:32: - 98:e1:1d:97:af:8f:c7:dc:c9:38:96:f3:db:1a:fc: - 51:ed:68:c6:d0:6e:a4:7c:24:d1:ae:42:c8:96:50: - 63:2e:e0:fe:75:fe:98:a7:5f:49:2e:95:e3:39:33: - 64:8e:1e:a4:5f:90:d2:67:3c:b2:d9:fe:41:b9:55: - a7:09:8e:72:05:1e:8b:dd:44:85:82:42:d0:49:c0: - 1d:60:f0:d1:17:2c:95:eb:f6:a5:c1:92:a3:c5:c2: - a7:08:60:0d:60:04:10:96:79:9e:16:34:e6:a9:b6: - fa:25:45:39:c8:1e:65:f9:93:f5:aa:f1:52:dc:99: - 98:3d:a5:86:1a:0c:35:33:fa:4b:a5:04:06:15:1c: - 31:80:ef:aa:18:6b:c2:7b:d7:da:ce:f9:33:20:d5: - f5:bd:6a:33:2d:81:04:fb:b0:5c:d4:9c:a3:e2:5c: - 1d:e3:a9:42:75:5e:7b:d4:77:ef:39:54:ba:c9:0a: - 18:1b:12:99:49:2f:88:4b:fd:50:62:d1:73:e7:8f: - 7a:43 - Exponent: 65537 (0x10001) - X509v3 extensions: - 1.3.6.1.4.1.311.20.2: - ...C.A - X509v3 Key Usage: - Digital Signature, Certificate Sign, CRL Sign - X509v3 Basic Constraints: critical - CA:TRUE - X509v3 Subject Key Identifier: - AF:44:04:C2:41:7E:48:83:DB:4E:39:02:EC:EC:84:7A:E6:CE:C9:A4 - X509v3 CRL Distribution Points: - - Full Name: - URI:http://crl.securetrust.com/SGCA.crl - - 1.3.6.1.4.1.311.21.1: - ... - Signature Algorithm: sha1WithRSAEncryption - 63:1a:08:40:7d:a4:5e:53:0d:77:d8:7a:ae:1f:0d:0b:51:16: - 03:ef:18:7c:c8:e3:af:6a:58:93:14:60:91:b2:84:dc:88:4e: - be:39:8a:3a:f3:e6:82:89:5d:01:37:b3:ab:24:a4:15:0e:92: - 35:5a:4a:44:5e:4e:57:fa:75:ce:1f:48:ce:66:f4:3c:40:26: - 92:98:6c:1b:ee:24:46:0c:17:b3:52:a5:db:a5:91:91:cf:37: - d3:6f:e7:27:08:3a:4e:19:1f:3a:a7:58:5c:17:cf:79:3f:8b: - e4:a7:d3:26:23:9d:26:0f:58:69:fc:47:7e:b2:d0:8d:8b:93: - bf:29:4f:43:69:74:76:67:4b:cf:07:8c:e6:02:f7:b5:e1:b4: - 43:b5:4b:2d:14:9f:f9:dc:26:0d:bf:a6:47:74:06:d8:88:d1: - 3a:29:30:84:ce:d2:39:80:62:1b:a8:c7:57:49:bc:6a:55:51: - 67:15:4a:be:35:07:e4:d5:75:98:37:79:30:14:db:29:9d:6c: - c5:69:cc:47:55:a2:30:f7:cc:5c:7f:c2:c3:98:1c:6b:4e:16: - 80:eb:7a:78:65:45:a2:00:1a:af:0c:0d:55:64:34:48:b8:92: - b9:f1:b4:50:29:f2:4f:23:1f:da:6c:ac:1f:44:e1:dd:23:78: - 51:5b:c7:16 ------BEGIN CERTIFICATE----- -MIIDvDCCAqSgAwIBAgIQB1YipOjUiolN9BPI8PjqpTANBgkqhkiG9w0BAQUFADBK -MQswCQYDVQQGEwJVUzEgMB4GA1UEChMXU2VjdXJlVHJ1c3QgQ29ycG9yYXRpb24x -GTAXBgNVBAMTEFNlY3VyZSBHbG9iYWwgQ0EwHhcNMDYxMTA3MTk0MjI4WhcNMjkx -MjMxMTk1MjA2WjBKMQswCQYDVQQGEwJVUzEgMB4GA1UEChMXU2VjdXJlVHJ1c3Qg -Q29ycG9yYXRpb24xGTAXBgNVBAMTEFNlY3VyZSBHbG9iYWwgQ0EwggEiMA0GCSqG -SIb3DQEBAQUAA4IBDwAwggEKAoIBAQCvNS7YrGxVaQZx5RNoJLNP2MwhR/jxYDiJ -iQPpvepeRlMJ3Fz1Wuj3RSoC6zFh1ykzTM7HfAo3fg+6MpjhHZevj8fcyTiW89sa -/FHtaMbQbqR8JNGuQsiWUGMu4P51/pinX0kuleM5M2SOHqRfkNJnPLLZ/kG5VacJ -jnIFHovdRIWCQtBJwB1g8NEXLJXr9qXBkqPFwqcIYA1gBBCWeZ4WNOaptvolRTnI -HmX5k/Wq8VLcmZg9pYYaDDUz+kulBAYVHDGA76oYa8J719rO+TMg1fW9ajMtgQT7 -sFzUnKPiXB3jqUJ1XnvUd+85VLrJChgbEplJL4hL/VBi0XPnj3pDAgMBAAGjgZ0w -gZowEwYJKwYBBAGCNxQCBAYeBABDAEEwCwYDVR0PBAQDAgGGMA8GA1UdEwEB/wQF -MAMBAf8wHQYDVR0OBBYEFK9EBMJBfkiD2045AuzshHrmzsmkMDQGA1UdHwQtMCsw -KaAnoCWGI2h0dHA6Ly9jcmwuc2VjdXJldHJ1c3QuY29tL1NHQ0EuY3JsMBAGCSsG -AQQBgjcVAQQDAgEAMA0GCSqGSIb3DQEBBQUAA4IBAQBjGghAfaReUw132HquHw0L -URYD7xh8yOOvaliTFGCRsoTciE6+OYo68+aCiV0BN7OrJKQVDpI1WkpEXk5X+nXO -H0jOZvQ8QCaSmGwb7iRGDBezUqXbpZGRzzfTb+cnCDpOGR86p1hcF895P4vkp9Mm -I50mD1hp/Ed+stCNi5O/KU9DaXR2Z0vPB4zmAve14bRDtUstFJ/53CYNv6ZHdAbY -iNE6KTCEztI5gGIbqMdXSbxqVVFnFUq+NQfk1XWYN3kwFNspnWzFacxHVaIw98xc -f8LDmBxrThaA63p4ZUWiABqvDA1VZDRIuJK58bRQKfJPIx/abKwfROHdI3hRW8cW ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: 0 (0x0) - Signature Algorithm: sha1WithRSAEncryption - Issuer: C=JP, O=SECOM Trust Systems CO.,LTD., OU=Security Communication EV RootCA1 - Validity - Not Before: Jun 6 02:12:32 2007 GMT - Not After : Jun 6 02:12:32 2037 GMT - Subject: C=JP, O=SECOM Trust Systems CO.,LTD., OU=Security Communication EV RootCA1 - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (2048 bit) - Modulus: - 00:bc:7f:ec:57:9b:24:e0:fe:9c:ba:42:79:a9:88: - 8a:fa:80:e0:f5:07:29:43:ea:8e:0a:34:36:8d:1c: - fa:a7:b5:39:78:ff:97:75:f7:2f:e4:aa:6b:04:84: - 44:ca:a6:e2:68:8e:fd:55:50:62:0f:a4:71:0e:ce: - 07:38:2d:42:85:50:ad:3c:96:6f:8b:d5:a2:0e:cf: - de:49:89:3d:d6:64:2e:38:e5:1e:6c:b5:57:8a:9e: - ef:48:0e:cd:7a:69:16:87:44:b5:90:e4:06:9d:ae: - a1:04:97:58:79:ef:20:4a:82:6b:8c:22:bf:ec:1f: - 0f:e9:84:71:ed:f1:0e:e4:b8:18:13:cc:56:36:5d: - d1:9a:1e:51:6b:39:6e:60:76:88:34:0b:f3:b3:d1: - b0:9d:ca:61:e2:64:1d:c1:46:07:b8:63:dd:1e:33: - 65:b3:8e:09:55:52:3d:b5:bd:ff:07:eb:ad:61:55: - 18:2c:a9:69:98:4a:aa:40:c5:33:14:65:74:00:f9: - 91:de:af:03:48:c5:40:54:dc:0f:84:90:68:20:c5: - 92:96:dc:2e:e5:02:45:aa:c0:5f:54:f8:6d:ea:49: - cf:5d:6c:4b:af:ef:9a:c2:56:5c:c6:35:56:42:6a: - 30:5f:c2:ab:f6:e2:3d:3f:b3:c9:11:8f:31:4c:d7: - 9f:49 - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Subject Key Identifier: - 35:4A:F5:4D:AF:3F:D7:82:38:AC:AB:71:65:17:75:8C:9D:55:93:E6 - X509v3 Key Usage: critical - Certificate Sign, CRL Sign - X509v3 Basic Constraints: critical - CA:TRUE - Signature Algorithm: sha1WithRSAEncryption - a8:87:e9:ec:f8:40:67:5d:c3:c1:66:c7:40:4b:97:fc:87:13: - 90:5a:c4:ef:a0:ca:5f:8b:b7:a7:b7:f1:d6:b5:64:b7:8a:b3: - b8:1b:cc:da:fb:ac:66:88:41:ce:e8:fc:e4:db:1e:88:a6:ed: - 27:50:1b:02:30:24:46:79:fe:04:87:70:97:40:73:d1:c0:c1: - 57:19:9a:69:a5:27:99:ab:9d:62:84:f6:51:c1:2c:c9:23:15: - d8:28:b7:ab:25:13:b5:46:e1:86:02:ff:26:8c:c4:88:92:1d: - 56:fe:19:67:f2:55:e4:80:a3:6b:9c:ab:77:e1:51:71:0d:20: - db:10:9a:db:bd:76:79:07:77:99:28:ad:9a:5e:da:b1:4f:44: - 2c:35:8e:a5:96:c7:fd:83:f0:58:c6:79:d6:98:7c:a8:8d:fe: - 86:3e:07:16:92:e1:7b:e7:1d:ec:33:76:7e:42:2e:4a:85:f9: - 91:89:68:84:03:81:a5:9b:9a:be:e3:37:c5:54:ab:56:3b:18: - 2d:41:a4:0c:f8:42:db:99:a0:e0:72:6f:bb:5d:e1:16:4f:53: - 0a:64:f9:4e:f4:bf:4e:54:bd:78:6c:88:ea:bf:9c:13:24:c2: - 70:69:a2:7f:0f:c8:3c:ad:08:c9:b0:98:40:a3:2a:e7:88:83: - ed:77:8f:74 ------BEGIN CERTIFICATE----- -MIIDfTCCAmWgAwIBAgIBADANBgkqhkiG9w0BAQUFADBgMQswCQYDVQQGEwJKUDEl -MCMGA1UEChMcU0VDT00gVHJ1c3QgU3lzdGVtcyBDTy4sTFRELjEqMCgGA1UECxMh -U2VjdXJpdHkgQ29tbXVuaWNhdGlvbiBFViBSb290Q0ExMB4XDTA3MDYwNjAyMTIz -MloXDTM3MDYwNjAyMTIzMlowYDELMAkGA1UEBhMCSlAxJTAjBgNVBAoTHFNFQ09N -IFRydXN0IFN5c3RlbXMgQ08uLExURC4xKjAoBgNVBAsTIVNlY3VyaXR5IENvbW11 -bmljYXRpb24gRVYgUm9vdENBMTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC -ggEBALx/7FebJOD+nLpCeamIivqA4PUHKUPqjgo0No0c+qe1OXj/l3X3L+SqawSE -RMqm4miO/VVQYg+kcQ7OBzgtQoVQrTyWb4vVog7P3kmJPdZkLjjlHmy1V4qe70gO -zXppFodEtZDkBp2uoQSXWHnvIEqCa4wiv+wfD+mEce3xDuS4GBPMVjZd0ZoeUWs5 -bmB2iDQL87PRsJ3KYeJkHcFGB7hj3R4zZbOOCVVSPbW9/wfrrWFVGCypaZhKqkDF -MxRldAD5kd6vA0jFQFTcD4SQaCDFkpbcLuUCRarAX1T4bepJz11sS6/vmsJWXMY1 -VkJqMF/Cq/biPT+zyRGPMUzXn0kCAwEAAaNCMEAwHQYDVR0OBBYEFDVK9U2vP9eC -OKyrcWUXdYydVZPmMA4GA1UdDwEB/wQEAwIBBjAPBgNVHRMBAf8EBTADAQH/MA0G -CSqGSIb3DQEBBQUAA4IBAQCoh+ns+EBnXcPBZsdAS5f8hxOQWsTvoMpfi7ent/HW -tWS3irO4G8za+6xmiEHO6Pzk2x6Ipu0nUBsCMCRGef4Eh3CXQHPRwMFXGZpppSeZ -q51ihPZRwSzJIxXYKLerJRO1RuGGAv8mjMSIkh1W/hln8lXkgKNrnKt34VFxDSDb -EJrbvXZ5B3eZKK2aXtqxT0QsNY6llsf9g/BYxnnWmHyojf6GPgcWkuF75x3sM3Z+ -Qi5KhfmRiWiEA4Glm5q+4zfFVKtWOxgtQaQM+ELbmaDgcm+7XeEWT1MKZPlO9L9O -VL14bIjqv5wTJMJwaaJ/D8g8rQjJsJhAoyrniIPtd490 ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: 0 (0x0) - Signature Algorithm: sha256WithRSAEncryption - Issuer: C=JP, O=SECOM Trust Systems CO.,LTD., OU=Security Communication RootCA2 - Validity - Not Before: May 29 05:00:39 2009 GMT - Not After : May 29 05:00:39 2029 GMT - Subject: C=JP, O=SECOM Trust Systems CO.,LTD., OU=Security Communication RootCA2 - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (2048 bit) - Modulus: - 00:d0:15:39:52:b1:52:b3:ba:c5:59:82:c4:5d:52: - ae:3a:43:65:80:4b:c7:f2:96:bc:db:36:97:d6:a6: - 64:8c:a8:5e:f0:e3:0a:1c:f7:df:97:3d:4b:ae:f6: - 5d:ec:21:b5:41:ab:cd:b9:7e:76:9f:be:f9:3e:36: - 34:a0:3b:c1:f6:31:11:45:74:93:3d:57:80:c5:f9: - 89:99:ca:e5:ab:6a:d4:b5:da:41:90:10:c1:d6:d6: - 42:89:c2:bf:f4:38:12:95:4c:54:05:f7:36:e4:45: - 83:7b:14:65:d6:dc:0c:4d:d1:de:7e:0c:ab:3b:c4: - 15:be:3a:56:a6:5a:6f:76:69:52:a9:7a:b9:c8:eb: - 6a:9a:5d:52:d0:2d:0a:6b:35:16:09:10:84:d0:6a: - ca:3a:06:00:37:47:e4:7e:57:4f:3f:8b:eb:67:b8: - 88:aa:c5:be:53:55:b2:91:c4:7d:b9:b0:85:19:06: - 78:2e:db:61:1a:fa:85:f5:4a:91:a1:e7:16:d5:8e: - a2:39:df:94:b8:70:1f:28:3f:8b:fc:40:5e:63:83: - 3c:83:2a:1a:99:6b:cf:de:59:6a:3b:fc:6f:16:d7: - 1f:fd:4a:10:eb:4e:82:16:3a:ac:27:0c:53:f1:ad: - d5:24:b0:6b:03:50:c1:2d:3c:16:dd:44:34:27:1a: - 75:fb - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Subject Key Identifier: - 0A:85:A9:77:65:05:98:7C:40:81:F8:0F:97:2C:38:F1:0A:EC:3C:CF - X509v3 Key Usage: critical - Certificate Sign, CRL Sign - X509v3 Basic Constraints: critical - CA:TRUE - Signature Algorithm: sha256WithRSAEncryption - 4c:3a:a3:44:ac:b9:45:b1:c7:93:7e:c8:0b:0a:42:df:64:ea: - 1c:ee:59:6c:08:ba:89:5f:6a:ca:4a:95:9e:7a:8f:07:c5:da: - 45:72:82:71:0e:3a:d2:cc:6f:a7:b4:a1:23:bb:f6:24:9f:cb: - 17:fe:8c:a6:ce:c2:d2:db:cc:8d:fc:71:fc:03:29:c1:6c:5d: - 33:5f:64:b6:65:3b:89:6f:18:76:78:f5:dc:a2:48:1f:19:3f: - 8e:93:eb:f1:fa:17:ee:cd:4e:e3:04:12:55:d6:e5:e4:dd:fb: - 3e:05:7c:e2:1d:5e:c6:a7:bc:97:4f:68:3a:f5:e9:2e:0a:43: - b6:af:57:5c:62:68:7c:b7:fd:a3:8a:84:a0:ac:62:be:2b:09: - 87:34:f0:6a:01:bb:9b:29:56:3c:fe:00:37:cf:23:6c:f1:4e: - aa:b6:74:46:12:6c:91:ee:34:d5:ec:9a:91:e7:44:be:90:31: - 72:d5:49:02:f6:02:e5:f4:1f:eb:7c:d9:96:55:a9:ff:ec:8a: - f9:99:47:ff:35:5a:02:aa:04:cb:8a:5b:87:71:29:91:bd:a4: - b4:7a:0d:bd:9a:f5:57:23:00:07:21:17:3f:4a:39:d1:05:49: - 0b:a7:b6:37:81:a5:5d:8c:aa:33:5e:81:28:7c:a7:7d:27:eb: - 00:ae:8d:37 ------BEGIN CERTIFICATE----- -MIIDdzCCAl+gAwIBAgIBADANBgkqhkiG9w0BAQsFADBdMQswCQYDVQQGEwJKUDEl -MCMGA1UEChMcU0VDT00gVHJ1c3QgU3lzdGVtcyBDTy4sTFRELjEnMCUGA1UECxMe -U2VjdXJpdHkgQ29tbXVuaWNhdGlvbiBSb290Q0EyMB4XDTA5MDUyOTA1MDAzOVoX -DTI5MDUyOTA1MDAzOVowXTELMAkGA1UEBhMCSlAxJTAjBgNVBAoTHFNFQ09NIFRy -dXN0IFN5c3RlbXMgQ08uLExURC4xJzAlBgNVBAsTHlNlY3VyaXR5IENvbW11bmlj -YXRpb24gUm9vdENBMjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBANAV -OVKxUrO6xVmCxF1SrjpDZYBLx/KWvNs2l9amZIyoXvDjChz335c9S672XewhtUGr -zbl+dp+++T42NKA7wfYxEUV0kz1XgMX5iZnK5atq1LXaQZAQwdbWQonCv/Q4EpVM -VAX3NuRFg3sUZdbcDE3R3n4MqzvEFb46VqZab3ZpUql6ucjrappdUtAtCms1FgkQ -hNBqyjoGADdH5H5XTz+L62e4iKrFvlNVspHEfbmwhRkGeC7bYRr6hfVKkaHnFtWO -ojnflLhwHyg/i/xAXmODPIMqGplrz95Zajv8bxbXH/1KEOtOghY6rCcMU/Gt1SSw -awNQwS08Ft1ENCcadfsCAwEAAaNCMEAwHQYDVR0OBBYEFAqFqXdlBZh8QIH4D5cs -OPEK7DzPMA4GA1UdDwEB/wQEAwIBBjAPBgNVHRMBAf8EBTADAQH/MA0GCSqGSIb3 -DQEBCwUAA4IBAQBMOqNErLlFsceTfsgLCkLfZOoc7llsCLqJX2rKSpWeeo8HxdpF -coJxDjrSzG+ntKEju/Ykn8sX/oymzsLS28yN/HH8AynBbF0zX2S2ZTuJbxh2ePXc -okgfGT+Ok+vx+hfuzU7jBBJV1uXk3fs+BXziHV7Gp7yXT2g69ekuCkO2r1dcYmh8 -t/2jioSgrGK+KwmHNPBqAbubKVY8/gA3zyNs8U6qtnRGEmyR7jTV7JqR50S+kDFy -1UkC9gLl9B/rfNmWVan/7Ir5mUf/NVoCqgTLiluHcSmRvaS0eg29mvVXIwAHIRc/ -SjnRBUkLp7Y3gaVdjKozXoEofKd9J+sAro03 ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: 0 (0x0) - Signature Algorithm: sha1WithRSAEncryption - Issuer: C=JP, O=SECOM Trust.net, OU=Security Communication RootCA1 - Validity - Not Before: Sep 30 04:20:49 2003 GMT - Not After : Sep 30 04:20:49 2023 GMT - Subject: C=JP, O=SECOM Trust.net, OU=Security Communication RootCA1 - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (2048 bit) - Modulus: - 00:b3:b3:fe:7f:d3:6d:b1:ef:16:7c:57:a5:0c:6d: - 76:8a:2f:4b:bf:64:fb:4c:ee:8a:f0:f3:29:7c:f5: - ff:ee:2a:e0:e9:e9:ba:5b:64:22:9a:9a:6f:2c:3a: - 26:69:51:05:99:26:dc:d5:1c:6a:71:c6:9a:7d:1e: - 9d:dd:7c:6c:c6:8c:67:67:4a:3e:f8:71:b0:19:27: - a9:09:0c:a6:95:bf:4b:8c:0c:fa:55:98:3b:d8:e8: - 22:a1:4b:71:38:79:ac:97:92:69:b3:89:7e:ea:21: - 68:06:98:14:96:87:d2:61:36:bc:6d:27:56:9e:57: - ee:c0:c0:56:fd:32:cf:a4:d9:8e:c2:23:d7:8d:a8: - f3:d8:25:ac:97:e4:70:38:f4:b6:3a:b4:9d:3b:97: - 26:43:a3:a1:bc:49:59:72:4c:23:30:87:01:58:f6: - 4e:be:1c:68:56:66:af:cd:41:5d:c8:b3:4d:2a:55: - 46:ab:1f:da:1e:e2:40:3d:db:cd:7d:b9:92:80:9c: - 37:dd:0c:96:64:9d:dc:22:f7:64:8b:df:61:de:15: - 94:52:15:a0:7d:52:c9:4b:a8:21:c9:c6:b1:ed:cb: - c3:95:60:d1:0f:f0:ab:70:f8:df:cb:4d:7e:ec:d6: - fa:ab:d9:bd:7f:54:f2:a5:e9:79:fa:d9:d6:76:24: - 28:73 - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Subject Key Identifier: - A0:73:49:99:68:DC:85:5B:65:E3:9B:28:2F:57:9F:BD:33:BC:07:48 - X509v3 Key Usage: - Certificate Sign, CRL Sign - X509v3 Basic Constraints: critical - CA:TRUE - Signature Algorithm: sha1WithRSAEncryption - 68:40:a9:a8:bb:e4:4f:5d:79:b3:05:b5:17:b3:60:13:eb:c6: - 92:5d:e0:d1:d3:6a:fe:fb:be:9b:6d:bf:c7:05:6d:59:20:c4: - 1c:f0:b7:da:84:58:02:63:fa:48:16:ef:4f:a5:0b:f7:4a:98: - f2:3f:9e:1b:ad:47:6b:63:ce:08:47:eb:52:3f:78:9c:af:4d: - ae:f8:d5:4f:cf:9a:98:2a:10:41:39:52:c4:dd:d9:9b:0e:ef: - 93:01:ae:b2:2e:ca:68:42:24:42:6c:b0:b3:3a:3e:cd:e9:da: - 48:c4:15:cb:e9:f9:07:0f:92:50:49:8a:dd:31:97:5f:c9:e9: - 37:aa:3b:59:65:97:94:32:c9:b3:9f:3e:3a:62:58:c5:49:ad: - 62:0e:71:a5:32:aa:2f:c6:89:76:43:40:13:13:67:3d:a2:54: - 25:10:cb:f1:3a:f2:d9:fa:db:49:56:bb:a6:fe:a7:41:35:c3: - e0:88:61:c9:88:c7:df:36:10:22:98:59:ea:b0:4a:fb:56:16: - 73:6e:ac:4d:f7:22:a1:4f:ad:1d:7a:2d:45:27:e5:30:c1:5e: - f2:da:13:cb:25:42:51:95:47:03:8c:6c:21:cc:74:42:ed:53: - ff:33:8b:8f:0f:57:01:16:2f:cf:a6:ee:c9:70:22:14:bd:fd: - be:6c:0b:03 ------BEGIN CERTIFICATE----- -MIIDWjCCAkKgAwIBAgIBADANBgkqhkiG9w0BAQUFADBQMQswCQYDVQQGEwJKUDEY -MBYGA1UEChMPU0VDT00gVHJ1c3QubmV0MScwJQYDVQQLEx5TZWN1cml0eSBDb21t -dW5pY2F0aW9uIFJvb3RDQTEwHhcNMDMwOTMwMDQyMDQ5WhcNMjMwOTMwMDQyMDQ5 -WjBQMQswCQYDVQQGEwJKUDEYMBYGA1UEChMPU0VDT00gVHJ1c3QubmV0MScwJQYD -VQQLEx5TZWN1cml0eSBDb21tdW5pY2F0aW9uIFJvb3RDQTEwggEiMA0GCSqGSIb3 -DQEBAQUAA4IBDwAwggEKAoIBAQCzs/5/022x7xZ8V6UMbXaKL0u/ZPtM7orw8yl8 -9f/uKuDp6bpbZCKamm8sOiZpUQWZJtzVHGpxxpp9Hp3dfGzGjGdnSj74cbAZJ6kJ -DKaVv0uMDPpVmDvY6CKhS3E4eayXkmmziX7qIWgGmBSWh9JhNrxtJ1aeV+7AwFb9 -Ms+k2Y7CI9eNqPPYJayX5HA49LY6tJ07lyZDo6G8SVlyTCMwhwFY9k6+HGhWZq/N -QV3Is00qVUarH9oe4kA92819uZKAnDfdDJZkndwi92SL32HeFZRSFaB9UslLqCHJ -xrHty8OVYNEP8Ktw+N/LTX7s1vqr2b1/VPKl6Xn62dZ2JChzAgMBAAGjPzA9MB0G -A1UdDgQWBBSgc0mZaNyFW2XjmygvV5+9M7wHSDALBgNVHQ8EBAMCAQYwDwYDVR0T -AQH/BAUwAwEB/zANBgkqhkiG9w0BAQUFAAOCAQEAaECpqLvkT115swW1F7NgE+vG -kl3g0dNq/vu+m22/xwVtWSDEHPC32oRYAmP6SBbvT6UL90qY8j+eG61Ha2POCEfr -Uj94nK9NrvjVT8+amCoQQTlSxN3Zmw7vkwGusi7KaEIkQmywszo+zenaSMQVy+n5 -Bw+SUEmK3TGXX8npN6o7WWWXlDLJs58+OmJYxUmtYg5xpTKqL8aJdkNAExNnPaJU -JRDL8Try2frbSVa7pv6nQTXD4IhhyYjH3zYQIphZ6rBK+1YWc26sTfcioU+tHXot -RSflMMFe8toTyyVCUZVHA4xsIcx0Qu1T/zOLjw9XARYvz6buyXAiFL39vmwLAw== ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: 29 (0x1d) - Signature Algorithm: sha1WithRSAEncryption - Issuer: C=FI, O=Sonera, CN=Sonera Class2 CA - Validity - Not Before: Apr 6 07:29:40 2001 GMT - Not After : Apr 6 07:29:40 2021 GMT - Subject: C=FI, O=Sonera, CN=Sonera Class2 CA - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (2048 bit) - Modulus: - 00:90:17:4a:35:9d:ca:f0:0d:96:c7:44:fa:16:37: - fc:48:bd:bd:7f:80:2d:35:3b:e1:6f:a8:67:a9:bf: - 03:1c:4d:8c:6f:32:47:d5:41:68:a4:13:04:c1:35: - 0c:9a:84:43:fc:5c:1d:ff:89:b3:e8:17:18:cd:91: - 5f:fb:89:e3:ea:bf:4e:5d:7c:1b:26:d3:75:79:ed: - e6:84:e3:57:e5:ad:29:c4:f4:3a:28:e7:a5:7b:84: - 36:69:b3:fd:5e:76:bd:a3:2d:99:d3:90:4e:23:28: - 7d:18:63:f1:54:3b:26:9d:76:5b:97:42:b2:ff:ae: - f0:4e:ec:dd:39:95:4e:83:06:7f:e7:49:40:c8:c5: - 01:b2:54:5a:66:1d:3d:fc:f9:e9:3c:0a:9e:81:b8: - 70:f0:01:8b:e4:23:54:7c:c8:ae:f8:90:1e:00:96: - 72:d4:54:cf:61:23:bc:ea:fb:9d:02:95:d1:b6:b9: - 71:3a:69:08:3f:0f:b4:e1:42:c7:88:f5:3f:98:a8: - a7:ba:1c:e0:71:71:ef:58:57:81:50:7a:5c:6b:74: - 46:0e:83:03:98:c3:8e:a8:6e:f2:76:32:6e:27:83: - c2:73:f3:dc:18:e8:b4:93:ea:75:44:6b:04:60:20: - 71:57:87:9d:f3:be:a0:90:23:3d:8a:24:e1:da:21: - db:c3 - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Basic Constraints: critical - CA:TRUE - X509v3 Subject Key Identifier: - 4A:A0:AA:58:84:D3:5E:3C - X509v3 Key Usage: - Certificate Sign, CRL Sign - Signature Algorithm: sha1WithRSAEncryption - 5a:ce:87:f9:16:72:15:57:4b:1d:d9:9b:e7:a2:26:30:ec:93: - 67:df:d6:2d:d2:34:af:f7:38:a5:ce:ab:16:b9:ab:2f:7c:35: - cb:ac:d0:0f:b4:4c:2b:fc:80:ef:6b:8c:91:5f:36:76:f7:db: - b3:1b:19:ea:f4:b2:11:fd:61:71:44:bf:28:b3:3a:1d:bf:b3: - 43:e8:9f:bf:dc:31:08:71:b0:9d:8d:d6:34:47:32:90:c6:65: - 24:f7:a0:4a:7c:04:73:8f:39:6f:17:8c:72:b5:bd:4b:c8:7a: - f8:7b:83:c3:28:4e:9c:09:ea:67:3f:b2:67:04:1b:c3:14:da: - f8:e7:49:24:91:d0:1d:6a:fa:61:39:ef:6b:e7:21:75:06:07: - d8:12:b4:21:20:70:42:71:81:da:3c:9a:36:be:a6:5b:0d:6a: - 6c:9a:1f:91:7b:f9:f9:ef:42:ba:4e:4e:9e:cc:0c:8d:94:dc: - d9:45:9c:5e:ec:42:50:63:ae:f4:5d:c4:b1:12:dc:ca:3b:a8: - 2e:9d:14:5a:05:75:b7:ec:d7:63:e2:ba:35:b6:04:08:91:e8: - da:9d:9c:f6:66:b5:18:ac:0a:a6:54:26:34:33:d2:1b:c1:d4: - 7f:1a:3a:8e:0b:aa:32:6e:db:fc:4f:25:9f:d9:32:c7:96:5a: - 70:ac:df:4c ------BEGIN CERTIFICATE----- -MIIDIDCCAgigAwIBAgIBHTANBgkqhkiG9w0BAQUFADA5MQswCQYDVQQGEwJGSTEP -MA0GA1UEChMGU29uZXJhMRkwFwYDVQQDExBTb25lcmEgQ2xhc3MyIENBMB4XDTAx -MDQwNjA3Mjk0MFoXDTIxMDQwNjA3Mjk0MFowOTELMAkGA1UEBhMCRkkxDzANBgNV -BAoTBlNvbmVyYTEZMBcGA1UEAxMQU29uZXJhIENsYXNzMiBDQTCCASIwDQYJKoZI -hvcNAQEBBQADggEPADCCAQoCggEBAJAXSjWdyvANlsdE+hY3/Ei9vX+ALTU74W+o -Z6m/AxxNjG8yR9VBaKQTBME1DJqEQ/xcHf+Js+gXGM2RX/uJ4+q/Tl18GybTdXnt -5oTjV+WtKcT0OijnpXuENmmz/V52vaMtmdOQTiMofRhj8VQ7Jp12W5dCsv+u8E7s -3TmVToMGf+dJQMjFAbJUWmYdPfz56TwKnoG4cPABi+QjVHzIrviQHgCWctRUz2Ej -vOr7nQKV0ba5cTppCD8PtOFCx4j1P5iop7oc4HFx71hXgVB6XGt0Rg6DA5jDjqhu -8nYybieDwnPz3BjotJPqdURrBGAgcVeHnfO+oJAjPYok4doh28MCAwEAAaMzMDEw -DwYDVR0TAQH/BAUwAwEB/zARBgNVHQ4ECgQISqCqWITTXjwwCwYDVR0PBAQDAgEG -MA0GCSqGSIb3DQEBBQUAA4IBAQBazof5FnIVV0sd2ZvnoiYw7JNn39Yt0jSv9zil -zqsWuasvfDXLrNAPtEwr/IDva4yRXzZ299uzGxnq9LIR/WFxRL8oszodv7ND6J+/ -3DEIcbCdjdY0RzKQxmUk96BKfARzjzlvF4xytb1LyHr4e4PDKE6cCepnP7JnBBvD -FNr450kkkdAdavphOe9r5yF1BgfYErQhIHBCcYHaPJo2vqZbDWpsmh+Re/n570K6 -Tk6ezAyNlNzZRZxe7EJQY670XcSxEtzKO6gunRRaBXW37Ndj4ro1tgQIkejanZz2 -ZrUYrAqmVCY0M9IbwdR/GjqOC6oybtv8TyWf2TLHllpwrN9M ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: 10000013 (0x98968d) - Signature Algorithm: sha256WithRSAEncryption - Issuer: C=NL, O=Staat der Nederlanden, CN=Staat der Nederlanden EV Root CA - Validity - Not Before: Dec 8 11:19:29 2010 GMT - Not After : Dec 8 11:10:28 2022 GMT - Subject: C=NL, O=Staat der Nederlanden, CN=Staat der Nederlanden EV Root CA - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (4096 bit) - Modulus: - 00:e3:c7:7e:89:f9:24:4b:3a:d2:33:83:35:2c:69: - ec:dc:09:a4:e3:51:a8:25:2b:79:b8:08:3d:e0:91: - ba:84:85:c6:85:a4:ca:e6:c9:2e:53:a4:c9:24:1e: - fd:55:66:71:5d:2c:c5:60:68:04:b7:d9:c2:52:26: - 38:88:a4:d6:3b:40:a6:c2:cd:3f:cd:98:93:b3:54: - 14:58:96:55:d5:50:fe:86:ad:a4:63:7f:5c:87:f6: - 8e:e6:27:92:67:17:92:02:03:2c:dc:d6:66:74:ed: - dd:67:ff:c1:61:8d:63:4f:0f:9b:6d:17:30:26:ef: - ab:d2:1f:10:a0:f9:c5:7f:16:69:81:03:47:ed:1e: - 68:8d:72:a1:4d:b2:26:c6:ba:6c:5f:6d:d6:af:d1: - b1:13:8e:a9:ad:f3:5e:69:75:26:18:3e:41:2b:21: - 7f:ee:8b:5d:07:06:9d:43:c4:29:0a:2b:fc:2a:3e: - 86:cb:3c:83:3a:f9:c9:0d:da:c5:99:e2:bc:78:41: - 33:76:e1:bf:2f:5d:e5:a4:98:50:0c:15:dd:e0:fa: - 9c:7f:38:68:d0:b2:a6:7a:a7:d1:31:bd:7e:8a:58: - 27:43:b3:ba:33:91:d3:a7:98:15:5c:9a:e6:d3:0f: - 75:d9:fc:41:98:97:3e:aa:25:db:8f:92:2e:b0:7b: - 0c:5f:f1:63:a9:37:f9:9b:75:69:4c:28:26:25:da: - d5:f2:12:70:45:55:e3:df:73:5e:37:f5:21:6c:90: - 8e:35:5a:c9:d3:23:eb:d3:c0:be:78:ac:42:28:58: - 66:a5:46:6d:70:02:d7:10:f9:4b:54:fc:5d:86:4a: - 87:cf:7f:ca:45:ac:11:5a:b5:20:51:8d:2f:88:47: - 97:39:c0:cf:ba:c0:42:01:40:99:48:21:0b:6b:a7: - d2:fd:96:d5:d1:be:46:9d:49:e0:0b:a6:a0:22:4e: - 38:d0:c1:3c:30:bc:70:8f:2c:75:cc:d0:c5:8c:51: - 3b:3d:94:08:64:26:61:7d:b9:c3:65:8f:14:9c:21: - d0:aa:fd:17:72:03:8f:bd:9b:8c:e6:5e:53:9e:b9: - 9d:ef:82:bb:e1:bc:e2:72:41:5b:21:94:d3:45:37: - 94:d1:df:09:39:5d:e7:23:aa:9a:1d:ca:6d:a8:0a: - 86:85:8a:82:be:42:07:d6:f2:38:82:73:da:87:5b: - e5:3c:d3:9e:3e:a7:3b:9e:f4:03:b3:f9:f1:7d:13: - 74:02:ff:bb:a1:e5:fa:00:79:1c:a6:66:41:88:5c: - 60:57:a6:2e:09:c4:ba:fd:9a:cf:a7:1f:40:c3:bb: - cc:5a:0a:55:4b:3b:38:76:51:b8:63:8b:84:94:16: - e6:56:f3 - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Basic Constraints: critical - CA:TRUE - X509v3 Key Usage: critical - Certificate Sign, CRL Sign - X509v3 Subject Key Identifier: - FE:AB:00:90:98:9E:24:FC:A9:CC:1A:8A:FB:27:B8:BF:30:6E:A8:3B - Signature Algorithm: sha256WithRSAEncryption - cf:77:2c:6e:56:be:4e:b3:b6:84:00:94:ab:47:c9:0d:d2:76: - c7:86:9f:1d:07:d3:b6:b4:bb:08:78:af:69:d2:0b:49:de:33: - c5:ac:ad:c2:88:02:7d:06:b7:35:02:c1:60:c9:bf:c4:e8:94: - de:d4:d3:a9:13:25:5a:fe:6e:a2:ae:7d:05:dc:7d:f3:6c:f0: - 7e:a6:8d:ee:d9:d7:ce:58:17:e8:a9:29:ae:73:48:87:e7:9b: - ca:6e:29:a1:64:5f:19:13:f7:ae:06:10:ff:51:c6:9b:4d:55: - 25:4f:93:99:10:01:53:75:f1:13:ce:c7:a6:41:41:d2:bf:88: - a5:7f:45:fc:ac:b8:a5:b5:33:0c:82:c4:fb:07:f6:6a:e5:25: - 84:5f:06:ca:c1:86:39:11:db:58:cd:77:3b:2c:c2:4c:0f:5e: - 9a:e3:f0:ab:3e:61:1b:50:24:c2:c0:f4:f1:19:f0:11:29:b6: - a5:18:02:9b:d7:63:4c:70:8c:47:a3:03:43:5c:b9:5d:46:a0: - 0d:6f:ff:59:8e:be:dd:9f:72:c3:5b:2b:df:8c:5b:ce:e5:0c: - 46:6c:92:b2:0a:a3:4c:54:42:18:15:12:18:bd:da:fc:ba:74: - 6e:ff:c1:b6:a0:64:d8:a9:5f:55:ae:9f:5c:6a:76:96:d8:73: - 67:87:fb:4d:7f:5c:ee:69:ca:73:10:fb:8a:a9:fd:9e:bd:36: - 38:49:49:87:f4:0e:14:f0:e9:87:b8:3f:a7:4f:7a:5a:8e:79: - d4:93:e4:bb:68:52:84:ac:6c:e9:f3:98:70:55:72:32:f9:34: - ab:2b:49:b5:cd:20:62:e4:3a:7a:67:63:ab:96:dc:6d:ae:97: - ec:fc:9f:76:56:88:2e:66:cf:5b:b6:c9:a4:b0:d7:05:ba:e1: - 27:2f:93:bb:26:2a:a2:93:b0:1b:f3:8e:be:1d:40:a3:b9:36: - 8f:3e:82:1a:1a:5e:88:ea:50:f8:59:e2:83:46:29:0b:e3:44: - 5c:e1:95:b6:69:90:9a:14:6f:97:ae:81:cf:68:ef:99:9a:be: - b5:e7:e1:7f:f8:fa:13:47:16:4c:cc:6d:08:40:e7:8b:78:6f: - 50:82:44:50:3f:66:06:8a:ab:43:84:56:4a:0f:20:2d:86:0e: - f5:d2:db:d2:7a:8a:4b:cd:a5:e8:4e:f1:5e:26:25:01:59:23: - a0:7e:d2:f6:7e:21:57:d7:27:bc:15:57:4c:a4:46:c1:e0:83: - 1e:0c:4c:4d:1f:4f:06:19:e2:f9:a8:f4:3a:82:a1:b2:79:43: - 79:d6:ad:6f:7a:27:90:03:a4:ea:24:87:3f:d9:bd:d9:e9:f2: - 5f:50:49:1c:ee:ec:d7:2e ------BEGIN CERTIFICATE----- -MIIFcDCCA1igAwIBAgIEAJiWjTANBgkqhkiG9w0BAQsFADBYMQswCQYDVQQGEwJO -TDEeMBwGA1UECgwVU3RhYXQgZGVyIE5lZGVybGFuZGVuMSkwJwYDVQQDDCBTdGFh -dCBkZXIgTmVkZXJsYW5kZW4gRVYgUm9vdCBDQTAeFw0xMDEyMDgxMTE5MjlaFw0y -MjEyMDgxMTEwMjhaMFgxCzAJBgNVBAYTAk5MMR4wHAYDVQQKDBVTdGFhdCBkZXIg -TmVkZXJsYW5kZW4xKTAnBgNVBAMMIFN0YWF0IGRlciBOZWRlcmxhbmRlbiBFViBS -b290IENBMIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEA48d+ifkkSzrS -M4M1LGns3Amk41GoJSt5uAg94JG6hIXGhaTK5skuU6TJJB79VWZxXSzFYGgEt9nC -UiY4iKTWO0Cmws0/zZiTs1QUWJZV1VD+hq2kY39ch/aO5ieSZxeSAgMs3NZmdO3d -Z//BYY1jTw+bbRcwJu+r0h8QoPnFfxZpgQNH7R5ojXKhTbImxrpsX23Wr9GxE46p -rfNeaXUmGD5BKyF/7otdBwadQ8QpCiv8Kj6GyzyDOvnJDdrFmeK8eEEzduG/L13l -pJhQDBXd4Pqcfzho0LKmeqfRMb1+ilgnQ7O6M5HTp5gVXJrm0w912fxBmJc+qiXb -j5IusHsMX/FjqTf5m3VpTCgmJdrV8hJwRVXj33NeN/UhbJCONVrJ0yPr08C+eKxC -KFhmpUZtcALXEPlLVPxdhkqHz3/KRawRWrUgUY0viEeXOcDPusBCAUCZSCELa6fS -/ZbV0b5GnUngC6agIk440ME8MLxwjyx1zNDFjFE7PZQIZCZhfbnDZY8UnCHQqv0X -cgOPvZuM5l5Tnrmd74K74bzickFbIZTTRTeU0d8JOV3nI6qaHcptqAqGhYqCvkIH -1vI4gnPah1vlPNOePqc7nvQDs/nxfRN0Av+7oeX6AHkcpmZBiFxgV6YuCcS6/ZrP -px9Aw7vMWgpVSzs4dlG4Y4uElBbmVvMCAwEAAaNCMEAwDwYDVR0TAQH/BAUwAwEB -/zAOBgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYEFP6rAJCYniT8qcwaivsnuL8wbqg7 -MA0GCSqGSIb3DQEBCwUAA4ICAQDPdyxuVr5Os7aEAJSrR8kN0nbHhp8dB9O2tLsI -eK9p0gtJ3jPFrK3CiAJ9Brc1AsFgyb/E6JTe1NOpEyVa/m6irn0F3H3zbPB+po3u -2dfOWBfoqSmuc0iH55vKbimhZF8ZE/euBhD/UcabTVUlT5OZEAFTdfETzsemQUHS -v4ilf0X8rLiltTMMgsT7B/Zq5SWEXwbKwYY5EdtYzXc7LMJMD16a4/CrPmEbUCTC -wPTxGfARKbalGAKb12NMcIxHowNDXLldRqANb/9Zjr7dn3LDWyvfjFvO5QxGbJKy -CqNMVEIYFRIYvdr8unRu/8G2oGTYqV9Vrp9canaW2HNnh/tNf1zuacpzEPuKqf2e -vTY4SUmH9A4U8OmHuD+nT3pajnnUk+S7aFKErGzp85hwVXIy+TSrK0m1zSBi5Dp6 -Z2Orltxtrpfs/J92VoguZs9btsmksNcFuuEnL5O7Jiqik7Ab846+HUCjuTaPPoIa -Gl6I6lD4WeKDRikL40Rc4ZW2aZCaFG+XroHPaO+Zmr615+F/+PoTRxZMzG0IQOeL -eG9QgkRQP2YGiqtDhFZKDyAthg710tvSeopLzaXoTvFeJiUBWSOgftL2fiFX1ye8 -FVdMpEbB4IMeDExNH08GGeL5qPQ6gqGyeUN51q1veieQA6TqJIc/2b3Z6fJfUEkc -7uzXLg== ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: 10000012 (0x98968c) - Signature Algorithm: sha256WithRSAEncryption - Issuer: C=NL, O=Staat der Nederlanden, CN=Staat der Nederlanden Root CA - G2 - Validity - Not Before: Mar 26 11:18:17 2008 GMT - Not After : Mar 25 11:03:10 2020 GMT - Subject: C=NL, O=Staat der Nederlanden, CN=Staat der Nederlanden Root CA - G2 - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (4096 bit) - Modulus: - 00:c5:59:e7:6f:75:aa:3e:4b:9c:b5:b8:ac:9e:0b: - e4:f9:d9:ca:ab:5d:8f:b5:39:10:82:d7:af:51:e0: - 3b:e1:00:48:6a:cf:da:e1:06:43:11:99:aa:14:25: - 12:ad:22:e8:00:6d:43:c4:a9:b8:e5:1f:89:4b:67: - bd:61:48:ef:fd:d2:e0:60:88:e5:b9:18:60:28:c3: - 77:2b:ad:b0:37:aa:37:de:64:59:2a:46:57:e4:4b: - b9:f8:37:7c:d5:36:e7:80:c1:b6:f3:d4:67:9b:96: - e8:ce:d7:c6:0a:53:d0:6b:49:96:f3:a3:0b:05:77: - 48:f7:25:e5:70:ac:30:14:20:25:e3:7f:75:5a:e5: - 48:f8:4e:7b:03:07:04:fa:82:61:87:6e:f0:3b:c4: - a4:c7:d0:f5:74:3e:a5:5d:1a:08:f2:9b:25:d2:f6: - ac:04:26:3e:55:3a:62:28:a5:7b:b2:30:af:f8:37: - c2:d1:ba:d6:38:fd:f4:ef:49:30:37:99:26:21:48: - 85:01:a9:e5:16:e7:dc:90:55:df:0f:e8:38:cd:99: - 37:21:4f:5d:f5:22:6f:6a:c5:12:16:60:17:55:f2: - 65:66:a6:a7:30:91:38:c1:38:1d:86:04:84:ba:1a: - 25:78:5e:9d:af:cc:50:60:d6:13:87:52:ed:63:1f: - 6d:65:7d:c2:15:18:74:ca:e1:7e:64:29:8c:72:d8: - 16:13:7d:0b:49:4a:f1:28:1b:20:74:6b:c5:3d:dd: - b0:aa:48:09:3d:2e:82:94:cd:1a:65:d9:2b:88:9a: - 99:bc:18:7e:9f:ee:7d:66:7c:3e:bd:94:b8:81:ce: - cd:98:30:78:c1:6f:67:d0:be:5f:e0:68:ed:de:e2: - b1:c9:2c:59:78:92:aa:df:2b:60:63:f2:e5:5e:b9: - e3:ca:fa:7f:50:86:3e:a2:34:18:0c:09:68:28:11: - 1c:e4:e1:b9:5c:3e:47:ba:32:3f:18:cc:5b:84:f5: - f3:6b:74:c4:72:74:e1:e3:8b:a0:4a:bd:8d:66:2f: - ea:ad:35:da:20:d3:88:82:61:f0:12:22:b6:bc:d0: - d5:a4:ec:af:54:88:25:24:3c:a7:6d:b1:72:29:3f: - 3e:57:a6:7f:55:af:6e:26:c6:fe:e7:cc:40:5c:51: - 44:81:0a:78:de:4a:ce:55:bf:1d:d5:d9:b7:56:ef: - f0:76:ff:0b:79:b5:af:bd:fb:a9:69:91:46:97:68: - 80:14:36:1d:b3:7f:bb:29:98:36:a5:20:fa:82:60: - 62:33:a4:ec:d6:ba:07:a7:6e:c5:cf:14:a6:e7:d6: - 92:34:d8:81:f5:fc:1d:5d:aa:5c:1e:f6:a3:4d:3b: - b8:f7:39 - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Basic Constraints: critical - CA:TRUE - X509v3 Certificate Policies: - Policy: X509v3 Any Policy - CPS: http://www.pkioverheid.nl/policies/root-policy-G2 - - X509v3 Key Usage: critical - Certificate Sign, CRL Sign - X509v3 Subject Key Identifier: - 91:68:32:87:15:1D:89:E2:B5:F1:AC:36:28:34:8D:0B:7C:62:88:EB - Signature Algorithm: sha256WithRSAEncryption - a8:41:4a:67:2a:92:81:82:50:6e:e1:d7:d8:b3:39:3b:f3:02: - 15:09:50:51:ef:2d:bd:24:7b:88:86:3b:f9:b4:bc:92:09:96: - b9:f6:c0:ab:23:60:06:79:8c:11:4e:51:d2:79:80:33:fb:9d: - 48:be:ec:41:43:81:1f:7e:47:40:1c:e5:7a:08:ca:aa:8b:75: - ad:14:c4:c2:e8:66:3c:82:07:a7:e6:27:82:5b:18:e6:0f:6e: - d9:50:3e:8a:42:18:29:c6:b4:56:fc:56:10:a0:05:17:bd:0c: - 23:7f:f4:93:ed:9c:1a:51:be:dd:45:41:bf:91:24:b4:1f:8c: - e9:5f:cf:7b:21:99:9f:95:9f:39:3a:46:1c:6c:f9:cd:7b:9c: - 90:cd:28:a9:c7:a9:55:bb:ac:62:34:62:35:13:4b:14:3a:55: - 83:b9:86:8d:92:a6:c6:f4:07:25:54:cc:16:57:12:4a:82:78: - c8:14:d9:17:82:26:2d:5d:20:1f:79:ae:fe:d4:70:16:16:95: - 83:d8:35:39:ff:52:5d:75:1c:16:c5:13:55:cf:47:cc:75:65: - 52:4a:de:f0:b0:a7:e4:0a:96:0b:fb:ad:c2:e2:25:84:b2:dd: - e4:bd:7e:59:6c:9b:f0:f0:d8:e7:ca:f2:e9:97:38:7e:89:be: - cc:fb:39:17:61:3f:72:db:3a:91:d8:65:01:19:1d:ad:50:a4: - 57:0a:7c:4b:bc:9c:71:73:2a:45:51:19:85:cc:8e:fd:47:a7: - 74:95:1d:a8:d1:af:4e:17:b1:69:26:c2:aa:78:57:5b:c5:4d: - a7:e5:9e:05:17:94:ca:b2:5f:a0:49:18:8d:34:e9:26:6c:48: - 1e:aa:68:92:05:e1:82:73:5a:9b:dc:07:5b:08:6d:7d:9d:d7: - 8d:21:d9:fc:14:20:aa:c2:45:df:3f:e7:00:b2:51:e4:c2:f8: - 05:b9:79:1a:8c:34:f3:9e:5b:e4:37:5b:6b:4a:df:2c:57:8a: - 40:5a:36:ba:dd:75:44:08:37:42:70:0c:fe:dc:5e:21:a0:a3: - 8a:c0:90:9c:68:da:50:e6:45:10:47:78:b6:4e:d2:65:c9:c3: - 37:df:e1:42:63:b0:57:37:45:2d:7b:8a:9c:bf:05:ea:65:55: - 33:f7:39:10:c5:28:2a:21:7a:1b:8a:c4:24:f9:3f:15:c8:9a: - 15:20:f5:55:62:96:ed:6d:93:50:bc:e4:aa:78:ad:d9:cb:0a: - 65:87:a6:66:c1:c4:81:a3:77:3a:58:1e:0b:ee:83:8b:9d:1e: - d2:52:a4:cc:1d:6f:b0:98:6d:94:31:b5:f8:71:0a:dc:b9:fc: - 7d:32:60:e6:eb:af:8a:01 ------BEGIN CERTIFICATE----- -MIIFyjCCA7KgAwIBAgIEAJiWjDANBgkqhkiG9w0BAQsFADBaMQswCQYDVQQGEwJO -TDEeMBwGA1UECgwVU3RhYXQgZGVyIE5lZGVybGFuZGVuMSswKQYDVQQDDCJTdGFh -dCBkZXIgTmVkZXJsYW5kZW4gUm9vdCBDQSAtIEcyMB4XDTA4MDMyNjExMTgxN1oX -DTIwMDMyNTExMDMxMFowWjELMAkGA1UEBhMCTkwxHjAcBgNVBAoMFVN0YWF0IGRl -ciBOZWRlcmxhbmRlbjErMCkGA1UEAwwiU3RhYXQgZGVyIE5lZGVybGFuZGVuIFJv -b3QgQ0EgLSBHMjCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAMVZ5291 -qj5LnLW4rJ4L5PnZyqtdj7U5EILXr1HgO+EASGrP2uEGQxGZqhQlEq0i6ABtQ8Sp -uOUfiUtnvWFI7/3S4GCI5bkYYCjDdyutsDeqN95kWSpGV+RLufg3fNU254DBtvPU -Z5uW6M7XxgpT0GtJlvOjCwV3SPcl5XCsMBQgJeN/dVrlSPhOewMHBPqCYYdu8DvE -pMfQ9XQ+pV0aCPKbJdL2rAQmPlU6Yiile7Iwr/g3wtG61jj99O9JMDeZJiFIhQGp -5Rbn3JBV3w/oOM2ZNyFPXfUib2rFEhZgF1XyZWampzCROME4HYYEhLoaJXhena/M -UGDWE4dS7WMfbWV9whUYdMrhfmQpjHLYFhN9C0lK8SgbIHRrxT3dsKpICT0ugpTN -GmXZK4iambwYfp/ufWZ8Pr2UuIHOzZgweMFvZ9C+X+Bo7d7iscksWXiSqt8rYGPy -5V6548r6f1CGPqI0GAwJaCgRHOThuVw+R7oyPxjMW4T182t0xHJ04eOLoEq9jWYv -6q012iDTiIJh8BIitrzQ1aTsr1SIJSQ8p22xcik/Plemf1WvbibG/ufMQFxRRIEK -eN5KzlW/HdXZt1bv8Hb/C3m1r737qWmRRpdogBQ2HbN/uymYNqUg+oJgYjOk7Na6 -B6duxc8UpufWkjTYgfX8HV2qXB72o007uPc5AgMBAAGjgZcwgZQwDwYDVR0TAQH/ -BAUwAwEB/zBSBgNVHSAESzBJMEcGBFUdIAAwPzA9BggrBgEFBQcCARYxaHR0cDov -L3d3dy5wa2lvdmVyaGVpZC5ubC9wb2xpY2llcy9yb290LXBvbGljeS1HMjAOBgNV -HQ8BAf8EBAMCAQYwHQYDVR0OBBYEFJFoMocVHYnitfGsNig0jQt8YojrMA0GCSqG -SIb3DQEBCwUAA4ICAQCoQUpnKpKBglBu4dfYszk78wIVCVBR7y29JHuIhjv5tLyS -CZa59sCrI2AGeYwRTlHSeYAz+51IvuxBQ4EffkdAHOV6CMqqi3WtFMTC6GY8ggen -5ieCWxjmD27ZUD6KQhgpxrRW/FYQoAUXvQwjf/ST7ZwaUb7dRUG/kSS0H4zpX897 -IZmflZ85OkYcbPnNe5yQzSipx6lVu6xiNGI1E0sUOlWDuYaNkqbG9AclVMwWVxJK -gnjIFNkXgiYtXSAfea7+1HAWFpWD2DU5/1JddRwWxRNVz0fMdWVSSt7wsKfkCpYL -+63C4iWEst3kvX5ZbJvw8NjnyvLplzh+ib7M+zkXYT9y2zqR2GUBGR2tUKRXCnxL -vJxxcypFURmFzI79R6d0lR2o0a9OF7FpJsKqeFdbxU2n5Z4FF5TKsl+gSRiNNOkm -bEgeqmiSBeGCc1qb3AdbCG19ndeNIdn8FCCqwkXfP+cAslHkwvgFuXkajDTznlvk -N1trSt8sV4pAWja63XVECDdCcAz+3F4hoKOKwJCcaNpQ5kUQR3i2TtJlycM33+FC -Y7BXN0Ute4qcvwXqZVUz9zkQxSgqIXobisQk+T8VyJoVIPVVYpbtbZNQvOSqeK3Z -ywplh6ZmwcSBo3c6WB4L7oOLnR7SUqTMHW+wmG2UMbX4cQrcufx9MmDm66+KAQ== ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: 10003001 (0x98a239) - Signature Algorithm: sha256WithRSAEncryption - Issuer: C=NL, O=Staat der Nederlanden, CN=Staat der Nederlanden Root CA - G3 - Validity - Not Before: Nov 14 11:28:42 2013 GMT - Not After : Nov 13 23:00:00 2028 GMT - Subject: C=NL, O=Staat der Nederlanden, CN=Staat der Nederlanden Root CA - G3 - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (4096 bit) - Modulus: - 00:be:32:a2:54:0f:70:fb:2c:5c:59:eb:6c:c4:a4: - 51:e8:85:2a:b3:cc:4a:34:f2:b0:5f:f3:0e:c7:1c: - 3d:53:1e:88:08:68:d8:6f:3d:ad:c2:9e:cc:82:67: - 07:27:87:68:71:3a:9f:75:96:22:46:05:b0:ed:ad: - c7:5b:9e:2a:de:9c:fc:3a:c6:95:a7:f5:17:67:18: - e7:2f:49:08:0c:5c:cf:e6:cc:34:ed:78:fb:50:b1: - dc:6b:32:f0:a2:fe:b6:3c:e4:ec:5a:97:c7:3f:1e: - 70:08:30:a0:dc:c5:b3:6d:6f:d0:82:72:11:ab:d2: - 81:68:59:82:17:b7:78:92:60:fa:cc:de:3f:84:eb: - 8d:38:33:90:0a:72:23:fa:35:cc:26:71:31:d1:72: - 28:92:d9:5b:23:6d:66:b5:6d:07:42:eb:a6:33:ce: - 92:db:c0:f6:6c:63:78:cd:ca:4e:3d:b5:e5:52:9b: - f1:be:3b:e6:54:60:b0:66:1e:09:ab:07:fe:54:89: - 11:42:d1:f7:24:ba:60:78:1a:98:f7:c9:11:fd:16: - c1:35:1a:54:75:ef:43:d3:e5:ae:4e:ce:e7:7b:c3: - c6:4e:61:51:4b:ab:9a:45:4b:a1:1f:41:bd:48:53: - 15:71:64:0b:86:b3:e5:2e:be:ce:a4:1b:c1:29:84: - a2:b5:cb:08:23:76:43:22:24:1f:17:04:d4:6e:9c: - c6:fc:7f:2b:66:1a:ec:8a:e5:d6:cf:4d:f5:63:09: - b7:15:39:d6:7b:ac:eb:e3:7c:e9:4e:fc:75:42:c8: - ed:58:95:0c:06:42:a2:9c:f7:e4:70:b3:df:72:6f: - 5a:37:40:89:d8:85:a4:d7:f1:0b:de:43:19:d4:4a: - 58:2c:8c:8a:39:9e:bf:84:87:f1:16:3b:36:0c:e9: - d3:b4:ca:6c:19:41:52:09:a1:1d:b0:6a:bf:82:ef: - 70:51:21:32:dc:05:76:8c:cb:f7:64:e4:03:50:af: - 8c:91:67:ab:c5:f2:ee:58:d8:de:be:f7:e7:31:cf: - 6c:c9:3b:71:c1:d5:88:b5:65:bc:c0:e8:17:17:07: - 12:b5:5c:d2:ab:20:93:b4:e6:82:83:70:36:c5:cd: - a3:8d:ad:8b:ec:a3:c1:43:87:e6:43:e2:34:be:95: - 8b:35:ed:07:39:da:a8:1d:7a:9f:36:9e:12:b0:0c: - 65:12:90:15:60:d9:26:40:44:e3:56:60:a5:10:d4: - 6a:3c:fd:41:dc:0e:5a:47:b6:ef:97:61:75:4f:d9: - fe:c7:b2:1d:d4:ed:5d:49:b3:a9:6a:cb:66:84:13: - d5:5c:a0:dc:df:6e:77:06:d1:71:75:c8:57:6f:af: - 0f:77:5b - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Basic Constraints: critical - CA:TRUE - X509v3 Key Usage: critical - Certificate Sign, CRL Sign - X509v3 Subject Key Identifier: - 54:AD:FA:C7:92:57:AE:CA:35:9C:2E:12:FB:E4:BA:5D:20:DC:94:57 - Signature Algorithm: sha256WithRSAEncryption - 30:99:9d:05:32:c8:5e:0e:3b:98:01:3a:8a:a4:e7:07:f7:7a: - f8:e7:9a:df:50:43:53:97:2a:3d:ca:3c:47:98:2e:e1:15:7b: - f1:92:f3:61:da:90:25:16:65:c0:9f:54:5d:0e:03:3b:5b:77: - 02:9c:84:b6:0d:98:5f:34:dd:3b:63:c2:c3:28:81:c2:9c:29: - 2e:29:e2:c8:c3:01:f2:33:ea:2a:aa:cc:09:08:f7:65:67:c6: - cd:df:d3:b6:2b:a7:bd:cc:d1:0e:70:5f:b8:23:d1:cb:91:4e: - 0a:f4:c8:7a:e5:d9:63:36:c1:d4:df:fc:22:97:f7:60:5d:ea: - 29:2f:58:b2:bd:58:bd:8d:96:4f:10:75:bf:48:7b:3d:51:87: - a1:3c:74:22:c2:fc:07:7f:80:dc:c4:ac:fe:6a:c1:70:30:b0: - e9:8e:69:e2:2c:69:81:94:09:ba:dd:fe:4d:c0:83:8c:94:58: - c0:46:20:af:9c:1f:02:f8:35:55:49:2f:46:d4:c0:f0:a0:96: - 02:0f:33:c5:71:f3:9e:23:7d:94:b7:fd:3a:d3:09:83:06:21: - fd:60:3d:ae:32:c0:d2:ee:8d:a6:f0:e7:b4:82:7c:0a:cc:70: - c9:79:80:f8:fe:4c:f7:35:84:19:8a:31:fb:0a:d9:d7:7f:9b: - f0:a2:9a:6b:c3:05:4a:ed:41:60:14:30:d1:aa:11:42:6e:d3: - 23:02:04:0b:c6:65:dd:dd:52:77:da:81:6b:b2:a8:fa:01:38: - b9:96:ea:2a:6c:67:97:89:94:9e:bc:e1:54:d5:e4:6a:78:ef: - 4a:bd:2b:9a:3d:40:7e:c6:c0:75:d2:6e:fb:68:30:ec:ec:8b: - 9d:f9:49:35:9a:1a:2c:d9:b3:95:39:d5:1e:92:f7:a6:b9:65: - 2f:e5:3d:6d:3a:48:4c:08:dc:e4:28:12:28:be:7d:35:5c:ea: - e0:16:7e:13:1b:6a:d7:3e:d7:9e:fc:2d:75:b2:c1:14:d5:23: - 03:db:5b:6f:0b:3e:78:2f:0d:de:33:8d:16:b7:48:e7:83:9a: - 81:0f:7b:c1:43:4d:55:04:17:38:4a:51:d5:59:a2:89:74:d3: - 9f:be:1e:4b:d7:c6:6d:b7:88:24:6f:60:91:a4:82:85:5b:56: - 41:bc:d0:44:ab:6a:13:be:d1:2c:58:b7:12:33:58:b2:37:63: - dc:13:f5:94:1d:3f:40:51:f5:4f:f5:3a:ed:c8:c5:eb:c2:1e: - 1d:16:95:7a:c7:7e:42:71:93:6e:4b:15:b7:30:df:aa:ed:57: - 85:48:ac:1d:6a:dd:39:69:e4:e1:79:78:be:ce:05:bf:a1:0c: - f7:80:7b:21:67:27:30:59 ------BEGIN CERTIFICATE----- -MIIFdDCCA1ygAwIBAgIEAJiiOTANBgkqhkiG9w0BAQsFADBaMQswCQYDVQQGEwJO -TDEeMBwGA1UECgwVU3RhYXQgZGVyIE5lZGVybGFuZGVuMSswKQYDVQQDDCJTdGFh -dCBkZXIgTmVkZXJsYW5kZW4gUm9vdCBDQSAtIEczMB4XDTEzMTExNDExMjg0MloX -DTI4MTExMzIzMDAwMFowWjELMAkGA1UEBhMCTkwxHjAcBgNVBAoMFVN0YWF0IGRl -ciBOZWRlcmxhbmRlbjErMCkGA1UEAwwiU3RhYXQgZGVyIE5lZGVybGFuZGVuIFJv -b3QgQ0EgLSBHMzCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAL4yolQP -cPssXFnrbMSkUeiFKrPMSjTysF/zDsccPVMeiAho2G89rcKezIJnByeHaHE6n3WW -IkYFsO2tx1ueKt6c/DrGlaf1F2cY5y9JCAxcz+bMNO14+1Cx3Gsy8KL+tjzk7FqX -xz8ecAgwoNzFs21v0IJyEavSgWhZghe3eJJg+szeP4TrjTgzkApyI/o1zCZxMdFy -KJLZWyNtZrVtB0LrpjPOktvA9mxjeM3KTj215VKb8b475lRgsGYeCasH/lSJEULR -9yS6YHgamPfJEf0WwTUaVHXvQ9Plrk7O53vDxk5hUUurmkVLoR9BvUhTFXFkC4az -5S6+zqQbwSmEorXLCCN2QyIkHxcE1G6cxvx/K2Ya7Irl1s9N9WMJtxU51nus6+N8 -6U78dULI7ViVDAZCopz35HCz33JvWjdAidiFpNfxC95DGdRKWCyMijmev4SH8RY7 -Ngzp07TKbBlBUgmhHbBqv4LvcFEhMtwFdozL92TkA1CvjJFnq8Xy7ljY3r735zHP -bMk7ccHViLVlvMDoFxcHErVc0qsgk7TmgoNwNsXNo42ti+yjwUOH5kPiNL6VizXt -BznaqB16nzaeErAMZRKQFWDZJkBE41ZgpRDUajz9QdwOWke275dhdU/Z/seyHdTt -XUmzqWrLZoQT1Vyg3N9udwbRcXXIV2+vD3dbAgMBAAGjQjBAMA8GA1UdEwEB/wQF -MAMBAf8wDgYDVR0PAQH/BAQDAgEGMB0GA1UdDgQWBBRUrfrHkleuyjWcLhL75Lpd -INyUVzANBgkqhkiG9w0BAQsFAAOCAgEAMJmdBTLIXg47mAE6iqTnB/d6+Oea31BD -U5cqPco8R5gu4RV78ZLzYdqQJRZlwJ9UXQ4DO1t3ApyEtg2YXzTdO2PCwyiBwpwp -LiniyMMB8jPqKqrMCQj3ZWfGzd/TtiunvczRDnBfuCPRy5FOCvTIeuXZYzbB1N/8 -Ipf3YF3qKS9Ysr1YvY2WTxB1v0h7PVGHoTx0IsL8B3+A3MSs/mrBcDCw6Y5p4ixp -gZQJut3+TcCDjJRYwEYgr5wfAvg1VUkvRtTA8KCWAg8zxXHzniN9lLf9OtMJgwYh -/WA9rjLA0u6NpvDntIJ8CsxwyXmA+P5M9zWEGYox+wrZ13+b8KKaa8MFSu1BYBQw -0aoRQm7TIwIEC8Zl3d1Sd9qBa7Ko+gE4uZbqKmxnl4mUnrzhVNXkanjvSr0rmj1A -fsbAddJu+2gw7OyLnflJNZoaLNmzlTnVHpL3prllL+U9bTpITAjc5CgSKL59NVzq -4BZ+Extq1z7XnvwtdbLBFNUjA9tbbws+eC8N3jONFrdI54OagQ97wUNNVQQXOEpR -1VmiiXTTn74eS9fGbbeIJG9gkaSChVtWQbzQRKtqE77RLFi3EjNYsjdj3BP1lB0/ -QFH1T/U67cjF68IeHRaVesd+QnGTbksVtzDfqu1XhUisHWrdOWnk4Xl4vs4Fv6EM -94B7IWcnMFk= ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: 0 (0x0) - Signature Algorithm: sha1WithRSAEncryption - Issuer: C=US, O=Starfield Technologies, Inc., OU=Starfield Class 2 Certification Authority - Validity - Not Before: Jun 29 17:39:16 2004 GMT - Not After : Jun 29 17:39:16 2034 GMT - Subject: C=US, O=Starfield Technologies, Inc., OU=Starfield Class 2 Certification Authority - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (2048 bit) - Modulus: - 00:b7:32:c8:fe:e9:71:a6:04:85:ad:0c:11:64:df: - ce:4d:ef:c8:03:18:87:3f:a1:ab:fb:3c:a6:9f:f0: - c3:a1:da:d4:d8:6e:2b:53:90:fb:24:a4:3e:84:f0: - 9e:e8:5f:ec:e5:27:44:f5:28:a6:3f:7b:de:e0:2a: - f0:c8:af:53:2f:9e:ca:05:01:93:1e:8f:66:1c:39: - a7:4d:fa:5a:b6:73:04:25:66:eb:77:7f:e7:59:c6: - 4a:99:25:14:54:eb:26:c7:f3:7f:19:d5:30:70:8f: - af:b0:46:2a:ff:ad:eb:29:ed:d7:9f:aa:04:87:a3: - d4:f9:89:a5:34:5f:db:43:91:82:36:d9:66:3c:b1: - b8:b9:82:fd:9c:3a:3e:10:c8:3b:ef:06:65:66:7a: - 9b:19:18:3d:ff:71:51:3c:30:2e:5f:be:3d:77:73: - b2:5d:06:6c:c3:23:56:9a:2b:85:26:92:1c:a7:02: - b3:e4:3f:0d:af:08:79:82:b8:36:3d:ea:9c:d3:35: - b3:bc:69:ca:f5:cc:9d:e8:fd:64:8d:17:80:33:6e: - 5e:4a:5d:99:c9:1e:87:b4:9d:1a:c0:d5:6e:13:35: - 23:5e:df:9b:5f:3d:ef:d6:f7:76:c2:ea:3e:bb:78: - 0d:1c:42:67:6b:04:d8:f8:d6:da:6f:8b:f2:44:a0: - 01:ab - Exponent: 3 (0x3) - X509v3 extensions: - X509v3 Subject Key Identifier: - BF:5F:B7:D1:CE:DD:1F:86:F4:5B:55:AC:DC:D7:10:C2:0E:A9:88:E7 - X509v3 Authority Key Identifier: - keyid:BF:5F:B7:D1:CE:DD:1F:86:F4:5B:55:AC:DC:D7:10:C2:0E:A9:88:E7 - DirName:/C=US/O=Starfield Technologies, Inc./OU=Starfield Class 2 Certification Authority - serial:00 - - X509v3 Basic Constraints: - CA:TRUE - Signature Algorithm: sha1WithRSAEncryption - 05:9d:3f:88:9d:d1:c9:1a:55:a1:ac:69:f3:f3:59:da:9b:01: - 87:1a:4f:57:a9:a1:79:09:2a:db:f7:2f:b2:1e:cc:c7:5e:6a: - d8:83:87:a1:97:ef:49:35:3e:77:06:41:58:62:bf:8e:58:b8: - 0a:67:3f:ec:b3:dd:21:66:1f:c9:54:fa:72:cc:3d:4c:40:d8: - 81:af:77:9e:83:7a:bb:a2:c7:f5:34:17:8e:d9:11:40:f4:fc: - 2c:2a:4d:15:7f:a7:62:5d:2e:25:d3:00:0b:20:1a:1d:68:f9: - 17:b8:f4:bd:8b:ed:28:59:dd:4d:16:8b:17:83:c8:b2:65:c7: - 2d:7a:a5:aa:bc:53:86:6d:dd:57:a4:ca:f8:20:41:0b:68:f0: - f4:fb:74:be:56:5d:7a:79:f5:f9:1d:85:e3:2d:95:be:f5:71: - 90:43:cc:8d:1f:9a:00:0a:87:29:e9:55:22:58:00:23:ea:e3: - 12:43:29:5b:47:08:dd:8c:41:6a:65:06:a8:e5:21:aa:41:b4: - 95:21:95:b9:7d:d1:34:ab:13:d6:ad:bc:dc:e2:3d:39:cd:bd: - 3e:75:70:a1:18:59:03:c9:22:b4:8f:9c:d5:5e:2a:d7:a5:b6: - d4:0a:6d:f8:b7:40:11:46:9a:1f:79:0e:62:bf:0f:97:ec:e0: - 2f:1f:17:94 ------BEGIN CERTIFICATE----- -MIIEDzCCAvegAwIBAgIBADANBgkqhkiG9w0BAQUFADBoMQswCQYDVQQGEwJVUzEl -MCMGA1UEChMcU3RhcmZpZWxkIFRlY2hub2xvZ2llcywgSW5jLjEyMDAGA1UECxMp -U3RhcmZpZWxkIENsYXNzIDIgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNMDQw -NjI5MTczOTE2WhcNMzQwNjI5MTczOTE2WjBoMQswCQYDVQQGEwJVUzElMCMGA1UE -ChMcU3RhcmZpZWxkIFRlY2hub2xvZ2llcywgSW5jLjEyMDAGA1UECxMpU3RhcmZp -ZWxkIENsYXNzIDIgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwggEgMA0GCSqGSIb3 -DQEBAQUAA4IBDQAwggEIAoIBAQC3Msj+6XGmBIWtDBFk385N78gDGIc/oav7PKaf -8MOh2tTYbitTkPskpD6E8J7oX+zlJ0T1KKY/e97gKvDIr1MvnsoFAZMej2YcOadN -+lq2cwQlZut3f+dZxkqZJRRU6ybH838Z1TBwj6+wRir/resp7defqgSHo9T5iaU0 -X9tDkYI22WY8sbi5gv2cOj4QyDvvBmVmepsZGD3/cVE8MC5fvj13c7JdBmzDI1aa -K4UmkhynArPkPw2vCHmCuDY96pzTNbO8acr1zJ3o/WSNF4Azbl5KXZnJHoe0nRrA -1W4TNSNe35tfPe/W93bC6j67eA0cQmdrBNj41tpvi/JEoAGrAgEDo4HFMIHCMB0G -A1UdDgQWBBS/X7fRzt0fhvRbVazc1xDCDqmI5zCBkgYDVR0jBIGKMIGHgBS/X7fR -zt0fhvRbVazc1xDCDqmI56FspGowaDELMAkGA1UEBhMCVVMxJTAjBgNVBAoTHFN0 -YXJmaWVsZCBUZWNobm9sb2dpZXMsIEluYy4xMjAwBgNVBAsTKVN0YXJmaWVsZCBD -bGFzcyAyIENlcnRpZmljYXRpb24gQXV0aG9yaXR5ggEAMAwGA1UdEwQFMAMBAf8w -DQYJKoZIhvcNAQEFBQADggEBAAWdP4id0ckaVaGsafPzWdqbAYcaT1epoXkJKtv3 -L7IezMdeatiDh6GX70k1PncGQVhiv45YuApnP+yz3SFmH8lU+nLMPUxA2IGvd56D -eruix/U0F47ZEUD0/CwqTRV/p2JdLiXTAAsgGh1o+Re49L2L7ShZ3U0WixeDyLJl -xy16paq8U4Zt3VekyvggQQto8PT7dL5WXXp59fkdheMtlb71cZBDzI0fmgAKhynp -VSJYACPq4xJDKVtHCN2MQWplBqjlIapBtJUhlbl90TSrE9atvNziPTnNvT51cKEY -WQPJIrSPnNVeKtelttQKbfi3QBFGmh95DmK/D5fs4C8fF5Q= ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: 0 (0x0) - Signature Algorithm: sha256WithRSAEncryption - Issuer: C=US, ST=Arizona, L=Scottsdale, O=Starfield Technologies, Inc., CN=Starfield Root Certificate Authority - G2 - Validity - Not Before: Sep 1 00:00:00 2009 GMT - Not After : Dec 31 23:59:59 2037 GMT - Subject: C=US, ST=Arizona, L=Scottsdale, O=Starfield Technologies, Inc., CN=Starfield Root Certificate Authority - G2 - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (2048 bit) - Modulus: - 00:bd:ed:c1:03:fc:f6:8f:fc:02:b1:6f:5b:9f:48: - d9:9d:79:e2:a2:b7:03:61:56:18:c3:47:b6:d7:ca: - 3d:35:2e:89:43:f7:a1:69:9b:de:8a:1a:fd:13:20: - 9c:b4:49:77:32:29:56:fd:b9:ec:8c:dd:22:fa:72: - dc:27:61:97:ee:f6:5a:84:ec:6e:19:b9:89:2c:dc: - 84:5b:d5:74:fb:6b:5f:c5:89:a5:10:52:89:46:55: - f4:b8:75:1c:e6:7f:e4:54:ae:4b:f8:55:72:57:02: - 19:f8:17:71:59:eb:1e:28:07:74:c5:9d:48:be:6c: - b4:f4:a4:b0:f3:64:37:79:92:c0:ec:46:5e:7f:e1: - 6d:53:4c:62:af:cd:1f:0b:63:bb:3a:9d:fb:fc:79: - 00:98:61:74:cf:26:82:40:63:f3:b2:72:6a:19:0d: - 99:ca:d4:0e:75:cc:37:fb:8b:89:c1:59:f1:62:7f: - 5f:b3:5f:65:30:f8:a7:b7:4d:76:5a:1e:76:5e:34: - c0:e8:96:56:99:8a:b3:f0:7f:a4:cd:bd:dc:32:31: - 7c:91:cf:e0:5f:11:f8:6b:aa:49:5c:d1:99:94:d1: - a2:e3:63:5b:09:76:b5:56:62:e1:4b:74:1d:96:d4: - 26:d4:08:04:59:d0:98:0e:0e:e6:de:fc:c3:ec:1f: - 90:f1 - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Basic Constraints: critical - CA:TRUE - X509v3 Key Usage: critical - Certificate Sign, CRL Sign - X509v3 Subject Key Identifier: - 7C:0C:32:1F:A7:D9:30:7F:C4:7D:68:A3:62:A8:A1:CE:AB:07:5B:27 - Signature Algorithm: sha256WithRSAEncryption - 11:59:fa:25:4f:03:6f:94:99:3b:9a:1f:82:85:39:d4:76:05: - 94:5e:e1:28:93:6d:62:5d:09:c2:a0:a8:d4:b0:75:38:f1:34: - 6a:9d:e4:9f:8a:86:26:51:e6:2c:d1:c6:2d:6e:95:20:4a:92: - 01:ec:b8:8a:67:7b:31:e2:67:2e:8c:95:03:26:2e:43:9d:4a: - 31:f6:0e:b5:0c:bb:b7:e2:37:7f:22:ba:00:a3:0e:7b:52:fb: - 6b:bb:3b:c4:d3:79:51:4e:cd:90:f4:67:07:19:c8:3c:46:7a: - 0d:01:7d:c5:58:e7:6d:e6:85:30:17:9a:24:c4:10:e0:04:f7: - e0:f2:7f:d4:aa:0a:ff:42:1d:37:ed:94:e5:64:59:12:20:77: - 38:d3:32:3e:38:81:75:96:73:fa:68:8f:b1:cb:ce:1f:c5:ec: - fa:9c:7e:cf:7e:b1:f1:07:2d:b6:fc:bf:ca:a4:bf:d0:97:05: - 4a:bc:ea:18:28:02:90:bd:54:78:09:21:71:d3:d1:7d:1d:d9: - 16:b0:a9:61:3d:d0:0a:00:22:fc:c7:7b:cb:09:64:45:0b:3b: - 40:81:f7:7d:7c:32:f5:98:ca:58:8e:7d:2a:ee:90:59:73:64: - f9:36:74:5e:25:a1:f5:66:05:2e:7f:39:15:a9:2a:fb:50:8b: - 8e:85:69:f4 ------BEGIN CERTIFICATE----- -MIID3TCCAsWgAwIBAgIBADANBgkqhkiG9w0BAQsFADCBjzELMAkGA1UEBhMCVVMx -EDAOBgNVBAgTB0FyaXpvbmExEzARBgNVBAcTClNjb3R0c2RhbGUxJTAjBgNVBAoT -HFN0YXJmaWVsZCBUZWNobm9sb2dpZXMsIEluYy4xMjAwBgNVBAMTKVN0YXJmaWVs -ZCBSb290IENlcnRpZmljYXRlIEF1dGhvcml0eSAtIEcyMB4XDTA5MDkwMTAwMDAw -MFoXDTM3MTIzMTIzNTk1OVowgY8xCzAJBgNVBAYTAlVTMRAwDgYDVQQIEwdBcml6 -b25hMRMwEQYDVQQHEwpTY290dHNkYWxlMSUwIwYDVQQKExxTdGFyZmllbGQgVGVj -aG5vbG9naWVzLCBJbmMuMTIwMAYDVQQDEylTdGFyZmllbGQgUm9vdCBDZXJ0aWZp -Y2F0ZSBBdXRob3JpdHkgLSBHMjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC -ggEBAL3twQP89o/8ArFvW59I2Z154qK3A2FWGMNHttfKPTUuiUP3oWmb3ooa/RMg -nLRJdzIpVv257IzdIvpy3Cdhl+72WoTsbhm5iSzchFvVdPtrX8WJpRBSiUZV9Lh1 -HOZ/5FSuS/hVclcCGfgXcVnrHigHdMWdSL5stPSksPNkN3mSwOxGXn/hbVNMYq/N -Hwtjuzqd+/x5AJhhdM8mgkBj87JyahkNmcrUDnXMN/uLicFZ8WJ/X7NfZTD4p7dN -dloedl40wOiWVpmKs/B/pM293DIxfJHP4F8R+GuqSVzRmZTRouNjWwl2tVZi4Ut0 -HZbUJtQIBFnQmA4O5t78w+wfkPECAwEAAaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAO -BgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYEFHwMMh+n2TB/xH1oo2Kooc6rB1snMA0G -CSqGSIb3DQEBCwUAA4IBAQARWfolTwNvlJk7mh+ChTnUdgWUXuEok21iXQnCoKjU -sHU48TRqneSfioYmUeYs0cYtbpUgSpIB7LiKZ3sx4mcujJUDJi5DnUox9g61DLu3 -4jd/IroAow57UvtruzvE03lRTs2Q9GcHGcg8RnoNAX3FWOdt5oUwF5okxBDgBPfg -8n/Uqgr/Qh037ZTlZFkSIHc40zI+OIF1lnP6aI+xy84fxez6nH7PfrHxBy22/L/K -pL/QlwVKvOoYKAKQvVR4CSFx09F9HdkWsKlhPdAKACL8x3vLCWRFCztAgfd9fDL1 -mMpYjn0q7pBZc2T5NnReJaH1ZgUufzkVqSr7UIuOhWn0 ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: 0 (0x0) - Signature Algorithm: sha256WithRSAEncryption - Issuer: C=US, ST=Arizona, L=Scottsdale, O=Starfield Technologies, Inc., CN=Starfield Services Root Certificate Authority - G2 - Validity - Not Before: Sep 1 00:00:00 2009 GMT - Not After : Dec 31 23:59:59 2037 GMT - Subject: C=US, ST=Arizona, L=Scottsdale, O=Starfield Technologies, Inc., CN=Starfield Services Root Certificate Authority - G2 - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (2048 bit) - Modulus: - 00:d5:0c:3a:c4:2a:f9:4e:e2:f5:be:19:97:5f:8e: - 88:53:b1:1f:3f:cb:cf:9f:20:13:6d:29:3a:c8:0f: - 7d:3c:f7:6b:76:38:63:d9:36:60:a8:9b:5e:5c:00: - 80:b2:2f:59:7f:f6:87:f9:25:43:86:e7:69:1b:52: - 9a:90:e1:71:e3:d8:2d:0d:4e:6f:f6:c8:49:d9:b6: - f3:1a:56:ae:2b:b6:74:14:eb:cf:fb:26:e3:1a:ba: - 1d:96:2e:6a:3b:58:94:89:47:56:ff:25:a0:93:70: - 53:83:da:84:74:14:c3:67:9e:04:68:3a:df:8e:40: - 5a:1d:4a:4e:cf:43:91:3b:e7:56:d6:00:70:cb:52: - ee:7b:7d:ae:3a:e7:bc:31:f9:45:f6:c2:60:cf:13: - 59:02:2b:80:cc:34:47:df:b9:de:90:65:6d:02:cf: - 2c:91:a6:a6:e7:de:85:18:49:7c:66:4e:a3:3a:6d: - a9:b5:ee:34:2e:ba:0d:03:b8:33:df:47:eb:b1:6b: - 8d:25:d9:9b:ce:81:d1:45:46:32:96:70:87:de:02: - 0e:49:43:85:b6:6c:73:bb:64:ea:61:41:ac:c9:d4: - 54:df:87:2f:c7:22:b2:26:cc:9f:59:54:68:9f:fc: - be:2a:2f:c4:55:1c:75:40:60:17:85:02:55:39:8b: - 7f:05 - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Basic Constraints: critical - CA:TRUE - X509v3 Key Usage: critical - Certificate Sign, CRL Sign - X509v3 Subject Key Identifier: - 9C:5F:00:DF:AA:01:D7:30:2B:38:88:A2:B8:6D:4A:9C:F2:11:91:83 - Signature Algorithm: sha256WithRSAEncryption - 4b:36:a6:84:77:69:dd:3b:19:9f:67:23:08:6f:0e:61:c9:fd: - 84:dc:5f:d8:36:81:cd:d8:1b:41:2d:9f:60:dd:c7:1a:68:d9: - d1:6e:86:e1:88:23:cf:13:de:43:cf:e2:34:b3:04:9d:1f:29: - d5:bf:f8:5e:c8:d5:c1:bd:ee:92:6f:32:74:f2:91:82:2f:bd: - 82:42:7a:ad:2a:b7:20:7d:4d:bc:7a:55:12:c2:15:ea:bd:f7: - 6a:95:2e:6c:74:9f:cf:1c:b4:f2:c5:01:a3:85:d0:72:3e:ad: - 73:ab:0b:9b:75:0c:6d:45:b7:8e:94:ac:96:37:b5:a0:d0:8f: - 15:47:0e:e3:e8:83:dd:8f:fd:ef:41:01:77:cc:27:a9:62:85: - 33:f2:37:08:ef:71:cf:77:06:de:c8:19:1d:88:40:cf:7d:46: - 1d:ff:1e:c7:e1:ce:ff:23:db:c6:fa:8d:55:4e:a9:02:e7:47: - 11:46:3e:f4:fd:bd:7b:29:26:bb:a9:61:62:37:28:b6:2d:2a: - f6:10:86:64:c9:70:a7:d2:ad:b7:29:70:79:ea:3c:da:63:25: - 9f:fd:68:b7:30:ec:70:fb:75:8a:b7:6d:60:67:b2:1e:c8:b9: - e9:d8:a8:6f:02:8b:67:0d:4d:26:57:71:da:20:fc:c1:4a:50: - 8d:b1:28:ba ------BEGIN CERTIFICATE----- -MIID7zCCAtegAwIBAgIBADANBgkqhkiG9w0BAQsFADCBmDELMAkGA1UEBhMCVVMx -EDAOBgNVBAgTB0FyaXpvbmExEzARBgNVBAcTClNjb3R0c2RhbGUxJTAjBgNVBAoT -HFN0YXJmaWVsZCBUZWNobm9sb2dpZXMsIEluYy4xOzA5BgNVBAMTMlN0YXJmaWVs -ZCBTZXJ2aWNlcyBSb290IENlcnRpZmljYXRlIEF1dGhvcml0eSAtIEcyMB4XDTA5 -MDkwMTAwMDAwMFoXDTM3MTIzMTIzNTk1OVowgZgxCzAJBgNVBAYTAlVTMRAwDgYD -VQQIEwdBcml6b25hMRMwEQYDVQQHEwpTY290dHNkYWxlMSUwIwYDVQQKExxTdGFy -ZmllbGQgVGVjaG5vbG9naWVzLCBJbmMuMTswOQYDVQQDEzJTdGFyZmllbGQgU2Vy -dmljZXMgUm9vdCBDZXJ0aWZpY2F0ZSBBdXRob3JpdHkgLSBHMjCCASIwDQYJKoZI -hvcNAQEBBQADggEPADCCAQoCggEBANUMOsQq+U7i9b4Zl1+OiFOxHz/Lz58gE20p -OsgPfTz3a3Y4Y9k2YKibXlwAgLIvWX/2h/klQ4bnaRtSmpDhcePYLQ1Ob/bISdm2 -8xpWriu2dBTrz/sm4xq6HZYuajtYlIlHVv8loJNwU4PahHQUw2eeBGg6345AWh1K -Ts9DkTvnVtYAcMtS7nt9rjrnvDH5RfbCYM8TWQIrgMw0R9+53pBlbQLPLJGmpufe -hRhJfGZOozptqbXuNC66DQO4M99H67FrjSXZm86B0UVGMpZwh94CDklDhbZsc7tk -6mFBrMnUVN+HL8cisibMn1lUaJ/8viovxFUcdUBgF4UCVTmLfwUCAwEAAaNCMEAw -DwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYEFJxfAN+q -AdcwKziIorhtSpzyEZGDMA0GCSqGSIb3DQEBCwUAA4IBAQBLNqaEd2ndOxmfZyMI -bw5hyf2E3F/YNoHN2BtBLZ9g3ccaaNnRbobhiCPPE95Dz+I0swSdHynVv/heyNXB -ve6SbzJ08pGCL72CQnqtKrcgfU28elUSwhXqvfdqlS5sdJ/PHLTyxQGjhdByPq1z -qwubdQxtRbeOlKyWN7Wg0I8VRw7j6IPdj/3vQQF3zCepYoUz8jcI73HPdwbeyBkd -iEDPfUYd/x7H4c7/I9vG+o1VTqkC50cRRj70/b17KSa7qWFiNyi2LSr2EIZkyXCn -0q23KXB56jzaYyWf/Wi3MOxw+3WKt21gZ7IeyLnp2KhvAotnDU0mV3HaIPzBSlCN -sSi6 ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: 1 (0x1) - Signature Algorithm: sha1WithRSAEncryption - Issuer: C=IL, O=StartCom Ltd., OU=Secure Digital Certificate Signing, CN=StartCom Certification Authority - Validity - Not Before: Sep 17 19:46:36 2006 GMT - Not After : Sep 17 19:46:36 2036 GMT - Subject: C=IL, O=StartCom Ltd., OU=Secure Digital Certificate Signing, CN=StartCom Certification Authority - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (4096 bit) - Modulus: - 00:c1:88:db:09:bc:6c:46:7c:78:9f:95:7b:b5:33: - 90:f2:72:62:d6:c1:36:20:22:24:5e:ce:e9:77:f2: - 43:0a:a2:06:64:a4:cc:8e:36:f8:38:e6:23:f0:6e: - 6d:b1:3c:dd:72:a3:85:1c:a1:d3:3d:b4:33:2b:d3: - 2f:af:fe:ea:b0:41:59:67:b6:c4:06:7d:0a:9e:74: - 85:d6:79:4c:80:37:7a:df:39:05:52:59:f7:f4:1b: - 46:43:a4:d2:85:85:d2:c3:71:f3:75:62:34:ba:2c: - 8a:7f:1e:8f:ee:ed:34:d0:11:c7:96:cd:52:3d:ba: - 33:d6:dd:4d:de:0b:3b:4a:4b:9f:c2:26:2f:fa:b5: - 16:1c:72:35:77:ca:3c:5d:e6:ca:e1:26:8b:1a:36: - 76:5c:01:db:74:14:25:fe:ed:b5:a0:88:0f:dd:78: - ca:2d:1f:07:97:30:01:2d:72:79:fa:46:d6:13:2a: - a8:b9:a6:ab:83:49:1d:e5:f2:ef:dd:e4:01:8e:18: - 0a:8f:63:53:16:85:62:a9:0e:19:3a:cc:b5:66:a6: - c2:6b:74:07:e4:2b:e1:76:3e:b4:6d:d8:f6:44:e1: - 73:62:1f:3b:c4:be:a0:53:56:25:6c:51:09:f7:aa: - ab:ca:bf:76:fd:6d:9b:f3:9d:db:bf:3d:66:bc:0c: - 56:aa:af:98:48:95:3a:4b:df:a7:58:50:d9:38:75: - a9:5b:ea:43:0c:02:ff:99:eb:e8:6c:4d:70:5b:29: - 65:9c:dd:aa:5d:cc:af:01:31:ec:0c:eb:d2:8d:e8: - ea:9c:7b:e6:6e:f7:27:66:0c:1a:48:d7:6e:42:e3: - 3f:de:21:3e:7b:e1:0d:70:fb:63:aa:a8:6c:1a:54: - b4:5c:25:7a:c9:a2:c9:8b:16:a6:bb:2c:7e:17:5e: - 05:4d:58:6e:12:1d:01:ee:12:10:0d:c6:32:7f:18: - ff:fc:f4:fa:cd:6e:91:e8:36:49:be:1a:48:69:8b: - c2:96:4d:1a:12:b2:69:17:c1:0a:90:d6:fa:79:22: - 48:bf:ba:7b:69:f8:70:c7:fa:7a:37:d8:d8:0d:d2: - 76:4f:57:ff:90:b7:e3:91:d2:dd:ef:c2:60:b7:67: - 3a:dd:fe:aa:9c:f0:d4:8b:7f:72:22:ce:c6:9f:97: - b6:f8:af:8a:a0:10:a8:d9:fb:18:c6:b6:b5:5c:52: - 3c:89:b6:19:2a:73:01:0a:0f:03:b3:12:60:f2:7a: - 2f:81:db:a3:6e:ff:26:30:97:f5:8b:dd:89:57:b6: - ad:3d:b3:af:2b:c5:b7:76:02:f0:a5:d6:2b:9a:86: - 14:2a:72:f6:e3:33:8c:5d:09:4b:13:df:bb:8c:74: - 13:52:4b - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Basic Constraints: - CA:TRUE - X509v3 Key Usage: - Digital Signature, Key Encipherment, Key Agreement, Certificate Sign, CRL Sign - X509v3 Subject Key Identifier: - 4E:0B:EF:1A:A4:40:5B:A5:17:69:87:30:CA:34:68:43:D0:41:AE:F2 - X509v3 CRL Distribution Points: - - Full Name: - URI:http://cert.startcom.org/sfsca-crl.crl - - Full Name: - URI:http://crl.startcom.org/sfsca-crl.crl - - X509v3 Certificate Policies: - Policy: 1.3.6.1.4.1.23223.1.1.1 - CPS: http://cert.startcom.org/policy.pdf - CPS: http://cert.startcom.org/intermediate.pdf - User Notice: - Organization: Start Commercial (StartCom) Ltd. - Number: 1 - Explicit Text: Limited Liability, read the section *Legal Limitations* of the StartCom Certification Authority Policy available at http://cert.startcom.org/policy.pdf - - Netscape Cert Type: - SSL CA, S/MIME CA, Object Signing CA - Netscape Comment: - StartCom Free SSL Certification Authority - Signature Algorithm: sha1WithRSAEncryption - 16:6c:99:f4:66:0c:34:f5:d0:85:5e:7d:0a:ec:da:10:4e:38: - 1c:5e:df:a6:25:05:4b:91:32:c1:e8:3b:f1:3d:dd:44:09:5b: - 07:49:8a:29:cb:66:02:b7:b1:9a:f7:25:98:09:3c:8e:1b:e1: - dd:36:87:2b:4b:bb:68:d3:39:66:3d:a0:26:c7:f2:39:91:1d: - 51:ab:82:7b:7e:d5:ce:5a:e4:e2:03:57:70:69:97:08:f9:5e: - 58:a6:0a:df:8c:06:9a:45:16:16:38:0a:5e:57:f6:62:c7:7a: - 02:05:e6:bc:1e:b5:f2:9e:f4:a9:29:83:f8:b2:14:e3:6e:28: - 87:44:c3:90:1a:de:38:a9:3c:ac:43:4d:64:45:ce:dd:28:a9: - 5c:f2:73:7b:04:f8:17:e8:ab:b1:f3:2e:5c:64:6e:73:31:3a: - 12:b8:bc:b3:11:e4:7d:8f:81:51:9a:3b:8d:89:f4:4d:93:66: - 7b:3c:03:ed:d3:9a:1d:9a:f3:65:50:f5:a0:d0:75:9f:2f:af: - f0:ea:82:43:98:f8:69:9c:89:79:c4:43:8e:46:72:e3:64:36: - 12:af:f7:25:1e:38:89:90:77:7e:c3:6b:6a:b9:c3:cb:44:4b: - ac:78:90:8b:e7:c7:2c:1e:4b:11:44:c8:34:52:27:cd:0a:5d: - 9f:85:c1:89:d5:1a:78:f2:95:10:53:32:dd:80:84:66:75:d9: - b5:68:28:fb:61:2e:be:84:a8:38:c0:99:12:86:a5:1e:67:64: - ad:06:2e:2f:a9:70:85:c7:96:0f:7c:89:65:f5:8e:43:54:0e: - ab:dd:a5:80:39:94:60:c0:34:c9:96:70:2c:a3:12:f5:1f:48: - 7b:bd:1c:7e:6b:b7:9d:90:f4:22:3b:ae:f8:fc:2a:ca:fa:82: - 52:a0:ef:af:4b:55:93:eb:c1:b5:f0:22:8b:ac:34:4e:26:22: - 04:a1:87:2c:75:4a:b7:e5:7d:13:d7:b8:0c:64:c0:36:d2:c9: - 2f:86:12:8c:23:09:c1:1b:82:3b:73:49:a3:6a:57:87:94:e5: - d6:78:c5:99:43:63:e3:4d:e0:77:2d:e1:65:99:72:69:04:1a: - 47:09:e6:0f:01:56:24:fb:1f:bf:0e:79:a9:58:2e:b9:c4:09: - 01:7e:95:ba:6d:00:06:3e:b2:ea:4a:10:39:d8:d0:2b:f5:bf: - ec:75:bf:97:02:c5:09:1b:08:dc:55:37:e2:81:fb:37:84:43: - 62:20:ca:e7:56:4b:65:ea:fe:6c:c1:24:93:24:a1:34:eb:05: - ff:9a:22:ae:9b:7d:3f:f1:65:51:0a:a6:30:6a:b3:f4:88:1c: - 80:0d:fc:72:8a:e8:83:5e ------BEGIN CERTIFICATE----- -MIIHyTCCBbGgAwIBAgIBATANBgkqhkiG9w0BAQUFADB9MQswCQYDVQQGEwJJTDEW -MBQGA1UEChMNU3RhcnRDb20gTHRkLjErMCkGA1UECxMiU2VjdXJlIERpZ2l0YWwg -Q2VydGlmaWNhdGUgU2lnbmluZzEpMCcGA1UEAxMgU3RhcnRDb20gQ2VydGlmaWNh -dGlvbiBBdXRob3JpdHkwHhcNMDYwOTE3MTk0NjM2WhcNMzYwOTE3MTk0NjM2WjB9 -MQswCQYDVQQGEwJJTDEWMBQGA1UEChMNU3RhcnRDb20gTHRkLjErMCkGA1UECxMi -U2VjdXJlIERpZ2l0YWwgQ2VydGlmaWNhdGUgU2lnbmluZzEpMCcGA1UEAxMgU3Rh -cnRDb20gQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwggIiMA0GCSqGSIb3DQEBAQUA -A4ICDwAwggIKAoICAQDBiNsJvGxGfHiflXu1M5DycmLWwTYgIiRezul38kMKogZk -pMyONvg45iPwbm2xPN1yo4UcodM9tDMr0y+v/uqwQVlntsQGfQqedIXWeUyAN3rf -OQVSWff0G0ZDpNKFhdLDcfN1YjS6LIp/Ho/u7TTQEceWzVI9ujPW3U3eCztKS5/C -Ji/6tRYccjV3yjxd5srhJosaNnZcAdt0FCX+7bWgiA/deMotHweXMAEtcnn6RtYT -Kqi5pquDSR3l8u/d5AGOGAqPY1MWhWKpDhk6zLVmpsJrdAfkK+F2PrRt2PZE4XNi -HzvEvqBTViVsUQn3qqvKv3b9bZvzndu/PWa8DFaqr5hIlTpL36dYUNk4dalb6kMM -Av+Z6+hsTXBbKWWc3apdzK8BMewM69KN6Oqce+Zu9ydmDBpI125C4z/eIT574Q1w -+2OqqGwaVLRcJXrJosmLFqa7LH4XXgVNWG4SHQHuEhANxjJ/GP/89PrNbpHoNkm+ -Gkhpi8KWTRoSsmkXwQqQ1vp5Iki/untp+HDH+no32NgN0nZPV/+Qt+OR0t3vwmC3 -Zzrd/qqc8NSLf3Iizsafl7b4r4qgEKjZ+xjGtrVcUjyJthkqcwEKDwOzEmDyei+B -26Nu/yYwl/WL3YlXtq09s68rxbd2AvCl1iuahhQqcvbjM4xdCUsT37uMdBNSSwID -AQABo4ICUjCCAk4wDAYDVR0TBAUwAwEB/zALBgNVHQ8EBAMCAa4wHQYDVR0OBBYE -FE4L7xqkQFulF2mHMMo0aEPQQa7yMGQGA1UdHwRdMFswLKAqoCiGJmh0dHA6Ly9j -ZXJ0LnN0YXJ0Y29tLm9yZy9zZnNjYS1jcmwuY3JsMCugKaAnhiVodHRwOi8vY3Js -LnN0YXJ0Y29tLm9yZy9zZnNjYS1jcmwuY3JsMIIBXQYDVR0gBIIBVDCCAVAwggFM -BgsrBgEEAYG1NwEBATCCATswLwYIKwYBBQUHAgEWI2h0dHA6Ly9jZXJ0LnN0YXJ0 -Y29tLm9yZy9wb2xpY3kucGRmMDUGCCsGAQUFBwIBFilodHRwOi8vY2VydC5zdGFy -dGNvbS5vcmcvaW50ZXJtZWRpYXRlLnBkZjCB0AYIKwYBBQUHAgIwgcMwJxYgU3Rh -cnQgQ29tbWVyY2lhbCAoU3RhcnRDb20pIEx0ZC4wAwIBARqBl0xpbWl0ZWQgTGlh -YmlsaXR5LCByZWFkIHRoZSBzZWN0aW9uICpMZWdhbCBMaW1pdGF0aW9ucyogb2Yg -dGhlIFN0YXJ0Q29tIENlcnRpZmljYXRpb24gQXV0aG9yaXR5IFBvbGljeSBhdmFp -bGFibGUgYXQgaHR0cDovL2NlcnQuc3RhcnRjb20ub3JnL3BvbGljeS5wZGYwEQYJ -YIZIAYb4QgEBBAQDAgAHMDgGCWCGSAGG+EIBDQQrFilTdGFydENvbSBGcmVlIFNT -TCBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTANBgkqhkiG9w0BAQUFAAOCAgEAFmyZ -9GYMNPXQhV59CuzaEE44HF7fpiUFS5Eyweg78T3dRAlbB0mKKctmArexmvclmAk8 -jhvh3TaHK0u7aNM5Zj2gJsfyOZEdUauCe37Vzlrk4gNXcGmXCPleWKYK34wGmkUW -FjgKXlf2Ysd6AgXmvB618p70qSmD+LIU424oh0TDkBreOKk8rENNZEXO3SipXPJz -ewT4F+irsfMuXGRuczE6Eri8sxHkfY+BUZo7jYn0TZNmezwD7dOaHZrzZVD1oNB1 -ny+v8OqCQ5j4aZyJecRDjkZy42Q2Eq/3JR44iZB3fsNrarnDy0RLrHiQi+fHLB5L -EUTINFInzQpdn4XBidUaePKVEFMy3YCEZnXZtWgo+2EuvoSoOMCZEoalHmdkrQYu -L6lwhceWD3yJZfWOQ1QOq92lgDmUYMA0yZZwLKMS9R9Ie70cfmu3nZD0Ijuu+Pwq -yvqCUqDvr0tVk+vBtfAii6w0TiYiBKGHLHVKt+V9E9e4DGTANtLJL4YSjCMJwRuC -O3NJo2pXh5Tl1njFmUNj403gdy3hZZlyaQQaRwnmDwFWJPsfvw55qVguucQJAX6V -um0ABj6y6koQOdjQK/W/7HW/lwLFCRsI3FU34oH7N4RDYiDK51ZLZer+bMEkkySh -NOsF/5oirpt9P/FlUQqmMGqz9IgcgA38corog14= ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: 45 (0x2d) - Signature Algorithm: sha256WithRSAEncryption - Issuer: C=IL, O=StartCom Ltd., OU=Secure Digital Certificate Signing, CN=StartCom Certification Authority - Validity - Not Before: Sep 17 19:46:37 2006 GMT - Not After : Sep 17 19:46:36 2036 GMT - Subject: C=IL, O=StartCom Ltd., OU=Secure Digital Certificate Signing, CN=StartCom Certification Authority - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (4096 bit) - Modulus: - 00:c1:88:db:09:bc:6c:46:7c:78:9f:95:7b:b5:33: - 90:f2:72:62:d6:c1:36:20:22:24:5e:ce:e9:77:f2: - 43:0a:a2:06:64:a4:cc:8e:36:f8:38:e6:23:f0:6e: - 6d:b1:3c:dd:72:a3:85:1c:a1:d3:3d:b4:33:2b:d3: - 2f:af:fe:ea:b0:41:59:67:b6:c4:06:7d:0a:9e:74: - 85:d6:79:4c:80:37:7a:df:39:05:52:59:f7:f4:1b: - 46:43:a4:d2:85:85:d2:c3:71:f3:75:62:34:ba:2c: - 8a:7f:1e:8f:ee:ed:34:d0:11:c7:96:cd:52:3d:ba: - 33:d6:dd:4d:de:0b:3b:4a:4b:9f:c2:26:2f:fa:b5: - 16:1c:72:35:77:ca:3c:5d:e6:ca:e1:26:8b:1a:36: - 76:5c:01:db:74:14:25:fe:ed:b5:a0:88:0f:dd:78: - ca:2d:1f:07:97:30:01:2d:72:79:fa:46:d6:13:2a: - a8:b9:a6:ab:83:49:1d:e5:f2:ef:dd:e4:01:8e:18: - 0a:8f:63:53:16:85:62:a9:0e:19:3a:cc:b5:66:a6: - c2:6b:74:07:e4:2b:e1:76:3e:b4:6d:d8:f6:44:e1: - 73:62:1f:3b:c4:be:a0:53:56:25:6c:51:09:f7:aa: - ab:ca:bf:76:fd:6d:9b:f3:9d:db:bf:3d:66:bc:0c: - 56:aa:af:98:48:95:3a:4b:df:a7:58:50:d9:38:75: - a9:5b:ea:43:0c:02:ff:99:eb:e8:6c:4d:70:5b:29: - 65:9c:dd:aa:5d:cc:af:01:31:ec:0c:eb:d2:8d:e8: - ea:9c:7b:e6:6e:f7:27:66:0c:1a:48:d7:6e:42:e3: - 3f:de:21:3e:7b:e1:0d:70:fb:63:aa:a8:6c:1a:54: - b4:5c:25:7a:c9:a2:c9:8b:16:a6:bb:2c:7e:17:5e: - 05:4d:58:6e:12:1d:01:ee:12:10:0d:c6:32:7f:18: - ff:fc:f4:fa:cd:6e:91:e8:36:49:be:1a:48:69:8b: - c2:96:4d:1a:12:b2:69:17:c1:0a:90:d6:fa:79:22: - 48:bf:ba:7b:69:f8:70:c7:fa:7a:37:d8:d8:0d:d2: - 76:4f:57:ff:90:b7:e3:91:d2:dd:ef:c2:60:b7:67: - 3a:dd:fe:aa:9c:f0:d4:8b:7f:72:22:ce:c6:9f:97: - b6:f8:af:8a:a0:10:a8:d9:fb:18:c6:b6:b5:5c:52: - 3c:89:b6:19:2a:73:01:0a:0f:03:b3:12:60:f2:7a: - 2f:81:db:a3:6e:ff:26:30:97:f5:8b:dd:89:57:b6: - ad:3d:b3:af:2b:c5:b7:76:02:f0:a5:d6:2b:9a:86: - 14:2a:72:f6:e3:33:8c:5d:09:4b:13:df:bb:8c:74: - 13:52:4b - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Basic Constraints: critical - CA:TRUE - X509v3 Key Usage: critical - Certificate Sign, CRL Sign - X509v3 Subject Key Identifier: - 4E:0B:EF:1A:A4:40:5B:A5:17:69:87:30:CA:34:68:43:D0:41:AE:F2 - X509v3 Authority Key Identifier: - keyid:4E:0B:EF:1A:A4:40:5B:A5:17:69:87:30:CA:34:68:43:D0:41:AE:F2 - - X509v3 Certificate Policies: - Policy: 1.3.6.1.4.1.23223.1.1.1 - CPS: http://www.startssl.com/policy.pdf - CPS: http://www.startssl.com/intermediate.pdf - User Notice: - Organization: Start Commercial (StartCom) Ltd. - Number: 1 - Explicit Text: Limited Liability, read the section *Legal Limitations* of the StartCom Certification Authority Policy available at http://www.startssl.com/policy.pdf - - Netscape Cert Type: - SSL CA, S/MIME CA, Object Signing CA - Netscape Comment: - StartCom Free SSL Certification Authority - Signature Algorithm: sha256WithRSAEncryption - 8e:8f:e7:dc:94:79:7c:f1:85:7f:9f:49:6f:6b:ca:5d:fb:8c: - fe:04:c5:c1:62:d1:7d:42:8a:bc:53:b7:94:03:66:30:3f:b1: - e7:0a:a7:50:20:55:25:7f:76:7a:14:0d:eb:04:0e:40:e6:3e: - d8:88:ab:07:27:83:a9:75:a6:37:73:c7:fd:4b:d2:4d:ad:17: - 40:c8:46:be:3b:7f:51:fc:c3:b6:05:31:dc:cd:85:22:4e:71: - b7:f2:71:5e:b0:1a:c6:ba:93:8b:78:92:4a:85:f8:78:0f:83: - fe:2f:ad:2c:f7:e4:a4:bb:2d:d0:e7:0d:3a:b8:3e:ce:f6:78: - f6:ae:47:24:ca:a3:35:36:ce:c7:c6:87:98:da:ec:fb:e9:b2: - ce:27:9b:88:c3:04:a1:f6:0b:59:68:af:c9:db:10:0f:4d:f6: - 64:63:5c:a5:12:6f:92:b2:93:94:c7:88:17:0e:93:b6:7e:62: - 8b:90:7f:ab:4e:9f:fc:e3:75:14:4f:2a:32:df:5b:0d:e0:f5: - 7b:93:0d:ab:a1:cf:87:e1:a5:04:45:e8:3c:12:a5:09:c5:b0: - d1:b7:53:f3:60:14:ba:85:69:6a:21:7c:1f:75:61:17:20:17: - 7b:6c:3b:41:29:5c:e1:ac:5a:d1:cd:8c:9b:eb:60:1d:19:ec: - f7:e5:b0:da:f9:79:18:a5:45:3f:49:43:57:d2:dd:24:d5:2c: - a3:fd:91:8d:27:b5:e5:eb:14:06:9a:4c:7b:21:bb:3a:ad:30: - 06:18:c0:d8:c1:6b:2c:7f:59:5c:5d:91:b1:70:22:57:eb:8a: - 6b:48:4a:d5:0f:29:ec:c6:40:c0:2f:88:4c:68:01:17:77:f4: - 24:19:4f:bd:fa:e1:b2:20:21:4b:dd:1a:d8:29:7d:aa:b8:de: - 54:ec:21:55:80:6c:1e:f5:30:c8:a3:10:e5:b2:e6:2a:14:31: - c3:85:2d:8c:98:b1:86:5a:4f:89:59:2d:b9:c7:f7:1c:c8:8a: - 7f:c0:9d:05:4a:e6:42:4f:62:a3:6d:29:a4:1f:85:ab:db:e5: - 81:c8:ad:2a:3d:4c:5d:5b:84:26:71:c4:85:5e:71:24:ca:a5: - 1b:6c:d8:61:d3:1a:e0:54:db:ce:ba:a9:32:b5:22:f6:73:41: - 09:5d:b8:17:5d:0e:0f:99:90:d6:47:da:6f:0a:3a:62:28:14: - 67:82:d9:f1:d0:80:59:9b:cb:31:d8:9b:0f:8c:77:4e:b5:68: - 8a:f2:6c:f6:24:0e:2d:6c:70:c5:73:d1:de:14:d0:71:8f:b6: - d3:7b:02:f6:e3:b8:d4:09:6e:6b:9e:75:84:39:e6:7f:25:a5: - f2:48:00:c0:a4:01:da:3f ------BEGIN CERTIFICATE----- -MIIHhzCCBW+gAwIBAgIBLTANBgkqhkiG9w0BAQsFADB9MQswCQYDVQQGEwJJTDEW -MBQGA1UEChMNU3RhcnRDb20gTHRkLjErMCkGA1UECxMiU2VjdXJlIERpZ2l0YWwg -Q2VydGlmaWNhdGUgU2lnbmluZzEpMCcGA1UEAxMgU3RhcnRDb20gQ2VydGlmaWNh -dGlvbiBBdXRob3JpdHkwHhcNMDYwOTE3MTk0NjM3WhcNMzYwOTE3MTk0NjM2WjB9 -MQswCQYDVQQGEwJJTDEWMBQGA1UEChMNU3RhcnRDb20gTHRkLjErMCkGA1UECxMi -U2VjdXJlIERpZ2l0YWwgQ2VydGlmaWNhdGUgU2lnbmluZzEpMCcGA1UEAxMgU3Rh -cnRDb20gQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwggIiMA0GCSqGSIb3DQEBAQUA -A4ICDwAwggIKAoICAQDBiNsJvGxGfHiflXu1M5DycmLWwTYgIiRezul38kMKogZk -pMyONvg45iPwbm2xPN1yo4UcodM9tDMr0y+v/uqwQVlntsQGfQqedIXWeUyAN3rf -OQVSWff0G0ZDpNKFhdLDcfN1YjS6LIp/Ho/u7TTQEceWzVI9ujPW3U3eCztKS5/C -Ji/6tRYccjV3yjxd5srhJosaNnZcAdt0FCX+7bWgiA/deMotHweXMAEtcnn6RtYT -Kqi5pquDSR3l8u/d5AGOGAqPY1MWhWKpDhk6zLVmpsJrdAfkK+F2PrRt2PZE4XNi -HzvEvqBTViVsUQn3qqvKv3b9bZvzndu/PWa8DFaqr5hIlTpL36dYUNk4dalb6kMM -Av+Z6+hsTXBbKWWc3apdzK8BMewM69KN6Oqce+Zu9ydmDBpI125C4z/eIT574Q1w -+2OqqGwaVLRcJXrJosmLFqa7LH4XXgVNWG4SHQHuEhANxjJ/GP/89PrNbpHoNkm+ -Gkhpi8KWTRoSsmkXwQqQ1vp5Iki/untp+HDH+no32NgN0nZPV/+Qt+OR0t3vwmC3 -Zzrd/qqc8NSLf3Iizsafl7b4r4qgEKjZ+xjGtrVcUjyJthkqcwEKDwOzEmDyei+B -26Nu/yYwl/WL3YlXtq09s68rxbd2AvCl1iuahhQqcvbjM4xdCUsT37uMdBNSSwID -AQABo4ICEDCCAgwwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwHQYD -VR0OBBYEFE4L7xqkQFulF2mHMMo0aEPQQa7yMB8GA1UdIwQYMBaAFE4L7xqkQFul -F2mHMMo0aEPQQa7yMIIBWgYDVR0gBIIBUTCCAU0wggFJBgsrBgEEAYG1NwEBATCC -ATgwLgYIKwYBBQUHAgEWImh0dHA6Ly93d3cuc3RhcnRzc2wuY29tL3BvbGljeS5w -ZGYwNAYIKwYBBQUHAgEWKGh0dHA6Ly93d3cuc3RhcnRzc2wuY29tL2ludGVybWVk -aWF0ZS5wZGYwgc8GCCsGAQUFBwICMIHCMCcWIFN0YXJ0IENvbW1lcmNpYWwgKFN0 -YXJ0Q29tKSBMdGQuMAMCAQEagZZMaW1pdGVkIExpYWJpbGl0eSwgcmVhZCB0aGUg -c2VjdGlvbiAqTGVnYWwgTGltaXRhdGlvbnMqIG9mIHRoZSBTdGFydENvbSBDZXJ0 -aWZpY2F0aW9uIEF1dGhvcml0eSBQb2xpY3kgYXZhaWxhYmxlIGF0IGh0dHA6Ly93 -d3cuc3RhcnRzc2wuY29tL3BvbGljeS5wZGYwEQYJYIZIAYb4QgEBBAQDAgAHMDgG -CWCGSAGG+EIBDQQrFilTdGFydENvbSBGcmVlIFNTTCBDZXJ0aWZpY2F0aW9uIEF1 -dGhvcml0eTANBgkqhkiG9w0BAQsFAAOCAgEAjo/n3JR5fPGFf59Jb2vKXfuM/gTF -wWLRfUKKvFO3lANmMD+x5wqnUCBVJX92ehQN6wQOQOY+2IirByeDqXWmN3PH/UvS -Ta0XQMhGvjt/UfzDtgUx3M2FIk5xt/JxXrAaxrqTi3iSSoX4eA+D/i+tLPfkpLst -0OcNOrg+zvZ49q5HJMqjNTbOx8aHmNrs++myziebiMMEofYLWWivydsQD032ZGNc -pRJvkrKTlMeIFw6Ttn5ii5B/q06f/ON1FE8qMt9bDeD1e5MNq6HPh+GlBEXoPBKl -CcWw0bdT82AUuoVpaiF8H3VhFyAXe2w7QSlc4axa0c2Mm+tgHRns9+Ww2vl5GKVF -P0lDV9LdJNUso/2RjSe15esUBppMeyG7Oq0wBhjA2MFrLH9ZXF2RsXAiV+uKa0hK -1Q8p7MZAwC+ITGgBF3f0JBlPvfrhsiAhS90a2Cl9qrjeVOwhVYBsHvUwyKMQ5bLm -KhQxw4UtjJixhlpPiVktucf3HMiKf8CdBUrmQk9io20ppB+Fq9vlgcitKj1MXVuE -JnHEhV5xJMqlG2zYYdMa4FTbzrqpMrUi9nNBCV24F10OD5mQ1kfabwo6YigUZ4LZ -8dCAWZvLMdibD4x3TrVoivJs9iQOLWxwxXPR3hTQcY+203sC9uO41Alua551hDnm -fyWl8kgAwKQB2j8= ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: 59 (0x3b) - Signature Algorithm: sha256WithRSAEncryption - Issuer: C=IL, O=StartCom Ltd., CN=StartCom Certification Authority G2 - Validity - Not Before: Jan 1 01:00:01 2010 GMT - Not After : Dec 31 23:59:01 2039 GMT - Subject: C=IL, O=StartCom Ltd., CN=StartCom Certification Authority G2 - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (4096 bit) - Modulus: - 00:b6:89:36:5b:07:b7:20:36:bd:82:bb:e1:16:20: - 03:95:7a:af:0e:a3:55:c9:25:99:4a:c5:d0:56:41: - 87:90:4d:21:60:a4:14:87:3b:cd:fd:b2:3e:b4:67: - 03:6a:ed:e1:0f:4b:c0:91:85:70:45:e0:42:9e:de: - 29:23:d4:01:0d:a0:10:79:b8:db:03:bd:f3:a9:2f: - d1:c6:e0:0f:cb:9e:8a:14:0a:b8:bd:f6:56:62:f1: - c5:72:b6:32:25:d9:b2:f3:bd:65:c5:0d:2c:6e:d5: - 92:6f:18:8b:00:41:14:82:6f:40:20:26:7a:28:0f: - f5:1e:7f:27:f7:94:b1:37:3d:b7:c7:91:f7:e2:01: - ec:fd:94:89:e1:cc:6e:d3:36:d6:0a:19:79:ae:d7: - 34:82:65:ff:7c:42:bb:b6:dd:0b:a6:34:af:4b:60: - fe:7f:43:49:06:8b:8c:43:b8:56:f2:d9:7f:21:43: - 17:ea:a7:48:95:01:75:75:ea:2b:a5:43:95:ea:15: - 84:9d:08:8d:26:6e:55:9b:ab:dc:d2:39:d2:31:1d: - 60:e2:ac:cc:56:45:24:f5:1c:54:ab:ee:86:dd:96: - 32:85:f8:4c:4f:e8:95:76:b6:05:dd:36:23:67:bc: - ff:15:e2:ca:3b:e6:a6:ec:3b:ec:26:11:34:48:8d: - f6:80:2b:1a:23:02:eb:8a:1c:3a:76:2a:7b:56:16: - 1c:72:2a:b3:aa:e3:60:a5:00:9f:04:9b:e2:6f:1e: - 14:58:5b:a5:6c:8b:58:3c:c3:ba:4e:3a:5c:f7:e1: - 96:2b:3e:ef:07:bc:a4:e5:5d:cc:4d:9f:0d:e1:dc: - aa:bb:e1:6e:1a:ec:8f:e1:b6:4c:4d:79:72:5d:17: - 35:0b:1d:d7:c1:47:da:96:24:e0:d0:72:a8:5a:5f: - 66:2d:10:dc:2f:2a:13:ae:26:fe:0a:1c:19:cc:d0: - 3e:0b:9c:c8:09:2e:f9:5b:96:7a:47:9c:e9:7a:f3: - 05:50:74:95:73:9e:30:09:f3:97:82:5e:e6:8f:39: - 08:1e:59:e5:35:14:42:13:ff:00:9c:f7:be:aa:50: - cf:e2:51:48:d7:b8:6f:af:f8:4e:7e:33:98:92:14: - 62:3a:75:63:cf:7b:fa:de:82:3b:a9:bb:39:e2:c4: - bd:2c:00:0e:c8:17:ac:13:ef:4d:25:8e:d8:b3:90: - 2f:a9:da:29:7d:1d:af:74:3a:b2:27:c0:c1:1e:3e: - 75:a3:16:a9:af:7a:22:5d:9f:13:1a:cf:a7:a0:eb: - e3:86:0a:d3:fd:e6:96:95:d7:23:c8:37:dd:c4:7c: - aa:36:ac:98:1a:12:b1:e0:4e:e8:b1:3b:f5:d6:6f: - f1:30:d7 - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Basic Constraints: critical - CA:TRUE - X509v3 Key Usage: critical - Certificate Sign, CRL Sign - X509v3 Subject Key Identifier: - 4B:C5:B4:40:6B:AD:1C:B3:A5:1C:65:6E:46:36:89:87:05:0C:0E:B6 - Signature Algorithm: sha256WithRSAEncryption - 73:57:3f:2c:d5:95:32:7e:37:db:96:92:eb:19:5e:7e:53:e7: - 41:ec:11:b6:47:ef:b5:de:ed:74:5c:c5:f1:8e:49:e0:fc:6e: - 99:13:cd:9f:8a:da:cd:3a:0a:d8:3a:5a:09:3f:5f:34:d0:2f: - 03:d2:66:1d:1a:bd:9c:90:37:c8:0c:8e:07:5a:94:45:46:2a: - e6:be:7a:da:a1:a9:a4:69:12:92:b0:7d:36:d4:44:87:d7:51: - f1:29:63:d6:75:cd:16:e4:27:89:1d:f8:c2:32:48:fd:db:99: - d0:8f:5f:54:74:cc:ac:67:34:11:62:d9:0c:0a:37:87:d1:a3: - 17:48:8e:d2:17:1d:f6:d7:fd:db:65:eb:fd:a8:d4:f5:d6:4f: - a4:5b:75:e8:c5:d2:60:b2:db:09:7e:25:8b:7b:ba:52:92:9e: - 3e:e8:c5:77:a1:3c:e0:4a:73:6b:61:cf:86:dc:43:ff:ff:21: - fe:23:5d:24:4a:f5:d3:6d:0f:62:04:05:57:82:da:6e:a4:33: - 25:79:4b:2e:54:19:8b:cc:2c:3d:30:e9:d1:06:ff:e8:32:46: - be:b5:33:76:77:a8:01:5d:96:c1:c1:d5:be:ae:25:c0:c9:1e: - 0a:09:20:88:a1:0e:c9:f3:6f:4d:82:54:00:20:a7:d2:8f:e4: - 39:54:17:2e:8d:1e:b8:1b:bb:1b:bd:9a:4e:3b:10:34:dc:9c: - 88:53:ef:a2:31:5b:58:4f:91:62:c8:c2:9a:9a:cd:15:5d:38: - a9:d6:be:f8:13:b5:9f:12:69:f2:50:62:ac:fb:17:37:f4:ee: - b8:75:67:60:10:fb:83:50:f9:44:b5:75:9c:40:17:b2:fe:fd: - 79:5d:6e:58:58:5f:30:fc:00:ae:af:33:c1:0e:4e:6c:ba:a7: - a6:a1:7f:32:db:38:e0:b1:72:17:0a:2b:91:ec:6a:63:26:ed: - 89:d4:78:cc:74:1e:05:f8:6b:fe:8c:6a:76:39:29:ae:65:23: - 12:95:08:22:1c:97:ce:5b:06:ee:0c:e2:bb:bc:1f:44:93:f6: - d8:38:45:05:21:ed:e4:ad:ab:12:b6:03:a4:42:2e:2d:c4:09: - 3a:03:67:69:84:9a:e1:59:90:8a:28:85:d5:5d:74:b1:d1:0e: - 20:58:9b:13:a5:b0:63:a6:ed:7b:47:fd:45:55:30:a4:ee:9a: - d4:e6:e2:87:ef:98:c9:32:82:11:29:22:bc:00:0a:31:5e:2d: - 0f:c0:8e:e9:6b:b2:8f:2e:06:d8:d1:91:c7:c6:12:f4:4c:fd: - 30:17:c3:c1:da:38:5b:e3:a9:ea:e6:a1:ba:79:ef:73:d8:b6: - 53:57:2d:f6:d0:e1:d7:48 ------BEGIN CERTIFICATE----- -MIIFYzCCA0ugAwIBAgIBOzANBgkqhkiG9w0BAQsFADBTMQswCQYDVQQGEwJJTDEW -MBQGA1UEChMNU3RhcnRDb20gTHRkLjEsMCoGA1UEAxMjU3RhcnRDb20gQ2VydGlm -aWNhdGlvbiBBdXRob3JpdHkgRzIwHhcNMTAwMTAxMDEwMDAxWhcNMzkxMjMxMjM1 -OTAxWjBTMQswCQYDVQQGEwJJTDEWMBQGA1UEChMNU3RhcnRDb20gTHRkLjEsMCoG -A1UEAxMjU3RhcnRDb20gQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkgRzIwggIiMA0G -CSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQC2iTZbB7cgNr2Cu+EWIAOVeq8Oo1XJ -JZlKxdBWQYeQTSFgpBSHO839sj60ZwNq7eEPS8CRhXBF4EKe3ikj1AENoBB5uNsD -vfOpL9HG4A/LnooUCri99lZi8cVytjIl2bLzvWXFDSxu1ZJvGIsAQRSCb0AgJnoo -D/Uefyf3lLE3PbfHkffiAez9lInhzG7TNtYKGXmu1zSCZf98Qru23QumNK9LYP5/ -Q0kGi4xDuFby2X8hQxfqp0iVAXV16iulQ5XqFYSdCI0mblWbq9zSOdIxHWDirMxW -RST1HFSr7obdljKF+ExP6JV2tgXdNiNnvP8V4so75qbsO+wmETRIjfaAKxojAuuK -HDp2KntWFhxyKrOq42ClAJ8Em+JvHhRYW6Vsi1g8w7pOOlz34ZYrPu8HvKTlXcxN -nw3h3Kq74W4a7I/htkxNeXJdFzULHdfBR9qWJODQcqhaX2YtENwvKhOuJv4KHBnM -0D4LnMgJLvlblnpHnOl68wVQdJVznjAJ85eCXuaPOQgeWeU1FEIT/wCc976qUM/i -UUjXuG+v+E5+M5iSFGI6dWPPe/regjupuznixL0sAA7IF6wT700ljtizkC+p2il9 -Ha90OrInwMEePnWjFqmveiJdnxMaz6eg6+OGCtP95paV1yPIN93EfKo2rJgaErHg -TuixO/XWb/Ew1wIDAQABo0IwQDAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQE -AwIBBjAdBgNVHQ4EFgQUS8W0QGutHLOlHGVuRjaJhwUMDrYwDQYJKoZIhvcNAQEL -BQADggIBAHNXPyzVlTJ+N9uWkusZXn5T50HsEbZH77Xe7XRcxfGOSeD8bpkTzZ+K -2s06Ctg6Wgk/XzTQLwPSZh0avZyQN8gMjgdalEVGKua+etqhqaRpEpKwfTbURIfX -UfEpY9Z1zRbkJ4kd+MIySP3bmdCPX1R0zKxnNBFi2QwKN4fRoxdIjtIXHfbX/dtl -6/2o1PXWT6RbdejF0mCy2wl+JYt7ulKSnj7oxXehPOBKc2thz4bcQ///If4jXSRK -9dNtD2IEBVeC2m6kMyV5Sy5UGYvMLD0w6dEG/+gyRr61M3Z3qAFdlsHB1b6uJcDJ -HgoJIIihDsnzb02CVAAgp9KP5DlUFy6NHrgbuxu9mk47EDTcnIhT76IxW1hPkWLI -wpqazRVdOKnWvvgTtZ8SafJQYqz7Fzf07rh1Z2AQ+4NQ+US1dZxAF7L+/XldblhY -XzD8AK6vM8EOTmy6p6ahfzLbOOCxchcKK5HsamMm7YnUeMx0HgX4a/6ManY5Ka5l -IxKVCCIcl85bBu4M4ru8H0ST9tg4RQUh7eStqxK2A6RCLi3ECToDZ2mEmuFZkIoo -hdVddLHRDiBYmxOlsGOm7XtH/UVVMKTumtTm4ofvmMkyghEpIrwACjFeLQ/Ajulr -so8uBtjRkcfGEvRM/TAXw8HaOFvjqermobp573PYtlNXLfbQ4ddI ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: - bb:40:1c:43:f5:5e:4f:b0 - Signature Algorithm: sha1WithRSAEncryption - Issuer: C=CH, O=SwissSign AG, CN=SwissSign Gold CA - G2 - Validity - Not Before: Oct 25 08:30:35 2006 GMT - Not After : Oct 25 08:30:35 2036 GMT - Subject: C=CH, O=SwissSign AG, CN=SwissSign Gold CA - G2 - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (4096 bit) - Modulus: - 00:af:e4:ee:7e:8b:24:0e:12:6e:a9:50:2d:16:44: - 3b:92:92:5c:ca:b8:5d:84:92:42:13:2a:bc:65:57: - 82:40:3e:57:24:cd:50:8b:25:2a:b7:6f:fc:ef:a2: - d0:c0:1f:02:24:4a:13:96:8f:23:13:e6:28:58:00: - a3:47:c7:06:a7:84:23:2b:bb:bd:96:2b:7f:55:cc: - 8b:c1:57:1f:0e:62:65:0f:dd:3d:56:8a:73:da:ae: - 7e:6d:ba:81:1c:7e:42:8c:20:35:d9:43:4d:84:fa: - 84:db:52:2c:f3:0e:27:77:0b:6b:bf:11:2f:72:78: - 9f:2e:d8:3e:e6:18:37:5a:2a:72:f9:da:62:90:92: - 95:ca:1f:9c:e9:b3:3c:2b:cb:f3:01:13:bf:5a:cf: - c1:b5:0a:60:bd:dd:b5:99:64:53:b8:a0:96:b3:6f: - e2:26:77:91:8c:e0:62:10:02:9f:34:0f:a4:d5:92: - 33:51:de:be:8d:ba:84:7a:60:3c:6a:db:9f:2b:ec: - de:de:01:3f:6e:4d:e5:50:86:cb:b4:af:ed:44:40: - c5:ca:5a:8c:da:d2:2b:7c:a8:ee:be:a6:e5:0a:aa: - 0e:a5:df:05:52:b7:55:c7:22:5d:32:6a:97:97:63: - 13:db:c9:db:79:36:7b:85:3a:4a:c5:52:89:f9:24: - e7:9d:77:a9:82:ff:55:1c:a5:71:69:2b:d1:02:24: - f2:b3:26:d4:6b:da:04:55:e5:c1:0a:c7:6d:30:37: - 90:2a:e4:9e:14:33:5e:16:17:55:c5:5b:b5:cb:34: - 89:92:f1:9d:26:8f:a1:07:d4:c6:b2:78:50:db:0c: - 0c:0b:7c:0b:8c:41:d7:b9:e9:dd:8c:88:f7:a3:4d: - b2:32:cc:d8:17:da:cd:b7:ce:66:9d:d4:fd:5e:ff: - bd:97:3e:29:75:e7:7e:a7:62:58:af:25:34:a5:41: - c7:3d:bc:0d:50:ca:03:03:0f:08:5a:1f:95:73:78: - 62:bf:af:72:14:69:0e:a5:e5:03:0e:78:8e:26:28: - 42:f0:07:0b:62:20:10:67:39:46:fa:a9:03:cc:04: - 38:7a:66:ef:20:83:b5:8c:4a:56:8e:91:00:fc:8e: - 5c:82:de:88:a0:c3:e2:68:6e:7d:8d:ef:3c:dd:65: - f4:5d:ac:51:ef:24:80:ae:aa:56:97:6f:f9:ad:7d: - da:61:3f:98:77:3c:a5:91:b6:1c:8c:26:da:65:a2: - 09:6d:c1:e2:54:e3:b9:ca:4c:4c:80:8f:77:7b:60: - 9a:1e:df:b6:f2:48:1e:0e:ba:4e:54:6d:98:e0:e1: - a2:1a:a2:77:50:cf:c4:63:92:ec:47:19:9d:eb:e6: - 6b:ce:c1 - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Key Usage: critical - Certificate Sign, CRL Sign - X509v3 Basic Constraints: critical - CA:TRUE - X509v3 Subject Key Identifier: - 5B:25:7B:96:A4:65:51:7E:B8:39:F3:C0:78:66:5E:E8:3A:E7:F0:EE - X509v3 Authority Key Identifier: - keyid:5B:25:7B:96:A4:65:51:7E:B8:39:F3:C0:78:66:5E:E8:3A:E7:F0:EE - - X509v3 Certificate Policies: - Policy: 2.16.756.1.89.1.2.1.1 - CPS: http://repository.swisssign.com/ - - Signature Algorithm: sha1WithRSAEncryption - 27:ba:e3:94:7c:f1:ae:c0:de:17:e6:e5:d8:d5:f5:54:b0:83: - f4:bb:cd:5e:05:7b:4f:9f:75:66:af:3c:e8:56:7e:fc:72:78: - 38:03:d9:2b:62:1b:00:b9:f8:e9:60:cd:cc:ce:51:8a:c7:50: - 31:6e:e1:4a:7e:18:2f:69:59:b6:3d:64:81:2b:e3:83:84:e6: - 22:87:8e:7d:e0:ee:02:99:61:b8:1e:f4:b8:2b:88:12:16:84: - c2:31:93:38:96:31:a6:b9:3b:53:3f:c3:24:93:56:5b:69:92: - ec:c5:c1:bb:38:00:e3:ec:17:a9:b8:dc:c7:7c:01:83:9f:32: - 47:ba:52:22:34:1d:32:7a:09:56:a7:7c:25:36:a9:3d:4b:da: - c0:82:6f:0a:bb:12:c8:87:4b:27:11:f9:1e:2d:c7:93:3f:9e: - db:5f:26:6b:52:d9:2e:8a:f1:14:c6:44:8d:15:a9:b7:bf:bd: - de:a6:1a:ee:ae:2d:fb:48:77:17:fe:bb:ec:af:18:f5:2a:51: - f0:39:84:97:95:6c:6e:1b:c3:2b:c4:74:60:79:25:b0:0a:27: - df:df:5e:d2:39:cf:45:7d:42:4b:df:b3:2c:1e:c5:c6:5d:ca: - 55:3a:a0:9c:69:9a:8f:da:ef:b2:b0:3c:9f:87:6c:12:2b:65: - 70:15:52:31:1a:24:cf:6f:31:23:50:1f:8c:4f:8f:23:c3:74: - 41:63:1c:55:a8:14:dd:3e:e0:51:50:cf:f1:1b:30:56:0e:92: - b0:82:85:d8:83:cb:22:64:bc:2d:b8:25:d5:54:a2:b8:06:ea: - ad:92:a4:24:a0:c1:86:b5:4a:13:6a:47:cf:2e:0b:56:95:54: - cb:ce:9a:db:6a:b4:a6:b2:db:41:08:86:27:77:f7:6a:a0:42: - 6c:0b:38:ce:d7:75:50:32:92:c2:df:2b:30:22:48:d0:d5:41: - 38:25:5d:a4:e9:5d:9f:c6:94:75:d0:45:fd:30:97:43:8f:90: - ab:0a:c7:86:73:60:4a:69:2d:de:a5:78:d7:06:da:6a:9e:4b: - 3e:77:3a:20:13:22:01:d0:bf:68:9e:63:60:6b:35:4d:0b:6d: - ba:a1:3d:c0:93:e0:7f:23:b3:55:ad:72:25:4e:46:f9:d2:16: - ef:b0:64:c1:01:9e:e9:ca:a0:6a:98:0e:cf:d8:60:f2:2f:49: - b8:e4:42:e1:38:35:16:f4:c8:6e:4f:f7:81:56:e8:ba:a3:be: - 23:af:ae:fd:6f:03:e0:02:3b:30:76:fa:1b:6d:41:cf:01:b1: - e9:b8:c9:66:f4:db:26:f3:3a:a4:74:f2:49:24:5b:c9:b0:d0: - 57:c1:fa:3e:7a:e1:97:c9 ------BEGIN CERTIFICATE----- -MIIFujCCA6KgAwIBAgIJALtAHEP1Xk+wMA0GCSqGSIb3DQEBBQUAMEUxCzAJBgNV -BAYTAkNIMRUwEwYDVQQKEwxTd2lzc1NpZ24gQUcxHzAdBgNVBAMTFlN3aXNzU2ln -biBHb2xkIENBIC0gRzIwHhcNMDYxMDI1MDgzMDM1WhcNMzYxMDI1MDgzMDM1WjBF -MQswCQYDVQQGEwJDSDEVMBMGA1UEChMMU3dpc3NTaWduIEFHMR8wHQYDVQQDExZT -d2lzc1NpZ24gR29sZCBDQSAtIEcyMIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIIC -CgKCAgEAr+TufoskDhJuqVAtFkQ7kpJcyrhdhJJCEyq8ZVeCQD5XJM1QiyUqt2/8 -76LQwB8CJEoTlo8jE+YoWACjR8cGp4QjK7u9lit/VcyLwVcfDmJlD909Vopz2q5+ -bbqBHH5CjCA12UNNhPqE21Is8w4ndwtrvxEvcnifLtg+5hg3Wipy+dpikJKVyh+c -6bM8K8vzARO/Ws/BtQpgvd21mWRTuKCWs2/iJneRjOBiEAKfNA+k1ZIzUd6+jbqE -emA8atufK+ze3gE/bk3lUIbLtK/tREDFylqM2tIrfKjuvqblCqoOpd8FUrdVxyJd -MmqXl2MT28nbeTZ7hTpKxVKJ+STnnXepgv9VHKVxaSvRAiTysybUa9oEVeXBCsdt -MDeQKuSeFDNeFhdVxVu1yzSJkvGdJo+hB9TGsnhQ2wwMC3wLjEHXuendjIj3o02y -MszYF9rNt85mndT9Xv+9lz4pded+p2JYryU0pUHHPbwNUMoDAw8IWh+Vc3hiv69y -FGkOpeUDDniOJihC8AcLYiAQZzlG+qkDzAQ4embvIIO1jEpWjpEA/I5cgt6IoMPi -aG59je883WX0XaxR7ySArqpWl2/5rX3aYT+YdzylkbYcjCbaZaIJbcHiVOO5ykxM -gI93e2CaHt+28kgeDrpOVG2Y4OGiGqJ3UM/EY5LsRxmd6+ZrzsECAwEAAaOBrDCB -qTAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUWyV7 -lqRlUX64OfPAeGZe6Drn8O4wHwYDVR0jBBgwFoAUWyV7lqRlUX64OfPAeGZe6Drn -8O4wRgYDVR0gBD8wPTA7BglghXQBWQECAQEwLjAsBggrBgEFBQcCARYgaHR0cDov -L3JlcG9zaXRvcnkuc3dpc3NzaWduLmNvbS8wDQYJKoZIhvcNAQEFBQADggIBACe6 -45R88a7A3hfm5djV9VSwg/S7zV4Fe0+fdWavPOhWfvxyeDgD2StiGwC5+OlgzczO -UYrHUDFu4Up+GC9pWbY9ZIEr44OE5iKHjn3g7gKZYbge9LgriBIWhMIxkziWMaa5 -O1M/wySTVltpkuzFwbs4AOPsF6m43Md8AYOfMke6UiI0HTJ6CVanfCU2qT1L2sCC -bwq7EsiHSycR+R4tx5M/nttfJmtS2S6K8RTGRI0Vqbe/vd6mGu6uLftIdxf+u+yv -GPUqUfA5hJeVbG4bwyvEdGB5JbAKJ9/fXtI5z0V9QkvfsywexcZdylU6oJxpmo/a -77KwPJ+HbBIrZXAVUjEaJM9vMSNQH4xPjyPDdEFjHFWoFN0+4FFQz/EbMFYOkrCC -hdiDyyJkvC24JdVUorgG6q2SpCSgwYa1ShNqR88uC1aVVMvOmttqtKay20EIhid3 -92qgQmwLOM7XdVAyksLfKzAiSNDVQTglXaTpXZ/GlHXQRf0wl0OPkKsKx4ZzYEpp -Ld6leNcG2mqeSz53OiATIgHQv2ieY2BrNU0LbbqhPcCT4H8js1WtciVORvnSFu+w -ZMEBnunKoGqYDs/YYPIvSbjkQuE4NRb0yG5P94FW6LqjviOvrv1vA+ACOzB2+htt -Qc8Bsem4yWb02ybzOqR08kkkW8mw0FfB+j564ZfJ ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: - 4f:1b:d4:2f:54:bb:2f:4b - Signature Algorithm: sha1WithRSAEncryption - Issuer: C=CH, O=SwissSign AG, CN=SwissSign Silver CA - G2 - Validity - Not Before: Oct 25 08:32:46 2006 GMT - Not After : Oct 25 08:32:46 2036 GMT - Subject: C=CH, O=SwissSign AG, CN=SwissSign Silver CA - G2 - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (4096 bit) - Modulus: - 00:c4:f1:87:7f:d3:78:31:f7:38:c9:f8:c3:99:43: - bc:c7:f7:bc:37:e7:4e:71:ba:4b:8f:a5:73:1d:5c: - 6e:98:ae:03:57:ae:38:37:43:2f:17:3d:1f:c8:ce: - 68:10:c1:78:ae:19:03:2b:10:fa:2c:79:83:f6:e8: - b9:68:b9:55:f2:04:44:a7:39:f9:fc:04:8b:1e:f1: - a2:4d:27:f9:61:7b:ba:b7:e5:a2:13:b6:eb:61:3e: - d0:6c:d1:e6:fb:fa:5e:ed:1d:b4:9e:a0:35:5b:a1: - 92:cb:f0:49:92:fe:85:0a:05:3e:e6:d9:0b:e2:4f: - bb:dc:95:37:fc:91:e9:32:35:22:d1:1f:3a:4e:27: - 85:9d:b0:15:94:32:da:61:0d:47:4d:60:42:ae:92: - 47:e8:83:5a:50:58:e9:8a:8b:b9:5d:a1:dc:dd:99: - 4a:1f:36:67:bb:48:e4:83:b6:37:eb:48:3a:af:0f: - 67:8f:17:07:e8:04:ca:ef:6a:31:87:d4:c0:b6:f9: - 94:71:7b:67:64:b8:b6:91:4a:42:7b:65:2e:30:6a: - 0c:f5:90:ee:95:e6:f2:cd:82:ec:d9:a1:4a:ec:f6: - b2:4b:e5:45:85:e6:6d:78:93:04:2e:9c:82:6d:36: - a9:c4:31:64:1f:86:83:0b:2a:f4:35:0a:78:c9:55: - cf:41:b0:47:e9:30:9f:99:be:61:a8:06:84:b9:28: - 7a:5f:38:d9:1b:a9:38:b0:83:7f:73:c1:c3:3b:48: - 2a:82:0f:21:9b:b8:cc:a8:35:c3:84:1b:83:b3:3e: - be:a4:95:69:01:3a:89:00:78:04:d9:c9:f4:99:19: - ab:56:7e:5b:8b:86:39:15:91:a4:10:2c:09:32:80: - 60:b3:93:c0:2a:b6:18:0b:9d:7e:8d:49:f2:10:4a: - 7f:f9:d5:46:2f:19:92:a3:99:a7:26:ac:bb:8c:3c: - e6:0e:bc:47:07:dc:73:51:f1:70:64:2f:08:f9:b4: - 47:1d:30:6c:44:ea:29:37:85:92:68:66:bc:83:38: - fe:7b:39:2e:d3:50:f0:1f:fb:5e:60:b6:a9:a6:fa: - 27:41:f1:9b:18:72:f2:f5:84:74:4a:c9:67:c4:54: - ae:48:64:df:8c:d1:6e:b0:1d:e1:07:8f:08:1e:99: - 9c:71:e9:4c:d8:a5:f7:47:12:1f:74:d1:51:9e:86: - f3:c2:a2:23:40:0b:73:db:4b:a6:e7:73:06:8c:c1: - a0:e9:c1:59:ac:46:fa:e6:2f:f8:cf:71:9c:46:6d: - b9:c4:15:8d:38:79:03:45:48:ef:c4:5d:d7:08:ee: - 87:39:22:86:b2:0d:0f:58:43:f7:71:a9:48:2e:fd: - ea:d6:1f - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Key Usage: critical - Certificate Sign, CRL Sign - X509v3 Basic Constraints: critical - CA:TRUE - X509v3 Subject Key Identifier: - 17:A0:CD:C1:E4:41:B6:3A:5B:3B:CB:45:9D:BD:1C:C2:98:FA:86:58 - X509v3 Authority Key Identifier: - keyid:17:A0:CD:C1:E4:41:B6:3A:5B:3B:CB:45:9D:BD:1C:C2:98:FA:86:58 - - X509v3 Certificate Policies: - Policy: 2.16.756.1.89.1.3.1.1 - CPS: http://repository.swisssign.com/ - - Signature Algorithm: sha1WithRSAEncryption - 73:c6:81:e0:27:d2:2d:0f:e0:95:30:e2:9a:41:7f:50:2c:5f: - 5f:62:61:a9:86:6a:69:18:0c:74:49:d6:5d:84:ea:41:52:18: - 6f:58:ad:50:56:20:6a:c6:bd:28:69:58:91:dc:91:11:35:a9: - 3a:1d:bc:1a:a5:60:9e:d8:1f:7f:45:91:69:d9:7e:bb:78:72: - c1:06:0f:2a:ce:8f:85:70:61:ac:a0:cd:0b:b8:39:29:56:84: - 32:4e:86:bb:3d:c4:2a:d9:d7:1f:72:ee:fe:51:a1:22:41:b1: - 71:02:63:1a:82:b0:62:ab:5e:57:12:1f:df:cb:dd:75:a0:c0: - 5d:79:90:8c:1b:e0:50:e6:de:31:fe:98:7b:70:5f:a5:90:d8: - ad:f8:02:b6:6f:d3:60:dd:40:4b:22:c5:3d:ad:3a:7a:9f:1a: - 1a:47:91:79:33:ba:82:dc:32:69:03:96:6e:1f:4b:f0:71:fe: - e3:67:72:a0:b1:bf:5c:8b:e4:fa:99:22:c7:84:b9:1b:8d:23: - 97:3f:ed:25:e0:cf:65:bb:f5:61:04:ef:dd:1e:b2:5a:41:22: - 5a:a1:9f:5d:2c:e8:5b:c9:6d:a9:0c:0c:78:aa:60:c6:56:8f: - 01:5a:0c:68:bc:69:19:79:c4:1f:7e:97:05:bf:c5:e9:24:51: - 5e:d4:d5:4b:53:ed:d9:23:5a:36:03:65:a3:c1:03:ad:41:30: - f3:46:1b:85:90:af:65:b5:d5:b1:e4:16:5b:78:75:1d:97:7a: - 6d:59:a9:2a:8f:7b:de:c3:87:89:10:99:49:73:78:c8:3d:bd: - 51:35:74:2a:d5:f1:7e:69:1b:2a:bb:3b:bd:25:b8:9a:5a:3d: - 72:61:90:66:87:ee:0c:d6:4d:d4:11:74:0b:6a:fe:0b:03:fc: - a3:55:57:89:fe:4a:cb:ae:5b:17:05:c8:f2:8d:23:31:53:38: - d2:2d:6a:3f:82:b9:8d:08:6a:f7:5e:41:74:6e:c3:11:7e:07: - ac:29:60:91:3f:38:ca:57:10:0d:bd:30:2f:c7:a5:e6:41:a0: - da:ae:05:87:9a:a0:a4:65:6c:4c:09:0c:89:ba:b8:d3:b9:c0: - 93:8a:30:fa:8d:e5:9a:6b:15:01:4e:67:aa:da:62:56:3e:84: - 08:66:d2:c4:36:7d:a7:3e:10:fc:88:e0:d4:80:e5:00:bd:aa: - f3:4e:06:a3:7a:6a:f9:62:72:e3:09:4f:eb:9b:0e:01:23:f1: - 9f:bb:7c:dc:dc:6c:11:97:25:b2:f2:b4:63:14:d2:06:2a:67: - 8c:83:f5:ce:ea:07:d8:9a:6a:1e:ec:e4:0a:bb:2a:4c:eb:09: - 60:39:ce:ca:62:d8:2e:6e ------BEGIN CERTIFICATE----- -MIIFvTCCA6WgAwIBAgIITxvUL1S7L0swDQYJKoZIhvcNAQEFBQAwRzELMAkGA1UE -BhMCQ0gxFTATBgNVBAoTDFN3aXNzU2lnbiBBRzEhMB8GA1UEAxMYU3dpc3NTaWdu -IFNpbHZlciBDQSAtIEcyMB4XDTA2MTAyNTA4MzI0NloXDTM2MTAyNTA4MzI0Nlow -RzELMAkGA1UEBhMCQ0gxFTATBgNVBAoTDFN3aXNzU2lnbiBBRzEhMB8GA1UEAxMY -U3dpc3NTaWduIFNpbHZlciBDQSAtIEcyMIICIjANBgkqhkiG9w0BAQEFAAOCAg8A -MIICCgKCAgEAxPGHf9N4Mfc4yfjDmUO8x/e8N+dOcbpLj6VzHVxumK4DV644N0Mv -Fz0fyM5oEMF4rhkDKxD6LHmD9ui5aLlV8gREpzn5/ASLHvGiTSf5YXu6t+WiE7br -YT7QbNHm+/pe7R20nqA1W6GSy/BJkv6FCgU+5tkL4k+73JU3/JHpMjUi0R86TieF -nbAVlDLaYQ1HTWBCrpJH6INaUFjpiou5XaHc3ZlKHzZnu0jkg7Y360g6rw9njxcH -6ATK72oxh9TAtvmUcXtnZLi2kUpCe2UuMGoM9ZDulebyzYLs2aFK7PayS+VFheZt -eJMELpyCbTapxDFkH4aDCyr0NQp4yVXPQbBH6TCfmb5hqAaEuSh6XzjZG6k4sIN/ -c8HDO0gqgg8hm7jMqDXDhBuDsz6+pJVpATqJAHgE2cn0mRmrVn5bi4Y5FZGkECwJ -MoBgs5PAKrYYC51+jUnyEEp/+dVGLxmSo5mnJqy7jDzmDrxHB9xzUfFwZC8I+bRH -HTBsROopN4WSaGa8gzj+ezku01DwH/teYLappvonQfGbGHLy9YR0SslnxFSuSGTf -jNFusB3hB48IHpmccelM2KX3RxIfdNFRnobzwqIjQAtz20um53MGjMGg6cFZrEb6 -5i/4z3GcRm25xBWNOHkDRUjvxF3XCO6HOSKGsg0PWEP3calILv3q1h8CAwEAAaOB -rDCBqTAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQU -F6DNweRBtjpbO8tFnb0cwpj6hlgwHwYDVR0jBBgwFoAUF6DNweRBtjpbO8tFnb0c -wpj6hlgwRgYDVR0gBD8wPTA7BglghXQBWQEDAQEwLjAsBggrBgEFBQcCARYgaHR0 -cDovL3JlcG9zaXRvcnkuc3dpc3NzaWduLmNvbS8wDQYJKoZIhvcNAQEFBQADggIB -AHPGgeAn0i0P4JUw4ppBf1AsX19iYamGamkYDHRJ1l2E6kFSGG9YrVBWIGrGvShp -WJHckRE1qTodvBqlYJ7YH39FkWnZfrt4csEGDyrOj4VwYaygzQu4OSlWhDJOhrs9 -xCrZ1x9y7v5RoSJBsXECYxqCsGKrXlcSH9/L3XWgwF15kIwb4FDm3jH+mHtwX6WQ -2K34ArZv02DdQEsixT2tOnqfGhpHkXkzuoLcMmkDlm4fS/Bx/uNncqCxv1yL5PqZ -IseEuRuNI5c/7SXgz2W79WEE790eslpBIlqhn10s6FvJbakMDHiqYMZWjwFaDGi8 -aRl5xB9+lwW/xekkUV7U1UtT7dkjWjYDZaPBA61BMPNGG4WQr2W11bHkFlt4dR2X -em1ZqSqPe97Dh4kQmUlzeMg9vVE1dCrV8X5pGyq7O70luJpaPXJhkGaH7gzWTdQR -dAtq/gsD/KNVV4n+SsuuWxcFyPKNIzFTONItaj+CuY0IavdeQXRuwxF+B6wpYJE/ -OMpXEA29MC/HpeZBoNquBYeaoKRlbEwJDIm6uNO5wJOKMPqN5ZprFQFOZ6raYlY+ -hAhm0sQ2fac+EPyI4NSA5QC9qvNOBqN6avlicuMJT+ubDgEj8Z+7fNzcbBGXJbLy -tGMU0gYqZ4yD9c7qB9iaah7s5Aq7KkzrCWA5zspi2C5u ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: - 5c:0b:85:5c:0b:e7:59:41:df:57:cc:3f:7f:9d:a8:36 - Signature Algorithm: sha1WithRSAEncryption - Issuer: C=ch, O=Swisscom, OU=Digital Certificate Services, CN=Swisscom Root CA 1 - Validity - Not Before: Aug 18 12:06:20 2005 GMT - Not After : Aug 18 22:06:20 2025 GMT - Subject: C=ch, O=Swisscom, OU=Digital Certificate Services, CN=Swisscom Root CA 1 - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (4096 bit) - Modulus: - 00:d0:b9:b0:a8:0c:d9:bb:3f:21:f8:1b:d5:33:93: - 80:16:65:20:75:b2:3d:9b:60:6d:46:c8:8c:31:6f: - 17:c3:fa:9a:6c:56:ed:3c:c5:91:57:c3:cd:ab:96: - 49:90:2a:19:4b:1e:a3:6d:57:dd:f1:2b:62:28:75: - 45:5e:aa:d6:5b:fa:0b:25:d8:a1:16:f9:1c:c4:2e: - e6:95:2a:67:cc:d0:29:6e:3c:85:34:38:61:49:b1: - 00:9f:d6:3a:71:5f:4d:6d:ce:5f:b9:a9:e4:89:7f: - 6a:52:fa:ca:9b:f2:dc:a9:f9:9d:99:47:3f:4e:29: - 5f:b4:a6:8d:5d:7b:0b:99:11:03:03:fe:e7:db:db: - a3:ff:1d:a5:cd:90:1e:01:1f:35:b0:7f:00:db:90: - 6f:c6:7e:7b:d1:ee:7a:7a:a7:aa:0c:57:6f:a4:6d: - c5:13:3b:b0:a5:d9:ed:32:1c:b4:5e:67:8b:54:dc: - 73:87:e5:d3:17:7c:66:50:72:5d:d4:1a:58:c1:d9: - cf:d8:89:02:6f:a7:49:b4:36:5d:d0:a4:de:07:2c: - b6:75:b7:28:91:d6:97:be:28:f5:98:1e:ea:5b:26: - c9:bd:b0:97:73:da:ae:91:26:eb:68:c1:f9:39:15: - d6:67:4b:0a:6d:4f:cb:cf:b0:e4:42:71:8c:53:79: - e7:ee:e1:db:1d:a0:6e:1d:8c:1a:77:35:5c:16:1e: - 2b:53:1f:34:8b:d1:6c:fc:f2:67:07:7a:f5:ad:ed: - d6:9a:ab:a1:b1:4b:e1:cc:37:5f:fd:7f:cd:4d:ae: - b8:1f:9c:43:f9:2a:58:55:43:45:bc:96:cd:70:0e: - fc:c9:e3:66:ba:4e:8d:3b:81:cb:15:64:7b:b9:94: - e8:5d:33:52:85:71:2e:4f:8e:a2:06:11:51:c9:e3: - cb:a1:6e:31:08:64:0c:c2:d2:3c:f5:36:e8:d7:d0: - 0e:78:23:20:91:c9:24:2a:65:29:5b:22:f7:21:ce: - 83:5e:a4:f3:de:4b:d3:68:8f:46:75:5c:83:09:6e: - 29:6b:c4:70:8c:f5:9d:d7:20:2f:ff:46:d2:2b:38: - c2:2f:75:1c:3d:7e:da:a5:ef:1e:60:85:69:42:d3: - cc:f8:63:fe:1e:43:39:85:a6:b6:63:41:10:b3:73: - 1e:bc:d3:fa:ca:7d:16:47:e2:a7:d5:d0:a3:8a:0a: - 08:96:62:56:6e:34:db:d9:02:b9:30:75:e3:04:d2: - e7:8f:c2:b0:11:40:0a:ac:d5:71:02:62:8b:31:be: - dd:c6:23:58:31:42:43:2d:74:f9:c6:9e:a6:8a:0f: - e9:fe:bf:83:e6:43:57:24:ba:ef:46:34:aa:d7:12: - 01:38:ed - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Key Usage: critical - Digital Signature, Certificate Sign, CRL Sign - X509v3 Policy Mappings: - 2.16.756.1.83.0.1:2.16.756.1.83.0.1 - X509v3 Basic Constraints: critical - CA:TRUE, pathlen:7 - X509v3 Authority Key Identifier: - keyid:03:25:2F:DE:6F:82:01:3A:5C:2C:DC:2B:A1:69:B5:67:D4:8C:D3:FD - - X509v3 Subject Key Identifier: - 03:25:2F:DE:6F:82:01:3A:5C:2C:DC:2B:A1:69:B5:67:D4:8C:D3:FD - Signature Algorithm: sha1WithRSAEncryption - 35:10:cb:ec:a6:04:0d:0d:0f:cd:c0:db:ab:a8:f2:88:97:0c: - df:93:2f:4d:7c:40:56:31:7a:eb:a4:0f:60:cd:7a:f3:be:c3: - 27:8e:03:3e:a4:dd:12:ef:7e:1e:74:06:3c:3f:31:f2:1c:7b: - 91:31:21:b4:f0:d0:6c:97:d4:e9:97:b2:24:56:1e:56:c3:35: - bd:88:05:0f:5b:10:1a:64:e1:c7:82:30:f9:32:ad:9e:50:2c: - e7:78:05:d0:31:b1:5a:98:8a:75:4e:90:5c:6a:14:2a:e0:52: - 47:82:60:e6:1e:da:81:b1:fb:14:0b:5a:f1:9f:d2:95:ba:3e: - d0:1b:d6:15:1d:a3:be:86:d5:db:0f:c0:49:64:bb:2e:50:19: - 4b:d2:24:f8:dd:1e:07:56:d0:38:a0:95:70:20:76:8c:d7:dd: - 1e:de:9f:71:c4:23:ef:83:13:5c:a3:24:15:4d:29:40:3c:6a: - c4:a9:d8:b7:a6:44:a5:0d:f4:e0:9d:77:1e:40:70:26:fc:da: - d9:36:e4:79:e4:b5:3f:bc:9b:65:be:bb:11:96:cf:db:c6:28: - 39:3a:08:ce:47:5b:53:5a:c5:99:fe:5d:a9:dd:ef:4c:d4:c6: - a5:ad:02:e6:8c:07:12:1e:6f:03:d1:6f:a0:a3:f3:29:bd:12: - c7:50:a2:b0:7f:88:a9:99:77:9a:b1:c0:a5:39:2e:5c:7c:69: - e2:2c:b0:ea:37:6a:a4:e1:5a:e1:f5:50:e5:83:ef:a5:bb:2a: - 88:e7:8c:db:fd:6d:5e:97:19:a8:7e:66:75:6b:71:ea:bf:b1: - c7:6f:a0:f4:8e:a4:ec:34:51:5b:8c:26:03:70:a1:77:d5:01: - 12:57:00:35:db:23:de:0e:8a:28:99:fd:b1:10:6f:4b:ff:38: - 2d:60:4e:2c:9c:eb:67:b5:ad:49:ee:4b:1f:ac:af:fb:0d:90: - 5a:66:60:70:5d:aa:cd:78:d4:24:ee:c8:41:a0:93:01:92:9c: - 6a:9e:fc:b9:24:c5:b3:15:82:7e:be:ae:95:2b:eb:b1:c0:da: - e3:01:60:0b:5e:69:ac:84:56:61:be:71:17:fe:1d:13:0f:fe: - c6:87:45:e9:fe:32:a0:1a:0d:13:a4:94:55:71:a5:16:8b:ba: - ca:89:b0:b2:c7:fc:8f:d8:54:b5:93:62:9d:ce:cf:59:fb:3d: - 18:ce:2a:cb:35:15:82:5d:ff:54:22:5b:71:52:fb:b7:c9:fe: - 60:9b:00:41:64:f0:aa:2a:ec:b6:42:43:ce:89:66:81:c8:8b: - 9f:39:54:03:25:d3:16:35:8e:84:d0:5f:fa:30:1a:f5:9a:6c: - f4:0e:53:f9:3a:5b:d1:1c ------BEGIN CERTIFICATE----- -MIIF2TCCA8GgAwIBAgIQXAuFXAvnWUHfV8w/f52oNjANBgkqhkiG9w0BAQUFADBk -MQswCQYDVQQGEwJjaDERMA8GA1UEChMIU3dpc3Njb20xJTAjBgNVBAsTHERpZ2l0 -YWwgQ2VydGlmaWNhdGUgU2VydmljZXMxGzAZBgNVBAMTElN3aXNzY29tIFJvb3Qg -Q0EgMTAeFw0wNTA4MTgxMjA2MjBaFw0yNTA4MTgyMjA2MjBaMGQxCzAJBgNVBAYT -AmNoMREwDwYDVQQKEwhTd2lzc2NvbTElMCMGA1UECxMcRGlnaXRhbCBDZXJ0aWZp -Y2F0ZSBTZXJ2aWNlczEbMBkGA1UEAxMSU3dpc3Njb20gUm9vdCBDQSAxMIICIjAN -BgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEA0LmwqAzZuz8h+BvVM5OAFmUgdbI9 -m2BtRsiMMW8Xw/qabFbtPMWRV8PNq5ZJkCoZSx6jbVfd8StiKHVFXqrWW/oLJdih -FvkcxC7mlSpnzNApbjyFNDhhSbEAn9Y6cV9Nbc5fuankiX9qUvrKm/LcqfmdmUc/ -TilftKaNXXsLmREDA/7n29uj/x2lzZAeAR81sH8A25Bvxn570e56eqeqDFdvpG3F -EzuwpdntMhy0XmeLVNxzh+XTF3xmUHJd1BpYwdnP2IkCb6dJtDZd0KTeByy2dbco -kdaXvij1mB7qWybJvbCXc9qukSbraMH5ORXWZ0sKbU/Lz7DkQnGMU3nn7uHbHaBu -HYwadzVcFh4rUx80i9Fs/PJnB3r1re3WmquhsUvhzDdf/X/NTa64H5xD+SpYVUNF -vJbNcA78yeNmuk6NO4HLFWR7uZToXTNShXEuT46iBhFRyePLoW4xCGQMwtI89Tbo -19AOeCMgkckkKmUpWyL3Ic6DXqTz3kvTaI9GdVyDCW4pa8RwjPWd1yAv/0bSKzjC -L3UcPX7ape8eYIVpQtPM+GP+HkM5haa2Y0EQs3MevNP6yn0WR+Kn1dCjigoIlmJW -bjTb2QK5MHXjBNLnj8KwEUAKrNVxAmKLMb7dxiNYMUJDLXT5xp6mig/p/r+D5kNX -JLrvRjSq1xIBOO0CAwEAAaOBhjCBgzAOBgNVHQ8BAf8EBAMCAYYwHQYDVR0hBBYw -FDASBgdghXQBUwABBgdghXQBUwABMBIGA1UdEwEB/wQIMAYBAf8CAQcwHwYDVR0j -BBgwFoAUAyUv3m+CATpcLNwroWm1Z9SM0/0wHQYDVR0OBBYEFAMlL95vggE6XCzc -K6FptWfUjNP9MA0GCSqGSIb3DQEBBQUAA4ICAQA1EMvspgQNDQ/NwNurqPKIlwzf -ky9NfEBWMXrrpA9gzXrzvsMnjgM+pN0S734edAY8PzHyHHuRMSG08NBsl9Tpl7Ik -Vh5WwzW9iAUPWxAaZOHHgjD5Mq2eUCzneAXQMbFamIp1TpBcahQq4FJHgmDmHtqB -sfsUC1rxn9KVuj7QG9YVHaO+htXbD8BJZLsuUBlL0iT43R4HVtA4oJVwIHaM190e -3p9xxCPvgxNcoyQVTSlAPGrEqdi3pkSlDfTgnXceQHAm/NrZNuR55LU/vJtlvrsR -ls/bxig5OgjOR1tTWsWZ/l2p3e9M1MalrQLmjAcSHm8D0W+go/MpvRLHUKKwf4ip -mXeascClOS5cfGniLLDqN2qk4Vrh9VDlg++luyqI54zb/W1elxmofmZ1a3Hqv7HH -b6D0jqTsNFFbjCYDcKF31QESVwA12yPeDooomf2xEG9L/zgtYE4snOtnta1J7ksf -rK/7DZBaZmBwXarNeNQk7shBoJMBkpxqnvy5JMWzFYJ+vq6VK+uxwNrjAWALXmms -hFZhvnEX/h0TD/7Gh0Xp/jKgGg0TpJRVcaUWi7rKibCyx/yP2FS1k2Kdzs9Z+z0Y -zirLNRWCXf9UIltxUvu3yf5gmwBBZPCqKuy2QkPOiWaByIufOVQDJdMWNY6E0F/6 -MBr1mmz0DlP5OlvRHA== ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: - 1e:9e:28:e8:48:f2:e5:ef:c3:7c:4a:1e:5a:18:67:b6 - Signature Algorithm: sha256WithRSAEncryption - Issuer: C=ch, O=Swisscom, OU=Digital Certificate Services, CN=Swisscom Root CA 2 - Validity - Not Before: Jun 24 08:38:14 2011 GMT - Not After : Jun 25 07:38:14 2031 GMT - Subject: C=ch, O=Swisscom, OU=Digital Certificate Services, CN=Swisscom Root CA 2 - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (4096 bit) - Modulus: - 00:95:42:4e:84:9d:51:e6:d3:09:e8:72:5a:23:69: - db:78:70:8e:16:f1:2b:8f:0d:03:ce:93:cc:2e:00: - 08:7b:ab:33:8c:f4:e9:40:e6:17:4c:ab:9e:b8:47: - 14:32:77:32:dd:28:0c:de:18:4b:5f:76:9f:f8:39: - 3b:fc:4e:89:d8:7c:c5:67:ef:ab:d2:b9:34:5f:6b: - 3a:f3:64:36:ce:c2:b0:cf:13:68:ca:c8:cb:eb:b5: - e2:3d:2e:21:df:ea:2c:d4:e0:f9:70:96:4c:ff:6a: - 58:98:b7:17:e4:1b:52:e5:7e:07:00:1d:5f:da:e6: - 3e:95:04:b7:69:88:39:a1:41:60:25:61:4b:95:39: - 68:62:1c:b1:0b:05:89:c0:36:82:14:21:3f:ae:db: - a1:fd:bc:6f:1c:60:86:b6:53:94:49:b9:2b:46:c5: - 4f:00:2b:bf:a1:bb:cb:3f:e0:c7:57:1c:57:e8:d6: - 69:f8:c1:24:52:9d:88:55:dd:c2:87:2e:74:23:d0: - 14:fd:2a:47:5a:bb:a6:9d:fd:94:e4:d1:8a:a5:5f: - 86:63:76:85:cb:af:ff:49:28:fc:80:ed:4c:79:d2: - bb:e4:c0:ef:01:ee:50:41:08:35:23:70:2b:a9:16: - b4:8c:6e:85:e9:b6:11:cf:31:dd:53:26:1b:df:2d: - 5a:4a:02:40:fc:c4:c0:b6:e9:31:1a:08:28:e5:60: - c3:1f:c4:90:8e:10:62:60:44:0d:ec:0a:be:55:18: - 71:2c:a5:f4:b2:bc:15:62:ff:1c:e3:be:1d:da:1e: - 57:b3:3c:7e:cd:82:1d:91:e3:4b:eb:2c:52:34:b0: - 8a:fd:12:4e:96:b0:eb:70:7f:9e:39:f7:66:42:b1: - ab:ac:52:da:76:40:57:7b:2a:bd:e8:6e:03:b2:0b: - 80:85:88:9d:0c:c7:c2:77:b0:9a:9a:57:f4:b8:fa: - 13:5c:68:93:3a:67:a4:97:d0:1b:99:b7:86:32:4b: - 60:d8:ce:ef:d0:0c:7f:95:9f:6f:87:4f:87:8a:8e: - 5f:08:7c:aa:5b:fc:5a:be:a1:91:9f:55:7d:4e:b0: - 0b:69:cc:b0:94:a8:a7:87:f2:d3:4a:50:dc:5f:72: - b0:16:75:1e:cb:b4:18:62:9a:b0:a7:39:aa:9b:9f: - 66:d8:8d:a6:6c:96:15:e3:e6:f2:f8:f1:83:62:6c: - bb:55:e9:61:93:a3:3d:f5:b1:57:8b:4f:23:b0:9b: - e5:94:6a:2f:df:8c:df:95:51:29:60:a1:0b:29:e4: - 5c:55:58:b7:a8:fc:99:ee:25:4d:4c:0e:b3:d3:4c: - 8f:84:e8:29:0f:fd:10:54:02:85:c8:f9:e5:c3:8b: - cf:e7:0f - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Key Usage: critical - Digital Signature, Certificate Sign, CRL Sign - X509v3 Policy Mappings: - 2.16.756.1.83.2.1:2.16.756.1.83.2.1 - X509v3 Basic Constraints: critical - CA:TRUE, pathlen:7 - X509v3 Subject Key Identifier: - 4D:26:20:22:89:4B:D3:D5:A4:0A:A1:6F:DE:E2:12:81:C5:F1:3C:2E - X509v3 Authority Key Identifier: - keyid:4D:26:20:22:89:4B:D3:D5:A4:0A:A1:6F:DE:E2:12:81:C5:F1:3C:2E - - Signature Algorithm: sha256WithRSAEncryption - 32:0a:b2:a4:1b:cb:7d:be:82:57:89:b9:6a:7f:f3:f4:c1:2e: - 11:7d:b8:19:3e:79:b7:a8:a8:72:37:66:9b:1a:ed:ac:13:3b: - 0e:bf:62:f0:9c:df:9e:7b:a1:53:48:0e:41:7a:ca:20:a7:17: - 1b:b6:78:ec:40:91:f3:42:ad:10:c3:5c:ef:ff:60:59:7f:cd: - 85:a3:8b:3d:48:1c:25:02:3c:67:7d:f5:32:e9:2f:30:e5:7d: - a5:7a:38:d0:f3:66:2a:66:1e:8d:33:83:8a:6f:7c:6e:a8:5a: - 75:9a:b8:d7:da:58:48:44:47:a8:4c:fa:4c:49:0a:4a:c2:12: - 37:a8:40:0c:c3:c8:e1:d0:57:0d:97:32:95:c7:3a:9f:97:d3: - 57:f8:0b:de:e5:72:f3:a3:db:ff:b5:d8:59:b2:73:dd:4d:2a: - 71:b2:ba:49:f5:cb:1c:d5:f5:79:c8:99:b3:fc:c1:4c:74:e3: - b4:bd:29:37:15:04:28:1e:de:45:46:70:ec:af:ba:78:0e:8a: - 2a:ce:00:79:dc:c0:5f:19:67:2c:6b:4b:ef:68:68:0b:43:e3: - ac:c1:62:09:ef:a6:dd:65:61:a0:af:84:55:48:91:52:1c:c6: - 25:91:2a:d0:c1:22:23:61:59:af:45:11:85:1d:01:24:34:8f: - cf:b3:ff:17:72:20:13:c2:80:aa:21:2c:71:39:0e:d0:8f:5c: - c1:d3:d1:8e:22:72:46:4c:1d:96:ae:4f:71:b1:e1:05:29:96: - 59:f4:bb:9e:75:3d:cf:0d:37:0d:62:db:26:8c:63:a9:23:df: - 67:06:3c:7c:3a:da:34:42:e1:66:b4:46:04:de:c6:96:98:0f: - 4b:48:7a:24:32:75:91:9f:ac:f7:68:e9:2a:b9:55:65:ce:5d: - 61:d3:27:70:d8:37:fe:9f:b9:af:a0:2e:56:b7:a3:65:51:ed: - 3b:ab:14:bf:4c:51:03:e8:5f:8a:05:9b:ee:8a:6e:9c:ef:bf: - 68:fa:c8:da:0b:e3:42:c9:d0:17:14:9c:b7:4a:e0:af:93:27: - 21:55:26:b5:64:2f:8d:f1:ff:a6:40:05:85:05:5c:ca:07:19: - 5c:0b:13:28:4c:58:7f:c2:a5:ef:45:da:60:d3:ae:65:61:9d: - 53:83:74:c2:ae:f2:5c:c2:16:ed:92:3e:84:3e:73:60:88:bc: - 76:f4:2c:cf:d0:7d:7d:d3:b8:5e:d1:91:12:10:e9:cd:dd:ca: - 25:e3:d5:ed:99:2f:be:75:81:4b:24:f9:45:46:94:c9:29:21: - 53:9c:26:45:aa:13:17:e4:e7:cd:78:e2:39:c1:2b:12:9e:a6: - 9e:1b:c5:e6:0e:d9:31:d9 ------BEGIN CERTIFICATE----- -MIIF2TCCA8GgAwIBAgIQHp4o6Ejy5e/DfEoeWhhntjANBgkqhkiG9w0BAQsFADBk -MQswCQYDVQQGEwJjaDERMA8GA1UEChMIU3dpc3Njb20xJTAjBgNVBAsTHERpZ2l0 -YWwgQ2VydGlmaWNhdGUgU2VydmljZXMxGzAZBgNVBAMTElN3aXNzY29tIFJvb3Qg -Q0EgMjAeFw0xMTA2MjQwODM4MTRaFw0zMTA2MjUwNzM4MTRaMGQxCzAJBgNVBAYT -AmNoMREwDwYDVQQKEwhTd2lzc2NvbTElMCMGA1UECxMcRGlnaXRhbCBDZXJ0aWZp -Y2F0ZSBTZXJ2aWNlczEbMBkGA1UEAxMSU3dpc3Njb20gUm9vdCBDQSAyMIICIjAN -BgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAlUJOhJ1R5tMJ6HJaI2nbeHCOFvEr -jw0DzpPMLgAIe6szjPTpQOYXTKueuEcUMncy3SgM3hhLX3af+Dk7/E6J2HzFZ++r -0rk0X2s682Q2zsKwzxNoysjL67XiPS4h3+os1OD5cJZM/2pYmLcX5BtS5X4HAB1f -2uY+lQS3aYg5oUFgJWFLlTloYhyxCwWJwDaCFCE/rtuh/bxvHGCGtlOUSbkrRsVP -ACu/obvLP+DHVxxX6NZp+MEkUp2IVd3Chy50I9AU/SpHWrumnf2U5NGKpV+GY3aF -y6//SSj8gO1MedK75MDvAe5QQQg1I3ArqRa0jG6F6bYRzzHdUyYb3y1aSgJA/MTA -tukxGggo5WDDH8SQjhBiYEQN7Aq+VRhxLKX0srwVYv8c474d2h5Xszx+zYIdkeNL -6yxSNLCK/RJOlrDrcH+eOfdmQrGrrFLadkBXeyq96G4DsguAhYidDMfCd7Camlf0 -uPoTXGiTOmekl9AbmbeGMktg2M7v0Ax/lZ9vh0+Hio5fCHyqW/xavqGRn1V9TrAL -acywlKinh/LTSlDcX3KwFnUey7QYYpqwpzmqm59m2I2mbJYV4+by+PGDYmy7Velh -k6M99bFXi08jsJvllGov34zflVEpYKELKeRcVVi3qPyZ7iVNTA6z00yPhOgpD/0Q -VAKFyPnlw4vP5w8CAwEAAaOBhjCBgzAOBgNVHQ8BAf8EBAMCAYYwHQYDVR0hBBYw -FDASBgdghXQBUwIBBgdghXQBUwIBMBIGA1UdEwEB/wQIMAYBAf8CAQcwHQYDVR0O -BBYEFE0mICKJS9PVpAqhb97iEoHF8TwuMB8GA1UdIwQYMBaAFE0mICKJS9PVpAqh -b97iEoHF8TwuMA0GCSqGSIb3DQEBCwUAA4ICAQAyCrKkG8t9voJXiblqf/P0wS4R -fbgZPnm3qKhyN2abGu2sEzsOv2LwnN+ee6FTSA5BesogpxcbtnjsQJHzQq0Qw1zv -/2BZf82Fo4s9SBwlAjxnffUy6S8w5X2lejjQ82YqZh6NM4OKb3xuqFp1mrjX2lhI -REeoTPpMSQpKwhI3qEAMw8jh0FcNlzKVxzqfl9NX+Ave5XLzo9v/tdhZsnPdTSpx -srpJ9csc1fV5yJmz/MFMdOO0vSk3FQQoHt5FRnDsr7p4DooqzgB53MBfGWcsa0vv -aGgLQ+OswWIJ76bdZWGgr4RVSJFSHMYlkSrQwSIjYVmvRRGFHQEkNI/Ps/8XciAT -woCqISxxOQ7Qj1zB09GOInJGTB2Wrk9xseEFKZZZ9LuedT3PDTcNYtsmjGOpI99n -Bjx8Oto0QuFmtEYE3saWmA9LSHokMnWRn6z3aOkquVVlzl1h0ydw2Df+n7mvoC5W -t6NlUe07qxS/TFED6F+KBZvuim6c779o+sjaC+NCydAXFJy3SuCvkychVSa1ZC+N -8f+mQAWFBVzKBxlcCxMoTFh/wqXvRdpg065lYZ1Tg3TCrvJcwhbtkj6EPnNgiLx2 -9CzP0H1907he0ZESEOnN3col49XtmS++dYFLJPlFRpTJKSFTnCZFqhMX5OfNeOI5 -wSsSnqaeG8XmDtkx2Q== ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: - f2:fa:64:e2:74:63:d3:8d:fd:10:1d:04:1f:76:ca:58 - Signature Algorithm: sha256WithRSAEncryption - Issuer: C=ch, O=Swisscom, OU=Digital Certificate Services, CN=Swisscom Root EV CA 2 - Validity - Not Before: Jun 24 09:45:08 2011 GMT - Not After : Jun 25 08:45:08 2031 GMT - Subject: C=ch, O=Swisscom, OU=Digital Certificate Services, CN=Swisscom Root EV CA 2 - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (4096 bit) - Modulus: - 00:c4:f7:1d:2f:57:ea:57:6c:f7:70:5d:63:b0:71: - 52:09:60:44:28:33:a3:7a:4e:0a:fa:d8:ea:6c:8b: - 51:16:1a:55:ae:54:26:c4:cc:45:07:41:4f:10:79: - 7f:71:d2:7a:4e:3f:38:4e:b3:00:c6:95:ca:5b:cd: - c1:2a:83:d7:27:1f:31:0e:23:16:b7:25:cb:1c:b4: - b9:80:32:5e:1a:9d:93:f1:e8:3c:60:2c:a7:5e:57: - 19:58:51:5e:bc:2c:56:0b:b8:d8:ef:8b:82:b4:3c: - b8:c2:24:a8:13:c7:a0:21:36:1b:7a:57:29:28:a7: - 2e:bf:71:25:90:f3:44:83:69:50:a4:e4:e1:1b:62: - 19:94:09:a3:f3:c3:bc:ef:f4:bd:ec:db:13:9d:cf: - 9d:48:09:52:67:c0:37:29:11:1e:fb:d2:11:a7:85: - 18:74:79:e4:4f:85:14:eb:52:37:e2:b1:45:d8:cc: - 0d:43:7f:ae:13:d2:6b:2b:3f:a7:c2:e2:a8:6d:76: - 5b:43:9f:be:b4:9d:b3:26:86:3b:1f:7f:e5:f2:e8: - 66:28:16:25:d0:4b:97:38:a7:e4:cf:09:d1:36:c3: - 0b:be:da:3b:44:58:8d:be:f1:9e:09:6b:3e:f3:32: - c7:2b:87:c6:ec:5e:9c:f6:87:65:ad:33:29:c4:2f: - 89:d9:b9:cb:c9:03:9d:fb:6c:94:51:97:10:1b:86: - 0b:1a:1b:3f:f6:02:7e:7b:d4:c5:51:64:28:9d:f5: - d3:ac:83:81:88:d3:74:b4:59:9d:c1:eb:61:33:5a: - 45:d1:cb:39:d0:06:6a:53:60:1d:af:f6:fb:69:bc: - 6a:dc:01:cf:bd:f9:8f:d9:bd:5b:c1:3a:5f:8e:da: - 0f:4b:a9:9b:9d:2a:28:6b:1a:0a:7c:3c:ab:22:0b: - e5:77:2d:71:f6:82:35:81:ae:f8:7b:81:e6:ea:fe: - ac:f4:1a:9b:74:5c:e8:8f:24:f6:5d:9d:46:c4:2c: - d2:1e:2b:21:6a:83:27:67:55:4a:a4:e3:c8:32:97: - 66:90:72:da:e3:d4:64:2e:5f:e3:a1:6a:f6:60:d4: - e7:35:cd:ca:c4:68:8d:d7:71:c8:d3:24:33:73:b1: - 6c:f9:6a:e1:28:db:5f:c6:3d:e8:be:55:e6:37:1b: - ed:24:d9:0f:19:8f:5f:63:18:58:50:81:51:65:6f: - f2:9f:7e:6a:04:e7:34:24:71:ba:76:4b:58:1e:19: - bd:15:60:45:aa:0c:12:40:01:9d:10:e2:c7:38:07: - 72:0a:65:c0:b6:bb:25:29:da:16:9e:8b:35:8b:61: - ed:e5:71:57:83:b5:3c:71:9f:e3:4f:bf:7e:1e:81: - 9f:41:97 - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Key Usage: critical - Digital Signature, Certificate Sign, CRL Sign - X509v3 Policy Mappings: - 2.16.756.1.83.2.2:2.16.756.1.83.2.2 - X509v3 Basic Constraints: critical - CA:TRUE, pathlen:3 - X509v3 Subject Key Identifier: - 45:D9:A5:81:6E:3D:88:4D:8D:71:D2:46:C1:6E:45:1E:F3:C4:80:9D - X509v3 Authority Key Identifier: - keyid:45:D9:A5:81:6E:3D:88:4D:8D:71:D2:46:C1:6E:45:1E:F3:C4:80:9D - - Signature Algorithm: sha256WithRSAEncryption - 94:3a:73:06:9f:52:4b:30:5c:d4:fe:b1:5c:25:f9:d7:8e:6f: - f5:87:64:9f:ed:14:8e:b8:04:8e:28:4b:8f:aa:7b:8e:39:b4: - d9:58:f6:7b:a1:35:0a:a1:9d:8a:f7:63:e5:eb:bd:39:82:d4: - e3:7a:2d:6f:df:13:3c:ba:fe:7e:56:98:0b:f3:54:9f:cd:44: - 4e:6e:3c:e1:3e:15:bf:06:26:9d:e4:f0:90:b6:d4:c2:9e:30: - 2e:1f:ef:c7:7a:c4:50:c7:ea:7b:da:50:cb:7a:26:cb:00:b4: - 5a:ab:b5:93:1f:80:89:84:04:95:8d:8d:7f:09:93:bf:d4:a8: - a8:e4:63:6d:d9:64:e4:b8:29:5a:08:bf:50:e1:84:0f:55:7b: - 5f:08:22:1b:f5:bd:99:1e:14:f6:ce:f4:58:10:82:b3:0a:3d: - 19:c1:bf:5b:ab:aa:99:d8:f2:31:bd:e5:38:66:dc:58:05:c7: - ed:63:1a:2e:0a:97:7c:87:93:2b:b2:8a:e3:f1:ec:18:e5:75: - b6:29:87:e7:dc:8b:1a:7e:b4:d8:c9:d3:8a:17:6c:7d:29:44: - be:8a:aa:f5:7e:3a:2e:68:31:93:b9:6a:da:9a:e0:db:e9:2e: - a5:84:cd:1c:0a:b8:4a:08:f9:9c:f1:61:26:98:93:b7:7b:66: - ec:91:5e:dd:51:3f:db:73:0f:ad:04:58:09:dd:04:02:95:0a: - 3e:d3:76:df:a6:10:1e:80:3d:e8:cd:a4:64:d1:33:c7:92:c7: - e2:4e:44:e3:09:c9:4e:c2:5d:87:0e:12:9e:bf:0f:c9:05:10: - de:7a:a3:b1:3c:f2:3f:a5:aa:27:79:ad:31:7d:1f:fd:fc:19: - 69:c5:dd:b9:3f:7c:cd:c6:b4:c2:30:1e:7e:6e:92:d7:7f:61: - 76:5a:8f:eb:95:4d:bc:11:6e:21:7c:59:37:99:d0:06:bc:f9: - 06:6d:32:16:a5:d9:69:a8:e1:dc:3c:80:1e:60:51:dc:d7:54: - 21:1e:ca:62:77:4f:fa:d8:8f:b3:2b:3a:0d:78:72:c9:68:41: - 5a:47:4a:c2:a3:eb:1a:d7:0a:ab:3c:32:55:c8:0a:11:9c:df: - 74:d6:f0:40:15:1d:c8:b9:8f:b5:36:c5:af:f8:22:b8:ca:1d: - f3:d6:b6:19:0f:9f:61:65:6a:ea:74:c8:7c:8f:c3:4f:5d:65: - 82:1f:d9:0d:89:da:75:72:fb:ef:f1:47:67:13:b3:c8:d1:19: - 88:27:26:9a:99:79:7f:1e:e4:2c:3f:7b:ee:f1:de:4d:8b:96: - 97:c3:d5:3f:7c:1b:23:ed:a4:b3:1d:16:72:43:4b:20:e1:59: - 7e:c2:e8:ad:26:bf:a2:f7 ------BEGIN CERTIFICATE----- -MIIF4DCCA8igAwIBAgIRAPL6ZOJ0Y9ON/RAdBB92ylgwDQYJKoZIhvcNAQELBQAw -ZzELMAkGA1UEBhMCY2gxETAPBgNVBAoTCFN3aXNzY29tMSUwIwYDVQQLExxEaWdp -dGFsIENlcnRpZmljYXRlIFNlcnZpY2VzMR4wHAYDVQQDExVTd2lzc2NvbSBSb290 -IEVWIENBIDIwHhcNMTEwNjI0MDk0NTA4WhcNMzEwNjI1MDg0NTA4WjBnMQswCQYD -VQQGEwJjaDERMA8GA1UEChMIU3dpc3Njb20xJTAjBgNVBAsTHERpZ2l0YWwgQ2Vy -dGlmaWNhdGUgU2VydmljZXMxHjAcBgNVBAMTFVN3aXNzY29tIFJvb3QgRVYgQ0Eg -MjCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAMT3HS9X6lds93BdY7Bx -UglgRCgzo3pOCvrY6myLURYaVa5UJsTMRQdBTxB5f3HSek4/OE6zAMaVylvNwSqD -1ycfMQ4jFrclyxy0uYAyXhqdk/HoPGAsp15XGVhRXrwsVgu42O+LgrQ8uMIkqBPH -oCE2G3pXKSinLr9xJZDzRINpUKTk4RtiGZQJo/PDvO/0vezbE53PnUgJUmfANykR -HvvSEaeFGHR55E+FFOtSN+KxRdjMDUN/rhPSays/p8LiqG12W0OfvrSdsyaGOx9/ -5fLoZigWJdBLlzin5M8J0TbDC77aO0RYjb7xnglrPvMyxyuHxuxenPaHZa0zKcQv -idm5y8kDnftslFGXEBuGCxobP/YCfnvUxVFkKJ3106yDgYjTdLRZncHrYTNaRdHL -OdAGalNgHa/2+2m8atwBz735j9m9W8E6X47aD0upm50qKGsaCnw8qyIL5XctcfaC -NYGu+HuB5ur+rPQam3Rc6I8k9l2dRsQs0h4rIWqDJ2dVSqTjyDKXZpBy2uPUZC5f -46Fq9mDU5zXNysRojddxyNMkM3OxbPlq4SjbX8Y96L5V5jcb7STZDxmPX2MYWFCB -UWVv8p9+agTnNCRxunZLWB4ZvRVgRaoMEkABnRDixzgHcgplwLa7JSnaFp6LNYth -7eVxV4O1PHGf40+/fh6Bn0GXAgMBAAGjgYYwgYMwDgYDVR0PAQH/BAQDAgGGMB0G -A1UdIQQWMBQwEgYHYIV0AVMCAgYHYIV0AVMCAjASBgNVHRMBAf8ECDAGAQH/AgED -MB0GA1UdDgQWBBRF2aWBbj2ITY1x0kbBbkUe88SAnTAfBgNVHSMEGDAWgBRF2aWB -bj2ITY1x0kbBbkUe88SAnTANBgkqhkiG9w0BAQsFAAOCAgEAlDpzBp9SSzBc1P6x -XCX5145v9Ydkn+0UjrgEjihLj6p7jjm02Vj2e6E1CqGdivdj5eu9OYLU43otb98T -PLr+flaYC/NUn81ETm484T4VvwYmneTwkLbUwp4wLh/vx3rEUMfqe9pQy3omywC0 -Wqu1kx+AiYQElY2NfwmTv9SoqORjbdlk5LgpWgi/UOGED1V7XwgiG/W9mR4U9s70 -WBCCswo9GcG/W6uqmdjyMb3lOGbcWAXH7WMaLgqXfIeTK7KK4/HsGOV1timH59yL -Gn602MnTihdsfSlEvoqq9X46Lmgxk7lq2prg2+kupYTNHAq4Sgj5nPFhJpiTt3tm -7JFe3VE/23MPrQRYCd0EApUKPtN236YQHoA96M2kZNEzx5LH4k5E4wnJTsJdhw4S -nr8PyQUQ3nqjsTzyP6WqJ3mtMX0f/fwZacXduT98zca0wjAefm6S139hdlqP65VN -vBFuIXxZN5nQBrz5Bm0yFqXZaajh3DyAHmBR3NdUIR7KYndP+tiPsys6DXhyyWhB -WkdKwqPrGtcKqzwyVcgKEZzfdNbwQBUdyLmPtTbFr/giuMod89a2GQ+fYWVq6nTI -fI/DT11lgh/ZDYnadXL77/FHZxOzyNEZiCcmmpl5fx7kLD977vHeTYuWl8PVP3wb -I+2ksx0WckNLIOFZfsLorSa/ovc= ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: 1 (0x1) - Signature Algorithm: sha256WithRSAEncryption - Issuer: C=DE, O=T-Systems Enterprise Services GmbH, OU=T-Systems Trust Center, CN=T-TeleSec GlobalRoot Class 2 - Validity - Not Before: Oct 1 10:40:14 2008 GMT - Not After : Oct 1 23:59:59 2033 GMT - Subject: C=DE, O=T-Systems Enterprise Services GmbH, OU=T-Systems Trust Center, CN=T-TeleSec GlobalRoot Class 2 - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (2048 bit) - Modulus: - 00:aa:5f:da:1b:5f:e8:73:91:e5:da:5c:f4:a2:e6: - 47:e5:f3:68:55:60:05:1d:02:a4:b3:9b:59:f3:1e: - 8a:af:34:ad:fc:0d:c2:d9:48:19:ee:69:8f:c9:20: - fc:21:aa:07:19:ed:b0:5c:ac:65:c7:5f:ed:02:7c: - 7b:7c:2d:1b:d6:ba:b9:80:c2:18:82:16:84:fa:66: - b0:08:c6:54:23:81:e4:cd:b9:49:3f:f6:4f:6e:37: - 48:28:38:0f:c5:be:e7:68:70:fd:39:97:4d:d2:c7: - 98:91:50:aa:c4:44:b3:23:7d:39:47:e9:52:62:d6: - 12:93:5e:b7:31:96:42:05:fb:76:a7:1e:a3:f5:c2: - fc:e9:7a:c5:6c:a9:71:4f:ea:cb:78:bc:60:af:c7: - de:f4:d9:cb:be:7e:33:a5:6e:94:83:f0:34:fa:21: - ab:ea:8e:72:a0:3f:a4:de:30:5b:ef:86:4d:6a:95: - 5b:43:44:a8:10:15:1c:e5:01:57:c5:98:f1:e6:06: - 28:91:aa:20:c5:b7:53:26:51:43:b2:0b:11:95:58: - e1:c0:0f:76:d9:c0:8d:7c:81:f3:72:70:9e:6f:fe: - 1a:8e:d9:5f:35:c6:b2:6f:34:7c:be:48:4f:e2:5a: - 39:d7:d8:9d:78:9e:9f:86:3e:03:5e:19:8b:44:a2: - d5:c7 - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Basic Constraints: critical - CA:TRUE - X509v3 Key Usage: critical - Certificate Sign, CRL Sign - X509v3 Subject Key Identifier: - BF:59:20:36:00:79:A0:A0:22:6B:8C:D5:F2:61:D2:B8:2C:CB:82:4A - Signature Algorithm: sha256WithRSAEncryption - 31:03:a2:61:0b:1f:74:e8:72:36:c6:6d:f9:4d:9e:fa:22:a8: - e1:81:56:cf:cd:bb:9f:ea:ab:91:19:38:af:aa:7c:15:4d:f3: - b6:a3:8d:a5:f4:8e:f6:44:a9:a7:e8:21:95:ad:3e:00:62:16: - 88:f0:02:ba:fc:61:23:e6:33:9b:30:7a:6b:36:62:7b:ad:04: - 23:84:58:65:e2:db:2b:8a:e7:25:53:37:62:53:5f:bc:da:01: - 62:29:a2:a6:27:71:e6:3a:22:7e:c1:6f:1d:95:70:20:4a:07: - 34:df:ea:ff:15:80:e5:ba:d7:7a:d8:5b:75:7c:05:7a:29:47: - 7e:40:a8:31:13:77:cd:40:3b:b4:51:47:7a:2e:11:e3:47:11: - de:9d:66:d0:8b:d5:54:66:fa:83:55:ea:7c:c2:29:89:1b:e9: - 6f:b3:ce:e2:05:84:c9:2f:3e:78:85:62:6e:c9:5f:c1:78:63: - 74:58:c0:48:18:0c:99:39:eb:a4:cc:1a:b5:79:5a:8d:15:9c: - d8:14:0d:f6:7a:07:57:c7:22:83:05:2d:3c:9b:25:26:3d:18: - b3:a9:43:7c:c8:c8:ab:64:8f:0e:a3:bf:9c:1b:9d:30:db:da: - d0:19:2e:aa:3c:f1:fb:33:80:76:e4:cd:ad:19:4f:05:27:8e: - 13:a1:6e:c2 ------BEGIN CERTIFICATE----- -MIIDwzCCAqugAwIBAgIBATANBgkqhkiG9w0BAQsFADCBgjELMAkGA1UEBhMCREUx -KzApBgNVBAoMIlQtU3lzdGVtcyBFbnRlcnByaXNlIFNlcnZpY2VzIEdtYkgxHzAd -BgNVBAsMFlQtU3lzdGVtcyBUcnVzdCBDZW50ZXIxJTAjBgNVBAMMHFQtVGVsZVNl -YyBHbG9iYWxSb290IENsYXNzIDIwHhcNMDgxMDAxMTA0MDE0WhcNMzMxMDAxMjM1 -OTU5WjCBgjELMAkGA1UEBhMCREUxKzApBgNVBAoMIlQtU3lzdGVtcyBFbnRlcnBy -aXNlIFNlcnZpY2VzIEdtYkgxHzAdBgNVBAsMFlQtU3lzdGVtcyBUcnVzdCBDZW50 -ZXIxJTAjBgNVBAMMHFQtVGVsZVNlYyBHbG9iYWxSb290IENsYXNzIDIwggEiMA0G -CSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCqX9obX+hzkeXaXPSi5kfl82hVYAUd -AqSzm1nzHoqvNK38DcLZSBnuaY/JIPwhqgcZ7bBcrGXHX+0CfHt8LRvWurmAwhiC -FoT6ZrAIxlQjgeTNuUk/9k9uN0goOA/FvudocP05l03Sx5iRUKrERLMjfTlH6VJi -1hKTXrcxlkIF+3anHqP1wvzpesVsqXFP6st4vGCvx9702cu+fjOlbpSD8DT6Iavq -jnKgP6TeMFvvhk1qlVtDRKgQFRzlAVfFmPHmBiiRqiDFt1MmUUOyCxGVWOHAD3bZ -wI18gfNycJ5v/hqO2V81xrJvNHy+SE/iWjnX2J14np+GPgNeGYtEotXHAgMBAAGj -QjBAMA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgEGMB0GA1UdDgQWBBS/ -WSA2AHmgoCJrjNXyYdK4LMuCSjANBgkqhkiG9w0BAQsFAAOCAQEAMQOiYQsfdOhy -NsZt+U2e+iKo4YFWz827n+qrkRk4r6p8FU3ztqONpfSO9kSpp+ghla0+AGIWiPAC -uvxhI+YzmzB6azZie60EI4RYZeLbK4rnJVM3YlNfvNoBYimipidx5joifsFvHZVw -IEoHNN/q/xWA5brXethbdXwFeilHfkCoMRN3zUA7tFFHei4R40cR3p1m0IvVVGb6 -g1XqfMIpiRvpb7PO4gWEyS8+eIVibslfwXhjdFjASBgMmTnrpMwatXlajRWc2BQN -9noHV8cigwUtPJslJj0Ys6lDfMjIq2SPDqO/nBudMNva0Bkuqjzx+zOAduTNrRlP -BSeOE6Fuwg== ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: 1 (0x1) - Signature Algorithm: sha256WithRSAEncryption - Issuer: C=DE, O=T-Systems Enterprise Services GmbH, OU=T-Systems Trust Center, CN=T-TeleSec GlobalRoot Class 3 - Validity - Not Before: Oct 1 10:29:56 2008 GMT - Not After : Oct 1 23:59:59 2033 GMT - Subject: C=DE, O=T-Systems Enterprise Services GmbH, OU=T-Systems Trust Center, CN=T-TeleSec GlobalRoot Class 3 - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (2048 bit) - Modulus: - 00:bd:75:93:f0:62:22:6f:24:ae:e0:7a:76:ac:7d: - bd:d9:24:d5:b8:b7:fc:cd:f0:42:e0:eb:78:88:56: - 5e:9b:9a:54:1d:4d:0c:8a:f6:d3:cf:70:f4:52:b5: - d8:93:04:e3:46:86:71:41:4a:2b:f0:2a:2c:55:03: - d6:48:c3:e0:39:38:ed:f2:5c:3c:3f:44:bc:93:3d: - 61:ab:4e:cd:0d:be:f0:20:27:58:0e:44:7f:04:1a: - 87:a5:d7:96:14:36:90:d0:49:7b:a1:75:fb:1a:6b: - 73:b1:f8:ce:a9:09:2c:f2:53:d5:c3:14:44:b8:86: - a5:f6:8b:2b:39:da:a3:33:54:d9:fa:72:1a:f7:22: - 15:1c:88:91:6b:7f:66:e5:c3:6a:80:b0:24:f3:df: - 86:45:88:fd:19:7f:75:87:1f:1f:b1:1b:0a:73:24: - 5b:b9:65:e0:2c:54:c8:60:d3:66:17:3f:e1:cc:54: - 33:73:91:02:3a:a6:7f:7b:76:39:a2:1f:96:b6:38: - ae:b5:c8:93:74:1d:9e:b9:b4:e5:60:9d:2f:56:d1: - e0:eb:5e:5b:4c:12:70:0c:6c:44:20:ab:11:d8:f4: - 19:f6:d2:9c:52:37:e7:fa:b6:c2:31:3b:4a:d4:14: - 99:ad:c7:1a:f5:5d:5f:fa:07:b8:7c:0d:1f:d6:83: - 1e:b3 - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Basic Constraints: critical - CA:TRUE - X509v3 Key Usage: critical - Certificate Sign, CRL Sign - X509v3 Subject Key Identifier: - B5:03:F7:76:3B:61:82:6A:12:AA:18:53:EB:03:21:94:BF:FE:CE:CA - Signature Algorithm: sha256WithRSAEncryption - 56:3d:ef:94:d5:bd:da:73:b2:58:be:ae:90:ad:98:27:97:fe: - 01:b1:b0:52:00:b8:4d:e4:1b:21:74:1b:7e:c0:ee:5e:69:2a: - 25:af:5c:d6:1d:da:d2:79:c9:f3:97:29:e0:86:87:de:04:59: - 0f:f1:59:d4:64:85:4b:99:af:25:04:1e:c9:46:a9:97:de:82: - b2:1b:70:9f:9c:f6:af:71:31:dd:7b:05:a5:2c:d3:b9:ca:47: - f6:ca:f2:f6:e7:ad:b9:48:3f:bc:16:b7:c1:6d:f4:ea:09:af: - ec:f3:b5:e7:05:9e:a6:1e:8a:53:51:d6:93:81:cc:74:93:f6: - b9:da:a6:25:05:74:79:5a:7e:40:3e:82:4b:26:11:30:6e:e1: - 3f:41:c7:47:00:35:d5:f5:d3:f7:54:3e:81:3d:da:49:6a:9a: - b3:ef:10:3d:e6:eb:6f:d1:c8:22:47:cb:cc:cf:01:31:92:d9: - 18:e3:22:be:09:1e:1a:3e:5a:b2:e4:6b:0c:54:7a:7d:43:4e: - b8:89:a5:7b:d7:a2:3d:96:86:cc:f2:26:34:2d:6a:92:9d:9a: - 1a:d0:30:e2:5d:4e:04:b0:5f:8b:20:7e:77:c1:3d:95:82:d1: - 46:9a:3b:3c:78:b8:6f:a1:d0:0d:64:a2:78:1e:29:4e:93:c3: - a4:54:14:5b ------BEGIN CERTIFICATE----- -MIIDwzCCAqugAwIBAgIBATANBgkqhkiG9w0BAQsFADCBgjELMAkGA1UEBhMCREUx -KzApBgNVBAoMIlQtU3lzdGVtcyBFbnRlcnByaXNlIFNlcnZpY2VzIEdtYkgxHzAd -BgNVBAsMFlQtU3lzdGVtcyBUcnVzdCBDZW50ZXIxJTAjBgNVBAMMHFQtVGVsZVNl -YyBHbG9iYWxSb290IENsYXNzIDMwHhcNMDgxMDAxMTAyOTU2WhcNMzMxMDAxMjM1 -OTU5WjCBgjELMAkGA1UEBhMCREUxKzApBgNVBAoMIlQtU3lzdGVtcyBFbnRlcnBy -aXNlIFNlcnZpY2VzIEdtYkgxHzAdBgNVBAsMFlQtU3lzdGVtcyBUcnVzdCBDZW50 -ZXIxJTAjBgNVBAMMHFQtVGVsZVNlYyBHbG9iYWxSb290IENsYXNzIDMwggEiMA0G -CSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQC9dZPwYiJvJK7genasfb3ZJNW4t/zN -8ELg63iIVl6bmlQdTQyK9tPPcPRStdiTBONGhnFBSivwKixVA9ZIw+A5OO3yXDw/ -RLyTPWGrTs0NvvAgJ1gORH8EGoel15YUNpDQSXuhdfsaa3Ox+M6pCSzyU9XDFES4 -hqX2iys52qMzVNn6chr3IhUciJFrf2blw2qAsCTz34ZFiP0Zf3WHHx+xGwpzJFu5 -ZeAsVMhg02YXP+HMVDNzkQI6pn97djmiH5a2OK61yJN0HZ65tOVgnS9W0eDrXltM -EnAMbEQgqxHY9Bn20pxSN+f6tsIxO0rUFJmtxxr1XV/6B7h8DR/Wgx6zAgMBAAGj -QjBAMA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgEGMB0GA1UdDgQWBBS1 -A/d2O2GCahKqGFPrAyGUv/7OyjANBgkqhkiG9w0BAQsFAAOCAQEAVj3vlNW92nOy -WL6ukK2YJ5f+AbGwUgC4TeQbIXQbfsDuXmkqJa9c1h3a0nnJ85cp4IaH3gRZD/FZ -1GSFS5mvJQQeyUapl96Cshtwn5z2r3Ex3XsFpSzTucpH9sry9uetuUg/vBa3wW30 -6gmv7PO15wWeph6KU1HWk4HMdJP2udqmJQV0eVp+QD6CSyYRMG7hP0HHRwA11fXT -91Q+gT3aSWqas+8QPebrb9HIIkfLzM8BMZLZGOMivgkeGj5asuRrDFR6fUNOuIml -e9eiPZaGzPImNC1qkp2aGtAw4l1OBLBfiyB+d8E9lYLRRpo7PHi4b6HQDWSieB4p -TpPDpFQUWw== ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: 1 (0x1) - Signature Algorithm: sha256WithRSAEncryption - Issuer: C=TR, L=Gebze - Kocaeli, O=Turkiye Bilimsel ve Teknolojik Arastirma Kurumu - TUBITAK, OU=Kamu Sertifikasyon Merkezi - Kamu SM, CN=TUBITAK Kamu SM SSL Kok Sertifikasi - Surum 1 - Validity - Not Before: Nov 25 08:25:55 2013 GMT - Not After : Oct 25 08:25:55 2043 GMT - Subject: C=TR, L=Gebze - Kocaeli, O=Turkiye Bilimsel ve Teknolojik Arastirma Kurumu - TUBITAK, OU=Kamu Sertifikasyon Merkezi - Kamu SM, CN=TUBITAK Kamu SM SSL Kok Sertifikasi - Surum 1 - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (2048 bit) - Modulus: - 00:af:75:30:33:aa:bb:6b:d3:99:2c:12:37:84:d9: - 8d:7b:97:80:d3:6e:e7:ff:9b:50:95:3e:90:95:56: - 42:d7:19:7c:26:84:8d:92:fa:01:1d:3a:0f:e2:64: - 38:b7:8c:bc:e8:88:f9:8b:24:ab:2e:a3:f5:37:e4: - 40:8e:18:25:79:83:75:1f:3b:ff:6c:a8:c5:c6:56: - f8:b4:ed:8a:44:a3:ab:6c:4c:fc:1d:d0:dc:ef:68: - bd:cf:e4:aa:ce:f0:55:f7:a2:34:d4:83:6b:37:7c: - 1c:c2:fe:b5:03:ec:57:ce:bc:b4:b5:c5:ed:00:0f: - 53:37:2a:4d:f4:4f:0c:83:fb:86:cf:cb:fe:8c:4e: - bd:87:f9:a7:8b:21:57:9c:7a:df:03:67:89:2c:9d: - 97:61:a7:10:b8:55:90:7f:0e:2d:27:38:74:df:e7: - fd:da:4e:12:e3:4d:15:22:02:c8:e0:e0:fc:0f:ad: - 8a:d7:c9:54:50:cc:3b:0f:ca:16:80:84:d0:51:56: - c3:8e:56:7f:89:22:33:2f:e6:85:0a:bd:a5:a8:1b: - 36:de:d3:dc:2c:6d:3b:c7:13:bd:59:23:2c:e6:e5: - a4:f7:d8:0b:ed:ea:90:40:44:a8:95:bb:93:d5:d0: - 80:34:b6:46:78:0e:1f:00:93:46:e1:ee:e9:f9:ec: - 4f:17 - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Subject Key Identifier: - 65:3F:C7:8A:86:C6:3C:DD:3C:54:5C:35:F8:3A:ED:52:0C:47:57:C8 - X509v3 Key Usage: critical - Certificate Sign, CRL Sign - X509v3 Basic Constraints: critical - CA:TRUE - Signature Algorithm: sha256WithRSAEncryption - 2a:3f:e1:f1:32:8e:ae:e1:98:5c:4b:5e:cf:6b:1e:6a:09:d2: - 22:a9:12:c7:5e:57:7d:73:56:64:80:84:7a:93:e4:09:b9:10: - cd:9f:2a:27:e1:00:77:be:48:c8:35:a8:81:9f:e4:b8:2c:c9: - 7f:0e:b0:d2:4b:37:5d:ea:b9:d5:0b:5e:34:bd:f4:73:29:c3: - ed:26:15:9c:7e:08:53:8a:58:8d:d0:4b:28:df:c1:b3:df:20: - f3:f9:e3:e3:3a:df:cc:9c:94:d8:4e:4f:c3:6b:17:b7:f7:72: - e8:ad:66:33:b5:25:53:ab:e0:f8:4c:a9:9d:fd:f2:0d:ba:ae: - b9:d9:aa:c6:6b:f9:93:bb:ae:ab:b8:97:3c:03:1a:ba:43:c6: - 96:b9:45:72:38:b3:a7:a1:96:3d:91:7b:7e:c0:21:53:4c:87: - ed:f2:0b:54:95:51:93:d5:22:a5:0d:8a:f1:93:0e:3e:54:0e: - b0:d8:c9:4e:dc:f2:31:32:56:ea:64:f9:ea:b5:9d:16:66:42: - 72:f3:7f:d3:b1:31:43:fc:a4:8e:17:f1:6d:23:ab:94:66:f8: - ad:fb:0f:08:6e:26:2d:7f:17:07:09:b2:8c:fb:50:c0:9f:96: - 8d:cf:b6:fd:00:9d:5a:14:9a:bf:02:44:f5:c1:c2:9f:22:5e: - a2:0f:a1:e3 ------BEGIN CERTIFICATE----- -MIIEYzCCA0ugAwIBAgIBATANBgkqhkiG9w0BAQsFADCB0jELMAkGA1UEBhMCVFIx -GDAWBgNVBAcTD0dlYnplIC0gS29jYWVsaTFCMEAGA1UEChM5VHVya2l5ZSBCaWxp -bXNlbCB2ZSBUZWtub2xvamlrIEFyYXN0aXJtYSBLdXJ1bXUgLSBUVUJJVEFLMS0w -KwYDVQQLEyRLYW11IFNlcnRpZmlrYXN5b24gTWVya2V6aSAtIEthbXUgU00xNjA0 -BgNVBAMTLVRVQklUQUsgS2FtdSBTTSBTU0wgS29rIFNlcnRpZmlrYXNpIC0gU3Vy -dW0gMTAeFw0xMzExMjUwODI1NTVaFw00MzEwMjUwODI1NTVaMIHSMQswCQYDVQQG -EwJUUjEYMBYGA1UEBxMPR2ViemUgLSBLb2NhZWxpMUIwQAYDVQQKEzlUdXJraXll -IEJpbGltc2VsIHZlIFRla25vbG9qaWsgQXJhc3Rpcm1hIEt1cnVtdSAtIFRVQklU -QUsxLTArBgNVBAsTJEthbXUgU2VydGlmaWthc3lvbiBNZXJrZXppIC0gS2FtdSBT -TTE2MDQGA1UEAxMtVFVCSVRBSyBLYW11IFNNIFNTTCBLb2sgU2VydGlmaWthc2kg -LSBTdXJ1bSAxMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAr3UwM6q7 -a9OZLBI3hNmNe5eA027n/5tQlT6QlVZC1xl8JoSNkvoBHToP4mQ4t4y86Ij5iySr -LqP1N+RAjhgleYN1Hzv/bKjFxlb4tO2KRKOrbEz8HdDc72i9z+SqzvBV96I01INr -N3wcwv61A+xXzry0tcXtAA9TNypN9E8Mg/uGz8v+jE69h/mniyFXnHrfA2eJLJ2X -YacQuFWQfw4tJzh03+f92k4S400VIgLI4OD8D62K18lUUMw7D8oWgITQUVbDjlZ/ -iSIzL+aFCr2lqBs23tPcLG07xxO9WSMs5uWk99gL7eqQQESolbuT1dCANLZGeA4f -AJNG4e7p+exPFwIDAQABo0IwQDAdBgNVHQ4EFgQUZT/HiobGPN08VFw1+DrtUgxH -V8gwDgYDVR0PAQH/BAQDAgEGMA8GA1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcNAQEL -BQADggEBACo/4fEyjq7hmFxLXs9rHmoJ0iKpEsdeV31zVmSAhHqT5Am5EM2fKifh -AHe+SMg1qIGf5LgsyX8OsNJLN13qudULXjS99HMpw+0mFZx+CFOKWI3QSyjfwbPf -IPP54+M638yclNhOT8NrF7f3cuitZjO1JVOr4PhMqZ398g26rrnZqsZr+ZO7rqu4 -lzwDGrpDxpa5RXI4s6ehlj2Re37AIVNMh+3yC1SVUZPVIqUNivGTDj5UDrDYyU7c -8jEyVupk+eq1nRZmQnLzf9OxMUP8pI4X8W0jq5Rm+K37DwhuJi1/FwcJsoz7UMCf -lo3Ptv0AnVoUmr8CRPXBwp8iXqIPoeM= ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: 1 (0x1) - Signature Algorithm: sha1WithRSAEncryption - Issuer: CN=T\xC3\x9CRKTRUST Elektronik Sertifika Hizmet Sa\xC4\x9Flay\xC4\xB1c\xC4\xB1s\xC4\xB1, C=TR, L=Ankara, O=T\xC3\x9CRKTRUST Bilgi \xC4\xB0leti\xC5\x9Fim ve Bili\xC5\x9Fim G\xC3\xBCvenli\xC4\x9Fi Hizmetleri A.\xC5\x9E. (c) Aral\xC4\xB1k 2007 - Validity - Not Before: Dec 25 18:37:19 2007 GMT - Not After : Dec 22 18:37:19 2017 GMT - Subject: CN=T\xC3\x9CRKTRUST Elektronik Sertifika Hizmet Sa\xC4\x9Flay\xC4\xB1c\xC4\xB1s\xC4\xB1, C=TR, L=Ankara, O=T\xC3\x9CRKTRUST Bilgi \xC4\xB0leti\xC5\x9Fim ve Bili\xC5\x9Fim G\xC3\xBCvenli\xC4\x9Fi Hizmetleri A.\xC5\x9E. (c) Aral\xC4\xB1k 2007 - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (2048 bit) - Modulus: - 00:ab:b7:3e:0a:8c:c8:a5:58:15:e6:8a:ef:27:3d: - 4a:b4:e8:25:d3:cd:33:c2:20:dc:19:ee:88:3f:4d: - 62:f0:dd:13:77:8f:61:a9:2a:b5:d4:f2:b9:31:58: - 29:3b:2f:3f:6a:9c:6f:73:76:25:ee:34:20:80:ee: - ea:b7:f0:c4:0a:cd:2b:86:94:c9:e3:60:b1:44:52: - b2:5a:29:b4:91:97:83:d8:b7:a6:14:2f:29:49:a2: - f3:05:06:fb:b4:4f:da:a1:6c:9a:66:9f:f0:43:09: - ca:ea:72:8f:eb:00:d7:35:39:d7:56:17:47:17:30: - f4:be:bf:3f:c2:68:af:36:40:c1:a9:f4:a9:a7:e8: - 10:6b:08:8a:f7:86:1e:dc:9a:2a:15:06:f6:a3:f0: - f4:e0:c7:14:d4:51:7f:cf:b4:db:6d:af:47:96:17: - 9b:77:71:d8:a7:71:9d:24:0c:f6:94:3f:85:31:12: - 4f:ba:ee:4e:82:b8:b9:3e:8f:23:37:5e:cc:a2:aa: - 75:f7:18:6f:09:d3:ae:a7:54:28:34:fb:e1:e0:3b: - 60:7d:a0:be:79:89:86:c8:9f:2d:f9:0a:4b:c4:50: - a2:e7:fd:79:16:c7:7a:0b:18:cf:ce:4c:ef:7d:d6: - 07:6f:98:f1:af:b1:c1:7a:d7:81:35:b8:aa:17:b4: - e0:cb - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Subject Key Identifier: - 29:C5:90:AB:25:AF:11:E4:61:BF:A3:FF:88:61:91:E6:0E:FE:9C:81 - X509v3 Key Usage: critical - Certificate Sign, CRL Sign - X509v3 Basic Constraints: critical - CA:TRUE - Signature Algorithm: sha1WithRSAEncryption - 10:0d:da:f8:3a:ec:28:d1:14:95:82:b1:12:2c:51:7a:41:25: - 36:4c:9f:ec:3f:1f:84:9d:65:54:5c:a8:16:02:40:fa:6e:1a: - 37:84:ef:72:9d:86:0a:55:9d:56:28:ac:66:2c:d0:3a:56:93: - 34:07:25:ad:08:b0:8f:c8:0f:09:59:ca:9d:98:1c:e5:54:f8: - b9:45:7f:6a:97:6f:88:68:4d:4a:06:26:37:88:02:0e:b6:c6: - d6:72:99:ce:6b:77:da:62:31:a4:56:1f:ae:5f:8d:77:da:5d: - f6:88:fc:1a:d9:9e:b5:81:f0:32:b8:e3:88:d0:9c:f3:6a:a0: - b9:9b:14:59:35:36:4f:cf:f3:8e:5e:5d:17:ad:15:95:d8:dd: - b2:d5:15:6e:00:4e:b3:4b:cf:66:94:e4:e0:cd:b5:05:da:63: - 57:8b:e5:b3:aa:db:c0:2e:1c:90:44:db:1a:5d:18:a4:ee:be: - 04:5b:99:d5:71:5f:55:65:64:62:d5:a2:9b:04:59:86:c8:62: - 77:e7:7c:82:45:6a:3d:17:bf:ec:9d:75:0c:ae:a3:6f:5a:d3: - 2f:98:36:f4:f0:f5:19:ab:11:5d:c8:a6:e3:2a:58:6a:42:09: - c3:bd:92:26:66:32:0d:5d:08:55:74:ff:8c:98:d0:0a:a6:84: - 6a:d1:39:7d ------BEGIN CERTIFICATE----- -MIIEPTCCAyWgAwIBAgIBATANBgkqhkiG9w0BAQUFADCBvzE/MD0GA1UEAww2VMOc -UktUUlVTVCBFbGVrdHJvbmlrIFNlcnRpZmlrYSBIaXptZXQgU2HEn2xhecSxY8Sx -c8SxMQswCQYDVQQGEwJUUjEPMA0GA1UEBwwGQW5rYXJhMV4wXAYDVQQKDFVUw5xS -S1RSVVNUIEJpbGdpIMSwbGV0acWfaW0gdmUgQmlsacWfaW0gR8O8dmVubGnEn2kg -SGl6bWV0bGVyaSBBLsWeLiAoYykgQXJhbMSxayAyMDA3MB4XDTA3MTIyNTE4Mzcx -OVoXDTE3MTIyMjE4MzcxOVowgb8xPzA9BgNVBAMMNlTDnFJLVFJVU1QgRWxla3Ry -b25payBTZXJ0aWZpa2EgSGl6bWV0IFNhxJ9sYXnEsWPEsXPEsTELMAkGA1UEBhMC -VFIxDzANBgNVBAcMBkFua2FyYTFeMFwGA1UECgxVVMOcUktUUlVTVCBCaWxnaSDE -sGxldGnFn2ltIHZlIEJpbGnFn2ltIEfDvHZlbmxpxJ9pIEhpem1ldGxlcmkgQS7F -ni4gKGMpIEFyYWzEsWsgMjAwNzCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC -ggEBAKu3PgqMyKVYFeaK7yc9SrToJdPNM8Ig3BnuiD9NYvDdE3ePYakqtdTyuTFY -KTsvP2qcb3N2Je40IIDu6rfwxArNK4aUyeNgsURSsloptJGXg9i3phQvKUmi8wUG -+7RP2qFsmmaf8EMJyupyj+sA1zU511YXRxcw9L6/P8JorzZAwan0qafoEGsIiveG -HtyaKhUG9qPw9ODHFNRRf8+0222vR5YXm3dx2KdxnSQM9pQ/hTEST7ruToK4uT6P -IzdezKKqdfcYbwnTrqdUKDT74eA7YH2gvnmJhsifLfkKS8RQouf9eRbHegsYz85M -733WB2+Y8a+xwXrXgTW4qhe04MsCAwEAAaNCMEAwHQYDVR0OBBYEFCnFkKslrxHk -Yb+j/4hhkeYO/pyBMA4GA1UdDwEB/wQEAwIBBjAPBgNVHRMBAf8EBTADAQH/MA0G -CSqGSIb3DQEBBQUAA4IBAQAQDdr4Ouwo0RSVgrESLFF6QSU2TJ/sPx+EnWVUXKgW -AkD6bho3hO9ynYYKVZ1WKKxmLNA6VpM0ByWtCLCPyA8JWcqdmBzlVPi5RX9ql2+I -aE1KBiY3iAIOtsbWcpnOa3faYjGkVh+uX4132l32iPwa2Z61gfAyuOOI0JzzaqC5 -mxRZNTZPz/OOXl0XrRWV2N2y1RVuAE6zS89mlOTgzbUF2mNXi+WzqtvALhyQRNsa -XRik7r4EW5nVcV9VZWRi1aKbBFmGyGJ353yCRWo9F7/snXUMrqNvWtMvmDb08PUZ -qxFdyKbjKlhqQgnDvZImZjINXQhVdP+MmNAKpoRq0Tl9 ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: 3262 (0xcbe) - Signature Algorithm: sha256WithRSAEncryption - Issuer: C=TW, O=TAIWAN-CA, OU=Root CA, CN=TWCA Global Root CA - Validity - Not Before: Jun 27 06:28:33 2012 GMT - Not After : Dec 31 15:59:59 2030 GMT - Subject: C=TW, O=TAIWAN-CA, OU=Root CA, CN=TWCA Global Root CA - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (4096 bit) - Modulus: - 00:b0:05:db:c8:eb:8c:c4:6e:8a:21:ef:8e:4d:9c: - 71:0a:1f:52:70:ed:6d:82:9c:97:c5:d7:4c:4e:45: - 49:cb:40:42:b5:12:34:6c:19:c2:74:a4:31:5f:85: - 02:97:ec:43:33:0a:53:d2:9c:8c:8e:b7:b8:79:db: - 2b:d5:6a:f2:8e:66:c4:ee:2b:01:07:92:d4:b3:d0: - 02:df:50:f6:55:af:66:0e:cb:e0:47:60:2f:2b:32: - 39:35:52:3a:28:83:f8:7b:16:c6:18:b8:62:d6:47: - 25:91:ce:f0:19:12:4d:ad:63:f5:d3:3f:75:5f:29: - f0:a1:30:1c:2a:a0:98:a6:15:bd:ee:fd:19:36:f0: - e2:91:43:8f:fa:ca:d6:10:27:49:4c:ef:dd:c1:f1: - 85:70:9b:ca:ea:a8:5a:43:fc:6d:86:6f:73:e9:37: - 45:a9:f0:36:c7:cc:88:75:1e:bb:6c:06:ff:9b:6b: - 3e:17:ec:61:aa:71:7c:c6:1d:a2:f7:49:e9:15:b5: - 3c:d6:a1:61:f5:11:f7:05:6f:1d:fd:11:be:d0:30: - 07:c2:29:b0:09:4e:26:dc:e3:a2:a8:91:6a:1f:c2: - 91:45:88:5c:e5:98:b8:71:a5:15:19:c9:7c:75:11: - cc:70:74:4f:2d:9b:1d:91:44:fd:56:28:a0:fe:bb: - 86:6a:c8:fa:5c:0b:58:dc:c6:4b:76:c8:ab:22:d9: - 73:0f:a5:f4:5a:02:89:3f:4f:9e:22:82:ee:a2:74: - 53:2a:3d:53:27:69:1d:6c:8e:32:2c:64:00:26:63: - 61:36:4e:a3:46:b7:3f:7d:b3:2d:ac:6d:90:a2:95: - a2:ce:cf:da:82:e7:07:34:19:96:e9:b8:21:aa:29: - 7e:a6:38:be:8e:29:4a:21:66:79:1f:b3:c3:b5:09: - 67:de:d6:d4:07:46:f3:2a:da:e6:22:37:60:cb:81: - b6:0f:a0:0f:e9:c8:95:7f:bf:55:91:05:7a:cf:3d: - 15:c0:6f:de:09:94:01:83:d7:34:1b:cc:40:a5:f0: - b8:9b:67:d5:98:91:3b:a7:84:78:95:26:a4:5a:08: - f8:2b:74:b4:00:04:3c:df:b8:14:8e:e8:df:a9:8d: - 6c:67:92:33:1d:c0:b7:d2:ec:92:c8:be:09:bf:2c: - 29:05:6f:02:6b:9e:ef:bc:bf:2a:bc:5b:c0:50:8f: - 41:70:71:87:b2:4d:b7:04:a9:84:a3:32:af:ae:ee: - 6b:17:8b:b2:b1:fe:6c:e1:90:8c:88:a8:97:48:ce: - c8:4d:cb:f3:06:cf:5f:6a:0a:42:b1:1e:1e:77:2f: - 8e:a0:e6:92:0e:06:fc:05:22:d2:26:e1:31:51:7d: - 32:dc:0f - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Key Usage: critical - Certificate Sign, CRL Sign - X509v3 Basic Constraints: critical - CA:TRUE - Signature Algorithm: sha256WithRSAEncryption - 5f:34:81:76:ef:96:1d:d5:e5:b5:d9:02:63:84:16:c1:ae:a0: - 70:51:a7:f7:4c:47:35:c8:0b:d7:28:3d:89:71:d9:aa:33:41: - ea:14:1b:6c:21:00:c0:6c:42:19:7e:9f:69:5b:20:42:df:a2: - d2:da:c4:7c:97:4b:8d:b0:e8:ac:c8:ee:a5:69:04:99:0a:92: - a6:ab:27:2e:1a:4d:81:bf:84:d4:70:1e:ad:47:fe:fd:4a:9d: - 33:e0:f2:b9:c4:45:08:21:0a:da:69:69:73:72:0d:be:34:fe: - 94:8b:ad:c3:1e:35:d7:a2:83:ef:e5:38:c7:a5:85:1f:ab:cf: - 34:ec:3f:28:fe:0c:f1:57:86:4e:c9:55:f7:1c:d4:d8:a5:7d: - 06:7a:6f:d5:df:10:df:81:4e:21:65:b1:b6:e1:17:79:95:45: - 06:ce:5f:cc:dc:46:89:63:68:44:8d:93:f4:64:70:a0:3d:9d: - 28:05:c3:39:70:b8:62:7b:20:fd:e4:db:e9:08:a1:b8:9e:3d: - 09:c7:4f:fb:2c:f8:93:76:41:de:52:e0:e1:57:d2:9d:03:bc: - 77:9e:fe:9e:29:5e:f7:c1:51:60:1f:de:da:0b:b2:2d:75:b7: - 43:48:93:e7:f6:79:c6:84:5d:80:59:60:94:fc:78:98:8f:3c: - 93:51:ed:40:90:07:df:64:63:24:cb:4e:71:05:a1:d7:94:1a: - 88:32:f1:22:74:22:ae:a5:a6:d8:12:69:4c:60:a3:02:ee:2b: - ec:d4:63:92:0b:5e:be:2f:76:6b:a3:b6:26:bc:8f:03:d8:0a: - f2:4c:64:46:bd:39:62:e5:96:eb:34:63:11:28:cc:95:f1:ad: - ef:ef:dc:80:58:48:e9:4b:b8:ea:65:ac:e9:fc:80:b5:b5:c8: - 45:f9:ac:c1:9f:d9:b9:ea:62:88:8e:c4:f1:4b:83:12:ad:e6: - 8b:84:d6:9e:c2:eb:83:18:9f:6a:bb:1b:24:60:33:70:cc:ec: - f7:32:f3:5c:d9:79:7d:ef:9e:a4:fe:c9:23:c3:24:ee:15:92: - b1:3d:91:4f:26:86:bd:66:73:24:13:ea:a4:ae:63:c1:ad:7d: - 84:03:3c:10:78:86:1b:79:e3:c4:f3:f2:04:95:20:ae:23:82: - c4:b3:3a:00:62:bf:e6:36:24:e1:57:ba:c7:1e:90:75:d5:5f: - 3f:95:61:2b:c1:3b:cd:e5:b3:68:61:d0:46:26:a9:21:52:69: - 2d:eb:2e:c7:eb:77:ce:a6:3a:b5:03:33:4f:76:d1:e7:5c:54: - 01:5d:cb:78:f4:c9:0c:bf:cf:12:8e:17:2d:23:68:94:e7:ab: - fe:a9:b2:2b:06:d0:04:cd ------BEGIN CERTIFICATE----- -MIIFQTCCAymgAwIBAgICDL4wDQYJKoZIhvcNAQELBQAwUTELMAkGA1UEBhMCVFcx -EjAQBgNVBAoTCVRBSVdBTi1DQTEQMA4GA1UECxMHUm9vdCBDQTEcMBoGA1UEAxMT -VFdDQSBHbG9iYWwgUm9vdCBDQTAeFw0xMjA2MjcwNjI4MzNaFw0zMDEyMzExNTU5 -NTlaMFExCzAJBgNVBAYTAlRXMRIwEAYDVQQKEwlUQUlXQU4tQ0ExEDAOBgNVBAsT -B1Jvb3QgQ0ExHDAaBgNVBAMTE1RXQ0EgR2xvYmFsIFJvb3QgQ0EwggIiMA0GCSqG -SIb3DQEBAQUAA4ICDwAwggIKAoICAQCwBdvI64zEbooh745NnHEKH1Jw7W2CnJfF -10xORUnLQEK1EjRsGcJ0pDFfhQKX7EMzClPSnIyOt7h52yvVavKOZsTuKwEHktSz -0ALfUPZVr2YOy+BHYC8rMjk1Ujoog/h7FsYYuGLWRyWRzvAZEk2tY/XTP3VfKfCh -MBwqoJimFb3u/Rk28OKRQ4/6ytYQJ0lM793B8YVwm8rqqFpD/G2Gb3PpN0Wp8DbH -zIh1HrtsBv+baz4X7GGqcXzGHaL3SekVtTzWoWH1EfcFbx39Eb7QMAfCKbAJTibc -46KokWofwpFFiFzlmLhxpRUZyXx1EcxwdE8tmx2RRP1WKKD+u4ZqyPpcC1jcxkt2 -yKsi2XMPpfRaAok/T54igu6idFMqPVMnaR1sjjIsZAAmY2E2TqNGtz99sy2sbZCi -laLOz9qC5wc0GZbpuCGqKX6mOL6OKUohZnkfs8O1CWfe1tQHRvMq2uYiN2DLgbYP -oA/pyJV/v1WRBXrPPRXAb94JlAGD1zQbzECl8LibZ9WYkTunhHiVJqRaCPgrdLQA -BDzfuBSO6N+pjWxnkjMdwLfS7JLIvgm/LCkFbwJrnu+8vyq8W8BQj0FwcYeyTbcE -qYSjMq+u7msXi7Kx/mzhkIyIqJdIzshNy/MGz19qCkKxHh53L46g5pIOBvwFItIm -4TFRfTLcDwIDAQABoyMwITAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/BAUwAwEB -/zANBgkqhkiG9w0BAQsFAAOCAgEAXzSBdu+WHdXltdkCY4QWwa6gcFGn90xHNcgL -1yg9iXHZqjNB6hQbbCEAwGxCGX6faVsgQt+i0trEfJdLjbDorMjupWkEmQqSpqsn -LhpNgb+E1HAerUf+/UqdM+DyucRFCCEK2mlpc3INvjT+lIutwx4116KD7+U4x6WF -H6vPNOw/KP4M8VeGTslV9xzU2KV9Bnpv1d8Q34FOIWWxtuEXeZVFBs5fzNxGiWNo -RI2T9GRwoD2dKAXDOXC4Ynsg/eTb6QihuJ49CcdP+yz4k3ZB3lLg4VfSnQO8d57+ -nile98FRYB/e2guyLXW3Q0iT5/Z5xoRdgFlglPx4mI88k1HtQJAH32RjJMtOcQWh -15QaiDLxInQirqWm2BJpTGCjAu4r7NRjkgtevi92a6O2JryPA9gK8kxkRr05YuWW -6zRjESjMlfGt7+/cgFhI6Uu46mWs6fyAtbXIRfmswZ/ZuepiiI7E8UuDEq3mi4TW -nsLrgxifarsbJGAzcMzs9zLzXNl5fe+epP7JI8Mk7hWSsT2RTyaGvWZzJBPqpK5j -wa19hAM8EHiGG3njxPPyBJUgriOCxLM6AGK/5jYk4Ve6xx6QddVfP5VhK8E7zeWz -aGHQRiapIVJpLesux+t3zqY6tQMzT3bR51xUAV3LePTJDL/PEo4XLSNolOer/qmy -KwbQBM0= ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: 1 (0x1) - Signature Algorithm: sha1WithRSAEncryption - Issuer: C=TW, O=TAIWAN-CA, OU=Root CA, CN=TWCA Root Certification Authority - Validity - Not Before: Aug 28 07:24:33 2008 GMT - Not After : Dec 31 15:59:59 2030 GMT - Subject: C=TW, O=TAIWAN-CA, OU=Root CA, CN=TWCA Root Certification Authority - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (2048 bit) - Modulus: - 00:b0:7e:72:b8:a4:03:94:e6:a7:de:09:38:91:4a: - 11:40:87:a7:7c:59:64:14:7b:b5:11:10:dd:fe:bf: - d5:c0:bb:56:e2:85:25:f4:35:72:0f:f8:53:d0:41: - e1:44:01:c2:b4:1c:c3:31:42:16:47:85:33:22:76: - b2:0a:6f:0f:e5:25:50:4f:85:86:be:bf:98:2e:10: - 67:1e:be:11:05:86:05:90:c4:59:d0:7c:78:10:b0: - 80:5c:b7:e1:c7:2b:75:cb:7c:9f:ae:b5:d1:9d:23: - 37:63:a7:dc:42:a2:2d:92:04:1b:50:c1:7b:b8:3e: - 1b:c9:56:04:8b:2f:52:9b:ad:a9:56:e9:c1:ff:ad: - a9:58:87:30:b6:81:f7:97:45:fc:19:57:3b:2b:6f: - e4:47:f4:99:45:fe:1d:f1:f8:97:a3:88:1d:37:1c: - 5c:8f:e0:76:25:9a:50:f8:a0:54:ff:44:90:76:23: - d2:32:c6:c3:ab:06:bf:fc:fb:bf:f3:ad:7d:92:62: - 02:5b:29:d3:35:a3:93:9a:43:64:60:5d:b2:fa:32: - ff:3b:04:af:4d:40:6a:f9:c7:e3:ef:23:fd:6b:cb: - e5:0f:8b:38:0d:ee:0a:fc:fe:0f:98:9f:30:31:dd: - 6c:52:65:f9:8b:81:be:22:e1:1c:58:03:ba:91:1b: - 89:07 - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Key Usage: critical - Certificate Sign, CRL Sign - X509v3 Basic Constraints: critical - CA:TRUE - X509v3 Subject Key Identifier: - 6A:38:5B:26:8D:DE:8B:5A:F2:4F:7A:54:83:19:18:E3:08:35:A6:BA - Signature Algorithm: sha1WithRSAEncryption - 3c:d5:77:3d:da:df:89:ba:87:0c:08:54:6a:20:50:92:be:b0: - 41:3d:b9:26:64:83:0a:2f:e8:40:c0:97:28:27:82:30:4a:c9: - 93:ff:6a:e7:a6:00:7f:89:42:9a:d6:11:e5:53:ce:2f:cc:f2: - da:05:c4:fe:e2:50:c4:3a:86:7d:cc:da:7e:10:09:3b:92:35: - 2a:53:b2:fe:eb:2b:05:d9:6c:5d:e6:d0:ef:d3:6a:66:9e:15: - 28:85:7a:e8:82:00:ac:1e:a7:09:69:56:42:d3:68:51:18:be: - 54:9a:bf:44:41:ba:49:be:20:ba:69:5c:ee:b8:77:cd:ce:6c: - 1f:ad:83:96:18:7d:0e:b5:14:39:84:f1:28:e9:2d:a3:9e:7b: - 1e:7a:72:5a:83:b3:79:6f:ef:b4:fc:d0:0a:a5:58:4f:46:df: - fb:6d:79:59:f2:84:22:52:ae:0f:cc:fb:7c:3b:e7:6a:ca:47: - 61:c3:7a:f8:d3:92:04:1f:b8:20:84:e1:36:54:16:c7:40:de: - 3b:8a:73:dc:df:c6:09:4c:df:ec:da:ff:d4:53:42:a1:c9:f2: - 62:1d:22:83:3c:97:c5:f9:19:62:27:ac:65:22:d7:d3:3c:c6: - e5:8e:b2:53:cc:49:ce:bc:30:fe:7b:0e:33:90:fb:ed:d2:14: - 91:1f:07:af ------BEGIN CERTIFICATE----- -MIIDezCCAmOgAwIBAgIBATANBgkqhkiG9w0BAQUFADBfMQswCQYDVQQGEwJUVzES -MBAGA1UECgwJVEFJV0FOLUNBMRAwDgYDVQQLDAdSb290IENBMSowKAYDVQQDDCFU -V0NBIFJvb3QgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNMDgwODI4MDcyNDMz -WhcNMzAxMjMxMTU1OTU5WjBfMQswCQYDVQQGEwJUVzESMBAGA1UECgwJVEFJV0FO -LUNBMRAwDgYDVQQLDAdSb290IENBMSowKAYDVQQDDCFUV0NBIFJvb3QgQ2VydGlm -aWNhdGlvbiBBdXRob3JpdHkwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIB -AQCwfnK4pAOU5qfeCTiRShFAh6d8WWQUe7UREN3+v9XAu1bihSX0NXIP+FPQQeFE -AcK0HMMxQhZHhTMidrIKbw/lJVBPhYa+v5guEGcevhEFhgWQxFnQfHgQsIBct+HH -K3XLfJ+utdGdIzdjp9xCoi2SBBtQwXu4PhvJVgSLL1KbralW6cH/ralYhzC2gfeX -RfwZVzsrb+RH9JlF/h3x+JejiB03HFyP4HYlmlD4oFT/RJB2I9IyxsOrBr/8+7/z -rX2SYgJbKdM1o5OaQ2RgXbL6Mv87BK9NQGr5x+PvI/1ry+UPizgN7gr8/g+YnzAx -3WxSZfmLgb4i4RxYA7qRG4kHAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV -HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRqOFsmjd6LWvJPelSDGRjjCDWmujANBgkq -hkiG9w0BAQUFAAOCAQEAPNV3PdrfibqHDAhUaiBQkr6wQT25JmSDCi/oQMCXKCeC -MErJk/9q56YAf4lCmtYR5VPOL8zy2gXE/uJQxDqGfczafhAJO5I1KlOy/usrBdls -XebQ79NqZp4VKIV66IIArB6nCWlWQtNoURi+VJq/REG6Sb4gumlc7rh3zc5sH62D -lhh9DrUUOYTxKOkto557HnpyWoOzeW/vtPzQCqVYT0bf+215WfKEIlKuD8z7fDvn -aspHYcN6+NOSBB+4IIThNlQWx0DeO4pz3N/GCUzf7Nr/1FNCocnyYh0igzyXxfkZ -YiesZSLX0zzG5Y6yU8xJzrww/nsOM5D77dIUkR8Hrw== ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: - 1f:9d:59:5a:d7:2f:c2:06:44:a5:80:08:69:e3:5e:f6 - Signature Algorithm: sha1WithRSAEncryption - Issuer: C=TW, O=Government Root Certification Authority - Validity - Not Before: Dec 5 13:23:33 2002 GMT - Not After : Dec 5 13:23:33 2032 GMT - Subject: C=TW, O=Government Root Certification Authority - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (4096 bit) - Modulus: - 00:9a:25:b8:ec:cc:a2:75:a8:7b:f7:ce:5b:59:8a: - c9:d1:86:12:08:54:ec:9c:f2:e7:46:f6:88:f3:7c: - e9:a5:df:4c:47:36:a4:1b:01:1c:7f:1e:57:8a:8d: - c3:c5:d1:21:e3:da:24:3f:48:2b:fb:9f:2e:a1:94: - e7:2c:1c:93:d1:bf:1b:01:87:53:99:ce:a7:f5:0a: - 21:76:77:ff:a9:b7:c6:73:94:4f:46:f7:10:49:37: - fa:a8:59:49:5d:6a:81:07:56:f2:8a:f9:06:d0:f7: - 70:22:4d:b4:b7:41:b9:32:b8:b1:f0:b1:c3:9c:3f: - 70:fd:53:dd:81:aa:d8:63:78:f6:d8:53:6e:a1:ac: - 6a:84:24:72:54:86:c6:d2:b2:ca:1c:0e:79:81:d6: - b5:70:62:08:01:2e:4e:4f:0e:d5:11:af:a9:af:e5: - 9a:bf:dc:cc:87:6d:26:e4:c9:57:a2:fb:96:f9:cc: - e1:3f:53:8c:6c:4c:7e:9b:53:08:0b:6c:17:fb:67: - c8:c2:ad:b1:cd:80:b4:97:dc:76:01:16:15:e9:6a: - d7:a4:e1:78:47:ce:86:d5:fb:31:f3:fa:31:be:34: - aa:28:fb:70:4c:1d:49:c7:af:2c:9d:6d:66:a6:b6: - 8d:64:7e:b5:20:6a:9d:3b:81:b6:8f:40:00:67:4b: - 89:86:b8:cc:65:fe:15:53:e9:04:c1:d6:5f:1d:44: - d7:0a:2f:27:9a:46:7d:a1:0d:75:ad:54:86:15:dc: - 49:3b:f1:96:ce:0f:9b:a0:ec:a3:7a:5d:be:d5:2a: - 75:42:e5:7b:de:a5:b6:aa:af:28:ac:ac:90:ac:38: - b7:d5:68:35:26:7a:dc:f7:3b:f3:fd:45:9b:d1:bb: - 43:78:6e:6f:f1:42:54:6a:98:f0:0d:ad:97:e9:52: - 5e:e9:d5:6a:72:de:6a:f7:1b:60:14:f4:a5:e4:b6: - 71:67:aa:1f:ea:e2:4d:c1:42:40:fe:67:46:17:38: - 2f:47:3f:71:9c:ae:e5:21:ca:61:2d:6d:07:a8:84: - 7c:2d:ee:51:25:f1:63:90:9e:fd:e1:57:88:6b:ef: - 8a:23:6d:b1:e6:bd:3f:ad:d1:3d:96:0b:85:8d:cd: - 6b:27:bb:b7:05:9b:ec:bb:91:a9:0a:07:12:02:97: - 4e:20:90:f0:ff:0d:1e:e2:41:3b:d3:40:3a:e7:8d: - 5d:da:66:e4:02:b0:07:52:98:5c:0e:8e:33:9c:c2: - a6:95:fb:55:19:6e:4c:8e:ae:4b:0f:bd:c1:38:4d: - 5e:8f:84:1d:66:cd:c5:60:96:b4:52:5a:05:89:8e: - 95:7a:98:c1:91:3c:95:23:b2:0e:f4:79:b4:c9:7c: - c1:4a:21 - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Subject Key Identifier: - CC:CC:EF:CC:29:60:A4:3B:B1:92:B6:3C:FA:32:62:8F:AC:25:15:3B - X509v3 Basic Constraints: - CA:TRUE - setCext-hashedRoot: - 0/0-...0...+......0...g*........"...(6....2.1:.Qe - Signature Algorithm: sha1WithRSAEncryption - 40:80:4a:fa:26:c9:ce:5e:30:dd:4f:86:74:76:58:f5:ae:b3: - 83:33:78:a4:7a:74:17:19:4e:e9:52:b5:b9:e0:0a:74:62:aa: - 68:ca:78:a0:4c:9a:8e:2c:23:2e:d5:6a:12:24:bf:d4:68:d3: - 8a:d0:d8:9c:9f:b4:1f:0c:de:38:7e:57:38:fc:8d:e2:4f:5e: - 0c:9f:ab:3b:d2:ff:75:97:cb:a4:e3:67:08:ff:e5:c0:16:b5: - 48:01:7d:e9:f9:0a:ff:1b:e5:6a:69:bf:78:21:a8:c2:a7:23: - a9:86:ab:76:56:e8:0e:0c:f6:13:dd:2a:66:8a:64:49:3d:1a: - 18:87:90:04:9f:42:52:b7:4f:cb:fe:47:41:76:35:ef:ff:00: - 76:36:45:32:9b:c6:46:85:5d:e2:24:b0:1e:e3:48:96:98:57: - 47:94:55:7a:0f:41:b1:44:24:f3:c1:fe:1a:6b:bf:88:fd:c1: - a6:da:93:60:5e:81:4a:99:20:9c:48:66:19:b5:00:79:54:0f: - b8:2c:2f:4b:bc:a9:5d:5b:60:7f:8c:87:a5:e0:52:63:2a:be: - d8:3b:85:40:15:fe:1e:b6:65:3f:c5:4b:da:7e:b5:7a:35:29: - a3:2e:7a:98:60:22:a3:f4:7d:27:4e:2d:ea:b4:74:3c:e9:0f: - a4:33:0f:10:11:bc:13:01:d6:e5:0e:d3:bf:b5:12:a2:e1:45: - 23:c0:cc:08:6e:61:b7:89:ab:83:e3:24:1e:e6:5d:07:e7:1f: - 20:3e:cf:67:c8:e7:ac:30:6d:27:4b:68:6e:4b:2a:5c:02:08: - 34:db:f8:76:e4:67:a3:26:9c:3f:a2:32:c2:4a:c5:81:18:31: - 10:56:aa:84:ef:2d:0a:ff:b8:1f:77:d2:bf:a5:58:a0:62:e4: - d7:4b:91:75:8d:89:80:98:7e:6d:cb:53:4e:5e:af:f6:b2:97: - 85:97:b9:da:55:06:b9:24:ee:d7:c6:38:1e:63:1b:12:3b:95: - e1:58:ac:f2:df:84:d5:5f:99:2f:0d:55:5b:e6:38:db:2e:3f: - 72:e9:48:85:cb:bb:29:13:8f:1e:38:55:b9:f3:b2:c4:30:99: - 23:4e:5d:f2:48:a1:12:0c:dc:12:90:09:90:54:91:03:3c:47: - e5:d5:c9:65:e0:b7:4b:7d:ec:47:d3:b3:0b:3e:ad:9e:d0:74: - 00:0e:eb:bd:51:ad:c0:de:2c:c0:c3:6a:fe:ef:dc:0b:a7:fa: - 46:df:60:db:9c:a6:59:50:75:23:69:73:93:b2:f9:fc:02:d3: - 47:e6:71:ce:10:02:ee:27:8c:84:ff:ac:45:0d:13:5c:83:32: - e0:25:a5:86:2c:7c:f4:12 ------BEGIN CERTIFICATE----- -MIIFcjCCA1qgAwIBAgIQH51ZWtcvwgZEpYAIaeNe9jANBgkqhkiG9w0BAQUFADA/ -MQswCQYDVQQGEwJUVzEwMC4GA1UECgwnR292ZXJubWVudCBSb290IENlcnRpZmlj -YXRpb24gQXV0aG9yaXR5MB4XDTAyMTIwNTEzMjMzM1oXDTMyMTIwNTEzMjMzM1ow -PzELMAkGA1UEBhMCVFcxMDAuBgNVBAoMJ0dvdmVybm1lbnQgUm9vdCBDZXJ0aWZp -Y2F0aW9uIEF1dGhvcml0eTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIB -AJoluOzMonWoe/fOW1mKydGGEghU7Jzy50b2iPN86aXfTEc2pBsBHH8eV4qNw8XR -IePaJD9IK/ufLqGU5ywck9G/GwGHU5nOp/UKIXZ3/6m3xnOUT0b3EEk3+qhZSV1q -gQdW8or5BtD3cCJNtLdBuTK4sfCxw5w/cP1T3YGq2GN49thTbqGsaoQkclSGxtKy -yhwOeYHWtXBiCAEuTk8O1RGvqa/lmr/czIdtJuTJV6L7lvnM4T9TjGxMfptTCAts -F/tnyMKtsc2AtJfcdgEWFelq16TheEfOhtX7MfP6Mb40qij7cEwdScevLJ1tZqa2 -jWR+tSBqnTuBto9AAGdLiYa4zGX+FVPpBMHWXx1E1wovJ5pGfaENda1UhhXcSTvx -ls4Pm6Dso3pdvtUqdULle96ltqqvKKyskKw4t9VoNSZ63Pc78/1Fm9G7Q3hub/FC -VGqY8A2tl+lSXunVanLeavcbYBT0peS2cWeqH+riTcFCQP5nRhc4L0c/cZyu5SHK -YS1tB6iEfC3uUSXxY5Ce/eFXiGvviiNtsea9P63RPZYLhY3Naye7twWb7LuRqQoH -EgKXTiCQ8P8NHuJBO9NAOueNXdpm5AKwB1KYXA6OM5zCppX7VRluTI6uSw+9wThN -Xo+EHWbNxWCWtFJaBYmOlXqYwZE8lSOyDvR5tMl8wUohAgMBAAGjajBoMB0GA1Ud -DgQWBBTMzO/MKWCkO7GStjz6MmKPrCUVOzAMBgNVHRMEBTADAQH/MDkGBGcqBwAE -MTAvMC0CAQAwCQYFKw4DAhoFADAHBgVnKgMAAAQUA5vwIhP/lSg209yewDL7MTqK -UWUwDQYJKoZIhvcNAQEFBQADggIBAECASvomyc5eMN1PhnR2WPWus4MzeKR6dBcZ -TulStbngCnRiqmjKeKBMmo4sIy7VahIkv9Ro04rQ2JyftB8M3jh+Vzj8jeJPXgyf -qzvS/3WXy6TjZwj/5cAWtUgBfen5Cv8b5Wppv3ghqMKnI6mGq3ZW6A4M9hPdKmaK -ZEk9GhiHkASfQlK3T8v+R0F2Ne//AHY2RTKbxkaFXeIksB7jSJaYV0eUVXoPQbFE -JPPB/hprv4j9wabak2BegUqZIJxIZhm1AHlUD7gsL0u8qV1bYH+Mh6XgUmMqvtg7 -hUAV/h62ZT/FS9p+tXo1KaMuephgIqP0fSdOLeq0dDzpD6QzDxARvBMB1uUO07+1 -EqLhRSPAzAhuYbeJq4PjJB7mXQfnHyA+z2fI56wwbSdLaG5LKlwCCDTb+HbkZ6Mm -nD+iMsJKxYEYMRBWqoTvLQr/uB930r+lWKBi5NdLkXWNiYCYfm3LU05er/ayl4WX -udpVBrkk7tfGOB5jGxI7leFYrPLfhNVfmS8NVVvmONsuP3LpSIXLuykTjx44Vbnz -ssQwmSNOXfJIoRIM3BKQCZBUkQM8R+XVyWXgt0t97EfTsws+rZ7QdAAO671RrcDe -LMDDav7v3Aun+kbfYNucpllQdSNpc5Oy+fwC00fmcc4QAu4njIT/rEUNE1yDMuAl -pYYsfPQS ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: - 95:be:16:a0:f7:2e:46:f1:7b:39:82:72:fa:8b:cd:96 - Signature Algorithm: sha1WithRSAEncryption - Issuer: O=TeliaSonera, CN=TeliaSonera Root CA v1 - Validity - Not Before: Oct 18 12:00:50 2007 GMT - Not After : Oct 18 12:00:50 2032 GMT - Subject: O=TeliaSonera, CN=TeliaSonera Root CA v1 - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (4096 bit) - Modulus: - 00:c2:be:eb:27:f0:21:a3:f3:69:26:55:7e:9d:c5: - 55:16:91:5c:fd:ef:21:bf:53:80:7a:2d:d2:91:8c: - 63:31:f0:ec:24:f0:c3:a5:d2:72:7c:10:6d:f4:37: - b7:e5:e6:7c:79:ea:8c:b5:82:8b:ae:48:b6:ac:00: - dc:65:75:ec:2a:4d:5f:c1:87:f5:20:65:2b:81:a8: - 47:3e:89:23:95:30:16:90:7f:e8:57:07:48:e7:19: - ae:bf:45:67:b1:37:1b:06:2a:fe:de:f9:ac:7d:83: - fb:5e:ba:e4:8f:97:67:be:4b:8e:8d:64:07:57:38: - 55:69:34:36:3d:13:48:ef:4f:e2:d3:66:1e:a4:cf: - 1a:b7:5e:36:33:d4:b4:06:bd:18:01:fd:77:84:50: - 00:45:f5:8c:5d:e8:23:bc:7e:fe:35:e1:ed:50:7b: - a9:30:8d:19:d3:09:8e:68:67:5d:bf:3c:97:18:53: - bb:29:62:c5:ca:5e:72:c1:c7:96:d4:db:2d:a0:b4: - 1f:69:03:ec:ea:e2:50:f1:0c:3c:f0:ac:f3:53:2d: - f0:1c:f5:ed:6c:39:39:73:80:16:c8:52:b0:23:cd: - e0:3e:dc:dd:3c:47:a0:bb:35:8a:e2:98:68:8b:be: - e5:bf:72:ee:d2:fa:a5:ed:12:ed:fc:98:18:a9:26: - 76:dc:28:4b:10:20:1c:d3:7f:16:77:2d:ed:6f:80: - f7:49:bb:53:05:bb:5d:68:c7:d4:c8:75:16:3f:89: - 5a:8b:f7:17:47:d4:4c:f1:d2:89:79:3e:4d:3d:98: - a8:61:de:3a:1e:d2:f8:5e:03:e0:c1:c9:1c:8c:d3: - 8d:4d:d3:95:36:b3:37:5f:63:63:9b:33:14:f0:2d: - 26:6b:53:7c:89:8c:32:c2:6e:ec:3d:21:00:39:c9: - a1:68:e2:50:83:2e:b0:3a:2b:f3:36:a0:ac:2f:e4: - 6f:61:c2:51:09:39:3e:8b:53:b9:bb:67:da:dc:53: - b9:76:59:36:9d:43:e5:20:e0:3d:32:60:85:22:51: - b7:c7:33:bb:dd:15:2f:a4:78:a6:07:7b:81:46:36: - 04:86:dd:79:35:c7:95:2c:3b:b0:a3:17:35:e5:73: - 1f:b4:5c:59:ef:da:ea:10:65:7b:7a:d0:7f:9f:b3: - b4:2a:37:3b:70:8b:9b:5b:b9:2b:b7:ec:b2:51:12: - 97:53:29:5a:d4:f0:12:10:dc:4f:02:bb:12:92:2f: - 62:d4:3f:69:43:7c:0d:d6:fc:58:75:01:88:9d:58: - 16:4b:de:ba:90:ff:47:01:89:06:6a:f6:5f:b2:90: - 6a:b3:02:a6:02:88:bf:b3:47:7e:2a:d9:d5:fa:68: - 78:35:4d - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Basic Constraints: critical - CA:TRUE - X509v3 Key Usage: - Certificate Sign, CRL Sign - X509v3 Subject Key Identifier: - F0:8F:59:38:00:B3:F5:8F:9A:96:0C:D5:EB:FA:7B:AA:17:E8:13:12 - Signature Algorithm: sha1WithRSAEncryption - be:e4:5c:62:4e:24:f4:0c:08:ff:f0:d3:0c:68:e4:93:49:22: - 3f:44:27:6f:bb:6d:de:83:66:ce:a8:cc:0d:fc:f5:9a:06:e5: - 77:14:91:eb:9d:41:7b:99:2a:84:e5:ff:fc:21:c1:5d:f0:e4: - 1f:57:b7:75:a9:a1:5f:02:26:ff:d7:c7:f7:4e:de:4f:f8:f7: - 1c:46:c0:7a:4f:40:2c:22:35:f0:19:b1:d0:6b:67:2c:b0:a8: - e0:c0:40:37:35:f6:84:5c:5c:e3:af:42:78:fe:a7:c9:0d:50: - ea:0d:84:76:f6:51:ef:83:53:c6:7a:ff:0e:56:49:2e:8f:7a: - d6:0c:e6:27:54:e3:4d:0a:60:72:62:cd:91:07:d6:a5:bf:c8: - 99:6b:ed:c4:19:e6:ab:4c:11:38:c5:6f:31:e2:6e:49:c8:3f: - 76:80:26:03:26:29:e0:36:f6:f6:20:53:e3:17:70:34:17:9d: - 63:68:1e:6b:ec:c3:4d:86:b8:13:30:2f:5d:46:0d:47:43:d5: - 1b:aa:59:0e:b9:5c:8d:06:48:ad:74:87:5f:c7:fc:31:54:41: - 13:e2:c7:21:0e:9e:e0:1e:0d:e1:c0:7b:43:85:90:c5:8a:58: - c6:65:0a:78:57:f2:c6:23:0f:01:d9:20:4b:de:0f:fb:92:85: - 75:2a:5c:73:8d:6d:7b:25:91:ca:ee:45:ae:06:4b:00:cc:d3: - b1:59:50:da:3a:88:3b:29:43:46:5e:97:2b:54:ce:53:6f:8d: - 4a:e7:96:fa:bf:71:0e:42:8b:7c:fd:28:a0:d0:48:ca:da:c4: - 81:4c:bb:a2:73:93:26:c8:eb:0c:d6:26:88:b6:c0:24:cf:bb: - bd:5b:eb:75:7d:e9:08:8e:86:33:2c:79:77:09:69:a5:89:fc: - b3:70:90:87:76:8f:d3:22:bb:42:ce:bd:73:0b:20:26:2a:d0: - 9b:3d:70:1e:24:6c:cd:87:76:a9:17:96:b7:cf:0d:92:fb:8e: - 18:a9:98:49:d1:9e:fe:60:44:72:21:b9:19:ed:c2:f5:31:f1: - 39:48:88:90:24:75:54:16:ad:ce:f4:f8:69:14:64:39:fb:a3: - b8:ba:70:40:c7:27:1c:bf:c4:56:53:fa:63:65:d0:f3:1c:0e: - 16:f5:6b:86:58:4d:18:d4:e4:0d:8e:a5:9d:5b:91:dc:76:24: - 50:3f:c6:2a:fb:d9:b7:9c:b5:d6:e6:d0:d9:e8:19:8b:15:71: - 48:ad:b7:ea:d8:59:88:d4:90:bf:16:b3:d9:e9:ac:59:61:54: - c8:1c:ba:ca:c1:ca:e1:b9:20:4c:8f:3a:93:89:a5:a0:cc:bf: - d3:f6:75:a4:75:96:6d:56 ------BEGIN CERTIFICATE----- -MIIFODCCAyCgAwIBAgIRAJW+FqD3LkbxezmCcvqLzZYwDQYJKoZIhvcNAQEFBQAw -NzEUMBIGA1UECgwLVGVsaWFTb25lcmExHzAdBgNVBAMMFlRlbGlhU29uZXJhIFJv -b3QgQ0EgdjEwHhcNMDcxMDE4MTIwMDUwWhcNMzIxMDE4MTIwMDUwWjA3MRQwEgYD -VQQKDAtUZWxpYVNvbmVyYTEfMB0GA1UEAwwWVGVsaWFTb25lcmEgUm9vdCBDQSB2 -MTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAMK+6yfwIaPzaSZVfp3F -VRaRXP3vIb9TgHot0pGMYzHw7CTww6XScnwQbfQ3t+XmfHnqjLWCi65ItqwA3GV1 -7CpNX8GH9SBlK4GoRz6JI5UwFpB/6FcHSOcZrr9FZ7E3GwYq/t75rH2D+1665I+X -Z75Ljo1kB1c4VWk0Nj0TSO9P4tNmHqTPGrdeNjPUtAa9GAH9d4RQAEX1jF3oI7x+ -/jXh7VB7qTCNGdMJjmhnXb88lxhTuylixcpecsHHltTbLaC0H2kD7OriUPEMPPCs -81Mt8Bz17Ww5OXOAFshSsCPN4D7c3TxHoLs1iuKYaIu+5b9y7tL6pe0S7fyYGKkm -dtwoSxAgHNN/Fnct7W+A90m7UwW7XWjH1Mh1Fj+JWov3F0fUTPHSiXk+TT2YqGHe -Oh7S+F4D4MHJHIzTjU3TlTazN19jY5szFPAtJmtTfImMMsJu7D0hADnJoWjiUIMu -sDor8zagrC/kb2HCUQk5PotTubtn2txTuXZZNp1D5SDgPTJghSJRt8czu90VL6R4 -pgd7gUY2BIbdeTXHlSw7sKMXNeVzH7RcWe/a6hBle3rQf5+ztCo3O3CLm1u5K7fs -slESl1MpWtTwEhDcTwK7EpIvYtQ/aUN8Ddb8WHUBiJ1YFkveupD/RwGJBmr2X7KQ -arMCpgKIv7NHfirZ1fpoeDVNAgMBAAGjPzA9MA8GA1UdEwEB/wQFMAMBAf8wCwYD -VR0PBAQDAgEGMB0GA1UdDgQWBBTwj1k4ALP1j5qWDNXr+nuqF+gTEjANBgkqhkiG -9w0BAQUFAAOCAgEAvuRcYk4k9AwI//DTDGjkk0kiP0Qnb7tt3oNmzqjMDfz1mgbl -dxSR651Be5kqhOX//CHBXfDkH1e3damhXwIm/9fH907eT/j3HEbAek9ALCI18Bmx -0GtnLLCo4MBANzX2hFxc469CeP6nyQ1Q6g2EdvZR74NTxnr/DlZJLo961gzmJ1Tj -TQpgcmLNkQfWpb/ImWvtxBnmq0wROMVvMeJuScg/doAmAyYp4Db29iBT4xdwNBed -Y2gea+zDTYa4EzAvXUYNR0PVG6pZDrlcjQZIrXSHX8f8MVRBE+LHIQ6e4B4N4cB7 -Q4WQxYpYxmUKeFfyxiMPAdkgS94P+5KFdSpcc41teyWRyu5FrgZLAMzTsVlQ2jqI -OylDRl6XK1TOU2+NSueW+r9xDkKLfP0ooNBIytrEgUy7onOTJsjrDNYmiLbAJM+7 -vVvrdX3pCI6GMyx5dwlppYn8s3CQh3aP0yK7Qs69cwsgJirQmz1wHiRszYd2qReW -t88NkvuOGKmYSdGe/mBEciG5Ge3C9THxOUiIkCR1VBatzvT4aRRkOfujuLpwQMcn -HL/EVlP6Y2XQ8xwOFvVrhlhNGNTkDY6lnVuR3HYkUD/GKvvZt5y11ubQ2egZixVx -SK236thZiNSQvxaz2emsWWFUyBy6ysHK4bkgTI86k4mloMy/0/Z1pHWWbVY= ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: - 1b:1f:ad:b6:20:f9:24:d3:36:6b:f7:c7:f1:8c:a0:59 - Signature Algorithm: sha1WithRSAEncryption - Issuer: C=GB, O=Trustis Limited, OU=Trustis FPS Root CA - Validity - Not Before: Dec 23 12:14:06 2003 GMT - Not After : Jan 21 11:36:54 2024 GMT - Subject: C=GB, O=Trustis Limited, OU=Trustis FPS Root CA - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (2048 bit) - Modulus: - 00:c5:50:7b:9e:3b:35:d0:df:c4:8c:cd:8e:9b:ed: - a3:c0:36:99:f4:42:ea:a7:3e:80:83:0f:a6:a7:59: - 87:c9:90:45:43:7e:00:ea:86:79:2a:03:bd:3d:37: - 99:89:66:b7:e5:8a:56:86:93:9c:68:4b:68:04:8c: - 93:93:02:3e:30:d2:37:3a:22:61:89:1c:85:4e:7d: - 8f:d5:af:7b:35:f6:7e:28:47:89:31:dc:0e:79:64: - 1f:99:d2:5b:ba:fe:7f:60:bf:ad:eb:e7:3c:38:29: - 6a:2f:e5:91:0b:55:ff:ec:6f:58:d5:2d:c9:de:4c: - 66:71:8f:0c:d7:04:da:07:e6:1e:18:e3:bd:29:02: - a8:fa:1c:e1:5b:b9:83:a8:41:48:bc:1a:71:8d:e7: - 62:e5:2d:b2:eb:df:7c:cf:db:ab:5a:ca:31:f1:4c: - 22:f3:05:13:f7:82:f9:73:79:0c:be:d7:4b:1c:c0: - d1:15:3c:93:41:64:d1:e6:be:23:17:22:00:89:5e: - 1f:6b:a5:ac:6e:a7:4b:8c:ed:a3:72:e6:af:63:4d: - 2f:85:d2:14:35:9a:2e:4e:8c:ea:32:98:28:86:a1: - 91:09:41:3a:b4:e1:e3:f2:fa:f0:c9:0a:a2:41:dd: - a9:e3:03:c7:88:15:3b:1c:d4:1a:94:d7:9f:64:59: - 12:6d - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Basic Constraints: critical - CA:TRUE - X509v3 Authority Key Identifier: - keyid:BA:FA:71:25:79:8B:57:41:25:21:86:0B:71:EB:B2:64:0E:8B:21:67 - - X509v3 Subject Key Identifier: - BA:FA:71:25:79:8B:57:41:25:21:86:0B:71:EB:B2:64:0E:8B:21:67 - Signature Algorithm: sha1WithRSAEncryption - 7e:58:ff:fd:35:19:7d:9c:18:4f:9e:b0:2b:bc:8e:8c:14:ff: - 2c:a0:da:47:5b:c3:ef:81:2d:af:05:ea:74:48:5b:f3:3e:4e: - 07:c7:6d:c5:b3:93:cf:22:35:5c:b6:3f:75:27:5f:09:96:cd: - a0:fe:be:40:0c:5c:12:55:f8:93:82:ca:29:e9:5e:3f:56:57: - 8b:38:36:f7:45:1a:4c:28:cd:9e:41:b8:ed:56:4c:84:a4:40: - c8:b8:b0:a5:2b:69:70:04:6a:c3:f8:d4:12:32:f9:0e:c3:b1: - dc:32:84:44:2c:6f:cb:46:0f:ea:66:41:0f:4f:f1:58:a5:a6: - 0d:0d:0f:61:de:a5:9e:5d:7d:65:a1:3c:17:e7:a8:55:4e:ef: - a0:c7:ed:c6:44:7f:54:f5:a3:e0:8f:f0:7c:55:22:8f:29:b6: - 81:a3:e1:6d:4e:2c:1b:80:67:ec:ad:20:9f:0c:62:61:d5:97: - ff:43:ed:2d:c1:da:5d:29:2a:85:3f:ac:65:ee:86:0f:05:8d: - 90:5f:df:ee:9f:f4:bf:ee:1d:fb:98:e4:7f:90:2b:84:78:10: - 0e:6c:49:53:ef:15:5b:65:46:4a:5d:af:ba:fb:3a:72:1d:cd: - f6:25:88:1e:97:cc:21:9c:29:01:0d:65:eb:57:d9:f3:57:96: - bb:48:cd:81 ------BEGIN CERTIFICATE----- -MIIDZzCCAk+gAwIBAgIQGx+ttiD5JNM2a/fH8YygWTANBgkqhkiG9w0BAQUFADBF -MQswCQYDVQQGEwJHQjEYMBYGA1UEChMPVHJ1c3RpcyBMaW1pdGVkMRwwGgYDVQQL -ExNUcnVzdGlzIEZQUyBSb290IENBMB4XDTAzMTIyMzEyMTQwNloXDTI0MDEyMTEx -MzY1NFowRTELMAkGA1UEBhMCR0IxGDAWBgNVBAoTD1RydXN0aXMgTGltaXRlZDEc -MBoGA1UECxMTVHJ1c3RpcyBGUFMgUm9vdCBDQTCCASIwDQYJKoZIhvcNAQEBBQAD -ggEPADCCAQoCggEBAMVQe547NdDfxIzNjpvto8A2mfRC6qc+gIMPpqdZh8mQRUN+ -AOqGeSoDvT03mYlmt+WKVoaTnGhLaASMk5MCPjDSNzoiYYkchU59j9WvezX2fihH -iTHcDnlkH5nSW7r+f2C/revnPDgpai/lkQtV/+xvWNUtyd5MZnGPDNcE2gfmHhjj -vSkCqPoc4Vu5g6hBSLwacY3nYuUtsuvffM/bq1rKMfFMIvMFE/eC+XN5DL7XSxzA -0RU8k0Fk0ea+IxciAIleH2ulrG6nS4zto3Lmr2NNL4XSFDWaLk6M6jKYKIahkQlB -OrTh4/L68MkKokHdqeMDx4gVOxzUGpTXn2RZEm0CAwEAAaNTMFEwDwYDVR0TAQH/ -BAUwAwEB/zAfBgNVHSMEGDAWgBS6+nEleYtXQSUhhgtx67JkDoshZzAdBgNVHQ4E -FgQUuvpxJXmLV0ElIYYLceuyZA6LIWcwDQYJKoZIhvcNAQEFBQADggEBAH5Y//01 -GX2cGE+esCu8jowU/yyg2kdbw++BLa8F6nRIW/M+TgfHbcWzk88iNVy2P3UnXwmW -zaD+vkAMXBJV+JOCyinpXj9WV4s4NvdFGkwozZ5BuO1WTISkQMi4sKUraXAEasP4 -1BIy+Q7DsdwyhEQsb8tGD+pmQQ9P8Vilpg0ND2HepZ5dfWWhPBfnqFVO76DH7cZE -f1T1o+CP8HxVIo8ptoGj4W1OLBuAZ+ytIJ8MYmHVl/9D7S3B2l0pKoU/rGXuhg8F -jZBf3+6f9L/uHfuY5H+QK4R4EA5sSVPvFVtlRkpdr7r7OnIdzfYliB6XzCGcKQEN -ZetX2fNXlrtIzYE= ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: 17 (0x11) - Signature Algorithm: sha1WithRSAEncryption - Issuer: C=TR, L=Gebze - Kocaeli, O=T\xC3\xBCrkiye Bilimsel ve Teknolojik Ara\xC5\x9Ft\xC4\xB1rma Kurumu - T\xC3\x9CB\xC4\xB0TAK, OU=Ulusal Elektronik ve Kriptoloji Ara\xC5\x9Ft\xC4\xB1rma Enstit\xC3\xBCs\xC3\xBC - UEKAE, OU=Kamu Sertifikasyon Merkezi, CN=T\xC3\x9CB\xC4\xB0TAK UEKAE K\xC3\xB6k Sertifika Hizmet Sa\xC4\x9Flay\xC4\xB1c\xC4\xB1s\xC4\xB1 - S\xC3\xBCr\xC3\xBCm 3 - Validity - Not Before: Aug 24 11:37:07 2007 GMT - Not After : Aug 21 11:37:07 2017 GMT - Subject: C=TR, L=Gebze - Kocaeli, O=T\xC3\xBCrkiye Bilimsel ve Teknolojik Ara\xC5\x9Ft\xC4\xB1rma Kurumu - T\xC3\x9CB\xC4\xB0TAK, OU=Ulusal Elektronik ve Kriptoloji Ara\xC5\x9Ft\xC4\xB1rma Enstit\xC3\xBCs\xC3\xBC - UEKAE, OU=Kamu Sertifikasyon Merkezi, CN=T\xC3\x9CB\xC4\xB0TAK UEKAE K\xC3\xB6k Sertifika Hizmet Sa\xC4\x9Flay\xC4\xB1c\xC4\xB1s\xC4\xB1 - S\xC3\xBCr\xC3\xBCm 3 - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (2048 bit) - Modulus: - 00:8a:6d:4b:ff:10:88:3a:c3:f6:7e:94:e8:ea:20: - 64:70:ae:21:81:be:3a:7b:3c:db:f1:1d:52:7f:59: - fa:f3:22:4c:95:a0:90:bc:48:4e:11:ab:fb:b7:b5: - 8d:7a:83:28:8c:26:46:d8:4e:95:40:87:61:9f:c5: - 9e:6d:81:87:57:6c:8a:3b:b4:66:ea:cc:40:fc:e3: - aa:6c:b2:cb:01:db:32:bf:d2:eb:85:cf:a1:0d:55: - c3:5b:38:57:70:b8:75:c6:79:d1:14:30:ed:1b:58: - 5b:6b:ef:35:f2:a1:21:4e:c5:ce:7c:99:5f:6c:b9: - b8:22:93:50:a7:cd:4c:70:6a:be:6a:05:7f:13:9c: - 2b:1e:ea:fe:47:ce:04:a5:6f:ac:93:2e:7c:2b:9f: - 9e:79:13:91:e8:ea:9e:ca:38:75:8e:62:b0:95:93: - 2a:e5:df:e9:5e:97:6e:20:5f:5f:84:7a:44:39:19: - 40:1c:ba:55:2b:fb:30:b2:81:ef:84:e3:dc:ec:98: - 38:39:03:85:08:a9:54:03:05:29:f0:c9:8f:8b:ea: - 0b:86:65:19:11:d3:e9:09:23:de:68:93:03:c9:36: - 1c:21:6e:ce:8c:66:f1:99:30:d8:d7:b3:c3:1d:f8: - 81:2e:a8:bd:82:0b:66:fe:82:cb:e1:e0:1a:82:c3: - 40:81 - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Subject Key Identifier: - BD:88:87:C9:8F:F6:A4:0A:0B:AA:EB:C5:FE:91:23:9D:AB:4A:8A:32 - X509v3 Key Usage: critical - Certificate Sign, CRL Sign - X509v3 Basic Constraints: critical - CA:TRUE - Signature Algorithm: sha1WithRSAEncryption - 1d:7c:fa:49:8f:34:e9:b7:26:92:16:9a:05:74:e7:4b:d0:6d: - 39:6c:c3:26:f6:ce:b8:31:bc:c4:df:bc:2a:f8:37:91:18:dc: - 04:c8:64:99:2b:18:6d:80:03:59:c9:ae:f8:58:d0:3e:ed:c3: - 23:9f:69:3c:86:38:1c:9e:ef:da:27:78:d1:84:37:71:8a:3c: - 4b:39:cf:7e:45:06:d6:2d:d8:8a:4d:78:12:d6:ad:c2:d3:cb: - d2:d0:41:f3:26:36:4a:9b:95:6c:0c:ee:e5:d1:43:27:66:c1: - 88:f7:7a:b3:20:6c:ea:b0:69:2b:c7:20:e8:0c:03:c4:41:05: - 99:e2:3f:e4:6b:f8:a0:86:81:c7:84:c6:1f:d5:4b:81:12:b2: - 16:21:2c:13:a1:80:b2:5e:0c:4a:13:9e:20:d8:62:40:ab:90: - ea:64:4a:2f:ac:0d:01:12:79:45:a8:2f:87:19:68:c8:e2:85: - c7:30:b2:75:f9:38:3f:b2:c0:93:b4:6b:e2:03:44:ce:67:a0: - df:89:d6:ad:8c:76:a3:13:c3:94:61:2b:6b:d9:6c:c1:07:0a: - 22:07:85:6c:85:24:46:a9:be:3f:8b:78:84:82:7e:24:0c:9d: - fd:81:37:e3:25:a8:ed:36:4e:95:2c:c9:9c:90:da:ec:a9:42: - 3c:ad:b6:02 ------BEGIN CERTIFICATE----- -MIIFFzCCA/+gAwIBAgIBETANBgkqhkiG9w0BAQUFADCCASsxCzAJBgNVBAYTAlRS -MRgwFgYDVQQHDA9HZWJ6ZSAtIEtvY2FlbGkxRzBFBgNVBAoMPlTDvHJraXllIEJp -bGltc2VsIHZlIFRla25vbG9qaWsgQXJhxZ90xLFybWEgS3VydW11IC0gVMOcQsSw -VEFLMUgwRgYDVQQLDD9VbHVzYWwgRWxla3Ryb25payB2ZSBLcmlwdG9sb2ppIEFy -YcWfdMSxcm1hIEVuc3RpdMO8c8O8IC0gVUVLQUUxIzAhBgNVBAsMGkthbXUgU2Vy -dGlmaWthc3lvbiBNZXJrZXppMUowSAYDVQQDDEFUw5xCxLBUQUsgVUVLQUUgS8O2 -ayBTZXJ0aWZpa2EgSGl6bWV0IFNhxJ9sYXnEsWPEsXPEsSAtIFPDvHLDvG0gMzAe -Fw0wNzA4MjQxMTM3MDdaFw0xNzA4MjExMTM3MDdaMIIBKzELMAkGA1UEBhMCVFIx -GDAWBgNVBAcMD0dlYnplIC0gS29jYWVsaTFHMEUGA1UECgw+VMO8cmtpeWUgQmls -aW1zZWwgdmUgVGVrbm9sb2ppayBBcmHFn3TEsXJtYSBLdXJ1bXUgLSBUw5xCxLBU -QUsxSDBGBgNVBAsMP1VsdXNhbCBFbGVrdHJvbmlrIHZlIEtyaXB0b2xvamkgQXJh -xZ90xLFybWEgRW5zdGl0w7xzw7wgLSBVRUtBRTEjMCEGA1UECwwaS2FtdSBTZXJ0 -aWZpa2FzeW9uIE1lcmtlemkxSjBIBgNVBAMMQVTDnELEsFRBSyBVRUtBRSBLw7Zr -IFNlcnRpZmlrYSBIaXptZXQgU2HEn2xhecSxY8Sxc8SxIC0gU8O8csO8bSAzMIIB -IjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAim1L/xCIOsP2fpTo6iBkcK4h -gb46ezzb8R1Sf1n68yJMlaCQvEhOEav7t7WNeoMojCZG2E6VQIdhn8WebYGHV2yK -O7Rm6sxA/OOqbLLLAdsyv9Lrhc+hDVXDWzhXcLh1xnnRFDDtG1hba+818qEhTsXO -fJlfbLm4IpNQp81McGq+agV/E5wrHur+R84EpW+sky58K5+eeROR6Oqeyjh1jmKw -lZMq5d/pXpduIF9fhHpEORlAHLpVK/swsoHvhOPc7Jg4OQOFCKlUAwUp8MmPi+oL -hmUZEdPpCSPeaJMDyTYcIW7OjGbxmTDY17PDHfiBLqi9ggtm/oLL4eAagsNAgQID -AQABo0IwQDAdBgNVHQ4EFgQUvYiHyY/2pAoLquvF/pEjnatKijIwDgYDVR0PAQH/ -BAQDAgEGMA8GA1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcNAQEFBQADggEBAB18+kmP -NOm3JpIWmgV050vQbTlswyb2zrgxvMTfvCr4N5EY3ATIZJkrGG2AA1nJrvhY0D7t -wyOfaTyGOBye79oneNGEN3GKPEs5z35FBtYt2IpNeBLWrcLTy9LQQfMmNkqblWwM -7uXRQydmwYj3erMgbOqwaSvHIOgMA8RBBZniP+Rr+KCGgceExh/VS4ESshYhLBOh -gLJeDEoTniDYYkCrkOpkSi+sDQESeUWoL4cZaMjihccwsnX5OD+ywJO0a+IDRM5n -oN+J1q2MdqMTw5RhK2vZbMEHCiIHhWyFJEapvj+LeISCfiQMnf2BN+MlqO02TpUs -yZyQ2uypQjyttgI= ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: - 8e:17:fe:24:20:81 - Signature Algorithm: sha256WithRSAEncryption - Issuer: C=TR, L=Ankara, O=T\xC3\x9CRKTRUST Bilgi \xC4\xB0leti\xC5\x9Fim ve Bili\xC5\x9Fim G\xC3\xBCvenli\xC4\x9Fi Hizmetleri A.\xC5\x9E., CN=T\xC3\x9CRKTRUST Elektronik Sertifika Hizmet Sa\xC4\x9Flay\xC4\xB1c\xC4\xB1s\xC4\xB1 H5 - Validity - Not Before: Apr 30 08:07:01 2013 GMT - Not After : Apr 28 08:07:01 2023 GMT - Subject: C=TR, L=Ankara, O=T\xC3\x9CRKTRUST Bilgi \xC4\xB0leti\xC5\x9Fim ve Bili\xC5\x9Fim G\xC3\xBCvenli\xC4\x9Fi Hizmetleri A.\xC5\x9E., CN=T\xC3\x9CRKTRUST Elektronik Sertifika Hizmet Sa\xC4\x9Flay\xC4\xB1c\xC4\xB1s\xC4\xB1 H5 - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (2048 bit) - Modulus: - 00:a4:25:19:e1:65:9e:eb:48:21:50:4a:08:e5:11: - f0:5a:ba:26:ff:83:59:ce:44:2a:2f:fe:e1:ce:60: - 03:fc:8d:03:a5:ed:ff:6b:a8:ba:cc:34:06:9f:59: - 35:f6:ec:2c:bb:9d:fb:8d:52:69:e3:9c:27:10:53: - f3:a4:02:c5:a7:f9:11:1a:69:75:6e:c3:1d:8b:d1: - 98:8d:93:87:a7:71:97:0d:21:c7:99:f9:52:d3:2c: - 63:5d:55:bc:e8:1f:01:48:b9:60:fe:42:4a:f6:c8: - 80:ae:cd:66:7a:9e:45:8a:68:77:e2:48:68:9f:a2: - da:f1:e1:c1:10:9f:eb:3c:29:81:a7:e1:32:08:d4: - a0:05:b1:8c:fb:8d:96:00:0e:3e:25:df:53:86:22: - 3b:fc:f4:bd:f3:09:7e:77:ec:86:eb:0f:33:e5:43: - 4f:f4:54:75:6d:29:99:2e:66:5a:43:df:cb:5c:ca: - c8:e5:38:f1:7e:3b:35:9d:0f:f4:c5:5a:a1:cc:f3: - 20:80:24:d3:57:ec:15:ba:75:25:9b:e8:64:4b:b3: - 34:84:ef:04:b8:f6:c9:6c:aa:02:3e:b6:55:e2:32: - 37:5f:fc:66:97:5f:cd:d6:9e:c7:20:bf:4d:c6:ac: - 3f:75:5f:1c:ed:32:9c:7c:69:00:69:91:e3:23:18: - 53:e9 - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Subject Key Identifier: - 56:99:07:1E:D3:AC:0C:69:64:B4:0C:50:47:DE:43:2C:BE:20:C0:FB - X509v3 Key Usage: critical - Certificate Sign, CRL Sign - X509v3 Basic Constraints: critical - CA:TRUE - Signature Algorithm: sha256WithRSAEncryption - 9e:45:76:7b:17:48:32:f2:38:8b:29:bd:ee:96:4a:4e:81:18: - b1:51:47:20:cd:d0:64:b1:0e:c9:d9:01:d9:09:ce:c8:99:dc: - 68:25:13:d4:5c:f2:a3:e8:04:fe:72:09:c7:0b:aa:1d:25:55: - 7e:96:9a:57:b7:ba:c5:11:7a:19:e6:a7:7e:3d:85:0e:f5:f9: - 2e:29:2f:e7:f9:6c:58:16:57:50:25:f6:3e:2e:3e:aa:ed:77: - 71:aa:aa:99:96:46:0a:ae:8e:ec:2a:51:16:b0:5e:cd:ea:67: - 04:1c:58:30:f5:60:8a:bd:a6:bd:4d:e5:96:b4:fc:42:89:01: - 6b:f6:70:c8:50:39:0c:2d:d5:66:d9:c8:d2:b3:32:b7:1b:19: - 6d:cb:33:f9:df:a5:e6:15:84:37:f0:c2:f2:65:96:92:90:77: - f0:ad:f4:90:e9:11:78:d7:93:89:c0:3d:0b:ba:29:f4:e8:99: - 9d:72:8e:ed:9d:2f:ee:92:7d:a1:f1:ff:5d:ba:33:60:85:62: - fe:07:02:a1:84:56:46:be:96:0a:9a:13:d7:21:4c:b7:7c:07: - 9f:4e:4e:3f:91:74:fb:27:9d:11:cc:dd:e6:b1:ca:71:4d:13: - 17:39:26:c5:29:21:2b:93:29:6a:96:fa:ab:41:e1:4b:b6:35: - 0b:c0:9b:15 ------BEGIN CERTIFICATE----- -MIIEJzCCAw+gAwIBAgIHAI4X/iQggTANBgkqhkiG9w0BAQsFADCBsTELMAkGA1UE -BhMCVFIxDzANBgNVBAcMBkFua2FyYTFNMEsGA1UECgxEVMOcUktUUlVTVCBCaWxn -aSDEsGxldGnFn2ltIHZlIEJpbGnFn2ltIEfDvHZlbmxpxJ9pIEhpem1ldGxlcmkg -QS7Fni4xQjBABgNVBAMMOVTDnFJLVFJVU1QgRWxla3Ryb25payBTZXJ0aWZpa2Eg -SGl6bWV0IFNhxJ9sYXnEsWPEsXPEsSBINTAeFw0xMzA0MzAwODA3MDFaFw0yMzA0 -MjgwODA3MDFaMIGxMQswCQYDVQQGEwJUUjEPMA0GA1UEBwwGQW5rYXJhMU0wSwYD -VQQKDERUw5xSS1RSVVNUIEJpbGdpIMSwbGV0acWfaW0gdmUgQmlsacWfaW0gR8O8 -dmVubGnEn2kgSGl6bWV0bGVyaSBBLsWeLjFCMEAGA1UEAww5VMOcUktUUlVTVCBF -bGVrdHJvbmlrIFNlcnRpZmlrYSBIaXptZXQgU2HEn2xhecSxY8Sxc8SxIEg1MIIB -IjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEApCUZ4WWe60ghUEoI5RHwWrom -/4NZzkQqL/7hzmAD/I0Dpe3/a6i6zDQGn1k19uwsu537jVJp45wnEFPzpALFp/kR -Gml1bsMdi9GYjZOHp3GXDSHHmflS0yxjXVW86B8BSLlg/kJK9siArs1mep5Fimh3 -4khon6La8eHBEJ/rPCmBp+EyCNSgBbGM+42WAA4+Jd9ThiI7/PS98wl+d+yG6w8z -5UNP9FR1bSmZLmZaQ9/LXMrI5Tjxfjs1nQ/0xVqhzPMggCTTV+wVunUlm+hkS7M0 -hO8EuPbJbKoCPrZV4jI3X/xml1/N1p7HIL9Nxqw/dV8c7TKcfGkAaZHjIxhT6QID -AQABo0IwQDAdBgNVHQ4EFgQUVpkHHtOsDGlktAxQR95DLL4gwPswDgYDVR0PAQH/ -BAQDAgEGMA8GA1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcNAQELBQADggEBAJ5FdnsX -SDLyOIspve6WSk6BGLFRRyDN0GSxDsnZAdkJzsiZ3GglE9Rc8qPoBP5yCccLqh0l -VX6Wmle3usURehnmp349hQ71+S4pL+f5bFgWV1Al9j4uPqrtd3GqqpmWRgqujuwq -URawXs3qZwQcWDD1YIq9pr1N5Za0/EKJAWv2cMhQOQwt1WbZyNKzMrcbGW3LM/nf -peYVhDfwwvJllpKQd/Ct9JDpEXjXk4nAPQu6KfTomZ1yju2dL+6SfaHx/126M2CF -Yv4HAqGEVka+lgqaE9chTLd8B59OTj+RdPsnnRHM3eaxynFNExc5JsUpISuTKWqW -+qtB4Uu2NQvAmxU= ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: - 5c:8b:99:c5:5a:94:c5:d2:71:56:de:cd:89:80:cc:26 - Signature Algorithm: ecdsa-with-SHA384 - Issuer: C=US, ST=New Jersey, L=Jersey City, O=The USERTRUST Network, CN=USERTrust ECC Certification Authority - Validity - Not Before: Feb 1 00:00:00 2010 GMT - Not After : Jan 18 23:59:59 2038 GMT - Subject: C=US, ST=New Jersey, L=Jersey City, O=The USERTRUST Network, CN=USERTrust ECC Certification Authority - Subject Public Key Info: - Public Key Algorithm: id-ecPublicKey - Public-Key: (384 bit) - pub: - 04:1a:ac:54:5a:a9:f9:68:23:e7:7a:d5:24:6f:53: - c6:5a:d8:4b:ab:c6:d5:b6:d1:e6:73:71:ae:dd:9c: - d6:0c:61:fd:db:a0:89:03:b8:05:14:ec:57:ce:ee: - 5d:3f:e2:21:b3:ce:f7:d4:8a:79:e0:a3:83:7e:2d: - 97:d0:61:c4:f1:99:dc:25:91:63:ab:7f:30:a3:b4: - 70:e2:c7:a1:33:9c:f3:bf:2e:5c:53:b1:5f:b3:7d: - 32:7f:8a:34:e3:79:79 - ASN1 OID: secp384r1 - X509v3 extensions: - X509v3 Subject Key Identifier: - 3A:E1:09:86:D4:CF:19:C2:96:76:74:49:76:DC:E0:35:C6:63:63:9A - X509v3 Key Usage: critical - Certificate Sign, CRL Sign - X509v3 Basic Constraints: critical - CA:TRUE - Signature Algorithm: ecdsa-with-SHA384 - 30:65:02:30:36:67:a1:16:08:dc:e4:97:00:41:1d:4e:be:e1: - 63:01:cf:3b:aa:42:11:64:a0:9d:94:39:02:11:79:5c:7b:1d: - fa:64:b9:ee:16:42:b3:bf:8a:c2:09:c4:ec:e4:b1:4d:02:31: - 00:e9:2a:61:47:8c:52:4a:4b:4e:18:70:f6:d6:44:d6:6e:f5: - 83:ba:6d:58:bd:24:d9:56:48:ea:ef:c4:a2:46:81:88:6a:3a: - 46:d1:a9:9b:4d:c9:61:da:d1:5d:57:6a:18 ------BEGIN CERTIFICATE----- -MIICjzCCAhWgAwIBAgIQXIuZxVqUxdJxVt7NiYDMJjAKBggqhkjOPQQDAzCBiDEL -MAkGA1UEBhMCVVMxEzARBgNVBAgTCk5ldyBKZXJzZXkxFDASBgNVBAcTC0plcnNl -eSBDaXR5MR4wHAYDVQQKExVUaGUgVVNFUlRSVVNUIE5ldHdvcmsxLjAsBgNVBAMT -JVVTRVJUcnVzdCBFQ0MgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNMTAwMjAx -MDAwMDAwWhcNMzgwMTE4MjM1OTU5WjCBiDELMAkGA1UEBhMCVVMxEzARBgNVBAgT -Ck5ldyBKZXJzZXkxFDASBgNVBAcTC0plcnNleSBDaXR5MR4wHAYDVQQKExVUaGUg -VVNFUlRSVVNUIE5ldHdvcmsxLjAsBgNVBAMTJVVTRVJUcnVzdCBFQ0MgQ2VydGlm -aWNhdGlvbiBBdXRob3JpdHkwdjAQBgcqhkjOPQIBBgUrgQQAIgNiAAQarFRaqflo -I+d61SRvU8Za2EurxtW20eZzca7dnNYMYf3boIkDuAUU7FfO7l0/4iGzzvfUinng -o4N+LZfQYcTxmdwlkWOrfzCjtHDix6EznPO/LlxTsV+zfTJ/ijTjeXmjQjBAMB0G -A1UdDgQWBBQ64QmG1M8ZwpZ2dEl23OA1xmNjmjAOBgNVHQ8BAf8EBAMCAQYwDwYD -VR0TAQH/BAUwAwEB/zAKBggqhkjOPQQDAwNoADBlAjA2Z6EWCNzklwBBHU6+4WMB -zzuqQhFkoJ2UOQIReVx7Hfpkue4WQrO/isIJxOzksU0CMQDpKmFHjFJKS04YcPbW -RNZu9YO6bVi9JNlWSOrvxKJGgYhqOkbRqZtNyWHa0V1Xahg= ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: - 01:fd:6d:30:fc:a3:ca:51:a8:1b:bc:64:0e:35:03:2d - Signature Algorithm: sha384WithRSAEncryption - Issuer: C=US, ST=New Jersey, L=Jersey City, O=The USERTRUST Network, CN=USERTrust RSA Certification Authority - Validity - Not Before: Feb 1 00:00:00 2010 GMT - Not After : Jan 18 23:59:59 2038 GMT - Subject: C=US, ST=New Jersey, L=Jersey City, O=The USERTRUST Network, CN=USERTrust RSA Certification Authority - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (4096 bit) - Modulus: - 00:80:12:65:17:36:0e:c3:db:08:b3:d0:ac:57:0d: - 76:ed:cd:27:d3:4c:ad:50:83:61:e2:aa:20:4d:09: - 2d:64:09:dc:ce:89:9f:cc:3d:a9:ec:f6:cf:c1:dc: - f1:d3:b1:d6:7b:37:28:11:2b:47:da:39:c6:bc:3a: - 19:b4:5f:a6:bd:7d:9d:a3:63:42:b6:76:f2:a9:3b: - 2b:91:f8:e2:6f:d0:ec:16:20:90:09:3e:e2:e8:74: - c9:18:b4:91:d4:62:64:db:7f:a3:06:f1:88:18:6a: - 90:22:3c:bc:fe:13:f0:87:14:7b:f6:e4:1f:8e:d4: - e4:51:c6:11:67:46:08:51:cb:86:14:54:3f:bc:33: - fe:7e:6c:9c:ff:16:9d:18:bd:51:8e:35:a6:a7:66: - c8:72:67:db:21:66:b1:d4:9b:78:03:c0:50:3a:e8: - cc:f0:dc:bc:9e:4c:fe:af:05:96:35:1f:57:5a:b7: - ff:ce:f9:3d:b7:2c:b6:f6:54:dd:c8:e7:12:3a:4d: - ae:4c:8a:b7:5c:9a:b4:b7:20:3d:ca:7f:22:34:ae: - 7e:3b:68:66:01:44:e7:01:4e:46:53:9b:33:60:f7: - 94:be:53:37:90:73:43:f3:32:c3:53:ef:db:aa:fe: - 74:4e:69:c7:6b:8c:60:93:de:c4:c7:0c:df:e1:32: - ae:cc:93:3b:51:78:95:67:8b:ee:3d:56:fe:0c:d0: - 69:0f:1b:0f:f3:25:26:6b:33:6d:f7:6e:47:fa:73: - 43:e5:7e:0e:a5:66:b1:29:7c:32:84:63:55:89:c4: - 0d:c1:93:54:30:19:13:ac:d3:7d:37:a7:eb:5d:3a: - 6c:35:5c:db:41:d7:12:da:a9:49:0b:df:d8:80:8a: - 09:93:62:8e:b5:66:cf:25:88:cd:84:b8:b1:3f:a4: - 39:0f:d9:02:9e:eb:12:4c:95:7c:f3:6b:05:a9:5e: - 16:83:cc:b8:67:e2:e8:13:9d:cc:5b:82:d3:4c:b3: - ed:5b:ff:de:e5:73:ac:23:3b:2d:00:bf:35:55:74: - 09:49:d8:49:58:1a:7f:92:36:e6:51:92:0e:f3:26: - 7d:1c:4d:17:bc:c9:ec:43:26:d0:bf:41:5f:40:a9: - 44:44:f4:99:e7:57:87:9e:50:1f:57:54:a8:3e:fd: - 74:63:2f:b1:50:65:09:e6:58:42:2e:43:1a:4c:b4: - f0:25:47:59:fa:04:1e:93:d4:26:46:4a:50:81:b2: - de:be:78:b7:fc:67:15:e1:c9:57:84:1e:0f:63:d6: - e9:62:ba:d6:5f:55:2e:ea:5c:c6:28:08:04:25:39: - b8:0e:2b:a9:f2:4c:97:1c:07:3f:0d:52:f5:ed:ef: - 2f:82:0f - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Subject Key Identifier: - 53:79:BF:5A:AA:2B:4A:CF:54:80:E1:D8:9B:C0:9D:F2:B2:03:66:CB - X509v3 Key Usage: critical - Certificate Sign, CRL Sign - X509v3 Basic Constraints: critical - CA:TRUE - Signature Algorithm: sha384WithRSAEncryption - 5c:d4:7c:0d:cf:f7:01:7d:41:99:65:0c:73:c5:52:9f:cb:f8: - cf:99:06:7f:1b:da:43:15:9f:9e:02:55:57:96:14:f1:52:3c: - 27:87:94:28:ed:1f:3a:01:37:a2:76:fc:53:50:c0:84:9b:c6: - 6b:4e:ba:8c:21:4f:a2:8e:55:62:91:f3:69:15:d8:bc:88:e3: - c4:aa:0b:fd:ef:a8:e9:4b:55:2a:06:20:6d:55:78:29:19:ee: - 5f:30:5c:4b:24:11:55:ff:24:9a:6e:5e:2a:2b:ee:0b:4d:9f: - 7f:f7:01:38:94:14:95:43:07:09:fb:60:a9:ee:1c:ab:12:8c: - a0:9a:5e:a7:98:6a:59:6d:8b:3f:08:fb:c8:d1:45:af:18:15: - 64:90:12:0f:73:28:2e:c5:e2:24:4e:fc:58:ec:f0:f4:45:fe: - 22:b3:eb:2f:8e:d2:d9:45:61:05:c1:97:6f:a8:76:72:8f:8b: - 8c:36:af:bf:0d:05:ce:71:8d:e6:a6:6f:1f:6c:a6:71:62:c5: - d8:d0:83:72:0c:f1:67:11:89:0c:9c:13:4c:72:34:df:bc:d5: - 71:df:aa:71:dd:e1:b9:6c:8c:3c:12:5d:65:da:bd:57:12:b6: - 43:6b:ff:e5:de:4d:66:11:51:cf:99:ae:ec:17:b6:e8:71:91: - 8c:de:49:fe:dd:35:71:a2:15:27:94:1c:cf:61:e3:26:bb:6f: - a3:67:25:21:5d:e6:dd:1d:0b:2e:68:1b:3b:82:af:ec:83:67: - 85:d4:98:51:74:b1:b9:99:80:89:ff:7f:78:19:5c:79:4a:60: - 2e:92:40:ae:4c:37:2a:2c:c9:c7:62:c8:0e:5d:f7:36:5b:ca: - e0:25:25:01:b4:dd:1a:07:9c:77:00:3f:d0:dc:d5:ec:3d:d4: - fa:bb:3f:cc:85:d6:6f:7f:a9:2d:df:b9:02:f7:f5:97:9a:b5: - 35:da:c3:67:b0:87:4a:a9:28:9e:23:8e:ff:5c:27:6b:e1:b0: - 4f:f3:07:ee:00:2e:d4:59:87:cb:52:41:95:ea:f4:47:d7:ee: - 64:41:55:7c:8d:59:02:95:dd:62:9d:c2:b9:ee:5a:28:74:84: - a5:9b:b7:90:c7:0c:07:df:f5:89:36:74:32:d6:28:c1:b0:b0: - 0b:e0:9c:4c:c3:1c:d6:fc:e3:69:b5:47:46:81:2f:a2:82:ab: - d3:63:44:70:c4:8d:ff:2d:33:ba:ad:8f:7b:b5:70:88:ae:3e: - 19:cf:40:28:d8:fc:c8:90:bb:5d:99:22:f5:52:e6:58:c5:1f: - 88:31:43:ee:88:1d:d7:c6:8e:3c:43:6a:1d:a7:18:de:7d:3d: - 16:f1:62:f9:ca:90:a8:fd ------BEGIN CERTIFICATE----- -MIIF3jCCA8agAwIBAgIQAf1tMPyjylGoG7xkDjUDLTANBgkqhkiG9w0BAQwFADCB -iDELMAkGA1UEBhMCVVMxEzARBgNVBAgTCk5ldyBKZXJzZXkxFDASBgNVBAcTC0pl -cnNleSBDaXR5MR4wHAYDVQQKExVUaGUgVVNFUlRSVVNUIE5ldHdvcmsxLjAsBgNV -BAMTJVVTRVJUcnVzdCBSU0EgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNMTAw -MjAxMDAwMDAwWhcNMzgwMTE4MjM1OTU5WjCBiDELMAkGA1UEBhMCVVMxEzARBgNV -BAgTCk5ldyBKZXJzZXkxFDASBgNVBAcTC0plcnNleSBDaXR5MR4wHAYDVQQKExVU -aGUgVVNFUlRSVVNUIE5ldHdvcmsxLjAsBgNVBAMTJVVTRVJUcnVzdCBSU0EgQ2Vy -dGlmaWNhdGlvbiBBdXRob3JpdHkwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIK -AoICAQCAEmUXNg7D2wiz0KxXDXbtzSfTTK1Qg2HiqiBNCS1kCdzOiZ/MPans9s/B -3PHTsdZ7NygRK0faOca8Ohm0X6a9fZ2jY0K2dvKpOyuR+OJv0OwWIJAJPuLodMkY -tJHUYmTbf6MG8YgYapAiPLz+E/CHFHv25B+O1ORRxhFnRghRy4YUVD+8M/5+bJz/ -Fp0YvVGONaanZshyZ9shZrHUm3gDwFA66Mzw3LyeTP6vBZY1H1dat//O+T23LLb2 -VN3I5xI6Ta5MirdcmrS3ID3KfyI0rn47aGYBROcBTkZTmzNg95S+UzeQc0PzMsNT -79uq/nROacdrjGCT3sTHDN/hMq7MkztReJVni+49Vv4M0GkPGw/zJSZrM233bkf6 -c0Plfg6lZrEpfDKEY1WJxA3Bk1QwGROs0303p+tdOmw1XNtB1xLaqUkL39iAigmT -Yo61Zs8liM2EuLE/pDkP2QKe6xJMlXzzawWpXhaDzLhn4ugTncxbgtNMs+1b/97l -c6wjOy0AvzVVdAlJ2ElYGn+SNuZRkg7zJn0cTRe8yexDJtC/QV9AqURE9JnnV4ee -UB9XVKg+/XRjL7FQZQnmWEIuQxpMtPAlR1n6BB6T1CZGSlCBst6+eLf8ZxXhyVeE -Hg9j1uliutZfVS7qXMYoCAQlObgOK6nyTJccBz8NUvXt7y+CDwIDAQABo0IwQDAd -BgNVHQ4EFgQUU3m/WqorSs9UgOHYm8Cd8rIDZsswDgYDVR0PAQH/BAQDAgEGMA8G -A1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcNAQEMBQADggIBAFzUfA3P9wF9QZllDHPF -Up/L+M+ZBn8b2kMVn54CVVeWFPFSPCeHlCjtHzoBN6J2/FNQwISbxmtOuowhT6KO -VWKR82kV2LyI48SqC/3vqOlLVSoGIG1VeCkZ7l8wXEskEVX/JJpuXior7gtNn3/3 -ATiUFJVDBwn7YKnuHKsSjKCaXqeYalltiz8I+8jRRa8YFWSQEg9zKC7F4iRO/Fjs -8PRF/iKz6y+O0tlFYQXBl2+odnKPi4w2r78NBc5xjeambx9spnFixdjQg3IM8WcR -iQycE0xyNN+81XHfqnHd4blsjDwSXWXavVcStkNr/+XeTWYRUc+ZruwXtuhxkYze -Sf7dNXGiFSeUHM9h4ya7b6NnJSFd5t0dCy5oGzuCr+yDZ4XUmFF0sbmZgIn/f3gZ -XHlKYC6SQK5MNyosycdiyA5d9zZbyuAlJQG03RoHnHcAP9Dc1ew91Pq7P8yF1m9/ -qS3fuQL39ZeatTXaw2ewh0qpKJ4jjv9cJ2vhsE/zB+4ALtRZh8tSQZXq9EfX7mRB -VXyNWQKV3WKdwrnuWih0hKWbt5DHDAff9Yk2dDLWKMGwsAvgnEzDHNb842m1R0aB -L6KCq9NjRHDEjf8tM7qtj3u1cIiuPhnPQCjY/MiQu12ZIvVS5ljFH4gxQ+6IHdfG -jjxDah2nGN59PRbxYvnKkKj9 ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: - 44:be:0c:8b:50:00:24:b4:11:d3:36:2a:fe:65:0a:fd - Signature Algorithm: sha1WithRSAEncryption - Issuer: C=US, ST=UT, L=Salt Lake City, O=The USERTRUST Network, OU=http://www.usertrust.com, CN=UTN-USERFirst-Hardware - Validity - Not Before: Jul 9 18:10:42 1999 GMT - Not After : Jul 9 18:19:22 2019 GMT - Subject: C=US, ST=UT, L=Salt Lake City, O=The USERTRUST Network, OU=http://www.usertrust.com, CN=UTN-USERFirst-Hardware - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (2048 bit) - Modulus: - 00:b1:f7:c3:38:3f:b4:a8:7f:cf:39:82:51:67:d0: - 6d:9f:d2:ff:58:f3:e7:9f:2b:ec:0d:89:54:99:b9: - 38:99:16:f7:e0:21:79:48:c2:bb:61:74:12:96:1d: - 3c:6a:72:d5:3c:10:67:3a:39:ed:2b:13:cd:66:eb: - 95:09:33:a4:6c:97:b1:e8:c6:ec:c1:75:79:9c:46: - 5e:8d:ab:d0:6a:fd:b9:2a:55:17:10:54:b3:19:f0: - 9a:f6:f1:b1:5d:b6:a7:6d:fb:e0:71:17:6b:a2:88: - fb:00:df:fe:1a:31:77:0c:9a:01:7a:b1:32:e3:2b: - 01:07:38:6e:c3:a5:5e:23:bc:45:9b:7b:50:c1:c9: - 30:8f:db:e5:2b:7a:d3:5b:fb:33:40:1e:a0:d5:98: - 17:bc:8b:87:c3:89:d3:5d:a0:8e:b2:aa:aa:f6:8e: - 69:88:06:c5:fa:89:21:f3:08:9d:69:2e:09:33:9b: - 29:0d:46:0f:8c:cc:49:34:b0:69:51:bd:f9:06:cd: - 68:ad:66:4c:bc:3e:ac:61:bd:0a:88:0e:c8:df:3d: - ee:7c:04:4c:9d:0a:5e:6b:91:d6:ee:c7:ed:28:8d: - ab:4d:87:89:73:d0:6e:a4:d0:1e:16:8b:14:e1:76: - 44:03:7f:63:ac:e4:cd:49:9c:c5:92:f4:ab:32:a1: - 48:5b - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Key Usage: - Digital Signature, Non Repudiation, Certificate Sign, CRL Sign - X509v3 Basic Constraints: critical - CA:TRUE - X509v3 Subject Key Identifier: - A1:72:5F:26:1B:28:98:43:95:5D:07:37:D5:85:96:9D:4B:D2:C3:45 - X509v3 CRL Distribution Points: - - Full Name: - URI:http://crl.usertrust.com/UTN-USERFirst-Hardware.crl - - X509v3 Extended Key Usage: - TLS Web Server Authentication, IPSec End System, IPSec Tunnel, IPSec User - Signature Algorithm: sha1WithRSAEncryption - 47:19:0f:de:74:c6:99:97:af:fc:ad:28:5e:75:8e:eb:2d:67: - ee:4e:7b:2b:d7:0c:ff:f6:de:cb:55:a2:0a:e1:4c:54:65:93: - 60:6b:9f:12:9c:ad:5e:83:2c:eb:5a:ae:c0:e4:2d:f4:00:63: - 1d:b8:c0:6c:f2:cf:49:bb:4d:93:6f:06:a6:0a:22:b2:49:62: - 08:4e:ff:c8:c8:14:b2:88:16:5d:e7:01:e4:12:95:e5:45:34: - b3:8b:69:bd:cf:b4:85:8f:75:51:9e:7d:3a:38:3a:14:48:12: - c6:fb:a7:3b:1a:8d:0d:82:40:07:e8:04:08:90:a1:89:cb:19: - 50:df:ca:1c:01:bc:1d:04:19:7b:10:76:97:3b:ee:90:90:ca: - c4:0e:1f:16:6e:75:ef:33:f8:d3:6f:5b:1e:96:e3:e0:74:77: - 74:7b:8a:a2:6e:2d:dd:76:d6:39:30:82:f0:ab:9c:52:f2:2a: - c7:af:49:5e:7e:c7:68:e5:82:81:c8:6a:27:f9:27:88:2a:d5: - 58:50:95:1f:f0:3b:1c:57:bb:7d:14:39:62:2b:9a:c9:94:92: - 2a:a3:22:0c:ff:89:26:7d:5f:23:2b:47:d7:15:1d:a9:6a:9e: - 51:0d:2a:51:9e:81:f9:d4:3b:5e:70:12:7f:10:32:9c:1e:bb: - 9d:f8:66:a8 ------BEGIN CERTIFICATE----- -MIIEdDCCA1ygAwIBAgIQRL4Mi1AAJLQR0zYq/mUK/TANBgkqhkiG9w0BAQUFADCB -lzELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAlVUMRcwFQYDVQQHEw5TYWx0IExha2Ug -Q2l0eTEeMBwGA1UEChMVVGhlIFVTRVJUUlVTVCBOZXR3b3JrMSEwHwYDVQQLExho -dHRwOi8vd3d3LnVzZXJ0cnVzdC5jb20xHzAdBgNVBAMTFlVUTi1VU0VSRmlyc3Qt -SGFyZHdhcmUwHhcNOTkwNzA5MTgxMDQyWhcNMTkwNzA5MTgxOTIyWjCBlzELMAkG -A1UEBhMCVVMxCzAJBgNVBAgTAlVUMRcwFQYDVQQHEw5TYWx0IExha2UgQ2l0eTEe -MBwGA1UEChMVVGhlIFVTRVJUUlVTVCBOZXR3b3JrMSEwHwYDVQQLExhodHRwOi8v -d3d3LnVzZXJ0cnVzdC5jb20xHzAdBgNVBAMTFlVUTi1VU0VSRmlyc3QtSGFyZHdh -cmUwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCx98M4P7Sof885glFn -0G2f0v9Y8+efK+wNiVSZuTiZFvfgIXlIwrthdBKWHTxqctU8EGc6Oe0rE81m65UJ -M6Rsl7HoxuzBdXmcRl6Nq9Bq/bkqVRcQVLMZ8Jr28bFdtqdt++BxF2uiiPsA3/4a -MXcMmgF6sTLjKwEHOG7DpV4jvEWbe1DByTCP2+UretNb+zNAHqDVmBe8i4fDidNd -oI6yqqr2jmmIBsX6iSHzCJ1pLgkzmykNRg+MzEk0sGlRvfkGzWitZky8PqxhvQqI -DsjfPe58BEydCl5rkdbux+0ojatNh4lz0G6k0B4WixThdkQDf2Os5M1JnMWS9Ksy -oUhbAgMBAAGjgbkwgbYwCwYDVR0PBAQDAgHGMA8GA1UdEwEB/wQFMAMBAf8wHQYD -VR0OBBYEFKFyXyYbKJhDlV0HN9WFlp1L0sNFMEQGA1UdHwQ9MDswOaA3oDWGM2h0 -dHA6Ly9jcmwudXNlcnRydXN0LmNvbS9VVE4tVVNFUkZpcnN0LUhhcmR3YXJlLmNy -bDAxBgNVHSUEKjAoBggrBgEFBQcDAQYIKwYBBQUHAwUGCCsGAQUFBwMGBggrBgEF -BQcDBzANBgkqhkiG9w0BAQUFAAOCAQEARxkP3nTGmZev/K0oXnWO6y1n7k57K9cM -//bey1WiCuFMVGWTYGufEpytXoMs61quwOQt9ABjHbjAbPLPSbtNk28Gpgoiskli -CE7/yMgUsogWXecB5BKV5UU0s4tpvc+0hY91UZ59Ojg6FEgSxvunOxqNDYJAB+gE -CJChicsZUN/KHAG8HQQZexB2lzvukJDKxA4fFm517zP4029bHpbj4HR3dHuKom4t -3XbWOTCC8KucUvIqx69JXn7HaOWCgchqJ/kniCrVWFCVH/A7HFe7fRQ5YiuayZSS -KqMiDP+JJn1fIytH1xUdqWqeUQ0qUZ6B+dQ7XnASfxAynB67nfhmqA== ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: - 2f:80:fe:23:8c:0e:22:0f:48:67:12:28:91:87:ac:b3 - Signature Algorithm: ecdsa-with-SHA384 - Issuer: C=US, O=VeriSign, Inc., OU=VeriSign Trust Network, OU=(c) 2007 VeriSign, Inc. - For authorized use only, CN=VeriSign Class 3 Public Primary Certification Authority - G4 - Validity - Not Before: Nov 5 00:00:00 2007 GMT - Not After : Jan 18 23:59:59 2038 GMT - Subject: C=US, O=VeriSign, Inc., OU=VeriSign Trust Network, OU=(c) 2007 VeriSign, Inc. - For authorized use only, CN=VeriSign Class 3 Public Primary Certification Authority - G4 - Subject Public Key Info: - Public Key Algorithm: id-ecPublicKey - Public-Key: (384 bit) - pub: - 04:a7:56:7a:7c:52:da:64:9b:0e:2d:5c:d8:5e:ac: - 92:3d:fe:01:e6:19:4a:3d:14:03:4b:fa:60:27:20: - d9:83:89:69:fa:54:c6:9a:18:5e:55:2a:64:de:06: - f6:8d:4a:3b:ad:10:3c:65:3d:90:88:04:89:e0:30: - 61:b3:ae:5d:01:a7:7b:de:7c:b2:be:ca:65:61:00: - 86:ae:da:8f:7b:d0:89:ad:4d:1d:59:9a:41:b1:bc: - 47:80:dc:9e:62:c3:f9 - ASN1 OID: secp384r1 - X509v3 extensions: - X509v3 Basic Constraints: critical - CA:TRUE - X509v3 Key Usage: critical - Certificate Sign, CRL Sign - 1.3.6.1.5.5.7.1.12: - 0_.].[0Y0W0U..image/gif0!0.0...+..............k...j.H.,{..0%.#http://logo.verisign.com/vslogo.gif - X509v3 Subject Key Identifier: - B3:16:91:FD:EE:A6:6E:E4:B5:2E:49:8F:87:78:81:80:EC:E5:B1:B5 - Signature Algorithm: ecdsa-with-SHA384 - 30:65:02:30:66:21:0c:18:26:60:5a:38:7b:56:42:e0:a7:fc: - 36:84:51:91:20:2c:76:4d:43:3d:c4:1d:84:23:d0:ac:d6:7c: - 35:06:ce:cd:69:bd:90:0d:db:6c:48:42:1d:0e:aa:42:02:31: - 00:9c:3d:48:39:23:39:58:1a:15:12:59:6a:9e:ef:d5:59:b2: - 1d:52:2c:99:71:cd:c7:29:df:1b:2a:61:7b:71:d1:de:f3:c0: - e5:0d:3a:4a:aa:2d:a7:d8:86:2a:dd:2e:10 ------BEGIN CERTIFICATE----- -MIIDhDCCAwqgAwIBAgIQL4D+I4wOIg9IZxIokYesszAKBggqhkjOPQQDAzCByjEL -MAkGA1UEBhMCVVMxFzAVBgNVBAoTDlZlcmlTaWduLCBJbmMuMR8wHQYDVQQLExZW -ZXJpU2lnbiBUcnVzdCBOZXR3b3JrMTowOAYDVQQLEzEoYykgMjAwNyBWZXJpU2ln -biwgSW5jLiAtIEZvciBhdXRob3JpemVkIHVzZSBvbmx5MUUwQwYDVQQDEzxWZXJp -U2lnbiBDbGFzcyAzIFB1YmxpYyBQcmltYXJ5IENlcnRpZmljYXRpb24gQXV0aG9y -aXR5IC0gRzQwHhcNMDcxMTA1MDAwMDAwWhcNMzgwMTE4MjM1OTU5WjCByjELMAkG -A1UEBhMCVVMxFzAVBgNVBAoTDlZlcmlTaWduLCBJbmMuMR8wHQYDVQQLExZWZXJp -U2lnbiBUcnVzdCBOZXR3b3JrMTowOAYDVQQLEzEoYykgMjAwNyBWZXJpU2lnbiwg -SW5jLiAtIEZvciBhdXRob3JpemVkIHVzZSBvbmx5MUUwQwYDVQQDEzxWZXJpU2ln -biBDbGFzcyAzIFB1YmxpYyBQcmltYXJ5IENlcnRpZmljYXRpb24gQXV0aG9yaXR5 -IC0gRzQwdjAQBgcqhkjOPQIBBgUrgQQAIgNiAASnVnp8Utpkmw4tXNherJI9/gHm -GUo9FANL+mAnINmDiWn6VMaaGF5VKmTeBvaNSjutEDxlPZCIBIngMGGzrl0Bp3ve -fLK+ymVhAIau2o970ImtTR1ZmkGxvEeA3J5iw/mjgbIwga8wDwYDVR0TAQH/BAUw -AwEB/zAOBgNVHQ8BAf8EBAMCAQYwbQYIKwYBBQUHAQwEYTBfoV2gWzBZMFcwVRYJ -aW1hZ2UvZ2lmMCEwHzAHBgUrDgMCGgQUj+XTGoasjY5rw8+AatRIGCx7GS4wJRYj -aHR0cDovL2xvZ28udmVyaXNpZ24uY29tL3ZzbG9nby5naWYwHQYDVR0OBBYEFLMW -kf3upm7ktS5Jj4d4gYDs5bG1MAoGCCqGSM49BAMDA2gAMGUCMGYhDBgmYFo4e1ZC -4Kf8NoRRkSAsdk1DPcQdhCPQrNZ8NQbOzWm9kA3bbEhCHQ6qQgIxAJw9SDkjOVga -FRJZap7v1VmyHVIsmXHNxynfGyphe3HR3vPA5Q06Sqotp9iGKt0uEA== ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: - 18:da:d1:9e:26:7d:e8:bb:4a:21:58:cd:cc:6b:3b:4a - Signature Algorithm: sha1WithRSAEncryption - Issuer: C=US, O=VeriSign, Inc., OU=VeriSign Trust Network, OU=(c) 2006 VeriSign, Inc. - For authorized use only, CN=VeriSign Class 3 Public Primary Certification Authority - G5 - Validity - Not Before: Nov 8 00:00:00 2006 GMT - Not After : Jul 16 23:59:59 2036 GMT - Subject: C=US, O=VeriSign, Inc., OU=VeriSign Trust Network, OU=(c) 2006 VeriSign, Inc. - For authorized use only, CN=VeriSign Class 3 Public Primary Certification Authority - G5 - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (2048 bit) - Modulus: - 00:af:24:08:08:29:7a:35:9e:60:0c:aa:e7:4b:3b: - 4e:dc:7c:bc:3c:45:1c:bb:2b:e0:fe:29:02:f9:57: - 08:a3:64:85:15:27:f5:f1:ad:c8:31:89:5d:22:e8: - 2a:aa:a6:42:b3:8f:f8:b9:55:b7:b1:b7:4b:b3:fe: - 8f:7e:07:57:ec:ef:43:db:66:62:15:61:cf:60:0d: - a4:d8:de:f8:e0:c3:62:08:3d:54:13:eb:49:ca:59: - 54:85:26:e5:2b:8f:1b:9f:eb:f5:a1:91:c2:33:49: - d8:43:63:6a:52:4b:d2:8f:e8:70:51:4d:d1:89:69: - 7b:c7:70:f6:b3:dc:12:74:db:7b:5d:4b:56:d3:96: - bf:15:77:a1:b0:f4:a2:25:f2:af:1c:92:67:18:e5: - f4:06:04:ef:90:b9:e4:00:e4:dd:3a:b5:19:ff:02: - ba:f4:3c:ee:e0:8b:eb:37:8b:ec:f4:d7:ac:f2:f6: - f0:3d:af:dd:75:91:33:19:1d:1c:40:cb:74:24:19: - 21:93:d9:14:fe:ac:2a:52:c7:8f:d5:04:49:e4:8d: - 63:47:88:3c:69:83:cb:fe:47:bd:2b:7e:4f:c5:95: - ae:0e:9d:d4:d1:43:c0:67:73:e3:14:08:7e:e5:3f: - 9f:73:b8:33:0a:cf:5d:3f:34:87:96:8a:ee:53:e8: - 25:15 - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Basic Constraints: critical - CA:TRUE - X509v3 Key Usage: critical - Certificate Sign, CRL Sign - 1.3.6.1.5.5.7.1.12: - 0_.].[0Y0W0U..image/gif0!0.0...+..............k...j.H.,{..0%.#http://logo.verisign.com/vslogo.gif - X509v3 Subject Key Identifier: - 7F:D3:65:A7:C2:DD:EC:BB:F0:30:09:F3:43:39:FA:02:AF:33:31:33 - Signature Algorithm: sha1WithRSAEncryption - 93:24:4a:30:5f:62:cf:d8:1a:98:2f:3d:ea:dc:99:2d:bd:77: - f6:a5:79:22:38:ec:c4:a7:a0:78:12:ad:62:0e:45:70:64:c5: - e7:97:66:2d:98:09:7e:5f:af:d6:cc:28:65:f2:01:aa:08:1a: - 47:de:f9:f9:7c:92:5a:08:69:20:0d:d9:3e:6d:6e:3c:0d:6e: - d8:e6:06:91:40:18:b9:f8:c1:ed:df:db:41:aa:e0:96:20:c9: - cd:64:15:38:81:c9:94:ee:a2:84:29:0b:13:6f:8e:db:0c:dd: - 25:02:db:a4:8b:19:44:d2:41:7a:05:69:4a:58:4f:60:ca:7e: - 82:6a:0b:02:aa:25:17:39:b5:db:7f:e7:84:65:2a:95:8a:bd: - 86:de:5e:81:16:83:2d:10:cc:de:fd:a8:82:2a:6d:28:1f:0d: - 0b:c4:e5:e7:1a:26:19:e1:f4:11:6f:10:b5:95:fc:e7:42:05: - 32:db:ce:9d:51:5e:28:b6:9e:85:d3:5b:ef:a5:7d:45:40:72: - 8e:b7:0e:6b:0e:06:fb:33:35:48:71:b8:9d:27:8b:c4:65:5f: - 0d:86:76:9c:44:7a:f6:95:5c:f6:5d:32:08:33:a4:54:b6:18: - 3f:68:5c:f2:42:4a:85:38:54:83:5f:d1:e8:2c:f2:ac:11:d6: - a8:ed:63:6a ------BEGIN CERTIFICATE----- -MIIE0zCCA7ugAwIBAgIQGNrRniZ96LtKIVjNzGs7SjANBgkqhkiG9w0BAQUFADCB -yjELMAkGA1UEBhMCVVMxFzAVBgNVBAoTDlZlcmlTaWduLCBJbmMuMR8wHQYDVQQL -ExZWZXJpU2lnbiBUcnVzdCBOZXR3b3JrMTowOAYDVQQLEzEoYykgMjAwNiBWZXJp -U2lnbiwgSW5jLiAtIEZvciBhdXRob3JpemVkIHVzZSBvbmx5MUUwQwYDVQQDEzxW -ZXJpU2lnbiBDbGFzcyAzIFB1YmxpYyBQcmltYXJ5IENlcnRpZmljYXRpb24gQXV0 -aG9yaXR5IC0gRzUwHhcNMDYxMTA4MDAwMDAwWhcNMzYwNzE2MjM1OTU5WjCByjEL -MAkGA1UEBhMCVVMxFzAVBgNVBAoTDlZlcmlTaWduLCBJbmMuMR8wHQYDVQQLExZW -ZXJpU2lnbiBUcnVzdCBOZXR3b3JrMTowOAYDVQQLEzEoYykgMjAwNiBWZXJpU2ln -biwgSW5jLiAtIEZvciBhdXRob3JpemVkIHVzZSBvbmx5MUUwQwYDVQQDEzxWZXJp -U2lnbiBDbGFzcyAzIFB1YmxpYyBQcmltYXJ5IENlcnRpZmljYXRpb24gQXV0aG9y -aXR5IC0gRzUwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCvJAgIKXo1 -nmAMqudLO07cfLw8RRy7K+D+KQL5VwijZIUVJ/XxrcgxiV0i6CqqpkKzj/i5Vbex -t0uz/o9+B1fs70PbZmIVYc9gDaTY3vjgw2IIPVQT60nKWVSFJuUrjxuf6/WhkcIz -SdhDY2pSS9KP6HBRTdGJaXvHcPaz3BJ023tdS1bTlr8Vd6Gw9KIl8q8ckmcY5fQG -BO+QueQA5N06tRn/Arr0PO7gi+s3i+z016zy9vA9r911kTMZHRxAy3QkGSGT2RT+ -rCpSx4/VBEnkjWNHiDxpg8v+R70rfk/Fla4OndTRQ8Bnc+MUCH7lP59zuDMKz10/ -NIeWiu5T6CUVAgMBAAGjgbIwga8wDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8E -BAMCAQYwbQYIKwYBBQUHAQwEYTBfoV2gWzBZMFcwVRYJaW1hZ2UvZ2lmMCEwHzAH -BgUrDgMCGgQUj+XTGoasjY5rw8+AatRIGCx7GS4wJRYjaHR0cDovL2xvZ28udmVy -aXNpZ24uY29tL3ZzbG9nby5naWYwHQYDVR0OBBYEFH/TZafC3ey78DAJ80M5+gKv -MzEzMA0GCSqGSIb3DQEBBQUAA4IBAQCTJEowX2LP2BqYLz3q3JktvXf2pXkiOOzE -p6B4Eq1iDkVwZMXnl2YtmAl+X6/WzChl8gGqCBpH3vn5fJJaCGkgDdk+bW48DW7Y -5gaRQBi5+MHt39tBquCWIMnNZBU4gcmU7qKEKQsTb47bDN0lAtukixlE0kF6BWlK -WE9gyn6CagsCqiUXObXbf+eEZSqVir2G3l6BFoMtEMze/aiCKm0oHw0LxOXnGiYZ -4fQRbxC1lfznQgUy286dUV4otp6F01vvpX1FQHKOtw5rDgb7MzVIcbidJ4vEZV8N -hnacRHr2lVz2XTIIM6RUthg/aFzyQkqFOFSDX9HoLPKsEdao7WNq ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: - 40:1a:c4:64:21:b3:13:21:03:0e:bb:e4:12:1a:c5:1d - Signature Algorithm: sha256WithRSAEncryption - Issuer: C=US, O=VeriSign, Inc., OU=VeriSign Trust Network, OU=(c) 2008 VeriSign, Inc. - For authorized use only, CN=VeriSign Universal Root Certification Authority - Validity - Not Before: Apr 2 00:00:00 2008 GMT - Not After : Dec 1 23:59:59 2037 GMT - Subject: C=US, O=VeriSign, Inc., OU=VeriSign Trust Network, OU=(c) 2008 VeriSign, Inc. - For authorized use only, CN=VeriSign Universal Root Certification Authority - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (2048 bit) - Modulus: - 00:c7:61:37:5e:b1:01:34:db:62:d7:15:9b:ff:58: - 5a:8c:23:23:d6:60:8e:91:d7:90:98:83:7a:e6:58: - 19:38:8c:c5:f6:e5:64:85:b4:a2:71:fb:ed:bd:b9: - da:cd:4d:00:b4:c8:2d:73:a5:c7:69:71:95:1f:39: - 3c:b2:44:07:9c:e8:0e:fa:4d:4a:c4:21:df:29:61: - 8f:32:22:61:82:c5:87:1f:6e:8c:7c:5f:16:20:51: - 44:d1:70:4f:57:ea:e3:1c:e3:cc:79:ee:58:d8:0e: - c2:b3:45:93:c0:2c:e7:9a:17:2b:7b:00:37:7a:41: - 33:78:e1:33:e2:f3:10:1a:7f:87:2c:be:f6:f5:f7: - 42:e2:e5:bf:87:62:89:5f:00:4b:df:c5:dd:e4:75: - 44:32:41:3a:1e:71:6e:69:cb:0b:75:46:08:d1:ca: - d2:2b:95:d0:cf:fb:b9:40:6b:64:8c:57:4d:fc:13: - 11:79:84:ed:5e:54:f6:34:9f:08:01:f3:10:25:06: - 17:4a:da:f1:1d:7a:66:6b:98:60:66:a4:d9:ef:d2: - 2e:82:f1:f0:ef:09:ea:44:c9:15:6a:e2:03:6e:33: - d3:ac:9f:55:00:c7:f6:08:6a:94:b9:5f:dc:e0:33: - f1:84:60:f9:5b:27:11:b4:fc:16:f2:bb:56:6a:80: - 25:8d - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Basic Constraints: critical - CA:TRUE - X509v3 Key Usage: critical - Certificate Sign, CRL Sign - 1.3.6.1.5.5.7.1.12: - 0_.].[0Y0W0U..image/gif0!0.0...+..............k...j.H.,{..0%.#http://logo.verisign.com/vslogo.gif - X509v3 Subject Key Identifier: - B6:77:FA:69:48:47:9F:53:12:D5:C2:EA:07:32:76:07:D1:97:07:19 - Signature Algorithm: sha256WithRSAEncryption - 4a:f8:f8:b0:03:e6:2c:67:7b:e4:94:77:63:cc:6e:4c:f9:7d: - 0e:0d:dc:c8:b9:35:b9:70:4f:63:fa:24:fa:6c:83:8c:47:9d: - 3b:63:f3:9a:f9:76:32:95:91:b1:77:bc:ac:9a:be:b1:e4:31: - 21:c6:81:95:56:5a:0e:b1:c2:d4:b1:a6:59:ac:f1:63:cb:b8: - 4c:1d:59:90:4a:ef:90:16:28:1f:5a:ae:10:fb:81:50:38:0c: - 6c:cc:f1:3d:c3:f5:63:e3:b3:e3:21:c9:24:39:e9:fd:15:66: - 46:f4:1b:11:d0:4d:73:a3:7d:46:f9:3d:ed:a8:5f:62:d4:f1: - 3f:f8:e0:74:57:2b:18:9d:81:b4:c4:28:da:94:97:a5:70:eb: - ac:1d:be:07:11:f0:d5:db:dd:e5:8c:f0:d5:32:b0:83:e6:57: - e2:8f:bf:be:a1:aa:bf:3d:1d:b5:d4:38:ea:d7:b0:5c:3a:4f: - 6a:3f:8f:c0:66:6c:63:aa:e9:d9:a4:16:f4:81:d1:95:14:0e: - 7d:cd:95:34:d9:d2:8f:70:73:81:7b:9c:7e:bd:98:61:d8:45: - 87:98:90:c5:eb:86:30:c6:35:bf:f0:ff:c3:55:88:83:4b:ef: - 05:92:06:71:f2:b8:98:93:b7:ec:cd:82:61:f1:38:e6:4f:97: - 98:2a:5a:8d ------BEGIN CERTIFICATE----- -MIIEuTCCA6GgAwIBAgIQQBrEZCGzEyEDDrvkEhrFHTANBgkqhkiG9w0BAQsFADCB -vTELMAkGA1UEBhMCVVMxFzAVBgNVBAoTDlZlcmlTaWduLCBJbmMuMR8wHQYDVQQL -ExZWZXJpU2lnbiBUcnVzdCBOZXR3b3JrMTowOAYDVQQLEzEoYykgMjAwOCBWZXJp -U2lnbiwgSW5jLiAtIEZvciBhdXRob3JpemVkIHVzZSBvbmx5MTgwNgYDVQQDEy9W -ZXJpU2lnbiBVbml2ZXJzYWwgUm9vdCBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTAe -Fw0wODA0MDIwMDAwMDBaFw0zNzEyMDEyMzU5NTlaMIG9MQswCQYDVQQGEwJVUzEX -MBUGA1UEChMOVmVyaVNpZ24sIEluYy4xHzAdBgNVBAsTFlZlcmlTaWduIFRydXN0 -IE5ldHdvcmsxOjA4BgNVBAsTMShjKSAyMDA4IFZlcmlTaWduLCBJbmMuIC0gRm9y -IGF1dGhvcml6ZWQgdXNlIG9ubHkxODA2BgNVBAMTL1ZlcmlTaWduIFVuaXZlcnNh -bCBSb290IENlcnRpZmljYXRpb24gQXV0aG9yaXR5MIIBIjANBgkqhkiG9w0BAQEF -AAOCAQ8AMIIBCgKCAQEAx2E3XrEBNNti1xWb/1hajCMj1mCOkdeQmIN65lgZOIzF -9uVkhbSicfvtvbnazU0AtMgtc6XHaXGVHzk8skQHnOgO+k1KxCHfKWGPMiJhgsWH -H26MfF8WIFFE0XBPV+rjHOPMee5Y2A7Cs0WTwCznmhcrewA3ekEzeOEz4vMQGn+H -LL729fdC4uW/h2KJXwBL38Xd5HVEMkE6HnFuacsLdUYI0crSK5XQz/u5QGtkjFdN -/BMReYTtXlT2NJ8IAfMQJQYXStrxHXpma5hgZqTZ79IugvHw7wnqRMkVauIDbjPT -rJ9VAMf2CGqUuV/c4DPxhGD5WycRtPwW8rtWaoAljQIDAQABo4GyMIGvMA8GA1Ud -EwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgEGMG0GCCsGAQUFBwEMBGEwX6FdoFsw -WTBXMFUWCWltYWdlL2dpZjAhMB8wBwYFKw4DAhoEFI/l0xqGrI2Oa8PPgGrUSBgs -exkuMCUWI2h0dHA6Ly9sb2dvLnZlcmlzaWduLmNvbS92c2xvZ28uZ2lmMB0GA1Ud -DgQWBBS2d/ppSEefUxLVwuoHMnYH0ZcHGTANBgkqhkiG9w0BAQsFAAOCAQEASvj4 -sAPmLGd75JR3Y8xuTPl9Dg3cyLk1uXBPY/ok+myDjEedO2Pzmvl2MpWRsXe8rJq+ -seQxIcaBlVZaDrHC1LGmWazxY8u4TB1ZkErvkBYoH1quEPuBUDgMbMzxPcP1Y+Oz -4yHJJDnp/RVmRvQbEdBNc6N9Rvk97ahfYtTxP/jgdFcrGJ2BtMQo2pSXpXDrrB2+ -BxHw1dvd5Yzw1TKwg+ZX4o+/vqGqvz0dtdQ46tewXDpPaj+PwGZsY6rp2aQW9IHR -lRQOfc2VNNnSj3BzgXucfr2YYdhFh5iQxeuGMMY1v/D/w1WIg0vvBZIGcfK4mJO3 -7M2CYfE45k+XmCpajQ== ------END CERTIFICATE----- -Certificate: - Data: - Version: 1 (0x0) - Serial Number: - 9b:7e:06:49:a3:3e:62:b9:d5:ee:90:48:71:29:ef:57 - Signature Algorithm: sha1WithRSAEncryption - Issuer: C=US, O=VeriSign, Inc., OU=VeriSign Trust Network, OU=(c) 1999 VeriSign, Inc. - For authorized use only, CN=VeriSign Class 3 Public Primary Certification Authority - G3 - Validity - Not Before: Oct 1 00:00:00 1999 GMT - Not After : Jul 16 23:59:59 2036 GMT - Subject: C=US, O=VeriSign, Inc., OU=VeriSign Trust Network, OU=(c) 1999 VeriSign, Inc. - For authorized use only, CN=VeriSign Class 3 Public Primary Certification Authority - G3 - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (2048 bit) - Modulus: - 00:cb:ba:9c:52:fc:78:1f:1a:1e:6f:1b:37:73:bd: - f8:c9:6b:94:12:30:4f:f0:36:47:f5:d0:91:0a:f5: - 17:c8:a5:61:c1:16:40:4d:fb:8a:61:90:e5:76:20: - c1:11:06:7d:ab:2c:6e:a6:f5:11:41:8e:fa:2d:ad: - 2a:61:59:a4:67:26:4c:d0:e8:bc:52:5b:70:20:04: - 58:d1:7a:c9:a4:69:bc:83:17:64:ad:05:8b:bc:d0: - 58:ce:8d:8c:f5:eb:f0:42:49:0b:9d:97:27:67:32: - 6e:e1:ae:93:15:1c:70:bc:20:4d:2f:18:de:92:88: - e8:6c:85:57:11:1a:e9:7e:e3:26:11:54:a2:45:96: - 55:83:ca:30:89:e8:dc:d8:a3:ed:2a:80:3f:7f:79: - 65:57:3e:15:20:66:08:2f:95:93:bf:aa:47:2f:a8: - 46:97:f0:12:e2:fe:c2:0a:2b:51:e6:76:e6:b7:46: - b7:e2:0d:a6:cc:a8:c3:4c:59:55:89:e6:e8:53:5c: - 1c:ea:9d:f0:62:16:0b:a7:c9:5f:0c:f0:de:c2:76: - ce:af:f7:6a:f2:fa:41:a6:a2:33:14:c9:e5:7a:63: - d3:9e:62:37:d5:85:65:9e:0e:e6:53:24:74:1b:5e: - 1d:12:53:5b:c7:2c:e7:83:49:3b:15:ae:8a:68:b9: - 57:97 - Exponent: 65537 (0x10001) - Signature Algorithm: sha1WithRSAEncryption - 11:14:96:c1:ab:92:08:f7:3f:2f:c9:b2:fe:e4:5a:9f:64:de: - db:21:4f:86:99:34:76:36:57:dd:d0:15:2f:c5:ad:7f:15:1f: - 37:62:73:3e:d4:e7:5f:ce:17:03:db:35:fa:2b:db:ae:60:09: - 5f:1e:5f:8f:6e:bb:0b:3d:ea:5a:13:1e:0c:60:6f:b5:c0:b5: - 23:22:2e:07:0b:cb:a9:74:cb:47:bb:1d:c1:d7:a5:6b:cc:2f: - d2:42:fd:49:dd:a7:89:cf:53:ba:da:00:5a:28:bf:82:df:f8: - ba:13:1d:50:86:82:fd:8e:30:8f:29:46:b0:1e:3d:35:da:38: - 62:16:18:4a:ad:e6:b6:51:6c:de:af:62:eb:01:d0:1e:24:fe: - 7a:8f:12:1a:12:68:b8:fb:66:99:14:14:45:5c:ae:e7:ae:69: - 17:81:2b:5a:37:c9:5e:2a:f4:c6:e2:a1:5c:54:9b:a6:54:00: - cf:f0:f1:c1:c7:98:30:1a:3b:36:16:db:a3:6e:ea:fd:ad:b2: - c2:da:ef:02:47:13:8a:c0:f1:b3:31:ad:4f:1c:e1:4f:9c:af: - 0f:0c:9d:f7:78:0d:d8:f4:35:56:80:da:b7:6d:17:8f:9d:1e: - 81:64:e1:fe:c5:45:ba:ad:6b:b9:0a:7a:4e:4f:4b:84:ee:4b: - f1:7d:dd:11 ------BEGIN CERTIFICATE----- -MIIEGjCCAwICEQCbfgZJoz5iudXukEhxKe9XMA0GCSqGSIb3DQEBBQUAMIHKMQsw -CQYDVQQGEwJVUzEXMBUGA1UEChMOVmVyaVNpZ24sIEluYy4xHzAdBgNVBAsTFlZl -cmlTaWduIFRydXN0IE5ldHdvcmsxOjA4BgNVBAsTMShjKSAxOTk5IFZlcmlTaWdu -LCBJbmMuIC0gRm9yIGF1dGhvcml6ZWQgdXNlIG9ubHkxRTBDBgNVBAMTPFZlcmlT -aWduIENsYXNzIDMgUHVibGljIFByaW1hcnkgQ2VydGlmaWNhdGlvbiBBdXRob3Jp -dHkgLSBHMzAeFw05OTEwMDEwMDAwMDBaFw0zNjA3MTYyMzU5NTlaMIHKMQswCQYD -VQQGEwJVUzEXMBUGA1UEChMOVmVyaVNpZ24sIEluYy4xHzAdBgNVBAsTFlZlcmlT -aWduIFRydXN0IE5ldHdvcmsxOjA4BgNVBAsTMShjKSAxOTk5IFZlcmlTaWduLCBJ -bmMuIC0gRm9yIGF1dGhvcml6ZWQgdXNlIG9ubHkxRTBDBgNVBAMTPFZlcmlTaWdu -IENsYXNzIDMgUHVibGljIFByaW1hcnkgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkg -LSBHMzCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAMu6nFL8eB8aHm8b -N3O9+MlrlBIwT/A2R/XQkQr1F8ilYcEWQE37imGQ5XYgwREGfassbqb1EUGO+i2t -KmFZpGcmTNDovFJbcCAEWNF6yaRpvIMXZK0Fi7zQWM6NjPXr8EJJC52XJ2cybuGu -kxUccLwgTS8Y3pKI6GyFVxEa6X7jJhFUokWWVYPKMIno3Nij7SqAP395ZVc+FSBm -CC+Vk7+qRy+oRpfwEuL+wgorUeZ25rdGt+INpsyow0xZVYnm6FNcHOqd8GIWC6fJ -Xwzw3sJ2zq/3avL6QaaiMxTJ5Xpj055iN9WFZZ4O5lMkdBteHRJTW8cs54NJOxWu -imi5V5cCAwEAATANBgkqhkiG9w0BAQUFAAOCAQEAERSWwauSCPc/L8my/uRan2Te -2yFPhpk0djZX3dAVL8WtfxUfN2JzPtTnX84XA9s1+ivbrmAJXx5fj267Cz3qWhMe -DGBvtcC1IyIuBwvLqXTLR7sdwdela8wv0kL9Sd2nic9TutoAWii/gt/4uhMdUIaC -/Y4wjylGsB49Ndo4YhYYSq3mtlFs3q9i6wHQHiT+eo8SGhJouPtmmRQURVyu565p -F4ErWjfJXir0xuKhXFSbplQAz/DxwceYMBo7Nhbbo27q/a2ywtrvAkcTisDxszGt -TxzhT5yvDwyd93gN2PQ1VoDat20Xj50egWTh/sVFuq1ruQp6Tk9LhO5L8X3dEQ== ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: - 13:86:35:4d:1d:3f:06:f2:c1:f9:65:05:d5:90:1c:62 - Signature Algorithm: sha1WithRSAEncryption - Issuer: C=US, O=VISA, OU=Visa International Service Association, CN=Visa eCommerce Root - Validity - Not Before: Jun 26 02:18:36 2002 GMT - Not After : Jun 24 00:16:12 2022 GMT - Subject: C=US, O=VISA, OU=Visa International Service Association, CN=Visa eCommerce Root - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (2048 bit) - Modulus: - 00:af:57:de:56:1e:6e:a1:da:60:b1:94:27:cb:17: - db:07:3f:80:85:4f:c8:9c:b6:d0:f4:6f:4f:cf:99: - d8:e1:db:c2:48:5c:3a:ac:39:33:c7:1f:6a:8b:26: - 3d:2b:35:f5:48:b1:91:c1:02:4e:04:96:91:7b:b0: - 33:f0:b1:14:4e:11:6f:b5:40:af:1b:45:a5:4a:ef: - 7e:b6:ac:f2:a0:1f:58:3f:12:46:60:3c:8d:a1:e0: - 7d:cf:57:3e:33:1e:fb:47:f1:aa:15:97:07:55:66: - a5:b5:2d:2e:d8:80:59:b2:a7:0d:b7:46:ec:21:63: - ff:35:ab:a5:02:cf:2a:f4:4c:fe:7b:f5:94:5d:84: - 4d:a8:f2:60:8f:db:0e:25:3c:9f:73:71:cf:94:df: - 4a:ea:db:df:72:38:8c:f3:96:bd:f1:17:bc:d2:ba: - 3b:45:5a:c6:a7:f6:c6:17:8b:01:9d:fc:19:a8:2a: - 83:16:b8:3a:48:fe:4e:3e:a0:ab:06:19:e9:53:f3: - 80:13:07:ed:2d:bf:3f:0a:3c:55:20:39:2c:2c:00: - 69:74:95:4a:bc:20:b2:a9:79:e5:18:89:91:a8:dc: - 1c:4d:ef:bb:7e:37:0b:5d:fe:39:a5:88:52:8c:00: - 6c:ec:18:7c:41:bd:f6:8b:75:77:ba:60:9d:84:e7: - fe:2d - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Basic Constraints: critical - CA:TRUE - X509v3 Key Usage: critical - Certificate Sign, CRL Sign - X509v3 Subject Key Identifier: - 15:38:83:0F:3F:2C:3F:70:33:1E:CD:46:FE:07:8C:20:E0:D7:C3:B7 - Signature Algorithm: sha1WithRSAEncryption - 5f:f1:41:7d:7c:5c:08:b9:2b:e0:d5:92:47:fa:67:5c:a5:13: - c3:03:21:9b:2b:4c:89:46:cf:59:4d:c9:fe:a5:40:b6:63:cd: - dd:71:28:95:67:11:cc:24:ac:d3:44:6c:71:ae:01:20:6b:03: - a2:8f:18:b7:29:3a:7d:e5:16:60:53:78:3c:c0:af:15:83:f7: - 8f:52:33:24:bd:64:93:97:ee:8b:f7:db:18:a8:6d:71:b3:f7: - 2c:17:d0:74:25:69:f7:fe:6b:3c:94:be:4d:4b:41:8c:4e:e2: - 73:d0:e3:90:22:73:43:cd:f3:ef:ea:73:ce:45:8a:b0:a6:49: - ff:4c:7d:9d:71:88:c4:76:1d:90:5b:1d:ee:fd:cc:f7:ee:fd: - 60:a5:b1:7a:16:71:d1:16:d0:7c:12:3c:6c:69:97:db:ae:5f: - 39:9a:70:2f:05:3c:19:46:04:99:20:36:d0:60:6e:61:06:bb: - 16:42:8c:70:f7:30:fb:e0:db:66:a3:00:01:bd:e6:2c:da:91: - 5f:a0:46:8b:4d:6a:9c:3d:3d:dd:05:46:fe:76:bf:a0:0a:3c: - e4:00:e6:27:b7:ff:84:2d:de:ba:22:27:96:10:71:eb:22:ed: - df:df:33:9c:cf:e3:ad:ae:8e:d4:8e:e6:4f:51:af:16:92:e0: - 5c:f6:07:0f ------BEGIN CERTIFICATE----- -MIIDojCCAoqgAwIBAgIQE4Y1TR0/BvLB+WUF1ZAcYjANBgkqhkiG9w0BAQUFADBr -MQswCQYDVQQGEwJVUzENMAsGA1UEChMEVklTQTEvMC0GA1UECxMmVmlzYSBJbnRl -cm5hdGlvbmFsIFNlcnZpY2UgQXNzb2NpYXRpb24xHDAaBgNVBAMTE1Zpc2EgZUNv -bW1lcmNlIFJvb3QwHhcNMDIwNjI2MDIxODM2WhcNMjIwNjI0MDAxNjEyWjBrMQsw -CQYDVQQGEwJVUzENMAsGA1UEChMEVklTQTEvMC0GA1UECxMmVmlzYSBJbnRlcm5h -dGlvbmFsIFNlcnZpY2UgQXNzb2NpYXRpb24xHDAaBgNVBAMTE1Zpc2EgZUNvbW1l -cmNlIFJvb3QwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCvV95WHm6h -2mCxlCfLF9sHP4CFT8icttD0b0/Pmdjh28JIXDqsOTPHH2qLJj0rNfVIsZHBAk4E -lpF7sDPwsRROEW+1QK8bRaVK7362rPKgH1g/EkZgPI2h4H3PVz4zHvtH8aoVlwdV -ZqW1LS7YgFmypw23RuwhY/81q6UCzyr0TP579ZRdhE2o8mCP2w4lPJ9zcc+U30rq -299yOIzzlr3xF7zSujtFWsan9sYXiwGd/BmoKoMWuDpI/k4+oKsGGelT84ATB+0t -vz8KPFUgOSwsAGl0lUq8ILKpeeUYiZGo3BxN77t+Nwtd/jmliFKMAGzsGHxBvfaL -dXe6YJ2E5/4tAgMBAAGjQjBAMA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQD -AgEGMB0GA1UdDgQWBBQVOIMPPyw/cDMezUb+B4wg4NfDtzANBgkqhkiG9w0BAQUF -AAOCAQEAX/FBfXxcCLkr4NWSR/pnXKUTwwMhmytMiUbPWU3J/qVAtmPN3XEolWcR -zCSs00Rsca4BIGsDoo8Ytyk6feUWYFN4PMCvFYP3j1IzJL1kk5fui/fbGKhtcbP3 -LBfQdCVp9/5rPJS+TUtBjE7ic9DjkCJzQ83z7+pzzkWKsKZJ/0x9nXGIxHYdkFsd -7v3M9+79YKWxehZx0RbQfBI8bGmX265fOZpwLwU8GUYEmSA20GBuYQa7FkKMcPcw -++DbZqMAAb3mLNqRX6BGi01qnD093QVG/na/oAo85ADmJ7f/hC3euiInlhBx6yLt -398znM/jra6O1I7mT1GvFpLgXPYHDw== ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: - 5e:68:d6:11:71:94:63:50:56:00:68:f3:3e:c9:c5:91 - Signature Algorithm: sha1WithRSAEncryption - Issuer: C=CN, O=WoSign CA Limited, CN=Certification Authority of WoSign - Validity - Not Before: Aug 8 01:00:01 2009 GMT - Not After : Aug 8 01:00:01 2039 GMT - Subject: C=CN, O=WoSign CA Limited, CN=Certification Authority of WoSign - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (4096 bit) - Modulus: - 00:bd:ca:8d:ac:b8:91:15:56:97:7b:6b:5c:7a:c2: - de:6b:d9:a1:b0:c3:10:23:fa:a7:a1:b2:cc:31:fa: - 3e:d9:a6:29:6f:16:3d:e0:6b:f8:b8:40:5f:db:39: - a8:00:7a:8b:a0:4d:54:7d:c2:22:78:fc:8e:09:b8: - a8:85:d7:cc:95:97:4b:74:d8:9e:7e:f0:00:e4:0e: - 89:ae:49:28:44:1a:10:99:32:0f:25:88:53:a4:0d: - b3:0f:12:08:16:0b:03:71:27:1c:7f:e1:db:d2:fd: - 67:68:c4:05:5d:0a:0e:5d:70:d7:d8:97:a0:bc:53: - 41:9a:91:8d:f4:9e:36:66:7a:7e:56:c1:90:5f:e6: - b1:68:20:36:a4:8c:24:2c:2c:47:0b:59:76:66:30: - b5:be:de:ed:8f:f8:9d:d3:bb:01:30:e6:f2:f3:0e: - e0:2c:92:80:f3:85:f9:28:8a:b4:54:2e:9a:ed:f7: - 76:fc:15:68:16:eb:4a:6c:eb:2e:12:8f:d4:cf:fe: - 0c:c7:5c:1d:0b:7e:05:32:be:5e:b0:09:2a:42:d5: - c9:4e:90:b3:59:0d:bb:7a:7e:cd:d5:08:5a:b4:7f: - d8:1c:69:11:f9:27:0f:7b:06:af:54:83:18:7b:e1: - dd:54:7a:51:68:6e:77:fc:c6:bf:52:4a:66:46:a1: - b2:67:1a:bb:a3:4f:77:a0:be:5d:ff:fc:56:0b:43: - 72:77:90:ca:9e:f9:f2:39:f5:0d:a9:f4:ea:d7:e7: - b3:10:2f:30:42:37:21:cc:30:70:c9:86:98:0f:cc: - 58:4d:83:bb:7d:e5:1a:a5:37:8d:b6:ac:32:97:00: - 3a:63:71:24:1e:9e:37:c4:ff:74:d4:37:c0:e2:fe: - 88:46:60:11:dd:08:3f:50:36:ab:b8:7a:a4:95:62: - 6a:6e:b0:ca:6a:21:5a:69:f3:f3:fb:1d:70:39:95: - f3:a7:6e:a6:81:89:a1:88:c5:3b:71:ca:a3:52:ee: - 83:bb:fd:a0:77:f4:e4:6f:e7:42:db:6d:4a:99:8a: - 34:48:bc:17:dc:e4:80:08:22:b6:f2:31:c0:3f:04: - 3e:eb:9f:20:79:d6:b8:06:64:64:02:31:d7:a9:cd: - 52:fb:84:45:69:09:00:2a:dc:55:8b:c4:06:46:4b: - c0:4a:1d:09:5b:39:28:fd:a9:ab:ce:00:f9:2e:48: - 4b:26:e6:30:4c:a5:58:ca:b4:44:82:4f:e7:91:1e: - 33:c3:b0:93:ff:11:fc:81:d2:ca:1f:71:29:dd:76: - 4f:92:25:af:1d:81:b7:0f:2f:8c:c3:06:cc:2f:27: - a3:4a:e4:0e:99:ba:7c:1e:45:1f:7f:aa:19:45:96: - fd:fc:3d - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Key Usage: critical - Certificate Sign, CRL Sign - X509v3 Basic Constraints: critical - CA:TRUE - X509v3 Subject Key Identifier: - E1:66:CF:0E:D1:F1:B3:4B:B7:06:20:14:FE:87:12:D5:F6:FE:FB:3E - Signature Algorithm: sha1WithRSAEncryption - a8:cb:72:40:b2:76:c1:7e:7b:fc:ad:64:e3:32:7b:cc:3c:b6: - 5d:46:d3:f5:2c:e2:70:5d:c8:2e:d8:06:7d:98:d1:0b:21:a0: - 89:59:24:01:9d:f9:af:09:7d:0a:23:82:34:d5:fc:7c:72:99: - b9:a3:d7:54:f4:ea:52:70:0e:c5:f5:d6:3b:e1:3a:09:32:e6: - 21:39:93:bd:b3:15:ea:4f:6a:f4:f5:8b:3f:2f:7c:8d:58:2e: - c5:e1:39:a0:3e:c7:3d:4a:73:9e:40:7a:c0:2b:61:a9:67:c9: - f3:24:b9:b3:6d:55:2c:5a:1d:9e:25:72:ce:0b:ad:aa:c7:55: - 62:0b:be:fb:63:b3:61:44:23:a3:cb:e1:1a:0e:f7:9a:06:4d: - de:d4:23:4e:21:96:5b:39:5b:57:1d:2f:5d:08:5e:09:79:ff: - 7c:97:b5:4d:83:ae:0d:d6:e6:a3:79:e0:33:d0:99:96:02:30: - a7:3e:ff:d2:a3:43:3f:05:5a:06:ea:44:02:da:7c:f8:48:d0: - 33:a9:f9:07:c7:95:e1:f5:3e:f5:5d:71:ba:f2:95:a9:74:88: - 61:59:e3:bf:ca:5a:13:ba:72:b4:8c:5d:36:87:e9:a6:c5:3c: - 13:bf:de:d0:44:26:ee:b7:ec:2e:70:fa:d7:9d:b7:ac:e5:c5: - 40:5a:e6:d7:6c:7b:2c:c3:56:9b:47:cd:0b:ce:fa:1b:b4:21: - d7:b7:66:b8:f4:25:30:8b:5c:0d:b9:ea:67:b2:f4:6d:ae:d5: - a1:9e:4f:d8:9f:e9:27:02:b0:1d:06:d6:8f:e3:fb:48:12:9f: - 7f:11:a1:10:3e:4c:51:3a:96:b0:d1:13:f1:c7:d8:26:ae:3a: - ca:91:c4:69:9d:df:01:29:64:51:6f:68:da:14:ec:08:41:97: - 90:8d:d0:b2:80:f2:cf:c2:3d:bf:91:68:c5:80:67:1e:c4:60: - 13:55:d5:61:99:57:7c:ba:95:0f:61:49:3a:ca:75:bc:c9:0a: - 93:3f:67:0e:12:f2:28:e2:31:1b:c0:57:16:df:08:7c:19:c1: - 7e:0f:1f:85:1e:0a:36:7c:5b:7e:27:bc:7a:bf:e0:db:f4:da: - 52:bd:de:0c:54:70:31:91:43:95:c8:bc:f0:3e:dd:09:7e:30: - 64:50:ed:7f:01:a4:33:67:4d:68:4f:be:15:ef:b0:f6:02:11: - a2:1b:13:25:3a:dc:c2:59:f1:e3:5c:46:bb:67:2c:02:46:ea: - 1e:48:a6:e6:5b:d9:b5:bc:51:a2:92:96:db:aa:c6:37:22:a6: - fe:cc:20:74:a3:2d:a9:2e:6b:cb:c0:82:11:21:b5:93:79:ee: - 44:86:be:d7:1e:e4:1e:fb ------BEGIN CERTIFICATE----- -MIIFdjCCA16gAwIBAgIQXmjWEXGUY1BWAGjzPsnFkTANBgkqhkiG9w0BAQUFADBV -MQswCQYDVQQGEwJDTjEaMBgGA1UEChMRV29TaWduIENBIExpbWl0ZWQxKjAoBgNV -BAMTIUNlcnRpZmljYXRpb24gQXV0aG9yaXR5IG9mIFdvU2lnbjAeFw0wOTA4MDgw -MTAwMDFaFw0zOTA4MDgwMTAwMDFaMFUxCzAJBgNVBAYTAkNOMRowGAYDVQQKExFX -b1NpZ24gQ0EgTGltaXRlZDEqMCgGA1UEAxMhQ2VydGlmaWNhdGlvbiBBdXRob3Jp -dHkgb2YgV29TaWduMIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAvcqN -rLiRFVaXe2tcesLea9mhsMMQI/qnobLMMfo+2aYpbxY94Gv4uEBf2zmoAHqLoE1U -fcIiePyOCbiohdfMlZdLdNiefvAA5A6JrkkoRBoQmTIPJYhTpA2zDxIIFgsDcScc -f+Hb0v1naMQFXQoOXXDX2JegvFNBmpGN9J42Znp+VsGQX+axaCA2pIwkLCxHC1l2 -ZjC1vt7tj/id07sBMOby8w7gLJKA84X5KIq0VC6a7fd2/BVoFutKbOsuEo/Uz/4M -x1wdC34FMr5esAkqQtXJTpCzWQ27en7N1QhatH/YHGkR+ScPewavVIMYe+HdVHpR -aG53/Ma/UkpmRqGyZxq7o093oL5d//xWC0Nyd5DKnvnyOfUNqfTq1+ezEC8wQjch -zDBwyYaYD8xYTYO7feUapTeNtqwylwA6Y3EkHp43xP901DfA4v6IRmAR3Qg/UDar -uHqklWJqbrDKaiFaafPz+x1wOZXzp26mgYmhiMU7ccqjUu6Du/2gd/Tkb+dC221K -mYo0SLwX3OSACCK28jHAPwQ+658geda4BmRkAjHXqc1S+4RFaQkAKtxVi8QGRkvA -Sh0JWzko/amrzgD5LkhLJuYwTKVYyrREgk/nkR4zw7CT/xH8gdLKH3Ep3XZPkiWv -HYG3Dy+MwwbMLyejSuQOmbp8HkUff6oZRZb9/D0CAwEAAaNCMEAwDgYDVR0PAQH/ -BAQDAgEGMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFOFmzw7R8bNLtwYgFP6H -EtX2/vs+MA0GCSqGSIb3DQEBBQUAA4ICAQCoy3JAsnbBfnv8rWTjMnvMPLZdRtP1 -LOJwXcgu2AZ9mNELIaCJWSQBnfmvCX0KI4I01fx8cpm5o9dU9OpScA7F9dY74ToJ -MuYhOZO9sxXqT2r09Ys/L3yNWC7F4TmgPsc9SnOeQHrAK2GpZ8nzJLmzbVUsWh2e -JXLOC62qx1ViC777Y7NhRCOjy+EaDveaBk3e1CNOIZZbOVtXHS9dCF4Jef98l7VN -g64N1uajeeAz0JmWAjCnPv/So0M/BVoG6kQC2nz4SNAzqfkHx5Xh9T71XXG68pWp -dIhhWeO/yloTunK0jF02h+mmxTwTv97QRCbut+wucPrXnbes5cVAWubXbHssw1ab -R80LzvobtCHXt2a49CUwi1wNuepnsvRtrtWhnk/Yn+knArAdBtaP4/tIEp9/EaEQ -PkxROpaw0RPxx9gmrjrKkcRpnd8BKWRRb2jaFOwIQZeQjdCygPLPwj2/kWjFgGce -xGATVdVhmVd8upUPYUk6ynW8yQqTP2cOEvIo4jEbwFcW3wh8GcF+Dx+FHgo2fFt+ -J7x6v+Db9NpSvd4MVHAxkUOVyLzwPt0JfjBkUO1/AaQzZ01oT74V77D2AhGiGxMl -OtzCWfHjXEa7ZywCRuoeSKbmW9m1vFGikpbbqsY3Iqb+zCB0oy2pLmvLwIIRIbWT -ee5Ehr7XHuQe+w== ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: - 50:70:6b:cd:d8:13:fc:1b:4e:3b:33:72:d2:11:48:8d - Signature Algorithm: sha256WithRSAEncryption - Issuer: C=CN, O=WoSign CA Limited, CN=CA \xE6\xB2\x83\xE9\x80\x9A\xE6\xA0\xB9\xE8\xAF\x81\xE4\xB9\xA6 - Validity - Not Before: Aug 8 01:00:01 2009 GMT - Not After : Aug 8 01:00:01 2039 GMT - Subject: C=CN, O=WoSign CA Limited, CN=CA \xE6\xB2\x83\xE9\x80\x9A\xE6\xA0\xB9\xE8\xAF\x81\xE4\xB9\xA6 - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (4096 bit) - Modulus: - 00:d0:49:21:1e:25:fc:87:c1:2a:c2:ac:db:76:86: - 06:4e:e7:d0:74:34:dc:ed:65:35:fc:50:d6:88:3f: - a4:f0:7f:eb:0f:5f:79:2f:89:b1:fd:bc:63:58:37: - 93:9b:38:f8:b7:5b:a9:fa:d8:71:c7:b4:bc:80:97: - 8d:6c:4b:f1:50:d5:2a:29:aa:a8:19:7a:96:e6:95: - 8e:74:ed:97:0a:57:75:f4:05:db:6d:0b:39:b9:01: - 7f:aa:f6:d6:da:6c:e6:05:e0:a4:4d:52:fc:db:d0: - 74:b7:11:8c:7b:8d:4f:ff:87:83:ae:ff:05:03:13: - 57:50:37:fe:8c:96:52:10:4c:5f:bf:94:71:69:d9: - 96:3e:0c:43:4f:be:30:c0:9f:39:74:4f:06:45:5d: - a3:d6:56:39:68:07:cc:87:4f:50:77:93:71:d9:44: - 08:b1:8a:34:e9:89:ac:db:9b:4e:e1:d9:e4:52:45: - 8c:2e:14:1f:91:6b:19:1d:68:29:2c:56:c4:e2:1e: - 13:57:64:f0:61:e3:b9:11:df:b0:e1:57:a0:1b:ad: - d7:5f:d1:af:db:2b:2d:3f:d0:68:8e:0f:ea:9f:0f: - 8b:35:58:1b:13:1c:f4:de:35:a1:0a:5d:d6:ea:df: - 12:6f:c0:fb:69:07:46:72:dc:81:f6:04:23:17:e0: - 4d:75:e1:72:6f:b0:28:eb:9b:e1:e1:83:a1:9f:4a: - 5d:af:cc:9b:fa:02:20:b6:18:62:77:91:3b:a3:d5: - 65:ad:dc:7c:90:77:1c:44:41:a4:4a:8b:eb:95:72: - e9:f6:09:64:dc:a8:2d:9f:74:78:e8:c1:a2:09:63: - 9c:ef:a0:db:4f:9d:95:ab:20:4f:b7:b0:f7:87:5c: - a6:a0:e4:37:38:c7:5c:e3:35:0f:2c:ad:a3:80:a2: - ec:2e:5d:c0:cf:ed:8b:05:c2:e6:73:6e:f6:89:d5: - f5:d2:46:8e:ea:6d:63:1b:1e:8a:c9:7d:a6:f8:9c: - eb:e5:d5:63:85:4d:73:66:69:11:fe:c8:0e:f4:c1: - c7:66:49:53:7e:e4:19:6b:f1:e9:7a:59:a3:6d:7e: - c5:17:e6:27:c6:ef:1b:db:6f:fc:0d:4d:06:01:b4: - 0e:5c:30:46:55:60:af:38:65:3a:ca:47:ba:ac:2c: - cc:46:1f:b2:46:96:3f:f3:ed:26:05:ee:77:a1:6a: - 6b:7e:2d:6d:58:5c:4a:d4:8e:67:b8:f1:da:d5:46: - 8a:27:f9:11:f2:c9:42:fe:4e:de:df:1f:5c:c4:a4: - 86:87:16:33:a1:a7:17:18:a5:0d:e4:05:e5:2b:c2: - 2b:0b:a2:95:90:b9:fd:60:3c:4e:89:3e:e7:9c:ee: - 1f:bb:01 - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Key Usage: critical - Certificate Sign, CRL Sign - X509v3 Basic Constraints: critical - CA:TRUE - X509v3 Subject Key Identifier: - E0:4D:BF:DC:9B:41:5D:13:E8:64:F0:A7:E9:15:A4:E1:81:C1:BA:31 - Signature Algorithm: sha256WithRSAEncryption - 6a:8a:70:38:59:b6:da:8b:18:c8:be:2a:d3:b6:19:d5:66:29: - 7a:5d:cd:5b:2f:73:1c:26:4e:a3:7d:6f:ab:b7:29:4d:a6:e9: - a5:11:83:a7:39:73:af:10:44:92:e6:25:5d:4f:61:fa:c8:06: - be:4e:4b:ef:fe:f3:31:fe:c6:7c:70:0a:41:58:da:e8:99:4b: - 96:c9:78:bc:98:7c:02:29:ed:09:80:e6:0a:3a:82:02:2a:e2: - c9:2f:c8:56:19:26:ee:78:1c:23:fd:f7:93:65:4e:e7:f3:98: - 98:af:cd:dd:d9:9e:40:88:31:28:3a:ab:2e:0b:b0:ac:0c:24: - fa:7a:26:98:f3:12:61:10:f4:5d:17:f7:7e:e2:78:97:54:e2: - 8c:e8:29:ba:8c:10:32:bd:dd:33:6b:38:86:7e:39:3d:0e:03: - 72:a7:5d:79:8f:45:8a:59:ae:5b:21:6e:31:46:d5:59:8d:cf: - 15:5f:dd:31:25:cf:db:60:d6:81:44:72:29:02:57:f6:96:d4: - d6:ff:ea:29:db:39:c5:b8:2c:8a:1a:8d:ce:cb:e7:42:31:86: - 05:68:0e:9e:14:dd:00:90:ba:69:45:08:db:6e:90:81:86:a7: - 2a:05:3f:e6:84:39:f8:b7:f9:57:5f:4c:a4:79:5a:10:0c:5e: - d5:6b:ff:35:5f:05:51:1e:6c:a3:75:a9:cf:50:83:d3:7c:f4: - 66:f7:82:8d:3d:0c:7d:e8:df:7b:a8:0e:1b:2c:9c:ae:40:70: - 87:da:ed:a7:16:82:5a:be:35:6c:20:4e:22:61:d9:bc:51:7a: - cd:7a:61:dc:4b:11:f9:fe:67:34:cf:2e:04:66:61:5c:57:97: - 23:8c:f3:86:1b:48:df:2a:af:a7:c1:ff:d8:8e:3e:03:bb:d8: - 2a:b0:fa:14:25:b2:51:6b:86:43:85:2e:07:23:16:80:8d:4c: - fb:b4:63:3b:cc:c3:74:ed:1b:a3:1e:fe:35:0f:5f:7c:1d:16: - 86:f5:0e:c3:95:f1:2f:af:5d:25:3b:51:e6:d7:76:41:38:d1: - 4b:03:39:28:a5:1e:91:72:d4:7d:ab:97:33:c4:d3:3e:e0:69: - b6:28:79:a0:09:8d:1c:d1:ff:41:72:48:06:fc:9a:2e:e7:20: - f9:9b:a2:de:89:ed:ae:3c:09:af:ca:57:b3:92:89:70:40:e4: - 2f:4f:c2:70:83:40:d7:24:2c:6b:e7:09:1f:d3:d5:c7:c1:08: - f4:db:0e:3b:1c:07:0b:43:11:84:21:86:e9:80:d4:75:d8:ab: - f1:02:62:c1:b1:7e:55:61:cf:13:d7:26:b0:d7:9c:cb:29:8b: - 38:4a:0b:0e:90:8d:ba:a1 ------BEGIN CERTIFICATE----- -MIIFWDCCA0CgAwIBAgIQUHBrzdgT/BtOOzNy0hFIjTANBgkqhkiG9w0BAQsFADBG -MQswCQYDVQQGEwJDTjEaMBgGA1UEChMRV29TaWduIENBIExpbWl0ZWQxGzAZBgNV -BAMMEkNBIOayg+mAmuagueivgeS5pjAeFw0wOTA4MDgwMTAwMDFaFw0zOTA4MDgw -MTAwMDFaMEYxCzAJBgNVBAYTAkNOMRowGAYDVQQKExFXb1NpZ24gQ0EgTGltaXRl -ZDEbMBkGA1UEAwwSQ0Eg5rKD6YCa5qC56K+B5LmmMIICIjANBgkqhkiG9w0BAQEF -AAOCAg8AMIICCgKCAgEA0EkhHiX8h8EqwqzbdoYGTufQdDTc7WU1/FDWiD+k8H/r -D195L4mx/bxjWDeTmzj4t1up+thxx7S8gJeNbEvxUNUqKaqoGXqW5pWOdO2XCld1 -9AXbbQs5uQF/qvbW2mzmBeCkTVL829B0txGMe41P/4eDrv8FAxNXUDf+jJZSEExf -v5RxadmWPgxDT74wwJ85dE8GRV2j1lY5aAfMh09Qd5Nx2UQIsYo06Yms25tO4dnk -UkWMLhQfkWsZHWgpLFbE4h4TV2TwYeO5Ed+w4VegG63XX9Gv2ystP9Bojg/qnw+L -NVgbExz03jWhCl3W6t8Sb8D7aQdGctyB9gQjF+BNdeFyb7Ao65vh4YOhn0pdr8yb -+gIgthhid5E7o9Vlrdx8kHccREGkSovrlXLp9glk3Kgtn3R46MGiCWOc76DbT52V -qyBPt7D3h1ymoOQ3OMdc4zUPLK2jgKLsLl3Az+2LBcLmc272idX10kaO6m1jGx6K -yX2m+Jzr5dVjhU1zZmkR/sgO9MHHZklTfuQZa/HpelmjbX7FF+Ynxu8b22/8DU0G -AbQOXDBGVWCvOGU6yke6rCzMRh+yRpY/8+0mBe53oWprfi1tWFxK1I5nuPHa1UaK -J/kR8slC/k7e3x9cxKSGhxYzoacXGKUN5AXlK8IrC6KVkLn9YDxOiT7nnO4fuwEC -AwEAAaNCMEAwDgYDVR0PAQH/BAQDAgEGMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0O -BBYEFOBNv9ybQV0T6GTwp+kVpOGBwboxMA0GCSqGSIb3DQEBCwUAA4ICAQBqinA4 -WbbaixjIvirTthnVZil6Xc1bL3McJk6jfW+rtylNpumlEYOnOXOvEESS5iVdT2H6 -yAa+Tkvv/vMx/sZ8cApBWNromUuWyXi8mHwCKe0JgOYKOoICKuLJL8hWGSbueBwj -/feTZU7n85iYr83d2Z5AiDEoOqsuC7CsDCT6eiaY8xJhEPRdF/d+4niXVOKM6Cm6 -jBAyvd0zaziGfjk9DgNyp115j0WKWa5bIW4xRtVZjc8VX90xJc/bYNaBRHIpAlf2 -ltTW/+op2znFuCyKGo3Oy+dCMYYFaA6eFN0AkLppRQjbbpCBhqcqBT/mhDn4t/lX -X0ykeVoQDF7Va/81XwVRHmyjdanPUIPTfPRm94KNPQx96N97qA4bLJyuQHCH2u2n -FoJavjVsIE4iYdm8UXrNemHcSxH5/mc0zy4EZmFcV5cjjPOGG0jfKq+nwf/Yjj4D -u9gqsPoUJbJRa4ZDhS4HIxaAjUz7tGM7zMN07RujHv41D198HRaG9Q7DlfEvr10l -O1Hm13ZBONFLAzkopR6RctR9q5czxNM+4Gm2KHmgCY0c0f9BckgG/Jou5yD5m6Le -ie2uPAmvylezkolwQOQvT8Jwg0DXJCxr5wkf09XHwQj02w47HAcLQxGEIYbpgNR1 -2KvxAmLBsX5VYc8T1yaw15zLKYs4SgsOkI26oQ== ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: - 50:94:6c:ec:18:ea:d5:9c:4d:d5:97:ef:75:8f:a0:ad - Signature Algorithm: sha1WithRSAEncryption - Issuer: C=US, OU=www.xrampsecurity.com, O=XRamp Security Services Inc, CN=XRamp Global Certification Authority - Validity - Not Before: Nov 1 17:14:04 2004 GMT - Not After : Jan 1 05:37:19 2035 GMT - Subject: C=US, OU=www.xrampsecurity.com, O=XRamp Security Services Inc, CN=XRamp Global Certification Authority - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (2048 bit) - Modulus: - 00:98:24:1e:bd:15:b4:ba:df:c7:8c:a5:27:b6:38: - 0b:69:f3:b6:4e:a8:2c:2e:21:1d:5c:44:df:21:5d: - 7e:23:74:fe:5e:7e:b4:4a:b7:a6:ad:1f:ae:e0:06: - 16:e2:9b:5b:d9:67:74:6b:5d:80:8f:29:9d:86:1b: - d9:9c:0d:98:6d:76:10:28:58:e4:65:b0:7f:4a:98: - 79:9f:e0:c3:31:7e:80:2b:b5:8c:c0:40:3b:11:86: - d0:cb:a2:86:36:60:a4:d5:30:82:6d:d9:6e:d0:0f: - 12:04:33:97:5f:4f:61:5a:f0:e4:f9:91:ab:e7:1d: - 3b:bc:e8:cf:f4:6b:2d:34:7c:e2:48:61:1c:8e:f3: - 61:44:cc:6f:a0:4a:a9:94:b0:4d:da:e7:a9:34:7a: - 72:38:a8:41:cc:3c:94:11:7d:eb:c8:a6:8c:b7:86: - cb:ca:33:3b:d9:3d:37:8b:fb:7a:3e:86:2c:e7:73: - d7:0a:57:ac:64:9b:19:eb:f4:0f:04:08:8a:ac:03: - 17:19:64:f4:5a:25:22:8d:34:2c:b2:f6:68:1d:12: - 6d:d3:8a:1e:14:da:c4:8f:a6:e2:23:85:d5:7a:0d: - bd:6a:e0:e9:ec:ec:17:bb:42:1b:67:aa:25:ed:45: - 83:21:fc:c1:c9:7c:d5:62:3e:fa:f2:c5:2d:d3:fd: - d4:65 - Exponent: 65537 (0x10001) - X509v3 extensions: - 1.3.6.1.4.1.311.20.2: - ...C.A - X509v3 Key Usage: - Digital Signature, Certificate Sign, CRL Sign - X509v3 Basic Constraints: critical - CA:TRUE - X509v3 Subject Key Identifier: - C6:4F:A2:3D:06:63:84:09:9C:CE:62:E4:04:AC:8D:5C:B5:E9:B6:1B - X509v3 CRL Distribution Points: - - Full Name: - URI:http://crl.xrampsecurity.com/XGCA.crl - - 1.3.6.1.4.1.311.21.1: - ... - Signature Algorithm: sha1WithRSAEncryption - 91:15:39:03:01:1b:67:fb:4a:1c:f9:0a:60:5b:a1:da:4d:97: - 62:f9:24:53:27:d7:82:64:4e:90:2e:c3:49:1b:2b:9a:dc:fc: - a8:78:67:35:f1:1d:f0:11:bd:b7:48:e3:10:f6:0d:df:3f:d2: - c9:b6:aa:55:a4:48:ba:02:db:de:59:2e:15:5b:3b:9d:16:7d: - 47:d7:37:ea:5f:4d:76:12:36:bb:1f:d7:a1:81:04:46:20:a3: - 2c:6d:a9:9e:01:7e:3f:29:ce:00:93:df:fd:c9:92:73:89:89: - 64:9e:e7:2b:e4:1c:91:2c:d2:b9:ce:7d:ce:6f:31:99:d3:e6: - be:d2:1e:90:f0:09:14:79:5c:23:ab:4d:d2:da:21:1f:4d:99: - 79:9d:e1:cf:27:9f:10:9b:1c:88:0d:b0:8a:64:41:31:b8:0e: - 6c:90:24:a4:9b:5c:71:8f:ba:bb:7e:1c:1b:db:6a:80:0f:21: - bc:e9:db:a6:b7:40:f4:b2:8b:a9:b1:e4:ef:9a:1a:d0:3d:69: - 99:ee:a8:28:a3:e1:3c:b3:f0:b2:11:9c:cf:7c:40:e6:dd:e7: - 43:7d:a2:d8:3a:b5:a9:8d:f2:34:99:c4:d4:10:e1:06:fd:09: - 84:10:3b:ee:c4:4c:f4:ec:27:7c:42:c2:74:7c:82:8a:09:c9: - b4:03:25:bc ------BEGIN CERTIFICATE----- -MIIEMDCCAxigAwIBAgIQUJRs7Bjq1ZxN1ZfvdY+grTANBgkqhkiG9w0BAQUFADCB -gjELMAkGA1UEBhMCVVMxHjAcBgNVBAsTFXd3dy54cmFtcHNlY3VyaXR5LmNvbTEk -MCIGA1UEChMbWFJhbXAgU2VjdXJpdHkgU2VydmljZXMgSW5jMS0wKwYDVQQDEyRY -UmFtcCBHbG9iYWwgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNMDQxMTAxMTcx -NDA0WhcNMzUwMTAxMDUzNzE5WjCBgjELMAkGA1UEBhMCVVMxHjAcBgNVBAsTFXd3 -dy54cmFtcHNlY3VyaXR5LmNvbTEkMCIGA1UEChMbWFJhbXAgU2VjdXJpdHkgU2Vy -dmljZXMgSW5jMS0wKwYDVQQDEyRYUmFtcCBHbG9iYWwgQ2VydGlmaWNhdGlvbiBB -dXRob3JpdHkwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCYJB69FbS6 -38eMpSe2OAtp87ZOqCwuIR1cRN8hXX4jdP5efrRKt6atH67gBhbim1vZZ3RrXYCP -KZ2GG9mcDZhtdhAoWORlsH9KmHmf4MMxfoArtYzAQDsRhtDLooY2YKTVMIJt2W7Q -DxIEM5dfT2Fa8OT5kavnHTu86M/0ay00fOJIYRyO82FEzG+gSqmUsE3a56k0enI4 -qEHMPJQRfevIpoy3hsvKMzvZPTeL+3o+hiznc9cKV6xkmxnr9A8ECIqsAxcZZPRa -JSKNNCyy9mgdEm3Tih4U2sSPpuIjhdV6Db1q4Ons7Be7QhtnqiXtRYMh/MHJfNVi -PvryxS3T/dRlAgMBAAGjgZ8wgZwwEwYJKwYBBAGCNxQCBAYeBABDAEEwCwYDVR0P -BAQDAgGGMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFMZPoj0GY4QJnM5i5ASs -jVy16bYbMDYGA1UdHwQvMC0wK6ApoCeGJWh0dHA6Ly9jcmwueHJhbXBzZWN1cml0 -eS5jb20vWEdDQS5jcmwwEAYJKwYBBAGCNxUBBAMCAQEwDQYJKoZIhvcNAQEFBQAD -ggEBAJEVOQMBG2f7Shz5CmBbodpNl2L5JFMn14JkTpAuw0kbK5rc/Kh4ZzXxHfAR -vbdI4xD2Dd8/0sm2qlWkSLoC295ZLhVbO50WfUfXN+pfTXYSNrsf16GBBEYgoyxt -qZ4Bfj8pzgCT3/3JknOJiWSe5yvkHJEs0rnOfc5vMZnT5r7SHpDwCRR5XCOrTdLa -IR9NmXmd4c8nnxCbHIgNsIpkQTG4DmyQJKSbXHGPurt+HBvbaoAPIbzp26a3QPSy -i6mx5O+aGtA9aZnuqCij4Tyz8LIRnM98QObd50N9otg6tamN8jSZxNQQ4Qb9CYQQ -O+7ETPTsJ3xCwnR8gooJybQDJbw= ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: - 20:06:05:16:70:02 - Signature Algorithm: sha1WithRSAEncryption - Issuer: C=RO, O=certSIGN, OU=certSIGN ROOT CA - Validity - Not Before: Jul 4 17:20:04 2006 GMT - Not After : Jul 4 17:20:04 2031 GMT - Subject: C=RO, O=certSIGN, OU=certSIGN ROOT CA - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (2048 bit) - Modulus: - 00:b7:33:b9:7e:c8:25:4a:8e:b5:db:b4:28:1b:aa: - 57:90:e8:d1:22:d3:64:ba:d3:93:e8:d4:ac:86:61: - 40:6a:60:57:68:54:84:4d:bc:6a:54:02:05:ff:df: - 9b:9a:2a:ae:5d:07:8f:4a:c3:28:7f:ef:fb:2b:fa: - 79:f1:c7:ad:f0:10:53:24:90:8b:66:c9:a8:88:ab: - af:5a:a3:00:e9:be:ba:46:ee:5b:73:7b:2c:17:82: - 81:5e:62:2c:a1:02:65:b3:bd:c5:2b:00:7e:c4:fc: - 03:33:57:0d:ed:e2:fa:ce:5d:45:d6:38:cd:35:b6: - b2:c1:d0:9c:81:4a:aa:e4:b2:01:5c:1d:8f:5f:99: - c4:b1:ad:db:88:21:eb:90:08:82:80:f3:30:a3:43: - e6:90:82:ae:55:28:49:ed:5b:d7:a9:10:38:0e:fe: - 8f:4c:5b:9b:46:ea:41:f5:b0:08:74:c3:d0:88:33: - b6:7c:d7:74:df:dc:84:d1:43:0e:75:39:a1:25:40: - 28:ea:78:cb:0e:2c:2e:39:9d:8c:8b:6e:16:1c:2f: - 26:82:10:e2:e3:65:94:0a:04:c0:5e:f7:5d:5b:f8: - 10:e2:d0:ba:7a:4b:fb:de:37:00:00:1a:5b:28:e3: - d2:9c:73:3e:32:87:98:a1:c9:51:2f:d7:de:ac:33: - b3:4f - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Basic Constraints: critical - CA:TRUE - X509v3 Key Usage: critical - Digital Signature, Non Repudiation, Certificate Sign, CRL Sign - X509v3 Subject Key Identifier: - E0:8C:9B:DB:25:49:B3:F1:7C:86:D6:B2:42:87:0B:D0:6B:A0:D9:E4 - Signature Algorithm: sha1WithRSAEncryption - 3e:d2:1c:89:2e:35:fc:f8:75:dd:e6:7f:65:88:f4:72:4c:c9: - 2c:d7:32:4e:f3:dd:19:79:47:bd:8e:3b:5b:93:0f:50:49:24: - 13:6b:14:06:72:ef:09:d3:a1:a1:e3:40:84:c9:e7:18:32:74: - 3c:48:6e:0f:9f:4b:d4:f7:1e:d3:93:86:64:54:97:63:72:50: - d5:55:cf:fa:20:93:02:a2:9b:c3:23:93:4e:16:55:76:a0:70: - 79:6d:cd:21:1f:cf:2f:2d:bc:19:e3:88:31:f8:59:1a:81:09: - c8:97:a6:74:c7:60:c4:5b:cc:57:8e:b2:75:fd:1b:02:09:db: - 59:6f:72:93:69:f7:31:41:d6:88:38:bf:87:b2:bd:16:79:f9: - aa:e4:be:88:25:dd:61:27:23:1c:b5:31:07:04:36:b4:1a:90: - bd:a0:74:71:50:89:6d:bc:14:e3:0f:86:ae:f1:ab:3e:c7:a0: - 09:cc:a3:48:d1:e0:db:64:e7:92:b5:cf:af:72:43:70:8b:f9: - c3:84:3c:13:aa:7e:92:9b:57:53:93:fa:70:c2:91:0e:31:f9: - 9b:67:5d:e9:96:38:5e:5f:b3:73:4e:88:15:67:de:9e:76:10: - 62:20:be:55:69:95:43:00:39:4d:f6:ee:b0:5a:4e:49:44:54: - 58:5f:42:83 ------BEGIN CERTIFICATE----- -MIIDODCCAiCgAwIBAgIGIAYFFnACMA0GCSqGSIb3DQEBBQUAMDsxCzAJBgNVBAYT -AlJPMREwDwYDVQQKEwhjZXJ0U0lHTjEZMBcGA1UECxMQY2VydFNJR04gUk9PVCBD -QTAeFw0wNjA3MDQxNzIwMDRaFw0zMTA3MDQxNzIwMDRaMDsxCzAJBgNVBAYTAlJP -MREwDwYDVQQKEwhjZXJ0U0lHTjEZMBcGA1UECxMQY2VydFNJR04gUk9PVCBDQTCC -ASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALczuX7IJUqOtdu0KBuqV5Do -0SLTZLrTk+jUrIZhQGpgV2hUhE28alQCBf/fm5oqrl0Hj0rDKH/v+yv6efHHrfAQ -UySQi2bJqIirr1qjAOm+ukbuW3N7LBeCgV5iLKECZbO9xSsAfsT8AzNXDe3i+s5d -RdY4zTW2ssHQnIFKquSyAVwdj1+ZxLGt24gh65AIgoDzMKND5pCCrlUoSe1b16kQ -OA7+j0xbm0bqQfWwCHTD0IgztnzXdN/chNFDDnU5oSVAKOp4yw4sLjmdjItuFhwv -JoIQ4uNllAoEwF73XVv4EOLQunpL+943AAAaWyjj0pxzPjKHmKHJUS/X3qwzs08C -AwEAAaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAcYwHQYDVR0O -BBYEFOCMm9slSbPxfIbWskKHC9BroNnkMA0GCSqGSIb3DQEBBQUAA4IBAQA+0hyJ -LjX8+HXd5n9liPRyTMks1zJO890ZeUe9jjtbkw9QSSQTaxQGcu8J06Gh40CEyecY -MnQ8SG4Pn0vU9x7Tk4ZkVJdjclDVVc/6IJMCopvDI5NOFlV2oHB5bc0hH88vLbwZ -44gx+FkagQnIl6Z0x2DEW8xXjrJ1/RsCCdtZb3KTafcxQdaIOL+Hsr0Wefmq5L6I -Jd1hJyMctTEHBDa0GpC9oHRxUIltvBTjD4au8as+x6AJzKNI0eDbZOeStc+vckNw -i/nDhDwTqn6Sm1dTk/pwwpEOMfmbZ13pljheX7NzTogVZ96edhBiIL5VaZVDADlN -9u6wWk5JRFRYX0KD ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: - 15:c8:bd:65:47:5c:af:b8:97:00:5e:e4:06:d2:bc:9d - Signature Algorithm: sha1WithRSAEncryption - Issuer: C=TW, O=Chunghwa Telecom Co., Ltd., OU=ePKI Root Certification Authority - Validity - Not Before: Dec 20 02:31:27 2004 GMT - Not After : Dec 20 02:31:27 2034 GMT - Subject: C=TW, O=Chunghwa Telecom Co., Ltd., OU=ePKI Root Certification Authority - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (4096 bit) - Modulus: - 00:e1:25:0f:ee:8d:db:88:33:75:67:cd:ad:1f:7d: - 3a:4e:6d:9d:d3:2f:14:f3:63:74:cb:01:21:6a:37: - ea:84:50:07:4b:26:5b:09:43:6c:21:9e:6a:c8:d5: - 03:f5:60:69:8f:cc:f0:22:e4:1f:e7:f7:6a:22:31: - b7:2c:15:f2:e0:fe:00:6a:43:ff:87:65:c6:b5:1a: - c1:a7:4c:6d:22:70:21:8a:31:f2:97:74:89:09:12: - 26:1c:9e:ca:d9:12:a2:95:3c:da:e9:67:bf:08:a0: - 64:e3:d6:42:b7:45:ef:97:f4:f6:f5:d7:b5:4a:15: - 02:58:7d:98:58:4b:60:bc:cd:d7:0d:9a:13:33:53: - d1:61:f9:7a:d5:d7:78:b3:9a:33:f7:00:86:ce:1d: - 4d:94:38:af:a8:ec:78:51:70:8a:5c:10:83:51:21: - f7:11:3d:34:86:5e:e5:48:cd:97:81:82:35:4c:19: - ec:65:f6:6b:c5:05:a1:ee:47:13:d6:b3:21:27:94: - 10:0a:d9:24:3b:ba:be:44:13:46:30:3f:97:3c:d8: - d7:d7:6a:ee:3b:38:e3:2b:d4:97:0e:b9:1b:e7:07: - 49:7f:37:2a:f9:77:78:cf:54:ed:5b:46:9d:a3:80: - 0e:91:43:c1:d6:5b:5f:14:ba:9f:a6:8d:24:47:40: - 59:bf:72:38:b2:36:6c:37:ff:99:d1:5d:0e:59:0a: - ab:69:f7:c0:b2:04:45:7a:54:00:ae:be:53:f6:b5: - e7:e1:f8:3c:a3:31:d2:a9:fe:21:52:64:c5:a6:67: - f0:75:07:06:94:14:81:55:c6:27:e4:01:8f:17:c1: - 6a:71:d7:be:4b:fb:94:58:7d:7e:11:33:b1:42:f7: - 62:6c:18:d6:cf:09:68:3e:7f:6c:f6:1e:8f:62:ad: - a5:63:db:09:a7:1f:22:42:41:1e:6f:99:8a:3e:d7: - f9:3f:40:7a:79:b0:a5:01:92:d2:9d:3d:08:15:a5: - 10:01:2d:b3:32:76:a8:95:0d:b3:7a:9a:fb:07:10: - 78:11:6f:e1:8f:c7:ba:0f:25:1a:74:2a:e5:1c:98: - 41:99:df:21:87:e8:95:06:6a:0a:b3:6a:47:76:65: - f6:3a:cf:8f:62:17:19:7b:0a:28:cd:1a:d2:83:1e: - 21:c7:2c:bf:be:ff:61:68:b7:67:1b:bb:78:4d:8d: - ce:67:e5:e4:c1:8e:b7:23:66:e2:9d:90:75:34:98: - a9:36:2b:8a:9a:94:b9:9d:ec:cc:8a:b1:f8:25:89: - 5c:5a:b6:2f:8c:1f:6d:79:24:a7:52:68:c3:84:35: - e2:66:8d:63:0e:25:4d:d5:19:b2:e6:79:37:a7:22: - 9d:54:31 - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Subject Key Identifier: - 1E:0C:F7:B6:67:F2:E1:92:26:09:45:C0:55:39:2E:77:3F:42:4A:A2 - X509v3 Basic Constraints: - CA:TRUE - setCext-hashedRoot: - 0/0-...0...+......0...g*.....E... -V|.[x....S..... - Signature Algorithm: sha1WithRSAEncryption - 09:b3:83:53:59:01:3e:95:49:b9:f1:81:ba:f9:76:20:23:b5: - 27:60:74:d4:6a:99:34:5e:6c:00:53:d9:9f:f2:a6:b1:24:07: - 44:6a:2a:c6:a5:8e:78:12:e8:47:d9:58:1b:13:2a:5e:79:9b: - 9f:0a:2a:67:a6:25:3f:06:69:56:73:c3:8a:66:48:fb:29:81: - 57:74:06:ca:9c:ea:28:e8:38:67:26:2b:f1:d5:b5:3f:65:93: - f8:36:5d:8e:8d:8d:40:20:87:19:ea:ef:27:c0:3d:b4:39:0f: - 25:7b:68:50:74:55:9c:0c:59:7d:5a:3d:41:94:25:52:08:e0: - 47:2c:15:31:19:d5:bf:07:55:c6:bb:12:b5:97:f4:5f:83:85: - ba:71:c1:d9:6c:81:11:76:0a:0a:b0:bf:82:97:f7:ea:3d:fa: - fa:ec:2d:a9:28:94:3b:56:dd:d2:51:2e:ae:c0:bd:08:15:8c: - 77:52:34:96:d6:9b:ac:d3:1d:8e:61:0f:35:7b:9b:ae:39:69: - 0b:62:60:40:20:36:8f:af:fb:36:ee:2d:08:4a:1d:b8:bf:9b: - 5c:f8:ea:a5:1b:a0:73:a6:d8:f8:6e:e0:33:04:5f:68:aa:27: - 87:ed:d9:c1:90:9c:ed:bd:e3:6a:35:af:63:df:ab:18:d9:ba: - e6:e9:4a:ea:50:8a:0f:61:93:1e:e2:2d:19:e2:30:94:35:92: - 5d:0e:b6:07:af:19:80:8f:47:90:51:4b:2e:4d:dd:85:e2:d2: - 0a:52:0a:17:9a:fc:1a:b0:50:02:e5:01:a3:63:37:21:4c:44: - c4:9b:51:99:11:0e:73:9c:06:8f:54:2e:a7:28:5e:44:39:87: - 56:2d:37:bd:85:44:94:e1:0c:4b:2c:9c:c3:92:85:34:61:cb: - 0f:b8:9b:4a:43:52:fe:34:3a:7d:b8:e9:29:dc:76:a9:c8:30: - f8:14:71:80:c6:1e:36:48:74:22:41:5c:87:82:e8:18:71:8b: - 41:89:44:e7:7e:58:5b:a8:b8:8d:13:e9:a7:6c:c3:47:ed:b3: - 1a:9d:62:ae:8d:82:ea:94:9e:dd:59:10:c3:ad:dd:e2:4d:e3: - 31:d5:c7:ec:e8:f2:b0:fe:92:1e:16:0a:1a:fc:d9:f3:f8:27: - b6:c9:be:1d:b4:6c:64:90:7f:f4:e4:c4:5b:d7:37:ae:42:0e: - dd:a4:1a:6f:7c:88:54:c5:16:6e:e1:7a:68:2e:f8:3a:bf:0d: - a4:3c:89:3b:78:a7:4e:63:83:04:21:08:67:8d:f2:82:49:d0: - 5b:fd:b1:cd:0f:83:84:d4:3e:20:85:f7:4a:3d:2b:9c:fd:2a: - 0a:09:4d:ea:81:f8:11:9c ------BEGIN CERTIFICATE----- -MIIFsDCCA5igAwIBAgIQFci9ZUdcr7iXAF7kBtK8nTANBgkqhkiG9w0BAQUFADBe -MQswCQYDVQQGEwJUVzEjMCEGA1UECgwaQ2h1bmdod2EgVGVsZWNvbSBDby4sIEx0 -ZC4xKjAoBgNVBAsMIWVQS0kgUm9vdCBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTAe -Fw0wNDEyMjAwMjMxMjdaFw0zNDEyMjAwMjMxMjdaMF4xCzAJBgNVBAYTAlRXMSMw -IQYDVQQKDBpDaHVuZ2h3YSBUZWxlY29tIENvLiwgTHRkLjEqMCgGA1UECwwhZVBL -SSBSb290IENlcnRpZmljYXRpb24gQXV0aG9yaXR5MIICIjANBgkqhkiG9w0BAQEF -AAOCAg8AMIICCgKCAgEA4SUP7o3biDN1Z82tH306Tm2d0y8U82N0ywEhajfqhFAH -SyZbCUNsIZ5qyNUD9WBpj8zwIuQf5/dqIjG3LBXy4P4AakP/h2XGtRrBp0xtInAh -ijHyl3SJCRImHJ7K2RKilTza6We/CKBk49ZCt0Xvl/T29de1ShUCWH2YWEtgvM3X -DZoTM1PRYfl61dd4s5oz9wCGzh1NlDivqOx4UXCKXBCDUSH3ET00hl7lSM2XgYI1 -TBnsZfZrxQWh7kcT1rMhJ5QQCtkkO7q+RBNGMD+XPNjX12ruOzjjK9SXDrkb5wdJ -fzcq+Xd4z1TtW0ado4AOkUPB1ltfFLqfpo0kR0BZv3I4sjZsN/+Z0V0OWQqraffA -sgRFelQArr5T9rXn4fg8ozHSqf4hUmTFpmfwdQcGlBSBVcYn5AGPF8Fqcde+S/uU -WH1+ETOxQvdibBjWzwloPn9s9h6PYq2lY9sJpx8iQkEeb5mKPtf5P0B6ebClAZLS -nT0IFaUQAS2zMnaolQ2zepr7BxB4EW/hj8e6DyUadCrlHJhBmd8hh+iVBmoKs2pH -dmX2Os+PYhcZewoozRrSgx4hxyy/vv9haLdnG7t4TY3OZ+XkwY63I2binZB1NJip -NiuKmpS5nezMirH4JYlcWrYvjB9teSSnUmjDhDXiZo1jDiVN1Rmy5nk3pyKdVDEC -AwEAAaNqMGgwHQYDVR0OBBYEFB4M97Zn8uGSJglFwFU5Lnc/QkqiMAwGA1UdEwQF -MAMBAf8wOQYEZyoHAAQxMC8wLQIBADAJBgUrDgMCGgUAMAcGBWcqAwAABBRFsMLH -ClZ87lt4DJX5GFPBphzYEDANBgkqhkiG9w0BAQUFAAOCAgEACbODU1kBPpVJufGB -uvl2ICO1J2B01GqZNF5sAFPZn/KmsSQHRGoqxqWOeBLoR9lYGxMqXnmbnwoqZ6Yl -PwZpVnPDimZI+ymBV3QGypzqKOg4ZyYr8dW1P2WT+DZdjo2NQCCHGervJ8A9tDkP -JXtoUHRVnAxZfVo9QZQlUgjgRywVMRnVvwdVxrsStZf0X4OFunHB2WyBEXYKCrC/ -gpf36j36+uwtqSiUO1bd0lEursC9CBWMd1I0ltabrNMdjmEPNXubrjlpC2JgQCA2 -j6/7Nu4tCEoduL+bXPjqpRugc6bY+G7gMwRfaKonh+3ZwZCc7b3jajWvY9+rGNm6 -5ulK6lCKD2GTHuItGeIwlDWSXQ62B68ZgI9HkFFLLk3dheLSClIKF5r8GrBQAuUB -o2M3IUxExJtRmREOc5wGj1QupyheRDmHVi03vYVElOEMSyycw5KFNGHLD7ibSkNS -/jQ6fbjpKdx2qcgw+BRxgMYeNkh0IkFch4LoGHGLQYlE535YW6i4jRPpp2zDR+2z -Gp1iro2C6pSe3VkQw63d4k3jMdXH7OjysP6SHhYKGvzZ8/gntsm+HbRsZJB/9OTE -W9c3rkIO3aQab3yIVMUWbuF6aC74Or8NpDyJO3inTmODBCEIZ43ygknQW/2xzQ+D -hNQ+IIX3Sj0rnP0qCglN6oH4EZw= ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: - 34:4e:d5:57:20:d5:ed:ec:49:f4:2f:ce:37:db:2b:6d - Signature Algorithm: sha1WithRSAEncryption - Issuer: C=US, O=thawte, Inc., OU=Certification Services Division, OU=(c) 2006 thawte, Inc. - For authorized use only, CN=thawte Primary Root CA - Validity - Not Before: Nov 17 00:00:00 2006 GMT - Not After : Jul 16 23:59:59 2036 GMT - Subject: C=US, O=thawte, Inc., OU=Certification Services Division, OU=(c) 2006 thawte, Inc. - For authorized use only, CN=thawte Primary Root CA - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (2048 bit) - Modulus: - 00:ac:a0:f0:fb:80:59:d4:9c:c7:a4:cf:9d:a1:59: - 73:09:10:45:0c:0d:2c:6e:68:f1:6c:5b:48:68:49: - 59:37:fc:0b:33:19:c2:77:7f:cc:10:2d:95:34:1c: - e6:eb:4d:09:a7:1c:d2:b8:c9:97:36:02:b7:89:d4: - 24:5f:06:c0:cc:44:94:94:8d:02:62:6f:eb:5a:dd: - 11:8d:28:9a:5c:84:90:10:7a:0d:bd:74:66:2f:6a: - 38:a0:e2:d5:54:44:eb:1d:07:9f:07:ba:6f:ee:e9: - fd:4e:0b:29:f5:3e:84:a0:01:f1:9c:ab:f8:1c:7e: - 89:a4:e8:a1:d8:71:65:0d:a3:51:7b:ee:bc:d2:22: - 60:0d:b9:5b:9d:df:ba:fc:51:5b:0b:af:98:b2:e9: - 2e:e9:04:e8:62:87:de:2b:c8:d7:4e:c1:4c:64:1e: - dd:cf:87:58:ba:4a:4f:ca:68:07:1d:1c:9d:4a:c6: - d5:2f:91:cc:7c:71:72:1c:c5:c0:67:eb:32:fd:c9: - 92:5c:94:da:85:c0:9b:bf:53:7d:2b:09:f4:8c:9d: - 91:1f:97:6a:52:cb:de:09:36:a4:77:d8:7b:87:50: - 44:d5:3e:6e:29:69:fb:39:49:26:1e:09:a5:80:7b: - 40:2d:eb:e8:27:85:c9:fe:61:fd:7e:e6:7c:97:1d: - d5:9d - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Basic Constraints: critical - CA:TRUE - X509v3 Key Usage: critical - Certificate Sign, CRL Sign - X509v3 Subject Key Identifier: - 7B:5B:45:CF:AF:CE:CB:7A:FD:31:92:1A:6A:B6:F3:46:EB:57:48:50 - Signature Algorithm: sha1WithRSAEncryption - 79:11:c0:4b:b3:91:b6:fc:f0:e9:67:d4:0d:6e:45:be:55:e8: - 93:d2:ce:03:3f:ed:da:25:b0:1d:57:cb:1e:3a:76:a0:4c:ec: - 50:76:e8:64:72:0c:a4:a9:f1:b8:8b:d6:d6:87:84:bb:32:e5: - 41:11:c0:77:d9:b3:60:9d:eb:1b:d5:d1:6e:44:44:a9:a6:01: - ec:55:62:1d:77:b8:5c:8e:48:49:7c:9c:3b:57:11:ac:ad:73: - 37:8e:2f:78:5c:90:68:47:d9:60:60:e6:fc:07:3d:22:20:17: - c4:f7:16:e9:c4:d8:72:f9:c8:73:7c:df:16:2f:15:a9:3e:fd: - 6a:27:b6:a1:eb:5a:ba:98:1f:d5:e3:4d:64:0a:9d:13:c8:61: - ba:f5:39:1c:87:ba:b8:bd:7b:22:7f:f6:fe:ac:40:79:e5:ac: - 10:6f:3d:8f:1b:79:76:8b:c4:37:b3:21:18:84:e5:36:00:eb: - 63:20:99:b9:e9:fe:33:04:bb:41:c8:c1:02:f9:44:63:20:9e: - 81:ce:42:d3:d6:3f:2c:76:d3:63:9c:59:dd:8f:a6:e1:0e:a0: - 2e:41:f7:2e:95:47:cf:bc:fd:33:f3:f6:0b:61:7e:7e:91:2b: - 81:47:c2:27:30:ee:a7:10:5d:37:8f:5c:39:2b:e4:04:f0:7b: - 8d:56:8c:68 ------BEGIN CERTIFICATE----- -MIIEIDCCAwigAwIBAgIQNE7VVyDV7exJ9C/ON9srbTANBgkqhkiG9w0BAQUFADCB -qTELMAkGA1UEBhMCVVMxFTATBgNVBAoTDHRoYXd0ZSwgSW5jLjEoMCYGA1UECxMf -Q2VydGlmaWNhdGlvbiBTZXJ2aWNlcyBEaXZpc2lvbjE4MDYGA1UECxMvKGMpIDIw -MDYgdGhhd3RlLCBJbmMuIC0gRm9yIGF1dGhvcml6ZWQgdXNlIG9ubHkxHzAdBgNV -BAMTFnRoYXd0ZSBQcmltYXJ5IFJvb3QgQ0EwHhcNMDYxMTE3MDAwMDAwWhcNMzYw -NzE2MjM1OTU5WjCBqTELMAkGA1UEBhMCVVMxFTATBgNVBAoTDHRoYXd0ZSwgSW5j -LjEoMCYGA1UECxMfQ2VydGlmaWNhdGlvbiBTZXJ2aWNlcyBEaXZpc2lvbjE4MDYG -A1UECxMvKGMpIDIwMDYgdGhhd3RlLCBJbmMuIC0gRm9yIGF1dGhvcml6ZWQgdXNl -IG9ubHkxHzAdBgNVBAMTFnRoYXd0ZSBQcmltYXJ5IFJvb3QgQ0EwggEiMA0GCSqG -SIb3DQEBAQUAA4IBDwAwggEKAoIBAQCsoPD7gFnUnMekz52hWXMJEEUMDSxuaPFs -W0hoSVk3/AszGcJ3f8wQLZU0HObrTQmnHNK4yZc2AreJ1CRfBsDMRJSUjQJib+ta -3RGNKJpchJAQeg29dGYvajig4tVUROsdB58Hum/u6f1OCyn1PoSgAfGcq/gcfomk -6KHYcWUNo1F77rzSImANuVud37r8UVsLr5iy6S7pBOhih94ryNdOwUxkHt3Ph1i6 -Sk/KaAcdHJ1KxtUvkcx8cXIcxcBn6zL9yZJclNqFwJu/U30rCfSMnZEfl2pSy94J -NqR32HuHUETVPm4pafs5SSYeCaWAe0At6+gnhcn+Yf1+5nyXHdWdAgMBAAGjQjBA -MA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgEGMB0GA1UdDgQWBBR7W0XP -r87Lev0xkhpqtvNG61dIUDANBgkqhkiG9w0BAQUFAAOCAQEAeRHAS7ORtvzw6WfU -DW5FvlXok9LOAz/t2iWwHVfLHjp2oEzsUHboZHIMpKnxuIvW1oeEuzLlQRHAd9mz -YJ3rG9XRbkREqaYB7FViHXe4XI5ISXycO1cRrK1zN44veFyQaEfZYGDm/Ac9IiAX -xPcW6cTYcvnIc3zfFi8VqT79aie2oetaupgf1eNNZAqdE8hhuvU5HIe6uL17In/2 -/qxAeeWsEG89jxt5dovEN7MhGITlNgDrYyCZuen+MwS7QcjBAvlEYyCegc5C09Y/ -LHbTY5xZ3Y+m4Q6gLkH3LpVHz7z9M/P2C2F+fpErgUfCJzDupxBdN49cOSvkBPB7 -jVaMaA== ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: - 35:fc:26:5c:d9:84:4f:c9:3d:26:3d:57:9b:ae:d7:56 - Signature Algorithm: ecdsa-with-SHA384 - Issuer: C=US, O=thawte, Inc., OU=(c) 2007 thawte, Inc. - For authorized use only, CN=thawte Primary Root CA - G2 - Validity - Not Before: Nov 5 00:00:00 2007 GMT - Not After : Jan 18 23:59:59 2038 GMT - Subject: C=US, O=thawte, Inc., OU=(c) 2007 thawte, Inc. - For authorized use only, CN=thawte Primary Root CA - G2 - Subject Public Key Info: - Public Key Algorithm: id-ecPublicKey - Public-Key: (384 bit) - pub: - 04:a2:d5:9c:82:7b:95:9d:f1:52:78:87:fe:8a:16: - bf:05:e6:df:a3:02:4f:0d:07:c6:00:51:ba:0c:02: - 52:2d:22:a4:42:39:c4:fe:8f:ea:c9:c1:be:d4:4d: - ff:9f:7a:9e:e2:b1:7c:9a:ad:a7:86:09:73:87:d1: - e7:9a:e3:7a:a5:aa:6e:fb:ba:b3:70:c0:67:88:a2: - 35:d4:a3:9a:b1:fd:ad:c2:ef:31:fa:a8:b9:f3:fb: - 08:c6:91:d1:fb:29:95 - ASN1 OID: secp384r1 - X509v3 extensions: - X509v3 Basic Constraints: critical - CA:TRUE - X509v3 Key Usage: critical - Certificate Sign, CRL Sign - X509v3 Subject Key Identifier: - 9A:D8:00:30:00:E7:6B:7F:85:18:EE:8B:B6:CE:8A:0C:F8:11:E1:BB - Signature Algorithm: ecdsa-with-SHA384 - 30:66:02:31:00:dd:f8:e0:57:47:5b:a7:e6:0a:c3:bd:f5:80: - 8a:97:35:0d:1b:89:3c:54:86:77:28:ca:a1:f4:79:de:b5:e6: - 38:b0:f0:65:70:8c:7f:02:54:c2:bf:ff:d8:a1:3e:d9:cf:02: - 31:00:c4:8d:94:fc:dc:53:d2:dc:9d:78:16:1f:15:33:23:53: - 52:e3:5a:31:5d:9d:ca:ae:bd:13:29:44:0d:27:5b:a8:e7:68: - 9c:12:f7:58:3f:2e:72:02:57:a3:8f:a1:14:2e ------BEGIN CERTIFICATE----- -MIICiDCCAg2gAwIBAgIQNfwmXNmET8k9Jj1Xm67XVjAKBggqhkjOPQQDAzCBhDEL -MAkGA1UEBhMCVVMxFTATBgNVBAoTDHRoYXd0ZSwgSW5jLjE4MDYGA1UECxMvKGMp -IDIwMDcgdGhhd3RlLCBJbmMuIC0gRm9yIGF1dGhvcml6ZWQgdXNlIG9ubHkxJDAi -BgNVBAMTG3RoYXd0ZSBQcmltYXJ5IFJvb3QgQ0EgLSBHMjAeFw0wNzExMDUwMDAw -MDBaFw0zODAxMTgyMzU5NTlaMIGEMQswCQYDVQQGEwJVUzEVMBMGA1UEChMMdGhh -d3RlLCBJbmMuMTgwNgYDVQQLEy8oYykgMjAwNyB0aGF3dGUsIEluYy4gLSBGb3Ig -YXV0aG9yaXplZCB1c2Ugb25seTEkMCIGA1UEAxMbdGhhd3RlIFByaW1hcnkgUm9v -dCBDQSAtIEcyMHYwEAYHKoZIzj0CAQYFK4EEACIDYgAEotWcgnuVnfFSeIf+iha/ -BebfowJPDQfGAFG6DAJSLSKkQjnE/o/qycG+1E3/n3qe4rF8mq2nhglzh9HnmuN6 -papu+7qzcMBniKI11KOasf2twu8x+qi58/sIxpHR+ymVo0IwQDAPBgNVHRMBAf8E -BTADAQH/MA4GA1UdDwEB/wQEAwIBBjAdBgNVHQ4EFgQUmtgAMADna3+FGO6Lts6K -DPgR4bswCgYIKoZIzj0EAwMDaQAwZgIxAN344FdHW6fmCsO99YCKlzUNG4k8VIZ3 -KMqh9HneteY4sPBlcIx/AlTCv//YoT7ZzwIxAMSNlPzcU9LcnXgWHxUzI1NS41ox -XZ3Krr0TKUQNJ1uo52icEvdYPy5yAlejj6EULg== ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: - 60:01:97:b7:46:a7:ea:b4:b4:9a:d6:4b:2f:f7:90:fb - Signature Algorithm: sha256WithRSAEncryption - Issuer: C=US, O=thawte, Inc., OU=Certification Services Division, OU=(c) 2008 thawte, Inc. - For authorized use only, CN=thawte Primary Root CA - G3 - Validity - Not Before: Apr 2 00:00:00 2008 GMT - Not After : Dec 1 23:59:59 2037 GMT - Subject: C=US, O=thawte, Inc., OU=Certification Services Division, OU=(c) 2008 thawte, Inc. - For authorized use only, CN=thawte Primary Root CA - G3 - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (2048 bit) - Modulus: - 00:b2:bf:27:2c:fb:db:d8:5b:dd:78:7b:1b:9e:77: - 66:81:cb:3e:bc:7c:ae:f3:a6:27:9a:34:a3:68:31: - 71:38:33:62:e4:f3:71:66:79:b1:a9:65:a3:a5:8b: - d5:8f:60:2d:3f:42:cc:aa:6b:32:c0:23:cb:2c:41: - dd:e4:df:fc:61:9c:e2:73:b2:22:95:11:43:18:5f: - c4:b6:1f:57:6c:0a:05:58:22:c8:36:4c:3a:7c:a5: - d1:cf:86:af:88:a7:44:02:13:74:71:73:0a:42:59: - 02:f8:1b:14:6b:42:df:6f:5f:ba:6b:82:a2:9d:5b: - e7:4a:bd:1e:01:72:db:4b:74:e8:3b:7f:7f:7d:1f: - 04:b4:26:9b:e0:b4:5a:ac:47:3d:55:b8:d7:b0:26: - 52:28:01:31:40:66:d8:d9:24:bd:f6:2a:d8:ec:21: - 49:5c:9b:f6:7a:e9:7f:55:35:7e:96:6b:8d:93:93: - 27:cb:92:bb:ea:ac:40:c0:9f:c2:f8:80:cf:5d:f4: - 5a:dc:ce:74:86:a6:3e:6c:0b:53:ca:bd:92:ce:19: - 06:72:e6:0c:5c:38:69:c7:04:d6:bc:6c:ce:5b:f6: - f7:68:9c:dc:25:15:48:88:a1:e9:a9:f8:98:9c:e0: - f3:d5:31:28:61:11:6c:67:96:8d:39:99:cb:c2:45: - 24:39 - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Basic Constraints: critical - CA:TRUE - X509v3 Key Usage: critical - Certificate Sign, CRL Sign - X509v3 Subject Key Identifier: - AD:6C:AA:94:60:9C:ED:E4:FF:FA:3E:0A:74:2B:63:03:F7:B6:59:BF - Signature Algorithm: sha256WithRSAEncryption - 1a:40:d8:95:65:ac:09:92:89:c6:39:f4:10:e5:a9:0e:66:53: - 5d:78:de:fa:24:91:bb:e7:44:51:df:c6:16:34:0a:ef:6a:44: - 51:ea:2b:07:8a:03:7a:c3:eb:3f:0a:2c:52:16:a0:2b:43:b9: - 25:90:3f:70:a9:33:25:6d:45:1a:28:3b:27:cf:aa:c3:29:42: - 1b:df:3b:4c:c0:33:34:5b:41:88:bf:6b:2b:65:af:28:ef:b2: - f5:c3:aa:66:ce:7b:56:ee:b7:c8:cb:67:c1:c9:9c:1a:18:b8: - c4:c3:49:03:f1:60:0e:50:cd:46:c5:f3:77:79:f7:b6:15:e0: - 38:db:c7:2f:28:a0:0c:3f:77:26:74:d9:25:12:da:31:da:1a: - 1e:dc:29:41:91:22:3c:69:a7:bb:02:f2:b6:5c:27:03:89:f4: - 06:ea:9b:e4:72:82:e3:a1:09:c1:e9:00:19:d3:3e:d4:70:6b: - ba:71:a6:aa:58:ae:f4:bb:e9:6c:b6:ef:87:cc:9b:bb:ff:39: - e6:56:61:d3:0a:a7:c4:5c:4c:60:7b:05:77:26:7a:bf:d8:07: - 52:2c:62:f7:70:63:d9:39:bc:6f:1c:c2:79:dc:76:29:af:ce: - c5:2c:64:04:5e:88:36:6e:31:d4:40:1a:62:34:36:3f:35:01: - ae:ac:63:a0 ------BEGIN CERTIFICATE----- -MIIEKjCCAxKgAwIBAgIQYAGXt0an6rS0mtZLL/eQ+zANBgkqhkiG9w0BAQsFADCB -rjELMAkGA1UEBhMCVVMxFTATBgNVBAoTDHRoYXd0ZSwgSW5jLjEoMCYGA1UECxMf -Q2VydGlmaWNhdGlvbiBTZXJ2aWNlcyBEaXZpc2lvbjE4MDYGA1UECxMvKGMpIDIw -MDggdGhhd3RlLCBJbmMuIC0gRm9yIGF1dGhvcml6ZWQgdXNlIG9ubHkxJDAiBgNV -BAMTG3RoYXd0ZSBQcmltYXJ5IFJvb3QgQ0EgLSBHMzAeFw0wODA0MDIwMDAwMDBa -Fw0zNzEyMDEyMzU5NTlaMIGuMQswCQYDVQQGEwJVUzEVMBMGA1UEChMMdGhhd3Rl -LCBJbmMuMSgwJgYDVQQLEx9DZXJ0aWZpY2F0aW9uIFNlcnZpY2VzIERpdmlzaW9u -MTgwNgYDVQQLEy8oYykgMjAwOCB0aGF3dGUsIEluYy4gLSBGb3IgYXV0aG9yaXpl -ZCB1c2Ugb25seTEkMCIGA1UEAxMbdGhhd3RlIFByaW1hcnkgUm9vdCBDQSAtIEcz -MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAsr8nLPvb2FvdeHsbnndm -gcs+vHyu86YnmjSjaDFxODNi5PNxZnmxqWWjpYvVj2AtP0LMqmsywCPLLEHd5N/8 -YZzic7IilRFDGF/Eth9XbAoFWCLINkw6fKXRz4aviKdEAhN0cXMKQlkC+BsUa0Lf -b1+6a4KinVvnSr0eAXLbS3ToO39/fR8EtCab4LRarEc9VbjXsCZSKAExQGbY2SS9 -9irY7CFJXJv2eul/VTV+lmuNk5Mny5K76qxAwJ/C+IDPXfRa3M50hqY+bAtTyr2S -zhkGcuYMXDhpxwTWvGzOW/b3aJzcJRVIiKHpqfiYnODz1TEoYRFsZ5aNOZnLwkUk -OQIDAQABo0IwQDAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIBBjAdBgNV -HQ4EFgQUrWyqlGCc7eT/+j4KdCtjA/e2Wb8wDQYJKoZIhvcNAQELBQADggEBABpA -2JVlrAmSicY59BDlqQ5mU1143vokkbvnRFHfxhY0Cu9qRFHqKweKA3rD6z8KLFIW -oCtDuSWQP3CpMyVtRRooOyfPqsMpQhvfO0zAMzRbQYi/aytlryjvsvXDqmbOe1bu -t8jLZ8HJnBoYuMTDSQPxYA5QzUbF83d597YV4Djbxy8ooAw/dyZ02SUS2jHaGh7c -KUGRIjxpp7sC8rZcJwOJ9Abqm+RyguOhCcHpABnTPtRwa7pxpqpYrvS76Wy274fM -m7v/OeZWYdMKp8RcTGB7BXcmer/YB1IsYvdwY9k5vG8cwnncdimvzsUsZAReiDZu -MdRAGmI0Nj81Aa6sY6A= ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: 927650371 (0x374ad243) - Signature Algorithm: sha1WithRSAEncryption - Issuer: C=US, O=Entrust.net, OU=www.entrust.net/CPS incorp. by ref. (limits liab.), OU=(c) 1999 Entrust.net Limited, CN=Entrust.net Secure Server Certification Authority - Validity - Not Before: May 25 16:09:40 1999 GMT - Not After : May 25 16:39:40 2019 GMT - Subject: C=US, O=Entrust.net, OU=www.entrust.net/CPS incorp. by ref. (limits liab.), OU=(c) 1999 Entrust.net Limited, CN=Entrust.net Secure Server Certification Authority - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (1024 bit) - Modulus: - 00:cd:28:83:34:54:1b:89:f3:0f:af:37:91:31:ff: - af:31:60:c9:a8:e8:b2:10:68:ed:9f:e7:93:36:f1: - 0a:64:bb:47:f5:04:17:3f:23:47:4d:c5:27:19:81: - 26:0c:54:72:0d:88:2d:d9:1f:9a:12:9f:bc:b3:71: - d3:80:19:3f:47:66:7b:8c:35:28:d2:b9:0a:df:24: - da:9c:d6:50:79:81:7a:5a:d3:37:f7:c2:4a:d8:29: - 92:26:64:d1:e4:98:6c:3a:00:8a:f5:34:9b:65:f8: - ed:e3:10:ff:fd:b8:49:58:dc:a0:de:82:39:6b:81: - b1:16:19:61:b9:54:b6:e6:43 - Exponent: 3 (0x3) - X509v3 extensions: - Netscape Cert Type: - SSL CA, S/MIME CA, Object Signing CA - X509v3 CRL Distribution Points: - - Full Name: - DirName: C = US, O = Entrust.net, OU = www.entrust.net/CPS incorp. by ref. (limits liab.), OU = (c) 1999 Entrust.net Limited, CN = Entrust.net Secure Server Certification Authority, CN = CRL1 - - Full Name: - URI:http://www.entrust.net/CRL/net1.crl - - X509v3 Private Key Usage Period: - Not Before: May 25 16:09:40 1999 GMT, Not After: May 25 16:09:40 2019 GMT - X509v3 Key Usage: - Certificate Sign, CRL Sign - X509v3 Authority Key Identifier: - keyid:F0:17:62:13:55:3D:B3:FF:0A:00:6B:FB:50:84:97:F3:ED:62:D0:1A - - X509v3 Subject Key Identifier: - F0:17:62:13:55:3D:B3:FF:0A:00:6B:FB:50:84:97:F3:ED:62:D0:1A - X509v3 Basic Constraints: - CA:TRUE - 1.2.840.113533.7.65.0: - 0 -..V4.0.... - Signature Algorithm: sha1WithRSAEncryption - 90:dc:30:02:fa:64:74:c2:a7:0a:a5:7c:21:8d:34:17:a8:fb: - 47:0e:ff:25:7c:8d:13:0a:fb:e4:98:b5:ef:8c:f8:c5:10:0d: - f7:92:be:f1:c3:d5:d5:95:6a:04:bb:2c:ce:26:36:65:c8:31: - c6:e7:ee:3f:e3:57:75:84:7a:11:ef:46:4f:18:f4:d3:98:bb: - a8:87:32:ba:72:f6:3c:e2:3d:9f:d7:1d:d9:c3:60:43:8c:58: - 0e:22:96:2f:62:a3:2c:1f:ba:ad:05:ef:ab:32:78:87:a0:54: - 73:19:b5:5c:05:f9:52:3e:6d:2d:45:0b:f7:0a:93:ea:ed:06: - f9:b2 ------BEGIN CERTIFICATE----- -MIIE2DCCBEGgAwIBAgIEN0rSQzANBgkqhkiG9w0BAQUFADCBwzELMAkGA1UEBhMC -VVMxFDASBgNVBAoTC0VudHJ1c3QubmV0MTswOQYDVQQLEzJ3d3cuZW50cnVzdC5u -ZXQvQ1BTIGluY29ycC4gYnkgcmVmLiAobGltaXRzIGxpYWIuKTElMCMGA1UECxMc -KGMpIDE5OTkgRW50cnVzdC5uZXQgTGltaXRlZDE6MDgGA1UEAxMxRW50cnVzdC5u -ZXQgU2VjdXJlIFNlcnZlciBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTAeFw05OTA1 -MjUxNjA5NDBaFw0xOTA1MjUxNjM5NDBaMIHDMQswCQYDVQQGEwJVUzEUMBIGA1UE -ChMLRW50cnVzdC5uZXQxOzA5BgNVBAsTMnd3dy5lbnRydXN0Lm5ldC9DUFMgaW5j -b3JwLiBieSByZWYuIChsaW1pdHMgbGlhYi4pMSUwIwYDVQQLExwoYykgMTk5OSBF -bnRydXN0Lm5ldCBMaW1pdGVkMTowOAYDVQQDEzFFbnRydXN0Lm5ldCBTZWN1cmUg -U2VydmVyIENlcnRpZmljYXRpb24gQXV0aG9yaXR5MIGdMA0GCSqGSIb3DQEBAQUA -A4GLADCBhwKBgQDNKIM0VBuJ8w+vN5Ex/68xYMmo6LIQaO2f55M28Qpku0f1BBc/ -I0dNxScZgSYMVHINiC3ZH5oSn7yzcdOAGT9HZnuMNSjSuQrfJNqc1lB5gXpa0zf3 -wkrYKZImZNHkmGw6AIr1NJtl+O3jEP/9uElY3KDegjlrgbEWGWG5VLbmQwIBA6OC -AdcwggHTMBEGCWCGSAGG+EIBAQQEAwIABzCCARkGA1UdHwSCARAwggEMMIHeoIHb -oIHYpIHVMIHSMQswCQYDVQQGEwJVUzEUMBIGA1UEChMLRW50cnVzdC5uZXQxOzA5 -BgNVBAsTMnd3dy5lbnRydXN0Lm5ldC9DUFMgaW5jb3JwLiBieSByZWYuIChsaW1p -dHMgbGlhYi4pMSUwIwYDVQQLExwoYykgMTk5OSBFbnRydXN0Lm5ldCBMaW1pdGVk -MTowOAYDVQQDEzFFbnRydXN0Lm5ldCBTZWN1cmUgU2VydmVyIENlcnRpZmljYXRp -b24gQXV0aG9yaXR5MQ0wCwYDVQQDEwRDUkwxMCmgJ6AlhiNodHRwOi8vd3d3LmVu -dHJ1c3QubmV0L0NSTC9uZXQxLmNybDArBgNVHRAEJDAigA8xOTk5MDUyNTE2MDk0 -MFqBDzIwMTkwNTI1MTYwOTQwWjALBgNVHQ8EBAMCAQYwHwYDVR0jBBgwFoAU8Bdi -E1U9s/8KAGv7UISX8+1i0BowHQYDVR0OBBYEFPAXYhNVPbP/CgBr+1CEl/PtYtAa -MAwGA1UdEwQFMAMBAf8wGQYJKoZIhvZ9B0EABAwwChsEVjQuMAMCBJAwDQYJKoZI -hvcNAQEFBQADgYEAkNwwAvpkdMKnCqV8IY00F6j7Rw7/JXyNEwr75Ji174z4xRAN -95K+8cPV1ZVqBLssziY2ZcgxxufuP+NXdYR6Ee9GTxj005i7qIcyunL2POI9n9cd -2cNgQ4xYDiKWL2KjLB+6rQXvqzJ4h6BUcxm1XAX5Uj5tLUUL9wqT6u0G+bI= ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: 903804111 (0x35def4cf) - Signature Algorithm: sha1WithRSAEncryption - Issuer: C=US, O=Equifax, OU=Equifax Secure Certificate Authority - Validity - Not Before: Aug 22 16:41:51 1998 GMT - Not After : Aug 22 16:41:51 2018 GMT - Subject: C=US, O=Equifax, OU=Equifax Secure Certificate Authority - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (1024 bit) - Modulus: - 00:c1:5d:b1:58:67:08:62:ee:a0:9a:2d:1f:08:6d: - 91:14:68:98:0a:1e:fe:da:04:6f:13:84:62:21:c3: - d1:7c:ce:9f:05:e0:b8:01:f0:4e:34:ec:e2:8a:95: - 04:64:ac:f1:6b:53:5f:05:b3:cb:67:80:bf:42:02: - 8e:fe:dd:01:09:ec:e1:00:14:4f:fc:fb:f0:0c:dd: - 43:ba:5b:2b:e1:1f:80:70:99:15:57:93:16:f1:0f: - 97:6a:b7:c2:68:23:1c:cc:4d:59:30:ac:51:1e:3b: - af:2b:d6:ee:63:45:7b:c5:d9:5f:50:d2:e3:50:0f: - 3a:88:e7:bf:14:fd:e0:c7:b9 - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 CRL Distribution Points: - - Full Name: - DirName: C = US, O = Equifax, OU = Equifax Secure Certificate Authority, CN = CRL1 - - X509v3 Private Key Usage Period: - Not After: Aug 22 16:41:51 2018 GMT - X509v3 Key Usage: - Certificate Sign, CRL Sign - X509v3 Authority Key Identifier: - keyid:48:E6:68:F9:2B:D2:B2:95:D7:47:D8:23:20:10:4F:33:98:90:9F:D4 - - X509v3 Subject Key Identifier: - 48:E6:68:F9:2B:D2:B2:95:D7:47:D8:23:20:10:4F:33:98:90:9F:D4 - X509v3 Basic Constraints: - CA:TRUE - 1.2.840.113533.7.65.0: - 0...V3.0c.... - Signature Algorithm: sha1WithRSAEncryption - 58:ce:29:ea:fc:f7:de:b5:ce:02:b9:17:b5:85:d1:b9:e3:e0: - 95:cc:25:31:0d:00:a6:92:6e:7f:b6:92:63:9e:50:95:d1:9a: - 6f:e4:11:de:63:85:6e:98:ee:a8:ff:5a:c8:d3:55:b2:66:71: - 57:de:c0:21:eb:3d:2a:a7:23:49:01:04:86:42:7b:fc:ee:7f: - a2:16:52:b5:67:67:d3:40:db:3b:26:58:b2:28:77:3d:ae:14: - 77:61:d6:fa:2a:66:27:a0:0d:fa:a7:73:5c:ea:70:f1:94:21: - 65:44:5f:fa:fc:ef:29:68:a9:a2:87:79:ef:79:ef:4f:ac:07: - 77:38 ------BEGIN CERTIFICATE----- -MIIDIDCCAomgAwIBAgIENd70zzANBgkqhkiG9w0BAQUFADBOMQswCQYDVQQGEwJV -UzEQMA4GA1UEChMHRXF1aWZheDEtMCsGA1UECxMkRXF1aWZheCBTZWN1cmUgQ2Vy -dGlmaWNhdGUgQXV0aG9yaXR5MB4XDTk4MDgyMjE2NDE1MVoXDTE4MDgyMjE2NDE1 -MVowTjELMAkGA1UEBhMCVVMxEDAOBgNVBAoTB0VxdWlmYXgxLTArBgNVBAsTJEVx -dWlmYXggU2VjdXJlIENlcnRpZmljYXRlIEF1dGhvcml0eTCBnzANBgkqhkiG9w0B -AQEFAAOBjQAwgYkCgYEAwV2xWGcIYu6gmi0fCG2RFGiYCh7+2gRvE4RiIcPRfM6f -BeC4AfBONOziipUEZKzxa1NfBbPLZ4C/QgKO/t0BCezhABRP/PvwDN1Dulsr4R+A -cJkVV5MW8Q+XarfCaCMczE1ZMKxRHjuvK9buY0V7xdlfUNLjUA86iOe/FP3gx7kC -AwEAAaOCAQkwggEFMHAGA1UdHwRpMGcwZaBjoGGkXzBdMQswCQYDVQQGEwJVUzEQ -MA4GA1UEChMHRXF1aWZheDEtMCsGA1UECxMkRXF1aWZheCBTZWN1cmUgQ2VydGlm -aWNhdGUgQXV0aG9yaXR5MQ0wCwYDVQQDEwRDUkwxMBoGA1UdEAQTMBGBDzIwMTgw -ODIyMTY0MTUxWjALBgNVHQ8EBAMCAQYwHwYDVR0jBBgwFoAUSOZo+SvSspXXR9gj -IBBPM5iQn9QwHQYDVR0OBBYEFEjmaPkr0rKV10fYIyAQTzOYkJ/UMAwGA1UdEwQF -MAMBAf8wGgYJKoZIhvZ9B0EABA0wCxsFVjMuMGMDAgbAMA0GCSqGSIb3DQEBBQUA -A4GBAFjOKer89961zgK5F7WF0bnj4JXMJTENAKaSbn+2kmOeUJXRmm/kEd5jhW6Y -7qj/WsjTVbJmcVfewCHrPSqnI0kBBIZCe/zuf6IWUrVnZ9NA2zsmWLIodz2uFHdh -1voqZiegDfqnc1zqcPGUIWVEX/r87yloqaKHee9570+sB3c4 ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: 1 (0x1) - Signature Algorithm: md5WithRSAEncryption - Issuer: C=US, O=Equifax Secure Inc., CN=Equifax Secure Global eBusiness CA-1 - Validity - Not Before: Jun 21 04:00:00 1999 GMT - Not After : Jun 21 04:00:00 2020 GMT - Subject: C=US, O=Equifax Secure Inc., CN=Equifax Secure Global eBusiness CA-1 - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (1024 bit) - Modulus: - 00:ba:e7:17:90:02:65:b1:34:55:3c:49:c2:51:d5: - df:a7:d1:37:8f:d1:e7:81:73:41:52:60:9b:9d:a1: - 17:26:78:ad:c7:b1:e8:26:94:32:b5:de:33:8d:3a: - 2f:db:f2:9a:7a:5a:73:98:a3:5c:e9:fb:8a:73:1b: - 5c:e7:c3:bf:80:6c:cd:a9:f4:d6:2b:c0:f7:f9:99: - aa:63:a2:b1:47:02:0f:d4:e4:51:3a:12:3c:6c:8a: - 5a:54:84:70:db:c1:c5:90:cf:72:45:cb:a8:59:c0: - cd:33:9d:3f:a3:96:eb:85:33:21:1c:3e:1e:3e:60: - 6e:76:9c:67:85:c5:c8:c3:61 - Exponent: 65537 (0x10001) - X509v3 extensions: - Netscape Cert Type: - SSL CA, S/MIME CA, Object Signing CA - X509v3 Basic Constraints: critical - CA:TRUE - X509v3 Authority Key Identifier: - keyid:BE:A8:A0:74:72:50:6B:44:B7:C9:23:D8:FB:A8:FF:B3:57:6B:68:6C - - X509v3 Subject Key Identifier: - BE:A8:A0:74:72:50:6B:44:B7:C9:23:D8:FB:A8:FF:B3:57:6B:68:6C - Signature Algorithm: md5WithRSAEncryption - 30:e2:01:51:aa:c7:ea:5f:da:b9:d0:65:0f:30:d6:3e:da:0d: - 14:49:6e:91:93:27:14:31:ef:c4:f7:2d:45:f8:ec:c7:bf:a2: - 41:0d:23:b4:92:f9:19:00:67:bd:01:af:cd:e0:71:fc:5a:cf: - 64:c4:e0:96:98:d0:a3:40:e2:01:8a:ef:27:07:f1:65:01:8a: - 44:2d:06:65:75:52:c0:86:10:20:21:5f:6c:6b:0f:6c:ae:09: - 1c:af:f2:a2:18:34:c4:75:a4:73:1c:f1:8d:dc:ef:ad:f9:b3: - 76:b4:92:bf:dc:95:10:1e:be:cb:c8:3b:5a:84:60:19:56:94: - a9:55 ------BEGIN CERTIFICATE----- -MIICkDCCAfmgAwIBAgIBATANBgkqhkiG9w0BAQQFADBaMQswCQYDVQQGEwJVUzEc -MBoGA1UEChMTRXF1aWZheCBTZWN1cmUgSW5jLjEtMCsGA1UEAxMkRXF1aWZheCBT -ZWN1cmUgR2xvYmFsIGVCdXNpbmVzcyBDQS0xMB4XDTk5MDYyMTA0MDAwMFoXDTIw -MDYyMTA0MDAwMFowWjELMAkGA1UEBhMCVVMxHDAaBgNVBAoTE0VxdWlmYXggU2Vj -dXJlIEluYy4xLTArBgNVBAMTJEVxdWlmYXggU2VjdXJlIEdsb2JhbCBlQnVzaW5l -c3MgQ0EtMTCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAuucXkAJlsTRVPEnC -UdXfp9E3j9HngXNBUmCbnaEXJnitx7HoJpQytd4zjTov2/KaelpzmKNc6fuKcxtc -58O/gGzNqfTWK8D3+ZmqY6KxRwIP1ORROhI8bIpaVIRw28HFkM9yRcuoWcDNM50/ -o5brhTMhHD4ePmBudpxnhcXIw2ECAwEAAaNmMGQwEQYJYIZIAYb4QgEBBAQDAgAH -MA8GA1UdEwEB/wQFMAMBAf8wHwYDVR0jBBgwFoAUvqigdHJQa0S3ySPY+6j/s1dr -aGwwHQYDVR0OBBYEFL6ooHRyUGtEt8kj2Puo/7NXa2hsMA0GCSqGSIb3DQEBBAUA -A4GBADDiAVGqx+pf2rnQZQ8w1j7aDRRJbpGTJxQx78T3LUX47Me/okENI7SS+RkA -Z70Br83gcfxaz2TE4JaY0KNA4gGK7ycH8WUBikQtBmV1UsCGECAhX2xrD2yuCRyv -8qIYNMR1pHMc8Y3c7635s3a0kr/clRAevsvIO1qEYBlWlKlV ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: 4 (0x4) - Signature Algorithm: md5WithRSAEncryption - Issuer: C=US, O=Equifax Secure Inc., CN=Equifax Secure eBusiness CA-1 - Validity - Not Before: Jun 21 04:00:00 1999 GMT - Not After : Jun 21 04:00:00 2020 GMT - Subject: C=US, O=Equifax Secure Inc., CN=Equifax Secure eBusiness CA-1 - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (1024 bit) - Modulus: - 00:ce:2f:19:bc:17:b7:77:de:93:a9:5f:5a:0d:17: - 4f:34:1a:0c:98:f4:22:d9:59:d4:c4:68:46:f0:b4: - 35:c5:85:03:20:c6:af:45:a5:21:51:45:41:eb:16: - 58:36:32:6f:e2:50:62:64:f9:fd:51:9c:aa:24:d9: - f4:9d:83:2a:87:0a:21:d3:12:38:34:6c:8d:00:6e: - 5a:a0:d9:42:ee:1a:21:95:f9:52:4c:55:5a:c5:0f: - 38:4f:46:fa:6d:f8:2e:35:d6:1d:7c:eb:e2:f0:b0: - 75:80:c8:a9:13:ac:be:88:ef:3a:6e:ab:5f:2a:38: - 62:02:b0:12:7b:fe:8f:a6:03 - Exponent: 65537 (0x10001) - X509v3 extensions: - Netscape Cert Type: - SSL CA, S/MIME CA, Object Signing CA - X509v3 Basic Constraints: critical - CA:TRUE - X509v3 Authority Key Identifier: - keyid:4A:78:32:52:11:DB:59:16:36:5E:DF:C1:14:36:40:6A:47:7C:4C:A1 - - X509v3 Subject Key Identifier: - 4A:78:32:52:11:DB:59:16:36:5E:DF:C1:14:36:40:6A:47:7C:4C:A1 - Signature Algorithm: md5WithRSAEncryption - 75:5b:a8:9b:03:11:e6:e9:56:4c:cd:f9:a9:4c:c0:0d:9a:f3: - cc:65:69:e6:25:76:cc:59:b7:d6:54:c3:1d:cd:99:ac:19:dd: - b4:85:d5:e0:3d:fc:62:20:a7:84:4b:58:65:f1:e2:f9:95:21: - 3f:f5:d4:7e:58:1e:47:87:54:3e:58:a1:b5:b5:f8:2a:ef:71: - e7:bc:c3:f6:b1:49:46:e2:d7:a0:6b:e5:56:7a:9a:27:98:7c: - 46:62:14:e7:c9:fc:6e:03:12:79:80:38:1d:48:82:8d:fc:17: - fe:2a:96:2b:b5:62:a6:a6:3d:bd:7f:92:59:cd:5a:2a:82:b2: - 37:79 ------BEGIN CERTIFICATE----- -MIICgjCCAeugAwIBAgIBBDANBgkqhkiG9w0BAQQFADBTMQswCQYDVQQGEwJVUzEc -MBoGA1UEChMTRXF1aWZheCBTZWN1cmUgSW5jLjEmMCQGA1UEAxMdRXF1aWZheCBT -ZWN1cmUgZUJ1c2luZXNzIENBLTEwHhcNOTkwNjIxMDQwMDAwWhcNMjAwNjIxMDQw -MDAwWjBTMQswCQYDVQQGEwJVUzEcMBoGA1UEChMTRXF1aWZheCBTZWN1cmUgSW5j -LjEmMCQGA1UEAxMdRXF1aWZheCBTZWN1cmUgZUJ1c2luZXNzIENBLTEwgZ8wDQYJ -KoZIhvcNAQEBBQADgY0AMIGJAoGBAM4vGbwXt3fek6lfWg0XTzQaDJj0ItlZ1MRo -RvC0NcWFAyDGr0WlIVFFQesWWDYyb+JQYmT5/VGcqiTZ9J2DKocKIdMSODRsjQBu -WqDZQu4aIZX5UkxVWsUPOE9G+m34LjXWHXzr4vCwdYDIqROsvojvOm6rXyo4YgKw -Env+j6YDAgMBAAGjZjBkMBEGCWCGSAGG+EIBAQQEAwIABzAPBgNVHRMBAf8EBTAD -AQH/MB8GA1UdIwQYMBaAFEp4MlIR21kWNl7fwRQ2QGpHfEyhMB0GA1UdDgQWBBRK -eDJSEdtZFjZe38EUNkBqR3xMoTANBgkqhkiG9w0BAQQFAAOBgQB1W6ibAxHm6VZM -zfmpTMANmvPMZWnmJXbMWbfWVMMdzZmsGd20hdXgPfxiIKeES1hl8eL5lSE/9dR+ -WB5Hh1Q+WKG1tfgq73HnvMP2sUlG4tega+VWeponmHxGYhTnyfxuAxJ5gDgdSIKN -/Bf+KpYrtWKmpj29f5JZzVoqgrI3eQ== ------END CERTIFICATE----- -Certificate: - Data: - Version: 1 (0x0) - Serial Number: 421 (0x1a5) - Signature Algorithm: md5WithRSAEncryption - Issuer: C=US, O=GTE Corporation, OU=GTE CyberTrust Solutions, Inc., CN=GTE CyberTrust Global Root - Validity - Not Before: Aug 13 00:29:00 1998 GMT - Not After : Aug 13 23:59:00 2018 GMT - Subject: C=US, O=GTE Corporation, OU=GTE CyberTrust Solutions, Inc., CN=GTE CyberTrust Global Root - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (1024 bit) - Modulus: - 00:95:0f:a0:b6:f0:50:9c:e8:7a:c7:88:cd:dd:17: - 0e:2e:b0:94:d0:1b:3d:0e:f6:94:c0:8a:94:c7:06: - c8:90:97:c8:b8:64:1a:7a:7e:6c:3c:53:e1:37:28: - 73:60:7f:b2:97:53:07:9f:53:f9:6d:58:94:d2:af: - 8d:6d:88:67:80:e6:ed:b2:95:cf:72:31:ca:a5:1c: - 72:ba:5c:02:e7:64:42:e7:f9:a9:2c:d6:3a:0d:ac: - 8d:42:aa:24:01:39:e6:9c:3f:01:85:57:0d:58:87: - 45:f8:d3:85:aa:93:69:26:85:70:48:80:3f:12:15: - c7:79:b4:1f:05:2f:3b:62:99 - Exponent: 65537 (0x10001) - Signature Algorithm: md5WithRSAEncryption - 6d:eb:1b:09:e9:5e:d9:51:db:67:22:61:a4:2a:3c:48:77:e3: - a0:7c:a6:de:73:a2:14:03:85:3d:fb:ab:0e:30:c5:83:16:33: - 81:13:08:9e:7b:34:4e:df:40:c8:74:d7:b9:7d:dc:f4:76:55: - 7d:9b:63:54:18:e9:f0:ea:f3:5c:b1:d9:8b:42:1e:b9:c0:95: - 4e:ba:fa:d5:e2:7c:f5:68:61:bf:8e:ec:05:97:5f:5b:b0:d7: - a3:85:34:c4:24:a7:0d:0f:95:93:ef:cb:94:d8:9e:1f:9d:5c: - 85:6d:c7:aa:ae:4f:1f:22:b5:cd:95:ad:ba:a7:cc:f9:ab:0b: - 7a:7f ------BEGIN CERTIFICATE----- -MIICWjCCAcMCAgGlMA0GCSqGSIb3DQEBBAUAMHUxCzAJBgNVBAYTAlVTMRgwFgYD -VQQKEw9HVEUgQ29ycG9yYXRpb24xJzAlBgNVBAsTHkdURSBDeWJlclRydXN0IFNv -bHV0aW9ucywgSW5jLjEjMCEGA1UEAxMaR1RFIEN5YmVyVHJ1c3QgR2xvYmFsIFJv -b3QwHhcNOTgwODEzMDAyOTAwWhcNMTgwODEzMjM1OTAwWjB1MQswCQYDVQQGEwJV -UzEYMBYGA1UEChMPR1RFIENvcnBvcmF0aW9uMScwJQYDVQQLEx5HVEUgQ3liZXJU -cnVzdCBTb2x1dGlvbnMsIEluYy4xIzAhBgNVBAMTGkdURSBDeWJlclRydXN0IEds -b2JhbCBSb290MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCVD6C28FCc6HrH -iM3dFw4usJTQGz0O9pTAipTHBsiQl8i4ZBp6fmw8U+E3KHNgf7KXUwefU/ltWJTS -r41tiGeA5u2ylc9yMcqlHHK6XALnZELn+aks1joNrI1CqiQBOeacPwGFVw1Yh0X4 -04Wqk2kmhXBIgD8SFcd5tB8FLztimQIDAQABMA0GCSqGSIb3DQEBBAUAA4GBAG3r -GwnpXtlR22ciYaQqPEh346B8pt5zohQDhT37qw4wxYMWM4ETCJ57NE7fQMh017l9 -3PR2VX2bY1QY6fDq81yx2YtCHrnAlU66+tXifPVoYb+O7AWXX1uw16OFNMQkpw0P -lZPvy5TYnh+dXIVtx6quTx8itc2VrbqnzPmrC3p/ ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: 105 (0x69) - Signature Algorithm: md5WithRSAEncryption - Issuer: C=HU, L=Budapest, O=NetLock Halozatbiztonsagi Kft., OU=Tanusitvanykiadok, CN=NetLock Uzleti (Class B) Tanusitvanykiado - Validity - Not Before: Feb 25 14:10:22 1999 GMT - Not After : Feb 20 14:10:22 2019 GMT - Subject: C=HU, L=Budapest, O=NetLock Halozatbiztonsagi Kft., OU=Tanusitvanykiadok, CN=NetLock Uzleti (Class B) Tanusitvanykiado - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (1024 bit) - Modulus: - 00:b1:ea:04:ec:20:a0:23:c2:8f:38:60:cf:c7:46: - b3:d5:1b:fe:fb:b9:99:9e:04:dc:1c:7f:8c:4a:81: - 98:ee:a4:d4:ca:8a:17:b9:22:7f:83:0a:75:4c:9b: - c0:69:d8:64:39:a3:ed:92:a3:fd:5b:5c:74:1a:c0: - 47:ca:3a:69:76:9a:ba:e2:44:17:fc:4c:a3:d5:fe: - b8:97:88:af:88:03:89:1f:a4:f2:04:3e:c8:07:0b: - e6:f9:b3:2f:7a:62:14:09:46:14:ca:64:f5:8b:80: - b5:62:a8:d8:6b:d6:71:93:2d:b3:bf:09:54:58:ed: - 06:eb:a8:7b:dc:43:b1:a1:69 - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Basic Constraints: critical - CA:TRUE, pathlen:4 - X509v3 Key Usage: critical - Certificate Sign, CRL Sign - Netscape Cert Type: - SSL CA, S/MIME CA, Object Signing CA - Netscape Comment: - FIGYELEM! Ezen tanusitvany a NetLock Kft. Altalanos Szolgaltatasi Felteteleiben leirt eljarasok alapjan keszult. A hitelesites folyamatat a NetLock Kft. termekfelelosseg-biztositasa vedi. A digitalis alairas elfogadasanak feltetele az eloirt ellenorzesi eljaras megtetele. Az eljaras leirasa megtalalhato a NetLock Kft. Internet honlapjan a https://www.netlock.net/docs cimen vagy kerheto az ellenorzes@netlock.net e-mail cimen. IMPORTANT! The issuance and the use of this certificate is subject to the NetLock CPS available at https://www.netlock.net/docs or by e-mail at cps@netlock.net. - Signature Algorithm: md5WithRSAEncryption - 04:db:ae:8c:17:af:f8:0e:90:31:4e:cd:3e:09:c0:6d:3a:b0: - f8:33:4c:47:4c:e3:75:88:10:97:ac:b0:38:15:91:c6:29:96: - cc:21:c0:6d:3c:a5:74:cf:d8:82:a5:39:c3:65:e3:42:70:bb: - 22:90:e3:7d:db:35:76:e1:a0:b5:da:9f:70:6e:93:1a:30:39: - 1d:30:db:2e:e3:7c:b2:91:b2:d1:37:29:fa:b9:d6:17:5c:47: - 4f:e3:1d:38:eb:9f:d5:7b:95:a8:28:9e:15:4a:d1:d1:d0:2b: - 00:97:a0:e2:92:36:2b:63:ac:58:01:6b:33:29:50:86:83:f1: - 01:48 ------BEGIN CERTIFICATE----- -MIIFSzCCBLSgAwIBAgIBaTANBgkqhkiG9w0BAQQFADCBmTELMAkGA1UEBhMCSFUx -ETAPBgNVBAcTCEJ1ZGFwZXN0MScwJQYDVQQKEx5OZXRMb2NrIEhhbG96YXRiaXp0 -b25zYWdpIEtmdC4xGjAYBgNVBAsTEVRhbnVzaXR2YW55a2lhZG9rMTIwMAYDVQQD -EylOZXRMb2NrIFV6bGV0aSAoQ2xhc3MgQikgVGFudXNpdHZhbnlraWFkbzAeFw05 -OTAyMjUxNDEwMjJaFw0xOTAyMjAxNDEwMjJaMIGZMQswCQYDVQQGEwJIVTERMA8G -A1UEBxMIQnVkYXBlc3QxJzAlBgNVBAoTHk5ldExvY2sgSGFsb3phdGJpenRvbnNh -Z2kgS2Z0LjEaMBgGA1UECxMRVGFudXNpdHZhbnlraWFkb2sxMjAwBgNVBAMTKU5l -dExvY2sgVXpsZXRpIChDbGFzcyBCKSBUYW51c2l0dmFueWtpYWRvMIGfMA0GCSqG -SIb3DQEBAQUAA4GNADCBiQKBgQCx6gTsIKAjwo84YM/HRrPVG/77uZmeBNwcf4xK -gZjupNTKihe5In+DCnVMm8Bp2GQ5o+2So/1bXHQawEfKOml2mrriRBf8TKPV/riX -iK+IA4kfpPIEPsgHC+b5sy96YhQJRhTKZPWLgLViqNhr1nGTLbO/CVRY7QbrqHvc -Q7GhaQIDAQABo4ICnzCCApswEgYDVR0TAQH/BAgwBgEB/wIBBDAOBgNVHQ8BAf8E -BAMCAAYwEQYJYIZIAYb4QgEBBAQDAgAHMIICYAYJYIZIAYb4QgENBIICURaCAk1G -SUdZRUxFTSEgRXplbiB0YW51c2l0dmFueSBhIE5ldExvY2sgS2Z0LiBBbHRhbGFu -b3MgU3pvbGdhbHRhdGFzaSBGZWx0ZXRlbGVpYmVuIGxlaXJ0IGVsamFyYXNvayBh -bGFwamFuIGtlc3p1bHQuIEEgaGl0ZWxlc2l0ZXMgZm9seWFtYXRhdCBhIE5ldExv -Y2sgS2Z0LiB0ZXJtZWtmZWxlbG9zc2VnLWJpenRvc2l0YXNhIHZlZGkuIEEgZGln -aXRhbGlzIGFsYWlyYXMgZWxmb2dhZGFzYW5hayBmZWx0ZXRlbGUgYXogZWxvaXJ0 -IGVsbGVub3J6ZXNpIGVsamFyYXMgbWVndGV0ZWxlLiBBeiBlbGphcmFzIGxlaXJh -c2EgbWVndGFsYWxoYXRvIGEgTmV0TG9jayBLZnQuIEludGVybmV0IGhvbmxhcGph -biBhIGh0dHBzOi8vd3d3Lm5ldGxvY2submV0L2RvY3MgY2ltZW4gdmFneSBrZXJo -ZXRvIGF6IGVsbGVub3J6ZXNAbmV0bG9jay5uZXQgZS1tYWlsIGNpbWVuLiBJTVBP -UlRBTlQhIFRoZSBpc3N1YW5jZSBhbmQgdGhlIHVzZSBvZiB0aGlzIGNlcnRpZmlj -YXRlIGlzIHN1YmplY3QgdG8gdGhlIE5ldExvY2sgQ1BTIGF2YWlsYWJsZSBhdCBo -dHRwczovL3d3dy5uZXRsb2NrLm5ldC9kb2NzIG9yIGJ5IGUtbWFpbCBhdCBjcHNA -bmV0bG9jay5uZXQuMA0GCSqGSIb3DQEBBAUAA4GBAATbrowXr/gOkDFOzT4JwG06 -sPgzTEdM43WIEJessDgVkcYplswhwG08pXTP2IKlOcNl40JwuyKQ433bNXbhoLXa -n3BukxowOR0w2y7jfLKRstE3Kfq51hdcR0/jHTjrn9V7lagonhVK0dHQKwCXoOKS -NitjrFgBazMpUIaD8QFI ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: 104 (0x68) - Signature Algorithm: md5WithRSAEncryption - Issuer: C=HU, L=Budapest, O=NetLock Halozatbiztonsagi Kft., OU=Tanusitvanykiadok, CN=NetLock Expressz (Class C) Tanusitvanykiado - Validity - Not Before: Feb 25 14:08:11 1999 GMT - Not After : Feb 20 14:08:11 2019 GMT - Subject: C=HU, L=Budapest, O=NetLock Halozatbiztonsagi Kft., OU=Tanusitvanykiadok, CN=NetLock Expressz (Class C) Tanusitvanykiado - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (1024 bit) - Modulus: - 00:eb:ec:b0:6c:61:8a:23:25:af:60:20:e3:d9:9f: - fc:93:0b:db:5d:8d:b0:a1:b3:40:3a:82:ce:fd:75: - e0:78:32:03:86:5a:86:95:91:ed:53:fa:9d:40:fc: - e6:e8:dd:d9:5b:7a:03:bd:5d:f3:3b:0c:c3:51:79: - 9b:ad:55:a0:e9:d0:03:10:af:0a:ba:14:42:d9:52: - 26:11:22:c7:d2:20:cc:82:a4:9a:a9:fe:b8:81:76: - 9d:6a:b7:d2:36:75:3e:b1:86:09:f6:6e:6d:7e:4e: - b7:7a:ec:ae:71:84:f6:04:33:08:25:32:eb:74:ac: - 16:44:c6:e4:40:93:1d:7f:ad - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Basic Constraints: critical - CA:TRUE, pathlen:4 - X509v3 Key Usage: critical - Certificate Sign, CRL Sign - Netscape Cert Type: - SSL CA, S/MIME CA, Object Signing CA - Netscape Comment: - FIGYELEM! Ezen tanusitvany a NetLock Kft. Altalanos Szolgaltatasi Felteteleiben leirt eljarasok alapjan keszult. A hitelesites folyamatat a NetLock Kft. termekfelelosseg-biztositasa vedi. A digitalis alairas elfogadasanak feltetele az eloirt ellenorzesi eljaras megtetele. Az eljaras leirasa megtalalhato a NetLock Kft. Internet honlapjan a https://www.netlock.net/docs cimen vagy kerheto az ellenorzes@netlock.net e-mail cimen. IMPORTANT! The issuance and the use of this certificate is subject to the NetLock CPS available at https://www.netlock.net/docs or by e-mail at cps@netlock.net. - Signature Algorithm: md5WithRSAEncryption - 10:ad:7f:d7:0c:32:80:0a:d8:86:f1:79:98:b5:ad:d4:cd:b3: - 36:c4:96:48:c1:5c:cd:9a:d9:05:2e:9f:be:50:eb:f4:26:14: - 10:2d:d4:66:17:f8:9e:c1:27:fd:f1:ed:e4:7b:4b:a0:6c:b5: - ab:9a:57:70:a6:ed:a0:a4:ed:2e:f5:fd:fc:bd:fe:4d:37:08: - 0c:bc:e3:96:83:22:f5:49:1b:7f:4b:2b:b4:54:c1:80:7c:99: - 4e:1d:d0:8c:ee:d0:ac:e5:92:fa:75:56:fe:64:a0:13:8f:b8: - b8:16:9d:61:05:67:80:c8:d0:d8:a5:07:02:34:98:04:8d:33: - 04:d4 ------BEGIN CERTIFICATE----- -MIIFTzCCBLigAwIBAgIBaDANBgkqhkiG9w0BAQQFADCBmzELMAkGA1UEBhMCSFUx -ETAPBgNVBAcTCEJ1ZGFwZXN0MScwJQYDVQQKEx5OZXRMb2NrIEhhbG96YXRiaXp0 -b25zYWdpIEtmdC4xGjAYBgNVBAsTEVRhbnVzaXR2YW55a2lhZG9rMTQwMgYDVQQD -EytOZXRMb2NrIEV4cHJlc3N6IChDbGFzcyBDKSBUYW51c2l0dmFueWtpYWRvMB4X -DTk5MDIyNTE0MDgxMVoXDTE5MDIyMDE0MDgxMVowgZsxCzAJBgNVBAYTAkhVMREw -DwYDVQQHEwhCdWRhcGVzdDEnMCUGA1UEChMeTmV0TG9jayBIYWxvemF0Yml6dG9u -c2FnaSBLZnQuMRowGAYDVQQLExFUYW51c2l0dmFueWtpYWRvazE0MDIGA1UEAxMr -TmV0TG9jayBFeHByZXNzeiAoQ2xhc3MgQykgVGFudXNpdHZhbnlraWFkbzCBnzAN -BgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEA6+ywbGGKIyWvYCDj2Z/8kwvbXY2wobNA -OoLO/XXgeDIDhlqGlZHtU/qdQPzm6N3ZW3oDvV3zOwzDUXmbrVWg6dADEK8KuhRC -2VImESLH0iDMgqSaqf64gXadarfSNnU+sYYJ9m5tfk63euyucYT2BDMIJTLrdKwW -RMbkQJMdf60CAwEAAaOCAp8wggKbMBIGA1UdEwEB/wQIMAYBAf8CAQQwDgYDVR0P -AQH/BAQDAgAGMBEGCWCGSAGG+EIBAQQEAwIABzCCAmAGCWCGSAGG+EIBDQSCAlEW -ggJNRklHWUVMRU0hIEV6ZW4gdGFudXNpdHZhbnkgYSBOZXRMb2NrIEtmdC4gQWx0 -YWxhbm9zIFN6b2xnYWx0YXRhc2kgRmVsdGV0ZWxlaWJlbiBsZWlydCBlbGphcmFz -b2sgYWxhcGphbiBrZXN6dWx0LiBBIGhpdGVsZXNpdGVzIGZvbHlhbWF0YXQgYSBO -ZXRMb2NrIEtmdC4gdGVybWVrZmVsZWxvc3NlZy1iaXp0b3NpdGFzYSB2ZWRpLiBB -IGRpZ2l0YWxpcyBhbGFpcmFzIGVsZm9nYWRhc2FuYWsgZmVsdGV0ZWxlIGF6IGVs -b2lydCBlbGxlbm9yemVzaSBlbGphcmFzIG1lZ3RldGVsZS4gQXogZWxqYXJhcyBs -ZWlyYXNhIG1lZ3RhbGFsaGF0byBhIE5ldExvY2sgS2Z0LiBJbnRlcm5ldCBob25s -YXBqYW4gYSBodHRwczovL3d3dy5uZXRsb2NrLm5ldC9kb2NzIGNpbWVuIHZhZ3kg -a2VyaGV0byBheiBlbGxlbm9yemVzQG5ldGxvY2submV0IGUtbWFpbCBjaW1lbi4g -SU1QT1JUQU5UISBUaGUgaXNzdWFuY2UgYW5kIHRoZSB1c2Ugb2YgdGhpcyBjZXJ0 -aWZpY2F0ZSBpcyBzdWJqZWN0IHRvIHRoZSBOZXRMb2NrIENQUyBhdmFpbGFibGUg -YXQgaHR0cHM6Ly93d3cubmV0bG9jay5uZXQvZG9jcyBvciBieSBlLW1haWwgYXQg -Y3BzQG5ldGxvY2submV0LjANBgkqhkiG9w0BAQQFAAOBgQAQrX/XDDKACtiG8XmY -ta3UzbM2xJZIwVzNmtkFLp++UOv0JhQQLdRmF/iewSf98e3ke0ugbLWrmldwpu2g -pO0u9f38vf5NNwgMvOOWgyL1SRt/Syu0VMGAfJlOHdCM7tCs5ZL6dVb+ZKATj7i4 -Fp1hBWeAyNDYpQcCNJgEjTME1A== ------END CERTIFICATE----- -Certificate: - Data: - Version: 1 (0x0) - Serial Number: 1 (0x1) - Signature Algorithm: sha1WithRSAEncryption - Issuer: L=ValiCert Validation Network, O=ValiCert, Inc., OU=ValiCert Class 3 Policy Validation Authority, CN=http://www.valicert.com//emailAddress=info@valicert.com - Validity - Not Before: Jun 26 00:22:33 1999 GMT - Not After : Jun 26 00:22:33 2019 GMT - Subject: L=ValiCert Validation Network, O=ValiCert, Inc., OU=ValiCert Class 3 Policy Validation Authority, CN=http://www.valicert.com//emailAddress=info@valicert.com - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (1024 bit) - Modulus: - 00:e3:98:51:96:1c:e8:d5:b1:06:81:6a:57:c3:72: - 75:93:ab:cf:9e:a6:fc:f3:16:52:d6:2d:4d:9f:35: - 44:a8:2e:04:4d:07:49:8a:38:29:f5:77:37:e7:b7: - ab:5d:df:36:71:14:99:8f:dc:c2:92:f1:e7:60:92: - 97:ec:d8:48:dc:bf:c1:02:20:c6:24:a4:28:4c:30: - 5a:76:6d:b1:5c:f3:dd:de:9e:10:71:a1:88:c7:5b: - 9b:41:6d:ca:b0:b8:8e:15:ee:ad:33:2b:cf:47:04: - 5c:75:71:0a:98:24:98:29:a7:49:59:a5:dd:f8:b7: - 43:62:61:f3:d3:e2:d0:55:3f - Exponent: 65537 (0x10001) - Signature Algorithm: sha1WithRSAEncryption - 56:bb:02:58:84:67:08:2c:df:1f:db:7b:49:33:f5:d3:67:9d: - f4:b4:0a:10:b3:c9:c5:2c:e2:92:6a:71:78:27:f2:70:83:42: - d3:3e:cf:a9:54:f4:f1:d8:92:16:8c:d1:04:cb:4b:ab:c9:9f: - 45:ae:3c:8a:a9:b0:71:33:5d:c8:c5:57:df:af:a8:35:b3:7f: - 89:87:e9:e8:25:92:b8:7f:85:7a:ae:d6:bc:1e:37:58:2a:67: - c9:91:cf:2a:81:3e:ed:c6:39:df:c0:3e:19:9c:19:cc:13:4d: - 82:41:b5:8c:de:e0:3d:60:08:20:0f:45:7e:6b:a2:7f:a3:8c: - 15:ee ------BEGIN CERTIFICATE----- -MIIC5zCCAlACAQEwDQYJKoZIhvcNAQEFBQAwgbsxJDAiBgNVBAcTG1ZhbGlDZXJ0 -IFZhbGlkYXRpb24gTmV0d29yazEXMBUGA1UEChMOVmFsaUNlcnQsIEluYy4xNTAz -BgNVBAsTLFZhbGlDZXJ0IENsYXNzIDMgUG9saWN5IFZhbGlkYXRpb24gQXV0aG9y -aXR5MSEwHwYDVQQDExhodHRwOi8vd3d3LnZhbGljZXJ0LmNvbS8xIDAeBgkqhkiG -9w0BCQEWEWluZm9AdmFsaWNlcnQuY29tMB4XDTk5MDYyNjAwMjIzM1oXDTE5MDYy -NjAwMjIzM1owgbsxJDAiBgNVBAcTG1ZhbGlDZXJ0IFZhbGlkYXRpb24gTmV0d29y -azEXMBUGA1UEChMOVmFsaUNlcnQsIEluYy4xNTAzBgNVBAsTLFZhbGlDZXJ0IENs -YXNzIDMgUG9saWN5IFZhbGlkYXRpb24gQXV0aG9yaXR5MSEwHwYDVQQDExhodHRw -Oi8vd3d3LnZhbGljZXJ0LmNvbS8xIDAeBgkqhkiG9w0BCQEWEWluZm9AdmFsaWNl -cnQuY29tMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDjmFGWHOjVsQaBalfD -cnWTq8+epvzzFlLWLU2fNUSoLgRNB0mKOCn1dzfnt6td3zZxFJmP3MKS8edgkpfs -2Ejcv8ECIMYkpChMMFp2bbFc893enhBxoYjHW5tBbcqwuI4V7q0zK89HBFx1cQqY -JJgpp0lZpd34t0NiYfPT4tBVPwIDAQABMA0GCSqGSIb3DQEBBQUAA4GBAFa7AliE -Zwgs3x/be0kz9dNnnfS0ChCzycUs4pJqcXgn8nCDQtM+z6lU9PHYkhaM0QTLS6vJ -n0WuPIqpsHEzXcjFV9+vqDWzf4mH6eglkrh/hXqu1rweN1gqZ8mRzyqBPu3GOd/A -PhmcGcwTTYJBtYze4D1gCCAPRX5ron+jjBXu ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: 1 (0x1) - Signature Algorithm: md5WithRSAEncryption - Issuer: C=ZA, ST=Western Cape, L=Cape Town, O=Thawte Consulting cc, OU=Certification Services Division, CN=Thawte Premium Server CA/emailAddress=premium-server@thawte.com - Validity - Not Before: Aug 1 00:00:00 1996 GMT - Not After : Dec 31 23:59:59 2020 GMT - Subject: C=ZA, ST=Western Cape, L=Cape Town, O=Thawte Consulting cc, OU=Certification Services Division, CN=Thawte Premium Server CA/emailAddress=premium-server@thawte.com - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (1024 bit) - Modulus: - 00:d2:36:36:6a:8b:d7:c2:5b:9e:da:81:41:62:8f: - 38:ee:49:04:55:d6:d0:ef:1c:1b:95:16:47:ef:18: - 48:35:3a:52:f4:2b:6a:06:8f:3b:2f:ea:56:e3:af: - 86:8d:9e:17:f7:9e:b4:65:75:02:4d:ef:cb:09:a2: - 21:51:d8:9b:d0:67:d0:ba:0d:92:06:14:73:d4:93: - cb:97:2a:00:9c:5c:4e:0c:bc:fa:15:52:fc:f2:44: - 6e:da:11:4a:6e:08:9f:2f:2d:e3:f9:aa:3a:86:73: - b6:46:53:58:c8:89:05:bd:83:11:b8:73:3f:aa:07: - 8d:f4:42:4d:e7:40:9d:1c:37 - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Basic Constraints: critical - CA:TRUE - Signature Algorithm: md5WithRSAEncryption - 26:48:2c:16:c2:58:fa:e8:16:74:0c:aa:aa:5f:54:3f:f2:d7: - c9:78:60:5e:5e:6e:37:63:22:77:36:7e:b2:17:c4:34:b9:f5: - 08:85:fc:c9:01:38:ff:4d:be:f2:16:42:43:e7:bb:5a:46:fb: - c1:c6:11:1f:f1:4a:b0:28:46:c9:c3:c4:42:7d:bc:fa:ab:59: - 6e:d5:b7:51:88:11:e3:a4:85:19:6b:82:4c:a4:0c:12:ad:e9: - a4:ae:3f:f1:c3:49:65:9a:8c:c5:c8:3e:25:b7:94:99:bb:92: - 32:71:07:f0:86:5e:ed:50:27:a6:0d:a6:23:f9:bb:cb:a6:07: - 14:42 ------BEGIN CERTIFICATE----- -MIIDJzCCApCgAwIBAgIBATANBgkqhkiG9w0BAQQFADCBzjELMAkGA1UEBhMCWkEx -FTATBgNVBAgTDFdlc3Rlcm4gQ2FwZTESMBAGA1UEBxMJQ2FwZSBUb3duMR0wGwYD -VQQKExRUaGF3dGUgQ29uc3VsdGluZyBjYzEoMCYGA1UECxMfQ2VydGlmaWNhdGlv -biBTZXJ2aWNlcyBEaXZpc2lvbjEhMB8GA1UEAxMYVGhhd3RlIFByZW1pdW0gU2Vy -dmVyIENBMSgwJgYJKoZIhvcNAQkBFhlwcmVtaXVtLXNlcnZlckB0aGF3dGUuY29t -MB4XDTk2MDgwMTAwMDAwMFoXDTIwMTIzMTIzNTk1OVowgc4xCzAJBgNVBAYTAlpB -MRUwEwYDVQQIEwxXZXN0ZXJuIENhcGUxEjAQBgNVBAcTCUNhcGUgVG93bjEdMBsG -A1UEChMUVGhhd3RlIENvbnN1bHRpbmcgY2MxKDAmBgNVBAsTH0NlcnRpZmljYXRp -b24gU2VydmljZXMgRGl2aXNpb24xITAfBgNVBAMTGFRoYXd0ZSBQcmVtaXVtIFNl -cnZlciBDQTEoMCYGCSqGSIb3DQEJARYZcHJlbWl1bS1zZXJ2ZXJAdGhhd3RlLmNv -bTCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEA0jY2aovXwlue2oFBYo847kkE -VdbQ7xwblRZH7xhINTpS9CtqBo87L+pW46+GjZ4X9560ZXUCTe/LCaIhUdib0GfQ -ug2SBhRz1JPLlyoAnFxODLz6FVL88kRu2hFKbgifLy3j+ao6hnO2RlNYyIkFvYMR -uHM/qgeN9EJN50CdHDcCAwEAAaMTMBEwDwYDVR0TAQH/BAUwAwEB/zANBgkqhkiG -9w0BAQQFAAOBgQAmSCwWwlj66BZ0DKqqX1Q/8tfJeGBeXm43YyJ3Nn6yF8Q0ufUI -hfzJATj/Tb7yFkJD57taRvvBxhEf8UqwKEbJw8RCfbz6q1lu1bdRiBHjpIUZa4JM -pAwSremkrj/xw0llmozFyD4lt5SZu5IycQfwhl7tUCemDaYj+bvLpgcUQg== ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: - 36:12:22:96:c5:e3:38:a5:20:a1:d2:5f:4c:d7:09:54 - Signature Algorithm: sha1WithRSAEncryption - Issuer: C=ZA, ST=Western Cape, L=Cape Town, O=Thawte Consulting cc, OU=Certification Services Division, CN=Thawte Premium Server CA/emailAddress=premium-server@thawte.com - Validity - Not Before: Aug 1 00:00:00 1996 GMT - Not After : Jan 1 23:59:59 2021 GMT - Subject: C=ZA, ST=Western Cape, L=Cape Town, O=Thawte Consulting cc, OU=Certification Services Division, CN=Thawte Premium Server CA/emailAddress=premium-server@thawte.com - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (1024 bit) - Modulus: - 00:d2:36:36:6a:8b:d7:c2:5b:9e:da:81:41:62:8f: - 38:ee:49:04:55:d6:d0:ef:1c:1b:95:16:47:ef:18: - 48:35:3a:52:f4:2b:6a:06:8f:3b:2f:ea:56:e3:af: - 86:8d:9e:17:f7:9e:b4:65:75:02:4d:ef:cb:09:a2: - 21:51:d8:9b:d0:67:d0:ba:0d:92:06:14:73:d4:93: - cb:97:2a:00:9c:5c:4e:0c:bc:fa:15:52:fc:f2:44: - 6e:da:11:4a:6e:08:9f:2f:2d:e3:f9:aa:3a:86:73: - b6:46:53:58:c8:89:05:bd:83:11:b8:73:3f:aa:07: - 8d:f4:42:4d:e7:40:9d:1c:37 - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Basic Constraints: critical - CA:TRUE - Signature Algorithm: sha1WithRSAEncryption - 65:90:ac:88:0f:56:d9:e6:30:34:d4:26:c7:d0:50:f1:92:de: - 6b:d4:39:88:09:22:c6:a6:63:83:03:f7:99:77:d8:b2:e5:18: - b8:5d:63:f3:d4:73:fb:6c:9c:99:78:f1:4b:78:7d:19:24:c3: - 2b:02:84:f8:bc:22:d9:8a:22:d7:a0:fc:71:ec:91:87:20:f1: - b8:ec:b1:e5:55:80:ac:3d:52:c8:39:0e:c2:f0:c0:05:4f:d6: - 82:75:8c:bd:5f:d2:dc:76:9a:05:12:c9:af:72:c3:dc:25:7e: - a4:4d:8e:17:a5:e0:87:7f:e1:9a:5a:e1:60:dc:64:23:3c:42: - 2e:4d ------BEGIN CERTIFICATE----- -MIIDNjCCAp+gAwIBAgIQNhIilsXjOKUgodJfTNcJVDANBgkqhkiG9w0BAQUFADCB -zjELMAkGA1UEBhMCWkExFTATBgNVBAgTDFdlc3Rlcm4gQ2FwZTESMBAGA1UEBxMJ -Q2FwZSBUb3duMR0wGwYDVQQKExRUaGF3dGUgQ29uc3VsdGluZyBjYzEoMCYGA1UE -CxMfQ2VydGlmaWNhdGlvbiBTZXJ2aWNlcyBEaXZpc2lvbjEhMB8GA1UEAxMYVGhh -d3RlIFByZW1pdW0gU2VydmVyIENBMSgwJgYJKoZIhvcNAQkBFhlwcmVtaXVtLXNl -cnZlckB0aGF3dGUuY29tMB4XDTk2MDgwMTAwMDAwMFoXDTIxMDEwMTIzNTk1OVow -gc4xCzAJBgNVBAYTAlpBMRUwEwYDVQQIEwxXZXN0ZXJuIENhcGUxEjAQBgNVBAcT -CUNhcGUgVG93bjEdMBsGA1UEChMUVGhhd3RlIENvbnN1bHRpbmcgY2MxKDAmBgNV -BAsTH0NlcnRpZmljYXRpb24gU2VydmljZXMgRGl2aXNpb24xITAfBgNVBAMTGFRo -YXd0ZSBQcmVtaXVtIFNlcnZlciBDQTEoMCYGCSqGSIb3DQEJARYZcHJlbWl1bS1z -ZXJ2ZXJAdGhhd3RlLmNvbTCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEA0jY2 -aovXwlue2oFBYo847kkEVdbQ7xwblRZH7xhINTpS9CtqBo87L+pW46+GjZ4X9560 -ZXUCTe/LCaIhUdib0GfQug2SBhRz1JPLlyoAnFxODLz6FVL88kRu2hFKbgifLy3j -+ao6hnO2RlNYyIkFvYMRuHM/qgeN9EJN50CdHDcCAwEAAaMTMBEwDwYDVR0TAQH/ -BAUwAwEB/zANBgkqhkiG9w0BAQUFAAOBgQBlkKyID1bZ5jA01CbH0FDxkt5r1DmI -CSLGpmODA/eZd9iy5Ri4XWPz1HP7bJyZePFLeH0ZJMMrAoT4vCLZiiLXoPxx7JGH -IPG47LHlVYCsPVLIOQ7C8MAFT9aCdYy9X9LcdpoFEsmvcsPcJX6kTY4XpeCHf+Ga -WuFg3GQjPEIuTQ== ------END CERTIFICATE----- -Certificate: - Data: - Version: 3 (0x2) - Serial Number: 1 (0x1) - Signature Algorithm: md5WithRSAEncryption - Issuer: C=ZA, ST=Western Cape, L=Cape Town, O=Thawte Consulting cc, OU=Certification Services Division, CN=Thawte Server CA/emailAddress=server-certs@thawte.com - Validity - Not Before: Aug 1 00:00:00 1996 GMT - Not After : Dec 31 23:59:59 2020 GMT - Subject: C=ZA, ST=Western Cape, L=Cape Town, O=Thawte Consulting cc, OU=Certification Services Division, CN=Thawte Server CA/emailAddress=server-certs@thawte.com - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (1024 bit) - Modulus: - 00:d3:a4:50:6e:c8:ff:56:6b:e6:cf:5d:b6:ea:0c: - 68:75:47:a2:aa:c2:da:84:25:fc:a8:f4:47:51:da: - 85:b5:20:74:94:86:1e:0f:75:c9:e9:08:61:f5:06: - 6d:30:6e:15:19:02:e9:52:c0:62:db:4d:99:9e:e2: - 6a:0c:44:38:cd:fe:be:e3:64:09:70:c5:fe:b1:6b: - 29:b6:2f:49:c8:3b:d4:27:04:25:10:97:2f:e7:90: - 6d:c0:28:42:99:d7:4c:43:de:c3:f5:21:6d:54:9f: - 5d:c3:58:e1:c0:e4:d9:5b:b0:b8:dc:b4:7b:df:36: - 3a:c2:b5:66:22:12:d6:87:0d - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Basic Constraints: critical - CA:TRUE - Signature Algorithm: md5WithRSAEncryption - 07:fa:4c:69:5c:fb:95:cc:46:ee:85:83:4d:21:30:8e:ca:d9: - a8:6f:49:1a:e6:da:51:e3:60:70:6c:84:61:11:a1:1a:c8:48: - 3e:59:43:7d:4f:95:3d:a1:8b:b7:0b:62:98:7a:75:8a:dd:88: - 4e:4e:9e:40:db:a8:cc:32:74:b9:6f:0d:c6:e3:b3:44:0b:d9: - 8a:6f:9a:29:9b:99:18:28:3b:d1:e3:40:28:9a:5a:3c:d5:b5: - e7:20:1b:8b:ca:a4:ab:8d:e9:51:d9:e2:4c:2c:59:a9:da:b9: - b2:75:1b:f6:42:f2:ef:c7:f2:18:f9:89:bc:a3:ff:8a:23:2e: - 70:47 ------BEGIN CERTIFICATE----- -MIIDEzCCAnygAwIBAgIBATANBgkqhkiG9w0BAQQFADCBxDELMAkGA1UEBhMCWkEx -FTATBgNVBAgTDFdlc3Rlcm4gQ2FwZTESMBAGA1UEBxMJQ2FwZSBUb3duMR0wGwYD -VQQKExRUaGF3dGUgQ29uc3VsdGluZyBjYzEoMCYGA1UECxMfQ2VydGlmaWNhdGlv -biBTZXJ2aWNlcyBEaXZpc2lvbjEZMBcGA1UEAxMQVGhhd3RlIFNlcnZlciBDQTEm -MCQGCSqGSIb3DQEJARYXc2VydmVyLWNlcnRzQHRoYXd0ZS5jb20wHhcNOTYwODAx -MDAwMDAwWhcNMjAxMjMxMjM1OTU5WjCBxDELMAkGA1UEBhMCWkExFTATBgNVBAgT -DFdlc3Rlcm4gQ2FwZTESMBAGA1UEBxMJQ2FwZSBUb3duMR0wGwYDVQQKExRUaGF3 -dGUgQ29uc3VsdGluZyBjYzEoMCYGA1UECxMfQ2VydGlmaWNhdGlvbiBTZXJ2aWNl -cyBEaXZpc2lvbjEZMBcGA1UEAxMQVGhhd3RlIFNlcnZlciBDQTEmMCQGCSqGSIb3 -DQEJARYXc2VydmVyLWNlcnRzQHRoYXd0ZS5jb20wgZ8wDQYJKoZIhvcNAQEBBQAD -gY0AMIGJAoGBANOkUG7I/1Zr5s9dtuoMaHVHoqrC2oQl/Kj0R1HahbUgdJSGHg91 -yekIYfUGbTBuFRkC6VLAYttNmZ7iagxEOM3+vuNkCXDF/rFrKbYvScg71CcEJRCX -L+eQbcAoQpnXTEPew/UhbVSfXcNY4cDk2VuwuNy0e982OsK1ZiIS1ocNAgMBAAGj -EzARMA8GA1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcNAQEEBQADgYEAB/pMaVz7lcxG -7oWDTSEwjsrZqG9JGubaUeNgcGyEYRGhGshIPllDfU+VPaGLtwtimHp1it2ITk6e -QNuozDJ0uW8NxuOzRAvZim+aKZuZGCg70eNAKJpaPNW15yAbi8qkq43pUdniTCxZ -qdq5snUb9kLy78fyGPmJvKP/iiMucEc= ------END CERTIFICATE----- -Certificate: - Data: - Version: 1 (0x0) - Serial Number: 1 (0x1) - Signature Algorithm: sha1WithRSAEncryption - Issuer: L=ValiCert Validation Network, O=ValiCert, Inc., OU=ValiCert Class 1 Policy Validation Authority, CN=http://www.valicert.com//emailAddress=info@valicert.com - Validity - Not Before: Jun 25 22:23:48 1999 GMT - Not After : Jun 25 22:23:48 2019 GMT - Subject: L=ValiCert Validation Network, O=ValiCert, Inc., OU=ValiCert Class 1 Policy Validation Authority, CN=http://www.valicert.com//emailAddress=info@valicert.com - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (1024 bit) - Modulus: - 00:d8:59:82:7a:89:b8:96:ba:a6:2f:68:6f:58:2e: - a7:54:1c:06:6e:f4:ea:8d:48:bc:31:94:17:f0:f3: - 4e:bc:b2:b8:35:92:76:b0:d0:a5:a5:01:d7:00:03: - 12:22:19:08:f8:ff:11:23:9b:ce:07:f5:bf:69:1a: - 26:fe:4e:e9:d1:7f:9d:2c:40:1d:59:68:6e:a6:f8: - 58:b0:9d:1a:8f:d3:3f:f1:dc:19:06:81:a8:0e:e0: - 3a:dd:c8:53:45:09:06:e6:0f:70:c3:fa:40:a6:0e: - e2:56:05:0f:18:4d:fc:20:82:d1:73:55:74:8d:76: - 72:a0:1d:9d:1d:c0:dd:3f:71 - Exponent: 65537 (0x10001) - Signature Algorithm: sha1WithRSAEncryption - 50:68:3d:49:f4:2c:1c:06:94:df:95:60:7f:96:7b:17:fe:4f: - 71:ad:64:c8:dd:77:d2:ef:59:55:e8:3f:e8:8e:05:2a:21:f2: - 07:d2:b5:a7:52:fe:9c:b1:b6:e2:5b:77:17:40:ea:72:d6:23: - cb:28:81:32:c3:00:79:18:ec:59:17:89:c9:c6:6a:1e:71:c9: - fd:b7:74:a5:25:45:69:c5:48:ab:19:e1:45:8a:25:6b:19:ee: - e5:bb:12:f5:7f:f7:a6:8d:51:c3:f0:9d:74:b7:a9:3e:a0:a5: - ff:b6:49:03:13:da:22:cc:ed:71:82:2b:99:cf:3a:b7:f5:2d: - 72:c8 ------BEGIN CERTIFICATE----- -MIIC5zCCAlACAQEwDQYJKoZIhvcNAQEFBQAwgbsxJDAiBgNVBAcTG1ZhbGlDZXJ0 -IFZhbGlkYXRpb24gTmV0d29yazEXMBUGA1UEChMOVmFsaUNlcnQsIEluYy4xNTAz -BgNVBAsTLFZhbGlDZXJ0IENsYXNzIDEgUG9saWN5IFZhbGlkYXRpb24gQXV0aG9y -aXR5MSEwHwYDVQQDExhodHRwOi8vd3d3LnZhbGljZXJ0LmNvbS8xIDAeBgkqhkiG -9w0BCQEWEWluZm9AdmFsaWNlcnQuY29tMB4XDTk5MDYyNTIyMjM0OFoXDTE5MDYy -NTIyMjM0OFowgbsxJDAiBgNVBAcTG1ZhbGlDZXJ0IFZhbGlkYXRpb24gTmV0d29y -azEXMBUGA1UEChMOVmFsaUNlcnQsIEluYy4xNTAzBgNVBAsTLFZhbGlDZXJ0IENs -YXNzIDEgUG9saWN5IFZhbGlkYXRpb24gQXV0aG9yaXR5MSEwHwYDVQQDExhodHRw -Oi8vd3d3LnZhbGljZXJ0LmNvbS8xIDAeBgkqhkiG9w0BCQEWEWluZm9AdmFsaWNl -cnQuY29tMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDYWYJ6ibiWuqYvaG9Y -LqdUHAZu9OqNSLwxlBfw8068srg1knaw0KWlAdcAAxIiGQj4/xEjm84H9b9pGib+ -TunRf50sQB1ZaG6m+FiwnRqP0z/x3BkGgagO4DrdyFNFCQbmD3DD+kCmDuJWBQ8Y -TfwggtFzVXSNdnKgHZ0dwN0/cQIDAQABMA0GCSqGSIb3DQEBBQUAA4GBAFBoPUn0 -LBwGlN+VYH+Wexf+T3GtZMjdd9LvWVXoP+iOBSoh8gfStadS/pyxtuJbdxdA6nLW -I8sogTLDAHkY7FkXicnGah5xyf23dKUlRWnFSKsZ4UWKJWsZ7uW7EvV/96aNUcPw -nXS3qT6gpf+2SQMT2iLM7XGCK5nPOrf1LXLI ------END CERTIFICATE----- -Certificate: - Data: - Version: 1 (0x0) - Serial Number: 1 (0x1) - Signature Algorithm: sha1WithRSAEncryption - Issuer: L=ValiCert Validation Network, O=ValiCert, Inc., OU=ValiCert Class 2 Policy Validation Authority, CN=http://www.valicert.com//emailAddress=info@valicert.com - Validity - Not Before: Jun 26 00:19:54 1999 GMT - Not After : Jun 26 00:19:54 2019 GMT - Subject: L=ValiCert Validation Network, O=ValiCert, Inc., OU=ValiCert Class 2 Policy Validation Authority, CN=http://www.valicert.com//emailAddress=info@valicert.com - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (1024 bit) - Modulus: - 00:ce:3a:71:ca:e5:ab:c8:59:92:55:d7:ab:d8:74: - 0e:f9:ee:d9:f6:55:47:59:65:47:0e:05:55:dc:eb: - 98:36:3c:5c:53:5d:d3:30:cf:38:ec:bd:41:89:ed: - 25:42:09:24:6b:0a:5e:b3:7c:dd:52:2d:4c:e6:d4: - d6:7d:5a:59:a9:65:d4:49:13:2d:24:4d:1c:50:6f: - b5:c1:85:54:3b:fe:71:e4:d3:5c:42:f9:80:e0:91: - 1a:0a:5b:39:36:67:f3:3f:55:7c:1b:3f:b4:5f:64: - 73:34:e3:b4:12:bf:87:64:f8:da:12:ff:37:27:c1: - b3:43:bb:ef:7b:6e:2e:69:f7 - Exponent: 65537 (0x10001) - Signature Algorithm: sha1WithRSAEncryption - 3b:7f:50:6f:6f:50:94:99:49:62:38:38:1f:4b:f8:a5:c8:3e: - a7:82:81:f6:2b:c7:e8:c5:ce:e8:3a:10:82:cb:18:00:8e:4d: - bd:a8:58:7f:a1:79:00:b5:bb:e9:8d:af:41:d9:0f:34:ee:21: - 81:19:a0:32:49:28:f4:c4:8e:56:d5:52:33:fd:50:d5:7e:99: - 6c:03:e4:c9:4c:fc:cb:6c:ab:66:b3:4a:21:8c:e5:b5:0c:32: - 3e:10:b2:cc:6c:a1:dc:9a:98:4c:02:5b:f3:ce:b9:9e:a5:72: - 0e:4a:b7:3f:3c:e6:16:68:f8:be:ed:74:4c:bc:5b:d5:62:1f: - 43:dd ------BEGIN CERTIFICATE----- -MIIC5zCCAlACAQEwDQYJKoZIhvcNAQEFBQAwgbsxJDAiBgNVBAcTG1ZhbGlDZXJ0 -IFZhbGlkYXRpb24gTmV0d29yazEXMBUGA1UEChMOVmFsaUNlcnQsIEluYy4xNTAz -BgNVBAsTLFZhbGlDZXJ0IENsYXNzIDIgUG9saWN5IFZhbGlkYXRpb24gQXV0aG9y -aXR5MSEwHwYDVQQDExhodHRwOi8vd3d3LnZhbGljZXJ0LmNvbS8xIDAeBgkqhkiG -9w0BCQEWEWluZm9AdmFsaWNlcnQuY29tMB4XDTk5MDYyNjAwMTk1NFoXDTE5MDYy -NjAwMTk1NFowgbsxJDAiBgNVBAcTG1ZhbGlDZXJ0IFZhbGlkYXRpb24gTmV0d29y -azEXMBUGA1UEChMOVmFsaUNlcnQsIEluYy4xNTAzBgNVBAsTLFZhbGlDZXJ0IENs -YXNzIDIgUG9saWN5IFZhbGlkYXRpb24gQXV0aG9yaXR5MSEwHwYDVQQDExhodHRw -Oi8vd3d3LnZhbGljZXJ0LmNvbS8xIDAeBgkqhkiG9w0BCQEWEWluZm9AdmFsaWNl -cnQuY29tMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDOOnHK5avIWZJV16vY -dA757tn2VUdZZUcOBVXc65g2PFxTXdMwzzjsvUGJ7SVCCSRrCl6zfN1SLUzm1NZ9 -WlmpZdRJEy0kTRxQb7XBhVQ7/nHk01xC+YDgkRoKWzk2Z/M/VXwbP7RfZHM047QS -v4dk+NoS/zcnwbNDu+97bi5p9wIDAQABMA0GCSqGSIb3DQEBBQUAA4GBADt/UG9v -UJSZSWI4OB9L+KXIPqeCgfYrx+jFzug6EILLGACOTb2oWH+heQC1u+mNr0HZDzTu -IYEZoDJJKPTEjlbVUjP9UNV+mWwD5MlM/Mtsq2azSiGM5bUMMj4QssxsodyamEwC -W/POuZ6lcg5Ktz885hZo+L7tdEy8W9ViH0Pd ------END CERTIFICATE----- -Certificate: - Data: - Version: 1 (0x0) - Serial Number: - 70:ba:e4:1d:10:d9:29:34:b6:38:ca:7b:03:cc:ba:bf - Signature Algorithm: md2WithRSAEncryption - Issuer: C=US, O=VeriSign, Inc., OU=Class 3 Public Primary Certification Authority - Validity - Not Before: Jan 29 00:00:00 1996 GMT - Not After : Aug 1 23:59:59 2028 GMT - Subject: C=US, O=VeriSign, Inc., OU=Class 3 Public Primary Certification Authority - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (1024 bit) - Modulus: - 00:c9:5c:59:9e:f2:1b:8a:01:14:b4:10:df:04:40: - db:e3:57:af:6a:45:40:8f:84:0c:0b:d1:33:d9:d9: - 11:cf:ee:02:58:1f:25:f7:2a:a8:44:05:aa:ec:03: - 1f:78:7f:9e:93:b9:9a:00:aa:23:7d:d6:ac:85:a2: - 63:45:c7:72:27:cc:f4:4c:c6:75:71:d2:39:ef:4f: - 42:f0:75:df:0a:90:c6:8e:20:6f:98:0f:f8:ac:23: - 5f:70:29:36:a4:c9:86:e7:b1:9a:20:cb:53:a5:85: - e7:3d:be:7d:9a:fe:24:45:33:dc:76:15:ed:0f:a2: - 71:64:4c:65:2e:81:68:45:a7 - Exponent: 65537 (0x10001) - Signature Algorithm: md2WithRSAEncryption - bb:4c:12:2b:cf:2c:26:00:4f:14:13:dd:a6:fb:fc:0a:11:84: - 8c:f3:28:1c:67:92:2f:7c:b6:c5:fa:df:f0:e8:95:bc:1d:8f: - 6c:2c:a8:51:cc:73:d8:a4:c0:53:f0:4e:d6:26:c0:76:01:57: - 81:92:5e:21:f1:d1:b1:ff:e7:d0:21:58:cd:69:17:e3:44:1c: - 9c:19:44:39:89:5c:dc:9c:00:0f:56:8d:02:99:ed:a2:90:45: - 4c:e4:bb:10:a4:3d:f0:32:03:0e:f1:ce:f8:e8:c9:51:8c:e6: - 62:9f:e6:9f:c0:7d:b7:72:9c:c9:36:3a:6b:9f:4e:a8:ff:64: - 0d:64 ------BEGIN CERTIFICATE----- -MIICPDCCAaUCEHC65B0Q2Sk0tjjKewPMur8wDQYJKoZIhvcNAQECBQAwXzELMAkG -A1UEBhMCVVMxFzAVBgNVBAoTDlZlcmlTaWduLCBJbmMuMTcwNQYDVQQLEy5DbGFz -cyAzIFB1YmxpYyBQcmltYXJ5IENlcnRpZmljYXRpb24gQXV0aG9yaXR5MB4XDTk2 -MDEyOTAwMDAwMFoXDTI4MDgwMTIzNTk1OVowXzELMAkGA1UEBhMCVVMxFzAVBgNV -BAoTDlZlcmlTaWduLCBJbmMuMTcwNQYDVQQLEy5DbGFzcyAzIFB1YmxpYyBQcmlt -YXJ5IENlcnRpZmljYXRpb24gQXV0aG9yaXR5MIGfMA0GCSqGSIb3DQEBAQUAA4GN -ADCBiQKBgQDJXFme8huKARS0EN8EQNvjV69qRUCPhAwL0TPZ2RHP7gJYHyX3KqhE -BarsAx94f56TuZoAqiN91qyFomNFx3InzPRMxnVx0jnvT0Lwdd8KkMaOIG+YD/is -I19wKTakyYbnsZogy1Olhec9vn2a/iRFM9x2Fe0PonFkTGUugWhFpwIDAQABMA0G -CSqGSIb3DQEBAgUAA4GBALtMEivPLCYATxQT3ab7/AoRhIzzKBxnki98tsX63/Do -lbwdj2wsqFHMc9ikwFPwTtYmwHYBV4GSXiHx0bH/59AhWM1pF+NEHJwZRDmJXNyc -AA9WjQKZ7aKQRUzkuxCkPfAyAw7xzvjoyVGM5mKf5p/AfbdynMk2OmufTqj/ZA1k ------END CERTIFICATE----- -Certificate: - Data: - Version: 1 (0x0) - Serial Number: - 3c:91:31:cb:1f:f6:d0:1b:0e:9a:b8:d0:44:bf:12:be - Signature Algorithm: sha1WithRSAEncryption - Issuer: C=US, O=VeriSign, Inc., OU=Class 3 Public Primary Certification Authority - Validity - Not Before: Jan 29 00:00:00 1996 GMT - Not After : Aug 2 23:59:59 2028 GMT - Subject: C=US, O=VeriSign, Inc., OU=Class 3 Public Primary Certification Authority - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (1024 bit) - Modulus: - 00:c9:5c:59:9e:f2:1b:8a:01:14:b4:10:df:04:40: - db:e3:57:af:6a:45:40:8f:84:0c:0b:d1:33:d9:d9: - 11:cf:ee:02:58:1f:25:f7:2a:a8:44:05:aa:ec:03: - 1f:78:7f:9e:93:b9:9a:00:aa:23:7d:d6:ac:85:a2: - 63:45:c7:72:27:cc:f4:4c:c6:75:71:d2:39:ef:4f: - 42:f0:75:df:0a:90:c6:8e:20:6f:98:0f:f8:ac:23: - 5f:70:29:36:a4:c9:86:e7:b1:9a:20:cb:53:a5:85: - e7:3d:be:7d:9a:fe:24:45:33:dc:76:15:ed:0f:a2: - 71:64:4c:65:2e:81:68:45:a7 - Exponent: 65537 (0x10001) - Signature Algorithm: sha1WithRSAEncryption - 10:72:52:a9:05:14:19:32:08:41:f0:c5:6b:0a:cc:7e:0f:21: - 19:cd:e4:67:dc:5f:a9:1b:e6:ca:e8:73:9d:22:d8:98:6e:73: - 03:61:91:c5:7c:b0:45:40:6e:44:9d:8d:b0:b1:96:74:61:2d: - 0d:a9:45:d2:a4:92:2a:d6:9a:75:97:6e:3f:53:fd:45:99:60: - 1d:a8:2b:4c:f9:5e:a7:09:d8:75:30:d7:d2:65:60:3d:67:d6: - 48:55:75:69:3f:91:f5:48:0b:47:69:22:69:82:96:be:c9:c8: - 38:86:4a:7a:2c:73:19:48:69:4e:6b:7c:65:bf:0f:fc:70:ce: - 88:90 ------BEGIN CERTIFICATE----- -MIICPDCCAaUCEDyRMcsf9tAbDpq40ES/Er4wDQYJKoZIhvcNAQEFBQAwXzELMAkG -A1UEBhMCVVMxFzAVBgNVBAoTDlZlcmlTaWduLCBJbmMuMTcwNQYDVQQLEy5DbGFz -cyAzIFB1YmxpYyBQcmltYXJ5IENlcnRpZmljYXRpb24gQXV0aG9yaXR5MB4XDTk2 -MDEyOTAwMDAwMFoXDTI4MDgwMjIzNTk1OVowXzELMAkGA1UEBhMCVVMxFzAVBgNV -BAoTDlZlcmlTaWduLCBJbmMuMTcwNQYDVQQLEy5DbGFzcyAzIFB1YmxpYyBQcmlt -YXJ5IENlcnRpZmljYXRpb24gQXV0aG9yaXR5MIGfMA0GCSqGSIb3DQEBAQUAA4GN -ADCBiQKBgQDJXFme8huKARS0EN8EQNvjV69qRUCPhAwL0TPZ2RHP7gJYHyX3KqhE -BarsAx94f56TuZoAqiN91qyFomNFx3InzPRMxnVx0jnvT0Lwdd8KkMaOIG+YD/is -I19wKTakyYbnsZogy1Olhec9vn2a/iRFM9x2Fe0PonFkTGUugWhFpwIDAQABMA0G -CSqGSIb3DQEBBQUAA4GBABByUqkFFBkyCEHwxWsKzH4PIRnN5GfcX6kb5sroc50i -2JhucwNhkcV8sEVAbkSdjbCxlnRhLQ2pRdKkkirWmnWXbj9T/UWZYB2oK0z5XqcJ -2HUw19JlYD1n1khVdWk/kfVIC0dpImmClr7JyDiGSnoscxlIaU5rfGW/D/xwzoiQ ------END CERTIFICATE----- -Certificate: - Data: - Version: 1 (0x0) - Serial Number: - 7d:d9:fe:07:cf:a8:1e:b7:10:79:67:fb:a7:89:34:c6 - Signature Algorithm: sha1WithRSAEncryption - Issuer: C=US, O=VeriSign, Inc., OU=Class 3 Public Primary Certification Authority - G2, OU=(c) 1998 VeriSign, Inc. - For authorized use only, OU=VeriSign Trust Network - Validity - Not Before: May 18 00:00:00 1998 GMT - Not After : Aug 1 23:59:59 2028 GMT - Subject: C=US, O=VeriSign, Inc., OU=Class 3 Public Primary Certification Authority - G2, OU=(c) 1998 VeriSign, Inc. - For authorized use only, OU=VeriSign Trust Network - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (1024 bit) - Modulus: - 00:cc:5e:d1:11:5d:5c:69:d0:ab:d3:b9:6a:4c:99: - 1f:59:98:30:8e:16:85:20:46:6d:47:3f:d4:85:20: - 84:e1:6d:b3:f8:a4:ed:0c:f1:17:0f:3b:f9:a7:f9: - 25:d7:c1:cf:84:63:f2:7c:63:cf:a2:47:f2:c6:5b: - 33:8e:64:40:04:68:c1:80:b9:64:1c:45:77:c7:d8: - 6e:f5:95:29:3c:50:e8:34:d7:78:1f:a8:ba:6d:43: - 91:95:8f:45:57:5e:7e:c5:fb:ca:a4:04:eb:ea:97: - 37:54:30:6f:bb:01:47:32:33:cd:dc:57:9b:64:69: - 61:f8:9b:1d:1c:89:4f:5c:67 - Exponent: 65537 (0x10001) - Signature Algorithm: sha1WithRSAEncryption - 51:4d:cd:be:5c:cb:98:19:9c:15:b2:01:39:78:2e:4d:0f:67: - 70:70:99:c6:10:5a:94:a4:53:4d:54:6d:2b:af:0d:5d:40:8b: - 64:d3:d7:ee:de:56:61:92:5f:a6:c4:1d:10:61:36:d3:2c:27: - 3c:e8:29:09:b9:11:64:74:cc:b5:73:9f:1c:48:a9:bc:61:01: - ee:e2:17:a6:0c:e3:40:08:3b:0e:e7:eb:44:73:2a:9a:f1:69: - 92:ef:71:14:c3:39:ac:71:a7:91:09:6f:e4:71:06:b3:ba:59: - 57:26:79:00:f6:f8:0d:a2:33:30:28:d4:aa:58:a0:9d:9d:69: - 91:fd ------BEGIN CERTIFICATE----- -MIIDAjCCAmsCEH3Z/gfPqB63EHln+6eJNMYwDQYJKoZIhvcNAQEFBQAwgcExCzAJ -BgNVBAYTAlVTMRcwFQYDVQQKEw5WZXJpU2lnbiwgSW5jLjE8MDoGA1UECxMzQ2xh -c3MgMyBQdWJsaWMgUHJpbWFyeSBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eSAtIEcy -MTowOAYDVQQLEzEoYykgMTk5OCBWZXJpU2lnbiwgSW5jLiAtIEZvciBhdXRob3Jp -emVkIHVzZSBvbmx5MR8wHQYDVQQLExZWZXJpU2lnbiBUcnVzdCBOZXR3b3JrMB4X -DTk4MDUxODAwMDAwMFoXDTI4MDgwMTIzNTk1OVowgcExCzAJBgNVBAYTAlVTMRcw -FQYDVQQKEw5WZXJpU2lnbiwgSW5jLjE8MDoGA1UECxMzQ2xhc3MgMyBQdWJsaWMg -UHJpbWFyeSBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eSAtIEcyMTowOAYDVQQLEzEo -YykgMTk5OCBWZXJpU2lnbiwgSW5jLiAtIEZvciBhdXRob3JpemVkIHVzZSBvbmx5 -MR8wHQYDVQQLExZWZXJpU2lnbiBUcnVzdCBOZXR3b3JrMIGfMA0GCSqGSIb3DQEB -AQUAA4GNADCBiQKBgQDMXtERXVxp0KvTuWpMmR9ZmDCOFoUgRm1HP9SFIIThbbP4 -pO0M8RcPO/mn+SXXwc+EY/J8Y8+iR/LGWzOOZEAEaMGAuWQcRXfH2G71lSk8UOg0 -13gfqLptQ5GVj0VXXn7F+8qkBOvqlzdUMG+7AUcyM83cV5tkaWH4mx0ciU9cZwID -AQABMA0GCSqGSIb3DQEBBQUAA4GBAFFNzb5cy5gZnBWyATl4Lk0PZ3BwmcYQWpSk -U01UbSuvDV1Ai2TT1+7eVmGSX6bEHRBhNtMsJzzoKQm5EWR0zLVznxxIqbxhAe7i -F6YM40AIOw7n60RzKprxaZLvcRTDOaxxp5EJb+RxBrO6WVcmeQD2+A2iMzAo1KpY -oJ2daZH9 ------END CERTIFICATE----- diff --git a/julia-0.6.3/share/julia/julia-config.jl b/julia-0.6.3/share/julia/julia-config.jl deleted file mode 100755 index 2a17724..0000000 --- a/julia-0.6.3/share/julia/julia-config.jl +++ /dev/null @@ -1,94 +0,0 @@ -#!/usr/bin/env julia -# This file is a part of Julia. License is MIT: https://julialang.org/license - -const options = [ - "--cflags", - "--ldflags", - "--ldlibs" -]; - -threadingOn() = ccall(:jl_threading_enabled, Cint, ()) != 0 - -function shell_escape(str) - str = replace(str, "'", "'\''") - return "'$str'" -end - -function imagePath() - opts = Base.JLOptions() - return unsafe_string(opts.image_file) -end - -function libDir() - return if ccall(:jl_is_debugbuild, Cint, ()) != 0 - dirname(abspath(Libdl.dlpath("libjulia-debug"))) - else - dirname(abspath(Libdl.dlpath("libjulia"))) - end -end - -private_libDir() = abspath(JULIA_HOME, Base.PRIVATE_LIBDIR) - -function includeDir() - return abspath(JULIA_HOME, Base.INCLUDEDIR, "julia") -end - -function ldflags() - fl = "-L$(shell_escape(libDir()))" - if is_windows() - fl = fl * " -Wl,--stack,8388608" - elseif is_linux() - fl = fl * " -Wl,--export-dynamic" - end - return fl -end - -function ldlibs() - libname = if ccall(:jl_is_debugbuild, Cint, ()) != 0 - "julia-debug" - else - "julia" - end - if is_unix() - return "-Wl,-rpath,$(shell_escape(libDir())) -Wl,-rpath,$(shell_escape(private_libDir())) -l$libname" - else - return "-l$libname -lopenlibm" - end -end - -function cflags() - flags = IOBuffer() - print(flags, "-std=gnu99") - include = shell_escape(includeDir()) - print(flags, " -I", include) - if threadingOn() - print(flags, " -DJULIA_ENABLE_THREADING=1") - end - if is_unix() - print(flags, " -fPIC") - end - return String(take!(flags)) -end - -function check_args(args) - checked = intersect(args, options) - if length(checked) == 0 || length(checked) != length(args) - println(STDERR, "Usage: julia-config [", join(options, " | "), "]") - exit(1) - end -end - -function main() - check_args(ARGS) - for args in ARGS - if args == "--ldflags" - println(ldflags()) - elseif args == "--cflags" - println(cflags()) - elseif args == "--ldlibs" - println(ldlibs()) - end - end -end - -main() diff --git a/julia-0.6.3/share/julia/test/.gitignore b/julia-0.6.3/share/julia/test/.gitignore deleted file mode 100644 index a1af9ae..0000000 --- a/julia-0.6.3/share/julia/test/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -/ccall -/ccalltest -/ccalltest.s -/libccalltest.* diff --git a/julia-0.6.3/share/julia/test/TestHelpers.jl b/julia-0.6.3/share/julia/test/TestHelpers.jl deleted file mode 100644 index 42ed574..0000000 --- a/julia-0.6.3/share/julia/test/TestHelpers.jl +++ /dev/null @@ -1,229 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -module TestHelpers - -include("dimensionful.jl") -export Furlong - -mutable struct FakeTerminal <: Base.Terminals.UnixTerminal - in_stream::Base.IO - out_stream::Base.IO - err_stream::Base.IO - hascolor::Bool - raw::Bool - FakeTerminal(stdin,stdout,stderr,hascolor=true) = - new(stdin,stdout,stderr,hascolor,false) -end - -Base.Terminals.hascolor(t::FakeTerminal) = t.hascolor -Base.Terminals.raw!(t::FakeTerminal, raw::Bool) = t.raw = raw -Base.Terminals.size(t::FakeTerminal) = (24, 80) - -function open_fake_pty() - @static if is_windows() - error("Unable to create a fake PTY in Windows") - end - - const O_RDWR = Base.Filesystem.JL_O_RDWR - const O_NOCTTY = Base.Filesystem.JL_O_NOCTTY - - fdm = ccall(:posix_openpt, Cint, (Cint,), O_RDWR|O_NOCTTY) - fdm == -1 && error("Failed to open PTY master") - rc = ccall(:grantpt, Cint, (Cint,), fdm) - rc != 0 && error("grantpt failed") - rc = ccall(:unlockpt, Cint, (Cint,), fdm) - rc != 0 && error("unlockpt") - - fds = ccall(:open, Cint, (Ptr{UInt8}, Cint), - ccall(:ptsname, Ptr{UInt8}, (Cint,), fdm), O_RDWR|O_NOCTTY) - - # slave - slave = RawFD(fds) - master = Base.TTY(RawFD(fdm); readable = true) - slave, master -end - -function with_fake_pty(f) - slave, master = open_fake_pty() - try - f(slave, master) - finally - ccall(:close,Cint,(Cint,),slave) # XXX: this causes the kernel to throw away all unread data on the pty - close(master) - end -end - -function challenge_prompt(code::AbstractString, challenges; timeout::Integer=10, debug::Bool=true) - output_file = tempname() - wrapped_code = """ - result = let - $code - end - open("$output_file", "w") do fp - serialize(fp, result) - end - """ - cmd = `$(Base.julia_cmd()) --startup-file=no -e $wrapped_code` - try - challenge_prompt(cmd, challenges, timeout=timeout, debug=debug) - return open(output_file, "r") do fp - deserialize(fp) - end - finally - isfile(output_file) && rm(output_file) - end - return nothing -end - -function challenge_prompt(cmd::Cmd, challenges; timeout::Integer=10, debug::Bool=true) - function format_output(output) - debug ? "Process output found:\n\"\"\"\n$(readstring(seekstart(out)))\n\"\"\"" : "" - end - out = IOBuffer() - with_fake_pty() do slave, master - p = spawn(detach(cmd), slave, slave, slave) - # Kill the process if it takes too long. Typically occurs when process is waiting for input - @async begin - sleep(timeout) - kill(p) - close(master) - end - try - for (challenge, response) in challenges - process_exited(p) && error("Too few prompts. $(format_output(out))") - - write(out, readuntil(master, challenge)) - if !isopen(master) - error("Could not locate challenge: \"$challenge\". $(format_output(out))") - end - write(master, response) - end - wait(p) - finally - kill(p) - end - # Determine if the process was explicitly killed - killed = process_exited(p) && (p.exitcode != 0 || p.termsignal != 0) - killed && error("Too many prompts. $(format_output(out))") - end - nothing -end - -# OffsetArrays (arrays with indexing that doesn't start at 1) - -# This test file is designed to exercise support for generic indexing, -# even though offset arrays aren't implemented in Base. - -module OAs - -using Base: Indices, IndexCartesian, IndexLinear, tail - -export OffsetArray - -struct OffsetArray{T,N,AA<:AbstractArray} <: AbstractArray{T,N} - parent::AA - offsets::NTuple{N,Int} -end -OffsetVector{T,AA<:AbstractArray} = OffsetArray{T,1,AA} - -OffsetArray{T,N}(A::AbstractArray{T,N}, offsets::NTuple{N,Int}) = OffsetArray{T,N,typeof(A)}(A, offsets) -OffsetArray{T,N}(A::AbstractArray{T,N}, offsets::Vararg{Int,N}) = OffsetArray(A, offsets) - -(::Type{OffsetArray{T,N}}){T,N}(inds::Indices{N}) = OffsetArray{T,N,Array{T,N}}(Array{T,N}(map(length, inds)), map(indsoffset, inds)) -(::Type{OffsetArray{T}}){T,N}(inds::Indices{N}) = OffsetArray{T,N}(inds) - -Base.IndexStyle{T<:OffsetArray}(::Type{T}) = Base.IndexStyle(parenttype(T)) -parenttype{T,N,AA}(::Type{OffsetArray{T,N,AA}}) = AA -parenttype(A::OffsetArray) = parenttype(typeof(A)) - -Base.parent(A::OffsetArray) = A.parent - -errmsg(A) = error("size not supported for arrays with indices $(indices(A)); see https://docs.julialang.org/en/latest/devdocs/offset-arrays/") -Base.size(A::OffsetArray) = errmsg(A) -Base.size(A::OffsetArray, d) = errmsg(A) -Base.eachindex(::IndexCartesian, A::OffsetArray) = CartesianRange(indices(A)) -Base.eachindex(::IndexLinear, A::OffsetVector) = indices(A, 1) - -# Implementations of indices and indices1. Since bounds-checking is -# performance-critical and relies on indices, these are usually worth -# optimizing thoroughly. -@inline Base.indices(A::OffsetArray, d) = 1 <= d <= length(A.offsets) ? indices(parent(A))[d] + A.offsets[d] : (1:1) -@inline Base.indices(A::OffsetArray) = _indices(indices(parent(A)), A.offsets) # would rather use ntuple, but see #15276 -@inline _indices(inds, offsets) = (inds[1]+offsets[1], _indices(tail(inds), tail(offsets))...) -_indices(::Tuple{}, ::Tuple{}) = () -Base.indices1{T}(A::OffsetArray{T,0}) = 1:1 # we only need to specialize this one - -function Base.similar(A::OffsetArray, T::Type, dims::Dims) - B = similar(parent(A), T, dims) -end -function Base.similar(A::AbstractArray, T::Type, inds::Tuple{UnitRange,Vararg{UnitRange}}) - B = similar(A, T, map(length, inds)) - OffsetArray(B, map(indsoffset, inds)) -end - -Base.similar(f::Union{Function,Type}, shape::Tuple{UnitRange,Vararg{UnitRange}}) = OffsetArray(f(map(length, shape)), map(indsoffset, shape)) - -Base.reshape(A::AbstractArray, inds::Tuple{UnitRange,Vararg{UnitRange}}) = OffsetArray(reshape(A, map(length, inds)), map(indsoffset, inds)) - -@inline function Base.getindex{T,N}(A::OffsetArray{T,N}, I::Vararg{Int,N}) - checkbounds(A, I...) - @inbounds ret = parent(A)[offset(A.offsets, I)...] - ret -end -# Vectors don't support one-based linear indexing; they always use the offsets -@inline function Base.getindex(A::OffsetVector, i::Int) - checkbounds(A, i) - @inbounds ret = parent(A)[offset(A.offsets, (i,))[1]] - ret -end -# But multidimensional arrays allow one-based linear indexing -@inline function Base.getindex(A::OffsetArray, i::Int) - checkbounds(A, i) - @inbounds ret = parent(A)[i] - ret -end -@inline function Base.setindex!{T,N}(A::OffsetArray{T,N}, val, I::Vararg{Int,N}) - checkbounds(A, I...) - @inbounds parent(A)[offset(A.offsets, I)...] = val - val -end -@inline function Base.setindex!(A::OffsetVector, val, i::Int) - checkbounds(A, i) - @inbounds parent(A)[offset(A.offsets, (i,))[1]] = val - val -end -@inline function Base.setindex!(A::OffsetArray, val, i::Int) - checkbounds(A, i) - @inbounds parent(A)[i] = val - val -end - -@inline function Base.deleteat!(A::OffsetArray, i::Int) - checkbounds(A, i) - @inbounds deleteat!(parent(A), offset(A.offsets, (i,))[1]) -end - -@inline function Base.deleteat!{T,N}(A::OffsetArray{T,N}, I::Vararg{Int, N}) - checkbounds(A, I...) - @inbounds deleteat!(parent(A), offset(A.offsets, I)...) -end - -@inline function Base.deleteat!(A::OffsetArray, i::UnitRange{Int}) - checkbounds(A, first(i)) - checkbounds(A, last(i)) - first_idx = offset(A.offsets, (first(i),))[1] - last_idx = offset(A.offsets, (last(i),))[1] - @inbounds deleteat!(parent(A), first_idx:last_idx) -end - -# Computing a shifted index (subtracting the offset) -offset{N}(offsets::NTuple{N,Int}, inds::NTuple{N,Int}) = _offset((), offsets, inds) -_offset(out, ::Tuple{}, ::Tuple{}) = out -@inline _offset(out, offsets, inds) = _offset((out..., inds[1]-offsets[1]), Base.tail(offsets), Base.tail(inds)) - -indsoffset(r::Range) = first(r) - 1 -indsoffset(i::Integer) = 0 - -end - -end diff --git a/julia-0.6.3/share/julia/test/abstractarray.jl b/julia-0.6.3/share/julia/test/abstractarray.jl deleted file mode 100644 index ac9353d..0000000 --- a/julia-0.6.3/share/julia/test/abstractarray.jl +++ /dev/null @@ -1,854 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -A = rand(5,4,3) -@testset "Bounds checking" begin - @test checkbounds(Bool, A, 1, 1, 1) == true - @test checkbounds(Bool, A, 5, 4, 3) == true - @test checkbounds(Bool, A, 0, 1, 1) == false - @test checkbounds(Bool, A, 1, 0, 1) == false - @test checkbounds(Bool, A, 1, 1, 0) == false - @test checkbounds(Bool, A, 6, 4, 3) == false - @test checkbounds(Bool, A, 5, 5, 3) == false - @test checkbounds(Bool, A, 5, 4, 4) == false - @test checkbounds(Bool, A, 1) == true # linear indexing - @test checkbounds(Bool, A, 60) == true - @test checkbounds(Bool, A, 61) == false - @test checkbounds(Bool, A, 2, 2, 2, 1) == true # extra indices - @test checkbounds(Bool, A, 2, 2, 2, 2) == false - @test checkbounds(Bool, A, 1, 1) == true # partial linear indexing (PLI) - # @test checkbounds(Bool, A, 1, 12) == false # PLI TODO: Re-enable after partial linear indexing deprecation - # @test checkbounds(Bool, A, 5, 12) == false # PLI TODO: Re-enable after partial linear indexing deprecation - @test checkbounds(Bool, A, 1, 13) == false # PLI - # @test checkbounds(Bool, A, 6, 12) == false # PLI TODO: Re-enable after partial linear indexing deprecation -end - -@testset "single CartesianIndex" begin - @test checkbounds(Bool, A, CartesianIndex((1, 1, 1))) == true - @test checkbounds(Bool, A, CartesianIndex((5, 4, 3))) == true - @test checkbounds(Bool, A, CartesianIndex((0, 1, 1))) == false - @test checkbounds(Bool, A, CartesianIndex((1, 0, 1))) == false - @test checkbounds(Bool, A, CartesianIndex((1, 1, 0))) == false - @test checkbounds(Bool, A, CartesianIndex((6, 4, 3))) == false - @test checkbounds(Bool, A, CartesianIndex((5, 5, 3))) == false - @test checkbounds(Bool, A, CartesianIndex((5, 4, 4))) == false - @test checkbounds(Bool, A, CartesianIndex((1,))) == true - # @test checkbounds(Bool, A, CartesianIndex((60,))) == false # TODO: Re-enable after partial linear indexing deprecation - @test checkbounds(Bool, A, CartesianIndex((61,))) == false - @test checkbounds(Bool, A, CartesianIndex((2, 2, 2, 1,))) == true - @test checkbounds(Bool, A, CartesianIndex((2, 2, 2, 2,))) == false - @test checkbounds(Bool, A, CartesianIndex((1, 1,))) == true - # @test checkbounds(Bool, A, CartesianIndex((1, 12,))) == false # TODO: Re-enable after partial linear indexing deprecation - # @test checkbounds(Bool, A, CartesianIndex((5, 12,))) == false # TODO: Re-enable after partial linear indexing deprecation - @test checkbounds(Bool, A, CartesianIndex((1, 13,))) == false - # @test checkbounds(Bool, A, CartesianIndex((6, 12,))) == false # TODO: Re-enable after partial linear indexing deprecation -end - -@testset "mix of CartesianIndex and Int" begin - @test checkbounds(Bool, A, CartesianIndex((1,)), 1, CartesianIndex((1,))) == true - @test checkbounds(Bool, A, CartesianIndex((5, 4)), 3) == true - @test checkbounds(Bool, A, CartesianIndex((0, 1)), 1) == false - @test checkbounds(Bool, A, 1, CartesianIndex((0, 1))) == false - @test checkbounds(Bool, A, 1, 1, CartesianIndex((0,))) == false - @test checkbounds(Bool, A, 6, CartesianIndex((4, 3))) == false - @test checkbounds(Bool, A, 5, CartesianIndex((5,)), 3) == false - @test checkbounds(Bool, A, CartesianIndex((5,)), CartesianIndex((4,)), CartesianIndex((4,))) == false -end - -@testset "vector indices" begin - @test checkbounds(Bool, A, 1:5, 1:4, 1:3) == true - @test checkbounds(Bool, A, 0:5, 1:4, 1:3) == false - @test checkbounds(Bool, A, 1:5, 0:4, 1:3) == false - @test checkbounds(Bool, A, 1:5, 1:4, 0:3) == false - @test checkbounds(Bool, A, 1:6, 1:4, 1:3) == false - @test checkbounds(Bool, A, 1:5, 1:5, 1:3) == false - @test checkbounds(Bool, A, 1:5, 1:4, 1:4) == false - @test checkbounds(Bool, A, 1:60) == true - @test checkbounds(Bool, A, 1:61) == false - @test checkbounds(Bool, A, 2, 2, 2, 1:1) == true # extra indices - @test checkbounds(Bool, A, 2, 2, 2, 1:2) == false - @test checkbounds(Bool, A, 1:5, 1:4) == true - # @test checkbounds(Bool, A, 1:5, 1:12) == false # TODO: Re-enable after partial linear indexing deprecation - @test checkbounds(Bool, A, 1:5, 1:13) == false - # @test checkbounds(Bool, A, 1:6, 1:12) == false # TODO: Re-enable after partial linear indexing deprecation -end - -@testset "logical" begin - @test checkbounds(Bool, A, trues(5), trues(4), trues(3)) == true - @test checkbounds(Bool, A, trues(6), trues(4), trues(3)) == false - @test checkbounds(Bool, A, trues(5), trues(5), trues(3)) == false - @test checkbounds(Bool, A, trues(5), trues(4), trues(4)) == false - @test checkbounds(Bool, A, trues(60)) == true - @test checkbounds(Bool, A, trues(61)) == false - @test checkbounds(Bool, A, 2, 2, 2, trues(1)) == true # extra indices - @test checkbounds(Bool, A, 2, 2, 2, trues(2)) == false - # @test checkbounds(Bool, A, trues(5), trues(12)) == false # TODO: Re-enable after partial linear indexing deprecation - @test checkbounds(Bool, A, trues(5), trues(13)) == false - # @test checkbounds(Bool, A, trues(6), trues(12)) == false # TODO: Re-enable after partial linear indexing deprecation - @test checkbounds(Bool, A, trues(5, 4, 3)) == true - @test checkbounds(Bool, A, trues(5, 4, 2)) == false - @test checkbounds(Bool, A, trues(5, 12)) == false - @test checkbounds(Bool, A, trues(1, 5), trues(1, 4, 1), trues(1, 1, 3)) == false - @test checkbounds(Bool, A, trues(1, 5), trues(1, 4, 1), trues(1, 1, 2)) == false - @test checkbounds(Bool, A, trues(1, 5), trues(1, 5, 1), trues(1, 1, 3)) == false - @test checkbounds(Bool, A, trues(1, 5), :, 2) == false -end - -@testset "array of CartesianIndex" begin - @test checkbounds(Bool, A, [CartesianIndex((1, 1, 1))]) == true - @test checkbounds(Bool, A, [CartesianIndex((5, 4, 3))]) == true - @test checkbounds(Bool, A, [CartesianIndex((0, 1, 1))]) == false - @test checkbounds(Bool, A, [CartesianIndex((1, 0, 1))]) == false - @test checkbounds(Bool, A, [CartesianIndex((1, 1, 0))]) == false - @test checkbounds(Bool, A, [CartesianIndex((6, 4, 3))]) == false - @test checkbounds(Bool, A, [CartesianIndex((5, 5, 3))]) == false - @test checkbounds(Bool, A, [CartesianIndex((5, 4, 4))]) == false - @test checkbounds(Bool, A, [CartesianIndex((1, 1))], 1) == true - @test checkbounds(Bool, A, [CartesianIndex((5, 4))], 3) == true - @test checkbounds(Bool, A, [CartesianIndex((0, 1))], 1) == false - @test checkbounds(Bool, A, [CartesianIndex((1, 0))], 1) == false - @test checkbounds(Bool, A, [CartesianIndex((1, 1))], 0) == false - @test checkbounds(Bool, A, [CartesianIndex((6, 4))], 3) == false - @test checkbounds(Bool, A, [CartesianIndex((5, 5))], 3) == false - @test checkbounds(Bool, A, [CartesianIndex((5, 4))], 4) == false -end - -@testset "sub2ind & ind2sub" begin - @testset "0-dimensional" begin - for i = 1:4 - @test sub2ind((), i) == i - end - @test sub2ind((), 2, 2) == 3 - @test ind2sub((), 1) == () - @test_throws BoundsError ind2sub((), 2) - end - - @testset "1-dimensional" begin - for i = 1:4 - @test sub2ind((3,), i) == i - @test ind2sub((3,), i) == (i,) - end - @test sub2ind((3,), 2, 2) == 5 - @test_throws MethodError ind2sub((3,), 2, 2) - # ambiguity btw cartesian indexing and linear indexing in 1d when - # indices may be nontraditional - @test_throws ArgumentError sub2ind((1:3,), 2) - @test_throws ArgumentError ind2sub((1:3,), 2) - end - - @testset "2-dimensional" begin - k = 0 - for j = 1:3, i = 1:4 - @test sub2ind((4,3), i, j) == (k+=1) - @test ind2sub((4,3), k) == (i,j) - @test sub2ind((1:4,1:3), i, j) == k - @test ind2sub((1:4,1:3), k) == (i,j) - @test sub2ind((0:3,3:5), i-1, j+2) == k - @test ind2sub((0:3,3:5), k) == (i-1, j+2) - end - @testset "Delete when partial linear indexing is deprecated (#14770)" begin - @test sub2ind((4,3), 7) == 7 - @test sub2ind((1:4,1:3), 7) == 7 - @test sub2ind((0:3,3:5), 7) == 8 - end - end - - @testset "3-dimensional" begin - l = 0 - for k = 1:2, j = 1:3, i = 1:4 - @test sub2ind((4,3,2), i, j, k) == (l+=1) - @test ind2sub((4,3,2), l) == (i,j,k) - @test sub2ind((1:4,1:3,1:2), i, j, k) == l - @test ind2sub((1:4,1:3,1:2), l) == (i,j,k) - @test sub2ind((0:3,3:5,-101:-100), i-1, j+2, k-102) == l - @test ind2sub((0:3,3:5,-101:-100), l) == (i-1, j+2, k-102) - end - - A = reshape(collect(1:9), (3,3)) - @test ind2sub(size(A), 6) == (3,2) - @test sub2ind(size(A), 3, 2) == 6 - @test ind2sub(A, 6) == (3,2) - @test sub2ind(A, 3, 2) == 6 - - @testset "PR #9256" begin - function pr9256() - m = [1 2 3; 4 5 6; 7 8 9] - ind2sub(m, 6) - end - @test pr9256() == (3,2) - end - end -end - -# token type on which to dispatch testing methods in order to avoid potential -# name conflicts elsewhere in the base test suite -mutable struct TestAbstractArray end - -## Tests for the abstract array interfaces with minimally defined array types - -# A custom linear fast array type with 24 elements that doesn't rely upon Array storage -mutable struct T24Linear{T,N,dims} <: AbstractArray{T,N} - v1::T; v2::T; v3::T; v4::T; v5::T; v6::T; v7::T; v8::T - v9::T; v10::T; v11::T; v12::T; v13::T; v14::T; v15::T; v16::T - v17::T; v18::T; v19::T; v20::T; v21::T; v22::T; v23::T; v24::T - T24Linear{T,N,d}() where {T,N,d} = - (prod(d) == 24 || throw(DimensionMismatch("T24Linear must have 24 elements")); new()) - function T24Linear{T,N,d}(v1,v2,v3,v4,v5,v6,v7,v8,v9,v10,v11,v12, - v13,v14,v15,v16,v17,v18,v19,v20,v21,v22,v23,v24) where {T,N,d} - prod(d) == 24 || throw(DimensionMismatch("T24Linear must have 24 elements")) - new(v1,v2,v3,v4,v5,v6,v7,v8,v9,v10,v11,v12,v13,v14,v15,v16,v17,v18,v19,v20,v21,v22,v23,v24) - end -end - -T24Linear(::Type{T}, dims::Int...) where T = T24Linear(T, dims) -T24Linear(::Type{T}, dims::NTuple{N,Int}) where {T,N} = T24Linear{T,N,dims}() - -Base.convert{T,N }(::Type{T24Linear }, X::AbstractArray{T,N}) = convert(T24Linear{T,N}, X) -Base.convert{T,N,_}(::Type{T24Linear{T }}, X::AbstractArray{_,N}) = convert(T24Linear{T,N}, X) -Base.convert{T,N }(::Type{T24Linear{T,N}}, X::AbstractArray ) = T24Linear{T,N,size(X)}(X...) - -Base.size{T,N,dims}(::T24Linear{T,N,dims}) = dims -import Base: IndexLinear -Base.IndexStyle{A<:T24Linear}(::Type{A}) = IndexLinear() -Base.getindex(A::T24Linear, i::Int) = getfield(A, i) -Base.setindex!{T}(A::T24Linear{T}, v, i::Int) = setfield!(A, i, convert(T, v)) - -# A custom linear slow sparse-like array that relies upon Dict for its storage -struct TSlow{T,N} <: AbstractArray{T,N} - data::Dict{NTuple{N,Int}, T} - dims::NTuple{N,Int} -end -TSlow{T}(::Type{T}, dims::Int...) = TSlow(T, dims) -TSlow{T,N}(::Type{T}, dims::NTuple{N,Int}) = TSlow{T,N}(Dict{NTuple{N,Int}, T}(), dims) - -Base.convert{T,N }(::Type{TSlow{T,N}}, X::TSlow{T,N}) = X -Base.convert{T,N }(::Type{TSlow }, X::AbstractArray{T,N}) = convert(TSlow{T,N}, X) -Base.convert{T,N,_}(::Type{TSlow{T }}, X::AbstractArray{_,N}) = convert(TSlow{T,N}, X) -Base.convert{T,N }(::Type{TSlow{T,N}}, X::AbstractArray ) = begin - A = TSlow(T, size(X)) - for I in CartesianRange(size(X)) - A[I.I...] = X[I.I...] - end - A -end - -Base.size(A::TSlow) = A.dims -Base.similar{T}(A::TSlow, ::Type{T}, dims::Dims) = TSlow(T, dims) -import Base: IndexCartesian -Base.IndexStyle{A<:TSlow}(::Type{A}) = IndexCartesian() -# Until #11242 is merged, we need to define each dimension independently -Base.getindex{T}(A::TSlow{T,0}) = get(A.data, (), zero(T)) -Base.getindex{T}(A::TSlow{T,1}, i1::Int) = get(A.data, (i1,), zero(T)) -Base.getindex{T}(A::TSlow{T,2}, i1::Int, i2::Int) = get(A.data, (i1,i2), zero(T)) -Base.getindex{T}(A::TSlow{T,3}, i1::Int, i2::Int, i3::Int) = - get(A.data, (i1,i2,i3), zero(T)) -Base.getindex{T}(A::TSlow{T,4}, i1::Int, i2::Int, i3::Int, i4::Int) = - get(A.data, (i1,i2,i3,i4), zero(T)) -Base.getindex{T}(A::TSlow{T,5}, i1::Int, i2::Int, i3::Int, i4::Int, i5::Int) = - get(A.data, (i1,i2,i3,i4,i5), zero(T)) - -Base.setindex!{T}(A::TSlow{T,0}, v) = (A.data[()] = v) -Base.setindex!{T}(A::TSlow{T,1}, v, i1::Int) = (A.data[(i1,)] = v) -Base.setindex!{T}(A::TSlow{T,2}, v, i1::Int, i2::Int) = (A.data[(i1,i2)] = v) -Base.setindex!{T}(A::TSlow{T,3}, v, i1::Int, i2::Int, i3::Int) = - (A.data[(i1,i2,i3)] = v) -Base.setindex!{T}(A::TSlow{T,4}, v, i1::Int, i2::Int, i3::Int, i4::Int) = - (A.data[(i1,i2,i3,i4)] = v) -Base.setindex!{T}(A::TSlow{T,5}, v, i1::Int, i2::Int, i3::Int, i4::Int, i5::Int) = - (A.data[(i1,i2,i3,i4,i5)] = v) - -const can_inline = Base.JLOptions().can_inline != 0 -function test_scalar_indexing{T}(::Type{T}, shape, ::Type{TestAbstractArray}) - N = prod(shape) - A = reshape(collect(1:N), shape) - B = T(A) - @test A == B - # Test indexing up to 5 dimensions - i=0 - for i5 = 1:size(B, 5) - for i4 = 1:size(B, 4) - for i3 = 1:size(B, 3) - for i2 = 1:size(B, 2) - for i1 = 1:size(B, 1) - i += 1 - @test A[i1,i2,i3,i4,i5] == B[i1,i2,i3,i4,i5] == i - @test A[i1,i2,i3,i4,i5] == - Base.unsafe_getindex(B, i1, i2, i3, i4, i5) == i - end - end - end - end - end - # Test linear indexing and partial linear indexing - i=0 - for i1 = 1:length(B) - i += 1 - @test A[i1] == B[i1] == i - end - i=0 - for i2 = 1:size(B, 2) - for i1 = 1:size(B, 1) - i += 1 - @test A[i1,i2] == B[i1,i2] == i - end - end - @test A == B - i=0 - for i3 = 1:size(B, 3) - for i2 = 1:size(B, 2) - for i1 = 1:size(B, 1) - i += 1 - @test A[i1,i2,i3] == B[i1,i2,i3] == i - end - end - end - # Test zero-dimensional accesses - @test A[] == B[] == A[1] == B[1] == 1 - # Test multidimensional scalar indexed assignment - C = T(Int, shape) - D1 = T(Int, shape) - D2 = T(Int, shape) - D3 = T(Int, shape) - i=0 - for i5 = 1:size(B, 5) - for i4 = 1:size(B, 4) - for i3 = 1:size(B, 3) - for i2 = 1:size(B, 2) - for i1 = 1:size(B, 1) - i += 1 - C[i1,i2,i3,i4,i5] = i - # test general unsafe_setindex! - Base.unsafe_setindex!(D1, i, i1,i2,i3,i4,i5) - # test for dropping trailing dims - Base.unsafe_setindex!(D2, i, i1,i2,i3,i4,i5, 1, 1, 1) - # test for expanding index argument to appropriate dims - Base.unsafe_setindex!(D3, i, i1,i2,i3,i4) - end - end - end - end - end - @test D1 == D2 == C == B == A - @test D3[:, :, :, :, 1] == D2[:, :, :, :, 1] - # Test linear indexing and partial linear indexing - C = T(Int, shape) - fill!(C, 0) - @test C != B && C != A - i=0 - for i1 = 1:length(C) - i += 1 - C[i1] = i - end - @test C == B == A - C = T(Int, shape) - i=0 - C2 = reshape(C, Val{2}) - for i2 = 1:size(C2, 2) - for i1 = 1:size(C2, 1) - i += 1 - C2[i1,i2] = i - end - end - @test C == B == A - C = T(Int, shape) - i=0 - C3 = reshape(C, Val{3}) - for i3 = 1:size(C3, 3) - for i2 = 1:size(C3, 2) - for i1 = 1:size(C3, 1) - i += 1 - C3[i1,i2,i3] = i - end - end - end - @test C == B == A - # Test zero-dimensional setindex - A[] = 0; B[] = 0 - @test A[] == B[] == 0 - @test A == B -end - -function test_vector_indexing{T}(::Type{T}, shape, ::Type{TestAbstractArray}) - @testset "test_vector_indexing{$(T)}" begin - N = prod(shape) - A = reshape(collect(1:N), shape) - B = T(A) - idxs = rand(1:N, 3, 3, 3) - @test B[idxs] == A[idxs] == idxs - @test B[vec(idxs)] == A[vec(idxs)] == vec(idxs) - @test B[:] == A[:] == collect(1:N) - @test B[1:end] == A[1:end] == collect(1:N) - # @test B[:,:] == A[:,:] == reshape(1:N, shape[1], prod(shape[2:end])) # TODO: Re-enable after partial linear indexing deprecation - # @test B[1:end,1:end] == A[1:end,1:end] == reshape(1:N, shape[1], prod(shape[2:end])) # TODO: Re-enable after partial linear indexing deprecation - - @testset "Test with containers that aren't Int[]" begin - @test B[[]] == A[[]] == [] - @test B[convert(Array{Any}, idxs)] == A[convert(Array{Any}, idxs)] == idxs - end - - idx1 = rand(1:size(A, 1), 3) - idx2 = rand(1:size(A, 2), 4, 5) - @testset "Test adding dimensions with matrices" begin - @test B[idx1, idx2] == A[idx1, idx2] == reshape(A[idx1, vec(idx2)], 3, 4, 5) == reshape(B[idx1, vec(idx2)], 3, 4, 5) - @test B[1, idx2] == A[1, idx2] == reshape(A[1, vec(idx2)], 4, 5) == reshape(B[1, vec(idx2)], 4, 5) - end - # test removing dimensions with 0-d arrays - @testset "test removing dimensions with 0-d arrays" begin - idx0 = reshape([rand(1:size(A, 1))]) - @test B[idx0, idx2] == A[idx0, idx2] == reshape(A[idx0[], vec(idx2)], 4, 5) == reshape(B[idx0[], vec(idx2)], 4, 5) - # @test B[reshape([end]), reshape([end])] == A[reshape([end]), reshape([end])] == reshape([A[end,end]]) == reshape([B[end,end]]) # TODO: Re-enable after partial linear indexing deprecation - end - - mask = bitrand(shape) - @testset "test logical indexing" begin - @test B[mask] == A[mask] == B[find(mask)] == A[find(mask)] == find(mask) - @test B[vec(mask)] == A[vec(mask)] == find(mask) - mask1 = bitrand(size(A, 1)) - mask2 = bitrand(size(A, 2)) - @test B[mask1, mask2] == A[mask1, mask2] == B[find(mask1), find(mask2)] - @test B[mask1, 1] == A[mask1, 1] == find(mask1) - end - end -end - -function test_primitives{T}(::Type{T}, shape, ::Type{TestAbstractArray}) - N = prod(shape) - A = reshape(collect(1:N), shape) - B = T(A) - - # last(a) - @test last(B) == B[length(B)] - - # strides(a::AbstractArray) - @inferred strides(B) - strides_B = strides(B) - for (i, _stride) in enumerate(collect(strides_B)) - @test _stride == stride(B, i) - end - - # isassigned(a::AbstractArray, i::Int...) - j = rand(1:length(B)) - @test isassigned(B, j) == true - if T == T24Linear - @test isassigned(B, length(B) + 1) == false - end - - # reshape(a::AbstractArray, dims::Dims) - @test_throws DimensionMismatch reshape(B, (0, 1)) - - # copy!(dest::AbstractArray, src::AbstractArray) - @test_throws BoundsError copy!(Array{Int}(10), [1:11...]) - - # convert{T, N}(::Type{Array}, A::AbstractArray{T, N}) - X = [1:10...] - Y = [1 2; 3 4] - @test convert(Array, X) == X - @test convert(Array, Y) == Y - - # convert{T}(::Type{Vector}, A::AbstractVector{T}) - @test convert(Vector, X) == X - @test convert(Vector, view(X, 2:4)) == [2,3,4] - @test_throws MethodError convert(Vector, Y) - - # convert{T}(::Type{Matrix}, A::AbstractMatrix{T}) - @test convert(Matrix, Y) == Y - @test convert(Matrix, view(Y, 1:2, 1:2)) == Y - @test_throws MethodError convert(Matrix, X) -end - -mutable struct TestThrowNoGetindex{T} <: AbstractVector{T} end -@testset "ErrorException if getindex is not defined" begin - Base.length(::TestThrowNoGetindex) = 2 - Base.size(::TestThrowNoGetindex) = (2,) - @test_throws ErrorException isassigned(TestThrowNoGetindex{Float64}(), 1) -end - -function test_in_bounds(::Type{TestAbstractArray}) - n = rand(2:5) - sz = rand(2:5, n) - len = prod(sz) - A = zeros(sz...) - for i in 1:len - @test checkbounds(Bool, A, i) == true - end - @test checkbounds(Bool, A, len + 1) == false -end - -mutable struct UnimplementedFastArray{T, N} <: AbstractArray{T, N} end -Base.IndexStyle(::UnimplementedFastArray) = Base.IndexLinear() - -mutable struct UnimplementedSlowArray{T, N} <: AbstractArray{T, N} end -Base.IndexStyle(::UnimplementedSlowArray) = Base.IndexCartesian() - -mutable struct UnimplementedArray{T, N} <: AbstractArray{T, N} end - -function test_getindex_internals{T}(::Type{T}, shape, ::Type{TestAbstractArray}) - N = prod(shape) - A = reshape(collect(1:N), shape) - B = T(A) - - @test getindex(A) == 1 - @test getindex(B) == 1 - @test Base.unsafe_getindex(A) == 1 - @test Base.unsafe_getindex(B) == 1 -end - -function test_getindex_internals(::Type{TestAbstractArray}) - U = UnimplementedFastArray{Int, 2}() - V = UnimplementedSlowArray{Int, 2}() - @test_throws ErrorException getindex(U, 1) - @test_throws ErrorException Base.unsafe_getindex(U, 1) - @test_throws ErrorException getindex(V, 1, 1) - @test_throws ErrorException Base.unsafe_getindex(V, 1, 1) -end - -function test_setindex!_internals{T}(::Type{T}, shape, ::Type{TestAbstractArray}) - N = prod(shape) - A = reshape(collect(1:N), shape) - B = T(A) - - Base.unsafe_setindex!(B, 1) - @test B[1] == 1 -end - -function test_setindex!_internals(::Type{TestAbstractArray}) - U = UnimplementedFastArray{Int, 2}() - V = UnimplementedSlowArray{Int, 2}() - @test_throws ErrorException setindex!(U, 0, 1) - @test_throws ErrorException Base.unsafe_setindex!(U, 0, 1) - @test_throws ErrorException setindex!(V, 0, 1, 1) - @test_throws ErrorException Base.unsafe_setindex!(V, 0, 1, 1) -end - -function test_get(::Type{TestAbstractArray}) - A = T24Linear([1:24...]) - B = TSlow([1:24...]) - - @test get(A, (), 0) == Int[] - @test get(B, (), 0) == TSlow(Int, 0) -end - -function test_cat(::Type{TestAbstractArray}) - A = T24Linear([1:24...]) - b_int = reshape([1:27...], 3, 3, 3) - b_float = reshape(Float64[1:27...], 3, 3, 3) - b2hcat = Array{Float64}(3, 6, 3) - b1 = reshape([1:9...], 3, 3) - b2 = reshape([10:18...], 3, 3) - b3 = reshape([19:27...], 3, 3) - b2hcat[:, :, 1] = hcat(b1, b1) - b2hcat[:, :, 2] = hcat(b2, b2) - b2hcat[:, :, 3] = hcat(b3, b3) - b3hcat = Array{Float64}(3, 9, 3) - b3hcat[:, :, 1] = hcat(b1, b1, b1) - b3hcat[:, :, 2] = hcat(b2, b2, b2) - b3hcat[:, :, 3] = hcat(b3, b3, b3) - B = TSlow(b_int) - B1 = TSlow([1:24...]) - B2 = TSlow([1:25...]) - C1 = TSlow([1 2; 3 4]) - C2 = TSlow([1 2 3; 4 5 6]) - C3 = TSlow([1 2; 3 4; 5 6]) - D = [1:24...] - i = rand(1:10) - - @test cat(i) == Any[] - @test vcat() == Any[] - @test hcat() == Any[] - @test hcat(1, 1.0, 3, 3.0) == [1.0 1.0 3.0 3.0] - @test_throws ArgumentError hcat(B1, B2) - @test_throws ArgumentError vcat(C1, C2) - - @test vcat(B) == B - @test hcat(B) == B - @test Base.typed_hcat(Float64, B) == TSlow(b_float) - @test Base.typed_hcat(Float64, B, B) == TSlow(b2hcat) - @test Base.typed_hcat(Float64, B, B, B) == TSlow(b3hcat) - - @test vcat(B1, B2) == TSlow(vcat([1:24...], [1:25...])) - @test hcat(C1, C2) == TSlow([1 2 1 2 3; 3 4 4 5 6]) - @test hcat(C1, C2, C1) == TSlow([1 2 1 2 3 1 2; 3 4 4 5 6 3 4]) - - # hvcat - for nbc in (1, 2, 3, 4, 5, 6) - @test hvcat(nbc, 1:120...) == - transpose(reshape([1:120...], nbc, round(Int, 120 / nbc))) - end - - @test_throws ArgumentError hvcat(7, 1:20...) - @test_throws ArgumentError hvcat((2), C1, C3) - @test_throws ArgumentError hvcat((1), C1, C2) - @test_throws ArgumentError hvcat((1), C2, C3) - - tup = tuple(rand(1:10, i)...) - @test hvcat(tup) == [] - - # check for shape mismatch - @test_throws ArgumentError hvcat((2, 2), 1, 2, 3, 4, 5) - @test_throws ArgumentError Base.typed_hvcat(Int, (2, 2), 1, 2, 3, 4, 5) - # check for # of columns mismatch b/w rows - @test_throws ArgumentError hvcat((3, 2), 1, 2, 3, 4, 5, 6) - @test_throws ArgumentError Base.typed_hvcat(Int, (3, 2), 1, 2, 3, 4, 5, 6) - - # 18395 - @test isa(Any["a" 5; 2//3 1.0][2,1], Rational{Int}) - - # 13665, 19038 - @test @inferred(hcat([1.0 2.0], 3))::Array{Float64,2} == [1.0 2.0 3.0] - @test @inferred(vcat([1.0, 2.0], 3))::Array{Float64,1} == [1.0, 2.0, 3.0] - - @test @inferred(vcat(["a"], "b"))::Vector{String} == ["a", "b"] - @test @inferred(vcat((1,), (2.0,)))::Vector{Tuple{Real}} == [(1,), (2.0,)] -end - -function test_ind2sub(::Type{TestAbstractArray}) - n = rand(2:5) - dims = tuple(rand(1:5, n)...) - len = prod(dims) - A = reshape(collect(1:len), dims...) - I = ind2sub(dims, [1:len...]) - for i in 1:len - idx = [ I[j][i] for j in 1:n ] - @test A[idx...] == A[i] - end -end - -# A custom linear slow array that insists upon Cartesian indexing -mutable struct TSlowNIndexes{T,N} <: AbstractArray{T,N} - data::Array{T,N} -end -Base.IndexStyle{A<:TSlowNIndexes}(::Type{A}) = Base.IndexCartesian() -Base.size(A::TSlowNIndexes) = size(A.data) -Base.getindex(A::TSlowNIndexes, index::Int...) = error("Must use $(ndims(A)) indexes") -Base.getindex{T}(A::TSlowNIndexes{T,2}, i::Int, j::Int) = A.data[i,j] - - -mutable struct GenericIterator{N} end -Base.start{N}(::GenericIterator{N}) = 1 -Base.next{N}(::GenericIterator{N}, i) = (i, i + 1) -Base.done{N}(::GenericIterator{N}, i) = i > N ? true : false -Base.iteratorsize{N}(::Type{GenericIterator{N}}) = Base.SizeUnknown() - -function test_map(::Type{TestAbstractArray}) - empty_pool = WorkerPool([myid()]) - pmap_fallback = (f, c...) -> pmap(empty_pool, f, c...) - - for mapf in [map, asyncmap, pmap_fallback] - for typ in (Float16, Float32, Float64, - Int8, Int16, Int32, Int64, Int128, - UInt8, UInt16, UInt32, UInt64, UInt128), - arg_typ in (Integer, - Signed, - Unsigned) - X = typ[1:10...] - _typ = typeof(arg_typ(one(typ))) - @test mapf(arg_typ, X) == _typ[1:10...] - end - - # generic map - f(x) = x + 1 - I = GenericIterator{10}() - @test mapf(f, I) == Any[2:11...] - - # AbstractArray map for 2 arg case - f(x, y) = x + y - B = Float64[1:10...] - C = Float64[1:10...] - @test mapf(f, convert(Vector{Int},B), C) == Float64[ 2 * i for i in 1:10 ] - @test mapf(f, Int[], Float64[]) == Union{}[] - # map with different result types - let m = mapf(x->x+1, Number[1, 2.0]) - # FIXME why is this different for asyncmap? - @test mapf !== map || isa(m, Vector{Real}) - @test m == Real[2, 3.0] - end - - # AbstractArray map for N-arg case - A = Array{Int}(10) - f(x, y, z) = x + y + z - D = Float64[1:10...] - - @test map!(f, A, B, C, D) == Int[ 3 * i for i in 1:10 ] - @test mapf(f, B, C, D) == Float64[ 3 * i for i in 1:10 ] - @test mapf(f, Int[], Int[], Complex{Int}[]) == Union{}[] - end - - # In-place map - A = Float64[1:10...] - map!(x -> x*x, A, A) - @test A == map(x -> x*x, Float64[1:10...]) - B = Float64[1:10...] - Base.asyncmap!(x->x*x, B, B) - @test A == B - - # Map to destination collection - map!((x,y,z)->x*y*z, A, Float64[1:10...], Float64[1:10...], Float64[1:10...]) - @test A == map(x->x*x*x, Float64[1:10...]) - C = Base.asyncmap!((x,y,z)->x*y*z, B, Float64[1:10...], Float64[1:10...], Float64[1:10...]) - @test A == B - @test B === C -end - -@testset "issue #15689, mapping an abstract type" begin - @test isa(map(Set, Array[[1,2],[3,4]]), Vector{Set{Int}}) -end - -@testset "mapping over scalars and empty arguments:" begin - @test map(sin, 1) === sin(1) - @test map(()->1234) === 1234 -end - -function test_UInt_indexing(::Type{TestAbstractArray}) - A = [1:100...] - _A = Expr(:quote, A) - for i in 1:100 - _i8 = convert(UInt8, i) - _i16 = convert(UInt16, i) - _i32 = convert(UInt32, i) - for _i in (_i8, _i16, _i32) - @eval begin - @test $_A[$_i] == $i - end - end - end -end - -# Issue 13315 -function test_13315(::Type{TestAbstractArray}) - U = UInt(1):UInt(2) - @test [U;[U;]] == [UInt(1), UInt(2), UInt(1), UInt(2)] -end - -# checksquare -function test_checksquare() - @test LinAlg.checksquare(zeros(2,2)) == 2 - @test LinAlg.checksquare(zeros(2,2),zeros(3,3)) == [2,3] - @test_throws DimensionMismatch LinAlg.checksquare(zeros(2,3)) -end - -#----- run tests -------------------------------------------------------------# - -@testset for T in (T24Linear, TSlow), shape in ((24,), (2, 12), (2,3,4), (1,2,3,4), (4,3,2,1)) - test_scalar_indexing(T, shape, TestAbstractArray) - test_vector_indexing(T, shape, TestAbstractArray) - test_primitives(T, shape, TestAbstractArray) - test_getindex_internals(T, shape, TestAbstractArray) - test_setindex!_internals(T, shape, TestAbstractArray) -end -test_in_bounds(TestAbstractArray) -test_getindex_internals(TestAbstractArray) -test_setindex!_internals(TestAbstractArray) -test_get(TestAbstractArray) -test_cat(TestAbstractArray) -test_ind2sub(TestAbstractArray) -test_map(TestAbstractArray) -test_UInt_indexing(TestAbstractArray) -test_13315(TestAbstractArray) -test_checksquare() - -A = TSlowNIndexes(rand(2,2)) -@test_throws ErrorException A[1] -@test A[1,1] == A.data[1] -@test first(A) == A.data[1] - -@testset "#16381" begin - @inferred size(rand(3,2,1), 2, 1) - @inferred size(rand(3,2,1), 2, 1, 3) - - @test @inferred(indices(rand(3,2))) == (1:3,1:2) - @test @inferred(indices(rand(3,2,1))) == (1:3,1:2,1:1) - @test @inferred(indices(rand(3,2), 1)) == 1:3 - @test @inferred(indices(rand(3,2), 2)) == 1:2 - @test @inferred(indices(rand(3,2), 3)) == 1:1 -end - -@testset "#17088" begin - n = 10 - M = rand(n, n) - @testset "vector of vectors" begin - v = [[M]; [M]] # using vcat - @test size(v) == (2,) - @test !issparse(v) - end - @testset "matrix of vectors" begin - m1 = [[M] [M]] # using hcat - m2 = [[M] [M];] # using hvcat - @test m1 == m2 - @test size(m1) == (1,2) - @test !issparse(m1) - @test !issparse(m2) - end -end - -@testset "isinteger and isreal" begin - @test all(isinteger, Diagonal(rand(1:5,5))) - @test isreal(Diagonal(rand(5))) -end - -@testset "unary ops" begin - let A = Diagonal(rand(1:5,5)) - @test +(A) == A - @test *(A) == A - end -end - -@testset "flipdim on empty" begin - @test flipdim(Diagonal([]),1) == Diagonal([]) -end - -@testset "ndims and friends" begin - @test ndims(Diagonal(rand(1:5,5))) == 2 - @test ndims(Diagonal{Float64}) == 2 - @test Base.elsize(Diagonal(rand(1:5,5))) == sizeof(Int) -end - -@testset "Issue #17811" begin - A17811 = Integer[] - I = [abs(x) for x in A17811] - @test isa(I, Array{Any,1}) - push!(I, 1) - @test I == Any[1] - @test isa(map(abs, A17811), Array{Any,1}) -end - -@testset "copymutable for itrs" begin - @test Base.copymutable((1,2,3)) == [1,2,3] -end - -@testset "sub2ind for empty tuple" begin - @test sub2ind(()) == 1 -end - -@testset "to_shape" begin - @test Base.to_shape(()) === () - @test Base.to_shape(1) === 1 -end - -@testset "issue #19267" begin - @test ndims((1:3)[:]) == 1 - @test ndims((1:3)[:,:]) == 2 - @test ndims((1:3)[:,[1],:]) == 3 - @test ndims((1:3)[:,[1],:,[1]]) == 4 - @test ndims((1:3)[:,[1],1:1,:]) == 4 - @test ndims((1:3)[:,:,1:1,:]) == 4 - @test ndims((1:3)[:,:,1:1]) == 3 - @test ndims((1:3)[:,:,1:1,:,:,[1]]) == 6 -end - -@testset "dispatch loop introduced in #19305" begin - @test [(1:2) zeros(2,2); ones(3,3)] == [[1,2] zeros(2,2); ones(3,3)] == [reshape([1,2],2,1) zeros(2,2); ones(3,3)] -end - -@testset "checkbounds_indices method ambiguities #20989" begin - @test Base.checkbounds_indices(Bool, (1:1,), ([CartesianIndex(1)],)) -end - -@testset "zero-dimensional copy" begin - Z = Array{Int}(); Z[] = 17 - @test Z == collect(Z) == copy(Z) -end - -@testset "issue #25770" begin - @test vcat(1:3, fill(1, (2,1))) == vcat([1:3;], fill(1, (2,1))) == reshape([1,2,3,1,1], 5,1) - @test hcat(1:2, fill(1, (2,1))) == hcat([1:2;], fill(1, (2,1))) == reshape([1,2,1,1],2,2) - @test [(1:3) (4:6); fill(1, (3,2))] == reshape([1,2,3,1,1,1,4,5,6,1,1,1], 6,2) -end diff --git a/julia-0.6.3/share/julia/test/ambiguous.jl b/julia-0.6.3/share/julia/test/ambiguous.jl deleted file mode 100644 index 32139c4..0000000 --- a/julia-0.6.3/share/julia/test/ambiguous.jl +++ /dev/null @@ -1,238 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -# DO NOT ALTER ORDER OR SPACING OF METHODS BELOW -const lineoffset = @__LINE__ + 0 # XXX: __LINE__ at the end of a line is off-by-one -ambig(x, y) = 1 -ambig(x::Integer, y) = 2 -ambig(x, y::Integer) = 3 -ambig(x::Int, y::Int) = 4 -ambig(x::Number, y) = 5 -# END OF LINE NUMBER SENSITIVITY - -# For curmod_* -include("testenv.jl") - -ambigs = Any[[], [3], [2,5], [], [3]] - -mt = methods(ambig) - -getline(m::Method) = m.line - lineoffset - -for m in mt - ln = getline(m) - atarget = ambigs[ln] - if isempty(atarget) - @test m.ambig === nothing - else - aln = Int[getline(a) for a in m.ambig] - @test sort(aln) == atarget - end -end - -@test length(methods(ambig)) == 5 -@test length(Base.methods_including_ambiguous(ambig, Tuple)) == 5 - -@test length(methods(ambig, (Int, Int))) == 1 -@test length(methods(ambig, (UInt8, Int))) == 0 -@test length(Base.methods_including_ambiguous(ambig, (UInt8, Int))) == 2 - -@test ambig("hi", "there") == 1 -@test ambig(3.1, 3.2) == 5 -@test ambig(3, 4) == 4 -@test_throws MethodError ambig(0x03, 4) -@test_throws MethodError ambig(0x03, 4) # test that not inserted into cache - -# Ensure it still works with potential inlining -callambig(x, y) = ambig(x, y) -@test_throws MethodError callambig(0x03, 4) - -# Printing ambiguity errors -let err = try - ambig(0x03, 4) - catch _e_ - _e_ - end - io = IOBuffer() - Base.showerror(io, err) - lines = split(String(take!(io)), '\n') - ambig_checkline(str) = startswith(str, " ambig(x, y::Integer) in $curmod_str at") || - startswith(str, " ambig(x::Integer, y) in $curmod_str at") - @test ambig_checkline(lines[2]) - @test ambig_checkline(lines[3]) - @test lines[4] == "Possible fix, define" - @test lines[5] == " ambig(::Integer, ::Integer)" -end - -## Other ways of accessing functions -# Test that non-ambiguous cases work -io = IOBuffer() -@test precompile(ambig, (Int, Int)) == true -cfunction(ambig, Int, (Int, Int)) -@test length(code_lowered(ambig, (Int, Int))) == 1 -@test length(code_typed(ambig, (Int, Int))) == 1 -code_llvm(io, ambig, (Int, Int)) -code_native(io, ambig, (Int, Int)) - -# Test that ambiguous cases fail appropriately -@test precompile(ambig, (UInt8, Int)) == false -cfunction(ambig, Int, (UInt8, Int)) # test for a crash (doesn't throw an error) -@test_throws ErrorException which(ambig, (UInt8, Int)) -@test_throws ErrorException code_llvm(io, ambig, (UInt8, Int)) -@test_throws ErrorException code_native(io, ambig, (UInt8, Int)) - -# Method overwriting doesn't destroy ambiguities -@test_throws MethodError ambig(2, 0x03) -ambig(x, y::Integer) = 3 -@test_throws MethodError ambig(2, 0x03) - -# Automatic detection of ambiguities -module Ambig1 -ambig(x, y) = 1 -ambig(x::Integer, y) = 2 -ambig(x, y::Integer) = 3 -end - -ambs = detect_ambiguities(Ambig1) -@test length(ambs) == 1 - -module Ambig2 -ambig(x, y) = 1 -ambig(x::Integer, y) = 2 -ambig(x, y::Integer) = 3 -ambig(x::Number, y) = 4 -end - -ambs = detect_ambiguities(Ambig2) -@test length(ambs) == 2 - -module Ambig3 -ambig(x, y) = 1 -ambig(x::Integer, y) = 2 -ambig(x, y::Integer) = 3 -ambig(x::Int, y::Int) = 4 -end - -ambs = detect_ambiguities(Ambig3) -@test length(ambs) == 1 - -module Ambig4 -ambig(x, y) = 1 -ambig(x::Int, y) = 2 -ambig(x, y::Int) = 3 -ambig(x::Int, y::Int) = 4 -end -ambs = detect_ambiguities(Ambig4) -@test length(ambs) == 0 - -module Ambig5 -ambig(x::Int8, y) = 1 -ambig(x::Integer, y) = 2 -ambig(x, y::Int) = 3 -end - -ambs = detect_ambiguities(Ambig5) -@test length(ambs) == 2 - -# Test that Core and Base are free of ambiguities -# not using isempty so this prints more information when it fails -@test detect_ambiguities(Core, Base; imported=true, ambiguous_bottom=false) == [] -# some ambiguities involving Union{} type parameters are expected, but not required -@test !isempty(detect_ambiguities(Core, Base; imported=true, ambiguous_bottom=true)) - -amb_1(::Int8, ::Int) = 1 -amb_1(::Integer, x) = 2 -amb_1(x, ::Int) = 3 -# if there is an ambiguity with some methods and not others, `methods` -# should return just the non-ambiguous ones, i.e. the ones that could actually -# be called. -@test length(methods(amb_1, Tuple{Integer, Int})) == 1 - -amb_2(::Int, y) = 1 -amb_2(x, ::Int) = 2 -amb_2(::Int8, y) = 3 -@test length(methods(amb_2)) == 3 # make sure no duplicates - -amb_3(::Int8, ::Int8) = 1 -amb_3(::Int16, ::Int16) = 2 -amb_3(::Integer, ::Integer) = 3 -amb_3(::Integer, x) = 4 -amb_3(x, ::Integer) = 5 -# ambiguous definitions exist, but are covered by multiple more specific definitions -let ms = methods(amb_3).ms - @test !Base.isambiguous(ms[4], ms[5]) -end - -amb_4(::Int8, ::Int8) = 1 -amb_4(::Int16, ::Int16) = 2 -amb_4(::Integer, x) = 4 -amb_4(x, ::Integer) = 5 -# as above, but without sufficient definition coverage -let ms = methods(amb_4).ms - @test Base.isambiguous(ms[3], ms[4]) -end - -g16493{T<:Number}(x::T, y::Integer) = 0 -g16493{T}(x::Complex{T}, y) = 1 -let ms = methods(g16493, (Complex, Any)) - @test length(ms) == 1 - @test first(ms).sig == (Tuple{typeof(g16493), Complex{T}, Any} where T) -end - -# issue #17350 -module Ambig6 -struct ScaleMinMax{To,From} end -map1{To<:Union{Float32,Float64},From<:Real}(mapi::ScaleMinMax{To,From}, val::From) = 1 -map1{To<:Union{Float32,Float64},From<:Real}(mapi::ScaleMinMax{To,From}, val::Union{Real,Complex}) = 2 -end - -@test isempty(detect_ambiguities(Ambig6)) - -module Ambig7 -struct T end -(::T)(x::Int8, y) = 1 -(::T)(x, y::Int8) = 2 -end -@test length(detect_ambiguities(Ambig7)) == 1 - -module Ambig17648 -struct MyArray{T,N} <: AbstractArray{T,N} - data::Array{T,N} -end - -foo{T,N}(::Type{Array{T,N}}, A::MyArray{T,N}) = A.data -foo{T<:AbstractFloat,N}(::Type{Array{T,N}}, A::MyArray{T,N}) = A.data -foo{S<:AbstractFloat,N,T<:AbstractFloat}(::Type{Array{S,N}}, A::AbstractArray{T,N}) = copy!(Array{S}(size(A)), A) -foo{S<:AbstractFloat,N,T<:AbstractFloat}(::Type{Array{S,N}}, A::MyArray{T,N}) = copy!(Array{S}(size(A)), A.data) -end - -@test isempty(detect_ambiguities(Ambig17648)) - -module Ambig8 -using Base: DimsInteger, Indices -g18307{T<:Integer}(::Union{Indices,Dims}, I::AbstractVector{T}...) = 1 -g18307(::DimsInteger) = 2 -g18307(::DimsInteger, I::Integer...) = 3 -end -try - # want this to be a test_throws MethodError, but currently it's not (see #18307) - Ambig8.g18307((1,)) -catch err - if isa(err, MethodError) - error("Test correctly returned a MethodError, please change to @test_throws MethodError") - else - rethrow(err) - end -end - -module Ambig9 -f(x::Complex{<:Integer}) = 1 -f(x::Complex{<:Rational}) = 2 -end -@test !Base.isambiguous(methods(Ambig9.f)..., ambiguous_bottom=false) -@test Base.isambiguous(methods(Ambig9.f)..., ambiguous_bottom=true) -@test !Base.isambiguous(methods(Ambig9.f)...) -@test length(detect_ambiguities(Ambig9, ambiguous_bottom=false)) == 0 -@test length(detect_ambiguities(Ambig9, ambiguous_bottom=true)) == 1 -@test length(detect_ambiguities(Ambig9)) == 0 - -nothing # don't return a module from the remote include diff --git a/julia-0.6.3/share/julia/test/arrayops.jl b/julia-0.6.3/share/julia/test/arrayops.jl deleted file mode 100644 index 5281342..0000000 --- a/julia-0.6.3/share/julia/test/arrayops.jl +++ /dev/null @@ -1,2144 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -# Array test -isdefined(Main, :TestHelpers) || @eval Main include("TestHelpers.jl") -using TestHelpers.OAs - -@testset "basics" begin - @test length([1, 2, 3]) == 3 - @test countnz([1, 2, 3]) == 3 - - let a = ones(4), b = a+a, c = a-a - @test b[1] === 2. && b[2] === 2. && b[3] === 2. && b[4] === 2. - @test c[1] === 0. && c[2] === 0. && c[3] === 0. && c[4] === 0. - end - - @test length((1,)) == 1 - @test length((1,2)) == 2 - - @test isequal(1.+[1,2,3], [2,3,4]) - @test isequal([1,2,3].+1, [2,3,4]) - @test isequal(1.-[1,2,3], [0,-1,-2]) - @test isequal([1,2,3].-1, [0,1,2]) - - @test isequal(5*[1,2,3], [5,10,15]) - @test isequal([1,2,3]*5, [5,10,15]) - @test isequal(1./[1,2,5], [1.0,0.5,0.2]) - @test isequal([1,2,3]/5, [0.2,0.4,0.6]) - - @test isequal(2.%[1,2,3], [0,0,2]) - @test isequal([1,2,3].%2, [1,0,1]) - @test isequal(2.÷[1,2,3], [2,1,0]) - @test isequal([1,2,3].÷2, [0,1,1]) - @test isequal(-2.%[1,2,3], [0,0,-2]) - @test isequal([-1,-2,-3].%2, [-1,0,-1]) - @test isequal(-2.÷[1,2,3], [-2,-1,0]) - @test isequal([-1,-2,-3].÷2, [0,-1,-1]) - - @test isequal(1.<<[1,2,5], [2,4,32]) - @test isequal(128.>>[1,2,5], [64,32,4]) - @test isequal(2.>>1, 1) - @test isequal(1.<<1, 2) - @test isequal([1,2,5].<<[1,2,5], [2,8,160]) - @test isequal([10,20,50].>>[1,2,5], [5,5,1]) - - - a = ones(2,2) - a[1,1] = 1 - a[1,2] = 2 - a[2,1] = 3 - a[2,2] = 4 - b = a' - @test a[1,1] == 1. && a[1,2] == 2. && a[2,1] == 3. && a[2,2] == 4. - @test b[1,1] == 1. && b[2,1] == 2. && b[1,2] == 3. && b[2,2] == 4. - a[[1 2 3 4]] = 0 - @test a == zeros(2,2) - a[[1 2], [1 2]] = 1 - @test a == ones(2,2) - a[[1 2], 1] = 0 - @test a[1,1] == 0. && a[1,2] == 1. && a[2,1] == 0. && a[2,2] == 1. - a[:, [1 2]] = 2 - @test a == 2ones(2,2) - - a = Array{Float64}(2, 2, 2, 2, 2) - a[1,1,1,1,1] = 10 - a[1,2,1,1,2] = 20 - a[1,1,2,2,1] = 30 - - @test a[1,1,1,1,1] == 10 - @test a[1,2,1,1,2] == 20 - @test a[1,1,2,2,1] == 30 - - @test_throws ArgumentError reinterpret(Int8, a) - - b = reshape(a, (32,)) - @test b[1] == 10 - @test b[19] == 20 - @test b[13] == 30 - @test_throws DimensionMismatch reshape(b,(5,7)) - @test_throws DimensionMismatch reshape(b,(35,)) - @test_throws DimensionMismatch reinterpret(Int, b, (35,)) - @test_throws ArgumentError reinterpret(Any, b, (32,)) - @test_throws DimensionMismatch reinterpret(Complex128, b, (32,)) - c = ["hello", "world"] - @test_throws ArgumentError reinterpret(Float32, c, (2,)) - a = Vector(ones(5)) - @test_throws ArgumentError resize!(a, -2) - - b = rand(32) - a = reshape(b, (2, 2, 2, 2, 2)) - @test ndims(a) == 5 - @test a[2,1,2,2,1] == b[14] - @test a[2,2,2,2,2] == b[end] -end -@testset "reshaping SubArrays" begin - a = collect(reshape(1:5, 1, 5)) - @testset "linearfast" begin - s = view(a, :, 2:4) - r = reshape(s, (length(s),)) - @test length(r) == 3 - @test r[1] == 2 - @test r[3,1] == 4 - @test r[Base.ReshapedIndex(CartesianIndex((1,2)))] == 3 - @test parent(reshape(r, (1,3))) === r.parent === s - @test parentindexes(r) == (1:1, 1:3) - @test reshape(r, (3,)) === r - @test convert(Array{Int,1}, r) == [2,3,4] - @test_throws MethodError convert(Array{Int,2}, r) - @test convert(Array{Int}, r) == [2,3,4] - @test Base.unsafe_convert(Ptr{Int}, r) == Base.unsafe_convert(Ptr{Int}, s) - @test isa(r, StridedArray) # issue #22411 - end - @testset "linearslow" begin - s = view(a, :, [2,3,5]) - r = reshape(s, length(s)) - @test length(r) == 3 - @test r[1] == 2 - @test r[3,1] == 5 - @test r[Base.ReshapedIndex(CartesianIndex((1,2)))] == 3 - @test parent(reshape(r, (1,3))) === r.parent === s - @test parentindexes(r) == (1:1, 1:3) - @test reshape(r, (3,)) === r - @test convert(Array{Int,1}, r) == [2,3,5] - @test_throws MethodError convert(Array{Int,2}, r) - @test convert(Array{Int}, r) == [2,3,5] - @test_throws ErrorException Base.unsafe_convert(Ptr{Int}, r) - r[2] = -1 - @test a[3] == -1 - a = zeros(0, 5) # an empty linearslow array - s = view(a, :, [2,3,5]) - @test length(reshape(s, length(s))) == 0 - end -end -@testset "reshape(a, Val{N})" begin - a = ones(Int,3,3) - s = view(a, 1:2, 1:2) - for N in (1,3) - @test isa(reshape(a, Val{N}), Array{Int,N}) - @test isa(reshape(s, Val{N}), Base.ReshapedArray{Int,N}) - end -end -@testset "reshape with colon" begin - # Reshape with an omitted dimension - let A = linspace(1, 60, 60) - @test size(reshape(A, :)) == (60,) - @test size(reshape(A, :, 1)) == (60, 1) - @test size(reshape(A, (:, 2))) == (30, 2) - @test size(reshape(A, 3, :)) == (3, 20) - @test size(reshape(A, 2, 3, :)) == (2, 3, 10) - @test size(reshape(A, (2, :, 5))) == (2, 6, 5) - @test_throws DimensionMismatch reshape(A, 7, :) - @test_throws DimensionMismatch reshape(A, :, 2, 3, 4) - @test_throws DimensionMismatch reshape(A, (:, :)) - - B = rand(2,2,2,2) - @test size(reshape(B, :)) == (16,) - @test size(reshape(B, :, 4)) == (4, 4) - @test size(reshape(B, (2, 1, :))) == (2, 1, 8) - @test_throws DimensionMismatch reshape(B, 3, :) - @test_throws DimensionMismatch reshape(B, :, :, 2, 2) - end -end - -@test reshape(1:5, (5,)) === 1:5 -@test reshape(1:5, 5) === 1:5 - -@testset "setindex! on a reshaped range" begin - a = reshape(1:20, 5, 4) - for idx in ((3,), (2,2), (Base.ReshapedIndex(1),)) - try - a[idx...] = 7 - error("wrong error") - catch err - @test err.msg == "indexed assignment fails for a reshaped range; consider calling collect" - end - end -end - -@testset "conversion from ReshapedArray to Array (#18262)" begin - a = Base.ReshapedArray(1:3, (3, 1), ()) - @test convert(Array, a) == a - @test convert(Array{Int}, a) == a - @test convert(Array{Float64}, a) == a - @test convert(Matrix, a) == a - @test convert(Matrix{Int}, a) == a - @test convert(Matrix{Float64}, a) == a - b = Base.ReshapedArray(1:3, (3,), ()) - @test convert(Array, b) == b - @test convert(Array{Int}, b) == b - @test convert(Array{Float64}, b) == b - @test convert(Vector, b) == b - @test convert(Vector{Int}, b) == b - @test convert(Vector{Float64}, b) == b -end - -@testset "operations with IndexLinear ReshapedArray" begin - b = collect(1:12) - a = Base.ReshapedArray(b, (4,3), ()) - @test a[3,2] == 7 - @test a[6] == 6 - a[3,2] = -2 - a[6] = -3 - a[Base.ReshapedIndex(5)] = -4 - @test b[5] == -4 - @test b[6] == -3 - @test b[7] == -2 - b = reinterpret(Int, a, (3,4)) - b[1] = -1 - @test vec(b) == vec(a) - - a = rand(1, 1, 8, 8, 1) - @test @inferred(squeeze(a, 1)) == @inferred(squeeze(a, (1,))) == reshape(a, (1, 8, 8, 1)) - @test @inferred(squeeze(a, (1, 5))) == squeeze(a, (5, 1)) == reshape(a, (1, 8, 8)) - @test @inferred(squeeze(a, (1, 2, 5))) == squeeze(a, (5, 2, 1)) == reshape(a, (8, 8)) - @test_throws ArgumentError squeeze(a, 0) - @test_throws ArgumentError squeeze(a, (1, 1)) - @test_throws ArgumentError squeeze(a, (1, 2, 1)) - @test_throws ArgumentError squeeze(a, (1, 1, 2)) - @test_throws ArgumentError squeeze(a, 3) - @test_throws ArgumentError squeeze(a, 4) - @test_throws ArgumentError squeeze(a, 6) - - sz = (5,8,7) - A = reshape(1:prod(sz),sz...) - @test A[2:6] == [2:6;] - @test A[1:3,2,2:4] == cat(2,46:48,86:88,126:128) - @test A[:,7:-3:1,5] == [191 176 161; 192 177 162; 193 178 163; 194 179 164; 195 180 165] - @test reshape(A, Val{2})[:,3:9] == reshape(11:45,5,7) - rng = (2,2:3,2:2:5) - tmp = zeros(Int,map(maximum,rng)...) - tmp[rng...] = A[rng...] - @test tmp == cat(3,zeros(Int,2,3),[0 0 0; 0 47 52],zeros(Int,2,3),[0 0 0; 0 127 132]) - - @test cat([1,2],1,2,3.,4.,5.) == diagm([1,2,3.,4.,5.]) - blk = [1 2;3 4] - tmp = cat([1,3],blk,blk) - @test tmp[1:2,1:2,1] == blk - @test tmp[1:2,1:2,2] == zero(blk) - @test tmp[3:4,1:2,1] == zero(blk) - @test tmp[3:4,1:2,2] == blk - - x = rand(2,2) - b = x[1,:] - @test isequal(size(b), (2,)) - b = x[:,1] - @test isequal(size(b), (2,)) - - x = rand(5,5) - b = x[2:3,2] - @test b[1] == x[2,2] && b[2] == x[3,2] - - B = zeros(4,5) - B[:,3] = 1:4 - @test B == [0 0 1 0 0; 0 0 2 0 0; 0 0 3 0 0; 0 0 4 0 0] - B[2,:] = 11:15 - @test B == [0 0 1 0 0; 11 12 13 14 15; 0 0 3 0 0; 0 0 4 0 0] - B[[3,1],[2,4]] = [21 22; 23 24] - @test B == [0 23 1 24 0; 11 12 13 14 15; 0 21 3 22 0; 0 0 4 0 0] - B[4,[2,3]] = 7 - @test B == [0 23 1 24 0; 11 12 13 14 15; 0 21 3 22 0; 0 7 7 0 0] - - @test isequal(reshape(reshape(1:27, 3, 3, 3), Val{2})[1,:], [1, 4, 7, 10, 13, 16, 19, 22, 25]) - - a = [3, 5, -7, 6] - b = [4, 6, 2, -7, 1] - ind = findin(a, b) - @test ind == [3,4] - - rt = Base.return_types(setindex!, Tuple{Array{Int32, 3}, UInt8, Vector{Int}, Int16, UnitRange{Int}}) - @test length(rt) == 1 && rt[1] == Array{Int32, 3} -end -@testset "construction" begin - @test typeof(Vector{Int}(3)) == Vector{Int} - @test typeof(Vector{Int}()) == Vector{Int} - @test typeof(Vector(3)) == Vector{Any} - @test typeof(Vector()) == Vector{Any} - @test typeof(Matrix{Int}(2,3)) == Matrix{Int} - @test typeof(Matrix(2,3)) == Matrix{Any} - - @test size(Vector{Int}(3)) == (3,) - @test size(Vector{Int}()) == (0,) - @test size(Vector(3)) == (3,) - @test size(Vector()) == (0,) - @test size(Matrix{Int}(2,3)) == (2,3) - @test size(Matrix(2,3)) == (2,3) - - # TODO: will throw MethodError after 0.6 deprecations are deleted - dw = Base.JLOptions().depwarn - if dw == 2 - @test_throws ErrorException Matrix{Int}() - @test_throws ErrorException Matrix() - elseif dw == 1 - @test_warn "deprecated" Matrix{Int}() - @test_warn "deprecated" Matrix() - elseif dw == 0 - @test size(Matrix{Int}()) == (0,0) - @test size(Matrix()) == (0,0) - else - error("unexpected depwarn value") - end - @test_throws MethodError Array{Int,3}() -end -@testset "get" begin - A = reshape(1:24, 3, 8) - x = get(A, 32, -12) - @test x == -12 - x = get(A, 14, -12) - @test x == 14 - x = get(A, (2,4), -12) - @test x == 11 - x = get(A, (4,4), -12) - @test x == -12 - X = get(A, -5:5, NaN32) - @test eltype(X) == Float32 - @test Base.elsize(X) == sizeof(Float32) - @test !all(isinteger, X) - @test isnan.(X) == [trues(6);falses(5)] - @test X[7:11] == [1:5;] - X = get(A, (2:4, 9:-2:-13), 0) - Xv = zeros(Int, 3, 12) - Xv[1:2, 2:5] = A[2:3, 7:-2:1] - @test X == Xv - X2 = get(A, Vector{Int}[[2:4;], [9:-2:-13;]], 0) - @test X == X2 -end -@testset "arrays as dequeues" begin - l = Any[1] - push!(l,2,3,8) - @test l[1]==1 && l[2]==2 && l[3]==3 && l[4]==8 - v = pop!(l) - @test v == 8 - v = pop!(l) - @test v == 3 - @test length(l)==2 - m = Any[] - @test_throws ArgumentError pop!(m) - @test_throws ArgumentError shift!(m) - unshift!(l,4,7,5) - @test l[1]==4 && l[2]==7 && l[3]==5 && l[4]==1 && l[5]==2 - v = shift!(l) - @test v == 4 - @test length(l)==4 - - v = [3, 7, 6] - @test_throws BoundsError insert!(v, 0, 5) - for i = 1:4 - vc = copy(v) - @test insert!(vc, i, 5) === vc - @test vc == [v[1:(i-1)]; 5; v[i:end]] - end - @test_throws BoundsError insert!(v, 5, 5) -end -@testset "concatenation" begin - @test isequal([ones(2,2) 2*ones(2,1)], [1. 1 2; 1 1 2]) - @test isequal([ones(2,2); 2*ones(1,2)], [1. 1; 1 1; 2 2]) -end - -@testset "typed array literals" begin - X = Float64[1 2 3] - Y = [1. 2. 3.] - @test size(X) == size(Y) - for i = 1:3 @test X[i] === Y[i] end - X = Float64[1;2;3] - Y = [1.,2.,3.] - @test size(X) == size(Y) - for i = 1:3 @test X[i] === Y[i] end - X = Float64[1 2 3; 4 5 6] - Y = [1. 2. 3.; 4. 5. 6.] - @test size(X) == size(Y) - for i = 1:length(X) @test X[i] === Y[i] end - - _array_equiv(a,b) = eltype(a) == eltype(b) && a == b - @test _array_equiv(UInt8[1:3;4], [0x1,0x2,0x3,0x4]) - @test_throws MethodError UInt8[1:3] - @test_throws MethodError UInt8[1:3,] - @test_throws MethodError UInt8[1:3,4:6] - a = Array{UnitRange{Int}}(1); a[1] = 1:3 - @test _array_equiv([1:3,], a) - a = Array{UnitRange{Int}}(2); a[1] = 1:3; a[2] = 4:6 - @test _array_equiv([1:3,4:6], a) -end - -@testset "typed hvcat" begin - X = Float64[1 2 3; 4 5 6] - X32 = Float32[X X; X X] - @test eltype(X32) <: Float32 - for i=[1,3], j=[1,4] - @test X32[i:(i+1), j:(j+2)] == X - end -end -@testset "end" begin - X = [ i+2j for i=1:5, j=1:5 ] - @test X[end,end] == 15 - @test X[end] == 15 # linear index - @test X[2, end] == 12 - @test X[end, 2] == 9 - @test X[end-1,2] == 8 - Y = [2, 1, 4, 3] - @test X[Y[end],1] == 5 - @test X[end,Y[end]] == 11 -end -@testset "find, findfirst, findnext, findlast, findprev" begin - a = [0,1,2,3,0,1,2,3] - @test find(a) == [2,3,4,6,7,8] - @test find(a.==2) == [3,7] - @test find(isodd,a) == [2,4,6,8] - @test findfirst(a) == 2 - @test findfirst(a.==0) == 1 - @test findfirst(a.==5) == 0 - @test findfirst([1,2,4,1,2,3,4], 3) == 6 - @test findfirst(isodd, [2,4,6,3,9,2,0]) == 4 - @test findfirst(isodd, [2,4,6,2,0]) == 0 - @test findnext(a,4) == 4 - @test findnext(a,5) == 6 - @test findnext(a,1) == 2 - @test findnext(a,1,4) == 6 - @test findnext(a,5,4) == 0 - @test findlast(a) == 8 - @test findlast(a.==0) == 5 - @test findlast(a.==5) == 0 - @test findlast([1,2,4,1,2,3,4], 3) == 6 - @test findlast(isodd, [2,4,6,3,9,2,0]) == 5 - @test findlast(isodd, [2,4,6,2,0]) == 0 - @test findprev(a,4) == 4 - @test findprev(a,5) == 4 - @test findprev(a,1) == 0 - @test findprev(a,1,4) == 2 - @test findprev(a,1,8) == 6 - @test findprev(isodd, [2,4,5,3,9,2,0], 7) == 5 - @test findprev(isodd, [2,4,5,3,9,2,0], 2) == 0 -end -@testset "find with general iterables" begin - s = "julia" - # FIXME once 16269 is resolved - # @test find(s) == [1,2,3,4,5] - @test find(c -> c == 'l', s) == [3] - g = graphemes("日本語") - @test find(g) == [1,2,3] - @test find(isascii, g) == Int[] -end -@testset "findn" begin - b = findn(ones(2,2,2,2)) - @test (length(b[1]) == 16) - @test (length(b[2]) == 16) - @test (length(b[3]) == 16) - @test (length(b[4]) == 16) - - #hand made case - a = ([2,1,2],[1,2,2],[2,2,2]) - z = zeros(2,2,2) - for i = 1:3 - z[a[1][i],a[2][i],a[3][i]] = 10 - end - @test isequal(a,findn(z)) -end - -@testset "findmin findmax indmin indmax" begin - @test indmax([10,12,9,11]) == 2 - @test indmin([10,12,9,11]) == 3 - @test findmin([NaN,3.2,1.8]) == (1.8,3) - @test findmax([NaN,3.2,1.8]) == (3.2,2) - @test findmin([NaN,3.2,1.8,NaN]) == (1.8,3) - @test findmax([NaN,3.2,1.8,NaN]) == (3.2,2) - @test findmin([3.2,1.8,NaN,2.0]) == (1.8,2) - @test findmax([3.2,1.8,NaN,2.0]) == (3.2,1) - - #14085 - @test findmax(4:9) == (9,6) - @test indmax(4:9) == 6 - @test findmin(4:9) == (4,1) - @test indmin(4:9) == 1 - @test findmax(5:-2:1) == (5,1) - @test indmax(5:-2:1) == 1 - @test findmin(5:-2:1) == (1,3) - @test indmin(5:-2:1) == 3 -end - -@testset "permutedims" begin - # keeps the num of dim - p = randperm(5) - q = randperm(5) - a = rand(p...) - b = permutedims(a,q) - @test isequal(size(b), tuple(p[q]...)) - - # hand made case - y = zeros(1,2,3) - for i = 1:6 - y[i]=i - end - - z = zeros(3,1,2) - for i = 1:3 - z[i] = i*2-1 - z[i+3] = i*2 - end - - # permutes correctly - @test isequal(z,permutedims(y,[3,1,2])) - @test isequal(z,permutedims(y,(3,1,2))) - - # of a subarray - a = rand(5,5) - s = view(a,2:3,2:3) - p = permutedims(s, [2,1]) - @test p[1,1]==a[2,2] && p[1,2]==a[3,2] - @test p[2,1]==a[2,3] && p[2,2]==a[3,3] - - # of a non-strided subarray - a = reshape(1:60, 3, 4, 5) - s = view(a,:,[1,2,4],[1,5]) - c = convert(Array, s) - for p in ([1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1]) - @test permutedims(s, p) == permutedims(c, p) - @test PermutedDimsArray(s, p) == permutedims(c, p) - end - @test_throws ArgumentError permutedims(a, (1,1,1)) - @test_throws ArgumentError permutedims(s, (1,1,1)) - @test_throws ArgumentError PermutedDimsArray(a, (1,1,1)) - @test_throws ArgumentError PermutedDimsArray(s, (1,1,1)) - cp = PermutedDimsArray(c, (3,2,1)) - @test pointer(cp) == pointer(c) - @test_throws ArgumentError pointer(cp, 2) - @test strides(cp) == (9,3,1) - ap = PermutedDimsArray(collect(a), (2,1,3)) - @test strides(ap) == (3,1,12) - - for A in [rand(1,2,3,4),rand(2,2,2,2),rand(5,6,5,6),rand(1,1,1,1)] - perm = randperm(4) - @test isequal(A,permutedims(permutedims(A,perm),invperm(perm))) - @test isequal(A,permutedims(permutedims(A,invperm(perm)),perm)) - end -end - -@testset "circshift" begin - @test circshift(1:5, -1) == circshift(1:5, 4) == circshift(1:5, -6) == [2,3,4,5,1] - @test circshift(1:5, 1) == circshift(1:5, -4) == circshift(1:5, 6) == [5,1,2,3,4] - a = [1:5;] - @test_throws ArgumentError Base.circshift!(a, a, 1) - b = copy(a) - @test Base.circshift!(b, a, 1) == [5,1,2,3,4] -end - -# unique across dim - -# All rows and columns unique -A = ones(10, 10) -A[diagind(A)] = shuffle!([1:10;]) -@test unique(A, 1) == A -@test unique(A, 2) == A - -# 10 repeats of each row -B = A[shuffle!(repmat(1:10, 10)), :] -C = unique(B, 1) -@test sortrows(C) == sortrows(A) -@test unique(B, 2) == B -@test unique(B.', 2).' == C - -# Along third dimension -D = cat(3, B, B) -@test unique(D, 1) == cat(3, C, C) -@test unique(D, 3) == cat(3, B) - -# With hash collisions -struct HashCollision - x::Float64 -end -Base.hash(::HashCollision, h::UInt) = h -@test map(x->x.x, unique(map(HashCollision, B), 1)) == C - -@testset "large matrices transpose" begin - for i = 1 : 3 - a = rand(200, 300) - @test isequal(a', permutedims(a, [2, 1])) - end -end - -@testset "repmat and repeat" begin - local A, A1, A2, A3, v, v2, cv, cv2, c, R, T - A = ones(Int,2,3,4) - A1 = reshape(repmat([1,2],1,12),2,3,4) - A2 = reshape(repmat([1 2 3],2,4),2,3,4) - A3 = reshape(repmat([1 2 3 4],6,1),2,3,4) - @test isequal(cumsum(A),A1) - @test isequal(cumsum(A,1),A1) - @test isequal(cumsum(A,2),A2) - @test isequal(cumsum(A,3),A3) - - # issue 20112 - A3 = reshape(repmat([1 2 3 4],UInt32(6),UInt32(1)),2,3,4) - @test isequal(cumsum(A,3),A3) - @test repmat([1,2,3,4], UInt32(1)) == [1,2,3,4] - @test repmat([1 2], UInt32(2)) == repmat([1 2], UInt32(2), UInt32(1)) - - # issue 20564 - @test_throws MethodError repmat(1, 2, 3) - @test_throws MethodError repmat([1, 2], 1, 2, 3) - - - R = repeat([1, 2]) - @test R == [1, 2] - R = repeat([1, 2], inner=1) - @test R == [1, 2] - R = repeat([1, 2], outer=1) - @test R == [1, 2] - R = repeat([1, 2], inner=(1,)) - @test R == [1, 2] - R = repeat([1, 2], outer=(1,)) - @test R == [1, 2] - R = repeat([1, 2], inner=[1]) - @test R == [1, 2] - R = repeat([1, 2], outer=[1]) - @test R == [1, 2] - R = repeat([1, 2], inner=1, outer=1) - @test R == [1, 2] - R = repeat([1, 2], inner=(1,), outer=(1,)) - @test R == [1, 2] - R = repeat([1, 2], inner=[1], outer=[1]) - @test R == [1, 2] - - R = repeat([1, 2], inner=2) - @test R == [1, 1, 2, 2] - R = repeat([1, 2], outer=2) - @test R == [1, 2, 1, 2] - R = repeat([1, 2], inner=(2,)) - @test R == [1, 1, 2, 2] - R = repeat([1, 2], outer=(2,)) - @test R == [1, 2, 1, 2] - R = repeat([1, 2], inner=[2]) - @test R == [1, 1, 2, 2] - R = repeat([1, 2], outer=[2]) - @test R == [1, 2, 1, 2] - - R = repeat([1, 2], inner=2, outer=2) - @test R == [1, 1, 2, 2, 1, 1, 2, 2] - R = repeat([1, 2], inner=(2,), outer=(2,)) - @test R == [1, 1, 2, 2, 1, 1, 2, 2] - R = repeat([1, 2], inner=[2], outer=[2]) - @test R == [1, 1, 2, 2, 1, 1, 2, 2] - - R = repeat([1, 2], inner = (1, 1), outer = (1, 1)) - @test R == reshape([1, 2], (2,1)) - R = repeat([1, 2], inner = (2, 1), outer = (1, 1)) - @test R == reshape([1, 1, 2, 2], (4,1)) - R = repeat([1, 2], inner = (1, 2), outer = (1, 1)) - @test R == [1 1; 2 2] - R = repeat([1, 2], inner = (1, 1), outer = (2, 1)) - @test R == reshape([1, 2, 1, 2], (4,1)) - R = repeat([1, 2], inner = (1, 1), outer = (1, 2)) - @test R == [1 1; 2 2] - - R = repeat([1 2; - 3 4], inner = (1, 1), outer = (1, 1)) - @test R == [1 2; - 3 4] - R = repeat([1 2; - 3 4], inner = (1, 1), outer = (2, 1)) - @test R == [1 2; - 3 4; - 1 2; - 3 4] - R = repeat([1 2; - 3 4], inner = (1, 1), outer = (1, 2)) - @test R == [1 2 1 2; - 3 4 3 4] - R = repeat([1 2; - 3 4], inner = (1, 1), outer = (2, 2)) - @test R == [1 2 1 2; - 3 4 3 4; - 1 2 1 2; - 3 4 3 4] - R = repeat([1 2; - 3 4], inner = (2, 1), outer = (1, 1)) - @test R == [1 2; - 1 2; - 3 4; - 3 4] - R = repeat([1 2; - 3 4], inner = (2, 1), outer = (2, 1)) - @test R == [1 2; - 1 2; - 3 4; - 3 4; - 1 2; - 1 2; - 3 4; - 3 4] - R = repeat([1 2; - 3 4], inner = (2, 1), outer = (1, 2)) - @test R == [1 2 1 2; - 1 2 1 2; - 3 4 3 4; - 3 4 3 4;] - R = repeat([1 2; - 3 4], inner = (2, 1), outer = (2, 2)) - @test R == [1 2 1 2; - 1 2 1 2; - 3 4 3 4; - 3 4 3 4; - 1 2 1 2; - 1 2 1 2; - 3 4 3 4; - 3 4 3 4] - R = repeat([1 2; - 3 4], inner = (1, 2), outer = (1, 1)) - @test R == [1 1 2 2; - 3 3 4 4] - R = repeat([1 2; - 3 4], inner = (1, 2), outer = (2, 1)) - @test R == [1 1 2 2; - 3 3 4 4; - 1 1 2 2; - 3 3 4 4] - R = repeat([1 2; - 3 4], inner = (1, 2), outer = (1, 2)) - @test R == [1 1 2 2 1 1 2 2; - 3 3 4 4 3 3 4 4] - R = repeat([1 2; - 3 4], inner = (1, 2), outer = (2, 2)) - @test R == [1 1 2 2 1 1 2 2; - 3 3 4 4 3 3 4 4; - 1 1 2 2 1 1 2 2; - 3 3 4 4 3 3 4 4] - R = repeat([1 2; - 3 4], inner = (2, 2), outer = [1, 1]) - @test R == [1 1 2 2; - 1 1 2 2; - 3 3 4 4; - 3 3 4 4] - R = repeat([1 2; - 3 4], inner = (2, 2), outer = (2, 1)) - @test R == [1 1 2 2; - 1 1 2 2; - 3 3 4 4; - 3 3 4 4; - 1 1 2 2; - 1 1 2 2; - 3 3 4 4; - 3 3 4 4] - R = repeat([1 2; - 3 4], inner = (2, 2), outer = (1, 2)) - @test R == [1 1 2 2 1 1 2 2; - 1 1 2 2 1 1 2 2; - 3 3 4 4 3 3 4 4; - 3 3 4 4 3 3 4 4] - R = repeat([1 2; - 3 4], inner = (2, 2), outer = (2, 2)) - @test R == [1 1 2 2 1 1 2 2; - 1 1 2 2 1 1 2 2; - 3 3 4 4 3 3 4 4; - 3 3 4 4 3 3 4 4; - 1 1 2 2 1 1 2 2; - 1 1 2 2 1 1 2 2; - 3 3 4 4 3 3 4 4; - 3 3 4 4 3 3 4 4] - @test_throws ArgumentError repeat([1 2; - 3 4], inner=2, outer=(2, 2)) - @test_throws ArgumentError repeat([1 2; - 3 4], inner=(2, 2), outer=2) - @test_throws ArgumentError repeat([1 2; - 3 4], inner=(2,), outer=(2, 2)) - @test_throws ArgumentError repeat([1 2; - 3 4], inner=(2, 2), outer=(2,)) - - A = reshape(1:8, 2, 2, 2) - R = repeat(A, inner = (1, 1, 2), outer = (1, 1, 1)) - T = reshape([1:4; 1:4; 5:8; 5:8], 2, 2, 4) - @test R == T - A = Array{Int}(2, 2, 2) - A[:, :, 1] = [1 2; - 3 4] - A[:, :, 2] = [5 6; - 7 8] - R = repeat(A, inner = (2, 2, 2), outer = (2, 2, 2)) - @test R[1, 1, 1] == 1 - @test R[2, 2, 2] == 1 - @test R[3, 3, 3] == 8 - @test R[4, 4, 4] == 8 - @test R[5, 5, 5] == 1 - @test R[6, 6, 6] == 1 - @test R[7, 7, 7] == 8 - @test R[8, 8, 8] == 8 - - R = repeat(1:2) - @test R == [1, 2] - R = repeat(1:2, inner=1) - @test R == [1, 2] - R = repeat(1:2, inner=2) - @test R == [1, 1, 2, 2] - R = repeat(1:2, outer=1) - @test R == [1, 2] - R = repeat(1:2, outer=2) - @test R == [1, 2, 1, 2] - R = repeat(1:2, inner=(3,), outer=(2,)) - @test R == [1, 1, 1, 2, 2, 2, 1, 1, 1, 2, 2, 2] - - # Arrays of arrays - @test repeat([[1], [2]], inner=2) == [[1], [1], [2], [2]] - @test repeat([[1], [2]], outer=2) == [[1], [2], [1], [2]] - @test repeat([[1], [2]], inner=2, outer=2) == [[1], [1], [2], [2], [1], [1], [2], [2]] - - @test size(repeat([1], inner=(0,))) == (0,) - @test size(repeat([1], outer=(0,))) == (0,) - @test size(repeat([1 1], inner=(0, 1))) == (0, 2) - @test size(repeat([1 1], outer=(1, 0))) == (1, 0) - @test size(repeat([1 1], inner=(2, 0), outer=(2, 1))) == (4, 0) - @test size(repeat([1 1], inner=(2, 0), outer=(0, 1))) == (0, 0) - - A = rand(4,4) - for s in Any[A[1:2:4, 1:2:4], view(A, 1:2:4, 1:2:4)] - c = cumsum(s, 1) - @test c[1,1] == A[1,1] - @test c[2,1] == A[1,1]+A[3,1] - @test c[1,2] == A[1,3] - @test c[2,2] == A[1,3]+A[3,3] - - c = cumsum(s, 2) - @test c[1,1] == A[1,1] - @test c[2,1] == A[3,1] - @test c[1,2] == A[1,1]+A[1,3] - @test c[2,2] == A[3,1]+A[3,3] - end - - v = [1,1e100,1,-1e100]*1000 - v2 = [1,-1e100,1,1e100]*1000 - - cv = [1,1e100,1e100,2]*1000 - cv2 = [1,-1e100,-1e100,2]*1000 - - @test isequal(cumsum_kbn(v), cv) - @test isequal(cumsum_kbn(v2), cv2) - - A = [v reverse(v) v2 reverse(v2)] - - c = cumsum_kbn(A, 1) - - @test isequal(c[:,1], cv) - @test isequal(c[:,3], cv2) - @test isequal(c[4,:], [2.0, 2.0, 2.0, 2.0]*1000) - - c = cumsum_kbn(A, 2) - - @test isequal(c[1,:], cv2) - @test isequal(c[3,:], cv) - @test isequal(c[:,4], [2.0,2.0,2.0,2.0]*1000) - - @test repeat(BitMatrix(eye(2)), inner = (2,1), outer = (1,2)) == repeat(eye(2), inner = (2,1), outer = (1,2)) -end - -@testset "indexing with bools" begin - @test (1:5)[[true,false,true,false,true]] == [1,3,5] - @test [1:5;][[true,false,true,false,true]] == [1,3,5] - @test_throws BoundsError (1:5)[[true,false,true,false]] - @test_throws BoundsError (1:5)[[true,false,true,false,true,false]] - @test_throws BoundsError [1:5;][[true,false,true,false]] - @test_throws BoundsError [1:5;][[true,false,true,false,true,false]] - a = [1:5;] - a[[true,false,true,false,true]] = 6 - @test a == [6,2,6,4,6] - a[[true,false,true,false,true]] = [7,8,9] - @test a == [7,2,8,4,9] - @test_throws DimensionMismatch (a[[true,false,true,false,true]] = [7,8,9,10]) - A = reshape(1:15, 3, 5) - @test A[[true, false, true], [false, false, true, true, false]] == [7 10; 9 12] - @test_throws BoundsError A[[true, false], [false, false, true, true, false]] - @test_throws BoundsError A[[true, false, true], [false, true, true, false]] - @test_throws BoundsError A[[true, false, true, true], [false, false, true, true, false]] - @test_throws BoundsError A[[true, false, true], [false, false, true, true, false, true]] - A = ones(Int, 3, 5) - @test_throws DimensionMismatch A[2,[true, false, true, true, false]] = 2:5 - A[2,[true, false, true, true, false]] = 2:4 - @test A == [1 1 1 1 1; 2 1 3 4 1; 1 1 1 1 1] - @test_throws DimensionMismatch A[[true,false,true], 5] = [19] - @test_throws DimensionMismatch A[[true,false,true], 5] = 19:21 - A[[true,false,true], 5] = 7 - @test A == [1 1 1 1 7; 2 1 3 4 1; 1 1 1 1 7] - - B = cat(3, 1, 2, 3) - @test B[:,:,[true, false, true]] == reshape([1,3], 1, 1, 2) # issue #5454 -end - -# issue #2342 -@test isequal(cumsum([1 2 3]), [1 2 3]) - -@testset "set-like operations" begin - @test isequal(union([1,2,3], [4,3,4]), [1,2,3,4]) - @test isequal(union(['e','c','a'], ['b','a','d']), ['e','c','a','b','d']) - @test isequal(union([1,2,3], [4,3], [5]), [1,2,3,4,5]) - @test isequal(union([1,2,3]), [1,2,3]) - @test isequal(union([1,2,3], Int64[]), Int64[1,2,3]) - @test isequal(union([1,2,3], Float64[]), Float64[1.0,2,3]) - @test isequal(union(Int64[], [1,2,3]), Int64[1,2,3]) - @test isequal(union(Int64[]), Int64[]) - @test isequal(intersect([1,2,3], [4,3,4]), [3]) - @test isequal(intersect(['e','c','a'], ['b','a','d']), ['a']) - @test isequal(intersect([1,2,3], [3,1], [2,1,3]), [1,3]) - @test isequal(intersect([1,2,3]), [1,2,3]) - @test isequal(intersect([1,2,3], Int64[]), Int64[]) - @test isequal(intersect([1,2,3], Float64[]), Float64[]) - @test isequal(intersect(Int64[], [1,2,3]), Int64[]) - @test isequal(intersect(Int64[]), Int64[]) - @test isequal(setdiff([1,2,3,4], [2,5,4]), [1,3]) - @test isequal(setdiff([1,2,3,4], [7,8,9]), [1,2,3,4]) - @test isequal(setdiff([1,2,3,4], Int64[]), Int64[1,2,3,4]) - @test isequal(setdiff([1,2,3,4], [1,2,3,4,5]), Int64[]) - @test isequal(symdiff([1,2,3], [4,3,4]), [1,2,4]) - @test isequal(symdiff(['e','c','a'], ['b','a','d']), ['e','c','b','d']) - @test isequal(symdiff([1,2,3], [4,3], [5]), [1,2,4,5]) - @test isequal(symdiff([1,2,3,4,5], [1,2,3], [3,4]), [3,5]) - @test isequal(symdiff([1,2,3]), [1,2,3]) - @test isequal(symdiff([1,2,3], Int64[]), Int64[1,2,3]) - @test isequal(symdiff([1,2,3], Float64[]), Float64[1.0,2,3]) - @test isequal(symdiff(Int64[], [1,2,3]), Int64[1,2,3]) - @test isequal(symdiff(Int64[]), Int64[]) -end - -@testset "mapslices" begin - local a,h,i - a = rand(5,5) - s = mapslices(sort, a, [1]) - S = mapslices(sort, a, [2]) - for i = 1:5 - @test s[:,i] == sort(a[:,i]) - @test vec(S[i,:]) == sort(vec(a[i,:])) - end - - # issue #3613 - b = mapslices(sum, ones(2,3,4), [1,2]) - @test size(b) === (1,1,4) - @test all(b.==6) - - # issue #5141 - ## Update Removed the version that removes the dimensions when dims==1:ndims(A) - c1 = mapslices(x-> maximum(-x), a, []) - @test c1 == -a - - # other types than Number - @test mapslices(prod,["1" "2"; "3" "4"],1) == ["13" "24"] - @test mapslices(prod,["1"],1) == ["1"] - - # issue #5177 - - c = ones(2,3,4) - m1 = mapslices(x-> ones(2,3), c, [1,2]) - m2 = mapslices(x-> ones(2,4), c, [1,3]) - m3 = mapslices(x-> ones(3,4), c, [2,3]) - @test size(m1) == size(m2) == size(m3) == size(c) - - n1 = mapslices(x-> ones(6), c, [1,2]) - n2 = mapslices(x-> ones(6), c, [1,3]) - n3 = mapslices(x-> ones(6), c, [2,3]) - n1a = mapslices(x-> ones(1,6), c, [1,2]) - n2a = mapslices(x-> ones(1,6), c, [1,3]) - n3a = mapslices(x-> ones(1,6), c, [2,3]) - @test size(n1a) == (1,6,4) && size(n2a) == (1,3,6) && size(n3a) == (2,1,6) - @test size(n1) == (6,1,4) && size(n2) == (6,3,1) && size(n3) == (2,6,1) - - # mutating functions - o = ones(3, 4) - m = mapslices(x->fill!(x, 0), o, 2) - @test m == zeros(3, 4) - @test o == ones(3, 4) - - # issue #18524 - m = mapslices(x->tuple(x), [1 2; 3 4], 1) - @test m[1,1] == ([1,3],) - @test m[1,2] == ([2,4],) - - # issue #21123 - @test mapslices(nnz, speye(3), 1) == [1 1 1] -end - -@testset "single multidimensional index" begin - a = rand(6,6) - I = [1 4 5; 4 2 6; 5 6 3] - a2 = a[I] - @test size(a2) == size(I) - for i = 1:length(a2) - @test a2[i] == a[I[i]] - end - a = [1,3,5] - b = [1 3] - a[b] = 8 - @test a == [8,3,8] -end - -@testset "assigning an array into itself" begin - a = [1,3,5] - b = [3,1,2] - a[b] = a - @test a == [3,5,1] - a = [3,2,1] - a[a] = [4,5,6] - @test a == [6,5,4] -end - -@testset "lexicographic comparison" begin - @test lexcmp([1.0], [1]) == 0 - @test lexcmp([1], [1.0]) == 0 - @test lexcmp([1, 1], [1, 1]) == 0 - @test lexcmp([1, 1], [2, 1]) == -1 - @test lexcmp([2, 1], [1, 1]) == 1 - @test lexcmp([1, 1], [1, 2]) == -1 - @test lexcmp([1, 2], [1, 1]) == 1 - @test lexcmp([1], [1, 1]) == -1 - @test lexcmp([1, 1], [1]) == 1 -end - -@testset "sort on arrays" begin - local a = rand(3,3) - - asr = sortrows(a) - @test lexless(asr[1,:],asr[2,:]) - @test lexless(asr[2,:],asr[3,:]) - - asc = sortcols(a) - @test lexless(asc[:,1],asc[:,2]) - @test lexless(asc[:,2],asc[:,3]) - - # mutating functions - o = ones(3, 4) - m = mapslices(x->fill!(x, 0), o, 2) - @test m == zeros(3, 4) - @test o == ones(3, 4) - - asr = sortrows(a, rev=true) - @test lexless(asr[2,:],asr[1,:]) - @test lexless(asr[3,:],asr[2,:]) - - asc = sortcols(a, rev=true) - @test lexless(asc[:,2],asc[:,1]) - @test lexless(asc[:,3],asc[:,2]) - - as = sort(a, 1) - @test issorted(as[:,1]) - @test issorted(as[:,2]) - @test issorted(as[:,3]) - - as = sort(a, 2) - @test issorted(as[1,:]) - @test issorted(as[2,:]) - @test issorted(as[3,:]) - - local b = rand(21,21,2) - - bs = sort(b, 1) - for i in 1:21 - @test issorted(bs[:,i,1]) - @test issorted(bs[:,i,2]) - end - - bs = sort(b, 2) - for i in 1:21 - @test issorted(bs[i,:,1]) - @test issorted(bs[i,:,2]) - end - - bs = sort(b, 3) - @test all(bs[:,:,1] .<= bs[:,:,2]) -end - -@testset "fill" begin - @test fill!(Array{Float64}(1),-0.0)[1] === -0.0 - A = ones(3,3) - S = view(A, 2, 1:3) - fill!(S, 2) - S = view(A, 1:2, 3) - fill!(S, 3) - @test A == [1 1 3; 2 2 3; 1 1 1] - rt = Base.return_types(fill!, Tuple{Array{Int32, 3}, UInt8}) - @test length(rt) == 1 && rt[1] == Array{Int32, 3} - A = Array{Union{UInt8,Int8}}(3) - fill!(A, UInt8(3)) - @test A == [0x03, 0x03, 0x03] - # Issue #9964 - A = Array{Vector{Float64}}(2) - fill!(A, [1, 2]) - @test A[1] == [1, 2] - @test A[1] === A[2] -end - -@testset "splice!" begin - for idx in Any[1, 2, 5, 9, 10, 1:0, 2:1, 1:1, 2:2, 1:2, 2:4, 9:8, 10:9, 9:9, 10:10, - 8:9, 9:10, 6:9, 7:10] - for repl in Any[[], [11], [11,22], [11,22,33,44,55]] - a = [1:10;]; acopy = copy(a) - @test splice!(a, idx, repl) == acopy[idx] - @test a == [acopy[1:(first(idx)-1)]; repl; acopy[(last(idx)+1):end]] - end - end -end - -@testset "filter!" begin - # base case w/ Vector - a = collect(1:10) - filter!(x -> x > 5, a) - @test a == collect(6:10) - - # different subtype of AbstractVector - ba = rand(10) .> 0.5 - @test isa(ba, BitArray) - filter!(x -> x, ba) - @test all(ba) - - # empty array - ea = [] - filter!(x -> x > 5, ea) - @test isempty(ea) - - # non-1-indexed array - oa = OffsetArray(collect(1:10), -5) - filter!(x -> x > 5, oa) - @test oa == OffsetArray(collect(6:10), -5) - - # empty non-1-indexed array - eoa = OffsetArray([], -5) - filter!(x -> x > 5, eoa) - @test isempty(eoa) -end - - -@testset "deleteat!" begin - for idx in Any[1, 2, 5, 9, 10, 1:0, 2:1, 1:1, 2:2, 1:2, 2:4, 9:8, 10:9, 9:9, 10:10, - 8:9, 9:10, 6:9, 7:10] - # integer indexing with AbstractArray - a = [1:10;]; acopy = copy(a) - @test deleteat!(a, idx) == [acopy[1:(first(idx)-1)]; acopy[(last(idx)+1):end]] - - # integer indexing with non-AbstractArray iterable - a = [1:10;]; acopy = copy(a) - @test deleteat!(a, (i for i in idx)) == [acopy[1:(first(idx)-1)]; acopy[(last(idx)+1):end]] - - # logical indexing - a = [1:10;]; acopy = copy(a) - @test deleteat!(a, map(i -> i in idx, 1:length(a))) == [acopy[1:(first(idx)-1)]; acopy[(last(idx)+1):end]] - end - a = [1:10;] - @test deleteat!(a, 11:10) == [1:10;] - @test deleteat!(a, [1,3,5,7:10...]) == [2,4,6] - @test_throws BoundsError deleteat!(a, 13) - @test_throws BoundsError deleteat!(a, [1,13]) - @test_throws ArgumentError deleteat!(a, [5,3]) - @test_throws BoundsError deleteat!(a, 5:20) - @test_throws BoundsError deleteat!(a, Bool[]) - @test_throws BoundsError deleteat!(a, [true]) - @test_throws BoundsError deleteat!(a, falses(11)) -end - -@testset "comprehensions" begin - X = [ i+2j for i=1:5, j=1:5 ] - @test X[2,3] == 8 - @test X[4,5] == 14 - @test isequal(ones(2,3) * ones(2,3)', [3. 3.; 3. 3.]) - # @test isequal([ [1,2] for i=1:2, : ], [1 2; 1 2]) - # where element type is a Union. try to confuse type inference. - foo32_64(x) = (x<2) ? Int32(x) : Int64(x) - boo32_64() = [ foo32_64(i) for i=1:2 ] - let a36 = boo32_64() - @test a36[1]==1 && a36[2]==2 - end - @test isequal([1,2,3], [a for (a,b) in enumerate(2:4)]) - @test isequal([2,3,4], [b for (a,b) in enumerate(2:4)]) - - @testset "comprehension in let-bound function" begin - let x⊙y = sum([x[i]*y[i] for i=1:length(x)]) - @test [1,2] ⊙ [3,4] == 11 - end - - @test_throws DomainError (10.^[-1])[1] == 0.1 - @test (10.^[-1.])[1] == 0.1 - end -end - -# issue #24002 -module I24002 -s1() = 1 -y = Int[i for i in 1:10] -end -@test I24002.y == [1:10;] -@test I24002.s1() == 1 - -@testset "eachindexvalue" begin - A14 = [11 13; 12 14] - R = CartesianRange(indices(A14)) - @test [a for (a,b) in enumerate(IndexLinear(), A14)] == [1,2,3,4] - @test [a for (a,b) in enumerate(IndexCartesian(), A14)] == vec(collect(R)) - @test [b for (a,b) in enumerate(IndexLinear(), A14)] == [11,12,13,14] - @test [b for (a,b) in enumerate(IndexCartesian(), A14)] == [11,12,13,14] -end - -@testset "reverse" begin - @test reverse([2,3,1]) == [1,3,2] - @test reverse([1:10;],1,4) == [4,3,2,1,5,6,7,8,9,10] - @test reverse([1:10;],3,6) == [1,2,6,5,4,3,7,8,9,10] - @test reverse([1:10;],6,10) == [1,2,3,4,5,10,9,8,7,6] - @test reverse(1:10,1,4) == [4,3,2,1,5,6,7,8,9,10] - @test reverse(1:10,3,6) == [1,2,6,5,4,3,7,8,9,10] - @test reverse(1:10,6,10) == [1,2,3,4,5,10,9,8,7,6] - @test reverse!([1:10;]) == [10,9,8,7,6,5,4,3,2,1] - @test reverse!([1:10;],1,4) == [4,3,2,1,5,6,7,8,9,10] - @test reverse!([1:10;],3,6) == [1,2,6,5,4,3,7,8,9,10] - @test reverse!([1:10;],6,10) == [1,2,3,4,5,10,9,8,7,6] - @test reverse!([1:10;], 11) == [1:10;] - @test_throws BoundsError reverse!([1:10;], 1, 11) - @test reverse!(Any[]) == Any[] -end - -@testset "flipdim" begin - @test isequal(flipdim([2,3,1], 1), [1,3,2]) - @test_throws ArgumentError flipdim([2,3,1], 2) - @test isequal(flipdim([2 3 1], 1), [2 3 1]) - @test isequal(flipdim([2 3 1], 2), [1 3 2]) - @test_throws ArgumentError flipdim([2,3,1], -1) - @test isequal(flipdim(1:10, 1), 10:-1:1) - @test_throws ArgumentError flipdim(1:10, 2) - @test_throws ArgumentError flipdim(1:10, -1) - @test isequal(flipdim(Array{Int}(0,0),1), Array{Int}(0,0)) # issue #5872 - - a = rand(5,3) - @test flipdim(flipdim(a,2),2) == a - @test_throws ArgumentError flipdim(a,3) -end - -@testset "isdiag, istril, istriu" begin - @test isdiag(3) - @test istril(4) - @test istriu(5) - @test !isdiag([1 2; 3 4]) - @test !istril([1 2; 3 4]) - @test !istriu([1 2; 3 4]) - @test isdiag([1 0; 0 4]) - @test istril([1 0; 3 4]) - @test istriu([1 2; 0 4]) -end - -# issue 4228 -A = [[i i; i i] for i=1:2] -@test cumsum(A) == Any[[1 1; 1 1], [3 3; 3 3]] -@test cumprod(A) == Any[[1 1; 1 1], [4 4; 4 4]] - -@testset "prepend/append" begin - # PR #4627 - A = [1,2] - @test append!(A, A) == [1,2,1,2] - @test prepend!(A, A) == [1,2,1,2,1,2,1,2] - - # iterators with length: - @test append!([1,2], (9,8)) == [1,2,9,8] == push!([1,2], (9,8)...) - @test prepend!([1,2], (9,8)) == [9,8,1,2] == unshift!([1,2], (9,8)...) - @test append!([1,2], ()) == [1,2] == prepend!([1,2], ()) - # iterators without length: - g = (i for i = 1:10 if iseven(i)) - @test append!([1,2], g) == [1,2,2,4,6,8,10] == push!([1,2], g...) - @test prepend!([1,2], g) == [2,4,6,8,10,1,2] == unshift!([1,2], g...) - g = (i for i = 1:2:10 if iseven(i)) # isempty(g) == true - @test append!([1,2], g) == [1,2] == push!([1,2], g...) - @test prepend!([1,2], g) == [1,2] == unshift!([1,2], g...) - - # offset array - @test append!([1,2], OffsetArray([9,8], (-3,))) == [1,2,9,8] - @test prepend!([1,2], OffsetArray([9,8], (-3,))) == [9,8,1,2] -end - -A = [1,2] -s = Set([1,2,3]) -@test sort(append!(A, s)) == [1,1,2,2,3] - -@testset "cases where shared arrays can/can't be grown" begin - A = [1 3;2 4] - B = reshape(A, 4) - @test push!(B,5) == [1,2,3,4,5] - @test pop!(B) == 5 - C = reshape(B, 1, 4) - @test_throws MethodError push!(C, 5) - - A = [NaN]; B = [NaN] - @test !(A==A) - @test isequal(A,A) - @test A===A - @test !(A==B) - @test isequal(A,B) - @test A!==B -end -# complete testsuite for reducedim - -# Inferred types -Nmax = 3 # TODO: go up to CARTESIAN_DIMS+2 (currently this exposes problems) -for N = 1:Nmax - #indexing with (UnitRange, UnitRange, UnitRange) - args = ntuple(d->UnitRange{Int}, N) - @test Base.return_types(getindex, Tuple{Array{Float32, N}, args...}) == [Array{Float32, N}] - @test Base.return_types(getindex, Tuple{BitArray{N}, args...}) == Any[BitArray{N}] - @test Base.return_types(setindex!, Tuple{Array{Float32, N}, Array{Int, 1}, args...}) == [Array{Float32, N}] - # Indexing with (UnitRange, UnitRange, Int) - args = ntuple(d->d<N ? UnitRange{Int} : Int, N) - N > 1 && @test Base.return_types(getindex, Tuple{Array{Float32, N}, args...}) == [Array{Float32, N-1}] - N > 1 && @test Base.return_types(getindex, Tuple{BitArray{N}, args...}) == [BitArray{N-1}] - N > 1 && @test Base.return_types(setindex!, Tuple{Array{Float32, N}, Array{Int, 1}, args...}) == [Array{Float32, N}] -end - -# issue #6645 (32-bit) -let x = Float64[] - for i=1:5; push!(x, 1.0); end - @test dot(zeros(5),x) == 0.0 -end - -# issue #6977 -@test size([]') == (1,0) - -# issue #6996 -@test Any[ 1 2; 3 4 ]' == Any[ 1 2; 3 4 ].' - -# map with promotion (issue #6541) -@test map(join, ["z", "я"]) == ["z", "я"] - -# Handle block matrices -A = [randn(2,2) for i = 1:2, j = 1:2] -@test issymmetric(A.'A) -A = [complex.(randn(2,2), randn(2,2)) for i = 1:2, j = 1:2] -@test ishermitian(A'A) - -# issue #7197 -function i7197() - S = [1 2 3; 4 5 6; 7 8 9] - ind2sub(size(S), 5) -end -@test i7197() == (2,2) - -# PR #8622 and general indexin test -function pr8622() - x=[1,3,5,7] - y=[5,4,3] - return indexin(x,y) -end -@test pr8622() == [0,3,1,0] - -#6828 - size of specific dimensions -let a = Array{Float64}(10) - @test size(a) == (10,) - @test size(a, 1) == 10 - @test size(a,2,1) == (1,10) - aa = Array{Float64}(2,3) - @test size(aa) == (2,3) - @test size(aa,4,3,2,1) == (1,1,3,2) - @test size(aa,1,2) == (2,3) - aaa = Array{Float64}(9,8,7,6,5,4,3,2,1) - @test size(aaa,1,1) == (9,9) - @test size(aaa,4) == 6 - @test size(aaa,9,8,7,6,5,4,3,2,19,8,7,6,5,4,3,2,1) == (1,2,3,4,5,6,7,8,1,2,3,4,5,6,7,8,9) - - #18459 Test Array{T, N} constructor - b = Array{Float64, 1}(10) - @test size(a) == size(b) - bb = Array{Float64, 2}(2,3) - @test size(aa) == size(bb) - bbb = Array{Float64, 9}(9,8,7,6,5,4,3,2,1) - @test size(aaa) == size(bbb) -end - -# Cartesian -function cartesian_foo() - Base.@nexprs 2 d->(a_d_d = d) - a_2_2 -end -@test cartesian_foo() == 2 - -@testset "Multidimensional iterators" begin - for a in ([1:5;], reshape([2])) - counter = 0 - for I in eachindex(a) - counter += 1 - end - @test counter == length(a) - counter = 0 - for aa in a - counter += 1 - end - @test counter == length(a) - end -end - -function mdsum(A) - s = 0.0 - for a in A - s += a - end - s -end - -function mdsum2(A) - s = 0.0 - @inbounds for I in eachindex(A) - s += A[I] - end - s -end - -@testset "linear indexing" begin - a = [1:5;] - @test isa(Base.IndexStyle(a), Base.IndexLinear) - b = view(a, :) - @test isa(Base.IndexStyle(b), Base.IndexLinear) - @test isa(Base.IndexStyle(trues(2)), Base.IndexLinear) - @test isa(Base.IndexStyle(BitArray{2}), Base.IndexLinear) - aa = fill(99, 10) - aa[1:2:9] = a - shp = [5] - for i = 1:10 - A = reshape(a, tuple(shp...)) - @test mdsum(A) == 15 - @test mdsum2(A) == 15 - AA = reshape(aa, tuple(2, shp...)) - B = view(AA, 1:1, ntuple(i->Colon(), i)...) - @test isa(Base.IndexStyle(B), Base.IteratorsMD.IndexCartesian) - @test mdsum(B) == 15 - @test mdsum2(B) == 15 - unshift!(shp, 1) - end - - a = [1:10;] - shp = [2,5] - for i = 2:10 - A = reshape(a, tuple(shp...)) - @test mdsum(A) == 55 - @test mdsum2(A) == 55 - B = view(A, ntuple(i->Colon(), i)...) - @test mdsum(B) == 55 - @test mdsum2(B) == 55 - insert!(shp, 2, 1) - end - - a = reshape([2]) - @test mdsum(a) == 2 - @test mdsum2(a) == 2 - - a = ones(0,5) - b = view(a, :, :) - @test mdsum(b) == 0 - a = ones(5,0) - b = view(a, :, :) - @test mdsum(b) == 0 -end -@testset "CartesianIndex" begin - for a in (copy(reshape(1:60, 3, 4, 5)), - view(copy(reshape(1:60, 3, 4, 5)), 1:3, :, :), - view(copy(reshape(1:60, 3, 4, 5)), CartesianIndex.(1:3, (1:4)'), :), - view(copy(reshape(1:60, 3, 4, 5)), :, CartesianIndex.(1:4, (1:5)'))) - @test a[CartesianIndex{3}(2,3,4)] == 44 - a[CartesianIndex{3}(2,3,3)] = -1 - @test a[CartesianIndex{3}(2,3,3)] == -1 - @test a[2,CartesianIndex{2}(3,4)] == 44 - a[1,CartesianIndex{2}(3,4)] = -2 - @test a[1,CartesianIndex{2}(3,4)] == -2 - @test a[CartesianIndex{1}(2),3,CartesianIndex{1}(4)] == 44 - a[CartesianIndex{1}(2),3,CartesianIndex{1}(3)] = -3 - @test a[CartesianIndex{1}(2),3,CartesianIndex{1}(3)] == -3 - - @test a[:, :, CartesianIndex((1,))] == (@view a[:, :, CartesianIndex((1,))]) == a[:,:,1] - @test a[CartesianIndex((1,)), [1,2], :] == (@view a[CartesianIndex((1,)), [1,2], :]) == a[1,[1,2],:] - @test a[CartesianIndex((2,)), 3:4, :] == (@view a[CartesianIndex((2,)), 3:4, :]) == a[2,3:4,:] - @test a[[CartesianIndex(1,3),CartesianIndex(2,4)],3:3] == - (@view a[[CartesianIndex(1,3),CartesianIndex(2,4)],3:3]) == reshape([a[1,3,3]; a[2,4,3]], 2, 1) - - @test a[[CartesianIndex()], :, :, :] == (@view a[[CartesianIndex()], :, :, :]) == reshape(a, 1, 3, 4, 5) - @test a[:, [CartesianIndex()], :, :] == (@view a[:, [CartesianIndex()], :, :]) == reshape(a, 3, 1, 4, 5) - @test a[:, :, [CartesianIndex()], :] == (@view a[:, :, [CartesianIndex()], :]) == reshape(a, 3, 4, 1, 5) - @test a[:, :, :, [CartesianIndex()]] == (@view a[:, :, :, [CartesianIndex()]]) == reshape(a, 3, 4, 5, 1) - a2 = reshape(a, Val{2}) - @test a2[[CartesianIndex()], :, :] == (@view a2[[CartesianIndex()], :, :]) == reshape(a, 1, 3, 20) - @test a2[:, [CartesianIndex()], :] == (@view a2[:, [CartesianIndex()], :]) == reshape(a, 3, 1, 20) - @test a2[:, :, [CartesianIndex()]] == (@view a2[:, :, [CartesianIndex()]]) == reshape(a, 3, 20, 1) - a1 = reshape(a, Val{1}) - @test a1[[CartesianIndex()], :] == (@view a1[[CartesianIndex()], :]) == reshape(a, 1, 60) - @test a1[:, [CartesianIndex()]] == (@view a1[:, [CartesianIndex()]]) == reshape(a, 60, 1) - - @test_throws BoundsError a[[CartesianIndex(1,5),CartesianIndex(2,4)],3:3] - @test_throws BoundsError a[1:4, [CartesianIndex(1,3),CartesianIndex(2,4)]] - @test_throws BoundsError @view a[[CartesianIndex(1,5),CartesianIndex(2,4)],3:3] - @test_throws BoundsError @view a[1:4, [CartesianIndex(1,3),CartesianIndex(2,4)]] - end - - for a in (view(zeros(3, 4, 5), :, :, :), - view(zeros(3, 4, 5), 1:3, :, :)) - a[CartesianIndex{3}(2,3,3)] = -1 - @test a[CartesianIndex{3}(2,3,3)] == -1 - a[1,CartesianIndex{2}(3,4)] = -2 - @test a[1,CartesianIndex{2}(3,4)] == -2 - a[CartesianIndex{1}(2),3,CartesianIndex{1}(3)] = -3 - @test a[CartesianIndex{1}(2),3,CartesianIndex{1}(3)] == -3 - a[[CartesianIndex(1,3),CartesianIndex(2,4)],3:3] = -4 - @test a[1,3,3] == -4 - @test a[2,4,3] == -4 - end - - I1 = CartesianIndex((2,3,0)) - I2 = CartesianIndex((-1,5,2)) - @test -I1 == CartesianIndex((-2,-3,0)) - @test I1 + I2 == CartesianIndex((1,8,2)) - @test I2 + I1 == CartesianIndex((1,8,2)) - @test I1 - I2 == CartesianIndex((3,-2,-2)) - @test I2 - I1 == CartesianIndex((-3,2,2)) - @test I1 + 1 == CartesianIndex((3,4,1)) - @test I1 - 2 == CartesianIndex((0,1,-2)) - - @test zero(CartesianIndex{2}) == CartesianIndex((0,0)) - @test zero(CartesianIndex((2,3))) == CartesianIndex((0,0)) - @test one(CartesianIndex{2}) == CartesianIndex((1,1)) - @test one(CartesianIndex((2,3))) == CartesianIndex((1,1)) - - @test min(CartesianIndex((2,3)), CartesianIndex((5,2))) == CartesianIndex((2,2)) - @test max(CartesianIndex((2,3)), CartesianIndex((5,2))) == CartesianIndex((5,3)) - - # CartesianIndex allows construction at a particular dimensionality - @test length(CartesianIndex{3}()) == 3 - @test length(CartesianIndex{3}(1,2)) == 3 - @test length(CartesianIndex{3}((1,2))) == 3 - @test length(CartesianIndex{3}(1,2,3)) == 3 - @test length(CartesianIndex{3}((1,2,3))) == 3 - @test_throws ArgumentError CartesianIndex{3}(1,2,3,4) - @test_throws ArgumentError CartesianIndex{3}((1,2,3,4)) - - @test length(I1) == 3 - - @test isless(CartesianIndex((1,1)), CartesianIndex((2,1))) - @test isless(CartesianIndex((1,1)), CartesianIndex((1,2))) - @test isless(CartesianIndex((2,1)), CartesianIndex((1,2))) - @test !isless(CartesianIndex((1,2)), CartesianIndex((2,1))) - - a = spzeros(2,3) - @test CartesianRange(size(a)) == eachindex(a) - a[CartesianIndex{2}(2,3)] = 5 - @test a[2,3] == 5 - b = view(a, 1:2, 2:3) - b[CartesianIndex{2}(1,1)] = 7 - @test a[1,2] == 7 - @test 2*CartesianIndex{3}(1,2,3) == CartesianIndex{3}(2,4,6) - - R = CartesianRange(CartesianIndex{2}(2,3),CartesianIndex{2}(5,5)) - @test eltype(R) <: CartesianIndex{2} - @test eltype(typeof(R)) <: CartesianIndex{2} - indexes = collect(R) - @test indexes[1] == CartesianIndex{2}(2,3) - @test indexes[2] == CartesianIndex{2}(3,3) - @test indexes[4] == CartesianIndex{2}(5,3) - @test indexes[5] == CartesianIndex{2}(2,4) - @test indexes[12] == CartesianIndex{2}(5,5) - @test length(indexes) == 12 - @test length(R) == 12 - @test ndims(R) == 2 - @test in(CartesianIndex((2,3)), R) - @test in(CartesianIndex((3,3)), R) - @test in(CartesianIndex((3,5)), R) - @test in(CartesianIndex((5,5)), R) - @test !in(CartesianIndex((1,3)), R) - @test !in(CartesianIndex((3,2)), R) - @test !in(CartesianIndex((3,6)), R) - @test !in(CartesianIndex((6,5)), R) - - @test @inferred(convert(NTuple{2,UnitRange}, R)) === (2:5, 3:5) - @test @inferred(convert(Tuple{Vararg{UnitRange}}, R)) === (2:5, 3:5) - - @test CartesianRange((3:5,-7:7)) == CartesianRange(CartesianIndex{2}(3,-7),CartesianIndex{2}(5,7)) - @test CartesianRange((3,-7:7)) == CartesianRange(CartesianIndex{2}(3,-7),CartesianIndex{2}(3,7)) -end - -# All we really care about is that we have an optimized -# implementation, but the seed is a useful way to check that. -@test hash(CartesianIndex()) == Base.IteratorsMD.cartindexhash_seed -@test hash(CartesianIndex(1, 2)) != hash((1, 2)) - -@testset "itr, start, done, next" begin - r = 2:3 - itr = eachindex(r) - state = start(itr) - @test !done(itr, state) - _, state = next(itr, state) - @test !done(itr, state) - val, state = next(itr, state) - @test done(itr, state) - @test r[val] == 3 - r = sparse(collect(2:3:8)) - itr = eachindex(r) - state = start(itr) - @test !done(itr, state) - _, state = next(itr, state) - _, state = next(itr, state) - @test !done(itr, state) - val, state = next(itr, state) - @test r[val] == 8 - @test done(itr, state) -end - -R = CartesianRange((1,3)) -@test done(R, start(R)) == false -R = CartesianRange((0,3)) -@test done(R, start(R)) == true -R = CartesianRange((3,0)) -@test done(R, start(R)) == true - -@test @inferred(eachindex(Base.IndexCartesian(),zeros(3),zeros(2,2),zeros(2,2,2),zeros(2,2))) == CartesianRange((3,2,2)) -@test @inferred(eachindex(Base.IndexLinear(),zeros(3),zeros(2,2),zeros(2,2,2),zeros(2,2))) == 1:8 -@test @inferred(eachindex(zeros(3),view(zeros(3,3),1:2,1:2),zeros(2,2,2),zeros(2,2))) == CartesianRange((3,2,2)) -@test @inferred(eachindex(zeros(3),zeros(2,2),zeros(2,2,2),zeros(2,2))) == 1:8 - - -@testset "rotates" begin - a = [1 0 0; 0 0 0] - @test rotr90(a,1) == [0 1; 0 0; 0 0] - @test rotr90(a,2) == rot180(a,1) - @test rotr90(a,3) == rotl90(a,1) - @test rotl90(a,3) == rotr90(a,1) - @test rotl90(a,1) == rotr90(a,3) - @test rotl90(a,4) == a - @test rotr90(a,4) == a - @test rot180(a,2) == a -end - -# issue #9648 -let x = fill(1.5f0, 10^7) - @test abs(1.5f7 - cumsum(x)[end]) < 3*eps(1.5f7) - @test cumsum(x) == cumsum!(similar(x), x) -end - -# PR #10164 -@test eltype(Array{Int}) == Int -@test eltype(Array{Int,1}) == Int - -# PR #11080 -let x = fill(0.9, 1000) - @test prod(x) ≈ cumprod(x)[end] -end - -@testset "binary ops on bool arrays" begin - A = Array(trues(5)) - @test A + true == [2,2,2,2,2] - A = Array(trues(5)) - @test A + false == [1,1,1,1,1] - A = Array(trues(5)) - @test true + A == [2,2,2,2,2] - A = Array(trues(5)) - @test false + A == [1,1,1,1,1] - A = Array(trues(5)) - @test A - true == [0,0,0,0,0] - A = Array(trues(5)) - @test A - false == [1,1,1,1,1] - A = Array(trues(5)) - @test true - A == [0,0,0,0,0] - A = Array(trues(5)) - @test false - A == [-1,-1,-1,-1,-1] -end - -@testset "simple transposes" begin - a = ones(Complex,1,5) - b = zeros(Complex,5) - c = ones(Complex,2,5) - d = ones(Complex,6) - @test_throws DimensionMismatch transpose!(a,d) - @test_throws DimensionMismatch transpose!(d,a) - @test_throws DimensionMismatch ctranspose!(a,d) - @test_throws DimensionMismatch ctranspose!(d,a) - @test_throws DimensionMismatch transpose!(b,c) - @test_throws DimensionMismatch ctranspose!(b,c) - @test_throws DimensionMismatch transpose!(c,b) - @test_throws DimensionMismatch ctranspose!(c,b) - transpose!(b,a) - @test b == ones(Complex,5) - b = ones(Complex,5) - a = zeros(Complex,1,5) - transpose!(a,b) - @test a == ones(Complex,1,5) - b = zeros(Complex,5) - ctranspose!(b,a) - @test b == ones(Complex,5) - a = zeros(Complex,1,5) - ctranspose!(a,b) - @test a == ones(Complex,1,5) -end - -@testset "bounds checking for copy!" begin - a = rand(5,3) - b = rand(6,7) - @test_throws BoundsError copy!(a,b) - @test_throws ArgumentError copy!(a,2:3,1:3,b,1:5,2:7) - @test_throws ArgumentError Base.copy_transpose!(a,2:3,1:3,b,1:5,2:7) -end - -module RetTypeDecl - using Base.Test - import Base: +, *, broadcast, convert - - struct MeterUnits{T,P} <: Number - val::T - end - MeterUnits{T}(val::T, pow::Int) = MeterUnits{T,pow}(val) - - m = MeterUnits(1.0, 1) # 1.0 meter, i.e. units of length - m2 = MeterUnits(1.0, 2) # 1.0 meter^2, i.e. units of area - - (+){T,pow}(x::MeterUnits{T,pow}, y::MeterUnits{T,pow}) = MeterUnits{T,pow}(x.val+y.val) - (*){T,pow}(x::Int, y::MeterUnits{T,pow}) = MeterUnits{typeof(x*one(T)),pow}(x*y.val) - (*){T}(x::MeterUnits{T,1}, y::MeterUnits{T,1}) = MeterUnits{T,2}(x.val*y.val) - broadcast{T}(::typeof(*), x::MeterUnits{T,1}, y::MeterUnits{T,1}) = MeterUnits{T,2}(x.val*y.val) - convert{T,pow}(::Type{MeterUnits{T,pow}}, y::Real) = MeterUnits{T,pow}(convert(T,y)) - - @test @inferred(m+[m,m]) == [m+m,m+m] - @test @inferred([m,m]+m) == [m+m,m+m] - @test @inferred(broadcast(*,m,[m,m])) == [m2,m2] - @test @inferred(broadcast(*,[m,m],m)) == [m2,m2] - @test @inferred([m 2m; m m]*[m,m]) == [3m2,2m2] - @test @inferred(broadcast(*,[m m],[m,m])) == [m2 m2; m2 m2] -end - -# range, range ops -A = 1:5 -B = 1.5:5.5 -@test A + B == 2.5:2.0:10.5 - -@testset "slicedim" begin - for A in (reshape(collect(1:20), 4, 5), - reshape(1:20, 4, 5)) - @test slicedim(A, 1, 2) == collect(2:4:20) - @test slicedim(A, 2, 2) == collect(5:8) - @test_throws ArgumentError slicedim(A,0,1) - @test slicedim(A, 3, 1) == A - @test_throws BoundsError slicedim(A, 3, 2) - @test @inferred(slicedim(A, 1, 2:2)) == collect(2:4:20)' - end -end - -### -### IndexCartesian workout -### -struct LinSlowMatrix{T} <: DenseArray{T,2} - data::Matrix{T} -end - -# This is the default, but just to be sure -Base.IndexStyle{A<:LinSlowMatrix}(::Type{A}) = Base.IndexCartesian() - -Base.size(A::LinSlowMatrix) = size(A.data) - -Base.getindex(A::LinSlowMatrix, i::Integer) = error("Not defined") -Base.getindex(A::LinSlowMatrix, i::Integer, j::Integer) = A.data[i,j] - -Base.setindex!(A::LinSlowMatrix, v, i::Integer) = error("Not defined") -Base.setindex!(A::LinSlowMatrix, v, i::Integer, j::Integer) = A.data[i,j] = v - -A = rand(3,5) -B = LinSlowMatrix(A) -S = view(A, :, :) - -@test A == B -@test B == A -@test isequal(A, B) -@test isequal(B, A) - -for (a,b) in zip(A, B) - @test a == b -end -for (a,s) in zip(A, S) - @test a == s -end - -C = copy(B) -@test A == C -@test B == C - -@test vec(A) == vec(B) == vec(S) -@test minimum(A) == minimum(B) == minimum(S) -@test maximum(A) == maximum(B) == maximum(S) - -a, ai = findmin(A) -b, bi = findmin(B) -s, si = findmin(S) -@test a == b == s -@test ai == bi == si - -a, ai = findmax(A) -b, bi = findmax(B) -s, si = findmax(S) -@test a == b == s -@test ai == bi == si - -fill!(B, 2) -@test all(x->x==2, B) - -iall = (1:size(A,1)).*ones(Int,size(A,2))' -jall = ones(Int,size(A,1)).*(1:size(A,2))' -i,j = findn(B) -@test vec(i) == vec(iall) -@test vec(j) == vec(jall) -fill!(S, 2) -i,j = findn(S) -@test vec(i) == vec(iall) -@test vec(j) == vec(jall) - -copy!(B, A) -copy!(S, A) - -@test cat(1, A, B, S) == cat(1, A, A, A) -@test cat(2, A, B, S) == cat(2, A, A, A) - -@test cumsum(A, 1) == cumsum(B, 1) == cumsum(S, 1) -@test cumsum(A, 2) == cumsum(B, 2) == cumsum(S, 2) - -@test mapslices(sort, A, 1) == mapslices(sort, B, 1) == mapslices(sort, S, 1) -@test mapslices(sort, A, 2) == mapslices(sort, B, 2) == mapslices(sort, S, 2) - -@test flipdim(A, 1) == flipdim(B, 1) == flipdim(S, 2) -@test flipdim(A, 2) == flipdim(B, 2) == flipdim(S, 2) - -@test A + 1 == B + 1 == S + 1 -@test 2*A == 2*B == 2*S -@test A/3 == B/3 == S/3 - -# issue #13250 -x13250 = zeros(3) -x13250[UInt(1):UInt(2)] = 1.0 -@test x13250[1] == 1.0 -@test x13250[2] == 1.0 -@test x13250[3] == 0.0 - -struct SquaresVector <: AbstractArray{Int, 1} - count::Int -end -Base.size(S::SquaresVector) = (S.count,) -Base.IndexStyle(::Type{SquaresVector}) = Base.IndexLinear() -Base.getindex(S::SquaresVector, i::Int) = i*i -foo_squares = SquaresVector(5) -@test convert(Array{Int}, foo_squares) == [1,4,9,16,25] -@test convert(Array{Int, 1}, foo_squares) == [1,4,9,16,25] - -# issue #13254 -let A = zeros(Int, 2, 2), B = zeros(Float64, 2, 2) - f1() = [1] - f2() = [1;] - f3() = [1;2] - f4() = [1;2.0] - f5() = [1 2] - f6() = [1 2.0] - f7() = Int[1] - f8() = Float64[1] - f9() = Int[1;] - f10() = Float64[1;] - f11() = Int[1;2] - f12() = Float64[1;2] - f13() = Int[1;2.0] - f14() = Int[1 2] - f15() = Float64[1 2] - f16() = Int[1 2.0] - f17() = [1:2;] - f18() = Int[1:2;] - f19() = Float64[1:2;] - f20() = [1:2;1:2] - f21() = Int[1:2;1:2] - f22() = Float64[1:2;1:2] - f23() = [1:2;1.0:2.0] - f24() = Int[1:2;1.0:2.0] - f25() = [1:2 1:2] - f26() = Int[1:2 1:2] - f27() = Float64[1:2 1:2] - f28() = [1:2 1.0:2.0] - f29() = Int[1:2 1.0:2.0] - f30() = [A;] - f31() = Int[A;] - f32() = Float64[A;] - f33() = [A;A] - f34() = Int[A;A] - f35() = Float64[A;A] - f36() = [A;B] - f37() = Int[A;B] - f38() = [A A] - f39() = Int[A A] - f40() = Float64[A A] - f41() = [A B] - f42() = Int[A B] - - for f in [f1, f2, f3, f4, f5, f6, f7, f8, f9, f10, f11, f12, f13, f14, f15, f16, - f17, f18, f19, f20, f21, f22, f23, f24, f25, f26, f27, f28, f29, f30, - f31, f32, f33, f34, f35, f36, f37, f38, f39, f40, f41, f42] - @test isleaftype(Base.return_types(f, ())[1]) - end -end - -# issue #14482 -@inferred map(Int8, Int[0]) - -# make sure @inbounds isn't used too much -mutable struct OOB_Functor{T}; a::T; end -(f::OOB_Functor)(i::Int) = f.a[i] -let f = OOB_Functor([1,2]) - @test_throws BoundsError map(f, [1,2,3,4,5]) -end - - -# issue 15654 -@test cumprod([5], 2) == [5] -@test cumprod([1 2; 3 4], 3) == [1 2; 3 4] -@test cumprod([1 2; 3 4], 1) == [1 2; 3 8] -@test cumprod([1 2; 3 4], 2) == [1 2; 3 12] - -@test cumsum([5], 2) == [5] -@test cumsum([1 2; 3 4], 1) == [1 2; 4 6] -@test cumsum([1 2; 3 4], 2) == [1 3; 3 7] -@test cumsum([1 2; 3 4], 3) == [1 2; 3 4] - -# issue #18363 -@test_throws DimensionMismatch cumsum!([0,0], 1:4) -@test cumsum(Any[])::Vector{Any} == Any[] -@test cumsum(Any[1, 2.3])::Vector{Any} == [1, 3.3] == cumsum(Real[1, 2.3])::Vector{Real} -@test cumsum([true,true,true]) == [1,2,3] -@test cumsum(0x00:0xff)[end] === 0x80 # overflow -@test cumsum([[true], [true], [false]])::Vector{Vector{Int}} == [[1], [2], [2]] - -#issue #18336 -@test cumsum([-0.0, -0.0])[1] === cumsum([-0.0, -0.0])[2] === -0.0 -@test cumprod(-0.0im + (0:0))[1] === Complex(0.0, -0.0) - -module TestNLoops15895 - -using Base.Cartesian -using Base.Test - -# issue 15894 -function f15894(d) - s = zero(eltype(d)) - @nloops 1 i d begin - s += @nref 1 d i - end - s -end -@test f15894(ones(Int, 100)) == 100 -end - -@testset "sign, conj, ~" begin - A = [-10,0,3] - B = [-10.0,0.0,3.0] - C = [1,im,0] - - @test sign.(A) == [-1,0,1] - @test sign.(B) == [-1,0,1] - @test typeof(sign.(A)) == Vector{Int} - @test typeof(sign.(B)) == Vector{Float64} - - @test conj(A) == A - @test conj(B) == A - @test conj(C) == [1,-im,0] - @test typeof(conj(A)) == Vector{Int} - @test typeof(conj(B)) == Vector{Float64} - @test typeof(conj(C)) == Vector{Complex{Int}} - - @test .~A == [9,-1,-4] - @test typeof(.~A) == Vector{Int} -end - -@testset "issue #16247" begin - A = zeros(3,3) - @test size(A[:,0x1:0x2]) == (3, 2) - @test size(A[:,UInt(1):UInt(2)]) == (3,2) - @test size(similar(A, UInt(3), 0x3)) == size(similar(A, (UInt(3), 0x3))) == (3,3) -end - -# issue 17254 -module AutoRetType - -using Base.Test - -struct Foo end -for op in (:+, :*, :÷, :%, :<<, :>>, :-, :/, :\, ://, :^) - @eval import Base.$(op) - @eval $(op)(::Foo, ::Foo) = Foo() -end -A = fill(Foo(), 10, 10) -@test typeof(A+A) == Matrix{Foo} -@test typeof(A-A) == Matrix{Foo} -for op in (:.+, :.*, :.÷, :.%, :.<<, :.>>, :.-, :./, :.\, :.//, :.^) - @eval @test typeof($(op)(A,A)) == Matrix{Foo} -end - -end # module AutoRetType - -@testset "concatenations of dense matrices/vectors yield dense matrices/vectors" begin - N = 4 - densevec = ones(N) - densemat = diagm(ones(N)) - # Test that concatenations of homogeneous pairs of either dense matrices or dense vectors - # (i.e., Matrix-Matrix concatenations, and Vector-Vector concatenations) yield dense arrays - for densearray in (densevec, densemat) - @test isa(vcat(densearray, densearray), Array) - @test isa(hcat(densearray, densearray), Array) - @test isa(hvcat((2,), densearray, densearray), Array) - @test isa(cat((1,2), densearray, densearray), Array) - end - @test isa([[1,2,3]'; [1,2,3]'], Matrix{Int}) - @test isa([[1,2,3]' [1,2,3]'], RowVector{Int, Vector{Int}}) - @test isa([Any[1.0, 2]'; Any[2.0, 2]'], Matrix{Any}) - @test isa([Any[1.0, 2]' Any[2.0, 2']'], RowVector{Any, Vector{Any}}) - # Test that concatenations of heterogeneous Matrix-Vector pairs yield dense matrices - @test isa(hcat(densemat, densevec), Array) - @test isa(hcat(densevec, densemat), Array) - @test isa(hvcat((2,), densemat, densevec), Array) - @test isa(hvcat((2,), densevec, densemat), Array) - @test isa(cat((1,2), densemat, densevec), Array) - @test isa(cat((1,2), densevec, densemat), Array) -end - -@testset "type constructor Array{T, N}(d...) works (especially for N>3)" begin - a = Array{Float64}(10) - b = Array{Float64, 1}(10) - @test size(a) == (10,) - @test size(a, 1) == 10 - @test size(a,2,1) == (1,10) - @test size(a) == size(b) - a = Array{Float64}(2,3) - b = Array{Float64, 2}(2,3) - @test size(a) == (2,3) - @test size(a,4,3,2,1) == (1,1,3,2) - @test size(a,1,2) == (2,3) - @test size(a) == size(b) - a = Array{Float64}(9,8,7,6,5,4,3,2,1) - b = Array{Float64, 9}(9,8,7,6,5,4,3,2,1) - @test size(a,1,1) == (9,9) - @test size(a,4) == 6 - @test size(a,9,8,7,6,5,4,3,2,19,8,7,6,5,4,3,2,1) == (1,2,3,4,5,6,7,8,1,2,3,4,5,6,7,8,9) - @test size(a) == size(b) -end - -@testset "accumulate, accumulate!" begin - @test accumulate(+, [1,2,3]) == [1, 3, 6] - @test accumulate(min, [1 2; 3 4], 1) == [1 2; 1 2] - @test accumulate(max, [1 2; 3 0], 2) == [1 2; 3 3] - @test accumulate(+, Bool[]) == Int[] - @test accumulate(*, Bool[]) == Bool[] - @test accumulate(+, Float64[]) == Float64[] - - @test accumulate(min, [1, 2, 5, -1, 3, -2]) == [1, 1, 1, -1, -1, -2] - @test accumulate(max, [1, 2, 5, -1, 3, -2]) == [1, 2, 5, 5, 5, 5] - - @test accumulate(max, [1 0; 0 1], 1) == [1 0; 1 1] - @test accumulate(max, [1 0; 0 1], 2) == [1 1; 0 1] - @test accumulate(min, [1 0; 0 1], 1) == [1 0; 0 0] - @test accumulate(min, [1 0; 0 1], 2) == [1 0; 0 0] - - @test isa(accumulate(+, Int[]) , Vector{Int}) - @test isa(accumulate(+, 1., Int[]) , Vector{Float64}) - @test accumulate(+, 1, [1,2]) == [2, 4] - arr = randn(4) - @test accumulate(*, 1, arr) ≈ accumulate(*, arr) - - N = 5 - for arr in [rand(Float64, N), rand(Bool, N), rand(-2:2, N)] - for (op, cumop) in [(+, cumsum), (*, cumprod)] - @inferred accumulate(op, arr) - accumulate_arr = accumulate(op, arr) - @test accumulate_arr ≈ cumop(arr) - @test accumulate_arr[end] ≈ reduce(op, arr) - @test accumulate_arr[1] ≈ arr[1] - @test accumulate(op, arr, 10) ≈ arr - - if eltype(arr) in [Int, Float64] # eltype of out easy - out = similar(arr) - @test accumulate!(op, out, arr) ≈ accumulate_arr - @test out ≈ accumulate_arr - end - end - end - - # exotic indexing - arr = randn(4) - oarr = OffsetArray(arr, (-3,)) - @test accumulate(+, oarr).parent == accumulate(+, arr) - - @inferred accumulate(+, randn(3)) - @inferred accumulate(+, 1, randn(3)) - - # asymmetric operation - op(x,y) = 2x+y - @test accumulate(op, [10,20, 30]) == [10, op(10, 20), op(op(10, 20), 30)] == [10, 40, 110] - @test accumulate(op, [10 20 30], 2) == [10 op(10, 20) op(op(10, 20), 30)] == [10 40 110] -end - -@testset "zeros and ones" begin - @test ones([1,2], Float64, (2,3)) == ones(2,3) - @test ones(2) == ones(Int, 2) == ones([2,3], Float32, 2) == [1,1] - @test isa(ones(2), Vector{Float64}) - @test isa(ones(Int, 2), Vector{Int}) - @test isa(ones([2,3], Float32, 2), Vector{Float32}) - - function test_zeros(arr, T, s) - @test all(arr .== 0) - @test isa(arr, T) - @test size(arr) == s - end - test_zeros(zeros(), Array{Float64, 0}, ()) - test_zeros(zeros(2), Vector{Float64}, (2,)) - test_zeros(zeros(2,3), Matrix{Float64}, (2,3)) - test_zeros(zeros((2,3)), Matrix{Float64}, (2,3)) - - test_zeros(zeros(Int, 6), Vector{Int}, (6,)) - test_zeros(zeros(Int, 2, 3), Matrix{Int}, (2,3)) - test_zeros(zeros(Int, (2, 3)), Matrix{Int}, (2,3)) - - test_zeros(zeros([1 2; 3 4]), Matrix{Int}, (2, 2)) - test_zeros(zeros([1 2; 3 4], Float64), Matrix{Float64}, (2, 2)) - - zs = zeros(SparseMatrixCSC([1 2; 3 4]), Complex{Float64}, (2,3)) - test_zeros(zs, SparseMatrixCSC{Complex{Float64}}, (2, 3)) - - # #19265" - @test_throws ErrorException zeros(Float64, [1.]) # TODO change to MethodError, when v0.6 deprecations are done - x = [1.] - test_zeros(zeros(x, Float64), Vector{Float64}, (1,)) - @test x == [1.] - - # exotic indexing - oarr = zeros(randn(3), UInt16, 1:3, -1:0) - @test indices(oarr) == (1:3, -1:0) - test_zeros(oarr.parent, Matrix{UInt16}, (3, 2)) -end - -# issue #11053 -mutable struct T11053 - a::Float64 -end -Base.:*(a::T11053, b::Real) = T11053(a.a*b) -Base.:(==)(a::T11053, b::T11053) = a.a == b.a -@test [T11053(1)] * 5 == [T11053(1)] .* 5 == [T11053(5.0)] - -#15907 -@test typeof(Array{Int,0}()) == Array{Int,0} - -@testset "issue 23629" begin - @test_throws BoundsError zeros(2,3,0)[2,3] - @test_throws BoundsError checkbounds(zeros(2,3,0), 2, 3) -end - -# issue #27072 -function type_testB27072(B::StridedArray) - return typeof(similar(B, size(B))) -end -@testset "issue 27072: manually added, non-backported test" begin - bb_inp = reshape(eye(2^8), fill(2,16)...); - @test typeof(similar(bb_inp, size(bb_inp))) === Array{Float64,16} - @test type_testB27072(bb_inp) === Array{Float64,16} -end diff --git a/julia-0.6.3/share/julia/test/asmvariant.jl b/julia-0.6.3/share/julia/test/asmvariant.jl deleted file mode 100644 index 2720999..0000000 --- a/julia-0.6.3/share/julia/test/asmvariant.jl +++ /dev/null @@ -1,32 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -using Base.Test - -ix86 = r"i[356]86" - -if Sys.ARCH === :x86_64 || ismatch(ix86, string(Sys.ARCH)) - function linear_foo() - x = 4 - y = 5 - end - - rgx = r"%" - buf = IOBuffer() - output="" - #test that the string output is at&t syntax by checking for occurrences of '%'s - code_native(buf,linear_foo,(),:att) - output=String(take!(buf)) - - @test ismatch(rgx,output) - - #test that the code output is intel syntax by checking it has no occurrences of '%' - code_native(buf,linear_foo,(),:intel) - output=String(take!(buf)) - - @test !(ismatch(rgx,output)) - - code_native(buf,linear_foo,()) - output=String(take!(buf)) - - @test ismatch(rgx, output) -end diff --git a/julia-0.6.3/share/julia/test/backtrace.jl b/julia-0.6.3/share/julia/test/backtrace.jl deleted file mode 100644 index 3c4d5ab..0000000 --- a/julia-0.6.3/share/julia/test/backtrace.jl +++ /dev/null @@ -1,151 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -bt = backtrace() -have_backtrace = false -for l in bt - lkup = ccall(:jl_lookup_code_address, Any, (Ptr{Void}, Cint), l, true) - if lkup[1][1] == :backtrace - @test lkup[1][5] == false # fromC - have_backtrace = true - break - end -end - -@test have_backtrace - -# Test location information for inlined code (ref issues #1334 #12544) -module test_inline_bt -using Base.Test - -function get_bt_frames(functionname, bt) - for i = 1:length(bt) - lkup = Base.StackTraces.lookup(bt[i]) - lkup[end].func == functionname && (return lkup) - end -end - -# same-file inline -eval(Expr(:function, Expr(:call, :test_inline_1), - Expr(:block, Expr(:line, 99, Symbol("backtrace.jl")), - Expr(:block, Expr(:line, 42), - Expr(:meta, :push_loc, Symbol("backtrace.jl"), :inlfunc), - Expr(:line, 37), - Expr(:call, :throw, "foo"), - Expr(:meta, :pop_loc), - Expr(:line, 99))))) - -@test functionloc(test_inline_1) == ("backtrace.jl", 99) -try - test_inline_1() - error("unexpected") -catch err - lkup = get_bt_frames(:test_inline_1, catch_backtrace()) - @test length(lkup) == 2 - @test endswith(string(lkup[2].file), "backtrace.jl") - @test lkup[2].line == 42 - @test lkup[1].func == :inlfunc - @test endswith(string(lkup[1].file), "backtrace.jl") - @test lkup[1].line == 37 -end - -# different-file inline -const absfilepath = is_windows() ? "C:\\foo\\bar\\baz.jl" : "/foo/bar/baz.jl" -eval(Expr(:function, Expr(:call, :test_inline_2), - Expr(:block, Expr(:line, 81, Symbol("backtrace.jl")), - Expr(:block, Expr(:meta, :push_loc, Symbol(absfilepath)), - Expr(:line, 111), - Expr(:call, :throw, "foo"), - Expr(:meta, :pop_loc), - Expr(:line, 99))))) - -@test functionloc(test_inline_2) == ("backtrace.jl", 81) -try - test_inline_2() - error("unexpected") -catch err - lkup = get_bt_frames(:test_inline_2, catch_backtrace()) - @test length(lkup) == 2 - @test endswith(string(lkup[2].file), "backtrace.jl") - @test lkup[2].line == 81 - @test string(lkup[1].file) == absfilepath - @test lkup[1].line == 111 -end - -end # module - -#issue 12977: line numbers for kwarg methods. -linenum = @__LINE__; f12977(; args...) = () -loc = functionloc(f12977) -@test endswith(loc[1], "backtrace.jl") -@test loc[2] == linenum - -@noinline function test_throw_commoning(x) - if x==1; throw(AssertionError()); end - if x==2; throw(AssertionError()); end -end - -let - local b1, b2 - try - test_throw_commoning(1) - catch - b1 = stacktrace(catch_backtrace()) - end - try - test_throw_commoning(2) - catch - b2 = stacktrace(catch_backtrace()) - end - i1 = findfirst(frame -> frame.func === :test_throw_commoning, b1) - i2 = findfirst(frame -> frame.func === :test_throw_commoning, b2) - @test i1 > 0 && i2 > 0 - @test b1[i1].line != b2[i2].line -end - -module BackTraceTesting - -using Base.Test - -@inline bt2() = backtrace() -@inline bt1() = bt2() -bt() = bt1() - -lkup = map(StackTraces.lookup, bt()) -hasbt = hasbt2 = false -for sfs in lkup - for sf in sfs - if sf.func == :bt - hasbt = true - end - if sf.func == :bt2 - hasbt2 = true - end - end -end -@test hasbt -if Base.JLOptions().can_inline != 0 - @test_broken hasbt2 -else - @test hasbt2 -end - -function btmacro() - ret = @timed backtrace() - ret[1] -end -lkup = map(StackTraces.lookup, btmacro()) -hasme = hasbtmacro = false -for sfs in lkup - for sf in sfs - if sf.func == Symbol("macro expansion") - hasme = true - end - if sf.func == :btmacro - hasbtmacro = true - end - end -end -@test hasme -@test hasbtmacro - -end diff --git a/julia-0.6.3/share/julia/test/base64.jl b/julia-0.6.3/share/julia/test/base64.jl deleted file mode 100644 index c35bce3..0000000 --- a/julia-0.6.3/share/julia/test/base64.jl +++ /dev/null @@ -1,46 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -const inputText = "Man is distinguished, not only by his reason, but by this singular passion from other animals, which is a lust of the mind, that by a perseverance of delight in the continued and indefatigable generation of knowledge, exceeds the short vehemence of any carnal pleasure." -const encodedMaxLine76 = -"""TWFuIGlzIGRpc3Rpbmd1aXNoZWQsIG5vdCBvbmx5IGJ5IGhpcyByZWFzb24sIGJ1dCBieSB0aGlz -IHNpbmd1bGFyIHBhc3Npb24gZnJvbSBvdGhlciBhbmltYWxzLCB3aGljaCBpcyBhIGx1c3Qgb2Yg -dGhlIG1pbmQsIHRoYXQgYnkgYSBwZXJzZXZlcmFuY2Ugb2YgZGVsaWdodCBpbiB0aGUgY29udGlu -dWVkIGFuZCBpbmRlZmF0aWdhYmxlIGdlbmVyYXRpb24gb2Yga25vd2xlZGdlLCBleGNlZWRzIHRo -ZSBzaG9ydCB2ZWhlbWVuY2Ugb2YgYW55IGNhcm5hbCBwbGVhc3VyZS4=""" - -# Encode and decode -fname = tempname() -open(fname, "w") do f - opipe = Base64EncodePipe(f) - write(opipe,inputText) - @test close(opipe) === nothing -end - -open(fname, "r") do f - ipipe = Base64DecodePipe(f) - @test readstring(ipipe) == inputText - @test close(ipipe) === nothing -end -rm(fname) - -# Encode to string and decode -@test String(base64decode(base64encode(inputText))) == inputText - -# Decode with max line chars = 76 and padding -ipipe = Base64DecodePipe(IOBuffer(encodedMaxLine76)) -@test readstring(ipipe) == inputText - -# Decode with max line chars = 76 and no padding -ipipe = Base64DecodePipe(IOBuffer(encodedMaxLine76[1:end-1])) -@test readstring(ipipe) == inputText - -# Decode with two padding characters ("==") -ipipe = Base64DecodePipe(IOBuffer(string(encodedMaxLine76[1:end-2],"=="))) -@test readstring(ipipe) == inputText[1:end-1] - -# Test incorrect format -ipipe = Base64DecodePipe(IOBuffer(encodedMaxLine76[1:end-3])) -@test_throws ArgumentError readstring(ipipe) - -# issue #21314 -@test base64decode(chomp("test")) == base64decode("test") diff --git a/julia-0.6.3/share/julia/test/bigfloat.jl b/julia-0.6.3/share/julia/test/bigfloat.jl deleted file mode 100644 index bef4c0c..0000000 --- a/julia-0.6.3/share/julia/test/bigfloat.jl +++ /dev/null @@ -1,11 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -@test big(2.0)^big(3) == 8 - -for T in [Int8, UInt8, Int16, UInt16, Int32, UInt32, Int64, UInt64, Int128, UInt128, BigInt] - @test T(2)^big(3.0) == 8 - @test big(2.0)^T(3) == 8 -end - -# issue 15659 -@test (setprecision(53) do; big(1/3); end) < 1//3 diff --git a/julia-0.6.3/share/julia/test/bigint.jl b/julia-0.6.3/share/julia/test/bigint.jl deleted file mode 100644 index 771e634..0000000 --- a/julia-0.6.3/share/julia/test/bigint.jl +++ /dev/null @@ -1,363 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -a = parse(BigInt,"123456789012345678901234567890") -b = parse(BigInt,"123456789012345678901234567891") - -@test typeof(a+1) == BigInt -@test a+1 == b -@test isequal(a+1, b) -@test b == a+1 -@test !(b == a) -@test b > a -@test b >= a -@test !(b < a) -@test !(b <= a) - -c = parse(BigInt,"246913578024691357802469135780") -@test typeof(a * 2) == BigInt -@test a*2 == c -@test c-a == a -@test c == a + a -@test c+1 == a+b - -d = parse(BigInt,"-246913578024691357802469135780") -@test typeof(d) == BigInt -@test d == -c - -ee = typemax(Int64) -@test typeof(BigInt(ee)) == BigInt -@test BigInt(ee)+1 == parse(BigInt,"9223372036854775808") - -#Multiple calls for sanity check, since we're doing direct memory manipulation -@test string(a) == "123456789012345678901234567890" -@test string(b) == "123456789012345678901234567891" -@test string(c) == "246913578024691357802469135780" -@test string(d) == "-246913578024691357802469135780" -@test string(a) == "123456789012345678901234567890" - -for i = -10:10, j = [-10:-1; 1:10] - @test div(BigInt(i), BigInt(j)) == div(i,j) - @test fld(BigInt(i), BigInt(j)) == fld(i,j) - @test mod(BigInt(i), BigInt(j)) == mod(i,j) - @test rem(BigInt(i), BigInt(j)) == rem(i,j) -end - -@test typeof(BigInt(typemax(Int8))) == BigInt -@test typeof(BigInt(typemax(Int16))) == BigInt -@test typeof(BigInt(typemax(Int32))) == BigInt -@test typeof(BigInt(typemax(Int64))) == BigInt -@test typeof(BigInt(typemax(Int128))) == BigInt - -@test typeof(BigInt(true)) == BigInt -@test typeof(BigInt(typemax(UInt8))) == BigInt -@test typeof(BigInt(typemax(UInt16))) == BigInt -@test typeof(BigInt(typemax(UInt32))) == BigInt -@test typeof(BigInt(typemax(UInt64))) == BigInt -@test typeof(BigInt(typemax(UInt128))) == BigInt - -@test typeof(BigInt(BigInt(1))) == BigInt - - -# Signed addition -@test a+Int8(1) == b -@test a+Int16(1) == b -@test a+Int32(1) == b -@test a+Int64(1) == b -@test a+Int128(1) == b -@test Int8(1)+ a == b -@test Int16(1)+a == b -@test Int32(1)+a == b -@test Int64(1)+a == b -@test b+Int8(-1) == a -@test b+Int16(-1) == a -@test b+Int32(-1) == a -@test b+Int64(-1) == a -@test Int8(-1)+ b == a -@test Int16(-1)+b == a -@test Int32(-1)+b == a -@test Int64(-1)+b == a - -# Unsigned addition -@test a+true == b -@test a+UInt8(1) == b -@test a+UInt16(1) == b -@test a+UInt32(1) == b -@test a+UInt64(1) == b -@test a+UInt128(1) == b -@test true+a == b -@test UInt8(1)+ a == b -@test UInt16(1)+a == b -@test UInt32(1)+a == b -@test UInt64(1)+a == b - -# Signed subtraction -@test b-Int8(1) == a -@test b-Int16(1) == a -@test b-Int32(1) == a -@test b-Int64(1) == a -@test Int8(1)- b == -a -@test Int16(1)-b == -a -@test Int32(1)-b == -a -@test Int64(1)-b == -a -@test a-Int8(-1) == b -@test a-Int16(-1) == b -@test a-Int32(-1) == b -@test a-Int64(-1) == b -@test Int8(-1)- a == -b -@test Int16(-1)-a == -b -@test Int32(-1)-a == -b -@test Int64(-1)-a == -b - -# Unsigned subtraction -@test b-true == a -@test b-UInt8(1) == a -@test b-UInt16(1) == a -@test b-UInt32(1) == a -@test b-UInt64(1) == a -@test true-b == -a -@test UInt8(1)- b == -a -@test UInt16(1)-b == -a -@test UInt32(1)-b == -a -@test UInt64(1)-b == -a - -# Signed multiplication -@test a*Int8(1) == a -@test a*Int16(1) == a -@test a*Int32(1) == a -@test a*Int64(1) == a -@test Int8(1)* a == a -@test Int16(1)*a == a -@test Int32(1)*a == a -@test Int64(1)*a == a -@test a*Int8(-1) == -a -@test a*Int16(-1) == -a -@test a*Int32(-1) == -a -@test a*Int64(-1) == -a -@test Int8(-1)* a == -a -@test Int16(-1)*a == -a -@test Int32(-1)*a == -a -@test Int64(-1)*a == -a - -# Unsigned multiplication -@test a*true == a -@test a*UInt8(1) == a -@test a*UInt16(1) == a -@test a*UInt32(1) == a -@test a*UInt64(1) == a -@test true*a == a -@test UInt8(1)* a == a -@test UInt16(1)*a == a -@test UInt32(1)*a == a -@test UInt64(1)*a == a - -@test a+BigInt(1) == b - -@test BigInt(5) << 3 == 40 -@test BigInt(5) >> 1 == 2 -@test BigInt(-5) << 3 == -40 -@test BigInt(-5) >> 1 == -3 -@test BigInt(5) >> -3 == 40 -@test BigInt(5) << -1 == 2 -@test BigInt(-5) >> -3 == -40 -@test BigInt(-5) << -1 == -3 - -@test ~BigInt(123) == -124 -@test BigInt(123) & BigInt(234) == 106 -@test BigInt(123) | BigInt(234) == 251 -@test BigInt(123) ⊻ BigInt(234) == 145 - -@test gcd(BigInt(48), BigInt(180)) == 12 -@test lcm(BigInt(48), BigInt(180)) == 720 - -@test factorial(BigInt(40)) == parse(BigInt,"815915283247897734345611269596115894272000000000") -@test binomial(BigInt(1), -1) == BigInt(0) -@test binomial(BigInt(1), 2) == BigInt(0) -@test binomial(BigInt(-53), 42) == parse(BigInt,"959509335087854414441273718") -@test binomial(BigInt(113), BigInt(42)) == parse(BigInt,"18672199984318438125634054194360") - -a = rand(1:100, 10000) -b = map(BigInt, a) -@test sum(a) == sum(b) - -# Iterated arithmetic -a = parse(BigInt,"315135") -b = parse(BigInt,"12412") -c = parse(BigInt,"3426495623485904783478347") -d = parse(BigInt,"-1398984130") -f = parse(BigInt,"2413804710837418037418307081437315263635345357386985747464") -g = parse(BigInt,"-1") - -@test +(a, b) == parse(BigInt,"327547") -@test +(a, b, c) == parse(BigInt,"3426495623485904783805894") -@test +(a, b, c, d) == parse(BigInt,"3426495623485903384821764") -@test +(a, b, c, d, f) == parse(BigInt,"2413804710837418037418307081437318690130968843290370569228") -@test +(a, b, c, d, f, g) == parse(BigInt,"2413804710837418037418307081437318690130968843290370569227") - -@test *(a, b) == parse(BigInt,"3911455620") -@test *(a, b, c) == parse(BigInt,"13402585563389346256121263521460140") -@test *(a, b, c, d) == parse(BigInt,"-18750004504148804423388563022070650287578200") -@test *(a, b, c, d, f) == parse(BigInt,"-45258849200337190631492857400003938881995610529251881450243326128168934937055005474972396281351684800") -@test *(a, b, c, d, f, g) == parse(BigInt,"45258849200337190631492857400003938881995610529251881450243326128168934937055005474972396281351684800") - -@test xor(a, b) == parse(BigInt,"327299") -@test xor(a, b, c) == parse(BigInt,"3426495623485904783798472") -@test xor(a, b, c, d) == parse(BigInt,"-3426495623485906178489610") -@test xor(a, b, c, d, f) == parse(BigInt,"-2413804710837418037418307081437316711364709261074607933698") -@test xor(a, b, c, d, f, g) == parse(BigInt,"2413804710837418037418307081437316711364709261074607933697") - -@test (&)(a, b) == parse(BigInt,"124") -@test (&)(a, b, c) == parse(BigInt,"72") -@test (&)(a, b, c, d) == parse(BigInt,"8") -@test (&)(a, b, c, d, f) == parse(BigInt,"8") -@test (&)(a, b, c, d, f, g) == parse(BigInt,"8") - -@test (|)(a, b) == parse(BigInt,"327423") -@test (|)(a, b, c) == parse(BigInt,"3426495623485904783802111") -@test (|)(a, b, c, d) == parse(BigInt,"-1396834561") -@test (|)(a, b, c, d, f) == parse(BigInt,"-1358954753") -@test (|)(a, b, c, d, f, g) == parse(BigInt,"-1") - - -@test trailing_ones(a) == 8 -@test trailing_zeros(b) == 2 -@test count_ones(a) == 14 - -# Large Fibonacci to exercise BigInt -# from Bill Hart, https://groups.google.com/group/julia-dev/browse_frm/thread/798e2d1322daf633 -function mul(a::Vector{BigInt}, b::Vector{BigInt}) - x = a[2]*b[2] - c = Array{BigInt,1}(3) - c[1] = a[1]*b[1] + x - c[2] = a[1]*b[2] + a[2]*b[3] - c[3] = x + a[3]*b[3] - return c -end - -function bigfib(n) - n == 0 && return BigInt(0) - n -= 1 - r = [BigInt(1), BigInt(1), BigInt(0)] - s = [BigInt(1), BigInt(0), BigInt(1)] - while true - (n & 1) == 1 && (s = mul(s,r)) - (n >>= 1) == 0 && return s[1] - r = mul(r,r) - end -end -@test [bigfib(n) for n=0:10] == [0,1,1,2,3,5,8,13,21,34,55] - -n = bigfib(1000001) -@test ndigits(n) == 208988 -@test mod(n,big(10)^15) == 359244926937501 -@test div(n,big(10)^208973) == 316047687386689 - -s = string(n) -@test length(s) == 208988 -@test endswith(s, "359244926937501") -@test startswith(s, "316047687386689") - -# serialization (#5133) -let n = parse(BigInt,"359334085968622831041960188598043661065388726959079837") - b = IOBuffer() - serialize(b,n) - seek(b,0) - @test deserialize(b) == n -end - -# issue #5873 -@test ndigits(big(90)) == 2 -@test ndigits(big(99)) == 2 -ndigits_mismatch(n) = ndigits(n) != ndigits(BigInt(n)) -@test !any(ndigits_mismatch, 8:9) -@test !any(ndigits_mismatch, 64:99) -@test !any(ndigits_mismatch, 512:999) -@test !any(ndigits_mismatch, 8192:9999) - -# The following should not crash (#16579) -ndigits(rand(big.(-999:999)), rand(63:typemax(Int))) -ndigits(rand(big.(-999:999)), big(2)^rand(2:999)) - -for i in big.([-20:-1;1:20]) - for b in -10:1 - @test_throws DomainError ndigits(i, b) - end -end - -# conversion from float -@test BigInt(2.0) == BigInt(2.0f0) == BigInt(big(2.0)) == 2 -@test_throws InexactError convert(BigInt, 2.1) -@test_throws InexactError convert(BigInt, big(2.1)) - -# issue #13367 -@test trunc(BigInt,2.1) == 2 -@test round(BigInt,2.1) == 2 -@test floor(BigInt,2.1) == 2 -@test ceil(BigInt,2.1) == 3 - -@test trunc(BigInt,2.1f0) == 2 -@test round(BigInt,2.1f0) == 2 -@test floor(BigInt,2.1f0) == 2 -@test ceil(BigInt,2.1f0) == 3 - -@test_throws InexactError trunc(BigInt,Inf) -@test_throws InexactError round(BigInt,Inf) -@test_throws InexactError floor(BigInt,Inf) -@test_throws InexactError ceil(BigInt,Inf) - -@test bin(big(3)) == "11" -@test oct(big(9)) == "11" -@test oct(-big(9)) == "-11" -@test hex(big(12)) == "c" - -# Issue #18849: bin, oct, dec, hex should not call sizeof on BigInts -# when padding is desired -let padding = 4, low = big(4), high = big(2^20) - @test bin(low, padding) == "0100" - @test oct(low, padding) == "0004" - @test dec(low, padding) == "0004" - @test hex(low, padding) == "0004" - - @test bin(high, padding) == "100000000000000000000" - @test oct(high, padding) == "4000000" - @test dec(high, padding) == "1048576" - @test hex(high, padding) == "100000" - - @test bin(-low, padding) == "-0100" # handle negative numbers correctly - @test oct(-low, padding) == "-0004" - @test dec(-low, padding) == "-0004" - @test hex(-low, padding) == "-0004" - - @test bin(-high, padding) == "-100000000000000000000" - @test oct(-high, padding) == "-4000000" - @test dec(-high, padding) == "-1048576" - @test hex(-high, padding) == "-100000" -end - -# respect 0-padding on big(0) -for f in (bin, oct, dec, hex) - @test f(big(0), 0) == "" -end -@test base(rand(2:62), big(0), 0) == "" - -@test isqrt(big(4)) == 2 -@test isqrt(big(5)) == 2 - -@test big(5)^true == big(5) -@test big(5)^false == one(BigInt) - - -# operations that when applied to Int64 give Float64, should give BigFloat -@test typeof(exp(a)) == BigFloat -@test typeof(exp2(a)) == BigFloat -@test typeof(exp10(a)) == BigFloat -@test typeof(expm1(a)) == BigFloat -@test typeof(cosh(a)) == BigFloat -@test typeof(sinh(a)) == BigFloat -@test typeof(tanh(a)) == BigFloat -@test typeof(sech(a)) == BigFloat -@test typeof(csch(a)) == BigFloat -@test typeof(coth(a)) == BigFloat -@test typeof(cbrt(a)) == BigFloat -@test typeof(tan(a)) == BigFloat -@test typeof(cos(a)) == BigFloat -@test typeof(sin(a)) == BigFloat diff --git a/julia-0.6.3/share/julia/test/bitarray.jl b/julia-0.6.3/share/julia/test/bitarray.jl deleted file mode 100644 index 4babea7..0000000 --- a/julia-0.6.3/share/julia/test/bitarray.jl +++ /dev/null @@ -1,1466 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -using Base: findprevnot, findnextnot - -tc{N}(r1::NTuple{N,Any}, r2::NTuple{N,Any}) = all(x->tc(x...), [zip(r1,r2)...]) -tc{N}(r1::BitArray{N}, r2::Union{BitArray{N},Array{Bool,N}}) = true -tc(r1::RowVector{Bool,BitVector}, r2::Union{RowVector{Bool,BitVector},RowVector{Bool,Vector{Bool}}}) = true -tc{T}(r1::T, r2::T) = true -tc(r1,r2) = false - -bitcheck(b::BitArray) = Base._check_bitarray_consistency(b) -bitcheck(x) = true - -function check_bitop_call(ret_type, func, args...) - r1 = func(args...) - r2 = func(map(x->(isa(x, BitArray) ? Array(x) : x), args)...) - ret_type ≢ nothing && !isa(r1, ret_type) && @show ret_type, r1 - ret_type ≢ nothing && @test isa(r1, ret_type) - @test tc(r1, r2) - @test isequal(r1, ret_type ≡ nothing ? r2 : convert(ret_type, r2)) - @test bitcheck(r1) -end -macro check_bit_operation(ex, ret_type) - @assert Meta.isexpr(ex, :call) - Expr(:call, :check_bitop_call, esc(ret_type), map(esc, ex.args)...) -end -macro check_bit_operation(ex) - @assert Meta.isexpr(ex, :call) - Expr(:call, :check_bitop_call, nothing, map(esc, ex.args)...) -end - -let t0 = time() - global timesofar - function timesofar(str) - return # no-op, comment to see timings - t1 = time() - println(str, ": ", t1-t0, " seconds") - t0 = t1 - end -end - -@testset "empty bitvector" begin - @test BitVector() == BitVector(0) -end - -# vectors size -v1 = 260 -# matrices size -n1, n2 = 17, 20 -# arrays size -s1, s2, s3, s4 = 5, 8, 3, 7 - -allsizes = [((), BitArray{0}), ((v1,), BitVector), - ((n1,n2), BitMatrix), ((s1,s2,s3,s4), BitArray{4})] - -@testset "trues and falses for size $sz" for (sz,T) in allsizes - a = falses(sz...) - @test a == falses(sz) - @test !any(a) - @test sz == size(a) - b = trues(sz...) - @test b == trues(sz) - @test all(b) - @test sz == size(b) - c = trues(a) - @test all(c) - @test !any(a) - @test sz == size(c) - d = falses(b) - @test !any(d) - @test all(b) - @test sz == size(d) -end - - -@testset "Conversions for size $sz" for (sz, T) in allsizes - b1 = rand!(falses(sz...)) - @test isequal(BitArray(Array(b1)), b1) - @test isequal(convert(Array{Float64,ndims(b1)}, b1), - convert(Array{Float64,ndims(b1)}, Array(b1))) - @test isequal(convert(AbstractArray{Float64,ndims(b1)}, b1), - convert(AbstractArray{Float64,ndims(b1)}, Array(b1))) - - i1 = rand!(zeros(Bool, sz...), false:true) - @test isequal(Array(BitArray(i1)), i1) -end - -timesofar("conversions") - -@testset "utility functions" begin - b1 = bitrand(v1) - @test isequal(fill!(b1, true), trues(size(b1))) - @test isequal(fill!(b1, false), falses(size(b1))) - - for (sz,T) in allsizes - @test isequal(Array(trues(sz...)), ones(Bool, sz...)) - @test isequal(Array(falses(sz...)), zeros(Bool, sz...)) - - b1 = rand!(falses(sz...)) - @test isa(b1, T) - - @check_bit_operation length(b1) Int - @check_bit_operation ndims(b1) Int - @check_bit_operation size(b1) Tuple{Vararg{Int}} - - b2 = similar(b1) - u1 = Array(b1) - @check_bit_operation copy!(b2, b1) T - @check_bit_operation copy!(b2, u1) T - end - - @testset "copy!" begin - for n in [1; 1023:1025] - b1 = falses(n) - for m in [1; 10; 1023:1025] - u1 = ones(Bool, m) - for fu! in [u->fill!(u, true), u->rand!(u)] - fu!(u1) - c1 = convert(Vector{Int}, u1) - for i1 in [1; 10; 53:65; 1013:1015; 1020:1025], i2 in [1; 3; 10; 511:513], l in [1; 5; 10; 511:513; 1023:1025] - for fb! in [b->fill!(b, false), b->rand!(b)] - fb!(b1) - if i1 < 1 || i1 > n || (i2 + l - 1 > m) || (i1 + l - 1 > n) - @test_throws BoundsError copy!(b1, i1, u1, i2, l) - else - @check_bit_operation copy!(b1, i1, u1, i2, l) BitArray - @check_bit_operation copy!(b1, i1, c1, i2, l) BitArray - end - end - end - end - end - end - end - - @test_throws BoundsError size(trues(5), 0) - - @testset "reshape and resize!" begin - b1 = bitrand(n1, n2) - @check_bit_operation reshape(b1, (n2,n1)) BitMatrix - @test_throws DimensionMismatch reshape(b1, (1,n1)) - - @test @inferred(reshape(b1, n1*n2)) == @inferred(reshape(b1, (n1*n2,))) == @inferred(reshape(b1, Val{1})) == @inferred(reshape(b1, :)) - @test @inferred(reshape(b1, n1, n2)) === @inferred(reshape(b1, Val{2})) === b1 - @test @inferred(reshape(b1, n2, :)) == @inferred(reshape(b1, (n2, n1))) != @inferred(reshape(b1, Val{2})) - - b1 = bitrand(s1, s2, s3, s4) - @check_bit_operation reshape(b1, (s3,s1,s2,s4)) BitArray{4} - @test_throws DimensionMismatch reshape(b1, (1,n1)) - - b1 = bitrand(v1) - @test_throws BoundsError resize!(b1, -1) - @check_bit_operation resize!(b1, v1 ÷ 2) BitVector - gr(b) = (resize!(b, v1)[(v1÷2):end] = 1; b) - @check_bit_operation gr(b1) BitVector - end - - @testset "sizeof (issue #7515)" begin - @test sizeof(BitArray(64)) == 8 - @test sizeof(BitArray(65)) == 16 - end -end - -timesofar("utils") - -@testset "Constructors" begin - @testset "non-Int dims constructors" begin - b1 = BitArray(Int32(v1)) - b2 = BitArray(Int64(v1)) - @test size(b1) == size(b2) - - for c in [trues, falses] - b1 = c(Int32(v1)) - b2 = c(Int64(v1)) - @test b1 == b2 - end - end - - @testset "constructors from iterables" begin - for g in ((x%7==3 for x = 1:v1), - (x%7==3 for x = 1:v1 if x>5), - ((x+y)%5==2 for x = 1:n1, y = 1:n2), - ((x+y+z+t)%5==2 for x = 1:s2, y = 1:s2, z = 1:s3, t = 1:s4), - ((x+y)%5==2 for x = 1:n1 for y = 1:n2)) - @test BitArray(g) == BitArray(collect(g)) - end - end - - @testset "one" begin - @test Array(one(BitMatrix(2,2))) == eye(2,2) - @test_throws DimensionMismatch one(BitMatrix(2,3)) - end -end - -timesofar("constructors") - -@testset "Indexing" begin - @testset "0d for size $sz" for (sz,T) in allsizes - b1 = rand!(falses(sz...)) - @check_bit_operation getindex(b1) Bool - @check_bit_operation setindex!(b1, true) T - @check_bit_operation setindex!(b1, false) T - end - - @testset "linear for size $sz" for (sz,T) in allsizes[2:end] - l = *(sz...) - b1 = rand!(falses(sz...)) - for j = 1:l - @check_bit_operation getindex(b1, j) Bool - end - for j in [0, 1, 63, 64, 65, 127, 128, 129, 191, 192, 193, l-1, l] - @check_bit_operation getindex(b1, 1:j) BitVector - @check_bit_operation getindex(b1, j+1:l) BitVector - end - for j in [1, 63, 64, 65, 127, 128, 129, div(l,2)] - m1 = j:(l-j) - @check_bit_operation getindex(b1, m1) BitVector - end - - t1 = find(bitrand(l)) - @check_bit_operation getindex(b1, t1) BitVector - - for j = 1:l - x = rand(Bool) - @check_bit_operation setindex!(b1, x, j) T - end - - y = rand(0.0:1.0) - @check_bit_operation setindex!(b1, y, 100) T - - for j in [1, 63, 64, 65, 127, 128, 129, 191, 192, 193, l-1] - x = rand(Bool) - @check_bit_operation setindex!(b1, x, 1:j) T - b2 = bitrand(j) - for bb in (b2, view(b2, 1:j), view(Array{Any}(b2), :)) - @check_bit_operation setindex!(b1, bb, 1:j) T - end - x = rand(Bool) - @check_bit_operation setindex!(b1, x, j+1:l) T - b2 = bitrand(l-j) - @check_bit_operation setindex!(b1, b2, j+1:l) T - end - for j in [1, 63, 64, 65, 127, 128, 129, div(l,2)] - m1 = j:(l-j) - x = rand(Bool) - @check_bit_operation setindex!(b1, x, m1) T - b2 = bitrand(length(m1)) - @check_bit_operation setindex!(b1, b2, m1) T - end - x = rand(Bool) - @check_bit_operation setindex!(b1, x, 1:100) T - b2 = bitrand(100) - @check_bit_operation setindex!(b1, b2, 1:100) T - - y = rand(0.0:1.0) - @check_bit_operation setindex!(b1, y, 1:100) T - - t1 = find(bitrand(l)) - x = rand(Bool) - @check_bit_operation setindex!(b1, x, t1) T - b2 = bitrand(length(t1)) - @check_bit_operation setindex!(b1, b2, t1) T - - y = rand(0.0:1.0) - @check_bit_operation setindex!(b1, y, t1) T - end - - @testset "multidimensional" begin - rand_m1m2() = rand(1:n1), rand(1:n2) - b1 = bitrand(n1, n2) - m1, m2 = rand_m1m2() - b2 = bitrand(m1, m2) - @check_bit_operation copy!(b1, b2) BitMatrix - - function gen_getindex_data(c) - m1, m2 = rand_m1m2() - put!(c, (m1, m2, Bool)) - m1, m2 = rand_m1m2() - put!(c, (m1, 1:m2, BitVector)) - put!(c, (m1, :, BitVector)) - m1, m2 = rand_m1m2() - put!(c, (m1, randperm(m2), BitVector)) - m1, m2 = rand_m1m2() - put!(c, (1:m1, m2, BitVector)) - put!(c, (:, m2, BitVector)) - m1, m2 = rand_m1m2() - put!(c, (1:m1, 1:m2, BitMatrix)) - put!(c, (:, :, BitMatrix)) - m1, m2 = rand_m1m2() - put!(c, (1:m1, randperm(m2), BitMatrix)) - put!(c, (:, randperm(m2), BitMatrix)) - m1, m2 = rand_m1m2() - put!(c, (randperm(m1), m2, BitVector)) - m1, m2 = rand_m1m2() - put!(c, (randperm(m1), 1:m2, BitMatrix)) - put!(c, (randperm(m1), :, BitMatrix)) - m1, m2 = rand_m1m2() - put!(c, (randperm(m1), randperm(m2), BitMatrix)) - end - - for (k1, k2, T) in Channel(gen_getindex_data) - # println(typeof(k1), " ", typeof(k2), " ", T) # uncomment to debug - @check_bit_operation getindex(b1, k1, k2) T - end - - m1, m2 = rand_m1m2() - @check_bit_operation getindex(b1, 1:m1, m2, 1) BitVector - @check_bit_operation getindex(b1, :, randperm(m2), 1) BitMatrix - - b1 = bitrand(s1, s2, s3, s4) - function gen_getindex_data4(c) - m1, m2, m3, m4 = (:, :, :, :) - put!(c, (m1, m2, m3, m4, BitArray{4})) - - m1, m2, m3, m4 = (2, :, :, :) - put!(c, (m1, m2, m3, m4, BitArray{3})) - m1, m2, m3, m4 = (:, :, 2, :) - put!(c, (m1, m2, m3, m4, BitArray{3})) - m1, m2, m3, m4 = (:, :, :, 2) - put!(c, (m1, m2, m3, m4, BitArray{3})) - - m1, m2, m3, m4 = (2, :, :, 2) - put!(c, (m1, m2, m3, m4, BitArray{2})) - m1, m2, m3, m4 = (:, 2, :, 2) - put!(c, (m1, m2, m3, m4, BitArray{2})) - m1, m2, m3, m4 = (2, :, 2, :) - put!(c, (m1, m2, m3, m4, BitArray{2})) - m1, m2, m3, m4 = (2, 2, :, :) - put!(c, (m1, m2, m3, m4, BitArray{2})) - - m1, m2, m3, m4 = (:, 2, 2, 2) - put!(c, (m1, m2, m3, m4, BitArray{1})) - m1, m2, m3, m4 = (2, 2, :, 2) - put!(c, (m1, m2, m3, m4, BitArray{1})) - - m1, m2, m3, m4 = (4, 3:7, 2:2, 2) - put!(c, (m1, m2, m3, m4, BitArray{2})) - m1, m2, m3, m4 = (1:2, 5, 1, 2:7) - put!(c, (m1, m2, m3, m4, BitArray{2})) - - m1, m2, m3, m4 = (2:3, 2:7, 1:2, 4:6) - put!(c, (m1, m2, m3, m4, BitArray{4})) - end - - for (k1, k2, k3, k4, T) in Channel(gen_getindex_data4) - #println(typeof(k1), " ", typeof(k2), " ", typeof(k3), " ", typeof(k4), " ", T) # uncomment to debug - @check_bit_operation getindex(b1, k1, k2, k3, k4) T - end - - b1 = bitrand(n1, n2) - function gen_setindex_data(c) - m1, m2 = rand_m1m2() - put!(c, (rand(Bool), m1, m2)) - m1, m2 = rand_m1m2() - put!(c, (rand(Bool), m1, 1:m2)) - put!(c, (rand(Bool), m1, :)) - put!(c, (bitrand(m2), m1, 1:m2)) - m1, m2 = rand_m1m2() - put!(c, (rand(Bool), m1, randperm(m2))) - put!(c, (bitrand(m2), m1, randperm(m2))) - m1, m2 = rand_m1m2() - put!(c, (rand(Bool), 1:m1, m2)) - put!(c, (rand(Bool), :, m2)) - put!(c, (bitrand(m1), 1:m1, m2)) - m1, m2 = rand_m1m2() - put!(c, (rand(Bool), 1:m1, 1:m2)) - put!(c, (rand(Bool), :, :)) - put!(c, (bitrand(m1, m2), 1:m1, 1:m2)) - m1, m2 = rand_m1m2() - put!(c, (rand(Bool), 1:m1, randperm(m2))) - put!(c, (rand(Bool), :, randperm(m2))) - put!(c, (bitrand(m1, m2), 1:m1, randperm(m2))) - m1, m2 = rand_m1m2() - put!(c, (rand(Bool), randperm(m1), m2)) - put!(c, (bitrand(m1), randperm(m1), m2)) - m1, m2 = rand_m1m2() - put!(c, (rand(Bool), randperm(m1), 1:m2)) - put!(c, (rand(Bool), randperm(m1), :)) - put!(c, (bitrand(m1,m2), randperm(m1), 1:m2)) - m1, m2 = rand_m1m2() - put!(c, (rand(Bool), randperm(m1), randperm(m2))) - put!(c, (bitrand(m1,m2), randperm(m1), randperm(m2))) - end - - for (b2, k1, k2) in Channel(gen_setindex_data) - # println(typeof(b2), " ", typeof(k1), " ", typeof(k2)) # uncomment to debug - for bb in ((b2 isa AbstractArray) ? (b2, view(b2, :), view(Array{Any}(b2), :)) : (b2,)) - @check_bit_operation setindex!(b1, bb, k1, k2) BitMatrix - end - end - - m1, m2 = rand_m1m2() - b2 = bitrand(1, 1, m2) - @check_bit_operation setindex!(b1, b2, m1, 1:m2) BitMatrix - x = rand(Bool) - b2 = bitrand(1, m2, 1) - @check_bit_operation setindex!(b1, x, m1, 1:m2, 1) BitMatrix - @check_bit_operation setindex!(b1, b2, m1, 1:m2, 1) BitMatrix - - b1 = bitrand(s1, s2, s3, s4) - function gen_setindex_data4(c) - m1, m2, m3, m4 = (:, :, :, :) - put!(c, (rand(Bool), m1, m2, m3, m4)) - put!(c, (bitrand(s1, s2, s3, s4), m1, m2, m3, m4)) - - m1, m2, m3, m4 = (2, :, :, :) - put!(c, (rand(Bool), m1, m2, m3, m4)) - put!(c, (bitrand(s2, s3, s4), m1, m2, m3, m4)) - m1, m2, m3, m4 = (:, :, 2, :) - put!(c, (bitrand(s1, s2, s4), m1, m2, m3, m4)) - m1, m2, m3, m4 = (:, :, :, 2) - put!(c, (rand(Bool), m1, m2, m3, m4)) - put!(c, (bitrand(s1, s2, s3), m1, m2, m3, m4)) - - m1, m2, m3, m4 = (2, :, :, 2) - put!(c, (rand(Bool), m1, m2, m3, m4)) - put!(c, (bitrand(s2, s3), m1, m2, m3, m4)) - m1, m2, m3, m4 = (:, 2, :, 2) - put!(c, (rand(Bool), m1, m2, m3, m4)) - put!(c, (bitrand(s1, s3), m1, m2, m3, m4)) - m1, m2, m3, m4 = (2, :, 2, :) - put!(c, (bitrand(s2, s4), m1, m2, m3, m4)) - m1, m2, m3, m4 = (:, 2, 2, :) - put!(c, (bitrand(s1, s4), m1, m2, m3, m4)) - - m1, m2, m3, m4 = (:, 2, 2, 2) - put!(c, (bitrand(s1), m1, m2, m3, m4)) - m1, m2, m3, m4 = (2, 2, :, 2) - put!(c, (bitrand(s3), m1, m2, m3, m4)) - - m1, m2, m3, m4 = (4, 3:7, 2:2, 2) - put!(c, (bitrand(5, 1), m1, m2, m3, m4)) - m1, m2, m3, m4 = (1:2, 5, 1, 2:7) - put!(c, (rand(Bool), m1, m2, m3, m4)) - put!(c, (bitrand(2, 6), m1, m2, m3, m4)) - - m1, m2, m3, m4 = (2:3, 2:7, 1:2, 4:6) - put!(c, (bitrand(2, 6, 2, 3), m1, m2, m3, m4)) - end - - for (b2, k1, k2, k3, k4) in Channel(gen_setindex_data4) - # println(typeof(b2), " ", typeof(k1), " ", typeof(k2), " ", typeof(k3), " ", typeof(k4)) # uncomment to debug - @check_bit_operation setindex!(b1, b2, k1, k2, k3, k4) BitArray{4} - end - - for p1 = [rand(1:v1) 1 63 64 65 191 192 193] - for p2 = [rand(1:v1) 1 63 64 65 191 192 193] - for n = 0 : min(v1 - p1 + 1, v1 - p2 + 1) - b1 = bitrand(v1) - b2 = bitrand(v1) - @check_bit_operation copy!(b1, p1, b2, p2, n) BitVector - end - end - end - end - - @testset "logical indexing" begin - b1 = bitrand(n1, n2) - - t1 = bitrand(n1, n2) - @test isequal(Array(b1[t1]), Array(b1)[t1]) - @test isequal(Array(b1[t1]), Array(b1)[Array(t1)]) - - t1 = bitrand(n1) - t2 = bitrand(n2) - @test isequal(Array(b1[t1, t2]), Array(b1)[t1, t2]) - @test isequal(Array(b1[t1, t2]), Array(b1)[Array(t1), Array(t2)]) - - b1 = bitrand(n1, n2) - t1 = bitrand(n1, n2) - @check_bit_operation setindex!(b1, true, t1) BitMatrix - - t1 = bitrand(n1, n2) - b2 = bitrand(countnz(t1)) - @check_bit_operation setindex!(b1, b2, t1) BitMatrix - - m1 = rand(1:n1) - m2 = rand(1:n2) - t1 = bitrand(n1) - b2 = bitrand(countnz(t1), m2) - k2 = randperm(m2) - @check_bit_operation setindex!(b1, b2, t1, 1:m2) BitMatrix - @check_bit_operation setindex!(b1, b2, t1, n2-m2+1:n2) BitMatrix - @check_bit_operation setindex!(b1, b2, t1, k2) BitMatrix - - t2 = bitrand(n2) - b2 = bitrand(m1, countnz(t2)) - k1 = randperm(m1) - @check_bit_operation setindex!(b1, b2, 1:m1, t2) BitMatrix - @check_bit_operation setindex!(b1, b2, n1-m1+1:n1, t2) BitMatrix - @check_bit_operation setindex!(b1, b2, k1, t2) BitMatrix - end -end - -timesofar("indexing") - -@testset "Deque Functionality" begin - b1 = BitArray(0) - i1 = Bool[] - for m = 1:v1 - x = rand(Bool) - push!(b1, x) - push!(i1, x) - @test isequal(Array(b1), i1) - @test bitcheck(b1) - end - - for m1 = 0:v1, m2 = [0, 1, 63, 64, 65, 127, 128, 129] - b1 = bitrand(m1) - b2 = bitrand(m2) - i1 = Array(b1) - i2 = Array(b2) - @test isequal(Array(append!(b1, b2)), append!(i1, i2)) - @test isequal(Array(append!(b1, i2)), append!(i1, b2)) - @test bitcheck(b1) - end - - for m1 = 0:v1, m2 = [0, 1, 63, 64, 65, 127, 128, 129] - b1 = bitrand(m1) - b2 = bitrand(m2) - i1 = Array(b1) - i2 = Array(b2) - @test isequal(Array(prepend!(b1, b2)), prepend!(i1, i2)) - @test isequal(Array(prepend!(b1, i2)), prepend!(i1, b2)) - @test bitcheck(b1) - end - - b1 = bitrand(v1) - i1 = Array(b1) - for m = 1:v1 - jb = pop!(b1) - ji = pop!(i1) - @test jb == ji - @test isequal(Array(b1), i1) - @test bitcheck(b1) - end - - @test length(b1) == 0 - - b1 = BitArray(0) - i1 = Bool[] - for m = 1:v1 - x = rand(Bool) - unshift!(b1, x) - unshift!(i1, x) - @test isequal(Array(b1), i1) - @test bitcheck(b1) - end - - b1 = bitrand(v1) - i1 = Array(b1) - for m = 1:v1 - jb = shift!(b1) - ji = shift!(i1) - @test jb == ji - @test isequal(Array(b1), i1) - @test bitcheck(b1) - end - @test length(b1) == 0 - - b1 = BitArray(0) - @test_throws BoundsError insert!(b1, 2, false) - @test_throws BoundsError insert!(b1, 0, false) - i1 = Array(b1) - for m = 1:v1 - j = rand(1:m) - x = rand(Bool) - @test insert!(b1, j, x) === b1 - insert!(i1, j, x) - @test isequal(Array(b1), i1) - @test bitcheck(b1) - end - - b1 = bitrand(v1) - i1 = Array(b1) - for j in [63, 64, 65, 127, 128, 129, 191, 192, 193] - x = rand(0:1) - @test insert!(b1, j, x) === b1 - insert!(i1, j, x) - @test isequal(Array(b1), i1) - @test bitcheck(b1) - end - - b1 = bitrand(v1) - i1 = Array(b1) - for m = v1:-1:1 - j = rand(1:m) - b = splice!(b1, j) - i = splice!(i1, j) - @test isequal(Array(b1), i1) - @test bitcheck(b1) - @test b == i - @test bitcheck(b) - end - @test length(b1) == 0 - - b1 = bitrand(v1) - i1 = Array(b1) - for m = v1:-1:1 - j = rand(1:m) - deleteat!(b1, j) - deleteat!(i1, j) - @test isequal(Array(b1), i1) - @test bitcheck(b1) - end - @test length(b1) == 0 - b1 = bitrand(v1) - @test_throws ArgumentError deleteat!(b1, [1, 1, 2]) - @test_throws BoundsError deleteat!(b1, [1, length(b1)+1]) - - b1 = bitrand(v1) - i1 = Array(b1) - for j in [63, 64, 65, 127, 128, 129, 191, 192, 193] - b = splice!(b1, j) - i = splice!(i1, j) - @test isequal(Array(b1), i1) - @test bitcheck(b1) - @test b == i - @test bitcheck(b) - end - - b1 = bitrand(v1) - i1 = Array(b1) - for j in [63, 64, 65, 127, 128, 129, 191, 192, 193] - deleteat!(b1, j) - deleteat!(i1, j) - @test isequal(Array(b1), i1) - @test bitcheck(b1) - end - - b1 = bitrand(v1) - i1 = Array(b1) - for m1 = 1:v1, m2 = m1:v1 - b2 = copy(b1) - i2 = copy(i1) - b = splice!(b2, m1:m2) - i = splice!(i2, m1:m2) - @test isequal(Array(b2), i2) - @test bitcheck(b2) - @test b == i - @test bitcheck(b) - end - - b1 = bitrand(v1) - i1 = Array(b1) - for m1 = 1:v1, m2 = m1:v1 - b2 = copy(b1) - i2 = copy(i1) - deleteat!(b2, m1:m2) - deleteat!(i2, m1:m2) - @test isequal(Array(b2), i2) - @test bitcheck(b2) - end - - b1 = bitrand(v1) - i1 = Array(b1) - for m1 = [1:7:v1; v1+1], m2 = [(m1-1):5:(v1-1); v1], v2 = [0, 1, 63, 64, 65, 127, 128, 129, 191, 192, 193, rand(1:v1)] - b2 = copy(b1) - i2 = copy(i1) - b3 = bitrand(v2) - i3 = Array(b3) - b = splice!(b2, m1:m2, b3) - i = splice!(i2, m1:m2, i3) - @test isequal(Array(b2), i2) - @test bitcheck(b2) - @test b == i - @test bitcheck(b) - - b2 = copy(b1) - i2 = copy(i1) - i3 = map(Int, bitrand(v2)) - b = splice!(b2, m1:m2, i3) - i = splice!(i2, m1:m2, i3) - @test isequal(Array(b2), i2) - @test bitcheck(b2) - @test b == i - @test bitcheck(b) - b2 = copy(b1) - i2 = copy(i1) - i3 = Dict(j => rand(0:1) for j = 1:v2) - b = splice!(b2, m1:m2, values(i3)) - i = splice!(i2, m1:m2, values(i3)) - @test isequal(Array(b2), i2) - @test bitcheck(b2) - @test b == i - @test bitcheck(b) - end - - b1 = bitrand(v1) - i1 = Array(b1) - for m1 = 1:v1, v2 = [0, 1, 63, 64, 65, 127, 128, 129, 191, 192, 193, rand(1:v1)] - b2 = copy(b1) - i2 = copy(i1) - b3 = bitrand(v2) - i3 = Array(b3) - b = splice!(b2, m1, b3) - i = splice!(i2, m1, i3) - @test isequal(Array(b2), i2) - @test bitcheck(b2) - @test b == i - @test bitcheck(b) - end - - b1 = bitrand(v1) - i1 = Array(b1) - for m1 = 1:(v1-1), m2 = (m1+1):v1 - locs = bitrand(m2-m1+1) - m = [m1:m2...][locs] - b2 = copy(b1) - i2 = copy(i1) - deleteat!(b2, m) - deleteat!(i2, m) - @test isequal(Array(b2), i2) - @test bitcheck(b2) - end - - b1 = bitrand(v1) - i1 = Array(b1) - empty!(b1) - empty!(i1) - @test isequal(Array(b1), i1) - @test bitcheck(b1) -end - -timesofar("dequeue") - -@testset "Unary operators" begin - b1 = bitrand(n1, n2) - @check_bit_operation broadcast(~, b1) BitMatrix - @check_bit_operation broadcast(!, b1) BitMatrix - @check_bit_operation (-)(b1) Matrix{Int} - @check_bit_operation broadcast(sign, b1) BitMatrix - @check_bit_operation real(b1) BitMatrix - @check_bit_operation imag(b1) BitMatrix - @check_bit_operation conj(b1) BitMatrix - - b0 = falses(0) - @check_bit_operation broadcast(~, b0) BitVector - @check_bit_operation broadcast(!, b0) BitVector - @check_bit_operation (-)(b0) Vector{Int} - @check_bit_operation broadcast(sign, b0) BitVector - - @testset "flipbits!" begin - b1 = bitrand(n1, n2) - i1 = Array(b1) - @test flipbits!(b1) == .~i1 - @test bitcheck(b1) - end -end - -timesofar("unary arithmetic") - -@testset "Binary arithmetic operators" begin - @testset "Matrix{Bool}/Matrix{Bool}" begin - b1 = bitrand(n1, n2) - b2 = bitrand(n1, n2) - @check_bit_operation broadcast(&, b1, b2) BitMatrix - @check_bit_operation broadcast(|, b1, b2) BitMatrix - @check_bit_operation broadcast(xor, b1, b2) BitMatrix - @check_bit_operation (+)(b1, b2) Matrix{Int} - @check_bit_operation (-)(b1, b2) Matrix{Int} - @check_bit_operation broadcast(*, b1, b2) BitMatrix - @check_bit_operation broadcast(/, b1, b2) Matrix{Float64} - @check_bit_operation broadcast(^, b1, b2) BitMatrix - @check_bit_operation (/)(b1,1) Matrix{Float64} - - b2 = trues(n1, n2) - @check_bit_operation broadcast(div, b1, b2) BitMatrix - @check_bit_operation broadcast(mod, b1, b2) BitMatrix - @check_bit_operation broadcast(div, b1, Array(b2)) BitMatrix - @check_bit_operation broadcast(mod, b1, Array(b2)) BitMatrix - @check_bit_operation broadcast(div, Array(b1), b2) BitMatrix - @check_bit_operation broadcast(mod, Array(b1), b2) BitMatrix - - b1 = bitrand(n1, n1) - while abs(det(Array{Float64}(b1))) ≤ 1e-6 - b1 = bitrand(n1, n1) - end - b2 = bitrand(n1, n1) - - @check_bit_operation (*)(b1, b2) Matrix{Int} - @check_bit_operation (/)(b1, b1) Matrix{Float64} - @check_bit_operation (\)(b1, b1) Matrix{Float64} - - b0 = falses(0) - @check_bit_operation broadcast(&, b0, b0) BitVector - @check_bit_operation broadcast(|, b0, b0) BitVector - @check_bit_operation broadcast(xor, b0, b0) BitVector - @check_bit_operation broadcast(*, b0, b0) BitVector - @check_bit_operation (*)(b0, b0') BitMatrix - end - - @testset "Matrix{Bool}/Matrix{Int}" begin - b1 = bitrand(n1, n2) - i2 = rand(1:10, n1, n2) - @check_bit_operation broadcast(&, b1, i2) Matrix{Int} - @check_bit_operation broadcast(|, b1, i2) Matrix{Int} - @check_bit_operation broadcast(xor, b1, i2) Matrix{Int} - @check_bit_operation (+)(b1, i2) Matrix{Int} - @check_bit_operation (-)(b1, i2) Matrix{Int} - @check_bit_operation broadcast(*, b1, i2) Matrix{Int} - @check_bit_operation broadcast(/, b1, i2) Matrix{Float64} - @check_bit_operation broadcast(^, b1, i2) BitMatrix - @check_bit_operation broadcast(div, b1, i2) Matrix{Int} - @check_bit_operation broadcast(mod, b1, i2) Matrix{Int} - end - - @testset "Matrix{Bool}/Matrix{Float64}" begin - b1 = bitrand(n1, n2) - f2 = 1.0 .+ rand(n1, n2) - @check_bit_operation broadcast(*, b1, f2) Matrix{Float64} - @check_bit_operation broadcast(/, b1, f2) Matrix{Float64} - @check_bit_operation broadcast(^, b1, f2) Matrix{Float64} - @check_bit_operation broadcast(div, b1, f2) Matrix{Float64} - @check_bit_operation broadcast(mod, b1, f2) Matrix{Float64} - end - - @testset "Number/Matrix" begin - b2 = bitrand(n1, n2) - i1 = rand(1:10) - u1 = UInt8(i1) - f1 = Float64(i1) - ci1 = complex(i1) - cu1 = complex(u1) - cf1 = complex(f1) - - @check_bit_operation broadcast(&, i1, b2) Matrix{Int} - @check_bit_operation broadcast(|, i1, b2) Matrix{Int} - @check_bit_operation broadcast(xor, i1, b2) Matrix{Int} - @check_bit_operation broadcast(+, i1, b2) Matrix{Int} - @check_bit_operation broadcast(-, i1, b2) Matrix{Int} - @check_bit_operation broadcast(*, i1, b2) Matrix{Int} - - @check_bit_operation broadcast(&, u1, b2) Matrix{UInt8} - @check_bit_operation broadcast(|, u1, b2) Matrix{UInt8} - @check_bit_operation broadcast(xor, u1, b2) Matrix{UInt8} - @check_bit_operation broadcast(+, u1, b2) Matrix{UInt8} - @check_bit_operation broadcast(-, u1, b2) Matrix{UInt8} - @check_bit_operation broadcast(*, u1, b2) Matrix{UInt8} - - for (x1,t1) = [(f1, Float64), - (ci1, Complex{Int}), - (cu1, Complex{UInt8}), - (cf1, Complex128)] - @check_bit_operation broadcast(+, x1, b2) Matrix{t1} - @check_bit_operation broadcast(-, x1, b2) Matrix{t1} - @check_bit_operation broadcast(*, x1, b2) Matrix{t1} - end - - b2 = trues(n1, n2) - @check_bit_operation broadcast(/, true, b2) Matrix{Float64} - @check_bit_operation broadcast(div, true, b2) BitMatrix - @check_bit_operation broadcast(mod, true, b2) BitMatrix - @check_bit_operation broadcast(/, false, b2) Matrix{Float64} - @check_bit_operation broadcast(div, false, b2) BitMatrix - @check_bit_operation broadcast(mod, false, b2) BitMatrix - - @check_bit_operation broadcast(/, i1, b2) Matrix{Float64} - @check_bit_operation broadcast(div, i1, b2) Matrix{Int} - @check_bit_operation broadcast(mod, i1, b2) Matrix{Int} - - @check_bit_operation broadcast(/, u1, b2) Matrix{Float64} - @check_bit_operation broadcast(div, u1, b2) Matrix{UInt8} - @check_bit_operation broadcast(mod, u1, b2) Matrix{UInt8} - - @check_bit_operation broadcast(/, f1, b2) Matrix{Float64} - @check_bit_operation broadcast(div, f1, b2) Matrix{Float64} - @check_bit_operation broadcast(mod, f1, b2) Matrix{Float64} - - @check_bit_operation broadcast(/, ci1, b2) Matrix{Complex128} - @check_bit_operation broadcast(/, cu1, b2) Matrix{Complex128} - @check_bit_operation broadcast(/, cf1, b2) Matrix{Complex128} - - b2 = bitrand(n1, n2) - @check_bit_operation broadcast(^, false, b2) BitMatrix - @check_bit_operation broadcast(^, true, b2) BitMatrix - @check_bit_operation broadcast(^, 0x0, b2) Matrix{UInt8} - @check_bit_operation broadcast(^, 0x1, b2) Matrix{UInt8} - @check_bit_operation broadcast(^, -1, b2) Matrix{Int} - @check_bit_operation broadcast(^, 0, b2) Matrix{Int} - @check_bit_operation broadcast(^, 1, b2) Matrix{Int} - @check_bit_operation broadcast(^, 0.0, b2) Matrix{Float64} - @check_bit_operation broadcast(^, 1.0, b2) Matrix{Float64} - @check_bit_operation broadcast(^, 0.0im, b2) Matrix{Complex128} - @check_bit_operation broadcast(^, 1.0im, b2) Matrix{Complex128} - @check_bit_operation broadcast(^, 0im, b2) Matrix{Complex{Int}} - @check_bit_operation broadcast(^, 1im, b2) Matrix{Complex{Int}} - @check_bit_operation broadcast(^, 0x0im, b2) Matrix{Complex{UInt8}} - @check_bit_operation broadcast(^, 0x1im, b2) Matrix{Complex{UInt8}} - end - - @testset "Matrix/Number" begin - b1 = bitrand(n1, n2) - i2 = rand(1:10) - u2 = UInt8(i2) - f2 = Float64(i2) - ci2 = complex(i2) - cu2 = complex(u2) - cf2 = complex(f2) - b2 = Array(bitrand(n1,n2)) - - @check_bit_operation broadcast(&, b1, true) BitMatrix - @check_bit_operation broadcast(&, b1, false) BitMatrix - @check_bit_operation broadcast(&, true, b1) BitMatrix - @check_bit_operation broadcast(&, false, b1) BitMatrix - @check_bit_operation broadcast(|, b1, true) BitMatrix - @check_bit_operation broadcast(|, b1, false) BitMatrix - @check_bit_operation broadcast(|, true, b1) BitMatrix - @check_bit_operation broadcast(|, false, b1) BitMatrix - @check_bit_operation broadcast(xor, b1, true) BitMatrix - @check_bit_operation broadcast(xor, b1, false) BitMatrix - @check_bit_operation broadcast(xor, true, b1) BitMatrix - @check_bit_operation broadcast(xor, false, b1) BitMatrix - @check_bit_operation broadcast(+, b1, true) Matrix{Int} - @check_bit_operation broadcast(+, b1, false) Matrix{Int} - @check_bit_operation broadcast(-, b1, true) Matrix{Int} - @check_bit_operation broadcast(-, b1, false) Matrix{Int} - @check_bit_operation broadcast(*, b1, true) BitMatrix - @check_bit_operation broadcast(*, b1, false) BitMatrix - @check_bit_operation broadcast(*, true, b1) BitMatrix - @check_bit_operation broadcast(*, false, b1) BitMatrix - @check_bit_operation broadcast(/, b1, true) Matrix{Float64} - @check_bit_operation broadcast(/, b1, false) Matrix{Float64} - @check_bit_operation broadcast(div, b1, true) BitMatrix - @check_bit_operation broadcast(mod,b1, true) BitMatrix - - @check_bit_operation broadcast(&, b1, b2) BitMatrix - @check_bit_operation broadcast(|, b1, b2) BitMatrix - @check_bit_operation broadcast(xor, b1, b2) BitMatrix - @check_bit_operation broadcast(&, b2, b1) BitMatrix - @check_bit_operation broadcast(|, b2, b1) BitMatrix - @check_bit_operation broadcast(xor, b2, b1) BitMatrix - @check_bit_operation broadcast(&, b1, i2) Matrix{Int} - @check_bit_operation broadcast(|, b1, i2) Matrix{Int} - @check_bit_operation broadcast(xor, b1, i2) Matrix{Int} - @check_bit_operation broadcast(+, b1, i2) Matrix{Int} - @check_bit_operation broadcast(-, b1, i2) Matrix{Int} - @check_bit_operation broadcast(*, b1, i2) Matrix{Int} - @check_bit_operation broadcast(/, b1, i2) Matrix{Float64} - @check_bit_operation broadcast(div, b1, i2) Matrix{Int} - @check_bit_operation broadcast(mod, b1, i2) Matrix{Int} - - @check_bit_operation broadcast(&, b1, u2) Matrix{UInt8} - @check_bit_operation broadcast(|, b1, u2) Matrix{UInt8} - @check_bit_operation broadcast(xor, b1, u2) Matrix{UInt8} - @check_bit_operation broadcast(+, b1, u2) Matrix{UInt8} - @check_bit_operation broadcast(-, b1, u2) Matrix{UInt8} - @check_bit_operation broadcast(*, b1, u2) Matrix{UInt8} - @check_bit_operation broadcast(/, b1, u2) Matrix{Float64} - @check_bit_operation broadcast(div, b1, u2) Matrix{UInt8} - @check_bit_operation broadcast(mod, b1, u2) Matrix{UInt8} - - @check_bit_operation broadcast(+, b1, f2) Matrix{Float64} - @check_bit_operation broadcast(-, b1, f2) Matrix{Float64} - @check_bit_operation broadcast(*, b1, f2) Matrix{Float64} - @check_bit_operation broadcast(/, b1, f2) Matrix{Float64} - @check_bit_operation broadcast(div, b1, f2) Matrix{Float64} - @check_bit_operation broadcast(mod, b1, f2) Matrix{Float64} - - @check_bit_operation broadcast(+, b1, ci2) Matrix{Complex{Int}} - @check_bit_operation broadcast(-, b1, ci2) Matrix{Complex{Int}} - @check_bit_operation broadcast(*, b1, ci2) Matrix{Complex{Int}} - @check_bit_operation broadcast(/, b1, ci2) Matrix{Complex128} - - @check_bit_operation broadcast(+, b1, cu2) Matrix{Complex{UInt8}} - @check_bit_operation broadcast(-, b1, cu2) Matrix{Complex{UInt8}} - @check_bit_operation broadcast(*, b1, cu2) Matrix{Complex{UInt8}} - @check_bit_operation broadcast(/, b1, cu2) Matrix{Complex128} - - @check_bit_operation broadcast(+, b1, cf2) Matrix{Complex128} - @check_bit_operation broadcast(-, b1, cf2) Matrix{Complex128} - @check_bit_operation broadcast(*, b1, cf2) Matrix{Complex128} - @check_bit_operation broadcast(/, b1, cf2) Matrix{Complex128} - - @check_bit_operation broadcast(^, b1, false) BitMatrix - @check_bit_operation broadcast(^, b1, true) BitMatrix - @check_bit_operation broadcast(^, b1, 0x0) BitMatrix - @check_bit_operation broadcast(^, b1, 0x1) BitMatrix - @check_bit_operation broadcast(^, b1, 0) BitMatrix - @check_bit_operation broadcast(^, b1, 1) BitMatrix - @check_bit_operation broadcast(^, b1, -1.0) Matrix{Float64} - @check_bit_operation broadcast(^, b1, 0.0) Matrix{Float64} - @check_bit_operation broadcast(^, b1, 1.0) Matrix{Float64} - @check_bit_operation broadcast(^, b1, 0.0im) Matrix{Complex128} - @check_bit_operation broadcast(^, b1, 0x0im) Matrix{Complex128} - @check_bit_operation broadcast(^, b1, 0im) Matrix{Complex128} - @test_throws DomainError broadcast(^, b1, -1) - - b1 = trues(n1, n2) - @check_bit_operation broadcast(^, b1, -1.0im) Matrix{Complex128} - @check_bit_operation broadcast(^, b1, 1.0im) Matrix{Complex128} - @check_bit_operation broadcast(^, b1, -1im) Matrix{Complex128} - @check_bit_operation broadcast(^, b1, 1im) Matrix{Complex128} - @check_bit_operation broadcast(^, b1, 0x1im) Matrix{Complex128} - end -end - -timesofar("binary arithmetic") - -@testset "Binary comparison operators" begin - b1 = bitrand(n1, n2) - b2 = bitrand(n1, n2) - @check_bit_operation broadcast(==, b1, b2) BitMatrix - @check_bit_operation broadcast(!=, b1, b2) BitMatrix - @check_bit_operation broadcast(<, b1, b2) BitMatrix - @check_bit_operation broadcast(<=, b1, b2) BitMatrix -end - -timesofar("binary comparison") - -@testset "Data movement" begin - b1 = bitrand(s1, s2, s3, s4) - for d = 1:4 - j = rand(1:size(b1, d)) - #for j = 1 : size(b1, d) - @check_bit_operation slicedim(b1, d, j) BitArray{3} - #end - @check_bit_operation flipdim(b1, d) BitArray{4} - end - @test_throws ArgumentError flipdim(b1, 5) - - b1 = bitrand(n1, n2) - for k = 1:4 - @check_bit_operation rotl90(b1, k) BitMatrix - end - - for m = 0:v1 - b1 = bitrand(m) - @check_bit_operation reverse(b1) BitVector - end - - b1 = bitrand(v1) - for m = [rand(1:v1)-1, 0, 1, 63, 64, 65, 191, 192, 193, v1-1] - @test isequal(b1 << m, [ b1[m+1:end]; falses(m) ]) - @test isequal(b1 >>> m, [ falses(m); b1[1:end-m] ]) - @test isequal(b1 << -m, b1 >> m) - @test isequal(b1 >>> -m, b1 << m) - @test isequal(rol(b1, m), [ b1[m+1:end]; b1[1:m] ]) - @test isequal(ror(b1, m), [ b1[end-m+1:end]; b1[1:end-m] ]) - @test isequal(ror(b1, m), rol(b1, -m)) - @test isequal(rol(b1, m), ror(b1, -m)) - end - - b = bitrand(v1) - i = bitrand(v1) - for m = [rand(1:v1), 63, 64, 65, 191, 192, 193, v1-1] - j = rand(1:m) - b1 = ror!(i, b, j) - i1 = ror!(b, j) - @test b1 == i1 - b2 = rol!(i1, b1, j) - i2 = rol!(b1, j) - @test b2 == i2 - end -end - -timesofar("datamove") - -@testset "countnz & find" begin - for m = 0:v1, b1 in Any[bitrand(m), trues(m), falses(m)] - @check_bit_operation countnz(b1) Int - - @check_bit_operation findfirst(b1) Int - - @check_bit_operation findfirst(b1, true) Int - @check_bit_operation findfirst(b1, false) Int - @check_bit_operation findfirst(b1, 3) Int - - @check_bit_operation findfirst(x->x, b1) Int - @check_bit_operation findfirst(x->!x, b1) Int - @check_bit_operation findfirst(x->true, b1) Int - @check_bit_operation findfirst(x->false, b1) Int - - @check_bit_operation find(b1) Vector{Int} - end - - b1 = trues(v1) - for i = 0:(v1-1) - @test findfirst(b1 >> i) == i+1 - @test Base.findfirstnot(.~(b1 >> i)) == i+1 - end - - for i = 3:(v1-1), j = 2:i - submask = b1 << (v1-j+1) - @test findnext((b1 >> i) .| submask, j) == i+1 - @test findnextnot((.~(b1 >> i)) .⊻ submask, j) == i+1 - end - - b1 = bitrand(n1, n2) - @check_bit_operation findnz(b1) Tuple{Vector{Int}, Vector{Int}, BitArray} -end - -timesofar("nnz&find") - -@testset "Findnext/findprev" begin - b1 = trues(v1) - b2 = falses(v1) - for i = 1:v1 - @test findprev(b1, i) == findprev(b1, true, i) == findprev(identity, b1, i) - @test findprevnot(b2, i) == findprev(!, b2, i) == i - end - - - odds = broadcast(isodd, 1:2000) - evens = broadcast(iseven, 1:2000) - - for i = 1:2:2000 - @test findprev(odds,i) == findprevnot(evens,i) == i - @test findnext(odds,i) == findnextnot(evens,i) == i - @test findprev(evens,i) == findprevnot(odds,i) == i-1 - @test findnext(evens,i) == findnextnot(odds,i) == (i < 2000 ? i+1 : 0) - end - for i = 2:2:2000 - @test findprev(odds,i) == findprevnot(evens,i) == i-1 - @test findprev(evens,i) == findprevnot(odds,i) == i - @test findnext(evens,i) == findnextnot(odds,i) == i - @test findnext(odds,i) == findnextnot(evens,i) == (i < 2000 ? i+1 : 0) - end - - elts = (1:64:(64*64+1)) .+ (0:64) - n = maximum(elts) - for c = [falses, trues] - b1 = c(n) - b1[elts] = .!b1[elts] - b2 = .~b1 - i1 = Array(b1) - for i = 1:n - @test findprev(b1, i) == findprev(i1, i) == findprevnot(b2, i) == findprev(!, b2, i) - @test findnext(b1, i) == findnext(i1, i) == findnextnot(b2, i) == findnext(!, b2, i) - end - end - - b1 = falses(1000) - b1[77] = true - b1[777] = true - b2 = .~b1 - @test_throws BoundsError findprev(b1, 1001) - @test_throws BoundsError findprevnot(b2, 1001) - @test_throws BoundsError findprev(!, b2, 1001) - @test_throws BoundsError findprev(identity, b1, 1001) - @test_throws BoundsError findprev(x->false, b1, 1001) - @test_throws BoundsError findprev(x->true, b1, 1001) - @test findprev(b1, 1000) == findprevnot(b2, 1000) == findprev(!, b2, 1000) == 777 - @test findprev(b1, 777) == findprevnot(b2, 777) == findprev(!, b2, 777) == 777 - @test findprev(b1, 776) == findprevnot(b2, 776) == findprev(!, b2, 776) == 77 - @test findprev(b1, 77) == findprevnot(b2, 77) == findprev(!, b2, 77) == 77 - @test findprev(b1, 76) == findprevnot(b2, 76) == findprev(!, b2, 76) == 0 - @test findprev(b1, -1) == findprevnot(b2, -1) == findprev(!, b2, -1) == 0 - @test findprev(identity, b1, -1) == findprev(x->false, b1, -1) == findprev(x->true, b1, -1) == 0 - @test_throws BoundsError findnext(b1, -1) - @test_throws BoundsError findnextnot(b2, -1) - @test_throws BoundsError findnext(!, b2, -1) - @test_throws BoundsError findnext(identity, b1, -1) - @test_throws BoundsError findnext(x->false, b1, -1) - @test_throws BoundsError findnext(x->true, b1, -1) - @test findnext(b1, 1) == findnextnot(b2, 1) == findnext(!, b2, 1) == 77 - @test findnext(b1, 77) == findnextnot(b2, 77) == findnext(!, b2, 77) == 77 - @test findnext(b1, 78) == findnextnot(b2, 78) == findnext(!, b2, 78) == 777 - @test findnext(b1, 777) == findnextnot(b2, 777) == findnext(!, b2, 777) == 777 - @test findnext(b1, 778) == findnextnot(b2, 778) == findnext(!, b2, 778) == 0 - @test findnext(b1, 1001) == findnextnot(b2, 1001) == findnext(!, b2, 1001) == 0 - @test findnext(identity, b1, 1001) == findnext(x->false, b1, 1001) == findnext(x->true, b1, 1001) == 0 - - @test findlast(b1) == Base.findlastnot(b2) == 777 - @test findfirst(b1) == Base.findfirstnot(b2) == 77 - - b0 = BitVector(0) - @test findprev(x->true, b0, -1) == 0 - @test_throws BoundsError findprev(x->true, b0, 1) - @test_throws BoundsError findnext(x->true, b0, -1) - @test findnext(x->true, b0, 1) == 0 - - b1 = falses(10) - @test findprev(x->true, b1, 5) == 5 - @test findnext(x->true, b1, 5) == 5 - @test findprev(x->true, b1, -1) == 0 - @test findnext(x->true, b1, 11) == 0 - @test findprev(x->false, b1, 5) == 0 - @test findnext(x->false, b1, 5) == 0 - @test findprev(x->false, b1, -1) == 0 - @test findnext(x->false, b1, 11) == 0 - @test_throws BoundsError findprev(x->true, b1, 11) - @test_throws BoundsError findnext(x->true, b1, -1) - - for l = [1, 63, 64, 65, 127, 128, 129] - f = falses(l) - t = trues(l) - @test findprev(f, l) == findprevnot(t, l) == 0 - @test findprev(t, l) == findprevnot(f, l) == l - b1 = falses(l) - b1[end] = true - b2 = .~b1 - @test findprev(b1, l) == findprevnot(b2, l) == l - @test findprevnot(b1, l) == findprev(b2, l) == l-1 - if l > 1 - b1 = falses(l) - b1[end-1] = true - b2 = .~b1 - @test findprev(b1, l) == findprevnot(b2, l) == l-1 - @test findprevnot(b1, l) == findprev(b2, l) == l - end - end -end - -@testset "Reductions" begin - b1 = bitrand(s1, s2, s3, s4) - m1 = 1 - m2 = 3 - @check_bit_operation maximum(b1, (m1, m2)) BitArray{4} - @check_bit_operation minimum(b1, (m1, m2)) BitArray{4} - @check_bit_operation sum(b1, (m1, m2)) Array{Int,4} - - @check_bit_operation maximum(b1) Bool - @check_bit_operation minimum(b1) Bool - @check_bit_operation any(b1) Bool - @check_bit_operation all(b1) Bool - @check_bit_operation sum(b1) Int - - b0 = falses(0) - @check_bit_operation any(b0) Bool - @check_bit_operation all(b0) Bool - @check_bit_operation sum(b0) Int -end - -timesofar("reductions") - -@testset "map over bitarrays" begin - for l = [0, 1, 63, 64, 65, 127, 128, 129, 255, 256, 257, 6399, 6400, 6401] - b1 = bitrand(l) - b2 = bitrand(l) - @test map(~, b1) == map(x->~x, b1) == broadcast(~, b1) - @test map(identity, b1) == map(x->x, b1) == b1 - - @test map(&, b1, b2) == map((x,y)->x&y, b1, b2) == broadcast(&, b1, b2) - @test map(|, b1, b2) == map((x,y)->x|y, b1, b2) == broadcast(|, b1, b2) - @test map(⊻, b1, b2) == map((x,y)->x⊻y, b1, b2) == broadcast(⊻, b1, b2) == broadcast(xor, b1, b2) - - @test map(^, b1, b2) == map((x,y)->x^y, b1, b2) == b1 .^ b2 - @test map(*, b1, b2) == map((x,y)->x*y, b1, b2) == b1 .* b2 - - @test map(min, b1, b2) == map((x,y)->min(x,y), b1, b2) == min.(b1, b2) - @test map(max, b1, b2) == map((x,y)->max(x,y), b1, b2) == max.(b1, b2) - - @test map(<, b1, b2) == map((x,y)->x<y, b1, b2) == (b1 .< b2) - @test map(<=, b1, b2) == map((x,y)->x<=y, b1, b2) == (b1 .<= b2) - @test map(==, b1, b2) == map((x,y)->x==y, b1, b2) == (b1 .== b2) - @test map(>=, b1, b2) == map((x,y)->x>=y, b1, b2) == (b1 .>= b2) - @test map(>, b1, b2) == map((x,y)->x>y, b1, b2) == (b1 .> b2) - @test map(!=, b1, b2) == map((x,y)->x!=y, b1, b2) == (b1 .!= b2) - - @testset "map! for length $l" begin - b = BitArray(l) - @test map!(~, b, b1) == map!(x->~x, b, b1) == broadcast(~, b1) == b - @test map!(!, b, b1) == map!(x->!x, b, b1) == broadcast(~, b1) == b - @test map!(identity, b, b1) == map!(x->x, b, b1) == b1 == b - @test map!(zero, b, b1) == map!(x->false, b, b1) == falses(l) == b - @test map!(one, b, b1) == map!(x->true, b, b1) == trues(l) == b - - @test map!(&, b, b1, b2) == map!((x,y)->x&y, b, b1, b2) == broadcast(&, b1, b2) == b - @test map!(|, b, b1, b2) == map!((x,y)->x|y, b, b1, b2) == broadcast(|, b1, b2) == b - @test map!(⊻, b, b1, b2) == map!((x,y)->x⊻y, b, b1, b2) == broadcast(⊻, b1, b2) == broadcast(xor, b1, b2) == b - - @test map!(^, b, b1, b2) == map!((x,y)->x^y, b, b1, b2) == b1 .^ b2 == b - @test map!(*, b, b1, b2) == map!((x,y)->x*y, b, b1, b2) == b1 .* b2 == b - - @test map!(min, b, b1, b2) == map!((x,y)->min(x,y), b, b1, b2) == min.(b1, b2) == b - @test map!(max, b, b1, b2) == map!((x,y)->max(x,y), b, b1, b2) == max.(b1, b2) == b - - @test map!(<, b, b1, b2) == map!((x,y)->x<y, b, b1, b2) == (b1 .< b2) == b - @test map!(<=, b, b1, b2) == map!((x,y)->x<=y, b, b1, b2) == (b1 .<= b2) == b - @test map!(==, b, b1, b2) == map!((x,y)->x==y, b, b1, b2) == (b1 .== b2) == b - @test map!(>=, b, b1, b2) == map!((x,y)->x>=y, b, b1, b2) == (b1 .>= b2) == b - @test map!(>, b, b1, b2) == map!((x,y)->x>y, b, b1, b2) == (b1 .> b2) == b - @test map!(!=, b, b1, b2) == map!((x,y)->x!=y, b, b1, b2) == (b1 .!= b2) == b - end - end - - @testset "Issue #17970" begin - A17970 = [1,2,3] .== [3,2,1] - B17970 = map(x -> x ? 1 : 2, A17970) - @test B17970::Array{Int,1} == [2,1,2] - C17970 = map(x -> x ? false : true, A17970) - @test C17970::BitArray{1} == map(~, A17970) - end -end - -## Filter ## - -# TODO - -@testset "Transpose" begin - b1 = bitrand(v1) - @check_bit_operation transpose(b1) RowVector{Bool,BitVector} - - for m1 = 0:n1, m2 = 0:n2 - b1 = bitrand(m1, m2) - @check_bit_operation transpose(b1) BitMatrix - end -end - -timesofar("transpose") - -@testset "Permutedims" begin - b1 = bitrand(s1, s2, s3, s4) - p = randperm(4) - @check_bit_operation permutedims(b1, p) BitArray{4} - @check_bit_operation permutedims(b1, tuple(p...)) BitArray{4} -end - -timesofar("permutedims") - -@testset "Concatenation" begin - b1 = bitrand(v1) - b2 = bitrand(v1) - @check_bit_operation hcat(b1, b2) BitMatrix - for m = 1:(v1-1) - @check_bit_operation vcat(b1[1:m], b1[m+1:end]) BitVector - end - @test_throws DimensionMismatch hcat(b1,trues(n1+1)) - @test_throws DimensionMismatch hcat(hcat(b1, b2),trues(n1+1)) - - b1 = bitrand(n1, n2) - b2 = bitrand(n1) - b3 = bitrand(n1, n2) - b4 = bitrand(1, n2) - @check_bit_operation hcat(b1, b2, b3) BitMatrix - @check_bit_operation vcat(b1, b4, b3) BitMatrix - @test_throws DimensionMismatch vcat(b1, b4, trues(n1,n2+1)) - - b1 = bitrand(s1, s2, s3, s4) - b2 = bitrand(s1, s3, s3, s4) - b3 = bitrand(s1, s2, s3, s1) - @check_bit_operation cat(2, b1, b2) BitArray{4} - @check_bit_operation cat(4, b1, b3) BitArray{4} - @check_bit_operation cat(6, b1, b1) BitArray{6} - - b1 = bitrand(1, v1, 1) - @check_bit_operation cat(2, 0, b1, 1, 1, b1) Array{Int,3} - @check_bit_operation cat(2, 3, b1, 4, 5, b1) Array{Int,3} - @check_bit_operation cat(2, false, b1, true, true, b1) BitArray{3} - - b1 = bitrand(n1, n2) - for m1 = 1:(n1-1), m2 = 1:(n2-1) - @test isequal([b1[1:m1,1:m2] b1[1:m1,m2+1:end]; b1[m1+1:end,1:m2] b1[m1+1:end,m2+1:end]], b1) - end -end - -timesofar("cat") - -@testset "Linear algebra" begin - b1 = bitrand(v1) - b2 = bitrand(v1) - @check_bit_operation dot(b1, b2) Int - - b1 = bitrand(n1, n2) - for k = (-n1):n2 - @check_bit_operation tril(b1, k) BitMatrix - @check_bit_operation triu(b1, k) BitMatrix - end - - for sz = [(n1,n1), (n1,n2), (n2,n1)], (f,isf) = [(tril,istril), (triu,istriu)] - b1 = bitrand(sz...) - @check_bit_operation isf(b1) Bool - b1 = f(bitrand(sz...)) - @check_bit_operation isf(b1) Bool - end - - b1 = bitrand(n1,n1) - b1 .|= b1.' - @check_bit_operation issymmetric(b1) Bool - @check_bit_operation ishermitian(b1) Bool - - b1 = bitrand(n1) - b2 = bitrand(n2) - @check_bit_operation kron(b1, b2) BitVector - - b1 = bitrand(s1, s2) - b2 = bitrand(s3, s4) - @check_bit_operation kron(b1, b2) BitMatrix - - b1 = bitrand(v1) - @check_bit_operation diff(b1) Vector{Int} - - b1 = bitrand(n1, n2) - @check_bit_operation diff(b1) Matrix{Int} - - b1 = bitrand(n1, n1) - @check_bit_operation svd(b1) - @check_bit_operation qr(b1) - - b1 = bitrand(v1) - @check_bit_operation gradient(b1) - @check_bit_operation gradient(b1, 1.0) - - b1 = bitrand(v1) - @check_bit_operation diagm(b1) BitMatrix - - b1 = bitrand(n1, n2) - @test_throws DimensionMismatch diagm(b1) - - b1 = bitrand(n1, n1) - @check_bit_operation diag(b1) -end - -timesofar("linalg") - -@testset "findmax, findmin" begin - b1 = trues(0) - @test_throws ArgumentError findmax(b1) - @test_throws ArgumentError findmin(b1) - - for b1 in [falses(v1), trues(v1), - BitArray([1,0,1,1,0]), - BitArray([0,0,1,1,0]), - bitrand(v1)] - @check_bit_operation findmin(b1) - @check_bit_operation findmax(b1) - end -end - -@testset "I/O" begin - b1 = bitrand(v1) - fname = "" - b1[v1 ÷ 2 + 1] = true - b1[end] = true - try - fname = tempname() - open(fname, "w") do f - write(f, b1) - end - b2 = falses(v1) - read!(fname, b2) - @test bitcheck(b2) - @test b1 == b2 - b2 = falses(v1 ÷ 10, 10) - read!(fname, b2) - @test bitcheck(b2) - @test reshape(b1, v1 ÷ 10, 10) == b2 - b2 = falses(v1 + 65) - @test bitcheck(b2) - @test_throws EOFError read!(fname, b2) - @test bitcheck(b2) - b2 = falses(v1 ÷ 2) - @test_throws DimensionMismatch read!(fname, b2) - @test bitcheck(b2) - b2 = falses(v1 - 1) - @test_throws DimensionMismatch read!(fname, b2) - @test bitcheck(b2) - - b1 = BitArray(0) - open(fname, "w") do f - write(f, b1) - end - b2 = BitArray(0) - read!(fname, b2) - @test b1 == b2 - @test bitcheck(b2) - b2 = trues(1) - @test_throws EOFError read!(fname, b2) - @test bitcheck(b2) - finally - isfile(fname) && rm(fname) - end -end - -timesofar("I/O") diff --git a/julia-0.6.3/share/julia/test/blas.jl b/julia-0.6.3/share/julia/test/blas.jl deleted file mode 100644 index 56ebdde..0000000 --- a/julia-0.6.3/share/julia/test/blas.jl +++ /dev/null @@ -1,325 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -import Base.LinAlg, Base.LinAlg.BlasReal, Base.LinAlg.BlasComplex - -srand(100) -## BLAS tests - testing the interface code to BLAS routines -@testset for elty in [Float32, Float64, Complex64, Complex128] - @testset "syr2k!" begin - U = randn(5,2) - V = randn(5,2) - if elty == Complex64 || elty == Complex128 - U = complex.(U, U) - V = complex.(V, V) - end - U = convert(Array{elty, 2}, U) - V = convert(Array{elty, 2}, V) - @test tril(LinAlg.BLAS.syr2k('L','N',U,V)) ≈ tril(U*V.' + V*U.') - @test triu(LinAlg.BLAS.syr2k('U','N',U,V)) ≈ triu(U*V.' + V*U.') - @test tril(LinAlg.BLAS.syr2k('L','T',U,V)) ≈ tril(U.'*V + V.'*U) - @test triu(LinAlg.BLAS.syr2k('U','T',U,V)) ≈ triu(U.'*V + V.'*U) - end - - if elty in (Complex64, Complex128) - @testset "her2k!" begin - U = randn(5,2) - V = randn(5,2) - U = complex.(U, U) - V = complex.(V, V) - U = convert(Array{elty, 2}, U) - V = convert(Array{elty, 2}, V) - @test tril(LinAlg.BLAS.her2k('L','N',U,V)) ≈ tril(U*V' + V*U') - @test triu(LinAlg.BLAS.her2k('U','N',U,V)) ≈ triu(U*V' + V*U') - @test tril(LinAlg.BLAS.her2k('L','C',U,V)) ≈ tril(U'*V + V'*U) - @test triu(LinAlg.BLAS.her2k('U','C',U,V)) ≈ triu(U'*V + V'*U) - end - end - - o4 = ones(elty, 4) - z4 = zeros(elty, 4) - - I4 = eye(elty, 4) - I43 = eye(elty, 4, 3) - L4 = tril(ones(elty, (4,4))) - U4 = triu(ones(elty, (4,4))) - Z4 = zeros(elty, (4,4)) - - elm1 = convert(elty, -1) - el2 = convert(elty, 2) - v14 = convert(Vector{elty}, [1:4;]) - v41 = convert(Vector{elty}, [4:-1:1;]) - - let n = 10 - @testset "dot products" begin - if elty <: Real - x1 = convert(Vector{elty}, randn(n)) - x2 = convert(Vector{elty}, randn(n)) - @test BLAS.dot(x1,x2) ≈ sum(x1.*x2) - @test_throws DimensionMismatch BLAS.dot(x1,rand(elty, n + 1)) - else - z1 = convert(Vector{elty}, complex.(randn(n),randn(n))) - z2 = convert(Vector{elty}, complex.(randn(n),randn(n))) - @test BLAS.dotc(z1,z2) ≈ sum(conj(z1).*z2) - @test BLAS.dotu(z1,z2) ≈ sum(z1.*z2) - @test_throws DimensionMismatch BLAS.dotc(z1,rand(elty, n + 1)) - @test_throws DimensionMismatch BLAS.dotu(z1,rand(elty, n + 1)) - end - end - @testset "iamax" begin - if elty <: Real - x = convert(Vector{elty}, randn(n)) - @test BLAS.iamax(x) == indmax(abs.(x)) - else - z = convert(Vector{elty}, complex.(randn(n),randn(n))) - @test BLAS.iamax(z) == indmax(map(x -> abs(real(x)) + abs(imag(x)), z)) - end - end - @testset "axpy" begin - if elty <: Real - x1 = convert(Vector{elty}, randn(n)) - x2 = convert(Vector{elty}, randn(n)) - α = rand(elty) - @test BLAS.axpy!(α,copy(x1),copy(x2)) ≈ x2 + α*x1 - @test_throws DimensionMismatch BLAS.axpy!(α, copy(x1), rand(elty, n + 1)) - @test_throws DimensionMismatch BLAS.axpy!(α, copy(x1), 1:div(n,2), copy(x2), 1:n) - @test_throws ArgumentError BLAS.axpy!(α, copy(x1), 0:div(n,2), copy(x2), 1:(div(n, 2) + 1)) - @test_throws ArgumentError BLAS.axpy!(α, copy(x1), 1:div(n,2), copy(x2), 0:(div(n, 2) - 1)) - @test BLAS.axpy!(α,copy(x1),1:n,copy(x2),1:n) ≈ x2 + α*x1 - else - z1 = convert(Vector{elty}, complex.(randn(n), randn(n))) - z2 = convert(Vector{elty}, complex.(randn(n), randn(n))) - α = rand(elty) - @test BLAS.axpy!(α, copy(z1), copy(z2)) ≈ z2 + α * z1 - @test_throws DimensionMismatch BLAS.axpy!(α, copy(z1), rand(elty, n + 1)) - @test_throws DimensionMismatch BLAS.axpy!(α, copy(z1), 1:div(n, 2), copy(z2), 1:(div(n, 2) + 1)) - @test_throws ArgumentError BLAS.axpy!(α, copy(z1), 0:div(n,2), copy(z2), 1:(div(n, 2) + 1)) - @test_throws ArgumentError BLAS.axpy!(α, copy(z1), 1:div(n,2), copy(z2), 0:(div(n, 2) - 1)) - @test BLAS.axpy!(α,copy(z1),1:n,copy(z2),1:n) ≈ z2 + α*z1 - end - end - @testset "nrm2, iamax, and asum for StridedVectors" begin - a = rand(elty,n) - b = view(a,2:2:n,1) - @test BLAS.nrm2(b) ≈ norm(b) - if elty <: Real - @test BLAS.asum(b) ≈ sum(abs.(b)) - @test BLAS.iamax(b) ≈ indmax(abs.(b)) - else - @test BLAS.asum(b) ≈ sum(abs.(real(b))) + sum(abs.(imag(b))) - @test BLAS.iamax(b) == indmax(map(x -> abs(real(x)) + abs(imag(x)), b)) - end - end - # scal - α = rand(elty) - a = rand(elty,n) - @test BLAS.scal(n,α,a,1) ≈ α * a - - @testset "trsv" begin - A = triu(rand(elty,n,n)) - @testset "Vector and SubVector" for x in (rand(elty, n), view(rand(elty,2n),1:2:2n)) - @test A\x ≈ BLAS.trsv('U','N','N',A,x) - @test_throws DimensionMismatch BLAS.trsv('U','N','N',A,ones(elty,n+1)) - end - end - @testset "ger, her, syr" for x in (rand(elty, n), view(rand(elty,2n), 1:2:2n)), - y in (rand(elty,n), view(rand(elty,3n), 1:3:3n)) - - A = rand(elty,n,n) - α = rand(elty) - - @test BLAS.ger!(α,x,y,copy(A)) ≈ A + α*x*y' - @test_throws DimensionMismatch BLAS.ger!(α,ones(elty,n+1),y,copy(A)) - - A = rand(elty,n,n) - A = A + A.' - @test issymmetric(A) - @test triu(BLAS.syr!('U',α,x,copy(A))) ≈ triu(A + α*x*x.') - @test_throws DimensionMismatch BLAS.syr!('U',α,ones(elty,n+1),copy(A)) - - if elty <: Complex - A = rand(elty,n,n) - A = A + A' - α = real(α) - @test triu(BLAS.her!('U',α,x,copy(A))) ≈ triu(A + α*x*x') - @test_throws DimensionMismatch BLAS.her!('U',α,ones(elty,n+1),copy(A)) - end - end - @testset "copy" begin - x1 = convert(Vector{elty}, randn(n)) - x2 = convert(Vector{elty}, randn(n)) - BLAS.copy!(x2, 1:n, x1, 1:n) - @test x2 == x1 - @test_throws DimensionMismatch BLAS.copy!(x2, 1:n, x1, 1:(n - 1)) - @test_throws ArgumentError BLAS.copy!(x1, 0:div(n, 2), x2, 1:(div(n, 2) + 1)) - @test_throws ArgumentError BLAS.copy!(x1, 1:(div(n, 2) + 1), x2, 0:div(n, 2)) - end - # trmv - A = triu(rand(elty,n,n)) - x = rand(elty,n) - @test BLAS.trmv('U','N','N',A,x) ≈ A*x - @testset "symmetric/Hermitian multiplication" begin - x = rand(elty,n) - A = rand(elty,n,n) - Aherm = A + A' - Asymm = A + A.' - @testset "symv and hemv" begin - @test BLAS.symv('U',Asymm,x) ≈ Asymm*x - @test_throws DimensionMismatch BLAS.symv!('U',one(elty),Asymm,x,one(elty),ones(elty,n+1)) - @test_throws DimensionMismatch BLAS.symv('U',ones(elty,n,n+1),x) - if elty <: BlasComplex - @test BLAS.hemv('U',Aherm,x) ≈ Aherm*x - @test_throws DimensionMismatch BLAS.hemv('U',ones(elty,n,n+1),x) - @test_throws DimensionMismatch BLAS.hemv!('U',one(elty),Aherm,x,one(elty),ones(elty,n+1)) - end - end - - @testset "symm error throwing" begin - @test_throws DimensionMismatch BLAS.symm('L','U',ones(elty,n,n-1),rand(elty,n,n)) - @test_throws DimensionMismatch BLAS.symm('R','U',ones(elty,n-1,n),rand(elty,n,n)) - @test_throws DimensionMismatch BLAS.symm!('L','U',one(elty),Asymm,ones(elty,n,n),one(elty),rand(elty,n-1,n)) - @test_throws DimensionMismatch BLAS.symm!('L','U',one(elty),Asymm,ones(elty,n,n),one(elty),rand(elty,n,n-1)) - if elty <: BlasComplex - @test_throws DimensionMismatch BLAS.hemm('L','U',ones(elty,n,n-1),rand(elty,n,n)) - @test_throws DimensionMismatch BLAS.hemm('R','U',ones(elty,n-1,n),rand(elty,n,n)) - @test_throws DimensionMismatch BLAS.hemm!('L','U',one(elty),Aherm,ones(elty,n,n),one(elty),rand(elty,n-1,n)) - @test_throws DimensionMismatch BLAS.hemm!('L','U',one(elty),Aherm,ones(elty,n,n),one(elty),rand(elty,n,n-1)) - end - end - end - @testset "trmm error throwing" begin - @test_throws DimensionMismatch BLAS.trmm('L','U','N','N',one(elty),triu(rand(elty,n,n)),ones(elty,n+1,n)) - @test_throws DimensionMismatch BLAS.trmm('R','U','N','N',one(elty),triu(rand(elty,n,n)),ones(elty,n,n+1)) - end - - #trsm - A = triu(rand(elty,n,n)) - B = rand(elty,(n,n)) - @test BLAS.trsm('L','U','N','N',one(elty),A,B) ≈ A\B - - #will work for SymTridiagonal,Tridiagonal,Bidiagonal! - @testset "banded matrix mv" begin - @testset "gbmv" begin - TD = Tridiagonal(rand(elty,n-1),rand(elty,n),rand(elty,n-1)) - x = rand(elty,n) - #put TD into the BLAS format! - fTD = zeros(elty,3,n) - fTD[1,2:n] = TD.du - fTD[2,:] = TD.d - fTD[3,1:n-1] = TD.dl - @test BLAS.gbmv('N',n,1,1,fTD,x) ≈ TD*x - end - #will work for SymTridiagonal only! - @testset "sbmv" begin - if elty <: BlasReal - ST = SymTridiagonal(rand(elty,n),rand(elty,n-1)) - x = rand(elty,n) - #put TD into the BLAS format! - fST = zeros(elty,2,n) - fST[1,2:n] = ST.ev - fST[2,:] = ST.dv - @test BLAS.sbmv('U',1,fST,x) ≈ ST*x - else - dv = real(rand(elty,n)) - ev = rand(elty,n-1) - bH = zeros(elty,2,n) - bH[1,2:n] = ev - bH[2,:] = dv - fullH = diagm(dv) + diagm(conj(ev),-1) + diagm(ev,1) - @test BLAS.hbmv('U',1,bH,x) ≈ fullH*x - end - end - end - end - - @testset "gemv" begin - @test all(BLAS.gemv('N', I4, o4) .== o4) - @test all(BLAS.gemv('T', I4, o4) .== o4) - @test all(BLAS.gemv('N', el2, I4, o4) .== el2 * o4) - @test all(BLAS.gemv('T', el2, I4, o4) .== el2 * o4) - @test_throws DimensionMismatch BLAS.gemv('N',I43,o4) - o4cp = copy(o4) - @test_throws DimensionMismatch BLAS.gemv!('T',one(elty),I43,o4,one(elty),o4cp) - @test_throws DimensionMismatch BLAS.gemv!('C',one(elty),I43,o4,one(elty),o4cp) - @test all(BLAS.gemv!('N', one(elty), I4, o4, elm1, o4cp) .== z4) - @test all(o4cp .== z4) - o4cp[:] = o4 - @test all(BLAS.gemv!('T', one(elty), I4, o4, elm1, o4cp) .== z4) - @test all(o4cp .== z4) - @test all(BLAS.gemv('N', U4, o4) .== v41) - @test all(BLAS.gemv('N', U4, o4) .== v41) - end - @testset "gemm" begin - @test all(BLAS.gemm('N', 'N', I4, I4) .== I4) - @test all(BLAS.gemm('N', 'T', I4, I4) .== I4) - @test all(BLAS.gemm('T', 'N', I4, I4) .== I4) - @test all(BLAS.gemm('T', 'T', I4, I4) .== I4) - @test all(BLAS.gemm('N', 'N', el2, I4, I4) .== el2 * I4) - @test all(BLAS.gemm('N', 'T', el2, I4, I4) .== el2 * I4) - @test all(BLAS.gemm('T', 'N', el2, I4, I4) .== el2 * I4) - @test all(LinAlg.BLAS.gemm('T', 'T', el2, I4, I4) .== el2 * I4) - I4cp = copy(I4) - @test all(BLAS.gemm!('N', 'N', one(elty), I4, I4, elm1, I4cp) .== Z4) - @test all(I4cp .== Z4) - I4cp[:] = I4 - @test all(BLAS.gemm!('N', 'T', one(elty), I4, I4, elm1, I4cp) .== Z4) - @test all(I4cp .== Z4) - I4cp[:] = I4 - @test all(BLAS.gemm!('T', 'N', one(elty), I4, I4, elm1, I4cp) .== Z4) - @test all(I4cp .== Z4) - I4cp[:] = I4 - @test all(BLAS.gemm!('T', 'T', one(elty), I4, I4, elm1, I4cp) .== Z4) - @test all(I4cp .== Z4) - @test all(BLAS.gemm('N', 'N', I4, U4) .== U4) - @test all(BLAS.gemm('N', 'T', I4, U4) .== L4) - @test_throws DimensionMismatch BLAS.gemm!('N','N', one(elty), I4, I4, elm1, eye(elty,5)) - @test_throws DimensionMismatch BLAS.gemm!('N','N', one(elty), I43, I4, elm1, I4) - @test_throws DimensionMismatch BLAS.gemm!('T','N', one(elty), I43, I4, elm1, I43) - @test_throws DimensionMismatch BLAS.gemm!('N','T', one(elty), I43, I43, elm1, I43) - @test_throws DimensionMismatch BLAS.gemm!('T','T', one(elty), I43, I43, elm1, I43') - end - @testset "gemm compared to (sy)(he)rk" begin - if eltype(elm1) <: Complex - @test all(triu(BLAS.herk('U', 'N', U4)) .== triu(BLAS.gemm('N', 'T', U4, U4))) - @test all(tril(BLAS.herk('L', 'N', U4)) .== tril(BLAS.gemm('N', 'T', U4, U4))) - @test all(triu(BLAS.herk('U', 'N', L4)) .== triu(BLAS.gemm('N', 'T', L4, L4))) - @test all(tril(BLAS.herk('L', 'N', L4)) .== tril(BLAS.gemm('N', 'T', L4, L4))) - @test all(triu(BLAS.herk('U', 'C', U4)) .== triu(BLAS.gemm('T', 'N', U4, U4))) - @test all(tril(BLAS.herk('L', 'C', U4)) .== tril(BLAS.gemm('T', 'N', U4, U4))) - @test all(triu(BLAS.herk('U', 'C', L4)) .== triu(BLAS.gemm('T', 'N', L4, L4))) - @test all(tril(BLAS.herk('L', 'C', L4)) .== tril(BLAS.gemm('T', 'N', L4, L4))) - ans = similar(L4) - @test all(tril(BLAS.herk('L','C', L4)) .== tril(BLAS.herk!('L', 'C', real(one(elty)), L4, real(zero(elty)), ans))) - @test all(Base.LinAlg.copytri!(ans, 'L') .== LinAlg.BLAS.gemm('T', 'N', L4, L4)) - @test_throws DimensionMismatch BLAS.herk!('L','N',real(one(elty)),eye(elty,5),real(one(elty)),eye(elty,6)) - else - @test all(triu(BLAS.syrk('U', 'N', U4)) .== triu(BLAS.gemm('N', 'T', U4, U4))) - @test all(tril(BLAS.syrk('L', 'N', U4)) .== tril(BLAS.gemm('N', 'T', U4, U4))) - @test all(triu(BLAS.syrk('U', 'N', L4)) .== triu(BLAS.gemm('N', 'T', L4, L4))) - @test all(tril(BLAS.syrk('L', 'N', L4)) .== tril(BLAS.gemm('N', 'T', L4, L4))) - @test all(triu(BLAS.syrk('U', 'T', U4)) .== triu(BLAS.gemm('T', 'N', U4, U4))) - @test all(tril(BLAS.syrk('L', 'T', U4)) .== tril(BLAS.gemm('T', 'N', U4, U4))) - @test all(triu(BLAS.syrk('U', 'T', L4)) .== triu(BLAS.gemm('T', 'N', L4, L4))) - @test all(tril(BLAS.syrk('L', 'T', L4)) .== tril(BLAS.gemm('T', 'N', L4, L4))) - ans = similar(L4) - @test all(tril(BLAS.syrk('L','T', L4)) .== tril(BLAS.syrk!('L', 'T', one(elty), L4, zero(elty), ans))) - @test all(Base.LinAlg.copytri!(ans, 'L') .== BLAS.gemm('T', 'N', L4, L4)) - @test_throws DimensionMismatch BLAS.syrk!('L','N',one(elty),eye(elty,5),one(elty),eye(elty,6)) - end - end -end - -@testset "syr for eltype $elty" for elty in (Float32, Float64, Complex{Float32}, Complex{Float64}) - A = rand(elty, 5, 5) - @test triu(A[1,:] * A[1,:].') ≈ BLAS.syr!('U', one(elty), A[1,:], zeros(elty, 5, 5)) - @test tril(A[1,:] * A[1,:].') ≈ BLAS.syr!('L', one(elty), A[1,:], zeros(elty, 5, 5)) - @test triu(A[1,:] * A[1,:].') ≈ BLAS.syr!('U', one(elty), view(A, 1, :), zeros(elty, 5, 5)) - @test tril(A[1,:] * A[1,:].') ≈ BLAS.syr!('L', one(elty), view(A, 1, :), zeros(elty, 5, 5)) -end - -@testset "her for eltype $elty" for elty in (Complex{Float32}, Complex{Float64}) - A = rand(elty, 5, 5) - @test triu(A[1,:] * A[1,:]') ≈ BLAS.her!('U', one(real(elty)), A[1,:], zeros(elty, 5, 5)) - @test tril(A[1,:] * A[1,:]') ≈ BLAS.her!('L', one(real(elty)), A[1,:], zeros(elty, 5, 5)) - @test triu(A[1,:] * A[1,:]') ≈ BLAS.her!('U', one(real(elty)), view(A, 1, :), zeros(elty, 5, 5)) - @test tril(A[1,:] * A[1,:]') ≈ BLAS.her!('L', one(real(elty)), view(A, 1, :), zeros(elty, 5, 5)) -end diff --git a/julia-0.6.3/share/julia/test/boundscheck.jl b/julia-0.6.3/share/julia/test/boundscheck.jl deleted file mode 100644 index a1ca1b8..0000000 --- a/julia-0.6.3/share/julia/test/boundscheck.jl +++ /dev/null @@ -1,18 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -# run boundscheck tests on separate workers launched with --check-bounds={default,yes,no} - -cmd = `$(Base.julia_cmd()) --depwarn=error --startup-file=no boundscheck_exec.jl` -if !success(pipeline(cmd; stdout=STDOUT, stderr=STDERR)) - error("boundscheck test failed, cmd : $cmd") -end - -cmd = `$(Base.julia_cmd()) --check-bounds=yes --startup-file=no --depwarn=error boundscheck_exec.jl` -if !success(pipeline(cmd; stdout=STDOUT, stderr=STDERR)) - error("boundscheck test failed, cmd : $cmd") -end - -cmd = `$(Base.julia_cmd()) --check-bounds=no --startup-file=no --depwarn=error boundscheck_exec.jl` -if !success(pipeline(cmd; stdout=STDOUT, stderr=STDERR)) - error("boundscheck test failed, cmd : $cmd") -end diff --git a/julia-0.6.3/share/julia/test/boundscheck_exec.jl b/julia-0.6.3/share/julia/test/boundscheck_exec.jl deleted file mode 100644 index e6ec13f..0000000 --- a/julia-0.6.3/share/julia/test/boundscheck_exec.jl +++ /dev/null @@ -1,212 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -module TestBoundsCheck - -using Base.Test - -@enum BCOption bc_default bc_on bc_off -bc_opt = BCOption(Base.JLOptions().check_bounds) - -# test for boundscheck block eliminated at same level -@inline function A1() - r = 0 - @boundscheck r += 1 - return r -end - -@noinline function A1_noinline() - r = 0 - @boundscheck r += 1 - return r -end - -function A1_inbounds() - r = 0 - @inbounds begin - @boundscheck r += 1 - end - return r -end - -if bc_opt == bc_default - @test A1() == 1 - @test A1_inbounds() == 0 -elseif bc_opt == bc_on - @test A1() == 1 - @test A1_inbounds() == 1 -else - @test A1() == 0 - @test A1_inbounds() == 0 -end - -# test for boundscheck block eliminated one layer deep, if the called method is inlined -@inline function A2() - r = A1()+1 - return r -end - -function A2_inbounds() - @inbounds r = A1()+1 - return r -end - -function A2_notinlined() - @inbounds r = A1_noinline()+1 - return r -end - -Base.@propagate_inbounds function A2_propagate_inbounds() - r = A1()+1 - return r -end - -if bc_opt == bc_default - @test A2() == 2 - @test A2_inbounds() == 1 - @test A2_notinlined() == 2 - @test A2_propagate_inbounds() == 2 -elseif bc_opt == bc_on - @test A2() == 2 - @test A2_inbounds() == 2 - @test A2_notinlined() == 2 - @test A2_propagate_inbounds() == 2 -else - @test A2() == 1 - @test A2_inbounds() == 1 - @test A2_notinlined() == 1 - @test A2_propagate_inbounds() == 1 -end - -# test boundscheck NOT eliminated two layers deep, unless propagated - -function A3() - r = A2()+1 - return r -end - -function A3_inbounds() - @inbounds r = A2()+1 - return r -end - -function A3_inbounds2() - @inbounds r = A2_propagate_inbounds()+1 - return r -end - -if bc_opt == bc_default - @test A3() == 3 - @test A3_inbounds() == 3 - @test A3_inbounds2() == 2 -elseif bc_opt == bc_on - @test A3() == 3 - @test A3_inbounds() == 3 - @test A3_inbounds2() == 3 -else - @test A3() == 2 - @test A3_inbounds() == 2 - @test A3_inbounds2() == 2 -end - -# swapped nesting order of @boundscheck and @inbounds -function A1_nested() - r = 0 - @boundscheck @inbounds r += 1 - return r -end - -if bc_opt == bc_default || bc_opt == bc_on - @test A1_nested() == 1 -else - @test A1_nested() == 0 -end - -# elide a throw -cb(x) = x > 0 || throw(BoundsError()) - -function B1() - y = [1,2,3] - @inbounds begin - @boundscheck cb(0) - end - return 0 -end - -if bc_opt == bc_default || bc_opt == bc_off - @test B1() == 0 -else - @test_throws BoundsError B1() -end - -# elide a simple branch -cond(x) = x > 0 ? x : -x - -function B2() - y = [1,2,3] - @inbounds begin - @boundscheck cond(0) - end - return 0 -end - -@test B2() == 0 - -# Make sure type inference doesn't incorrectly optimize out -# `Expr(:inbounds, false)` -# Simply `return a[1]` doesn't work due to inlining bug -@inline function f1(a) - # This has to be an arrayget / arrayset since these currently have a - # implicit `Expr(:boundscheck)` that's not visible to type inference - x = a[1] - return x -end -# second level -@inline function g1(a) - x = f1(a) - return x -end -function k1(a) - # This `Expr(:inbounds, true)` shouldn't affect `f1` - @inbounds x = g1(a) - return x -end -if bc_opt != bc_off - @test_throws BoundsError k1(Int[]) -end - -# Ensure that broadcast doesn't use @inbounds when calling the function -if bc_opt != bc_off - let A = zeros(3,3) - @test_throws BoundsError broadcast(getindex, A, 1:3, 1:3) - end -end - -# issue #19554 -function f19554(a) - a[][3] -end -function f19554_2(a, b) - a[][3] = b - return a -end -a19554 = Ref{Array{Float64}}([1 2; 3 4]) -@test f19554(a19554) === 2.0 -@test f19554_2(a19554, 1) === a19554 -@test a19554[][3] === f19554(a19554) === 1.0 - -# Ensure unsafe_view doesn't check bounds -function V1() - A = rand(10,10) - B = view(A, 4:7, 4:7) - C = Base.unsafe_view(B, -2:7, -2:7) - @test C == A - nothing -end - -if bc_opt == bc_default || bc_opt == bc_off - @test V1() === nothing -else - @test_throws BoundsError V1() -end - -end diff --git a/julia-0.6.3/share/julia/test/broadcast.jl b/julia-0.6.3/share/julia/test/broadcast.jl deleted file mode 100644 index 9fe4b4f..0000000 --- a/julia-0.6.3/share/julia/test/broadcast.jl +++ /dev/null @@ -1,544 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -module TestBroadcastInternals - -using Base.Broadcast: broadcast_indices, check_broadcast_indices, - check_broadcast_shape, newindex, _bcs, _bcsm -using Base: Test, OneTo - -@test @inferred(_bcs((), (3,5), (3,5))) == (3,5) -@test @inferred(_bcs((), (3,1), (3,5))) == (3,5) -@test @inferred(_bcs((), (3,), (3,5))) == (3,5) -@test @inferred(_bcs((), (3,5), (3,))) == (3,5) -@test_throws DimensionMismatch _bcs((), (3,5), (4,5)) -@test_throws DimensionMismatch _bcs((), (3,5), (3,4)) -@test @inferred(_bcs((), (-1:1, 2:5), (-1:1, 2:5))) == (-1:1, 2:5) -@test @inferred(_bcs((), (-1:1, 2:5), (1, 2:5))) == (-1:1, 2:5) -@test @inferred(_bcs((), (-1:1, 1), (1, 2:5))) == (-1:1, 2:5) -@test @inferred(_bcs((), (-1:1,), (-1:1, 2:5))) == (-1:1, 2:5) -@test_throws DimensionMismatch _bcs((), (-1:1, 2:6), (-1:1, 2:5)) -@test_throws DimensionMismatch _bcs((), (-1:1, 2:5), (2, 2:5)) - -@test @inferred(broadcast_indices(zeros(3,4), zeros(3,4))) == (OneTo(3),OneTo(4)) -@test @inferred(broadcast_indices(zeros(3,4), zeros(3))) == (OneTo(3),OneTo(4)) -@test @inferred(broadcast_indices(zeros(3), zeros(3,4))) == (OneTo(3),OneTo(4)) -@test @inferred(broadcast_indices(zeros(3), zeros(1,4), zeros(1))) == (OneTo(3),OneTo(4)) - -check_broadcast_indices((OneTo(3),OneTo(5)), zeros(3,5)) -check_broadcast_indices((OneTo(3),OneTo(5)), zeros(3,1)) -check_broadcast_indices((OneTo(3),OneTo(5)), zeros(3)) -check_broadcast_indices((OneTo(3),OneTo(5)), zeros(3,5), zeros(3)) -check_broadcast_indices((OneTo(3),OneTo(5)), zeros(3,5), 1) -check_broadcast_indices((OneTo(3),OneTo(5)), 5, 2) -@test_throws DimensionMismatch check_broadcast_indices((OneTo(3),OneTo(5)), zeros(2,5)) -@test_throws DimensionMismatch check_broadcast_indices((OneTo(3),OneTo(5)), zeros(3,4)) -@test_throws DimensionMismatch check_broadcast_indices((OneTo(3),OneTo(5)), zeros(3,4,2)) -@test_throws DimensionMismatch check_broadcast_indices((OneTo(3),OneTo(5)), zeros(3,5), zeros(2)) -check_broadcast_indices((-1:1, 6:9), 1) - -check_broadcast_shape((-1:1, 6:9), (-1:1, 6:9)) -check_broadcast_shape((-1:1, 6:9), (-1:1, 1)) -check_broadcast_shape((-1:1, 6:9), (1, 6:9)) -@test_throws DimensionMismatch check_broadcast_shape((-1:1, 6:9), (-1, 6:9)) -@test_throws DimensionMismatch check_broadcast_shape((-1:1, 6:9), (-1:1, 6)) - -ci(x) = CartesianIndex(x) -@test @inferred(newindex(ci((2,2)), (true, true), (-1,-1))) == ci((2,2)) -@test @inferred(newindex(ci((2,2)), (true, false), (-1,-1))) == ci((2,-1)) -@test @inferred(newindex(ci((2,2)), (false, true), (-1,-1))) == ci((-1,2)) -@test @inferred(newindex(ci((2,2)), (false, false), (-1,-1))) == ci((-1,-1)) -@test @inferred(newindex(ci((2,2)), (true,), (-1,-1))) == ci((2,)) -@test @inferred(newindex(ci((2,2)), (true,), (-1,))) == ci((2,)) -@test @inferred(newindex(ci((2,2)), (false,), (-1,))) == ci((-1,)) -@test @inferred(newindex(ci((2,2)), (), ())) == ci(()) - -end - -function as_sub(x::AbstractVector) - y = similar(x, eltype(x), tuple(([size(x)...]*2)...)) - y = view(y, 2:2:length(y)) - y[:] = x[:] - y -end -function as_sub(x::AbstractMatrix) - y = similar(x, eltype(x), tuple(([size(x)...]*2)...)) - y = view(y, 2:2:size(y,1), 2:2:size(y,2)) - for j=1:size(x,2) - for i=1:size(x,1) - y[i,j] = x[i,j] - end - end - y -end -function as_sub{T}(x::AbstractArray{T,3}) - y = similar(x, eltype(x), tuple(([size(x)...]*2)...)) - y = view(y, 2:2:size(y,1), 2:2:size(y,2), 2:2:size(y,3)) - for k=1:size(x,3) - for j=1:size(x,2) - for i=1:size(x,1) - y[i,j,k] = x[i,j,k] - end - end - end - y -end - -bittest(f::Function, a...) = (@test f.(a...) == BitArray(broadcast(f, a...))) -n1 = 21 -n2 = 32 -n3 = 17 -rb = 1:5 - -for arr in (identity, as_sub) - @test broadcast(+, arr(eye(2)), arr([1, 4])) == [2 1; 4 5] - @test broadcast(+, arr(eye(2)), arr([1 4])) == [2 4; 1 5] - @test broadcast(+, arr([1 0]), arr([1, 4])) == [2 1; 5 4] - @test broadcast(+, arr([1, 0]), arr([1 4])) == [2 5; 1 4] - @test broadcast(+, arr([1, 0]), arr([1, 4])) == [2, 4] - @test broadcast(+, arr([1, 0]), 2) == [3, 2] - - @test @inferred(broadcast(+, arr(eye(2)), arr([1, 4]))) == arr([2 1; 4 5]) - @test arr(eye(2)) .+ arr([1 4]) == arr([2 4; 1 5]) - @test arr([1 0]) .+ arr([1, 4]) == arr([2 1; 5 4]) - @test arr([1, 0]) .+ arr([1 4]) == arr([2 5; 1 4]) - @test arr([1, 0]) .+ arr([1, 4]) == arr([2, 4]) - @test arr([1]) .+ arr([]) == arr([]) - - A = arr(eye(2)); @test broadcast!(+, A, A, arr([1, 4])) == arr([2 1; 4 5]) - A = arr(eye(2)); @test broadcast!(+, A, A, arr([1 4])) == arr([2 4; 1 5]) - A = arr([1 0]); @test_throws DimensionMismatch broadcast!(+, A, A, arr([1, 4])) - A = arr([1 0]); @test broadcast!(+, A, A, arr([1 4])) == arr([2 4]) - A = arr([1 0]); @test broadcast!(+, A, A, 2) == arr([3 2]) - - @test arr([ 1 2]) .* arr([3, 4]) == [ 3 6; 4 8] - @test arr([24.0 12.0]) ./ arr([2.0, 3.0]) == [12 6; 8 4] - @test arr([1 2]) ./ arr([3, 4]) == [1/3 2/3; 1/4 2/4] - @test arr([1 2]) .\ arr([3, 4]) == [3 1.5; 4 2] - @test arr([3 4]) .^ arr([1, 2]) == [3 4; 9 16] - @test arr(BitArray([true false])) .* arr(BitArray([true, true])) == [true false; true false] - @test arr(BitArray([true false])) .^ arr(BitArray([false, true])) == [true true; true false] - @test arr(BitArray([true false])) .^ arr([0, 3]) == [true true; true false] - - M = arr([11 12; 21 22]) - @test broadcast_getindex(M, eye(Int, 2).+1,arr([1, 2])) == [21 11; 12 22] - @test_throws BoundsError broadcast_getindex(M, eye(Int, 2).+1,arr([1, -1])) - @test_throws BoundsError broadcast_getindex(M, eye(Int, 2).+1,arr([1, 2]), [2]) - @test broadcast_getindex(M, eye(Int, 2).+1,arr([2, 1]), [1]) == [22 12; 11 21] - - A = arr(zeros(2,2)) - broadcast_setindex!(A, arr([21 11; 12 22]), eye(Int, 2).+1,arr([1, 2])) - @test A == M - broadcast_setindex!(A, 5, [1,2], [2 2]) - @test A == [11 5; 21 5] - broadcast_setindex!(A, 7, [1,2], [1 2]) - @test A == fill(7, 2, 2) - A = arr(zeros(3,3)) - broadcast_setindex!(A, 10:12, 1:3, 1:3) - @test A == diagm(10:12) - @test_throws BoundsError broadcast_setindex!(A, 7, [1,-1], [1 2]) - - for f in ((==), (<) , (!=), (<=)) - bittest(f, arr(eye(2)), arr([1, 4])) - bittest(f, arr(eye(2)), arr([1 4])) - bittest(f, arr([0, 1]), arr([1 4])) - bittest(f, arr([0 1]), arr([1, 4])) - bittest(f, arr([1, 0]), arr([1, 4])) - bittest(f, arr(rand(rb, n1, n2, n3)), arr(rand(rb, n1, n2, n3))) - bittest(f, arr(rand(rb, 1, n2, n3)), arr(rand(rb, n1, 1, n3))) - bittest(f, arr(rand(rb, 1, n2, 1)), arr(rand(rb, n1, 1, n3))) - bittest(f, arr(bitrand(n1, n2, n3)), arr(bitrand(n1, n2, n3))) - end -end - -r1 = 1:1 -r2 = 1:5 -ratio = [1,1/2,1/3,1/4,1/5] -@test r1.*r2 == [1:5;] -@test r1./r2 == ratio -m = [1:2;]' -@test m.*r2 == [1:5 2:2:10] -@test m./r2 ≈ [ratio 2ratio] -@test m./[r2;] ≈ [ratio 2ratio] - -@test @inferred(broadcast(+,[0,1.2],reshape([0,-2],1,1,2))) == reshape([0 -2; 1.2 -0.8],2,1,2) -rt = Base.return_types(broadcast, Tuple{typeof(+), Array{Float64, 3}, Array{Int, 1}}) -@test length(rt) == 1 && rt[1] == Array{Float64, 3} -rt = Base.return_types(broadcast!, Tuple{Function, Array{Float64, 3}, Array{Float64, 3}, Array{Int, 1}}) -@test length(rt) == 1 && rt[1] == Array{Float64, 3} - -# f.(args...) syntax (#15032) -let x = [1,3.2,4.7], y = [3.5, pi, 1e-4], α = 0.2342 - @test sin.(x) == broadcast(sin, x) - @test sin.(α) == broadcast(sin, α) - @test sin.(3.2) == broadcast(sin, 3.2) == sin(3.2) - @test factorial.(3) == broadcast(factorial, 3) - @test atan2.(x, y) == broadcast(atan2, x, y) - @test atan2.(x, y') == broadcast(atan2, x, y') - @test atan2.(x, α) == broadcast(atan2, x, α) - @test atan2.(α, y') == broadcast(atan2, α, y') -end - -# issue 14725 -let a = Number[2, 2.0, 4//2, 2+0im] / 2 - @test eltype(a) == Number -end -let a = Real[2, 2.0, 4//2] / 2 - @test eltype(a) == Real -end -let a = Real[2, 2.0, 4//2] / 2.0 - @test eltype(a) == Float64 -end - -# issue 16164 -let a = broadcast(Float32, [3, 4, 5]) - @test eltype(a) == Float32 -end - -# broadcasting scalars: -@test sin.(1) === broadcast(sin, 1) === sin(1) -@test (()->1234).() === broadcast(()->1234) === 1234 - -# issue #4883 -@test isa(broadcast(tuple, [1 2 3], ["a", "b", "c"]), Matrix{Tuple{Int,String}}) -@test isa(broadcast((x,y)->(x==1?1.0:x,y), [1 2 3], ["a", "b", "c"]), Matrix{Tuple{Real,String}}) -let a = length.(["foo", "bar"]) - @test isa(a, Vector{Int}) - @test a == [3, 3] -end -let a = sin.([1, 2]) - @test isa(a, Vector{Float64}) - @test a ≈ [0.8414709848078965, 0.9092974268256817] -end - -# PR #17300: loop fusion -@test (x->x+1).((x->x+2).((x->x+3).(1:10))) == collect(7:16) -let A = [sqrt(i)+j for i = 1:3, j=1:4] - @test atan2.(log.(A), sum(A,1)) == broadcast(atan2, broadcast(log, A), sum(A, 1)) -end -let x = sin.(1:10) - @test atan2.((x->x+1).(x), (x->x+2).(x)) == broadcast(atan2, x+1, x+2) == broadcast(atan2, x.+1, x.+2) - @test sin.(atan2.([x+1,x+2]...)) == sin.(atan2.(x+1,x+2)) == @. sin(atan2(x+1,x+2)) - @test sin.(atan2.(x, 3.7)) == broadcast(x -> sin(atan2(x,3.7)), x) - @test atan2.(x, 3.7) == broadcast(x -> atan2(x,3.7), x) == broadcast(atan2, x, 3.7) -end -# Use side effects to check for loop fusion. -let g = Int[] - f17300(x) = begin; push!(g, x); x+2; end - f17300.(f17300.(f17300.(1:3))) - @test g == [1,3,5, 2,4,6, 3,5,7] - empty!(g) - @. f17300(f17300(f17300(1:3))) - @test g == [1,3,5, 2,4,6, 3,5,7] -end -# fusion with splatted args: -let x = sin.(1:10), a = [x] - @test cos.(x) == cos.(a...) - @test atan2.(x,x) == atan2.(a..., a...) == atan2.([x, x]...) - @test atan2.(x, cos.(x)) == atan2.(a..., cos.(x)) == broadcast(atan2, x, cos.(a...)) == broadcast(atan2, a..., cos.(a...)) - @test ((args...)->cos(args[1])).(x) == cos.(x) == ((y,args...)->cos(y)).(x) -end -@test atan2.(3,4) == atan2(3,4) == (() -> atan2(3,4)).() -# fusion with keyword args: -let x = [1:4;] - f17300kw(x; y=0) = x + y - @test f17300kw.(x) == x - @test f17300kw.(x, y=1) == f17300kw.(x; y=1) == f17300kw.(x; [(:y,1)]...) == x .+ 1 - @test f17300kw.(sin.(x), y=1) == f17300kw.(sin.(x); y=1) == sin.(x) .+ 1 - @test sin.(f17300kw.(x, y=1)) == sin.(f17300kw.(x; y=1)) == sin.(x .+ 1) -end - -# issue #23236 -let X = [[true,false],[false,true]] - @test [.!x for x in X] == [[false,true],[true,false]] -end - -# splice escaping of @. -let x = [4, -9, 1, -16] - @test [2, 3, 4, 5] == @.(1 + sqrt($sort(abs(x)))) -end - -# interaction of @. with let -@test [1,4,9] == @. let x = [1,2,3]; x^2; end - -# interaction of @. with for loops -let x = [1,2,3], y = x - @. for i = 1:3 - y = y^2 # should convert to y .= y.^2 - end - @test x == [1,256,6561] -end - -# interaction of @. with function definitions -let x = [1,2,3] - @. f(x) = x^2 - @test f(x) == [1,4,9] -end - -# PR #17510: Fused in-place assignment -let x = [1:4;], y = x - y .= 2:5 - @test y === x == [2:5;] - y .= factorial.(x) - @test y === x == [2,6,24,120] - y .= 7 - @test y === x == [7,7,7,7] - y .= factorial.(3) - @test y === x == [6,6,6,6] - f17510() = 9 - y .= f17510.() - @test y === x == [9,9,9,9] - y .-= 1 - @test y === x == [8,8,8,8] - @. y -= 1:4 # @. should convert to .-= - @test y === x == [7,6,5,4] - x[1:2] .= 1 - @test y === x == [1,1,5,4] - @. x[1:2] .+= [2,3] # use .+= to make sure @. works with dotted assignment - @test y === x == [3,4,5,4] - @. x[:] .= 0 # use .= to make sure @. works with dotted assignment - @test y === x == [0,0,0,0] - @. x[2:end] = 1:3 # @. should convert to .= - @test y === x == [0,1,2,3] -end -let a = [[4, 5], [6, 7]] - a[1] .= 3 - @test a == [[3, 3], [6, 7]] -end -let d = Dict(:foo => [1,3,7], (3,4) => [5,9]) - d[:foo] .+= 2 - @test d[:foo] == [3,5,9] - d[3,4] .-= 1 - @test d[3,4] == [4,8] -end -let identity = error, x = [1,2,3] - x .= 1 # make sure it goes to broadcast!(Base.identity, ...), not identity - @test x == [1,1,1] -end - -# make sure scalars are inlined, which causes f.(x,scalar) to lower to a "thunk" -import Base.Meta: isexpr -@test isexpr(expand(:(f.(x,y))), :call) -@test isexpr(expand(:(f.(x,1))), :thunk) -@test isexpr(expand(:(f.(x,1.0))), :thunk) -@test isexpr(expand(:(f.(x,$π))), :thunk) -@test isexpr(expand(:(f.(x,"hello"))), :thunk) -@test isexpr(expand(:(f.(x,$("hello")))), :thunk) - -# PR #17623: Fused binary operators -@test [true] .* [true] == [true] -@test [1,2,3] .|> (x->x+1) == [2,3,4] -let g = Int[], ⊕ = (a,b) -> let c=a+2b; push!(g, c); c; end - @test [1,2,3] .⊕ [10,11,12] .⊕ [100,200,300] == [221,424,627] - @test g == [21,221,24,424,27,627] # test for loop fusion -end - -# Fused unary operators -@test .√[3,4,5] == sqrt.([3,4,5]) -@test .![true, true, false] == [false, false, true] -@test .-[1,2,3] == -[1,2,3] == .+[-1,-2,-3] == [-1,-2,-3] - -# PR 16988 -@test Base.promote_op(+, Bool) === Int -@test isa(broadcast(+, [true]), Array{Int,1}) - -# issue #17304 -let foo = [[1,2,3],[4,5,6],[7,8,9]] - @test max.(foo...) == broadcast(max, foo...) == [7,8,9] -end - -# Issue 17314 -@test broadcast(x->log(log(log(x))), [1000]) == [log(log(log(1000)))] -let f17314 = x -> x < 0 ? false : x - @test eltype(broadcast(f17314, 1:3)) === Int - @test eltype(broadcast(f17314, -1:1)) === Integer - @test eltype(broadcast(f17314, Int[])) === Union{Bool,Int} -end -let io = IOBuffer() - broadcast(x->print(io,x), 1:5) # broadcast with side effects - @test take!(io) == [0x31,0x32,0x33,0x34,0x35] -end - -# Issue 18176 -let f18176(a, b, c) = a + b + c - @test f18176.(1.0:2, 3, 4) == f18176.(3.0, 1.0:2, 4.0) == broadcast(f18176, 3, 4, 1.0:2) -end - -# Issue #17984 -let A17984 = [] - @test isa(abs.(A17984), Array{Any,1}) -end - -# Issue #16966 -@test parse.(Int, "1") == 1 -@test parse.(Int, ["1", "2"]) == [1, 2] -@test trunc.((Int,), [1.2, 3.4]) == [1, 3] -@test abs.((1, -2)) == (1, 2) -@test broadcast(+, 1.0, (0, -2.0)) == (1.0,-1.0) -@test broadcast(+, 1.0, (0, -2.0), [1]) == [2.0, 0.0] -@test broadcast(*, ["Hello"], ", ", ["World"], "!") == ["Hello, World!"] -let s = "foo" - @test s .* ["bar", "baz"] == ["foobar", "foobaz"] == "foo" .* ["bar", "baz"] -end - -# Ensure that even strange constructors that break `T(x)::T` work with broadcast -struct StrangeType18623 end -StrangeType18623(x) = x -StrangeType18623(x,y) = (x,y) -@test @inferred(broadcast(StrangeType18623, 1:3)) == [1,2,3] -@test @inferred(broadcast(StrangeType18623, 1:3, 4:6)) == [(1,4),(2,5),(3,6)] - -@test typeof(Int.(Number[1, 2, 3])) === typeof((x->Int(x)).(Number[1, 2, 3])) - -@test @inferred(broadcast(CartesianIndex, 1:2)) == [CartesianIndex(1), CartesianIndex(2)] -@test @inferred(broadcast(CartesianIndex, 1:2, 3:4)) == [CartesianIndex(1,3), CartesianIndex(2,4)] - -# Issue 18622 -@test @inferred(broadcast(muladd, [1.0], [2.0], [3.0])) == [5.0] -@test @inferred(broadcast(tuple, 1:3, 4:6, 7:9)) == [(1,4,7), (2,5,8), (3,6,9)] - -# 19419 -@test @inferred(broadcast(round, Int, [1])) == [1] - -# https://discourse.julialang.org/t/towards-broadcast-over-combinations-of-sparse-matrices-and-scalars/910 -let - f(A, n) = broadcast(x -> +(x, n), A) - @test @inferred(f([1.0], 1)) == [2.0] - g() = (a = 1; Base.Broadcast._broadcast_eltype(x -> x + a, 1.0)) - @test @inferred(g()) === Float64 -end - -# Ref as 0-dimensional array for broadcast -@test (-).(C_NULL, C_NULL)::UInt == 0 -@test (+).(1, Ref(2)) == fill(3) -@test (+).(Ref(1), Ref(2)) == fill(3) -@test (+).([[0,2], [1,3]], [1,-1]) == [[1,3], [0,2]] -@test (+).([[0,2], [1,3]], Ref{Vector{Int}}([1,-1])) == [[1,1], [2,2]] - -# Check that broadcast!(f, A) populates A via independent calls to f (#12277, #19722), -# and similarly for broadcast!(f, A, numbers...) (#19799). -@test let z = 1; A = broadcast!(() -> z += 1, zeros(2)); A[1] != A[2]; end -@test let z = 1; A = broadcast!(x -> z += x, zeros(2), 1); A[1] != A[2]; end - -# broadcasting for custom AbstractArray -struct Array19745{T,N} <: AbstractArray{T,N} - data::Array{T,N} -end -Base.getindex(A::Array19745, i::Integer...) = A.data[i...] -Base.size(A::Array19745) = size(A.data) - -Base.Broadcast._containertype{T<:Array19745}(::Type{T}) = Array19745 - -Base.Broadcast.promote_containertype(::Type{Array19745}, ::Type{Array19745}) = Array19745 -Base.Broadcast.promote_containertype(::Type{Array19745}, ::Type{Array}) = Array19745 -Base.Broadcast.promote_containertype(::Type{Array19745}, ct) = Array19745 -Base.Broadcast.promote_containertype(::Type{Array}, ::Type{Array19745}) = Array19745 -Base.Broadcast.promote_containertype(ct, ::Type{Array19745}) = Array19745 - -Base.Broadcast.broadcast_indices(::Type{Array19745}, A) = indices(A) -Base.Broadcast.broadcast_indices(::Type{Array19745}, A::Ref) = () - -getfield19745(x::Array19745) = x.data -getfield19745(x) = x - -Base.Broadcast.broadcast_c(f, ::Type{Array19745}, A, Bs...) = - Array19745(Base.Broadcast.broadcast_c(f, Array, getfield19745(A), map(getfield19745, Bs)...)) - -@testset "broadcasting for custom AbstractArray" begin - a = randn(10) - aa = Array19745(a) - @test a .+ 1 == @inferred(aa .+ 1) - @test a .* a' == @inferred(aa .* aa') - @test isa(aa .+ 1, Array19745) - @test isa(aa .* aa', Array19745) -end - -# broadcast with a custom type that looses to tuple -struct DataValue{T} - value::T -end - -Base.Broadcast._containertype(::Type{<:DataValue}) = DataValue -Base.Broadcast.promote_containertype(::Type{Tuple}, ::Type{DataValue}) = Tuple -Base.Broadcast.promote_containertype(::Type{DataValue}, ::Type{Tuple}) = Tuple -Base.Broadcast._broadcast_getindex(::Type{DataValue}, A, I) = A.value - -@testset "Broadcast with tuple and a custom type" begin - @test DataValue(1) .+ (1, 2) == (2, 3) -end - -# broadcast should only "peel off" one container layer -@test get.([Nullable(1), Nullable(2)]) == [1, 2] -let io = IOBuffer() - broadcast(x -> print(io, x), [Nullable(1.0)]) - @test String(take!(io)) == "Nullable{Float64}(1.0)" -end - -# Test that broadcast's promotion mechanism handles closures accepting more than one argument. -# (See issue #19641 and referenced issues and pull requests.) -let f() = (a = 1; Base.Broadcast._broadcast_eltype((x, y) -> x + y + a, 1.0, 1.0)) - @test @inferred(f()) == Float64 -end - -@testset "broadcast resulting in BitArray" begin - let f(x) = x ? true : "false" - ba = f.([true]) - @test ba isa BitArray - @test ba == [true] - a = f.([false]) - @test a isa Array{String} - @test a == ["false"] - @test f.([true, false]) == [true, "false"] - end -end - -# Test that broadcast treats type arguments as scalars, i.e. containertype yields Any, -# even for subtypes of abstract array. (https://github.com/JuliaStats/DataArrays.jl/issues/229) -@testset "treat type arguments as scalars, DataArrays issue 229" begin - @test Base.Broadcast.containertype(AbstractArray) == Any - @test broadcast(==, [1], AbstractArray) == BitArray([false]) - @test broadcast(==, 1, AbstractArray) == false -end - -# Test that broadcasting identity where the input and output Array shapes do not match -# yields the correct result, not merely a partial copy. See pull request #19895 for discussion. -let N = 5 - @test iszero(ones(N, N) .= zeros(N, N)) - @test iszero(ones(N, N) .= zeros(N, 1)) - @test iszero(ones(N, N) .= zeros(1, N)) - @test iszero(ones(N, N) .= zeros(1, 1)) -end - -@testset "test broadcast for matrix of matrices" begin - A = fill(zeros(2,2), 4, 4) - A[1:3,1:3] .= [ones(2,2)] - @test all(A[1:3,1:3] .== [ones(2,2)]) -end - -# Test that broadcast does not confuse eltypes. See also -# https://github.com/JuliaLang/julia/issues/21325 -@testset "eltype confusion (#21325)" begin - foo(x::Char, y::Int) = 0 - foo(x::String, y::Int) = "hello" - @test broadcast(foo, "x", [1, 2, 3]) == ["hello", "hello", "hello"] - - @test isequal( - [Set([1]), Set([2])] .∪ Set([3]), - [Set([1, 3]), Set([2, 3])]) - - @test isequal(@inferred(broadcast(foo, "world", Nullable(1))), - Nullable("hello")) -end - -@testset "broadcast resulting in tuples" begin - # Issue #21291 - let t = (0, 1, 2) - o = 1 - @test @inferred(broadcast(+, t, o)) == (1, 2, 3) - end - - # Issue #23647 - @test (1, 2, 3) .+ (1,) == (1,) .+ (1, 2, 3) == (2, 3, 4) - @test (1,) .+ () == () .+ (1,) == () .+ () == () - @test (1, 2) .+ (1, 2) == (2, 4) - @test_throws DimensionMismatch (1, 2) .+ (1, 2, 3) -end diff --git a/julia-0.6.3/share/julia/test/cartesian.jl b/julia-0.6.3/share/julia/test/cartesian.jl deleted file mode 100644 index be2605d..0000000 --- a/julia-0.6.3/share/julia/test/cartesian.jl +++ /dev/null @@ -1,5 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -@test Base.Cartesian.exprresolve(:(1 + 3)) == 4 -ex = Base.Cartesian.exprresolve(:(if 5 > 4; :x; else :y; end)) -@test ex.args[2] == QuoteNode(:x) diff --git a/julia-0.6.3/share/julia/test/ccall.jl b/julia-0.6.3/share/julia/test/ccall.jl deleted file mode 100644 index 204a40c..0000000 --- a/julia-0.6.3/share/julia/test/ccall.jl +++ /dev/null @@ -1,1279 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -import Base.copy, Base.== - -const libccalltest = "libccalltest" - -const verbose = false -ccall((:set_verbose, libccalltest), Void, (Int32,), verbose) - - -# Test for proper argument register truncation -ccall_test_func(x) = ccall((:testUcharX, libccalltest), Int32, (UInt8,), x % UInt8) -@test ccall_test_func(3) == 1 -@test ccall_test_func(259) == 1 - - -# Test for proper round-trip of Ref{T} type -function gen_ccall_echo(x, T, U, ret=nothing) - # Construct a noninline function to do all the work, this is necessary - # to make sure object x is still valid (rooted as argument) - # when loading the pointer. - # This works as long as we still keep the argument - # rooted but might fail if we are smarter about eliminating dead root. - - # `eval` in global scope to make sure the function is not a closure - func_ex = :(ccall((:test_echo_p, libccalltest), $T, ($U,), x)) - # It is not allowed to allocate after the ccall returns - # and before calling `ret`. - if ret !== nothing - func_ex = :($ret($func_ex)) - end - @gensym func_name - @eval @noinline $func_name(x) = $func_ex - :($func_name($(esc(x)))) -end - -macro ccall_echo_func(x, T, U) - gen_ccall_echo(x, T, U) -end -macro ccall_echo_load(x, T, U) - gen_ccall_echo(x, T, U, :unsafe_load) -end -macro ccall_echo_objref(x, T, U) - gen_ccall_echo(x, :(Ptr{$T}), U, :unsafe_pointer_to_objref) -end - -mutable struct IntLike - x::Int -end -@test @ccall_echo_load(132, Ptr{Int}, Ref{Int}) === 132 -@test @ccall_echo_load(Ref(921), Ptr{Int}, Ref{Int}) === 921 -@test @ccall_echo_load(IntLike(993), Ptr{Int}, Ref{IntLike}) === 993 -@test @ccall_echo_load(IntLike(881), Ptr{IntLike}, Ref{IntLike}).x === 881 -@test @ccall_echo_func(532, Int, Int) === 532 -if Sys.WORD_SIZE == 64 - # this test is valid only for x86_64 and win64 - @test @ccall_echo_func(164, IntLike, Int).x === 164 -end -@test @ccall_echo_func(IntLike(828), Int, IntLike) === 828 -@test @ccall_echo_func(913, Any, Any) === 913 -@test @ccall_echo_objref(553, Ptr{Any}, Any) === 553 -@test @ccall_echo_func(124, Ref{Int}, Any) === 124 -@test @ccall_echo_load(422, Ptr{Any}, Ref{Any}) === 422 -@test @ccall_echo_load([383], Ptr{Int}, Ref{Int}) === 383 -@test @ccall_echo_load(Ref([144,172],2), Ptr{Int}, Ref{Int}) === 172 -# @test @ccall_echo_load(Ref([8],1,1), Ptr{Int}, Ref{Int}) === 8 - - -## Tests for passing and returning structs - -let a, ci_ary, x - a = 20 + 51im - - x = ccall((:ctest, libccalltest), Complex{Int}, (Complex{Int},), a) - - @test x == a + 1 - 2im - - ci_ary = [a] # Make sure the array is alive during unsafe_load - x = unsafe_load(ccall((:cptest, libccalltest), Ptr{Complex{Int}}, - (Ptr{Complex{Int}},), ci_ary)) - - @test x == a + 1 - 2im - @test a == 20 + 51im - - x = ccall((:cptest_static, libccalltest), Ptr{Complex{Int}}, (Ptr{Complex{Int}},), &a) - @test unsafe_load(x) == a - Libc.free(convert(Ptr{Void}, x)) -end - -let a, b, x - a = 2.84 + 5.2im - - x = ccall((:cgtest, libccalltest), Complex128, (Complex128,), a) - - @test x == a + 1 - 2im - - b = [a] # Make sure the array is alive during unsafe_load - x = unsafe_load(ccall((:cgptest, libccalltest), Ptr{Complex128}, (Ptr{Complex128},), b)) - - @test x == a + 1 - 2im - @test a == 2.84 + 5.2im -end - -let a, b, x - a = 3.34f0 + 53.2f0im - - x = ccall((:cftest, libccalltest), Complex64, (Complex64,), a) - - @test x == a + 1 - 2im - - b = [a] # Make sure the array is alive during unsafe_load - x = unsafe_load(ccall((:cfptest, libccalltest), Ptr{Complex64}, (Ptr{Complex64},), b)) - - @test x == a + 1 - 2im - @test a == 3.34f0 + 53.2f0im -end - - -## Tests for native Julia data types - -let a - a = 2.84 + 5.2im - - @test_throws MethodError ccall((:cptest, libccalltest), Ptr{Complex{Int}}, (Ptr{Complex{Int}},), a) - @test_throws MethodError ccall((:cptest, libccalltest), Ptr{Complex{Int}}, (Complex{Int},), &a) -end - - -## Tests for various sized data types (ByVal) - -mutable struct Struct1 - x::Float32 - y::Float64 -end -struct Struct1I - x::Float32 - y::Float64 -end -copy(a::Struct1) = Struct1(a.x, a.y) -copy(a::Struct1I) = a - -function test_struct1{Struct}(::Type{Struct}) - a = Struct(352.39422f23, 19.287577) - b = Float32(123.456) - - a2 = copy(a) - if Struct === Struct1 - x = ccall((:test_1, libccalltest), Struct1, (Struct1, Float32), a2, b) - else - x = ccall((:test_1, libccalltest), Struct1I, (Struct1I, Float32), a2, b) - end - - @test a2.x == a.x && a2.y == a.y - @test !(a2 === x) - - @test x.x ≈ a.x + 1*b - @test x.y ≈ a.y - 2*b -end -test_struct1(Struct1) -test_struct1(Struct1I) - -let a, b, x - a = Struct1(352.39422f23, 19.287577) - b = Float32(123.456) - a2 = copy(a) - - x = ccall((:test_1long_a, libccalltest), Struct1, (Int, Int, Int, Struct1, Float32), 2, 3, 4, a2, b) - @test a2.x == a.x && a2.y == a.y - @test !(a2 === x) - @test x.x ≈ a.x + b + 9 - @test x.y ≈ a.y - 2*b - - x = ccall((:test_1long_b, libccalltest), Struct1, (Int, Float64, Int, Struct1, Float32), 2, 3, 4, a2, b) - @test a2.x == a.x && a2.y == a.y - @test !(a2 === x) - @test x.x ≈ a.x + b + 9 - @test x.y ≈ a.y - 2*b - - x = ccall((:test_1long_c, libccalltest), Struct1, (Int, Float64, Int, Int, Struct1, Float32), 2, 3, 4, 5, a2, b) - @test a2.x == a.x && a2.y == a.y - @test !(a2 === x) - @test x.x ≈ a.x + b + 14 - @test x.y ≈ a.y - 2*b -end - -let a, b, x, y - a = Complex{Int32}(Int32(10),Int32(31)) - b = Int32(42) - - x = ccall((:test_2a, libccalltest), Complex{Int32}, (Complex{Int32}, Int32), a, b) - y = ccall((:test_2b, libccalltest), Complex{Int32}, (Complex{Int32},Int32), a, b) - - @test a == Complex{Int32}(Int32(10),Int32(31)) - - @test x == y - @test x == a + b*1 - b*2im -end - -let a, b, x, y, z - a = Complex{Int64}(Int64(20),Int64(51)) - b = Int64(42) - - x = ccall((:test_3a, libccalltest), Complex{Int64}, (Complex{Int64}, Int64), a, b) - y = ccall((:test_3b, libccalltest), Complex{Int64}, (Complex{Int64}, Int64), a, b) - z = ccall((:test_128, libccalltest), Complex{Int64}, (Complex{Int64}, Int64), a, b) - - @test a == Complex{Int64}(Int64(20),Int64(51)) - - @test x == y - @test x == a + b*1 - b*2im - - @test z == a + 1*b -end - -mutable struct Struct4 - x::Int32 - y::Int32 - z::Int32 -end -struct Struct4I - x::Int32 - y::Int32 - z::Int32 -end - -function test_struct4{Struct}(::Type{Struct}) - a = Struct(-512275808,882558299,-2133022131) - b = Int32(42) - - if Struct === Struct4 - x = ccall((:test_4, libccalltest), Struct4, (Struct4, Int32), a, b) - else - x = ccall((:test_4, libccalltest), Struct4I, (Struct4I, Int32), a, b) - end - - @test x.x == a.x+b*1 - @test x.y == a.y-b*2 - @test x.z == a.z+b*3 -end -test_struct4(Struct4) -test_struct4(Struct4I) - -mutable struct Struct5 - x::Int32 - y::Int32 - z::Int32 - a::Int32 -end -struct Struct5I - x::Int32 - y::Int32 - z::Int32 - a::Int32 -end - -function test_struct5{Struct}(::Type{Struct}) - a = Struct(1771319039, 406394736, -1269509787, -745020976) - b = Int32(42) - - if Struct === Struct5 - x = ccall((:test_5, libccalltest), Struct5, (Struct5, Int32), a, b) - else - x = ccall((:test_5, libccalltest), Struct5I, (Struct5I, Int32), a, b) - end - - @test x.x == a.x+b*1 - @test x.y == a.y-b*2 - @test x.z == a.z+b*3 - @test x.a == a.a-b*4 -end -test_struct5(Struct5) -test_struct5(Struct5I) - -mutable struct Struct6 - x::Int64 - y::Int64 - z::Int64 -end -struct Struct6I - x::Int64 - y::Int64 - z::Int64 -end - -function test_struct6{Struct}(::Type{Struct}) - a = Struct(-654017936452753226, -5573248801240918230, -983717165097205098) - b = Int64(42) - - if Struct === Struct6 - x = ccall((:test_6, libccalltest), Struct6, (Struct6, Int64), a, b) - else - x = ccall((:test_6, libccalltest), Struct6I, (Struct6I, Int64), a, b) - end - - @test x.x == a.x+b*1 - @test x.y == a.y-b*2 - @test x.z == a.z+b*3 -end -test_struct6(Struct6) -test_struct6(Struct6I) - -mutable struct Struct7 - x::Int64 - y::Cchar -end -struct Struct7I - x::Int64 - y::Cchar -end - -function test_struct7{Struct}(::Type{Struct}) - a = Struct(-384082741977533896, 'h') - b = Int8(42) - - if Struct === Struct7 - x = ccall((:test_7, libccalltest), Struct7, (Struct7, Int8), a, b) - else - x = ccall((:test_7, libccalltest), Struct7I, (Struct7I, Int8), a, b) - end - - @test x.x == a.x+Int(b)*1 - @test x.y == a.y-Int(b)*2 -end -test_struct7(Struct7) -test_struct7(Struct7I) - -mutable struct Struct8 - x::Int32 - y::Cchar -end -struct Struct8I - x::Int32 - y::Cchar -end - -function test_struct8{Struct}(::Type{Struct}) - a = Struct(-384082896, 'h') - b = Int8(42) - - if Struct === Struct8 - r8 = ccall((:test_8, libccalltest), Struct8, (Struct8, Int8), a, b) - else - r8 = ccall((:test_8, libccalltest), Struct8I, (Struct8I, Int8), a, b) - end - - @test r8.x == a.x+b*1 - @test r8.y == a.y-b*2 -end -test_struct8(Struct8) -test_struct8(Struct8I) - -mutable struct Struct9 - x::Int32 - y::Int16 -end -struct Struct9I - x::Int32 - y::Int16 -end - -function test_struct9{Struct}(::Type{Struct}) - a = Struct(-394092996, -3840) - b = Int16(42) - - if Struct === Struct9 - x = ccall((:test_9, libccalltest), Struct9, (Struct9, Int16), a, b) - else - x = ccall((:test_9, libccalltest), Struct9I, (Struct9I, Int16), a, b) - end - - @test x.x == a.x+b*1 - @test x.y == a.y-b*2 -end -test_struct9(Struct9) -test_struct9(Struct9I) - -mutable struct Struct10 - x::Cchar - y::Cchar - z::Cchar - a::Cchar -end -struct Struct10I - x::Cchar - y::Cchar - z::Cchar - a::Cchar -end - -function test_struct10{Struct}(::Type{Struct}) - a = Struct('0', '1', '2', '3') - b = Int8(2) - - if Struct === Struct10 - x = ccall((:test_10, libccalltest), Struct10, (Struct10, Int8), a, b) - else - x = ccall((:test_10, libccalltest), Struct10I, (Struct10I, Int8), a, b) - end - - @test x.x == a.x+b*1 - @test x.y == a.y-b*2 - @test x.z == a.z+b*3 - @test x.a == a.a-b*4 -end -test_struct10(Struct10) -test_struct10(Struct10I) - -mutable struct Struct11 - x::Complex64 -end -struct Struct11I - x::Complex64 -end - -function test_struct11{Struct}(::Type{Struct}) - a = Struct(0.8877077f0 + 0.4591081f0im) - b = Float32(42) - - if Struct === Struct11 - x = ccall((:test_11, libccalltest), Struct11, (Struct11, Float32), a, b) - else - x = ccall((:test_11, libccalltest), Struct11I, (Struct11I, Float32), a, b) - end - - @test x.x ≈ a.x + b*1 - b*2im -end -test_struct11(Struct11) -test_struct11(Struct11I) - -mutable struct Struct12 - x::Complex64 - y::Complex64 -end -struct Struct12I - x::Complex64 - y::Complex64 -end - -function test_struct12{Struct}(::Type{Struct}) - a = Struct(0.8877077f5 + 0.4591081f2im, 0.0004842868f0 - 6982.3265f3im) - b = Float32(42) - - if Struct === Struct12 - x = ccall((:test_12, libccalltest), Struct12, (Struct12, Float32), a, b) - else - x = ccall((:test_12, libccalltest), Struct12I, (Struct12I, Float32), a, b) - end - - @test x.x ≈ a.x + b*1 - b*2im - @test x.y ≈ a.y + b*3 - b*4im -end -test_struct12(Struct12) -test_struct12(Struct12I) - -mutable struct Struct13 - x::Complex128 -end -struct Struct13I - x::Complex128 -end - -function test_struct13{Struct}(::Type{Struct}) - a = Struct(42968.97560380495 - 803.0576845153616im) - b = Float64(42) - - if Struct === Struct13 - x = ccall((:test_13, libccalltest), Struct13, (Struct13, Float64), a, b) - else - x = ccall((:test_13, libccalltest), Struct13I, (Struct13I, Float64), a, b) - end - - @test x.x ≈ a.x + b*1 - b*2im -end -test_struct13(Struct13) -test_struct13(Struct13I) - -mutable struct Struct14 - x::Float32 - y::Float32 -end -struct Struct14I - x::Float32 - y::Float32 -end - -function test_struct14{Struct}(::Type{Struct}) - a = Struct(0.024138331f0, 0.89759064f32) - b = Float32(42) - - if Struct === Struct14 - x = ccall((:test_14, libccalltest), Struct14, (Struct14, Float32), a, b) - else - x = ccall((:test_14, libccalltest), Struct14I, (Struct14I, Float32), a, b) - end - - @test x.x ≈ a.x + b*1 - @test x.y ≈ a.y - b*2 -end -test_struct14(Struct14) -test_struct14(Struct14I) - -mutable struct Struct15 - x::Float64 - y::Float64 -end -struct Struct15I - x::Float64 - y::Float64 -end - -function test_struct15{Struct}(::Type{Struct}) - a = Struct(4.180997967273657, -0.404218594294923) - b = Float64(42) - - if Struct === Struct15 - x = ccall((:test_15, libccalltest), Struct15, (Struct15, Float64), a, b) - else - x = ccall((:test_15, libccalltest), Struct15I, (Struct15I, Float64), a, b) - end - - @test x.x ≈ a.x + b*1 - @test x.y ≈ a.y - b*2 -end -test_struct15(Struct15) -test_struct15(Struct15I) - -mutable struct Struct16 - x::Float32 - y::Float32 - z::Float32 - a::Float64 - b::Float64 - c::Float64 -end -struct Struct16I - x::Float32 - y::Float32 - z::Float32 - a::Float64 - b::Float64 - c::Float64 -end - -function test_struct16{Struct}(::Type{Struct}) - a = Struct(0.1604656f0, 0.6297606f0, 0.83588994f0, - 0.6460273620993535, 0.9472692581106656, 0.47328535437352093) - b = Float32(42) - - if Struct === Struct16 - x = ccall((:test_16, libccalltest), Struct16, (Struct16, Float32), a, b) - else - x = ccall((:test_16, libccalltest), Struct16I, (Struct16I, Float32), a, b) - end - - @test x.x ≈ a.x + b*1 - @test x.y ≈ a.y - b*2 - @test x.z ≈ a.z + b*3 - @test x.a ≈ a.a - b*4 - @test x.b ≈ a.b + b*5 - @test x.c ≈ a.c - b*6 -end -test_struct16(Struct16) -test_struct16(Struct16I) - -mutable struct Struct17 - a::Int8 - b::Int16 -end -struct Struct17I - a::Int8 - b::Int16 -end - -function test_struct17{Struct}(::Type{Struct}) - a = Struct(2, 10) - b = Int8(2) - - if Struct === Struct17 - x = ccall((:test_17, libccalltest), Struct17, (Struct17, Int8), a, b) - else - x = ccall((:test_17, libccalltest), Struct17I, (Struct17I, Int8), a, b) - end - - @test x.a == a.a + b * 1 - @test x.b == a.b - b * 2 -end -test_struct17(Struct17) -test_struct17(Struct17I) - -mutable struct Struct18 - a::Int8 - b::Int8 - c::Int8 -end -struct Struct18I - a::Int8 - b::Int8 - c::Int8 -end - -function test_struct18{Struct}(::Type{Struct}) - a = Struct(2, 10, -3) - b = Int8(2) - - if Struct === Struct18 - x = ccall((:test_18, libccalltest), Struct18, (Struct18, Int8), a, b) - else - x = ccall((:test_18, libccalltest), Struct18I, (Struct18I, Int8), a, b) - end - - @test x.a == a.a + b * 1 - @test x.b == a.b - b * 2 - @test x.c == a.c + b * 3 -end -test_struct18(Struct18) -test_struct18(Struct18I) - -let a, b, x - a = Int128(0x7f00123456789abc)<<64 + typemax(UInt64) - b = Int64(1) - - x = ccall((:test_128, libccalltest), Int128, (Int128, Int64), a, b) - - @test x == a + b*1 - @test a == Int128(0x7f00123456789abc)<<64 + typemax(UInt64) -end - -mutable struct Struct_Big - x::Int - y::Int - z::Int8 -end -struct Struct_BigI - x::Int - y::Int - z::Int8 -end -copy(a::Struct_Big) = Struct_Big(a.x, a.y, a.z) -copy(a::Struct_BigI) = a - -function test_struct_big{Struct}(::Type{Struct}) - a = Struct(424,-5,Int8('Z')) - a2 = copy(a) - - if Struct == Struct_Big - x = ccall((:test_big, libccalltest), Struct_Big, (Struct_Big,), a2) - else - x = ccall((:test_big, libccalltest), Struct_BigI, (Struct_BigI,), a2) - end - - @test a2.x == a.x && a2.y == a.y && a2.z == a.z - @test x.x == a.x + 1 - @test x.y == a.y - 2 - @test x.z == a.z - Int('A') -end -test_struct_big(Struct_Big) -test_struct_big(Struct_BigI) - -let a, a2, x - a = Struct_Big(424,-5,Int8('Z')) - a2 = copy(a) - x = ccall((:test_big_long, libccalltest), Struct_Big, (Int, Int, Int, Struct_Big,), 2, 3, 4, a2) - @test a2.x == a.x && a2.y == a.y && a2.z == a.z - @test x.x == a.x + 10 - @test x.y == a.y - 2 - @test x.z == a.z - Int('A') -end - -const Struct_huge1a = NTuple{8, Int64} -const Struct_huge1b = NTuple{9, Int64} -const Struct_huge2a = NTuple{8, Cdouble} -const Struct_huge2b = NTuple{9, Cdouble} -mutable struct Struct_huge3a - cf::NTuple{3, Complex{Cfloat}} - f7::Cfloat - f8::Cfloat -end -mutable struct Struct_huge3b - cf::NTuple{7, Complex{Cfloat}} - r8a::Cfloat - r8b::Cfloat -end -mutable struct Struct_huge3c - cf::NTuple{7, Complex{Cfloat}} - r8a::Cfloat - r8b::Cfloat - r9::Cfloat -end -mutable struct Struct_huge4a - r12::Complex{Cdouble} - r34::Complex{Cdouble} - r5::Complex{Cfloat} - r67::Complex{Cdouble} - r8::Cdouble -end -mutable struct Struct_huge4b - r12::Complex{Cdouble} - r34::Complex{Cdouble} - r5::Complex{Cfloat} - r67::Complex{Cdouble} - r89::Complex{Cdouble} -end -const Struct_huge5a = NTuple{8, Complex{Cint}} -const Struct_huge5b = NTuple{9, Complex{Cint}} - -function verify_huge(init, a, b) - @test typeof(init) === typeof(a) === typeof(b) - verbose && @show (a, b) - # make sure a was unmodified - for i = 1:nfields(a) - @test getfield(init, i) === getfield(a, i) - end - # make sure b was modifed as expected - a1, b1 = getfield(a, 1), getfield(b, 1) - while isa(a1, Tuple) - @test a1[2:end] === b1[2:end] - a1 = a1[1] - b1 = b1[1] - end - if isa(a1, VecElement) - a1 = a1.value - b1 = b1.value - end - @test oftype(a1, a1 * 39) === b1 - for i = 2:nfields(a) - @test getfield(a, i) === getfield(b, i) - end -end -macro test_huge(i, b, init) - f = QuoteNode(Symbol("test_huge", i, b)) - ty = Symbol("Struct_huge", i, b) - return quote - let a = $ty($(esc(init))...), f - f(b) = ccall(($f, libccalltest), $ty, (Cchar, $ty, Cchar), '0' + $i, a, $b[1]) - #code_llvm(f, typeof((a,))) - verify_huge($ty($(esc(init))...), a, f(a)) - end - end -end -@test_huge 1 'a' ((1, 2, 3, 4, 5, 6, 7, 8),) -@test_huge 1 'b' ((1, 2, 3, 4, 5, 6, 7, 8, 9),) -@test_huge 2 'a' ((1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0),) -@test_huge 2 'b' ((1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0),) -@test_huge 3 'a' ((1.0 + 2.0im, 3.0 + 4.0im, 5.0 + 6.0im), 7.0, 8.0) -@test_huge 3 'b' ((1.0 + 2.0im, 3.0 + 4.0im, 5.0 + 6.0im, 7.0 + 8.0im, 9.0 + 10.0im, 11.0 + 12.0im, 13.0 + 14.0im), 7.0, 8.0) -@test_huge 3 'c' ((1.0 + 2.0im, 3.0 + 4.0im, 5.0 + 6.0im, 7.0 + 8.0im, 9.0 + 10.0im, 11.0 + 12.0im, 13.0 + 14.0im), 7.0, 8.0, 9.0) -@test_huge 4 'a' (1.0 + 2.0im, 3.0 + 4.0im, 5.0f0 + 6.0f0im, 7.0 + 8.0im, 9.0) -@test_huge 4 'b' (1.0 + 2.0im, 3.0 + 4.0im, 5.0f0 + 6.0f0im, 7.0 + 8.0im, 9.0 + 10.0im) -@test_huge 5 'a' ((1 + 2im, 3 + 4im, 5 + 6im, 7 + 8im, 9 + 10im, 11 + 12im, 13 + 14im, 15 + 16im),) -@test_huge 5 'b' ((1 + 2im, 3 + 4im, 5 + 6im, 7 + 8im, 9 + 10im, 11 + 12im, 13 + 14im, 15 + 16im, 17 + 17im),) - -## cfunction roundtrip - -verbose && Libc.flush_cstdio() -verbose && println("Testing cfunction roundtrip: ") - -cf64 = 2.84+5.2im -cf32 = 3.34f0+53.2f0im -ci32 = Complex{Int32}(Int32(10),Int32(31)) -ci64 = Complex{Int64}(Int64(20),Int64(51)) -s1 = Struct1(352.39422f23, 19.287577) -==(a::Struct1,b::Struct1) = a.x == b.x && a.y == b.y - -for (t,v) in ((Complex{Int32},:ci32),(Complex{Int64},:ci64), - (Complex64,:cf32),(Complex128,:cf64),(Struct1,:s1)) - fname = Symbol("foo",v) - fname1 = Symbol("foo1",v) - @eval begin - verbose && println($t) - a = copy($v) - verbose && println("A: ",a) - function $fname1(s::$t) - verbose && println("B: ",s) - @test s == $v - @test s === a - global c = s - s - end - function $fname1(s) - @assert false - end - function $fname(s::$t) - verbose && println("B: ",s) - @test s == $v - if($(t).mutable) - @test !(s === a) - end - global c = s - s - end - function $fname(s) - @assert false - end - b = ccall(cfunction($fname1,Ref{$t},(Ref{$t},)),Ref{$t},(Ref{$t},),a) - verbose && println("C: ",b) - @test b == $v - @test b === a - @test b === c - b = ccall(cfunction($fname,$t,($t,)),$t,($t,),a) - verbose && println("C: ",b) - @test b == $v - if ($(t).mutable) - @test !(b === c) - @test !(b === a) - end - b = ccall(cfunction($fname1,$t,(Ref{$t},)),$t,(Ref{$t},),a) - verbose && println("C: ",b) - @test b == $v - if ($(t).mutable) - @test !(b === c) - @test !(b === a) - end - b = ccall(cfunction($fname,Ref{$t},($t,)),Ref{$t},($t,),a) - verbose && println("C: ",b) - @test b == $v - @test b === c - if ($(t).mutable) - @test !(b === a) - end - b = ccall(cfunction($fname,Any,(Ref{$t},)),Any,(Ref{$t},),$v) - verbose && println("C: ",b) - @test b == $v - @test b === c - if ($(t).mutable) - @test !(b === a) - end - b = ccall(cfunction($fname,Any,(Ref{Any},)),Any,(Ref{Any},),$v) - @test b == $v - @test b === c - if ($(t).mutable) - @test !(b === a) - end - @test_throws TypeError ccall(cfunction($fname,Ref{AbstractString},(Ref{Any},)),Any,(Ref{Any},),$v) - @test_throws TypeError ccall(cfunction($fname,AbstractString,(Ref{Any},)),Any,(Ref{Any},),$v) - end -end - -# issue 13031 -foo13031(x) = Cint(1) -foo13031p = cfunction(foo13031, Cint, (Ref{Tuple{}},)) -ccall(foo13031p, Cint, (Ref{Tuple{}},), ()) - -foo13031(x,y,z) = z -foo13031p = cfunction(foo13031, Cint, (Ref{Tuple{}},Ref{Tuple{}},Cint)) -ccall(foo13031p, Cint, (Ref{Tuple{}},Ref{Tuple{}},Cint), (), (), 8) - -# issue 17219 -function ccall_reassigned_ptr(ptr::Ptr{Void}) - ptr = Libdl.dlsym(Libdl.dlopen(libccalltest), "test_echo_p") - ccall(ptr, Any, (Any,), "foo") -end -@test ccall_reassigned_ptr(C_NULL) == "foo" - -# @threadcall functionality -threadcall_test_func(x) = - @threadcall((:testUcharX, libccalltest), Int32, (UInt8,), x % UInt8) - -@test threadcall_test_func(3) == 1 -@test threadcall_test_func(259) == 1 - -# issue 17819 -# NOTE: can't use cfunction or reuse ccalltest Struct methods, as those call into the runtime -@test @threadcall((:threadcall_args, libccalltest), Cint, (Cint, Cint), 1, 2) == 3 - -let n=3 - tids = Culong[] - @sync for i in 1:10^n - @async push!(tids, @threadcall(:uv_thread_self, Culong, ())) - end - - # The work should not be done on the master thread - t0 = ccall(:uv_thread_self, Culong, ()) - @test length(tids) == 10^n - for t in tids - @test t != t0 - end -end - -@test ccall(:jl_getpagesize, Clong, ()) == @threadcall(:jl_getpagesize, Clong, ()) - -# Pointer finalizer (issue #15408) -let A = [1] - ccall((:set_c_int, libccalltest), Void, (Cint,), 1) - @test ccall((:get_c_int, libccalltest), Cint, ()) == 1 - finalizer(A, cglobal((:finalizer_cptr, libccalltest), Void)) - finalize(A) - @test ccall((:get_c_int, libccalltest), Cint, ()) == -1 -end - -# Pointer finalizer at exit (PR #19911) -let result = readstring(`$(Base.julia_cmd()) --startup-file=no -e "A = Ref{Cint}(42); finalizer(A, cglobal((:c_exit_finalizer, \"$libccalltest\"), Void))"`) - @test result == "c_exit_finalizer: 42, 0" -end - -# SIMD Registers - -const VecReg{N,T} = NTuple{N,VecElement{T}} -const V2xF32 = VecReg{2,Float32} -const V4xF32 = VecReg{4,Float32} -const V2xF64 = VecReg{2,Float64} -const V2xI32 = VecReg{2,Int32} -const V4xI32 = VecReg{4,Int32} - -struct Struct_AA64_1 - v1::Int32 - v2::Int128 -end -struct Struct_AA64_2 - v1::Float16 - v2::Float64 -end - -# This is a homogenious short vector aggregate -struct Struct_AA64_3 - v1::VecReg{8,Int8} - v2::VecReg{2,Float32} -end -# This is NOT a homogenious short vector aggregate -struct Struct_AA64_4 - v2::VecReg{2,Float32} - v1::VecReg{8,Int16} -end - -mutable struct Struct_huge1_ppc64 - m::Int64 - v::V4xF32 -end - -mutable struct Struct_huge2_ppc64 - v1::V4xF32 - v2::V2xI32 -end - -mutable struct Struct_huge3_ppc64 - v1::V4xF32 - f::NTuple{4,Float32} -end - -mutable struct Struct_huge4_ppc64 - v1::V2xF32 - v2::V2xF64 -end - -mutable struct Struct_huge5_ppc64 - v1::NTuple{9,V4xF32} -end - -mutable struct Struct_huge6_ppc64 - v1::NTuple{8,V4xF32} - v2::V4xF32 -end - -mutable struct Struct_huge7_ppc64 - v1::VecReg{3,Int32} - v2::VecReg{3,Int32} -end - -mutable struct Struct_huge1_ppc64_hva - v1::NTuple{8,V4xF32} -end - -mutable struct Struct_huge2_ppc64_hva - v1::NTuple{2,NTuple{2,V4xF32}} -end - -mutable struct Struct_huge3_ppc64_hva - vf1::V4xF32 - vf2::Tuple{NTuple{2,V4xF32}} -end - -mutable struct Struct_huge4_ppc64_hva - v1::V4xI32 - v2::V4xF32 -end - -mutable struct Struct_huge5_ppc64_hva - v1::V4xI32 - v2::V2xF64 -end - -if Sys.ARCH === :x86_64 - function test_sse(a1::V4xF32, a2::V4xF32, a3::V4xF32, a4::V4xF32) - ccall((:test_m128, libccalltest), V4xF32, (V4xF32, V4xF32, V4xF32, V4xF32), a1, a2, a3, a4) - end - - function test_sse(a1::V4xI32, a2::V4xI32, a3::V4xI32, a4::V4xI32) - ccall((:test_m128i, libccalltest), V4xI32, (V4xI32, V4xI32, V4xI32, V4xI32), a1, a2, a3, a4) - end - - foo_ams(a1, a2, a3, a4) = VecReg(ntuple(i -> VecElement(a1[i].value + a2[i].value * (a3[i].value - a4[i].value)), 4)) - - for s in [Float32, Int32] - T = NTuple{4, VecElement{s}} - @eval function rt_sse(a1::$T, a2::$T, a3::$T, a4::$T) - return ccall( - cfunction(foo_ams, $T, ($T, $T, $T, $T)), - $T, - ($T, $T, $T, $T), - a1, a2, a3, a4) - end - - a1 = VecReg(ntuple(i -> VecElement(s(1i)), 4)) - a2 = VecReg(ntuple(i -> VecElement(s(2i)), 4)) - a3 = VecReg(ntuple(i -> VecElement(s(3i)), 4)) - a4 = VecReg(ntuple(i -> VecElement(s(4i)), 4)) - r = VecReg(ntuple(i -> VecElement(s(1i + 2i * (3i - 4i))), 4)) - @test test_sse(a1, a2, a3, a4) == r - - # cfunction round-trip - @test rt_sse(a1, a2, a3, a4) == r - end - -elseif Sys.ARCH === :aarch64 - for v1 in 1:99:1000, v2 in -100:-1999:-20000 - @test ccall((:test_aa64_i128_1, libccalltest), Int128, - (Int64, Int128), v1, v2) == v1 * 2 - v2 - end - for v1 in 1:4, v2 in -4:-1, v3_1 in 3:5, v3_2 in 7:9 - res = ccall((:test_aa64_i128_2, libccalltest), Struct_AA64_1, - (Int64, Int128, Struct_AA64_1), - v1, v2, Struct_AA64_1(v3_1, v3_2)) - expected = Struct_AA64_1(v1 ÷ 2 + 1 - v3_1, v2 * 2 - 1 - v3_2) - @test res === expected - end - for v1 in 1:4, v2 in -4:-1, v3 in 3:5, v4 in -(1:3) - res = ccall((:test_aa64_fp16_1, libccalltest), Float16, - (Cint, Float32, Float64, Float16), - v1, v2, v3, v4) - expected = Float16(v1 + v2 * 2 + v3 * 3 + v4 * 4) - @test res === expected - - res = ccall((:test_aa64_fp16_2, libccalltest), Struct_AA64_2, - (Cint, Float32, Float64, Float16), - v1, v2, v3, v4) - expected = Struct_AA64_2(v4 / 2 + 1, v1 * 2 + v2 * 4 - v3) - @test res === expected - end - for v1_1 in 1:4, v1_2 in -2:2, v2 in -4:-1, v3_1 in 3:5, v3_2 in 6:8 - res = ccall((:test_aa64_vec_1, libccalltest), - VecReg{2,Int64}, - (VecReg{2,Int32}, Float32, VecReg{2,Int32}), - (VecElement(Int32(v1_1)), VecElement(Int32(v1_2))), - v2, (VecElement(Int32(v3_1)), VecElement(Int32(v3_2)))) - expected = (VecElement(v1_1 * v2 + v3_1), VecElement(v1_2 * v2 + v3_2)) - @test res === expected - end - for v1_11 in 1:4, v1_12 in -2:2, v1_21 in 1:4, v1_22 in -2:2, - v2_11 in 1:4, v2_12 in -2:2, v2_21 in 1:4, v2_22 in -2:2 - v1 = Struct_AA64_3((VecElement(Int8(v1_11)), VecElement(Int8(v1_12)), - VecElement(Int8(0)), VecElement(Int8(0)), - VecElement(Int8(0)), VecElement(Int8(0)), - VecElement(Int8(0)), VecElement(Int8(0))), - (VecElement(Float32(v1_21)), - VecElement(Float32(v1_22)))) - v2 = Struct_AA64_4((VecElement(Float32(v2_21)), - VecElement(Float32(v2_22))), - (VecElement(Int16(v2_11)), VecElement(Int16(v2_12)), - VecElement(Int16(0)), VecElement(Int16(0)), - VecElement(Int16(0)), VecElement(Int16(0)), - VecElement(Int16(0)), VecElement(Int16(0)))) - res = ccall((:test_aa64_vec_2, libccalltest), - Struct_AA64_3, (Struct_AA64_3, Struct_AA64_4), v1, v2) - expected = Struct_AA64_3((VecElement(Int8(v1_11 + v2_11)), - VecElement(Int8(v1_12 + v2_12)), - VecElement(Int8(0)), VecElement(Int8(0)), - VecElement(Int8(0)), VecElement(Int8(0)), - VecElement(Int8(0)), VecElement(Int8(0))), - (VecElement(Float32(v1_21 - v2_21)), - VecElement(Float32(v1_22 - v2_22)))) - @test res === expected - end - -elseif Sys.ARCH === :powerpc64le || Sys.ARCH === :ppc64le -@test_huge 1 "_ppc64" (1, (2.0, 3.0, 4.0, 5.0),) -@test_huge 2 "_ppc64" ((1.0, 2.0, 3.0, 4.0), (11, 12)) -@test_huge 3 "_ppc64" ((1, 2, 3, 4), (11.0, 12.0, 13.0, 14.0)) -@test_huge 4 "_ppc64" ((1, 2), (11.0, 12.0)) -@test_huge 5 "_ppc64" ((((1.0, 2.0, 3.0, 4.0), - (5.0, 6.0, 7.0, 8.0), - (11.0, 12.0, 13.0, 14.0), - (15.0, 16.0, 17.0, 18.0), - (21.0, 22.0, 23.0, 24.0), - (25.0, 26.0, 27.0, 28.0), - (31.0, 32.0, 33.0, 34.0), - (35.0, 36.0, 37.0, 38.0), - (41.0, 42.0, 43.0, 44.0)),)) -@test_huge 6 "_ppc64" ((((1.0, 2.0, 3.0, 4.0), - (5.0, 6.0, 7.0, 8.0), - (11.0, 12.0, 13.0, 14.0), - (15.0, 16.0, 17.0, 18.0), - (21.0, 22.0, 23.0, 24.0), - (25.0, 26.0, 27.0, 28.0), - (31.0, 32.0, 33.0, 34.0), - (35.0, 36.0, 37.0, 38.0)), - (41.0, 42.0, 43.0, 44.0))) -@test_huge 1 "_ppc64_hva" ((((1.0, 2.0, 3.0, 4.0), - (5.0, 6.0, 7.0, 8.0), - (11.0, 12.0, 13.0, 14.0), - (15.0, 16.0, 17.0, 18.0), - (21.0, 22.0, 23.0, 24.0), - (25.0, 26.0, 27.0, 28.0), - (31.0, 32.0, 33.0, 34.0), - (35.0, 36.0, 37.0, 38.0)),)) -@test_huge 2 "_ppc64_hva" (((((1.0, 2.0, 3.0, 4.0), - (5.0, 6.0, 7.0, 8.0)), - ((11.0, 12.0, 13.0, 14.0), - (15.0, 16.0, 17.0, 18.0))),)) -@test_huge 3 "_ppc64_hva" (((1.0, 2.0, 3.0, 4.0), - (((11.0, 12.0, 13.0, 14.0), - (15.0, 16.0, 17.0, 18.0)),))) -@test_huge 4 "_ppc64_hva" (((1, 2, 3, 4), - (11.0, 12.0, 13.0, 14.0))) -@test_huge 5 "_ppc64_hva" (((1, 2, 3, 4), - (11.0, 12.0))) - -@test 18451 == ccall((:test_ppc64_vec1long, libccalltest), Int64, - (Int64, Int64, Int64, Int64, Int64, Int64, Int64, Int64, Int64, Struct_huge1_ppc64), - 1, 2, 3, 4, 5, 6, 7, 8, 9, Struct_huge1_ppc64(18000, (100, 101, 102, 103))) - -@test 941 == ccall((:test_ppc64_vec1long_vec, libccalltest), Int64, - (Int64, Int64, Int64, Int64, Int64, Int64, Int64, Int64, Int64, V4xF32), - 11, 12, 13, 14, 15, 16, 17, 18, 19, (200, 201, 202, 203)) - -@test V4xF32((614232, 614218, 614204, 614190)) == - ccall((:test_ppc64_vec2, libccalltest), V4xF32, - (Int64, V4xF32, V4xF32, V4xF32, V4xF32, - V4xF32, V4xF32, V4xF32, V4xF32, V4xF32, - V4xF32, V4xF32, V4xF32, V4xF32, V4xF32), - 600000, (4, 3, 2, 1), (5, 4, 3, 2), (6, 5, 4, 3), (7, 6, 5, 4), - (14, 13, 12, 11), (15, 14, 13, 12), (16, 15, 14, 13), (17, 16, 15, 14), (18, 17, 16, 15), - (1024, 1023, 1022, 1021), (1025, 1024, 1023, 1022), (1026, 1025, 1024, 1023), (1027, 1026, 1025, 1024), (10028, 10027, 10026, 10025)) - -elseif Sys.ARCH !== :i686 && Sys.ARCH !== :arm # TODO -warn("ccall: no VecReg tests run for this platform") - -end - -# Special calling convention for `Array` -function f17204(a) - b = similar(a) - for i in eachindex(a) - b[i] = a[i] + 10 - end - return b -end -@test ccall(cfunction(f17204, Vector{Any}, Tuple{Vector{Any}}), - Vector{Any}, (Vector{Any},), Any[1:10;]) == Any[11:20;] - -# This used to trigger incorrect ccall callee inlining. -# Not sure if there's a more reliable way to test this. -# Do not put these in a function. -@noinline g17413() = rand() -@inline f17413() = (g17413(); g17413()) -ccall((:test_echo_p, libccalltest), Ptr{Void}, (Any,), f17413()) -for i in 1:3 - ccall((:test_echo_p, libccalltest), Ptr{Void}, (Any,), f17413()) -end - -struct SpillPint - a::Ptr{Cint} - b::Ptr{Cint} -end -Base.cconvert(::Type{SpillPint}, v::NTuple{2,Cint}) = - Base.cconvert(Ref{NTuple{2,Cint}}, v) -function Base.unsafe_convert(::Type{SpillPint}, vr) - ptr = Base.unsafe_convert(Ref{NTuple{2,Cint}}, vr) - return SpillPint(ptr, ptr + 4) -end - -macro test_spill_n(n::Int, intargs, floatargs) - fname_int = Symbol(:test_spill_int, n) - fname_float = Symbol(:test_spill_float, n) - quote - local ints = $(esc(intargs)) - local floats = $(esc(intargs)) - @test ccall(($(QuoteNode(fname_int)), libccalltest), Cint, - ($((:(Ref{Cint}) for j in 1:n)...), SpillPint), - $((:(ints[$j]) for j in 1:n)...), - (ints[$n + 1], ints[$n + 2])) == sum(ints[1:($n + 2)]) - @test ccall(($(QuoteNode(fname_float)), libccalltest), Float32, - ($((:Float32 for j in 1:n)...), NTuple{2,Float32}), - $((:(floats[$j]) for j in 1:n)...), - (floats[$n + 1], floats[$n + 2])) == sum(floats[1:($n + 2)]) - end -end - -for i in 1:100 - local intargs = rand(1:10000, 14) - local int32args = Int32.(intargs) - local intsum = sum(intargs) - local floatargs = rand(14) - local float32args = Float32.(floatargs) - local float32sum = sum(float32args) - local float64sum = sum(floatargs) - @test ccall((:test_long_args_intp, libccalltest), Cint, - (Ref{Cint}, Ref{Cint}, Ref{Cint}, Ref{Cint}, - Ref{Cint}, Ref{Cint}, Ref{Cint}, Ref{Cint}, - Ref{Cint}, Ref{Cint}, Ref{Cint}, Ref{Cint}, - Ref{Cint}, Ref{Cint}), - intargs[1], intargs[2], intargs[3], intargs[4], - intargs[5], intargs[6], intargs[7], intargs[8], - intargs[9], intargs[10], intargs[11], intargs[12], - intargs[13], intargs[14]) == intsum - @test ccall((:test_long_args_int, libccalltest), Cint, - (Cint, Cint, Cint, Cint, Cint, Cint, Cint, Cint, - Cint, Cint, Cint, Cint, Cint, Cint), - intargs[1], intargs[2], intargs[3], intargs[4], - intargs[5], intargs[6], intargs[7], intargs[8], - intargs[9], intargs[10], intargs[11], intargs[12], - intargs[13], intargs[14]) == intsum - @test ccall((:test_long_args_float, libccalltest), Float32, - (Float32, Float32, Float32, Float32, Float32, Float32, - Float32, Float32, Float32, Float32, Float32, Float32, - Float32, Float32), - floatargs[1], floatargs[2], floatargs[3], floatargs[4], - floatargs[5], floatargs[6], floatargs[7], floatargs[8], - floatargs[9], floatargs[10], floatargs[11], floatargs[12], - floatargs[13], floatargs[14]) ≈ float32sum - @test ccall((:test_long_args_double, libccalltest), Float64, - (Float64, Float64, Float64, Float64, Float64, Float64, - Float64, Float64, Float64, Float64, Float64, Float64, - Float64, Float64), - floatargs[1], floatargs[2], floatargs[3], floatargs[4], - floatargs[5], floatargs[6], floatargs[7], floatargs[8], - floatargs[9], floatargs[10], floatargs[11], floatargs[12], - floatargs[13], floatargs[14]) ≈ float64sum - - @test_spill_n 1 int32args float32args - @test_spill_n 2 int32args float32args - @test_spill_n 3 int32args float32args - @test_spill_n 4 int32args float32args - @test_spill_n 5 int32args float32args - @test_spill_n 6 int32args float32args - @test_spill_n 7 int32args float32args - @test_spill_n 8 int32args float32args - @test_spill_n 9 int32args float32args - @test_spill_n 10 int32args float32args -end - -# issue #20835 -@test_throws ErrorException eval(:(f20835(x) = ccall(:fn, Void, (Ptr{typeof(x)},), x))) -@test_throws UndefVarError eval(:(f20835(x) = ccall(:fn, Something_not_defined_20835, (Ptr{typeof(x)},), x))) - -@noinline f21104at(::Type{T}) where {T} = ccall(:fn, Void, (Nullable{T},), 0) -@noinline f21104rt(::Type{T}) where {T} = ccall(:fn, Nullable{T}, ()) -@test code_llvm(DevNull, f21104at, (Type{Float64},)) === nothing -@test code_llvm(DevNull, f21104rt, (Type{Float64},)) === nothing -@test try - f21104at(Float64) - "unreachable" - catch ex - (ex::ErrorException).msg - end == "ccall: the type of argument 1 doesn't correspond to a C type" -@test try - f21104rt(Float64) - "unreachable" - catch ex - (ex::ErrorException).msg - end == "ccall: return type doesn't correspond to a C type" - - -# cfunction on non-function singleton -struct CallableSingleton -end -(::CallableSingleton)(x, y) = x + y -@test ccall(cfunction(CallableSingleton(), Int, Tuple{Int,Int}), - Int, (Int, Int), 1, 2) === 3 - -# 19805 -mutable struct callinfos_19805{FUNC_FT<:Function} - f :: FUNC_FT -end - -evalf_callback_19805{FUNC_FT}(ci::callinfos_19805{FUNC_FT}) = ci.f(0.5)::Float64 - -evalf_callback_c_19805{FUNC_FT}(ci::callinfos_19805{FUNC_FT}) = cfunction( - evalf_callback_19805, Float64, (callinfos_19805{FUNC_FT},)) - -@test_throws ErrorException evalf_callback_c_19805( callinfos_19805(sin) ) diff --git a/julia-0.6.3/share/julia/test/channels.jl b/julia-0.6.3/share/julia/test/channels.jl deleted file mode 100644 index 7f5d206..0000000 --- a/julia-0.6.3/share/julia/test/channels.jl +++ /dev/null @@ -1,351 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -# Test various constructors -c=Channel(1) -@test eltype(c) == Any -@test put!(c, 1) == 1 -@test isready(c) == true -@test take!(c) == 1 -@test isready(c) == false - -@test eltype(Channel(1.0)) == Any - -c=Channel{Int}(1) -@test eltype(c) == Int -@test_throws MethodError put!(c, "Hello") - -c=Channel{Int}(Inf) -@test eltype(c) == Int -pvals = map(i->put!(c,i), 1:10^6) -tvals = Int[take!(c) for i in 1:10^6] -@test pvals == tvals - -# Uncomment line below once deprecation support has been removed. -# @test_throws MethodError Channel() - -@test_throws ArgumentError Channel(-1) -@test_throws InexactError Channel(1.5) - -# Test multiple concurrent put!/take! on a channel for different sizes -function testcpt(sz) - c = Channel{Int}(sz) - size = 0 - inc() = size += 1 - dec() = size -= 1 - @sync for i = 1:10^4 - @async (sleep(rand()); put!(c, i); inc()) - @async (sleep(rand()); take!(c); dec()) - end - @test size == 0 -end -testcpt(0) -testcpt(1) -testcpt(32) -testcpt(Inf) - -# Test multiple "for" loops waiting on the same channel which -# is closed after adding a few elements. -c=Channel(32) -results=[] -@sync begin - for i in 1:20 - @async for i in c - push!(results, i) - end - end - sleep(1.0) - for i in 1:5 - put!(c,i) - end - close(c) -end -@test sum(results) == 15 - -# Test channel iterator with done() being called multiple times -# This needs to be explicitly tested since `take!` is called -# in `done()` and not `next()` -c=Channel(32); foreach(i->put!(c,i), 1:10); close(c) -s=start(c) -@test done(c,s) == false -res = Int[] -while !done(c,s) - @test done(c,s) == false - v,s = next(c,s) - push!(res,v) -end -@test res == Int[1:10...] - -# Tests for channels bound to tasks. -for N in [0,10] - # Normal exit of task - c=Channel(N) - bind(c, @schedule (yield();nothing)) - @test_throws InvalidStateException take!(c) - @test !isopen(c) - - # Error exception in task - c=Channel(N) - bind(c, @schedule (yield();error("foo"))) - @test_throws ErrorException take!(c) - @test !isopen(c) - - # Multiple channels closed by the same bound task - cs = [Channel(N) for i in 1:5] - tf2 = () -> begin - if N > 0 - foreach(c->assert(take!(c)==2), cs) - end - yield() - error("foo") - end - task = Task(tf2) - foreach(c->bind(c, task), cs) - schedule(task) - - if N > 0 - for i in 1:5 - @test put!(cs[i], 2) == 2 - end - end - for i in 1:5 - while (isopen(cs[i])); yield(); end - @test_throws ErrorException wait(cs[i]) - @test_throws ErrorException take!(cs[i]) - @test_throws ErrorException put!(cs[i], 1) - @test_throws ErrorException fetch(cs[i]) - end - - # Multiple tasks, first one to terminate closes the channel - nth = rand(1:5) - ref = Ref(0) - cond = Condition() - tf3(i) = begin - if i == nth - ref[] = i - else - sleep(2.0) - end - end - - tasks = [Task(()->tf3(i)) for i in 1:5] - c = Channel(N) - foreach(t->bind(c,t), tasks) - foreach(schedule, tasks) - @test_throws InvalidStateException wait(c) - @test !isopen(c) - @test ref[] == nth - - # channeled_tasks - for T in [Any, Int] - chnls, tasks = Base.channeled_tasks(2, (c1,c2)->(assert(take!(c1)==1); put!(c2,2)); ctypes=[T,T], csizes=[N,N]) - put!(chnls[1], 1) - @test take!(chnls[2]) == 2 - @test_throws InvalidStateException wait(chnls[1]) - @test_throws InvalidStateException wait(chnls[2]) - @test istaskdone(tasks[1]) - @test !isopen(chnls[1]) - @test !isopen(chnls[2]) - - f=Future() - tf4 = (c1,c2) -> begin - assert(take!(c1)==1) - wait(f) - end - - tf5 = (c1,c2) -> begin - put!(c2,2) - wait(f) - end - - chnls, tasks = Base.channeled_tasks(2, tf4, tf5; ctypes=[T,T], csizes=[N,N]) - put!(chnls[1], 1) - @test take!(chnls[2]) == 2 - yield() - put!(f, 1) - - @test_throws InvalidStateException wait(chnls[1]) - @test_throws InvalidStateException wait(chnls[2]) - @test istaskdone(tasks[1]) - @test istaskdone(tasks[2]) - @test !isopen(chnls[1]) - @test !isopen(chnls[2]) - end - - # channel - tf6 = c -> begin - assert(take!(c)==2) - error("foo") - end - - for T in [Any, Int] - taskref = Ref{Task}() - chnl = Channel(tf6, ctype=T, csize=N, taskref=taskref) - put!(chnl, 2) - yield() - @test_throws ErrorException wait(chnl) - @test istaskdone(taskref[]) - @test !isopen(chnl) - @test_throws ErrorException take!(chnl) - end -end - - -# Testing timedwait on multiple channels -@sync begin - rr1 = Channel(1) - rr2 = Channel(1) - rr3 = Channel(1) - - callback() = all(map(isready, [rr1, rr2, rr3])) - # precompile functions which will be tested for execution time - @test !callback() - @test timedwait(callback, 0.0) === :timed_out - - @async begin sleep(0.5); put!(rr1, :ok) end - @async begin sleep(1.0); put!(rr2, :ok) end - @async begin sleep(2.0); put!(rr3, :ok) end - - tic() - timedwait(callback, Dates.Second(1)) - et=toq() - # assuming that 0.5 seconds is a good enough buffer on a typical modern CPU - try - @assert (et >= 1.0) && (et <= 1.5) - @assert !isready(rr3) - catch - warn("timedwait tests delayed. et=$et, isready(rr3)=$(isready(rr3))") - end - @test isready(rr1) -end - - -# test for yield/wait/event failures -@noinline garbage_finalizer(f) = finalizer("gar" * "bage", f) -let t, run = Ref(0) - gc_enable(false) - # test for finalizers trying to yield leading to failed attempts to context switch - garbage_finalizer((x) -> (run[] += 1; sleep(1))) - garbage_finalizer((x) -> (run[] += 1; yield())) - garbage_finalizer((x) -> (run[] += 1; yieldto(@task () -> ()))) - t = @task begin - gc_enable(true) - gc() - end - oldstderr = STDERR - local newstderr, errstream - try - newstderr = redirect_stderr() - errstream = @async readstring(newstderr[1]) - yield(t) - finally - redirect_stderr(oldstderr) - close(newstderr[2]) - end - wait(t) - @test run[] == 3 - @test wait(errstream) == """ - error in running finalizer: ErrorException("task switch not allowed from inside gc finalizer") - error in running finalizer: ErrorException("task switch not allowed from inside gc finalizer") - error in running finalizer: ErrorException("task switch not allowed from inside gc finalizer") - """ - # test for invalid state in Workqueue during yield - t = @schedule nothing - t.state = :invalid - try - newstderr = redirect_stderr() - errstream = @async readstring(newstderr[1]) - yield() - finally - redirect_stderr(oldstderr) - close(newstderr[2]) - end - @test wait(errstream) == "\nWARNING: Workqueue inconsistency detected: shift!(Workqueue).state != :queued\n" -end - -# schedule_and_wait tests -let t = @schedule(nothing), - ct = current_task(), - testobject = "testobject" - @test length(Base.Workqueue) == 1 - @test Base.schedule_and_wait(ct, 8) == 8 - @test isempty(Base.Workqueue) - @test Base.schedule_and_wait(ct, testobject) === testobject -end - -# throwto tests -let t = @task(nothing), - ct = current_task(), - testerr = ErrorException("expected") - @async Base.throwto(t, testerr) - @test try - wait(t) - false - catch ex - ex - end === testerr -end - -# Timer / AsyncCondition triggering and race #12719 -let tc = Ref(0), - t = Timer(0) do t - tc[] += 1 - end - @test isopen(t) - Base.process_events(false) - @test !isopen(t) - @test tc[] == 0 - yield() - @test tc[] == 1 -end -let tc = Ref(0), - t = Timer(0) do t - tc[] += 1 - end - @test isopen(t) - close(t) - @test !isopen(t) - sleep(0.1) - @test tc[] == 0 -end -let tc = Ref(0), - async = Base.AsyncCondition() do async - tc[] += 1 - end - @test isopen(async) - ccall(:uv_async_send, Void, (Ptr{Void},), async) - Base.process_events(false) # schedule event - ccall(:uv_async_send, Void, (Ptr{Void},), async) - is_windows() && Base.process_events(false) # schedule event (windows?) - @test tc[] == 0 - yield() # consume event - @test tc[] == 1 - sleep(0.1) # no further events - @test tc[] == 1 - ccall(:uv_async_send, Void, (Ptr{Void},), async) - ccall(:uv_async_send, Void, (Ptr{Void},), async) - close(async) - @test !isopen(async) - @test tc[] == 1 - Base.process_events(false) # schedule event & then close - is_windows() && Base.process_events(false) # schedule event (windows?) - yield() # consume event & then close - @test tc[] == 2 - sleep(0.1) # no further events - @test tc[] == 2 -end -let tc = Ref(0), - async = Base.AsyncCondition() do async - tc[] += 1 - end - @test isopen(async) - ccall(:uv_async_send, Void, (Ptr{Void},), async) - close(async) - @test !isopen(async) - Base.process_events(false) # schedule event & then close - is_windows() && Base.process_events(false) # schedule event (windows) - @test tc[] == 0 - yield() # consume event & then close - @test tc[] == 1 - sleep(0.1) - @test tc[] == 1 -end diff --git a/julia-0.6.3/share/julia/test/char.jl b/julia-0.6.3/share/julia/test/char.jl deleted file mode 100644 index c40f60d..0000000 --- a/julia-0.6.3/share/julia/test/char.jl +++ /dev/null @@ -1,200 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -#tests for /base/char.jl - -@test typemin(Char) == Char(0) -@test ndims(Char) == 0 -@test getindex('a', 1) == 'a' -@test_throws BoundsError getindex('a',2) -# This is current behavior, but it seems incorrect -@test getindex('a',1,1,1) == 'a' -@test_throws BoundsError getindex('a',1,1,2) -# bswap of a Char should be removed, only the underlying codeunit (UInt32) -# should be swapped -@test bswap('\U10200') == '\U20100' - -@test 'b' + 1 == 'c' -@test typeof('b' + 1) == Char -@test 1 + 'b' == 'c' -@test typeof(1 + 'b') == Char -@test 'b' - 1 == 'a' -@test typeof('b' - 1) == Char - -let - numberchars = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] - lowerchars = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] - upperchars = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'] - plane1_playingcards = ['🂠', '🂡', '🂢', '🂣', '🂤', '🂥', '🂦', '🂧', '🂨', '🂩', '🂪', '🂫', '🂬', '🂭', '🂮'] - plane2_cjkpart1 = ['𠀀', '𠀁', '𠀂', '𠀃', '𠀄', '𠀅', '𠀆', '𠀇', '𠀈', '𠀉', '𠀊', '𠀋', '𠀌', '𠀍', '𠀎', '𠀏'] - - testarrays = [numberchars; lowerchars; upperchars; plane1_playingcards; plane2_cjkpart1] - - #Integer(x::Char) = Int(x) - #tests ASCII 48 - 57 - counter = 48 - for x in numberchars - @test Integer(x) == counter - counter += 1 - end - - #tests ASCII 65 - 90 - counter = 65 - for x in upperchars - @test Integer(x) == counter - counter += 1 - end - - #tests ASCII 97 - 122 - counter = 97 - for x in lowerchars - @test Integer(x) == counter - counter += 1 - end - - #tests Unicode plane 1: 127136 - 127150 - counter = 127136 - for x in plane1_playingcards - @test Integer(x) == counter - counter += 1 - end - - #tests Unicode plane 2: 131072 - 131087 - counter = 131072 - for x in plane2_cjkpart1 - @test Integer(x) == counter - counter += 1 - end - - #convert(::Type{Char}, x::Float16) = char(convert(UInt32, x)) - #convert(::Type{Char}, x::Float32) = char(convert(UInt32, x)) - #convert(::Type{Char}, x::Float64) = char(convert(UInt32, x)) - for x = 1:9 - @test convert(Char, Float16(x)) == convert(Char, Float32(x)) == convert(Char, Float64(x)) == Char(x) - end - - #size(c::Char) = () - for x in testarrays - @test size(x) == () - @test_throws BoundsError size(x,0) - @test size(x,1) == 1 - end - - #ndims(c::Char) = 0 - for x in testarrays - @test ndims(x) == 0 - end - - #length(c::Char) = 1 - for x in testarrays - @test length(x) == 1 - end - - #endof(c::Char) = 1 - for x in testarrays - @test endof(x) == 1 - end - - #getindex(c::Char) = c - for x in testarrays - @test getindex(x) == x - end - - #first(c::Char) = c - for x in testarrays - @test first(x) == x - end - - #last(c::Char) = c - for x in testarrays - @test last(x) == x - end - - #eltype(c::Char) = Char - for x in testarrays - @test eltype(x) == Char - end - - #start(c::Char) = false - for x in testarrays - @test start(x) == false - end - - #next(c::Char, state) = (c, true) - for x in testarrays - for state in [true, false] - @test next(x, state) == (x, true) - end - end - - #done(c::Char, state) = state - for x in testarrays - for state in [true, false] - @test done(x, state) == state - end - end - - #isless(x::Char, y::Integer) = isless(UInt32(x), y) - for x in upperchars - @test isless(x, Char(91)) == true - end - - for x in lowerchars - @test isless(x, Char(123)) == true - end - - for x in numberchars - @test isless(x, Char(66)) == true - end - - for x in plane1_playingcards - @test isless(x, Char(127151)) == true - end - - for x in plane2_cjkpart1 - @test isless(x, Char(131088)) == true - end - - #isless(x::Integer, y::Char) = isless(x, UInt32(y)) - for x in upperchars - @test isless(Char(64), x) == true - end - - for x in lowerchars - @test isless(Char(96), x) == true - end - - for x in numberchars - @test isless(Char(47), x) == true - end - - for x in plane1_playingcards - @test isless(Char(127135), x) == true - end - - for x in plane2_cjkpart1 - @test isless(Char(131071), x) == true - end -end #end of let block - -@test convert(Signed, 'A') === Int32(65) -@test convert(Unsigned, 'A') === UInt32(65) - -# issue #14573 -let - array = ['a', 'b', 'c'] + [1, 2, 3] - @test array == ['b', 'd', 'f'] - @test eltype(array) == Char - - array = [1, 2, 3] + ['a', 'b', 'c'] - @test array == ['b', 'd', 'f'] - @test eltype(array) == Char - - array = ['a', 'b', 'c'] - [0, 1, 2] - @test array == ['a', 'a', 'a'] - @test eltype(array) == Char -end - -@test !isequal('x', 120) - -@test sprint(show, "text/plain", '$') == "'\$': ASCII/Unicode U+0024 (category Sc: Symbol, currency)" -@test repr('$') == "'\$'" diff --git a/julia-0.6.3/share/julia/test/checked.jl b/julia-0.6.3/share/julia/test/checked.jl deleted file mode 100644 index 43e897e..0000000 --- a/julia-0.6.3/share/julia/test/checked.jl +++ /dev/null @@ -1,324 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -# Checked integer arithmetic - -import Base: checked_abs, checked_neg, checked_add, checked_sub, checked_mul, - checked_div, checked_rem, checked_fld, checked_mod, checked_cld, - add_with_overflow, sub_with_overflow, mul_with_overflow - -# checked operations - -for T in (Int8, Int16, Int32, Int64, Int128) - # regular cases - @test checked_abs(T(0)) === T(0) - @test checked_neg(T(0)) === T(0) - @test checked_add(T(0)) === T(0) - @test checked_mul(T(0)) === T(0) - - for s in (-1, +1) - @test checked_abs(T(3s)) === T(abs(3s)) - @test checked_neg(T(3s)) === T(-3s) - @test checked_add(T(3s)) === T(3s) - @test checked_mul(T(3s)) === T(3s) - @test checked_abs(T(s*typemax(T))) === typemax(T) - @test checked_neg(T(s*typemax(T))) === T(-s*typemax(T)) - @test checked_add(T(s*typemax(T))) === T(s*typemax(T)) - @test checked_mul(T(s*typemax(T))) === T(s*typemax(T)) - end - - # corner cases - @test_throws OverflowError checked_abs(typemin(T)) - @test_throws OverflowError checked_neg(typemin(T)) - - # regular cases - for s1 in (-1, +1), s2 in (-1, +1) - @test checked_add(T(4s1), T(3s2)) === T(4s1 + 3s2) - @test checked_sub(T(4s1), T(3s2)) === T(4s1 - 3s2) - @test checked_mul(T(4s1), T(3s2)) === T(4s1 * 3s2) - @test checked_div(T(4s1), T(3s2)) === T(div(4s1, 3s2)) - @test checked_rem(T(4s1), T(3s2)) === T(rem(4s1, 3s2)) - @test checked_fld(T(4s1), T(3s2)) === T(fld(4s1, 3s2)) - @test checked_mod(T(4s1), T(3s2)) === T(mod(4s1, 3s2)) - @test checked_cld(T(4s1), T(3s2)) === T(cld(4s1, 3s2)) - end - - # corner cases - halfmax = T(typemax(T)÷2) - halfmax_plus1 = T(halfmax+1) - halfmin = T(typemin(T)÷2) - halfmin_minus1 = T(halfmin-1) - sqrtmax = T(1) << T(sizeof(T)*4) - half_sqrtmax = sqrtmax >> T(1) - half_sqrtmax_plus1 = half_sqrtmax + T(1) - - @test checked_add(typemax(T), T(-1)) === T(typemax(T) - 1) - @test_throws OverflowError checked_add(typemin(T), T(-1)) - @test checked_add(typemax(T), T(0)) === typemax(T) - @test checked_add(typemin(T), T(0)) === typemin(T) - @test_throws OverflowError checked_add(typemax(T), T(1)) - @test checked_add(typemin(T), T(1)) === T(typemin(T) + 1) - @test checked_add(T(-1), typemax(T)) === T(typemax(T) - 1) - @test_throws OverflowError checked_add(T(-1), typemin(T)) - @test checked_add(T(0), typemax(T)) === typemax(T) - @test checked_add(T(0), typemin(T)) === typemin(T) - @test_throws OverflowError checked_add(T(1), typemax(T)) - @test checked_add(T(1), typemin(T)) === T(typemin(T) + 1) - @test checked_add(typemax(T), typemin(T)) === T(-1) - @test checked_add(typemin(T), typemax(T)) === T(-1) - @test_throws OverflowError checked_add(halfmax_plus1, halfmax_plus1) - @test_throws OverflowError checked_add(halfmin, halfmin_minus1) - - @test add_with_overflow(typemax(T), T(-1)) === (T(typemax(T) - 1), false) - @test add_with_overflow(typemin(T), T(-1)) === (T(typemax(T)), true) - @test add_with_overflow(typemax(T), T(0)) === (typemax(T), false) - @test add_with_overflow(typemin(T), T(0)) === (typemin(T), false) - @test add_with_overflow(typemax(T), T(1)) === (typemin(T), true) - @test add_with_overflow(typemin(T), T(1)) === (T(typemin(T) + 1), false) - @test add_with_overflow(T(-1), typemax(T)) === (T(typemax(T) - 1), false) - @test add_with_overflow(T(-1), typemin(T)) === (typemax(T), true) - @test add_with_overflow(T(0), typemax(T)) === (typemax(T), false) - @test add_with_overflow(T(0), typemin(T)) === (typemin(T), false) - @test add_with_overflow(T(1), typemax(T)) === (typemin(T), true) - @test add_with_overflow(T(1), typemin(T)) === (T(typemin(T) + 1), false) - @test add_with_overflow(typemax(T), typemin(T)) === (T(-1), false) - @test add_with_overflow(typemin(T), typemax(T)) === (T(-1), false) - @test add_with_overflow(halfmax_plus1, halfmax_plus1) === (typemin(T), true) - @test add_with_overflow(halfmin, halfmin_minus1) === (typemax(T), true) - - @test_throws OverflowError checked_sub(typemax(T), T(-1)) - @test checked_sub(typemax(T), T(0)) === typemax(T) - @test checked_sub(typemax(T), T(1)) === T(typemax(T) - 1) - @test checked_sub(typemin(T), T(-1)) === T(typemin(T) + 1) - @test checked_sub(typemin(T), T(0)) === typemin(T) - @test_throws OverflowError checked_sub(typemin(T), T(1)) - @test checked_sub(T(0), typemax(T)) === T(typemin(T) + 1) - @test checked_sub(T(1), typemax(T)) === T(typemin(T) + 2) - @test checked_sub(T(-1), typemin(T)) === typemax(T) - @test_throws OverflowError checked_sub(T(0), typemin(T)) - @test checked_sub(typemax(T), typemax(T)) === T(0) - @test checked_sub(typemin(T), typemin(T)) === T(0) - @test checked_sub(halfmax, T(-halfmin)) === T(-1) - @test_throws OverflowError checked_sub(halfmin, T(-halfmin_minus1)) - - @test sub_with_overflow(typemax(T), T(-1)) === (typemin(T), true) - @test sub_with_overflow(typemax(T), T(0)) === (typemax(T), false) - @test sub_with_overflow(typemax(T), T(1)) === (T(typemax(T) - 1), false) - @test sub_with_overflow(typemin(T), T(-1)) === (T(typemin(T) + 1), false) - @test sub_with_overflow(typemin(T), T(0)) === (typemin(T), false) - @test sub_with_overflow(typemin(T), T(1)) === (typemax(T), true) - @test sub_with_overflow(T(0), typemax(T)) === (T(typemin(T) + 1), false) - @test sub_with_overflow(T(1), typemax(T)) === (T(typemin(T) + 2), false) - @test sub_with_overflow(T(-1), typemin(T)) === (typemax(T), false) - @test sub_with_overflow(T(0), typemin(T)) === (typemin(T), true) - @test sub_with_overflow(typemax(T), typemax(T)) === (T(0), false) - @test sub_with_overflow(typemin(T), typemin(T)) === (T(0), false) - @test sub_with_overflow(halfmax, T(-halfmin)) === (T(-1), false) - @test sub_with_overflow(halfmin, T(-halfmin_minus1)) === (typemax(T), true) - - @test checked_mul(typemax(T), T(0)) === T(0) - @test checked_mul(typemin(T), T(0)) === T(0) - @test checked_mul(typemax(T), T(1)) === typemax(T) - @test checked_mul(typemin(T), T(1)) === typemin(T) - @test_throws OverflowError checked_mul(sqrtmax, half_sqrtmax) - @test checked_mul(sqrtmax, -half_sqrtmax) === T(sqrtmax * -half_sqrtmax) - @test_throws OverflowError checked_mul(sqrtmax, -half_sqrtmax_plus1) - @test checked_mul(-sqrtmax, half_sqrtmax) === T(-sqrtmax * half_sqrtmax) - @test_throws OverflowError checked_mul(-sqrtmax, half_sqrtmax_plus1) - @test_throws OverflowError checked_mul(-sqrtmax, -half_sqrtmax) - - @test mul_with_overflow(typemax(T), T(0)) === (T(0), false) - @test mul_with_overflow(typemin(T), T(0)) === (T(0), false) - @test mul_with_overflow(typemax(T), T(1)) === (typemax(T), false) - @test mul_with_overflow(typemin(T), T(1)) === (typemin(T), false) - @test mul_with_overflow(sqrtmax, half_sqrtmax) === (typemin(T), true) - @test mul_with_overflow(sqrtmax, -half_sqrtmax) === (T(sqrtmax * -half_sqrtmax), false) - @test mul_with_overflow(sqrtmax, -half_sqrtmax_plus1) === (T(sqrtmax * -half_sqrtmax_plus1), true) - @test mul_with_overflow(-sqrtmax, half_sqrtmax) === (T(-sqrtmax * half_sqrtmax), false) - @test mul_with_overflow(-sqrtmax, half_sqrtmax_plus1) === (T(-sqrtmax * half_sqrtmax_plus1), true) - @test mul_with_overflow(-sqrtmax, -half_sqrtmax) === (T(-sqrtmax * -half_sqrtmax), true) - - @test checked_div(typemax(T), T(1)) === typemax(T) - @test_throws DivideError checked_div(typemax(T), T(0)) - @test checked_div(typemax(T), T(-1)) === T(-typemax(T)) - @test checked_div(typemin(T), T(1)) === typemin(T) - @test_throws DivideError checked_div(typemin(T), T(0)) - @test_throws DivideError checked_div(typemin(T), T(-1)) - @test checked_rem(typemax(T), T(1)) === T(0) - @test_throws DivideError checked_rem(typemax(T), T(0)) - @test checked_rem(typemax(T), T(-1)) === T(0) - @test checked_rem(typemin(T), T(1)) === T(0) - @test_throws DivideError checked_rem(typemin(T), T(0)) - @test checked_rem(typemin(T), T(-1)) === T(0) - @test checked_fld(typemax(T), T(1)) === typemax(T) - @test_throws DivideError checked_fld(typemax(T), T(0)) - @test checked_fld(typemax(T), T(-1)) === T(-typemax(T)) - @test checked_fld(typemin(T), T(1)) === typemin(T) - @test_throws DivideError checked_fld(typemin(T), T(0)) - @test_throws DivideError checked_fld(typemin(T), T(-1)) - @test checked_mod(typemax(T), T(1)) === T(0) - @test_throws DivideError checked_mod(typemax(T), T(0)) - @test checked_mod(typemax(T), T(-1)) === T(0) - @test checked_mod(typemin(T), T(1)) === T(0) - @test_throws DivideError checked_mod(typemin(T), T(0)) - @test checked_mod(typemin(T), T(-1)) === T(0) - @test_throws DivideError checked_cld(typemax(T), T(0)) - @test checked_cld(typemax(T), T(-1)) === T(-typemax(T)) - @test checked_cld(typemin(T), T(1)) === typemin(T) - @test_throws DivideError checked_cld(typemin(T), T(0)) - @test_throws DivideError checked_cld(typemin(T), T(-1)) -end - -for T in (UInt8, UInt16, UInt32, UInt64, UInt128) - # regular cases - @test checked_abs(T(0)) === T(0) - @test checked_neg(T(0)) === T(0) - @test checked_add(T(0)) === T(0) - @test checked_mul(T(0)) === T(0) - - @test checked_abs(T(3)) === T(3) - @test_throws OverflowError checked_neg(T(3)) - @test checked_add(T(3)) === T(3) - @test checked_mul(T(3)) === T(3) - - # regular cases - @test checked_add(T(4), T(3)) === T(7) - @test checked_sub(T(4), T(3)) === T(1) - @test checked_mul(T(4), T(3)) === T(12) - - # corner cases - halfmax = T(typemax(T)÷2) - halfmax_plus1 = T(halfmax+1) - sqrtmax = T(1) << T(sizeof(T)*4) - - @test checked_add(typemax(T), T(0)) === typemax(T) - @test checked_add(T(0), T(0)) === T(0) - @test_throws OverflowError checked_add(typemax(T), T(1)) - @test checked_add(T(0), T(1)) === T(T(0) + 1) - @test checked_add(T(0), typemax(T)) === typemax(T) - @test checked_add(T(0), T(0)) === T(0) - @test_throws OverflowError checked_add(T(1), typemax(T)) - @test checked_add(T(1), T(0)) === T(T(0) + 1) - @test checked_add(typemax(T), T(0)) === typemax(T) - @test checked_add(T(0), typemax(T)) === typemax(T) - @test_throws OverflowError checked_add(halfmax_plus1, halfmax_plus1) - - @test add_with_overflow(typemax(T), T(0)) === (typemax(T), false) - @test add_with_overflow(T(0), T(0)) === (T(0), false) - @test add_with_overflow(typemax(T), T(1)) === (T(0), true) - @test add_with_overflow(T(0), T(1)) === (T(T(0) + 1), false) - @test add_with_overflow(T(0), typemax(T)) === (typemax(T), false) - @test add_with_overflow(T(0), T(0)) === (T(0), false) - @test add_with_overflow(T(1), typemax(T)) === (T(0), true) - @test add_with_overflow(T(1), T(0)) === (T(T(0) + 1), false) - @test add_with_overflow(typemax(T), T(0)) === (typemax(T), false) - @test add_with_overflow(T(0), typemax(T)) === (typemax(T), false) - @test add_with_overflow(halfmax_plus1, halfmax_plus1) === (T(0), true) - - @test checked_sub(typemax(T), T(0)) === typemax(T) - @test checked_sub(typemax(T), T(1)) === T(typemax(T) - 1) - @test checked_sub(T(0), T(0)) === T(0) - @test_throws OverflowError checked_sub(T(0), T(1)) - @test_throws OverflowError checked_sub(T(0), typemax(T)) - @test_throws OverflowError checked_sub(T(1), typemax(T)) - @test checked_sub(T(0), T(0)) === T(0) - @test checked_sub(typemax(T), typemax(T)) === T(0) - - @test sub_with_overflow(typemax(T), T(0)) === (typemax(T), false) - @test sub_with_overflow(typemax(T), T(1)) === (T(typemax(T) - 1), false) - @test sub_with_overflow(T(0), T(0)) === (T(0), false) - @test sub_with_overflow(T(0), T(1)) === (typemax(T), true) - @test sub_with_overflow(T(0), typemax(T)) === (T(1), true) - @test sub_with_overflow(T(1), typemax(T)) === (T(2), true) - @test sub_with_overflow(T(0), T(0)) === (T(0), false) - @test sub_with_overflow(typemax(T), typemax(T)) === (T(0), false) - - @test checked_mul(typemax(T), T(0)) === T(0) - @test checked_mul(T(0), T(0)) === T(0) - @test checked_mul(typemax(T), T(1)) === typemax(T) - @test checked_mul(T(0), T(1)) === T(0) - @test_throws OverflowError checked_mul(sqrtmax, sqrtmax) - - @test mul_with_overflow(typemax(T), T(0)) === (T(0), false) - @test mul_with_overflow(T(0), T(0)) === (T(0), false) - @test mul_with_overflow(typemax(T), T(1)) === (typemax(T), false) - @test mul_with_overflow(T(0), T(1)) === (T(0), false) - @test mul_with_overflow(sqrtmax, sqrtmax) === (T(0), true) - - @test checked_div(typemax(T), T(1)) === typemax(T) - @test_throws DivideError checked_div(typemax(T), T(0)) - @test checked_rem(typemax(T), T(1)) === T(0) - @test_throws DivideError checked_rem(typemax(T), T(0)) - @test checked_fld(typemax(T), T(1)) === typemax(T) - @test_throws DivideError checked_fld(typemax(T), T(0)) - @test checked_mod(typemax(T), T(1)) === T(0) - @test_throws DivideError checked_mod(typemax(T), T(0)) - @test checked_cld(typemax(T), T(1)) === typemax(T) - @test_throws DivideError checked_cld(typemax(T), T(0)) -end - -# Boolean -@test checked_add(false) === 0 -@test checked_add(true) === 1 -@test checked_neg(false) === 0 -@test checked_neg(true) === -1 -@test checked_abs(true) === true -@test checked_abs(false) === false -@test checked_mul(false) === false -@test checked_mul(true) === true - -@test checked_add(true, true) === 2 -@test checked_add(true, false) === 1 -@test checked_add(false, false) === 0 -@test checked_add(false, true) === 1 - -@test checked_sub(true, true) === 0 -@test checked_sub(true, false) === 1 -@test checked_sub(false, false) === 0 -@test checked_sub(false, true) === -1 - -@test checked_mul(true, false) === false -@test checked_mul(false, false) === false -@test checked_mul(true, true) === true -@test checked_mul(false, true) === false - -@test checked_div(true, true) === true -@test checked_div(false, true) === false -@test_throws DivideError checked_div(true, false) -@test checked_rem(true, true) === false -@test checked_rem(false, true) === false -@test_throws DivideError checked_rem(true, false) -@test checked_fld(true, true) === true -@test checked_fld(false, true) === false -@test_throws DivideError checked_fld(true, false) -@test checked_mod(true, true) === false -@test checked_mod(false, true) === false -@test_throws DivideError checked_mod(true, false) -@test checked_cld(true, true) === true -@test checked_cld(false, true) === false -@test_throws DivideError checked_cld(true, false) - -# BigInt -@test checked_abs(BigInt(-1)) == BigInt(1) -@test checked_abs(BigInt(1)) == BigInt(1) -@test checked_neg(BigInt(-1)) == BigInt(1) -@test checked_neg(BigInt(1)) == BigInt(-1) - -# Additional tests - -@test checked_sub(UInt(4), UInt(3)) === UInt(1) -@test_throws OverflowError checked_sub(UInt(5), UInt(6)) -@test checked_mul(UInt(4), UInt(3)) === UInt(12) - -@test checked_sub(Int128(-1),Int128(-2)) === Int128(1) - -@test_throws OverflowError checked_mul(UInt32(2)^30, UInt32(2)^2) -@test_throws OverflowError checked_mul(UInt64(2)^62, UInt64(2)^2) - -@test checked_add(UInt128(1), UInt128(2)) === UInt128(3) -@test_throws OverflowError checked_add(UInt128(2)^127, UInt128(2)^127) - -@test checked_sub(UInt128(2), UInt128(1)) === UInt128(1) -@test_throws OverflowError checked_sub(UInt128(3), UInt128(4)) - -@test checked_mul(UInt128(3), UInt128(4)) === UInt128(12) -@test_throws OverflowError checked_mul(UInt128(2)^127, UInt128(2)) diff --git a/julia-0.6.3/share/julia/test/choosetests.jl b/julia-0.6.3/share/julia/test/choosetests.jl deleted file mode 100644 index b8a88c1..0000000 --- a/julia-0.6.3/share/julia/test/choosetests.jl +++ /dev/null @@ -1,175 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -@doc """ - -`tests, net_on = choosetests(choices)` selects a set of tests to be -run. `choices` should be a vector of test names; if empty or set to -`["all"]`, all tests are selected. - -This function also supports "test collections": specifically, "linalg" - refers to collections of tests in the correspondingly-named -directories. - -Upon return, `tests` is a vector of fully-expanded test names, and -`net_on` is true if networking is available (required for some tests). -""" -> -function choosetests(choices = []) - testnames = [ - "linalg", "subarray", "core", "inference", "worlds", - "keywordargs", "numbers", "subtype", - "printf", "char", "strings", "triplequote", "unicode", "intrinsics", - "dates", "dict", "hashing", "iobuffer", "staged", "offsetarray", - "arrayops", "tuple", "reduce", "reducedim", "random", "abstractarray", - "intfuncs", "simdloop", "vecelement", "blas", "sparse", - "bitarray", "copy", "math", "fastmath", "functional", "iterators", - "operators", "path", "ccall", "parse", "loading", "bigint", - "bigfloat", "sorting", "statistics", "spawn", "backtrace", - "file", "read", "mmap", "version", "resolve", - "pollfd", "mpfr", "broadcast", "complex", "socket", - "floatapprox", "datafmt", "reflection", "regex", "float16", - "combinatorics", "sysinfo", "env", "rounding", "ranges", "mod2pi", - "euler", "show", "lineedit", "replcompletions", "repl", - "replutil", "sets", "test", "goto", "llvmcall", "llvmcall2", "grisu", - "nullable", "meta", "stacktraces", "profile", "libgit2", "docs", - "markdown", "base64", "serialize", "misc", "threads", - "enums", "cmdlineargs", "i18n", "workspace", "libdl", "int", - "checked", "intset", "floatfuncs", "compile", "distributed", "inline", - "boundscheck", "error", "ambiguous", "cartesian", "asmvariant", "osutils", - "channels", "iostream", "specificity" - ] - profile_skipped = false - if startswith(string(Sys.ARCH), "arm") - # Remove profile from default tests on ARM since it currently segfaults - # Allow explicitly adding it for testing - filter!(x -> (x != "profile"), testnames) - profile_skipped = true - end - - if Base.USE_GPL_LIBS - append!(testnames, ["fft", "dsp"]) - end - - if isdir(joinpath(JULIA_HOME, Base.DOCDIR, "examples")) - push!(testnames, "examples") - end - - tests = [] - skip_tests = [] - - for (i, t) in enumerate(choices) - if t == "--skip" - skip_tests = choices[i + 1:end] - break - else - push!(tests, t) - end - end - - if tests == ["all"] || isempty(tests) - tests = testnames - if profile_skipped - warn("profile test skipped") - end - end - - datestests = ["dates/accessors", "dates/adjusters", "dates/query", - "dates/periods", "dates/ranges", "dates/rounding", "dates/types", - "dates/io", "dates/arithmetic", "dates/conversions"] - if "dates" in skip_tests - filter!(x -> (x != "dates" && !(x in datestests)), tests) - elseif "dates" in tests - # specifically selected case - filter!(x -> x != "dates", tests) - prepend!(tests, datestests) - end - - unicodetests = ["unicode/UnicodeError", "unicode/utf8proc", "unicode/utf8"] - if "unicode" in skip_tests - filter!(x -> (x != "unicode" && !(x in unicodetests)), tests) - elseif "unicode" in tests - # specifically selected case - filter!(x -> x != "unicode", tests) - prepend!(tests, unicodetests) - end - - stringtests = ["strings/basic", "strings/search", "strings/util", - "strings/io", "strings/types"] - if "strings" in skip_tests - filter!(x -> (x != "strings" && !(x in stringtests)), tests) - elseif "strings" in tests - # specifically selected case - filter!(x -> x != "strings", tests) - prepend!(tests, stringtests) - end - - - sparsetests = ["sparse/sparse", "sparse/sparsevector", "sparse/higherorderfns"] - if Base.USE_GPL_LIBS - append!(sparsetests, ["sparse/umfpack", "sparse/cholmod", "sparse/spqr"]) - end - if "sparse" in skip_tests - filter!(x -> (x != "sparse" && !(x in sparsetests)), tests) - elseif "sparse" in tests - # specifically selected case - filter!(x -> x != "sparse", tests) - prepend!(tests, sparsetests) - end - - # do subarray before sparse but after linalg - if "subarray" in skip_tests - filter!(x -> x != "subarray", tests) - elseif "subarray" in tests - filter!(x -> x != "subarray", tests) - prepend!(tests, ["subarray"]) - end - - linalgtests = ["linalg/triangular", "linalg/qr", "linalg/dense", - "linalg/matmul", "linalg/schur", "linalg/special", - "linalg/eigen", "linalg/bunchkaufman", "linalg/svd", - "linalg/lapack", "linalg/tridiag", "linalg/bidiag", - "linalg/diagonal", "linalg/pinv", "linalg/givens", - "linalg/cholesky", "linalg/lu", "linalg/symmetric", - "linalg/generic", "linalg/uniformscaling", "linalg/lq", - "linalg/hessenberg", "linalg/rowvector", "linalg/conjarray"] - if Base.USE_GPL_LIBS - push!(linalgtests, "linalg/arnoldi") - end - - if "linalg" in skip_tests - filter!(x -> (x != "linalg" && !(x in linalgtests)), tests) - elseif "linalg" in tests - # specifically selected case - filter!(x -> x != "linalg", tests) - prepend!(tests, linalgtests) - end - - # do ambiguous first to avoid failing if ambiguities are introduced by other tests - if "ambiguous" in skip_tests - filter!(x -> x != "ambiguous", tests) - elseif "ambiguous" in tests - filter!(x -> x != "ambiguous", tests) - prepend!(tests, ["ambiguous"]) - end - - net_required_for = ["socket", "distributed", "libgit2"] - net_on = true - try - ipa = getipaddr() - catch - warn("Networking unavailable: Skipping tests [" * join(net_required_for, ", ") * "]") - net_on = false - end - - if ccall(:jl_running_on_valgrind,Cint,()) != 0 && "rounding" in tests - warn("Running under valgrind: Skipping rounding tests") - filter!(x -> x != "rounding", tests) - end - - if !net_on - filter!(x -> !(x in net_required_for), tests) - end - - filter!(x -> !(x in skip_tests), tests) - - tests, net_on -end diff --git a/julia-0.6.3/share/julia/test/cmdlineargs.jl b/julia-0.6.3/share/julia/test/cmdlineargs.jl deleted file mode 100644 index f5ca5f9..0000000 --- a/julia-0.6.3/share/julia/test/cmdlineargs.jl +++ /dev/null @@ -1,416 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -catcmd = `cat` -if is_windows() - try # use busybox-w32 on windows - success(`busybox`) - catcmd = `busybox cat` - end -end - -let exename = `$(Base.julia_cmd()) --precompiled=yes --startup-file=no` - # --version - let v = split(readstring(`$exename -v`), "julia version ")[end] - @test Base.VERSION_STRING == chomp(v) - end - @test readstring(`$exename -v`) == readstring(`$exename --version`) - - # --help - let header = "julia [switches] -- [programfile] [args...]" - @test startswith(readstring(`$exename -h`), header) - @test startswith(readstring(`$exename --help`), header) - end - - # --quiet - # This flag is indirectly tested in test/repl.jl - - # --home - @test success(`$exename -H $JULIA_HOME`) - @test success(`$exename --home=$JULIA_HOME`) - - # --eval - @test success(`$exename -e "exit(0)"`) - @test !success(`$exename -e "exit(1)"`) - @test success(`$exename --eval="exit(0)"`) - @test !success(`$exename --eval="exit(1)"`) - @test !success(`$exename -e`) - @test !success(`$exename --eval`) - # --eval --interactive (replaced --post-boot) - @test success(`$exename -i -e "exit(0)"`) - @test !success(`$exename -i -e "exit(1)"`) - - # --print - @test readstring(`$exename -E "1+1"`) == "2\n" - @test readstring(`$exename --print="1+1"`) == "2\n" - @test !success(`$exename -E`) - @test !success(`$exename --print`) - - # --load - let testfile = tempname() - try - write(testfile, "testvar = :test\n") - @test split(readchomp(`$exename -i --load=$testfile -e "println(testvar)"`), - '\n')[end] == "test" - @test split(readchomp(`$exename -i -e "println(testvar)" -L $testfile`), - '\n')[end] == "test" - finally - rm(testfile) - end - end - # -L, --load requires an argument - @test !success(`$exename -L`) - @test !success(`$exename --load`) - - # --cpu-target - # NOTE: this test only holds true if image_file is a shared library. - if Libdl.dlopen_e(unsafe_string(Base.JLOptions().image_file)) != C_NULL - @test !success(`$exename -C invalidtarget --precompiled=yes`) - @test !success(`$exename --cpu-target=invalidtarget --precompiled=yes`) - else - warn("--cpu-target test not runnable") - end - - # --procs - @test readchomp(`$exename -q -p 2 -e "println(nworkers())"`) == "2" - @test !success(`$exename -p 0`) - @test !success(`$exename --procs=1.0`) - - # --machinefile - # this does not check that machinefile works, - # only that the filename gets correctly passed to the option struct - let fname = tempname() - touch(fname) - fname = realpath(fname) - try - @test readchomp(`$exename --machinefile $fname -e - "println(unsafe_string(Base.JLOptions().machinefile))"`) == fname - finally - rm(fname) - end - end - - # -i, isinteractive - @test readchomp(`$exename -E "isinteractive()"`) == "false" - @test readchomp(`$exename -E "isinteractive()" -i`) == "true" - - # --color - @test readchomp(`$exename --color=yes -E "Base.have_color"`) == "true" - @test readchomp(`$exename --color=no -E "Base.have_color"`) == "false" - @test !success(`$exename --color=false`) - - # --history-file - @test readchomp(`$exename -E "Bool(Base.JLOptions().historyfile)" - --history-file=yes`) == "true" - @test readchomp(`$exename -E "Bool(Base.JLOptions().historyfile)" - --history-file=no`) == "false" - @test !success(`$exename --history-file=false`) - - # --code-coverage - @test readchomp(`$exename -E "Bool(Base.JLOptions().code_coverage)"`) == "false" - @test readchomp(`$exename -E "Bool(Base.JLOptions().code_coverage)" - --code-coverage=none`) == "false" - - @test readchomp(`$exename -E "Bool(Base.JLOptions().code_coverage)" - --code-coverage`) == "true" - @test readchomp(`$exename -E "Bool(Base.JLOptions().code_coverage)" - --code-coverage=user`) == "true" - - # --track-allocation - @test readchomp(`$exename -E "Bool(Base.JLOptions().malloc_log)"`) == "false" - @test readchomp(`$exename -E "Bool(Base.JLOptions().malloc_log)" - --track-allocation=none`) == "false" - - @test readchomp(`$exename -E "Bool(Base.JLOptions().malloc_log)" - --track-allocation`) == "true" - @test readchomp(`$exename -E "Bool(Base.JLOptions().malloc_log)" - --track-allocation=user`) == "true" - - # --optimize - @test readchomp(`$exename -E "Base.JLOptions().opt_level"`) == "2" - @test readchomp(`$exename -E "Base.JLOptions().opt_level" -O`) == "3" - @test readchomp(`$exename -E "Base.JLOptions().opt_level" --optimize`) == "3" - @test readchomp(`$exename -E "Base.JLOptions().opt_level" -O0`) == "0" - - # -g - @test readchomp(`$exename -E "Base.JLOptions().debug_level" -g`) == "2" - let code = readstring(`$exename -g0 -e "code_llvm(STDOUT, +, (Int64, Int64), false, true)"`) - @test contains(code, "llvm.module.flags") - @test !contains(code, "llvm.dbg.cu") - @test !contains(code, "int.jl") - @test !contains(code, "Int64") - end - let code = readstring(`$exename -g1 -e "code_llvm(STDOUT, +, (Int64, Int64), false, true)"`) - @test contains(code, "llvm.module.flags") - @test contains(code, "llvm.dbg.cu") - @test contains(code, "int.jl") - @test !contains(code, "Int64") - end - let code = readstring(`$exename -g2 -e "code_llvm(STDOUT, +, (Int64, Int64), false, true)"`) - @test contains(code, "llvm.module.flags") - @test contains(code, "llvm.dbg.cu") - @test contains(code, "int.jl") - @test contains(code, "\"Int64\"") - end - - # --check-bounds - let JL_OPTIONS_CHECK_BOUNDS_DEFAULT = 0, - JL_OPTIONS_CHECK_BOUNDS_ON = 1, - JL_OPTIONS_CHECK_BOUNDS_OFF = 2 - @test parse(Int,readchomp(`$exename -E "Int(Base.JLOptions().check_bounds)"`)) == - JL_OPTIONS_CHECK_BOUNDS_DEFAULT - @test parse(Int,readchomp(`$exename -E "Int(Base.JLOptions().check_bounds)" - --check-bounds=yes`)) == JL_OPTIONS_CHECK_BOUNDS_ON - @test parse(Int,readchomp(`$exename -E "Int(Base.JLOptions().check_bounds)" - --check-bounds=no`)) == JL_OPTIONS_CHECK_BOUNDS_OFF - end - # check-bounds takes yes/no as argument - @test !success(`$exename -E "exit(0)" --check-bounds=false`) - - # --depwarn - @test readchomp(`$exename --depwarn=no -E - "Base.syntax_deprecation_warnings(true)"`) == "false" - @test readchomp(`$exename --depwarn=yes -E - "Base.syntax_deprecation_warnings(false)"`) == "true" - @test !success(`$exename --depwarn=false`) - # test deprecated syntax - @test !success(`$exename -e "foo (x::Int) = x * x" --depwarn=error`) - # test deprecated method - @test !success(`$exename -e " - foo() = :foo; bar() = :bar - @deprecate foo() bar() - foo() - " --depwarn=error`) - - # test deprecated bindings, #13269 - let code = """ - module Foo - import Base: @deprecate_binding - - const NotDeprecated = true - @deprecate_binding Deprecated NotDeprecated - end - - Foo.Deprecated - """ - - @test !success(`$exename -E "$code" --depwarn=error`) - - let out = Pipe(), - proc = spawn(pipeline(`$exename -E "$code" --depwarn=yes`, stderr=out)), - output = @async readchomp(out) - - close(out.in) - wait(proc) - @test success(proc) - @test wait(output) == "WARNING: Foo.Deprecated is deprecated.\n likely near no file:5" - end - - let out = Pipe(), - proc = spawn(pipeline(`$exename -E "$code" --depwarn=no`, stderr=out)) - output = @async readstring(out) - - wait(proc) - close(out.in) - @test success(proc) - @test wait(output) == "" - end - end - - # --inline - @test readchomp(`$exename -E "Bool(Base.JLOptions().can_inline)"`) == "true" - @test readchomp(`$exename --inline=yes -E "Bool(Base.JLOptions().can_inline)"`) == "true" - @test readchomp(`$exename --inline=no -E "Bool(Base.JLOptions().can_inline)"`) == "false" - # --inline takes yes/no as argument - @test !success(`$exename --inline=false`) - - # --polly - @test readchomp(`$exename -E "Bool(Base.JLOptions().polly)"`) == "true" - @test readchomp(`$exename --polly=yes -E "Bool(Base.JLOptions().polly)"`) == "true" - @test readchomp(`$exename --polly=no -E "Bool(Base.JLOptions().polly)"`) == "false" - # --polly takes yes/no as argument - @test !success(`$exename --polly=false`) - - # --fast-math - let JL_OPTIONS_FAST_MATH_DEFAULT = 0, - JL_OPTIONS_FAST_MATH_ON = 1, - JL_OPTIONS_FAST_MATH_OFF = 2 - @test parse(Int,readchomp(`$exename -E - "Int(Base.JLOptions().fast_math)"`)) == JL_OPTIONS_FAST_MATH_DEFAULT - @test parse(Int,readchomp(`$exename --math-mode=user -E - "Int(Base.JLOptions().fast_math)"`)) == JL_OPTIONS_FAST_MATH_DEFAULT - @test parse(Int,readchomp(`$exename --math-mode=ieee -E - "Int(Base.JLOptions().fast_math)"`)) == JL_OPTIONS_FAST_MATH_OFF - @test parse(Int,readchomp(`$exename --math-mode=fast -E - "Int(Base.JLOptions().fast_math)"`)) == JL_OPTIONS_FAST_MATH_ON - end - - # --worker takes default / custom as argument (default/custom arguments - # tested in test/parallel.jl, test/examples.jl) - @test !success(`$exename --worker=true`) - - escape(str) = replace(str, "\\", "\\\\") - - # test passing arguments - let testfile = tempname() - try - # write a julia source file that just prints ARGS to STDOUT - write(testfile, """ - println(ARGS) - """) - @test readchomp(`$exename $testfile foo -bar --baz`) == - "String[\"foo\", \"-bar\", \"--baz\"]" - @test readchomp(`$exename $testfile -- foo -bar --baz`) == - "String[\"foo\", \"-bar\", \"--baz\"]" - @test readchomp(`$exename -L $testfile -e 'exit(0)' -- foo -bar --baz`) == - "String[\"foo\", \"-bar\", \"--baz\"]" - @test split(readchomp(`$exename -L $testfile $testfile`), '\n') == - ["String[\"$(escape(testfile))\"]", "String[]"] - @test !success(`$exename --foo $testfile`) - @test readchomp(`$exename -L $testfile -e 'exit(0)' -- foo -bar -- baz`) == "String[\"foo\", \"-bar\", \"--\", \"baz\"]" - finally - rm(testfile) - end - end - - # test the script name - let a = tempname(), b = tempname() - try - write(a, """ - println(@__FILE__) - println(PROGRAM_FILE) - println(length(ARGS)) - include(\"$(escape(b))\") - """) - write(b, """ - println(@__FILE__) - println(PROGRAM_FILE) - println(length(ARGS)) - """) - @test split(readchomp(`$exename $a`), '\n') == - ["$a", "$a", "0", "$b", "$a", "0"] - @test split(readchomp(`$exename -L $b -e 'exit(0)'`), '\n') == - ["$(realpath(b))", "", "0"] - @test split(readchomp(`$exename -L $b $a`), '\n') == - ["$(realpath(b))", "", "1", "$a", "$a", "0", "$b", "$a", "0"] - finally - rm(a) - rm(b) - end - end - - # issue #10562 - @test readchomp(`$exename -e 'println(ARGS);' ''`) == "String[\"\"]" - - # issue #12679 - @test readchomp(pipeline(ignorestatus(`$exename --startup-file=no --compile=yes -ioo`), - stderr=catcmd)) == "ERROR: unknown option `-o`" - @test readchomp(pipeline(ignorestatus(`$exename --startup-file=no -p`), - stderr=catcmd)) == "ERROR: option `-p/--procs` is missing an argument" - @test readchomp(pipeline(ignorestatus(`$exename --startup-file=no --inline`), - stderr=catcmd)) == "ERROR: option `--inline` is missing an argument" - @test readchomp(pipeline(ignorestatus(`$exename --startup-file=no -e "@show ARGS" -now -- julia RUN.jl`), - stderr=catcmd)) == "ERROR: unknown option `-n`" - - # --compilecache={yes|no} - @test readchomp(`$exename -E "Bool(Base.JLOptions().use_compilecache)"`) == "true" - @test readchomp(`$exename --compilecache=yes -E - "Bool(Base.JLOptions().use_compilecache)"`) == "true" - @test readchomp(`$exename --compilecache=no -E - "Bool(Base.JLOptions().use_compilecache)"`) == "false" - @test !success(`$exename --compilecache=foo -e "exit(0)"`) - - # issue #12671, starting from a non-directory - # rm(dir) fails on windows with Permission denied - # and was an upstream bug in llvm <= v3.3 - if !is_windows() && VersionNumber(Base.libllvm_version) > v"3.3" - testdir = mktempdir() - cd(testdir) do - rm(testdir) - @test success(`$exename -e "exit(0)"`) - end - end -end - - -# Find the path of libjulia (or libjulia-debug, as the case may be) -# to use as a dummy shlib to open -libjulia = abspath(Libdl.dlpath((ccall(:jl_is_debugbuild, Cint, ()) != 0) ? "libjulia-debug" : "libjulia")) - -# test error handling code paths of running --sysimage -let exename = joinpath(JULIA_HOME, Base.julia_exename()), - sysname = unsafe_string(Base.JLOptions().image_file) - for nonexist_image in ( - joinpath(@__DIR__, "nonexistent"), - "$sysname.nonexistent", - ) - let stderr = Pipe(), - p = spawn(pipeline(`$exename --sysimage=$nonexist_image`, stderr=stderr)) - close(stderr.in) - let s = readstring(stderr) - @test contains(s, "ERROR: could not load library \"$nonexist_image\"\n") - @test !contains(s, "Segmentation fault") - @test !contains(s, "EXCEPTION_ACCESS_VIOLATION") - end - @test !success(p) - @test !Base.process_signaled(p) - @test p.exitcode == 1 - end - end - let stderr = Pipe(), - p = spawn(pipeline(`$exename --sysimage=$libjulia`, stderr=stderr)) - close(stderr.in) - let s = readstring(stderr) - @test s == "ERROR: System image file failed consistency check: maybe opened the wrong version?\n" - end - @test !success(p) - @test !Base.process_signaled(p) - @test p.exitcode == 1 - end -end - -let exename = `$(Base.julia_cmd()) --precompiled=yes` - # --startup-file - let JL_OPTIONS_STARTUPFILE_ON = 1, - JL_OPTIONS_STARTUPFILE_OFF = 2 - # `HOME=$tmpdir` to avoid errors in the user .juliarc.jl, which hangs the tests. Issue #17642 - mktempdir() do tmpdir - withenv("HOME"=>tmpdir) do - @test parse(Int,readchomp(`$exename -E "Base.JLOptions().startupfile" --startup-file=yes`)) == JL_OPTIONS_STARTUPFILE_ON - end - end - @test parse(Int,readchomp(`$exename -E "Base.JLOptions().startupfile" - --startup-file=no`)) == JL_OPTIONS_STARTUPFILE_OFF - end - @test !success(`$exename --startup-file=false`) -end - -# Make sure `julia --lisp` doesn't break -run(pipeline(DevNull, `$(joinpath(JULIA_HOME, Base.julia_exename())) --lisp`, DevNull)) - -# Test that `julia [some other option] --lisp` is disallowed -@test_throws ErrorException run(pipeline(DevNull, pipeline(`$(joinpath(JULIA_HOME, - Base.julia_exename())) -Cnative --lisp`, stderr=DevNull), DevNull)) - -# --precompiled={yes|no} -let exename = `$(Base.julia_cmd()) --startup-file=no` - @test readchomp(`$exename --precompiled=yes -E - "Bool(Base.JLOptions().use_precompiled)"`) == "true" - @test readchomp(`$exename --precompiled=no -E - "Bool(Base.JLOptions().use_precompiled)"`) == "false" -end - -# backtrace contains type and line number info (esp. on windows #17179) -for precomp in ("yes", "no") - bt = readstring(pipeline(ignorestatus(`$(Base.julia_cmd()) --startup-file=no --precompiled=$precomp - -E 'include("____nonexistent_file")'`), stderr=catcmd)) - @test contains(bt, "include_from_node1") - if ((is_windows() && Sys.WORD_SIZE == 32) || (is_bsd() && !is_apple())) && precomp == "yes" - # FIXME: Issue #17251 (Windows), #20798 (FreeBSD) - @test_broken contains(bt, "include_from_node1(::String) at $(joinpath(".","loading.jl"))") - else - @test contains(bt, "include_from_node1(::String) at $(joinpath(".","loading.jl"))") - end - lno = match(r"at \.[\/\\]loading\.jl:(\d+)", bt) - @test length(lno.captures) == 1 - @test parse(Int, lno.captures[1]) > 0 -end diff --git a/julia-0.6.3/share/julia/test/codegen.jl b/julia-0.6.3/share/julia/test/codegen.jl deleted file mode 100644 index a500987..0000000 --- a/julia-0.6.3/share/julia/test/codegen.jl +++ /dev/null @@ -1,250 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -# tests for codegen and optimizations - -const opt_level = Base.JLOptions().opt_level -const coverage = (Base.JLOptions().code_coverage > 0) || (Base.JLOptions().malloc_log > 0) -const Iptr = sizeof(Int) == 8 ? "i64" : "i32" - -# `_dump_function` might be more efficient but it doesn't really matter here... -get_llvm(@nospecialize(f), @nospecialize(t), strip_ir_metadata=true, dump_module=false) = - sprint(code_llvm, f, t, strip_ir_metadata, dump_module) - -if opt_level > 0 - # Make sure getptls call is removed at IR level with optimization on - @test !contains(get_llvm(identity, Tuple{String}), " call ") -end - -jl_string_ptr(s::String) = ccall(:jl_string_ptr, Ptr{UInt8}, (Any,), s) -core_sizeof(o) = Core.sizeof(o) -function test_loads_no_call(ir, load_types) - in_function = false - load_idx = 1 - for line in eachline(IOBuffer(ir)) - if !in_function - if startswith(line, "define ") - in_function = true - end - continue - end - @test !contains(line, " call ") - load_split = split(line, " load ", limit=2) - if !coverage && length(load_split) >= 2 - @test load_idx <= length(load_types) - if load_idx <= length(load_types) - @test startswith(load_split[2], "$(load_types[load_idx]),") - end - load_idx += 1 - end - if startswith(line, "}") - break - end - end - if !coverage - @test load_idx == length(load_types) + 1 - end -end - -# This function tests if functions are output when compiled if jl_dump_compiles is enabled. -# Have to go through pains with recursive function (eval probably not required) to make sure -# that inlining won't happen. -function test_jl_dump_compiles() - tfile = tempname() - io = open(tfile, "w") - ccall(:jl_dump_compiles, Void, (Ptr{Void},), io.handle) - eval(@noinline function test_jl_dump_compiles_internal(x) - if x > 0 - test_jl_dump_compiles_internal(x-1) - end - end) - test_jl_dump_compiles_internal(1) - ccall(:jl_dump_compiles, Void, (Ptr{Void},), C_NULL) - close(io) - tstats = stat(tfile) - tempty = tstats.size == 0 - rm(tfile) - @test tempty == false -end - -# This function tests if a toplevel thunk is output if jl_dump_compiles is enabled. -# The eval statement creates the toplevel thunk. -function test_jl_dump_compiles_toplevel_thunks() - tfile = tempname() - io = open(tfile, "w") - ccall(:jl_dump_compiles, Void, (Ptr{Void},), io.handle) - eval(expand(Main, :(for i in 1:10 end))) - ccall(:jl_dump_compiles, Void, (Ptr{Void},), C_NULL) - close(io) - tstats = stat(tfile) - tempty = tstats.size == 0 - rm(tfile) - @test tempty == true -end - -if opt_level > 0 - # Make sure `jl_string_ptr` is inlined - @test !contains(get_llvm(jl_string_ptr, Tuple{String}), " call ") - s = "aaa" - @test jl_string_ptr(s) == pointer_from_objref(s) + sizeof(Int) - # String - test_loads_no_call(get_llvm(core_sizeof, Tuple{String}), [Iptr]) - # String - test_loads_no_call(get_llvm(core_sizeof, Tuple{SimpleVector}), [Iptr]) - # Array - test_loads_no_call(get_llvm(core_sizeof, Tuple{Vector{Int}}), [Iptr]) - # As long as the eltype is known we don't need to load the elsize - test_loads_no_call(get_llvm(core_sizeof, Tuple{Array{Any}}), [Iptr]) - # Check that we load the elsize - test_loads_no_call(get_llvm(core_sizeof, Tuple{Vector}), [Iptr, "i16"]) - - test_jl_dump_compiles() - test_jl_dump_compiles_toplevel_thunks() -end - -# Make sure we will not elide the allocation -@noinline create_ref1() = Ref(1) -function pointer_not_safepoint() - a = create_ref1() - unsafe_store!(Ptr{Int}(pointer_from_objref(a)), 3) - return a[] -end -@test pointer_not_safepoint() == 3 - -# The current memcmp threshold is 512bytes, make sure this struct has the same size on -# 32bits and 64bits -struct LargeStruct - x::NTuple{1024,Int8} - LargeStruct() = new() -end - -const large_struct = LargeStruct() -@noinline create_ref_struct() = Ref(large_struct) -function compare_large_struct(a) - b = create_ref_struct() - if a[] === b[] - b[].x[1] - else - a[].x[2] - end -end - -mutable struct MutableStruct - a::Int - MutableStruct() = new() -end - -breakpoint_mutable(a::MutableStruct) = ccall(:jl_breakpoint, Void, (Ref{MutableStruct},), a) - -# Allocation with uninitialized field as gcroot -mutable struct BadRef - x::MutableStruct - y::MutableStruct - BadRef(x) = new(x) -end -Base.cconvert(::Type{Ptr{BadRef}}, a::MutableStruct) = BadRef(a) -Base.unsafe_convert(::Type{Ptr{BadRef}}, ar::BadRef) = Ptr{BadRef}(pointer_from_objref(ar.x)) - -breakpoint_badref(a::MutableStruct) = ccall(:jl_breakpoint, Void, (Ptr{BadRef},), a) - -struct PtrStruct - a::Ptr{Void} - b::Int -end - -mutable struct RealStruct - a::Float64 - b::Int -end - -function Base.cconvert(::Type{Ref{PtrStruct}}, a::RealStruct) - (a, Ref(PtrStruct(pointer_from_objref(a), a.b))) -end -Base.unsafe_convert(::Type{Ref{PtrStruct}}, at::Tuple) = - Base.unsafe_convert(Ref{PtrStruct}, at[2]) - -breakpoint_ptrstruct(a::RealStruct) = - ccall(:jl_breakpoint, Void, (Ref{PtrStruct},), a) - -if opt_level > 0 - @test !contains(get_llvm(isequal, Tuple{Nullable{BigFloat}, Nullable{BigFloat}}), "%gcframe") - @test !contains(get_llvm(pointer_not_safepoint, Tuple{}), "%gcframe") - compare_large_struct_ir = get_llvm(compare_large_struct, Tuple{typeof(create_ref_struct())}) - @test contains(compare_large_struct_ir, "call i32 @memcmp") - @test !contains(compare_large_struct_ir, "%gcframe") - - @test contains(get_llvm(MutableStruct, Tuple{}), "jl_gc_pool_alloc") - breakpoint_mutable_ir = get_llvm(breakpoint_mutable, Tuple{MutableStruct}) - @test !contains(breakpoint_mutable_ir, "%gcframe") - @test !contains(breakpoint_mutable_ir, "jl_gc_pool_alloc") - - breakpoint_badref_ir = get_llvm(breakpoint_badref, Tuple{MutableStruct}) - @test !contains(breakpoint_badref_ir, "%gcframe") - @test !contains(breakpoint_badref_ir, "jl_gc_pool_alloc") - - breakpoint_ptrstruct_ir = get_llvm(breakpoint_ptrstruct, Tuple{RealStruct}) - @test !contains(breakpoint_ptrstruct_ir, "%gcframe") - @test !contains(breakpoint_ptrstruct_ir, "jl_gc_pool_alloc") -end - -function two_breakpoint(a::Float64) - ccall(:jl_breakpoint, Void, (Ref{Float64},), a) - ccall(:jl_breakpoint, Void, (Ref{Float64},), a) -end - -if opt_level > 0 - breakpoint_f64_ir = get_llvm((a)->ccall(:jl_breakpoint, Void, (Ref{Float64},), a), - Tuple{Float64}) - @test !contains(breakpoint_f64_ir, "jl_gc_pool_alloc") - breakpoint_any_ir = get_llvm((a)->ccall(:jl_breakpoint, Void, (Ref{Any},), a), - Tuple{Float64}) - @test contains(breakpoint_any_ir, "jl_gc_pool_alloc") - two_breakpoint_ir = get_llvm(two_breakpoint, Tuple{Float64}) - @test !contains(two_breakpoint_ir, "jl_gc_pool_alloc") - @test contains(two_breakpoint_ir, "llvm.lifetime.end") -end - -# Issue 22770 -let was_gced = false - @noinline make_tuple(x) = tuple(x) - @noinline use(x) = ccall(:jl_breakpoint, Void, ()) - @noinline assert_not_gced() = @test !was_gced - - function foo22770() - b = Ref(2) - finalizer(b, x -> was_gced = true) - y = make_tuple(b) - x = y[1] - a = Ref(1) - use(x); use(a); use(y) - c = Ref(3) - gc() - assert_not_gced() - use(x) - use(c) - end - foo22770() - gc() - @test was_gced -end - -function egal_svecs() - a = Core.svec(:a, :b) - b = Core.svec(:a, :b) - a === b -end -@test egal_svecs() -@test Core.svec(:a, :b) === Core.svec(:a, :b) - -# issue #22582 -function issue22582!(a::AbstractArray, b) - len = length(a) - if b - ccall(:jl_array_grow_end, Void, (Any, Csize_t), a, 1) - end - return len -end -let c = [1,2,3] - len1 = length(c) - len2 = issue22582!(c, true) - @test len1 == len2 -end diff --git a/julia-0.6.3/share/julia/test/combinatorics.jl b/julia-0.6.3/share/julia/test/combinatorics.jl deleted file mode 100644 index 95fc8c5..0000000 --- a/julia-0.6.3/share/julia/test/combinatorics.jl +++ /dev/null @@ -1,70 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -@testset "binomial" begin - @test binomial(5,-1) == 0 - @test binomial(5,10) == 0 - @test binomial(5,3) == 10 - @test binomial(2,1) == 2 - @test binomial(1,2) == 0 - @test binomial(-2,1) == -2 # let's agree - @test binomial(2,-1) == 0 - - #Issue 6154 - @test binomial(Int32(34), Int32(15)) == binomial(BigInt(34), BigInt(15)) == 1855967520 - @test binomial(Int64(67), Int64(29)) == binomial(BigInt(67), BigInt(29)) == 7886597962249166160 - @test binomial(Int128(131), Int128(62)) == binomial(BigInt(131), BigInt(62)) == 157311720980559117816198361912717812000 - @test_throws InexactError binomial(Int64(67), Int64(30)) -end - -@testset "permutations" begin - p = shuffle([1:1000;]) - @test isperm(p) - @test all(invperm(invperm(p)) .== p) - @test isperm(()) == true - @test isperm((1,)) == true - @test isperm((2,)) == false - @test isperm((1,2)) == true - @test isperm((2,1)) == true - @test isperm((2,2)) == false - @test isperm((1,3)) == false - @test invperm(()) == () - @test invperm((1,)) == (1,) - @test invperm((1,2)) == (1,2) - @test invperm((2,1)) == (2,1) - @test_throws ArgumentError invperm((1,3)) - - push!(p, 1) - @test !isperm(p) - - a = randcycle(10) - @test ipermute!(permute!([1:10;], a),a) == [1:10;] - - # PR 12785 - let a = 2:-1:1 - @test ipermute!(permute!([1, 2], a), a) == [1, 2] - end -end - -@testset "factorial" begin - @test factorial(7) == 5040 - @test factorial(Int8(7)) == 5040 - @test factorial(UInt8(7)) == 5040 - @test factorial(Int16(7)) == 5040 - @test factorial(UInt16(7)) == 5040 - @test factorial(Int32(7)) == 5040 - @test factorial(UInt32(7)) == 5040 - @test factorial(Int64(7)) == 5040 - @test factorial(UInt64(7)) == 5040 - @test factorial(Int128(7)) == 5040 - @test factorial(UInt128(7)) == 5040 - @test factorial(0) == 1 - @test_throws DomainError factorial(-1) - @test factorial(Int64(20)) == 2432902008176640000 - # issue #6579 - @test_throws OverflowError factorial(Int64(21)) - @test typeof(factorial(Int8(2))) == typeof(factorial(Int8(1))) - if Int === Int32 - @test factorial(Int32(12)) === Int32(479001600) - @test_throws OverflowError factorial(Int32(13)) - end -end diff --git a/julia-0.6.3/share/julia/test/compile.jl b/julia-0.6.3/share/julia/test/compile.jl deleted file mode 100644 index 25715e1..0000000 --- a/julia-0.6.3/share/julia/test/compile.jl +++ /dev/null @@ -1,592 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -using Base.Test - -Foo_module = :Foo4b3a94a1a081a8cb -Foo2_module = :F2oo4b3a94a1a081a8cb -FooBase_module = :FooBase4b3a94a1a081a8cb -@eval module ConflictingBindings - export $Foo_module, $FooBase_module - $Foo_module = 232 - $FooBase_module = 9134 -end -using .ConflictingBindings - -# this environment variable would affect some error messages being tested below -# so we disable it for the tests below -withenv( "JULIA_DEBUG_LOADING" => nothing ) do - -dir = mktempdir() -dir2 = mktempdir() -insert!(LOAD_PATH, 1, dir) -insert!(Base.LOAD_CACHE_PATH, 1, dir) -try - Foo_file = joinpath(dir, "$Foo_module.jl") - Foo2_file = joinpath(dir, "$Foo2_module.jl") - FooBase_file = joinpath(dir, "$FooBase_module.jl") - - write(FooBase_file, - """ - __precompile__(true) - - module $FooBase_module - import Base: hash, > - struct fmpz end - struct typeA end - >(x::fmpz, y::Int) = Base.cmp(x, y) > 0 - function hash(a::typeA, h::UInt) - d = den(a) - return h - end - end - """) - write(Foo2_file, - """ - __precompile__(true) - - module $Foo2_module - export override - override(x::Integer) = 2 - override(x::AbstractFloat) = Float64(override(1)) - end - """) - write(Foo_file, - """ - __precompile__(true) - - module $Foo_module - using $FooBase_module, $FooBase_module.typeA - import $Foo2_module: $Foo2_module, override - import $FooBase_module.hash - - struct typeB - y::typeA - end - hash(x::typeB) = hash(x.y) - - # test that docs get reconnected - @doc "foo function" foo(x) = x + 1 - include_dependency("foo.jl") - include_dependency("foo.jl") - module Bar - @doc "bar function" bar(x) = x + 2 - include_dependency("bar.jl") - end - - # test for creation of some reasonably complicated type - struct MyType{T} end - const t17809s = Any[ - Tuple{ - Type{Ptr{MyType{i}}}, - Array{Ptr{MyType{MyType{:sym}()}}(0), 0}, - Val{Complex{Int}(1, 2)}, - Val{3}, - Val{nothing}} - for i = 0:25] - - # test that types and methods get reconnected correctly - # issue 16529 (adding a method to a type with no instances) - (::Task)(::UInt8, ::UInt16, ::UInt32) = 2 - - # issue 16471 (capturing references to a kwfunc) - Base.Test.@test_throws ErrorException Core.kwfunc(Base.nothing) - Base.nothing(::UInt8, ::UInt16, ::UInt32; x = 52) = x - const nothingkw = Core.kwfunc(Base.nothing) - - # issue 16908 (some complicated types and external method definitions) - abstract type CategoricalPool{T, R <: Integer, V} end - abstract type CategoricalValue{T, R <: Integer} end - struct NominalPool{T, R <: Integer, V} <: CategoricalPool{T, R, V} - index::Vector{T} - invindex::Dict{T, R} - order::Vector{R} - ordered::Vector{T} - valindex::Vector{V} - end - struct NominalValue{T, R <: Integer} <: CategoricalValue{T, R} - level::R - pool::NominalPool{T, R, NominalValue{T, R}} - end - struct OrdinalValue{T, R <: Integer} <: CategoricalValue{T, R} - level::R - pool::NominalPool{T, R, NominalValue{T, R}} - end - (::Union{Type{NominalValue}, Type{OrdinalValue}})() = 1 - (::Union{Type{NominalValue{T}}, Type{OrdinalValue{T}}}){T}() = 2 - (::Type{Vector{NominalValue{T, R}}}){T, R}() = 3 - (::Type{Vector{NominalValue{T, T}}}){T}() = 4 - (::Type{Vector{NominalValue{Int, Int}}})() = 5 - - # more tests for method signature involving a complicated type - # issue 18343 - struct Pool18343{R, V} - valindex::Vector{V} - end - struct Value18343{T, R} - pool::Pool18343{R, Value18343{T, R}} - end - Base.convert{S}(::Type{Nullable{S}}, ::Value18343{Nullable}) = 2 - Base.convert(::Type{Nullable{Value18343}}, ::Value18343{Nullable}) = 2 - Base.convert{T}(::Type{Ref}, ::Value18343{T}) = 3 - - - let some_method = @which Base.include("string") - # global const some_method // FIXME: support for serializing a direct reference to an external Method not implemented - global const some_linfo = - ccall(:jl_specializations_get_linfo, Ref{Core.MethodInstance}, (Any, Any, Any, UInt), - some_method, Tuple{typeof(Base.include), String}, Core.svec(), typemax(UInt)) - end - - g() = override(1.0) - Base.Test.@test g() === 2.0 # compile this - end - """) - @test_throws ErrorException Core.kwfunc(Base.nothing) # make sure `nothing` didn't have a kwfunc (which would invalidate the attempted test) - - # Issue #12623 - @test __precompile__(true) === nothing - - # Issue #21307 - Base.require(Foo2_module) - @eval let Foo2_module = $(QuoteNode(Foo2_module)), # use @eval to see the results of loading the compile - Foo = getfield(Main, Foo2_module) - Foo.override(::Int) = 'a' - Foo.override(::Float32) = 'b' - end - - Base.require(Foo_module) - - @eval let Foo_module = $(QuoteNode(Foo_module)), # use @eval to see the results of loading the compile - Foo = getfield(Main, Foo_module) - @test Foo.foo(17) == 18 - @test Foo.Bar.bar(17) == 19 - - # Issue #21307 - @test Foo.g() === 97.0 - @test Foo.override(1.0e0) == Float64('a') - @test Foo.override(1.0f0) == 'b' - @test Foo.override(UInt(1)) == 2 - end - - cachefile = joinpath(dir, "$Foo_module.ji") - # use _require_from_serialized to ensure that the test fails if - # the module doesn't reload from the image: - @test_warn "WARNING: replacing module $Foo_module." begin - @test isa(Base._require_from_serialized(myid(), Foo_module, cachefile, #=broadcast-load=#false), Array{Any,1}) - end - - let Foo = getfield(Main, Foo_module) - @test_throws MethodError Foo.foo(17) # world shouldn't be visible yet - end - @eval let Foo_module = $(QuoteNode(Foo_module)), # use @eval to see the results of loading the compile - Foo2_module = $(QuoteNode(Foo2_module)), - FooBase_module = $(QuoteNode(FooBase_module)), - Foo = getfield(Main, Foo_module), - dir = $(QuoteNode(dir)), - cachefile = $(QuoteNode(cachefile)), - Foo_file = $(QuoteNode(Foo_file)) - @test Foo.foo(17) == 18 - @test Foo.Bar.bar(17) == 19 - - # Issue #21307 - @test Foo.g() === 97.0 - @test Foo.override(1.0e0) == Float64('a') - @test Foo.override(1.0f0) == 'b' - @test Foo.override(UInt(1)) == 2 - - # issue #12284: - @test stringmime("text/plain", Base.Docs.doc(Foo.foo)) == "foo function\n" - @test stringmime("text/plain", Base.Docs.doc(Foo.Bar.bar)) == "bar function\n" - - modules, deps, required_modules = Base.parse_cache_header(cachefile) - @test modules == Dict(Foo_module => Base.module_uuid(Foo)) - @test map(x -> x[1], sort(deps)) == [Foo_file, joinpath(dir, "bar.jl"), joinpath(dir, "foo.jl")] - - modules, deps1 = Base.cache_dependencies(cachefile) - @test modules == Dict(s => Base.module_uuid(getfield(Foo, s)) for s in - [:Base, :Core, Foo2_module, FooBase_module, :Main]) - @test deps == deps1 - - @test current_task()(0x01, 0x4000, 0x30031234) == 2 - @test nothing(0x01, 0x4000, 0x30031234) == 52 - @test nothing(0x01, 0x4000, 0x30031234; x = 9142) == 9142 - @test Foo.nothingkw === Core.kwfunc(Base.nothing) - - @test Foo.NominalValue() == 1 - @test Foo.OrdinalValue() == 1 - @test Foo.NominalValue{Int}() == 2 - @test Foo.OrdinalValue{Int}() == 2 - let T = Vector{Foo.NominalValue{Int}} - @test isa(T(), T) - end - @test Vector{Foo.NominalValue{Int32, Int64}}() == 3 - @test Vector{Foo.NominalValue{UInt, UInt}}() == 4 - @test Vector{Foo.NominalValue{Int, Int}}() == 5 - @test all(i -> Foo.t17809s[i + 1] === - Tuple{ - Type{Ptr{Foo.MyType{i}}}, - Array{Ptr{Foo.MyType{Foo.MyType{:sym}()}}(0), 0}, - Val{Complex{Int}(1, 2)}, - Val{3}, - Val{nothing}}, - 0:25) - some_method = @which Base.include("string") - some_linfo = - ccall(:jl_specializations_get_linfo, Ref{Core.MethodInstance}, (Any, Any, Any, UInt), - some_method, Tuple{typeof(Base.include), String}, Core.svec(), typemax(UInt)) - @test Foo.some_linfo::Core.MethodInstance === some_linfo - - PV = Foo.Value18343{Nullable}.body.types[1] - VR = PV.types[1].parameters[1] - @test PV.types[1] === Array{VR,1} - @test pointer_from_objref(PV.types[1]) === - pointer_from_objref(PV.types[1].parameters[1].types[1].types[1]) - @test PV === PV.types[1].parameters[1].types[1] - @test pointer_from_objref(PV) === pointer_from_objref(PV.types[1].parameters[1].types[1]) - end - - Baz_file = joinpath(dir, "Baz.jl") - write(Baz_file, - """ - __precompile__(false) - module Baz - end - """) - - @test_warn "ERROR: LoadError: Declaring __precompile__(false) is not allowed in files that are being precompiled.\nStacktrace:\n [1] __precompile__" try - Base.compilecache("Baz") # from __precompile__(false) - error("__precompile__ disabled test failed") - catch exc - isa(exc, ErrorException) || rethrow(exc) - !isempty(search(exc.msg, "__precompile__(false)")) && rethrow(exc) - end - - # Issue #12720 - FooBar1_file = joinpath(dir, "FooBar1.jl") - write(FooBar1_file, - """ - __precompile__(true) - module FooBar1 - using FooBar - end - """) - sleep(2) # give FooBar and FooBar1 different timestamps, in reverse order too - FooBar_file = joinpath(dir, "FooBar.jl") - write(FooBar_file, - """ - __precompile__(true) - module FooBar - end - """) - - Base.compilecache("FooBar") - @test isfile(joinpath(dir, "FooBar.ji")) - @test !Base.stale_cachefile(FooBar_file, joinpath(dir, "FooBar.ji")) - @test !isdefined(Main, :FooBar) - @test !isdefined(Main, :FooBar1) - - relFooBar_file = joinpath(dir, "subfolder", "..", "FooBar.jl") - @test Base.stale_cachefile(relFooBar_file, joinpath(dir, "FooBar.ji")) == !is_windows() # `..` is not a symlink on Windows - mkdir(joinpath(dir, "subfolder")) - @test !Base.stale_cachefile(relFooBar_file, joinpath(dir, "FooBar.ji")) - - @eval using FooBar - fb_uuid = Base.module_uuid(Main.FooBar) - sleep(2); touch(FooBar_file) - insert!(Base.LOAD_CACHE_PATH, 1, dir2) - @test Base.stale_cachefile(FooBar_file, joinpath(dir, "FooBar.ji")) - @eval using FooBar1 - @test !isfile(joinpath(dir2, "FooBar.ji")) - @test !isfile(joinpath(dir, "FooBar1.ji")) - @test isfile(joinpath(dir2, "FooBar1.ji")) - @test Base.stale_cachefile(FooBar_file, joinpath(dir, "FooBar.ji")) - @test !Base.stale_cachefile(FooBar1_file, joinpath(dir2, "FooBar1.ji")) - @test fb_uuid == Base.module_uuid(Main.FooBar) - fb_uuid1 = Base.module_uuid(Main.FooBar1) - @test fb_uuid != fb_uuid1 - - @test_warn "WARNING: replacing module FooBar." reload("FooBar") - @test fb_uuid != Base.module_uuid(Main.FooBar) - @test fb_uuid1 == Base.module_uuid(Main.FooBar1) - fb_uuid = Base.module_uuid(Main.FooBar) - @test isfile(joinpath(dir2, "FooBar.ji")) - @test Base.stale_cachefile(FooBar_file, joinpath(dir, "FooBar.ji")) - @test !Base.stale_cachefile(FooBar1_file, joinpath(dir2, "FooBar1.ji")) - @test !Base.stale_cachefile(FooBar_file, joinpath(dir2, "FooBar.ji")) - - @test_warn "WARNING: replacing module FooBar1." reload("FooBar1") - @test fb_uuid == Base.module_uuid(Main.FooBar) - @test fb_uuid1 != Base.module_uuid(Main.FooBar1) - - @test isfile(joinpath(dir2, "FooBar.ji")) - @test isfile(joinpath(dir2, "FooBar1.ji")) - @test Base.stale_cachefile(FooBar_file, joinpath(dir, "FooBar.ji")) - @test !Base.stale_cachefile(FooBar_file, joinpath(dir2, "FooBar.ji")) - @test !Base.stale_cachefile(FooBar1_file, joinpath(dir2, "FooBar1.ji")) - - # test behavior of precompile modules that throw errors - write(FooBar_file, - """ - __precompile__(true) - module FooBar - error("break me") - end - """) - @test_warn "ERROR: LoadError: break me\nStacktrace:\n [1] error" try - Base.require(:FooBar) - error("\"LoadError: break me\" test failed") - catch exc - isa(exc, ErrorException) || rethrow(exc) - !isempty(search(exc.msg, "ERROR: LoadError: break me")) && rethrow(exc) - end - - # Test transitive dependency for #21266 - FooBarT_file = joinpath(dir, "FooBarT.jl") - write(FooBarT_file, - """ - __precompile__(true) - module FooBarT - end - """) - FooBarT1_file = joinpath(dir, "FooBarT1.jl") - write(FooBarT1_file, - """ - __precompile__(true) - module FooBarT1 - using FooBarT - end - """) - FooBarT2_file = joinpath(dir, "FooBarT2.jl") - write(FooBarT2_file, - """ - __precompile__(true) - module FooBarT2 - using FooBarT1 - end - """) - Base.compilecache("FooBarT2") - write(FooBarT1_file, - """ - __precompile__(true) - module FooBarT1 - end - """) - rm(FooBarT_file) - @test Base.stale_cachefile(FooBarT2_file, joinpath(dir2, "FooBarT2.ji")) - @test Base.require(:FooBarT2) === nothing -finally - splice!(Base.LOAD_CACHE_PATH, 1:2) - splice!(LOAD_PATH, 1) - rm(dir, recursive=true) - rm(dir2, recursive=true) -end - -# test --compilecache=no command line option -let dir = mktempdir(), - Time_module = :Time4b3a94a1a081a8cb - - try - write(joinpath(dir, "$Time_module.jl"), - """ - module $Time_module - __precompile__(true) - time = Base.time() - end - """) - - eval(quote - insert!(LOAD_PATH, 1, $(dir)) - insert!(Base.LOAD_CACHE_PATH, 1, $(dir)) - Base.compilecache(:Time4b3a94a1a081a8cb) - end) - - exename = `$(Base.julia_cmd()) --precompiled=yes --startup-file=no` - - testcode = """ - insert!(LOAD_PATH, 1, $(repr(dir))) - insert!(Base.LOAD_CACHE_PATH, 1, $(repr(dir))) - using $Time_module - getfield($Time_module, :time) - """ - - t1_yes = readchomp(`$exename --compilecache=yes -E $(testcode)`) - t2_yes = readchomp(`$exename --compilecache=yes -E $(testcode)`) - @test t1_yes == t2_yes - - t1_no = readchomp(`$exename --compilecache=no -E $(testcode)`) - t2_no = readchomp(`$exename --compilecache=no -E $(testcode)`) - @test t1_no != t2_no - @test parse(Float64, t1_no) < parse(Float64, t2_no) - - finally - splice!(Base.LOAD_CACHE_PATH, 1) - splice!(LOAD_PATH, 1) - rm(dir, recursive=true) - end -end - -# test loading a package with conflicting namespace -let dir = mktempdir() - Test_module = :Test6c92f26 - try - write(joinpath(dir, "Iterators.jl"), - """ - module Iterators - __precompile__(true) - end - """) - - write(joinpath(dir, "$Test_module.jl"), - """ - module $Test_module - __precompile__(true) - using Iterators - end - """) - - testcode = """ - insert!(LOAD_PATH, 1, $(repr(dir))) - insert!(Base.LOAD_CACHE_PATH, 1, $(repr(dir))) - using $Test_module - """ - - exename = `$(Base.julia_cmd()) --startup-file=no` - let fname = tempname() - try - @test readchomp(pipeline(`$exename -E $(testcode)`, stderr=fname)) == "nothing" - @test Test.ismatch_warn("WARNING: replacing module $Test_module.\n", readstring(fname)) - finally - rm(fname, force=true) - end - end - # Loading $Test_module from the cache should not bring `Base.Iterators` - # into `Main`, since that would lead to a namespace conflict with - # the module `Iterators` defined above. - let fname = tempname() - try - @test readchomp(pipeline(`$exename -E $(testcode)`, stderr=fname)) == "nothing" - # e.g `@test_nowarn` - @test Test.ismatch_warn(r"^(?!.)"s, readstring(fname)) - finally - rm(fname, force=true) - end - end - finally - rm(dir, recursive=true) - end -end - -let dir = mktempdir() - try - insert!(LOAD_PATH, 1, dir) - insert!(Base.LOAD_CACHE_PATH, 1, dir) - - loaded_modules = Channel{Symbol}(32) - callback = (mod::Symbol) -> put!(loaded_modules, mod) - push!(Base.package_callbacks, callback) - - Test1_module = :Teste4095a81 - Test2_module = :Teste4095a82 - Test3_module = :Teste4095a83 - - write(joinpath(dir, "$(Test1_module).jl"), - """ - module $(Test1_module) - __precompile__(true) - end - """) - - Base.compilecache("$(Test1_module)") - write(joinpath(dir, "$(Test2_module).jl"), - """ - module $(Test2_module) - __precompile__(true) - using $(Test1_module) - end - """) - Base.compilecache("$(Test2_module)") - @test !Base.isbindingresolved(Main, Test2_module) - Base.require(Test2_module) - @test Base.isbindingresolved(Main, Test2_module) - @test take!(loaded_modules) == Test1_module - @test take!(loaded_modules) == Test2_module - write(joinpath(dir, "$(Test3_module).jl"), - """ - module $(Test3_module) - using $(Test3_module) - end - """) - Base.require(Test3_module) - @test take!(loaded_modules) == Test3_module - finally - pop!(Base.package_callbacks) - splice!(Base.LOAD_CACHE_PATH, 1) - splice!(LOAD_PATH, 1) - rm(dir, recursive=true) - end -end - -let module_name = string("a",randstring()) - insert!(LOAD_PATH, 1, pwd()) - file_name = string(module_name, ".jl") - sleep(2); touch(file_name) - code = """module $(module_name)\nend\n""" - write(file_name, code) - reload(module_name) - @test isa(eval(Main, Symbol(module_name)), Module) - deleteat!(LOAD_PATH,1) - rm(file_name) -end - -# Issue #19960 -let - # ideally this would test with workers on a remote host that does not have access to the master node filesystem for loading - # can simulate this for local workers by using relative load paths on master node that are not valid on workers - # so addprocs before changing directory to temp directory, otherwise workers will inherit temp working directory - - test_workers = addprocs(1) - temp_path = mktempdir() - save_cwd = pwd() - cd(temp_path) - load_path = mktempdir(temp_path) - load_cache_path = mktempdir(temp_path) - unshift!(LOAD_PATH, basename(load_path)) - unshift!(Base.LOAD_CACHE_PATH, basename(load_cache_path)) - - ModuleA = :Issue19960A - ModuleB = :Issue19960B - - write(joinpath(load_path, "$ModuleA.jl"), - """ - __precompile__(true) - module $ModuleA - export f - f() = myid() - end - """) - - write(joinpath(load_path, "$ModuleB.jl"), - """ - __precompile__(true) - module $ModuleB - using $ModuleA - export g - g() = f() - end - """) - - try - @eval using $ModuleB - for wid in test_workers - @test remotecall_fetch(g, wid) == wid - end - finally - shift!(LOAD_PATH) - shift!(Base.LOAD_CACHE_PATH) - cd(save_cwd) - rm(temp_path, recursive=true) - rmprocs(test_workers) - end -end - -end # !withenv diff --git a/julia-0.6.3/share/julia/test/complex.jl b/julia-0.6.3/share/julia/test/complex.jl deleted file mode 100644 index 52350a4..0000000 --- a/julia-0.6.3/share/julia/test/complex.jl +++ /dev/null @@ -1,975 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -@test reim(2 + 3im) == (2, 3) - -for T in (Int64, Float64) - @test real(T) == T - @test real(Complex{T}) == T - @test complex(T) == Complex{T} - @test complex(Complex{T}) == Complex{T} -end - -#showcompact -@test sprint(showcompact, complex(1, 0)) == "1+0im" -@test sprint(show, complex(true, true)) == "Complex(true,true)" - -@testset "arithmetic" begin - @testset for T in (Float16, Float32, Float64, BigFloat) - t = true - f = false - - @testset "add and subtract" begin - @test isequal(T(+0.0) + im, Complex(T(+0.0), T(+1.0))) - @test isequal(T(-0.0) + im, Complex(T(-0.0), T(+1.0))) - @test isequal(T(+0.0) - im, Complex(T(+0.0), T(-1.0))) - @test isequal(T(-0.0) - im, Complex(T(-0.0), T(-1.0))) - @test isequal(T(+1.0) + im, Complex(T(+1.0), T(+1.0))) - @test isequal(T(-1.0) + im, Complex(T(-1.0), T(+1.0))) - @test isequal(T(+1.0) - im, Complex(T(+1.0), T(-1.0))) - @test isequal(T(-1.0) - im, Complex(T(-1.0), T(-1.0))) - @test isequal(im + T(+0.0), Complex(T(+0.0), T(+1.0))) - @test isequal(im + T(-0.0), Complex(T(-0.0), T(+1.0))) - @test isequal(im - T(+0.0), Complex(T(+0.0), T(+1.0))) - @test isequal(im - T(-0.0), Complex(T(+0.0), T(+1.0))) - @test isequal(im + T(+1.0), Complex(T(+1.0), T(+1.0))) - @test isequal(im + T(-1.0), Complex(T(-1.0), T(+1.0))) - @test isequal(im - T(+1.0), Complex(T(-1.0), T(+1.0))) - @test isequal(im - T(-1.0), Complex(T(+1.0), T(+1.0))) - @test isequal(T(f) + im, Complex(T(+0.0), T(+1.0))) - @test isequal(T(t) + im, Complex(T(+1.0), T(+1.0))) - @test isequal(T(f) - im, Complex(T(+0.0), T(-1.0))) - @test isequal(T(t) - im, Complex(T(+1.0), T(-1.0))) - @test isequal(im + T(f), Complex(T(+0.0), T(+1.0))) - @test isequal(im + T(t), Complex(T(+1.0), T(+1.0))) - @test isequal(im - T(f), Complex(T(+0.0), T(+1.0))) - @test isequal(im - T(t), Complex(T(-1.0), T(+1.0))) - end - - @testset "multiply" begin - @test isequal(T(+0.0) * im, Complex(T(+0.0), T(+0.0))) - @test isequal(T(-0.0) * im, Complex(T(-0.0), T(-0.0))) - @test isequal(T(+1.0) * im, Complex(T(+0.0), T(+1.0))) - @test isequal(T(-1.0) * im, Complex(T(-0.0), T(-1.0))) - @test isequal(im * T(+0.0), Complex(T(+0.0), T(+0.0))) - @test isequal(im * T(-0.0), Complex(T(-0.0), T(-0.0))) - @test isequal(im * T(+1.0), Complex(T(+0.0), T(+1.0))) - @test isequal(im * T(-1.0), Complex(T(-0.0), T(-1.0))) - end - - @testset "divide" begin - @test isequal(T(+0.0) / im, Complex(T(+0.0), T(-0.0))) - @test isequal(T(-0.0) / im, Complex(T(-0.0), T(+0.0))) - @test isequal(T(+1.0) / im, Complex(T(+0.0), T(-1.0))) - @test isequal(T(-1.0) / im, Complex(T(-0.0), T(+1.0))) - end - end - @test isequal(true + complex(true,false), complex(true,false) + complex(true,false)) - @test isequal(complex(true,false) + true, complex(true,false) + complex(true,false)) - @test isequal(true - complex(true,false), complex(true,false) - complex(true,false)) - @test isequal(complex(true,false) - true, complex(true,false) - complex(true,false)) - @test isequal(true * complex(true,false), complex(true,false) * complex(true,false)) - @test isequal(complex(true,false) * true, complex(true,false) * complex(true,false)) -end - -@testset "basic math functions" begin - # We compare to BigFloat instead of hard-coding - # values, assuming that BigFloat has an independent and independently - # tested implementation. - @testset for T in (Float32, Float64) - x = Complex{T}(1//3 + 1//4*im) - y = Complex{T}(1//2 + 1//5*im) - yi = 4 - @testset "Random values" begin - @test x^y ≈ big(x)^big(y) - @test x^yi ≈ big(x)^yi - @test x^true ≈ big(x)^true - @test x^false ≈ big(x)^false - @test x^1 ≈ big(x)^1 - @test abs(x) ≈ abs(big(x)) - @test abs2(x) ≈ abs2(big(x)) - @test acos(x) ≈ acos(big(x)) - @test acosh(1+x) ≈ acosh(1+big(x)) - @test angle(x) ≈ angle(big(x)) - @test asin(x) ≈ asin(big(x)) - @test asinh(x) ≈ asinh(big(x)) - @test atan(x) ≈ atan(big(x)) - @test atanh(x) ≈ atanh(big(x)) - @test cis(real(x)) ≈ cis(real(big(x))) - @test cis(x) ≈ cis(big(x)) - @test cos(x) ≈ cos(big(x)) - @test cosh(x) ≈ cosh(big(x)) - @test exp(x) ≈ exp(big(x)) - @test exp10(x) ≈ exp10(big(x)) - @test exp2(x) ≈ exp2(big(x)) - @test expm1(x) ≈ expm1(big(x)) atol=eps(T) - @test log(x) ≈ log(big(x)) - @test log10(x) ≈ log10(big(x)) - @test log1p(x) ≈ log1p(big(x)) - @test log2(x) ≈ log2(big(x)) - @test sin(x) ≈ sin(big(x)) - @test sinh(x) ≈ sinh(big(x)) - @test sqrt(x) ≈ sqrt(big(x)) - @test tan(x) ≈ tan(big(x)) - @test tanh(x) ≈ tanh(big(x)) - end - @testset "Inverses" begin - @test acos(cos(x)) ≈ x - @test acosh(cosh(x)) ≈ x - @test asin(sin(x)) ≈ x - @test asinh(sinh(x)) ≈ x - @test atan(tan(x)) ≈ x - @test atanh(tanh(x)) ≈ x - @test cos(acos(x)) ≈ x - @test cosh(acosh(1+x)) ≈ 1+x - @test exp(log(x)) ≈ x - @test exp10(log10(x)) ≈ x - @test exp2(log2(x)) ≈ x - @test expm1(log1p(x)) ≈ x - @test log(exp(x)) ≈ x - @test log10(exp10(x)) ≈ x - @test log1p(expm1(x)) ≈ x - @test log2(exp2(x)) ≈ x - @test sin(asin(x)) ≈ x - @test sinh(asinh(x)) ≈ x - @test sqrt(x)^2 ≈ x - @test sqrt(x^2) ≈ x - @test tan(atan(x)) ≈ x - @test tanh(atanh(x)) ≈ x - end - @testset "Relations between functions" begin - @test cosh(x) ≈ (exp(x)+exp(-x))/2 - @test cosh(x)^2-sinh(x)^2 ≈ 1 - @test sin(x)^2+cos(x)^2 ≈ 1 - @test sinh(x) ≈ (exp(x)-exp(-x))/2 - @test tan(x) ≈ sin(x)/cos(x) - @test tanh(x) ≈ sinh(x)/cosh(x) - end - end -end - -@testset "isinf" begin - @test iszero(real(complex(0.0,1.0))) # isimag deprecated - @test !iszero(real(complex(1.0,1.0))) # isimag deprecated - @test isinf(complex(Inf,0)) - @test isinf(complex(-Inf,0)) - @test isinf(complex(0,Inf)) - @test isinf(complex(0,-Inf)) - @test !isinf(complex(0,0)) -end - -@testset "flipsign" begin - @test isequal(complex( 0.0, 0.0 ), flipsign(complex( 0.0, 0.0 ), 1)) - @test isequal(complex( -0.0, -0.0 ), flipsign(complex( 0.0, 0.0 ), -1)) - @test isequal(complex( Inf, 0.0 ), flipsign(complex( Inf, 0.0 ), 1)) - @test isequal(complex( -Inf, -0.0 ), flipsign(complex( Inf, 0.0 ), -1)) - @test isequal(complex( 0.0, NaN ), flipsign(complex( 0.0, NaN ), 1.0)) - @test isequal(complex( -0.0, NaN ), flipsign(complex( 0.0, NaN ), -1.0)) - - @test isequal(complex( 5.0, 4.0 ), flipsign(complex(-5.0, -4.0), -1)) - @test isequal(complex( 0.5, -0.5 ), flipsign(complex(-0.5, 0.5), -2)) -end - -@testset "sqrt" begin - # tests special values from csqrt man page - # as well as conj(sqrt(z)) = sqrt(conj(z)) - @test isequal(sqrt(complex( 0.0, 0.0)), complex( 0.0, 0.0)) - @test isequal(sqrt(complex( 0.0,-0.0)), complex( 0.0,-0.0)) - @test isequal(sqrt(complex( 0.0, Inf)), complex( Inf, Inf)) - @test isequal(sqrt(complex( 0.0,-Inf)), complex( Inf,-Inf)) - @test isequal(sqrt(complex( 0.0, NaN)), complex( NaN, NaN)) - @test isequal(sqrt(complex(-0.0, 0.0)), complex( 0.0, 0.0)) - @test isequal(sqrt(complex(-0.0,-0.0)), complex( 0.0,-0.0)) - - @test isequal(sqrt(complex( 5.0, 0.0)), complex(sqrt(5.0), 0.0)) - @test isequal(sqrt(complex( 5.0,-0.0)), complex(sqrt(5.0),-0.0)) - @test isequal(sqrt(complex(-5.0, 0.0)), complex( 0.0, sqrt(5.0))) - @test isequal(sqrt(complex(-5.0,-0.0)), complex( 0.0,-sqrt(5.0))) - - @test isequal(sqrt(complex( Inf, 0.0)), complex( Inf, 0.0)) - @test isequal(sqrt(complex( Inf,-0.0)), complex( Inf,-0.0)) - @test isequal(sqrt(complex( Inf, 5.0)), complex( Inf, 0.0)) - @test isequal(sqrt(complex( Inf,-5.0)), complex( Inf,-0.0)) - @test isequal(sqrt(complex( Inf, Inf)), complex( Inf, Inf)) - @test isequal(sqrt(complex( Inf,-Inf)), complex( Inf,-Inf)) - @test isequal(sqrt(complex( Inf, NaN)), complex( Inf, NaN)) - - @test isequal(sqrt(complex(-Inf, 0.0)), complex( 0.0, Inf)) - @test isequal(sqrt(complex(-Inf,-0.0)), complex( 0.0,-Inf)) - @test isequal(sqrt(complex(-Inf, 5.0)), complex( 0.0, Inf)) - @test isequal(sqrt(complex(-Inf,-5.0)), complex( 0.0,-Inf)) - @test isequal(sqrt(complex(-Inf, Inf)), complex( Inf, Inf)) - @test isequal(sqrt(complex(-Inf,-Inf)), complex( Inf,-Inf)) - @test isequal(sqrt(complex(-Inf, NaN)), complex( NaN, Inf)) - - @test isequal(sqrt(complex( NaN, 0.0)), complex( NaN, NaN)) - @test isequal(sqrt(complex( NaN, 0.0)), complex( NaN, NaN)) - @test isequal(sqrt(complex( NaN, Inf)), complex( Inf, Inf)) - @test isequal(sqrt(complex( NaN,-Inf)), complex( Inf,-Inf)) -end - -@testset "log(conj(z)) == conj(log(z))" begin - @test isequal(log(complex( 0.0, 0.0)), complex(-Inf, 0.0)) - @test isequal(log(complex( 0.0,-0.0)), complex(-Inf,-0.0)) - @test isequal(log(complex( 0.0, 1.0)), complex( 0.0, pi/2)) - @test isequal(log(complex( 0.0,-1.0)), complex( 0.0,-pi/2)) - @test isequal(log(complex( 0.0, Inf)), complex( Inf, pi/2)) - @test isequal(log(complex( 0.0,-Inf)), complex( Inf,-pi/2)) - @test isequal(log(complex( 0.0, NaN)), complex( NaN, NaN)) - @test isequal(log(complex(-0.0, 0.0)), complex(-Inf, pi)) - @test isequal(log(complex(-0.0,-0.0)), complex(-Inf,-pi)) - - @test isequal(log(complex( 5.0, 0.0)),complex(log(5.0), 0.0)) - @test isequal(log(complex( 5.0,-0.0)),complex(log(5.0),-0.0)) - - @test isequal(log(complex( Inf, 5.0)), complex( Inf, 0.0)) - @test isequal(log(complex( Inf,-5.0)), complex( Inf,-0.0)) - @test isequal(log(complex( Inf, Inf)), complex( Inf, pi/4)) - @test isequal(log(complex( Inf,-Inf)), complex( Inf,-pi/4)) - @test isequal(log(complex( Inf, NaN)), complex( Inf, NaN)) - - @test isequal(log(complex(-Inf, 5.0)), complex( Inf, pi)) - @test isequal(log(complex(-Inf,-5.0)), complex( Inf,-pi)) - @test isequal(log(complex(-Inf, Inf)), complex( Inf, 3*pi/4)) - @test isequal(log(complex(-Inf,-Inf)), complex( Inf,-3*pi/4)) - @test isequal(log(complex(-Inf, NaN)), complex( Inf, NaN)) - - @test isequal(log(complex( NaN, 0.0)), complex( NaN, NaN)) - @test isequal(log(complex( NaN, Inf)), complex( Inf, NaN)) - @test isequal(log(complex( NaN,-Inf)), complex( Inf, NaN)) - @test isequal(log(complex( NaN, NaN)), complex( NaN, NaN)) -end - -@testset "exp(conj(z)) == conj(exp(z))" begin - @test isequal(exp(complex( 0.0, 0.0)), complex(1.0, 0.0)) - @test isequal(exp(complex( 0.0,-0.0)), complex(1.0,-0.0)) - @test isequal(exp(complex( 0.0, Inf)), complex(NaN, NaN)) - @test isequal(exp(complex( 0.0,-Inf)), complex(NaN, NaN)) - @test isequal(exp(complex( 0.0, NaN)), complex(NaN, NaN)) - - @test isequal(exp(complex(-0.0, 0.0)), complex(1.0, 0.0)) - @test isequal(exp(complex(-0.0,-0.0)), complex(1.0,-0.0)) - - @test isequal(exp(complex( 5.0, Inf)), complex(NaN, NaN)) - - @test isequal(exp(complex( Inf, 0.0)), complex(Inf, 0.0)) - @test isequal(exp(complex( Inf,-0.0)), complex(Inf,-0.0)) - @test isequal(exp(complex( Inf, 5.0)), complex(cos(5.0)*Inf,sin(5.0)* Inf)) - @test isequal(exp(complex( Inf,-5.0)), complex(cos(5.0)*Inf,sin(5.0)*-Inf)) - @test isequal(exp(complex( Inf, NaN)), complex(-Inf, NaN)) - @test isequal(exp(complex( Inf, Inf)), complex(-Inf, NaN)) - @test isequal(exp(complex( Inf,-Inf)), complex(-Inf, NaN)) - - @test isequal(exp(complex(-Inf, 0.0)), complex(0.0, 0.0)) - @test isequal(exp(complex(-Inf,-0.0)), complex(0.0,-0.0)) - @test isequal(exp(complex(-Inf, 5.0)), complex(cos(5.0)*0.0,sin(5.0)* 0.0)) - @test isequal(exp(complex(-Inf,-5.0)), complex(cos(5.0)*0.0,sin(5.0)*-0.0)) - @test isequal(exp(complex(-Inf, Inf)), complex(-0.0, 0.0)) - @test isequal(exp(complex(-Inf,-Inf)), complex(-0.0,-0.0)) - @test isequal(exp(complex(-Inf, NaN)), complex(-0.0, 0.0)) - - @test isequal(exp(complex( NaN, 0.0)), complex( NaN, 0.0)) - @test isequal(exp(complex( NaN,-0.0)), complex( NaN,-0.0)) - @test isequal(exp(complex( NaN, 5.0)), complex( NaN, NaN)) - @test isequal(exp(complex( NaN, NaN)), complex( NaN, NaN)) -end - -@testset "expm1(conj(z)) == conj(expm1(z))" begin - @test isequal(expm1(complex( 0.0, 0.0)), complex(0.0, 0.0)) - @test isequal(expm1(complex( 0.0,-0.0)), complex(0.0,-0.0)) - @test isequal(expm1(complex( 0.0, Inf)), complex(NaN, NaN)) - @test isequal(expm1(complex( 0.0,-Inf)), complex(NaN, NaN)) - @test isequal(expm1(complex( 0.0, NaN)), complex(NaN, NaN)) - - @test isequal(expm1(complex(-0.0, 0.0)), complex(-0.0, 0.0)) - @test isequal(expm1(complex(-0.0,-0.0)), complex(-0.0,-0.0)) - - @test isequal(expm1(complex( 5.0, Inf)), complex(NaN, NaN)) - - @test isequal(expm1(complex( Inf, 0.0)), complex(Inf, 0.0)) - @test isequal(expm1(complex( Inf,-0.0)), complex(Inf,-0.0)) - @test isequal(expm1(complex( Inf, 5.0)), complex(cos(5.0)*Inf,sin(5.0)* Inf)) - @test isequal(expm1(complex( Inf,-5.0)), complex(cos(5.0)*Inf,sin(5.0)*-Inf)) - @test isequal(expm1(complex( Inf, NaN)), complex(-Inf, NaN)) - @test isequal(expm1(complex( Inf, Inf)), complex(-Inf, NaN)) - @test isequal(expm1(complex( Inf,-Inf)), complex(-Inf, NaN)) - - @test isequal(expm1(complex(-Inf, 0.0)), complex(-1.0, 0.0)) - @test isequal(expm1(complex(-Inf,-0.0)), complex(-1.0,-0.0)) - @test isequal(expm1(complex(-Inf, 5.0)), complex(-1.0,sin(5.0)* 0.0)) - @test isequal(expm1(complex(-Inf,-5.0)), complex(-1.0,sin(5.0)*-0.0)) - @test isequal(expm1(complex(-Inf, Inf)), complex(-1.0, 0.0)) - @test isequal(expm1(complex(-Inf,-Inf)), complex(-1.0,-0.0)) - @test isequal(expm1(complex(-Inf, NaN)), complex(-1.0, 0.0)) - - @test isequal(expm1(complex( NaN, 0.0)), complex( NaN, 0.0)) - @test isequal(expm1(complex( NaN,-0.0)), complex( NaN,-0.0)) - @test isequal(expm1(complex( NaN, 5.0)), complex( NaN, NaN)) - @test isequal(expm1(complex( NaN, NaN)), complex( NaN, NaN)) - - @test isequal(expm1(complex( 1e-20, 0.0)), complex(expm1( 1e-20), 0.0)) - @test isequal(expm1(complex(-1e-20, 0.0)), complex(expm1(-1e-20), 0.0)) - - @test expm1(complex( 1e-20, 1e-10)) ≈ complex( 5e-21, 1e-10) - @test expm1(complex( 1e-20,-1e-10)) ≈ complex( 5e-21,-1e-10) - @test expm1(complex(-1e-20, 1e-10)) ≈ complex(-1.5e-20, 1e-10) - @test expm1(complex(-1e-20,-1e-10)) ≈ complex(-1.5e-20,-1e-10) - - @test expm1(complex( 10.0, 10.0)) ≈ exp(complex( 10.0, 10.0))-1 - @test expm1(complex( 10.0,-10.0)) ≈ exp(complex( 10.0,-10.0))-1 - @test expm1(complex(-10.0, 10.0)) ≈ exp(complex(-10.0, 10.0))-1 - @test expm1(complex(-10.0,-10.0)) ≈ exp(complex(-10.0,-10.0))-1 -end - -import Base.Math.@horner -@testset "log1p" begin - @test isequal(log1p(complex(Inf, 3)), complex(Inf, +0.)) - @test isequal(log1p(complex(Inf, -3)), complex(Inf, -0.)) - @test isequal(log1p(complex(-Inf, 3)), complex(Inf, +pi)) - @test isequal(log1p(complex(-Inf, -3)), complex(Inf, -pi)) - @test isequal(log1p(complex(Inf, NaN)), complex(Inf, NaN)) - @test isequal(log1p(complex(NaN, 0)), complex(NaN, NaN)) - @test isequal(log1p(complex(0, NaN)), complex(NaN, NaN)) - @test isequal(log1p(complex(-1, +0.)), complex(-Inf, +0.)) - @test isequal(log1p(complex(-1, -0.)), complex(-Inf, -0.)) - @test isequal(log1p(complex(-2, 1e-10)), log(1 + complex(-2, 1e-10))) - @test isequal(log1p(complex(1, Inf)), complex(Inf, pi/2)) - @test isequal(log1p(complex(1, -Inf)), complex(Inf, -pi/2)) - - for z in (1e-10+1e-9im, 1e-10-1e-9im, -1e-10+1e-9im, -1e-10-1e-9im) - @test log1p(z) ≈ @horner(z, 0, 1, -0.5, 1/3, -0.25, 0.2) - end - for z in (15+4im, 0.2+3im, 0.08-0.9im) - @test log1p(z) ≈ log(1+z) - end -end - - -@testset "^ (cpow)" begin - # equivalent to exp(y*log(x)) - # except for 0^0? - # conj(x)^conj(y) = conj(x^y) - @test isequal(complex( 0.0, 0.0)^complex( 0.0, 0.0), complex(1.0, 0.0)) - @test isequal(complex( 0.0, 0.0)^complex( 0.0,-0.0), complex(1.0, 0.0)) - @test isequal(complex( 0.0, 0.0)^complex(-0.0, 0.0), complex(1.0,-0.0)) - @test isequal(complex( 0.0, 0.0)^complex(-0.0,-0.0), complex(1.0,-0.0)) - - @test isequal(complex( 0.0,-0.0)^complex( 0.0, 0.0), complex(1.0,-0.0)) - @test isequal(complex( 0.0,-0.0)^complex( 0.0,-0.0), complex(1.0,-0.0)) - @test isequal(complex( 0.0,-0.0)^complex(-0.0, 0.0), complex(1.0, 0.0)) - @test isequal(complex( 0.0,-0.0)^complex(-0.0,-0.0), complex(1.0, 0.0)) - - @test isequal(complex(-0.0, 0.0)^complex( 0.0, 0.0), complex(1.0, 0.0)) - @test isequal(complex(-0.0, 0.0)^complex( 0.0,-0.0), complex(1.0, 0.0)) - @test isequal(complex(-0.0, 0.0)^complex(-0.0, 0.0), complex(1.0,-0.0)) - @test isequal(complex(-0.0, 0.0)^complex(-0.0,-0.0), complex(1.0,-0.0)) - - @test isequal(complex(-0.0,-0.0)^complex( 0.0, 0.0), complex(1.0,-0.0)) - @test isequal(complex(-0.0,-0.0)^complex( 0.0,-0.0), complex(1.0,-0.0)) - @test isequal(complex(-0.0,-0.0)^complex(-0.0, 0.0), complex(1.0, 0.0)) - @test isequal(complex(-0.0,-0.0)^complex(-0.0,-0.0), complex(1.0, 0.0)) - - @test complex(0.0,1.0)^complex(2.0,0) ≈ complex(-1.0, 0.0) - @test complex(1.0,2.0)^complex(3.0,0) ≈ complex(-11.0, -2.0) - - @test isequal(complex(0.0,0.0)^false, complex(1.0,0.0)) - @test isequal(complex(0.0,0.0)^0, complex(1.0,0.0)) -end - -@testset "sinh and sin" begin - # sinh: has properties - # sinh(conj(z)) = conj(sinh(z)) - # sinh(-z) = -sinh(z) - - # sin: defined in terms of sinh - # sin(z) = -i*sinh(i*z) - # i.e. if sinh(a+ib) = x+iy - # then sin(b-ia) = y-ix - # sin(conj(z)) = conj(sin(z)) - # sin(-z) = -sin(z) - - # @test isequal(sin(complex( 0, 10000)),complex( 0.0, Inf)) - # @test isequal(sin(complex( 0,-10000)),complex( 0.0,-Inf)) - for (x,y) in [(complex( 0.0, 0.0), complex( 0.0, 0.0)), - (complex( 0.0, Inf), complex( 0.0, NaN)), - (complex( 0.0, NaN), complex( 0.0, NaN)), - (complex( 7.2, Inf), complex( NaN, NaN)), - (complex( 7.2, NaN), complex( NaN, NaN)), - (complex( 7.2, 0.0), complex( sinh(7.2), 0.0)), - (complex( 1e5, 0.0), complex( sinh(1e5), 0.0)), - (complex( Inf, 0.0), complex( Inf, 0.0)), - (complex( Inf, 7.2), Inf*cis(7.2)), - (complex( Inf, Inf), complex( Inf, NaN)), - (complex( Inf, NaN), complex( Inf, NaN)), - (complex( NaN, 0.0), complex( NaN, 0.0)), - (complex( NaN, 7.2), complex( NaN, NaN)), - (complex( NaN, NaN), complex( NaN, NaN)), - ] - @test isequal(sinh(x), y) - @test isequal(sinh(conj(x)), conj(y)) - @test isequal(sinh(-x), -y) - @test isequal(sinh(-conj(x)), -conj(y)) - - xx = complex(imag(x),-real(x)) - yy = complex(imag(y),-real(y)) - - @test isequal(sin(xx),yy) - @test isequal(sin(conj(xx)), conj(yy)) - @test isequal(sin(-xx), -yy) - @test isequal(sin(-conj(xx)), -conj(yy)) - - yyy = sin(pi*xx) - @test isequal(sinpi(xx), yyy) - @test isequal(sinpi(conj(xx)),conj(yyy)) - @test isequal(sinpi(-xx),-yyy) - @test isequal(sinpi(-conj(xx)),-conj(yyy)) - end -end - -@testset "cosh and cos" begin - # cosh: has properties - # cosh(conj(z)) = conj(cosh(z)) - # coshh(-z) = cosh(z) - - # cos - # cos(z) = cosh(iz) - # i.e cos(b-ia) = cosh(a+ib) - # and cos(b+ia) = cosh(a-ib) - # cos(conj(z)) = conj(cos(z)) - # cos(-z) = cos(z) - for (x,y) in [(complex( 0.0, 0.0), complex( 1.0, 0.0)), - (complex( 0.0, Inf), complex( NaN, 0.0)), - (complex( 0.0, NaN), complex( NaN, 0.0)), - (complex( 7.2, Inf), complex( NaN, NaN)), - (complex( 7.2, NaN), complex( NaN, NaN)), - (complex( 7.2, 0.0), complex( cosh(7.2), 0.0)), - (complex( 1e5, 0.0), complex( Inf, 0.0)), - (complex( Inf, 0.0), complex( Inf, 0.0)), - (complex( Inf, 7.2), Inf*cis(7.2)), - (complex( Inf, Inf), complex( Inf, NaN)), - (complex( Inf, NaN), complex( Inf, NaN)), - (complex( NaN, 0.0), complex( NaN, 0.0)), - (complex( NaN, 7.2), complex( NaN, NaN)), - (complex( NaN, NaN), complex( NaN, NaN)), - ] - undef_sign = isequal(x,complex( NaN, 0.0)) || isequal(x,complex( 0.0, NaN)) - - @test isequal(cosh(x), y) - if !undef_sign - @test isequal(cosh(conj(x)), conj(y)) - @test isequal(cosh(-x), y) - @test isequal(cosh(-conj(x)), conj(y)) - end - - xx = complex(imag(x),-real(x)) - yy = y - @test isequal(cos(xx),yy) - if !undef_sign - @test isequal(cos(conj(xx)), conj(yy)) - @test isequal(cos(-xx), yy) - @test isequal(cos(-conj(xx)), conj(yy)) - end - - yyy = cos(pi*xx) - @test isequal(cospi(xx), yyy) - if !undef_sign - @test isequal(cospi(conj(xx)), conj(yyy)) - @test isequal(cospi(-xx), yyy) - @test isequal(cospi(-conj(xx)), conj(yyy)) - end - end -end - -@testset "tanh(op(z)) == op(tanh(z)) for op in (conj, -)" begin - @test isequal(tanh(complex( 0, 0)),complex(0.0,0.0)) #integer fallback - @test isequal(tanh(complex( 0.0, 0.0)),complex(0.0,0.0)) - @test isequal(tanh(complex( 0.0,-0.0)),complex(0.0,-0.0)) - @test_throws DomainError tanh(complex( 0.0, Inf)) - @test_throws DomainError tanh(complex( 0.0,-Inf)) - @test isequal(tanh(complex( 0.0, NaN)),complex(NaN,NaN)) - - @test isequal(tanh(complex(-0.0, 0.0)),complex(-0.0,0.0)) - @test isequal(tanh(complex(-0.0,-0.0)),complex(-0.0,-0.0)) - - @test_throws DomainError tanh(complex( 5.0, Inf)) - @test isequal(tanh(complex( 5.0, NaN)),complex(NaN,NaN)) - - @test isequal(tanh(complex( Inf, 0.0)),complex(1.0, 0.0)) - @test isequal(tanh(complex( Inf,-0.0)),complex(1.0,-0.0)) - @test isequal(tanh(complex( Inf, 5.0)),complex(1.0,sin(2*5.0)* 0.0)) - @test isequal(tanh(complex( Inf,-5.0)),complex(1.0,sin(2*5.0)*-0.0)) - @test isequal(tanh(complex( Inf, Inf)),complex(1.0, 0.0)) - @test isequal(tanh(complex( Inf,-Inf)),complex(1.0,-0.0)) - @test isequal(tanh(complex( Inf, NaN)),complex(1.0, 0.0)) - - @test isequal(tanh(complex(-Inf, 0.0)),complex(-1.0, 0.0)) - @test isequal(tanh(complex(-Inf,-0.0)),complex(-1.0,-0.0)) - @test isequal(tanh(complex(-Inf, 5.0)),complex(-1.0,sin(2*5.0)* 0.0)) - @test isequal(tanh(complex(-Inf,-5.0)),complex(-1.0,sin(2*5.0)*-0.0)) - @test isequal(tanh(complex(-Inf, Inf)),complex(-1.0, 0.0)) - @test isequal(tanh(complex(-Inf,-Inf)),complex(-1.0,-0.0)) - @test isequal(tanh(complex(-Inf, NaN)),complex(-1.0, 0.0)) - - @test isequal(tanh(complex( NaN, 0.0)),complex(NaN, 0.0)) - @test isequal(tanh(complex( NaN,-0.0)),complex(NaN,-0.0)) - @test isequal(tanh(complex( NaN, 5.0)),complex(NaN, NaN)) - @test isequal(tanh(complex( NaN,-5.0)),complex(NaN, NaN)) - @test isequal(tanh(complex( NaN, NaN)),complex(NaN, NaN)) -end - -@testset "tan(z) == -i tanh(iz)" begin - @test isequal(tan(complex( 0.0, Inf)),complex( 0.0, 1.0)) - @test isequal(tan(complex( 0.0,-Inf)),complex( 0.0,-1.0)) - @test isequal(tan(complex( 0.0, NaN)),complex( 0.0, NaN)) - @test isequal(tan(complex(-0.0,-Inf)),complex(-0.0,-1.0)) - @test isequal(tan(complex(-0.0, Inf)),complex(-0.0, 1.0)) - @test isequal(tan(complex(-0.0, NaN)),complex(-0.0, NaN)) - - @test isequal(tan(complex( 5.0, Inf)),complex(sin(2*5.0)* 0.0, 1.0)) - @test isequal(tan(complex( 5.0,-Inf)),complex(sin(2*5.0)* 0.0,-1.0)) - @test isequal(tan(complex( 5.0, NaN)),complex( NaN, NaN)) - @test isequal(tan(complex(-5.0, Inf)),complex(sin(2*5.0)*-0.0, 1.0)) - @test isequal(tan(complex(-5.0,-Inf)),complex(sin(2*5.0)*-0.0,-1.0)) - @test isequal(tan(complex(-5.0, NaN)),complex( NaN, NaN)) - - @test_throws DomainError tan(complex( Inf, 5.0)) - @test isequal(tan(complex( Inf, Inf)),complex( 0.0, 1.0)) - @test isequal(tan(complex( Inf,-Inf)),complex( 0.0,-1.0)) - @test isequal(tan(complex(-Inf, Inf)),complex(-0.0, 1.0)) - @test isequal(tan(complex(-Inf,-Inf)),complex(-0.0,-1.0)) - - @test isequal(tan(complex( NaN, 5.0)),complex( NaN, NaN)) - @test isequal(tan(complex( NaN, Inf)),complex( 0.0, 1.0)) - @test isequal(tan(complex( NaN,-Inf)),complex( 0.0,-1.0)) - @test isequal(tan(complex( NaN, NaN)),complex( NaN, NaN)) -end - -@testset "acosh(conj(z)) == conj(acosh(z))" begin - @test isequal(acosh(complex( 0.0, 0.0)), complex( 0.0, pi/2)) - @test isequal(acosh(complex( 0.0,-0.0)), complex( 0.0,-pi/2)) - @test isequal(acosh(complex( 0.0, Inf)), complex( Inf, pi/2)) - @test isequal(acosh(complex( 0.0,-Inf)), complex( Inf,-pi/2)) - @test isequal(acosh(complex(-0.0, 0.0)), complex( 0.0, pi/2)) - @test isequal(acosh(complex(-0.0,-0.0)), complex( 0.0,-pi/2)) - @test isequal(acosh(complex( 5.0, Inf)), complex( Inf, pi/2)) - @test isequal(acosh(complex( 5.0,-Inf)), complex( Inf,-pi/2)) - @test isequal(acosh(complex( 5.0, NaN)), complex( NaN, NaN)) - - @test isequal(acosh(complex( Inf, 0.0)), complex( Inf, 0.0)) - @test isequal(acosh(complex( Inf,-0.0)), complex( Inf,-0.0)) - @test isequal(acosh(complex( Inf, 5.0)), complex( Inf, 0.0)) - @test isequal(acosh(complex( Inf,-5.0)), complex( Inf,-0.0)) - @test isequal(acosh(complex( Inf, Inf)), complex( Inf, pi/4)) - @test isequal(acosh(complex( Inf,-Inf)), complex( Inf,-pi/4)) - @test isequal(acosh(complex( Inf, NaN)), complex( Inf, NaN)) - - @test isequal(acosh(complex(-Inf, 0.0)), complex( Inf, pi)) - @test isequal(acosh(complex(-Inf,-0.0)), complex( Inf,-pi)) - @test isequal(acosh(complex(-Inf, 5.0)), complex( Inf, pi)) - @test isequal(acosh(complex(-Inf,-5.0)), complex( Inf,-pi)) - @test isequal(acosh(complex(-Inf, Inf)), complex( Inf, 3*pi/4)) - @test isequal(acosh(complex(-Inf,-Inf)), complex( Inf,-3*pi/4)) - @test isequal(acosh(complex(-Inf, NaN)), complex( Inf, NaN)) - - @test isequal(acosh(complex( NaN, Inf)), complex( Inf, NaN)) - @test isequal(acosh(complex( NaN,-Inf)), complex( Inf, NaN)) - @test isequal(acosh(complex( NaN, NaN)), complex( NaN, NaN)) -end - -@testset "acos(conj(z)) == conj(acos(z))" begin - @test isequal(acos(complex( 0, 0)),complex(pi/2,-0.0)) #integer fallback - @test isequal(acos(complex( 0.0, 0.0)),complex(pi/2,-0.0)) - @test isequal(acos(complex( 0.0,-0.0)),complex(pi/2, 0.0)) - @test isequal(acos(complex( 0.0, Inf)),complex(pi/2,-Inf)) - @test isequal(acos(complex( 0.0,-Inf)),complex(pi/2, Inf)) - @test isequal(acos(complex( 0.0, NaN)),complex(pi/2, NaN)) - - @test isequal(acos(complex(-0.0, 0.0)),complex(pi/2,-0.0)) - @test isequal(acos(complex(-0.0,-0.0)),complex(pi/2, 0.0)) - @test isequal(acos(complex(-0.0, NaN)),complex(pi/2, NaN)) - - @test isequal(acos(complex( 5.0, Inf)),complex(pi/2,-Inf)) - @test isequal(acos(complex( 5.0,-Inf)),complex(pi/2, Inf)) - @test isequal(acos(complex( 5.0, NaN)),complex( NaN, NaN)) - - @test isequal(acos(complex( Inf, 0.0)),complex( 0.0,-Inf)) - @test isequal(acos(complex( Inf,-0.0)),complex( 0.0, Inf)) - @test isequal(acos(complex( Inf, 5.0)),complex( 0.0,-Inf)) - @test isequal(acos(complex( Inf,-5.0)),complex( 0.0, Inf)) - @test isequal(acos(complex( Inf, Inf)),complex(pi/4,-Inf)) - @test isequal(acos(complex( Inf,-Inf)),complex(pi/4, Inf)) - @test isequal(acos(complex( Inf, NaN)),complex( NaN, Inf)) - - @test isequal(acos(complex(-Inf, 0.0)),complex(pi,-Inf)) - @test isequal(acos(complex(-Inf,-0.0)),complex(pi, Inf)) - @test isequal(acos(complex(-Inf, 5.0)),complex(pi,-Inf)) - @test isequal(acos(complex(-Inf,-5.0)),complex(pi, Inf)) - @test isequal(acos(complex(-Inf, Inf)),complex(3*pi/4,-Inf)) - @test isequal(acos(complex(-Inf,-Inf)),complex(3*pi/4, Inf)) - @test isequal(acos(complex(-Inf, NaN)),complex( NaN, Inf)) - - @test isequal(acos(complex( NaN, 0.0)),complex( NaN, NaN)) - @test isequal(acos(complex( NaN, 5.0)),complex( NaN, NaN)) - @test isequal(acos(complex( NaN, Inf)),complex( NaN,-Inf)) - @test isequal(acos(complex( NaN,-Inf)),complex( NaN, Inf)) - @test isequal(acos(complex( NaN, NaN)),complex( NaN, NaN)) -end - -@testset "asinh(op(z)) == op(asinh(z)) for op in (conj, -)" begin - @test isequal(asinh(complex( 0.0, 0.0)),complex( 0.0, 0.0)) - @test isequal(asinh(complex( 0.0,-0.0)),complex( 0.0,-0.0)) - @test isequal(asinh(complex( 0.0, Inf)),complex( Inf, pi/2)) - @test isequal(asinh(complex( 0.0,-Inf)),complex( Inf,-pi/2)) - @test isequal(asinh(complex( 0.0, NaN)),complex( NaN, NaN)) - - @test isequal(asinh(complex(-0.0, 0.0)),complex(-0.0, 0.0)) - @test isequal(asinh(complex(-0.0,-0.0)),complex(-0.0,-0.0)) - @test isequal(asinh(complex(-0.0, Inf)),complex(-Inf, pi/2)) - @test isequal(asinh(complex(-0.0,-Inf)),complex(-Inf,-pi/2)) - - @test isequal(asinh(complex( 5.0, Inf)),complex( Inf, pi/2)) - @test isequal(asinh(complex( 5.0,-Inf)),complex( Inf,-pi/2)) - @test isequal(asinh(complex( 5.0, NaN)),complex( NaN, NaN)) - @test isequal(asinh(complex(-5.0, Inf)),complex(-Inf, pi/2)) - @test isequal(asinh(complex(-5.0,-Inf)),complex(-Inf,-pi/2)) - - @test isequal(asinh(complex( Inf, Inf)),complex( Inf, pi/4)) - @test isequal(asinh(complex( Inf,-Inf)),complex( Inf,-pi/4)) - @test isequal(asinh(complex( Inf, NaN)),complex( Inf, NaN)) - @test isequal(asinh(complex(-Inf, Inf)),complex(-Inf, pi/4)) - @test isequal(asinh(complex(-Inf,-Inf)),complex(-Inf,-pi/4)) - @test isequal(asinh(complex(-Inf, NaN)),complex(-Inf, NaN)) - - @test isequal(asinh(complex( NaN, 0.0)),complex( NaN, 0.0)) - @test isequal(asinh(complex( NaN,-0.0)),complex( NaN,-0.0)) - @test isequal(asinh(complex( NaN, 5.0)),complex( NaN, NaN)) - @test isequal(asinh(complex( NaN, Inf)),complex( Inf, NaN)) - @test isequal(asinh(complex( NaN,-Inf)),complex( Inf, NaN)) - @test isequal(asinh(complex( NaN, NaN)),complex( NaN, NaN)) -end - -@testset "asin(z) == -i*asinh(iz)" begin - @test isequal(asin(complex( 0.0, 0.0)),complex( 0.0, 0.0)) - @test isequal(asin(complex( 0.0,-0.0)),complex( 0.0,-0.0)) - @test isequal(asin(complex(-0.0, 0.0)),complex(-0.0, 0.0)) - @test isequal(asin(complex( 0.0, NaN)),complex( 0.0, NaN)) - @test isequal(asin(complex(-0.0,-0.0)),complex(-0.0,-0.0)) - @test isequal(asin(complex(-0.0, NaN)),complex(-0.0, NaN)) - @test isequal(asin(complex( 5.0, NaN)),complex( NaN, NaN)) - - @test isequal(asin(complex( Inf, 0.0)),complex( pi/2, Inf)) - @test isequal(asin(complex( Inf,-0.0)),complex( pi/2,-Inf)) - @test isequal(asin(complex( Inf, 5.0)),complex( pi/2, Inf)) - @test isequal(asin(complex( Inf,-5.0)),complex( pi/2,-Inf)) - @test isequal(asin(complex( Inf, Inf)),complex( pi/4, Inf)) - @test isequal(asin(complex( Inf,-Inf)),complex( pi/4,-Inf)) - @test isequal(asin(complex( Inf, NaN)),complex( NaN, Inf)) - - @test isequal(asin(complex(-Inf, 0.0)),complex(-pi/2, Inf)) - @test isequal(asin(complex(-Inf,-0.0)),complex(-pi/2,-Inf)) - @test isequal(asin(complex(-Inf, 5.0)),complex(-pi/2, Inf)) - @test isequal(asin(complex(-Inf,-5.0)),complex(-pi/2,-Inf)) - @test isequal(asin(complex(-Inf, Inf)),complex(-pi/4, Inf)) - @test isequal(asin(complex(-Inf,-Inf)),complex(-pi/4,-Inf)) - @test isequal(asin(complex(-Inf, NaN)),complex( NaN, Inf)) - - @test isequal(asin(complex( NaN, 0.0)),complex( NaN, NaN)) - @test isequal(asin(complex( NaN, 5.0)),complex( NaN, NaN)) - @test isequal(asin(complex( NaN, Inf)),complex( NaN, Inf)) - @test isequal(asin(complex( NaN,-Inf)),complex( NaN,-Inf)) - @test isequal(asin(complex( NaN, NaN)),complex( NaN, NaN)) -end - -@testset "atanh(op(z)) == op(atanh(z)) for op in (conj, -)" begin - @test isequal(atanh(complex( 0, 0)),complex( 0.0, 0.0)) #integer fallback - @test isequal(atanh(complex( 0.0, 0.0)),complex( 0.0, 0.0)) - @test isequal(atanh(complex( 0.0,-0.0)),complex( 0.0,-0.0)) - @test isequal(atanh(complex( 0.0, NaN)),complex( 0.0, NaN)) - @test isequal(atanh(complex( 0.0, Inf)),complex( 0.0, pi/2)) - @test isequal(atanh(complex( 0.0,-Inf)),complex( 0.0,-pi/2)) - - @test isequal(atanh(complex(-0.0, NaN)),complex(-0.0, NaN)) - @test isequal(atanh(complex(-0.0, 0.0)),complex(-0.0, 0.0)) - @test isequal(atanh(complex(-0.0,-0.0)),complex(-0.0,-0.0)) - @test isequal(atanh(complex(-0.0, Inf)),complex(-0.0, pi/2)) - @test isequal(atanh(complex(-0.0,-Inf)),complex(-0.0,-pi/2)) - - @test isequal(atanh(complex( 1.0, 0.0)),complex( Inf, 0.0)) - @test isequal(atanh(complex(-1.0, 0.0)),complex(-Inf, 0.0)) - @test isequal(atanh(complex( 5.0, Inf)),complex( 0.0, pi/2)) - @test isequal(atanh(complex( 5.0,-Inf)),complex( 0.0,-pi/2)) - @test isequal(atanh(complex( 5.0, NaN)),complex( NaN, NaN)) - @test isequal(atanh(complex(-5.0, Inf)),complex(-0.0, pi/2)) - @test isequal(atanh(complex(-5.0,-Inf)),complex(-0.0,-pi/2)) - @test isequal(atanh(complex(-5.0, NaN)),complex( NaN, NaN)) - - @test isequal(atanh(complex( Inf, 0.0)),complex(0.0, pi/2)) - @test isequal(atanh(complex( Inf,-0.0)),complex(0.0,-pi/2)) - @test isequal(atanh(complex( Inf, 5.0)),complex(0.0, pi/2)) - @test isequal(atanh(complex( Inf,-5.0)),complex(0.0,-pi/2)) - @test isequal(atanh(complex( Inf, Inf)),complex(0.0, pi/2)) - @test isequal(atanh(complex( Inf,-Inf)),complex(0.0,-pi/2)) - @test isequal(atanh(complex( Inf, NaN)),complex(0.0, NaN)) - - @test isequal(atanh(complex(-Inf, 0.0)),complex(-0.0, pi/2)) - @test isequal(atanh(complex(-Inf,-0.0)),complex(-0.0,-pi/2)) - @test isequal(atanh(complex(-Inf, 5.0)),complex(-0.0, pi/2)) - @test isequal(atanh(complex(-Inf,-5.0)),complex(-0.0,-pi/2)) - @test isequal(atanh(complex(-Inf, Inf)),complex(-0.0, pi/2)) - @test isequal(atanh(complex(-Inf,-Inf)),complex(-0.0,-pi/2)) - @test isequal(atanh(complex(-Inf, NaN)),complex(-0.0, NaN)) - - @test isequal(atanh(complex( NaN, 0.0)),complex( NaN, NaN)) - @test isequal(atanh(complex( NaN,-0.0)),complex( NaN, NaN)) - @test isequal(atanh(complex( NaN, 5.0)),complex( NaN, NaN)) - @test isequal(atanh(complex( NaN,-5.0)),complex( NaN, NaN)) - @test isequal(atanh(complex( NaN, Inf)),complex( 0.0, pi/2)) - @test isequal(atanh(complex( NaN,-Inf)),complex( 0.0,-pi/2)) - @test isequal(atanh(complex( NaN, NaN)),complex( NaN, NaN)) -end - -@testset "atan(z) == -i*atanh(iz)" begin - @test isequal(atan(complex( 0.0, 0.0)),complex( 0.0, 0.0)) - @test isequal(atan(complex( 0.0,-0.0)),complex( 0.0,-0.0)) - @test isequal(atan(complex( 0.0, 1.0)),complex( 0.0, Inf)) - @test isequal(atan(complex( 0.0, Inf)),complex( pi/2, 0.0)) - @test isequal(atan(complex( 0.0,-Inf)),complex( pi/2,-0.0)) - @test isequal(atan(complex( 0.0, NaN)),complex( NaN, NaN)) - - @test isequal(atan(complex(-0.0, 0.0)),complex(-0.0, 0.0)) - @test isequal(atan(complex(-0.0,-0.0)),complex(-0.0,-0.0)) - @test isequal(atan(complex(-0.0, Inf)),complex(-pi/2, 0.0)) - @test isequal(atan(complex(-0.0,-Inf)),complex(-pi/2,-0.0)) - @test isequal(atan(complex(-0.0, NaN)),complex( NaN, NaN)) - - @test isequal(atan(complex( 5.0, Inf)),complex( pi/2, 0.0)) - @test isequal(atan(complex( 5.0,-Inf)),complex( pi/2,-0.0)) - @test isequal(atan(complex( 5.0, NaN)),complex( NaN, NaN)) - - @test isequal(atan(complex(-5.0, Inf)),complex(-pi/2, 0.0)) - @test isequal(atan(complex(-5.0,-Inf)),complex(-pi/2,-0.0)) - @test isequal(atan(complex(-5.0, NaN)),complex( NaN, NaN)) - - @test isequal(atan(complex( Inf, 0.0)),complex( pi/2, 0.0)) - @test isequal(atan(complex( Inf,-0.0)),complex( pi/2,-0.0)) - @test isequal(atan(complex( Inf, 5.0)),complex( pi/2, 0.0)) - @test isequal(atan(complex( Inf,-5.0)),complex( pi/2,-0.0)) - @test isequal(atan(complex( Inf, Inf)),complex( pi/2, 0.0)) - @test isequal(atan(complex( Inf,-Inf)),complex( pi/2,-0.0)) - @test isequal(atan(complex( Inf, NaN)),complex( pi/2, 0.0)) - - @test isequal(atan(complex(-Inf, 0.0)),complex(-pi/2, 0.0)) - @test isequal(atan(complex(-Inf,-0.0)),complex(-pi/2,-0.0)) - @test isequal(atan(complex(-Inf, 5.0)),complex(-pi/2, 0.0)) - @test isequal(atan(complex(-Inf,-5.0)),complex(-pi/2,-0.0)) - @test isequal(atan(complex(-Inf, Inf)),complex(-pi/2, 0.0)) - @test isequal(atan(complex(-Inf,-Inf)),complex(-pi/2,-0.0)) - @test isequal(atan(complex(-Inf, NaN)),complex(-pi/2, 0.0)) - - @test isequal(atan(complex( NaN, 0.0)),complex( NaN, 0.0)) - @test isequal(atan(complex( NaN,-0.0)),complex( NaN,-0.0)) - @test isequal(atan(complex( NaN, 5.0)),complex( NaN, NaN)) - @test isequal(atan(complex( NaN,-5.0)),complex( NaN, NaN)) - @test isequal(atan(complex( NaN, Inf)),complex( NaN, 0.0)) - @test isequal(atan(complex( NaN,-Inf)),complex( NaN,-0.0)) - @test isequal(atan(complex( NaN, NaN)),complex( NaN, NaN)) -end - -@testset "lexcmp" begin - @test lexcmp(1.0-1.0im, 1.0+0.0im) == -1 - @test lexcmp(0.0+0.0im, 0.0+0.0im) == 0 - @test lexcmp(1.0-1.0im, 0.0+0.0im) == 1 -end - -# misc. - -@test complex(1//2,1//3)^2 === complex(5//36, 1//3) -@test complex(2,2)^2 === complex(0,8) -@test_throws DomainError complex(2,2)^(-2) -@test complex(2.0,2.0)^(-2) === complex(0.0, -0.125) - -@test complex.(1.0, [1.0, 1.0]) == [complex(1.0, 1.0), complex(1.0, 1.0)] -@test complex.([1.0, 1.0], 1.0) == [complex(1.0, 1.0), complex(1.0, 1.0)] -# robust division of Float64 -# hard complex divisions from Fig 6 of arxiv.1210.4539 -z7 = Complex{Float64}(3.898125604559113300e289, 8.174961907852353577e295) -z9 = Complex{Float64}(0.001953125, -0.001953125) -z10 = Complex{Float64}( 1.02951151789360578e-84, 6.97145987515076231e-220) -harddivs = ((1.0+im*1.0, 1.0+im*2^1023.0, 2^-1023.0-im*2^-1023.0), #1 - (1.0+im*1.0, 2^-1023.0+im*2^-1023.0, 2^1023.0+im*0.0), #2 - (2^1023.0+im*2^-1023.0, 2^677.0+im*2^-677.0, 2^346.0-im*2^-1008.0), #3 - (2^1023.0+im*2^1023.0, 1.0+im*1.0, 2^1023.0+im*0.0), #4 - (2^1020.0+im*2^-844., 2^656.0+im*2^-780.0, 2^364.0-im*2^-1072.0), #5 - (2^-71.0+im*2^1021., 2^1001.0+im*2^-323.0, 2^-1072.0+im*2^20.0), #6 - (2^-347.0+im*2^-54., 2^-1037.0+im*2^-1058.0, z7), #7 - (2^-1074.0+im*2^-1074., 2^-1073.0+im*2^-1074., 0.6+im*0.2), #8 - (2^1015.0+im*2^-989., 2^1023.0+im*2^1023.0, z9), #9 - (2^-622.0+im*2^-1071., 2^-343.0+im*2^-798.0, z10) #10 - ) - -# calculate "accurate bits" in range 0:53 by algorithm given in arxiv.1210.4539 -function sb_accuracy(x,expected) - min(logacc(real(x),real(expected)), - logacc(imag(x),imag(expected))) -end -relacc(x,expected) = abs(x-expected)/abs(expected) -function logacc(x::Float64,expected::Float64) - x == expected && (return 53) - expected == 0 && (return 0) - (x == Inf || x == -Inf) && (return 0) - isnan(x) && (return 0) - ra = relacc(BigFloat(x),BigFloat(expected)) - max(floor(Int,-log2(ra)),0) -end -# the robust division algorithm should have 53 or 52 -# bits accuracy for each of the hard divisions -@test 52 <= minimum([sb_accuracy(h[1]/h[2],h[3]) for h in harddivs]) - -# division of non-Float64 -function cdiv_test(a,b) - c=convert(Complex{Float64},a)/convert(Complex{Float64},b) - 50 <= sb_accuracy(c,convert(Complex{Float64},a/b)) -end -@test cdiv_test(complex(1//2, 3//4), complex(17//13, 4//5)) -@test cdiv_test(complex(1,2), complex(8997,2432)) - -@testset "inv" begin - @test inv(1e300+0im) == 1e-300 - 0.0im - @test inv(0+1e300im) == 0.0 - 1e-300im -end - -@testset "issue #7904" begin - @test log10(10+0im) === 1.0 + 0.0im - @test log2(2+0im) === 1.0 + 0.0im -end - -@testset "sign" begin - for T in (Float32, Float64) - z = Complex{T}(1) - @test typeof(sign(z)) == typeof(z) - z = Complex{T}(0) - @test typeof(sign(z)) == typeof(z) - end - for T in (Int32, Int64) - z = Complex{T}(1) - @test typeof(sign(z)) == typeof(float(z)) - z = Complex{T}(0) - @test typeof(sign(z)) == typeof(float(z)) - end - - @test sign(0 + 0im) == 0 - @test sign(2 + 0im) == 1 - @test sign(-2 + 0im) == -1 - @test sign(1 + im) ≈ (1 + im) / sqrt(2) - @test sign(1 - im) ≈ (1 - im) / sqrt(2) - - for T in (Float16, Float32, Float64) - z = Complex(zero(T), zero(T)) - @test sign(z) === z - @test sign(-z) === -z - @test sign(conj(z)) === conj(z) - @test sign(-conj(z)) === -conj(z) - end -end - -@testset "cis" begin - @test cis(0.0+1.0im) ≈ 0.367879441171442321595523770161460867445811131031767834507836+0.0im - @test cis(1.0+0.0im) ≈ 0.54030230586813971740093660744297660373231042061+0.84147098480789650665250232163029899962256306079im - @test cis(pi) ≈ -1.0+0.0im - @test cis(pi/2) ≈ 0.0+1.0im -end - -@testset "exp2" begin - @test exp2(0.0+0.0im) == 1.0+0.0im - @test exp2(1.0+0.0im) == 2.0+0.0im - #wolframalpha - @test exp2(1.0+3.0im) ≈ -0.9739888359315627962096198412+1.74681016354974281701922im - @test exp2(im) ≈ 0.7692389013639721 + 0.6389612763136348im -end - -@testset "exp10" begin - @test exp10(0.0+0.0im) == 1.0+0.0im - @test exp10(1.0+0.0im) == 10.0+0.0im - #wolframalpha - @test exp10(1.0+2.0im) ≈ -1.0701348355877020772086517528518239460495529361-9.9425756941378968736161937190915602112878340717im - @test exp10(im) ≈ -0.6682015101903132 + 0.7439803369574931im -end - -@testset "round and float, PR #8291" begin - @test round(Complex(1.125, 0.875), 2) == Complex(1.12, 0.88) - @test round(Complex(1.5, 0.5), RoundDown, RoundUp) == Complex(1.0, 1.0) - @test round.([1:5;] + im) == [1:5;] + im - @test round.([1:5;] + 0.5im) == [1.0:5.0;] - - @test float(Complex(1, 2)) == Complex(1.0, 2.0) - @test round(float(Complex(π, e)),3) == Complex(3.142, 2.718) -end - -@testset "Complex32 arithmetic, PR #10003" begin - @test Float16(1)+Float16(1)im === Complex32(1, 1) - @test Float16(1)-Float16(1)im === Float16(1)+Float16(-1)im === Complex32(1, -1) - @test Float16(1)*im === Complex32(im) - @test Float16(1)/im === Complex32(0,-1) - @test Float16(1)^im === Complex32(1) === Float16(1)+Float16(0)im -end - -# issue/PR #10148 -@test typeof(Int8(1) - im) == Complex{Int8} - -# issue #10926 -@test typeof(π - 1im) == Complex{Float64} - -@testset "issue #15969" begin - # specialized muladd for complex types - for x in (3, 3+13im), y in (2, 2+7im), z in (5, 5+11im) - @test muladd(x,y,z) === x*y + z - end -end - -@testset "issue #11839" begin - # type stability for Complex{Int64} - let x = 1+im - @inferred sin(x) - @inferred cos(x) - @inferred norm(x) - @inferred vecnorm(x) - end -end - -@testset "issue #18785" begin - # type stability for exp, expm1 for Complex{Int64} - let x = 2*im - @inferred exp(x) - @inferred expm1(x) - end -end - -# issue #19240 -@test big(1)/(10+10im) ≈ (5-5im)/big(100) ≈ big"0.05" - big"0.05"*im - -@testset "Complex Irrationals, issue #21204" begin - for x in (pi, e, catalan) # No need to test all of them - z = Complex(x, x) - @test typeof(z) == Complex{typeof(x)} - @test exp(z) ≈ exp(x) * cis(x) - @test exp2(z) ≈ exp(z * log(2)) - @test exp10(z) ≈ exp(z * log(10)) - end -end - -@testset "expm1 type stability" begin - x = @inferred expm1(0.1im) - @test x isa Complex128 - x = @inferred expm1(0.1f0im) - @test x isa Complex64 -end - -@testset "array printing with exponent format" begin - a = [1.0 + 1e-10im, 2.0e-15 - 2.0e-5im, 1.0e-15 + 2im, 1.0 + 2e-15im] - @test sprint((io, x) -> show(io, MIME("text/plain"), x), a) == - join([ - "4-element Array{Complex{Float64},1}:", - " 1.0+1.0e-10im", - " 2.0e-15-2.0e-5im ", - " 1.0e-15+2.0im ", - " 1.0+2.0e-15im"], "\n") -end diff --git a/julia-0.6.3/share/julia/test/copy.jl b/julia-0.6.3/share/julia/test/copy.jl deleted file mode 100644 index ae7ce7d..0000000 --- a/julia-0.6.3/share/julia/test/copy.jl +++ /dev/null @@ -1,144 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -mainres = ([4, 5, 3], - [1, 5, 3]) -bitres = ([true, true, false], - [false, true, false]) - -chnlprod(x) = Channel(c->for i in x; put!(c,i); end) - -for (dest, src, bigsrc, emptysrc, res) in [ - ([1, 2, 3], () -> [4, 5], () -> [1, 2, 3, 4, 5], () -> Int[], mainres), - ([1, 2, 3], () -> 4:5, () -> 1:5, () -> 1:0, mainres), - ([1, 2, 3], () -> chnlprod(4:5), () -> chnlprod(1:5), () -> chnlprod(1:0), mainres), - (falses(3), () -> trues(2), () -> trues(5), () -> trues(0), bitres)] - - @test copy!(copy(dest), src()) == res[1] - @test copy!(copy(dest), 1, src()) == res[1] - @test copy!(copy(dest), 2, src(), 2) == res[2] - @test copy!(copy(dest), 2, src(), 2, 1) == res[2] - - @test copy!(copy(dest), 99, src(), 99, 0) == dest - - @test copy!(copy(dest), 1, emptysrc()) == dest - x = emptysrc() - exc = isa(x, AbstractArray) ? BoundsError : ArgumentError - @test_throws exc copy!(dest, 1, emptysrc(), 1) - - for idx in (0, 4) - @test_throws BoundsError copy!(dest, idx, src()) - @test_throws BoundsError copy!(dest, idx, src(), 1) - @test_throws BoundsError copy!(dest, idx, src(), 1, 1) - x = src() - exc = isa(x, AbstractArray) ? BoundsError : ArgumentError - @test_throws exc copy!(dest, 1, x, idx) - x = src() - exc = isa(x, AbstractArray) ? BoundsError : ArgumentError - @test_throws exc copy!(dest, 1, x, idx, 1) - end - - @test_throws ArgumentError copy!(dest, 1, src(), 1, -1) - - @test_throws BoundsError copy!(dest, bigsrc()) - - @test_throws BoundsError copy!(dest, 3, src()) - @test_throws BoundsError copy!(dest, 3, src(), 1) - @test_throws BoundsError copy!(dest, 3, src(), 1, 2) - - @test_throws BoundsError copy!(dest, 1, src(), 2, 2) -end - -let A = reshape(1:6, 3, 2), B = similar(A) - RA = CartesianRange(indices(A)) - copy!(B, RA, A, RA) - @test B == A -end -let A = reshape(1:6, 3, 2), B = zeros(8,8) - RA = CartesianRange(indices(A)) - copy!(B, CartesianRange((5:7,2:3)), A, RA) - @test B[5:7,2:3] == A - B[5:7,2:3] = 0 - @test all(x->x==0, B) -end - - -# test behavior of shallow and deep copying -let a = Any[[1]], q = QuoteNode([1]) - ca = copy(a); dca = @inferred(deepcopy(a)) - @test ca !== a - @test ca[1] === a[1] - @test dca !== a - @test dca[1] !== a[1] - @test deepcopy(q).value !== q.value -end - -# issue #13124 -let a = rand(3, 5) - b = (a,a) - c = deepcopy(b) - @test c[1] === c[2] -end - -# issue #14027 -@test isnull(deepcopy(Nullable{Array}())) - -# issue #15250 -let a1 = Core.svec(1, 2, 3, []), a2 = Core.svec(1, 2, 3) - a3 = Core.svec(a1,a1) - b1 = deepcopy(a1) - @test a1 == b1 - @test a1 !== b1 - @test a1[4] !== b1[4] - b2 = deepcopy(a2) - @test a2 === b2 - b3 = deepcopy(a3) - @test a3 == b3 - @test a3 !== b3 - @test a3[1] === a3[2] -end - -# issue #16667 -let x = BigInt[1:1000;], y = deepcopy(x), v - # Finalize the original values to make sure the deep copy is indeed - # independent - for v in x - finalize(v) - end - # Allocate some memory to make it more likely to trigger an error - # if `deepcopy` went wrong - x = BigInt[1:1000;] - @test y == x -end -let x = BigFloat[1:1000;], y, z, v - y, z = setprecision(2) do - deepcopy(x), BigFloat[1:1000;] - end - for v in x - finalize(v) - end - x = BigFloat[1:1000;] - # Make sure the difference in precision doesn't affect deep copy - @test y == x - # Check that the setprecision indeed does something - @test z != x -end - -# issue #19921 -mutable struct Foo19921 - a::String -end - -mutable struct Bar19921 - foo::Foo19921 - fooDict::Dict{Foo19921, Int64} -end - -@testset "issue 19921" begin - for i = 1 : 100 - foo = Foo19921("foo") - bar = Bar19921(foo, Dict(foo => 3)) - bar2 = deepcopy(bar) - @test bar2.foo ∈ keys(bar2.fooDict) - @test bar2.fooDict[bar2.foo] != nothing - end -end diff --git a/julia-0.6.3/share/julia/test/core.jl b/julia-0.6.3/share/julia/test/core.jl deleted file mode 100644 index c98cbe9..0000000 --- a/julia-0.6.3/share/julia/test/core.jl +++ /dev/null @@ -1,5020 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -# test core language features -const Bottom = Union{} - -# For curmod_* -include("testenv.jl") - -f47{T}(x::Vector{Vector{T}}) = 0 -@test_throws MethodError f47(Array{Vector}(0)) -@test f47(Array{Vector{Int}}(0)) == 0 - -# checking unionall and typevar components -@test_throws TypeError ([] where T) -@test_throws TypeError ([T] where T) -@test_throws TypeError (Array{T} where T<:[]) -@test_throws TypeError (Array{T} where T>:[]) -@test_throws TypeError (Array{T} where T<:Vararg) -@test_throws TypeError (Array{T} where T>:Vararg) -@test_throws TypeError (Array{T} where T<:Vararg{Int}) -@test_throws TypeError (Array{T} where T<:Vararg{Int,2}) - -# issue #12939 -module Issue12939 -abstract type Abs; end -struct Foo <: Abs; end -struct Bar; val::Int64; end -struct Baz; val::Int64; end -f{T}(::Type{T}, x::T) = T(3) -f{T <: Abs}(::Type{Bar}, x::T) = Bar(2) -f(::Type{Bar}, x) = Bar(1) -f(::Type{Baz}, x) = Baz(1) -f{T <: Abs}(::Type{Baz}, x::T) = Baz(2) -end - -@test Issue12939.f(Issue12939.Baz,Issue12939.Foo()) === Issue12939.Baz(2) -@test Issue12939.f(Issue12939.Bar,Issue12939.Foo()) === Issue12939.Bar(2) - -# issue #11840 -TT11840{T} = Tuple{T,T} -f11840(::Type) = "Type" -f11840(::DataType) = "DataType" -f11840(::UnionAll) = "UnionAll" -f11840{T<:Tuple}(::Type{T}) = "Tuple" -@test f11840(Type) == "UnionAll" -@test f11840(Type.body) == "DataType" -@test f11840(Union{Int,Int8}) == "Type" -@test f11840(Tuple) == "Tuple" -@test f11840(TT11840) == "Tuple" - -g11840(::DataType) = 1 -g11840(::Type) = 2 -g11840{T<:Tuple}(sig::Type{T}) = 3 -@test g11840(Vector.body) == 1 -@test g11840(Vector) == 2 -@test g11840(Vector.body) == 1 -@test g11840(Vector) == 2 -@test g11840(Tuple) == 3 -@test g11840(TT11840) == 3 - -g11840b(::DataType) = 1 -g11840b(::Type) = 2 -# FIXME (needs a test): how to compute that the guard entry is still required, -# even though Type{Vector} ∩ DataType = Bottom and this method would set -# cache_with_orig = true -g11840b{T<:Tuple}(sig::Type{T}) = 3 -@test g11840b(Vector) == 2 -@test g11840b(Vector.body) == 1 -@test g11840b(Vector) == 2 -@test g11840b(Vector.body) == 1 -@test g11840b(Tuple) == 3 -@test g11840b(TT11840) == 3 - -h11840(::DataType) = '1' -h11840(::Type) = '2' -h11840(::UnionAll) = '3' -h11840{T<:Tuple}(::Type{T}) = '4' -@test h11840(Vector) == '3' -@test h11840(Vector.body) == '1' -@test h11840(Vector) == '3' -@test h11840(Union{Vector, Matrix}) == '2' -@test h11840(Union{Vector.body, Matrix.body}) == '2' -@test h11840(Tuple) == '4' -@test h11840(TT11840) == '4' - -# issue #20511 -f20511(x::DataType) = 0 -f20511(x) = 1 -Type{Integer} # cache this -@test f20511(Union{Integer,T} where T <: Unsigned) == 1 - -# join -@test typejoin(Int8,Int16) === Signed -@test typejoin(Int,AbstractString) === Any -@test typejoin(Array{Float64},BitArray) <: AbstractArray -@test typejoin(Array{Bool},BitArray) <: AbstractArray{Bool} -@test typejoin(Tuple{Int,Int8},Tuple{Int8,Float64}) === Tuple{Signed,Real} -@test Base.typeseq(typejoin(Tuple{String,String},Tuple{DirectIndexString,String}, - Tuple{String,DirectIndexString},Tuple{Int,String,Int}), - Tuple{Any,AbstractString,Vararg{Int}}) -@test Base.typeseq(typejoin(Tuple{Int8,Vararg{Int}},Tuple{Int8,Int8}), - Tuple{Int8,Vararg{Signed}}) -@test Base.typeseq(typejoin(Tuple{Int8,Vararg{Int}},Tuple{Int8,Vararg{Int8}}), - Tuple{Int8,Vararg{Signed}}) -@test Base.typeseq(typejoin(Tuple{Int8,UInt8,Vararg{Int}},Tuple{Int8,Vararg{Int8}}), - Tuple{Int8,Vararg{Integer}}) -@test Base.typeseq(typejoin(Union{Int,AbstractString},Int), Union{Int,AbstractString}) -@test Base.typeseq(typejoin(Union{Int,AbstractString},Int8), Any) - -# typejoin associativity -abstract type Foo____{K} end -mutable struct Wow____{K,V} <: Foo____{K} end -mutable struct Bar____{K,V} <: Foo____{K} end -let - a = Wow____{Int64, Int64} - b = Wow____{Int64, Float64} - c = Bar____{Int64, Int64} - @test typejoin(typejoin(b,c), a) == typejoin(typejoin(b,a), c) == Foo____{Int64} -end - -# typejoin with Vararg{T,N} -@test typejoin(Tuple{Vararg{Int,2}}, Tuple{Int,Int,Int}) === Tuple{Int,Int,Vararg{Int}} -@test typejoin(Tuple{Vararg{Int,2}}, Tuple{Vararg{Int}}) === Tuple{Vararg{Int}} - -@test promote_type(Bool,Bottom) === Bool - -# ntuples -nttest1{n}(x::NTuple{n,Int}) = n -@test nttest1(()) == 0 -@test nttest1((1,2)) == 2 -@test NTuple <: Tuple -@test (NTuple{T,Int32} where T) <: Tuple{Vararg{Int32}} -@test !((NTuple{T,Int32} where T) <: Tuple{Int32,Vararg{Int32}}) -@test Tuple{Vararg{Int32}} <: (NTuple{T,Int32} where T) -@test Tuple{Int32,Vararg{Int32}} <: (NTuple{T,Int32} where T) - -# #17198 -@test_throws MethodError convert(Tuple{Int}, (1.0, 2.0, 3.0)) -# #21238 -@test_throws MethodError convert(Tuple{Int,Int,Int}, (1, 2)) - -# type declarations - -abstract type Sup_{A,B} end -abstract type Qux_{T} <: Sup_{Qux_{Int},T} end - -@test Qux_{Int}.super <: Sup_ -@test ===(Qux_{Int}, Qux_{Int}.super.parameters[1]) -@test ===(Qux_{Int}.super.parameters[2], Int) -@test Qux_{Char}.super <: Sup_ -@test ===(Qux_{Int}, Qux_{Char}.super.parameters[1]) -@test ===(Qux_{Char}.super.parameters[2], Char) - -@test Qux_.body.super.parameters[1].super <: Sup_ -@test ===(Qux_{Int}, Qux_.body.super.parameters[1].super.parameters[1]) -@test ===(Int, Qux_.body.super.parameters[1].super.parameters[2]) - -mutable struct Foo_{T} x::Foo_{Int} end - -@test ===(Foo_.body.types[1], Foo_{Int}) -@test ===(Foo_.body.types[1].types[1], Foo_{Int}) - -mutable struct Circ_{T} x::Circ_{T} end -@test ===(Circ_{Int}, Circ_{Int}.types[1]) - -abstract type Sup2a_ end -abstract type Sup2b_{A <: Sup2a_, B} <: Sup2a_ end -@test_throws ErrorException @eval abstract type Qux2_{T} <: Sup2b_{Qux2_{Int}, T} end # wrapped in eval to avoid #16793 - -# issue #21923 -struct A21923{T,N}; v::Vector{A21923{T}}; end -@test fieldtype(A21923,1) == Vector{A21923{T}} where T -struct B21923{T,N}; v::Vector{B21923{T,M} where M}; end -@test fieldtype(B21923, 1) == Vector{B21923{T,M} where M} where T -struct C21923{T,N}; v::C21923{T,M} where M; end -@test fieldtype(C21923, 1) == C21923 -struct D21923{T,N}; v::D21923{T}; end -@test fieldtype(D21923, 1) == D21923 - -# issue #22624, more circular definitions -struct T22624{A,B,C}; v::Vector{T22624{Int64,A}}; end -let elT = T22624.body.body.body.types[1].parameters[1] - @test elT == T22624{Int64, T22624.var, C} where C - elT2 = elT.body.types[1].parameters[1] - @test elT2 == T22624{Int64, Int64, C} where C - @test elT2.body.types[1].parameters[1] === elT2 - @test isleaftype(elT2.body.types[1]) -end - -# issue #3890 -mutable struct A3890{T1} - x::Matrix{Complex{T1}} -end -@test A3890{Float64}.types[1] === Array{Complex{Float64},2} -# make sure the field type Matrix{Complex{T1}} isn't cached -mutable struct B3890{T2} - x::Matrix{Complex{T2}} -end -@test B3890{Float64}.types[1] === Array{Complex{Float64},2} - -# issue #786 -mutable struct Node{T} - v::Vector{Node} -end - -@test ===(Node{Int}.types[1].parameters[1], Node) - -mutable struct Node2{T} - v::Vector{Node2{T}} -end - -@test ===(Node2{Int}.types[1].parameters[1], Node2{Int}) - -mutable struct FooFoo{A,B} y::FooFoo{A} end - -@test FooFoo{Int} <: FooFoo{Int,AbstractString}.types[1] - - -let x = (2,3) - @test +(x...) == 5 -end - -# conversions -function fooo() - local x::Int8 - x = 100 - x -end -@test fooo() === convert(Int8,100) -function fooo_2() - local x::Int8 - x = 100 -end -@test fooo_2() === 100 -function fooo_3() - local x::Int8 - y = x = 100 - @test isa(x,Int8) - y -end -@test fooo_3() === 100 -let - function foo() - local x::Int8 - function bar() - x = 100 - end - bar() - x - end - @test foo() === convert(Int8,100) -end - -function bar{T}(x::T) - local z::Complex{T} - z = x - z -end -@test bar(3.0) == Complex(3.0,0.0) - -z = convert(Complex{Float64},2) -@test z == Complex(2.0,0.0) - -function typeassert_instead_of_decl() - local x - x = 1 - x::Float64 - return 0 -end -@test_throws TypeError typeassert_instead_of_decl() - -# type declarations on globals not implemented yet -@test_throws ErrorException eval(parse("global x20327::Int")) - -y20327 = 1 -@test_throws TypeError y20327::Float64 - -# misc -fib(n) = n < 2 ? n : fib(n-1) + fib(n-2) -@test fib(20) == 6765 - -# static parameters -sptest1{T}(x::T, y::T) = 42 -sptest1{T,S}(x::T, y::S) = 43 -@test sptest1(1,2) == 42 -@test sptest1(1,"b") == 43 - -sptest2{T}(x::T) = T -@test ===(sptest2(:a),Symbol) - -sptest3{T}(x::T) = y->T -let m = sptest3(:a) - @test ===(m(0),Symbol) -end - -sptest4{T}(x::T, y::T) = 42 -sptest4{T}(x::T, y) = 44 -@test sptest4(1,2) == 42 -@test sptest4(1, "cat") == 44 - -# closures -function clotest() - c = 0 - function inc() - c += 1 - end - function dec() - c -= 1 - end - inc(); inc() - @test c == 2 - dec() - @test c == 1 - @test (()->c)() == 1 - - fibb(n) = n < 2 ? n : fibb(n-1)+fibb(n-2) - @test fibb(10) == 55 - - return (n->(c+=n), ()->c) -end -let T = clotest() - (inc, C) = T - inc(11) - @test C() == 12 -end - -Yc(f) = (h->f(x->h(h)(x)))(h->f(x->h(h)(x))) -yfib = Yc(fib->(n->(n < 2 ? n : fib(n-1) + fib(n-2)))) -@test yfib(20) == 6765 - -function capt_before_def() - f() = y - y = 2 - f -end -@test capt_before_def()() == 2 - -function i18408() - local i - x->i -end -let f = i18408() - @test_throws UndefRefError f(0) -end - -# issue #23558 -c23558(n,k) = - let fact(n) = if (n == 0) 1 else n*fact(n-1) end - fact(n)/fact(k)/fact(n-k) - end -@test c23558(10, 5) == 252 - -# issue #23996 -function foo23996(xs...) - rets = [] - bar(::Int) = push!(rets, 1) - foobar() = push!(rets, 3) - bar(::AbstractFloat) = push!(rets, 2) - bar(::Bool) = foobar() - for x in xs - bar(x) - end - rets -end -@test foo23996(1,2.0,false) == [1,2,3] - -# variable scope, globals -glob_x = 23 -function glotest() - global glob_x - glob_x = 24 - loc_x = 8 - function inner() - global loc_x = 10 - glob_x = 88 - end - function inner2() - local glob_x # override - global loc_x - glob_x = 2 - @test glob_x == 2 - @test loc_x == 10 - end - inner() - inner2() - @test glob_x == 88 - @test loc_x == 8 -end -glotest() -@test glob_x == 88 -@test loc_x == 10 - -# issue #7234 -f7234_cnt = 0 -begin - glob_x2 = 24 - function f7234_a() - global f7234_cnt += 1 - glob_x2 += 1 - global f7234_cnt += -10000 - end -end -@test_throws UndefVarError f7234_a() -@test f7234_cnt == 1 -begin - global glob_x2 = 24 - function f7234_b() - global f7234_cnt += 1 - glob_x2 += 1 - global f7234_cnt += -10000 - end -end -@test_throws UndefVarError f7234_b() -@test f7234_cnt == 2 -# existing globals can be inherited by non-function blocks -for i = 1:2 - glob_x2 += 1 -end -@test glob_x2 == 26 -# globals declared as such in a non-global scope are inherited -let - global glob_x3 = 11 - f7234_2() = (glob_x3 += 1) - f7234_2() -end -@test glob_x3 == 12 - -# interaction between local variable renaming and nested globals (#19333) -x19333 = 1 -function f19333(x19333) - return let x19333 = x19333 - g19333() = (global x19333 += 2) - g19333() + (x19333 += 1) - end + (x19333 += 1) -end -@test f19333(0) == 5 -@test f19333(0) == 7 -@test x19333 == 5 - -function h19333() - s = 0 - for (i, j) in ((1, 2),) - s += i + j # use + as a global - end - for (k, +) in ((3, 4),) - s -= (k - +) # use + as a local - end - return s -end -@test h19333() == 4 - -# let - new variables, including undefinedness -let_undef_cnt = 0 -function let_undef() - first = true - for i = 1:2 - let x # new x - if first # not defined on second pass - x = 1 - first = false - end - global let_undef_cnt += 1 - x + 1 - global let_undef_cnt += 23 - end - end -end -@test_throws UndefVarError let_undef() -@test let_undef_cnt == 25 - -# const implies local in a local scope block -function const_implies_local() - let - x = 1 - local y - let - const x = 0 - y = x - end - x, y - end -end -@test const_implies_local() === (1, 0) - -a = Vector{Any}(3) -for i=1:3 - let ii = i - a[i] = x->x+ii - end -end -@test a[1](10) == 11 -@test a[2](10) == 12 -@test a[3](10) == 13 - -# issue #22032 -let a = [], fs = [] - for f() in 1:3 - push!(a, f()) - push!(fs, f) - end - @test a == [1,2,3] - @test [f() for f in fs] == [1,2,3] -end -let t = (22,33) - (g(), x) = t - @test g() == 22 - @test x == 33 -end - -# issue #23091 -let (f(), x) = (1, 2) - @test f() == 1 - @test x == 2 -end - -# issue #21900 -f21900_cnt = 0 -function f21900() - for i = 1:1 - x = 0 - end - global f21900_cnt += 1 - x - global f21900_cnt += -1000 - nothing -end -@test_throws UndefVarError f21900() -@test f21900_cnt == 1 - -@test_throws UndefVarError @eval begin - for i21900 = 1:10 - for j21900 = 1:10 - foo21900 = 10 - end - bar21900 = 0 - bar21900 = foo21900 + 1 - end -end -@test !isdefined(:foo21900) -@test !isdefined(:bar21900) -bar21900 = 0 -@test_throws UndefVarError @eval begin - for i21900 = 1:10 - for j21900 = 1:10 - foo21900 = 10 - end - bar21900 = -1 - bar21900 = foo21900 + 1 - end -end -@test bar21900 == -1 -@test !isdefined(:foo21900) -foo21900 = 0 -@test nothing === @eval begin - for i21900 = 1:10 - for j21900 = 1:10 - foo21900 = 10 - end - bar21900 = -1 - bar21900 = foo21900 + 1 - end -end -@test foo21900 == 10 -@test bar21900 == 11 - -# ? syntax -@test (true ? 1 : false ? 2 : 3) == 1 - -# issue #7252 -let - local a - 1 > 0 ? a=2 : a=3 - @test a == 2 - 1 < 0 ? a=2 : a=3 - @test a == 3 -end - -# tricky space sensitive syntax cases -@test [-1 ~1] == [(-1) (~1)] - -# undefinedness -mutable struct UndefField - field - UndefField() = new() -end - -let - local a - a = UndefField() - @test !isdefined(a, :field) - @test !isdefined(a, :foo) - @test !isdefined(2, :a) - - @test_throws TypeError isdefined(2) -end - -let - local a - a = Vector{Any}(2) - @test !isassigned(a,1) && !isassigned(a,2) - a[1] = 1 - @test isassigned(a,1) && !isassigned(a,2) - a = Array{Float64}(1) - @test isassigned(a,1) - @test isassigned(a) - @test !isassigned(a,2) -end - -# isassigned, issue #11167 -mutable struct Type11167{T,N} end -Type11167{Int,2} -let tname = Type11167.body.body.name - @test !isassigned(tname.cache, 0) - @test isassigned(tname.cache, 1) - @test !isassigned(tname.cache, 2) - Type11167{Float32,5} - @test isassigned(tname.cache, 2) - @test !isassigned(tname.cache, 3) -end - -# dispatch -let - local foo, foo2, fooN, bar, baz - foo(x::Tuple{Vararg{Any}}) = 0 - foo(x::Tuple{Vararg{Integer}}) = 1 - @test foo((:a,)) == 0 - @test foo(( 2,)) == 1 - - foo2(x::Vararg{Any,2}) = 2 - @test foo2(1,2) == 2 - @test_throws MethodError foo2(1) - @test_throws MethodError foo2(1,2,3) - - fooN{T,N}(A::Array{T,N}, x::Vararg{Any,N}) = -1 - @test fooN([1,2], 1) == -1 - @test_throws MethodError fooN([1,2], 1, 2) == -1 - @test fooN([1 2; 3 4], 1, 2) == -1 - @test_throws MethodError fooN([1 2; 3 4], 1) - @test_throws MethodError fooN([1 2; 3 4], 1, 2, 3) - - bar{T}(x::Tuple{T,T,T,T})=1 - bar(x::Tuple{Any,Any,Any,Any})=2 - @test bar((1,1,1,1)) == 1 - @test bar((1,1,1,"a")) == 2 - @test bar((:a,:a,:a,:a)) == 1 - - baz(::Type{Rational}) = 1 - baz{T}(::Type{Rational{T}}) = 2 - @test baz(Rational) == 1 - @test baz(Rational{Int}) == 2 -end - -let - local mytype - function mytype(vec) - convert(Vector{Tuple{String, DataType}}, vec) - end - some_data = Any[("a", Int32), ("b", Int32)] - @test isa(mytype(some_data),Vector{Tuple{String, DataType}}) -end - -mutable struct MyArray{N} <: AbstractArray{Int, N} -end -let - local x - x = MyArray{1}() - foob(x::AbstractArray)=0 - foob{T}(x::AbstractVector{T})=1 - @test foob(x) == 1 -end - -let - local f, g, a - f{T}(a::Vector{Vector{T}}) = a - g{T}(a::Vector{Vector{T}}) = a - a = Vector{Int}[] - @test ===(f(a), a) - @test ===(g(a), a) -end - -mutable struct _AA{T}; a::T; end -_AoA{T} = _AA{_AA{T}} -let - local g, a - g{T}(a::_AA{_AA{T}}) = a - a = _AA(_AA(1)) - @test ===(g(a),a) -end - -# dispatch using Val{T}. See discussion in #9452 for instances vs types -let - local firstlast - firstlast(::Type{Val{true}}) = "First" - firstlast(::Type{Val{false}}) = "Last" - - @test firstlast(Val{true}) == "First" - @test firstlast(Val{false}) == "Last" -end - -# x::Vararg{Any} declarations -let - local f1, f2, f3 - f1(x...) = [x...] - f2(x::Vararg{Any}) = [x...] - f3(x::Vararg) = [x...] - @test f1(1,2,3) == [1,2,3] - @test f2(1,2,3) == [1,2,3] - @test f3(1,2,3) == [1,2,3] -end - -# try/finally -begin - after = 0 - b = try - 1+2 - finally - after = 1 - end - @test b == 3 - @test after == 1 - - after = 0 - gothere = 0 - try - try - error(" ") - finally - after = 1 - end - gothere = 1 - end - @test after == 1 - @test gothere == 0 - - after = 0 - b = try - error(" ") - catch - 42 - finally - after = 1 - end - @test b == 42 - @test after == 1 - - glo = 0 - function retfinally() - try - return 5 - finally - global glo = 18 - end - end - @test retfinally() == 5 - @test glo == 18 - - @test try error() end === nothing -end - -# finalizers -let A = [1] - local x = 0 - finalizer(A, a->(x+=1)) - finalize(A) - @test x == 1 - A = 0 - gc(); gc() - @test x == 1 -end - -# Module() constructor -@test names(Module(:anonymous), true, true) == [:anonymous] -@test names(Module(:anonymous, false), true, true) == [:anonymous] - -# exception from __init__() -let didthrow = - try - include_string( - """ - module TestInitError - __init__() = error() - end - """) - false - catch ex - @test isa(ex, LoadError) - @test isa(ex.error, InitError) - true - end - @test didthrow -end - -# issue #7307 -function test7307(a, ret) - try - try - ret && return a - finally - push!(a, "inner") - end - finally - push!(a, "outer") - end - return a -end -@test test7307([], true) == ["inner","outer"] -@test test7307([], false) == ["inner","outer"] - -# issue #8277 -function test8277(a) - i = 0 - for j=1:2 - try - if i == 0 - push!(a,0) - end - i += 1 - error() - catch - end - end -end -let a = [] - test8277(a) - @test length(a) == 1 -end - -# chained and multiple assignment behavior (issue #2913) -let - local x, a, b, c, d, e - x = (a,b,b,b,e) = (1,2,3,4,5) - @test x === (1,2,3,4,5) - @test a == 1 - @test b == 4 - @test e == 5 - x = (a,b,b,e) = (1,2,3,4,5) - @test x === (1,2,3,4,5) - @test a == 1 - @test b == 3 - @test e == 4 - - a = complex(1,2) - b = 3 - b, a = a.re, b - @test b == 1 - @test a == 3 - a = complex(1,2) - b = 3 - a, b = b, a.re - @test a == 3 - @test b == 1 -end - -# accessing fields by index -let - local z = complex(3, 4) - v = Int[0,0] - for i=1:2 - v[i] = getfield(z, i) - end - @test v == [3,4] - @test_throws BoundsError getfield(z, -1) - @test_throws BoundsError getfield(z, 0) - @test_throws BoundsError getfield(z, 3) - - strct = LoadError("", 0, "") - setfield!(strct, 2, 8) - @test strct.line == 8 - setfield!(strct, 3, "hi") - @test strct.error == "hi" - setfield!(strct, 1, "yo") - @test strct.file == "yo" - @test_throws BoundsError getfield(strct, 10) - @test_throws BoundsError setfield!(strct, 0, "") - @test_throws BoundsError setfield!(strct, 4, "") -end - -# allow typevar in Union to match as long as the arguments contain -# sufficient information -# issue #814 -let - local MatOrNot, my_func, M - MatOrNot{T} = Union{AbstractMatrix{T}, Vector{Union{}}} - my_func{T<:Real}(A::MatOrNot{T}, B::MatOrNot{T}, C::MatOrNot{T}) = 0 - M = [ 2. 1. ; 1. 1. ] - @test my_func(Union{}[], M, M) == 0 -end - -let - local my_func, a, c - my_func{T}(P::Vector{T}, Q::Vector{T}) = 0 - my_func{T}(x::T, P::Vector{T}) = 1 - my_func{T}(P::Vector{T}, x::T) = 2 - a = Int[3] - c = Vector[a] - - @test my_func(c,c)==0 - @test my_func(a,c)==1 -end - -let - local baar, foor, boor - # issue #1131 - baar(x::DataType) = 0 - baar(x::Union) = 1 - baar(x::UnionAll) = 2 - @test baar(StridedArray) == 2 - @test baar(Base.unwrap_unionall(StridedArray)) == 1 - @test baar(Vector) == 2 - @test baar(Vector.body) == 0 - - boor(x) = 0 - boor(x::Union) = 1 - @test boor(StridedArray) == 0 - @test boor(Base.unwrap_unionall(StridedArray)) == 1 - - # issue #1202 - foor(x::Union) = 1 - @test_throws MethodError foor(StridedArray) - @test foor(Base.unwrap_unionall(StridedArray)) == 1 - @test_throws MethodError foor(StridedArray) -end - -# issue #22842 -f22842(x::UnionAll) = UnionAll -f22842(x::DataType) = length(x.parameters) -@test f22842(Tuple{Vararg{Int64,N} where N}) == 1 -@test f22842(Tuple{Vararg{Int64,N}} where N) === UnionAll - -# issue #1153 -mutable struct SI{m, s, kg} - value::AbstractFloat -end - -import Base.* - -*{m1, m2, s1, s2, kg1, kg2}(x::SI{m1, s1, kg1}, y::SI{m2, s2, kg2}) = SI{m1 + m2, s1 + s2, kg1 + kg2}(x.value * y.value) - -let - local a,b - a = SI{0,0,1}(1.0) * SI{1,2,0}(2.0) - b = SI{0,0,1}(1.0) * SI{1,-2,0}(2.0) - @test typeof(a) === SI{1,2,1} - @test typeof(b) === SI{1,-2,1} -end - -# pointer arithmetic -let - local a,b,c - a = C_NULL - b = C_NULL + 1 - c = C_NULL - 1 - d = 1 + C_NULL - @test eltype(a) == Void - - @test a != b != c - @test b == d - @test UInt(a) == 0 - @test UInt(b) == 1 - @test UInt(c) == typemax(UInt) - - @test b - a == -(a - b) == 1 - @test c - a == -(a - c) == typemax(UInt) - @test c - b == -(b - c) == typemax(UInt) - 1 - @test a < b < c -end - -# pull request 1270 -let - local a,p, a2,p2 - a = [11,12,13] - p = pointer(a) - @test unsafe_load(p, 1) == 11 - unsafe_store!(p, 99, 2) - @test a == [11,99,13] - a2 = Any[101,102,103] - p2 = pointer(a2) - @test unsafe_load(p2) == 101 - unsafe_store!(p2, 909, 3) - @test a2 == [101,102,909] -end - -@test unsafe_pointer_to_objref(ccall(:jl_call1, Ptr{Void}, (Any,Any), - x -> x+1, 314158)) == 314159 -@test unsafe_pointer_to_objref(pointer_from_objref(e+pi)) == e+pi - -let - local a, aa - a = [1,2,3] - aa = unsafe_wrap(Array, pointer(a), length(a)) - @test aa == a - aa = unsafe_wrap(Array, pointer(a), (length(a),)) - @test aa == a - aa = unsafe_wrap(Array, pointer(a), UInt(length(a))) - @test aa == a - aa = unsafe_wrap(Array, pointer(a), UInt16(length(a))) - @test aa == a - @test_throws InexactError unsafe_wrap(Array, pointer(a), -3) -end - -struct FooBar2515 - foo::Int - bar::Int -end -let - local X, p - X = FooBar2515[ FooBar2515(3,1), FooBar2515(4,4) ] - p = pointer(X) - @test unsafe_load(p) == FooBar2515(3,1) - @test unsafe_load(p, 2) == FooBar2515(4,4) - unsafe_store!(p, FooBar2515(8,4)) - @test X[1] == FooBar2515(8,4) - unsafe_store!(p, FooBar2515(7,3), 1) - @test X[1] == FooBar2515(7,3) -end - -# issue #1287, combinations of try, catch, return -let - local f, g - - function f() - try - return 1 - end - end - @test f() == 1 - - function g() - try - error("badness") - catch - return 2 - end - end - @test g() == 2 -end - -# issue #1442 -mutable struct S1442{T} -end - -let - local f1442 - f1442(::DataType) = 1 - f1442{T}(::Type{S1442{T}}) = 2 - - @test f1442(S1442{Int}) == 2 - @test f1442(DataType) == 1 -end - -# issue #1727 -abstract type Component end - -mutable struct Transform <: Component - x - y - z - - Transform() = new(0, 0, 0) -end - -mutable struct Body <: Component - vel - curr_force - - Body() = new(0, 0) -end - -function NewEntity{T<:Component}(components::Type{T}...) - map((c)->c(), components) -end - -@test_throws MethodError NewEntity(Transform, Transform, Body, Body) -@test isa(NewEntity(Transform, Transform), Tuple{Transform, Transform}) -@test_throws MethodError NewEntity(Transform, Transform, Body, Body) - -# issue #1826 -let - a = (1,2) - a,b = a - @test a==1 && b==2 -end - -@testset "issue #1876" begin -let - tst = 1 - m1(i) = (tst+=1;i-1) - x = [1:4;] - x[1:end] *= 2 - @test x == [2:2:8;] - x[m1(end)] += 3 - @test x == [2,4,9,8] - @test tst == 2 - - # issue #1886 - X = [1:4;] - r = Array{UnitRange{Int}}(1) - r[1] = 2:3 - X[r...] *= 2 - @test X == [1,4,6,4] -end -end - -# issue #1632 -let - f1632{R,S}(::R, ::S) = 1 - f1632{T}( ::T, ::T) = 2 - @test f1632(1, 2) == 2 - @test f1632(:a, 2) == 1 - g1632{T}( ::T, ::T) = 2 - g1632{R,S}(::R, ::S) = 1 - @test g1632(1, 2) == 2 - @test g1632(:a, 2) == 1 -end - -# issue #2098 -let - i2098() = begin - c = Any[2.0] - [1:1:c[1];] - end - @test isequal(i2098(), [1.0,2.0]) -end - -# issue #2161 -let - i2161_1() = promote(2,2,2.0,2) - i2161_2() = i2161_1()[1] - @test i2161_2() === 2.0 -end - -# issue #2169 -let - i2169{T}(a::Array{T}) = typemin(T) - @test invoke(i2169, Tuple{Array} ,Int8[1]) === Int8(-128) -end - -# issue #2365 -mutable struct B2365{T} - v::Union{T, Void} -end -@test B2365{Int}(nothing).v === nothing -@test B2365{Int}(0).v === 0 - -# issue #2352 -let - local Sum, n - Sum=0.0; for n=1:2:10000 - Sum += -1/n + 1/(n+1) - end - @test Sum < -0.69 -end - -# issue #2509 -struct Foo2509; foo::Int; end -@test Foo2509(1) != Foo2509(2) -@test Foo2509(42) == Foo2509(42) - -# issue #2517 -struct Foo2517; end -@test repr(Foo2517()) == "$(curmod_prefix)Foo2517()" -@test repr(Array{Foo2517}(1)) == "$(curmod_prefix)Foo2517[$(curmod_prefix)Foo2517()]" -@test Foo2517() === Foo2517() - -# issue #1474 -mutable struct X1474{a,b} end -let - local Y - Y{A,B}(::Type{X1474{A,B}}) = 1 - Y{A}(::Type{X1474{A}}) = 2 - Y(::Type{X1474}) = 3 - @test Y(X1474) == 3 - @test Y(X1474{Int}) == 2 - @test Y(X1474{Int,AbstractString}) == 1 -end - -# issue #2562 -mutable struct Node2562{T} - value::T - Node2562{T}(value::T) where T = new(value) -end -Node2562{T}(value::T, args...) = Node2562{T}(value, args...) -makenode2562(value) = Node2562(value) -@test isa(Node2562(0), Node2562) -@test isa(makenode2562(0), Node2562) - -# issue #2619 -mutable struct I2619{T} - v::T - I2619{T}(v) where T = new(convert(T,v)) -end -bad2619 = false -function i2619() - global e2619 = try - I2619{Float64}(0.0f) - global bad2619 = true - catch _e - _e - end -end -i2619() -@test !bad2619 -@test isa(e2619,UndefVarError) && e2619.var === :f - -# issue #2919 -const Foo2919 = Int -mutable struct Baz2919; Foo2919::Foo2919; end -@test Baz2919(3).Foo2919 === 3 - -# issue #2982 -module M2982 -abstract type U end -macro bad(Y) - quote - mutable struct $(esc(Y)) <: U - end - end -end -export @bad -end - -@M2982.bad(T2982) -@test T2982.super === M2982.U - -# issue #3221 -let x = fill(nothing, 1) - @test_throws MethodError x[1] = 1 -end - -# issue #3220 -function x3220() - a = [1] - a::Vector{Int} += [1] -end -@test x3220() == [2] - -# issue #3471 -function f3471(y) - convert(Array{typeof(y[1]),1}, y) -end -@test isa(f3471(Any[1.0,2.0]), Vector{Float64}) - -# issue #3729 -A3729{B} = Vector{Vector{B}} -C3729{D} = Vector{Vector{D}} -@test Vector{Vector{Int}} === A3729{Int} === C3729{Int} - -# issue #3789 -x3789 = 0 -while(all([false for idx in 1:10])) - x3789 = 1 -end -@test x3789 == 0 - -# issue #3852 -function f3852() - local x - for i = 1:10 - x = identity - end - x("hi") -end -@test f3852() == "hi" - -# issue #3821 -function f3821() - p = [] - [x for x in p] -end -@test isa(f3821(), Array) - -# issue #4075 -struct Foo4075 - x::Int64 - y::Float64 -end - -function foo4075(f::Foo4075, s::Symbol) - x = getfield(f,s) - gc() - x -end - -@test isa(foo4075(Foo4075(Int64(1),2.0),:y), Float64) -# very likely to segfault the second time if this is broken -@test isa(foo4075(Foo4075(Int64(1),2.0),:y), Float64) - -# issue #3167 -let - function foo(x) - ret=Array{typeof(x[1])}(length(x)) - for j = 1:length(x) - ret[j] = x[j] - end - return ret - end - x = Array{Union{Dict{Int64,AbstractString},Array{Int64,3},Number,AbstractString,Void}}(3) - x[1] = 1.0 - x[2] = 2.0 - x[3] = 3.0 - @test foo(x) == [1.0, 2.0, 3.0] -end - -# TODO!! -# issue #4115 -#mutable struct Foo4115 -#end -#const Foo4115s = NTuple{3,Union{Foo4115,Type{Foo4115}}} -#baz4115(x::Foo4115s) = x -#@test baz4115(convert(Tuple{Type{Foo4115},Type{Foo4115},Foo4115}, -# (Foo4115,Foo4115,Foo4115()))) == (Foo4115,Foo4115,Foo4115()) - -# issue #4129 -mutable struct Foo4129; end - -abstract type Bar4129 end - -mutable struct Bar41291 <: Bar4129 - f::Foo4129 -end -mutable struct Bar41292 <: Bar4129 - f::Foo4129 -end - -mutable struct Baz4129 - b::Bar4129 -end - -foo4129(a::Baz4129,c::Foo4129,b::Bar4129,x::ANY,y) = (a,b,c,x,y) -foo4129(a::Baz4129,b::Bar41291,args...) = foo4129(a,b.f,b,args...) -foo4129(a::Baz4129,b::Bar41292,args...) = foo4129(a,b.f,b,args...) -foo4129(a::Baz4129,args...) = foo4129(a,a.b,args...) - -@test isa(foo4129(Baz4129(Bar41291(Foo4129())),1,2), Tuple{Baz4129,Bar4129,Foo4129,Int,Int}) - -# issue #4141 -mutable struct Vertex4141{N,T}; end -mutable struct Face4141{V}; end -mutable struct Hull4141{F<:Face4141}; end - -g4141(N,T) = Hull4141{Face4141{Vertex4141{N,T}}}() -@test isa(g4141(4,Int), Hull4141{Face4141{Vertex4141{4,Int}}}) - -# issue #4154 -mutable struct MyType4154{T} - a1::T - a2 -end - -foo4154(x) = MyType4154(x, []) -h4154() = typeof(foo4154(rand(2,2,2))) -g4154() = typeof(foo4154(rand(2,2,2,2,2,2,2,2,2))) - -@test h4154() === MyType4154{Array{Float64,3}} -@test g4154() === MyType4154{Array{Float64,9}} - -# issue #4208 -mutable struct a4208 - a4208 -end -@test isa(a4208(5),a4208) -mutable struct b4208 - b4208() = (local b4208=1;new()) -end -@test isa(b4208(),b4208) - -# make sure convert_default error isn't swallowed by typeof() -convert_default_should_fail_here() = similar([1],typeof(zero(typeof(rand(2,2))))) -@test_throws MethodError convert_default_should_fail_here() - -# issue #4343 -@test_throws ErrorException Array{Float64}{Int, 2} - -mutable struct Foo4376{T} - x - Foo4376{T}(x::T) where T = new(x) - Foo4376{T}(a::Foo4376{Int}) where T = new(a.x) -end - -@test isa(Foo4376{Float32}(Foo4376{Int}(2)), Foo4376{Float32}) - -mutable struct _0_test_ctor_syntax_ - _0_test_ctor_syntax_{T<:AbstractString}(files::Vector{T},step) = 0 -end - -# issue #4413 -mutable struct A4413 end -mutable struct B4413 end -mutable struct C4413 end -f4413(::Union{A4413, B4413, C4413}) = "ABC" -f4413(::Union{A4413, B4413}) = "AB" -g4413(::Union{A4413, C4413}) = "AC" -g4413(::Union{A4413, B4413, C4413}) = "ABC" - -@test f4413(A4413()) == "AB" && f4413(B4413()) == "AB" -@test g4413(A4413()) == "AC" && g4413(C4413()) == "AC" - -# issue #4482 -# what happens here: the method cache logic wants to widen the type of a -# tuple argument, but it shouldn't do that for an argument that a static -# parameter depends on. -f4482{T}(x::T) = T -@test f4482((Ptr,Ptr)) === Tuple{UnionAll,UnionAll} -@test f4482((Ptr,)) === Tuple{UnionAll,} - -# issue #4486 -try - # note: this test expression must run at the top level, - # in the interpreter. - (function() end)(1) - # should throw an argument count error - @test false -end - -# issue #4526 -f4526(x) = isa(x.a, Void) -@test_throws ErrorException f4526(1) -@test_throws ErrorException f4526(im) -@test_throws ErrorException f4526(1+2im) - -# issue #4528 -function f4528(A, B) - if A - reinterpret(UInt64, B) - end -end -@test f4528(false, Int32(12)) === nothing -@test_throws ErrorException f4528(true, Int32(12)) - -# issue #4518 -f4518(x, y::Union{Int32,Int64}) = 0 -f4518(x::String, y::Union{Int32,Int64}) = 1 -@test f4518("",1) == 1 - -# issue #4645 -i4645(x) = (println(zz); zz = x; zz) -@test_throws UndefVarError i4645(4) - -# more undef var errors -function test_undef_var_9898(a) - a1 = a1 - a -end -@test_throws UndefVarError test_undef_var_9898(1) - -# issue #4505 -let - g4505{X}(::X) = 0 - @test g4505(0) == 0 -end -@test !isdefined(:g4505) - -# issue #4681 -# ccall should error if convert() returns something of the wrong type -mutable struct Z4681 - x::Ptr{Void} - Z4681() = new(C_NULL) -end -Base.unsafe_convert(::Type{Ptr{Z4681}},b::Z4681) = b.x -@test_throws TypeError ccall(:printf,Int,(Ptr{UInt8},Ptr{Z4681}),"",Z4681()) - -# issue #4479 -f4479(::Real,c) = 1 -f4479(::Int, ::Int, ::Bool) = 2 -f4479(::Int, x, a...) = 0 -@test f4479(1,1,true) == 2 - -# issue #4688 -a4688(y) = "should be unreachable by calling b" -b4688(y) = "not an Int" -begin - a4688(y::Int) = "an Int" - let x = true - b4688(y::Int) = x == true ? a4688(y) : a4688(y) - end -end -@test b4688(1) == "an Int" - -# issue #4731 -mutable struct SIQ{A,B} <: Number - x::A -end -import Base: promote_rule -promote_rule{T,T2,S,S2}(A::Type{SIQ{T,T2}},B::Type{SIQ{S,S2}}) = SIQ{promote_type(T,S)} -@test_throws ErrorException promote_type(SIQ{Int},SIQ{Float64}) -f4731{T}(x::T...) = 0 -f4731(x...) = "" -g4731() = f4731() -@test f4731() == "" -@test g4731() == "" - -# issue #4675 -f4675(x::StridedArray...) = 1 -f4675{T}(x::StridedArray{T}...) = 2 -@test f4675(zeros(50,50), zeros(50,50)) == 2 -g4675{T}(x::StridedArray{T}...) = 2 -g4675(x::StridedArray...) = 1 -@test g4675(zeros(50,50), zeros(50,50)) == 2 - -# issue #4771 -module Lib4771 -export @make_closure -macro make_closure() - quote - f = (x)->1 - end -end -end # module -@test (Lib4771.@make_closure)(0) == 1 - -# issue #4805 -abstract type IT4805{N, T} end - -let - test0{T <: Int64}(::Type{IT4805{1, T}}, x) = x - test1() = test0(IT4805{1, Int64}, 1) - test2() = test0(IT4805{1+0, Int64}, 1) - test3(n) = test0(IT4805{n, Int64}, 1) - - @test test1() == 1 - @test test2() == 1 - @test test3(1) == 1 - @test_throws MethodError test3(2) -end - -# issue #4873 -macro myassert4873(ex) - :($ex ? nothing : error("Assertion failed: ", $(string(ex)))) -end -x4873 = 1 -@myassert4873 (x -> x)(x4873) == 1 - -# issue from IRC -function invalid_tupleref() - A = (1, "2", 3.0) - try - return A[0] - catch - return true - end -end -@test invalid_tupleref()==true - -# issue #5150 -f5150(T) = Array{Rational{T}}(1) -@test typeof(f5150(Int)) === Array{Rational{Int},1} - - -# issue #5165 -primitive type T5165{S} 64 end -make_t(x::Int64) = Core.Intrinsics.bitcast(T5165{Void}, x) -xs5165 = T5165[make_t(Int64(1))] -b5165 = IOBuffer() -for x in xs5165 - println(b5165, x) # segfaulted -end - -# support tuples as type parameters - -mutable struct TupleParam{P} - x::Bool -end - -function tupledispatch(a::TupleParam{(1,:a)}) - a.x -end - -let - # tuples can be used as type params - t1 = TupleParam{(1,:a)}(true) - t2 = TupleParam{(1,:b)}(true) - - # tuple type params can't contain invalid type params - @test_throws TypeError t3 = TupleParam{(1,"nope")}(true) - - # dispatch works properly - @test tupledispatch(t1) == true - @test_throws MethodError tupledispatch(t2) -end - -# issue #5254 -f5254{T}(::Type{T}, b::T) = 0 -f5254(a, b) = 1 -@test f5254(Bottom, 1) == 1 - -# evaluate arguments left-to-right, including assignments. issue #4990 -let i = 0, x = 65 - @test (i, i+=1, i+=1) === (0, 1, 2) - @test i == 2 - @test [x, x|=0x20] == [65, 97] -end - -# issue #5312 -let - local x = 0 - global incr5312, foo5312 - incr5312() = (x+=1; nothing) - foo5312() = (incr5312(),) - @test foo5312() === (nothing,) - @test x == 1 -end - -# issue #5319 -cnvt(T, x) = convert_default(T, x, cnvt) -cnvt{S, T, N}(::Type{Array{S, N}}, x::Array{T, N}) = convert(Array{S}, x) - -function tighttypes!(adf) - T = Bottom - tt = Any[Int] - for t in tt - T = typejoin(T, t) - end - cnvt(Vector{T}, adf[1]) -end - -@test isequal(tighttypes!(Any[Any[1.0,2.0],]), [1,2]) - -# issue #5142 -primitive type Int5142 64 end -function h5142(a::Bool) - x=a ? (Int64(0),reinterpret(Int5142,Int64(0))) : (Int64(1),reinterpret(Int5142,Int64(1))) - x[2]::Int5142 -end -function h5142(a::Int) - x=(Int64(0),reinterpret(Int5142,Int64(0))) - x[a]::Int5142 -end -h5142(true) -@test_throws TypeError h5142(1) -h5142(2) -f5142() = h5142(1) -try - # try running this code in a different context that triggers the codegen - # assertion `assert(isboxed || v.typ == typ)`. - f5142() -end - -primitive type Int5142b 8 end -function h5142b(a::Int) - x=((Int8(1),Int8(2)),(reinterpret(Int5142b,Int8(3)),reinterpret(Int5142b,Int8(4)))) - x[a]::Tuple{Int8,Int8} -end -h5142b(1) -@test_throws TypeError h5142b(2) - -# accessing bits tuples of structs -function test_bits_tuples() - a = (complex(1,2),complex(1,3));s=0 - for i=1:10 - s += a[rand(1:2)] - end - s -end -@test real(test_bits_tuples()) == 10 - -# issue #5374 -mutable struct FileObj5374 - io::IO -end -function read_file5374(fileobj) - read(fileobj.io, Float32) -end -@test isa(read_file5374(FileObj5374(IOBuffer(UInt8[0,0,0,0]))), Float32) - -# issue #5457 -function f5457(obj_ptr::Ptr{Float64}, f) - new_obj = convert(Float64, f(1.0)) - unsafe_store!(obj_ptr, new_obj) - return Int32(1) -end -let - a = [1.0] - f5457(pointer(a,1), sin) -end - -# issue #5584 -# this is an intermittent memory bug, but this code is very likely to trigger it -mapshape_5584{N}(s1::NTuple{N,Int}, s2::NTuple{N,Int}) = - (s1 == s2 || error("Argument dimensions are not map-compatible."); s1) -function f5584() - for i = 1:1000000 - a = rand(1:1000, 3) - # the bug was a failure to root these tuples - mapshape_5584(tuple(a...), tuple(a...)) - end -end -f5584() - -# issue #5884 - -mutable struct Polygon5884{T<:Real} - points::Vector{Complex{T}} -end - -function test5884() - star = Array{Polygon5884}((3,)) - star[1] = Polygon5884([Complex(1.0,1.0)]) - p1 = star[1].points[1] - @test p1 == Complex(1.0,1.0) - @test p1.re == 1.0 - @test star[1].points[1].re == 1.0 -end -test5884() - -# issue #5924 -let - function Test() - func = function () end - func - end - @test Test()() === nothing -end - -# issue #6031 -macro m6031(x); x; end -@test @m6031([2,4,6])[3] == 6 -@test (@m6031 [2,4,6])[2] == 4 - -# issue #6068 -x6068 = 1 -function test6068() - local a - while true - a = x6068 - break - end - a + 1 -end -@test test6068() == 2 - -# issue #6074 -macro X6074() - quote - global x6074 - let x6074 = x6074 - x6074 - end - end -end -x6074 = 6074 -@test @X6074() == 6074 - -# issue #5536 -test5536(a::Union{Real, AbstractArray}...) = "Splatting" -test5536(a::Union{Real, AbstractArray}) = "Non-splatting" -@test test5536(5) == "Non-splatting" - -# multiline comments (#6139 and others raised in #6128) and embedded NUL chars (#10994) -@test 3 == include_string("1 + 2") == include_string("1 + #==# 2") == include_string("1 + #===# 2") == include_string("1 + #= #= blah =# =# 2") == include_string("1 + #= #= #= nested =# =# =# 2") == include_string("1 + #= \0 =# 2") -@test_throws LoadError include_string("#=") -@test_throws LoadError include_string("#= #= #= =# =# =") - -# issue #6142 -import Base: + -mutable struct A6142 <: AbstractMatrix{Float64}; end -+{TJ}(x::A6142, y::UniformScaling{TJ}) = "UniformScaling method called" -+(x::A6142, y::AbstractArray) = "AbstractArray method called" -@test A6142() + I == "UniformScaling method called" -+(x::A6142, y::Range) = "Range method called" #16324 ambiguity - -# issue #6175 -function g6175(); print(""); (); end -g6175(i::Real, I...) = g6175(I...) -g6175(i, I...) = tuple(length(i), g6175(I...)...) -@test g6175(1:5) === (5,) - -# issue #6242 -f6242{N}(x::NTuple{N,Int})=(N==0 ? 1 : ntuple(n->x[n],N)) -@test f6242(()) === 1 - -# issue #6292 -let i = 0 - global g6292() = i+=1 -end -@test g6292() == 1 -@test g6292() == 2 - -# issue #6404 -mutable struct type_2{T <: Integer, N} <: Number - x::T - type_2{T,N}(n::T) where {T<:Integer,N} = new(n) -end -mutable struct type_1{T <: Number} <: Number - x::Vector{T} - type_1{T}(x::Vector{T}) where T<:Number = new(x) -end -type_1{T <: Number}(x::Vector{T}) = type_1{T}(x) -type_1{T <: Number}(c::T) = type_1{T}([c]) -Base.convert{T<:Number, S<:Number}(::Type{type_1{T}}, x::S) = type_1(convert(T, x)) -+{T <: Number}(a::type_1{T}, b::type_1{T}) = a - -function func1_6404(v1::Integer) - e1 = type_1([type_2{Int,v1}(0)]) - e1+e1 -end - -@test isa(func1_6404(3), type_1) - -# issue #5577 -f5577(::Any) = false -f5577(::Type) = true -@test !f5577((Int,AbstractString,2)) -@test !f5577(((Int,AbstractString),AbstractString)) -@test f5577(Tuple{Tuple{Int,AbstractString},AbstractString}) -@test f5577(Int) -@test !f5577(2) - -# issue #6426 -f6426(x,args...) = f6426(x,map(a->(isa(a,Type) ? Type{a} : typeof(a)), args)) -f6426(x,t::Tuple{Vararg{Type}}) = string(t) -@test f6426(1, (1.,2.)) == "(Tuple{Float64,Float64},)" - -# issue #6502 -f6502() = convert(Tuple{Vararg{Int}}, (10,)) -@test f6502() === (10,) -@test convert(Tuple{Bool,Vararg{Int}}, (true,10)) === (true,10) -@test convert(Tuple{Int,Vararg{Bool}}, (true,1,0)) === (1,true,false) - -# issue #6611 -function crc6611(spec) - direcn = spec ? 1 : 2 - local remainder::blech - ()->(remainder=1) -end -@test_throws UndefVarError crc6611(true)() - -# issue #6634 -function crc6634(spec) - A = UInt - remainder::A = 1 - function handler(append) - remainder = append ? 1 : 2 - end -end -@test crc6634(0x1)(true) == 1 -@test crc6634(0x1)(false) == 2 - -# issue #5876 -module A5876 -macro x() - quote - function $(esc(:f5876)){T}(::Type{T}) - T - end - 42 - end -end -end - -let - local z = A5876.@x() - @test z == 42 - @test f5876(Int) === Int -end - -# issue #20524 -macro m20524(ex) - quote - global f20524 - function f20524() - $ex - end - end -end -@m20524 ((a,(b20524,c)) = (8,(1,5)); (a,b20524,c)) -@test f20524() === (8,1,5) -@test !isdefined(:b20524) # should not assign to a global - -# issue #6387 -primitive type Date6387{C} 64 end - -mutable struct DateRange6387{C} <: Range{Date6387{C}} -end - -mutable struct ObjMember - member::DateRange6387 -end - -obj6387 = ObjMember(DateRange6387{Int64}()) - -function v6387{T}(r::Range{T}) - a = Array{T}(1) - a[1] = Core.Intrinsics.bitcast(Date6387{Int64}, Int64(1)) - return a -end - -function day_in(obj::ObjMember) - x = v6387(obj.member) - @test isa(x, Vector{Date6387{Int64}}) - @test isa(x[1], Date6387{Int64}) -end -day_in(obj6387) - -# issue #6784 -@test ndims(Array{Array{Float64}}(3,5)) == 2 -@test ndims(Array{Array}(3,5)) == 2 - -# issue #6793 -function segfault6793(;gamma=1) - A = 1 - B = 1 - print() - return - -gamma - nothing -end -@test segfault6793() === nothing - -# issue #6896 -g6896(x) = x::Int=x -@test g6896(5.0) === 5.0 -f6896(x) = y::Int=x -@test f6896(5.0) === 5.0 - -# issue #6938 -module M6938 -macro mac() - quote - let - y = 0 - y - end - end -end -end -@test @M6938.mac() == 0 - -# issue #7012 -let x = zeros(2) - x[1]::Float64 = 1 - @test x == [1.0, 0.0] - @test_throws TypeError (x[1]::Int = 1) - - x[1]::Float64 += 1 - @test x == [2.0, 0.0] - @test_throws TypeError (x[1]::Int += 1) -end - -# issue #6980 -abstract type A6980 end -mutable struct B6980 <: A6980 end -f6980(::Union{Int, Float64}, ::A6980) = false -f6980(::Union{Int, Float64}, ::B6980) = true -@test f6980(1, B6980()) - -# issue #7049 -Maybe7049{T} = Union{T,Void} -function ttt7049(;init::Maybe7049{Union{AbstractString,Tuple{Int,Char}}} = nothing) - string("init=", init) -end -@test ttt7049(init="a") == "init=a" - -# issue #7074 -let z{T<:Union{Float64,Complex{Float64},Float32,Complex{Float32}}}(A::StridedMatrix{T}) = T, - S = zeros(Complex,2,2) - @test_throws MethodError z(S) -end - -# issue #7062 -f7062{t,n}(::Type{Array{t}} , ::Array{t,n}) = (t,n,1) -f7062{t,n}(::Type{Array{t,n}}, ::Array{t,n}) = (t,n,2) -@test f7062(Array{Int,1}, [1,2,3]) === (Int,1,2) -@test f7062(Array{Int} , [1,2,3]) === (Int,1,1) - -# issue #7302 -function test7302() - t = [UInt64][1] - convert(t, "5") -end -@test_throws MethodError test7302() - -macro let_with_uninit() - quote - let x - x = 1 - x+1 - end - end -end - -@test @let_with_uninit() == 2 - -# issue #5154 -let - v = [] - for i=1:3, j=1:3 - push!(v, (i, j)) - i == 1 && j == 2 && break - end - @test v == Any[(1,1), (1,2)] -end - -# addition of ¬ (\neg) parsing -const (¬) = ! -@test ¬false - -# issue #7652 -mutable struct A7652 - a :: Int -end -a7652 = A7652(0) -t_a7652 = A7652 -f7652() = issubtype(fieldtype(t_a7652, :a), Int) -@test f7652() == issubtype(fieldtype(A7652, :a), Int) == true -g7652() = fieldtype(DataType, :types) -@test g7652() == fieldtype(DataType, :types) == SimpleVector -@test fieldtype(t_a7652, 1) == Int -h7652() = setfield!(a7652, 1, 2) -h7652() -@test a7652.a == 2 -# commented out due to issue #16195: setfield! does not perform conversions -# i7652() = setfield!(a7652, 1, 3.0) -# i7652() -# @test a7652.a == 3 - -# issue #7679 -@test map(f->f(), Any[ ()->i for i=1:3 ]) == Any[1,2,3] - -# issue 7897 -function issue7897!(data, arr) - data = reinterpret(UInt32, data) - a = arr[1] -end - -a = ones(UInt8, 10) -sa = view(a,4:6) -# This can throw an error, but shouldn't segfault -try - issue7897!(sa, zeros(10)) -end - -# issue #7582 -aₜ = "a variable using Unicode 6" - -struct My8156{A, B} - a::A - b::B -end -let m = My8156(nothing, 1) - @test sizeof(m) == sizeof(1) - @test m.a === nothing - @test m.b === 1 -end - -# issue #8184 -struct Foo8184 - x::Void - y::Void - z::Float64 -end -let f = Foo8184(nothing,nothing,1.0) - g(x) = x.z - @test g(f) === 1.0 -end - -# issue #8213 -@test map((x...)->x,(1,2),(3,4),(5,6)) === ((1,3,5),(2,4,6)) - -# issue #8338 -let ex = Expr(:(=), :(f8338(x;y=4)), :(x*y)) - eval(ex) - @test f8338(2) == 8 -end - -# call overloading (#2403) -(x::Int)(y::Int) = x + 3y -issue2403func(f) = f(7) -let x = 10 - @test x(3) == 19 - @test x((3,)...) == 19 - @test issue2403func(x) == 31 -end -mutable struct Issue2403 - x -end -(i::Issue2403)(y) = i.x + 2y -let x = Issue2403(20) - @test x(3) == 26 - @test issue2403func(x) == 34 -end - -# issue #8798 -let - const npy_typestrs = Dict("b1"=>Bool, - "i1"=>Int8, "u1"=>UInt8, - "i2"=>Int16, "u2"=>UInt16, - "i4"=>Int32, "u4"=>UInt32, - "i8"=>Int64, "u8"=>UInt64) - sizeof_lookup() = sizeof(npy_typestrs["i8"]) - @test sizeof_lookup() == 8 -end - -# issue #8978 -module I8978 -y = 1 -g() = f(y) -f(x) = 2 -f(x::Int) = 3.0 -module II8978 -function callf(f) - try - f() - finally - end -end -end -h(f) = II8978.callf() do - local x - for i = 1:1 - x = g()+f - end - x -end -end - -@test I8978.h(4) === 7.0 - -# issue #9134 -function f9134() - ii = zeros(Int32, 1) - let i - ii[1] = i - end -end -@test_throws UndefVarError f9134() - -# issue #9475 -module I9475 - arr = Array{Any}(1) - @eval @eval $arr[1] = 1 -end - -# issue #9520 -f9520a(::Any, ::Any, args...) = 15 -f9520b(::Any, ::Any, ::Any, args...) = 23 -f9520c(::Any, ::Any, ::Any, ::Any, ::Any, ::Any, args...) = 46 -@test invoke(f9520a, Tuple{Any, Any}, 1, 2) == 15 -@test invoke(f9520a, Tuple{Any, Any, Any}, 1, 2, 3) == 15 -@test invoke(f9520b, Tuple{Any, Any, Any}, 1, 2, 3) == 23 -@test invoke(f9520b, Tuple{Any, Any, Any, Any, Any, Any}, 1, 2, 3, 4, 5, 6) == 23 -@test invoke(f9520c, Tuple{Any, Any, Any, Any, Any, Any}, 1, 2, 3, 4, 5, 6) == 46 -@test invoke(f9520c, Tuple{Any, Any, Any, Any, Any, Any, Any}, 1, 2, 3, 4, 5, 6, 7) == 46 - -call_lambda1() = (()->x)(1) -call_lambda2() = ((x)->x)() -call_lambda3() = ((x)->x)(1,2) -call_lambda4() = ((x,y...)->x)() -@test_throws MethodError call_lambda1() -@test_throws MethodError call_lambda2() -@test_throws MethodError call_lambda3() -@test_throws MethodError call_lambda4() -call_lambda5() = ((x...)->x)() -call_lambda6() = ((x...)->x)(1) -call_lambda7() = ((x...)->x)(1,2) -@test call_lambda5() == () -@test call_lambda6() == (1,) -@test call_lambda7() == (1,2) - -# jl_new_bits testing -let x = [1,2,3] - @test ccall(:jl_new_bits, Any, (Any,Ptr{Void},), Int, x) === 1 - @test ccall(:jl_new_bits, Any, (Any,Ptr{Void},), Complex{Int}, x) === 1+2im - @test ccall(:jl_new_bits, Any, (Any,Ptr{Void},), NTuple{3,Int}, x) === (1,2,3) - @test ccall(:jl_new_bits, Any, (Any,Ptr{Void},), Tuple{Int,Int,Int}, x) === (1,2,3) - @test (ccall(:jl_new_bits, Any, (Any,Ptr{Void},), Tuple{Int16,Tuple{Void},Int8,Tuple{},Int,Void,Int}, x)::Tuple)[[2,4,5,6,7]] === ((nothing,),(),2,nothing,3) -end - -# sig 2 is SIGINT per the POSIX.1-1990 standard -if !is_windows() - ccall(:jl_exit_on_sigint, Void, (Cint,), 0) - @test_throws InterruptException begin - ccall(:kill, Void, (Cint, Cint,), getpid(), 2) - for i in 1:10 - Libc.systemsleep(0.1) - ccall(:jl_gc_safepoint, Void, ()) # wait for SIGINT to arrive - end - end - ccall(:jl_exit_on_sigint, Void, (Cint,), 1) -end -let - # Exception frame automatically restores sigatomic counter. - Base.sigatomic_begin() - @test_throws ErrorException begin - for i = 1:2 - Base.sigatomic_end() - end - end - Base.sigatomic_end() -end - -# pull request #9534 -@test try; a,b,c = 1,2; catch ex; (ex::BoundsError).a === (1,2) && ex.i == 3; end -@test try; [][]; catch ex; isempty((ex::BoundsError).a::Array{Any,1}) && ex.i == (1,); end -@test try; [][1,2]; catch ex; isempty((ex::BoundsError).a::Array{Any,1}) && ex.i == (1,2); end -@test try; [][10]; catch ex; isempty((ex::BoundsError).a::Array{Any,1}) && ex.i == (10,); end -f9534a() = (a=1+2im; getfield(a, -100)) -f9534a(x) = (a=1+2im; getfield(a, x)) -@test try; f9534a() catch ex; (ex::BoundsError).a === 1+2im && ex.i == -100; end -@test try; f9534a(3) catch ex; (ex::BoundsError).a === 1+2im && ex.i == 3; end -f9534b() = (a=(1,2.,""); a[5]) -f9534b(x) = (a=(1,2.,""); a[x]) -@test try; f9534b() catch ex; (ex::BoundsError).a == (1,2.,"") && ex.i == 5; end -@test try; f9534b(4) catch ex; (ex::BoundsError).a == (1,2.,"") && ex.i == 4; end -f9534c() = (a=(1,2.); a[3]) -f9534c(x) = (a=(1,2.); a[x]) -@test try; f9534c() catch ex; (ex::BoundsError).a === (1,2.) && ex.i == 3; end -@test try; f9534c(0) catch ex; (ex::BoundsError).a === (1,2.) && ex.i == 0; end -f9534d() = (a=(1,2,4,6,7); a[7]) -f9534d(x) = (a=(1,2,4,6,7); a[x]) -@test try; f9534d() catch ex; (ex::BoundsError).a === (1,2,4,6,7) && ex.i == 7; end -@test try; f9534d(-1) catch ex; (ex::BoundsError).a === (1,2,4,6,7) && ex.i == -1; end -f9534e(x) = (a=IOBuffer(); setfield!(a, x, 3)) -@test try; f9534e(-2) catch ex; isa((ex::BoundsError).a,Base.IOBuffer) && ex.i == -2; end -f9534f() = (a=IOBuffer(); getfield(a, -2)) -f9534f(x) = (a=IOBuffer(); getfield(a, x)) -@test try; f9534f() catch ex; isa((ex::BoundsError).a,Base.IOBuffer) && ex.i == -2; end -@test try; f9534f(typemin(Int)+2) catch ex; isa((ex::BoundsError).a,Base.IOBuffer) && ex.i == typemin(Int)+2; end -x9634 = 3 -@test try; getfield(1+2im, x9634); catch ex; (ex::BoundsError).a === 1+2im && ex.i == 3; end -@test try; throw(BoundsError()) catch ex; !isdefined((ex::BoundsError), :a) && !isdefined((ex::BoundsError), :i); end -@test try; throw(BoundsError(Int)) catch ex; (ex::BoundsError).a == Int && !isdefined((ex::BoundsError), :i); end -@test try; throw(BoundsError(Int, typemin(Int))) catch ex; (ex::BoundsError).a == Int && (ex::BoundsError).i == typemin(Int); end -@test try; throw(BoundsError(Int, (:a,))) catch ex; (ex::BoundsError).a == Int && (ex::BoundsError).i == (:a,); end -f9534g(a,b,c...) = c[0] -@test try; f9534g(1,2,3,4,5,6) catch ex; (ex::BoundsError).a === (3,4,5,6) && ex.i == 0; end -f9534h(a,b,c...) = c[a] -@test f9534h(4,2,3,4,5,6) == 6 -@test try; f9534h(5,2,3,4,5,6) catch ex; (ex::BoundsError).a === (3,4,5,6) && ex.i == 5; end - -# issue #9535 -counter9535 = 0 -f9535() = (global counter9535; counter9535 += 1; counter9535) -g9535() = (f9535(),f9535()) -@test g9535() == (1,2) -@test g9535() == (3,4) - -# weak references -mutable struct Obj; x; end -@testset "weak references" begin - @noinline function mk_wr(r, wr) - x = Obj(1) - push!(r, x) - push!(wr, WeakRef(x)) - end - test_wr(r,wr) = @test r[1] == wr[1].value - function test_wr() - ref = [] - wref = [] - mk_wr(ref, wref) - test_wr(ref, wref) - gc() - test_wr(ref, wref) - pop!(ref) - gc() - @test wref[1].value === nothing - end - test_wr() -end - -# issue #9947 -function f9947() - if 1 == 0 - 1 - else - min(UInt128(2),1) - end -end -@test f9947() == UInt128(1) - -#issue #9835 -module M9835 - using Base.Test - mutable struct A end; mutable struct B end - f() = (isa(A(), A) ? A : B)() - @test isa(f(), A) -end - -#issue #10163 -let a = :(()), b = :(()) - @test a.args !== b.args -end - -# issue caused by commit 189b00aef0376d1a998d36115cd11b17464d26ce and worked around -# by commit 24c64b86bd4e793dbfe9d85c067dc0579b320d14 -let - g{T}(x::T...) = T - g(x...) = 0 - @test g((),Int) == 0 - @test g((),()) == Tuple{} -end - -# TODO: hopefully this issue is obsolete after the tuple type change -## issue #8631 -#f8631(::(Type, Type...), ::(Any, Any...)) = 1 -#f8631{T}(::Type{(T...)}, x::Tuple) = 2 -#@test length(methods(f8631, ((Type, Type...), (Any, Any...)))) == 2 - -# issue caused by 8d0037cb377257fc4232c8526b12337dd7bdf0a7 -args8d003 = (:x, :y) -@test eval(:(:(f($(($args8d003)...))))) == :(f(x,y)) -x8d003 = Any[:y8d003] -y8d003 = 777 -@test eval(:(string(:(f($($(x8d003...))))))) == "f(777)" - -# issue #9378 -abstract type Foo9378{T,S} end -struct B9378{T} end -FooB9378{T} = Foo9378{T,B9378} -struct CFoo9378 <: FooB9378{Float64} end -@test isa(CFoo9378(),FooB9378) - -# issue #10281 -const N10281 = 1000 -@test if false - for i in 1:N10281 - end -end === nothing - -# issue #10221 -module GCbrokentype -OLD_STDOUT = STDOUT -fname = tempname() -file = open(fname, "w") -redirect_stdout(file) -versioninfo() -try - mutable struct Foo{T} - val::Bar{T} - end -end -gc() -redirect_stdout(OLD_STDOUT) -close(file) -rm(fname) -end - -# issue #10373 -f10373(x) = x -g10373(x) = x -mutable struct newtype10373 -end -let f - for f in (f10373,g10373) - (::typeof(f))(x::newtype10373) = println("$f") - end -end -for m in methods(f10373) - @test m.name == :f10373 -end -for m in methods(g10373) - @test m.name == :g10373 -end - -# issue #7221 -f7221{T<:Number}(::T) = 1 -f7221(::BitArray) = 2 -f7221(::AbstractVecOrMat) = 3 -@test f7221(trues(1)) == 2 - -# issue #10570 -struct Array_512_Uint8 - d1::UInt8 - d2::UInt8 - d3::UInt8 - d4::UInt8 - d5::UInt8 - d6::UInt8 - d7::UInt8 - d8::UInt8 - d9::UInt8 - d10::UInt8 - d11::UInt8 - d12::UInt8 - d13::UInt8 - d14::UInt8 - d15::UInt8 - d16::UInt8 - d17::UInt8 - d18::UInt8 - d19::UInt8 - d20::UInt8 - d21::UInt8 - d22::UInt8 - d23::UInt8 - d24::UInt8 - d25::UInt8 - d26::UInt8 - d27::UInt8 - d28::UInt8 - d29::UInt8 - d30::UInt8 - d31::UInt8 - d32::UInt8 - d33::UInt8 - d34::UInt8 - d35::UInt8 - d36::UInt8 - d37::UInt8 - d38::UInt8 - d39::UInt8 - d40::UInt8 - d41::UInt8 - d42::UInt8 - d43::UInt8 - d44::UInt8 - d45::UInt8 - d46::UInt8 - d47::UInt8 - d48::UInt8 - d49::UInt8 - d50::UInt8 - d51::UInt8 - d52::UInt8 - d53::UInt8 - d54::UInt8 - d55::UInt8 - d56::UInt8 - d57::UInt8 - d58::UInt8 - d59::UInt8 - d60::UInt8 - d61::UInt8 - d62::UInt8 - d63::UInt8 - d64::UInt8 - d65::UInt8 - d66::UInt8 - d67::UInt8 - d68::UInt8 - d69::UInt8 - d70::UInt8 - d71::UInt8 - d72::UInt8 - d73::UInt8 - d74::UInt8 - d75::UInt8 - d76::UInt8 - d77::UInt8 - d78::UInt8 - d79::UInt8 - d80::UInt8 - d81::UInt8 - d82::UInt8 - d83::UInt8 - d84::UInt8 - d85::UInt8 - d86::UInt8 - d87::UInt8 - d88::UInt8 - d89::UInt8 - d90::UInt8 - d91::UInt8 - d92::UInt8 - d93::UInt8 - d94::UInt8 - d95::UInt8 - d96::UInt8 - d97::UInt8 - d98::UInt8 - d99::UInt8 - d100::UInt8 - d101::UInt8 - d102::UInt8 - d103::UInt8 - d104::UInt8 - d105::UInt8 - d106::UInt8 - d107::UInt8 - d108::UInt8 - d109::UInt8 - d110::UInt8 - d111::UInt8 - d112::UInt8 - d113::UInt8 - d114::UInt8 - d115::UInt8 - d116::UInt8 - d117::UInt8 - d118::UInt8 - d119::UInt8 - d120::UInt8 - d121::UInt8 - d122::UInt8 - d123::UInt8 - d124::UInt8 - d125::UInt8 - d126::UInt8 - d127::UInt8 - d128::UInt8 - d129::UInt8 - d130::UInt8 - d131::UInt8 - d132::UInt8 - d133::UInt8 - d134::UInt8 - d135::UInt8 - d136::UInt8 - d137::UInt8 - d138::UInt8 - d139::UInt8 - d140::UInt8 - d141::UInt8 - d142::UInt8 - d143::UInt8 - d144::UInt8 - d145::UInt8 - d146::UInt8 - d147::UInt8 - d148::UInt8 - d149::UInt8 - d150::UInt8 - d151::UInt8 - d152::UInt8 - d153::UInt8 - d154::UInt8 - d155::UInt8 - d156::UInt8 - d157::UInt8 - d158::UInt8 - d159::UInt8 - d160::UInt8 - d161::UInt8 - d162::UInt8 - d163::UInt8 - d164::UInt8 - d165::UInt8 - d166::UInt8 - d167::UInt8 - d168::UInt8 - d169::UInt8 - d170::UInt8 - d171::UInt8 - d172::UInt8 - d173::UInt8 - d174::UInt8 - d175::UInt8 - d176::UInt8 - d177::UInt8 - d178::UInt8 - d179::UInt8 - d180::UInt8 - d181::UInt8 - d182::UInt8 - d183::UInt8 - d184::UInt8 - d185::UInt8 - d186::UInt8 - d187::UInt8 - d188::UInt8 - d189::UInt8 - d190::UInt8 - d191::UInt8 - d192::UInt8 - d193::UInt8 - d194::UInt8 - d195::UInt8 - d196::UInt8 - d197::UInt8 - d198::UInt8 - d199::UInt8 - d200::UInt8 - d201::UInt8 - d202::UInt8 - d203::UInt8 - d204::UInt8 - d205::UInt8 - d206::UInt8 - d207::UInt8 - d208::UInt8 - d209::UInt8 - d210::UInt8 - d211::UInt8 - d212::UInt8 - d213::UInt8 - d214::UInt8 - d215::UInt8 - d216::UInt8 - d217::UInt8 - d218::UInt8 - d219::UInt8 - d220::UInt8 - d221::UInt8 - d222::UInt8 - d223::UInt8 - d224::UInt8 - d225::UInt8 - d226::UInt8 - d227::UInt8 - d228::UInt8 - d229::UInt8 - d230::UInt8 - d231::UInt8 - d232::UInt8 - d233::UInt8 - d234::UInt8 - d235::UInt8 - d236::UInt8 - d237::UInt8 - d238::UInt8 - d239::UInt8 - d240::UInt8 - d241::UInt8 - d242::UInt8 - d243::UInt8 - d244::UInt8 - d245::UInt8 - d246::UInt8 - d247::UInt8 - d248::UInt8 - d249::UInt8 - d250::UInt8 - d251::UInt8 - d252::UInt8 - d253::UInt8 - d254::UInt8 - d255::UInt8 - d256::UInt8 - d257::UInt8 - d258::UInt8 - d259::UInt8 - d260::UInt8 - d261::UInt8 - d262::UInt8 - d263::UInt8 - d264::UInt8 - d265::UInt8 - d266::UInt8 - d267::UInt8 - d268::UInt8 - d269::UInt8 - d270::UInt8 - d271::UInt8 - d272::UInt8 - d273::UInt8 - d274::UInt8 - d275::UInt8 - d276::UInt8 - d277::UInt8 - d278::UInt8 - d279::UInt8 - d280::UInt8 - d281::UInt8 - d282::UInt8 - d283::UInt8 - d284::UInt8 - d285::UInt8 - d286::UInt8 - d287::UInt8 - d288::UInt8 - d289::UInt8 - d290::UInt8 - d291::UInt8 - d292::UInt8 - d293::UInt8 - d294::UInt8 - d295::UInt8 - d296::UInt8 - d297::UInt8 - d298::UInt8 - d299::UInt8 - d300::UInt8 - d301::UInt8 - d302::UInt8 - d303::UInt8 - d304::UInt8 - d305::UInt8 - d306::UInt8 - d307::UInt8 - d308::UInt8 - d309::UInt8 - d310::UInt8 - d311::UInt8 - d312::UInt8 - d313::UInt8 - d314::UInt8 - d315::UInt8 - d316::UInt8 - d317::UInt8 - d318::UInt8 - d319::UInt8 - d320::UInt8 - d321::UInt8 - d322::UInt8 - d323::UInt8 - d324::UInt8 - d325::UInt8 - d326::UInt8 - d327::UInt8 - d328::UInt8 - d329::UInt8 - d330::UInt8 - d331::UInt8 - d332::UInt8 - d333::UInt8 - d334::UInt8 - d335::UInt8 - d336::UInt8 - d337::UInt8 - d338::UInt8 - d339::UInt8 - d340::UInt8 - d341::UInt8 - d342::UInt8 - d343::UInt8 - d344::UInt8 - d345::UInt8 - d346::UInt8 - d347::UInt8 - d348::UInt8 - d349::UInt8 - d350::UInt8 - d351::UInt8 - d352::UInt8 - d353::UInt8 - d354::UInt8 - d355::UInt8 - d356::UInt8 - d357::UInt8 - d358::UInt8 - d359::UInt8 - d360::UInt8 - d361::UInt8 - d362::UInt8 - d363::UInt8 - d364::UInt8 - d365::UInt8 - d366::UInt8 - d367::UInt8 - d368::UInt8 - d369::UInt8 - d370::UInt8 - d371::UInt8 - d372::UInt8 - d373::UInt8 - d374::UInt8 - d375::UInt8 - d376::UInt8 - d377::UInt8 - d378::UInt8 - d379::UInt8 - d380::UInt8 - d381::UInt8 - d382::UInt8 - d383::UInt8 - d384::UInt8 - d385::UInt8 - d386::UInt8 - d387::UInt8 - d388::UInt8 - d389::UInt8 - d390::UInt8 - d391::UInt8 - d392::UInt8 - d393::UInt8 - d394::UInt8 - d395::UInt8 - d396::UInt8 - d397::UInt8 - d398::UInt8 - d399::UInt8 - d400::UInt8 - d401::UInt8 - d402::UInt8 - d403::UInt8 - d404::UInt8 - d405::UInt8 - d406::UInt8 - d407::UInt8 - d408::UInt8 - d409::UInt8 - d410::UInt8 - d411::UInt8 - d412::UInt8 - d413::UInt8 - d414::UInt8 - d415::UInt8 - d416::UInt8 - d417::UInt8 - d418::UInt8 - d419::UInt8 - d420::UInt8 - d421::UInt8 - d422::UInt8 - d423::UInt8 - d424::UInt8 - d425::UInt8 - d426::UInt8 - d427::UInt8 - d428::UInt8 - d429::UInt8 - d430::UInt8 - d431::UInt8 - d432::UInt8 - d433::UInt8 - d434::UInt8 - d435::UInt8 - d436::UInt8 - d437::UInt8 - d438::UInt8 - d439::UInt8 - d440::UInt8 - d441::UInt8 - d442::UInt8 - d443::UInt8 - d444::UInt8 - d445::UInt8 - d446::UInt8 - d447::UInt8 - d448::UInt8 - d449::UInt8 - d450::UInt8 - d451::UInt8 - d452::UInt8 - d453::UInt8 - d454::UInt8 - d455::UInt8 - d456::UInt8 - d457::UInt8 - d458::UInt8 - d459::UInt8 - d460::UInt8 - d461::UInt8 - d462::UInt8 - d463::UInt8 - d464::UInt8 - d465::UInt8 - d466::UInt8 - d467::UInt8 - d468::UInt8 - d469::UInt8 - d470::UInt8 - d471::UInt8 - d472::UInt8 - d473::UInt8 - d474::UInt8 - d475::UInt8 - d476::UInt8 - d477::UInt8 - d478::UInt8 - d479::UInt8 - d480::UInt8 - d481::UInt8 - d482::UInt8 - d483::UInt8 - d484::UInt8 - d485::UInt8 - d486::UInt8 - d487::UInt8 - d488::UInt8 - d489::UInt8 - d490::UInt8 - d491::UInt8 - d492::UInt8 - d493::UInt8 - d494::UInt8 - d495::UInt8 - d496::UInt8 - d497::UInt8 - d498::UInt8 - d499::UInt8 - d500::UInt8 - d501::UInt8 - d502::UInt8 - d503::UInt8 - d504::UInt8 - d505::UInt8 - d506::UInt8 - d507::UInt8 - d508::UInt8 - d509::UInt8 - d510::UInt8 - d511::UInt8 - d512::UInt8 -end -gc() - -# issue #10867 -@test collect(enumerate((Tuple,Int))) == [(1,Tuple), (2,Int)] -@test collect(enumerate((Tuple,3))) == [(1,Tuple), (2,3)] - -# issue #10978 -TupleType10978{T<:Tuple} = Type{T} -f10978(T::TupleType10978) = isa(T, TupleType10978) -@test f10978(Tuple{Int}) - -# issue #10995 -#TupleType{T<:Tuple} = Type{T} -f10995(::Any) = (while false; end; nothing) -f10995(T::TupleType10978) = (while false; end; @assert isa(T, TupleType10978)) -g10995(x) = f10995(typeof(x)) -g10995((1, 2)) -@test g10995(UInt8) === nothing - -# issue #11149 -@noinline f11149(a,b,args...) = (a,b,args...) -@test f11149(1,2,3) == invoke(f11149, Tuple{Int,Int,Int}, 1,2,3) - -# issue #11357 -function f11357() - x = (1,2,3) - i = (1,) - x[i...] -end -@test f11357() === 1 - -# issue #11355 -function f11355{T<:Tuple}(sig::Type{T}) - f11355(sig.parameters[1]) -end -function f11355(arg::DataType) - if arg <: Tuple - return 200 - end - return 100 -end -let t = Tuple{Type{Vector{Int}}} - @test f11355(t) == 100 - t = Tuple{Type{Dict{K} where K}} - @test f11355(t) == 100 -end - -# issue #8283 -function func8283 end -@test isa(func8283,Function) -@test_throws MethodError func8283() - -# issue #11243 -mutable struct Type11243{A, B} - x::A - y::B -end -let a = [Type11243(1,2), Type11243("a","b")] - @test typeof(a) == Vector{Type11243} - @test typeof(a) <: Vector{Type11243} -end - -# issue #11065, #1571 -function f11065() - for i = 1:2 - if i == 1 - z = "z is defined" - elseif i == 2 - print(z) - end - end -end -@test_throws UndefVarError f11065() - -# issue #11295 -function f11295(x...) - call = Expr(x...) -end -@test isa(f11295(:a,:b), Expr) - -# issue #11675 -struct T11675{T} - x::T - T11675{T}() where T = new() -end -let x = T11675{Union{}}() - function f11675(x) - x.x + 1 - end - @test_throws UndefRefError f11675(x) -end - -# issue #7864 -module M7864 -export x7864 -x7864 = 1 -end - -@test_throws UndefVarError x7864 -using .M7864 -@test x7864 == 1 - -# issue #11715 -f11715(x) = (x === Tuple{Any}) -@test f11715(Tuple{Any}) - -# part of #11597 -# make sure invalid, partly-constructed types don't end up in the cache -abstract type C11597{T<:Union{Void, Int}} end -mutable struct D11597{T} <: C11597{T} d::T end -@test_throws TypeError D11597(1.0) -@test_throws TypeError repr(D11597(1.0)) - -# issue #11772 -@test_throws UndefRefError (Vector{Any}(5)...) - -# issue #11813 -let a = UInt8[1, 107, 66, 88, 2, 99, 254, 13, 0, 0, 0, 0] - u32 = UInt32[0x3] - a[9:end] = reinterpret(UInt8, u32) - p = pointer(a) - @test (Int8(1),(Int8(2),Int32(3))) === unsafe_load(convert(Ptr{Tuple{Int8,Tuple{Int8,Int32}}},p)) - f11813(p) = (Int8(1),(Int8(2),Int32(3))) === unsafe_load(convert(Ptr{Tuple{Int8,Tuple{Int8,Int32}}},p)) - @test f11813(p) === true # redundant comparison test seems to make this test more reliable, don't remove -end -# issue #13037 -let a = UInt8[0, 0, 0, 0, 0x66, 99, 254, 13, 0, 0, 0, 0] - u32 = UInt32[0x3] - a[1:4] = reinterpret(UInt8, u32) - p = pointer(a) - @test ((Int32(3),UInt8(0x66)),Int32(0)) === unsafe_load(convert(Ptr{Tuple{Tuple{Int32,UInt8},Int32}},p)) - f11813(p) = ((Int32(3),UInt8(0x66)),Int32(0)) === unsafe_load(convert(Ptr{Tuple{Tuple{Int32,UInt8},Int32}},p)) - @test f11813(p) === true # redundant comparison test seems to make this test more reliable, don't remove -end -let a = (1:1000...), - b = (1:1000...) - @test a == b - @test a === b - @test (a == b) === true - @test (a === b) === true -end - -# issue 11858 -mutable struct Foo11858 - x::Float64 - Foo11858(x::Float64) = new(x) -end - -mutable struct Bar11858 - x::Float64 - Bar11858(x::Float64) = new(x) -end - -g11858(x::Float64) = x -f11858(a) = for Baz in a - (f::Baz)(x) = f(float(x)) -end -f11858(Any[Type{Foo11858}, Type{Bar11858}, typeof(g11858)]) - -@test g11858(1) == 1.0 -@test Foo11858(1).x == 1.0 -@test Bar11858(1).x == 1.0 - -# issue 11904 -@noinline throw_error() = error() -foo11904(x::Int) = x -@inline function foo11904{S}(x::Nullable{S}) - if isbits(S) - Nullable(foo11904(x.value), x.hasvalue) - else - throw_error() - end -end - -@test !isnull(foo11904(Nullable(1))) - -# issue 11874 -struct Foo11874 - x::Int -end - -function bar11874(x) - local y::Foo11874 - y = x - nothing -end - -Base.convert(::Type{Foo11874},x::Int) = float(x) - -@test_throws TypeError bar11874(1) - -# issue #9233 -let - try - NTuple{Int, 1} - @test false - catch err - @test isa(err, TypeError) - @test err.func == :apply_type - @test err.expected == Int - @test err.got == Int - end - - try - NTuple{0x1, Int} - @test false - catch err - @test isa(err, TypeError) - @test err.func == :apply_type - @test err.expected == Int - @test err.got == 0x1 - end -end - -# 11996 -@test_throws ErrorException NTuple{-1, Int} -@test_throws TypeError Union{Int, 1} - -mutable struct FooNTuple{N} - z::Tuple{Integer, Vararg{Int, N}} -end -@test_throws ErrorException FooNTuple{-1} -@test_throws ErrorException FooNTuple{typemin(Int)} -@test_throws TypeError FooNTuple{0x01} -@test fieldtype(FooNTuple{0}, 1) == Tuple{Integer} - -mutable struct FooTupleT{T} - z::Tuple{Int, T, Int} -end -@test_throws TypeError FooTupleT{Vararg{Int, 2}} -@test fieldtype(FooTupleT{Int}, 1) == NTuple{3, Int} - -@test Tuple{} === NTuple{0, Any} -@test Tuple{Int} === Tuple{Int, Vararg{Integer, 0}} - -# issue #12003 -const DATE12003 = DateTime(1917,1,1) -failure12003(dt=DATE12003) = Dates.year(dt) -@test isa(failure12003(), Integer) - -# issue #12023 Test error checking in primitive type -@test_throws ErrorException (@eval primitive type 0 SPJa12023 end) -@test_throws ErrorException (@eval primitive type 4294967312 SPJb12023 end) -@test_throws ErrorException (@eval primitive type -4294967280 SPJc12023 end) - -# issue #12089 -mutable struct A12089{K, N} - sz::NTuple{N, Int} - A12089{K,N}(sz::NTuple{N, Int}) where {K,N} = new(sz) -end -A12089{-1, 1}((1,)) - -# issue #12092 -f12092(x::Int, y) = 0 -f12092(x::Int,) = 1 -f12092(x::Int, y::Int...) = 2 -@test f12092(1) == 1 - -# issue #12063 -# NOTE: should have > MAX_TUPLETYPE_LEN arguments -f12063{T}(tt, g, p, c, b, v, cu::T, d::AbstractArray{T, 2}, ve) = 1 -f12063(args...) = 2 -g12063() = f12063(0, 0, 0, 0, 0, 0, 0.0, spzeros(0,0), Int[]) -@test g12063() == 1 - -# issue #11587 -mutable struct Sampler11587{N} - clampedpos::Array{Int,2} - buf::Array{Float64,N} -end -function Sampler11587() - a = tuple(Any[32,32]...,) - Sampler11587(zeros(Int,a), zeros(Float64,a)) -end -@test isa(Sampler11587(), Sampler11587{2}) - -# issue #8010 - error when convert returns wrong type during new() -struct Vec8010{T} - x::T - y::T -end -Vec8010(a::AbstractVector) = Vec8010(ntuple(x->a[x],2)...) -Base.convert{T}(::Type{Vec8010{T}},x::AbstractVector) = Vec8010(x) -Base.convert(::Type{Void},x::AbstractVector) = Vec8010(x) -struct MyType8010 - m::Vec8010{Float32} -end -struct MyType8010_ghost - m::Void -end -@test_throws TypeError MyType8010([3.0;4.0]) -@test_throws TypeError MyType8010_ghost([3.0;4.0]) - -# don't allow redefining types if ninitialized changes -struct NInitializedTestType - a -end - -@test_throws ErrorException @eval struct NInitializedTestType - a - NInitializedTestType() = new() -end - -# issue #12394 -mutable struct Empty12394 end -let x = Array{Empty12394}(1), y = [Empty12394()] - @test_throws UndefRefError x==y - @test_throws UndefRefError y==x -end - -module TestRecursiveConstGlobalStructCtor -const x = (1,2) -const y = (x,(3,4)) -f() = (x,y,(5,6)) -end -@test TestRecursiveConstGlobalStructCtor.f() == ((1,2),((1,2),(3,4)),(5,6)) - -const const_array_int1 = Array{Int} -const const_array_int2 = Array{Int} -test_eq_array_int() = ===(const_array_int1, const_array_int2) -@test test_eq_array_int() - -# object_id of haspadding field -struct HasPadding - x::Bool - y::Int -end -struct HasHasPadding - x::HasPadding -end -hashaspadding = HasHasPadding(HasPadding(true,1)) -hashaspadding2 = HasHasPadding(HasPadding(true,1)) -unsafe_store!(convert(Ptr{UInt8},pointer_from_objref(hashaspadding)), 0x12, 2) -unsafe_store!(convert(Ptr{UInt8},pointer_from_objref(hashaspadding2)), 0x21, 2) -@test object_id(hashaspadding) == object_id(hashaspadding2) - -# issue #12517 -let x = (1,2) - @eval f12517() = Val{$x} - @test f12517() === Val{(1,2)} -end - -# don't allow Vararg{} in Union{} type constructor -@test_throws TypeError Union{Int,Vararg{Int}} -@test_throws TypeError Union{Vararg{Int}} - -# only allow Vararg{} in last position of Tuple{ } -@test_throws TypeError Tuple{Vararg{Int32},Int64,Float64} -@test_throws TypeError Tuple{Int64,Vararg{Int32},Float64} -@test_throws TypeError Array{Vararg} - -# don't allow non-types in Union -@test_throws TypeError Union{1} -@test_throws TypeError Union{Int,0} -PossiblyInvalidUnion{T} = Union{T,Int} -@test_throws TypeError PossiblyInvalidUnion{1} - -# issue #12569 -@test Symbol("x") === Symbol("x") -@test split(string(gensym("abc")),'#')[3] == "abc" - -# issue #13007 -call13007{T,N}(::Type{Array{T,N}}) = 0 -call13007(::Type{Array}) = 1 -@test length(Base._methods(call13007, Tuple{Type{x} where x<:Array}, 4, typemax(UInt))) == 2 - -# detecting cycles during type intersection, e.g. #1631 -cycle_in_solve_tvar_constraints{S}(::Type{Nullable{S}}, x::S) = 0 -cycle_in_solve_tvar_constraints{T}(::Type{T}, x::Val{T}) = 1 -@test length(methods(cycle_in_solve_tvar_constraints)) == 2 - -# issue #12967 -foo12967(x, ::ANY) = 1 -TupleType12967{T<:Tuple} = Type{T} -foo12967(x, ::TupleType12967) = 2 -@test foo12967(1, Int) == 1 -@test foo12967(1, Tuple{}) == 2 - -# issue #13083 -@test Void() === nothing - -# issue discovered in #11973 -for j = 1:1 - x = try - error() - 2 - catch - continue - end -end - -# PR 11888 -struct A11888{T} - a::NTuple{16,T} -end - -B11888{T} = A11888{A11888{A11888{T}}} - -@test sizeof(B11888{B11888{Int64}}) == (1 << 24) * 8 - -# issue #13175 -struct EmptyImmutable13175 end -struct EmptyIIOtherField13175 - x::EmptyImmutable13175 - y::Float64 -end -@test EmptyIIOtherField13175(EmptyImmutable13175(), 1.0) == EmptyIIOtherField13175(EmptyImmutable13175(), 1.0) -@test EmptyIIOtherField13175(EmptyImmutable13175(), 1.0) != EmptyIIOtherField13175(EmptyImmutable13175(), 2.0) - -# issue #13183 -gg13183{X}(x::X...) = 1==0 ? gg13183(x, x) : 0 -@test gg13183(5) == 0 - -# issue 8932 (llvm return type legalizer error) -struct Vec3_8932 - x::Float32 - y::Float32 - z::Float32 -end -f8932(a::Vec3_8932, b::Vec3_8932) = Vec3_8932(a.x % b.x, a.y % b.y, a.z % b.z) -a8932 = Vec3_8932(1,1,1) -b8932 = Vec3_8932(2,2,2) -@test f8932(a8932, b8932) == Vec3_8932(1.0, 1.0, 1.0) - -# issue #13261 -f13261() = (x = (error("oops"),); +(x...)) -g13261() = f13261() -@test_throws ErrorException g13261() - -# issue 13432 -@noinline function f13432(x) - offset = x ? Base.Bottom : 1 - return ===(offset, Base.Bottom) -end -@test f13432(true) == true -@test f13432(false) == false -@noinline function f13432b(x) - a = x ? 1 : 1.0 - b = x ? 1 : 1.0f0 - return ===(a, b) -end -@test f13432b(true) == true -@test f13432b(false) == false - -#13433, read!(::IO, a::Vector{UInt8}) should return a -mutable struct IO13433 <: IO end -Base.read(::IO13433, ::Type{UInt8}) = 0x01 -@test read!(IO13433(), Array{UInt8}(4)) == [0x01, 0x01, 0x01, 0x01] - -# issue #13647, comparing boxed isbits immutables -struct X13647 - a::Int - b::Bool -end -function f13647(x, y) - z = false - z = y - x === z -end -@test f13647(X13647(1, false), X13647(1, false)) -@test !f13647(X13647(1, false), X13647(1, true)) -@test !f13647(X13647(2, false), X13647(1, false)) - -# issue #13636 -module I13636 -foo(x) = 1 -end -let cache = Dict() - function I13636.foo(y::Int;k::Int=1) - cache[1] = y+k - end -end -@test I13636.foo(1,k=2) == 3 - -# issue #11327 and #13547 -@test_throws MethodError convert(Type{Int}, Float32) -@test_throws MethodError Array{Type{Int64}}([Float32]) -abstract type A11327 end -abstract type B11327 <: A11327 end -f11327{T}(::Type{T},x::T) = x -@test_throws MethodError f11327(Type{A11327},B11327) - -# issue #8487 -@test [x for x in 1:3] == [x for x ∈ 1:3] == [x for x = 1:3] -let A = Array{Int}(4,3) - for i ∈ 1:size(A,1), j ∈ 1:size(A,2) - A[i,j] = 17*i + 51*j - end - @test A == [17*i + 51*j for i ∈ 1:size(A,1), j ∈ 1:size(A,2)] -end - -# check if finalizers for the old gen can be triggered manually -# issue #13986 -let - obj = Ref(1) - finalized = 0 - finalizer(obj, (obj) -> (finalized = 1)) - # obj should be marked for promotion after the second gc and be promoted - # after the third GC - # GC_CLEAN; age = 0 - gc(false) - # GC_CLEAN; age = 1 - gc(false) - # GC_QUEUED; age = 1 - gc(false) - # GC_MARKED; age = 1 - finalize(obj) - @test finalized == 1 -end - -# check if finalizers for the old gen can be triggered manually -# PR #14181 -let - # The following three `gc(false)` clears the `finalizer_list`. It is - # not strictly necessary to make the test pass but should make the failure - # more repeatable if something breaks. - gc(false) - # At least: GC_CLEAN; age = 1 - gc(false) - # At least: GC_QUEUED; age = 1 - gc(false) - # all objects in `finalizer_list` are now moved to `finalizer_list_marked` - - obj1 = Ref(1) - obj2 = Ref(1) - finalized = 0 - finalizer(obj1, (obj) -> (finalized += 1)) - finalizer(obj1, (obj) -> (finalized += 1)) - finalizer(obj2, (obj) -> (finalized += 1; finalize(obj1))) - finalizer(obj2, (obj) -> (finalized += 1; finalize(obj1))) - finalize(obj2) - @test finalized == 4 -end - -# issue #14323 -@test_throws ErrorException eval(Expr(:body, :(1))) - -# issue #14339 -f14339{T<:Union{}}(x::T, y::T) = 0 -@test_throws MethodError f14339(1, 2) - -# Make sure jlcall objects are rooted -# PR #14301 -module JLCall14301 - -# Define f -function f end - -let i = Any[[1.23], [2.34]] - # f() with capture variables - # Intentionally type unstable so that the dynamic dispatch will - # read the corrupted tag if the object is incorrectly GC'd. - global @noinline f() = i[1][1] * i[2][1] -end - -# Another function that use f() -g() = f() * 100 -# Compile it -g() - -let i = 9.0 - # Override f() - global @noinline f() = i + 1 -end - -# Make sure the old f() method is GC'd if it was not rooted properly -gc() -gc() -gc() - -# Run again. -g() - -end - -# make sure codegen doesn't remove argument to `isa` -@noinline __g_isa_test_1(a) = push!(a,1) -function __f_isa_arg_1() - a = [] - isa(__g_isa_test_1(a), Any) - length(a) -end -@test __f_isa_arg_1() == 1 - -# issue #14477 -struct Z14477 - fld::Z14477 - Z14477() = new(new()) -end -let z1 = Z14477() - @test isa(z1, Z14477) - @test isa(z1.fld, Z14477) -end - -# issue #8846, generic macros -macro m8846(a, b=0) - a, b -end -@test @m8846(a) === (:a, 0) -@test @m8846(a,1) === (:a, 1) -@test_throws MethodError @eval @m8846(a,b,c) - -# a simple case of parametric dispatch with unions -let foo{T}(x::Union{T,Void},y::Union{T,Void}) = 1 - @test foo(1, nothing) === 1 - @test_throws MethodError foo(nothing, nothing) # can't determine T -end - -module TestMacroGlobalFunction -macro makefn(f,g) - quote - global $(f) - function $(f)(x) - x+1 - end - global $(g) - $(g)(x) = x+2 - end -end -@makefn ff gg -end -@test TestMacroGlobalFunction.ff(1) == 2 -@test TestMacroGlobalFunction.gg(1) == 3 - -# issue #18672 -macro x18672() - quote - function f - end - end -end -let - @test isa(@x18672, Function) -end - -# issue #14564 -@test isa(object_id(Tuple.name.cache), Integer) - -# issue #14691 -mutable struct T14691; a::UInt; end -@test (T14691(0).a = 0) === 0 - -# issue #14245 -f14245() = (v = []; push!(v, length(v)); v) -@test f14245()[1] == 0 - -# issue #9677 -@generated function foo9677{T,N}(x::AbstractArray{T,N}) - quote - x=$N - y=x+1 - return y - end -end -foo9677(x::Array) = invoke(foo9677, Tuple{AbstractArray}, x) -@test foo9677(1:5) == foo9677(randn(3)) - -# issue #6846 -f6846() = (please6846; 2) -@test_throws UndefVarError f6846() - -module M6846 - macro f() - return :(please6846; 2) - end -end -@test_throws UndefVarError @M6846.f() - -# issue #14758 -@test isa(@eval(f14758(; $([]...)) = ()), Function) - -# issue #14767 -@inline f14767(x) = x ? A14767 : () -const A14767 = f14767(false) -@test A14767 === () - -# issue #10985 -f10985(::Any...) = 1 -@test f10985(1, 2, 3) == 1 - -# a tricky case for closure conversion -mutable struct _CaptureInCtor - yy - function _CaptureInCtor(list_file::AbstractString="") - y = 0 - f = x->add_node(y) - new(f(2)) - end - add_node(y) = y+1 -end -@test _CaptureInCtor().yy == 1 - -# issue #14610 -let sometypes = (Int,Int8) - f(::Union{ntuple(i->Type{sometypes[i]}, length(sometypes))...}) = 1 - @test method_exists(f, (Union{Type{Int},Type{Int8}},)) -end - -let - b=()->c - c=1 - @test b() == 1 -end - -# issue #14825 -abstract type abstest_14825 end - -mutable struct t1_14825{A <: abstest_14825, B} - x::A - y::B -end - -mutable struct t2_14825{C, B} <: abstest_14825 - x::C - y::t1_14825{t2_14825{C, B}, B} -end - -@test t2_14825{Int,Int}.types[2] <: t1_14825 - -# issue #14917 -@test isa(let generic - function generic end - end, - Function) - -# f.(x) vectorization syntax (#15032) -@test (x -> 2x).([1,2,3]) == [2,4,6] -@test ((x,y) -> 2x+y^2).([1,2,3],[3,4,5]) == [1,2,3]*2 + [3,4,5].^2 - -# let syntax with multiple lhs -let z = (3,9,42) - let (a,b,c) = z - @test a == 3 && b == 9 && c == 42 - end - let (a,b::Float64,c::Int8) = z - @test a == 3 && b === 9.0 && c === Int8(42) - end - z = (1, z, 10) - let (a, (b,c,d), e) = z - @test (a,b,c,d,e) == (1,3,9,42,10) - end -end - -# issue #15072 -let grphtest = ((1, [2]),) - for (s, g) in grphtest - g_ = map(s -> s+1, g) - @test g_ == [3] - end - for s = 1:1 - end -end - -# issue #13229 -module I13229 -using Base.Test -if !startswith(string(Sys.ARCH), "arm") - global z = 0 - @timed @profile for i = 1:5 - function f(x) - return x + i - end - global z = f(i) - end - @test z == 10 -else - warn("@profile test skipped") -end -end - -# issue #15186 -let ex = quote - $(if true; :(test); end) - end - @test ex.args[2] == :test -end - -# issue #15180 -function f15180{T}(x::T) - X = Array{T}(1) - X[1] = x - @noinline ef{J}(::J) = (J,X[1]) # Use T - ef{J}(::J, ::Int) = (T,J) - return ef -end -@test map(f15180(1), [1,2]) == [(Int,1),(Int,1)] - -let ary = Vector{Any}(10) - check_undef_and_fill(ary, rng) = for i in rng - @test !isassigned(ary, i) - ary[i] = (Float64(i), i) # some non-cached content - @test isassigned(ary, i) - end - # Check if the memory is initially zerod and fill it with value - # to check if these values are not reused later. - check_undef_and_fill(ary, 1:10) - # Check if the memory grown at the end are zerod - ccall(:jl_array_grow_end, Void, (Any, Csize_t), ary, 10) - check_undef_and_fill(ary, 11:20) - # Make sure the content of the memory deleted at the end are not reused - ccall(:jl_array_del_end, Void, (Any, Csize_t), ary, 5) - ccall(:jl_array_grow_end, Void, (Any, Csize_t), ary, 5) - check_undef_and_fill(ary, 16:20) - - # Now check grow/del_end - ary = Vector{Any}(1010) - check_undef_and_fill(ary, 1:1010) - # This del_beg should move the buffer - ccall(:jl_array_del_beg, Void, (Any, Csize_t), ary, 1000) - ccall(:jl_array_grow_beg, Void, (Any, Csize_t), ary, 1000) - check_undef_and_fill(ary, 1:1000) - ary = Vector{Any}(1010) - check_undef_and_fill(ary, 1:1010) - # This del_beg should not move the buffer - ccall(:jl_array_del_beg, Void, (Any, Csize_t), ary, 10) - ccall(:jl_array_grow_beg, Void, (Any, Csize_t), ary, 10) - check_undef_and_fill(ary, 1:10) - - ary = Vector{Any}(1010) - check_undef_and_fill(ary, 1:1010) - ccall(:jl_array_grow_end, Void, (Any, Csize_t), ary, 10) - check_undef_and_fill(ary, 1011:1020) - ccall(:jl_array_del_end, Void, (Any, Csize_t), ary, 10) - ccall(:jl_array_grow_beg, Void, (Any, Csize_t), ary, 10) - check_undef_and_fill(ary, 1:10) - - # Make sure newly malloc'd buffers are filled with 0 - # test this for a few different sizes since we need to make sure - # we are malloc'ing the buffer after the grow_end and malloc is not using - # mmap directly (which may return a zero'd new page). - for n in [50, 51, 100, 101, 200, 201, 300, 301] - ary = Vector{Any}(n) - # Try to free the previous buffer that was filled with random content - # and to increase the chance of getting a non-zero'd buffer next time - gc() - gc() - gc() - ccall(:jl_array_grow_beg, Void, (Any, Csize_t), ary, 4) - ccall(:jl_array_del_beg, Void, (Any, Csize_t), ary, 4) - ccall(:jl_array_grow_end, Void, (Any, Csize_t), ary, n) - ccall(:jl_array_grow_beg, Void, (Any, Csize_t), ary, 4) - check_undef_and_fill(ary, 1:(2n + 4)) - end - - ary = Vector{Any}(100) - ccall(:jl_array_grow_end, Void, (Any, Csize_t), ary, 10000) - ary[:] = 1:length(ary) - ccall(:jl_array_del_beg, Void, (Any, Csize_t), ary, 10000) - # grow on the back until a buffer reallocation happens - cur_ptr = pointer(ary) - while cur_ptr == pointer(ary) - len = length(ary) - ccall(:jl_array_grow_end, Void, (Any, Csize_t), ary, 10) - for i in (len + 1):(len + 10) - @test !isassigned(ary, i) - end - end - - ary = Vector{Any}(100) - ary[:] = 1:length(ary) - ccall(:jl_array_grow_at, Void, (Any, Csize_t, Csize_t), ary, 50, 10) - for i in 51:60 - @test !isassigned(ary, i) - end -end - -# check if we can run multiple finalizers at the same time -# Use a `@noinline` function to make sure the inefficient gc root generation -# doesn't keep the object alive. -@noinline function create_dead_object13995(finalized) - obj = Ref(1) - finalizer(obj, (x)->(finalized[1] = true)) - finalizer(obj, (x)->(finalized[2] = true)) - finalizer(obj, (x)->(finalized[3] = true)) - finalizer(obj, (x)->(finalized[4] = true)) - nothing -end -# disable GC to make sure no collection/promotion happens -# when we are constructing the objects -let gc_enabled13995 = gc_enable(false) - finalized13995 = [false, false, false, false] - create_dead_object13995(finalized13995) - gc_enable(true) - # obj is unreachable and young, a single young gc should collect it - # and trigger all the finalizers. - gc(false) - gc_enable(false) - @test finalized13995 == [true, true, true, true] - gc_enable(gc_enabled13995) -end - -# issue #15283 -j15283 = 0 -let - k15283 = j15283+=1 -end -@test j15283 == 1 -@test !isdefined(:k15283) - -# issue #15264 -module Test15264 - mod1{T}(x::T) = x < 1 ? x : mod1(x-1) -end -@test Test15264.mod1 !== Base.mod1 - -module M15455 -function rpm_provides{T}(r::T) - push!([], select(r,T)) -end -select(a,b) = 0 -end -@test M15455.select(1,2)==0 - -# check that medium-sized array is 64-byte aligned (#15139) -@test Int(pointer(Vector{Float64}(1024))) % 64 == 0 - -# PR #15413 -# Make sure arrayset can handle `Array{T}` (where `T` is a type and not a -# `TypeVar`) without crashing -let - function arrayset_unknown_dim{T}(::Type{T}, n) - Base.arrayset(reshape(Vector{T}(1), ones(Int, n)...), 2, 1) - end - arrayset_unknown_dim(Any, 1) - arrayset_unknown_dim(Any, 2) - arrayset_unknown_dim(Any, 3) - arrayset_unknown_dim(Int, 1) - arrayset_unknown_dim(Int, 2) - arrayset_unknown_dim(Int, 3) -end - -module TestSharedArrayResize -using Base.Test -# Attempting to change the shape of a shared array should unshare it and -# not modify the original data -function test_shared_array_resize{T}(::Type{T}) - len = 100 - a = Vector{T}(len) - function test_unshare(f) - a′ = reshape(reshape(a, (len ÷ 2, 2)), len) - a[:] = 1:length(a) - # The operation should fail on the owner shared array - # and has no side effect. - @test_throws ErrorException f(a) - @test a == [1:len;] - @test a′ == [1:len;] - @test pointer(a) == pointer(a′) - # The operation should pass on the non-owner shared array - # and should unshare the arrays with no effect on the original one. - f(a′) - @test a == [1:len;] - @test pointer(a) != pointer(a′) - end - - test_unshare(a->ccall(:jl_array_del_end, Void, (Any, Csize_t), a, 0)) - test_unshare(a->ccall(:jl_array_del_end, Void, (Any, Csize_t), a, 1)) - test_unshare(a->ccall(:jl_array_del_beg, Void, (Any, Csize_t), a, 0)) - test_unshare(a->ccall(:jl_array_del_beg, Void, (Any, Csize_t), a, 1)) - test_unshare(a->deleteat!(a, 10)) - test_unshare(a->deleteat!(a, 90)) - test_unshare(a->ccall(:jl_array_grow_end, Void, (Any, Csize_t), a, 0)) - test_unshare(a->ccall(:jl_array_grow_end, Void, (Any, Csize_t), a, 1)) - test_unshare(a->ccall(:jl_array_grow_beg, Void, (Any, Csize_t), a, 0)) - test_unshare(a->ccall(:jl_array_grow_beg, Void, (Any, Csize_t), a, 1)) - test_unshare(a->insert!(a, 10, 10)) - test_unshare(a->insert!(a, 90, 90)) -end -test_shared_array_resize(Int) -test_shared_array_resize(Any) -end - -module TestArrayNUL -using Base.Test -function check_nul(a::Vector{UInt8}) - b = ccall(:jl_array_cconvert_cstring, - Ref{Vector{UInt8}}, (Vector{UInt8},), a) - @test unsafe_load(pointer(b), length(b) + 1) == 0x0 - return b === a -end - -a = UInt8[] -b = "aaa" -c = [0x2, 0x1, 0x3] - -@test check_nul(a) -@test check_nul(Vector{UInt8}(b)) -@test check_nul(c) -d = [0x2, 0x1, 0x3] -@test check_nul(d) -push!(d, 0x3) -@test check_nul(d) -push!(d, 0x3) -@test check_nul(d) -ccall(:jl_array_del_end, Void, (Any, UInt), d, 2) -@test check_nul(d) -ccall(:jl_array_grow_end, Void, (Any, UInt), d, 1) -@test check_nul(d) -ccall(:jl_array_grow_end, Void, (Any, UInt), d, 1) -@test check_nul(d) -ccall(:jl_array_grow_end, Void, (Any, UInt), d, 10) -@test check_nul(d) -ccall(:jl_array_del_beg, Void, (Any, UInt), d, 8) -@test check_nul(d) -ccall(:jl_array_grow_beg, Void, (Any, UInt), d, 8) -@test check_nul(d) -ccall(:jl_array_grow_beg, Void, (Any, UInt), d, 8) -@test check_nul(d) -f = unsafe_wrap(Array, pointer(d), length(d)) -@test !check_nul(f) -f = unsafe_wrap(Array, ccall(:malloc, Ptr{UInt8}, (Csize_t,), 10), 10, true) -@test !check_nul(f) -g = reinterpret(UInt8, UInt16[0x1, 0x2]) -@test !check_nul(g) -@test check_nul(copy(g)) -end - -# Copy of `#undef` -copy!(Vector{Any}(10), Vector{Any}(10)) -function test_copy_alias{T}(::Type{T}) - ary = T[1:100;] - unsafe_copy!(ary, 1, ary, 11, 90) - @test ary == [11:100; 91:100] - ary = T[1:100;] - unsafe_copy!(ary, 11, ary, 1, 90) - @test ary == [1:10; 1:90] -end -test_copy_alias(Int) -test_copy_alias(Any) - -# issue #15370 -@test isdefined(Core, :Box) -@test !isdefined(Base, :Box) -@test !isdefined(Main, :Box) - -# issue #1784 -let a = [false] -function foo1784() - (a,b) = try - return true - (0,1) - finally - a[1] = true - end -end -@test foo1784() -@test a[1] == true -end - -# issue #14113 -module A14113 - using Base.Test - # show that making several thousand methods (and lots of AST constants) - # doesn't cause any serious issues (for example, for the serializer) - # although to keep runtime on the order of several seconds for this test, - # only several hundred of them are compiled / called - for i = 1:2^14 + 256 - r = rand(2^4) - code = Expr(:tuple, r...) - f = @eval () -> $code - i > (2^14 - 256) && @test [f()...] == r - end -end - -# issue #15425 -@noinline function f15425(x) -end -@test f15425(1) === nothing - -# issue #15809 --- TODO: this code should be disallowed -function f15809() - global g15809 - g15809{T}(x::T) = T -end -f15809() -@test g15809(2) === Int - -module Macro_Yielding_Global_Assignment -macro m() - quote - global x - x = 2 - end -end -@m -end -@test Macro_Yielding_Global_Assignment.x == 2 - -# issue #15718 -@test :(f($NaN)) == :(f($NaN)) -@test isequal(:(f($NaN)), :(f($NaN))) - -# PR #16011 Make sure dead code elimination doesn't delete push and pop -# of metadata -module TestDeadElim16011 -using Base.Test - -function count_expr_push(ex::Expr, head::Symbol, counter) - if ex.head === head - if ex.args[1] === :pop - counter[] -= 1 - else - counter[] += 1 - end - return - end - for arg in ex.args - isa(arg, Expr) && count_expr_push(arg, head, counter) - end - return false -end - -function metadata_matches(ast::CodeInfo) - inbounds_cnt = Ref(0) - boundscheck_cnt = Ref(0) - for ex in ast.code::Array{Any,1} - if isa(ex, Expr) - ex = ex::Expr - count_expr_push(ex, :inbounds, inbounds_cnt) - count_expr_push(ex, :boundscheck, boundscheck_cnt) - end - end - @test inbounds_cnt[] == 0 - @test boundscheck_cnt[] == 0 -end - -function test_metadata_matches(f::ANY, tt::ANY) - metadata_matches(code_typed(f, tt)[1][1]) -end - -function f1() - @inbounds return 1 -end -function f2() - @boundscheck begin - error() - end -end -# No, don't write code this way... -@eval function f3() - a = $(Expr(:boundscheck, true)) - return 1 - b = $(Expr(:boundscheck, :pop)) -end -@noinline function g(a) -end -@eval function f4() - g($(Expr(:inbounds, true))) - @goto out - g($(Expr(:inbounds, :pop))) - @label out -end - -test_metadata_matches(f1, Tuple{}) -test_metadata_matches(f2, Tuple{}) -test_metadata_matches(f3, Tuple{}) -test_metadata_matches(f4, Tuple{}) - -end - -# SSA value where the assignment is after the user in syntactic order -let f = function(a, b) - @goto a - @label b - return j[1] + j[2] * 2 - @label a - j = (a, b) - @goto b -end - @test f(1, 2) == 5 -end - -# issue #8712 -mutable struct Issue8712; end -@test isa(invoke(Issue8712, Tuple{}), Issue8712) - -# issue #16089 -f16089(args...) = typeof(args) -g16089() = f16089(UInt8) -@test g16089() === Tuple{DataType} - -# issue #16023 -function f16023() - x - x = 1 -end -@test_throws UndefVarError f16023() - -# issue #16158 -function f16158(x) - bar(x) = length(x)==1 ? x : string(x, bar(x[1:end-1])) - bar(x) -end -@test f16158("abc") == "abcaba" - -# LLVM verifier error for noreturn function -# the `code_llvm(DevNull, ...)` tests are only meaningful on debug build -# with verifier on (but should still pass on release build). -module TestSSA16244 - -using Base.Test -@noinline k(a) = a - -# unreachable branch due to `ccall(:jl_throw)` -function f1(a) - if a - b = (k(a) + 1, 3) - else - throw(DivideError()) - end - b[1] -end -code_llvm(DevNull, f1, Tuple{Bool}) -@test f1(true) == 2 -@test_throws DivideError f1(false) - -# unreachable branch due to function that does not return -@noinline g() = error() -function f2(a) - if a - b = (k(a) + 1, 3) - else - # Make sure type inference can infer the type of `g` - g() - end - b[1] -end -code_llvm(DevNull, f2, Tuple{Bool}) -@test f2(true) == 2 -@test_throws ErrorException f2(false) - -# SA but not SSA -function f3(a) - if a - b = (k(a) + 1, 3) - end - b[1] -end -code_llvm(DevNull, f3, Tuple{Bool}) -@test f3(true) == 2 -ex = try - f3(false) -catch _ex - _ex -end -@test isa(ex, UndefVarError) -@test ex.var === :b - -# unreachable branch due to ccall that does not return -function f4(a, p) - if a - b = (k(a) + 1, 3) - else - ccall(p, Union{}, ()) - end - b[1] -end -code_llvm(DevNull, f4, Tuple{Bool,Ptr{Void}}) -@test f4(true, C_NULL) == 2 -@test_throws UndefRefError f4(false, C_NULL) - -# SSA due to const prop of condition -function f5(a) - c = true - if c - b = (k(a) + 1, 3) - end - b[1] -end -code_llvm(DevNull, f5, Tuple{Bool}) -@test f5(true) == 2 -@test f5(false) == 1 - -# SSA due to const prop of condition -function f6(a) - if 1 === 1 - b = (k(a) + 1, 3) - end - b[1] -end -code_llvm(DevNull, f6, Tuple{Bool}) -@test f6(true) == 2 -@test f6(false) == 1 - -# unreachable branch due to typeassert -function f7(a) - if a - b = (k(a) + 1, 3) - else - a = a::Int - end - b[1] -end -code_llvm(DevNull, f7, Tuple{Bool}) -@test f7(true) == 2 -@test_throws TypeError f7(false) - -# unreachable branch due to non-Bool used in Bool context -function f8(a, c) - if a - b = (k(a) + 1, 3) - else - c && a - end - b[1] -end -code_llvm(DevNull, f8, Tuple{Bool,Int}) -@test f8(true, 1) == 2 -@test_throws TypeError f8(false, 1) - -# unreachable branch due to undef local variable -function f9(a) - if a - b = (k(a) + 1, 3) - else - d - d = 1 - end - b[1] -end -code_llvm(DevNull, f9, Tuple{Bool}) -@test f9(true) == 2 -ex = try - f9(false) -catch _ex - _ex -end -@test isa(ex, UndefVarError) -@test ex.var === :d - -end - -# issue #16153 -f16153(x) = 1 -f16153(x::ANY, y...) = 2 -@test f16153("") == 1 -ff16153(x::ANY, y...) = 2 -ff16153(x) = 1 -@test ff16153("") == 1 -g16153(x::ANY, y...) = 1 -g16153(x::ANY, y::ANY) = 2 -@test g16153(1, 1) == 2 -gg16153(x::ANY, y::ANY) = 2 -gg16153(x::ANY, y...) = 1 -@test gg16153(1, 1) == 2 - -# don't remove global variable accesses even if we "know" their type -# see #16090 -f16090() = typeof(undefined_x16090::Tuple{Type{Int}}) -@test_throws UndefVarError f16090() -undefined_x16090 = (Int,) -@test_throws TypeError f16090() - -# issue #12238 -mutable struct A12238{T} end -mutable struct B12238{T,S} - a::A12238{B12238{Int,S}} -end -@test B12238.body.body.types[1] === A12238{B12238{Int}.body} -@test isa(A12238{B12238{Int}}.instance, A12238{B12238{Int}}) -@test !isdefined(B12238.body.body.types[1], :instance) # has free type vars - -# issue #16315 -let a = Any[] - @noinline f() = a[end] - @test (push!(a,10); f()) - (push!(a,2); f()) == 8 - @test a == [10, 2] -end - -# issue #12096 -let a = Val{Val{TypeVar(:_, Int)}}, - b = Val{Val{x} where x<:Int} - - @test !isdefined(a, :instance) - @test isdefined(b, :instance) - @test isleaftype(b) -end - -# A return type widened to Type{Union{T,Void}} should not confuse -# codegen -@noinline MaybeFunc(T) = Union{T, Void} -fMaybeFunc() = MaybeFunc(Int64) -@test fMaybeFunc() == Union{Int64, Void} - -# issue #16431 -function f16431(x) - z::Int = x * 2 - g(y) = begin z = z + y; y + x end - z * g(x) -end -@test @inferred(f16431(1)) == 4 - -# issue #14878 -mutable struct A14878 - ext -end -A14878() = A14878(Dict()) -mutable struct B14878 -end -B14878(ng) = B14878() -function trigger14878() - w = A14878() - w.ext[:14878] = B14878(junk) # junk not defined! - return w -end -@test_throws UndefVarError trigger14878() - -# issue #1090 -function f1090(x)::Int - if x == 1 - return 1 - end - 2.0 -end -@test f1090(1) === 1 -@test f1090(2) === 2 -g1090{T}(x::T)::T = x+1.0 -@test g1090(1) === 2 -@test g1090(Float32(3)) === Float32(4) - -function f17613_2(x)::Float64 - try - return x - catch - return x+1 - end -end -@test isa(f17613_2(1), Float64) - -# return type decl with `where` -function where1090(x::Array{T})::T where T<:Real - return x[1] + 2.0 -end -@test where1090([4]) === 6 -@test_throws MethodError where1090(String[]) - -mutable struct A1090 end -Base.convert(::Type{Int}, ::A1090) = "hey" -f1090()::Int = A1090() -@test_throws TypeError f1090() - -# issue #19106 -function f19106()::Void end -@test f19106() === nothing - -# issue #16783 -function f16783() - T = UInt32 - x::T = 0 - bar() = x+1 -end -@test f16783()() == 1 - -# issue #16767 -mutable struct A16767{T} - a::Base.RefValue{T} -end -mutable struct B16767{T} - b::A16767{B16767{T}} -end -mutable struct C16767{T} - b::A16767{C16767{:a}} -end -@test B16767.body.types[1].types[1].parameters[1].types[1] === A16767{B16767.body} -@test C16767.body.types[1].types[1].parameters[1].types[1] === A16767{C16767{:a}} - -# issue #16340 -function f16340{T}(x::T) - function g{T}(y::T) - return (T,T) - end - return g -end -let g = f16340(1) - @test isa(typeof(g).name.mt.defs.sig, UnionAll) -end - -# issue #16793 -try - abstract type T16793 end -catch -end -@test isa(T16793, Type) -@test isa(abstract type T16793_2 end, Void) - -# issue #17147 -f17147(::Tuple) = 1 -f17147{N}(::Vararg{Tuple,N}) = 2 -@test f17147((), ()) == 2 - -# issue #17449, argument evaluation order -@noinline f17449(x, y) = nothing -@noinline function g17449(r) - r[] = :g - return 1 -end -@noinline function k17449(r, v) - r[] = :k - return v ? 1 : 1.0 -end -function h17449(v) - r = Ref(:h) - f17449(g17449(r), k17449(r, v)) - return r[] -end -@test h17449(true) === :k - -# make sure lowering agrees on sp order -function captsp{T, S}(x::T, y::S) - subf(x2::Int) = T - subf(x2::UInt) = S - return subf(Int(1)), subf(UInt(1)) -end -@test captsp(1, 2.0) == (Int, Float64) - -# issue #15068 -function sp_innersig{T}(x::T) - subf(x2::T) = (x, x2, :a) - subf(x2) = (x, x2, :b) - return (subf(one(T)), subf(unsigned(one(T)))) -end -@test sp_innersig(2) == ((2, 1, :a), (2, UInt(1), :b)) - -# TODO: also allow local variables? -#function local_innersig{T}(x::T) -# V = typeof(x) -# U = unsigned(T) -# subf(x2::T, x3::Complex{V}) = (x, x2, x3) -# subf(x2::U) = (x, x2) -# return (subf(one(T), x * im), subf(unsigned(one(T)))) -#end -#@test local_innersig(Int32(2)) == ((Int32(2), Int32(1), Int32(2)im), (Int32(2), UInt32(1))) -#@test local_innersig(Int64(3)) == ((Int64(3), Int64(1), Int64(3)im), (Int64(3), UInt64(1))) - -# Issue 4914 -let - j(j) = j - @test j(1) == 1 - k(x) = (k = x; k) - @test k(1) == 1 -end - -# PR #18054: compilation of cfunction leaves IRBuilder in bad state, -# causing heap-use-after-free when compiling f18054 -function f18054() - return Cint(0) -end -cfunction(f18054, Cint, ()) - -# issue #18986: the ccall optimization of cfunction leaves JL_TRY stack in bad state -dummy18996() = return nothing -function main18986() - cfunction(dummy18986, Void, ()) - ccall((:dummy2, "this_is_a_nonexisting_library"), Void, ()) -end -@test_throws ErrorException main18986() - -# issue #18085 -f18085(a,x...) = (0,) -for (f,g) in ((:asin,:sin), (:acos,:cos)) - gx = eval(g) - f18085(::Type{Val{f}},x...) = map(x->2gx(x), f18085(Val{g},x...)) -end -@test f18085(Val{:asin},3) === (0.0,) - -# issue #18236 constant VecElement in ast triggers codegen assertion/undef -# VecElement of scalar -v18236 = VecElement(1.0) -ptr18236 = cfunction(identity, VecElement{Float64}, Tuple{VecElement{Float64}}) -@eval @noinline f18236(ptr) = ccall(ptr, VecElement{Float64}, - (VecElement{Float64},), $v18236) -@test f18236(ptr18236) === v18236 -@test !contains(sprint(code_llvm, f18236, Tuple{Ptr{Void}}), "double undef") -# VecElement of struct, not necessarily useful but does have special -# ABI so should be handled correctly -# This struct should be small enough to be passed by value in C ABI -# in order to trigger the problematic code path. -# We should be at least testing this on some platforms. -# Not sure if there's a better way to trigger unboxing in codegen. -v18236_2 = VecElement((Int8(1), Int8(2))) -ptr18236_2 = cfunction(identity, VecElement{NTuple{2,Int8}}, - Tuple{VecElement{NTuple{2,Int8}}}) -@eval @noinline f18236_2(ptr) = ccall(ptr, VecElement{NTuple{2,Int8}}, - (VecElement{NTuple{2,Int8}},), - $v18236_2) -@test f18236_2(ptr18236_2) === v18236_2 - -# issue #18385 -function f18385(g) - if g - a = (1, 2) - end - return a[1] -end -@test f18385(true) === 1 -# variable name in the error is tested above in `TestSSA16244` -@test_throws UndefVarError f18385(false) - -# Another similar issue, make sure newvar nodes are created for the fields -# variables too. -function f18386(a, b, second_pass) - s = 0 - firstpass = true - for i in 1:2 - if firstpass - x = (a, b) - firstpass = !second_pass - end - s += x[1] - end - s -end -@test f18386(1, 2, false) === 2 -# variable name in the error is tested above in `TestSSA16244` -@test_throws UndefVarError f18386(1, 2, true) - -Base.@propagate_inbounds function f18412(a) - @inbounds b = a[1] - return b -end -@test f18412([1]) == 1 - -# issue #18173 -function f18173() - identity(()->successflag) - successflag = false -end -@test f18173() == false - -let _true = Ref(true), f, g, h - @noinline f() = ccall((:time, "error_library_doesnt_exist\0"), Void, ()) # some expression that throws an error in codegen - @noinline g() = _true[] ? 0 : h() - @noinline h() = (g(); f()) - @test_throws ErrorException @code_native h() # due to a failure to compile f() - @test g() == 0 -end - -fVararg(x) = Vararg{x} -gVararg(a::fVararg(Int)) = length(a) -@test gVararg(1,2,3,4,5) == 5 - -# issue #18577 -@generated f18577() = quote ()->1 end -@test try - f18577() - false -catch e - (e::ErrorException).msg -end == "generated function body is not pure. this likely means it contains a closure or comprehension." - -let x = 1 - global g18444 - @noinline g18444(a) = (x += 1; a[]) - f18444_1(a) = invoke(sin, Tuple{Int}, g18444(a)) - f18444_2(a) = invoke(sin, Tuple{Integer}, g18444(a)) - @test_throws ErrorException f18444_1(Ref{Any}(1.0)) - @test x == 2 - @test_throws ErrorException f18444_2(Ref{Any}(1.0)) - @test x == 3 - @test f18444_1(Ref{Any}(1)) === sin(1) - @test x == 4 - @test f18444_2(Ref{Any}(1)) === sin(1) - @test x == 5 -end - -# issue #10981, long argument lists -let a = fill(["sdf"], 2*10^6), temp_vcat(x...) = vcat(x...) - # we introduce a new function `temp_vcat` to make sure there is no existing - # method cache match, leading to a path that allocates a large tuple type. - b = temp_vcat(a...) - @test isa(b, Vector{String}) - @test length(b) == 2*10^6 - @test b[1] == b[end] == "sdf" -end - -# issue #17255, take `deferred_alloc` into account -# when calculating total allocation size. -@noinline function f17255(n) - gc_enable(false) - b0 = Base.gc_bytes() - local a - for i in 1:n - a, t, allocd = @timed [Ref(1) for i in 1:1000] - @test allocd > 0 - b1 = Base.gc_bytes() - if b1 < b0 - return false, a - end - end - return true, a -end -@test f17255(10000)[1] -gc_enable(true) - -# issue #18710 -bad_tvars{T}() = 1 -@test_throws ErrorException @which(bad_tvars()) -@test_throws MethodError bad_tvars() - -# issue #19059 - test for lowering of `let` with assignment not adding Box in simple cases -contains_Box(e::GlobalRef) = (e.name === :Box) -contains_Box(e::ANY) = false -contains_Box(e::Expr) = any(contains_Box, e.args) - -function let_noBox() - local x - for i = 1:2 - if i == 1 - x = 21 - end - let x = x - return () -> x - end - end -end -function let_Box1() - local x - for i = 1:2 - if i == 1 - x = 22 - end - let y = x - return () -> x - end - end -end -function let_Box2() - local x - for i = 1:2 - if i == 1 - x = 23 - end - let x = x - # In the future, this may change to no-Box if lowering improves - return () -> x - x = 43 - end - end -end -function let_Box3() - local x - for i = 1:2 - if i == 1 - x = 24 - end - let y - # In the future, this may change to no-Box if lowering improves - y = x - return () -> x - end - end -end -function let_Box4() - local x, g - for i = 1:2 - if i == 1 - x = 25 - end - let x = x - g = () -> x - x = 44 - end - @test x == 25 - return g - end -end -function let_Box5() - local x, g, h - for i = 1:2 - if i == 1 - x = 25 - end - let x = x - g = () -> (x = 46) - h = () -> x - end - @test x == 25 - @test h() == 25 - @test g() == 46 - @test h() == 46 - @test x == 25 - return g - end -end -@test any(contains_Box, (@code_lowered let_Box1()).code) -@test any(contains_Box, (@code_lowered let_Box2()).code) -@test any(contains_Box, (@code_lowered let_Box3()).code) -@test any(contains_Box, (@code_lowered let_Box4()).code) -@test any(contains_Box, (@code_lowered let_Box5()).code) -@test !any(contains_Box, (@code_lowered let_noBox()).code) -@test let_Box1()() == 22 -@test let_Box2()() == 23 -@test let_Box3()() == 24 -@test let_Box4()() == 44 -@test let_Box5()() == 46 -@test let_noBox()() == 21 - -module TestModuleAssignment -using Base.Test -@eval $(GlobalRef(TestModuleAssignment, :x)) = 1 -@test x == 1 -@eval $(GlobalRef(TestModuleAssignment, :x)) = 2 -@test x == 2 -end - -# issue #14893 -module M14893 -x = 14893 -macro m14893() - :x -end -function f14893() - x = 1 - @m14893 -end -end -function f14893() - x = 2 - M14893.@m14893 -end - -@test f14893() == 14893 -@test M14893.f14893() == 14893 - -# issue #18725 -@test_nowarn @eval Main begin - f18725(x) = 1 - f18725(x) = 2 -end -@test Main.f18725(0) == 2 -@test_warn "WARNING: Method definition f18725(Any) in module Module18725" @eval Main module Module18725 - f18725(x) = 1 - f18725(x) = 2 -end - -# issue #19599 -f19599{T}(x::((S)->Vector{S})(T)...) = 1 -@test f19599([1],[1]) == 1 -@test_throws MethodError f19599([1],[1.0]) - -# avoiding StackOverflowErrors (issues #12007, #10326, #15736) -module SOE -mutable struct Sgnd <: Signed - v::Int -end -using Base.Test -@test_throws ErrorException abs(Sgnd(1)) #12007 -io = IOBuffer() -@test_throws ErrorException show(io, Sgnd(1)) #12007 - -struct MyTime <: Dates.TimeType - value::Int -end -@test_throws ErrorException isless(MyTime(1), now()) - -end # module SOE - -# issue #15240 -@test_nowarn begin - local p15240 - p15240 = ccall(:jl_realloc, Ptr{Void}, (Ptr{Void}, Csize_t), C_NULL, 10) - ccall(:jl_free, Void, (Ptr{Void},), p15240) -end - -# issue #19963 -@test_nowarn ccall(:jl_free, Void, (Ptr{Void},), C_NULL) - -# Wrong string size on 64bits for large string. -if Sys.WORD_SIZE == 64 - @noinline function test_large_string20360(slot) - try - # Do no touch the string to avoid triggering OOM - slot[] = Base._string_n(2^32) - gc(false) - catch ex - # This can happen if there's a virtual address size limit - @test isa(ex, OutOfMemoryError) - @test_broken false - end - return - end - @noinline function tester20360() - gc() - # Makes sure the string is rooted during the `gc(false)` - # but is not before the last gc in this function. - slot = Ref{Any}() - test_large_string20360(slot) - slot[] = nothing - gc() - return - end - @test_nowarn tester20360() -end - -@test_throws ArgumentError eltype(Bottom) - -# issue #16424, re-evaluating type definitions -struct A16424 - x - y -end - -struct A16424 # allowed - x - y -end - -@test_throws ErrorException @eval struct A16424 - x - z -end - -@test_throws ErrorException @eval struct A16424 - x - y::Real -end - -struct B16424{T} - a -end - -struct B16424{T} - a -end - -@test_throws ErrorException @eval struct B16424{S} - a -end - -struct C16424{T,S} - x::T - y::S -end - -struct C16424{T,S} - x::T - y::S -end - -@test_throws ErrorException @eval struct C16424{T,S} - x::S - y::T -end - -struct D16424{T<:Real,S<:T} - x::Vector{S} - y::Vector{T} -end - -struct D16424{T<:Real,S<:T} - x::Vector{S} - y::Vector{T} -end - -@test_throws ErrorException struct D16424{T<:Real,S<:Real} - x::Vector{S} - y::Vector{T} -end - -# issue #20999, allow more type redefinitions -struct T20999 - x::Array{T} where T<:Real -end - -struct T20999 - x::Array{T} where T<:Real -end - -@test_throws ErrorException struct T20999 - x::Array{T} where T<:Integer -end - -let a = Array{Core.TypeofBottom, 1}(2) - @test a[1] == Union{} - @test a == [Union{}, Union{}] -end - -# issue #21178 -struct F21178{A,B} end -b21178(::F1,::F2) where {B1,B2,F1<:F21178{B1,<:Any},F2<:F21178{B2}} = F1,F2,B1,B2 -@test b21178(F21178{1,2}(),F21178{1,2}()) == (F21178{1,2}, F21178{1,2}, 1, 1) - -# issue #21172 -a21172 = f21172(x) = 2x -@test f21172(8) == 16 -@test a21172 === f21172 - -# issue #21271 -f21271() = convert(Tuple{Type{Int}, Type{Float64}}, (Int, Float64))::Tuple{Type{Int}, Type{Float64}} -f21271(x) = x::Tuple{Type{Int}, Type{Float64}} -@test_throws TypeError f21271() -@test_throws TypeError f21271((Int, Float64)) - -# issue #21397 -bar21397(x::T) where {T} = T -foo21397(x) = bar21397(x) -@test foo21397(Tuple) == DataType - -# issue 21216 -primitive type FP128test <: AbstractFloat 128 end -struct FP128align <: AbstractFloat - i::Int # cause forced misalignment - fp::FP128test -end -let ni128 = sizeof(FP128test) ÷ sizeof(Int), - ns128 = sizeof(FP128align) ÷ sizeof(Int), - nbit = sizeof(Int) * 8, - arr = Vector{FP128align}(2), - offset = Base.datatype_alignment(FP128test) ÷ sizeof(Int), - little, - expected, - arrint = reinterpret(Int, arr) - - @test length(arrint) == 2 * ns128 - arrint .= 1:(2 * ns128) - @test sizeof(FP128test) == 16 - @test arr[1].i == 1 - @test arr[2].i == 1 + ns128 - expected = UInt128(0) - for little in ni128:-1:1 - little += offset - expected = (expected << nbit) + little - end - @test arr[1].fp == reinterpret(FP128test, expected) - expected = UInt128(0) - for little in ni128:-1:1 - little += offset + ns128 - expected = (expected << nbit) + little - end - @test reinterpret(UInt128, arr[2].fp) == expected -end - -# issue #21516 -struct T21516 - x::Vector{Float64} - y::Vector{Float64} - # check that this definition works - T21516(x::Vector{T}, y::Vector{T}) where {T<:Real} = new(float.(x), float.(y)) -end -@test isa(T21516([1],[2]).x, Vector{Float64}) - -# let with type declaration -let letvar::Int = 2 - letvar = 3.0 - @test letvar === 3 -end - -# issue #21568 -f21568() = 0 -function foo21568() - y = 1 - global f21568 - f21568{T<:Real}(x::AbstractArray{T,1}) = y -end -foo21568() -@test f21568([0]) == 1 - -# issue #21719 -mutable struct T21719{V} - f - tol::Float64 - goal::V -end -g21719(f, goal; tol = 1e-6) = T21719(f, tol, goal) -@test isa(g21719(identity, 1.0; tol=0.1), T21719) - -# issue #21581 -global function f21581()::Int - return 2.0 -end -@test f21581() === 2 -global g21581()::Int = 2.0 -@test g21581() === 2 -module M21581 -macro bar() - :(foo21581(x)::Int = x) -end -M21581.@bar -end -@test M21581.foo21581(1) === 1 - -module N21581 -macro foo(var) - quote - function f(x::T = 1) where T - ($(esc(var)), x) - end - f() - end -end -end -let x = 8 - @test @N21581.foo(x) === (8, 1) -end - -# issue #22122 -let - global @inline function f22122(x::T) where {T} - T - end -end -@test f22122(1) === Int - -# issue #22256 -mutable struct Bar22256{AParameter} - inner::Int -end -mutable struct Foo22256 - bar::Bar22256 -end -setbar22256_inner(a) = (a.bar.inner = 3; nothing) -let a_foo = Foo22256(Bar22256{true}(2)) - @test a_foo.bar.inner == 2 - setbar22256_inner(a_foo) - @test a_foo.bar.inner == 3 -end - -# issue #22026 -module M22026 - -macro foo(TYP) - quote - global foofunction - foofunction(x::Type{T}) where {T<:Number} = x - end -end -struct Foo end -@foo Foo - -macro foo2() - quote - global foofunction2 - (foofunction2(x::T)::Float32) where {T<:Number} = 2x - end -end - -@foo2 - -end -@test M22026.foofunction(Int16) === Int16 -@test M22026.foofunction2(3) === 6.0f0 - -# issue #23218 -let idx = (7,5,9) - (v,) = (idx...,) - @test v == 7 -end diff --git a/julia-0.6.3/share/julia/test/datafmt.jl b/julia-0.6.3/share/julia/test/datafmt.jl deleted file mode 100644 index 8f936d6..0000000 --- a/julia-0.6.3/share/julia/test/datafmt.jl +++ /dev/null @@ -1,284 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -# countlines -@test countlines(IOBuffer("\n")) == 1 -@test countlines(IOBuffer("\n"),'\r') == 0 -@test countlines(IOBuffer("\n\n\n\n\n\n\n\n\n\n")) == 10 -@test countlines(IOBuffer("\n \n \n \n \n \n \n \n \n \n")) == 10 -@test countlines(IOBuffer("\r\n \r\n \r\n \r\n \r\n")) == 5 -file = tempname() -write(file,"Spiffy header\nspectacular first row\neven better 2nd row\nalmost done\n") -@test countlines(file) == 4 -@test countlines(file,'\r') == 0 -@test countlines(file,'\n') == 4 -rm(file) - -isequaldlm(m1, m2, t) = isequal(m1, m2) && (eltype(m1) == eltype(m2) == t) - -@test isequaldlm(readdlm(IOBuffer("1\t2\n3\t4\n5\t6\n")), [1. 2; 3 4; 5 6], Float64) -@test isequaldlm(readdlm(IOBuffer("1\t2\n3\t4\n5\t6\n"), Int), [1 2; 3 4; 5 6], Int) - -@test size(readcsv(IOBuffer("1,2,3,4"))) == (1,4) -@test size(readcsv(IOBuffer("1,2,3,"))) == (1,4) -@test size(readcsv(IOBuffer("1,2,3,4\n"))) == (1,4) -@test size(readcsv(IOBuffer("1,2,3,\n"))) == (1,4) -@test size(readcsv(IOBuffer("1,2,3,4\n1,2,3,4"))) == (2,4) -@test size(readcsv(IOBuffer("1,2,3,4\n1,2,3,"))) == (2,4) -@test size(readcsv(IOBuffer("1,2,3,4\n1,2,3"))) == (2,4) - -@test size(readcsv(IOBuffer("1,2,3,4\r\n"))) == (1,4) -@test size(readcsv(IOBuffer("1,2,3,4\r\n1,2,3\r\n"))) == (2,4) -@test size(readcsv(IOBuffer("1,2,3,4\r\n1,2,3,4\r\n"))) == (2,4) -@test size(readcsv(IOBuffer("1,2,3,\"4\"\r\n1,2,3,4\r\n"))) == (2,4) - -@test size(readdlm(IOBuffer("1 2 3 4\n1 2 3"))) == (2,4) -@test size(readdlm(IOBuffer("1\t2 3 4\n1 2 3"))) == (2,4) -@test size(readdlm(IOBuffer("1\t 2 3 4\n1 2 3"))) == (2,4) -@test size(readdlm(IOBuffer("1\t 2 3 4\n1 2 3\n"))) == (2,4) -@test size(readdlm(IOBuffer("1,,2,3,4\n1,2,3\n"), ',')) == (2,5) - -let result1 = reshape(Any["", "", "", "", "", "", 1.0, 1.0, "", "", "", "", "", 1.0, 2.0, "", 3.0, "", "", "", "", "", 4.0, "", "", ""], 2, 13), - result2 = reshape(Any[1.0, 1.0, 2.0, 1.0, 3.0, "", 4.0, ""], 2, 4) - - @test isequaldlm(readdlm(IOBuffer(",,,1,,,,2,3,,,4,\n,,,1,,,1\n"), ','), result1, Any) - @test isequaldlm(readdlm(IOBuffer(" 1 2 3 4 \n 1 1\n")), result2, Any) - @test isequaldlm(readdlm(IOBuffer(" 1 2 3 4 \n 1 1\n"), ' '), result1, Any) - @test isequaldlm(readdlm(IOBuffer("1 2\n3 4 \n")), [[1.0, 3.0] [2.0, 4.0]], Float64) -end - -let result1 = reshape(Any["", "", "", "", "", "", "भारत", 1.0, "", "", "", "", "", 1.0, 2.0, "", 3.0, "", "", "", "", "", 4.0, "", "", ""], 2, 13) - @test isequaldlm(readdlm(IOBuffer(",,,भारत,,,,2,3,,,4,\n,,,1,,,1\n"), ',') , result1, Any) -end - -let result1 = reshape(Any[1.0, 1.0, 2.0, 2.0, 3.0, 3.0, 4.0, ""], 2, 4) - @test isequaldlm(readdlm(IOBuffer("1\t 2 3 4\n1 2 3")), result1, Any) - @test isequaldlm(readdlm(IOBuffer("1\t 2 3 4\n1 2 3 ")), result1, Any) - @test isequaldlm(readdlm(IOBuffer("1\t 2 3 4\n1 2 3\n")), result1, Any) - @test isequaldlm(readdlm(IOBuffer("1,2,3,4\n1,2,3\n"), ','), result1, Any) - @test isequaldlm(readdlm(IOBuffer("1,2,3,4\n1,2,3"), ','), result1, Any) - @test isequaldlm(readdlm(IOBuffer("1,2,3,4\r\n1,2,3\r\n"), ','), result1, Any) - @test isequaldlm(readdlm(IOBuffer("1,2,3,\"4\"\r\n1,2,3\r\n"), ','), result1, Any) -end - -let result1 = reshape(Any["abc", "hello", "def,ghi", " \"quote\" ", "new\nline", "world"], 2, 3), - result2 = reshape(Any["abc", "line\"", "\"hello\"", "\"def", "", "\" \"\"quote\"\" \"", "ghi\"", "", "world", "\"new", "", ""], 3, 4) - - @test isequaldlm(readdlm(IOBuffer("abc,\"def,ghi\",\"new\nline\"\n\"hello\",\" \"\"quote\"\" \",world"), ','), result1, Any) - @test isequaldlm(readdlm(IOBuffer("abc,\"def,ghi\",\"new\nline\"\n\"hello\",\" \"\"quote\"\" \",world"), ',', quotes=false), result2, Any) -end - -let result1 = reshape(Any["t", "c", "", "c"], 2, 2), - result2 = reshape(Any["t", "\"c", "t", "c"], 2, 2) - @test isequaldlm(readdlm(IOBuffer("t \n\"c\" c")), result1, Any) - @test isequaldlm(readdlm(IOBuffer("t t \n\"\"\"c\" c")), result2, Any) -end - -@test isequaldlm(readcsv(IOBuffer("\n1,2,3\n4,5,6\n\n\n"), skipblanks=false), - reshape(Any["",1.0,4.0,"","","",2.0,5.0,"","","",3.0,6.0,"",""], 5, 3), Any) -@test isequaldlm(readcsv(IOBuffer("\n1,2,3\n4,5,6\n\n\n"), skipblanks=true), reshape([1.0,4.0,2.0,5.0,3.0,6.0], 2, 3), Float64) -@test isequaldlm(readcsv(IOBuffer("1,2\n\n4,5"), skipblanks=false), reshape(Any[1.0,"",4.0,2.0,"",5.0], 3, 2), Any) -@test isequaldlm(readcsv(IOBuffer("1,2\n\n4,5"), skipblanks=true), reshape([1.0,4.0,2.0,5.0], 2, 2), Float64) - -let x = bitrand(5, 10), io = IOBuffer() - writedlm(io, x) - seek(io, 0) - @test readdlm(io, Bool) == x -end - -let x = [1,2,3], y = [4,5,6], io = IOBuffer() - writedlm(io, zip(x,y), ", ") - seek(io, 0) - @test readcsv(io) == [x y] -end - -let x = [0.1 0.3 0.5], io = IOBuffer() - writedlm(io, x, ", ") - seek(io, 0) - @test readstring(io) == "0.1, 0.3, 0.5\n" -end - -let x = [0.1 0.3 0.5], io = IOBuffer() - writedlm(io, x, ", ") - seek(io, 0) - @test readcsv(io) == [0.1 0.3 0.5] -end - -let x = ["abc", "def\"ghi", "jk\nl"], y = [1, ",", "\"quoted\""], io = IOBuffer() - writedlm(io, zip(x,y), ',') - seek(io, 0) - @test readcsv(io) == [x y] -end - -let x = ["a" "b"; "d" ""], io = IOBuffer() - writedlm(io, x) - seek(io, 0) - @test readdlm(io) == x -end - -let x = ["\"hello\"", "world\""], io = IOBuffer() - writedlm(io, x, quotes=false) - @test String(take!(io)) == "\"hello\"\nworld\"\n" - - writedlm(io, x) - @test String(take!(io)) == "\"\"\"hello\"\"\"\n\"world\"\"\"\n" -end - -# test comments -@test isequaldlm(readcsv(IOBuffer("#this is comment\n1,2,3\n#one more comment\n4,5,6")), [1. 2. 3.;4. 5. 6.], Float64) -@test isequaldlm(readcsv(IOBuffer("#this is \n#comment\n1,2,3\n#one more \n#comment\n4,5,6")), [1. 2. 3.;4. 5. 6.], Float64) -@test isequaldlm(readcsv(IOBuffer("1,2,#3\n4,5,6")), [1. 2. "";4. 5. 6.], Any) -@test isequaldlm(readcsv(IOBuffer("1#,2,3\n4,5,6")), [1. "" "";4. 5. 6.], Any) -@test isequaldlm(readcsv(IOBuffer("1,2,\"#3\"\n4,5,6")), [1. 2. "#3";4. 5. 6.], Any) -@test isequaldlm(readcsv(IOBuffer("1,2,3\n #with leading whitespace\n4,5,6")), [1. 2. 3.;" " "" "";4. 5. 6.], Any) - -# test skipstart -let x = ["a" "b" "c"; "d" "e" "f"; "g" "h" "i"; "A" "B" "C"; 1 2 3; 4 5 6; 7 8 9], io = IOBuffer() - writedlm(io, x, quotes=false) - seek(io, 0) - (data, hdr) = readdlm(io, header=true, skipstart=3) - @test data == [1 2 3; 4 5 6; 7 8 9] - @test hdr == ["A" "B" "C"] -end -let x = ["a" "b" "\nc"; "d" "\ne" "f"; "g" "h" "i\n"; "A" "B" "C"; 1 2 3; 4 5 6; 7 8 9] - io = IOBuffer() - writedlm(io, x, quotes=true) - seek(io, 0) - (data, hdr) = readdlm(io, header=true, skipstart=6) - @test data == [1 2 3; 4 5 6; 7 8 9] - @test hdr == ["A" "B" "C"] - - io = IOBuffer() - writedlm(io, x, quotes=false) - seek(io, 0) - (data, hdr) = readdlm(io, header=true, skipstart=6) - @test data == [1 2 3; 4 5 6; 7 8 9] - @test hdr == ["A" "B" "C"] -end - -# source: http://www.i18nguy.com/unicode/unicode-example-utf8.zip -let i18n_data = ["Origin (English)", "Name (English)", "Origin (Native)", "Name (Native)", - "Australia", "Nicole Kidman", "Australia", "Nicole Kidman", - "Austria", "Johann Strauss", "Österreich", "Johann Strauß", - "Belgium (Flemish)", "Rene Magritte", "België", "René Magritte", - "Belgium (French)", "Rene Magritte", "Belgique", "René Magritte", - "Belgium (German)", "Rene Magritte", "Belgien", "René Magritte", - "Bhutan", "Gonpo Dorji", "འབྲུག་ཡུལ།", "མགོན་པོ་རྡོ་རྗེ།", - "Canada", "Celine Dion", "Canada", "Céline Dion", - "Canada - Nunavut (Inuktitut)", "Susan Aglukark", "ᓄᓇᕗᒻᒥᐅᑦ", "ᓱᓴᓐ ᐊᒡᓗᒃᑲᖅ", - "Democratic People's Rep. of Korea", "LEE Sol-Hee", "조선 민주주의 인민 공화국", "이설희", - "Denmark", "Soren Hauch-Fausboll", "Danmark", "Søren Hauch-Fausbøll", - "Denmark", "Soren Kierkegaard", "Danmark", "Søren Kierkegård", - "Egypt", "Abdel Halim Hafez", "ﻣﺼﺮ", "ﻋﺑﺪﺍﻠﺣﻟﻳﻢ ﺤﺎﻓﻅ", - "Egypt", "Om Kolthoum", "ﻣﺼﺮ", "ﺃﻡ ﻛﻟﺛﻭﻡ", - "Eritrea", "Berhane Zeray", "ብርሃነ ዘርኣይ", "ኤርትራ", - "Ethiopia", "Haile Gebreselassie", "ኃይሌ ገብረሥላሴ", "ኢትዮጵያ", - "France", "Gerard Depardieu", "France", "Gérard Depardieu", - "France", "Jean Reno", "France", "Jean Réno", - "France", "Camille Saint-Saens", "France", "Camille Saint-Saëns", - "France", "Mylene Demongeot", "France", "Mylène Demongeot", - "France", "Francois Truffaut", "France", "François Truffaut", - "France (Braille)", "Louis Braille", "⠋⠗⠁⠝⠉⠑", "⠇⠕⠥⠊⠎⠀<BR>⠃⠗⠁⠊⠇⠇⠑", - "Georgia", "Eduard Shevardnadze", "საქართველო", "ედუარდ შევარდნაძე", - "Germany", "Rudi Voeller", "Deutschland", "Rudi Völler", - "Germany", "Walter Schultheiss", "Deutschland", "Walter Schultheiß", - "Greece", "Giorgos Dalaras", "Ελλάς", "Γιώργος Νταλάρας", - "Iceland", "Bjork Gudmundsdottir", "Ísland", "Björk Guðmundsdóttir", - "India (Hindi)", "Madhuri Dixit", "भारत", "माधुरी दिछित", - "Ireland", "Sinead O'Connor", "Éire", "Sinéad O'Connor", - "Israel", "Yehoram Gaon", "ישראל", "יהורם גאון", - "Italy", "Fabrizio DeAndre", "Italia", "Fabrizio De André", - "Japan", "KUBOTA Toshinobu", "日本", "久保田    利伸", - "Japan", "HAYASHIBARA Megumi", "日本", "林原 めぐみ", - "Japan", "Mori Ogai", "日本", "森鷗外", - "Japan", "Tex Texin", "日本", "テクス テクサン", - "Norway", "Tor Age Bringsvaerd", "Noreg", "Tor Åge Bringsværd", - "Pakistan (Urdu)", "Nusrat Fatah Ali Khan", "پاکستان", "نصرت فتح علی خان", - "People's Rep. of China", "ZHANG Ziyi", "中国", "章子怡", - "People's Rep. of China", "WONG Faye", "中国", "王菲", - "Poland", "Lech Walesa", "Polska", "Lech Wałęsa", - "Puerto Rico", "Olga Tanon", "Puerto Rico", "Olga Tañón", - "Rep. of China", "Hsu Chi", "臺灣", "舒淇", - "Rep. of China", "Ang Lee", "臺灣", "李安", - "Rep. of Korea", "AHN Sung-Gi", "한민국", "안성기", - "Rep. of Korea", "SHIM Eun-Ha", "한민국", "심은하", - "Russia", "Mikhail Gorbachev", "Россия", "Михаил Горбачёв", - "Russia", "Boris Grebenshchikov", "Россия", "Борис Гребенщиков", - "Slovenia", "\"Frane \"\"Jezek\"\" Milcinski", "Slovenija", "Frane Milčinski - Ježek", - "Syracuse (Sicily)", "Archimedes", "Συρακούσα", "Ἀρχιμήδης", - "Thailand", "Thongchai McIntai", "ประเทศไทย", "ธงไชย แม็คอินไตย์", - "U.S.A.", "Brad Pitt", "U.S.A.", "Brad Pitt", - "Yugoslavia (Cyrillic)", "Djordje Balasevic", "Југославија", "Ђорђе Балашевић", - "Yugoslavia (Latin)", "Djordje Balasevic", "Jugoslavija", "Đorđe Balašević"] - - i18n_arr = permutedims(reshape(i18n_data, 4, Int(floor(length(i18n_data)/4))), [2, 1]) - i18n_buff = PipeBuffer() - writedlm(i18n_buff, i18n_arr, ',') - @test i18n_arr == readcsv(i18n_buff) - - hdr = i18n_arr[1:1, :] - data = i18n_arr[2:end, :] - writedlm(i18n_buff, i18n_arr, ',') - @test (data, hdr) == readcsv(i18n_buff, header=true) - - writedlm(i18n_buff, i18n_arr, '\t') - @test (data, hdr) == readdlm(i18n_buff, '\t', header=true) -end - -@test isequaldlm(readcsv(IOBuffer("1,22222222222222222222222222222222222222,0x3,10e6\n2000.1,true,false,-10.34"), Any), - reshape(Any[1,2000.1,Float64(22222222222222222222222222222222222222),true,0x3,false,10e6,-10.34], 2, 4), Any) - -@test isequaldlm(readcsv(IOBuffer("-9223355253176920979,9223355253176920979"), Int64), Int64[-9223355253176920979 9223355253176920979], Int64) - -# fix #13028 -for data in ["A B C", "A B C\n"] - data,hdr = readdlm(IOBuffer(data), header=true) - @test hdr == AbstractString["A" "B" "C"] - @test data == Array{Float64}(0, 3) -end - -# fix #13179 parsing unicode lines with default delmiters -@test isequaldlm(readdlm(IOBuffer("# Should ignore this π\n1\tα\n2\tβ\n")), Any[1 "α"; 2 "β"], Any) - -# BigInt parser -let data = "1 2 3" - readdlm(IOBuffer(data), ' ', BigInt) == BigInt[1 2 3] -end - -# test show with MIME types -@test sprint(show, "text/csv", [1 2; 3 4]) == "1,2\n3,4\n" - -for writefunc in ((io,x) -> show(io, "text/csv", x), - (io,x) -> invoke(writedlm, Tuple{IO,Any,Any}, io, x, ",")) - # iterable collections of iterable rows: - let x = [(1,2), (3,4)], io = IOBuffer() - writefunc(io, x) - seek(io, 0) - @test readcsv(io) == [1 2; 3 4] - end - # vectors of strings: - let x = ["foo", "bar"], io = IOBuffer() - writefunc(io, x) - seek(io, 0) - @test vec(readcsv(io)) == x - end -end - -# Test that we can read a write protected file -let fn = tempname() - open(fn, "w") do f - write(f, "Julia") - end - chmod(fn, 0o444) - readdlm(fn)[] == "Julia" - rm(fn) -end - -# issue #21180 -let data = "\"721\",\"1438\",\"1439\",\"…\",\"1\"" - @test readcsv(IOBuffer(data)) == Any[721 1438 1439 "…" 1] -end - -# issue #21207 -let data = "\"1\",\"灣\"\"灣灣灣灣\",\"3\"" - @test readcsv(IOBuffer(data)) == Any[1 "灣\"灣灣灣灣" 3] -end diff --git a/julia-0.6.3/share/julia/test/dates/accessors.jl b/julia-0.6.3/share/julia/test/dates/accessors.jl deleted file mode 100644 index 4e6ab4a..0000000 --- a/julia-0.6.3/share/julia/test/dates/accessors.jl +++ /dev/null @@ -1,208 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -# yearmonthday is the opposite of totaldays -# taking Rata Die Day # and returning proleptic Gregorian date -@test Dates.yearmonthday(-306) == (0, 2, 29) -@test Dates.yearmonth(-306) == (0, 2) -@test Dates.monthday(-306) == (2, 29) -@test Dates.yearmonthday(-305) == (0, 3, 1) -@test Dates.yearmonth(-305) == (0, 3) -@test Dates.monthday(-305) == (3, 1) -@test Dates.yearmonthday(-2) == (0, 12, 29) -@test Dates.yearmonth(-2) == (0, 12) -@test Dates.monthday(-2) == (12, 29) -@test Dates.yearmonthday(-1) == (0, 12, 30) -@test Dates.yearmonth(-1) == (0, 12) -@test Dates.monthday(-1) == (12, 30) -@test Dates.yearmonthday(0) == (0, 12, 31) -@test Dates.yearmonth(-0) == (0, 12) -@test Dates.monthday(-0) == (12, 31) -@test Dates.yearmonthday(1) == (1, 1, 1) -@test Dates.yearmonth(1) == (1, 1) -@test Dates.monthday(1) == (1, 1) -# year, month, and day return the indivial components -# of yearmonthday, avoiding additional calculations when possible -@test Dates.year(-1) == 0 -@test Dates.month(-1) == 12 -@test Dates.day(-1) == 30 -@test Dates.year(0) == 0 -@test Dates.month(0) == 12 -@test Dates.day(0) == 31 -@test Dates.year(1) == 1 -@test Dates.month(1) == 1 -@test Dates.day(1) == 1 -@test Dates.yearmonthday(730120) == (2000, 1, 1) -@test Dates.year(730120) == 2000 -@test Dates.month(730120) == 1 -@test Dates.day(730120) == 1 - -# Test totaldays and yearmonthday from January 1st of "from" to December 31st of "to" -# test_dates(-10000, 10000) takes about 15 seconds -# test_dates(year(typemin(Date)), year(typemax(Date))) is full range -# and would take.......a really long time -let from=0, to=2100, y=0, m=0, d=0 - test_day = Dates.totaldays(from, 1, 1) - for y in from:to - for m = 1:12 - for d = 1:Dates.daysinmonth(y, m) - days = Dates.totaldays(y, m, d) - @test days == test_day - @test (y, m, d) == Dates.yearmonthday(days) - test_day += 1 - end - end - end -end - -# Test year, month, day, hour, minute -let y=0, m=0, d=0, h=0, mi=0 - for m = 1:12 - for d = 1:Dates.daysinmonth(y, m) - for h = 0:23 - for mi = 0:59 - dt = Dates.DateTime(y, m, d, h, mi) - @test y == Dates.year(dt) - @test m == Dates.month(dt) - @test d == Dates.day(dt) - @test d == Dates.dayofmonth(dt) - @test h == Dates.hour(dt) - @test mi == Dates.minute(dt) - @test (m, d) == Dates.monthday(dt) - end - end - end - end -end - -# Test second, millisecond -let y=0, m=0, d=0, h=0, mi=0, s=0, ms=0 - for y in [-2013, -1, 0, 1, 2013] - for m in [1, 6, 12] - for d in [1, 15, Dates.daysinmonth(y, m)] - for h in [0, 12, 23] - for s = 0:59 - for ms in [0, 1, 500, 999] - dt = Dates.DateTime(y, m, d, h, mi, s, ms) - @test y == Dates.year(dt) - @test m == Dates.month(dt) - @test d == Dates.day(dt) - @test h == Dates.hour(dt) - @test s == Dates.second(dt) - @test ms == Dates.millisecond(dt) - end - end - end - end - end - end -end - -let from=0, to=2100, y=0, m=0, d=0 - for y in from:to - for m = 1:12 - for d = 1:Dates.daysinmonth(y, m) - dt = Dates.Date(y, m, d) - @test y == Dates.year(dt) - @test m == Dates.month(dt) - @test d == Dates.day(dt) - end - end - end -end - -# test hour, minute, second -let h=0, mi=0, s=0, ms=0, us=0, ns=0 - for h = (0, 23), mi = (0, 59), s = (0, 59), - ms in (0, 1, 500, 999), us in (0, 1, 500, 999), ns in (0, 1, 500, 999) - t = Dates.Time(h, mi, s, ms, us, ns) - @test h == Dates.hour(t) - @test mi == Dates.minute(t) - @test s == Dates.second(t) - @test ms == Dates.millisecond(t) - @test us == Dates.microsecond(t) - @test ns == Dates.nanosecond(t) - end -end - -# week function -# Tests from https://en.wikipedia.org/wiki/ISO_week_date -@test Dates.week(Dates.Date(2005, 1, 1)) == 53 -@test Dates.week(Dates.Date(2005, 1, 2)) == 53 -@test Dates.week(Dates.Date(2005, 12, 31)) == 52 -@test Dates.week(Dates.Date(2007, 1, 1)) == 1 -@test Dates.week(Dates.Date(2007, 12, 30)) == 52 -@test Dates.week(Dates.Date(2007, 12, 31)) == 1 -@test Dates.week(Dates.Date(2008, 1, 1)) == 1 -@test Dates.week(Dates.Date(2008, 12, 28)) == 52 -@test Dates.week(Dates.Date(2008, 12, 29)) == 1 -@test Dates.week(Dates.Date(2008, 12, 30)) == 1 -@test Dates.week(Dates.Date(2008, 12, 31)) == 1 -@test Dates.week(Dates.Date(2009, 1, 1)) == 1 -@test Dates.week(Dates.Date(2009, 12, 31)) == 53 -@test Dates.week(Dates.Date(2010, 1, 1)) == 53 -@test Dates.week(Dates.Date(2010, 1, 2)) == 53 -@test Dates.week(Dates.Date(2010, 1, 2)) == 53 -# Tests from http://www.epochconverter.com/date-and-time/weeknumbers-by-year.php?year=1999 -dt = Dates.DateTime(1999, 12, 27) -dt1 = Dates.Date(1999, 12, 27) -check = (52, 52, 52, 52, 52, 52, 52, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2) -for i = 1:21 - @test Dates.week(dt) == check[i] - @test Dates.week(dt1) == check[i] - dt = dt + Dates.Day(1) - dt1 = dt1 + Dates.Day(1) -end -# Tests from http://www.epochconverter.com/date-and-time/weeknumbers-by-year.php?year=2000 -dt = Dates.DateTime(2000, 12, 25) -dt1 = Dates.Date(2000, 12, 25) -for i = 1:21 - @test Dates.week(dt) == check[i] - @test Dates.week(dt1) == check[i] - dt = dt + Dates.Day(1) - dt1 = dt1 + Dates.Day(1) -end -# Test from http://www.epochconverter.com/date-and-time/weeknumbers-by-year.php?year=2030 -dt = Dates.DateTime(2030, 12, 23) -dt1 = Dates.Date(2030, 12, 23) -for i = 1:21 - @test Dates.week(dt) == check[i] - @test Dates.week(dt1) == check[i] - dt = dt + Dates.Day(1) - dt1 = dt1 + Dates.Day(1) -end -# Tests from http://www.epochconverter.com/date-and-time/weeknumbers-by-year.php?year=2004 -dt = Dates.DateTime(2004, 12, 20) -dt1 = Dates.Date(2004, 12, 20) -check = (52, 52, 52, 52, 52, 52, 52, 53, 53, 53, 53, 53, 53, 53, 1, 1, 1, 1, 1, 1, 1) -for i = 1:21 - @test Dates.week(dt) == check[i] - @test Dates.week(dt1) == check[i] - dt = dt + Dates.Day(1) - dt1 = dt1 + Dates.Day(1) -end - -# Vectorized accessors -a = Dates.Date(2014, 1, 1) -dr = [a, a, a, a, a, a, a, a, a, a] -@test Dates.year.(dr) == repmat([2014], 10) -@test Dates.month.(dr) == repmat([1], 10) -@test Dates.day.(dr) == repmat([1], 10) - -a = Dates.DateTime(2014, 1, 1) -dr = [a, a, a, a, a, a, a, a, a, a] -@test Dates.year.(dr) == repmat([2014], 10) -@test Dates.month.(dr) == repmat([1], 10) -@test Dates.day.(dr) == repmat([1], 10) -@test Dates.hour.(dr) == repmat([0], 10) -@test Dates.minute.(dr) == repmat([0], 10) -@test Dates.second.(dr) == repmat([0], 10) -@test Dates.millisecond.(dr) == repmat([0], 10) - -b = Dates.Time(1, 2, 3, 4, 5, 6) -tr = [b, b, b, b, b, b, b, b, b, b] -@test Dates.hour.(tr) == repmat([1], 10) -@test Dates.minute.(tr) == repmat([2], 10) -@test Dates.second.(tr) == repmat([3], 10) -@test Dates.millisecond.(tr) == repmat([4], 10) -@test Dates.microsecond.(tr) == repmat([5], 10) -@test Dates.nanosecond.(tr) == repmat([6], 10) diff --git a/julia-0.6.3/share/julia/test/dates/adjusters.jl b/julia-0.6.3/share/julia/test/dates/adjusters.jl deleted file mode 100644 index 5d94dc8..0000000 --- a/julia-0.6.3/share/julia/test/dates/adjusters.jl +++ /dev/null @@ -1,475 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -#trunc -dt = Dates.Date(2012, 12, 21) -@test trunc(dt, Dates.Year) == Dates.Date(2012) -@test trunc(dt, Dates.Month) == Dates.Date(2012, 12) -@test trunc(dt, Dates.Day) == Dates.Date(2012, 12, 21) -dt = Dates.DateTime(2012, 12, 21, 16, 30, 20, 200) -@test trunc(dt, Dates.Year) == Dates.DateTime(2012) -@test trunc(dt, Dates.Month) == Dates.DateTime(2012, 12) -@test trunc(dt, Dates.Day) == Dates.DateTime(2012, 12, 21) -@test trunc(dt, Dates.Hour) == Dates.DateTime(2012, 12, 21, 16) -@test trunc(dt, Dates.Minute) == Dates.DateTime(2012, 12, 21, 16, 30) -@test trunc(dt, Dates.Second) == Dates.DateTime(2012, 12, 21, 16, 30, 20) -@test trunc(dt, Dates.Millisecond) == Dates.DateTime(2012, 12, 21, 16, 30, 20, 200) -t = Dates.Time(1, 2, 3, 4, 5, 6) -@test trunc(t, Dates.Hour) == Dates.Time(1) -@test trunc(t, Dates.Minute) == Dates.Time(1, 2) -@test trunc(t, Dates.Second) == Dates.Time(1, 2, 3) -@test trunc(t, Dates.Millisecond) == Dates.Time(1, 2, 3, 4) -@test trunc(t, Dates.Microsecond) == Dates.Time(1, 2, 3, 4, 5) -@test trunc(t, Dates.Nanosecond) == Dates.Time(1, 2, 3, 4, 5, 6) - -# Date functions -Jan = Dates.DateTime(2013, 1, 1) #Tuesday -Feb = Dates.DateTime(2013, 2, 2) #Saturday -Mar = Dates.DateTime(2013, 3, 3) #Sunday -Apr = Dates.DateTime(2013, 4, 4) #Thursday -May = Dates.DateTime(2013, 5, 5) #Sunday -Jun = Dates.DateTime(2013, 6, 7) #Friday -Jul = Dates.DateTime(2013, 7, 7) #Sunday -Aug = Dates.DateTime(2013, 8, 8) #Thursday -Sep = Dates.DateTime(2013, 9, 9) #Monday -Oct = Dates.DateTime(2013, 10, 10) #Thursday -Nov = Dates.DateTime(2013, 11, 11) #Monday -Dec = Dates.DateTime(2013, 12, 11) #Wednesday - -@test Dates.lastdayofmonth(Jan) == Dates.DateTime(2013, 1, 31) -@test Dates.lastdayofmonth(Feb) == Dates.DateTime(2013, 2, 28) -@test Dates.lastdayofmonth(Mar) == Dates.DateTime(2013, 3, 31) -@test Dates.lastdayofmonth(Apr) == Dates.DateTime(2013, 4, 30) -@test Dates.lastdayofmonth(May) == Dates.DateTime(2013, 5, 31) -@test Dates.lastdayofmonth(Jun) == Dates.DateTime(2013, 6, 30) -@test Dates.lastdayofmonth(Jul) == Dates.DateTime(2013, 7, 31) -@test Dates.lastdayofmonth(Aug) == Dates.DateTime(2013, 8, 31) -@test Dates.lastdayofmonth(Sep) == Dates.DateTime(2013, 9, 30) -@test Dates.lastdayofmonth(Oct) == Dates.DateTime(2013, 10, 31) -@test Dates.lastdayofmonth(Nov) == Dates.DateTime(2013, 11, 30) -@test Dates.lastdayofmonth(Dec) == Dates.DateTime(2013, 12, 31) - -@test Dates.lastdayofmonth(Date(Jan)) == Dates.Date(2013, 1, 31) -@test Dates.lastdayofmonth(Date(Feb)) == Dates.Date(2013, 2, 28) -@test Dates.lastdayofmonth(Date(Mar)) == Dates.Date(2013, 3, 31) -@test Dates.lastdayofmonth(Date(Apr)) == Dates.Date(2013, 4, 30) -@test Dates.lastdayofmonth(Date(May)) == Dates.Date(2013, 5, 31) -@test Dates.lastdayofmonth(Date(Jun)) == Dates.Date(2013, 6, 30) -@test Dates.lastdayofmonth(Date(Jul)) == Dates.Date(2013, 7, 31) -@test Dates.lastdayofmonth(Date(Aug)) == Dates.Date(2013, 8, 31) -@test Dates.lastdayofmonth(Date(Sep)) == Dates.Date(2013, 9, 30) -@test Dates.lastdayofmonth(Date(Oct)) == Dates.Date(2013, 10, 31) -@test Dates.lastdayofmonth(Date(Nov)) == Dates.Date(2013, 11, 30) -@test Dates.lastdayofmonth(Date(Dec)) == Dates.Date(2013, 12, 31) - -@test Dates.firstdayofmonth(Jan) == Dates.DateTime(2013, 1, 1) -@test Dates.firstdayofmonth(Feb) == Dates.DateTime(2013, 2, 1) -@test Dates.firstdayofmonth(Mar) == Dates.DateTime(2013, 3, 1) -@test Dates.firstdayofmonth(Apr) == Dates.DateTime(2013, 4, 1) -@test Dates.firstdayofmonth(May) == Dates.DateTime(2013, 5, 1) -@test Dates.firstdayofmonth(Jun) == Dates.DateTime(2013, 6, 1) -@test Dates.firstdayofmonth(Jul) == Dates.DateTime(2013, 7, 1) -@test Dates.firstdayofmonth(Aug) == Dates.DateTime(2013, 8, 1) -@test Dates.firstdayofmonth(Sep) == Dates.DateTime(2013, 9, 1) -@test Dates.firstdayofmonth(Oct) == Dates.DateTime(2013, 10, 1) -@test Dates.firstdayofmonth(Nov) == Dates.DateTime(2013, 11, 1) -@test Dates.firstdayofmonth(Dec) == Dates.DateTime(2013, 12, 1) - -@test Dates.firstdayofmonth(Date(Jan)) == Dates.Date(2013, 1, 1) -@test Dates.firstdayofmonth(Date(Feb)) == Dates.Date(2013, 2, 1) -@test Dates.firstdayofmonth(Date(Mar)) == Dates.Date(2013, 3, 1) -@test Dates.firstdayofmonth(Date(Apr)) == Dates.Date(2013, 4, 1) -@test Dates.firstdayofmonth(Date(May)) == Dates.Date(2013, 5, 1) -@test Dates.firstdayofmonth(Date(Jun)) == Dates.Date(2013, 6, 1) -@test Dates.firstdayofmonth(Date(Jul)) == Dates.Date(2013, 7, 1) -@test Dates.firstdayofmonth(Date(Aug)) == Dates.Date(2013, 8, 1) -@test Dates.firstdayofmonth(Date(Sep)) == Dates.Date(2013, 9, 1) -@test Dates.firstdayofmonth(Date(Oct)) == Dates.Date(2013, 10, 1) -@test Dates.firstdayofmonth(Date(Nov)) == Dates.Date(2013, 11, 1) -@test Dates.firstdayofmonth(Date(Dec)) == Dates.Date(2013, 12, 1) - -# Test first day of week; 2014-01-06 is a Monday = 1st day of week -a = Dates.Date(2014, 1, 6) -b = Dates.Date(2014, 1, 7) -c = Dates.Date(2014, 1, 8) -d = Dates.Date(2014, 1, 9) -e = Dates.Date(2014, 1, 10) -f = Dates.Date(2014, 1, 11) -g = Dates.Date(2014, 1, 12) -@test Dates.firstdayofweek(a) == a -@test Dates.firstdayofweek(b) == a -@test Dates.firstdayofweek(c) == a -@test Dates.firstdayofweek(d) == a -@test Dates.firstdayofweek(e) == a -@test Dates.firstdayofweek(f) == a -@test Dates.firstdayofweek(g) == a -# Test firstdayofweek over the course of the year -dt = a -for i = 0:364 - @test Dates.firstdayofweek(dt) == a + Dates.Week(div(i, 7)) - dt += Dates.Day(1) -end -a = Dates.DateTime(2014, 1, 6) -b = Dates.DateTime(2014, 1, 7) -c = Dates.DateTime(2014, 1, 8) -d = Dates.DateTime(2014, 1, 9) -e = Dates.DateTime(2014, 1, 10) -f = Dates.DateTime(2014, 1, 11) -g = Dates.DateTime(2014, 1, 12) -@test Dates.firstdayofweek(a) == a -@test Dates.firstdayofweek(b) == a -@test Dates.firstdayofweek(c) == a -@test Dates.firstdayofweek(d) == a -@test Dates.firstdayofweek(e) == a -@test Dates.firstdayofweek(f) == a -@test Dates.firstdayofweek(g) == a -dt = a -for i = 0:364 - @test Dates.firstdayofweek(dt) == a + Dates.Week(div(i, 7)) - dt += Dates.Day(1) -end -@test Dates.firstdayofweek(Dates.DateTime(2013, 12, 24)) == Dates.DateTime(2013, 12, 23) -# Test last day of week; Sunday = last day of week -# 2014-01-12 is a Sunday -a = Dates.Date(2014, 1, 6) -b = Dates.Date(2014, 1, 7) -c = Dates.Date(2014, 1, 8) -d = Dates.Date(2014, 1, 9) -e = Dates.Date(2014, 1, 10) -f = Dates.Date(2014, 1, 11) -g = Dates.Date(2014, 1, 12) -@test Dates.lastdayofweek(a) == g -@test Dates.lastdayofweek(b) == g -@test Dates.lastdayofweek(c) == g -@test Dates.lastdayofweek(d) == g -@test Dates.lastdayofweek(e) == g -@test Dates.lastdayofweek(f) == g -@test Dates.lastdayofweek(g) == g -dt = a -for i = 0:364 - @test Dates.lastdayofweek(dt) == g + Dates.Week(div(i, 7)) - dt += Dates.Day(1) -end -a = Dates.DateTime(2014, 1, 6) -b = Dates.DateTime(2014, 1, 7) -c = Dates.DateTime(2014, 1, 8) -d = Dates.DateTime(2014, 1, 9) -e = Dates.DateTime(2014, 1, 10) -f = Dates.DateTime(2014, 1, 11) -g = Dates.DateTime(2014, 1, 12) -@test Dates.lastdayofweek(a) == g -@test Dates.lastdayofweek(b) == g -@test Dates.lastdayofweek(c) == g -@test Dates.lastdayofweek(d) == g -@test Dates.lastdayofweek(e) == g -@test Dates.lastdayofweek(f) == g -@test Dates.lastdayofweek(g) == g -dt = a -for i = 0:364 - @test Dates.lastdayofweek(dt) == g + Dates.Week(div(i, 7)) - dt += Dates.Day(1) -end -@test Dates.lastdayofweek(Dates.DateTime(2013, 12, 24)) == Dates.DateTime(2013, 12, 29) - -@test Dates.firstdayofquarter(Dates.Date(2014, 2, 2)) == Dates.Date(2014, 1, 1) -@test Dates.firstdayofquarter(Dates.Date(2014, 5, 2)) == Dates.Date(2014, 4, 1) -@test Dates.firstdayofquarter(Dates.Date(2014, 8, 2)) == Dates.Date(2014, 7, 1) -@test Dates.firstdayofquarter(Dates.Date(2014, 12, 2)) == Dates.Date(2014, 10, 1) - -@test Dates.firstdayofquarter(Dates.DateTime(2014, 2, 2)) == Dates.DateTime(2014, 1, 1) -@test Dates.firstdayofquarter(Dates.DateTime(2014, 5, 2)) == Dates.DateTime(2014, 4, 1) -@test Dates.firstdayofquarter(Dates.DateTime(2014, 8, 2)) == Dates.DateTime(2014, 7, 1) -@test Dates.firstdayofquarter(Dates.DateTime(2014, 12, 2)) == Dates.DateTime(2014, 10, 1) - -@test Dates.lastdayofquarter(Dates.Date(2014, 2, 2)) == Dates.Date(2014, 3, 31) -@test Dates.lastdayofquarter(Dates.Date(2014, 5, 2)) == Dates.Date(2014, 6, 30) -@test Dates.lastdayofquarter(Dates.Date(2014, 8, 2)) == Dates.Date(2014, 9, 30) -@test Dates.lastdayofquarter(Dates.Date(2014, 12, 2)) == Dates.Date(2014, 12, 31) - -@test Dates.lastdayofquarter(Dates.DateTime(2014, 2, 2)) == Dates.DateTime(2014, 3, 31) -@test Dates.lastdayofquarter(Dates.DateTime(2014, 5, 2)) == Dates.DateTime(2014, 6, 30) -@test Dates.lastdayofquarter(Dates.DateTime(2014, 8, 2)) == Dates.DateTime(2014, 9, 30) -@test Dates.lastdayofquarter(Dates.DateTime(2014, 12, 2)) == Dates.DateTime(2014, 12, 31) - -firstday = Dates.Date(2014, 1, 1) -lastday = Dates.Date(2014, 12, 31) -for i = 0:364 - dt = firstday + Dates.Day(i) - - @test Dates.firstdayofyear(dt) == firstday - @test Dates.firstdayofyear(DateTime(dt)) == DateTime(firstday) - - @test Dates.lastdayofyear(dt) == lastday - @test Dates.lastdayofyear(DateTime(dt)) == DateTime(lastday) -end - -# Adjusters -# Adjuster Constructors -@test Dates.Date(Dates.ismonday, 2014) == Dates.Date(2014, 1, 6) -@test Dates.Date(Dates.ismonday, 2014, 5) == Dates.Date(2014, 5, 5) - -@test Dates.DateTime(Dates.ismonday, 2014) == Dates.DateTime(2014, 1, 6) -@test Dates.DateTime(Dates.ismonday, 2014, 5) == Dates.DateTime(2014, 5, 5) -@test Dates.DateTime(x->Dates.hour(x)==12, 2014, 5, 21) == Dates.DateTime(2014, 5, 21, 12) -@test Dates.DateTime(x->Dates.minute(x)==30, 2014, 5, 21, 12) == Dates.DateTime(2014, 5, 21, 12, 30) -@test Dates.DateTime(x->Dates.second(x)==30, 2014, 5, 21, 12, 30) == Dates.DateTime(2014, 5, 21, 12, 30, 30) -@test Dates.DateTime(x->Dates.millisecond(x)==500, 2014, 5, 21, 12, 30, 30) == Dates.DateTime(2014, 5, 21, 12, 30, 30, 500) - -# tonext, toprev, tofirst, tolast -dt = Dates.Date(2014, 5, 21) -@test Dates.tonext(dt, Dates.Wed) == Dates.Date(2014, 5, 28) -@test Dates.tonext(dt, Dates.Wed; same=true) == dt -@test Dates.tonext(dt, Dates.Thu) == Dates.Date(2014, 5, 22) -@test Dates.tonext(dt, Dates.Fri) == Dates.Date(2014, 5, 23) -@test Dates.tonext(dt, Dates.Sat) == Dates.Date(2014, 5, 24) -@test Dates.tonext(dt, Dates.Sun) == Dates.Date(2014, 5, 25) -@test Dates.tonext(dt, Dates.Mon) == Dates.Date(2014, 5, 26) -@test Dates.tonext(dt, Dates.Tue) == Dates.Date(2014, 5, 27) -# No dayofweek function for out of range values -@test_throws KeyError Dates.tonext(dt, 8) - -@test Dates.tonext(Dates.Date(0), Dates.Mon) == Dates.Date(0, 1, 3) - -#test func, diff steps, same -@test Dates.tonext(Dates.iswednesday, dt) == Dates.Date(2014, 5, 28) -@test Dates.tonext(Dates.iswednesday, dt; same=true) == dt -@test Dates.tonext(Dates.isthursday, dt) == Dates.Date(2014, 5, 22) -@test Dates.tonext(Dates.isfriday, dt) == Dates.Date(2014, 5, 23) -@test Dates.tonext(Dates.issaturday, dt) == Dates.Date(2014, 5, 24) -@test Dates.tonext(Dates.issunday, dt) == Dates.Date(2014, 5, 25) -@test Dates.tonext(Dates.ismonday, dt) == Dates.Date(2014, 5, 26) -@test Dates.tonext(Dates.istuesday, dt) == Dates.Date(2014, 5, 27) -@test Dates.tonext(Dates.ismonday, Dates.Date(0)) == Dates.Date(0, 1, 3) - -@test Dates.tonext(!Dates.iswednesday, dt) == Dates.Date(2014, 5, 22) -@test Dates.tonext(!Dates.isthursday, dt) == Dates.Date(2014, 5, 23) - -# Reach adjust limit -@test_throws ArgumentError Dates.tonext(Dates.iswednesday, dt; limit=6) - -@test Dates.tonext(Dates.iswednesday, dt;step=Dates.Day(2)) == Dates.Date(2014, 6, 4) -@test Dates.tonext(Dates.iswednesday, dt;step=Dates.Day(3)) == Dates.Date(2014, 6, 11) -@test Dates.tonext(Dates.iswednesday, dt;step=Dates.Day(4)) == Dates.Date(2014, 6, 18) -@test Dates.tonext(Dates.iswednesday, dt;step=Dates.Day(5)) == Dates.Date(2014, 6, 25) -@test Dates.tonext(Dates.iswednesday, dt;step=Dates.Day(6)) == Dates.Date(2014, 7, 2) -@test Dates.tonext(Dates.iswednesday, dt;step=Dates.Day(7)) == Dates.Date(2014, 5, 28) -@test Dates.tonext(Dates.iswednesday, dt;step=Dates.Week(1)) == Dates.Date(2014, 5, 28) -@test Dates.tonext(Dates.iswednesday, dt;step=Dates.Week(2)) == Dates.Date(2014, 6, 4) -@test Dates.tonext(Dates.iswednesday, dt;step=Dates.Week(3)) == Dates.Date(2014, 6, 11) -@test Dates.tonext(Dates.iswednesday, dt;step=Dates.Week(4)) == Dates.Date(2014, 6, 18) -@test Dates.tonext(Dates.iswednesday, dt;step=Dates.Week(5)) == Dates.Date(2014, 6, 25) -@test Dates.tonext(Dates.iswednesday, dt;step=Dates.Week(6)) == Dates.Date(2014, 7, 2) - -@test Dates.tonext(Dates.iswednesday, dt; same=true) == dt -@test Dates.tonext(Dates.isthursday, dt) == Dates.Date(2014, 5, 22) - -#toprev -@test Dates.toprev(dt, Dates.Wed) == Dates.Date(2014, 5, 14) -@test Dates.toprev(dt, Dates.Wed; same=true) == dt -@test Dates.toprev(dt, Dates.Thu) == Dates.Date(2014, 5, 15) -@test Dates.toprev(dt, Dates.Fri) == Dates.Date(2014, 5, 16) -@test Dates.toprev(dt, Dates.Sat) == Dates.Date(2014, 5, 17) -@test Dates.toprev(dt, Dates.Sun) == Dates.Date(2014, 5, 18) -@test Dates.toprev(dt, Dates.Mon) == Dates.Date(2014, 5, 19) -@test Dates.toprev(dt, Dates.Tue) == Dates.Date(2014, 5, 20) -# No dayofweek function for out of range values -@test_throws KeyError Dates.toprev(dt, 8) - -@test Dates.toprev(Dates.Date(0), Dates.Mon) == Dates.Date(-1, 12, 27) - -#tofirst -@test Dates.tofirst(dt, Dates.Mon) == Dates.Date(2014, 5, 5) -@test Dates.tofirst(dt, Dates.Tue) == Dates.Date(2014, 5, 6) -@test Dates.tofirst(dt, Dates.Wed) == Dates.Date(2014, 5, 7) -@test Dates.tofirst(dt, Dates.Thu) == Dates.Date(2014, 5, 1) -@test Dates.tofirst(dt, Dates.Fri) == Dates.Date(2014, 5, 2) -@test Dates.tofirst(dt, Dates.Sat) == Dates.Date(2014, 5, 3) -@test Dates.tofirst(dt, Dates.Sun) == Dates.Date(2014, 5, 4) - -@test Dates.tofirst(dt, Dates.Mon, of=Dates.Year) == Dates.Date(2014, 1, 6) -@test Dates.tofirst(dt, Dates.Tue, of=Dates.Year) == Dates.Date(2014, 1, 7) -@test Dates.tofirst(dt, Dates.Wed, of=Dates.Year) == Dates.Date(2014, 1, 1) -@test Dates.tofirst(dt, Dates.Thu, of=Dates.Year) == Dates.Date(2014, 1, 2) -@test Dates.tofirst(dt, Dates.Fri, of=Dates.Year) == Dates.Date(2014, 1, 3) -@test Dates.tofirst(dt, Dates.Sat, of=Dates.Year) == Dates.Date(2014, 1, 4) -@test Dates.tofirst(dt, Dates.Sun, of=Dates.Year) == Dates.Date(2014, 1, 5) - -@test Dates.tofirst(Dates.Date(0), Dates.Mon) == Dates.Date(0, 1, 3) - -#tolast -@test Dates.tolast(dt, Dates.Mon) == Dates.Date(2014, 5, 26) -@test Dates.tolast(dt, Dates.Tue) == Dates.Date(2014, 5, 27) -@test Dates.tolast(dt, Dates.Wed) == Dates.Date(2014, 5, 28) -@test Dates.tolast(dt, Dates.Thu) == Dates.Date(2014, 5, 29) -@test Dates.tolast(dt, Dates.Fri) == Dates.Date(2014, 5, 30) -@test Dates.tolast(dt, Dates.Sat) == Dates.Date(2014, 5, 31) -@test Dates.tolast(dt, Dates.Sun) == Dates.Date(2014, 5, 25) - -@test Dates.tolast(dt, Dates.Mon, of=Dates.Year) == Dates.Date(2014, 12, 29) -@test Dates.tolast(dt, Dates.Tue, of=Dates.Year) == Dates.Date(2014, 12, 30) -@test Dates.tolast(dt, Dates.Wed, of=Dates.Year) == Dates.Date(2014, 12, 31) -@test Dates.tolast(dt, Dates.Thu, of=Dates.Year) == Dates.Date(2014, 12, 25) -@test Dates.tolast(dt, Dates.Fri, of=Dates.Year) == Dates.Date(2014, 12, 26) -@test Dates.tolast(dt, Dates.Sat, of=Dates.Year) == Dates.Date(2014, 12, 27) -@test Dates.tolast(dt, Dates.Sun, of=Dates.Year) == Dates.Date(2014, 12, 28) - -@test Dates.tolast(Dates.Date(0), Dates.Mon) == Dates.Date(0, 1, 31) - -# filter (was recur) -startdate = Dates.Date(2014, 1, 1) -stopdate = Dates.Date(2014, 2, 1) -@test length(filter(x->true, startdate:stopdate)) == 32 -@test length(filter(x->true, stopdate:Dates.Day(-1):startdate)) == 32 - -Januarymondays2014 = [Dates.Date(2014, 1, 6), Dates.Date(2014, 1, 13), Dates.Date(2014, 1, 20), Dates.Date(2014, 1, 27)] -@test filter(Dates.ismonday, startdate:stopdate) == Januarymondays2014 - -@test_throws MethodError filter((x, y)->x + y, Dates.Date(2013):Dates.Date(2014)) -@test_throws MethodError Dates.DateFunction((x, y)->x + y, Date(0)) -@test_throws ArgumentError Dates.DateFunction((dt)->2, Date(0)) -@test length(filter(x->true, Dates.Date(2013):Dates.Date(2013, 2))) == 32 -@test length(filter(x->true, Dates.Date(2013):Dates.Date(2013, 1, 1))) == 1 -@test length(filter(x->true, Dates.Date(2013):Dates.Date(2013, 1, 2))) == 2 -@test length(filter(x->true, Dates.Date(2013):Dates.Date(2013, 1, 3))) == 3 -@test length(filter(x->true, Dates.Date(2013):Dates.Date(2013, 1, 4))) == 4 -@test length(filter(x->true, Dates.Date(2013):Dates.Date(2013, 1, 5))) == 5 -@test length(filter(x->true, Dates.Date(2013):Dates.Date(2013, 1, 6))) == 6 -@test length(filter(x->true, Dates.Date(2013):Dates.Date(2013, 1, 7))) == 7 -@test length(filter(x->true, Dates.Date(2013):Dates.Date(2013, 1, 8))) == 8 -@test length(filter(x->true, Dates.Date(2013):Dates.Month(1):Dates.Date(2013, 1, 1))) == 1 -@test length(filter(x->true, Dates.Date(2013):Dates.Day(-1):Dates.Date(2012, 1, 1))) == 367 - -# Empty range -@test length(filter(x->true, Dates.Date(2013):Dates.Date(2012, 1, 1))) == 0 - -# All leap days in 20th century -@test length(filter(Dates.Date(1900):Dates.Date(2000)) do x - Dates.month(x) == Dates.Feb && Dates.day(x) == 29 -end) == 24 - -# Thanksgiving: 4th Thursday of November -thanksgiving = x->Dates.dayofweek(x) == Dates.Thu && - Dates.month(x) == Dates.Nov && - Dates.dayofweekofmonth(x) == 4 - -d = Dates.Date(2014, 6, 5) - -@test Dates.tonext(d) do x - thanksgiving(x) -end == Dates.Date(2014, 11, 27) - -@test Dates.toprev(d) do x - thanksgiving(x) -end == Dates.Date(2013, 11, 28) - -# Pittsburgh street cleaning -dr = Dates.Date(2014):Dates.Date(2015) -@test length(filter(dr) do x - Dates.dayofweek(x) == Dates.Tue && - Dates.April < Dates.month(x) < Dates.Nov && - Dates.dayofweekofmonth(x) == 2 -end) == 6 - -# U.S. Federal Holidays -newyears(y) = (y, 1, 1) -independenceday(y) = (y, 7, 4) -veteransday(y) = (y, 11, 11) -christmas(y) = (y, 12, 25) - -isnewyears(dt) = Dates.yearmonthday(dt) == newyears(Dates.year(dt)) -isindependenceday(dt) = Dates.yearmonthday(dt) == independenceday(Dates.year(dt)) -isveteransday(dt) = Dates.yearmonthday(dt) == veteransday(Dates.year(dt)) -ischristmas(dt) = Dates.yearmonthday(dt) == christmas(Dates.year(dt)) -ismartinlutherking(dt) = Dates.dayofweek(dt) == Dates.Mon && - Dates.month(dt) == Dates.Jan && Dates.dayofweekofmonth(dt) == 3 -ispresidentsday(dt) = Dates.dayofweek(dt) == Dates.Mon && - Dates.month(dt) == Dates.Feb && Dates.dayofweekofmonth(dt) == 3 -# Last Monday of May -ismemorialday(dt) = Dates.dayofweek(dt) == Dates.Mon && - Dates.month(dt) == Dates.May && - Dates.dayofweekofmonth(dt) == Dates.daysofweekinmonth(dt) -islaborday(dt) = Dates.dayofweek(dt) == Dates.Mon && - Dates.month(dt) == Dates.Sep && Dates.dayofweekofmonth(dt) == 1 -iscolumbusday(dt) = Dates.dayofweek(dt) == Dates.Mon && - Dates.month(dt) == Dates.Oct && Dates.dayofweekofmonth(dt) == 2 -isthanksgiving(dt) = Dates.dayofweek(dt) == Dates.Thu && - Dates.month(dt) == Dates.Nov && Dates.dayofweekofmonth(dt) == 4 - -function easter(y) - # Butcher's Algorithm: http://www.smart.net/~mmontes/butcher.html - a = y % 19 - b = div(y, 100) - c = y % 100 - d = div(b, 4) - e = b % 4 - f = div(b + 8, 25) - g = div(b - f + 1, 3) - h = (19 * a + b - d - g + 15) % 30 - i = div(c, 4) - k = c % 4 - l = (32 + 2 * e + 2 * i - h - k) % 7 - m = div(a + 11 * h + 22 * l, 451) - month = div(h + l - 7 * m + 114, 31) - p = (h + l - 7 * m + 114) % 31 - return (y, month, p + 1) -end -iseaster(dt) = Dates.yearmonthday(dt) == easter(Dates.year(dt)) - -const HOLIDAYS = x->isnewyears(x) || isindependenceday(x) || - isveteransday(x) || ischristmas(x) || - ismartinlutherking(x) || ispresidentsday(x) || - ismemorialday(x) || islaborday(x) || - iscolumbusday(x) || isthanksgiving(x) - -@test length(filter(HOLIDAYS, dr)) == 11 - -const OBSERVEDHOLIDAYS = x->begin - # If the holiday is on a weekday - if HOLIDAYS(x) && Dates.dayofweek(x) < Dates.Saturday - return true - # Holiday is observed Monday if falls on Sunday - elseif Dates.dayofweek(x) == 1 && HOLIDAYS(x - Dates.Day(1)) - return true - # Holiday is observed Friday if falls on Saturday - elseif Dates.dayofweek(x) == 5 && HOLIDAYS(x + Dates.Day(1)) - return true - else - return false - end -end - -observed = filter(OBSERVEDHOLIDAYS, Dates.Date(1999):Dates.Date(2000)) -@test length(observed) == 11 -@test observed[10] == Dates.Date(1999, 12, 24) -@test observed[11] == Dates.Date(1999, 12, 31) - -# Get all business/working days of 2014 -# Since we have already defined observed holidays, -# we just look at weekend days and negate the result -@test length(filter(Dates.Date(2014):Dates.Date(2015)) do x - !(OBSERVEDHOLIDAYS(x) || - Dates.dayofweek(x) > 5) -end) == 251 - -# First day of the next month for each day of 2014 -@test length([Dates.firstdayofmonth(i + Dates.Month(1)) - for i in Dates.Date(2014):Dates.Date(2014, 12, 31)]) == 365 - -# From those goofy email forwards claiming a "special, lucky month" -# that has 5 Fridays, 5 Saturdays, and 5 Sundays and that it only -# occurs every 823 years -@test length(filter(Date(2000):Dates.Month(1):Date(2016)) do dt - sum = 0 - for i = 1:7 - sum += Dates.dayofweek(dt) > 4 ? Dates.daysofweekinmonth(dt) : 0 - dt += Dates.Day(1) - end - return sum == 15 -end) == 15 # On average, there's one of those months every year - -r = Dates.Time(x->Dates.second(x) == 5, 1) -@test r == Dates.Time(1, 0, 5) - -r = filter(x->Dates.second(x) == 5, Dates.Time(0):Dates.Time(10)) -@test length(r) == 600 -@test first(r) == Dates.Time(0, 0, 5) -@test last(r) == Dates.Time(9, 59, 5) diff --git a/julia-0.6.3/share/julia/test/dates/arithmetic.jl b/julia-0.6.3/share/julia/test/dates/arithmetic.jl deleted file mode 100644 index 98732fe..0000000 --- a/julia-0.6.3/share/julia/test/dates/arithmetic.jl +++ /dev/null @@ -1,441 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -# Time arithmetic -a = Dates.Time(23, 59, 59) -b = Dates.Time(11, 59, 59) -@test Dates.CompoundPeriod(a - b) == Dates.Hour(12) - -# Dates.DateTime arithmetic -a = Dates.DateTime(2013, 1, 1, 0, 0, 0, 1) -b = Dates.DateTime(2013, 1, 1, 0, 0, 0, 0) -@test a - b == Dates.Millisecond(1) -@test Dates.DateTime(2013, 1, 2) - b == Dates.Millisecond(86400000) - -# Dates.DateTime-Year arithmetic -dt = Dates.DateTime(1999, 12, 27) -@test dt + Dates.Year(1) == Dates.DateTime(2000, 12, 27) -@test dt + Dates.Year(100) == Dates.DateTime(2099, 12, 27) -@test dt + Dates.Year(1000) == Dates.DateTime(2999, 12, 27) -@test dt - Dates.Year(1) == Dates.DateTime(1998, 12, 27) -@test dt - Dates.Year(100) == Dates.DateTime(1899, 12, 27) -@test dt - Dates.Year(1000) == Dates.DateTime(999, 12, 27) -dt = Dates.DateTime(2000, 2, 29) -@test dt + Dates.Year(1) == Dates.DateTime(2001, 2, 28) -@test dt - Dates.Year(1) == Dates.DateTime(1999, 2, 28) -@test dt + Dates.Year(4) == Dates.DateTime(2004, 2, 29) -@test dt - Dates.Year(4) == Dates.DateTime(1996, 2, 29) -dt = Dates.DateTime(1972, 6, 30, 23, 59, 59) -@test dt + Dates.Year(1) == Dates.DateTime(1973, 6, 30, 23, 59, 59) -@test dt - Dates.Year(1) == Dates.DateTime(1971, 6, 30, 23, 59, 59) -@test dt + Dates.Year(-1) == Dates.DateTime(1971, 6, 30, 23, 59, 59) -@test dt - Dates.Year(-1) == Dates.DateTime(1973, 6, 30, 23, 59, 59) - -# Wrapping arithemtic for Months -# This ends up being trickier than expected because -# the user might do 2014-01-01 + Month(-14) -# monthwrap figures out the resulting month -# when adding/subtracting months from a date -@test Dates.monthwrap(1, -14) == 11 -@test Dates.monthwrap(1, -13) == 12 -@test Dates.monthwrap(1, -12) == 1 -@test Dates.monthwrap(1, -11) == 2 -@test Dates.monthwrap(1, -10) == 3 -@test Dates.monthwrap(1, -9) == 4 -@test Dates.monthwrap(1, -8) == 5 -@test Dates.monthwrap(1, -7) == 6 -@test Dates.monthwrap(1, -6) == 7 -@test Dates.monthwrap(1, -5) == 8 -@test Dates.monthwrap(1, -4) == 9 -@test Dates.monthwrap(1, -3) == 10 -@test Dates.monthwrap(1, -2) == 11 -@test Dates.monthwrap(1, -1) == 12 -@test Dates.monthwrap(1, 0) == 1 -@test Dates.monthwrap(1, 1) == 2 -@test Dates.monthwrap(1, 2) == 3 -@test Dates.monthwrap(1, 3) == 4 -@test Dates.monthwrap(1, 4) == 5 -@test Dates.monthwrap(1, 5) == 6 -@test Dates.monthwrap(1, 6) == 7 -@test Dates.monthwrap(1, 7) == 8 -@test Dates.monthwrap(1, 8) == 9 -@test Dates.monthwrap(1, 9) == 10 -@test Dates.monthwrap(1, 10) == 11 -@test Dates.monthwrap(1, 11) == 12 -@test Dates.monthwrap(1, 12) == 1 -@test Dates.monthwrap(1, 13) == 2 -@test Dates.monthwrap(1, 24) == 1 -@test Dates.monthwrap(12, -14) == 10 -@test Dates.monthwrap(12, -13) == 11 -@test Dates.monthwrap(12, -12) == 12 -@test Dates.monthwrap(12, -11) == 1 -@test Dates.monthwrap(12, -2) == 10 -@test Dates.monthwrap(12, -1) == 11 -@test Dates.monthwrap(12, 0) == 12 -@test Dates.monthwrap(12, 1) == 1 -@test Dates.monthwrap(12, 2) == 2 -@test Dates.monthwrap(12, 11) == 11 -@test Dates.monthwrap(12, 12) == 12 -@test Dates.monthwrap(12, 13) == 1 - -# yearwrap figures out the resulting year -# when adding/subtracting months from a date -@test Dates.yearwrap(2000, 1, -3600) == 1700 -@test Dates.yearwrap(2000, 1, -37) == 1996 -@test Dates.yearwrap(2000, 1, -36) == 1997 -@test Dates.yearwrap(2000, 1, -35) == 1997 -@test Dates.yearwrap(2000, 1, -25) == 1997 -@test Dates.yearwrap(2000, 1, -24) == 1998 -@test Dates.yearwrap(2000, 1, -23) == 1998 -@test Dates.yearwrap(2000, 1, -14) == 1998 -@test Dates.yearwrap(2000, 1, -13) == 1998 -@test Dates.yearwrap(2000, 1, -12) == 1999 -@test Dates.yearwrap(2000, 1, -11) == 1999 -@test Dates.yearwrap(2000, 1, -2) == 1999 -@test Dates.yearwrap(2000, 1, -1) == 1999 -@test Dates.yearwrap(2000, 1, 0) == 2000 -@test Dates.yearwrap(2000, 1, 1) == 2000 -@test Dates.yearwrap(2000, 1, 11) == 2000 -@test Dates.yearwrap(2000, 1, 12) == 2001 -@test Dates.yearwrap(2000, 1, 13) == 2001 -@test Dates.yearwrap(2000, 1, 23) == 2001 -@test Dates.yearwrap(2000, 1, 24) == 2002 -@test Dates.yearwrap(2000, 1, 25) == 2002 -@test Dates.yearwrap(2000, 1, 36) == 2003 -@test Dates.yearwrap(2000, 1, 3600) == 2300 -@test Dates.yearwrap(2000, 2, -2) == 1999 -@test Dates.yearwrap(2000, 3, 10) == 2001 -@test Dates.yearwrap(2000, 4, -4) == 1999 -@test Dates.yearwrap(2000, 5, 8) == 2001 -@test Dates.yearwrap(2000, 6, -18) == 1998 -@test Dates.yearwrap(2000, 6, -6) == 1999 -@test Dates.yearwrap(2000, 6, 6) == 2000 -@test Dates.yearwrap(2000, 6, 7) == 2001 -@test Dates.yearwrap(2000, 6, 19) == 2002 -@test Dates.yearwrap(2000, 12, -3600) == 1700 -@test Dates.yearwrap(2000, 12, -36) == 1997 -@test Dates.yearwrap(2000, 12, -35) == 1998 -@test Dates.yearwrap(2000, 12, -24) == 1998 -@test Dates.yearwrap(2000, 12, -23) == 1999 -@test Dates.yearwrap(2000, 12, -14) == 1999 -@test Dates.yearwrap(2000, 12, -13) == 1999 -@test Dates.yearwrap(2000, 12, -12) == 1999 -@test Dates.yearwrap(2000, 12, -11) == 2000 -@test Dates.yearwrap(2000, 12, -2) == 2000 -@test Dates.yearwrap(2000, 12, -1) == 2000 -@test Dates.yearwrap(2000, 12, 0) == 2000 -@test Dates.yearwrap(2000, 12, 1) == 2001 -@test Dates.yearwrap(2000, 12, 11) == 2001 -@test Dates.yearwrap(2000, 12, 12) == 2001 -@test Dates.yearwrap(2000, 12, 13) == 2002 -@test Dates.yearwrap(2000, 12, 24) == 2002 -@test Dates.yearwrap(2000, 12, 25) == 2003 -@test Dates.yearwrap(2000, 12, 36) == 2003 -@test Dates.yearwrap(2000, 12, 37) == 2004 -@test Dates.yearwrap(2000, 12, 3600) == 2300 - -dt = Dates.DateTime(1999, 12, 27) -@test dt + Dates.Month(1) == Dates.DateTime(2000, 1, 27) -@test dt + Dates.Month(-1) == Dates.DateTime(1999, 11, 27) -@test dt + Dates.Month(-11) == Dates.DateTime(1999, 1, 27) -@test dt + Dates.Month(11) == Dates.DateTime(2000, 11, 27) -@test dt + Dates.Month(-12) == Dates.DateTime(1998, 12, 27) -@test dt + Dates.Month(12) == Dates.DateTime(2000, 12, 27) -@test dt + Dates.Month(13) == Dates.DateTime(2001, 1, 27) -@test dt + Dates.Month(100) == Dates.DateTime(2008, 4, 27) -@test dt + Dates.Month(1000) == Dates.DateTime(2083, 4, 27) -@test dt - Dates.Month(1) == Dates.DateTime(1999, 11, 27) -@test dt - Dates.Month(-1) == Dates.DateTime(2000, 1, 27) -@test dt - Dates.Month(100) == Dates.DateTime(1991, 8, 27) -@test dt - Dates.Month(1000) == Dates.DateTime(1916, 8, 27) -dt = Dates.DateTime(2000, 2, 29) -@test dt + Dates.Month(1) == Dates.DateTime(2000, 3, 29) -@test dt - Dates.Month(1) == Dates.DateTime(2000, 1, 29) -dt = Dates.DateTime(1972, 6, 30, 23, 59, 59) -@test dt + Dates.Month(1) == Dates.DateTime(1972, 7, 30, 23, 59, 59) -@test dt - Dates.Month(1) == Dates.DateTime(1972, 5, 30, 23, 59, 59) -@test dt + Dates.Month(-1) == Dates.DateTime(1972, 5, 30, 23, 59, 59) - -dt = Dates.DateTime(1999, 12, 27) -@test dt + Dates.Week(1) == Dates.DateTime(2000, 1, 3) -@test dt + Dates.Week(100) == Dates.DateTime(2001, 11, 26) -@test dt + Dates.Week(1000) == Dates.DateTime(2019, 2, 25) -@test dt - Dates.Week(1) == Dates.DateTime(1999, 12, 20) -@test dt - Dates.Week(100) == Dates.DateTime(1998, 1, 26) -@test dt - Dates.Week(1000) == Dates.DateTime(1980, 10, 27) -dt = Dates.DateTime(2000, 2, 29) -@test dt + Dates.Week(1) == Dates.DateTime(2000, 3, 7) -@test dt - Dates.Week(1) == Dates.DateTime(2000, 2, 22) -dt = Dates.DateTime(1972, 6, 30, 23, 59, 59) -@test dt + Dates.Week(1) == Dates.DateTime(1972, 7, 7, 23, 59, 59) -@test dt - Dates.Week(1) == Dates.DateTime(1972, 6, 23, 23, 59, 59) -@test dt + Dates.Week(-1) == Dates.DateTime(1972, 6, 23, 23, 59, 59) - -dt = Dates.DateTime(1999, 12, 27) -@test dt + Dates.Day(1) == Dates.DateTime(1999, 12, 28) -@test dt + Dates.Day(100) == Dates.DateTime(2000, 4, 5) -@test dt + Dates.Day(1000) == Dates.DateTime(2002, 9, 22) -@test dt - Dates.Day(1) == Dates.DateTime(1999, 12, 26) -@test dt - Dates.Day(100) == Dates.DateTime(1999, 9, 18) -@test dt - Dates.Day(1000) == Dates.DateTime(1997, 4, 1) -dt = Dates.DateTime(1972, 6, 30, 23, 59, 59) -@test dt + Dates.Day(1) == Dates.DateTime(1972, 7, 1, 23, 59, 59) -@test dt - Dates.Day(1) == Dates.DateTime(1972, 6, 29, 23, 59, 59) -@test dt + Dates.Day(-1) == Dates.DateTime(1972, 6, 29, 23, 59, 59) - -dt = Dates.DateTime(1999, 12, 27) -@test dt + Dates.Hour(1) == Dates.DateTime(1999, 12, 27, 1) -@test dt + Dates.Hour(100) == Dates.DateTime(1999, 12, 31, 4) -@test dt + Dates.Hour(1000) == Dates.DateTime(2000, 2, 6, 16) -@test dt - Dates.Hour(1) == Dates.DateTime(1999, 12, 26, 23) -@test dt - Dates.Hour(100) == Dates.DateTime(1999, 12, 22, 20) -@test dt - Dates.Hour(1000) == Dates.DateTime(1999, 11, 15, 8) -dt = Dates.DateTime(1972, 6, 30, 23, 59, 59) -@test dt + Dates.Hour(1) == Dates.DateTime(1972, 7, 1, 0, 59, 59) -@test dt - Dates.Hour(1) == Dates.DateTime(1972, 6, 30, 22, 59, 59) -@test dt + Dates.Hour(-1) == Dates.DateTime(1972, 6, 30, 22, 59, 59) - -dt = Dates.DateTime(1999, 12, 27) -@test dt + Dates.Minute(1) == Dates.DateTime(1999, 12, 27, 0, 1) -@test dt + Dates.Minute(100) == Dates.DateTime(1999, 12, 27, 1, 40) -@test dt + Dates.Minute(1000) == Dates.DateTime(1999, 12, 27, 16, 40) -@test dt - Dates.Minute(1) == Dates.DateTime(1999, 12, 26, 23, 59) -@test dt - Dates.Minute(100) == Dates.DateTime(1999, 12, 26, 22, 20) -@test dt - Dates.Minute(1000) == Dates.DateTime(1999, 12, 26, 7, 20) -dt = Dates.DateTime(1972, 6, 30, 23, 59, 59) -@test dt + Dates.Minute(1) == Dates.DateTime(1972, 7, 1, 0, 0, 59) -@test dt - Dates.Minute(1) == Dates.DateTime(1972, 6, 30, 23, 58, 59) -@test dt + Dates.Minute(-1) == Dates.DateTime(1972, 6, 30, 23, 58, 59) - -dt = Dates.DateTime(1999, 12, 27) -@test dt + Dates.Second(1) == Dates.DateTime(1999, 12, 27, 0, 0, 1) -@test dt + Dates.Second(100) == Dates.DateTime(1999, 12, 27, 0, 1, 40) -@test dt + Dates.Second(1000) == Dates.DateTime(1999, 12, 27, 0, 16, 40) -@test dt - Dates.Second(1) == Dates.DateTime(1999, 12, 26, 23, 59, 59) -@test dt - Dates.Second(100) == Dates.DateTime(1999, 12, 26, 23, 58, 20) -@test dt - Dates.Second(1000) == Dates.DateTime(1999, 12, 26, 23, 43, 20) - -dt = Dates.DateTime(1999, 12, 27) -@test dt + Dates.Millisecond(1) == Dates.DateTime(1999, 12, 27, 0, 0, 0, 1) -@test dt + Dates.Millisecond(100) == Dates.DateTime(1999, 12, 27, 0, 0, 0, 100) -@test dt + Dates.Millisecond(1000) == Dates.DateTime(1999, 12, 27, 0, 0, 1) -@test dt - Dates.Millisecond(1) == Dates.DateTime(1999, 12, 26, 23, 59, 59, 999) -@test dt - Dates.Millisecond(100) == Dates.DateTime(1999, 12, 26, 23, 59, 59, 900) -@test dt - Dates.Millisecond(1000) == Dates.DateTime(1999, 12, 26, 23, 59, 59) -dt = Dates.DateTime(1972, 6, 30, 23, 59, 59) -@test dt + Dates.Millisecond(1) == Dates.DateTime(1972, 6, 30, 23, 59, 59, 1) -@test dt - Dates.Millisecond(1) == Dates.DateTime(1972, 6, 30, 23, 59, 58, 999) -@test dt + Dates.Millisecond(-1) == Dates.DateTime(1972, 6, 30, 23, 59, 58, 999) - -dt = Dates.Date(1999, 12, 27) -@test dt + Dates.Year(1) == Dates.Date(2000, 12, 27) -@test dt + Dates.Year(100) == Dates.Date(2099, 12, 27) -@test dt + Dates.Year(1000) == Dates.Date(2999, 12, 27) -@test dt - Dates.Year(1) == Dates.Date(1998, 12, 27) -@test dt - Dates.Year(100) == Dates.Date(1899, 12, 27) -@test dt - Dates.Year(1000) == Dates.Date(999, 12, 27) -dt = Dates.Date(2000, 2, 29) -@test dt + Dates.Year(1) == Dates.Date(2001, 2, 28) -@test dt - Dates.Year(1) == Dates.Date(1999, 2, 28) -@test dt + Dates.Year(4) == Dates.Date(2004, 2, 29) -@test dt - Dates.Year(4) == Dates.Date(1996, 2, 29) - -dt = Dates.Date(1999, 12, 27) -@test dt + Dates.Month(1) == Dates.Date(2000, 1, 27) -@test dt + Dates.Month(100) == Dates.Date(2008, 4, 27) -@test dt + Dates.Month(1000) == Dates.Date(2083, 4, 27) -@test dt - Dates.Month(1) == Dates.Date(1999, 11, 27) -@test dt - Dates.Month(100) == Dates.Date(1991, 8, 27) -@test dt - Dates.Month(1000) == Dates.Date(1916, 8, 27) -dt = Dates.Date(2000, 2, 29) -@test dt + Dates.Month(1) == Dates.Date(2000, 3, 29) -@test dt - Dates.Month(1) == Dates.Date(2000, 1, 29) - -dt = Dates.Date(1999, 12, 27) -@test dt + Dates.Week(1) == Dates.Date(2000, 1, 3) -@test dt + Dates.Week(100) == Dates.Date(2001, 11, 26) -@test dt + Dates.Week(1000) == Dates.Date(2019, 2, 25) -@test dt - Dates.Week(1) == Dates.Date(1999, 12, 20) -@test dt - Dates.Week(100) == Dates.Date(1998, 1, 26) -@test dt - Dates.Week(1000) == Dates.Date(1980, 10, 27) -dt = Dates.Date(2000, 2, 29) -@test dt + Dates.Week(1) == Dates.Date(2000, 3, 7) -@test dt - Dates.Week(1) == Dates.Date(2000, 2, 22) - -dt = Dates.Date(1999, 12, 27) -@test dt + Dates.Day(1) == Dates.Date(1999, 12, 28) -@test dt + Dates.Day(100) == Dates.Date(2000, 4, 5) -@test dt + Dates.Day(1000) == Dates.Date(2002, 9, 22) -@test dt - Dates.Day(1) == Dates.Date(1999, 12, 26) -@test dt - Dates.Day(100) == Dates.Date(1999, 9, 18) -@test dt - Dates.Day(1000) == Dates.Date(1997, 4, 1) - -# Test Time-TimePeriod arithmetic -t = Dates.Time(0) -@test t + Dates.Hour(1) == Dates.Time(1) -@test t - Dates.Hour(1) == Dates.Time(23) -@test t - Dates.Nanosecond(1) == Dates.Time(23, 59, 59, 999, 999, 999) -@test t + Dates.Nanosecond(-1) == Dates.Time(23, 59, 59, 999, 999, 999) -@test t + Dates.Hour(24) == t -@test t + Dates.Nanosecond(86400000000000) == t -@test t - Dates.Nanosecond(86400000000000) == t -@test t + Dates.Minute(1) == Dates.Time(0, 1) -@test t + Dates.Second(1) == Dates.Time(0, 0, 1) -@test t + Dates.Millisecond(1) == Dates.Time(0, 0, 0, 1) -@test t + Dates.Microsecond(1) == Dates.Time(0, 0, 0, 0, 1) -@test_throws MethodError t + Dates.Day(1) - -# Vectorized Time arithmetic -a = Dates.Time(1, 1, 1) -dr = [a, a, a, a, a, a, a, a, a, a] -b = a + Dates.Hour(1) -@test dr .+ Dates.Hour(1) == repmat([b], 10) -b = a + Dates.Second(1) -@test dr .+ Dates.Second(1) == repmat([b], 10) -b = a + Dates.Millisecond(1) -@test dr .+ Dates.Millisecond(1) == repmat([b], 10) -b = a + Dates.Microsecond(1) -@test dr .+ Dates.Microsecond(1) == repmat([b], 10) -b = a + Dates.Nanosecond(1) -@test dr .+ Dates.Nanosecond(1) == repmat([b], 10) - -b = a - Dates.Hour(1) -@test dr .- Dates.Hour(1) == repmat([b], 10) -b = a - Dates.Second(1) -@test dr .- Dates.Second(1) == repmat([b], 10) -b = a - Dates.Millisecond(1) -@test dr .- Dates.Millisecond(1) == repmat([b], 10) -b = a - Dates.Microsecond(1) -@test dr .- Dates.Microsecond(1) == repmat([b], 10) -b = a - Dates.Nanosecond(1) -@test dr .- Dates.Nanosecond(1) == repmat([b], 10) - -# Vectorized arithmetic -a = Dates.Date(2014, 1, 1) -dr = [a, a, a, a, a, a, a, a, a, a] -b = a + Dates.Year(1) -@test dr .+ Dates.Year(1) == repmat([b], 10) -b = a + Dates.Month(1) -@test dr .+ Dates.Month(1) == repmat([b], 10) -b = a + Dates.Day(1) -@test dr .+ Dates.Day(1) == repmat([b], 10) -b = a - Dates.Year(1) -@test dr .- Dates.Year(1) == repmat([b], 10) -b = a - Dates.Month(1) -@test dr .- Dates.Month(1) == repmat([b], 10) -b = a - Dates.Day(1) -@test dr .- Dates.Day(1) == repmat([b], 10) - -# Vectorized arithmetic -b = a + Dates.Year(1) -@test dr .+ Dates.Year(1) == repmat([b], 10) -b = a + Dates.Month(1) -@test dr .+ Dates.Month(1) == repmat([b], 10) -b = a + Dates.Day(1) -@test dr .+ Dates.Day(1) == repmat([b], 10) -b = a - Dates.Year(1) -@test dr .- Dates.Year(1) == repmat([b], 10) -b = a - Dates.Month(1) -@test dr .- Dates.Month(1) == repmat([b], 10) -b = a - Dates.Day(1) -@test dr .- Dates.Day(1) == repmat([b], 10) - -# Month arithmetic minimizes "edit distance", or number of changes -# needed to get a correct answer -# This approach results in a few cases of non-associativity -a = Dates.Date(2012, 1, 29) -@test (a + Dates.Day(1)) + Dates.Month(1) != (a + Dates.Month(1)) + Dates.Day(1) -a = Dates.Date(2012, 1, 30) -@test (a + Dates.Day(1)) + Dates.Month(1) != (a + Dates.Month(1)) + Dates.Day(1) -a = Dates.Date(2012, 2, 29) -@test (a + Dates.Day(1)) + Dates.Month(1) != (a + Dates.Month(1)) + Dates.Day(1) -a = Dates.Date(2012, 3, 30) -@test (a + Dates.Day(1)) + Dates.Month(1) != (a + Dates.Month(1)) + Dates.Day(1) -a = Dates.Date(2012, 4, 30) -@test (a + Dates.Day(1)) + Dates.Month(1) != (a + Dates.Month(1)) + Dates.Day(1) -a = Dates.Date(2012, 5, 30) -@test (a + Dates.Day(1)) + Dates.Month(1) != (a + Dates.Month(1)) + Dates.Day(1) -a = Dates.Date(2012, 6, 30) -@test (a + Dates.Day(1)) + Dates.Month(1) != (a + Dates.Month(1)) + Dates.Day(1) -a = Dates.Date(2012, 8, 30) -@test (a + Dates.Day(1)) + Dates.Month(1) != (a + Dates.Month(1)) + Dates.Day(1) -a = Dates.Date(2012, 9, 30) -@test (a + Dates.Day(1)) + Dates.Month(1) != (a + Dates.Month(1)) + Dates.Day(1) -a = Dates.Date(2012, 10, 30) -@test (a + Dates.Day(1)) + Dates.Month(1) != (a + Dates.Month(1)) + Dates.Day(1) -a = Dates.Date(2012, 11, 30) -@test (a + Dates.Day(1)) + Dates.Month(1) != (a + Dates.Month(1)) + Dates.Day(1) - - -dt = Dates.DateTime(2000, 1, 1, 12, 30, 45, 500) -dt2 = dt + Dates.Year(1) -@test Dates.year(dt2) == 2001 -@test Dates.month(dt2) == 1 -@test Dates.day(dt2) == 1 -@test Dates.hour(dt2) == 12 -@test Dates.minute(dt2) == 30 -@test Dates.second(dt2) == 45 -@test Dates.millisecond(dt2) == 500 - -t1 = [Dates.Date(2009, 1, 1) Dates.Date(2009, 1, 2) Dates.Date(2009, 1, 3); Dates.Date(2009, 2, 1) Dates.Date(2009, 2, 2) Dates.Date(2009, 2, 3)] -t2 = [Dates.Date(2009, 1, 2) Dates.Date(2009, 2, 2) Dates.Date(2010, 1, 3); Dates.Date(2010, 2, 1) Dates.Date(2009, 3, 2) Dates.Date(2009, 2, 4)] -t3 = [Dates.DateTime(2009, 1, 1), Dates.DateTime(2009, 1, 2), Dates.DateTime(2009, 1, 3)] -t4 = [Dates.DateTime(2009, 1, 1, 0, 0, 1), Dates.DateTime(2009, 1, 2, 0, 1), Dates.DateTime(2009, 1, 3, 1)] -t5 = [Dates.Time(0, 0, 0) Dates.Time(0, 0, 1) Dates.Time(0, 0, 2); Dates.Time(0, 1, 0) Dates.Time(0, 2, 0) Dates.Time(0, 3, 0)] - -# TimeType, Array{TimeType} -@test Dates.Date(2010, 1, 1) .- t1 == [Dates.Day(365) Dates.Day(364) Dates.Day(363); Dates.Day(334) Dates.Day(333) Dates.Day(332)] -@test t1 .- Dates.Date(2010, 1, 1) == [Dates.Day(-365) Dates.Day(-364) Dates.Day(-363); Dates.Day(-334) Dates.Day(-333) Dates.Day(-332)] -@test Dates.DateTime(2009, 1, 1) .- t3 == [Dates.Millisecond(0), Dates.Millisecond(-86400000), Dates.Millisecond(-172800000)] -@test t3 .- Dates.DateTime(2009, 1, 1) == [Dates.Millisecond(0), Dates.Millisecond(86400000), Dates.Millisecond(172800000)] -@test Dates.Date(2010, 1, 1) - t1 == [Dates.Day(365) Dates.Day(364) Dates.Day(363); Dates.Day(334) Dates.Day(333) Dates.Day(332)] -@test t1 - Dates.Date(2010, 1, 1) == [Dates.Day(-365) Dates.Day(-364) Dates.Day(-363); Dates.Day(-334) Dates.Day(-333) Dates.Day(-332)] -@test Dates.DateTime(2009, 1, 1) - t3 == [Dates.Millisecond(0), Dates.Millisecond(-86400000), Dates.Millisecond(-172800000)] -@test t3 - Dates.DateTime(2009, 1, 1) == [Dates.Millisecond(0), Dates.Millisecond(86400000), Dates.Millisecond(172800000)] -@test Dates.Time(2) .- t5 == [Dates.Nanosecond(7200000000000) Dates.Nanosecond(7199000000000) Dates.Nanosecond(7198000000000); - Dates.Nanosecond(7140000000000) Dates.Nanosecond(7080000000000) Dates.Nanosecond(7020000000000)] - -# GeneralPeriod, Array{TimeType} -@test Dates.Day(1) .+ t1 == [Dates.Date(2009, 1, 2) Dates.Date(2009, 1, 3) Dates.Date(2009, 1, 4); Dates.Date(2009, 2, 2) Dates.Date(2009, 2, 3) Dates.Date(2009, 2, 4)] -@test Dates.Hour(1) .+ t3 == [Dates.DateTime(2009, 1, 1, 1), Dates.DateTime(2009, 1, 2, 1), Dates.DateTime(2009, 1, 3, 1)] -@test t1 .+ Dates.Day(1) == [Dates.Date(2009, 1, 2) Dates.Date(2009, 1, 3) Dates.Date(2009, 1, 4); Dates.Date(2009, 2, 2) Dates.Date(2009, 2, 3) Dates.Date(2009, 2, 4)] -@test t3 .+ Dates.Hour(1) == [Dates.DateTime(2009, 1, 1, 1), Dates.DateTime(2009, 1, 2, 1), Dates.DateTime(2009, 1, 3, 1)] -@test Dates.Day(1) + t1 == [Dates.Date(2009, 1, 2) Dates.Date(2009, 1, 3) Dates.Date(2009, 1, 4); Dates.Date(2009, 2, 2) Dates.Date(2009, 2, 3) Dates.Date(2009, 2, 4)] -@test Dates.Hour(1) + t3 == [Dates.DateTime(2009, 1, 1, 1), Dates.DateTime(2009, 1, 2, 1), Dates.DateTime(2009, 1, 3, 1)] -@test t1 + Dates.Day(1) == [Dates.Date(2009, 1, 2) Dates.Date(2009, 1, 3) Dates.Date(2009, 1, 4); Dates.Date(2009, 2, 2) Dates.Date(2009, 2, 3) Dates.Date(2009, 2, 4)] -@test t3 + Dates.Hour(1) == [Dates.DateTime(2009, 1, 1, 1), Dates.DateTime(2009, 1, 2, 1), Dates.DateTime(2009, 1, 3, 1)] -@test t5 + Dates.Hour(1) == [Dates.Time(1, 0, 0) Dates.Time(1, 0, 1) Dates.Time(1, 0, 2); Dates.Time(1, 1, 0) Dates.Time(1, 2, 0) Dates.Time(1, 3, 0)] - -@test (Dates.Month(1) + Dates.Day(1)) .+ t1 == [Dates.Date(2009, 2, 2) Dates.Date(2009, 2, 3) Dates.Date(2009, 2, 4); Dates.Date(2009, 3, 2) Dates.Date(2009, 3, 3) Dates.Date(2009, 3, 4)] -@test (Dates.Hour(1) + Dates.Minute(1)) .+ t3 == [Dates.DateTime(2009, 1, 1, 1, 1), Dates.DateTime(2009, 1, 2, 1, 1), Dates.DateTime(2009, 1, 3, 1, 1)] -@test t1 .+ (Dates.Month(1) + Dates.Day(1)) == [Dates.Date(2009, 2, 2) Dates.Date(2009, 2, 3) Dates.Date(2009, 2, 4); Dates.Date(2009, 3, 2) Dates.Date(2009, 3, 3) Dates.Date(2009, 3, 4)] -@test t3 .+ (Dates.Hour(1) + Dates.Minute(1)) == [Dates.DateTime(2009, 1, 1, 1, 1), Dates.DateTime(2009, 1, 2, 1, 1), Dates.DateTime(2009, 1, 3, 1, 1)] -@test (Dates.Month(1) + Dates.Day(1)) + t1 == [Dates.Date(2009, 2, 2) Dates.Date(2009, 2, 3) Dates.Date(2009, 2, 4); Dates.Date(2009, 3, 2) Dates.Date(2009, 3, 3) Dates.Date(2009, 3, 4)] -@test (Dates.Hour(1) + Dates.Minute(1)) + t3 == [Dates.DateTime(2009, 1, 1, 1, 1), Dates.DateTime(2009, 1, 2, 1, 1), Dates.DateTime(2009, 1, 3, 1, 1)] -@test t1 + (Dates.Month(1) + Dates.Day(1)) == [Dates.Date(2009, 2, 2) Dates.Date(2009, 2, 3) Dates.Date(2009, 2, 4); Dates.Date(2009, 3, 2) Dates.Date(2009, 3, 3) Dates.Date(2009, 3, 4)] -@test t3 + (Dates.Hour(1) + Dates.Minute(1)) == [Dates.DateTime(2009, 1, 1, 1, 1), Dates.DateTime(2009, 1, 2, 1, 1), Dates.DateTime(2009, 1, 3, 1, 1)] - -@test t1 .- Dates.Day(1) == [Dates.Date(2008, 12, 31) Dates.Date(2009, 1, 1) Dates.Date(2009, 1, 2); Dates.Date(2009, 1, 31) Dates.Date(2009, 2, 1) Dates.Date(2009, 2, 2)] -@test t3 .- Dates.Hour(1) == [Dates.DateTime(2008, 12, 31, 23), Dates.DateTime(2009, 1, 1, 23), Dates.DateTime(2009, 1, 2, 23)] -@test t1 - Dates.Day(1) == [Dates.Date(2008, 12, 31) Dates.Date(2009, 1, 1) Dates.Date(2009, 1, 2); Dates.Date(2009, 1, 31) Dates.Date(2009, 2, 1) Dates.Date(2009, 2, 2)] -@test t3 - Dates.Hour(1) == [Dates.DateTime(2008, 12, 31, 23), Dates.DateTime(2009, 1, 1, 23), Dates.DateTime(2009, 1, 2, 23)] - -@test t1 .- (Dates.Month(1) + Dates.Day(1)) == [Dates.Date(2008, 11, 30) Dates.Date(2008, 12, 1) Dates.Date(2008, 12, 2); Dates.Date(2008, 12, 31) Dates.Date(2009, 1, 1) Dates.Date(2009, 1, 2)] -@test t3 .- (Dates.Hour(1) + Dates.Minute(1)) == [Dates.DateTime(2008, 12, 31, 22, 59), Dates.DateTime(2009, 1, 1, 22, 59), Dates.DateTime(2009, 1, 2, 22, 59)] -@test t1 - (Dates.Month(1) + Dates.Day(1)) == [Dates.Date(2008, 11, 30) Dates.Date(2008, 12, 1) Dates.Date(2008, 12, 2); Dates.Date(2008, 12, 31) Dates.Date(2009, 1, 1) Dates.Date(2009, 1, 2)] -@test t3 - (Dates.Hour(1) + Dates.Minute(1)) == [Dates.DateTime(2008, 12, 31, 22, 59), Dates.DateTime(2009, 1, 1, 22, 59), Dates.DateTime(2009, 1, 2, 22, 59)] - -# Array{TimeType}, Array{TimeType} -@test t2 - t1 == [Dates.Day(1) Dates.Day(31) Dates.Day(365); Dates.Day(365) Dates.Day(28) Dates.Day(1)] -@test t4 - t3 == [Dates.Millisecond(1000), Dates.Millisecond(60000), Dates.Millisecond(3600000)] -@test (Dates.Date(2009, 1, 1):Dates.Week(1):Dates.Date(2009, 1, 21)) - (Dates.Date(2009, 1, 1):Dates.Day(1):Dates.Date(2009, 1, 3)) == [Dates.Day(0), Dates.Day(6), Dates.Day(12)] -@test (Dates.DateTime(2009, 1, 1, 1, 1, 1):Dates.Second(1):Dates.DateTime(2009, 1, 1, 1, 1, 3)) - (Dates.DateTime(2009, 1, 1, 1, 1):Dates.Second(1):Dates.DateTime(2009, 1, 1, 1, 1, 2)) == [Dates.Second(1), Dates.Second(1), Dates.Second(1)] - -# ensure commutative subtraction methods are not defined, #20205 -@test_throws MethodError Dates.Day(1) .- t1 -@test_throws MethodError Dates.Hour(1) .- t3 -@test_throws MethodError Dates.Day(1) - t1 -@test_throws MethodError Dates.Hour(1) - t3 -@test_throws MethodError (Dates.Month(1) + Dates.Day(1)) .- t1 -@test_throws MethodError (Dates.Hour(1) + Dates.Minute(1)) .- t3 -@test_throws MethodError (Dates.Month(1) + Dates.Day(1)) - t1 -@test_throws MethodError (Dates.Hour(1) + Dates.Minute(1)) - t3 diff --git a/julia-0.6.3/share/julia/test/dates/conversions.jl b/julia-0.6.3/share/julia/test/dates/conversions.jl deleted file mode 100644 index d092ec6..0000000 --- a/julia-0.6.3/share/julia/test/dates/conversions.jl +++ /dev/null @@ -1,112 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -# Test conversion to and from unix -@test Dates.unix2datetime(Dates.datetime2unix(DateTime(2000, 1, 1))) == DateTime(2000, 1, 1) -@test Dates.value(Dates.DateTime(1970)) == Dates.UNIXEPOCH - -# Tests from here: https://en.wikipedia.org/wiki/Unix_time -@test string(Dates.unix2datetime(1095379198.75)) == string("2004-09-16T23:59:58.75") -@test string(Dates.unix2datetime(1095379199.00)) == string("2004-09-16T23:59:59") -@test string(Dates.unix2datetime(1095379199.25)) == string("2004-09-16T23:59:59.25") -@test string(Dates.unix2datetime(1095379199.50)) == string("2004-09-16T23:59:59.5") -@test string(Dates.unix2datetime(1095379199.75)) == string("2004-09-16T23:59:59.75") -@test string(Dates.unix2datetime(1095379200.00)) == string("2004-09-17T00:00:00") -@test string(Dates.unix2datetime(1095379200.25)) == string("2004-09-17T00:00:00.25") -@test string(Dates.unix2datetime(1095379200.50)) == string("2004-09-17T00:00:00.5") -@test string(Dates.unix2datetime(1095379200.75)) == string("2004-09-17T00:00:00.75") -@test string(Dates.unix2datetime(1095379201.00)) == string("2004-09-17T00:00:01") -@test string(Dates.unix2datetime(1095379201.25)) == string("2004-09-17T00:00:01.25") -@test string(Dates.unix2datetime(915148798.75)) == string("1998-12-31T23:59:58.75") -@test string(Dates.unix2datetime(915148799.00)) == string("1998-12-31T23:59:59") -@test string(Dates.unix2datetime(915148799.25)) == string("1998-12-31T23:59:59.25") -@test string(Dates.unix2datetime(915148799.50)) == string("1998-12-31T23:59:59.5") -@test string(Dates.unix2datetime(915148799.75)) == string("1998-12-31T23:59:59.75") -@test string(Dates.unix2datetime(915148800.00)) == string("1999-01-01T00:00:00") -@test string(Dates.unix2datetime(915148800.25)) == string("1999-01-01T00:00:00.25") -@test string(Dates.unix2datetime(915148800.50)) == string("1999-01-01T00:00:00.5") -@test string(Dates.unix2datetime(915148800.75)) == string("1999-01-01T00:00:00.75") -@test string(Dates.unix2datetime(915148801.00)) == string("1999-01-01T00:00:01") -@test string(Dates.unix2datetime(915148801.25)) == string("1999-01-01T00:00:01.25") - -# Test conversion to and from Rata Die -@test Date(Dates.rata2datetime(734869)) == Dates.Date(2013, 1, 1) -@test Dates.datetime2rata(Dates.rata2datetime(734869)) == 734869 - -# Tests from here: http://mysite.verizon.net/aesir_research/date/back.htm#JDN -@test Dates.julian2datetime(1721119.5) == Dates.DateTime(0, 3, 1) -@test Dates.julian2datetime(1721424.5) == Dates.DateTime(0, 12, 31) -@test Dates.julian2datetime(1721425.5) == Dates.DateTime(1, 1, 1) -@test Dates.julian2datetime(2299149.5) == Dates.DateTime(1582, 10, 4) -@test Dates.julian2datetime(2415020.5) == Dates.DateTime(1900, 1, 1) -@test Dates.julian2datetime(2415385.5) == Dates.DateTime(1901, 1, 1) -@test Dates.julian2datetime(2440587.5) == Dates.DateTime(1970, 1, 1) -@test Dates.julian2datetime(2444239.5) == Dates.DateTime(1980, 1, 1) -@test Dates.julian2datetime(2452695.625) == Dates.DateTime(2003, 2, 25, 3) -@test Dates.datetime2julian(Dates.DateTime(2013, 12, 3, 21)) == 2456630.375 - -@test typeof(Dates.now()) <: Dates.DateTime -@test typeof(Dates.today()) <: Dates.Date -@test typeof(Dates.now(Dates.UTC)) <: Dates.DateTime - -if is_apple() - withenv("TZ" => "UTC") do - @test abs(Dates.now() - now(Dates.UTC)) < Dates.Second(1) - end -end -@test abs(Dates.now() - now(Dates.UTC)) < Dates.Hour(16) - -# Issue #9171, #9169 -let t = Dates.Period[Dates.Week(2), Dates.Day(14), Dates.Hour(14 * 24), Dates.Minute(14 * 24 * 60), Dates.Second(14 * 24 * 60 * 60), Dates.Millisecond(14 * 24 * 60 * 60 * 1000)] - for i = 1:length(t) - Pi = typeof(t[i]) - for j = 1:length(t) - @test t[i] == t[j] - end - for j = i+1:length(t) - Pj = typeof(t[j]) - tj1 = t[j] + Pj(1) - @test t[i] < tj1 - @test_throws InexactError Pi(tj1) - @test_throws InexactError Pj(Pi(typemax(Int64))) - @test_throws InexactError Pj(Pi(typemin(Int64))) - end - end -end -@test Dates.Year(3) == Dates.Month(36) -#@test_throws MethodError Int(Dates.Month(36)) # re-enable when deprecation removed -@test Dates.Year(3) < Dates.Month(37) -@test_throws InexactError convert(Dates.Year, Dates.Month(37)) -@test_throws InexactError Dates.Month(Dates.Year(typemax(Int64))) - -# Ensure that conversion of 32-bit integers work -let dt = DateTime(1915, 1, 1, 12) - unix = Int32(Dates.datetime2unix(dt)) - julian = Int32(Dates.datetime2julian(dt)) - - @test Dates.unix2datetime(unix) == dt - @test Dates.julian2datetime(julian) == dt -end - -# "Conversions" to/from numbers -a = Dates.DateTime(2000) -b = Dates.Date(2000) -@test Dates.value(b) == 730120 -@test Dates.value(a) == 63082368000000 -@test convert(Dates.DateTime, Dates.Millisecond(63082368000000)) == a -@test convert(Dates.Millisecond, a) == Dates.Millisecond(63082368000000) -@test Dates.DateTime(Dates.UTM(63082368000000)) == a -@test Dates.DateTime(Dates.UTM(63082368000000.0)) == a -@test convert(Dates.Date, Dates.Day(730120)) == b -@test convert(Dates.Day, b) == Dates.Day(730120) -@test Dates.Date(Dates.UTD(730120)) == b -@test Dates.Date(Dates.UTD(730120.0)) == b -@test Dates.Date(Dates.UTD(Int32(730120))) == b - -dt = Dates.DateTime(2000, 1, 1, 23, 59, 59, 50) -t = Dates.Time(dt) -@test Dates.hour(t) == 23 -@test Dates.minute(t) == 59 -@test Dates.second(t) == 59 -@test Dates.millisecond(t) == 50 -@test Dates.microsecond(t) == 0 -@test Dates.nanosecond(t) == 0 diff --git a/julia-0.6.3/share/julia/test/dates/io.jl b/julia-0.6.3/share/julia/test/dates/io.jl deleted file mode 100644 index b5090ee..0000000 --- a/julia-0.6.3/share/julia/test/dates/io.jl +++ /dev/null @@ -1,447 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -# Test string/show representation of Date -@test string(Dates.Date(1, 1, 1)) == "0001-01-01" # January 1st, 1 AD/CE -@test sprint(show, Dates.Date(1, 1, 1)) == "0001-01-01" -@test string(Dates.Date(0, 12, 31)) == "0000-12-31" # December 31, 1 BC/BCE -@test Dates.Date(1, 1, 1) - Dates.Date(0, 12, 31) == Dates.Day(1) -@test Dates.Date(Dates.UTD(-306)) == Dates.Date(0, 2, 29) -@test string(Dates.Date(0, 1, 1)) == "0000-01-01" # January 1st, 1 BC/BCE -@test string(Dates.Date(-1, 1, 1)) == "-0001-01-01" # January 1st, 2 BC/BCE -@test string(Dates.Date(-1000000, 1, 1)) == "-1000000-01-01" -@test string(Dates.Date(1000000, 1, 1)) == "1000000-01-01" -@test string(Dates.DateTime(2000, 1, 1, 0, 0, 0, 1)) == "2000-01-01T00:00:00.001" -@test sprint(show, Dates.DateTime(2000, 1, 1, 0, 0, 0, 1)) == "2000-01-01T00:00:00.001" -@test string(Dates.DateTime(2000, 1, 1, 0, 0, 0, 2)) == "2000-01-01T00:00:00.002" -@test string(Dates.DateTime(2000, 1, 1, 0, 0, 0, 500)) == "2000-01-01T00:00:00.5" -@test string(Dates.DateTime(2000, 1, 1, 0, 0, 0, 998)) == "2000-01-01T00:00:00.998" -@test string(Dates.DateTime(2000, 1, 1, 0, 0, 0, 999)) == "2000-01-01T00:00:00.999" -@test string(Dates.Time(0)) == "00:00:00" -@test string(Dates.Time(0, 1)) == "00:01:00" -@test string(Dates.Time(0, 1, 2)) == "00:01:02" -@test string(Dates.Time(0, 1, 2, 3)) == "00:01:02.003" -@test string(Dates.Time(0, 1, 2, 3, 4)) == "00:01:02.003004" -@test string(Dates.Time(0, 1, 2, 3, 4, 5)) == "00:01:02.003004005" -@test string(Dates.Time(0, 0, 0, 0, 1)) == "00:00:00.000001" -@test string(Dates.Time(0, 0, 0, 0, 0, 1)) == "00:00:00.000000001" -@test string(Dates.Time(0, 0, 0, 1)) == "00:00:00.001" - -# DateTime parsing -# Useful reference for different locales: http://library.princeton.edu/departments/tsd/katmandu/reference/months.html - -# Allow parsing of strings which are not representable as a TimeType -let str = "02/15/1996 24:00", df = Dates.DateFormat("mm/dd/yyyy HH:MM") - parsed = Any[ - Dates.Month(2), Dates.Day(15), Dates.Year(1996), Dates.Hour(24), Dates.Minute(0) - ] - @test Dates.parse_components(str, df) == parsed - @test_throws ArgumentError Dates.parse(DateTime, str, df) -end - -# DateFormat printing - -@test sprint(show, DateFormat("yyyzzxmmdd\\MHH:MM:SS\\P")) == "dateformat\"yyyzzxmmdd\\MHH:MM:SSP\"" -@test sprint(show, DateFormat("yyy").tokens[1]) == "DatePart(yyy)" -@test sprint(show, DateFormat("mmzzdd").tokens[2]) == "Delim(zz)" -@test sprint(show, DateFormat("ddxmm").tokens[2]) == "Delim(x)" -@test sprint(show, DateFormat("xxmmxx").tokens[2]) == "DatePart(mm)" - -# Common Parsing Patterns -#'1996-January-15' -dt = Dates.DateTime(1996, 1, 15) -f = "yy-mm-dd" -a = "96-01-15" -@test DateTime(a, f) + Dates.Year(1900) == dt -@test Dates.format(dt, f) == a -a1 = "96-1-15" -@test Dates.DateTime(a1, f) + Dates.Year(1900) == dt -@test Dates.format(dt, "yy-m-dd") == a1 -a2 = "96-1-1" -@test Dates.DateTime(a2, f) + Dates.Year(1900) + Dates.Day(14) == dt -@test Dates.format(dt - Dates.Day(14), "yy-m-d") == a2 -a3 = "1996-1-15" -@test Dates.DateTime(a3, f) == dt -@test Dates.format(dt, "yyyy-m-d") == a3 -a4 = "1996-Jan-15" -@test_throws ArgumentError Dates.DateTime(a4, f) # Trying to use month name, but specified only "mm" - -f = "yy/uuu/dd" -b = "96/Feb/15" -@test Dates.DateTime(b, f) + Dates.Year(1900) == dt + Dates.Month(1) -@test Dates.format(dt + Dates.Month(1), f) == b -b1 = "1996/Feb/15" -@test Dates.DateTime(b1, f) == dt + Dates.Month(1) -@test Dates.format(dt + Dates.Month(1), "yyyy/uuu/dd") == b1 -b2 = "96/Feb/1" -@test Dates.DateTime(b2, f) + Dates.Year(1900) + Dates.Day(14) == dt + Dates.Month(1) -@test Dates.format(dt + Dates.Month(1) - Dates.Day(14), "yy/uuu/d") == b2 -# Here we've specifed a text month name, but given a number -b3 = "96/2/15" -@test_throws ArgumentError Dates.DateTime(b3, f) -try - Dates.parse(DateTime, "2012/2/20T9:9:31.25i90", dateformat"yyyy/mm/ddTHH:MM:SS.s") - @test false -catch err - @test isa(err, ArgumentError) - @test err.msg == "Found extra characters at the end of date time string" -end -try - Dates.parse(DateTime, "2012/2/20T9:9:3i90", dateformat"yyyy/mm/ddTHH:MM:SS.s") - @test false -catch err - @test isa(err, ArgumentError) - @test err.msg == "Unable to parse date time. Expected directive Delim(.) at char 16" -end - -f = "yy:dd:mm" -c = "96:15:01" -@test Dates.DateTime(c, f) + Dates.Year(1900) == dt -@test Dates.format(dt, f) == c -c1 = "1996:15:01" -@test Dates.DateTime(c1, f) == dt -@test Dates.format(dt, "yyyy:dd:mm") == c1 -c2 = "96:15:1" -@test Dates.DateTime(c2, f) + Dates.Year(1900) == dt -@test Dates.format(dt, "yy:dd:m") == c2 -c3 = "96:1:01" -@test Dates.DateTime(c3, f) + Dates.Year(1900) + Dates.Day(14) == dt -@test Dates.format(dt - Dates.Day(14), "yy:m:dd") == c3 -c4 = "1996:15:01 # random comment" -@test_throws ArgumentError Dates.DateTime(c4, f) - -f = "yyyy, uuu, dd" -d = "1996, Jan, 15" -@test Dates.DateTime(d, f) == dt -@test Dates.format(dt, f) == d -d1 = "96, Jan, 15" -@test Dates.DateTime(d1, f) + Dates.Year(1900) == dt -@test Dates.format(dt, "yy, uuu, dd") == d1 -d2 = "1996, Jan, 1" -@test Dates.DateTime(d2, f) + Dates.Day(14) == dt -@test Dates.format(dt - Dates.Day(14), "yyyy, uuu, d") == d2 -d3 = "1996, 2, 15" -@test_throws ArgumentError Dates.DateTime(d3, f) - -f = "yyyy.U.dd" -e = "1996.January.15" -@test Dates.DateTime(e, f) == dt -@test Dates.format(dt, f) == e -e1 = "96.January.15" -@test Dates.DateTime(e1, f) + Dates.Year(1900) == dt -@test Dates.format(dt, "yy.U.dd") == e1 - -fo = "yyyy m dd" -f = "1996 1 15" -@test Dates.DateTime(f, fo) == dt -@test Dates.format(dt, fo) == f -f1 = "1996 01 15" -@test Dates.DateTime(f1, fo) == dt -@test Dates.format(dt, "yyyy mm dd") == f1 -f2 = "1996 1 1" -@test Dates.DateTime(f2, fo) + Dates.Day(14) == dt -@test Dates.format(dt - Dates.Day(14), "yyyy m d") == f2 - -j = "1996-01-15" -f = "yyyy-mm-dd zzz" -@test Dates.DateTime(j, f) == dt -@test Dates.format(dt, f) == j * " zzz" -k = "1996-01-15 10:00:00" -f = "yyyy-mm-dd HH:MM:SS zzz" -@test Dates.DateTime(k, f) == dt + Dates.Hour(10) -@test Dates.format(dt + Dates.Hour(10), f) == k * " zzz" -l = "1996-01-15 10:10:10.25" -f = "yyyy-mm-dd HH:MM:SS.ss zzz" -@test Dates.DateTime(l, f) == dt + Dates.Hour(10) + Dates.Minute(10) + Dates.Second(10) + Dates.Millisecond(250) -@test Dates.format(dt + Dates.Hour(10) + Dates.Minute(10) + Dates.Second(10) + Dates.Millisecond(250), f) == l * " zzz" - -r = "1/15/1996" # Excel -f = "m/dd/yyyy" -@test Dates.DateTime(r, f) == dt -@test Dates.format(dt, f) == r -s = "19960115" -f = "yyyymmdd" -@test Dates.DateTime(s, f) == dt -@test Dates.format(dt, f) == s -v = "1996-01-15 10:00:00" -f = "yyyy-mm-dd HH:MM:SS" -@test Dates.DateTime(v, f) == dt + Dates.Hour(10) -@test Dates.format(dt + Dates.Hour(10), f) == v -w = "1996-01-15T10:00:00" -f = "yyyy-mm-ddTHH:MM:SS zzz" -@test Dates.DateTime(w, f) == dt + Dates.Hour(10) -@test Dates.format(dt + Dates.Hour(10), f) == w * " zzz" - -f = "yyyy/m" -y = "1996/1" -@test Dates.DateTime(y, f) == dt - Dates.Day(14) -@test Dates.format(dt, f) == y -y1 = "1996/1/15" -@test_throws ArgumentError Dates.DateTime(y1, f) -y2 = "96/1" -@test Dates.DateTime(y2, f) + Dates.Year(1900) == dt - Dates.Day(14) -@test Dates.format(dt, "yy/m") == y2 - -f = "yyyy" -z = "1996" -@test Dates.DateTime(z, f) == dt - Dates.Day(14) -@test Dates.format(dt, f) == z -z1 = "1996-3" -@test_throws ArgumentError Dates.DateTime(z1, f) -z2 = "1996-3-1" -@test_throws ArgumentError Dates.DateTime(z2, f) - -aa = "1/5/1996" -f = "m/d/yyyy" -@test Dates.DateTime(aa, f) == dt - Dates.Day(10) -@test Dates.format(dt - Dates.Day(10), f) == aa -bb = "5/1/1996" -f = "d/m/yyyy" -@test Dates.DateTime(bb, f) == dt - Dates.Day(10) -@test Dates.format(dt - Dates.Day(10), f) == bb -cc = "01151996" -f = "mmddyyyy" -@test Dates.DateTime(cc, f) == dt -@test Dates.format(dt, f) == cc -dd = "15011996" -f = "ddmmyyyy" -@test Dates.DateTime(dd, f) == dt -@test Dates.format(dt, f) == dd -ee = "01199615" -f = "mmyyyydd" -@test Dates.DateTime(ee, f) == dt -@test Dates.format(dt, f) == ee -ff = "1996-15-Jan" -f = "yyyy-dd-uuu" -@test Dates.DateTime(ff, f) == dt -@test Dates.format(dt, f) == ff -gg = "Jan-1996-15" -f = "uuu-yyyy-dd" -@test Dates.DateTime(gg, f) == dt -@test Dates.format(dt, f) == gg -hh = "1996#1#15" -f = "yyyy#m#d" -@test Dates.DateTime(hh, f) == dt -@test Dates.format(dt, f) == hh - -# test prefix. -s = "/1996/1/15" -f = "/yyyy/m/d" -@test Dates.DateTime(s, f) == dt -@test Dates.format(dt, f) == s -@test_throws ArgumentError Dates.DateTime("1996/1/15", f) - -# from Jiahao -@test Dates.Date("2009年12月01日", "yyyy年mm月dd日") == Dates.Date(2009, 12, 1) -@test Dates.format(Dates.Date(2009, 12, 1), "yyyy年mm月dd日") == "2009年12月01日" -@test Dates.Date("2009-12-01", "yyyy-mm-dd") == Dates.Date(2009, 12, 1) - -# French: from Milan -f = "dd/mm/yyyy" -f2 = "dd/mm/yy" -@test Dates.Date("28/05/2014", f) == Dates.Date(2014, 5, 28) -@test Dates.Date("28/05/14", f2) + Dates.Year(2000) == Dates.Date(2014, 5, 28) - -# Customizing locale -Dates.LOCALES["french"] = Dates.DateLocale( - ["janvier", "février", "mars", "avril", "mai", "juin", - "juillet", "août", "septembre", "octobre", "novembre", "décembre"], - ["janv", "févr", "mars", "avril", "mai", "juin", - "juil", "août", "sept", "oct", "nov", "déc"], - ["lundi", "mardi", "mercredi", "jeudi", "vendredi", "samedi", "dimanche"], - [""], -) - -f = "dd uuuuu yyyy" -@test Dates.Date("28 mai 2014", f; locale="french") == Dates.Date(2014, 5, 28) -@test Dates.format(Dates.Date(2014, 5, 28), f; locale="french") == "28 mai 2014" -@test Dates.Date("28 févr 2014", f; locale="french") == Dates.Date(2014, 2, 28) -@test Dates.format(Dates.Date(2014, 2, 28), f; locale="french") == "28 févr 2014" -@test Dates.Date("28 août 2014", f; locale="french") == Dates.Date(2014, 8, 28) -@test Dates.format(Dates.Date(2014, 8, 28), f; locale="french") == "28 août 2014" -@test Dates.Date("28 avril 2014", f; locale="french") == Dates.Date(2014, 4, 28) -@test Dates.format(Dates.Date(2014, 4, 28), f; locale="french") == "28 avril 2014" - -f = "dd u yyyy" -@test Dates.Date("28 avril 2014", f; locale="french") == Dates.Date(2014, 4, 28) -f = "dduuuuyyyy" -# parses 3 and 4 character month names -@test Dates.Date("28mai2014", f; locale="french") == Dates.Date(2014, 5, 28) -@test Dates.Date("28août2014", f; locale="french") == Dates.Date(2014, 8, 28) -# doesn't parse month name greater than 4 chars -@test_throws ArgumentError Dates.Date("28avril2014", f; locale="french") - -# From Tony Fong -f = "dduuuyy" -@test Dates.Date("01Dec09", f) + Dates.Year(2000) == Dates.Date(2009, 12, 1) -@test Dates.format(Dates.Date(2009, 12, 1), f) == "01Dec09" -f = "dduuuyyyy" -@test Dates.Date("01Dec2009", f) == Dates.Date(2009, 12, 1) -@test Dates.format(Dates.Date(2009, 12, 1), f) == "01Dec2009" -f = "duy" -const globex = ["f", "g", "h", "j", "k", "m", "n", "q", "u", "v", "x", "z"] -locale = Dates.DateLocale(globex, map(uppercase, globex), globex[1:7], globex[1:7]) -@test Dates.Date("1F4", f; locale=locale) + Dates.Year(2010) == Dates.Date(2014, 1, 1) -@test Dates.format(Dates.Date(2014, 1, 1), f; locale=locale) == "1F4" - -# From Matt Bauman -f = "yyyy-mm-ddTHH:MM:SS" -@test Dates.DateTime("2014-05-28T16:46:04", f) == Dates.DateTime(2014, 5, 28, 16, 46, 04) - -# Try to break stuff - -# Specified mm/dd, but date string has day/mm -@test_throws ArgumentError Dates.DateTime("18/05/2009", "mm/dd/yyyy") -@test_throws ArgumentError Dates.DateTime("18/05/2009 16", "mm/dd/yyyy hh") -# Used "mm" for months AND minutes -@test_throws ArgumentError Dates.DateTime("18/05/2009 16:12", "mm/dd/yyyy hh:mm") -# Date string has different delimiters than format string -@test_throws ArgumentError Dates.DateTime("18:05:2009", "mm/dd/yyyy") - -f = "y m d" -@test Dates.Date("1 1 1", f) == Dates.Date(1) -@test Dates.Date("10000000000 1 1", f) == Dates.Date(10000000000) -@test_throws ArgumentError Dates.Date("1 13 1", f) -@test_throws ArgumentError Dates.Date("1 1 32", f) -@test_throws ArgumentError Dates.Date(" 1 1 32", f) -@test_throws ArgumentError Dates.Date("# 1 1 32", f) -@test Dates.Date("1", f) == Dates.Date(1) -@test Dates.Date("1 ", f) == Dates.Date(1) -@test Dates.Date("1 2", f) == Dates.Date(1, 2) -# can't find space delimiter (finds '/'), so fails -@test_throws ArgumentError Dates.Date("2000/1", f) - -f = "ymd" -@test Dates.Date("111", f) == Dates.Date(1) -@test Dates.Date("1", f) == Dates.Date(1) - -@test Dates.DateTime("20140529 120000", "yyyymmdd HHMMSS") == Dates.DateTime(2014, 5, 29, 12) - -@test Dates.Date(string(Dates.Date(dt))) == Dates.Date(dt) -@test Dates.DateTime(string(dt)) == dt - -# Vectorized -dr = ["2000-01-01", "2000-01-02", "2000-01-03", "2000-01-04", "2000-01-05", - "2000-01-06", "2000-01-07", "2000-01-08", "2000-01-09", "2000-01-10"] -dr2 = [Dates.Date(2000) : Dates.Date(2000, 1, 10);] -@test Dates.Date(dr) == dr2 -@test Dates.Date(dr, "yyyy-mm-dd") == dr2 -@test Dates.DateTime.(dr) == Dates.DateTime.(dr2) -@test Dates.DateTime(dr, "yyyy-mm-dd") == Dates.DateTime.(dr2) - -@test Dates.format(dr2) == dr -@test Dates.format(dr2, "yyyy-mm-dd") == dr - -@test typeof(Dates.Date(dr)) == Array{Date, 1} - -# Issue 13 -t = Dates.DateTime(1, 1, 1, 14, 51, 0, 118) -@test Dates.DateTime("[14:51:00.118]", "[HH:MM:SS.sss]") == t -@test Dates.DateTime("14:51:00.118", "HH:MM:SS.sss") == t -@test Dates.DateTime("[14:51:00.118?", "[HH:MM:SS.sss?") == t -@test Dates.DateTime("?14:51:00.118?", "?HH:MM:SS.sss?") == t -@test Dates.DateTime("x14:51:00.118", "xHH:MM:SS.sss") == t -@test Dates.DateTime("14:51:00.118]", "HH:MM:SS.sss]") == t - -# RFC1123Format -dt = Dates.DateTime(2014, 8, 23, 17, 22, 15) -@test Dates.format(dt, Dates.RFC1123Format) == "Sat, 23 Aug 2014 17:22:15" -@test Dates.DateTime(Dates.format(dt, Dates.RFC1123Format), Dates.RFC1123Format) == dt -@test Dates.format(dt, "yyyy-mm-ddTHH:MM:SS E") == "2014-08-23T17:22:15 Saturday" -@test Dates.format(dt, "yyyy-mm-ddTHH:MM:SS e") == "2014-08-23T17:22:15 Sat" -@test Dates.format(dt, "yyyy-mm-dd E") == "2014-08-23 Saturday" -@test Dates.format(dt, "yyyy-mm-dd e") == "2014-08-23 Sat" -@test Dates.format(dt, "yyyy-e-mm-dd") == "2014-Sat-08-23" - -@test Dates.format(Dates.DateTime(2014, 1, 2, 0, 0, 0, 999), Dates.RFC1123Format) == "Thu, 02 Jan 2014 00:00:00" -@test Dates.format(Dates.DateTime(2014, 2, 18, 0, 0, 0, 9), Dates.RFC1123Format) == "Tue, 18 Feb 2014 00:00:00" -@test Dates.format(Dates.DateTime(2014, 3, 8, 0, 0, 0, 9), Dates.RFC1123Format) == "Sat, 08 Mar 2014 00:00:00" -@test Dates.format(Dates.DateTime(2014, 4, 28, 0, 0, 0, 9), Dates.RFC1123Format) == "Mon, 28 Apr 2014 00:00:00" -@test Dates.format(Dates.DateTime(2014, 5, 10, 0, 0, 0, 9), Dates.RFC1123Format) == "Sat, 10 May 2014 00:00:00" -@test Dates.format(Dates.DateTime(2014, 6, 4, 0, 0, 0, 9), Dates.RFC1123Format) == "Wed, 04 Jun 2014 00:00:00" -@test Dates.format(Dates.DateTime(2014, 7, 13, 0, 0, 0, 9), Dates.RFC1123Format) == "Sun, 13 Jul 2014 00:00:00" -@test Dates.format(Dates.DateTime(2014, 8, 17, 0, 0, 0, 9), Dates.RFC1123Format) == "Sun, 17 Aug 2014 00:00:00" -@test Dates.format(Dates.DateTime(2014, 9, 20, 0, 0, 0, 9), Dates.RFC1123Format) == "Sat, 20 Sep 2014 00:00:00" -@test Dates.format(Dates.DateTime(2014, 10, 31, 0, 0, 0, 9), Dates.RFC1123Format) == "Fri, 31 Oct 2014 00:00:00" -@test Dates.format(Dates.DateTime(2014, 11, 2, 0, 0, 0, 9), Dates.RFC1123Format) == "Sun, 02 Nov 2014 00:00:00" -@test Dates.format(Dates.DateTime(2014, 12, 5, 0, 0, 0, 9), Dates.RFC1123Format) == "Fri, 05 Dec 2014 00:00:00" - -dt = Dates.DateTime(2016, 11, 12, 7, 45, 36) -@test parse(Dates.DateTime, "Sat, 12 Nov 2016 07:45:36", Dates.RFC1123Format) == dt -@test parse(Dates.DateTime, "Mon, 12 Nov 2016 07:45:36", Dates.RFC1123Format) == dt # Wrong day of week -@test_throws ArgumentError parse(Date, "Foo, 12 Nov 2016 07:45:36", Dates.RFC1123Format) - -# Issue 15195 -let f = "YY" - @test Dates.format(Dates.Date(1999), f) == "1999" - @test Dates.format(Dates.Date(9), f) == "09" - @test Dates.format(typemax(Dates.Date), f) == "252522163911149" -end - -# Issue: https://github.com/quinnj/TimeZones.jl/issues/19 -let - const Zulu = String - - function Dates.tryparsenext(d::Dates.DatePart{'Z'}, str, i, len) - Dates.tryparsenext_word(str, i, len, Dates.min_width(d), Dates.max_width(d)) - end - - str = "2015-07-24T05:38:19.591Z" - dt = Dates.DateTime(2015, 7, 24, 5, 38, 19, 591) - parsed = Any[ - Dates.Year(2015), Dates.Month(7), Dates.Day(24), - Dates.Hour(5), Dates.Minute(38), Dates.Second(19), Dates.Millisecond(591) - ] - - format = "yyyy-mm-ddTHH:MM:SS.sssZ" - escaped_format = "yyyy-mm-dd\\THH:MM:SS.sss\\Z" - - # Typically 'Z' isn't treated as a specifier so it doesn't have to be escaped - @test Dates.parse_components(str, Dates.DateFormat(format)) == parsed - @test Dates.parse_components(str, Dates.DateFormat(escaped_format)) == parsed - - try - # Make 'Z' into a specifier - Dates.CONVERSION_SPECIFIERS['Z'] = Zulu - Dates.CONVERSION_DEFAULTS[Zulu] = "" - - @test Dates.parse_components(str, Dates.DateFormat(format)) == [parsed; Zulu("Z")] - @test Dates.parse_components(str, Dates.DateFormat(escaped_format)) == parsed - finally - delete!(Dates.CONVERSION_SPECIFIERS, 'Z') - delete!(Dates.CONVERSION_DEFAULTS, Zulu) - end - - # Ensure that the default behaviour has been restored - @test Dates.parse_components(str, Dates.DateFormat(format)) == parsed - @test Dates.parse_components(str, Dates.DateFormat(escaped_format)) == parsed -end - -# Issue 10817 -@test Dates.Date("Apr 01 2014", "uuu dd yyyy") == Dates.Date(2014, 4, 1) -@test_throws ArgumentError Dates.Date("Apr 01 xx 2014", "uuu dd zz yyyy") -@test_throws ArgumentError Dates.Date("Apr 01 xx 2014", "uuu dd yyyy") - -# Issue 21001 -for (ms, str) in zip([0, 1, 20, 300, 450, 678], ["0", "001", "02", "3", "45", "678"]) - dt = DateTime(2000, 1, 1, 0, 0, 0, ms) - @test Dates.format(dt, "s") == str - @test Dates.format(dt, "ss") == rpad(str, 2, '0') - @test Dates.format(dt, "sss") == rpad(str, 3, '0') - @test Dates.format(dt, "ssss") == rpad(str, 4, '0') -end - -# Issue #21504 -@test isnull(tryparse(Dates.Date, "0-1000")) - -# Issue #22100 -@testset "parse milliseconds" begin - @test Dates.DateTime("2017-Mar-17 00:00:00.0000", "y-u-d H:M:S.s") == Dates.DateTime(2017, 3, 17) - @test Dates.parse_components(".1", Dates.DateFormat(".s")) == [Dates.Millisecond(100)] - @test Dates.parse_components(".12", Dates.DateFormat(".s")) == [Dates.Millisecond(120)] - @test Dates.parse_components(".123", Dates.DateFormat(".s")) == [Dates.Millisecond(123)] - @test Dates.parse_components(".1230", Dates.DateFormat(".s")) == [Dates.Millisecond(123)] - @test_throws InexactError Dates.parse_components(".1234", Dates.DateFormat(".s")) - - # Ensure that no overflow occurs when using Int32 literals: Int32(10)^10 - @test Dates.parse_components("." * rpad(999, 10, '0'), Dates.DateFormat(".s")) == [Dates.Millisecond(999)] -end diff --git a/julia-0.6.3/share/julia/test/dates/periods.jl b/julia-0.6.3/share/julia/test/dates/periods.jl deleted file mode 100644 index 72ce644..0000000 --- a/julia-0.6.3/share/julia/test/dates/periods.jl +++ /dev/null @@ -1,396 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -# Period testing -@test -Dates.Year(1) == Dates.Year(-1) -@test Dates.Year(1) > Dates.Year(0) -@test (Dates.Year(1) < Dates.Year(0)) == false -@test Dates.Year(1) == Dates.Year(1) -@test Dates.Year(1) != 1 -@test Dates.Year(1) + Dates.Year(1) == Dates.Year(2) -@test Dates.Year(1) - Dates.Year(1) == zero(Dates.Year) -@test_throws MethodError Dates.Year(1) * Dates.Year(1) == Dates.Year(1) -@test Dates.Year(10) % Dates.Year(4) == Dates.Year(2) -@test gcd(Dates.Year(10), Dates.Year(4)) == Dates.Year(2) -@test lcm(Dates.Year(10), Dates.Year(4)) == Dates.Year(20) -@test div(Dates.Year(10), Dates.Year(3)) == 3 -@test div(Dates.Year(10), Dates.Year(4)) == 2 -@test div(Dates.Year(10), 4) == Dates.Year(2) -@test Dates.Year(10) / Dates.Year(4) == 2.5 - -@test mod(Dates.Year(10), Dates.Year(4)) == Dates.Year(2) -@test mod(Dates.Year(-10), Dates.Year(4)) == Dates.Year(2) -@test mod(Dates.Year(10), 4) == Dates.Year(2) -@test mod(Dates.Year(-10), 4) == Dates.Year(2) - -@test rem(Dates.Year(10), Dates.Year(4)) == Dates.Year(2) -@test rem(Dates.Year(-10), Dates.Year(4)) == Dates.Year(-2) -@test rem(Dates.Year(10), 4) == Dates.Year(2) -@test rem(Dates.Year(-10), 4) == Dates.Year(-2) - -t = Dates.Year(1) -t2 = Dates.Year(2) -@test ([t, t, t, t, t] + Dates.Year(1)) == ([t2, t2, t2, t2, t2]) -@test (Dates.Year(1) + [t, t, t, t, t]) == ([t2, t2, t2, t2, t2]) -@test ([t2, t2, t2, t2, t2] - Dates.Year(1)) == ([t, t, t, t, t]) -@test_throws MethodError ([t, t, t, t, t] .* Dates.Year(1)) == ([t, t, t, t, t]) -@test ([t, t, t, t, t] * 1) == ([t, t, t, t, t]) -@test ([t, t, t, t, t] .% t2) == ([t, t, t, t, t]) -@test div.([t, t, t, t, t], Dates.Year(1)) == ([1, 1, 1, 1, 1]) -@test mod.([t, t, t, t, t], Dates.Year(2)) == ([t, t, t, t, t]) -@test [t, t, t] / t2 == [0.5, 0.5, 0.5] -@test abs(-t) == t - -#Period arithmetic -y = Dates.Year(1) -m = Dates.Month(1) -w = Dates.Week(1) -d = Dates.Day(1) -h = Dates.Hour(1) -mi = Dates.Minute(1) -s = Dates.Second(1) -ms = Dates.Millisecond(1) -us = Dates.Microsecond(1) -ns = Dates.Nanosecond(1) -@test Dates.Year(y) == y -@test Dates.Month(m) == m -@test Dates.Week(w) == w -@test Dates.Day(d) == d -@test Dates.Hour(h) == h -@test Dates.Minute(mi) == mi -@test Dates.Second(s) == s -@test Dates.Millisecond(ms) == ms -@test Dates.Microsecond(us) == us -@test Dates.Nanosecond(ns) == ns -@test Dates.Year(convert(Int8, 1)) == y -@test Dates.Year(convert(UInt8, 1)) == y -@test Dates.Year(convert(Int16, 1)) == y -@test Dates.Year(convert(UInt16, 1)) == y -@test Dates.Year(convert(Int32, 1)) == y -@test Dates.Year(convert(UInt32, 1)) == y -@test Dates.Year(convert(Int64, 1)) == y -@test Dates.Year(convert(UInt64, 1)) == y -@test Dates.Year(convert(Int128, 1)) == y -@test Dates.Year(convert(UInt128, 1)) == y -@test Dates.Year(convert(BigInt, 1)) == y -@test Dates.Year(convert(BigFloat, 1)) == y -@test Dates.Year(convert(Complex, 1)) == y -@test Dates.Year(convert(Rational, 1)) == y -@test Dates.Year(convert(Float16, 1)) == y -@test Dates.Year(convert(Float32, 1)) == y -@test Dates.Year(convert(Float64, 1)) == y -@test y == y -@test m == m -@test w == w -@test d == d -@test h == h -@test mi == mi -@test s == s -@test ms == ms -@test us == us -@test ns == ns -y2 = Dates.Year(2) -@test y < y2 -@test y2 > y -@test y != y2 - -@test Dates.Year(Int8(1)) == y -@test Dates.Year(UInt8(1)) == y -@test Dates.Year(Int16(1)) == y -@test Dates.Year(UInt16(1)) == y -@test Dates.Year(Int(1)) == y -@test Dates.Year(UInt(1)) == y -@test Dates.Year(Int64(1)) == y -@test Dates.Year(UInt64(1)) == y -@test Dates.Year(UInt128(1)) == y -@test Dates.Year(UInt128(1)) == y -@test Dates.Year(big(1)) == y -@test Dates.Year(BigFloat(1)) == y -@test Dates.Year(float(1)) == y -@test Dates.Year(Float32(1)) == y -@test Dates.Year(Rational(1)) == y -@test Dates.Year(complex(1)) == y -@test_throws InexactError Dates.Year(BigFloat(1.2)) == y -@test_throws InexactError Dates.Year(1.2) == y -@test_throws InexactError Dates.Year(Float32(1.2)) == y -@test_throws InexactError Dates.Year(3//4) == y -@test_throws InexactError Dates.Year(complex(1.2)) == y -@test_throws InexactError Dates.Year(Float16(1.2)) == y -@test Dates.Year(true) == y -@test Dates.Year(false) != y -@test_throws MethodError Dates.Year(:hey) == y -@test Dates.Year(real(1)) == y -@test_throws InexactError Dates.Year(m) == y -@test_throws MethodError Dates.Year(w) == y -@test_throws MethodError Dates.Year(d) == y -@test_throws MethodError Dates.Year(h) == y -@test_throws MethodError Dates.Year(mi) == y -@test_throws MethodError Dates.Year(s) == y -@test_throws MethodError Dates.Year(ms) == y -@test Dates.Year(Dates.Date(2013, 1, 1)) == Dates.Year(2013) -@test Dates.Year(Dates.DateTime(2013, 1, 1)) == Dates.Year(2013) -@test typeof(y + m) <: Dates.CompoundPeriod -@test typeof(m + y) <: Dates.CompoundPeriod -@test typeof(y + w) <: Dates.CompoundPeriod -@test typeof(y + d) <: Dates.CompoundPeriod -@test typeof(y + h) <: Dates.CompoundPeriod -@test typeof(y + mi) <: Dates.CompoundPeriod -@test typeof(y + s) <: Dates.CompoundPeriod -@test typeof(y + ms) <: Dates.CompoundPeriod -@test typeof(y + us) <: Dates.CompoundPeriod -@test typeof(y + ns) <: Dates.CompoundPeriod -@test y > m -@test d < w -@test mi < h -@test ms < h -@test ms < mi -@test us < ms -@test ns < ms -@test ns < us -@test ns < w -@test us < w -@test typemax(Dates.Year) == Dates.Year(typemax(Int64)) -@test typemax(Dates.Year) + y == Dates.Year(-9223372036854775808) -@test typemin(Dates.Year) == Dates.Year(-9223372036854775808) - -#Period-Real arithmetic -@test_throws MethodError y + 1 == Dates.Year(2) -@test_throws MethodError y + true == Dates.Year(2) -@test_throws InexactError y + Dates.Year(1.2) -@test y + Dates.Year(1f0) == Dates.Year(2) -@test y * 4 == Dates.Year(4) -@test y * 4f0 == Dates.Year(4) -@test_throws InexactError y * 3//4 == Dates.Year(1) -@test div(y, 2) == Dates.Year(0) -@test_throws MethodError div(2, y) == Dates.Year(2) -@test div(y, y) == 1 -@test y*10 % Dates.Year(5) == Dates.Year(0) -@test_throws MethodError (y > 3) == false -@test_throws MethodError (4 < y) == false -@test 1 != y -t = [y, y, y, y, y] -@test t .+ Dates.Year(2) == [Dates.Year(3), Dates.Year(3), Dates.Year(3), Dates.Year(3), Dates.Year(3)] - -let x = Dates.Year(5), y = Dates.Year(2) - @test div(x, y) * y + rem(x, y) == x - @test fld(x, y) * y + mod(x, y) == x -end - -# Associativity -dt = Dates.DateTime(2012, 12, 21) -test = ((((((((dt + y) - m) + w) - d) + h) - mi) + s) - ms) -@test test == dt + y - m + w - d + h - mi + s - ms -@test test == y - m + w - d + dt + h - mi + s - ms -@test test == dt - m + y - d + w - mi + h - ms + s -@test test == dt + (y - m + w - d + h - mi + s - ms) -@test test == dt + y - m + w - d + (h - mi + s - ms) -@test (dt + Dates.Year(4)) + Dates.Day(1) == dt + (Dates.Year(4) + Dates.Day(1)) -@test Dates.Date(2014, 1, 29) + Dates.Month(1) + Dates.Day(1) + Dates.Month(1) + Dates.Day(1) == - Dates.Date(2014, 1, 29) + Dates.Day(1) + Dates.Month(1) + Dates.Month(1) + Dates.Day(1) -@test Dates.Date(2014, 1, 29) + Dates.Month(1) + Dates.Day(1) == Dates.Date(2014, 1, 29) + Dates.Day(1) + Dates.Month(1) -# traits -@test Dates._units(Dates.Year(0)) == " years" -@test Dates._units(Dates.Year(1)) == " year" -@test Dates._units(Dates.Year(-1)) == " year" -@test Dates._units(Dates.Year(2)) == " years" -@test Dates.string(Dates.Year(0)) == "0 years" -@test Dates.string(Dates.Year(1)) == "1 year" -@test Dates.string(Dates.Year(-1)) == "-1 year" -@test Dates.string(Dates.Year(2)) == "2 years" -@test zero(Dates.Year) == Dates.Year(0) -@test zero(Dates.Year(10)) == Dates.Year(0) -@test zero(Dates.Month) == Dates.Month(0) -@test zero(Dates.Month(10)) == Dates.Month(0) -@test zero(Dates.Day) == Dates.Day(0) -@test zero(Dates.Day(10)) == Dates.Day(0) -@test zero(Dates.Hour) == Dates.Hour(0) -@test zero(Dates.Hour(10)) == Dates.Hour(0) -@test zero(Dates.Minute) == Dates.Minute(0) -@test zero(Dates.Minute(10)) == Dates.Minute(0) -@test zero(Dates.Second) == Dates.Second(0) -@test zero(Dates.Second(10)) == Dates.Second(0) -@test zero(Dates.Millisecond) == Dates.Millisecond(0) -@test zero(Dates.Millisecond(10)) == Dates.Millisecond(0) -@test Dates.Year(-1) < Dates.Year(1) -@test !(Dates.Year(-1) > Dates.Year(1)) -@test Dates.Year(1) == Dates.Year(1) -@test Dates.Year(1) != 1 -@test 1 != Dates.Year(1) -@test Dates.Month(-1) < Dates.Month(1) -@test !(Dates.Month(-1) > Dates.Month(1)) -@test Dates.Month(1) == Dates.Month(1) -@test Dates.Day(-1) < Dates.Day(1) -@test !(Dates.Day(-1) > Dates.Day(1)) -@test Dates.Day(1) == Dates.Day(1) -@test Dates.Hour(-1) < Dates.Hour(1) -@test !(Dates.Hour(-1) > Dates.Hour(1)) -@test Dates.Hour(1) == Dates.Hour(1) -@test Dates.Minute(-1) < Dates.Minute(1) -@test !(Dates.Minute(-1) > Dates.Minute(1)) -@test Dates.Minute(1) == Dates.Minute(1) -@test Dates.Second(-1) < Dates.Second(1) -@test !(Dates.Second(-1) > Dates.Second(1)) -@test Dates.Second(1) == Dates.Second(1) -@test Dates.Millisecond(-1) < Dates.Millisecond(1) -@test !(Dates.Millisecond(-1) > Dates.Millisecond(1)) -@test Dates.Millisecond(1) == Dates.Millisecond(1) -@test_throws MethodError Dates.Year(1) < Dates.Millisecond(1) -@test_throws MethodError Dates.Millisecond(1) < Dates.Year(1) -@test_throws MethodError Dates.Year(1) == Dates.Millisecond(1) -@test_throws MethodError Dates.Millisecond(1) == Dates.Year(1) - -# Allow comparisons with new Period subtypes -let - # https://en.wikipedia.org/wiki/Swatch_Internet_Time - struct Beat <: Dates.Period - value::Int64 - end - - Dates.value(b::Beat) = b.value - Dates.toms(b::Beat) = Dates.value(b) * 86400 - Dates._units(b::Beat) = " beat" * (abs(Dates.value(b)) == 1 ? "" : "s") - Base.promote_rule(::Type{Dates.Day}, ::Type{Beat}) = Dates.Millisecond - Base.convert{T<:Dates.Millisecond}(::Type{T}, b::Beat) = T(Dates.toms(b)) - - @test Beat(1000) == Dates.Day(1) - @test Beat(1) < Dates.Day(1) -end - -@test Dates.Year("1") == y -@test Dates.Month("1") == m -@test Dates.Week("1") == w -@test Dates.Day("1") == d -@test Dates.Hour("1") == h -@test Dates.Minute("1") == mi -@test Dates.Second("1") == s -@test Dates.Millisecond("1") == ms -@test Dates.Microsecond("1") == us -@test Dates.Nanosecond("1") == ns -@test_throws ArgumentError Dates.Year("1.0") -@test Dates.Year(parse(Float64, "1.0")) == y - -dt = Dates.DateTime(2014) -@test typeof(Dates.Year(dt)) <: Dates.Year -@test typeof(Dates.Month(dt)) <: Dates.Month -@test typeof(Dates.Week(dt)) <: Dates.Week -@test typeof(Dates.Day(dt)) <: Dates.Day -@test typeof(Dates.Hour(dt)) <: Dates.Hour -@test typeof(Dates.Minute(dt)) <: Dates.Minute -@test typeof(Dates.Second(dt)) <: Dates.Second -@test typeof(Dates.Millisecond(dt)) <: Dates.Millisecond - -# Default values -@test Dates.default(Dates.Year) == y -@test Dates.default(Dates.Month) == m -@test Dates.default(Dates.Week) == w -@test Dates.default(Dates.Day) == d -@test Dates.default(Dates.Hour) == zero(Dates.Hour) -@test Dates.default(Dates.Minute) == zero(Dates.Minute) -@test Dates.default(Dates.Second) == zero(Dates.Second) -@test Dates.default(Dates.Millisecond) == zero(Dates.Millisecond) -@test Dates.default(Dates.Microsecond) == zero(Dates.Microsecond) -@test Dates.default(Dates.Nanosecond) == zero(Dates.Nanosecond) - -# Conversions -@test Dates.toms(ms) == Dates.value(Dates.Millisecond(ms)) == 1 -@test Dates.toms(s) == Dates.value(Dates.Millisecond(s)) == 1000 -@test Dates.toms(mi) == Dates.value(Dates.Millisecond(mi)) == 60000 -@test Dates.toms(h) == Dates.value(Dates.Millisecond(h)) == 3600000 -@test Dates.toms(d) == Dates.value(Dates.Millisecond(d)) == 86400000 -@test Dates.toms(w) == Dates.value(Dates.Millisecond(w)) == 604800000 - -@test Dates.days(ms) == Dates.days(s) == Dates.days(mi) == Dates.days(h) == 0 -@test Dates.days(Dates.Millisecond(86400000)) == 1 -@test Dates.days(Dates.Second(86400)) == 1 -@test Dates.days(Dates.Minute(1440)) == 1 -@test Dates.days(Dates.Hour(24)) == 1 -@test Dates.days(d) == 1 -@test Dates.days(w) == 7 - -# issue #9214 -@test 2s + (7ms + 1ms) == (2s + 7ms) + 1ms == 1ms + (2s + 7ms) == 1ms + (1s + 7ms) + 1s == 1ms + (2s + 3d + 7ms) + (-3d) == (1ms + (2s + 3d)) + (7ms - 3d) == (1ms + (2s + 3d)) - (3d - 7ms) -@test 1ms - (2s + 7ms) == -((2s + 7ms) - 1ms) == (-6ms) - 2s -emptyperiod = ((y + d) - d) - y -@test emptyperiod == ((d + y) - y) - d == ((d + y) - d) - y -@test emptyperiod == 2y + (m - d) + ms - ((m - d) + 2y + ms) -@test emptyperiod == 0ms -@test string(emptyperiod) == "empty period" -@test string(ms + mi + d + m + y + w + h + s + 2y + m) == "3 years, 2 months, 1 week, 1 day, 1 hour, 1 minute, 1 second, 1 millisecond" -@test 8d - s == 1w + 23h + 59mi + 59s -@test h + 3mi == 63mi -@test y - m == 11m - -# compound periods should avoid automatically converting period types -@test (d - h).periods == Dates.Period[d, -h] -@test d - h == 23h -@test !isequal(d - h, 23h) -@test isequal(d - h, 2d - 2h - 1d + 1h) - -# reduce compound periods into the most basic form -@test Dates.canonicalize(h - mi).periods == Dates.Period[59mi] -@test Dates.canonicalize(-h + mi).periods == Dates.Period[-59mi] -@test Dates.canonicalize(-y + d).periods == Dates.Period[-y, d] -@test Dates.canonicalize(-y + m - w + d).periods == Dates.Period[-11m, -6d] -@test Dates.canonicalize(-y + m - w + ms).periods == Dates.Period[-11m, -6d, -23h, -59mi, -59s, -999ms] -@test Dates.canonicalize(y - m + w - d + h - mi + s - ms).periods == Dates.Period[11m, 6d, 59mi, 999ms] -@test Dates.canonicalize(-y + m - w + d - h + mi - s + ms).periods == Dates.Period[-11m, -6d, -59mi, -999ms] - -@test Dates.Date(2009, 2, 1) - (Dates.Month(1) + Dates.Day(1)) == Dates.Date(2008, 12, 31) -@test_throws MethodError (Dates.Month(1) + Dates.Day(1)) - Dates.Date(2009,2,1) - -pa = [1y 1m 1w 1d; 1h 1mi 1s 1ms] -cpa = [1y + 1s 1m + 1s 1w + 1s 1d + 1s; 1h + 1s 1mi + 1s 2m + 1s 1s + 1ms] - -@test +pa == pa == -(-pa) -@test -pa == map(-, pa) -@test 1y .+ pa == [2y 1y + 1m 1y + 1w 1y + 1d; 1y + 1h 1y + 1mi 1y + 1s 1y + 1ms] -@test (1y + 1m) .+ pa == [2y + 1m 1y + 2m 1y + 1m + 1w 1y + 1m + 1d; 1y + 1m + 1h 1y + 1m + 1mi 1y + 1m + 1s 1y + 1m + 1ms] -@test pa .+ 1y == [2y 1y + 1m 1y + 1w 1y + 1d; 1y + 1h 1y + 1mi 1y + 1s 1y + 1ms] -@test pa .+ (1y + 1m) == [2y + 1m 1y + 2m 1y + 1m + 1w 1y + 1m + 1d; 1y + 1m + 1h 1y + 1m + 1mi 1y + 1m + 1s 1y + 1m + 1ms] - -@test 1y .+ cpa == [2y + 1s 1y + 1m + 1s 1y + 1w + 1s 1y + 1d + 1s; 1y + 1h + 1s 1y + 1mi + 1s 1y + 2m + 1s 1y + 1ms + 1s] -@test (1y + 1m) .+ cpa == [2y + 1m + 1s 1y + 2m + 1s 1y + 1m + 1w + 1s 1y + 1m + 1d + 1s; 1y + 1m + 1h + 1s 1y + 1m + 1mi + 1s 1y + 3m + 1s 1y + 1m + 1s + 1ms] -@test cpa .+ 1y == [2y + 1s 1y + 1m + 1s 1y + 1w + 1s 1y + 1d + 1s; 1y + 1h + 1s 1y + 1mi + 1s 1y + 2m + 1s 1y + 1ms + 1s] -@test cpa .+ (1y + 1m) == [2y + 1m + 1s 1y + 2m + 1s 1y + 1m + 1w + 1s 1y + 1m + 1d + 1s; 1y + 1m + 1h + 1s 1y + 1m + 1mi + 1s 1y + 3m + 1s 1y + 1m + 1s + 1ms] - -@test 1y + pa == [2y 1y + 1m 1y + 1w 1y + 1d; 1y + 1h 1y + 1mi 1y + 1s 1y + 1ms] -@test (1y + 1m) + pa == [2y + 1m 1y + 2m 1y + 1m + 1w 1y + 1m + 1d; 1y + 1m + 1h 1y + 1m + 1mi 1y + 1m + 1s 1y + 1m + 1ms] -@test pa + 1y == [2y 1y + 1m 1y + 1w 1y + 1d; 1y + 1h 1y + 1mi 1y + 1s 1y + 1ms] -@test pa + (1y + 1m) == [2y + 1m 1y + 2m 1y + 1m + 1w 1y + 1m + 1d; 1y + 1m + 1h 1y + 1m + 1mi 1y + 1m + 1s 1y + 1m + 1ms] - -@test 1y + cpa == [2y + 1s 1y + 1m + 1s 1y + 1w + 1s 1y + 1d + 1s; 1y + 1h + 1s 1y + 1mi + 1s 1y + 2m + 1s 1y + 1ms + 1s] -@test (1y + 1m) + cpa == [2y + 1m + 1s 1y + 2m + 1s 1y + 1m + 1w + 1s 1y + 1m + 1d + 1s; 1y + 1m + 1h + 1s 1y + 1m + 1mi + 1s 1y + 3m + 1s 1y + 1m + 1s + 1ms] -@test cpa + 1y == [2y + 1s 1y + 1m + 1s 1y + 1w + 1s 1y + 1d + 1s; 1y + 1h + 1s 1y + 1mi + 1s 1y + 2m + 1s 1y + 1ms + 1s] -@test cpa + (1y + 1m) == [2y + 1m + 1s 1y + 2m + 1s 1y + 1m + 1w + 1s 1y + 1m + 1d + 1s; 1y + 1m + 1h + 1s 1y + 1m + 1mi + 1s 1y + 3m + 1s 1y + 1m + 1s + 1ms] - -@test 1y .- pa == [0y 1y-1m 1y-1w 1y-1d; 1y-1h 1y-1mi 1y-1s 1y-1ms] -@test (1y + 1m) .- pa == [1m 1y 1y + 1m-1w 1y + 1m-1d; 1y + 1m-1h 1y + 1m-1mi 1y + 1m-1s 1y + 1m-1ms] -@test pa .- (1y + 1m) == [-1m -1y -1y-1m + 1w -1y-1m + 1d; -1y-1m + 1h -1y-1m + 1mi -1y-1m + 1s -1y-1m + 1ms] -@test pa .- 1y == [0y 1m-1y -1y + 1w -1y + 1d; -1y + 1h -1y + 1mi -1y + 1s -1y + 1ms] - -@test 1y .- cpa == [-1s 1y-1m-1s 1y-1w-1s 1y-1d-1s; 1y-1h-1s 1y-1mi-1s 1y-2m-1s 1y-1ms-1s] -@test (1y + 1m) .- cpa == [1m-1s 1y-1s 1y + 1m-1w-1s 1y + 1m-1d-1s; 1y + 1m-1h-1s 1y + 1m-1mi-1s 1y-1m-1s 1y + 1m-1s-1ms] -@test cpa .- 1y == [1s -1y + 1m + 1s -1y + 1w + 1s -1y + 1d + 1s; -1y + 1h + 1s -1y + 1mi + 1s -1y + 2m + 1s -1y + 1ms + 1s] -@test cpa .- (1y + 1m) == [-1m + 1s -1y + 1s -1y-1m + 1w + 1s -1y-1m + 1d + 1s; -1y-1m + 1h + 1s -1y-1m + 1mi + 1s -1y + 1m + 1s -1y + -1m + 1s + 1ms] - -@test 1y - pa == [0y 1y-1m 1y-1w 1y-1d; 1y-1h 1y-1mi 1y-1s 1y-1ms] -@test (1y + 1m) - pa == [1m 1y 1y + 1m-1w 1y + 1m-1d; 1y + 1m-1h 1y + 1m-1mi 1y + 1m-1s 1y + 1m-1ms] -@test pa - (1y + 1m) == [-1m -1y -1y-1m + 1w -1y-1m + 1d; -1y-1m + 1h -1y-1m + 1mi -1y-1m + 1s -1y-1m + 1ms] -@test pa - 1y == [0y 1m-1y -1y + 1w -1y + 1d; -1y + 1h -1y + 1mi -1y + 1s -1y + 1ms] - -@test 1y - cpa == [-1s 1y-1m-1s 1y-1w-1s 1y-1d-1s; 1y-1h-1s 1y-1mi-1s 1y-2m-1s 1y-1ms-1s] -@test (1y + 1m) - cpa == [1m-1s 1y-1s 1y + 1m-1w-1s 1y + 1m-1d-1s; 1y + 1m-1h-1s 1y + 1m-1mi-1s 1y-1m-1s 1y + 1m-1s-1ms] -@test cpa - 1y == [1s -1y + 1m + 1s -1y + 1w + 1s -1y + 1d + 1s; -1y + 1h + 1s -1y + 1mi + 1s -1y + 2m + 1s -1y + 1ms + 1s] -@test cpa - (1y + 1m) == [-1m + 1s -1y + 1s -1y-1m + 1w + 1s -1y-1m + 1d + 1s; -1y-1m + 1h + 1s -1y-1m + 1mi + 1s -1y + 1m + 1s -1y + -1m + 1s + 1ms] - -@test [1y 1m; 1w 1d] + [1h 1mi; 1s 1ms] == [1y + 1h 1m + 1mi; 1w + 1s 1d + 1ms] -@test [1y 1m; 1w 1d] - [1h 1mi; 1s 1ms] == [1y-1h 1m-1mi; 1w-1s 1d-1ms] -@test [1y 1m; 1w 1d] - [1h 1mi; 1s 1ms] - [1y-1h 1m-1mi; 1w-1s 1d-1ms] == [emptyperiod emptyperiod; emptyperiod emptyperiod] - -@test [1y + 1s 1m + 1s; 1w + 1s 1d + 1s] + [1h 1mi; 1s 1ms] == [1y + 1h + 1s 1m + 1mi + 1s; 1w + 2s 1d + 1s + 1ms] -@test [1y + 1s 1m + 1s; 1w + 1s 1d + 1s] - [1h 1mi; 1s 1ms] == [1y-1h + 1s 1m-1mi + 1s; 1w 1d + 1s-1ms] - -@test [1y 1m; 1w 1d] + [1h + 1s 1mi + 1s; 1m + 1s 1s + 1ms] == [1y + 1h + 1s 1m + 1mi + 1s; 1w + 1m + 1s 1d + 1s + 1ms] -@test [1y 1m; 1w 1d] - [1h + 1s 1mi + 1s; 1m + 1s 1s + 1ms] == [1y-1h-1s 1m-1mi-1s; 1w-1m-1s 1d-1s-1ms] - -@test [1y + 1s 1m + 1s; 1w + 1s 1d + 1s] + [1y + 1h 1y + 1mi; 1y + 1s 1y + 1ms] == [2y + 1h + 1s 1y + 1m + 1mi + 1s; 1y + 1w + 2s 1y + 1d + 1s + 1ms] -@test [1y + 1s 1m + 1s; 1w + 1s 1d + 1s] - [1y + 1h 1y + 1mi; 1y + 1s 1y + 1ms] == [1s-1h 1m + 1s-1y-1mi; 1w-1y 1d + 1s-1y-1ms] diff --git a/julia-0.6.3/share/julia/test/dates/query.jl b/julia-0.6.3/share/julia/test/dates/query.jl deleted file mode 100644 index 7931612..0000000 --- a/julia-0.6.3/share/julia/test/dates/query.jl +++ /dev/null @@ -1,202 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -# Name functions -Jan = Dates.DateTime(2013, 1, 1) # Tuesday -Feb = Dates.DateTime(2013, 2, 2) # Saturday -Mar = Dates.DateTime(2013, 3, 3) # Sunday -Apr = Dates.DateTime(2013, 4, 4) # Thursday -May = Dates.DateTime(2013, 5, 5) # Sunday -Jun = Dates.DateTime(2013, 6, 7) # Friday -Jul = Dates.DateTime(2013, 7, 7) # Sunday -Aug = Dates.DateTime(2013, 8, 8) # Thursday -Sep = Dates.DateTime(2013, 9, 9) # Monday -Oct = Dates.DateTime(2013, 10, 10) # Thursday -Nov = Dates.DateTime(2013, 11, 11) # Monday -Dec = Dates.DateTime(2013, 12, 11) # Wednesday -monthnames = ["January", "February", "March", "April", - "May", "June", "July", "August", "September", - "October", "November", "December"] -daysofweek = [Dates.Tue, Dates.Sat, Dates.Sun, Dates.Thu, Dates.Sun, Dates.Fri, - Dates.Sun, Dates.Thu, Dates.Mon, Dates.Thu, Dates.Mon, Dates.Wed] -dows = ["Tuesday", "Saturday", "Sunday", "Thursday", "Sunday", "Friday", - "Sunday", "Thursday", "Monday", "Thursday", "Monday", "Wednesday"] -daysinmonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] -for (i, dt) in enumerate([Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec]) - @test Dates.month(dt) == i - @test Dates.monthname(dt) == monthnames[i] - @test Dates.monthname(i) == monthnames[i] - @test Dates.monthabbr(dt) == monthnames[i][1:3] - @test Dates.monthabbr(i) == monthnames[i][1:3] - @test Dates.dayofweek(dt) == daysofweek[i] - @test Dates.dayname(dt) == dows[i] - @test Dates.dayname(Dates.dayofweek(dt)) == dows[i] - @test Dates.dayabbr(dt) == dows[i][1:3] - @test Dates.dayabbr(Dates.dayofweek(dt)) == dows[i][1:3] - @test Dates.daysinmonth(dt) == daysinmonth[i] -end - -# Customizing locale -Dates.LOCALES["french"] = Dates.DateLocale( - ["janvier", "février", "mars", "avril", "mai", "juin", - "juillet", "août", "septembre", "octobre", "novembre", "décembre"], - ["janv", "févr", "mars", "avril", "mai", "juin", - "juil", "août", "sept", "oct", "nov", "déc"], - ["lundi", "mardi", "mercredi", "jeudi", "vendredi", "samedi", "dimanche"], - [""], -) -@test Dates.dayname(Nov; locale="french") == "lundi" -@test Dates.dayname(Jan; locale="french") == "mardi" -@test Dates.dayname(Dec; locale="french") == "mercredi" -@test Dates.dayname(Apr; locale="french") == "jeudi" -@test Dates.dayname(Jun; locale="french") == "vendredi" -@test Dates.dayname(Feb; locale="french") == "samedi" -@test Dates.dayname(May; locale="french") == "dimanche" - -@test Dates.monthname(Jan; locale="french") == "janvier" -@test Dates.monthname(Feb; locale="french") == "février" -@test Dates.monthname(Mar; locale="french") == "mars" -@test Dates.monthname(Apr; locale="french") == "avril" -@test Dates.monthname(May; locale="french") == "mai" -@test Dates.monthname(Jun; locale="french") == "juin" -@test Dates.monthname(Jul; locale="french") == "juillet" -@test Dates.monthname(Aug; locale="french") == "août" -@test Dates.monthname(Sep; locale="french") == "septembre" -@test Dates.monthname(Oct; locale="french") == "octobre" -@test Dates.monthname(Nov; locale="french") == "novembre" -@test Dates.monthname(Dec; locale="french") == "décembre" - -@test Dates.isleapyear(Dates.DateTime(1900)) == false -@test Dates.isleapyear(Dates.DateTime(2000)) == true -@test Dates.isleapyear(Dates.DateTime(2004)) == true -@test Dates.isleapyear(Dates.DateTime(2008)) == true -@test Dates.isleapyear(Dates.DateTime(0)) == true -@test Dates.isleapyear(Dates.DateTime(1)) == false -@test Dates.isleapyear(Dates.DateTime(-1)) == false -@test Dates.isleapyear(Dates.DateTime(4)) == true -@test Dates.isleapyear(Dates.DateTime(-4)) == true - -@test Dates.daysinyear(2000) == 366 -@test Dates.daysinyear(2001) == 365 -@test Dates.daysinyear(2000) == 366 -@test Dates.daysinyear(2001) == 365 - -@test Dates.daysinyear(Dates.Date(2000)) == 366 -@test Dates.daysinyear(Dates.Date(2001)) == 365 -@test Dates.daysinyear(Dates.DateTime(2000)) == 366 -@test Dates.daysinyear(Dates.DateTime(2001)) == 365 - -# Days of week from Monday = 1 to Sunday = 7 -@test Dates.dayofweek(Dates.DateTime(2013, 12, 22)) == 7 -@test Dates.dayofweek(Dates.DateTime(2013, 12, 23)) == 1 -@test Dates.dayofweek(Dates.DateTime(2013, 12, 24)) == 2 -@test Dates.dayofweek(Dates.DateTime(2013, 12, 25)) == 3 -@test Dates.dayofweek(Dates.DateTime(2013, 12, 26)) == 4 -@test Dates.dayofweek(Dates.DateTime(2013, 12, 27)) == 5 -@test Dates.dayofweek(Dates.DateTime(2013, 12, 28)) == 6 -@test Dates.dayofweek(Dates.DateTime(2013, 12, 29)) == 7 - -# There are 5 Sundays in December, 2013 -@test Dates.daysofweekinmonth(Dates.DateTime(2013, 12, 1)) == 5 -# There are 4 Sundays in November, 2013 -@test Dates.daysofweekinmonth(Dates.DateTime(2013, 11, 24)) == 4 - -@test Dates.dayofweekofmonth(Dates.DateTime(2013, 12, 1)) == 1 -@test Dates.dayofweekofmonth(Dates.DateTime(2013, 12, 8)) == 2 -@test Dates.dayofweekofmonth(Dates.DateTime(2013, 12, 15)) == 3 -@test Dates.dayofweekofmonth(Dates.DateTime(2013, 12, 22)) == 4 -@test Dates.dayofweekofmonth(Dates.DateTime(2013, 12, 29)) == 5 - -@test Dates.dayofyear(2000, 1, 1) == 1 -@test Dates.dayofyear(2004, 1, 1) == 1 -@test Dates.dayofyear(20013, 1, 1) == 1 -# Leap year -@test Dates.dayofyear(2000, 12, 31) == 366 -# Non-leap year -@test Dates.dayofyear(2001, 12, 31) == 365 - -@test Dates.dayofyear(Dates.DateTime(2000, 1, 1)) == 1 -@test Dates.dayofyear(Dates.DateTime(2004, 1, 1)) == 1 -@test Dates.dayofyear(Dates.DateTime(20013, 1, 1)) == 1 -# Leap year -@test Dates.dayofyear(Dates.DateTime(2000, 12, 31)) == 366 -# Non-leap year -@test Dates.dayofyear(Dates.DateTime(2001, 12, 31)) == 365 -# Test every day of a year -dt = Dates.DateTime(2000, 1, 1) -for i = 1:366 - @test Dates.dayofyear(dt) == i - dt += Dates.Day(1) -end -dt = Dates.DateTime(2001, 1, 1) -for i = 1:365 - @test Dates.dayofyear(dt) == i - dt += Dates.Day(1) -end - -@test Dates.quarterofyear(Dates.Date(2000, 1, 1)) == 1 -@test Dates.quarterofyear(Dates.Date(2000, 1, 31)) == 1 -@test Dates.quarterofyear(Dates.Date(2000, 2, 1)) == 1 -@test Dates.quarterofyear(Dates.Date(2000, 2, 29)) == 1 -@test Dates.quarterofyear(Dates.Date(2000, 3, 1)) == 1 -@test Dates.quarterofyear(Dates.Date(2000, 3, 31)) == 1 -@test Dates.quarterofyear(Dates.Date(2000, 4, 1)) == 2 -@test Dates.quarterofyear(Dates.Date(2000, 4, 30)) == 2 -@test Dates.quarterofyear(Dates.Date(2000, 5, 1)) == 2 -@test Dates.quarterofyear(Dates.Date(2000, 5, 31)) == 2 -@test Dates.quarterofyear(Dates.Date(2000, 6, 1)) == 2 -@test Dates.quarterofyear(Dates.Date(2000, 6, 30)) == 2 -@test Dates.quarterofyear(Dates.Date(2000, 7, 1)) == 3 -@test Dates.quarterofyear(Dates.Date(2000, 7, 31)) == 3 -@test Dates.quarterofyear(Dates.Date(2000, 8, 1)) == 3 -@test Dates.quarterofyear(Dates.Date(2000, 8, 31)) == 3 -@test Dates.quarterofyear(Dates.Date(2000, 9, 1)) == 3 -@test Dates.quarterofyear(Dates.Date(2000, 9, 30)) == 3 -@test Dates.quarterofyear(Dates.Date(2000, 10, 1)) == 4 -@test Dates.quarterofyear(Dates.Date(2000, 10, 31)) == 4 -@test Dates.quarterofyear(Dates.Date(2000, 11, 1)) == 4 -@test Dates.quarterofyear(Dates.Date(2000, 11, 30)) == 4 -@test Dates.quarterofyear(Dates.Date(2000, 12, 1)) == 4 -@test Dates.quarterofyear(Dates.Date(2000, 12, 31)) == 4 - -@test Dates.quarterofyear(Dates.DateTime(2000, 1, 1)) == 1 -@test Dates.quarterofyear(Dates.DateTime(2000, 1, 31)) == 1 -@test Dates.quarterofyear(Dates.DateTime(2000, 2, 1)) == 1 -@test Dates.quarterofyear(Dates.DateTime(2000, 2, 29)) == 1 -@test Dates.quarterofyear(Dates.DateTime(2000, 3, 1)) == 1 -@test Dates.quarterofyear(Dates.DateTime(2000, 3, 31)) == 1 -@test Dates.quarterofyear(Dates.DateTime(2000, 4, 1)) == 2 -@test Dates.quarterofyear(Dates.DateTime(2000, 4, 30)) == 2 -@test Dates.quarterofyear(Dates.DateTime(2000, 5, 1)) == 2 -@test Dates.quarterofyear(Dates.DateTime(2000, 5, 31)) == 2 -@test Dates.quarterofyear(Dates.DateTime(2000, 6, 1)) == 2 -@test Dates.quarterofyear(Dates.DateTime(2000, 6, 30)) == 2 -@test Dates.quarterofyear(Dates.DateTime(2000, 7, 1)) == 3 -@test Dates.quarterofyear(Dates.DateTime(2000, 7, 31)) == 3 -@test Dates.quarterofyear(Dates.DateTime(2000, 8, 1)) == 3 -@test Dates.quarterofyear(Dates.DateTime(2000, 8, 31)) == 3 -@test Dates.quarterofyear(Dates.DateTime(2000, 9, 1)) == 3 -@test Dates.quarterofyear(Dates.DateTime(2000, 9, 30)) == 3 -@test Dates.quarterofyear(Dates.DateTime(2000, 10, 1)) == 4 -@test Dates.quarterofyear(Dates.DateTime(2000, 10, 31)) == 4 -@test Dates.quarterofyear(Dates.DateTime(2000, 11, 1)) == 4 -@test Dates.quarterofyear(Dates.DateTime(2000, 11, 30)) == 4 -@test Dates.quarterofyear(Dates.DateTime(2000, 12, 1)) == 4 -@test Dates.quarterofyear(Dates.DateTime(2000, 12, 31)) == 4 - -@test Dates.dayofquarter(Dates.Date(2014, 1, 1)) == 1 -@test Dates.dayofquarter(Dates.Date(2014, 4, 1)) == 1 -@test Dates.dayofquarter(Dates.Date(2014, 7, 1)) == 1 -@test Dates.dayofquarter(Dates.Date(2014, 10, 1)) == 1 -@test Dates.dayofquarter(Dates.Date(2014, 3, 31)) == 90 -@test Dates.dayofquarter(Dates.Date(2014, 6, 30)) == 91 -@test Dates.dayofquarter(Dates.Date(2014, 9, 30)) == 92 -@test Dates.dayofquarter(Dates.Date(2014, 12, 31)) == 92 -@test Dates.dayofquarter(Dates.DateTime(2014, 1, 1)) == 1 -@test Dates.dayofquarter(Dates.DateTime(2014, 4, 1)) == 1 -@test Dates.dayofquarter(Dates.DateTime(2014, 7, 1)) == 1 -@test Dates.dayofquarter(Dates.DateTime(2014, 10, 1)) == 1 -@test Dates.dayofquarter(Dates.DateTime(2014, 3, 31)) == 90 -@test Dates.dayofquarter(Dates.DateTime(2014, 6, 30)) == 91 -@test Dates.dayofquarter(Dates.DateTime(2014, 9, 30)) == 92 -@test Dates.dayofquarter(Dates.DateTime(2014, 12, 31)) == 92 - diff --git a/julia-0.6.3/share/julia/test/dates/ranges.jl b/julia-0.6.3/share/julia/test/dates/ranges.jl deleted file mode 100644 index 74b2a19..0000000 --- a/julia-0.6.3/share/julia/test/dates/ranges.jl +++ /dev/null @@ -1,548 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -let - for T in (Dates.Date, Dates.DateTime) - f1 = T(2014); l1 = T(2013, 12, 31) - f2 = T(2014); l2 = T(2014) - f3 = T(-2000); l3 = T(2000) - f4 = typemin(T); l4 = typemax(T) - - for P in subtypes(Dates.DatePeriod) - for pos_step in (P(1), P(2), P(50), P(2048), P(10000)) - # empty range - dr = f1:pos_step:l1 - len = length(dr) - @test len == 0 - @test isa(len, Int64) - @test isempty(dr) - @test first(dr) == f1 - @test last(dr) < f1 - @test length([i for i in dr]) == 0 - @test_throws ArgumentError minimum(dr) - @test_throws ArgumentError maximum(dr) - @test_throws BoundsError dr[1] - @test findin(dr, dr) == Int64[] - @test [dr;] == T[] - @test isempty(reverse(dr)) - @test length(reverse(dr)) == 0 - @test first(reverse(dr)) < f1 - @test last(reverse(dr)) >= f1 - @test issorted(dr) - @test sortperm(dr) == 1:1:0 - @test !(f1 in dr) - @test !(l1 in dr) - @test !(f1 - pos_step in dr) - @test !(l1 + pos_step in dr) - - for (f, l) in ((f2, l2), (f3, l3), (f4, l4)) - dr = f:pos_step:l - len = length(dr) - @test len > 0 - @test isa(len, Int64) - @test !isempty(dr) - @test first(dr) == f - @test last(dr) <= l - @test minimum(dr) == first(dr) - @test maximum(dr) == last(dr) - @test dr[1] == f - @test dr[end] <= l - @test next(dr, start(dr)) == (first(dr), 1) - - if len < 10000 - dr1 = [i for i in dr] - @test length(dr1) == len - @test findin(dr, dr) == [1:len;] - @test length([dr;]) == len - end - @test !isempty(reverse(dr)) - @test length(reverse(dr)) == len - @test last(reverse(dr)) == f - @test issorted(dr) - @test f in dr - - end - end - for neg_step in (P(-1), P(-2), P(-50), P(-2048), P(-10000)) - # empty range - dr = l1:neg_step:f1 - len = length(dr) - @test len == 0 - @test isa(len, Int64) - @test isempty(dr) - @test first(dr) == l1 - @test last(dr) > l1 - @test length([i for i in dr]) == 0 - @test_throws ArgumentError minimum(dr) - @test_throws ArgumentError maximum(dr) - @test_throws BoundsError dr[1] - @test findin(dr, dr) == Int64[] - @test [dr;] == T[] - @test isempty(reverse(dr)) - @test length(reverse(dr)) == 0 - @test first(reverse(dr)) > l1 - @test last(reverse(dr)) <= l1 - @test issorted(dr) - @test sortperm(dr) == 1:1:0 - @test !(l1 in dr) - @test !(l1 in dr) - @test !(l1 - neg_step in dr) - @test !(l1 + neg_step in dr) - - for (f, l) in ((f2, l2), (f3, l3), (f4, l4)) - dr = l:neg_step:f - len = length(dr) - @test len > 0 - @test isa(len, Int64) - @test !isempty(dr) - @test first(dr) == l - @test last(dr) >= f - @test minimum(dr) == last(dr) - @test maximum(dr) == first(dr) - @test dr[1] == l - @test dr[end] >= f - @test next(dr, start(dr)) == (first(dr), 1) - - if len < 10000 - dr1 = [i for i in dr] - @test length(dr1) == len - @test findin(dr, dr) == [1:len;] - @test length([dr;]) == len - end - @test !isempty(reverse(dr)) - @test length(reverse(dr)) == len - @test issorted(dr) == (len <= 1) - @test l in dr - end - end - end - if T == Dates.DateTime - for P in subtypes(Dates.TimePeriod) - P in (Dates.Microsecond, Dates.Nanosecond) && continue - for pos_step in (P(1), P(2), P(50), P(2048), P(10000)) - # empty range - dr = f1:pos_step:l1 - len = length(dr) - @test len == 0 - @test isa(len, Int64) - @test isempty(dr) - @test first(dr) == f1 - @test last(dr) < f1 - @test length([i for i in dr]) == 0 - @test_throws ArgumentError minimum(dr) - @test_throws ArgumentError maximum(dr) - @test_throws BoundsError dr[1] - @test findin(dr, dr) == Int64[] - @test [dr;] == T[] - @test isempty(reverse(dr)) - @test length(reverse(dr)) == 0 - @test first(reverse(dr)) < f1 - @test last(reverse(dr)) >= f1 - @test issorted(dr) - @test sortperm(dr) == 1:1:0 - @test !(f1 in dr) - @test !(l1 in dr) - @test !(f1 - pos_step in dr) - @test !(l1 + pos_step in dr) - - for (f, l) in ((f2, l2), (f3, l3), (f4, l4)) - dr = f:pos_step:l - len = length(dr) - @test len > 0 - @test isa(len, Int64) - @test !isempty(dr) - @test first(dr) == f - @test last(dr) <= l - @test minimum(dr) == first(dr) - @test maximum(dr) == last(dr) - @test dr[1] == f - @test dr[end] <= l - @test next(dr, start(dr)) == (first(dr), 1) - - if len < 10000 - dr1 = [i for i in dr] - @test length(dr1) == len - @test findin(dr, dr) == [1:len;] - @test length([dr;]) == len - end - @test !isempty(reverse(dr)) - @test length(reverse(dr)) == len - @test last(reverse(dr)) == f - @test issorted(dr) - @test f in dr - - end - end - for neg_step in (P(-1), P(-2), P(-50), P(-2048), P(-10000)) - # empty range - dr = l1:neg_step:f1 - len = length(dr) - @test len == 0 - @test isa(len, Int64) - @test isempty(dr) - @test first(dr) == l1 - @test last(dr) > l1 - @test length([i for i in dr]) == 0 - @test_throws ArgumentError minimum(dr) - @test_throws ArgumentError maximum(dr) - @test_throws BoundsError dr[1] - @test findin(dr, dr) == Int64[] - @test [dr;] == T[] - @test isempty(reverse(dr)) - @test length(reverse(dr)) == 0 - @test first(reverse(dr)) > l1 - @test last(reverse(dr)) <= l1 - @test issorted(dr) - @test sortperm(dr) == 1:1:0 - @test !(l1 in dr) - @test !(l1 in dr) - @test !(l1 - neg_step in dr) - @test !(l1 + neg_step in dr) - - for (f, l) in ((f2, l2), (f3, l3), (f4, l4)) - dr = l:neg_step:f - len = length(dr) - @test len > 0 - @test isa(len, Int64) - @test !isempty(dr) - @test first(dr) == l - @test last(dr) >= f - @test minimum(dr) == last(dr) - @test maximum(dr) == first(dr) - @test dr[1] == l - @test dr[end] >= f - @test next(dr, start(dr)) == (first(dr), 1) - - if len < 10000 - dr1 = [i for i in dr] - @test length(dr1) == len - @test findin(dr, dr) == [1:len;] - @test length([dr;]) == len - end - @test !isempty(reverse(dr)) - @test length(reverse(dr)) == len - @test last(reverse(dr)) >= l - @test issorted(dr) == (len <= 1) - @test l in dr - - end - end - end - end - end -end - -# All the range representations we want to test -# Date ranges -dr = Dates.DateTime(2013, 1, 1):Dates.DateTime(2013, 2, 1) -dr1 = Dates.DateTime(2013, 1, 1):Dates.DateTime(2013, 1, 1) -dr2 = Dates.DateTime(2013, 1, 1):Dates.DateTime(2012, 2, 1) # empty range -dr3 = Dates.DateTime(2013, 1, 1):Dates.Day(-1):Dates.DateTime(2012) # negative step -# Big ranges -dr4 = Dates.DateTime(0):Dates.DateTime(20000, 1, 1) -dr5 = Dates.DateTime(0):Dates.DateTime(200000, 1, 1) -dr6 = Dates.DateTime(0):Dates.DateTime(2000000, 1, 1) -dr7 = Dates.DateTime(0):Dates.DateTime(20000000, 1, 1) -dr8 = Dates.DateTime(0):Dates.DateTime(200000000, 1, 1) -dr9 = typemin(Dates.DateTime):typemax(Dates.DateTime) -# Non-default steps -dr10 = typemax(Dates.DateTime):Dates.Day(-1):typemin(Dates.DateTime) -dr11 = typemin(Dates.DateTime):Dates.Week(1):typemax(Dates.DateTime) - -dr12 = typemin(Dates.DateTime):Dates.Month(1):typemax(Dates.DateTime) -dr13 = typemin(Dates.DateTime):Dates.Year(1):typemax(Dates.DateTime) - -dr14 = typemin(Dates.DateTime):Dates.Week(10):typemax(Dates.DateTime) -dr15 = typemin(Dates.DateTime):Dates.Month(100):typemax(Dates.DateTime) -dr16 = typemin(Dates.DateTime):Dates.Year(1000):typemax(Dates.DateTime) -dr17 = typemax(Dates.DateTime):Dates.Week(-10000):typemin(Dates.DateTime) -dr18 = typemax(Dates.DateTime):Dates.Month(-100000):typemin(Dates.DateTime) -dr19 = typemax(Dates.DateTime):Dates.Year(-1000000):typemin(Dates.DateTime) -dr20 = typemin(Dates.DateTime):Dates.Day(2):typemax(Dates.DateTime) - -drs = Any[dr, dr1, dr2, dr3, dr4, dr5, dr6, dr7, dr8, dr9, dr10, - dr11, dr12, dr13, dr14, dr15, dr16, dr17, dr18, dr19, dr20] -drs2 = map(x->Dates.Date(first(x)):step(x):Dates.Date(last(x)), drs) - -@test map(length, drs) == map(x->size(x)[1], drs) -@test map(length, drs) == map(x->length(Dates.Date(first(x)):step(x):Dates.Date(last(x))), drs) -@test map(length, drs) == map(x->length(reverse(x)), drs) -@test all(x->findin(x, x)==[1:length(x);], drs[1:4]) -@test isempty(dr2) -@test all(x->reverse(x) == range(last(x), -step(x), length(x)), drs) -@test all(x->minimum(x) == (step(x) < zero(step(x)) ? last(x) : first(x)), drs[4:end]) -@test all(x->maximum(x) == (step(x) < zero(step(x)) ? first(x) : last(x)), drs[4:end]) -@test all(drs[1:3]) do dd - for (i, d) in enumerate(dd) - @test d == (first(dd) + Dates.Day(i - 1)) - end - true -end -@test_throws MethodError dr + 1 -a = Dates.DateTime(2013, 1, 1) -b = Dates.DateTime(2013, 2, 1) -@test map!(x->x + Dates.Day(1), Array{Dates.DateTime}(32), dr) == [(a + Dates.Day(1)):(b + Dates.Day(1));] -@test map(x->x + Dates.Day(1), dr) == [(a + Dates.Day(1)):(b + Dates.Day(1));] - -@test map(x->a in x, drs[1:4]) == [true, true, false, true] -@test a in dr -@test b in dr -@test Dates.DateTime(2013, 1, 3) in dr -@test Dates.DateTime(2013, 1, 15) in dr -@test Dates.DateTime(2013, 1, 26) in dr -@test !(Dates.DateTime(2012, 1, 1) in dr) - -@test all(x->sort(x) == (step(x) < zero(step(x)) ? reverse(x) : x), drs) -@test all(x->step(x) < zero(step(x)) ? issorted(reverse(x)) : issorted(x), drs) - -@test length(b:Dates.Day(-1):a) == 32 -@test length(b:a) == 0 -@test length(b:Dates.Day(1):a) == 0 -@test length(a:Dates.Day(2):b) == 16 -@test last(a:Dates.Day(2):b) == Dates.DateTime(2013, 1, 31) -@test length(a:Dates.Day(7):b) == 5 -@test last(a:Dates.Day(7):b) == Dates.DateTime(2013, 1, 29) -@test length(a:Dates.Day(32):b) == 1 -@test last(a:Dates.Day(32):b) == Dates.DateTime(2013, 1, 1) -@test (a:b)[1] == Dates.DateTime(2013, 1, 1) -@test (a:b)[2] == Dates.DateTime(2013, 1, 2) -@test (a:b)[7] == Dates.DateTime(2013, 1, 7) -@test (a:b)[end] == b -@test first(a:Dates.DateTime(20000, 1, 1)) == a -@test first(a:Dates.DateTime(200000, 1, 1)) == a -@test first(a:Dates.DateTime(2000000, 1, 1)) == a -@test first(a:Dates.DateTime(20000000, 1, 1)) == a -@test first(a:Dates.DateTime(200000000, 1, 1)) == a -@test first(a:typemax(Dates.DateTime)) == a -@test first(typemin(Dates.DateTime):typemax(Dates.DateTime)) == typemin(Dates.DateTime) - -# Date ranges -dr = Dates.Date(2013, 1, 1):Dates.Date(2013, 2, 1) -dr1 = Dates.Date(2013, 1, 1):Dates.Date(2013, 1, 1) -dr2 = Dates.Date(2013, 1, 1):Dates.Date(2012, 2, 1) # empty range -dr3 = Dates.Date(2013, 1, 1):Dates.Day(-1):Dates.Date(2012, 1, 1) # negative step -# Big ranges -dr4 = Dates.Date(0):Dates.Date(20000, 1, 1) -dr5 = Dates.Date(0):Dates.Date(200000, 1, 1) -dr6 = Dates.Date(0):Dates.Date(2000000, 1, 1) -dr7 = Dates.Date(0):Dates.Date(20000000, 1, 1) -dr8 = Dates.Date(0):Dates.Date(200000000, 1, 1) -dr9 = typemin(Dates.Date):typemax(Dates.Date) -# Non-default steps -dr10 = typemax(Dates.Date):Dates.Day(-1):typemin(Dates.Date) -dr11 = typemin(Dates.Date):Dates.Week(1):typemax(Dates.Date) -dr12 = typemin(Dates.Date):Dates.Month(1):typemax(Dates.Date) -dr13 = typemin(Dates.Date):Dates.Year(1):typemax(Dates.Date) -dr14 = typemin(Dates.Date):Dates.Week(10):typemax(Dates.Date) -dr15 = typemin(Dates.Date):Dates.Month(100):typemax(Dates.Date) -dr16 = typemin(Dates.Date):Dates.Year(1000):typemax(Dates.Date) -dr17 = typemax(Dates.Date):Dates.Week(-10000):typemin(Dates.Date) -dr18 = typemax(Dates.Date):Dates.Month(-100000):typemin(Dates.Date) -dr19 = typemax(Dates.Date):Dates.Year(-1000000):typemin(Dates.Date) -dr20 = typemin(Dates.Date):Dates.Day(2):typemax(Dates.Date) - -drs = Any[dr, dr1, dr2, dr3, dr4, dr5, dr6, dr7, dr8, dr9, dr10, - dr11, dr12, dr13, dr14, dr15, dr16, dr17, dr18, dr19, dr20] - -@test map(length, drs) == map(x->size(x)[1], drs) -@test all(x->findin(x, x) == [1:length(x);], drs[1:4]) -@test isempty(dr2) -@test all(x->reverse(x) == last(x): - step(x):first(x), drs) -@test all(x->minimum(x) == (step(x) < zero(step(x)) ? last(x) : first(x)), drs[4:end]) -@test all(x->maximum(x) == (step(x) < zero(step(x)) ? first(x) : last(x)), drs[4:end]) -@test all(drs[1:3]) do dd - for (i, d) in enumerate(dd) - @test d == (first(dd) + Dates.Day(i - 1)) - end - true -end -@test_throws MethodError dr + 1 -a = Dates.Date(2013, 1, 1) -b = Dates.Date(2013, 2, 1) -@test map!(x->x + Dates.Day(1), Array{Dates.Date}(32), dr) == [(a + Dates.Day(1)):(b + Dates.Day(1));] -@test map(x->x + Dates.Day(1), dr) == [(a + Dates.Day(1)):(b + Dates.Day(1));] - -@test map(x->a in x, drs[1:4]) == [true, true, false, true] -@test a in dr -@test b in dr -@test Dates.Date(2013, 1, 3) in dr -@test Dates.Date(2013, 1, 15) in dr -@test Dates.Date(2013, 1, 26) in dr -@test !(Dates.Date(2012, 1, 1) in dr) - -@test all(x->sort(x) == (step(x) < zero(step(x)) ? reverse(x) : x), drs) -@test all(x->step(x) < zero(step(x)) ? issorted(reverse(x)) : issorted(x), drs) - -@test length(b:Dates.Day(-1):a) == 32 -@test length(b:a) == 0 -@test length(b:Dates.Day(1):a) == 0 -@test length(a:Dates.Day(2):b) == 16 -@test last(a:Dates.Day(2):b) == Dates.Date(2013, 1, 31) -@test length(a:Dates.Day(7):b) == 5 -@test last(a:Dates.Day(7):b) == Dates.Date(2013, 1, 29) -@test length(a:Dates.Day(32):b) == 1 -@test last(a:Dates.Day(32):b) == Dates.Date(2013, 1, 1) -@test (a:b)[1] == Dates.Date(2013, 1, 1) -@test (a:b)[2] == Dates.Date(2013, 1, 2) -@test (a:b)[7] == Dates.Date(2013, 1, 7) -@test (a:b)[end] == b -@test first(a:Dates.Date(20000, 1, 1)) == a -@test first(a:Dates.Date(200000, 1, 1)) == a -@test first(a:Dates.Date(2000000, 1, 1)) == a -@test first(a:Dates.Date(20000000, 1, 1)) == a -@test first(a:Dates.Date(200000000, 1, 1)) == a -@test first(a:typemax(Dates.Date)) == a -@test first(typemin(Dates.Date):typemax(Dates.Date)) == typemin(Dates.Date) - -# Non-default step sizes -@test length(typemin(Dates.Date):Dates.Week(1):typemax(Dates.Date)) == 26351950414948059 -# Big Month/Year ranges -@test length(typemin(Dates.Date):Dates.Month(1):typemax(Dates.Date)) == 6060531933867600 -@test length(typemin(Dates.Date):Dates.Year(1):typemax(Dates.Date)) == 505044327822300 -@test length(typemin(Dates.DateTime):Dates.Month(1):typemax(Dates.DateTime)) == 3507324288 -@test length(typemin(Dates.DateTime):Dates.Year(1):typemax(Dates.DateTime)) == 292277024 - -@test length(typemin(Dates.DateTime):Dates.Week(1):typemax(Dates.DateTime)) == 15250284420 -@test length(typemin(Dates.DateTime):Dates.Day(1):typemax(Dates.DateTime)) == 106751990938 -@test length(typemin(Dates.DateTime):Dates.Hour(1):typemax(Dates.DateTime)) == 2562047782512 -@test length(typemin(Dates.DateTime):Dates.Minute(1):typemax(Dates.DateTime)) == 153722866950720 -@test length(typemin(Dates.DateTime):Dates.Second(1):typemax(Dates.DateTime)) == 9223372017043200 -@test length(typemin(DateTime):Dates.Millisecond(1):typemax(DateTime)) == 9223372017043199001 - -c = Dates.Date(2013, 6, 1) -@test length(a:Dates.Month(1):c) == 6 -@test [a:Dates.Month(1):c;] == [a + Dates.Month(1)*i for i in 0:5] -@test [a:Dates.Month(2):Dates.Date(2013, 1, 2);] == [a] -@test [c:Dates.Month(-1):a;] == reverse([a:Dates.Month(1):c;]) - -@test length(range(Date(2000), 366)) == 366 -let n=100000 - a = Dates.Date(2000) - for i = 1:n - @test length(range(a, i)) == i - end - return a + Dates.Day(n) -end - -# Custom definition to override default step of DateTime ranges -@test typeof(step(Dates.DateTime(2000):Dates.DateTime(2001))) == Dates.Day - -a = Dates.Date(2013, 1, 1) -b = Dates.Date(2013, 2, 1) -d = Dates.Date(2020, 1, 1) -@test length(a:Dates.Year(1):d) == 8 -@test first(a:Dates.Year(1):d) == a -@test last(a:Dates.Year(1):d) == d -@test length(a:Dates.Month(12):d) == 8 -@test first(a:Dates.Month(12):d) == a -@test last(a:Dates.Month(12):d) == d -@test length(a:Dates.Week(52):d) == 8 -@test first(a:Dates.Week(52):d) == a -@test last(a:Dates.Week(52):d) == Dates.Date(2019, 12, 24) -@test length(a:Dates.Day(365):d) == 8 -@test first(a:Dates.Day(365):d) == a -@test last(a:Dates.Day(365):d) == Dates.Date(2019, 12, 31) - -a = Dates.Date(2013, 1, 1) -b = Dates.Date(2013, 2, 1) -@test length(a:Dates.Year(1):Dates.Date(2020, 2, 1)) == 8 -@test length(a:Dates.Year(1):Dates.Date(2020, 6, 1)) == 8 -@test length(a:Dates.Year(1):Dates.Date(2020, 11, 1)) == 8 -@test length(a:Dates.Year(1):Dates.Date(2020, 12, 31)) == 8 -@test length(a:Dates.Year(1):Dates.Date(2021, 1, 1)) == 9 -@test length(Dates.Date(2000):Dates.Year(-10):Dates.Date(1900)) == 11 -@test length(Dates.Date(2000, 6, 23):Dates.Year(-10):Dates.Date(1900, 2, 28)) == 11 -@test length(Dates.Date(2000, 1, 1):Dates.Year(1):Dates.Date(2000, 2, 1)) == 1 - -let n=100000 - a = b = Dates.Date(0) - for i = 1:n - @test length(a:Dates.Year(1):b) == i - b += Dates.Year(1) - end -end - -let n=10000 - a = Dates.Date(1985, 12, 5) - b = Dates.Date(1986, 12, 27) - c = Dates.DateTime(1985, 12, 5) - d = Dates.DateTime(1986, 12, 27) - for i = 1:n - @test length(a:Dates.Month(1):b) == 13 - @test length(a:Dates.Year(1):b) == 2 - @test length(c:Dates.Month(1):d) == 13 - @test length(c:Dates.Year(1):d) == 2 - a += Dates.Day(1) - b += Dates.Day(1) - end - return b -end - -let n=100000 - a = b = Dates.Date(2000) - for i = 1:n - @test length(a:Dates.Month(1):b) == i - b += Dates.Month(1) - end - return b -end - -@test length(Dates.Year(1):Dates.Year(1):Dates.Year(10)) == 10 -@test length(Dates.Year(10):Dates.Year(-1):Dates.Year(1)) == 10 -@test length(Dates.Year(10):Dates.Year(-2):Dates.Year(1)) == 5 -@test_throws OverflowError length(typemin(Dates.Year):Dates.Year(1):typemax(Dates.Year)) -@test_throws MethodError Dates.Date(0):Dates.DateTime(2000) -@test_throws MethodError Dates.Date(0):Dates.Year(10) -@test length(range(Dates.Date(2000), 366)) == 366 -@test last(range(Dates.Date(2000), 366)) == Dates.Date(2000, 12, 31) -@test last(range(Dates.Date(2001), 365)) == Dates.Date(2001, 12, 31) -@test last(range(Dates.Date(2000), 367)) == last(range(Dates.Date(2000), Dates.Month(12), 2)) == last(range(Dates.Date(2000), Dates.Year(1), 2)) -@test last(range(Dates.DateTime(2000), Dates.Day(366), 2)) == last(range(Dates.DateTime(2000), Dates.Hour(8784), 2)) - -# Issue 5 -lastdaysofmonth = [Dates.Date(2014, i, Dates.daysinmonth(2014, i)) for i=1:12] -@test [Date(2014, 1, 31):Dates.Month(1):Date(2015);] == lastdaysofmonth - -# Range addition/subtraction: -let d = Dates.Day(1) - @test (Dates.Date(2000):d:Dates.Date(2001)) + d == (Dates.Date(2000) + d:d:Dates.Date(2001) + d) - @test (Dates.Date(2000):d:Dates.Date(2001)) - d == (Dates.Date(2000) - d:d:Dates.Date(2001) - d) -end - -# Time ranges -dr = Dates.Time(23, 1, 1):Dates.Time(23, 2, 1) -dr1 = Dates.Time(23, 1, 1):Dates.Time(23, 1, 1) -dr2 = Dates.Time(23, 1, 1):Dates.Time(22, 2, 1) # empty range -dr3 = Dates.Time(23, 1, 1):Dates.Minute(-1):Dates.Time(22, 1, 1) # negative step -# Big ranges -dr8 = typemin(Dates.Time):typemax(Dates.Time) -dr9 = typemin(Dates.Time):Dates.Nanosecond(1):typemax(Dates.Time) -# Non - default steps -dr10 = typemax(Dates.Time):Dates.Microsecond(-1):typemin(Dates.Time) -dr11 = typemin(Dates.Time):Dates.Millisecond(1):typemax(Dates.Time) -dr12 = typemin(Dates.Time):Dates.Minute(1):typemax(Dates.Time) -dr13 = typemin(Dates.Time):Dates.Hour(1):typemax(Dates.Time) -dr14 = typemin(Dates.Time):Dates.Millisecond(10):typemax(Dates.Time) -dr15 = typemin(Dates.Time):Dates.Minute(100):typemax(Dates.Time) -dr16 = typemin(Dates.Time):Dates.Hour(1000):typemax(Dates.Time) -dr17 = typemax(Dates.Time):Dates.Millisecond(-10000):typemin(Dates.Time) -dr18 = typemax(Dates.Time):Dates.Minute(-100):typemin(Dates.Time) -dr19 = typemax(Dates.Time):Dates.Hour(-10):typemin(Dates.Time) -dr20 = typemin(Dates.Time):Dates.Microsecond(2):typemax(Dates.Time) - -drs = Any[dr, dr1, dr2, dr3, dr8, dr9, dr10, - dr11, dr12, dr13, dr14, dr15, dr16, dr17, dr18, dr19, dr20] - -@test map(length, drs) == map(x->size(x)[1], drs) -@test all(x->findin(x, x) == [1:length(x);], drs[1:4]) -@test isempty(dr2) -@test all(x->reverse(x) == last(x): - step(x):first(x), drs) -@test all(x->minimum(x) == (step(x) < zero(step(x)) ? last(x) : first(x)), drs[4:end]) -@test all(x->maximum(x) == (step(x) < zero(step(x)) ? first(x) : last(x)), drs[4:end]) -@test_throws MethodError dr + 1 - -a = Dates.Time(23, 1, 1) -@test map(x->a in x, drs[1:4]) == [true, true, false, true] -@test a in dr - -@test all(x->sort(x) == (step(x) < zero(step(x)) ? reverse(x) : x), drs) -@test all(x->step(x) < zero(step(x)) ? issorted(reverse(x)) : issorted(x), drs) diff --git a/julia-0.6.3/share/julia/test/dates/rounding.jl b/julia-0.6.3/share/julia/test/dates/rounding.jl deleted file mode 100644 index e32f592..0000000 --- a/julia-0.6.3/share/julia/test/dates/rounding.jl +++ /dev/null @@ -1,141 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -# Test conversion to and from the rounding epoch (ISO 8601 year 0000) -@test Dates.epochdays2date(-1) == Dates.Date(-1, 12, 31) -@test Dates.epochdays2date(0) == Dates.Date(0, 1, 1) -@test Dates.epochdays2date(1) == Dates.Date(0, 1, 2) -@test Dates.epochdays2date(736329) == Dates.Date(2016, 1, 1) -@test Dates.epochms2datetime(-86400000) == Dates.DateTime(-1, 12, 31) -@test Dates.epochms2datetime(0) == Dates.DateTime(0, 1, 1) -@test Dates.epochms2datetime(86400000) == Dates.DateTime(0, 1, 2) -@test Dates.epochms2datetime(Int64(736329) * 86400000) == Dates.DateTime(2016, 1, 1) -@test Dates.date2epochdays(Dates.Date(-1, 12, 31)) == -1 -@test Dates.date2epochdays(Dates.Date(0, 1, 1)) == 0 -@test Dates.date2epochdays(Dates.Date(2016, 1, 1)) == 736329 -@test Dates.datetime2epochms(Dates.DateTime(-1, 12, 31)) == -86400000 -@test Dates.datetime2epochms(Dates.DateTime(0, 1, 1)) == 0 -@test Dates.datetime2epochms(Dates.DateTime(2016, 1, 1)) == Int64(736329) * 86400000 - -# Basic rounding tests -dt = Dates.Date(2016, 2, 28) # Sunday -@test floor(dt, Dates.Year) == Dates.Date(2016) -@test floor(dt, Dates.Year(5)) == Dates.Date(2015) -@test floor(dt, Dates.Year(10)) == Dates.Date(2010) -@test floor(dt, Dates.Month) == Dates.Date(2016, 2) -@test floor(dt, Dates.Month(6)) == Dates.Date(2016, 1) -@test floor(dt, Dates.Week) == Dates.toprev(dt, Dates.Monday) -@test ceil(dt, Dates.Year) == Dates.Date(2017) -@test ceil(dt, Dates.Year(5)) == Dates.Date(2020) -@test ceil(dt, Dates.Month) == Dates.Date(2016, 3) -@test ceil(dt, Dates.Month(6)) == Dates.Date(2016, 7) -@test ceil(dt, Dates.Week) == Dates.tonext(dt, Dates.Monday) -@test round(dt, Dates.Year) == Dates.Date(2016) -@test round(dt, Dates.Month) == Dates.Date(2016, 3) -@test round(dt, Dates.Week) == Dates.Date(2016, 2, 29) - -dt = Dates.DateTime(2016, 2, 28, 15, 10, 50, 500) -@test floor(dt, Dates.Day) == Dates.DateTime(2016, 2, 28) -@test floor(dt, Dates.Hour) == Dates.DateTime(2016, 2, 28, 15) -@test floor(dt, Dates.Hour(2)) == Dates.DateTime(2016, 2, 28, 14) -@test floor(dt, Dates.Hour(12)) == Dates.DateTime(2016, 2, 28, 12) -@test floor(dt, Dates.Minute) == Dates.DateTime(2016, 2, 28, 15, 10) -@test floor(dt, Dates.Minute(15)) == Dates.DateTime(2016, 2, 28, 15, 0) -@test floor(dt, Dates.Second) == Dates.DateTime(2016, 2, 28, 15, 10, 50) -@test floor(dt, Dates.Second(30)) == Dates.DateTime(2016, 2, 28, 15, 10, 30) -@test ceil(dt, Dates.Day) == Dates.DateTime(2016, 2, 29) -@test ceil(dt, Dates.Hour) == Dates.DateTime(2016, 2, 28, 16) -@test ceil(dt, Dates.Hour(2)) == Dates.DateTime(2016, 2, 28, 16) -@test ceil(dt, Dates.Hour(12)) == Dates.DateTime(2016, 2, 29, 0) -@test ceil(dt, Dates.Minute) == Dates.DateTime(2016, 2, 28, 15, 11) -@test ceil(dt, Dates.Minute(15)) == Dates.DateTime(2016, 2, 28, 15, 15) -@test ceil(dt, Dates.Second) == Dates.DateTime(2016, 2, 28, 15, 10, 51) -@test ceil(dt, Dates.Second(30)) == Dates.DateTime(2016, 2, 28, 15, 11, 0) -@test round(dt, Dates.Day) == Dates.DateTime(2016, 2, 29) -@test round(dt, Dates.Hour) == Dates.DateTime(2016, 2, 28, 15) -@test round(dt, Dates.Hour(2)) == Dates.DateTime(2016, 2, 28, 16) -@test round(dt, Dates.Hour(12)) == Dates.DateTime(2016, 2, 28, 12) -@test round(dt, Dates.Minute) == Dates.DateTime(2016, 2, 28, 15, 11) -@test round(dt, Dates.Minute(15)) == Dates.DateTime(2016, 2, 28, 15, 15) -@test round(dt, Dates.Second) == Dates.DateTime(2016, 2, 28, 15, 10, 51) -@test round(dt, Dates.Second(30)) == Dates.DateTime(2016, 2, 28, 15, 11, 0) - -# Rounding for dates at the rounding epoch (year 0000) -dt = Dates.DateTime(0) -@test floor(dt, Dates.Year) == dt -@test floor(dt, Dates.Month) == dt -@test floor(dt, Dates.Week) == Dates.Date(-1, 12, 27) # Monday prior to 0000-01-01 -@test floor(Dates.Date(-1, 12, 27), Dates.Week) == Dates.Date(-1, 12, 27) -@test floor(dt, Dates.Day) == dt -@test floor(dt, Dates.Hour) == dt -@test floor(dt, Dates.Minute) == dt -@test floor(dt, Dates.Second) == dt -@test ceil(dt, Dates.Year) == dt -@test ceil(dt, Dates.Month) == dt -@test ceil(dt, Dates.Week) == Dates.Date(0, 1, 3) # Monday following 0000-01-01 -@test ceil(Dates.Date(0, 1, 3), Dates.Week) == Dates.Date(0, 1, 3) -@test ceil(dt, Dates.Day) == dt -@test ceil(dt, Dates.Hour) == dt -@test ceil(dt, Dates.Minute) == dt -@test ceil(dt, Dates.Second) == dt - -# Test rounding for multiples of a period (easiest to test close to rounding epoch) -dt = Dates.DateTime(0, 1, 19, 19, 19, 19, 19) -@test floor(dt, Dates.Year(2)) == DateTime(0) -@test floor(dt, Dates.Month(2)) == DateTime(0, 1) # Odd number; months are 1-indexed -@test floor(dt, Dates.Week(2)) == DateTime(0, 1, 17) # Third Monday of 0000 -@test floor(dt, Dates.Day(2)) == DateTime(0, 1, 19) # Odd number; days are 1-indexed -@test floor(dt, Dates.Hour(2)) == DateTime(0, 1, 19, 18) -@test floor(dt, Dates.Minute(2)) == DateTime(0, 1, 19, 19, 18) -@test floor(dt, Dates.Second(2)) == DateTime(0, 1, 19, 19, 19, 18) -@test ceil(dt, Dates.Year(2)) == DateTime(2) -@test ceil(dt, Dates.Month(2)) == DateTime(0, 3) # Odd number; months are 1-indexed -@test ceil(dt, Dates.Week(2)) == DateTime(0, 1, 31) # Fifth Monday of 0000 -@test ceil(dt, Dates.Day(2)) == DateTime(0, 1, 21) # Odd number; days are 1-indexed -@test ceil(dt, Dates.Hour(2)) == DateTime(0, 1, 19, 20) -@test ceil(dt, Dates.Minute(2)) == DateTime(0, 1, 19, 19, 20) -@test ceil(dt, Dates.Second(2)) == DateTime(0, 1, 19, 19, 19, 20) - -# Test rounding for dates with negative years -dt = Dates.DateTime(-1, 12, 29, 19, 19, 19, 19) -@test floor(dt, Dates.Year(2)) == DateTime(-2) -@test floor(dt, Dates.Month(2)) == DateTime(-1, 11) # Odd number; months are 1-indexed -@test floor(dt, Dates.Week(2)) == DateTime(-1, 12, 20) # 2 weeks prior to 0000-01-03 -@test floor(dt, Dates.Day(2)) == DateTime(-1, 12, 28) # Even; 4 days prior to 0000-01-01 -@test floor(dt, Dates.Hour(2)) == DateTime(-1, 12, 29, 18) -@test floor(dt, Dates.Minute(2)) == DateTime(-1, 12, 29, 19, 18) -@test floor(dt, Dates.Second(2)) == DateTime(-1, 12, 29, 19, 19, 18) -@test ceil(dt, Dates.Year(2)) == DateTime(0) -@test ceil(dt, Dates.Month(2)) == DateTime(0, 1) # Odd number; months are 1-indexed -@test ceil(dt, Dates.Week(2)) == DateTime(0, 1, 3) # First Monday of 0000 -@test ceil(dt, Dates.Day(2)) == DateTime(-1, 12, 30) # Even; 2 days prior to 0000-01-01 -@test ceil(dt, Dates.Hour(2)) == DateTime(-1, 12, 29, 20) -@test ceil(dt, Dates.Minute(2)) == DateTime(-1, 12, 29, 19, 20) -@test ceil(dt, Dates.Second(2)) == DateTime(-1, 12, 29, 19, 19, 20) - -# Test rounding for dates that should not need rounding -for dt in [Dates.DateTime(2016, 1, 1), Dates.DateTime(-2016, 1, 1)] - for p in [Dates.Year, Dates.Month, Dates.Day, Dates.Hour, Dates.Minute, Dates.Second] - @test floor(dt, p) == dt - @test ceil(dt, p) == dt - end -end - -# Test available RoundingModes -dt = Dates.DateTime(2016, 2, 28, 12) -@test round(dt, Dates.Day, RoundNearestTiesUp) == Dates.DateTime(2016, 2, 29) -@test round(dt, Dates.Day, RoundUp) == Dates.DateTime(2016, 2, 29) -@test round(dt, Dates.Day, RoundDown) == Dates.DateTime(2016, 2, 28) -@test_throws DomainError round(dt, Dates.Day, RoundNearest) -@test_throws DomainError round(dt, Dates.Day, RoundNearestTiesAway) -@test_throws DomainError round(dt, Dates.Day, RoundToZero) -@test round(dt, Dates.Day) == round(dt, Dates.Day, RoundNearestTiesUp) - -# Test rounding to invalid resolutions -dt = Dates.DateTime(2016, 2, 28, 12, 15) -for p in [Dates.Year, Dates.Month, Dates.Week, Dates.Day, Dates.Hour] - for v in [-1, 0] - @test_throws DomainError floor(dt, p(v)) - @test_throws DomainError ceil(dt, p(v)) - @test_throws DomainError round(dt, p(v)) - end -end diff --git a/julia-0.6.3/share/julia/test/dates/types.jl b/julia-0.6.3/share/julia/test/dates/types.jl deleted file mode 100644 index 21d7918..0000000 --- a/julia-0.6.3/share/julia/test/dates/types.jl +++ /dev/null @@ -1,210 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -# Date internal algorithms -@test Dates.totaldays(0, 2, 28) == -307 -@test Dates.totaldays(0, 2, 29) == -306 -@test Dates.totaldays(0, 3, 1) == -305 -@test Dates.totaldays(0, 12, 31) == 0 -# Rata Die Days # start from 0001-01-01 -@test Dates.totaldays(1, 1, 1) == 1 -@test Dates.totaldays(1, 1, 2) == 2 -@test Dates.totaldays(2013, 1, 1) == 734869 - -@test Dates.daysinmonth(2000, 1) == 31 -@test Dates.daysinmonth(2000, 2) == 29 -@test Dates.daysinmonth(2000, 3) == 31 -@test Dates.daysinmonth(2000, 4) == 30 -@test Dates.daysinmonth(2000, 5) == 31 -@test Dates.daysinmonth(2000, 6) == 30 -@test Dates.daysinmonth(2000, 7) == 31 -@test Dates.daysinmonth(2000, 8) == 31 -@test Dates.daysinmonth(2000, 9) == 30 -@test Dates.daysinmonth(2000, 10) == 31 -@test Dates.daysinmonth(2000, 11) == 30 -@test Dates.daysinmonth(2000, 12) == 31 -@test Dates.daysinmonth(2001, 2) == 28 - -@test Dates.isleapyear(1900) == false -@test Dates.isleapyear(2000) == true -@test Dates.isleapyear(2004) == true -@test Dates.isleapyear(2008) == true -@test Dates.isleapyear(0) == true -@test Dates.isleapyear(1) == false -@test Dates.isleapyear(-1) == false -@test Dates.isleapyear(4) == true -@test Dates.isleapyear(-4) == true - -# Create "test" check manually -test = Dates.DateTime(Dates.UTM(63492681600000)) -# Test DateTime construction by parts -@test Dates.DateTime(2013) == test -@test Dates.DateTime(2013, 1) == test -@test Dates.DateTime(2013, 1, 1) == test -@test Dates.DateTime(2013, 1, 1, 0) == test -@test Dates.DateTime(2013, 1, 1, 0, 0) == test -@test Dates.DateTime(2013, 1, 1, 0, 0, 0) == test -@test Dates.DateTime(2013, 1, 1, 0, 0, 0, 0) == test -test = Dates.Date(Dates.UTD(734869)) -# Test Date construction by parts -@test Dates.Date(2013) == test -@test Dates.Date(2013, 1) == test -@test Dates.Date(2013, 1, 1) == test -# Test Time construction by parts -t = Dates.Time(Dates.Nanosecond(82800000000000)) -@test Dates.Time(23) == t -@test Dates.Time(23, 0) == t -@test Dates.Time(23, 0, 0) == t -@test Dates.Time(23, 0, 0, 0) == t -@test Dates.Time(23, 0, 0, 0, 0) == t -@test Dates.Time(23, 0, 0, 0, 0, 0) == t - -# Test various input types for Date/DateTime -test = Dates.Date(1, 1, 1) -@test Dates.Date(Int8(1), Int8(1), Int8(1)) == test -@test Dates.Date(UInt8(1), UInt8(1), UInt8(1)) == test -@test Dates.Date(Int16(1), Int16(1), Int16(1)) == test -@test Dates.Date(UInt8(1), UInt8(1), UInt8(1)) == test -@test Dates.Date(Int32(1), Int32(1), Int32(1)) == test -@test Dates.Date(UInt32(1), UInt32(1), UInt32(1)) == test -@test Dates.Date(Int64(1), Int64(1), Int64(1)) == test -@test Dates.Date('\x01', '\x01', '\x01') == test -@test Dates.Date(true, true, true) == test -@test_throws ArgumentError Dates.Date(false, true, false) -@test Dates.Date(false, true, true) == test - Dates.Year(1) -@test_throws ArgumentError Dates.Date(true, true, false) -@test Dates.Date(UInt64(1), UInt64(1), UInt64(1)) == test -@test Dates.Date(-1, UInt64(1), UInt64(1)) == test - Dates.Year(2) -@test Dates.Date(Int128(1), Int128(1), Int128(1)) == test -@test_throws InexactError Dates.Date(170141183460469231731687303715884105727, Int128(1), Int128(1)) -@test Dates.Date(UInt128(1), UInt128(1), UInt128(1)) == test -@test Dates.Date(big(1), big(1), big(1)) == test -@test Dates.Date(big(1), big(1), big(1)) == test -# Potentially won't work if can't losslessly convert to Int64 -@test Dates.Date(BigFloat(1), BigFloat(1), BigFloat(1)) == test -@test Dates.Date(complex(1), complex(1), complex(1)) == test -@test Dates.Date(Float64(1), Float64(1), Float64(1)) == test -@test Dates.Date(Float32(1), Float32(1), Float32(1)) == test -@test Dates.Date(Float16(1), Float16(1), Float16(1)) == test -@test Dates.Date(Rational(1), Rational(1), Rational(1)) == test -@test_throws InexactError Dates.Date(BigFloat(1.2), BigFloat(1), BigFloat(1)) -@test_throws InexactError Dates.Date(1 + im, complex(1), complex(1)) -@test_throws InexactError Dates.Date(1.2, 1.0, 1.0) -@test_throws InexactError Dates.Date(1.2f0, 1.f0, 1.f0) -@test_throws InexactError Dates.Date(3//4, Rational(1), Rational(1)) == test - -# Months, days, hours, minutes, seconds, and milliseconds must be in range -@test_throws ArgumentError Dates.Date(2013, 0, 1) -@test_throws ArgumentError Dates.Date(2013, 13, 1) -@test_throws ArgumentError Dates.Date(2013, 1, 0) -@test_throws ArgumentError Dates.Date(2013, 1, 32) -@test_throws ArgumentError Dates.DateTime(2013, 0, 1) -@test_throws ArgumentError Dates.DateTime(2013, 13, 1) -@test_throws ArgumentError Dates.DateTime(2013, 1, 0) -@test_throws ArgumentError Dates.DateTime(2013, 1, 32) -@test_throws ArgumentError Dates.DateTime(2013, 1, 1, 24) -@test_throws ArgumentError Dates.DateTime(2013, 1, 1, -1) -@test_throws ArgumentError Dates.DateTime(2013, 1, 1, 0, -1) -@test_throws ArgumentError Dates.DateTime(2013, 1, 1, 0, 60) -@test_throws ArgumentError Dates.DateTime(2013, 1, 1, 0, 0, -1) -@test_throws ArgumentError Dates.DateTime(2013, 1, 1, 0, 0, 60) -@test_throws ArgumentError Dates.DateTime(2013, 1, 1, 0, 0, 0, -1) -@test_throws ArgumentError Dates.DateTime(2013, 1, 1, 0, 0, 0, 1000) -@test_throws ArgumentError Dates.Time(24) -@test_throws ArgumentError Dates.Time(-1) -@test_throws ArgumentError Dates.Time(0, -1) -@test_throws ArgumentError Dates.Time(0, 60) -@test_throws ArgumentError Dates.Time(0, 0, -1) -@test_throws ArgumentError Dates.Time(0, 0, 60) -@test_throws ArgumentError Dates.Time(0, 0, 0, -1) -@test_throws ArgumentError Dates.Time(0, 0, 0, 1000) -@test_throws ArgumentError Dates.Time(0, 0, 0, 0, -1) -@test_throws ArgumentError Dates.Time(0, 0, 0, 0, 1000) -@test_throws ArgumentError Dates.Time(0, 0, 0, 0, 0, -1) -@test_throws ArgumentError Dates.Time(0, 0, 0, 0, 0, 1000) - -# Test DateTime traits -a = Dates.DateTime(2000) -b = Dates.Date(2000) -c = Dates.Time(0) -@test Dates.calendar(a) == Dates.ISOCalendar -@test Dates.calendar(b) == Dates.ISOCalendar -@test eps(a) == Dates.Millisecond(1) -@test eps(b) == Dates.Day(1) -@test eps(c) == Dates.Nanosecond(1) -@test string(typemax(Dates.DateTime)) == "146138512-12-31T23:59:59" -@test string(typemin(Dates.DateTime)) == "-146138511-01-01T00:00:00" -@test typemax(Dates.DateTime) - typemin(Dates.DateTime) == Dates.Millisecond(9223372017043199000) -@test string(typemax(Dates.Date)) == "252522163911149-12-31" -@test string(typemin(Dates.Date)) == "-252522163911150-01-01" -@test string(typemax(Dates.Time)) == "23:59:59.999999999" -@test string(typemin(Dates.Time)) == "00:00:00" -@test isfinite(Dates.Date) -@test isfinite(Dates.DateTime) -@test isfinite(Dates.Time) - -# Date-DateTime conversion/promotion -@test Dates.DateTime(a) == a -@test Dates.Date(a) == b -@test Dates.DateTime(b) == a -@test Dates.Date(b) == b -@test a == b -@test a == a -@test b == a -@test b == b -@test !(a < b) -@test !(b < a) -c = Dates.DateTime(2000) -d = Dates.Date(2000) -@test ==(a, c) -@test ==(c, a) -@test ==(d, b) -@test ==(b, d) -@test ==(a, d) -@test ==(d, a) -@test ==(b, c) -@test ==(c, b) -b = Dates.Date(2001) -@test b > a -@test a < b -@test a != b -@test Dates.Date(Dates.DateTime(Dates.Date(2012, 7, 1))) == Dates.Date(2012, 7, 1) - -y = Dates.Year(1) -m = Dates.Month(1) -w = Dates.Week(1) -d = Dates.Day(1) -h = Dates.Hour(1) -mi = Dates.Minute(1) -s = Dates.Second(1) -ms = Dates.Millisecond(1) -@test Dates.DateTime(y) == Dates.DateTime(1) -@test Dates.DateTime(y, m) == Dates.DateTime(1, 1) -@test Dates.DateTime(y, m, d) == Dates.DateTime(1, 1, 1) -@test Dates.DateTime(y, m, d, h) == Dates.DateTime(1, 1, 1, 1) -@test Dates.DateTime(y, m, d, h, mi) == Dates.DateTime(1, 1, 1, 1, 1) -@test Dates.DateTime(y, m, d, h, mi, s) == Dates.DateTime(1, 1, 1, 1, 1, 1) -@test Dates.DateTime(y, m, d, h, mi, s, ms) == Dates.DateTime(1, 1, 1, 1, 1, 1, 1) -@test Dates.DateTime(Dates.Day(10), Dates.Month(2), y) == Dates.DateTime(1, 2, 10) -@test Dates.DateTime(Dates.Second(10), Dates.Month(2), y, Dates.Hour(4)) == Dates.DateTime(1, 2, 1, 4, 0, 10) -@test Dates.DateTime(Dates.Year(1), Dates.Month(2), Dates.Day(1), - Dates.Hour(4), Dates.Second(10)) == Dates.DateTime(1, 2, 1, 4, 0, 10) -@test Dates.Date(y) == Dates.Date(1) -@test Dates.Date(y, m) == Dates.Date(1, 1) -@test Dates.Date(y, m, d) == Dates.Date(1, 1, 1) -@test Dates.Date(m) == Dates.Date(1, 1, 1) -@test Dates.Date(d, y) == Dates.Date(1, 1, 1) -@test Dates.Date(d, m) == Dates.Date(1, 1, 1) -@test Dates.Date(m, y) == Dates.Date(1, 1, 1) -@test Dates.Date(Dates.Day(10), Dates.Month(2), y) == Dates.Date(1, 2, 10) -us = Dates.Microsecond(1) -ns = Dates.Nanosecond(1) -@test Dates.Time(h) == Dates.Time(1) -@test Dates.Time(h, mi) == Dates.Time(1, 1) -@test Dates.Time(h, mi, s) == Dates.Time(1, 1, 1) -@test Dates.Time(h, mi, s, ms) == Dates.Time(1, 1, 1, 1) -@test Dates.Time(h, mi, s, ms, us) == Dates.Time(1, 1, 1, 1, 1) -@test Dates.Time(h, mi, s, ms, us, ns) == Dates.Time(1, 1, 1, 1, 1, 1) -@test Dates.Time(us, h, s, ns, mi, ms) == Dates.Time(1, 1, 1, 1, 1, 1) -@test Dates.Time(Dates.Second(10), Dates.Minute(2), us, Dates.Hour(4)) == Dates.Time(4, 2, 10, 0, 1) -@test Dates.Time(Dates.Hour(4), Dates.Second(10), Dates.Millisecond(15), - Dates.Microsecond(20), Dates.Nanosecond(25)) == Dates.Time(4, 0, 10, 15, 20, 25) diff --git a/julia-0.6.3/share/julia/test/deprecation_exec.jl b/julia-0.6.3/share/julia/test/deprecation_exec.jl deleted file mode 100644 index e9773fa..0000000 --- a/julia-0.6.3/share/julia/test/deprecation_exec.jl +++ /dev/null @@ -1,66 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -using Base.Test - -module DeprecationTests # to test @deprecate - f() = true - - # test the Symbol path of @deprecate - @deprecate f1 f - @deprecate f2 f false # test that f2 is not exported - - # test the Expr path of @deprecate - @deprecate f3() f() - @deprecate f4() f() false # test that f4 is not exported - @deprecate f5(x::T) where T f() - - # test deprecation of a constructor - struct A{T} end - @deprecate A{T}(x::S) where {T, S} f() -end # module -module Foo1234 - export foo1234 - foo1234(x) = x+1 -end - -# issue #21972 -struct T21972 - @noinline function T21972() - Base.depwarn("something", :T21972) - new() - end -end - -@testset "@deprecate" begin - using .DeprecationTests - using .Foo1234 - @test foo1234(3) == 4 - - # enable when issue #22043 is fixed - # @test @test_warn "f1 is deprecated, use f instead." f1() - # @test @test_nowarn f1() - - # @test_throws UndefVarError f2() # not exported - # @test @test_warn "f2 is deprecated, use f instead." DeprecationTests.f2() - # @test @test_nowarn DeprecationTests.f2() - - # @test @test_warn "f3() is deprecated, use f() instead." f3() - # @test @test_nowarn f3() - - # @test_throws UndefVarError f4() # not exported - # @test @test_warn "f4() is deprecated, use f() instead." DeprecationTests.f4() - # @test @test_nowarn DeprecationTests.f4() - - # @test @test_warn "f5(x::T) where T is deprecated, use f() instead." f5(1) - # @test @test_nowarn f5(1) - - # @test @test_warn "A{T}(x::S) where {T, S} is deprecated, use f() instead." A{Int}(1.) - # @test @test_nowarn A{Int}(1.) - - # issue #21972 - @noinline function f21972() - T21972() - end - @test_warn "deprecated" f21972() - @test_nowarn f21972() -end diff --git a/julia-0.6.3/share/julia/test/dict.jl b/julia-0.6.3/share/julia/test/dict.jl deleted file mode 100644 index 9f900b8..0000000 --- a/julia-0.6.3/share/julia/test/dict.jl +++ /dev/null @@ -1,744 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -# Pair -p = Pair(10,20) -@test p == (10=>20) -@test isequal(p,10=>20) -@test start(p) == 1 -@test next(p, 1) == (10,2) -@test !done(p, 1) -@test !done(p,2) -@test done(p,3) -@test !done(p,0) -@test endof(p) == length(p) == 2 -@test Base.indexed_next(p, 1, (1,2)) == (10,2) -@test Base.indexed_next(p, 2, (1,2)) == (20,3) -@test (1=>2) < (2=>3) -@test (2=>2) < (2=>3) -@test !((2=>3) < (2=>3)) -@test (2=>3) < (4=>3) -@test (1=>100) < (4=>1) -@test p[1] == 10 -@test p[2] == 20 -@test_throws BoundsError p[3] -@test_throws BoundsError p[false] -@test p[true] == 10 -@test p[2.0] == 20 -@test p[0x01] == 10 -@test_throws InexactError p[2.3] -@test first(p) == 10 -@test last(p) == 20 -@test eltype(p) == Int -@test eltype(4 => 5.6) == Union{Int,Float64} - -# Dict -h = Dict() -for i=1:10000 - h[i] = i+1 -end -for i=1:10000 - @test (h[i] == i+1) -end -for i=1:2:10000 - delete!(h, i) -end -for i=1:2:10000 - h[i] = i+1 -end -for i=1:10000 - @test (h[i] == i+1) -end -for i=1:10000 - delete!(h, i) -end -@test isempty(h) -h[77] = 100 -@test h[77] == 100 -for i=1:10000 - h[i] = i+1 -end -for i=1:2:10000 - delete!(h, i) -end -for i=10001:20000 - h[i] = i+1 -end -for i=2:2:10000 - @test h[i] == i+1 -end -for i=10000:20000 - @test h[i] == i+1 -end -h = Dict{Any,Any}("a" => 3) -@test h["a"] == 3 -h["a","b"] = 4 -@test h["a","b"] == h[("a","b")] == 4 -h["a","b","c"] = 4 -@test h["a","b","c"] == h[("a","b","c")] == 4 - -# Test eltype, keytype and valtype -@test eltype(h) == Pair{Any,Any} -@test keytype(h) == Any -@test valtype(h) == Any - -let td = Dict{AbstractString,Float64}() - @test eltype(td) == Pair{AbstractString,Float64} - @test keytype(td) == AbstractString - @test valtype(td) == Float64 - @test keytype(Dict{AbstractString,Float64}) === AbstractString - @test valtype(Dict{AbstractString,Float64}) === Float64 -end - -let z = Dict() - get_KeyError = false - try - z["a"] - catch _e123_ - get_KeyError = isa(_e123_,KeyError) - end - @test get_KeyError -end - -_d = Dict("a"=>0) -@test isa([k for k in filter(x->length(x)==1, collect(keys(_d)))], Vector{String}) - -let d = Dict(((1, 2), (3, 4))) - @test d[1] === 2 - @test d[3] === 4 - d2 = Dict(1 => 2, 3 => 4) - d3 = Dict((1 => 2, 3 => 4)) - @test d == d2 == d3 - @test typeof(d) == typeof(d2) == typeof(d3) == Dict{Int,Int} - - d = Dict(((1, 2), (3, "b"))) - @test d[1] === 2 - @test d[3] == "b" - d2 = Dict(1 => 2, 3 => "b") - d3 = Dict((1 => 2, 3 => "b")) - @test d == d2 == d3 - @test typeof(d) == typeof(d2) == typeof(d3) == Dict{Int,Any} - - d = Dict(((1, 2), ("a", 4))) - @test d[1] === 2 - @test d["a"] === 4 - d2 = Dict(1 => 2, "a" => 4) - d3 = Dict((1 => 2, "a" => 4)) - @test d == d2 == d3 - @test typeof(d) == typeof(d2) == typeof(d3) == Dict{Any,Int} - - d = Dict(((1, 2), ("a", "b"))) - @test d[1] === 2 - @test d["a"] == "b" - d2 = Dict(1 => 2, "a" => "b") - d3 = Dict((1 => 2, "a" => "b")) - @test d == d2 == d3 - @test typeof(d) == typeof(d2) == typeof(d3) == Dict{Any,Any} -end - -@test_throws ArgumentError first(Dict()) -@test first(Dict(:f=>2)) == (:f=>2) - -# constructing Dicts from iterators -let d = @inferred Dict(i=>i for i=1:3) - @test isa(d, Dict{Int,Int}) - @test d == Dict(1=>1, 2=>2, 3=>3) -end -let d = Dict(i==1 ? (1=>2) : (2.0=>3.0) for i=1:2) - @test isa(d, Dict{Real,Real}) - @test d == Dict{Real,Real}(2.0=>3.0, 1=>2) -end - -@test_throws KeyError Dict("a"=>2)[Base.secret_table_token] - -# issue #1821 -let d = Dict{String, Vector{Int}}() - d["a"] = [1, 2] - @test_throws MethodError d["b"] = 1 - @test isa(repr(d), AbstractString) # check that printable without error -end - -# issue #2344 -let - local bar - bestkey(d, key) = key - bestkey{K<:AbstractString,V}(d::Associative{K,V}, key) = string(key) - bar(x) = bestkey(x, :y) - @test bar(Dict(:x => [1,2,5])) == :y - @test bar(Dict("x" => [1,2,5])) == "y" -end - -# issue #1438 -mutable struct I1438T - id -end -import Base.hash -hash(x::I1438T, h::UInt) = hash(x.id, h) - -let - local seq, xs, s - seq = [26,28,29,30,31,32,33,34,35,36,-32,-35,-34,-28,37,38,39,40,-30, - -31,41,42,43,44,-33,-36,45,46,47,48,-37,-38,49,50,51,52,-46,-50,53] - xs = [ I1438T(id) for id=1:53 ] - s = Set() - for id in seq - if id > 0 - x = xs[id] - push!(s, x) - @test in(x, s) # check that x can be found - else - delete!(s, xs[-id]) - end - end -end - -@test isequal(Dict(), Dict()) -@test isequal(Dict(1 => 1), Dict(1 => 1)) -@test !isequal(Dict(1 => 1), Dict()) -@test !isequal(Dict(1 => 1), Dict(1 => 2)) -@test !isequal(Dict(1 => 1), Dict(2 => 1)) - -# Generate some data to populate dicts to be compared -data_in = [ (rand(1:1000), randstring(2)) for _ in 1:1001 ] - -# Populate the first dict -d1 = Dict{Int, AbstractString}() -for (k,v) in data_in - d1[k] = v -end -data_in = collect(d1) -# shuffle the data -for i in 1:length(data_in) - j = rand(1:length(data_in)) - data_in[i], data_in[j] = data_in[j], data_in[i] -end -# Inserting data in different (shuffled) order should result in -# equivalent dict. -d2 = Dict{Int, AbstractString}() -for (k,v) in data_in - d2[k] = v -end - -@test isequal(d1, d2) -d3 = copy(d2) -d4 = copy(d2) -# Removing an item gives different dict -delete!(d1, data_in[rand(1:length(data_in))][1]) -@test !isequal(d1, d2) -# Changing a value gives different dict -d3[data_in[rand(1:length(data_in))][1]] = randstring(3) -!isequal(d1, d3) -# Adding a pair gives different dict -d4[1001] = randstring(3) -@test !isequal(d1, d4) - -@test isequal(Dict(), sizehint!(Dict(),96)) - -# Here is what currently happens when dictionaries of different types -# are compared. This is not necessarily desirable. These tests are -# descriptive rather than proscriptive. -@test !isequal(Dict(1 => 2), Dict("dog" => "bone")) -@test isequal(Dict{Int,Int}(), Dict{AbstractString,AbstractString}()) - -# get! (get with default values assigned to the given location) -let f(x) = x^2, d = Dict(8=>19) - @test get!(d, 8, 5) == 19 - @test get!(d, 19, 2) == 2 - - @test get!(d, 42) do # d is updated with f(2) - f(2) - end == 4 - - @test get!(d, 42) do # d is not updated - f(200) - end == 4 - - @test get(d, 13) do # d is not updated - f(4) - end == 16 - - @test d == Dict(8=>19, 19=>2, 42=>4) -end - -# show -for d in (Dict("\n" => "\n", "1" => "\n", "\n" => "2"), - Dict(string(i) => i for i = 1:30), - Dict(reshape(1:i^2,i,i) => reshape(1:i^2,i,i) for i = 1:24), - Dict(String(Char['α':'α'+i;]) => String(Char['α':'α'+i;]) for i = (1:10)*10), - Dict("key" => zeros(0, 0))) - for cols in (12, 40, 80), rows in (2, 10, 24) - # Ensure output is limited as requested - s = IOBuffer() - io = Base.IOContext(Base.IOContext(s, :limit => true), :displaysize => (rows, cols)) - Base.show(io, MIME("text/plain"), d) - out = split(String(take!(s)),'\n') - for line in out[2:end] - @test strwidth(line) <= cols - end - @test length(out) <= rows - - for f in (keys, values) - s = IOBuffer() - io = Base.IOContext(Base.IOContext(s, :limit => true), :displaysize => (rows, cols)) - Base.show(io, MIME("text/plain"), f(d)) - out = split(String(take!(s)),'\n') - for line in out[2:end] - @test strwidth(line) <= cols - end - @test length(out) <= rows - end - end - # Simply ensure these do not throw errors - Base.show(IOBuffer(), d) - @test !isempty(summary(d)) - @test !isempty(summary(keys(d))) - @test !isempty(summary(values(d))) -end - -# Issue #15739 - Compact REPL printouts of an `Associative` use brackets when appropriate -let d = Dict((1=>2) => (3=>45), (3=>10) => (10=>11)) - buf = IOBuffer() - showcompact(buf, d) - - # Check explicitly for the expected strings, since the CPU bitness effects - # dictionary ordering. - result = String(buf) - @test contains(result, "Dict") - @test contains(result, "(1=>2)=>(3=>45)") - @test contains(result, "(3=>10)=>(10=>11)") -end - -# issue #9463 -mutable struct Alpha end -Base.show(io::IO, ::Alpha) = print(io,"α") -let sbuff = IOBuffer(), - io = Base.IOContext(Base.IOContext(sbuff, :limit => true), :displaysize => (10, 20)) - - Base.show(io, MIME("text/plain"), Dict(Alpha()=>1)) - @test !contains(String(sbuff), "…") - @test endswith(String(sbuff), "α => 1") -end - -# issue #2540 -let d = Dict{Any,Any}(Dict(x => 1 for x in ['a', 'b', 'c'])) - @test d == Dict('a'=>1, 'b'=>1, 'c'=> 1) -end - -# issue #2629 -let d = Dict{AbstractString,AbstractString}(Dict( a => "foo" for a in ["a","b","c"])) - @test d == Dict("a"=>"foo","b"=>"foo","c"=>"foo") -end - -# issue #5886 -d5886 = Dict() -for k5886 in 1:11 - d5886[k5886] = 1 -end -for k5886 in keys(d5886) - # undefined ref if not fixed - d5886[k5886] += 1 -end - -# issue #8877 -let a = Dict("foo" => 0.0, "bar" => 42.0), - b = Dict("フー" => 17, "バー" => 4711) - @test typeof(merge(a, b)) === Dict{String,Float64} -end - -# issue 9295 -let d = Dict() - @test push!(d, 'a' => 1) === d - @test d['a'] == 1 - @test push!(d, 'b' => 2, 'c' => 3) === d - @test d['b'] == 2 - @test d['c'] == 3 - @test push!(d, 'd' => 4, 'e' => 5, 'f' => 6) === d - @test d['d'] == 4 - @test d['e'] == 5 - @test d['f'] == 6 - @test length(d) == 6 -end - -# issue #10647 -mutable struct T10647{T}; x::T; end -let a = ObjectIdDict() - a[1] = a - a[a] = 2 - a[3] = T10647(a) - @test a == a - show(IOBuffer(), a) - Base.show(Base.IOContext(IOBuffer(), :limit => true), a) - Base.show(IOBuffer(), a) - Base.show(Base.IOContext(IOBuffer(), :limit => true), a) -end - -let - a = ObjectIdDict() - a[1] = a - a[a] = 2 - - sa = similar(a) - @test isempty(sa) - @test isa(sa, ObjectIdDict) - - @test length(a) == 2 - @test 1 in keys(a) - @test a in keys(a) - @test a[1] === a - @test a[a] === 2 - - ca = copy(a) - @test length(ca) == length(a) - @test ca == a - @test ca !== a # make sure they are different objects - - ca = empty!(ca) - @test length(ca) == 0 - @test length(a) == 2 - - d = Dict('a'=>1, 'b'=>1, 'c'=> 3) - @test a != d -end - -@test length(ObjectIdDict(1=>2, 1.0=>3)) == 2 -@test length(Dict(1=>2, 1.0=>3)) == 1 - -let d = @inferred ObjectIdDict(i=>i for i=1:3) - @test isa(d, ObjectIdDict) - @test d == ObjectIdDict(1=>1, 2=>2, 3=>3) -end - -let d = @inferred ObjectIdDict(Pair(1,1), Pair(2,2), Pair(3,3)) - @test isa(d, ObjectIdDict) - @test d == ObjectIdDict(1=>1, 2=>2, 3=>3) - @test eltype(d) == Pair{Any,Any} -end - -@testset "issue #26833, deletion from IdDict" begin - d = ObjectIdDict() - i = 1 - # generate many hash collisions - while length(d) < 32 # expected to occur at i <≈ 2^16 * 2^5 - if object_id(i) % UInt16 == 0x1111 - push!(d, i => true) - end - i += 1 - end - k = collect(keys(d)) - @test haskey(d, k[1]) - delete!(d, k[1]) - @test length(d) == 31 - @test !haskey(d, k[1]) - @test haskey(d, k[end]) - push!(d, k[end] => false) - @test length(d) == 31 - @test haskey(d, k[end]) - @test !pop!(d, k[end]) - @test !haskey(d, k[end]) - @test length(d) == 30 -end - -# Issue #7944 -let d = Dict{Int,Int}() - get!(d, 0) do - d[0] = 1 - end - @test length(d) == 1 -end - -# iteration -d = Dict('a'=>1, 'b'=>1, 'c'=> 3) -@test [d[k] for k in keys(d)] == [d[k] for k in eachindex(d)] == - [v for (k, v) in d] == [d[x[1]] for (i, x) in enumerate(d)] - -# generators, similar -d = Dict(:a=>"a") -@test @inferred(map(identity, d)) == d -@test @inferred(map(p->p.first=>p.second[1], d)) == Dict(:a=>'a') -@test_throws ArgumentError map(p->p.second, d) - -# Issue 12451 -@test_throws ArgumentError Dict(0) -@test_throws ArgumentError Dict([1]) -@test_throws ArgumentError Dict([(1,2),0]) - -# test Dict constructor's argument checking (for an iterable of pairs or tuples) -# make sure other errors can propagate when the nature of the iterator is not the problem -@test_throws InexactError Dict(convert(Int,1.5) for i=1:1) -@test_throws InexactError WeakKeyDict(convert(Int,1.5) for i=1:1) - -# ImmutableDict -import Base.ImmutableDict -let d = ImmutableDict{String, String}(), - k1 = "key1", - k2 = "key2", - v1 = "value1", - v2 = "value2", - d1 = ImmutableDict(d, k1 => v1), - d2 = ImmutableDict(d1, k2 => v2), - d3 = ImmutableDict(d2, k1 => v2), - d4 = ImmutableDict(d3, k2 => v1), - dnan = ImmutableDict{String, Float64}(k2, NaN), - dnum = ImmutableDict(dnan, k2 => 1) - - @test isempty(collect(d)) - @test !isempty(collect(d1)) - @test isempty(d) - @test !isempty(d1) - @test length(d) == 0 - @test length(d1) == 1 - @test length(d2) == 2 - @test length(d3) == 3 - @test length(d4) == 4 - @test !(k1 in keys(d)) - @test k1 in keys(d1) - @test k1 in keys(d2) - @test k1 in keys(d3) - @test k1 in keys(d4) - - @test !haskey(d, k1) - @test haskey(d1, k1) - @test haskey(d2, k1) - @test haskey(d3, k1) - @test haskey(d4, k1) - @test !(k2 in keys(d1)) - @test k2 in keys(d2) - @test !(k1 in values(d4)) - @test v1 in values(d4) - @test collect(d1) == [Pair(k1, v1)] - @test collect(d4) == reverse([Pair(k1, v1), Pair(k2, v2), Pair(k1, v2), Pair(k2, v1)]) - @test d1 == ImmutableDict(d, k1 => v1) - @test !((k1 => v2) in d2) - @test (k1 => v2) in d3 - @test (k1 => v1) in d4 - @test (k1 => v2) in d4 - @test !in(k2 => "value2", d4, ===) - @test in(k2 => v2, d4, ===) - @test in(k2 => NaN, dnan, isequal) - @test in(k2 => NaN, dnan, ===) - @test !in(k2 => NaN, dnan, ==) - @test !in(k2 => 1, dnum, ===) - @test in(k2 => 1.0, dnum, ===) - @test !in(k2 => 1, dnum, <) - @test in(k2 => 0, dnum, <) - @test get(d1, "key1", :default) === v1 - @test get(d4, "key1", :default) === v2 - @test get(d4, "foo", :default) === :default - @test get(d, k1, :default) === :default - @test d1["key1"] === v1 - @test d4["key1"] === v2 - @test similar(d3) === d - @test similar(d) === d - - @test_throws KeyError d[k1] - @test_throws KeyError d1["key2"] -end - -# filtering -let d = Dict(zip(1:1000,1:1000)), f = (k,v) -> iseven(k) - @test filter(f, d) == filter!(f, copy(d)) == - invoke(filter!, Tuple{Function,Associative}, f, copy(d)) == - Dict(zip(2:2:1000, 2:2:1000)) -end - -# issue #15077 -struct MyString <: AbstractString - str::String -end -import Base.== - -const global hashoffset = [UInt(190)] - -Base.hash(s::MyString) = hash(s.str) + hashoffset[] -Base.endof(s::MyString) = endof(s.str) -Base.next(s::MyString, v::Int) = next(s.str, v) -Base.isequal(a::MyString, b::MyString) = isequal(a.str, b.str) -==(a::MyString, b::MyString) = (a.str == b.str) - -let badKeys = [ - "FINO_emv5.0","FINO_ema0.1","RATE_ema1.0","NIBPM_ema1.0", - "SAO2_emv5.0","O2FLOW_ema5.0","preop_Neuro/Psych_","gender_", - "FIO2_ema0.1","PEAK_ema5.0","preop_Reproductive_denies","O2FLOW_ema0.1", - "preop_Endocrine_denies","preop_Respiratory_", - "NIBPM_ema0.1","PROPOFOL_MCG/KG/MIN_decay5.0","NIBPD_ema1.0","NIBPS_ema5.0", - "anesthesiaStartTime","NIBPS_ema1.0","RESPRATE_ema1.0","PEAK_ema0.1", - "preop_GU_denies","preop_Cardiovascular_","PIP_ema5.0","preop_ENT_denies", - "preop_Skin_denies","preop_Renal_denies","asaCode_IIIE","N2OFLOW_emv5.0", - "NIBPD_emv5.0", # <--- here is the key that we later can't find - "NIBPM_ema5.0","preop_Respiratory_complete","ETCO2_ema5.0", - "RESPRATE_ema0.1","preop_Functional Status_<2","preop_Renal_symptoms", - "ECGRATE_ema5.0","FIO2_emv5.0","RESPRATE_emv5.0","7wu3ty0a4fs","BVO", - "4UrCWXUsaT" -] - d = Dict{AbstractString,Int}() - for i = 1:length(badKeys) - d[badKeys[i]] = i - end - # Check all keys for missing values - for i = 1:length(badKeys) - @test d[badKeys[i]] == i - end - - # Walk through all possible hash values (mod size of hash table) - for offset = 0:1023 - d2 = Dict{MyString,Int}() - hashoffset[] = offset - for i = 1:length(badKeys) - d2[MyString(badKeys[i])] = i - end - # Check all keys for missing values - for i = 1:length(badKeys) - @test d2[MyString(badKeys[i])] == i - end - end -end - -struct MyInt <: Integer - val::UInt -end - -Base.hash(v::MyInt) = v.val + hashoffset[] -Base.endof(v::MyInt) = endof(v.val) -Base.next(v::MyInt, i::Int) = next(v.val, i) -Base.isequal(a::MyInt, b::MyInt) = isequal(a.val, b.val) -==(a::MyInt, b::MyInt) = (a.val == b.val) - -let badKeys = UInt16[0xb800,0xa501,0xcdff,0x6303,0xe40a,0xcf0e,0xf3df,0xae99,0x9913,0x741c, - 0xd01f,0xc822,0x9723,0xb7a0,0xea25,0x7423,0x6029,0x202a,0x822b,0x492c, - 0xd02c,0x862d,0x8f34,0xe529,0xf938,0x4f39,0xd03a,0x473b,0x1e3b,0x1d3a, - 0xcc39,0x7339,0xcf40,0x8740,0x813d,0xe640,0xc443,0x6344,0x3744,0x2c3d, - 0x8c48,0xdf49,0x5743] - # Walk through all possible hash values (mod size of hash table) - for offset = 0:1023 - d2 = Dict{MyInt, Int}() - hashoffset[] = offset - for i = 1:length(badKeys) - d2[MyInt(badKeys[i])] = i - end - # Check all keys for missing values - for i = 1:length(badKeys) - @test d2[MyInt(badKeys[i])] == i - end - end -end - -# #18213 -Dict(1 => rand(2,3), 'c' => "asdf") # just make sure this does not trigger a deprecation - -@testset "WeakKeyDict" begin - A = [1] - B = [2] - C = [3] - local x = 0 - local y = 0 - local z = 0 - finalizer(A, a->(x+=1)) - finalizer(B, b->(y+=1)) - finalizer(C, c->(z+=1)) - - # construction - wkd = WeakKeyDict() - wkd[A] = 2 - wkd[B] = 3 - wkd[C] = 4 - dd = convert(Dict{Any,Any},wkd) - @test WeakKeyDict(dd) == wkd - @test isa(WeakKeyDict(dd), WeakKeyDict{Any,Any}) - @test WeakKeyDict(A=>2, B=>3, C=>4) == wkd - @test isa(WeakKeyDict(A=>2, B=>3, C=>4), WeakKeyDict{Array{Int,1},Int}) - @test WeakKeyDict(a=>i+1 for (i,a) in enumerate([A,B,C]) ) == wkd - @test WeakKeyDict([(A,2), (B,3), (C,4)]) == wkd - @test copy(wkd) == wkd - - @test length(wkd) == 3 - @test !isempty(wkd) - res = pop!(wkd, C) - @test res == 4 - @test C ∉ keys(wkd) - @test 4 ∉ values(wkd) - @test length(wkd) == 2 - @test !isempty(wkd) - wkd = filter!( (k,v) -> k != B, wkd) - @test B ∉ keys(wkd) - @test 3 ∉ values(wkd) - @test length(wkd) == 1 - @test !isempty(wkd) - - wkd = empty!(wkd) - @test wkd == similar(wkd) - @test typeof(wkd) == typeof(similar(wkd)) - @test length(wkd) == 0 - @test isempty(wkd) - @test isa(wkd, WeakKeyDict) -end - -@testset "issue #19995, hash of dicts" begin - @test hash(Dict(Dict(1=>2) => 3, Dict(4=>5) => 6)) != hash(Dict(Dict(4=>5) => 3, Dict(1=>2) => 6)) - a = Dict(Dict(3 => 4, 2 => 3) => 2, Dict(1 => 2, 5 => 6) => 1) - b = Dict(Dict(1 => 2, 2 => 3, 5 => 6) => 1, Dict(3 => 4) => 2) - @test hash(a) != hash(b) -end - -mutable struct Foo_15776 - x::Vector{Pair{Tuple{Function, Vararg{Int}}, Int}} -end -@testset "issue #15776, convert for pair" begin - z = [Pair((+,1,5,7), 3), Pair((-,6,5,3,5,8), 1)] - f = Foo_15776(z) - @test f.x[1].first == (+, 1, 5, 7) - @test f.x[1].second == 3 - @test f.x[2].first == (-, 6, 5, 3, 5, 8) - @test f.x[2].second == 1 -end - -@testset "issue #18708 error type for dict constructor" begin - @test_throws UndefVarError Dict(x => y for x in 1:10) -end - -mutable struct Error19179 <: Exception -end - -@testset "issue #19179 throwing error in dict constructor" begin - @test_throws Error19179 Dict(i => throw(Error19179()) for i in 1:10) -end - -# issue #18090 -let - d = Dict(i => i^2 for i in 1:10_000) - z = zip(keys(d), values(d)) - for (pair, tupl) in zip(d, z) - @test pair[1] == tupl[1] && pair[2] == tupl[2] - end -end - -@testset "Dict merge" begin - d1 = Dict("A" => 1, "B" => 2) - d2 = Dict("B" => 3.0, "C" => 4.0) - @test @inferred merge(d1, d2) == Dict("A" => 1, "B" => 3, "C" => 4) - # merge with combiner function - @test @inferred merge(+, d1, d2) == Dict("A" => 1, "B" => 5, "C" => 4) - @test @inferred merge(*, d1, d2) == Dict("A" => 1, "B" => 6, "C" => 4) - @test @inferred merge(-, d1, d2) == Dict("A" => 1, "B" => -1, "C" => 4) -end - -@testset "Dict merge!" begin - d1 = Dict("A" => 1, "B" => 2) - d2 = Dict("B" => 3, "C" => 4) - @inferred merge!(d1, d2) - @test d1 == Dict("A" => 1, "B" => 3, "C" => 4) - # merge! with combiner function - @inferred merge!(+, d1, d2) - @test d1 == Dict("A" => 1, "B" => 6, "C" => 8) - @inferred merge!(*, d1, d2) - @test d1 == Dict("A" => 1, "B" => 18, "C" => 32) - @inferred merge!(-, d1, d2) - @test d1 == Dict("A" => 1, "B" => 15, "C" => 28) -end - -@testset "misc error/io" begin - d = Dict('a'=>1, 'b'=>1, 'c'=> 3) - @test_throws ErrorException 'a' in d - key_str = sprint(show, keys(d)) - @test 'a' ∈ key_str - @test 'b' ∈ key_str - @test 'c' ∈ key_str -end diff --git a/julia-0.6.3/share/julia/test/dimensionful.jl b/julia-0.6.3/share/julia/test/dimensionful.jl deleted file mode 100644 index d55defc..0000000 --- a/julia-0.6.3/share/julia/test/dimensionful.jl +++ /dev/null @@ -1,79 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -# Here we implement a minimal dimensionful type Furlong, which is used -# to test dimensional correctness of various functions in Base. Furlong -# is exported by the TestHelpers module. - -# represents a quantity in furlongs^p -struct Furlong{p,T<:Number} <: Number - val::T - Furlong{p,T}(v::Number) where {p,T} = new(v) - Furlong{p,T}(x::Furlong{p}) where {p,T} = new(x.val) -end -Furlong{T<:Number}(x::T) = Furlong{1,T}(x) -(::Type{T}){p,T}(x::Furlong{p,T}) = x.val -(::Type{Furlong{p}}){p}(v::Number) = Furlong{p,typeof(v)}(v) -Base.convert{T,p,S}(::Type{Furlong{p,T}}, x::Furlong{p,S}) = Furlong{p,T}(convert(T,x.val)) -Base.convert{T}(::Type{Furlong{0,T}}, x::Furlong{0}) = Furlong{0,T}(convert(T, x.val)) -Base.convert{T<:Number}(::Type{T}, x::Furlong{0}) = convert(T, x.val) -Base.convert{T}(::Type{Furlong{0,T}}, x::Number) = Furlong{0,T}(convert(T, x)) - -Base.promote_type{p,T,S}(::Type{Furlong{p,T}}, ::Type{Furlong{p,S}}) = - (Base.@_pure_meta; Furlong{p,promote_type(T,S)}) - -Base.one{p,T}(x::Furlong{p,T}) = one(T) -Base.one{p,T}(::Type{Furlong{p,T}}) = one(T) -Base.zero{p,T}(x::Furlong{p,T}) = Furlong{p,T}(zero(T)) -Base.zero{p,T}(::Type{Furlong{p,T}}) = Furlong{p,T}(zero(T)) -Base.iszero(x::Furlong) = iszero(x.val) - -# convert Furlong exponent p to a canonical form. This -# is not type stable, but it doesn't matter since it is used -# at compile time (in generated functions), not runtime -canonical_p(p) = isinteger(p) ? Int(p) : Rational{Int}(p) - -Base.abs{p}(x::Furlong{p}) = Furlong{p}(abs(x.val)) -@generated Base.abs2{p}(x::Furlong{p}) = :(Furlong{$(canonical_p(2p))}(abs2(x.val))) -@generated Base.inv{p}(x::Furlong{p}) = :(Furlong{$(canonical_p(-p))}(inv(x.val))) -Base.sylvester(a::Furlong,b::Furlong,c::Furlong) = -c / (a + b) - -for f in (:isfinite, :isnan, :isreal) - @eval Base.$f(x::Furlong) = $f(x.val) -end -for f in (:real,:imag,:complex,:middle,:+,:-) - @eval Base.$f{p}(x::Furlong{p}) = Furlong{p}($f(x.val)) -end - -import Base: +, -, ==, !=, <, <=, isless, isequal, *, /, //, div, rem, mod, ^, - middle, hypot -for op in (:+, :-, :middle, :hypot) - @eval function $op{p}(x::Furlong{p}, y::Furlong{p}) - v = $op(x.val, y.val) - Furlong{p}(v) - end -end -for op in (:(==), :(!=), :<, :<=, :isless, :isequal) - @eval $op{p}(x::Furlong{p}, y::Furlong{p}) = $op(x.val, y.val) -end -# generated functions to allow type inference of the value of the exponent: -for (f,op) in ((:_plus,:+),(:_minus,:-),(:_times,:*),(:_div,://)) - @eval @generated function $f{T,p,q}(v::T, ::Furlong{p}, ::Union{Furlong{q},Type{Val{q}}}) - s = $op(p, q) - :(Furlong{$(canonical_p(s)),$T}(v)) - end -end -for (op,eop) in ((:*, :_plus), (:/, :_minus), (://, :_minus), (:div, :_minus)) - @eval begin - $op{p,q}(x::Furlong{p}, y::Furlong{q}) = - $eop($op(x.val, y.val),x,y) - $op{p,S<:Number}(x::Furlong{p}, y::S) = $op(x,Furlong{0,S}(y)) - $op{p,S<:Number}(x::S, y::Furlong{p}) = $op(Furlong{0,S}(x),y) - end -end -for op in (:rem, :mod) - @eval begin - $op{p}(x::Furlong{p}, y::Furlong) = Furlong{p}($op(x.val, y.val)) - $op{p}(x::Furlong{p}, y::Number) = Furlong{p}($op(x.val, y)) - end -end -Base.sqrt(x::Furlong) = _div(sqrt(x.val), x, Val{2}) diff --git a/julia-0.6.3/share/julia/test/distributed.jl b/julia-0.6.3/share/julia/test/distributed.jl deleted file mode 100644 index fc3bac4..0000000 --- a/julia-0.6.3/share/julia/test/distributed.jl +++ /dev/null @@ -1,11 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -# Run the distributed test outside of the main driver since it needs its own -# set of dedicated workers. - -include("testenv.jl") -cmd = `$test_exename $test_exeflags distributed_exec.jl` - -if !success(pipeline(cmd; stdout=STDOUT, stderr=STDERR)) && ccall(:jl_running_on_valgrind,Cint,()) == 0 - error("Distributed test failed, cmd : $cmd") -end diff --git a/julia-0.6.3/share/julia/test/distributed_exec.jl b/julia-0.6.3/share/julia/test/distributed_exec.jl deleted file mode 100644 index ec093d2..0000000 --- a/julia-0.6.3/share/julia/test/distributed_exec.jl +++ /dev/null @@ -1,1749 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -using Base.Test -include("testenv.jl") - -# Test a few "remote" invocations when no workers are present -@test remote(myid)() == 1 -@test pmap(identity, 1:100) == [1:100...] -@test 100 == @parallel (+) for i in 1:100 - 1 - end - -addprocs_with_testenv(4) -@test nprocs() == 5 - -function reuseport_tests() - # Run the test on all processes. - results = asyncmap(procs()) do p - remotecall_fetch(p) do - ports_lower = [] # ports of pids lower than myid() - ports_higher = [] # ports of pids higher than myid() - for w in Base.Distributed.PGRP.workers - w.id == myid() && continue - port = Base._sockname(w.r_stream, true)[2] - if (w.id == 1) - # master connects to workers - push!(ports_higher, port) - elseif w.id < myid() - push!(ports_lower, port) - elseif w.id > myid() - push!(ports_higher, port) - end - end - @assert (length(ports_lower) + length(ports_higher)) == nworkers() - for portset in [ports_lower, ports_higher] - if (length(portset) > 0) && (length(unique(portset)) != 1) - warn("SO_REUSEPORT TESTS FAILED. UNSUPPORTED/OLDER UNIX VERSION?") - return 0 - end - end - return myid() - end - end - - # Ensure that the code has indeed been successfully executed everywhere - @test all(p -> p in results, procs()) -end - -# Test that the client port is reused. SO_REUSEPORT may not be supported on -# all UNIX platforms, Linux kernels prior to 3.9 and older versions of OSX -if is_unix() - # Run reuse client port tests only if SO_REUSEPORT is supported. - s = TCPSocket(delay = false) - is_linux() && Base.Distributed.bind_client_port(s) - if ccall(:jl_tcp_reuseport, Int32, (Ptr{Void},), s.handle) == 0 - # Client reuse port has been disabled in 0.6.2 -# reuseport_tests() - else - info("SO_REUSEPORT is unsupported, skipping reuseport tests.") - end -end - -id_me = myid() -id_other = filter(x -> x != id_me, procs())[rand(1:(nprocs()-1))] - -# Test remote() -let - pool = Base.default_worker_pool() - - count = 0 - count_condition = Condition() - - function remote_wait(c) - @async begin - count += 1 - remote(take!)(c) - count -= 1 - notify(count_condition) - end - yield() - end - - testchannels = [RemoteChannel() for i in 1:nworkers()] - testcount = 0 - @test isready(pool) == true - for c in testchannels - @test count == testcount - remote_wait(c) - testcount += 1 - end - @test count == testcount - @test isready(pool) == false - - for c in testchannels - @test count == testcount - put!(c, "foo") - testcount -= 1 - wait(count_condition) - @test count == testcount - @test isready(pool) == true - end - - @test count == 0 - - for c in testchannels - @test count == testcount - remote_wait(c) - testcount += 1 - end - @test count == testcount - @test isready(pool) == false - - for c in reverse(testchannels) - @test count == testcount - put!(c, "foo") - testcount -= 1 - wait(count_condition) - @test count == testcount - @test isready(pool) == true - end - - @test count == 0 -end - -# Test Futures -function testf(id) - f=Future(id) - @test isready(f) == false - @test isnull(f.v) == true - put!(f, :OK) - @test isready(f) == true - @test isnull(f.v) == false - - @test_throws ErrorException put!(f, :OK) # Cannot put! to a already set future - @test_throws MethodError take!(f) # take! is unsupported on a Future - - @test fetch(f) == :OK -end - -testf(id_me) -testf(id_other) - -# Distributed GC tests for Futures -function test_futures_dgc(id) - f = remotecall(myid, id) - fid = Base.remoteref_id(f) - - # remote value should be deleted after a fetch - @test remotecall_fetch(k->(yield();haskey(Base.Distributed.PGRP.refs, k)), id, fid) == true - @test isnull(f.v) == true - @test fetch(f) == id - @test isnull(f.v) == false - yield(); # flush gc msgs - @test remotecall_fetch(k->(yield();haskey(Base.Distributed.PGRP.refs, k)), id, fid) == false - - - # if unfetched, it should be deleted after a finalize - f = remotecall(myid, id) - fid = Base.remoteref_id(f) - @test remotecall_fetch(k->(yield();haskey(Base.Distributed.PGRP.refs, k)), id, fid) == true - @test isnull(f.v) == true - finalize(f) - yield(); # flush gc msgs - @test remotecall_fetch(k->(yield();haskey(Base.Distributed.PGRP.refs, k)), id, fid) == false -end - -test_futures_dgc(id_me) -test_futures_dgc(id_other) - -# if sent to another worker, it should not be deleted till all references are fetched. -wid1 = workers()[1] -wid2 = workers()[2] -f = remotecall(myid, wid1) -fid = Base.remoteref_id(f) - -fstore = RemoteChannel(wid2) -put!(fstore, f) - -@test fetch(f) == wid1 -@test remotecall_fetch(k->haskey(Base.Distributed.PGRP.refs, k), wid1, fid) == true -remotecall_fetch(r->(fetch(fetch(r)); yield()), wid2, fstore) -sleep(0.5) # to ensure that wid2 gc messages have been executed on wid1 -@test remotecall_fetch(k->haskey(Base.Distributed.PGRP.refs, k), wid1, fid) == false - -# put! should release remote reference since it would have been cached locally -f = Future(wid1) -fid = Base.remoteref_id(f) - -# should not be created remotely till accessed -@test remotecall_fetch(k->haskey(Base.Distributed.PGRP.refs, k), wid1, fid) == false -# create it remotely -isready(f) - -@test remotecall_fetch(k->haskey(Base.Distributed.PGRP.refs, k), wid1, fid) == true -put!(f, :OK) -@test remotecall_fetch(k->haskey(Base.Distributed.PGRP.refs, k), wid1, fid) == false -@test fetch(f) == :OK - -# RemoteException should be thrown on a put! when another process has set the value -f = Future(wid1) -fid = Base.remoteref_id(f) - -fstore = RemoteChannel(wid2) -put!(fstore, f) # send f to wid2 -put!(f, :OK) # set value from master - -@test remotecall_fetch(k->haskey(Base.Distributed.PGRP.refs, k), wid1, fid) == true - -testval = remotecall_fetch(wid2, fstore) do x - try - put!(fetch(x), :OK) - return 0 - catch e - if isa(e, RemoteException) - return 1 - else - return 2 - end - end -end -@test testval == 1 - -# Issue number #25847 -@everywhere function f25847(ref) - fetch(ref) - return true -end - -f = remotecall_wait(identity, id_other, ones(10)) -rrid = Distributed.RRID(f.whence, f.id) -remotecall_fetch(f25847, id_other, f) -@test IntSet([id_me]) == remotecall_fetch(()->Distributed.PGRP.refs[rrid].clientset, id_other) - -remotecall_fetch(f25847, id_other, f) -@test IntSet([id_me]) == remotecall_fetch(()->Distributed.PGRP.refs[rrid].clientset, id_other) - -finalize(f) -yield() # flush gc msgs -@test false == remotecall_fetch(chk_rrid->haskey(Distributed.PGRP.refs, chk_rrid), id_other, rrid) - - -# Distributed GC tests for RemoteChannels -function test_remoteref_dgc(id) - rr = RemoteChannel(id) - put!(rr, :OK) - rrid = Base.remoteref_id(rr) - - # remote value should be deleted after finalizing the ref - @test remotecall_fetch(k->(yield();haskey(Base.Distributed.PGRP.refs, k)), id, rrid) == true - @test fetch(rr) == :OK - @test remotecall_fetch(k->(yield();haskey(Base.Distributed.PGRP.refs, k)), id, rrid) == true - finalize(rr) - yield(); # flush gc msgs - @test remotecall_fetch(k->(yield();haskey(Base.Distributed.PGRP.refs, k)), id, rrid) == false -end -test_remoteref_dgc(id_me) -test_remoteref_dgc(id_other) - -# if sent to another worker, it should not be deleted till the other worker has also finalized. -wid1 = workers()[1] -wid2 = workers()[2] -rr = RemoteChannel(wid1) -rrid = Base.remoteref_id(rr) - -fstore = RemoteChannel(wid2) -put!(fstore, rr) - -@test remotecall_fetch(k->haskey(Base.Distributed.PGRP.refs, k), wid1, rrid) == true -finalize(rr) # finalize locally -yield(); # flush gc msgs -@test remotecall_fetch(k->haskey(Base.Distributed.PGRP.refs, k), wid1, rrid) == true -remotecall_fetch(r->(finalize(take!(r)); yield(); nothing), wid2, fstore) # finalize remotely -sleep(0.5) # to ensure that wid2 messages have been executed on wid1 -@test remotecall_fetch(k->haskey(Base.Distributed.PGRP.refs, k), wid1, rrid) == false - -# Tests for issue #23109 - should not hang. -f = @spawn rand(1,1) -@sync begin - for _ in 1:10 - @async fetch(f) - end -end - -wid1,wid2 = workers()[1:2] -f = @spawnat wid1 rand(1,1) -@sync begin - @async fetch(f) - @async remotecall_fetch(()->fetch(f), wid2) -end - - -@test fetch(@spawnat id_other myid()) == id_other -@test (@fetchfrom id_other myid()) == id_other - -pids=[] -for i in 1:nworkers() - push!(pids, @fetch myid()) -end -@test sort(pids) == sort(workers()) - - -# test getindex on Futures and RemoteChannels -function test_indexing(rr) - a = rand(5,5) - put!(rr, a) - @test rr[2,3] == a[2,3] - @test rr[] == a -end - -test_indexing(Future()) -test_indexing(Future(id_other)) -test_indexing(RemoteChannel()) -test_indexing(RemoteChannel(id_other)) - -dims = (20,20,20) - -if is_linux() - S = SharedArray{Int64,3}(dims) - @test startswith(S.segname, "/jl") - @test !ispath("/dev/shm" * S.segname) - - S = SharedArray{Int64,3}(dims; pids=[id_other]) - @test startswith(S.segname, "/jl") - @test !ispath("/dev/shm" * S.segname) -end - -# TODO : Need a similar test of shmem cleanup for OSX - -##### SharedArray tests - -function check_pids_all(S::SharedArray) - pidtested = falses(size(S)) - for p in procs(S) - idxes_in_p = remotecall_fetch(p, S) do D - parentindexes(D.loc_subarr_1d)[1] - end - @test all(sdata(S)[idxes_in_p] .== p) - pidtested[idxes_in_p] = true - end - @test all(pidtested) -end - -d = Base.shmem_rand(1:100, dims) -a = convert(Array, d) - -partsums = Array{Int}(length(procs(d))) -@sync begin - for (i, p) in enumerate(procs(d)) - @async partsums[i] = remotecall_fetch(p, d) do D - sum(D.loc_subarr_1d) - end - end -end -@test sum(a) == sum(partsums) - -d = Base.shmem_rand(dims) -for p in procs(d) - idxes_in_p = remotecall_fetch(p, d) do D - parentindexes(D.loc_subarr_1d)[1] - end - idxf = first(idxes_in_p) - idxl = last(idxes_in_p) - d[idxf] = Float64(idxf) - rv = remotecall_fetch(p, d,idxf,idxl) do D,idxf,idxl - assert(D[idxf] == Float64(idxf)) - D[idxl] = Float64(idxl) - D[idxl] - end - @test d[idxl] == rv -end - -@test ones(10, 10, 10) == Base.shmem_fill(1.0, (10,10,10)) -@test zeros(Int32, 10, 10, 10) == Base.shmem_fill(0, (10,10,10)) - -d = Base.shmem_rand(dims) -s = Base.shmem_rand(dims) -copy!(s, d) -@test s == d -s = Base.shmem_rand(dims) -copy!(s, sdata(d)) -@test s == d -a = rand(dims) -@test sdata(a) == a - -d = SharedArray{Int}(dims, init = D->fill!(D.loc_subarr_1d, myid())) -for p in procs(d) - idxes_in_p = remotecall_fetch(p, d) do D - parentindexes(D.loc_subarr_1d)[1] - end - idxf = first(idxes_in_p) - idxl = last(idxes_in_p) - @test d[idxf] == p - @test d[idxl] == p -end - -d = @inferred(SharedArray{Float64,2}((2,3))) -@test isa(d[:,2], Vector{Float64}) - -### SharedArrays from a file - -# Mapping an existing file -fn = tempname() -write(fn, 1:30) -sz = (6,5) -Atrue = reshape(1:30, sz) - -S = @inferred(SharedArray{Int,2}(fn, sz)) -@test S == Atrue -@test length(procs(S)) > 1 -@sync begin - for p in procs(S) - @async remotecall_wait(p, S) do D - fill!(D.loc_subarr_1d, myid()) - end - end -end -check_pids_all(S) - -filedata = similar(Atrue) -read!(fn, filedata) -@test filedata == sdata(S) -finalize(S) - -# Error for write-only files -@test_throws ArgumentError SharedArray{Int,2}(fn, sz, mode="w") - -# Error for file doesn't exist, but not allowed to create -@test_throws ArgumentError SharedArray{Int,2}(joinpath(tempdir(),randstring()), sz, mode="r") - -# Creating a new file -fn2 = tempname() -S = SharedArray{Int,2}(fn2, sz, init=D->D[localindexes(D)] = myid()) -@test S == filedata -filedata2 = similar(Atrue) -read!(fn2, filedata2) -@test filedata == filedata2 -finalize(S) - -# Appending to a file -fn3 = tempname() -write(fn3, ones(UInt8, 4)) -S = SharedArray{UInt8}(fn3, sz, 4, mode="a+", init=D->D[localindexes(D)]=0x02) -len = prod(sz)+4 -@test filesize(fn3) == len -filedata = Array{UInt8}(len) -read!(fn3, filedata) -@test all(filedata[1:4] .== 0x01) -@test all(filedata[5:end] .== 0x02) -finalize(S) - -# call gc 3 times to avoid unlink: operation not permitted (EPERM) on Windows -S = nothing -@everywhere gc() -@everywhere gc() -@everywhere gc() -rm(fn); rm(fn2); rm(fn3) - -### Utility functions - -# construct PR #13514 -S = @inferred(SharedArray{Int}((1,2,3))) -@test size(S) == (1,2,3) -@test typeof(S) <: SharedArray{Int} -S = @inferred(SharedArray{Int}(2)) -@test size(S) == (2,) -@test typeof(S) <: SharedArray{Int} -S = @inferred(SharedArray{Int}(1,2)) -@test size(S) == (1,2) -@test typeof(S) <: SharedArray{Int} -S = @inferred(SharedArray{Int}(1,2,3)) -@test size(S) == (1,2,3) -@test typeof(S) <: SharedArray{Int} - -# reshape - -d = Base.shmem_fill(1.0, (10,10,10)) -@test ones(100, 10) == reshape(d,(100,10)) -d = Base.shmem_fill(1.0, (10,10,10)) -@test_throws DimensionMismatch reshape(d,(50,)) - -# rand, randn -d = Base.shmem_rand(dims) -@test size(rand!(d)) == dims -d = Base.shmem_fill(1.0, dims) -@test size(randn!(d)) == dims - -# similar -d = Base.shmem_rand(dims) -@test size(similar(d, Complex128)) == dims -@test size(similar(d, dims)) == dims - -# issue #6362 -d = Base.shmem_rand(dims) -s = copy(sdata(d)) -ds = deepcopy(d) -@test ds == d -pids_d = procs(d) -remotecall_fetch(setindex!, pids_d[findfirst(id->(id != myid()), pids_d)], d, 1.0, 1:10) -@test ds != d -@test s != d -copy!(d, s) -@everywhere setid!(A) = A[localindexes(A)] = myid() -@sync for p in procs(ds) - @async remotecall_wait(setid!, p, ds) -end -@test d == s -@test ds != s -@test first(ds) == first(procs(ds)) -@test last(ds) == last(procs(ds)) - - -# SharedArray as an array -# Since the data in d will depend on the nprocs, just test that these operations work -a = d[1:5] -@test_throws BoundsError d[-1:5] -a = d[1,1,1:3:end] -d[2:4] = 7 -d[5,1:2:4,8] = 19 - -AA = rand(4,2) -A = @inferred(convert(SharedArray, AA)) -B = @inferred(convert(SharedArray, AA')) -@test B*A == ctranspose(AA)*AA - -d=SharedArray{Int64,2}((10,10); init = D->fill!(D.loc_subarr_1d, myid()), pids=[id_me, id_other]) -d2 = map(x->1, d) -@test reduce(+, d2) == 100 - -@test reduce(+, d) == ((50*id_me) + (50*id_other)) -map!(x->1, d, d) -@test reduce(+, d) == 100 - -@test fill!(d, 1) == ones(10, 10) -@test fill!(d, 2.) == fill(2, 10, 10) -@test d[:] == fill(2, 100) -@test d[:,1] == fill(2, 10) -@test d[1,:] == fill(2, 10) - -# Boundary cases where length(S) <= length(pids) -@test 2.0 == remotecall_fetch(D->D[2], id_other, Base.shmem_fill(2.0, 2; pids=[id_me, id_other])) -@test 3.0 == remotecall_fetch(D->D[1], id_other, Base.shmem_fill(3.0, 1; pids=[id_me, id_other])) - -# Shared arrays of singleton immutables -@everywhere struct ShmemFoo end -for T in [Void, ShmemFoo] - s = @inferred(SharedArray{T}(10)) - @test T() === remotecall_fetch(x->x[3], workers()[1], s) -end - -# Issue #14664 -d = SharedArray{Int}(10) -@sync @parallel for i=1:10 - d[i] = i -end - -for (x,i) in enumerate(d) - @test x == i -end - -# complex -sd = SharedArray{Int}(10) -se = SharedArray{Int}(10) -@sync @parallel for i=1:10 - sd[i] = i - se[i] = i -end -sc = convert(SharedArray, complex.(sd,se)) -for (x,i) in enumerate(sc) - @test i == complex(x,x) -end - -# Once finalized accessing remote references and shared arrays should result in exceptions. -function finalize_and_test(r) - finalize(r) - @test_throws ErrorException fetch(r) -end - -for id in [id_me, id_other] - finalize_and_test(Future(id)) - finalize_and_test((r=Future(id); put!(r, 1); r)) - finalize_and_test(RemoteChannel(id)) - finalize_and_test((r=RemoteChannel(id); put!(r, 1); r)) -end - -d = SharedArray{Int}(10) -finalize(d) -@test_throws BoundsError d[1] - -# Issue 22139 -aorig = a1 = SharedArray{Float64}((3, 3)) -a1 = remotecall_fetch(fill!, id_other, a1, 1.0) -@test object_id(aorig) == object_id(a1) -id = a1.id -aorig = nothing -a1 = remotecall_fetch(fill!, id_other, a1, 1.0) -gc(); gc() -a1 = remotecall_fetch(fill!, id_other, a1, 1.0) -@test haskey(Base.sa_refs, id) -finalize(a1) -@test !haskey(Base.sa_refs, id) - -# Test @parallel load balancing - all processors should get either M or M+1 -# iterations out of the loop range for some M. -ids = @parallel((a,b)->[a;b], for i=1:7; myid(); end) -workloads = Int[sum(ids .== i) for i in 2:nprocs()] -@test maximum(workloads) - minimum(workloads) <= 1 - -# @parallel reduction should work even with very short ranges -@test @parallel(+, for i=1:2; i; end) == 3 - -@test_throws ArgumentError sleep(-1) -@test_throws ArgumentError timedwait(()->false, 0.1, pollint=-0.5) - -# specify pids for pmap -@test sort(workers()[1:2]) == sort(unique(pmap(WorkerPool(workers()[1:2]), x->(sleep(0.1);myid()), 1:10))) - -# Testing buffered and unbuffered reads -# This large array should write directly to the socket -a = ones(10^6) -@test a == remotecall_fetch((x)->x, id_other, a) - -# Not a bitstype, should be buffered -s = [randstring() for x in 1:10^5] -@test s == remotecall_fetch((x)->x, id_other, s) - -#large number of small requests -num_small_requests = 10000 -@test fill(id_other, num_small_requests) == [remotecall_fetch(myid, id_other) for i in 1:num_small_requests] - -# test parallel sends of large arrays from multiple tasks to the same remote worker -ntasks = 10 -rr_list = [Channel(1) for x in 1:ntasks] - -for rr in rr_list - let rr=rr - @async try - for i in 1:10 - a = rand(2*10^5) - @test a == remotecall_fetch(x->x, id_other, a) - yield() - end - put!(rr, :OK) - catch - put!(rr, :ERROR) - end - end -end - -@test [fetch(rr) for rr in rr_list] == [:OK for x in 1:ntasks] - -function test_channel(c) - put!(c, 1) - put!(c, "Hello") - put!(c, 5.0) - - @test isready(c) == true - @test fetch(c) == 1 - @test fetch(c) == 1 # Should not have been popped previously - @test take!(c) == 1 - @test take!(c) == "Hello" - @test fetch(c) == 5.0 - @test take!(c) == 5.0 - @test isready(c) == false - close(c) -end - -test_channel(Channel(10)) -test_channel(RemoteChannel(()->Channel(10))) - -c=Channel{Int}(1) -@test_throws MethodError put!(c, "Hello") - -# test channel iterations -function test_iteration(in_c, out_c) - t=@schedule for v in in_c - put!(out_c, v) - end - - isa(in_c, Channel) && @test isopen(in_c) == true - put!(in_c, 1) - @test take!(out_c) == 1 - put!(in_c, "Hello") - close(in_c) - @test take!(out_c) == "Hello" - isa(in_c, Channel) && @test isopen(in_c) == false - @test_throws InvalidStateException put!(in_c, :foo) - yield() - @test istaskdone(t) == true -end - -test_iteration(Channel(10), Channel(10)) -# make sure exceptions propagate when waiting on Tasks -@test_throws CompositeException (@sync (@async error("oops"))) -try - @sync begin - for i in 1:5 - @async error(i) - end - end - error("unexpected") -catch ex - @test typeof(ex) == CompositeException - @test length(ex) == 5 - @test typeof(ex.exceptions[1]) == CapturedException - @test typeof(ex.exceptions[1].ex) == ErrorException - errors = map(x->x.ex.msg, ex.exceptions) - @test collect(1:5) == sort(map(x->parse(Int, x), errors)) -end - -function test_remoteexception_thrown(expr) - try - expr() - error("unexpected") - catch ex - @test typeof(ex) == RemoteException - @test typeof(ex.captured) == CapturedException - @test typeof(ex.captured.ex) == ErrorException - @test ex.captured.ex.msg == "foobar" - end -end - -for id in [id_other, id_me] - test_remoteexception_thrown() do - remotecall_fetch(id) do - throw(ErrorException("foobar")) - end - end - test_remoteexception_thrown() do - remotecall_wait(id) do - throw(ErrorException("foobar")) - end - end - test_remoteexception_thrown() do - wait(remotecall(id) do - throw(ErrorException("foobar")) - end) - end -end - -# make sure the stackframe from the remote error can be serialized -let ex - try - remotecall_fetch(id_other) do - @eval module AModuleLocalToOther - foo() = throw(ErrorException("A.error")) - foo() - end - end - catch ex - end - @test (ex::RemoteException).pid == id_other - @test ((ex.captured::CapturedException).ex::ErrorException).msg == "A.error" - bt = ex.captured.processed_bt::Array{Any,1} - @test length(bt) > 1 - frame, repeated = bt[1]::Tuple{StackFrame, Int} - @test frame.func == :foo - @test isnull(frame.linfo) - @test repeated == 1 -end - -# pmap tests. Needs at least 4 processors dedicated to the below tests. Which we currently have -# since the distributed tests are now spawned as a separate set. - -# Test all combinations of pmap keyword args. -pmap_args = [ - (:distributed, [:default, false]), - (:batch_size, [:default,2]), - (:on_error, [:default, e -> (e.msg == "foobar" ? true : rethrow(e))]), - (:retry_delays, [:default, fill(0.001, 1000)]), - (:retry_check, [:default, (s,e) -> (s,endswith(e.msg,"foobar"))]), - ] - -kwdict = Dict() -function walk_args(i) - if i > length(pmap_args) - kwargs = [] - for (k,v) in kwdict - if v !== :default - push!(kwargs, (k,v)) - end - end - - data = 1:100 - - testw = kwdict[:distributed] === false ? [1] : workers() - - if kwdict[:retry_delays] !== :default - mapf = x -> iseven(myid()) ? error("notfoobar") : (x*2, myid()) - results_test = pmap_res -> begin - results = [x[1] for x in pmap_res] - pids = [x[2] for x in pmap_res] - @test results == [2:2:200...] - for p in testw - if isodd(p) - @test p in pids - else - @test !(p in pids) - end - end - end - elseif kwdict[:on_error] === :default - mapf = x -> (x*2, myid()) - results_test = pmap_res -> begin - results = [x[1] for x in pmap_res] - pids = [x[2] for x in pmap_res] - @test results == [2:2:200...] - for p in testw - @test p in pids - end - end - else - mapf = x -> iseven(x) ? error("foobar") : (x*2, myid()) - results_test = pmap_res -> begin - w = testw - for (idx,x) in enumerate(data) - if iseven(x) - @test pmap_res[idx] == true - else - @test pmap_res[idx][1] == x*2 - @test pmap_res[idx][2] in w - end - end - end - end - - try - results_test(pmap(mapf, data; kwargs...)) - catch e - println("pmap executing with args : ", kwargs) - rethrow(e) - end - - return - end - - kwdict[pmap_args[i][1]] = pmap_args[i][2][1] - walk_args(i+1) - - kwdict[pmap_args[i][1]] = pmap_args[i][2][2] - walk_args(i+1) -end - -# Start test for various kw arg combinations -walk_args(1) - -# Simple test for pmap throws error -error_thrown = false -try - pmap(x -> x==50 ? error("foobar") : x, 1:100) -catch e - @test e.captured.ex.msg == "foobar" - error_thrown = true -end -@test error_thrown - -# Test pmap with a generator type iterator -@test [1:100...] == pmap(x->x, Base.Generator(x->(sleep(0.0001); x), 1:100)) - -# Test pgenerate -n = 10 -as = [rand(4,4) for i in 1:n] -bs = deepcopy(as) -cs = collect(Base.Distributed.pgenerate(x->(sleep(rand()*0.1); svdfact(x)), bs)) -svdas = map(svdfact, as) -for i in 1:n - @test cs[i][:U] ≈ svdas[i][:U] - @test cs[i][:S] ≈ svdas[i][:S] - @test cs[i][:V] ≈ svdas[i][:V] -end - -# Test asyncmap -@test allunique(asyncmap(x->(sleep(1.0);object_id(current_task())), 1:10)) - -# num tasks -@test length(unique(asyncmap(x->(yield();object_id(current_task())), 1:20; ntasks=5))) == 5 - -# default num tasks -@test length(unique(asyncmap(x->(yield();object_id(current_task())), 1:200))) == 100 - -# ntasks as a function -let nt=0 - global nt_func - nt_func() = (v=div(nt, 25); nt+=1; v) # increment number of tasks by 1 for every 25th call. - # nt_func() will be called initally once and then for every - # iteration -end -@test length(unique(asyncmap(x->(yield();object_id(current_task())), 1:200; ntasks=nt_func))) == 7 - -# batch mode tests -let ctr=0 - global next_ctr - next_ctr() = (ctr+=1; ctr) -end -resp = asyncmap(x->(v=next_ctr(); map(_->v, x)), 1:22; ntasks=5, batch_size=5) -@test length(resp) == 22 -@test length(unique(resp)) == 5 - -input = rand(1:1000, 100) -@test asyncmap(x->map(args->identity(args...), x), input; ntasks=5, batch_size=5) == input - -# check whether shape is retained -a=rand(2,2) -b=asyncmap(identity, a) -@test a == b -@test size(a) == size(b) - -# check with an iterator that does not implement size() -c=Channel(32); foreach(i->put!(c,i), 1:10); close(c) -b=asyncmap(identity, c) -@test Int[1:10...] == b -@test size(b) == (10,) - -# check with an iterator that has only implements length() -len_only_iterable = (1,2,3,4,5) -@test Base.iteratorsize(len_only_iterable) == Base.HasLength() -@test asyncmap(identity, len_only_iterable) == map(identity, len_only_iterable) - -# Error conditions -@test_throws ArgumentError asyncmap(identity, 1:10; batch_size=0) -@test_throws ArgumentError asyncmap(identity, 1:10; batch_size="10") -@test_throws ArgumentError asyncmap(identity, 1:10; ntasks="10") - -# asyncmap and pmap with various types. Test for equivalence with map -function testmap_equivalence(f, c...) - x1 = asyncmap(f,c...) - x2 = pmap(f,c...) - x3 = map(f,c...) - - if Base.iteratorsize == Base.HasShape() - @test size(x1) == size(x3) - @test size(x2) == size(x3) - else - @test length(x1) == length(x3) - @test length(x2) == length(x3) - end - - @test eltype(x1) == eltype(x3) - @test eltype(x2) == eltype(x3) - - for (v1,v2) in zip(x1,x3) - @test v1==v2 - end - for (v1,v2) in zip(x2,x3) - @test v1==v2 - end -end - -testmap_equivalence(identity, (1,2,3,4)) -testmap_equivalence(x->x>0?1.0:0.0, sparse(eye(5))) -testmap_equivalence((x,y,z)->x+y+z, 1,2,3) -testmap_equivalence(x->x?false:true, BitArray(10,10)) -testmap_equivalence(x->"foobar", BitArray(10,10)) -testmap_equivalence((x,y,z)->string(x,y,z), BitArray(10), ones(10), "1234567890") - -@test asyncmap(uppercase, "Hello World!") == map(uppercase, "Hello World!") -@test pmap(uppercase, "Hello World!") == map(uppercase, "Hello World!") - - -# Test that the default worker pool cycles through all workers -pmap(_->myid(), 1:nworkers()) # priming run -@test nworkers() == length(unique(pmap(_->myid(), 1:100))) - -# Test same behaviour when executed on a worker -@test nworkers() == length(unique(remotecall_fetch(()->pmap(_->myid(), 1:100), id_other))) - -# Same tests with custom worker pools. -wp = WorkerPool(workers()) -@test nworkers() == length(unique(pmap(wp, _->myid(), 1:100))) -@test nworkers() == length(unique(remotecall_fetch(wp->pmap(wp, _->myid(), 1:100), id_other, wp))) - - -# CachingPool tests -wp = CachingPool(workers()) -@test [1:100...] == pmap(wp, x->x, 1:100) - -clear!(wp) -@test length(wp.map_obj2ref) == 0 - -# The below block of tests are usually run only on local development systems, since: -# - tests which print errors -# - addprocs tests are memory intensive -# - ssh addprocs requires sshd to be running locally with passwordless login enabled. -# The test block is enabled by defining env JULIA_TESTFULL=1 - -DoFullTest = Bool(parse(Int,(get(ENV, "JULIA_TESTFULL", "0")))) - -if DoFullTest - println("Testing exception printing on remote worker from a `remote_do` call") - println("Please ensure the remote error and backtrace is displayed on screen") - - remote_do(id_other) do - throw(ErrorException("TESTING EXCEPTION ON REMOTE DO. PLEASE IGNORE")) - end - sleep(0.5) # Give some time for the above error to be printed - - println("\n\nThe following 'invalid connection credentials' error messages are to be ignored.") - all_w = workers() - # Test sending fake data to workers. The worker processes will print an - # error message but should not terminate. - for w in Base.Distributed.PGRP.workers - if isa(w, Base.Distributed.Worker) - s = connect(get(w.config.host), get(w.config.port)) - write(s, randstring(32)) - end - end - @test workers() == all_w - @test all([p == remotecall_fetch(myid, p) for p in all_w]) - -if is_unix() # aka have ssh - function test_n_remove_pids(new_pids) - for p in new_pids - w_in_remote = sort(remotecall_fetch(workers, p)) - try - @test intersect(new_pids, w_in_remote) == new_pids - catch e - print("p : $p\n") - print("newpids : $new_pids\n") - print("w_in_remote : $w_in_remote\n") - print("intersect : $(intersect(new_pids, w_in_remote))\n\n\n") - rethrow(e) - end - end - - remotecall_fetch(rmprocs, 1, new_pids) - end - - print("\n\nTesting SSHManager. A minimum of 4GB of RAM is recommended.\n") - print("Please ensure: \n") - print("1) sshd is running locally with passwordless login enabled.\n") - print("2) Env variable USER is defined and is the ssh user.\n") - print("3) Port 9300 is not in use.\n") - - sshflags = `-o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no -o LogLevel=ERROR ` - #Issue #9951 - hosts=[] - localhost_aliases = ["localhost", string(getipaddr()), "127.0.0.1"] - num_workers = parse(Int,(get(ENV, "JULIA_ADDPROCS_NUM", "9"))) - - for i in 1:(num_workers/length(localhost_aliases)) - append!(hosts, localhost_aliases) - end - - print("\nTesting SSH addprocs with $(length(hosts)) workers...\n") - new_pids = addprocs_with_testenv(hosts; sshflags=sshflags) - @test length(new_pids) == length(hosts) - test_n_remove_pids(new_pids) - - print("\nMixed ssh addprocs with :auto\n") - new_pids = addprocs_with_testenv(["localhost", ("127.0.0.1", :auto), "localhost"]; sshflags=sshflags) - @test length(new_pids) == (2 + Sys.CPU_CORES) - test_n_remove_pids(new_pids) - - print("\nMixed ssh addprocs with numeric counts\n") - new_pids = addprocs_with_testenv([("localhost", 2), ("127.0.0.1", 2), "localhost"]; sshflags=sshflags) - @test length(new_pids) == 5 - test_n_remove_pids(new_pids) - - print("\nssh addprocs with tunnel\n") - new_pids = addprocs_with_testenv([("localhost", num_workers)]; tunnel=true, sshflags=sshflags) - @test length(new_pids) == num_workers - test_n_remove_pids(new_pids) - - print("\nAll supported formats for hostname\n") - h1 = "localhost" - user = ENV["USER"] - h2 = "$user@$h1" - h3 = "$h2:22" - h4 = "$h3 $(string(getipaddr()))" - h5 = "$h4:9300" - - new_pids = addprocs_with_testenv([h1, h2, h3, h4, h5]; sshflags=sshflags) - @test length(new_pids) == 5 - test_n_remove_pids(new_pids) - - print("\nkeyword arg exename\n") - for exename in [`$(joinpath(JULIA_HOME, Base.julia_exename()))`, "$(joinpath(JULIA_HOME, Base.julia_exename()))"] - for addp_func in [()->addprocs_with_testenv(["localhost"]; exename=exename, exeflags=test_exeflags, sshflags=sshflags), - ()->addprocs_with_testenv(1; exename=exename, exeflags=test_exeflags)] - - new_pids = addp_func() - @test length(new_pids) == 1 - test_n_remove_pids(new_pids) - end - end - -end # unix-only -end # full-test - -let t = @task 42 - schedule(t, ErrorException(""), error=true) - @test_throws ErrorException wait(t) -end - -# issue #8207 -let A = Any[] - @parallel (+) for i in (push!(A,1); 1:2) - i - end - @test length(A) == 1 -end - -# issue #13168 -function f13168(n) - val = 0 - for i=1:n val+=sum(rand(n,n)^2) end - val -end -let t = schedule(@task f13168(100)) - @test t.state == :queued - @test_throws ErrorException schedule(t) - yield() - @test t.state == :done - @test_throws ErrorException schedule(t) - @test isa(wait(t),Float64) -end - -# issue #13122 -@test remotecall_fetch(identity, workers()[1], C_NULL) === C_NULL - -# issue #11062 -function t11062() - @async v11062 = 1 - v11062 = 2 -end - -@test t11062() == 2 - -# issue #15406 -v15406 = remotecall_wait(() -> 1, id_other) -fetch(v15406) -remotecall_wait(fetch, id_other, v15406) - -# Test various forms of remotecall* invocations - -@everywhere f_args(v1, v2=0; kw1=0, kw2=0) = v1+v2+kw1+kw2 - -function test_f_args(result, args...; kwargs...) - @test fetch(remotecall(args...; kwargs...)) == result - @test fetch(remotecall_wait(args...; kwargs...)) == result - @test remotecall_fetch(args...; kwargs...) == result - - # A visual test - remote_do should NOT print any errors - remote_do(args...; kwargs...) -end - -for tid in [id_other, id_me, Base.default_worker_pool()] - test_f_args(1, f_args, tid, 1) - test_f_args(3, f_args, tid, 1, 2) - test_f_args(5, f_args, tid, 1; kw1=4) - test_f_args(13, f_args, tid, 1; kw1=4, kw2=8) - test_f_args(15, f_args, tid, 1, 2; kw1=4, kw2=8) -end - -# Test remote_do -f=Future(id_me) -remote_do(fut->put!(fut, myid()), id_me, f) -@test fetch(f) == id_me - -f=Future(id_other) -remote_do(fut->put!(fut, myid()), id_other, f) -@test fetch(f) == id_other - -# github PR #14456 -n = DoFullTest ? 6 : 5 -for i = 1:10^n - fetch(@spawnat myid() myid()) -end - -# issue #15451 -@test remotecall_fetch(x->(y->2y)(x)+1, workers()[1], 3) == 7 - -# issue #16091 -mutable struct T16091 end -wid = workers()[1] -@test try - remotecall_fetch(()->T16091, wid) - false -catch ex - ((ex::RemoteException).captured::CapturedException).ex === UndefVarError(:T16091) -end -@test try - remotecall_fetch(identity, wid, T16091) - false -catch ex - ((ex::RemoteException).captured::CapturedException).ex === UndefVarError(:T16091) -end - -f16091a() = 1 -remotecall_fetch(()->eval(:(f16091a() = 2)), wid) -@test remotecall_fetch(f16091a, wid) === 2 -@test remotecall_fetch((myid)->remotecall_fetch(f16091a, myid), wid, myid()) === 1 - -# these will only heisen-fail, since it depends on the gensym counter collisions: -f16091b = () -> 1 -remotecall_fetch(()->eval(:(f16091b = () -> 2)), wid) -@test remotecall_fetch(f16091b, 2) === 1 -# Global anonymous functions are over-written... -@test remotecall_fetch((myid)->remotecall_fetch(f16091b, myid), wid, myid()) === 1 - -# ...while local anonymous functions are by definition, local. -let - f16091c = () -> 1 - @test remotecall_fetch(f16091c, 2) === 1 - @test remotecall_fetch( - myid -> begin - let - f16091c = () -> 2 - remotecall_fetch(f16091c, myid) - end - end, wid, myid()) === 2 -end - -# issue #16451 -rng=RandomDevice() -retval = @parallel (+) for _ in 1:10 - rand(rng) -end -@test retval > 0.0 && retval < 10.0 - -rand(rng) -retval = @parallel (+) for _ in 1:10 - rand(rng) -end -@test retval > 0.0 && retval < 10.0 - -# serialization tests -wrkr1 = workers()[1] -wrkr2 = workers()[end] - -@test remotecall_fetch(p->remotecall_fetch(myid, p), wrkr1, wrkr2) == wrkr2 - -# Send f to wrkr1 and wrkr2. Then try calling f on wrkr2 from wrkr1 -f_myid = ()->myid() -@test wrkr1 == remotecall_fetch(f_myid, wrkr1) -@test wrkr2 == remotecall_fetch(f_myid, wrkr2) -@test wrkr2 == remotecall_fetch((f, p)->remotecall_fetch(f, p), wrkr1, f_myid, wrkr2) - -# Deserialization error recovery test -# locally defined module, but unavailable on workers -module LocalFoo - global foo=1 -end - -let - @test_throws RemoteException remotecall_fetch(()->LocalFoo.foo, 2) - - bad_thunk = ()->NonexistantModule.f() - @test_throws RemoteException remotecall_fetch(bad_thunk, 2) - - # Test that the stream is still usable - @test remotecall_fetch(()->:test,2) == :test - ref = remotecall(bad_thunk, 2) - @test_throws RemoteException fetch(ref) -end - -# Test calling @everywhere from a module not defined on the workers -module LocalBar - bar() = @everywhere new_bar()=myid() -end -LocalBar.bar() -for p in procs() - @test p == remotecall_fetch(new_bar, p) -end - -# Test addprocs enable_threaded_blas parameter - -const get_num_threads = function() # anonymous so it will be serialized when called - blas = BLAS.vendor() - # Wrap in a try to catch unsupported blas versions - try - if blas == :openblas - return ccall((:openblas_get_num_threads, Base.libblas_name), Cint, ()) - elseif blas == :openblas64 - return ccall((:openblas_get_num_threads64_, Base.libblas_name), Cint, ()) - elseif blas == :mkl - return ccall((:MKL_Get_Max_Num_Threads, Base.libblas_name), Cint, ()) - end - - # OSX BLAS looks at an environment variable - if is_apple() - return ENV["VECLIB_MAXIMUM_THREADS"] - end - end - - return nothing -end - -function get_remote_num_threads(processes_added) - return [remotecall_fetch(get_num_threads, proc_id) for proc_id in processes_added] -end - -function test_blas_config(pid, expected) - for worker in Base.Distributed.PGRP.workers - if worker.id == pid - @test get(worker.config.enable_threaded_blas) == expected - return - end - end -end - -function test_add_procs_threaded_blas() - if get_num_threads() === nothing - warn("Skipping blas num threads tests due to unsupported blas version") - return - end - master_blas_thread_count = get_num_threads() - - # Test with default enable_threaded_blas false - processes_added = addprocs_with_testenv(2) - for proc_id in processes_added - test_blas_config(proc_id, false) - end - - # Master thread should not have changed - @test get_num_threads() == master_blas_thread_count - - # Threading disabled in children by default - thread_counts_by_process = get_remote_num_threads(processes_added) - for thread_count in thread_counts_by_process - @test thread_count == 1 - end - rmprocs(processes_added) - - processes_added = addprocs_with_testenv(2, enable_threaded_blas=true) - for proc_id in processes_added - test_blas_config(proc_id, true) - end - - @test get_num_threads() == master_blas_thread_count - - # BLAS.set_num_threads(`num`) doesn't cause get_num_threads to return `num` - # depending on the machine, the BLAS version, and BLAS configuration, so - # we need a very lenient test. - thread_counts_by_process = get_remote_num_threads(processes_added) - for thread_count in thread_counts_by_process - @test thread_count >= 1 - end - rmprocs(processes_added) -end -test_add_procs_threaded_blas() - -#19687 -# ensure no race conditions between rmprocs and addprocs -for i in 1:5 - p = addprocs_with_testenv(1)[1] - @spawnat p sleep(5) - rmprocs(p; waitfor=0) -end - -# Test if a wait has been called on rmprocs(...;waitfor=0), further remotecalls -# don't throw errors. -for i in 1:5 - p = addprocs_with_testenv(1)[1] - np = nprocs() - @spawnat p sleep(5) - wait(rmprocs(p; waitfor=0)) - for pid in procs() - @test pid == remotecall_fetch(myid, pid) - end - @test nprocs() == np - 1 -end - -# Test that an exception is thrown if workers are unable to be removed within requested time. -if DoFullTest - pids=addprocs_with_testenv(4); - @test_throws ErrorException rmprocs(pids; waitfor=0.001); - # wait for workers to be removed - while any(x -> (x in procs()), pids) - sleep(0.1) - end -end - -# Test addprocs/rmprocs from master node only -for f in [ ()->addprocs(1; exeflags=test_exeflags), ()->rmprocs(workers()) ] - try - remotecall_fetch(f, id_other) - error("Unexpected") - catch ex - @test isa(ex, RemoteException) - @test ex.captured.ex.msg == "Only process 1 can add and remove workers" - end -end - -# Test the following addprocs error conditions -# - invalid host name - github issue #20372 -# - julia exe exiting with an error -# - timeout reading host:port from worker STDOUT -# - host:port not found in worker STDOUT in the first 1000 lines - -struct ErrorSimulator <: ClusterManager - mode -end - -function Base.launch(manager::ErrorSimulator, params::Dict, launched::Array, c::Condition) - exename = params[:exename] - dir = params[:dir] - - cmd = `$(Base.julia_cmd(exename)) --startup-file=no` - if manager.mode == :timeout - cmd = `$cmd -e "sleep(10)"` - elseif manager.mode == :ntries - cmd = `$cmd -e "[println(x) for x in 1:1001]"` - elseif manager.mode == :exit - cmd = `$cmd -e "exit(-1)"` - else - error("Unknown mode") - end - io, pobj = open(pipeline(detach(setenv(cmd, dir=dir)); stderr=STDERR), "r") - - wconfig = WorkerConfig() - wconfig.process = pobj - wconfig.io = io - push!(launched, wconfig) - notify(c) -end - -testruns = Any[] - -if DoFullTest - append!(testruns, [(()->addprocs_with_testenv(["errorhost20372"]), "Unable to read host:port string from worker. Launch command exited with error?", ())]) -end - -append!(testruns, [ - (()->addprocs_with_testenv(ErrorSimulator(:exit)), "Unable to read host:port string from worker. Launch command exited with error?", ()), - (()->addprocs_with_testenv(ErrorSimulator(:ntries)), "Unexpected output from worker launch command. Host:port string not found.", ()), - (()->addprocs_with_testenv(ErrorSimulator(:timeout)), "Timed out waiting to read host:port string from worker.", ("JULIA_WORKER_TIMEOUT"=>"1",)) -]) - -for (addp_testf, expected_errstr, env) in testruns - try - withenv(env...) do - addp_testf() - end - error("Unexpected") - catch ex - @test isa(ex, CompositeException) - @test ex.exceptions[1].ex.msg == expected_errstr - end -end - - -# Auto serialization of globals from Main. -# bitstypes -global v1 = 1 -@test remotecall_fetch(()->v1, id_other) == v1 -@test remotecall_fetch(()->isdefined(Main, :v1), id_other) -for i in 2:5 - global v1 = i - @test remotecall_fetch(()->v1, id_other) == i -end - -# non-bitstypes -global v2 = zeros(10) -for i in 1:5 - v2[i] = i - @test remotecall_fetch(()->v2, id_other) == v2 -end - -# Different global bindings to the same object -global v3 = ones(10) -global v4 = v3 -@test remotecall_fetch(()->v3, id_other) == remotecall_fetch(()->v4, id_other) -@test remotecall_fetch(()->isdefined(Main, :v3), id_other) -@test remotecall_fetch(()->isdefined(Main, :v4), id_other) - -# Global references to Types and Modules should work if they are locally defined -global v5 = Int -global v6 = Base.Distributed -@test remotecall_fetch(()->v5, id_other) === Int -@test remotecall_fetch(()->v6, id_other) === Base.Distributed - -struct FooStructLocal end -module FooModLocal end -v5 = FooStructLocal -v6 = FooModLocal -@test_throws RemoteException remotecall_fetch(()->v5, id_other) -@test_throws RemoteException remotecall_fetch(()->v6, id_other) - -@everywhere struct FooStructEverywhere end -@everywhere module FooModEverywhere end -v5 = FooStructEverywhere -v6 = FooModEverywhere -@test remotecall_fetch(()->v5, id_other) === FooStructEverywhere -@test remotecall_fetch(()->v6, id_other) === FooModEverywhere - - -# Test that a global is not being repeatedly serialized when -# a) referenced multiple times in the closure -# b) hash value has not changed. - -@everywhere begin - global testsercnt_d = Dict() - mutable struct TestSerCnt - v - end - import Base.hash, Base.== - hash(x::TestSerCnt, h::UInt) = hash(hash(x.v), h) - ==(x1::TestSerCnt, x2::TestSerCnt) = (x1.v == x2.v) - - function Base.serialize(s::AbstractSerializer, t::TestSerCnt) - Base.Serializer.serialize_type(s, TestSerCnt) - serialize(s, t.v) - global testsercnt_d - cnt = get!(testsercnt_d, object_id(t), 0) - testsercnt_d[object_id(t)] = cnt+1 - end - - Base.deserialize(s::AbstractSerializer, ::Type{TestSerCnt}) = TestSerCnt(deserialize(s)) -end - -# hash value of tsc is not changed -global tsc = TestSerCnt(zeros(10)) -for i in 1:5 - remotecall_fetch(()->tsc, id_other) -end -# should have been serialized only once -@test testsercnt_d[object_id(tsc)] == 1 - -# hash values are changed -n=5 -testsercnt_d[object_id(tsc)] = 0 -for i in 1:n - tsc.v[i] = i - remotecall_fetch(()->tsc, id_other) -end -# should have been serialized as many times as the loop -@test testsercnt_d[object_id(tsc)] == n - -# Multiple references in a closure should be serialized only once. -global mrefs = TestSerCnt(ones(10)) -@test remotecall_fetch(()->(mrefs.v, 2*mrefs.v, 3*mrefs.v), id_other) == (ones(10), 2*ones(10), 3*ones(10)) -@test testsercnt_d[object_id(mrefs)] == 1 - - -# nested anon functions -global f1 = x->x -global f2 = x->f1(x) -v = rand() -@test remotecall_fetch(f2, id_other, v) == v -@test remotecall_fetch(x->f2(x), id_other, v) == v - -# consts -const c1 = ones(10) -@test remotecall_fetch(()->c1, id_other) == c1 -@test remotecall_fetch(()->isconst(Main, :c1), id_other) - -# Test same calls with local vars -function wrapped_var_ser_tests() - # bitstypes - local lv1 = 1 - @test remotecall_fetch(()->lv1, id_other) == lv1 - @test !remotecall_fetch(()->isdefined(Main, :lv1), id_other) - for i in 2:5 - lv1 = i - @test remotecall_fetch(()->lv1, id_other) == i - end - - # non-bitstypes - local lv2 = zeros(10) - for i in 1:5 - lv2[i] = i - @test remotecall_fetch(()->lv2, id_other) == lv2 - end - - # nested anon functions - local lf1 = x->x - local lf2 = x->lf1(x) - v = rand() - @test remotecall_fetch(lf2, id_other, v) == v - @test remotecall_fetch(x->lf2(x), id_other, v) == v -end - -wrapped_var_ser_tests() - -# Test internal data structures being cleaned up upon gc. -global ids_cleanup = ones(6) -global ids_func = ()->ids_cleanup - -clust_ser = (Base.Distributed.worker_from_id(id_other)).w_serializer -@test remotecall_fetch(ids_func, id_other) == ids_cleanup - -@test haskey(clust_ser.glbs_sent, object_id(ids_cleanup)) -finalize(ids_cleanup) -@test !haskey(clust_ser.glbs_sent, object_id(ids_cleanup)) - -# TODO Add test for cleanup from `clust_ser.glbs_in_tnobj` - -# reported github issues - Mostly tests with globals and various distributed macros -#2669, #5390 -v2669=10 -@test fetch(@spawn (1+v2669)) == 11 - -#12367 -refs = [] -if true - n = 10 - for p in procs() - push!(refs, @spawnat p begin - @sync for i in 1:n - nothing - end - end) - end -end -foreach(wait, refs) - -#14399 -s = convert(SharedArray, [1,2,3,4]) -@test pmap(i->length(s), 1:2) == [4,4] - -#6760 -if true - a = 2 - x = @parallel (vcat) for k=1:2 - sin(a) - end -end -@test x == map(_->sin(2), 1:2) - -let thrown = false - try - remotecall_fetch(sqrt, 2, -1) - catch e - thrown = true - b = IOBuffer() - showerror(b, e) - @test contains(String(take!(b)), "sqrt will only return") - end - @test thrown -end - -#19463 -function foo19463() - w1 = workers()[1] - w2 = workers()[2] - w3 = workers()[3] - - b1 = () -> 1 - b2 = () -> fetch(@spawnat w1 b1()) + 1 - b3 = () -> fetch(@spawnat w2 b2()) + 1 - b4 = () -> fetch(@spawnat w3 b3()) + 1 - b4() -end -@test foo19463() == 4 - -# Testing clear! -function setup_syms(n, pids) - syms = [] - for i in 1:n - symstr = string("clrtest", randstring()) - sym = Symbol(symstr) - eval(:(global $sym = rand())) - for p in pids - eval(:(@test $sym == remotecall_fetch(()->$sym, $p))) - eval(:(@test remotecall_fetch(isdefined, $p, Symbol($symstr)))) - end - push!(syms, sym) - end - syms -end - -function test_clear(syms, pids) - for p in pids - for sym in syms - remote_val = remotecall_fetch(()->getfield(Main, sym), p) - @test remote_val === nothing - @test remote_val != getfield(Main, sym) - end - end -end - -syms = setup_syms(1, [id_other]) -clear!(syms[1], id_other) -test_clear(syms, [id_other]) - -syms = setup_syms(1, workers()) -clear!(syms[1], workers()) -test_clear(syms, workers()) - -syms = setup_syms(3, [id_other]) -clear!(syms, id_other) -test_clear(syms, [id_other]) - -syms = setup_syms(3, workers()) -clear!(syms, workers()) -test_clear(syms, workers()) - -# Test partial recovery from a deserialization error in CapturedException -try - expr = quote - mutable struct DontExistOn1 - x - end - throw(BoundsError(DontExistOn1(1), 1)) - end - - remotecall_fetch(()->eval(expr), id_other) - error("unexpected") -catch ex - @test isa(ex.captured.ex.exceptions[1].ex, ErrorException) - @test contains(ex.captured.ex.exceptions[1].ex.msg, "BoundsError") - @test ex.captured.ex.exceptions[2].ex == UndefVarError(:DontExistOn1) -end - -@test let - # creates a new worker in the same folder and tries to include file - tmp_file, temp_file_stream = mktemp() - close(temp_file_stream) - tmp_file = relpath(tmp_file) - try - proc = addprocs_with_testenv(1) - include(tmp_file) - remotecall_fetch(include, proc[1], tmp_file) - rmprocs(proc) - rm(tmp_file) - return true - catch e - println(e) - rm(tmp_file, force=true) - return false - end -end == true - -@test let - # creates a new worker in the different folder and tries to include file - tmp_file, temp_file_stream = mktemp() - close(temp_file_stream) - tmp_file = relpath(tmp_file) - tmp_dir = relpath(mktempdir()) - try - proc = addprocs_with_testenv(1, dir=tmp_dir) - include(tmp_file) - remotecall_fetch(include, proc[1], tmp_file) - rmprocs(proc) - rm(tmp_dir) - rm(tmp_file) - return true - catch e - println(e) - rm(tmp_dir, force=true) - rm(tmp_file, force=true) - return false - end -end == true - -# Run topology tests last after removing all workers, since a given -# cluster at any time only supports a single topology. -rmprocs(workers()) -include("topology.jl") diff --git a/julia-0.6.3/share/julia/test/docs.jl b/julia-0.6.3/share/julia/test/docs.jl deleted file mode 100644 index dcb91d9..0000000 --- a/julia-0.6.3/share/julia/test/docs.jl +++ /dev/null @@ -1,1019 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -import Base.Docs: meta, @var, DocStr, parsedoc - -# For curmod_* -include("testenv.jl") - -# Test helpers. -function docstrings_equal(d1, d2) - io1 = IOBuffer() - io2 = IOBuffer() - show(io1, MIME"text/markdown"(), d1) - show(io2, MIME"text/markdown"(), d2) - String(take!(io1)) == String(take!(io2)) -end -docstrings_equal(d1::DocStr, d2) = docstrings_equal(parsedoc(d1), d2) - -function docstring_startswith(d1, d2) - io1 = IOBuffer() - io2 = IOBuffer() - show(io1, MIME"text/markdown"(), d1) - show(io2, MIME"text/markdown"(), d2) - startswith(String(take!(io1)), String(take!(io2))) -end -docstring_startswith(d1::DocStr, d2) = docstring_startswith(parsedoc(d1), d2) - -@doc "Doc abstract type" -> -abstract type C74685{T,N} <: AbstractArray{T,N} end -@test stringmime("text/plain", Docs.doc(C74685))=="Doc abstract type\n" - -macro macro_doctest() end -@doc "Helps test if macros can be documented with `@doc \"...\" -> @...`." -> -:@macro_doctest - -@test (@doc @macro_doctest) !== nothing - -# test that random stuff interpolated into docstrings doesn't break search or other methods here -doc""" -break me: - - code - -$:asymbol # a symbol -$1 # a number -$string # a function -$$latex literal$$ -### header! -""" -function break_me_docs end - -# issue #11548 - -module ModuleMacroDoc -macro m() end -end - -@doc "I am a module" ModuleMacroDoc -@doc "I am a macro" :@ModuleMacroDoc.m - -@test docstrings_equal(@doc(ModuleMacroDoc), doc"I am a module") -@test docstrings_equal(@doc(ModuleMacroDoc.@m), doc"I am a macro") - -# General tests for docstrings. - -const LINE_NUMBER = @__LINE__+1 -"DocsTest" -module DocsTest - -"f-1" -function f(x) - x -end - -"f-2" -f(x, y) = x + y - -"s-1" -@generated function s(x) - :(x) -end - -"s-2" -@generated s(x, y) = :(x + y) - -"g" -function g end - -"AT" -abstract type AT end - -"BT" -primitive type BT 8 end - -"BT2" -primitive type BT2 <: Integer 8 end - -"T" -mutable struct T <: AT - "T.x" - x - "T.y" - y :: Int -end - -"IT" -struct IT - "IT.x" - x :: Int - "IT.y" - y -end - -"TA" -const TA = Union{T, IT} - -"@mac()" -macro mac() end - -"@mac(x)" -macro mac(x) end - -"@mac(x::Int, y::Expr, z = 0)" -macro mac(x::Int, y::Expr, z = 0) end - -":@mac" -:@mac - -"G" -G = :G - -"K" -const K = :K - -# Adding docstrings to methods after definition. - -t(x::AbstractString) = x -t(x::Int, y) = y -t{S <: Integer}(x::S) = x - -"t-1" -t(::AbstractString) -"t-2" -t(::Int, ::Any) -"t-3" -t{S <: Integer}(::S) - -"FieldDocs" -mutable struct FieldDocs - "one" - one - doc"two" - two - three -end - -"h/0-3" -h(x = 1, y = 2, z = 3) = x + y + z - -# Issue #12700. -module Inner - macro m() end -end -import .Inner.@m - -"Inner.@m" -:@m - -mutable struct Foo - x -end - -# value with no docs -const val = Foo(1.0) - -"doc multiple expressions" -function multidoc end, -function multidoc! end - -"returntype-1" -returntype(x::Float64)::Float64 = x - -"returntype-2" -function returntype(x::Int)::Int - x -end - -end - -let md = meta(DocsTest)[@var(DocsTest)] - @test docstrings_equal(md.docs[Union{}], doc"DocsTest") - # Check that plain docstrings store a module reference. - # https://github.com/JuliaLang/julia/pull/13017#issuecomment-138618663 - @test md.docs[Union{}].data[:module] == DocsTest - @test md.docs[Union{}].data[:linenumber] == LINE_NUMBER -end - -let f = @var(DocsTest.f) - md = meta(DocsTest)[f] - @test docstrings_equal(md.docs[Tuple{Any}], doc"f-1") - @test docstrings_equal(md.docs[Tuple{Any,Any}], doc"f-2") - @test md.docs[Tuple{Any}].data[:binding] === f - @test md.docs[Tuple{Any}].data[:typesig] === Tuple{Any} - @test md.docs[Tuple{Any,Any}].data[:binding] === f - @test md.docs[Tuple{Any,Any}].data[:typesig] === Tuple{Any,Any} -end - -let s = @var(DocsTest.s) - md = meta(DocsTest)[s] - @test docstrings_equal(md.docs[Tuple{Any,}], doc"s-1") - @test docstrings_equal(md.docs[Tuple{Any,Any}], doc"s-2") -end - -let g = @var(DocsTest.g) - md = meta(DocsTest)[g] - @test docstrings_equal(md.docs[Union{}], doc"g") -end - -let h = @var(DocsTest.h) - md = meta(DocsTest)[h] - sig = Union{Tuple{}, Tuple{Any}, Tuple{Any, Any}, Tuple{Any, Any, Any}} - @test docstrings_equal(md.docs[sig], doc"h/0-3") -end - -let AT = @var(DocsTest.AT) - md = meta(DocsTest)[AT] - @test docstrings_equal(md.docs[Union{}], doc"AT") -end - -let BT = @var(DocsTest.BT) - md = meta(DocsTest)[BT] - @test docstrings_equal(md.docs[Union{}], doc"BT") -end - -let BT2 = @var(DocsTest.BT2) - md = meta(DocsTest)[BT2] - @test docstrings_equal(md.docs[Union{}], doc"BT2") -end - -let T = @var(DocsTest.T) - md = meta(DocsTest)[T] - d = md.docs[Union{}] - @test docstrings_equal(d, doc"T") - @test d.data[:fields][:x] == "T.x" - @test d.data[:fields][:y] == "T.y" -end - -let IT = @var(DocsTest.IT) - md = meta(DocsTest)[IT] - d = md.docs[Union{}] - @test docstrings_equal(d, doc"IT") - @test d.data[:fields][:x] == "IT.x" - @test d.data[:fields][:y] == "IT.y" -end - -let rt = @var(DocsTest.returntype) - md = meta(DocsTest)[rt] - @test md.order == [Tuple{Float64}, Tuple{Int}] -end - -@test docstrings_equal(@doc(DocsTest.TA), doc"TA") - -@test docstrings_equal(@doc(DocsTest.@mac), doc"@mac()") -@test docstrings_equal(@doc(DocsTest.@mac()), doc"@mac()") -@test docstrings_equal(@doc(DocsTest.@mac(x)), doc"@mac(x)") -@test docstrings_equal(@doc(DocsTest.@mac(x::Int, y::Expr)), doc"@mac(x::Int, y::Expr, z = 0)") -@test docstrings_equal(@doc(DocsTest.@mac(x::Int, y::Expr, z)), doc"@mac(x::Int, y::Expr, z = 0)") -let m = doc""" - @mac() - - @mac(x) - - @mac(x::Int, y::Expr, z = 0) - - :@mac - """ - @test docstrings_equal(@doc(:@DocsTest.mac), m) - @test docstrings_equal(@doc(:(DocsTest.@mac)), m) -end - -@test docstrings_equal(@doc(DocsTest.G), doc"G") -@test docstrings_equal(@doc(DocsTest.K), doc"K") - -let d1 = @doc(DocsTest.t(::AbstractString)), - d2 = doc"t-1" - @test docstrings_equal(d1,d2) -end - -let d1 = @doc(DocsTest.t(::AbstractString)), - d2 = doc"t-1" - @test docstrings_equal(d1,d2) -end - -let d1 = @doc(DocsTest.t(::Int, ::Any)), - d2 = doc"t-2" - @test docstrings_equal(d1,d2) -end - -let d1 = @doc(DocsTest.t{S <: Integer}(::S)), - d2 = doc"t-3" - @test docstrings_equal(d1,d2) -end - -let fields = meta(DocsTest)[@var(DocsTest.FieldDocs)].docs[Union{}].data[:fields] - @test haskey(fields, :one) && fields[:one] == "one" - @test haskey(fields, :two) && fields[:two] == doc"two" -end - -let a = @doc(DocsTest.multidoc), - b = @doc(DocsTest.multidoc!) - @test docstrings_equal(a, b) -end - -"BareModule" -baremodule BareModule - -"f/1" -f(x) = x - -"g/1" -function g(x) end - -"h" -function h end - -"@m" -macro m() end - -"C" -const C = 1 - -"A" -abstract type A end - -"T" -mutable struct T - "x" - x - "y" - y -end - -end - -@test docstrings_equal(@doc(BareModule), doc"BareModule") -@test docstrings_equal(@doc(BareModule.f), doc"f/1") -@test docstrings_equal(@doc(BareModule.g), doc"g/1") -@test docstrings_equal(@doc(BareModule.@m), doc"@m") -@test docstrings_equal(@doc(BareModule.C), doc"C") -@test docstrings_equal(@doc(BareModule.A), doc"A") -@test docstrings_equal(@doc(BareModule.T), doc"T") - -@test_throws ErrorException @doc("...", "error") -@test_throws ErrorException @doc("...", @time 0) - -# test that when no docs exist, they fallback to -# the docs for the typeof(value) -let d1 = @doc(DocsTest.val) - @test d1 !== nothing -end - -# DocRefs - -module DocRefTests - -"..." -function f end, function f! end, @enum E a b c - -@doc Docs.@ref(f) g() = () -@doc Docs.@ref(f!) g!() = () - -end - -let d_1 = @doc(DocRefTests.f).meta[:results][1], - d_2 = @doc(DocRefTests.f!).meta[:results][1], - d_3 = @doc(DocRefTests.g).meta[:results][1], - d_4 = @doc(DocRefTests.g!).meta[:results][1], - d_5 = @doc(DocRefTests.E).meta[:results][1] - @test d_1 === d_2 === d_3 === d_4 === d_5 -end - -# Document specific expressions generated by macro calls. -module MacroGenerated - -import Base.@__doc__ - -macro example_1(f) - quote - $(f)() = 0 - @__doc__ $(f)(x) = x - $(f)(x, y) = x + y - end |> esc -end - -"f" -@example_1 f - -@example_1 _f - -macro example_2(f) - quote - $(f)() = 0 - @__doc__ $(f)(x) = x - @__doc__ $(f)(x, y) = x + y - end |> esc -end - -"g" -@example_2 g - -@example_2 _g - -end - -let md = meta(MacroGenerated)[@var(MacroGenerated.f)] - @test md.order == [Tuple{Any}] - @test docstrings_equal(md.docs[Tuple{Any}], doc"f") -end - -@test isdefined(MacroGenerated, :_f) - -let md = meta(MacroGenerated)[@var(MacroGenerated.g)] - @test md.order == [Tuple{Any}, Tuple{Any, Any}] - @test docstrings_equal(md.docs[Tuple{Any}], doc"g") - @test docstrings_equal(md.docs[Tuple{Any, Any}], doc"g") -end - -@test isdefined(MacroGenerated, :_g) - -module DocVars - -struct __FIELDS__ end - -function Docs.formatdoc(buffer, docstr, ::Type{__FIELDS__}) - fields = get(docstr.data, :fields, Dict()) - if !isempty(fields) - println(buffer, "# Fields") - for (k, v) in sort!(collect(fields)) - println(buffer, "`", k, "` -- ", v, "\n") - end - end -end - -""" - $T - -$__FIELDS__ -""" -mutable struct T - "x" - x - "y" - y - z -end - -""" - $S - -$__FIELDS__ -""" -mutable struct S - x - y - z -end - -end - -let T = meta(DocVars)[@var(DocVars.T)], - S = meta(DocVars)[@var(DocVars.S)], - Tname = Markdown.parse("```\n$(curmod_prefix)DocVars.T\n```"), - Sname = Markdown.parse("```\n$(curmod_prefix)DocVars.S\n```") - # Splicing the expression directly doesn't work - @test docstrings_equal(T.docs[Union{}], - doc""" - $Tname - - # Fields - - `x` -- x - - `y` -- y - """ - ) - @test docstrings_equal(S.docs[Union{}], - doc""" - $Sname - - """ - ) -end - -# Issues. -# ======= - -# Issue #16359. Error message for invalid doc syntax. - -for each in [ # valid syntax - :(f()), - :(f(x)), - :(f(x::Int)), - :(f(x...)), - :(f(x = 1)), - :(f(; x = 1)) - ] - @test Meta.isexpr(Docs.docm("...", each), :block) -end -for each in [ # invalid syntax - :(f("...")), - :(f(1, 2)), - :(f(() -> ())) - ] - result = Docs.docm("...", each) - @test Meta.isexpr(result, :call) - @test result.args[1] === error -end - -# Issue #15424. Non-markdown docstrings. - -module I15424 - -struct LazyHelp - text -end - -function Base.show(io::IO, ::MIME"text/plain", h::LazyHelp) - print(io, h.text) -end - -Base.show(io::IO, h::LazyHelp) = show(io, "text/plain", h) - -function Base.Docs.catdoc(hs::LazyHelp...) - Base.Docs.Text() do io - for h in hs - show(io, MIME"text/plain"(), h) - end - end -end - -Docs.docsearch(haystack::LazyHelp, needle) = Docs.docsearch(haystack.text, needle) - -@doc LazyHelp("LazyHelp\n") LazyHelp -@doc LazyHelp("LazyHelp(text)\n") LazyHelp(text) - -end - -let d = @doc(I15424.LazyHelp) - @test stringmime("text/plain", d) == "LazyHelp\nLazyHelp(text)\n" -end - -# Issue #13385. -@test @doc(I) !== nothing - -# Issue #12700. -@test docstrings_equal(@doc(DocsTest.@m), doc"Inner.@m") - -# issue 11993 -# Check if we are documenting the expansion of the macro -macro m1_11993() -end - -macro m2_11993() - Symbol("@m1_11993") -end - -@doc "This should document @m1... since its the result of expansion" @m2_11993 -@test (@doc @m1_11993) !== nothing -let d = (@doc :@m2_11993), - macro_doc = Markdown.parse("`$(curmod_prefix)@m2_11993` is a macro.") - @test docstring_startswith(d, doc""" - No documentation found. - - $macro_doc""") -end - -@doc "Now @m2... should be documented" :@m2_11993 -@test (@doc @m2_11993) !== nothing - -"Document inline function" -@inline f1_11993() = nothing - -@test (@doc f1_11993) !== nothing - -f1_11993() - -@doc "Document inline function with old syntax" -> -@inline f2_11993() = nothing - -@test (@doc f2_11993) !== nothing - -f2_11993() - -# issue #11798 - -module I11798 - -"read" -read(x) = x - -end - -let md = Base.Docs.meta(I11798)[@var(I11798.read)], - d1 = md.docs[md.order[1]], - d2 = doc"read" - @test docstrings_equal(d1,d2) -end - -module I12515 - -struct EmptyType{T} end - -"A new method" -Base.collect{T}(::Type{EmptyType{T}}) = "borked" - -end - -let fd = meta(I12515)[@var(Base.collect)] - @test fd.order[1] == (Union{Tuple{Type{I12515.EmptyType{T}}}, Tuple{T}} where T) -end - -# PR #12593 - -"$(1 + 1)" -f12593_1() = 1 - -"$(1 + 1) 2" -f12593_2() = 1 - -@test (@doc f12593_1) !== nothing -@test (@doc f12593_2) !== nothing - -# @test Docs.doc(svdvals, Tuple{Vector{Float64}}) === nothing -@test Docs.doc(svdvals, Tuple{Float64}) !== nothing - -# crude test to make sure we sort docstring output by method specificity -@test !docstrings_equal(Docs.doc(getindex, Tuple{Dict{Int,Int},Int}), - Docs.doc(getindex, Tuple{Type{Int64},Int})) - -# test that macro documentation works -@test (Docs.@repl :@assert) !== nothing - -@test (Docs.@repl 0) !== nothing - -let t = @doc(DocsTest.t(::Int, ::Int)) - @test docstrings_equal(Docs.@repl(DocsTest.t(0, 0)), t) - @test docstrings_equal(Docs.@repl(DocsTest.t(::Int, ::Int)), t) -end - -# Issue #13467. -@test (Docs.@repl :@r_str) !== nothing - -# Simple tests for apropos: -@test contains(sprint(apropos, "pearson"), "cor") -@test contains(sprint(apropos, r"ind(exes|ices)"), "eachindex") -@test contains(sprint(apropos, "print"), "Profile.print") - -# Issue #13068. - -module I13068 - -module A - -export foo - -""" -foo from A -""" -foo(::Int) = 1 - -end - -module B - -import ..A: foo - -export foo - -""" -foo from B -""" -foo(::Float64) = 2 - -end - -end - -@test docstrings_equal( - @doc(I13068.A.foo), - doc""" - foo from A - - foo from B - """ -) -@test docstrings_equal(Docs.doc(I13068.A.foo, Tuple{Int}), doc"foo from A") -@test docstrings_equal(Docs.doc(I13068.A.foo, Tuple{Float64}), doc"foo from B") -@test docstrings_equal(Docs.doc(I13068.A.foo, Tuple{Char}), - doc""" - foo from A - - foo from B - """ -) - -# Issue #13905. -@test macroexpand(:(@doc "" f() = @x)) == Expr(:error, UndefVarError(Symbol("@x"))) - -# Undocumented DataType Summaries. - -module Undocumented - -abstract type A end -abstract type B <: A end - -mutable struct C <: A end - -struct D <: B - one - two::String - three::Float64 -end - -f = () -> nothing - -undocumented() = 1 -undocumented(x) = 2 -undocumented(x,y) = 3 - -end - -doc_str = Markdown.parse(""" -No documentation found. - -Binding `$(curmod_prefix)Undocumented.bindingdoesnotexist` does not exist. -""") -@test docstrings_equal(@doc(Undocumented.bindingdoesnotexist), doc"$doc_str") - -doc_str = Markdown.parse(""" -No documentation found. - -**Summary:** -``` -abstract type $(curmod_prefix)Undocumented.A <: Any -``` - -**Subtypes:** -``` -$(curmod_prefix)Undocumented.B -$(curmod_prefix)Undocumented.C -``` -""") -@test docstrings_equal(@doc(Undocumented.A), doc"$doc_str") - -doc_str = Markdown.parse(""" -No documentation found. - -**Summary:** -``` -abstract type $(curmod_prefix)Undocumented.B <: $(curmod_prefix)Undocumented.A -``` - -**Subtypes:** -``` -$(curmod_prefix)Undocumented.D -``` -""") -@test docstrings_equal(@doc(Undocumented.B), doc"$doc_str") - -doc_str = Markdown.parse(""" -No documentation found. - -**Summary:** -``` -mutable struct $(curmod_prefix)Undocumented.C <: $(curmod_prefix)Undocumented.A -``` -""") -@test docstrings_equal(@doc(Undocumented.C), doc"$doc_str") - -doc_str = Markdown.parse(""" -No documentation found. - -**Summary:** -``` -struct $(curmod_prefix)Undocumented.D <: $(curmod_prefix)Undocumented.B -``` - -**Fields:** -``` -one :: Any -two :: String -three :: Float64 -``` -""") -@test docstrings_equal(@doc(Undocumented.D), doc"$doc_str") - -let d = @doc Undocumented.f - io = IOBuffer() - show(io, MIME"text/markdown"(), d) - @test startswith(String(take!(io)),""" - No documentation found. - - `$(curmod_prefix)Undocumented.f` is a `Function`. - """) -end - -let d = @doc Undocumented.undocumented - io = IOBuffer() - show(io, MIME"text/markdown"(), d) - @test startswith(String(take!(io)), """ - No documentation found. - - `$(curmod_prefix)Undocumented.undocumented` is a `Function`. - """) -end - -# `@doc` "metadata". - -let m = @doc(DocsTest).meta - @test length(m[:results]) == 1 - @test m[:results][1] === Docs.meta(DocsTest)[@var(DocsTest)].docs[Union{}] - @test m[:binding] == @var(DocsTest) - @test m[:typesig] === Union{} -end - -let m = @doc(DocsTest.f).meta - @test length(m[:results]) == 2 - @test m[:results][1] === Docs.meta(DocsTest)[@var(DocsTest.f)].docs[Tuple{Any}] - @test m[:results][2] === Docs.meta(DocsTest)[@var(DocsTest.f)].docs[Tuple{Any, Any}] - @test m[:binding] == @var(DocsTest.f) - @test m[:typesig] === Union{} -end - -let m = @doc(DocsTest.f(x)).meta - @test length(m[:results]) == 1 - @test m[:results][1] === Docs.meta(DocsTest)[@var(DocsTest.f)].docs[Tuple{Any}] - @test m[:binding] == @var(DocsTest.f) - @test m[:typesig] == Tuple{Any} -end - -let m = @doc(Undocumented.f).meta - @test isempty(m[:results]) - @test m[:binding] == @var(Undocumented.f) - @test m[:typesig] === Union{} -end - -# Bindings. - -import Base.Docs: @var, Binding, defined - -let x = Binding(Base, Symbol("@time")) - @test defined(x) == true - @test @var(@time) == x - @test @var(Base.@time) == x - @test @var(Base.Pkg.@time) == x -end - -let x = Binding(Base.LinAlg, :norm) - @test defined(x) == true - @test @var(norm) == x - @test @var(Base.norm) == x - @test @var(Base.LinAlg.norm) == x - @test @var(Base.Pkg.Dir.norm) == x -end - -let x = Binding(Core, :Int) - @test defined(x) == true - @test @var(Int) == x - @test @var(Base.Int) == x - @test @var(Core.Int) == x - @test @var(Base.Pkg.Resolve.Int) == x -end - -let x = Binding(Base, :Pkg) - @test defined(x) == true - @test @var(Pkg) == x - @test @var(Base.Pkg) == x - @test @var(Main.Pkg) == x -end - -let x = Binding(Base, :VERSION) - @test defined(x) == true - @test @var(VERSION) == x - @test @var(Base.VERSION) == x -end - -let x = Binding(Base, :bindingdoesnotexist) - @test defined(x) == false - @test @var(Base.bindingdoesnotexist) == x -end - -let x = Binding(curmod, :bindingdoesnotexist) - @test defined(x) == false - @test @var(bindingdoesnotexist) == x -end - -let x = Binding(Main, :+) - @test parse(string(x)) == :(Base.:+) -end - -let x = Binding(Base, :parse) - @test parse(string(x)) == :(Base.parse) -end - -let x = Binding(Main, :⊕) - @test parse(string(x)) == :(⊕) -end - -# Docs.helpmode tests: we test whether the correct expressions are being generated here, -# rather than complete integration with Julia's REPL mode system. -for (line, expr) in Pair[ - "sin" => :sin, - "Base.sin" => :(Base.sin), - "@time(x)" => :(@time(x)), - "@time" => :(:@time), - ":@time" => :(:@time), - "@time()" => :(@time), - "Base.@time()" => :(Base.@time), - "ccall" => :ccall, # keyword - "while " => :while, # keyword, trailing spaces should be stripped. - "0" => 0, - "\"...\"" => "...", - "r\"...\"" => :(r"..."), - ] - @test Docs.helpmode(line) == :(Base.Docs.@repl($STDOUT, $expr)) - buf = IOBuffer() - @test eval(Base, Docs.helpmode(buf, line)) isa Union{Base.Markdown.MD,Void} -end - -let save_color = Base.have_color - try - @eval Base have_color = false - @test sprint(Base.Docs.repl_latex, "√") == "\"√\" can be typed by \\sqrt<tab>\n\n" - @test sprint(Base.Docs.repl_latex, "x̂₂") == "\"x̂₂\" can be typed by x\\hat<tab>\\_2<tab>\n\n" - finally - @eval Base have_color = $save_color - end -end - -# issue #15684 -begin - """ - abc - """ - f15684(x) = 1 -end - -@test string(@doc f15684) == "abc\n" - -# Dynamic docstrings - -mutable struct DynamicDocType - x -end - -Base.Docs.getdoc(d::DynamicDocType, sig) = "$(d.x) $(sig)" - -dynamic_test = DynamicDocType("test 1") -@test @doc(dynamic_test) == "test 1 Union{}" -dynamic_test.x = "test 2" -@test @doc(dynamic_test) == "test 2 Union{}" -@test @doc(dynamic_test(::String)) == "test 2 Tuple{String}" - -@test Docs._repl(:(dynamic_test(1.0))) == :(@doc $(Expr(:escape, :(dynamic_test(::typeof(1.0)))))) -@test Docs._repl(:(dynamic_test(::String))) == :(@doc $(Expr(:escape, :(dynamic_test(::String))))) - - -# Equality testing - -@test Text("docstring") == Text("docstring") -@test hash(Text("docstring")) == hash(Text("docstring")) -@test HTML("<b>docstring</b>") == HTML("<b>docstring</b>") -@test Text("docstring1") ≠ Text("docstring2") -@test hash(Text("docstring1")) ≠ hash(Text("docstring2")) -@test hash(Text("docstring")) ≠ hash(HTML("docstring")) - -# issue 21016 -module I21016 - -struct Struct{T} -end - -"String 1" -function Struct{T}(arg1) where T<:Float64 -end - -"String 2" -function Struct{T}(arg1) where T -end - -"String 3" -function Struct{T}(arg1) where Integer <: T <: Real -end - -"String 4" -function Struct{T}(arg1) where T >: Int -end - -end - -@test docstrings_equal( - @doc(I21016.Struct), - doc""" - String 1 - - String 2 - - String 3 - - String 4 - """ -) - -# issue #23011 -@test_nowarn @eval Main begin - @doc "first" f23011() = 1 - @doc "second" f23011() = 2 -end -@test Main.f23011() == 2 -@test docstrings_equal(@doc(Main.f23011), doc"second") diff --git a/julia-0.6.3/share/julia/test/download.jl b/julia-0.6.3/share/julia/test/download.jl deleted file mode 100644 index e982dbf..0000000 --- a/julia-0.6.3/share/julia/test/download.jl +++ /dev/null @@ -1,26 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -mktempdir() do temp_dir - # Download a file - file = joinpath(temp_dir, "ip") - @test download("http://httpbin.org/ip", file) == file - @test isfile(file) - @test !isempty(read(file)) - - # Download an empty file - empty_file = joinpath(temp_dir, "empty") - @test download("http://httpbin.org/status/200", empty_file) == empty_file - - # Windows and older versions of curl do not create the empty file (https://github.com/curl/curl/issues/183) - @test !isfile(empty_file) || isempty(read(empty_file)) - - # Make sure that failed downloads do not leave files around - missing_file = joinpath(temp_dir, "missing") - @test_throws ErrorException download("http://httpbin.org/status/404", missing_file) - @test !isfile(missing_file) - - # Use a TEST-NET (192.0.2.0/24) address which shouldn't be bound - invalid_host_file = joinpath(temp_dir, "invalid_host") - @test_throws ErrorException download("http://192.0.2.1", invalid_host_file) - @test !isfile(invalid_host_file) -end diff --git a/julia-0.6.3/share/julia/test/dsp.jl b/julia-0.6.3/share/julia/test/dsp.jl deleted file mode 100644 index ced0c82..0000000 --- a/julia-0.6.3/share/julia/test/dsp.jl +++ /dev/null @@ -1,139 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -# Filter -b = [1., 2., 3., 4.] -x = [1., 1., 0., 1., 1., 0., 0., 0.] -@test filt(b, 1., x) == [1., 3., 5., 8., 7., 5., 7., 4.] -@test filt(b, [1., -0.5], x) == [1., 3.5, 6.75, 11.375, 12.6875, 11.34375, 12.671875, 10.3359375] -# With ranges -@test filt(b, 1., 1.0:10.0) == [1., 4., 10., 20., 30., 40., 50., 60., 70., 80.] -@test filt(1.:4., 1., 1.0:10.0) == [1., 4., 10., 20., 30., 40., 50., 60., 70., 80.] -# Across an array is the same as channel-by-channel -@test filt(b, 1., [x 1.0:8.0]) == [filt(b, 1., x) filt(b, 1., 1.0:8.0)] -@test filt(b, [1., -0.5], [x 1.0:8.0]) == [filt(b, [1., -0.5], x) filt(b, [1., -0.5], 1.0:8.0)] -si = zeros(3) -@test filt(b, 1., [x 1.0:8.0], si) == [filt(b, 1., x, si) filt(b, 1., 1.0:8.0, si)] -@test si == zeros(3) # Will likely fail if/when arrayviews are implemented -si = [zeros(3) ones(3)] -@test filt(b, 1., [x 1.0:8.0], si) == [filt(b, 1., x, zeros(3)) filt(b, 1., 1.0:8.0, ones(3))] -# With initial conditions: a lowpass 5-pole butterworth filter with W_n = 0.25, -# and a stable initial filter condition matched to the initial value -b = [0.003279216306360201,0.016396081531801006,0.03279216306360201,0.03279216306360201,0.016396081531801006,0.003279216306360201] -a = [1.0,-2.4744161749781606,2.8110063119115782,-1.703772240915465,0.5444326948885326,-0.07231566910295834] -si = [0.9967207836936347,-1.4940914728163142,1.2841226760316475,-0.4524417279474106,0.07559488540931815] -@test filt(b, a, ones(10), si) ≈ ones(10) # Shouldn't affect DC offset - -@test_throws ArgumentError filt!([1, 2], [1], [1], [1]) -@test xcorr([1, 2], [3, 4]) == [4, 11, 6] - -# Shift-Functions -@test fftshift([1 2 3]) == [3 1 2] -@test fftshift([1, 2, 3]) == [3, 1, 2] -@test fftshift([1 2 3; 4 5 6]) == [6 4 5; 3 1 2] - -@test fftshift([1 2 3; 4 5 6], 1) == [4 5 6; 1 2 3] -@test fftshift([1 2 3; 4 5 6], ()) == [1 2 3; 4 5 6] -@test fftshift([1 2 3; 4 5 6], (1,2)) == [6 4 5; 3 1 2] -@test fftshift([1 2 3; 4 5 6], 1:2) == [6 4 5; 3 1 2] - -@test ifftshift([1 2 3]) == [2 3 1] -@test ifftshift([1, 2, 3]) == [2, 3, 1] -@test ifftshift([1 2 3; 4 5 6]) == [5 6 4; 2 3 1] - -@test ifftshift([1 2 3; 4 5 6], 1) == [4 5 6; 1 2 3] -@test ifftshift([1 2 3; 4 5 6], ()) == [1 2 3; 4 5 6] -@test ifftshift([1 2 3; 4 5 6], (1,2)) == [5 6 4; 2 3 1] -@test ifftshift([1 2 3; 4 5 6], 1:2) == [5 6 4; 2 3 1] - -# Convolution -a = [1., 2., 1., 2.] -b = [1., 2., 3.] -@test conv(a, b) ≈ [1., 4., 8., 10., 7., 6.] -@test conv(complex.(a, ones(4)), complex(b)) ≈ complex.([1., 4., 8., 10., 7., 6.], [1., 3., 6., 6., 5., 3.]) - -# Discrete cosine transform (DCT) tests - -if Base.fftw_vendor() != :mkl - a = rand(8,11) + im*rand(8,11) - @test norm(idct(dct(a)) - a) < 1e-8 - - X = reshape([1,2,7,2,1,5,9,-1,3,4,6,9],3,4) - Y = rand(17,14) - Y[3:5,9:12] = X - sX = view(Y,3:5,9:12) - - true_Xdct = [ 13.856406460551018 -3.863239728836245 2.886751345948129 -0.274551994240164; -2.828427124746190 -2.184015211898548 -4.949747468305834 3.966116180118245; 4.898979485566356 -0.194137576915510 -2.857738033247041 2.731723009609389 ] - - true_Xdct_1 = [ 5.773502691896258 4.618802153517007 6.350852961085884 10.969655114602890; -4.242640687119286 -2.121320343559643 4.242640687119286 -3.535533905932738; 1.632993161855452 2.041241452319315 5.715476066494083 0.408248290463863 ] - - true_Xdct_2 = [ 8. -3.854030797826254 -3.0 3.761176226848022; - 4.0 -2.071929829606556 4.0 -2.388955165168770; 12. -0.765366864730179 4.0 -1.847759065022573 ] - - Xdct = dct(X) - Xdct! = float(X); dct!(Xdct!) - Xdct_1 = dct(X,1) - Xdct!_1 = float(X); dct!(Xdct!_1,1) - Xdct_2 = dct(X,2) - Xdct!_2 = float(X); dct!(Xdct!_2,2) - - Xidct = idct(true_Xdct) - Xidct! = copy(true_Xdct); idct!(Xidct!) - Xidct_1 = idct(true_Xdct_1,1) - Xidct!_1 = copy(true_Xdct_1); idct!(Xidct!_1,1) - Xidct_2 = idct(true_Xdct_2,2) - Xidct!_2 = copy(true_Xdct_2); idct!(Xidct!_2,2) - - pXdct = plan_dct(X)*(X) - pXdct! = float(X); plan_dct!(pXdct!)*(pXdct!) - pXdct_1 = plan_dct(X,1)*(X) - pXdct!_1 = float(X); plan_dct!(pXdct!_1,1)*(pXdct!_1) - pXdct_2 = plan_dct(X,2)*(X) - pXdct!_2 = float(X); plan_dct!(pXdct!_2,2)*(pXdct!_2) - - pXidct = plan_idct(true_Xdct)*(true_Xdct) - pXidct! = copy(true_Xdct); plan_idct!(pXidct!)*(pXidct!) - pXidct_1 = plan_idct(true_Xdct_1,1)*(true_Xdct_1) - pXidct!_1 = copy(true_Xdct_1); plan_idct!(pXidct!_1,1)*(pXidct!_1) - pXidct_2 = plan_idct(true_Xdct_2,2)*(true_Xdct_2) - pXidct!_2 = copy(true_Xdct_2); plan_idct!(pXidct!_2,2)*(pXidct!_2) - - sXdct = dct(sX) - psXdct = plan_dct(sX)*(sX) - sYdct! = copy(Y); sXdct! = view(sYdct!,3:5,9:12); dct!(sXdct!) - psYdct! = copy(Y); psXdct! = view(psYdct!,3:5,9:12); plan_dct!(psXdct!)*(psXdct!) - - for i = 1:length(X) - @test Xdct[i] ≈ true_Xdct[i] - @test Xdct![i] ≈ true_Xdct[i] - @test Xdct_1[i] ≈ true_Xdct_1[i] - @test Xdct!_1[i] ≈ true_Xdct_1[i] - @test Xdct_2[i] ≈ true_Xdct_2[i] - @test Xdct!_2[i] ≈ true_Xdct_2[i] - - @test pXdct[i] ≈ true_Xdct[i] - @test pXdct![i] ≈ true_Xdct[i] - @test pXdct_1[i] ≈ true_Xdct_1[i] - @test pXdct!_1[i] ≈ true_Xdct_1[i] - @test pXdct_2[i] ≈ true_Xdct_2[i] - @test pXdct!_2[i] ≈ true_Xdct_2[i] - - @test Xidct[i] ≈ X[i] - @test Xidct![i] ≈ X[i] - @test Xidct_1[i] ≈ X[i] - @test Xidct!_1[i] ≈ X[i] - @test Xidct_2[i] ≈ X[i] - @test Xidct!_2[i] ≈ X[i] - - @test pXidct[i] ≈ X[i] - @test pXidct![i] ≈ X[i] - @test pXidct_1[i] ≈ X[i] - @test pXidct!_1[i] ≈ X[i] - @test pXidct_2[i] ≈ X[i] - @test pXidct!_2[i] ≈ X[i] - - @test sXdct[i] ≈ true_Xdct[i] - @test psXdct[i] ≈ true_Xdct[i] - @test sXdct![i] ≈ true_Xdct[i] - @test psXdct![i] ≈ true_Xdct[i] - end -end # fftw_vendor() != :mkl diff --git a/julia-0.6.3/share/julia/test/enums.jl b/julia-0.6.3/share/julia/test/enums.jl deleted file mode 100644 index 243650b..0000000 --- a/julia-0.6.3/share/julia/test/enums.jl +++ /dev/null @@ -1,136 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -# For curmod_* -include("testenv.jl") - -using Base.Test - -@test_throws MethodError convert(Enum, 1.0) - -@test_throws ArgumentError eval(:(@enum Foo)) - -@enum Fruit apple orange kiwi -@test typeof(Fruit) == DataType -@test isbits(Fruit) -@test typeof(apple) <: Fruit <: Enum -@test Int(apple) == 0 -@test Int(orange) == 1 -@test Int(kiwi) == 2 -@test Fruit(0) == apple -@test Fruit(1) == orange -@test Fruit(2) == kiwi -@test_throws ArgumentError Fruit(3) -@test_throws ArgumentError Fruit(-1) -@test Fruit(0x00) == apple -@test Fruit(big(0)) == apple -@test_throws MethodError Fruit(0.0) -@test typemin(Fruit) == apple -@test typemax(Fruit) == kiwi -@test convert(Fruit,0) == apple -@test convert(Fruit,1) == orange -@test convert(Fruit,2) == kiwi -@test_throws ArgumentError convert(Fruit,3) -@test_throws ArgumentError convert(Fruit,-1) -@test convert(UInt8,apple) === 0x00 -@test convert(UInt16,orange) === 0x0001 -@test convert(UInt128,kiwi) === 0x00000000000000000000000000000002 -@test typeof(convert(BigInt,apple)) <: BigInt -@test convert(BigInt,apple) == 0 -@test convert(Bool,apple) == false -@test convert(Bool,orange) == true -@test_throws InexactError convert(Bool,kiwi) -@test instances(Fruit) == (apple, orange, kiwi) - -f(x::Fruit) = "hey, I'm a Fruit" -@test f(apple) == "hey, I'm a Fruit" - -d = Dict(apple=>"apple",orange=>"orange",kiwi=>"kiwi") -@test d[apple] == "apple" -@test d[orange] == "orange" -@test d[kiwi] == "kiwi" -vals = [apple,orange,kiwi] -for (i,enum) in enumerate(instances(Fruit)) - @test enum == vals[i] -end - -@enum(QualityofFrenchFood, ReallyGood) -@test length(instances(QualityofFrenchFood)) == 1 -@test typeof(ReallyGood) <: QualityofFrenchFood <: Enum -@test Int(ReallyGood) == 0 - -@enum Binary _zero=0 _one=1 _two=10 _three=11 -@test Int(_zero) === 0 -@test Int(_one) === 1 -@test Int(_two) === 10 -@test Int(_three) === 11 -@enum Negative _neg1=-1 _neg2=-2 -@test Int(_neg1) === -1 -@test Int(_neg2) === -2 -@test_throws InexactError convert(UInt8, _neg1) -@enum Negative2 _neg5=-5 _neg4 _neg3 -@test Int(_neg5) === -5 -@test Int(_neg4) === -4 -@test Int(_neg3) === -3 - -@test_throws ArgumentError eval(:(@enum Test1 _zerofp=0.0)) -@test_throws ArgumentError eval(:(@enum Test11 _zerofp2=0.5)) -@enum Test111 _zerobi=BigInt(1) -@test Integer(_zerobi) == 1 - -# can't use non-identifiers as enum members -@test_throws ArgumentError eval(:(@enum(Test2, ?))) -@test_throws ArgumentError eval(:(@enum Test22 1=2)) - -# other Integer types of enum members -@enum Test3::UInt8 _one_Test3=0x01 _two_Test3=0x02 _three_Test3=0x03 -@test Test3.size == 1 -@test convert(UInt8, _one_Test3) === 0x01 -@test length(instances(Test3)) == 3 - -@enum Test4::UInt16 _one_Test4=0x01 _two_Test4=0x0002 _three_Test4=0x03 -@test Test4.size == 2 - -@enum Test5::UInt32 _one_Test5=0x01 _two_Test5=0x00000002 _three_Test5=0x00000003 -@test Test5.size == 4 - -@enum Test6::UInt128 _one_Test6=0x00000000000000000000000000000001 _two_Test6=0x00000000000000000000000000000002 -@test Test6.size == 16 -@test typeof(convert(Integer, _one_Test6)) == UInt128 - -# enum values must be integers -@test_throws ArgumentError eval(:(@enum Test7 _zero="zero")) -@test_throws ArgumentError eval(:(@enum Test8 _zero='0')) -@test_throws ArgumentError eval(:(@enum Test9 _zero=0.5)) - -# test macro handles keyword arguments -@enum(Test11, _zero_Test11=2, - _one_Test11, - _two_Test11=5, - _three_Test11) - -@test Int(_zero_Test11) == 2 -@test Int(_one_Test11) == 3 -@test Int(_two_Test11) == 5 -@test Int(_three_Test11) == 6 - -# don't allow enum value to overflow -@test_throws ArgumentError @eval(@enum EnumOvf x=typemax(Int32) y) - -# test for unique Enum values -@test_throws ArgumentError eval(:(@enum(Test14, _zero_Test14, _one_Test14, _two_Test14=0))) - -@test repr(apple) == "apple::$(string(Fruit)) = 0" -@test string(apple) == "apple" - -@test reprmime("text/plain", Fruit) == "Enum $(string(Fruit)):\napple = 0\norange = 1\nkiwi = 2" -@test reprmime("text/plain", orange) == "orange::$(curmod_prefix)Fruit = 1" - -@enum LogLevel DEBUG INFO WARN ERROR CRITICAL -@test DEBUG < CRITICAL - -# serialization -let b = IOBuffer() - serialize(b, apple) - seekstart(b) - @test deserialize(b) === apple -end diff --git a/julia-0.6.3/share/julia/test/env.jl b/julia-0.6.3/share/julia/test/env.jl deleted file mode 100644 index 10c75d4..0000000 --- a/julia-0.6.3/share/julia/test/env.jl +++ /dev/null @@ -1,72 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -@test !("f=a=k=e=n=a=m=e" ∈ keys(ENV)) - -# issue #10994 -@test_throws ArgumentError ENV["bad\0name"] = "ok" -@test_throws ArgumentError ENV["okname"] = "bad\0val" -@test_throws ArgumentError Sys.set_process_title("bad\0title") - -withenv("bad"=>"dog") do - @test_throws ArgumentError ENV["bad\0cat"] -end - -# issue #11170 -withenv("TEST"=>"nonempty") do - @test ENV["TEST"] == "nonempty" -end -withenv("TEST"=>"") do - @test ENV["TEST"] == "" -end - -let c = collect(ENV) - @test isa(c, Vector) - @test length(ENV) == length(c) - @test isempty(ENV) || first(ENV) in c -end - -# test for non-existent keys -key = randstring(25) -@test !haskey(ENV,key) -@test_throws KeyError ENV[key] -@test get(ENV,key,"default") == "default" - -# Test for #17956 -@test length(ENV) > 1 -k1, k2 = "__test__", "__test1__" -withenv(k1=>k1, k2=>k2) do - b_k1, b_k2 = false, false - for (k, v) in ENV - if k==k1 - b_k1=true - elseif k==k2 - b_k2=true - end - end - @test b_k1 && b_k2 - io = IOBuffer() - show(io, ENV) - s = String(take!(io)) - @test contains(s, "$k1=$k1") - @test contains(s, "$k2=$k2") - - @test pop!(ENV, k1) == k1 - @test !haskey(ENV, k1) - ENV[k1] = k1 - @test pop!(ENV, k1) == k1 - @test pop!(ENV, k1, "not_there") == "not_there" - - ENV[k1] = k1 - @test delete!(ENV, k1) == ENV - @test !haskey(ENV, k1) -end - -# Test for #10853 -@test withenv(Dict{Any,Any}()...) do; true; end - -# Test for #18141 -for (k, v) in ENV - if length(v) > 0 - @test v[end] != '\0' - end -end diff --git a/julia-0.6.3/share/julia/test/error.jl b/julia-0.6.3/share/julia/test/error.jl deleted file mode 100644 index e92aa93..0000000 --- a/julia-0.6.3/share/julia/test/error.jl +++ /dev/null @@ -1,71 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -@test length(ExponentialBackOff(n=10)) == 10 -@test collect(ExponentialBackOff(n=10, first_delay=0.01))[1] == 0.01 -@test maximum(ExponentialBackOff(n=10, max_delay=0.06)) == 0.06 -ratio(x) = x[2:end]./x[1:end-1] -@test all(x->x ≈ 10.0, ratio(collect(ExponentialBackOff(n=10, max_delay=Inf, factor=10, jitter=0.0)))) -srand(12345) -@test (mean(ratio(collect(ExponentialBackOff(n=100, max_delay=Inf, factor=1, jitter=0.1)))) - 1.0) < 1e-4 - -let - function foo_error(c, n) - c[1] += 1 - if c[1] <= n - error("foo") - end - return 7 - end - - # Success on first attempt - c = [0] - @test retry(foo_error)(c,0) == 7 - @test c[1] == 1 - - # Success on second attempt - c = [0] - @test retry(foo_error)(c,1) == 7 - @test c[1] == 2 - - # 2 failed retry attempts, so exception is raised - c = [0] - ex = try retry(foo_error, delays=ExponentialBackOff(n=2))(c,3) catch e; e end - @test ex.msg == "foo" - @test c[1] == 3 - - c = [0] - ex = try retry(foo_error, check=(s,e)->(s,isa(e, ErrorException)))(c,2) catch e; e end - @test typeof(ex) == ErrorException - @test ex.msg == "foo" - @test c[1] == 2 - - c = [0] - ex = try retry(foo_error, check=(s,e)->(s,e.msg == "foo"))(c,2) catch e; e end - @test typeof(ex) == ErrorException - @test ex.msg == "foo" - @test c[1] == 2 - - # No retry if condition does not match - c = [0] - ex = try retry(foo_error, check=(s,e)->(s,e.msg == "bar"))(c,2) catch e; e end - @test typeof(ex) == ErrorException - @test ex.msg == "foo" - @test c[1] == 1 - - c = [0] - ex = try retry(foo_error, check=(s,e)->(s,try e.http_status_code == "503" end != true))(c,2) catch e; e end - @test typeof(ex) == ErrorException - @test ex.msg == "foo" - @test c[1] == 2 - - c = [0] - ex = try retry(foo_error, check=(s,e)->(s,isa(e,SystemError)))(c,2) catch e; e end - @test typeof(ex) == ErrorException - @test ex.msg == "foo" - @test c[1] == 1 - - # Functions with keyword arguments - foo_kwargs(x; y=5) = x + y - @test retry(foo_kwargs)(3) == 8 - @test retry(foo_kwargs)(3; y=4) == 7 -end diff --git a/julia-0.6.3/share/julia/test/euler.jl b/julia-0.6.3/share/julia/test/euler.jl deleted file mode 100644 index 52b9bd0..0000000 --- a/julia-0.6.3/share/julia/test/euler.jl +++ /dev/null @@ -1,654 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -## Project Euler -# -# problems: http://projecteuler.net/problems -# solutions: https://code.google.com/p/projecteuler-solutions/wiki/ProjectEulerSolutions - -#1: 233168 -@test sum(filter(n->(n%3==0)|(n%5==0),1:999)) == 233168 - -#2: 4613732 -function euler2(n) - t, i, j = 0, 1, 2 - while j <= n - t += j - i, j = j, i+j - i, j = j, i+j - i, j = j, i+j - end - return t -end -@test euler2(4000000) == 4613732 - -#4: 906609 -function euler4(n) - m = 1 - for a = 10^n-1:-1:10^(n-1) - for b = 10^n-1:-1:max(a,-fld(-m,a)) - p = a*b - d = digits(p) - if d == reverse(d) && p > m - m = p - b < -fld(-m,a) && break - end - end - end - return m -end -@test euler4(3) == 906609 - -#5: 232792560 -@test lcm(1:20) == 232792560 - -#6: 25164150 -@test sum(1:100)^2 - sum((1:100).^2) == 25164150 - -#8: 40824 -function euler8(n,m) - d = digits(n) - maximum([prod(d[k:k+m-1]) for k=1:length(d)-m+1]) -end -let n = 7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450 - @test euler8(n,5) == 40824 -end - -#9: 31875000 -function euler9(n) - for a = 1:n, b = 1:n-a, c = n-a-b - a^2 + b^2 == c^2 && return a*b*c - end -end -@test euler9(1000) == 31875000 - - -#11: 70600674 -function euler11(grid,n) - m = typemin(eltype(grid)) - for i = n:size(grid,1)-n+1, - j = n:size(grid,2)-n+1, - di = -1:1, dj = -1:1 - di == dj == 0 && continue - idx = sub2ind(size(grid), - di==0 ? fill(i,n) : range(i,di,n), - dj==0 ? fill(j,n) : range(j,dj,n)) - m = max(m,prod(grid[idx])) - end - return m -end -let grid = [ - 08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08 - 49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00 - 81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65 - 52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91 - 22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80 - 24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50 - 32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70 - 67 26 20 68 02 62 12 20 95 63 94 39 63 08 40 91 66 49 94 21 - 24 55 58 05 66 73 99 26 97 17 78 78 96 83 14 88 34 89 63 72 - 21 36 23 09 75 00 76 44 20 45 35 14 00 61 33 97 34 31 33 95 - 78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92 - 16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57 - 86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58 - 19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40 - 04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66 - 88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69 - 04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36 - 20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16 - 20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54 - 01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48 -] - @test euler11(grid,4) == 70600674 -end - -#12: 76576500 - -#13: 5537376230 -let nums = [ - 37107287533902102798797998220837590246510135740250 - 46376937677490009712648124896970078050417018260538 - 74324986199524741059474233309513058123726617309629 - 91942213363574161572522430563301811072406154908250 - 23067588207539346171171980310421047513778063246676 - 89261670696623633820136378418383684178734361726757 - 28112879812849979408065481931592621691275889832738 - 44274228917432520321923589422876796487670272189318 - 47451445736001306439091167216856844588711603153276 - 70386486105843025439939619828917593665686757934951 - 62176457141856560629502157223196586755079324193331 - 64906352462741904929101432445813822663347944758178 - 92575867718337217661963751590579239728245598838407 - 58203565325359399008402633568948830189458628227828 - 80181199384826282014278194139940567587151170094390 - 35398664372827112653829987240784473053190104293586 - 86515506006295864861532075273371959191420517255829 - 71693888707715466499115593487603532921714970056938 - 54370070576826684624621495650076471787294438377604 - 53282654108756828443191190634694037855217779295145 - 36123272525000296071075082563815656710885258350721 - 45876576172410976447339110607218265236877223636045 - 17423706905851860660448207621209813287860733969412 - 81142660418086830619328460811191061556940512689692 - 51934325451728388641918047049293215058642563049483 - 62467221648435076201727918039944693004732956340691 - 15732444386908125794514089057706229429197107928209 - 55037687525678773091862540744969844508330393682126 - 18336384825330154686196124348767681297534375946515 - 80386287592878490201521685554828717201219257766954 - 78182833757993103614740356856449095527097864797581 - 16726320100436897842553539920931837441497806860984 - 48403098129077791799088218795327364475675590848030 - 87086987551392711854517078544161852424320693150332 - 59959406895756536782107074926966537676326235447210 - 69793950679652694742597709739166693763042633987085 - 41052684708299085211399427365734116182760315001271 - 65378607361501080857009149939512557028198746004375 - 35829035317434717326932123578154982629742552737307 - 94953759765105305946966067683156574377167401875275 - 88902802571733229619176668713819931811048770190271 - 25267680276078003013678680992525463401061632866526 - 36270218540497705585629946580636237993140746255962 - 24074486908231174977792365466257246923322810917141 - 91430288197103288597806669760892938638285025333403 - 34413065578016127815921815005561868836468420090470 - 23053081172816430487623791969842487255036638784583 - 11487696932154902810424020138335124462181441773470 - 63783299490636259666498587618221225225512486764533 - 67720186971698544312419572409913959008952310058822 - 95548255300263520781532296796249481641953868218774 - 76085327132285723110424803456124867697064507995236 - 37774242535411291684276865538926205024910326572967 - 23701913275725675285653248258265463092207058596522 - 29798860272258331913126375147341994889534765745501 - 18495701454879288984856827726077713721403798879715 - 38298203783031473527721580348144513491373226651381 - 34829543829199918180278916522431027392251122869539 - 40957953066405232632538044100059654939159879593635 - 29746152185502371307642255121183693803580388584903 - 41698116222072977186158236678424689157993532961922 - 62467957194401269043877107275048102390895523597457 - 23189706772547915061505504953922979530901129967519 - 86188088225875314529584099251203829009407770775672 - 11306739708304724483816533873502340845647058077308 - 82959174767140363198008187129011875491310547126581 - 97623331044818386269515456334926366572897563400500 - 42846280183517070527831839425882145521227251250327 - 55121603546981200581762165212827652751691296897789 - 32238195734329339946437501907836945765883352399886 - 75506164965184775180738168837861091527357929701337 - 62177842752192623401942399639168044983993173312731 - 32924185707147349566916674687634660915035914677504 - 99518671430235219628894890102423325116913619626622 - 73267460800591547471830798392868535206946944540724 - 76841822524674417161514036427982273348055556214818 - 97142617910342598647204516893989422179826088076852 - 87783646182799346313767754307809363333018982642090 - 10848802521674670883215120185883543223812876952786 - 71329612474782464538636993009049310363619763878039 - 62184073572399794223406235393808339651327408011116 - 66627891981488087797941876876144230030984490851411 - 60661826293682836764744779239180335110989069790714 - 85786944089552990653640447425576083659976645795096 - 66024396409905389607120198219976047599490197230297 - 64913982680032973156037120041377903785566085089252 - 16730939319872750275468906903707539413042652315011 - 94809377245048795150954100921645863754710598436791 - 78639167021187492431995700641917969777599028300699 - 15368713711936614952811305876380278410754449733078 - 40789923115535562561142322423255033685442488917353 - 44889911501440648020369068063960672322193204149535 - 41503128880339536053299340368006977710650566631954 - 81234880673210146739058568557934581403627822703280 - 82616570773948327592232845941706525094512325230608 - 22918802058777319719839450180888072429661980811197 - 77158542502016545090413245809786882778948721859617 - 72107838435069186155435662884062257473692284509516 - 20849603980134001723930671666823555245252804609722 - 53503534226472524250874054075591789781264330331690 -] - @test sum(digits(sum(nums))[end-9:end].*Int64(10).^(0:9)) == 5537376230 -end - -#14: 837799 -function euler14(m) - c = zeros(Int,m) - c[1] = 1 - for n::Int64 = 2:m - nʹ, d = n, 0 - while nʹ > length(c) || c[nʹ] == 0 - nʹ = iseven(nʹ) ? nʹ>>1 : 3nʹ+1 - d += 1 - end - d += c[nʹ] - while n > length(c) || c[n] == 0 - n <= length(c) && (c[n] = d) - n = iseven(n) ? n>>1 : 3n+1 - d -= 1 - end - end - indmax(c) -end -@test euler14(999999) == 837799 - -#15: 137846528820 - -#16: 1366 -@test sum(digits(big(2)^1000)) == 1366 - -#17: 21124 -#18: 1074 -#19: 171 - -#20: 648 -@test sum(digits(factorial(big(100)))) == 648 - -#21: 31626 -#22: 871198282 -#23: 4179871 -#24: 2783915460 -#25: 4782 -#26: 983 -#27: -59231 -#28: 669171001 -#29: 9183 -#30: 443839 -#31: 73682 -#32: 45228 -#33: 100 -#34: 40730 -#35: 55 -#36: 872187 -#37: 748317 -#38: 932718654 -#39: 840 -#40: 210 -#41: 7652413 -#42: 162 -#43: 16695334890 -#44: 5482660 -#45: 1533776805 -#46: 5777 -#47: 134043 -#48: 9110846700 -#49: 296962999629 -#50: 997651 -#51: 121313 -#52: 142857 -#53: 4075 -#54: 376 -#55: 249 -#56: 972 -#57: 153 -#58: 26241 -#59: 107359 -#60: 26033 -#61: 28684 -#62: 127035954683 -#63: 49 -#64: 1322 -#65: 272 -#66: 661 -#67: 7273 -#68: 6531031914842725 -#69: 510510 -#70: 8319823 -#71: 428570 -#72: 303963552391 -#73: 7295372 -#74: 402 -#75: 161667 -#76: 190569291 -#77: 71 -#78: 55374 -#79: 73162890 -#80: 40886 -#81: 427337 -#82: 260324 -#83: 425185 -#84: 101524 -#85: 2772 -#86: 1818 -#87: 1097343 -#88: 7587457 -#89: 743 -#90: 1217 -#91: 14234 -#92: 8581146 -#93: 1258 -#94: 518408346 -#95: 14316 -#96: 24702 -#97: 8739992577 -#98: 18769 -#99: 709 -#100: 756872327473 -#101: 37076114526 -#102: 228 -#103: 20313839404245 -#104: 329468 -#105: 73702 -#106: 21384 -#107: 259679 -#108: 180180 -#109: 38182 -#110: 9350130049860600 -#111: 612407567715 -#112: 1587000 -#113: 51161058134250 -#114: 16475640049 -#115: 168 -#116: 20492570929 -#117: 100808458960497 -#118: 44680 -#119: 248155780267521 -#120: 333082500 -#121: 2269 -#122: 1582 -#123: 21035 -#124: 21417 -#125: 2906969179 -#126: 18522 -#127: 18407904 -#128: 14516824220 -#129: 1000023 -#130: 149253 -#131: 173 -#132: 843296 -#133: 453647705 -#134: 18613426663617118 -#135: 4989 -#136: 2544559 -#137: 1120149658760 -#138: 1118049290473932 -#139: 10057761 -#140: 5673835352990 -#141: 878454337159 -#142: 1006193 -#143: 30758397 -#144: 354 -#145: 608720 -#146: 676333270 -#147: 846910284 -#148: 2129970655314432 -#149: 52852124 -#150: -271248680 -#151: 0.464399 -#152: 301 -#153: 17971254122360635 -#154: 479742450 -#155: 3857447 -#156: 21295121502550 -#157: 53490 -#158: 409511334375 -#159: 14489159 -#160: 16576 -#161: 20574308184277971 -#162: 3D58725572C62302 -#163: 343047 -#164: 378158756814587 -#165: 2868868 -#166: 7130034 -#167: 3916160068885 -#168: 59206 -#169: 178653872807 -#170: 9857164023 -#171: 142989277 -#172: 227485267000992000 -#173: 1572729 -#174: 209566 -#175: 1,13717420,8 -#176: 96818198400000 -#177: 129325 -#178: 126461847755 -#179: 986262 -#180: 285196020571078987 -#181: 83735848679360680 -#182: 399788195976 -#183: 48861552 -#184: 1725323624056 -#185: 4640261571849533 -#186: 2325629 -#187: 17427258 -#188: 95962097 -#189: 10834893628237824 -#190: 371048281 -#191: 1918080160 -#192: 57060635927998347 -#193: 684465067343069 -#194: 61190912 -#195: 75085391 -#196: 322303240771079935 -#197: 1.710637717 -#198: 52374425 -#199: 0.00396087 -#200: 229161792008 -#201: 115039000 -#202: 1209002624 -#203: 34029210557338 -#204: 2944730 -#205: 0.5731441 -#206: 1389019170 -#207: 44043947822 -#208: 331951449665644800 -#209: 15964587728784 -#210: 1598174770174689458 -#211: 1922364685 -#212: 328968937309 -#213: 330.721154 -#214: 1677366278943 -#215: 806844323190414 -#216: 5437849 -#217: 6273134 -#218: 0 -#219: 64564225042 -#220: 139776,963904 -#221: 1884161251122450 -#222: 1590933 -#223: 61614848 -#224: 4137330 -#225: 2009 -#226: 0.11316017 -#227: 3780.618622 -#228: 86226 -#229: 11325263 -#230: 850481152593119296 -#231: 7526965179680 -#232: 0.83648556 -#233: 271204031455541309 -#234: 1259187438574927161 -#235: 1.002322108633 -#236: 123/59 -#237: 15836928 -#238: 9922545104535661 -#239: 0.001887854841 -#240: 7448717393364181966 -#241: 482316491800641154 -#242: 997104142249036713 -#243: 892371480 -#244: 96356848 -#245: 288084712410001 -#246: 810834388 -#247: 782252 -#248: 23507044290 -#249: 9275262564250418 -#250: 1425480602091519 -#251: 18946051 -#252: 104924.0 -#253: 11.492847 -#254: 8184523820510 -#255: 4.4474011180 -#256: 85765680 -#257: 139012411 -#258: 12747994 -#259: 20101196798 -#260: 167542057 -#261: 238890850232021 -#262: 2531.205 -#263: 2039506520 -#264: 2816417.1055 -#265: 209110240768 -#266: 1096883702440585 -#267: 0.999992836187 -#268: 785478606870985 -#269: 1311109198529286 -#270: 82282080 -#271: 4617456485273129588 -#272: 8495585919506151122 -#273: 2032447591196869022 -#274: 1601912348822 -#275: 15030564 -#276: 5777137137739632912 -#277: 1125977393124310 -#278: 1228215747273908452 -#279: 416577688 -#280: 430.088247 -#281: 1485776387445623 -#282: 1098988351 -#283: 28038042525570324 -#284: 5a411d7b -#285: 157055.80999 -#286: 52.6494571953 -#287: 313135496 -#288: 605857431263981935 -#289: 6567944538 -#290: 20444710234716473 -#291: 4037526 -#292: 3600060866 -#293: 2209 -#294: 789184709 -#295: 4884650818 -#296: 1137208419 -#297: 2252639041804718029 -#298: 1.76882294 -#299: 549936643 -#300: 8.0540771484375 -#301: 2178309 -#302: 1170060 -#303: 1111981904675169 -#304: 283988410192 -#305: 18174995535140 -#306: 852938 -#307: 0.7311720251 -#308: 1539669807660924 -#309: 210139 -#310: 2586528661783 -#311: 2466018557 -#312: 324681947 -#313: 2057774861813004 -#314: 132.52756426 -#315: 13625242 -#316: 542934735751917735 -#317: 1856532.8455 -#318: 709313889 -#319: 268457129 -#320: 278157919195482643 -#321: 2470433131948040 -#322: 999998760323313995 -#323: 6.3551758451 -#324: 96972774 -#325: 54672965 -#326: 1966666166408794329 -#327: 34315549139516 -#328: 260511850222 -#329: 199740353/29386561536000 -#330: 15955822 -#331: 467178235146843549 -#332: 2717.751525 -#333: 3053105 -#334: 150320021261690835 -#335: 5032316 -#336: CAGBIHEFJDK -#337: 85068035 -#338: 15614292 -#339: 19823.542204 -#340: 291504964 -#341: 56098610614277014 -#342: 5943040885644 -#343: 269533451410884183 -#344: 65579304332 -#345: 13938 -#346: 336108797689259276 -#347: 11109800204052 -#348: 1004195061 -#349: 115384615384614952 -#350: 84664213 -#351: 11762187201804552 -#352: 378563.260589 -#353: 1.2759860331 -#354: 58065134 -#355: 1726545007 -#356: 28010159 -#357: 1739023853137 -#358: 3284144505 -#359: 40632119 -#360: 878825614395267072 -#361: 178476944 -#362: 457895958010 -#363: 0.0000372091 -#364: 44855254 -#365: 162619462356610313 -#366: 88351299 -#367: 48271207 -#368: 253.6135092068 -#369: 862400558448 -#370: 41791929448408 -#371: 40.66368097 -#372: 301450082318807027 -#373: 727227472448913 -#374: 334420941 -#375: 7435327983715286168 -#376: 973059630185670 -#377: 732385277 -#378: 147534623725724718 -#379: 132314136838185 -#380: 6.3202e25093 -#381: 139602943319822 -#382: 697003956 -#383: 22173624649806 -#384: 3354706415856332783 -#385: 3776957309612153700 -#386: 528755790 -#387: 696067597313468 -#388: 831907372805129931 -#389: 2406376.3623 -#390: 2919133642971 -#391: 61029882288 -#392: 3.1486734435 -#393: 112398351350823112 -#394: 3.2370342194 -#395: 28.2453753155 -#396: 173214653 -#397: 141630459461893728 -#398: 2010.59096 -#399: 1508395636674243,6.5e27330467 -#400: 438505383468410633 -#401: 281632621 -#402: 356019862 -#403: 18224771 -#404: 1199215615081353 -#405: 237696125 -#406: 36813.12757207 -#407: 39782849136421 -#408: 299742733 -#409: 253223948 -#410: -#411: 9936352 -#412: 38788800 -#413: 3079418648040719 -#414: -#415: -#416: -#417: 446572970925740 -#418: 1177163565297340320 -#419: 998567458,1046245404,43363922 -#420: 145159332 -#421: -#422: -#423: -#424: -#425: 46479497324 -#426: -#427: -#428: -#429: 98792821 -#430: 5000624921.38 diff --git a/julia-0.6.3/share/julia/test/examples.jl b/julia-0.6.3/share/julia/test/examples.jl deleted file mode 100644 index fd63c59..0000000 --- a/julia-0.6.3/share/julia/test/examples.jl +++ /dev/null @@ -1,91 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -dir = joinpath(JULIA_HOME, Base.DOCDIR, "examples") - -include(joinpath(dir, "bubblesort.jl")) -a = rand(1:100,100) -@test issorted(sort!(a;alg=BubbleSort)) - -include(joinpath(dir, "lru.jl")) -include(joinpath(dir, "lru_test.jl")) - -include(joinpath(dir, "ModInts.jl")) -b = ModInts.ModInt{10}(2) -c = ModInts.ModInt{10}(4) -@test b + c == ModInts.ModInt{10}(6) -@test c - b == ModInts.ModInt{10}(2) -x = ModInts.ModInt{256}(13) -y = inv(x) -@test y == ModInts.ModInt{256}(197) -@test x*y == ModInts.ModInt{256}(1) -@test_throws DomainError inv(ModInts.ModInt{8}(4)) - -include(joinpath(dir, "ndgrid.jl")) -r = repmat(1:10,1,10) -r1, r2 = ndgrid(1:10, 1:10) -@test r1 == r -@test r2 == r' -r3, r4 = meshgrid(1:10,1:10) -@test r3 == r' -@test r4 == r - -include(joinpath(dir, "queens.jl")) -@test trysolve(8, 8, 1) == (Queen(1,1),) -@test trysolve(8, 8, 7) == - (Queen(1,1), Queen(2,3), Queen(3,5), Queen(4,2), Queen(5,8), Queen(7,4), Queen(8,7)) - -# Different cluster managers do not play well together. Since -# the test infrastructure already uses LocalManager, we will test the simple -# cluster manager example through a new Julia session. -if is_unix() - script = joinpath(dir, "clustermanager/simple/test_simple.jl") - cmd = `$(Base.julia_cmd()) --startup-file=no $script` - if !success(pipeline(cmd; stdout=STDOUT, stderr=STDERR)) && ccall(:jl_running_on_valgrind,Cint,()) == 0 - error("UnixDomainCM failed test, cmd : $cmd") - end -end - -dc_path = joinpath(dir, "dictchannel.jl") -# Run the remote on pid 1, since runtests may terminate workers -# at any time depending on memory usage -main_ex = quote - myid() == 1 || include($dc_path) - remotecall_fetch(1, $dc_path) do f - include(f) - nothing - end - RemoteChannel(()->DictChannel(), 1) -end -dc = eval(Main, main_ex) -@test typeof(dc) == RemoteChannel{Main.DictChannel} - -@test isready(dc) == false -put!(dc, 1, 2) -put!(dc, "Hello", "World") -@test isready(dc) == true -@test isready(dc, 1) == true -@test isready(dc, "Hello") == true -@test isready(dc, 2) == false -@test fetch(dc, 1) == 2 -@test fetch(dc, "Hello") == "World" -@test take!(dc, 1) == 2 -@test isready(dc, 1) == false - - -# At least make sure code loads -include(joinpath(dir, "wordcount.jl")) - -# the 0mq clustermanager depends on package ZMQ. Just making sure the -# code loads using a stub module definition for ZMQ. -zmq_found=true -try - using ZMQ -catch - zmq_found=false -end - -if !zmq_found - eval(Main, parse("module ZMQ end")) -end - -include(joinpath(dir, "clustermanager/0mq/ZMQCM.jl")) diff --git a/julia-0.6.3/share/julia/test/fastmath.jl b/julia-0.6.3/share/julia/test/fastmath.jl deleted file mode 100644 index 0085d84..0000000 --- a/julia-0.6.3/share/julia/test/fastmath.jl +++ /dev/null @@ -1,209 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -# fast math - -# check expansions - -@test macroexpand(:(@fastmath 1+2)) == :(Base.FastMath.add_fast(1,2)) -@test macroexpand(:(@fastmath +)) == :(Base.FastMath.add_fast) -@test macroexpand(:(@fastmath min(1))) == :(Base.FastMath.min_fast(1)) -@test macroexpand(:(@fastmath min)) == :(Base.FastMath.min_fast) -@test macroexpand(:(@fastmath x.min)) == :(x.min) - -# basic arithmetic - -const one32 = one(Float32) -const eps32 = eps(Float32) -const eps32_2 = eps32/2 -# Note: Cannot use local functions since these are not yet optimized -fm_ieee_32(x) = x + eps32_2 + eps32_2 -fm_fast_32(x) = @fastmath x + eps32_2 + eps32_2 -@test fm_ieee_32(one32) == one32 -@test (fm_fast_32(one32) == one32 || - fm_fast_32(one32) == one32 + eps32 > one32) - -const one64 = one(Float64) -const eps64 = eps(Float64) -const eps64_2 = eps64/2 -# Note: Cannot use local functions since these are not yet optimized -fm_ieee_64(x) = x + eps64_2 + eps64_2 -fm_fast_64(x) = @fastmath x + eps64_2 + eps64_2 -@test fm_ieee_64(one64) == one64 -@test (fm_fast_64(one64) == one64 || - fm_fast_64(one64) == one64 + eps64 > one64) -# check updating operators -fm_ieee_64_upd(x) = (r=x; r+=eps64_2; r+=eps64_2) -fm_fast_64_upd(x) = @fastmath (r=x; r+=eps64_2; r+=eps64_2) -@test fm_ieee_64_upd(one64) == one64 -@test (fm_fast_64_upd(one64) == one64 || - fm_fast_64_upd(one64) == one64 + eps64 > one64) - -let epsf = 1.0f0/2^15, one_epsf = 1+epsf - @test @fastmath(one_epsf * one_epsf - 1) ≈ Float32(65537/1073741824) -end -let eps = 1.0/2^30, one_eps = 1+eps - @test @fastmath(one_eps * one_eps - 1) ≈ 2147483649/1152921504606846976 -end - -for T in (Float32, Float64, BigFloat) - zero = convert(T, 0) - one = convert(T, 1) + eps(T) - two = convert(T, 2) + 1//10 - three = convert(T, 3) + 1//100 - - @test @fastmath(+two) ≈ +two - @test @fastmath(-two) ≈ -two - @test @fastmath(zero+one+two) ≈ zero+one+two - @test @fastmath(zero-one-two) ≈ zero-one-two - @test @fastmath(one*two*three) ≈ one*two*three - @test @fastmath(one/two/three) ≈ one/two/three - @test @fastmath(rem(two,three)) ≈ rem(two,three) - @test @fastmath(mod(two,three)) ≈ mod(two,three) - @test @fastmath(cmp(two,two)) == cmp(two,two) - @test @fastmath(cmp(two,three)) == cmp(two,three) - @test @fastmath(cmp(three,two)) == cmp(three,two) - @test @fastmath(one/zero) == convert(T,Inf) - @test @fastmath(-one/zero) == -convert(T,Inf) - @test isnan(@fastmath(zero/zero)) # must not throw - - for x in (zero, two, convert(T, Inf), convert(T, NaN)) - @test @fastmath(isfinite(x)) - @test !@fastmath(isinf(x)) - @test !@fastmath(isnan(x)) - @test !@fastmath(issubnormal(x)) - end -end - -for T in (Complex64, Complex128, Complex{BigFloat}) - zero = convert(T,0) - one = convert(T,1) + im*eps(real(convert(T,1))) - two = convert(T,2) + im//10 - three = convert(T,3) + im//100 - - @test @fastmath(+two) ≈ +two - @test @fastmath(-two) ≈ -two - @test @fastmath(zero+one+two) ≈ zero+one+two - @test @fastmath(zero-one-two) ≈ zero-one-two - @test @fastmath(one*two*three) ≈ one*two*three - @test @fastmath(one/two/three) ≈ one/two/three - @test @fastmath(three == two) == (three == two) - @test @fastmath(three != two) == (three != two) - @test isnan(@fastmath(one/zero)) # must not throw - @test isnan(@fastmath(-one/zero)) # must not throw - @test isnan(@fastmath(zero/zero)) # must not throw - - for x in (zero, two, convert(T, Inf), convert(T, NaN)) - @test @fastmath(isfinite(x)) - @test !@fastmath(isinf(x)) - @test !@fastmath(isnan(x)) - @test !@fastmath(issubnormal(x)) - end -end - - -# math functions - -# real arithmetic -for T in (Float32, Float64, BigFloat) - half = 1/convert(T,2) - third = 1/convert(T,3) - - for f in (:+, :-, :abs, :abs2, :conj, :inv, :sign, - :acos, :asin, :asinh, :atan, :atanh, :cbrt, :cos, :cosh, - :exp10, :exp2, :exp, :expm1, :lgamma, :log10, :log1p, - :log2, :log, :sin, :sinh, :sqrt, :tan, :tanh) - @eval begin - @test @fastmath($f($half)) ≈ $f($half) - @test @fastmath($f($third)) ≈ $f($third) - end - end - for f in (:acosh,) - @eval begin - @test @fastmath($f(1+$half)) ≈ $f(1+$half) - @test @fastmath($f(1+$third)) ≈ $f(1+$third) - end - end - for f in (:+, :-, :*, :/, :%, :(==), :!=, :<, :<=, :>, :>=, :^, - :atan2, :hypot, :max, :min) - @eval begin - @test @fastmath($f($half, $third)) ≈ $f($half, $third) - @test @fastmath($f($third, $half)) ≈ $f($third, $half) - end - end - for f in (:minmax,) - @eval begin - @test @fastmath($f($half, $third)[1]) ≈ $f($half, $third)[1] - @test @fastmath($f($half, $third)[2]) ≈ $f($half, $third)[2] - @test @fastmath($f($third, $half)[1]) ≈ $f($third, $half)[1] - @test @fastmath($f($third, $half)[2]) ≈ $f($third, $half)[2] - end - end -end - -# complex arithmetic -for T in (Complex64, Complex128, Complex{BigFloat}) - half = (1+1im)/T(2) - third = (1-1im)/T(3) - - # some of these functions promote their result to double - # precision, but we want to check equality at precision T - rtol = Base.rtoldefault(real(T)) - - for f in (:+, :-, :abs, :abs2, :conj, :inv, :sign, - :acos, :acosh, :asin, :asinh, :atan, :atanh, :cis, :cos, - :cosh, :exp10, :exp2, :exp, :expm1, :log10, :log1p, - :log2, :log, :sin, :sinh, :sqrt, :tan, :tanh) - @eval begin - @test @fastmath($f($half)) ≈ $f($half) rtol=$rtol - @test @fastmath($f($third)) ≈ $f($third) rtol=$rtol - end - end - for f in (:+, :-, :*, :/, :(==), :!=, :^) - @eval begin - @test @fastmath($f($half, $third)) ≈ $f($half, $third) rtol=$rtol - @test @fastmath($f($third, $half)) ≈ $f($third, $half) rtol=$rtol - end - end -end - -# mixed real/complex arithmetic -for T in (Float32, Float64, BigFloat) - CT = Complex{T} - half = 1/T(2) - third = 1/T(3) - chalf = (1+1im)/CT(2) - cthird = (1-1im)/CT(3) - - for f in (:+, :-, :*, :/, :(==), :!=, :^) - @eval begin - @test @fastmath($f($chalf, $third)) ≈ $f($chalf, $third) - @test @fastmath($f($half, $cthird)) ≈ $f($half, $cthird) - @test @fastmath($f($cthird, $half)) ≈ $f($cthird, $half) - @test @fastmath($f($third, $chalf)) ≈ $f($third, $chalf) - end - end - - @test @fastmath(third^3) ≈ third^3 - @test @fastmath(chalf/third) ≈ chalf/third - @test @fastmath(chalf^3) ≈ chalf^3 - @test @fastmath(cis(third)) ≈ cis(third) -end - -# issue #10544 -let a = ones(2,2), b = ones(2,2) - @test @fastmath(a[1] += 2.0) ≈ (b[1] += 2.0) - @test @fastmath(a[2] -= 2.0) ≈ (b[2] -= 2.0) - @test @fastmath(a[1,1] *= 2.0) ≈ (b[1,1] *= 2.0) - @test @fastmath(a[2,2] /= 2.0) ≈ (b[2,2] /= 2.0) - @test @fastmath(a[1,2] ^= 2.0) ≈ (b[1,2] ^= 2.0) - - # test fallthrough for unsupported ops - local c = 0 - @test @fastmath(c |= 1) == 1 -end - -# issue #23218 -let a = zeros(1), b = ones(1), idx = (1,) - @fastmath a[idx...] += b[idx...] - @test a == b -end diff --git a/julia-0.6.3/share/julia/test/fft.jl b/julia-0.6.3/share/julia/test/fft.jl deleted file mode 100644 index 63a1a24..0000000 --- a/julia-0.6.3/share/julia/test/fft.jl +++ /dev/null @@ -1,352 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -# issue #19892 -# (test this first to make sure it happens before set_num_threads) -let a = randn(10^5,1), p1 = plan_rfft(a, flags=FFTW.ESTIMATE) - FFTW.set_num_threads(2) - p2 = plan_rfft(a, flags=FFTW.ESTIMATE) - @test p1*a ≈ p2*a - # make sure threads are actually being used for p2 - # (tests #21163). - if FFTW.version >= v"3.3.4" - @test !contains(string(p1), "dft-thr") - @test contains(string(p2), "dft-thr") - end -end - -# fft -a = rand(8) + im*rand(8) -@test norm(ifft(fft(a)) - a) < 1e-8 -@test norm(ifft(fft(a,1),1) - a) < 1e-8 -@test norm(ifft(fft(a,[1]),[1]) - a) < 1e-8 -@test norm(ifft(fft(a,(1,)),(1,)) - a) < 1e-8 -a = rand(-10:10, 8) + im*rand(-10:10, 8) -@test norm(ifft(fft(a)) - a) < 1e-8 - -m4 = [16. 2 3 13; - 5 11 10 8; - 9 7 6 12; - 4 14 15 1] - -true_fft_m4 = [ - 34. 34. 34. 34.; - 7. - 1.0im -5. + 3.0im -3. + 5.0im 1. - 7.0im; - 16. -16. -16. 16.; - 7. + 1.0im -5. - 3.0im -3. - 5.0im 1. + 7.0im ] - -true_fftn_m4 = [ - 136. 0 0 0 ; - 0. 20 8 + 8im 0 - 12im ; - 0. 32 + 32im 0 32 - 32im ; - 0. 0 + 12im 8 - 8im 20 ] - -true_fftd2_m4 = [ - 34. 13 + 11im 4 13 - 11im ; - 34. -5 - 3im -4 -5 + 3im ; - 34. 3 + 5im -4 3 - 5im ; - 34. -11 - 13im 4 -11 + 13im ] - -b = rand(17,14) -b[3:6,9:12] = m4 -sm4 = view(b,3:6,9:12) - -m3d = map(Float32,copy(reshape(1:5*3*2, 5, 3, 2))) -true_fftd3_m3d = Array{Float32}(5, 3, 2) -true_fftd3_m3d[:,:,1] = 17:2:45 -true_fftd3_m3d[:,:,2] = -15 - -# use invoke to force usage of CTPlan versions even if FFTW is present -for A in (Array,SubArray) - for f in (:fft,:ifft,:plan_fft,:plan_ifft) - f_ = Symbol(f, "_") - @eval begin - $f_{T,N}(x::$A{T,N}) = invoke($f, Tuple{AbstractArray{T,N}}, x) - $f_{T,N,R}(x::$A{T,N},r::R) = invoke($f,Tuple{AbstractArray{T,N},R},x,r) - end - end -end - -for (f,fi,pf,pfi) in ((fft,ifft,plan_fft,plan_ifft), - (fft_,ifft_,plan_fft_,plan_ifft_)) - pm4 = pf(m4,1) - - fft_m4 = f(m4,1) - fftd2_m4 = f(m4,2) - ifft_fft_m4 = fi(f(m4,1),1) - fftn_m4 = f(m4) - ifftn_fftn_m4 = fi(f(m4)) - - fft!_m4 = complex(m4); fft!(fft!_m4,1) - fft!d2_m4 = complex(m4); fft!(fft!d2_m4,2) - ifft!_fft_m4 = f(m4,1); ifft!(ifft!_fft_m4,1) - fft!n_m4 = complex(m4); fft!(fft!n_m4) - ifft!n_fftn_m4 = f(m4); ifft!(ifft!n_fftn_m4) - - pfft_m4 = pf(m4,1)*m4 - pfftd2_m4 = pf(m4,2)*m4 - pifft_fft_m4 = pfi(fft_m4,1)*fft_m4 - pfftn_m4 = pf(m4)*m4 - pifftn_fftn_m4 = pfi(fftn_m4)*fftn_m4 - - pfft!_m4 = complex(m4); plan_fft!(pfft!_m4,1)*pfft!_m4 - pfft!d2_m4 = complex(m4); plan_fft!(pfft!d2_m4,2)*pfft!d2_m4 - pifft!_fft_m4 = f(m4,1); plan_ifft!(pifft!_fft_m4,1)*pifft!_fft_m4 - pfft!n_m4 = complex(m4); plan_fft!(pfft!n_m4)*pfft!n_m4 - pifft!n_fftn_m4 = f(m4); plan_ifft!(pifft!n_fftn_m4)*pifft!n_fftn_m4 - - sfftn_m4 = f(sm4) - psfftn_m4 = pf(sm4)*sm4 - sfft!n_b = map(Complex128,b) - sfft!n_m4 = view(sfft!n_b,3:6,9:12); fft!(sfft!n_m4) - psfft!n_b = map(Complex128,b) - psfft!n_m4 = view(psfft!n_b,3:6,9:12); plan_fft!(psfft!n_m4)*psfft!n_m4 - - for i = 1:length(m4) - @test fft_m4[i] ≈ true_fft_m4[i] - @test fftd2_m4[i] ≈ true_fftd2_m4[i] - @test ifft_fft_m4[i] ≈ m4[i] - @test fftn_m4[i] ≈ true_fftn_m4[i] - @test ifftn_fftn_m4[i] ≈ m4[i] - - @test fft!_m4[i] ≈ true_fft_m4[i] - @test fft!d2_m4[i] ≈ true_fftd2_m4[i] - @test ifft!_fft_m4[i] ≈ m4[i] - @test fft!n_m4[i] ≈ true_fftn_m4[i] - @test ifft!n_fftn_m4[i] ≈ m4[i] - - @test pfft_m4[i] ≈ true_fft_m4[i] - @test pfftd2_m4[i] ≈ true_fftd2_m4[i] - @test pifft_fft_m4[i] ≈ m4[i] - @test pfftn_m4[i] ≈ true_fftn_m4[i] - @test pifftn_fftn_m4[i] ≈ m4[i] - - @test pfft!_m4[i] ≈ true_fft_m4[i] - @test pfft!d2_m4[i] ≈ true_fftd2_m4[i] - @test pifft!_fft_m4[i] ≈ m4[i] - @test pfft!n_m4[i] ≈ true_fftn_m4[i] - @test pifft!n_fftn_m4[i] ≈ m4[i] - - @test sfftn_m4[i] ≈ true_fftn_m4[i] - @test sfft!n_m4[i] ≈ true_fftn_m4[i] - @test psfftn_m4[i] ≈ true_fftn_m4[i] - @test psfft!n_m4[i] ≈ true_fftn_m4[i] - end - - ifft!(sfft!n_m4) - plan_ifft!(psfft!n_m4)*psfft!n_m4 - @test norm(sfft!n_m4 - m4) < 1e-8 - @test norm(psfft!n_m4 - m4) < 1e-8 - - # The following capabilities are FFTW only. - # They are not available in MKL, and hence do not test them. - if Base.fftw_vendor() != :mkl - ifft3_fft3_m3d = fi(f(m3d)) - - fftd3_m3d = f(m3d,3) - ifftd3_fftd3_m3d = fi(fftd3_m3d,3) - - fft!d3_m3d = complex(m3d); fft!(fft!d3_m3d,3) - ifft!d3_fftd3_m3d = copy(fft!d3_m3d); ifft!(ifft!d3_fftd3_m3d,3) - - pfftd3_m3d = pf(m3d,3)*m3d - pifftd3_fftd3_m3d = pfi(fftd3_m3d,3)*fftd3_m3d - - pfft!d3_m3d = complex(m3d); plan_fft!(pfft!d3_m3d,3)*pfft!d3_m3d - pifft!d3_fftd3_m3d = copy(fft!d3_m3d); plan_ifft!(pifft!d3_fftd3_m3d,3)*pifft!d3_fftd3_m3d - - @test isa(fftd3_m3d, Array{Complex64,3}) - @test isa(ifftd3_fftd3_m3d, Array{Complex64,3}) - @test isa(fft!d3_m3d, Array{Complex64,3}) - @test isa(ifft!d3_fftd3_m3d, Array{Complex64,3}) - @test isa(pfftd3_m3d, Array{Complex64,3}) - @test isa(pifftd3_fftd3_m3d, Array{Complex64,3}) - @test isa(pfft!d3_m3d, Array{Complex64,3}) - @test isa(pifft!d3_fftd3_m3d, Array{Complex64,3}) - - for i = 1:length(m3d) - @test fftd3_m3d[i] ≈ true_fftd3_m3d[i] - @test ifftd3_fftd3_m3d[i] ≈ m3d[i] - @test ifft3_fft3_m3d[i] ≈ m3d[i] - - @test fft!d3_m3d[i] ≈ true_fftd3_m3d[i] - @test ifft!d3_fftd3_m3d[i] ≈ m3d[i] - - @test pfftd3_m3d[i] ≈ true_fftd3_m3d[i] - @test pifftd3_fftd3_m3d[i] ≈ m3d[i] - @test pfft!d3_m3d[i] ≈ true_fftd3_m3d[i] - @test pifft!d3_fftd3_m3d[i] ≈ m3d[i] - end - end # if fftw_vendor() != :mkl - - # rfft/rfftn - - rfft_m4 = rfft(m4,1) - rfftd2_m4 = rfft(m4,2) - rfftn_m4 = rfft(m4) - - prfft_m4 = plan_rfft(m4,1)*m4 - prfftd2_m4 = plan_rfft(m4,2)*m4 - prfftn_m4 = plan_rfft(m4)*m4 - - srfftn_m4 = rfft(sm4) - psrfftn_m4 = plan_rfft(sm4)*sm4 - - for i = 1:3, j = 1:4 - @test rfft_m4[i,j] ≈ true_fft_m4[i,j] - @test rfftd2_m4[j,i] ≈ true_fftd2_m4[j,i] - @test rfftn_m4[i,j] ≈ true_fftn_m4[i,j] - - @test prfft_m4[i,j] ≈ true_fft_m4[i,j] - @test prfftd2_m4[j,i] ≈ true_fftd2_m4[j,i] - @test prfftn_m4[i,j] ≈ true_fftn_m4[i,j] - - @test srfftn_m4[i,j] ≈ true_fftn_m4[i,j] - @test psrfftn_m4[i,j] ≈ true_fftn_m4[i,j] - end - - irfft_rfft_m4 = irfft(rfft_m4,size(m4,1),1) - irfft_rfftd2_m4 = irfft(rfftd2_m4,size(m4,2),2) - irfftn_rfftn_m4 = irfft(rfftn_m4,size(m4,1)) - - pirfft_rfft_m4 = plan_irfft(rfft_m4,size(m4,1),1)*rfft_m4 - pirfft_rfftd2_m4 = plan_irfft(rfftd2_m4,size(m4,2),2)*rfftd2_m4 - pirfftn_rfftn_m4 = plan_irfft(rfftn_m4,size(m4,1))*rfftn_m4 - - for i = 1:length(m4) - @test irfft_rfft_m4[i] ≈ m4[i] - @test irfft_rfftd2_m4[i] ≈ m4[i] - @test irfftn_rfftn_m4[i] ≈ m4[i] - - @test pirfft_rfft_m4[i] ≈ m4[i] - @test pirfft_rfftd2_m4[i] ≈ m4[i] - @test pirfftn_rfftn_m4[i] ≈ m4[i] - end - - if Base.fftw_vendor() != :mkl - rfftn_m3d = rfft(m3d) - rfftd3_m3d = rfft(m3d,3) - @test size(rfftd3_m3d) == size(fftd3_m3d) - irfft_rfftd3_m3d = irfft(rfftd3_m3d,size(m3d,3),3) - irfftn_rfftn_m3d = irfft(rfftn_m3d,size(m3d,1)) - for i = 1:length(m3d) - @test rfftd3_m3d[i] ≈ true_fftd3_m3d[i] - @test irfft_rfftd3_m3d[i] ≈ m3d[i] - @test irfftn_rfftn_m3d[i] ≈ m3d[i] - end - - fftn_m3d = fft(m3d) - @test size(fftn_m3d) == (5,3,2) - rfftn_m3d = rfft(m3d) - @test size(rfftn_m3d) == (3,3,2) - for i = 1:3, j = 1:3, k = 1:2 - @test rfftn_m3d[i,j,k] ≈ fftn_m3d[i,j,k] - end - end # !mkl -end - -# FFT self-test algorithm (for unscaled 1d forward FFTs): -# Funda Ergün, "Testing multivariate linear functions: Overcoming -# the generator bottleneck," Proc. 27th ACM Symposium on the Theory -# of Computing, pp. 407-416 (1995). -# Check linearity, impulse-response, and time-shift properties. -function fft_test{T<:Complex}(p::Base.DFT.Plan{T}, ntrials=4, - tol=1e5 * eps(real(T))) - ndims(p) == 1 || throw(ArgumentError("not a 1d FFT")) - n = length(p) - twopi_i = (-2 * convert(real(T), π)/n * (0:n-1)) * im - for trial = 1:ntrials - # linearity: - x = rand(T, n) - y = rand(T, n) - α = rand(T) - β = rand(T) - X = p * (α*x + β*y) - err = norm(α * (p*x) + β * (p*y) - X, Inf) / norm(X, Inf) - err <= tol || error("linearity error $err in $p") - - # impulse-response: - z = zeros(T, n) - i = rand(0:n-1) - z[i+1] = 1 - X = exp.(twopi_i*i) - err = norm(p*z - X, Inf) / norm(X, Inf) - err <= tol || error("impulse-response error $err in $p") - - # time-shift: - if n > 1 - s = rand(1:n-1) - X = (p*x).*exp.(twopi_i*s) - err = norm(p*circshift(x,s) - X, Inf) / norm(X, Inf) - err <= tol || error("time-shift error $err in $p") - end - end -end - -for T in (Complex64, Complex128) - for n in [1:100; 121; 143; 1000; 1024; 1031; 2000; 2048] - x = zeros(T, n) - fft_test(plan_fft(x)) - fft_test(plan_fft_(x)) - end -end - -# test inversion, scaling, and pre-allocated variants -for T in (Complex64, Complex128) - for x in (T[1:100;], copy(reshape(T[1:200;], 20,10))) - y = similar(x) - for planner in (plan_fft, plan_fft_, plan_ifft, plan_ifft_) - p = planner(x) - pi = inv(p) - p3 = 3*p - p3i = inv(p3) - @test eltype(p) == eltype(pi) == eltype(p3) == eltype(p3i) == T - @test vecnorm(x - p3i * (p * 3x)) < eps(real(T)) * 10000 - @test vecnorm(3x - pi * (p3 * x)) < eps(real(T)) * 10000 - A_mul_B!(y, p, x) - @test y == p * x - A_ldiv_B!(y, p, x) - @test y == p \ x - end - end -end - -let - plan32 = plan_fft([1.0:2048.0;]) - plan64 = plan_fft([1f0:2048f0;]) - FFTW.flops(plan32) - FFTW.flops(plan64) -end - -# issue #9772 -for x in (randn(10),randn(10,12)) - z = complex(x) - y = rfft(x) - @inferred rfft(x) - @inferred brfft(x,18) - @inferred brfft(y,10) - for f in (plan_bfft!, plan_fft!, plan_ifft!, - plan_bfft, plan_fft, plan_ifft, - fft, bfft, fft_, ifft) - p = @inferred f(z) - if isa(p, FFTW.Plan) - @inferred FFTW.plan_inv(p) - end - end - for f in (plan_bfft, plan_fft, plan_ifft, - plan_rfft, fft, bfft, fft_, ifft) - p = @inferred f(x) - if isa(p, FFTW.Plan) - @inferred FFTW.plan_inv(p) - end - end - # note: inference doesn't work for plan_fft_ since the - # algorithm steps are included in the CTPlan type -end - -# issue #17896 -a = rand(5) -@test fft(a) == fft(view(a,:)) == fft(view(a, 1:5)) == fft(view(a, [1:5;])) -@test rfft(a) == rfft(view(a,:)) == rfft(view(a, 1:5)) == rfft(view(a, [1:5;])) -a16 = convert(Vector{Float16}, a) -@test fft(a16) == fft(view(a16,:)) == fft(view(a16, 1:5)) == fft(view(a16, [1:5;])) -@test rfft(a16) == rfft(view(a16,:)) == rfft(view(a16, 1:5)) == rfft(view(a16, [1:5;])) diff --git a/julia-0.6.3/share/julia/test/file.jl b/julia-0.6.3/share/julia/test/file.jl deleted file mode 100644 index 269d5fe..0000000 --- a/julia-0.6.3/share/julia/test/file.jl +++ /dev/null @@ -1,1136 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -############################################# -# Create some temporary files & directories # -############################################# -starttime = time() -pwd_ = pwd() -dir = mktempdir() -file = joinpath(dir, "afile.txt") -# like touch, but lets the operating system update the timestamp -# for greater precision on some platforms (windows) -@test close(open(file,"w")) === nothing - -subdir = joinpath(dir, "adir") -mkdir(subdir) -subdir2 = joinpath(dir, "adir2") -mkdir(subdir2) -@test_throws SystemError mkdir(file) -let err = nothing - try - mkdir(file) - catch err - io = IOBuffer() - showerror(io, err) - @test startswith(String(take!(io)), "SystemError (with $file): mkdir:") - end -end - -if !is_windows() || Sys.windows_version() >= Sys.WINDOWS_VISTA_VER - dirlink = joinpath(dir, "dirlink") - symlink(subdir, dirlink) - # relative link - cd(subdir) - relsubdirlink = joinpath(subdir, "rel_subdirlink") - reldir = joinpath("..", "adir2") - symlink(reldir, relsubdirlink) - cd(pwd_) -end - -if !is_windows() - link = joinpath(dir, "afilelink.txt") - symlink(file, link) - # relative link - cd(subdir) - rellink = joinpath(subdir, "rel_afilelink.txt") - relfile = joinpath("..", "afile.txt") - symlink(relfile, rellink) - cd(pwd_) -end - - -####################################################################### -# This section tests some of the features of the stat-based file info # -####################################################################### -@test isdir(dir) -@test !isfile(dir) -@test !islink(dir) -@test !isdir(file) -@test isfile(file) -@test !islink(file) - -@test filemode(file) & 0o444 > 0 # readable -@test filemode(file) & 0o222 > 0 # writable -chmod(file, filemode(file) & 0o7555) -@test filemode(file) & 0o222 == 0 -chmod(file, filemode(file) | 0o222) -@test filemode(file) & 0o111 == 0 -@test filesize(file) == 0 - -if is_windows() - permissions = 0o444 - @test filemode(dir) & 0o777 != permissions - @test filemode(subdir) & 0o777 != permissions - @test filemode(file) & 0o777 != permissions - chmod(dir, permissions, recursive=true) - @test filemode(dir) & 0o777 == permissions - @test filemode(subdir) & 0o777 == permissions - @test filemode(file) & 0o777 == permissions - chmod(dir, 0o666, recursive=true) # Reset permissions in case someone wants to use these later -else - mktempdir() do tmpdir - tmpfile=joinpath(tmpdir, "tempfile.txt") - touch(tmpfile) - chmod(tmpfile, 0o707) - linkfile=joinpath(dir, "tempfile.txt") - symlink(tmpfile, linkfile) - permissions=0o776 - @test filemode(dir) & 0o777 != permissions - @test filemode(subdir) & 0o777 != permissions - @test filemode(file) & 0o777 != permissions - @test filemode(linkfile) & 0o777 != permissions - @test filemode(tmpfile) & 0o777 != permissions - chmod(dir, permissions, recursive=true) - @test filemode(dir) & 0o777 == permissions - @test filemode(subdir) & 0o777 == permissions - @test filemode(file) & 0o777 == permissions - @test lstat(link).mode & 0o777 != permissions # Symbolic links are not modified. - @test filemode(linkfile) & 0o777 != permissions # Symbolic links are not followed. - @test filemode(tmpfile) & 0o777 != permissions - rm(linkfile) - end -end - -# On windows the filesize of a folder is the accumulation of all the contained -# files and is thus zero in this case. -if is_windows() - @test filesize(dir) == 0 -else - @test filesize(dir) > 0 -end -nowtime = time() -# Allow 10s skew in addition to the time it took us to actually execute this code -let skew = 10 + (nowtime - starttime) - mfile = mtime(file) - mdir = mtime(dir) - @test abs(nowtime - mfile) <= skew && abs(nowtime - mdir) <= skew && abs(mfile - mdir) <= skew -end -#@test Int(time()) >= Int(mtime(file)) >= Int(mtime(dir)) >= 0 # 1 second accuracy should be sufficient - -# test links -if is_unix() - @test islink(link) == true - @test readlink(link) == file -end - -if !is_windows() || Sys.windows_version() >= Sys.WINDOWS_VISTA_VER - @test islink(dirlink) == true - @test isdir(dirlink) == true - @test readlink(dirlink) == subdir * (is_windows() ? "\\" : "") -end - -# rm recursive TODO add links -newfile = joinpath(dir, "bfile.txt") -mv(file, newfile) -file = newfile -c_tmpdir = mktempdir() -c_subdir = joinpath(c_tmpdir, "c_subdir") -mkdir(c_subdir) -c_file = joinpath(c_tmpdir, "cfile.txt") -cp(newfile, c_file) - -@test isdir(c_subdir) -@test isfile(c_file) -@test_throws SystemError rm(c_tmpdir) -@test_throws SystemError rm(c_tmpdir, force=true) - -# create temp dir in specific directory -d_tmpdir = mktempdir(c_tmpdir) -@test isdir(d_tmpdir) -@test Base.samefile(dirname(d_tmpdir), c_tmpdir) - -# create temp file in specific directory -d_tmpfile,f = mktemp(c_tmpdir) -close(f) -@test isfile(d_tmpfile) -@test Base.samefile(dirname(d_tmpfile), c_tmpdir) - -rm(c_tmpdir, recursive=true) -@test !isdir(c_tmpdir) -@test_throws Base.UVError rm(c_tmpdir) -@test rm(c_tmpdir, force=true) === nothing -@test_throws Base.UVError rm(c_tmpdir, recursive=true) -@test rm(c_tmpdir, force=true, recursive=true) === nothing - -if !is_windows() - # chown will give an error if the user does not have permissions to change files - if get(ENV, "USER", "") == "root" || get(ENV, "HOME", "") == "/root" - chown(file, -2, -1) # Change the file owner to nobody - @test stat(file).uid !=0 - chown(file, 0, -2) # Change the file group to nogroup (and owner back to root) - @test stat(file).gid !=0 - @test stat(file).uid ==0 - chown(file, -1, 0) - @test stat(file).gid ==0 - @test stat(file).uid ==0 - else - @test_throws Base.UVError chown(file, -2, -1) # Non-root user cannot change ownership to another user - @test_throws Base.UVError chown(file, -1, -2) # Non-root user cannot change group to a group they are not a member of (eg: nogroup) - end -else - # test that chown doesn't cause any errors for Windows - @test chown(file, -2, -2) === nothing -end - -####################################################################### -# This section tests file watchers. # -####################################################################### -function test_file_poll(channel,interval,timeout_s) - rc = poll_file(file, interval, timeout_s) - put!(channel,rc) -end - -function test_timeout(tval) - tic() - channel = Channel(1) - @async test_file_poll(channel, 10, tval) - tr = take!(channel) - t_elapsed = toq() - @test !ispath(tr[1]) && !ispath(tr[2]) - @test tval <= t_elapsed -end - -function test_touch(slval) - tval = slval*1.1 - channel = Channel(1) - @async test_file_poll(channel, tval/3, tval) - sleep(tval/3) # one poll period - f = open(file,"a") - write(f,"Hello World\n") - close(f) - tr = take!(channel) - @test ispath(tr[1]) && ispath(tr[2]) -end - -function test_watch_file_timeout(tval) - watch = @async watch_file(file, tval) - @test wait(watch) == Base.Filesystem.FileEvent(false, false, true) -end - -function test_watch_file_change(tval) - watch = @async watch_file(file, tval) - sleep(tval/3) - open(file, "a") do f - write(f, "small change\n") - end - @test wait(watch) == Base.Filesystem.FileEvent(false, true, false) -end - -function test_monitor_wait(tval) - fm = FileMonitor(file) - @async begin - sleep(tval) - f = open(file,"a") - write(f,"Hello World\n") - close(f) - end - fname, events = wait(fm) - close(fm) - if is_linux() || is_windows() || is_apple() - @test fname == basename(file) - else - @test fname == "" # platforms where F_GETPATH is not available - end - @test events.changed -end - -function test_monitor_wait_poll() - pfw = PollingFileWatcher(file, 5.007) - @async begin - sleep(2.5) - f = open(file,"a") - write(f,"Hello World\n") - close(f) - end - (old, new) = wait(pfw) - close(pfw) - @test new.mtime - old.mtime > 2.5 - 1.5 # mtime may only have second-level accuracy (plus add some hysteresis) -end - -test_timeout(0.1) -test_timeout(1) -test_touch(6) -test_monitor_wait(0.1) -test_monitor_wait(0.1) -test_monitor_wait_poll() -test_monitor_wait_poll() -test_watch_file_timeout(0.1) -test_watch_file_change(6) - -@test_throws Base.UVError watch_file("____nonexistent_file", 10) -@test_throws Base.UVError poll_file("____nonexistent_file", 2, 10) - -############## -# mark/reset # -############## - -s = open(file, "w") -write(s, "Marked!\n") -write(s, "Hello world!\n") -write(s, "Goodbye world!\n") -close(s) -s = open(file) -mark(s) -str = readline(s) -@test startswith(str, "Marked!") -@test ismarked(s) -reset(s) -@test !ismarked(s) -str = readline(s) -@test startswith(str, "Marked!") -mark(s) -@test readline(s) == "Hello world!" -@test ismarked(s) -unmark(s) -@test !ismarked(s) -@test_throws ArgumentError reset(s) -@test !unmark(s) -@test !ismarked(s) -close(s) - -####################################################################### -# This section tests temporary file and directory creation. # -####################################################################### - -my_tempdir = tempdir() -@test isdir(my_tempdir) == true - -path = tempname() -# Issue #9053. -@test ispath(path) == is_windows() -ispath(path) && rm(path) - -(p, f) = mktemp() -print(f, "Here is some text") -close(f) -@test isfile(p) == true -@test readstring(p) == "Here is some text" -rm(p) - -let - tmp_path = mktemp() do p, io - @test isfile(p) - print(io, "鴨かも?") - p - end - @test tmp_path != "" - @test !isfile(tmp_path) -end - -let - tmpdir = mktempdir() do d - @test isdir(d) - d - end - @test tmpdir != "" - @test !isdir(tmpdir) -end - -emptyfile = joinpath(dir, "empty") -touch(emptyfile) -emptyf = open(emptyfile) -@test isempty(readlines(emptyf, chomp=false)) -close(emptyf) -rm(emptyfile) - - -######################################################################################## -## This section tests cp & mv(rename) files, directories, absolute and relative links. # -######################################################################################## -function check_dir(orig_path::AbstractString, copied_path::AbstractString, follow_symlinks::Bool) - isdir(orig_path) || throw(ArgumentError("'$orig_path' is not a directory.")) - # copied_path must also be a dir. - @test isdir(copied_path) - readir_orig = readdir(orig_path) - readir_copied = readdir(copied_path) - @test readir_orig == readir_copied - # check recursive - for name in readir_orig - @test name in readir_copied - check_cp(joinpath(orig_path, name), joinpath(copied_path, name), follow_symlinks) - end -end - -function check_cp(orig_path::AbstractString, copied_path::AbstractString, follow_symlinks::Bool) - if islink(orig_path) - if !follow_symlinks - # copied_path must be a link - @test islink(copied_path) - readlink_orig = readlink(orig_path) - # copied_path must have the same link value: - # this is true for absolute and relative links - @test readlink_orig == readlink(copied_path) - if isabspath(readlink_orig) - @test isabspath(readlink(copied_path)) - end - else - # copied_path may not be a link if follow_symlinks=true - @test islink(orig_path) == !islink(copied_path) - if isdir(orig_path) - check_dir(orig_path, copied_path, follow_symlinks) - else - # copied_path must also be a file. - @test isfile(copied_path) - # copied_path must have same content - @test readstring(orig_path) == readstring(copied_path) - end - end - elseif isdir(orig_path) - check_cp_main(orig_path, copied_path, follow_symlinks) - else - # copied_path must also be a file. - @test isfile(copied_path) - # copied_path must have same content - @test readstring(orig_path) == readstring(copied_path) - end -end - -function check_cp_main(orig::AbstractString, copied::AbstractString, follow_symlinks::Bool) - if isdir(orig) - check_dir(orig, copied, follow_symlinks) - else - check_cp(orig, copied, follow_symlinks) - end -end - -function cp_and_test(src::AbstractString, dst::AbstractString, follow_symlinks::Bool) - cp(src, dst; follow_symlinks=follow_symlinks) - check_cp_main(src, dst, follow_symlinks) -end - -## cp ---------------------------------------------------- -# issue #8698 -# Test copy file -afile = joinpath(dir, "a.txt") -touch(afile) -af = open(afile, "r+") -write(af, "This is indeed a test") - -bfile = joinpath(dir, "b.txt") -cp(afile, bfile) - -cfile = joinpath(dir, "c.txt") -write(cfile, "This is longer than the contents of afile") -cp(afile, cfile; remove_destination=true) - -a_stat = stat(afile) -b_stat = stat(bfile) -c_stat = stat(cfile) -@test a_stat.mode == b_stat.mode -@test a_stat.size == b_stat.size -@test a_stat.size == c_stat.size - -@test parse(Int,match(r"mode=(.*),",sprint(show,a_stat)).captures[1]) == a_stat.mode - -close(af) -rm(afile) -rm(bfile) -rm(cfile) - -## mv ---------------------------------------------------- -mktempdir() do tmpdir - # rename file - file = joinpath(tmpdir, "afile.txt") - files_stat = stat(file) - close(open(file,"w")) # like touch, but lets the operating system update - # the timestamp for greater precision on some platforms (windows) - - newfile = joinpath(tmpdir, "bfile.txt") - mv(file, newfile) - newfile_stat = stat(file) - - @test !ispath(file) - @test isfile(newfile) - @test Base.samefile(files_stat, newfile_stat) - - file = newfile - - # Test renaming directories - a_tmpdir = mktempdir() - b_tmpdir = joinpath(tmpdir, "b_tmpdir") - - # grab a_tmpdir's file info before renaming - a_stat = stat(a_tmpdir) - - # rename, then make sure b_tmpdir does exist and a_tmpdir doesn't - mv(a_tmpdir, b_tmpdir) - @test isdir(b_tmpdir) - @test !ispath(a_tmpdir) - - # get b_tmpdir's file info and compare with a_tmpdir - b_stat = stat(b_tmpdir) - @test Base.samefile(a_stat, b_stat) - - rm(b_tmpdir) -end - -# issue #10506 #10434 -## Tests for directories and links to directories -if !is_windows() || Sys.windows_version() >= Sys.WINDOWS_VISTA_VER - function setup_dirs(tmpdir) - srcdir = joinpath(tmpdir, "src") - hidden_srcdir = joinpath(tmpdir, ".hidden_srcdir") - hidden_srcsubdir = joinpath(hidden_srcdir, ".hidden_srcsubdir") - srcdir_cp = joinpath(tmpdir, "srcdir_cp") - mkdir(srcdir) - mkdir(hidden_srcdir) - mkdir(hidden_srcsubdir) - abs_dirlink = joinpath(tmpdir, "abs_dirlink") - symlink(abspath(srcdir), abs_dirlink) - cd(tmpdir) - rel_dirlink = "rel_dirlink" - symlink("src", rel_dirlink) - cd(pwd_) - - cfile = joinpath(srcdir, "c.txt") - file_txt = "This is some text with unicode - 这是一个文件" - write(cfile, file_txt) - hidden_cfile = joinpath(hidden_srcsubdir, "c.txt") - write(hidden_cfile, file_txt) - - abs_dirlink_cp = joinpath(tmpdir, "abs_dirlink_cp") - hidden_srcsubdir_cp = joinpath(tmpdir, ".hidden_srcsubdir_cp") - path_rel_dirlink = joinpath(tmpdir, rel_dirlink) - path_rel_dirlink_cp = joinpath(tmpdir, "rel_dirlink_cp") - - test_src_paths = [srcdir, hidden_srcsubdir, abs_dirlink, path_rel_dirlink] - test_cp_paths = [srcdir_cp, hidden_srcsubdir_cp, abs_dirlink_cp, path_rel_dirlink_cp] - return test_src_paths, test_cp_paths - end - - function cp_follow_symlinks_false_check(s, d; remove_destination=false) - cp(s, d; remove_destination=remove_destination, follow_symlinks=false) - @test isdir(s) == isdir(d) - @test islink(s) == islink(d) - islink(s) && @test readlink(s) == readlink(d) - islink(s) && @test isabspath(readlink(s)) == isabspath(readlink(d)) - # all should contain 1 file named "c.txt" - @test "c.txt" in readdir(d) - @test length(readdir(d)) == 1 - end - - function mv_check(s, d, d_mv; remove_destination=true) - # setup dest - cp(s, d; remove_destination=true, follow_symlinks=false) - stat_d = stat(d) - # mv(rename) dst to dst_mv - mv(d, d_mv; remove_destination=remove_destination) - stat_d_mv = stat(d_mv) - # make sure d does not exist anymore - @test !ispath(d) - # compare s, with d_mv - @test isdir(s) == isdir(d_mv) - @test islink(s) == islink(d_mv) - islink(s) && @test readlink(s) == readlink(d_mv) - islink(s) && @test isabspath(readlink(s)) == isabspath(readlink(d_mv)) - # all should contain 1 file named "c.txt" - @test "c.txt" in readdir(d_mv) - @test length(readdir(d_mv)) == 1 - # d => d_mv same file/dir - @test Base.samefile(stat_d, stat_d_mv) - end - - ## Test require `remove_destination=true` (remove destination first) for existing - # directories and existing links to directories - # cp ---------------------------------------------------- - mktempdir() do tmpdir - # Setup new copies for the test - maindir1 = joinpath(tmpdir, "maindir1") - maindir2 = joinpath(tmpdir, "maindir2") - mkdir(maindir1) - mkdir(maindir2) - test_src_paths1, test_new_paths1 = setup_dirs(maindir1) - test_src_paths2, test_new_paths2 = setup_dirs(maindir2) - for (s, d) in zip(test_src_paths1, test_new_paths1) - cp_follow_symlinks_false_check(s, d) - end - for (s, d) in zip(test_src_paths2, test_new_paths2) - cp_follow_symlinks_false_check(s, d) - end - # Test require `remove_destination=true` - for s in test_src_paths1 - for d in test_new_paths2 - @test_throws ArgumentError cp(s, d; remove_destination=false) - @test_throws ArgumentError cp(s, d; remove_destination=false, follow_symlinks=true) - end - end - # Test remove the existing path first and copy - # need to use here the test_src_paths2: - # otherwise ArgumentError: 'src' and 'dst' refer to the same file/dir. - for (s, d) in zip(test_src_paths2, test_new_paths1) - cp_follow_symlinks_false_check(s, d; remove_destination=true) - end - # Test remove the existing path first and copy an empty dir - emptydir = joinpath(maindir1, "emptydir") - mkdir(emptydir) - for d in test_new_paths1 - cp(emptydir, d; remove_destination=true, follow_symlinks=false) - # Expect no link because a dir is copied (follow_symlinks=false does not effect this) - @test isdir(d) && !islink(d) - # none should contain any file - @test isempty(readdir(d)) - end - end - # mv ---------------------------------------------------- - mktempdir() do tmpdir - # Setup new copies for the test - maindir1 = joinpath(tmpdir, "maindir1") - maindir2 = joinpath(tmpdir, "maindir2") - mkdir(maindir1) - mkdir(maindir2) - test_src_paths1, test_new_paths1 = setup_dirs(maindir1) - test_src_paths2, test_new_paths2 = setup_dirs(maindir2) - for (s, d) in zip(test_src_paths1, test_new_paths1) - cp_follow_symlinks_false_check(s, d; remove_destination=true) - end - for (s, d) in zip(test_src_paths2, test_new_paths2) - cp_follow_symlinks_false_check(s, d; remove_destination=true) - end - - # Test require `remove_destination=true` - for s in test_src_paths1 - for d in test_new_paths2 - @test_throws ArgumentError mv(s, d; remove_destination=false) - end - end - # Test remove the existing path first and move - # need to use here the test_src_paths2: - # otherwise ArgumentError: 'src' and 'dst' refer to the same file/dir.This is not supported. - for (s, d) in zip(test_src_paths2, test_new_paths1) - d_mv = joinpath(dirname(d), "$(basename(d))_mv") - mv_check(s, d, d_mv; remove_destination=true) - end - end - - # Test full: absolute and relative directory links - # cp / mv ---------------------------------------------------- - mktempdir() do tmpdir - maindir = joinpath(tmpdir, "mytestdir") - mkdir(maindir) - targetdir = abspath(joinpath(maindir, "targetdir")) - mkdir(targetdir) - subdir1 = joinpath(maindir, "subdir1") - mkdir(subdir1) - - cfile = abspath(joinpath(maindir, "c.txt")) - write(cfile, "This is c.txt - 这是一个文件") - write(abspath(joinpath(targetdir, "file1.txt")), - "This is file1.txt - 这是一个文件") - - abs_dl = joinpath(maindir, "abs_linkto_targetdir") - symlink(targetdir, abs_dl) - # Setup relative links - cd(subdir1) - rel_dl = "rel_linkto_targetdir" - rel_dir = joinpath("..", "targetdir") - symlink(rel_dir, rel_dl) - cd(pwd_) - # TEST: Directory with links: Test each option - maindir_new = joinpath(dirname(maindir),"maindir_new") - maindir_new_keepsym = joinpath(dirname(maindir),"maindir_new_keepsym") - cp_and_test(maindir, maindir_new, true) - cp_and_test(maindir, maindir_new_keepsym, false) - - # mv ---------------------------------------------------- - # move the 3 maindirs - for d in [maindir_new, maindir_new_keepsym, maindir] - d_mv = joinpath(dirname(d), "$(basename(d))_mv") - mv(d, d_mv; remove_destination=true) - end - end - - # issue ---------------------------------------------------- - # Check for issue when: (src == dst) or when one is a link to the other - # https://github.com/JuliaLang/julia/pull/11172#issuecomment-100391076 - mktempdir() do tmpdir - test_src_paths1, test_new_paths1 = setup_dirs(tmpdir) - dirs = [joinpath(tmpdir, "src"), joinpath(tmpdir, "abs_dirlink"), joinpath(tmpdir, "rel_dirlink")] - for src in dirs - for dst in dirs - # cptree - @test_throws ArgumentError Base.cptree(src,dst; remove_destination=true, follow_symlinks=false) - @test_throws ArgumentError Base.cptree(src,dst; remove_destination=true, follow_symlinks=true) - # cp - @test_throws ArgumentError cp(src,dst; remove_destination=true, follow_symlinks=false) - @test_throws ArgumentError cp(src,dst; remove_destination=true, follow_symlinks=true) - # mv - @test_throws ArgumentError mv(src,dst; remove_destination=true) - end - end - end - # None existing src - mktempdir() do tmpdir - none_existing_src = joinpath(tmpdir, "none_existing_src") - dst = joinpath(tmpdir, "dst") - @test !ispath(none_existing_src) - # cptree - @test_throws ArgumentError Base.cptree(none_existing_src,dst; remove_destination=true, follow_symlinks=false) - @test_throws ArgumentError Base.cptree(none_existing_src,dst; remove_destination=true, follow_symlinks=true) - # cp - @test_throws Base.UVError cp(none_existing_src,dst; remove_destination=true, follow_symlinks=false) - @test_throws Base.UVError cp(none_existing_src,dst; remove_destination=true, follow_symlinks=true) - # mv - @test_throws Base.UVError mv(none_existing_src,dst; remove_destination=true) - end -end - -# issue #10506 #10434 -## Tests for files and links to files as well as directories and links to directories -if !is_windows() - function setup_files(tmpdir) - srcfile = joinpath(tmpdir, "srcfile.txt") - hidden_srcfile = joinpath(tmpdir, ".hidden_srcfile.txt") - srcfile_new = joinpath(tmpdir, "srcfile_new.txt") - hidden_srcfile_new = joinpath(tmpdir, ".hidden_srcfile_new.txt") - file_txt = "This is some text with unicode - 这是一个文件" - write(srcfile, file_txt) - write(hidden_srcfile, file_txt) - abs_filelink = joinpath(tmpdir, "abs_filelink") - symlink(abspath(srcfile), abs_filelink) - cd(tmpdir) - rel_filelink = "rel_filelink" - symlink("srcfile.txt", rel_filelink) - cd(pwd_) - - abs_filelink_new = joinpath(tmpdir, "abs_filelink_new") - path_rel_filelink = joinpath(tmpdir, rel_filelink) - path_rel_filelink_new = joinpath(tmpdir, "rel_filelink_new") - - test_src_paths = [srcfile, hidden_srcfile, abs_filelink, path_rel_filelink] - test_new_paths = [srcfile_new, hidden_srcfile_new, abs_filelink_new, path_rel_filelink_new] - return test_src_paths, test_new_paths, file_txt - end - - function cp_follow_symlinks_false_check(s, d, file_txt; remove_destination=false) - cp(s, d; remove_destination=remove_destination, follow_symlinks=false) - @test isfile(s) == isfile(d) - @test islink(s) == islink(d) - islink(s) && @test readlink(s) == readlink(d) - islink(s) && @test isabspath(readlink(s)) == isabspath(readlink(d)) - # all should contain the same - @test readstring(s) == readstring(d) == file_txt - end - - function mv_check(s, d, d_mv, file_txt; remove_destination=true) - # setup dest - cp(s, d; remove_destination=true, follow_symlinks=false) - stat_d = stat(d) - # mv(rename) dst to dst_mv - mv(d, d_mv; remove_destination=remove_destination) - stat_d_mv = stat(d_mv) - # make sure d does not exist anymore - @test !ispath(d) - # comare s, with d_mv - @test isfile(s) == isfile(d_mv) - @test islink(s) == islink(d_mv) - islink(s) && @test readlink(s) == readlink(d_mv) - islink(s) && @test isabspath(readlink(s)) == isabspath(readlink(d_mv)) - # all should contain the same - @test readstring(s) == readstring(d_mv) == file_txt - # d => d_mv same file/dir - @test Base.samefile(stat_d, stat_d_mv) - end - - ## Test require `remove_destination=true` (remove destination first) for existing - # files and existing links to files - # cp ---------------------------------------------------- - mktempdir() do tmpdir - # Setup new copies for the test - maindir1 = joinpath(tmpdir, "maindir1") - maindir2 = joinpath(tmpdir, "maindir2") - mkdir(maindir1) - mkdir(maindir2) - test_src_paths1, test_new_paths1, file_txt1 = setup_files(maindir1) - test_src_paths2, test_new_paths2, file_txt2 = setup_files(maindir2) - for (s, d) in zip(test_src_paths1, test_new_paths1) - cp_follow_symlinks_false_check(s, d, file_txt1) - end - for (s, d) in zip(test_src_paths2, test_new_paths2) - cp_follow_symlinks_false_check(s, d, file_txt2) - end - # Test require `remove_destination=true` - for s in test_src_paths1 - for d in test_new_paths2 - @test_throws ArgumentError cp(s, d; remove_destination=false) - @test_throws ArgumentError cp(s, d; remove_destination=false, follow_symlinks=true) - end - end - # Test remove the existing path first and copy - # need to use here the test_src_paths2: - # otherwise ArgumentError: 'src' and 'dst' refer to the same file/dir.This is not supported. - for (s, d) in zip(test_src_paths2, test_new_paths1) - cp_follow_symlinks_false_check(s, d, file_txt2; remove_destination=true) - end - # Test remove the existing path first and copy an other file - otherfile = joinpath(tmpdir, "otherfile.txt") - otherfile_content = "This is otherfile.txt with unicode - 这是一个文件" - write(otherfile, otherfile_content) - for d in test_new_paths1 - cp(otherfile, d; remove_destination=true, follow_symlinks=false) - # Expect no link because a file is copied (follow_symlinks=false does not effect this) - @test isfile(d) && !islink(d) - # all should contain otherfile_content - @test readstring(d) == otherfile_content - end - end - # mv ---------------------------------------------------- - mktempdir() do tmpdir - # Setup new copies for the test - maindir1 = joinpath(tmpdir, "maindir1") - maindir2 = joinpath(tmpdir, "maindir2") - mkdir(maindir1) - mkdir(maindir2) - test_src_paths1, test_new_paths1, file_txt1 = setup_files(maindir1) - test_src_paths2, test_new_paths2, file_txt2 = setup_files(maindir2) - for (s, d) in zip(test_src_paths1, test_new_paths1) - cp_follow_symlinks_false_check(s, d, file_txt1) - end - for (s, d) in zip(test_src_paths2, test_new_paths2) - cp_follow_symlinks_false_check(s, d, file_txt2) - end - # Test require `remove_destination=true` - for s in test_src_paths1 - for d in test_new_paths2 - @test_throws ArgumentError mv(s, d; remove_destination=false) - end - end - # Test remove the existing path first and move - # need to use here the test_src_paths2: - # otherwise ArgumentError: 'src' and 'dst' refer to the same file/dir.This is not supported. - for (s, d) in zip(test_src_paths2, test_new_paths1) - d_mv = joinpath(dirname(d), "$(basename(d))_mv") - mv_check(s, d, d_mv, file_txt2; remove_destination=true) - end - end - - # Test full: absolute and relative file links and absolute and relative directory links - # cp / mv ---------------------------------------------------- - mktempdir() do tmpdir - maindir = joinpath(tmpdir, "mytestdir") - mkdir(maindir) - targetdir = abspath(joinpath(maindir, "targetdir")) - mkdir(targetdir) - subdir1 = joinpath(maindir, "subdir1") - mkdir(subdir1) - - cfile = abspath(joinpath(maindir, "c.txt")) - write(cfile, "This is c.txt - 这是一个文件") - write(abspath(joinpath(targetdir, "file1.txt")), - "This is file1.txt - 这是一个文件") - - abs_fl = joinpath(maindir, "abs_linkto_c.txt") - symlink(cfile, abs_fl) - abs_dl = joinpath(maindir, "abs_linkto_targetdir") - symlink(targetdir, abs_dl) - # Setup relative links - cd(subdir1) - rel_fl = "rel_linkto_c.txt" - rel_file = joinpath("..", "c.txt") - symlink(rel_file, rel_fl) - rel_dl = "rel_linkto_targetdir" - rel_dir = joinpath("..", "targetdir") - symlink(rel_dir, rel_dl) - rel_file_read_txt = readstring(rel_file) - cd(pwd_) - # Setup copytodir - copytodir = joinpath(tmpdir, "copytodir") - mkdir(copytodir) - cp(cfile, joinpath(copytodir, basename(cfile))) - subdir_test = joinpath(copytodir, "subdir_test") - mkdir(subdir_test) - cp(targetdir, joinpath(copytodir, basename(targetdir)); follow_symlinks=false) - # TEST: Directory with links: Test each option - maindir_new = joinpath(dirname(maindir),"maindir_new") - maindir_new_keepsym = joinpath(dirname(maindir),"maindir_new_keepsym") - cp_and_test(maindir, maindir_new, true) - cp_and_test(maindir, maindir_new_keepsym, false) - - ## Tests single Files, File Links - rel_flpath = joinpath(subdir1, rel_fl) - # `cp file` - cp_and_test(cfile, joinpath(copytodir,"cfile_new.txt"), true) - cp_and_test(cfile, joinpath(copytodir,"cfile_new_keepsym.txt"), false) - # `cp absolute file link` - cp_and_test(abs_fl, joinpath(copytodir,"abs_fl_new.txt"), true) - cp_and_test(abs_fl, joinpath(copytodir,"abs_fl_new_keepsym.txt"), false) - # `cp relative file link` - cp_and_test(rel_flpath, joinpath(subdir_test,"rel_fl_new.txt"), true) - cp_and_test(rel_flpath, joinpath(subdir_test,"rel_fl_new_keepsym.txt"), false) - - # mv ---------------------------------------------------- - # move all 4 existing dirs - # As expected this will leave some absolute links broken #11145#issuecomment-99315168 - for d in [copytodir, maindir_new, maindir_new_keepsym, maindir] - d_mv = joinpath(dirname(d), "$(basename(d))_mv") - mv(d, d_mv; remove_destination=true) - end - end - # issue ---------------------------------------------------- - # Check for issue when: (src == dst) or when one is a link to the other - # https://github.com/JuliaLang/julia/pull/11172#issuecomment-100391076 - mktempdir() do tmpdir - test_src_paths, test_new_paths, file_txt = setup_files(tmpdir) - files = [joinpath(tmpdir, "srcfile.txt"), joinpath(tmpdir, "abs_filelink"), joinpath(tmpdir, "rel_filelink")] - for src in files - for dst in files - # cptree - @test_throws ArgumentError Base.cptree(src,dst; remove_destination=true, follow_symlinks=false) - @test_throws ArgumentError Base.cptree(src,dst; remove_destination=true, follow_symlinks=true) - # cp - @test_throws ArgumentError cp(src,dst; remove_destination=true, follow_symlinks=false) - @test_throws ArgumentError cp(src,dst; remove_destination=true, follow_symlinks=true) - # mv - @test_throws ArgumentError mv(src,dst; remove_destination=true) - end - end - end - # None existing src: not needed here as it is done above with the directories. -end - - -################### -# FILE* interface # -################### - -function test_LibcFILE(FILEp) - buf = Array{UInt8}(8) - str = ccall(:fread, Csize_t, (Ptr{Void}, Csize_t, Csize_t, Ptr{Void}), buf, 1, 8, FILEp) - @test String(buf) == "Hello, w" - @test position(FILEp) == 8 - seek(FILEp, 5) - @test position(FILEp) == 5 - close(FILEp) -end - -let f = open(file, "w") - write(f, "Hello, world!") - close(f) - f = open(file, "r") - test_LibcFILE(convert(Libc.FILE, f)) - close(f) - if is_windows() - f = RawFD(ccall(:_open, Cint, (Cstring, Cint), file, Base.Filesystem.JL_O_RDONLY)) - else - f = RawFD(ccall(:open, Cint, (Cstring, Cint), file, Base.Filesystem.JL_O_RDONLY)) - end - test_LibcFILE(Libc.FILE(f, Libc.modestr(true, false))) -end - -# issue #10994: pathnames cannot contain embedded NUL chars -for f in (mkdir, cd, Base.Filesystem.unlink, readlink, rm, touch, readdir, mkpath, - stat, lstat, ctime, mtime, filemode, filesize, uperm, gperm, operm, touch, - isblockdev, ischardev, isdir, isfifo, isfile, islink, ispath, issetgid, - issetuid, issocket, issticky, realpath, watch_file, poll_file) - @test_throws ArgumentError f("adir\0bad") -end -@test_throws ArgumentError chmod("ba\0d", 0o222) -@test_throws ArgumentError open("ba\0d", "w") -@test_throws ArgumentError cp(file, "ba\0d") -@test_throws ArgumentError mv(file, "ba\0d") -if !is_windows() || (Sys.windows_version() >= Sys.WINDOWS_VISTA_VER) - @test_throws ArgumentError symlink(file, "ba\0d") -else - @test_throws ErrorException symlink(file, "ba\0d") -end -@test_throws ArgumentError download("good", "ba\0d") -@test_throws ArgumentError download("ba\0d", "good") - -################### -# walkdir # -################### - -dirwalk = mktempdir() -cd(dirwalk) do - for i=1:2 - mkdir("sub_dir$i") - open("file$i", "w") do f end - - mkdir(joinpath("sub_dir1", "subsub_dir$i")) - touch(joinpath("sub_dir1", "file$i")) - end - touch(joinpath("sub_dir2", "file_dir2")) - has_symlinks = !is_windows() || (Sys.windows_version() >= Sys.WINDOWS_VISTA_VER) - follow_symlink_vec = has_symlinks ? [true, false] : [false] - has_symlinks && symlink(abspath("sub_dir2"), joinpath("sub_dir1", "link")) - for follow_symlinks in follow_symlink_vec - chnl = walkdir(".", follow_symlinks=follow_symlinks) - root, dirs, files = take!(chnl) - @test root == "." - @test dirs == ["sub_dir1", "sub_dir2"] - @test files == ["file1", "file2"] - - root, dirs, files = take!(chnl) - @test root == joinpath(".", "sub_dir1") - @test dirs == (has_symlinks ? ["link", "subsub_dir1", "subsub_dir2"] : ["subsub_dir1", "subsub_dir2"]) - @test files == ["file1", "file2"] - - root, dirs, files = take!(chnl) - if follow_symlinks - @test root == joinpath(".", "sub_dir1", "link") - @test dirs == [] - @test files == ["file_dir2"] - root, dirs, files = take!(chnl) - end - for i=1:2 - @test root == joinpath(".", "sub_dir1", "subsub_dir$i") - @test dirs == [] - @test files == [] - root, dirs, files = take!(chnl) - end - - @test root == joinpath(".", "sub_dir2") - @test dirs == [] - @test files == ["file_dir2"] - end - - for follow_symlinks in follow_symlink_vec - chnl = walkdir(".", follow_symlinks=follow_symlinks, topdown=false) - root, dirs, files = take!(chnl) - if follow_symlinks - @test root == joinpath(".", "sub_dir1", "link") - @test dirs == [] - @test files == ["file_dir2"] - root, dirs, files = take!(chnl) - end - for i=1:2 - @test root == joinpath(".", "sub_dir1", "subsub_dir$i") - @test dirs == [] - @test files == [] - root, dirs, files = take!(chnl) - end - @test root == joinpath(".", "sub_dir1") - @test dirs == (has_symlinks ? ["link", "subsub_dir1", "subsub_dir2"] : ["subsub_dir1", "subsub_dir2"]) - @test files == ["file1", "file2"] - - root, dirs, files = take!(chnl) - @test root == joinpath(".", "sub_dir2") - @test dirs == [] - @test files == ["file_dir2"] - - root, dirs, files = take!(chnl) - @test root == "." - @test dirs == ["sub_dir1", "sub_dir2"] - @test files == ["file1", "file2"] - end - #test of error handling - chnl_error = walkdir(".") - chnl_noerror = walkdir(".", onerror=x->x) - root, dirs, files = take!(chnl_error) - @test root == "." - @test dirs == ["sub_dir1", "sub_dir2"] - @test files == ["file1", "file2"] - - rm(joinpath("sub_dir1"), recursive=true) - @test_throws SystemError take!(chnl_error) # throws an error because sub_dir1 do not exist - - root, dirs, files = take!(chnl_noerror) - @test root == "." - @test dirs == ["sub_dir1", "sub_dir2"] - @test files == ["file1", "file2"] - - root, dirs, files = take!(chnl_noerror) # skips sub_dir1 as it no longer exist - @test root == joinpath(".", "sub_dir2") - @test dirs == [] - @test files == ["file_dir2"] -end -rm(dirwalk, recursive=true) - -############ -# Clean up # -############ -if !is_windows() - rm(link) - rm(rellink) -end -if !is_windows() || (Sys.windows_version() >= Sys.WINDOWS_VISTA_VER) - rm(dirlink) - rm(relsubdirlink) -end -rm(file) -rm(subdir) -rm(subdir2) -rm(dir) - -@test !ispath(file) -@test !ispath(dir) - -# issue #9687 -let n = tempname() - w = open(n, "a") - io = open(n) - write(w, "A"); flush(w) - @test read(io) == UInt8[0x41] - @test read(io) == UInt8[] - write(w, "A"); flush(w) - @test read(io) == UInt8[0x41] - close(io); close(w) - rm(n) -end - -#issue #12992 -function test_12992() - pfw = PollingFileWatcher(@__FILE__, 0.01) - close(pfw) - pfw = PollingFileWatcher(@__FILE__, 0.01) - close(pfw) - pfw = PollingFileWatcher(@__FILE__, 0.01) - close(pfw) - gc() - gc() -end - -# Make sure multiple close is fine -function test2_12992() - pfw = PollingFileWatcher(@__FILE__, 0.01) - close(pfw) - close(pfw) - pfw = PollingFileWatcher(@__FILE__, 0.01) - close(pfw) - close(pfw) - pfw = PollingFileWatcher(@__FILE__, 0.01) - close(pfw) - close(pfw) - gc() - gc() -end - -test_12992() -test_12992() -test_12992() - -test2_12992() -test2_12992() -test2_12992() - -# issue 13559 -if !is_windows() -function test_13559() - fn = tempname() - run(`mkfifo $fn`) - # use subprocess to write 127 bytes to FIFO - writer_cmds = "x=open(\"$fn\", \"w\"); for i=1:127 write(x,0xaa); flush(x); sleep(0.1) end; close(x); quit()" - open(pipeline(`$(Base.julia_cmd()) --startup-file=no -e $writer_cmds`, stderr=STDERR)) - #quickly read FIFO, draining it and blocking but not failing with EOFError yet - r = open(fn, "r") - # 15 proper reads - for i=1:15 - @test read(r, Int64) == -6148914691236517206 - end - # last read should throw EOFError when FIFO closes, since there are only 7 bytes available. - @test_throws EOFError read(r, Int64) - close(r) - rm(fn) -end -test_13559() -end -@test_throws ArgumentError mkpath("fakepath",-1) diff --git a/julia-0.6.3/share/julia/test/float16.jl b/julia-0.6.3/share/julia/test/float16.jl deleted file mode 100644 index e9a1883..0000000 --- a/julia-0.6.3/share/julia/test/float16.jl +++ /dev/null @@ -1,157 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -using Base.Test - -f = Float16(2.) -g = Float16(1.) - -@test f >= g -@test f > g -@test g < f -@test g <= g -@test all([g g] .< [f f]) -@test all([g g] .<= [f f]) -@test all([f f] .> [g g]) -@test all([f f] .>= [g g]) -@test isless(g, f) -@test !isless(f, g) - -@test convert(Bool,Float16(0.0)) == false -@test convert(Bool,Float16(1.0)) == true -@test_throws InexactError convert(Bool,Float16(0.1)) - -@test convert(Int128,Float16(-2.0)) == Int128(-2) -@test convert(UInt128,Float16(2.0)) == UInt128(2) - -# convert(::Type{Int128}, x::Float16) -@test convert(Int128, Float16(1.0)) === Int128(1.0) -@test convert(Int128, Float16(-1.0)) === Int128(-1.0) -@test_throws InexactError convert(Int128, Float16(3.5)) - -# convert(::Type{UInt128}, x::Float16) -@test convert(UInt128, Float16(1.0)) === UInt128(1.0) -@test_throws InexactError convert(UInt128, Float16(3.5)) -@test_throws InexactError convert(UInt128, Float16(-1)) - -@test Float16(0.5f0)^2 ≈ Float16(0.5f0^2) -@test round(Int,Float16(0.5f0)) == round(Int,0.5f0) -@test trunc(Int,Float16(0.9f0)) === trunc(Int,0.9f0) === 0 -@test floor(Int,Float16(0.9f0)) === floor(Int,0.9f0) === 0 -@test trunc(Int,Float16(1)) === 1 -@test floor(Int,Float16(1)) === 1 -@test ceil(Int,Float16(0.1f0)) === ceil(Int,0.1f0) === 1 -@test ceil(Int,Float16(0)) === ceil(Int,0) === 0 -@test round(Float16(0.1f0)) == round(0.1f0) == 0 -@test round(Float16(0.9f0)) == round(0.9f0) == 1 -@test trunc(Float16(0.9f0)) == trunc(0.9f0) == 0 -@test floor(Float16(0.9f0)) == floor(0.9f0) == 0 -@test trunc(Float16(1)) === Float16(1) -@test floor(Float16(1)) === Float16(1) -@test ceil(Float16(0.1)) == ceil(0.1) -@test ceil(Float16(0.9)) == ceil(0.9) -@test unsafe_trunc(UInt8, Float16(3)) === 0x03 -@test unsafe_trunc(Int16, Float16(3)) === Int16(3) -@test unsafe_trunc(UInt128, Float16(3)) === UInt128(3) -@test unsafe_trunc(Int128, Float16(3)) === Int128(3) -@test unsafe_trunc(Int16, NaN16) === Int16(0) #18771 -@test fma(Float16(0.1),Float16(0.9),Float16(0.5)) ≈ fma(0.1,0.9,0.5) -@test muladd(Float16(0.1),Float16(0.9),Float16(0.5)) ≈ muladd(0.1,0.9,0.5) -@test convert(Int128,Float16(-1.0)) == Int128(-1) -@test convert(UInt128,Float16(5.0)) == UInt128(5) - -@test -f === Float16(-2.) - -@test f+g === Float16(3f0) -@test f-g === Float16(1f0) -@test f*g === Float16(2f0) -@test f/g === Float16(2f0) -@test f^g === Float16(2f0) -@test f^1 === Float16(2f0) -@test f^-g === Float16(0.5f0) - -@test f + 2 === Float16(4f0) -@test f - 2 === Float16(0f0) -@test f*2 === Float16(4f0) -@test f/2 === Float16(1f0) -@test f + 2. === 4. -@test f - 2. === 0. -@test f*2. === 4. -@test f/2. === 1. - -@test sin(f) ≈ sin(2f0) - -@test isnan(NaN16) -@test isnan(-NaN16) -@test !isnan(Inf16) -@test !isnan(-Inf16) -@test !isnan(Float16(2.6)) -@test NaN16 != NaN16 -@test isequal(NaN16, NaN16) -@test repr(NaN16) == "NaN16" -@test sprint(showcompact, NaN16) == "NaN" - -@test isinf(Inf16) -@test isinf(-Inf16) -@test !isinf(NaN16) -@test !isinf(-NaN16) -@test !isinf(Float16(2.6)) -@test Inf16 == Inf16 -@test Inf16 != -Inf16 -@test -Inf16 < Inf16 -@test isequal(Inf16, Inf16) -@test repr(Inf16) == "Inf16" -@test sprint(showcompact, Inf16) == "Inf" - -@test repr(Float16(44099)) == "Float16(4.41e4)" - -for z1 in (Float16(0.0), Float16(-0.0)), z2 in (Float16(0.0), Float16(-0.0)) - @test z1 == z2 - @test isequal(z1, z1) - @test z1 === z1 - for elty in (Float32, Float64) - z3 = convert(elty, z2) - @test z1==z3 - end -end - -@test Float16(2.5) == Float16(2.5) -@test Float16(2.5) != Float16(2.6) -@test isequal(Float16(0.0), Float16(0.0)) -@test !isequal(Float16(-0.0), Float16(0.0)) -@test !isequal(Float16(0.0), Float16(-0.0)) - -@test isnan(reinterpret(Float16,0x7c01)) -@test !isinf(reinterpret(Float16,0x7c01)) - -@test nextfloat(Inf16) === Inf16 -@test prevfloat(-Inf16) === -Inf16 - -# rounding in conversions -let - for f in [.3325f0, -.3325f0] - f16 = Float16(f) - # need to round away from 0. make sure we picked closest number. - @test abs(f-f16) < abs(f-nextfloat(f16)) - @test abs(f-f16) < abs(f-prevfloat(f16)) - end - # halfway between and last bit is 1 - f = reinterpret(Float32, 0b00111110101010100011000000000000) - @test Float32(Float16(f)) === reinterpret(Float32, 0b00111110101010100100000000000000) - # halfway between and last bit is 0 - f = reinterpret(Float32, 0b00111110101010100001000000000000) - @test Float32(Float16(f)) === reinterpret(Float32, 0b00111110101010100000000000000000) -end - -# issue #5948 -@test string(reinterpret(Float16, 0x7bff)) == "6.55e4" - -@test log10(Float16(100)) == Float16(2.0) - -# #9939 (and #9897) -@test rationalize(Float16(0.1)) == 1//10 - -# issue #17148 -@test rem(Float16(1.2), Float16(one(1.2))) == 0.20019531f0 - -# no domain error is thrown for negative values -@test cbrt(Float16(-1.0)) == -1.0 diff --git a/julia-0.6.3/share/julia/test/floatapprox.jl b/julia-0.6.3/share/julia/test/floatapprox.jl deleted file mode 100644 index 0f09312..0000000 --- a/julia-0.6.3/share/julia/test/floatapprox.jl +++ /dev/null @@ -1,71 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -# Floating point numbers - basic tests -@test 4.00000000000001 ≈ 4.0 -@test 5.0 ≈ 4.999999999999993 -@test 4.000000002 ≉ 4.00300002 - -# Other tolerance levels -@test 4.32 ≈ 4.3 rtol=0.1 atol=0.01 -@test 1.001 ≈ 1.002 rtol=0.001 atol=0.0001 -@test 4.5 ≉ 4.9 rtol=0.001 atol=0.001 - -# Complex numbers -@test 1.0 + 1.0im ≈ 1.0 + 1.00000000000001im -@test 0.9999999999999 + 1.0im ≈ 1.0 + 1.000000000000001im -@test 0.9999 + 1.0im ≈ 1.0 + 1.1im rtol=0.0001 atol=1.1 - -# Complex <-> reals -@test 1.0 + 0im ≈ 1.0000000000001 -@test 0.9999999999999 ≈ 1.0 + 0im -@test 1.0+1im ≉ 1.000000000000001 - -# Comparing NaNs -@test 4.0 ≉ NaN -@test NaN ≉ 4.0 -@test complex(2.3,NaN) ≉ complex(NaN,2.3) -@test NaN ≉ NaN -@test complex(NaN,NaN) ≉ complex(NaN,NaN) -@test complex(NaN,2.3) ≉ complex(NaN,2.3) -@test complex(2.3,NaN) ≉ complex(2.3,NaN) - -# Comparing Infs -@test Inf ≈ Inf -@test Inf ≉ 1 -@test Inf ≉ -Inf -@test complex(0.0,Inf) ≈ complex(0.0,Inf) -@test complex(0.0,Inf) ≉ complex(0.0,-Inf) - -# Tests for integers and rationals -@test 4 ≈ 4 -@test 4 ≈ 5 atol=1 -@test 4 ≉ 6 atol=1 -@test 4 ≉ 5 - -@test 1//2+3im ≈ 1//2+3im -@test 1//3 ≈ 0.33333333333333333 -@test 1//3 ≈ 0.3333 rtol=0.0001 atol=0.0001 -@test 1+1im ≈ 1im+1 - -# Notably missing from this test suite at the moment -# * Tests for other magnitudes of numbers - very small, very big, and combinations of small and big -# * Tests for various odd combinations of types, e.g. x::Integer ≈ y::Rational - -# issue #12375: -@test 1e17 ≉ 1 - -# Tests for arrays: -@test [1,2,3] ≈ [1,2,3+1e-9] -@test [0,1] ≈ [1e-9, 1] -@test [0,Inf] ≈ [0,Inf] -@test [0,Inf] ≉ [0,-Inf] - -# issue #19936 -for elty in (Float16,Float32,Float64) - nan = elty(NaN) - half = elty(0.5) - @test nan ≉ nan - @test nan ≈ nan nans=true - @test [half, nan, half] ≉ [half, nan, half] - @test [half, nan, half] ≈ [half, nan, half] nans=true -end diff --git a/julia-0.6.3/share/julia/test/floatfuncs.jl b/julia-0.6.3/share/julia/test/floatfuncs.jl deleted file mode 100644 index 30e189b..0000000 --- a/julia-0.6.3/share/julia/test/floatfuncs.jl +++ /dev/null @@ -1,74 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -using Base.Test - -# test the basic floating point functions - -# flipsign - -for elty in (Float32,Float64) - x = convert(elty,-2.0) - x = flipsign(x,-1.0) - @test flipsign(x,big(-1.0)) == convert(elty,-2.0) -end - -# maxintfloat - -@test maxintfloat(Float16) === Float16(2048f0) -for elty in (Float16,Float32,Float64) - @test maxintfloat(rand(elty)) === maxintfloat(elty) -end -@test maxintfloat() === maxintfloat(Float64) -@test maxintfloat(Float64, Int32) === 2147483647.0 -@test maxintfloat(Float32, Int32) === maxintfloat(Float32) -@test maxintfloat(Float64, Int16) === 32767.0 -@test maxintfloat(Float64, Int64) === maxintfloat(Float64) - -# isinteger -for elty in (Float16,Float32,Float64) - @test !isinteger(elty(1.2)) - @test isinteger(elty(12)) - @test isinteger(zero(elty)) - @test isinteger(-zero(elty)) - @test !isinteger(nextfloat(zero(elty))) - @test !isinteger(prevfloat(zero(elty))) - @test isinteger(maxintfloat(elty)) - @test isinteger(-maxintfloat(elty)) - @test !isinteger(elty(Inf)) - @test !isinteger(-elty(Inf)) - @test !isinteger(elty(NaN)) -end - -# num2hex, hex2num -for elty in (Float16,Float32,Float64), _ = 1:10 - x = rand(elty) - @test hex2num(num2hex(x)) ≈ x -end - -# round -for elty in (Float32,Float64) - x = rand(elty) - A = fill(x,(10,10)) - @test round.(A,RoundToZero) == fill(trunc(x),(10,10)) - @test round.(A,RoundUp) == fill(ceil(x),(10,10)) - @test round.(A,RoundDown) == fill(floor(x),(10,10)) - A = fill(x,(10,10,10)) - @test round.(A,RoundToZero) == fill(trunc(x),(10,10,10)) - @test round.(A,RoundUp) == fill(ceil(x),(10,10,10)) - @test round.(A,RoundDown) == fill(floor(x),(10,10,10)) - for elty2 in (Int32,Int64) - A = fill(x,(10,)) - @test round.(elty2,A,RoundToZero) == fill(trunc(elty2,x),(10,)) - @test round.(elty2,A,RoundUp) == fill(ceil(elty2,x),(10,)) - @test round.(elty2,A,RoundDown) == fill(floor(elty2,x),(10,)) - A = fill(x,(10,10)) - @test round.(elty2,A,RoundToZero) == fill(trunc(elty2,x),(10,10)) - @test round.(elty2,A,RoundUp) == fill(ceil(elty2,x),(10,10)) - @test round.(elty2,A,RoundDown) == fill(floor(elty2,x),(10,10)) - A = fill(x,(10,10,10)) - @test round.(elty2,A,RoundToZero) == fill(trunc(elty2,x),(10,10,10)) - @test round.(elty2,A,RoundUp) == fill(ceil(elty2,x),(10,10,10)) - @test round.(elty2,A,RoundDown) == fill(floor(elty2,x),(10,10,10)) - @test round.(elty2,A) == fill(round(elty2,x),(10,10,10)) - end -end diff --git a/julia-0.6.3/share/julia/test/functional.jl b/julia-0.6.3/share/julia/test/functional.jl deleted file mode 100644 index 5256a54..0000000 --- a/julia-0.6.3/share/julia/test/functional.jl +++ /dev/null @@ -1,144 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -# tests related to functional programming functions and styles - -# map -- array.jl -@test isequal(map((x)->"$x"[end:end], 9:11), ["9", "0", "1"]) -# TODO: @test map!() much more thoroughly -let a = [1.0, 2.0] - map!(sin, a, a) - @test isequal(a, sin.([1.0, 2.0])) -end -# map -- ranges.jl -@test isequal(map(sqrt, 1:5), [sqrt(i) for i in 1:5]) -@test isequal(map(sqrt, 2:6), [sqrt(i) for i in 2:6]) - -# map on ranges should evaluate first value only once (#4453) -let io=IOBuffer(3) - map(x->print(io,x), 1:2) - @test String(take!(io))=="12" -end - -# map over Bottom[] should return Bottom[] -# issue #6719 -@test isequal(typeof(map(x -> x, Array{Union{}}(0))), Array{Union{},1}) - -# maps of tuples (formerly in test/core.jl) -- tuple.jl -@test map((x,y)->x+y,(1,2,3),(4,5,6)) == (5,7,9) -@test map((x,y)->x+y, - (100001,100002,100003), - (100004,100005,100006)) == (200005,200007,200009) - -# maps of strings (character arrays) -- string.jl -@test map((c)->Char(c+1), "abcDEF") == "bcdEFG" - -# issue #10633 -@test isa(map(Integer, Any[1, 2]), Vector{Int}) -@test isa(map(Integer, Any[]), Vector{Integer}) - -# filter -- array.jl -@test isequal(filter(x->(x>1), [0 1 2 3 2 1 0]), [2, 3, 2]) -# TODO: @test_throws isequal(filter(x->x+1, [0 1 2 3 2 1 0]), [2, 3, 2]) -@test isequal(filter(x->(x>10), [0 1 2 3 2 1 0]), []) -@test isequal(filter((ss)->length(ss)==3, ["abcd", "efg", "hij", "klmn", "opq"]), ["efg", "hij", "opq"]) - -# numbers -@test size(collect(1)) == size(1) - -@test isa(collect(Any, [1,2]), Vector{Any}) - -# foreach -let a = [] - foreach(()->push!(a,0)) - @test a == [0] - a = [] - foreach(x->push!(a,x), [1,5,10]) - @test a == [1,5,10] - a = [] - foreach((args...)->push!(a,args), [2,4,6], [10,20,30]) - @test a == [(2,10),(4,20),(6,30)] -end - -# generators (#4470, #14848) -@test sum(i/2 for i=1:2) == 1.5 -@test collect(2i for i=2:5) == [4,6,8,10] -@test collect((i+10j for i=1:2,j=3:4)) == [31 41; 32 42] -@test collect((i+10j for i=1:2,j=3:4,k=1:1)) == reshape([31 41; 32 42], (2,2,1)) - -let A = collect(Base.Generator(x->2x, Real[1.5,2.5])) - @test A == [3,5] - @test isa(A,Vector{Float64}) -end - -let f(g) = (@test size(g.iter)==(2,3)) - f(i+j for i=1:2, j=3:5) -end - -@test collect(Base.Generator(+, [1,2], [10,20])) == [11,22] - -# generator ndims #16394 -let gens_dims = [((i for i = 1:5), 1), - ((i for i = 1:5, j = 1:5), 2), - ((i for i = 1:5, j = 1:5, k = 1:5), 3), - ((i for i = Array{Int}()), 0), - ((i for i = Array{Int}(1)), 1), - ((i for i = Array{Int}(1, 2)), 2), - ((i for i = Array{Int}(1, 2, 3)), 3)] - for (gen, dim) in gens_dims - @test ndims(gen) == ndims(collect(gen)) == dim - end -end - -# generator with destructuring -let d = Dict(:a=>1, :b=>2), a = Dict(3=>4, 5=>6) - @test Dict( v=>(k,) for (k,v) in d) == Dict(2=>(:b,), 1=>(:a,)) - @test Dict( (x,b)=>(c,y) for (x,c) in d, (b,y) in a ) == Dict((:a,5)=>(1,6),(:b,5)=>(2,6),(:a,3)=>(1,4),(:b,3)=>(2,4)) -end - -let i = 1 - local g = (i+j for i=2:2, j=3:3) - @test first(g) == 5 - @test i == 1 -end - -# generators and guards -let gen = (x for x in 1:10) - @test gen.iter == 1:10 - @test gen.f(first(1:10)) == next(gen, start(gen))[1] - for (a,b) in zip(1:10,gen) - @test a == b - end -end - -let gen = (x * y for x in 1:10, y in 1:10) - @test collect(gen) == collect(1:10) .* collect(1:10)' - @test first(gen) == 1 - @test collect(gen)[1:10] == collect(1:10) -end - -let gen = Base.Generator(+, 1:10, 1:10, 1:10) - @test first(gen) == 3 - @test collect(gen) == collect(3:3:30) -end - -let gen = (x for x in 1:10 if x % 2 == 0), gen2 = Iterators.filter(x->x % 2 == 0, x for x in 1:10) - @test collect(gen) == collect(gen2) - @test collect(gen) == collect(2:2:10) -end - -let gen = ((x,y) for x in 1:10, y in 1:10 if x % 2 == 0 && y % 2 == 0), - gen2 = Iterators.filter(x->x[1] % 2 == 0 && x[2] % 2 == 0, (x,y) for x in 1:10, y in 1:10) - @test collect(gen) == collect(gen2) -end - -# generators with nested loops (#4867) -@test [(i,j) for i=1:3 for j=1:i] == [(1,1), (2,1), (2,2), (3,1), (3,2), (3,3)] - -@test [(i,j) for i=1:3 for j=1:i if j>1] == [(2,2), (3,2), (3,3)] - -# issue #18707 -@test [(q,d,n,p) for q = 0:25:100 - for d = 0:10:100-q - for n = 0:5:100-q-d - for p = 100-q-d-n - if p < n < d < q] == [(50,30,15,5), (50,30,20,0), (50,40,10,0), (75,20,5,0)] diff --git a/julia-0.6.3/share/julia/test/goto.jl b/julia-0.6.3/share/julia/test/goto.jl deleted file mode 100644 index 69a1817..0000000 --- a/julia-0.6.3/share/julia/test/goto.jl +++ /dev/null @@ -1,127 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -# Basic goto tests - -function goto_test1() - @goto a - return false - @label a - return true -end -@test goto_test1() - - -@test_throws ErrorException eval( - quote - function goto_test2() - @goto a - @label a - @label a - return - end - end) - - -@test_throws ErrorException eval( - quote - function goto_test3() - @goto a - return - end - end) - - -@test_throws ErrorException eval( - quote - function goto_test4() - @goto a - try - @label a - catch - end - end - end) - - -# test that labels in macros are reassigned -macro goto_test5_macro() - @label a -end - -@test_throws ErrorException eval( - quote - function goto_test5() - @goto a - @goto_test5_macro - return - end - end) - - -@test_throws ErrorException eval( - quote - function goto_test6() - try - @goto a - finally - end - @label a - return - end - end) - - -function goto_test6() - @goto a - @label a -end - -@test goto_test6() === nothing - - -function goto_test7(x) - @label a - if x - @goto a - end -end - -@test goto_test7(false) === nothing - -module GotoMacroTest - macro goto_test8_macro() - quote - function $(esc(:goto_test8))() - @label a - @goto a - end - end - end -end - -GotoMacroTest.@goto_test8_macro - -# issue #15600 -function t0_15600(flag) - flag && @goto return2 - return 1 - @label return2 - return 2 -end -@test t0_15600(true) == 2 -@test t0_15600(false) == 1 -function t1_15600(flag) - flag || @goto return2 - return 1 - @label return2 - return 2 -end -@test t1_15600(true) == 1 -@test t1_15600(false) == 2 - -# issue #15561 -function f15561() - a = @goto crater - @label crater -end -@test f15561() === nothing diff --git a/julia-0.6.3/share/julia/test/grisu.jl b/julia-0.6.3/share/julia/test/grisu.jl deleted file mode 100644 index 5fb6332..0000000 --- a/julia-0.6.3/share/julia/test/grisu.jl +++ /dev/null @@ -1,1753 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -using Base.Grisu - -function trimrep(buffer) - len = length(unsafe_string(pointer(buffer))) - ind = len - for i = len:-1:1 - buffer[i] != 0x30 && break - ind -= 1 - end - buffer[ind+1] = 0 - return unsafe_string(pointer(buffer)) -end - -const bufsize = 500 -buffer = Array{UInt8}(bufsize) -fill!(buffer,0) -bignums = [Grisu.Bignums.Bignum(),Grisu.Bignums.Bignum(),Grisu.Bignums.Bignum(),Grisu.Bignums.Bignum()] - -# Start by checking the byte-order. -ordered = 0x0123456789ABCDEF -@test 3512700564088504e-318 == reinterpret(Float64,ordered) - -min_double64 = 0x0000000000000001 -@test 5e-324 == reinterpret(Float64,min_double64) - -max_double64 = 0x7fefffffffffffff -@test 1.7976931348623157e308 == reinterpret(Float64,max_double64) - -# Start by checking the byte-order. -ordered = 0x01234567 -@test Float32(2.9988165487136453e-38) == reinterpret(Float32,ordered) - -min_float32 = 0x00000001 -@test Float32(1.4e-45) == reinterpret(Float32,min_float32) - -max_float32 = 0x7f7fffff -@test Float32(3.4028234e38) == reinterpret(Float32,max_float32) - -ordered = 0x0123456789ABCDEF -diy_fp = Grisu.Float(reinterpret(Float64,ordered)) -@test UInt64(0x12) - UInt64(0x3FF) - 52 == diy_fp.e % UInt64 -# The 52 mantissa bits, plus the implicit 1 in bit 52 as a UINT64. -@test 0x0013456789ABCDEF== diy_fp.s - -min_double64 = 0x0000000000000001 -diy_fp = Grisu.Float(reinterpret(Float64,min_double64)) -@test -UInt64(0x3FF) - Int64(52) + Int64(1) == diy_fp.e % UInt64 -# This is a denormal so no hidden bit. -@test 1 == diy_fp.s - -max_double64 = 0x7fefffffffffffff -diy_fp = Grisu.Float(reinterpret(Float64,max_double64)) -@test 0x7FE - 0x3FF - 52 == diy_fp.e % UInt64 -@test 0x001fffffffffffff== diy_fp.s - -ordered = 0x01234567 -diy_fp = Grisu.Float(reinterpret(Float32,ordered)) -@test UInt64(0x2) - UInt64(0x7F) - 23 == diy_fp.e % UInt64 -# The 23 mantissa bits, plus the implicit 1 in bit 24 as a uint32_t. -@test 0xA34567 == UInt64(diy_fp.s) - -min_float32 = 0x00000001 -diy_fp = Grisu.Float(reinterpret(Float32,min_float32)) -@test -UInt64(0x7F) - 23 + 1 == diy_fp.e % UInt64 -# This is a denormal so no hidden bit. -@test 1 == UInt64(diy_fp.s) - -max_float32 = 0x7f7fffff -diy_fp = Grisu.Float(reinterpret(Float32,max_float32)) -@test 0xFE - 0x7F - 23 == diy_fp.e % UInt64 -@test 0x00ffffff == UInt64(diy_fp.s) - -ordered = 0x0123456789ABCDEF -diy_fp = Grisu.normalize(Grisu.Float(reinterpret(Float64,ordered))) -@test UInt64(0x12) - UInt64(0x3FF) - 52 - 11 == diy_fp.e % UInt64 -@test 0x0013456789ABCDEF<< 11 == diy_fp.s - -min_double64 = 0x0000000000000001 -diy_fp = Grisu.normalize(Grisu.Float(reinterpret(Float64,min_double64))) -@test -UInt64(0x3FF) - 52 + 1 - 63 == diy_fp.e % UInt64 -# This is a denormal so no hidden bit. -@test 0x8000000000000000== diy_fp.s - -max_double64 = 0x7fefffffffffffff -diy_fp = Grisu.normalize(Grisu.Float(reinterpret(Float64,max_double64))) -@test 0x7FE - 0x3FF - 52 - 11 == diy_fp.e % UInt64 -@test (0x001fffffffffffff<< 11) == diy_fp.s - -min_double64 = 0x0000000000000001 -@test Grisu.isdenormal(reinterpret(Float64,min_double64)) -float_bits = 0x000FFFFFFFFFFFFF -@test Grisu.isdenormal(reinterpret(Float64,float_bits)) -float_bits = 0x0010000000000000 -@test !Grisu.isdenormal(reinterpret(Float64,float_bits)) - -min_float32 = 0x00000001 -@test Grisu.isdenormal(reinterpret(Float32,min_float32)) -float_bits = 0x007FFFFF -@test Grisu.isdenormal(reinterpret(Float32,float_bits)) -float_bits = 0x00800000 -@test !Grisu.isdenormal(reinterpret(Float32,float_bits)) - -diy_fp = Grisu.normalize(Grisu.Float(1.5)) -boundary_minus, boundary_plus = Grisu.normalizedbound(1.5) -@test diy_fp.e == boundary_minus.e -@test diy_fp.e == boundary_plus.e -# 1.5 does not have a significand of the form 2^p (for some p). -# Therefore its boundaries are at the same distance. -@test diy_fp.s - boundary_minus.s == boundary_plus.s - diy_fp.s -@test (1 << 10) == diy_fp.s - boundary_minus.s - -diy_fp = Grisu.normalize(Grisu.Float(1.0)) -boundary_minus, boundary_plus = Grisu.normalizedbound(1.0) -@test diy_fp.e == boundary_minus.e -@test diy_fp.e == boundary_plus.e -# 1.0 does have a significand of the form 2^p (for some p). -# Therefore its lower boundary is twice as close as the upper boundary. -@test boundary_plus.s - diy_fp.s > diy_fp.s - boundary_minus.s -@test (1 << 9) == diy_fp.s - boundary_minus.s -@test (1 << 10) == boundary_plus.s - diy_fp.s - -min_double64 = 0x0000000000000001 -diy_fp = Grisu.normalize(Grisu.Float(reinterpret(Float64,min_double64))) -boundary_minus, boundary_plus = Grisu.normalizedbound(reinterpret(Float64,min_double64)) -@test diy_fp.e == boundary_minus.e -@test diy_fp.e == boundary_plus.e -# min-value does not have a significand of the form 2^p (for some p). -# Therefore its boundaries are at the same distance. -@test diy_fp.s - boundary_minus.s == boundary_plus.s - diy_fp.s -# Denormals have their boundaries much closer. -@test (UInt64(1) << 62) == diy_fp.s - boundary_minus.s - -smallest_normal64 = 0x0010000000000000 -diy_fp = Grisu.normalize(reinterpret(Float64,smallest_normal64)) -boundary_minus, boundary_plus = Grisu.normalizedbound(reinterpret(Float64,smallest_normal64)) -@test diy_fp.e == boundary_minus.e -@test diy_fp.e == boundary_plus.e -# Even though the significand is of the form 2^p (for some p), its boundaries -# are at the same distance. (This is the only exception). -@test diy_fp.s - boundary_minus.s == boundary_plus.s - diy_fp.s -@test (1 << 10) == diy_fp.s - boundary_minus.s - -largest_denormal64 = 0x000FFFFFFFFFFFFF -diy_fp = Grisu.normalize(reinterpret(Float64,largest_denormal64)) -boundary_minus, boundary_plus = Grisu.normalizedbound(reinterpret(Float64,largest_denormal64)) -@test diy_fp.e == boundary_minus.e -@test diy_fp.e == boundary_plus.e -@test diy_fp.s - boundary_minus.s == boundary_plus.s - diy_fp.s -@test (1 << 11) == diy_fp.s - boundary_minus.s - -max_double64 = 0x7fefffffffffffff -diy_fp = Grisu.normalize(reinterpret(Float64,max_double64)) -boundary_minus, boundary_plus = Grisu.normalizedbound(reinterpret(Float64,max_double64)) -@test diy_fp.e == boundary_minus.e -@test diy_fp.e == boundary_plus.e -# max-value does not have a significand of the form 2^p (for some p). -# Therefore its boundaries are at the same distance. -@test diy_fp.s - boundary_minus.s == boundary_plus.s - diy_fp.s -@test (1 << 10) == diy_fp.s - boundary_minus.s - -kOne64 = UInt64(1) -diy_fp = Grisu.normalize(Grisu.Float(Float32(1.5))) -boundary_minus, boundary_plus = Grisu.normalizedbound(Float32(1.5)) -@test diy_fp.e == boundary_minus.e -@test diy_fp.e == boundary_plus.e -# 1.5 does not have a significand of the form 2^p (for some p). -# Therefore its boundaries are at the same distance. -@test diy_fp.s - boundary_minus.s == boundary_plus.s - diy_fp.s -# Normalization shifts the significand by 8 bits. Add 32 bits for the bigger -# data-type, and remove 1 because boundaries are at half a ULP. -@test (kOne64 << 39) == diy_fp.s - boundary_minus.s - -diy_fp = Grisu.normalize(Grisu.Float(Float32(1.0))) -boundary_minus, boundary_plus = Grisu.normalizedbound(Float32(1.0)) -@test diy_fp.e == boundary_minus.e -@test diy_fp.e == boundary_plus.e -# 1.0 does have a significand of the form 2^p (for some p). -# Therefore its lower boundary is twice as close as the upper boundary. -@test boundary_plus.s - diy_fp.s > diy_fp.s - boundary_minus.s -@test (kOne64 << 38) == diy_fp.s - boundary_minus.s -@test (kOne64 << 39) == boundary_plus.s - diy_fp.s - -min_float32 = 0x00000001 -diy_fp = Grisu.normalize(Grisu.Float(reinterpret(Float32,min_float32))) -boundary_minus, boundary_plus = Grisu.normalizedbound(reinterpret(Float32,min_float32)) -@test diy_fp.e == boundary_minus.e -@test diy_fp.e == boundary_plus.e -# min-value does not have a significand of the form 2^p (for some p). -# Therefore its boundaries are at the same distance. -@test diy_fp.s - boundary_minus.s == boundary_plus.s - diy_fp.s -# Denormals have their boundaries much closer. -@test (kOne64 << 62) == diy_fp.s - boundary_minus.s - -smallest_normal32 = 0x00800000 -diy_fp = Grisu.normalize(Grisu.Float(reinterpret(Float32,smallest_normal32))) -boundary_minus, boundary_plus = Grisu.normalizedbound(reinterpret(Float32,smallest_normal32)) -@test diy_fp.e == boundary_minus.e -@test diy_fp.e == boundary_plus.e -# Even though the significand is of the form 2^p (for some p), its boundaries -# are at the same distance. (This is the only exception). -@test diy_fp.s - boundary_minus.s == boundary_plus.s - diy_fp.s -@test (kOne64 << 39) == diy_fp.s - boundary_minus.s - -largest_denormal32 = 0x007FFFFF -diy_fp = Grisu.normalize(Grisu.Float(reinterpret(Float32,largest_denormal32))) -boundary_minus, boundary_plus = Grisu.normalizedbound(reinterpret(Float32,largest_denormal32)) -@test diy_fp.e == boundary_minus.e -@test diy_fp.e == boundary_plus.e -@test diy_fp.s - boundary_minus.s == boundary_plus.s - diy_fp.s -@test (kOne64 << 40) == diy_fp.s - boundary_minus.s - -max_float32 = 0x7f7fffff -diy_fp = Grisu.normalize(Grisu.Float(reinterpret(Float32,max_float32))) -boundary_minus, boundary_plus = Grisu.normalizedbound(reinterpret(Float32,max_float32)) -@test diy_fp.e == boundary_minus.e -@test diy_fp.e == boundary_plus.e -# max-value does not have a significand of the form 2^p (for some p). -# Therefore its boundaries are at the same distance. -@test diy_fp.s - boundary_minus.s == boundary_plus.s - diy_fp.s -@test (kOne64 << 39) == diy_fp.s - boundary_minus.s - -#fastshortest -min_double = 5e-324 -status,len,point = Grisu.fastshortest(min_double, buffer) -@test status -@test "5" == trimrep(buffer) -@test -323 == point -fill!(buffer,0) - -max_double = 1.7976931348623157e308 -status,len,point = Grisu.fastshortest(max_double, buffer) -@test status -@test "17976931348623157" == trimrep(buffer) -@test 309 == point -fill!(buffer,0) - -status,len,point = Grisu.fastshortest(4294967272.0, buffer) -@test status -@test "4294967272" == trimrep(buffer) -@test 10 == point -fill!(buffer,0) - -status,len,point = Grisu.fastshortest(4.1855804968213567e298, buffer) -@test status -@test "4185580496821357" == trimrep(buffer) -@test 299 == point -fill!(buffer,0) - -status,len,point = Grisu.fastshortest(5.5626846462680035e-309, buffer) -@test status -@test "5562684646268003" == trimrep(buffer) -@test -308 == point -fill!(buffer,0) - -status,len,point = Grisu.fastshortest(2147483648.0, buffer) -@test status -@test "2147483648" == trimrep(buffer) -@test 10 == point -fill!(buffer,0) - -status,len,point = Grisu.fastshortest(3.5844466002796428e+298, buffer) -@test !status # Not all Grisu.fastshortest variants manage to compute this number. -if status - @test "35844466002796428" == trimrep(buffer) - @test 299 == point - fill!(buffer,0) -end - -smallest_normal64 = 0x0010000000000000 -v = reinterpret(Float64,smallest_normal64) -status,len,point = Grisu.fastshortest(v, buffer) -if status - @test "22250738585072014" == trimrep(buffer) - @test -307 == point - fill!(buffer,0) -end - -largest_denormal64 = 0x000FFFFFFFFFFFFF -v = reinterpret(Float64,largest_denormal64) -status,len,point = Grisu.fastshortest(v, buffer) -if status - @test "2225073858507201" == trimrep(buffer) - @test -307 == point - fill!(buffer,0) -end - - -min_float = Float32(1e-45) -status,len,point = Grisu.fastshortest(min_float, buffer) -@test status -@test "1" == trimrep(buffer) -@test -44 == point -fill!(buffer,0) - -max_float = 3.4028234f38 #Float32(3.4028234e38) -status,len,point = Grisu.fastshortest(max_float, buffer) -@test status -@test "34028235" == trimrep(buffer) -@test 39 == point -fill!(buffer,0) - -status,len,point = Grisu.fastshortest(Float32(4294967272.0), buffer) -@test status -@test "42949673" == trimrep(buffer) -@test 10 == point -fill!(buffer,0) - -status,len,point = Grisu.fastshortest(Float32(3.32306998946228968226e+35), buffer) -@test status -@test "332307" == trimrep(buffer) -@test 36 == point -fill!(buffer,0) - -status,len,point = Grisu.fastshortest(Float32(1.2341e-41), buffer) -@test status -@test "12341" == trimrep(buffer) -@test -40 == point -fill!(buffer,0) - -status,len,point = Grisu.fastshortest(Float32(3.3554432e7), buffer) -@test status -@test "33554432" == trimrep(buffer) -@test 8 == point -fill!(buffer,0) - -status,len,point = Grisu.fastshortest(Float32(3.26494756798464e14), buffer) -@test status -@test "32649476" == trimrep(buffer) -@test 15 == point -fill!(buffer,0) - -status,len,point = Grisu.fastshortest(Float32(3.91132223637771935344e37), buffer) -if status # Not all Grisu.fastshortest variants manage to compute this number. - @test "39113222" == trimrep(buffer) - @test 38 == point - fill!(buffer,0) -end - -smallest_normal32 = 0x00800000 -v = reinterpret(Float32,smallest_normal32) -status,len,point = Grisu.fastshortest(v, buffer) -if status - @test "11754944" == trimrep(buffer) - @test -37 == point - fill!(buffer,0) -end - -largest_denormal32 = 0x007FFFFF -v = reinterpret(Float32,largest_denormal32) -status,len,point = Grisu.fastshortest(v, buffer) -@test status -@test "11754942" == trimrep(buffer) -@test -37 == point -fill!(buffer,0) - -status,len,point = Grisu.fastprecision(1.0, 3, buffer) -@test status -@test 3 >= len-1 -@test "1" == trimrep(buffer) -@test 1 == point -fill!(buffer,0) - -status,len,point = Grisu.fastprecision(1.5, 10, buffer) -if status - @test 10 >= len-1 - @test "15" == trimrep(buffer) - @test 1 == point - fill!(buffer,0) -end - -min_double = 5e-324 -status,len,point = Grisu.fastprecision(min_double, 5,buffer) -@test status -@test "49407" == trimrep(buffer) -@test -323 == point -fill!(buffer,0) - -max_double = 1.7976931348623157e308 -status,len,point = Grisu.fastprecision(max_double, 7,buffer) -@test status -@test "1797693" == trimrep(buffer) -@test 309 == point -fill!(buffer,0) - -status,len,point = Grisu.fastprecision(4294967272.0, 14,buffer) -if status - @test 14 >= len-1 - @test "4294967272" == trimrep(buffer) - @test 10 == point - fill!(buffer,0) -end - -status,len,point = Grisu.fastprecision(4.1855804968213567e298, 17,buffer) -@test status -@test "41855804968213567" == trimrep(buffer) -@test 299 == point -fill!(buffer,0) - -status,len,point = Grisu.fastprecision(5.5626846462680035e-309, 1,buffer) -@test status -@test "6" == trimrep(buffer) -@test -308 == point -fill!(buffer,0) - -status,len,point = Grisu.fastprecision(2147483648.0, 5,buffer) -@test status -@test "21475" == trimrep(buffer) -@test 10 == point -fill!(buffer,0) - -status,len,point = Grisu.fastprecision(3.5844466002796428e+298, 10,buffer) -@test status -@test 10 >= len-1 -@test "35844466" == trimrep(buffer) -@test 299 == point -fill!(buffer,0) - -smallest_normal64 = 0x0010000000000000 -v = reinterpret(Float64,smallest_normal64) -status,len,point = Grisu.fastprecision(v, 17, buffer) -@test status -@test "22250738585072014" == trimrep(buffer) -@test -307 == point -fill!(buffer,0) - -largest_denormal64 = 0x000FFFFFFFFFFFFF -v = reinterpret(Float64,largest_denormal64) -status,len,point = Grisu.fastprecision(v, 17, buffer) -@test status -@test 20 >= len-1 -@test "22250738585072009" == trimrep(buffer) -@test -307 == point -fill!(buffer,0) - -v = 3.3161339052167390562200598e-237 -status,len,point = Grisu.fastprecision(v, 18, buffer) -@test status -@test "331613390521673906" == trimrep(buffer) -@test -236 == point -fill!(buffer,0) - -v = 7.9885183916008099497815232e+191 -status,len,point = Grisu.fastprecision(v, 4, buffer) -@test status -@test "7989" == trimrep(buffer) -@test 192 == point -fill!(buffer,0) - -#fastfixedtoa -status,len,point = Grisu.fastfixedtoa(1.0, 0,1, buffer) -@test "1" == unsafe_string(pointer(buffer)) -@test 1 == point -fill!(buffer,0) - -status,len,point = Grisu.fastfixedtoa(1.0, 0,15, buffer) -@test "1" == unsafe_string(pointer(buffer)) -@test 1 == point -fill!(buffer,0) - -status,len,point = Grisu.fastfixedtoa(1.0, 0,0, buffer) -@test "1" == unsafe_string(pointer(buffer)) -@test 1 == point -fill!(buffer,0) - -status,len,point = Grisu.fastfixedtoa(0xFFFFFFFF, 0,5, buffer) -@test "4294967295" == unsafe_string(pointer(buffer)) -@test 10 == point -fill!(buffer,0) - -status,len,point = Grisu.fastfixedtoa(4294967296.0, 0,5, buffer) -@test "4294967296" == unsafe_string(pointer(buffer)) #todo -@test 10 == point -fill!(buffer,0) - -status,len,point = Grisu.fastfixedtoa(1e21, 0,5, buffer) -@test "1" == unsafe_string(pointer(buffer)) #todo extra '0's -@test 22 == point -fill!(buffer,0) - -status,len,point = Grisu.fastfixedtoa(999999999999999868928.00, 0,2, buffer) -@test "999999999999999868928" == unsafe_string(pointer(buffer)) #todo extra '0' -@test 21 == point -fill!(buffer,0) - -status,len,point = Grisu.fastfixedtoa(6.9999999999999989514240000e+21, 0,5, buffer) -@test "6999999999999998951424" == unsafe_string(pointer(buffer)) #todo short several '9's -@test 22 == point -fill!(buffer,0) - -status,len,point = Grisu.fastfixedtoa(1.5, 0,5, buffer) -@test "15" == unsafe_string(pointer(buffer)) -@test 1 == point -fill!(buffer,0) - -status,len,point = Grisu.fastfixedtoa(1.55, 0,5, buffer) -@test "155" == unsafe_string(pointer(buffer)) -@test 1 == point -fill!(buffer,0) - -status,len,point = Grisu.fastfixedtoa(1.55, 0,1, buffer) -@test "16" == unsafe_string(pointer(buffer)) -@test 1 == point -fill!(buffer,0) - -status,len,point = Grisu.fastfixedtoa(1.00000001, 0,15, buffer) -@test "100000001" == unsafe_string(pointer(buffer)) -@test 1 == point -fill!(buffer,0) - -status,len,point = Grisu.fastfixedtoa(0.1, 0,10, buffer) -@test "1" == unsafe_string(pointer(buffer)) -@test 0 == point -fill!(buffer,0) - -status,len,point = Grisu.fastfixedtoa(0.01, 0,10, buffer) -@test "1" == unsafe_string(pointer(buffer)) -@test -1 == point -fill!(buffer,0) - -status,len,point = Grisu.fastfixedtoa(0.001, 0,10, buffer) -@test "1" == unsafe_string(pointer(buffer)) -@test -2 == point -fill!(buffer,0) - -status,len,point = Grisu.fastfixedtoa(0.0001, 0,10, buffer) #todo -@test "1" == unsafe_string(pointer(buffer)) -@test -3 == point -fill!(buffer,0) - -status,len,point = Grisu.fastfixedtoa(0.00001, 0,10, buffer) #todo -@test "1" == unsafe_string(pointer(buffer)) -@test -4 == point -fill!(buffer,0) - -status,len,point = Grisu.fastfixedtoa(0.000001, 0,10, buffer) -@test "1" == unsafe_string(pointer(buffer)) -@test -5 == point -fill!(buffer,0) - -status,len,point = Grisu.fastfixedtoa(0.0000001, 0,10, buffer) -@test "1" == unsafe_string(pointer(buffer)) -@test -6 == point -fill!(buffer,0) - -status,len,point = Grisu.fastfixedtoa(0.00000001, 0,10, buffer) -@test "1" == unsafe_string(pointer(buffer)) -@test -7 == point -fill!(buffer,0) - -status,len,point = Grisu.fastfixedtoa(0.000000001, 0,10, buffer) -@test "1" == unsafe_string(pointer(buffer)) -@test -8 == point -fill!(buffer,0) - -status,len,point = Grisu.fastfixedtoa(0.0000000001, 0,15, buffer) -@test "1" == unsafe_string(pointer(buffer)) -@test -9 == point -fill!(buffer,0) - -status,len,point = Grisu.fastfixedtoa(0.00000000001, 0,15, buffer) -@test "1" == unsafe_string(pointer(buffer)) -@test -10 == point -fill!(buffer,0) - -status,len,point = Grisu.fastfixedtoa(0.000000000001, 0,15, buffer) -@test "1" == unsafe_string(pointer(buffer)) -@test -11 == point -fill!(buffer,0) - -status,len,point = Grisu.fastfixedtoa(0.0000000000001, 0,15, buffer) -@test "1" == unsafe_string(pointer(buffer)) -@test -12 == point -fill!(buffer,0) - -status,len,point = Grisu.fastfixedtoa(0.00000000000001, 0,15, buffer) -@test "1" == unsafe_string(pointer(buffer)) -@test -13 == point -fill!(buffer,0) - -status,len,point = Grisu.fastfixedtoa(0.000000000000001, 0,20, buffer) -@test "1" == unsafe_string(pointer(buffer)) -@test -14 == point -fill!(buffer,0) - -status,len,point = Grisu.fastfixedtoa(0.0000000000000001, 0,20, buffer) -@test "1" == unsafe_string(pointer(buffer)) -@test -15 == point -fill!(buffer,0) - -status,len,point = Grisu.fastfixedtoa(0.00000000000000001, 0,20, buffer) -@test "1" == unsafe_string(pointer(buffer)) -@test -16 == point -fill!(buffer,0) - -status,len,point = Grisu.fastfixedtoa(0.000000000000000001, 0,20, buffer) -@test "1" == unsafe_string(pointer(buffer)) -@test -17 == point -fill!(buffer,0) - -status,len,point = Grisu.fastfixedtoa(0.0000000000000000001, 0,20, buffer) -@test "1" == unsafe_string(pointer(buffer)) -@test -18 == point -fill!(buffer,0) - -status,len,point = Grisu.fastfixedtoa(0.00000000000000000001, 0,20, buffer) -@test "1" == unsafe_string(pointer(buffer)) -@test -19 == point -fill!(buffer,0) - -status,len,point = Grisu.fastfixedtoa(0.10000000004, 0,10, buffer) -@test "1" == unsafe_string(pointer(buffer)) -@test 0 == point -fill!(buffer,0) - -status,len,point = Grisu.fastfixedtoa(0.01000000004, 0,10, buffer) -@test "1" == unsafe_string(pointer(buffer)) -@test -1 == point -fill!(buffer,0) - -status,len,point = Grisu.fastfixedtoa(0.00100000004, 0,10, buffer) -@test "1" == unsafe_string(pointer(buffer)) -@test -2 == point -fill!(buffer,0) - -status,len,point = Grisu.fastfixedtoa(0.00010000004, 0,10, buffer) #todo -@test "1" == unsafe_string(pointer(buffer)) -@test -3 == point -fill!(buffer,0) - -status,len,point = Grisu.fastfixedtoa(0.00001000004, 0,10, buffer) -@test "1" == unsafe_string(pointer(buffer)) -@test -4 == point -fill!(buffer,0) - -status,len,point = Grisu.fastfixedtoa(0.00000100004, 0,10, buffer) -@test "1" == unsafe_string(pointer(buffer)) -@test -5 == point -fill!(buffer,0) - -status,len,point = Grisu.fastfixedtoa(0.00000010004, 0,10, buffer) -@test "1" == unsafe_string(pointer(buffer)) -@test -6 == point -fill!(buffer,0) - -status,len,point = Grisu.fastfixedtoa(0.00000001004, 0,10, buffer) -@test "1" == unsafe_string(pointer(buffer)) -@test -7 == point -fill!(buffer,0) - -status,len,point = Grisu.fastfixedtoa(0.00000000104, 0,10, buffer) -@test "1" == unsafe_string(pointer(buffer)) -@test -8 == point -fill!(buffer,0) - -status,len,point = Grisu.fastfixedtoa(0.0000000001000004, 0,15, buffer) -@test "1" == unsafe_string(pointer(buffer)) -@test -9 == point -fill!(buffer,0) - -status,len,point = Grisu.fastfixedtoa(0.0000000000100004, 0,15, buffer) -@test "1" == unsafe_string(pointer(buffer)) -@test -10 == point -fill!(buffer,0) - -status,len,point = Grisu.fastfixedtoa(0.0000000000010004, 0,15, buffer) -@test "1" == unsafe_string(pointer(buffer)) -@test -11 == point -fill!(buffer,0) - -status,len,point = Grisu.fastfixedtoa(0.0000000000001004, 0,15, buffer) -@test "1" == unsafe_string(pointer(buffer)) -@test -12 == point -fill!(buffer,0) - -status,len,point = Grisu.fastfixedtoa(0.0000000000000104, 0,15, buffer) -@test "1" == unsafe_string(pointer(buffer)) -@test -13 == point -fill!(buffer,0) - -status,len,point = Grisu.fastfixedtoa(0.000000000000001000004, 0,20, buffer) -@test "1" == unsafe_string(pointer(buffer)) -@test -14 == point -fill!(buffer,0) - -status,len,point = Grisu.fastfixedtoa(0.000000000000000100004, 0,20, buffer) -@test "1" == unsafe_string(pointer(buffer)) -@test -15 == point -fill!(buffer,0) - -status,len,point = Grisu.fastfixedtoa(0.000000000000000010004, 0,20, buffer) -@test "1" == unsafe_string(pointer(buffer)) -@test -16 == point -fill!(buffer,0) - -status,len,point = Grisu.fastfixedtoa(0.000000000000000001004, 0,20, buffer) -@test "1" == unsafe_string(pointer(buffer)) -@test -17 == point -fill!(buffer,0) - -status,len,point = Grisu.fastfixedtoa(0.000000000000000000104, 0,20, buffer) -@test "1" == unsafe_string(pointer(buffer)) -@test -18 == point -fill!(buffer,0) - -status,len,point = Grisu.fastfixedtoa(0.000000000000000000014, 0,20, buffer) -@test "1" == unsafe_string(pointer(buffer)) -@test -19 == point -fill!(buffer,0) - -status,len,point = Grisu.fastfixedtoa(0.10000000006, 0,10, buffer) -@test "1000000001" == unsafe_string(pointer(buffer)) -@test 0 == point -fill!(buffer,0) - -status,len,point = Grisu.fastfixedtoa(0.01000000006, 0,10, buffer) -@test "100000001" == unsafe_string(pointer(buffer)) -@test -1 == point -fill!(buffer,0) - -status,len,point = Grisu.fastfixedtoa(0.00100000006, 0,10, buffer) -@test "10000001" == unsafe_string(pointer(buffer)) -@test -2 == point -fill!(buffer,0) - -status,len,point = Grisu.fastfixedtoa(0.00010000006, 0,10, buffer) -@test "1000001" == unsafe_string(pointer(buffer)) -@test -3 == point -fill!(buffer,0) - -status,len,point = Grisu.fastfixedtoa(0.00001000006, 0,10, buffer) -@test "100001" == unsafe_string(pointer(buffer)) -@test -4 == point -fill!(buffer,0) - -status,len,point = Grisu.fastfixedtoa(0.00000100006, 0,10, buffer) -@test "10001" == unsafe_string(pointer(buffer)) -@test -5 == point -fill!(buffer,0) - -status,len,point = Grisu.fastfixedtoa(0.00000010006, 0,10, buffer) -@test "1001" == unsafe_string(pointer(buffer)) -@test -6 == point -fill!(buffer,0) - -status,len,point = Grisu.fastfixedtoa(0.00000001006, 0,10, buffer) -@test "101" == unsafe_string(pointer(buffer)) -@test -7 == point -fill!(buffer,0) - -status,len,point = Grisu.fastfixedtoa(0.00000000106, 0,10, buffer) -@test "11" == unsafe_string(pointer(buffer)) -@test -8 == point -fill!(buffer,0) - -status,len,point = Grisu.fastfixedtoa(0.0000000001000006, 0,15, buffer) -@test "100001" == unsafe_string(pointer(buffer)) -@test -9 == point -fill!(buffer,0) - -status,len,point = Grisu.fastfixedtoa(0.0000000000100006, 0,15, buffer) -@test "10001" == unsafe_string(pointer(buffer)) -@test -10 == point -fill!(buffer,0) - -status,len,point = Grisu.fastfixedtoa(0.0000000000010006, 0,15, buffer) -@test "1001" == unsafe_string(pointer(buffer)) -@test -11 == point -fill!(buffer,0) - -status,len,point = Grisu.fastfixedtoa(0.0000000000001006, 0,15, buffer) -@test "101" == unsafe_string(pointer(buffer)) -@test -12 == point -fill!(buffer,0) - -status,len,point = Grisu.fastfixedtoa(0.0000000000000106, 0,15, buffer) -@test "11" == unsafe_string(pointer(buffer)) -@test -13 == point -fill!(buffer,0) - -status,len,point = Grisu.fastfixedtoa(0.000000000000001000006, 0,20, buffer) -@test "100001" == unsafe_string(pointer(buffer)) -@test -14 == point -fill!(buffer,0) - -status,len,point = Grisu.fastfixedtoa(0.000000000000000100006, 0,20, buffer) -@test "10001" == unsafe_string(pointer(buffer)) -@test -15 == point -fill!(buffer,0) - -status,len,point = Grisu.fastfixedtoa(0.000000000000000010006, 0,20, buffer) -@test "1001" == unsafe_string(pointer(buffer)) -@test -16 == point -fill!(buffer,0) - -status,len,point = Grisu.fastfixedtoa(0.000000000000000001006, 0,20, buffer) -@test "101" == unsafe_string(pointer(buffer)) -@test -17 == point -fill!(buffer,0) - -status,len,point = Grisu.fastfixedtoa(0.000000000000000000106, 0,20, buffer) -@test "11" == unsafe_string(pointer(buffer)) -@test -18 == point -fill!(buffer,0) - -status,len,point = Grisu.fastfixedtoa(0.000000000000000000016, 0,20, buffer) -@test "2" == unsafe_string(pointer(buffer)) -@test -19 == point -fill!(buffer,0) - -status,len,point = Grisu.fastfixedtoa(0.6, 0,0, buffer) -@test "1" == unsafe_string(pointer(buffer)) -@test 1 == point -fill!(buffer,0) - -status,len,point = Grisu.fastfixedtoa(0.96, 0,1, buffer) -@test "1" == unsafe_string(pointer(buffer)) -@test 1 == point -fill!(buffer,0) - -status,len,point = Grisu.fastfixedtoa(0.996, 0,2, buffer) -@test "1" == unsafe_string(pointer(buffer)) -@test 1 == point -fill!(buffer,0) - -status,len,point = Grisu.fastfixedtoa(0.9996, 0,3, buffer) -@test "1" == unsafe_string(pointer(buffer)) -@test 1 == point -fill!(buffer,0) - -status,len,point = Grisu.fastfixedtoa(0.99996, 0,4, buffer) -@test "1" == unsafe_string(pointer(buffer)) -@test 1 == point -fill!(buffer,0) - -status,len,point = Grisu.fastfixedtoa(0.999996, 0,5, buffer) -@test "1" == unsafe_string(pointer(buffer)) -@test 1 == point -fill!(buffer,0) - -status,len,point = Grisu.fastfixedtoa(0.9999996, 0,6, buffer) -@test "1" == unsafe_string(pointer(buffer)) -@test 1 == point -fill!(buffer,0) - -status,len,point = Grisu.fastfixedtoa(0.99999996, 0,7, buffer) -@test "1" == unsafe_string(pointer(buffer)) -@test 1 == point -fill!(buffer,0) - -status,len,point = Grisu.fastfixedtoa(0.999999996, 0,8, buffer) -@test "1" == unsafe_string(pointer(buffer)) -@test 1 == point -fill!(buffer,0) - -status,len,point = Grisu.fastfixedtoa(0.9999999996, 0,9, buffer) -@test "1" == unsafe_string(pointer(buffer)) -@test 1 == point -fill!(buffer,0) - -status,len,point = Grisu.fastfixedtoa(0.99999999996, 0,10, buffer) -@test "1" == unsafe_string(pointer(buffer)) -@test 1 == point -fill!(buffer,0) - -status,len,point = Grisu.fastfixedtoa(0.999999999996, 0,11, buffer) -@test "1" == unsafe_string(pointer(buffer)) -@test 1 == point -fill!(buffer,0) - -status,len,point = Grisu.fastfixedtoa(0.9999999999996, 0,12, buffer) -@test "1" == unsafe_string(pointer(buffer)) -@test 1 == point -fill!(buffer,0) - -status,len,point = Grisu.fastfixedtoa(0.99999999999996, 0,13, buffer) -@test "1" == unsafe_string(pointer(buffer)) -@test 1 == point -fill!(buffer,0) - -status,len,point = Grisu.fastfixedtoa(0.999999999999996, 0,14, buffer) -@test "1" == unsafe_string(pointer(buffer)) -@test 1 == point -fill!(buffer,0) - -status,len,point = Grisu.fastfixedtoa(0.9999999999999996, 0,15, buffer) -@test "1" == unsafe_string(pointer(buffer)) -@test 1 == point -fill!(buffer,0) - -status,len,point = Grisu.fastfixedtoa(0.00999999999999996, 0,16, buffer) -@test "1" == unsafe_string(pointer(buffer)) -@test -1 == point -fill!(buffer,0) - -status,len,point = Grisu.fastfixedtoa(0.000999999999999996, 0,17, buffer) -@test "1" == unsafe_string(pointer(buffer)) -@test -2 == point -fill!(buffer,0) - -status,len,point = Grisu.fastfixedtoa(0.0000999999999999996, 0,18, buffer) -@test "1" == unsafe_string(pointer(buffer)) -@test -3 == point -fill!(buffer,0) - -status,len,point = Grisu.fastfixedtoa(0.00000999999999999996, 0,19, buffer) -@test "1" == unsafe_string(pointer(buffer)) -@test -4 == point -fill!(buffer,0) - -status,len,point = Grisu.fastfixedtoa(0.000000999999999999996, 0,20, buffer) -@test "1" == unsafe_string(pointer(buffer)) -@test -5 == point -fill!(buffer,0) - -status,len,point = Grisu.fastfixedtoa(323423.234234, 0,10, buffer) -@test "323423234234" == unsafe_string(pointer(buffer)) -@test 6 == point -fill!(buffer,0) - -status,len,point = Grisu.fastfixedtoa(12345678.901234, 0,4, buffer) -@test "123456789012" == unsafe_string(pointer(buffer)) -@test 8 == point -fill!(buffer,0) - -status,len,point = Grisu.fastfixedtoa(98765.432109, 0,5, buffer) -@test "9876543211" == unsafe_string(pointer(buffer)) -@test 5 == point -fill!(buffer,0) - -status,len,point = Grisu.fastfixedtoa(42, 0,20, buffer) -@test "42" == unsafe_string(pointer(buffer)) -@test 2 == point -fill!(buffer,0) - -status,len,point = Grisu.fastfixedtoa(0.5, 0,0, buffer) -@test "1" == unsafe_string(pointer(buffer)) -@test 1 == point -fill!(buffer,0) - -status,len,point = Grisu.fastfixedtoa(1e-23, 0,10, buffer) -@test "" == unsafe_string(pointer(buffer)) -@test -10 == point -fill!(buffer,0) - -status,len,point = Grisu.fastfixedtoa(1e-123, 0,2, buffer) -@test "" == unsafe_string(pointer(buffer)) -@test -2 == point -fill!(buffer,0) - -status,len,point = Grisu.fastfixedtoa(1e-123, 0,0, buffer) -@test "" == unsafe_string(pointer(buffer)) -@test 0 == point -fill!(buffer,0) - -status,len,point = Grisu.fastfixedtoa(1e-23, 0,20, buffer) -@test "" == unsafe_string(pointer(buffer)) -@test -20 == point -fill!(buffer,0) - -status,len,point = Grisu.fastfixedtoa(1e-21, 0,20, buffer) -@test "" == unsafe_string(pointer(buffer)) -@test -20 == point -fill!(buffer,0) - -status,len,point = Grisu.fastfixedtoa(1e-22, 0,20, buffer) -@test "" == unsafe_string(pointer(buffer)) -@test -20 == point -fill!(buffer,0) - -status,len,point = Grisu.fastfixedtoa(6e-21, 0,20, buffer) -@test "1" == unsafe_string(pointer(buffer)) -@test -19 == point -fill!(buffer,0) - -status,len,point = Grisu.fastfixedtoa(9.1193616301674545152000000e+19, 0,0,buffer) -@test "91193616301674545152" == unsafe_string(pointer(buffer)) -@test 20 == point -fill!(buffer,0) - -status,len,point = Grisu.fastfixedtoa(4.8184662102767651659096515e-04, 0,19,buffer) -@test "4818466210276765" == unsafe_string(pointer(buffer)) -@test -3 == point -fill!(buffer,0) - -status,len,point = Grisu.fastfixedtoa(1.9023164229540652612705182e-23, 0,8,buffer) -@test "" == unsafe_string(pointer(buffer)) -@test -8 == point -fill!(buffer,0) - -status,len,point = Grisu.fastfixedtoa(1000000000000000128.0, 0,0,buffer) -@test "1000000000000000128" == unsafe_string(pointer(buffer)) -@test 19 == point -fill!(buffer,0) - -#bignumdtoa -status,len,point = Grisu.bignumdtoa(1.0, Grisu.SHORTEST, 0, buffer,bignums) -@test "1" == trimrep(buffer) -@test 1 == point -fill!(buffer,0) -map(x->Grisu.Bignums.zero!(x),bignums) - -status,len,point = Grisu.bignumdtoa(1.0, Grisu.FIXED, 3, buffer,bignums) -@test 3 >= len - 1 - point -@test "1" == trimrep(buffer) -@test 1 == point -fill!(buffer,0) -map(x->Grisu.Bignums.zero!(x),bignums) - -status,len,point = Grisu.bignumdtoa(1.0, Grisu.PRECISION, 3, buffer,bignums) -@test 3 >= len - 1 -@test "1" == trimrep(buffer) -@test 1 == point -fill!(buffer,0) -map(x->Grisu.Bignums.zero!(x),bignums) - -status,len,point = Grisu.bignumdtoa(1.5, Grisu.SHORTEST, 0, buffer,bignums) -@test "15" == trimrep(buffer) -@test 1 == point -fill!(buffer,0) -map(x->Grisu.Bignums.zero!(x),bignums) - -status,len,point = Grisu.bignumdtoa(1.5, Grisu.FIXED, 10, buffer,bignums) -@test 10 >= len - 1 - point -@test "15" == trimrep(buffer) -@test 1 == point -fill!(buffer,0) -map(x->Grisu.Bignums.zero!(x),bignums) - -status,len,point = Grisu.bignumdtoa(1.5, Grisu.PRECISION, 10, buffer,bignums) -@test 10 >= len - 1 -@test "15" == trimrep(buffer) -@test 1 == point -fill!(buffer,0) -map(x->Grisu.Bignums.zero!(x),bignums) - -min_double = 5e-324 -status,len,point = Grisu.bignumdtoa(min_double, Grisu.SHORTEST, 0, buffer,bignums) -@test "5" == trimrep(buffer) -@test -323 == point -fill!(buffer,0) -map(x->Grisu.Bignums.zero!(x),bignums) - -status,len,point = Grisu.bignumdtoa(min_double, Grisu.FIXED, 5, buffer,bignums) -@test 5 >= len - 1 - point -@test "" == trimrep(buffer) - -status,len,point = Grisu.bignumdtoa(min_double, Grisu.PRECISION, 5, buffer,bignums) -@test 5 >= len - 1 -@test "49407" == trimrep(buffer) -@test -323 == point -fill!(buffer,0) -map(x->Grisu.Bignums.zero!(x),bignums) - -max_double = 1.7976931348623157e308 -status,len,point = Grisu.bignumdtoa(max_double, Grisu.SHORTEST, 0, buffer,bignums) -@test "17976931348623157" == trimrep(buffer) -@test 309 == point -fill!(buffer,0) -map(x->Grisu.Bignums.zero!(x),bignums) - -status,len,point = Grisu.bignumdtoa(max_double, Grisu.PRECISION, 7, buffer,bignums) -@test 7 >= len - 1 -@test "1797693" == trimrep(buffer) -@test 309 == point -fill!(buffer,0) -map(x->Grisu.Bignums.zero!(x),bignums) - -status,len,point = Grisu.bignumdtoa(4294967272.0, Grisu.SHORTEST, 0, buffer,bignums) -@test "4294967272" == unsafe_string(pointer(buffer)) -@test 10 == point -fill!(buffer,0) -map(x->Grisu.Bignums.zero!(x),bignums) - -status,len,point = Grisu.bignumdtoa(4294967272.0, Grisu.FIXED, 5, buffer,bignums) -@test "429496727200000" == unsafe_string(pointer(buffer)) -@test 10 == point -fill!(buffer,0) -map(x->Grisu.Bignums.zero!(x),bignums) - -status,len,point = Grisu.bignumdtoa(4294967272.0, Grisu.PRECISION, 14, buffer,bignums) -@test 14 >= len - 1 -@test "4294967272" == trimrep(buffer) -@test 10 == point -fill!(buffer,0) -map(x->Grisu.Bignums.zero!(x),bignums) - -status,len,point = Grisu.bignumdtoa(4.1855804968213567e298, Grisu.SHORTEST, 0,buffer,bignums) -@test "4185580496821357" == trimrep(buffer) -@test 299 == point -fill!(buffer,0) -map(x->Grisu.Bignums.zero!(x),bignums) - -status,len,point = Grisu.bignumdtoa(4.1855804968213567e298, Grisu.PRECISION, 20,buffer,bignums) -@test 20 >= len - 1 -@test "41855804968213567225" == trimrep(buffer) -@test 299 == point -fill!(buffer,0) -map(x->Grisu.Bignums.zero!(x),bignums) - -status,len,point = Grisu.bignumdtoa(5.5626846462680035e-309, Grisu.SHORTEST, 0, buffer,bignums) -@test "5562684646268003" == trimrep(buffer) -@test -308 == point -fill!(buffer,0) -map(x->Grisu.Bignums.zero!(x),bignums) - -status,len,point = Grisu.bignumdtoa(5.5626846462680035e-309, Grisu.PRECISION, 1, buffer,bignums) -@test 1 >= len - 1 -@test "6" == trimrep(buffer) -@test -308 == point -fill!(buffer,0) -map(x->Grisu.Bignums.zero!(x),bignums) - -status,len,point = Grisu.bignumdtoa(2147483648.0, Grisu.SHORTEST, 0, buffer,bignums) -@test "2147483648" == trimrep(buffer) -@test 10 == point -fill!(buffer,0) -map(x->Grisu.Bignums.zero!(x),bignums) - -status,len,point = Grisu.bignumdtoa(2147483648.0, Grisu.FIXED, 2, buffer,bignums) -@test 2 >= len - 1 - point -@test "2147483648" == trimrep(buffer) -@test 10 == point -fill!(buffer,0) -map(x->Grisu.Bignums.zero!(x),bignums) - -status,len,point = Grisu.bignumdtoa(2147483648.0, Grisu.PRECISION, 5, buffer,bignums) -@test 5 >= len - 1 -@test "21475" == trimrep(buffer) -@test 10 == point -fill!(buffer,0) -map(x->Grisu.Bignums.zero!(x),bignums) - -status,len,point = Grisu.bignumdtoa(3.5844466002796428e+298, Grisu.SHORTEST, 0, buffer,bignums) -@test "35844466002796428" == trimrep(buffer) -@test 299 == point -fill!(buffer,0) -map(x->Grisu.Bignums.zero!(x),bignums) - -status,len,point = Grisu.bignumdtoa(3.5844466002796428e+298, Grisu.PRECISION, 10, buffer,bignums) -@test 10 >= len - 1 -@test "35844466" == trimrep(buffer) -@test 299 == point -fill!(buffer,0) -map(x->Grisu.Bignums.zero!(x),bignums) - -v = reinterpret(Float64,0x0010000000000000) -status,len,point = Grisu.bignumdtoa(v, Grisu.SHORTEST, 0, buffer,bignums) -@test "22250738585072014" == trimrep(buffer) -@test -307 == point -fill!(buffer,0) -map(x->Grisu.Bignums.zero!(x),bignums) - -status,len,point = Grisu.bignumdtoa(v, Grisu.PRECISION, 20, buffer,bignums) -@test 20 >= len - 1 -@test "22250738585072013831" == trimrep(buffer) -@test -307 == point -fill!(buffer,0) -map(x->Grisu.Bignums.zero!(x),bignums) - -v = reinterpret(Float64,0x000FFFFFFFFFFFFF) -status,len,point = Grisu.bignumdtoa(v, Grisu.SHORTEST, 0, buffer,bignums) -@test "2225073858507201" == trimrep(buffer) -@test -307 == point -fill!(buffer,0) -map(x->Grisu.Bignums.zero!(x),bignums) - -status,len,point = Grisu.bignumdtoa(v, Grisu.PRECISION, 20, buffer,bignums) -@test 20 >= len - 1 -@test "2225073858507200889" == trimrep(buffer) -@test -307 == point -fill!(buffer,0) -map(x->Grisu.Bignums.zero!(x),bignums) - -status,len,point = Grisu.bignumdtoa(4128420500802942e-24, Grisu.SHORTEST, 0, buffer,bignums) -@test "4128420500802942" == trimrep(buffer) -@test -8 == point -fill!(buffer,0) -map(x->Grisu.Bignums.zero!(x),bignums) - -v = 3.9292015898194142585311918e-10 -status,len,point = Grisu.bignumdtoa(v, Grisu.SHORTEST, 0, buffer,bignums) -@test "39292015898194143" == trimrep(buffer) - -v = 4194304.0 -status,len,point = Grisu.bignumdtoa(v, Grisu.FIXED, 5, buffer,bignums) -@test 5 >= len - 1 - point -@test "4194304" == trimrep(buffer) - -v = 3.3161339052167390562200598e-237 -status,len,point = Grisu.bignumdtoa(v, Grisu.PRECISION, 19, buffer,bignums) -@test 19 >= len - 1 -@test "3316133905216739056" == trimrep(buffer) -@test -236 == point -fill!(buffer,0) -map(x->Grisu.Bignums.zero!(x),bignums) - -v = 7.9885183916008099497815232e+191 -status,len,point = Grisu.bignumdtoa(v, Grisu.PRECISION, 4, buffer,bignums) -@test 4 >= len - 1 -@test "7989" == trimrep(buffer) -@test 192 == point -fill!(buffer,0) -map(x->Grisu.Bignums.zero!(x),bignums) - -v = 1.0000000000000012800000000e+17 -status,len,point = Grisu.bignumdtoa(v, Grisu.FIXED, 1, buffer,bignums) -@test 1 >= len - 1 - point -@test "100000000000000128" == trimrep(buffer) -@test 18 == point -fill!(buffer,0) -map(x->Grisu.Bignums.zero!(x),bignums) - - -min_float = Float32(1e-45) -status,len,point = Grisu.bignumdtoa(min_float, Grisu.SHORTEST, 0, buffer,bignums) -@test "1" == trimrep(buffer) -@test -44 == point -fill!(buffer,0) -map(x->Grisu.Bignums.zero!(x),bignums) - -max_float = Float32(3.4028234e38) -status,len,point = Grisu.bignumdtoa(max_float, Grisu.SHORTEST, 0, buffer,bignums) -@test "34028235" == trimrep(buffer) -@test 39 == point -fill!(buffer,0) -map(x->Grisu.Bignums.zero!(x),bignums) - -status,len,point = Grisu.bignumdtoa(Float32(4294967272.0), Grisu.SHORTEST, 0, buffer,bignums) -@test "42949673" == trimrep(buffer) -@test 10 == point -fill!(buffer,0) -map(x->Grisu.Bignums.zero!(x),bignums) - -status,len,point = Grisu.bignumdtoa(Float32(3.32306998946228968226e+35), Grisu.SHORTEST, 0, buffer,bignums) -@test "332307" == trimrep(buffer) -@test 36 == point -fill!(buffer,0) -map(x->Grisu.Bignums.zero!(x),bignums) - -status,len,point = Grisu.bignumdtoa(Float32(1.2341e-41), Grisu.SHORTEST, 0, buffer,bignums) -@test "12341" == trimrep(buffer) -@test -40 == point -fill!(buffer,0) -map(x->Grisu.Bignums.zero!(x),bignums) - -status,len,point = Grisu.bignumdtoa(Float32(3.3554432e7), Grisu.SHORTEST, 0, buffer,bignums) -@test "33554432" == trimrep(buffer) -@test 8 == point -fill!(buffer,0) -map(x->Grisu.Bignums.zero!(x),bignums) - -status,len,point = Grisu.bignumdtoa(Float32(3.26494756798464e14), Grisu.SHORTEST, 0, buffer,bignums) -@test "32649476" == trimrep(buffer) -@test 15 == point -fill!(buffer,0) -map(x->Grisu.Bignums.zero!(x),bignums) - -status,len,point = Grisu.bignumdtoa(Float32(3.91132223637771935344e37), Grisu.SHORTEST, 0, buffer,bignums) -@test "39113222" == trimrep(buffer) -@test 38 == point -fill!(buffer,0) -map(x->Grisu.Bignums.zero!(x),bignums) - -v = reinterpret(Float32,0x00800000) -status,len,point = Grisu.bignumdtoa(v, Grisu.SHORTEST, 0, buffer,bignums) -@test "11754944" == trimrep(buffer) -@test -37 == point -fill!(buffer,0) -map(x->Grisu.Bignums.zero!(x),bignums) - -v = reinterpret(Float32,0x007FFFFF) -status,len,point = Grisu.bignumdtoa(v, Grisu.SHORTEST, 0, buffer,bignums) -@test "11754942" == trimrep(buffer) -@test -37 == point -fill!(buffer,0) -map(x->Grisu.Bignums.zero!(x),bignums) - -#Float16 -min_double = realmin(Float16) -status,len,point = Grisu.fastshortest(min_double,buffer) -@test status -@test "6104" == trimrep(buffer) -@test -4 == point -fill!(buffer,0) - -max_double = realmax(Float16) -status,len,point = Grisu.fastshortest(max_double,buffer) -@test status -@test "655" == trimrep(buffer) -@test 5 == point -fill!(buffer,0) - -status,len,point = Grisu.fastprecision(Float16(1.0), 3, buffer) -@test status -@test 3 >= len-1 -@test "1" == trimrep(buffer) -@test 1 == point -fill!(buffer,0) - -status,len,point = Grisu.fastprecision(Float16(1.5), 10, buffer) -if status - @test 10 >= len-1 - @test "15" == trimrep(buffer) - @test 1 == point - fill!(buffer,0) -end - -status,len,point = Grisu.fastfixedtoa(Float16(1.0), 0,1, buffer) -@test "1" == unsafe_string(pointer(buffer)) -@test 1 == point -fill!(buffer,0) - -status,len,point = Grisu.fastfixedtoa(Float16(1.0), 0,15, buffer) -@test "1" == unsafe_string(pointer(buffer)) -@test 1 == point -fill!(buffer,0) - -status,len,point = Grisu.fastfixedtoa(Float16(1.0), 0,0, buffer) -@test "1" == unsafe_string(pointer(buffer)) -@test 1 == point -fill!(buffer,0) - -status,len,point = Grisu.fastfixedtoa(Float16(1.5), 0,5, buffer) -@test "15" == unsafe_string(pointer(buffer)) -@test 1 == point -fill!(buffer,0) - -status,len,point = Grisu.fastfixedtoa(Float16(1.55), 0,5, buffer) -@test "15498" == unsafe_string(pointer(buffer)) #todo -@test 1 == point -fill!(buffer,0) - -status,len,point = Grisu.fastfixedtoa(Float16(1.55), 0,1, buffer) -@test "15" == unsafe_string(pointer(buffer)) -@test 1 == point -fill!(buffer,0) - -status,len,point = Grisu.fastfixedtoa(Float16(1.00000001), 0,15, buffer) -@test "1" == unsafe_string(pointer(buffer)) -@test 1 == point -fill!(buffer,0) - -status,len,point = Grisu.fastfixedtoa(Float16(0.1), 0,10, buffer) -@test "999755859" == unsafe_string(pointer(buffer)) -@test -1 == point -fill!(buffer,0) - -status,len,point = Grisu.fastfixedtoa(Float16(0.01), 0,10, buffer) -@test "100021362" == unsafe_string(pointer(buffer)) -@test -1 == point -fill!(buffer,0) - -status,len,point = Grisu.fastfixedtoa(Float16(0.001), 0,10, buffer) -@test "10004044" == unsafe_string(pointer(buffer)) -@test -2 == point -fill!(buffer,0) - -status,len,point = Grisu.fastfixedtoa(Float16(0.0001), 0,10, buffer) #todo -@test "1000166" == unsafe_string(pointer(buffer)) -@test -3 == point -fill!(buffer,0) - -status,len,point = Grisu.fastfixedtoa(Float16(0.00001), 0,10, buffer) #todo -@test "100136" == unsafe_string(pointer(buffer)) -@test -4 == point -fill!(buffer,0) - -status,len,point = Grisu.fastfixedtoa(Float16(0.000001), 0,10, buffer) -@test "10133" == unsafe_string(pointer(buffer)) -@test -5 == point -fill!(buffer,0) - -status,len,point = Grisu.fastfixedtoa(Float16(0.0000001), 0,10, buffer) -@test "1192" == unsafe_string(pointer(buffer)) -@test -6 == point -fill!(buffer,0) - -status,len,point = Grisu.fastfixedtoa(Float16(0.6), 0,0, buffer) -@test "1" == unsafe_string(pointer(buffer)) -@test 1 == point -fill!(buffer,0) - -status,len,point = Grisu.fastfixedtoa(Float16(0.96), 0,1, buffer) -@test "1" == unsafe_string(pointer(buffer)) -@test 1 == point -fill!(buffer,0) - -status,len,point = Grisu.fastfixedtoa(Float16(0.996), 0,2, buffer) -@test "1" == unsafe_string(pointer(buffer)) -@test 1 == point -fill!(buffer,0) - -status,len,point = Grisu.fastfixedtoa(Float16(0.9996), 0,3, buffer) -@test "1" == unsafe_string(pointer(buffer)) -@test 1 == point -fill!(buffer,0) - -status,len,point = Grisu.fastfixedtoa(Float16(0.99996), 0,4, buffer) -@test "1" == unsafe_string(pointer(buffer)) -@test 1 == point -fill!(buffer,0) - -status,len,point = Grisu.fastfixedtoa(Float16(0.999996), 0,5, buffer) -@test "1" == unsafe_string(pointer(buffer)) -@test 1 == point -fill!(buffer,0) - -status,len,point = Grisu.fastfixedtoa(Float16(0.9999996), 0,6, buffer) -@test "1" == unsafe_string(pointer(buffer)) -@test 1 == point -fill!(buffer,0) - -status,len,point = Grisu.fastfixedtoa(Float16(0.99999996), 0,7, buffer) -@test "1" == unsafe_string(pointer(buffer)) -@test 1 == point -fill!(buffer,0) - -status,len,point = Grisu.fastfixedtoa(Float16(42), 0,20, buffer) -@test "42" == unsafe_string(pointer(buffer)) -@test 2 == point -fill!(buffer,0) - -status,len,point = Grisu.fastfixedtoa(Float16(0.5), 0,0, buffer) -@test "1" == unsafe_string(pointer(buffer)) -@test 1 == point -fill!(buffer,0) - -#dtoa -len,point,neg = Grisu.grisu(0.0, Grisu.SHORTEST, 0, buffer) -@test "0" == unsafe_string(pointer(buffer)) -@test 1 == point -fill!(buffer,0) - -len,point,neg = Grisu.grisu(Float32(0.0), Grisu.SHORTEST, 0, buffer) -@test "0" == unsafe_string(pointer(buffer)) -@test 1 == point -fill!(buffer,0) - -len,point,neg = Grisu.grisu(0.0, Grisu.FIXED, 2, buffer) -@test 1 >= len-1 -@test "0" == unsafe_string(pointer(buffer)) -@test 1 == point -fill!(buffer,0) - -len,point,neg = Grisu.grisu(0.0, Grisu.PRECISION, 3, buffer) -@test 1 >= len-1 -@test "0" == unsafe_string(pointer(buffer)) -@test 1 == point -fill!(buffer,0) - -len,point,neg = Grisu.grisu(1.0, Grisu.SHORTEST, 0, buffer) -@test "1" == unsafe_string(pointer(buffer)) -@test 1 == point -fill!(buffer,0) - -len,point,neg = Grisu.grisu(Float32(1.0), Grisu.SHORTEST, 0, buffer) -@test "1" == unsafe_string(pointer(buffer)) -@test 1 == point -fill!(buffer,0) - -len,point,neg = Grisu.grisu(1.0, Grisu.FIXED, 3, buffer) -@test 3 >= len-1-point -@test "1" == trimrep(buffer) -@test 1 == point -fill!(buffer,0) - -len,point,neg = Grisu.grisu(1.0, Grisu.PRECISION, 3, buffer) -@test 3 >= len-1 -@test "1" == trimrep(buffer) -@test 1 == point -fill!(buffer,0) - -len,point,neg = Grisu.grisu(1.5, Grisu.SHORTEST, 0, buffer) -@test "15" == unsafe_string(pointer(buffer)) -@test 1 == point -fill!(buffer,0) - -len,point,neg = Grisu.grisu(Float32(1.5), Grisu.SHORTEST, 0, buffer) -@test "15" == unsafe_string(pointer(buffer)) -@test 1 == point -fill!(buffer,0) - -len,point,neg = Grisu.grisu(1.5, Grisu.FIXED, 10, buffer) -@test 10 >= len-1-point -@test "15" == trimrep(buffer) -@test 1 == point -fill!(buffer,0) - -len,point,neg = Grisu.grisu(1.5, Grisu.PRECISION, 10, buffer) -@test 10 >= len-1 -@test "15" == trimrep(buffer) -@test 1 == point -fill!(buffer,0) - -min_double = 5e-324 -len,point,neg = Grisu.grisu(min_double, Grisu.SHORTEST, 0, buffer) -@test "5" == unsafe_string(pointer(buffer)) -@test -323 == point -fill!(buffer,0) - -min_float = 1e-45 -len,point,neg = Grisu.grisu(Float32(min_float), Grisu.SHORTEST, 0, buffer) -@test "1" == unsafe_string(pointer(buffer)) -@test -44 == point -fill!(buffer,0) - -len,point,neg = Grisu.grisu(min_double, Grisu.FIXED, 5, buffer) -@test 5 >= len-1-point -@test "" == trimrep(buffer) -@test -5 == point -fill!(buffer,0) - -len,point,neg = Grisu.grisu(min_double, Grisu.PRECISION, 5, buffer) -@test 5 >= len-1 -@test "49407" == trimrep(buffer) -@test -323 == point -fill!(buffer,0) - -max_double = 1.7976931348623157e308 -len,point,neg = Grisu.grisu(max_double, Grisu.SHORTEST, 0, buffer) -@test "17976931348623157" == unsafe_string(pointer(buffer)) -@test 309 == point -fill!(buffer,0) - -max_float = 3.4028234e38 -len,point,neg = Grisu.grisu(Float32(max_float), Grisu.SHORTEST, 0, buffer) -@test "34028235" == unsafe_string(pointer(buffer)) -@test 39 == point -fill!(buffer,0) - -len,point,neg = Grisu.grisu(max_double, Grisu.PRECISION, 7, buffer) -@test 7 >= len-1 -@test "1797693" == trimrep(buffer) -@test 309 == point -fill!(buffer,0) - -len,point,neg = Grisu.grisu(4294967272.0, Grisu.SHORTEST, 0, buffer) -@test "4294967272" == unsafe_string(pointer(buffer)) -@test 10 == point -fill!(buffer,0) - -len,point,neg = Grisu.grisu(Float32(4294967272.0), Grisu.SHORTEST, 0, buffer) -@test "42949673" == unsafe_string(pointer(buffer)) -@test 10 == point -fill!(buffer,0) - -len,point,neg = Grisu.grisu(4294967272.0, Grisu.FIXED, 5, buffer) -@test 5 >= len-1-point -@test "4294967272" == trimrep(buffer) -@test 10 == point -fill!(buffer,0) - -len,point,neg = Grisu.grisu(4294967272.0, Grisu.PRECISION, 14, buffer) -@test 14 >= len-1 -@test "4294967272" == trimrep(buffer) -@test 10 == point -fill!(buffer,0) - -len,point,neg = Grisu.grisu(4.1855804968213567e298, Grisu.SHORTEST, 0, buffer) -@test "4185580496821357" == unsafe_string(pointer(buffer)) -@test 299 == point -fill!(buffer,0) - -len,point,neg = Grisu.grisu(4.1855804968213567e298, Grisu.PRECISION, 20, buffer) -@test 20 >= len-1 -@test "41855804968213567225" == trimrep(buffer) -@test 299 == point -fill!(buffer,0) - -len,point,neg = Grisu.grisu(5.5626846462680035e-309, Grisu.SHORTEST, 0, buffer) -@test "5562684646268003" == unsafe_string(pointer(buffer)) -@test -308 == point -fill!(buffer,0) - -len,point,neg = Grisu.grisu(5.5626846462680035e-309, Grisu.PRECISION, 1, buffer) -@test 1 >= len-1 -@test "6" == trimrep(buffer) -@test -308 == point -fill!(buffer,0) - -len,point,neg = Grisu.grisu(-2147483648.0, Grisu.SHORTEST, 0, buffer) -@test 1 == neg -@test "2147483648" == unsafe_string(pointer(buffer)) -@test 10 == point -fill!(buffer,0) - -len,point,neg = Grisu.grisu(Float32(-2147483648.), Grisu.SHORTEST, 0, buffer) -@test 1 == neg -@test "21474836" == unsafe_string(pointer(buffer)) -@test 10 == point -fill!(buffer,0) - - -len,point,neg = Grisu.grisu(-2147483648.0, Grisu.FIXED, 2, buffer) -@test 2 >= len-1-point -@test "2147483648" == trimrep(buffer) -@test 10 == point -fill!(buffer,0) - -len,point,neg = Grisu.grisu(-2147483648.0, Grisu.PRECISION, 5, buffer) -@test 5 >= len-1 -@test "21475" == trimrep(buffer) -@test 10 == point -fill!(buffer,0) - -len,point,neg = Grisu.grisu(-3.5844466002796428e+298, Grisu.SHORTEST, 0, buffer) -@test 1 == neg -@test "35844466002796428" == unsafe_string(pointer(buffer)) -@test 299 == point -fill!(buffer,0) - -len,point,neg = Grisu.grisu(-3.5844466002796428e+298, Grisu.PRECISION, 10, buffer) -@test 1 == neg -@test 10 >= len-1 -@test "35844466" == trimrep(buffer) -@test 299 == point -fill!(buffer,0) - -v = reinterpret(Float64,0x0010000000000000) -len,point,neg = Grisu.grisu(v, Grisu.SHORTEST, 0, buffer) -@test "22250738585072014" == unsafe_string(pointer(buffer)) -@test -307 == point -fill!(buffer,0) - -f = reinterpret(Float32,0x00800000) -len,point,neg = Grisu.grisu(f, Grisu.SHORTEST, 0, buffer) -@test "11754944" == unsafe_string(pointer(buffer)) -@test -37 == point -fill!(buffer,0) - -len,point,neg = Grisu.grisu(v, Grisu.PRECISION, 20, buffer) -@test 20 >= len-1 -@test "22250738585072013831" == trimrep(buffer) -@test -307 == point -fill!(buffer,0) - -v = reinterpret(Float64,0x000FFFFFFFFFFFFF) -len,point,neg = Grisu.grisu(v, Grisu.SHORTEST, 0, buffer) -@test "2225073858507201" == unsafe_string(pointer(buffer)) -@test -307 == point -fill!(buffer,0) - -f = reinterpret(Float32,0x007FFFFF) -len,point,neg = Grisu.grisu(f, Grisu.SHORTEST, 0, buffer) -@test "11754942" == unsafe_string(pointer(buffer)) -@test -37 == point -fill!(buffer,0) - -len,point,neg = Grisu.grisu(v, Grisu.PRECISION, 20, buffer) -@test 20 >= len-1 -@test "2225073858507200889" == trimrep(buffer) -@test -307 == point -fill!(buffer,0) - -len,point,neg = Grisu.grisu(4128420500802942e-24, Grisu.SHORTEST, 0, buffer) -@test 0 == neg -@test "4128420500802942" == unsafe_string(pointer(buffer)) -@test -8 == point -fill!(buffer,0) - -v = -3.9292015898194142585311918e-10 -len,point,neg = Grisu.grisu(v, Grisu.SHORTEST, 0, buffer) -@test "39292015898194143" == unsafe_string(pointer(buffer)) -fill!(buffer,0) - -f = Float32(-3.9292015898194142585311918e-10) -len,point,neg = Grisu.grisu(f, Grisu.SHORTEST, 0, buffer) -@test "39292017" == unsafe_string(pointer(buffer)) -fill!(buffer,0) - -v = 4194304.0 -len,point,neg = Grisu.grisu(v, Grisu.FIXED, 5, buffer) -@test 5 >= len-1-point -@test "4194304" == trimrep(buffer) -fill!(buffer,0) - -v = 3.3161339052167390562200598e-237 -len,point,neg = Grisu.grisu(v, Grisu.PRECISION, 19, buffer) -@test 19 >= len-1 -@test "3316133905216739056" == trimrep(buffer) -@test -236 == point -fill!(buffer,0) - -len,point,neg = Grisu.grisu(0.0, Grisu.SHORTEST, 0, buffer) -@test !neg - -len,point,neg = Grisu.grisu(-0.0, Grisu.SHORTEST, 0, buffer) -@test neg - -len,point,neg = Grisu.grisu(1.0, Grisu.SHORTEST, 0, buffer) -@test !neg - -len,point,neg = Grisu.grisu(-1.0, Grisu.SHORTEST, 0, buffer) -@test neg - -len,point,neg = Grisu.grisu(Float32(0.0), Grisu.SHORTEST, 0, buffer) -@test !neg - -len,point,neg = Grisu.grisu(-Float32(0.0), Grisu.SHORTEST, 0, buffer) -@test neg - -len,point,neg = Grisu.grisu(Float32(1.0), Grisu.SHORTEST, 0, buffer) -@test !neg - -len,point,neg = Grisu.grisu(-Float32(1.0), Grisu.SHORTEST, 0, buffer) -@test neg - -len,point,neg = Grisu.grisu(0.0, Grisu.PRECISION, 1, buffer) -@test !neg - -len,point,neg = Grisu.grisu(-0.0, Grisu.PRECISION, 1, buffer) -@test neg - -len,point,neg = Grisu.grisu(1.0, Grisu.PRECISION, 1, buffer) -@test !neg - -len,point,neg = Grisu.grisu(-1.0, Grisu.PRECISION, 1, buffer) -@test neg - -len,point,neg = Grisu.grisu(0.0, Grisu.FIXED, 1, buffer) -@test !neg - -len,point,neg = Grisu.grisu(-0.0, Grisu.FIXED, 1, buffer) -@test neg - -len,point,neg = Grisu.grisu(1.0, Grisu.FIXED, 1, buffer) -@test !neg - -len,point,neg = Grisu.grisu(-1.0, Grisu.FIXED, 1, buffer) -@test neg - - -len,point,neg = Grisu.grisu(0.0, Grisu.PRECISION, 0, buffer) -@test 0 >= len-1 -@test "" == unsafe_string(pointer(buffer)) -@test !neg - -len,point,neg = Grisu.grisu(1.0, Grisu.PRECISION, 0, buffer) -@test 0 >= len-1 -@test "" == unsafe_string(pointer(buffer)) -@test !neg - -len,point,neg = Grisu.grisu(0.0, Grisu.FIXED, 0, buffer) -@test 1 >= len-1 -@test "0" == unsafe_string(pointer(buffer)) -@test !neg - -len,point,neg = Grisu.grisu(1.0, Grisu.FIXED, 0, buffer) -@test 1 >= len-1 -@test "1" == unsafe_string(pointer(buffer)) -@test !neg diff --git a/julia-0.6.3/share/julia/test/hashing.jl b/julia-0.6.3/share/julia/test/hashing.jl deleted file mode 100644 index de532db..0000000 --- a/julia-0.6.3/share/julia/test/hashing.jl +++ /dev/null @@ -1,122 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -types = Any[ - Bool, - Int8, UInt8, Int16, UInt16, Int32, UInt32, Int64, UInt64, Float32, Float64, - Rational{Int8}, Rational{UInt8}, Rational{Int16}, Rational{UInt16}, - Rational{Int32}, Rational{UInt32}, Rational{Int64}, Rational{UInt64} -] -vals = vcat( - typemin(Int64), - -Int64(maxintfloat(Float64))+Int64[-4:1;], - typemin(Int32), - -Integer(maxintfloat(Float32))+(-4:1), - -2:2, - Integer(maxintfloat(Float32))+(-1:4), - typemax(Int32), - Int64(maxintfloat(Float64))+Int64[-1:4;], - typemax(Int64), -) - -function coerce(T::Type, x) - if T<:Rational - convert(T, coerce(typeof(numerator(zero(T))), x)) - elseif !(T<:Integer) - convert(T, x) - else - x % T - end -end - -for T=types[2:end], x=vals - a = coerce(T,x) - @test hash(a,zero(UInt)) == invoke(hash, Tuple{Real, UInt}, a, zero(UInt)) -end - -for T=types, S=types, x=vals - a = coerce(T,x) - b = coerce(S,x) - #println("$(typeof(a)) $a") - #println("$(typeof(b)) $b") - @test isequal(a,b) == (hash(a)==hash(b)) - # for y=vals - # println("T=$T; S=$S; x=$x; y=$y") - # c = convert(T,x//y) - # d = convert(S,x//y) - # @test !isequal(a,b) || hash(a)==hash(b) - # end -end - -# issue #8619 -@test hash(nextfloat(2.0^63)) == hash(UInt64(nextfloat(2.0^63))) -@test hash(prevfloat(2.0^64)) == hash(UInt64(prevfloat(2.0^64))) - -# issue #9264 -@test hash(1//6,zero(UInt)) == invoke(hash, Tuple{Real, UInt}, 1//6, zero(UInt)) -@test hash(1//6) == hash(big(1)//big(6)) -@test hash(1//6) == hash(0x01//0x06) - -# hashing collections (e.g. issue #6870) -vals = Any[ - [1,2,3,4], [1 3;2 4], Any[1,2,3,4], [1,3,2,4], - [1,0], [true,false], BitArray([true,false]), - Set([1,2,3,4]), - Set([1:10;]), # these lead to different key orders - Set([7,9,4,10,2,3,5,8,6,1]), # - Dict(42 => 101, 77 => 93), Dict{Any,Any}(42 => 101, 77 => 93), - (1,2,3,4), (1.0,2.0,3.0,4.0), (1,3,2,4), - ("a","b"), (SubString("a",1,1), SubString("b",1,1)), - # issue #6900 - Dict(x => x for x in 1:10), - Dict(7=>7,9=>9,4=>4,10=>10,2=>2,3=>3,8=>8,5=>5,6=>6,1=>1), - [], [1], [2], [1, 1], [1, 2], [1, 3], [2, 2], [1, 2, 2], [1, 3, 3], - zeros(2, 2), spzeros(2, 2), eye(2, 2), speye(2, 2), - sparse(ones(2, 2)), ones(2, 2), sparse([0 0; 1 0]), [0 0; 1 0], - [-0. 0; -0. 0.], SparseMatrixCSC(2, 2, [1, 3, 3], [1, 2], [-0., -0.]) -] - -for a in vals, b in vals - @test isequal(a,b) == (hash(a)==hash(b)) -end - -@test hash(SubString("--hello--",3,7)) == hash("hello") -@test hash(:(X.x)) == hash(:(X.x)) -@test hash(:(X.x)) != hash(:(X.y)) - -@test hash([1,2]) == hash(view([1,2,3,4],1:2)) - -# test explicit zeros in SparseMatrixCSC -x = sprand(10, 10, 0.5) -x[1] = 1 -x.nzval[1] = 0 -@test hash(x) == hash(Array(x)) - -let a = QuoteNode(1), b = QuoteNode(1.0) - @test (hash(a)==hash(b)) == (a==b) -end - -let a = Expr(:block, TypedSlot(1, Any)), - b = Expr(:block, TypedSlot(1, Any)), - c = Expr(:block, TypedSlot(3, Any)) - @test a == b && hash(a) == hash(b) - @test a != c && hash(a) != hash(c) - @test b != c && hash(b) != hash(c) -end - -@test hash(Dict(),hash(Set())) != hash(Set(),hash(Dict())) - -# issue 15659 -for prec in [3, 11, 15, 16, 31, 32, 33, 63, 64, 65, 254, 255, 256, 257, 258, 1023, 1024, 1025], - v in Any[-0.0, 0, 1, -1, 1//10, 2//10, 3//10, 1//2, pi] - setprecision(prec) do - x = convert(BigFloat, v) - @test precision(x) == prec - num, pow, den = Base.decompose(x) - y = num*big(2.0)^pow/den - @test precision(y) == prec - @test isequal(x, y) - end -end - -# issue #20744 -@test hash(:c, hash(:b, hash(:a))) != hash(:a, hash(:b, hash(:c))) diff --git a/julia-0.6.3/share/julia/test/i18n.jl b/julia-0.6.3/share/julia/test/i18n.jl deleted file mode 100644 index 0ff3d60..0000000 --- a/julia-0.6.3/share/julia/test/i18n.jl +++ /dev/null @@ -1,7 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -using Base.I18n - -@test locale()=="" -locale("en_US") -@test locale()=="en_US" diff --git a/julia-0.6.3/share/julia/test/inference.jl b/julia-0.6.3/share/julia/test/inference.jl deleted file mode 100644 index 207a45f..0000000 --- a/julia-0.6.3/share/julia/test/inference.jl +++ /dev/null @@ -1,976 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -# tests for Core.Inference correctness and precision -import Core.Inference: Const, Conditional, ⊑ - -# issue 9770 -@noinline x9770() = false -function f9770(x) - return if x9770() - g9770(:a, :foo) - else - x - end -end -function g9770(x,y) - return if isa(y, Symbol) - f9770(x) - else - g9770(:a, :foo) - end -end -@test g9770(:a, "c") === :a -@test g9770(:b, :c) === :b - - -# issue #1628 -mutable struct I1628{X} - x::X -end -let - # here the potential problem is that the run-time value of static - # parameter X in the I1628 constructor is (DataType,DataType), - # but type inference will track it more accurately as - # (Type{Integer}, Type{Int}). - f1628() = I1628((Integer,Int)) - @test isa(f1628(), I1628{Tuple{DataType,DataType}}) -end - -let - fT{T}(x::T) = T - @test fT(Any) === DataType - @test fT(Int) === DataType - @test fT(Type{Any}) === DataType - @test fT(Type{Int}) === DataType - - ff{T}(x::Type{T}) = T - @test ff(Type{Any}) === Type{Any} - @test ff(Type{Int}) === Type{Int} - @test ff(Any) === Any - @test ff(Int) === Int -end - - -# issue #3182 -f3182{T}(::Type{T}) = 0 -f3182(x) = 1 -function g3182(t::DataType) - # tricky thing here is that DataType is a concrete type, and a - # subtype of Type, but we cannot infer the T in Type{T} just - # by knowing (at compile time) that the argument is a DataType. - # however the ::Type{T} method should still match at run time. - return f3182(t) -end -@test g3182(Complex.body) == 0 - - -# issue #5906 - -abstract type Outer5906{T} end - -struct Inner5906{T} - a:: T -end - -struct Empty5906{T} <: Outer5906{T} -end - -struct Hanoi5906{T} <: Outer5906{T} - a::T - succ :: Outer5906{Inner5906{T}} - Hanoi5906{T}(a) where T = new(a, Empty5906{Inner5906{T}}()) -end - -function f5906{T}(h::Hanoi5906{T}) - if isa(h.succ, Empty5906) return end - f5906(h.succ) -end - -# can cause infinite recursion in type inference via instantiation of -# the type of the `succ` field -@test f5906(Hanoi5906{Int}(1)) === nothing - -# issue on the flight from DFW -# (type inference deducing Type{:x} rather than Symbol) -mutable struct FooBarDFW{s}; end -fooDFW(p::Type{FooBarDFW}) = string(p.parameters[1]) -fooDFW(p) = string(p.parameters[1]) -@test fooDFW(FooBarDFW{:x}) == "x" # not ":x" - -# Type inference for tuple parameters -struct fooTuple{s}; end -barTuple1() = fooTuple{(:y,)}() -barTuple2() = fooTuple{tuple(:y)}() - -@test Base.return_types(barTuple1,Tuple{})[1] == Base.return_types(barTuple2,Tuple{})[1] == fooTuple{(:y,)} - -# issue #6050 -@test Core.Inference.getfield_tfunc( - Dict{Int64,Tuple{UnitRange{Int64},UnitRange{Int64}}}, - Core.Inference.Const(:vals)) == Array{Tuple{UnitRange{Int64},UnitRange{Int64}},1} - -# issue #12476 -function f12476(a) - (k, v) = a - return v -end -@inferred f12476(1.0 => 1) - - -# issue #12551 (make sure these don't throw in inference) -Base.return_types(unsafe_load, (Ptr{nothing},)) -Base.return_types(getindex, (Vector{nothing},)) - - -# issue #12636 -module MyColors - -abstract type Paint{T} end -struct RGB{T<:AbstractFloat} <: Paint{T} - r::T - g::T - b::T -end - -myeltype{T}(::Type{Paint{T}}) = T -myeltype{P<:Paint}(::Type{P}) = myeltype(supertype(P)) -myeltype(::Type{Any}) = Any - -end - -@test @inferred(MyColors.myeltype(MyColors.RGB{Float32})) == Float32 -@test @inferred(MyColors.myeltype(MyColors.RGB)) == Any - - -# issue #12826 -f12826{I<:Integer}(v::Vector{I}) = v[1] -@test Base.return_types(f12826,Tuple{Array{I,1} where I<:Integer})[1] == Integer - - -# non-terminating inference, issue #14009 -# non-terminating codegen, issue #16201 -mutable struct A14009{T}; end -A14009{T}(a::T) = A14009{T}() -f14009(a) = rand(Bool) ? f14009(A14009(a)) : a -code_typed(f14009, (Int,)) -code_llvm(DevNull, f14009, (Int,)) - -mutable struct B14009{T}; end -g14009(a) = g14009(B14009{a}) -code_typed(g14009, (Type{Int},)) -code_llvm(DevNull, f14009, (Int,)) - - -# issue #9232 -arithtype9232{T<:Real}(::Type{T},::Type{T}) = arithtype9232(T) -result_type9232{T1<:Number,T2<:Number}(::Type{T1}, ::Type{T2}) = arithtype9232(T1, T2) -# this gave a "type too large", but not reliably -@test length(code_typed(result_type9232, Tuple{(Type{x} where x<:Union{Float32,Float64}), Type{T2} where T2<:Number})) == 1 - - -# issue #10878 -function g10878(x; kw...); end -invoke_g10878() = invoke(g10878, Tuple{Any}, 1) -@code_typed invoke_g10878() -code_llvm(DevNull, invoke_g10878, ()) - - -# issue #10930 -@test isa(code_typed(promote,(Any,Any,Vararg{Any})), Array) -find_tvar10930{T<:Tuple}(sig::Type{T}) = 1 -function find_tvar10930(arg) - if arg<:Tuple - find_tvar10930(arg[random_var_name]) - end - return 1 -end -@test find_tvar10930(Vararg{Int}) === 1 - - -# issue #12474 -@generated function f12474(::Any) - :(for i in 1 - end) -end -let - ast12474 = code_typed(f12474, Tuple{Float64}) - @test isleaftype(ast12474[1][2]) - @test all(isleaftype, ast12474[1][1].slottypes) -end - - -# pr #15259 -struct A15259 - x - y -end -# check that allocation was ellided -@eval f15259(x,y) = (a = $(Expr(:new, :A15259, :x, :y)); (a.x, a.y, getfield(a,1), getfield(a, 2))) -@test isempty(filter(x -> isa(x,Expr) && x.head === :(=) && - isa(x.args[2], Expr) && x.args[2].head === :new, - code_typed(f15259, (Any,Int))[1][1].code)) -@test f15259(1,2) == (1,2,1,2) -# check that error cases are still correct -@eval g15259(x,y) = (a = $(Expr(:new, :A15259, :x, :y)); a.z) -@test_throws ErrorException g15259(1,1) -@eval h15259(x,y) = (a = $(Expr(:new, :A15259, :x, :y)); getfield(a, 3)) -@test_throws BoundsError h15259(1,1) - - -# issue #7810 -mutable struct Foo7810{T<:AbstractVector} - v::T -end -bar7810() = [Foo7810([(a,b) for a in 1:2]) for b in 3:4] -@test Base.return_types(bar7810,Tuple{})[1] == Array{Foo7810{Array{Tuple{Int,Int},1}},1} - - -# issue #11366 -f11366{T}(x::Type{Ref{T}}) = Ref{x} -@test !isleaftype(Base.return_types(f11366, (Any,))[1]) - - -let f(T) = Type{T} - @test Base.return_types(f, Tuple{Type{Int}}) == [Type{Type{Int}}] -end - -# issue #9222 -function SimpleTest9222{T1<:Real}(pdedata, mu_actual::Vector{T1}, - nu_actual::Vector{T1}, v0::Vector{T1}, epsilon::T1, beta::Vector{T1}, - delta::T1, l::T1, R::T1, s0::T1, show_trace::Bool = true) - return 0.0 -end -function SimpleTest9222{T1<:Real}(pdedata, mu_actual::Vector{T1}, - nu_actual::Vector{T1}, v0::Vector{T1}, epsilon::T1, beta::Vector{T1}, - delta::T1, l::T1, R::T1) - return SimpleTest9222(pdedata, mu_actual, nu_actual, v0, epsilon, - beta, delta, l, R, v0[1]) -end -function foo9222() - v0 = rand(10) - mu_actual = rand(10) - nu_actual = rand(10) - SimpleTest9222(0.0, mu_actual, nu_actual, v0, 0.0, [1.0,1.0], 0.5, 5.0, 20.0) -end -@test 0.0 == foo9222() - -# make sure none of the slottypes are left as Core.Inference.Const objects -function f18679() - for i = 1:2 - if i == 1 - a = ((),) - else - return a[1] - end - end -end -g18679(x::Tuple) = () -g18679() = g18679(any_undef_global::Union{Int,Tuple{}}) -for code in Any[ - @code_typed(f18679())[1] - @code_typed(g18679())[1]] - @test all(x->isa(x, Type), code.slottypes) - local notconst(other::ANY) = true - notconst(slot::TypedSlot) = @test isa(slot.typ, Type) - function notconst(expr::Expr) - @test isa(expr.typ, Type) - for a in expr.args - notconst(a) - end - end - for e in code.code - notconst(e) - end -end - -# branching based on inferrable conditions -let f(x) = isa(x,Int) ? 1 : "" - @test Base.return_types(f, Tuple{Int}) == [Int] -end - -let g() = Int <: Real ? 1 : "" - @test Base.return_types(g, Tuple{}) == [Int] -end - -const NInt{N} = Tuple{Vararg{Int, N}} -@test Base.eltype(NInt) === Int -@test Base.return_types(eltype, (NInt,)) == Any[Union{Type{Int}, Type{Union{}}}] # issue 21763 -fNInt(x::NInt) = (x...) -gNInt() = fNInt(x) -@test Base.return_types(gNInt, ()) == Any[NInt] - -# issue #17572 -function f17572{A}(::Type{Val{A}}) - return Tuple{Int}(Tuple{A}((1,))) -end -# test that inference doesn't error -@test isa(code_typed(f17572, (Type{Val{0}},)), Array) - -# === with singleton constants -let f(x) = (x===nothing) ? 1 : 1.0 - @test Base.return_types(f, (Void,)) == Any[Int] -end - -# issue #16530 -mutable struct Foo16530a{dim} - c::Vector{NTuple{dim, Float64}} - d::Vector -end -mutable struct Foo16530b{dim} - c::Vector{NTuple{dim, Float64}} -end -f16530a() = fieldtype(Foo16530a, :c) -f16530a(c) = fieldtype(Foo16530a, c) -f16530b() = fieldtype(Foo16530b, :c) -f16530b(c) = fieldtype(Foo16530b, c) - -let T = Vector{Tuple{Vararg{Float64,dim}}} where dim - @test f16530a() == T - @test f16530a(:c) == T - @test Base.return_types(f16530a, ()) == Any[Type{T}] - @test Base.return_types(f16530b, ()) == Any[Type{T}] - @test Base.return_types(f16530b, (Symbol,)) == Any[Type{T}] -end -@test f16530a(:d) == Vector - -let T1 = Tuple{Int, Float64}, - T2 = Tuple{Int, Float32}, - T = Tuple{T1, T2} - - global f18037 - f18037() = fieldtype(T, 1) - f18037(i) = fieldtype(T, i) - - @test f18037() === T1 - @test f18037(1) === T1 - @test f18037(2) === T2 - - @test Base.return_types(f18037, ()) == Any[Type{T1}] - @test Base.return_types(f18037, (Int,)) == Any[Union{Type{T1},Type{T2}}] -end - -# issue #18015 -mutable struct Triple18015 - a::Int - b::Int - c::Int -end -a18015(tri) = tri.a -b18015(tri) = tri.b -c18015(tri) = tri.c -setabc18015!(tri, a, b, c) = (tri.a = a; tri.b = b; tri.c = c) -let tri = Triple18015(1, 2, 3) - setabc18015!(tri, b18015(tri), c18015(tri), a18015(tri)) - @test tri.a === 2 && tri.b === 3 && tri.c === 1 -end - -# issue #18222 -f18222{T<:AbstractFloat}(::Union{T, Int}) = false -f18222(x) = true -g18222(x) = f18222(x) -@test f18222(1) == g18222(1) == true -@test f18222(1.0) == g18222(1.0) == false - -# issue #18399 -# TODO: this test is rather brittle -mutable struct TSlow18399{T} - x::T -end -function hvcat18399(as) - cb = ri->as[ri] - g = Base.Generator(cb, 1) - return g.f(1) -end -function cat_t18399(X...) - for i = 2:1 - X[i] - d->i - end -end -C18399 = TSlow18399{Int}(1) -GB18399 = TSlow18399{Int}(1) -function test18399(C) - B = GB18399::Union{TSlow18399{Int},TSlow18399{Any}} - cat_t18399() - cat_t18399(B, B, B) - hvcat18399((C,)) - return hvcat18399(((2, 3),)) -end -@test test18399(C18399) == (2, 3) - -# issue #18450 -f18450() = ifelse(true, Tuple{Vararg{Int}}, Tuple{Vararg}) -@test f18450() == Tuple{Vararg{Int}} - -# issue #18569 -@test !Core.Inference.isconstType(Type{Tuple}) - -# ensure pure attribute applies correctly to all signatures of fpure -Base.@pure function fpure(a=rand(); b=rand()) - # use the `rand` function since it is known to be `@inline` - # but would be too big to inline - return a + b + rand() -end -gpure() = fpure() -gpure(x::Irrational) = fpure(x) -@test which(fpure, ()).pure -@test which(fpure, (typeof(pi),)).pure -@test !which(gpure, ()).pure -@test !which(gpure, (typeof(pi),)).pure -@test @code_typed(gpure())[1].pure -@test @code_typed(gpure(π))[1].pure -@test gpure() == gpure() == gpure() -@test gpure(π) == gpure(π) == gpure(π) - -# Make sure @pure works for functions using the new syntax -Base.@pure (fpure2(x::T) where T) = T -@test which(fpure2, (Int64,)).pure - -# issue #10880 -function cat10880(a, b) - Tuple{a.parameters..., b.parameters...} -end -@inferred cat10880(Tuple{Int8,Int16}, Tuple{Int32}) - -# issue #19348 -function is_typed_expr(e::Expr) - if e.head === :call || - e.head === :invoke || - e.head === :new || - e.head === :copyast || - e.head === :inert - return true - end - return false -end -test_inferred_static(other::ANY) = true -test_inferred_static(slot::TypedSlot) = @test isleaftype(slot.typ) -function test_inferred_static(expr::Expr) - if is_typed_expr(expr) - @test isleaftype(expr.typ) - end - for a in expr.args - test_inferred_static(a) - end -end -function test_inferred_static(arrow::Pair) - code, rt = arrow - @test isleaftype(rt) - @test code.inferred - @test all(x->isleaftype(x), code.slottypes) - @test all(x->isleaftype(x), code.ssavaluetypes) - for e in code.code - test_inferred_static(e) - end -end - -function g19348(x) - a, b = x - return a + b -end -test_inferred_static(@code_typed g19348((1, 2.0))) - -# issue #5575 -f5575() = zeros(Type[Float64][1], 1) -@test Base.return_types(f5575, ())[1] == Vector - -# make sure Tuple{unknown} handles the possibility that `unknown` is a Vararg -function maybe_vararg_tuple_1() - x = Any[Vararg{Int}][1] - Tuple{x} -end -@test Type{Tuple{Vararg{Int}}} <: Base.return_types(maybe_vararg_tuple_1, ())[1] -function maybe_vararg_tuple_2() - x = Type[Vararg{Int}][1] - Tuple{x} -end -@test Type{Tuple{Vararg{Int}}} <: Base.return_types(maybe_vararg_tuple_2, ())[1] - -# inference of `fieldtype` -mutable struct UndefField__ - x::Union{} -end -f_infer_undef_field() = fieldtype(UndefField__, :x) -@test Base.return_types(f_infer_undef_field, ()) == Any[Type{Union{}}] -@test f_infer_undef_field() === Union{} - -mutable struct HasAbstractlyTypedField - x::Union{Int,String} -end -f_infer_abstract_fieldtype() = fieldtype(HasAbstractlyTypedField, :x) -@test Base.return_types(f_infer_abstract_fieldtype, ()) == Any[Type{Union{Int,String}}] - -# issue #11480 -@noinline f11480(x,y) = x -let A = Ref - function h11480(x::A{A{A{A{A{A{A{A{A{Int}}}}}}}}}) # enough for type_too_complex - y :: Tuple{Vararg{typeof(x)}} = (x,) # apply_type(Vararg, too_complex) => TypeVar(_,Vararg) - f(y[1], # fool getfield logic : Tuple{_<:Vararg}[1] => Vararg - 1) # make it crash by construction of the signature Tuple{Vararg,Int} - end - @test !Base.isvarargtype(Base.return_types(h11480, (Any,))[1]) -end - -# Issue 19641 -foo19641() = let a = 1.0 - Core.Inference.return_type(x -> x + a, Tuple{Float64}) -end -@inferred foo19641() - -test_fast_eq(a, b) = @fastmath a == b -test_fast_ne(a, b) = @fastmath a != b -test_fast_lt(a, b) = @fastmath a < b -test_fast_le(a, b) = @fastmath a <= b -@inferred test_fast_eq(1f0, 1f0) -@inferred test_fast_ne(1f0, 1f0) -@inferred test_fast_lt(1f0, 1f0) -@inferred test_fast_le(1f0, 1f0) -@inferred test_fast_eq(1.0, 1.0) -@inferred test_fast_ne(1.0, 1.0) -@inferred test_fast_lt(1.0, 1.0) -@inferred test_fast_le(1.0, 1.0) - -abstract type AbstractMyType18457{T,F,G} end -struct MyType18457{T,F,G}<:AbstractMyType18457{T,F,G} end -tpara18457{I}(::Type{AbstractMyType18457{I}}) = I -tpara18457{A<:AbstractMyType18457}(::Type{A}) = tpara18457(supertype(A)) -@test tpara18457(MyType18457{true}) === true - -@testset "type inference error #19322" begin - Y_19322 = reshape(round.(Int, abs.(randn(5*1000)))+1,1000,5) - - function FOO_19322(Y::AbstractMatrix; frac::Float64=0.3, nbins::Int=100, n_sims::Int=100) - num_iters, num_chains = size(Y) - start_iters = unique([1; [round(Int64, s) for s in logspace(log(10,100), - log(10,num_iters/2),nbins-1)]]) - result = zeros(Float64, 10, length(start_iters) * num_chains) - j=1 - for c in 1:num_chains - for st in 1:length(start_iters) - n = length(start_iters[st]:num_iters) - idx1 = start_iters[st]:round(Int64, start_iters[st] + frac * n - 1) - idx2 = round(Int64, num_iters - frac * n + 1):num_iters - y1 = Y[idx1,c] - y2 = Y[idx2,c] - n_min = min(length(y1), length(y2)) - X = [y1[1:n_min] y2[(end - n_min + 1):end]] - end - end - end - - @test_nowarn FOO_19322(Y_19322) -end - -randT_inferred_union() = rand(Bool) ? rand(Bool) ? 1 : 2.0 : nothing -function f_inferred_union() - b = randT_inferred_union() - if !(nothing !== b) === true - return f_inferred_union_nothing(b) - elseif (isa(b, Float64) === true) !== false - return f_inferred_union_float(b) - else - return f_inferred_union_int(b) - end -end -f_inferred_union_nothing(::Void) = 1 -f_inferred_union_nothing(::Any) = "broken" -f_inferred_union_float(::Float64) = 2 -f_inferred_union_float(::Any) = "broken" -f_inferred_union_int(::Int) = 3 -f_inferred_union_int(::Any) = "broken" -@test @inferred(f_inferred_union()) in (1, 2, 3) - -# issue #11015 -mutable struct AT11015 - f::Union{Bool,Function} -end - -g11015{S}(::Type{S}, ::S) = 1 -f11015(a::AT11015) = g11015(Base.fieldtype(typeof(a), :f), true) -g11015(::Type{Bool}, ::Bool) = 2.0 -@test Int <: Base.return_types(f11015, (AT11015,))[1] -@test f11015(AT11015(true)) === 1 - -# better inference of apply (#20343) -f20343(::String, ::Int) = 1 -f20343(::Int, ::String, ::Int, ::Int) = 1 -f20343(::Int, ::Int, ::String, ::Int, ::Int, ::Int) = 1 -f20343(::Union{Int,String}...) = Int8(1) -f20343(::Any...) = "no" -function g20343() - n = rand(1:3) - i = ntuple(i->n==i ? "" : 0, 2n)::Union{Tuple{String,Int},Tuple{Int,String,Int,Int},Tuple{Int,Int,String,Int,Int,Int}} - f20343(i...) -end -@test Base.return_types(g20343, ()) == [Int] -function h20343() - n = rand(1:3) - i = ntuple(i->n==i ? "" : 0, 3)::Union{Tuple{String,Int,Int},Tuple{Int,String,Int},Tuple{Int,Int,String}} - f20343(i..., i...) -end -@test all(t -> t<:Integer, Base.return_types(h20343, ())) -function i20343() - f20343([1,2,3]..., 4) -end -@test Base.return_types(i20343, ()) == [Int8] -struct Foo20518 <: AbstractVector{Int}; end # issue #20518; inference assumed AbstractArrays -Base.getindex(::Foo20518, ::Int) = "oops" # not to lie about their element type -Base.indices(::Foo20518) = (Base.OneTo(4),) -foo20518(xs::Any...) = -1 -foo20518(xs::Int...) = [0] -bar20518(xs) = sum(foo20518(xs...)) -@test bar20518(Foo20518()) == -1 -f19957(::Int) = Int8(1) # issue #19957, inference failure when splatting a number -f19957(::Int...) = Int16(1) -f19957(::Any...) = "no" -g19957(x) = f19957(x...) -@test all(t -> t<:Union{Int8,Int16}, Base.return_types(g19957, (Int,))) # with a full fix, this should just be Int8 - -# Inference for some type-level computation -fUnionAll{T}(::Type{T}) = Type{S} where S <: T -@inferred fUnionAll(Real) == Type{T} where T <: Real -@inferred fUnionAll(Rational{T} where T <: AbstractFloat) == Type{T} where T<:(Rational{S} where S <: AbstractFloat) - -fComplicatedUnionAll{T}(::Type{T}) = Type{Tuple{S,rand() >= 0.5 ? Int : Float64}} where S <: T -let pub = Base.parameter_upper_bound, x = fComplicatedUnionAll(Real) - @test pub(pub(x, 1), 1) == Real - @test pub(pub(x, 1), 2) == Int || pub(pub(x, 1), 2) == Float64 -end - -# issue #20733 -# run this test in a separate process to avoid interfering with `getindex` -let def = "Base.getindex(t::NTuple{3,NTuple{2,Int}}, i::Int, j::Int, k::Int) = (t[1][i], t[2][j], t[3][k])" - @test readstring(`$(Base.julia_cmd()) --startup-file=no -E "$def;test(t) = t[2,1,2];test(((3,4), (5,6), (7,8)))"`) == - "(4, 5, 8)\n" -end - -# issue #20267 -mutable struct T20267{T} - inds::Vector{T} -end -# infinite type growth via lower bounds (formed by intersection) -f20267(x::T20267{T}, y::T) where (T) = f20267(Any[1][1], x.inds) -@test Base.return_types(f20267, (Any, Any)) == Any[Union{}] - -# issue #20615 -let A = 1:2, z = zip(A, A, A, A, A, A, A, A, A, A, A, A) - @test z isa Core.Inference.limit_type_depth(typeof(z), 0) - @test start(z) == (1, (1, (1, (1, (1, (1, (1, (1, (1, (1, (1, 1))))))))))) -end -# introduce TypeVars in Unions in invariant position -let T = Val{Val{Val{Union{Int8,Int16,Int32,Int64,UInt8,UInt16,UInt32,UInt64}}}} - @test T <: Core.Inference.limit_type_depth(T, 0) -end - -# issue #20704 -f20704(::Int) = 1 -Base.@pure b20704(x::ANY) = f20704(x) -@test b20704(42) === 1 -@test_throws MethodError b20704(42.0) - -bb20704() = b20704(Any[1.0][1]) -@test_throws MethodError bb20704() - -v20704() = Val{b20704(Any[1.0][1])} -@test_throws MethodError v20704() -@test Base.return_types(v20704, ()) == Any[Type{Val{1}}] - -Base.@pure g20704(::Int) = 1 -h20704(x::ANY) = g20704(x) -@test g20704(1) === 1 -@test_throws MethodError h20704(1.2) - -Base.@pure c20704() = (f20704(1.0); 1) -d20704() = c20704() -@test_throws MethodError d20704() - -Base.@pure function a20704(x) - rand() - 42 -end -aa20704(x) = x(nothing) -@test code_typed(aa20704, (typeof(a20704),))[1][1].pure - -#issue #21065, elision of _apply when splatted expression is not effect_free -function f21065(x,y) - println("x=$x, y=$y") - return x, y -end -g21065(x,y) = +(f21065(x,y)...) -function test_no_apply(expr::Expr) - return all(test_no_apply, expr.args) -end -function test_no_apply(ref::GlobalRef) - return ref.mod != Core || ref.name !== :_apply -end -test_no_apply(::Any) = true -@test all(test_no_apply, code_typed(g21065, Tuple{Int,Int})[1].first.code) - -# issue #20033 -# check return_type_tfunc for calls where no method matches -bcast_eltype_20033(f, A) = Core.Inference.return_type(f, Tuple{eltype(A)}) -err20033(x::Float64...) = prod(x) -@test bcast_eltype_20033(err20033, [1]) === Union{} -@test Base.return_types(bcast_eltype_20033, (typeof(err20033), Vector{Int},)) == Any[Type{Union{}}] -# return_type on builtins -@test Core.Inference.return_type(tuple, Tuple{Int,Int8,Int}) === Tuple{Int,Int8,Int} - -# issue #21088 -@test Core.Inference.return_type(typeof, Tuple{Int}) == Type{Int} - -# Inference of constant svecs -@eval fsvecinf() = $(QuoteNode(Core.svec(Tuple{Int,Int}, Int)))[1] -@test Core.Inference.return_type(fsvecinf, Tuple{}) == Type{Tuple{Int,Int}} - -# nfields tfunc on `DataType` -let f = ()->Val{nfields(DataType[Int][1])} - @test f() == Val{0} -end - -# inference on invalid getfield call -@eval _getfield_with_string_() = getfield($(1=>2), "") -@test Base.return_types(_getfield_with_string_, ()) == Any[Union{}] - -# inference AST of a constant return value -f21175() = 902221 -@test code_typed(f21175, ())[1].second === Int -# call again, so that the AST is built on-demand -let e = code_typed(f21175, ())[1].first.code[1]::Expr - @test e.head === :return - @test e.args[1] ∈ (902221, Core.QuoteNode(902221)) -end - -# issue #10207 -mutable struct T10207{A, B} - a::A - b::B -end -@test code_typed(T10207, (Int,Any))[1].second == T10207{Int,T} where T - -# issue #21410 -f21410(::V, ::Pair{V,E}) where {V, E} = E -@test code_typed(f21410, Tuple{Ref, Pair{Ref{T},Ref{T}} where T<:Number})[1].second == Type{Ref{T}} where T<:Number - -# issue #21369 -function inf_error_21369(arg) - if arg - # invalid instantiation, causing throw during inference - Complex{String} - end -end -function break_21369() - try - error("uhoh") - catch - eval(:(inf_error_21369(false))) - bt = catch_backtrace() - i = 1 - local fr - while true - fr = Base.StackTraces.lookup(bt[i])[end] - if !fr.from_c - break - end - i += 1 - end - @test fr.func === :break_21369 - rethrow() - end -end -@test_throws ErrorException break_21369() # not TypeError - -# issue #17003 -abstract type AArray_17003{T,N} end -AVector_17003{T} = AArray_17003{T,1} - -struct Nable_17003{T} -end - -struct NArray_17003{T,N} <: AArray_17003{Nable_17003{T},N} -end - -(::Type{NArray_17003}){T,N}(::Array{T,N}) = NArray_17003{T,N}() - -gl_17003 = [1, 2, 3] - -f2_17003(item::AVector_17003) = nothing -f2_17003(::Any) = f2_17003(NArray_17003(gl_17003)) - -@test f2_17003(1) == nothing - -# issue #20847 -function segfaultfunction_20847{N, T}(A::Vector{NTuple{N, T}}) - B = reinterpret(T, A, (N, length(A))) - return nothing -end - -tuplevec_20847 = Tuple{Float64, Float64}[(0.0,0.0), (1.0,0.0)] - -for A in (1,) - @test segfaultfunction_20847(tuplevec_20847) == nothing -end - -# issue #21848 -@test Core.Inference.limit_type_depth(Ref{Complex{T} where T}, Core.Inference.MAX_TYPE_DEPTH) == Ref -let T = Tuple{Tuple{Int64, Void}, - Tuple{Tuple{Int64, Void}, - Tuple{Int64, Tuple{Tuple{Int64, Void}, - Tuple{Tuple{Int64, Void}, Tuple{Int64, Tuple{Tuple{Int64, Void}, Tuple{Tuple, Tuple}}}}}}}} - @test Core.Inference.limit_type_depth(T, 0) >: T - @test Core.Inference.limit_type_depth(T, 1) >: T - @test Core.Inference.limit_type_depth(T, 2) >: T -end - -# Issue #20902, check that this doesn't error. -@generated function test_20902() - quote - 10 + 11 - end -end -@test length(code_typed(test_20902, (), optimize = false)) == 1 -@test length(code_typed(test_20902, (), optimize = false)) == 1 - -# normalization of arguments with constant Types as parameters -g21771(T) = T -f21771(::Val{U}) where {U} = Tuple{g21771(U)} -@test @inferred(f21771(Val{Int}())) === Tuple{Int} -@test @inferred(f21771(Val{Union{}}())) === Tuple{Union{}} -@test @inferred(f21771(Val{Integer}())) === Tuple{Integer} - -# issue #21653 -# ensure that we don't try to resolve cycles using uncached edges -f21653() = f21653() -@test code_typed(f21653, Tuple{}, optimize=false)[1] isa Pair{CodeInfo, typeof(Union{})} - -@noinline map3_22347(f, t::Tuple{}) = () -@noinline map3_22347(f, t::Tuple) = (f(t[1]), map3_22347(f, Base.tail(t))...) -# issue #22347 -let niter = 0 - map3_22347((1, 2, 3, 4)) do y - niter += 1 - nothing - end - @test niter == 4 -end - -let isa_tfunc = Core.Inference.t_ffunc_val[ - findfirst(Core.Inference.t_ffunc_key, isa)][3] - @test isa_tfunc(Array, Const(AbstractArray)) === Const(true) - @test isa_tfunc(Array, Type{AbstractArray}) === Const(true) - @test isa_tfunc(Array, Type{AbstractArray{Int}}) == Bool - @test isa_tfunc(Array{Real}, Type{AbstractArray{Int}}) === Const(false) - @test isa_tfunc(Array{Real, 2}, Const(AbstractArray{Real, 2})) === Const(true) - @test isa_tfunc(Array{Real, 2}, Const(AbstractArray{Int, 2})) === Const(false) - @test isa_tfunc(DataType, Int) === Bool # could be improved - @test isa_tfunc(DataType, Const(Type{Int})) === Bool - @test isa_tfunc(DataType, Const(Type{Array})) === Bool - @test isa_tfunc(UnionAll, Const(Type{Int})) === Bool # could be improved - @test isa_tfunc(UnionAll, Const(Type{Array})) === Bool - @test isa_tfunc(Union, Const(Union{Float32, Float64})) === Bool - @test isa_tfunc(Union, Type{Union}) === Const(true) - @test isa_tfunc(typeof(Union{}), Const(Int)) === Bool # any result is ok - @test isa_tfunc(typeof(Union{}), Const(Union{})) === Const(false) - @test isa_tfunc(typeof(Union{}), typeof(Union{})) === Const(false) - @test isa_tfunc(typeof(Union{}), Union{}) === Const(false) # any result is ok - @test isa_tfunc(typeof(Union{}), Type{typeof(Union{})}) === Const(true) - @test isa_tfunc(typeof(Union{}), Const(typeof(Union{}))) === Const(true) - let c = Conditional(Core.SlotNumber(0), Const(Union{}), Const(Union{})) - @test isa_tfunc(c, Const(Bool)) === Const(true) - @test isa_tfunc(c, Type{Bool}) === Const(true) - @test isa_tfunc(c, Const(Real)) === Const(true) - @test isa_tfunc(c, Type{Real}) === Const(true) - @test isa_tfunc(c, Const(Signed)) === Const(false) - @test isa_tfunc(c, Type{Complex}) === Const(false) - @test isa_tfunc(c, Type{Complex{T}} where T) === Const(false) - end - @test isa_tfunc(Val{1}, Type{Val{T}} where T) === Bool - @test isa_tfunc(Val{1}, DataType) === Bool - @test isa_tfunc(Any, Const(Any)) === Const(true) - @test isa_tfunc(Any, Union{}) === Const(false) # any result is ok - @test isa_tfunc(Any, Type{Union{}}) === Const(false) - @test isa_tfunc(Union{Int64, Float64}, Type{Real}) === Const(true) - @test isa_tfunc(Union{Int64, Float64}, Type{Integer}) === Bool - @test isa_tfunc(Union{Int64, Float64}, Type{AbstractArray}) === Const(false) -end - -let subtype_tfunc = Core.Inference.t_ffunc_val[ - findfirst(Core.Inference.t_ffunc_key, <:)][3] - @test subtype_tfunc(Type{<:Array}, Const(AbstractArray)) === Const(true) - @test subtype_tfunc(Type{<:Array}, Type{AbstractArray}) === Const(true) - @test subtype_tfunc(Type{<:Array}, Type{AbstractArray{Int}}) == Bool - @test subtype_tfunc(Type{<:Array{Real}}, Type{AbstractArray{Int}}) === Const(false) - @test subtype_tfunc(Type{<:Array{Real, 2}}, Const(AbstractArray{Real, 2})) === Const(true) - @test subtype_tfunc(Type{Array{Real, 2}}, Const(AbstractArray{Int, 2})) === Const(false) - @test subtype_tfunc(DataType, Int) === Bool - @test subtype_tfunc(DataType, Const(Type{Int})) === Bool - @test subtype_tfunc(DataType, Const(Type{Array})) === Bool - @test subtype_tfunc(UnionAll, Const(Type{Int})) === Bool - @test subtype_tfunc(UnionAll, Const(Type{Array})) === Bool - @test subtype_tfunc(Union, Const(Union{Float32, Float64})) === Bool - @test subtype_tfunc(Union, Type{Union}) === Bool - @test subtype_tfunc(Union{}, Const(Int)) === Const(true) # any result is ok - @test subtype_tfunc(Union{}, Const(Union{})) === Const(true) # any result is ok - @test subtype_tfunc(Union{}, typeof(Union{})) === Const(true) # any result is ok - @test subtype_tfunc(Union{}, Union{}) === Const(true) # any result is ok - @test subtype_tfunc(Union{}, Type{typeof(Union{})}) === Const(true) # any result is ok - @test subtype_tfunc(Union{}, Const(typeof(Union{}))) === Const(true) # any result is ok - @test subtype_tfunc(typeof(Union{}), Const(typeof(Union{}))) === Const(true) # Union{} <: typeof(Union{}) - @test subtype_tfunc(typeof(Union{}), Const(Int)) === Const(true) # Union{} <: Int - @test subtype_tfunc(typeof(Union{}), Const(Union{})) === Const(true) # Union{} <: Union{} - @test subtype_tfunc(typeof(Union{}), Type{typeof(Union{})}) === Const(true) # Union{} <: Union{} - @test subtype_tfunc(typeof(Union{}), Type{typeof(Union{})}) === Const(true) # Union{} <: typeof(Union{}) - @test subtype_tfunc(typeof(Union{}), Type{Union{}}) === Const(true) # Union{} <: Union{} - @test subtype_tfunc(Type{Union{}}, typeof(Union{})) === Const(true) # Union{} <: Union{} - @test subtype_tfunc(Type{Union{}}, Const(typeof(Union{}))) === Const(true) # Union{} <: typeof(Union{}) - @test subtype_tfunc(Type{Union{}}, Const(Int)) === Const(true) # Union{} <: typeof(Union{}) - @test subtype_tfunc(Type{Union{}}, Any) === Const(true) # Union{} <: Any - @test subtype_tfunc(Type{Union{}}, Union{Type{Int64}, Type{Float64}}) === Const(true) - @test subtype_tfunc(Type{Union{}}, Union{Type{T}, Type{Float64}} where T) === Const(true) - let c = Conditional(Core.SlotNumber(0), Const(Union{}), Const(Union{})) - @test subtype_tfunc(c, Const(Bool)) === Bool # any result is ok - end - @test subtype_tfunc(Type{Val{1}}, Type{Val{T}} where T) === Bool - @test subtype_tfunc(Type{Val{1}}, DataType) === Bool - @test subtype_tfunc(Type, Type{Val{T}} where T) === Bool - @test subtype_tfunc(Type{Val{T}} where T, Type) === Bool - @test subtype_tfunc(Any, Const(Any)) === Const(true) - @test subtype_tfunc(Type{Any}, Const(Any)) === Const(true) - @test subtype_tfunc(Any, Union{}) === Bool # any result is ok - @test subtype_tfunc(Type{Any}, Union{}) === Const(false) # any result is ok - @test subtype_tfunc(Type, Union{}) === Bool # any result is ok - @test subtype_tfunc(Type, Type{Union{}}) === Bool - @test subtype_tfunc(Union{Type{Int64}, Type{Float64}}, Type{Real}) === Const(true) - @test subtype_tfunc(Union{Type{Int64}, Type{Float64}}, Type{Integer}) === Bool - @test subtype_tfunc(Union{Type{Int64}, Type{Float64}}, Type{AbstractArray}) === Const(false) -end - -function f23024(::Type{T}, ::Int) where T - 1 + 1 -end -v23024 = 0 -g23024(TT::Tuple{DataType}) = f23024(TT[1], v23024) -@test Base.return_types(f23024, (DataType, Any)) == Any[Int] -@test Base.return_types(g23024, (Tuple{DataType},)) == Any[Int] -@test g23024((UInt8,)) === 2 - -# issue #22290 -f22290() = return nothing -for i in 1:3 - ir = sprint(io->code_llvm(io, f22290, Tuple{})) - @test contains(ir, "julia_f22290") -end - -# approximate static parameters due to unions -let T1 = Array{Float64}, T2 = Array{_1,2} where _1 - inference_test_copy(a::T) where {T<:Array} = ccall(:jl_array_copy, Ref{T}, (Any,), a) - rt = Union{Base.return_types(inference_test_copy, (Union{T1,T2},))...} - @test rt >: T1 && rt >: T2 - - el(x::T) where {T} = eltype(T) - rt = Union{Base.return_types(el, (Union{T1,Array{Float32,2}},))...} - @test rt >: Union{Type{Float64}, Type{Float32}} - - g(x::Ref{T}) where {T} = T - rt = Union{Base.return_types(g, (Union{Ref{Array{Float64}}, Ref{Array{Float32}}},))...} - @test rt >: Union{Type{Array{Float64}}, Type{Array{Float32}}} -end diff --git a/julia-0.6.3/share/julia/test/inline.jl b/julia-0.6.3/share/julia/test/inline.jl deleted file mode 100644 index 3a7d7cc..0000000 --- a/julia-0.6.3/share/julia/test/inline.jl +++ /dev/null @@ -1,125 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -using Base.Test - -""" -Helper to walk the AST and call a function on every node. -""" -function walk(func, expr) - func(expr) - if isa(expr, Expr) - func(expr.head) - for o in expr.args - walk(func, o) - end - end -end - -""" -Helper to test that every slot is in range after inlining. -""" -function test_inlined_symbols(func, argtypes) - src, rettype = code_typed(func, argtypes)[1] - nl = length(src.slottypes) - ast = Expr(:body) - ast.args = src.code - ast.typ = rettype - walk(ast) do e - if isa(e, Slot) - @test 1 <= e.id <= nl - end - if isa(e, NewvarNode) - @test 1 <= e.slot.id <= nl - end - end -end - -# Test case 1: -# Make sure that all symbols are properly escaped after inlining -# https://github.com/JuliaLang/julia/issues/12620 -@inline function test_inner(count) - x = 1 - i = 0 - while i <= count - y = x - x = x + y - i += 1 - end -end -function test_outer(a) - test_inner(a) -end -test_inlined_symbols(test_outer, Tuple{Int64}) - -# Test case 2: -# Make sure that an error is thrown for the undeclared -# y in the else branch. -# https://github.com/JuliaLang/julia/issues/12620 -@inline function foo_inl(x) - if x - y = 2 - else - return y - end -end -function bar12620() - for i = 1:3 - foo_inl(i==1) - end -end -@test_throws UndefVarError bar12620() - -# issue #16165 -@inline f16165(x) = (x = UInt(x) + 1) -g16165(x) = f16165(x) -@test g16165(1) === (UInt(1) + 1) - -# issue #18948 -f18948() = (local bar::Int64; bar=1.5) -g18948() = (local bar::Int32; bar=0x80000000) -@test_throws InexactError f18948() -@test_throws InexactError g18948() - -# issue #21074 -struct s21074 - x::Tuple{Int, Int} -end -@inline Base.getindex(v::s21074, i::Integer) = v.x[i] -@eval f21074() = $(s21074((1,2))).x[1] -let (src, _) = code_typed(f21074, ())[1] - @test src.code[end] == Expr(:return, 1) -end -@eval g21074() = $(s21074((1,2)))[1] -let (src, _) = code_typed(g21074, ())[1] - @test src.code[end] == Expr(:return, 1) -end - -# issue #21311 -counter21311 = Ref(0) -@noinline function update21311!(x) - counter21311[] += 1 - x[] = counter21311[] - return x -end -@noinline map21311(t::Tuple{Any}) = (update21311!(t[1]),) -@inline map21311(t::Tuple) = (update21311!(t[1]), map21311(Base.tail(t))...) -function read21311() - xs = Ref(1), Ref(1) - map21311(xs) - return xs[1] -end -let a = read21311() - @test a[] == 1 -end - -@testset "issue #19122: [no]inline of short func. def. with return type annotation" begin - exf19122 = macroexpand(:(@inline f19122()::Bool = true)) - exg19122 = macroexpand(:(@noinline g19122()::Bool = true)) - @test exf19122.args[2].args[1].args[1] == :inline - @test exg19122.args[2].args[1].args[1] == :noinline - - @inline f19122()::Bool = true - @noinline g19122()::Bool = true - @test f19122() - @test g19122() -end diff --git a/julia-0.6.3/share/julia/test/int.jl b/julia-0.6.3/share/julia/test/int.jl deleted file mode 100644 index d89811e..0000000 --- a/julia-0.6.3/share/julia/test/int.jl +++ /dev/null @@ -1,216 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -# Test integer conversion routines from int.jl - - -for y in (-4, Float32(-4), -4.0, big(-4.0)) - @test flipsign(3, y) == -3 - @test flipsign(-3, y) == 3 - @test copysign(3, y) == -3 - @test copysign(-3, y) == -3 -end - -for y in (4, Float32(4), 4.0, big(4.0)) - @test flipsign(3, y) == 3 - @test flipsign(-3, y) == -3 - @test copysign(3, y) == 3 - @test copysign(-3, y) == 3 -end - -# Result type must be type of first argument -for T in (Base.BitInteger_types..., BigInt, - Rational{Int}, Rational{BigInt}, - Float16, Float32, Float64) - for U in (Base.BitInteger_types..., BigInt, - Rational{Int}, Rational{BigInt}, - Float16, Float32, Float64) - @test typeof(copysign(T(3), U(4))) === T - @test typeof(flipsign(T(3), U(4))) === T - end -end - -for s1 in (-1,+1), s2 in (-1,+1) - @test flipsign(Int16(3s1), Float16(3s2)) === Int16(3s1*s2) - @test flipsign(Int32(3s1), Float32(3s2)) === Int32(3s1*s2) - @test flipsign(Int64(3s1), Float64(3s2)) === Int64(3s1*s2) -end - -@test signed(3) == 3 -@test signed(UInt(3)) == 3 -@test isa(signed(UInt(3)), Int) -@test signed(UInt(0) - 1) == -1 -@test_throws InexactError signed(UInt(-3)) - -@test bswap(Int8(3)) == 3 -@test bswap(UInt8(3)) == 3 -@test bswap(Int16(3)) == 256*3 -@test bswap(Int16(256)) == 1 -@test bswap(Int16(257)) == 257 -@test bswap(Int32(1)) == 2^(3*8) -@test bswap(Int32(2)^(3*8)) == 1 -@test bswap(Int64(1)) == Int64(2)^(7*8) -@test bswap(Int64(2)^(7*8)) == 1 -@test bswap(Int128(1)) == Int128(2)^(15*8) -@test bswap(Int128(2)^(15*8)) == Int128(1) -@test bswap(UInt128(2)^(15*8)) == UInt128(1) - -@test count_zeros(10) == Sys.WORD_SIZE - 2 -@test count_zeros(UInt8(10)) == 6 - -@test convert(Signed, UInt128(3)) === Int128(3) -@test convert(Signed, false) === 0 -@test convert(Signed, true) === 1 - -for (II, UU) in ((Int8,UInt8), (Int16,UInt16), - (Int32,UInt32), (Int64,UInt64), - (Int128,UInt128)) - @test convert(Unsigned, II(3)) === UU(3) -end - -for T in (Float32, Float64) - @test convert(Unsigned, T(3.0)) === UInt(3) -end - -@test trunc(3) == 3 -@test trunc(Integer, 3) == 3 - -@test floor(3) == 3 -@test ceil(3) == 3 - -@test big"2"^100 == BigInt(2)^100 -@test isa(big"2", BigInt) -@test big"1.0" == BigFloat(1.0) -@test_throws ArgumentError big"1.0.3" -@test_throws ArgumentError big"pi" - -@test round(UInt8, 123) == 123 -@test mod(123, UInt8) == 0x7b - -primitive type MyBitsType <: Integer 8 end -@test_throws MethodError ~reinterpret(MyBitsType, 0x7b) - -UItypes = Base.BitUnsigned_types -SItypes = Base.BitSigned_types - -for T in UItypes, S in UItypes - @test promote(S(3), T(3)) === (sizeof(T) < sizeof(S) ? (S(3), S(3)) : (T(3), T(3))) -end - -for T in SItypes, S in SItypes - @test promote(S(3), T(3)) === (sizeof(T) < sizeof(S) ? (S(3), S(3)) : (T(3), T(3))) -end - -for T in SItypes, S in UItypes - R = sizeof(S) < sizeof(Int) ? Int : S - @test promote(R(3), T(3)) === (sizeof(R) < sizeof(T) ? (T(3), T(3)) : (R(3), R(3))) -end - -# Test limiting conversions -for T in (Int8, Int16, Int32, Int64) - max_val = Int128(typemax(T)) - @test convert(T, max_val) == max_val - @test_throws InexactError convert(T, max_val+1) - - m = Int128(typemin(T)) - @test convert(T, m) == m - @test_throws InexactError convert(T, m-1) -end - -for T in (UInt8, UInt16, UInt32, UInt64) - max_val = Int128(typemax(T)) - @test convert(T, max_val) == max_val - @test_throws InexactError convert(T, max_val+1) - @test_throws InexactError convert(T, -1) -end - -# Test bit shifts -for T in Base.BitInteger_types - nbits = 8*sizeof(T) - issigned = typemin(T) < 0 - highbit = T(2) ^ (nbits-1) - val1 = 0x1234567890abcdef % T % highbit - val2 = val1 + highbit - for val in (val1, val2) - for count in 0:nbits+1 - ucount, scount = unsigned(count), signed(count) - # Note: We assume modulo semantics for the arithmetic operations - # used here - if count < nbits - @test val << ucount === val * T(2)^count - @test val >>> ucount === - fld(unsigned(val), unsigned(T(2))^count) % T - else - @test val << ucount === T(0) - @test val >>> ucount === T(0) - end - @test val << scount === val << ucount - @test val << -scount === val >> ucount - @test val >>> scount === val >>> ucount - @test val >>> -scount === val << ucount - if count < (issigned ? nbits-1 : nbits) - @test val >> ucount === fld(val, T(2)^count) - else - @test val >> ucount === T(val<0 ? -1 : 0) - end - @test val >> scount === val >> ucount - @test val >> -scount === val << ucount - end - end -end - -@test widen(UInt8(3)) === UInt32(3) -@test widen(UInt16(3)) === UInt32(3) -@test widen(UInt32(3)) === UInt64(3) -@test widen(UInt64(3)) === UInt128(3) -@test widen(UInt128(3)) == 3 -@test typeof(widen(UInt128(3))) == BigInt - -@test widen(Int8(-3)) === Int32(-3) -@test widen(Int16(-3)) === Int32(-3) -@test widen(Int32(-3)) === Int64(-3) -@test widen(Int64(-3)) === Int128(-3) -@test widen(Int128(-3)) == -3 -@test typeof(widen(Int128(-3))) == BigInt - -@test widemul(false, false) == false -@test widemul(false, 3) == 0 -@test widemul(3, true) == widemul(true, 3) == 3 - -let i=Int64(2)^63-1, k=widemul(i,i) - @test widemul(i,i)==85070591730234615847396907784232501249 - j=div(k,2) - @test div(k,j)==2 - j=div(k,5) - @test rem(k,j)==4 -end - -# issue #3596 -@test Int128(1)<<0 == 1 -@test repr(Int128(1)<<1) == "2" - -# issue #16700 -@test_throws MethodError 1.0 >> 8 - -# PR #16988 -@test true << 2 === 1 << 2 -@test true >> 2 === 1 >> 2 -@test true >>> 2 === 1 >>> 2 - -@test @inferred(unsafe_trunc(Int8, 127)) === Int8(127) -@test unsafe_trunc(Int8, 128) === Int8(-128) -@test unsafe_trunc(Int8, -127) === Int8(-127) -@test unsafe_trunc(Int8, -128) === Int8(-128) -@test unsafe_trunc(Int8, -129) === Int8(127) - -# Test x % T returns a T -for T in [Base.BitInteger_types..., BigInt], - U in [Base.BitInteger_types..., BigInt] - @test typeof(rand(U(0):U(127)) % T) === T -end - - -@testset "left shift with Vector{Int} on BigInt-scalar #13832" begin - x = BigInt(1) .<< [1:70;] - @test x[end] == 1180591620717411303424 - @test eltype(x) == BigInt -end diff --git a/julia-0.6.3/share/julia/test/intfuncs.jl b/julia-0.6.3/share/julia/test/intfuncs.jl deleted file mode 100644 index ed3469f..0000000 --- a/julia-0.6.3/share/julia/test/intfuncs.jl +++ /dev/null @@ -1,171 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -# Int32 and Int64 take different code paths -- test both -for T in (Int32, Int64) - @test gcd(T(3)) === T(3) - @test gcd(T(3), T(5)) === T(1) - @test gcd(T(3), T(15)) === T(3) - @test gcd(T(0), T(15)) === T(15) - @test gcd(T(3), T(-15)) === T(3) - @test gcd(T(-3), T(-15)) === T(3) - @test gcd(T(0), T(0)) === T(0) - - @test gcd(T(2), T(4), T(6)) === T(2) - - @test gcd(typemax(T), T(1)) === T(1) - @test gcd(-typemax(T), T(1)) === T(1) - @test gcd(typemin(T), T(1)) === T(1) - @test_throws OverflowError gcd(typemin(T), typemin(T)) - - @test lcm(T(0)) === T(0) - @test lcm(T(2)) === T(2) - @test lcm(T(2), T(3)) === T(6) - @test lcm(T(4), T(6)) === T(12) - @test lcm(T(3), T(0)) === T(0) - @test lcm(T(0), T(0)) === T(0) - @test lcm(T(4), T(-6)) === T(12) - @test lcm(T(-4), T(-6)) === T(12) - - @test lcm(T(2), T(4), T(6)) === T(12) - - @test lcm(typemax(T), T(1)) === typemax(T) - @test lcm(-typemax(T), T(1)) === typemax(T) - @test_throws OverflowError lcm(typemin(T), T(1)) - @test_throws OverflowError lcm(typemin(T), typemin(T)) -end - -@test gcdx(5, 12) == (1, 5, -2) -@test gcdx(5, -12) == (1, 5, 2) -@test gcdx(-25, -4) == (1, -1, 6) - -@test invmod(6, 31) === 26 -@test invmod(-1, 3) === 2 -@test invmod(1, -3) === -2 -@test invmod(-1, -3) === -1 -@test invmod(0x2, 0x3) === 0x2 -@test invmod(2, 0x3) === 2 -@test_throws DomainError invmod(0, 3) - -@test powermod(2, 3, 5) == 3 -@test powermod(2, 3, -5) == -2 - -@test powermod(2, 0, 5) == 1 -@test powermod(2, 0, -5) == -4 - -@test powermod(2, -1, 5) == 3 -@test powermod(2, -2, 5) == 4 -@test powermod(2, -1, -5) == -2 -@test powermod(2, -2, -5) == -1 - -@test nextpow2(3) == 4 -@test nextpow(2, 3) == 4 -@test nextpow(2, 4) == 4 -@test nextpow(2, 7) == 8 -@test_throws DomainError nextpow(0, 3) -@test_throws DomainError nextpow(3, 0) - -@test prevpow2(3) == 2 -@test prevpow(2, 4) == 4 -@test prevpow(2, 5) == 4 -@test_throws DomainError prevpow(0, 3) -@test_throws DomainError prevpow(0, 3) - -# issue #8266 -@test ndigits(-15, 10) == 2 -@test ndigits(-15, -10) == 2 -@test ndigits(-1, 10) == 1 -@test ndigits(-1, -10) == 2 -@test ndigits(2, 10) == 1 -@test ndigits(2, -10) == 1 -@test ndigits(10, 10) == 2 -@test ndigits(10, -10) == 3 -@test ndigits(17, 10) == 2 -@test ndigits(17, -10) == 3 -@test ndigits(unsigned(17), -10) == 3 - -@test ndigits(146, -3) == 5 - -let n = rand(Int) - @test ndigits(n) == ndigits(big(n)) == ndigits(n, 10) -end -@test ndigits(Int8(5)) == ndigits(5) - -# issue #19367 -@test ndigits(Int128(2)^64, 256) == 9 - -@test bin('3') == "110011" -@test bin('3',7) == "0110011" -@test bin(3) == "11" -@test bin(3, 2) == "11" -@test bin(3, 3) == "011" -@test bin(-3) == "-11" -@test bin(-3, 3) == "-011" - -@test oct(9) == "11" -@test oct(-9) == "-11" - -@test dec(121) == "121" - -@test hex(12) == "c" -@test hex(-12, 3) == "-00c" -@test num2hex(1243) == (Int == Int32 ? "000004db" : "00000000000004db") - -@test base(2, 5, 7) == "0000101" - -@test bits(Int16(3)) == "0000000000000011" -@test bits('3') == "00000000000000000000000000110011" -@test bits(1035) == (Int == Int32 ? "00000000000000000000010000001011" : - "0000000000000000000000000000000000000000000000000000010000001011") -@test bits(Int128(3)) == "00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000011" - -@test digits(4, 2) == [0, 0, 1] -@test digits(5, 3) == [2, 1] - -@test leading_ones(UInt32(Int64(2) ^ 32 - 2)) == 31 -@test leading_ones(1) == 0 -@test leading_zeros(Int32(1)) == 31 -@test leading_zeros(UInt32(Int64(2) ^ 32 - 2)) == 0 - -@test count_zeros(Int64(1)) == 63 - -@test factorial(3) == 6 -@test factorial(Int8(3)) === 6 -@test_throws DomainError factorial(-3) -@test_throws DomainError factorial(Int8(-3)) - -@test isqrt(4) == 2 -@test isqrt(5) == 2 -@test isqrt(Int8(4)) === Int8(2) -@test isqrt(Int8(5)) === Int8(2) -# issue #4884 -@test isqrt(9223372030926249000) == 3037000498 -@test isqrt(typemax(Int128)) == parse(Int128,"13043817825332782212") -@test isqrt(Int128(typemax(Int64))^2-1) == 9223372036854775806 -@test isqrt(0) == 0 -for i = 1:1000 - n = rand(UInt128) - s = isqrt(n) - @test s*s <= n - @test (s+1)*(s+1) > n - n = rand(UInt64) - s = isqrt(n) - @test s*s <= n - @test (s+1)*(s+1) > n -end - -# issue #9786 -let ptr = Ptr{Void}(typemax(UInt)) - for T in (Int, Cssize_t) - @test T(ptr) == -1 - @test ptr == Ptr{Void}(T(ptr)) - @test typeof(Ptr{Float64}(T(ptr))) == Ptr{Float64} - end -end - -# issue #15911 -@inferred string(1) - -# issue #22837 -for b in [-100:-2; 2:100;] - @test Base.ndigits0z(0, b) == 0 -end diff --git a/julia-0.6.3/share/julia/test/intrinsics.jl b/julia-0.6.3/share/julia/test/intrinsics.jl deleted file mode 100644 index a28968a..0000000 --- a/julia-0.6.3/share/julia/test/intrinsics.jl +++ /dev/null @@ -1,92 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -# intrinsic functions - -# For curmod_* -include("testenv.jl") - -# bits types -@test isa((() -> Core.Intrinsics.bitcast(Ptr{Int8}, 0))(), Ptr{Int8}) -@test isa(convert(Char, 65), Char) - -# runtime intrinsics -let f = Any[Core.Intrinsics.add_int, Core.Intrinsics.sub_int] - @test f[1](1, 1) == 2 - @test f[2](1, 1) == 0 -end - -# issue #4581 -primitive type Date4581{T} 64 end -let - x = Core.Intrinsics.bitcast(Date4581{Int}, Int64(1234)) - xs = Date4581[x] - ys = copy(xs) - @test ys !== xs - @test ys == xs -end - -# issue #6591 -function f6591(d) - Core.Intrinsics.bitcast(Int64, d) - return (f -> f(d))(identity) -end -let d = Core.Intrinsics.bitcast(Date4581{Int}, Int64(1)) - @test isa(f6591(d), Date4581) -end - -# test functionality of non-power-of-2 primitive type constants -primitive type Int24 24 end -Int24(x::Int) = Core.Intrinsics.trunc_int(Int24, x) -Int(x::Int24) = Core.Intrinsics.zext_int(Int, x) -let x, y, f - x = Int24(Int(0x12345678)) # create something (via truncation) - @test Int(0x345678) === Int(x) - f() = Int24(Int(0x02468ace)) - y = f() # invoke llvm constant folding - @test Int(0x468ace) === Int(y) - @test x !== y - @test string(y) == "$(curmod_prefix)Int24(0x468ace)" -end - -# test nonsensical valid conversions and errors - -compiled_addi(x, y) = Core.Intrinsics.add_int(x, y) -@test compiled_addi(C_NULL, C_NULL) === C_NULL -@test_throws ErrorException compiled_addi(C_NULL, 1) -@test_throws ErrorException ((x)->compiled_addi(Float64(x), x))(1) -@test ((x)->compiled_addi(Float64(x), Float64(x)))(2) === -0.0 -@test compiled_addi(0.5, 5.0e-323) === 0.5000000000000011 -@test_throws ErrorException compiled_addi(Int8(1), UInt8(1)) -@test compiled_addi(UInt8(1), UInt8(2)) === UInt8(3) -@test_throws ErrorException compiled_addi(UInt8(1), UInt16(2)) -@test compiled_addi(Float32(.125), Float32(10)) === 2.1267648f38 -@test compiled_addi(true, true) === false - -compiled_addf(x, y) = Core.Intrinsics.add_float(x, y) -@test compiled_addf(C_NULL, C_NULL) === C_NULL -@test_throws ErrorException compiled_addf(C_NULL, 1) -@test compiled_addf(0.5, 5.0e-323) === 0.5 -@test_throws ErrorException compiled_addf(im, im) -@test_throws ErrorException compiled_addf(true, true) - -function compiled_conv{T}(::Type{T}, x) - t = Core.Intrinsics.trunc_int(T, x) - z = Core.Intrinsics.zext_int(typeof(x), t) - s = Core.Intrinsics.sext_int(typeof(x), t) - fpt = Core.Intrinsics.fptrunc(T, x) - fpe = Core.Intrinsics.fpext(typeof(x), fpt) - return (t, z, s, fpt, fpe) -end -@test compiled_conv(UInt32, Int64(0x8000_0000)) == - (0x80000000, Int64(0x80000000), -Int64(0x80000000), 0x00000000, 0) -@test compiled_conv(UInt32, UInt64(0xC000_BA98_8765_4321)) == - (0x87654321, 0x0000000087654321, 0xffffffff87654321, 0xc005d4c4, 0xc000ba9880000000) -@test_throws ErrorException compiled_conv(Bool, im) - -let f = Core.Intrinsics.ashr_int - @test f(Int8(-17), 1) == -9 - @test f(Int32(-1), 33) == -1 - @test f(Int32(-1), -1) == -1 - @test f(Int32(-1), -10) == -1 - @test f(Int32(2), -1) == 0 -end diff --git a/julia-0.6.3/share/julia/test/intset.jl b/julia-0.6.3/share/julia/test/intset.jl deleted file mode 100644 index 3fe2ffb..0000000 --- a/julia-0.6.3/share/julia/test/intset.jl +++ /dev/null @@ -1,294 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -# Test functionality of IntSet - -@testset "Construction, collect" begin - data_in = (1,5,100) - s = IntSet(data_in) - data_out = collect(s) - @test all(map(d->in(d,data_out), data_in)) - @test length(data_out) === length(data_in) -end - -@testset "eltype, similar" begin - @test eltype(IntSet()) === Int - @test eltype(IntSet) === Int - @test isequal(similar(IntSet([1,2,3])), IntSet()) -end - -@testset "show" begin - @test sprint(show, IntSet()) == "IntSet([])" - @test sprint(show, IntSet([1,2,3])) == "IntSet([1, 2, 3])" - show(IOBuffer(), IntSet()) -end - -@testset "in, hashing" begin - s = IntSet([1,2,10,20,200,300,1000,10000,10002]) - @test last(s) === 10002 - @test first(s) === 1 - @test length(s) === 9 - @test pop!(s) === 10002 - @test_throws KeyError pop!(s, -1) - @test length(s) === 8 - @test shift!(s) === 1 - @test length(s) === 7 - @test !in(0,s) - @test !in(1,s) - @test in(2,s) - @test !in(10002,s) - @test in(10000,s) - @test in(10000.0,s) - @test !in(10002.0,s) - @test_throws ArgumentError first(IntSet()) - @test_throws ArgumentError last(IntSet()) - t = copy(s) - sizehint!(t, 20000) #check that hash does not depend on size of internal storage - @test hash(s) === hash(t) - push!(t, 20000) - @test 20000 in t - sizehint!(t, 200) # ensure that sizehint!'ing a small amount isn't destructive - @test 20000 in t - @test pop!(t, 20000) === 20000 - @test hash(s) === hash(t) - # Ensure empty chunks don't affect hash - @test hash(IntSet([1])) != hash(IntSet([17])) - @test hash(IntSet([1])) != hash(IntSet([33])) - @test hash(IntSet([1])) != hash(IntSet([65])) - @test hash(IntSet([1])) != hash(IntSet([129])) - - # issue #7851 - @test_throws ArgumentError IntSet(-1) - @test !(-1 in IntSet(1:10)) -end - -# # issue #8570 -# This requires 2^29 bytes of storage, which is too much for a simple test -# s = IntSet(typemax(Int32)) -# @test length(s) === 1 -# for b in s; b; end - -@testset "union!, symdiff!" begin - i = IntSet([1, 2, 3]) - union!(i, [1, 2]) - @test length(i) === 3 - union!(i, [3, 4, 5]) - @test length(i) === 5 - - @test_throws KeyError pop!(i, 10) - - empty!(i) - @test length(i) === 0 - - @test_throws ArgumentError symdiff!(i, -3) - @test symdiff!(i, 3) == IntSet([3]) - @test symdiff!(i, 257) == IntSet([3, 257]) - @test symdiff!(i, [3, 6]) == IntSet([6, 257]) - - i = IntSet(1:6) - @test symdiff!(i, IntSet([6, 513])) == IntSet([1:5; 513]) - - # issue #23099 : these tests should not segfault - @test_throws ArgumentError symdiff!(IntSet(rand(1:100, 30)), 0) - @test_throws ArgumentError symdiff!(IntSet(rand(1:100, 30)), [0, 2, 4]) -end - -@testset "copy, copy!, similar" begin - s1 = IntSet([1,2,3]) - s2 = similar(s1) - copy!(s2, s1) - s3 = copy(s2) - @test s3 == s2 == s1 - @test collect(s3) == collect(s2) == [1,2,3] -end - -@testset "push!, union" begin - i = IntSet([1, 2, 3]) - j = union(i) - @test j == i - @test !(j === i) - - j = IntSet([4, 5, 6]) - @test union(i, j) == IntSet(1:6) - - k = IntSet([7, 8, 9]) - @test union(i, j, k) == IntSet(1:9) - i = IntSet([1, 2, 3]) - j = union(i) - @test j == i - @test !(j === i) - - j = IntSet([4, 5, 6]) - @test union(i, j) == IntSet(1:6) - - k = IntSet([7, 8, 9]) - @test union(i, j, k) == IntSet(1:9) - - s1 = IntSet() - @test_throws ArgumentError push!(s1, -1) - push!(s1, 1, 10, 100, 1000) - @test collect(s1) == [1, 10, 100, 1000] - push!(s1, 606) - @test collect(s1) == [1, 10, 100, 606, 1000] - s2 = IntSet() - @test s2 === union!(s2, s1) - s3 = IntSet([1, 10, 100]) - union!(s3, [1, 606, 1000]) - s4 = union(IntSet([1, 100, 1000]), IntSet([10, 100, 606])) - @test s1 == s2 == s3 == s4 -end - -@testset "pop!, delete!" begin - s = IntSet(1:2:10) - @test pop!(s, 1) === 1 - @test !(1 in s) - @test_throws KeyError pop!(s, 1) - @test_throws KeyError pop!(s, -1) - @test pop!(s, -1, 1) === 1 - @test pop!(s, 1, 0) === 0 - @test s === delete!(s, 1) - for i in s; pop!(s, i); end - @test isempty(s) - push!(s, 100) - @test pop!(s, 100) == 100 - push!(s, 1:2:10...) - @test pop!(s) === 9 - @test pop!(s) === 7 - @test shift!(s) === 1 - @test shift!(s) === 3 - @test collect(s) == [5] - empty!(s) - @test isempty(s) -end - -@testset "intersect" begin - i = IntSet([1, 2, 3]) - j = IntSet([4, 5, 6]) - - @test intersect(i) == i - @test !(intersect(i) === i) - @test intersect(i, j) == IntSet([]) - push!(j, 257) - @test intersect(i, j) == IntSet([]) - push!(j, 2, 3, 17) - @test intersect(i, j) == IntSet([2, 3]) - k = IntSet([1, 2, 3, 4, 5, 6, 7]) - @test intersect(i, j, k) == IntSet([2, 3]) - - @test isempty(intersect(IntSet())) - @test isempty(intersect(IntSet(1:10), IntSet())) - @test isempty(intersect(IntSet(), IntSet(1:10))) - - @test intersect(IntSet([1,2,3])) == IntSet([1,2,3]) - @test intersect(IntSet(1:7), IntSet(3:10)) == - intersect(IntSet(3:10), IntSet(1:7)) == IntSet(3:7) - @test intersect(IntSet(1:10), IntSet(1:4), 1:5, [2,3,10]) == [2,3] -end - -@testset "setdiff, symdiff" begin - @test setdiff(IntSet([1, 2, 3, 4]), IntSet([2, 4, 5, 6])) == IntSet([1, 3]) - @test symdiff(IntSet([1, 2, 3, 4]), IntSet([2, 4, 5, 6])) == IntSet([1, 3, 5, 6]) - - s2 = IntSet([1, 2, 3, 4]) - setdiff!(s2, IntSet([2, 4, 5, 6])) - @test s2 == IntSet([1, 3]) - - s1 = IntSet(1:100) - setdiff!(s1, IntSet(1:2:100)) - s2 = setdiff(IntSet(1:100), IntSet(1:2:100)) - @test s1 == s2 == IntSet(2:2:100) - @test collect(s1) == collect(2:2:100) - - @test symdiff(IntSet([1, 2, 3, 4]), IntSet([2, 4, 5, 6])) == - symdiff(IntSet([2, 4, 5, 6]), IntSet([1, 2, 3, 4])) == - symdiff(IntSet([1, 2, 3, 4]), [2, 4, 5, 6]) == - symdiff(IntSet([2, 4, 5, 6]), [1, 2, 3, 4]) == IntSet([1, 3, 5, 6]) -end - -@testset "subsets, equality" begin - i = IntSet([1, 2, 3]) - k = IntSet([4, 5]) - copy!(k, i) - @test k == i - @test !(k === i) - copy!(k, k) - @test k == i - - i = IntSet([1, 2, 3]) - j = IntSet([1, 2, 4]) - @test i != j - - push!(j, 257) - pop!(j, 257) - @test i != j - @test j != i - - @test issubset(IntSet([1, 2, 4]), IntSet(1:10)) - @test issubset(IntSet([]), IntSet([])) - @test IntSet([1, 2, 4]) < IntSet(1:10) - @test !(IntSet([]) < IntSet([])) - @test IntSet([1, 2, 4]) <= IntSet(1:10) - @test IntSet([1, 2, 4]) <= IntSet([1, 2, 4]) - @test IntSet([]) <= IntSet([]) - - @test IntSet(2:2:10) < IntSet(1:10) - @test !(IntSet(2:2:10) < IntSet(2:2:10)) - @test IntSet(2:2:10) <= IntSet(2:10) - @test IntSet(2:2:10) <= IntSet(2:2:10) - - # == with last-bit set (groups.google.com/forum/#!topic/julia-users/vZNjiIEG_sY) - s = IntSet(255) - @test s == s -end - -@testset "setlike" begin - p = IntSet([1,2,5,6]) - resize!(p.bits, 6) - q = IntSet([1,3,5,7]) - resize!(q.bits, 8) - a = Set(p) - b = Set(q) - for f in (union, intersect, setdiff, symdiff) - @test collect(f(p, p)) == sort(collect(f(a, a))) - @test collect(f(q, q)) == sort(collect(f(b, b))) - @test collect(f(p, q)) == sort(collect(f(a, b))) - @test collect(f(q, p)) == sort(collect(f(b, a))) - end -end - -@testset "misc" begin - s = IntSet() - push!(s, 1, 2, 100) - @test !(0 in s) - @test 1 in s - @test 2 in s - @test !(3 in s) - @test 100 in s - @test !(101 in s) - @test !(1000 in s) - @test first(s) === 1 - @test last(s) === 100 - @test s == IntSet([1, 2, 100]) - push!(s, 1000) - @test [i for i in s] == [1, 2, 100, 1000] - @test pop!(s) === 1000 - @test s == IntSet([1, 2, 100]) - @test hash(s) === hash(IntSet([1, 2, 100])) - - b = 1:1000 - s = IntSet(b) - @test collect(s) == collect(b) - @test length(s) === length(b) - @test pop!(s, 100) === 100 - @test collect(s) == [1:99; 101:1000] - @test_throws KeyError pop!(s, 100) - @test_throws KeyError pop!(s, 0) - @test pop!(s, 100, 0) === 0 - @test pop!(s, 99, 0) === 99 -end - -@testset "unsigned overflow" begin - @test IntSet(UInt8(2^8-1)) == IntSet(2^8-1) - @test [x for x in IntSet(UInt8(2^8-1))] == [UInt8(2^8-1)] - @test IntSet(UInt16(2^16-1)) == IntSet(2^16-1) - @test [x for x in IntSet(UInt16(2^16-1))] == [UInt16(2^16-1)] -end diff --git a/julia-0.6.3/share/julia/test/iobuffer.jl b/julia-0.6.3/share/julia/test/iobuffer.jl deleted file mode 100644 index a7de17b..0000000 --- a/julia-0.6.3/share/julia/test/iobuffer.jl +++ /dev/null @@ -1,253 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -ioslength(io::IOBuffer) = (io.seekable ? io.size : nb_available(io)) - -let io = IOBuffer() -@test eof(io) -@test_throws EOFError read(io,UInt8) -@test write(io,"abc") === 3 -@test isreadable(io) -@test iswritable(io) -@test isopen(io) -@test ioslength(io) == 3 -@test position(io) == 3 -@test eof(io) -seek(io, 0) -@test read(io,UInt8) == convert(UInt8, 'a') -a = Array{UInt8}(2) -@test read!(io, a) == a -@test a == UInt8['b','c'] -@test String(io) == "abc" -seek(io, 1) -truncate(io, 2) -@test position(io) == 1 -@test !eof(io) -seekend(io) -@test position(io) == 2 -truncate(io, 0) -@test position(io) == 0 -truncate(io, 10) -@test position(io) == 0 -@test all(io.data .== 0) -@test write(io,Int16[1,2,3,4,5,6]) === 12 -seek(io, 2) -truncate(io, 10) -@test ioslength(io) == 10 -io.readable = false -@test_throws ArgumentError read!(io,UInt8[0]) -truncate(io, 0) -@test write(io,"boston\ncambridge\n") > 0 -@test String(take!(io)) == "boston\ncambridge\n" -@test String(take!(io)) == "" -@test write(io, Complex{Float64}(0)) === 16 -@test write(io, Rational{Int64}(1//2)) === 16 -close(io) -@test_throws ArgumentError write(io,UInt8[0]) -@test_throws ArgumentError seek(io,0) -@test eof(io) -end - -let io = IOBuffer("hamster\nguinea pig\nturtle") -@test position(io) == 0 -@test readline(io) == "hamster" -@test readstring(io) == "guinea pig\nturtle" -@test_throws EOFError read(io,UInt8) -seek(io,0) -@test read(io,UInt8) == convert(UInt8, 'h') -@test_throws ArgumentError truncate(io,0) -@test_throws ArgumentError write(io,UInt8(0)) -@test_throws ArgumentError write(io,UInt8[0]) -@test String(take!(io)) == "hamster\nguinea pig\nturtle" -@test String(take!(io)) == "hamster\nguinea pig\nturtle" #should be unchanged -close(io) -end - -let io = PipeBuffer() -@test_throws EOFError read(io,UInt8) -@test write(io,"pancakes\nwaffles\nblueberries\n") > 0 -@test position(io) == 0 -@test readline(io) == "pancakes" -Base.compact(io) -@test readline(io) == "waffles" -@test write(io,"whipped cream\n") > 0 -@test readline(io) == "blueberries" -@test_throws ArgumentError seek(io,0) -@test_throws ArgumentError truncate(io,0) -@test readline(io) == "whipped cream" -@test write(io,"pancakes\nwaffles\nblueberries\n") > 0 -@test readlines(io) == String["pancakes", "waffles", "blueberries"] -write(io,"\n\r\n\n\r \n") > 0 -@test readlines(io, chomp=false) == String["\n", "\r\n", "\n", "\r \n"] -write(io,"\n\r\n\n\r \n") > 0 -@test readlines(io, chomp=true) == String["", "", "", "\r "] -@test write(io,"α\nβ\nγ\nδ") > 0 -@test readlines(io, chomp=false) == String["α\n","β\n","γ\n","δ"] -@test write(io,"α\nβ\nγ\nδ") > 0 -@test readlines(io, chomp=true) == String["α", "β", "γ", "δ"] -@test readlines(IOBuffer(""), chomp=false) == [] -@test readlines(IOBuffer(""), chomp=true) == [] -@test readlines(IOBuffer("first\nsecond"), chomp=false) == String["first\n", "second"] -@test readlines(IOBuffer("first\nsecond"), chomp=true) == String["first", "second"] - -let fname = tempname() - for dochomp in [true, false], - endline in ["\n", "\r\n"], - i in -5:5 - - ref = ("1"^(2^17 - i)) * endline - open(fname, "w") do io - write(io, ref) - end - x = readlines(fname, chomp = dochomp) - if dochomp - ref = chomp(ref) - end - @test ref == x[1] - end - rm(fname) -end - -Base.compact(io) -@test position(io) == 0 -@test ioslength(io) == 0 -Base.ensureroom(io,50) -@test position(io) == 0 -@test ioslength(io) == 0 -@test length(io.data) == 50 -Base.ensureroom(io,10) -@test ioslength(io) == 0 -@test length(io.data) == 50 -io.maxsize = 75 -Base.ensureroom(io,100) -@test ioslength(io) == 0 -@test length(io.data) == 75 -seekend(io) -@test ioslength(io) == 0 -@test position(io) == 0 -write(io,zeros(UInt8,200)) -@test ioslength(io) == 75 -@test length(io.data) == 75 -write(io,1) -@test ioslength(io) == 75 -@test length(io.data) == 75 -write(io,[1,2,3]) -@test ioslength(io) == 75 -@test length(io.data) == 75 -skip(io,1) -@test write(io,UInt8(104)) === 1 -skip(io,3) -@test write(io,b"apples") === 3 -skip(io,71) -@test write(io,'y') === 1 -@test readstring(io) == "happy" -@test eof(io) -write(io,zeros(UInt8,73)) -write(io,'a') -write(io,'b') -write(io,'c') -write(io,'d') -write(io,'e') -@test ioslength(io) == 75 -@test length(io.data) == 75 -@test position(io) == 0 -skip(io,72) -@test String(take!(io)) == "\0ab" -@test String(take!(io)) == "" - -# issues 4021 -print(io, true) -close(io) -end - -# issue 5453 -let io=IOBuffer("abcdef") -a = Array{UInt8}(1024) -@test_throws EOFError read!(io,a) -@test eof(io) -end - -@test isempty(readlines(IOBuffer(), chomp=false)) - -# issue #8193 -let io=IOBuffer("asdf") - @test position(skip(io, -1)) == 0 - @test position(skip(io, 6)) == 4 - @test position(seek(io, -1)) == 0 - @test position(seek(io, 6)) == 4 -end - -# issue #10658 -let io=IOBuffer("hello") - @test position(skip(io, 4)) == 4 - @test position(skip(io, 10)) == 5 - @test position(skip(io, -2)) == 3 - @test position(skip(io, -3)) == 0 - @test position(skip(io, -3)) == 0 -end - -# pr #11554 -let io=IOBuffer(SubString("***αhelloworldω***",4,16)), io2 = IOBuffer(b"goodnightmoon", true, true) - @test read(io, Char) == 'α' - @test_throws ArgumentError write(io,"!") - @test_throws ArgumentError write(io,'β') - a = Array{UInt8}(10) - @test read!(io, a) === a - @test String(a) == "helloworld" - @test read(io, Char) == 'ω' - @test_throws EOFError read(io,UInt8) - skip(io, -3) - @test readstring(io) == "dω" - @test String(io) == "αhelloworldω" - @test_throws ArgumentError write(io,"!") - @test take!(io) == b"αhelloworldω" - seek(io, 2) - seekend(io2) - write(io2, io) - @test readstring(io) == "" - @test readstring(io2) == "" - @test String(take!(io)) == "αhelloworldω" - seek(io2, 0) - truncate(io2, io2.size - 2) - @test readstring(io2) == "goodnightmoonhelloworld" - seek(io2, 0) - write(io2, io2) - @test readstring(io2) == "" - @test String(io2) == "goodnightmoonhelloworld" -end - -# issue #11917 -# (previous tests triggered this sometimes, but this should trigger nearly all the time) -let io = IOBuffer(0) - write(io, ones(UInt8, 1048577)) -end - -let bstream = BufferStream() - @test isopen(bstream) - @test isreadable(bstream) - @test iswritable(bstream) - @test nb_available(bstream) == 0 - @test sprint(show, bstream) == "BufferStream() bytes waiting:$(nb_available(bstream.buffer)), isopen:true" - a = rand(UInt8,10) - write(bstream,a) - @test !eof(bstream) - @test flush(bstream) === nothing - b = read(bstream,UInt8) - @test a[1] == b - b = read(bstream,UInt8) - @test a[2] == b - c = zeros(UInt8,8) - @test nb_available(bstream) == 8 - @test !eof(bstream) - read!(bstream,c) - @test c == a[3:10] - @test close(bstream) === nothing - @test eof(bstream) - @test nb_available(bstream) == 0 -end - -@test flush(IOBuffer()) === nothing # should be a no-op - -# pr #19461 -let io = IOBuffer() - @test Base.buffer_writes(io) === io -end diff --git a/julia-0.6.3/share/julia/test/iostream.jl b/julia-0.6.3/share/julia/test/iostream.jl deleted file mode 100644 index 31026b7..0000000 --- a/julia-0.6.3/share/julia/test/iostream.jl +++ /dev/null @@ -1,48 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -# Test skipchars for IOStreams -mktemp() do path, file - function append_to_file(str) - mark(file) - print(file, str) - flush(file) - reset(file) - end - - # test it doesn't error on eof - @test eof(skipchars(file, isspace)) - - # test it correctly skips - append_to_file(" ") - @test eof(skipchars(file, isspace)) - - # test it correctly detects comment lines - append_to_file("# \n ") - @test eof(skipchars(file, isspace, linecomment='#')) - - # test it stops at the appropriate time - append_to_file(" not a space") - @test !eof(skipchars(file, isspace)) - @test read(file, Char) == 'n' - - # test it correctly ignores the contents of comment lines - append_to_file(" #not a space \n not a space") - @test !eof(skipchars(file, isspace, linecomment='#')) - @test read(file, Char) == 'n' - - # test it correctly handles unicode - for (byte,char) in zip(1:4, ('@','߷','࿊','𐋺')) - append_to_file("abcdef$char") - @test Base.codelen(char) == byte - @test !eof(skipchars(file, isalpha)) - @test read(file, Char) == char - end -end - -# issue #18755 -mktemp() do path, io - write(io, zeros(UInt8, 131073)) - @test position(io) == 131073 - write(io, zeros(UInt8, 131073)) - @test position(io) == 262146 -end diff --git a/julia-0.6.3/share/julia/test/iterators.jl b/julia-0.6.3/share/julia/test/iterators.jl deleted file mode 100644 index 44538ba..0000000 --- a/julia-0.6.3/share/julia/test/iterators.jl +++ /dev/null @@ -1,414 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -using Base.Iterators - -# zip and filter iterators -# issue #4718 -@test collect(Iterators.filter(x->x[1], zip([true, false, true, false],"abcd"))) == [(true,'a'),(true,'c')] - -let z = zip(1:2) - @test collect(z) == [(1,), (2,)] - # Issue #13979 - @test eltype(z) == Tuple{Int} -end - -let z = zip(1:2, 3:4) - @test collect(z) == [(1,3), (2,4)] - @test eltype(z) == Tuple{Int,Int} -end - -let z = zip(1:2, 3:4, 5:6) - @test collect(z) == [(1,3,5), (2,4,6)] - @test eltype(z) == Tuple{Int,Int,Int} -end - -@test eltype(Iterators.filter(isodd, 1:5)) == Int - -# typed `collect` -@test collect(Float64, Iterators.filter(isodd, [1,2,3,4]))[1] === 1.0 - -# check direct EachLine constructor -let b = IOBuffer("foo\n") - @test collect(EachLine(b)) == ["foo"] - seek(b, 0) - @test collect(EachLine(b, chomp=false)) == ["foo\n"] - seek(b, 0) - @test collect(EachLine(b, ondone=()->0)) == ["foo"] - seek(b, 0) - @test collect(EachLine(b, chomp=false, ondone=()->0)) == ["foo\n"] -end - -# enumerate (issue #6284) -let b = IOBuffer("1\n2\n3\n"), a = [] - for (i,x) in enumerate(eachline(b)) - push!(a, (i,x)) - end - @test a == [(1,"1"),(2,"2"),(3,"3")] -end - -# zip eachline (issue #7369) -let zeb = IOBuffer("1\n2\n3\n4\n5\n"), - letters = ['a', 'b', 'c', 'd', 'e'], - res = [] - for (number, letter) in zip(eachline(zeb), letters) - push!(res, (parse(Int,strip(number)), letter)) - end - @test res == [(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd'), (5, 'e')] -end - -@test length(zip(cycle(1:3), 1:7)) == 7 -@test length(zip(cycle(1:3), 1:7, cycle(1:3))) == 7 -@test length(zip(1:3,product(1:7,cycle(1:3)))) == 3 -@test length(zip(1:3,product(1:7,cycle(1:3)),8)) == 1 - -# rest -# ---- -let s = "hello" - _, st = next(s, start(s)) - @test collect(rest(s, st)) == ['e','l','l','o'] -end - -@test_throws MethodError collect(rest(countfrom(1), 5)) - -# countfrom -# --------- -let i = 0 - for j = countfrom(0, 2) - @test j == i*2 - i += 1 - i <= 10 || break - end -end - -# take -# ---- -let t = take(0:2:8, 10), i = 0 - @test length(collect(t)) == 5 - - for j = t - @test j == i*2 - i += 1 - end - @test i == 5 -end - -let i = 0 - for j = take(0:2:100, 10) - @test j == i*2 - i += 1 - end - @test i == 10 -end - -@test length(take(1:3,typemax(Int))) == 3 -@test length(take(countfrom(1),3)) == 3 -@test length(take(1:6,3)) == 3 - -# drop -# ---- -let i = 0 - for j = drop(0:2:10, 2) - @test j == (i+2)*2 - i += 1 - end - @test i == 4 -end - -@test length(drop(1:3,typemax(Int))) == 0 -@test Base.iteratorsize(drop(countfrom(1),3)) == Base.IsInfinite() -@test_throws MethodError length(drop(countfrom(1), 3)) - -# double take -# and take/drop canonicalization -# ----------- -for xs in Any["abc", [1, 2, 3]] - @test take(take(xs, 2), 3) === take(xs, 2) - @test take(take(xs, 4), 2) === take(xs, 2) - @test drop(drop(xs, 1), 1) === drop(xs, 2) - @test take(drop(xs, 1), 1) === drop(take(xs, 2), 1) - @test take(drop(xs, 3), 0) === drop(take(xs, 2), 3) - @test isempty(drop(drop(xs, 2), 2)) - @test drop(take(drop(xs, 1), 2), 1) === take(drop(xs, 2), 1) - @test take(drop(take(xs, 3), 1), 1) === take(drop(xs, 1), 1) -end - -# cycle -# ----- -let i = 0 - for j = cycle(0:3) - @test j == i % 4 - i += 1 - i <= 10 || break - end -end - -# repeated -# -------- -let i = 0 - for j = repeated(1, 10) - @test j == 1 - i += 1 - end - @test i == 10 -end -let i = 0 - for j = repeated(1) - @test j == 1 - i += 1 - i <= 10 || break - end -end -@test eltype(repeated(0)) == Int -@test eltype(repeated(0, 5)) == Int -@test Base.iteratorsize(repeated(0)) == Base.IsInfinite() -@test Base.iteratorsize(repeated(0, 5)) == Base.HasLength() -@test Base.iteratoreltype(repeated(0)) == Base.HasEltype() -@test Base.iteratoreltype(repeated(0, 5)) == Base.HasEltype() -@test Base.iteratorsize(zip(repeated(0), repeated(0))) == Base.IsInfinite() - - -# product -# ------- - -# empty? -for itr in [product(1:0), - product(1:2, 1:0), - product(1:0, 1:2), - product(1:0, 1:1, 1:2), - product(1:1, 1:0, 1:2), - product(1:1, 1:2 ,1:0)] - @test isempty(itr) - @test isempty(collect(itr)) -end - -# collect a product - first iterators runs faster -@test collect(product(1:2)) == [(i,) for i=1:2] -@test collect(product(1:2, 3:4)) == [(i, j) for i=1:2, j=3:4] -@test collect(product(1:2, 3:4, 5:6)) == [(i, j, k) for i=1:2, j=3:4, k=5:6] - -# iteration order -let expected = [(1,3,5), (2,3,5), (1,4,5), (2,4,5), (1,3,6), (2,3,6), (1,4,6), (2,4,6)] - actual = product(1:2, 3:4, 5:6) - for (exp, act) in zip(expected, actual) - @test exp == act - end -end - -# collect multidimensional array -let (a, b) = (1:3, [4 6; - 5 7]) - p = product(a, b) - @test size(p) == (3, 2, 2) - @test length(p) == 12 - @test ndims(p) == 3 - @test eltype(p) == NTuple{2, Int} - cp = collect(p) - for i = 1:3 - @test cp[i, :, :] == [(i, 4) (i, 6); - (i, 5) (i, 7)] - end -end - -# with 1D inputs -let (a, b, c) = (1:2, 1.0:10.0, Int32(1):Int32(0)) - # length - @test length(product(a)) == 2 - @test length(product(a, b)) == 20 - @test length(product(a, b, c)) == 0 - - # size - @test size(product(a)) == (2,) - @test size(product(a, b)) == (2, 10) - @test size(product(a, b, c)) == (2, 10, 0) - - # eltype - @test eltype(product(a)) == Tuple{Int} - @test eltype(product(a, b)) == Tuple{Int, Float64} - @test eltype(product(a, b, c)) == Tuple{Int, Float64, Int32} - - # ndims - @test ndims(product(a)) == 1 - @test ndims(product(a, b)) == 2 - @test ndims(product(a, b, c)) == 3 -end - -# with multidimensional inputs -let (a, b, c) = (randn(4, 4), randn(3, 3, 3), randn(2, 2, 2, 2)) - args = Any[(a,), - (a, a), - (a, b), - (a, a, a), - (a, b, c)] - sizes = Any[(4, 4), - (4, 4, 4, 4), - (4, 4, 3, 3, 3), - (4, 4, 4, 4, 4, 4), - (4, 4, 3, 3, 3, 2, 2, 2, 2)] - for (method, fun) in zip([size, ndims, length], [x->x, length, prod]) - for i in 1:length(args) - @test method(product(args[i]...)) == method(collect(product(args[i]...))) == fun(sizes[i]) - end - end -end - -# more tests on product with iterators of various type -let iters = (1:2, - rand(2, 2, 2), - take(1:4, 2), - product(1:2, 1:3), - product(rand(2, 2), rand(1, 1, 1)) - ) - for method in [size, length, ndims, eltype] - for i = 1:length(iters) - args = iters[i] - @test method(product(args...)) == method(collect(product(args...))) - for j = 1:length(iters) - args = iters[i], iters[j] - @test method(product(args...)) == method(collect(product(args...))) - for k = 1:length(iters) - args = iters[i], iters[j], iters[k] - @test method(product(args...)) == method(collect(product(args...))) - end - end - end - end -end - -# product of finite length and infinite length iterators -let a = 1:2 - b = countfrom(1) - ab = product(a, b) - ba = product(b, a) - abexp = [(1, 1), (2, 1), (1, 2), (2, 2), (1, 3), (2, 3)] - baexp = [(1, 1), (2, 1), (3, 1), (4, 1), (5, 1), (6, 1)] - for (expected, actual) in zip([abexp, baexp], [ab, ba]) - for (i, el) in enumerate(actual) - @test el == expected[i] - i == length(expected) && break - end - @test_throws ArgumentError length(actual) - @test_throws ArgumentError size(actual) - @test_throws ArgumentError ndims(actual) - end - - # size infinite or unknown raises an error - for itr in Any[countfrom(1), Iterators.filter(i->0, 1:10)] - @test_throws ArgumentError length(product(itr)) - @test_throws ArgumentError size(product(itr)) - @test_throws ArgumentError ndims(product(itr)) - end -end - -# iteratorsize trait business -let f1 = Iterators.filter(i->i>0, 1:10) - @test Base.iteratorsize(product(f1)) == Base.SizeUnknown() - @test Base.iteratorsize(product(1:2, f1)) == Base.SizeUnknown() - @test Base.iteratorsize(product(f1, 1:2)) == Base.SizeUnknown() - @test Base.iteratorsize(product(f1, f1)) == Base.SizeUnknown() - @test Base.iteratorsize(product(f1, countfrom(1))) == Base.IsInfinite() - @test Base.iteratorsize(product(countfrom(1), f1)) == Base.IsInfinite() -end -@test Base.iteratorsize(product(1:2, countfrom(1))) == Base.IsInfinite() -@test Base.iteratorsize(product(countfrom(2), countfrom(1))) == Base.IsInfinite() -@test Base.iteratorsize(product(countfrom(1), 1:2)) == Base.IsInfinite() -@test Base.iteratorsize(product(1:2)) == Base.HasShape() -@test Base.iteratorsize(product(1:2, 1:2)) == Base.HasShape() -@test Base.iteratorsize(product(take(1:2, 1), take(1:2, 1))) == Base.HasShape() -@test Base.iteratorsize(product(take(1:2, 2))) == Base.HasLength() -@test Base.iteratorsize(product([1 2; 3 4])) == Base.HasShape() - -# iteratoreltype trait business -let f1 = Iterators.filter(i->i>0, 1:10) - @test Base.iteratoreltype(product(f1)) == Base.HasEltype() # FIXME? eltype(f1) is Any - @test Base.iteratoreltype(product(1:2, f1)) == Base.HasEltype() # FIXME? eltype(f1) is Any - @test Base.iteratoreltype(product(f1, 1:2)) == Base.HasEltype() # FIXME? eltype(f1) is Any - @test Base.iteratoreltype(product(f1, f1)) == Base.HasEltype() # FIXME? eltype(f1) is Any - @test Base.iteratoreltype(product(f1, countfrom(1))) == Base.HasEltype() # FIXME? eltype(f1) is Any - @test Base.iteratoreltype(product(countfrom(1), f1)) == Base.HasEltype() # FIXME? eltype(f1) is Any -end -@test Base.iteratoreltype(product(1:2, countfrom(1))) == Base.HasEltype() -@test Base.iteratoreltype(product(countfrom(1), 1:2)) == Base.HasEltype() -@test Base.iteratoreltype(product(1:2)) == Base.HasEltype() -@test Base.iteratoreltype(product(1:2, 1:2)) == Base.HasEltype() -@test Base.iteratoreltype(product(take(1:2, 1), take(1:2, 1))) == Base.HasEltype() -@test Base.iteratoreltype(product(take(1:2, 2))) == Base.HasEltype() -@test Base.iteratoreltype(product([1 2; 3 4])) == Base.HasEltype() - -@test collect(product(1:2,3:4)) == [(1,3) (1,4); (2,3) (2,4)] -@test isempty(collect(product(1:0,1:2))) -@test length(product(1:2,1:10,4:6)) == 60 -@test Base.iteratorsize(product(1:2, countfrom(1))) == Base.IsInfinite() - -# flatten -# ------- -@test collect(flatten(Any[1:2, 4:5])) == Any[1,2,4,5] -@test collect(flatten(Any[flatten(Any[1:2, 6:5]), flatten(Any[10:7, 10:9])])) == Any[1,2] -@test collect(flatten(Any[flatten(Any[1:2, 4:5]), flatten(Any[6:7, 8:9])])) == Any[1,2,4,5,6,7,8,9] -@test collect(flatten(Any[flatten(Any[1:2, 6:5]), flatten(Any[6:7, 8:9])])) == Any[1,2,6,7,8,9] -@test collect(flatten(Any[2:1])) == Any[] -@test eltype(flatten(UnitRange{Int8}[1:2, 3:4])) == Int8 -@test_throws ArgumentError collect(flatten(Any[])) - -@test Base.iteratoreltype(Base.Flatten((i for i=1:2) for j=1:1)) == Base.EltypeUnknown() - -# partition(c, n) -let v = collect(partition([1,2,3,4,5], 1)) - @test all(i->v[i][1] == i, v) -end - -let v = collect(partition([1,2,3,4,5], 2)) - @test v[1] == [1,2] - @test v[2] == [3,4] - @test v[3] == [5] -end - -let v = collect(partition(enumerate([1,2,3,4,5]), 3)) - @test v[1] == [(1,1),(2,2),(3,3)] - @test v[2] == [(4,4),(5,5)] -end - -for n in [5,6] - @test collect(partition([1,2,3,4,5], n))[1] == [1,2,3,4,5] - @test collect(partition(enumerate([1,2,3,4,5]), n))[1] == - [(1,1),(2,2),(3,3),(4,4),(5,5)] -end - - -@test join(map(x->string(x...), partition("Hello World!", 5)), "|") == - "Hello| Worl|d!" - -let s = "Monkey 🙈🙊🙊" - tf = (n)->join(map(x->string(x...), partition(s,n)), "|") - @test tf(10) == s - @test tf(9) == "Monkey 🙈🙊|🙊" - @test tf(8) == "Monkey 🙈|🙊🙊" - @test tf(7) == "Monkey |🙈🙊🙊" - @test tf(6) == "Monkey| 🙈🙊🙊" - @test tf(5) == "Monke|y 🙈🙊🙊" - @test tf(4) == "Monk|ey 🙈|🙊🙊" - @test tf(3) == "Mon|key| 🙈🙊|🙊" - @test tf(2) == "Mo|nk|ey| 🙈|🙊🙊" - @test tf(1) == "M|o|n|k|e|y| |🙈|🙊|🙊" -end - -# take and friends with arbitrary integers (#19214) -for T in (UInt8, UInt16, UInt32, UInt64, UInt128, Int8, Int16, Int128, BigInt) - @test length(take(1:6, T(3))) == 3 - @test length(drop(1:6, T(3))) == 3 - @test length(repeated(1, T(5))) == 5 - @test collect(partition(1:5, T(5)))[1] == collect(1:5) -end - -@testset "collect finite iterators issue #12009" begin - @test eltype(collect(enumerate(Iterators.Filter(x -> x>0, randn(10))))) == Tuple{Int, Float64} -end - -@testset "product iterator infinite loop" begin - @test collect(product(1:1, (1, "2"))) == [(1, 1) (1, "2")] -end - -@testset "filter empty iterable #16704" begin - arr = filter(n -> true, 1:0) - @test length(arr) == 0 - @test eltype(arr) == Int -end diff --git a/julia-0.6.3/share/julia/test/keywordargs.jl b/julia-0.6.3/share/julia/test/keywordargs.jl deleted file mode 100644 index 0ac76fa..0000000 --- a/julia-0.6.3/share/julia/test/keywordargs.jl +++ /dev/null @@ -1,287 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -# simple keyword args case -kwf1(ones; tens=0, hundreds=0) = ones + 10*tens + 100*hundreds -@test kwf1(2) == 2 -@test kwf1(2, hundreds=6) == 602 -@test kwf1(2, tens=6) == 62 -@test kwf1(1, hundreds=2, tens=7) == 271 -@test kwf1(3, tens=7, hundreds=2) == 273 - -@test_throws MethodError kwf1() # no method, too few args -@test_throws MethodError kwf1(1, z=0) # unsupported keyword -@test_throws MethodError kwf1(1, 2) # no method, too many positional args - -# keyword args plus varargs -kwf2(x, rest...; y=1) = (x, y, rest) -@test isequal(kwf2(0), (0, 1, ())) -@test isequal(kwf2(0,1,2), (0, 1, (1,2))) -@test isequal(kwf2(0,1,2,y=88), (0, 88, (1,2))) -@test isequal(kwf2(0,y=88,1,2), (0, 88, (1,2))) -@test_throws MethodError kwf2(0, z=1) -@test_throws MethodError kwf2(y=1) - -# Test for #13919 -test13919(x::Vararg{Int}; key=100) = (x, key) -@test test13919(1, 1)[1] === (1, 1) -@test test13919(1, 1)[2] === 100 -@test test13919(1, 1, key=10)[1] === (1, 1) -@test test13919(1, 1, key=10)[2] === 10 - -# keyword arg with declared type -kwf3(x; y::Float64 = 1.0) = x + y -@test kwf3(2) == 3.0 -@test kwf3(2, y=3.0) == 5.0 -@test_throws TypeError kwf3(2, y=3) # wrong type keyword - -# function with only keyword args -kwf4(;a=1,b=2) = (a,b) -@test isequal(kwf4(), (1,2)) -@test isequal(kwf4(b=10), (1,10)) - -# in-order evaluation of keyword args -kwf9(;read=true,write=!read) = (read,write) -@test kwf9() === (true,false) -@test kwf9(read=false) === (false,true) -@test kwf9(write=true) === (true,true) - -# rest keywords -kwdelegator(ones;kw...) = kwf1(ones;kw...) -@test kwdelegator(4,hundreds=8) == 804 - -# optional positional args -opaf1(a,b=1,c=2,d=3) = (a,b,c,d) -@test isequal(opaf1(0), (0,1,2,3)) -@test isequal(opaf1(0,2), (0,2,2,3)) -@test isequal(opaf1(0,2,4), (0,2,4,3)) -@test isequal(opaf1(0,2,4,6), (0,2,4,6)) -@test_throws MethodError opaf1() -@test_throws MethodError opaf1(0,1,2,3,4) - -# optional positional plus varargs -opaf2(a=1,rest...) = (a,rest) -@test isequal(opaf2(), (1,())) -@test isequal(opaf2(2), (2,())) -@test isequal(opaf2(2,3), (2,(3,))) - -# optional positional plus keyword args -opkwf1(a=0,b=1;k=2) = (a,b,k) -@test isequal(opkwf1(), (0,1,2)) -@test isequal(opkwf1(10), (10,1,2)) -@test isequal(opkwf1(10,20), (10,20,2)) -@test_throws MethodError opkwf1(10,20,30) -@test isequal(opkwf1(10,20,k=8), (10,20,8)) -@test isequal(opkwf1(11;k=8), (11, 1,8)) -@test isequal(opkwf1(k=8), ( 0, 1,8)) - -# dictionaries as keywords -@test kwf1(4; Dict(:hundreds=>9, :tens=>5)...) == 954 - -# with inner function -let - function kwf_maker() - f(;k=0) = 2k+1 - end - kwf5 = kwf_maker() - @test kwf5() == 1 - @test kwf5(k=2) == 5 - @test_throws MethodError kwf5(1) -end - -# with every feature! -extravagant_args(x,y=0,rest...;color="blue",kw...) = - (x,y,rest,color,kwf1(6;tens=8,kw...)) - -@test isequal(extravagant_args(1), (1,0,(),"blue",86)) -@test isequal(extravagant_args(1;hundreds=7), (1,0,(),"blue",786)) -@test isequal(extravagant_args(1,2,3;Dict(:color=>"red", :hundreds=>3)...), - (1,2,(3,),"red",386)) - -# passing empty kw container to function with no kwargs -@test sin(1.0) == sin(1.0; Dict()...) -# issue #18845 -@test (@eval sin(1.0; $([]...))) == sin(1.0) -f18845() = 2 -@test f18845(;) == 2 -@test f18845(; []...) == 2 -@test (@eval f18845(; $([]...))) == 2 - -# passing junk kw container -@test_throws BoundsError extravagant_args(1; Any[[]]...) - -# keyword args with static parmeters -kwf6{T}(x; k::T=1) = T -@test kwf6(1) === Int -@test kwf6(1;k=2.5) === Float64 - -kwf7{T}(x::T; k::T=1) = T -@test kwf7(2) === Int -@test kwf7(1.5;k=2.5) === Float64 -@test_throws MethodError kwf7(1.5) -@test_throws TypeError kwf7(1.5;k=2) - -# try to confuse it with quoted symbol -kwf8{T}(x::MIME{:T};k::T=0) = 0 -@test kwf8(MIME{:T}()) === 0 - -# issue #4538 -macro TEST4538() - quote - function $(esc(:test4538))(x=1) - return x - end - end -end -@TEST4538 -@test test4538() == 1 -@test test4538(2) == 2 - -macro TEST4538_2() - quote - function $(esc(:test4538_2))(;x=1) - return x - end - end -end -@TEST4538_2 -@test test4538_2() == 1 -@test_throws MethodError test4538_2(2) -@test test4538_2(x=2) == 2 - -# that, but in a module -module Foo4538 -macro TEST() - quote - function $(esc(:test4538_foo_2))(;x=1) - return x - end - end -end -end -@Foo4538.TEST() -@test test4538_foo_2() == 1 -@test test4538_foo_2(x=2) == 2 - -f4538_3(;x=1) = x -macro TEST4538_3() - quote - x = 2 - f4538_3(x=3) - end -end -@test (@TEST4538_3) == 3 - -# issue #4801 -mutable struct T4801{X} - T4801{X}(;k=0) where X = new() -end -@test isa(T4801{Any}(k=0), T4801{Any}) - -# issue #4974 -function Foo4974(f; kwargs...) - (f(), kwargs) -end - -function test4974(;kwargs...) - Foo4974(;kwargs...) do - 2 - end -end - -@test test4974(a=1) == (2, [(:a, 1)]) - -# issue #7704, computed keywords -@test kwf1(1; (:tens, 2)) == 21 -let - p = (:hundreds, 3) - q = (:tens, 1) - @test kwf1(0; p, q) == 310 - @test kwf1(0; q, hundreds=4) == 410 -end - -# with anonymous functions, issue #2773 -let f = (x;a=1,b=2)->(x, a, b) - @test f(0) === (0, 1, 2) - @test f(1,a=10,b=20) === (1,10,20) - @test f(0,b=88) === (0, 1, 88) - @test_throws MethodError f(0,z=1) -end -@test ((a=2)->10a)(3) == 30 -@test ((a=2)->10a)() == 20 -@test ((a=1,b=2)->(a,b))() == (1,2) -@test ((a=1,b=2)->(a,b))(5) == (5,2) -@test ((a=1,b=2)->(a,b))(5,6) == (5,6) - -# issue #9948 -f9948, getx9948 = let - x = 3 - h(;x=x) = x - getx() = x - h, getx -end -@test_throws UndefVarError f9948() -@test getx9948() == 3 -@test f9948(x=5) == 5 -@test_throws UndefVarError f9948() -@test getx9948() == 3 - -# issue #17785 - handle all sources of kwargs left-to-right -g17785(; a=1, b=2) = (a, b) -let opts = (:a=>3, :b=>4) - @test g17785(; a=5, opts...) == (3, 4) - @test g17785(; opts..., a=5) == (5, 4) - @test g17785(; opts..., a=5, b=6) == (5, 6) - @test g17785(; b=0, opts..., a=5) == (5, 4) -end - -# pr #18396, kwargs before Base is defined -@eval Core.Inference begin - f18396(;kwargs...) = g18396(;kwargs...) - g18396(;x=1,y=2) = x+y -end -@test Core.Inference.f18396() == 3 - -# issue #7045, `invoke` with keyword args -f7045(x::Float64; y=true) = y ? 1 : invoke(f7045,Tuple{Real},x,y=y) -f7045(x::Real; y=true) = y ? 2 : 3 -@test f7045(1) === 2 -@test f7045(1.0) === 1 -@test f7045(1, y=false) === 3 -@test f7045(1.0, y=false) === 3 - -# issue #20804 -struct T20804{T} - y::T -end -(f::T20804)(;x=10) = f.y + x -let x = T20804(4) - @test x() == 14 - @test x(x=8) == 12 -end - -# issue #21147 -function f21147(f::Tuple{A}; kwargs...) where {B,A<:Tuple{B}} - return B -end -@test f21147(((1,),)) === Int -@test f21147(((1,),), k = 2) === Int -function g21147(f::Tuple{A}, k = 2) where {B,A<:Tuple{B}} - return B -end -@test g21147(((1,),)) === Int -@test g21147(((1,),), 2) === Int - -# issue #21510 -f21510(; a::ANY = 2) = a -@test f21510(a=:b) == :b -@test f21510() == 2 - -# issue #21518 -let a = 0 - f21518(;kw=nothing) = kw - g21518() = (a+=1; f21518) - g21518()(kw=1) - @test a == 1 - g21518()(; :kw=>1) - @test a == 2 -end diff --git a/julia-0.6.3/share/julia/test/libdl.jl b/julia-0.6.3/share/julia/test/libdl.jl deleted file mode 100644 index 4aba535..0000000 --- a/julia-0.6.3/share/julia/test/libdl.jl +++ /dev/null @@ -1,190 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -# these could fail on an embedded installation -# but for now, we don't handle that case -dlls = Libdl.dllist() -@test !isempty(dlls) -@test length(dlls) > 3 # at a bare minimum, probably have some version of libstdc, libgcc, libjulia, ... -if !is_windows() || Sys.windows_version() >= Sys.WINDOWS_VISTA_VER - for dl in dlls - if isfile(dl) && (Libdl.dlopen_e(dl) != C_NULL) - @test Base.samefile(Libdl.dlpath(dl), dl) - end - end -end -@test length(filter(dlls) do dl - return ismatch(Regex("^libjulia(?:.*)\.$(Libdl.dlext)(?:\..+)?\$"), basename(dl)) - end) == 1 # look for something libjulia-like (but only one) - -# library handle pointer must not be NULL -@test_throws ArgumentError Libdl.dlsym(C_NULL, :foo) -@test_throws ArgumentError Libdl.dlsym_e(C_NULL, :foo) - -cd(dirname(@__FILE__)) do - -# Find the library directory by finding the path of libjulia (or libjulia-debug, as the case may be) -# and then adding on /julia to that directory path to get the private library directory, if we need -# to (where "need to" is defined as private_libdir/julia/libccalltest.dlext exists -private_libdir = if ccall(:jl_is_debugbuild, Cint, ()) != 0 - dirname(abspath(Libdl.dlpath("libjulia-debug"))) -else - dirname(abspath(Libdl.dlpath("libjulia"))) -end - -if isfile(joinpath(private_libdir,"julia","libccalltest."*Libdl.dlext)) - private_libdir = joinpath(private_libdir, "julia") -end - -@test !isempty(Libdl.find_library(["libccalltest"], [private_libdir])) -@test !isempty(Libdl.find_library("libccalltest", [private_libdir])) -@test !isempty(Libdl.find_library(:libccalltest, [private_libdir])) - -# dlopen should be able to handle absolute and relative paths, with and without dlext -let dl = C_NULL - try - dl = Libdl.dlopen_e(abspath(joinpath(private_libdir, "libccalltest"))) - @test dl != C_NULL - finally - Libdl.dlclose(dl) - end -end - -let dl = C_NULL - try - dl = Libdl.dlopen_e(abspath(joinpath(private_libdir, "libccalltest.$(Libdl.dlext)"))) - @test dl != C_NULL - finally - Libdl.dlclose(dl) - end -end - -let dl = C_NULL - try - dl = Libdl.dlopen_e(relpath(joinpath(private_libdir, "libccalltest"))) - @test dl != C_NULL - finally - Libdl.dlclose(dl) - end -end - -let dl = C_NULL - try - dl = Libdl.dlopen_e(relpath(joinpath(private_libdir, "libccalltest.$(Libdl.dlext)"))) - @test dl != C_NULL - finally - Libdl.dlclose(dl) - end -end - -let dl = C_NULL - try - dl = Libdl.dlopen_e("./foo") - @test dl == C_NULL - finally - Libdl.dlclose(dl) - end -end - -# unqualified names present in DL_LOAD_PATH -let dl = C_NULL - try - dl = Libdl.dlopen_e("libccalltest") - @test dl != C_NULL - finally - Libdl.dlclose(dl) - end -end - -let dl = C_NULL - try - dl = Libdl.dlopen_e(string("libccalltest",".",Libdl.dlext)) - @test dl != C_NULL - finally - Libdl.dlclose(dl) - end -end - -# path with dlopen-able file first in load path -#= -let dl = C_NULL, - tmpdir = mktempdir(), - fpath = joinpath(tmpdir,"libccalltest") - try - write(open(fpath,"w")) - push!(Libdl.DL_LOAD_PATH, dirname(@__FILE__)) - push!(Libdl.DL_LOAD_PATH, dirname(fpath)) - dl = Libdl.dlopen_e("libccalltest") - @test dl != C_NULL - finally - pop!(Libdl.DL_LOAD_PATH) - pop!(Libdl.DL_LOAD_PATH) - rm(tmpdir, recursive=true) - end -end -=# - -# path with dlopen-able file second in load path -#= -let dl = C_NULL, - tmpdir = mktempdir(), - fpath = joinpath(tmpdir,"libccalltest") - try - write(open(fpath,"w")) - push!(Libdl.DL_LOAD_PATH, dirname(fpath)) - push!(Libdl.DL_LOAD_PATH, dirname(@__FILE__)) - dl = Libdl.dlopen_e("libccalltest") - @test dl != C_NULL - finally - pop!(Libdl.DL_LOAD_PATH) - pop!(Libdl.DL_LOAD_PATH) - rm(tmpdir, recursive=true) - end -end -=# - -# test dlpath -let dl = C_NULL - try - path = abspath(joinpath(private_libdir, "libccalltest")) - dl = Libdl.dlopen(path) - @test dl != C_NULL - @test Base.samefile(abspath(Libdl.dlpath(dl)), - abspath(Libdl.dlpath(path))) - @test Base.samefile(abspath(Libdl.dlpath(dl)), - string(path,".",Libdl.dlext)) - finally - Libdl.dlclose(dl) - end -end - -# opening a library that does not exist throws an ErrorException -@test_throws ErrorException Libdl.dlopen("./foo") - -# opening a versioned library that does not exist does not result in adding extension twice -err = @test_throws ErrorException Libdl.dlopen("./foo.$(Libdl.dlext).0") -@test !contains(err.value.msg, "foo.$(Libdl.dlext).0.$(Libdl.dlext)") -err = @test_throws ErrorException Libdl.dlopen("./foo.$(Libdl.dlext).0.22.1") -@test !contains(err.value.msg, "foo.$(Libdl.dlext).0.22.1.$(Libdl.dlext)") - -# test dlsym -let dl = C_NULL - try - dl = Libdl.dlopen(abspath(joinpath(private_libdir, "libccalltest"))) - fptr = Libdl.dlsym(dl, :set_verbose) - @test fptr != C_NULL - @test_throws ErrorException Libdl.dlsym(dl, :foo) - - fptr = Libdl.dlsym_e(dl, :set_verbose) - @test fptr != C_NULL - fptr = Libdl.dlsym_e(dl, :foo) - @test fptr == C_NULL - finally - Libdl.dlclose(dl) - end -end - -if Sys.KERNEL in (:Linux, :FreeBSD) - ccall(:jl_read_sonames, Void, ()) -end - -end diff --git a/julia-0.6.3/share/julia/test/libgit2-helpers.jl b/julia-0.6.3/share/julia/test/libgit2-helpers.jl deleted file mode 100644 index 1f0cae5..0000000 --- a/julia-0.6.3/share/julia/test/libgit2-helpers.jl +++ /dev/null @@ -1,66 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -import Base.LibGit2: AbstractCredentials, UserPasswordCredentials, SSHCredentials, CachedCredentials - -""" -Emulates the LibGit2 credential loop to allows testing of the credential_callback function -without having to authenticate against a real server. -""" -function credential_loop( - valid_credential::AbstractCredentials, - url::AbstractString, - user::AbstractString, - allowed_types::UInt32, - cache::CachedCredentials=CachedCredentials()) - cb = Base.LibGit2.credentials_cb() - libgitcred_ptr_ptr = Ref{Ptr{Void}}(C_NULL) - payload_ptr = Ref(Nullable{AbstractCredentials}(cache)) - - # Number of times credentials were authenticated against. With the real LibGit2 - # credential loop this would be how many times we sent credentials to the remote. - num_authentications = 0 - - # Emulate how LibGit2 uses the credential callback by repeatedly calling the function - # until we find valid credentials or an exception is raised. - err = Cint(0) - while err == 0 - err = ccall(cb, Cint, (Ptr{Ptr{Void}}, Cstring, Cstring, Cuint, Ptr{Void}), - libgitcred_ptr_ptr, url, isempty(user) ? C_NULL : user, allowed_types, pointer_from_objref(payload_ptr)) - num_authentications += 1 - - # Check if the callback provided us with valid credentials - if length(cache.cred) == 1 && first(values(cache.cred)) == valid_credential - break - end - - if num_authentications > 50 - error("Credential callback seems to be caught in an infinite loop") - end - end - - return err, num_authentications -end - -function credential_loop( - valid_credential::UserPasswordCredentials, - url::AbstractString, - user::AbstractString="") - credential_loop(valid_credential, url, user, 0x000001) -end - -function credential_loop( - valid_credential::SSHCredentials, - url::AbstractString, - user::AbstractString=""; - use_ssh_agent::Bool=false) - cache = CachedCredentials() - - if !use_ssh_agent - m = match(LibGit2.URL_REGEX, url) - default_cred = LibGit2.reset!(SSHCredentials(true), -1) - default_cred.usesshagent = "N" - LibGit2.get_creds!(cache, "ssh://$(m[:host])", default_cred) - end - - credential_loop(valid_credential, url, user, 0x000046, cache) -end diff --git a/julia-0.6.3/share/julia/test/libgit2-online.jl b/julia-0.6.3/share/julia/test/libgit2-online.jl deleted file mode 100644 index cd1c48b..0000000 --- a/julia-0.6.3/share/julia/test/libgit2-online.jl +++ /dev/null @@ -1,34 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -######### -# TESTS # -######### -# init & clone -mktempdir() do dir - repo_url = "https://github.com/JuliaLang/Example.jl" - @testset "Cloning repository" begin - @testset "with 'https' protocol" begin - repo_path = joinpath(dir, "Example1") - repo = LibGit2.clone(repo_url, repo_path) - try - @test isdir(repo_path) - @test isdir(joinpath(repo_path, ".git")) - finally - close(repo) - end - end - - @testset "with incorrect url" begin - try - repo_path = joinpath(dir, "Example2") - # credentials are required because github tries to authenticate on unknown repo - cred = LibGit2.UserPasswordCredentials("","") # empty credentials cause authentication error - LibGit2.clone(repo_url*randstring(10), repo_path, payload=Nullable(cred)) - error("unexpected") - catch ex - @test isa(ex, LibGit2.Error.GitError) - @test ex.code == LibGit2.Error.EAUTH - end - end - end -end diff --git a/julia-0.6.3/share/julia/test/libgit2.jl b/julia-0.6.3/share/julia/test/libgit2.jl deleted file mode 100644 index 0f09a6f..0000000 --- a/julia-0.6.3/share/julia/test/libgit2.jl +++ /dev/null @@ -1,1708 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -isdefined(Main, :TestHelpers) || @eval Main include(joinpath(dirname(@__FILE__), "TestHelpers.jl")) -import TestHelpers: challenge_prompt - -const LIBGIT2_MIN_VER = v"0.23.0" -const LIBGIT2_HELPER_PATH = joinpath(dirname(@__FILE__), "libgit2-helpers.jl") - -function get_global_dir() - buf = Ref(LibGit2.Buffer()) - LibGit2.@check ccall((:git_libgit2_opts, :libgit2), Cint, - (Cint, Cint, Ptr{LibGit2.Buffer}), - LibGit2.Consts.GET_SEARCH_PATH, LibGit2.Consts.CONFIG_LEVEL_GLOBAL, buf) - path = unsafe_string(buf[].ptr) - LibGit2.free(buf) - return path -end - -function set_global_dir(dir) - LibGit2.@check ccall((:git_libgit2_opts, :libgit2), Cint, - (Cint, Cint, Cstring), - LibGit2.Consts.SET_SEARCH_PATH, LibGit2.Consts.CONFIG_LEVEL_GLOBAL, dir) - return -end - -function with_libgit2_temp_home(f) - mktempdir() do tmphome - oldpath = get_global_dir() - set_global_dir(tmphome) - try - @test get_global_dir() == tmphome - f(tmphome) - finally - set_global_dir(oldpath) - end - return - end -end - -######### -# TESTS # -######### - -@testset "Check library version" begin - v = LibGit2.version() - @test v.major == LIBGIT2_MIN_VER.major && v.minor >= LIBGIT2_MIN_VER.minor -end - -@testset "Check library features" begin - f = LibGit2.features() - @test findfirst(f, LibGit2.Consts.FEATURE_SSH) > 0 - @test findfirst(f, LibGit2.Consts.FEATURE_HTTPS) > 0 -end - -@testset "OID" begin - z = LibGit2.GitHash() - @test LibGit2.iszero(z) - @test z == zero(LibGit2.GitHash) - @test z == LibGit2.GitHash(z) - rs = string(z) - rr = LibGit2.raw(z) - @test z == LibGit2.GitHash(rr) - @test z == LibGit2.GitHash(rs) - @test z == LibGit2.GitHash(pointer(rr)) - - @test LibGit2.GitShortHash(z, 20) == LibGit2.GitShortHash(rs[1:20]) - @test_throws ArgumentError LibGit2.GitHash(Ptr{UInt8}(C_NULL)) - @test_throws ArgumentError LibGit2.GitHash(rand(UInt8, 2*LibGit2.OID_RAWSZ)) - @test_throws ArgumentError LibGit2.GitHash("a") -end - -@testset "StrArrayStruct" begin - p = ["XXX","YYY"] - a = Base.cconvert(Ptr{LibGit2.StrArrayStruct}, p) - b = Base.unsafe_convert(Ptr{LibGit2.StrArrayStruct}, a) - @test p == convert(Vector{String}, unsafe_load(b)) -end - -@testset "Signature" begin - sig = LibGit2.Signature("AAA", "AAA@BBB.COM", round(time(), 0), 0) - git_sig = convert(LibGit2.GitSignature, sig) - sig2 = LibGit2.Signature(git_sig) - close(git_sig) - @test sig.name == sig2.name - @test sig.email == sig2.email - @test sig.time == sig2.time - sig3 = LibGit2.Signature("AAA","AAA@BBB.COM") - @test sig3.name == sig.name - @test sig3.email == sig.email -end - -@testset "Default config" begin - with_libgit2_temp_home() do tmphome - cfg = LibGit2.GitConfig() - @test isa(cfg, LibGit2.GitConfig) - @test LibGit2.getconfig("fake.property", "") == "" - LibGit2.set!(cfg, "fake.property", "AAAA") - @test LibGit2.getconfig("fake.property", "") == "AAAA" - end -end - -# See #21872 and #21636 -LibGit2.version() >= v"0.26.0" && is_unix() && @testset "Default config with symlink" begin - with_libgit2_temp_home() do tmphome - write(joinpath(tmphome, "real_gitconfig"), "[fake]\n\tproperty = BBB") - symlink(joinpath(tmphome, "real_gitconfig"), - joinpath(tmphome, ".gitconfig")) - cfg = LibGit2.GitConfig() - @test isa(cfg, LibGit2.GitConfig) - LibGit2.getconfig("fake.property", "") == "BBB" - LibGit2.set!(cfg, "fake.property", "AAAA") - LibGit2.getconfig("fake.property", "") == "AAAA" - end -end - -@testset "Git URL parsing" begin - @testset "HTTPS URL" begin - m = match(LibGit2.URL_REGEX, "https://user:pass@server.com:80/org/project.git") - @test m[:scheme] == "https" - @test m[:user] == "user" - @test m[:password] == "pass" - @test m[:host] == "server.com" - @test m[:port] == "80" - @test m[:path] == "/org/project.git" - end - - @testset "SSH URL" begin - m = match(LibGit2.URL_REGEX, "ssh://user:pass@server:22/project.git") - @test m[:scheme] == "ssh" - @test m[:user] == "user" - @test m[:password] == "pass" - @test m[:host] == "server" - @test m[:port] == "22" - @test m[:path] == "/project.git" - end - - @testset "SSH URL, scp-like syntax" begin - m = match(LibGit2.URL_REGEX, "user@server:project.git") - @test m[:scheme] === nothing - @test m[:user] == "user" - @test m[:password] === nothing - @test m[:host] == "server" - @test m[:port] === nothing - @test m[:path] == "project.git" - end - - # scp-like syntax corner case. The SCP syntax does not support port so everything after - # the colon is part of the path. - @testset "scp-like syntax, no port" begin - m = match(LibGit2.URL_REGEX, "server:1234/repo") - @test m[:scheme] === nothing - @test m[:user] === nothing - @test m[:password] === nothing - @test m[:host] == "server" - @test m[:port] === nothing - @test m[:path] == "1234/repo" - end - - @testset "HTTPS URL, realistic" begin - m = match(LibGit2.URL_REGEX, "https://github.com/JuliaLang/Example.jl.git") - @test m[:scheme] == "https" - @test m[:user] === nothing - @test m[:password] === nothing - @test m[:host] == "github.com" - @test m[:port] === nothing - @test m[:path] == "/JuliaLang/Example.jl.git" - end - - @testset "SSH URL, realistic" begin - m = match(LibGit2.URL_REGEX, "git@github.com:JuliaLang/Example.jl.git") - @test m[:scheme] === nothing - @test m[:user] == "git" - @test m[:password] === nothing - @test m[:host] == "github.com" - @test m[:port] === nothing - @test m[:path] == "JuliaLang/Example.jl.git" - end - - @testset "usernames with special characters" begin - m = match(LibGit2.URL_REGEX, "user-name@hostname.com") - @test m[:user] == "user-name" - end - - @testset "HTTPS URL, no path" begin - m = match(LibGit2.URL_REGEX, "https://user:pass@server.com:80") - @test m[:path] == "" - end - - @testset "scp-like syntax, no path" begin - m = match(LibGit2.URL_REGEX, "user@server:") - @test m[:path] == "" - - m = match(LibGit2.URL_REGEX, "user@server") - @test m[:path] == "" - end -end - -mktempdir() do dir - # test parameters - repo_url = "https://github.com/JuliaLang/Example.jl" - cache_repo = joinpath(dir, "Example") - test_repo = joinpath(dir, "Example.Test") - test_sig = LibGit2.Signature("TEST", "TEST@TEST.COM", round(time(), 0), 0) - test_file = "testfile" - config_file = "testconfig" - commit_msg1 = randstring(10) - commit_msg2 = randstring(10) - commit_oid1 = LibGit2.GitHash() - commit_oid2 = LibGit2.GitHash() - commit_oid3 = LibGit2.GitHash() - master_branch = "master" - test_branch = "test_branch" - test_branch2 = "test_branch_two" - tag1 = "tag1" - tag2 = "tag2" - - @testset "Configuration" begin - cfg = LibGit2.GitConfig(joinpath(dir, config_file), LibGit2.Consts.CONFIG_LEVEL_APP) - try - @test_throws LibGit2.Error.GitError LibGit2.get(AbstractString, cfg, "tmp.str") - @test isempty(LibGit2.get(cfg, "tmp.str", "")) == true - - LibGit2.set!(cfg, "tmp.str", "AAAA") - LibGit2.set!(cfg, "tmp.int32", Int32(1)) - LibGit2.set!(cfg, "tmp.int64", Int64(1)) - LibGit2.set!(cfg, "tmp.bool", true) - - @test LibGit2.get(cfg, "tmp.str", "") == "AAAA" - @test LibGit2.get(cfg, "tmp.int32", Int32(0)) == Int32(1) - @test LibGit2.get(cfg, "tmp.int64", Int64(0)) == Int64(1) - @test LibGit2.get(cfg, "tmp.bool", false) == true - finally - close(cfg) - end - end - - @testset "Initializing repository" begin - @testset "with remote branch" begin - repo = LibGit2.init(cache_repo) - try - @test isdir(cache_repo) - @test LibGit2.path(repo) == LibGit2.posixpath(realpath(cache_repo)) - @test isdir(joinpath(cache_repo, ".git")) - - # set a remote branch - branch = "upstream" - LibGit2.GitRemote(repo, branch, repo_url) |> close - - config = joinpath(cache_repo, ".git", "config") - lines = split(open(readstring, config, "r"), "\n") - @test any(map(x->x == "[remote \"upstream\"]", lines)) - - remote = LibGit2.get(LibGit2.GitRemote, repo, branch) - @test LibGit2.url(remote) == repo_url - @test LibGit2.push_url(remote) == "" - @test LibGit2.name(remote) == "upstream" - @test isa(remote, LibGit2.GitRemote) - @test sprint(show, remote) == "GitRemote:\nRemote name: upstream url: $repo_url" - @test LibGit2.isattached(repo) - LibGit2.set_remote_url(repo, "", remote="upstream") - remote = LibGit2.get(LibGit2.GitRemote, repo, branch) - @test LibGit2.url(remote) == "" - @test LibGit2.push_url(remote) == "" - @test sprint(show, remote) == "GitRemote:\nRemote name: upstream url: " - close(remote) - LibGit2.set_remote_url(cache_repo, repo_url, remote="upstream") - remote = LibGit2.get(LibGit2.GitRemote, repo, branch) - @test LibGit2.url(remote) == repo_url - @test LibGit2.push_url(remote) == repo_url - @test sprint(show, remote) == "GitRemote:\nRemote name: upstream url: $repo_url" - LibGit2.add_fetch!(repo, remote, "upstream") - @test LibGit2.fetch_refspecs(remote) == String["+refs/heads/*:refs/remotes/upstream/*"] - LibGit2.add_push!(repo, remote, "refs/heads/master") - close(remote) - remote = LibGit2.get(LibGit2.GitRemote, repo, branch) - @test LibGit2.push_refspecs(remote) == String["refs/heads/master"] - close(remote) - # constructor with a refspec - remote = LibGit2.GitRemote(repo, "upstream2", repo_url, "upstream") - @test sprint(show, remote) == "GitRemote:\nRemote name: upstream2 url: $repo_url" - @test LibGit2.fetch_refspecs(remote) == String["upstream"] - close(remote) - - remote = LibGit2.GitRemoteAnon(repo, repo_url) - @test LibGit2.url(remote) == repo_url - @test LibGit2.push_url(remote) == "" - @test LibGit2.name(remote) == "" - @test isa(remote, LibGit2.GitRemote) - close(remote) - finally - close(repo) - end - end - - @testset "bare" begin - path = joinpath(dir, "Example.Bare") - repo = LibGit2.init(path, true) - try - @test isdir(path) - @test LibGit2.path(repo) == LibGit2.posixpath(realpath(path)) - @test isfile(joinpath(path, LibGit2.Consts.HEAD_FILE)) - @test LibGit2.isattached(repo) - finally - close(repo) - end - - path = joinpath("garbagefakery", "Example.Bare") - try - LibGit2.GitRepo(path) - error("unexpected") - catch e - @test typeof(e) == LibGit2.GitError - @test startswith( - lowercase(sprint(show, e)), - lowercase("GitError(Code:ENOTFOUND, Class:OS, failed to resolve path")) - end - path = joinpath(dir, "Example.BareTwo") - repo = LibGit2.init(path, true) - try - #just to see if this works - LibGit2.cleanup(repo) - finally - close(repo) - end - end - end - - @testset "Cloning repository" begin - - @testset "bare" begin - repo_path = joinpath(dir, "Example.Bare1") - repo = LibGit2.clone(cache_repo, repo_path, isbare = true) - try - @test isdir(repo_path) - @test LibGit2.path(repo) == LibGit2.posixpath(realpath(repo_path)) - @test isfile(joinpath(repo_path, LibGit2.Consts.HEAD_FILE)) - @test LibGit2.isattached(repo) - @test LibGit2.remotes(repo) == ["origin"] - finally - close(repo) - end - end - @testset "bare with remote callback" begin - repo_path = joinpath(dir, "Example.Bare2") - repo = LibGit2.clone(cache_repo, repo_path, isbare = true, remote_cb = LibGit2.mirror_cb()) - try - @test isdir(repo_path) - @test LibGit2.path(repo) == LibGit2.posixpath(realpath(repo_path)) - @test isfile(joinpath(repo_path, LibGit2.Consts.HEAD_FILE)) - rmt = LibGit2.get(LibGit2.GitRemote, repo, "origin") - try - @test LibGit2.fetch_refspecs(rmt)[1] == "+refs/*:refs/*" - @test LibGit2.isattached(repo) - @test LibGit2.remotes(repo) == ["origin"] - finally - close(rmt) - end - finally - close(repo) - end - end - @testset "normal" begin - repo = LibGit2.clone(cache_repo, test_repo) - try - @test isdir(test_repo) - @test LibGit2.path(repo) == LibGit2.posixpath(realpath(test_repo)) - @test isdir(joinpath(test_repo, ".git")) - @test LibGit2.workdir(repo) == LibGit2.path(repo)*"/" - @test LibGit2.isattached(repo) - @test LibGit2.isorphan(repo) - repo_str = sprint(show, repo) - @test repo_str == "LibGit2.GitRepo($(sprint(show,LibGit2.path(repo))))" - finally - close(repo) - end - end - end - - @testset "Update cache repository" begin - - @testset "with commits" begin - repo = LibGit2.GitRepo(cache_repo) - repo_file = open(joinpath(cache_repo,test_file), "a") - try - # create commits - println(repo_file, commit_msg1) - flush(repo_file) - LibGit2.add!(repo, test_file) - @test LibGit2.iszero(commit_oid1) - commit_oid1 = LibGit2.commit(repo, commit_msg1; author=test_sig, committer=test_sig) - @test !LibGit2.iszero(commit_oid1) - - println(repo_file, randstring(10)) - flush(repo_file) - LibGit2.add!(repo, test_file) - commit_oid3 = LibGit2.commit(repo, randstring(10); author=test_sig, committer=test_sig) - - println(repo_file, commit_msg2) - flush(repo_file) - LibGit2.add!(repo, test_file) - @test LibGit2.iszero(commit_oid2) - commit_oid2 = LibGit2.commit(repo, commit_msg2; author=test_sig, committer=test_sig) - @test !LibGit2.iszero(commit_oid2) - auths = LibGit2.authors(repo) - @test length(auths) == 3 - for auth in auths - @test auth.name == test_sig.name - @test auth.time == test_sig.time - @test auth.email == test_sig.email - end - @test LibGit2.is_ancestor_of(string(commit_oid1), string(commit_oid2), repo) - @test LibGit2.iscommit(string(commit_oid1), repo) - @test !LibGit2.iscommit(string(commit_oid1)*"fake", repo) - @test LibGit2.iscommit(string(commit_oid2), repo) - - # lookup commits - cmt = LibGit2.GitCommit(repo, commit_oid1) - try - @test LibGit2.Consts.OBJECT(typeof(cmt)) == LibGit2.Consts.OBJ_COMMIT - @test commit_oid1 == LibGit2.GitHash(cmt) - short_oid1 = LibGit2.GitShortHash(string(commit_oid1)) - @test hex(commit_oid1) == hex(short_oid1) - @test cmp(commit_oid1, short_oid1) == 0 - @test cmp(short_oid1, commit_oid1) == 0 - @test !(short_oid1 < commit_oid1) - short_str = sprint(show, short_oid1) - @test short_str == "GitShortHash(\"$(string(short_oid1))\")" - auth = LibGit2.author(cmt) - @test isa(auth, LibGit2.Signature) - @test auth.name == test_sig.name - @test auth.time == test_sig.time - @test auth.email == test_sig.email - short_auth = LibGit2.author(LibGit2.GitCommit(repo, short_oid1)) - @test short_auth.name == test_sig.name - @test short_auth.time == test_sig.time - @test short_auth.email == test_sig.email - cmtr = LibGit2.committer(cmt) - @test isa(cmtr, LibGit2.Signature) - @test cmtr.name == test_sig.name - @test cmtr.time == test_sig.time - @test cmtr.email == test_sig.email - @test LibGit2.message(cmt) == commit_msg1 - showstr = split(sprint(show, cmt), "\n") - # the time of the commit will vary so just test the first two parts - @test contains(showstr[1], "Git Commit:") - @test contains(showstr[2], "Commit Author: Name: TEST, Email: TEST@TEST.COM, Time:") - @test contains(showstr[3], "Committer: Name: TEST, Email: TEST@TEST.COM, Time:") - @test contains(showstr[4], "SHA:") - @test showstr[5] == "Message:" - @test showstr[6] == commit_msg1 - - @test LibGit2.revcount(repo, string(commit_oid1), string(commit_oid3)) == (-1,0) - finally - close(cmt) - end - finally - close(repo) - close(repo_file) - end - end - - @testset "with branch" begin - repo = LibGit2.GitRepo(cache_repo) - try - brnch = LibGit2.branch(repo) - brref = LibGit2.head(repo) - try - @test LibGit2.isbranch(brref) - @test !LibGit2.isremote(brref) - @test LibGit2.name(brref) == "refs/heads/master" - @test LibGit2.shortname(brref) == master_branch - @test LibGit2.ishead(brref) - @test isnull(LibGit2.upstream(brref)) - show_strs = split(sprint(show, brref), "\n") - @test show_strs[1] == "GitReference:" - @test show_strs[2] == "Branch with name refs/heads/master" - @test show_strs[3] == "Branch is HEAD." - @test repo.ptr == LibGit2.repository(brref).ptr - @test brnch == master_branch - @test LibGit2.headname(repo) == master_branch - LibGit2.branch!(repo, test_branch, string(commit_oid1), set_head=false) - - @test isnull(LibGit2.lookup_branch(repo, test_branch, true)) - tbref = Base.get(LibGit2.lookup_branch(repo, test_branch, false)) - try - @test LibGit2.shortname(tbref) == test_branch - @test isnull(LibGit2.upstream(tbref)) - finally - close(tbref) - end - @test isnull(LibGit2.lookup_branch(repo, test_branch2, true)) - LibGit2.branch!(repo, test_branch2; set_head=false) - tbref = Base.get(LibGit2.lookup_branch(repo, test_branch2, false)) - try - @test LibGit2.shortname(tbref) == test_branch2 - LibGit2.delete_branch(tbref) - @test isnull(LibGit2.lookup_branch(repo, test_branch2, true)) - finally - close(tbref) - end - finally - close(brref) - end - - branches = map(b->LibGit2.shortname(b[1]), LibGit2.GitBranchIter(repo)) - @test master_branch in branches - @test test_branch in branches - finally - close(repo) - end - end - - @testset "with default configuration" begin - repo = LibGit2.GitRepo(cache_repo) - try - try - LibGit2.Signature(repo) - catch ex - # these test configure repo with new signature - # in case when global one does not exsist - @test isa(ex, LibGit2.Error.GitError) == true - - cfg = LibGit2.GitConfig(repo) - LibGit2.set!(cfg, "user.name", "AAAA") - LibGit2.set!(cfg, "user.email", "BBBB@BBBB.COM") - sig = LibGit2.Signature(repo) - @test sig.name == "AAAA" - @test sig.email == "BBBB@BBBB.COM" - @test LibGit2.getconfig(repo, "user.name", "") == "AAAA" - @test LibGit2.getconfig(cache_repo, "user.name", "") == "AAAA" - end - finally - close(repo) - end - end - - @testset "with tags" begin - repo = LibGit2.GitRepo(cache_repo) - try - tags = LibGit2.tag_list(repo) - @test length(tags) == 0 - - tag_oid1 = LibGit2.tag_create(repo, tag1, commit_oid1, sig=test_sig) - @test !LibGit2.iszero(tag_oid1) - tags = LibGit2.tag_list(repo) - @test length(tags) == 1 - @test tag1 in tags - tag1ref = LibGit2.GitReference(repo, "refs/tags/$tag1") - @test isempty(LibGit2.fullname(tag1ref)) #because this is a reference to an OID - show_strs = split(sprint(show, tag1ref), "\n") - @test show_strs[1] == "GitReference:" - @test show_strs[2] == "Tag with name refs/tags/$tag1" - tag1tag = LibGit2.peel(LibGit2.GitTag,tag1ref) - @test LibGit2.name(tag1tag) == tag1 - @test LibGit2.target(tag1tag) == commit_oid1 - @test sprint(show, tag1tag) == "GitTag:\nTag name: $tag1 target: $commit_oid1" - tag_oid2 = LibGit2.tag_create(repo, tag2, commit_oid2) - @test !LibGit2.iszero(tag_oid2) - tags = LibGit2.tag_list(repo) - @test length(tags) == 2 - @test tag2 in tags - - refs = LibGit2.ref_list(repo) - @test refs == ["refs/heads/master","refs/heads/test_branch","refs/tags/tag1","refs/tags/tag2"] - - LibGit2.tag_delete(repo, tag1) - tags = LibGit2.tag_list(repo) - @test length(tags) == 1 - @test tag2 ∈ tags - @test tag1 ∉ tags - finally - close(repo) - end - end - - @testset "status" begin - repo = LibGit2.GitRepo(cache_repo) - try - status = LibGit2.GitStatus(repo) - @test length(status) == 0 - @test_throws BoundsError status[1] - repo_file = open(joinpath(cache_repo,"statusfile"), "a") - - # create commits - println(repo_file, commit_msg1) - flush(repo_file) - LibGit2.add!(repo, test_file) - status = LibGit2.GitStatus(repo) - @test length(status) != 0 - @test_throws BoundsError status[0] - @test_throws BoundsError status[length(status)+1] - # we've added a file - show that it is new - @test status[1].status == LibGit2.Consts.STATUS_WT_NEW - close(repo_file) - finally - close(repo) - end - end - - @testset "blobs" begin - repo = LibGit2.GitRepo(cache_repo) - try - # this is slightly dubious, as it assumes the object has not been packed - # could be replaced by another binary format - hash_string = hex(commit_oid1) - blob_file = joinpath(cache_repo,".git/objects", hash_string[1:2], hash_string[3:end]) - - id = LibGit2.addblob!(repo, blob_file) - blob = LibGit2.GitBlob(repo, id) - @test LibGit2.isbinary(blob) - len1 = length(blob) - blob_show_strs = split(sprint(show, blob), "\n") - @test blob_show_strs[1] == "GitBlob:" - @test contains(blob_show_strs[2], "Blob id:") - @test blob_show_strs[3] == "Contents are binary." - - blob2 = LibGit2.GitBlob(repo, LibGit2.GitHash(blob)) - @test LibGit2.isbinary(blob2) - @test length(blob2) == len1 - finally - close(repo) - end - end - @testset "trees" begin - repo = LibGit2.GitRepo(cache_repo) - try - @test_throws LibGit2.Error.GitError LibGit2.GitTree(repo, "HEAD") - tree = LibGit2.GitTree(repo, "HEAD^{tree}") - @test isa(tree, LibGit2.GitTree) - @test isa(LibGit2.GitObject(repo, "HEAD^{tree}"), LibGit2.GitTree) - @test LibGit2.Consts.OBJECT(typeof(tree)) == LibGit2.Consts.OBJ_TREE - @test count(tree) == 1 - tree_str = sprint(show, tree) - @test tree_str == "GitTree:\nOwner: $(LibGit2.repository(tree))\nNumber of entries: 1\n" - @test_throws BoundsError tree[0] - @test_throws BoundsError tree[2] - tree_entry = tree[1] - @test LibGit2.filemode(tree_entry) == 33188 - te_str = sprint(show, tree_entry) - @test te_str == "GitTreeEntry:\nEntry name: testfile\nEntry type: Base.LibGit2.GitBlob\nEntry OID: $(LibGit2.entryid(tree_entry))\n" - blob = LibGit2.GitBlob(tree_entry) - blob_str = sprint(show, blob) - @test blob_str == "GitBlob:\nBlob id: $(LibGit2.GitHash(blob))\nContents:\n$(LibGit2.content(blob))\n" - finally - close(repo) - end - end - - @testset "diff" begin - repo = LibGit2.GitRepo(cache_repo) - try - @test !LibGit2.isdirty(repo) - @test !LibGit2.isdirty(repo, test_file) - @test !LibGit2.isdirty(repo, "nonexistent") - @test !LibGit2.isdiff(repo, "HEAD") - @test !LibGit2.isdirty(repo, cached=true) - @test !LibGit2.isdirty(repo, test_file, cached=true) - @test !LibGit2.isdirty(repo, "nonexistent", cached=true) - @test !LibGit2.isdiff(repo, "HEAD", cached=true) - open(joinpath(cache_repo,test_file), "a") do f - println(f, "zzzz") - end - @test LibGit2.isdirty(repo) - @test LibGit2.isdirty(repo, test_file) - @test !LibGit2.isdirty(repo, "nonexistent") - @test LibGit2.isdiff(repo, "HEAD") - @test !LibGit2.isdirty(repo, cached=true) - @test !LibGit2.isdiff(repo, "HEAD", cached=true) - LibGit2.add!(repo, test_file) - @test LibGit2.isdirty(repo) - @test LibGit2.isdiff(repo, "HEAD") - @test LibGit2.isdirty(repo, cached=true) - @test LibGit2.isdiff(repo, "HEAD", cached=true) - tree = LibGit2.GitTree(repo, "HEAD^{tree}") - diff = LibGit2.diff_tree(repo, tree, "", cached=true) - @test count(diff) == 1 - @test_throws BoundsError diff[0] - @test_throws BoundsError diff[2] - @test LibGit2.Consts.DELTA_STATUS(diff[1].status) == LibGit2.Consts.DELTA_MODIFIED - @test diff[1].nfiles == 2 - diff_strs = split(sprint(show, diff[1]), '\n') - @test diff_strs[1] == "DiffDelta:" - @test diff_strs[2] == "Status: DELTA_MODIFIED" - @test diff_strs[3] == "Number of files: 2" - @test diff_strs[4] == "Old file:" - @test diff_strs[5] == "DiffFile:" - @test contains(diff_strs[6], "Oid:") - @test contains(diff_strs[7], "Path:") - @test contains(diff_strs[8], "Size:") - @test isempty(diff_strs[9]) - @test diff_strs[10] == "New file:" - diff_strs = split(sprint(show, diff), '\n') - @test diff_strs[1] == "GitDiff:" - @test diff_strs[2] == "Number of deltas: 1" - @test diff_strs[3] == "GitDiffStats:" - @test diff_strs[4] == "Files changed: 1" - @test diff_strs[5] == "Insertions: 1" - @test diff_strs[6] == "Deletions: 0" - LibGit2.commit(repo, "zzz") - @test !LibGit2.isdirty(repo) - @test !LibGit2.isdiff(repo, "HEAD") - @test !LibGit2.isdirty(repo, cached=true) - @test !LibGit2.isdiff(repo, "HEAD", cached=true) - finally - close(repo) - end - end - end - - # TO DO: add more tests for various merge - # preference options - @testset "Fastforward merges" begin - path = joinpath(dir, "Example.FF") - repo = LibGit2.clone(cache_repo, path) - # need to set this for merges to succeed - cfg = LibGit2.GitConfig(repo) - LibGit2.set!(cfg, "user.name", "AAAA") - LibGit2.set!(cfg, "user.email", "BBBB@BBBB.COM") - try - oldhead = LibGit2.head_oid(repo) - LibGit2.branch!(repo, "branch/ff_a") - open(joinpath(LibGit2.path(repo),"ff_file1"),"w") do f - write(f, "111\n") - end - LibGit2.add!(repo, "ff_file1") - LibGit2.commit(repo, "add ff_file1") - - open(joinpath(LibGit2.path(repo),"ff_file2"),"w") do f - write(f, "222\n") - end - LibGit2.add!(repo, "ff_file2") - LibGit2.commit(repo, "add ff_file2") - LibGit2.branch!(repo, "master") - # switch back, now try to ff-merge the changes - # from branch/a - - upst_ann = LibGit2.GitAnnotated(repo, "branch/ff_a") - head_ann = LibGit2.GitAnnotated(repo, "master") - - # ff merge them - @test LibGit2.merge!(repo, [upst_ann], true) - @test LibGit2.is_ancestor_of(string(oldhead), string(LibGit2.head_oid(repo)), repo) - - oldhead = LibGit2.head_oid(repo) - LibGit2.branch!(repo, "branch/ff_b") - open(joinpath(LibGit2.path(repo),"ff_file3"),"w") do f - write(f, "333\n") - end - LibGit2.add!(repo, "ff_file3") - LibGit2.commit(repo, "add ff_file3") - - open(joinpath(LibGit2.path(repo),"ff_file4"),"w") do f - write(f, "444\n") - end - LibGit2.add!(repo, "ff_file4") - LibGit2.commit(repo, "add ff_file4") - branchhead = LibGit2.head_oid(repo) - LibGit2.branch!(repo, "master") - # switch back, now try to ff-merge the changes - # from branch/a using committish - @test LibGit2.merge!(repo, committish=string(branchhead)) - @test LibGit2.is_ancestor_of(string(oldhead), string(LibGit2.head_oid(repo)), repo) - - oldhead = LibGit2.head_oid(repo) - LibGit2.branch!(repo, "branch/ff_c") - open(joinpath(LibGit2.path(repo),"ff_file5"),"w") do f - write(f, "555\n") - end - LibGit2.add!(repo, "ff_file5") - LibGit2.commit(repo, "add ff_file5") - - open(joinpath(LibGit2.path(repo),"ff_file6"),"w") do f - write(f, "666\n") - end - LibGit2.add!(repo, "ff_file6") - LibGit2.commit(repo, "add ff_file6") - branchhead = LibGit2.head_oid(repo) - LibGit2.branch!(repo, "master") - # switch back, now try to ff-merge the changes - # from branch/ff_c using branch name - @test LibGit2.merge!(repo, branch="refs/heads/branch/ff_c") - @test LibGit2.is_ancestor_of(string(oldhead), string(LibGit2.head_oid(repo)), repo) - finally - close(repo) - end - end - - @testset "Merges" begin - path = joinpath(dir, "Example.Merge") - repo = LibGit2.clone(cache_repo, path) - # need to set this for merges to succeed - cfg = LibGit2.GitConfig(repo) - LibGit2.set!(cfg, "user.name", "AAAA") - LibGit2.set!(cfg, "user.email", "BBBB@BBBB.COM") - try - oldhead = LibGit2.head_oid(repo) - LibGit2.branch!(repo, "branch/merge_a") - open(joinpath(LibGit2.path(repo),"file1"),"w") do f - write(f, "111\n") - end - LibGit2.add!(repo, "file1") - LibGit2.commit(repo, "add file1") - - # switch back, add a commit, try to merge - # from branch/merge_a - LibGit2.branch!(repo, "master") - - # test for showing a Reference to a non-HEAD branch - brref = LibGit2.GitReference(repo, "refs/heads/branch/merge_a") - @test LibGit2.name(brref) == "refs/heads/branch/merge_a" - @test !LibGit2.ishead(brref) - show_strs = split(sprint(show, brref), "\n") - @test show_strs[1] == "GitReference:" - @test show_strs[2] == "Branch with name refs/heads/branch/merge_a" - @test show_strs[3] == "Branch is not HEAD." - - open(joinpath(LibGit2.path(repo), "file2"), "w") do f - write(f, "222\n") - end - LibGit2.add!(repo, "file2") - LibGit2.commit(repo, "add file2") - - upst_ann = LibGit2.GitAnnotated(repo, "branch/merge_a") - head_ann = LibGit2.GitAnnotated(repo, "master") - - # (fail to) merge them because we can't fastforward - @test_warn "WARNING: Cannot perform fast-forward merge." !LibGit2.merge!(repo, [upst_ann], true) - # merge them now that we allow non-ff - @test_warn "INFO: Review and commit merged changes." LibGit2.merge!(repo, [upst_ann], false) - @test LibGit2.is_ancestor_of(string(oldhead), string(LibGit2.head_oid(repo)), repo) - - # go back to merge_a and rename a file - LibGit2.branch!(repo, "branch/merge_b") - mv(joinpath(LibGit2.path(repo),"file1"),joinpath(LibGit2.path(repo),"mvfile1")) - LibGit2.add!(repo, "mvfile1") - LibGit2.commit(repo, "move file1") - LibGit2.branch!(repo, "master") - upst_ann = LibGit2.GitAnnotated(repo, "branch/merge_b") - rename_flag = 0 - rename_flag = LibGit2.toggle(rename_flag, 0) # turns on the find renames opt - mos = LibGit2.MergeOptions(flags=rename_flag) - @test_warn "INFO: Review and commit merged changes." LibGit2.merge!(repo, [upst_ann], merge_opts=mos) - finally - close(repo) - end - end - - @testset "push" begin - up_path = joinpath(dir, "Example.PushUp") - up_repo = LibGit2.clone(cache_repo, up_path) - our_path = joinpath(dir, "Example.Push") - our_repo = LibGit2.clone(cache_repo, our_path) - # need to set this for merges to succeed - our_cfg = LibGit2.GitConfig(our_repo) - LibGit2.set!(our_cfg, "user.name", "AAAA") - LibGit2.set!(our_cfg, "user.email", "BBBB@BBBB.COM") - up_cfg = LibGit2.GitConfig(up_repo) - LibGit2.set!(up_cfg, "user.name", "AAAA") - LibGit2.set!(up_cfg, "user.email", "BBBB@BBBB.COM") - try - open(joinpath(LibGit2.path(our_repo),"file1"),"w") do f - write(f, "111\n") - end - LibGit2.add!(our_repo, "file1") - LibGit2.commit(our_repo, "add file1") - if LibGit2.version() >= v"0.26.0" # See #21872, #21639 and #21597 - # we cannot yet locally push to non-bare repos - @test_throws LibGit2.GitError LibGit2.push(our_repo, remoteurl=up_path) - end - finally - close(our_repo) - close(up_repo) - end - end - - @testset "Fetch from cache repository" begin - repo = LibGit2.GitRepo(test_repo) - try - # fetch changes - @test LibGit2.fetch(repo) == 0 - @test !isfile(joinpath(test_repo, test_file)) - - # ff merge them - @test LibGit2.merge!(repo, fastforward=true) - - # because there was not any file we need to reset branch - head_oid = LibGit2.head_oid(repo) - new_head = LibGit2.reset!(repo, head_oid, LibGit2.Consts.RESET_HARD) - @test isfile(joinpath(test_repo, test_file)) - @test new_head == head_oid - - # GitAnnotated for a fetchhead - fh_ann = LibGit2.GitAnnotated(repo, LibGit2.Consts.FETCH_HEAD) - @test LibGit2.GitHash(fh_ann) == head_oid - - # Detach HEAD - no merge - LibGit2.checkout!(repo, string(commit_oid3)) - @test_throws LibGit2.Error.GitError LibGit2.merge!(repo, fastforward=true) - - # Switch to a branch without remote - no merge - LibGit2.branch!(repo, test_branch) - @test_throws LibGit2.Error.GitError LibGit2.merge!(repo, fastforward=true) - - # Set the username and email for the test_repo (needed for rebase) - cfg = LibGit2.GitConfig(repo) - LibGit2.set!(cfg, "user.name", "AAAA") - LibGit2.set!(cfg, "user.email", "BBBB@BBBB.COM") - - # If upstream argument is empty, libgit2 will look for tracking - # information. If the current branch isn't tracking any upstream - # the rebase should fail. - @test_throws LibGit2.GitError LibGit2.rebase!(repo) - # Try rebasing on master instead - newhead = LibGit2.rebase!(repo, master_branch) - @test newhead == head_oid - - # Switch to the master branch - LibGit2.branch!(repo, master_branch) - - fetch_heads = LibGit2.fetchheads(repo) - @test fetch_heads[1].name == "refs/heads/master" - @test fetch_heads[1].ismerge == true # we just merged master - @test fetch_heads[2].name == "refs/heads/test_branch" - @test fetch_heads[2].ismerge == false - @test fetch_heads[3].name == "refs/tags/tag2" - @test fetch_heads[3].ismerge == false - for fh in fetch_heads - @test fh.url == cache_repo - fh_strs = split(sprint(show, fh), '\n') - @test fh_strs[1] == "FetchHead:" - @test fh_strs[2] == "Name: $(fh.name)" - @test fh_strs[3] == "URL: $(fh.url)" - @test fh_strs[5] == "Merged: $(fh.ismerge)" - end - finally - close(repo) - end - end - - @testset "Examine test repository" begin - @testset "files" begin - @test readstring(joinpath(test_repo, test_file)) == readstring(joinpath(cache_repo, test_file)) - end - - @testset "tags & branches" begin - repo = LibGit2.GitRepo(test_repo) - try - # all tag in place - tags = LibGit2.tag_list(repo) - @test length(tags) == 1 - @test tag2 in tags - - # all tag in place - branches = map(b->LibGit2.shortname(b[1]), LibGit2.GitBranchIter(repo)) - @test master_branch in branches - @test test_branch in branches - - # issue #16337 - tag2ref = LibGit2.GitReference(repo, "refs/tags/$tag2") - try - @test_throws LibGit2.Error.GitError LibGit2.upstream(tag2ref) - finally - close(tag2ref) - end - - finally - close(repo) - end - end - - @testset "commits with revwalk" begin - repo = LibGit2.GitRepo(test_repo) - cache = LibGit2.GitRepo(cache_repo) - try - oids = LibGit2.with(LibGit2.GitRevWalker(repo)) do walker - LibGit2.map((oid,repo)->(oid,repo), walker, oid=commit_oid1, by=LibGit2.Consts.SORT_TIME) - end - @test length(oids) == 1 - - test_oids = LibGit2.with(LibGit2.GitRevWalker(repo)) do walker - LibGit2.map((oid,repo)->string(oid), walker, by = LibGit2.Consts.SORT_TIME) - end - cache_oids = LibGit2.with(LibGit2.GitRevWalker(cache)) do walker - LibGit2.map((oid,repo)->string(oid), walker, by = LibGit2.Consts.SORT_TIME) - end - for i in eachindex(oids) - @test cache_oids[i] == test_oids[i] - end - LibGit2.with(LibGit2.GitRevWalker(repo)) do walker - @test count((oid,repo)->(oid == commit_oid1), walker, oid=commit_oid1, by=LibGit2.Consts.SORT_TIME) == 1 - end - finally - close(repo) - close(cache) - end - end - end - - @testset "Modify and reset repository" begin - repo = LibGit2.GitRepo(test_repo) - try - # check index for file - LibGit2.with(LibGit2.GitIndex(repo)) do idx - i = find(test_file, idx) - @test !isnull(i) - idx_entry = idx[get(i)] - @test idx_entry !== nothing - idx_entry_str = sprint(show, idx_entry) - @test idx_entry_str == "IndexEntry($(string(idx_entry.id)))" - @test LibGit2.stage(idx_entry) == 0 - - i = find("zzz", idx) - @test isnull(i) - idx_str = sprint(show, idx) - @test idx_str == "GitIndex:\nRepository: $(LibGit2.repository(idx))\nNumber of elements: 1\n" - - LibGit2.remove!(repo, test_file) - LibGit2.read!(repo) - @test count(idx) == 0 - LibGit2.add!(repo, test_file) - LibGit2.update!(repo, test_file) - @test count(idx) == 1 - end - - # check non-existent file status - st = LibGit2.status(repo, "XYZ") - @test isnull(st) - - # check file status - st = LibGit2.status(repo, test_file) - @test !isnull(st) - @test LibGit2.isset(get(st), LibGit2.Consts.STATUS_CURRENT) - - # modify file - open(joinpath(test_repo, test_file), "a") do io - write(io, 0x41) - end - - # file modified but not staged - st_mod = LibGit2.status(repo, test_file) - @test !LibGit2.isset(get(st_mod), LibGit2.Consts.STATUS_INDEX_MODIFIED) - @test LibGit2.isset(get(st_mod), LibGit2.Consts.STATUS_WT_MODIFIED) - - # stage file - LibGit2.add!(repo, test_file) - - # modified file staged - st_stg = LibGit2.status(repo, test_file) - @test LibGit2.isset(get(st_stg), LibGit2.Consts.STATUS_INDEX_MODIFIED) - @test !LibGit2.isset(get(st_stg), LibGit2.Consts.STATUS_WT_MODIFIED) - - # try to unstage to unknown commit - @test_throws LibGit2.Error.GitError LibGit2.reset!(repo, "XYZ", test_file) - - # status should not change - st_new = LibGit2.status(repo, test_file) - @test get(st_new) == get(st_stg) - - # try to unstage to HEAD - new_head = LibGit2.reset!(repo, LibGit2.Consts.HEAD_FILE, test_file) - st_uns = LibGit2.status(repo, test_file) - @test get(st_uns) == get(st_mod) - - # reset repo - @test_throws LibGit2.Error.GitError LibGit2.reset!(repo, LibGit2.GitHash(), LibGit2.Consts.RESET_HARD) - - new_head = LibGit2.reset!(repo, LibGit2.head_oid(repo), LibGit2.Consts.RESET_HARD) - open(joinpath(test_repo, test_file), "r") do io - @test read(io)[end] != 0x41 - end - finally - close(repo) - end - end - - @testset "rebase" begin - repo = LibGit2.GitRepo(test_repo) - try - LibGit2.branch!(repo, "branch/a") - - oldhead = LibGit2.head_oid(repo) - open(joinpath(LibGit2.path(repo),"file1"),"w") do f - write(f, "111\n") - end - LibGit2.add!(repo, "file1") - LibGit2.commit(repo, "add file1") - - open(joinpath(LibGit2.path(repo),"file2"),"w") do f - write(f, "222\n") - end - LibGit2.add!(repo, "file2") - LibGit2.commit(repo, "add file2") - - LibGit2.branch!(repo, "branch/b") - - # squash last 2 commits - new_head = LibGit2.reset!(repo, oldhead, LibGit2.Consts.RESET_SOFT) - @test new_head == oldhead - LibGit2.commit(repo, "squash file1 and file2") - - # add another file - open(joinpath(LibGit2.path(repo),"file3"),"w") do f - write(f, "333\n") - end - LibGit2.add!(repo, "file3") - LibGit2.commit(repo, "add file3") - - newhead = LibGit2.head_oid(repo) - - files = LibGit2.diff_files(repo, "branch/a", "branch/b", filter=Set([LibGit2.Consts.DELTA_ADDED])) - @test files == ["file3"] - files = LibGit2.diff_files(repo, "branch/a", "branch/b", filter=Set([LibGit2.Consts.DELTA_MODIFIED])) - @test files == [] - # switch back and rebase - LibGit2.branch!(repo, "branch/a") - newnewhead = LibGit2.rebase!(repo, "branch/b") - - # issue #19624 - @test newnewhead == newhead - - # add yet another file - open(joinpath(LibGit2.path(repo),"file4"),"w") do f - write(f, "444\n") - end - LibGit2.add!(repo, "file4") - LibGit2.commit(repo, "add file4") - - # rebase with onto - newhead = LibGit2.rebase!(repo, "branch/a", "master") - - newerhead = LibGit2.head_oid(repo) - @test newerhead == newhead - - # add yet more files - open(joinpath(LibGit2.path(repo),"file5"),"w") do f - write(f, "555\n") - end - LibGit2.add!(repo, "file5") - LibGit2.commit(repo, "add file5") - open(joinpath(LibGit2.path(repo),"file6"),"w") do f - write(f, "666\n") - end - LibGit2.add!(repo, "file6") - LibGit2.commit(repo, "add file6") - - pre_abort_head = LibGit2.head_oid(repo) - # Rebase type - head_ann = LibGit2.GitAnnotated(repo, "branch/a") - upst_ann = LibGit2.GitAnnotated(repo, "master") - rb = LibGit2.GitRebase(repo, head_ann, upst_ann) - @test_throws BoundsError rb[3] - @test_throws BoundsError rb[0] - rbo = next(rb) - rbo_str = sprint(show, rbo) - @test rbo_str == "RebaseOperation($(string(rbo.id)))\nOperation type: REBASE_OPERATION_PICK\n" - rb_str = sprint(show, rb) - @test rb_str == "GitRebase:\nNumber: 2\nCurrently performing operation: 1\n" - rbo = rb[2] - rbo_str = sprint(show, rbo) - @test rbo_str == "RebaseOperation($(string(rbo.id)))\nOperation type: REBASE_OPERATION_PICK\n" - - # test rebase abort - LibGit2.abort(rb) - @test LibGit2.head_oid(repo) == pre_abort_head - finally - close(repo) - end - end - - @testset "merge" begin - path = joinpath(dir, "Example.simple_merge") - repo = LibGit2.clone(cache_repo, path) - cfg = LibGit2.GitConfig(repo) - LibGit2.set!(cfg, "user.name", "AAAA") - LibGit2.set!(cfg, "user.email", "BBBB@BBBB.COM") - try - LibGit2.branch!(repo, "branch/merge_a") - - a_head = LibGit2.head_oid(repo) - open(joinpath(LibGit2.path(repo),"merge_file1"),"w") do f - write(f, "111\n") - end - LibGit2.add!(repo, "merge_file1") - LibGit2.commit(repo, "add merge_file1") - LibGit2.branch!(repo, "master") - a_head_ann = LibGit2.GitAnnotated(repo, "branch/merge_a") - @test_warn "INFO: Review and commit merged changes." LibGit2.merge!(repo, [a_head_ann]) #merge returns true if successful - finally - close(repo) - end - end - - @testset "Transact test repository" begin - repo = LibGit2.GitRepo(test_repo) - try - cp(joinpath(test_repo, test_file), joinpath(test_repo, "CCC")) - cp(joinpath(test_repo, test_file), joinpath(test_repo, "AAA")) - LibGit2.add!(repo, "AAA") - @test_throws ErrorException LibGit2.transact(repo) do trepo - mv(joinpath(test_repo, test_file), joinpath(test_repo, "BBB")) - LibGit2.add!(trepo, "BBB") - oid = LibGit2.commit(trepo, "test commit"; author=test_sig, committer=test_sig) - error("Force recovery") - end - @test isfile(joinpath(test_repo, "AAA")) - @test isfile(joinpath(test_repo, "CCC")) - @test !isfile(joinpath(test_repo, "BBB")) - @test isfile(joinpath(test_repo, test_file)) - finally - close(repo) - end - end - - @testset "checkout/headname" begin - repo = LibGit2.GitRepo(cache_repo) - try - LibGit2.checkout!(repo, string(commit_oid1)) - @test !LibGit2.isattached(repo) - @test LibGit2.headname(repo) == "(detached from $(string(commit_oid1)[1:7]))" - finally - close(repo) - end - end - - - if is_unix() - @testset "checkout/proptest" begin - repo = LibGit2.GitRepo(test_repo) - try - cp(joinpath(test_repo, test_file), joinpath(test_repo, "proptest")) - LibGit2.add!(repo, "proptest") - id1 = LibGit2.commit(repo, "test property change 1") - # change in file permissions (#17610) - chmod(joinpath(test_repo, "proptest"),0o744) - LibGit2.add!(repo, "proptest") - id2 = LibGit2.commit(repo, "test property change 2") - LibGit2.checkout!(repo, string(id1)) - @test !LibGit2.isdirty(repo) - # change file to symlink (#18420) - mv(joinpath(test_repo, "proptest"), joinpath(test_repo, "proptest2")) - symlink(joinpath(test_repo, "proptest2"), joinpath(test_repo, "proptest")) - LibGit2.add!(repo, "proptest", "proptest2") - id3 = LibGit2.commit(repo, "test symlink change") - LibGit2.checkout!(repo, string(id1)) - @test !LibGit2.isdirty(repo) - finally - close(repo) - end - end - end - - - @testset "Credentials" begin - creds_user = "USER" - creds_pass = "PASS" - creds = LibGit2.UserPasswordCredentials(creds_user, creds_pass) - @test !LibGit2.checkused!(creds) - @test !LibGit2.checkused!(creds) - @test !LibGit2.checkused!(creds) - @test LibGit2.checkused!(creds) - @test creds.user == creds_user - @test creds.pass == creds_pass - sshcreds = LibGit2.SSHCredentials(creds_user, creds_pass) - @test sshcreds.user == creds_user - @test sshcreds.pass == creds_pass - @test isempty(sshcreds.prvkey) - @test isempty(sshcreds.pubkey) - end - - # The following tests require that we can fake a TTY so that we can provide passwords - # which use the `getpass` function. At the moment we can only fake this on UNIX based - # systems. - if is_unix() - @testset "SSH credential prompt" begin - url = "git@github.com/test/package.jl" - - key_dir = joinpath(dirname(@__FILE__), "libgit2") - valid_key = joinpath(key_dir, "valid") - invalid_key = joinpath(key_dir, "invalid") - valid_p_key = joinpath(key_dir, "valid-passphrase") - passphrase = "secret" - - ssh_cmd = """ - include("$LIBGIT2_HELPER_PATH") - valid_cred = LibGit2.SSHCredentials("git", "", "$valid_key", "$valid_key.pub") - err, auth_attempts = credential_loop(valid_cred, "$url", "git") - (err < 0 ? LibGit2.GitError(err) : err, auth_attempts) - """ - - ssh_p_cmd = """ - include("$LIBGIT2_HELPER_PATH") - valid_cred = LibGit2.SSHCredentials("git", "$passphrase", "$valid_p_key", "$valid_p_key.pub") - err, auth_attempts = credential_loop(valid_cred, "$url", "git") - (err < 0 ? LibGit2.GitError(err) : err, auth_attempts) - """ - - # Note: We cannot use the default ~/.ssh/id_rsa for tests since we cannot be - # sure a users will actually have these files. Instead we will use the ENV - # variables to set the default values. - - # Default credentials are valid - withenv("SSH_KEY_PATH" => valid_key) do - err, auth_attempts = challenge_prompt(ssh_cmd, []) - @test err == 0 - @test auth_attempts == 1 - end - - # Default credentials are valid but requires a passphrase - withenv("SSH_KEY_PATH" => valid_p_key) do - challenges = [ - "Passphrase for $valid_p_key:" => "$passphrase\n", - ] - err, auth_attempts = challenge_prompt(ssh_p_cmd, challenges) - @test err == 0 - @test auth_attempts == 1 - - # User mistypes passphrase. - # Note: In reality LibGit2 will raise an error upon using the invalid SSH - # credentials. Since we don't control the internals of LibGit2 though they - # could also just re-call the credential callback like they do for HTTP. - challenges = [ - "Passphrase for $valid_p_key:" => "foo\n", - # "Private key location for 'git@github.com' [$valid_p_key]:" => "\n", - "Passphrase for $valid_p_key:" => "$passphrase\n", - ] - err, auth_attempts = challenge_prompt(ssh_p_cmd, challenges) - @test err == 0 - @test auth_attempts == 5 - end - - withenv("SSH_KEY_PATH" => valid_p_key, "SSH_KEY_PASS" => passphrase) do - err, auth_attempts = challenge_prompt(ssh_p_cmd, []) - @test err == 0 - @test auth_attempts == 1 - end - - # TODO: Tests are currently broken. Credential callback prompts for: - # "Passphrase for :" - #= - # Explicitly setting these env variables to be empty means the user will be - # given a prompt with no defaults set. - withenv("SSH_KEY_PATH" => "", "SSH_PUB_KEY_PATH" => "") do - # User provides valid credentials - challenges = [ - "Private key location for 'git@github.com':" => "$valid_key\n", - ] - err, auth_attempts = challenge_prompt(ssh_cmd, challenges) - @test err == 0 - @test auth_attempts == 2 - - # User provides valid credentials that requires a passphrase - challenges = [ - "Private key location for 'git@github.com':" => "$valid_p_key\n", - "Passphrase for $valid_p_key:" => "$passphrase\n", - ] - err, auth_attempts = challenge_prompt(ssh_p_cmd, challenges) - @test err == 0 - @test auth_attempts == 2 - end - =# - - # TODO: Tests are currently broken. Credential callback currently infinite loops - # and never prompts user to change private keys. - #= - # Explicitly setting these env variables to an existing but invalid key pair - # means the user will be given a prompt with that defaults to the given values. - withenv("SSH_KEY_PATH" => invalid_key, "SSH_PUB_KEY_PATH" => invalid_key * ".pub") do - challenges = [ - "Private key location for 'git@github.com' [$invalid_key]:" => "$valid_key\n", - ] - err, auth_attempts = challenge_prompt(ssh_cmd, challenges) - @test err == 0 - @test auth_attempts == 2 - end - =# - - # TODO: Tests are currently broken. Credential callback currently infinite loops - # and never prompts user to change private keys. - #= - withenv("SSH_KEY_PATH" => valid_key, "SSH_PUB_KEY_PATH" => valid_key * ".public") do - @test !isfile(ENV["SSH_PUB_KEY_PATH"]) - - # User explicitly sets the SSH_PUB_KEY_PATH incorrectly. - challenges = [ - "Private key location for 'git@github.com' [$valid_key]:" => "\n" - "Public key location for 'git@github.com':" => "$valid_key.pub\n" - ] - err, auth_attempts = challenge_prompt(ssh_cmd, challenges) - @test err == 0 - @test auth_attempts == 2 - end - =# - end - - @testset "HTTPS credential prompt" begin - url = "https://github.com/test/package.jl" - - valid_username = "julia" - valid_password = randstring(16) - - https_cmd = """ - include("$LIBGIT2_HELPER_PATH") - valid_cred = LibGit2.UserPasswordCredentials("$valid_username", "$valid_password") - err, auth_attempts = credential_loop(valid_cred, "$url") - (err < 0 ? LibGit2.GitError(err) : err, auth_attempts) - """ - - # User provides a valid username and password - challenges = [ - "Username for 'https://github.com':" => "$valid_username\n", - "Password for 'https://$valid_username@github.com':" => "$valid_password\n", - ] - err, auth_attempts = challenge_prompt(https_cmd, challenges) - @test err == 0 - @test auth_attempts == 1 - - # User repeatedly chooses invalid username/password until the prompt limit is - # reached - challenges = [ - "Username for 'https://github.com':" => "foo\n", - "Password for 'https://foo@github.com':" => "bar\n", - "Username for 'https://github.com' [foo]:" => "$valid_username\n", - "Password for 'https://$valid_username@github.com':" => "$valid_password\n", - ] - err, auth_attempts = challenge_prompt(https_cmd, challenges) - @test err == 0 - @test auth_attempts == 5 - end - end - - #= temporarily disabled until working on the buildbots, ref https://github.com/JuliaLang/julia/pull/17651#issuecomment-238211150 - @testset "SSH" begin - sshd_command = "" - ssh_repo = joinpath(dir, "Example.SSH") - if !is_windows() - try - # SSHD needs to be executed by its full absolute path - sshd_command = strip(readstring(`which sshd`)) - catch - warn("Skipping SSH tests (Are `which` and `sshd` installed?)") - end - end - if !isempty(sshd_command) - mktempdir() do fakehomedir - mkdir(joinpath(fakehomedir,".ssh")) - # Unsetting the SSH agent serves two purposes. First, we make - # sure that we don't accidentally pick up an existing agent, - # and second we test that we fall back to using a key file - # if the agent isn't present. - withenv("HOME"=>fakehomedir,"SSH_AUTH_SOCK"=>nothing) do - # Generate user file, first an unencrypted one - wait(spawn(`ssh-keygen -N "" -C juliatest@localhost -f $fakehomedir/.ssh/id_rsa`)) - - # Generate host keys - wait(spawn(`ssh-keygen -f $fakehomedir/ssh_host_rsa_key -N '' -t rsa`)) - wait(spawn(`ssh-keygen -f $fakehomedir/ssh_host_dsa_key -N '' -t dsa`)) - - our_ssh_port = rand(13000:14000) # Chosen arbitrarily - - key_option = "AuthorizedKeysFile $fakehomedir/.ssh/id_rsa.pub" - pidfile_option = "PidFile $fakehomedir/sshd.pid" - sshp = agentp = nothing - logfile = tempname() - ssh_debug = false - function spawn_sshd() - debug_flags = ssh_debug ? `-d -d` : `` - _p = open(logfile, "a") do logfilestream - spawn(pipeline(pipeline(`$sshd_command - -e -f /dev/null $debug_flags - -h $fakehomedir/ssh_host_rsa_key - -h $fakehomedir/ssh_host_dsa_key -p $our_ssh_port - -o $pidfile_option - -o 'Protocol 2' - -o $key_option - -o 'UsePrivilegeSeparation no' - -o 'StrictModes no'`,STDOUT),stderr=logfilestream)) - end - # Give the SSH server 5 seconds to start up - yield(); sleep(5) - _p - end - sshp = spawn_sshd() - - TIOCSCTTY_str = "ccall(:ioctl, Void, (Cint, Cint, Int64), 0, - (is_bsd() || is_apple()) ? 0x20007461 : is_linux() ? 0x540E : - error(\"Fill in TIOCSCTTY for this OS here\"), 0)" - - # To fail rather than hang - function killer_task(p, master) - @async begin - sleep(10) - kill(p) - if isopen(master) - nb_available(master) > 0 && - write(logfile, - readavailable(master)) - close(master) - end - end - end - - try - function try_clone(challenges = []) - cmd = """ - repo = nothing - try - $TIOCSCTTY_str - reponame = "ssh://$(ENV["USER"])@localhost:$our_ssh_port$cache_repo" - repo = LibGit2.clone(reponame, "$ssh_repo") - catch err - open("$logfile","a") do f - println(f,"HOME: ",ENV["HOME"]) - println(f, err) - end - finally - close(repo) - end - """ - # We try to be helpful by desperately looking for - # a way to prompt the password interactively. Pretend - # to be a TTY to suppress those shenanigans. Further, we - # need to detach and change the controlling terminal with - # TIOCSCTTY, since getpass opens the controlling terminal - TestHelpers.with_fake_pty() do slave, master - err = Base.Pipe() - let p = spawn(detach( - `$(Base.julia_cmd()) --startup-file=no -e $cmd`),slave,slave,STDERR) - killer_task(p, master) - for (challenge, response) in challenges - readuntil(master, challenge) - sleep(1) - print(master, response) - end - sleep(2) - wait(p) - close(master) - end - end - @test isfile(joinpath(ssh_repo,"testfile")) - rm(ssh_repo, recursive = true) - end - - # Should use the default files, no interaction required. - try_clone() - ssh_debug && (kill(sshp); sshp = spawn_sshd()) - - # Ok, now encrypt the file and test with that (this also - # makes sure that we don't accidentally fall back to the - # unencrypted version) - wait(spawn(`ssh-keygen -p -N "xxxxx" -f $fakehomedir/.ssh/id_rsa`)) - - # Try with the encrypted file. Needs a password. - try_clone(["Passphrase"=>"xxxxx\r\n"]) - ssh_debug && (kill(sshp); sshp = spawn_sshd()) - - # Move the file. It should now ask for the location and - # then the passphrase - mv("$fakehomedir/.ssh/id_rsa","$fakehomedir/.ssh/id_rsa2") - cp("$fakehomedir/.ssh/id_rsa.pub","$fakehomedir/.ssh/id_rsa2.pub") - try_clone(["location"=>"$fakehomedir/.ssh/id_rsa2\n", - "Passphrase"=>"xxxxx\n"]) - mv("$fakehomedir/.ssh/id_rsa2","$fakehomedir/.ssh/id_rsa") - rm("$fakehomedir/.ssh/id_rsa2.pub") - - # Ok, now start an agent - agent_sock = tempname() - agentp = spawn(`ssh-agent -a $agent_sock -d`) - while stat(agent_sock).mode == 0 # Wait until the agent is started - sleep(1) - end - - # fake pty is required for the same reason as in try_clone - # above - withenv("SSH_AUTH_SOCK" => agent_sock) do - TestHelpers.with_fake_pty() do slave, master - cmd = """ - $TIOCSCTTY_str - run(pipeline(`ssh-add $fakehomedir/.ssh/id_rsa`, - stderr = DevNull)) - """ - addp = spawn(detach(`$(Base.julia_cmd()) --startup-file=no -e $cmd`), - slave, slave, STDERR) - killer_task(addp, master) - sleep(2) - write(master, "xxxxx\n") - wait(addp) - end - - # Should now use the agent - try_clone() - end - catch err - println("SSHD logfile contents follows:") - println(readstring(logfile)) - rethrow(err) - finally - rm(logfile) - sshp !== nothing && kill(sshp) - agentp !== nothing && kill(agentp) - end - end - end - end - end - =# - - # Note: Tests only work on linux as SSL_CERT_FILE is only respected on linux systems. - @testset "Hostname verification" begin - openssl_installed = false - common_name = "" - if is_linux() - try - # OpenSSL needs to be on the path - openssl_installed = !isempty(readstring(`openssl version`)) - catch - warn("Skipping hostname verification tests. Is `openssl` on the path?") - end - - # Find a hostname that maps to the loopback address - hostnames = ["localhost"] - - # In minimal environments a hostname might not be available (issue #20758) - try - # In some environments, namely Macs, the hostname "macbook.local" is bound - # to the external address while "macbook" is bound to the loopback address. - unshift!(hostnames, replace(gethostname(), r"\..*$", "")) - end - - loopback = ip"127.0.0.1" - for hostname in hostnames - local addr - try - addr = getaddrinfo(hostname) - catch - continue - end - - if addr == loopback - common_name = hostname - break - end - end - - if isempty(common_name) - warn("Skipping hostname verification tests. Unable to determine a hostname which maps to the loopback address") - end - end - if openssl_installed && !isempty(common_name) - mktempdir() do root - key = joinpath(root, common_name * ".key") - cert = joinpath(root, common_name * ".crt") - pem = joinpath(root, common_name * ".pem") - - # Generated a certificate which has the CN set correctly but no subjectAltName - run(pipeline(`openssl req -new -x509 -newkey rsa:2048 -nodes -keyout $key -out $cert -days 1 -subj "/CN=$common_name"`, stderr=DevNull)) - run(`openssl x509 -in $cert -out $pem -outform PEM`) - - # Make a fake Julia package and minimal HTTPS server with our generated - # certificate. The minimal server can't actually serve a Git repository. - mkdir(joinpath(root, "Example.jl")) - pobj = cd(root) do - spawn(`openssl s_server -key $key -cert $cert -WWW`) - end - - errfile = joinpath(root, "error") - repo_url = "https://$common_name:4433/Example.jl" - repo_dir = joinpath(root, "dest") - code = """ - dest_dir = "$repo_dir" - open("$errfile", "w+") do f - try - repo = LibGit2.clone("$repo_url", dest_dir) - catch err - serialize(f, err) - finally - isdir(dest_dir) && rm(dest_dir, recursive=true) - end - end - """ - cmd = `$(Base.julia_cmd()) --startup-file=no -e $code` - - try - # The generated certificate is normally invalid - run(cmd) - err = open(errfile, "r") do f - deserialize(f) - end - @test err.code == LibGit2.Error.ECERTIFICATE - - rm(errfile) - - # Specify that Julia use only the custom certificate. Note: we need to - # spawn a new Julia process in order for this ENV variable to take effect. - withenv("SSL_CERT_FILE" => pem) do - run(cmd) - err = open(errfile, "r") do f - deserialize(f) - end - @test err.code == LibGit2.Error.ERROR - @test err.msg == "Invalid Content-Type: text/plain" - end - finally - kill(pobj) - end - end - end - end -end diff --git a/julia-0.6.3/share/julia/test/libgit2/invalid b/julia-0.6.3/share/julia/test/libgit2/invalid deleted file mode 100644 index 7fa5389..0000000 --- a/julia-0.6.3/share/julia/test/libgit2/invalid +++ /dev/null @@ -1,27 +0,0 @@ ------BEGIN RSA PRIVATE KEY----- -MIIEowIBAAKCAQEAs1L+Z8s5GdtzLXGM3+4UVQ7jc5q/uNPzQgGUl+nC+o2VFuHm -omkAIxxrS3zkVT0A4AnkrVq/H2l2AOlxKudFan4o87AJQsTHkj9LvFBhm+bBdHau -0SGSft8cCWAXv5lifFChYaxT78Y3QnSO4Q7AVEXQVAmGFiu3CgBKq7c1srQt8V4n -dH8PuMYdIiYuNG8HNAnErGjApdNHmosY63jybkRmTffvhuS/Df1FKLYY60QYThKM -50P+8HHX1jvH+JI5bWLyDhG97E8Vmh9bpgvHhdZ52WBVaf5i6qmYB2FBHHfb8Yuh -/EB39RQjPLEI9K5HP5LkBXAWxozv75qmKF7AiQIDAQABAoIBAFF1H89yRyvxva4k -6INIGMBSlQuMfg6taNDQ+vjO3R0Hd3P/hc68t607WZnez7HQljcvB0uf7zWLqGjd -oeSFTckEKgIYMvy7epR6YCLYuJ4jAjmvN9YT1AIBwzCXD/Ke8FfcIJLHvxEqDywG -2mhtVPxzAiFKejhT/z9xxnmeLaxQ3eE77XrFJiJR0M+fc6B2zyN8eVR/jdpoVFOw -Jb6TkzxDY1OWVY72EMf+7JBzpnNVqe36T0aJapF1c4qeqC+bklYtgnJ1GfohzbKU -ij8SF1yH1y+LX0qq67DLfxmm1qNMgBNhLC8eYm9yfAWkRi4eX9c7U2X/61S3Sm9a -CMGb8QECgYEA2x9d5uCeVdg595NutArea7sHVuJViF8kWYBwYgkAFgdEtjGhoEXX -YMa+11HQ+yUX4WfrLhcQm/eiSdaqKEcE0g/tz6ytuFCZvPHPZe2p2QIIHjqKYezc -mtcc95qYm1O3U5iTHsiL73TurdESOl7O1eSK/TgQwoes6cuELqZ5GBkCgYEA0YD2 -lJ7uW1MBCQwTENbe4ZapvwtEXsRIVad0dg6kzgaYgBWDIuNS0XBnB6sbD3B0TL6G -vhpfO7wMV8VQ1H2h0aMLSgpevPxHrD0uQsXhZ0cM8hzhAKmbAscBdQXv6MnXzr37 -8FL3nHyYc9qvk7qNcMqa1x975s5SlzR5UrA9ufECgYAydOeXiXOMSu0WMFHWjYYo -AnovLJELhPUG0weN24q0h9nvpkAUeuCcfUdmp4Vav3DfS6GhDFibwYsSO6cU/T2D -7X0STC34ej7cfkYGr5Jj0Q7zfwFsiTFHSm92KJgpdD6Ltl9yQDXQ3vky9yieXkR8 -hlLm+ikJ0lojv+RhJZ5OyQKBgQDLlVuIXszXF9jItuAMHBEn/GVlTYiZ4nk8KuaE -FoTV5BjrVnxBOc/v0B9+lypLnYaWUQrUzwG+JWWFISwD4TWPZrYAtAUN9sWbPTSo -FGyOFMAiwidvomEMmN/0nNleSE4bDAk3pxgRDA6FfnvhvYXWljtTUrfvOI2Pe6Ft -1e+VsQKBgFF1wW0E7L7ItpClFifF0tDZdOjfBwiUutusvFSj6RVtIv9s0WiSoc/R -qOc4Jfle2F0cw3Fwp5Qv/qgKItOT0zo4mOJKOzyHfER5UgI7zcIK9dBNuYCRBwwE -lXZzcMoTuRH8GrMdoTUTMyJ5DRC5vqRW422pM4K+ICVIYrZpfpDh ------END RSA PRIVATE KEY----- diff --git a/julia-0.6.3/share/julia/test/libgit2/invalid.pub b/julia-0.6.3/share/julia/test/libgit2/invalid.pub deleted file mode 100644 index d7abfc2..0000000 --- a/julia-0.6.3/share/julia/test/libgit2/invalid.pub +++ /dev/null @@ -1 +0,0 @@ -ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCzUv5nyzkZ23MtcYzf7hRVDuNzmr+40/NCAZSX6cL6jZUW4eaiaQAjHGtLfORVPQDgCeStWr8faXYA6XEq50VqfijzsAlCxMeSP0u8UGGb5sF0dq7RIZJ+3xwJYBe/mWJ8UKFhrFPvxjdCdI7hDsBURdBUCYYWK7cKAEqrtzWytC3xXid0fw+4xh0iJi40bwc0CcSsaMCl00eaixjrePJuRGZN9++G5L8N/UUothjrRBhOEoznQ/7wcdfWO8f4kjltYvIOEb3sTxWaH1umC8eF1nnZYFVp/mLqqZgHYUEcd9vxi6H8QHf1FCM8sQj0rkc/kuQFcBbGjO/vmqYoXsCJ invalid-credentials diff --git a/julia-0.6.3/share/julia/test/libgit2/valid b/julia-0.6.3/share/julia/test/libgit2/valid deleted file mode 100644 index bc6cf6a..0000000 --- a/julia-0.6.3/share/julia/test/libgit2/valid +++ /dev/null @@ -1,27 +0,0 @@ ------BEGIN RSA PRIVATE KEY----- -MIIEowIBAAKCAQEA3oA311O95RTuncUrnHxLu7CUMN9Mh5ZolXct33RoEoAkar7E -oyW2C0AQ+yA7C3PjlC2SmgYbebUC+N/0bFOoibDwFCUmZbOlRTWITYbq7t0f6nk7 -cl4l8BvyMPbRN25ozPyn1SrGc/vHj11LnGXGNZWqCfz5EJ6LfLIlA5P/0814QrRk -ePg/J3RZ3HJj7QlvHvG9uAQQ//WXeFdmRQDKNhZbMc0bibxZGgMQeKL7hoGwGBHT -a5DSWsCWermUC5IYsrC5PAzGcN/KwTbQ0S9U7xVTOuKDSEMv8AzEmkpCtkulVses -x7P47wUKhOOm9OFikVEC2s0uoRvNfUDUSzjFLQIDAQABAoIBACgKhwIXLetV8wMt -goWs0Kw8QM7ywID+DmAnjHfUKQ57RRJ4tkZt+O7ZXrTyve13s5LtCJ7zTmp+qsRC -+WetPn1Y/DuD2/8dbzafRaI+D3VhEedOXeZdDxLA1Lr/D/ObyPxq04FHK2OgAe/I -6FyC7EKkZm9ZuTDGd2+/V23nanihAXJ8ILk02cKxNjpq4gxt0i0Zm3CjVEYlrywm -fBov7sbLWwu2ovISdRBziJAs8wsGPKTcbOCREtHe2BP7bfiAcf9UEatdH7C1kO8U -gdCluvH2RMwy00NunthrKEy7CmdOh/lfV7p6VYbH3/ikq+XkhntE8SEJzafLuIUl -mbglGsECgYEA+SflaLun2WqqsUlrVH3mN7lUbYpHhs72zOa7NcvRzBqEeYhhFyoQ -WvQzJlzfIZ+I/JqgHjsGeJx8cHpxI7zwd7n45nc9ycU9yc5UHsAGcyQwrTpVMIEn -gHL6Ybe2vN7CIazPGnmiwaCD25/Kp5eBXmc8Syckt12GMDIwMuozwbkCgYEA5Jzh -O8lZMGTmoz4iGIWr0g21ySmNX+toKq+zto7jhZSZcEpFGxARP4GdiN9CafGJRRz1 -r4ZHruWazLpxozsWRAgVnWJrgee7JZ4oWi0geAw+wUxQYny+/rx0AQl81lHwPhOm -f8WfTZifKhu9QaR5fa3DAfrgc8Gfay1TP7UtaRUCgYEAqFeEcRcZeZTQb6ijlBrc -iZn2qWxcl4EOz7K1mstznOvtxg+XSgdptYp5ZNorCJS6AbKXrNVEsglJKtYPy43F -C5/jxBOc888IyGlX/M7RjMpO+TwIgxVAk1EcSxnNph78G7Se2cyFYz4I2UNFsaZ0 -CkzGOCDideIC4F2Io14KSkECgYBhRzw0Q45XIGhfyD2b761YWYskCTFmQnZ1y4QO -R6kbG0tbU88qH+EnA9Fz/4R0Llo59YO558qy6nK/cQqP6cGku0fvS4TxpxikfjMv -hApP6u39NKrz7Z8cKDa4hj//tqgi0hvEPOR3kV0Q/vK+bu1fhEP5oLZHq3lZktTc -xAyJrQKBgClH3j759U82D2bUXVanDqs7S0Zef91u11kYDFrnX4kUWlG0DZCB7e5P -yBUWd/ZoXULBkoCfbwO8PGGxFYRmXzYQvVnSGiAP09dHFodvMm7hP8VueoRbAbEL -/UKMQOhYhEpcENylUjaaLUzxaYzwqeT/dcu+Edd7sCKk0J/1beA/ ------END RSA PRIVATE KEY----- diff --git a/julia-0.6.3/share/julia/test/libgit2/valid-passphrase b/julia-0.6.3/share/julia/test/libgit2/valid-passphrase deleted file mode 100644 index 169fef6..0000000 --- a/julia-0.6.3/share/julia/test/libgit2/valid-passphrase +++ /dev/null @@ -1,30 +0,0 @@ ------BEGIN RSA PRIVATE KEY----- -Proc-Type: 4,ENCRYPTED -DEK-Info: AES-128-CBC,EC9D334AA2ECD3E7A9DCBD7BDFB5CABC - -J9EWrlaxABoCAeow7k8oteiGorPKpZMVQBmIomx91kpfncVBC/WDbRa2HbmVkkYh -kgFbpDmzD6cMuu1sAbOROcCBFLqtKsXwHj4nynW8PTJRNSG9GazY9tmQ/OzAV9Ng -ZELXVncyexKEG7WDlXuArqd2KwbopNe6SetW4OYZy6t7QBNp6c4wwyRwuCYwGjMg -3rAugZvMPv7Ytr4DCluKp+/S5P81LKPpGDYdGSD3wMQtEzB/81DPsp+BP2r0rqPA -9Wa49c5aOcLdDaG8tVlogAQEwn4Mt/GI3U5b2Q14/YUy41AD4ZuYLl+3iv+18PsM -6Kqs0QmD6FM6hDg82+FYh5fbvJqoHjAFqieljWFdm0oLpuz7p3q3MMfAkhl5Xrvq -bCLQenFww8IxgyIMUGYRtq5kGKm+rXbKg/vQV/jxyLCdQZoZXO6F07gwUKX2YM1K -H1j9DbexbtJXoAtXP7nP0qo2WJjhGnDvcqxuBRrJFW7Z/T8r0pqetYSUFuIiS7Nt -ftT60QPziRB1G9nwR7TiWhOfl1VQlrRxXompfK+We3+njp96Yuqdw9mOZ3slEz40 -LlTlPqmC8Fp1rm+M5qtjotlYGJLUcFOpbwKzt0knl+gYPg7qCSVcjoQ0E6WrciyH -3t8+pRtguICjV2Jfq+MFnzfJujNSBIxYro/oQ+dl3b2s9eeks6SVloCmuaGj45hN -Y3wrfMe+4dv+wy9JuYzHualBpPk8GCxDNHqXkd7nTjDPY9uCW2xqjP8HBq+GNj0Q -XLSyZ95iPJwxcAigXa8g3+jMg/IUddIF7tNQbHLZR1h+4nP2HB7Fo0GQM9dOGNzU -r+LGBeIJTmFite0jSFDjRHDo/GunV7/A21ZSykt8aMAQYlEQg2eKAdfzDYK5JTXw -dFn5YURKGpmlyRWc91Dvg6uF28KAwcMBogRK/3EiEyZushndHqtE1Rqtq+Afi1Ld -GBgIk2dgD+TCqxtmTcPO+ZQN4Tm1rRM5j+b4VehCTQTxeqC+YMfiwZZvW8xQj5Ja -DMG/A+0M8PZtjr+QygGXGmtWxx0dn/ez0sLO6om11U7OmYXJGEp6KqNKnlZZiv3t -wY7wJ/IS5DhWhZ+ttsq3z+0XKCiP/06IhNmT6Aq0CUaYuXmbtx7hdnhGA92Jbn8X -pwF8GkDdPA/nqmRiwwJSI2jAMs5EGtYCbcn4QlpCZu9x+m3/YTCGqByQN3VLRtrd -u3UlYH1dT+EAsnG6fxXzj1MdSmT5RRadbEOW6Z3Ykfw47Ft6FKEC+WX0ZC5bBrpC -8a9f/knEbAd5NHEgEuhHHZ+8yv0cz/SHdrDS+cygKIEB237Zwx1TIJ0x9wVtns7g -jk7EV9PBFdmw2aD0WBoK16gQYVhGb8sDQ88ps6llxm8iLV4iQSIAeBDURvjx90aA -vIjqC2RzqXsbtueIo1zk41gElDpDYdI9hSMqhyJaShBOcAPPSso3V0VcAylRTjRt -B9NBbLVjajgWjqse6jcNacbhMnFvbqFEWeHLAI3jOog3aXTmkgIDtuSHGjD/r0WA -FpOQrzn5IDkMEamtqaemFxp14MKxRAPMJ8nOPyZzXM1Pz6dARH1d3EKeC1tFMh3j ------END RSA PRIVATE KEY----- diff --git a/julia-0.6.3/share/julia/test/libgit2/valid-passphrase.pub b/julia-0.6.3/share/julia/test/libgit2/valid-passphrase.pub deleted file mode 100644 index 2ed2cd3..0000000 --- a/julia-0.6.3/share/julia/test/libgit2/valid-passphrase.pub +++ /dev/null @@ -1 +0,0 @@ -ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDLsjzj6P2eGJEASR+MqajdDkVzCK5rTnc/BXDzgCA3Zff8uGgHQlXTX++OspluSnPKvaHFuYUWbCDEH2mwHeLWiwXk68T5+3/GqOX9/m2dxEy6TOmLQ4iOPVC5mrBrSFbHTc5J2PPh3q9hwp/p35BwWo5nCUMc+pqq7WEVdgNNziRuFyAtva2vCVDXEZ5+6FJDvysoMndoIQQlVJXHoPp8w+Eb8gOg5kxTYtpNjb7Vjx/Ux70nl26B5JYtpWUTxLHfnzPRcjGrINgtbsbVDC6BJTnSnBttxaZRcON4/pZDpcvLBhOhqBKjkRkxoMvTGeiA7M5cm/G9LWROeCc88I/D valid-credentials-with-passphrase diff --git a/julia-0.6.3/share/julia/test/libgit2/valid.pub b/julia-0.6.3/share/julia/test/libgit2/valid.pub deleted file mode 100644 index 1e53e6c..0000000 --- a/julia-0.6.3/share/julia/test/libgit2/valid.pub +++ /dev/null @@ -1 +0,0 @@ -ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDegDfXU73lFO6dxSucfEu7sJQw30yHlmiVdy3fdGgSgCRqvsSjJbYLQBD7IDsLc+OULZKaBht5tQL43/RsU6iJsPAUJSZls6VFNYhNhuru3R/qeTtyXiXwG/Iw9tE3bmjM/KfVKsZz+8ePXUucZcY1laoJ/PkQnot8siUDk//TzXhCtGR4+D8ndFnccmPtCW8e8b24BBD/9Zd4V2ZFAMo2FlsxzRuJvFkaAxB4ovuGgbAYEdNrkNJawJZ6uZQLkhiysLk8DMZw38rBNtDRL1TvFVM64oNIQy/wDMSaSkK2S6VWx6zHs/jvBQqE46b04WKRUQLazS6hG819QNRLOMUt valid-credentials diff --git a/julia-0.6.3/share/julia/test/linalg/arnoldi.jl b/julia-0.6.3/share/julia/test/linalg/arnoldi.jl deleted file mode 100644 index 6f895a1..0000000 --- a/julia-0.6.3/share/julia/test/linalg/arnoldi.jl +++ /dev/null @@ -1,247 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -using Base.Test - -@testset "eigs" begin - let - srand(1234) - local n,a,asym,b,bsym,d,v - n = 10 - areal = sprandn(n,n,0.4) - breal = sprandn(n,n,0.4) - acmplx = complex.(sprandn(n,n,0.4), sprandn(n,n,0.4)) - bcmplx = complex.(sprandn(n,n,0.4), sprandn(n,n,0.4)) - - testtol = 1e-6 - - @testset for elty in (Float64, Complex128) - if elty == Complex64 || elty == Complex128 - a = acmplx - b = bcmplx - else - a = areal - b = breal - end - a = convert(SparseMatrixCSC{elty}, a) - asym = a' + a # symmetric indefinite - apd = a'*a # symmetric positive-definite - - b = convert(SparseMatrixCSC{elty}, b) - bsym = b' + b - bpd = b'*b - - (d,v) = eigs(a, nev=3) - @test a*v[:,2] ≈ d[2]*v[:,2] - @test norm(v) > testtol # eigenvectors cannot be null vectors - # (d,v) = eigs(a, b, nev=3, tol=1e-8) # not handled yet - # @test a*v[:,2] ≈ d[2]*b*v[:,2] atol=testtol - # @test norm(v) > testtol # eigenvectors cannot be null vectors - - (d,v) = eigs(asym, nev=3) - @test asym*v[:,1] ≈ d[1]*v[:,1] - @test eigs(asym; nev=1, sigma=d[3])[1][1] ≈ d[3] - @test norm(v) > testtol # eigenvectors cannot be null vectors - - (d,v) = eigs(apd, nev=3) - @test apd*v[:,3] ≈ d[3]*v[:,3] - @test eigs(apd; nev=1, sigma=d[3])[1][1] ≈ d[3] - - (d,v) = eigs(apd, bpd, nev=3, tol=1e-8) - @test apd*v[:,2] ≈ d[2]*bpd*v[:,2] atol=testtol - @test norm(v) > testtol # eigenvectors cannot be null vectors - - @testset "(shift-and-)invert mode" begin - (d,v) = eigs(apd, nev=3, sigma=0) - @test apd*v[:,3] ≈ d[3]*v[:,3] - @test norm(v) > testtol # eigenvectors cannot be null vectors - - (d,v) = eigs(apd, bpd, nev=3, sigma=0, tol=1e-8) - @test apd*v[:,1] ≈ d[1]*bpd*v[:,1] atol=testtol - @test norm(v) > testtol # eigenvectors cannot be null vectors - end - - @testset "ArgumentErrors" begin - @test_throws ArgumentError eigs(rand(elty,2,2)) - @test_throws ArgumentError eigs(a, nev=-1) - @test_throws ArgumentError eigs(a, which=:Z) - @test_throws ArgumentError eigs(a, which=:BE) - @test_throws DimensionMismatch eigs(a, v0=zeros(elty,n+2)) - @test_throws ArgumentError eigs(a, v0=zeros(Int,n)) - if elty == Float64 - @test_throws ArgumentError eigs(a+a.',which=:SI) - @test_throws ArgumentError eigs(a+a.',which=:LI) - @test_throws ArgumentError eigs(a,sigma=rand(Complex64)) - end - end - end - end -end - -# Problematic example from #6965 -let A6965 = [ - 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 - -1.0 2.0 0.0 0.0 0.0 0.0 0.0 1.0 - -1.0 0.0 3.0 0.0 0.0 0.0 0.0 1.0 - -1.0 0.0 0.0 4.0 0.0 0.0 0.0 1.0 - -1.0 0.0 0.0 0.0 5.0 0.0 0.0 1.0 - -1.0 0.0 0.0 0.0 0.0 6.0 0.0 1.0 - -1.0 0.0 0.0 0.0 0.0 0.0 7.0 1.0 - -1.0 -1.0 -1.0 -1.0 -1.0 -1.0 -1.0 8.0 - ] - d, = eigs(A6965,which=:SM,nev=2,ncv=4,tol=eps()) - @test d[1] ≈ 2.5346936860350002 - @test real(d[2]) ≈ 2.6159972444834976 - @test abs(imag(d[2])) ≈ 1.2917858749046127 - - # Requires ARPACK 3.2 or a patched 3.1.5 - #T6965 = [ 0.9 0.05 0.05 - # 0.8 0.1 0.1 - # 0.7 0.1 0.2 ] - #d,v,nconv = eigs(T6965,nev=1,which=:LM) - # @test T6965*v ≈ d[1]*v atol=1e-6 -end - -# Example from Quantum Information Theory -import Base: size, issymmetric, ishermitian - -mutable struct CPM{T<:Base.LinAlg.BlasFloat} <: AbstractMatrix{T} # completely positive map - kraus::Array{T,3} # kraus operator representation -end -size(Phi::CPM) = (size(Phi.kraus,1)^2,size(Phi.kraus,3)^2) -issymmetric(Phi::CPM) = false -ishermitian(Phi::CPM) = false -import Base: A_mul_B! -function A_mul_B!{T<:Base.LinAlg.BlasFloat}(rho2::StridedVector{T},Phi::CPM{T},rho::StridedVector{T}) - rho = reshape(rho,(size(Phi.kraus,3),size(Phi.kraus,3))) - rho1 = zeros(T,(size(Phi.kraus,1),size(Phi.kraus,1))) - for s = 1:size(Phi.kraus,2) - As = view(Phi.kraus,:,s,:) - rho1 += As*rho*As' - end - return copy!(rho2,rho1) -end - -let - # Generate random isometry - (Q,R) = qr(randn(100,50)) - Q = reshape(Q,(50,2,50)) - # Construct trace-preserving completely positive map from this - Phi = CPM(copy(Q)) - (d,v,nconv,numiter,numop,resid) = eigs(Phi,nev=1,which=:LM) - # Properties: largest eigenvalue should be 1, largest eigenvector, when reshaped as matrix - # should be a Hermitian positive definite matrix (up to an arbitrary phase) - - @test d[1] ≈ 1. # largest eigenvalue should be 1. - v = reshape(v,(50,50)) # reshape to matrix - v /= trace(v) # factor out arbitrary phase - @test vecnorm(imag(v)) ≈ 0. # it should be real - v = real(v) - # @test vecnorm(v-v')/2 ≈ 0. # it should be Hermitian - # Since this fails sometimes (numerical precision error),this test is commented out - v = (v+v')/2 - @test isposdef(v) - - # Repeat with starting vector - (d2,v2,nconv2,numiter2,numop2,resid2) = eigs(Phi,nev=1,which=:LM,v0=reshape(v,(2500,))) - v2 = reshape(v2,(50,50)) - v2 /= trace(v2) - @test numiter2 < numiter - @test v ≈ v2 - - @test eigs(speye(50), nev=10)[1] ≈ ones(10) #Issue 4246 -end - -@testset "real svds" begin - let A = sparse([1, 1, 2, 3, 4], [2, 1, 1, 3, 1], [2.0, -1.0, 6.1, 7.0, 1.5]) - S1 = svds(A, nsv = 2) - S2 = svd(Array(A)) - - ## singular values match: - @test S1[1][:S] ≈ S2[2][1:2] - @testset "singular vectors" begin - ## 1st left singular vector - s1_left = sign(S1[1][:U][3,1]) * S1[1][:U][:,1] - s2_left = sign(S2[1][3,1]) * S2[1][:,1] - @test s1_left ≈ s2_left - - ## 1st right singular vector - s1_right = sign(S1[1][:V][3,1]) * S1[1][:V][:,1] - s2_right = sign(S2[3][3,1]) * S2[3][:,1] - @test s1_right ≈ s2_right - end - # Issue number 10329 - # Ensure singular values from svds are in - # the correct order - @testset "singular values ordered correctly" begin - B = sparse(diagm([1.0, 2.0, 34.0, 5.0, 6.0])) - S3 = svds(B, ritzvec=false, nsv=2) - @test S3[1][:S] ≈ [34.0, 6.0] - S4 = svds(B, nsv=2) - @test S4[1][:S] ≈ [34.0, 6.0] - end - @testset "passing guess for Krylov vectors" begin - S1 = svds(A, nsv = 2, u0=rand(eltype(A),size(A,1))) - @test S1[1][:S] ≈ S2[2][1:2] - S1 = svds(A, nsv = 2, v0=rand(eltype(A),size(A,2))) - @test S1[1][:S] ≈ S2[2][1:2] - S1 = svds(A, nsv = 2, u0=rand(eltype(A),size(A,1)), v0=rand(eltype(A),size(A,2))) - @test S1[1][:S] ≈ S2[2][1:2] - end - - @test_throws ArgumentError svds(A,nsv=0) - @test_throws ArgumentError svds(A,nsv=20) - @test_throws DimensionMismatch svds(A,nsv=2,u0=rand(size(A,1)+1)) - @test_throws DimensionMismatch svds(A,nsv=2,v0=rand(size(A,2)+1)) - end -end - -@testset "complex svds" begin - let A = sparse([1, 1, 2, 3, 4], [2, 1, 1, 3, 1], exp.(im*[2.0:2:10;])) - S1 = svds(A, nsv = 2) - S2 = svd(Array(A)) - - ## singular values match: - @test S1[1][:S] ≈ S2[2][1:2] - @testset "singular vectors" begin - ## left singular vectors - s1_left = abs.(S1[1][:U][:,1:2]) - s2_left = abs.(S2[1][:,1:2]) - @test s1_left ≈ s2_left - - ## right singular vectors - s1_right = abs.(S1[1][:V][:,1:2]) - s2_right = abs.(S2[3][:,1:2]) - @test s1_right ≈ s2_right - end - @testset "passing guess for Krylov vectors" begin - S1 = svds(A, nsv = 2, u0=rand(eltype(A),size(A,1))) - @test S1[1][:S] ≈ S2[2][1:2] - S1 = svds(A, nsv = 2, v0=rand(eltype(A),size(A,2))) - @test S1[1][:S] ≈ S2[2][1:2] - S1 = svds(A, nsv = 2, u0=rand(eltype(A),size(A,1)), v0=rand(eltype(A),size(A,2))) - @test S1[1][:S] ≈ S2[2][1:2] - end - - @test_throws ArgumentError svds(A,nsv=0) - @test_throws ArgumentError svds(A,nsv=20) - @test_throws DimensionMismatch svds(A,nsv=2,u0=complex(rand(size(A,1)+1))) - @test_throws DimensionMismatch svds(A,nsv=2,v0=complex(rand(size(A,2)+1))) - end -end - -@testset "promotion" begin - eigs(rand(1:10, 10, 10)) - eigs(rand(1:10, 10, 10), rand(1:10, 10, 10) |> t -> t't) - svds(rand(1:10, 10, 8)) - @test_throws MethodError eigs(big.(rand(1:10, 10, 10))) - @test_throws MethodError eigs(big.(rand(1:10, 10, 10)), rand(1:10, 10, 10)) - @test_throws MethodError svds(big.(rand(1:10, 10, 8))) -end - -# Symmetric generalized with singular B -let n = 10 - k = 3 - A = randn(n,n); A = A'A - B = randn(n,k); B = B*B' - @test sort(eigs(A, B, nev = k, sigma = 1.0)[1]) ≈ sort(eigvals(A, B)[1:k]) -end diff --git a/julia-0.6.3/share/julia/test/linalg/bidiag.jl b/julia-0.6.3/share/julia/test/linalg/bidiag.jl deleted file mode 100644 index 7e12884..0000000 --- a/julia-0.6.3/share/julia/test/linalg/bidiag.jl +++ /dev/null @@ -1,330 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -using Base.Test -import Base.LinAlg: BlasReal, BlasFloat - -n = 10 #Size of test matrix -srand(1) - -@testset for relty in (Int, Float32, Float64, BigFloat), elty in (relty, Complex{relty}) - if relty <: AbstractFloat - dv = convert(Vector{elty}, randn(n)) - ev = convert(Vector{elty}, randn(n-1)) - if (elty <: Complex) - dv += im*convert(Vector{elty}, randn(n)) - ev += im*convert(Vector{elty}, randn(n-1)) - end - elseif relty <: Integer - dv = convert(Vector{elty}, rand(1:10, n)) - ev = convert(Vector{elty}, rand(1:10, n-1)) - if (elty <: Complex) - dv += im*convert(Vector{elty}, rand(1:10, n)) - ev += im*convert(Vector{elty}, rand(1:10, n-1)) - end - end - - @testset "Constructors" begin - @test Bidiagonal(dv,ev,'U') == Bidiagonal(dv,ev,true) - @test_throws ArgumentError Bidiagonal(dv,ev,'R') - @test_throws DimensionMismatch Bidiagonal(dv,ones(elty,n),true) - @test_throws ArgumentError Bidiagonal(dv,ev) - end - - @testset "getindex, setindex!, size, and similar" begin - ubd = Bidiagonal(dv, ev, true) - lbd = Bidiagonal(dv, ev, false) - # bidiagonal getindex / upper & lower - @test_throws BoundsError ubd[n + 1, 1] - @test_throws BoundsError ubd[1, n + 1] - @test ubd[2, 2] == dv[2] - # bidiagonal getindex / upper - @test ubd[2, 3] == ev[2] - @test iszero(ubd[3, 2]) - # bidiagonal getindex / lower - @test lbd[3, 2] == ev[2] - @test iszero(lbd[2, 3]) - # bidiagonal setindex! / upper - cubd = copy(ubd) - @test_throws ArgumentError ubd[2, 1] = 1 - @test_throws ArgumentError ubd[3, 1] = 1 - @test (cubd[2, 1] = 0; cubd == ubd) - @test ((cubd[1, 2] = 10) == 10; cubd[1, 2] == 10) - # bidiagonal setindex! / lower - clbd = copy(lbd) - @test_throws ArgumentError lbd[1, 2] = 1 - @test_throws ArgumentError lbd[1, 3] = 1 - @test (clbd[1, 2] = 0; clbd == lbd) - @test ((clbd[2, 1] = 10) == 10; clbd[2, 1] == 10) - # bidiagonal setindex! / upper & lower - @test_throws BoundsError ubd[n + 1, 1] = 1 - @test_throws BoundsError ubd[1, n + 1] = 1 - @test ((cubd[2, 2] = 10) == 10; cubd[2, 2] == 10) - # bidiagonal size - @test_throws ArgumentError size(ubd, 0) - @test size(ubd, 1) == size(ubd, 2) == n - @test size(ubd, 3) == 1 - # bidiagonal similar - @test isa(similar(ubd), Bidiagonal{elty}) - @test isa(similar(ubd, Int), Bidiagonal{Int}) - @test isa(similar(ubd, Int, (3, 2)), Matrix{Int}) - end - - BD = Bidiagonal(dv, ev, true) - @testset "show" begin - dstring = sprint(Base.print_matrix,BD.dv') - estring = sprint(Base.print_matrix,BD.ev') - @test sprint(show,BD) == "$(summary(BD)):\n diag:$dstring\n super:$estring" - BD = Bidiagonal(dv,ev,false) - @test sprint(show,BD) == "$(summary(BD)):\n diag:$dstring\n sub:$estring" - end - - @testset for isupper in (true, false) - T = Bidiagonal(dv, ev, isupper) - - @testset "Constructor and basic properties" begin - @test size(T, 1) == size(T, 2) == n - @test size(T) == (n, n) - @test Array(T) == diagm(dv) + diagm(ev, isupper?1:-1) - @test Bidiagonal(Array(T), isupper) == T - @test big.(T) == T - @test Array(abs.(T)) == abs.(diagm(dv)) + abs.(diagm(ev, isupper?1:-1)) - @test Array(real(T)) == real(diagm(dv)) + real(diagm(ev, isupper?1:-1)) - @test Array(imag(T)) == imag(diagm(dv)) + imag(diagm(ev, isupper?1:-1)) - end - z = zeros(elty, n) - - @testset for func in (conj, transpose, ctranspose) - @test func(func(T)) == T - end - - @testset "triu and tril" begin - @test istril(Bidiagonal(dv,ev,'L')) - @test !istril(Bidiagonal(dv,ev,'U')) - @test tril!(Bidiagonal(dv,ev,'U'),-1) == Bidiagonal(zeros(dv),zeros(ev),'U') - @test tril!(Bidiagonal(dv,ev,'L'),-1) == Bidiagonal(zeros(dv),ev,'L') - @test tril!(Bidiagonal(dv,ev,'U'),-2) == Bidiagonal(zeros(dv),zeros(ev),'U') - @test tril!(Bidiagonal(dv,ev,'L'),-2) == Bidiagonal(zeros(dv),zeros(ev),'L') - @test tril!(Bidiagonal(dv,ev,'U'),1) == Bidiagonal(dv,ev,'U') - @test tril!(Bidiagonal(dv,ev,'L'),1) == Bidiagonal(dv,ev,'L') - @test tril!(Bidiagonal(dv,ev,'U')) == Bidiagonal(dv,zeros(ev),'U') - @test tril!(Bidiagonal(dv,ev,'L')) == Bidiagonal(dv,ev,'L') - @test_throws ArgumentError tril!(Bidiagonal(dv,ev,'U'),n+1) - - @test istriu(Bidiagonal(dv,ev,'U')) - @test !istriu(Bidiagonal(dv,ev,'L')) - @test triu!(Bidiagonal(dv,ev,'L'),1) == Bidiagonal(zeros(dv),zeros(ev),'L') - @test triu!(Bidiagonal(dv,ev,'U'),1) == Bidiagonal(zeros(dv),ev,'U') - @test triu!(Bidiagonal(dv,ev,'U'),2) == Bidiagonal(zeros(dv),zeros(ev),'U') - @test triu!(Bidiagonal(dv,ev,'L'),2) == Bidiagonal(zeros(dv),zeros(ev),'L') - @test triu!(Bidiagonal(dv,ev,'U'),-1) == Bidiagonal(dv,ev,'U') - @test triu!(Bidiagonal(dv,ev,'L'),-1) == Bidiagonal(dv,ev,'L') - @test triu!(Bidiagonal(dv,ev,'L')) == Bidiagonal(dv,zeros(ev),'L') - @test triu!(Bidiagonal(dv,ev,'U')) == Bidiagonal(dv,ev,'U') - @test_throws ArgumentError triu!(Bidiagonal(dv,ev,'U'),n+1) - end - - Tfull = Array(T) - @testset "Linear solves" begin - if relty <: AbstractFloat - c = convert(Matrix{elty}, randn(n,n)) - b = convert(Matrix{elty}, randn(n, 2)) - if (elty <: Complex) - b += im*convert(Matrix{elty}, randn(n, 2)) - end - elseif relty <: Integer - c = convert(Matrix{elty}, rand(1:10, n, n)) - b = convert(Matrix{elty}, rand(1:10, n, 2)) - if (elty <: Complex) - b += im*convert(Matrix{elty}, rand(1:10, n, 2)) - end - end - condT = cond(map(Complex128,Tfull)) - promty = typeof((zero(relty)*zero(relty) + zero(relty)*zero(relty))/one(relty)) - if relty != BigFloat - x = T.'\c.' - tx = Tfull.' \ c.' - elty <: AbstractFloat && @test norm(x-tx,Inf) <= 4*condT*max(eps()*norm(tx,Inf), eps(promty)*norm(x,Inf)) - @test_throws DimensionMismatch T.'\b.' - x = T'\c.' - tx = Tfull' \ c.' - @test norm(x-tx,Inf) <= 4*condT*max(eps()*norm(tx,Inf), eps(promty)*norm(x,Inf)) - @test_throws DimensionMismatch T'\b.' - x = T\c.' - tx = Tfull\c.' - @test norm(x-tx,Inf) <= 4*condT*max(eps()*norm(tx,Inf), eps(promty)*norm(x,Inf)) - @test_throws DimensionMismatch T\b.' - end - @test_throws DimensionMismatch T \ ones(elty,n+1,2) - @test_throws DimensionMismatch T.' \ ones(elty,n+1,2) - @test_throws DimensionMismatch T' \ ones(elty,n+1,2) - - @test_throws DimensionMismatch T \ RowVector(ones(elty,n+1)) - @test_throws DimensionMismatch T.' \ RowVector(ones(elty,n+1)) - @test_throws DimensionMismatch T' \ RowVector(ones(elty,n+1)) - @test_throws DimensionMismatch Base.LinAlg.At_ldiv_B(T, RowVector(ones(elty,n+1))) - @test_throws DimensionMismatch Base.LinAlg.Ac_ldiv_B(T, RowVector(ones(elty,n+1))) - let bb = b, cc = c - for atype in ("Array", "SubArray") - if atype == "Array" - b = bb - c = cc - else - b = view(bb, 1:n) - c = view(cc, 1:n, 1:2) - end - end - x = T \ b - tx = Tfull \ b - @test_throws DimensionMismatch Base.LinAlg.naivesub!(T,ones(elty,n+1)) - @test norm(x-tx,Inf) <= 4*condT*max(eps()*norm(tx,Inf), eps(promty)*norm(x,Inf)) - @testset "Generic Mat-vec ops" begin - @test T*b ≈ Tfull*b - @test T'*b ≈ Tfull'*b - if relty != BigFloat # not supported by pivoted QR - @test T/b' ≈ Tfull/b' - end - end - end - end - - @testset "Round,float,trunc,ceil" begin - if elty <: BlasReal - @test floor.(Int, T) == Bidiagonal(floor.(Int, T.dv), floor.(Int, T.ev), T.isupper) - @test isa(floor.(Int, T), Bidiagonal) - @test trunc.(Int,T) == Bidiagonal(trunc.(Int, T.dv), trunc.(Int, T.ev), T.isupper) - @test isa(trunc.(Int,T), Bidiagonal) - @test round.(Int, T) == Bidiagonal(round.(Int, T.dv), round.(Int, T.ev), T.isupper) - @test isa(round.(Int, T), Bidiagonal) - @test ceil.(Int,T) == Bidiagonal(ceil.(Int,T.dv), ceil.(Int,T.ev), T.isupper) - @test isa(ceil.(Int,T), Bidiagonal) - @test floor.(T) == Bidiagonal(floor.(T.dv), floor.(T.ev), T.isupper) - @test isa(floor.(T), Bidiagonal) - @test trunc.(T) == Bidiagonal(trunc.(T.dv), trunc.(T.ev), T.isupper) - @test isa(trunc.(T), Bidiagonal) - @test round.(T) == Bidiagonal(round.(T.dv), round.(T.ev), T.isupper) - @test isa(round.(T), Bidiagonal) - @test ceil.(T) == Bidiagonal(ceil.(T.dv), ceil.(T.ev), T.isupper) - @test isa(ceil.(T), Bidiagonal) - end - end - - @testset "Diagonals" begin - @test diag(T,2) == zeros(elty, n-2) - @test_throws ArgumentError diag(T,n+1) - end - - @testset "Eigensystems" begin - if relty <: AbstractFloat - d1, v1 = eig(T) - d2, v2 = eig(map(elty<:Complex ? Complex128 : Float64,Tfull)) - @test (isupper ? d1 : reverse(d1)) ≈ d2 - if elty <: Real - Test.test_approx_eq_modphase(v1, isupper ? v2 : v2[:,n:-1:1]) - end - end - end - - @testset "Singular systems" begin - if (elty <: BlasReal) - @test AbstractArray(svdfact(T)) ≈ AbstractArray(svdfact!(copy(Tfull))) - @test svdvals(Tfull) ≈ svdvals(T) - u1, d1, v1 = svd(Tfull) - u2, d2, v2 = svd(T) - @test d1 ≈ d2 - if elty <: Real - Test.test_approx_eq_modphase(u1, u2) - Test.test_approx_eq_modphase(v1, v2) - end - @test 0 ≈ vecnorm(u2*diagm(d2)*v2'-Tfull) atol=n*max(n^2*eps(relty),vecnorm(u1*diagm(d1)*v1'-Tfull)) - @inferred svdvals(T) - @inferred svd(T) - end - end - - @testset "Binary operations" begin - @test -T == Bidiagonal(-T.dv,-T.ev,T.isupper) - @test convert(elty,-1.0) * T == Bidiagonal(-T.dv,-T.ev,T.isupper) - @test T * convert(elty,-1.0) == Bidiagonal(-T.dv,-T.ev,T.isupper) - @testset for isupper2 in (true, false) - dv = convert(Vector{elty}, relty <: AbstractFloat ? randn(n) : rand(1:10, n)) - ev = convert(Vector{elty}, relty <: AbstractFloat ? randn(n-1) : rand(1:10, n-1)) - T2 = Bidiagonal(dv, ev, isupper2) - Tfull2 = Array(T2) - for op in (+, -, *) - @test Array(op(T, T2)) ≈ op(Tfull, Tfull2) - end - end - end - - @test inv(T)*Tfull ≈ eye(elty,n) - end - - @test Matrix{Complex{Float64}}(BD) == BD - -end - -# Issue 10742 and similar -let A = Bidiagonal([1,2,3], [0,0], true) - @test istril(A) - @test isdiag(A) -end - -# test construct from range -@test Bidiagonal(1:3, 1:2, true) == [1 1 0; 0 2 2; 0 0 3] - -@testset "promote_rule" begin - A = Bidiagonal(ones(Float32,10),ones(Float32,9),true) - B = rand(Float64,10,10) - C = Tridiagonal(rand(Float64,9),rand(Float64,10),rand(Float64,9)) - @test promote_rule(Matrix{Float64}, Bidiagonal{Float64}) == Matrix{Float64} - @test promote(B,A) == (B, convert(Matrix{Float64}, A)) - @test promote(C,A) == (C,Tridiagonal(zeros(Float64,9),convert(Vector{Float64},A.dv),convert(Vector{Float64},A.ev))) -end - -import Base.LinAlg: fillslots!, UnitLowerTriangular -@testset "fill! and fillslots!" begin - let #fill! - let # fillslots! - A = Tridiagonal(randn(2), randn(3), randn(2)) - @test fillslots!(A, 3) == Tridiagonal([3, 3.], [3, 3, 3.], [3, 3.]) - B = Bidiagonal(randn(3), randn(2), true) - @test fillslots!(B, 2) == Bidiagonal([2.,2,2], [2,2.], true) - S = SymTridiagonal(randn(3), randn(2)) - @test fillslots!(S, 1) == SymTridiagonal([1,1,1.], [1,1.]) - Ult = UnitLowerTriangular(randn(3,3)) - @test fillslots!(Ult, 3) == UnitLowerTriangular([1 0 0; 3 1 0; 3 3 1]) - end - let # fill!(exotic, 0) - exotic_arrays = Any[Tridiagonal(randn(3), randn(4), randn(3)), - Bidiagonal(randn(3), randn(2), rand(Bool)), - SymTridiagonal(randn(3), randn(2)), - sparse(randn(3,4)), - Diagonal(randn(5)), - sparse(rand(3)), - LowerTriangular(randn(3,3)), - UpperTriangular(randn(3,3)) - ] - for A in exotic_arrays - fill!(A, 0) - for a in A - @test a == 0 - end - end - end - let # fill!(small, x) - val = randn() - b = Bidiagonal(randn(1,1), true) - st = SymTridiagonal(randn(1,1)) - for x in (b, st) - @test Array(fill!(x, val)) == fill!(Array(x), val) - end - b = Bidiagonal(randn(2,2), true) - st = SymTridiagonal(randn(3), randn(2)) - t = Tridiagonal(randn(3,3)) - for x in (b, t, st) - @test_throws ArgumentError fill!(x, val) - @test Array(fill!(x, 0)) == fill!(Array(x), 0) - end - end - end -end diff --git a/julia-0.6.3/share/julia/test/linalg/bunchkaufman.jl b/julia-0.6.3/share/julia/test/linalg/bunchkaufman.jl deleted file mode 100644 index 8d197b4..0000000 --- a/julia-0.6.3/share/julia/test/linalg/bunchkaufman.jl +++ /dev/null @@ -1,127 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -using Base.Test - -using Base.LinAlg: BlasComplex, BlasFloat, BlasReal, QRPivoted - -n = 10 - -# Split n into 2 parts for tests needing two matrices -n1 = div(n, 2) -n2 = 2*n1 - -srand(1234321) - -areal = randn(n,n)/2 -aimg = randn(n,n)/2 -a2real = randn(n,n)/2 -a2img = randn(n,n)/2 -breal = randn(n,2)/2 -bimg = randn(n,2)/2 - -@testset for eltya in (Float32, Float64, Complex64, Complex128, Int) - a = eltya == Int ? rand(1:7, n, n) : convert(Matrix{eltya}, eltya <: Complex ? complex.(areal, aimg) : areal) - a2 = eltya == Int ? rand(1:7, n, n) : convert(Matrix{eltya}, eltya <: Complex ? complex.(a2real, a2img) : a2real) - @testset for atype in ("Array", "SubArray") - asym = a'+a # symmetric indefinite - apd = a'*a # symmetric positive-definite - if atype == "Array" - a = a - a2 = a2 - else - a = view(a, 1:n, 1:n) - a2 = view(a2, 1:n, 1:n) - asym = view(asym, 1:n, 1:n) - apd = view(apd, 1:n, 1:n) - end - ε = εa = eps(abs(float(one(eltya)))) - - @testset for eltyb in (Float32, Float64, Complex64, Complex128, Int) - b = eltyb == Int ? rand(1:5, n, 2) : convert(Matrix{eltyb}, eltyb <: Complex ? complex.(breal, bimg) : breal) - @testset for btype in ("Array", "SubArray") - if btype == "Array" - b = b - else - b = view(b, 1:n, 1:2) - end - - εb = eps(abs(float(one(eltyb)))) - ε = max(εa,εb) - - @testset "(Automatic) Bunch-Kaufman factor of indefinite matrix" begin - bc1 = factorize(asym) - @test logabsdet(bc1)[1] ≈ log(abs(det(bc1))) - if eltya <: Real - @test logabsdet(bc1)[2] == sign(det(bc1)) - else - @test logabsdet(bc1)[2] ≈ sign(det(bc1)) - end - @test inv(bc1)*asym ≈ eye(n) - @test asym*(bc1\b) ≈ b atol=1000ε - @testset for rook in (false, true) - @test inv(bkfact(a.'+a, :U, true, rook))*(a.'+a) ≈ eye(n) - @test size(bc1) == size(bc1.LD) - @test size(bc1,1) == size(bc1.LD,1) - @test size(bc1,2) == size(bc1.LD,2) - if eltya <: BlasReal - @test_throws ArgumentError bkfact(a) - end - end - end - - @testset "Bunch-Kaufman factors of a pos-def matrix" begin - @testset for rook in (false, true) - bc2 = bkfact(apd, :U, issymmetric(apd), rook) - @test logdet(bc2) ≈ log(det(bc2)) - @test logabsdet(bc2)[1] ≈ log(abs(det(bc2))) - @test logabsdet(bc2)[2] == sign(det(bc2)) - @test inv(bc2)*apd ≈ eye(n) - @test apd*(bc2\b) ≈ b atol=150000ε - @test ishermitian(bc2) == !issymmetric(bc2) - end - end - end - end - end -end - - -@testset "Bunch-Kaufman factors of a singular matrix" begin - let As1 = ones(n, n) - As2 = complex(ones(n, n)) - As3 = complex(ones(n, n)) - As3[end, 1] += im - As3[1, end] -= im - - for As = (As1, As2, As3) - @testset for Astype in ("Array", "SubArray") - if Astype == "Array" - As = As - else - As = view(As, 1:n, 1:n) - end - - @testset for rook in (false, true) - F = bkfact(As, :U, issymmetric(As), rook) - @test det(F) == 0 - @test_throws LinAlg.SingularException inv(F) - @test_throws LinAlg.SingularException F \ ones(size(As, 1)) - end - end - end - end -end - - -# test example due to @timholy in PR 15354 -let - A = rand(6,5); A = complex(A'*A) # to avoid calling the real-lhs-complex-rhs method - F = cholfact(A); - v6 = rand(Complex128, 6) - v5 = view(v6, 1:5) - @test F\v5 == F\v6[1:5] -end - -@test_throws DomainError logdet(bkfact([-1 -1; -1 1])) -@test logabsdet(bkfact([8 4; 4 2]))[1] == -Inf -@test isa(bkfact(Symmetric(ones(0,0))), Base.LinAlg.BunchKaufman) # 0x0 matrix diff --git a/julia-0.6.3/share/julia/test/linalg/cholesky.jl b/julia-0.6.3/share/julia/test/linalg/cholesky.jl deleted file mode 100644 index e6aabd7..0000000 --- a/julia-0.6.3/share/julia/test/linalg/cholesky.jl +++ /dev/null @@ -1,274 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -debug = false - -using Base.Test - -using Base.LinAlg: BlasComplex, BlasFloat, BlasReal, QRPivoted - -n = 10 - -# Split n into 2 parts for tests needing two matrices -n1 = div(n, 2) -n2 = 2*n1 - -srand(1234321) - -areal = randn(n,n)/2 -aimg = randn(n,n)/2 -a2real = randn(n,n)/2 -a2img = randn(n,n)/2 -breal = randn(n,2)/2 -bimg = randn(n,2)/2 - -for eltya in (Float32, Float64, Complex64, Complex128, BigFloat, Int) - a = eltya == Int ? rand(1:7, n, n) : convert(Matrix{eltya}, eltya <: Complex ? complex.(areal, aimg) : areal) - a2 = eltya == Int ? rand(1:7, n, n) : convert(Matrix{eltya}, eltya <: Complex ? complex.(a2real, a2img) : a2real) - apd = a'*a # symmetric positive-definite - - apds = Symmetric(apd) - apdsL = Symmetric(apd, :L) - apdh = Hermitian(apd) - apdhL = Hermitian(apd, :L) - ε = εa = eps(abs(float(one(eltya)))) - - @inferred cholfact(apd) - @inferred chol(apd) - capd = factorize(apd) - r = capd[:U] - κ = cond(apd, 1) #condition number - - #getindex - @test_throws KeyError capd[:Z] - - #Test error bound on reconstruction of matrix: LAWNS 14, Lemma 2.1 - - #these tests were failing on 64-bit linux when inside the inner loop - #for eltya = Complex64 and eltyb = Int. The E[i,j] had NaN32 elements - #but only with srand(1234321) set before the loops. - E = abs.(apd - r'*r) - for i=1:n, j=1:n - @test E[i,j] <= (n+1)ε/(1-(n+1)ε)*real(sqrt(apd[i,i]*apd[j,j])) - end - E = abs.(apd - full(capd)) - for i=1:n, j=1:n - @test E[i,j] <= (n+1)ε/(1-(n+1)ε)*real(sqrt(apd[i,i]*apd[j,j])) - end - @test apd*inv(capd) ≈ eye(n) - @test abs((det(capd) - det(apd))/det(capd)) <= ε*κ*n # Ad hoc, but statistically verified, revisit - @test @inferred(logdet(capd)) ≈ log(det(capd)) # logdet is less likely to overflow - - apos = apd[1,1] # test chol(x::Number), needs x>0 - @test all(x -> x ≈ √apos, cholfact(apos).factors) - @test_throws ArgumentError chol(-one(eltya)) - - if eltya <: Real - capds = cholfact(apds) - @test inv(capds)*apds ≈ eye(n) - @test abs((det(capds) - det(apd))/det(capds)) <= ε*κ*n - if eltya <: BlasReal - capds = cholfact!(copy(apds)) - @test inv(capds)*apds ≈ eye(n) - @test abs((det(capds) - det(apd))/det(capds)) <= ε*κ*n - end - ulstring = sprint(show,capds[:UL]) - @test sprint(show,capds) == "$(typeof(capds)) with factor:\n$ulstring" - else - capdh = cholfact(apdh) - @test inv(capdh)*apdh ≈ eye(n) - @test abs((det(capdh) - det(apd))/det(capdh)) <= ε*κ*n - capdh = cholfact!(copy(apdh)) - @test inv(capdh)*apdh ≈ eye(n) - @test abs((det(capdh) - det(apd))/det(capdh)) <= ε*κ*n - capdh = cholfact!(copy(apd)) - @test inv(capdh)*apdh ≈ eye(n) - @test abs((det(capdh) - det(apd))/det(capdh)) <= ε*κ*n - capdh = cholfact!(copy(apd), :L) - @test inv(capdh)*apdh ≈ eye(n) - @test abs((det(capdh) - det(apd))/det(capdh)) <= ε*κ*n - ulstring = sprint(show,capdh[:UL]) - @test sprint(show,capdh) == "$(typeof(capdh)) with factor:\n$ulstring" - end - - # test chol of 2x2 Strang matrix - S = convert(AbstractMatrix{eltya},full(SymTridiagonal([2,2],[-1]))) - U = Bidiagonal([2,sqrt(eltya(3))],[-1],true) / sqrt(eltya(2)) - @test full(chol(S)) ≈ full(U) - - #lower Cholesky factor - lapd = cholfact(apd, :L) - @test full(lapd) ≈ apd - l = lapd[:L] - @test l*l' ≈ apd - @test triu(capd.factors) ≈ lapd[:U] - @test tril(lapd.factors) ≈ capd[:L] - if eltya <: Real - capds = cholfact(apds) - lapds = cholfact(apdsL) - cl = chol(apdsL) - ls = lapds[:L] - @test ls*ls' ≈ apd - @test triu(capds.factors) ≈ lapds[:U] - @test tril(lapds.factors) ≈ capds[:L] - @test istriu(cl) - @test cl'cl ≈ apds - @test cl'cl ≈ apdsL - else - capdh = cholfact(apdh) - lapdh = cholfact(apdhL) - cl = chol(apdhL) - ls = lapdh[:L] - @test ls*ls' ≈ apd - @test triu(capdh.factors) ≈ lapdh[:U] - @test tril(lapdh.factors) ≈ capdh[:L] - @test istriu(cl) - @test cl'cl ≈ apdh - @test cl'cl ≈ apdhL - end - - #pivoted upper Cholesky - if eltya != BigFloat - cz = cholfact(zeros(eltya,n,n), :U, Val{true}) - @test_throws Base.LinAlg.RankDeficientException Base.LinAlg.chkfullrank(cz) - cpapd = cholfact(apd, :U, Val{true}) - @test rank(cpapd) == n - @test all(diff(diag(real(cpapd.factors))).<=0.) # diagonal should be non-increasing - if isreal(apd) - @test apd*inv(cpapd) ≈ eye(n) - end - @test full(cpapd) ≈ apd - #getindex - @test_throws KeyError cpapd[:Z] - - @test size(cpapd) == size(apd) - @test full(copy(cpapd)) ≈ apd - @test det(cpapd) ≈ det(apd) - @test logdet(cpapd) ≈ logdet(apd) - @test cpapd[:P]*cpapd[:L]*cpapd[:U]*cpapd[:P]' ≈ apd - end - - for eltyb in (Float32, Float64, Complex64, Complex128, Int) - b = eltyb == Int ? rand(1:5, n, 2) : convert(Matrix{eltyb}, eltyb <: Complex ? complex.(breal, bimg) : breal) - εb = eps(abs(float(one(eltyb)))) - ε = max(εa,εb) - -debug && println("\ntype of a: ", eltya, " type of b: ", eltyb, "\n") - let Bs = b - for atype in ("Array", "SubArray") - if atype == "Array" - b = Bs - else - b = view(Bs, 1:n, 1) - end - - # Test error bound on linear solver: LAWNS 14, Theorem 2.1 - # This is a surprisingly loose bound - x = capd\b - @test norm(x-apd\b,1)/norm(x,1) <= (3n^2 + n + n^3*ε)*ε/(1-(n+1)*ε)*κ - @test norm(apd*x-b,1)/norm(b,1) <= (3n^2 + n + n^3*ε)*ε/(1-(n+1)*ε)*κ - - @test norm(a*(capd\(a'*b)) - b,1)/norm(b,1) <= ε*κ*n # Ad hoc, revisit - - if eltya != BigFloat && eltyb != BigFloat - @test norm(apd * (lapd\b) - b)/norm(b) <= ε*κ*n - @test norm(apd * (lapd\b[1:n]) - b[1:n])/norm(b[1:n]) <= ε*κ*n - end - @test_throws DimensionMismatch lapd\RowVector(ones(n)) - -debug && println("pivoted Cholesky decomposition") - if eltya != BigFloat && eltyb != BigFloat # Note! Need to implement pivoted Cholesky decomposition in julia - - @test norm(apd * (cpapd\b) - b)/norm(b) <= ε*κ*n # Ad hoc, revisit - @test norm(apd * (cpapd\b[1:n]) - b[1:n])/norm(b[1:n]) <= ε*κ*n - - lpapd = cholfact(apd, :L, Val{true}) - @test norm(apd * (lpapd\b) - b)/norm(b) <= ε*κ*n # Ad hoc, revisit - @test norm(apd * (lpapd\b[1:n]) - b[1:n])/norm(b[1:n]) <= ε*κ*n - - @test_throws BoundsError lpapd\RowVector(ones(n)) - end - end - end - end -end - -begin - # Cholesky factor of Matrix with non-commutative elements, here 2x2-matrices - - X = Matrix{Float64}[0.1*rand(2,2) for i in 1:3, j = 1:3] - L = full(Base.LinAlg._chol!(X*X', LowerTriangular)) - U = full(Base.LinAlg._chol!(X*X', UpperTriangular)) - XX = full(X*X') - - @test sum(sum(norm, L*L' - XX)) < eps() - @test sum(sum(norm, U'*U - XX)) < eps() -end - -# Test generic cholfact! -for elty in (Float32, Float64, Complex{Float32}, Complex{Float64}) - if elty <: Complex - A = complex.(randn(5,5), randn(5,5)) - else - A = randn(5,5) - end - A = convert(Matrix{elty}, A'A) - @test full(cholfact(A)[:L]) ≈ full(invoke(Base.LinAlg._chol!, Tuple{AbstractMatrix, Type{LowerTriangular}}, copy(A), LowerTriangular)) - @test full(cholfact(A)[:U]) ≈ full(invoke(Base.LinAlg._chol!, Tuple{AbstractMatrix, Type{UpperTriangular}}, copy(A), UpperTriangular)) -end - -# Test up- and downdates -let A = complex.(randn(10,5), randn(10, 5)), v = complex.(randn(5), randn(5)) - for uplo in (:U, :L) - AcA = A'A - BcB = AcA + v*v' - BcB = (BcB + BcB')/2 - F = cholfact(AcA, uplo) - G = cholfact(BcB, uplo) - @test LinAlg.lowrankupdate(F, v)[uplo] ≈ G[uplo] - @test_throws DimensionMismatch LinAlg.lowrankupdate(F, ones(eltype(v), length(v)+1)) - @test LinAlg.lowrankdowndate(G, v)[uplo] ≈ F[uplo] - @test_throws DimensionMismatch LinAlg.lowrankdowndate(G, ones(eltype(v), length(v)+1)) - end -end - -# issue #13243, unexpected nans in complex cholfact -let apd = [5.8525753f0 + 0.0f0im -0.79540455f0 + 0.7066077f0im 0.98274714f0 + 1.3824869f0im 2.619998f0 + 1.8532984f0im -1.8306153f0 - 1.2336911f0im 0.32275113f0 + 0.015575029f0im 2.1968813f0 + 1.0640624f0im 0.27894387f0 + 0.97911835f0im 3.0476584f0 + 0.18548489f0im 0.3842994f0 + 0.7050991f0im - -0.79540455f0 - 0.7066077f0im 8.313246f0 + 0.0f0im -1.8076122f0 - 0.8882447f0im 0.47806996f0 + 0.48494184f0im 0.5096429f0 - 0.5395974f0im -0.7285097f0 - 0.10360408f0im -1.1760061f0 - 2.7146957f0im -0.4271084f0 + 0.042899966f0im -1.7228563f0 + 2.8335886f0im 1.8942566f0 + 0.6389735f0im - 0.98274714f0 - 1.3824869f0im -1.8076122f0 + 0.8882447f0im 9.367975f0 + 0.0f0im -0.1838578f0 + 0.6468568f0im -1.8338387f0 + 0.7064959f0im 0.041852742f0 - 0.6556877f0im 2.5673025f0 + 1.9732997f0im -1.1148382f0 - 0.15693812f0im 2.4704504f0 - 1.0389464f0im 1.0858271f0 - 1.298006f0im - 2.619998f0 - 1.8532984f0im 0.47806996f0 - 0.48494184f0im -0.1838578f0 - 0.6468568f0im 3.1117508f0 + 0.0f0im -1.956626f0 + 0.22825956f0im 0.07081801f0 - 0.31801307f0im 0.3698375f0 - 0.5400855f0im 0.80686307f0 + 1.5315914f0im 1.5649154f0 - 1.6229297f0im -0.112077385f0 + 1.2014246f0im - -1.8306153f0 + 1.2336911f0im 0.5096429f0 + 0.5395974f0im -1.8338387f0 - 0.7064959f0im -1.956626f0 - 0.22825956f0im 3.6439795f0 + 0.0f0im -0.2594722f0 + 0.48786148f0im -0.47636223f0 - 0.27821827f0im -0.61608654f0 - 2.01858f0im -2.7767487f0 + 1.7693765f0im 0.048102796f0 - 0.9741874f0im - 0.32275113f0 - 0.015575029f0im -0.7285097f0 + 0.10360408f0im 0.041852742f0 + 0.6556877f0im 0.07081801f0 + 0.31801307f0im -0.2594722f0 - 0.48786148f0im 3.624376f0 + 0.0f0im -1.6697118f0 + 0.4017511f0im -1.4397877f0 - 0.7550918f0im -0.31456697f0 - 1.0403451f0im -0.31978557f0 + 0.13701046f0im - 2.1968813f0 - 1.0640624f0im -1.1760061f0 + 2.7146957f0im 2.5673025f0 - 1.9732997f0im 0.3698375f0 + 0.5400855f0im -0.47636223f0 + 0.27821827f0im -1.6697118f0 - 0.4017511f0im 6.8273163f0 + 0.0f0im -0.10051322f0 + 0.24303961f0im 1.4415971f0 + 0.29750675f0im 1.221786f0 - 0.85654986f0im - 0.27894387f0 - 0.97911835f0im -0.4271084f0 - 0.042899966f0im -1.1148382f0 + 0.15693812f0im 0.80686307f0 - 1.5315914f0im -0.61608654f0 + 2.01858f0im -1.4397877f0 + 0.7550918f0im -0.10051322f0 - 0.24303961f0im 3.4057708f0 + 0.0f0im -0.5856801f0 - 1.0203559f0im 0.7103452f0 + 0.8422135f0im - 3.0476584f0 - 0.18548489f0im -1.7228563f0 - 2.8335886f0im 2.4704504f0 + 1.0389464f0im 1.5649154f0 + 1.6229297f0im -2.7767487f0 - 1.7693765f0im -0.31456697f0 + 1.0403451f0im 1.4415971f0 - 0.29750675f0im -0.5856801f0 + 1.0203559f0im 7.005772f0 + 0.0f0im -0.9617417f0 - 1.2486815f0im - 0.3842994f0 - 0.7050991f0im 1.8942566f0 - 0.6389735f0im 1.0858271f0 + 1.298006f0im -0.112077385f0 - 1.2014246f0im 0.048102796f0 + 0.9741874f0im -0.31978557f0 - 0.13701046f0im 1.221786f0 + 0.85654986f0im 0.7103452f0 - 0.8422135f0im -0.9617417f0 + 1.2486815f0im 3.4629636f0 + 0.0f0im] - b = [-0.905011814118756 + 0.2847570854574069im -0.7122162951294634 - 0.630289556702497im - -0.7620356655676837 + 0.15533508334193666im 0.39947219167701153 - 0.4576746001199889im - -0.21782716937787788 - 0.9222220085490986im -0.727775859267237 + 0.50638268521728im - -1.0509472322215125 + 0.5022165705328413im -0.7264975746431271 + 0.31670415674097235im - -0.6650468984506477 - 0.5000967284800251im -0.023682508769195098 + 0.18093440285319276im - -0.20604111555491242 + 0.10570814584017311im 0.562377322638969 - 0.2578030745663871im - -0.3451346708401685 + 1.076948486041297im 0.9870834574024372 - 0.2825689605519449im - 0.25336108035924787 + 0.975317836492159im 0.0628393808469436 - 0.1253397353973715im - 0.11192755545114 - 0.1603741874112385im 0.8439562576196216 + 1.0850814110398734im - -1.0568488936791578 - 0.06025820467086475im 0.12696236014017806 - 0.09853584666755086im] - cholfact(apd, :L, Val{true}) \ b - r = factorize(apd)[:U] - E = abs.(apd - r'*r) - ε = eps(abs(float(one(Complex64)))) - n = 10 - for i=1:n, j=1:n - @test E[i,j] <= (n+1)ε/(1-(n+1)ε)*real(sqrt(apd[i,i]*apd[j,j])) - end -end - -# Fail if non-Hermitian -@test_throws ArgumentError cholfact(randn(5,5)) -@test_throws ArgumentError cholfact(complex.(randn(5,5), randn(5,5))) -@test_throws ArgumentError Base.LinAlg.chol!(randn(5,5)) -@test_throws ArgumentError Base.LinAlg.cholfact!(randn(5,5),:U,Val{false}) -@test_throws ArgumentError Base.LinAlg.cholfact!(randn(5,5),:U,Val{true}) -@test_throws ArgumentError cholfact(randn(5,5),:U,Val{false}) - -# Fail for non-BLAS element types -@test_throws ArgumentError cholfact!(Hermitian(rand(Float16, 5,5)), Val{true}) diff --git a/julia-0.6.3/share/julia/test/linalg/conjarray.jl b/julia-0.6.3/share/julia/test/linalg/conjarray.jl deleted file mode 100644 index 4ba4ac9..0000000 --- a/julia-0.6.3/share/julia/test/linalg/conjarray.jl +++ /dev/null @@ -1,28 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -@testset "Core" begin - m = [1+im 2; 2 4-im] - cm = ConjMatrix(m) - @test cm[1,1] == 1-im - @test cm[1] == 1-im - @test trace(cm*m) == 27 - @test cm' == m - - cm[:,2] = [3; 3-im] #setindex! with a vector - @test conj(cm) == [1+im 3; 2 3+im] - - v = [[1+im], [1-im]] - cv = ConjVector(v) - @test cv[1] == [1-im] -end - -@testset "RowVector conjugates" begin - v = [1+im, 1-im] - rv = v' - @test (parent(rv) isa ConjArray) - @test rv' === v - - # Currently, view behavior defaults to only RowVectors. - @test isa((v').', Vector) - @test isa((v.')', Vector) -end diff --git a/julia-0.6.3/share/julia/test/linalg/dense.jl b/julia-0.6.3/share/julia/test/linalg/dense.jl deleted file mode 100644 index 3f1b316..0000000 --- a/julia-0.6.3/share/julia/test/linalg/dense.jl +++ /dev/null @@ -1,640 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -using Base.Test - -@testset "Check that non-floats are correctly promoted" begin - @test [1 0 0; 0 1 0]\[1,1] ≈ [1;1;0] -end - -using Base.LinAlg: BlasComplex, BlasFloat, BlasReal - -n = 10 - -# Split n into 2 parts for tests needing two matrices -n1 = div(n, 2) -n2 = 2*n1 - -srand(1234321) - -@testset "Matrix condition number" begin - ainit = rand(n,n) - @testset "for $elty" for elty in (Float32, Float64, Complex64, Complex128) - ainit = convert(Matrix{elty}, ainit) - for arraytype in ("Array", "SubArray") - if arraytype == "Array" - a = ainit - else - a = view(ainit, 1:n, 1:n) - end - @test cond(a,1) ≈ 4.837320054554436e+02 atol=0.01 - @test cond(a,2) ≈ 1.960057871514615e+02 atol=0.01 - @test cond(a,Inf) ≈ 3.757017682707787e+02 atol=0.01 - @test cond(a[:,1:5]) ≈ 10.233059337453463 atol=0.01 - @test_throws ArgumentError cond(a,3) - end - end -end - -areal = randn(n,n)/2 -aimg = randn(n,n)/2 -a2real = randn(n,n)/2 -a2img = randn(n,n)/2 -breal = randn(n,2)/2 -bimg = randn(n,2)/2 - -@testset "For A containing $eltya" for eltya in (Float32, Float64, Complex64, Complex128, Int) - ainit = eltya == Int ? rand(1:7, n, n) : convert(Matrix{eltya}, eltya <: Complex ? complex.(areal, aimg) : areal) - ainit2 = eltya == Int ? rand(1:7, n, n) : convert(Matrix{eltya}, eltya <: Complex ? complex.(a2real, a2img) : a2real) - ε = εa = eps(abs(float(one(eltya)))) - - apd = ainit'*ainit # symmetric positive-definite - @testset "Positive definiteness" begin - @test isposdef(apd,:U) - end - @testset "For b containing $eltyb" for eltyb in (Float32, Float64, Complex64, Complex128, Int) - binit = eltyb == Int ? rand(1:5, n, 2) : convert(Matrix{eltyb}, eltyb <: Complex ? complex.(breal, bimg) : breal) - εb = eps(abs(float(one(eltyb)))) - ε = max(εa,εb) - - for arraytype in ("Array", "SubArray") - if arraytype == "Array" - a = ainit - b = binit - else - a = view(ainit, 1:n, 1:n) - b = view(binit, 1:n, 1:2) - end - - @testset "Solve square general system of equations" begin - κ = cond(a,1) - x = a \ b - @test_throws DimensionMismatch b'\b - @test_throws DimensionMismatch b\b' - @test norm(a*x - b, 1)/norm(b) < ε*κ*n*2 # Ad hoc, revisit! - @test zeros(eltya,n)\ones(eltya,n) ≈ zeros(eltya,n,1)\ones(eltya,n,1) - end - - @testset "Test nullspace" begin - a15null = nullspace(a[:,1:n1]') - @test rank([a[:,1:n1] a15null]) == 10 - @test norm(a[:,1:n1]'a15null,Inf) ≈ zero(eltya) atol=300ε - @test norm(a15null'a[:,1:n1],Inf) ≈ zero(eltya) atol=400ε - @test size(nullspace(b), 2) == 0 - @test nullspace(zeros(eltya,n)) == eye(eltya,1) - end - end - end # for eltyb - - for arraytype in ("Array", "SubArray") - if arraytype == "Array" - a = ainit - a2 = ainit2 - else - a = view(ainit, 1:n, 1:n) - a2 = view(ainit2, 1:n, 1:n) - end - - @testset "Test pinv" begin - pinva15 = pinv(a[:,1:n1]) - @test a[:,1:n1]*pinva15*a[:,1:n1] ≈ a[:,1:n1] - @test pinva15*a[:,1:n1]*pinva15 ≈ pinva15 - - @test size(pinv(ones(eltya,0,0))) == (0,0) - end - - @testset "Lyapunov/Sylvester" begin - x = lyap(a, a2) - @test -a2 ≈ a*x + x*a' - x2 = sylvester(a[1:3, 1:3], a[4:n, 4:n], a2[1:3,4:n]) - @test -a2[1:3, 4:n] ≈ a[1:3, 1:3]*x2 + x2*a[4:n, 4:n] - end - - @testset "Matrix square root" begin - asq = sqrtm(a) - @test asq*asq ≈ a - asym = a'+a # symmetric indefinite - asymsq = sqrtm(asym) - @test asymsq*asymsq ≈ asym - end - - @testset "Powers" begin - if eltya <: AbstractFloat - z = zero(eltya) - t = convert(eltya,2) - r = convert(eltya,2.5) - @test a^z ≈ eye(a) - @test a^t ≈ a^2 - @test eye(eltya,n,n)^r ≈ eye(a) - end - end - end # end for loop over arraytype - - @testset "Numbers" begin - α = rand(eltya) - A = zeros(eltya,1,1) - A[1,1] = α - @test diagm(α) == A # Test behavior of `diagm` when passed a scalar - @test expm(α) == exp(α) # `expm` should behave like `exp` with scalar argument - end - - @testset "Factorize" begin - d = rand(eltya,n) - e = rand(eltya,n-1) - e2 = rand(eltya,n-1) - f = rand(eltya,n-2) - A = diagm(d) - @test factorize(A) == Diagonal(d) - A += diagm(e,-1) - @test factorize(A) == Bidiagonal(d,e,false) - A += diagm(f,-2) - @test factorize(A) == LowerTriangular(A) - A = diagm(d) + diagm(e,1) - @test factorize(A) == Bidiagonal(d,e,true) - if eltya <: Real - A = diagm(d) + diagm(e,1) + diagm(e,-1) - @test full(factorize(A)) ≈ full(factorize(SymTridiagonal(d,e))) - A = diagm(d) + diagm(e,1) + diagm(e,-1) + diagm(f,2) + diagm(f,-2) - @test inv(factorize(A)) ≈ inv(factorize(Symmetric(A))) - end - A = diagm(d) + diagm(e,1) + diagm(e2,-1) - @test full(factorize(A)) ≈ full(factorize(Tridiagonal(e2,d,e))) - A = diagm(d) + diagm(e,1) + diagm(f,2) - @test factorize(A) == UpperTriangular(A) - end -end # for eltya - -@testset "test triu/tril bounds checking" begin - ainit = rand(5,7) - for arraytype in ("Array", "SubArray") - if arraytype == "Array" - a = ainit - else - a = view(ainit, 1:size(ainit, 1), 1:size(ainit, 2)) - end - @test_throws(ArgumentError,triu(a,8)) - @test_throws(ArgumentError,triu(a,-6)) - @test_throws(ArgumentError,tril(a,8)) - @test_throws(ArgumentError,tril(a,-6)) - end -end - -@testset "Test gradient for $elty" for elty in (Int32, Int64, Float32, Float64, Complex64, Complex128) - if elty <: Real - x = convert(Vector{elty}, [1:3;]) - g = ones(elty, 3) - else - x = convert(Vector{elty}, complex.([1:3;], [1:3;])) - g = convert(Vector{elty}, complex.(ones(3), ones(3))) - end - xsub = view(x, 1:size(x, 1)) - @test gradient(x) ≈ g - @test gradient(xsub) ≈ g # Test gradient on SubArray - @test gradient(ones(elty,1)) == zeros(elty,1) -end - -@testset "Tests norms" begin - nnorm = 10 - mmat = 10 - nmat = 8 - @testset "For $elty" for elty in (Float32, Float64, BigFloat, Complex{Float32}, Complex{Float64}, Complex{BigFloat}, Int32, Int64, BigInt) - x = ones(elty,10) - @testset "Vector" begin - xs = view(x,1:2:10) - @test norm(x, -Inf) ≈ 1 - @test norm(x, -1) ≈ 1/10 - @test norm(x, 0) ≈ 10 - @test norm(x, 1) ≈ 10 - @test norm(x, 2) ≈ sqrt(10) - @test norm(x, 3) ≈ cbrt(10) - @test norm(x, Inf) ≈ 1 - if elty <: Base.LinAlg.BlasFloat - @test norm(x, 1:4) ≈ 2 - @test_throws BoundsError norm(x,-1:4) - @test_throws BoundsError norm(x,1:11) - end - @test norm(xs, -Inf) ≈ 1 - @test norm(xs, -1) ≈ 1/5 - @test norm(xs, 0) ≈ 5 - @test norm(xs, 1) ≈ 5 - @test norm(xs, 2) ≈ sqrt(5) - @test norm(xs, 3) ≈ cbrt(5) - @test norm(xs, Inf) ≈ 1 - end - - @testset "Issue #12552:" begin - if real(elty) <: AbstractFloat - for p in [-Inf,-1,1,2,3,Inf] - @test isnan(norm(elty[0,NaN],p)) - @test isnan(norm(elty[NaN,0],p)) - end - end - end - - @testset "Number" begin - norm(x[1:1]) === norm(x[1], -Inf) - norm(x[1:1]) === norm(x[1], 0) - norm(x[1:1]) === norm(x[1], 1) - norm(x[1:1]) === norm(x[1], 2) - norm(x[1:1]) === norm(x[1], Inf) - end - - @testset "Absolute homogeneity, triangle inequality, & vectorized versions" begin - for i = 1:10 - xinit = elty <: Integer ? convert(Vector{elty}, rand(1:10, nnorm)) : - elty <: Complex ? convert(Vector{elty}, complex.(randn(nnorm), randn(nnorm))) : - convert(Vector{elty}, randn(nnorm)) - yinit = elty <: Integer ? convert(Vector{elty}, rand(1:10, nnorm)) : - elty <: Complex ? convert(Vector{elty}, complex.(randn(nnorm), randn(nnorm))) : - convert(Vector{elty}, randn(nnorm)) - α = elty <: Integer ? randn() : - elty <: Complex ? convert(elty, complex(randn(),randn())) : - convert(elty, randn()) - for arraytype in ("Array", "SubArray") - if arraytype == "Array" - x = xinit - y = yinit - else - x = view(xinit,1:2:nnorm) - y = view(yinit,1:2:nnorm) - end - # Absolute homogeneity - @test norm(α*x,-Inf) ≈ abs(α)*norm(x,-Inf) - @test norm(α*x,-1) ≈ abs(α)*norm(x,-1) - @test norm(α*x,1) ≈ abs(α)*norm(x,1) - @test norm(α*x) ≈ abs(α)*norm(x) # two is default - @test norm(α*x,3) ≈ abs(α)*norm(x,3) - @test norm(α*x,Inf) ≈ abs(α)*norm(x,Inf) - - # Triangle inequality - @test norm(x + y,1) <= norm(x,1) + norm(y,1) - @test norm(x + y) <= norm(x) + norm(y) # two is default - @test norm(x + y,3) <= norm(x,3) + norm(y,3) - @test norm(x + y,Inf) <= norm(x,Inf) + norm(y,Inf) - - # Against vectorized versions - @test norm(x,-Inf) ≈ minimum(abs.(x)) - @test norm(x,-1) ≈ inv(sum(1./abs.(x))) - @test norm(x,0) ≈ sum(x .!= 0) - @test norm(x,1) ≈ sum(abs.(x)) - @test norm(x) ≈ sqrt(sum(abs2.(x))) - @test norm(x,3) ≈ cbrt(sum(abs.(x).^3.)) - @test norm(x,Inf) ≈ maximum(abs.(x)) - end - end - end - - @testset "Matrix (Operator)" begin - A = ones(elty,10,10) - As = view(A,1:5,1:5) - @test norm(A, 1) ≈ 10 - elty <: Union{BigFloat,Complex{BigFloat},BigInt} || @test norm(A, 2) ≈ 10 - @test norm(A, Inf) ≈ 10 - @test norm(As, 1) ≈ 5 - elty <: Union{BigFloat,Complex{BigFloat},BigInt} || @test norm(As, 2) ≈ 5 - @test norm(As, Inf) ≈ 5 - end - - @testset "Absolute homogeneity, triangle inequality, & vecnorm" begin - for i = 1:10 - Ainit = elty <: Integer ? convert(Matrix{elty}, rand(1:10, mmat, nmat)) : - elty <: Complex ? convert(Matrix{elty}, complex.(randn(mmat, nmat), randn(mmat, nmat))) : - convert(Matrix{elty}, randn(mmat, nmat)) - Binit = elty <: Integer ? convert(Matrix{elty}, rand(1:10, mmat, nmat)) : - elty <: Complex ? convert(Matrix{elty}, complex.(randn(mmat, nmat), randn(mmat, nmat))) : - convert(Matrix{elty}, randn(mmat, nmat)) - α = elty <: Integer ? randn() : - elty <: Complex ? convert(elty, complex(randn(),randn())) : - convert(elty, randn()) - - for arraytype in ("Array", "SubArray") - if arraytype == "Array" - A = Ainit - B = Binit - else - A = view(Ainit,1:nmat,1:nmat) - B = view(Binit,1:nmat,1:nmat) - end - - # Absolute homogeneity - @test norm(α*A,1) ≈ abs(α)*norm(A,1) - elty <: Union{BigFloat,Complex{BigFloat},BigInt} || @test norm(α*A) ≈ abs(α)*norm(A) # two is default - @test norm(α*A,Inf) ≈ abs(α)*norm(A,Inf) - - # Triangle inequality - @test norm(A + B,1) <= norm(A,1) + norm(B,1) - elty <: Union{BigFloat,Complex{BigFloat},BigInt} || @test norm(A + B) <= norm(A) + norm(B) # two is default - @test norm(A + B,Inf) <= norm(A,Inf) + norm(B,Inf) - - # vecnorm: - for p = -2:3 - @test norm(reshape(A, length(A)), p) == vecnorm(A, p) - end - end - end - - @testset "issue #10234" begin - if elty <: AbstractFloat || elty <: Complex - z = zeros(elty, 100) - z[1] = -Inf - for p in [-2,-1.5,-1,-0.5,0.5,1,1.5,2,Inf] - @test norm(z, p) == (p < 0 ? 0 : Inf) - @test norm(elty[Inf],p) == Inf - end - end - end - end - end - - @testset "issue #10234" begin - @test norm(Any[Inf],-2) == norm(Any[Inf],-1) == norm(Any[Inf],1) == norm(Any[Inf],1.5) == norm(Any[Inf],2) == norm(Any[Inf],Inf) == Inf - end - - @testset "overflow/underflow in norms" begin - @test norm(Float64[1e-300, 1], -3)*1e300 ≈ 1 - @test norm(Float64[1e300, 1], 3)*1e-300 ≈ 1 - end -end - -## Issue related tests -@testset "issue #1447" begin - A = [1.+0.0im 0; 0 1] - B = pinv(A) - for i = 1:4 - @test A[i] ≈ B[i] - end -end - -@testset "issue #2246" begin - A = [1 2 0 0; 0 1 0 0; 0 0 0 0; 0 0 0 0] - Asq = sqrtm(A) - @test Asq*Asq ≈ A - A2 = view(A, 1:2, 1:2) - A2sq = sqrtm(A2) - @test A2sq*A2sq ≈ A2 - - N = 3 - @test log(det(eye(N))) ≈ logdet(eye(N)) -end - -@testset "issue #2637" begin - a = [1, 2, 3] - b = [4, 5, 6] - @test kron(eye(2),eye(2)) == eye(4) - @test kron(a,b) == [4,5,6,8,10,12,12,15,18] - @test kron(a',b') == [4 5 6 8 10 12 12 15 18] - @test kron(a,b') == [4 5 6; 8 10 12; 12 15 18] - @test kron(a',b) == [4 8 12; 5 10 15; 6 12 18] - @test kron(a,eye(2)) == [1 0; 0 1; 2 0; 0 2; 3 0; 0 3] - @test kron(eye(2),a) == [ 1 0; 2 0; 3 0; 0 1; 0 2; 0 3] - @test kron(eye(2),2) == 2*eye(2) - @test kron(3,eye(3)) == 3*eye(3) - @test kron(a,2) == [2, 4, 6] - @test kron(b',2) == [8 10 12] -end - -@testset "issue #4796" begin - dim=2 - S=zeros(Complex,dim,dim) - T=zeros(Complex,dim,dim) - T[:] = 1 - z = 2.5 + 1.5im - S[1] = z - @test S*T == [z z; 0 0] - - # similar issue for Array{Real} - @test Real[1 2] * Real[1.5; 2.0] == Real[5.5] -end - -@testset "Matrix exponential" begin - @testset "Tests for $elty" for elty in (Float32, Float64, Complex64, Complex128) - A1 = convert(Matrix{elty}, [4 2 0; 1 4 1; 1 1 4]) - eA1 = convert(Matrix{elty}, [147.866622446369 127.781085523181 127.781085523182; - 183.765138646367 183.765138646366 163.679601723179; - 71.797032399996 91.8825693231832 111.968106246371]') - @test expm(A1) ≈ eA1 - - A2 = convert(Matrix{elty}, - [29.87942128909879 0.7815750847907159 -2.289519314033932; - 0.7815750847907159 25.72656945571064 8.680737820540137; - -2.289519314033932 8.680737820540137 34.39400925519054]) - eA2 = convert(Matrix{elty}, - [ 5496313853692458.0 -18231880972009236.0 -30475770808580460.0; - -18231880972009252.0 60605228702221920.0 101291842930249760.0; - -30475770808580480.0 101291842930249728.0 169294411240851968.0]) - @test expm(A2) ≈ eA2 - - A3 = convert(Matrix{elty}, [-131 19 18;-390 56 54;-387 57 52]) - eA3 = convert(Matrix{elty}, [-1.50964415879218 -5.6325707998812 -4.934938326092; - 0.367879439109187 1.47151775849686 1.10363831732856; - 0.135335281175235 0.406005843524598 0.541341126763207]') - @test expm(A3) ≈ eA3 - - A4 = convert(Matrix{elty}, [0.25 0.25; 0 0]) - eA4 = convert(Matrix{elty}, [1.2840254166877416 0.2840254166877415; 0 1]) - @test expm(A4) ≈ eA4 - - A5 = convert(Matrix{elty}, [0 0.02; 0 0]) - eA5 = convert(Matrix{elty}, [1 0.02; 0 1]) - @test expm(A5) ≈ eA5 - - # Hessenberg - @test hessfact(A1)[:H] ≈ convert(Matrix{elty}, - [4.000000000000000 -1.414213562373094 -1.414213562373095 - -1.414213562373095 4.999999999999996 -0.000000000000000 - 0 -0.000000000000002 3.000000000000000]) - end - - @testset "Additional tests for $elty" for elty in (Float64, Complex{Float64}) - A4 = convert(Matrix{elty}, [1/2 1/3 1/4 1/5+eps(); - 1/3 1/4 1/5 1/6; - 1/4 1/5 1/6 1/7; - 1/5 1/6 1/7 1/8]) - @test expm(logm(A4)) ≈ A4 - - A5 = convert(Matrix{elty}, [1 1 0 1; 0 1 1 0; 0 0 1 1; 1 0 0 1]) - @test expm(logm(A5)) ≈ A5 - - A6 = convert(Matrix{elty}, [-5 2 0 0 ; 1/2 -7 3 0; 0 1/3 -9 4; 0 0 1/4 -11]) - @test expm(logm(A6)) ≈ A6 - - A7 = convert(Matrix{elty}, [1 0 0 1e-8; 0 1 0 0; 0 0 1 0; 0 0 0 1]) - @test expm(logm(A7)) ≈ A7 - end - - A8 = 100 * [-1+1im 0 0 1e-8; 0 1 0 0; 0 0 1 0; 0 0 0 1] - @test expm(logm(A8)) ≈ A8 -end - -@testset "issue 5116" begin - A9 = [0 10 0 0; -1 0 0 0; 0 0 0 0; -2 0 0 0] - eA9 = [-0.999786072879326 -0.065407069689389 0.0 0.0 - 0.006540706968939 -0.999786072879326 0.0 0.0 - 0.0 0.0 1.0 0.0 - 0.013081413937878 -3.999572145758650 0.0 1.0] - @test expm(A9) ≈ eA9 - - A10 = [ 0. 0. 0. 0. ; 0. 0. -im 0.; 0. im 0. 0.; 0. 0. 0. 0.] - eA10 = [ 1.0+0.0im 0.0+0.0im 0.0+0.0im 0.0+0.0im - 0.0+0.0im 1.543080634815244+0.0im 0.0-1.175201193643801im 0.0+0.0im - 0.0+0.0im 0.0+1.175201193643801im 1.543080634815243+0.0im 0.0+0.0im - 0.0+0.0im 0.0+0.0im 0.0+0.0im 1.0+0.0im] - @test expm(A10) ≈ eA10 -end - -@testset "Additional matrix logarithm tests" for elty in (Float64, Complex{Float64}) - A11 = convert(Matrix{elty}, [3 2; -5 -3]) - @test expm(logm(A11)) ≈ A11 - - A12 = convert(Matrix{elty}, [1 -1; 1 -1]) - @test typeof(logm(A12)) == Array{Complex{Float64}, 2} - - A1 = convert(Matrix{elty}, [4 2 0; 1 4 1; 1 1 4]) - logmA1 = convert(Matrix{elty}, [1.329661349 0.5302876358 -0.06818951543; - 0.2310490602 1.295566591 0.2651438179; - 0.2310490602 0.1969543025 1.363756107]) - @test logm(A1) ≈ logmA1 - @test expm(logm(A1)) ≈ A1 - - A4 = convert(Matrix{elty}, [1/2 1/3 1/4 1/5+eps(); - 1/3 1/4 1/5 1/6; - 1/4 1/5 1/6 1/7; - 1/5 1/6 1/7 1/8]) - logmA4 = convert(Matrix{elty}, [-1.73297159 1.857349738 0.4462766564 0.2414170219; - 1.857349738 -5.335033737 2.994142974 0.5865285289; - 0.4462766564 2.994142974 -7.351095988 3.318413247; - 0.2414170219 0.5865285289 3.318413247 -5.444632124]) - @test logm(A4) ≈ logmA4 - @test expm(logm(A4)) ≈ A4 -end - -@testset "issue #7181" begin - A = [ 1 5 9 - 2 6 10 - 3 7 11 - 4 8 12 ] - @test_throws ArgumentError diag(A, -5) - @test diag(A,-4) == [] - @test diag(A,-3) == [4] - @test diag(A,-2) == [3,8] - @test diag(A,-1) == [2,7,12] - @test diag(A, 0) == [1,6,11] - @test diag(A, 1) == [5,10] - @test diag(A, 2) == [9] - @test diag(A, 3) == [] - @test_throws ArgumentError diag(A, 4) - - @test diag(zeros(0,0)) == [] - @test_throws ArgumentError diag(zeros(0,0),1) - @test_throws ArgumentError diag(zeros(0,0),-1) - - @test diag(zeros(1,0)) == [] - @test diag(zeros(1,0),-1) == [] - @test_throws ArgumentError diag(zeros(1,0),1) - @test_throws ArgumentError diag(zeros(1,0),-2) - - @test diag(zeros(0,1)) == [] - @test diag(zeros(0,1),1) == [] - @test_throws ArgumentError diag(zeros(0,1),-1) - @test_throws ArgumentError diag(zeros(0,1),2) -end - -@testset "Matrix to real power" for elty in (Float64, Complex{Float64}) -# Tests proposed at Higham, Deadman: Testing Matrix Function Algorithms Using Identities, March 2014 - #Aa : only positive real eigenvalues - Aa = convert(Matrix{elty}, [5 4 2 1; 0 1 -1 -1; -1 -1 3 0; 1 1 -1 2]) - - @test Aa^(1/2) ≈ sqrtm(Aa) - @test Aa^(-1/2) ≈ inv(sqrtm(Aa)) - @test Aa^(3/4) ≈ sqrtm(Aa) * sqrtm(sqrtm(Aa)) - @test Aa^(-3/4) ≈ inv(Aa) * sqrtm(sqrtm(Aa)) - @test Aa^(17/8) ≈ Aa^2 * sqrtm(sqrtm(sqrtm(Aa))) - @test Aa^(-17/8) ≈ inv(Aa^2 * sqrtm(sqrtm(sqrtm(Aa)))) - @test (Aa^0.2)^5 ≈ Aa - @test (Aa^(2/3))*(Aa^(1/3)) ≈ Aa - @test (Aa^im)^(-im) ≈ Aa - - #Ab : both positive and negative real eigenvalues - Ab = convert(Matrix{elty}, [1 2 3; 4 7 1; 2 1 4]) - - @test Ab^(1/2) ≈ sqrtm(Ab) - @test Ab^(-1/2) ≈ inv(sqrtm(Ab)) - @test Ab^(3/4) ≈ sqrtm(Ab) * sqrtm(sqrtm(Ab)) - @test Ab^(-3/4) ≈ inv(Ab) * sqrtm(sqrtm(Ab)) - @test Ab^(17/8) ≈ Ab^2 * sqrtm(sqrtm(sqrtm(Ab))) - @test Ab^(-17/8) ≈ inv(Ab^2 * sqrtm(sqrtm(sqrtm(Ab)))) - @test (Ab^0.2)^5 ≈ Ab - @test (Ab^(2/3))*(Ab^(1/3)) ≈ Ab - @test (Ab^im)^(-im) ≈ Ab - - #Ac : complex eigenvalues - Ac = convert(Matrix{elty}, [5 4 2 1;0 1 -1 -1;-1 -1 3 6;1 1 -1 5]) - - @test Ac^(1/2) ≈ sqrtm(Ac) - @test Ac^(-1/2) ≈ inv(sqrtm(Ac)) - @test Ac^(3/4) ≈ sqrtm(Ac) * sqrtm(sqrtm(Ac)) - @test Ac^(-3/4) ≈ inv(Ac) * sqrtm(sqrtm(Ac)) - @test Ac^(17/8) ≈ Ac^2 * sqrtm(sqrtm(sqrtm(Ac))) - @test Ac^(-17/8) ≈ inv(Ac^2 * sqrtm(sqrtm(sqrtm(Ac)))) - @test (Ac^0.2)^5 ≈ Ac - @test (Ac^(2/3))*(Ac^(1/3)) ≈ Ac - @test (Ac^im)^(-im) ≈ Ac - - #Ad : defective Matrix - Ad = convert(Matrix{elty}, [3 1; 0 3]) - - @test Ad^(1/2) ≈ sqrtm(Ad) - @test Ad^(-1/2) ≈ inv(sqrtm(Ad)) - @test Ad^(3/4) ≈ sqrtm(Ad) * sqrtm(sqrtm(Ad)) - @test Ad^(-3/4) ≈ inv(Ad) * sqrtm(sqrtm(Ad)) - @test Ad^(17/8) ≈ Ad^2 * sqrtm(sqrtm(sqrtm(Ad))) - @test Ad^(-17/8) ≈ inv(Ad^2 * sqrtm(sqrtm(sqrtm(Ad)))) - @test (Ad^0.2)^5 ≈ Ad - @test (Ad^(2/3))*(Ad^(1/3)) ≈ Ad - @test (Ad^im)^(-im) ≈ Ad -end - -@testset "Least squares solutions" begin - a = [ones(20) 1:20 1:20] - b = reshape(eye(8, 5), 20, 2) - @testset "Tests for type $elty" for elty in (Float32, Float64, Complex64, Complex128) - a = convert(Matrix{elty}, a) - b = convert(Matrix{elty}, b) - - # Vector rhs - x = a[:,1:2]\b[:,1] - @test ((a[:,1:2]*x-b[:,1])'*(a[:,1:2]*x-b[:,1]))[1] ≈ convert(elty, 2.546616541353384) - - # Matrix rhs - x = a[:,1:2]\b - @test det((a[:,1:2]*x-b)'*(a[:,1:2]*x-b)) ≈ convert(elty, 4.437969924812031) - - # Rank deficient - x = a\b - @test det((a*x-b)'*(a*x-b)) ≈ convert(elty, 4.437969924812031) - - # Underdetermined minimum norm - x = convert(Matrix{elty}, [1 0 0; 0 1 -1]) \ convert(Vector{elty}, [1,1]) - @test x ≈ convert(Vector{elty}, [1, 0.5, -0.5]) - - # symmetric, positive definite - @test inv(convert(Matrix{elty}, [6. 2; 2 1])) ≈ convert(Matrix{elty}, [0.5 -1; -1 3]) - - # symmetric, indefinite - @test inv(convert(Matrix{elty}, [1. 2; 2 1])) ≈ convert(Matrix{elty}, [-1. 2; 2 -1]/3) - end -end - -@testset "test ops on Numbers for $elty" for elty in [Float32,Float64,Complex64,Complex128] - a = rand(elty) - @test expm(a) == exp(a) - @test isposdef(one(elty)) - @test sqrtm(a) == sqrt(a) - @test logm(a) ≈ log(a) - @test lyap(one(elty),a) == -a/2 -end - -@testset "stride1" begin - a = rand(10) - b = view(a,2:2:10) - @test Base.LinAlg.stride1(b) == 2 -end diff --git a/julia-0.6.3/share/julia/test/linalg/diagonal.jl b/julia-0.6.3/share/julia/test/linalg/diagonal.jl deleted file mode 100644 index 562070e..0000000 --- a/julia-0.6.3/share/julia/test/linalg/diagonal.jl +++ /dev/null @@ -1,370 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -using Base.Test -import Base.LinAlg: BlasFloat, BlasComplex, SingularException - -n=12 #Size of matrix problem to test -srand(1) - -@testset for relty in (Float32, Float64, BigFloat), elty in (relty, Complex{relty}) - d=convert(Vector{elty}, randn(n)) - v=convert(Vector{elty}, randn(n)) - U=convert(Matrix{elty}, randn(n,n)) - if elty <: Complex - d+=im*convert(Vector{elty}, randn(n)) - v+=im*convert(Vector{elty}, randn(n)) - U+=im*convert(Matrix{elty}, randn(n,n)) - end - D = Diagonal(d) - DM = diagm(d) - @testset "Basic properties" begin - @test eye(Diagonal{elty},n) == Diagonal(ones(elty,n)) - @test_throws ArgumentError size(D,0) - @test typeof(convert(Diagonal{Complex64},D)) == Diagonal{Complex64} - @test typeof(convert(AbstractMatrix{Complex64},D)) == Diagonal{Complex64} - - @test Array(real(D)) == real(DM) - @test Array(abs.(D)) == abs.(DM) - @test Array(imag(D)) == imag(DM) - - @test parent(D) == d - @test diag(D) == d - @test D[1,1] == d[1] - @test D[1,2] == 0 - - @test issymmetric(D) - @test istriu(D) - @test istril(D) - if elty <: Real - @test ishermitian(D) - end - end - - @testset "Simple unary functions" begin - for op in (-,) - @test op(D)==op(DM) - end - - for func in (det, trace) - @test func(D) ≈ func(DM) atol=n^2*eps(relty)*(1+(elty<:Complex)) - end - if relty <: BlasFloat - for func in (expm,) - @test func(D) ≈ func(DM) atol=n^3*eps(relty) - end - @test logm(Diagonal(abs.(D.diag))) ≈ logm(abs.(DM)) atol=n^3*eps(relty) - end - if elty <: BlasComplex - for func in (logdet, sqrtm) - @test func(D) ≈ func(DM) atol=n^2*eps(relty)*2 - end - end - end - - @testset "Linear solve" begin - let vv = v, UU = U - @testset for atype in ("Array", "SubArray") - if atype == "Array" - v = vv - U = UU - else - v = view(vv, 1:n) - U = view(UU, 1:n, 1:2) - end - - @test D*v ≈ DM*v atol=n*eps(relty)*(1+(elty<:Complex)) - @test D*U ≈ DM*U atol=n^2*eps(relty)*(1+(elty<:Complex)) - - @test U.'*D ≈ U.'*Array(D) - @test U'*D ≈ U'*Array(D) - - if relty != BigFloat - @test D\v ≈ DM\v atol=2n^2*eps(relty)*(1+(elty<:Complex)) - @test D\U ≈ DM\U atol=2n^3*eps(relty)*(1+(elty<:Complex)) - @test A_ldiv_B!(D,copy(v)) ≈ DM\v atol=2n^2*eps(relty)*(1+(elty<:Complex)) - @test A_ldiv_B!(D,copy(U)) ≈ DM\U atol=2n^3*eps(relty)*(1+(elty<:Complex)) - @test A_ldiv_B!(D,eye(D)) ≈ D\eye(D) atol=2n^3*eps(relty)*(1+(elty<:Complex)) - @test_throws DimensionMismatch A_ldiv_B!(D, ones(elty, n + 1)) - @test_throws SingularException A_ldiv_B!(Diagonal(zeros(relty,n)),copy(v)) - b = rand(elty,n,n) - b = sparse(b) - @test A_ldiv_B!(D,copy(b)) ≈ Array(D)\Array(b) - @test_throws SingularException A_ldiv_B!(Diagonal(zeros(elty,n)),copy(b)) - b = view(rand(elty,n),collect(1:n)) - b2 = copy(b) - c = A_ldiv_B!(D,b) - d = Array(D)\b2 - for i in 1:n - @test c[i] ≈ d[i] - end - @test_throws SingularException A_ldiv_B!(Diagonal(zeros(elty,n)),b) - b = rand(elty,n+1,n+1) - b = sparse(b) - @test_throws DimensionMismatch A_ldiv_B!(D,copy(b)) - b = view(rand(elty,n+1),collect(1:n+1)) - @test_throws DimensionMismatch A_ldiv_B!(D,b) - end - end - end - end - d = convert(Vector{elty}, randn(n)) - D2 = Diagonal(d) - DM2= diagm(d) - @testset "Binary operations" begin - for op in (+, -, *) - @test Array(op(D, D2)) ≈ op(DM, DM2) - end - @testset "with plain numbers" begin - a = rand() - @test Array(a*D) ≈ a*DM - @test Array(D*a) ≈ DM*a - @test Array(D/a) ≈ DM/a - if relty <: BlasFloat - b = rand(elty,n,n) - b = sparse(b) - @test A_mul_B!(copy(D), copy(b)) ≈ Array(D)*Array(b) - @test At_mul_B!(copy(D), copy(b)) ≈ Array(D).'*Array(b) - @test Ac_mul_B!(copy(D), copy(b)) ≈ Array(D)'*Array(b) - end - end - - #a few missing mults - bd = Bidiagonal(D2) - @test D*D2.' ≈ Array(D)*Array(D2).' - @test D2*D.' ≈ Array(D2)*Array(D).' - @test D2*D' ≈ Array(D2)*Array(D)' - - #division of two Diagonals - @test D/D2 ≈ Diagonal(D.diag./D2.diag) - @test D\D2 ≈ Diagonal(D2.diag./D.diag) - - # Performance specialisations for A*_mul_B! - vv = similar(v) - @test (r = full(D) * v ; A_mul_B!(vv, D, v) ≈ r ≈ vv) - @test (r = full(D)' * v ; Ac_mul_B!(vv, D, v) ≈ r ≈ vv) - @test (r = full(D).' * v ; At_mul_B!(vv, D, v) ≈ r ≈ vv) - - UU = similar(U) - @test (r = full(D) * U ; A_mul_B!(UU, D, U) ≈ r ≈ UU) - @test (r = full(D)' * U ; Ac_mul_B!(UU, D, U) ≈ r ≈ UU) - @test (r = full(D).' * U ; At_mul_B!(UU, D, U) ≈ r ≈ UU) - end - @testset "triu/tril" begin - @test istriu(D) - @test istril(D) - @test triu(D,1) == zeros(D) - @test triu(D,0) == D - @test triu(D,-1) == D - @test tril(D,1) == D - @test tril(D,-1) == zeros(D) - @test tril(D,0) == D - @test_throws ArgumentError tril(D,n+1) - @test_throws ArgumentError triu(D,n+1) - end - - # factorize - @test factorize(D) == D - - @testset "Eigensystem" begin - eigD = eigfact(D) - @test Diagonal(eigD[:values]) ≈ D - @test eigD[:vectors] == eye(D) - end - - @testset "ldiv" begin - v = rand(n + 1) - @test_throws DimensionMismatch D\v - v = rand(n) - @test D\v ≈ DM\v - V = rand(n + 1, n) - @test_throws DimensionMismatch D\V - V = rand(n, n) - @test D\V ≈ DM\V - end - - @testset "conj and transpose" begin - @test transpose(D) == D - if elty <: BlasComplex - @test Array(conj(D)) ≈ conj(DM) - @test ctranspose(D) == conj(D) - end - # Translates to Ac/t_mul_B, which is specialized after issue 21286 - @test(D' * v == conj(D) * v) - @test(D.' * v == D * v) - end - - #logdet - if relty <: Real - ld=convert(Vector{relty},rand(n)) - @test logdet(Diagonal(ld)) ≈ logdet(diagm(ld)) - end - - @testset "similar" begin - @test isa(similar(D), Diagonal{elty}) - @test isa(similar(D, Int), Diagonal{Int}) - @test isa(similar(D, (3,2)), Matrix{elty}) - @test isa(similar(D, Int, (3,2)), Matrix{Int}) - end - - # Issue number 10036 - # make sure issymmetric/ishermitian work for - # non-real diagonal matrices - @testset "issymmetric/hermitian for complex Diagonal" begin - @test issymmetric(D2) - @test ishermitian(D2) - if elty <: Complex - dc = d + im*convert(Vector{elty}, ones(n)) - D3 = Diagonal(dc) - @test issymmetric(D3) - @test !ishermitian(D3) - end - end - - @testset "svd (#11120/#11247)" begin - U, s, V = svd(D) - @test (U*Diagonal(s))*V' ≈ D - @test svdvals(D) == s - @test svdfact(D)[:V] == V - end -end - -@testset "svdvals and eigvals (#11120/#11247)" begin - D = Diagonal(Matrix{Float64}[randn(3,3), randn(2,2)]) - @test sort([svdvals(D)...;], rev = true) ≈ svdvals([D.diag[1] zeros(3,2); zeros(2,3) D.diag[2]]) - @test [eigvals(D)...;] ≈ eigvals([D.diag[1] zeros(3,2); zeros(2,3) D.diag[2]]) -end - -@testset "isposdef" begin - @test !isposdef(Diagonal(-1.0 * rand(n))) -end - -@testset "getindex" begin - d = randn(n) - D = Diagonal(d) - # getindex bounds checking - @test_throws BoundsError D[0, 0] - @test_throws BoundsError D[-1, -2] - @test_throws BoundsError D[n, n + 1] - @test_throws BoundsError D[n + 1, n] - @test_throws BoundsError D[n + 1, n + 1] - # getindex on and off the diagonal - for i in 1:n, j in 1:n - @test D[i, j] == (i == j ? d[i] : 0) - end -end - -@testset "setindex!" begin - d = randn(n) - D = Diagonal(d) - # setindex! bounds checking - @test_throws BoundsError D[0, 0] = 0 - @test_throws BoundsError D[-1 , -2] = 0 - @test_throws BoundsError D[n, n + 1] = 0 - @test_throws BoundsError D[n + 1, n] = 0 - @test_throws BoundsError D[n + 1, n + 1] = 0 - for i in 1:n, j in 1:n - if i == j - # setindex on! the diagonal - @test ((D[i, j] = i) == i; D[i, j] == i) - else - # setindex! off the diagonal - @test ((D[i, j] = 0) == 0; iszero(D[i, j])) - @test_throws ArgumentError D[i, j] = 1 - end - end -end - -@testset "inverse" begin - for d in (randn(n), [1, 2, 3], [1im, 2im, 3im]) - D = Diagonal(d) - @test inv(D) ≈ inv(Array(D)) - end - @test_throws SingularException inv(Diagonal(zeros(n))) - @test_throws SingularException inv(Diagonal([0, 1, 2])) - @test_throws SingularException inv(Diagonal([0im, 1im, 2im])) -end - -# allow construct from range -@test Diagonal(linspace(1,3,3)) == Diagonal([1.,2.,3.]) - -# Issue 12803 -for t in (Float32, Float64, Int, Complex{Float64}, Rational{Int}) - @test Diagonal(Matrix{t}[ones(t, 2, 2), ones(t, 3, 3)])[2,1] == zeros(t, 3, 2) -end - -# Issue 15401 -@test eye(5) \ Diagonal(ones(5)) == eye(5) - -@testset "Triangular and Diagonal" begin - for T in (LowerTriangular(randn(5,5)), LinAlg.UnitLowerTriangular(randn(5,5))) - D = Diagonal(randn(5)) - @test T*D == Array(T)*Array(D) - @test T'D == Array(T)'*Array(D) - @test T.'D == Array(T).'*Array(D) - @test D*T' == Array(D)*Array(T)' - @test D*T.' == Array(D)*Array(T).' - @test D*T == Array(D)*Array(T) - end -end - -let D1 = Diagonal(rand(5)), D2 = Diagonal(rand(5)) - @test_throws MethodError A_mul_B!(D1,D2) - @test_throws MethodError At_mul_B!(D1,D2) - @test_throws MethodError Ac_mul_B!(D1,D2) -end - -@testset "multiplication of QR Q-factor and Diagonal (#16615 spot test)" begin - D = Diagonal(randn(5)) - Q = qrfact(randn(5, 5))[:Q] - @test D * Q' == Array(D) * Q' -end - -@testset "block diagonal matrices" begin - D = Diagonal([[1 2; 3 4], [1 2; 3 4]]) - Dherm = Diagonal([[1 1+im; 1-im 1], [1 1+im; 1-im 1]]) - Dsym = Diagonal([[1 1+im; 1+im 1], [1 1+im; 1+im 1]]) - @test D' == Diagonal([[1 3; 2 4], [1 3; 2 4]]) - @test D.' == Diagonal([[1 3; 2 4], [1 3; 2 4]]) - @test Dherm' == Dherm - @test Dherm.' == Diagonal([[1 1-im; 1+im 1], [1 1-im; 1+im 1]]) - @test Dsym' == Diagonal([[1 1-im; 1-im 1], [1 1-im; 1-im 1]]) - @test Dsym.' == Dsym - - v = [[1, 2], [3, 4]] - @test Dherm' * v == Dherm * v - @test D.' * v == [[7, 10], [15, 22]] - - @test issymmetric(D) == false - @test issymmetric(Dherm) == false - @test issymmetric(Dsym) == true - - @test ishermitian(D) == false - @test ishermitian(Dherm) == true - @test ishermitian(Dsym) == false - - @test expm(D) == Diagonal([expm([1 2; 3 4]), expm([1 2; 3 4])]) - @test logm(D) == Diagonal([logm([1 2; 3 4]), logm([1 2; 3 4])]) - @test sqrtm(D) == Diagonal([sqrtm([1 2; 3 4]), sqrtm([1 2; 3 4])]) -end - -@testset "multiplication with Symmetric/Hermitian" begin - for T in (Float64, Complex128) - if T <: Complex - R = Float64 - D = Diagonal(complex.(randn(R, n), randn(R, n))) - A = complex.(randn(R, n, n), randn(R, n, n)) - else - D = Diagonal(randn(T, n)) - A = randn(T, n, n) - end - A = A'A - S = Symmetric(A) - H = Hermitian(A) - for f in (*, Ac_mul_B, A_mul_Bc, Ac_mul_Bc, At_mul_B, A_mul_Bt, At_mul_Bt) - @test f(D, S) ≈ f(Matrix(D), Matrix(S)) - @test f(D, H) ≈ f(Matrix(D), Matrix(H)) - @test f(S, D) ≈ f(Matrix(S), Matrix(D)) - @test f(S, H) ≈ f(Matrix(S), Matrix(H)) - end - end -end diff --git a/julia-0.6.3/share/julia/test/linalg/eigen.jl b/julia-0.6.3/share/julia/test/linalg/eigen.jl deleted file mode 100644 index c44563e..0000000 --- a/julia-0.6.3/share/julia/test/linalg/eigen.jl +++ /dev/null @@ -1,121 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -using Base.Test - -using Base.LinAlg: BlasComplex, BlasFloat, BlasReal, QRPivoted - -n = 10 - -# Split n into 2 parts for tests needing two matrices -n1 = div(n, 2) -n2 = 2*n1 - -srand(1234321) - -areal = randn(n,n)/2 -aimg = randn(n,n)/2 - -@testset for eltya in (Float32, Float64, Complex64, Complex128, Int) - aa = eltya == Int ? rand(1:7, n, n) : convert(Matrix{eltya}, eltya <: Complex ? complex.(areal, aimg) : areal) - asym = aa'+aa # symmetric indefinite - apd = aa'*aa # symmetric positive-definite - @testset for atype in ("Array", "SubArray") - if atype == "Array" - a = aa - else - a = view(aa, 1:n, 1:n) - asym = view(asym, 1:n, 1:n) - apd = view(apd, 1:n, 1:n) - end - ε = εa = eps(abs(float(one(eltya)))) - - α = rand(eltya) - β = rand(eltya) - eab = eig(α,β) - @test eab[1] == eigvals(fill(α,1,1),fill(β,1,1)) - @test eab[2] == eigvecs(fill(α,1,1),fill(β,1,1)) - - d,v = eig(a) - @testset "non-symmetric eigen decomposition" begin - for i in 1:size(a,2) - @test a*v[:,i] ≈ d[i]*v[:,i] - end - f = eigfact(a) - @test det(a) ≈ det(f) - @test inv(a) ≈ inv(f) - @test eigvals(f) === f[:values] - @test eigvecs(f) === f[:vectors] - - num_fact = eigfact(one(eltya)) - @test num_fact.values[1] == one(eltya) - h = asym - @test minimum(eigvals(h)) ≈ eigmin(h) - @test maximum(eigvals(h)) ≈ eigmax(h) - @test_throws DomainError eigmin(a - a') - @test_throws DomainError eigmax(a - a') - end - @testset "symmetric generalized eigenproblem" begin - if atype == "Array" - asym_sg = asym[1:n1, 1:n1] - a_sg = a[:,n1+1:n2] - else - asym_sg = view(asym, 1:n1, 1:n1) - a_sg = view(a, 1:n, n1+1:n2) - end - f = eigfact(asym_sg, a_sg'a_sg) - @test asym_sg*f[:vectors] ≈ (a_sg'a_sg*f[:vectors]) * Diagonal(f[:values]) - @test f[:values] ≈ eigvals(asym_sg, a_sg'a_sg) - @test prod(f[:values]) ≈ prod(eigvals(asym_sg/(a_sg'a_sg))) atol=200ε - @test eigvecs(asym_sg, a_sg'a_sg) == f[:vectors] - @test eigvals(f) === f[:values] - @test eigvecs(f) === f[:vectors] - @test_throws KeyError f[:Z] - - d,v = eig(asym_sg, a_sg'a_sg) - @test d == f[:values] - @test v == f[:vectors] - end - @testset "Non-symmetric generalized eigenproblem" begin - if atype == "Array" - a1_nsg = a[1:n1, 1:n1] - a2_nsg = a[n1+1:n2, n1+1:n2] - else - a1_nsg = view(a, 1:n1, 1:n1) - a2_nsg = view(a, n1+1:n2, n1+1:n2) - end - f = eigfact(a1_nsg, a2_nsg) - @test a1_nsg*f[:vectors] ≈ (a2_nsg*f[:vectors]) * Diagonal(f[:values]) - @test f[:values] ≈ eigvals(a1_nsg, a2_nsg) - @test prod(f[:values]) ≈ prod(eigvals(a1_nsg/a2_nsg)) atol=50000ε - @test eigvecs(a1_nsg, a2_nsg) == f[:vectors] - @test_throws KeyError f[:Z] - - d,v = eig(a1_nsg, a2_nsg) - @test d == f[:values] - @test v == f[:vectors] - end - end -end - -@testset "eigenvalue computations with NaNs" begin - for eltya in (NaN16, NaN32, NaN) - @test_throws(ArgumentError, eig(fill(eltya, 1, 1))) - @test_throws(ArgumentError, eig(fill(eltya, 2, 2))) - test_matrix = rand(typeof(eltya),3,3) - test_matrix[2,2] = eltya - @test_throws(ArgumentError, eig(test_matrix)) - end -end - -# test a matrix larger than 140-by-140 for #14174 -let aa = rand(200, 200) - for atype in ("Array", "SubArray") - if atype == "Array" - a = aa - else - a = view(aa, 1:n, 1:n) - end - f = eigfact(a) - @test a ≈ f[:vectors] * Diagonal(f[:values]) / f[:vectors] - end -end diff --git a/julia-0.6.3/share/julia/test/linalg/generic.jl b/julia-0.6.3/share/julia/test/linalg/generic.jl deleted file mode 100644 index 89fa709..0000000 --- a/julia-0.6.3/share/julia/test/linalg/generic.jl +++ /dev/null @@ -1,312 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -import Base: -, *, /, \ -using Base.Test - -# A custom Quaternion type with minimal defined interface and methods. -# Used to test scale and scale! methods to show non-commutativity. -struct Quaternion{T<:Real} <: Number - s::T - v1::T - v2::T - v3::T -end -Quaternion(s::Real, v1::Real, v2::Real, v3::Real) = Quaternion(promote(s, v1, v2, v3)...) -Base.abs2(q::Quaternion) = q.s*q.s + q.v1*q.v1 + q.v2*q.v2 + q.v3*q.v3 -Base.abs(q::Quaternion) = sqrt(abs2(q)) -Base.real{T}(::Type{Quaternion{T}}) = T -Base.conj(q::Quaternion) = Quaternion(q.s, -q.v1, -q.v2, -q.v3) -Base.isfinite(q::Quaternion) = isfinite(q.s) & isfinite(q.v1) & isfinite(q.v2) & isfinite(q.v3) - -(-)(ql::Quaternion, qr::Quaternion) = - Quaternion(ql.s - qr.s, ql.v1 - qr.v1, ql.v2 - qr.v2, ql.v3 - qr.v3) -(*)(q::Quaternion, w::Quaternion) = Quaternion(q.s*w.s - q.v1*w.v1 - q.v2*w.v2 - q.v3*w.v3, - q.s*w.v1 + q.v1*w.s + q.v2*w.v3 - q.v3*w.v2, - q.s*w.v2 - q.v1*w.v3 + q.v2*w.s + q.v3*w.v1, - q.s*w.v3 + q.v1*w.v2 - q.v2*w.v1 + q.v3*w.s) -(*)(q::Quaternion, r::Real) = Quaternion(q.s*r, q.v1*r, q.v2*r, q.v3*r) -(*)(q::Quaternion, b::Bool) = b * q # remove method ambiguity -(/)(q::Quaternion, w::Quaternion) = q * conj(w) * (1.0 / abs2(w)) -(\)(q::Quaternion, w::Quaternion) = conj(q) * w * (1.0 / abs2(q)) - -debug = false - -srand(123) - -n = 5 # should be odd - -for elty in (Int, Rational{BigInt}, Float32, Float64, BigFloat, Complex{Float32}, Complex{Float64}, Complex{BigFloat}) - if elty <: Int - A = rand(-n:n, n, n) + 10I - elseif elty <: Rational - A = Rational{BigInt}[rand(-n:n)/rand(1:n) for i = 1:n, j = 1:n] + 10I - elseif elty <: Real - A = convert(Matrix{elty}, randn(n,n)) + 10I - else - A = convert(Matrix{elty}, complex.(randn(n,n), randn(n,n))) - end - - debug && println("element type: $elty") - - @test logdet(A) ≈ log(det(A)) - @test logabsdet(A)[1] ≈ log(abs(det(A))) - @test logabsdet(convert(Matrix{elty}, -eye(n)))[2] == -1 - if elty <: Real - @test logabsdet(A)[2] == sign(det(A)) - @test_throws DomainError logdet(convert(Matrix{elty}, -eye(n))) - else - @test logabsdet(A)[2] ≈ sign(det(A)) - end -end - -# test diff, throw ArgumentError for invalid dimension argument -let X = [3 9 5; - 7 4 2; - 2 1 10] - @test diff(X,1) == [4 -5 -3; -5 -3 8] - @test diff(X,2) == [6 -4; -3 -2; -1 9] - @test diff(view(X, 1:2, 1:2),1) == [4 -5] - @test diff(view(X, 1:2, 1:2),2) == reshape([6; -3], (2,1)) - @test diff(view(X, 2:3, 2:3),1) == [-3 8] - @test diff(view(X, 2:3, 2:3),2) == reshape([-2; 9], (2,1)) - @test_throws ArgumentError diff(X,3) - @test_throws ArgumentError diff(X,-1) -end - -# test linrange -# make sure unequal input arrays throw an error -x = [2; 5; 6] -y = [3; 7; 10; 10] -@test_throws DimensionMismatch linreg(x, y) -x = [2 5 6] -y = [3; 7; 10] -@test_throws MethodError linreg(x, y) - -# check (UnitRange, Array) -x = 1:12 -y = [5.5; 6.3; 7.6; 8.8; 10.9; 11.79; 13.48; 15.02; 17.77; 20.81; 22.0; 22.99] -@test [linreg(x,y)...] ≈ [2.5559090909090867, 1.6960139860139862] -@test [linreg(view(x,1:6),view(y,1:6))...] ≈ [3.8366666666666642,1.3271428571428574] - -# check (LinSpace, UnitRange) -x = linspace(1.0, 12.0, 100) -y = -100:-1 -@test [linreg(x, y)...] ≈ [-109.0, 9.0] - -# check (UnitRange, UnitRange) -x = 1:12 -y = 12:-1:1 -@test [linreg(x, y)...] ≈ [13.0, -1.0] - -# check (LinSpace, LinSpace) -x = linspace(-5, 10, 100) -y = linspace(50, 200, 100) -@test [linreg(x, y)...] ≈ [100.0, 10.0] - -# check (Array, Array) -# Anscombe's quartet (https://en.wikipedia.org/wiki/Anscombe%27s_quartet) -x123 = [10.0; 8.0; 13.0; 9.0; 11.0; 14.0; 6.0; 4.0; 12.0; 7.0; 5.0] -y1 = [8.04; 6.95; 7.58; 8.81; 8.33; 9.96; 7.24; 4.26; 10.84; 4.82; 5.68] -@test [linreg(x123,y1)...] ≈ [3.0,0.5] atol=15e-5 - -y2 = [9.14; 8.14; 8.74; 8.77; 9.26; 8.10; 6.12; 3.10; 9.13; 7.26; 4.74] -@test [linreg(x123,y2)...] ≈ [3.0,0.5] atol=10e-3 - -y3 = [7.46; 6.77; 12.74; 7.11; 7.81; 8.84; 6.08; 5.39; 8.15; 6.42; 5.73] -@test [linreg(x123,y3)...] ≈ [3.0,0.5] atol=10e-3 - -x4 = [8.0; 8.0; 8.0; 8.0; 8.0; 8.0; 8.0; 19.0; 8.0; 8.0; 8.0] -y4 = [6.58; 5.76; 7.71; 8.84; 8.47; 7.04; 5.25; 12.50; 5.56; 7.91; 6.89] -@test [linreg(x4,y4)...] ≈ [3.0,0.5] atol=10e-3 - -# test diag -let A = eye(4) - @test diag(A) == ones(4) - @test diag(view(A, 1:3, 1:3)) == ones(3) - @test diag(view(A, 1:2, 1:2)) == ones(2) -end - -# test generic axpy -x = ['a','b','c','d','e'] -y = ['a','b','c','d','e'] -α = 'f' -@test_throws DimensionMismatch Base.LinAlg.axpy!(α,x,['g']) -@test_throws BoundsError Base.LinAlg.axpy!(α,x,collect(-1:5),y,collect(1:7)) -@test_throws BoundsError Base.LinAlg.axpy!(α,x,collect(1:7),y,collect(-1:5)) -@test_throws BoundsError Base.LinAlg.axpy!(α,x,collect(1:7),y,collect(1:7)) -@test_throws DimensionMismatch Base.LinAlg.axpy!(α,x,collect(1:3),y,collect(1:5)) - -@test_throws ArgumentError diag(rand(10)) -@test !issymmetric(ones(5,3)) -@test !ishermitian(ones(5,3)) -@test cross(ones(3),ones(3)) == zeros(3) - -@test trace(Bidiagonal(ones(5),zeros(4),true)) == 5 - - -# array and subarray tests -let aa = reshape([1.:6;], (2,3)) - for atype in ("Array", "SubArray") - if atype == "Array" - a = aa - else - a = view(aa, 1:2, 1:2) - end - - # 2-argument version of scale! - @test scale!(copy(a), 5.) == a*5 - @test scale!(5., copy(a)) == a*5 - b = randn(Base.LinAlg.SCAL_CUTOFF) # make sure we try BLAS path - subB = view(b, :, :) - @test scale!(copy(b), 5.) == b*5 - @test scale!(copy(subB), 5.) == subB*5 - @test scale!([1.; 2.], copy(a)) == a.*[1; 2] - @test scale!([1; 2], copy(a)) == a.*[1; 2] - @test_throws DimensionMismatch scale!(ones(3), a) - - if atype == "Array" - @test scale!(copy(a), [1.; 2.; 3.]) == a.*[1 2 3] - @test scale!(copy(a), [1; 2; 3]) == a.*[1 2 3] - @test_throws DimensionMismatch scale!(a, ones(2)) - else - @test scale!(copy(a), [1.; 2.]) == a.*[1 2] - @test scale!(copy(a), [1; 2]) == a.*[1 2] - @test_throws DimensionMismatch scale!(a, ones(3)) - end - - # 3-argument version of scale! - @test scale!(similar(a), 5., a) == a*5 - @test scale!(similar(a), a, 5.) == a*5 - @test scale!(similar(a), [1.; 2.], a) == a.*[1; 2] - @test scale!(similar(a), [1; 2], a) == a.*[1; 2] - @test_throws DimensionMismatch scale!(similar(a), ones(3), a) - @test_throws DimensionMismatch scale!(Array{Float64}(3, 2), a, ones(3)) - - if atype == "Array" - @test scale!(similar(a), a, [1.; 2.; 3.]) == a.*[1 2 3] - @test scale!(similar(a), a, [1; 2; 3]) == a.*[1 2 3] - @test_throws DimensionMismatch scale!(similar(a), a, ones(2)) - else - @test scale!(similar(a), a, [1.; 2.]) == a.*[1 2] - @test scale!(similar(a), a, [1; 2]) == a.*[1 2] - @test_throws DimensionMismatch scale!(similar(a), a, ones(3)) - end - end -end - -# scale real matrix by complex type -@test_throws InexactError scale!([1.0], 2.0im) -@test isequal([1.0] * 2.0im, Complex{Float64}[2.0im]) -@test isequal(2.0im * [1.0], Complex{Float64}[2.0im]) -@test isequal(Float32[1.0] * 2.0f0im, Complex{Float32}[2.0im]) -@test isequal(Float32[1.0] * 2.0im, Complex{Float64}[2.0im]) -@test isequal(Float64[1.0] * 2.0f0im, Complex{Float64}[2.0im]) -@test isequal(Float32[1.0] * big(2.0)im, Complex{BigFloat}[2.0im]) -@test isequal(Float64[1.0] * big(2.0)im, Complex{BigFloat}[2.0im]) -@test isequal(BigFloat[1.0] * 2.0im, Complex{BigFloat}[2.0im]) -@test isequal(BigFloat[1.0] * 2.0f0im, Complex{BigFloat}[2.0im]) - -# test scale and scale! for non-commutative multiplication -q = Quaternion(0.44567, 0.755871, 0.882548, 0.423612) -qmat = [Quaternion(0.015007, 0.355067, 0.418645, 0.318373)] -@test scale!(q, copy(qmat)) != scale!(copy(qmat), q) -## Test * because it doesn't dispatch to scale! -@test q*qmat ≉ qmat*q -@test conj(q*qmat) ≈ conj(qmat)*conj(q) -@test q * (q \ qmat) ≈ qmat ≈ (qmat / q) * q -@test q\qmat ≉ qmat/q - -# test ops on Numbers -for elty in [Float32,Float64,Complex64,Complex128] - a = rand(elty) - @test trace(a) == a - @test rank(zero(elty)) == 0 - @test rank(one(elty)) == 1 - @test !isfinite(cond(zero(elty))) - @test cond(a) == one(elty) - @test cond(a,1) == one(elty) - @test issymmetric(a) - @test ishermitian(one(elty)) - @test det(a) == a -end - -@test !issymmetric(NaN16) -@test !issymmetric(NaN32) -@test !issymmetric(NaN) - -@test rank([1.0 0.0; 0.0 0.9],0.95) == 1 -@test qr(big.([0 1; 0 0]))[2] == [0 1; 0 0] - -@test norm([2.4e-322, 4.4e-323]) ≈ 2.47e-322 -@test norm([2.4e-322, 4.4e-323], 3) ≈ 2.4e-322 -@test_throws ArgumentError norm(ones(5,5),5) - -# test generic vecnorm for arrays of arrays -let x = Vector{Int}[[1,2], [3,4]] - @test norm(x) ≈ sqrt(30) - @test norm(x, 1) ≈ sqrt(5) + 5 - @test norm(x, 3) ≈ cbrt(sqrt(125)+125) -end - -# test that LinAlg.axpy! works for element type without commutative multiplication -let - α = ones(Int, 2, 2) - x = fill([1 0; 1 1], 3) - y = fill(zeros(Int, 2, 2), 3) - @test LinAlg.axpy!(α, x, deepcopy(y)) == x .* Matrix{Int}[α] - @test LinAlg.axpy!(α, x, deepcopy(y)) != Matrix{Int}[α] .* x -end - -# test that LinAlg.axpy! works for x and y of different dimensions -let - α = 5 - x = 2:5 - y = ones(Int, 2, 4) - rx = [1 4] - ry = [2 8] - @test LinAlg.axpy!(α, x, rx, y, ry) == [1 1 1 1; 11 1 1 26] -end - -let - vr = [3.0, 4.0] - for Tr in (Float32, Float64) - for T in (Tr, Complex{Tr}) - v = convert(Vector{T}, vr) - @test norm(v) == 5.0 - w = normalize(v) - @test norm(w - [0.6, 0.8], Inf) < eps(Tr) - @test norm(w) == 1.0 - @test norm(normalize!(copy(v)) - w, Inf) < eps(Tr) - @test isempty(normalize!(T[])) - end - end -end - -#Test potential overflow in normalize! -let - δ = inv(prevfloat(typemax(Float64))) - v = [δ, -δ] - - @test norm(v) === 7.866824069956793e-309 - w = normalize(v) - @test w ≈ [1/√2, -1/√2] - @test norm(w) === 1.0 - @test norm(normalize!(v) - w, Inf) < eps() -end - -# Issue 14657 -@test det([true false; false true]) == det(eye(Int, 2)) - -@test_throws ArgumentError Base.LinAlg.char_uplo(:Z) - -# Issue 17650 -@test [0.01311489462160816, Inf] ≈ [0.013114894621608135, Inf] - -# Issue 19035 -@test Base.LinAlg.promote_leaf_eltypes([1, 2, [3.0, 4.0]]) == Float64 -@test Base.LinAlg.promote_leaf_eltypes([[1,2, [3,4]], 5.0, [6im, [7.0, 8.0]]]) == Complex128 -@test [1, 2, 3] ≈ [1, 2, 3] -@test [[1, 2], [3, 4]] ≈ [[1, 2], [3, 4]] -@test [[1, 2], [3, 4]] ≈ [[1.0-eps(), 2.0+eps()], [3.0+2eps(), 4.0-1e8eps()]] -@test [[1, 2], [3, 4]] ≉ [[1.0-eps(), 2.0+eps()], [3.0+2eps(), 4.0-1e9eps()]] -@test [[1,2, [3,4]], 5.0, [6im, [7.0, 8.0]]] ≈ [[1,2, [3,4]], 5.0, [6im, [7.0, 8.0]]] diff --git a/julia-0.6.3/share/julia/test/linalg/givens.jl b/julia-0.6.3/share/julia/test/linalg/givens.jl deleted file mode 100644 index 06ad1b9..0000000 --- a/julia-0.6.3/share/julia/test/linalg/givens.jl +++ /dev/null @@ -1,75 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -using Base.Test - -let -debug = false - -# Test givens rotations -for elty in (Float32, Float64, Complex64, Complex128) - debug && println("elty is $elty") - - if elty <: Real - A = convert(Matrix{elty}, randn(10,10)) - else - A = convert(Matrix{elty}, complex.(randn(10,10),randn(10,10))) - end - for Atype in ("Array", "SubArray") - if Atype == "Array" - A = A - else - A = view(A, 1:10, 1:10) - end - Ac = copy(A) - R = Base.LinAlg.Rotation(Base.LinAlg.Givens{elty}[]) - for j = 1:8 - for i = j+2:10 - G, _ = givens(A, j+1, i, j) - A_mul_B!(G, A) - A_mul_Bc!(A, G) - A_mul_B!(G, R) - - @test A_mul_B!(G,eye(elty,10,10)) == [G[i,j] for i=1:10,j=1:10] - - # test transposes - @test ctranspose(G)*G*eye(10) ≈ eye(elty, 10) - @test ctranspose(R)*(R*eye(10)) ≈ eye(elty, 10) - @test_throws ErrorException transpose(G) - @test_throws ErrorException transpose(R) - end - end - @test_throws ArgumentError givens(A, 3, 3, 2) - @test_throws ArgumentError givens(one(elty),zero(elty),2,2) - G, _ = givens(one(elty),zero(elty),11,12) - @test_throws DimensionMismatch A_mul_B!(G, A) - @test_throws DimensionMismatch A_mul_Bc!(A,G) - @test abs.(A) ≈ abs.(hessfact(Ac)[:H]) - @test norm(R*eye(elty, 10)) ≈ one(elty) - - G, _ = givens(one(elty),zero(elty),9,10) - @test ctranspose(G*eye(elty,10))*(G*eye(elty,10)) ≈ eye(elty, 10) - K, _ = givens(zero(elty),one(elty),9,10) - @test ctranspose(K*eye(elty,10))*(K*eye(elty,10)) ≈ eye(elty, 10) - - # test that Givens * work for vectors - if Atype == "Array" - x = A[:, 1] - else - x = view(A, 1:10, 1) - end - G, r = givens(x[2], x[4], 2, 4) - @test (G*x)[2] ≈ r - @test abs((G*x)[4]) < eps(real(elty)) - @inferred givens(x[2], x[4], 2, 4) - - G, r = givens(x, 2, 4) - @test (G*x)[2] ≈ r - @test abs((G*x)[4]) < eps(real(elty)) - @inferred givens(x, 2, 4) - - G, r = givens(x, 4, 2) - @test (G*x)[4] ≈ r - @test abs((G*x)[2]) < eps(real(elty)) - end -end -end #let diff --git a/julia-0.6.3/share/julia/test/linalg/hessenberg.jl b/julia-0.6.3/share/julia/test/linalg/hessenberg.jl deleted file mode 100644 index aca74a7..0000000 --- a/julia-0.6.3/share/julia/test/linalg/hessenberg.jl +++ /dev/null @@ -1,33 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -using Base.Test - -using Base.LinAlg: BlasComplex, BlasFloat, BlasReal, QRPivoted - -let n = 10 - srand(1234321) - - Areal = randn(n,n)/2 - Aimg = randn(n,n)/2 - - @testset for eltya in (Float32, Float64, Complex64, Complex128, BigFloat, Int) - A = eltya == Int ? - rand(1:7, n, n) : - convert(Matrix{eltya}, eltya <: Complex ? - complex.(Areal, Aimg) : - Areal) - - if eltya != BigFloat - H = hessfact(A) - @test size(H[:Q], 1) == size(A, 1) - @test size(H[:Q], 2) == size(A, 2) - @test size(H[:Q]) == size(A) - @test_throws KeyError H[:Z] - @test AbstractArray(H) ≈ A - @test (H[:Q] * H[:H]) * H[:Q]' ≈ A - @test (H[:Q]' *A) * H[:Q] ≈ H[:H] - #getindex for HessenbergQ - @test H[:Q][1,1] ≈ Array(H[:Q])[1,1] - end - end -end diff --git a/julia-0.6.3/share/julia/test/linalg/lapack.jl b/julia-0.6.3/share/julia/test/linalg/lapack.jl deleted file mode 100644 index 49af313..0000000 --- a/julia-0.6.3/share/julia/test/linalg/lapack.jl +++ /dev/null @@ -1,620 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -using Base.Test - -import Base.LinAlg.BlasInt - -@test_throws ArgumentError Base.LinAlg.LAPACK.chkuplo('Z') -@test_throws ArgumentError Base.LinAlg.LAPACK.chkside('Z') -@test_throws ArgumentError Base.LinAlg.LAPACK.chkdiag('Z') -@test_throws ArgumentError Base.LinAlg.LAPACK.chktrans('Z') - -@testset "syevr" begin - let - srand(123) - Ainit = randn(5,5) - @testset for elty in (Float32, Float64, Complex64, Complex128) - if elty == Complex64 || elty == Complex128 - A = complex.(Ainit, Ainit) - else - A = Ainit - end - A = convert(Array{elty, 2}, A) - Asym = A'A - vals, Z = LAPACK.syevr!('V', copy(Asym)) - @test Z*(Diagonal(vals)*Z') ≈ Asym - @test all(vals .> 0.0) - @test LAPACK.syevr!('N','V','U',copy(Asym),0.0,1.0,4,5,-1.0)[1] ≈ vals[vals .< 1.0] - @test LAPACK.syevr!('N','I','U',copy(Asym),0.0,1.0,4,5,-1.0)[1] ≈ vals[4:5] - @test vals ≈ LAPACK.syev!('N','U',copy(Asym)) - - @test_throws DimensionMismatch LAPACK.sygvd!(1,'V','U',copy(Asym),ones(elty,6,6)) - end - end -end - -@testset "gglse" begin - let - @testset for elty in (Float32, Float64, Complex64, Complex128) - A = convert(Array{elty, 2}, [1 1 1 1; 1 3 1 1; 1 -1 3 1; 1 1 1 3; 1 1 1 -1]) - c = convert(Array{elty, 1}, [2, 1, 6, 3, 1]) - B = convert(Array{elty, 2}, [1 1 1 -1; 1 -1 1 1; 1 1 -1 1]) - d = convert(Array{elty, 1}, [1, 3, -1]) - @test LAPACK.gglse!(A, c, B, d)[1] ≈ convert(Array{elty}, [0.5, -0.5, 1.5, 0.5]) - end - end -end - -@testset "gebrd, bdsqr, throw for bdsdc" begin - let - n = 10 - @testset for elty in (Float32, Float64) - d, e = convert(Vector{elty}, randn(n)), convert(Vector{elty}, randn(n - 1)) - U, Vt, C = eye(elty, n), eye(elty, n), eye(elty, n) - s, _ = LAPACK.bdsqr!('U', copy(d), copy(e), Vt, U, C) - @test Array(Bidiagonal(d, e, true)) ≈ U*Diagonal(s)*Vt - - @test_throws ArgumentError LAPACK.bdsqr!('A', d, e, Vt, U, C) - @test_throws DimensionMismatch LAPACK.bdsqr!('U', d, [e; 1], Vt, U, C) - @test_throws DimensionMismatch LAPACK.bdsqr!('U', d, e, Vt[1:end - 1, :], U, C) - @test_throws DimensionMismatch LAPACK.bdsqr!('U', d, e, Vt, U[:,1:end - 1], C) - @test_throws DimensionMismatch LAPACK.bdsqr!('U', d, e, Vt, U, C[1:end - 1, :]) - - @test_throws ArgumentError LAPACK.bdsdc!('U','Z',d,e) - - A = rand(elty,n,n) - B = copy(A) - B, d, e, tauq, taup = LAPACK.gebrd!(B) - U, Vt, C = eye(elty, n), eye(elty, n), eye(elty, n) - s, _ = LAPACK.bdsqr!('U',d,e[1:n-1],Vt, U, C) - @test s ≈ svdvals(A) - end - end -end - -@testset "Issue #7886" begin - let - x, r = LAPACK.gelsy!([0 1; 0 2; 0 3.], [2, 4, 6.]) - @test x ≈ [0,2] - @test r == 1 - end -end - -@testset "geqrt(3)" begin - @testset for elty in (Float32, Float64, Complex64, Complex128) - A = rand(elty,10,10) - B = copy(A) - C,T = LAPACK.geqrt!(A,zeros(elty,10,10)) - D,S = LAPACK.geqrt3!(A,zeros(elty,10,10)) - @test C ≈ D - end -end - -@testset "gbtrf and gbtrs" begin - @testset for elty in (Float32, Float64, Complex64, Complex128) - d = rand(elty,6) - dl = rand(elty,5) - du = rand(elty,5) - dl2 = rand(elty,4) - AB = zeros(elty,6,6) - AB[6,1:4] = dl2 - AB[5,1:5] = dl - AB[4,:] = d - AB[3,2:6] = du - AB,ipiv = LAPACK.gbtrf!(2,1,6,AB) - C = rand(elty,6,6) - D = copy(C) - D = LAPACK.gbtrs!('N',2,1,6,AB,ipiv,D) - A = diagm(dl2,-2) + diagm(dl,-1) + diagm(d) + diagm(du,1) - @test A\C ≈ D - @test_throws DimensionMismatch LAPACK.gbtrs!('N',2,1,6,AB,ipiv,ones(elty,7,6)) - @test_throws Base.LinAlg.LAPACKException LAPACK.gbtrf!(2,1,6,zeros(AB)) - end -end - - -@testset "geqp3, geqrt error handling" begin - @testset for elty in (Float32, Float64, Complex64, Complex128) - A = rand(elty,10,10) - @test_throws DimensionMismatch LAPACK.geqlf!(A,zeros(elty,11)) - @test_throws DimensionMismatch LAPACK.gelqf!(A,zeros(elty,11)) - @test_throws DimensionMismatch LAPACK.geqp3!(A,ones(Base.LinAlg.BlasInt,11),zeros(elty,10)) - @test_throws DimensionMismatch LAPACK.geqp3!(A,ones(Base.LinAlg.BlasInt,10),zeros(elty,11)) - @test_throws ArgumentError LAPACK.geqrt!(A,zeros(elty,11,10)) - @test_throws DimensionMismatch LAPACK.geqrt3!(A,zeros(elty,11,10)) - @test_throws DimensionMismatch LAPACK.geqrt3!(ones(elty,10,11),zeros(elty,11,11)) - @test_throws DimensionMismatch LAPACK.geqrf!(A,zeros(elty,11)) - @test_throws DimensionMismatch LAPACK.gerqf!(A,zeros(elty,11)) - end -end - -@testset "gels, gesv, getrs, getri error handling" begin - @testset for elty in (Float32, Float64, Complex64, Complex128) - A = rand(elty,10,10) - B = rand(elty,11,11) - @test_throws DimensionMismatch LAPACK.gels!('N',A,B) - @test_throws DimensionMismatch LAPACK.gels!('T',A,B) - @test_throws DimensionMismatch LAPACK.gesv!(A,B) - @test_throws DimensionMismatch LAPACK.getrs!('N',A,ones(Base.LinAlg.BlasInt,10),B) - @test_throws DimensionMismatch LAPACK.getrs!('T',A,ones(Base.LinAlg.BlasInt,10),B) - @test_throws DimensionMismatch LAPACK.getri!(A,ones(Base.LinAlg.BlasInt,11)) - end -end - -@testset "gelsy, gelsd" begin - @testset for elty in (Float32, Float64, Complex64, Complex128) - A = rand(elty,10,10) - B = rand(elty,10,10) - C, j = LAPACK.gelsd!(copy(A),copy(B)) - D, k = LAPACK.gelsy!(copy(A),copy(B)) - @test C ≈ D - @test_throws DimensionMismatch LAPACK.gelsd!(A,rand(elty,12,10)) - @test_throws DimensionMismatch LAPACK.gelsy!(A,rand(elty,12,10)) - end -end - -@testset "gglse errors" begin - @testset for elty in (Float32, Float64, Complex64, Complex128) - A = rand(elty,10,10) - @test_throws DimensionMismatch LAPACK.gglse!(A,zeros(elty,10),rand(elty,12,11),zeros(elty,12)) - @test_throws DimensionMismatch LAPACK.gglse!(A,zeros(elty,11),rand(elty,10,10),zeros(elty,10)) - @test_throws DimensionMismatch LAPACK.gglse!(A,zeros(elty,10),rand(elty,10,10),zeros(elty,11)) - end -end - -@testset "gesvd, ggsvd" begin - @testset for elty in (Float32, Float64, Complex64, Complex128) - A = rand(elty,10,5) - U,S,V = svd(A) - lU,lS,lVt = LAPACK.gesvd!('S','S',A) - @test U ≈ lU - @test S ≈ lS - @test V' ≈ lVt - B = rand(elty,10,10) - # xggsvd3 replaced xggsvd in LAPACK 3.6.0 - if LAPACK.laver() < (3, 6, 0) - @test_throws DimensionMismatch LAPACK.ggsvd!('S','S','S',A,B) - else - @test_throws DimensionMismatch LAPACK.ggsvd3!('S','S','S',A,B) - end - end -end - -@testset "geevx, ggev errors" begin - @testset for elty in (Float32, Float64, Complex64, Complex128) - A = rand(elty,10,10) - B = rand(elty,10,10) - @test_throws ArgumentError LAPACK.geevx!('M','N','N','N',A) - @test_throws ArgumentError LAPACK.geevx!('N','Z','N','N',A) - @test_throws ArgumentError LAPACK.geevx!('N','N','Z','N',A) - @test_throws ArgumentError LAPACK.geevx!('N','N','N','Z',A) - @test_throws ArgumentError LAPACK.ggev!('N','B',A,B) - @test_throws ArgumentError LAPACK.ggev!('B','N',A,B) - @test_throws DimensionMismatch LAPACK.ggev!('N','N',A,zeros(elty,12,12)) - end -end - -@testset "gebal/gebak" begin - @testset for elty in (Float32, Float64, Complex64, Complex128) - A = rand(elty,10,10) * Diagonal(exp10.(linspace(-10,10,10))) - B = copy(A) - ilo, ihi, scale = LAPACK.gebal!('S',B) - Bvs = eigvecs(B) - Avs = eigvecs(A) - Bvs = LAPACK.gebak!('S','R',ilo,ihi,scale,Bvs) - @test norm(diff(Avs ./ Bvs)) < 100 * eps(abs(float(one(elty)))) - end -end - -@testset "gels" begin - @testset for elty in (Float32, Float64, Complex64, Complex128) - A = rand(elty,10,10) - X = rand(elty,10) - B,Y,z = LAPACK.gels!('N',copy(A),copy(X)) - @test A\X ≈ Y - end -end - -@testset "getrf/getri" begin - @testset for elty in (Float32, Float64, Complex64, Complex128) - A = rand(elty,10,10) - iA = inv(A) - A, ipiv = LAPACK.getrf!(A) - A = LAPACK.getri!(A, ipiv) - @test A ≈ iA - end -end - -@testset "geev" begin - # complex is easier for now - @testset for elty in (Complex64, Complex128) - A = rand(elty,10,10) - Aw, Avl, Avr = LAPACK.geev!('N','V',copy(A)) - fA = eigfact(A) - @test fA[:values] ≈ Aw - @test fA[:vectors] ≈ Avr - end -end - -@testset "gtsv" begin - @testset for elty in (Float32, Float64, Complex64, Complex128) - du = rand(elty,9) - d = rand(elty,10) - dl = rand(elty,9) - b = rand(elty,10) - c = Tridiagonal(dl,d,du) \ b - b = LAPACK.gtsv!(dl,d,du,b) - @test b ≈ c - @test_throws DimensionMismatch LAPACK.gtsv!(zeros(elty,11),d,du,b) - @test_throws DimensionMismatch LAPACK.gtsv!(dl,d,zeros(elty,11),b) - @test_throws DimensionMismatch LAPACK.gtsv!(dl,d,du,zeros(elty,11)) - @test LAPACK.gtsv!(elty[],elty[],elty[],elty[]) == elty[] - end -end - -@testset "gttrs,gttrf errors" begin - @testset for elty in (Float32, Float64, Complex64, Complex128) - du = rand(elty,9) - d = rand(elty,10) - dl = rand(elty,9) - b = rand(elty,10) - @test_throws DimensionMismatch LAPACK.gttrf!(zeros(elty,11),d,du) - @test_throws DimensionMismatch LAPACK.gttrf!(dl,d,zeros(elty,11)) - @test_throws DimensionMismatch LAPACK.gttrs!('N',zeros(elty,11),d,du,ones(elty,9),zeros(Base.LinAlg.BlasInt,10),b) - @test_throws DimensionMismatch LAPACK.gttrs!('N',dl,d,zeros(elty,11),ones(elty,9),zeros(Base.LinAlg.BlasInt,10),b) - @test_throws DimensionMismatch LAPACK.gttrs!('N',dl,d,du,ones(elty,9),zeros(Base.LinAlg.BlasInt,10),zeros(elty,11)) - A = lufact(Tridiagonal(dl,d,du)) - b = rand(elty,10,5) - c = copy(b) - dl,d,du,du2,ipiv = LAPACK.gttrf!(dl,d,du) - c = LAPACK.gttrs!('N',dl,d,du,du2,ipiv,c) - @test A\b ≈ c - end -end - -@testset "orglq and friends errors" begin - @testset for elty in (Float32, Float64, Complex64, Complex128) - A = rand(elty,10,10) - A,tau = LAPACK.gelqf!(A) - @test_throws DimensionMismatch LAPACK.orglq!(A,tau,11) - @test_throws DimensionMismatch LAPACK.ormlq!('R','N',A,tau,rand(elty,11,11)) - @test_throws DimensionMismatch LAPACK.ormlq!('L','N',A,tau,rand(elty,11,11)) - @test_throws DimensionMismatch LAPACK.ormlq!('R','N',A,zeros(elty,11),rand(elty,10,10)) - @test_throws DimensionMismatch LAPACK.ormlq!('L','N',A,zeros(elty,11),rand(elty,10,10)) - - B = copy(A) - C = LAPACK.orglq!(B,tau) - @test LAPACK.ormlq!('R','N',A,tau,eye(elty,10)) ≈ C - - A = rand(elty,10,10) - A,tau = LAPACK.geqrf!(A) - @test_throws DimensionMismatch LAPACK.orgqr!(A,tau,11) - B = copy(A) - @test LAPACK.orgqr!(B,tau) ≈ LAPACK.ormqr!('R','N',A,tau,eye(elty,10)) - @test_throws DimensionMismatch LAPACK.ormqr!('R','N',A,tau,rand(elty,11,11)) - @test_throws DimensionMismatch LAPACK.ormqr!('L','N',A,tau,rand(elty,11,11)) - @test_throws DimensionMismatch LAPACK.ormqr!('R','N',A,zeros(elty,11),rand(elty,10,10)) - @test_throws DimensionMismatch LAPACK.ormqr!('L','N',A,zeros(elty,11),rand(elty,10,10)) - - A = rand(elty,10,10) - A,tau = LAPACK.geqlf!(A) - @test_throws DimensionMismatch LAPACK.orgql!(A,tau,11) - B = copy(A) - @test LAPACK.orgql!(B,tau) ≈ LAPACK.ormql!('R','N',A,tau,eye(elty,10)) - @test_throws DimensionMismatch LAPACK.ormql!('R','N',A,tau,rand(elty,11,11)) - @test_throws DimensionMismatch LAPACK.ormql!('L','N',A,tau,rand(elty,11,11)) - @test_throws DimensionMismatch LAPACK.ormql!('R','N',A,zeros(elty,11),rand(elty,10,10)) - @test_throws DimensionMismatch LAPACK.ormql!('L','N',A,zeros(elty,11),rand(elty,10,10)) - - A = rand(elty,10,10) - A,tau = LAPACK.gerqf!(A) - @test_throws DimensionMismatch LAPACK.orgrq!(A,tau,11) - B = copy(A) - @test LAPACK.orgrq!(B,tau) ≈ LAPACK.ormrq!('R','N',A,tau,eye(elty,10)) - @test_throws DimensionMismatch LAPACK.ormrq!('R','N',A,tau,rand(elty,11,11)) - @test_throws DimensionMismatch LAPACK.ormrq!('L','N',A,tau,rand(elty,11,11)) - @test_throws DimensionMismatch LAPACK.ormrq!('R','N',A,zeros(elty,11),rand(elty,10,10)) - @test_throws DimensionMismatch LAPACK.ormrq!('L','N',A,zeros(elty,11),rand(elty,10,10)) - - C = rand(elty,10,10) - V = rand(elty,10,10) - T = zeros(elty,10,11) - @test_throws DimensionMismatch LAPACK.gemqrt!('L','N',V,T,C) - @test_throws DimensionMismatch LAPACK.gemqrt!('R','N',V,T,C) - - C = rand(elty,10,10) - V = rand(elty,11,10) - T = zeros(elty,10,10) - @test_throws DimensionMismatch LAPACK.gemqrt!('R','N',V,T,C) - @test_throws DimensionMismatch LAPACK.gemqrt!('L','N',V,T,C) - - # test size(T) = (nb,k) ensures 1 <= nb <= k - T = zeros(elty,10,10) - V = rand(elty,5,10) - @test_throws DimensionMismatch LAPACK.gemqrt!('L','N',V,T,C) - C = rand(elty,10,10) - V = rand(elty,10,10) - T = zeros(elty,11,10) - @test_throws DimensionMismatch LAPACK.gemqrt!('R','N',V,T,C) - - @test_throws DimensionMismatch LAPACK.orghr!(1, 10, C, zeros(elty,11)) - end -end - -@testset "sytri, sytrs, and sytrf" begin - @testset for elty in (Float32, Float64, Complex64, Complex128) - A = rand(elty,10,10) - A = A + A.' #symmetric! - B = copy(A) - B,ipiv = LAPACK.sytrf!('U',B) - @test triu(inv(A)) ≈ triu(LAPACK.sytri!('U',B,ipiv)) - @test_throws DimensionMismatch LAPACK.sytrs!('U',B,ipiv,rand(elty,11,5)) - @test LAPACK.sytrf!('U',zeros(elty,0,0)) == (zeros(elty,0,0),zeros(BlasInt,0),zero(BlasInt)) - end - - # Rook-pivoting variants - @testset for elty in (Float32, Float64, Complex64, Complex128) - A = rand(elty,10,10) - A = A + A.' #symmetric! - B = copy(A) - B,ipiv = LAPACK.sytrf_rook!('U',B) - @test triu(inv(A)) ≈ triu(LAPACK.sytri_rook!('U',B,ipiv)) - @test_throws DimensionMismatch LAPACK.sytrs_rook!('U',B,ipiv,rand(elty,11,5)) - @test LAPACK.sytrf_rook!('U',zeros(elty,0,0)) == (zeros(elty,0,0),zeros(BlasInt,0),zero(BlasInt)) - A = rand(elty,10,10) - A = A + A.' #symmetric! - b = rand(elty,10) - c = A \ b - b,A = LAPACK.sysv_rook!('U',A,b) - @test b ≈ c - @test_throws DimensionMismatch LAPACK.sysv_rook!('U',A,rand(elty,11)) - end -end - -@testset "hetrf, hetrs" begin - @testset for elty in (Complex64, Complex128) - A = rand(elty,10,10) - A = A + A' #hermitian! - B = copy(A) - B,ipiv = LAPACK.hetrf!('U',B) - @test_throws DimensionMismatch LAPACK.hetrs!('U',B,ipiv,rand(elty,11,5)) - @test_throws DimensionMismatch LAPACK.hetrs_rook!('U',B,ipiv,rand(elty,11,5)) - end -end - -@testset "stev, stebz, stein, stegr" begin - @testset for elty in (Float32, Float64) - d = rand(elty,10) - e = rand(elty,9) - @test_throws DimensionMismatch LAPACK.stev!('U',d,rand(elty,10)) - @test_throws DimensionMismatch LAPACK.stebz!('A','B',zero(elty),zero(elty),0,0,-1.,d,rand(elty,10)) - @test_throws DimensionMismatch LAPACK.stegr!('N','A',d,rand(elty,10),zero(elty),zero(elty),0,0) - @test_throws DimensionMismatch LAPACK.stein!(d,zeros(elty,10),zeros(d),zeros(BlasInt,10),zeros(BlasInt,10)) - @test_throws DimensionMismatch LAPACK.stein!(d,e,zeros(elty,11),zeros(BlasInt,10),zeros(BlasInt,10)) - end -end - -@testset "trtri & trtrs" begin - @testset for elty in (Float32, Float64, Complex64, Complex128) - A = rand(elty,10,10) - A = triu(A) - B = copy(A) - @test inv(A) ≈ LAPACK.trtri!('U','N',B) - @test_throws DimensionMismatch LAPACK.trtrs!('U','N','N',B,zeros(elty,11,10)) - end -end - -@testset "tgsen, tzrzf, & trsyl" begin - @testset for elty in (Float32, Float64, Complex64, Complex128) - Z = zeros(elty,10,10) - @test_throws DimensionMismatch LAPACK.tgsen!(zeros(BlasInt,10),Z,zeros(elty,11,11),Z,Z) - @test_throws DimensionMismatch LAPACK.tgsen!(zeros(BlasInt,10),Z,Z,zeros(elty,11,11),Z) - @test_throws DimensionMismatch LAPACK.tgsen!(zeros(BlasInt,10),Z,Z,Z,zeros(elty,11,11)) - @test_throws DimensionMismatch LAPACK.trsyl!('N','N',Z,Z,zeros(elty,11,11)) - @test_throws DimensionMismatch LAPACK.tzrzf!(zeros(elty,10,5)) - end -end - -@testset "sysv" begin - @testset for elty in (Float32, Float64, Complex64, Complex128) - A = rand(elty,10,10) - A = A + A.' #symmetric! - b = rand(elty,10) - c = A \ b - b,A = LAPACK.sysv!('U',A,b) - @test b ≈ c - @test_throws DimensionMismatch LAPACK.sysv!('U',A,rand(elty,11)) - end -end - -@testset "hesv" begin - @testset for elty in (Complex64, Complex128) - A = rand(elty,10,10) - A = A + A' #hermitian! - b = rand(elty,10) - c = A \ b - b,A = LAPACK.hesv!('U',A,b) - @test b ≈ c - @test_throws DimensionMismatch LAPACK.hesv!('U',A,rand(elty,11)) - A = rand(elty,10,10) - A = A + A' #hermitian! - b = rand(elty,10) - c = A \ b - b,A = LAPACK.hesv_rook!('U',A,b) - @test b ≈ c - @test_throws DimensionMismatch LAPACK.hesv_rook!('U',A,rand(elty,11)) - end -end - -@testset "ptsv" begin - @testset for elty in (Float32, Float64, Complex64, Complex128) - dv = real(ones(elty,10)) - ev = zeros(elty,9) - A = SymTridiagonal(dv,ev) - if elty <: Complex - A = Tridiagonal(conj(ev),dv,ev) - end - B = rand(elty,10,10) - C = copy(B) - @test A\B ≈ LAPACK.ptsv!(dv,ev,C) - @test_throws DimensionMismatch LAPACK.ptsv!(dv,ones(elty,10),C) - @test_throws DimensionMismatch LAPACK.ptsv!(dv,ev,ones(elty,11,11)) - end -end - -@testset "pttrf and pttrs" begin - @testset for elty in (Float32, Float64, Complex64, Complex128) - dv = real(ones(elty,10)) - ev = zeros(elty,9) - A = SymTridiagonal(dv,ev) - if elty <: Complex - A = Tridiagonal(conj(ev),dv,ev) - end - dv,ev = LAPACK.pttrf!(dv,ev) - @test_throws DimensionMismatch LAPACK.pttrf!(dv,ones(elty,10)) - B = rand(elty,10,10) - C = copy(B) - if elty <: Complex - @test A\B ≈ LAPACK.pttrs!('U',dv,ev,C) - @test_throws DimensionMismatch LAPACK.pttrs!('U',dv,ones(elty,10),C) - @test_throws DimensionMismatch LAPACK.pttrs!('U',dv,ev,rand(elty,11,11)) - else - @test A\B ≈ LAPACK.pttrs!(dv,ev,C) - @test_throws DimensionMismatch LAPACK.pttrs!(dv,ones(elty,10),C) - @test_throws DimensionMismatch LAPACK.pttrs!(dv,ev,rand(elty,11,11)) - end - end -end - -@testset "posv and some errors for friends" begin - @testset for elty in (Float32, Float64, Complex64, Complex128) - A = rand(elty,10,10)/100 - A += real(diagm(10*real(rand(elty,10)))) - if elty <: Complex - A = A + A' - else - A = A + A.' - end - B = rand(elty,10,10) - D = copy(A) - C = copy(B) - D,C = LAPACK.posv!('U',D,C) - @test A\B ≈ C - @test_throws DimensionMismatch LAPACK.posv!('U',D,ones(elty,12,12)) - @test_throws DimensionMismatch LAPACK.potrs!('U',D,ones(elty,12,12)) - - @test LAPACK.potrs!('U',zeros(elty,0,0),ones(elty,0)) == ones(elty,0) - end -end - -@testset "gesvx" begin - @testset for elty in (Float32, Float64, Complex64, Complex128) - A = rand(elty,10,10) - B = rand(elty,10,5) - C = copy(A) - D = copy(B) - X, rcond, f, b, r = LAPACK.gesvx!(C,D) - @test X ≈ A\B - end -end - -@testset "gees, gges error throwing" begin - @testset for elty in (Float32, Float64, Complex64, Complex128) - A = rand(elty,10,10) - B = rand(elty,11,11) - @test_throws DimensionMismatch LAPACK.gges!('V','V',A,B) - end -end - -@testset "trrfs & trevc" begin - @testset for elty in (Float32, Float64, Complex64, Complex128) - T = triu(rand(elty,10,10)) - S = copy(T) - select = zeros(Base.LinAlg.BlasInt,10) - select[1] = 1 - select,Vr = LAPACK.trevc!('R','S',select,copy(T)) - @test Vr ≈ eigvecs(S)[:,1] - select = zeros(Base.LinAlg.BlasInt,10) - select[1] = 1 - select,Vl = LAPACK.trevc!('L','S',select,copy(T)) - select = zeros(Base.LinAlg.BlasInt,10) - select[1] = 1 - select,Vln,Vrn = LAPACK.trevc!('B','S',select,copy(T)) - @test Vrn ≈ eigvecs(S)[:,1] - @test Vln ≈ Vl - @test_throws ArgumentError LAPACK.trevc!('V','S',select,copy(T)) - @test_throws DimensionMismatch LAPACK.trrfs!('U','N','N',T,rand(elty,10,10),rand(elty,10,11)) - end -end - -@testset "laic1" begin - @testset for elty in (Float32, Float64, Complex64, Complex128) - @test_throws DimensionMismatch LAPACK.laic1!(1,rand(elty,10),real(rand(elty)),rand(elty,11),rand(elty)) - end -end - -@testset "trexc" begin - @testset for elty in (Float32, Float64, Complex64, Complex128) - for c in ('V', 'N') - A = convert(Matrix{elty}, [7 2 2 1; 1 5 2 0; 0 3 9 4; 1 1 1 4]) - T,Q,d = schur(A) - Base.LinAlg.LAPACK.trsen!('N',c,Array{LinAlg.BlasInt}([0,1,0,0]),T,Q) - @test d[1] ≈ T[2,2] - @test d[2] ≈ T[1,1] - if c == 'V' - @test Q*T*Q' ≈ A - end - end - end -end - -@testset "trexc and trsen" begin - @testset for elty in (Float32, Float64, Complex64, Complex128) - for c in ('V', 'N') - A = convert(Matrix{elty}, [7 2 2 1; 1 5 2 0; 0 3 9 4; 1 1 1 4]) - T,Q,d = schur(A) - Base.LinAlg.LAPACK.trexc!(c,LinAlg.BlasInt(1),LinAlg.BlasInt(2),T,Q) - @test d[1] ≈ T[2,2] - @test d[2] ≈ T[1,1] - if c == 'V' - @test Q*T*Q' ≈ A - end - end - end -end - -@testset "Julia vs LAPACK" begin - # Test our own linear algebra functionality against LAPACK - @testset for elty in (Float32, Float64, Complex{Float32}, Complex{Float64}) - for nn in (5,10,15) - if elty <: Real - A = convert(Matrix{elty}, randn(10,nn)) - else - A = convert(Matrix{elty}, complex.(randn(10,nn),randn(10,nn))) - end ## LU (only equal for real because LAPACK uses different absolute value when choosing permutations) - if elty <: Real - FJulia = Base.LinAlg.generic_lufact!(copy(A)) - FLAPACK = Base.LinAlg.LAPACK.getrf!(copy(A)) - @test FJulia.factors ≈ FLAPACK[1] - @test FJulia.ipiv ≈ FLAPACK[2] - @test FJulia.info ≈ FLAPACK[3] - end - - ## QR - FJulia = LinAlg.qrfactUnblocked!(copy(A)) - FLAPACK = Base.LinAlg.LAPACK.geqrf!(copy(A)) - @test FJulia.factors ≈ FLAPACK[1] - @test FJulia.τ ≈ FLAPACK[2] - end - end -end - -# Issue 13976 -let A = [NaN 0.0 NaN; 0 0 0; NaN 0 NaN] - @test_throws ArgumentError expm(A) -end - -# Issue 14065 (and 14220) -let A = [NaN NaN; NaN NaN] - @test_throws ArgumentError eigfact(A) -end diff --git a/julia-0.6.3/share/julia/test/linalg/lq.jl b/julia-0.6.3/share/julia/test/linalg/lq.jl deleted file mode 100644 index 30b55ba..0000000 --- a/julia-0.6.3/share/julia/test/linalg/lq.jl +++ /dev/null @@ -1,136 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -using Base.Test - -using Base.LinAlg: BlasComplex, BlasFloat, BlasReal - - -n = 10 - -# Split n into 2 parts for tests needing two matrices -n1 = div(n, 2) -n2 = 2*n1 - -srand(1234321) - -areal = randn(n,n)/2 -aimg = randn(n,n)/2 -a2real = randn(n,n)/2 -a2img = randn(n,n)/2 -breal = randn(n,2)/2 -bimg = randn(n,2)/2 - -@testset for eltya in (Float32, Float64, Complex64, Complex128) - a = eltya == Int ? rand(1:7, n, n) : convert(Matrix{eltya}, eltya <: Complex ? complex.(areal, aimg) : areal) - a2 = eltya == Int ? rand(1:7, n, n) : convert(Matrix{eltya}, eltya <: Complex ? complex.(a2real, a2img) : a2real) - asym = a'+a # symmetric indefinite - apd = a'*a # symmetric positive-definite - ε = εa = eps(abs(float(one(eltya)))) - - @testset for eltyb in (Float32, Float64, Complex64, Complex128, Int) - b = eltyb == Int ? rand(1:5, n, 2) : convert(Matrix{eltyb}, eltyb <: Complex ? complex.(breal, bimg) : breal) - εb = eps(abs(float(one(eltyb)))) - ε = max(εa,εb) - - α = rand(eltya) - aα = fill(α,1,1) - @test lqfact(α)[:L]*lqfact(α)[:Q] ≈ lqfact(aα)[:L]*lqfact(aα)[:Q] - @test lq(α)[1]*lq(α)[2] ≈ lqfact(aα)[:L]*lqfact(aα)[:Q] - @test abs(lqfact(α)[:Q][1,1]) ≈ one(eltya) - tab = promote_type(eltya,eltyb) - - for i = 1:2 - let a = i == 1 ? a : view(a, 1:n - 1, 1:n - 1), b = i == 1 ? b : view(b, 1:n - 1), n = i == 1 ? n : n - 1 - lqa = lqfact(a) - l,q = lqa[:L], lqa[:Q] - qra = qrfact(a) - @testset "Basic ops" begin - @test size(lqa,1) == size(a,1) - @test size(lqa,3) == 1 - @test size(lqa[:Q],3) == 1 - @test Base.LinAlg.getq(lqa) == lqa[:Q] - @test_throws KeyError lqa[:Z] - @test full(lqa') ≈ a' - @test lqa * lqa' ≈ a * a' - @test lqa' * lqa ≈ a' * a - @test q*full(q, thin = false)' ≈ eye(eltya,n) - @test l*q ≈ a - @test full(lqa) ≈ a - @test full(copy(lqa)) ≈ a - lstring = sprint(show,l) - qstring = sprint(show,q) - @test sprint(show,lqa) == "$(typeof(lqa)) with factors L and Q:\n$lstring\n$qstring" - end - @testset "Binary ops" begin - @test a*(lqa\b) ≈ b atol=3000ε - @test lqa*b ≈ qra[:Q]*qra[:R]*b atol=3000ε - @test A_mul_Bc(eye(eltyb,size(q.factors,2)),q)*full(q,thin=false) ≈ eye(n) atol=5000ε - if eltya != Int - @test eye(eltyb,n)*q ≈ convert(AbstractMatrix{tab},q) - end - @test q*b ≈ full(q,thin=false)*b atol=100ε - @test q.'*b ≈ full(q,thin=false).'*b atol=100ε - @test q'*b ≈ full(q,thin=false)'*b atol=100ε - @test a*q ≈ a*full(q,thin=false) atol=100ε - @test a*q.' ≈ a*full(q,thin=false).' atol=100ε - @test a*q' ≈ a*full(q,thin=false)' atol=100ε - @test a'*q ≈ a'*full(q,thin=false) atol=100ε - @test a'*q' ≈ a'*full(q,thin=false)' atol=100ε - @test_throws DimensionMismatch q*b[1:n1 + 1] - @test_throws DimensionMismatch Ac_mul_B(q,ones(eltya,n+2,n+2)) - @test_throws DimensionMismatch ones(eltyb,n+2,n+2)*q - if isa(a, DenseArray) && isa(b, DenseArray) - # use this to test 2nd branch in mult code - pad_a = vcat(eye(a), a) - pad_b = hcat(eye(b), b) - @test pad_a*q ≈ pad_a*full(q,thin=false) atol=100ε - @test q.'*pad_b ≈ full(q,thin=false).'*pad_b atol=100ε - @test q'*pad_b ≈ full(q,thin=false)'*pad_b atol=100ε - end - end - end - end - - @testset "Matmul with LQ factorizations" begin - lqa = lqfact(a[:,1:n1]) - l,q = lqa[:L], lqa[:Q] - @test full(q)*full(q)' ≈ eye(eltya,n1) - @test (full(q,thin=false)'*full(q,thin=false))[1:n1,:] ≈ eye(eltya,n1,n) - @test_throws DimensionMismatch A_mul_B!(eye(eltya,n+1),q) - @test Ac_mul_B!(q,full(q)) ≈ eye(eltya,n1) - @test_throws DimensionMismatch A_mul_Bc!(eye(eltya,n+1),q) - @test_throws BoundsError size(q,-1) - end - end -end - -@testset "getindex on LQPackedQ (#23733)" begin - function getqs(F::Base.LinAlg.LQ) - implicitQ = F[:Q] - explicitQ = A_mul_B!(implicitQ, eye(eltype(implicitQ), size(implicitQ.factors, 2))) - return implicitQ, explicitQ - end - - m, n = 3, 3 # thin Q 3-by-3, square Q 3-by-3 - implicitQ, explicitQ = getqs(lqfact(randn(m, n))) - @test implicitQ[1, 1] == explicitQ[1, 1] - @test implicitQ[m, 1] == explicitQ[m, 1] - @test implicitQ[1, n] == explicitQ[1, n] - @test implicitQ[m, n] == explicitQ[m, n] - - m, n = 3, 4 # thin Q 3-by-4, square Q 4-by-4 - implicitQ, explicitQ = getqs(lqfact(randn(m, n))) - @test implicitQ[1, 1] == explicitQ[1, 1] - @test implicitQ[m, 1] == explicitQ[m, 1] - @test implicitQ[1, n] == explicitQ[1, n] - @test implicitQ[m, n] == explicitQ[m, n] - @test implicitQ[m+1, 1] == explicitQ[m+1, 1] - @test implicitQ[m+1, n] == explicitQ[m+1, n] - - m, n = 4, 3 # thin Q 3-by-3, square Q 3-by-3 - implicitQ, explicitQ = getqs(lqfact(randn(m, n))) - @test implicitQ[1, 1] == explicitQ[1, 1] - @test implicitQ[n, 1] == explicitQ[n, 1] - @test implicitQ[1, n] == explicitQ[1, n] - @test implicitQ[n, n] == explicitQ[n, n] -end diff --git a/julia-0.6.3/share/julia/test/linalg/lu.jl b/julia-0.6.3/share/julia/test/linalg/lu.jl deleted file mode 100644 index 674a5e7..0000000 --- a/julia-0.6.3/share/julia/test/linalg/lu.jl +++ /dev/null @@ -1,210 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -debug = false - -using Base.Test -import Base.LinAlg.BlasInt, Base.LinAlg.BlasFloat - -n = 10 - -# Split n into 2 parts for tests needing two matrices -n1 = div(n, 2) -n2 = 2*n1 - -srand(1234321) - -a = rand(n,n) - -areal = randn(n,n)/2 -aimg = randn(n,n)/2 -breal = randn(n,2)/2 -bimg = randn(n,2)/2 -creal = randn(n)/2 -cimg = randn(n)/2 -dureal = randn(n-1)/2 -duimg = randn(n-1)/2 -dlreal = randn(n-1)/2 -dlimg = randn(n-1)/2 -dreal = randn(n)/2 -dimg = randn(n)/2 - -for eltya in (Float32, Float64, Complex64, Complex128, BigFloat, Int) - a = eltya == Int ? rand(1:7, n, n) : - convert(Matrix{eltya}, eltya <: Complex ? complex.(areal, aimg) : areal) - d = if eltya == Int - Tridiagonal(rand(1:7, n-1), rand(1:7, n), rand(1:7, n-1)) - elseif eltya <: Complex - convert(Tridiagonal{eltya}, Tridiagonal( - complex.(dlreal, dlimg), complex.(dreal, dimg), complex.(dureal, duimg))) - else - convert(Tridiagonal{eltya}, Tridiagonal(dlreal, dreal, dureal)) - end - ε = εa = eps(abs(float(one(eltya)))) - - if eltya <: BlasFloat - num = rand(eltya) - @test lu(num) == (one(eltya),num,1) - @test AbstractArray(lufact(num)) ≈ eltya[num] - end - for eltyb in (Float32, Float64, Complex64, Complex128, Int) - b = eltyb == Int ? rand(1:5, n, 2) : - convert(Matrix{eltyb}, eltyb <: Complex ? complex.(breal, bimg) : breal) - c = eltyb == Int ? rand(1:5, n) : - convert(Vector{eltyb}, eltyb <: Complex ? complex.(creal, cimg) : creal) - εb = eps(abs(float(one(eltyb)))) - ε = max(εa,εb) - -debug && println("(Automatic) Square LU decomposition. eltya: $eltya, eltyb: $eltyb") - κ = cond(a,1) - lua = factorize(a) - @test_throws KeyError lua[:Z] - l,u,p = lua[:L], lua[:U], lua[:p] - ll,ul,pl = lu(a) - @test ll * ul ≈ a[pl,:] - @test l*u ≈ a[p,:] - @test (l*u)[invperm(p),:] ≈ a - @test a * inv(lua) ≈ eye(n) - - lstring = sprint(show,l) - ustring = sprint(show,u) - @test sprint(show,lua) == "$(typeof(lua)) with factors L and U:\n$lstring\n$ustring" - let Bs = b, Cs = c - for atype in ("Array", "SubArray") - if atype == "Array" - b = Bs - c = Cs - else - b = view(Bs, 1:n, 1) - c = view(Cs, 1:n) - end - @test norm(a*(lua\b) - b, 1) < ε*κ*n*2 # Two because the right hand side has two columns - @test norm(a'*(lua'\b) - b, 1) < ε*κ*n*2 # Two because the right hand side has two columns - @test norm(a'*(lua'\a') - a', 1) < ε*κ*n^2 - @test norm(a*(lua\c) - c, 1) < ε*κ*n # c is a vector - @test norm(a'*(lua'\c) - c, 1) < ε*κ*n # c is a vector - @test AbstractArray(lua) ≈ a - if eltya <: Real && eltyb <: Real - @test norm(a.'*(lua.'\b) - b,1) < ε*κ*n*2 # Two because the right hand side has two columns - @test norm(a.'*(lua.'\c) - c,1) < ε*κ*n - end - end - end - if eltya <: BlasFloat && eltyb <: BlasFloat - e = rand(eltyb,n,n) - @test norm(e/lua - e/a,1) < ε*κ*n^2 - end - -debug && println("Tridiagonal LU") - κd = cond(Array(d),1) - lud = lufact(d) - @test lufact(lud) == lud - @test_throws KeyError lud[:Z] - @test lud[:L]*lud[:U] ≈ lud[:P]*Array(d) - @test lud[:L]*lud[:U] ≈ Array(d)[lud[:p],:] - @test AbstractArray(lud) ≈ d - f = zeros(eltyb, n+1) - @test_throws DimensionMismatch lud\f - @test_throws DimensionMismatch lud.'\f - @test_throws DimensionMismatch lud'\f - @test_throws DimensionMismatch Base.LinAlg.At_ldiv_B!(lud, f) - let Bs = b - for atype in ("Array", "SubArray") - if atype == "Array" - b = Bs - else - b = view(Bs, 1:n, 1) - end - - @test norm(d*(lud\b) - b, 1) < ε*κd*n*2 # Two because the right hand side has two columns - if eltya <: Real - @test norm((lud.'\b) - Array(d.')\b, 1) < ε*κd*n*2 # Two because the right hand side has two columns - if eltya != Int && eltyb != Int - @test norm(Base.LinAlg.At_ldiv_B!(lud, copy(b)) - Array(d.')\b, 1) < ε*κd*n*2 - end - end - if eltya <: Complex - @test norm((lud'\b) - Array(d')\b, 1) < ε*κd*n*2 # Two because the right hand side has two columns - end - end - end - if eltya <: BlasFloat && eltyb <: BlasFloat - e = rand(eltyb,n,n) - @test norm(e/lud - e/d,1) < ε*κ*n^2 - @test norm((lud.'\e') - Array(d.')\e',1) < ε*κd*n^2 - #test singular - du = rand(eltya,n-1) - dl = rand(eltya,n-1) - dd = rand(eltya,n) - dd[1] = zero(eltya) - du[1] = zero(eltya) - dl[1] = zero(eltya) - zT = Tridiagonal(dl,dd,du) - @test lufact(zT).info == 1 - end - -debug && println("Thin LU") - lua = @inferred lufact(a[:,1:n1]) - @test lua[:L]*lua[:U] ≈ lua[:P]*a[:,1:n1] - -debug && println("Fat LU") - lua = lufact(a[1:n1,:]) - @test lua[:L]*lua[:U] ≈ lua[:P]*a[1:n1,:] - end -end - -# test conversion routine -a = Tridiagonal(rand(9),rand(10),rand(9)) -fa = Array(a) -falu = lufact(fa) -alu = lufact(a) -falu = convert(typeof(falu),alu) -@test AbstractArray(alu) == fa - -# Test rational matrices -## Integrate in general tests when more linear algebra is implemented in julia -a = convert(Matrix{Rational{BigInt}}, rand(1:10//1,n,n))/n -b = rand(1:10,n,2) -@inferred lufact(a) -lua = factorize(a) -l,u,p = lua[:L], lua[:U], lua[:p] -@test l*u ≈ a[p,:] -@test l[invperm(p),:]*u ≈ a -@test a*inv(lua) ≈ eye(n) -let Bs = b - for atype in ("Array", "SubArray") - if atype == "Array" - b = Bs - else - b = view(Bs, 1:n, 1) - end - @test a*(lua\b) ≈ b - end -end -@test @inferred(det(a)) ≈ det(Array{Float64}(a)) -## Hilbert Matrix (very ill conditioned) -## Testing Rational{BigInt} and BigFloat version -nHilbert = 50 -H = Rational{BigInt}[1//(i+j-1) for i = 1:nHilbert,j = 1:nHilbert] -Hinv = Rational{BigInt}[(-1)^(i+j)*(i+j-1)*binomial(nHilbert+i-1,nHilbert-j)* - binomial(nHilbert+j-1,nHilbert-i)*binomial(i+j-2,i-1)^2 - for i = big(1):nHilbert,j=big(1):nHilbert] -@test inv(H) == Hinv -setprecision(2^10) do - @test norm(Array{Float64}(inv(float(H)) - float(Hinv))) < 1e-100 -end - -# Test balancing in eigenvector calculations -for elty in (Float32, Float64, Complex64, Complex128) - A = convert(Matrix{elty}, [ 3.0 -2.0 -0.9 2*eps(real(one(elty))); - -2.0 4.0 1.0 -eps(real(one(elty))); - -eps(real(one(elty)))/4 eps(real(one(elty)))/2 -1.0 0; - -0.5 -0.5 0.1 1.0]) - F = eigfact(A, permute=false, scale=false) - eig(A, permute=false, scale=false) - @test F[:vectors]*Diagonal(F[:values])/F[:vectors] ≈ A - F = eigfact(A) - # @test norm(F[:vectors]*Diagonal(F[:values])/F[:vectors] - A) > 0.01 -end - -@test @inferred(logdet(Complex64[1.0f0 0.5f0; 0.5f0 -1.0f0])) === 0.22314355f0 + 3.1415927f0im -@test_throws DomainError logdet([1 1; 1 -1]) diff --git a/julia-0.6.3/share/julia/test/linalg/matmul.jl b/julia-0.6.3/share/julia/test/linalg/matmul.jl deleted file mode 100644 index c97f69d..0000000 --- a/julia-0.6.3/share/julia/test/linalg/matmul.jl +++ /dev/null @@ -1,422 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -using Base.Test - -## Test Julia fallbacks to BLAS routines - -# matrices with zero dimensions -@test ones(0,5)*ones(5,3) == zeros(0,3) -@test ones(3,5)*ones(5,0) == zeros(3,0) -@test ones(3,0)*ones(0,4) == zeros(3,4) -@test ones(0,5)*ones(5,0) == zeros(0,0) -@test ones(0,0)*ones(0,4) == zeros(0,4) -@test ones(3,0)*ones(0,0) == zeros(3,0) -@test ones(0,0)*ones(0,0) == zeros(0,0) -@test Array{Float64}(5, 0) |> t -> t't == zeros(0,0) -@test Array{Float64}(5, 0) |> t -> t*t' == zeros(5,5) -@test Array{Complex128}(5, 0) |> t -> t't == zeros(0,0) -@test Array{Complex128}(5, 0) |> t -> t*t' == zeros(5,5) - -# 2x2 -let - AA = [1 2; 3 4] - BB = [5 6; 7 8] - AAi = AA+(0.5*im).*BB - BBi = BB+(2.5*im).*AA[[2,1],[2,1]] - for Atype = ["Array", "SubArray"], Btype = ["Array", "SubArray"] - A = Atype == "Array" ? AA : view(AA, 1:2, 1:2) - B = Btype == "Array" ? BB : view(BB, 1:2, 1:2) - @test A*B == [19 22; 43 50] - @test At_mul_B(A, B) == [26 30; 38 44] - @test A_mul_Bt(A, B) == [17 23; 39 53] - @test At_mul_Bt(A, B) == [23 31; 34 46] - - Ai = Atype == "Array" ? AAi : view(AAi, 1:2, 1:2) - Bi = Btype == "Array" ? BBi : view(BBi, 1:2, 1:2) - @test Ai*Bi == [-21+53.5im -4.25+51.5im; -12+95.5im 13.75+85.5im] - @test Ac_mul_B(Ai, Bi) == [68.5-12im 57.5-28im; 88-3im 76.5-25im] - @test A_mul_Bc(Ai, Bi) == [64.5+5.5im 43+31.5im; 104-18.5im 80.5+31.5im] - @test Ac_mul_Bc(Ai, Bi) == [-28.25-66im 9.75-58im; -26-89im 21-73im] - @test_throws DimensionMismatch [1 2; 0 0; 0 0] * [1 2] - end - CC = ones(3, 3) - @test_throws DimensionMismatch A_mul_B!(CC, AA, BB) -end -# 3x3 -let - AA = [1 2 3; 4 5 6; 7 8 9].-5 - BB = [1 0 5; 6 -10 3; 2 -4 -1] - AAi = AA+(0.5*im).*BB - BBi = BB+(2.5*im).*AA[[2,1,3],[2,3,1]] - for Atype = ["Array", "SubArray"], Btype = ["Array", "SubArray"] - A = Atype == "Array" ? AA : view(AA, 1:3, 1:3) - B = Btype == "Array" ? BB : view(BB, 1:3, 1:3) - @test A*B == [-26 38 -27; 1 -4 -6; 28 -46 15] - @test Ac_mul_B(A, B) == [-6 2 -25; 3 -12 -18; 12 -26 -11] - @test A_mul_Bc(A, B) == [-14 0 6; 4 -3 -3; 22 -6 -12] - @test Ac_mul_Bc(A, B) == [6 -8 -6; 12 -9 -9; 18 -10 -12] - - Ai = Atype == "Array" ? AAi : view(AAi, 1:3, 1:3) - Bi = Btype == "Array" ? BBi : view(BBi, 1:3, 1:3) - @test Ai*Bi == [-44.75+13im 11.75-25im -38.25+30im; -47.75-16.5im -51.5+51.5im -56+6im; 16.75-4.5im -53.5+52im -15.5im] - @test Ac_mul_B(Ai, Bi) == [-21+2im -1.75+49im -51.25+19.5im; 25.5+56.5im -7-35.5im 22+35.5im; -3+12im -32.25+43im -34.75-2.5im] - @test A_mul_Bc(Ai, Bi) == [-20.25+15.5im -28.75-54.5im 22.25+68.5im; -12.25+13im -15.5+75im -23+27im; 18.25+im 1.5+94.5im -27-54.5im] - @test Ac_mul_Bc(Ai, Bi) == [1+2im 20.75+9im -44.75+42im; 19.5+17.5im -54-36.5im 51-14.5im; 13+7.5im 11.25+31.5im -43.25-14.5im] - @test_throws DimensionMismatch [1 2 3; 0 0 0; 0 0 0] * [1 2 3] - end - CC = ones(4, 4) - @test_throws DimensionMismatch A_mul_B!(CC, AA, BB) -end -# Generic integer matrix multiplication -# Generic AbstractArrays -module MyArray15367 - using Base.Test - struct MyArray{T,N} <: AbstractArray{T,N} - data::Array{T,N} - end - - Base.size(A::MyArray) = size(A.data) - Base.getindex(A::MyArray, indexes...) = A.data[indexes...] - - A = MyArray(rand(4,5)) - b = rand(5) - @test A*b ≈ A.data*b -end - -let - AA = [1 2 3; 4 5 6] .- 3 - BB = [2 -2; 3 -5; -4 7] - for Atype = ["Array", "SubArray"], Btype = ["Array", "SubArray"] - A = Atype == "Array" ? AA : view(AA, 1:2, 1:3) - B = Btype == "Array" ? BB : view(BB, 1:3, 1:2) - @test A*B == [-7 9; -4 9] - @test At_mul_Bt(A, B) == [-6 -11 15; -6 -13 18; -6 -15 21] - end - AA = ones(Int, 2, 100) - BB = ones(Int, 100, 3) - for Atype = ["Array", "SubArray"], Btype = ["Array", "SubArray"] - A = Atype == "Array" ? AA : view(AA, 1:2, 1:100) - B = Btype == "Array" ? BB : view(BB, 1:100, 1:3) - @test A*B == [100 100 100; 100 100 100] - end - AA = rand(1:20, 5, 5) .- 10 - BB = rand(1:20, 5, 5) .- 10 - CC = Array{Int}(size(AA, 1), size(BB, 2)) - for Atype = ["Array", "SubArray"], Btype = ["Array", "SubArray"], Ctype = ["Array", "SubArray"] - A = Atype == "Array" ? AA : view(AA, 1:5, 1:5) - B = Btype == "Array" ? BB : view(BB, 1:5, 1:5) - C = Btype == "Array" ? CC : view(CC, 1:5, 1:5) - @test At_mul_B(A, B) == A'*B - @test A_mul_Bt(A, B) == A*B' - # Preallocated - @test A_mul_B!(C, A, B) == A*B - @test At_mul_B!(C, A, B) == A'*B - @test A_mul_Bt!(C, A, B) == A*B' - @test At_mul_Bt!(C, A, B) == A'*B' - @test Base.LinAlg.Ac_mul_Bt!(C, A, B) == A'*B.' - - #test DimensionMismatch for generic_matmatmul - @test_throws DimensionMismatch Base.LinAlg.Ac_mul_Bt!(C,A,ones(Int,4,4)) - @test_throws DimensionMismatch Base.LinAlg.Ac_mul_Bt!(C,ones(Int,4,4),B) - end - vv = [1,2] - CC = Array{Int}(2, 2) - for vtype = ["Array", "SubArray"], Ctype = ["Array", "SubArray"] - v = vtype == "Array" ? vv : view(vv, 1:2) - C = Ctype == "Array" ? CC : view(CC, 1:2, 1:2) - @test @inferred(A_mul_Bc!(C, v, v)) == [1 2; 2 4] - end -end - -#and for generic_matvecmul -let - AA = rand(5,5) - BB = rand(5) - for Atype = ["Array", "SubArray"], Btype = ["Array", "SubArray"] - A = Atype == "Array" ? AA : view(AA, 1:5, 1:5) - B = Btype == "Array" ? BB : view(BB, 1:5) - @test_throws DimensionMismatch Base.LinAlg.generic_matvecmul!(zeros(6),'N',A,B) - @test_throws DimensionMismatch Base.LinAlg.generic_matvecmul!(B,'N',A,zeros(6)) - end - vv = [1,2,3] - CC = Array{Int}(3, 3) - for vtype = ["Array", "SubArray"], Ctype = ["Array", "SubArray"] - v = vtype == "Array" ? vv : view(vv, 1:3) - C = Ctype == "Array" ? CC : view(CC, 1:3, 1:3) - @test A_mul_Bt!(C, v, v) == v*v' - end - vvf = map(Float64,vv) - CC = Array{Float64}(3, 3) - for vtype = ["Array", "SubArray"], Ctype = ["Array", "SubArray"] - vf = vtype == "Array" ? vvf : view(vvf, 1:3) - C = Ctype == "Array" ? CC : view(CC, 1:3, 1:3) - @test A_mul_Bt!(C, vf, vf) == vf*vf' - end -end - -# fallbacks & such for BlasFloats -let - AA = rand(Float64,6,6) - BB = rand(Float64,6,6) - CC = zeros(Float64,6,6) - for Atype = ["Array", "SubArray"], Btype = ["Array", "SubArray"], Ctype = ["Array", "SubArray"] - A = Atype == "Array" ? AA : view(AA, 1:6, 1:6) - B = Btype == "Array" ? BB : view(BB, 1:6, 1:6) - C = Ctype == "Array" ? CC : view(CC, 1:6, 1:6) - @test Base.LinAlg.At_mul_Bt!(C,A,B) == A.'*B.' - @test Base.LinAlg.A_mul_Bc!(C,A,B) == A*B.' - @test Base.LinAlg.Ac_mul_B!(C,A,B) == A.'*B - end -end - -# matrix algebra with subarrays of floats (stride != 1) -let - A = reshape(map(Float64,1:20),5,4) - Aref = A[1:2:end,1:2:end] - Asub = view(A, 1:2:5, 1:2:4) - b = [1.2,-2.5] - @test (Aref*b) == (Asub*b) - @test At_mul_B(Asub, Asub) == At_mul_B(Aref, Aref) - @test A_mul_Bt(Asub, Asub) == A_mul_Bt(Aref, Aref) - Ai = A .+ im - Aref = Ai[1:2:end,1:2:end] - Asub = view(Ai, 1:2:5, 1:2:4) - @test Ac_mul_B(Asub, Asub) == Ac_mul_B(Aref, Aref) - @test A_mul_Bc(Asub, Asub) == A_mul_Bc(Aref, Aref) -end - -# issue #15286 -let A = reshape(map(Float64, 1:20), 5, 4), C = zeros(8, 8), sC = view(C, 1:2:8, 1:2:8), B = reshape(map(Float64,-9:10),5,4) - @test At_mul_B!(sC, A, A) == A'*A - @test At_mul_B!(sC, A, B) == A'*B - - Aim = A .- im - C = zeros(Complex128,8,8) - sC = view(C, 1:2:8, 1:2:8) - B = reshape(map(Float64,-9:10),5,4) .+ im - @test Ac_mul_B!(sC, Aim, Aim) == Aim'*Aim - @test Ac_mul_B!(sC, Aim, B) == Aim'*B -end - -# syrk & herk -let - AA = reshape(1:1503, 501, 3).-750.0 - res = Float64[135228751 9979252 -115270247; 9979252 10481254 10983256; -115270247 10983256 137236759] - for Atype = ["Array", "SubArray"] - A = Atype == "Array" ? AA : view(AA, 1:501, 1:3) - @test At_mul_B(A, A) == res - @test A_mul_Bt(A',A') == res - end - cutoff = 501 - A = reshape(1:6*cutoff,2*cutoff,3).-(6*cutoff)/2 - Asub = view(A, 1:2:2*cutoff, 1:3) - Aref = A[1:2:2*cutoff, 1:3] - @test At_mul_B(Asub, Asub) == At_mul_B(Aref, Aref) - Ai = A .- im - Asub = view(Ai, 1:2:2*cutoff, 1:3) - Aref = Ai[1:2:2*cutoff, 1:3] - @test Ac_mul_B(Asub, Asub) == Ac_mul_B(Aref, Aref) - - @test_throws DimensionMismatch Base.LinAlg.syrk_wrapper!(zeros(5,5),'N',ones(6,5)) - @test_throws DimensionMismatch Base.LinAlg.herk_wrapper!(zeros(5,5),'N',ones(6,5)) -end - -# matmul for types w/o sizeof (issue #1282) -let - AA = fill(complex(1,1), 10, 10) - for Atype = ["Array", "SubArray"] - A = Atype == "Array" ? AA : view(AA, 1:10, 1:10) - A2 = A^2 - @test A2[1,1] == 20im - end -end - -let - AA = zeros(5, 5) - BB = ones(5) - CC = rand(5, 6) - for Atype = ["Array", "SubArray"], Btype = ["Array", "SubArray"] - for Ctype = ["Array", "SubArray"] - A = Atype == "Array" ? AA : view(AA, 1:5, 1:5) - B = Btype == "Array" ? BB : view(BB, 1:5) - C = Ctype == "Array" ? CC : view(CC, 1:5, 1:6) - - @test_throws DimensionMismatch scale!(A, B, C) - end - end -end - -# issue #6450 -@test dot(Any[1.0,2.0], Any[3.5,4.5]) === 12.5 - -for elty in (Float32,Float64,Complex64,Complex128) - x = convert(Vector{elty},[1.0,2.0,3.0]) - y = convert(Vector{elty},[3.5,4.5,5.5]) - @test_throws DimensionMismatch dot(x, 1:2, y, 1:3) - @test_throws BoundsError dot(x, 1:4, y, 1:4) - @test_throws BoundsError dot(x, 1:3, y, 2:4) - @test dot(x,1:2,y,1:2) == convert(elty,12.5) - @test x.'*y == convert(elty,29.0) -end - -vecdot_(x,y) = invoke(vecdot, Tuple{Any,Any}, x,y) # generic vecdot -let AA = [1+2im 3+4im; 5+6im 7+8im], BB = [2+7im 4+1im; 3+8im 6+5im] - for Atype = ["Array", "SubArray"], Btype = ["Array", "SubArray"] - A = Atype == "Array" ? AA : view(AA, 1:2, 1:2) - B = Btype == "Array" ? BB : view(BB, 1:2, 1:2) - @test vecdot(A,B) == dot(vec(A),vec(B)) == vecdot_(A,B) == vecdot(float.(A),float.(B)) - @test vecdot(Int[], Int[]) == 0 == vecdot_(Int[], Int[]) - @test_throws MethodError vecdot(Any[], Any[]) - @test_throws MethodError vecdot_(Any[], Any[]) - for n1 = 0:2, n2 = 0:2, d in (vecdot, vecdot_) - if n1 != n2 - @test_throws DimensionMismatch d(1:n1, 1:n2) - else - @test d(1:n1, 1:n2) ≈ vecnorm(1:n1)^2 - end - end - end -end - -# Issue 11978 -let - A = Array{Matrix{Float64}}(2, 2) - A[1,1] = eye(3) - A[1,2] = eye(3,2) - A[2,1] = eye(2,3) - A[2,2] = eye(2) - b = Array{Vector{Float64}}(2) - b[1] = ones(3) - b[2] = ones(2) - @test A*b == Vector{Float64}[[2,2,1], [2,2]] -end - -@test_throws ArgumentError Base.LinAlg.copytri!(ones(10,10),'Z') - -for elty in [Float32,Float64,Complex128,Complex64] - @test_throws DimensionMismatch Base.LinAlg.gemv!(ones(elty,10),'N',rand(elty,10,10),ones(elty,11)) - @test_throws DimensionMismatch Base.LinAlg.gemv!(ones(elty,11),'N',rand(elty,10,10),ones(elty,10)) - @test Base.LinAlg.gemv!(ones(elty,0),'N',rand(elty,0,0),rand(elty,0)) == ones(elty,0) - @test Base.LinAlg.gemv!(ones(elty,10), 'N',ones(elty,10,0),ones(elty,0)) == zeros(elty,10) - - @test Base.LinAlg.gemm_wrapper('N','N',eye(elty,10,10),eye(elty,10,10)) == eye(elty,10,10) - @test_throws DimensionMismatch Base.LinAlg.gemm_wrapper!(eye(elty,10,10),'N','N',eye(elty,10,11),eye(elty,10,10)) - @test_throws DimensionMismatch Base.LinAlg.gemm_wrapper!(eye(elty,10,10),'N','N',eye(elty,0,0),eye(elty,0,0)) - - A = rand(elty,3,3) - @test Base.LinAlg.matmul3x3('T','N',A,eye(elty,3)) == A.' -end - -# 13593, #13488 -let - aa = rand(3,3) - bb = rand(3,3) - for atype = ["Array", "SubArray"], btype = ["Array", "SubArray"] - a = atype == "Array" ? aa : view(aa, 1:3, 1:3) - b = btype == "Array" ? bb : view(bb, 1:3, 1:3) - @test_throws ArgumentError A_mul_B!(a, a, b) - @test_throws ArgumentError A_mul_B!(a, b, a) - @test_throws ArgumentError A_mul_B!(a, a, a) - end -end - -# Number types that lack conversion to the destination type (#14293) -struct RootInt - i::Int -end -import Base: *, transpose -(*)(x::RootInt, y::RootInt) = x.i*y.i -transpose(x::RootInt) = x -@test Base.promote_op(*, RootInt, RootInt) === Int - -a = [RootInt(3)] -C = [0] -A_mul_Bt!(C, a, a) -@test C[1] == 9 -a = [RootInt(2),RootInt(10)] -@test a*a' == [4 20; 20 100] -A = [RootInt(3) RootInt(5)] -@test A*a == [56] - -function test_mul(C, A, B) - A_mul_B!(C, A, B) - @test Array(A) * Array(B) ≈ C - @test A*B ≈ C -end - -let - eltypes = [Float32, Float64, Int64] - for k in [3, 4, 10] - T = rand(eltypes) - bi1 = Bidiagonal(rand(T, k), rand(T, k-1), rand(Bool)) - bi2 = Bidiagonal(rand(T, k), rand(T, k-1), rand(Bool)) - tri1 = Tridiagonal(rand(T,k-1), rand(T, k), rand(T, k-1)) - tri2 = Tridiagonal(rand(T,k-1), rand(T, k), rand(T, k-1)) - stri1 = SymTridiagonal(rand(T, k), rand(T, k-1)) - stri2 = SymTridiagonal(rand(T, k), rand(T, k-1)) - C = rand(T, k, k) - specialmatrices = (bi1, bi2, tri1, tri2, stri1, stri2) - for A in specialmatrices - B = specialmatrices[rand(1:length(specialmatrices))] - test_mul(C, A, B) - end - for S in specialmatrices - l = rand(1:6) - B = randn(k, l) - C = randn(k, l) - test_mul(C, S, B) - A = randn(l, k) - C = randn(l, k) - test_mul(C, A, S) - end - end - for T in eltypes - A = Bidiagonal(rand(T, 2), rand(T, 1), rand(Bool)) - B = Bidiagonal(rand(T, 2), rand(T, 1), rand(Bool)) - C = randn(2,2) - test_mul(C, A, B) - B = randn(2, 9) - C = randn(2, 9) - test_mul(C, A, B) - end - let - tri44 = Tridiagonal(randn(3), randn(4), randn(3)) - tri33 = Tridiagonal(randn(2), randn(3), randn(2)) - full43 = randn(4, 3) - full24 = randn(2, 4) - full33 = randn(3, 3) - full44 = randn(4, 4) - @test_throws DimensionMismatch A_mul_B!(full43, tri44, tri33) - @test_throws DimensionMismatch A_mul_B!(full44, tri44, tri33) - @test_throws DimensionMismatch A_mul_B!(full44, tri44, full43) - @test_throws DimensionMismatch A_mul_B!(full43, tri33, full43) - @test_throws DimensionMismatch A_mul_B!(full43, full43, tri44) - end -end - -# #18218 -module TestPR18218 - using Base.Test - import Base.*, Base.+, Base.zero - struct TypeA - x::Int - end - Base.convert(::Type{TypeA}, x::Int) = TypeA(x) - struct TypeB - x::Int - end - struct TypeC - x::Int - end - Base.convert(::Type{TypeC}, x::Int) = TypeC(x) - zero(c::TypeC) = TypeC(0) - zero(::Type{TypeC}) = TypeC(0) - (*)(x::Int, a::TypeA) = TypeB(x*a.x) - (*)(a::TypeA, x::Int) = TypeB(a.x*x) - (+)(a::Union{TypeB,TypeC}, b::Union{TypeB,TypeC}) = TypeC(a.x+b.x) - A = TypeA[1 2; 3 4] - b = [1, 2] - d = A * b - @test typeof(d) == Vector{TypeC} - @test d == TypeC[5, 11] -end diff --git a/julia-0.6.3/share/julia/test/linalg/pinv.jl b/julia-0.6.3/share/julia/test/linalg/pinv.jl deleted file mode 100644 index f1f7745..0000000 --- a/julia-0.6.3/share/julia/test/linalg/pinv.jl +++ /dev/null @@ -1,327 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -# -# Test the pseudo-inverse -# - -debug = false - -using Base.Test - -function hilb(T::Type, n::Integer) - a=Array{T}(n,n) - for i=1:n - for j=1:n - a[j,i]=one(T)/(i+j-one(T)) - end - end - return a -end -hilb(n::Integer) = hilb(Float64,n) - -function hilb(T::Type, m::Integer, n::Integer) - a=Array{T}(m,n) - for i=1:n - for j=1:m - a[j,i]=one(T)/(i+j-one(T)) - end - end - return a -end -hilb(m::Integer, n::Integer) = hilb(Float64,m,n) - -function onediag(T::Type, m::Integer, n::Integer) - a=zeros(T,m,n) - for i=1:min(n,m) - a[i,i]=one(T)/(float(i)^5) - end - a[1,1] = 0 - a[min(m,n),min(m,n)] = 0 - return a -end -onediag(m::Integer, n::Integer) = onediag(Float64, m::Integer, n::Integer) - -function onediag_sparse(T::Type, n::Integer) - a=zeros(T,n) - for i=1:n - a[i]=one(T)/(float(i)^5) - end - a[1] = 0 - a[n] = 0 - return Diagonal(a) -end -onediag_sparse(n::Integer) = onediag_sparse(Float64, n::Integer) - -function tridiag(T::Type, m::Integer, n::Integer) - a=zeros(T,m,n) - for i=1:min(n,m) - a[i,i]=one(T)/(float(i)^5) - end - for i=1:min(n,m)-1 - a[i+1,i]=2*one(T)/(float(i)^5) - a[1,i+1]=2*one(T)/(float(i)^5) - end - return a -end -tridiag(m::Integer, n::Integer) = tridiag(Float64, m::Integer, n::Integer) - -function randn_float64(m::Integer, n::Integer) - a=randn(m,n) - b=Array{Float64}(m,n) - for i=1:n - for j=1:m - b[j,i]=convert(Float64,a[j,i]) - end - end - return b -end - -function randn_float32(m::Integer, n::Integer) - a=randn(m,n) - b=Array{Float32}(m,n) - for i=1:n - for j=1:m - b[j,i]=convert(Float32,a[j,i]) - end - end - return b -end - - -function test_pinv(a,m,n,tol1,tol2,tol3) - debug && println("=== julia/matlab pinv, default tol=eps(1.0)*max(size(a)) ===") - apinv = @inferred pinv(a) - - @test vecnorm(a*apinv*a-a)/vecnorm(a) ≈ 0 atol=tol1 - x0 = randn(n); b = a*x0; x = apinv*b - @test vecnorm(a*x-b)/vecnorm(b) ≈ 0 atol=tol1 - debug && println(vecnorm(a*apinv*a - a)/vecnorm(a)) - debug && println(vecnorm(a*x-b)/vecnorm(b)) - - - debug && println("=== julia pinv, tol=sqrt(eps(1.0)) ===") - apinv = pinv(a,sqrt(eps(real(one(eltype(a)))))) - - @test vecnorm(a*apinv*a-a)/vecnorm(a) ≈ 0 atol=tol2 - x0 = randn(n); b = a*x0; x = apinv*b - @test vecnorm(a*x-b)/vecnorm(b) ≈ 0 atol=tol2 - debug && println(vecnorm(a*apinv*a - a)/vecnorm(a)) - debug && println(vecnorm(a*x-b)/vecnorm(b)) -end - - -srand(12345) - -let - for eltya in (Float64, Complex128) - - debug && println("\n\n<<<<<", eltya, ">>>>>") - - m = 1000 - n = 100 - debug && println("\n\n n = ", n, ", m = ",m) - - default_tol = (real(one(eltya))) * max(m,n) * 10 - - debug && println("\n--- dense/ill-conditioned matrix ---\n") - ### a = randn_float64(m,n) * hilb(eltya,n) - a = hilb(eltya,m,n) - test_pinv(a,m,n,1e-2,1e-5,1e-5) - - debug && println("\n--- dense/diagonal matrix ---\n") - a = onediag(eltya,m,n) - test_pinv(a,m,n,default_tol,default_tol,default_tol) - - debug && println("\n--- dense/tri-diagonal matrix ---\n") - a = tridiag(eltya,m,n) - test_pinv(a,m,n,default_tol,1e-5,default_tol) - - debug && println("\n--- Diagonal matrix ---\n") - a = onediag_sparse(eltya,m) - test_pinv(a,m,m,default_tol,default_tol,default_tol) - - m = 100 - n = 100 - debug && println("\n\n n = ", n, ", m = ",m) - - default_tol = (real(one(eltya))) * max(m,n) * 10 - - debug && println("\n--- dense/ill-conditioned matrix ---\n") - ### a = randn_float64(m,n) * hilb(eltya,n) - a = hilb(eltya,m,n) - test_pinv(a,m,n,1e-2,1e-5,1e-5) - - debug && println("\n--- dense/diagonal matrix ---\n") - a = onediag(eltya,m,n) - test_pinv(a,m,n,default_tol,default_tol,default_tol) - - debug && println("\n--- dense/tri-diagonal matrix ---\n") - a = tridiag(eltya,m,n) - test_pinv(a,m,n,default_tol,1e-5,default_tol) - - debug && println("\n--- Diagonal matrix ---\n") - a = onediag_sparse(eltya,m) - test_pinv(a,m,m,default_tol,default_tol,default_tol) - - m = 100 - n = 1000 - debug && println("\n\n n = ", n, ", m = ",m) - - default_tol = (real(one(eltya))) * max(m,n) * 10 - - debug && println("\n--- dense/ill-conditioned matrix ---\n") - ### a = randn_float64(m,n) * hilb(eltya,n) - a = hilb(eltya,m,n) - test_pinv(a,m,n,1e-2,1e-5,1e-5) - - debug && println("\n--- dense/diagonal matrix ---\n") - a = onediag(eltya,m,n) - test_pinv(a,m,n,default_tol,default_tol,default_tol) - - debug && println("\n--- dense/tri-diagonal matrix ---\n") - a = tridiag(eltya,m,n) - test_pinv(a,m,n,default_tol,1e-5,default_tol) - - debug && println("\n--- Diagonal matrix ---\n") - a = onediag_sparse(eltya,m) - test_pinv(a,m,m,default_tol,default_tol,default_tol) - end -end - - -for eltya in (Float32, Complex64) - - debug && println("\n\n<<<<<", eltya, ">>>>>") - - m = 1000 - n = 100 - debug && println("\n\n n = ", n, ", m = ",m) - - default_tol = (real(one(eltya))) * max(m,n) * 10 - - debug && println("\n--- dense/ill-conditioned matrix ---\n") -### a = randn_float32(m,n) * hilb(eltya,n) - a = hilb(eltya,m,n) - test_pinv(a,m,n,1e0,1e-2,1e-2) - - debug && println("\n--- dense/diagonal matrix ---\n") - a = onediag(eltya,m,n) - test_pinv(a,m,n,default_tol,default_tol,default_tol) - - debug && println("\n--- dense/tri-diagonal matrix ---\n") - a = tridiag(eltya,m,n) - test_pinv(a,m,n,default_tol,1e-2,default_tol) - - debug && println("\n--- Diagonal matrix ---\n") - a = onediag_sparse(eltya,m) - test_pinv(a,m,m,default_tol,default_tol,default_tol) - - m = 100 - n = 100 - debug && println("\n\n n = ", n, ", m = ",m) - - default_tol = (real(one(eltya))) * max(m,n) * 10 - - debug && println("\n--- dense/ill-conditioned matrix ---\n") -### a = randn_float32(m,n) * hilb(eltya,n) - a = hilb(eltya,m,n) - test_pinv(a,m,n,1e0,1e-2,1e-2) - - debug && println("\n--- dense/diagonal matrix ---\n") - a = onediag(eltya,m,n) - test_pinv(a,m,n,default_tol,default_tol,default_tol) - - debug && println("\n--- dense/tri-diagonal matrix ---\n") - a = tridiag(eltya,m,n) - test_pinv(a,m,n,default_tol,1e-2,default_tol) - - debug && println("\n--- Diagonal matrix ---\n") - a = onediag_sparse(eltya,m) - test_pinv(a,m,m,default_tol,default_tol,default_tol) - - m = 100 - n = 1000 - debug && println("\n\n n = ", n, ", m = ",m) - - default_tol = (real(one(eltya))) * max(m,n) * 10 - - debug && println("\n--- dense/ill-conditioned matrix ---\n") -### a = randn_float32(m,n) * hilb(eltya,n) - a = hilb(eltya,m,n) - test_pinv(a,m,n,1e0,1e-2,1e-2) - - debug && println("\n--- dense/diagonal matrix ---\n") - a = onediag(eltya,m,n) - test_pinv(a,m,n,default_tol,default_tol,default_tol) - - debug && println("\n--- dense/tri-diagonal matrix ---\n") - a = tridiag(eltya,m,n) - test_pinv(a,m,n,default_tol,1e-2,default_tol) - - debug && println("\n--- Diagonal matrix ---\n") - a = onediag_sparse(eltya,m) - test_pinv(a,m,m,default_tol,default_tol,default_tol) - -end - -# test zero matrices -for eltya in (Float32, Float64, Complex64, Complex128) - debug && println("\n\n<<<<<", eltya, ">>>>>") - debug && println("\n--- zero constant ---") - a = pinv(zero(eltya)) - @test a ≈ 0.0 -end - -for eltya in (Float32, Float64, Complex64, Complex128) - debug && println("\n\n<<<<<", eltya, ">>>>>") - debug && println("\n--- zero vector ---") - a = pinv([zero(eltya); zero(eltya)]) - @test a[1] ≈ 0.0 - @test a[2] ≈ 0.0 -end - -for eltya in (Float32, Float64, Complex64, Complex128) - debug && println("\n\n<<<<<", eltya, ">>>>>") - debug && println("\n--- zero Diagonal matrix ---") - a = pinv(Diagonal([zero(eltya); zero(eltya)])) - @test a.diag[1] ≈ 0.0 - @test a.diag[2] ≈ 0.0 -end - -# test sub-normal matrices -for eltya in (Float32, Float64) - debug && println("\n\n<<<<<", eltya, ">>>>>") - debug && println("\n--- sub-normal constant ---") - a = pinv(realmin(eltya)/100) - @test a ≈ 0.0 - debug && println("\n\n<<<<<Complex{", eltya, "}>>>>>") - debug && println("\n--- sub-normal constant ---") - a = pinv(realmin(eltya)/100*(1+1im)) - @test a ≈ 0.0 -end - -for eltya in (Float32, Float64) - debug && println("\n\n<<<<<", eltya, ">>>>>") - debug && println("\n--- sub-normal vector ---") - a = pinv([realmin(eltya); realmin(eltya)]/100) - @test a[1] ≈ 0.0 - @test a[2] ≈ 0.0 - debug && println("\n\n<<<<<Complex{", eltya, "}>>>>>") - debug && println("\n--- sub-normal vector ---") - a = pinv([realmin(eltya); realmin(eltya)]/100*(1+1im)) - @test a[1] ≈ 0.0 - @test a[2] ≈ 0.0 -end - -for eltya in (Float32, Float64) - debug && println("\n\n<<<<<", eltya, ">>>>>") - debug && println("\n--- sub-normal Diagonal matrix ---") - a = pinv(Diagonal([realmin(eltya); realmin(eltya)]/100)) - @test a.diag[1] ≈ 0.0 - @test a.diag[2] ≈ 0.0 - debug && println("\n\n<<<<<Complex{", eltya, "}>>>>>") - debug && println("\n--- sub-normal Diagonal matrix ---") - a = pinv(Diagonal([realmin(eltya); realmin(eltya)]/100*(1+1im))) - @test a.diag[1] ≈ 0.0 - @test a.diag[2] ≈ 0.0 -end diff --git a/julia-0.6.3/share/julia/test/linalg/qr.jl b/julia-0.6.3/share/julia/test/linalg/qr.jl deleted file mode 100644 index b80f3e8..0000000 --- a/julia-0.6.3/share/julia/test/linalg/qr.jl +++ /dev/null @@ -1,198 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -debug = false -using Base.Test - -using Base.LinAlg: BlasComplex, BlasFloat, BlasReal, QRPivoted - -n = 10 - -# Split n into 2 parts for tests needing two matrices -n1 = div(n, 2) -n2 = 2*n1 - -srand(1234321) - -areal = randn(n,n)/2 -aimg = randn(n,n)/2 -a2real = randn(n,n)/2 -a2img = randn(n,n)/2 -breal = randn(n,2)/2 -bimg = randn(n,2)/2 - -for eltya in (Float32, Float64, Complex64, Complex128, BigFloat, Int) - a = eltya == Int ? rand(1:7, n, n) : convert(Matrix{eltya}, eltya <: Complex ? complex.(areal, aimg) : areal) - a2 = eltya == Int ? rand(1:7, n, n) : convert(Matrix{eltya}, eltya <: Complex ? complex.(a2real, a2img) : a2real) - asym = a'+a # symmetric indefinite - apd = a'*a # symmetric positive-definite - ε = εa = eps(abs(float(one(eltya)))) - - for eltyb in (Float32, Float64, Complex64, Complex128, Int) - b = eltyb == Int ? rand(1:5, n, 2) : convert(Matrix{eltyb}, eltyb <: Complex ? complex.(breal, bimg) : breal) - εb = eps(abs(float(one(eltyb)))) - ε = max(εa,εb) - - α = rand(eltyb) - aα = fill(α,1,1) - @test qrfact(α)[:Q]*qrfact(α)[:R] ≈ qrfact(aα)[:Q]*qrfact(aα)[:R] - @test abs(qrfact(α)[:Q][1,1]) ≈ one(eltyb) - tab = promote_type(eltya,eltyb) - -debug && println("\ntype of a: ", eltya, " type of b: ", eltyb, "\n") -debug && println("QR decomposition (without pivoting)") - for i = 1:2 - let a = i == 1 ? a : view(a, 1:n - 1, 1:n - 1), b = i == 1 ? b : view(b, 1:n - 1), n = i == 1 ? n : n - 1 - qra = @inferred qrfact(a) - @inferred qr(a) - q, r = qra[:Q], qra[:R] - @test_throws KeyError qra[:Z] - @test q'*full(q, thin=false) ≈ eye(n) - @test q*full(q, thin=false)' ≈ eye(n) - @test q'*eye(n)' ≈ full(q, thin=false)' - @test full(q, thin=false)'q ≈ eye(n) - @test eye(n)'q' ≈ full(q, thin=false)' - @test q*r ≈ a - @test a*(qra\b) ≈ b atol=3000ε - @test full(qra) ≈ a - @test A_mul_Bc(eye(eltyb,size(q.factors,2)),q)*full(q,thin=false) ≈ eye(n) atol=5000ε - if eltya != Int - @test eye(eltyb,n)*q ≈ convert(AbstractMatrix{tab},q) - ac = copy(a) - @test qrfact!(a[:, 1:5])\b == qrfact!(view(ac, :, 1:5))\b - end - rstring = sprint(show,r) - qstring = sprint(show,q) - @test sprint(show,qra) == "$(typeof(qra)) with factors Q and R:\n$qstring\n$rstring" - -debug && println("Thin QR decomposition (without pivoting)") - qra = @inferred qrfact(a[:,1:n1], Val{false}) - @inferred qr(a[:,1:n1], Val{false}) - q,r = qra[:Q], qra[:R] - @test_throws KeyError qra[:Z] - @test q'*full(q, thin=false) ≈ eye(n) - @test q'*full(q) ≈ eye(n,n1) - @test q*r ≈ a[:,1:n1] - @test q*b[1:n1] ≈ full(q)*b[1:n1] atol=100ε - @test q*b ≈ full(q,thin=false)*b atol=100ε - @test_throws DimensionMismatch q*b[1:n1 + 1] - @test_throws DimensionMismatch b[1:n1 + 1]*q' - @test A_mul_Bc(UpperTriangular(eye(eltyb,size(q.factors,2))),q)*full(q,thin=false) ≈ eye(n1,n) atol=5000ε - if eltya != Int - @test eye(eltyb,n)*q ≈ convert(AbstractMatrix{tab},q) - end - -debug && println("(Automatic) Fat (pivoted) QR decomposition") - @inferred qrfact(a, Val{true}) - @inferred qr(a, Val{true}) - - qrpa = factorize(a[1:n1,:]) - q,r = qrpa[:Q], qrpa[:R] - @test_throws KeyError qrpa[:Z] - p = qrpa[:p] - @test q'*full(q, thin=false) ≈ eye(n1) - @test q*full(q, thin=false)' ≈ eye(n1) - @test (UpperTriangular(eye(eltya,size(q,2)))*q')*full(q, thin=false) ≈ eye(n1) - @test q*r ≈ (isa(qrpa,QRPivoted) ? a[1:n1,p] : a[1:n1,:]) - @test q*r[:,invperm(p)] ≈ a[1:n1,:] - @test q*r*qrpa[:P].' ≈ a[1:n1,:] - @test a[1:n1,:]*(qrpa\b[1:n1]) ≈ b[1:n1] atol=5000ε - @test full(qrpa) ≈ a[1:5,:] - @test_throws DimensionMismatch q*b[1:n1+1] - @test_throws DimensionMismatch b[1:n1+1]*q' - if eltya != Int - @test eye(eltyb,n1)*q ≈ convert(AbstractMatrix{tab},q) - end - -debug && println("(Automatic) Thin (pivoted) QR decomposition") - qrpa = factorize(a[:,1:n1]) - q,r = qrpa[:Q], qrpa[:R] - @test_throws KeyError qrpa[:Z] - p = qrpa[:p] - @test q'*full(q, thin=false) ≈ eye(n) - @test q*full(q, thin=false)' ≈ eye(n) - @test q*r ≈ a[:,p] - @test q*r[:,invperm(p)] ≈ a[:,1:n1] - @test full(qrpa) ≈ a[:,1:5] - @test_throws DimensionMismatch q*b[1:n1+1] - @test_throws DimensionMismatch b[1:n1+1]*q' - @test A_mul_Bc(UpperTriangular(eye(eltyb,size(q.factors,2))),q)*full(q,thin=false) ≈ eye(n1,n) atol=5000ε - if eltya != Int - @test eye(eltyb,n)*q ≈ convert(AbstractMatrix{tab},q) - end - end - end - -debug && println("Matmul with QR factorizations") - if eltya != Int - qrpa = factorize(a[:,1:n1]) - q, r = qrpa[:Q], qrpa[:R] - @test A_mul_B!(full(q, thin=false)',q) ≈ eye(n) - @test_throws DimensionMismatch A_mul_B!(eye(eltya,n+1),q) - @test A_mul_Bc!(full(q, thin=false),q) ≈ eye(n) - @test_throws DimensionMismatch A_mul_Bc!(eye(eltya,n+1),q) - @test_throws BoundsError size(q,-1) - @test_throws DimensionMismatch Base.LinAlg.A_mul_B!(q,zeros(eltya,n1+1)) - @test_throws DimensionMismatch Base.LinAlg.Ac_mul_B!(q,zeros(eltya,n1+1)) - - qra = qrfact(a[:,1:n1], Val{false}) - q, r = qra[:Q], qra[:R] - @test A_mul_B!(full(q, thin=false)',q) ≈ eye(n) - @test_throws DimensionMismatch A_mul_B!(eye(eltya,n+1),q) - @test A_mul_Bc!(full(q, thin=false),q) ≈ eye(n) - @test_throws DimensionMismatch A_mul_Bc!(eye(eltya,n+1),q) - @test_throws BoundsError size(q,-1) - @test_throws DimensionMismatch q * eye(Int8,n+4) - end - end -end - -# Because transpose(x) == x -@test_throws ErrorException transpose(qrfact(randn(3,3))) -@test_throws ErrorException ctranspose(qrfact(randn(3,3))) -@test_throws ErrorException transpose(qrfact(randn(3,3), Val{false})) -@test_throws ErrorException ctranspose(qrfact(randn(3,3), Val{false})) -@test_throws ErrorException transpose(qrfact(big.(randn(3,3)))) -@test_throws ErrorException ctranspose(qrfact(big.(randn(3,3)))) - -# Issue 7304 -let - A = [-√.5 -√.5; -√.5 √.5] - Q = full(qrfact(A)[:Q]) - @test vecnorm(A-Q) < eps() -end - -let - debug && println("qr on AbstractVector") - - vr = [3.0, 4.0] - for Tr in (Float32, Float64) - for T in (Tr, Complex{Tr}) - v = convert(Vector{T}, vr) - nv, nm = qr(v) - @test norm(nv - [0.6, 0.8], Inf) < eps(Tr) - @test nm == 5.0 - end - end -end - -@test qr(Int[]) == (Int[],1) -@test Base.LinAlg.qr!(Int[1]) == (Int[1],1) - -B = rand(7,2) -@test (1:7)\B ≈ collect(1:7)\B - -# Issue 16520 -@test_throws DimensionMismatch ones(3,2)\(1:5) - -# Issue 22810 -let - A = zeros(1, 2) - B = zeros(1, 1) - @test A \ B == zeros(2, 1) - @test qrfact(A, Val{true}) \ B == zeros(2, 1) -end - -@testset "Issue 24107" begin - A = rand(200,2) - @test A \ linspace(0,1,200) == A \ collect(linspace(0,1,200)) -end diff --git a/julia-0.6.3/share/julia/test/linalg/rowvector.jl b/julia-0.6.3/share/julia/test/linalg/rowvector.jl deleted file mode 100644 index 8d0d140..0000000 --- a/julia-0.6.3/share/julia/test/linalg/rowvector.jl +++ /dev/null @@ -1,275 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -@testset "Core" begin - v = [1,2,3] - z = [1+im,2,3] - - @test RowVector(v) == [1 2 3] - @test RowVector{Int}(v) == [1 2 3] - @test size(RowVector{Int}(3)) === (1,3) - @test size(RowVector{Int}(1,3)) === (1,3) - @test size(RowVector{Int}((3,))) === (1,3) - @test size(RowVector{Int}((1,3))) === (1,3) - @test_throws ErrorException RowVector{Float64, Vector{Int}}(v) - - @test (v.')::RowVector == [1 2 3] - @test (v')::RowVector == [1 2 3] - @test (z.')::RowVector == [1+im 2 3] - @test (z')::RowVector == [1-im 2 3] - - rv = v.' - tz = z.' - - @test (rv.')::Vector == [1, 2, 3] - @test (rv')::Vector == [1, 2, 3] - @test (tz.')::Vector == [1+im, 2, 3] - @test (tz')::Vector == [1-im, 2, 3] - - @test conj(rv) === rv - @test conj(tz) == [1-im 2 3] - - @test isa(similar(rv), RowVector) - @test isa(similar(rv, Float64), RowVector) - @test isa(copy(rv), RowVector) - - @test rv[2] === v[2] - @test rv[1,2] === v[2] - - @test (rv2 = copy(rv); rv2[2] = 6; rv2[2] === 6) - @test (rv2 = copy(rv); rv2[1,2] = 6; rv2[2] === 6) - - @test length(rv) === 3 - @test size(rv) === (1,3) - @test size(rv,1) === 1 - @test size(rv,2) === 3 - - @test map(-, rv)::RowVector == [-1 -2 -3] - @test (-).(rv)::RowVector == [-1 -2 -3] - @test (-).(rv,1)::RowVector == [0 1 2] - - y = rand(Complex{Float64},3) - @test sum(abs2, imag.(diag(y .+ y'))) < 1e-20 -end - -@testset "Diagonal ambiguity methods" begin - d = Diagonal([1,2,3]) - v = [2,3,4] - rv = v.' - - @test (rv*d)::RowVector == [2,6,12].' - @test_throws DimensionMismatch d*rv - - @test (d*rv.')::Vector == [2,6,12] - - @test_throws DimensionMismatch rv.'*d - - @test (d*rv')::Vector == [2,6,12] - - @test_throws DimensionMismatch rv'*d - - @test (rv/d)::RowVector ≈ [2/1 3/2 4/3] - - @test_throws DimensionMismatch d \ rv -end - -@testset "Bidiagonal ambiguity methods" begin - bd = Bidiagonal([1,2,3], [0,0], true) - v = [2,3,4] - rv = v.' - - @test (rv/bd)::RowVector ≈ [2/1 3/2 4/3] - - @test_throws DimensionMismatch bd \ rv -end - -@testset "hcat" begin - @test isa([([1, 2, 3].') 4], RowVector{Int}) - @test isa([([1, 2, 3].') ([4, 5].')], RowVector{Int}) -end - -@testset "Left Division" begin - mat = diagm([1,2,3]) - v = [2,3,4] - rv = v.' - - @test_throws DimensionMismatch mat \ rv -end - -@testset "Multiplication" begin - v = [1,2,3] - rv = v.' - mat = diagm([1,2,3]) - - @test (rv*v) === 14 - @test (rv*mat)::RowVector == [1 4 9] - @test [1]*reshape([1],(1,1)) == reshape([1], (1,1)) - @test_throws DimensionMismatch rv*rv - @test (v*rv)::Matrix == [1 2 3; 2 4 6; 3 6 9] - @test_throws DimensionMismatch v*v # Was previously a missing method error, now an error message - @test_throws DimensionMismatch mat*rv - - @test_throws DimensionMismatch rv*v.' - @test (rv*mat.')::RowVector == [1 4 9] - @test [1]*reshape([1],(1,1)).' == reshape([1], (1,1)) - @test rv*rv.' === 14 - @test_throws DimensionMismatch v*rv.' - @test (v*v.')::Matrix == [1 2 3; 2 4 6; 3 6 9] - @test (mat*rv.')::Vector == [1,4,9] - - @test (rv.'*v.')::Matrix == [1 2 3; 2 4 6; 3 6 9] - @test_throws DimensionMismatch rv.'*mat.' - @test (v.'*mat.')::RowVector == [1 4 9] - @test_throws DimensionMismatch rv.'*rv.' - @test v.'*rv.' === 14 - @test_throws DimensionMismatch v.'*v.' - @test (mat.'*rv.')::Vector == [1,4,9] - - @test_throws DimensionMismatch rv.'*v - @test_throws DimensionMismatch rv.'*mat - @test (v.'*mat)::RowVector == [1 4 9] - @test (rv.'*rv)::Matrix == [1 2 3; 2 4 6; 3 6 9] - @test_throws DimensionMismatch v.'*rv - @test v.'*v === 14 - @test_throws DimensionMismatch mat.'*rv - - z = [1+im,2,3] - cz = z' - mat = diagm([1+im,2,3]) - - @test cz*z === 15 + 0im - - @test_throws DimensionMismatch cz*z' - @test (cz*mat')::RowVector == [-2im 4 9] - @test [1]*reshape([1],(1,1))' == reshape([1], (1,1)) - @test cz*cz' === 15 + 0im - @test_throws DimensionMismatch z*cz' - @test (z*z')::Matrix == [2 2+2im 3+3im; 2-2im 4 6; 3-3im 6 9] - @test (mat*cz')::Vector == [2im,4,9] - - @test (cz'*z')::Matrix == [2 2+2im 3+3im; 2-2im 4 6; 3-3im 6 9] - @test_throws DimensionMismatch cz'*mat' - @test (z'*mat')::RowVector == [-2im 4 9] - @test_throws DimensionMismatch cz'*cz' - @test z'*cz' === 15 + 0im - @test_throws DimensionMismatch z'*z' - @test (mat'*cz')::Vector == [2,4,9] - - @test_throws DimensionMismatch cz'*z - @test_throws DimensionMismatch cz'*mat - @test (z'*mat)::RowVector == [2 4 9] - @test (cz'*cz)::Matrix == [2 2+2im 3+3im; 2-2im 4 6; 3-3im 6 9] - @test_throws DimensionMismatch z'*cz - @test z'*z === 15 + 0im - @test_throws DimensionMismatch mat'*cz -end - -@testset "norm" begin - @test norm([3.0,4.0].') ≈ 5.0 - @test norm([3.0,4.0].', 1) ≈ 4.0 - @test norm([3.0,4.0].', Inf) ≈ 7.0 -end - -@testset "QR ambiguity methods" begin - qrmat = Base.LinAlg.getq(qrfact(eye(3))) - v = [2,3,4] - rv = v.' - - @test (rv*qrmat')::RowVector == [2 3 4] -end - -@testset "Right Division" begin - mat = diagm([1,2,3]) - v = [2,3,4] - rv = v.' - - @test (rv/mat)::RowVector ≈ [2/1 3/2 4/3] - - @test (v.'/mat)::RowVector ≈ [2/1 3/2 4/3] - @test (v.'/mat.')::RowVector ≈ [2/1 3/2 4/3] - @test (rv/mat.')::RowVector ≈ [2/1 3/2 4/3] - - @test (v'/mat)::RowVector ≈ [2/1 3/2 4/3] - @test (v'/mat')::RowVector ≈ [2/1 3/2 4/3] - @test (rv/mat')::RowVector ≈ [2/1 3/2 4/3] -end - -@testset "Sparse ambiguity methods" begin - mat = sparse(diagm([1,2,3])) - v = [2,3,4] - rv = v.' - - @test (rv/mat)::RowVector ≈ [2/1 3/2 4/3] - - @test_throws DimensionMismatch mat\rv -end - -@testset "AbstractTriangular ambiguity methods" begin - ut = UpperTriangular([1 0 0; 0 2 0; 0 0 3]) - v = [2,3,4] - rv = v.' - - @test (rv*ut)::RowVector == [2 6 12] - @test_throws DimensionMismatch ut*rv - - @test (rv*ut.')::RowVector == [2 6 12] - @test (ut*rv.')::Vector == [2,6,12] - - @test (ut.'*rv.')::Vector == [2,6,12] - @test_throws DimensionMismatch rv.'*ut.' - - @test_throws DimensionMismatch ut.'*rv - @test_throws DimensionMismatch rv.'*ut - - @test (rv*ut')::RowVector == [2 6 12] - @test (ut*rv')::Vector == [2,6,12] - - @test_throws DimensionMismatch rv'*ut' - @test (ut'*rv')::Vector == [2,6,12] - - @test_throws DimensionMismatch ut'*rv - @test_throws DimensionMismatch rv'*ut - - @test (rv/ut)::RowVector ≈ [2/1 3/2 4/3] - @test (rv/ut.')::RowVector ≈ [2/1 3/2 4/3] - @test (rv/ut')::RowVector ≈ [2/1 3/2 4/3] - - @test_throws DimensionMismatch ut\rv -end - -# issue #20389 -@testset "1 row/col vec*mat" begin - let x=[1,2,3], A=ones(1,4), y=x', B=A', C=x.*A - @test x*A == y'*A == x*B' == y'*B' == C - @test A'*x' == A'*y == B*x' == B*y == C' - end -end -@testset "complex 1 row/col vec*mat" begin - let x=[1,2,3]*im, A=ones(1,4)*im, y=x', B=A', C=x.*A - @test x*A == y'*A == x*B' == y'*B' == C - @test A'*x' == A'*y == B*x' == B*y == C' - end -end - -@testset "issue #20979" begin - f20979(z::Complex) = [z.re -z.im; z.im z.re] - v = [1+2im]' - @test (f20979.(v))[1] == f20979(v[1]) - @test f20979.(v) == f20979.(collect(v)) - - w = rand(Complex128, 3) - @test f20979.(v') == f20979.(collect(v')) == (f20979.(v))' - - g20979(x, y) = [x[2,1] x[1,2]; y[1,2] y[2,1]] - v = [rand(2,2), rand(2,2), rand(2,2)] - @test g20979.(v', v') == g20979.(collect(v'), collect(v')) == - map(g20979, v', v') == map(g20979, collect(v'), collect(v')) -end - -@testset "ambiguity between * methods with RowVectors and ConjRowVectors (#20971)" begin - @test RowVector(ConjArray(ones(4))) * ones(4) == 4 -end - -@testset "setindex!/getindex" begin - # setindex!(v::RowVector, ...) should return v rather than v's parent - @test setindex!(RowVector([1, 2, 3]), 4, 1)::RowVector == [4 2 3] -end diff --git a/julia-0.6.3/share/julia/test/linalg/schur.jl b/julia-0.6.3/share/julia/test/linalg/schur.jl deleted file mode 100644 index 3e9913d..0000000 --- a/julia-0.6.3/share/julia/test/linalg/schur.jl +++ /dev/null @@ -1,109 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -using Base.Test - -using Base.LinAlg: BlasComplex, BlasFloat, BlasReal, QRPivoted - -n = 10 - -# Split n into 2 parts for tests needing two matrices -n1 = div(n, 2) -n2 = 2*n1 - -srand(1234321) - -areal = randn(n,n)/2 -aimg = randn(n,n)/2 - -@testset for eltya in (Float32, Float64, Complex64, Complex128, Int) - a = eltya == Int ? rand(1:7, n, n) : convert(Matrix{eltya}, eltya <: Complex ? complex.(areal, aimg) : areal) - asym = a'+a # symmetric indefinite - apd = a'*a # symmetric positive-definite - @testset for atype in ("Array", "SubArray") - if atype == "Array" - a = a - else - a = view(a, 1:n, 1:n) - asym = view(asym, 1:n, 1:n) - apd = view(apd, 1:n, 1:n) - end - ε = εa = eps(abs(float(one(eltya)))) - - d,v = eig(a) - f = schurfact(a) - @test f[:vectors]*f[:Schur]*f[:vectors]' ≈ a - @test sort(real(f[:values])) ≈ sort(real(d)) - @test sort(imag(f[:values])) ≈ sort(imag(d)) - @test istriu(f[:Schur]) || eltype(a)<:Real - @test AbstractArray(f) ≈ a - @test_throws KeyError f[:A] - - tstring = sprint(show,f[:T]) - zstring = sprint(show,f[:Z]) - vstring = sprint(show,f[:values]) - @test sprint(show,f) == "$(typeof(f)) with factors T and Z:\n$tstring\n$(zstring)\nand values:\n$vstring" - @testset "Reorder Schur" begin - # use asym for real schur to enforce tridiag structure - # avoiding partly selection of conj. eigenvalues - ordschura = eltya <: Complex ? a : asym - S = schurfact(ordschura) - select = bitrand(n) - O = ordschur(S, select) - sum(select) != 0 && @test S[:values][find(select)] ≈ O[:values][1:sum(select)] - @test O[:vectors]*O[:Schur]*O[:vectors]' ≈ ordschura - @test_throws KeyError f[:A] - Snew = Base.LinAlg.Schur(S.T, S.Z, S.values) - SchurNew = ordschur!(copy(Snew), select) - @test O[:vectors] ≈ SchurNew[:vectors] - @test O[:Schur] ≈ SchurNew[:Schur] - end - - if atype == "Array" - a1_sf = a[1:n1, 1:n1] - a2_sf = a[n1+1:n2, n1+1:n2] - else - a1_sf = view(a, 1:n1, 1:n1) - a2_sf = view(a, n1+1:n2, n1+1:n2) - end - @testset "Generalized Schur" begin - f = schurfact(a1_sf, a2_sf) - @test f[:Q]*f[:S]*f[:Z]' ≈ a1_sf - @test f[:Q]*f[:T]*f[:Z]' ≈ a2_sf - @test istriu(f[:S]) || eltype(a)<:Real - @test istriu(f[:T]) || eltype(a)<:Real - @test_throws KeyError f[:A] - end - @testset "Reorder Generalized Schur" begin - NS = schurfact(a1_sf, a2_sf) - # Currently just testing with selecting gen eig values < 1 - select = abs2.(NS[:values]) .< 1 - m = sum(select) - S = ordschur(NS, select) - # Make sure that the new factorization stil factors matrix - @test S[:Q]*S[:S]*S[:Z]' ≈ a1_sf - @test S[:Q]*S[:T]*S[:Z]' ≈ a2_sf - # Make sure that we have sorted it correctly - @test NS[:values][find(select)] ≈ S[:values][1:m] - - Snew = Base.LinAlg.GeneralizedSchur(NS.S, NS.T, NS.alpha, NS.beta, NS.Q, NS.Z) - SchurNew = ordschur!(copy(Snew), select) - @test S[:Q] ≈ SchurNew[:Q] - @test S[:S] ≈ SchurNew[:S] - @test S[:T] ≈ SchurNew[:T] - @test S[:Z] ≈ SchurNew[:Z] - @test S[:alpha] ≈ SchurNew[:alpha] - @test S[:beta] ≈ SchurNew[:beta] - sS,sT,sQ,sZ = schur(a1_sf,a2_sf) - @test NS[:Q] ≈ sQ - @test NS[:T] ≈ sT - @test NS[:S] ≈ sS - @test NS[:Z] ≈ sZ - end - end - @testset "0x0 matrix" for A in (zeros(eltya, 0, 0), view(rand(eltya, 2, 2), 1:0, 1:0)) - T, Z, λ = Base.LinAlg.schur(A) - @test T == A - @test Z == A - @test λ == zeros(0) - end -end diff --git a/julia-0.6.3/share/julia/test/linalg/special.jl b/julia-0.6.3/share/julia/test/linalg/special.jl deleted file mode 100644 index 2301ce9..0000000 --- a/julia-0.6.3/share/julia/test/linalg/special.jl +++ /dev/null @@ -1,252 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -using Base.Test -debug = false - -n= 10 #Size of matrix to test -srand(1) - -debug && println("Test interconversion between special matrix types") -let a=[1.0:n;] - A=Diagonal(a) - for newtype in [Diagonal, Bidiagonal, SymTridiagonal, Tridiagonal, Matrix] - debug && println("newtype is $(newtype)") - @test full(convert(newtype, A)) == full(A) - end - - for isupper in (true, false) - debug && println("isupper is $(isupper)") - A=Bidiagonal(a, [1.0:n-1;], isupper) - for newtype in [Bidiagonal, Tridiagonal, Matrix] - debug && println("newtype is $(newtype)") - @test full(convert(newtype, A)) == full(A) - @test full(newtype(A)) == full(A) - end - @test_throws ArgumentError convert(SymTridiagonal, A) - tritype = isupper ? UpperTriangular : LowerTriangular - @test full(tritype(A)) == full(A) - - A=Bidiagonal(a, zeros(n-1), isupper) #morally Diagonal - for newtype in [Diagonal, Bidiagonal, SymTridiagonal, Tridiagonal, Matrix] - debug && println("newtype is $(newtype)") - @test full(convert(newtype, A)) == full(A) - @test full(newtype(A)) == full(A) - end - @test full(tritype(A)) == full(A) - end - - A = SymTridiagonal(a, [1.0:n-1;]) - for newtype in [Tridiagonal, Matrix] - @test full(convert(newtype, A)) == full(A) - end - for newtype in [Diagonal, Bidiagonal] - @test_throws ArgumentError convert(newtype,A) - end - A = SymTridiagonal(a, zeros(n-1)) - @test full(convert(Bidiagonal,A)) == full(A) - - A = Tridiagonal(zeros(n-1), [1.0:n;], zeros(n-1)) #morally Diagonal - for newtype in [Diagonal, Bidiagonal, SymTridiagonal, Matrix] - @test full(convert(newtype, A)) == full(A) - end - A = Tridiagonal(ones(n-1), [1.0:n;], ones(n-1)) #not morally Diagonal - for newtype in [SymTridiagonal, Matrix] - @test full(convert(newtype, A)) == full(A) - end - for newtype in [Diagonal, Bidiagonal] - @test_throws ArgumentError convert(newtype,A) - end - A = Tridiagonal(zeros(n-1), [1.0:n;], ones(n-1)) #not morally Diagonal - @test full(convert(Bidiagonal, A)) == full(A) - A = UpperTriangular(Tridiagonal(zeros(n-1), [1.0:n;], ones(n-1))) - @test full(convert(Bidiagonal, A)) == full(A) - A = Tridiagonal(ones(n-1), [1.0:n;], zeros(n-1)) #not morally Diagonal - @test full(convert(Bidiagonal, A)) == full(A) - A = LowerTriangular(Tridiagonal(ones(n-1), [1.0:n;], zeros(n-1))) - @test full(convert(Bidiagonal, A)) == full(A) - @test_throws ArgumentError convert(SymTridiagonal,A) - - A = LowerTriangular(full(Diagonal(a))) #morally Diagonal - for newtype in [Diagonal, Bidiagonal, SymTridiagonal, LowerTriangular, Matrix] - @test full(convert(newtype, A)) == full(A) - end - A = UpperTriangular(full(Diagonal(a))) #morally Diagonal - for newtype in [Diagonal, Bidiagonal, SymTridiagonal, UpperTriangular, Matrix] - @test full(convert(newtype, A)) == full(A) - end - A = UpperTriangular(triu(rand(n,n))) - for newtype in [Diagonal, Bidiagonal, Tridiagonal, SymTridiagonal] - @test_throws ArgumentError convert(newtype,A) - end -end - -# Binary ops among special types -let a=[1.0:n;] - A=Diagonal(a) - Spectypes = [Diagonal, Bidiagonal, Tridiagonal, Matrix] - for (idx, type1) in enumerate(Spectypes) - for type2 in Spectypes - B = convert(type1,A) - C = convert(type2,A) - @test full(B + C) ≈ full(A + A) - @test full(B - C) ≈ full(A - A) - end - end - B = SymTridiagonal(a, ones(n-1)) - for Spectype in [Diagonal, Bidiagonal, Tridiagonal, Matrix] - @test full(B + convert(Spectype,A)) ≈ full(B + A) - @test full(convert(Spectype,A) + B) ≈ full(B + A) - @test full(B - convert(Spectype,A)) ≈ full(B - A) - @test full(convert(Spectype,A) - B) ≈ full(A - B) - end - - C = rand(n,n) - for TriType in [Base.LinAlg.UnitLowerTriangular, Base.LinAlg.UnitUpperTriangular, UpperTriangular, LowerTriangular] - D = TriType(C) - for Spectype in [Diagonal, Bidiagonal, Tridiagonal, Matrix] - @test full(D + convert(Spectype,A)) ≈ full(D + A) - @test full(convert(Spectype,A) + D) ≈ full(A + D) - @test full(D - convert(Spectype,A)) ≈ full(D - A) - @test full(convert(Spectype,A) - D) ≈ full(A - D) - end - end -end - -#Triangular Types and QR -for typ in [UpperTriangular,LowerTriangular,Base.LinAlg.UnitUpperTriangular,Base.LinAlg.UnitLowerTriangular] - a = rand(n,n) - atri = typ(a) - b = rand(n,n) - qrb = qrfact(b,Val{true}) - @test Base.LinAlg.A_mul_Bc(atri,qrb[:Q]) ≈ full(atri) * qrb[:Q]' - @test Base.LinAlg.A_mul_Bc!(copy(atri),qrb[:Q]) ≈ full(atri) * qrb[:Q]' - qrb = qrfact(b,Val{false}) - @test Base.LinAlg.A_mul_Bc(atri,qrb[:Q]) ≈ full(atri) * qrb[:Q]' - @test Base.LinAlg.A_mul_Bc!(copy(atri),qrb[:Q]) ≈ full(atri) * qrb[:Q]' -end - -# Test that concatenations of combinations of special and other matrix types yield sparse arrays -let N = 4 - # Test concatenating pairwise combinations of special matrices - diagmat = Diagonal(ones(N)) - bidiagmat = Bidiagonal(ones(N), ones(N-1), true) - tridiagmat = Tridiagonal(ones(N-1), ones(N), ones(N-1)) - symtridiagmat = SymTridiagonal(ones(N), ones(N-1)) - specialmats = (diagmat, bidiagmat, tridiagmat, symtridiagmat) - for specialmata in specialmats, specialmatb in specialmats - @test issparse(hcat(specialmata, specialmatb)) - @test issparse(vcat(specialmata, specialmatb)) - @test issparse(hvcat((1,1), specialmata, specialmatb)) - @test issparse(cat((1,2), specialmata, specialmatb)) - end - # Test concatenating pairwise combinations of special matrices with sparse matrices, - # dense matrices, or dense vectors - densevec = ones(N) - densemat = diagm(ones(N)) - spmat = spdiagm(ones(N)) - for specialmat in specialmats - # --> Tests applicable only to pairs of matrices - for othermat in (spmat, densemat) - @test issparse(vcat(specialmat, othermat)) - @test issparse(vcat(othermat, specialmat)) - end - # --> Tests applicable also to pairs including vectors - for specialmat in specialmats, othermatorvec in (spmat, densemat, densevec) - @test issparse(hcat(specialmat, othermatorvec)) - @test issparse(hcat(othermatorvec, specialmat)) - @test issparse(hvcat((2,), specialmat, othermatorvec)) - @test issparse(hvcat((2,), othermatorvec, specialmat)) - @test issparse(cat((1,2), specialmat, othermatorvec)) - @test issparse(cat((1,2), othermatorvec, specialmat)) - end - end -end - -# Test that concatenations of annotated sparse/special matrix types with other matrix -# types yield sparse arrays, and that the code which effects that does not make concatenations -# strictly involving un/annotated dense matrices yield sparse arrays -# -# TODO: As with the associated code, these tests should be moved to a more appropriate -# location, particularly some future equivalent of base/linalg/special.jl dedicated to -# intereactions between a broader set of matrix types -let - N = 4 - # The tested annotation types - testfull = Bool(parse(Int,(get(ENV, "JULIA_TESTFULL", "0")))) - utriannotations = (UpperTriangular, Base.LinAlg.UnitUpperTriangular) - ltriannotations = (LowerTriangular, Base.LinAlg.UnitLowerTriangular) - triannotations = (utriannotations..., ltriannotations...) - symannotations = (Symmetric, Hermitian) - annotations = testfull ? (triannotations..., symannotations...) : (LowerTriangular, Symmetric) - # Concatenations involving these types, un/annotated, should yield sparse arrays - spvec = spzeros(N) - spmat = speye(N) - diagmat = Diagonal(ones(N)) - bidiagmat = Bidiagonal(ones(N), ones(N-1), true) - tridiagmat = Tridiagonal(ones(N-1), ones(N), ones(N-1)) - symtridiagmat = SymTridiagonal(ones(N), ones(N-1)) - sparseconcatmats = testfull ? (spmat, diagmat, bidiagmat, tridiagmat, symtridiagmat) : (spmat, diagmat) - # Concatenations involving strictly these types, un/annotated, should yield dense arrays - densevec = ones(N) - densemat = ones(N, N) - # Annotated collections - annodmats = [annot(densemat) for annot in annotations] - annospcmats = [annot(spcmat) for annot in annotations, spcmat in sparseconcatmats] - # Test that concatenations of pairwise combinations of annotated sparse/special - # yield sparse matrices - for annospcmata in annospcmats, annospcmatb in annospcmats - @test issparse(vcat(annospcmata, annospcmatb)) - @test issparse(hcat(annospcmata, annospcmatb)) - @test issparse(hvcat((2,), annospcmata, annospcmatb)) - @test issparse(cat((1,2), annospcmata, annospcmatb)) - end - # Test that concatenations of pairwise combinations of annotated sparse/special - # matrices and other matrix/vector types yield sparse matrices - for annospcmat in annospcmats - # --> Tests applicable to pairs including only matrices - for othermat in (densemat, annodmats..., sparseconcatmats...) - @test issparse(vcat(annospcmat, othermat)) - @test issparse(vcat(othermat, annospcmat)) - end - # --> Tests applicable to pairs including other vectors or matrices - for other in (spvec, densevec, densemat, annodmats..., sparseconcatmats...) - @test issparse(hcat(annospcmat, other)) - @test issparse(hcat(other, annospcmat)) - @test issparse(hvcat((2,), annospcmat, other)) - @test issparse(hvcat((2,), other, annospcmat)) - @test issparse(cat((1,2), annospcmat, other)) - @test issparse(cat((1,2), other, annospcmat)) - end - end - # The preceding tests should cover multi-way combinations of those types, but for good - # measure test a few multi-way combinations involving those types - @test issparse(vcat(spmat, densemat, annospcmats[1], annodmats[2])) - @test issparse(vcat(densemat, spmat, annodmats[1], annospcmats[2])) - @test issparse(hcat(spvec, annodmats[1], annospcmats[3], densevec, diagmat)) - @test issparse(hcat(annodmats[2], annospcmats[4], spvec, densevec, diagmat)) - @test issparse(hvcat((5,), diagmat, densevec, spvec, annodmats[1], annospcmats[1])) - @test issparse(hvcat((5,), spvec, annodmats[2], diagmat, densevec, annospcmats[2])) - @test issparse(cat((1,2), annodmats[1], diagmat, annospcmats[3], densevec, spvec)) - @test issparse(cat((1,2), spvec, diagmat, densevec, annospcmats[4], annodmats[2])) - # Test that concatenations strictly involving un/annotated dense matrices/vectors - # yield dense arrays - for densemata in (densemat, annodmats...) - # --> Tests applicable to pairs including only matrices - for densematb in (densemat, annodmats...) - @test !issparse(vcat(densemata, densematb)) - @test !issparse(vcat(densematb, densemata)) - end - # --> Tests applicable to pairs including vectors or matrices - for otherdense in (densevec, densemat, annodmats...) - @test !issparse(hcat(densemata, otherdense)) - @test !issparse(hcat(otherdense, densemata)) - @test !issparse(hvcat((2,), densemata, otherdense)) - @test !issparse(hvcat((2,), otherdense, densemata)) - @test !issparse(cat((1,2), densemata, otherdense)) - @test !issparse(cat((1,2), otherdense, densemata)) - end - end -end -@testset "vcat of Vectors with SparseVectors should yield SparseVector (#22225)" begin - @test isa((@inferred vcat(Float64[], spzeros(1))), SparseVector) -end diff --git a/julia-0.6.3/share/julia/test/linalg/svd.jl b/julia-0.6.3/share/julia/test/linalg/svd.jl deleted file mode 100644 index f8d1611..0000000 --- a/julia-0.6.3/share/julia/test/linalg/svd.jl +++ /dev/null @@ -1,81 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -using Base.Test - -using Base.LinAlg: BlasComplex, BlasFloat, BlasReal, QRPivoted - -n = 10 - -# Split n into 2 parts for tests needing two matrices -n1 = div(n, 2) -n2 = 2*n1 - -srand(1234321) - -areal = randn(n,n)/2 -aimg = randn(n,n)/2 -a2real = randn(n,n)/2 -a2img = randn(n,n)/2 - -@testset for eltya in (Float32, Float64, Complex64, Complex128, Int) - aa = eltya == Int ? rand(1:7, n, n) : convert(Matrix{eltya}, eltya <: Complex ? complex.(areal, aimg) : areal) - aa2 = eltya == Int ? rand(1:7, n, n) : convert(Matrix{eltya}, eltya <: Complex ? complex.(a2real, a2img) : a2real) - asym = aa'+aa # symmetric indefinite - apd = aa'*aa # symmetric positive-definite - @testset for atype in ("Array", "SubArray") - if atype == "Array" - a = aa - a2 = aa2 - else - a = view(aa, 1:n, 1:n) - a2 = view(aa2, 1:n, 1:n) - end - ε = εa = eps(abs(float(one(eltya)))) - - usv = svdfact(a) - @testset "singular value decomposition" begin - @test usv[:S] === svdvals(usv) - @test usv[:U] * (Diagonal(usv[:S]) * usv[:Vt]) ≈ a - @test AbstractArray(usv) ≈ a - @test usv[:Vt]' ≈ usv[:V] - @test_throws KeyError usv[:Z] - b = rand(eltya,n) - @test usv\b ≈ a\b - - if eltya <: BlasFloat - svdz = svdfact!(ones(eltya,0,0)) - @test svdz[:U] ≈ eye(eltya,0,0) - @test svdz[:S] ≈ real(zeros(eltya,0)) - @test svdz[:Vt] ≈ eye(eltya,0,0) - end - end - @testset "Generalized svd" begin - a_svd = a[1:n1, :] - gsvd = svdfact(a,a_svd) - @test gsvd[:U]*gsvd[:D1]*gsvd[:R]*gsvd[:Q]' ≈ a - @test gsvd[:V]*gsvd[:D2]*gsvd[:R]*gsvd[:Q]' ≈ a_svd - @test usv[:Vt]' ≈ usv[:V] - @test_throws KeyError usv[:Z] - @test_throws KeyError gsvd[:Z] - @test gsvd[:vals] ≈ svdvals(a,a_svd) - α = eltya == Int ? -1 : rand(eltya) - β = svdfact(α) - @test β[:S] == [abs(α)] - @test svdvals(α) == abs(α) - u,v,q,d1,d2,r0 = svd(a,a_svd) - @test u ≈ gsvd[:U] - @test v ≈ gsvd[:V] - @test d1 ≈ gsvd[:D1] - @test d2 ≈ gsvd[:D2] - @test q ≈ gsvd[:Q] - @test gsvd[:a].^2 + gsvd[:b].^2 ≈ ones(eltya,length(gsvd[:a])) - - #testing the other layout for D1 & D2 - b = rand(eltya,n,2*n) - c = rand(eltya,n,2*n) - gsvd = svdfact(b,c) - @test gsvd[:U]*gsvd[:D1]*gsvd[:R]*gsvd[:Q]' ≈ b - @test gsvd[:V]*gsvd[:D2]*gsvd[:R]*gsvd[:Q]' ≈ c - end - end -end diff --git a/julia-0.6.3/share/julia/test/linalg/symmetric.jl b/julia-0.6.3/share/julia/test/linalg/symmetric.jl deleted file mode 100644 index e5a6498..0000000 --- a/julia-0.6.3/share/julia/test/linalg/symmetric.jl +++ /dev/null @@ -1,303 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -using Base.Test - -srand(101) -debug = false #Turn on for more debugging info - -#Pauli σ-matrices -for σ in map(Hermitian, Any[ eye(2), [0 1; 1 0], [0 -im; im 0], [1 0; 0 -1] ]) - @test ishermitian(σ) -end - -# Hermitian matrix exponential/log -let A1 = randn(4,4) + im*randn(4,4) - A2 = A1 + A1' - @test expm(A2) ≈ expm(Hermitian(A2)) - @test logm(A2) ≈ logm(Hermitian(A2)) - A3 = A1 * A1' # posdef - @test expm(A3) ≈ expm(Hermitian(A3)) - @test logm(A3) ≈ logm(Hermitian(A3)) -end - -let A1 = randn(4,4) - A3 = A1 * A1' - A4 = A1 + A1.' - @test expm(A4) ≈ expm(Symmetric(A4)) - @test logm(A3) ≈ logm(Symmetric(A3)) - @test logm(A3) ≈ logm(Hermitian(A3)) -end - -let n=10 - areal = randn(n,n)/2 - aimg = randn(n,n)/2 - debug && println("symmetric eigendecomposition") - for eltya in (Float32, Float64, Complex64, Complex128, BigFloat, Int) - a = eltya == Int ? rand(1:7, n, n) : convert(Matrix{eltya}, eltya <: Complex ? complex.(areal, aimg) : areal) - asym = a'+a # symmetric indefinite - ε = εa = eps(abs(float(one(eltya)))) - - x = randn(n) - y = randn(n) - b = randn(n,n)/2 - x = eltya == Int ? rand(1:7, n) : convert(Vector{eltya}, eltya <: Complex ? complex.(x, zeros(n)) : x) - y = eltya == Int ? rand(1:7, n) : convert(Vector{eltya}, eltya <: Complex ? complex.(y, zeros(n)) : y) - b = eltya == Int ? rand(1:7, n, n) : convert(Matrix{eltya}, eltya <: Complex ? complex.(b, zeros(n,n)) : b) - - debug && println("\ntype of a: ", eltya, "\n") - - # constructor - @test Symmetric(Symmetric(asym, :U)) === Symmetric(asym, :U) - @test Hermitian(Hermitian(asym, :U)) === Hermitian(asym, :U) - @test Symmetric(Symmetric(asym, :U), :U) === Symmetric(asym, :U) - @test Hermitian(Hermitian(asym, :U), :U) === Hermitian(asym, :U) - @test_throws ArgumentError Symmetric(Symmetric(asym, :U), :L) - @test_throws ArgumentError Hermitian(Hermitian(asym, :U), :L) - - # similar - @test isa(similar(Symmetric(asym)), Symmetric{eltya}) - @test isa(similar(Hermitian(asym)), Hermitian{eltya}) - @test isa(similar(Symmetric(asym), Int), Symmetric{Int}) - @test isa(similar(Hermitian(asym), Int), Hermitian{Int}) - @test isa(similar(Symmetric(asym), (3,2)), Matrix{eltya}) - @test isa(similar(Hermitian(asym), (3,2)), Matrix{eltya}) - @test isa(similar(Symmetric(asym), Int, (3,2)), Matrix{Int}) - @test isa(similar(Hermitian(asym), Int, (3,2)), Matrix{Int}) - - # full - @test asym == full(Hermitian(asym)) - - # parent - @test asym == parent(Hermitian(asym)) - - # getindex - @test asym[1,1] == Hermitian(asym)[1,1] - @test asym[1,1] == Symmetric(asym)[1,1] - - #trace - @test trace(asym) == trace(Hermitian(asym)) - - # issymmetric, ishermitian - if eltya <: Real - @test issymmetric(Symmetric(asym)) - @test ishermitian(Symmetric(asym)) - end - if eltya <: Complex - @test ishermitian(Symmetric(b + b')) - end - - #transpose, ctranspose - if eltya <: Real - @test transpose(Symmetric(asym)) == asym - else - @test transpose(Hermitian(asym)) == transpose(asym) - end - @test ctranspose(Symmetric(asym)) == Symmetric(conj(asym)) - @test ctranspose(Hermitian(asym)) == asym - - #tril/triu - for di in -n:n - @test triu(Symmetric(a+a.'),di) == triu(a+a.',di) - @test tril(Symmetric(a+a.'),di) == tril(a+a.',di) - @test triu(Hermitian(asym),di) == triu(asym,di) - @test tril(Hermitian(asym),di) == tril(asym,di) - @test triu(Symmetric(a+a.',:L),di) == triu(a+a.',di) - @test tril(Symmetric(a+a.',:L),di) == tril(a+a.',di) - @test triu(Hermitian(asym,:L),di) == triu(asym,di) - @test tril(Hermitian(asym,:L),di) == tril(asym,di) - end - - eltya == BigFloat && continue # Revisit when implemented in julia - d, v = eig(asym) - @test asym*v[:,1] ≈ d[1]*v[:,1] - @test v*Diagonal(d)*v' ≈ asym - @test isequal(eigvals(asym[1]), eigvals(asym[1:1,1:1])) - @test abs.(eigfact(Hermitian(asym), 1:2)[:vectors]'v[:,1:2]) ≈ eye(eltya, 2) - eig(Hermitian(asym), 1:2) # same result, but checks that method works - @test abs.(eigfact(Hermitian(asym), d[1] - 1, (d[2] + d[3])/2)[:vectors]'v[:,1:2]) ≈ eye(eltya, 2) - eig(Hermitian(asym), d[1] - 1, (d[2] + d[3])/2) # same result, but checks that method works - @test eigvals(Hermitian(asym), 1:2) ≈ d[1:2] - @test eigvals(Hermitian(asym), d[1] - 1, (d[2] + d[3])/2) ≈ d[1:2] - @test full(eigfact(asym)) ≈ asym - @test eigvecs(Hermitian(asym)) ≈ eigvecs(asym) - - # relation to svdvals - @test sum(sort(abs.(eigvals(Hermitian(asym))))) == sum(sort(svdvals(Hermitian(asym)))) - - # cond - @test cond(Hermitian(asym)) ≈ cond(asym) - - # det - @test det(asym) ≈ det(Hermitian(asym, :U)) - @test det(asym) ≈ det(Hermitian(asym, :L)) - if eltya <: Real - @test det(asym) ≈ det(Symmetric(asym, :U)) - @test det(asym) ≈ det(Symmetric(asym, :L)) - end - @test det(a + a.') ≈ det(Symmetric(a + a.', :U)) - @test det(a + a.') ≈ det(Symmetric(a + a.', :L)) - - # isposdef[!] - @test isposdef(Symmetric(asym)) == isposdef(full(Symmetric(asym))) - @test isposdef(Hermitian(asym)) == isposdef(full(Hermitian(asym))) - if eltya != Int - @test isposdef!(Symmetric(copy(asym))) == isposdef(full(Symmetric(asym))) - @test isposdef!(Hermitian(copy(asym))) == isposdef(full(Hermitian(asym))) - end - - # rank - let A = a[:,1:5]*a[:,1:5]' - # Make sure A is Hermitian even in the present of rounding error - # xianyi/OpenBLAS#729 - A = (A' + A) / 2 - @test rank(A) == rank(Hermitian(A)) - end - - # mat * vec - if eltya <: Complex - @test Hermitian(asym)*x+y ≈ asym*x+y - end - if eltya <: Real && eltya != Int - @test Symmetric(asym)*x+y ≈ asym*x+y - end - - C = zeros(eltya,n,n) - # mat * mat - if eltya <: Complex - @test Hermitian(asym) * a ≈ asym * a - @test a * Hermitian(asym) ≈ a * asym - @test Hermitian(asym) * Hermitian(asym) ≈ asym*asym - @test_throws DimensionMismatch Hermitian(asym) * ones(eltya,n+1) - Base.LinAlg.A_mul_B!(C,a,Hermitian(asym)) - @test C ≈ a*asym - end - if eltya <: Real && eltya != Int - @test Symmetric(asym) * Symmetric(asym) ≈ asym*asym - @test Symmetric(asym) * a ≈ asym * a - @test a * Symmetric(asym) ≈ a * asym - @test_throws DimensionMismatch Symmetric(asym) * ones(eltya,n+1) - Base.LinAlg.A_mul_B!(C,a,Symmetric(asym)) - @test C ≈ a*asym - end - - # solver - @test Hermitian(asym)\x ≈ asym\x - if eltya <: Real - @test Symmetric(asym)\x ≈ asym\x - end - - #inversion - @test inv(Hermitian(asym)) ≈ inv(asym) - if eltya <: Real && eltya != Int - @test inv(Symmetric(asym)) ≈ inv(asym) - @test inv(Hermitian(a)) ≈ inv(full(Hermitian(a))) - @test inv(Symmetric(a)) ≈ inv(full(Symmetric(a))) - end - - # conversion - @test Symmetric(asym) == convert(Symmetric,Symmetric(asym)) - if eltya <: Real && eltya != Int - typs = [Float16,Float32,Float64] - for typ in typs - @test Symmetric(convert(Matrix{typ},asym)) == convert(Symmetric{typ,Matrix{typ}},Symmetric(asym)) - end - end - if eltya <: Complex && eltya != Int - typs = [Complex64,Complex128] - for typ in typs - @test Hermitian(convert(Matrix{typ},asym)) == convert(Hermitian{typ,Matrix{typ}},Hermitian(asym)) - end - end - - #unsafe_getindex - if eltya <: Real - @test Symmetric(asym)[1:2,1:2] == asym[1:2,1:2] - end - @test Hermitian(asym)[1:2,1:2] == asym[1:2,1:2] - end -end - -#Issue #7647: test xsyevr, xheevr, xstevr drivers -for Mi7647 in (Symmetric(diagm(1.0:3.0)), - Hermitian(diagm(1.0:3.0)), - Hermitian(diagm(complex(1.0:3.0))), - SymTridiagonal([1.0:3.0;], zeros(2))) - debug && println("Eigenvalues in interval for $(typeof(Mi7647))") - @test eigmin(Mi7647) == eigvals(Mi7647, 0.5, 1.5)[1] == 1.0 - @test eigmax(Mi7647) == eigvals(Mi7647, 2.5, 3.5)[1] == 3.0 - @test eigvals(Mi7647) == eigvals(Mi7647, 0.5, 3.5) == [1.0:3.0;] -end - -#Issue #7933 -let A7933 = [1 2; 3 4] - B7933 = copy(A7933) - C7933 = full(Symmetric(A7933)) - @test A7933 == B7933 -end - -# Issues #8057 and #8058 -for f in (eigfact, eigvals, eig) - for A in (Symmetric([0 1; 1 0]), Hermitian([0 im; -im 0])) - @test_throws ArgumentError f(A, 3, 2) - @test_throws ArgumentError f(A, 1:4) - end -end - -#Issue 10671 -let A = [1.0+im 2.0; 2.0 0.0] - @test !ishermitian(A) - @test_throws ArgumentError Hermitian(A) -end - -# Unary minus for Symmetric matrices -let A = Symmetric(randn(5,5)) - B = -A - @test A + B ≈ zeros(5,5) -end - -# 17780 -let a = randn(2,2) - a = a'a - b = complex.(a,a) - c = Symmetric(b) - @test conj(c) == conj(Array(c)) - cc = copy(c) - @test conj!(c) == conj(Array(cc)) - c = Hermitian(b + b') - @test conj(c) == conj(Array(c)) - cc = copy(c) - @test conj!(c) == conj(Array(c)) -end - -# 19225 -let X = [1 -1; -1 1] - for T in (Symmetric, Hermitian) - Y = T(copy(X)) - _Y = similar(Y) - copy!(_Y, Y) - @test _Y == Y - - W = T(copy(X), :L) - copy!(W, Y) - @test W.data == Y.data - @test W.uplo != Y.uplo - - W[1,1] = 4 - @test W == T([4 -1; -1 1]) - @test_throws ArgumentError (W[1,2] = 2) - - @test Y + I == T([2 -1; -1 2]) - @test Y - I == T([0 -1; -1 0]) - @test Y * I == Y - - @test Y + 1 == T([2 0; 0 2]) - @test Y - 1 == T([0 -2; -2 0]) - @test Y * 2 == T([2 -2; -2 2]) - @test Y / 1 == Y - - @test T([true false; false true]) + true == T([2 1; 1 2]) - end - - @test_throws ArgumentError Hermitian(X) + 2im*I - @test_throws ArgumentError Hermitian(X) - 2im*I -end diff --git a/julia-0.6.3/share/julia/test/linalg/triangular.jl b/julia-0.6.3/share/julia/test/linalg/triangular.jl deleted file mode 100644 index f6dbe41..0000000 --- a/julia-0.6.3/share/julia/test/linalg/triangular.jl +++ /dev/null @@ -1,513 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -debug = false -using Base.Test -using Base.LinAlg: BlasFloat, errorbounds, full!, naivesub!, transpose!, UnitUpperTriangular, UnitLowerTriangular, A_rdiv_B!, A_rdiv_Bt!, A_rdiv_Bc! - -debug && println("Triangular matrices") - -n = 9 -srand(123) - -debug && println("Test basic type functionality") -@test_throws DimensionMismatch LowerTriangular(randn(5, 4)) -@test LowerTriangular(randn(3, 3)) |> t -> [size(t, i) for i = 1:3] == [size(full(t), i) for i = 1:3] - -# The following test block tries to call all methods in base/linalg/triangular.jl in order for a combination of input element types. Keep the ordering when adding code. -for elty1 in (Float32, Float64, BigFloat, Complex64, Complex128, Complex{BigFloat}, Int) - # Begin loop for first Triangular matrix - for (t1, uplo1) in ((UpperTriangular, :U), - (UnitUpperTriangular, :U), - (LowerTriangular, :L), - (UnitLowerTriangular, :L)) - - # Construct test matrix - A1 = t1(elty1 == Int ? rand(1:7, n, n) : convert(Matrix{elty1}, (elty1 <: Complex ? complex.(randn(n, n), randn(n, n)) : randn(n, n)) |> t -> chol(t't) |> t -> uplo1 == :U ? t : ctranspose(t))) - - - debug && println("elty1: $elty1, A1: $t1") - - # Convert - @test convert(AbstractMatrix{elty1}, A1) == A1 - @test convert(Matrix, A1) == full(A1) - - # full! - @test full!(copy(A1)) == full(A1) - - # fill! - @test full!(fill!(copy(A1), 1)) == full(t1(ones(size(A1)...))) - - # similar - @test isa(similar(A1), t1) - @test eltype(similar(A1)) == elty1 - @test isa(similar(A1, Int), t1) - @test eltype(similar(A1, Int)) == Int - @test isa(similar(A1, (3,2)), Matrix{elty1}) - @test isa(similar(A1, Int, (3,2)), Matrix{Int}) - - #copy! - simA1 = similar(A1) - copy!(simA1, A1) - @test simA1 == A1 - - # getindex - ## Linear indexing - for i = 1:length(A1) - @test A1[i] == full(A1)[i] - end - @test isa(A1[2:4,1], Vector) - - ## Cartesian indexing - for i = 1:size(A1, 1) - for j = 1:size(A1, 2) - @test A1[i,j] == full(A1)[i,j] - end - end - - # setindex! (and copy) - A1c = copy(A1) - for i = 1:size(A1, 1) - for j = 1:size(A1, 2) - if uplo1 == :U - if i > j - A1c[i,j] = 0 - @test_throws ArgumentError A1c[i,j] = 1 - elseif i == j && t1 == UnitUpperTriangular - A1c[i,j] = 1 - @test_throws ArgumentError A1c[i,j] = 0 - else - A1c[i,j] = 0 - @test A1c[i,j] == 0 - end - else - if i < j - A1c[i,j] = 0 - @test_throws ArgumentError A1c[i,j] = 1 - elseif i == j && t1 == UnitLowerTriangular - A1c[i,j] = 1 - @test_throws ArgumentError A1c[i,j] = 0 - else - A1c[i,j] = 0 - @test A1c[i,j] == 0 - end - end - end - end - - # istril/istriu - if uplo1 == :L - @test istril(A1) - @test !istriu(A1) - else - @test istriu(A1) - @test !istril(A1) - end - - #tril/triu - if uplo1 == :L - @test tril(A1,0) == A1 - @test tril(A1,-1) == LowerTriangular(tril(full(A1),-1)) - @test tril(A1,1) == t1(tril(tril(full(A1),1))) - @test_throws ArgumentError tril!(A1,n+1) - @test triu(A1,0) == t1(diagm(diag(A1))) - @test triu(A1,-1) == t1(tril(triu(A1.data,-1))) - @test triu(A1,1) == LowerTriangular(zeros(A1.data)) - @test_throws ArgumentError triu!(A1,n+1) - else - @test triu(A1,0) == A1 - @test triu(A1,1) == UpperTriangular(triu(full(A1),1)) - @test triu(A1,-1) == t1(triu(triu(full(A1),-1))) - @test_throws ArgumentError triu!(A1,n+1) - @test tril(A1,0) == t1(diagm(diag(A1))) - @test tril(A1,1) == t1(triu(tril(A1.data,1))) - @test tril(A1,-1) == UpperTriangular(zeros(A1.data)) - @test_throws ArgumentError tril!(A1,n+1) - end - - # factorize - @test factorize(A1) == A1 - - # [c]transpose[!] (test views as well, see issue #14317) - let vrange = 1:n-1, viewA1 = t1(view(A1.data, vrange, vrange)) - # transpose - @test full(A1.') == full(A1).' - @test full(viewA1.') == full(viewA1).' - # ctranspose - @test full(A1') == full(A1)' - @test full(viewA1') == full(viewA1)' - # transpose! - @test transpose!(copy(A1)) == A1.' - @test transpose!(t1(view(copy(A1).data, vrange, vrange))) == viewA1.' - # ctranspose! - @test ctranspose!(copy(A1)) == A1' - @test ctranspose!(t1(view(copy(A1).data, vrange, vrange))) == viewA1' - end - - # diag - @test diag(A1) == diag(full(A1)) - - # real - @test full(real(A1)) == real(full(A1)) - @test full(imag(A1)) == imag(full(A1)) - @test full(abs.(A1)) == abs.(full(A1)) - - # Unary operations - @test full(-A1) == -full(A1) - - # copy and copy! (test views as well, see issue #14317) - let vrange = 1:n-1, viewA1 = t1(view(A1.data, vrange, vrange)) - # copy - @test copy(A1) == copy(full(A1)) - @test copy(viewA1) == copy(full(viewA1)) - # copy! - B = similar(A1) - copy!(B, A1) - @test B == A1 - B = similar(A1.') - copy!(B, A1.') - @test B == A1.' - B = similar(viewA1) - copy!(B, viewA1) - @test B == viewA1 - B = similar(viewA1.') - copy!(B, viewA1.') - @test B == viewA1.' - end - - #expm/logm - if (elty1 == Float64 || elty1 == Complex128) && (t1 == UpperTriangular || t1 == LowerTriangular) - @test expm(full(logm(A1))) ≈ full(A1) - end - - # scale - if (t1 == UpperTriangular || t1 == LowerTriangular) - unitt = istriu(A1) ? UnitUpperTriangular : UnitLowerTriangular - if elty1 == Int - cr = 2 - else - cr = 0.5 - end - ci = cr * im - if elty1 <: Real - A1tmp = copy(A1) - scale!(A1tmp,cr) - @test A1tmp == cr*A1 - A1tmp = copy(A1) - scale!(cr,A1tmp) - @test A1tmp == cr*A1 - A1tmp = copy(A1) - A2tmp = unitt(A1) - scale!(A1tmp,A2tmp,cr) - @test A1tmp == cr * A2tmp - else - A1tmp = copy(A1) - scale!(A1tmp,ci) - @test A1tmp == ci*A1 - A1tmp = copy(A1) - scale!(ci,A1tmp) - @test A1tmp == ci*A1 - A1tmp = copy(A1) - A2tmp = unitt(A1) - scale!(A1tmp,A2tmp,ci) - @test A1tmp == ci * A2tmp - end - end - - # Binary operations - @test A1*0.5 == full(A1)*0.5 - @test 0.5*A1 == 0.5*full(A1) - @test A1/0.5 == full(A1)/0.5 - @test 0.5\A1 == 0.5\full(A1) - - # inversion - @test inv(A1) ≈ inv(lufact(full(A1))) - inv(full(A1)) # issue #11298 - @test isa(inv(A1), t1) - # make sure the call to LAPACK works right - if elty1 <: BlasFloat - @test Base.LinAlg.inv!(copy(A1)) ≈ inv(lufact(full(A1))) - end - - # Determinant - @test det(A1) ≈ det(lufact(full(A1))) atol=sqrt(eps(real(float(one(elty1)))))*n*n - @test logdet(A1) ≈ logdet(lufact(full(A1))) atol=sqrt(eps(real(float(one(elty1)))))*n*n - lada, ladb = logabsdet(A1) - flada, fladb = logabsdet(lufact(full(A1))) - @test lada ≈ flada atol=sqrt(eps(real(float(one(elty1)))))*n*n - @test ladb ≈ fladb atol=sqrt(eps(real(float(one(elty1)))))*n*n - - # Matrix square root - @test sqrtm(A1) |> t -> t*t ≈ A1 - - # naivesub errors - @test_throws DimensionMismatch naivesub!(A1,ones(elty1,n+1)) - - # eigenproblems - if !(elty1 in (BigFloat, Complex{BigFloat})) # Not handled yet - vals, vecs = eig(A1) - if (t1 == UpperTriangular || t1 == LowerTriangular) && elty1 != Int # Cannot really handle degenerate eigen space and Int matrices will probably have repeated eigenvalues. - @test vecs*diagm(vals)/vecs ≈ full(A1) atol=sqrt(eps(float(real(one(vals[1])))))*(norm(A1,Inf)*n)^2 - end - end - - # Condition number tests - can be VERY approximate - if elty1 <:BlasFloat - for p in (1.0, Inf) - @test cond(A1,p) ≈ cond(A1,p) atol=(cond(A1,p)+cond(A1,p)) - end - @test cond(A1,2) == cond(full(A1),2) - end - - if !(elty1 in (BigFloat, Complex{BigFloat})) # Not implemented yet - svd(A1) - svdfact(A1) - elty1 <: BlasFloat && svdfact!(copy(A1)) - svdvals(A1) - end - - # Begin loop for second Triangular matrix - for elty2 in (Float32, Float64, BigFloat, Complex64, Complex128, Complex{BigFloat}, Int) - for (t2, uplo2) in ((UpperTriangular, :U), - (UnitUpperTriangular, :U), - (LowerTriangular, :L), - (UnitLowerTriangular, :L)) - - debug && println("elty1: $elty1, A1: $t1, elty2: $elty2") - - A2 = t2(elty2 == Int ? rand(1:7, n, n) : convert(Matrix{elty2}, (elty2 <: Complex ? complex.(randn(n, n), randn(n, n)) : randn(n, n)) |> t -> chol(t't) |> t -> uplo2 == :U ? t : ctranspose(t))) - - # Convert - if elty1 <: Real && !(elty2 <: Integer) - @test convert(AbstractMatrix{elty2}, A1) == t1(convert(Matrix{elty2}, A1.data)) - elseif elty2 <: Real && !(elty1 <: Integer) - @test_throws InexactError convert(AbstractMatrix{elty2}, A1) == t1(convert(Matrix{elty2}, A1.data)) - end - - # Binary operations - @test full(A1 + A2) == full(A1) + full(A2) - @test full(A1 - A2) == full(A1) - full(A2) - - # Triangular-Triangualar multiplication and division - @test full(A1*A2) ≈ full(A1)*full(A2) - @test full(A1.'A2) ≈ full(A1).'full(A2) - @test full(A1'A2) ≈ full(A1)'full(A2) - @test full(A1*A2.') ≈ full(A1)*full(A2).' - @test full(A1*A2') ≈ full(A1)*full(A2)' - @test full(A1.'A2.') ≈ full(A1).'full(A2).' - @test full(A1'A2') ≈ full(A1)'full(A2)' - @test full(A1/A2) ≈ full(A1)/full(A2) - @test full(A1\A2) ≈ full(A1)\full(A2) - @test_throws DimensionMismatch eye(n+1)/A2 - @test_throws DimensionMismatch eye(n+1)/A2.' - @test_throws DimensionMismatch eye(n+1)/A2' - @test_throws DimensionMismatch eye(n+1)*A2 - @test_throws DimensionMismatch eye(n+1)*A2.' - @test_throws DimensionMismatch eye(n+1)*A2' - @test_throws DimensionMismatch A2.'*eye(n+1) - @test_throws DimensionMismatch A2'*eye(n+1) - @test_throws DimensionMismatch A2*eye(n+1) - @test_throws DimensionMismatch A2*ones(n+1) # redundant with immediately preceding test? - end - end - - for eltyB in (Float32, Float64, BigFloat, Complex64, Complex128, Complex{BigFloat}) - B = convert(Matrix{eltyB}, elty1 <: Complex ? real(A1)*ones(n, n) : A1*ones(n, n)) - - debug && println("elty1: $elty1, A1: $t1, B: $eltyB") - - if !(eltyB in (BigFloat, Complex{BigFloat})) # rand does not support BigFloat and Complex{BigFloat} as of Dec 2015 - Tri = Tridiagonal(rand(eltyB,n-1),rand(eltyB,n),rand(eltyB,n-1)) - @test Base.LinAlg.A_mul_B!(Tri,copy(A1)) ≈ Tri*full(A1) - end - - # Triangular-dense Matrix/vector multiplication - @test A1*B[:,1] ≈ full(A1)*B[:,1] - @test A1*B ≈ full(A1)*B - @test A1.'B[:,1] ≈ full(A1).'B[:,1] - @test A1'B[:,1] ≈ full(A1)'B[:,1] - @test A1.'B ≈ full(A1).'B - @test A1'B ≈ full(A1)'B - @test A1*B.' ≈ full(A1)*B.' - @test A1*B' ≈ full(A1)*B' - @test B*A1 ≈ B*full(A1) - @test B[:,1].'A1 ≈ B[:,1].'full(A1) - @test B[:,1]'A1 ≈ B[:,1]'full(A1) - @test B.'A1 ≈ B.'full(A1) - @test B'A1 ≈ B'full(A1) - @test B*A1.' ≈ B*full(A1).' - @test B*A1' ≈ B*full(A1)' - @test B[:,1].'A1.' ≈ B[:,1].'full(A1).' - @test B[:,1]'A1' ≈ B[:,1]'full(A1)' - @test B.'A1.' ≈ B.'full(A1).' - @test B'A1' ≈ B'full(A1)' - - if eltyB == elty1 - @test A_mul_B!(zeros(B),A1,B) ≈ A1*B - @test A_mul_Bc!(zeros(B),A1,B) ≈ A1*B' - @test A_mul_Bt!(zeros(B),A1,B) ≈ A1*B.' - end - #error handling - @test_throws DimensionMismatch Base.LinAlg.A_mul_B!(A1, ones(eltyB,n+1)) - @test_throws DimensionMismatch Base.LinAlg.A_mul_B!(ones(eltyB,n+1,n+1), A1) - @test_throws DimensionMismatch Base.LinAlg.At_mul_B!(A1, ones(eltyB,n+1)) - @test_throws DimensionMismatch Base.LinAlg.Ac_mul_B!(A1, ones(eltyB,n+1)) - @test_throws DimensionMismatch Base.LinAlg.A_mul_Bc!(ones(eltyB,n+1,n+1),A1) - @test_throws DimensionMismatch Base.LinAlg.A_mul_Bt!(ones(eltyB,n+1,n+1),A1) - - # ... and division - @test A1\B[:,1] ≈ full(A1)\B[:,1] - @test A1\B ≈ full(A1)\B - @test A1.'\B[:,1] ≈ full(A1).'\B[:,1] - @test A1'\B[:,1] ≈ full(A1)'\B[:,1] - @test A1.'\B ≈ full(A1).'\B - @test A1'\B ≈ full(A1)'\B - @test A1\B.' ≈ full(A1)\B.' - @test A1\B' ≈ full(A1)\B' - @test A1.'\B.' ≈ full(A1).'\B.' - @test A1'\B' ≈ full(A1)'\B' - @test_throws DimensionMismatch A1\ones(elty1,n+2) - @test_throws DimensionMismatch A1'\ones(elty1,n+2) - @test_throws DimensionMismatch A1.'\ones(elty1,n+2) - if t1 == UpperTriangular || t1 == LowerTriangular - @test_throws Base.LinAlg.SingularException naivesub!(t1(zeros(elty1,n,n)),ones(eltyB,n)) - end - @test B/A1 ≈ B/full(A1) - @test B/A1.' ≈ B/full(A1).' - @test B/A1' ≈ B/full(A1)' - @test B.'/A1 ≈ B.'/full(A1) - @test B'/A1 ≈ B'/full(A1) - @test B.'/A1.' ≈ B.'/full(A1).' - @test B'/A1' ≈ B'/full(A1)' - - # Error bounds - !(elty1 in (BigFloat, Complex{BigFloat})) && !(eltyB in (BigFloat, Complex{BigFloat})) && errorbounds(A1, A1\B, B) - - end - end -end - -# Matrix square root -Atn = UpperTriangular([-1 1 2; 0 -2 2; 0 0 -3]) -Atp = UpperTriangular([1 1 2; 0 2 2; 0 0 3]) -@test sqrtm(Atn) |> t->t*t ≈ Atn -@test typeof(sqrtm(Atn)[1,1]) <: Complex -@test sqrtm(Atp) |> t->t*t ≈ Atp -@test typeof(sqrtm(Atp)[1,1]) <: Real - -Areal = randn(n, n)/2 -Aimg = randn(n, n)/2 -A2real = randn(n, n)/2 -A2img = randn(n, n)/2 - -for eltya in (Float32, Float64, Complex64, Complex128, BigFloat, Int) - A = eltya == Int ? rand(1:7, n, n) : convert(Matrix{eltya}, eltya <: Complex ? complex.(Areal, Aimg) : Areal) - # a2 = eltya == Int ? rand(1:7, n, n) : convert(Matrix{eltya}, eltya <: Complex ? complex.(a2real, a2img) : a2real) - εa = eps(abs(float(one(eltya)))) - - for eltyb in (Float32, Float64, Complex64, Complex128) - εb = eps(abs(float(one(eltyb)))) - ε = max(εa,εb) - - debug && println("\ntype of A: ", eltya, " type of b: ", eltyb, "\n") - - debug && println("Solve upper triangular system") - Atri = UpperTriangular(lufact(A)[:U]) |> t -> eltya <: Complex && eltyb <: Real ? real(t) : t # Here the triangular matrix can't be too badly conditioned - b = convert(Matrix{eltyb}, eltya <: Complex ? full(Atri)*ones(n, 2) : full(Atri)*ones(n, 2)) - x = full(Atri) \ b - - debug && println("Test error estimates") - if eltya != BigFloat && eltyb != BigFloat - for i = 1:2 - @test norm(x[:,1] .- 1) <= errorbounds(UpperTriangular(A), x, b)[1][i] - end - end - debug && println("Test forward error [JIN 5705] if this is not a BigFloat") - - x = Atri \ b - γ = n*ε/(1 - n*ε) - if eltya != BigFloat - bigA = big.(Atri) - x̂ = ones(n, 2) - for i = 1:size(b, 2) - @test norm(x̂[:,i] - x[:,i], Inf)/norm(x̂[:,i], Inf) <= condskeel(bigA, x̂[:,i])*γ/(1 - condskeel(bigA)*γ) - end - end - - debug && println("Test backward error [JIN 5705]") - for i = 1:size(b, 2) - @test norm(abs.(b[:,i] - Atri*x[:,i]), Inf) <= γ * norm(Atri, Inf) * norm(x[:,i], Inf) - end - - debug && println("Solve lower triangular system") - Atri = UpperTriangular(lufact(A)[:U]) |> t -> eltya <: Complex && eltyb <: Real ? real(t) : t # Here the triangular matrix can't be too badly conditioned - b = convert(Matrix{eltyb}, eltya <: Complex ? full(Atri)*ones(n, 2) : full(Atri)*ones(n, 2)) - x = full(Atri)\b - - debug && println("Test error estimates") - if eltya != BigFloat && eltyb != BigFloat - for i = 1:2 - @test norm(x[:,1] .- 1) <= errorbounds(UpperTriangular(A), x, b)[1][i] - end - end - - debug && println("Test forward error [JIN 5705] if this is not a BigFloat") - b = eltyb == Int ? trunc.(Int,Atri*ones(n, 2)) : convert(Matrix{eltyb}, Atri*ones(eltya, n, 2)) - x = Atri \ b - γ = n*ε/(1 - n*ε) - if eltya != BigFloat - bigA = big.(Atri) - x̂ = ones(n, 2) - for i = 1:size(b, 2) - @test norm(x̂[:,i] - x[:,i], Inf)/norm(x̂[:,i], Inf) <= condskeel(bigA, x̂[:,i])*γ/(1 - condskeel(bigA)*γ) - end - end - - debug && println("Test backward error [JIN 5705]") - for i = 1:size(b, 2) - @test norm(abs.(b[:,i] - Atri*x[:,i]), Inf) <= γ * norm(Atri, Inf) * norm(x[:,i], Inf) - end - end -end - -# Issue 10742 and similar -@test istril(UpperTriangular(diagm([1,2,3,4]))) -@test istriu(LowerTriangular(diagm([1,2,3,4]))) -@test isdiag(UpperTriangular(diagm([1,2,3,4]))) -@test isdiag(LowerTriangular(diagm([1,2,3,4]))) -@test !isdiag(UpperTriangular(rand(4, 4))) -@test !isdiag(LowerTriangular(rand(4, 4))) - -# Test throwing in fallbacks for non BlasFloat/BlasComplex in A_rdiv_Bx! -let - n = 5 - A = rand(Float16, n, n) - B = rand(Float16, n-1, n-1) - @test_throws DimensionMismatch A_rdiv_B!(A, LowerTriangular(B)) - @test_throws DimensionMismatch A_rdiv_B!(A, UpperTriangular(B)) - @test_throws DimensionMismatch A_rdiv_B!(A, UnitLowerTriangular(B)) - @test_throws DimensionMismatch A_rdiv_B!(A, UnitUpperTriangular(B)) - - @test_throws DimensionMismatch A_rdiv_Bc!(A, LowerTriangular(B)) - @test_throws DimensionMismatch A_rdiv_Bc!(A, UpperTriangular(B)) - @test_throws DimensionMismatch A_rdiv_Bc!(A, UnitLowerTriangular(B)) - @test_throws DimensionMismatch A_rdiv_Bc!(A, UnitUpperTriangular(B)) - - @test_throws DimensionMismatch A_rdiv_Bt!(A, LowerTriangular(B)) - @test_throws DimensionMismatch A_rdiv_Bt!(A, UpperTriangular(B)) - @test_throws DimensionMismatch A_rdiv_Bt!(A, UnitLowerTriangular(B)) - @test_throws DimensionMismatch A_rdiv_Bt!(A, UnitUpperTriangular(B)) -end - -# Test that UpperTriangular(LowerTriangular) throws. See #16201 -@test_throws ArgumentError LowerTriangular(UpperTriangular(randn(3,3))) -@test_throws ArgumentError UpperTriangular(LowerTriangular(randn(3,3))) - -# Issue 16196 -@test UpperTriangular(eye(3)) \ view(ones(3), [1,2,3]) == ones(3) - -# dimensional correctness: -isdefined(Main, :TestHelpers) || @eval Main include("../TestHelpers.jl") -using TestHelpers.Furlong -let A = UpperTriangular([Furlong(1) Furlong(4); Furlong(0) Furlong(1)]) - @test sqrtm(A) == Furlong{1//2}.(UpperTriangular([1 2; 0 1])) -end diff --git a/julia-0.6.3/share/julia/test/linalg/tridiag.jl b/julia-0.6.3/share/julia/test/linalg/tridiag.jl deleted file mode 100644 index 5c5de79..0000000 --- a/julia-0.6.3/share/julia/test/linalg/tridiag.jl +++ /dev/null @@ -1,490 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -debug = false - -# basic tridiagonal operations -n = 5 - -srand(123) - -d = 1 .+ rand(n) -dl = -rand(n-1) -du = -rand(n-1) -v = randn(n) -B = randn(n,2) - -for elty in (Float32, Float64, Complex64, Complex128, Int) - if elty == Int - srand(61516384) - d = rand(1:100, n) - dl = -rand(0:10, n-1) - du = -rand(0:10, n-1) - v = rand(1:100, n) - B = rand(1:100, n, 2) - else - d = convert(Vector{elty}, d) - dl = convert(Vector{elty}, dl) - du = convert(Vector{elty}, du) - v = convert(Vector{elty}, v) - B = convert(Matrix{elty}, B) - end - ε = eps(abs2(float(one(elty)))) - T = Tridiagonal(dl, d, du) - Ts = SymTridiagonal(d, dl) - @test_throws ArgumentError size(Ts,0) - @test size(Ts,3) == 1 - @test size(T, 1) == n - @test size(T) == (n, n) - F = diagm(d) - for i = 1:n-1 - F[i,i+1] = du[i] - F[i+1,i] = dl[i] - end - @test Array(T) == F - - # elementary operations on tridiagonals - @test conj(T) == Tridiagonal(conj(dl), conj(d), conj(du)) - @test transpose(T) == Tridiagonal(du, d, dl) - @test ctranspose(T) == Tridiagonal(conj(du), conj(d), conj(dl)) - - @test abs.(T) == Tridiagonal(abs.(dl),abs.(d),abs.(du)) - if elty <: Real - @test round.(T) == Tridiagonal(round.(dl),round.(d),round.(du)) - @test isa(round.(T), Tridiagonal) - @test trunc.(T) == Tridiagonal(trunc.(dl),trunc.(d),trunc.(du)) - @test isa(trunc.(T), Tridiagonal) - @test floor.(T) == Tridiagonal(floor.(dl),floor.(d),floor.(du)) - @test isa(floor.(T), Tridiagonal) - @test ceil.(T) == Tridiagonal(ceil.(dl),ceil.(d),ceil.(du)) - @test isa(ceil.(T), Tridiagonal) - end - @test real(T) == Tridiagonal(real(dl),real(d),real(du)) - @test imag(T) == Tridiagonal(imag(dl),imag(d),imag(du)) - @test abs.(Ts) == SymTridiagonal(abs.(d),abs.(dl)) - if elty <: Real - @test round.(Ts) == SymTridiagonal(round.(d),round.(dl)) - @test isa(round.(Ts), SymTridiagonal) - @test trunc.(Ts) == SymTridiagonal(trunc.(d),trunc.(dl)) - @test isa(trunc.(Ts), SymTridiagonal) - @test floor.(Ts) == SymTridiagonal(floor.(d),floor.(dl)) - @test isa(floor.(Ts), SymTridiagonal) - @test ceil.(Ts) == SymTridiagonal(ceil.(d),ceil.(dl)) - @test isa(ceil.(Ts), SymTridiagonal) - end - @test real(Ts) == SymTridiagonal(real(d),real(dl)) - @test imag(Ts) == SymTridiagonal(imag(d),imag(dl)) - - # test interconversion of Tridiagonal and SymTridiagonal - @test Tridiagonal(dl, d, dl) == SymTridiagonal(d, dl) - @test SymTridiagonal(d, dl) == Tridiagonal(dl, d, dl) - @test Tridiagonal(dl, d, du) + Tridiagonal(du, d, dl) == SymTridiagonal(2d, dl+du) - @test SymTridiagonal(d, dl) + Tridiagonal(dl, d, du) == Tridiagonal(dl + dl, d+d, dl+du) - @test convert(SymTridiagonal,Tridiagonal(Ts)) == Ts - @test Array(convert(SymTridiagonal{Complex64},Tridiagonal(Ts))) == convert(Matrix{Complex64}, Ts) - if elty == Int - vv = rand(1:100, n) - BB = rand(1:100, n, 2) - else - vv = convert(Vector{elty}, v) - BB = convert(Matrix{elty}, B) - end - let Bs = BB, vs = vv - for atype in ("Array", "SubArray") - if atype == "Array" - BB = Bs - vv = vs - else - BB = view(Bs, 1:n, 1) - vv = view(vs, 1:n) - end - end - - # tridiagonal linear algebra - @test T*vv ≈ F*vv - invFv = F\vv - @test T\vv ≈ invFv - # @test Base.solve(T,v) ≈ invFv - # @test Base.solve(T, B) ≈ F\B - Tlu = factorize(T) - x = Tlu\vv - @test x ≈ invFv - end - @test det(T) ≈ det(F) - - @test T*Base.LinAlg.UnitUpperTriangular(eye(n)) ≈ F*eye(n) - @test T*Base.LinAlg.UnitLowerTriangular(eye(n)) ≈ F*eye(n) - @test T*UpperTriangular(eye(n)) ≈ F*eye(n) - @test T*LowerTriangular(eye(n)) ≈ F*eye(n) - - # symmetric tridiagonal - if elty <: Real - Ts = SymTridiagonal(d, dl) - Fs = Array(Ts) - Tldlt = factorize(Ts) - @test_throws DimensionMismatch Tldlt\rand(elty,n+1) - @test size(Tldlt) == size(Ts) - if elty <: AbstractFloat - @test typeof(convert(Base.LinAlg.LDLt{Float32},Tldlt)) == Base.LinAlg.LDLt{Float32,SymTridiagonal{elty}} - end - let vs = vv - for atype in ("Array", "SubArray") - if atype == "Array" - vv = vs - else - vv = view(vs, 1:n) - end - end - invFsv = Fs\vv - x = Ts\vv - @test x ≈ invFsv - @test Array(AbstractArray(Tldlt)) ≈ Fs - end - - # similar - @test isa(similar(Ts), SymTridiagonal{elty}) - @test isa(similar(Ts, Int), SymTridiagonal{Int}) - @test isa(similar(Ts, Int, (3,2)), Matrix{Int}) - end - - # eigenvalues/eigenvectors of symmetric tridiagonal - if elty === Float32 || elty === Float64 - DT, VT = @inferred eig(Ts) - @inferred eig(Ts, 2:4) - @inferred eig(Ts, 1.0, 2.0) - D, Vecs = eig(Fs) - @test DT ≈ D - @test abs.(VT'Vecs) ≈ eye(elty, n) - @test eigvecs(Ts) == eigvecs(Fs) - #call to LAPACK.stein here - Test.test_approx_eq_modphase(eigvecs(Ts,eigvals(Ts)),eigvecs(Fs)) - elseif elty != Int - # check that undef is determined accurately even if type inference - # bails out due to the number of try/catch blocks in this code. - @test_throws UndefVarError Fs - end - - # Test det(A::Matrix) - # In the long run, these tests should step through Strang's - # axiomatic definition of determinants. - # If all axioms are satisfied and all the composition rules work, - # all determinants will be correct except for floating point errors. - - # The determinant of the identity matrix should always be 1. - for i = 1:10 - A = eye(elty, i) - @test det(A) ≈ one(elty) - end - - # The determinant of a Householder reflection matrix should always be -1. - for i = 1:10 - A = eye(elty, 10) - A[i, i] = -one(elty) - @test det(A) ≈ -one(elty) - end - - # The determinant of a rotation matrix should always be 1. - if elty != Int - for theta = convert(Vector{elty}, pi ./ [1:4;]) - R = [cos(theta) -sin(theta); - sin(theta) cos(theta)] - @test convert(elty, det(R)) ≈ one(elty) - end - - # issue #1490 - @test det(ones(elty,3,3)) ≈ zero(elty) atol=3*eps(real(one(elty))) - - @test det(SymTridiagonal(elty[],elty[])) == one(elty) - - #tril/triu - @test_throws ArgumentError tril!(SymTridiagonal(d,dl),n+1) - @test_throws ArgumentError tril!(Tridiagonal(dl,d,du),n+1) - @test tril(SymTridiagonal(d,dl)) == Tridiagonal(dl,d,zeros(dl)) - @test tril(SymTridiagonal(d,dl),1) == Tridiagonal(dl,d,dl) - @test tril(SymTridiagonal(d,dl),-1) == Tridiagonal(dl,zeros(d),zeros(dl)) - @test tril(SymTridiagonal(d,dl),-2) == Tridiagonal(zeros(dl),zeros(d),zeros(dl)) - @test tril(Tridiagonal(dl,d,du)) == Tridiagonal(dl,d,zeros(du)) - @test tril(Tridiagonal(dl,d,du),1) == Tridiagonal(dl,d,du) - @test tril(Tridiagonal(dl,d,du),-1) == Tridiagonal(dl,zeros(d),zeros(du)) - @test tril(Tridiagonal(dl,d,du),-2) == Tridiagonal(zeros(dl),zeros(d),zeros(du)) - - @test_throws ArgumentError triu!(SymTridiagonal(d,dl),n+1) - @test_throws ArgumentError triu!(Tridiagonal(dl,d,du),n+1) - @test triu(SymTridiagonal(d,dl)) == Tridiagonal(zeros(dl),d,dl) - @test triu(SymTridiagonal(d,dl),-1) == Tridiagonal(dl,d,dl) - @test triu(SymTridiagonal(d,dl),1) == Tridiagonal(zeros(dl),zeros(d),dl) - @test triu(SymTridiagonal(d,dl),2) == Tridiagonal(zeros(dl),zeros(d),zeros(dl)) - @test triu(Tridiagonal(dl,d,du)) == Tridiagonal(zeros(dl),d,du) - @test triu(Tridiagonal(dl,d,du),-1) == Tridiagonal(dl,d,du) - @test triu(Tridiagonal(dl,d,du),1) == Tridiagonal(zeros(dl),zeros(d),du) - @test triu(Tridiagonal(dl,d,du),2) == Tridiagonal(zeros(dl),zeros(d),zeros(du)) - - @test !istril(SymTridiagonal(d,dl)) - @test !istriu(SymTridiagonal(d,dl)) - @test istriu(Tridiagonal(zeros(dl),d,du)) - @test istril(Tridiagonal(dl,d,zeros(du))) - end -end - -#Test equivalence of eigenvectors/singular vectors taking into account possible phase (sign) differences -function test_approx_eq_vecs{S<:Real,T<:Real}(a::StridedVecOrMat{S}, b::StridedVecOrMat{T}, error=nothing) - n = size(a, 1) - @test n==size(b,1) && size(a,2)==size(b,2) - error===nothing && (error=n^3*(eps(S)+eps(T))) - for i=1:n - ev1, ev2 = a[:,i], b[:,i] - deviation = min(abs(norm(ev1-ev2)),abs(norm(ev1+ev2))) - if !isnan(deviation) - @test deviation ≈ 0.0 atol=error - end - end -end - -let n = 12 #Size of matrix problem to test - srand(123) - debug && println("SymTridiagonal (symmetric tridiagonal) matrices") - for relty in (Float32, Float64), elty in (relty, Complex{relty}) - debug && println("elty is $(elty), relty is $(relty)") - a = convert(Vector{elty}, randn(n)) - b = convert(Vector{elty}, randn(n-1)) - if elty <: Complex - a += im*convert(Vector{elty}, randn(n)) - b += im*convert(Vector{elty}, randn(n-1)) - end - - @test_throws DimensionMismatch SymTridiagonal(a, ones(n+1)) - @test_throws ArgumentError SymTridiagonal(rand(n,n)) - - A = SymTridiagonal(a, b) - fA = map(elty <: Complex ? Complex128 : Float64, Array(A)) - - debug && println("getindex") - @test_throws BoundsError A[n+1,1] - @test_throws BoundsError A[1,n+1] - @test A[1,n] == convert(elty,0.0) - @test A[1,1] == a[1] - - debug && println("setindex!") - @test_throws BoundsError A[n + 1, 1] = 0 # test bounds check - @test_throws BoundsError A[1, n + 1] = 0 # test bounds check - @test ((A[3, 3] = A[3, 3]) == A[3, 3]; A == fA) # test assignment on the main diagonal - @test_throws ArgumentError A[3, 2] = 1 # test assignment on the subdiagonal - @test_throws ArgumentError A[2, 3] = 1 # test assignment on the superdiagonal - @test_throws ArgumentError A[1, 3] = 1 # test assignment off the main/sub/super diagonal - - debug && println("Diagonal extraction") - @test diag(A,1) == b - @test diag(A,-1) == b - @test diag(A,0) == a - @test diag(A,n-1) == zeros(elty,1) - @test_throws ArgumentError diag(A,n+1) - - debug && println("Idempotent tests") - for func in (conj, transpose, ctranspose) - @test func(func(A)) == A - end - - debug && println("Simple unary functions") - for func in (det, inv) - @test func(A) ≈ func(fA) atol=n^2*sqrt(eps(relty)) - end - - debug && println("Rounding to Ints") - if elty <: Real - @test round.(Int,A) == round.(Int,fA) - @test isa(round.(Int,A), SymTridiagonal) - @test trunc.(Int,A) == trunc.(Int,fA) - @test isa(trunc.(Int,A), SymTridiagonal) - @test ceil.(Int,A) == ceil.(Int,fA) - @test isa(ceil.(Int,A), SymTridiagonal) - @test floor.(Int,A) == floor.(Int,fA) - @test isa(floor.(Int,A), SymTridiagonal) - end - - debug && println("Tridiagonal/SymTridiagonal mixing ops") - B = convert(Tridiagonal{elty},A) - @test B == A - @test B + A == A + B - @test B - A == A - B - - debug && println("Multiplication with strided vector") - @test A*ones(n) ≈ Array(A)*ones(n) - - debug && println("Multiplication with strided matrix") - @test A*ones(n, 2) ≈ Array(A)*ones(n, 2) - - debug && println("Eigensystems") - if elty <: Real - zero, infinity = convert(elty, 0), convert(elty, Inf) - debug && println("This tests eigenvalue and eigenvector computations using stebz! and stein!") - w, iblock, isplit = LAPACK.stebz!('V', 'B', -infinity, infinity, 0, 0, zero, a, b) - evecs = LAPACK.stein!(a, b, w) - - (e, v) = eig(SymTridiagonal(a, b)) - @test e ≈ w - test_approx_eq_vecs(v, evecs) - - debug && println("stein! call using iblock and isplit") - w, iblock, isplit = LAPACK.stebz!('V', 'B', -infinity, infinity, 0, 0, zero, a, b) - evecs = LAPACK.stein!(a, b, w, iblock, isplit) - test_approx_eq_vecs(v, evecs) - - debug && println("stegr! call with index range") - F = eigfact(SymTridiagonal(a, b),1:2) - fF = eigfact(Symmetric(Array(SymTridiagonal(a, b))),1:2) - Test.test_approx_eq_modphase(F[:vectors], fF[:vectors]) - @test F[:values] ≈ fF[:values] - - debug && println("stegr! call with value range") - F = eigfact(SymTridiagonal(a, b),0.0,1.0) - fF = eigfact(Symmetric(Array(SymTridiagonal(a, b))),0.0,1.0) - Test.test_approx_eq_modphase(F[:vectors], fF[:vectors]) - @test F[:values] ≈ fF[:values] - end - - debug && println("Binary operations") - a = convert(Vector{elty}, randn(n)) - b = convert(Vector{elty}, randn(n - 1)) - if elty <: Complex - a += im*convert(Vector{elty}, randn(n)) - b += im*convert(Vector{elty}, randn(n - 1)) - end - - B = SymTridiagonal(a, b) - fB = map(elty <: Complex ? Complex128 : Float64, Array(B)) - - for op in (+, -, *) - @test Array(op(A, B)) ≈ op(fA, fB) - end - α = rand(elty) - @test Array(α*A) ≈ α*Array(A) - @test Array(A*α) ≈ Array(A)*α - @test Array(A/α) ≈ Array(A)/α - - debug && println("A_mul_B!") - @test_throws DimensionMismatch A_mul_B!(zeros(elty,n,n),B,ones(elty,n+1,n)) - @test_throws DimensionMismatch A_mul_B!(zeros(elty,n+1,n),B,ones(elty,n,n)) - @test_throws DimensionMismatch A_mul_B!(zeros(elty,n,n+1),B,ones(elty,n,n)) - - end - - debug && println("Tridiagonal matrices") - for relty in (Float32, Float64), elty in (relty, Complex{relty}) - debug && println("relty is $(relty), elty is $(elty)") - a = convert(Vector{elty}, randn(n - 1)) - b = convert(Vector{elty}, randn(n)) - c = convert(Vector{elty}, randn(n - 1)) - if elty <: Complex - a += im*convert(Vector{elty}, randn(n - 1)) - b += im*convert(Vector{elty}, randn(n)) - c += im*convert(Vector{elty}, randn(n - 1)) - end - - @test_throws ArgumentError Tridiagonal(a,a,a) - A = Tridiagonal(a, b, c) - fA = map(elty <: Complex ? Complex128 : Float64, Array(A)) - - debug && println("Similar, size, and copy!") - B = similar(A) - @test size(B) == size(A) - copy!(B,A) - @test B == A - @test isa(similar(A), Tridiagonal{elty}) - @test isa(similar(A, Int), Tridiagonal{Int}) - @test isa(similar(A, Int, (3,2)), Matrix{Int}) - @test size(A,3) == 1 - @test_throws ArgumentError size(A,0) - - debug && println("Diagonal extraction") - @test diag(A,-1) == a - @test diag(A,0) == b - @test diag(A,1) == c - @test diag(A,n-1) == zeros(elty,1) - @test_throws ArgumentError diag(A,n+1) - - debug && println("Simple unary functions") - for func in (det, inv) - @test func(A) ≈ func(fA) atol=n^2*sqrt(eps(relty)) - end - - debug && println("Rounding to Ints") - if elty <: Real - @test round.(Int,A) == round.(Int,fA) - @test isa(round.(Int,A), Tridiagonal) - @test trunc.(Int,A) == trunc.(Int,fA) - @test isa(trunc.(Int,A), Tridiagonal) - @test ceil.(Int,A) == ceil.(Int,fA) - @test isa(ceil.(Int,A), Tridiagonal) - @test floor.(Int,A) == floor.(Int,fA) - @test isa(floor.(Int,A), Tridiagonal) - end - - debug && println("Binary operations") - a = convert(Vector{elty}, randn(n - 1)) - b = convert(Vector{elty}, randn(n)) - c = convert(Vector{elty}, randn(n - 1)) - if elty <: Complex - a += im*convert(Vector{elty}, randn(n - 1)) - b += im*convert(Vector{elty}, randn(n)) - c += im*convert(Vector{elty}, randn(n - 1)) - end - - debug && println("Multiplication with strided vector") - @test A*ones(n) ≈ Array(A)*ones(n) - - debug && println("Multiplication with strided matrix") - @test A*ones(n, 2) ≈ Array(A)*ones(n, 2) - - - B = Tridiagonal(a, b, c) - fB = map(elty <: Complex ? Complex128 : Float64, Array(B)) - - for op in (+, -, *) - @test Array(op(A, B)) ≈ op(fA, fB) - end - α = rand(elty) - @test Array(α*A) ≈ α*Array(A) - @test Array(A*α) ≈ Array(A)*α - @test Array(A/α) ≈ Array(A)/α - - @test_throws ArgumentError convert(SymTridiagonal{elty},A) - - debug && println("A_mul_B!") - @test_throws DimensionMismatch Base.LinAlg.A_mul_B!(zeros(fA),A,ones(elty,n,n+1)) - @test_throws DimensionMismatch Base.LinAlg.A_mul_B!(zeros(fA),A,ones(elty,n+1,n)) - - debug && println("getindex") - @test_throws BoundsError A[n+1,1] - @test_throws BoundsError A[1,n+1] - - debug && println("setindex!") - @test_throws BoundsError A[n + 1, 1] = 0 # test bounds check - @test_throws BoundsError A[1, n + 1] = 0 # test bounds check - @test (A[3, 3] = A[3, 3]; A == fA) # test assignment on the main diagonal - @test (A[3, 2] = A[3, 2]; A == fA) # test assignment on the subdiagonal - @test (A[2, 3] = A[2, 3]; A == fA) # test assignment on the superdiagonal - @test ((A[1, 3] = 0) == 0; A == fA) # test zero assignment off the main/sub/super diagonal - @test_throws ArgumentError A[1, 3] = 1 # test non-zero assignment off the main/sub/super diagonal - end -end - -# Issue 12068 -SymTridiagonal([1, 2], [0])^3 == [1 0; 0 8] - -#test convert for SymTridiagonal -@test convert(SymTridiagonal{Float64},SymTridiagonal(ones(Float32,5),ones(Float32,4))) == SymTridiagonal(ones(Float64,5),ones(Float64,4)) -@test convert(AbstractMatrix{Float64},SymTridiagonal(ones(Float32,5),ones(Float32,4))) == SymTridiagonal(ones(Float64,5),ones(Float64,4)) - -# Test constructors from matrix -@test SymTridiagonal([1 2 3; 2 5 6; 0 6 9]) == [1 2 0; 2 5 6; 0 6 9] -@test Tridiagonal([1 2 3; 4 5 6; 7 8 9]) == [1 2 0; 4 5 6; 0 8 9] - -# Test constructors with range and other abstract vectors -@test SymTridiagonal(1:3, 1:2) == [1 1 0; 1 2 2; 0 2 3] -@test Tridiagonal(4:5, 1:3, 1:2) == [1 1 0; 4 2 2; 0 5 3] - -@testset "Issue #26994 (and the empty case)" begin - T = SymTridiagonal([1.0],[3.0]) - x = ones(1) - @test T*x == ones(1) - @test SymTridiagonal(ones(0), ones(0)) * ones(0, 2) == ones(0, 2) -end diff --git a/julia-0.6.3/share/julia/test/linalg/uniformscaling.jl b/julia-0.6.3/share/julia/test/linalg/uniformscaling.jl deleted file mode 100644 index f61bdef..0000000 --- a/julia-0.6.3/share/julia/test/linalg/uniformscaling.jl +++ /dev/null @@ -1,169 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -using Base.Test - -srand(123) - -@testset "basic functions" begin - @test I[1,1] == 1 # getindex - @test I[1,2] == 0 # getindex - @test I === I' # transpose - @test ndims(I) == 2 - @test one(UniformScaling{Float32}) == UniformScaling(one(Float32)) - @test zero(UniformScaling{Float32}) == UniformScaling(zero(Float32)) - @test eltype(one(UniformScaling{Float32})) == Float32 - @test zero(UniformScaling(rand(Complex128))) == zero(UniformScaling{Complex128}) - @test one(UniformScaling(rand(Complex128))) == one(UniformScaling{Complex128}) - @test eltype(one(UniformScaling(rand(Complex128)))) == Complex128 - @test -one(UniformScaling(2)) == UniformScaling(-1) - @test sparse(3I,4,5) == spdiagm(fill(3,4),0,4,5) - @test sparse(3I,5,4) == spdiagm(fill(3,4),0,5,4) -end - -@testset "istriu, istril, issymmetric, ishermitian, isapprox" begin - @test istriu(I) - @test istril(I) - @test issymmetric(I) - @test issymmetric(UniformScaling(complex(1.0,1.0))) - @test ishermitian(I) - @test !ishermitian(UniformScaling(complex(1.0,1.0))) - @test UniformScaling(4.00000000000001) ≈ UniformScaling(4.0) - @test UniformScaling(4.32) ≈ UniformScaling(4.3) rtol=0.1 atol=0.01 -end - -@testset "* and / with number" begin - α = randn() - @test α .* UniformScaling(1.0) == UniformScaling(1.0) .* α - @test UniformScaling(α)./α == UniformScaling(1.0) -end - -@test copy(UniformScaling(one(Float64))) == UniformScaling(one(Float64)) -@test sprint(show,UniformScaling(one(Complex128))) == "UniformScaling{Complex{Float64}}\n(1.0 + 0.0im)*I" -@test sprint(show,UniformScaling(one(Float32))) == "UniformScaling{Float32}\n1.0*I" - -λ = complex(randn(),randn()) -J = UniformScaling(λ) -@testset "transpose, conj, inv" begin - @test ndims(J) == 2 - @test transpose(J) == J - @test J*eye(2) == conj(J'eye(2)) # ctranpose (and A(c)_mul_B) - @test I + I === UniformScaling(2) # + - @test inv(I) == I - @test inv(J) == UniformScaling(inv(λ)) - @test cond(I) == 1 - @test cond(J) == (λ ≠ zero(λ) ? one(real(λ)) : oftype(real(λ), Inf)) -end - -B = bitrand(2,2) -@test B + I == B + eye(B) -@test I + B == B + eye(B) - -@testset "binary ops with matrices" begin - let AA = randn(2, 2) - for SS in (sprandn(3,3, 0.5), speye(Int, 3)) - @testset for atype in ("Array", "SubArray") - if atype == "Array" - A = AA - S = SS - else - A = view(AA, 1:2, 1:2) - S = view(SS, 1:3, 1:3) - end - - @test @inferred(A + I) == A + eye(A) - @test @inferred(I + A) == A + eye(A) - @test @inferred(I - I) === UniformScaling(0) - @test @inferred(B - I) == B - eye(B) - @test @inferred(I - B) == eye(B) - B - @test @inferred(A - I) == A - eye(A) - @test @inferred(I - A) == eye(A) - A - @test @inferred(I*J) === UniformScaling(λ) - @test @inferred(B*J) == B*λ - @test @inferred(J*B) == B*λ - @test @inferred(I*A) !== A # Don't alias - @test @inferred(I*S) !== S # Don't alias - @test @inferred(A*I) !== A # Don't alias - @test @inferred(S*I) !== S # Don't alias - - @test @inferred(S*J) == S*λ - @test @inferred(J*S) == S*λ - @test @inferred(A*J) == A*λ - @test @inferred(J*A) == A*λ - @test @inferred(J*ones(3)) == ones(3)*λ - @test @inferred(λ*J) === UniformScaling(λ*J.λ) - @test @inferred(J*λ) === UniformScaling(λ*J.λ) - @test @inferred(J/I) === J - @test @inferred(I/A) == inv(A) - @test @inferred(A/I) == A - @test @inferred(I/λ) === UniformScaling(1/λ) - @test @inferred(I\J) === J - - if atype == "Array" - T = LowerTriangular(randn(3,3)) - else - T = LowerTriangular(view(randn(3,3), 1:3, 1:3)) - end - @test @inferred(T + J) == full(T) + J - @test @inferred(J + T) == J + full(T) - @test @inferred(T - J) == full(T) - J - @test @inferred(J - T) == J - full(T) - @test @inferred(T\I) == inv(T) - - if atype == "Array" - T = LinAlg.UnitLowerTriangular(randn(3,3)) - else - T = LinAlg.UnitLowerTriangular(view(randn(3,3), 1:3, 1:3)) - end - @test @inferred(T + J) == full(T) + J - @test @inferred(J + T) == J + full(T) - @test @inferred(T - J) == full(T) - J - @test @inferred(J - T) == J - full(T) - @test @inferred(T\I) == inv(T) - - if atype == "Array" - T = UpperTriangular(randn(3,3)) - else - T = UpperTriangular(view(randn(3,3), 1:3, 1:3)) - end - @test @inferred(T + J) == full(T) + J - @test @inferred(J + T) == J + full(T) - @test @inferred(T - J) == full(T) - J - @test @inferred(J - T) == J - full(T) - @test @inferred(T\I) == inv(T) - - if atype == "Array" - T = LinAlg.UnitUpperTriangular(randn(3,3)) - else - T = LinAlg.UnitUpperTriangular(view(randn(3,3), 1:3, 1:3)) - end - @test @inferred(T + J) == full(T) + J - @test @inferred(J + T) == J + full(T) - @test @inferred(T - J) == full(T) - J - @test @inferred(J - T) == J - full(T) - @test @inferred(T\I) == inv(T) - - @test @inferred(I\A) == A - @test @inferred(A\I) == inv(A) - @test @inferred(λ\I) === UniformScaling(1/λ) - end - end - end -end - -@testset "hcat and vcat" begin - @test_throws ArgumentError hcat(I) - @test_throws ArgumentError [I I] - @test_throws ArgumentError vcat(I) - @test_throws ArgumentError [I; I] - @test_throws ArgumentError [I I; I] - for T in (Matrix, SparseMatrixCSC) - A = T(rand(3,4)) - B = T(rand(3,3)) - @test (hcat(A,2I))::T == hcat(A,2eye(3,3)) - @test (vcat(A,2I))::T == vcat(A,2eye(4,4)) - @test (hcat(I,3I,A,2I))::T == hcat(eye(3,3),3eye(3,3),A,2eye(3,3)) - @test (vcat(I,3I,A,2I))::T == vcat(eye(4,4),3eye(4,4),A,2eye(4,4)) - @test (hvcat((2,1,2),B,2I,I,3I,4I))::T == - hvcat((2,1,2),B,2eye(3,3),eye(6,6),3eye(3,3),4eye(3,3)) - end -end diff --git a/julia-0.6.3/share/julia/test/lineedit.jl b/julia-0.6.3/share/julia/test/lineedit.jl deleted file mode 100644 index 4aeca1b..0000000 --- a/julia-0.6.3/share/julia/test/lineedit.jl +++ /dev/null @@ -1,403 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -using Base.LineEdit -isdefined(Main, :TestHelpers) || @eval Main include(joinpath(dirname(@__FILE__), "TestHelpers.jl")) -using TestHelpers - -function run_test(d,buf) - global a_foo, b_foo, a_bar, b_bar - a_foo = b_foo = a_bar = b_bar = 0 - while !eof(buf) - LineEdit.match_input(d, nothing, buf)(nothing,nothing) - end -end - - -a_foo = 0 - -const foo_keymap = Dict( - 'a' => (o...)->(global a_foo; a_foo += 1) -) - -b_foo = 0 - -const foo2_keymap = Dict( - 'b' => (o...)->(global b_foo; b_foo += 1) -) - -a_bar = 0 -b_bar = 0 - -const bar_keymap = Dict( - 'a' => (o...)->(global a_bar; a_bar += 1), - 'b' => (o...)->(global b_bar; b_bar += 1) -) - -test1_dict = LineEdit.keymap([foo_keymap]) - -run_test(test1_dict,IOBuffer("aa")) -@test a_foo == 2 - -test2_dict = LineEdit.keymap([foo2_keymap, foo_keymap]) - -run_test(test2_dict,IOBuffer("aaabb")) -@test a_foo == 3 -@test b_foo == 2 - -test3_dict = LineEdit.keymap([bar_keymap, foo_keymap]) - -run_test(test3_dict,IOBuffer("aab")) -@test a_bar == 2 -@test b_bar == 1 - -# Multiple spellings in the same keymap -const test_keymap_1 = Dict( - "^C" => (o...)->1, - "\\C-C" => (o...)->2 -) - -@test_throws ErrorException LineEdit.keymap([test_keymap_1]) - -a_foo = a_bar = 0 - -const test_keymap_2 = Dict( - "abc" => (o...)->(global a_foo = 1) -) - -const test_keymap_3 = Dict( - "a" => (o...)->(global a_foo = 2), - "bc" => (o...)->(global a_bar = 3) -) - -function keymap_fcn(keymaps) - d = LineEdit.keymap(keymaps) - f = buf->(LineEdit.match_input(d, nothing, buf)(nothing,nothing)) -end - -let f = keymap_fcn([test_keymap_3, test_keymap_2]) - buf = IOBuffer("abc") - f(buf); f(buf) - @test a_foo == 2 - @test a_bar == 3 - @test eof(buf) -end - -# Eager redirection when the redirected-to behavior is changed. - -a_foo = 0 - -const test_keymap_4 = Dict( - "a" => (o...)->(global a_foo = 1), - "b" => "a", - "c" => (o...)->(global a_foo = 2), -) - -const test_keymap_5 = Dict( - "a" => (o...)->(global a_foo = 3), - "d" => "c" -) - -let f = keymap_fcn([test_keymap_5, test_keymap_4]) - buf = IOBuffer("abd") - f(buf) - @test a_foo == 3 - f(buf) - @test a_foo == 1 - f(buf) - @test a_foo == 2 - @test eof(buf) -end - -# Eager redirection with cycles - -const test_cycle = Dict( - "a" => "b", - "b" => "a" -) - -@test_throws ErrorException keymap([test_cycle]) - -# Lazy redirection with Cycles - -const level1 = Dict( - "a" => LineEdit.KeyAlias("b") -) - -const level2a = Dict( - "b" => "a" -) - -const level2b = Dict( - "b" => LineEdit.KeyAlias("a") -) - -@test_throws ErrorException keymap([level2a,level1]) -@test_throws ErrorException keymap([level2b,level1]) - -# Lazy redirection functionality test - -a_foo = 0 - -const test_keymap_6 = Dict( - "a" => (o...)->(global a_foo = 1), - "b" => LineEdit.KeyAlias("a"), - "c" => (o...)->(global a_foo = 2), -) - -const test_keymap_7 = Dict( - "a" => (o...)->(global a_foo = 3), - "d" => "c" -) - -let f = keymap_fcn([test_keymap_7, test_keymap_6]) - buf = IOBuffer("abd") - f(buf) - @test a_foo == 3 - a_foo = 0 - f(buf) - @test a_foo == 3 - f(buf) - @test a_foo == 2 - @test eof(buf) -end - -# Test requiring postprocessing (see conflict fixing in LineEdit.jl ) - -global path1 = 0 -global path2 = 0 -global path3 = 0 - -const test_keymap_8 = Dict( - "**" => (o...)->(global path1 += 1), - "ab" => (o...)->(global path2 += 1), - "cd" => (o...)->(global path3 += 1), - "d" => (o...)->(error("This is not the key you're looking for")) -) - -let f = keymap_fcn([test_keymap_8]) - buf = IOBuffer("bbabaccd") - f(buf) - @test path1 == 1 - f(buf) - @test path2 == 1 - f(buf) - @test path1 == 2 - f(buf) - @test path3 == 1 - @test eof(buf) -end - -global path1 = 0 -global path2 = 0 - -const test_keymap_9 = Dict( - "***" => (o...)->(global path1 += 1), - "*a*" => (o...)->(global path2 += 1) -) - -let f = keymap_fcn([test_keymap_9]) - buf = IOBuffer("abaaaa") - f(buf) - @test path1 == 1 - f(buf) - @test path2 == 1 - @test eof(buf) -end - - -## edit_move{left,right} ## -buf = IOBuffer("a\na\na\n") -seek(buf, 0) -for i = 1:6 - LineEdit.edit_move_right(buf) - @test position(buf) == i -end -@test eof(buf) -for i = 5:0 - LineEdit.edit_move_left(buf) - @test position(buf) == i -end - -# skip unicode combining characters -buf = IOBuffer("ŷ") -seek(buf, 0) -LineEdit.edit_move_right(buf) -@test eof(buf) -LineEdit.edit_move_left(buf) -@test position(buf) == 0 - -## edit_move_{up,down} ## - -buf = IOBuffer("type X\n a::Int\nend") -for i = 0:6 - seek(buf,i) - @test !LineEdit.edit_move_up(buf) - @test position(buf) == i - seek(buf,i) - @test LineEdit.edit_move_down(buf) - @test position(buf) == i+7 -end -for i = 7:17 - seek(buf,i) - @test LineEdit.edit_move_up(buf) - @test position(buf) == min(i-7,6) - seek(buf,i) - @test LineEdit.edit_move_down(buf) - @test position(buf) == min(i+11,21) -end -for i = 18:21 - seek(buf,i) - @test LineEdit.edit_move_up(buf) - @test position(buf) == i-11 - seek(buf,i) - @test !LineEdit.edit_move_down(buf) - @test position(buf) == i -end - -buf = IOBuffer("type X\n\n") -seekend(buf) -@test LineEdit.edit_move_up(buf) -@test position(buf) == 7 -@test LineEdit.edit_move_up(buf) -@test position(buf) == 0 -@test !LineEdit.edit_move_up(buf) -@test position(buf) == 0 -seek(buf,0) -@test LineEdit.edit_move_down(buf) -@test position(buf) == 7 -@test LineEdit.edit_move_down(buf) -@test position(buf) == 8 -@test !LineEdit.edit_move_down(buf) -@test position(buf) == 8 - -## edit_delete_prev_word ## - -buf = IOBuffer("type X\n ") -seekend(buf) -@test LineEdit.edit_delete_prev_word(buf) -@test position(buf) == 5 -@test buf.size == 5 -@test String(buf.data[1:buf.size]) == "type " - -buf = IOBuffer("4 +aaa+ x") -seek(buf,8) -@test LineEdit.edit_delete_prev_word(buf) -@test position(buf) == 3 -@test buf.size == 4 -@test String(buf.data[1:buf.size]) == "4 +x" - -buf = IOBuffer("x = func(arg1,arg2 , arg3)") -seekend(buf) -LineEdit.char_move_word_left(buf) -@test position(buf) == 21 -@test LineEdit.edit_delete_prev_word(buf) -@test String(buf.data[1:buf.size]) == "x = func(arg1,arg3)" -@test LineEdit.edit_delete_prev_word(buf) -@test String(buf.data[1:buf.size]) == "x = func(arg3)" -@test LineEdit.edit_delete_prev_word(buf) -@test String(buf.data[1:buf.size]) == "x = arg3)" - -# Unicode combining characters -let buf = IOBuffer() - LineEdit.edit_insert(buf, "â") - LineEdit.edit_move_left(buf) - @test position(buf) == 0 - LineEdit.edit_move_right(buf) - @test nb_available(buf) == 0 - LineEdit.edit_backspace(buf) - @test String(buf.data[1:buf.size]) == "a" -end - -## edit_transpose ## -let buf = IOBuffer() - LineEdit.edit_insert(buf, "abcde") - seek(buf,0) - LineEdit.edit_transpose(buf) - @test String(buf.data[1:buf.size]) == "abcde" - LineEdit.char_move_right(buf) - LineEdit.edit_transpose(buf) - @test String(buf.data[1:buf.size]) == "bacde" - LineEdit.edit_transpose(buf) - @test String(buf.data[1:buf.size]) == "bcade" - seekend(buf) - LineEdit.edit_transpose(buf) - @test String(buf.data[1:buf.size]) == "bcaed" - LineEdit.edit_transpose(buf) - @test String(buf.data[1:buf.size]) == "bcade" - - seek(buf, 0) - LineEdit.edit_clear(buf) - LineEdit.edit_insert(buf, "αβγδε") - seek(buf,0) - LineEdit.edit_transpose(buf) - @test String(buf.data[1:buf.size]) == "αβγδε" - LineEdit.char_move_right(buf) - LineEdit.edit_transpose(buf) - @test String(buf.data[1:buf.size]) == "βαγδε" - LineEdit.edit_transpose(buf) - @test String(buf.data[1:buf.size]) == "βγαδε" - seekend(buf) - LineEdit.edit_transpose(buf) - @test String(buf.data[1:buf.size]) == "βγαεδ" - LineEdit.edit_transpose(buf) - @test String(buf.data[1:buf.size]) == "βγαδε" -end - -let - term = TestHelpers.FakeTerminal(IOBuffer(), IOBuffer(), IOBuffer()) - s = LineEdit.init_state(term, ModalInterface([Prompt("test> ")])) - buf = LineEdit.buffer(s) - - LineEdit.edit_insert(s,"first line\nsecond line\nthird line") - @test String(buf.data[1:buf.size]) == "first line\nsecond line\nthird line" - - ## edit_move_line_start/end ## - seek(buf, 0) - LineEdit.move_line_end(s) - @test position(buf) == sizeof("first line") - LineEdit.move_line_end(s) # Only move to input end on repeated keypresses - @test position(buf) == sizeof("first line") - s.key_repeats = 1 # Manually flag a repeated keypress - LineEdit.move_line_end(s) - s.key_repeats = 0 - @test eof(buf) - - seekend(buf) - LineEdit.move_line_start(s) - @test position(buf) == sizeof("first line\nsecond line\n") - LineEdit.move_line_start(s) - @test position(buf) == sizeof("first line\nsecond line\n") - s.key_repeats = 1 # Manually flag a repeated keypress - LineEdit.move_line_start(s) - s.key_repeats = 0 - @test position(buf) == 0 - - ## edit_kill_line, edit_yank ## - seek(buf, 0) - LineEdit.edit_kill_line(s) - s.key_repeats = 1 # Manually flag a repeated keypress - LineEdit.edit_kill_line(s) - s.key_repeats = 0 - @test String(buf.data[1:buf.size]) == "second line\nthird line" - LineEdit.move_line_end(s) - LineEdit.edit_move_right(s) - LineEdit.edit_yank(s) - @test String(buf.data[1:buf.size]) == "second line\nfirst line\nthird line" -end - -# Issue 7845 -# First construct a problematic string: -# julia> is 6 characters + 1 character for space, -# so the rest of the terminal is 73 characters -######################################################################### -let - buf = IOBuffer( - "begin\nprint(\"A very very very very very very very very very very very very ve\")\nend") - seek(buf,4) - outbuf = IOBuffer() - termbuf = Base.Terminals.TerminalBuffer(outbuf) - term = TestHelpers.FakeTerminal(IOBuffer(), IOBuffer(), IOBuffer()) - s = LineEdit.refresh_multi_line(termbuf, term, buf, - Base.LineEdit.InputAreaState(0,0), "julia> ", indent = 7) - @test s == Base.LineEdit.InputAreaState(3,1) -end diff --git a/julia-0.6.3/share/julia/test/llvmcall.jl b/julia-0.6.3/share/julia/test/llvmcall.jl deleted file mode 100644 index ec2253d..0000000 --- a/julia-0.6.3/share/julia/test/llvmcall.jl +++ /dev/null @@ -1,209 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -using Base.llvmcall - -#function add1234(x::Tuple{Int32,Int32,Int32,Int32}) -# llvmcall("""%3 = add <4 x i32> %1, %0 -# ret <4 x i32> %3""", -# Tuple{Int32,Int32,Int32,Int32}, -# Tuple{Tuple{Int32,Int32,Int32,Int32}, -# Tuple{Int32,Int32,Int32,Int32}}, -# (Int32(1),Int32(2),Int32(3),Int32(4)), -# x) -#end -# -#function add1234(x::NTuple{4,Int64}) -# llvmcall("""%3 = add <4 x i64> %1, %0 -# ret <4 x i64> %3""",NTuple{4,Int64}, -# Tuple{NTuple{4,Int64},NTuple{4,Int64}}, -# (Int64(1),Int64(2),Int64(3),Int64(4)), -# x) -#end -# -function add1234(x::Tuple{Int32,Int32,Int32,Int32}) - llvmcall("""%3 = extractvalue [4 x i32] %0, 0 - %4 = extractvalue [4 x i32] %0, 1 - %5 = extractvalue [4 x i32] %0, 2 - %6 = extractvalue [4 x i32] %0, 3 - %7 = extractvalue [4 x i32] %1, 0 - %8 = extractvalue [4 x i32] %1, 1 - %9 = extractvalue [4 x i32] %1, 2 - %10 = extractvalue [4 x i32] %1, 3 - %11 = add i32 %3, %7 - %12 = add i32 %4, %8 - %13 = add i32 %5, %9 - %14 = add i32 %6, %10 - %15 = insertvalue [4 x i32] undef, i32 %11, 0 - %16 = insertvalue [4 x i32] %15, i32 %12, 1 - %17 = insertvalue [4 x i32] %16, i32 %13, 2 - %18 = insertvalue [4 x i32] %17, i32 %14, 3 - ret [4 x i32] %18""",Tuple{Int32,Int32,Int32,Int32}, - Tuple{Tuple{Int32,Int32,Int32,Int32},Tuple{Int32,Int32,Int32,Int32}}, - (Int32(1),Int32(2),Int32(3),Int32(4)), - x) -end - -@test add1234(map(Int32,(2,3,4,5))) === map(Int32,(3,5,7,9)) -#@test add1234(map(Int64,(2,3,4,5))) === map(Int64,(3,5,7,9)) - -# Test whether llvmcall escapes the function name correctly -baremodule PlusTest - using Base.llvmcall - using Base.Test - using Base - - function +(x::Int32, y::Int32) - llvmcall("""%3 = add i32 %1, %0 - ret i32 %3""", - Int32, - Tuple{Int32, Int32}, - x, - y) - end - @test Int32(1) + Int32(2) == Int32(3) -end - -# issue #11800 -@test_throws ErrorException eval(Expr(:call,Core.Intrinsics.llvmcall, - """%3 = add i32 %1, %0 - ret i32 %3""", Int32, Tuple{Int32, Int32}, - Int32(1), Int32(2))) # llvmcall must be compiled to be called - -# Test whether declarations work properly -function undeclared_ceil(x::Float64) - llvmcall("""%2 = call double @llvm.ceil.f64(double %0) - ret double %2""", Float64, Tuple{Float64}, x) -end -@test_throws ErrorException undeclared_ceil(4.2) -@test_throws ErrorException undeclared_ceil(4.2) - -function declared_floor(x::Float64) - llvmcall( - ("""declare double @llvm.floor.f64(double)""", - """%2 = call double @llvm.floor.f64(double %0) - ret double %2"""), - Float64, Tuple{Float64}, x) -end -@test declared_floor(4.2) ≈ 4. -ir = sprint(code_llvm, declared_floor, Tuple{Float64}) -@test contains(ir, "call double @llvm.floor.f64") # should be inlined - -function doubly_declared_floor(x::Float64) - llvmcall( - ("""declare double @llvm.floor.f64(double)""", - """%2 = call double @llvm.floor.f64(double %0) - ret double %2"""), - Float64, Tuple{Float64}, x+1)-1 -end -@test doubly_declared_floor(4.2) ≈ 4. - -function doubly_declared2_trunc(x::Float64) - a = llvmcall( - ("""declare double @llvm.trunc.f64(double)""", - """%2 = call double @llvm.trunc.f64(double %0) - ret double %2"""), - Float64, Tuple{Float64}, x) - b = llvmcall( - ("""declare double @llvm.trunc.f64(double)""", - """%2 = call double @llvm.trunc.f64(double %0) - ret double %2"""), - Float64, Tuple{Float64}, x+1)-1 - a + b -end -@test doubly_declared2_trunc(4.2) ≈ 8. - -# Test for single line -function declared_ceil(x::Float64) - llvmcall( - ("declare double @llvm.ceil.f64(double)", - """%2 = call double @llvm.ceil.f64(double %0) - ret double %2"""), - Float64, Tuple{Float64}, x) -end -@test declared_ceil(4.2) ≈ 5.0 - -# Test for multiple lines -function ceilfloor(x::Float64) - llvmcall( - ("""declare double @llvm.ceil.f64(double) - declare double @llvm.floor.f64(double)""", - """%2 = call double @llvm.ceil.f64(double %0) - %3 = call double @llvm.floor.f64(double %2) - ret double %3"""), - Float64, Tuple{Float64}, x) -end -@test ceilfloor(7.4) ≈ 8.0 - -# Test for proper declaration extraction -function confuse_declname_parsing() - llvmcall( - ("""declare i64 addrspace(0)* @foobar()""", - """ret void"""), - Void, Tuple{}) -end -confuse_declname_parsing() - -# Test for proper mangling of external (C) functions -function call_jl_errno() - llvmcall( - (""" declare i32 @jl_errno()""", - """ - %r = call i32 @jl_errno() - ret i32 %r - """),Int32,Tuple{}) -end -call_jl_errno() - -module ObjLoadTest - using Base: Test, llvmcall, @ccallable - didcall = false - @ccallable Void function jl_the_callback() - global didcall - didcall = true - nothing - end - # Make sure everything up until here gets compiled - jl_the_callback(); didcall = false - function do_the_call() - llvmcall( - (""" declare void @jl_the_callback()""", - """ - call void @jl_the_callback() - ret void - """),Void,Tuple{}) - end - do_the_call() - @test didcall -end - -# Test for proper parenting -if VersionNumber(Base.libllvm_version) >= v"3.6" # llvm 3.6 changed the syntax for a gep, so just ignore this test on older versions - local foo - function foo() - # this IR snippet triggers an optimization relying - # on the llvmcall function having a parent module - Base.llvmcall( - """%1 = getelementptr i64, i64* null, i64 1 - ret void""", - Void, Tuple{}) - end - code_llvm(DevNull, foo, ()) -else - println("INFO: skipping gep parentage test on llvm < 3.6") -end - -module CcallableRetTypeTest - using Base: Test, llvmcall, @ccallable - @ccallable function jl_test_returns_float()::Float64 - return 42 - end - function do_the_call() - llvmcall( - (""" declare double @jl_test_returns_float()""", - """ - %1 = call double @jl_test_returns_float() - ret double %1 - """),Float64,Tuple{}) - end - @test do_the_call() === 42.0 -end diff --git a/julia-0.6.3/share/julia/test/llvmcall2.jl b/julia-0.6.3/share/julia/test/llvmcall2.jl deleted file mode 100644 index a0129f2..0000000 --- a/julia-0.6.3/share/julia/test/llvmcall2.jl +++ /dev/null @@ -1,36 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -function declared_floor(x::Float64) - return ccall("llvm.floor.f64", llvmcall, Float64, (Float64,), x) -end -@test declared_floor(4.2) == 4.0 -ir = sprint(code_llvm, declared_floor, Tuple{Float64}) -@test contains(ir, "call double @llvm.floor.f64") # should be inlined - -function doubly_declared_floor(x::Float64) - a = ccall("llvm.floor.f64", llvmcall, Float64, (Float64,), x) - b = ccall("llvm.floor.f64", llvmcall, Float64, (Float64,), x + 1) - 1 - return a + b -end -@test doubly_declared_floor(4.2) == 8.0 - -function doubly_declared2_trunc(x::Float64) - a = ccall("llvm.trunc.f64", llvmcall, Float64, (Float64,), x) - b = ccall("llvm.trunc.f64", llvmcall, Float64, (Float64,), x + 1) - 1 - return a + b -end -@test doubly_declared2_trunc(4.2) == 8.0 - -# Test for single line -function declared_ceil(x::Float64) - return ccall("llvm.ceil.f64", llvmcall, Float64, (Float64,), x) -end -@test declared_ceil(4.2) == 5.0 - -# Test for multiple lines -function ceilfloor(x::Float64) - a = ccall("llvm.ceil.f64", llvmcall, Float64, (Float64,), x) - b = ccall("llvm.floor.f64", llvmcall, Float64, (Float64,), a) - return b -end -@test ceilfloor(7.4) == 8.0 diff --git a/julia-0.6.3/share/julia/test/llvmpasses/Makefile b/julia-0.6.3/share/julia/test/llvmpasses/Makefile deleted file mode 100644 index 76c8301..0000000 --- a/julia-0.6.3/share/julia/test/llvmpasses/Makefile +++ /dev/null @@ -1,11 +0,0 @@ -SRCDIR := $(abspath $(dir $(lastword $(MAKEFILE_LIST)))) -JULIAHOME := $(abspath $(SRCDIR)/../..) -include $(JULIAHOME)/deps/Versions.make -include $(JULIAHOME)/Make.inc -include $(JULIAHOME)/deps/llvm-ver.make -BUILDDIR = $(JULIAHOME)/deps/scratch -include $(JULIAHOME)/deps/llvm-options.mk -LLVM_SRC_DIR:=$(JULIAHOME)/deps/srccache/llvm-$(LLVM_VER) -test: - PATH=$$PATH:$(LLVM_BUILDDIR_withtype)/bin $(LLVM_SRC_DIR)/utils/lit/lit.py -v . -.PHONY: test diff --git a/julia-0.6.3/share/julia/test/llvmpasses/lit.cfg b/julia-0.6.3/share/julia/test/llvmpasses/lit.cfg deleted file mode 100644 index c5b5ace..0000000 --- a/julia-0.6.3/share/julia/test/llvmpasses/lit.cfg +++ /dev/null @@ -1,15 +0,0 @@ -import os -import sys -import re -import platform - -import lit.util -import lit.formats - -config.name = 'Julia' -config.suffixes = ['.ll'] -config.test_source_root = os.path.dirname(__file__) -config.test_format = lit.formats.ShTest(False) - -path = os.path.pathsep.join((os.path.join(os.path.dirname(__file__),"../../usr/tools"), config.environment['PATH'])) -config.environment['PATH'] = path diff --git a/julia-0.6.3/share/julia/test/llvmpasses/simdloop.ll b/julia-0.6.3/share/julia/test/llvmpasses/simdloop.ll deleted file mode 100644 index 812e71f..0000000 --- a/julia-0.6.3/share/julia/test/llvmpasses/simdloop.ll +++ /dev/null @@ -1,22 +0,0 @@ -; RUN: opt -load libjulia.so -LowerSIMDLoop -S %s | FileCheck %s - -define void @simd_test(double *%a, double *%b) { -top: - br label %loop -loop: - %i = phi i64 [0, %top], [%nexti, %loop] - %aptr = getelementptr double, double *%a, i64 %i - %bptr = getelementptr double, double *%b, i64 %i -; CHECK: llvm.mem.parallel_loop_access - %aval = load double, double *%aptr - %bval = load double, double *%aptr - %cval = fadd double %aval, %bval - store double %cval, double *%bptr - %nexti = add i64 %i, 1, !simd_loop !1 - %done = icmp sgt i64 %nexti, 500 - br i1 %done, label %loopdone, label %loop -loopdone: - ret void -} - -!1 = !{} diff --git a/julia-0.6.3/share/julia/test/loading.jl b/julia-0.6.3/share/julia/test/loading.jl deleted file mode 100644 index 618700d..0000000 --- a/julia-0.6.3/share/julia/test/loading.jl +++ /dev/null @@ -1,68 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -using Base.Test - -@test @__LINE__ == 5 - -include("test_sourcepath.jl") -thefname = "the fname!//\\&\1*" -include_string_test_func = include_string("include_string_test() = @__FILE__", thefname) -@test include_string_test_func() == Base.source_path() -@test include_string("Base.source_path()", thefname) == Base.source_path() -@test basename(@__FILE__) == "loading.jl" -@test isabspath(@__FILE__) - -@test isdir(@__DIR__) -@test @__DIR__() == dirname(@__FILE__) - -# Issue #5789 and PR #13542: -mktempdir() do dir - cd(dir) do - let true_filename = "cAsEtEsT.jl", lowered_filename="casetest.jl" - touch(true_filename) - @test Base.isfile_casesensitive(true_filename) - @test !Base.isfile_casesensitive(lowered_filename) - - # check that case-sensitivity only applies to basename of a path: - if isfile(lowered_filename) # case-insensitive filesystem - mkdir("cAsEtEsT") - touch(joinpath("cAsEtEsT", true_filename)) - @test Base.isfile_casesensitive(joinpath("casetest", true_filename)) - @test !Base.isfile_casesensitive(joinpath("casetest", lowered_filename)) - end - end - - # Test Unicode normalization; pertinent for OS X - let nfc_name = "\U00F4.jl" - touch(nfc_name) - @test Base.isfile_casesensitive(nfc_name) - end - end -end - -SAVED_LOAD_PATH = copy(LOAD_PATH) -empty!(LOAD_PATH) -dir = abspath(@__DIR__) -push!(LOAD_PATH, dir) - -@test Base.find_in_path("test_sourcepath") == joinpath(dir, "test_sourcepath.jl") -@test Base.find_in_path(GenericString("test_sourcepath")) == joinpath(dir, "test_sourcepath.jl") -LOAD_PATH[end] = GenericString(LOAD_PATH[end]) -@test Base.find_in_path("test_sourcepath") == joinpath(dir, "test_sourcepath.jl") - -struct CustomLoader - path::String -end -push!(LOAD_PATH, CustomLoader("abc")) -let name = randstring(20) - @test_throws ArgumentError Base.find_in_path(name, nothing) - Base.load_hook(prefix::CustomLoader, name::String, found) = joinpath(prefix.path, name) - @test Base.find_in_path(name, nothing) == joinpath("abc", name) -end -@test Base.find_in_path("test_sourcepath", nothing) == joinpath("abc", "test_sourcepath") -Base.load_hook(prefix::CustomLoader, name::String, found::String) = found -@test Base.find_in_path("test_sourcepath", nothing) == joinpath(dir, "test_sourcepath.jl") - -empty!(LOAD_PATH) -append!(LOAD_PATH, SAVED_LOAD_PATH) -@test LOAD_PATH == SAVED_LOAD_PATH diff --git a/julia-0.6.3/share/julia/test/markdown.jl b/julia-0.6.3/share/julia/test/markdown.jl deleted file mode 100644 index 4eba701..0000000 --- a/julia-0.6.3/share/julia/test/markdown.jl +++ /dev/null @@ -1,1053 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -using Base.Markdown -import Base.Markdown: MD, Paragraph, Header, Italic, Bold, LineBreak, plain, term, html, rst, Table, Code, LaTeX, Footnote -import Base: show - -# Basics -# Equality is checked by making sure the HTML output is -# the same – the structure itself may be different. - -@test md"foo" == MD(Paragraph("foo")) -@test md"foo *bar* baz" == MD(Paragraph(["foo ", Italic("bar"), " baz"])) -@test md"""foo -bar""" == MD(Paragraph(["foo bar"])) -@test md"""foo\ -bar""" == MD(Paragraph(["foo", LineBreak(), "bar"])) - -@test md"#no title" == MD(Paragraph(["#no title"])) -@test md"# title" == MD(Header{1}("title")) -@test md""" - # - empty - """ == MD(Header{1}(""), Paragraph("empty")) -@test md"## section" == MD(Header{2}("section")) -@test md"# title *foo* `bar` **baz**" == - MD(Header{1}(["title ", Italic("foo")," ",Code("bar")," ",Bold("baz")])) -@test md""" -h1 -===""" == md"# h1" -@test md""" -h2 - ---""" == md"## h2" - -@test md"**foo *bar* baz**" == MD(Paragraph(Bold(["foo ", Italic("bar"), " baz"]))) -@test md"*foo **bar** baz*" == MD(Paragraph(Italic(["foo ", Bold("bar"), " baz"]))) - -@test md"""```julia -foo -``` -""" == MD(Code("julia", "foo")) - -@test md"foo ``bar`` baz" == MD(Paragraph(["foo ", LaTeX("bar"), " baz"])) - -@test md""" -```math -... -``` -""" == MD(LaTeX("...")) - -code_in_code = md""" -```` -``` -```` -""" -@test code_in_code == MD(Code("```")) -@test plain(code_in_code) == "````\n```\n````\n" - -let text = "Foo ```bar` ``baz`` ```\n", - md = Markdown.parse(text) - @test text == Markdown.plain(md) -end - -@test isempty(Markdown.parse("\r")) -@test Markdown.parse("hello\r") == MD(Paragraph(["hello"])) -@test Markdown.parse("hello\r*julia*") == MD(Paragraph(Any["hello ", Italic(Any["julia"])])) - -@test md"A footnote [^foo]." == MD(Paragraph(["A footnote ", Footnote("foo", nothing), "."])) - -@test md"[^foo]: footnote" == MD([Footnote("foo", Any[Paragraph(Any["footnote"])])]) - -let text = - """ - A paragraph with some footnotes,[^1] and another.[^note] - - [^1]: Footnote text for the first. - - [^note]: A longer footnote: - - Indented paragraphs are part of the footnote. - - some.code - - And *another* paragraph. - - This isn't part of the footnote. - """, - md = Markdown.parse(text) - @test length(md.content) == 4 - @test isa(md.content[1], Markdown.Paragraph) - @test isa(md.content[2], Markdown.Footnote) - @test isa(md.content[3], Markdown.Footnote) - @test isa(md.content[4], Markdown.Paragraph) - - @test md.content[2].id == "1" - @test md.content[3].id == "note" - - @test length(md.content[3].text) == 4 - - let expected = - """ - A paragraph with some footnotes,[^1] and another.[^note] - - [^1]: Footnote text for the first. - - [^note]: - A longer footnote: - - Indented paragraphs are part of the footnote. - - ``` - some.code - ``` - - And *another* paragraph. - - - This isn't part of the footnote. - """ - @test Markdown.plain(md) == expected - end - let expected = - """ - A paragraph with some footnotes,[1]_ and another.[note]_ - - .. [1] Footnote text for the first. - - .. [note] - A longer footnote: - - Indented paragraphs are part of the footnote. - - .. code-block:: julia - - some.code - - And *another* paragraph. - - - This isn't part of the footnote. - """ - @test Markdown.rst(md) == expected - end - let html = Markdown.html(md) - @test contains(html, ",<a href=\"#footnote-1\" class=\"footnote\">[1]</a>") - @test contains(html, ".<a href=\"#footnote-note\" class=\"footnote\">[note]</a>") - @test contains(html, "<div class=\"footnote\" id=\"footnote-1\"><p class=\"footnote-title\">1</p>") - @test contains(html, "<div class=\"footnote\" id=\"footnote-note\"><p class=\"footnote-title\">note</p>") - end - let latex = Markdown.latex(md) - @test contains(latex, ",\\footnotemark[1]") - @test contains(latex, ".\\footnotemark[note]") - @test contains(latex, "\n\\footnotetext[1]{Footnote text for") - @test contains(latex, "\n\\footnotetext[note]{A longer footnote:\n") - end -end - -let doc = md""" -* one -* two - -1. pirate -2. ninja -3. zombie""" - @test isa(doc.content[1], Markdown.List) - @test isa(doc.content[2], Markdown.List) - @test doc.content[1].items[1][1].content[1] == "one" - @test doc.content[1].items[2][1].content[1] == "two" - @test doc.content[2].items[1][1].content[1] == "pirate" - @test doc.content[2].items[2][1].content[1] == "ninja" - @test doc.content[2].items[3][1].content[1] == "zombie" -end - -let doc = Markdown.parse( - """ - A paragraph... - - one - - two - * three - * four - ... another paragraph. - """ - ) - @test length(doc.content) === 3 - @test isa(doc.content[1], Markdown.Paragraph) - @test isa(doc.content[2], Markdown.List) - @test isa(doc.content[3], Markdown.Paragraph) - - @test length(doc.content[2].items) === 2 - @test doc.content[2].items[1][1].content[1] == "one" - @test length(doc.content[2].items[2]) == 2 - @test doc.content[2].items[2][1].content[1] == "two" - - @test isa(doc.content[2].items[2][2], Markdown.List) - @test length(doc.content[2].items[2][2].items) === 2 - @test doc.content[2].items[2][2].items[1][1].content[1] == "three" - @test doc.content[2].items[2][2].items[2][1].content[1] == "four" -end - -@test md"Foo [bar]" == MD(Paragraph("Foo [bar]")) -@test md"Foo [bar](baz)" != MD(Paragraph("Foo [bar](baz)")) -@test md"Foo \[bar](baz)" == MD(Paragraph("Foo [bar](baz)")) - -# Basic plain (markdown) output -@test md"foo" |> plain == "foo\n" -@test md"foo *bar* baz" |> plain == "foo *bar* baz\n" -@test md"# title" |> plain == "# title\n" -@test md"## section" |> plain == "## section\n" -@test md"## section `foo`" |> plain == "## section `foo`\n" -@test md"""Hello - ---- -World""" |> plain == "Hello\n\n---\n\nWorld\n" -@test md"[*a*](b)" |> plain == "[*a*](b)\n" -@test md""" -> foo -> -> * bar -> -> ``` -> baz -> ```""" |> plain == """> foo\n>\n> * bar\n>\n> ```\n> baz\n> ```\n\n""" - -# Terminal (markdown) output - -# multiple whitespace is ignored -@test sprint(term, md"a b") == " a b\n" -@test sprint(term, md"[x](https://julialang.org)") == " x\n" -@test sprint(term, md"![x](https://julialang.org)") == " (Image: x)\n" - -# enumeration is normalized -let doc = Markdown.parse( - """ - 1. a - 3. b - """ - ) - @test contains(sprint(term, doc), "1. ") - @test contains(sprint(term, doc), "2. ") - @test !contains(sprint(term, doc), "3. ") -end - -# HTML output -@test md"foo *bar* baz" |> html == "<p>foo <em>bar</em> baz</p>\n" -@test md"something ***" |> html == "<p>something ***</p>\n" -@test md"# h1## " |> html == "<h1>h1##</h1>\n" -@test md"## h2 ### " |> html == "<h2>h2</h2>\n" -@test md"###### h6" |> html == "<h6>h6</h6>\n" -@test md"####### h7" |> html == "<p>####### h7</p>\n" -@test md" >" |> html == "<blockquote>\n</blockquote>\n" -@test md"1. Hello" |> html == "<ol>\n<li><p>Hello</p>\n</li>\n</ol>\n" -@test md"* World" |> html == "<ul>\n<li><p>World</p>\n</li>\n</ul>\n" -@test md"# title *blah*" |> html == "<h1>title <em>blah</em></h1>\n" -@test md"## title *blah*" |> html == "<h2>title <em>blah</em></h2>\n" -@test md"<https://julialang.org>" |> html == """<p><a href="https://julialang.org">https://julialang.org</a></p>\n""" -@test md"<mailto://a@example.com>" |> html == """<p><a href="mailto://a@example.com">mailto://a@example.com</a></p>\n""" -@test md"<https://julialang.org/not a link>" |> html == "<p><https://julialang.org/not a link></p>\n" -@test md"""<https://julialang.org/nota -link>""" |> html == "<p><https://julialang.org/nota link></p>\n" -@test md"""Hello - ---- -World""" |> html == "<p>Hello</p>\n<hr />\n<p>World</p>\n" -@test md"`escape</code>`" |> html == "<p><code>escape</code></code></p>\n" - -@test md""" - code1 - - code2 -""" |> html == "<pre><code>code1\n\ncode2</code></pre>\n" # single code block - -# @test md""" -# - Foo -# --- -# - Bar""" |> html == "<ul>\n<li>Foo</li>\n</ul>\n<hr />\n<ul>\n<li>Bar</li>\n</ul>\n" -@test md""" -h1 -=== -h2 ---- -not -== =""" |> html == "<h1>h1</h1>\n<h2>h2</h2>\n<p>not == =</p>\n" - -# Latex output -book = md""" -# Title - -Some discussion - -> A quote - -## Section *important* - -Some **bolded** - -- list1 -- list2 -""" -@test latex(book) == "\\section{Title}\nSome discussion\n\n\\begin{quote}\nA quote\n\n\\end{quote}\n\\subsection{Section \\emph{important}}\nSome \\textbf{bolded}\n\n\\begin{itemize}\n\\item list1\n\n\n\\item list2\n\n\\end{itemize}\n" -# mime output -let out = - """ - # Title - - Some discussion - - > A quote - - - ## Section *important* - - Some **bolded** - - * list1 - * list2 - """ - @test sprint(show, "text/plain", book) == out - @test sprint(show, "text/markdown", book) == out -end -let out = - """ - <div class="markdown"><h1>Title</h1> - <p>Some discussion</p> - <blockquote> - <p>A quote</p> - </blockquote> - <h2>Section <em>important</em></h2> - <p>Some <strong>bolded</strong></p> - <ul> - <li><p>list1</p> - </li> - <li><p>list2</p> - </li> - </ul> - </div>""" - @test sprint(show, "text/html", book) == out -end -let out = - """ - \\section{Title} - Some discussion - - \\begin{quote} - A quote - - \\end{quote} - \\subsection{Section \\emph{important}} - Some \\textbf{bolded} - - \\begin{itemize} - \\item list1 - - - \\item list2 - - \\end{itemize} - """ - @test sprint(show, "text/latex", book) == out -end -let out = - """ - Title - ***** - - - Some discussion - - A quote - - - Section *important* - =================== - - - Some **bolded** - - * list1 - * list2 - """ - @test sprint(show, "text/rst", book) == out -end - -# rst rendering -for (input, output) in ( - md"foo *bar* baz" => "foo *bar* baz\n", - md"something ***" => "something ***\n", - md"# h1## " => "h1##\n****\n\n", - md"## h2 ### " => "h2\n==\n\n", - md"###### h6" => "h6\n..\n\n", - md"####### h7" => "####### h7\n", - md" >" => " \n\n", - md"1. Hello" => "1. Hello\n", - md"* World" => "* World\n", - md"``x + y``" => ":math:`x + y`\n", - md"# title *blah*" => "title *blah*\n************\n\n", - md"## title *blah*" => "title *blah*\n============\n\n", - md"[`x`](:func:`x`)" => ":func:`x`\n", - md"[`x`](:obj:`x`)" => ":obj:`x`\n", - md"[`x`](:ref:`x`)" => ":ref:`x`\n", - md"[`x`](:exc:`x`)" => ":exc:`x`\n", - md"[`x`](:class:`x`)" => ":class:`x`\n", - md"[`x`](:const:`x`)" => ":const:`x`\n", - md"[`x`](:data:`x`)" => ":data:`x`\n", - md"[`x`](:???:`x`)" => "```x`` <:???:`x`>`_\n", - md"[x](y)" => "`x <y>`_\n", - ) - @test rst(input) == output -end - -# Interpolation / Custom types -mutable struct Reference - ref -end - -ref(x) = Reference(x) - -ref(mean) - -show(io::IO, m::MIME"text/plain", r::Reference) = - print(io, "$(r.ref) (see Julia docs)") - -mean_ref = md"Behaves like $(ref(mean))" -@test plain(mean_ref) == "Behaves like mean (see Julia docs)\n" -@test html(mean_ref) == "<p>Behaves like mean (see Julia docs)</p>\n" - -show(io::IO, m::MIME"text/html", r::Reference) = - Markdown.withtag(io, :a, :href=>"test") do - Markdown.htmlesc(io, Markdown.plaininline(r)) - end -@test html(mean_ref) == "<p>Behaves like <a href=\"test\">mean (see Julia docs)</a></p>\n" - -@test md""" -````julia -foo() -````""" == md""" -```julia -foo() -```""" - -# GH tables -@test md""" - a | b - ---|--- - 1 | 2""" == MD(Table(Any[["a","b"], - ["1","2"]], [:r, :r])) - -@test md""" - | a | b | c | - | :-- | --: | --- | - | d`gh`hg | hgh**jhj**ge | f |""" == MD(Table(Any[["a","b","c"], - Any[["d",Code("gh"),"hg"], - ["hgh",Bold("jhj"),"ge"], - "f"]], - [:l, :r, :r])) -@test md""" -no|table -no error -""" == MD([Paragraph(Any["no|table no error"])]) - -let t = """a | b - :-- | --: - 1 | 2 - """ - @test Markdown.parse(t) == MD(Table(Any[Any["a", "b"], Any["1", "2"]], [:l, :r])) -end - -let text = - """ - | a | b | - |:--- | ---:| - | 1 | 2 | - """, - table = Markdown.parse(text) - @test text == Markdown.plain(table) -end -let text = - """ - | Markdown | Table | Test | - |:-------- |:-----:| -----:| - | foo | `bar` | *baz* | - | `bar` | baz | *foo* | - """, - table = Markdown.parse(text) - @test text == Markdown.plain(table) -end -let text = - """ - | a | b | - |:-------- | ---:| - | `x \\| y` | 2 | - """, - table = Markdown.parse(text) - @test text == Markdown.plain(table) -end - -# LaTeX extension -let in_dollars = - """ - We have \$x^2 < x\$ whenever: - - \$|x| < 1\$ - - etc. - """, - in_backticks = - """ - We have ``x^2 < x`` whenever: - - ```math - |x| < 1 - ``` - - etc. - """, - out_plain = - """ - We have \$x^2 < x\$ whenever: - - \$\$ - |x| < 1 - \$\$ - - etc. - """, - out_rst = - """ - We have :math:`x^2 < x` whenever: - - .. math:: - - |x| < 1 - - etc. - """, - out_latex = - """ - We have \$x^2 < x\$ whenever: - - \$\$|x| < 1\$\$ - etc. - - """, - dollars = Markdown.parse(in_dollars), - backticks = Markdown.parse(in_backticks), - latex_doc = MD( - Any[Paragraph(Any["We have ", LaTeX("x^2 < x"), " whenever:"]), - LaTeX("|x| < 1"), - Paragraph(Any["etc."]) - ]) - - @test out_plain == Markdown.plain(dollars) - @test out_plain == Markdown.plain(backticks) - - @test out_rst == Markdown.rst(dollars) - @test out_rst == Markdown.rst(backticks) - - @test out_latex == Markdown.latex(dollars) - @test out_latex == Markdown.latex(backticks) - - @test latex_doc == dollars - @test latex_doc == backticks -end - -# Nested backticks for inline code and math. -let t_1 = "`code` ``math`` ```code``` ````math```` `````code`````", - t_2 = "`` `math` `` ``` `code` ``code`` ``` ```` `math` ``math`` ```math``` ````", - t_3 = "`` ` `` ``` `` ` `` ` ` ```", - t_4 = """`code - over several - lines` ``math - over several - lines`` ``math with - ` some extra ` ` backticks` - ``""", - t_5 = "``code at end of string`", - t_6 = "```math at end of string``" - @test Markdown.parse(t_1) == MD(Paragraph([ - Code("code"), - " ", - LaTeX("math"), - " ", - Code("code"), - " ", - LaTeX("math"), - " ", - Code("code"), - ])) - @test Markdown.parse(t_2) == MD(Paragraph([ - LaTeX("`math`"), - " ", - Code("`code` ``code``"), - " ", - LaTeX("`math` ``math`` ```math```"), - ])) - @test Markdown.parse(t_3) == MD(Paragraph([ - LaTeX("`"), - " ", - Code("`` ` `` ` `"), - ])) - @test Markdown.parse(t_4) == MD(Paragraph([ - Code("code over several lines"), - " ", - LaTeX("math over several lines"), - " ", - LaTeX("math with ` some extra ` ` backticks`") - ])) - @test Markdown.parse(t_5) == MD(Paragraph([ - "`", - Code("code at end of string"), - ])) - @test Markdown.parse(t_6) == MD(Paragraph([ - "`", - LaTeX("math at end of string"), - ])) -end - -# Admonitions. -let t_1 = - """ - # Foo - - !!! note - - !!! warning "custom title" - - ## Bar - - !!! danger "" - - !!! - """, - t_2 = - """ - !!! note - foo bar baz - - !!! warning "custom title" - - foo - - bar - - baz - - foo bar baz - - !!! danger "" - - ``` - foo - ``` - - bar - - # baz - """, - m_1 = Markdown.parse(t_1), - m_2 = Markdown.parse(t_2) - - # Content Tests. - - @test isa(m_1.content[2], Markdown.Admonition) - @test m_1.content[2].category == "note" - @test m_1.content[2].title == "Note" - @test m_1.content[2].content == [] - - @test isa(m_1.content[3], Markdown.Admonition) - @test m_1.content[3].category == "warning" - @test m_1.content[3].title == "custom title" - @test m_1.content[3].content == [] - - @test isa(m_1.content[5], Markdown.Admonition) - @test m_1.content[5].category == "danger" - @test m_1.content[5].title == "" - @test m_1.content[5].content == [] - - @test isa(m_1.content[6], Markdown.Paragraph) - - @test isa(m_2.content[1], Markdown.Admonition) - @test m_2.content[1].category == "note" - @test m_2.content[1].title == "Note" - @test isa(m_2.content[1].content[1], Markdown.Paragraph) - - @test isa(m_2.content[2], Markdown.Admonition) - @test m_2.content[2].category == "warning" - @test m_2.content[2].title == "custom title" - @test isa(m_2.content[2].content[1], Markdown.List) - @test isa(m_2.content[2].content[2], Markdown.Paragraph) - - @test isa(m_2.content[3], Markdown.Admonition) - @test m_2.content[3].category == "danger" - @test m_2.content[3].title == "" - @test isa(m_2.content[3].content[1], Markdown.Code) - @test isa(m_2.content[3].content[2], Markdown.Code) - @test isa(m_2.content[3].content[3], Markdown.Header{1}) - - # Rendering Tests. - let out = Markdown.plain(m_1), - expected = - """ - # Foo - - !!! note - \n\n - !!! warning "custom title" - \n\n - ## Bar - - !!! danger "" - \n\n - !!! - """ - @test out == expected - end - let out = Markdown.rst(m_1), - expected = - """ - Foo - *** - \n - .. note:: - \n\n - .. warning:: custom title - \n\n - Bar - === - \n - .. danger:: - \n\n - !!! - """ - @test out == expected - end - let out = Markdown.latex(m_1), - expected = - """ - \\section{Foo} - \\begin{quote} - \\textbf{note} - - Note - - \\end{quote} - \\begin{quote} - \\textbf{warning} - - custom title - - \\end{quote} - \\subsection{Bar} - \\begin{quote} - \\textbf{danger} - \n\n - \\end{quote} - !!! - - """ - @test out == expected - end - let out = Markdown.html(m_1), - expected = - """ - <h1>Foo</h1> - <div class="admonition note"><p class="admonition-title">Note</p></div> - <div class="admonition warning"><p class="admonition-title">custom title</p></div> - <h2>Bar</h2> - <div class="admonition danger"><p class="admonition-title"></p></div> - <p>!!!</p> - """ - @test out == expected - end - - let out = Markdown.plain(m_2), - expected = - """ - !!! note - foo bar baz - - - !!! warning "custom title" - * foo - * bar - * baz - - foo bar baz - - - !!! danger "" - ``` - foo - ``` - - ``` - bar - ``` - - # baz - - """ - @test out == expected - end - let out = Markdown.rst(m_2), - expected = - """ - .. note:: - foo bar baz - - - .. warning:: custom title - * foo - * bar - * baz - - foo bar baz - - - .. danger:: - .. code-block:: julia - - foo - - .. code-block:: julia - - bar - - baz - *** - - """ - @test out == expected - end -end - -# Nested Lists. -let text = - """ - 1. A paragraph - with two lines. - - indented code - - > A block quote. - - - one - - two - - - one - - two - - - - baz - - + ``` - foo - ``` - - 1. foo - 2. bar - 3. baz - """, - md = Markdown.parse(text) - - # Content and structure tests. - - @test length(md.content) == 6 - @test length(md.content[1].items) == 1 - @test length(md.content[1].items[1]) == 3 - @test isa(md.content[1].items[1][1], Markdown.Paragraph) - @test isa(md.content[1].items[1][2], Markdown.Code) - @test isa(md.content[1].items[1][3], Markdown.BlockQuote) - @test length(md.content[2].items) == 1 - @test isa(md.content[2].items[1][1], Markdown.Paragraph) - @test isa(md.content[3], Markdown.Paragraph) - @test length(md.content[4].items) == 1 - @test isa(md.content[4].items[1][1], Paragraph) - @test isa(md.content[4].items[1][2], Paragraph) - @test length(md.content[5].items) == 2 - @test isa(md.content[5].items[1][1], Markdown.Paragraph) - @test isa(md.content[5].items[2][1], Markdown.Code) - @test length(md.content[6].items) == 3 - @test md.content[6].items[1][1].content[1] == "foo" - @test md.content[6].items[2][1].content[1] == "bar" - @test md.content[6].items[3][1].content[1] == "baz" - - # Rendering tests. - let expected = - """ - 1. A paragraph with two lines. - - ``` - indented code - ``` - - > A block quote. - - * one - - two - - * one - - two - - * baz - * ``` - foo - ``` - - 1. foo - 2. bar - 3. baz - """ - @test expected == Markdown.plain(md) - end - - let expected = - """ - <ol> - <li><p>A paragraph with two lines.</p> - <pre><code>indented code</code></pre> - <blockquote> - <p>A block quote.</p> - </blockquote> - </li> - </ol> - <ul> - <li><p>one</p> - </li> - </ul> - <p>two</p> - <ul> - <li><p>one</p> - <p>two</p> - </li> - </ul> - <ul> - <li><p>baz</p> - </li> - <li><pre><code>foo</code></pre> - </li> - </ul> - <ol> - <li><p>foo</p> - </li> - <li><p>bar</p> - </li> - <li><p>baz</p> - </li> - </ol> - """ - @test expected == Markdown.html(md) - end - - let expected = - """ - 1. A paragraph with two lines. - - .. code-block:: julia - - indented code - - A block quote. - - * one - - two - - * one - - two - - * baz - * .. code-block:: julia - - foo - - 1. foo - 2. bar - 3. baz - """ - @test expected == Markdown.rst(md) - end -end - -# Ordered list starting number. -let text = - """ - 42. foo - 43. bar - - - 1. foo - 2. bar - - - - foo - - bar - """, - md = Markdown.parse(text) - - @test md.content[1].ordered == 42 - @test md.content[2].ordered == 1 - @test md.content[3].ordered == -1 - - let expected = - """ - <ol start="42"> - <li><p>foo</p> - </li> - <li><p>bar</p> - </li> - </ol> - <ol> - <li><p>foo</p> - </li> - <li><p>bar</p> - </li> - </ol> - <ul> - <li><p>foo</p> - </li> - <li><p>bar</p> - </li> - </ul> - """ - @test expected == Markdown.html(md) - end - - let expected = - """ - \\begin{itemize} - \\item[42. ] foo - - - \\item[43. ] bar - - \\end{itemize} - \\begin{itemize} - \\item[1. ] foo - - - \\item[2. ] bar - - \\end{itemize} - \\begin{itemize} - \\item foo - - - \\item bar - - \\end{itemize} - """ - @test expected == Markdown.latex(md) - end -end diff --git a/julia-0.6.3/share/julia/test/math.jl b/julia-0.6.3/share/julia/test/math.jl deleted file mode 100644 index 04ce580..0000000 --- a/julia-0.6.3/share/julia/test/math.jl +++ /dev/null @@ -1,616 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -@testset "clamp" begin - @test clamp(0, 1, 3) == 1 - @test clamp(1, 1, 3) == 1 - @test clamp(2, 1, 3) == 2 - @test clamp(3, 1, 3) == 3 - @test clamp(4, 1, 3) == 3 - - @test clamp(0.0, 1, 3) == 1.0 - @test clamp(1.0, 1, 3) == 1.0 - @test clamp(2.0, 1, 3) == 2.0 - @test clamp(3.0, 1, 3) == 3.0 - @test clamp(4.0, 1, 3) == 3.0 - - @test clamp.([0, 1, 2, 3, 4], 1.0, 3.0) == [1.0, 1.0, 2.0, 3.0, 3.0] - @test clamp.([0 1; 2 3], 1.0, 3.0) == [1.0 1.0; 2.0 3.0] - begin - x = [0.0, 1.0, 2.0, 3.0, 4.0] - clamp!(x, 1, 3) - @test x == [1.0, 1.0, 2.0, 3.0, 3.0] - end -end - -@testset "constants" begin - @test pi != e - @test e != 1//2 - @test 1//2 <= e - @test e <= 15//3 - @test big(1//2) < e - @test e < big(20//6) - @test e^pi == exp(pi) - @test e^2 == exp(2) - @test e^2.4 == exp(2.4) - @test e^(2//3) == exp(2//3) - - @test Float16(3.0) < pi - @test pi < Float16(4.0) - @test contains(sprint(show,π),"3.14159") -end - -@testset "frexp,ldexp,significand,exponent" begin - @testset "$T" for T in (Float16,Float32,Float64) - for z in (zero(T),-zero(T)) - frexp(z) === (z,0) - significand(z) === z - @test_throws DomainError exponent(z) - end - - for (a,b) in [(T(12.8),T(0.8)), - (prevfloat(realmin(T)), nextfloat(one(T),-2)), - (nextfloat(zero(T),3), T(0.75)), - (nextfloat(zero(T)), T(0.5))] - - n = Int(log2(a/b)) - @test frexp(a) == (b,n) - @test ldexp(b,n) == a - @test ldexp(a,-n) == b - @test significand(a) == 2b - @test exponent(a) == n-1 - - @test frexp(-a) == (-b,n) - @test ldexp(-b,n) == -a - @test ldexp(-a,-n) == -b - @test significand(-a) == -2b - @test exponent(-a) == n-1 - end - @test_throws DomainError exponent(convert(T,NaN)) - @test isnan(significand(convert(T,NaN))) - x,y = frexp(convert(T,NaN)) - @test isnan(x) - @test y == 0 - - @testset "ldexp function" begin - @test ldexp(T(0.0), 0) === T(0.0) - @test ldexp(T(-0.0), 0) === T(-0.0) - @test ldexp(T(Inf), 1) === T(Inf) - @test ldexp(T(Inf), 10000) === T(Inf) - @test ldexp(T(-Inf), 1) === T(-Inf) - @test ldexp(T(NaN), 10) === T(NaN) - @test ldexp(T(1.0), 0) === T(1.0) - @test ldexp(T(0.8), 4) === T(12.8) - @test ldexp(T(-0.854375), 5) === T(-27.34) - @test ldexp(T(1.0), typemax(Int)) === T(Inf) - @test ldexp(T(1.0), typemin(Int)) === T(0.0) - @test ldexp(prevfloat(realmin(T)), typemax(Int)) === T(Inf) - @test ldexp(prevfloat(realmin(T)), typemin(Int)) === T(0.0) - - @test ldexp(T(0.0), Int128(0)) === T(0.0) - @test ldexp(T(-0.0), Int128(0)) === T(-0.0) - @test ldexp(T(1.0), Int128(0)) === T(1.0) - @test ldexp(T(0.8), Int128(4)) === T(12.8) - @test ldexp(T(-0.854375), Int128(5)) === T(-27.34) - @test ldexp(T(1.0), typemax(Int128)) === T(Inf) - @test ldexp(T(1.0), typemin(Int128)) === T(0.0) - @test ldexp(prevfloat(realmin(T)), typemax(Int128)) === T(Inf) - @test ldexp(prevfloat(realmin(T)), typemin(Int128)) === T(0.0) - - @test ldexp(T(0.0), BigInt(0)) === T(0.0) - @test ldexp(T(-0.0), BigInt(0)) === T(-0.0) - @test ldexp(T(1.0), BigInt(0)) === T(1.0) - @test ldexp(T(0.8), BigInt(4)) === T(12.8) - @test ldexp(T(-0.854375), BigInt(5)) === T(-27.34) - @test ldexp(T(1.0), BigInt(typemax(Int128))) === T(Inf) - @test ldexp(T(1.0), BigInt(typemin(Int128))) === T(0.0) - @test ldexp(prevfloat(realmin(T)), BigInt(typemax(Int128))) === T(Inf) - @test ldexp(prevfloat(realmin(T)), BigInt(typemin(Int128))) === T(0.0) - - # Test also against BigFloat reference. Needs to be exactly rounded. - @test ldexp(realmin(T), -1) == T(ldexp(big(realmin(T)), -1)) - @test ldexp(realmin(T), -2) == T(ldexp(big(realmin(T)), -2)) - @test ldexp(realmin(T)/2, 0) == T(ldexp(big(realmin(T)/2), 0)) - @test ldexp(realmin(T)/3, 0) == T(ldexp(big(realmin(T)/3), 0)) - @test ldexp(realmin(T)/3, -1) == T(ldexp(big(realmin(T)/3), -1)) - @test ldexp(realmin(T)/3, 11) == T(ldexp(big(realmin(T)/3), 11)) - @test ldexp(realmin(T)/11, -10) == T(ldexp(big(realmin(T)/11), -10)) - @test ldexp(-realmin(T)/11, -10) == T(ldexp(big(-realmin(T)/11), -10)) - end - end -end - -# We compare to BigFloat instead of hard-coding -# values, assuming that BigFloat has an independently tested implementation. -@testset "basic math functions" begin - @testset "$T" for T in (Float32, Float64) - x = T(1//3) - y = T(1//2) - yi = 4 - @testset "Random values" begin - @test x^y ≈ big(x)^big(y) - @test x^1 === x - @test x^yi ≈ big(x)^yi - @test acos(x) ≈ acos(big(x)) - @test acosh(1+x) ≈ acosh(big(1+x)) - @test asin(x) ≈ asin(big(x)) - @test asinh(x) ≈ asinh(big(x)) - @test atan(x) ≈ atan(big(x)) - @test atan2(x,y) ≈ atan2(big(x),big(y)) - @test atanh(x) ≈ atanh(big(x)) - @test cbrt(x) ≈ cbrt(big(x)) - @test cos(x) ≈ cos(big(x)) - @test cosh(x) ≈ cosh(big(x)) - @test exp(x) ≈ exp(big(x)) - @test exp10(x) ≈ exp10(big(x)) - @test exp2(x) ≈ exp2(big(x)) - @test expm1(x) ≈ expm1(big(x)) - @test hypot(x,y) ≈ hypot(big(x),big(y)) - @test hypot(x,x,y) ≈ hypot(hypot(big(x),big(x)),big(y)) - @test hypot(x,x,y,y) ≈ hypot(hypot(big(x),big(x)),hypot(big(y),big(y))) - @test log(x) ≈ log(big(x)) - @test log10(x) ≈ log10(big(x)) - @test log1p(x) ≈ log1p(big(x)) - @test log2(x) ≈ log2(big(x)) - @test sin(x) ≈ sin(big(x)) - @test sinh(x) ≈ sinh(big(x)) - @test sqrt(x) ≈ sqrt(big(x)) - @test tan(x) ≈ tan(big(x)) - @test tanh(x) ≈ tanh(big(x)) - end - @testset "Special values" begin - @test isequal(T(1//4)^T(1//2), T(1//2)) - @test isequal(T(1//4)^2, T(1//16)) - @test isequal(acos(T(1)), T(0)) - @test isequal(acosh(T(1)), T(0)) - @test asin(T(1)) ≈ T(pi)/2 atol=eps(T) - @test atan(T(1)) ≈ T(pi)/4 atol=eps(T) - @test atan2(T(1),T(1)) ≈ T(pi)/4 atol=eps(T) - @test isequal(cbrt(T(0)), T(0)) - @test isequal(cbrt(T(1)), T(1)) - @test isequal(cbrt(T(1000000000)), T(1000)) - @test isequal(cos(T(0)), T(1)) - @test cos(T(pi)/2) ≈ T(0) atol=eps(T) - @test isequal(cos(T(pi)), T(-1)) - @test exp(T(1)) ≈ T(e) atol=10*eps(T) - @test isequal(exp10(T(1)), T(10)) - @test isequal(exp2(T(1)), T(2)) - @test isequal(expm1(T(0)), T(0)) - @test expm1(T(1)) ≈ T(e)-1 atol=10*eps(T) - @test isequal(hypot(T(3),T(4)), T(5)) - @test isequal(log(T(1)), T(0)) - @test isequal(log(e,T(1)), T(0)) - @test log(T(e)) ≈ T(1) atol=eps(T) - @test isequal(log10(T(1)), T(0)) - @test isequal(log10(T(10)), T(1)) - @test isequal(log1p(T(0)), T(0)) - @test log1p(T(e)-1) ≈ T(1) atol=eps(T) - @test isequal(log2(T(1)), T(0)) - @test isequal(log2(T(2)), T(1)) - @test isequal(sin(T(0)), T(0)) - @test isequal(sin(T(pi)/2), T(1)) - @test sin(T(pi)) ≈ T(0) atol=eps(T) - @test isequal(sqrt(T(0)), T(0)) - @test isequal(sqrt(T(1)), T(1)) - @test isequal(sqrt(T(100000000)), T(10000)) - @test isequal(tan(T(0)), T(0)) - @test tan(T(pi)/4) ≈ T(1) atol=eps(T) - end - @testset "Inverses" begin - @test acos(cos(x)) ≈ x - @test acosh(cosh(x)) ≈ x - @test asin(sin(x)) ≈ x - @test cbrt(x)^3 ≈ x - @test cbrt(x^3) ≈ x - @test asinh(sinh(x)) ≈ x - @test atan(tan(x)) ≈ x - @test atan2(x,y) ≈ atan(x/y) - @test atanh(tanh(x)) ≈ x - @test cos(acos(x)) ≈ x - @test cosh(acosh(1+x)) ≈ 1+x - @test exp(log(x)) ≈ x - @test exp10(log10(x)) ≈ x - @test exp2(log2(x)) ≈ x - @test expm1(log1p(x)) ≈ x - @test log(exp(x)) ≈ x - @test log10(exp10(x)) ≈ x - @test log1p(expm1(x)) ≈ x - @test log2(exp2(x)) ≈ x - @test sin(asin(x)) ≈ x - @test sinh(asinh(x)) ≈ x - @test sqrt(x)^2 ≈ x - @test sqrt(x^2) ≈ x - @test tan(atan(x)) ≈ x - @test tanh(atanh(x)) ≈ x - end - @testset "Relations between functions" begin - @test cosh(x) ≈ (exp(x)+exp(-x))/2 - @test cosh(x)^2-sinh(x)^2 ≈ 1 - @test hypot(x,y) ≈ sqrt(x^2+y^2) - @test sin(x)^2+cos(x)^2 ≈ 1 - @test sinh(x) ≈ (exp(x)-exp(-x))/2 - @test tan(x) ≈ sin(x)/cos(x) - @test tanh(x) ≈ sinh(x)/cosh(x) - end - @testset "Edge cases" begin - @test isinf(log(zero(T))) - @test isnan(log(convert(T,NaN))) - @test_throws DomainError log(-one(T)) - @test isinf(log1p(-one(T))) - @test isnan(log1p(convert(T,NaN))) - @test_throws DomainError log1p(convert(T,-2.0)) - @test hypot(T(0), T(0)) === T(0) - @test hypot(T(Inf), T(Inf)) === T(Inf) - @test hypot(T(Inf), T(x)) === T(Inf) - @test hypot(T(Inf), T(NaN)) === T(Inf) - @test isnan(hypot(T(x), T(NaN))) - end - end -end -@test exp10(5) ≈ exp10(5.0) -@test exp10(50//10) ≈ exp10(5.0) -@test log10(exp10(e)) ≈ e -@test exp2(Float16(2.)) ≈ exp2(2.) -@test log(e) == 1 - -@testset "exp function" for T in (Float64, Float32) - @testset "$T accuracy" begin - X = map(T, vcat(-10:0.0002:10, -80:0.001:80, 2.0^-27, 2.0^-28, 2.0^-14, 2.0^-13)) - for x in X - y, yb = exp(x), exp(big(x)) - @test abs(y-yb) <= 1.0*eps(T(yb)) - end - end - @testset "$T edge cases" begin - @test isnan(exp(T(NaN))) - @test exp(T(-Inf)) === T(0.0) - @test exp(T(Inf)) === T(Inf) - @test exp(T(0.0)) === T(1.0) # exact - @test exp(T(5000.0)) === T(Inf) - @test exp(T(-5000.0)) === T(0.0) - end -end - -@testset "test abstractarray trig fxns" begin - TAA = rand(2,2) - TAA = (TAA + TAA.')/2. - STAA = Symmetric(TAA) - @test full(atanh.(STAA)) == atanh.(TAA) - @test full(asinh.(STAA)) == asinh.(TAA) - @test full(acosh.(STAA+Symmetric(ones(TAA)))) == acosh.(TAA+ones(TAA)) - @test full(acsch.(STAA+Symmetric(ones(TAA)))) == acsch.(TAA+ones(TAA)) - @test full(acoth.(STAA+Symmetric(ones(TAA)))) == acoth.(TAA+ones(TAA)) -end - -@testset "check exp2(::Integer) matches exp2(::Float)" begin - for ii in -2048:2048 - expected = exp2(float(ii)) - @test exp2(Int16(ii)) == expected - @test exp2(Int32(ii)) == expected - @test exp2(Int64(ii)) == expected - @test exp2(Int128(ii)) == expected - if ii >= 0 - @test exp2(UInt16(ii)) == expected - @test exp2(UInt32(ii)) == expected - @test exp2(UInt64(ii)) == expected - @test exp2(UInt128(ii)) == expected - end - end -end - -@testset "deg2rad/rad2deg" begin - @testset "$T" for T in (Int, Float64, BigFloat) - @test deg2rad(T(180)) ≈ 1pi - @test deg2rad.(T[45, 60]) ≈ [pi/T(4), pi/T(3)] - @test rad2deg.([pi/T(4), pi/T(3)]) ≈ [45, 60] - @test rad2deg(T(1)*pi) ≈ 180 - @test rad2deg(T(1)) ≈ rad2deg(true) - @test deg2rad(T(1)) ≈ deg2rad(true) - end -end - -@testset "degree-based trig functions" begin - @testset "$T" for T = (Float32,Float64,Rational{Int}) - fT = typeof(float(one(T))) - for x = -400:40:400 - @test sind(convert(T,x))::fT ≈ convert(fT,sin(pi/180*x)) atol=eps(deg2rad(convert(fT,x))) - @test cosd(convert(T,x))::fT ≈ convert(fT,cos(pi/180*x)) atol=eps(deg2rad(convert(fT,x))) - end - @testset "sind" begin - @test sind(convert(T,0.0))::fT === zero(fT) - @test sind(convert(T,180.0))::fT === zero(fT) - @test sind(convert(T,360.0))::fT === zero(fT) - T != Rational{Int} && @test sind(convert(T,-0.0))::fT === -zero(fT) - @test sind(convert(T,-180.0))::fT === -zero(fT) - @test sind(convert(T,-360.0))::fT === -zero(fT) - end - @testset "cosd" begin - @test cosd(convert(T,90))::fT === zero(fT) - @test cosd(convert(T,270))::fT === zero(fT) - @test cosd(convert(T,-90))::fT === zero(fT) - @test cosd(convert(T,-270))::fT === zero(fT) - end - - @testset "sinpi and cospi" begin - for x = -3:0.3:3 - @test sinpi(convert(T,x))::fT ≈ convert(fT,sin(pi*x)) atol=eps(pi*convert(fT,x)) - @test cospi(convert(T,x))::fT ≈ convert(fT,cos(pi*x)) atol=eps(pi*convert(fT,x)) - end - - @test sinpi(convert(T,0.0))::fT === zero(fT) - @test sinpi(convert(T,1.0))::fT === zero(fT) - @test sinpi(convert(T,2.0))::fT === zero(fT) - T != Rational{Int} && @test sinpi(convert(T,-0.0))::fT === -zero(fT) - @test sinpi(convert(T,-1.0))::fT === -zero(fT) - @test sinpi(convert(T,-2.0))::fT === -zero(fT) - @test_throws DomainError sinpi(convert(T,Inf)) - - @test cospi(convert(T,0.5))::fT === zero(fT) - @test cospi(convert(T,1.5))::fT === zero(fT) - @test cospi(convert(T,-0.5))::fT === zero(fT) - @test cospi(convert(T,-1.5))::fT === zero(fT) - @test_throws DomainError cospi(convert(T,Inf)) - end - @testset "Check exact values" begin - @test sind(convert(T,30)) == 0.5 - @test cosd(convert(T,60)) == 0.5 - @test sind(convert(T,150)) == 0.5 - @test sinpi(one(T)/convert(T,6)) == 0.5 - @test_throws DomainError sind(convert(T,Inf)) - @test_throws DomainError cosd(convert(T,Inf)) - T != Float32 && @test cospi(one(T)/convert(T,3)) == 0.5 - T == Rational{Int} && @test sinpi(5//6) == 0.5 - end - end -end - -@testset "Integer args to sinpi/cospi/sinc/cosc" begin - @test sinpi(1) == 0 - @test sinpi(-1) == -0 - @test cospi(1) == -1 - @test cospi(2) == 1 - - @test sinc(1) == 0 - @test sinc(complex(1,0)) == 0 - @test sinc(0) == 1 - @test sinc(Inf) == 0 - @test cosc(1) == -1 - @test cosc(0) == 0 - @test cosc(complex(1,0)) == -1 - @test cosc(Inf) == 0 -end - -@testset "trig function type stability" begin - @testset "$T $f" for T = (Float32,Float64,BigFloat), f = (sind,cosd,sinpi,cospi) - @test Base.return_types(f,Tuple{T}) == [T] - end -end - -@testset "beta, lbeta" begin - @test beta(3/2,7/2) ≈ 5π/128 - @test beta(3,5) ≈ 1/105 - @test lbeta(5,4) ≈ log(beta(5,4)) - @test beta(5,4) ≈ beta(4,5) - @test beta(-1/2, 3) ≈ beta(-1/2 + 0im, 3 + 0im) ≈ -16/3 - @test lbeta(-1/2, 3) ≈ log(16/3) - @test beta(Float32(5),Float32(4)) == beta(Float32(4),Float32(5)) - @test beta(3,5) ≈ beta(3+0im,5+0im) - @test(beta(3.2+0.1im,5.3+0.3im) ≈ exp(lbeta(3.2+0.1im,5.3+0.3im)) ≈ - 0.00634645247782269506319336871208405439180447035257028310080 - - 0.00169495384841964531409376316336552555952269360134349446910im) -end - -# useful test functions for relative error, which differ from isapprox (≈) -# in that relerrc separately looks at the real and imaginary parts -relerr(z, x) = z == x ? 0.0 : abs(z - x) / abs(x) -relerrc(z, x) = max(relerr(real(z),real(x)), relerr(imag(z),imag(x))) -≅(a,b) = relerrc(a,b) ≤ 1e-13 - -@testset "gamma and friends" begin - @testset "gamma, lgamma (complex argument)" begin - if Base.Math.libm == "libopenlibm" - @test gamma.(Float64[1:25;]) == gamma.(1:25) - else - @test gamma.(Float64[1:25;]) ≈ gamma.(1:25) - end - for elty in (Float32, Float64) - @test gamma(convert(elty,1/2)) ≈ convert(elty,sqrt(π)) - @test gamma(convert(elty,-1/2)) ≈ convert(elty,-2sqrt(π)) - @test lgamma(convert(elty,-1/2)) ≈ convert(elty,log(abs(gamma(-1/2)))) - end - @test lgamma(1.4+3.7im) ≈ -3.7094025330996841898 + 2.4568090502768651184im - @test lgamma(1.4+3.7im) ≈ log(gamma(1.4+3.7im)) - @test lgamma(-4.2+0im) ≈ lgamma(-4.2)-5pi*im - @test factorial(3.0) == gamma(4.0) == factorial(3) - for x in (3.2, 2+1im, 3//2, 3.2+0.1im) - @test factorial(x) == gamma(1+x) - end - @test lfact(0) == lfact(1) == 0 - @test lfact(2) == lgamma(3) - # Ensure that the domain of lfact matches that of factorial (issue #21318) - @test_throws DomainError lfact(-3) - @test_throws MethodError lfact(1.0) - end - - # lgamma test cases (from Wolfram Alpha) - @test lgamma(-300im) ≅ -473.17185074259241355733179182866544204963885920016823743 - 1410.3490664555822107569308046418321236643870840962522425im - @test lgamma(3.099) ≅ lgamma(3.099+0im) ≅ 0.786413746900558058720665860178923603134125854451168869796 - @test lgamma(1.15) ≅ lgamma(1.15+0im) ≅ -0.06930620867104688224241731415650307100375642207340564554 - @test lgamma(0.89) ≅ lgamma(0.89+0im) ≅ 0.074022173958081423702265889979810658434235008344573396963 - @test lgamma(0.91) ≅ lgamma(0.91+0im) ≅ 0.058922567623832379298241751183907077883592982094770449167 - @test lgamma(0.01) ≅ lgamma(0.01+0im) ≅ 4.599479878042021722513945411008748087261001413385289652419 - @test lgamma(-3.4-0.1im) ≅ -1.1733353322064779481049088558918957440847715003659143454 + 12.331465501247826842875586104415980094316268974671819281im - @test lgamma(-13.4-0.1im) ≅ -22.457344044212827625152500315875095825738672314550695161 + 43.620560075982291551250251193743725687019009911713182478im - @test lgamma(-13.4+0.0im) ≅ conj(lgamma(-13.4-0.0im)) ≅ -22.404285036964892794140985332811433245813398559439824988 - 43.982297150257105338477007365913040378760371591251481493im - @test lgamma(-13.4+8im) ≅ -44.705388949497032519400131077242200763386790107166126534 - 22.208139404160647265446701539526205774669649081807864194im - @test lgamma(1+exp2(-20)) ≅ lgamma(1+exp2(-20)+0im) ≅ -5.504750066148866790922434423491111098144565651836914e-7 - @test lgamma(1+exp2(-20)+exp2(-19)*im) ≅ -5.5047799872835333673947171235997541985495018556426e-7 - 1.1009485171695646421931605642091915847546979851020e-6im - @test lgamma(-300+2im) ≅ -1419.3444991797240659656205813341478289311980525970715668 - 932.63768120761873747896802932133229201676713644684614785im - @test lgamma(300+2im) ≅ 1409.19538972991765122115558155209493891138852121159064304 + 11.4042446282102624499071633666567192538600478241492492652im - @test lgamma(1-6im) ≅ -7.6099596929506794519956058191621517065972094186427056304 - 5.5220531255147242228831899544009162055434670861483084103im - @test lgamma(1-8im) ≅ -10.607711310314582247944321662794330955531402815576140186 - 9.4105083803116077524365029286332222345505790217656796587im - @test lgamma(1+6.5im) ≅ conj(lgamma(1-6.5im)) ≅ -8.3553365025113595689887497963634069303427790125048113307 + 6.4392816159759833948112929018407660263228036491479825744im - @test lgamma(1+1im) ≅ conj(lgamma(1-1im)) ≅ -0.6509231993018563388852168315039476650655087571397225919 - 0.3016403204675331978875316577968965406598997739437652369im - @test lgamma(-pi*1e7 + 6im) ≅ -5.10911758892505772903279926621085326635236850347591e8 - 9.86959420047365966439199219724905597399295814979993e7im - @test lgamma(-pi*1e7 + 8im) ≅ -5.10911765175690634449032797392631749405282045412624e8 - 9.86959074790854911974415722927761900209557190058925e7im - @test lgamma(-pi*1e14 + 6im) ≅ -1.0172766411995621854526383224252727000270225301426e16 - 9.8696044010873714715264929863618267642124589569347e14im - @test lgamma(-pi*1e14 + 8im) ≅ -1.0172766411995628137711690403794640541491261237341e16 - 9.8696044010867038531027376655349878694397362250037e14im - @test lgamma(2.05 + 0.03im) ≅ conj(lgamma(2.05 - 0.03im)) ≅ 0.02165570938532611215664861849215838847758074239924127515 + 0.01363779084533034509857648574107935425251657080676603919im - @test lgamma(2+exp2(-20)+exp2(-19)*im) ≅ 4.03197681916768997727833554471414212058404726357753e-7 + 8.06398296652953575754782349984315518297283664869951e-7im - - @testset "lgamma for non-finite arguments" begin - @test lgamma(Inf + 0im) === Inf + 0im - @test lgamma(Inf - 0.0im) === Inf - 0.0im - @test lgamma(Inf + 1im) === Inf + Inf*im - @test lgamma(Inf - 1im) === Inf - Inf*im - @test lgamma(-Inf + 0.0im) === -Inf - Inf*im - @test lgamma(-Inf - 0.0im) === -Inf + Inf*im - @test lgamma(Inf*im) === -Inf + Inf*im - @test lgamma(-Inf*im) === -Inf - Inf*im - @test lgamma(Inf + Inf*im) === lgamma(NaN + 0im) === lgamma(NaN*im) === NaN + NaN*im - end -end - -@testset "subnormal flags" begin - # Ensure subnormal flags functions don't segfault - @test any(set_zero_subnormals(true) .== [false,true]) - @test any(get_zero_subnormals() .== [false,true]) - @test set_zero_subnormals(false) - @test !get_zero_subnormals() -end - -@testset "evalpoly" begin - @test @evalpoly(2,3,4,5,6) == 3+2*(4+2*(5+2*6)) == @evalpoly(2+0im,3,4,5,6) - @test let evalcounts=0 - @evalpoly(begin - evalcounts += 1 - 4 - end, 1,2,3,4,5) - evalcounts - end == 1 - a0 = 1 - a1 = 2 - c = 3 - @test @evalpoly(c, a0, a1) == 7 -end - -@testset "cis" begin - for z in (1.234, 1.234 + 5.678im) - @test cis(z) ≈ exp(im*z) - end - let z = [1.234, 5.678] - @test cis.(z) ≈ exp.(im*z) - end -end - -@testset "modf" begin - @testset "$elty" for elty in (Float16, Float32, Float64) - @test modf( convert(elty,1.2) )[1] ≈ convert(elty,0.2) - @test modf( convert(elty,1.2) )[2] ≈ convert(elty,1.0) - @test modf( convert(elty,1.0) )[1] ≈ convert(elty,0.0) - @test modf( convert(elty,1.0) )[2] ≈ convert(elty,1.0) - end -end - -@testset "frexp" begin - @testset "$elty" for elty in (Float16, Float32, Float64) - @test frexp( convert(elty,0.5) ) == (0.5, 0) - @test frexp( convert(elty,4.0) ) == (0.5, 3) - @test frexp( convert(elty,10.5) ) == (0.65625, 4) - end -end - -@testset "log/log1p" begin - # if using Tang's algorithm, should be accurate to within 0.56 ulps - X = rand(100) - for x in X - for n = -5:5 - xn = ldexp(x,n) - - for T in (Float32,Float64) - xt = T(x) - - y = Base.Math.JuliaLibm.log(xt) - yb = log(big(xt)) - @test abs(y-yb) <= 0.56*eps(T(yb)) - - y = Base.Math.JuliaLibm.log1p(xt) - yb = log1p(big(xt)) - @test abs(y-yb) <= 0.56*eps(T(yb)) - - if n <= 0 - y = Base.Math.JuliaLibm.log1p(-xt) - yb = log1p(big(-xt)) - @test abs(y-yb) <= 0.56*eps(T(yb)) - end - end - end - end - - for n = 0:28 - @test log(2,2^n) == n - end - setprecision(10_000) do - @test log(2,big(2)^100) == 100 - @test log(2,big(2)^200) == 200 - @test log(2,big(2)^300) == 300 - @test log(2,big(2)^400) == 400 - end - - for T in (Float32,Float64) - @test log(zero(T)) == -Inf - @test isnan(log(NaN)) - @test_throws DomainError log(-one(T)) - @test log1p(-one(T)) == -Inf - @test isnan(log1p(NaN)) - @test_throws DomainError log1p(-2*one(T)) - end -end - -@testset "vectorization of 2-arg functions" begin - binary_math_functions = [ - copysign, flipsign, log, atan2, hypot, max, min, - beta, lbeta, - ] - @testset "$f" for f in binary_math_functions - x = y = 2 - v = [f(x,y)] - @test f.([x],y) == v - @test f.(x,[y]) == v - @test f.([x],[y]) == v - end -end - -@testset "issues #3024, #12822" begin - @test_throws DomainError 2 ^ -2 - @test_throws DomainError (-2)^(2.2) - @test_throws DomainError (-2.0)^(2.2) - @test_throws DomainError false ^ -2 - @test 1 ^ -2 === (-1) ^ -2 === 1 - @test (-1) ^ -3 === -1 - @test true ^ -2 === true -end - -@testset "issue #13748" begin - let A = [1 2; 3 4]; B = [5 6; 7 8]; C = [9 10; 11 12] - @test muladd(A,B,C) == A*B + C - end -end - -@testset "issue #19872" begin - f19872a(x) = x ^ 5 - f19872b(x) = x ^ (-1024) - @test 0 < f19872b(2.0) < 1e-300 - @test issubnormal(2.0 ^ (-1024)) - @test issubnormal(f19872b(2.0)) - @test !issubnormal(f19872b(0.0)) - @test f19872a(2.0) === 32.0 - @test !issubnormal(f19872a(2.0)) - @test !issubnormal(0.0) -end - -# no domain error is thrown for negative values -@test invoke(cbrt, Tuple{AbstractFloat}, -1.0) == -1.0 - -@testset "promote Float16 irrational #15359" begin - @test typeof(Float16(.5) * pi) == Float16 -end diff --git a/julia-0.6.3/share/julia/test/meta.jl b/julia-0.6.3/share/julia/test/meta.jl deleted file mode 100644 index 299ed3c..0000000 --- a/julia-0.6.3/share/julia/test/meta.jl +++ /dev/null @@ -1,151 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -# test meta-expressions that annotate blocks of code - -const inlining_on = Base.JLOptions().can_inline != 0 - -function f(x) - y = x+5 - z = y*y - q = z/y - m = q-3 -end - -@inline function f_inlined(x) - y = x+5 - z = y*y - q = z/y - m = q-3 -end - -g(x) = f(2x) -g_inlined(x) = f_inlined(2x) - -@test g(3) == g_inlined(3) -@test f(3) == f_inlined(3) - -f() = backtrace() -@inline g_inlined() = f() -@noinline g_noinlined() = f() -h_inlined() = g_inlined() -h_noinlined() = g_noinlined() - -function foundfunc(bt, funcname) - for b in bt - for lkup in StackTraces.lookup(b) - if lkup.func == funcname - return true - end - end - end - false -end -if inlining_on - @test !foundfunc(h_inlined(), :g_inlined) -end -@test foundfunc(h_noinlined(), :g_noinlined) - -using Base.pushmeta!, Base.popmeta! - -macro attach(val, ex) - esc(_attach(val, ex)) -end - -_attach(val, ex) = pushmeta!(ex, :test, val) - -@attach 42 function dummy() - false -end - -asts = code_lowered(dummy, Tuple{}) -@test length(asts) == 1 -ast = asts[1] - -body = Expr(:block) -body.args = ast.code - -@test popmeta!(body, :test) == (true, [42]) -@test popmeta!(body, :nonexistent) == (false, []) - -# Simple popmeta!() tests -ex1 = quote - $(Expr(:meta, :foo)) - x*x+1 -end -@test popmeta!(ex1, :foo)[1] -@test !popmeta!(ex1, :foo)[1] -@test !popmeta!(ex1, :bar)[1] -@test !(popmeta!(:(x*x+1), :foo)[1]) - -# Find and pop meta information from general ast locations -multi_meta = quote - $(Expr(:meta, :foo1)) - y = x - $(Expr(:meta, :foo2, :foo3)) - begin - $(Expr(:meta, :foo4, Expr(:foo5, 1, 2))) - end - x*x+1 -end -@test popmeta!(deepcopy(multi_meta), :foo1) == (true, []) -@test popmeta!(deepcopy(multi_meta), :foo2) == (true, []) -@test popmeta!(deepcopy(multi_meta), :foo3) == (true, []) -@test popmeta!(deepcopy(multi_meta), :foo4) == (true, []) -@test popmeta!(deepcopy(multi_meta), :foo5) == (true, [1,2]) -@test popmeta!(deepcopy(multi_meta), :bar) == (false, []) - -# Test that popmeta!() removes meta blocks entirely when they become empty. -for m in [:foo1, :foo2, :foo3, :foo4, :foo5] - @test popmeta!(multi_meta, m)[1] -end -@test Base.findmeta(multi_meta.args)[1] == 0 - -# Test that pushmeta! can push across other macros, -# in the case multiple pushmeta!-based macros are combined - -@attach 40 @attach 41 @attach 42 dummy_multi() = return nothing - -asts = code_lowered(dummy_multi, Tuple{}) -@test length(asts) == 1 -ast = asts[1] - -body = Expr(:block) -body.args = ast.code - -@test popmeta!(body, :test) == (true, [40]) -@test popmeta!(body, :test) == (true, [41]) -@test popmeta!(body, :test) == (true, [42]) -@test popmeta!(body, :nonexistent) == (false, []) - -# tests to fully cover functions in base/meta.jl -using Base.Meta - -@test isexpr(:(1+1),Set([:call])) -@test isexpr(:(1+1),Vector([:call])) -@test isexpr(:(1+1),(:call,)) -@test isexpr(1,:call)==false -@test isexpr(:(1+1),:call,3) -ioB = IOBuffer() -show_sexpr(ioB,:(1+1)) - -show_sexpr(ioB,QuoteNode(1),1) - -@test Base.Distributed.extract_imports(:(begin; import Foo, Bar; let; using Baz; end; end)) == - [:Foo, :Bar, :Baz] - -# test base/expr.jl -baremodule B - eval = 0 - x = 1 - module M; x = 2; end - import Base - @Base.eval x = 3 - @Base.eval M x = 4 -end -@test B.x == 3 -@test B.M.x == 4 - -# caused by #24538. forms that lower to `call` should wrap with `call` before -# recursively calling expand-forms. -@test [(0,0)... 1] == [0 0 1] -@test Float32[(0,0)... 1] == Float32[0 0 1] diff --git a/julia-0.6.3/share/julia/test/misc.jl b/julia-0.6.3/share/julia/test/misc.jl deleted file mode 100644 index ba6e20d..0000000 --- a/julia-0.6.3/share/julia/test/misc.jl +++ /dev/null @@ -1,719 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -# Tests that do not really go anywhere else - -# Test info -@test contains(sprint(info, "test"), "INFO:") -@test contains(sprint(info, "test"), "INFO: test") -@test contains(sprint(info, "test ", 1, 2, 3), "INFO: test 123") -@test contains(sprint(io->info(io,"test", prefix="MYINFO: ")), "MYINFO: test") - -# Test warn -@test contains(sprint(Base.warn_once, "test"), "WARNING: test") -@test isempty(sprint(Base.warn_once, "test")) - -@test contains(sprint(warn), "WARNING:") -@test contains(sprint(warn, "test"), "WARNING: test") -@test contains(sprint(warn, "test ", 1, 2, 3), "WARNING: test 123") -@test contains(sprint(io->warn(io, "test", prefix="MYWARNING: ")), "MYWARNING: test") -@test contains(sprint(io->warn(io, "testonce", once=true)), "WARNING: testonce") -@test isempty(sprint(io->warn(io, "testonce", once=true))) -@test !isempty(sprint(io->warn(io, "testonce", once=true, key=hash("testonce",hash("testanother"))))) -let bt = backtrace() - ws = split(chomp(sprint(warn, "test", bt)), '\n') - bs = split(chomp(sprint(Base.show_backtrace, bt)), '\n') - @test contains(ws[1],"WARNING: test") - for (l,b) in zip(ws[2:end],bs) - @test contains(l, b) - end -end - -# PR #16213 -module Logging - function bar(io) - info(io,"barinfo") - warn(io,"barwarn") - Base.display_error(io,"barerror",backtrace()) - end - function pooh(io) - info(io,"poohinfo") - warn(io,"poohwarn") - Base.display_error(io,"pooherror",backtrace()) - end -end -function foo(io) - info(io,"fooinfo") - warn(io,"foowarn") - Base.display_error(io,"fooerror",backtrace()) -end - -@test all(contains.(sprint(Logging.bar), ["INFO: barinfo", "WARNING: barwarn", "ERROR: \"barerror\""])) -@test all(contains.(sprint(Logging.pooh), ["INFO: poohinfo", "WARNING: poohwarn", "ERROR: \"pooherror\""])) -@test all(contains.(sprint(foo), ["INFO: fooinfo", "WARNING: foowarn", "ERROR: \"fooerror\""])) - - -logging(DevNull, Logging, :bar; kind=:info) -@test all(contains.(sprint(Logging.bar), ["WARNING: barwarn", "ERROR: \"barerror\""])) -@test all(contains.(sprint(Logging.pooh), ["INFO: poohinfo", "WARNING: poohwarn", "ERROR: \"pooherror\""])) -@test all(contains.(sprint(foo), ["INFO: fooinfo", "WARNING: foowarn", "ERROR: \"fooerror\""])) - -logging(DevNull, Logging; kind=:info) -@test all(contains.(sprint(Logging.bar), ["WARNING: barwarn", "ERROR: \"barerror\""])) -@test all(contains.(sprint(Logging.pooh), ["WARNING: poohwarn", "ERROR: \"pooherror\""])) -@test all(contains.(sprint(foo), ["INFO: fooinfo", "WARNING: foowarn", "ERROR: \"fooerror\""])) - -logging(DevNull; kind=:info) -@test all(contains.(sprint(Logging.bar), ["WARNING: barwarn", "ERROR: \"barerror\""])) -@test all(contains.(sprint(Logging.pooh), ["WARNING: poohwarn", "ERROR: \"pooherror\""])) -@test all(contains.(sprint(foo), ["WARNING: foowarn", "ERROR: \"fooerror\""])) - -logging(kind=:info) -@test all(contains.(sprint(Logging.bar), ["INFO: barinfo", "WARNING: barwarn", "ERROR: \"barerror\""])) -@test all(contains.(sprint(Logging.pooh), ["INFO: poohinfo", "WARNING: poohwarn", "ERROR: \"pooherror\""])) -@test all(contains.(sprint(foo), ["INFO: fooinfo", "WARNING: foowarn", "ERROR: \"fooerror\""])) - - -logging(DevNull, Logging, :bar; kind=:warn) -@test all(contains.(sprint(Logging.bar), ["INFO: barinfo", "ERROR: \"barerror\""])) -@test all(contains.(sprint(Logging.pooh), ["INFO: poohinfo", "WARNING: poohwarn", "ERROR: \"pooherror\""])) -@test all(contains.(sprint(foo), ["INFO: fooinfo", "WARNING: foowarn", "ERROR: \"fooerror\""])) - -logging(DevNull, Logging; kind=:warn) -@test all(contains.(sprint(Logging.bar), ["INFO: barinfo", "ERROR: \"barerror\""])) -@test all(contains.(sprint(Logging.pooh), ["INFO: poohinfo", "ERROR: \"pooherror\""])) -@test all(contains.(sprint(foo), ["INFO: fooinfo", "WARNING: foowarn", "ERROR: \"fooerror\""])) - -logging(DevNull; kind=:warn) -@test all(contains.(sprint(Logging.bar), ["INFO: barinfo", "ERROR: \"barerror\""])) -@test all(contains.(sprint(Logging.pooh), ["INFO: poohinfo", "ERROR: \"pooherror\""])) -@test all(contains.(sprint(foo), ["INFO: fooinfo", "ERROR: \"fooerror\""])) - -logging(kind=:warn) -@test all(contains.(sprint(Logging.bar), ["INFO: barinfo", "WARNING: barwarn", "ERROR: \"barerror\""])) -@test all(contains.(sprint(Logging.pooh), ["INFO: poohinfo", "WARNING: poohwarn", "ERROR: \"pooherror\""])) -@test all(contains.(sprint(foo), ["INFO: fooinfo", "WARNING: foowarn", "ERROR: \"fooerror\""])) - - -logging(DevNull, Logging, :bar; kind=:error) -@test all(contains.(sprint(Logging.bar), ["INFO: barinfo", "WARNING: barwarn"])) -@test all(contains.(sprint(Logging.pooh), ["INFO: poohinfo", "WARNING: poohwarn", "ERROR: \"pooherror\""])) -@test all(contains.(sprint(foo), ["INFO: fooinfo", "WARNING: foowarn", "ERROR: \"fooerror\""])) - -logging(DevNull, Logging; kind=:error) -@test all(contains.(sprint(Logging.bar), ["INFO: barinfo", "WARNING: barwarn"])) -@test all(contains.(sprint(Logging.pooh), ["INFO: poohinfo", "WARNING: poohwarn"])) -@test all(contains.(sprint(foo), ["INFO: fooinfo", "WARNING: foowarn", "ERROR: \"fooerror\""])) - -logging(DevNull; kind=:error) -@test all(contains.(sprint(Logging.bar), ["INFO: barinfo", "WARNING: barwarn"])) -@test all(contains.(sprint(Logging.pooh), ["INFO: poohinfo", "WARNING: poohwarn"])) -@test all(contains.(sprint(foo), ["INFO: fooinfo", "WARNING: foowarn"])) - -logging(kind=:error) -@test all(contains.(sprint(Logging.bar), ["INFO: barinfo", "WARNING: barwarn", "ERROR: \"barerror\""])) -@test all(contains.(sprint(Logging.pooh), ["INFO: poohinfo", "WARNING: poohwarn", "ERROR: \"pooherror\""])) -@test all(contains.(sprint(foo), ["INFO: fooinfo", "WARNING: foowarn", "ERROR: \"fooerror\""])) - - -logging(DevNull, Logging, :bar) -@test sprint(Logging.bar) == "" -@test all(contains.(sprint(Logging.pooh), ["INFO: poohinfo", "WARNING: poohwarn", "ERROR: \"pooherror\""])) -@test all(contains.(sprint(foo), ["INFO: fooinfo", "WARNING: foowarn", "ERROR: \"fooerror\""])) - -logging(DevNull, Logging) -@test sprint(Logging.bar) == "" -@test sprint(Logging.pooh) == "" -@test all(contains.(sprint(foo), ["INFO: fooinfo", "WARNING: foowarn", "ERROR: \"fooerror\""])) - -logging(DevNull) -@test sprint(Logging.bar) == "" -@test sprint(Logging.pooh) == "" -@test sprint(foo) == "" - -logging() -@test all(contains.(sprint(Logging.bar), ["INFO: barinfo", "WARNING: barwarn", "ERROR: \"barerror\""])) -@test all(contains.(sprint(Logging.pooh), ["INFO: poohinfo", "WARNING: poohwarn", "ERROR: \"pooherror\""])) -@test all(contains.(sprint(foo), ["INFO: fooinfo", "WARNING: foowarn", "ERROR: \"fooerror\""])) - -# test assert() method -@test_throws AssertionError assert(false) -let res = assert(true) - @test res === nothing -end -let - try - assert(false) - error("unexpected") - catch ex - @test isa(ex, AssertionError) - @test isempty(ex.msg) - end -end - -# test @assert macro -@test_throws AssertionError (@assert 1 == 2) -@test_throws AssertionError (@assert false) -@test_throws AssertionError (@assert false "this is a test") -@test_throws AssertionError (@assert false "this is a test" "another test") -@test_throws AssertionError (@assert false :a) -let - try - @assert 1 == 2 - error("unexpected") - catch ex - @test isa(ex, AssertionError) - @test contains(ex.msg, "1 == 2") - end -end -# test @assert message -let - try - @assert 1 == 2 "this is a test" - error("unexpected") - catch ex - @test isa(ex, AssertionError) - @test ex.msg == "this is a test" - end -end -# @assert only uses the first message string -let - try - @assert 1 == 2 "this is a test" "this is another test" - error("unexpected") - catch ex - @test isa(ex, AssertionError) - @test ex.msg == "this is a test" - end -end -# @assert calls string() on second argument -let - try - @assert 1 == 2 :random_object - error("unexpected") - catch ex - @test isa(ex, AssertionError) - @test !contains(ex.msg, "1 == 2") - @test contains(ex.msg, "random_object") - end -end -# if the second argument is an expression, c -let deepthought(x, y) = 42 - try - @assert 1 == 2 string("the answer to the ultimate question: ", - deepthought(6, 9)) - error("unexpected") - catch ex - @test isa(ex, AssertionError) - @test ex.msg == "the answer to the ultimate question: 42" - end -end - -let # test the process title functions, issue #9957 - oldtitle = Sys.get_process_title() - Sys.set_process_title("julia0x1") - @test Sys.get_process_title() == "julia0x1" - Sys.set_process_title(oldtitle) - @test Sys.get_process_title() == oldtitle -end - -# test gc_enable/disable -@test gc_enable(true) -@test gc_enable(false) -@test gc_enable(false) == false -@test gc_enable(true) == false -@test gc_enable(true) - -# test methodswith -# `methodswith` relies on exported symbols -export func4union, Base -struct NoMethodHasThisType end -@test isempty(methodswith(NoMethodHasThisType)) -@test !isempty(methodswith(Int)) -struct Type4Union end -func4union(::Union{Type4Union,Int}) = () -@test !isempty(methodswith(Type4Union)) - -# PR #10984 -# Disable on windows because of issue (missing flush) when redirecting STDERR. -let - redir_err = "redirect_stderr(STDOUT)" - exename = Base.julia_cmd() - script = "$redir_err; module A; f() = 1; end; A.f() = 1" - warning_str = readstring(`$exename --startup-file=no -e $script`) - @test contains(warning_str, "f()") -end - -# lock / unlock -let l = ReentrantLock() - lock(l) - success = Ref(false) - @test trylock(l) do - @test lock(l) do - success[] = true - return :foo - end === :foo - return :bar - end === :bar - @test success[] - t = @async begin - @test trylock(l) do - @test false - end === false - end - wait(t) - unlock(l) - @test_throws ErrorException unlock(l) -end - -# timing macros - -# test that they don't introduce global vars -global v11801, t11801, names_before_timing -names_before_timing = names(current_module(), true) - -let t = @elapsed 1+1 - @test isa(t, Real) && t >= 0 -end - -let - val, t = @timed sin(1) - @test val == sin(1) - @test isa(t, Real) && t >= 0 -end - -# problem after #11801 - at global scope -t11801 = @elapsed 1+1 -@test isa(t11801,Real) && t11801 >= 0 -v11801, t11801 = @timed sin(1) -@test v11801 == sin(1) -@test isa(t11801,Real) && t11801 >= 0 - -@test names(current_module(), true) == names_before_timing - -# interactive utilities - -import Base.summarysize -@test summarysize(Core) > (summarysize(Core.Inference) + Base.summarysize(Core.Intrinsics)) > Core.sizeof(Core) -@test summarysize(Base) > 100_000 * sizeof(Ptr) - -let R = Ref{Any}(nothing), depth = 10^6 - for i = 1:depth - R = Ref{Any}(R) - end - R = Core.svec(R, R) - @test summarysize(R) == (depth + 4) * sizeof(Ptr) -end - -module _test_whos_ -export x -x = 1.0 -end -@test sprint(whos, Main, r"^$") == "" -let v = sprint(whos, _test_whos_) - @test contains(v, "x 8 bytes Float64") -end - -# issue #13021 -let ex = try - Main.x13021 = 0 - nothing -catch ex - ex -end - @test isa(ex, ErrorException) && ex.msg == "cannot assign variables in other modules" -end - -# Issue 14173 -module Tmp14173 - export A - A = randn(2000, 2000) -end -whos(IOBuffer(), Tmp14173) # warm up -const MEMDEBUG = ccall(:jl_is_memdebug, Bool, ()) -@test @allocated(whos(IOBuffer(), Tmp14173)) < (MEMDEBUG ? 30000 : 10000) - -## test conversion from UTF-8 to UTF-16 (for Windows APIs) - -# empty arrays -@test transcode(UInt16, UInt8[]) == UInt16[] -@test transcode(UInt8, UInt16[]) == UInt8[] - -# UTF-8-like sequences -V8 = [ - # 1-byte (ASCII) - ([0x00],[0x0000]) - ([0x0a],[0x000a]) - ([0x7f],[0x007f]) - # 2-byte - ([0xc0,0x80],[0x0000]) # overlong encoding - ([0xc1,0xbf],[0x007f]) # overlong encoding - ([0xc2,0x80],[0x0080]) - ([0xc3,0xbf],[0x00ff]) - ([0xc4,0x80],[0x0100]) - ([0xc4,0xa3],[0x0123]) - ([0xdf,0xbf],[0x07ff]) - # 3-byte - ([0xe0,0x80,0x80],[0x0000]) # overlong encoding - ([0xe0,0x81,0xbf],[0x007f]) # overlong encoding - ([0xe0,0x82,0x80],[0x0080]) # overlong encoding - ([0xe0,0x9f,0xbf],[0x07ff]) # overlong encoding - ([0xe0,0xa0,0x80],[0x0800]) - ([0xe0,0xa2,0x9a],[0x089a]) - ([0xe1,0x88,0xb4],[0x1234]) - ([0xea,0xaf,0x8d],[0xabcd]) - ([0xed,0x9f,0xbf],[0xd7ff]) - ([0xed,0xa0,0x80],[0xd800]) # invalid code point – high surrogate - ([0xed,0xaf,0xbf],[0xdbff]) # invalid code point – high surrogate - ([0xed,0xb0,0x80],[0xdc00]) # invalid code point – low surrogate - ([0xed,0xbf,0xbf],[0xdfff]) # invalid code point – low surrogate - ([0xee,0x80,0x80],[0xe000]) - ([0xef,0xbf,0xbf],[0xffff]) - # 4-byte - ([0xf0,0x80,0x80,0x80],[0x0000]) # overlong encoding - ([0xf0,0x80,0x81,0xbf],[0x007f]) # overlong encoding - ([0xf0,0x80,0x82,0x80],[0x0080]) # overlong encoding - ([0xf0,0x80,0x9f,0xbf],[0x07ff]) # overlong encoding - ([0xf0,0x80,0xa0,0x80],[0x0800]) # overlong encoding - ([0xf0,0x8f,0xbf,0xbf],[0xffff]) # overlong encoding - ([0xf0,0x90,0x80,0x80],[0xd800,0xdc00]) # U+10000 - ([0xf0,0x90,0x8d,0x88],[0xd800,0xdf48]) # U+10348 - ([0xf0,0x90,0x90,0xb7],[0xd801,0xdc37]) # U+10437 - ([0xf0,0xa4,0xad,0xa2],[0xd852,0xdf62]) # U+24b62 - ([0xf2,0xab,0xb3,0x9e],[0xda6f,0xdcde]) # U+abcde - ([0xf3,0xbf,0xbf,0xbf],[0xdbbf,0xdfff]) # U+fffff - ([0xf4,0x80,0x80,0x80],[0xdbc0,0xdc00]) # U+100000 - ([0xf4,0x8a,0xaf,0x8d],[0xdbea,0xdfcd]) # U+10abcd - ([0xf4,0x8f,0xbf,0xbf],[0xdbff,0xdfff]) # U+10ffff -] - -# non UTF-8-like sequences -X8 = Vector{UInt8}[ - # invalid 1-byte sequences - [0x80], # 1 leading ones - [0xbf], - [0xc0], # 2 leading ones - [0xdf], - [0xe0], # 3 leading ones - [0xef], - [0xf0], # 4 leading ones - [0xf7], - [0xf8], # 5 leading ones - [0xfb], - [0xfc], # 6 leading ones - [0xfd], - [0xfe], # 7 leading ones - [0xff], # 8 leading ones - # other invalid sequences - [0xf4,0x90,0xbf,0xbf], - [0xf4,0x91,0x80,0x80], - [0xf7,0x80,0x80,0x80], - [0xf7,0xbf,0xbf,0xbf], - [0xf8,0x80,0x80,0x80], - [0xf8,0xbf,0xbf,0xbf], - [0xff,0x80,0x80,0x80], - [0xff,0xbf,0xbf,0xbf], -] - -for s in [map(first,V8); X8], - i = 1:length(s)-1, - j = i+1:length(s)-(i==1) - ss = s[i:j] - ss in X8 || push!(X8, ss) -end -sort!(X8, lt=lexless) -sort!(X8, by=length) - -I8 = [(s,map(UInt16,s)) for s in X8] - -for (X,Y,Z) in ((V8,V8,V8), (I8,V8,I8), (V8,I8,V8), (V8,V8,I8), (I8,V8,V8)) - for (a8, a16) in X - @test transcode(UInt16, a8) == a16 - for (b8, b16) in Y - ab8 = [a8; b8] - ab16 = [a16; b16] - @test transcode(UInt16, ab8) == ab16 - for (c8, c16) in Z - abc8 = [ab8; c8] - abc16 = [ab16; c16] - @test transcode(UInt16, abc8) == abc16 - end - end - end -end - -# UTF-16-like sequences -V16 = [ - # 1-unit UTF-16, 1-byte UTF-8 (ASCII) - ([0x0000],[0x00]) - ([0x000a],[0x0a]) - ([0x007f],[0x7f]) - # 1-unit UTF-16, 2-byte UTF-8 - ([0x0080],[0xc2,0x80]) - ([0x00ff],[0xc3,0xbf]) - ([0x0100],[0xc4,0x80]) - ([0x0123],[0xc4,0xa3]) - ([0x07ff],[0xdf,0xbf]) - # 1-unit UTF-16, 3-byte UTF-8 - ([0x0800],[0xe0,0xa0,0x80]) - ([0x089a],[0xe0,0xa2,0x9a]) - ([0x1234],[0xe1,0x88,0xb4]) - ([0xabcd],[0xea,0xaf,0x8d]) - ([0xd7ff],[0xed,0x9f,0xbf]) - ([0xe000],[0xee,0x80,0x80]) - ([0xffff],[0xef,0xbf,0xbf]) - # 2-unit UTF-16, 4-byte UTF-8 - ([0xd800,0xdc00],[0xf0,0x90,0x80,0x80]) # U+10000 - ([0xd800,0xdf48],[0xf0,0x90,0x8d,0x88]) # U+10348 - ([0xd801,0xdc37],[0xf0,0x90,0x90,0xb7]) # U+10437 - ([0xd852,0xdf62],[0xf0,0xa4,0xad,0xa2]) # U+24b62 - ([0xda6f,0xdcde],[0xf2,0xab,0xb3,0x9e]) # U+abcde - ([0xdbbf,0xdfff],[0xf3,0xbf,0xbf,0xbf]) # U+fffff - ([0xdbc0,0xdc00],[0xf4,0x80,0x80,0x80]) # U+100000 - ([0xdbea,0xdfcd],[0xf4,0x8a,0xaf,0x8d]) # U+10abcd - ([0xdbff,0xdfff],[0xf4,0x8f,0xbf,0xbf]) # U+10ffff -] - -I16 = [ - ([0xd800],[0xed,0xa0,0x80]) # high surrogate - ([0xdbff],[0xed,0xaf,0xbf]) # high surrogate - ([0xdc00],[0xed,0xb0,0x80]) # low surrogate - ([0xdfff],[0xed,0xbf,0xbf]) # low surrogate -] - -for (X,Y,Z) in ((V16,V16,V16), (I16,V16,I16), (V16,I16,V16), (V16,V16,I16), (I16,V16,V16)) - for (a16, a8) in X - @test transcode(UInt8, a16) == a8 - @test transcode(UInt16, a8) == a16 - for (b16, b8) in Y - ab16 = [a16; b16] - ab8 = [a8; b8] - @test transcode(UInt8, ab16) == ab8 - @test transcode(UInt16, ab8) == ab16 - for (c16, c8) in Z - abc16 = [ab16; c16] - abc8 = [ab8; c8] - @test transcode(UInt8, abc16) == abc8 - @test transcode(UInt16, abc8) == abc16 - end - end - end -end - -let s = "abcα🐨\0x\0" - for T in (UInt8, UInt16, UInt32, Int32) - @test transcode(T, s) == transcode(T, Vector{UInt8}(s)) - @test transcode(String, transcode(T, s)) == s - end -end - -# clipboard functionality -if is_windows() - for str in ("Hello, world.", "∀ x ∃ y", "") - clipboard(str) - @test clipboard() == str - end -end - -let optstring = stringmime(MIME("text/plain"), Base.JLOptions()) - @test startswith(optstring, "JLOptions(\n") - @test !contains(optstring, "Ptr") - @test endswith(optstring, "\n)") - @test contains(optstring, " = \"") -end -let optstring = repr(Base.JLOptions()) - @test startswith(optstring, "JLOptions(") - @test endswith(optstring, ")") - @test !contains(optstring, "\n") - @test !contains(optstring, "Ptr") - @test contains(optstring, " = \"") -end - -# Base.securezero! functions (#17579) -import Base: securezero!, unsafe_securezero! -let a = [1,2,3] - @test securezero!(a) === a == [0,0,0] - a[:] = 1:3 - @test unsafe_securezero!(pointer(a), length(a)) == pointer(a) - @test a == [0,0,0] - a[:] = 1:3 - @test unsafe_securezero!(Ptr{Void}(pointer(a)), sizeof(a)) == Ptr{Void}(pointer(a)) - @test a == [0,0,0] -end -let creds = Base.LibGit2.CachedCredentials() - LibGit2.get_creds!(creds, "foo", LibGit2.SSHCredentials()).pass = "bar" - securezero!(creds) - @test LibGit2.get_creds!(creds, "foo", nothing).pass == "\0\0\0" -end - -# Test that we can VirtualProtect jitted code to writable -if is_windows() - @noinline function WeVirtualProtectThisToRWX(x, y) - x+y - end - - let addr = cfunction(WeVirtualProtectThisToRWX, UInt64, (UInt64, UInt64)) - addr = addr-(UInt64(addr)%4096) - const PAGE_EXECUTE_READWRITE = 0x40 - oldPerm = Ref{UInt32}() - err18083 = ccall(:VirtualProtect,stdcall,Cint, - (Ptr{Void}, Csize_t, UInt32, Ptr{UInt32}), - addr, 4096, PAGE_EXECUTE_READWRITE, oldPerm) - err18083 == 0 && error(Libc.GetLastError()) - end -end - -# CRC32c checksum (test data generated from @andrewcooke's CRC.jl package) -for force_software_crc in (1,0) - ccall(:jl_crc32c_init, Void, (Cint,), force_software_crc) - for (n,crc) in [(0,0x00000000),(1,0xa016d052),(2,0x03f89f52),(3,0xf130f21e),(4,0x29308cf4),(5,0x53518fab),(6,0x4f4dfbab),(7,0xbd3a64dc),(8,0x46891f81),(9,0x5a14b9f9),(10,0xb219db69),(11,0xd232a91f),(12,0x51a15563),(13,0x9f92de41),(14,0x4d8ae017),(15,0xc8b74611),(16,0xa0de6714),(17,0x672c992a),(18,0xe8206eb6),(19,0xc52fd285),(20,0x327b0397),(21,0x318263dd),(22,0x08485ccd),(23,0xea44d29e),(24,0xf6c0cb13),(25,0x3969bba2),(26,0x6a8810ec),(27,0x75b3d0df),(28,0x82d535b1),(29,0xbdf7fc12),(30,0x1f836b7d),(31,0xd29f33af),(32,0x8e4acb3e),(33,0x1cbee2d1),(34,0xb25f7132),(35,0xb0fa484c),(36,0xb9d262b4),(37,0x3207fe27),(38,0xa024d7ac),(39,0x49a2e7c5),(40,0x0e2c157f),(41,0x25f7427f),(42,0x368c6adc),(43,0x75efd4a5),(44,0xa84c5c31),(45,0x0fc817b2),(46,0x8d99a881),(47,0x5cc3c078),(48,0x9983d5e2),(49,0x9267c2db),(50,0xc96d4745),(51,0x058d8df3),(52,0x453f9cf3),(53,0xb714ade1),(54,0x55d3c2bc),(55,0x495710d0),(56,0x3bddf494),(57,0x4f2577d0),(58,0xdae0f604),(59,0x3c57c632),(60,0xfe39bbb0),(61,0x6f5d1d41),(62,0x7d996665),(63,0x68c738dc),(64,0x8dfea7ae)] - @test Base.crc32c(UInt8[1:n;]) == crc - end -end - -let - old_have_color = Base.have_color - try - @eval Base have_color = true - buf = IOBuffer() - print_with_color(:red, buf, "foo") - @test startswith(String(take!(buf)), Base.text_colors[:red]) - finally - @eval Base have_color = $(old_have_color) - end -end - -# Test that `print_with_color` accepts non-string values, just as `print` does -let - old_have_color = Base.have_color - try - @eval Base have_color = true - buf_color = IOBuffer() - args = (3.2, "foo", :testsym) - print_with_color(:red, buf_color, args...) - buf_plain = IOBuffer() - print(buf_plain, args...) - expected_str = string(Base.text_colors[:red], - String(take!(buf_plain)), - Base.text_colors[:default]) - @test expected_str == String(take!(buf_color)) - finally - @eval Base have_color = $(old_have_color) - end -end - -let - global c_18711 = 0 - buf = IOContext(IOBuffer(), :hascontext => true) - Base.with_output_color(:red, buf) do buf - global c_18711 - get(buf, :hascontext, false) && (c_18711 += 1) - end - @test c_18711 == 1 -end - -let - old_have_color = Base.have_color - try - @eval Base have_color = true - buf = IOBuffer() - print_with_color(:red, buf, "foo") - # Check that we get back to normal text color in the end - @test String(take!(buf)) == "\e[31mfoo\e[39m" - - # Check that boldness is turned off - print_with_color(:red, buf, "foo"; bold = true) - @test String(take!(buf)) == "\e[1m\e[31mfoo\e[39m\e[22m" - finally - @eval Base have_color = $(old_have_color) - end -end - -abstract type DA_19281{T, N} <: AbstractArray{T, N} end -Base.convert{S,T,N}(::Type{Array{S, N}}, ::DA_19281{T, N}) = error() -x_19281 = [(), (1,)] -mutable struct Foo_19281 - f::Vector{Tuple} - Foo_19281() = new(x_19281) -end - -@testset "test this does not segfault #19281" begin - @test Foo_19281().f[1] == () - @test Foo_19281().f[2] == (1,) -end - -let - x_notdefined = Ref{String}() - @test !isassigned(x_notdefined) - - x_defined = Ref{String}("Test") - @test isassigned(x_defined) -end - -mutable struct Demo_20254 - arr::Array{String} -end - -# these cause stack overflows and are a little flaky on CI, ref #20256 -if Bool(parse(Int,(get(ENV, "JULIA_TESTFULL", "0")))) - function Demo_20254(arr::AbstractArray=Any[]) - Demo_20254(string.(arr)) - end - - _unsafe_get_19433(x::NTuple{1}) = (unsafe_get(x[1]),) - _unsafe_get_19433(xs::Vararg) = (unsafe_get(xs[1]), _unsafe_get_19433(xs[2:end])...) - - f_19433(f_19433, xs...) = f_19433(_unsafe_get_19433(xs)...) - - @testset "test this does not crash, issue #19433 and #20254" begin - @test_throws StackOverflowError Demo_20254() - @test_throws StackOverflowError f_19433(+, 1, 2) - end -end - -# invokelatest function for issue #19774 -issue19774(x) = 1 -let foo() = begin - eval(:(issue19774(x::Int) = 2)) - return Base.invokelatest(issue19774, 0) - end - @test foo() == 2 -end - -# Endian tests -# For now, we only support little endian. -# Add an `Sys.ARCH` test for big endian when/if we add support for that. -# Do **NOT** use `ENDIAN_BOM` to figure out the endianess -# since that's exactly what we want to test. -@test ENDIAN_BOM == 0x04030201 -@test ntoh(0x1) == 0x1 -@test hton(0x1) == 0x1 -@test ltoh(0x1) == 0x1 -@test htol(0x1) == 0x1 -@test ntoh(0x102) == 0x201 -@test hton(0x102) == 0x201 -@test ltoh(0x102) == 0x102 -@test htol(0x102) == 0x102 -@test ntoh(0x1020304) == 0x4030201 -@test hton(0x1020304) == 0x4030201 -@test ltoh(0x1020304) == 0x1020304 -@test htol(0x1020304) == 0x1020304 -@test ntoh(0x102030405060708) == 0x807060504030201 -@test hton(0x102030405060708) == 0x807060504030201 -@test ltoh(0x102030405060708) == 0x102030405060708 -@test htol(0x102030405060708) == 0x102030405060708 - -@testset "inline bug #18735" begin - @noinline f(n) = n ? error() : Int - g() = Union{f(true)} - @test_throws ErrorException g() -end - -include("testenv.jl") - -let flags = Cmd(filter(a->!contains(a, "depwarn"), test_exeflags.exec)) - local cmd = `$test_exename $flags deprecation_exec.jl` - - if !success(pipeline(cmd; stdout=STDOUT, stderr=STDERR)) - error("Deprecation test failed, cmd : $cmd") - end -end diff --git a/julia-0.6.3/share/julia/test/mmap.jl b/julia-0.6.3/share/julia/test/mmap.jl deleted file mode 100644 index eb6c37f..0000000 --- a/julia-0.6.3/share/julia/test/mmap.jl +++ /dev/null @@ -1,298 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -file = tempname() -write(file, "Hello World\n") -t = b"Hello World" -@test Mmap.mmap(file, Array{UInt8,3}, (11,1,1)) == reshape(t,(11,1,1)) -gc(); gc() -@test Mmap.mmap(file, Array{UInt8,3}, (1,11,1)) == reshape(t,(1,11,1)) -gc(); gc() -@test Mmap.mmap(file, Array{UInt8,3}, (1,1,11)) == reshape(t,(1,1,11)) -gc(); gc() -@test Mmap.mmap(file, Array{UInt8,3}, (11,0,1)) == Array{UInt8}((0,0,0)) -@test Mmap.mmap(file, Vector{UInt8}, (11,)) == t -gc(); gc() -@test Mmap.mmap(file, Array{UInt8,2}, (1,11)) == t' -gc(); gc() -@test Mmap.mmap(file, Array{UInt8,2}, (0,12)) == Array{UInt8}((0,0)) -m = Mmap.mmap(file, Array{UInt8,3}, (1,2,1)) -@test m == reshape(b"He",(1,2,1)) -finalize(m); m=nothing; gc() - -# constructors -@test length(@inferred Mmap.mmap(file)) == 12 -@test length(@inferred Mmap.mmap(file, Vector{Int8})) == 12 -@test length(@inferred Mmap.mmap(file, Matrix{Int8}, (12,1))) == 12 -@test length(@inferred Mmap.mmap(file, Matrix{Int8}, (12,1), 0)) == 12 -@test length(@inferred Mmap.mmap(file, Matrix{Int8}, (12,1), 0; grow=false)) == 12 -@test length(@inferred Mmap.mmap(file, Matrix{Int8}, (12,1), 0; shared=false)) == 12 -@test length(@inferred Mmap.mmap(file, Vector{Int8}, 12)) == 12 -@test length(@inferred Mmap.mmap(file, Vector{Int8}, 12, 0)) == 12 -@test length(@inferred Mmap.mmap(file, Vector{Int8}, 12, 0; grow=false)) == 12 -@test length(@inferred Mmap.mmap(file, Vector{Int8}, 12, 0; shared=false)) == 12 -s = open(file) -@test length(@inferred Mmap.mmap(s)) == 12 -@test length(@inferred Mmap.mmap(s, Vector{Int8})) == 12 -@test length(@inferred Mmap.mmap(s, Matrix{Int8}, (12,1))) == 12 -@test length(@inferred Mmap.mmap(s, Matrix{Int8}, (12,1), 0)) == 12 -@test length(@inferred Mmap.mmap(s, Matrix{Int8}, (12,1), 0; grow=false)) == 12 -@test length(@inferred Mmap.mmap(s, Matrix{Int8}, (12,1), 0; shared=false)) == 12 -@test length(@inferred Mmap.mmap(s, Vector{Int8}, 12)) == 12 -@test length(@inferred Mmap.mmap(s, Vector{Int8}, 12, 0)) == 12 -@test length(@inferred Mmap.mmap(s, Vector{Int8}, 12, 0; grow=false)) == 12 -@test length(@inferred Mmap.mmap(s, Vector{Int8}, 12, 0; shared=false)) == 12 -close(s) -@test_throws ErrorException Mmap.mmap(file, Vector{Ref}) # must be bit-type -gc(); gc() - -s = open(f->f,file,"w") -@test Mmap.mmap(file) == Array{UInt8}(0) # requested len=0 on empty file -@test Mmap.mmap(file,Vector{UInt8},0) == Array{UInt8}(0) -m = Mmap.mmap(file,Vector{UInt8},12) -m[:] = b"Hello World\n" -Mmap.sync!(m) -finalize(m); m=nothing; gc() -@test open(readstring,file) == "Hello World\n" - -s = open(file, "r") -close(s) -@test_throws Base.UVError Mmap.mmap(s) # closed IOStream -@test_throws ArgumentError Mmap.mmap(s,Vector{UInt8},12,0) # closed IOStream -@test_throws SystemError Mmap.mmap("") - -# negative length -@test_throws ArgumentError Mmap.mmap(file, Vector{UInt8}, -1) -# negative offset -@test_throws ArgumentError Mmap.mmap(file, Vector{UInt8}, 1, -1) - -for i = 0x01:0x0c - @test length(Mmap.mmap(file, Vector{UInt8}, i)) == Int(i) -end -gc(); gc() - -sz = filesize(file) -m = Mmap.mmap(file, Vector{UInt8}, sz+1) -@test length(m) == sz+1 # test growing -@test m[end] == 0x00 -finalize(m); m=nothing; gc() -sz = filesize(file) -m = Mmap.mmap(file, Vector{UInt8}, 1, sz) -@test length(m) == 1 -@test m[1] == 0x00 -finalize(m); m=nothing; gc() -sz = filesize(file) -# test where offset is actually > than size of file; file is grown with zeroed bytes -m = Mmap.mmap(file, Vector{UInt8}, 1, sz+1) -@test length(m) == 1 -@test m[1] == 0x00 -finalize(m); m=nothing; gc() - -s = open(file, "r") -m = Mmap.mmap(s) -@test_throws ReadOnlyMemoryError m[5] = UInt8('x') # tries to setindex! on read-only array -finalize(m); m=nothing; gc() - -write(file, "Hello World\n") - -s = open(file, "r") -m = Mmap.mmap(s) -close(s) -finalize(m); m=nothing; gc() -m = Mmap.mmap(file) -s = open(file, "r+") -c = Mmap.mmap(s) -d = Mmap.mmap(s) -c[1] = UInt8('J') -Mmap.sync!(c) -close(s) -@test m[1] == UInt8('J') -@test d[1] == UInt8('J') -finalize(m); finalize(c); finalize(d) -m=nothing; c=nothing; d=nothing; gc() - -write(file, "Hello World\n") - -s = open(file, "r") -@test isreadonly(s) == true -c = Mmap.mmap(s, Vector{UInt8}, (11,)) -@test c == b"Hello World" -finalize(c); c=nothing; gc() -c = Mmap.mmap(s, Vector{UInt8}, (UInt16(11),)) -@test c == b"Hello World" -finalize(c); c=nothing; gc() -@test_throws ArgumentError Mmap.mmap(s, Vector{UInt8}, (Int16(-11),)) -@test_throws ArgumentError Mmap.mmap(s, Vector{UInt8}, (typemax(UInt),)) -close(s) -s = open(file, "r+") -@test isreadonly(s) == false -c = Mmap.mmap(s, Vector{UInt8}, (11,)) -c[5] = UInt8('x') -Mmap.sync!(c) -close(s) -s = open(file, "r") -str = readline(s) -close(s) -@test startswith(str, "Hellx World") -finalize(c); c=nothing; gc() - -c = Mmap.mmap(file) -@test c == b"Hellx World\n" -finalize(c); c=nothing; gc() -c = Mmap.mmap(file, Vector{UInt8}, 3) -@test c == b"Hel" -finalize(c); c=nothing; gc() -s = open(file, "r") -c = Mmap.mmap(s, Vector{UInt8}, 6) -@test c == b"Hellx " -close(s) -finalize(c); c=nothing; gc() -c = Mmap.mmap(file, Vector{UInt8}, 5, 6) -@test c == b"World" -finalize(c); c=nothing; gc() - -s = open(file, "w") -write(s, "Hello World\n") -close(s) - -# test Mmap.mmap -m = Mmap.mmap(file) -tdata = b"Hello World\n" -for i = 1:12 - @test m[i] == tdata[i] -end -@test_throws BoundsError m[13] -finalize(m); m=nothing; gc() - -m = Mmap.mmap(file,Vector{UInt8},6) -@test m[1] == b"H"[1] -@test m[2] == b"e"[1] -@test m[3] == b"l"[1] -@test m[4] == b"l"[1] -@test m[5] == b"o"[1] -@test m[6] == b" "[1] -@test_throws BoundsError m[7] -finalize(m); m=nothing; gc() - -m = Mmap.mmap(file,Vector{UInt8},2,6) -@test m[1] == b"W"[1] -@test m[2] == b"o"[1] -@test_throws BoundsError m[3] -finalize(m); m = nothing; gc() - -s = open(file, "w") -write(s, [0xffffffffffffffff, - 0xffffffffffffffff, - 0xffffffffffffffff, - 0x000000001fffffff]) -close(s) -s = open(file, "r") -@test isreadonly(s) -b = @inferred Mmap.mmap(s, BitArray, (17,13)) -@test Base._check_bitarray_consistency(b) -@test b == trues(17,13) -@test_throws ArgumentError Mmap.mmap(s, BitArray, (7,3)) -close(s) -s = open(file, "r+") -b = Mmap.mmap(s, BitArray, (17,19)) -@test Base._check_bitarray_consistency(b) -rand!(b) -Mmap.sync!(b) -b0 = copy(b) -@test Base._check_bitarray_consistency(b0) -close(s) -s = open(file, "r") -@test isreadonly(s) -b = Mmap.mmap(s, BitArray, (17,19)) -@test Base._check_bitarray_consistency(b) -@test b == b0 -close(s) -finalize(b); finalize(b0) -b = nothing; b0 = nothing -gc() - -open(file,"w") do f - write(f,UInt64(1)) - write(f,UInt8(1)) -end -@test filesize(file) == 9 -m = Mmap.mmap(file, BitArray, (72,)) -@test Base._check_bitarray_consistency(m) -@test length(m) == 72 -finalize(m); m = nothing; gc() -rm(file) - -# Mmap.mmap with an offset -A = rand(1:20, 500, 300) -fname = tempname() -s = open(fname, "w+") -write(s, size(A,1)) -write(s, size(A,2)) -write(s, A) -close(s) -s = open(fname) -m = read(s, Int) -n = read(s, Int) -A2 = Mmap.mmap(s, Matrix{Int}, (m,n)) -@test A == A2 -seek(s, 0) -A3 = Mmap.mmap(s, Matrix{Int}, (m,n), convert(Int64, 2*sizeof(Int))) -@test A == A3 -A4 = Mmap.mmap(s, Matrix{Int}, (m,150), convert(Int64, (2+150*m)*sizeof(Int))) -@test A[:, 151:end] == A4 -close(s) -finalize(A2); finalize(A3); finalize(A4) -A2 = A3 = A4 = nothing -gc() -rm(fname) - -# Mmap.Anonymous -m = Mmap.Anonymous() -@test m.name == "" -@test !m.readonly -@test m.create -@test isopen(m) -@test isreadable(m) -@test iswritable(m) - -m = Mmap.mmap(Vector{UInt8}, 12) -@test length(m) == 12 -@test all(m .== 0x00) -@test m[1] === 0x00 -@test m[end] === 0x00 -m[1] = 0x0a -Mmap.sync!(m) -@test m[1] === 0x0a -m = Mmap.mmap(Vector{UInt8}, 12; shared=false) -m = Mmap.mmap(Vector{Int}, 12) -@test length(m) == 12 -@test all(m .== 0) -@test m[1] === 0 -@test m[end] === 0 -m = Mmap.mmap(Vector{Float64}, 12) -@test length(m) == 12 -@test all(m .== 0.0) -m = Mmap.mmap(Matrix{Int8}, (12,12)) -@test size(m) == (12,12) -@test all(m == zeros(Int8, (12,12))) -@test sizeof(m) == prod((12,12)) -n = similar(m) -@test size(n) == (12,12) -n = similar(m, (2,2)) -@test size(n) == (2,2) -n = similar(m, 12) -@test length(n) == 12 -@test size(n) == (12,) -finalize(m); m = nothing; gc() - -# test #14885 -file = tempname() -touch(file) -open(file, "r+") do s - A = Mmap.mmap(s, Vector{UInt8}, (10,), 0) - Mmap.sync!(A) - finalize(A); A = nothing; gc() - A = Mmap.mmap(s, Vector{UInt8}, (10,), 1) - Mmap.sync!(A) - finalize(A); A = nothing; gc() -end -rm(file) diff --git a/julia-0.6.3/share/julia/test/mod2pi.jl b/julia-0.6.3/share/julia/test/mod2pi.jl deleted file mode 100644 index 103402f..0000000 --- a/julia-0.6.3/share/julia/test/mod2pi.jl +++ /dev/null @@ -1,196 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -# NOTES on range reduction -# [1] compute numbers near pi: http://www.cs.berkeley.edu/~wkahan/testpi/nearpi.c -# [2] range reduction: http://hal-ujm.ccsd.cnrs.fr/docs/00/08/69/04/PDF/RangeReductionIEEETC0305.pdf -# [3] precise addition, see Add22: http://ftp.nluug.nl/pub/os/BSD/FreeBSD/distfiles/crlibm/crlibm-1.0beta3.pdf - -# Examples: -# ΓΓ = 6411027962775774 / 2^45 # see [2] above, section 1.2 -# julia> mod(ΓΓ, 2pi) # "naive" way - easily wrong -# 7.105427357601002e-15 -# julia> mod2pi(ΓΓ) # using function provided here -# 2.475922546353431e-18 -# Wolfram Alpha: mod(6411027962775774 / 2^45, 2pi) -# 2.475922546353430800060268586243862383453213646146648435... × 10^-18 - -# Test Cases. Each row contains: x and x mod 2pi (as from Wolfram Alpha) -# The values x are: -# -pi/2, pi/2, -pi, pi, 2pi, -2pi -# (or rather, the Float64 approx to those numbers. -# Thus, x mod pi will result in a small, but positive number) -# ΓΓ = 6411027962775774 / 2^47 -# from [2], section 1.2: -# the Float64 greater than 8, and less than 2**63 − 1 closest to a multiple of π/4 is -# Γ = 6411027962775774 / 2^48. We take ΓΓ = 2*Γ to get cancellation with pi/2 already -# 3.14159265359, -3.14159265359 -# pi/16*k +/- 0.00001 for k in [-20:20] # to cover all quadrants -# numerators of continuous fraction approximations to pi -# see http://oeis.org/A002485 -# (reason: for max cancellation, we want x = k*pi + eps for small eps, so x/k ≈ pi) - -testCases = [ - -1.5707963267948966 4.71238898038469 - 1.5707963267948966 1.5707963267948966 - -3.141592653589793 3.1415926535897936 - 3.141592653589793 3.141592653589793 - 6.283185307179586 6.283185307179586 - -6.283185307179586 2.4492935982947064e-16 - 45.553093477052 1.5707963267948966 - 3.14159265359 3.14159265359 - -3.14159265359 3.1415926535895866 - -3.9269808169872418 2.356204490192345 - -3.73063127613788 2.5525540310417068 - -3.5342817352885176 2.748903571891069 - -3.337932194439156 2.945253112740431 - -3.1415826535897935 3.141602653589793 - -2.9452331127404316 3.337952194439155 - -2.7488835718910694 3.5343017352885173 - -2.5525340310417075 3.730651276137879 - -2.356184490192345 3.9270008169872415 - -2.1598349493429834 4.123350357836603 - -1.9634854084936209 4.319699898685966 - -1.7671358676442588 4.516049439535328 - -1.5707863267948967 4.71239898038469 - -1.3744367859455346 4.908748521234052 - -1.1780872450961726 5.105098062083414 - -0.9817377042468104 5.301447602932776 - -0.7853881633974483 5.4977971437821385 - -0.5890386225480863 5.6941466846315 - -0.3926890816987242 5.890496225480862 - -0.1963395408493621 6.0868457663302244 - 1.0e-5 1.0e-5 - 0.19635954084936205 0.19635954084936205 - 0.3927090816987241 0.3927090816987241 - 0.5890586225480862 0.5890586225480862 - 0.7854081633974482 0.7854081633974482 - 0.9817577042468103 0.9817577042468103 - 1.1781072450961723 1.1781072450961723 - 1.3744567859455343 1.3744567859455343 - 1.5708063267948964 1.5708063267948964 - 1.7671558676442585 1.7671558676442585 - 1.9635054084936205 1.9635054084936205 - 2.159854949342982 2.159854949342982 - 2.3562044901923445 2.3562044901923445 - 2.5525540310417063 2.5525540310417063 - 2.7489035718910686 2.7489035718910686 - 2.9452531127404304 2.9452531127404304 - 3.1416026535897927 3.1416026535897927 - 3.3379521944391546 3.3379521944391546 - 3.534301735288517 3.534301735288517 - 3.7306512761378787 3.7306512761378787 - 3.927000816987241 3.927000816987241 - -3.9270008169872415 2.356184490192345 - -3.7306512761378796 2.552534031041707 - -3.5343017352885173 2.7488835718910694 - -3.3379521944391555 2.945233112740431 - -3.141602653589793 3.1415826535897935 - -2.9452531127404313 3.3379321944391553 - -2.748903571891069 3.5342817352885176 - -2.552554031041707 3.7306312761378795 - -2.356204490192345 3.9269808169872418 - -2.159854949342983 4.123330357836603 - -1.9635054084936208 4.3196798986859655 - -1.7671558676442587 4.516029439535328 - -1.5708063267948966 4.71237898038469 - -1.3744567859455346 4.908728521234052 - -1.1781072450961725 5.105078062083414 - -0.9817577042468104 5.301427602932776 - -0.7854081633974483 5.497777143782138 - -0.5890586225480863 5.694126684631501 - -0.39270908169872415 5.890476225480862 - -0.19635954084936208 6.086825766330224 - -1.0e-5 6.283175307179587 - 0.19633954084936206 0.19633954084936206 - 0.39268908169872413 0.39268908169872413 - 0.5890386225480861 0.5890386225480861 - 0.7853881633974482 0.7853881633974482 - 0.9817377042468103 0.9817377042468103 - 1.1780872450961724 1.1780872450961724 - 1.3744367859455344 1.3744367859455344 - 1.5707863267948965 1.5707863267948965 - 1.7671358676442586 1.7671358676442586 - 1.9634854084936206 1.9634854084936206 - 2.1598349493429825 2.1598349493429825 - 2.3561844901923448 2.3561844901923448 - 2.5525340310417066 2.5525340310417066 - 2.748883571891069 2.748883571891069 - 2.9452331127404308 2.9452331127404308 - 3.141582653589793 3.141582653589793 - 3.337932194439155 3.337932194439155 - 3.534281735288517 3.534281735288517 - 3.730631276137879 3.730631276137879 - 3.9269808169872413 3.9269808169872413 - 22.0 3.1504440784612404 - 333.0 6.2743640266615035 - 355.0 3.1416227979431572 - 103993.0 6.283166177843807 - 104348.0 3.141603668607378 - 208341.0 3.141584539271598 - 312689.0 2.9006993893361787e-6 - 833719.0 3.1415903406703767 - 1.146408e6 3.1415932413697663 - 4.272943e6 6.283184757600089 - 5.419351e6 3.1415926917902683 - 8.0143857e7 6.283185292406739 - 1.65707065e8 3.1415926622445745 - 2.45850922e8 3.141592647471728 - 4.11557987e8 2.5367160519636766e-9 - 1.068966896e9 3.14159265254516 - 2.549491779e9 4.474494938161497e-10 - 6.167950454e9 3.141592653440059 - 1.4885392687e10 1.4798091093322177e-10 - 2.1053343141e10 3.14159265358804 - 1.783366216531e12 6.969482408757582e-13 - 3.587785776203e12 3.141592653589434 - 5.371151992734e12 3.1415926535901306 - 8.958937768937e12 6.283185307179564 - 1.39755218526789e14 3.1415926535898 - 4.28224593349304e14 3.1415926535897927 - 5.706674932067741e15 4.237546464512562e-16 - 6.134899525417045e15 3.141592653589793 -] - -function testModPi() - numTestCases = size(testCases,1) - modFns = [mod2pi] - xDivisors = [2pi] - errsNew, errsOld = Array{Float64}(0), Array{Float64}(0) - for rowIdx in 1:numTestCases - xExact = testCases[rowIdx,1] - for colIdx in 1:1 - xSoln = testCases[rowIdx,colIdx+1] - xDivisor = xDivisors[colIdx] - modFn = modFns[colIdx] - # 2. want: xNew := modFn(xExact) ≈ xSoln <--- this is the crucial bit, xNew close to xSoln - # 3. know: xOld := mod(xExact,xDivisor) might be quite a bit off from xSoln - that's expected - xNew = modFn(xExact) - xOld = mod(xExact,xDivisor) - - newDiff = abs(xNew - xSoln) # should be zero, ideally (our new function) - oldDiff = abs(xOld - xSoln) # should be zero in a perfect world, but often bigger due to cancellation - oldDiff = min(oldDiff, abs(xDivisor - oldDiff)) # we are being generous here: - # if xOld happens to end up "on the wrong side of 0", eg - # if xSoln = 3.14 (correct), but xOld reports 0.01, - # we don't take the long way around the circle of 3.14 - 0.01, but the short way of 3.1415.. - (3.14 - 0.1) - push!(errsNew,abs(newDiff)) - push!(errsOld,abs(oldDiff)) - end - end - sort!(errsNew) - sort!(errsOld) - totalErrNew = sum(errsNew) - totalErrOld = sum(errsOld) - @test totalErrNew ≈ 0.0 -end -testModPi() - -# 2pi -@test mod2pi(10) ≈ mod(10,2pi) -@test mod2pi(-10) ≈ mod(-10,2pi) -@test mod2pi(355) ≈ 3.1416227979431572 -@test mod2pi(Int32(355)) ≈ 3.1416227979431572 -@test mod2pi(355.0) ≈ 3.1416227979431572 -@test mod2pi(355.0f0) ≈ 3.1416228f0 -@test mod2pi(Int64(2)^60) == mod2pi(2.0^60) -@test_throws ArgumentError mod2pi(Int64(2)^60-1) diff --git a/julia-0.6.3/share/julia/test/mpfr.jl b/julia-0.6.3/share/julia/test/mpfr.jl deleted file mode 100644 index d25f7a6..0000000 --- a/julia-0.6.3/share/julia/test/mpfr.jl +++ /dev/null @@ -1,887 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -import Base.MPFR -# constructors -setprecision(53) do - x = BigFloat() - x = BigFloat(12) -end -x = BigFloat(12) -y = BigFloat(x) -@test x ≈ y -y = BigFloat(0xc) -@test x ≈ y -y = BigFloat(12.) -@test x ≈ y -y = BigFloat(BigInt(12)) -@test x ≈ y -y = BigFloat(BigFloat(12)) -@test x ≈ y -y = parse(BigFloat,"12") -@test x ≈ y -y = BigFloat(Float32(12.)) -@test x ≈ y -y = BigFloat(12//1) -@test x ≈ y - -# + -x = BigFloat(12) -y = BigFloat(30) -@test x + y == BigFloat(42) -@test x + typemax(UInt128) == x + BigInt(typemax(UInt128)) -@test x + typemax(Int128) == x + BigInt(typemax(Int128)) - -# - -x = BigFloat(12) -y = BigFloat(-30) -@test x - y == BigFloat(42) -@test x - typemax(UInt128) == x - BigInt(typemax(UInt128)) -@test x - typemax(Int128) == x - BigInt(typemax(Int128)) - -# * -x = BigFloat(6) -y = BigFloat(9) -@test x * y != BigFloat(42) -@test x * y == BigFloat(54) -@test x * typemax(UInt128) == x * BigInt(typemax(UInt128)) -@test x * typemax(Int128) == x * BigInt(typemax(Int128)) - -# / -x = BigFloat(9) -y = BigFloat(6) -@test x / y == BigFloat(9/6) -@test x / typemax(UInt128) == x / BigInt(typemax(UInt128)) -@test x / typemax(Int128) == x / BigInt(typemax(Int128)) - -# iterated arithmetic -a = BigFloat(12.25) -b = BigFloat(23.125) -c = BigFloat(-7) -d = BigFloat(-12.75) -f = BigFloat(2.0625) -g = BigFloat(0.03125) -@test +(a, b) == BigFloat(35.375) -@test +(a, b, c) == BigFloat(28.375) -@test +(a, b, c, d) == BigFloat(15.625) -@test +(a, b, c, d, f) == BigFloat(17.6875) -@test +(a, b, c, d, f, g) == BigFloat(17.71875) - -@test *(a, b) == parse(BigFloat,"2.8328125e+02") -@test *(a, b, c) == parse(BigFloat,"-1.98296875e+03") -@test *(a, b, c, d) == parse(BigFloat,"2.52828515625e+04") -@test *(a, b, c, d, f) == parse(BigFloat,"5.214588134765625e+04") -@test *(a, b, c, d, f, g) == parse(BigFloat,"1.6295587921142578125e+03") - -# < / > / <= / >= -x = BigFloat(12) -y = BigFloat(42) -z = BigFloat(30) -@test y > x -@test y >= x -@test y > z -@test y >= z -@test x < y -@test x <= y -@test z < y -@test z <= y -@test y - x >= z -@test y - x <= z -@test !(x >= z) -@test !(y <= z) - -# rounding modes -setprecision(4) do - # default mode is round to nearest - down, up = setrounding(BigFloat,RoundNearest) do - parse(BigFloat,"0.0938"), parse(BigFloat,"0.102") - end - setrounding(BigFloat,RoundDown) do - @test BigFloat(0.1) == down - @test BigFloat(0.1) != up - end - setrounding(BigFloat,RoundUp) do - @test BigFloat(0.1) != down - @test BigFloat(0.1) == up - end -end - -# ^ -x = BigFloat(12) -y = BigFloat(4) -@test x^y == BigFloat(20736) - -# ceil -x = BigFloat(12.042) -@test BigFloat(13) == ceil(x) - -# copysign -x = BigFloat(1) -y = BigFloat(-1) -@test copysign(x, y) == y -@test copysign(y, x) == x - -# isfinite / isinf -x = BigFloat(Inf) -y = BigFloat(1) -@test isinf(x) == true -@test isinf(y) == false -@test isfinite(x) == false -@test isinf(x) == true - -# isnan -x = BigFloat(NaN) -y = BigFloat(1) -@test isnan(x) == true -@test isnan(y) == false - -# convert to -@test convert(BigFloat, 1//2) == parse(BigFloat,"0.5") -@test typeof(convert(BigFloat, 1//2)) == BigFloat -@test convert(BigFloat, 0.5) == parse(BigFloat,"0.5") -@test typeof(convert(BigFloat, 0.5)) == BigFloat -@test convert(BigFloat, 40) == parse(BigFloat,"40") -@test typeof(convert(BigFloat, 40)) == BigFloat -@test convert(BigFloat, Float32(0.5)) == parse(BigFloat,"0.5") -@test typeof(convert(BigFloat, Float32(0.5))) == BigFloat -@test convert(BigFloat, parse(BigInt,"9223372036854775808")) == parse(BigFloat,"9223372036854775808") -@test typeof(convert(BigFloat, parse(BigInt,"9223372036854775808"))) == BigFloat -@test convert(AbstractFloat, parse(BigInt,"9223372036854775808")) == parse(BigFloat,"9223372036854775808") -@test typeof(convert(AbstractFloat, parse(BigInt,"9223372036854775808"))) == BigFloat - -# convert from -@test convert(Float64, BigFloat(0.5)) == 0.5 -@test convert(Float32, BigFloat(0.5)) == Float32(0.5) -@test convert(Float16, BigFloat(0.5)) == Float16(0.5) -@test convert(Bool, BigFloat(0.0)) == false -@test convert(Bool, BigFloat(1.0)) == true -@test_throws InexactError convert(Bool, BigFloat(0.1)) - -# exponent -x = BigFloat(0) -@test_throws DomainError exponent(x) -x = BigFloat(Inf) -@test_throws DomainError exponent(x) -x = BigFloat(15.674) -@test exponent(x) == exponent(15.674) - -# frexp -for i in [big(0.2), big(1.2), big(1220.0), big(23414.123)] - mantissa, ex = frexp(i) - @test i == mantissa * 2. ^ ex -end - -# significand -for i in [big(0.2), big(1.2), big(1220.0), big(23414.123)] - @test i == significand(i) * 2. ^ exponent(i) -end - -# nextfloat/prevfloat should be immutable -x = 12. -y = BigFloat(x) -@test x == y -nextfloat(y) -@test x == y -prevfloat(y) -@test x == y - -# sqrt DomainError -@test_throws DomainError sqrt(BigFloat(-1)) - -# precision -old_precision = precision(BigFloat) -x = BigFloat(0) -@test precision(x) == old_precision -setprecision(256) -x = BigFloat(0) -@test precision(x) == 256 -setprecision(old_precision) -z = setprecision(240) do - z = x + 20 - return z -end -@test float(z) == 20. -@test precision(z) == 240 -x = BigFloat(12) -@test precision(x) == old_precision -@test_throws DomainError setprecision(1) - -# isinteger -@test !isinteger(BigFloat(1.2)) -@test isinteger(BigFloat(12)) -@test isinteger(zero(BigFloat)) -@test isinteger(-zero(BigFloat)) -@test !isinteger(nextfloat(zero(BigFloat))) -@test !isinteger(prevfloat(zero(BigFloat))) -@test isinteger(maxintfloat(BigFloat)) -@test isinteger(-maxintfloat(BigFloat)) -@test !isinteger(BigFloat(Inf)) -@test !isinteger(-BigFloat(Inf)) -@test !isinteger(BigFloat(NaN)) - -# nextfloat / prevfloat -setprecision(53) do - x = BigFloat(12.12) - @test BigFloat(nextfloat(12.12)) == nextfloat(x) - @test BigFloat(prevfloat(12.12)) == prevfloat(x) -end -@test isnan(nextfloat(BigFloat(NaN))) -@test isnan(prevfloat(BigFloat(NaN))) - -# comparisons -x = BigFloat(1) -y = BigFloat(-1) -z = BigFloat(NaN) -ipl = BigFloat(Inf) -imi = BigFloat(-Inf) -@test x > y -@test x >= y -@test x >= x -@test y < x -@test y <= x -@test y <= y -@test x < ipl -@test x <= ipl -@test x > imi -@test x >= imi -@test imi == imi -@test ipl == ipl -@test imi < ipl -@test z != z -@test !(z == z) -@test !(z <= z) -@test !(z < z) -@test !(z >= z) -@test !(z > z) - -@test !isequal(BigFloat(0.0),BigFloat(-0.0)) -@test isequal(z, BigFloat(NaN)) - -# total ordering -@test isless(big(-0.0), big(0.0)) -@test isless(big(1.0), big(NaN)) - -# cmp -@test cmp(big(-0.0), big(0.0)) == 0 -@test cmp(big(0.0), big(-0.0)) == 0 -@test_throws DomainError cmp(big(1.0), big(NaN)) -@test_throws DomainError cmp(big(NaN), big(NaN)) -@test_throws DomainError cmp(big(NaN), big(1.0)) - -# signbit -@test signbit(BigFloat(-1.0)) == 1 -@test signbit(BigFloat(1.0)) == 0 -@test signbit(BigFloat(-0.0)) == 1 - -# modf -x = BigFloat(12) -y = BigFloat(0.5) -@test modf(x+y) == (y, x) -x = BigFloat(NaN) -@test map(isnan, modf(x)) == (true, true) -x = BigFloat(Inf) -y = modf(x) -@test (isnan(y[1]), isinf(y[2])) == (true, true) - -# rem -setprecision(53) do - x = BigFloat(2) - y = BigFloat(1.67) - @test rem(x,y) == rem(2, 1.67) - y = BigFloat(NaN) - @test isnan(rem(x,y)) - @test isnan(rem(y,x)) - y = BigFloat(Inf) - @test rem(x,y) == x - @test isnan(rem(y,x)) -end - -# min/max -x = BigFloat(4) -y = BigFloat(2) -@test max(x,y) == x -@test min(x,y) == y -y = BigFloat(NaN) -@test isnan(max(x,y)) -@test isnan(min(x,y)) -@test isnan(max(y,y)) -@test isnan(min(y,y)) - -# sum -x = BigFloat(1) -y = BigFloat(2) -z = BigFloat(3) -w = BigFloat(4) -@test sum([x,y,z,w]) == BigFloat(10) -big_array = ones(BigFloat, 100) -@test sum(big_array) == BigFloat(100) -@test sum(BigFloat[]) == BigFloat(0) - -# promotion -# the array converts everyone to the DEFAULT_PRECISION! -x = BigFloat(12) -y = setprecision(60) do - BigFloat(42) -end -@test [x,y] == [BigFloat(12), BigFloat(42)] - -# log / log2 / log10 -setprecision(53) do -x = BigFloat(42) - @test log(x) == log(42) - @test isinf(log(BigFloat(0))) - @test_throws DomainError log(BigFloat(-1)) - @test log2(x) == log2(42) - @test isinf(log2(BigFloat(0))) - @test_throws DomainError log2(BigFloat(-1)) - @test log10(x) == log10(42) - @test isinf(log10(BigFloat(0))) - @test_throws DomainError log10(BigFloat(-1)) -end - -# exp / exp2 / exp10 -setprecision(53) do - x = BigFloat(10) - @test exp(x) == exp(10) - @test exp2(x) == 1024 - @test exp10(x) == 10000000000 -end - -# convert to integer types -x = BigFloat(12.1) -y = BigFloat(42) -@test_throws InexactError convert(Int32, x) -@test_throws InexactError convert(Int64, x) -@test_throws InexactError convert(BigInt, x) -@test_throws InexactError convert(UInt32, x) -@test_throws InexactError convert(UInt32, x) -@test convert(Int32, y) == 42 -@test convert(Int64, y) == 42 -@test convert(BigInt, y) == 42 -@test convert(UInt32, y) == 42 -@test convert(UInt32, y) == 42 - -# round -x = BigFloat(42.42) -y = setprecision(256) do - parse(BigFloat,"9223372036854775809.2324") -end -z = parse(BigInt,"9223372036854775809") -@test round(Integer,x) == 42 -@test round(Integer,y) == z -@test typeof(round(UInt8, x)) == UInt8 && round(UInt8, x) == 0x2a -@test typeof(round(UInt16, x)) == UInt16 && round(UInt16, x) == 0x2a -@test typeof(round(UInt32, x)) == UInt32 && round(UInt32, x) == 0x2a -@test typeof(round(UInt64, x)) == UInt64 && round(UInt64, x) == 0x2a -@test typeof(round(Int64, x)) == Int64 && round(Int64, x) == 42 -@test typeof(round(Int, x)) == Int && round(Int, x) == 42 -@test typeof(round(UInt, x)) == UInt && round(UInt, x) == 0x2a - -# string representation -str = "1.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000012" -setprecision(406) do - @test string(nextfloat(BigFloat(1))) == str -end -setprecision(21) do - @test string(zero(BigFloat)) == "0.0000000" - @test string(parse(BigFloat, "0.1")) == "1.0000002e-01" - @test string(parse(BigFloat, "-9.9")) == "-9.9000015" -end -setprecision(40) do - @test string(zero(BigFloat)) == "0.0000000000000" - @test string(parse(BigFloat, "0.1")) == "1.0000000000002e-01" - @test string(parse(BigFloat, "-9.9")) == "-9.8999999999942" -end -setprecision(123) do - @test string(zero(BigFloat)) == "0.00000000000000000000000000000000000000" - @test string(parse(BigFloat, "0.1")) == "9.99999999999999999999999999999999999953e-02" - @test string(parse(BigFloat, "-9.9")) == "-9.8999999999999999999999999999999999997" -end - -# eps -x = eps(BigFloat) -@test BigFloat(1) + x == BigFloat(1) + prevfloat(x) -@test eps(BigFloat) == eps(BigFloat(1)) - -# realmin/realmax -x = realmin(BigFloat) -@test x > 0 -@test prevfloat(x) == 0 -x = realmax(BigFloat) -@test !isinf(x) -@test isinf(nextfloat(x)) - -# factorial -setprecision(256) do - x = BigFloat(42) - @test factorial(x) == factorial(BigInt(42)) - x = BigFloat(10) - @test factorial(x) == factorial(10) - @test_throws DomainError factorial(BigFloat(-1)) - @test_throws DomainError factorial(BigFloat(331.3)) -end - -# trigonometric functions -setprecision(53) do - for f in (:sin,:cos,:tan,:sec,:csc,:cot,:acos,:asin,:atan, - :cosh,:sinh,:tanh,:sech,:csch,:coth,:asinh), - j in (-1., -0.5, -0.25, .25, .5, 1.) - @eval begin - @test ($f)(BigFloat($j)) ≈ ($f)($j) - end - end - for f in (:acos,:asin,:acosh,:atanh), - j in (-2, -1.5) - @eval begin - @test_throws DomainError ($f)(BigFloat($j)) - end - end - for f in (:sin,:cos,:tan,:sec,:csc,:cot,:cosh,:sinh,:tanh, - :sech,:csch,:coth,:acosh,:asinh), - j in (1., 1.5, 1.9) - @eval begin - @test ($f)(BigFloat($j)) ≈ ($f)($j) - end - end - for j in (.25, .5) - @test atanh(BigFloat(j)) ≈ atanh(j) - end -end - -# hypot -@test hypot(BigFloat(3), BigFloat(4)) == 5 - -# atan2 -setprecision(53) do - @test atan2(12,2) == atan2(BigFloat(12), BigFloat(2)) -end - -# ldexp -setprecision(53) do - @test ldexp(BigFloat(24.5), 72) == ldexp(24.5, 72) - @test ldexp(BigFloat(24.5), Int16(72)) == ldexp(24.5, 72) - @test ldexp(BigFloat(24.5), -72) == ldexp(24.5, -72) - @test ldexp(BigFloat(24.5), Int16(-72)) == ldexp(24.5, -72) - @test ldexp(BigFloat(24.5), UInt(72)) == ldexp(24.5, 72) - @test ldexp(BigFloat(24.5), 0x48) == ldexp(24.5, 72) -end - -# ceil / floor / trunc -x = parse(BigFloat,"28273.7312487489135135135") -y = BigInt(28273) -z = BigInt(28274) -a = parse(BigFloat,"123456789012345678901234567890.2414") -b = parse(BigInt,"123456789012345678901234567890") -c = parse(BigInt,"123456789012345678901234567891") -@test ceil(x) == z -@test typeof(ceil(x)) == BigFloat -@test floor(x) == y -@test typeof(floor(x)) == BigFloat -@test trunc(x) == y -@test typeof(trunc(x)) == BigFloat - -@test ceil(Integer,x) == z -@test typeof(ceil(Integer,x)) == BigInt -@test floor(Integer,x) == y -@test typeof(floor(Integer,x)) == BigInt -@test trunc(Integer,x) == y -@test typeof(trunc(Integer,x)) == BigInt - -@test ceil(Int64, x) == Int64(z) -@test typeof(ceil(Int64, x)) == Int64 -@test floor(Int64, x) == Int64(y) -@test typeof(floor(Int64, x)) == Int64 -@test trunc(Int64, x) == Int64(y) -@test typeof(trunc(Int64, x)) == Int64 - -@test ceil(Int32, x) == Int32(z) -@test typeof(ceil(Int32, x)) == Int32 -@test floor(Int32, x) == Int32(y) -@test typeof(floor(Int32, x)) == Int32 -@test trunc(Int32, x) == Int32(y) -@test typeof(trunc(Int32, x)) == Int32 - -@test ceil(Int16, x) == Int16(z) -@test typeof(ceil(Int16, x)) == Int16 -@test floor(Int16, x) == Int16(y) -@test typeof(floor(Int16, x)) == Int16 -@test trunc(Int16, x) == Int16(y) -@test typeof(trunc(Int16, x)) == Int16 - -#@test ceil(Int8, x) == Int8(z) -#@test typeof(ceil(Int8, x)) == Int8 -#@test floor(Int8, x) == Int8(y) -#@test typeof(floor(Int8, x)) == Int8 -#@test trunc(Int8, x) == Int8(y) -#@test typeof(trunc(Int8, x)) == Int8 - -@test ceil(UInt64, x) == UInt64(z) -@test typeof(ceil(UInt64, x)) == UInt64 -@test floor(UInt64, x) == UInt64(y) -@test typeof(floor(UInt64, x)) == UInt64 -@test trunc(UInt64, x) == UInt64(y) -@test typeof(trunc(UInt64, x)) == UInt64 - -@test ceil(UInt32, x) == UInt32(z) -@test typeof(ceil(UInt32, x)) == UInt32 -@test floor(UInt32, x) == UInt32(y) -@test typeof(floor(UInt32, x)) == UInt32 -@test trunc(UInt32, x) == UInt32(y) -@test typeof(trunc(UInt32, x)) == UInt32 - -@test ceil(UInt16, x) == UInt16(z) -@test typeof(ceil(UInt16, x)) == UInt16 -@test floor(UInt16, x) == UInt16(y) -@test typeof(floor(UInt16, x)) == UInt16 -@test trunc(UInt16, x) == UInt16(y) -@test typeof(trunc(UInt16, x)) == UInt16 - -#@test ceil(UInt8, x) == UInt8(z) -#@test typeof(ceil(UInt8, x)) == UInt8 -#@test floor(UInt8, x) == UInt8(y) -#@test typeof(floor(UInt8, x)) == UInt8 -#@test trunc(UInt8, x) == UInt8(y) -#@test typeof(trunc(UInt8, x)) == UInt8 - -@test ceil(Integer,a) == c -@test typeof(ceil(Integer,a)) == BigInt -@test floor(Integer,a) == b -@test typeof(floor(Integer,a)) == BigInt -@test trunc(Integer,a) == b -@test typeof(trunc(Integer,a)) == BigInt - -@test ceil(Int128,a) == c -@test typeof(ceil(Int128,a)) == Int128 -@test floor(Int128,a) == b -@test typeof(floor(Int128,a)) == Int128 -@test trunc(Int128,a) == b -@test typeof(trunc(Int128,a)) == Int128 - -@test ceil(UInt128,a) == c -@test typeof(ceil(UInt128,a)) == UInt128 -@test floor(UInt128,a) == b -@test typeof(floor(UInt128,a)) == UInt128 -@test trunc(UInt128,a) == b -@test typeof(trunc(UInt128,a)) == UInt128 - - -# basic arithmetic -# Signed addition -a = parse(BigFloat,"123456789012345678901234567890") -b = parse(BigFloat,"123456789012345678901234567891") -@test a+Int8(1) == b -@test a+Int16(1) == b -@test a+Int32(1) == b -@test a+Int64(1) == b -@test Int8(1)+ a == b -@test Int16(1)+a == b -@test Int32(1)+a == b -@test Int64(1)+a == b -@test b+Int8(-1) == a -@test b+Int16(-1) == a -@test b+Int32(-1) == a -@test b+Int64(-1) == a -@test Int8(-1)+ b == a -@test Int16(-1)+b == a -@test Int32(-1)+b == a -@test Int64(-1)+b == a - -# Unsigned addition -@test a+true == b -@test a+UInt8(1) == b -@test a+UInt16(1) == b -@test a+UInt32(1) == b -@test a+UInt64(1) == b -@test true+a == b -@test UInt8(1)+ a == b -@test UInt16(1)+a == b -@test UInt32(1)+a == b -@test UInt64(1)+a == b - -# Float64 addition -@test a + 1.0f0 == b -@test 1.0f0 + a == b -@test a + 1.0 == b -@test 1.0 + a == b - -# BigInt addition -@test a + BigInt(1) == b -@test BigInt(1) + a == b - -# Signed subtraction -@test b-Int8(1) == a -@test b-Int16(1) == a -@test b-Int32(1) == a -@test b-Int64(1) == a -@test Int8(1)- b == -a -@test Int16(1)-b == -a -@test Int32(1)-b == -a -@test Int64(1)-b == -a -@test a-Int8(-1) == b -@test a-Int16(-1) == b -@test a-Int32(-1) == b -@test a-Int64(-1) == b -@test Int8(-1)- a == -b -@test Int16(-1)-a == -b -@test Int32(-1)-a == -b -@test Int64(-1)-a == -b - -# Unsigned subtraction -@test b-true == a -@test b-UInt8(1) == a -@test b-UInt16(1) == a -@test b-UInt32(1) == a -@test b-UInt64(1) == a -@test true-b == -a -@test UInt8(1)- b == -a -@test UInt16(1)-b == -a -@test UInt32(1)-b == -a -@test UInt64(1)-b == -a - -# Float64 subtraction -@test b - 1.0f0 == a -@test 1.0f0 - b == -a -@test b - 1.0 == a -@test 1.0 - b == -a - -# BigInt subtraction -@test b - BigInt(1) == a -@test BigInt(1) - b == -a - -# Signed multiplication -@test a*Int8(1) == a -@test a*Int16(1) == a -@test a*Int32(1) == a -@test a*Int64(1) == a -@test Int8(1)* a == a -@test Int16(1)*a == a -@test Int32(1)*a == a -@test Int64(1)*a == a -@test a*Int8(-1) == -a -@test a*Int16(-1) == -a -@test a*Int32(-1) == -a -@test a*Int64(-1) == -a -@test Int8(-1)* a == -a -@test Int16(-1)*a == -a -@test Int32(-1)*a == -a -@test Int64(-1)*a == -a - -# Unsigned multiplication -@test a*true == a -@test a*UInt8(1) == a -@test a*UInt16(1) == a -@test a*UInt32(1) == a -@test a*UInt64(1) == a -@test true*a == a -@test UInt8(1)* a == a -@test UInt16(1)*a == a -@test UInt32(1)*a == a -@test UInt64(1)*a == a - -# Float64 multiplication -@test a * 1.0f0 == a -@test 1.0f0 * a == a -@test a * 1.0 == a -@test 1.0 * a == a - -# BigInt multiplication -@test a * BigInt(1) == a -@test BigInt(1) * a == a - -# Signed division -c = parse(BigInt,"61728394506172839450617283945") -# d = 2^200 -d = parse(BigFloat,"1606938044258990275541962092341162602522202993782792835301376") -f = parse(BigFloat,"6.223015277861141707144064053780124240590252168721167133101116614789698834035383e-61") - -@test a/Int8(2) == c -@test a/Int16(2) == c -@test a/Int32(2) == c -@test a/Int64(2) == c -@test Int8(1)/ d == f -@test Int16(1)/d == f -@test Int32(1)/d == f -@test Int64(1)/d == f -@test a/Int8(-2) == -c -@test a/Int16(-2) == -c -@test a/Int32(-2) == -c -@test a/Int64(-2) == -c -@test Int8(-1)/ d == -f -@test Int16(-1)/d == -f -@test Int32(-1)/d == -f -@test Int64(-1)/d == -f - -# Unsigned division -@test a/true == a -@test a/UInt8(2) == c -@test a/UInt16(2) == c -@test a/UInt32(2) == c -@test a/UInt64(2) == c -@test true/d == f -@test UInt8(1)/ d == f -@test UInt16(1)/d == f -@test UInt32(1)/d == f -@test UInt64(1)/d == f - -# Float64 division -@test a / 2.0f0 == c -@test 1.0f0 / d == f -@test a / 2.0 == c -@test 1.0 / d == f - -# BigInt division -@test a / BigInt(2) == c - -# div -@test div(big"1.0",big"0.1") == 9 -@test div(1,big"0.1") == 9 -@test div(1.0,big"0.1") == 9 -@test div(big"1.0",0.1) == 9 -@test div(big"1",big"0.1") == 9 -@test div(big"1",0.1) == 9 - - -# old tests -tol = 1e-12 - -a = parse(BigFloat,"12.34567890121") -b = parse(BigFloat,"12.34567890122") - -@test a+1e-11 ≈ b atol=tol -@test !(b == a) -@test b > a -@test b >= a -@test !(b < a) -@test !(b <= a) - -c = parse(BigFloat,"24.69135780242") -@test typeof(a * 2) == BigFloat -@test a*2 ≈ c atol=tol -@test (c-a) ≈ a atol=tol - - -d = parse(BigFloat,"-24.69135780242") -@test typeof(d) == BigFloat -@test d+c ≈ 0 atol=tol - -@test (BigFloat(3)/BigFloat(2)) ≈ BigFloat(1.5) atol=tol - -@test typeof(BigFloat(typemax(Int8))) == BigFloat -@test typeof(BigFloat(typemax(Int16))) == BigFloat -@test typeof(BigFloat(typemax(Int32))) == BigFloat -@test typeof(BigFloat(typemax(Int64))) == BigFloat -@test typeof(BigFloat(typemax(Int128))) == BigFloat - -@test typeof(BigFloat(true)) == BigFloat -@test typeof(BigFloat(typemax(UInt8))) == BigFloat -@test typeof(BigFloat(typemax(UInt16))) == BigFloat -@test typeof(BigFloat(typemax(UInt32))) == BigFloat -@test typeof(BigFloat(typemax(UInt64))) == BigFloat -@test typeof(BigFloat(typemax(UInt128))) == BigFloat - -@test typeof(BigFloat(realmax(Float32))) == BigFloat -@test typeof(BigFloat(realmax(Float64))) == BigFloat - -@test typeof(BigFloat(BigInt(1))) == BigFloat -@test typeof(BigFloat(BigFloat(1))) == BigFloat - -@test typeof(BigFloat(1//1)) == BigFloat -@test typeof(BigFloat(one(Rational{BigInt}))) == BigFloat - -f = parse(BigFloat,"1234567890.123") -g = parse(BigFloat,"1234567891.123") - -tol = 1e-3 - -@test f+Int8(1) ≈ g atol=tol -@test f+Int16(1) ≈ g atol=tol -@test f+Int32(1) ≈ g atol=tol -@test f+Int64(1) ≈ g atol=tol -@test f+Int128(1) ≈ g atol=tol - -@test f+true ≈ g atol=tol -@test f+UInt8(1) ≈ g atol=tol -@test f+UInt16(1) ≈ g atol=tol -@test f+UInt32(1) ≈ g atol=tol -@test f+UInt64(1) ≈ g atol=tol -@test f+UInt128(1) ≈ g atol=tol - -@test f+BigInt(1) ≈ g atol=tol - -@test f+1f0 ≈ g atol=tol -@test f+1e0 ≈ g atol=tol - -@test f+BigFloat(1) ≈ g atol=tol - -@test f+(1//1) ≈ g atol=tol - -@test f+one(Rational{BigInt}) ≈ g atol=tol - -# issue #5963 -@test typemax(Int128) == convert(BigFloat, typemax(Int128)) -@test typemax(Int128) * big(1.0) == convert(BigFloat, typemax(Int128)) -@test typemax(UInt64) * big(1.0) == big(typemax(UInt64)) -@test typemax(UInt128) * big(1.0) == big(typemax(UInt128)) - -# issue #3399 -i1 = BigInt(10)^Int32(1000) -i2 = parse(BigInt,"10000000000000000000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000") -f = BigFloat(10)^Int32(1000) -@test i1 != i2 -@test i1 != f -@test i2 != f - -@test f > i1 -@test f > i2 - -i3 = trunc(Integer,f) -@test i3 == f -@test i3+1 > f -@test i3+1 >= f - -# issue #8318 -@test convert(Int64,big(500_000_000_000_000.)) == 500_000_000_000_000 - -# issue #9816 -# check exponent range is set to max possible -@test MPFR.get_emin() == MPFR.get_emin_min() -@test MPFR.get_emax() == MPFR.get_emax_max() - -# issue #10994: handle embedded NUL chars for string parsing -@test_throws ArgumentError parse(BigFloat, "1\0") - -# serialization (issue #12386) -let b = IOBuffer() - x = 2.1*big(pi) - serialize(b, x) - seekstart(b) - @test deserialize(b) == x -end - -@test isnan(sqrt(BigFloat(NaN))) - -# PR 17217 -- BigFloat constructors with given precision and rounding mode -# test constructors and `big` with additional precision and rounding mode: -for prec in (10, 100, 1000) - for val in ("3.1", pi, "-1.3", 3.1) - let - a = BigFloat(val) - b = BigFloat(val, prec) - c = BigFloat(val, RoundUp) - d = BigFloat(val, prec, RoundDown) - e = BigFloat(val, prec, RoundUp) - - @test precision(a) == precision(BigFloat) - @test precision(b) == prec - @test precision(c) == precision(BigFloat) - @test precision(d) == prec - @test precision(e) == prec - (val != 3.1) && @test e > d # rounding has no effect when constructing from Float64 - end - end -end - -setprecision(256) do - @test string(big(Inf)) == "BigFloat(Inf, 256)" - @test string(big(-Inf)) == "BigFloat(-Inf, 256)" - @test string(big(NaN)) == "BigFloat(NaN, 256)" -end diff --git a/julia-0.6.3/share/julia/test/netload/memtest.jl b/julia-0.6.3/share/julia/test/netload/memtest.jl deleted file mode 100644 index b024df4..0000000 --- a/julia-0.6.3/share/julia/test/netload/memtest.jl +++ /dev/null @@ -1,62 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -struct RUsage - ru_utime_sec::Clong # user CPU time used - ru_utime_usec::Clong # user CPU time used - ru_stime_sec::Clong # system CPU time used - ru_stime_usec::Clong # system CPU time used - ru_maxrss::Clong # maximum resident set size - ru_ixrss::Clong # integral shared memory size - ru_idrss::Clong # integral unshared data size - ru_isrss::Clong # integral unshared stack size - ru_minflt::Clong # page reclaims (soft page faults) - ru_majflt::Clong # page faults (hard page faults) - ru_nswap::Clong # swaps - ru_inblock::Clong # block input operations - ru_oublock::Clong # block output operations - ru_msgsnd::Clong # IPC messages sent - ru_msgrcv::Clong # IPC messages received - ru_nsignals::Clong # signals received - ru_nvcsw::Clong # voluntary context switches - ru_nivcsw::Clong # involuntary context switches -end - -function get_vmsize() - ru = Array{RUsage}(1) - ccall(:getrusage, Cint, (Cint, Ptr{Void}), 0, ru) - return ru[1].ru_maxrss -end - -function run_mtest(name, testf) - print("Testing $name...") - for i in 1:2 - print("priming process...") - testf() - end - vm1 = get_vmsize() - println("monitored run...") - testf() - vm2 = get_vmsize() - - diff = vm2 - vm1 - WARN = (diff > 1000) ? "<===================================== WARNING" : "" - println("Memory Test ($name) : VMSize difference : $diff KB $WARN") -end - - -function mtest_create_strings() - for i in 1:10^8 - string("$i") - end - gc() -end - -function mtest_remotecall_fetch() - for i in 1:10^5 - remotecall_fetch(myid, 1) - end - gc() -end - -run_mtest("create_strings", () -> mtest_create_strings()) -run_mtest("remotecall_fetch", () -> mtest_remotecall_fetch()) diff --git a/julia-0.6.3/share/julia/test/netload/nettest.jl b/julia-0.6.3/share/julia/test/netload/nettest.jl deleted file mode 100644 index 0f7394d..0000000 --- a/julia-0.6.3/share/julia/test/netload/nettest.jl +++ /dev/null @@ -1,185 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -# Run various networking tests checking to see how we perform under large loads -addprocs(1) - -function test_connect_disconnect(exp) - print("Testing 10^$exp connect/disconnects:\n") - - (port, server) = listenany(8000) - server_started = RemoteChannel() - server_exited = RemoteChannel() - client_exited = RemoteChannel() - - @async begin - clients_served = 0 - print("\t\t\t[SERVER] Started on port $(port), with PID $(getpid())\n") - put!(server_started, false) - while (clients_served < 10^exp) - close(accept(server)) - clients_served += 1 - end - put!(server_exited, true) - print("\t\t\t[SERVER] Finished serving $(clients_served) clients\n") - end - - # Wait for the server - @spawnat(2, begin - take!(server_started) - print("[CLIENT] Connecting repeatedly to port $(port)\n") - for i in 1:10^exp - close(connect("localhost", port)) - end - print("[CLIENT] Finished with 10^$exp connections\n") - put!(client_exited,true) - end) - - fetch(client_exited) - close(server) - fetch(server_exited) - print("OK\n") -end - -# Perform first test -test_connect_disconnect(5) - - -function test_send(exp) - (port, server) = listenany(8000) - - @assert exp > 4 - size = 10^exp - block = 10^(exp - 4) - - print("Testing open, send of 10^$exp bytes and closing:\n") - - server_started = RemoteChannel() - server_exited = RemoteChannel() - client_exited = RemoteChannel() - - @async begin - print("\t\t\t[SERVER] Started on port $(port)\n") - put!(server_started, false) - serv_sock = accept(server) - bread = 0 - while bread < size - serv_data = read(serv_sock, UInt8, block) - @assert length(serv_data) == block - bread += block - end - close(serv_sock) - print("\t\t\t[SERVER] Received 10^$(log10(bread))B of 10^$(exp)B\n") - put!(server_exited, bread) - end - - @spawnat(2, begin - # wait for the server - take!(server_started) - print("[CLIENT] Connecting to port $(port)\n") - cli_sock = connect("localhost", port) - data = fill!(zeros(UInt8, block), Int8(65)) - cli_bsent = 0 - while cli_bsent < size - write(cli_sock, data) - cli_bsent += block - end - close(cli_sock) - print("[CLIENT] Transmitted 10^$(log10(cli_bsent))B of 10^$(exp)B\n") - put!(client_exited, cli_bsent) - end) - - brcvd = take!(server_exited) - bsent = take!(client_exited) - close(server) - - if brcvd != bsent - print("\t[ERROR] Received bytes ($(brcvd)) != sent bytes ($(bsent))\n") - else - print("OK\n") - end -end - -# Run second test on a gigabyte of data -test_send(9) - - -# Utility function for test_bidirectional() that simultaneously transmits and -# receives 10^exp bits of data over s -@everywhere function xfer(s, exp) - @assert exp > 4 - xfer_size = 10^exp - xfer_block = 10^(exp - 4) - - bsent = 0 - bread = 0 - - @sync begin - # Create an asynchronous task that can modify bread properly - recv_task = @task begin - while bread < xfer_size - data = read(s, UInt8, xfer_block) - @assert length(data) == xfer_block - bread += xfer_block - end - end - Base.sync_add(recv_task) - Base.enq_work(recv_task) - - send_task = @task begin - # write in chunks of xfer_block - data = fill!(zeros(UInt8, xfer_block), Int8(65)) - while bsent < xfer_size - write(s, data) - bsent += xfer_block - end - end - Base.sync_add(send_task) - Base.enq_work(send_task) - end - - return (bsent, bread) -end - -function test_bidirectional(exp) - print("Testing 10^$exp bytes of concurrent bidirectional transfers:\n") - (port, server) = listenany(8000) - - # For both the server and the client, we will transfer/receive 10^exp bytes - server_started = RemoteChannel() - server_exited = RemoteChannel() - client_exited = RemoteChannel() - - @async begin - print("\t\t\t[SERVER] Started on port $(port)\n") - put!(server_started, true) - server_sock = accept(server) - (bsent, bread) = xfer(server_sock, exp) - close(server_sock) - print("\t\t\t[SERVER] Transmitted 10^$(log10(bsent))B and received 10^$(log10(bread))B\n") - put!(server_exited, (bsent, bread)) - end - - @spawnat(2, begin - # Wait for the server - take!(server_started) - print("[CLIENT] Connecting to port $(port)\n") - client_sock = connect("localhost", port) - (bsent, bread) = xfer(client_sock, exp) - close(client_sock) - print("[CLIENT] Transmitted 10^$(log10(bsent))B and received 10^$(log10(bread))B\n") - put!(client_exited, (bsent,bread)) - end) - - (serv_bsent, serv_bread) = take!(server_exited) - (cli_bsent, cli_bread) = take!(client_exited) - close(server) - - if serv_bsent != cli_bread || serv_bread != cli_bsent - print("\t[ERROR] Data was not faithfully transmitted!") - else - print("OK\n") - end -end - -# Test 1GB of bidirectional data -test_bidirectional(9) diff --git a/julia-0.6.3/share/julia/test/nullable.jl b/julia-0.6.3/share/julia/test/nullable.jl deleted file mode 100644 index 15bcb9e..0000000 --- a/julia-0.6.3/share/julia/test/nullable.jl +++ /dev/null @@ -1,529 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -# "is a null with type T", curried on 2nd argument -isnull_oftype(x::Nullable, T::Type) = eltype(x) == T && isnull(x) -isnull_oftype(T::Type) = x -> isnull_oftype(x, T) - -# return true if nullables (or arrays of nullables) have the same type, -# nullity, and value (if they are non-null) -istypeequal(x::Nullable, y::Nullable) = - typeof(x) == typeof(y) && isnull(filter(!, x .== y)) -istypeequal(x::AbstractArray, y::AbstractArray) = - length(x) == length(y) && all(xy -> istypeequal(xy...), zip(x, y)) - -types = [ - Bool, - Float16, - Float32, - Float64, - Int128, - Int16, - Int32, - Int64, - Int8, - UInt16, - UInt32, - UInt64, - UInt8, -] - -# Nullable{T}() = new(true) -for T in types - x = Nullable{T}() - @test x.hasvalue === false - @test isa(x.value, T) - @test eltype(Nullable{T}) === T - @test eltype(x) === T -end - -# Nullable{T}(value::T) = new(false, value) -for T in types - x = Nullable{T}(zero(T)) - @test x.hasvalue === true - @test isa(x.value, T) - @test x.value === zero(T) - @test eltype(x) === T - - x = Nullable{T}(one(T)) - @test x.hasvalue === true - @test isa(x.value, T) - @test x.value === one(T) - @test eltype(x) === T -end - -# Nullable{T}(value::T, hasvalue::Bool) = new(hasvalue, value) -for T in types - x = Nullable{T}(zero(T), true) - @test x.hasvalue === true - @test isa(x.value, T) - @test x.value === zero(T) - @test eltype(x) === T - - x = Nullable{T}(zero(T), false) - @test x.hasvalue === false - @test isa(x.value, T) - @test eltype(Nullable{T}) === T - @test eltype(x) === T -end - - -# struct NullException <: Exception -@test isa(NullException(), NullException) -@test_throws NullException throw(NullException()) - -# Nullable{T}(value::T) = Nullable{T}(value) -for T in types - v = zero(T) - x = Nullable(v) - @test x.hasvalue === true - @test isa(x.value, T) - @test x.value === v - - v = one(T) - x = Nullable(v) - @test x.hasvalue === true - @test isa(x.value, T) - @test x.value === v -end - -# show{T}(io::IO, x::Nullable{T}) -io1 = IOBuffer() -io2 = IOBuffer() -for (i, T) in enumerate(types) - x1 = Nullable{T}() - x2 = Nullable(zero(T)) - x3 = Nullable(one(T)) - show(io1, x1) - @test String(take!(io1)) == @sprintf("Nullable{%s}()", T) - show(io1, x2) - showcompact(io2, get(x2)) - @test String(take!(io1)) == @sprintf("Nullable{%s}(%s)", T, String(take!(io2))) - show(io1, x3) - showcompact(io2, get(x3)) - @test String(take!(io1)) == @sprintf("Nullable{%s}(%s)", T, String(take!(io2))) - - a1 = [x2] - show(IOContext(io1, :compact => false), a1) - show(IOContext(io2, :compact => false), x2) - @test String(take!(io1)) == - @sprintf("Nullable{%s}[%s]", string(T), String(take!(io2))) - - show(io1, a1) - show(IOContext(io2, :compact => true), x2) - @test String(take!(io1)) == - @sprintf("Nullable{%s}[%s]", string(T), String(take!(io2))) -end - -module NullableTestEnum -# For curmod_* -include("testenv.jl") -io = IOBuffer() -@enum TestEnum a b -show(io, Nullable(a)) -Base.Test.@test String(take!(io)) == "Nullable{$(curmod_prefix)TestEnum}(a)" -end - -# showcompact(io::IO, x::Nullable) -io1 = IOBuffer() -io2 = IOBuffer() -for (i, T) in enumerate(types) - x1 = Nullable{T}() - x2 = Nullable(zero(T)) - x3 = Nullable(one(T)) - showcompact(io1, x1) - @test String(take!(io1)) == "#NULL" - showcompact(io1, x2) - showcompact(io2, get(x2)) - @test String(take!(io1)) == String(take!(io2)) - showcompact(io1, x3) - showcompact(io2, get(x3)) - @test String(take!(io1)) == String(take!(io2)) - - a1 = [x2] - showcompact(io1, a1) - showcompact(io2, x2) - @test String(take!(io1)) == - @sprintf("Nullable{%s}[%s]", string(T), String(take!(io2))) -end - -# get(x::Nullable) -for T in types - x1 = Nullable{T}() - x2 = Nullable(zero(T)) - x3 = Nullable(one(T)) - - @test_throws NullException get(x1) - @test get(x2) === zero(T) - @test get(x3) === one(T) -end - -@test_throws NullException get(Nullable()) - -# get{S, T}(x::Nullable{S}, y::T) -for T in types - x0 = Nullable() - x1 = Nullable{T}() - x2 = Nullable(zero(T)) - x3 = Nullable(one(T)) - - @test get(x0, zero(T)) === zero(T) - @test get(x0, one(T)) === one(T) - @test get(x1, zero(T)) === zero(T) - @test get(x1, one(T)) === one(T) - @test get(x2, one(T)) === zero(T) - @test get(x3, zero(T)) === one(T) -end - -for T in types - # unsafe_get(x::Nullable) - x1 = Nullable{T}() - x2 = Nullable(zero(T)) - x3 = Nullable(one(T)) - a = rand(T) - x4 = Nullable(a) - - @test isa(unsafe_get(x1), T) - @test unsafe_get(x2) === zero(T) - @test unsafe_get(x3) === one(T) - @test unsafe_get(x4) === a - - # unsafe_get(x) - x2 = zero(T) - x3 = one(T) - x4 = rand(T) - - @test unsafe_get(x2) === zero(T) - @test unsafe_get(x3) === one(T) - @test unsafe_get(x4) === x4 -end - -@test_throws UndefRefError unsafe_get(Nullable()) -@test_throws UndefRefError unsafe_get(Nullable{String}()) -@test_throws UndefRefError unsafe_get(Nullable{Array}()) - -for T in types - # isnull(x::Nullable) - x1 = Nullable{T}() - x2 = Nullable(zero(T)) - x3 = Nullable(one(T)) - - @test isnull(x1) === true - @test isnull(x2) === false - @test isnull(x3) === false - - # isnull(x) - x1 = zero(T) - x2 = one(T) - x3 = rand(T) - - @test isnull(x1) === false - @test isnull(x2) === false - @test isnull(x3) === false -end - -@test isnull(Nullable()) - -# function =={S, T}(x::Nullable{S}, y::Nullable{T}) -for T in types - x0 = Nullable() - x1 = Nullable{T}() - x2 = Nullable{T}() - x3 = Nullable(zero(T)) - x4 = Nullable(one(T)) - - @test_throws NullException (x0 == x1) - @test_throws NullException (x0 == x2) - @test_throws NullException (x0 == x3) - @test_throws NullException (x0 == x4) - - @test_throws NullException (x1 == x1) - @test_throws NullException (x1 == x2) - @test_throws NullException (x1 == x3) - @test_throws NullException (x1 == x4) - - @test_throws NullException (x2 == x1) - @test_throws NullException (x2 == x2) - @test_throws NullException (x2 == x3) - @test_throws NullException (x2 == x4) - - @test_throws NullException (x3 == x1) - @test_throws NullException (x3 == x2) - @test_throws NullException (x3 == x3) - @test_throws NullException (x3 == x4) - - @test_throws NullException (x4 == x1) - @test_throws NullException (x4 == x2) - @test_throws NullException (x4 == x3) - @test_throws NullException (x4 == x4) -end - -# function hash(x::Nullable, h::UInt) -for T in types - x0 = Nullable() - x1 = Nullable{T}() - x2 = Nullable{T}() - x3 = Nullable(zero(T)) - x4 = Nullable(one(T)) - - @test isa(hash(x0), UInt) - @test isa(hash(x1), UInt) - @test isa(hash(x2), UInt) - @test isa(hash(x3), UInt) - @test isa(hash(x4), UInt) - - @test hash(x0) == hash(x2) - @test hash(x0) != hash(x3) - @test hash(x0) != hash(x4) - @test hash(x1) == hash(x2) - @test hash(x1) != hash(x3) - @test hash(x1) != hash(x4) - @test hash(x2) != hash(x3) - @test hash(x2) != hash(x4) - @test hash(x3) != hash(x4) -end - -mutable struct TestNType{T} - v::Nullable{T} -end - -for T in types - x1 = TestNType{T}(Nullable{T}()) - @test isnull(x1.v) - x1.v = one(T) - @test !isnull(x1.v) - @test get(x1.v, one(T)) === one(T) -end - -# Operators -TestTypes = [[T.parameters[1] for T in Base.uniontypes(Base.NullSafeTypes)]; - [BigInt, BigFloat, - Complex{Int}, Complex{Float64}, Complex{BigFloat}, - Rational{Int}, Rational{BigInt}]] -for S in TestTypes, T in TestTypes - u0 = zero(S) - u1 = one(S) - if S <: AbstractFloat - u2 = S(NaN) - elseif S <: Complex && S.parameters[1] <: AbstractFloat - u2 = S(NaN, NaN) - else - u2 = u1 - end - - v0 = zero(T) - v1 = one(T) - if T <: AbstractFloat - v2 = T(NaN) - elseif T <: Complex && T.parameters[1] <: AbstractFloat - v2 = T(NaN, NaN) - else - v2 = v1 - end - - for u in (u0, u1, u2), v in (v0, v1, v2) - # function isequal(x::Nullable, y::Nullable) - @test isequal(Nullable(u), Nullable(v)) === isequal(u, v) - @test isequal(Nullable(u), Nullable(u)) === true - @test isequal(Nullable(v), Nullable(v)) === true - - @test isequal(Nullable(u), Nullable(v, false)) === false - @test isequal(Nullable(u, false), Nullable(v)) === false - @test isequal(Nullable(u, false), Nullable(v, false)) === true - - @test isequal(Nullable(u), Nullable{T}()) === false - @test isequal(Nullable{S}(), Nullable(v)) === false - @test isequal(Nullable{S}(), Nullable{T}()) === true - - @test isequal(Nullable(u), Nullable()) === false - @test isequal(Nullable(), Nullable(v)) === false - @test isequal(Nullable{S}(), Nullable()) === true - @test isequal(Nullable(), Nullable{T}()) === true - @test isequal(Nullable(), Nullable()) === true - - # function isless(x::Nullable, y::Nullable) - if S <: Real && T <: Real - @test isless(Nullable(u), Nullable(v)) === isless(u, v) - @test isless(Nullable(u), Nullable(u)) === false - @test isless(Nullable(v), Nullable(v)) === false - - @test isless(Nullable(u), Nullable(v, false)) === true - @test isless(Nullable(u, false), Nullable(v)) === false - @test isless(Nullable(u, false), Nullable(v, false)) === false - - @test isless(Nullable(u), Nullable{T}()) === true - @test isless(Nullable{S}(), Nullable(v)) === false - @test isless(Nullable{S}(), Nullable{T}()) === false - - @test isless(Nullable(u), Nullable()) === true - @test isless(Nullable(), Nullable(v)) === false - @test isless(Nullable{S}(), Nullable()) === false - @test isless(Nullable(), Nullable{T}()) === false - @test isless(Nullable(), Nullable()) === false - end - end -end - -# issue #9462 -for T in types - @test isa(convert(Nullable{Number}, Nullable(one(T))), Nullable{Number}) - @test isa(convert(Nullable{Number}, one(T)), Nullable{Number}) - @test isa(convert(Nullable{T}, one(T)), Nullable{T}) - @test isa(convert(Nullable{Any}, Nullable(one(T))), Nullable{Any}) - @test isa(convert(Nullable{Any}, one(T)), Nullable{Any}) - - # one(T) is convertible to every type in types - # let's test that with Nullables - for S in types - @test isa(convert(Nullable{T}, one(S)), Nullable{T}) - end -end - -@test isnull(convert(Nullable, nothing)) -@test isnull(convert(Nullable{Int}, nothing)) -@test isa(convert(Nullable{Int}, nothing), Nullable{Int}) - -@test convert(Nullable, 1) === Nullable(1) -@test convert(Nullable, Nullable(1)) === Nullable(1) -@test isequal(convert(Nullable, "a"), Nullable("a")) -@test isequal(convert(Nullable, Nullable("a")), Nullable("a")) - -@test promote_type(Nullable{Int}, Int) === Nullable{Int} -@test promote_type(Nullable{Union{}}, Int) === Nullable{Int} -@test promote_type(Nullable{Float64}, Nullable{Int}) === Nullable{Float64} -@test promote_type(Nullable{Union{}}, Nullable{Int}) === Nullable{Int} -@test promote_type(Nullable{Date}, Nullable{DateTime}) === Nullable{DateTime} - -@test Base.promote_op(+, Nullable{Int}, Nullable{Int}) == Nullable{Int} -@test Base.promote_op(-, Nullable{Int}, Nullable{Int}) == Nullable{Int} -@test Base.promote_op(+, Nullable{Float64}, Nullable{Int}) == Nullable{Float64} -@test Base.promote_op(-, Nullable{Float64}, Nullable{Int}) == Nullable{Float64} -@test Base.promote_op(-, Nullable{DateTime}, Nullable{DateTime}) == Nullable{Base.Dates.Millisecond} - -# tests for istypeequal (which uses filter, broadcast) -@test istypeequal(Nullable(0), Nullable(0)) -@test !istypeequal(Nullable(0), Nullable(0.0)) -@test !istypeequal(Nullable(0), Nullable(1)) -@test !istypeequal(Nullable(0), Nullable(1.0)) -@test istypeequal([Nullable(0), Nullable(1)], [Nullable(0), Nullable(1)]) -@test istypeequal([Nullable(0), Nullable(1)], Any[Nullable(0), Nullable(1)]) -@test !istypeequal([Nullable(0), Nullable(1)], Any[Nullable(0.0), Nullable(1)]) -@test !istypeequal([Nullable(0), Nullable(1)], [Nullable(0), Nullable(2)]) -@test !istypeequal([Nullable(0), Nullable(1)], - [Nullable(0), Nullable(1), Nullable(2)]) - -# filter -for p in (_ -> true, _ -> false) - @test @inferred(filter(p, Nullable())) |> isnull_oftype(Union{}) - @test @inferred(filter(p, Nullable{Int}())) |> isnull_oftype(Int) -end -@test @inferred(filter(_ -> true, Nullable(85))) === Nullable(85) -@test @inferred(filter(_ -> false, Nullable(85))) |> isnull_oftype(Int) -@test @inferred(filter(x -> x > 0, Nullable(85))) === Nullable(85) -@test @inferred(filter(x -> x < 0, Nullable(85))) |> isnull_oftype(Int) -@test get(@inferred(filter(x -> length(x) > 2, Nullable("test")))) == "test" -@test @inferred(filter(x -> length(x) > 5, Nullable("test"))) |> - isnull_oftype(String) - -# map -sqr(x) = x^2 -@test @inferred(map(sqr, Nullable())) |> isnull_oftype(Union{}) -@test @inferred(map(sqr, Nullable{Int}())) |> isnull_oftype(Int) -@test @inferred(map(sqr, Nullable(2))) === Nullable(4) -@test @inferred(map(+, Nullable(0.0))) === Nullable(0.0) -@test @inferred(map(+, Nullable(3.0, false)))=== Nullable(3.0, false) -@test @inferred(map(-, Nullable(1.0))) === Nullable(-1.0) -@test @inferred(map(-, Nullable{Float64}())) |> isnull_oftype(Float64) -@test @inferred(map(sin, Nullable(1))) === Nullable(sin(1)) -@test @inferred(map(sin, Nullable{Int}())) |> isnull_oftype(Float64) - -# should not throw if function wouldn't be called -@test map(x -> x ? 0 : 0.0, Nullable()) |> isnull_oftype(Union{}) -@test map(x -> x ? 0 : 0.0, Nullable(true)) === Nullable(0) -@test map(x -> x ? 0 : 0.0, Nullable(false)) === Nullable(0.0) -@test map(x -> x ? 0 : 0.0, Nullable{Bool}()) |> isnull_oftype(Union{}) - -# broadcast and elementwise -@test sin.(Nullable(0.0)) === Nullable(0.0) -@test sin.(Nullable{Float64}()) |> isnull_oftype(Float64) -@test @inferred(broadcast(sin, Nullable(0.0))) === Nullable(0.0) -@test @inferred(broadcast(sin, Nullable{Float64}())) |> isnull_oftype(Float64) - -@test Nullable(8) .+ Nullable(10) === Nullable(18) -@test Nullable(8) .- Nullable(10) === Nullable(-2) -@test Nullable(8) .+ Nullable{Int}() |> isnull_oftype(Int) -@test Nullable{Int}() .- Nullable(10) |> isnull_oftype(Int) - -@test @inferred(broadcast(log, 10, Nullable(1.0))) === - Nullable(0.0) -@test @inferred(broadcast(log, 10, Nullable{Float64}())) |> - isnull_oftype(Float64) -@test @inferred(broadcast(log, Nullable(10), Nullable(1.0))) === - Nullable(0.0) -@test @inferred(broadcast(log, Nullable(10), Nullable{Float64}())) |> - isnull_oftype(Float64) - -@test Nullable(2) .^ Nullable(4) === Nullable(16) -@test Nullable(2) .^ Nullable{Int}() |> isnull_oftype(Int) - -# multi-arg broadcast -@test (Nullable(1) .+ Nullable(1) .+ Nullable(1) .+ Nullable(1) .+ Nullable(1) .+ - Nullable(1) === Nullable(6)) -@test (Nullable(1) .+ Nullable(1) .+ Nullable(1) .+ Nullable{Int}() .+ - Nullable(1) .+ Nullable(1) |> isnull_oftype(Int)) - -# these are not inferrable because there are too many arguments -us = map(Nullable, 1:20) -@test broadcast(max, us...) === Nullable(20) -@test isnull(broadcast(max, us..., Nullable{Int}())) - -# test all elementwise operations -# note that elementwise operations are the same as broadcast -for op in (+, -, *, /, \, //, ==, <, !=, <=, ÷, %, <<, >>, ^) - # op(1, 1) chosen because it works for all operations - res = op(1, 1) - @test @inferred(broadcast(op, Nullable(1), Nullable(1))) === - Nullable(res) - @test @inferred(broadcast(op, Nullable{Int}(), Nullable(1))) |> - isnull_oftype(typeof(res)) - @test @inferred(broadcast(op, Nullable(1), Nullable{Int}())) |> - isnull_oftype(typeof(res)) - @test @inferred(broadcast(op, Nullable{Int}(), Nullable{Int}())) |> - isnull_oftype(typeof(res)) - @test @inferred(broadcast(op, Nullable(1), 1)) === - Nullable(res) - @test @inferred(broadcast(op, 1, Nullable(1))) === - Nullable(res) -end - -# test reasonable results for Union{} -# the exact types of these is finnicky and depends on implementation details -# but is guaranteed to be at worst concrete and possibly Union{} on a good day -@test isnull(@inferred(Nullable() .+ Nullable())) -@test isnull(@inferred(Nullable() .+ 1)) -@test isnull(@inferred(Nullable() .+ Nullable(1))) - -# test that things don't pessimize because of non-homogenous types -@test Nullable(10.5) === - @inferred(broadcast(+, 1, 2, Nullable(3), Nullable(4.0), Nullable(1//2))) - -# test fast path taken -for op in (+, *, -) - for b1 in (false, true) - for b2 in (false, true) - @test Nullable{Int}(op(1, 2), b1 & b2) === - @inferred(broadcast(op, Nullable{Int}(1, b1), - Nullable{Int}(2, b2))) - end - end -end - -# issue #11675 -@test repr(Nullable()) == "Nullable{Union{}}()" - -# issue #19270 -let f19270{S,T}(x::S, y::T) = Base.promote_op(^, S, T) - @test f19270(Nullable(0.0f0), Nullable(BigInt(0))) == Nullable{Float32} -end - -# issue #21397 -@test Nullable(Tuple) === Nullable{DataType}(Tuple) diff --git a/julia-0.6.3/share/julia/test/numbers.jl b/julia-0.6.3/share/julia/test/numbers.jl deleted file mode 100644 index 7d57699..0000000 --- a/julia-0.6.3/share/julia/test/numbers.jl +++ /dev/null @@ -1,2977 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -const ≣ = isequal # convenient for comparing NaNs - -# basic booleans -@test true -@test !false -@test !!true -@test !!!false - -@test true == true -@test false == false -@test true != false -@test false != true - -@test ~true == false -@test ~false == true - -@test false & false == false -@test true & false == false -@test false & true == false -@test true & true == true - -@test false | false == false -@test true | false == true -@test false | true == true -@test true | true == true - -@test false ⊻ false == false -@test true ⊻ false == true -@test false ⊻ true == true -@test true ⊻ true == false -@test xor(false, false) == false -@test xor(true, false) == true -@test xor(false, true) == true -@test xor(true, true) == false - -# the bool operator -@test Bool(false) == false -@test Bool(true) == true -@test Bool(0) == false -@test Bool(1) == true -@test_throws InexactError Bool(-1) -@test Bool(0.0) == false -@test Bool(1.0) == true -@test_throws InexactError Bool(0.1) -@test_throws InexactError Bool(-1.0) -@test Bool(Complex(0,0)) == false -@test Bool(Complex(1,0)) == true -@test_throws InexactError Bool(Complex(0,1)) -@test Bool(0//1) == false -@test Bool(1//1) == true -@test_throws InexactError Bool(1//2) - -@test iszero(false) && !iszero(true) - -# basic arithmetic -@test 2 + 3 == 5 -@test 2.0 + 3.0 == 5. -@test 2 * 3 == 6 -@test 2.0 * 3 == 6 -@test 2.0 * 3.0 == 6. -@test min(1.0,1) == 1 - -# min, max and minmax -@test min(1) === 1 -@test max(1) === 1 -@test minmax(1) === (1, 1) -@test minmax(5, 3) == (3, 5) -@test minmax(3., 5.) == (3., 5.) -@test minmax(5., 3.) == (3., 5.) -@test minmax(3., NaN) ≣ (NaN, NaN) -@test minmax(NaN, 3) ≣ (NaN, NaN) -@test minmax(Inf, NaN) ≣ (NaN, NaN) -@test minmax(NaN, Inf) ≣ (NaN, NaN) -@test minmax(-Inf, NaN) ≣ (NaN, NaN) -@test minmax(NaN, -Inf) ≣ (NaN, NaN) -@test minmax(NaN, NaN) ≣ (NaN, NaN) -@test min(-0.0,0.0) === min(0.0,-0.0) -@test max(-0.0,0.0) === max(0.0,-0.0) -@test minmax(-0.0,0.0) === minmax(0.0,-0.0) -@test max(-3.2, 5.1) == max(5.1, -3.2) == 5.1 -@test min(-3.2, 5.1) == min(5.1, -3.2) == -3.2 -@test max(-3.2, Inf) == max(Inf, -3.2) == Inf -@test max(-3.2, NaN) ≣ max(NaN, -3.2) ≣ NaN -@test min(5.1, Inf) == min(Inf, 5.1) == 5.1 -@test min(5.1, -Inf) == min(-Inf, 5.1) == -Inf -@test min(5.1, NaN) ≣ min(NaN, 5.1) ≣ NaN -@test min(5.1, -NaN) ≣ min(-NaN, 5.1) ≣ NaN -@test minmax(-3.2, 5.1) == (min(-3.2, 5.1), max(-3.2, 5.1)) -@test minmax(-3.2, Inf) == (min(-3.2, Inf), max(-3.2, Inf)) -@test minmax(-3.2, NaN) ≣ (min(-3.2, NaN), max(-3.2, NaN)) -@test (max(Inf,NaN), max(-Inf,NaN), max(Inf,-NaN), max(-Inf,-NaN)) ≣ (NaN,NaN,NaN,NaN) -@test (max(NaN,Inf), max(NaN,-Inf), max(-NaN,Inf), max(-NaN,-Inf)) ≣ (NaN,NaN,NaN,NaN) -@test (min(Inf,NaN), min(-Inf,NaN), min(Inf,-NaN), min(-Inf,-NaN)) ≣ (NaN,NaN,NaN,NaN) -@test (min(NaN,Inf), min(NaN,-Inf), min(-NaN,Inf), min(-NaN,-Inf)) ≣ (NaN,NaN,NaN,NaN) -@test minmax(-Inf,NaN) ≣ (min(-Inf,NaN), max(-Inf,NaN)) - -# fma -let x = Int64(7)^7 - @test fma(x-1, x-2, x-3) == (x-1) * (x-2) + (x-3) - @test (fma((x-1)//(x-2), (x-3)//(x-4), (x-5)//(x-6)) == - (x-1)//(x-2) * (x-3)//(x-4) + (x-5)//(x-6)) -end - -let x = BigInt(7)^77 - @test fma(x-1, x-2, x-3) == (x-1) * (x-2) + (x-3) - @test (fma((x-1)//(x-2), (x-3)//(x-4), (x-5)//(x-6)) == - (x-1)//(x-2) * (x-3)//(x-4) + (x-5)//(x-6)) -end - -let eps = 1//BigInt(2)^30, one_eps = 1+eps, - eps64 = Float64(eps), one_eps64 = Float64(one_eps) - @test eps64 == Float64(eps) - @test rationalize(BigInt, eps64, tol=0) == eps - @test one_eps64 == Float64(one_eps) - @test rationalize(BigInt, one_eps64, tol=0) == one_eps - @test one_eps64 * one_eps64 - 1 != Float64(one_eps * one_eps - 1) - @test fma(one_eps64, one_eps64, -1) == Float64(one_eps * one_eps - 1) -end - -let eps = 1//BigInt(2)^15, one_eps = 1+eps, - eps32 = Float32(eps), one_eps32 = Float32(one_eps) - @test eps32 == Float32(eps) - @test rationalize(BigInt, eps32, tol=0) == eps - @test one_eps32 == Float32(one_eps) - @test rationalize(BigInt, one_eps32, tol=0) == one_eps - @test one_eps32 * one_eps32 - 1 != Float32(one_eps * one_eps - 1) - @test fma(one_eps32, one_eps32, -1) == Float32(one_eps * one_eps - 1) -end - -let eps = 1//BigInt(2)^7, one_eps = 1+eps, - eps16 = Float16(Float32(eps)), one_eps16 = Float16(Float32(one_eps)) - @test eps16 == Float16(Float32(eps)) - @test rationalize(BigInt, eps16, tol=0) == eps - @test one_eps16 == Float16(Float32(one_eps)) - @test rationalize(BigInt, one_eps16, tol=0) == one_eps - @test one_eps16 * one_eps16 - 1 != Float16(Float32(one_eps * one_eps - 1)) - @test (fma(one_eps16, one_eps16, -1) == - Float16(Float32(one_eps * one_eps - 1))) -end - -let eps = 1//BigInt(2)^200, one_eps = 1+eps, - eps256 = BigFloat(eps), one_eps256 = BigFloat(one_eps) - @test eps256 == BigFloat(eps) - @test rationalize(BigInt, eps256, tol=0) == eps - @test one_eps256 == BigFloat(one_eps) - @test rationalize(BigInt, one_eps256, tol=0) == one_eps - @test one_eps256 * one_eps256 - 1 != BigFloat(one_eps * one_eps - 1) - @test fma(one_eps256, one_eps256, -1) == BigFloat(one_eps * one_eps - 1) -end - -# muladd - -let eps = 1//BigInt(2)^30, one_eps = 1+eps, - eps64 = Float64(eps), one_eps64 = Float64(one_eps) - @test eps64 == Float64(eps) - @test one_eps64 == Float64(one_eps) - @test one_eps64 * one_eps64 - 1 != Float64(one_eps * one_eps - 1) - @test muladd(one_eps64, one_eps64, -1) ≈ Float64(one_eps * one_eps - 1) -end - -let eps = 1//BigInt(2)^15, one_eps = 1+eps, - eps32 = Float32(eps), one_eps32 = Float32(one_eps) - @test eps32 == Float32(eps) - @test one_eps32 == Float32(one_eps) - @test one_eps32 * one_eps32 - 1 != Float32(one_eps * one_eps - 1) - @test muladd(one_eps32, one_eps32, -1) ≈ Float32(one_eps * one_eps - 1) -end - -let eps = 1//BigInt(2)^7, one_eps = 1+eps, - eps16 = Float16(Float32(eps)), one_eps16 = Float16(Float32(one_eps)) - @test eps16 == Float16(Float32(eps)) - @test one_eps16 == Float16(Float32(one_eps)) - @test one_eps16 * one_eps16 - 1 != Float16(Float32(one_eps * one_eps - 1)) - @test muladd(one_eps16, one_eps16, -1) ≈ Float16(Float32(one_eps * one_eps - 1)) -end - -@test muladd(1,2,3) == 1*2+3 -@test muladd(big(1),2,3) == big(1)*2+3 -@test muladd(UInt(1),2,3) == UInt(1)*2+3 -@test muladd(1//1,2,3) == (1//1)*2+3 -@test muladd(big(1//1),2,3) == big(1//1)*2+3 -@test muladd(1.0,2,3) == 1.0*2+3 -@test muladd(big(1.0),2,3) == big(1.0)*2+3 - -# lexing typemin(Int64) -@test (-9223372036854775808)^1 == -9223372036854775808 -@test [1 -1 -9223372036854775808] == [1 -1 typemin(Int64)] - -# large integer literals -@test isa(-170141183460469231731687303715884105729,BigInt) -@test isa(-170141183460469231731687303715884105728,Int128) -@test isa(-9223372036854775809,Int128) -@test isa(-9223372036854775808,Int64) -@test isa(9223372036854775807,Int64) -@test isa(9223372036854775808,Int128) -@test isa(170141183460469231731687303715884105727,Int128) -@test isa(170141183460469231731687303715884105728,BigInt) - -@test isa(0170141183460469231731687303715884105728,BigInt) - -# exponentiating with a negative base -@test -3^2 == -9 -@test -9223372036854775808^2 == -(9223372036854775808^2) -@test -10000000000000000000^2 == -(10000000000000000000^2) -@test -170141183460469231731687303715884105728^2 == - -(170141183460469231731687303715884105728^2) - -# numeric literal coefficients -let x = 10 - @test 2x == 20 - @test 9223372036854775808x == 92233720368547758080 - @test 170141183460469231731687303715884105728x == - 1701411834604692317316873037158841057280 -end - -@test 2(10) == 20 -@test 9223372036854775808(10) == 92233720368547758080 -@test 170141183460469231731687303715884105728(10) == - 1701411834604692317316873037158841057280 - -# definition and printing of extreme integers -@test bin(typemin(UInt8)) == "0" -@test bin(typemax(UInt8)) == "1"^8 -@test oct(typemin(UInt8)) == "0" -@test oct(typemax(UInt8)) == "377" -@test dec(typemin(UInt8)) == "0" -@test dec(typemax(UInt8)) == "255" -@test hex(typemin(UInt8)) == "0" -@test hex(typemax(UInt8)) == "ff" -@test repr(typemin(UInt8)) == "0x00" -@test string(typemin(UInt8)) == "0" -@test repr(typemax(UInt8)) == "0xff" -@test string(typemax(UInt8)) == "255" -@test base(3,typemin(UInt8)) == "0" -@test base(3,typemax(UInt8)) == "100110" -@test base(12,typemin(UInt8)) == "0" -@test base(12,typemax(UInt8)) == "193" - -@test bin(typemin(UInt16)) == "0" -@test bin(typemax(UInt16)) == "1"^16 -@test oct(typemin(UInt16)) == "0" -@test oct(typemax(UInt16)) == "177777" -@test dec(typemin(UInt16)) == "0" -@test dec(typemax(UInt16)) == "65535" -@test hex(typemin(UInt16)) == "0" -@test hex(typemax(UInt16)) == "ffff" -@test repr(typemin(UInt16)) == "0x0000" -@test string(typemin(UInt16)) == "0" -@test repr(typemax(UInt16)) == "0xffff" -@test string(typemax(UInt16)) == "65535" -@test base(3,typemin(UInt16)) == "0" -@test base(3,typemax(UInt16)) == "10022220020" -@test base(12,typemin(UInt16)) == "0" -@test base(12,typemax(UInt16)) == "31b13" - -@test bin(typemin(UInt32)) == "0" -@test bin(typemax(UInt32)) == "1"^32 -@test oct(typemin(UInt32)) == "0" -@test oct(typemax(UInt32)) == "37777777777" -@test dec(typemin(UInt32)) == "0" -@test dec(typemax(UInt32)) == "4294967295" -@test hex(typemin(UInt32)) == "0" -@test hex(typemax(UInt32)) == "ffffffff" -@test repr(typemin(UInt32)) == "0x00000000" -@test string(typemin(UInt32)) == "0" -@test repr(typemax(UInt32)) == "0xffffffff" -@test string(typemax(UInt32)) == "4294967295" -@test base(3,typemin(UInt32)) == "0" -@test base(3,typemax(UInt32)) == "102002022201221111210" -@test base(12,typemin(UInt32)) == "0" -@test base(12,typemax(UInt32)) == "9ba461593" - -@test bin(typemin(UInt64)) == "0" -@test bin(typemax(UInt64)) == "1"^64 -@test oct(typemin(UInt64)) == "0" -@test oct(typemax(UInt64)) == "1777777777777777777777" -@test dec(typemin(UInt64)) == "0" -@test dec(typemax(UInt64)) == "18446744073709551615" -@test hex(typemin(UInt64)) == "0" -@test hex(typemax(UInt64)) == "ffffffffffffffff" -@test repr(typemin(UInt64)) == "0x0000000000000000" -@test string(typemin(UInt64)) == "0" -@test repr(typemax(UInt64)) == "0xffffffffffffffff" -@test string(typemax(UInt64)) == "18446744073709551615" -@test base(3,typemin(UInt64)) == "0" -@test base(3,typemax(UInt64)) == "11112220022122120101211020120210210211220" -@test base(12,typemin(UInt64)) == "0" -@test base(12,typemax(UInt64)) == "839365134a2a240713" - -@test bin(typemin(UInt128)) == "0" -@test bin(typemax(UInt128)) == "1"^128 -@test oct(typemin(UInt128)) == "0" -@test oct(typemax(UInt128)) == "3777777777777777777777777777777777777777777" -@test hex(typemin(UInt128)) == "0" -@test hex(typemax(UInt128)) == "ffffffffffffffffffffffffffffffff" -@test repr(typemin(UInt128)) == "0x00000000000000000000000000000000" -@test string(typemin(UInt128)) == "0" -@test repr(typemax(UInt128)) == "0xffffffffffffffffffffffffffffffff" -@test string(typemax(UInt128)) == "340282366920938463463374607431768211455" - -@test dec(typemin(UInt128)) == "0" -@test dec(typemax(UInt128)) == "340282366920938463463374607431768211455" -@test base(3,typemin(UInt128)) == "0" -@test base(3,typemax(UInt128)) == - "202201102121002021012000211012011021221022212021111001022110211020010021100121010" -@test base(12,typemin(UInt128)) == "0" -@test base(12,typemax(UInt128)) == "5916b64b41143526a777873841863a6a6993" - -@test bin(typemin(Int8)) == "-1"*"0"^7 -@test bin(typemax(Int8)) == "1"^7 -@test oct(typemin(Int8)) == "-200" -@test oct(typemax(Int8)) == "177" -@test dec(typemin(Int8)) == "-128" -@test dec(typemax(Int8)) == "127" -@test hex(typemin(Int8)) == "-80" -@test hex(typemax(Int8)) == "7f" -@test string(typemin(Int8)) == "-128" -@test string(typemax(Int8)) == "127" -@test base(3,typemin(Int8)) == "-11202" -@test base(3,typemax(Int8)) == "11201" -@test base(12,typemin(Int8)) == "-a8" -@test base(12,typemax(Int8)) == "a7" - -@test bin(typemin(Int16)) == "-1"*"0"^15 -@test bin(typemax(Int16)) == "1"^15 -@test oct(typemin(Int16)) == "-100000" -@test oct(typemax(Int16)) == "77777" -@test dec(typemin(Int16)) == "-32768" -@test dec(typemax(Int16)) == "32767" -@test hex(typemin(Int16)) == "-8000" -@test hex(typemax(Int16)) == "7fff" -@test string(typemin(Int16)) == "-32768" -@test string(typemax(Int16)) == "32767" -@test base(3,typemin(Int16)) == "-1122221122" -@test base(3,typemax(Int16)) == "1122221121" -@test base(12,typemin(Int16)) == "-16b68" -@test base(12,typemax(Int16)) == "16b67" - -@test bin(typemin(Int32)) == "-1"*"0"^31 -@test bin(typemax(Int32)) == "1"^31 -@test oct(typemin(Int32)) == "-20000000000" -@test oct(typemax(Int32)) == "17777777777" -@test dec(typemin(Int32)) == "-2147483648" -@test dec(typemax(Int32)) == "2147483647" -@test hex(typemin(Int32)) == "-80000000" -@test hex(typemax(Int32)) == "7fffffff" -@test string(typemin(Int32)) == "-2147483648" -@test string(typemax(Int32)) == "2147483647" -@test base(3,typemin(Int32)) == "-12112122212110202102" -@test base(3,typemax(Int32)) == "12112122212110202101" -@test base(12,typemin(Int32)) == "-4bb2308a8" -@test base(12,typemax(Int32)) == "4bb2308a7" - -@test bin(typemin(Int64)) == "-1"*"0"^63 -@test bin(typemax(Int64)) == "1"^63 -@test oct(typemin(Int64)) == "-1000000000000000000000" -@test oct(typemax(Int64)) == "777777777777777777777" -@test dec(typemin(Int64)) == "-9223372036854775808" -@test dec(typemax(Int64)) == "9223372036854775807" -@test hex(typemin(Int64)) == "-8000000000000000" -@test hex(typemax(Int64)) == "7fffffffffffffff" -@test string(typemin(Int64)) == "-9223372036854775808" -@test string(typemax(Int64)) == "9223372036854775807" -@test base(3,typemin(Int64)) == "-2021110011022210012102010021220101220222" -@test base(3,typemax(Int64)) == "2021110011022210012102010021220101220221" -@test base(12,typemin(Int64)) == "-41a792678515120368" -@test base(12,typemax(Int64)) == "41a792678515120367" - -@test bin(typemin(Int128)) == "-1"*"0"^127 -@test bin(typemax(Int128)) == "1"^127 -@test oct(typemin(Int128)) == "-2000000000000000000000000000000000000000000" -@test oct(typemax(Int128)) == "1777777777777777777777777777777777777777777" -@test hex(typemin(Int128)) == "-80000000000000000000000000000000" -@test hex(typemax(Int128)) == "7fffffffffffffffffffffffffffffff" - -@test dec(typemin(Int128)) == "-170141183460469231731687303715884105728" -@test dec(typemax(Int128)) == "170141183460469231731687303715884105727" -@test string(typemin(Int128)) == "-170141183460469231731687303715884105728" -@test string(typemax(Int128)) == "170141183460469231731687303715884105727" -@test base(3,typemin(Int128)) == - "-101100201022001010121000102002120122110122221010202000122201220121120010200022002" -@test base(3,typemax(Int128)) == - "101100201022001010121000102002120122110122221010202000122201220121120010200022001" -@test base(12,typemin(Int128)) == "-2a695925806818735399a37a20a31b3534a8" -@test base(12,typemax(Int128)) == "2a695925806818735399a37a20a31b3534a7" - -@test hex2num("3ff0000000000000") == 1. -@test hex2num("bff0000000000000") == -1. -@test hex2num("4000000000000000") == 2. -@test hex2num("7ff0000000000000") == Inf -@test hex2num("fff0000000000000") == -Inf -@test isnan(hex2num("7ff8000000000000")) -@test isnan(hex2num("fff8000000000000")) -@test hex2num("3f800000") == 1.0f0 -@test hex2num("bf800000") == -1.0f0 -@test hex2num("7f800000") == Inf32 -@test hex2num("ff800000") == -Inf32 -@test isnan(hex2num("7fc00000")) -@test isnan(hex2num("ffc00000")) - -# floating-point printing -@test repr(1.0) == "1.0" -@test repr(-1.0) == "-1.0" -@test repr(0.0) == "0.0" -@test repr(-0.0) == "-0.0" -@test repr(0.1) == "0.1" -@test repr(0.2) == "0.2" -@test repr(0.3) == "0.3" -@test repr(0.1+0.2) != "0.3" -@test repr(Inf) == "Inf" -@test repr(-Inf) == "-Inf" -@test repr(NaN) == "NaN" -@test repr(-NaN) == "NaN" -@test repr(Float64(pi)) == "3.141592653589793" -# issue 6608 -@test sprint(showcompact, 666666.6) == "6.66667e5" -@test sprint(showcompact, 666666.049) == "666666.0" -@test sprint(showcompact, 666665.951) == "666666.0" -@test sprint(showcompact, 66.66666) == "66.6667" -@test sprint(showcompact, -666666.6) == "-6.66667e5" -@test sprint(showcompact, -666666.049) == "-666666.0" -@test sprint(showcompact, -666665.951) == "-666666.0" -@test sprint(showcompact, -66.66666) == "-66.6667" - -@test repr(1.0f0) == "1.0f0" -@test repr(-1.0f0) == "-1.0f0" -@test repr(0.0f0) == "0.0f0" -@test repr(-0.0f0) == "-0.0f0" -@test repr(0.1f0) == "0.1f0" -@test repr(0.2f0) == "0.2f0" -@test repr(0.3f0) == "0.3f0" -@test repr(0.1f0+0.2f0) == "0.3f0" -@test repr(Inf32) == "Inf32" -@test repr(-Inf32) == "-Inf32" -@test repr(NaN32) == "NaN32" -@test repr(-NaN32) == "NaN32" -@test repr(Float32(pi)) == "3.1415927f0" - -# signs -@test sign(1) == 1 -@test sign(-1) == -1 -@test sign(0) == 0 -@test sign(1.0) == 1 -@test sign(-1.0) == -1 -@test sign(0.0) == 0 -@test sign(-0.0) == 0 -@test sign( 1.0/0.0) == 1 -@test sign(-1.0/0.0) == -1 -@test sign(Inf) == 1 -@test sign(-Inf) == -1 -@test isequal(sign(NaN), NaN) -@test isequal(sign(-NaN), NaN) -@test sign(2//3) == 1 -@test sign(-2//3) == -1 -@test sign(0//1) == 0 -@test sign(-0//1) == 0 -@test sign(1//0) == 1 -@test sign(-1//0) == -1 -@test isa(sign(2//3), Rational{Int}) -@test isa(2//3 + 2//3im, Complex{Rational{Int}}) -@test isa(sign(2//3 + 2//3im), Complex{Float64}) -@test sign(one(UInt)) == 1 -@test sign(zero(UInt)) == 0 - -@test signbit(1) == 0 -@test signbit(0) == 0 -@test signbit(-1) == 1 -@test signbit(1.0) == 0 -@test signbit(0.0) == 0 -@test signbit(-0.0) == 1 -@test signbit(-1.0) == 1 -@test signbit(1.0/0.0) == 0 -@test signbit(-1.0/0.0) == 1 -@test signbit(Inf) == 0 -@test signbit(-Inf) == 1 -@test signbit(NaN) == 0 -@test signbit(-NaN) == 1 -@test signbit(2//3) == 0 -@test signbit(-2//3) == 1 -@test signbit(0//1) == 0 -@test signbit(-0//1) == 0 -@test signbit(1//0) == 0 -@test signbit(-1//0) == 1 - -@test copysign(big(1.0),big(-2.0)) == big(-1.0) - -#copysign -@test copysign(-1,1) == 1 -@test copysign(1,-1) == -1 - -@test copysign(-1,1.0) == 1 -@test copysign(1,-1.0) == -1 - -@test copysign(-1,1//2) == 1 -@test copysign(1,-1//2) == -1 - -@test copysign(1.0,-1) == -1.0 -@test copysign(-1.0,1) == 1.0 - -@test copysign(1.0,-1.0) == -1.0 -@test copysign(-1.0,1.0) == 1.0 - -@test copysign(1.0,-1//2) == -1.0 -@test copysign(-1.0,1//2) == 1.0 - -@test copysign(1//2,-1) == -1//2 -@test copysign(-1//2,1) == 1//2 - -@test copysign(1//2,-1//2) == -1//2 -@test copysign(-1//2,1//2) == 1//2 - -@test copysign(1//2,-1.0) == -1//2 -@test copysign(-1//2,1.0) == 1//2 - -# verify type stability with integer (x is negative) -@test eltype(copysign(-1,1)) <: Integer -@test eltype(copysign(-1,BigInt(1))) <: Integer -@test eltype(copysign(-1,1.0)) <: Integer -@test eltype(copysign(-1,1//2)) <: Integer -@test eltype(copysign(-BigInt(1),1)) <: Integer -@test eltype(copysign(-BigInt(1),1.0)) <: Integer -@test eltype(copysign(-BigInt(1),1//2)) <: Integer -@test eltype(copysign(-BigInt(1),BigInt(1))) <: Integer -@test eltype(copysign(-1,-1)) <: Integer -@test eltype(copysign(-1,-BigInt(1))) <: Integer -@test eltype(copysign(-1,-1.0)) <: Integer -@test eltype(copysign(-1,-1//2)) <: Integer -@test eltype(copysign(-BigInt(1),-1)) <: Integer -@test eltype(copysign(-BigInt(1),-1.0)) <: Integer -@test eltype(copysign(-BigInt(1),-1//2)) <: Integer -@test eltype(copysign(-BigInt(1),-BigInt(1))) <: Integer - -# verify type stability with integer (x is positive) -@test eltype(copysign(1,1)) <: Integer -@test eltype(copysign(1,BigInt(1))) <: Integer -@test eltype(copysign(1,1.0)) <: Integer -@test eltype(copysign(1,1//2)) <: Integer -@test eltype(copysign(BigInt(1),1)) <: Integer -@test eltype(copysign(BigInt(1),1.0)) <: Integer -@test eltype(copysign(BigInt(1),1//2)) <: Integer -@test eltype(copysign(BigInt(1),BigInt(1))) <: Integer -@test eltype(copysign(1,-1)) <: Integer -@test eltype(copysign(1,-BigInt(1))) <: Integer -@test eltype(copysign(1,-1.0)) <: Integer -@test eltype(copysign(1,-1//2)) <: Integer -@test eltype(copysign(BigInt(1),-1)) <: Integer -@test eltype(copysign(BigInt(1),-1.0)) <: Integer -@test eltype(copysign(BigInt(1),-1//2)) <: Integer -@test eltype(copysign(BigInt(1),-BigInt(1))) <: Integer - -# verify type stability with real (x is negative) -@test eltype(copysign(-1.0,1)) <: Real -@test eltype(copysign(-1.0,BigInt(1))) <: Real -@test eltype(copysign(-1.0,1.0)) <: Real -@test eltype(copysign(-1.0,1//2)) <: Real -@test eltype(copysign(-1.0,-1)) <: Real -@test eltype(copysign(-1.0,-BigInt(1))) <: Real -@test eltype(copysign(-1.0,-1.0)) <: Real -@test eltype(copysign(-1.0,-1//2)) <: Real - -# Verify type stability with real (x is positive) -@test eltype(copysign(1.0,1)) <: Real -@test eltype(copysign(1.0,BigInt(1))) <: Real -@test eltype(copysign(1.0,1.0)) <: Real -@test eltype(copysign(1.0,1//2)) <: Real -@test eltype(copysign(1.0,-1)) <: Real -@test eltype(copysign(1.0,-BigInt(1))) <: Real -@test eltype(copysign(1.0,-1.0)) <: Real -@test eltype(copysign(1.0,-1//2)) <: Real - -# Verify type stability with rational (x is negative) -@test eltype(copysign(-1//2,1)) <: Rational -@test eltype(copysign(-1//2,BigInt(1))) <: Rational -@test eltype(copysign(-1//2,1.0)) <: Rational -@test eltype(copysign(-1//2,1//2)) <: Rational -@test eltype(copysign(-1//2,-1)) <: Rational -@test eltype(copysign(-1//2,-BigInt(1))) <: Rational -@test eltype(copysign(-1//2,-1.0)) <: Rational -@test eltype(copysign(-1//2,-1//2)) <: Rational - -# Verify type stability with rational (x is positive) -@test eltype(copysign(-1//2,1)) <: Rational -@test eltype(copysign(-1//2,BigInt(1))) <: Rational -@test eltype(copysign(-1//2,1.0)) <: Rational -@test eltype(copysign(-1//2,1//2)) <: Rational -@test eltype(copysign(-1//2,-1)) <: Rational -@test eltype(copysign(-1//2,-BigInt(1))) <: Rational -@test eltype(copysign(-1//2,-1.0)) <: Rational -@test eltype(copysign(-1//2,-1//2)) <: Rational - -# test x = NaN -@test isnan(copysign(0/0,1)) -@test isnan(copysign(0/0,-1)) - -# test x = Inf -@test isinf(copysign(1/0,1)) -@test isinf(copysign(1/0,-1)) - -@test isnan(1) == false -@test isnan(1.0) == false -@test isnan(-1.0) == false -@test isnan(Inf) == false -@test isnan(-Inf) == false -@test isnan(NaN) == true -@test isnan(1//2) == false -@test isnan(-2//3) == false -@test isnan(5//0) == false -@test isnan(-3//0) == false - -@test isinf(1) == false -@test isinf(1.0) == false -@test isinf(-1.0) == false -@test isinf(Inf) == true -@test isinf(-Inf) == true -@test isinf(NaN) == false -@test isinf(1//2) == false -@test isinf(-2//3) == false -@test isinf(5//0) == true -@test isinf(-3//0) == true - -@test isfinite(1) == true -@test isfinite(1.0) == true -@test isfinite(-1.0) == true -@test isfinite(Inf) == false -@test isfinite(-Inf) == false -@test isfinite(NaN) == false -@test isfinite(1//2) == true -@test isfinite(-2//3) == true -@test isfinite(5//0) == false -@test isfinite(-3//0) == false -@test isfinite(pi) == true - -@test isequal(-Inf,-Inf) -@test isequal(-1.0,-1.0) -@test isequal(-0.0,-0.0) -@test isequal(+0.0,+0.0) -@test isequal(+1.0,+1.0) -@test isequal(+Inf,+Inf) -@test isequal(-NaN,-NaN) -@test isequal(-NaN,+NaN) -@test isequal(+NaN,-NaN) -@test isequal(+NaN,+NaN) - -@test !isequal(-Inf,+Inf) -@test !isequal(-1.0,+1.0) -@test !isequal(-0.0,+0.0) -@test !isequal(+0.0,-0.0) -@test !isequal(+1.0,-1.0) -@test !isequal(+Inf,-Inf) - -@test isequal(-0.0f0,-0.0) -@test isequal( 0.0f0, 0.0) -@test !isequal(-0.0f0, 0.0) -@test !isequal(0.0f0 ,-0.0) - -@test !isless(-Inf,-Inf) -@test isless(-Inf,-1.0) -@test isless(-Inf,-0.0) -@test isless(-Inf,+0.0) -@test isless(-Inf,+1.0) -@test isless(-Inf,+Inf) -@test isless(-Inf,-NaN) -@test isless(-Inf,+NaN) - -@test !isless(-1.0,-Inf) -@test !isless(-1.0,-1.0) -@test isless(-1.0,-0.0) -@test isless(-1.0,+0.0) -@test isless(-1.0,+1.0) -@test isless(-1.0,+Inf) -@test isless(-1.0,-NaN) -@test isless(-1.0,+NaN) - -@test !isless(-0.0,-Inf) -@test !isless(-0.0,-1.0) -@test !isless(-0.0,-0.0) -@test isless(-0.0,+0.0) -@test isless(-0.0,+1.0) -@test isless(-0.0,+Inf) -@test isless(-0.0,-NaN) -@test isless(-0.0,+NaN) - -@test !isless(+0.0,-Inf) -@test !isless(+0.0,-1.0) -@test !isless(+0.0,-0.0) -@test !isless(+0.0,+0.0) -@test isless(+0.0,+1.0) -@test isless(+0.0,+Inf) -@test isless(+0.0,-NaN) -@test isless(+0.0,+NaN) - -@test !isless(+1.0,-Inf) -@test !isless(+1.0,-1.0) -@test !isless(+1.0,-0.0) -@test !isless(+1.0,+0.0) -@test !isless(+1.0,+1.0) -@test isless(+1.0,+Inf) -@test isless(+1.0,-NaN) -@test isless(+1.0,+NaN) - -@test !isless(+Inf,-Inf) -@test !isless(+Inf,-1.0) -@test !isless(+Inf,-0.0) -@test !isless(+Inf,+0.0) -@test !isless(+Inf,+1.0) -@test !isless(+Inf,+Inf) -@test isless(+Inf,-NaN) -@test isless(+Inf,+NaN) - -@test !isless(-NaN,-Inf) -@test !isless(-NaN,-1.0) -@test !isless(-NaN,-0.0) -@test !isless(-NaN,+0.0) -@test !isless(-NaN,+1.0) -@test !isless(-NaN,+Inf) -@test !isless(-NaN,-NaN) -@test !isless(-NaN,+NaN) - -@test !isless(+NaN,-Inf) -@test !isless(+NaN,-1.0) -@test !isless(+NaN,-0.0) -@test !isless(+NaN,+0.0) -@test !isless(+NaN,+1.0) -@test !isless(+NaN,+Inf) -@test !isless(+NaN,-NaN) -@test !isless(+NaN,+NaN) - -@test isequal( 0, 0.0) -@test isequal( 0.0, 0) -@test !isequal( 0,-0.0) -@test !isequal(-0.0, 0) -@test isless(-0.0, 0) -@test !isless( 0,-0.0) - -@test isless(-0.0, 0.0f0) -@test lexcmp(-0.0, 0.0f0) == -1 -@test lexcmp(0.0, -0.0f0) == 1 -@test lexcmp(NaN, 1) == 1 -@test lexcmp(1, NaN) == -1 -@test lexcmp(NaN, NaN) == 0 - -for x=-5:5, y=-5:5 - @test (x==y)==(Float64(x)==Int64(y)) - @test (x!=y)==(Float64(x)!=Int64(y)) - @test (x< y)==(Float64(x)< Int64(y)) - @test (x> y)==(Float64(x)> Int64(y)) - @test (x<=y)==(Float64(x)<=Int64(y)) - @test (x>=y)==(Float64(x)>=Int64(y)) - - @test (x==y)==(Int64(x)==Float64(y)) - @test (x!=y)==(Int64(x)!=Float64(y)) - @test (x< y)==(Int64(x)< Float64(y)) - @test (x> y)==(Int64(x)> Float64(y)) - @test (x<=y)==(Int64(x)<=Float64(y)) - @test (x>=y)==(Int64(x)>=Float64(y)) - - if x >= 0 - @test (x==y)==(UInt64(x)==Float64(y)) - @test (x!=y)==(UInt64(x)!=Float64(y)) - @test (x< y)==(UInt64(x)< Float64(y)) - @test (x> y)==(UInt64(x)> Float64(y)) - @test (x<=y)==(UInt64(x)<=Float64(y)) - @test (x>=y)==(UInt64(x)>=Float64(y)) - end - if y >= 0 - @test (x==y)==(Float64(x)==UInt64(y)) - @test (x!=y)==(Float64(x)!=UInt64(y)) - @test (x< y)==(Float64(x)< UInt64(y)) - @test (x> y)==(Float64(x)> UInt64(y)) - @test (x<=y)==(Float64(x)<=UInt64(y)) - @test (x>=y)==(Float64(x)>=UInt64(y)) - end -end - -function _cmp_(x::Union{Int64,UInt64}, y::Float64) - if x==Int64(2)^53-2 && y==2.0^53-2; return 0; end - if x==Int64(2)^53-2 && y==2.0^53-1; return -1; end - if x==Int64(2)^53-2 && y==2.0^53 ; return -1; end - if x==Int64(2)^53-2 && y==2.0^53+2; return -1; end - if x==Int64(2)^53-2 && y==2.0^53+3; return -1; end - if x==Int64(2)^53-2 && y==2.0^53+4; return -1; end - - if x==Int64(2)^53-1 && y==2.0^53-2; return +1; end - if x==Int64(2)^53-1 && y==2.0^53-1; return 0; end - if x==Int64(2)^53-1 && y==2.0^53 ; return -1; end - if x==Int64(2)^53-1 && y==2.0^53+2; return -1; end - if x==Int64(2)^53-1 && y==2.0^53+3; return -1; end - if x==Int64(2)^53-1 && y==2.0^53+4; return -1; end - - if x==Int64(2)^53 && y==2.0^53-2; return +1; end - if x==Int64(2)^53 && y==2.0^53-1; return +1; end - if x==Int64(2)^53 && y==2.0^53 ; return 0; end - if x==Int64(2)^53 && y==2.0^53+2; return -1; end - if x==Int64(2)^53 && y==2.0^53+4; return -1; end - - if x==Int64(2)^53+1 && y==2.0^53-2; return +1; end - if x==Int64(2)^53+1 && y==2.0^53-1; return +1; end - if x==Int64(2)^53+1 && y==2.0^53 ; return +1; end - if x==Int64(2)^53+1 && y==2.0^53+2; return -1; end - if x==Int64(2)^53+1 && y==2.0^53+4; return -1; end - - if x==Int64(2)^53+2 && y==2.0^53-2; return +1; end - if x==Int64(2)^53+2 && y==2.0^53-1; return +1; end - if x==Int64(2)^53+2 && y==2.0^53 ; return +1; end - if x==Int64(2)^53+2 && y==2.0^53+2; return 0; end - if x==Int64(2)^53+2 && y==2.0^53+4; return -1; end - - if x==Int64(2)^53+3 && y==2.0^53-2; return +1; end - if x==Int64(2)^53+3 && y==2.0^53-1; return +1; end - if x==Int64(2)^53+3 && y==2.0^53 ; return +1; end - if x==Int64(2)^53+3 && y==2.0^53+2; return +1; end - if x==Int64(2)^53+3 && y==2.0^53+4; return -1; end - - if x==Int64(2)^53+4 && y==2.0^53-2; return +1; end - if x==Int64(2)^53+4 && y==2.0^53-1; return +1; end - if x==Int64(2)^53+4 && y==2.0^53 ; return +1; end - if x==Int64(2)^53+4 && y==2.0^53+2; return +1; end - if x==Int64(2)^53+4 && y==2.0^53+4; return 0; end - - if x==Int64(2)^53+5 && y==2.0^53-2; return +1; end - if x==Int64(2)^53+5 && y==2.0^53-1; return +1; end - if x==Int64(2)^53+5 && y==2.0^53 ; return +1; end - if x==Int64(2)^53+5 && y==2.0^53+2; return +1; end - if x==Int64(2)^53+5 && y==2.0^53+4; return +1; end - - error("invalid: _cmp_($x,$y)") -end - -for x=Int64(2)^53-2:Int64(2)^53+5, - y=[2.0^53-2 2.0^53-1 2.0^53 2.0^53+2 2.0^53+4] - u = UInt64(x) - @test y == Float64(trunc(Int64,y)) - - @test (x==y)==(y==x) - @test (x!=y)==!(x==y) - @test (-x==-y)==(-y==-x) - @test (-x!=-y)==!(-x==-y) - - @test (x<y)==(x<=y)&(x!=y) - @test (x<=y)==(x<y)|(x==y) - @test (x==y)==(x<=y)&!(x<y) - - @test -x != x - @test -y != y - @test -x != y - @test -y != x - @test -x < x - @test -y < y - @test -x < y - @test -y < x - @test -x <= x - @test -y <= y - @test -x <= y - @test -y <= x - - @test -y != u - @test -y < u - @test -y <= u - - c = _cmp_(x,y) - if c < 0 - @test !(x == y) - @test (x < y) - @test !(y < x) - @test (x <= y) - @test !(y <= x) - - @test !(u == y) - @test (u < y) - @test !(y < u) - @test (u <= y) - @test !(y <= u) - - @test !(-x == -y) - @test !(-x < -y) - @test (-y < -x) - @test !(-x <= -y) - @test (-y <= -x) - elseif c > 0 - @test !(x == y) - @test !(x < y) - @test (y < x) - @test !(x <= y) - @test (y <= x) - - @test !(u == y) - @test !(u < y) - @test (y < u) - @test !(u <= y) - @test (y <= u) - - @test !(-x == -y) - @test (-x < -y) - @test !(-y < -x) - @test (-x <= -y) - @test !(-y <= -x) - else - @test (x == y) - @test !(x < y) - @test !(y < x) - @test (x <= y) - @test (y <= x) - - @test (u == y) - @test !(u < y) - @test !(y < u) - @test (u <= y) - @test (y <= u) - - @test (-x == -y) - @test !(-x < -y) - @test !(-y < -x) - @test (-x <= -y) - @test (-y <= -x) - end -end - -@test Int64(2)^62-1 != 2.0^62 -@test Int64(2)^62 == 2.0^62 -@test Int64(2)^62+1 != 2.0^62 -@test 2.0^62 != Int64(2)^62-1 -@test 2.0^62 == Int64(2)^62 -@test 2.0^62 != Int64(2)^62+1 - -@test typemax(Int64) != +2.0^63 -@test typemin(Int64) == -2.0^63 -@test typemin(Int64)+1 != -2.0^63 - -@test UInt64(2)^60-1 != 2.0^60 -@test UInt64(2)^60 == 2.0^60 -@test UInt64(2)^60+1 != 2.0^60 -@test 2.0^60 != UInt64(2)^60-1 -@test 2.0^60 == UInt64(2)^60 -@test 2.0^60 != UInt64(2)^60+1 - -@test UInt64(2)^63-1 != 2.0^63 -@test UInt64(2)^63 == 2.0^63 -@test UInt64(2)^63+1 != 2.0^63 -@test 2.0^63 != UInt64(2)^63-1 -@test 2.0^63 == UInt64(2)^63 -@test 2.0^63 != UInt64(2)^63+1 - -@test typemax(UInt64) != 2.0^64 -# issue #9085 -f9085() = typemax(UInt64) != 2.0^64 -@test f9085() - -@test typemax(UInt64) < Float64(typemax(UInt64)) -@test typemax(Int64) < Float64(typemax(Int64)) -@test typemax(UInt64) <= Float64(typemax(UInt64)) -@test typemax(Int64) <= Float64(typemax(Int64)) - -@test Float64(typemax(UInt64)) > typemax(UInt64) -@test Float64(typemax(Int64)) > typemax(Int64) -@test Float64(typemax(UInt64)) >= typemax(UInt64) -@test Float64(typemax(Int64)) >= typemax(Int64) - -@test Float64(Int128(0)) == 0.0 -@test Float32(Int128(0)) == 0.0f0 -@test Float64(Int128(-1)) == -1.0 -@test Float32(Int128(-1)) == -1.0f0 -@test Float64(Int128(3)) == 3.0 -@test Float32(Int128(3)) == 3.0f0 -@test Float64(UInt128(10121)) == 10121.0 -@test Float32(UInt128(10121)) == 10121.0f0 -@test Float64(typemin(Int128)) == -2.0^127 -@test Float32(typemin(Int128)) == -2.0f0^127 -@test Float64(typemax(Int128)) == 2.0^127 -@test Float32(typemax(Int128)) == 2.0f0^127 -@test Float64(typemin(UInt128)) == 0.0 -@test Float32(typemin(UInt128)) == 0.0f0 -@test Float64(typemax(UInt128)) == 2.0^128 -@test Float32(typemax(UInt128)) == 2.0f0^128 - -# check for double rounding in conversion -@test Float64(10633823966279328163822077199654060032) == 1.0633823966279327e37 #0x1p123 -@test Float64(10633823966279328163822077199654060033) == 1.063382396627933e37 #nextfloat(0x1p123) -@test Float64(-10633823966279328163822077199654060032) == -1.0633823966279327e37 -@test Float64(-10633823966279328163822077199654060033) == -1.063382396627933e37 - -# check Float vs Int128 comparisons -@test Int128(1e30) == 1e30 -@test Int128(1e30)+1 > 1e30 - -@test Int128(-2.0^127) == typemin(Int128) -@test Float64(UInt128(3.7e19)) == 3.7e19 -@test Float64(UInt128(3.7e30)) == 3.7e30 - -@test !(NaN <= 1) -@test !(NaN >= 1) -@test !(NaN < 1) -@test !(NaN > 1) -@test !(1 <= NaN) -@test !(1 >= NaN) -@test !(1 < NaN) -@test !(1 > NaN) - -@test 1//1 == 1 -@test 2//2 == 1 -@test 1//1 == 1//1 -@test 2//2 == 1//1 -@test 2//4 == 3//6 -@test 1//2 + 1//2 == 1 -@test (-1)//3 == -(1//3) -@test 1//2 + 3//4 == 5//4 -@test 1//3 * 3//4 == 1//4 -@test 1//2 / 3//4 == 2//3 -@test 1//0 == 1//0 -@test 5//0 == 1//0 -@test -1//0 == -1//0 -@test -7//0 == -1//0 - -@test_throws OverflowError -(0x01//0x0f) -@test_throws OverflowError -(typemin(Int)//1) -@test_throws OverflowError (typemax(Int)//3) + 1 -@test_throws OverflowError (typemax(Int)//3) * 2 -@test (typemax(Int)//1) * (1//typemax(Int)) == 1 -@test (typemax(Int)//1) / (typemax(Int)//1) == 1 -@test (1//typemax(Int)) / (1//typemax(Int)) == 1 -@test_throws OverflowError (1//2)^63 - -@test @inferred(rationalize(Int, 3.0, 0.0)) === 3//1 -@test @inferred(rationalize(Int, 3.0, 0)) === 3//1 -@test_throws ArgumentError rationalize(Int, big(3.0), -1.) - -for a = -5:5, b = -5:5 - if a == b == 0; continue; end - if ispow2(b) - @test a//b == a/b - @test convert(Rational,a/b) == a//b - end - @test rationalize(a/b) == a//b - @test a//b == a//b - if b == 0 - @test_throws DivideError round(Integer,a//b) == round(Integer,a/b) - else - @test round(Integer,a//b) == round(Integer,a/b) - end - for c = -5:5 - @test (a//b == c) == (a/b == c) - @test (a//b != c) == (a/b != c) - @test (a//b <= c) == (a/b <= c) - @test (a//b < c) == (a/b < c) - @test (a//b >= c) == (a/b >= c) - @test (a//b > c) == (a/b > c) - for d = -5:5 - if c == d == 0; continue; end - @test (a//b == c//d) == (a/b == c/d) - @test (a//b != c//d) == (a/b != c/d) - @test (a//b <= c//d) == (a/b <= c/d) - @test (a//b < c//d) == (a/b < c/d) - @test (a//b >= c//d) == (a/b >= c/d) - @test (a//b > c//d) == (a/b > c/d) - end - end -end - -@test 0.5 == 1//2 -@test 0.1 != 1//10 -@test 0.1 == 3602879701896397//36028797018963968 -@test Inf == 1//0 == 2//0 == typemax(Int)//0 -@test -Inf == -1//0 == -2//0 == -typemax(Int)//0 -@test realmin() != 1//(BigInt(2)^1022+1) -@test realmin() == 1//(BigInt(2)^1022) -@test realmin() != 1//(BigInt(2)^1022-1) -@test realmin()/2 != 1//(BigInt(2)^1023+1) -@test realmin()/2 == 1//(BigInt(2)^1023) -@test realmin()/2 != 1//(BigInt(2)^1023-1) -@test nextfloat(0.0) != 1//(BigInt(2)^1074+1) -@test nextfloat(0.0) == 1//(BigInt(2)^1074) -@test nextfloat(0.0) != 1//(BigInt(2)^1074-1) - -@test 1/3 < 1//3 -@test !(1//3 < 1/3) -@test -1/3 < 1//3 -@test -1/3 > -1//3 -@test 1/3 > -1//3 -@test 1/5 > 1//5 -@test 1//3 < Inf -@test 0//1 < Inf -@test 1//0 == Inf -@test -1//0 == -Inf -@test -1//0 != Inf -@test 1//0 != -Inf -@test !(1//0 < Inf) -@test !(1//3 < NaN) -@test !(1//3 == NaN) -@test !(1//3 > NaN) - -@test Float64(pi,RoundDown) < pi -@test Float64(pi,RoundUp) > pi -@test !(Float64(pi,RoundDown) > pi) -@test !(Float64(pi,RoundUp) < pi) -@test Float64(pi,RoundDown) <= pi -@test Float64(pi,RoundUp) >= pi -@test Float64(pi,RoundDown) != pi -@test Float64(pi,RoundUp) != pi - -@test Float32(pi,RoundDown) < pi -@test Float32(pi,RoundUp) > pi -@test !(Float32(pi,RoundDown) > pi) -@test !(Float32(pi,RoundUp) < pi) - -# issue #6365 -for T in (Float32, Float64) - for i = 9007199254740992:9007199254740996 - @test T(i) == T(BigFloat(i)) - @test T(-i) == T(BigFloat(-i)) - for r in (RoundNearest,RoundUp,RoundDown,RoundToZero) - @test T(i,r) == T(BigFloat(i),r) - @test T(-i,r) == T(BigFloat(-i),r) - end - end -end - -@test prevfloat(big(pi)) < pi -@test nextfloat(big(pi)) > pi -@test !(prevfloat(big(pi)) > pi) -@test !(nextfloat(big(pi)) < pi) - -@test 2646693125139304345//842468587426513207 < pi -@test !(2646693125139304345//842468587426513207 > pi) -@test 2646693125139304345//842468587426513207 != pi - -@test sqrt(2) == 1.4142135623730951 - -@test 1+1.5 == 2.5 -@test 1.5+1 == 2.5 -@test 1+1.5+2 == 4.5 -@test isa(convert(Complex{Int16},1), Complex{Int16}) -@test Complex(1,2)+1 == Complex(2,2) -@test Complex(1,2)+1.5 == Complex(2.5,2.0) -@test 1/Complex(2,2) == Complex(.25,-.25) -@test Complex(1.5,1.0) + 1//2 == Complex(2.0,1.0) -@test real(Complex(1//2,2//3)) == 1//2 -@test imag(Complex(1//2,2//3)) == 2//3 -@test Complex(1,2) + 1//2 == Complex(3//2,2//1) -@test Complex(1,2) + 1//2 * 0.5 == Complex(1.25,2.0) -@test (Complex(1,2) + 1//2) * 0.5 == Complex(0.75,1.0) -@test (Complex(1,2)/Complex(2.5,3.0))*Complex(2.5,3.0) ≈ Complex(1,2) -@test 0.7 < real(sqrt(Complex(0,1))) < 0.707107 - -for T in Base.BitSigned_types - @test abs(typemin(T)) == -typemin(T) - #for x in (typemin(T),convert(T,-1),zero(T),one(T),typemax(T)) - # @test signed(unsigned(x)) == x - #end -end - -#for T in (UInt8,UInt16,UInt32,UInt64,UInt128) -# x in (typemin(T),one(T),typemax(T)) -# @test unsigned(signed(x)) == x -#end - -for S = Base.BitSigned64_types, - U = Base.BitUnsigned64_types - @test !(-one(S) == typemax(U)) - @test -one(S) != typemax(U) - @test -one(S) < typemax(U) - @test !(typemax(U) <= -one(S)) -end - -# check type of constructed rationals -int_types = Base.BitInteger64_types -for N = int_types, D = int_types - T = promote_type(N,D) - @test typeof(convert(N,2)//convert(D,3)) <: Rational{T} -end - -# issue #7564 -@test typeof(convert(Rational{Integer},1)) === Rational{Integer} - -# check type of constructed complexes -real_types = [Base.BitInteger64_types..., - [Rational{T} for T in Base.BitInteger64_types]..., - Float32, Float64] -for A = real_types, B = real_types - T = promote_type(A,B) - @test typeof(Complex(convert(A,2),convert(B,3))) <: Complex{T} -end - -# comparison should fail on complex -@test_throws MethodError complex(1,2) > 0 -@test_throws MethodError complex(1,2) > complex(0,0) - -# div, fld, cld, rem, mod -for yr = Any[ - 1:6, - 0.25:0.25:6.0, - 1//4:1//4:6//1 -], xr = Any[ - 0:6, - 0.0:0.25:6.0, - 0//1:1//4:6//1 -] - for y = yr, x = xr - # check basic div functionality - if 0 <= x < 1y - @test div(+x,+y) == 0 - @test div(+x,-y) == 0 - @test div(-x,+y) == 0 - @test div(-x,-y) == 0 - end - if 1y <= x < 2y - @test div(+x,+y) == +1 - @test div(+x,-y) == -1 - @test div(-x,+y) == -1 - @test div(-x,-y) == +1 - end - if 2y <= x < 3y - @test div(+x,+y) == +2 - @test div(+x,-y) == -2 - @test div(-x,+y) == -2 - @test div(-x,-y) == +2 - end - - # check basic fld functionality - if 0 == x - @test fld(+x,+y) == 0 - @test fld(+x,-y) == 0 - @test fld(-x,+y) == 0 - @test fld(-x,-y) == 0 - end - if 0 < x < 1y - @test fld(+x,+y) == +0 - @test fld(+x,-y) == -1 - @test fld(-x,+y) == -1 - @test fld(-x,-y) == +0 - end - if 1y == x - @test fld(+x,+y) == +1 - @test fld(+x,-y) == -1 - @test fld(-x,+y) == -1 - @test fld(-x,-y) == +1 - end - if 1y < x < 2y - @test fld(+x,+y) == +1 - @test fld(+x,-y) == -2 - @test fld(-x,+y) == -2 - @test fld(-x,-y) == +1 - end - if 2y == x - @test fld(+x,+y) == +2 - @test fld(+x,-y) == -2 - @test fld(-x,+y) == -2 - @test fld(-x,-y) == +2 - end - if 2y < x < 3y - @test fld(+x,+y) == +2 - @test fld(+x,-y) == -3 - @test fld(-x,+y) == -3 - @test fld(-x,-y) == +2 - end - - # check basic cld functionality - if 0 == x - @test cld(+x,+y) == 0 - @test cld(+x,-y) == 0 - @test cld(-x,+y) == 0 - @test cld(-x,-y) == 0 - end - if 0 < x < 1y - @test cld(+x,+y) == +1 - @test cld(+x,-y) == +0 - @test cld(-x,+y) == +0 - @test cld(-x,-y) == +1 - end - if 1y == x - @test cld(+x,+y) == +1 - @test cld(+x,-y) == -1 - @test cld(-x,+y) == -1 - @test cld(-x,-y) == +1 - end - if 1y < x < 2y - @test cld(+x,+y) == +2 - @test cld(+x,-y) == -1 - @test cld(-x,+y) == -1 - @test cld(-x,-y) == +2 - end - if 2y == x - @test cld(+x,+y) == +2 - @test cld(+x,-y) == -2 - @test cld(-x,+y) == -2 - @test cld(-x,-y) == +2 - end - if 2y < x < 3y - @test cld(+x,+y) == +3 - @test cld(+x,-y) == -2 - @test cld(-x,+y) == -2 - @test cld(-x,-y) == +3 - end - - # check everything else in terms of div, fld, cld - d = div(x,y) - f = fld(x,y) - c = cld(x,y) - r = rem(x,y) - m = mod(x,y) - d2, r2 = divrem(x,y) - f2, m2 = fldmod(x,y) - - t1 = isa(x,Rational) && isa(y,Rational) ? - promote_type(typeof(numerator(x)),typeof(numerator(y))) : - isa(x,Rational) ? promote_type(typeof(numerator(x)),typeof(y)) : - isa(y,Rational) ? promote_type(typeof(x),typeof(numerator(y))) : - promote_type(typeof(x),typeof(y)) - - t2 = promote_type(typeof(x),typeof(y)) - - @test typeof(d) <: t1 - @test typeof(f) <: t1 - @test typeof(c) <: t1 - @test typeof(r) <: t2 - @test typeof(m) <: t2 - - @test d == f - @test c == f + (m == 0 ? 0 : 1) - @test r == m - @test 0 <= r < y - @test x == y*d + r - - @test typeof(d2) == typeof(d) - @test typeof(r2) == typeof(r) - @test typeof(f2) == typeof(f) - @test typeof(m2) == typeof(m) - - @test d2 == d - @test r2 == r - @test f2 == f - @test m2 == m - - for X=[-1,1], Y=[-1,1] - sx = X*x - sy = Y*y - - sd = div(sx,sy) - sf = fld(sx,sy) - sc = cld(sx,sy) - sr = rem(sx,sy) - sm = mod(sx,sy) - sd2, sr2 = divrem(sx,sy) - sf2, sm2 = fldmod(sx,sy) - - @test typeof(sd) <: t1 - @test typeof(sf) <: t1 - @test typeof(sc) <: t1 - @test typeof(sr) <: t2 - @test typeof(sm) <: t2 - - @test sx < 0 ? -y < sr <= 0 : 0 <= sr < +y - @test sy < 0 ? -y < sm <= 0 : 0 <= sm < +y - @test sx == sy*sd + sr - @test sx == sy*sf + sm - - @test typeof(sd2) == typeof(sd) - @test typeof(sr2) == typeof(sr) - @test typeof(sf2) == typeof(sf) - @test typeof(sm2) == typeof(sm) - - @test sd2 == sd - @test sr2 == sr - @test sf2 == sf - @test sm2 == sm - end - end -end - -@test div(typemax(Int64) , 1) == 9223372036854775807 -@test div(typemax(Int64) , 2) == 4611686018427387903 -@test div(typemax(Int64) , 7) == 1317624576693539401 -@test div(typemax(Int64) ,-1) == -9223372036854775807 -@test div(typemax(Int64) ,-2) == -4611686018427387903 -@test div(typemax(Int64) ,-7) == -1317624576693539401 -@test div(typemax(Int64)-1, 1) == 9223372036854775806 -@test div(typemax(Int64)-1, 2) == 4611686018427387903 -@test div(typemax(Int64)-1, 7) == 1317624576693539400 -@test div(typemax(Int64)-1,-1) == -9223372036854775806 -@test div(typemax(Int64)-1,-2) == -4611686018427387903 -@test div(typemax(Int64)-1,-7) == -1317624576693539400 -@test div(typemax(Int64)-2, 1) == 9223372036854775805 -@test div(typemax(Int64)-2, 2) == 4611686018427387902 -@test div(typemax(Int64)-2, 7) == 1317624576693539400 -@test div(typemax(Int64)-2,-1) == -9223372036854775805 -@test div(typemax(Int64)-2,-2) == -4611686018427387902 -@test div(typemax(Int64)-2,-7) == -1317624576693539400 - -@test div(typemin(Int64) , 1) == -9223372036854775807-1 -@test div(typemin(Int64) , 2) == -4611686018427387904 -@test div(typemin(Int64) , 7) == -1317624576693539401 -@test div(typemin(Int64) ,-2) == 4611686018427387904 -@test div(typemin(Int64) ,-7) == 1317624576693539401 -@test div(typemin(Int64)+1, 1) == -9223372036854775807 -@test div(typemin(Int64)+1, 2) == -4611686018427387903 -@test div(typemin(Int64)+1, 7) == -1317624576693539401 -@test div(typemin(Int64)+1,-1) == 9223372036854775807 -@test div(typemin(Int64)+1,-2) == 4611686018427387903 -@test div(typemin(Int64)+1,-7) == 1317624576693539401 -@test div(typemin(Int64)+2, 1) == -9223372036854775806 -@test div(typemin(Int64)+2, 2) == -4611686018427387903 -@test div(typemin(Int64)+2, 7) == -1317624576693539400 -@test div(typemin(Int64)+2,-1) == 9223372036854775806 -@test div(typemin(Int64)+2,-2) == 4611686018427387903 -@test div(typemin(Int64)+2,-7) == 1317624576693539400 -@test div(typemin(Int64)+3, 1) == -9223372036854775805 -@test div(typemin(Int64)+3, 2) == -4611686018427387902 -@test div(typemin(Int64)+3, 7) == -1317624576693539400 -@test div(typemin(Int64)+3,-1) == 9223372036854775805 -@test div(typemin(Int64)+3,-2) == 4611686018427387902 -@test div(typemin(Int64)+3,-7) == 1317624576693539400 - -@test fld(typemax(Int64) , 1) == 9223372036854775807 -@test fld(typemax(Int64) , 2) == 4611686018427387903 -@test fld(typemax(Int64) , 7) == 1317624576693539401 -@test fld(typemax(Int64) ,-1) == -9223372036854775807 -@test fld(typemax(Int64) ,-2) == -4611686018427387904 -@test fld(typemax(Int64) ,-7) == -1317624576693539401 -@test fld(typemax(Int64)-1, 1) == 9223372036854775806 -@test fld(typemax(Int64)-1, 2) == 4611686018427387903 -@test fld(typemax(Int64)-1, 7) == 1317624576693539400 -@test fld(typemax(Int64)-1,-1) == -9223372036854775806 -@test fld(typemax(Int64)-1,-2) == -4611686018427387903 -@test fld(typemax(Int64)-1,-7) == -1317624576693539401 -@test fld(typemax(Int64)-2, 1) == 9223372036854775805 -@test fld(typemax(Int64)-2, 2) == 4611686018427387902 -@test fld(typemax(Int64)-2, 7) == 1317624576693539400 -@test fld(typemax(Int64)-2,-1) == -9223372036854775805 -@test fld(typemax(Int64)-2,-2) == -4611686018427387903 -@test fld(typemax(Int64)-2,-7) == -1317624576693539401 - -@test fld(typemin(Int64) , 1) == -9223372036854775807-1 -@test fld(typemin(Int64) , 2) == -4611686018427387904 -@test fld(typemin(Int64) , 7) == -1317624576693539402 -@test fld(typemin(Int64) ,-2) == 4611686018427387904 -@test fld(typemin(Int64) ,-7) == 1317624576693539401 -@test fld(typemin(Int64)+1, 1) == -9223372036854775807 -@test fld(typemin(Int64)+1, 2) == -4611686018427387904 -@test fld(typemin(Int64)+1, 7) == -1317624576693539401 -@test fld(typemin(Int64)+1,-1) == 9223372036854775807 -@test fld(typemin(Int64)+1,-2) == 4611686018427387903 -@test fld(typemin(Int64)+1,-7) == 1317624576693539401 -@test fld(typemin(Int64)+2, 1) == -9223372036854775806 -@test fld(typemin(Int64)+2, 2) == -4611686018427387903 -@test fld(typemin(Int64)+2, 7) == -1317624576693539401 -@test fld(typemin(Int64)+2,-1) == 9223372036854775806 -@test fld(typemin(Int64)+2,-2) == 4611686018427387903 -@test fld(typemin(Int64)+2,-7) == 1317624576693539400 -@test fld(typemin(Int64)+3, 1) == -9223372036854775805 -@test fld(typemin(Int64)+3, 2) == -4611686018427387903 -@test fld(typemin(Int64)+3, 7) == -1317624576693539401 -@test fld(typemin(Int64)+3,-1) == 9223372036854775805 -@test fld(typemin(Int64)+3,-2) == 4611686018427387902 -@test fld(typemin(Int64)+3,-7) == 1317624576693539400 - -@test cld(typemax(Int64) , 1) == 9223372036854775807 -@test cld(typemax(Int64) , 2) == 4611686018427387904 -@test cld(typemax(Int64) , 7) == 1317624576693539401 -@test cld(typemax(Int64) ,-1) == -9223372036854775807 -@test cld(typemax(Int64) ,-2) == -4611686018427387903 -@test cld(typemax(Int64) ,-7) == -1317624576693539401 -@test cld(typemax(Int64)-1, 1) == 9223372036854775806 -@test cld(typemax(Int64)-1, 2) == 4611686018427387903 -@test cld(typemax(Int64)-1, 7) == 1317624576693539401 -@test cld(typemax(Int64)-1,-1) == -9223372036854775806 -@test cld(typemax(Int64)-1,-2) == -4611686018427387903 -@test cld(typemax(Int64)-1,-7) == -1317624576693539400 -@test cld(typemax(Int64)-2, 1) == 9223372036854775805 -@test cld(typemax(Int64)-2, 2) == 4611686018427387903 -@test cld(typemax(Int64)-2, 7) == 1317624576693539401 -@test cld(typemax(Int64)-2,-1) == -9223372036854775805 -@test cld(typemax(Int64)-2,-2) == -4611686018427387902 -@test cld(typemax(Int64)-2,-7) == -1317624576693539400 - -@test cld(typemin(Int64) , 1) == -9223372036854775807-1 -@test cld(typemin(Int64) , 2) == -4611686018427387904 -@test cld(typemin(Int64) , 7) == -1317624576693539401 -@test cld(typemin(Int64) ,-2) == 4611686018427387904 -@test cld(typemin(Int64) ,-7) == 1317624576693539402 -@test cld(typemin(Int64)+1, 1) == -9223372036854775807 -@test cld(typemin(Int64)+1, 2) == -4611686018427387903 -@test cld(typemin(Int64)+1, 7) == -1317624576693539401 -@test cld(typemin(Int64)+1,-1) == 9223372036854775807 -@test cld(typemin(Int64)+1,-2) == 4611686018427387904 -@test cld(typemin(Int64)+1,-7) == 1317624576693539401 -@test cld(typemin(Int64)+2, 1) == -9223372036854775806 -@test cld(typemin(Int64)+2, 2) == -4611686018427387903 -@test cld(typemin(Int64)+2, 7) == -1317624576693539400 -@test cld(typemin(Int64)+2,-1) == 9223372036854775806 -@test cld(typemin(Int64)+2,-2) == 4611686018427387903 -@test cld(typemin(Int64)+2,-7) == 1317624576693539401 -@test cld(typemin(Int64)+3, 1) == -9223372036854775805 -@test cld(typemin(Int64)+3, 2) == -4611686018427387902 -@test cld(typemin(Int64)+3, 7) == -1317624576693539400 -@test cld(typemin(Int64)+3,-1) == 9223372036854775805 -@test cld(typemin(Int64)+3,-2) == 4611686018427387903 -@test cld(typemin(Int64)+3,-7) == 1317624576693539401 - -for x=Any[typemin(Int64), -typemax(Int64), -typemax(Int64)+1, -typemax(Int64)+2, - typemax(Int64)-2, typemax(Int64)-1, typemax(Int64), - typemax(UInt64)-1, typemax(UInt64)-2, typemax(UInt64)], - y=[-7,-2,-1,1,2,7] - if x >= 0 - @test div(unsigned(x),y) == unsigned(div(x,y)) - @test fld(unsigned(x),y) == unsigned(fld(x,y)) - @test cld(unsigned(x),y) == unsigned(cld(x,y)) - end - if isa(x,Signed) && y >= 0 - @test div(x,unsigned(y)) == div(x,y) - @test fld(x,unsigned(y)) == fld(x,y) - @test cld(x,unsigned(y)) == cld(x,y) - end -end - -for x=0:5, y=1:5 - @test div(UInt(x),UInt(y)) == div(x,y) - @test div(UInt(x),y) == div(x,y) - @test div(x,UInt(y)) == div(x,y) - @test div(UInt(x),-y) == reinterpret(UInt,div(x,-y)) - @test div(-x,UInt(y)) == div(-x,y) - - @test fld(UInt(x),UInt(y)) == fld(x,y) - @test fld(UInt(x),y) == fld(x,y) - @test fld(x,UInt(y)) == fld(x,y) - @test fld(UInt(x),-y) == reinterpret(UInt,fld(x,-y)) - @test fld(-x,UInt(y)) == fld(-x,y) - - @test cld(UInt(x),UInt(y)) == cld(x,y) - @test cld(UInt(x),y) == cld(x,y) - @test cld(x,UInt(y)) == cld(x,y) - @test cld(UInt(x),-y) == reinterpret(UInt,cld(x,-y)) - @test cld(-x,UInt(y)) == cld(-x,y) - - @test rem(UInt(x),UInt(y)) == rem(x,y) - @test rem(UInt(x),y) == rem(x,y) - @test rem(x,UInt(y)) == rem(x,y) - @test rem(UInt(x),-y) == rem(x,-y) - @test rem(-x,UInt(y)) == rem(-x,y) - - @test mod(UInt(x),UInt(y)) == mod(x,y) - @test mod(UInt(x),y) == mod(x,y) - @test mod(x,UInt(y)) == mod(x,y) - @test mod(UInt(x),-y) == mod(x,-y) - @test mod(-x,UInt(y)) == mod(-x,y) -end - -@test div(typemax(UInt64) , 1) == typemax(UInt64) -@test div(typemax(UInt64) ,-1) == -typemax(UInt64) -@test div(typemax(UInt64)-1, 1) == typemax(UInt64)-1 -@test div(typemax(UInt64)-1,-1) == -typemax(UInt64)+1 -@test div(typemax(UInt64)-2, 1) == typemax(UInt64)-2 -@test div(typemax(UInt64)-2,-1) == -typemax(UInt64)+2 - -@test signed(div(unsigned(typemax(Int64))+2, 1)) == typemax(Int64)+2 -@test signed(div(unsigned(typemax(Int64))+2,-1)) == -typemax(Int64)-2 -@test signed(div(unsigned(typemax(Int64))+1, 1)) == typemax(Int64)+1 -@test signed(div(unsigned(typemax(Int64))+1,-1)) == -typemax(Int64)-1 -@test signed(div(unsigned(typemax(Int64)) , 1)) == typemax(Int64) -@test signed(div(unsigned(typemax(Int64)) ,-1)) == -typemax(Int64) - -@test signed(div(typemax(UInt),typemax(Int))) == 2 -@test signed(div(typemax(UInt),(typemax(Int)>>1)+1)) == 3 -@test signed(div(typemax(UInt),typemax(Int)>>1)) == 4 -@test signed(div(typemax(UInt),typemin(Int))) == -1 -@test signed(div(typemax(UInt),typemin(Int)+1)) == -2 -@test signed(div(typemax(UInt),typemin(Int)>>1)) == -3 -@test signed(div(typemax(UInt),(typemin(Int)>>1)+1)) == -4 - -@test fld(typemax(UInt64) , 1) == typemax(UInt64) -@test fld(typemax(UInt64) ,-1) == -typemax(UInt64) -@test fld(typemax(UInt64)-1, 1) == typemax(UInt64)-1 -@test fld(typemax(UInt64)-1,-1) == -typemax(UInt64)+1 -@test fld(typemax(UInt64)-2, 1) == typemax(UInt64)-2 -@test fld(typemax(UInt64)-2,-1) == -typemax(UInt64)+2 - -@test signed(fld(unsigned(typemax(Int64))+2, 1)) == typemax(Int64)+2 -@test signed(fld(unsigned(typemax(Int64))+2,-1)) == -typemax(Int64)-2 -@test signed(fld(unsigned(typemax(Int64))+1, 1)) == typemax(Int64)+1 -@test signed(fld(unsigned(typemax(Int64))+1,-1)) == -typemax(Int64)-1 -@test signed(fld(unsigned(typemax(Int64)) , 1)) == typemax(Int64) -@test signed(fld(unsigned(typemax(Int64)) ,-1)) == -typemax(Int64) - -@test signed(fld(typemax(UInt),typemax(Int))) == 2 -@test signed(fld(typemax(UInt),(typemax(Int)>>1)+1)) == 3 -@test signed(fld(typemax(UInt),typemax(Int)>>1)) == 4 -@test signed(fld(typemax(UInt),typemin(Int))) == -2 -@test signed(fld(typemax(UInt),typemin(Int)+1)) == -3 -@test signed(fld(typemax(UInt),typemin(Int)>>1)) == -4 -@test signed(fld(typemax(UInt),(typemin(Int)>>1)+1)) == -5 - -@test cld(typemax(UInt64) , 1) == typemax(UInt64) -@test cld(typemax(UInt64) ,-1) == -typemax(UInt64) -@test cld(typemax(UInt64)-1, 1) == typemax(UInt64)-1 -@test cld(typemax(UInt64)-1,-1) == -typemax(UInt64)+1 -@test cld(typemax(UInt64)-2, 1) == typemax(UInt64)-2 -@test cld(typemax(UInt64)-2,-1) == -typemax(UInt64)+2 - -@test signed(cld(unsigned(typemax(Int64))+2, 1)) == typemax(Int64)+2 -@test signed(cld(unsigned(typemax(Int64))+2,-1)) == -typemax(Int64)-2 -@test signed(cld(unsigned(typemax(Int64))+1, 1)) == typemax(Int64)+1 -@test signed(cld(unsigned(typemax(Int64))+1,-1)) == -typemax(Int64)-1 -@test signed(cld(unsigned(typemax(Int64)) , 1)) == typemax(Int64) -@test signed(cld(unsigned(typemax(Int64)) ,-1)) == -typemax(Int64) - -@test signed(cld(typemax(UInt),typemax(Int))) == 3 -@test signed(cld(typemax(UInt),(typemax(Int)>>1)+1)) == 4 -@test signed(cld(typemax(UInt),typemax(Int)>>1)) == 5 -@test signed(cld(typemax(UInt),typemin(Int))) == -1 -@test signed(cld(typemax(UInt),typemin(Int)+1)) == -2 -@test signed(cld(typemax(UInt),typemin(Int)>>1)) == -3 -@test signed(cld(typemax(UInt),(typemin(Int)>>1)+1)) == -4 - -# Test exceptions and special cases -for T in (Int8,Int16,Int32,Int64,Int128, UInt8,UInt16,UInt32,UInt64,UInt128) - @test_throws DivideError div(T(1), T(0)) - @test_throws DivideError fld(T(1), T(0)) - @test_throws DivideError cld(T(1), T(0)) - @test_throws DivideError rem(T(1), T(0)) - @test_throws DivideError mod(T(1), T(0)) -end -for T in (Int8,Int16,Int32,Int64,Int128) - @test_throws DivideError div(typemin(T), T(-1)) - @test_throws DivideError fld(typemin(T), T(-1)) - @test_throws DivideError cld(typemin(T), T(-1)) - @test rem(typemin(T), T(-1)) === T(0) - @test mod(typemin(T), T(-1)) === T(0) -end - -# Test return types -for T in (Int8,Int16,Int32,Int64,Int128, UInt8,UInt16,UInt32,UInt64,UInt128) - z, o = T(0), T(1) - @test typeof(+z) === T - @test typeof(-z) === T - @test typeof(abs(z)) === T - @test typeof(sign(z)) === T - @test typeof(copysign(z,z)) === T - @test typeof(flipsign(z,z)) === T - @test typeof(z+z) === T - @test typeof(z-z) === T - @test typeof(z*z) === T - @test typeof(z÷o) === T - @test typeof(z%o) === T - @test typeof(fld(z,o)) === T - @test typeof(mod(z,o)) === T - @test typeof(cld(z,o)) === T -end - -# issue #4156 -@test fld(1.4,0.35667494393873234) == 3.0 -@test div(1.4,0.35667494393873234) == 3.0 -@test fld(0.3,0.01) == 29.0 -@test div(0.3,0.01) == 29.0 -# see https://github.com/JuliaLang/julia/issues/3127 - -# issue #8831 -@test rem(prevfloat(1.0),1.0) == prevfloat(1.0) -@test mod(prevfloat(1.0),1.0) == prevfloat(1.0) - -# issue #3046 -@test mod(Int64(2),typemax(Int64)) == 2 - -# things related to floating-point epsilon -@test eps() == eps(Float64) -@test eps(Float64) == eps(1.0) -@test eps(Float64) == eps(1.5) -@test eps(Float32) == eps(1f0) -@test eps(float(0)) == 5e-324 -@test eps(-float(0)) == 5e-324 -@test eps(nextfloat(float(0))) == 5e-324 -@test eps(-nextfloat(float(0))) == 5e-324 -@test eps(realmin()) == 5e-324 -@test eps(-realmin()) == 5e-324 -@test eps(realmax()) == 2.0^(1023-52) -@test eps(-realmax()) == 2.0^(1023-52) -@test isnan(eps(NaN)) -@test isnan(eps(Inf)) -@test isnan(eps(-Inf)) - -@test .1+.1+.1 != .3 -@test .1+.1+.1 ≈ .3 -@test .1+.1+.1-.3 ≉ 0 -@test .1+.1+.1-.3 ≈ 0 atol=eps(.3) -@test 1.1 ≈ 1.1f0 - -@test div(1e50,1) == 1e50 -@test fld(1e50,1) == 1e50 -@test cld(1e50,1) == 1e50 - -# rounding difficult values - -for x = 2^53-10:2^53+10 - y = Float64(x) - i = trunc(Int64,y) - @test Int64(trunc(y)) == i - @test Int64(round(y)) == i - @test Int64(floor(y)) == i - @test Int64(ceil(y)) == i - - @test round(Int64,y) == i - @test floor(Int64,y) == i - @test ceil(Int64,y) == i -end - -for x = 2^24-10:2^24+10 - y = Float32(x) - i = trunc(Int,y) - @test Int(trunc(y)) == i - @test Int(round(y)) == i - @test Int(floor(y)) == i - @test Int(ceil(y)) == i - @test round(Int,y) == i - @test floor(Int,y) == i - @test ceil(Int,y) == i -end - -# rounding vectors -let ≈(x,y) = x==y && typeof(x)==typeof(y) - for t in [Float32,Float64] - # try different vector lengths - for n in [0,3,255,256] - r = (1:n)-div(n,2) - y = t[x/4 for x in r] - @test trunc.(y) ≈ t[div(i,4) for i in r] - @test floor.(y) ≈ t[i>>2 for i in r] - @test ceil.(y) ≈ t[(i+3)>>2 for i in r] - @test round.(y) ≈ t[(i+1+isodd(i>>2))>>2 for i in r] - @test broadcast(x -> round(x, RoundNearestTiesAway), y) ≈ t[(i+1+(i>=0))>>2 for i in r] - @test broadcast(x -> round(x, RoundNearestTiesUp), y) ≈ t[(i+2)>>2 for i in r] - end - end -end - -@test_throws InexactError round(Int,Inf) -@test_throws InexactError round(Int,NaN) -@test round(Int,2.5) == 2 -@test round(Int,1.5) == 2 -@test round(Int,-2.5) == -2 -@test round(Int,-1.5) == -2 -@test round(Int,2.5,RoundNearestTiesAway) == 3 -@test round(Int,1.5,RoundNearestTiesAway) == 2 -@test round(Int,2.5,RoundNearestTiesUp) == 3 -@test round(Int,1.5,RoundNearestTiesUp) == 2 -@test round(Int,-2.5,RoundNearestTiesAway) == -3 -@test round(Int,-1.5,RoundNearestTiesAway) == -2 -@test round(Int,-2.5,RoundNearestTiesUp) == -2 -@test round(Int,-1.5,RoundNearestTiesUp) == -1 -@test round(Int,-1.9) == -2 -@test_throws InexactError round(Int64, 9.223372036854776e18) -@test round(Int64, 9.223372036854775e18) == 9223372036854774784 -@test_throws InexactError round(Int64, -9.223372036854778e18) -@test round(Int64, -9.223372036854776e18) == typemin(Int64) -@test_throws InexactError round(UInt64, 1.8446744073709552e19) -@test round(UInt64, 1.844674407370955e19) == 0xfffffffffffff800 -@test_throws InexactError round(Int32, 2.1474836f9) -@test round(Int32, 2.1474835f9) == 2147483520 -@test_throws InexactError round(Int32, -2.147484f9) -@test round(Int32, -2.1474836f9) == typemin(Int32) -@test_throws InexactError round(UInt32, 4.2949673f9) -@test round(UInt32, 4.294967f9) == 0xffffff00 - - -for Ti in [Int,UInt] - for Tf in [Float16,Float32,Float64] - - @test round(Ti,Tf(-0.0)) == 0 - @test round(Ti,Tf(-0.0),RoundNearestTiesAway) == 0 - @test round(Ti,Tf(-0.0),RoundNearestTiesUp) == 0 - - @test round(Ti, Tf(0.5)) == 0 - @test round(Ti, Tf(0.5), RoundNearestTiesAway) == 1 - @test round(Ti, Tf(0.5), RoundNearestTiesUp) == 1 - - @test round(Ti, prevfloat(Tf(0.5))) == 0 - @test round(Ti, prevfloat(Tf(0.5)), RoundNearestTiesAway) == 0 - @test round(Ti, prevfloat(Tf(0.5)), RoundNearestTiesUp) == 0 - - @test round(Ti, nextfloat(Tf(0.5))) == 1 - @test round(Ti, nextfloat(Tf(0.5)), RoundNearestTiesAway) == 1 - @test round(Ti, nextfloat(Tf(0.5)), RoundNearestTiesUp) == 1 - - @test round(Ti, Tf(-0.5)) == 0 - @test round(Ti, Tf(-0.5), RoundNearestTiesUp) == 0 - - @test round(Ti, nextfloat(Tf(-0.5))) == 0 - @test round(Ti, nextfloat(Tf(-0.5)), RoundNearestTiesAway) == 0 - @test round(Ti, nextfloat(Tf(-0.5)), RoundNearestTiesUp) == 0 - - if Ti <: Signed - @test round(Ti, Tf(-0.5), RoundNearestTiesAway) == -1 - @test round(Ti, prevfloat(Tf(-0.5))) == -1 - @test round(Ti, prevfloat(Tf(-0.5)), RoundNearestTiesAway) == -1 - @test round(Ti, prevfloat(Tf(-0.5)), RoundNearestTiesUp) == -1 - else - @test_throws InexactError round(Ti, Tf(-0.5), RoundNearestTiesAway) - @test_throws InexactError round(Ti, prevfloat(Tf(-0.5))) - @test_throws InexactError round(Ti, prevfloat(Tf(-0.5)), RoundNearestTiesAway) - @test_throws InexactError round(Ti, prevfloat(Tf(-0.5)), RoundNearestTiesUp) - end - end -end - -# numbers that can't be rounded by trunc(x+0.5) -@test round(Int64, 2.0^52 + 1) == 4503599627370497 -@test round(Int32, 2.0f0^23 + 1) == 8388609 - -# binary literals - -@test 0b1010101 == 0x55 -@test isa(0b00000000,UInt8) -@test isa(0b000000000,UInt16) -@test isa(0b0000000000000000,UInt16) -@test isa(0b00000000000000000,UInt32) -@test isa(0b00000000000000000000000000000000,UInt32) -@test isa(0b000000000000000000000000000000000,UInt64) -@test isa(0b0000000000000000000000000000000000000000000000000000000000000000,UInt64) -@test isa(0b00000000000000000000000000000000000000000000000000000000000000000,UInt128) -@test isa(0b00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000,UInt128) -# remove BigInt unsigned integer literals #11105 -@test_throws ParseError parse("0b000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000") -@test isa(0b11111111,UInt8) -@test isa(0b111111111,UInt16) -@test isa(0b1111111111111111,UInt16) -@test isa(0b11111111111111111,UInt32) -@test isa(0b11111111111111111111111111111111,UInt32) -@test isa(0b111111111111111111111111111111111,UInt64) -@test isa(0b1111111111111111111111111111111111111111111111111111111111111111,UInt64) -@test isa(0b11111111111111111111111111111111111111111111111111111111111111111,UInt128) -@test isa(0b11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111,UInt128) -# remove BigInt unsigned integer literals #11105 -@test_throws ParseError parse("0b111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111") - -# octal literals - -@test 0o10 == 0x8 -@test 0o100 == 0x40 -@test 0o1000 == 0x200 -@test 0o724 == 0x1d4 -@test isa(0o377,UInt8) -@test isa(0o00,UInt8) -@test isa(0o000,UInt16) -@test isa(0o00000,UInt16) -@test isa(0o000000,UInt32) -@test isa(0o0000000000,UInt32) -@test isa(0o00000000000,UInt64) -@test isa(0o000000000000000000000,UInt64) -@test isa(0o0000000000000000000000,UInt128) -@test isa(0o000000000000000000000000000000000000000000,UInt128) -# remove BigInt unsigned integer literals #11105 -@test_throws ParseError parse("0o0000000000000000000000000000000000000000000") -@test isa(0o11,UInt8) -@test isa(0o111,UInt8) -@test isa(0o11111,UInt16) -@test isa(0o111111,UInt16) -@test isa(0o1111111111,UInt32) -@test isa(0o11111111111,UInt32) -@test isa(0o111111111111111111111,UInt64) -@test isa(0o1111111111111111111111,UInt64) -@test isa(0o111111111111111111111111111111111111111111,UInt128) -@test isa(0o1111111111111111111111111111111111111111111,UInt128) -# remove BigInt unsigned integer literals #11105 -@test_throws ParseError parse("0o11111111111111111111111111111111111111111111") - -# hexadecimal literals - -@test isa(0x00,UInt8) -@test isa(0x000,UInt16) -@test isa(0x0000,UInt16) -@test isa(0x00000,UInt32) -@test isa(0x00000000,UInt32) -@test isa(0x000000000,UInt64) -@test isa(0x0000000000000000,UInt64) -@test isa(0x00000000000000000,UInt128) -@test isa(0x00000000000000000000000000000000,UInt128) -# remove BigInt unsigned integer literals #11105 -@test_throws ParseError parse("0x000000000000000000000000000000000") - -@test isa(0x11,UInt8) -@test isa(0x111,UInt16) -@test isa(0x1111,UInt16) -@test isa(0x11111,UInt32) -@test isa(0x11111111,UInt32) -@test isa(0x111111111,UInt64) -@test isa(0x1111111111111111,UInt64) -@test isa(0x11111111111111111,UInt128) -@test isa(0x11111111111111111111111111111111,UInt128) -# remove BigInt unsigned integer literals #11105 -@test_throws ParseError parse("0x111111111111111111111111111111111") - -# "-" is not part of unsigned literals -@test -0x10 == -(0x10) -@test -0b10 == -(0b10) -@test -0o10 == -(0o10) -@test -0x0010 == -(0x0010) -@test -0b0010 == -(0b0010) -@test -0o0010 == -(0o0010) -@test -0x00000000000000001 == -(0x00000000000000001) -@test -0o0000000000000000000001 == -(0o0000000000000000000001) -@test -0b00000000000000000000000000000000000000000000000000000000000000001 == - -(0b00000000000000000000000000000000000000000000000000000000000000001) - -@test isa(-0x00,UInt8) -@test isa(-0x0000000000000000,UInt64) -@test isa(-0x00000000000000000,UInt128) -@test isa(-0x00000000000000000000000000000000,UInt128) -# remove BigInt unsigned integer literals #11105 -@test_throws ParseError parse("-0x000000000000000000000000000000000") - -# Float32 literals -@test isa(1f0,Float32) -@test isa(1.f0,Float32) -@test isa(1.0f0,Float32) -@test 1f0 == 1. -@test isa(1f1,Float32) -@test 1f1 == 10. - -# hexadecimal float literals -@test 0x1p0 === 1. -@test 0x1p1 === 2. -@test 0x.1p0 === 0.0625 -@test 0x.1p1 === 0.125 -@test 0xfp0 === 15. -@test 0xfp1 === 30. -@test 0x.fp0 === 0.9375 -@test 0x.fp1 === 1.875 -@test 0x1.p0 === 1. -@test 0x1.p1 === 2. -@test 0xf.p0 === 15. -@test 0xf.p1 === 30. -@test 0x1.0p0 === 1. -@test 0x1.0p1 === 2. -@test 0x1.1p0 === 1.0625 -@test 0x1.1p1 === 2.125 -@test 0x1.fp0 === 1.9375 -@test 0x1.fp1 === 3.875 -@test 0xf.0p0 === 15. -@test 0xf.0p1 === 30. -@test 0xf.1p0 === 15.0625 -@test 0xf.1p1 === 30.125 -@test 0xf.fp0 === 15.9375 -@test 0xf.fp1 === 31.875 -@test 0x1P0 === 1. -@test 0x1P1 === 2. -@test 0x.1P0 === 0.0625 -@test 0x.1P1 === 0.125 -@test 0xfP0 === 15. -@test 0xfP1 === 30. -@test 0x.fP0 === 0.9375 -@test 0x.fP1 === 1.875 -@test 0x1.P0 === 1. -@test 0x1.P1 === 2. -@test 0xf.P0 === 15. -@test 0xf.P1 === 30. -@test 0x1.0P0 === 1. -@test 0x1.0P1 === 2. -@test 0x1.1P0 === 1.0625 -@test 0x1.1P1 === 2.125 -@test 0x1.fP0 === 1.9375 -@test 0x1.fP1 === 3.875 -@test 0xf.0P0 === 15. -@test 0xf.0P1 === 30. -@test 0xf.1P0 === 15.0625 -@test 0xf.1P1 === 30.125 -@test 0xf.fP0 === 15.9375 -@test 0xf.fP1 === 31.875 - -@test -0x1.0p2 === -4.0 - -# eps / realmin / realmax -@test 0x1p-52 == eps() -@test 0x1p-52 + 1 != 1 -@test 0x1p-53 + 1 == 1 -@test 0x1p-1022 == realmin() -@test 0x1.fffffffffffffp1023 == realmax() -@test isinf(nextfloat(0x1.fffffffffffffp1023)) - -# custom rounding and significant-digit ops -function approx_eq(a, b, tol) - abs(a - b) < tol -end -approx_eq(a, b) = approx_eq(a, b, 1e-6) -# rounding to digits relative to the decimal point -@test approx_eq(round(pi,0), 3.) -@test approx_eq(round(pi,1), 3.1) -@test approx_eq(round(10*pi,-1), 30.) -@test round(.1,0) == 0. -@test round(-.1,0) == -0. -@test isnan(round(NaN, 2)) -@test isinf(round(Inf,2)) -@test isinf(round(-Inf,2)) -# round vs trunc vs floor vs ceil -@test approx_eq(round(123.456,1), 123.5) -@test approx_eq(round(-123.456,1), -123.5) -@test approx_eq(trunc(123.456,1), 123.4) -@test approx_eq(trunc(-123.456,1), -123.4) -@test approx_eq(ceil(123.456,1), 123.5) -@test approx_eq(ceil(-123.456,1), -123.4) -@test approx_eq(floor(123.456,1), 123.4) -@test approx_eq(floor(-123.456,1), -123.5) -# rounding with too much (or too few) precision -for x in (12345.6789, 0, -12345.6789) - y = float(x) - @test y == trunc(x, 1000) - @test y == round(x, 1000) - @test y == floor(x, 1000) - @test y == ceil(x, 1000) -end -x = 12345.6789 -@test 0.0 == trunc(x, -1000) -@test 0.0 == round(x, -1000) -@test 0.0 == floor(x, -1000) -@test Inf == ceil(x, -1000) -x = -12345.6789 -@test -0.0 == trunc(x, -1000) -@test -0.0 == round(x, -1000) -@test -Inf == floor(x, -1000) -@test -0.0 == ceil(x, -1000) -x = 0.0 -@test 0.0 == trunc(x, -1000) -@test 0.0 == round(x, -1000) -@test 0.0 == floor(x, -1000) -@test 0.0 == ceil(x, -1000) -# rounding in other bases -@test approx_eq(round(pi,2,2), 3.25) -@test approx_eq(round(pi,3,2), 3.125) -@test approx_eq(round(pi,3,5), 3.144) -# vectorized trunc/round/floor/ceil with digits/base argument -a = rand(2, 2, 2) -for f in (round, trunc, floor, ceil) - @test f.(a[:, 1, 1], 2) == map(x->f(x, 2), a[:, 1, 1]) - @test f.(a[:, :, 1], 2) == map(x->f(x, 2), a[:, :, 1]) - @test f.(a, 9, 2) == map(x->f(x, 9, 2), a) - @test f.(a[:, 1, 1], 9, 2) == map(x->f(x, 9, 2), a[:, 1, 1]) - @test f.(a[:, :, 1], 9, 2) == map(x->f(x, 9, 2), a[:, :, 1]) - @test f.(a, 9, 2) == map(x->f(x, 9, 2), a) -end -# significant digits (would be nice to have a smart vectorized -# version of signif) -@test approx_eq(signif(123.456,1), 100.) -@test approx_eq(signif(123.456,3), 123.) -@test approx_eq(signif(123.456,5), 123.46) -@test approx_eq(signif(123.456,8,2), 123.5) -@test signif(0.0, 1) === 0.0 -@test signif(-0.0, 1) === -0.0 -@test signif(1.2, 2) === 1.2 -@test signif(1.0, 6) === 1.0 -@test signif(0.6, 1) === 0.6 -@test signif(7.262839104539736, 2) === 7.3 -@test isinf(signif(Inf, 3)) -@test isnan(signif(NaN, 3)) -@test signif(1.12312, 1000) === 1.12312 -@test signif(Float32(7.262839104539736), 3) === Float32(7.26) -@test signif(Float32(7.262839104539736), 4) === Float32(7.263) -@test signif(Float32(1.2), 3) === Float32(1.2) -@test signif(Float32(1.2), 5) === Float32(1.2) -@test signif(Float16(0.6), 2) === Float16(0.6) -@test signif(Float16(1.1), 70) === Float16(1.1) - -# issue #1308 -@test hex(~UInt128(0)) == "f"^32 -@test (~0)%UInt128 == ~UInt128(0) -@test Int128(~0) == ~Int128(0) - -# issue 1552 -@test isa(rationalize(Int8, float(pi)), Rational{Int8}) -@test rationalize(Int8, float(pi)) == 22//7 -@test rationalize(Int64, 0.957762604052997) == 42499549//44373782 -@test rationalize(Int16, 0.929261477046077) == 11639//12525 -@test rationalize(Int16, 0.2264705884044309) == 77//340 -@test rationalize(Int16, 0.39999899264235683) == 2//5 -@test rationalize(Int16, 1.1264233500618559e-5) == 0//1 -@test rationalize(UInt16, 0.6666652791223875) == 2//3 -@test rationalize(Int8, 0.9374813124660655) == 15//16 -@test rationalize(Int8, 0.003803032342443835) == 0//1 - -# issue 3412 -@test convert(Rational{Int32},0.5) === Int32(1)//Int32(2) - -# issue 6712 -@test convert(Rational{BigInt},Float64(pi)) == Float64(pi) -@test convert(Rational{BigInt},big(pi)) == big(pi) - -@test convert(Rational,0.0) == 0 -@test convert(Rational,-0.0) == 0 -@test convert(Rational,zero(BigFloat)) == 0 -@test convert(Rational,-zero(BigFloat)) == 0 -@test convert(Rational{BigInt},0.0) == 0 -@test convert(Rational{BigInt},-0.0) == 0 -@test convert(Rational{BigInt},zero(BigFloat)) == 0 -@test convert(Rational{BigInt},-zero(BigFloat)) == 0 -@test convert(Rational{BigInt},5e-324) == 5e-324 -@test convert(Rational{BigInt},realmin(Float64)) == realmin(Float64) -@test convert(Rational{BigInt},realmax(Float64)) == realmax(Float64) - -@test isa(convert(Float64, big(1)//2), Float64) - -# issue 16513 -@test convert(Rational{Int32}, pi) == 1068966896 // 340262731 -@test convert(Rational{Int64}, pi) == 2646693125139304345 // 842468587426513207 -@test convert(Rational{Int128}, pi) == 60728338969805745700507212595448411044 // 19330430665609526556707216376512714945 -@test_throws ArgumentError convert(Rational{BigInt}, pi) - -# issue 5935 -@test rationalize(Int8, nextfloat(0.1)) == 1//10 -@test rationalize(Int64, nextfloat(0.1)) == 300239975158034//3002399751580339 -@test rationalize(Int128,nextfloat(0.1)) == 300239975158034//3002399751580339 -@test rationalize(BigInt,nextfloat(0.1)) == 300239975158034//3002399751580339 -@test rationalize(Int8, nextfloat(0.1),tol=0.5eps(0.1)) == 1//10 -@test rationalize(Int64, nextfloat(0.1),tol=0.5eps(0.1)) == 379250494936463//3792504949364629 -@test rationalize(Int128,nextfloat(0.1),tol=0.5eps(0.1)) == 379250494936463//3792504949364629 -@test rationalize(BigInt,nextfloat(0.1),tol=0.5eps(0.1)) == 379250494936463//3792504949364629 -@test rationalize(Int8, nextfloat(0.1),tol=1.5eps(0.1)) == 1//10 -@test rationalize(Int64, nextfloat(0.1),tol=1.5eps(0.1)) == 1//10 -@test rationalize(Int128,nextfloat(0.1),tol=1.5eps(0.1)) == 1//10 -@test rationalize(BigInt,nextfloat(0.1),tol=1.5eps(0.1)) == 1//10 -@test rationalize(BigInt,nextfloat(parse(BigFloat,"0.1")),tol=1.5eps(big(0.1))) == 1//10 -@test rationalize(Int64, nextfloat(0.1),tol=0) == 7205759403792795//72057594037927936 -@test rationalize(Int128,nextfloat(0.1),tol=0) == 7205759403792795//72057594037927936 -@test rationalize(BigInt,nextfloat(0.1),tol=0) == 7205759403792795//72057594037927936 - -@test rationalize(Int8, prevfloat(0.1)) == 1//10 -@test rationalize(Int64, prevfloat(0.1)) == 1//10 -@test rationalize(Int128,prevfloat(0.1)) == 1//10 -@test rationalize(BigInt,prevfloat(0.1)) == 1//10 -@test rationalize(BigInt,prevfloat(parse(BigFloat,"0.1"))) == 1//10 -@test rationalize(Int64, prevfloat(0.1),tol=0) == 7205759403792793//72057594037927936 -@test rationalize(Int128,prevfloat(0.1),tol=0) == 7205759403792793//72057594037927936 -@test rationalize(BigInt,prevfloat(0.1),tol=0) == 7205759403792793//72057594037927936 - -@test rationalize(BigInt,nextfloat(parse(BigFloat,"0.1")),tol=0) == 46316835694926478169428394003475163141307993866256225615783033603165251855975//463168356949264781694283940034751631413079938662562256157830336031652518559744 - - -@test rationalize(Int8, 200f0) == 1//0 -@test rationalize(Int8, -200f0) == -1//0 - -@test [rationalize(1pi,tol=0.1^n) for n=1:10] == [ - 16//5 - 22//7 - 201//64 - 333//106 - 355//113 - 355//113 - 75948//24175 - 100798//32085 - 103993//33102 - 312689//99532 ] - -# issue 16311 -rationalize(nextfloat(0.0)) == 0//1 - -# rational-exponent promotion rules (issue #3155): -@test 2.0f0^(1//3) == 2.0f0^(1.0f0/3) -@test 2^(1//3) == 2^(1/3) -# no loss of precision for rational powers (issue #18114) -@test BigFloat(2)^(BigFloat(1)/BigFloat(3)) == BigFloat(2)^(1//3) - -# large shift amounts -@test Int32(-1)>>31 == -1 -@test Int32(-1)>>32 == -1 -@test Int32(-1)>>33 == -1 -@test 10>>64 == 0 -@test 10>>>64 == 0 -@test 10<<64 == 0 - -# issue #3520 - certain int literals on 32-bit systems -@test -536870913 === -536870912-1 - -# overflow in rational comparison -@test 3//2 < typemax(Int) -@test 3//2 <= typemax(Int) - -# check gcd and related functions against GMP -for T in (Int32,Int64), ii = -20:20, jj = -20:20 - i::T, j::T = ii, jj - local d = gcd(i,j) - @test d >= 0 - @test lcm(i,j) >= 0 - local ib = big(i) - local jb = big(j) - @test d == gcd(ib,jb) - @test lcm(i,j) == lcm(ib,jb) - @test gcdx(i,j) == gcdx(ib,jb) - if j == 0 || d != 1 - @test_throws DomainError invmod(i,j) - @test_throws DomainError invmod(ib,jb) - else - n = invmod(i,j) - @test div(n, j) == 0 - @test n == invmod(ib,jb) - @test mod(n*i,j) == mod(1,j) - end -end - -# check powermod function against few types (in particular [U]Int128 and BigInt) -for i = -10:10, p = 0:5, m = -10:10 - m == 0 && continue - x = powermod(i, p, m) - for T in [Int32, Int64, Int128, UInt128, BigInt] - T <: Unsigned && m < 0 && continue - let xT = powermod(i, p, T(m)) - @test x == xT - @test isa(xT, T) - end - T <: Unsigned && i < 0 && continue - @test x == mod(T(i)^p, T(m)) - end -end - -# with m==1 should give 0 -@test powermod(1,0,1) == 0 -@test powermod(1,0,big(1)) == 0 -@test powermod(1,0,-1) == 0 -@test powermod(1,0,big(-1)) == 0 -# divide by zero error -@test_throws DivideError powermod(1,0,0) -@test_throws DivideError powermod(1,0,big(0)) -# negative powers perform modular inversion before exponentiation -@test powermod(1, -1, 1) == 0 -@test powermod(1, -1, big(1)) == 0 -# additional BigInt powermod tests -@test powermod(0, 1, big(6)) == 0 -@test powermod(1, 0, big(6)) == 1 -@test powermod(big(6), big(6), big(6)) == 0 -@test powermod(10, 50, big(10)^50 - 1) == 1 - -@test powermod(-1, 1, big(6)) == 5 -@test powermod(-1, 0, big(6)) == 1 -@test powermod(-1, -1, big(6)) == 5 -@test powermod(-1, 1, big(-6)) == -1 -@test powermod(-1, 0, big(-6)) == -5 -@test powermod(-1, -1, big(-6)) == -1 - -@test_throws DivideError powermod(2, -1, big(6)) -@test_throws DivideError powermod(-2, -1, big(6)) - -# other divide-by-zero errors -@test_throws DivideError div(1,0) -@test_throws DivideError rem(1,0) -@test_throws DivideError divrem(1,0) -@test_throws DivideError fld(1,0) -@test_throws DivideError mod(1,0) -@test_throws DivideError fldmod(1,0) -@test_throws DivideError cld(1,0) - -@test_throws DivideError div(-1,0) -@test_throws DivideError rem(-1,0) -@test_throws DivideError divrem(-1,0) -@test_throws DivideError fld(-1,0) -@test_throws DivideError mod(-1,0) -@test_throws DivideError fldmod(-1,0) -@test_throws DivideError cld(-1,0) - -@test_throws DivideError div(UInt(1),UInt(0)) -@test_throws DivideError rem(UInt(1),UInt(0)) -@test_throws DivideError divrem(UInt(1),UInt(0)) -@test_throws DivideError fld(UInt(1),UInt(0)) -@test_throws DivideError mod(UInt(1),UInt(0)) -@test_throws DivideError fldmod(UInt(1),UInt(0)) -@test_throws DivideError cld(UInt(1),UInt(0)) - -@test_throws DivideError div(typemin(Int),-1) -@test_throws DivideError fld(typemin(Int),-1) -@test_throws DivideError cld(typemin(Int),-1) -@test_throws DivideError divrem(typemin(Int),-1) -@test_throws DivideError fldmod(typemin(Int),-1) -@test rem(typemin(Int),-1) == 0 -@test mod(typemin(Int),-1) == 0 - -# prevpow2/nextpow2: -@test nextpow2(0) == prevpow2(0) == 0 -for i = -2:2 - @test nextpow2(i) == prevpow2(i) == i -end -@test nextpow2(56789) == -nextpow2(-56789) == 65536 -@test prevpow2(56789) == -prevpow2(-56789) == 32768 -for i = -100:100 - @test nextpow2(i) == nextpow2(big(i)) - @test prevpow2(i) == prevpow2(big(i)) -end -for T in (Int8, UInt8, Int16, UInt16, Int32, UInt32, Int64, UInt64) - @test nextpow2(T(42)) === T(64) - @test prevpow2(T(42)) === T(32) -end - -@test ispow2(64) -@test !ispow2(42) -@test !ispow2(~typemax(Int)) - -@test nextpow(2,1) == 1 -@test prevpow(2,1) == 1 -@test nextpow(3,243) == 243 -@test prevpow(3,243) == 243 -@test nextpow(3,241) == 243 -@test prevpow(3,244) == 243 -for a = -1:1 - @test_throws DomainError nextpow(a, 2) - @test_throws DomainError prevpow(a, 2) -end -@test_throws DomainError nextpow(2,0) -@test_throws DomainError prevpow(2,0) - -@test_throws ArgumentError nextprod([2,3,5],Int128(typemax(Int))+1) -@test nextprod([2,3,5],30) == 30 -@test nextprod([2,3,5],33) == 36 - -@test nextfloat(0.0) == 5.0e-324 -@test prevfloat(0.0) == -5.0e-324 -@test nextfloat(-0.0) == 5.0e-324 -@test prevfloat(-0.0) == -5.0e-324 -@test nextfloat(-5.0e-324) === -0.0 -@test prevfloat(5.0e-324) == 0.0 -@test nextfloat(-1.0) > -1.0 -@test prevfloat(-1.0) < -1.0 -@test nextfloat(nextfloat(0.0),-2) == -5.0e-324 -@test nextfloat(prevfloat(0.0), 2) == 5.0e-324 -@test nextfloat(Inf) === Inf -@test prevfloat(-Inf) === -Inf -@test isequal(nextfloat(NaN), NaN) -@test nextfloat(Inf32) === Inf32 -@test prevfloat(-Inf32) === -Inf32 -@test isequal(nextfloat(NaN32), NaN32) - -# issue #16206 -@test prevfloat(Inf) == 1.7976931348623157e308 -@test prevfloat(Inf32) == 3.4028235f38 -@test nextfloat(prevfloat(Inf)) == Inf -@test nextfloat(prevfloat(Inf),2) == Inf -@test nextfloat(1.0,typemax(Int64)) == Inf -@test nextfloat(0.0,typemin(Int64)) == -Inf -@test nextfloat(1f0,typemin(Int64)) == -Inf32 -@test nextfloat(1.0,typemax(UInt64)) == Inf -@test nextfloat(1.0,typemax(UInt128)) == Inf -@test nextfloat(1.0,big(2)^67) == Inf -@test nextfloat(1.0,-big(2)^67) == -Inf - -for F in (Float16,Float32,Float64) - @test reinterpret(Unsigned,one(F)) === Base.exponent_one(F) - @test reinterpret(Signed,one(F)) === signed(Base.exponent_one(F)) -end - - -@test eps(realmax(Float64)) == 1.99584030953472e292 -@test eps(-realmax(Float64)) == 1.99584030953472e292 - -# modular multiplicative inverses of odd numbers via exponentiation - -for T = (UInt8,Int8,UInt16,Int16,UInt32,Int32,UInt64,Int64,UInt128,Int128) - for n = 1:2:1000 - @test n*(n^typemax(T)) & typemax(T) == 1 - n = rand(T) | one(T) - @test n*(n^typemax(T)) == 1 - end -end - -@test false*pi === 0.0 -@test pi*false === 0.0 -@test true*pi === Float64(pi) -@test pi*true === Float64(pi) - -# issue #5492 -@test -0.0 + false === -0.0 - -# issue #5881 -@test bits(true) == "00000001" -@test bits(false) == "00000000" - -# edge cases of intrinsics -let g() = sqrt(-1.0) - @test_throws DomainError sqrt(-1.0) -end -@test sqrt(NaN) === NaN -let g() = sqrt(NaN) - @test g() === NaN -end -let g(x) = sqrt(x) - @test g(NaN) === NaN -end - -# widen -@test widen(1.5f0) === 1.5 -@test widen(Int32(42)) === Int64(42) -@test widen(Int8) === Int32 -@test widen(Int64) === Int128 -@test widen(Float32) === Float64 -@test widen(Float16) === Float32 -## Note: this should change to e.g. Float128 at some point -@test widen(Float64) === BigFloat -@test widen(BigInt) === BigInt - -@test widemul(typemax(Int64),typemax(Int64)) == 85070591730234615847396907784232501249 -@test typeof(widemul(Int64(1),UInt64(1))) == Int128 -@test typeof(widemul(UInt64(1),Int64(1))) == Int128 -@test typeof(widemul(Int128(1),UInt128(1))) == BigInt -@test typeof(widemul(UInt128(1),Int128(1))) == BigInt - -# .// -@test [1,2,3] // 4 == [1//4, 2//4, 3//4] -@test [1,2,3] .// [4,5,6] == [1//4, 2//5, 3//6] -@test [1+2im,3+4im] .// [5,6] == [(1+2im)//5,(3+4im)//6] -@test [1//3+2im,3+4im] .// [5,6] == [(1//3+2im)//5,(3+4im)//6] - -# issue #7441 -@test_throws InexactError Int32(2.0^50) - -@test_throws InexactError round(UInt8, 255.5) -@test round(UInt8, 255.4) === 0xff - -@test_throws InexactError round(Int16, -32768.7) -@test round(Int16, -32768.1) === Int16(-32768) - -# issue #7508 -@test_throws ErrorException reinterpret(Int, 0x01) - -# issue #12832 -@test_throws ErrorException reinterpret(Float64, Complex{Int64}(1)) -@test_throws ErrorException reinterpret(Float64, Complex64(1)) -@test_throws ErrorException reinterpret(Complex64, Float64(1)) -@test_throws ErrorException reinterpret(Int32, false) - -# issue #41 -ndigf(n) = Float64(log(Float32(n))) -@test Float64(log(Float32(256))) == ndigf(256) == 5.545177459716797 - -# cmp on unsigned integers (see commit 24b236321e03c6d9b8cb91a450f567256a793196) -@test cmp(0x77777777,0x88888888) == -1 -@test cmp(0x3959dcc5d7fd177b67df4e10bc350850, 0xd63d5b1183221b0a9e38c6809b33cdec) == -1 - -# issue #7911 -@test sum([Int128(1) Int128(2)]) == Int128(3) - -# digits and digits! -@test digits(24, 2) == [0, 0, 0, 1, 1] -@test digits(24, 2, 3) == [0, 0, 0, 1, 1] -@test digits(24, 2, 7) == [0, 0, 0, 1, 1, 0, 0] -@test digits(100) == [0, 0, 1] -@test digits(BigInt(2)^128, 2) == [zeros(128); 1] -let a = zeros(Int, 3) - digits!(a, 50) - @test a == [0, 5, 0] - digits!(a, 9, 2) - @test a == [1, 0, 0] - digits!(a, 7, 2) - @test a == [1, 1, 1] -end - -# Fill a pre allocated 2x4 matrix -let a = zeros(Int,(2,4)) - for i in 0:3 - digits!(view(a,:,i+1),i,2) - end - @test a == [0 1 0 1; - 0 0 1 1] -end -@test_throws InexactError convert(UInt8, 256) -@test_throws InexactError convert(UInt, -1) -@test_throws InexactError convert(Int, big(2)^100) -@test_throws InexactError convert(Int16, big(2)^100) -@test_throws InexactError convert(Int, typemax(UInt)) - -# issue #9789 -@test_throws InexactError convert(Int8, typemax(UInt64)) -@test_throws InexactError convert(Int16, typemax(UInt64)) -@test_throws InexactError convert(Int, typemax(UInt64)) - -# issue #14549 -for T in (Int8, Int16, UInt8, UInt16) - for F in (Float32,Float64) - @test_throws InexactError convert(T, F(200000.0)) - end -end - -let x = big(-0.0) - @test signbit(x) && !signbit(abs(x)) -end - - -@test all(x -> (m=mod1(x,3); 0<m<=3), -5:+5) -@test all(x -> x == (fld1(x,3)-1)*3 + mod1(x,3), -5:+5) -@test all(x -> fldmod1(x,3) == (fld1(x,3), mod1(x,3)), -5:+5) -#Issue #5570 -@test map(x -> Int(mod1(UInt(x),UInt(5))), 0:15) == [5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5] - -# Issue #9618: errors thrown by large exponentiations -@test_throws DomainError big(2)^-(big(typemax(UInt))+1) -@test_throws OverflowError big(2)^(big(typemax(UInt))+1) -@test 0==big(0)^(big(typemax(UInt))+1) - -# bswap (issue #9726) -@test bswap(0x0002) === 0x0200 -@test bswap(0x01020304) === 0x04030201 -@test reinterpret(Float64,bswap(0x000000000000f03f)) === 1.0 -@test reinterpret(Float32,bswap(0x0000c03f)) === 1.5f0 -@test bswap(reinterpret(Float64,0x000000000000f03f)) === 1.0 -@test bswap(reinterpret(Float32,0x0000c03f)) === 1.5f0 -zbuf = IOBuffer([0xbf, 0xc0, 0x00, 0x00, 0x40, 0x20, 0x00, 0x00, - 0x40, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0xc0, 0x12, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]) -z1 = read(zbuf, Complex64) -z2 = read(zbuf, Complex128) -@test bswap(z1) === -1.5f0 + 2.5f0im -@test bswap(z2) === 3.5 - 4.5im - -#isreal(x::Real) = true -for x in [1.23, 7, e, 4//5] #[FP, Int, Irrational, Rat] - @test isreal(x) == true -end - -function allsubtypes!(m::Module, x::DataType, sts::Set) - for s in names(m, true) - if isdefined(m, s) && !Base.isdeprecated(m, s) - t = getfield(m, s) - if isa(t, Type) && t <: x && t != Union{} - push!(sts, t) - elseif isa(t, Module) && t !== m && module_name(t) === s && module_parent(t) === m - allsubtypes!(t, x, sts) - end - end - end -end - -let number_types = Set() - allsubtypes!(Base, Number, number_types) - allsubtypes!(Core, Number, number_types) - - @test !isempty(number_types) - - #eltype{T<:Number}(::Type{T}) = T - for T in number_types - @test eltype(T) == T - end - - #ndims{T<:Number}(::Type{T}) = 0 - for x in number_types - @test ndims(x) == 0 - end -end - -#getindex(x::Number) = x -for x in [1.23, 7, e, 4//5] #[FP, Int, Irrational, Rat] - @test getindex(x) == x - @test getindex(x, 1, 1) == x -end - -#getindex(x::Number,-1) throws BoundsError -#getindex(x::Number,0) throws BoundsError -#getindex(x::Number,2) throws BoundsError -#getindex(x::Array,-1) throws BoundsError -#getindex(x::Array,0 throws BoundsError -#getindex(x::Array,length(x::Array)+1) throws BoundsError -for x in [1.23, 7, e, 4//5] #[FP, Int, Irrational, Rat] - @test_throws BoundsError getindex(x,-1) - @test_throws BoundsError getindex(x,0) - @test_throws BoundsError getindex(x,2) - @test_throws BoundsError getindex([x x],-1) - @test_throws BoundsError getindex([x x],0) - @test_throws BoundsError getindex([x x],length([x,x])+1) - @test_throws BoundsError getindex(x, 1, 0) -end - -# copysign(x::Real, y::Real) = ifelse(signbit(x)!=signbit(y), -x, x) -# flipsign(x::Real, y::Real) = ifelse(signbit(y), -x, x) -for x in [1.23, 7, e, 4//5] - for y in [1.23, 7, e, 4//5] - @test copysign(x, y) == x - @test copysign(x, -y) == -x - @test copysign(-x, y) == x - @test copysign(-x, -y) == -x - @test flipsign(x, y) == x - @test flipsign(x, -y) == -x - @test flipsign(-x, y) == -x - @test flipsign(-x, -y) == x - end -end - -#angle(z::Real) = atan2(zero(z), z) -#function only returns two values, depending on sign -@test angle(10) == 0.0 -@test angle(-10) == 3.141592653589793 - -#in(x::Number, y::Number) = x == y -@test in(3,3) == true #Int -@test in(2.0,2.0) == true #FP -@test in(e,e) == true #Const -@test in(4//5,4//5) == true #Rat -@test in(1+2im, 1+2im) == true #Imag -@test in(3, 3.0) == true #mixed - -#map(f::Callable, x::Number, ys::Number...) = f(x) -@test map(sin, 3) == sin(3) -@test map(cos, 3) == cos(3) -@test map(tan, 3) == tan(3) -@test map(log, 3) == log(3) -@test map(copysign, 1.0, -2.0) == -1.0 -@test map(muladd, 2, 3, 4) == 10 - -@test_throws InexactError convert(UInt8, big(300)) - -# issue #10311 -let n = 1 - @test n//n + n//big(n)*im == 1//1 + 1//1*im -end - -# BigInt - (small negative) is tricky because gmp only has gmpz_sub_ui -@test big(-200) - Int8(-128) == -72 - -# n % Type -for T in Any[Int16, Int32, UInt32, Int64, UInt64, BigInt] - if !(T <: Unsigned) - @test convert(T, -200) % Int8 === Int8(56) - @test convert(T, -200) % UInt8 === 0x38 - @test convert(T, -300) % Int8 === Int8(-44) - @test convert(T, -300) % UInt8 === 0xd4 - @test convert(T, -128) % Int8 === Int8(-128) - @test convert(T, -128) % UInt8 === 0x80 - end - @test convert(T, 127) % Int8 === Int8(127) - @test convert(T, 127) % UInt8 === 0x7f - @test convert(T, 128) % Int8 === Int8(-128) - @test convert(T, 128) % UInt8 === 0x80 - @test convert(T, 200) % Int8 === Int8(-56) - @test convert(T, 300) % UInt8 === 0x2c -end - -@test_throws InexactError UInt128(-1) - -for T in (Int8,Int16,Int32,Int64,Int128,UInt8,UInt16,UInt32,UInt64,UInt128) - @test_throws InexactError T(big(typemax(T))+1) - @test_throws InexactError T(big(typemin(T))-1) -end - -for (d,B) in ((4//2+1im,Rational{BigInt}),(3.0+1im,BigFloat),(2+1im,BigInt)) - @test typeof(big(d)) == Complex{B} - @test big(d) == d - @test typeof(big.([d])) == Vector{Complex{B}} - @test big.([d]) == [d] -end - -# issue #12536 -@test Rational{Int16}(1,2) === Rational(Int16(1),Int16(2)) -@test Rational{Int16}(500000,1000000) === Rational(Int16(1),Int16(2)) - - -rand_int = rand(Int8) - -for T in [Int8, Int16, Int32, Int128, BigInt] - @test numerator(convert(T, rand_int)) == rand_int - @test denominator(convert(T, rand_int)) == 1 - - @test typemin(Rational{T}) == -one(T)//zero(T) - @test typemax(Rational{T}) == one(T)//zero(T) - @test widen(Rational{T}) == Rational{widen(T)} -end - -@test Rational(Float32(rand_int)) == Rational(rand_int) - -@test Rational(Rational(rand_int)) == Rational(rand_int) - -@test begin - var = -Rational(UInt32(0)) - var == UInt32(0) -end - -@test Rational(rand_int, 3)/Complex(3, 2) == Complex(Rational(rand_int, 13), -Rational(rand_int*2, 39)) - -@test Complex(rand_int, 0) == Rational(rand_int) -@test Rational(rand_int) == Complex(rand_int, 0) - -@test (Complex(rand_int, 4) == Rational(rand_int)) == false -@test (Rational(rand_int) == Complex(rand_int, 4)) == false - -@test trunc(Rational(BigInt(rand_int), BigInt(3))) == Rational(trunc(BigInt, Rational(BigInt(rand_int),BigInt(3)))) -@test ceil(Rational(BigInt(rand_int), BigInt(3))) == Rational( ceil(BigInt, Rational(BigInt(rand_int),BigInt(3)))) -@test round(Rational(BigInt(rand_int), BigInt(3))) == Rational(round(BigInt, Rational(BigInt(rand_int),BigInt(3)))) - - -for a = -3:3 - @test Rational(Float32(a)) == Rational(a) - @test Rational(a)//2 == a//2 - @test a//Rational(2) == Rational(a/2) - @test a.//[-2, -1, 1, 2] == [-a//2, -a//1, a//1, a//2] - for b=-3:3, c=1:3 - @test b//(a+c*im) == b*a//(a^2+c^2)-(b*c//(a^2+c^2))*im - for d=-3:3 - @test (a+b*im)//(c+d*im) == (a*c+b*d+(b*c-a*d)*im)//(c^2+d^2) - @test Complex(Rational(a)+b*im)//Complex(Rational(c)+d*im) == Complex(a+b*im)//Complex(c+d*im) - end - end -end - -# issue #15205 -let T = Rational - x = Complex{T}(1//3 + 1//4*im) - y = Complex{T}(1//2 + 1//5*im) - xf = Complex{BigFloat}(1//3 + 1//4*im) - yf = Complex{BigFloat}(1//2 + 1//5*im) - yi = 4 - - @test x^y ≈ xf^yf - @test x^yi ≈ xf^yi - @test x^true ≈ xf^true - @test x^false == xf^false - @test x^1 ≈ xf^1 - @test xf^Rational(2, 1) ≈ xf*xf - @test Complex(1., 1.)^Rational(2,1) == Complex(1., 1.)*Complex(1.,1.) == Complex(0., 2.) -end - -for Tf = (Float16, Float32, Float64), Ti = (Int16, Int32, Int64) - almost_half = Rational(div(typemax(Ti),Ti(2)) , typemax(Ti)) - over_half = Rational(div(typemax(Ti),Ti(2))+one(Ti), typemax(Ti)) - exactly_half = Rational(one(Ti) , Ti(2)) - - @test round( almost_half) == 0//1 - @test round(-almost_half) == 0//1 - @test round(Tf, almost_half, RoundNearestTiesUp) == 0.0 - @test round(Tf, -almost_half, RoundNearestTiesUp) == 0.0 - @test round(Tf, almost_half, RoundNearestTiesAway) == 0.0 - @test round(Tf, -almost_half, RoundNearestTiesAway) == 0.0 - - @test round( exactly_half) == 0//1 # rounds to closest _even_ integer - @test round(-exactly_half) == 0//1 # rounds to closest _even_ integer - @test round(Tf, exactly_half, RoundNearestTiesUp) == 1.0 - @test round(Tf, -exactly_half, RoundNearestTiesUp) == 0.0 - @test round(Tf, exactly_half, RoundNearestTiesAway) == 1.0 - @test round(Tf, -exactly_half, RoundNearestTiesAway) == -1.0 - - - @test round(over_half) == 1//1 - @test round(-over_half) == -1//1 - @test round(Tf, over_half, RoundNearestTiesUp) == 1.0 - @test round(Tf, over_half, RoundNearestTiesAway) == 1.0 - @test round(Tf, -over_half, RoundNearestTiesUp) == -1.0 - @test round(Tf, -over_half, RoundNearestTiesAway) == -1.0 - - @test round(Tf, 11//2, RoundNearestTiesUp) == 6.0 - @test round(Tf, -11//2, RoundNearestTiesUp) == -5.0 - @test round(Tf, 11//2, RoundNearestTiesAway) == 6.0 - @test round(Tf, -11//2, RoundNearestTiesAway) == -6.0 - - @test round(Tf, Ti(-1)//zero(Ti)) == -Inf - @test round(Tf, one(1)//zero(Ti)) == Inf - @test round(Tf, Ti(-1)//zero(Ti), RoundNearestTiesUp) == -Inf - @test round(Tf, one(1)//zero(Ti), RoundNearestTiesUp) == Inf - @test round(Tf, Ti(-1)//zero(Ti), RoundNearestTiesAway) == -Inf - @test round(Tf, one(1)//zero(Ti), RoundNearestTiesAway) == Inf - - @test round(Tf, zero(Ti)//one(Ti)) == 0 - @test round(Tf, zero(Ti)//one(Ti), RoundNearestTiesUp) == 0 - @test round(Tf, zero(Ti)//one(Ti), RoundNearestTiesAway) == 0 -end - -let - io = IOBuffer() - rational1 = Rational(1465, 8593) - rational2 = Rational(-4500, 9000) - @test sprint(show, rational1) == "1465//8593" - @test sprint(show, rational2) == "-1//2" - let - io1 = IOBuffer() - write(io1, rational1) - io1.ptr = 1 - @test read(io1, typeof(rational1)) == rational1 - - io2 = IOBuffer() - write(io2, rational2) - io2.ptr = 1 - @test read(io2, typeof(rational2)) == rational2 - end -end - -@test round(11//2) == 6//1 # rounds to closest _even_ integer -@test round(-11//2) == -6//1 # rounds to closest _even_ integer -@test round(11//3) == 4//1 # rounds to closest _even_ integer -@test round(-11//3) == -4//1 # rounds to closest _even_ integer - -for T in (Float16, Float32, Float64) - @test round(T, true//false) === convert(T, Inf) - @test round(T, true//true) === one(T) - @test round(T, false//true) === zero(T) -end - -for T in (Int8, Int16, Int32, Int64, Bool) - @test_throws DivideError round(T, true//false) - @test round(T, true//true) === one(T) - @test round(T, false//true) === zero(T) -end - -# multiplicative inverses -function testmi(numrange, denrange) - for d in denrange - d == 0 && continue - fastd = Base.multiplicativeinverse(d) - for n in numrange - @test div(n,d) == div(n,fastd) - end - end -end -testmi(-1000:1000, -100:100) -testmi(typemax(Int)-1000:typemax(Int), -100:100) -testmi(typemin(Int)+1:typemin(Int)+1000, -100:100) -@test_throws ArgumentError Base.multiplicativeinverse(0) -testmi(map(UInt32, 0:1000), map(UInt32, 1:100)) -testmi(typemax(UInt32)-UInt32(1000):typemax(UInt32), map(UInt32, 1:100)) - -@test ndims(1) == 0 -@test ndims(Integer) == 0 -@test size(1,1) == 1 -@test_throws BoundsError size(1,-1) -@test indices(1) == () -@test indices(1,1) == 1:1 -@test_throws BoundsError indices(1,-1) -@test isinteger(Integer(2)) == true -@test size(1) == () -@test length(1) == 1 -@test endof(1) == 1 -@test eltype(Integer) == Integer - -# issue #15920 -@test Rational(0, 1) / Complex(3, 2) == 0 - -# issue #16282 -@test_throws MethodError 3 // 4.5im - -# PR #16995 -let types = (Base.BitInteger_types..., BigInt, Bool, - Rational{Int}, Rational{BigInt}, - Float16, Float32, Float64, BigFloat, - Complex{Int}, Complex{UInt}, Complex32, Complex64, Complex128) - for S in types - for op in (+, -) - T = @inferred Base.promote_op(op, S) - t = @inferred op(one(S)) - @test T === typeof(t) - end - - for R in types - for op in (+, -, *, /, ^) - T = @inferred Base.promote_op(op, S, R) - t = @inferred op(one(S), one(R)) - @test T === typeof(t) - end - end - end - - @test @inferred(Base.promote_op(!, Bool)) === Bool -end - -let types = (Base.BitInteger_types..., BigInt, Bool, - Rational{Int}, Rational{BigInt}, - Float16, Float32, Float64, BigFloat) - for S in types, T in types - for op in (<, >, <=, >=, (==)) - @test @inferred(Base.promote_op(op, S, T)) === Bool - end - end -end - -let types = (Base.BitInteger_types..., BigInt, Bool) - for S in types - T = @inferred Base.promote_op(~, S) - t = @inferred ~one(S) - @test T === typeof(t) - - for R in types - for op in (&, |, <<, >>, (>>>), %, ÷) - T = @inferred Base.promote_op(op, S, R) - t = @inferred op(one(S), one(R)) - @test T === typeof(t) - end - end - end -end - -@test !isempty(complex(1,2)) - -@testset "rem $T rounded" for T in (Float16, Float32, Float64, BigFloat) - @test rem(T(1), T(2), RoundToZero) == 1 - @test rem(T(1), T(2), RoundNearest) == 1 - @test rem(T(1), T(2), RoundDown) == 1 - @test rem(T(1), T(2), RoundUp) == -1 - @test rem(T(1.5), T(2), RoundToZero) == 1.5 - @test rem(T(1.5), T(2), RoundNearest) == -0.5 - @test rem(T(1.5), T(2), RoundDown) == 1.5 - @test rem(T(1.5), T(2), RoundUp) == -0.5 - @test rem(T(-1), T(2), RoundToZero) == -1 - @test rem(T(-1), T(2), RoundNearest) == -1 - @test rem(T(-1), T(2), RoundDown) == 1 - @test rem(T(-1), T(2), RoundUp) == -1 - @test rem(T(-1.5), T(2), RoundToZero) == -1.5 - @test rem(T(-1.5), T(2), RoundNearest) == 0.5 - @test rem(T(-1.5), T(2), RoundDown) == 0.5 - @test rem(T(-1.5), T(2), RoundUp) == -1.5 -end - -@testset "rem2pi $T" for T in (Float16, Float32, Float64, BigFloat) - @test rem2pi(T(1), RoundToZero) == 1 - @test rem2pi(T(1), RoundNearest) == 1 - @test rem2pi(T(1), RoundDown) == 1 - @test rem2pi(T(1), RoundUp) ≈ 1-2pi - @test rem2pi(T(2), RoundToZero) == 2 - @test rem2pi(T(2), RoundNearest) == 2 - @test rem2pi(T(2), RoundDown) == 2 - @test rem2pi(T(2), RoundUp) ≈ 2-2pi - @test rem2pi(T(4), RoundToZero) == 4 - @test rem2pi(T(4), RoundNearest) ≈ 4-2pi - @test rem2pi(T(4), RoundDown) == 4 - @test rem2pi(T(4), RoundUp) ≈ 4-2pi - @test rem2pi(T(-4), RoundToZero) == -4 - @test rem2pi(T(-4), RoundNearest) ≈ 2pi-4 - @test rem2pi(T(-4), RoundDown) ≈ 2pi-4 - @test rem2pi(T(-4), RoundUp) == -4 -end - -import Base.^ -struct PR20530; end -struct PR20889; x; end -^(::PR20530, p::Int) = 1 -^(t::PR20889, b) = t.x + b -^(t::PR20889, b::Integer) = t.x + b -Base.literal_pow{p}(::typeof(^), ::PR20530, ::Type{Val{p}}) = 2 -@testset "literal powers" begin - x = PR20530() - p = 2 - @test x^p == 1 - @test x^2 == 2 - @test [x,x,x].^2 == [2,2,2] - for T in (Float16, Float32, Float64, BigFloat, Int8, Int, BigInt, Complex{Int}, Complex{Float64}) - for p in -4:4 - if p < 0 && real(T) <: Integer - @test_throws DomainError eval(:($T(2)^$p)) - else - v = eval(:($T(2)^$p)) - @test 2.0^p == T(2)^p == v - @test v isa T - end - end - end - @test PR20889(2)^3 == 5 -end -module M20889 # do we get the expected behavior without importing Base.^? - struct PR20889; x; end - ^(t::PR20889, b) = t.x + b - Base.Test.@test PR20889(2)^3 == 5 -end - -@testset "iszero" begin - # Numeric scalars - for T in [Float16, Float32, Float64, BigFloat, - Int8, Int16, Int32, Int64, Int128, BigInt, - UInt8, UInt16, UInt32, UInt64, UInt128] - @test iszero(T(0)) - @test iszero(Complex{T}(0)) - if T <: Integer - @test iszero(Rational{T}(0)) - elseif T <: AbstractFloat - @test iszero(T(-0.0)) - @test iszero(Complex{T}(-0.0)) - end - end - @test !iszero(nextfloat(BigFloat(0))) - for x in (π, e, γ, catalan, φ) - @test !iszero(x) - end - - # Array reduction - @test !iszero([0, 1, 2, 3]) - @test iszero(zeros(Int, 5)) -end - -f20065(B, i) = UInt8(B[i]) -@testset "issue 20065" begin - # f20065 must be called from global scope to exhibit the buggy behavior - for B in (Array{Bool}(10), Array{Bool}(10,10), reinterpret(Bool, rand(UInt8, 10))) - @test all(x-> x <= 1, (f20065(B, i) for i in eachindex(B))) - for i in 1:length(B) - @test (@eval f20065($B, $i) <= 1) - end - end -end diff --git a/julia-0.6.3/share/julia/test/offsetarray.jl b/julia-0.6.3/share/julia/test/offsetarray.jl deleted file mode 100644 index 88cebeb..0000000 --- a/julia-0.6.3/share/julia/test/offsetarray.jl +++ /dev/null @@ -1,453 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -isdefined(Main, :TestHelpers) || @eval Main include(joinpath(dirname(@__FILE__), "TestHelpers.jl")) -using TestHelpers.OAs - -const OAs_name = join(fullname(OAs), ".") - -let -# Basics -v0 = rand(4) -v = OffsetArray(v0, (-3,)) -h = OffsetArray([-1,1,-2,2,0], (-3,)) -@test indices(v) == (-2:1,) -@test_throws ErrorException size(v) -@test_throws ErrorException size(v, 1) - -A0 = [1 3; 2 4] -A = OffsetArray(A0, (-1,2)) # IndexLinear -S = OffsetArray(view(A0, 1:2, 1:2), (-1,2)) # IndexCartesian -@test indices(A) == indices(S) == (0:1, 3:4) -@test_throws ErrorException size(A) -@test_throws ErrorException size(A, 1) - -# Scalar indexing -@test A[0,3] == A[1] == A[0,3,1] == S[0,3] == S[1] == S[0,3,1] == 1 -@test A[1,3] == A[2] == A[1,3,1] == S[1,3] == S[2] == S[1,3,1] == 2 -@test A[0,4] == A[3] == A[0,4,1] == S[0,4] == S[3] == S[0,4,1] == 3 -@test A[1,4] == A[4] == A[1,4,1] == S[1,4] == S[4] == S[1,4,1] == 4 -@test_throws BoundsError A[1,1] -@test_throws BoundsError S[1,1] -@test_throws BoundsError A[0,3,2] -@test_throws BoundsError S[0,3,2] -# partial indexing -S3 = OffsetArray(view(reshape(collect(1:4*3*2), 4, 3, 2), 1:3, 1:2, :), (-1,-2,1)) -@test S3[1,-1] == 2 -@test S3[1,0] == 6 -@test_throws BoundsError S3[1,1] -@test_throws BoundsError S3[1,-2] - -# Vector indexing -@test A[:, 3] == S[:, 3] == OffsetArray([1,2], (A.offsets[1],)) -@test A[:, 4] == S[:, 4] == OffsetArray([3,4], (A.offsets[1],)) -@test_throws BoundsError A[:, 1] -@test_throws BoundsError S[:, 1] -@test A[0, :] == S[0, :] == OffsetArray([1,3], (A.offsets[2],)) -@test A[1, :] == S[1, :] == OffsetArray([2,4], (A.offsets[2],)) -@test_throws BoundsError A[2, :] -@test_throws BoundsError S[2, :] -@test A[0:1, 3] == S[0:1, 3] == [1,2] -@test A[[1,0], 3] == S[[1,0], 3] == [2,1] -@test A[0, 3:4] == S[0, 3:4] == [1,3] -@test A[1, [4,3]] == S[1, [4,3]] == [4,2] -@test A[:, :] == S[:, :] == A - -A_3_3 = OffsetArray(Array{Int}(3,3), (-2,-1)) -A_3_3[:, :] = reshape(1:9, 3, 3) -for i = 1:9 @test A_3_3[i] == i end -A_3_3[-1:1, 0:2] = reshape(1:9, 3, 3) -for i = 1:9 @test A_3_3[i] == i end -A_3_3[:, :] = 1:9 -for i = 1:9 @test A_3_3[i] == i end -A_3_3[-1:1, 0:2] = 1:9 -for i = 1:9 @test A_3_3[i] == i end -A_3_3[:] = 1:9 -for i = 1:9 @test A_3_3[i] == i end -A_3_3[1:9] = 1:9 -for i = 1:9 @test A_3_3[i] == i end - -# CartesianIndexing -@test A[CartesianIndex((0,3))] == S[CartesianIndex((0,3))] == 1 -@test_throws BoundsError A[CartesianIndex(1,1)] -@test_throws BoundsError S[CartesianIndex(1,1)] -@test eachindex(A) == 1:4 -@test eachindex(S) == CartesianRange((0:1,3:4)) - -# logical indexing -@test A[A .> 2] == [3,4] -@test_throws BoundsError h[trues(2)] -@test_throws BoundsError h[trues(5)] -@test h[OffsetArray(trues(5), (-3,))] == parent(h) -@test h[OffsetArray([true,false,false,true,true], (-3,))] == parent(h)[[1,4,5]] -@test A[OffsetArray([true false; false true], A.offsets)] == [1,4] -@test A[OffsetArray([true true; false true], A.offsets)] == [1,3,4] -@test_throws BoundsError A[[true true; false true]] - -# view -S = view(A, :, 3) -@test S == OffsetArray([1,2], (A.offsets[1],)) -@test S[0] == 1 -@test S[1] == 2 -@test_throws BoundsError S[2] -@test indices(S) === (0:1,) -S = view(A, 0, :) -@test S == OffsetArray([1,3], (A.offsets[2],)) -@test S[3] == 1 -@test S[4] == 3 -@test_throws BoundsError S[1] -@test indices(S) === (3:4,) -S = view(A, 0:0, 4) -@test S == [3] -@test S[1] == 3 -@test_throws BoundsError S[0] -@test indices(S) === (Base.OneTo(1),) -S = view(A, 1, 3:4) -@test S == [2,4] -@test S[1] == 2 -@test S[2] == 4 -@test_throws BoundsError S[3] -@test indices(S) === (Base.OneTo(2),) -S = view(A, :, :) -@test S == A -@test S[0,3] == S[1] == 1 -@test S[1,3] == S[2] == 2 -@test S[0,4] == S[3] == 3 -@test S[1,4] == S[4] == 4 -@test_throws BoundsError S[1,1] -@test indices(S) === (0:1, 3:4) -# https://github.com/JuliaArrays/OffsetArrays.jl/issues/27 -g = OffsetArray(collect(-2:3), (-3,)) -gv = view(g, -1:2) -@test indices(gv, 1) === Base.OneTo(4) -@test collect(gv) == collect(-1:2) -gv = view(g, OffsetArray(-1:2, (-2,))) -@test indices(gv, 1) === -1:2 -@test collect(gv) == collect(-1:2) -gv = view(g, OffsetArray(-1:2, (-1,))) -@test indices(gv, 1) === 0:3 -@test collect(gv) == collect(-1:2) - -# iteration -for (a,d) in zip(A, A0) - @test a == d -end - - -# show -io = IOBuffer() -show(io, v) -str = String(take!(io)) -show(io, v0) -@test str == String(take!(io)) -show(io, A) -str = String(take!(io)) -@test str == "[1 3; 2 4]" -show(io, S) -str = String(take!(io)) -@test str == "[1 3; 2 4]" -show(io, MIME("text/plain"), A) -strs = split(strip(String(take!(io))), '\n') -@test strs[2] == " 1 3" -@test strs[3] == " 2 4" -v = OffsetArray(rand(3), (-2,)) -show(io, v) -str = String(take!(io)) -show(io, parent(v)) -@test str == String(take!(io)) -smry = summary(v) -@test contains(smry, "OffsetArray{Float64,1") -@test contains(smry, "with indices -1:1") -function cmp_showf(printfunc, io, A) - ioc = IOContext(IOContext(io, :limit => true), :compact => true) - printfunc(ioc, A) - str1 = String(take!(io)) - printfunc(ioc, parent(A)) - str2 = String(take!(io)) - @test str1 == str2 -end -cmp_showf(Base.print_matrix, io, OffsetArray(rand(5,5), (10,-9))) # rows&cols fit -cmp_showf(Base.print_matrix, io, OffsetArray(rand(10^3,5), (10,-9))) # columns fit -cmp_showf(Base.print_matrix, io, OffsetArray(rand(5,10^3), (10,-9))) # rows fit -cmp_showf(Base.print_matrix, io, OffsetArray(rand(10^3,10^3), (10,-9))) # neither fits -cmp_showf(Base.show, io, OffsetArray(rand(1,1,10^3,1), (1,2,3,4))) # issue in #24393 -targets1 = ["0-dimensional $OAs_name.OffsetArray{Float64,0,Array{Float64,0}}:\n1.0", - "$OAs_name.OffsetArray{Float64,1,Array{Float64,1}} with indices 2:2:\n 1.0", - "$OAs_name.OffsetArray{Float64,2,Array{Float64,2}} with indices 2:2×3:3:\n 1.0", - "$OAs_name.OffsetArray{Float64,3,Array{Float64,3}} with indices 2:2×3:3×4:4:\n[:, :, 4] =\n 1.0", - "$OAs_name.OffsetArray{Float64,4,Array{Float64,4}} with indices 2:2×3:3×4:4×5:5:\n[:, :, 4, 5] =\n 1.0"] -targets2 = ["(1.0, 1.0)", - "([1.0], [1.0])", - "([1.0], [1.0])", - "([1.0], [1.0])", - "([1.0], [1.0])"] -for n = 0:4 - a = OffsetArray(ones(Float64,ntuple(d->1,n)), ntuple(identity,n)) - show(IOContext(io, :limit => true), MIME("text/plain"), a) - @test String(take!(io)) == targets1[n+1] - show(IOContext(io, :limit => true), MIME("text/plain"), (a,a)) - @test String(take!(io)) == targets2[n+1] -end -P = OffsetArray(rand(8,8), (1,1)) -PV = view(P, 2:3, :) -@test endswith(summary(PV), "with indices Base.OneTo(2)×2:9") - -# Similar -B = similar(A, Float32) -@test isa(B, OffsetArray{Float32,2}) -@test indices(B) === indices(A) -B = similar(A, (3,4)) -@test isa(B, Array{Int,2}) -@test size(B) == (3,4) -@test indices(B) === (Base.OneTo(3), Base.OneTo(4)) -B = similar(A, (-3:3,1:4)) -@test isa(B, OffsetArray{Int,2}) -@test indices(B) === (-3:3, 1:4) -B = similar(parent(A), (-3:3,1:4)) -@test isa(B, OffsetArray{Int,2}) -@test indices(B) === (-3:3, 1:4) - -# Indexing with OffsetArray indices -i1 = OffsetArray([2,1], (-5,)) -i1 = OffsetArray([2,1], -5) -b = A0[i1, 1] -@test indices(b) === (-4:-3,) -@test b[-4] == 2 -@test b[-3] == 1 -b = A0[1,i1] -@test indices(b) === (-4:-3,) -@test b[-4] == 3 -@test b[-3] == 1 -v = view(A0, i1, 1) -@test indices(v) === (-4:-3,) -v = view(A0, 1:1, i1) -@test indices(v) === (Base.OneTo(1), -4:-3) - -# copy! and fill! -a = OffsetArray{Int}((-3:-1,)) -fill!(a, -1) -copy!(a, (1,2)) # non-array iterables -@test a[-3] == 1 -@test a[-2] == 2 -@test a[-1] == -1 -fill!(a, -1) -copy!(a, -2, (1,2)) -@test a[-3] == -1 -@test a[-2] == 1 -@test a[-1] == 2 -@test_throws BoundsError copy!(a, 1, (1,2)) -fill!(a, -1) -copy!(a, -2, (1,2,3), 2) -@test a[-3] == -1 -@test a[-2] == 2 -@test a[-1] == 3 -@test_throws BoundsError copy!(a, -2, (1,2,3), 1) -fill!(a, -1) -copy!(a, -2, (1,2,3), 1, 2) -@test a[-3] == -1 -@test a[-2] == 1 -@test a[-1] == 2 - -b = 1:2 # copy between AbstractArrays -bo = OffsetArray(1:2, (-3,)) -@test_throws BoundsError copy!(a, b) -fill!(a, -1) -copy!(a, bo) -@test a[-3] == -1 -@test a[-2] == 1 -@test a[-1] == 2 -fill!(a, -1) -copy!(a, -2, bo) -@test a[-3] == -1 -@test a[-2] == 1 -@test a[-1] == 2 -@test_throws BoundsError copy!(a, -4, bo) -@test_throws BoundsError copy!(a, -1, bo) -fill!(a, -1) -copy!(a, -3, b, 2) -@test a[-3] == 2 -@test a[-2] == a[-1] == -1 -@test_throws BoundsError copy!(a, -3, b, 1, 4) -am = OffsetArray{Int}((1:1, 7:9)) # for testing linear indexing -fill!(am, -1) -copy!(am, b) -@test am[1] == 1 -@test am[2] == 2 -@test am[3] == -1 -@test am[1,7] == 1 -@test am[1,8] == 2 -@test am[1,9] == -1 - -# map -dest = similar(am) -map!(+, dest, am, am) -@test dest[1,7] == 2 -@test dest[1,8] == 4 -@test dest[1,9] == -2 - -am = map(identity, a) -@test isa(am, OffsetArray) -@test am == a - -# other functions -v = OffsetArray(v0, (-3,)) -@test endof(v) == 1 -@test v ≈ v -@test indices(v') === (Base.OneTo(1),-2:1) -@test parent(v) == collect(v) -rv = reverse(v) -@test indices(rv) == indices(v) -@test rv[1] == v[-2] -@test rv[0] == v[-1] -@test rv[-1] == v[0] -@test rv[-2] == v[1] -cv = copy(v) -@test reverse!(cv) == rv - -A = OffsetArray(rand(4,4), (-3,5)) -@test A ≈ A -@test indices(A') === (6:9, -2:1) -@test parent(A') == parent(A)' -@test collect(A) == parent(A) -@test maximum(A) == maximum(parent(A)) -@test minimum(A) == minimum(parent(A)) -@test extrema(A) == extrema(parent(A)) -@test maximum(A, 1) == OffsetArray(maximum(parent(A), 1), (0,A.offsets[2])) -@test maximum(A, 2) == OffsetArray(maximum(parent(A), 2), (A.offsets[1],0)) -@test maximum(A, 1:2) == maximum(parent(A), 1:2) -C = similar(A) -cumsum!(C, A, 1) -@test parent(C) == cumsum(parent(A), 1) -@test parent(cumsum(A, 1)) == cumsum(parent(A), 1) -cumsum!(C, A, 2) -@test parent(C) == cumsum(parent(A), 2) -R = similar(A, (1:1, 6:9)) -maximum!(R, A) -@test parent(R) == maximum(parent(A), 1) -R = similar(A, (-2:1, 1:1)) -maximum!(R, A) -@test parent(R) == maximum(parent(A), 2) -amin, iamin = findmin(A) -pmin, ipmin = findmin(parent(A)) -@test amin == pmin -@test A[iamin] == amin -@test amin == parent(A)[ipmin] -amax, iamax = findmax(A) -pmax, ipmax = findmax(parent(A)) -@test amax == pmax -@test A[iamax] == amax -@test amax == parent(A)[ipmax] -z = OffsetArray([0 0; 2 0; 0 0; 0 0], (-3,-1)) -I,J = findn(z) -@test I == [-1] -@test J == [0] -I,J,N = findnz(z) -@test I == [-1] -@test J == [0] -@test N == [2] -@test find(h) == [-2:1;] -@test find(x->x>0, h) == [-1,1] -@test find(x->x<0, h) == [-2,0] -@test find(x->x==0, h) == [2] -@test mean(A_3_3) == median(A_3_3) == 5 -@test mean(x->2x, A_3_3) == 10 -@test mean(A_3_3, 1) == median(A_3_3, 1) == OffsetArray([2 5 8], (0,A_3_3.offsets[2])) -@test mean(A_3_3, 2) == median(A_3_3, 2) == OffsetArray(reshape([4,5,6],(3,1)), (A_3_3.offsets[1],0)) -@test var(A_3_3) == 7.5 -@test std(A_3_3, 1) == OffsetArray([1 1 1], (0,A_3_3.offsets[2])) -@test std(A_3_3, 2) == OffsetArray(reshape([3,3,3], (3,1)), (A_3_3.offsets[1],0)) -@test sum(OffsetArray(ones(Int,3000), -1000)) == 3000 - -@test vecnorm(v) ≈ vecnorm(parent(v)) -@test vecnorm(A) ≈ vecnorm(parent(A)) -@test vecdot(v, v) ≈ vecdot(v0, v0) - -v = OffsetArray([1,1e100,1,-1e100], (-3,))*1000 -v2 = OffsetArray([1,-1e100,1,1e100], (5,))*1000 -@test isa(v, OffsetArray) -cv = OffsetArray([1,1e100,1e100,2], (-3,))*1000 -cv2 = OffsetArray([1,-1e100,-1e100,2], (5,))*1000 -@test isequal(cumsum_kbn(v), cv) -@test isequal(cumsum_kbn(v2), cv2) -@test isequal(sum_kbn(v), sum_kbn(parent(v))) - -io = IOBuffer() -writedlm(io, A) -seek(io, 0) -@test readdlm(io, eltype(A)) == parent(A) - -amin, amax = extrema(parent(A)) -@test clamp.(A, (amax+amin)/2, amax).parent == clamp.(parent(A), (amax+amin)/2, amax) - -@test unique(A, 1) == parent(A) -@test unique(A, 2) == parent(A) -v = OffsetArray(rand(8), (-2,)) -@test sort(v) == OffsetArray(sort(parent(v)), v.offsets) -@test sortrows(A) == OffsetArray(sortrows(parent(A)), A.offsets) -@test sortcols(A) == OffsetArray(sortcols(parent(A)), A.offsets) -@test sort(A, 1) == OffsetArray(sort(parent(A), 1), A.offsets) -@test sort(A, 2) == OffsetArray(sort(parent(A), 2), A.offsets) - -@test mapslices(sort, A, 1) == OffsetArray(mapslices(sort, parent(A), 1), A.offsets) -@test mapslices(sort, A, 2) == OffsetArray(mapslices(sort, parent(A), 2), A.offsets) - -@test rotl90(A) == OffsetArray(rotl90(parent(A)), A.offsets[[2,1]]) -@test rotr90(A) == OffsetArray(rotr90(parent(A)), A.offsets[[2,1]]) -@test flipdim(A, 1) == OffsetArray(flipdim(parent(A), 1), A.offsets) -@test flipdim(A, 2) == OffsetArray(flipdim(parent(A), 2), A.offsets) - -@test A+1 == OffsetArray(parent(A)+1, A.offsets) -@test 2*A == OffsetArray(2*parent(A), A.offsets) -@test A+A == OffsetArray(parent(A)+parent(A), A.offsets) -@test A.*A == OffsetArray(parent(A).*parent(A), A.offsets) - -@test circshift(A, (-1,2)) == OffsetArray(circshift(parent(A), (-1,2)), A.offsets) - -src = reshape(collect(1:16), (4,4)) -dest = OffsetArray(Array{Int}(4,4), (-1,1)) -circcopy!(dest, src) -@test parent(dest) == [8 12 16 4; 5 9 13 1; 6 10 14 2; 7 11 15 3] -@test dest[1:3,2:4] == src[1:3,2:4] - -e = eye(5) -a = [e[:,1], e[:,2], e[:,3], e[:,4], e[:,5]] -a1 = zeros(5) -c = [ones(Complex{Float64}, 5), - exp.(-2*pi*im*(0:4)/5), - exp.(-4*pi*im*(0:4)/5), - exp.(-6*pi*im*(0:4)/5), - exp.(-8*pi*im*(0:4)/5)] -for s = -5:5 - for i = 1:5 - thisa = OffsetArray(a[i], (s,)) - thisc = c[mod1(i+s+5,5)] - if Base.USE_GPL_LIBS - @test fft(thisa) ≈ thisc - @test fft(thisa, 1) ≈ thisc - @test ifft(fft(thisa)) ≈ circcopy!(a1, thisa) - @test ifft(fft(thisa, 1), 1) ≈ circcopy!(a1, thisa) - @test rfft(thisa) ≈ thisc[1:3] - @test rfft(thisa, 1) ≈ thisc[1:3] - @test irfft(rfft(thisa, 1), 5, 1) ≈ a1 - @test irfft(rfft(thisa, 1), 5, 1) ≈ a1 - end - end -end - -end # let - -# Check that similar throws a MethodError rather than a -# StackOverflowError if no appropriate method has been defined -# (#18107) -module SimilarUR - using Base.Test - struct MyURange <: AbstractUnitRange{Int} - start::Int - stop::Int - end - ur = MyURange(1,3) - a = Array{Int}(2) - @test_throws MethodError similar(a, ur) - @test_throws MethodError similar(a, Float64, ur) - @test_throws MethodError similar(a, Float64, (ur,)) - @test_throws MethodError similar(a, (2.0,3.0)) -end diff --git a/julia-0.6.3/share/julia/test/operators.jl b/julia-0.6.3/share/julia/test/operators.jl deleted file mode 100644 index 66fbe1a..0000000 --- a/julia-0.6.3/share/julia/test/operators.jl +++ /dev/null @@ -1,99 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -@test ifelse(true, 1, 2) == 1 -@test ifelse(false, 1, 2) == 2 - -s = Set() -ifelse(true, push!(s, 1), push!(s, 2)) -@test s == Set([1, 2]) - -s = Set() -true ? push!(s, 1) : push!(s, 2) -false ? push!(s, 3) : push!(s, 4) -@test s == Set([1, 4]) - -B = [true true false] -@test ifelse.(B, 1, 2) == [1 1 2] -@test ifelse.(B, 1, [2 3 4]) == [1 1 4] -@test ifelse.(B, [2 3 4], 1) == [2 3 1] -@test ifelse.(B, [2 3 4], [5 6 7]) == [2 3 7] - -@test reverse(Pair(1,2)) == Pair(2,1) -@test reverse(Pair("13","24")) == Pair("24","13") -@test typeof(reverse(Pair{String,Int64}("a",1))) == Pair{Int64,String} -@test convert(Pair{Float64,Float64}, 17 => 4711) === (17.0 => 4711.0) -@test convert(Pair{Int,Float64}, 17 => 4711) === (17 => 4711.0) -@test convert(Pair{Float64,Int}, 17 => 4711) === (17.0 => 4711) -@test convert(Pair{Any,Any}, 17 => 4711) === Pair{Any,Any}(17, 4711) -@test convert(Pair{Number,Number}, 17 => 4711) === Pair{Number,Number}(17, 4711) -@test promote(1=>1, 2=>2.0) === (1=>1.0, 2=>2.0) -@test promote(1=>1, 2.0=>2) === (1.0=>1, 2.0=>2) -@test promote(1=>1.0, 2.0=>2) === (1.0=>1.0, 2.0=>2.0) -@test promote(1=>1, :b=>2.0) === (Pair{Any,Float64}(1,1.0),Pair{Any,Float64}(:b,2.0)) -@test isa([:a=>1, :b=>2], Vector{Pair{Symbol,Int}}) -@test isa([:a=>1, :b=>2.0], Vector{Pair{Symbol,Float64}}) -@test isa(["a"=>1, :b=>2.0], Vector{Pair{Any,Float64}}) - -# Infix `isa` -@test 1 isa Integer - -p = 1=>:foo -@test first(p) == 1 -@test last(p) == :foo -@test first(reverse(p)) == :foo -@test last(reverse(p)) == 1 -@test endof(p) == 2 -@test p[endof(p)] == p[end] == p[2] == :foo - -@test (|)(2) == 2 -@test xor(2) == 2 -@test (⊻)(2) == 2 - -# @test ctranspose('a') == 'a' # (c)transpose of Chars no longer supported - -@test_throws ArgumentError Base.scalarmin(['a','b'],['c','d']) -@test_throws ArgumentError Base.scalarmin('a',['c','d']) -@test_throws ArgumentError Base.scalarmin(['a','b'],'c') -@test_throws ArgumentError Base.scalarmax(['a','b'],['c','d']) -@test_throws ArgumentError Base.scalarmax('a',['c','d']) -@test_throws ArgumentError Base.scalarmax(['a','b'],'c') - -@test lexless('a','b') - -@test 1 .!= 2 -@test 1 .== 1 -@test 1 .< 2 -@test 1 .<= 2 - -# issue #13144: max() with 4 or more array arguments -let xs = [[i:i+4;] for i in 1:10] - for n in 2:10 - @test max.(xs[1:n]...) == [n:n+4;] - end -end - -# issue #19714 -struct T19714 <: Integer end -Base.float(::T19714) = 19714.0 -Base.:/(::T19714, ::T19714) = T19714() -Base.convert(::Type{T19714}, ::Int) = T19714() -Base.promote_rule(::Type{T19714}, ::Type{Int}) = T19714 -@test T19714()/1 === 1/T19714() === T19714() - -# pr #17155 -@testset "function composition" begin - @test (uppercase∘hex)(239487) == "3A77F" -end -@testset "function negation" begin - str = randstring(20) - @test filter(!isupper, str) == replace(str, r"[A-Z]", "") - @test filter(!islower, str) == replace(str, r"[a-z]", "") -end - -# issue #19891 -@testset "chained comparison" begin - B = 0 .< [1 -1 5] .< 3 - @test B == [true false false] - B = 3 .> [1 -1 5] .> 0 - @test B == [true false false] -end diff --git a/julia-0.6.3/share/julia/test/osutils.jl b/julia-0.6.3/share/julia/test/osutils.jl deleted file mode 100644 index 270680c..0000000 --- a/julia-0.6.3/share/julia/test/osutils.jl +++ /dev/null @@ -1,28 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -@test !Base.is_unix(:Windows) -@test !Base.is_linux(:Windows) -@test Base.is_linux(:Linux) -@test Base.is_windows(:Windows) -@test Base.is_windows(:NT) -@test !Base.is_windows(:Darwin) -@test Base.is_apple(:Darwin) -@test Base.is_apple(:Apple) -@test !Base.is_apple(:Windows) -@test Base.is_unix(:Darwin) -@test Base.is_unix(:FreeBSD) -@test_throws ArgumentError Base.is_unix(:BeOS) -if !is_windows() - @test Sys.windows_version() === (0, 0) -else - @test (Sys.windows_version()::Tuple{Int,Int})[1] > 0 -end - -@test (@static true ? 1 : 2) === 1 -@test (@static false ? 1 : 2) === 2 -@test (@static if true 1 end) === 1 -@test (@static if false 1 end) === nothing -@test (@static true && 1) === 1 -@test (@static false && 1) === false -@test (@static true || 1) === true -@test (@static false || 1) === 1 diff --git a/julia-0.6.3/share/julia/test/parse.jl b/julia-0.6.3/share/julia/test/parse.jl deleted file mode 100644 index 052b0c2..0000000 --- a/julia-0.6.3/share/julia/test/parse.jl +++ /dev/null @@ -1,1226 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -# tests for parser and syntax lowering - -function parseall(str) - pos = start(str) - exs = [] - while !done(str, pos) - ex, pos = parse(str, pos) - push!(exs, ex) - end - if length(exs) == 0 - throw(ParseError("end of input")) - elseif length(exs) == 1 - return exs[1] - else - return Expr(:block, exs...) - end -end - -# issue #9684 -let - undot(op) = Symbol(string(op)[2:end]) - for (ex1, ex2) in [("5.≠x", "5.!=x"), - ("5.≥x", "5.>=x"), - ("5.≤x", "5.<=x")] - ex1 = parse(ex1); ex2 = parse(ex2) - @test ex1.head === :call && (ex1.head === ex2.head) - @test ex1.args[2] === 5 && ex2.args[2] === 5 - @test eval(Main, undot(ex1.args[1])) === eval(Main, undot(ex2.args[1])) - @test ex1.args[3] === :x && (ex1.args[3] === ex2.args[3]) - end -end - -# issue #9704 -let a = :a - @test :(try - catch $a - end) == :(try - catch a - end) - @test :(module $a end) == :(module a - end) -end - -# string literals -macro test999_str(args...); args; end -@test test999"a"b == ("a","b") -@test test999"""a"""b == ("a","b") -@test test999" - a - b" == (" - a - b",) -@test test999""" - a - b""" == ("a\nb",) - -# issue #5997 -@test_throws ParseError parse(": x") -@test_throws ParseError parse("d[: 2]") - -# issue #6770 -@test_throws ParseError parse("x.3") - -# issue #8763 -@test_throws ParseError parse("sqrt(16)2") -@test_throws ParseError parse("x' y") -@test_throws ParseError parse("x 'y") -@test parse("x'y") == Expr(:call, :*, Expr(Symbol("'"), :x), :y) - -# issue #8301 -@test_throws ParseError parse("&*s") - -# issue #10677 -@test_throws ParseError parse("/1") -@test_throws ParseError parse("/pi") -@test parse("- = 2") == Expr(:(=), :(-), 2) -@test parse("/ = 2") == Expr(:(=), :(/), 2) -@test_throws ParseError parse("< : 2") -@test_throws ParseError parse("+ : 2") -@test_throws ParseError parse("< :2") -@test parse("+ :2") == Expr(:call, :(+), QuoteNode(2)) - -# issue #10900 -@test_throws ParseError parse("+=") -@test_throws ParseError parse(".") -@test_throws ParseError parse("...") - -# issue #10901 -@test parse("/([1], 1)[1]") == :(([1] / 1)[1]) - -# issue #10997 -@test parse(":(x.\$f[i])") == Expr(:quote, - Expr(:ref, - Expr(Symbol("."), :x, - QuoteNode(Expr(:$, :f))), - :i)) - -# issue #10994 -@test parse("1 + #= \0 =# 2") == :(1 + 2) - -# issue #10910 -@test parse(":(using A)") == Expr(:quote, Expr(:using, :A)) -@test parse(":(using A.b, B)") == Expr(:quote, - Expr(:toplevel, - Expr(:using, :A, :b), - Expr(:using, :B))) -@test parse(":(using A: b, c.d)") == Expr(:quote, - Expr(:toplevel, - Expr(:using, :A, :b), - Expr(:using, :A, :c, :d))) - -@test parse(":(importall A)") == Expr(:quote, Expr(:importall, :A)) - -@test parse(":(import A)") == Expr(:quote, Expr(:import, :A)) -@test parse(":(import A.b, B)") == Expr(:quote, - Expr(:toplevel, - Expr(:import, :A, :b), - Expr(:import, :B))) -@test parse(":(import A: b, c.d)") == Expr(:quote, - Expr(:toplevel, - Expr(:import, :A, :b), - Expr(:import, :A, :c, :d))) - -# issue #11332 -@test parse("export \$(Symbol(\"A\"))") == :(export $(Expr(:$, :(Symbol("A"))))) -@test parse("export \$A") == :(export $(Expr(:$, :A))) -@test parse("using \$a.\$b") == Expr(:using, Expr(:$, :a), Expr(:$, :b)) -@test parse("using \$a.\$b, \$c") == Expr(:toplevel, Expr(:using, Expr(:$, :a), - Expr(:$, :b)), - Expr(:using, Expr(:$, :c))) -@test parse("using \$a: \$b, \$c.\$d") == - Expr(:toplevel, Expr(:using, Expr(:$, :a), Expr(:$, :b)), - Expr(:using, Expr(:$, :a), Expr(:$, :c), Expr(:$, :d))) - -# fix pr #11338 and test for #11497 -@test parseall("using \$\na") == Expr(:block, Expr(:using, :$), :a) -@test parseall("using \$,\na") == Expr(:toplevel, Expr(:using, :$), - Expr(:using, :a)) -@test parseall("using &\na") == Expr(:block, Expr(:using, :&), :a) - -@test parseall("a = &\nb") == Expr(:block, Expr(:(=), :a, :&), :b) -@test parseall("a = \$\nb") == Expr(:block, Expr(:(=), :a, :$), :b) -@test parseall(":(a = &\nb)") == Expr(:quote, Expr(:(=), :a, Expr(:&, :b))) -@test parseall(":(a = \$\nb)") == Expr(:quote, Expr(:(=), :a, Expr(:$, :b))) - -# issue 11970 -@test parseall(""" -macro f(args...) end; @f "" -""") == Expr(:toplevel, - Expr(:macro, Expr(:call, :f, Expr(:..., :args)), Expr(:block, Expr(:line, 1, :none))), - Expr(:macrocall, Symbol("@f"), "")) - -# blocks vs. tuples -@test parse("()") == Expr(:tuple) -@test parse("(;)") == Expr(:block) -@test parse("(;;;;)") == Expr(:block) -@test_throws ParseError parse("(,)") -@test_throws ParseError parse("(;,)") -@test_throws ParseError parse("(,;)") -@test parse("(x;)") == Expr(:block, :x) -@test parse("(;x)") == Expr(:tuple, Expr(:parameters, :x)) -@test parse("(;x,)") == Expr(:tuple, Expr(:parameters, :x)) -@test parse("(x,)") == Expr(:tuple, :x) -@test parse("(x,;)") == Expr(:tuple, :x) -@test parse("(x;y)") == Expr(:block, :x, :y) -@test parse("(x=1;y=2)") == Expr(:block, Expr(:(=), :x, 1), Expr(:(=), :y, 2)) -@test parse("(x,;y)") == Expr(:tuple, Expr(:parameters, :y), :x) -@test parse("(x,;y=1)") == Expr(:tuple, Expr(:parameters, Expr(:kw, :y, 1)), :x) -@test parse("(x,a;y=1)") == Expr(:tuple, Expr(:parameters, Expr(:kw, :y, 1)), :x, :a) -@test parse("(x,a;y=1,z=2)") == Expr(:tuple, Expr(:parameters, Expr(:kw,:y,1), Expr(:kw,:z,2)), :x, :a) -@test parse("(a=1, b=2)") == Expr(:tuple, Expr(:(=), :a, 1), Expr(:(=), :b, 2)) -@test_throws ParseError parse("(1 2)") # issue #15248 - -# integer parsing -@test parse(Int32,"0",36) === Int32(0) -@test parse(Int32,"1",36) === Int32(1) -@test parse(Int32,"9",36) === Int32(9) -@test parse(Int32,"A",36) === Int32(10) -@test parse(Int32,"a",36) === Int32(10) -@test parse(Int32,"B",36) === Int32(11) -@test parse(Int32,"b",36) === Int32(11) -@test parse(Int32,"F",36) === Int32(15) -@test parse(Int32,"f",36) === Int32(15) -@test parse(Int32,"Z",36) === Int32(35) -@test parse(Int32,"z",36) === Int32(35) - -@test parse(Int,"0") == 0 -@test parse(Int,"-0") == 0 -@test parse(Int,"1") == 1 -@test parse(Int,"-1") == -1 -@test parse(Int,"9") == 9 -@test parse(Int,"-9") == -9 -@test parse(Int,"10") == 10 -@test parse(Int,"-10") == -10 -@test parse(Int64,"3830974272") == 3830974272 -@test parse(Int64,"-3830974272") == -3830974272 -@test parse(Int,'3') == 3 -@test parse(Int,'3', 8) == 3 - -# Issue 20587 -for T in vcat(subtypes(Signed), subtypes(Unsigned)) - for s in ["", " ", " "] - # Without a base (handles things like "0x00001111", etc) - result = @test_throws ArgumentError parse(T, s) - exception_without_base = result.value - if T == Bool - if s == "" - @test exception_without_base.msg == "input string is empty" - else - @test exception_without_base.msg == "input string only contains whitespace" - end - else - @test exception_without_base.msg == "input string is empty or only contains whitespace" - end - - # With a base - result = @test_throws ArgumentError parse(T, s, 16) - exception_with_base = result.value - if T == Bool - if s == "" - @test exception_with_base.msg == "input string is empty" - else - @test exception_with_base.msg == "input string only contains whitespace" - end - else - @test exception_with_base.msg == "input string is empty or only contains whitespace" - end - end - - # Test `tryparse_internal` with part of a string - let b = " " - result = @test_throws ArgumentError get(Base.tryparse_internal(Bool, b, 7, 11, 0, true)) - exception_bool = result.value - @test exception_bool.msg == "input string only contains whitespace" - - result = @test_throws ArgumentError get(Base.tryparse_internal(Int, b, 7, 11, 0, true)) - exception_int = result.value - @test exception_int.msg == "input string is empty or only contains whitespace" - - result = @test_throws ArgumentError get(Base.tryparse_internal(UInt128, b, 7, 11, 0, true)) - exception_uint = result.value - @test exception_uint.msg == "input string is empty or only contains whitespace" - end - - # Test that the entire input string appears in error messages - let s = " false true " - result = @test_throws(ArgumentError, - get(Base.tryparse_internal(Bool, s, start(s), endof(s), 0, true))) - @test result.value.msg == "invalid Bool representation: $(repr(s))" - end - - # Test that leading and trailing whitespace is ignored. - for v in (1, 2, 3) - @test parse(Int, " $v" ) == v - @test parse(Int, " $v\n" ) == v - @test parse(Int, "$v " ) == v - @test parse(Int, " $v ") == v - end - for v in (true, false) - @test parse(Bool, " $v" ) == v - @test parse(Bool, " $v\n" ) == v - @test parse(Bool, "$v " ) == v - @test parse(Bool, " $v ") == v - end - for v in (0.05, -0.05, 2.5, -2.5) - @test parse(Float64, " $v" ) == v - @test parse(Float64, " $v\n" ) == v - @test parse(Float64, "$v " ) == v - @test parse(Float64, " $v ") == v - end - @test parse(Float64, " .5" ) == 0.5 - @test parse(Float64, " .5\n" ) == 0.5 - @test parse(Float64, " .5 ") == 0.5 - @test parse(Float64, ".5 " ) == 0.5 -end - -@test parse(Bool, "\u202f true") === true -@test parse(Bool, "\u202f false") === false - -parsebin(s) = parse(Int,s,2) -parseoct(s) = parse(Int,s,8) -parsehex(s) = parse(Int,s,16) - -@test parsebin("0") == 0 -@test parsebin("-0") == 0 -@test parsebin("1") == 1 -@test parsebin("-1") == -1 -@test parsebin("10") == 2 -@test parsebin("-10") == -2 -@test parsebin("11") == 3 -@test parsebin("-11") == -3 -@test parsebin("1111000011110000111100001111") == 252645135 -@test parsebin("-1111000011110000111100001111") == -252645135 - -@test parseoct("0") == 0 -@test parseoct("-0") == 0 -@test parseoct("1") == 1 -@test parseoct("-1") == -1 -@test parseoct("7") == 7 -@test parseoct("-7") == -7 -@test parseoct("10") == 8 -@test parseoct("-10") == -8 -@test parseoct("11") == 9 -@test parseoct("-11") == -9 -@test parseoct("72") == 58 -@test parseoct("-72") == -58 -@test parseoct("3172207320") == 434704080 -@test parseoct("-3172207320") == -434704080 - -@test parsehex("0") == 0 -@test parsehex("-0") == 0 -@test parsehex("1") == 1 -@test parsehex("-1") == -1 -@test parsehex("9") == 9 -@test parsehex("-9") == -9 -@test parsehex("a") == 10 -@test parsehex("-a") == -10 -@test parsehex("f") == 15 -@test parsehex("-f") == -15 -@test parsehex("10") == 16 -@test parsehex("-10") == -16 -@test parsehex("0BADF00D") == 195948557 -@test parsehex("-0BADF00D") == -195948557 -@test parse(Int64,"BADCAB1E",16) == 3135023902 -@test parse(Int64,"-BADCAB1E",16) == -3135023902 -@test parse(Int64,"CafeBabe",16) == 3405691582 -@test parse(Int64,"-CafeBabe",16) == -3405691582 -@test parse(Int64,"DeadBeef",16) == 3735928559 -@test parse(Int64,"-DeadBeef",16) == -3735928559 - -@test parse(Int,"2\n") == 2 -@test parse(Int," 2 \n ") == 2 -@test parse(Int," 2 ") == 2 -@test parse(Int,"2 ") == 2 -@test parse(Int," 2") == 2 -@test parse(Int,"+2\n") == 2 -@test parse(Int,"-2") == -2 -@test_throws ArgumentError parse(Int," 2 \n 0") -@test_throws ArgumentError parse(Int,"2x") -@test_throws ArgumentError parse(Int,"-") - -# parsing numbers with _ and . -@test parse("1_2.3_4") == 12.34 -@test_throws ParseError parse("1._") -@test_throws ParseError parse("1._5") -@test_throws ParseError parse("1e.3") -@test_throws ParseError parse("1e3.") -@test parse("2e_1") == Expr(:call, :*, 2, :e_1) -# issue #17705 -@test parse("2e3_") == Expr(:call, :*, 2e3, :_) -@test parse("2e-3_") == Expr(:call, :*, 2e-3, :_) -@test parse("2e3_\"x\"") == Expr(:call, :*, 2e3, Expr(:macrocall, Symbol("@__str"), "x")) - -# multibyte spaces -@test parse(Int, "3\u2003\u202F") == 3 -@test_throws ArgumentError parse(Int, "3\u2003\u202F,") - -@test parse(Int,'a') == 10 -@test_throws ArgumentError parse(Int,typemax(Char)) - -@test parse(Int,"1234") == 1234 -@test parse(Int,"0x1234") == 0x1234 -@test parse(Int,"0o1234") == 0o1234 -@test parse(Int,"0b1011") == 0b1011 -@test parse(Int,"-1234") == -1234 -@test parse(Int,"-0x1234") == -Int(0x1234) -@test parse(Int,"-0o1234") == -Int(0o1234) -@test parse(Int,"-0b1011") == -Int(0b1011) - -for T in (Int8, Int16, Int32, Int64, Int128) - @test parse(T,string(typemin(T))) == typemin(T) - @test parse(T,string(typemax(T))) == typemax(T) - @test_throws OverflowError parse(T,string(big(typemin(T))-1)) - @test_throws OverflowError parse(T,string(big(typemax(T))+1)) -end - -for T in (UInt8,UInt16,UInt32,UInt64,UInt128) - @test parse(T,string(typemin(T))) == typemin(T) - @test parse(T,string(typemax(T))) == typemax(T) - @test_throws ArgumentError parse(T,string(big(typemin(T))-1)) - @test_throws OverflowError parse(T,string(big(typemax(T))+1)) -end - -@test parse("1 == 2|>3") == Expr(:call, :(==), 1, Expr(:call, :(|>), 2, 3)) - -# issue #12501 and pr #12502 -parse(""" - baremodule A - "a" in b - end - """) -parse(""" - baremodule A - "a" - end - """) - -# issue #12626 -@test parse("a .÷ 1") == Expr(:call, :.÷, :a, 1) -@test parse("a .÷= 1") == Expr(:.÷=, :a, 1) - -# issue #12771 -@test -(3)^2 == -9 - -# issue #13302 -let p = parse("try - a - catch - b, c = t - end") - @test isa(p,Expr) && p.head === :try - @test p.args[2] === false - @test p.args[3].args[end] == parse("b,c = t") -end - -# pr #13078 -@test parse("a in b in c") == Expr(:comparison, :a, :in, :b, :in, :c) -@test parse("a||b→c&&d") == Expr(:call, :→, - Expr(Symbol("||"), :a, :b), - Expr(Symbol("&&"), :c, :d)) - -# issue #11988 -- normalize \r and \r\n in literal strings to \n -@test "foo\nbar" == parse("\"\"\"\r\nfoo\r\nbar\"\"\"") == - parse("\"\"\"\nfoo\nbar\"\"\"") == parse("\"\"\"\rfoo\rbar\"\"\"") == - parse("\"foo\r\nbar\"") == parse("\"foo\rbar\"") == parse("\"foo\nbar\"") -@test '\r' == first("\r") == first("\r\n") # still allow explicit \r - -# issue #14561 - generating 0-method generic function def -let fname = :f - @test :(function $fname end) == Expr(:function, :f) -end - -# issue #14977 -@test parse("x = 1", 1) == (:(x = 1), 6) -@test parse("x = 1", 6) == (nothing, 6) -@test_throws BoundsError parse("x = 1", 0) -@test_throws BoundsError parse("x = 1", -1) -@test_throws BoundsError parse("x = 1", 7) - -# issue #14683 -@test_throws ParseError parse("'\\A\"'") -@test parse("'\"'") == parse("'\\\"'") == '"' == "\""[1] == '\42' - -@test_throws ParseError parse("f(2x for x=1:10, y") - -# issue #15223 -call0(f) = f() -call1(f,x) = f(x) -call2(f,x,y) = f(x,y) -@test (call0() do; 42 end) == 42 -@test (call1(42) do x; x+1 end) == 43 -@test (call2(42,1) do x,y; x+y+1 end) == 44 - -# definitions using comparison syntax -let a⊂b = reduce(&, x ∈ b for x in a) && length(b)>length(a) - @test [1,2] ⊂ [1,2,3,4] - @test !([1,2] ⊂ [1,3,4]) - @test !([1,2] ⊂ [1,2]) -end - -# issue #9503 -@test parse("x<:y") == Expr(:(<:), :x, :y) -@test parse("x>:y") == Expr(:(>:), :x, :y) -@test parse("x<:y<:z").head === :comparison -@test parse("x>:y<:z").head === :comparison - -# reason PR #19765, <- operator, was reverted -@test -2<-1 # DO NOT ADD SPACES - -# issue #11169 -uncalled(x) = @test false -fret() = uncalled(return true) -@test fret() - -# issue #9617 -let p = 15 - @test 2p+1 == 31 # not a hex float literal -end - -# issue #15597 -function test_parseerror(str, msg) - try - parse(str) - @test false - catch e - @test isa(e,ParseError) && e.msg == msg - end -end -test_parseerror("0x", "invalid numeric constant \"0x\"") -test_parseerror("0b", "invalid numeric constant \"0b\"") -test_parseerror("0o", "invalid numeric constant \"0o\"") -test_parseerror("0x0.1", "hex float literal must contain \"p\" or \"P\"") -test_parseerror("0x1.0p", "invalid numeric constant \"0x1.0\"") - -# issue #15798 -@test expand(Base.parse_input_line(""" - try = "No" - """)) == Expr(:error, "unexpected \"=\"") - -# issue #19861 make sure macro-expansion happens in the newest world for top-level expression -@test eval(Base.parse_input_line(""" - macro X19861() - return 23341 - end - @X19861 - """)::Expr) == 23341 - -# test parse_input_line for a streaming IO input -let b = IOBuffer(""" - let x = x - x - end - f() - """) - @test Base.parse_input_line(b) == Expr(:let, Expr(:block, Expr(:line, 2, :none), :x), Expr(:(=), :x, :x)) - @test Base.parse_input_line(b) == Expr(:call, :f) - @test Base.parse_input_line(b) === nothing -end - -# issue #15763 -test_parseerror("if\nfalse\nend", "missing condition in \"if\" at none:1") -test_parseerror("if false\nelseif\nend", "missing condition in \"elseif\" at none:2") - -# issue #15828 -@test expand(parse("x...")) == Expr(:error, "\"...\" expression outside call") - -# issue #15830 -@test expand(parse("foo(y = (global x)) = y")) == Expr(:error, "misplaced \"global\" declaration") - -# issue #15844 -function f15844(x) - x -end - -g15844 = let - local function f15844(x::Int32) - 2x - end -end - -function add_method_to_glob_fn!() - global function f15844(x::Int64) - 3x - end -end - -add_method_to_glob_fn!() -@test g15844 !== f15844 -@test g15844(Int32(1)) == 2 -@test f15844(Int32(1)) == 1 -@test f15844(Int64(1)) == 3 - -# issue #15661 -@test_throws ParseError parse("function catch() end") -@test_throws ParseError parse("function end() end") -@test_throws ParseError parse("function finally() end") - -# PR #16170 -@test expand(parse("true(x) = x")) == Expr(:error, "invalid function name \"true\"") -@test expand(parse("false(x) = x")) == Expr(:error, "invalid function name \"false\"") - -# issue #16355 -@test expand(:(f(d:Int...)=nothing)) == Expr(:error, "\"d:Int\" is not a valid function argument name") - -# issue #16517 -@test (try error(); catch 0; end) === 0 -@test (try error(); catch false; end) === false # false and true are Bool literals, not variables -@test (try error(); catch true; end) === true -f16517() = try error(); catch 0; end -@test f16517() === 0 - -# issue #16671 -@test parse("1.") === 1.0 - -isline(x) = isa(x,Expr) && x.head === :line - -# issue #16672 -@test count(isline, parse("begin end").args) == 1 -@test count(isline, parse("begin; end").args) == 1 -@test count(isline, parse("begin; x+2; end").args) == 1 -@test count(isline, parse("begin; x+2; y+1; end").args) == 2 - -# issue #16736 -let - local lineoffset0 = @__LINE__ + 1 - local lineoffset1 = @__LINE__ - local lineoffset2 = @__LINE__ - 1 - @test lineoffset0 == lineoffset1 == lineoffset2 -end - -# issue #16686 -@test parse("try x - catch test() - y - end") == Expr(:try, - Expr(:block, - Expr(:line, 1, :none), - :x), - false, - Expr(:block, - Expr(:line, 2, :none), - Expr(:call, :test), - Expr(:line, 3, :none), - :y)) - -# test that pre 0.5 deprecated syntax is a parse error -@test_throws ParseError parse("Int [1,2,3]") -@test_throws ParseError parse("Int [x for x in 1:10]") -@test_throws ParseError parse("foo (x) = x") -@test_throws ParseError parse("foo {T<:Int}(x::T) = x") - -@test_throws ParseError parse("Foo .bar") - -@test_throws ParseError parse("import x .y") -@test_throws ParseError parse("using x .y") - -@test_throws ParseError parse("--x") -@test_throws ParseError parse("stagedfunction foo(x); end") - -#@test_throws ParseError parse("{1,2,3}") -#@test_throws ParseError parse("{1 2 3 4}") -#@test_throws ParseError parse("{1,2; 3,4}") -@test_throws ParseError parse("{x for x in 1:10}") -@test_throws ParseError parse("{x=>y for (x,y) in zip([1,2,3],[4,5,6])}") -#@test_throws ParseError parse("{:a=>1, :b=>2}") - -@test parse("A=>B") == Expr(:call, :(=>), :A, :B) - -# this now is parsed as getindex(Pair{Any,Any}, ...) -@test_throws MethodError eval(parse("(Any=>Any)[]")) -@test_throws MethodError eval(parse("(Any=>Any)[:a=>1,:b=>2]")) - -# make sure base can be any Integer -for T in (Int, BigInt) - let n = parse(T, "123", Int8(10)) - @test n == 123 - @test isa(n, T) - end -end - -# issue #16720 -let err = try - include_string("module A - - function broken() - - x[1] = some_func( - - end - - end") - catch e - e - end - @test err.line == 7 -end - -# issue #17065 -@test parse(Int, "2") === 2 -@test parse(Bool, "true") === true -@test parse(Bool, "false") === false -@test get(tryparse(Bool, "true")) === get(Nullable{Bool}(true)) -@test get(tryparse(Bool, "false")) === get(Nullable{Bool}(false)) -@test_throws ArgumentError parse(Int, "2", 1) -@test_throws ArgumentError parse(Int, "2", 63) - -# issue #17333: tryparse should still throw on invalid base -for T in (Int32, BigInt), base in (0,1,100) - @test_throws ArgumentError tryparse(T, "0", base) -end - -# error throwing branch from #10560 -@test_throws ArgumentError Base.tryparse_internal(Bool, "foo", 1, 2, 10, true) - -@test tryparse(Float64, "1.23") === Nullable(1.23) -@test tryparse(Float32, "1.23") === Nullable(1.23f0) -@test tryparse(Float16, "1.23") === Nullable(Float16(1.23)) - -# PR #17393 -for op in (:.==, :.&, :.|, :.≤) - @test parse("a $op b") == Expr(:call, op, :a, :b) -end -for op in (:.=, :.+=) - @test parse("a $op b") == Expr(op, :a, :b) -end - -# issue #17489 -let m_error, error_out, filename = Base.source_path() - m_error = try @eval method_c6(a::(:A)) = 1; catch e; e; end - error_out = sprint(showerror, m_error) - @test startswith(error_out, "ArgumentError: invalid type for argument a in method definition for method_c6 at $filename:") - - m_error = try @eval method_c6(::(:A)) = 2; catch e; e; end - error_out = sprint(showerror, m_error) - @test startswith(error_out, "ArgumentError: invalid type for argument number 1 in method definition for method_c6 at $filename:") - - m_error = try @eval method_c6(A; B) = 3; catch e; e; end - error_out = sprint(showerror, m_error) - @test error_out == "syntax: keyword argument \"B\" needs a default value" - - # issue #20614 - m_error = try @eval foo{N}(types::NTuple{N}, values::Vararg{Any,N}, c) = nothing; catch e; e; end - error_out = sprint(showerror, m_error) - @test startswith(error_out, "ArgumentError: Vararg on non-final argument") -end - -# issue #7272 -@test expand(parse("let - global x = 2 - local x = 1 - end")) == Expr(:error, "variable \"x\" declared both local and global") - -@test expand(parse("let - local x = 2 - local x = 1 - end")) == Expr(:error, "local \"x\" declared twice") - -@test expand(parse("let x - local x = 1 - end")) == Expr(:error, "local \"x\" declared twice") - -@test expand(parse("let x = 2 - local x = 1 - end")) == Expr(:error, "local \"x\" declared twice") - - -# make sure front end can correctly print values to error messages -let ex = expand(parse("\"a\"=1")) - @test ex == Expr(:error, "invalid assignment location \"\"a\"\"") -end - -# make sure that incomplete tags are detected correctly -# (i.e. error messages in src/julia-parser.scm must be matched correctly -# by the code in base/client.jl) -for (str, tag) in Dict("" => :none, "\"" => :string, "#=" => :comment, "'" => :char, - "`" => :cmd, "begin;" => :block, "quote;" => :block, - "let;" => :block, "for i=1;" => :block, "function f();" => :block, - "f() do x;" => :block, "module X;" => :block, "mutable struct X;" => :block, - "struct X;" => :block, "(" => :other, "[" => :other, - "begin" => :other, "quote" => :other, - "let" => :other, "for" => :other, "function" => :other, - "f() do" => :other, "module" => :other, "mutable struct" => :other, - "struct" => :other) - @test Base.incomplete_tag(parse(str, raise=false)) == tag -end - -# meta nodes for optional positional arguments -@test expand(:(@inline f(p::Int=2) = 3)).args[2].args[3].inlineable - -# issue #16096 -module M16096 -macro iter() - quote - @inline function foo(sub) - it = 1 - end - end -end -end -let ex = expand(:(@M16096.iter)) - @test !(isa(ex,Expr) && ex.head === :error) -end -macro f16096() - quote - g16096($(esc(:x))) = 2x - end -end -let g = @f16096 - @test g(3) == 6 -end -macro f16096_2() - quote - g16096_2(;$(esc(:x))=2) = 2x - end -end -let g = @f16096_2 - @test g() == 4 -end - -# issue #15838 -module A15838 - macro f() end - const x = :a -end -module B15838 - import ..A15838.@f - macro f(x); return :x; end - const x = :b -end -@test A15838.@f() === nothing -@test A15838.@f(1) === :b -let nometh = expand(:(A15838.@f(1, 2))) - @test (nometh::Expr).head === :error - @test length(nometh.args) == 1 - e = nometh.args[1]::MethodError - @test e.f === getfield(A15838, Symbol("@f")) - @test e.args === (1,2) -end - -# issue 10046 -for op in ["+", "-", "\$", "|", ".+", ".-", "*", ".*"] - @test_throws ParseError parse("$op in [+, -]") -end - -# issue #17701 -@test expand(:(i==3 && i+=1)) == Expr(:error, "invalid assignment location \"==(i,3)&&i\"") - -# issue #18667 -@test expand(:(true = 1)) == Expr(:error, "invalid assignment location \"true\"") -@test expand(:(false = 1)) == Expr(:error, "invalid assignment location \"false\"") - -# PR #15592 -let str = "[1] [2]" - @test_throws ParseError parse(str) -end - -# issue 15896 and PR 15913 -@test_throws ErrorException eval(:(macro test15896(d; y=0) end)) - -# Issue #16578 (Lowering) mismatch between push_loc and pop_loc -module TestMeta_16578 -using Base.Test -function get_expr_list(ex::CodeInfo) - return ex.code::Array{Any,1} -end -function get_expr_list(ex::Expr) - if ex.head == :thunk - return get_expr_list(ex.args[1]) - else - return ex.args - end -end - -function count_meta_loc(exprs) - push_count = 0 - pop_count = 0 - for expr in exprs - Meta.isexpr(expr, :meta) || continue - expr = expr::Expr - if expr.args[1] === :push_loc - push_count += 1 - elseif expr.args[1] === :pop_loc - pop_count += 1 - end - @test push_count >= pop_count - end - @test push_count == pop_count - return push_count -end - -function is_return_ssavalue(ex::Expr) - ex.head === :return && isa(ex.args[1], SSAValue) -end - -function is_pop_loc(ex::Expr) - ex.head === :meta && ex.args[1] === :pop_loc -end - -# Macros -macro m1() - quote - sin(1) - end -end -macro m2() - quote - 1 - end -end -include_string(""" -macro m3() - quote - @m1 - end -end -macro m4() - quote - @m2 - end -end -""", "another_file.jl") -m1_exprs = get_expr_list(expand(:(@m1))) -m2_exprs = get_expr_list(expand(:(@m2))) -m3_exprs = get_expr_list(expand(:(@m3))) -m4_exprs = get_expr_list(expand(:(@m4))) - -# Check the expanded expresion has expected number of matching push/pop -# and the return is handled correctly -@test count_meta_loc(m1_exprs) == 1 -@test is_return_ssavalue(m1_exprs[end]) -@test is_pop_loc(m1_exprs[end - 1]) - -@test count_meta_loc(m2_exprs) == 1 -@test m2_exprs[end] == :(return 1) -@test is_pop_loc(m2_exprs[end - 1]) - -@test count_meta_loc(m3_exprs) == 2 -@test is_return_ssavalue(m3_exprs[end]) -@test is_pop_loc(m3_exprs[end - 1]) - -@test count_meta_loc(m4_exprs) == 2 -@test m4_exprs[end] == :(return 1) -@test is_pop_loc(m4_exprs[end - 1]) - -function f1(a) - b = a + 100 - b -end - -@generated function f2(a) - quote - b = a + 100 - b - end -end - -f1_exprs = get_expr_list(@code_typed(f1(1))[1]) -f2_exprs = get_expr_list(@code_typed(f2(1))[1]) - -@test Meta.isexpr(f1_exprs[end], :return) -@test is_pop_loc(f2_exprs[end - 1]) -@test Meta.isexpr(f2_exprs[end], :return) - -if Base.JLOptions().code_coverage != 0 && Base.JLOptions().can_inline != 0 - @test count_meta_loc(f1_exprs) == 1 - @test count_meta_loc(f2_exprs) == 2 -else - @test count_meta_loc(f1_exprs) == 0 - @test count_meta_loc(f2_exprs) == 1 -end - -# Check that string and command literals are parsed to the appropriate macros -@test :(x"s") == :(@x_str "s") -@test :(x"s"flag) == :(@x_str "s" "flag") -@test :(x"s\"`\x\$\\") == :(@x_str "s\"`\\x\\\$\\\\") -@test :(x`s`) == :(@x_cmd "s") -@test :(x`s`flag) == :(@x_cmd "s" "flag") -@test :(x`s\`"\x\$\\`) == :(@x_cmd "s`\"\\x\\\$\\\\") - -# Check multiline command literals -@test :``` -multiline -command -``` == :(@cmd "multiline\ncommand\n") - -macro julia_cmd(s) - Meta.quot(parse(s)) -end -@test julia``` -if test + test == test - println(test) -end -```.head == :if - -end - -# issue 18756 -module Mod18756 -mutable struct Type -end -end -@test method_exists(Mod18756.Type, ()) - -# issue 18002 -@test parse("Foo{T} = Bar{T}") == Expr(:(=), Expr(:curly, :Foo, :T), Expr(:curly, :Bar, :T)) - -# don't insert push_loc for filename `none` at the top level -let ex = expand(parse(""" -begin - x = 1 -end""")) - @test !any(x->(x == Expr(:meta, :push_loc, :none)), ex.args) -end - -# Check qualified string macros -Base.r"regex" == r"regex" - -module QualifiedStringMacro -module SubModule -macro x_str(x) - 1 -end -macro y_cmd(x) - 2 -end -end -end - -@test QualifiedStringMacro.SubModule.x"" === 1 -@test QualifiedStringMacro.SubModule.y`` === 2 - -let ..(x,y) = x + y - @test 3 .. 4 === 7 -end - -# issue #7669 -@test parse("@a(b=1, c=2)") == Expr(:macrocall, Symbol("@a"), :(b=1), :(c=2)) - -# issue #19685 -let f = function (x; kw...) - return (x, kw) - end, - g = function (x; a = 2) - return (x, a) - end - @test f(1) == (1, Any[]) - @test g(1) == (1, 2) -end - -# normalization of Unicode symbols (#19464) -let ε=1, μ=2, x=3, î=4 - # issue #5434 (mu vs micro): - @test parse("\u00b5") === parse("\u03bc") - @test µ == μ == 2 - # NFC normalization of identifiers: - @test parse("\u0069\u0302") === parse("\u00ee") - @test î == 4 - # latin vs greek ε (#14751) - @test parse("\u025B") === parse("\u03B5") - @test ɛ == ε == 1 -end - -# issue #8925 -let - global const (c8925, d8925) = (3, 4) -end -@test c8925 == 3 && isconst(:c8925) -@test d8925 == 4 && isconst(:d8925) - -# issue #18754: parse ccall as a regular function -@test parse("ccall([1], 2)[3]") == Expr(:ref, Expr(:call, :ccall, Expr(:vect, 1), 2), 3) -@test parse("ccall(a).member") == Expr(:., Expr(:call, :ccall, :a), QuoteNode(:member)) - -# Check that the body of a `where`-qualified short form function definition gets -# a :block for its body -short_where_call = :(f(x::T) where T = T) -@test short_where_call.args[2].head == :block - -# `where` with multi-line anonymous functions -let f = function (x::T) where T - T - end - @test f(:x) === Symbol -end - -let f = function (x::T, y::S) where T<:S where S - (T,S) - end - @test f(0,1) === (Int,Int) -end - -# issue #20541 -@test parse("[a .!b]") == Expr(:hcat, :a, Expr(:call, :(.!), :b)) - -@test expand(:(a{1} = b)) == Expr(:error, "invalid type parameter name \"1\"") -@test expand(:(a{2<:Any} = b)) == Expr(:error, "invalid type parameter name \"2\"") - -# issue #20653 -@test_throws UndefVarError Base.call(::Int) = 1 -module Test20653 -using Base.Test -struct A -end -call(::A) = 1 -const a = A() -@test_throws MethodError a() -@test call(a) === 1 -end - -# issue #20729 -macro m20729() - ex = Expr(:head) - resize!(ex.args, 1) - return ex -end - -@test_throws ErrorException eval(:(@m20729)) -@test expand(:(@m20729)) == Expr(:error, "undefined reference in AST") - -macro err20000() - return Expr(:error, "oops!") -end - -@test expand(:(@err20000)) == Expr(:error, "oops!") - -# issue #20000 -@test parse("@m(a; b=c)") == Expr(:macrocall, Symbol("@m"), - Expr(:parameters, Expr(:kw, :b, :c)), :a) - -# issue #21054 -macro make_f21054(T) - quote - $(esc(:f21054))(X::Type{<:$T}) = 1 - end -end -@eval @make_f21054 $Array -@test isa(f21054, Function) -g21054(>:) = >:2 -@test g21054(-) == -2 - -# issue #21168 -@test expand(:(a.[1])) == Expr(:error, "invalid syntax a.[1]") -@test expand(:(a.{1})) == Expr(:error, "invalid syntax a.{1}") - -# Issue #21225 -let abstr = parse("abstract type X end") - @test parse("abstract type X; end") == abstr - @test parse(string("abstract type X", ";"^5, " end")) == abstr - @test parse("abstract type X\nend") == abstr - @test parse(string("abstract type X", "\n"^5, "end")) == abstr -end -let prim = parse("primitive type X 8 end") - @test parse("primitive type X 8; end") == prim - @test parse(string("primitive type X 8", ";"^5, " end")) == prim - @test parse("primitive type X 8\nend") == prim - @test parse(string("primitive type X 8", "\n"^5, "end")) == prim -end - -# issue #21155 -@test filter(!isline, - parse("module B - using ..x, - ..y - end").args[3].args)[1] == - Expr(:toplevel, - Expr(:using, Symbol("."), Symbol("."), :x), - Expr(:using, Symbol("."), Symbol("."), :y)) - -@test filter(!isline, - parse("module A - using .B, - .C - end").args[3].args)[1] == - Expr(:toplevel, - Expr(:using, Symbol("."), :B), - Expr(:using, Symbol("."), :C)) - -# issue #21440 -@test parse("+(x::T,y::T) where {T} = 0") == parse("(+)(x::T,y::T) where {T} = 0") -@test parse("a::b::c") == Expr(:(::), Expr(:(::), :a, :b), :c) - -# issue #21545 -f21545(::Type{<: AbstractArray{T,N} where N}) where T = T -@test f21545(Array{Int8}) === Int8 -@test parse("<:{T} where T") == Expr(:where, Expr(:curly, :(<:), :T), :T) -@test parse("<:(T) where T") == Expr(:where, Expr(:(<:), :T), :T) -@test parse("<:{T}(T) where T") == Expr(:where, Expr(:call, Expr(:curly, :(<:), :T), :T), :T) - -# issue #21586 -macro m21586(x) - Expr(:kw, esc(x), 42) -end - -f21586(; @m21586(a), @m21586(b)) = a + b -@test f21586(a=10) == 52 - -# issue #21604 -@test_nowarn @eval module Test21604 - const Foo = Any - struct X - x::Foo - end -end -@test Test21604.X(1.0) === Test21604.X(1.0) - -# comment 298107224 on pull #21607 -module Test21607 - using Base.Test - - @test_warn( - "WARNING: imported binding for Any overwritten in module Test21607", - @eval const Any = Integer) - - # check that X <: Core.Any, not Integer - mutable struct X; end - @test supertype(X) === Core.Any - - # check that return type is Integer - f()::Any = 1.0 - @test f() === 1 - - # check that constructor accepts Any - struct Y - x - end - @test Y(1.0) !== Y(1) - - # check that function default argument type is Any - g(x) = x - @test g(1.0) === 1.0 - - # check that asserted variable type is Integer - @test let - x::Any = 1.0 - x - end === 1 - - # check that unasserted variable type is not Integer - @test let - x = 1.0 - x - end === 1.0 -end - -# let-bound functions with `where` and static parameters -@test let f()::Int = 2.0 - f() -end === 2 -@test let (f(x::T)::Tuple{Int,Any}) where {T} = (3.0, T) - f("") -end === (3, String) - -# issue #19351 -# adding return type decl should not affect parse of function body -@test :(t(abc) = 3).args[2] == :(t(abc)::Int = 3).args[2] - -# issue #23234 -let - f = function (x=0) - x - end - @test f() == 0 - @test f(2) == 2 -end diff --git a/julia-0.6.3/share/julia/test/path.jl b/julia-0.6.3/share/julia/test/path.jl deleted file mode 100644 index e02176c..0000000 --- a/julia-0.6.3/share/julia/test/path.jl +++ /dev/null @@ -1,211 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -for S in (String, GenericString) - dir = pwd() - sep = Base.Filesystem.path_separator - - @test abspath(S("foo")) == "$dir$(sep)foo" - @test abspath(S("foo"), S("bar")) == "$dir$(sep)foo$(sep)bar" - - @test basename(S("foo$(sep)bar")) == "bar" - @test dirname(S("foo$(sep)bar")) == "foo" - - @test expanduser(S("x")) == "x" - @test expanduser(S("~")) == (is_windows() ? "~" : homedir()) - - @test isabspath(S(homedir())) - @test !isabspath(S("foo")) - - @test !isdirpath(S("foo")) - @test isdirpath(S("foo$sep")) - @test isdirpath(S("")) - @test isdirpath(S(".")) - @test isdirpath(S("..")) - - @test joinpath(S("foo")) == "foo" - @test joinpath(S("foo"), S("bar")) == "foo$(sep)bar" - @test joinpath(S("foo"), S(homedir())) == homedir() - @test joinpath(S(abspath("foo")), S(homedir())) == homedir() - - @test normpath(S(joinpath("."))) == "." - @test normpath(S(joinpath(".."))) == ".." - @test normpath(S(joinpath("..","."))) == ".." - @test normpath(S(joinpath(".",".."))) == ".." - @test normpath(S(joinpath("..",".."))) == "..$(sep).." - @test normpath(S(joinpath(".","..",".."))) == "..$(sep).." - @test normpath(S(joinpath("..",".",".."))) == "..$(sep).." - @test normpath(S(joinpath("..","..","."))) == "..$(sep).." - - @test normpath(S(joinpath("foo","."))) == "foo$sep" - @test normpath(S(joinpath("foo",".."))) == "." - @test normpath(S(joinpath("foo","..","."))) == "." - @test normpath(S(joinpath("foo",".",".."))) == "." - @test normpath(S(joinpath("foo","..",".."))) == ".." - @test normpath(S(joinpath("foo",".","..",".."))) == ".." - @test normpath(S(joinpath("foo","..",".",".."))) == ".." - @test normpath(S(joinpath("foo","..","..","."))) == ".." - - @test normpath(S(joinpath(".","bar"))) == "bar" - @test normpath(S(joinpath("..","bar"))) == "..$(sep)bar" - @test normpath(S(joinpath("..",".","bar"))) == "..$(sep)bar" - @test normpath(S(joinpath(".","..","bar"))) == "..$(sep)bar" - @test normpath(S(joinpath("..","..","bar"))) == "..$(sep)..$(sep)bar" - @test normpath(S(joinpath(".","..","..","bar"))) == "..$(sep)..$(sep)bar" - @test normpath(S(joinpath("..",".","..","bar"))) == "..$(sep)..$(sep)bar" - @test normpath(S(joinpath("..","..",".","bar"))) == "..$(sep)..$(sep)bar" - - @test normpath(S(joinpath("foo",".","bar"))) == "foo$(sep)bar" - @test normpath(S(joinpath("foo","..","bar"))) == "bar" - @test normpath(S(joinpath("foo","..",".","bar"))) == "bar" - @test normpath(S(joinpath("foo",".","..","bar"))) == "bar" - @test normpath(S(joinpath("foo","..","..","bar"))) == "..$(sep)bar" - @test normpath(S(joinpath("foo",".","..","..","bar"))) == "..$(sep)bar" - @test normpath(S(joinpath("foo","..",".","..","bar"))) == "..$(sep)bar" - @test normpath(S(joinpath("foo","..","..",".","bar"))) == "..$(sep)bar" - - @test relpath(S(joinpath("foo","bar")), S("foo")) == "bar" - - @test joinpath(splitdir(S(homedir()))...) == homedir() - @test string(splitdrive(S(homedir()))...) == homedir() - - if is_windows() - @test splitdrive(S("\\\\servername\\hello.world\\filename.ext")) == - ("\\\\servername\\hello.world","\\filename.ext") - @test splitdrive(S("\\\\servername.com\\hello.world\\filename.ext")) == - ("\\\\servername.com\\hello.world","\\filename.ext") - @test splitdrive(S("C:\\foo\\bar")) == - ("C:","\\foo\\bar") - end - - @test splitext(S("")) == ("", "") - @test splitext(S(".")) == (".", "") - @test_broken splitext(S("..")) == ("..", "") - @test_broken splitext(S("...")) == ("...", "") - @test splitext(S("foo")) == ("foo", "") - @test splitext(S("foo.")) == ("foo", ".") - @test_broken splitext(S("foo..")) == ("foo", "..") - @test_broken splitext(S("foo...")) == ("foo", "...") - @test splitext(S("foo.bar")) == ("foo", ".bar") - @test splitext(S(".foo")) == (".foo", "") - @test splitext(S(".foo.")) == (".foo", ".") - @test_broken splitext(S(".foo..")) == (".foo", "..") - @test_broken splitext(S(".foo...")) == (".foo", "...") - @test splitext(S(".foo.bar")) == (".foo", ".bar") -end - -@test isabspath("~") == false -@test isabspath("/") == true # on windows, this is relatively absolute -@test isabspath("A:/") == is_windows() -@test isabspath("B:\\") == is_windows() -@test isabspath("./") == false -@test isabspath("C:") == false -@test isabspath("C:.") == false -@test isabspath("α:/") == false -@test isabspath(".:/") == false -#@test isabspath("_:/") == false # FIXME? -#@test isabspath("AB:/") == false # FIXME? -@test isabspath("\\\\") == is_windows() -if is_unix() - @test isabspath(expanduser("~")) == true - @test startswith(expanduser("~"), homedir()) -else - @test expanduser("~") == "~" -end - -############################################ -# This section tests relpath computation. # -########################################### -function test_relpath() - sep = Base.Filesystem.path_separator - filepaths = [ - "$(sep)home$(sep)user$(sep).julia$(sep)Test1$(sep)docs$(sep)api$(sep)Test1.md", - "$(sep)home$(sep)user$(sep).julia$(sep)Test1$(sep)docs$(sep)api$(sep)lib$(sep)file1.md", - "$(sep)home$(sep)user$(sep).julia$(sep)测试2$(sep)docs$(sep)api$(sep)测试2.md", - "$(sep)home$(sep)user$(sep)dir_withendsep$(sep)", - "$(sep)home$(sep)dir2_withendsep$(sep)", - "$(sep)home$(sep)test.md", - "$(sep)home", - # Special cases - "$(sep)", - "$(sep)home$(sep)$(sep)$(sep)" - ] - startpaths = [ - "$(sep)home$(sep)user$(sep).julia$(sep)Test1$(sep)docs$(sep)api$(sep)genindex.md", - "$(sep)multi_docs$(sep)genindex.md", - "$(sep)home$(sep)user$(sep)dir_withendsep$(sep)", - "$(sep)home$(sep)dir2_withendsep$(sep)", - "$(sep)home$(sep)test.md", - "$(sep)home", - # Special cases - "$(sep)", - "$(sep)home$(sep)$(sep)$(sep)" - ] - relpath_expected_results = [ - "..$(sep)Test1.md", - "..$(sep)..$(sep)home$(sep)user$(sep).julia$(sep)Test1$(sep)docs$(sep)api$(sep)Test1.md", - "..$(sep).julia$(sep)Test1$(sep)docs$(sep)api$(sep)Test1.md", - "..$(sep)user$(sep).julia$(sep)Test1$(sep)docs$(sep)api$(sep)Test1.md", - "..$(sep)user$(sep).julia$(sep)Test1$(sep)docs$(sep)api$(sep)Test1.md", - "user$(sep).julia$(sep)Test1$(sep)docs$(sep)api$(sep)Test1.md", - "home$(sep)user$(sep).julia$(sep)Test1$(sep)docs$(sep)api$(sep)Test1.md", - "user$(sep).julia$(sep)Test1$(sep)docs$(sep)api$(sep)Test1.md", - "..$(sep)lib$(sep)file1.md", - "..$(sep)..$(sep)home$(sep)user$(sep).julia$(sep)Test1$(sep)docs$(sep)api$(sep)lib$(sep)file1.md", - "..$(sep).julia$(sep)Test1$(sep)docs$(sep)api$(sep)lib$(sep)file1.md", - "..$(sep)user$(sep).julia$(sep)Test1$(sep)docs$(sep)api$(sep)lib$(sep)file1.md", - "..$(sep)user$(sep).julia$(sep)Test1$(sep)docs$(sep)api$(sep)lib$(sep)file1.md", - "user$(sep).julia$(sep)Test1$(sep)docs$(sep)api$(sep)lib$(sep)file1.md", - "home$(sep)user$(sep).julia$(sep)Test1$(sep)docs$(sep)api$(sep)lib$(sep)file1.md", - "user$(sep).julia$(sep)Test1$(sep)docs$(sep)api$(sep)lib$(sep)file1.md", - "..$(sep)..$(sep)..$(sep)..$(sep)测试2$(sep)docs$(sep)api$(sep)测试2.md", - "..$(sep)..$(sep)home$(sep)user$(sep).julia$(sep)测试2$(sep)docs$(sep)api$(sep)测试2.md", - "..$(sep).julia$(sep)测试2$(sep)docs$(sep)api$(sep)测试2.md", - "..$(sep)user$(sep).julia$(sep)测试2$(sep)docs$(sep)api$(sep)测试2.md", - "..$(sep)user$(sep).julia$(sep)测试2$(sep)docs$(sep)api$(sep)测试2.md", - "user$(sep).julia$(sep)测试2$(sep)docs$(sep)api$(sep)测试2.md", - "home$(sep)user$(sep).julia$(sep)测试2$(sep)docs$(sep)api$(sep)测试2.md", - "user$(sep).julia$(sep)测试2$(sep)docs$(sep)api$(sep)测试2.md", - "..$(sep)..$(sep)..$(sep)..$(sep)..$(sep)dir_withendsep", - "..$(sep)..$(sep)home$(sep)user$(sep)dir_withendsep",".","..$(sep)user$(sep)dir_withendsep", - "..$(sep)user$(sep)dir_withendsep","user$(sep)dir_withendsep", - "home$(sep)user$(sep)dir_withendsep","user$(sep)dir_withendsep", - "..$(sep)..$(sep)..$(sep)..$(sep)..$(sep)..$(sep)dir2_withendsep", - "..$(sep)..$(sep)home$(sep)dir2_withendsep","..$(sep)..$(sep)dir2_withendsep",".", - "..$(sep)dir2_withendsep","dir2_withendsep","home$(sep)dir2_withendsep","dir2_withendsep", - "..$(sep)..$(sep)..$(sep)..$(sep)..$(sep)..$(sep)test.md","..$(sep)..$(sep)home$(sep)test.md", - "..$(sep)..$(sep)test.md","..$(sep)test.md",".","test.md","home$(sep)test.md","test.md", - "..$(sep)..$(sep)..$(sep)..$(sep)..$(sep)..","..$(sep)..$(sep)home","..$(sep)..", - "..","..",".","home",".","..$(sep)..$(sep)..$(sep)..$(sep)..$(sep)..$(sep)..","..$(sep)..", - "..$(sep)..$(sep)..","..$(sep)..","..$(sep)..","..",".","..", - "..$(sep)..$(sep)..$(sep)..$(sep)..$(sep)..","..$(sep)..$(sep)home","..$(sep)..", - "..","..",".","home","." - ] - idx = 0 - for filep in filepaths - for startp in startpaths - res = relpath(filep, startp) - idx += 1 - @test res == relpath_expected_results[idx] - end - end - # Additional cases - @test_throws ArgumentError relpath("$(sep)home$(sep)user$(sep)dir_withendsep$(sep)", "") - @test_throws ArgumentError relpath("", "$(sep)home$(sep)user$(sep)dir_withendsep$(sep)") -end -test_relpath() - -# Test type stability -@test isa(joinpath("a", "b"), String) -@test isa(joinpath(abspath("a"), "b"), String) - -# homedir -let var = is_windows() ? "USERPROFILE" : "HOME", - MAX_PATH = is_windows() ? 240 : 1020 - for i = 0:9 - local home = " "^MAX_PATH * "123456789"[1:i] - @test withenv(var => home) do - homedir() - end == home - end - @test isabspath(withenv(homedir, var => nothing)) -end diff --git a/julia-0.6.3/share/julia/test/pkg.jl b/julia-0.6.3/share/julia/test/pkg.jl deleted file mode 100644 index 16ce24d..0000000 --- a/julia-0.6.3/share/julia/test/pkg.jl +++ /dev/null @@ -1,642 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -import Base.Pkg.PkgError - -function capture_stdout(f::Function) - let fname = tempname() - try - open(fname, "w") do fout - redirect_stdout(fout) do - f() - end - end - return readstring(fname) - finally - rm(fname, force=true) - end - end -end - - -function temp_pkg_dir(fn::Function, tmp_dir=joinpath(tempdir(), randstring()), - remove_tmp_dir::Bool=true; initialize::Bool=true) - - # Used in tests below to set up and tear down a sandboxed package directory - withenv("JULIA_PKGDIR" => tmp_dir) do - @test !isdir(Pkg.dir()) - try - if initialize - Pkg.init() - @test isdir(Pkg.dir()) - Pkg.resolve() - else - mkpath(Pkg.dir()) - end - fn() - finally - remove_tmp_dir && rm(tmp_dir, recursive=true) - end - end -end - -function write_build(pkg, content) - build_filename = Pkg.dir(pkg, "deps", "build.jl") - mkpath(dirname(build_filename)) - write(build_filename, content) -end - -# Test basic operations: adding or removing a package, status, free -# Also test for the existence of REQUIRE and META_BRANCH -temp_pkg_dir() do - @test isfile(joinpath(Pkg.dir(),"REQUIRE")) - @test isfile(joinpath(Pkg.dir(),"META_BRANCH")) - @test isempty(Pkg.installed()) - @test sprint(Pkg.status) == "No packages installed\n" - @test !isempty(Pkg.available()) - - # 18325 - cd(Pkg.dir()) do - avail = Pkg.Read.available() - avail_copy = Pkg.Query.availcopy(avail); - delete!(avail_copy["Example"][v"0.0.1"].requires, "julia") - @test haskey(avail["Example"][v"0.0.1"].requires, "julia") - end - - @test_throws PkgError Pkg.installed("MyFakePackage") - @test Pkg.installed("Example") === nothing - - # check that versioninfo(io, true) doesn't error and produces some output - # (done here since it calls Pkg.status which might error or clone metadata) - buf = PipeBuffer() - versioninfo(buf, true) - ver = readstring(buf) - @test startswith(ver, "Julia Version $VERSION") - @test contains(ver, "Environment:") - - # Check that setprotocol! works. - begin - try - Pkg.setprotocol!("notarealprotocol") - Pkg.add("Example") - error("unexpected") - catch ex - if isa(ex, CompositeException) - ex = ex.exceptions[1] - - if isa(ex, CapturedException) - ex = ex.ex - end - end - @test isa(ex,Pkg.PkgError) - @test contains(ex.msg, "Cannot clone Example from notarealprotocol://github.com/JuliaLang/Example.jl.git") - end - end - - Pkg.setprotocol!("") - @test Pkg.Cache.rewrite_url_to === nothing - Pkg.setprotocol!("https") - Pkg.add("Example") - @test [keys(Pkg.installed())...] == ["Example"] - iob = IOBuffer() - Pkg.checkout("Example") - Pkg.status("Example", iob) - str = chomp(String(take!(iob))) - @test startswith(str, " - Example") - @test endswith(str, "master") - Pkg.free("Example") - Pkg.status("Example", iob) - str = chomp(String(take!(iob))) - @test endswith(str, string(Pkg.installed("Example"))) - Pkg.checkout("Example") - Pkg.free(("Example",)) - Pkg.status("Example", iob) - str = chomp(String(take!(iob))) - @test endswith(str, string(Pkg.installed("Example"))) - Pkg.rm("Example") - @test isempty(Pkg.installed()) - @test !isempty(Pkg.available("Example")) - @test !in("Example", keys(Pkg.installed())) - Pkg.rm("Example") - @test isempty(Pkg.installed()) - @test !isempty(Pkg.available("Example")) - @test !in("Example", keys(Pkg.installed())) - Pkg.clone("https://github.com/JuliaLang/Example.jl.git") - @test [keys(Pkg.installed())...] == ["Example"] - Pkg.status("Example", iob) - str = chomp(String(take!(iob))) - @test startswith(str, " - Example") - @test endswith(str, "master") - Pkg.free("Example") - Pkg.status("Example", iob) - str = chomp(String(take!(iob))) - @test endswith(str, string(Pkg.installed("Example"))) - Pkg.checkout("Example") - Pkg.free(("Example",)) - Pkg.status("Example", iob) - str = chomp(String(take!(iob))) - @test endswith(str, string(Pkg.installed("Example"))) - - # 17364 - a, Pkg.checkout with specific local branch - let branch_name = "test-branch-1", - branch_commit = "ba3888212e30a7974ac6803a89e64c7098f4865e" - - # create a branch in Example package - LibGit2.with(LibGit2.GitRepo, Pkg.dir("Example")) do repo - LibGit2.branch!(repo, branch_name, branch_commit, set_head=false) - end - - Pkg.clone(Pkg.dir("Example"), "Example2") - Pkg.clone(Pkg.dir("Example"), "Example3") - open(Pkg.dir("Example3", "README.md"), "w") do f - println(f, "overwritten") - end - LibGit2.with(LibGit2.GitRepo, Pkg.dir("Example3")) do repo - LibGit2.add!(repo, "README.md") - test_sig = LibGit2.Signature("TEST", "TEST@TEST.COM", round(time(), 0), 0) - LibGit2.commit(repo, "testmsg"; author=test_sig, committer=test_sig) - end - - Pkg.checkout("Example2", branch_name) - Pkg.checkout("Example3", branch_name) - - LibGit2.with(LibGit2.GitRepo, Pkg.dir("Example2")) do repo - @test LibGit2.head_oid(repo) == LibGit2.GitHash(branch_commit) - end - LibGit2.with(LibGit2.GitRepo, Pkg.dir("Example3")) do repo - @test LibGit2.head_oid(repo) == LibGit2.GitHash(branch_commit) - end - end - - # 17364 - b, remote off-tree branch - let branch_name = "test-branch-2", - branch_commit = "ba3888212e30a7974ac6803a89e64c7098f4865e" - - # create a branch in Example package - LibGit2.with(LibGit2.GitRepo, Pkg.dir("Example")) do repo - LibGit2.branch!(repo, branch_name, branch_commit, set_head=true) - end - - # Make changes to local branch - open(Pkg.dir("Example", "README.md"), "w") do f - println(f, "overwritten") - end - - test_commit = LibGit2.with(LibGit2.GitRepo, Pkg.dir("Example")) do repo - LibGit2.add!(repo, "README.md") - test_sig = LibGit2.Signature("TEST", "TEST@TEST.COM", round(time(), 0), 0) - LibGit2.commit(repo, "testmsg"; author=test_sig, committer=test_sig) - end - Pkg.checkout("Example") - - Pkg.clone(Pkg.dir("Example"), "Example4") - Pkg.checkout("Example4", branch_name) - - LibGit2.with(LibGit2.GitRepo, Pkg.dir("Example4")) do repo - @test LibGit2.head_oid(repo) == test_commit - end - end - - # adding a package with unsatisfiable julia version requirements (REPL.jl) errors - try - Pkg.add("REPL") - error("unexpected") - catch err - @test isa(err.exceptions[1].ex, PkgError) - @test err.exceptions[1].ex.msg == "REPL can't be installed because " * - "it has no versions that support $VERSION of julia. You may " * - "need to update METADATA by running `Pkg.update()`" - end - - # trying to add, check availability, or pin a nonexistent package errors - try - Pkg.add("NonexistentPackage") - error("unexpected") - catch err - @test isa(err.exceptions[1].ex, PkgError) - @test err.exceptions[1].ex.msg == "unknown package NonexistentPackage" - end - try - Pkg.available("NonexistentPackage") - error("unexpected") - catch err - @test isa(err, PkgError) - @test err.msg == "NonexistentPackage is not a package (not registered or installed)" - end - try - Pkg.pin("NonexistentPackage", v"1.0.0") - error("unexpected") - catch err - @test isa(err, PkgError) - @test err.msg == "NonexistentPackage is not a git repo" - end - - # trying to pin a git repo under Pkg.dir that is not an installed package errors - try - Pkg.pin("METADATA", v"1.0.0") - error("unexpected") - catch err - @test isa(err, PkgError) - @test err.msg == "METADATA cannot be pinned – not an installed package" - end - - # trying to pin an installed, registered package to an unregistered version errors - try - Pkg.pin("Example", v"2147483647.0.0") - error("unexpected") - catch err - @test isa(err, PkgError) - @test err.msg == "Example – 2147483647.0.0 is not a registered version" - end - - # PR #13572, handling of versions with untagged detached heads - LibGit2.with(LibGit2.GitRepo, Pkg.dir("Example")) do repo - LibGit2.checkout!(repo, "72f09c7d0099793378c645929a9961155faae6d2") - end - @test Pkg.installed()["Example"] > v"0.0.0" - - # issue #13583 - begin - try - Pkg.test("IDoNotExist") - error("unexpected") - catch ex - @test isa(ex,Pkg.Entry.PkgTestError) - @test ex.msg == "IDoNotExist is not an installed package" - end - - try - Pkg.test("IDoNotExist1", "IDoNotExist2") - error("unexpected") - catch ex - @test isa(ex,Pkg.Entry.PkgTestError) - @test ex.msg == "IDoNotExist1 and IDoNotExist2 are not installed packages" - end - end - - # Various pin/free/re-pin/change-pin patterns (issue #17176) - @test "" == capture_stdout() do - @test_warn "INFO: Freeing Example" Pkg.free("Example") - - @test_warn r"^INFO: Creating Example branch pinned\.[0-9a-f]{8}\.tmp$" Pkg.pin("Example") - vers = Pkg.installed("Example") - branch = LibGit2.with(LibGit2.GitRepo, Pkg.dir("Example")) do repo - LibGit2.branch(repo) - end - - @test_warn "INFO: Freeing Example" Pkg.free("Example") - - @test_warn ("INFO: Creating Example branch pinned.b1990792.tmp", - "INFO: No packages to install, update or remove") Pkg.pin("Example", v"0.4.0") - @test Pkg.installed("Example") == v"0.4.0" - - @test_warn r"^INFO: Package Example is already pinned to the selected commit$" Pkg.pin("Example", v"0.4.0") - @test Pkg.installed("Example") == v"0.4.0" - - @test_warn r"^INFO: Package Example is already pinned$" Pkg.pin("Example") - @test Pkg.installed("Example") == v"0.4.0" - - @test_warn "INFO: Package Example: skipping update (pinned)..." Pkg.update() - @test Pkg.installed("Example") == v"0.4.0" - - @test_warn ("INFO: Creating Example branch pinned.d1ef7b00.tmp", - "INFO: No packages to install, update or remove") Pkg.pin("Example", v"0.3.1") - @test Pkg.installed("Example") == v"0.3.1" - - @test_warn ("INFO: Package Example: checking out existing branch pinned.b1990792.tmp", - "INFO: No packages to install, update or remove") Pkg.pin("Example", v"0.4.0") - @test Pkg.installed("Example") == v"0.4.0" - - @test_warn ("INFO: Freeing Example", - "INFO: No packages to install, update or remove") Pkg.free("Example") - @test Pkg.installed("Example") == vers - - @test_warn Regex("^INFO: Package Example: checking out existing branch $branch\$") Pkg.pin("Example") - @test Pkg.installed("Example") == vers - - @test_warn "INFO: Freeing Example" Pkg.free("Example") - @test Pkg.installed("Example") == vers - end - - begin - # bug identified in #16850, Base.url \ vs / for non-Base methods - include(Pkg.dir("Example","src","Example.jl")) - meth = first(methods(Example.domath)) - fname = string(meth.file) - @test ('\\' in fname) == is_windows() - @test startswith(Base.url(meth), "https://github.com/JuliaLang/Example.jl/tree") - end - - # add a directory that is not a git repository - begin - mkdir(joinpath(Pkg.dir(), "NOTGIT")) - Pkg.installed("NOTGIT") == typemin(VersionNumber) - Pkg.installed()["NOTGIT"] == typemin(VersionNumber) - end - - begin - # don't bork when a Pkg repo is bare, issue #13804 - pth = joinpath(Pkg.dir(), "BAREGIT") - mkdir(pth) - # create a bare repo (isbare = true) - repo = LibGit2.init(pth, true) - @test repo.ptr != C_NULL - close(repo) - Pkg.update() - end - - #test PkgDev redirects - begin - try - Pkg.register("IDoNotExist") - error("unexpected") - catch ex - @test ex.msg == "Pkg.register(pkg,[url]) has been moved to the package PkgDev.jl.\nRun Pkg.add(\"PkgDev\") to install PkgDev on Julia v0.5-" - end - - try - Pkg.tag("IDoNotExist") - error("unexpected") - catch ex - @test ex.msg == "Pkg.tag(pkg, [ver, [commit]]) has been moved to the package PkgDev.jl.\nRun Pkg.add(\"PkgDev\") to install PkgDev on Julia v0.5-" - end - - try - Pkg.generate("IDoNotExist","MIT") - error("unexpected") - catch ex - @test ex.msg == "Pkg.generate(pkg, license) has been moved to the package PkgDev.jl.\nRun Pkg.add(\"PkgDev\") to install PkgDev on Julia v0.5-" - end - - try - Pkg.publish() - error("unexpected") - catch ex - @test ex.msg == "Pkg.publish() has been moved to the package PkgDev.jl.\nRun Pkg.add(\"PkgDev\") to install PkgDev on Julia v0.5-" - end - - try - Pkg.license() - error("unexpected") - catch ex - @test ex.msg == "Pkg.license([lic]) has been moved to the package PkgDev.jl.\nRun Pkg.add(\"PkgDev\") to install PkgDev on Julia v0.5-" - end - try - Pkg.submit("IDoNotExist") - error("unexpected") - catch ex - @test ex.msg == "Pkg.submit(pkg[, commit]) has been moved to the package PkgDev.jl.\nRun Pkg.add(\"PkgDev\") to install PkgDev on Julia v0.5-" - end - try - Pkg.submit("IDoNotExist", "nonexistentcommit") - error("unexpected") - catch ex - @test ex.msg == "Pkg.submit(pkg[, commit]) has been moved to the package PkgDev.jl.\nRun Pkg.add(\"PkgDev\") to install PkgDev on Julia v0.5-" - end - end - - # Test Pkg.Read.url works - @test Pkg.Read.url("Example") == "git://github.com/JuliaLang/Example.jl.git" - - # issue #15789, build failure warning are printed correctly. - # Also makes sure `Pkg.build()` works even for non-git repo - begin - pth = joinpath(Pkg.dir(), "BuildFail") - mkdir(pth) - depspath = joinpath(pth, "deps") - mkdir(depspath) - depsbuild = joinpath(depspath, "build.jl") - touch(depsbuild) - # Pkg.build works without the src directory now - # but it's probably fine to require it. - msg = readstring(`$(Base.julia_cmd()) --startup-file=no -e 'redirect_stderr(STDOUT); Pkg.build("BuildFail")'`) - @test contains(msg, "Building BuildFail") - @test !contains(msg, "ERROR") - open(depsbuild, "w") do fd - println(fd, "error(\"Throw build error\")") - end - msg = readstring(`$(Base.julia_cmd()) --startup-file=no -e 'redirect_stderr(STDOUT); Pkg.build("BuildFail")'`) - @test contains(msg, "Building BuildFail") - @test contains(msg, "ERROR") - @test contains(msg, "Pkg.build(\"BuildFail\")") - @test contains(msg, "Throw build error") - end - - # issue #15948 - let package = "Example" - Pkg.rm(package) # Remove package if installed - @test Pkg.installed(package) === nothing # Registered with METADATA but not installed - msg = readstring(ignorestatus(`$(Base.julia_cmd()) --startup-file=no -e "redirect_stderr(STDOUT); Pkg.build(\"$package\")"`)) - @test contains(msg, "$package is not an installed package") - @test !contains(msg, "signal (15)") - end - - # issue #20695 - Pkg.cd() do - @test Pkg.Entry.url_and_pkg("Example") == ("git://github.com/JuliaLang/Example.jl.git", "Example") - for url = [ - "https://github.com/Org/Nonsense", - "git@github.com:Org/Nonsense", - "file:///home/user/Nonsense", - "/home/user/Nonsense", - ] - @test Pkg.Entry.url_and_pkg(url) == (url, "Nonsense") - @test Pkg.Entry.url_and_pkg("$url.jl") == ("$url.jl", "Nonsense") - @test Pkg.Entry.url_and_pkg("$url.git") == ("$url.git", "Nonsense") - @test Pkg.Entry.url_and_pkg("$url.jl.git") == ("$url.jl.git", "Nonsense") - end - pkg = randstring(20) - @test Pkg.Entry.url_and_pkg(pkg) == (pkg, pkg) - end - - # partial Pkg.update - @test "" == capture_stdout() do - nothingtodomsg = "INFO: No packages to install, update or remove" - - @test_warn "INFO: Installing Example v" begin - Pkg.rm("Example") - Pkg.add("Example") - end - - @test_warn nothingtodomsg Pkg.update("Example") - - @test_warn "INFO: Installing Example v0.4.0" begin - Pkg.rm("Example") - Pkg.add("Example", v"0", v"0.4.1-") # force version to be < 0.4.1 - end - - @test_warn (r"INFO: Package Example was set to version 0\.4\.0, but a higher version \d+\.\d+\.\d+\S* exists.", - "The update is prevented by explicit requirements constraints. Edit your REQUIRE file to change this.", - nothingtodomsg) Pkg.update("Example") - - @test_warn "INFO: Installing Example" begin - Pkg.rm("Example") - Pkg.add("Example") - Pkg.pin("Example", v"0.4.0") - end - - @test_warn ("INFO: Package Example: skipping update (pinned)...", - r"INFO: Package Example was set to version 0\.4\.0, but a higher version \d+\.\d+\.\d+\S* exists.", - "The package is fixed. You can try using `Pkg.free(\"Example\")` to update it.", - nothingtodomsg) Pkg.update("Example") - - metadata_dir = Pkg.dir("METADATA") - const old_commit = "313bfaafa301e82d40574a778720e893c559a7e2" - - # Force a METADATA rollback to an old version, so that we will install some - # outdated versions of some packages and then update some of those - # (note that the following Pkg.update calls will update METADATA to the - # latest version even though they don't update all packages) - LibGit2.with(LibGit2.GitRepo, metadata_dir) do repo - LibGit2.reset!(repo, LibGit2.GitHash(old_commit), LibGit2.Consts.RESET_HARD) - end - - # run these at an old metadata commit where it's guaranteed no - # packages depend on Example.jl - @test isempty(Pkg.dependents("Example")) - @test isempty(Pkg.dependents("Example.jl")) - - @test_warn s -> !contains(s, "updated but were already imported") begin - Pkg.add("Iterators") - Pkg.update("Iterators") - end - - # Do it again, because the above Iterators test will update things prematurely - LibGit2.with(LibGit2.GitRepo, metadata_dir) do repo - LibGit2.reset!(repo, LibGit2.GitHash(old_commit), LibGit2.Consts.RESET_HARD) - end - - @test_warn ("INFO: Installing Colors v0.6.4", - "INFO: Installing ColorTypes v0.2.2", - "INFO: Installing FixedPointNumbers v0.1.3", - "INFO: Installing Compat v0.7.18", - "INFO: Installing Reexport v0.0.3") Pkg.add("Colors") - - @test_warn (r"INFO: Upgrading ColorTypes: v0\.2\.2 => v\d+\.\d+\.\d+", - r"INFO: Upgrading Compat: v0\.7\.18 => v\d+\.\d+\.\d+", - s -> !contains(s, "INFO: Upgrading Colors: ")) Pkg.update("ColorTypes") - @test Pkg.installed("Colors") == v"0.6.4" - - @test_warn nothingtodomsg Pkg.update("FixedPointNumbers") - end - - # issue #18239 - let package = "Example" - Pkg.free(package) - Pkg.rm(package) # Remove package if installed - - metadata_dir = Pkg.dir("METADATA") - const old_commit = "83ff7116e51fc9cdbd7e67affbd344b9f5c9dbf2" - - # Reset METADATA to the second to last update of Example.jl - LibGit2.with(LibGit2.GitRepo, metadata_dir) do repo - LibGit2.reset!(repo, LibGit2.GitHash(old_commit), LibGit2.Consts.RESET_HARD) - end - - Pkg.add(package) - msg = readstring(ignorestatus(`$(Base.julia_cmd()) --startup-file=no -e - "redirect_stderr(STDOUT); using Example; Pkg.update(\"$package\")"`)) - @test contains(msg, "- $package\nRestart Julia to use the updated versions.") - end - - let package = "Output" - stdout_file = Pkg.dir(package, "stdout.txt") - stderr_file = Pkg.dir(package, "stderr.txt") - content = """ - println(STDOUT, "stdout") - println(STDERR, "stderr") - """ - write_build(package, content) - - code = "Pkg.build(\"$package\")" - msg = run(pipeline( - `$(Base.julia_cmd()) --startup-file=no -e $code`, - stdout=stdout_file, stderr=stderr_file)) - @test last(readlines(stdout_file)) == "stdout" - @test last(readlines(stderr_file)) == "stderr" - end -end - -@testset "Pkg functions with .jl extension" begin - temp_pkg_dir() do - @test Pkg.installed("Example.jl") === nothing - Pkg.add("Example.jl") - @test [keys(Pkg.installed())...] == ["Example"] - iob = IOBuffer() - Pkg.update("Example.jl") - Pkg.checkout("Example.jl") - Pkg.status("Example.jl", iob) - str = chomp(String(take!(iob))) - @test startswith(str, " - Example") - @test endswith(str, "master") - Pkg.free("Example.jl") - Pkg.status("Example.jl", iob) - str = chomp(String(take!(iob))) - @test endswith(str, string(Pkg.installed("Example.jl"))) - Pkg.checkout("Example.jl") - Pkg.free(("Example.jl",)) - Pkg.status("Example.jl", iob) - str = chomp(String(take!(iob))) - @test endswith(str, string(Pkg.installed("Example.jl"))) - Pkg.rm("Example.jl") - @test isempty(Pkg.installed()) - @test !isempty(Pkg.available("Example.jl")) - @test !in("Example", keys(Pkg.installed())) - Pkg.rm("Example.jl") - @test isempty(Pkg.installed()) - @test !isempty(Pkg.available("Example.jl")) - @test !in("Example", keys(Pkg.installed())) - Pkg.clone("https://github.com/JuliaLang/Example.jl.git") - @test [keys(Pkg.installed())...] == ["Example"] - Pkg.status("Example.jl", iob) - str = chomp(String(take!(iob))) - @test startswith(str, " - Example") - @test endswith(str, "master") - Pkg.free("Example.jl") - Pkg.status("Example.jl", iob) - str = chomp(String(take!(iob))) - @test endswith(str, string(Pkg.installed("Example.jl"))) - Pkg.checkout("Example.jl") - Pkg.free(("Example.jl",)) - Pkg.status("Example.jl", iob) - str = chomp(String(take!(iob))) - @test endswith(str, string(Pkg.installed("Example.jl"))) - end -end - -let io = IOBuffer() - Base.showerror(io, Base.Pkg.Entry.PkgTestError("ppp"), backtrace()) - @test !contains(String(take!(io)), "backtrace()") -end - -@testset "Relative path operations" begin - cd(tempdir()) do - temp_pkg_dir(randstring()) do - Pkg.add("Example") - @test [keys(Pkg.installed())...] == ["Example"] - end - end -end - -temp_pkg_dir(initialize=false) do - write_build("Normal", "") - write_build("Error", "error(\"An error has occurred while building a package\")") - write_build("Exit", "exit()") - - cd(Pkg.dir()) do - errors = Dict() - - empty!(errors) - @test_warn ("INFO: Building Error", - "INFO: Building Normal") Pkg.Entry.build!(["Error", "Normal"], errors) - - empty!(errors) - @test_warn ("INFO: Building Exit", - "INFO: Building Normal") Pkg.Entry.build!(["Exit", "Normal"], errors) - - empty!(errors) - @test_warn ("INFO: Building Exit", - "INFO: Building Normal", - "INFO: Building Exit", - "INFO: Building Normal") Pkg.Entry.build!(["Exit", "Normal", "Exit", "Normal"], errors) - end -end diff --git a/julia-0.6.3/share/julia/test/pollfd.jl b/julia-0.6.3/share/julia/test/pollfd.jl deleted file mode 100644 index 0218ac8..0000000 --- a/julia-0.6.3/share/julia/test/pollfd.jl +++ /dev/null @@ -1,147 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -# This script does the following -# Sets up n unix pipes -# For the odd pipes, a byte is written to the write end at intervals specified in intvls -# Nothing is written into the even numbered pipes -# Odd numbered pipes are tested for reads -# Even numbered pipes are tested for timeouts -# Writable ends are always tested for writability before a write - -n = 20 -intvls = [2, .2, .1, .005] - -pipe_fds = Vector{Any}(n) -for i in 1:n - @static if is_windows() - pipe_fds[i] = Array{Libc.WindowsRawSocket}(2) - 0 == ccall(:wsasocketpair, Cint, (Cint, Cuint, Cint, Ptr{Libc.WindowsRawSocket}), 1, 1, 6, pipe_fds[i]) || error(Libc.FormatMessage()) - else - pipe_fds[i] = Array{RawFD}(2) - @test 0 == ccall(:pipe, Cint, (Ptr{RawFD},), pipe_fds[i]) - end -end - -function pfd_tst_reads(idx, intvl) - global ready += 1 - wait(ready_c) - tic() - start_evt2 = Condition() - evt2 = @async (notify(start_evt2); poll_fd(pipe_fds[idx][1], intvl; readable=true, writable=false)) - wait(start_evt2); yield() # make sure the async poll_fd is pumping events - evt = poll_fd(pipe_fds[idx][1], intvl; readable=true, writable=false) - t_elapsed = toq() - @test !evt.timedout - @test evt.readable - @test !evt.writable - @test evt === wait(evt2) - - # println("Expected ", intvl, ", actual ", t_elapsed, ", diff ", t_elapsed - intvl) - # Disabled since this assertion fails randomly, notably on build VMs (issue #12824) - # @test t_elapsed <= (intvl + 1) - - dout = Array{UInt8}(1) - @static if is_windows() - 1 == ccall(:recv, stdcall, Cint, (Ptr{Void}, Ptr{UInt8}, Cint, Cint), pipe_fds[idx][1], dout, 1, 0) || error(Libc.FormatMessage()) - else - @test 1 == ccall(:read, Csize_t, (Cint, Ptr{UInt8}, Csize_t), pipe_fds[idx][1], dout, 1) - end - @test dout[1] == Int8('A') -end - - -function pfd_tst_timeout(idx, intvl) - global ready += 1 - wait(ready_c) - tic() - start_evt2 = Condition() - evt2 = @async (notify(start_evt2); poll_fd(pipe_fds[idx][1], intvl; readable=true, writable=false)) - wait(start_evt2); yield() # make sure the async poll_fd is pumping events - evt = poll_fd(pipe_fds[idx][1], intvl; readable=true, writable=false) - @test evt.timedout - @test !evt.readable - @test !evt.writable - @test evt === wait(evt2) - t_elapsed = toq() - - # Disabled since these assertions fail randomly, notably on build VMs (issue #12824) - # @test intvl <= t_elapsed - # @test t_elapsed <= (intvl + 1) -end - - -# Odd numbers trigger reads, even numbers timeout -for (i, intvl) in enumerate(intvls) - @sync begin - global ready = 0 - global ready_c = Condition() - t = Vector{Task}(n) - for idx in 1:n - if isodd(idx) - t[idx] = @async pfd_tst_reads(idx, intvl) - else - t[idx] = @async pfd_tst_timeout(idx, intvl) - end - end - - while ready < n - sleep(0.1) - end - ready = 0 - # tickle only the odd ones, but test for writablity for everyone - for idx in 1:n - event = poll_fd(pipe_fds[idx][2], 0.001; readable=true, writable=true) - @test !event.timedout - @test !event.readable - @test event.writable - - if isodd(idx) - @static if is_windows() - 1 == ccall(:send, stdcall, Cint, (Ptr{Void}, Ptr{UInt8}, Cint, Cint), pipe_fds[idx][2], "A", 1, 0) || error(Libc.FormatMessage()) - else - @test 1 == ccall(:write, Csize_t, (Cint, Ptr{UInt8}, Csize_t), pipe_fds[idx][2], "A", 1) - end - end - end - notify(ready_c, all=true) - for idx in 1:n - wait(t[idx]) - end - end -end - -for i in 1:n - for j = 1:2 - @static if is_windows() - 0 == ccall(:closesocket, stdcall, Cint, (Ptr{Void},), pipe_fds[i][j]) || error(Libc.FormatMessage()) - else - @test 0 == ccall(:close, Cint, (Cint,), pipe_fds[i][j]) - end - end -end - -# issue #12473 -# make sure 1-shot timers work -let a = [] - Timer(t -> push!(a, 1), 0.01, 0) - sleep(0.2) - @test a == [1] -end - -# make sure repeating timers work -@noinline function make_unrooted_timer(a) - t = Timer(0.0, 0.1) - finalizer(t, t -> a[] += 1) - wait(t) - e = @elapsed for i = 1:5 - wait(t) - end - @test 1.5 > e >= 0.4 - @test a[] == 0 - nothing -end -let a = Ref(0) - make_unrooted_timer(a) - gc() - @test a[] == 1 -end diff --git a/julia-0.6.3/share/julia/test/printf.jl b/julia-0.6.3/share/julia/test/printf.jl deleted file mode 100644 index 02f03bb..0000000 --- a/julia-0.6.3/share/julia/test/printf.jl +++ /dev/null @@ -1,260 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -# printf -# int -@test (@sprintf "%d" typemax(Int64)) == "9223372036854775807" -@test (@sprintf "%a" typemax(Int64)) == "0x7.fffffffffffffffp+60" -@test (@sprintf "%A" typemax(Int64)) == "0X7.FFFFFFFFFFFFFFFP+60" - -#printing an int value -for (fmt, val) in (("%i", "42"), - ("%u", "42"), - ("Test: %i", "Test: 42"), - ("%#x", "0x2a"), - ("%#o", "052"), - ("%x", "2a"), - ("%X", "2A"), - ("% i", " 42"), - ("%+i", "+42"), - ("%4i", " 42"), - ("%-4i", "42 "), - ("%a", "0x2.ap+4"), - ("%A", "0X2.AP+4"), - ("%20a"," 0x2.ap+4"), - ("%-20a","0x2.ap+4 "), - ("%f", "42.000000"), - ("%g", "42")), - num in (UInt16(42), UInt32(42), UInt64(42), UInt128(42), - Int16(42), Int32(42), Int64(42), Int128(42)) - #big"42" causes stack overflow on %a ; gh #14409 - @test @eval(@sprintf($fmt, $num) == $val) -end - -# pointers -if Sys.WORD_SIZE == 64 - @test (@sprintf "%20p" 0) == " 0x0000000000000000" - @test (@sprintf "%-20p" 0) == "0x0000000000000000 " -elseif Sys.WORD_SIZE == 32 - @test (@sprintf "%20p" 0) == " 0x00000000" - @test (@sprintf "%-20p" 0) == "0x00000000 " -else - @test false -end - -# float / BigFloat -for (fmt, val) in (("%7.2f", " 1.23"), - ("%-7.2f", "1.23 "), - ("%07.2f", "0001.23"), - ("%.0f", "1"), - ("%#.0f", "1."), - ("%.4e", "1.2345e+00"), - ("%.4E", "1.2345E+00"), - ("%.2a", "0x1.3cp+0"), - ("%.2A", "0X1.3CP+0")), - num in (1.2345, big"1.2345") - @test @eval(@sprintf($fmt, $num) == $val) -end - -# numeric spacing and various flag tests -function _test_flags(val, vflag::AbstractString, fmt::AbstractString, res::AbstractString, prefix::AbstractString) - vflag = string("%", vflag) - space_fmt = string(length(res) + length(prefix) + 3, fmt) - fsign = string((val < 0 ? "-" : "+"), prefix) - nsign = string((val < 0 ? "-" : " "), prefix) - osign = val < 0 ? string("-", prefix) : string(prefix, "0") - esign = string(val < 0 ? "-" : "", prefix) - esignend = val < 0 ? "" : " " - - for (flag::AbstractString, ans::AbstractString) in ( - ("", string(" ", nsign, res)), - ("+", string(" ", fsign, res)), - (" ", string(" ", nsign, res)), - ("0", string(osign, "00", res)), - ("-", string(esign, res, " ", esignend)), - ("0+", string(fsign, "00", res)), - ("0 ", string(nsign, "00", res)), - ("-+", string(fsign, res, " ")), - ("- ", string(nsign, res, " ")), - ) - fmt_string = string(vflag, flag, space_fmt) - @test @eval(@sprintf($fmt_string, $val) == $ans) - end -end - -for i in ( - (42, "", "i", "42", ""), - (42, "", "d", "42", ""), - - (42, "", "u", "42", ""), - (42, "", "x", "2a", ""), - (42, "", "X", "2A", ""), - (42, "", "o", "52", ""), - - (42, "#", "x", "2a", "0x"), - (42, "#", "X", "2A", "0X"), - (42, "#", "o", "052", ""), - - (1.2345, "", ".2f", "1.23", ""), - (1.2345, "", ".2e", "1.23e+00", ""), - (1.2345, "", ".2E", "1.23E+00", ""), - - (1.2345, "#", ".0f", "1.", ""), - (1.2345, "#", ".0e", "1.e+00", ""), - (1.2345, "#", ".0E", "1.E+00", ""), - - (1.2345, "", ".2a", "1.3cp+0", "0x"), - (1.2345, "", ".2A", "1.3CP+0", "0X"), - ) - _test_flags(i...) - _test_flags(-i[1], i[2:5]...) -end - -# Inf / NaN handling -@test (@sprintf "%f" Inf) == "Inf" -@test (@sprintf "%f" NaN) == "NaN" -@test (@sprintf "%f" big"Inf") == "Inf" -@test (@sprintf "%f" big"NaN") == "NaN" - -# scientific notation -@test (@sprintf "%.0e" 3e142) == "3e+142" -@test (@sprintf "%#.0e" 3e142) == "3.e+142" -@test (@sprintf "%.0e" big"3e142") == "3e+142" -@test (@sprintf "%#.0e" big"3e142") == "3.e+142" - -@test (@sprintf "%.0e" big"3e1042") == "3e+1042" - -@test (@sprintf "%e" 3e42) == "3.000000e+42" -@test (@sprintf "%E" 3e42) == "3.000000E+42" -@test (@sprintf "%e" 3e-42) == "3.000000e-42" -@test (@sprintf "%E" 3e-42) == "3.000000E-42" -@test (@sprintf "%a" 3e4) == "0x1.d4cp+14" -@test (@sprintf "%A" 3e4) == "0X1.D4CP+14" -@test (@sprintf "%.4a" 3e-4) == "0x1.3a93p-12" -@test (@sprintf "%.4A" 3e-4) == "0X1.3A93P-12" - -# %g -for (val, res) in ((12345678., "1.23457e+07"), - (1234567.8, "1.23457e+06"), - (123456.78, "123457"), - (12345.678, "12345.7"), - (12340000.0, "1.234e+07")) - @test (@sprintf("%.6g", val) == res) -end -for (val, res) in ((big"12345678.", "1.23457e+07"), - (big"1234567.8", "1.23457e+06"), - (big"123456.78", "123457"), - (big"12345.678", "12345.7")) - @test (@sprintf("%.6g", val) == res) -end -for (fmt, val) in (("%10.5g", " 123.4"), - ("%+10.5g", " +123.4"), - ("% 10.5g"," 123.4"), - ("%#10.5g", " 123.40"), - ("%-10.5g", "123.4 "), - ("%-+10.5g", "+123.4 "), - ("%010.5g", "00000123.4")), - num in (123.4, big"123.4") - @test @eval(@sprintf($fmt, $num) == $val) -end -@test( @sprintf( "%10.5g", -123.4 ) == " -123.4") -@test( @sprintf( "%010.5g", -123.4 ) == "-0000123.4") -@test( @sprintf( "%.6g", 12340000.0 ) == "1.234e+07") -@test( @sprintf( "%#.6g", 12340000.0 ) == "1.23400e+07") -@test( @sprintf( "%10.5g", big"-123.4" ) == " -123.4") -@test( @sprintf( "%010.5g", big"-123.4" ) == "-0000123.4") -@test( @sprintf( "%.6g", big"12340000.0" ) == "1.234e+07") -@test( @sprintf( "%#.6g", big"12340000.0") == "1.23400e+07") - -# %g regression gh #14331 -@test( @sprintf( "%.5g", 42) == "42") -@test( @sprintf( "%#.2g", 42) == "42.") -@test( @sprintf( "%#.5g", 42) == "42.000") - -# hex float -@test (@sprintf "%a" 1.5) == "0x1.8p+0" -@test (@sprintf "%a" 1.5f0) == "0x1.8p+0" -@test (@sprintf "%a" big"1.5") == "0x1.8p+0" -@test (@sprintf "%#.0a" 1.5) == "0x2.p+0" -@test (@sprintf "%+30a" 1/3) == " +0x1.5555555555555p-2" - -# chars -@test (@sprintf "%c" 65) == "A" -@test (@sprintf "%c" 'A') == "A" -@test (@sprintf "%3c" 'A') == " A" -@test (@sprintf "%-3c" 'A') == "A " -@test (@sprintf "%c" 248) == "ø" -@test (@sprintf "%c" 'ø') == "ø" - -# escape % -@test (@sprintf "%%") == "%" -@test (@sprintf "%%s") == "%s" -@test_throws ArgumentError eval(:(@sprintf "%")) - -# argument count -@test_throws ArgumentError eval(:(@sprintf "%s")) -@test_throws ArgumentError eval(:(@sprintf "%s" "1" "2")) - -# no interpolation -@test_throws ArgumentError eval(:(@sprintf "$n")) - -# type width specifier parsing (ignored) -@test (@sprintf "%llf" 1.2) == "1.200000" -@test (@sprintf "%Lf" 1.2) == "1.200000" -@test (@sprintf "%hhu" 1) == "1" -@test (@sprintf "%hu" 1) == "1" -@test (@sprintf "%lu" 1) == "1" -@test (@sprintf "%llu" 1) == "1" -@test (@sprintf "%Lu" 1) == "1" -@test (@sprintf "%zu" 1) == "1" -@test (@sprintf "%ju" 1) == "1" -@test (@sprintf "%tu" 1) == "1" - -# strings -@test (@sprintf "%s" "test") == "test" -@test (@sprintf "%s" "tést") == "tést" - -@test (@sprintf "%8s" "test") == " test" -@test (@sprintf "%-8s" "test") == "test " - -@test (@sprintf "%s" "tést") == "tést" - -@test (@sprintf "%s" :test) == "test" -@test (@sprintf "%#s" :test) == ":test" -@test (@sprintf "%#8s" :test) == " :test" -@test (@sprintf "%#-8s" :test) == ":test " - -@test (@sprintf "%8.3s" "test") == " tes" -@test (@sprintf "%#8.3s" "test") == " \"te" -@test (@sprintf "%-8.3s" "test") == "tes " -@test (@sprintf "%#-8.3s" "test") == "\"te " -@test (@sprintf "%.3s" "test") == "tes" -@test (@sprintf "%#.3s" "test") == "\"te" -@test (@sprintf "%-.3s" "test") == "tes" -@test (@sprintf "%#-.3s" "test") == "\"te" - -# reasonably complex -@test (@sprintf "Test: %s%c%C%c%#-.0f." "t" 65 66 67 -42) == "Test: tABC-42.." - -#test simple splatting -@test (@sprintf "%d%d" [1 2]...) == "12" - -# invalid format specifiers, not "diouxXDOUeEfFgGaAcCsSpn" -for c in "bBhHIjJkKlLmMNPqQrRtTvVwWyYzZ" - fmt_str = string("%", c) - @test_throws ArgumentError eval(:(@sprintf $fmt_str 1)) -end - -# combo -@test (@sprintf "%f %d %d %f" 1.0 [3 4]... 5) == "1.000000 3 4 5.000000" - -# multi -@test (@sprintf "%s %f %9.5f %d %d %d %d%d%d%d" [1:6;]... [7,8,9,10]...) == "1 2.000000 3.00000 4 5 6 78910" - -# comprehension -@test (@sprintf "%s %s %s %d %d %d %f %f %f" Any[10^x+y for x=1:3,y=1:3 ]...) == "11 101 1001 12 102 1002 13.000000 103.000000 1003.000000" - -# @printf -@test_throws ArgumentError eval(:(@printf 1)) - -# Check bug with trailing nul printing BigFloat -@test (@sprintf("%.330f", BigFloat(1)))[end] != '\0' diff --git a/julia-0.6.3/share/julia/test/profile.jl b/julia-0.6.3/share/julia/test/profile.jl deleted file mode 100644 index 92e3076..0000000 --- a/julia-0.6.3/share/julia/test/profile.jl +++ /dev/null @@ -1,45 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -function busywait(t, n_tries) - iter = 0 - while iter < n_tries && Profile.len_data() == 0 - iter += 1 - tend = time() + t - while time() < tend end - end -end - -Profile.clear() -@profile busywait(1, 20) - -let r = Profile.retrieve() - mktemp() do path, io - serialize(io, r) - close(io) - open(path) do io - @test isa(deserialize(io), Tuple{Vector{UInt},Dict{UInt64,Vector{StackFrame}}}) - end - end -end - -let iobuf = IOBuffer() - Profile.print(iobuf, format=:tree, C=true) - str = String(take!(iobuf)) - @test !isempty(str) - truncate(iobuf, 0) - Profile.print(iobuf, format=:tree, maxdepth=2) - str = String(take!(iobuf)) - @test !isempty(str) - truncate(iobuf, 0) - Profile.print(iobuf, format=:flat, C=true) - str = String(take!(iobuf)) - @test !isempty(str) - truncate(iobuf, 0) - Profile.print(iobuf) - @test !isempty(String(take!(iobuf))) - truncate(iobuf, 0) - Profile.print(iobuf, format=:flat, sortedby=:count) - @test !isempty(String(take!(iobuf))) - Profile.clear() - @test isempty(Profile.fetch()) -end diff --git a/julia-0.6.3/share/julia/test/random.jl b/julia-0.6.3/share/julia/test/random.jl deleted file mode 100644 index 1403af9..0000000 --- a/julia-0.6.3/share/julia/test/random.jl +++ /dev/null @@ -1,495 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -# Issue #6573 -srand(0); rand(); x = rand(384) -@test find(x .== rand()) == [] - -@test rand() != rand() -@test 0.0 <= rand() < 1.0 -@test rand(UInt32) >= 0 -@test -10 <= rand(-10:-5) <= -5 -@test -10 <= rand(-10:5) <= 5 -@test minimum([rand(Int32(1):Int32(7^7)) for i = 1:100000]) > 0 -@test typeof(rand(false:true)) === Bool -@test typeof(rand(Char)) === Char -@test length(randn(4, 5)) == 20 -@test length(bitrand(4, 5)) == 20 - -@test rand(MersenneTwister(0)) == 0.8236475079774124 -@test rand(MersenneTwister(42)) == 0.5331830160438613 -# Try a seed larger than 2^32 -@test rand(MersenneTwister(5294967296)) == 0.3498809918210497 - -# Test array filling, Issues #7643, #8360 -@test rand(MersenneTwister(0), 1) == [0.8236475079774124] -A = zeros(2, 2) -rand!(MersenneTwister(0), A) -@test A == [0.8236475079774124 0.16456579813368521; - 0.9103565379264364 0.17732884646626457] -A = zeros(2, 2) -@test_throws BoundsError rand!(MersenneTwister(0), A, 5) -@test rand(MersenneTwister(0), Int64, 1) == [4439861565447045202] -A = zeros(Int64, 2, 2) -rand!(MersenneTwister(0), A) -@test A == [858542123778948672 5715075217119798169; - 8690327730555225005 8435109092665372532] -A = zeros(UInt128, 2, 2) -@test_throws BoundsError rand!(MersenneTwister(0), A, 5) - -# rand from AbstractArray -let mt = MersenneTwister(0) - srand(mt) - @test rand(mt, 0:3:1000) in 0:3:1000 - @test issubset(rand!(mt, Array{Int}(100), 0:3:1000), 0:3:1000) - coll = Any[2, UInt128(128), big(619), "string"] - @test rand(mt, coll) in coll - @test issubset(rand(mt, coll, 2, 3), coll) - - # check API with default RNG: - rand(0:3:1000) - rand!(Array{Int}(100), 0:3:1000) - rand(coll) - rand(coll, 2, 3) -end - -# rand using Dict, Set -adict = Dict(1=>2, 3=>4, 5=>6) -@test rand(adict) in adict -aset = Set(1:10) -@test rand(aset) in aset - -# randn -@test randn(MersenneTwister(42)) == -0.5560268761463861 -A = zeros(2, 2) -randn!(MersenneTwister(42), A) -@test A == [-0.5560268761463861 0.027155338009193845; - -0.444383357109696 -0.29948409035891055] - -for T in (Int8, UInt8, Int16, UInt16, Int32, UInt32, Int64, UInt64, Int128, UInt128, BigInt, - Float16, Float32, Float64, Rational{Int}) - r = rand(convert(T, 97):convert(T, 122)) - @test typeof(r) == T - @test 97 <= r <= 122 - r = rand(convert(T, 97):convert(T,2):convert(T, 122),2)[1] - @test typeof(r) == T - @test 97 <= r <= 122 - @test mod(r,2)==1 - - if T<:Integer && !(T===BigInt) - x = rand(typemin(T):typemax(T)) - @test isa(x,T) - @test typemin(T) <= x <= typemax(T) - end -end - -@test !any([(Base.Random.maxmultiple(i)+i) > 0xFF for i in 0x00:0xFF]) -@test all([(Base.Random.maxmultiple(i)+1) % i for i in 0x01:0xFF] .== 0) -@test all([(Base.Random.maxmultiple(i)+1+i) > 0xFF for i in 0x00:0xFF]) -@test length(0x00:0xFF)== Base.Random.maxmultiple(0x0)+1 - - -if sizeof(Int32) < sizeof(Int) - r = rand(Int32(-1):typemax(Int32)) - @test typeof(r) == Int32 - @test -1 <= r <= typemax(Int32) - @test all([div(0x00010000000000000000,k)*k - 1 == Base.Random.RangeGenerator(map(UInt64,1:k)).u for k in 13 .+ Int64(2).^(32:62)]) - @test all([div(0x00010000000000000000,k)*k - 1 == Base.Random.RangeGenerator(map(Int64,1:k)).u for k in 13 .+ Int64(2).^(32:61)]) - - @test Base.Random.maxmultiplemix(0x000100000000) === 0xffffffffffffffff - @test Base.Random.maxmultiplemix(0x0000FFFFFFFF) === 0x00000000fffffffe - @test Base.Random.maxmultiplemix(0x000000000000) === 0xffffffffffffffff -end - -# BigInt specific -for T in [UInt32, UInt64, UInt128, Int128] - s = big(typemax(T)-1000) : big(typemax(T)) + 10000 - @test rand(s) != rand(s) - @test big(typemax(T)-1000) <= rand(s) <= big(typemax(T)) + 10000 - r = rand(s, 1, 2) - @test size(r) == (1, 2) - @test typeof(r) == Matrix{BigInt} - - srand(0) - r = rand(s) - srand(0) - @test rand(s) == r -end - -# Test ziggurat tables -ziggurat_table_size = 256 -nmantissa = Int64(2)^51 # one bit for the sign -ziggurat_nor_r = parse(BigFloat,"3.65415288536100879635194725185604664812733315920964488827246397029393565706474") -erfc_zigg_root2 = parse(BigFloat,"2.580324876539008898343885504487203185398584536409033046076029509351995983934371e-04") -nor_section_area = ziggurat_nor_r*exp(-ziggurat_nor_r^2/2) + erfc_zigg_root2*sqrt(big(π)/2) -emantissa = Int64(2)^52 -ziggurat_exp_r = parse(BigFloat,"7.69711747013104971404462804811408952334296818528283253278834867283241051210533") -exp_section_area = (ziggurat_exp_r + 1)*exp(-ziggurat_exp_r) - -ki = Array{UInt64}(ziggurat_table_size) -wi = Array{Float64}(ziggurat_table_size) -fi = Array{Float64}(ziggurat_table_size) -# Tables for exponential variates -ke = Array{UInt64}(ziggurat_table_size) -we = Array{Float64}(ziggurat_table_size) -fe = Array{Float64}(ziggurat_table_size) -function randmtzig_fill_ziggurat_tables() # Operates on the global arrays - wib = big.(wi) - fib = big.(fi) - web = big.(we) - feb = big.(fe) - # Ziggurat tables for the normal distribution - x1 = ziggurat_nor_r - wib[256] = x1/nmantissa - fib[256] = exp(-0.5*x1*x1) - # Index zero is special for tail strip, where Marsaglia and Tsang - # defines this as - # k_0 = 2^31 * r * f(r) / v, w_0 = 0.5^31 * v / f(r), f_0 = 1, - # where v is the area of each strip of the ziggurat. - ki[1] = trunc(UInt64,x1*fib[256]/nor_section_area*nmantissa) - wib[1] = nor_section_area/fib[256]/nmantissa - fib[1] = one(BigFloat) - - for i = 255:-1:2 - # New x is given by x = f^{-1}(v/x_{i+1} + f(x_{i+1})), thus - # need inverse operator of y = exp(-0.5*x*x) -> x = sqrt(-2*ln(y)) - x = sqrt(-2.0*log(nor_section_area/x1 + fib[i+1])) - ki[i+1] = trunc(UInt64,x/x1*nmantissa) - wib[i] = x/nmantissa - fib[i] = exp(-0.5*x*x) - x1 = x - end - - ki[2] = UInt64(0) - - # Zigurrat tables for the exponential distribution - x1 = ziggurat_exp_r - web[256] = x1/emantissa - feb[256] = exp(-x1) - - # Index zero is special for tail strip, where Marsaglia and Tsang - # defines this as - # k_0 = 2^32 * r * f(r) / v, w_0 = 0.5^32 * v / f(r), f_0 = 1, - # where v is the area of each strip of the ziggurat. - ke[1] = trunc(UInt64,x1*feb[256]/exp_section_area*emantissa) - web[1] = exp_section_area/feb[256]/emantissa - feb[1] = one(BigFloat) - - for i = 255:-1:2 - # New x is given by x = f^{-1}(v/x_{i+1} + f(x_{i+1})), thus - # need inverse operator of y = exp(-x) -> x = -ln(y) - x = -log(exp_section_area/x1 + feb[i+1]) - ke[i+1] = trunc(UInt64,x/x1*emantissa) - web[i] = x/emantissa - feb[i] = exp(-x) - x1 = x - end - ke[2] = zero(UInt64) - - wi[:] = wib - fi[:] = fib - we[:] = web - fe[:] = feb - return nothing -end -randmtzig_fill_ziggurat_tables() -@test all(ki == Base.Random.ki) -@test all(wi == Base.Random.wi) -@test all(fi == Base.Random.fi) -@test all(ke == Base.Random.ke) -@test all(we == Base.Random.we) -@test all(fe == Base.Random.fe) - -#same random numbers on for small ranges on all systems - -seed = rand(UInt) #leave state nondeterministic as above -srand(seed) -r = map(Int64,rand(map(Int32,97:122))) -srand(seed) -@test r == rand(map(Int64,97:122)) - -srand(seed) -r = map(UInt64,rand(map(UInt32,97:122))) -srand(seed) -@test r == rand(map(UInt64,97:122)) - -@test all([div(0x000100000000,k)*k - 1 == Base.Random.RangeGenerator(map(UInt64,1:k)).u for k in 13 .+ Int64(2).^(1:30)]) -@test all([div(0x000100000000,k)*k - 1 == Base.Random.RangeGenerator(map(Int64,1:k)).u for k in 13 .+ Int64(2).^(1:30)]) - -import Base.Random: uuid1, uuid4, UUID, uuid_version - -# UUID -u1 = uuid1() -u4 = uuid4() -@test uuid_version(u1) == 1 -@test uuid_version(u4) == 4 -@test u1 == UUID(string(u1)) == UUID(GenericString(string(u1))) -@test u4 == UUID(string(u4)) == UUID(GenericString(string(u4))) -@test u1 == UUID(UInt128(u1)) -@test u4 == UUID(UInt128(u4)) -@test uuid4(MersenneTwister(0)) == uuid4(MersenneTwister(0)) -@test_throws ArgumentError UUID("550e8400e29b-41d4-a716-446655440000") -@test_throws ArgumentError UUID("550e8400e29b-41d4-a716-44665544000098") -@test_throws ArgumentError UUID("z50e8400-e29b-41d4-a716-446655440000") - -#issue 8257 -i8257 = 1:1/3:100 -for i = 1:100 - @test rand(i8257) in i8257 -end - -# test code paths of rand! - -let mt = MersenneTwister(0) - A128 = Array{UInt128}(0) - @test length(rand!(mt, A128)) == 0 - for (i,n) in enumerate([1, 3, 5, 6, 10, 11, 30]) - resize!(A128, n) - rand!(mt, A128) - @test length(A128) == n - @test A128[end] == UInt128[0x15de6b23025813ad129841f537a04e40, - 0xcfa4db38a2c65bc4f18c07dc91125edf, - 0x33bec08136f19b54290982449b3900d5, - 0xde41af3463e74cb830dad4add353ca20, - 0x066d8695ebf85f833427c93416193e1f, - 0x48fab49cc9fcee1c920d6dae629af446, - 0x4b54632b4619f4eca22675166784d229][i] - end - - srand(mt,0) - for (i,T) in enumerate([Int8, UInt8, Int16, UInt16, Int32, UInt32, Int64, UInt64, Int128, Float16, Float32]) - A = Array{T}(16) - B = Array{T}(31) - rand!(mt, A) - rand!(mt, B) - @test A[end] == Any[21,0x7b,17385,0x3086,-1574090021,0xadcb4460,6797283068698303107,0x4e91c9c4d4f5f759, - -3482609696641744459568613291754091152,Float16(0.03125),0.68733835f0][i] - - @test B[end] == Any[49,0x65,-3725,0x719d,814246081,0xdf61843a,-3010919637398300844,0x61b367cf8810985d, - -33032345278809823492812856023466859769,Float16(0.95),0.51829386f0][i] - end - - srand(mt,0) - AF64 = Array{Float64}(Base.Random.dsfmt_get_min_array_size()-1) - @test rand!(mt, AF64)[end] == 0.957735065345398 - @test rand!(mt, AF64)[end] == 0.6492481059865669 - resize!(AF64, 2*length(mt.vals)) - @test Base.Random.rand_AbstractArray_Float64!(mt, AF64)[end] == 0.432757268470779 -end - -# Issue #9037 -let mt = MersenneTwister(0) - a = Array{Float64}(0) - resize!(a, 1000) # could be 8-byte aligned - b = Array{Float64}(1000) # should be 16-byte aligned - c8 = Array{UInt64}(1001) - pc8 = pointer(c8) - if Int(pc8) % 16 == 0 - # Make sure pc8 is not 16-byte aligned since that's what we want to test. - # It still has to be 8-byte aligned since it is otherwise invalid on - # certain architectures (e.g. ARM) - pc8 += 8 - end - c = unsafe_wrap(Array, Ptr{Float64}(pc8), 1000) # Int(pointer(c)) % 16 == 8 - - for A in (a, b, c) - srand(mt, 0) - rand(mt) # this is to fill mt.vals, cf. #9040 - rand!(mt, A) # must not segfault even if Int(pointer(A)) % 16 != 0 - @test A[end-4:end] == [0.49508297796349776,0.3408340446375888,0.3211229457075784,0.9103565379264364,0.16456579813368521] - end -end - -# make sure reading 128-bit ints from RandomDevice works -let a = [rand(RandomDevice(), UInt128) for i=1:10] - @test reduce(|, a)>>>64 != 0 -end - -# test all rand APIs -for rng in ([], [MersenneTwister(0)], [RandomDevice()]) - types = [Base.BitInteger_types..., Bool, Float16, Float32, Float64, Char] - ftypes = [Float16, Float32, Float64] - b2 = big(2) - u3 = UInt(3) - for f in [rand, randn, randexp] - f(rng...) ::Float64 - f(rng..., 5) ::Vector{Float64} - f(rng..., 2, 3) ::Array{Float64, 2} - f(rng..., b2, u3) ::Array{Float64, 2} - f(rng..., (2, 3)) ::Array{Float64, 2} - for T in (f === rand ? types : ftypes) - a0 = f(rng..., T) ::T - a1 = f(rng..., T, 5) ::Vector{T} - a2 = f(rng..., T, 2, 3) ::Array{T, 2} - a3 = f(rng..., T, b2, u3) ::Array{T, 2} - a4 = f(rng..., T, (2, 3)) ::Array{T, 2} - if T <: AbstractFloat && f === rand - for a in [a0, a1..., a2..., a3..., a4...] - @test 0.0 <= a < 1.0 - end - end - end - end - for f! in [rand!, randn!, randexp!] - for T in (f! === rand! ? types : ftypes) - X = T == Bool ? T[0,1] : T[0,1,2] - for A in (Array{T}(5), Array{T}(2, 3)) - f!(rng..., A) ::typeof(A) - if f! === rand! - f!(rng..., A, X) ::typeof(A) - if T !== Char # Char/Integer comparison - f!(rng..., sparse(A)) ::typeof(sparse(A)) - f!(rng..., sparse(A), X) ::typeof(sparse(A)) - end - end - end - end - end - - bitrand(rng..., 5) ::BitArray{1} - bitrand(rng..., 2, 3) ::BitArray{2} - rand!(rng..., BitArray(5)) ::BitArray{1} - rand!(rng..., BitArray(2, 3)) ::BitArray{2} - - # Test that you cannot call randn or randexp with non-Float types. - for r in [randn, randexp, randn!, randexp!] - @test_throws MethodError r(Int) - @test_throws MethodError r(Int32) - @test_throws MethodError r(Bool) - @test_throws MethodError r(String) - @test_throws MethodError r(AbstractFloat) - # TODO(#17627): Consider adding support for randn(BigFloat) and removing this test. - @test_throws MethodError r(BigFloat) - - @test_throws MethodError r(Int64, (2,3)) - @test_throws MethodError r(String, 1) - - @test_throws MethodError r(rng..., Number, (2,3)) - @test_throws MethodError r(rng..., Any, 1) - end -end - -function hist(X,n) - v = zeros(Int,n) - for x in X - v[floor(Int,x*n)+1] += 1 - end - v -end - -# test uniform distribution of floats -for rng in [srand(MersenneTwister(0)), RandomDevice()] - for T in [Float16,Float32,Float64] - # array version - counts = hist(rand(rng, T, 2000), 4) - @test minimum(counts) > 300 # should fail with proba < 1e-26 - # scalar version - counts = hist([rand(rng, T) for i in 1:2000], 4) - @test minimum(counts) > 300 - end -end - -# test reproducility of methods -let mta = MersenneTwister(42), mtb = MersenneTwister(42) - - @test rand(mta) == rand(mtb) - @test rand(mta,10) == rand(mtb,10) - @test randn(mta) == randn(mtb) - @test randn(mta,10) == randn(mtb,10) - @test randexp(mta) == randexp(mtb) - @test randexp(mta,10) == randexp(mtb,10) - @test rand(mta,1:100) == rand(mtb,1:100) - @test rand(mta,1:10,10) == rand(mtb,1:10,10) - @test rand(mta,Bool) == rand(mtb,Bool) - @test bitrand(mta,10) == bitrand(mtb,10) - - @test randstring(mta) == randstring(mtb) - @test randstring(mta,10) == randstring(mtb,10) - - @test randsubseq(mta,1:10,0.4) == randsubseq(mtb,1:10,0.4) - @test randsubseq!(mta,Int[],1:10,0.4) == randsubseq!(mtb,Int[],1:10,0.4) - - @test shuffle(mta,collect(1:10)) == shuffle(mtb,collect(1:10)) - @test shuffle!(mta,collect(1:10)) == shuffle!(mtb,collect(1:10)) - @test shuffle(mta,collect(2:11)) == shuffle(mtb,2:11) - - @test randperm(mta,10) == randperm(mtb,10) - @test sort!(randperm(10)) == sort!(shuffle(1:10)) == collect(1:10) - @test randperm(mta,big(10)) == randperm(mtb,big(10)) # cf. #16376 - @test randperm(0) == [] - @test_throws ErrorException randperm(-1) - - @test randcycle(mta,10) == randcycle(mtb,10) - - @test sprand(mta,1,1,0.9) == sprand(mtb,1,1,0.9) - @test sprand(mta,10,10,0.3) == sprand(mtb,10,10,0.3) -end - -# test PRNG jump -let mta = MersenneTwister(seed), mtb = MersenneTwister(seed) - step = 25000*2 - size = 4 - jump25000 = "35931a4947eeab70a9abbfaca4a79cfcf2610a35a586c6f4e4bdfa826d538cbfb0432c37321fcec4f6c98de3df06685087032988b0ad9a2144562aa82e06f2f6f256b5b412c524e35383a894da7b04e142c4156290585186d8fc06d3141a778220c2519a851b5a9e5947a3f745b71804631988825e21dba40392ff4c036b30d2d013b45e2be94b5e130a9c6424d2e82f48c855c81bd10757fdb5a91e23e9e312e430514ea31631d8897b4cf26eb39b37be0c92706e5637d4b34c1e4046b741e455df195cb512e8e0f8d578175a3da5e00d7ce247d9b92042b1b515d01f7f89fe661ebccb06dfb77bc0fbb99806921b472ccce58f2166ac058d9cf427ad7d74986e60a56d2fee0a8b680e466a8ea4e508a76c058b6f97b99c9aa5b10297b1a1bd6a8e80f3a79e008fa55a4a8915fbdec78b6b117ad67e195311fe79fc084c33f6db546f5b7602d010fa8b830e3f1b00cef00ee16840178fc7e9aa5f1cee625d43de8488bf6c8bd379ea6f97c55c7a9ee091477a23533d5e52e194bd9d4e17b02a64a2736feb3779fabd5777e448ffee0f2d4b38a8e7441822b882fc6df0bde8541e85c0c78a05936cff0c88a50980b7a84971fba3650991fe2cba425ac4b4289e7b06ce2cfabfcc8a553201e8c74b45e4ae74b6d054e37af95e6fd55e029b7c526b85ecfb3be8db670218ee3dda7b2a54ab1ed26eefe4cd1d2a9c589a6e94d0aa3ebe29e40e616aa0b731061c3d6e247ec610024a1a97b7adb7919308b0fb5dd5d51a58aa2f55d77b88037de7c1a74823c96cb09d22dd7f90dba14eefdcffaab34d323c829f24742f6f6b32b0724a26ae4a81130a8a275d30c21e6245fa27cf26d606a49bccba2980697c32d9efe583c4ee2140569025c4f044d744bc40cec1660d9e4d2de3a4de83bae4f0a9fdb34ef4509b2b4e6c37967a485a52d69d1573bb826bc64c966de9c792b7c2f07b645c56a29381911a98928e48516f246a55bcaa78f3c7d1c30127df5f06ba0a2d6a5e54605a20e60fab30c01a9472cb610ca0ef2418a985af00c7e47539111bf539dd554297d0374a7ff627d879600595b442c8dcffcffa3bbb07e5c7882ff0858142be4deac448698f0917fe2b7a9b686a9df1fa929f06a51aff992a6ee0b0605f8b34b87600cfa0af2475333b78625ce1520c793dc5080218247b4e41bbd7d9dab163470fe17a3d2622cdce979cc5565b0bc04eabaf656f21fa072a18ab33c656b665248ef20321407fef263b1c67316f2c6f236951990099e42d4614d8e08b27aa89d9f4548fa321d4b381d2da04fd7f17d6b9a68adfd0e4427196d25dcad869f8a155c6242f7d072baa5e7405ceb65dfaa3eb864bfe679a17df34273fde5037befe9ed5391b932cee271f59128c61ab3f0fc3f7cf8ff051fbda8382c64579efddd494c79850c56bda73bcd39c20c2820d191995b3335253c3b0ac8f5e5373f40c228886e6c526c2c249a5304578ba2a80f591c34ca1eaa84d6cc9399cf3f1207e61c4acada647e4e87ad5fba84aeeff6b6881d35bda77c74384fc5e279a0f495d509bc882c2b8bc790651a6d7a4ecba23a3f05111e1d8be37c03439fbd484668ceab69a52b7d519b169cbbcf634ee5e3bf78a5f8771f95fea03f2cb889e116a9f5de3abeacb8e42475fb5d022484b02d11f1e406332e0a773098fc4f0baa57cda2863c554f291d4eb74e63e4b3d44b0ed156bff1820003d407a3aaa9e6dfaa226ba7ef2fd0eff90a5482926f47f24f67019edccb6fd329eef30b5fb2125276aa1fe75a702b32c907ab133c72a74e77e0a5eb48fc5176b9d65b75b0038e1a9ed74ec2a3dcd2348fa54256f082abc01a301bacef7380f20ee0411c08a35dafdaae9f9fc123448da28626ffcc654e9d522bc8b8776b13a3310f7eeb4d27290ef4cbc7492fbcb5409d455748a8a1f087430cf5e6f453e2caa0c5343fcf4374cc38bead49941d8ab59b4d5181716c238aa88dbf1c4a2da3a9a9b9435d5ee1d51d27b0655a4308c1252aaf633cd8f44a351ffc8cec65de0b7e4e2556100e2ae9bc511044351109a6254b2d387b1a72c768f43fa7be6b93806e323b55c3e7925ed627dc708fde0954b299b1ca33bb7fbe33e0f9e4ce5b4f26efaf8e5b9507ada4f8658998eb7167afbd4482ee47cc60f4039d6a77c1fb126033bfc2e7c6162ff7561f22e263325c53a014a4ac9390fe6fab5d433c1e9896fe561f22fc8290f3f4560b676f3dfbfd1fe605343a0685349241b83a28d61cc0292d1f638a36d3d87bfa9f72f9df1cfe90692dfda5bd5e698362f5316984cbe73a132a801acbca76b5f5c23d98a217f2159b6cbbcdf8f52d23ea24c9471a31562a651b20e05cd0300ee500a450cfdaa4d2d83f7e7e27f8b7c793cf80f8067dadef77e49a64c373b97bac4dd472e5145072c73d0fdd68d9646c8a8ed9aec6c40bc915ae44ae27391ca0f1a4d2cb1c3d097be614e6eba807f4549d769a5872f268ccf770f2682d844490348f0b6a0d2b51aadbb5523cf708b66f9928eed12b35a39cf42d283b29f5283e1c8ba1f73457af17b14cdfdf9a85b0589acf1f9504e46b0bab8be848dac5673587035b99f56c41d3195bbba1616b149a22193cfb760d6bf2d84861653cd21be9a2d33187cb25d47fbecdd4626d1d97202f460a39b7128cadb77ddf682feca61fb6de0290df598a565a6361a91d76c0c685046489ed4cb1dcc4f1cea849c12dc4a3d38d3010567f387590532b78927e92f0b718c84e882b3df071a78a011d0fd56d4101dcb009914a16a781b240a6fb2440c72b0ffb365be9d3459d114e665a0d35d7b8bd280101d85d1211d939ba0b15ab528c4f9dd2b001172561d211671b96873010ae3c2b8317f773d735698914228764b831423ae19dd4bbb008b9f1bd1e3ebdd626e629a46a9dd70bdd4bb30e2279e83c12bbbead6479b5f9980b1a9c785395520703a9367d931b45c1566c9d314b1745cafc6d0667cc9bc94d0c53a960c829eb09b768ab6bb2133e4fea1d939f3d3f8e1237210cf3577c830f0493073dc1d189abf27402b8b31b7c172c43dbf331a0828adfe737380e763d0ab0bfaaf94ec04830f94380a83718f340c4eeb20d7eb22b94613be84a9ed332ab364efff6cb37eec35d186185cca725e7a748f6bdb427604fb1628d49a7424a5a62a2e930fe142b035503af332fe748d5e63591b9ac54071ca843d5e474a48837de8b80387f3269ab50d2fd99c08c971e015d13fa02c7c315922ce58bdacbf8ee48827851a61fca59882d7eadcce3166dfe012aa9ec849e698e776a4d384f4755b506a222636942a81bbbffa1ff47e4d81fe68120aebcfd1a7e0000fd0cffdc44e1f0cd69ea2b4936564c78af51fed1cc8e34f0b46d6330b4b50ddee09335b7b0be0bc9f7f8e48415e15d08f811653d21bc6dd152742b086caadcc6dff5e27b40da42c2f1ebf3dd2bd51c418718e499859239317fcab10892eadf1c0ebf7a4246bce4cce3617193032f3e41b977dc8650298ac39631c527460364effea0f0bfd043df72ead0406aba1bcd636d65d7b89979eb8e1"; - - mts = randjump(mta, size, jump25000) - @test length(mts) == 4 - - tmp = zeros(Float64, size*step) - for j in 1:step - for k in 1:size - tmp[j + (k-1) * step] = rand(mts[k], Float64) - end - end - - for j in 1:(size * step) - @test rand(mtb, Float64) == tmp[j] - end -end - -# test that the following is not an error (#16925) -srand(typemax(UInt)) -srand(typemax(UInt128)) - -# copy and == -let seed = rand(UInt32, 10) - r = MersenneTwister(seed) - @test r == MersenneTwister(seed) # r.vals should be all zeros - s = copy(r) - @test s == r && s !== r - skip, len = rand(0:2000, 2) - for j=1:skip - rand(r) - rand(s) - end - @test rand(r, len) == rand(s, len) - @test s == r -end - -# MersenneTwister initialization with invalid values -@test_throws DomainError Base.dSFMT.DSFMT_state(zeros(Int32, rand(0:Base.dSFMT.JN32-1))) -@test_throws DomainError MersenneTwister(zeros(UInt32, 1), Base.dSFMT.DSFMT_state(), - zeros(Float64, 10), 0) -@test_throws DomainError MersenneTwister(zeros(UInt32, 1), Base.dSFMT.DSFMT_state(), - zeros(Float64, Base.Random.MTCacheLength), -1) - -# seed is private to MersenneTwister -let seed = rand(UInt32, 10) - r = MersenneTwister(seed) - @test r.seed == seed && r.seed !== seed - resize!(seed, 4) - @test r.seed != seed -end - -# srand(rng, ...) returns rng (#21248) -let g = Base.Random.GLOBAL_RNG, - m = MersenneTwister(0) - @test srand() === g - @test srand(rand(UInt)) === g - @test srand(rand(UInt32, rand(1:10))) === g - @test srand(@__FILE__) === g - @test srand(@__FILE__, rand(1:10)) === g - @test srand(m) === m - @test srand(m, rand(UInt)) === m - @test srand(m, rand(UInt32, rand(1:10))) === m - @test srand(m, rand(1:10)) === m - @test srand(m, @__FILE__, rand(1:10)) === m -end diff --git a/julia-0.6.3/share/julia/test/ranges.jl b/julia-0.6.3/share/julia/test/ranges.jl deleted file mode 100644 index 82352cd..0000000 --- a/julia-0.6.3/share/julia/test/ranges.jl +++ /dev/null @@ -1,930 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -# ranges -@test size(10:1:0) == (0,) -@test length(1:.2:2) == 6 -@test length(1.:.2:2.) == 6 -@test length(2:-.2:1) == 6 -@test length(2.:-.2:1.) == 6 -@test length(2:.2:1) == 0 -@test length(2.:.2:1.) == 0 - -@inferred(colon(10, 1, 0)) -@inferred(colon(1, .2, 2)) -@inferred(colon(1., .2, 2.)) -@inferred(colon(2, -.2, 1)) -@inferred(colon(1, 0)) -@inferred(colon(0.0, -0.5)) - -@test length(1:0) == 0 -@test length(0.0:-0.5) == 0 -@test length(1:2:0) == 0 -L32 = @inferred(linspace(Int32(1), Int32(4), 4)) -L64 = @inferred(linspace(Int64(1), Int64(4), 4)) -@test @inferred(L32[1]) === 1.0 && @inferred(L64[1]) === 1.0 -@test L32[2] == 2 && L64[2] == 2 -@test L32[3] == 3 && L64[3] == 3 -@test L32[4] == 4 && L64[4] == 4 -@test @inferred(linspace(1.0, 2.0, 2.0f0)) === linspace(1.0, 2.0, 2) - -r = 5:-1:1 -@test r[1]==5 -@test r[2]==4 -@test r[3]==3 -@test r[4]==2 -@test r[5]==1 - -@test length(.1:.1:.3) == 3 -@test length(1.1:1.1:3.3) == 3 -@test length(1.1:1.3:3) == 2 -@test length(1:1:1.8) == 1 - -@test @inferred((0.1:0.1:0.3)[2]) === 0.2 -@test @inferred((0.1f0:0.1f0:0.3f0)[2]) === 0.2f0 - -@test @inferred((1:5)[1:4]) === 1:4 -@test @inferred((1.0:5)[1:4]) === 1.0:4 -@test (2:6)[1:4] == 2:5 -@test (1:6)[2:5] === 2:5 -@test (1:6)[2:2:5] === 2:2:4 -@test (1:2:13)[2:6] === 3:2:11 -@test (1:2:13)[2:3:7] === 3:6:13 - -@test isempty((1:4)[5:4]) -@test_throws BoundsError (1:10)[8:-1:-2] - -r = typemax(Int)-5:typemax(Int)-1 -@test_throws BoundsError r[7] - -@test findin([5.2, 3.3], 3:20) == findin([5.2, 3.3], collect(3:20)) - -let - span = 5:20 - r = -7:3:42 - @test findin(r, span) == 5:10 - r = 15:-2:-38 - @test findin(r, span) == 1:6 -end -#@test isempty(findin(5+0*(1:6), 2:4)) -#@test findin(5+0*(1:6), 2:5) == 1:6 -#@test findin(5+0*(1:6), 2:7) == 1:6 -#@test findin(5+0*(1:6), 5:7) == 1:6 -#@test isempty(findin(5+0*(1:6), 6:7)) -#@test findin(5+0*(1:6), 5:5) == 1:6 - -@test reverse(reverse(1:10)) == 1:10 - -@test reverse(reverse(typemin(Int):typemax(Int))) == typemin(Int):typemax(Int) -@test reverse(reverse(typemin(Int):2:typemax(Int))) == typemin(Int):2:typemax(Int) - -@test intersect(1:5, 2:3) == 2:3 -@test intersect(-3:5, 2:8) == 2:5 -@test intersect(-8:-3, -8:-3) == -8:-3 -@test intersect(1:5, 5:13) == 5:5 -@test isempty(intersect(-8:-3, -2:2)) -@test isempty(intersect(-3:7, 2:1)) -@test intersect(1:11, -2:3:15) == 1:3:10 -@test intersect(1:11, -2:2:15) == 2:2:10 -@test intersect(1:11, -2:1:15) == 1:11 -@test intersect(1:11, 15:-1:-2) == 1:11 -@test intersect(1:11, 15:-4:-2) == 3:4:11 -@test intersect(-20:-5, -10:3:-2) == -10:3:-7 -@test isempty(intersect(-5:5, -6:13:20)) -@test isempty(intersect(1:11, 15:4:-2)) -@test isempty(intersect(11:1, 15:-4:-2)) -#@test intersect(-5:5, 1+0*(1:3)) == 1:1 -#@test isempty(intersect(-5:5, 6+0*(1:3))) -@test intersect(-15:4:7, -10:-2) == -7:4:-3 -@test intersect(13:-2:1, -2:8) == 7:-2:1 -@test isempty(intersect(13:2:1, -2:8)) -@test isempty(intersect(13:-2:1, 8:-2)) -#@test intersect(5+0*(1:4), 2:8) == 5+0*(1:4) -#@test isempty(intersect(5+0*(1:4), -7:3)) -@test intersect(0:3:24, 0:4:24) == 0:12:24 -@test intersect(0:4:24, 0:3:24) == 0:12:24 -@test intersect(0:3:24, 24:-4:0) == 0:12:24 -@test intersect(24:-3:0, 0:4:24) == 24:-12:0 -@test intersect(24:-3:0, 24:-4:0) == 24:-12:0 -@test intersect(1:3:24, 0:4:24) == 4:12:16 -@test intersect(0:6:24, 0:4:24) == 0:12:24 -@test isempty(intersect(1:6:2400, 0:4:2400)) -@test intersect(-51:5:100, -33:7:125) == -26:35:79 -@test intersect(-51:5:100, -32:7:125) == -11:35:94 -#@test intersect(0:6:24, 6+0*(0:4:24)) == 6:6:6 -#@test intersect(12+0*(0:6:24), 0:4:24) == Range(12, 0, 5) -#@test isempty(intersect(6+0*(0:6:24), 0:4:24)) -@test intersect(-10:3:24, -10:3:24) == -10:3:23 -@test isempty(intersect(-11:3:24, -10:3:24)) -@test intersect(typemin(Int):2:typemax(Int),1:10) == 2:2:10 -@test intersect(1:10,typemin(Int):2:typemax(Int)) == 2:2:10 - -@test intersect(reverse(typemin(Int):2:typemax(Int)),typemin(Int):2:typemax(Int)) == reverse(typemin(Int):2:typemax(Int)) -@test intersect(typemin(Int):2:typemax(Int),reverse(typemin(Int):2:typemax(Int))) == typemin(Int):2:typemax(Int) - -@test intersect(UnitRange(1,2),3) == UnitRange(3,2) -@test intersect(UnitRange(1,2), UnitRange(1,5), UnitRange(3,7), UnitRange(4,6)) == UnitRange(4,3) - -@test intersect(1:3, 2) === intersect(2, 1:3) === 2:2 -@test intersect(1.0:3.0, 2) == intersect(2, 1.0:3.0) == [2.0] - -@test sort(UnitRange(1,2)) == UnitRange(1,2) -@test sort!(UnitRange(1,2)) == UnitRange(1,2) -@test sort(1:10, rev=true) == collect(10:-1:1) -@test sort(-3:3, by=abs) == [0,-1,1,-2,2,-3,3] -@test select(1:10, 4) == 4 - -@test 0 in UInt(0):100:typemax(UInt) -@test last(UInt(0):100:typemax(UInt)) in UInt(0):100:typemax(UInt) -@test -9223372036854775790 in -9223372036854775790:100:9223372036854775710 -@test -9223372036854775690 in -9223372036854775790:100:9223372036854775710 -@test -90 in -9223372036854775790:100:9223372036854775710 -@test 10 in -9223372036854775790:100:9223372036854775710 -@test 110 in -9223372036854775790:100:9223372036854775710 -@test 9223372036854775610 in -9223372036854775790:100:9223372036854775710 -@test 9223372036854775710 in -9223372036854775790:100:9223372036854775710 - - -@test !(3.5 in 1:5) -@test (3 in 1:5) -@test (3 in 5:-1:1) -#@test (3 in 3+0*(1:5)) -#@test !(4 in 3+0*(1:5)) - -r = 0.0:0.01:1.0 -@test (r[30] in r) -r = (-4*Int64(maxintfloat(Int === Int32 ? Float32 : Float64))):5 -@test (3 in r) -@test (3.0 in r) - -@test !(1 in 1:0) -@test !(1.0 in 1.0:0.0) - -# indexing range with empty range (#4309) -@test (3:6)[5:4] == 7:6 -@test_throws BoundsError (3:6)[5:5] -@test_throws BoundsError (3:6)[5] -@test (0:2:10)[7:6] == 12:2:10 -@test_throws BoundsError (0:2:10)[7:7] - -# indexing with negative ranges (#8351) -for a=Range[3:6, 0:2:10], b=Range[0:1, 2:-1:0] - @test_throws BoundsError a[b] -end - -# avoiding intermediate overflow (#5065) -@test length(1:4:typemax(Int)) == div(typemax(Int),4) + 1 - -# overflow in length -@test_throws OverflowError length(0:typemax(Int)) -@test_throws OverflowError length(typemin(Int):typemax(Int)) -@test_throws OverflowError length(-1:typemax(Int)-1) - -let s = 0 - # loops ending at typemax(Int) - for i = (typemax(Int)-1):typemax(Int) - s += 1 - @test s <= 2 - end - @test s == 2 - - s = 0 - for i = (typemax(Int)-2):(typemax(Int)-1) - s += 1 - @test s <= 2 - end - @test s == 2 - - s = 0 - for i = typemin(Int):(typemin(Int)+1) - s += 1 - @test s <= 2 - end - @test s == 2 - - # loops covering the full range of smaller integer types - s = 0 - for i = typemin(UInt8):typemax(UInt8) - s += 1 - end - @test s == 256 - - s = 0 - for i = typemin(UInt8):one(UInt8):typemax(UInt8) - s += 1 - end - @test s == 256 - - # loops past typemax(Int) - n = 0 - s = Int128(0) - for i = typemax(UInt64)-2:typemax(UInt64) - n += 1 - s += i - end - @test n == 3 - @test s == 3*Int128(typemax(UInt64)) - 3 - - # loops over empty ranges - s = 0 - for i = 0xff:0x00 - s += 1 - end - @test s == 0 - - s = 0 - for i = Int128(typemax(Int128)):Int128(typemin(Int128)) - s += 1 - end - @test s == 0 -end - -# sums of ranges -@test sum(1:100) == 5050 -@test sum(0:100) == 5050 -@test sum(-100:100) == 0 -@test sum(0:2:100) == 2550 - -# overflowing sums (see #5798) -if Sys.WORD_SIZE == 64 - @test sum(Int128(1):10^18) == div(10^18 * (Int128(10^18)+1), 2) - @test sum(Int128(1):10^18-1) == div(10^18 * (Int128(10^18)-1), 2) -else - @test sum(Int64(1):10^9) == div(10^9 * (Int64(10^9)+1), 2) - @test sum(Int64(1):10^9-1) == div(10^9 * (Int64(10^9)-1), 2) -end - -# Tricky sums of StepRangeLen #8272 -@test sum(10000.:-0.0001:0) == 5.00000005e11 -@test sum(0:0.001:1) == 500.5 -@test sum(0:0.000001:1) == 500000.5 -@test sum(0:0.1:10) == 505. - -# operations with scalars -@test (1:3) - 2 == -1:1 -@test (1:3) - 0.25 == 1-0.25:3-0.25 -@test (1:3) + 2 == 3:5 -@test (1:3) + 0.25 == 1+0.25:3+0.25 -@test (1:2:6) + 1 == 2:2:6 -@test (1:2:6) + 0.3 == 1+0.3:2:5+0.3 -@test (1:2:6) - 1 == 0:2:4 -@test (1:2:6) - 0.3 == 1-0.3:2:5-0.3 -@test 2 - (1:3) == 1:-1:-1 - -# operations between ranges and arrays -@test all(([1:5;] + (5:-1:1)) .== 6) -@test all(((5:-1:1) + [1:5;]) .== 6) -@test all(([1:5;] - (1:5)) .== 0) -@test all(((1:5) - [1:5;]) .== 0) - -# tricky floating-point ranges - -@test [0.1:0.1:0.3;] == [linspace(0.1,0.3,3);] == [1:3;]./10 -@test [0.0:0.1:0.3;] == [linspace(0.0,0.3,4);] == [0:3;]./10 -@test [0.3:-0.1:-0.1;] == [linspace(0.3,-0.1,5);] == [3:-1:-1;]./10 -@test [0.1:-0.1:-0.3;] == [linspace(0.1,-0.3,5);] == [1:-1:-3;]./10 -@test [0.0:0.1:1.0;] == [linspace(0.0,1.0,11);] == [0:10;]./10 -@test [0.0:-0.1:1.0;] == [linspace(0.0,1.0,0);] == [] -@test [0.0:0.1:-1.0;] == [linspace(0.0,-1.0,0);] == [] -@test [0.0:-0.1:-1.0;] == [linspace(0.0,-1.0,11);] == [0:-1:-10;]./10 -@test [1.0:1/49:27.0;] == [linspace(1.0,27.0,1275);] == [49:1323;]./49 -@test [0.0:0.7:2.1;] == [linspace(0.0,2.1,4);] == [0:7:21;]./10 -@test [0.0:1.1:3.3;] == [linspace(0.0,3.3,4);] == [0:11:33;]./10 -@test [0.1:1.1:3.4;] == [linspace(0.1,3.4,4);] == [1:11:34;]./10 -@test [0.0:1.3:3.9;] == [linspace(0.0,3.9,4);] == [0:13:39;]./10 -@test [0.1:1.3:4.0;] == [linspace(0.1,4.0,4);] == [1:13:40;]./10 -@test [1.1:1.1:3.3;] == [linspace(1.1,3.3,3);] == [11:11:33;]./10 -@test [0.3:0.1:1.1;] == [linspace(0.3,1.1,9);] == [3:1:11;]./10 -@test [0.0:1.0:0.0;] == [linspace(0.0,0.0,1);] == [0.0] -@test [0.0:-1.0:0.0;] == [linspace(0.0,0.0,1);] == [0.0] - -@test [0.0:1.0:5.5;] == [0:10:55;]./10 -@test [0.0:-1.0:0.5;] == [] -@test [0.0:1.0:0.5;] == [0.0] - -@test [prevfloat(0.1):0.1:0.3;] == [prevfloat(0.1), 0.2, 0.3] -@test [nextfloat(0.1):0.1:0.3;] == [nextfloat(0.1), 0.2] -@test [prevfloat(0.0):0.1:0.3;] == [prevfloat(0.0), 0.1, 0.2] -@test [nextfloat(0.0):0.1:0.3;] == [nextfloat(0.0), 0.1, 0.2] -@test [0.1:0.1:prevfloat(0.3);] == [0.1, 0.2] -@test [0.1:0.1:nextfloat(0.3);] == [0.1, 0.2, nextfloat(0.3)] -@test [0.0:0.1:prevfloat(0.3);] == [0.0, 0.1, 0.2] -@test [0.0:0.1:nextfloat(0.3);] == [0.0, 0.1, 0.2, nextfloat(0.3)] -@test [0.1:prevfloat(0.1):0.3;] == [0.1, 0.2, 0.3] -@test [0.1:nextfloat(0.1):0.3;] == [0.1, 0.2] -@test [0.0:prevfloat(0.1):0.3;] == [0.0, prevfloat(0.1), prevfloat(0.2), 0.3] -@test [0.0:nextfloat(0.1):0.3;] == [0.0, nextfloat(0.1), nextfloat(0.2)] - -for T = (Float32, Float64,),# BigFloat), - a = -5:25, s = [-5:-1;1:25;], d = 1:25, n = -1:15 - den = convert(T,d) - start = convert(T,a)/den - step = convert(T,s)/den - stop = convert(T,(a+(n-1)*s))/den - vals = T[a:s:a+(n-1)*s;]./den - r = start:step:stop - @test [r;] == vals - @test [linspace(start, stop, length(r));] == vals - # issue #7420 - n = length(r) - @test [r[1:n];] == [r;] - @test [r[2:n];] == [r;][2:end] - @test [r[1:3:n];] == [r;][1:3:n] - @test [r[2:2:n];] == [r;][2:2:n] - @test [r[n:-1:2];] == [r;][n:-1:2] - @test [r[n:-2:1];] == [r;][n:-2:1] -end - -# issue #20373 (unliftable ranges with exact end points) -@test [3*0.05:0.05:0.2;] == [linspace(3*0.05,0.2,2);] == [3*0.05,0.2] -@test [0.2:-0.05:3*0.05;] == [linspace(0.2,3*0.05,2);] == [0.2,3*0.05] -@test [-3*0.05:-0.05:-0.2;] == [linspace(-3*0.05,-0.2,2);] == [-3*0.05,-0.2] -@test [-0.2:0.05:-3*0.05;] == [linspace(-0.2,-3*0.05,2);] == [-0.2,-3*0.05] - -for T = (Float32, Float64,), i = 1:2^15, n = 1:5 - start, step = randn(T), randn(T) - step == 0 && continue - stop = start + (n-1)*step - # `n` is not necessarily unique s.t. `start + (n-1)*step == stop` - # so test that `length(start:step:stop)` satisfies this identity - # and is the closest value to `(stop-start)/step` to do so - lo = hi = n - while start + (lo-1)*step == stop; lo -= 1; end - while start + (hi-1)*step == stop; hi += 1; end - m = clamp(round(Int, (stop-start)/step) + 1, lo+1, hi-1) - r = start:step:stop - @test m == length(r) - # FIXME: these fail some small portion of the time - @test_skip start == first(r) - @test_skip stop == last(r) - l = linspace(start,stop,n) - @test n == length(l) - # FIXME: these fail some small portion of the time - @test_skip start == first(l) - @test_skip stop == last(l) -end - -# Inexact errors on 32 bit architectures. #22613 -@test first(linspace(log(0.2), log(10.0), 10)) == log(0.2) -@test last(linspace(log(0.2), log(10.0), 10)) == log(10.0) -@test length(Base.floatrange(-3e9, 1.0, 1, 1.0)) == 1 - -# linspace & ranges with very small endpoints -for T = (Float32, Float64) - z = zero(T) - u = eps(z) - @test first(linspace(u,u,0)) == u - @test last(linspace(u,u,0)) == u - @test first(linspace(-u,u,0)) == -u - @test last(linspace(-u,u,0)) == u - @test [linspace(-u,u,0);] == [] - @test [linspace(-u,-u,1);] == [-u] - @test [linspace(-u,u,2);] == [-u,u] - @test [linspace(-u,u,3);] == [-u,0,u] - @test first(linspace(-u,-u,0)) == -u - @test last(linspace(-u,-u,0)) == -u - @test first(linspace(u,-u,0)) == u - @test last(linspace(u,-u,0)) == -u - @test [linspace(u,-u,0);] == [] - @test [linspace(u,u,1);] == [u] - @test [linspace(u,-u,2);] == [u,-u] - @test [linspace(u,-u,3);] == [u,0,-u] - v = linspace(-u,u,12) - @test length(v) == 12 - @test [-3u:u:3u;] == [linspace(-3u,3u,7);] == [-3:3;].*u - @test [3u:-u:-3u;] == [linspace(3u,-3u,7);] == [3:-1:-3;].*u -end - -# linspace with very large endpoints -for T = (Float32, Float64) - largeint = Int(min(maxintfloat(T), typemax(Int))) - a = realmax() - for i = 1:5 - @test [linspace(a,a,1);] == [a] - @test [linspace(-a,-a,1);] == [-a] - b = realmax() - for j = 1:5 - @test [linspace(-a,b,0);] == [] - @test [linspace(-a,b,2);] == [-a,b] - @test [linspace(-a,b,3);] == [-a,(b-a)/2,b] - @test [linspace(a,-b,0);] == [] - @test [linspace(a,-b,2);] == [a,-b] - @test [linspace(a,-b,3);] == [a,(a-b)/2,-b] - for c = largeint-3:largeint - s = linspace(-a,b,c) - @test first(s) == -a - @test last(s) == b - @test length(s) == c - s = linspace(a,-b,c) - @test first(s) == a - @test last(s) == -b - @test length(s) == c - end - b = prevfloat(b) - end - a = prevfloat(a) - end -end - -# issue #20380 -r = LinSpace(1,4,4) -@test isa(r[1:4], LinSpace) - -# linspace with 1 or 0 elements (whose step length is NaN) -@test issorted(linspace(1,1,0)) -@test issorted(linspace(1,1,1)) - -# near-equal ranges -@test 0.0:0.1:1.0 != 0.0f0:0.1f0:1.0f0 - -# comparing and hashing ranges -let - Rs = Range[1:2, map(Int32,1:3:17), map(Int64,1:3:17), 1:0, 17:-3:0, - 0.0:0.1:1.0, map(Float32,0.0:0.1:1.0), - linspace(0, 1, 20), map(Float32, linspace(0, 1, 20))] - for r in Rs - ar = collect(r) - @test r != ar - @test !isequal(r,ar) - for s in Rs - as = collect(s) - @test !isequal(r,s) || hash(r)==hash(s) - @test (r==s) == (ar==as) - end - end -end - - -@test 1:2:10 == 1:2:10 != 1:3:10 != 1:3:13 != 2:3:13 == 2:3:11 != 2:11 -@test 1:1:10 == 1:10 == 1:10 == Base.OneTo(10) == Base.OneTo(10) -@test 1:10 != 2:10 != 2:11 != Base.OneTo(11) -@test Base.OneTo(10) != Base.OneTo(11) != 1:10 - -# issue #2959 -@test 1.0:1.5 == 1.0:1.0:1.5 == 1.0:1.0 -#@test 1.0:(.3-.1)/.1 == 1.0:2.0 - -let r = typemin(Int64):2:typemax(Int64), s = typemax(Int64):-2:typemin(Int64) - @test first(r) == typemin(Int64) - @test last(r) == (typemax(Int64)-1) - @test_throws OverflowError length(r) - - @test first(s) == typemax(Int64) - @test last(s) == (typemin(Int64)+1) - @test_throws OverflowError length(s) -end - -@test length(typemin(Int64):3:typemax(Int64)) == 6148914691236517206 -@test length(typemax(Int64):-3:typemin(Int64)) == 6148914691236517206 - -for s in 3:100 - @test length(typemin(Int):s:typemax(Int)) == length(big(typemin(Int)):big(s):big(typemax(Int))) - @test length(typemax(Int):-s:typemin(Int)) == length(big(typemax(Int)):big(-s):big(typemin(Int))) -end - -@test length(UInt(1):UInt(1):UInt(0)) == 0 -@test length(typemax(UInt):UInt(1):(typemax(UInt)-1)) == 0 -@test length(typemax(UInt):UInt(2):(typemax(UInt)-1)) == 0 -@test length((typemin(Int)+3):5:(typemin(Int)+1)) == 0 - -# issue #6364 -@test length((1:64)*(pi/5)) == 64 - -# issue #6973 -let r1 = 1.0:0.1:2.0, r2 = 1.0f0:0.2f0:3.0f0, r3 = 1:2:21 - @test r1 + r1 == 2*r1 - @test r1 + r2 == 2.0:0.3:5.0 - @test (r1 + r2) - r2 == r1 - @test r1 + r3 == convert(StepRangeLen{Float64}, r3) + r1 - @test r3 + r3 == 2 * r3 -end - -# issue #7114 -r = -0.004532318104333742:1.2597349521122731e-5:0.008065031416788989 -@test length(r[1:end-1]) == length(r) - 1 -@test isa(r[1:2:end],Range) && length(r[1:2:end]) == div(length(r)+1, 2) -@test r[3:5][2] ≈ r[4] -@test r[5:-2:1][2] ≈ r[3] -@test_throws BoundsError r[0:10] -@test_throws BoundsError r[1:10000] - -r = linspace(1/3,5/7,6) -@test length(r) == 6 -@test r[1] == 1/3 -@test abs(r[end] - 5/7) <= eps(5/7) -r = linspace(0.25,0.25,1) -@test length(r) == 1 -@test_throws ArgumentError linspace(0.25,0.5,1) - -# issue #7426 -@test [typemax(Int):1:typemax(Int);] == [typemax(Int)] - -#issue #7484 -r7484 = 0.1:0.1:1 -@test [reverse(r7484);] == reverse([r7484;]) - -# issue #7387 -for r in (0:1, 0.0:1.0) - @test [r+im;] == [r;]+im - @test [r-im;] == [r;]-im - @test [r*im;] == [r;]*im - @test [r/im;] == [r;]/im -end - -# Preservation of high precision upon addition -r = (-0.1:0.1:0.3) + ((-0.3:0.1:0.1) + 1e-12) -@test r[3] == 1e-12 - -# issue #7709 -@test length(map(identity, 0x01:0x05)) == 5 -@test length(map(identity, 0x0001:0x0005)) == 5 -@test length(map(identity, UInt64(1):UInt64(5))) == 5 -@test length(map(identity, UInt128(1):UInt128(5))) == 5 - -# mean/median -for f in (mean, median) - for n = 2:5 - @test f(2:n) == f([2:n;]) - @test f(2:0.1:n) ≈ f([2:0.1:n;]) - end -end - -# issue #8531 -let smallint = (Int === Int64 ? - (Int8,UInt8,Int16,UInt16,Int32,UInt32) : - (Int8,UInt8,Int16,UInt16)) - for T in smallint - @test length(typemin(T):typemax(T)) == 2^(8*sizeof(T)) - end -end - -# issue #8584 -@test (0:1//2:2)[1:2:3] == 0:1//1:1 - -# issue #12278 -@test length(1:UInt(0)) == 0 - -# zip -let i = 0 -x = 1:2:8 -y = 2:2:8 -xy = 1:8 -for (thisx, thisy) in zip(x, y) - @test thisx == xy[i+=1] - @test thisy == xy[i+=1] -end -end - -# issue #9962 -@test eltype(0:1//3:10) <: Rational -@test (0:1//3:10)[1] == 0 -@test (0:1//3:10)[2] == 1//3 - -# converting ranges (issue #10965) -@test promote(0:1, UInt8(2):UInt8(5)) === (0:1, 2:5) -@test convert(UnitRange{Int}, 0:5) === 0:5 -@test convert(UnitRange{Int128}, 0:5) === Int128(0):Int128(5) - -@test promote(0:1:1, UInt8(2):UInt8(1):UInt8(5)) === (0:1:1, 2:1:5) -@test convert(StepRange{Int,Int}, 0:1:1) === 0:1:1 -@test convert(StepRange{Int128,Int128}, 0:1:1) === Int128(0):Int128(1):Int128(1) - -@test promote(0:1:1, 2:5) === (0:1:1, 2:1:5) -@test convert(StepRange{Int128,Int128}, 0:5) === Int128(0):Int128(1):Int128(5) -@test convert(StepRange, 0:5) === 0:1:5 -@test convert(StepRange{Int128,Int128}, 0.:5) === Int128(0):Int128(1):Int128(5) - -@test_throws ArgumentError StepRange(1.1,1,5.1) - -@test promote(0f0:inv(3f0):1f0, 0.:2.:5.) === (0:1/3:1, 0.:2.:5.) - -@test convert(StepRangeLen{Float64}, 0:1/3:1) === 0:1/3:1 -@test convert(StepRangeLen{Float64}, 0f0:inv(3f0):1f0) === 0:1/3:1 - -@test promote(0:1/3:1, 0:5) === (0:1/3:1, 0.:1.:5.) -@test convert(StepRangeLen{Float64}, 0:5) === 0.:1.:5. -@test convert(StepRangeLen{Float64}, 0:1:5) === 0.:1.:5. -@test convert(StepRangeLen, 0:5) == 0:5 -@test convert(StepRangeLen, 0:1:5) == 0:1:5 - -@test convert(LinSpace{Float64}, 0.0:0.1:0.3) === LinSpace{Float64}(0.0, 0.3, 4) -@test convert(LinSpace, 0.0:0.1:0.3) === LinSpace{Float64}(0.0, 0.3, 4) -@test convert(LinSpace, 0:3) === LinSpace{Int}(0, 3, 4) - -@test start(LinSpace(0,3,4)) == 1 -@test 2*LinSpace(0,3,4) == LinSpace(0,6,4) -@test LinSpace(0,3,4)*2 == LinSpace(0,6,4) -@test LinSpace(0,3,4)/3 == LinSpace(0,1,4) -@test 2-LinSpace(0,3,4) == LinSpace(2,-1,4) -@test 2+LinSpace(0,3,4) == LinSpace(2,5,4) -@test -LinSpace(0,3,4) == LinSpace(0,-3,4) -@test reverse(LinSpace(0,3,4)) == LinSpace(3,0,4) - -# Issue #11245 -let io = IOBuffer() - show(io, linspace(1, 2, 3)) - str = String(take!(io)) -# @test str == "linspace(1.0,2.0,3)" - @test str == "1.0:0.5:2.0" -end - -# issue 10950 -r = 1//2:3 -@test length(r) == 3 -i = 1 -for x in r - @test x == i//2 - i += 2 -end -@test i == 7 - -# stringmime/show should display the range or linspace nicely -# to test print_range in range.jl -replstrmime(x) = sprint((io,x) -> show(IOContext(io, :limit => true), MIME("text/plain"), x), x) -@test replstrmime(1:4) == "1:4" -@test stringmime("text/plain", 1:4) == "1:4" -@test stringmime("text/plain", linspace(1,5,7)) == "1.0:0.6666666666666666:5.0" -@test stringmime("text/plain", LinSpace{Float64}(1,5,7)) == "7-element LinSpace{Float64}:\n 1.0,1.66667,2.33333,3.0,3.66667,4.33333,5.0" -@test repr(linspace(1,5,7)) == "1.0:0.6666666666666666:5.0" -@test repr(LinSpace{Float64}(1,5,7)) == "linspace(1.0,5.0,7)" -@test replstrmime(0:100.) == "0.0:1.0:100.0" -# next is to test a very large range, which should be fast because print_range -# only examines spacing of the left and right edges of the range, sufficient -# to cover the designated screen size. -@test replstrmime(linspace(0,100, 10000)) == "0.0:0.010001000100010001:100.0" -@test replstrmime(LinSpace{Float64}(0,100, 10000)) == "10000-element LinSpace{Float64}:\n 0.0,0.010001,0.020002,0.030003,0.040004,…,99.95,99.96,99.97,99.98,99.99,100.0" - -@test sprint(show, UnitRange(1, 2)) == "1:2" -@test sprint(show, StepRange(1, 2, 5)) == "1:2:5" - - -# Issue 11049 and related -@test promote(linspace(0f0, 1f0, 3), linspace(0., 5., 2)) === - (linspace(0., 1., 3), linspace(0., 5., 2)) -@test convert(LinSpace{Float64}, linspace(0., 1., 3)) === LinSpace(0., 1., 3) -@test convert(LinSpace{Float64}, linspace(0f0, 1f0, 3)) === LinSpace(0., 1., 3) - -@test promote(linspace(0., 1., 3), 0:5) === (linspace(0., 1., 3), - linspace(0., 5., 6)) -@test convert(LinSpace{Float64}, 0:5) === LinSpace(0., 5., 6) -@test convert(LinSpace{Float64}, 0:1:5) === LinSpace(0., 5., 6) -@test convert(LinSpace, 0:5) === LinSpace{Int}(0, 5, 6) -@test convert(LinSpace, 0:1:5) === LinSpace{Int}(0, 5, 6) - -function test_range_index(r, s) - @test typeof(r[s]) == typeof(r) - @test [r;][s] == [r[s];] -end -test_range_index(linspace(0.1, 0.3, 3), 1:2) -test_range_index(linspace(0.1, 0.3, 3), 1:0) -test_range_index(linspace(1.0, 1.0, 1), 1:1) -test_range_index(linspace(1.0, 1.0, 1), 1:0) -test_range_index(linspace(1.0, 2.0, 0), 1:0) - -function test_linspace_identity{T}(r::Range{T}, mr) - @test -r == mr - @test -collect(r) == collect(mr) - @test isa(-r, typeof(r)) - - @test 1 + r + (-1) == r - @test 1 + collect(r) == collect(1 + r) == collect(r + 1) - @test isa(1 + r + (-1), typeof(r)) - @test 1 - r - 1 == mr - @test 1 - collect(r) == collect(1 - r) == collect(1 + mr) - @test collect(r) - 1 == collect(r - 1) == -collect(mr + 1) - @test isa(1 - r - 1, typeof(r)) - - @test 1 * r * 1 == r - @test 2 * r * T(0.5) == r - @test isa(1 * r * 1, typeof(r)) - @test r / 1 == r - @test r / 2 * 2 == r - @test r / T(0.5) * T(0.5) == r - @test isa(r / 1, typeof(r)) - - @test (2 * collect(r) == collect(r * 2) == collect(2 * r) == - collect(r * T(2.0)) == collect(T(2.0) * r) == - collect(r / T(0.5)) == -collect(mr * T(2.0))) -end - -test_linspace_identity(linspace(1.0, 27.0, 10), linspace(-1.0, -27.0, 10)) -test_linspace_identity(linspace(1f0, 27f0, 10), linspace(-1f0, -27f0, 10)) - -test_linspace_identity(linspace(1.0, 27.0, 0), linspace(-1.0, -27.0, 0)) -test_linspace_identity(linspace(1f0, 27f0, 0), linspace(-1f0, -27f0, 0)) - -test_linspace_identity(linspace(1.0, 1.0, 1), linspace(-1.0, -1.0, 1)) -test_linspace_identity(linspace(1f0, 1f0, 1), linspace(-1f0, -1f0, 1)) - -@test reverse(linspace(1.0, 27.0, 1275)) == linspace(27.0, 1.0, 1275) -@test [reverse(linspace(1.0, 27.0, 1275));] == - reverse([linspace(1.0, 27.0, 1275);]) - -# PR 12200 and related -for _r in (1:2:100, 1:100, 1f0:2f0:100f0, 1.0:2.0:100.0, - linspace(1, 100, 10), linspace(1f0, 100f0, 10)) - float_r = float(_r) - big_r = big.(_r) - @test typeof(big_r).name === typeof(_r).name - if eltype(_r) <: AbstractFloat - @test isa(float_r, typeof(_r)) - @test eltype(big_r) === BigFloat - else - @test isa(float_r, Range) - @test eltype(float_r) <: AbstractFloat - @test eltype(big_r) === BigInt - end -end - -@test_throws DimensionMismatch linspace(1.,5.,5) + linspace(1.,5.,6) -@test_throws DimensionMismatch linspace(1.,5.,5) - linspace(1.,5.,6) -@test_throws DimensionMismatch linspace(1.,5.,5) .* linspace(1.,5.,6) -@test_throws DimensionMismatch linspace(1.,5.,5) ./ linspace(1.,5.,6) - -@test_throws DimensionMismatch (1:5) + (1:6) -@test_throws DimensionMismatch (1:5) - (1:6) -@test_throws DimensionMismatch (1:5) .* (1:6) -@test_throws DimensionMismatch (1:5) ./ (1:6) - -@test_throws DimensionMismatch (1.:5.) + (1.:6.) -@test_throws DimensionMismatch (1.:5.) - (1.:6.) -@test_throws DimensionMismatch (1.:5.) .* (1.:6.) -@test_throws DimensionMismatch (1.:5.) ./ (1.:6.) - -function test_range_sum_diff(r1, r2, r_sum, r_diff) - @test r1 + r2 == r_sum - @test r2 + r1 == r_sum - @test r1 - r2 == r_diff - @test r2 - r1 == -r_diff - - @test collect(r1) + collect(r2) == collect(r_sum) - @test collect(r2) + collect(r1) == collect(r_sum) - @test collect(r1) - collect(r2) == collect(r_diff) - @test collect(r2) - collect(r1) == collect(-r_diff) -end - -test_range_sum_diff(1:5, 0:2:8, 1:3:13, 1:-1:-3) -test_range_sum_diff(1.:5., 0.:2.:8., 1.:3.:13., 1.:-1.:-3.) -test_range_sum_diff(linspace(1.,5.,5), linspace(0.,-4.,5), - linspace(1.,1.,5), linspace(1.,9.,5)) - -test_range_sum_diff(1:5, 0.:2.:8., 1.:3.:13., 1.:-1.:-3.) -test_range_sum_diff(1:5, linspace(0, 8, 5), - linspace(1, 13, 5), linspace(1, -3, 5)) -test_range_sum_diff(1.:5., linspace(0, 8, 5), - linspace(1, 13, 5), linspace(1, -3, 5)) - -# Issue #12388 -let r = 0x02:0x05 - @test r[2:3] == 0x03:0x04 -end - -# Issue #13738 -for r in (big(1):big(2), UInt128(1):UInt128(2), 0x1:0x2) - rr = r[r] - @test typeof(rr) == typeof(r) - @test r[r] == r - # these calls to similar must not throw: - @test size(similar(r, size(r))) == size(similar(r, length(r))) -end - -# sign, conj, ~ (Issue #16067) -let A = -1:1, B = -1.0:1.0 - @test sign.(A) == [-1,0,1] - @test sign.(B) == [-1,0,1] - @test typeof(sign.(A)) === Vector{Int} - @test typeof(sign.(B)) === Vector{Float64} - - @test conj(A) === A - @test conj(B) === B - - @test .~A == [0,-1,-2] - @test typeof(.~A) == Vector{Int} -end - -# conversion to Array -let r = 1:3, a = [1,2,3] - @test convert(Array, r) == a - @test convert(Array{Int}, r) == a - @test convert(Array{Float64}, r) == a - @test convert(Array{Int,1}, r) == a - @test convert(Array{Float64,1}, r) == a -end - -# OneTo -r = Base.OneTo(-5) -@test isempty(r) -@test length(r) == 0 -@test size(r) == (0,) -r = Base.OneTo(3) -@test !isempty(r) -@test length(r) == 3 -@test size(r) == (3,) -@test step(r) == 1 -@test first(r) == 1 -@test last(r) == 3 -@test minimum(r) == 1 -@test maximum(r) == 3 -@test r[2] == 2 -@test r[2:3] === 2:3 -@test_throws BoundsError r[4] -@test_throws BoundsError r[0] -@test r+1 === 2:4 -@test 2*r === 2:2:6 -@test r+r === 2:2:6 -k = 0 -for i in r - @test i == (k+=1) -end -@test intersect(r, Base.OneTo(2)) == Base.OneTo(2) -@test intersect(r, 0:5) == 1:3 -@test intersect(r, 2) === intersect(2, r) === 2:2 -@test findin(r, r) === findin(r, 1:length(r)) === findin(1:length(r), r) === 1:length(r) -r2 = Base.OneTo(7) -@test findin(r2, 2:length(r2)-1) === 2:length(r2)-1 -@test findin(2:length(r2)-1, r2) === 1:length(r2)-2 -io = IOBuffer() -show(io, r) -str = String(take!(io)) -@test str == "Base.OneTo(3)" - -# linspace of other types -r = linspace(0, 3//10, 4) -@test eltype(r) == Rational{Int} -@test r[2] === 1//10 - -a, b = 1.0, nextfloat(1.0) -ba, bb = BigFloat(a), BigFloat(b) -r = linspace(ba, bb, 3) -@test eltype(r) == BigFloat -@test r[1] == a && r[3] == b -@test r[2] == (ba+bb)/2 - -a, b = rand(10), rand(10) -r = linspace(a, b, 5) -@test r[1] == a && r[5] == b -for i = 2:4 - x = ((5-i)//4)*a + ((i-1)//4)*b - @test r[i] == x -end - -# issue #20382 -r = @inferred(colon(big(1.0),big(2.0),big(5.0))) -@test eltype(r) == BigFloat - -# issue #14420 -for r in (linspace(0.10000000000000045, 1), 0.10000000000000045:(1-0.10000000000000045)/49:1) - @test r[1] === 0.10000000000000045 - @test r[end] === 1.0 -end - -# issue #20381 -let r = linspace(-big(1.0),big(1.0),4) - @test isa(@inferred(r[2]), BigFloat) - @test r[2] ≈ big(-1.0)/3 -end - -# issue #20520 -let r = linspace(1.3173739f0, 1.3173739f0, 3) - @test length(r) == 3 - @test first(r) === 1.3173739f0 - @test last(r) === 1.3173739f0 - @test r[2] === 1.3173739f0 -end - -let r = linspace(1.0, 3+im, 4) - @test r[1] === 1.0+0.0im - @test r[2] ≈ (5/3)+(1/3)im - @test r[3] ≈ (7/3)+(2/3)im - @test r[4] === 3.0+im -end - -# ambiguity between colon methods (#20988) -struct NotReal; val; end -Base.:+(x, y::NotReal) = x + y.val -Base.zero(y::NotReal) = zero(y.val) -Base.rem(x, y::NotReal) = rem(x, y.val) -Base.isless(x, y::NotReal) = isless(x, y.val) -@test colon(1, NotReal(1), 5) isa StepRange{Int,NotReal} - -# dimensional correctness: -isdefined(Main, :TestHelpers) || @eval Main include("TestHelpers.jl") -using TestHelpers.Furlong -@test_throws MethodError collect(Furlong(2):Furlong(10)) # step size is ambiguous -@test_throws MethodError range(Furlong(2), 9) # step size is ambiguous -@test collect(Furlong(2):Furlong(1):Furlong(10)) == collect(range(Furlong(2),Furlong(1),9)) == Furlong.(2:10) -@test collect(Furlong(1.0):Furlong(0.5):Furlong(10.0)) == - collect(Furlong(1):Furlong(0.5):Furlong(10)) == Furlong.(1:0.5:10) - -# issue #22270 -let linsp = linspace(1.0, 2.0, 10) - @test typeof(linsp.ref) == Base.TwicePrecision{Float64} - @test Float32(linsp.ref) === convert(Float32, linsp.ref) - @test Float32(linsp.ref) ≈ linsp.ref.hi + linsp.ref.lo -end - -# Issue #23300 -x = -5:big(1.0):5 -@test map(Float64, x) === -5.0:1.0:5.0 -@test map(Float32, x) === -5.0f0:1.0f0:5.0f0 -@test map(Float16, x) === Float16(-5.0):Float16(1.0):Float16(5.0) -@test map(BigFloat, x) === x diff --git a/julia-0.6.3/share/julia/test/read.jl b/julia-0.6.3/share/julia/test/read.jl deleted file mode 100644 index 6f794a8..0000000 --- a/julia-0.6.3/share/julia/test/read.jl +++ /dev/null @@ -1,494 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -mktempdir() do dir - -tasks = [] - -# Create test file -filename = joinpath(dir, "file.txt") -text = "C1,C2\n1,2\na,b\n" - -# List of IO producers -l = Vector{Tuple{AbstractString,Function}}() - - -# File -io = (text) -> begin - write(filename, text) - Base.Filesystem.open(filename, Base.Filesystem.JL_O_RDONLY) -end -s = io(text) -@test isa(s, IO) -@test isa(s, Base.Filesystem.File) -close(s) -push!(l, ("File", io)) - - -# IOStream -io = (text) -> begin - write(filename, text) - open(filename) -end -s = io(text) -@test isa(s, IO) -@test isa(s, IOStream) -close(s) -push!(l, ("IOStream", io)) - - -# IOBuffer -io = (text)->IOBuffer(text) -s = io(text) -@test isa(s, IO) -@test isa(s, IOBuffer) -close(s) -push!(l, ("IOBuffer", io)) - - -function run_test_server(srv, text) - push!(tasks, @async begin - try - sock = accept(srv) - try - write(sock,text) - catch e - if typeof(e) != Base.UVError - rethrow(e) - end - finally - close(sock) - end - finally - close(srv) - end - end) - yield() -end - - -# TCPSocket -io = (text) -> begin - port, srv = listenany(rand(2000:4000)) - run_test_server(srv, text) - connect(port) -end -s = io(text) -@test isa(s, IO) -@test isa(s, TCPSocket) -close(s) -push!(l, ("TCPSocket", io)) - - -# PipeEndpoint -io = (text) -> begin - a = "\\\\.\\pipe\\uv-test-$(randstring(6))" - b = joinpath(dir, "socket-$(randstring(6))") - socketname = is_windows() ? a : b - srv = listen(socketname) - run_test_server(srv, text) - connect(socketname) -end -s = io(text) -@test isa(s, IO) -@test isa(s, Base.PipeEndpoint) -close(s) -push!(l, ("PipeEndpoint", io)) - - -#FIXME See https://github.com/JuliaLang/julia/issues/14747 -# Reading from open(::Command) seems to deadlock on Linux/Travis -#= -if !is_windows() - -# Windows type command not working? -# See "could not spawn `type 'C:\Users\appveyor\AppData\Local\Temp\1\jul3516.tmp\file.txt'`" -#https://ci.appveyor.com/project/StefanKarpinski/julia/build/1.0.12733/job/hpwjs4hmf03vs5ag#L1244 - -# Pipe -io = (text) -> begin - write(filename, text) - open(`$(is_windows() ? "type" : "cat") $filename`)[1] -# Was open(`echo -n $text`)[1] -# See https://github.com/JuliaLang/julia/issues/14747 -end -s = io(text) -@test isa(s, IO) -@test isa(s, Pipe) -close(s) -push!(l, ("Pipe", io)) - -end -=# - - -open_streams = [] -function cleanup() - for s in open_streams - try close(s) end - end - empty!(open_streams) - for tsk in tasks - wait(tsk) - end - empty!(tasks) -end - - -verbose = false - - -for (name, f) in l - io = ()->(s=f(text); push!(open_streams, s); s) - - write(filename, text) - - verbose && println("$name read...") - @test read(io(), UInt8) == read(IOBuffer(text), UInt8) - @test read(io(), UInt8) == read(filename, UInt8) - @test read(io(), Int) == read(IOBuffer(text), Int) - @test read(io(), Int) == read(filename,Int) - s1 = io() - s2 = IOBuffer(text) - @test read(s1, UInt32, 2) == read(s2, UInt32, 2) - @test !eof(s1) - @test read(s1, UInt8, 5) == read(s2, UInt8, 5) - @test !eof(s1) - @test read(s1, UInt8, 1) == read(s2, UInt8, 1) - @test eof(s1) - @test_throws EOFError read(s1, UInt8) - @test eof(s1) - close(s1) - close(s2) - - verbose && println("$name eof...") - n = length(text) - 1 - @test read!(io(), Vector{UInt8}(n)) == - read!(IOBuffer(text), Vector{UInt8}(n)) - @test (s = io(); read!(s, Vector{UInt8}(n)); !eof(s)) - n = length(text) - @test read!(io(), Vector{UInt8}(n)) == - read!(IOBuffer(text), Vector{UInt8}(n)) - @test (s = io(); read!(s, Vector{UInt8}(n)); eof(s)) - n = length(text) + 1 - @test_throws EOFError read!(io(), Vector{UInt8}(n)) - @test_throws EOFError read!(io(), Vector{UInt8}(n)) - - old_text = text - cleanup() - - for text in [ - old_text, - String(Char['A' + i % 52 for i in 1:(div(Base.SZ_UNBUFFERED_IO,2))]), - String(Char['A' + i % 52 for i in 1:( Base.SZ_UNBUFFERED_IO -1)]), - String(Char['A' + i % 52 for i in 1:( Base.SZ_UNBUFFERED_IO )]), - String(Char['A' + i % 52 for i in 1:( Base.SZ_UNBUFFERED_IO +1)]) - ] - write(filename, text) - - verbose && println("$name readstring...") - @test readstring(io()) == text - - @test readstring(io()) == readstring(filename) - - - verbose && println("$name read...") - @test read(io()) == Vector{UInt8}(text) - - @test read(io()) == read(filename) - - cleanup() - - - verbose && println("$name readbytes!...") - l = length(text) - for n = [1, 2, l-2, l-1, l, l+1, l+2] - a1 = Vector{UInt8}(n) - a2 = Vector{UInt8}(n) - s1 = io() - s2 = IOBuffer(text) - n1 = readbytes!(s1, a1) - n2 = readbytes!(s2, a2) - @test n1 == n2 - @test length(a1) == length(a2) - @test a1[1:n1] == a2[1:n2] - @test n <= length(text) || eof(s1) - @test n <= length(text) || eof(s2) - - cleanup() - end - - verbose && println("$name read!...") - l = length(text) - for n = [1, 2, l-2, l-1, l] - @test read!(io(), Vector{UInt8}(n)) == - read!(IOBuffer(text), Vector{UInt8}(n)) - @test read!(io(), Vector{UInt8}(n)) == - read!(filename, Vector{UInt8}(n)) - - cleanup() - end - @test_throws EOFError read!(io(), Vector{UInt8}(length(text)+1)) - - - verbose && println("$name readuntil...") - @test readuntil(io(), '\n') == readuntil(IOBuffer(text),'\n') - @test readuntil(io(), '\n') == readuntil(filename,'\n') - @test readuntil(io(), "\n") == readuntil(IOBuffer(text),"\n") - @test readuntil(io(), "\n") == readuntil(filename,"\n") - @test readuntil(io(), ',') == readuntil(IOBuffer(text),',') - @test readuntil(io(), ',') == readuntil(filename,',') - - cleanup() - - verbose && println("$name readline...") - @test readline(io(), chomp=false) == readline(IOBuffer(text), chomp=false) - @test readline(io(), chomp=false) == readline(filename, chomp=false) - - verbose && println("$name readlines...") - @test readlines(io(), chomp=false) == readlines(IOBuffer(text), chomp=false) - @test readlines(io(), chomp=false) == readlines(filename, chomp=false) - @test readlines(io()) == readlines(IOBuffer(text)) - @test readlines(io()) == readlines(filename) - @test collect(eachline(io(), chomp=false)) == collect(eachline(IOBuffer(text), chomp=false)) - @test collect(eachline(io(), chomp=false)) == collect(eachline(filename, chomp=false)) - @test collect(eachline(io())) == collect(eachline(IOBuffer(text))) - @test collect(@inferred(eachline(io()))) == collect(@inferred(eachline(filename))) #20351 - - cleanup() - - verbose && println("$name countlines...") - @test countlines(io()) == countlines(IOBuffer(text)) - - verbose && println("$name readcsv...") - @test readcsv(io()) == readcsv(IOBuffer(text)) - @test readcsv(io()) == readcsv(filename) - - cleanup() - end - - text = old_text - write(filename, text) - - if !(typeof(io()) in [Base.PipeEndpoint, Pipe, TCPSocket]) - verbose && println("$name position...") - @test (s = io(); read!(s, Vector{UInt8}(4)); position(s)) == 4 - - verbose && println("$name seek...") - for n = 0:length(text)-1 - @test readlines(seek(io(), n)) == readlines(seek(IOBuffer(text), n)) - cleanup() - end - verbose && println("$name skip...") - for n = 0:length(text)-1 - @test readlines(seek(io(), n)) == readlines(seek(IOBuffer(text), n)) - @test readlines(skip(io(), n)) == readlines(skip(IOBuffer(text), n)) - cleanup() - end - verbose && println("$name seekend...") - @test readstring(seekend(io())) == "" - end - - - verbose && println("$name write(::IOStream, ...)") - to = open("$filename.to", "w") - write(to, io()) - close(to) - @test readstring("$filename.to") == text - - verbose && println("$name write(filename, ...)") - write("$filename.to", io()) - @test readstring("$filename.to") == text - - verbose && println("$name write(::IOBuffer, ...)") - to = IOBuffer(copy(Vector{UInt8}(text)), false, true) - write(to, io()) - @test String(take!(to)) == text - - cleanup() -end - -function test_read_nbyte() - fn = tempname() - # Write one byte. One byte read should work once - # but 2-byte read should throw EOFError. - f = open(fn, "w+") do f - write(f, 0x55) - flush(f) - seek(f, 0) - @test read(f, UInt8) == 0x55 - @test_throws EOFError read(f, UInt8) - seek(f, 0) - @test_throws EOFError read(f, UInt16) - end - # Write 2 more bytes. Now 2-byte read should work once - # but 4-byte read should fail with EOFError. - open(fn, "a+") do f - write(f, 0x4444) - flush(f) - seek(f, 0) - @test read(f, UInt16) == 0x4455 - @test_throws EOFError read(f, UInt16) - seek(f, 0) - @test_throws EOFError read(f, UInt32) - end - # Write 4 more bytes. Now 4-byte read should work once - # but 8-byte read should fail with EOFError. - open(fn, "a+") do f - write(f, 0x33333333) - flush(f) - seek(f, 0) - @test read(f, UInt32) == 0x33444455 - @test_throws EOFError read(f, UInt32) - seek(f, 0) - @test_throws EOFError read(f, UInt64) - end - # Writing one more byte should allow an 8-byte - # read to proceed. - open(fn, "a+") do f - write(f, 0x22) - flush(f) - seek(f, 0) - @test read(f, UInt64) == 0x2233333333444455 - end - rm(fn) -end -test_read_nbyte() - - -# DevNull -@test !isreadable(DevNull) -@test iswritable(DevNull) -@test isopen(DevNull) -@test write(DevNull, 0xff) === 1 -@test write(DevNull, Int32(1234)) === 4 -@test_throws EOFError read(DevNull, UInt8) -@test close(DevNull) === nothing -@test flush(DevNull) === nothing -@test eof(DevNull) -@test print(DevNull, "go to /dev/null") === nothing - - -let s = "qwerty" - @test read(IOBuffer(s)) == Vector{UInt8}(s) - @test read(IOBuffer(s), 10) == Vector{UInt8}(s) - @test read(IOBuffer(s), 1) == Vector{UInt8}(s)[1:1] - - # Test growing output array - x = UInt8[] - n = readbytes!(IOBuffer(s), x, 10) - @test x == Vector{UInt8}(s) - @test n == length(x) -end - - -# Filesystem.File -f = joinpath(dir, "test.txt") -open(io->write(io, "123"), f, "w") -f1 = open(f) -f2 = Base.Filesystem.open(f, Base.Filesystem.JL_O_RDONLY) -@test read(f1, UInt8) == read(f2, UInt8) == UInt8('1') -@test read(f1, UInt8) == read(f2, UInt8) == UInt8('2') -@test read(f1, UInt8) == read(f2, UInt8) == UInt8('3') -@test_throws EOFError read(f1, UInt8) -@test_throws EOFError read(f2, UInt8) -close(f1) -close(f2) - -a = UInt8[0,0,0] -f1 = open(f) -f2 = Base.Filesystem.open(f, Base.Filesystem.JL_O_RDONLY) -@test read!(f1, a) == read!(f2, a) == UInt8['1','2','3'] -@test_throws EOFError read!(f1, a) -@test_throws EOFError read!(f2, a) -close(f1) -close(f2) - -a = UInt8[0,0,0,0] -f1 = open(f) -f2 = Base.Filesystem.open(f, Base.Filesystem.JL_O_RDONLY) -@test_throws EOFError read!(f1, a) -@test_throws EOFError read!(f2, a) -close(f1) -close(f2) -rm(f) - -io = Base.Filesystem.open(f, Base.Filesystem.JL_O_WRONLY | Base.Filesystem.JL_O_CREAT | Base.Filesystem.JL_O_EXCL, 0o000) -@test write(io, "abc") == 3 -close(io) -if !is_windows() && get(ENV, "USER", "") != "root" && get(ENV, "HOME", "") != "/root" - # msvcrt _wchmod documentation states that all files are readable, - # so we don't test that it correctly set the umask on windows - @test_throws SystemError open(f) - @test_throws Base.UVError Base.Filesystem.open(f, Base.Filesystem.JL_O_RDONLY) -else - is_windows() || warn("file permissions tests skipped due to running tests as root (not recommended)") - close(open(f)) -end -chmod(f, 0o400) -f1 = open(f) -f2 = Base.Filesystem.open(f, Base.Filesystem.JL_O_RDONLY) -for i = 1:2 - @test !eof(f1) - @test !eof(f2) - @test position(f1) == 0 - @test position(f2) == 0 - @test readstring(f1) == readstring(f2) == "abc" - @test readstring(f1) == readstring(f2) == "" - @test position(f1) == 3 - @test position(f2) == 3 - @test eof(f1) - @test eof(f2) - @test seekstart(f1) == f1 - @test seekstart(f2) == f2 -end -@test seekend(f1) == f1 -@test seekend(f2) == f2 -@test eof(f1) -@test eof(f2) -@test skip(f1, -2) == f1 -@test skip(f2, -2) == f2 -@test position(f1) == 1 -@test position(f2) == 1 -@test_throws SystemError skip(f1, -2) -@test_throws SystemError skip(f2, -2) -@test position(f1) == 1 -@test position(f2) == 1 -@test skip(f1, 300) == f1 -@test skip(f2, 300) == f2 -@test position(f1) == 301 -@test position(f2) == 301 -@test eof(f1) -@test eof(f2) -@test_throws ArgumentError write(f1, '*') -@test_throws Base.UVError write(f2, '*') -close(f1) -close(f2) -@test eof(f1) -@test_throws Base.UVError eof(f2) -if get(ENV, "USER", "") != "root" && get(ENV, "HOME", "") != "/root" - @test_throws SystemError open(f, "r+") - @test_throws Base.UVError Base.Filesystem.open(f, Base.Filesystem.JL_O_RDWR) -else - warn("file permissions tests skipped due to running tests as root (not recommended)") -end -chmod(f, 0o600) -f1 = open(f, "r+") -f2 = Base.Filesystem.open(f, Base.Filesystem.JL_O_RDWR) -@test skip(f1, 10) == f1 -@test skip(f2, 10) == f2 -@test eof(f1) -@test eof(f2) -@test write(f1, '*') == 1 -@test flush(f1) === nothing -@test !eof(f2) -@test skip(f2, 1) == f2 -@test write(f2, '*') == 1 -@test !eof(f1) -@test seekstart(f1) == f1 -@test seekstart(f2) == f2 -@test readstring(f1) == readstring(f2) == "abc\0\0\0\0\0\0\0**" -close(f1) -close(f2) -rm(f) - -end # mktempdir() do dir diff --git a/julia-0.6.3/share/julia/test/reduce.jl b/julia-0.6.3/share/julia/test/reduce.jl deleted file mode 100644 index e537a83..0000000 --- a/julia-0.6.3/share/julia/test/reduce.jl +++ /dev/null @@ -1,375 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -# fold(l|r) & mapfold(l|r) -@test foldl(+, Int64[]) === Int64(0) # In reference to issues #7465/#20144 (PR #20160) -@test foldl(+, Int16[]) === Int32(0) -@test foldl(-, 1:5) == -13 -@test foldl(-, 10, 1:5) == -5 - -@test Base.mapfoldl(abs2, -, 2:5) == -46 -@test Base.mapfoldl(abs2, -, 10, 2:5) == -44 - -@test Base.mapfoldl(abs2, /, 2:5) ≈ 1/900 -@test Base.mapfoldl(abs2, /, 10, 2:5) ≈ 1/1440 - -@test Base.mapfoldl((x)-> x ⊻ true, &, true, [true false true false false]) == false -@test Base.mapfoldl((x)-> x ⊻ true, &, [true false true false false]) == false - -@test Base.mapfoldl((x)-> x ⊻ true, |, [true false true false false]) == true -@test Base.mapfoldl((x)-> x ⊻ true, |, false, [true false true false false]) == true - -@test foldr(+, Int64[]) === Int64(0) # In reference to issue #20144 (PR #20160) -@test foldr(+, Int16[]) === Int32(0) -@test foldr(-, 1:5) == 3 -@test foldr(-, 10, 1:5) == -7 -@test foldr(+, [1]) == 1 # Issue #21493 - -@test Base.mapfoldr(abs2, -, 2:5) == -14 -@test Base.mapfoldr(abs2, -, 10, 2:5) == -4 - -# reduce -@test reduce(+, Int64[]) === Int64(0) # In reference to issue #20144 (PR #20160) -@test reduce(+, Int16[]) === Int32(0) -@test reduce((x,y)->"($x+$y)", 9:11) == "((9+10)+11)" -@test reduce(max, [8 6 7 5 3 0 9]) == 9 -@test reduce(+, 1000, 1:5) == (1000 + 1 + 2 + 3 + 4 + 5) -@test reduce(+,1) == 1 - -# mapreduce -@test mapreduce(-, +, [-10 -9 -3]) == ((10 + 9) + 3) -@test mapreduce((x)->x[1:3], (x,y)->"($x+$y)", ["abcd", "efgh", "01234"]) == "((abc+efg)+012)" - -# mapreduce() for 1- 2- and n-sized blocks (PR #19325) -@test mapreduce(-, +, [-10]) == 10 -@test mapreduce(abs2, +, [-9, -3]) == 81 + 9 -@test mapreduce(-, +, [-9, -3, -4, 8, -2]) == (9 + 3 + 4 - 8 + 2) -@test mapreduce(-, +, collect(linspace(1.0, 10000.0, 10000))) == -50005000.0 -# mapreduce() type stability -@test typeof(mapreduce(*, +, Int8[10])) === - typeof(mapreduce(*, +, Int8[10, 11])) === - typeof(mapreduce(*, +, Int8[10, 11, 12, 13])) -@test typeof(mapreduce(*, +, Float32[10.0])) === - typeof(mapreduce(*, +, Float32[10, 11])) === - typeof(mapreduce(*, +, Float32[10, 11, 12, 13])) -# mapreduce() type stability when f supports empty collections -@test typeof(mapreduce(abs, +, Int8[])) === - typeof(mapreduce(abs, +, Int8[10])) === - typeof(mapreduce(abs, +, Int8[10, 11])) === - typeof(mapreduce(abs, +, Int8[10, 11, 12, 13])) -@test typeof(mapreduce(abs, +, Float32[])) === - typeof(mapreduce(abs, +, Float32[10])) === - typeof(mapreduce(abs, +, Float32[10, 11])) === - typeof(mapreduce(abs, +, Float32[10, 11, 12, 13])) - -# sum - -@test sum(Int8[]) === Int32(0) -@test sum(Int[]) === Int(0) -@test sum(Float64[]) === 0.0 - -@test sum(Int8(3)) === Int8(3) -@test sum(3) === 3 -@test sum(3.0) === 3.0 - -@test sum([Int8(3)]) === Int32(3) -@test sum([3]) === 3 -@test sum([3.0]) === 3.0 - -z = reshape(1:16, (2,2,2,2)) -fz = float(z) -@test sum(z) === 136 -@test sum(fz) === 136.0 - -@test_throws ArgumentError sum(sin, Int[]) -@test sum(sin, 3) == sin(3.0) -@test sum(sin, [3]) == sin(3.0) -a = sum(sin, z) -@test a ≈ sum(sin, fz) -@test a ≈ sum(sin.(fz)) - -z = [-4, -3, 2, 5] -fz = float(z) -a = randn(32) # need >16 elements to trigger BLAS code path -b = complex.(randn(32), randn(32)) - -# check variants of summation for type-stability and other issues (#6069) -sum2(itr) = invoke(sum, Tuple{Any}, itr) -plus(x,y) = x + y -sum3(A) = reduce(plus, A) -sum4(itr) = invoke(reduce, Tuple{Function, Any}, plus, itr) -sum5(A) = reduce(plus, 0, A) -sum6(itr) = invoke(reduce, Tuple{Function, Int, Any}, plus, 0, itr) -sum7(A) = mapreduce(x->x, plus, A) -sum8(itr) = invoke(mapreduce, Tuple{Function, Function, Any}, x->x, plus, itr) -sum9(A) = mapreduce(x->x, plus, 0, A) -sum10(itr) = invoke(mapreduce, Tuple{Function, Function, Int, Any}, x->x,plus,0,itr) -for f in (sum2, sum5, sum6, sum9, sum10) - @test sum(z) == f(z) - @test sum(Int[]) == f(Int[]) == 0 - @test sum(Int[7]) == f(Int[7]) == 7 - @test typeof(f(Int8[])) == typeof(f(Int8[1])) == typeof(f(Int8[1 7])) -end -for f in (sum3, sum4, sum7, sum8) - @test sum(z) == f(z) - @test_throws ArgumentError f(Int[]) - @test sum(Int[7]) == f(Int[7]) == 7 -end -@test typeof(sum(Int8[])) == typeof(sum(Int8[1])) == typeof(sum(Int8[1 7])) - -@test sum_kbn([1,1e100,1,-1e100]) === 2.0 -@test sum_kbn(Float64[]) === 0.0 -@test sum_kbn(i for i=1.0:1.0:10.0) === 55.0 -@test sum_kbn(i for i=1:1:10) === 55 -@test sum_kbn([1 2 3]) === 6 -@test sum_kbn([2+im 3-im]) === 5+0im -@test sum_kbn([1+im 2+3im]) === 3+4im -@test sum_kbn([7 8 9]) === sum_kbn([8 9 7]) -@test sum_kbn(i for i=1:1:10) === sum_kbn(i for i=10:-1:1) -@test sum_kbn([-0.0]) === -0.0 -@test sum_kbn([-0.0,-0.0]) === -0.0 - -# prod - -@test prod(Int[]) === 1 -@test prod(Int8[]) === Int32(1) -@test prod(Float64[]) === 1.0 - -@test prod([3]) === 3 -@test prod([Int8(3)]) === Int32(3) -@test prod([3.0]) === 3.0 - -@test prod(z) === 120 -@test prod(fz) === 120.0 - -@test prod(1:big(16)) == big(20922789888000) -@test prod(big(typemax(Int64)):big(typemax(Int64))+16) == parse(BigInt,"25300281663413827620486300433089141956148633919452440329174083959168114253708467653081909888307573358090001734956158476311046124934597861626299416732205795533726326734482449215730132757595422510465791525610410023802664753402501982524443370512346073948799084936298007821432734720004795146875180123558814648586972474376192000") - -@test typeof(prod(Array(trues(10)))) == Bool - -# check type-stability -prod2(itr) = invoke(prod, Tuple{Any}, itr) -@test prod(Int[]) === prod2(Int[]) === 1 -@test prod(Int[7]) === prod2(Int[7]) === 7 -@test typeof(prod(Int8[])) == typeof(prod(Int8[1])) == typeof(prod(Int8[1, 7])) == Int32 -@test typeof(prod2(Int8[])) == typeof(prod2(Int8[1])) == typeof(prod2(Int8[1 7])) == Int32 - -# maximum & minimum & extrema - -@test_throws ArgumentError maximum(Int[]) -@test_throws ArgumentError minimum(Int[]) - -@test maximum(5) == 5 -@test minimum(5) == 5 -@test extrema(5) == (5, 5) - -@test maximum([4, 3, 5, 2]) == 5 -@test minimum([4, 3, 5, 2]) == 2 -@test extrema([4, 3, 5, 2]) == (2, 5) - -@test isnan(maximum([NaN])) -@test isnan(minimum([NaN])) -@test isequal(extrema([NaN]), (NaN, NaN)) - -@test isnan(maximum([NaN, 2.])) -@test isnan(minimum([NaN, 2.])) -@test isequal(extrema([NaN, 2.]), (NaN,NaN)) - -@test isnan(maximum([NaN, 2., 3.])) -@test isnan(minimum([NaN, 2., 3.])) -@test isequal(extrema([NaN, 2., 3.]), (NaN,NaN)) - -@test isnan(maximum([4., 3., NaN, 5., 2.])) -@test isnan(minimum([4., 3., NaN, 5., 2.])) -@test isequal(extrema([4., 3., NaN, 5., 2.]), (NaN,NaN)) - - # test long arrays -@test isnan(maximum([NaN; 1.:10000.])) -@test isnan(maximum([1.:10000.; NaN])) -@test isnan(minimum([NaN; 1.:10000.])) -@test isnan(minimum([1.:10000.; NaN])) -@test isequal(extrema([1.:10000.; NaN]), (NaN,NaN)) -@test isequal(extrema([NaN; 1.:10000.]), (NaN,NaN)) - -@test maximum(abs2, 3:7) == 49 -@test minimum(abs2, 3:7) == 9 - -@test maximum(Int16[1]) === Int16(1) -@test maximum(collect(Int16(1):Int16(100))) === Int16(100) -@test maximum(Int32[1,2]) === Int32(2) - -A = circshift(reshape(1:24,2,3,4), (0,1,1)) -@test extrema(A,1) == reshape([(23,24),(19,20),(21,22),(5,6),(1,2),(3,4),(11,12),(7,8),(9,10),(17,18),(13,14),(15,16)],1,3,4) -@test extrema(A,2) == reshape([(19,23),(20,24),(1,5),(2,6),(7,11),(8,12),(13,17),(14,18)],2,1,4) -@test extrema(A,3) == reshape([(5,23),(6,24),(1,19),(2,20),(3,21),(4,22)],2,3,1) -@test extrema(A,(1,2)) == reshape([(19,24),(1,6),(7,12),(13,18)],1,1,4) -@test extrema(A,(1,3)) == reshape([(5,24),(1,20),(3,22)],1,3,1) -@test extrema(A,(2,3)) == reshape([(1,23),(2,24)],2,1,1) -@test extrema(A,(1,2,3)) == reshape([(1,24)],1,1,1) -@test size(extrema(A,1)) == size(maximum(A,1)) -@test size(extrema(A,(1,2))) == size(maximum(A,(1,2))) -@test size(extrema(A,(1,2,3))) == size(maximum(A,(1,2,3))) - -# any & all - -@test any([]) == false -@test any(Bool[]) == false -@test any([true]) == true -@test any([false, false]) == false -@test any([false, true]) == true -@test any([true, false]) == true -@test any([true, true]) == true -@test any([true, true, true]) == true -@test any([true, false, true]) == true -@test any([false, false, false]) == false - -@test all([]) == true -@test all(Bool[]) == true -@test all([true]) == true -@test all([false, false]) == false -@test all([false, true]) == false -@test all([true, false]) == false -@test all([true, true]) == true -@test all([true, true, true]) == true -@test all([true, false, true]) == false -@test all([false, false, false]) == false - -@test any(x->x>0, []) == false -@test any(x->x>0, Int[]) == false -@test any(x->x>0, [-3]) == false -@test any(x->x>0, [4]) == true -@test any(x->x>0, [-3, 4, 5]) == true - -@test all(x->x>0, []) == true -@test all(x->x>0, Int[]) == true -@test all(x->x>0, [-3]) == false -@test all(x->x>0, [4]) == true -@test all(x->x>0, [-3, 4, 5]) == false - -@test reduce((a, b) -> a .| b, fill(trues(5), 24)) == trues(5) -@test reduce((a, b) -> a .| b, fill(falses(5), 24)) == falses(5) -@test reduce((a, b) -> a .& b, fill(trues(5), 24)) == trues(5) -@test reduce((a, b) -> a .& b, fill(falses(5), 24)) == falses(5) - -@test_throws TypeError any(x->0, [false]) -@test_throws TypeError all(x->0, [false]) - -# short-circuiting any and all - -let c = [0, 0], A = 1:1000 - any(x->(c[1]=x; x==10), A) - all(x->(c[2]=x; x!=10), A) - - @test c == [10,10] -end - -# 19151 - always short circuit -let c = Int[], d = Int[], A = 1:9 - all((push!(c, x); x < 5) for x in A) - @test c == collect(1:5) - - any((push!(d, x); x > 4) for x in A) - @test d == collect(1:5) -end - -# any/all with non-boolean collections - -let f(x) = x == 1 ? true : x == 2 ? false : 1 - @test any(Any[false,true,false]) - @test any(map(f, [2,1,2])) - @test any([f(x) for x in [2,1,2]]) - - @test all(Any[true,true,true]) - @test all(map(f, [1,1,1])) - @test all([f(x) for x in [1,1,1]]) - - @test_throws TypeError any([1,true]) - @test_throws TypeError all([true,1]) - @test_throws TypeError any(map(f,[3,1])) - @test_throws TypeError all(map(f,[1,3])) -end - -# any and all with functors - -struct SomeFunctor end -(::SomeFunctor)(x) = true - -@test any(SomeFunctor(), 1:10) -@test all(SomeFunctor(), 1:10) - - -# in - -@test in(1, Int[]) == false -@test in(1, Int[1]) == true -@test in(1, Int[2]) == false -@test in(0, 1:3) == false -@test in(1, 1:3) == true -@test in(2, 1:3) == true - -# contains - -@test contains("quick fox", "fox") == true -@test contains("quick fox", "lazy dog") == false - -# count & countnz - -@test count(x->x>0, Int[]) == count(Bool[]) == 0 -@test count(x->x>0, -3:5) == count((-3:5) .> 0) == 5 -@test count([true, true, false, true]) == count(BitVector([true, true, false, true])) == 3 -@test_throws TypeError count(sqrt, [1]) -@test_throws TypeError count([1]) -let itr = (x for x in 1:10 if x < 7) - @test count(iseven, itr) == 3 - @test_throws TypeError count(itr) - @test_throws TypeError count(sqrt, itr) -end -@test count(iseven(x) for x in 1:10 if x < 7) == 3 -@test count(iseven(x) for x in 1:10 if x < -7) == 0 - -@test countnz(Int[]) == 0 -@test countnz(Int[0]) == 0 -@test countnz(Int[1]) == 1 -@test countnz([1, 0, 2, 0, 3, 0, 4]) == 4 - - -## cumsum, cummin, cummax - -z = rand(10^6) -let es = sum_kbn(z), es2 = sum_kbn(z[1:10^5]) - @test (es - sum(z)) < es * 1e-13 - cs = cumsum(z) - @test (es - cs[end]) < es * 1e-13 - @test (es2 - cs[10^5]) < es2 * 1e-13 -end - - -@test sum(collect(map(UInt8,0:255))) == 32640 -@test sum(collect(map(UInt8,254:255))) == 509 - -A = reshape(map(UInt8, 101:109), (3,3)) -@test @inferred(sum(A)) == 945 -@test @inferred(sum(view(A, 1:3, 1:3))) == 945 - -A = reshape(map(UInt8, 1:100), (10,10)) -@test @inferred(sum(A)) == 5050 -@test @inferred(sum(view(A, 1:10, 1:10))) == 5050 - -# issue #11618 -@test sum([-0.0]) === -0.0 -@test sum([-0.0, -0.0]) === -0.0 -@test prod([-0.0, -0.0]) === 0.0 - -#contains -let A = collect(1:10) - @test A ∋ 5 - @test A ∌ 11 - @test contains(==,A,6) -end - -# issue #18695 -test18695(r) = sum( t^2 for t in r ) -@test @inferred(test18695([1.0,2.0,3.0,4.0])) == 30.0 -@test_throws ArgumentError test18695(Any[]) - -# issue #21107 -@test foldr(-,2:2) == 2 diff --git a/julia-0.6.3/share/julia/test/reducedim.jl b/julia-0.6.3/share/julia/test/reducedim.jl deleted file mode 100644 index 4da3439..0000000 --- a/julia-0.6.3/share/julia/test/reducedim.jl +++ /dev/null @@ -1,156 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -# main tests - -function safe_mapslices(op, A, region) - newregion = intersect(region, 1:ndims(A)) - return isempty(newregion) ? A : mapslices(op, A, newregion) -end -safe_sum{T}(A::Array{T}, region) = safe_mapslices(sum, A, region) -safe_prod{T}(A::Array{T}, region) = safe_mapslices(prod, A, region) -safe_maximum{T}(A::Array{T}, region) = safe_mapslices(maximum, A, region) -safe_minimum{T}(A::Array{T}, region) = safe_mapslices(minimum, A, region) -safe_sumabs{T}(A::Array{T}, region) = safe_mapslices(sum, abs.(A), region) -safe_sumabs2{T}(A::Array{T}, region) = safe_mapslices(sum, abs2.(A), region) -safe_maxabs{T}(A::Array{T}, region) = safe_mapslices(maximum, abs.(A), region) -safe_minabs{T}(A::Array{T}, region) = safe_mapslices(minimum, abs.(A), region) - -Areduc = rand(3, 4, 5, 6) -for region in Any[ - 1, 2, 3, 4, 5, (1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4), - (1, 2, 3), (1, 3, 4), (2, 3, 4), (1, 2, 3, 4)] - # println("region = $region") - r = fill(NaN, map(length, Base.reduced_indices(indices(Areduc), region))) - @test sum!(r, Areduc) ≈ safe_sum(Areduc, region) - @test prod!(r, Areduc) ≈ safe_prod(Areduc, region) - @test maximum!(r, Areduc) ≈ safe_maximum(Areduc, region) - @test minimum!(r, Areduc) ≈ safe_minimum(Areduc, region) - @test sum!(abs, r, Areduc) ≈ safe_sumabs(Areduc, region) - @test sum!(abs2, r, Areduc) ≈ safe_sumabs2(Areduc, region) - @test maximum!(abs, r, Areduc) ≈ safe_maxabs(Areduc, region) - @test minimum!(abs, r, Areduc) ≈ safe_minabs(Areduc, region) - - # With init=false - r2 = similar(r) - fill!(r, 1) - @test sum!(r, Areduc, init=false) ≈ safe_sum(Areduc, region)+1 - fill!(r, 2.2) - @test prod!(r, Areduc, init=false) ≈ safe_prod(Areduc, region)*2.2 - fill!(r, 1.8) - @test maximum!(r, Areduc, init=false) ≈ fill!(r2, 1.8) - fill!(r, -0.2) - @test minimum!(r, Areduc, init=false) ≈ fill!(r2, -0.2) - fill!(r, 8.1) - @test sum!(abs, r, Areduc, init=false) ≈ safe_sumabs(Areduc, region)+8.1 - fill!(r, 8.1) - @test sum!(abs2, r, Areduc, init=false) ≈ safe_sumabs2(Areduc, region)+8.1 - fill!(r, 1.5) - @test maximum!(abs, r, Areduc, init=false) ≈ fill!(r2, 1.5) - fill!(r, -1.5) - @test minimum!(abs, r, Areduc, init=false) ≈ fill!(r2, -1.5) - - @test sum(Areduc, region) ≈ safe_sum(Areduc, region) - @test prod(Areduc, region) ≈ safe_prod(Areduc, region) - @test maximum(Areduc, region) ≈ safe_maximum(Areduc, region) - @test minimum(Areduc, region) ≈ safe_minimum(Areduc, region) - @test sum(abs, Areduc, region) ≈ safe_sumabs(Areduc, region) - @test sum(abs2, Areduc, region) ≈ safe_sumabs2(Areduc, region) - @test maximum(abs, Areduc, region) ≈ safe_maxabs(Areduc, region) - @test minimum(abs, Areduc, region) ≈ safe_minabs(Areduc, region) -end - -# Test reduction along first dimension; this is special-cased for -# size(A, 1) >= 16 -Breduc = rand(64, 3) -r = fill(NaN, map(length, Base.reduced_indices(indices(Breduc), 1))) -@test sum!(r, Breduc) ≈ safe_sum(Breduc, 1) -@test sum!(abs, r, Breduc) ≈ safe_sumabs(Breduc, 1) -@test sum!(abs2, r, Breduc) ≈ safe_sumabs2(Breduc, 1) -@test sum(Breduc, 1) ≈ safe_sum(Breduc, 1) -@test sum(abs, Breduc, 1) ≈ safe_sumabs(Breduc, 1) -@test sum(abs2, Breduc, 1) ≈ safe_sumabs2(Breduc, 1) - -fill!(r, 4.2) -@test sum!(r, Breduc, init=false) ≈ safe_sum(Breduc, 1)+4.2 -fill!(r, -6.3) -@test sum!(abs, r, Breduc, init=false) ≈ safe_sumabs(Breduc, 1)-6.3 -fill!(r, -1.1) -@test sum!(abs2, r, Breduc, init=false) ≈ safe_sumabs2(Breduc, 1)-1.1 - -# Small arrays with init=false -A = reshape(1:15, 3, 5) -R = ones(Int, 3) -@test sum!(R, A, init=false) == [36,41,46] -R = ones(Int, 1, 5) -@test sum!(R, A, init=false) == [7 16 25 34 43] -R = [2] -A = reshape(1:6, 3, 2) -@test prod!(R, A, init=false) == [1440] - -# Small integers -@test @inferred(sum(Int8[1], 1)) == [1] -@test @inferred(sum(UInt8[1], 1)) == [1] - -# Complex types -@test typeof(@inferred(sum([1.0+1.0im], 1))) == Vector{Complex128} -@test typeof(@inferred(Base.sum(abs, [1.0+1.0im], 1))) == Vector{Float64} -@test typeof(@inferred(Base.sum(abs2, [1.0+1.0im], 1))) == Vector{Float64} -@test typeof(@inferred(prod([1.0+1.0im], 1))) == Vector{Complex128} -@test typeof(@inferred(Base.prod(abs, [1.0+1.0im], 1))) == Vector{Float64} -@test typeof(@inferred(Base.prod(abs2, [1.0+1.0im], 1))) == Vector{Float64} - -# min/max -@test reducedim(max, A, 1) == [3 6] -@test reducedim(min, A, 2) == reshape([1,2,3], 3, 1) - -# Heterogeneously typed arrays -@test sum(Union{Float32, Float64}[1.0], 1) == [1.0] -@test prod(Union{Float32, Float64}[1.0], 1) == [1.0] - -@test reducedim((a,b) -> a|b, [true false; false false], 1, false) == [true false] -R = reducedim((a,b) -> a+b, [1 2; 3 4], 2, 0.0) -@test eltype(R) == Float64 -@test R ≈ [3,7] -@test reducedim((a,b) -> a+b, [1 2; 3 4], 1, 0) == [4 6] - -# inferred return types -rt = Base.return_types(reducedim, Tuple{Function, Array{Float64, 3}, Int, Float64}) -@test length(rt) == 1 && rt[1] == Array{Float64, 3} - - -## findmin/findmax -A = [1.0 3.0 6.0; - 5.0 2.0 4.0] -for (tup, rval, rind) in [((1,), [1.0 2.0 4.0], [1 4 6]), - ((2,), reshape([1.0,2.0], 2, 1), reshape([1,4], 2, 1)), - ((1,2), fill(1.0,1,1),fill(1,1,1))] - @test findmin(A, tup) == (rval, rind) - @test findmin!(similar(rval), similar(rind), A) == (rval, rind) -end - -for (tup, rval, rind) in [((1,), [5.0 3.0 6.0], [2 3 5]), - ((2,), reshape([6.0,5.0], 2, 1), reshape([5,2], 2, 1)), - ((1,2), fill(6.0,1,1),fill(5,1,1))] - @test findmax(A, tup) == (rval, rind) - @test findmax!(similar(rval), similar(rind), A) == (rval, rind) -end - -# issue #6672 -@test sum(Real[1 2 3; 4 5.3 7.1], 2) == reshape([6, 16.4], 2, 1) -@test std(AbstractFloat[1,2,3], 1) == [1.0] -@test sum(Any[1 2;3 4],1) == [4 6] -@test sum(Vector{Int}[[1,2],[4,3]], 1)[1] == [5,5] - -# issue #10461 -Areduc = rand(3, 4, 5, 6) -for region in Any[-1, 0, (-1, 2), [0, 1], (1,-2,3), [0 1; - 2 3], "hello"] - @test_throws ArgumentError sum(Areduc, region) - @test_throws ArgumentError prod(Areduc, region) - @test_throws ArgumentError maximum(Areduc, region) - @test_throws ArgumentError minimum(Areduc, region) - @test_throws ArgumentError sum(abs, Areduc, region) - @test_throws ArgumentError sum(abs2, Areduc, region) - @test_throws ArgumentError maximum(abs, Areduc, region) - @test_throws ArgumentError minimum(abs, Areduc, region) -end diff --git a/julia-0.6.3/share/julia/test/reflection.jl b/julia-0.6.3/share/julia/test/reflection.jl deleted file mode 100644 index 4af005d..0000000 --- a/julia-0.6.3/share/julia/test/reflection.jl +++ /dev/null @@ -1,653 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -# code_native / code_llvm (issue #8239) -# It's hard to really test these, but just running them should be -# sufficient to catch segfault bugs. - -module ReflectionTest -using Base.Test - -function test_ast_reflection(freflect, f, types) - @test !isempty(freflect(f, types)) - nothing -end - -function test_bin_reflection(freflect, f, types) - iob = IOBuffer() - freflect(iob, f, types) - str = String(take!(iob)) - @test !isempty(str) - nothing -end - -function test_code_reflection(freflect, f, types, tester) - tester(freflect, f, types) - tester(freflect, f, (types.parameters...)) - nothing -end - -function test_code_reflections(tester, freflect) - test_code_reflection(freflect, ismatch, - Tuple{Regex, AbstractString}, tester) # abstract type - test_code_reflection(freflect, +, Tuple{Int, Int}, tester) # leaftype signature - test_code_reflection(freflect, +, - Tuple{Array{Float32}, Array{Float32}}, tester) # incomplete types - test_code_reflection(freflect, Module, Tuple{}, tester) # Module() constructor (transforms to call) - test_code_reflection(freflect, Array{Int64}, Tuple{Array{Int32}}, tester) # with incomplete types - test_code_reflection(freflect, muladd, Tuple{Float64, Float64, Float64}, tester) -end - -test_code_reflections(test_ast_reflection, code_lowered) -test_code_reflections(test_ast_reflection, code_typed) -test_code_reflections(test_bin_reflection, code_llvm) -test_code_reflections(test_bin_reflection, code_native) - -# Issue #16326 -mktemp() do f, io - OLDSTDOUT = STDOUT - redirect_stdout(io) - @test try @code_native map(abs, rand(3)); true; catch false; end - redirect_stdout(OLDSTDOUT) - nothing -end - -end # module ReflectionTest - -# code_warntype -module WarnType -using Base.Test - -function warntype_hastag(f, types, tag) - iob = IOBuffer() - code_warntype(iob, f, types) - str = String(take!(iob)) - return !isempty(search(str, tag)) -end - -pos_stable(x) = x > 0 ? x : zero(x) -pos_unstable(x) = x > 0 ? x : 0 - -tag = Base.have_color ? Base.error_color() : "UNION" -@test warntype_hastag(pos_unstable, Tuple{Float64}, tag) -@test !warntype_hastag(pos_stable, Tuple{Float64}, tag) - -mutable struct Stable{T,N} - A::Array{T,N} -end -mutable struct Unstable{T} - A::Array{T} -end -Base.getindex(A::Stable, i) = A.A[i] -Base.getindex(A::Unstable, i) = A.A[i] - -tag = Base.have_color ? Base.error_color() : "ARRAY{FLOAT64,N}" -@test warntype_hastag(getindex, Tuple{Unstable{Float64},Int}, tag) -@test !warntype_hastag(getindex, Tuple{Stable{Float64,2},Int}, tag) -@test warntype_hastag(getindex, Tuple{Stable{Float64},Int}, tag) - -# Make sure emphasis is not used for other functions -tag = Base.have_color ? Base.error_color() : "ANY" -iob = IOBuffer() -show(iob, expand(:(x->x^2))) -str = String(take!(iob)) -@test isempty(search(str, tag)) - -# Make sure non used variables are not emphasized -has_unused() = (a = rand(5)) -@test !warntype_hastag(has_unused, Tuple{}, tag) -@test warntype_hastag(has_unused, Tuple{}, "<optimized out>") - -module ImportIntrinsics15819 -# Make sure changing the lookup path of an intrinsic doesn't break -# the heuristic for type instability warning. -import Core.Intrinsics: sqrt_llvm, bitcast -# Use import -sqrt15819(x::Float64) = bitcast(Float64, sqrt_llvm(x)) -# Use fully qualified name -sqrt15819(x::Float32) = bitcast(Float32, Core.Intrinsics.sqrt_llvm(x)) -end -foo11122(x) = @fastmath x - 1.0 - -# issue #11122, #13568 and #15819 -@test !warntype_hastag(+, Tuple{Int,Int}, tag) -@test !warntype_hastag(-, Tuple{Int,Int}, tag) -@test !warntype_hastag(*, Tuple{Int,Int}, tag) -@test !warntype_hastag(/, Tuple{Int,Int}, tag) -@test !warntype_hastag(foo11122, Tuple{Float32}, tag) -@test !warntype_hastag(foo11122, Tuple{Float64}, tag) -@test !warntype_hastag(foo11122, Tuple{Int}, tag) -@test !warntype_hastag(sqrt, Tuple{Int}, tag) -@test !warntype_hastag(sqrt, Tuple{Float64}, tag) -@test !warntype_hastag(^, Tuple{Float64,Int32}, tag) -@test !warntype_hastag(^, Tuple{Float32,Int32}, tag) -@test !warntype_hastag(ImportIntrinsics15819.sqrt15819, Tuple{Float64}, tag) -@test !warntype_hastag(ImportIntrinsics15819.sqrt15819, Tuple{Float32}, tag) - -end - -# isbits - -@test !isbits(Array{Int}) -@test isbits(Float32) -@test isbits(Int) -@test !isbits(AbstractString) -@test isbits(Tuple{Int, Vararg{Int, 2}}) -@test !isbits(Tuple{Int, Vararg{Int}}) -@test !isbits(Tuple{Integer, Vararg{Int, 2}}) -@test isbits(Tuple{Int, Vararg{Any, 0}}) -@test isbits(Tuple{Vararg{Any, 0}}) - -# issue #16670 -@test isleaftype(Tuple{Int, Vararg{Int, 2}}) -@test !isleaftype(Tuple{Integer, Vararg{Int, 2}}) -@test !isleaftype(Tuple{Int, Vararg{Int}}) -@test isleaftype(Type{Tuple{Integer, Vararg{Int}}}) -@test isleaftype(Type{Vector}) - -# issue #10165 -i10165(::Type) = 0 -i10165{T,n}(::Type{AbstractArray{T,n}}) = 1 -@test i10165(AbstractArray{Int,n} where n) == 0 -@test which(i10165, Tuple{Type{AbstractArray{Int,n} where n},}).sig == Tuple{typeof(i10165),Type} - -# fullname -@test fullname(Base) == (:Base,) -@test fullname(Base.Pkg) == (:Base, :Pkg) - -const a_const = 1 -not_const = 1 -@test isconst(:a_const) == true -@test isconst(Base, :pi) == true -@test isconst(:pi) == true -@test isconst(:not_const) == false -@test isconst(:is_not_defined) == false - -@test isimmutable(1) == true -@test isimmutable([]) == false - -## find bindings tests -@test ccall(:jl_get_module_of_binding, Any, (Any, Any), Base, :sin)==Base - -# For curmod_* -include("testenv.jl") - -module TestMod7648 -using Base.Test -import Base.convert -import ..curmod_name, ..curmod -export a9475, foo9475, c7648, foo7648, foo7648_nomethods, Foo7648 - -const c7648 = 8 -d7648 = 9 -const f7648 = 10 -foo7648(x) = x -function foo7648_nomethods end -mutable struct Foo7648 end - -module TestModSub9475 - using Base.Test - using ..TestMod7648 - import ..curmod_name - export a9475, foo9475 - a9475 = 5 - b9475 = 7 - foo9475(x) = x - let - @test Base.binding_module(:a9475) == current_module() - @test Base.binding_module(:c7648) == TestMod7648 - @test Base.module_name(current_module()) == :TestModSub9475 - @test Base.fullname(current_module()) == (curmod_name..., :TestMod7648, - :TestModSub9475) - @test Base.module_parent(current_module()) == TestMod7648 - end -end # module TestModSub9475 - -using .TestModSub9475 - -let - @test Base.binding_module(:d7648) == current_module() - @test Base.binding_module(:a9475) == TestModSub9475 - @test Base.module_name(current_module()) == :TestMod7648 - @test Base.module_parent(current_module()) == curmod -end -end # module TestMod7648 - -let - @test Base.binding_module(TestMod7648, :d7648) == TestMod7648 - @test Base.binding_module(TestMod7648, :a9475) == TestMod7648.TestModSub9475 - @test Base.binding_module(TestMod7648.TestModSub9475, :b9475) == TestMod7648.TestModSub9475 - @test Set(names(TestMod7648))==Set([:TestMod7648, :a9475, :foo9475, :c7648, :foo7648, :foo7648_nomethods, :Foo7648]) - @test Set(names(TestMod7648, true)) == Set([:TestMod7648, :TestModSub9475, :a9475, :foo9475, :c7648, :d7648, :f7648, - :foo7648, Symbol("#foo7648"), :foo7648_nomethods, Symbol("#foo7648_nomethods"), - :Foo7648, :eval, Symbol("#eval")]) - @test Set(names(TestMod7648, true, true)) == Set([:TestMod7648, :TestModSub9475, :a9475, :foo9475, :c7648, :d7648, :f7648, - :foo7648, Symbol("#foo7648"), :foo7648_nomethods, Symbol("#foo7648_nomethods"), - :Foo7648, :eval, Symbol("#eval"), :convert, :curmod_name, :curmod]) - @test isconst(TestMod7648, :c7648) - @test !isconst(TestMod7648, :d7648) -end - -let - using .TestMod7648 - @test Base.binding_module(:a9475) == TestMod7648.TestModSub9475 - @test Base.binding_module(:c7648) == TestMod7648 - @test Base.function_name(foo7648) == :foo7648 - @test Base.function_module(foo7648, (Any,)) == TestMod7648 - @test Base.function_module(foo7648) == TestMod7648 - @test Base.function_module(foo7648_nomethods) == TestMod7648 - @test Base.function_module(foo9475, (Any,)) == TestMod7648.TestModSub9475 - @test Base.function_module(foo9475) == TestMod7648.TestModSub9475 - @test Base.datatype_module(Foo7648) == TestMod7648 - @test Base.datatype_name(Foo7648) == :Foo7648 - @test basename(functionloc(foo7648, (Any,))[1]) == "reflection.jl" - @test first(methods(TestMod7648.TestModSub9475.foo7648)) == @which foo7648(5) - @test TestMod7648 == @which foo7648 - @test TestMod7648.TestModSub9475 == @which a9475 -end - -@test_throws ArgumentError which(===, Tuple{Int, Int}) -@test_throws ArgumentError code_typed(===, Tuple{Int, Int}) -@test_throws ArgumentError code_llvm(===, Tuple{Int, Int}) -@test_throws ArgumentError code_native(===, Tuple{Int, Int}) -@test_throws ArgumentError Base.return_types(===, Tuple{Int, Int}) - -module TestingExported -using Base.Test -import Base.isexported -global this_is_not_defined -export this_is_not_defined -@test_throws ErrorException which(:this_is_not_defined) -@test_throws ErrorException @which this_is_not_defined -@test_throws ErrorException which(:this_is_not_exported) -@test isexported(current_module(), :this_is_not_defined) -@test !isexported(current_module(), :this_is_not_exported) -const a_value = 1 -@test which(:a_value) == current_module() -@test !isexported(current_module(), :a_value) -end - -# issue #13264 -@test isa((@which vcat(1...)), Method) - -# issue #13464 -let t13464 = "hey there sailor" - try - @which t13464[1,1] = (1.0,true) - error("unexpected") - catch err13464 - @test startswith(err13464.msg, "expression is not a function call, or is too complex") - end -end - -# PR 13825 -let ex = :(a + b) - @test string(ex) == "a + b" - ex.typ = Integer - @test string(ex) == "(a + b)::Integer" -end -foo13825{T, N}(::Array{T,N}, ::Array, ::Vector) = nothing -@test startswith(string(first(methods(foo13825))), - "foo13825(::Array{T,N}, ::Array, ::Array{T,1} where T)") - -mutable struct TLayout - x::Int8 - y::Int16 - z::Int32 -end -tlayout = TLayout(5,7,11) -@test fieldnames(tlayout) == fieldnames(TLayout) == [:x, :y, :z] -@test [(fieldoffset(TLayout,i), fieldname(TLayout,i), fieldtype(TLayout,i)) for i = 1:nfields(TLayout)] == - [(0, :x, Int8), (2, :y, Int16), (4, :z, Int32)] -@test_throws BoundsError fieldtype(TLayout, 0) -@test_throws BoundsError fieldname(TLayout, 0) -@test_throws BoundsError fieldoffset(TLayout, 0) -@test_throws BoundsError fieldtype(TLayout, 4) -@test_throws BoundsError fieldname(TLayout, 4) -@test_throws BoundsError fieldoffset(TLayout, 4) - -@test fieldtype(Tuple{Vararg{Int8}}, 1) === Int8 -@test fieldtype(Tuple{Vararg{Int8}}, 10) === Int8 -@test_throws BoundsError fieldtype(Tuple{Vararg{Int8}}, 0) - -@test fieldnames((1,2,3)) == fieldnames(NTuple{3, Int}) == [fieldname(NTuple{3, Int}, i) for i = 1:3] == [1, 2, 3] -@test_throws BoundsError fieldname(NTuple{3, Int}, 0) -@test_throws BoundsError fieldname(NTuple{3, Int}, 4) - -import Base: isstructtype, type_alignment, return_types -@test !isstructtype(Union{}) -@test !isstructtype(Union{Int,Float64}) -@test !isstructtype(Int) -@test isstructtype(TLayout) -@test type_alignment(UInt16) == 2 -@test type_alignment(TLayout) == 4 -let rts = return_types(TLayout) - @test length(rts) >= 3 # general constructor, specific constructor, and call-to-convert adapter(s) - @test all(rts .== TLayout) -end - -# issue #15447 -@noinline function f15447(s, a) - if s - return a - else - nb = 0 - return nb - end -end -@test functionloc(f15447)[2] > 0 - -# issue #14346 -@noinline function f14346(id, mask, limit) - if id <= limit && mask[id] - return true - end -end -@test functionloc(f14346)[2] == @__LINE__-4 - -# test jl_get_llvm_fptr. We test functions both in and definitely not in the system image -definitely_not_in_sysimg() = nothing -for (f, t) in Any[(definitely_not_in_sysimg, Tuple{}), - (Base.:+, Tuple{Int, Int})] - meth = which(f, t) - tt = Tuple{typeof(f), t.parameters...} - env = (ccall(:jl_match_method, Any, (Any, Any), tt, meth.sig))[2] - world = typemax(UInt) - linfo = ccall(:jl_specializations_get_linfo, Ref{Core.MethodInstance}, (Any, Any, Any, UInt), meth, tt, env, world) - params = Base.CodegenParams() - llvmf = ccall(:jl_get_llvmf_decl, Ptr{Void}, (Any, UInt, Bool, Base.CodegenParams), linfo::Core.MethodInstance, world, true, params) - @test llvmf != C_NULL - @test ccall(:jl_get_llvm_fptr, Ptr{Void}, (Ptr{Void},), llvmf) != C_NULL -end - -module MacroTest -export @macrotest -macro macrotest(x::Int, y::Symbol) end -macro macrotest(x::Int, y::Int) - nothing #This is here because of #15280 -end -end - -let - using .MacroTest - a = 1 - m = getfield(current_module(), Symbol("@macrotest")) - @test which(m, Tuple{Int,Symbol})==@which @macrotest 1 a - @test which(m, Tuple{Int,Int})==@which @macrotest 1 1 - - @test first(methods(m,Tuple{Int, Int}))==@which MacroTest.@macrotest 1 1 - @test functionloc(@which @macrotest 1 1) == @functionloc @macrotest 1 1 -end - -# issue #15714 -# show variable names for slots and suppress spurious type warnings -function f15714(array_var15714) - for index_var15714 in eachindex(array_var15714) - array_var15714[index_var15714] += 0 - end -end - -function g15714(array_var15714) - for index_var15714 in eachindex(array_var15714) - array_var15714[index_var15714] += 0 - end - for index_var15714 in eachindex(array_var15714) - array_var15714[index_var15714] += 0 - end -end - -used_dup_var_tested15714 = false -used_unique_var_tested15714 = false -function test_typed_ast_printing(f::ANY, types::ANY, must_used_vars) - src, rettype = code_typed(f, types)[1] - dupnames = Set() - slotnames = Set() - for name in src.slotnames - if name in slotnames - push!(dupnames, name) - else - push!(slotnames, name) - end - end - # Make sure must_used_vars are in slotnames - for name in must_used_vars - @test name in slotnames - end - for str in (sprint(code_warntype, f, types), - stringmime("text/plain", src)) - for var in must_used_vars - @test contains(str, string(var)) - end - @test !contains(str, "Any") - @test !contains(str, "ANY") - # Check that we are not printing the bare slot numbers - for i in 1:length(src.slotnames) - name = src.slotnames[i] - if name in dupnames - @test contains(str, "_$i") - if name in must_used_vars - global used_dup_var_tested15714 = true - end - else - @test !contains(str, "_$i") - if name in must_used_vars - global used_unique_var_tested15714 = true - end - end - end - end - # Make sure printing an AST outside CodeInfo still works. - str = sprint(show, src.code) - # Check that we are printing the slot numbers when we don't have the context - # Use the variable names that we know should be present in the optimized AST - for i in 2:length(src.slotnames) - name = src.slotnames[i] - if name in must_used_vars - @test contains(str, "_$i") - end - end -end -test_typed_ast_printing(f15714, Tuple{Vector{Float32}}, - [:array_var15714, :index_var15714]) -test_typed_ast_printing(g15714, Tuple{Vector{Float32}}, - [:array_var15714, :index_var15714]) -@test used_dup_var_tested15714 -@test used_unique_var_tested15714 - -let li = typeof(getfield).name.mt.cache.func::Core.MethodInstance, - lrepr = string(li), - mrepr = string(li.def), - lmime = stringmime("text/plain", li), - mmime = stringmime("text/plain", li.def) - - @test lrepr == lmime == "MethodInstance for getfield(...)" - @test mrepr == mmime == "getfield(...) in Core" -end - - -# Linfo Tracing test -tracefoo(x, y) = x+y -didtrace = false -tracer(x::Ptr{Void}) = (@test isa(unsafe_pointer_to_objref(x), Core.MethodInstance); global didtrace = true; nothing) -ccall(:jl_register_method_tracer, Void, (Ptr{Void},), cfunction(tracer, Void, (Ptr{Void},))) -meth = which(tracefoo,Tuple{Any,Any}) -ccall(:jl_trace_method, Void, (Any,), meth) -@test tracefoo(1, 2) == 3 -ccall(:jl_untrace_method, Void, (Any,), meth) -@test didtrace -didtrace = false -@test tracefoo(1.0, 2.0) == 3.0 -@test !didtrace -ccall(:jl_register_method_tracer, Void, (Ptr{Void},), C_NULL) - -# Method Tracing test -methtracer(x::Ptr{Void}) = (@test isa(unsafe_pointer_to_objref(x), Method); global didtrace = true; nothing) -ccall(:jl_register_newmeth_tracer, Void, (Ptr{Void},), cfunction(methtracer, Void, (Ptr{Void},))) -tracefoo2(x, y) = x*y -@test didtrace -didtrace = false -tracefoo(x::Int64, y::Int64) = x*y -@test didtrace -didtrace = false -ccall(:jl_register_newmeth_tracer, Void, (Ptr{Void},), C_NULL) - -# test for reflection over large method tables -for i = 1:100; @eval fLargeTable(::Val{$i}, ::Any) = 1; end -for i = 1:100; @eval fLargeTable(::Any, ::Val{$i}) = 2; end -fLargeTable(::Any...) = 3 -@test length(methods(fLargeTable, Tuple{})) == 1 -fLargeTable(::Complex, ::Complex) = 4 -fLargeTable(::Union{Complex64, Complex128}...) = 5 -@test length(methods(fLargeTable, Tuple{})) == 1 -fLargeTable() = 4 -@test length(methods(fLargeTable)) == 204 -@test length(methods(fLargeTable, Tuple{})) == 1 -@test fLargeTable(1im, 2im) == 4 -@test fLargeTable(1.0im, 2.0im) == 5 -@test_throws MethodError fLargeTable(Val{1}(), Val{1}()) -@test fLargeTable(Val{1}(), 1) == 1 -@test fLargeTable(1, Val{1}()) == 2 - -# issue #15280 -function f15280(x) end -@test functionloc(f15280)[2] > 0 - -# bug found in #16850, Base.url with backslashes on Windows -function module_depth(from::Module, to::Module) - if from === to - return 0 - else - return 1 + module_depth(from, module_parent(to)) - end -end -function has_backslashes(mod::Module) - for n in names(mod, true, true) - isdefined(mod, n) || continue - Base.isdeprecated(mod, n) && continue - f = getfield(mod, n) - if isa(f, Module) && module_depth(Main, f) <= module_depth(Main, mod) - continue - end - h = has_backslashes(f) - isnull(h) || return h - end - return Nullable{Method}() -end -function has_backslashes(f::Function) - for m in methods(f) - h = has_backslashes(m) - isnull(h) || return h - end - return Nullable{Method}() -end -function has_backslashes(meth::Method) - if '\\' in string(meth.file) - return Nullable{Method}(meth) - else - return Nullable{Method}() - end -end -has_backslashes(x) = Nullable{Method}() -h16850 = has_backslashes(Base) -if is_windows() - if isnull(h16850) - warn("No methods found in Base with backslashes in file name, ", - "skipping test for Base.url") - else - @test !('\\' in Base.url(get(h16850))) - end -else - @test isnull(h16850) -end - -# Adds test for PR #17636 -let a = @code_typed 1 + 1 - b = @code_lowered 1 + 1 - @test isa(a, Pair{CodeInfo, DataType}) - @test isa(b, CodeInfo) - @test isa(a[1].code, Array{Any,1}) - @test isa(b.code, Array{Any,1}) - - function thing(a::Array, b::Real) - println("thing") - end - function thing(a::AbstractArray, b::Int) - println("blah") - end - @test_throws MethodError thing(rand(10), 1) - a = @code_typed thing(rand(10), 1) - b = @code_lowered thing(rand(10), 1) - @test length(a) == 0 - @test length(b) == 0 -end - -mutable struct A18434 -end -(::Type{A18434})(x; y=1) = 1 - -global counter18434 = 0 -function get_A18434() - global counter18434 - counter18434 += 1 - return A18434 -end -@which get_A18434()(1; y=2) -@test counter18434 == 1 -@which get_A18434()(1, y=2) -@test counter18434 == 2 - -# PR #18888: code_typed shouldn't cache if not optimizing -let - world = typemax(UInt) - f18888() = return nothing - m = first(methods(f18888, Tuple{})) - @test m.specializations === nothing - ft = typeof(f18888) - - code_typed(f18888, Tuple{}; optimize=false) - @test m.specializations !== nothing # uncached, but creates the specializations entry - code = Core.Inference.code_for_method(m, Tuple{ft}, Core.svec(), world, true) - @test !isdefined(code, :inferred) - - code_typed(f18888, Tuple{}; optimize=true) - code = Core.Inference.code_for_method(m, Tuple{ft}, Core.svec(), world, true) - @test isdefined(code, :inferred) -end - -# Issue #18883, code_llvm/code_native for generated functions -@generated f18883() = nothing -@test !isempty(sprint(code_llvm, f18883, Tuple{})) -@test !isempty(sprint(code_native, f18883, Tuple{})) - -# PR #19964 -@test isempty(subtypes(Float64)) - -# New reflection methods in 0.6 -struct ReflectionExample{T<:AbstractFloat, N} - x::Tuple{T, N} -end - -@test Base.isabstract(AbstractArray) -@test !Base.isabstract(ReflectionExample) -@test !Base.isabstract(Int) - -@test Base.parameter_upper_bound(ReflectionExample, 1) === AbstractFloat -@test Base.parameter_upper_bound(ReflectionExample, 2) === Any -@test Base.parameter_upper_bound(ReflectionExample{T, N} where T where N <: Real, 2) === Real - -let - wrapperT(T) = Base.typename(T).wrapper - @test @inferred wrapperT(ReflectionExample{Float64, Int64}) == ReflectionExample - @test @inferred wrapperT(ReflectionExample{Float64, N} where N) == ReflectionExample - @test @inferred wrapperT(ReflectionExample{T, Int64} where T) == ReflectionExample - @test @inferred wrapperT(ReflectionExample) == ReflectionExample - @test @inferred wrapperT(Union{ReflectionExample{Union{},1},ReflectionExample{Float64,1}}) == ReflectionExample - @test_throws ErrorException Base.typename(Union{Int, Float64}) -end - -# Issue #20086 -abstract type A20086{T,N} end -struct B20086{T,N} <: A20086{T,N} end -@test subtypes(A20086) == [B20086] -@test subtypes(A20086{Int}) == [B20086{Int}] -@test subtypes(A20086{T,3} where T) == [B20086{T,3} where T] -@test subtypes(A20086{Int,3}) == [B20086{Int,3}] diff --git a/julia-0.6.3/share/julia/test/regex.jl b/julia-0.6.3/share/julia/test/regex.jl deleted file mode 100644 index f1affea..0000000 --- a/julia-0.6.3/share/julia/test/regex.jl +++ /dev/null @@ -1,57 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -function collect_eachmatch(re, str, overlap=false) - [m.match for m in collect(eachmatch(re, str, overlap))] -end - -for f in [matchall, collect_eachmatch] - @test f(r"a?b?", "asbd") == ["a","","b","",""] == f(r"""a?b?""", "asbd") - @test f(r"a?b?", "asbd", true) == ["a","","b","",""] - @test f(r"\w+", "hello", true) == ["hello","ello","llo","lo","o"] - @test f(r".\s", "x \u2200 x \u2203 y") == ["x ", "∀ ", "x ", "∃ "] - @test f(r"(\w+)(\s*)", "The dark side of the moon") == - ["The ", "dark ", "side ", "of ", "the ", "moon"] - @test f(r"", "") == [""] - @test f(r"", "", true) == [""] - @test f(r"aa", "aaaa") == ["aa", "aa"] - @test f(r"aa", "aaaa", true) == ["aa", "aa", "aa"] - @test f(r"", "aaa") == ["", "", "", ""] - @test f(r"", "aaa", true) == ["", "", "", ""] - @test f(r"GCG","GCGCG") == ["GCG"] - @test f(r"GCG","GCGCG",true) == ["GCG","GCG"] -end - -# Issue 8278 -target = """71.163.72.113 - - [30/Jul/2014:16:40:55 -0700] "GET emptymind.org/thevacantwall/wp-content/uploads/2013/02/DSC_006421.jpg HTTP/1.1" 200 492513 "http://images.search.yahoo.com/images/view;_ylt=AwrB8py9gdlTGEwADcSjzbkF;_ylu=X3oDMTI2cGZrZTA5BHNlYwNmcC1leHAEc2xrA2V4cARvaWQDNTA3NTRiMzYzY2E5OTEwNjBiMjc2YWJhMjkxMTEzY2MEZ3BvcwM0BGl0A2Jpbmc-?back=http%3A%2F%2Fus.yhs4.search.yahoo.com%2Fyhs%2Fsearch%3Fei%3DUTF-8%26p%3Dapartheid%2Bwall%2Bin%2Bpalestine%26type%3Dgrvydef%26param1%3D1%26param2%3Dsid%253Db01676f9c26355f014f8a9db87545d61%2526b%253DChrome%2526ip%253D71.163.72.113%2526p%253Dgroovorio%2526x%253DAC811262A746D3CD%2526dt%253DS940%2526f%253D7%2526a%253Dgrv_tuto1_14_30%26hsimp%3Dyhs-fullyhosted_003%26hspart%3Dironsource&w=588&h=387&imgurl=occupiedpalestine.files.wordpress.com%2F2012%2F08%2F5-peeking-through-the-wall.jpg%3Fw%3D588%26h%3D387&rurl=http%3A%2F%2Fwww.stopdebezetting.com%2Fwereldpers%2Fcompare-the-berlin-wall-vs-israel-s-apartheid-wall-in-palestine.html&size=49.0KB&name=...+%3Cb%3EApartheid+wall+in+Palestine%3C%2Fb%3E...+%7C+Or+you+go+peeking+through+the+%3Cb%3Ewall%3C%2Fb%3E&p=apartheid+wall+in+palestine&oid=50754b363ca991060b276aba291113cc&fr2=&fr=&tt=...+%3Cb%3EApartheid+wall+in+Palestine%3C%2Fb%3E...+%7C+Or+you+go+peeking+through+the+%3Cb%3Ewall%3C%2Fb%3E&b=0&ni=21&no=4&ts=&tab=organic&sigr=13evdtqdq&sigb=19k7nsjvb&sigi=12o2la1db&sigt=12lia2m0j&sign=12lia2m0j&.crumb=.yUtKgFI6DE&hsimp=yhs-fullyhosted_003&hspart=ironsource" "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.125 Safari/537.36""" -pat = r"""([\d\.]+) ([\w.-]+) ([\w.-]+) (\[.+\]) "([^"\r\n]*|[^"\r\n\[]*\[.+\][^"]+|[^"\r\n]+.[^"]+)" (\d{3}) (\d+|-) ("(?:[^"]|\")+)"? ("(?:[^"]|\")+)"?""" -match(pat, target) - -# issue #26829 -@test map(m -> m.match, eachmatch(r"^$|\S", "ö")) == ["ö"] - -# issue #26199 -@test map(m -> m.match, eachmatch(r"(\p{L}+)", "Tú")) == ["Tú"] -@test map(m -> m.match, eachmatch(r"(\p{L}+)", "Tú lees.")) == ["Tú", "lees"] -@test map(m -> m.match, eachmatch(r"(\p{L}+)", "¿Cuál es tu pregunta?")) == ["Cuál", "es", "tu", "pregunta"] - -# Issue 9545 (32 bit) -buf = PipeBuffer() -show(buf, r"") -@test readstring(buf) == "r\"\"" - -# see #10994, #11447: PCRE2 allows NUL chars in the pattern -@test ismatch(Regex("^a\0b\$"), "a\0b") - -# regex match / search string must be a String -@test_throws ArgumentError match(r"test", GenericString("this is a test")) -@test_throws ArgumentError search(GenericString("this is a test"), r"test") - -# Named subpatterns -let m = match(r"(?<a>.)(.)(?<b>.)", "xyz") - @test (m[:a], m[2], m["b"]) == ("x", "y", "z") - @test sprint(show, m) == "RegexMatch(\"xyz\", a=\"x\", 2=\"y\", b=\"z\")" -end - -# Backcapture reference in substitution string -@test replace("abcde", r"(..)(?P<byname>d)", s"\g<byname>xy\\\1") == "adxy\\bce" -@test_throws ErrorException replace("a", r"(?P<x>)", s"\g<y>") diff --git a/julia-0.6.3/share/julia/test/repl.jl b/julia-0.6.3/share/julia/test/repl.jl deleted file mode 100644 index 0121873..0000000 --- a/julia-0.6.3/share/julia/test/repl.jl +++ /dev/null @@ -1,667 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -# For curmod_* -include("testenv.jl") - -# REPL tests -isdefined(Main, :TestHelpers) || @eval Main include(joinpath(dirname(@__FILE__), "TestHelpers.jl")) -using TestHelpers -import Base: REPL, LineEdit - -function fake_repl() - # Use pipes so we can easily do blocking reads - # In the future if we want we can add a test that the right object - # gets displayed by intercepting the display - stdin_read,stdin_write = (Base.PipeEndpoint(), Base.PipeEndpoint()) - stdout_read,stdout_write = (Base.PipeEndpoint(), Base.PipeEndpoint()) - stderr_read,stderr_write = (Base.PipeEndpoint(), Base.PipeEndpoint()) - Base.link_pipe(stdin_read,true,stdin_write,true) - Base.link_pipe(stdout_read,true,stdout_write,true) - Base.link_pipe(stderr_read,true,stderr_write,true) - - repl = Base.REPL.LineEditREPL(TestHelpers.FakeTerminal(stdin_read, stdout_write, stderr_write)) - stdin_write, stdout_read, stderr_read, repl -end - -# Writing ^C to the repl will cause sigint, so let's not die on that -ccall(:jl_exit_on_sigint, Void, (Cint,), 0) -# These are integration tests. If you want to unit test test e.g. completion, or -# exact LineEdit behavior, put them in the appropriate test files. -# Furthermore since we are emulating an entire terminal, there may be control characters -# in the mix. If verification needs to be done, keep it to the bare minimum. Basically -# this should make sure nothing crashes without depending on how exactly the control -# characters are being used. -if !is_windows() || Sys.windows_version() >= Sys.WINDOWS_VISTA_VER - stdin_write, stdout_read, stderr_read, repl = fake_repl() - - repl.specialdisplay = Base.REPL.REPLDisplay(repl) - repl.history_file = false - - repltask = @async begin - Base.REPL.run_repl(repl) - end - - sendrepl(cmd) = begin - write(stdin_write,"$(curmod_prefix)inc || wait($(curmod_prefix)b); r = $cmd; notify($(curmod_prefix)c); r\r") - end - - inc = false - b = Condition() - c = Condition() - sendrepl("\"Hello REPL\"") - - inc=true - begin - notify(b) - wait(c) - end - # Latex completions - write(stdin_write, "\x32\\alpha\t") - readuntil(stdout_read, "α") - # Bracketed paste in search mode - write(stdin_write, "\e[200~paste here ;)\e[201~") - # Abort search (^C) - write(stdin_write, '\x03') - # Test basic completion in main mode - write(stdin_write, "Base.REP\t") - readuntil(stdout_read, "Base.REPL") - write(stdin_write, '\x03') - write(stdin_write, "\\alpha\t") - readuntil(stdout_read,"α") - write(stdin_write, '\x03') - # Test cd feature in shell mode. We limit to 40 characters when - # calling readuntil() to suppress the warning it (currently) gives for - # long strings. - origpwd = pwd() - mktempdir() do tmpdir - write(stdin_write, ";") - readuntil(stdout_read, "shell> ") - write(stdin_write, "cd $(escape_string(tmpdir))\n") - readuntil(stdout_read, "cd $(escape_string(tmpdir))"[max(1,end-39):end]) - readuntil(stdout_read, realpath(tmpdir)[max(1,end-39):end]) - readuntil(stdout_read, "\n") - readuntil(stdout_read, "\n") - @test pwd() == realpath(tmpdir) - write(stdin_write, ";") - readuntil(stdout_read, "shell> ") - write(stdin_write, "cd -\n") - readuntil(stdout_read, origpwd[max(1,end-39):end]) - readuntil(stdout_read, "\n") - readuntil(stdout_read, "\n") - @test pwd() == origpwd - write(stdin_write, ";") - readuntil(stdout_read, "shell> ") - write(stdin_write, "cd\n") - readuntil(stdout_read, realpath(homedir())[max(1,end-39):end]) - readuntil(stdout_read, "\n") - readuntil(stdout_read, "\n") - @test pwd() == realpath(homedir()) - end - cd(origpwd) - - # issue #20482 - if !is_windows() - write(stdin_write, ";") - readuntil(stdout_read, "shell> ") - write(stdin_write, "echo hello >/dev/null\n") - let s = readuntil(stdout_read, "\n") - @test contains(s, "shell> ") # make sure we echoed the prompt - @test contains(s, "echo hello >/dev/null") # make sure we echoed the input - end - @test readuntil(stdout_read, "\n") == "\e[0m\n" - end - - # issue #20771 - let s - write(stdin_write, ";") - readuntil(stdout_read, "shell> ") - write(stdin_write, "'\n") # invalid input - s = readuntil(stdout_read, "\n") - @test contains(s, "shell> ") # check for the echo of the prompt - @test contains(s, "'") # check for the echo of the input - s = readuntil(stdout_read, "\n\n") - @test startswith(s, "\e[0mERROR: unterminated single quote\nStacktrace:\n [1] ") || - startswith(s, "\e[0m\e[1m\e[91mERROR: \e[39m\e[22m\e[91munterminated single quote\e[39m\nStacktrace:\n [1] ") - end - - # issues #22176 & #20482 - # TODO: figure out how to test this on Windows - is_windows() || let tmp = tempname() - try - write(stdin_write, ";") - readuntil(stdout_read, "shell> ") - write(stdin_write, "echo \$123 >$tmp\n") - let s = readuntil(stdout_read, "\n") - @test contains(s, "shell> ") # make sure we echoed the prompt - @test contains(s, "echo \$123 >$tmp") # make sure we echoed the input - end - @test readuntil(stdout_read, "\n") == "\e[0m\n" - @test readstring(tmp) == "123\n" - finally - rm(tmp, force=true) - end - end - - # Issue #7001 - # Test ignoring '\0' - let - write(stdin_write, "\0\n") - s = readuntil(stdout_read, "\n\n") - @test !contains(s, "invalid character") - end - - # Test that accepting a REPL result immediately shows up, not - # just on the next keystroke - write(stdin_write, "1+1\n") # populate history with a trivial input - readline(stdout_read) - write(stdin_write, "\e[A\n") - t = Timer(10) do t - isopen(t) || return - error("Stuck waiting for the repl to write `1+1`") - end - # yield make sure this got processed - readuntil(stdout_read, "1+1") - close(t) - readuntil(stdout_read, "\n\n") - - # Issue #10222 - # Test ignoring insert key in standard and prefix search modes - write(stdin_write, "\e[2h\e[2h\n") # insert (VT100-style) - @test search(readline(stdout_read), "[2h") == 0:-1 - readline(stdout_read) - write(stdin_write, "\e[2~\e[2~\n") # insert (VT220-style) - @test search(readline(stdout_read), "[2~") == 0:-1 - readline(stdout_read) - write(stdin_write, "1+1\n") # populate history with a trivial input - readline(stdout_read) - write(stdin_write, "\e[A\e[2h\n") # up arrow, insert (VT100-style) - readline(stdout_read) - readline(stdout_read) - write(stdin_write, "\e[A\e[2~\n") # up arrow, insert (VT220-style) - readline(stdout_read) - readline(stdout_read) - - # Test down arrow to go back to history - # populate history with a trivial input - - t = Timer(10) do t - isopen(t) || return - error("Stuck waiting for history test") - end - s1 = "12345678"; s2 = "23456789" - write(stdin_write, s1, '\n') - readuntil(stdout_read, s1) - write(stdin_write, s2, '\n') - readuntil(stdout_read, s2) - # Two up arrow, enter, should get back to 1 - write(stdin_write, "\e[A\e[A\n") - readuntil(stdout_read, s1) - # Now, down arrow, enter, should get us back to 2 - write(stdin_write, "\e[B\n") - readuntil(stdout_read, s2) - close(t) - - # Close REPL ^D - write(stdin_write, '\x04') - wait(repltask) -end - -function buffercontents(buf::IOBuffer) - p = position(buf) - seek(buf,0) - c = readstring(buf) - seek(buf,p) - c -end - -function AddCustomMode(repl) - # Custom REPL mode tests - foobar_mode = LineEdit.Prompt("TestΠ"; - prompt_prefix="\e[38;5;166m", - prompt_suffix=Base.text_colors[:white], - on_enter = s->true, - on_done = line->true) - - main_mode = repl.interface.modes[1] - push!(repl.interface.modes,foobar_mode) - - hp = main_mode.hist - hp.mode_mapping[:foobar] = foobar_mode - foobar_mode.hist = hp - - const foobar_keymap = Dict{Any,Any}( - '<' => function (s,args...) - if isempty(s) - if !haskey(s.mode_state,foobar_mode) - s.mode_state[foobar_mode] = LineEdit.init_state(repl.t,foobar_mode) - end - LineEdit.transition(s,foobar_mode) - else - LineEdit.edit_insert(s,'<') - end - end - ) - - search_prompt, skeymap = LineEdit.setup_search_keymap(hp) - mk = REPL.mode_keymap(main_mode) - - b = Dict{Any,Any}[skeymap, mk, LineEdit.history_keymap, LineEdit.default_keymap, LineEdit.escape_defaults] - foobar_mode.keymap_dict = LineEdit.keymap(b) - - main_mode.keymap_dict = LineEdit.keymap_merge(main_mode.keymap_dict, foobar_keymap) - foobar_mode, search_prompt -end - -# Note: since the \t character matters for the REPL file history, -# it is important not to have the """ code reindent this line, -# possibly converting \t to spaces. -fakehistory = """ -# time: 2014-06-29 20:44:29 EDT -# mode: julia -\té -# time: 2014-06-29 21:44:29 EDT -# mode: julia -\téé -# time: 2014-06-30 17:32:49 EDT -# mode: julia -\tshell -# time: 2014-06-30 17:32:59 EDT -# mode: shell -\tll -# time: 2014-06-30 99:99:99 EDT -# mode: julia -\tx ΔxΔ -# time: 2014-06-30 17:32:49 EDT -# mode: julia -\t1 + 1 -# time: 2014-06-30 17:35:39 EDT -# mode: foobar -\tbarfoo -# time: 2014-06-30 18:44:29 EDT -# mode: shell -\tls -# time: 2014-06-30 19:44:29 EDT -# mode: foobar -\tls -# time: 2014-06-30 20:44:29 EDT -# mode: julia -\t2 + 2 -""" - -# Test various history related issues -begin - stdin_write, stdout_read, stdout_read, repl = fake_repl() - # In the future if we want we can add a test that the right object - # gets displayed by intercepting the display - repl.specialdisplay = Base.REPL.REPLDisplay(repl) - - repl.interface = REPL.setup_interface(repl) - repl_mode = repl.interface.modes[1] - shell_mode = repl.interface.modes[2] - help_mode = repl.interface.modes[3] - histp = repl.interface.modes[4] - prefix_mode = repl.interface.modes[5] - - hp = REPL.REPLHistoryProvider(Dict{Symbol,Any}(:julia => repl_mode, - :shell => shell_mode, - :help => help_mode)) - - REPL.hist_from_file(hp, IOBuffer(fakehistory), "fakehistorypath") - REPL.history_reset_state(hp) - - histp.hp = repl_mode.hist = shell_mode.hist = help_mode.hist = hp - - # Some manual setup - s = LineEdit.init_state(repl.t, repl.interface) - LineEdit.edit_insert(s, "wip") - - # Test that navigating history skips invalid modes - # (in both directions) - LineEdit.history_prev(s, hp) - @test LineEdit.mode(s) == repl_mode - @test buffercontents(LineEdit.buffer(s)) == "2 + 2" - LineEdit.history_prev(s, hp) - @test LineEdit.mode(s) == shell_mode - @test buffercontents(LineEdit.buffer(s)) == "ls" - LineEdit.history_prev(s, hp) - @test LineEdit.mode(s) == repl_mode - @test buffercontents(LineEdit.buffer(s)) == "1 + 1" - LineEdit.history_next(s, hp) - @test LineEdit.mode(s) == shell_mode - @test buffercontents(LineEdit.buffer(s)) == "ls" - LineEdit.history_next(s, hp) - @test LineEdit.mode(s) == repl_mode - @test buffercontents(LineEdit.buffer(s)) == "2 + 2" - LineEdit.history_next(s, hp) - @test LineEdit.mode(s) == repl_mode - @test buffercontents(LineEdit.buffer(s)) == "wip" - @test position(LineEdit.buffer(s)) == 3 - LineEdit.move_line_start(s) - @test position(LineEdit.buffer(s)) == 0 - - # Test that the same holds for prefix search - ps = LineEdit.state(s, prefix_mode)::LineEdit.PrefixSearchState - @test LineEdit.input_string(ps) == "" - LineEdit.enter_prefix_search(s, prefix_mode, true) - LineEdit.history_prev_prefix(ps, hp, "") - @test ps.prefix == "" - @test ps.parent == repl_mode - @test LineEdit.input_string(ps) == "2 + 2" - @test position(LineEdit.buffer(s)) == 5 - LineEdit.history_prev_prefix(ps, hp, "") - @test ps.parent == shell_mode - @test LineEdit.input_string(ps) == "ls" - @test position(LineEdit.buffer(s)) == 2 - LineEdit.history_prev_prefix(ps, hp, "sh") - @test ps.parent == repl_mode - @test LineEdit.input_string(ps) == "shell" - @test position(LineEdit.buffer(s)) == 2 - LineEdit.history_next_prefix(ps, hp, "sh") - @test ps.parent == repl_mode - @test LineEdit.input_string(ps) == "wip" - @test position(LineEdit.buffer(s)) == 0 - LineEdit.move_input_end(s) - LineEdit.history_prev_prefix(ps, hp, "é") - @test ps.parent == repl_mode - @test LineEdit.input_string(ps) == "éé" - @test position(LineEdit.buffer(s)) == sizeof("é") > 1 - LineEdit.history_prev_prefix(ps, hp, "é") - @test ps.parent == repl_mode - @test LineEdit.input_string(ps) == "é" - @test position(LineEdit.buffer(s)) == sizeof("é") - LineEdit.history_next_prefix(ps, hp, "zzz") - @test ps.parent == repl_mode - @test LineEdit.input_string(ps) == "wip" - @test position(LineEdit.buffer(s)) == 3 - LineEdit.accept_result(s, prefix_mode) - - # Test that searching backwards puts you into the correct mode and - # skips invalid modes. - LineEdit.enter_search(s, histp, true) - ss = LineEdit.state(s, histp) - write(ss.query_buffer, "l") - LineEdit.update_display_buffer(ss, ss) - LineEdit.accept_result(s, histp) - @test LineEdit.mode(s) == shell_mode - @test buffercontents(LineEdit.buffer(s)) == "ls" - @test position(LineEdit.buffer(s)) == 0 - - # Test that searching for `ll` actually matches `ll` after - # both letters are types rather than jumping to `shell` - LineEdit.history_prev(s, hp) - LineEdit.enter_search(s, histp, true) - write(ss.query_buffer, "l") - LineEdit.update_display_buffer(ss, ss) - @test buffercontents(ss.response_buffer) == "ll" - @test position(ss.response_buffer) == 1 - write(ss.query_buffer, "l") - LineEdit.update_display_buffer(ss, ss) - LineEdit.accept_result(s, histp) - @test LineEdit.mode(s) == shell_mode - @test buffercontents(LineEdit.buffer(s)) == "ll" - @test position(LineEdit.buffer(s)) == 0 - - # Test that searching backwards with a one-letter query doesn't - # return indefinitely the same match (#9352) - LineEdit.enter_search(s, histp, true) - write(ss.query_buffer, "l") - LineEdit.update_display_buffer(ss, ss) - LineEdit.history_next_result(s, ss) - LineEdit.update_display_buffer(ss, ss) - LineEdit.accept_result(s, histp) - @test LineEdit.mode(s) == repl_mode - @test buffercontents(LineEdit.buffer(s)) == "shell" - @test position(LineEdit.buffer(s)) == 4 - - # Test that searching backwards doesn't skip matches (#9352) - # (for a search with multiple one-byte characters, or UTF-8 characters) - LineEdit.enter_search(s, histp, true) - write(ss.query_buffer, "é") # matches right-most "é" in "éé" - LineEdit.update_display_buffer(ss, ss) - @test position(ss.query_buffer) == sizeof("é") - LineEdit.history_next_result(s, ss) # matches left-most "é" in "éé" - LineEdit.update_display_buffer(ss, ss) - LineEdit.accept_result(s, histp) - @test buffercontents(LineEdit.buffer(s)) == "éé" - @test position(LineEdit.buffer(s)) == 0 - - # Issue #7551 - # Enter search mode and try accepting an empty result - REPL.history_reset_state(hp) - LineEdit.edit_clear(s) - cur_mode = LineEdit.mode(s) - LineEdit.enter_search(s, histp, true) - LineEdit.accept_result(s, histp) - @test LineEdit.mode(s) == cur_mode - @test buffercontents(LineEdit.buffer(s)) == "" - @test position(LineEdit.buffer(s)) == 0 - - # Test that new modes can be dynamically added to the REPL and will - # integrate nicely - foobar_mode, custom_histp = AddCustomMode(repl) - - # ^R l, should now find `ls` in foobar mode - LineEdit.enter_search(s, histp, true) - ss = LineEdit.state(s, histp) - write(ss.query_buffer, "l") - LineEdit.update_display_buffer(ss, ss) - LineEdit.accept_result(s, histp) - @test LineEdit.mode(s) == foobar_mode - @test buffercontents(LineEdit.buffer(s)) == "ls" - @test position(LineEdit.buffer(s)) == 0 - - # Try the same for prefix search - LineEdit.history_next(s, hp) - LineEdit.history_prev_prefix(ps, hp, "l") - @test ps.parent == foobar_mode - @test LineEdit.input_string(ps) == "ls" - @test position(LineEdit.buffer(s)) == 1 - - # Some Unicode handling testing - LineEdit.history_prev(s, hp) - LineEdit.enter_search(s, histp, true) - write(ss.query_buffer, "x") - LineEdit.update_display_buffer(ss, ss) - @test buffercontents(ss.response_buffer) == "x ΔxΔ" - @test position(ss.response_buffer) == 4 - write(ss.query_buffer, " ") - LineEdit.update_display_buffer(ss, ss) - LineEdit.accept_result(s, histp) - @test LineEdit.mode(s) == repl_mode - @test buffercontents(LineEdit.buffer(s)) == "x ΔxΔ" - @test position(LineEdit.buffer(s)) == 0 - - # Try entering search mode while in custom repl mode - LineEdit.enter_search(s, custom_histp, true) -end - -# Test removal of prompt in bracket pasting -begin - stdin_write, stdout_read, stderr_read, repl = fake_repl() - - repl.interface = REPL.setup_interface(repl) - repl_mode = repl.interface.modes[1] - shell_mode = repl.interface.modes[2] - help_mode = repl.interface.modes[3] - - repltask = @async begin - Base.REPL.run_repl(repl) - end - - c = Condition() - sendrepl2(cmd) = write(stdin_write,"$cmd\n notify($(curmod_prefix)c)\n") - - # Test removal of prefix in single statement paste - sendrepl2("\e[200~julia> A = 2\e[201~\n") - wait(c) - @test Main.A == 2 - - # Test removal of prefix in multiple statement paste - sendrepl2("""\e[200~ - julia> mutable struct T17599; a::Int; end - - julia> function foo(julia) - julia> 3 - end - - julia> A = 3\e[201~ - """) - wait(c) - @test Main.A == 3 - @test Main.foo(4) - @test Main.T17599(3).a == 3 - @test !Main.foo(2) - - sendrepl2("""\e[200~ - julia> goo(x) = x + 1 - error() - - julia> A = 4 - 4\e[201~ - """) - wait(c) - @test Main.A == 4 - @test Main.goo(4) == 5 - - # Test prefix removal only active in bracket paste mode - sendrepl2("julia = 4\n julia> 3 && (A = 1)\n") - wait(c) - @test Main.A == 1 - - # Close repl - write(stdin_write, '\x04') - wait(repltask) -end - -# Simple non-standard REPL tests -if !is_windows() || Sys.windows_version() >= Sys.WINDOWS_VISTA_VER - stdin_write, stdout_read, stdout_read, repl = fake_repl() - panel = LineEdit.Prompt("testπ"; - prompt_prefix="\e[38;5;166m", - prompt_suffix=Base.text_colors[:white], - on_enter = s->true) - - hp = REPL.REPLHistoryProvider(Dict{Symbol,Any}(:parse => panel)) - search_prompt, skeymap = LineEdit.setup_prefix_keymap(hp, panel) - REPL.history_reset_state(hp) - - panel.hist = hp - panel.keymap_dict = LineEdit.keymap(Dict{Any,Any}[skeymap, - LineEdit.default_keymap, LineEdit.escape_defaults]) - - c = Condition() - panel.on_done = (s,buf,ok)->begin - if !ok - LineEdit.transition(s,:abort) - end - line = strip(String(take!(buf))) - LineEdit.reset_state(s) - return notify(c,line) - end - - repltask = @async Base.REPL.run_interface(repl.t, LineEdit.ModalInterface([panel,search_prompt])) - - write(stdin_write,"a\n") - @test wait(c) == "a" - # Up arrow enter should recall history even at the start - write(stdin_write,"\e[A\n") - @test wait(c) == "a" - # And again - write(stdin_write,"\e[A\n") - @test wait(c) == "a" - # Close REPL ^D - write(stdin_write, '\x04') - wait(repltask) -end - -ccall(:jl_exit_on_sigint, Void, (Cint,), 1) - -let exename = Base.julia_cmd() - -# Test REPL in dumb mode -if !is_windows() - TestHelpers.with_fake_pty() do slave, master - nENV = copy(ENV) - nENV["TERM"] = "dumb" - p = spawn(setenv(`$exename --startup-file=no --quiet`,nENV),slave,slave,slave) - output = readuntil(master,"julia> ") - if ccall(:jl_running_on_valgrind,Cint,()) == 0 - # If --trace-children=yes is passed to valgrind, we will get a - # valgrind banner here, not just the prompt. - @test output == "julia> " - end - write(master,"1\nquit()\n") - - wait(p) - output = readuntil(master,' ') - @test output == "1\r\nquit()\r\n1\r\n\r\njulia> " - @test nb_available(master) == 0 - end -end - -# Test stream mode -if !is_windows() || Sys.windows_version() >= Sys.WINDOWS_VISTA_VER - outs, ins, p = readandwrite(`$exename --startup-file=no --quiet`) - write(ins,"1\nquit()\n") - @test readstring(outs) == "1\n" -end -end # let exename - -# issue #19864: -mutable struct Error19864 <: Exception; end -function test19864() - @eval current_module() Base.showerror(io::IO, e::Error19864) = print(io, "correct19864") - buf = IOBuffer() - REPL.print_response(buf, Error19864(), [], false, false, nothing) - return String(take!(buf)) -end -@test contains(test19864(), "correct19864") - -# Test containers in error messages are limited #18726 -let io = IOBuffer() - Base.display_error(io, - try - [][trues(6000)] - catch e - e - end, []) - @test length(String(take!(io))) < 1500 -end - -function test_replinit() - stdin_write, stdout_read, stdout_read, repl = fake_repl() - # Relies on implementation detail to make sure we only have the single - # replinit callback we want to test. - saved_replinit = copy(Base.repl_hooks) - slot = Ref(false) - # Create a closure from a newer world to check if `_atreplinit` - # can run it correctly - atreplinit(@eval(repl::Base.REPL.LineEditREPL->($slot[] = true))) - Base._atreplinit(repl) - @test slot[] - @test_throws MethodError Base.repl_hooks[1](repl) - copy!(Base.repl_hooks, saved_replinit) -end -test_replinit() - -let ends_with_semicolon = Base.REPL.ends_with_semicolon - @test !ends_with_semicolon("") - @test ends_with_semicolon(";") - @test !ends_with_semicolon("a") - @test ends_with_semicolon("1;") - @test ends_with_semicolon("1;\n") - @test ends_with_semicolon("1;\r") - @test ends_with_semicolon("1;\r\n \t\f") - @test ends_with_semicolon("1;#text\n") - @test ends_with_semicolon("a; #=#=# =# =#\n") - @test !ends_with_semicolon("begin\na;\nb;\nend") - @test !ends_with_semicolon("begin\na; #=#=#\n=#b=#\nend") - @test ends_with_semicolon("\na; #=#=#\n=#b=#\n# test\n#=\nfoobar\n=##bazbax\n") -end - -# PR #20794, TTYTerminal with other kinds of streams -let term = Base.Terminals.TTYTerminal("dumb",IOBuffer("1+2\n"),IOBuffer(),IOBuffer()) - r = Base.REPL.BasicREPL(term) - REPL.run_repl(r) - @test String(take!(term.out_stream)) == "julia> 3\n\njulia> \n" -end diff --git a/julia-0.6.3/share/julia/test/replcompletions.jl b/julia-0.6.3/share/julia/test/replcompletions.jl deleted file mode 100644 index 6e0d9a3..0000000 --- a/julia-0.6.3/share/julia/test/replcompletions.jl +++ /dev/null @@ -1,750 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -using Base.REPLCompletions - -ex = quote - module CompletionFoo - mutable struct Test_y - yy - end - mutable struct Test_x - xx :: Test_y - end - type_test = Test_x(Test_y(1)) - (::Test_y)() = "", "" - module CompletionFoo2 - - end - const bar = 1 - foo() = bar - macro foobar() - :() - end - - # Support non-Dict Associatives, #19441 - mutable struct CustomDict{K, V} <: Associative{K, V} - mydict::Dict{K, V} - end - - Base.keys(d::CustomDict) = collect(keys(d.mydict)) - Base.length(d::CustomDict) = length(d.mydict) - - test{T<:Real}(x::T, y::T) = pass - test(x::Real, y::Real) = pass - test{T<:Real}(x::AbstractArray{T}, y) = pass - test(args...) = pass - - test1(x::Type{Float64}) = pass - - test2(x::AbstractString) = pass - test2(x::Char) = pass - test2(x::Cmd) = pass - - test3(x::AbstractArray{Int}, y::Int) = pass - test3(x::AbstractArray{Float64}, y::Float64) = pass - - test4(x::AbstractString, y::AbstractString) = pass - test4(x::AbstractString, y::Regex) = pass - - test5(x::Array{Bool,1}) = pass - test5(x::BitArray{1}) = pass - test5(x::Float64) = pass - const a=x->x - test6()=[a, a] - - kwtest(; x=1, y=2, w...) = pass - - array = [1, 1] - varfloat = 0.1 - - const tuple = (1, 2) - - test_y_array=[CompletionFoo.Test_y(rand()) for i in 1:10] - test_dict = Dict("abc"=>1, "abcd"=>10, :bar=>2, :bar2=>9, Base=>3, - contains=>4, `ls`=>5, 66=>7, 67=>8, ("q",3)=>11, - "α"=>12, :α=>13) - test_customdict = CustomDict(test_dict) - end - test_repl_comp_dict = CompletionFoo.test_dict - test_repl_comp_customdict = CompletionFoo.test_customdict -end -ex.head = :toplevel -eval(Main, ex) - -function temp_pkg_dir_noinit(fn::Function) - # Used in tests below to set up and tear down a sandboxed package directory - # Unlike the version in test/pkg.jl, this does not run Pkg.init so does not - # clone METADATA (only pkg and libgit2-online tests should need internet access) - const tmpdir = joinpath(tempdir(),randstring()) - withenv("JULIA_PKGDIR" => tmpdir) do - @test !isdir(Pkg.dir()) - try - mkpath(Pkg.dir()) - @test isdir(Pkg.dir()) - fn() - finally - rm(tmpdir, recursive=true) - end - end -end - -test_complete(s) = completions(s,endof(s)) -test_scomplete(s) = shell_completions(s,endof(s)) -test_bslashcomplete(s) = bslash_completions(s,endof(s))[2] - -s = "" -c,r = test_complete(s) -@test "CompletionFoo" in c -@test isempty(r) -@test s[r] == "" - -s = "Comp" -c,r = test_complete(s) -@test "CompletionFoo" in c -@test r == 1:4 -@test s[r] == "Comp" - -s = "Main.Comp" -c,r = test_complete(s) -@test "CompletionFoo" in c -@test r == 6:9 -@test s[r] == "Comp" - -s = "Main.CompletionFoo." -c,r = test_complete(s) -@test "bar" in c -@test r == 20:19 -@test s[r] == "" - -s = "Main.CompletionFoo.f" -c,r = test_complete(s) -@test "foo" in c -@test r == 20:20 -@test s[r] == "f" -@test !("foobar" in c) - -# issue #6424 -s = "Main.CompletionFoo.@f" -c,r = test_complete(s) -@test "@foobar" in c -@test r == 20:21 -@test s[r] == "@f" -@test !("foo" in c) - -s = "Main.CompletionFoo.type_test.x" -c,r = test_complete(s) -@test "xx" in c -@test r == 30:30 -@test s[r] == "x" - -s = "Main.CompletionFoo.bar.no_val_available" -c,r = test_complete(s) -@test length(c)==0 -#cannot do dot completion on infix operator -s = "+." -c,r = test_complete(s) -@test length(c)==0 - -# To complete on a variable of a type, the type T of the variable -# must be a concrete type, hence Base.isstructtype(T) returns true, -# for the completion to succeed. That why `xx :: Test_y` of `Test_x`. -s = "Main.CompletionFoo.type_test.xx.y" -c,r = test_complete(s) -@test "yy" in c -@test r == 33:33 -@test s[r] == "y" - -# issue #6333 -s = "Base.return_types(getin" -c,r = test_complete(s) -@test "getindex" in c -@test r == 19:23 -@test s[r] == "getin" - -# inexistent completion inside a string -s = "Pkg.add(\"lol" -c,r,res = test_complete(s) -@test res == false - -# test latex symbol completions -s = "\\alpha" -c,r = test_bslashcomplete(s) -@test c[1] == "α" -@test r == 1:length(s) -@test length(c) == 1 - -# test latex symbol completions after unicode #9209 -s = "α\\alpha" -c,r = test_bslashcomplete(s) -@test c[1] == "α" -@test r == 3:sizeof(s) -@test length(c) == 1 - -# test emoji symbol completions -s = "\\:koala:" -c,r = test_bslashcomplete(s) -@test c[1] == "🐨" -@test r == 1:sizeof(s) -@test length(c) == 1 - -s = "\\:ko" -c,r = test_bslashcomplete(s) -@test "\\:koala:" in c - -# test emoji symbol completions after unicode #9209 -s = "α\\:koala:" -c,r = test_bslashcomplete(s) -@test c[1] == "🐨" -@test r == 3:sizeof(s) -@test length(c) == 1 - -# test latex symbol completions in strings should not work when there -# is a backslash in front of `\alpha` because it interferes with path completion on windows -s = "cd(\"path_to_an_empty_folder_should_not_complete_latex\\\\\\alpha" -c,r,res = test_complete(s) -@test length(c) == 0 - -# test latex symbol completions in strings -s = "\"C:\\\\ \\alpha" -c,r,res = test_complete(s) -@test c[1] == "α" -@test r == 7:12 -@test length(c) == 1 - -s = "\\a" -c, r, res = test_complete(s) -"\\alpha" in c -@test r == 1:2 -@test s[r] == "\\a" - -# `cd("C:\U should not make the repl crash due to escaping see comment #9137 -s = "cd(\"C:\\U" -c,r,res = test_complete(s) - -# Test method completions -s = "max(" -c, r, res = test_complete(s) -@test !res -@test let found = false - for m in methods(max) - if !found - found = (c[1] == string(m)) - end - end - found -end -@test r == 1:3 -@test s[r] == "max" - -# Test completion of methods with input concrete args and args where typeinference determine their type -s = "CompletionFoo.test(1,1, " -c, r, res = test_complete(s) -@test !res -@test c[1] == string(first(methods(Main.CompletionFoo.test, Tuple{Int, Int}))) -@test length(c) == 3 -@test r == 1:18 -@test s[r] == "CompletionFoo.test" - -s = "CompletionFoo.test(CompletionFoo.array," -c, r, res = test_complete(s) -@test !res -@test c[1] == string(first(methods(Main.CompletionFoo.test, Tuple{Array{Int, 1}, Any}))) -@test length(c) == 2 -@test r == 1:18 -@test s[r] == "CompletionFoo.test" - -s = "CompletionFoo.test(1,1,1," -c, r, res = test_complete(s) -@test !res -@test c[1] == string(first(methods(Main.CompletionFoo.test, Tuple{Any, Any, Any}))) -@test r == 1:18 -@test s[r] == "CompletionFoo.test" - -s = "CompletionFoo.test1(Int," -c, r, res = test_complete(s) -@test !res -@test length(c) == 0 -@test r == 1:19 -@test s[r] == "CompletionFoo.test1" - -s = "CompletionFoo.test1(Float64," -c, r, res = test_complete(s) -@test !res -@test length(c) == 1 -@test r == 1:19 -@test s[r] == "CompletionFoo.test1" - -s = "prevind(\"θ\",1," -c, r, res = test_complete(s) -@test c[1] == string(first(methods(prevind, Tuple{String, Int}))) -@test r == 1:7 -@test s[r] == "prevind" - -for (T, arg) in [(String,"\")\""),(Char, "')'")] - s = "(1, CompletionFoo.test2($arg," - c, r, res = test_complete(s) - @test length(c) == 1 - @test c[1] == string(first(methods(Main.CompletionFoo.test2, Tuple{T,}))) - @test r == 5:23 - @test s[r] == "CompletionFoo.test2" -end - -s = "(1, CompletionFoo.test2(`')'`," -c, r, res = test_complete(s) -@test c[1] == string(first(methods(Main.CompletionFoo.test2, Tuple{Cmd}))) -@test length(c) == 1 - -s = "CompletionFoo.test3([1, 2] + CompletionFoo.varfloat," -c, r, res = test_complete(s) -@test !res -@test c[1] == string(first(methods(Main.CompletionFoo.test3, Tuple{Array{Float64, 1}, Float64}))) -@test length(c) == 1 - -s = "CompletionFoo.test3([1.,2.], 1.," -c, r, res = test_complete(s) -@test !res -@test c[1] == string(first(methods(Main.CompletionFoo.test3, Tuple{Array{Float64, 1}, Float64}))) -@test r == 1:19 -@test length(c) == 1 -@test s[r] == "CompletionFoo.test3" - -s = "CompletionFoo.test4(\"e\",r\" \"," -c, r, res = test_complete(s) -@test !res -@test c[1] == string(first(methods(Main.CompletionFoo.test4, Tuple{String, Regex}))) -@test r == 1:19 -@test length(c) == 1 -@test s[r] == "CompletionFoo.test4" - -# (As discussed in #19829, the Base.REPLCompletions.get_type function isn't -# powerful enough to analyze general dot calls because it can't handle -# anonymous-function evaluation.) -s = "CompletionFoo.test5(push!(Base.split(\"\",' '),\"\",\"\").==\"\"," -c, r, res = test_complete(s) -@test !res -@test_broken length(c) == 1 -@test_broken c[1] == string(first(methods(Main.CompletionFoo.test5, Tuple{BitArray{1}}))) - -s = "CompletionFoo.test4(CompletionFoo.test_y_array[1]()[1], CompletionFoo.test_y_array[1]()[2], " -c, r, res = test_complete(s) -@test !res -@test length(c) == 1 -@test c[1] == string(first(methods(Main.CompletionFoo.test4, Tuple{String, String}))) - -# Test that string escaption is handled correct -s = """CompletionFoo.test4("\\"",""" -c, r, res = test_complete(s) -@test !res -@test length(c) == 2 - -########## Test where the current inference logic fails ######## -# Fails due to inferrence fails to determine a concrete type for arg 1 -# But it returns AbstractArray{T,N} and hence is able to remove test5(x::Float64) from the suggestions -s = "CompletionFoo.test5(AbstractArray[[]][1]," -c, r, res = test_complete(s) -@test !res -@test length(c) == 2 - -# equivalent to above but due to the time macro the completion fails to find the concrete type -s = "CompletionFoo.test3(@time([1, 2] + CompletionFoo.varfloat)," -c, r, res = test_complete(s) -@test !res -@test length(c) == 2 -################################################################# - -s = "CompletionFoo.kwtest( " -c, r, res = test_complete(s) -@test !res -@test length(c) == 1 -@test contains(c[1], "x, y, w...") - -# Test of inference based getfield completion -s = "\"\"." -c,r = test_complete(s) -@test length(c)==1 -@test r == (endof(s)+1):endof(s) -@test c[1] == "len" - -s = "(\"\"*\"\")." -c,r = test_complete(s) -@test length(c)==1 -@test r == (endof(s)+1):endof(s) -@test c[1] == "len" - -s = "CompletionFoo.test_y_array[1]." -c,r = test_complete(s) -@test length(c)==1 -@test r == (endof(s)+1):endof(s) -@test c[1] == "yy" - -s = "CompletionFoo.Test_y(rand()).y" -c,r = test_complete(s) -@test length(c)==1 -@test r == endof(s):endof(s) -@test c[1] == "yy" - -s = "CompletionFoo.test6()[1](CompletionFoo.Test_y(rand())).y" -c,r = test_complete(s) -@test length(c)==1 -@test r == endof(s):endof(s) -@test c[1] == "yy" - -# Test completion in multi-line comments -s = "#=\n\\alpha" -c, r, res = test_complete(s) -@test c[1] == "α" -@test r == 4:9 -@test length(c) == 1 - -# Test that completion do not work in multi-line comments -s = "#=\nmax" -c, r, res = test_complete(s) -@test length(c) == 0 - -# Test completion of packages -mkp(p) = ((@assert !isdir(p)); mkpath(p)) -temp_pkg_dir_noinit() do - # Complete <Mod>/src/<Mod>.jl and <Mod>.jl/src/<Mod>.jl - # but not <Mod>/ if no corresponding .jl file is found - pkg_dir = Pkg.dir("CompletionFooPackage", "src") - mkp(pkg_dir) - touch(joinpath(pkg_dir, "CompletionFooPackage.jl")) - - pkg_dir = Pkg.dir("CompletionFooPackage2.jl", "src") - mkp(pkg_dir) - touch(joinpath(pkg_dir, "CompletionFooPackage2.jl")) - - touch(Pkg.dir("CompletionFooPackage3.jl")) - - mkp(Pkg.dir("CompletionFooPackageNone")) - mkp(Pkg.dir("CompletionFooPackageNone2.jl")) - - s = "using Completion" - c,r = test_complete(s) - @test "CompletionFoo" in c #The module - @test "CompletionFooPackage" in c #The package - @test "CompletionFooPackage2" in c #The package - @test "CompletionFooPackage3" in c #The package - @test !("CompletionFooPackageNone" in c) #The package - @test !("CompletionFooPackageNone2" in c) #The package - @test s[r] == "Completion" -end - -path = joinpath(tempdir(),randstring()) -push!(LOAD_PATH, path) -try - # Should not throw an error even though the path do no exist - test_complete("using ") - Pack_folder = joinpath(path, "Test_pack") - mkpath(Pack_folder) - - Pack_folder2 = joinpath(path, "Test_pack2", "src") - mkpath(Pack_folder2) - touch(joinpath(Pack_folder2, "Test_pack2.jl")) - - # Test it completes on folders - c,r,res = test_complete("using Test_p") - @test !("Test_pack" in c) - @test "Test_pack2" in c - - # Test that it also completes on .jl files in pwd() - cd(Pack_folder) do - open("Text.txt","w") do f end - open("Pack.jl","w") do f end - c,r,res = test_complete("using ") - @test "Pack" in c - @test !("Text.txt" in c) - end -finally - @test pop!(LOAD_PATH) == path - rm(path, recursive=true) -end - -# Test $ in shell-mode -s = "cd \$(max" -c, r, res = test_scomplete(s) -@test "max" in c -@test r == 6:8 -@test s[r] == "max" - -# The return type is of importance, before #8995 it would return nothing -# which would raise an error in the repl code. -@test (String[], 0:-1, false) == test_scomplete("\$a") - -if is_unix() - #Assume that we can rely on the existence and accessibility of /tmp - - # Tests path in Julia code and closing " if it's a file - # Issue #8047 - s = "@show \"/dev/nul" - c,r = test_complete(s) - @test "null\"" in c - @test r == 13:15 - @test s[r] == "nul" - - # Tests path in Julia code and not closing " if it's a directory - # Issue #8047 - s = "@show \"/tm" - c,r = test_complete(s) - @test "tmp/" in c - @test r == 9:10 - @test s[r] == "tm" - - # Tests path in Julia code and not double-closing " - # Issue #8047 - s = "@show \"/dev/nul\"" - c,r = completions(s, 15) - @test "null" in c - @test r == 13:15 - @test s[r] == "nul" - - s = "/t" - c,r = test_scomplete(s) - @test "tmp/" in c - @test r == 2:2 - @test s[r] == "t" - - s = "/tmp" - c,r = test_scomplete(s) - @test "tmp/" in c - @test r == 2:4 - @test s[r] == "tmp" - - # This should match things that are inside the tmp directory - if !isdir("/tmp/tmp") - s = "/tmp/" - c,r = test_scomplete(s) - @test !("tmp/" in c) - @test r == 6:5 - @test s[r] == "" - end - - s = "cd \$(Pk" - c,r = test_scomplete(s) - @test "Pkg" in c - @test r == 6:7 - @test s[r] == "Pk" - - # Pressing tab after having entered "/tmp " should not - # attempt to complete "/tmp" but rather work on the current - # working directory again. - let - file = joinpath(path, "repl completions") - s = "/tmp " - c,r = test_scomplete(s) - @test r == 6:5 - end - - # Test completing paths with an escaped trailing space - let - file = joinpath(tempdir(), "repl completions") - touch(file) - s = string(tempdir(), "/repl\\ ") - c,r = test_scomplete(s) - @test ["repl\\ completions"] == c - @test s[r] == "repl\\ " - rm(file) - end - - # Tests homedir expansion - let - path = homedir() - dir = joinpath(path, "tmpfoobar") - mkdir(dir) - s = "\"~/tmpfoob" - c,r = test_complete(s) - @test "tmpfoobar/" in c - @test r == 4:10 - @test s[r] == "tmpfoob" - s = "\"~" - @test "tmpfoobar/" in c - c,r = test_complete(s) - rm(dir) - end - - # Tests detecting of files in the env path (in shell mode) - let - oldpath = ENV["PATH"] - path = tempdir() - # PATH can also contain folders which we aren't actually allowed to read. - unreadable = joinpath(tempdir(), "replcompletion-unreadable") - ENV["PATH"] = string(path, ":", unreadable) - - file = joinpath(path, "tmp-executable") - touch(file) - chmod(file, 0o755) - mkdir(unreadable) - chmod(unreadable, 0o000) - - s = "tmp-execu" - c,r = test_scomplete(s) - @test "tmp-executable" in c - @test r == 1:9 - @test s[r] == "tmp-execu" - - rm(file) - rm(unreadable) - ENV["PATH"] = oldpath - end - - # Make sure completion results are unique in case things are in the env path twice. - let - file0 = joinpath(tempdir(), "repl-completion") - dir = joinpath(tempdir(), "repl-completion-subdir") - file1 = joinpath(dir, "repl-completion") - - try - # Create /tmp/repl-completion and /tmp/repl-completion-subdir/repl-completion - mkdir(dir) - touch(file0) - touch(file1) - - withenv("PATH" => string(tempdir(), ":", dir)) do - s = string("repl-completio") - c,r = test_scomplete(s) - @test ["repl-completion"] == c - @test s[r] == "repl-completio" - end - - finally - rm(file0) - rm(file1) - rm(dir) - end - end -end - -let #test that it can auto complete with spaces in file/path - path = tempdir() - space_folder = randstring() * " α" - dir = joinpath(path, space_folder) - dir_space = replace(space_folder, " ", "\\ ") - mkdir(dir) - cd(path) do - open(joinpath(space_folder, "space .file"),"w") do f - s = is_windows() ? "rm $dir_space\\\\space" : "cd $dir_space/space" - c,r = test_scomplete(s) - @test r == endof(s)-4:endof(s) - @test "space\\ .file" in c - - s = is_windows() ? "cd(\"β $dir_space\\\\space" : "cd(\"β $dir_space/space" - c,r = test_complete(s) - @test r == endof(s)-4:endof(s) - @test "space\\ .file\"" in c - end - # Test for issue #10324 - s = "cd(\"$dir_space" - c,r = test_complete(s) - @test r == 5:15 - @test s[r] == dir_space - end - rm(dir, recursive=true) -end - -# Test the completion returns nothing when the folder do not exist -c,r = test_complete("cd(\"folder_do_not_exist_77/file") -@test length(c) == 0 - -if is_windows() - tmp = tempname() - path = dirname(tmp) - file = basename(tmp) - temp_name = basename(path) - cd(path) do - s = "cd ..\\\\" - c,r = test_scomplete(s) - @test r == length(s)+1:length(s) - @test temp_name * "\\\\" in c - - s = "ls $(file[1:2])" - c,r = test_scomplete(s) - @test r == length(s)-1:length(s) - @test file in c - - s = "cd(\"..\\" - c,r = test_complete(s) - @test r == length(s)+1:length(s) - @test temp_name * "\\\\" in c - - s = "cd(\"$(file[1:2])" - c,r = test_complete(s) - @test r == length(s) - 1:length(s) - @test (length(c) > 1 && file in c) || (["$file\""] == c) - end - rm(tmp) -end - -# auto completions of true and false... issue #14101 -s = "tru" -c, r, res = test_complete(s) -@test "true" in c -s = "fals" -c, r, res = test_complete(s) -@test "false" in c - -# Don't crash when attempting to complete a tuple, #15329 -s = "CompletionFoo.tuple." -c, r, res = test_complete(s) -@test isempty(c) - -# test Dicts -function test_dict_completion(dict_name) - s = "$dict_name[\"ab" - c, r = test_complete(s) - @test c == Any["\"abc\"", "\"abcd\""] - s = "$dict_name[\"abcd" - c, r = test_complete(s) - @test c == Any["\"abcd\"]"] - s = "$dict_name[ \"abcd" # leading whitespace - c, r = test_complete(s) - @test c == Any["\"abcd\"]"] - s = "$dict_name[\"abcd]" # trailing close bracket - c, r = completions(s, endof(s) - 1) - @test c == Any["\"abcd\""] - s = "$dict_name[:b" - c, r = test_complete(s) - @test c == Any[":bar", ":bar2"] - s = "$dict_name[:bar2" - c, r = test_complete(s) - @test c == Any[":bar2]"] - s = "$dict_name[Ba" - c, r = test_complete(s) - @test c == Any["Base]"] - s = "$dict_name[co" - c, r = test_complete(s) - @test c == Any["contains]"] - s = "$dict_name[`l" - c, r = test_complete(s) - @test c == Any["`ls`]"] - s = "$dict_name[6" - c, r = test_complete(s) - @test c == Any["66", "67"] - s = "$dict_name[66" - c, r = test_complete(s) - @test c == Any["66]"] - s = "$dict_name[(" - c, r = test_complete(s) - @test c == Any["(\"q\", 3)]"] - s = "$dict_name[\"\\alp" - c, r = test_complete(s) - @test c == String["\\alpha"] - s = "$dict_name[\"\\alpha" - c, r = test_complete(s) - @test c == String["α"] - s = "$dict_name[\"α" - c, r = test_complete(s) - @test c == Any["\"α\"]"] - s = "$dict_name[:\\alp" - c, r = test_complete(s) - @test c == String["\\alpha"] - s = "$dict_name[:\\alpha" - c, r = test_complete(s) - @test c == String["α"] - s = "$dict_name[:α" - c, r = test_complete(s) - @test c == Any[":α]"] -end -test_dict_completion("CompletionFoo.test_dict") -test_dict_completion("CompletionFoo.test_customdict") -test_dict_completion("test_repl_comp_dict") -test_dict_completion("test_repl_comp_customdict") diff --git a/julia-0.6.3/share/julia/test/replutil.jl b/julia-0.6.3/share/julia/test/replutil.jl deleted file mode 100644 index 63e3091..0000000 --- a/julia-0.6.3/share/julia/test/replutil.jl +++ /dev/null @@ -1,562 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -# For curmod_* -include("testenv.jl") - -function test_have_color(buf, color, no_color) - if Base.have_color - @test String(take!(buf)) == color - else - @test String(take!(buf)) == no_color - end -end - -cfile = " at $(@__FILE__):" -c1line = @__LINE__ + 1 -method_c1(x::Float64, s::AbstractString...) = true - -buf = IOBuffer() -Base.show_method_candidates(buf, Base.MethodError(method_c1,(1, 1, ""))) -no_color = "\nClosest candidates are:\n method_c1(!Matched::Float64, !Matched::AbstractString...)$cfile$c1line" -@test length(methods(method_c1)) <= 3 # because of '...' in candidate printing -test_have_color(buf, - "\e[0m\nClosest candidates are:\n method_c1(\e[1m\e[31m::Float64\e[0m, \e[1m\e[31m::AbstractString...\e[0m)$cfile$c1line\e[0m", - no_color) - -no_color = "\nClosest candidates are:\n method_c1(!Matched::Float64, ::AbstractString...)$cfile$c1line" -Base.show_method_candidates(buf, Base.MethodError(method_c1,(1, "", ""))) -test_have_color(buf, - "\e[0m\nClosest candidates are:\n method_c1(\e[1m\e[31m::Float64\e[0m, ::AbstractString...)$cfile$c1line\e[0m", - no_color) - -# should match -no_color = "\nClosest candidates are:\n method_c1(::Float64, ::AbstractString...)$cfile$c1line" -Base.show_method_candidates(buf, Base.MethodError(method_c1,(1., "", ""))) -test_have_color(buf, - "\e[0m\nClosest candidates are:\n method_c1(::Float64, ::AbstractString...)$cfile$c1line\e[0m", - no_color) - -# Have no matches so should return empty -Base.show_method_candidates(buf, Base.MethodError(method_c1,(1, 1, 1))) -test_have_color(buf, "", "") - -# matches the implicit constructor -> convert method -Base.show_method_candidates(buf, Base.MethodError(Tuple{}, (1, 1, 1))) -let mc = String(take!(buf)) - @test contains(mc, "\nClosest candidates are:\n Tuple{}") - @test !contains(mc, cfile) -end - -c2line = @__LINE__ -method_c2(x::Int32, args...) = true -method_c2(x::Int32, y::Float64, args...) = true -method_c2(x::Int32, y::Float64) = true -method_c2(x::Int32, y::Int32, z::Int32) = true -method_c2{T<:Real}(x::T, y::T, z::T) = true - -Base.show_method_candidates(buf, Base.MethodError(method_c2,(1., 1., 2))) -color = "\e[0m\nClosest candidates are:\n method_c2(\e[1m\e[31m::Int32\e[0m, ::Float64, ::Any...)$cfile$(c2line+2)\n method_c2(\e[1m\e[31m::Int32\e[0m, ::Any...)$cfile$(c2line+1)\n method_c2(::T<:Real, ::T<:Real, \e[1m\e[31m::T<:Real\e[0m)$cfile$(c2line+5)\n ...\e[0m" -no_color = no_color = "\nClosest candidates are:\n method_c2(!Matched::Int32, ::Float64, ::Any...)$cfile$(c2line+2)\n method_c2(!Matched::Int32, ::Any...)$cfile$(c2line+1)\n method_c2(::T<:Real, ::T<:Real, !Matched::T<:Real) where T<:Real$cfile$(c2line+5)\n ..." -test_have_color(buf, color, no_color) - -c3line = @__LINE__ + 1 -method_c3(x::Float64, y::Float64) = true -Base.show_method_candidates(buf, Base.MethodError(method_c3,(1.,))) -color = "\e[0m\nClosest candidates are:\n method_c3(::Float64, \e[1m\e[31m::Float64\e[0m)$cfile$c3line\e[0m" -no_color = no_color = "\nClosest candidates are:\n method_c3(::Float64, !Matched::Float64)$cfile$c3line" -test_have_color(buf, color, no_color) - -# Test for the method error in issue #8651 -c4line = @__LINE__ -method_c4() = true -method_c4(x::AbstractString) = false -Base.show_method_candidates(buf, MethodError(method_c4,("",))) -test_have_color(buf, - "\e[0m\nClosest candidates are:\n method_c4(::AbstractString)$cfile$(c4line+2)\n method_c4()$cfile$(c4line+1)\e[0m", - "\nClosest candidates are:\n method_c4(::AbstractString)$cfile$(c4line+2)\n method_c4()$cfile$(c4line+1)") - -c5line = @__LINE__ + 1 -method_c5(::Type{Float64}) = true -Base.show_method_candidates(buf, MethodError(method_c5,(Float64,))) -test_have_color(buf, "\e[0m\nClosest candidates are:\n method_c5(::Type{Float64})$cfile$c5line\e[0m", - "\nClosest candidates are:\n method_c5(::Type{Float64})$cfile$c5line") - -Base.show_method_candidates(buf, MethodError(method_c5,(Int32,))) -test_have_color(buf, "\e[0m\nClosest candidates are:\n method_c5(\e[1m\e[31m::Type{Float64}\e[0m)$cfile$c5line\e[0m", - "\nClosest candidates are:\n method_c5(!Matched::Type{Float64})$cfile$c5line") - -mutable struct Test_type end -test_type = Test_type() -for f in [getindex, setindex!] - Base.show_method_candidates(buf, MethodError(f,(test_type, 1,1))) - test_have_color(buf, "", "") -end - -PR16155line = @__LINE__ + 2 -mutable struct PR16155 - a::Int64 - b -end -PR16155line2 = @__LINE__ + 1 -(::Type{T}){T<:PR16155}(arg::Any) = "replace call-to-convert method from sysimg" - -Base.show_method_candidates(buf, MethodError(PR16155,(1.0, 2.0, Int64(3)))) -test_have_color(buf, "\e[0m\nClosest candidates are:\n $(curmod_prefix)PR16155(::Any, ::Any)$cfile$PR16155line\n $(curmod_prefix)PR16155(\e[1m\e[31m::Int64\e[0m, ::Any)$cfile$PR16155line\n $(curmod_prefix)PR16155(::Any) where T<:$(curmod_prefix)PR16155$cfile$PR16155line2\e[0m", - "\nClosest candidates are:\n $(curmod_prefix)PR16155(::Any, ::Any)$cfile$PR16155line\n $(curmod_prefix)PR16155(!Matched::Int64, ::Any)$cfile$PR16155line\n $(curmod_prefix)PR16155(::Any) where T<:$(curmod_prefix)PR16155$cfile$PR16155line2") - -Base.show_method_candidates(buf, MethodError(PR16155,(Int64(3), 2.0, Int64(3)))) -test_have_color(buf, "\e[0m\nClosest candidates are:\n $(curmod_prefix)PR16155(::Int64, ::Any)$cfile$PR16155line\n $(curmod_prefix)PR16155(::Any, ::Any)$cfile$PR16155line\n $(curmod_prefix)PR16155(::Any) where T<:$(curmod_prefix)PR16155$cfile$PR16155line2\e[0m", - "\nClosest candidates are:\n $(curmod_prefix)PR16155(::Int64, ::Any)$cfile$PR16155line\n $(curmod_prefix)PR16155(::Any, ::Any)$cfile$PR16155line\n $(curmod_prefix)PR16155(::Any) where T<:$(curmod_prefix)PR16155$cfile$PR16155line2") - -c6line = @__LINE__ -method_c6(; x=1) = x -method_c6(a; y=1) = y -m_error = try method_c6(y=1) catch e; e; end -showerror(buf, m_error) -error_out = String(take!(buf)) -m_error = try method_c6(1, x=1) catch e; e; end -showerror(buf, m_error) -error_out1 = String(take!(buf)) - -c6mline = @__LINE__ -module TestKWError -method_c6_in_module(; x=1) = x -method_c6_in_module(a; y=1) = y -end -m_error = try TestKWError.method_c6_in_module(y=1) catch e; e; end -showerror(buf, m_error) -error_out2 = String(take!(buf)) -m_error = try TestKWError.method_c6_in_module(1, x=1) catch e; e; end -showerror(buf, m_error) -error_out3 = String(take!(buf)) - -if Base.have_color - @test contains(error_out, "method_c6(; x)$cfile$(c6line + 1)\e[1m\e[31m got unsupported keyword argument \"y\"\e[0m") - @test contains(error_out, "method_c6(\e[1m\e[31m::Any\e[0m; y)$cfile$(c6line + 2)") - @test contains(error_out1, "method_c6(::Any; y)$cfile$(c6line + 2)\e[1m\e[31m got unsupported keyword argument \"x\"\e[0m") - @test contains(error_out2, "method_c6_in_module(; x)$cfile$(c6mline + 2)\e[1m\e[31m got unsupported keyword argument \"y\"\e[0m") - @test contains(error_out2, "method_c6_in_module(\e[1m\e[31m::Any\e[0m; y)$cfile$(c6mline + 3)") - @test contains(error_out3, "method_c6_in_module(::Any; y)$cfile$(c6mline + 3)\e[1m\e[31m got unsupported keyword argument \"x\"\e[0m") -else - @test contains(error_out, "method_c6(; x)$cfile$(c6line + 1) got unsupported keyword argument \"y\"") - @test contains(error_out, "method_c6(!Matched::Any; y)$cfile$(c6line + 2)") - @test contains(error_out1, "method_c6(::Any; y)$cfile$(c6line + 2) got unsupported keyword argument \"x\"") - @test contains(error_out2, "method_c6_in_module(; x)$cfile$(c6mline + 2) got unsupported keyword argument \"y\"") - @test contains(error_out2, "method_c6_in_module(!Matched::Any; y)$cfile$(c6mline + 3)") - @test contains(error_out3, "method_c6_in_module(::Any; y)$cfile$(c6mline + 3) got unsupported keyword argument \"x\"") -end - -c7line = @__LINE__ + 1 -method_c7(a, b; kargs...) = a -Base.show_method_candidates(buf, MethodError(method_c7, (1, 1)), [(:x, 1), (:y, 2)]) -test_have_color(buf, "\e[0m\nClosest candidates are:\n method_c7(::Any, ::Any; kargs...)$cfile$c7line\e[0m", - "\nClosest candidates are:\n method_c7(::Any, ::Any; kargs...)$cfile$c7line") -c8line = @__LINE__ + 1 -method_c8(a, b; y=1, w=1) = a -Base.show_method_candidates(buf, MethodError(method_c8, (1, 1)), [(:x, 1), (:y, 2), (:z, 1), (:w, 1)]) -test_have_color(buf, "\e[0m\nClosest candidates are:\n method_c8(::Any, ::Any; y, w)$cfile$c8line\e[1m\e[31m got unsupported keyword arguments \"x\", \"z\"\e[0m\e[0m", - "\nClosest candidates are:\n method_c8(::Any, ::Any; y, w)$cfile$c8line got unsupported keyword arguments \"x\", \"z\"") - -ac15639line = @__LINE__ -addConstraint_15639(c::Int32) = c -addConstraint_15639(c::Int64; uncset=nothing) = addConstraint_15639(Int32(c), uncset=uncset) - -Base.show_method_candidates(buf, MethodError(addConstraint_15639, (Int32(1),)), [(:uncset, nothing)]) -test_have_color(buf, "\e[0m\nClosest candidates are:\n addConstraint_15639(::Int32)$cfile$(ac15639line + 1)\e[1m\e[31m got unsupported keyword argument \"uncset\"\e[0m\n addConstraint_15639(\e[1m\e[31m::Int64\e[0m; uncset)$cfile$(ac15639line + 2)\e[0m", - "\nClosest candidates are:\n addConstraint_15639(::Int32)$cfile$(ac15639line + 1) got unsupported keyword argument \"uncset\"\n addConstraint_15639(!Matched::Int64; uncset)$cfile$(ac15639line + 2)") - -macro except_str(expr, err_type) - return quote - let err = nothing - try - $(esc(expr)) - catch err - end - err === nothing && error("expected failure, but no exception thrown") - @test typeof(err) === $(esc(err_type)) - buf = IOBuffer() - showerror(buf, err) - String(take!(buf)) - end - end -end - -macro except_strbt(expr, err_type) - return quote - let err = nothing - try - $(esc(expr)) - catch err - end - err === nothing && error("expected failure, but no exception thrown") - @test typeof(err) === $(esc(err_type)) - buf = IOBuffer() - showerror(buf, err, catch_backtrace()) - String(take!(buf)) - end - end -end - -macro except_stackframe(expr, err_type) - return quote - let err = nothing - local st - try - $(esc(expr)) - catch err - st = catch_stacktrace() - end - err === nothing && error("expected failure, but no exception thrown") - @test typeof(err) === $(esc(err_type)) - sprint(show, st[1]) - end - end -end - -# Pull Request 11007 -abstract type InvokeType11007 end -abstract type MethodType11007 <: InvokeType11007 end -mutable struct InstanceType11007 <: MethodType11007 -end -let - f11007(::MethodType11007) = nothing - err_str = @except_str(invoke(f11007, Tuple{InvokeType11007}, - InstanceType11007()), MethodError) - @test !contains(err_str, "::$(curmod_prefix)InstanceType11007") - @test contains(err_str, "::$(curmod_prefix)InvokeType11007") -end - -module __tmp_replutil - -using Base.Test -import ..@except_str -global + -+() = nothing -err_str = @except_str 1 + 2 MethodError -@test contains(err_str, "import Base.+") - -err_str = @except_str Float64[](1) MethodError -@test !contains(err_str, "import Base.Array") - -Array() = 1 -err_str = @except_str Array(1) MethodError -@test contains(err_str, "import Base.Array") - -end - -let - g11007(::AbstractVector) = nothing - err_str = @except_str g11007([[1] [1]]) MethodError - @test contains(err_str, "row vector") - @test contains(err_str, "column vector") -end - -struct TypeWithIntParam{T <: Integer} end -let undefvar - err_str = @except_strbt sqrt(-1) DomainError - @test contains(err_str, "Try sqrt(complex(x)).") - err_str = @except_strbt 2^(-1) DomainError - @test contains(err_str, "Cannot raise an integer x to a negative power -n") - err_str = @except_strbt (-1)^0.25 DomainError - @test contains(err_str, "Exponentiation yielding a complex result requires a complex argument") - - err_str = @except_str (1, 2, 3)[4] BoundsError - @test err_str == "BoundsError: attempt to access (1, 2, 3)\n at index [4]" - - err_str = @except_str [5, 4, 3][-2, 1] BoundsError - @test err_str == "BoundsError: attempt to access 3-element Array{$Int,1} at index [-2, 1]" - err_str = @except_str [5, 4, 3][1:5] BoundsError - @test err_str == "BoundsError: attempt to access 3-element Array{$Int,1} at index [1:5]" - - err_str = @except_str 0::Bool TypeError - @test err_str == "TypeError: non-boolean ($Int) used in boolean context" - err_str = @except_str 0::AbstractFloat TypeError - @test err_str == "TypeError: typeassert: expected AbstractFloat, got $Int" - err_str = @except_str 0::7 TypeError - @test err_str == "TypeError: typeassert: expected Type, got $Int" - err_str = @except_str "" <: AbstractString TypeError - @test err_str == "TypeError: issubtype: expected Type, got String" - err_str = @except_str AbstractString <: "" TypeError - @test err_str == "TypeError: issubtype: expected Type, got String" - err_str = @except_str Type{""} TypeError - @test err_str == "TypeError: Type: in parameter, expected Type, got String" - err_str = @except_str TypeWithIntParam{Any} TypeError - @test err_str == "TypeError: TypeWithIntParam: in T, expected T<:Integer, got Type{Any}" - - err_str = @except_str mod(1,0) DivideError - @test err_str == "DivideError: integer division error" - err_str = @except_str Array{Any,1}(1)[1] UndefRefError - @test err_str == "UndefRefError: access to undefined reference" - err_str = @except_str undefvar UndefVarError - @test err_str == "UndefVarError: undefvar not defined" - err_str = @except_str read(IOBuffer(), UInt8) EOFError - @test err_str == "EOFError: read end of file" - err_str = @except_str Dict()[:doesnotexist] KeyError - @test err_str == "KeyError: key :doesnotexist not found" - err_str = @except_str throw(InterruptException()) InterruptException - @test err_str == "InterruptException:" - err_str = @except_str throw(ArgumentError("not an error")) ArgumentError - @test err_str == "ArgumentError: not an error" - err_str = @except_str @assert(false) AssertionError - @test err_str == "AssertionError: false" -end - - -# issue 11845 -let - buf = IOBuffer() - showerror(buf, MethodError(convert, (3, 1.0))) - showerror(buf, MethodError(convert, (Int, 1.0))) - showerror(buf, MethodError(convert, Tuple{Type, Float64})) - showerror(buf, MethodError(convert, Tuple{DataType, Float64})) -end - -# Issue #14884 -primitive type EightBitType 8 end -primitive type EightBitTypeT{T} 8 end -struct FunctionLike <: Function; end -let err_str, - i = reinterpret(EightBitType, 0x54), - j = reinterpret(EightBitTypeT{Int32}, 0x54) - - err_str = @except_str Bool() MethodError - @test contains(err_str, "MethodError: no method matching Bool()") - err_str = @except_str :a() MethodError - @test contains(err_str, "MethodError: objects of type Symbol are not callable") - err_str = @except_str EightBitType() MethodError - @test contains(err_str, "MethodError: no method matching $(curmod_prefix)EightBitType()") - err_str = @except_str i() MethodError - @test contains(err_str, "MethodError: objects of type $(curmod_prefix)EightBitType are not callable") - err_str = @except_str EightBitTypeT() MethodError - @test contains(err_str, "MethodError: no method matching $(curmod_prefix)EightBitTypeT()") - err_str = @except_str EightBitTypeT{Int32}() MethodError - @test contains(err_str, "MethodError: no method matching $(curmod_prefix)EightBitTypeT{Int32}()") - err_str = @except_str j() MethodError - @test contains(err_str, "MethodError: objects of type $(curmod_prefix)EightBitTypeT{Int32} are not callable") - err_str = @except_str FunctionLike()() MethodError - @test contains(err_str, "MethodError: no method matching (::$(curmod_prefix)FunctionLike)()") - err_str = @except_str [1,2](1) MethodError - @test contains(err_str, "MethodError: objects of type Array{$Int,1} are not callable\nUse square brackets [] for indexing an Array.") - # Issue 14940 - err_str = @except_str randn(1)() MethodError - @test contains(err_str, "MethodError: objects of type Array{Float64,1} are not callable") -end -@test stringmime("text/plain", FunctionLike()) == "(::FunctionLike) (generic function with 0 methods)" -@test ismatch(r"^@doc \(macro with \d+ method[s]?\)$", stringmime("text/plain", getfield(Base, Symbol("@doc")))) - -method_defs_lineno = @__LINE__+1 -Base.Symbol() = throw(ErrorException("1")) -(::Symbol)() = throw(ErrorException("2")) -EightBitType() = throw(ErrorException("3")) -(::EightBitType)() = throw(ErrorException("4")) -EightBitTypeT() = throw(ErrorException("5")) -(::Type{EightBitTypeT{T}}){T}() = throw(ErrorException("6")) -(::EightBitTypeT)() = throw(ErrorException("7")) -(::FunctionLike)() = throw(ErrorException("8")) - - -let err_str, - i = reinterpret(EightBitType, 0x54), - j = reinterpret(EightBitTypeT{Int32}, 0x54), - sp = Base.source_path() - sn = basename(sp) - - @test sprint(show, which(Symbol, Tuple{})) == "Symbol() in $curmod_str at $sp:$(method_defs_lineno + 0)" - @test sprint(show, which(:a, Tuple{})) == "(::Symbol)() in $curmod_str at $sp:$(method_defs_lineno + 1)" - @test sprint(show, which(EightBitType, Tuple{})) == "$(curmod_prefix)EightBitType() in $curmod_str at $sp:$(method_defs_lineno + 2)" - @test sprint(show, which(reinterpret(EightBitType, 0x54), Tuple{})) == "(::$(curmod_prefix)EightBitType)() in $curmod_str at $sp:$(method_defs_lineno + 3)" - @test sprint(show, which(EightBitTypeT, Tuple{})) == "(::Type{$(curmod_prefix)EightBitTypeT})() in $curmod_str at $sp:$(method_defs_lineno + 4)" - @test sprint(show, which(EightBitTypeT{Int32}, Tuple{})) == "(::Type{$(curmod_prefix)EightBitTypeT{T}})() where T in $curmod_str at $sp:$(method_defs_lineno + 5)" - @test sprint(show, which(reinterpret(EightBitTypeT{Int32}, 0x54), Tuple{})) == "(::$(curmod_prefix)EightBitTypeT)() in $curmod_str at $sp:$(method_defs_lineno + 6)" - @test startswith(sprint(show, which(getfield(Base, Symbol("@doc")), Tuple{Vararg{Any}})), "@doc(x...) in Core at boot.jl:") - @test startswith(sprint(show, which(FunctionLike(), Tuple{})), "(::$(curmod_prefix)FunctionLike)() in $curmod_str at $sp:$(method_defs_lineno + 7)") - @test stringmime("text/plain", FunctionLike()) == "(::FunctionLike) (generic function with 1 method)" - @test stringmime("text/plain", Core.arraysize) == "arraysize (built-in function)" - - err_str = @except_stackframe Symbol() ErrorException - @test err_str == "Symbol() at $sn:$(method_defs_lineno + 0)" - err_str = @except_stackframe :a() ErrorException - @test err_str == "(::Symbol)() at $sn:$(method_defs_lineno + 1)" - err_str = @except_stackframe EightBitType() ErrorException - @test err_str == "$(curmod_prefix)EightBitType() at $sn:$(method_defs_lineno + 2)" - err_str = @except_stackframe i() ErrorException - @test err_str == "(::$(curmod_prefix)EightBitType)() at $sn:$(method_defs_lineno + 3)" - err_str = @except_stackframe EightBitTypeT() ErrorException - @test err_str == "$(curmod_prefix)EightBitTypeT() at $sn:$(method_defs_lineno + 4)" - err_str = @except_stackframe EightBitTypeT{Int32}() ErrorException - @test err_str == "$(curmod_prefix)EightBitTypeT{Int32}() at $sn:$(method_defs_lineno + 5)" - err_str = @except_stackframe j() ErrorException - @test err_str == "(::$(curmod_prefix)EightBitTypeT{Int32})() at $sn:$(method_defs_lineno + 6)" - err_str = @except_stackframe FunctionLike()() ErrorException - @test err_str == "(::$(curmod_prefix)FunctionLike)() at $sn:$(method_defs_lineno + 7)" -end - -# Issue #13032 -withenv("JULIA_EDITOR" => nothing, "VISUAL" => nothing, "EDITOR" => nothing) do - # Make sure editor doesn't error when no ENV editor is set. - @test isa(Base.editor(), Array) - - # Invalid editor - ENV["JULIA_EDITOR"] = "" - @test_throws ErrorException Base.editor() - - # Note: The following testcases should work regardless of whether these editors are - # installed or not. - - # Editor on the path. - ENV["JULIA_EDITOR"] = "vim" - @test Base.editor() == ["vim"] - - # Absolute path to editor. - ENV["JULIA_EDITOR"] = "/usr/bin/vim" - @test Base.editor() == ["/usr/bin/vim"] - - # Editor on the path using arguments. - ENV["JULIA_EDITOR"] = "subl -w" - @test Base.editor() == ["subl", "-w"] - - # Absolute path to editor with spaces. - ENV["JULIA_EDITOR"] = "/Applications/Sublime\\ Text.app/Contents/SharedSupport/bin/subl" - @test Base.editor() == ["/Applications/Sublime Text.app/Contents/SharedSupport/bin/subl"] - - # Paths with spaces and arguments (#13032). - ENV["JULIA_EDITOR"] = "/Applications/Sublime\\ Text.app/Contents/SharedSupport/bin/subl -w" - @test Base.editor() == ["/Applications/Sublime Text.app/Contents/SharedSupport/bin/subl", "-w"] - - ENV["JULIA_EDITOR"] = "'/Applications/Sublime Text.app/Contents/SharedSupport/bin/subl' -w" - @test Base.editor() == ["/Applications/Sublime Text.app/Contents/SharedSupport/bin/subl", "-w"] - - ENV["JULIA_EDITOR"] = "\"/Applications/Sublime Text.app/Contents/SharedSupport/bin/subl\" -w" - @test Base.editor() == ["/Applications/Sublime Text.app/Contents/SharedSupport/bin/subl", "-w"] -end - -# Issue #14684: `display` should print associative types in full. -let d = Dict(1 => 2, 3 => 45) - buf = IOBuffer() - td = TextDisplay(buf) - display(td, d) - result = String(td.io) - - @test contains(result, summary(d)) - - # Is every pair in the string? - # Compare by removing spaces - for el in d - @test contains(replace(result, " ", ""), string(el)) - end -end - -# Issue #20108 -let err, buf = IOBuffer() - try Array() catch err end - Base.show_method_candidates(buf,err) - @test isa(err, MethodError) - @test contains(String(buf), "Closest candidates are:") -end - -# Issue 20111 -let K20111(x) = y -> x, buf = IOBuffer() - show(buf, methods(K20111(1))) - @test contains(String(buf), " 1 method for generic function") -end - -# @macroexpand tests -macro seven_dollar(ex) - # simonbyrne example 18240 - isa(ex,Expr) && ex.head == :$ ? 7 : esc(ex) -end - -let - @test (@macroexpand @macroexpand x) == macroexpand(:(@macroexpand x)) - @test (@macroexpand :(1+$y) ) == macroexpand(:( :(1+ $y))) - @test (@macroexpand @fastmath 1+2 ) == :(Base.FastMath.add_fast(1,2)) - @test (@macroexpand @fastmath + ) == :(Base.FastMath.add_fast) - @test (@macroexpand @fastmath min(1) ) == :(Base.FastMath.min_fast(1)) - @test (@macroexpand @doc "" f() = @x) == Expr(:error, UndefVarError(Symbol("@x"))) - @test (@macroexpand @seven_dollar $bar) == 7 - x = 2 - @test (@macroexpand @seven_dollar 1+$x) == :(1 + $(Expr(:$, :x))) -end - -foo_9965(x::Float64; w=false) = x -foo_9965(x::Int) = 2x - -@testset "closest candidates kwarg #9965" begin - ex = try - foo_9965(1, w=true) - catch e - e - end - @test typeof(ex) == MethodError - io = IOBuffer() - Base.show_method_candidates(io, ex, [(:w,true)]) - @test contains(String(take!(io)), "got unsupported keyword argument \"w\"") -end - -# Issue #20556 -module EnclosingModule - abstract type AbstractTypeNoConstructors end -end -let - method_error = MethodError(EnclosingModule.AbstractTypeNoConstructors, ()) - - # Test that it shows a special message when no constructors have been defined by the user. - @test sprint(showerror, method_error) == - "MethodError: no constructors have been defined for $(EnclosingModule.AbstractTypeNoConstructors)" - - # Does it go back to previous behaviour when there *is* at least - # one constructor defined? - EnclosingModule.AbstractTypeNoConstructors(x, y) = x + y - @test startswith(sprint(showerror, method_error), - "MethodError: no method matching $(EnclosingModule.AbstractTypeNoConstructors)()") - - # Test that the 'default' sysimg.jl method is not displayed. - @test !contains(sprint(showerror, method_error), "where T at sysimg.jl") - - # Test that tab-completion will not show the 'default' sysimg.jl method. - for method_string in Base.REPLCompletions.complete_methods(:(EnclosingModule.AbstractTypeNoConstructors())) - @test !startswith(method_string, "(::Type{T})(arg) where T in Base at sysimg.jl") - end -end - -@testset "show for manually thrown MethodError" begin - global f21006 - - f21006() = nothing - # Normal method error should not warn about world age. - ex1 = try - f21006(()) - catch e - e - end::MethodError - str = sprint(Base.showerror, ex1) - @test startswith(str, "MethodError: no method matching f21006(::Tuple{})") - @test !contains(str, "The applicable method may be too new") - - # If newer applicable methods are available, world age should be mentioned. - f21006(x) = x - @test f21006(()) === () - str = sprint(Base.showerror, ex1) - @test startswith(str, "MethodError: no method matching f21006(::Tuple{})") - @test contains(str, "The applicable method may be too new: running in world age $(ex1.world)") - - # This method error should be thrown in a world new enough for `f21006(())`. - # Also makes sure it's printed correctly. - ex2 = try - f21006((), ()) - catch e - e - end::MethodError - str = sprint(Base.showerror, ex2) - @test startswith(str, "MethodError: no method matching f21006(::Tuple{}, ::Tuple{})") - @test !contains(str, "The applicable method may be too new") - - # If the method is available in the exception world or if the exception world is invalid, - # don't warn about world age - for ex3 in (MethodError(ex1.f, ex1.args, ex2.world), - MethodError(ex1.f, ex1.args, typemax(UInt))) - str = sprint(Base.showerror, ex3) - @test startswith(str, "MethodError: no method matching f21006(::Tuple{})") - @test !contains(str, "The applicable method may be too new") - end -end diff --git a/julia-0.6.3/share/julia/test/resolve.jl b/julia-0.6.3/share/julia/test/resolve.jl deleted file mode 100644 index f122ca2..0000000 --- a/julia-0.6.3/share/julia/test/resolve.jl +++ /dev/null @@ -1,542 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -using Base.Pkg.Types -using Base.Pkg.Query -using Base.Pkg.Resolve -using Base.Pkg.Resolve.VersionWeights -import Base.Pkg.PkgError - -# Check that VersionWeight keeps the same ordering as VersionNumber - -vlst = [ - v"0.0.0", - v"0.0.1", - v"0.1.0", - v"0.1.1", - v"1.0.0", - v"1.0.1", - v"1.1.0", - v"1.1.1", - v"1.0.0-pre", - v"1.0.0-pre1", - v"1.0.1-pre", - v"1.0.0-0.pre.2", - v"1.0.0-0.pre.3", - v"1.0.0-0.pre1.tst", - v"1.0.0-pre.1+0.1", - v"1.0.0-pre.1+0.1plus", - v"1.0.0-pre.1-+0.1plus", - v"1.0.0-pre.1-+0.1Plus", - v"1.0.0-pre.1-+0.1pLUs", - v"1.0.0-pre.1-+0.1pluS", - v"1.0.0+0.1plus", - v"1.0.0+0.1plus-", - v"1.0.0+-", - v"1.0.0-", - v"1.0.0+", - v"1.0.0--", - v"1.0.0---", - v"1.0.0--+-", - v"1.0.0+--", - v"1.0.0+-.-", - v"1.0.0+0.-", - v"1.0.0+-.0", - v"1.0.0-a+--", - v"1.0.0-a+-.-", - v"1.0.0-a+0.-", - v"1.0.0-a+-.0" - ] - -for v1 in vlst, v2 in vlst - vw1 = VersionWeight(v1) - vw2 = VersionWeight(v2) - clt = v1 < v2 - @test clt == (vw1 < vw2) - ceq = v1 == v2 - @test ceq == (vw1 == vw2) -end - -# auxiliary functions - -function deps_from_data(deps_data) - deps = Dict{String,Dict{VersionNumber,Available}}() - for d in deps_data - p = d[1]; vn = d[2]; r = d[3:end] - if !haskey(deps, p) - deps[p] = Dict{VersionNumber,Available}() - end - if !haskey(deps[p], vn) - deps[p][vn] = Available("$(p)_$(vn)_sha1", Dict{String,VersionSet}()) - end - isempty(r) && continue - rp = r[1] - if length(r) > 1 - rvs = VersionSet(VersionNumber[r[2:end]...]) - else - rvs = VersionSet() - end - deps[p][vn].requires[rp] = rvs - end - deps -end -function reqs_from_data(reqs_data) - reqs = Dict{String,VersionSet}() - for r in reqs_data - p = r[1] - reqs[p] = VersionSet(VersionNumber[r[2:end]...]) - end - reqs -end -function sanity_tst(deps_data, expected_result; pkgs=[]) - deps = deps_from_data(deps_data) - #println("deps=$deps") - #println() - result = sanity_check(deps, Set(String[pkgs...])) - length(result) == length(expected_result) || return false - for (p, vn, pp) in result - (p, vn) ∈ expected_result || return false - end - return true -end -sanity_tst(deps_data; kw...) = sanity_tst(deps_data, []; kw...) - -function resolve_tst(deps_data, reqs_data, want_data = nothing) - deps = deps_from_data(deps_data) - reqs = reqs_from_data(reqs_data) - - #println() - #println("deps=$deps") - #println("reqs=$reqs") - deps = Query.prune_dependencies(reqs, deps) - want = resolve(reqs, deps) - return want == want_data -end - -## DEPENDENCY SCHEME 1: TWO PACKAGES, DAG -deps_data = Any[ - ["A", v"1", "B", v"1"], - ["A", v"2", "B", v"2"], - ["B", v"1"], - ["B", v"2"] -] - -@test sanity_tst(deps_data) -@test sanity_tst(deps_data, pkgs=["A", "B"]) -@test sanity_tst(deps_data, pkgs=["B"]) -@test sanity_tst(deps_data, pkgs=["A"]) - -# require just B -reqs_data = Any[ - ["B"] -] - -want_data = Dict("B"=>v"2") -@test resolve_tst(deps_data, reqs_data, want_data) - -# require just A: must bring in B -reqs_data = Any[ - ["A"] -] -want_data = Dict("A"=>v"2", "B"=>v"2") -@test resolve_tst(deps_data, reqs_data, want_data) - - -## DEPENDENCY SCHEME 2: TWO PACKAGES, CYCLIC -deps_data = Any[ - ["A", v"1", "B", v"2"], - ["A", v"2", "B", v"1"], - ["B", v"1", "A", v"2"], - ["B", v"2", "A", v"1"] -] - -@test sanity_tst(deps_data) - -# require just A -reqs_data = Any[ - ["A"] -] -want_data = Dict("A"=>v"2", "B"=>v"2") -@test resolve_tst(deps_data, reqs_data, want_data) - -# require just B, force lower version -reqs_data = Any[ - ["B", v"1", v"2"] -] -want_data = Dict("A"=>v"2", "B"=>v"1") -@test resolve_tst(deps_data, reqs_data, want_data) - -# require just A, force lower version -reqs_data = Any[ - ["A", v"1", v"2"] -] -want_data = Dict("A"=>v"1", "B"=>v"2") -@test resolve_tst(deps_data, reqs_data, want_data) - - -## DEPENDENCY SCHEME 3: THREE PACKAGES, CYCLIC, TWO MUTUALLY EXCLUSIVE SOLUTIONS -deps_data = Any[ - ["A", v"1", "B", v"2"], - ["A", v"2", "B", v"1", v"2"], - ["B", v"1", "C", v"2"], - ["B", v"2", "C", v"1", v"2"], - ["C", v"1", "A", v"1", v"2"], - ["C", v"2", "A", v"2"] -] - -@test sanity_tst(deps_data) - -# require just A (must choose solution which has the highest version for A) -reqs_data = Any[ - ["A"] -] -want_data = Dict("A"=>v"2", "B"=>v"1", "C"=>v"2") -@test resolve_tst(deps_data, reqs_data, want_data) - -# require just B (must choose solution which has the highest version for B) -reqs_data = Any[ - ["B"] -] -want_data = Dict("A"=>v"1", "B"=>v"2", "C"=>v"1") -@test resolve_tst(deps_data, reqs_data, want_data) - -# require just A, force lower version -reqs_data = Any[ - ["A", v"1", v"2"] -] -want_data = Dict("A"=>v"1", "B"=>v"2", "C"=>v"1") -@test resolve_tst(deps_data, reqs_data, want_data) - -# require A and C, incompatible versions -reqs_data = Any[ - ["A", v"1", v"2"], - ["C", v"2"] -] -@test_throws PkgError resolve_tst(deps_data, reqs_data) - - -## DEPENDENCY SCHEME 4: TWO PACKAGES, DAG, WITH TRIVIAL INCONSISTENCY -deps_data = Any[ - ["A", v"1", "B", v"2"], - ["B", v"1"] -] - -@test sanity_tst(deps_data, [("A", v"1")]) -@test sanity_tst(deps_data, [("A", v"1")], pkgs=["B"]) - -# require B (must not give errors) -reqs_data = Any[ - ["B"] -] -want_data = Dict("B"=>v"1") -@test resolve_tst(deps_data, reqs_data, want_data) - - -## DEPENDENCY SCHEME 5: THREE PACKAGES, DAG, WITH IMPLICIT INCONSISTENCY -deps_data = Any[ - ["A", v"1", "B", v"2"], - ["A", v"1", "C", v"2"], - ["A", v"2", "B", v"1", v"2"], - ["A", v"2", "C", v"1", v"2"], - ["B", v"1", "C", v"2"], - ["B", v"2", "C", v"2"], - ["C", v"1"], - ["C", v"2"] -] - -@test sanity_tst(deps_data, [("A", v"2")]) -@test sanity_tst(deps_data, [("A", v"2")], pkgs=["B"]) -@test sanity_tst(deps_data, [("A", v"2")], pkgs=["C"]) - -# require A, any version (must use the highest non-inconsistent) -reqs_data = Any[ - ["A"] -] -want_data = Dict("A"=>v"1", "B"=>v"2", "C"=>v"2") -@test resolve_tst(deps_data, reqs_data, want_data) - -# require A, force highest version (impossible) -reqs_data = Any[ - ["A", v"2"] -] -@test_throws PkgError resolve_tst(deps_data, reqs_data) - - -## DEPENDENCY SCHEME 6: TWO PACKAGES, CYCLIC, TOTALLY INCONSISTENT -deps_data = Any[ - ["A", v"1", "B", v"2"], - ["A", v"2", "B", v"1", v"2"], - ["B", v"1", "A", v"1", v"2"], - ["B", v"2", "A", v"2"] -] - -@test sanity_tst(deps_data, [("A", v"1"), ("A", v"2"), - ("B", v"1"), ("B", v"2")]) - -# require A (impossible) -reqs_data = Any[ - ["A"] -] -@test_throws PkgError resolve_tst(deps_data, reqs_data) - -# require B (impossible) -reqs_data = Any[ - ["B"] -] -@test_throws PkgError resolve_tst(deps_data, reqs_data) - - -## DEPENDENCY SCHEME 7: THREE PACKAGES, CYCLIC, WITH INCONSISTENCY -deps_data = Any[ - ["A", v"1", "B", v"1", v"2"], - ["A", v"2", "B", v"2"], - ["B", v"1", "C", v"1", v"2"], - ["B", v"2", "C", v"2"], - ["C", v"1", "A", v"2"], - ["C", v"2", "A", v"2"], -] - -@test sanity_tst(deps_data, [("A", v"1"), ("B", v"1"), - ("C", v"1")]) - -# require A -reqs_data = Any[ - ["A"] -] -want_data = Dict("A"=>v"2", "B"=>v"2", "C"=>v"2") -@test resolve_tst(deps_data, reqs_data, want_data) - -# require C -reqs_data = Any[ - ["C"] -] -want_data = Dict("A"=>v"2", "B"=>v"2", "C"=>v"2") -@test resolve_tst(deps_data, reqs_data, want_data) - -# require C, lowest version (impossible) -reqs_data = Any[ - ["C", v"1", v"2"] -] -@test_throws PkgError resolve_tst(deps_data, reqs_data) - - -## DEPENDENCY SCHEME 8: THREE PACKAGES, CYCLIC, TOTALLY INCONSISTENT -deps_data = Any[ - ["A", v"1", "B", v"1", v"2"], - ["A", v"2", "B", v"2"], - ["B", v"1", "C", v"1", v"2"], - ["B", v"2", "C", v"2"], - ["C", v"1", "A", v"2"], - ["C", v"2", "A", v"1", v"2"], -] - -@test sanity_tst(deps_data, [("A", v"1"), ("A", v"2"), - ("B", v"1"), ("B", v"2"), - ("C", v"1"), ("C", v"2")]) - -# require A (impossible) -reqs_data = Any[ - ["A"] -] -@test_throws PkgError resolve_tst(deps_data, reqs_data) - -# require B (impossible) -reqs_data = Any[ - ["B"] -] -@test_throws PkgError resolve_tst(deps_data, reqs_data) - -# require C (impossible) -reqs_data = Any[ - ["C"] -] -@test_throws PkgError resolve_tst(deps_data, reqs_data) - -## DEPENDENCY SCHEME 9: SIX PACKAGES, DAG -deps_data = Any[ - ["A", v"1"], - ["A", v"2"], - ["A", v"3"], - ["B", v"1", "A", v"1", v"2"], - ["B", v"2", "A"], - ["C", v"1", "A", v"2", v"3"], - ["C", v"2", "A", v"2"], - ["D", v"1", "B", v"1"], - ["D", v"2", "B", v"2"], - ["E", v"1", "D"], - ["F", v"1", "A", v"1", v"3"], - ["F", v"1", "E"], - ["F", v"2", "C", v"2"], - ["F", v"2", "E"], -] - -@test sanity_tst(deps_data) - -# require just F -reqs_data = Any[ - ["F"] -] -want_data = Dict("A"=>v"3", "B"=>v"2", "C"=>v"2", - "D"=>v"2", "E"=>v"1", "F"=>v"2") -@test resolve_tst(deps_data, reqs_data, want_data) - -# require just F, lower version -reqs_data = Any[ - ["F", v"1", v"2"] -] -want_data = Dict("A"=>v"2", "B"=>v"2", "D"=>v"2", - "E"=>v"1", "F"=>v"1") -@test resolve_tst(deps_data, reqs_data, want_data) - -# require F and B; force lower B version -> must bring down F, A, and D versions too -reqs_data = Any[ - ["F"], - ["B", v"1", v"2"] -] -want_data = Dict("A"=>v"1", "B"=>v"1", "D"=>v"1", - "E"=>v"1", "F"=>v"1") -@test resolve_tst(deps_data, reqs_data, want_data) - -# require F and D; force lower D version -> must not bring down F version -reqs_data = Any[ - ["F"], - ["D", v"1", v"2"] -] -want_data = Dict("A"=>v"3", "B"=>v"2", "C"=>v"2", - "D"=>v"1", "E"=>v"1", "F"=>v"2") -@test resolve_tst(deps_data, reqs_data, want_data) - -# require F and C; force lower C version -> must bring down F and A versions -reqs_data = Any[ - ["F"], - ["C", v"1", v"2"] -] -want_data = Dict("A"=>v"2", "B"=>v"2", "C"=>v"1", - "D"=>v"2", "E"=>v"1", "F"=>v"1") -@test resolve_tst(deps_data, reqs_data, want_data) - -## DEPENDENCY SCHEME 10: SIX PACKAGES, DAG, WITH PRERELEASE/BUILD VERSIONS -deps_data = Any[ - ["A", v"1"], - ["A", v"2-rc.1"], - ["A", v"2-rc.1+bld"], - ["A", v"2"], - ["A", v"2.1.0"], - ["B", v"1", "A", v"1", v"2-"], - ["B", v"1.0.1-beta", "A", v"2-rc"], - ["B", v"1.0.1", "A"], - ["C", v"1", "A", v"2-", v"2.1"], - ["C", v"1+BLD", "A", v"2-rc.1", v"2.1"], - ["C", v"2", "A", v"2-rc.1"], - ["D", v"1", "B", v"1"], - ["D", v"2", "B", v"1.0.1-"], - ["E", v"1-plztst", "D"], - ["E", v"1", "D"], - ["F", v"1.1", "A", v"1", v"2.1"], - ["F", v"1.1", "E", v"1"], - ["F", v"2-rc.1", "A", v"2-", v"2.1"], - ["F", v"2-rc.1", "C", v"1"], - ["F", v"2-rc.1", "E"], - ["F", v"2-rc.2", "A", v"2-", v"2.1"], - ["F", v"2-rc.2", "C", v"2"], - ["F", v"2-rc.2", "E"], - ["F", v"2", "C", v"2"], - ["F", v"2", "E"], -] - -@test sanity_tst(deps_data) - -# require just F -reqs_data = Any[ - ["F"] -] -want_data = Dict("A"=>v"2.1", "B"=>v"1.0.1", "C"=>v"2", - "D"=>v"2", "E"=>v"1", "F"=>v"2") -@test resolve_tst(deps_data, reqs_data, want_data) - -# require just F, lower version -reqs_data = Any[ - ["F", v"1", v"2-"] -] -want_data = Dict("A"=>v"2", "B"=>v"1.0.1", "D"=>v"2", - "E"=>v"1", "F"=>v"1.1") -@test resolve_tst(deps_data, reqs_data, want_data) - -# require F and B; force lower B version -> must bring down F, A, and D versions too -reqs_data = Any[ - ["F"], - ["B", v"1", v"1.0.1-"] -] -want_data = Dict("A"=>v"1", "B"=>v"1", "D"=>v"1", - "E"=>v"1", "F"=>v"1.1") -@test resolve_tst(deps_data, reqs_data, want_data) - -# require F and D; force lower D version -> must not bring down F version -reqs_data = Any[ - ["F"], - ["D", v"1", v"2"] -] -want_data = Dict("A"=>v"2.1", "B"=>v"1.0.1", "C"=>v"2", - "D"=>v"1", "E"=>v"1", "F"=>v"2") -@test resolve_tst(deps_data, reqs_data, want_data) - -# require F and C; force lower C version -> must bring down F and A versions -reqs_data = Any[ - ["F"], - ["C", v"1", v"2"] -] -want_data = Dict("A"=>v"2", "B"=>v"1.0.1", "C"=>v"1+BLD", - "D"=>v"2", "E"=>v"1", "F"=>v"2-rc.1") -@test resolve_tst(deps_data, reqs_data, want_data) - -## DEPENDENCY SCHEME 11: FIVE PACKAGES, SAME AS SCHEMES 5 + 1, UNCONNECTED -deps_data = Any[ - ["A", v"1", "B", v"2"], - ["A", v"1", "C", v"2"], - ["A", v"2", "B", v"1", v"2"], - ["A", v"2", "C", v"1", v"2"], - ["B", v"1", "C", v"2"], - ["B", v"2", "C", v"2"], - ["C", v"1"], - ["C", v"2"], - ["D", v"1", "E", v"1"], - ["D", v"2", "E", v"2"], - ["E", v"1"], - ["E", v"2"] -] - -@test sanity_tst(deps_data, [("A", v"2")]) -@test sanity_tst(deps_data, [("A", v"2")], pkgs=["B"]) -@test sanity_tst(deps_data, pkgs=["D"]) -@test sanity_tst(deps_data, pkgs=["E"]) -@test sanity_tst(deps_data, [("A", v"2")], pkgs=["B", "D"]) - -# require A, any version (must use the highest non-inconsistent) -reqs_data = Any[ - ["A"] -] -want_data = Dict("A"=>v"1", "B"=>v"2", "C"=>v"2") -@test resolve_tst(deps_data, reqs_data, want_data) - -# require just D: must bring in E -reqs_data = Any[ - ["D"] -] -want_data = Dict("D"=>v"2", "E"=>v"2") -@test resolve_tst(deps_data, reqs_data, want_data) - - -# require A and D, must be the merge of the previous two cases -reqs_data = Any[ - ["A"], - ["D"] -] -want_data = Dict("A"=>v"1", "B"=>v"2", "C"=>v"2", "D"=>v"2", "E"=>v"2") -@test resolve_tst(deps_data, reqs_data, want_data) - -## DEPENDENCY SCHEME 12: A REALISTIC EXAMPLE -## ref issue #21485 - -include("resolvedata1.jl") - -@test sanity_tst(deps_data, problematic_data) -@test resolve_tst(deps_data, reqs_data, want_data) diff --git a/julia-0.6.3/share/julia/test/resolvedata1.jl b/julia-0.6.3/share/julia/test/resolvedata1.jl deleted file mode 100644 index 26d6c64..0000000 --- a/julia-0.6.3/share/julia/test/resolvedata1.jl +++ /dev/null @@ -1,2853 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -deps_data = Any[ - ["ASTInterpreter", v"0.0.1", "AbstractTrees", v"0.0.1", v"0.1.0"], - ["ASTInterpreter", v"0.0.1", "JuliaParser", v"0.7.1"], - ["ASTInterpreter", v"0.0.3", "AbstractTrees", v"0.0.2", v"0.1.0"], - ["ASTInterpreter", v"0.0.3", "JuliaParser", v"0.7.2"], - ["ASTInterpreter", v"0.0.4", "AbstractTrees", v"0.0.4", v"0.1.0"], - ["ASTInterpreter", v"0.0.4", "JuliaParser", v"0.7.2"], - ["AbstractTrees", v"0.0.1"], - ["AbstractTrees", v"0.0.3"], - ["AbstractTrees", v"0.0.4"], - ["AbstractTrees", v"0.1.0", "Compat", v"0.17.0"], - ["AlgebraicDiffEq", v"0.0.1", "DiffEqBase"], - ["AlgebraicDiffEq", v"0.0.1", "Parameters", v"0.5.0"], - ["AlgebraicDiffEq", v"0.0.1", "Sundials", v"0.3.0"], - ["AlgebraicDiffEq", v"0.0.2", "DiffEqBase"], - ["AlgebraicDiffEq", v"0.0.2", "Parameters", v"0.5.0"], - ["AlgebraicDiffEq", v"0.0.2", "Sundials", v"0.3.0"], - ["AlgebraicDiffEq", v"0.1.0", "DiffEqBase", v"0.2.0"], - ["AlgebraicDiffEq", v"0.1.0", "Parameters", v"0.5.0"], - ["AnsiColor", v"0.0.2"], - ["ArgParse", v"0.2.9", "Options"], - ["ArgParse", v"0.2.9", "TextWrap", v"0.1.0-"], - ["ArgParse", v"0.2.10", "Compat"], - ["ArgParse", v"0.2.10", "Options"], - ["ArgParse", v"0.2.10", "TextWrap", v"0.1.0-"], - ["ArgParse", v"0.2.12", "Options"], - ["ArgParse", v"0.2.12", "Compat", v"0.2.9"], - ["ArgParse", v"0.2.12", "TextWrap", v"0.1.0-"], - ["ArgParse", v"0.2.13", "Options"], - ["ArgParse", v"0.2.13", "Compat", v"0.7.3"], - ["ArgParse", v"0.2.13", "TextWrap", v"0.1.4"], - ["ArgParse", v"0.3.0", "Compat", v"0.7.3"], - ["ArgParse", v"0.3.0", "TextWrap", v"0.1.4"], - ["ArgParse", v"0.4.0", "Compat", v"0.8.0"], - ["ArgParse", v"0.4.0", "TextWrap", v"0.1.4"], - ["ArrayViews", v"0.1.1"], - ["ArrayViews", v"0.3.0"], - ["ArrayViews", v"0.4.5"], - ["ArrayViews", v"0.4.7"], - ["ArrayViews", v"0.4.8"], - ["ArrayViews", v"0.4.9"], - ["ArrayViews", v"0.4.11"], - ["ArrayViews", v"0.6.3"], - ["ArrayViews", v"0.6.4", "Compat"], - ["Atom", v"0.2.1", "CodeTools"], - ["Atom", v"0.2.1", "Hiccup"], - ["Atom", v"0.2.1", "JSON"], - ["Atom", v"0.2.1", "LNR"], - ["Atom", v"0.2.1", "Lazy"], - ["Atom", v"0.2.1", "Media"], - ["Atom", v"0.4.0", "Blink"], - ["Atom", v"0.4.0", "CodeTools"], - ["Atom", v"0.4.0", "Hiccup"], - ["Atom", v"0.4.0", "JSON"], - ["Atom", v"0.4.0", "LNR"], - ["Atom", v"0.4.0", "Lazy"], - ["Atom", v"0.4.0", "Media"], - ["Atom", v"0.4.0", "Reexport"], - ["Atom", v"0.4.6", "Blink"], - ["Atom", v"0.4.6", "CodeTools"], - ["Atom", v"0.4.6", "Hiccup"], - ["Atom", v"0.4.6", "JSON"], - ["Atom", v"0.4.6", "LNR"], - ["Atom", v"0.4.6", "Lazy"], - ["Atom", v"0.4.6", "MacroTools"], - ["Atom", v"0.4.6", "Media"], - ["Atom", v"0.4.6", "Reexport"], - ["Atom", v"0.4.6", "Requires"], - ["Atom", v"0.5.0", "ASTInterpreter"], - ["Atom", v"0.5.0", "Blink"], - ["Atom", v"0.5.0", "CodeTools"], - ["Atom", v"0.5.0", "Gallium"], - ["Atom", v"0.5.0", "Hiccup"], - ["Atom", v"0.5.0", "JSON"], - ["Atom", v"0.5.0", "LNR"], - ["Atom", v"0.5.0", "Lazy"], - ["Atom", v"0.5.0", "MacroTools"], - ["Atom", v"0.5.0", "Media"], - ["Atom", v"0.5.0", "Reexport"], - ["Atom", v"0.5.0", "Requires"], - ["Atom", v"0.5.2", "ASTInterpreter"], - ["Atom", v"0.5.2", "Blink"], - ["Atom", v"0.5.2", "CodeTools"], - ["Atom", v"0.5.2", "Gallium"], - ["Atom", v"0.5.2", "Hiccup"], - ["Atom", v"0.5.2", "JSON"], - ["Atom", v"0.5.2", "Juno"], - ["Atom", v"0.5.2", "LNR"], - ["Atom", v"0.5.2", "Lazy"], - ["Atom", v"0.5.2", "MacroTools"], - ["Atom", v"0.5.2", "Media"], - ["Atom", v"0.5.2", "Reexport"], - ["Atom", v"0.5.2", "Requires"], - ["Atom", v"0.5.8", "ASTInterpreter"], - ["Atom", v"0.5.8", "Blink"], - ["Atom", v"0.5.8", "CodeTools"], - ["Atom", v"0.5.8", "Gallium"], - ["Atom", v"0.5.8", "Hiccup"], - ["Atom", v"0.5.8", "JSON"], - ["Atom", v"0.5.8", "Juno"], - ["Atom", v"0.5.8", "LNR"], - ["Atom", v"0.5.8", "MacroTools"], - ["Atom", v"0.5.8", "Media"], - ["Atom", v"0.5.8", "Reexport"], - ["Atom", v"0.5.8", "Lazy", v"0.11.3"], - ["Atom", v"0.5.10", "ASTInterpreter"], - ["Atom", v"0.5.10", "Blink"], - ["Atom", v"0.5.10", "CodeTools"], - ["Atom", v"0.5.10", "Gallium"], - ["Atom", v"0.5.10", "Hiccup"], - ["Atom", v"0.5.10", "JSON"], - ["Atom", v"0.5.10", "LNR"], - ["Atom", v"0.5.10", "MacroTools"], - ["Atom", v"0.5.10", "Media"], - ["Atom", v"0.5.10", "Reexport"], - ["Atom", v"0.5.10", "Juno", v"0.2.6"], - ["Atom", v"0.5.10", "Lazy", v"0.11.3"], - ["AxisAlgorithms", v"0.1.6", "WoodburyMatrices"], - ["AxisAlgorithms", v"0.1.6", "Compat", v"0.8.0"], - ["AxisArrays", v"0.0.3", "IntervalSets"], - ["AxisArrays", v"0.0.3", "Iterators"], - ["AxisArrays", v"0.0.3", "RangeArrays"], - ["AxisArrays", v"0.1.2", "Compat", v"0.19.0"], - ["AxisArrays", v"0.1.2", "IntervalSets"], - ["AxisArrays", v"0.1.2", "Iterators"], - ["AxisArrays", v"0.1.2", "RangeArrays"], - ["BinDeps", v"0.2.0"], - ["BinDeps", v"0.2.4", "URIParser"], - ["BinDeps", v"0.2.14", "URIParser"], - ["BinDeps", v"0.3.4", "URIParser"], - ["BinDeps", v"0.3.4", "SHA", v"0.0.0", v"0.0.3"], - ["BinDeps", v"0.3.5", "URIParser"], - ["BinDeps", v"0.3.5", "SHA", v"0.0.3"], - ["BinDeps", v"0.3.8", "SHA"], - ["BinDeps", v"0.3.8", "URIParser"], - ["BinDeps", v"0.3.10", "Compat", v"0.3.6"], - ["BinDeps", v"0.3.10", "SHA"], - ["BinDeps", v"0.3.10", "URIParser"], - ["BinDeps", v"0.3.15", "Compat", v"0.4.0"], - ["BinDeps", v"0.3.15", "SHA"], - ["BinDeps", v"0.3.15", "URIParser"], - ["BinDeps", v"0.3.21", "Compat", v"0.7.1"], - ["BinDeps", v"0.3.21", "SHA"], - ["BinDeps", v"0.3.21", "URIParser"], - ["BinDeps", v"0.3.23", "URIParser"], - ["BinDeps", v"0.3.23", "Compat", v"0.8.4"], - ["BinDeps", v"0.3.23", "SHA"], - ["BinDeps", v"0.4.2", "Compat", v"0.8.4"], - ["BinDeps", v"0.4.2", "SHA"], - ["BinDeps", v"0.4.2", "URIParser"], - ["BinDeps", v"0.4.5", "Compat", v"0.8.4"], - ["BinDeps", v"0.4.5", "SHA"], - ["BinDeps", v"0.4.5", "URIParser"], - ["BinDeps", v"0.4.7", "Compat", v"0.17.0"], - ["BinDeps", v"0.4.7", "SHA"], - ["BinDeps", v"0.4.7", "URIParser"], - ["Blink", v"0.1.4", "JSON"], - ["Blink", v"0.1.4", "Lazy"], - ["Blink", v"0.1.4", "Requires"], - ["Blink", v"0.1.5", "JSON"], - ["Blink", v"0.1.5", "Lazy"], - ["Blink", v"0.1.5", "MacroTools"], - ["Blink", v"0.1.5", "Requires"], - ["Blink", v"0.2.0", "HttpServer"], - ["Blink", v"0.2.0", "JSON"], - ["Blink", v"0.2.0", "Lazy"], - ["Blink", v"0.2.0", "MacroTools"], - ["Blink", v"0.2.0", "Mustache"], - ["Blink", v"0.2.0", "Reexport"], - ["Blink", v"0.2.0", "Requires"], - ["Blink", v"0.2.0", "WebSockets"], - ["Blink", v"0.2.1", "HttpServer"], - ["Blink", v"0.2.1", "JSON"], - ["Blink", v"0.2.1", "Lazy"], - ["Blink", v"0.2.1", "MacroTools"], - ["Blink", v"0.2.1", "Mustache"], - ["Blink", v"0.2.1", "Mux"], - ["Blink", v"0.2.1", "Reexport"], - ["Blink", v"0.2.1", "Requires"], - ["Blink", v"0.2.1", "WebSockets"], - ["Blink", v"0.3.4", "BinDeps"], - ["Blink", v"0.3.4", "HttpServer"], - ["Blink", v"0.3.4", "JSON"], - ["Blink", v"0.3.4", "Lazy"], - ["Blink", v"0.3.4", "MacroTools"], - ["Blink", v"0.3.4", "Mustache"], - ["Blink", v"0.3.4", "Mux"], - ["Blink", v"0.3.4", "Reexport"], - ["Blink", v"0.3.4", "Requires"], - ["Blink", v"0.3.4", "WebSockets"], - ["Blink", v"0.4.1", "BinDeps"], - ["Blink", v"0.4.1", "HttpServer"], - ["Blink", v"0.4.1", "Mustache"], - ["Blink", v"0.4.1", "Reexport"], - ["Blink", v"0.4.1", "Requires"], - ["Blink", v"0.4.1", "Compat", v"0.8.6"], - ["Blink", v"0.4.1", "JSON"], - ["Blink", v"0.4.1", "Lazy"], - ["Blink", v"0.4.1", "MacroTools"], - ["Blink", v"0.4.1", "Mux"], - ["Blink", v"0.4.1", "WebSockets"], - ["Blink", v"0.5.1", "BinDeps"], - ["Blink", v"0.5.1", "HttpServer"], - ["Blink", v"0.5.1", "Compat", v"0.8.6"], - ["Blink", v"0.5.1", "JSON"], - ["Blink", v"0.5.1", "MacroTools"], - ["Blink", v"0.5.1", "Mustache"], - ["Blink", v"0.5.1", "Lazy", v"0.11.3"], - ["Blink", v"0.5.1", "Mux"], - ["Blink", v"0.5.1", "Reexport"], - ["Blink", v"0.5.1", "WebSockets"], - ["Blocks", v"0.0.4"], - ["Blocks", v"0.1.0", "Compat"], - ["Blosc", v"0.1.1", "BinDeps"], - ["Blosc", v"0.1.5", "BinDeps"], - ["Blosc", v"0.1.5", "Compat"], - ["Blosc", v"0.2.0", "BinDeps"], - ["Blosc", v"0.2.0", "Compat", v"0.8.0"], - ["COFF", v"0.0.2", "DWARF"], - ["COFF", v"0.0.2", "ObjFileBase"], - ["COFF", v"0.0.2", "StructIO"], - ["CRC", v"0.1.0", "ArgParse"], - ["CRC", v"0.1.0", "Zlib"], - ["CRC", v"1.1.1", "ArgParse"], - ["CRC", v"1.1.1", "Compat"], - ["CRC", v"1.2.0", "ArgParse"], - ["Calculus", v"0.1.5"], - ["Calculus", v"0.1.6", "Compat"], - ["Calculus", v"0.1.14", "Compat", v"0.4.0"], - ["Calculus", v"0.1.15", "Compat", v"0.4.0"], - ["Calculus", v"0.2.0", "Compat", v"0.4.0"], - ["Calculus", v"0.2.2", "Compat", v"0.17.0"], - ["Calendar", v"0.4.3", "ICU"], - ["CatIndices", v"0.0.2", "CustomUnitRanges"], - ["CatIndices", v"0.0.2", "OffsetArrays"], - ["ChunkedArrays", v"0.0.1", "Compat"], - ["ChunkedArrays", v"0.0.1", "EllipsisNotation"], - ["ChunkedArrays", v"0.0.2", "Compat"], - ["ChunkedArrays", v"0.0.2", "EllipsisNotation"], - ["ChunkedArrays", v"0.1.0", "Compat"], - ["ChunkedArrays", v"0.1.0", "EllipsisNotation"], - ["ChunkedArrays", v"0.1.1", "EllipsisNotation", v"0.0.2"], - ["CodeTools", v"0.1.0", "JuliaParser"], - ["CodeTools", v"0.1.0", "LNR"], - ["CodeTools", v"0.1.0", "Lazy"], - ["CodeTools", v"0.1.0", "MacroTools"], - ["CodeTools", v"0.2.0", "Compat"], - ["CodeTools", v"0.2.0", "JuliaParser"], - ["CodeTools", v"0.2.0", "LNR"], - ["CodeTools", v"0.2.0", "Lazy"], - ["CodeTools", v"0.2.0", "MacroTools"], - ["CodeTools", v"0.4.1", "Compat"], - ["CodeTools", v"0.4.1", "JuliaParser"], - ["CodeTools", v"0.4.1", "LNR"], - ["CodeTools", v"0.4.1", "Lazy"], - ["CodeTools", v"0.4.1", "MacroTools"], - ["CodeTools", v"0.4.1", "Requires"], - ["CodeTools", v"0.4.3", "LNR"], - ["CodeTools", v"0.4.3", "Lazy"], - ["CodeTools", v"0.4.3", "MacroTools"], - ["Codecs", v"0.1.0", "Iterators"], - ["Codecs", v"0.1.3"], - ["Codecs", v"0.1.5", "Compat"], - ["Codecs", v"0.2.0", "Compat", v"0.7.20"], - ["Codecs", v"0.3.0", "Compat", v"0.17.0"], - ["ColorTypes", v"0.0.1", "FixedPointNumbers", v"0.0.0-", v"0.3.0"], - ["ColorTypes", v"0.0.1", "FixedSizeArrays"], - ["ColorTypes", v"0.1.7", "Compat"], - ["ColorTypes", v"0.1.7", "Docile"], - ["ColorTypes", v"0.1.7", "FixedPointNumbers", v"0.0.0-", v"0.3.0"], - ["ColorTypes", v"0.2.6", "FixedPointNumbers", v"0.1.0", v"0.3.0"], - ["ColorTypes", v"0.2.8", "FixedPointNumbers", v"0.1.0", v"0.3.0"], - ["ColorTypes", v"0.2.12", "FixedPointNumbers", v"0.1.0", v"0.3.0"], - ["ColorTypes", v"0.3.0", "FixedPointNumbers", v"0.3.0"], - ["ColorTypes", v"0.3.2", "Compat", v"0.16.0"], - ["ColorTypes", v"0.3.2", "FixedPointNumbers", v"0.3.0"], - ["ColorTypes", v"0.3.3", "Compat", v"0.17.0"], - ["ColorTypes", v"0.3.3", "FixedPointNumbers", v"0.3.0"], - ["ColorTypes", v"0.3.5", "Compat", v"0.18.0"], - ["ColorTypes", v"0.3.5", "FixedPointNumbers", v"0.3.0"], - ["ColorTypes", v"0.4.1", "Compat", v"0.18.0"], - ["ColorTypes", v"0.4.1", "FixedPointNumbers", v"0.3.0"], - ["ColorVectorSpace", v"0.0.5", "ColorTypes"], - ["ColorVectorSpace", v"0.0.5", "Compat"], - ["ColorVectorSpace", v"0.0.5", "FixedPointNumbers", v"0.0.0-", v"0.3.0"], - ["ColorVectorSpace", v"0.1.7", "ColorTypes", v"0.2.0"], - ["ColorVectorSpace", v"0.1.7", "FixedPointNumbers", v"0.1.0", v"0.3.0"], - ["ColorVectorSpace", v"0.1.8", "ColorTypes", v"0.2.0"], - ["ColorVectorSpace", v"0.1.8", "Compat", v"0.9.1"], - ["ColorVectorSpace", v"0.1.8", "FixedPointNumbers", v"0.1.0", v"0.3.0"], - ["ColorVectorSpace", v"0.1.10", "ColorTypes", v"0.2.7"], - ["ColorVectorSpace", v"0.1.10", "Compat", v"0.9.1"], - ["ColorVectorSpace", v"0.1.10", "FixedPointNumbers", v"0.1.8", v"0.3.0"], - ["ColorVectorSpace", v"0.1.12", "ColorTypes", v"0.2.7"], - ["ColorVectorSpace", v"0.1.12", "Compat", v"0.9.1"], - ["ColorVectorSpace", v"0.1.12", "FixedPointNumbers", v"0.1.8", v"0.3.0"], - ["ColorVectorSpace", v"0.2.0", "ColorTypes", v"0.3.0"], - ["ColorVectorSpace", v"0.2.0", "Compat", v"0.9.1"], - ["ColorVectorSpace", v"0.2.0", "FixedPointNumbers", v"0.3.0"], - ["ColorVectorSpace", v"0.3.0", "ColorTypes", v"0.3.3"], - ["ColorVectorSpace", v"0.3.0", "Colors", v"0.7.1"], - ["ColorVectorSpace", v"0.3.0", "Compat", v"0.9.1"], - ["ColorVectorSpace", v"0.3.0", "FixedPointNumbers", v"0.3.0"], - ["ColorVectorSpace", v"0.3.0", "StatsBase", v"0.8.2"], - ["ColorVectorSpace", v"0.4.0", "ColorTypes", v"0.3.3"], - ["ColorVectorSpace", v"0.4.0", "Colors", v"0.7.1"], - ["ColorVectorSpace", v"0.4.0", "Compat", v"0.18.0"], - ["ColorVectorSpace", v"0.4.0", "FixedPointNumbers", v"0.3.0"], - ["ColorVectorSpace", v"0.4.0", "StatsBase", v"0.8.2"], - ["ColorVectorSpace", v"0.4.2", "ColorTypes", v"0.4.0"], - ["ColorVectorSpace", v"0.4.2", "Colors", v"0.7.1"], - ["ColorVectorSpace", v"0.4.2", "Compat", v"0.18.0"], - ["ColorVectorSpace", v"0.4.2", "FixedPointNumbers", v"0.3.0"], - ["ColorVectorSpace", v"0.4.2", "StatsBase", v"0.8.2"], - ["Colors", v"0.4.7", "Compat", v"0.2.0"], - ["Colors", v"0.4.7", "Graphics", v"0.1.0"], - ["Colors", v"0.4.7", "FixedPointNumbers", v"0.0.0-", v"0.3.0"], - ["Colors", v"0.5.0", "ColorTypes"], - ["Colors", v"0.5.0", "Reexport"], - ["Colors", v"0.5.0", "Compat", v"0.2.0"], - ["Colors", v"0.5.0", "Graphics", v"0.1.0"], - ["Colors", v"0.5.0", "FixedPointNumbers", v"0.0.0-", v"0.3.0"], - ["Colors", v"0.5.4", "ColorTypes"], - ["Colors", v"0.5.4", "Reexport"], - ["Colors", v"0.5.4", "Compat", v"0.2.0"], - ["Colors", v"0.5.4", "FixedPointNumbers", v"0.0.0-", v"0.3.0"], - ["Colors", v"0.6.2", "Reexport"], - ["Colors", v"0.6.2", "ColorTypes", v"0.2.0"], - ["Colors", v"0.6.2", "FixedPointNumbers", v"0.1.0", v"0.3.0"], - ["Colors", v"0.6.4", "Compat"], - ["Colors", v"0.6.4", "Reexport"], - ["Colors", v"0.6.4", "ColorTypes", v"0.2.0"], - ["Colors", v"0.6.4", "FixedPointNumbers", v"0.1.0", v"0.3.0"], - ["Colors", v"0.6.6", "Reexport"], - ["Colors", v"0.6.6", "ColorTypes", v"0.2.0"], - ["Colors", v"0.6.6", "Compat", v"0.8.0"], - ["Colors", v"0.6.6", "FixedPointNumbers", v"0.1.0", v"0.3.0"], - ["Colors", v"0.6.7", "Reexport"], - ["Colors", v"0.6.7", "ColorTypes", v"0.2.0"], - ["Colors", v"0.6.7", "Compat", v"0.9.1"], - ["Colors", v"0.6.7", "FixedPointNumbers", v"0.1.0", v"0.3.0"], - ["Colors", v"0.6.8", "Reexport"], - ["Colors", v"0.6.8", "ColorTypes", v"0.2.7"], - ["Colors", v"0.6.8", "Compat", v"0.9.1"], - ["Colors", v"0.6.8", "FixedPointNumbers", v"0.1.8", v"0.3.0"], - ["Colors", v"0.6.9", "Reexport"], - ["Colors", v"0.6.9", "ColorTypes", v"0.2.9"], - ["Colors", v"0.6.9", "Compat", v"0.9.1"], - ["Colors", v"0.6.9", "FixedPointNumbers", v"0.1.8", v"0.3.0"], - ["Colors", v"0.7.0", "Reexport"], - ["Colors", v"0.7.0", "ColorTypes", v"0.3.0"], - ["Colors", v"0.7.0", "Compat", v"0.9.1"], - ["Colors", v"0.7.0", "FixedPointNumbers", v"0.3.0"], - ["Colors", v"0.7.1", "Reexport"], - ["Colors", v"0.7.1", "ColorTypes", v"0.3.0"], - ["Colors", v"0.7.1", "Compat", v"0.9.1"], - ["Colors", v"0.7.1", "FixedPointNumbers", v"0.3.0"], - ["Colors", v"0.7.2", "Reexport"], - ["Colors", v"0.7.2", "ColorTypes", v"0.3.0"], - ["Colors", v"0.7.2", "Compat", v"0.17.0"], - ["Colors", v"0.7.2", "FixedPointNumbers", v"0.3.0"], - ["Colors", v"0.7.3", "ColorTypes", v"0.3.0"], - ["Colors", v"0.7.3", "Compat", v"0.18.0"], - ["Colors", v"0.7.3", "FixedPointNumbers", v"0.3.0"], - ["Colors", v"0.7.3", "Reexport"], - ["Combinatorics", v"0.2.0", "Compat"], - ["Combinatorics", v"0.2.0", "Iterators"], - ["Combinatorics", v"0.2.0", "Polynomials"], - ["Combinatorics", v"0.3.2", "Iterators"], - ["Combinatorics", v"0.3.2", "Polynomials"], - ["Combinatorics", v"0.4.0", "Compat", v"0.18.0"], - ["Combinatorics", v"0.4.0", "Iterators"], - ["Combinatorics", v"0.4.0", "Polynomials"], - ["Compat", v"0.8.1"], - ["Compat", v"0.8.3"], - ["Compat", v"0.8.4"], - ["Compat", v"0.8.5"], - ["Compat", v"0.8.6"], - ["Compat", v"0.8.7"], - ["Compat", v"0.8.8"], - ["Compat", v"0.9.0"], - ["Compat", v"0.9.1"], - ["Compat", v"0.9.3"], - ["Compat", v"0.9.4"], - ["Compat", v"0.10.0"], - ["Compat", v"0.11.0"], - ["Compat", v"0.12.0"], - ["Compat", v"0.13.0"], - ["Compat", v"0.15.0"], - ["Compat", v"0.16.2"], - ["Compat", v"0.17.0"], - ["Compat", v"0.18.0"], - ["Compat", v"0.23.0"], - ["Compat", v"0.24.0"], - ["ComputationalResources", v"0.0.1"], - ["ComputationalResources", v"0.0.2", "Compat", v"0.17.0"], - ["Conda", v"0.1.5", "BinDeps"], - ["Conda", v"0.1.5", "Compat"], - ["Conda", v"0.1.5", "JSON"], - ["Conda", v"0.1.9", "BinDeps"], - ["Conda", v"0.1.9", "Compat"], - ["Conda", v"0.1.9", "JSON"], - ["Conda", v"0.2.2", "BinDeps"], - ["Conda", v"0.2.2", "Compat", v"0.7.15"], - ["Conda", v"0.2.2", "JSON"], - ["Conda", v"0.2.4", "BinDeps"], - ["Conda", v"0.2.4", "Compat", v"0.8.0"], - ["Conda", v"0.2.4", "JSON"], - ["Conda", v"0.2.5", "BinDeps"], - ["Conda", v"0.2.5", "Compat", v"0.7.20"], - ["Conda", v"0.2.5", "JSON"], - ["Conda", v"0.3.2", "BinDeps"], - ["Conda", v"0.3.2", "Compat", v"0.8.0"], - ["Conda", v"0.3.2", "JSON"], - ["Conda", v"0.5.3", "BinDeps"], - ["Conda", v"0.5.3", "Compat", v"0.8.0"], - ["Conda", v"0.5.3", "JSON"], - ["CoordinateTransformations", v"0.1.0", "FixedSizeArrays"], - ["CoordinateTransformations", v"0.1.0", "Rotations"], - ["CoordinateTransformations", v"0.2.0", "Compat", v"0.8.0", v"0.11.0"], - ["CoordinateTransformations", v"0.2.0", "FixedSizeArrays", v"0.2.2"], - ["CoordinateTransformations", v"0.2.0", "Rotations", v"0.1.0", v"0.2.0+"], - ["CoordinateTransformations", v"0.3.2", "Rotations", v"0.3.0"], - ["CoordinateTransformations", v"0.3.2", "StaticArrays"], - ["CoordinateTransformations", v"0.4.0", "Rotations", v"0.3.0"], - ["CoordinateTransformations", v"0.4.0", "StaticArrays"], - ["CoordinateTransformations", v"0.4.1", "Compat", v"0.17.0"], - ["CoordinateTransformations", v"0.4.1", "Rotations", v"0.3.0"], - ["CoordinateTransformations", v"0.4.1", "StaticArrays"], - ["CustomUnitRanges", v"0.0.4"], - ["DWARF", v"0.0.0", "ELF"], - ["DWARF", v"0.0.0", "StrPack"], - ["DWARF", v"0.1.0", "AbstractTrees"], - ["DWARF", v"0.1.0", "ObjFileBase"], - ["DWARF", v"0.1.0", "StructIO"], - ["DataArrays", v"0.4.0", "Reexport"], - ["DataArrays", v"0.4.0", "SpecialFunctions"], - ["DataArrays", v"0.4.0", "Compat", v"0.8.6"], - ["DataArrays", v"0.4.0", "StatsBase", v"0.3.0"], - ["DataFrames", v"0.0.0", "Options"], - ["DataFrames", v"0.0.0", "StatsBase", v"0.0.0", v"0.8.3"], - ["DataFrames", v"0.2.2", "GZip"], - ["DataFrames", v"0.2.2", "Options"], - ["DataFrames", v"0.2.2", "StatsBase", v"0.0.0", v"0.8.3"], - ["DataFrames", v"0.3.10", "GZip"], - ["DataFrames", v"0.3.10", "StatsBase", v"0.0.0", v"0.8.3"], - ["DataFrames", v"0.3.11", "Blocks"], - ["DataFrames", v"0.3.11", "GZip"], - ["DataFrames", v"0.3.11", "StatsBase", v"0.0.0", v"0.8.3"], - ["DataFrames", v"0.3.16", "Blocks"], - ["DataFrames", v"0.3.16", "GZip"], - ["DataFrames", v"0.3.16", "SortingAlgorithms"], - ["DataFrames", v"0.3.16", "StatsBase", v"0.0.0", v"0.8.3"], - ["DataFrames", v"0.4.2", "Blocks"], - ["DataFrames", v"0.4.2", "DataArrays"], - ["DataFrames", v"0.4.2", "GZip"], - ["DataFrames", v"0.4.2", "SortingAlgorithms"], - ["DataFrames", v"0.4.2", "Stats"], - ["DataFrames", v"0.5.0", "Blocks"], - ["DataFrames", v"0.5.0", "GZip"], - ["DataFrames", v"0.5.0", "SortingAlgorithms"], - ["DataFrames", v"0.5.0", "DataArrays", v"0.1.0-"], - ["DataFrames", v"0.5.0", "StatsBase", v"0.3.0-", v"0.8.3"], - ["DataFrames", v"0.5.3", "Blocks"], - ["DataFrames", v"0.5.3", "DataArrays"], - ["DataFrames", v"0.5.3", "GZip"], - ["DataFrames", v"0.5.3", "SortingAlgorithms"], - ["DataFrames", v"0.5.3", "StatsBase", v"0.0.0", v"0.8.3"], - ["DataFrames", v"0.5.4", "Blocks"], - ["DataFrames", v"0.5.4", "DataArrays"], - ["DataFrames", v"0.5.4", "GZip"], - ["DataFrames", v"0.5.4", "Reexport"], - ["DataFrames", v"0.5.4", "SortingAlgorithms"], - ["DataFrames", v"0.5.4", "StatsBase", v"0.3.9+", v"0.8.3"], - ["DataFrames", v"0.5.11", "DataArrays"], - ["DataFrames", v"0.5.11", "GZip"], - ["DataFrames", v"0.5.11", "Reexport"], - ["DataFrames", v"0.5.11", "SortingAlgorithms"], - ["DataFrames", v"0.5.11", "StatsBase", v"0.3.9+", v"0.8.3"], - ["DataFrames", v"0.6.1", "Compat"], - ["DataFrames", v"0.6.1", "DataArrays"], - ["DataFrames", v"0.6.1", "GZip"], - ["DataFrames", v"0.6.1", "Reexport"], - ["DataFrames", v"0.6.1", "SortingAlgorithms"], - ["DataFrames", v"0.6.1", "StatsBase", v"0.3.9+", v"0.8.3"], - ["DataFrames", v"0.6.5", "Compat"], - ["DataFrames", v"0.6.5", "DataArrays"], - ["DataFrames", v"0.6.5", "Docile"], - ["DataFrames", v"0.6.5", "GZip"], - ["DataFrames", v"0.6.5", "Reexport"], - ["DataFrames", v"0.6.5", "SortingAlgorithms"], - ["DataFrames", v"0.6.5", "StatsBase", v"0.3.9+", v"0.8.3"], - ["DataFrames", v"0.6.10", "Compat"], - ["DataFrames", v"0.6.10", "Docile"], - ["DataFrames", v"0.6.10", "GZip"], - ["DataFrames", v"0.6.10", "Reexport"], - ["DataFrames", v"0.6.10", "SortingAlgorithms"], - ["DataFrames", v"0.6.10", "DataArrays", v"0.2.15"], - ["DataFrames", v"0.6.10", "StatsBase", v"0.3.9+", v"0.8.3"], - ["DataFrames", v"0.7.0", "Docile"], - ["DataFrames", v"0.7.0", "GZip"], - ["DataFrames", v"0.7.0", "Reexport"], - ["DataFrames", v"0.7.0", "SortingAlgorithms"], - ["DataFrames", v"0.7.0", "Compat", v"0.7.12"], - ["DataFrames", v"0.7.0", "DataArrays", v"0.2.15"], - ["DataFrames", v"0.7.0", "StatsBase", v"0.8.0", v"0.8.3"], - ["DataFrames", v"0.7.2", "Docile"], - ["DataFrames", v"0.7.2", "GZip"], - ["DataFrames", v"0.7.2", "Reexport"], - ["DataFrames", v"0.7.2", "SortingAlgorithms"], - ["DataFrames", v"0.7.2", "Compat", v"0.7.17"], - ["DataFrames", v"0.7.2", "DataArrays", v"0.2.15"], - ["DataFrames", v"0.7.2", "StatsBase", v"0.8.0", v"0.8.3"], - ["DataFrames", v"0.7.3", "Docile"], - ["DataFrames", v"0.7.3", "GZip"], - ["DataFrames", v"0.7.3", "Reexport"], - ["DataFrames", v"0.7.3", "SortingAlgorithms"], - ["DataFrames", v"0.7.3", "Compat", v"0.7.19"], - ["DataFrames", v"0.7.3", "DataArrays", v"0.2.15"], - ["DataFrames", v"0.7.3", "StatsBase", v"0.8.0", v"0.8.3"], - ["DataFrames", v"0.7.4", "Docile"], - ["DataFrames", v"0.7.4", "GZip"], - ["DataFrames", v"0.7.4", "Reexport"], - ["DataFrames", v"0.7.4", "SortingAlgorithms"], - ["DataFrames", v"0.7.4", "Compat", v"0.7.19"], - ["DataFrames", v"0.7.4", "DataArrays", v"0.3.4"], - ["DataFrames", v"0.7.4", "StatsBase", v"0.8.0", v"0.8.3"], - ["DataFrames", v"0.7.6", "Docile"], - ["DataFrames", v"0.7.6", "GZip"], - ["DataFrames", v"0.7.6", "Reexport"], - ["DataFrames", v"0.7.6", "SortingAlgorithms"], - ["DataFrames", v"0.7.6", "Compat", v"0.7.19"], - ["DataFrames", v"0.7.6", "DataArrays", v"0.3.4"], - ["DataFrames", v"0.7.6", "StatsBase", v"0.8.3"], - ["DataFrames", v"0.7.8", "GZip"], - ["DataFrames", v"0.7.8", "Reexport"], - ["DataFrames", v"0.7.8", "SortingAlgorithms"], - ["DataFrames", v"0.7.8", "Compat", v"0.8.0"], - ["DataFrames", v"0.7.8", "DataArrays", v"0.3.4"], - ["DataFrames", v"0.7.8", "StatsBase", v"0.8.3"], - ["DataFrames", v"0.8.0", "GZip"], - ["DataFrames", v"0.8.0", "Reexport"], - ["DataFrames", v"0.8.0", "SortingAlgorithms"], - ["DataFrames", v"0.8.0", "Compat", v"0.8.4"], - ["DataFrames", v"0.8.0", "DataArrays", v"0.3.4"], - ["DataFrames", v"0.8.0", "StatsBase", v"0.8.3"], - ["DataFrames", v"0.8.3", "GZip"], - ["DataFrames", v"0.8.3", "Reexport"], - ["DataFrames", v"0.8.3", "SortingAlgorithms"], - ["DataFrames", v"0.8.3", "Compat", v"0.8.4"], - ["DataFrames", v"0.8.3", "DataArrays", v"0.3.4"], - ["DataFrames", v"0.8.3", "FileIO", v"0.1.2"], - ["DataFrames", v"0.8.3", "StatsBase", v"0.8.3"], - ["DataFrames", v"0.8.4", "GZip"], - ["DataFrames", v"0.8.4", "Reexport"], - ["DataFrames", v"0.8.4", "SortingAlgorithms"], - ["DataFrames", v"0.8.4", "Compat", v"0.8.4"], - ["DataFrames", v"0.8.4", "DataArrays", v"0.3.4"], - ["DataFrames", v"0.8.4", "FileIO", v"0.1.2"], - ["DataFrames", v"0.8.4", "StatsBase", v"0.11.0"], - ["DataFrames", v"0.8.5", "GZip"], - ["DataFrames", v"0.8.5", "Reexport"], - ["DataFrames", v"0.8.5", "SortingAlgorithms"], - ["DataFrames", v"0.8.5", "Compat", v"0.8.4"], - ["DataFrames", v"0.8.5", "DataArrays", v"0.3.4"], - ["DataFrames", v"0.8.5", "FileIO", v"0.1.2"], - ["DataFrames", v"0.8.5", "Juno", v"0.2.4"], - ["DataFrames", v"0.8.5", "StatsBase", v"0.11.0"], - ["DataFrames", v"0.9.1", "GZip"], - ["DataFrames", v"0.9.1", "Reexport"], - ["DataFrames", v"0.9.1", "SortingAlgorithms"], - ["DataFrames", v"0.9.1", "Compat", v"0.18.0"], - ["DataFrames", v"0.9.1", "DataArrays", v"0.3.4"], - ["DataFrames", v"0.9.1", "FileIO", v"0.1.2"], - ["DataFrames", v"0.9.1", "StatsBase", v"0.11.0"], - ["DataStructures", v"0.4.5"], - ["DataStructures", v"0.4.6", "Compat", v"0.8.5"], - ["DataStructures", v"0.5.1", "Compat", v"0.9.4"], - ["DataStructures", v"0.5.2", "Compat", v"0.9.4"], - ["DataStructures", v"0.5.3", "Compat", v"0.17.0"], - ["Dates", v"0.4.4"], - ["DelayDiffEq", v"0.0.1", "Combinatorics"], - ["DelayDiffEq", v"0.0.1", "DataStructures", v"0.4.6"], - ["DelayDiffEq", v"0.0.1", "DiffEqBase", v"0.5.0", v"0.7.0"], - ["DelayDiffEq", v"0.0.1", "RecursiveArrayTools", v"0.1.2"], - ["DelayDiffEq", v"0.0.1", "OrdinaryDiffEq", v"1.0.0", v"1.2.0"], - ["DelayDiffEq", v"0.1.0", "Combinatorics"], - ["DelayDiffEq", v"0.1.0", "DataStructures", v"0.4.6"], - ["DelayDiffEq", v"0.1.0", "DiffEqBase", v"0.8.0", v"0.15.0"], - ["DelayDiffEq", v"0.1.0", "OrdinaryDiffEq", v"1.2.0"], - ["DelayDiffEq", v"0.1.0", "RecursiveArrayTools", v"0.2.0"], - ["DelayDiffEq", v"0.2.0", "Combinatorics"], - ["DelayDiffEq", v"0.2.0", "DataStructures", v"0.4.6"], - ["DelayDiffEq", v"0.2.0", "DiffEqBase", v"0.8.0", v"0.15.0"], - ["DelayDiffEq", v"0.2.0", "OrdinaryDiffEq", v"1.6.0"], - ["DelayDiffEq", v"0.2.0", "RecursiveArrayTools", v"0.2.0"], - ["DelayDiffEq", v"0.3.0", "Combinatorics"], - ["DelayDiffEq", v"0.3.0", "DataStructures", v"0.4.6"], - ["DelayDiffEq", v"0.3.0", "DiffEqBase", v"0.15.0"], - ["DelayDiffEq", v"0.3.0", "OrdinaryDiffEq", v"1.6.0"], - ["DelayDiffEq", v"0.3.0", "RecursiveArrayTools", v"0.2.0"], - ["DiffBase", v"0.0.2", "Compat", v"0.7.15"], - ["DiffBase", v"0.1.0", "Compat", v"0.7.15"], - ["DiffEqBase", v"0.0.1", "RecipesBase", v"0.1.0"], - ["DiffEqBase", v"0.0.4", "Ranges", v"0.0.1"], - ["DiffEqBase", v"0.0.4", "RecipesBase", v"0.1.0"], - ["DiffEqBase", v"0.1.0", "Parameters"], - ["DiffEqBase", v"0.1.0", "Ranges", v"0.0.1"], - ["DiffEqBase", v"0.1.0", "RecursiveArrayTools"], - ["DiffEqBase", v"0.1.0", "RecipesBase", v"0.1.0"], - ["DiffEqBase", v"0.1.1", "Parameters"], - ["DiffEqBase", v"0.1.1", "Ranges", v"0.0.1"], - ["DiffEqBase", v"0.1.1", "RecursiveArrayTools"], - ["DiffEqBase", v"0.1.1", "RecipesBase", v"0.1.0"], - ["DiffEqBase", v"0.1.2", "Parameters", v"0.5.0"], - ["DiffEqBase", v"0.1.2", "Ranges", v"0.0.1"], - ["DiffEqBase", v"0.1.2", "RecipesBase", v"0.1.0"], - ["DiffEqBase", v"0.1.2", "RecursiveArrayTools", v"0.0.2"], - ["DiffEqBase", v"0.1.3", "Parameters", v"0.5.0"], - ["DiffEqBase", v"0.1.3", "Ranges", v"0.0.1"], - ["DiffEqBase", v"0.1.3", "RecipesBase", v"0.1.0"], - ["DiffEqBase", v"0.1.3", "RecursiveArrayTools", v"0.0.2"], - ["DiffEqBase", v"0.2.0", "Parameters", v"0.5.0"], - ["DiffEqBase", v"0.2.0", "Ranges", v"0.0.1"], - ["DiffEqBase", v"0.2.0", "RecipesBase", v"0.1.0"], - ["DiffEqBase", v"0.2.0", "RecursiveArrayTools", v"0.0.2"], - ["DiffEqBase", v"0.3.2", "Parameters", v"0.5.0"], - ["DiffEqBase", v"0.3.2", "Ranges", v"0.0.1"], - ["DiffEqBase", v"0.3.2", "RecipesBase", v"0.1.0"], - ["DiffEqBase", v"0.3.2", "RecursiveArrayTools", v"0.0.2"], - ["DiffEqBase", v"0.3.2", "SimpleTraits", v"0.1.1"], - ["DiffEqBase", v"0.4.0", "Parameters", v"0.5.0"], - ["DiffEqBase", v"0.4.0", "Ranges", v"0.0.1"], - ["DiffEqBase", v"0.4.0", "RecipesBase", v"0.1.0"], - ["DiffEqBase", v"0.4.0", "RecursiveArrayTools", v"0.0.2"], - ["DiffEqBase", v"0.4.0", "SimpleTraits", v"0.1.1"], - ["DiffEqBase", v"0.4.1", "Parameters", v"0.5.0"], - ["DiffEqBase", v"0.4.1", "Ranges", v"0.0.1"], - ["DiffEqBase", v"0.4.1", "RecipesBase", v"0.1.0"], - ["DiffEqBase", v"0.4.1", "RecursiveArrayTools", v"0.0.2"], - ["DiffEqBase", v"0.4.1", "SimpleTraits", v"0.1.1"], - ["DiffEqBase", v"0.5.0", "Parameters", v"0.5.0"], - ["DiffEqBase", v"0.5.0", "Ranges", v"0.0.1"], - ["DiffEqBase", v"0.5.0", "RecipesBase", v"0.1.0"], - ["DiffEqBase", v"0.5.0", "RecursiveArrayTools", v"0.0.2"], - ["DiffEqBase", v"0.5.0", "SimpleTraits", v"0.1.1"], - ["DiffEqBase", v"0.6.0", "Parameters", v"0.5.0"], - ["DiffEqBase", v"0.6.0", "Ranges", v"0.0.1"], - ["DiffEqBase", v"0.6.0", "RecipesBase", v"0.1.0"], - ["DiffEqBase", v"0.6.0", "RecursiveArrayTools", v"0.0.2"], - ["DiffEqBase", v"0.6.0", "SimpleTraits", v"0.1.1"], - ["DiffEqBase", v"0.7.0", "Parameters", v"0.5.0"], - ["DiffEqBase", v"0.7.0", "Ranges", v"0.0.1"], - ["DiffEqBase", v"0.7.0", "RecipesBase", v"0.1.0"], - ["DiffEqBase", v"0.7.0", "RecursiveArrayTools", v"0.0.2"], - ["DiffEqBase", v"0.7.0", "SimpleTraits", v"0.1.1"], - ["DiffEqBase", v"0.10.0", "Parameters", v"0.5.0"], - ["DiffEqBase", v"0.10.0", "Ranges", v"0.0.1"], - ["DiffEqBase", v"0.10.0", "RecipesBase", v"0.1.0"], - ["DiffEqBase", v"0.10.0", "RecursiveArrayTools", v"0.2.0"], - ["DiffEqBase", v"0.10.0", "SimpleTraits", v"0.1.1"], - ["DiffEqBase", v"0.11.0", "Parameters", v"0.5.0"], - ["DiffEqBase", v"0.11.0", "Ranges", v"0.0.1"], - ["DiffEqBase", v"0.11.0", "RecipesBase", v"0.1.0"], - ["DiffEqBase", v"0.11.0", "RecursiveArrayTools", v"0.2.0"], - ["DiffEqBase", v"0.11.0", "SimpleTraits", v"0.1.1"], - ["DiffEqBase", v"0.12.1", "Compat", v"0.19.0"], - ["DiffEqBase", v"0.12.1", "Parameters", v"0.5.0"], - ["DiffEqBase", v"0.12.1", "Ranges", v"0.0.1"], - ["DiffEqBase", v"0.12.1", "RecipesBase", v"0.1.0"], - ["DiffEqBase", v"0.12.1", "RecursiveArrayTools", v"0.2.0"], - ["DiffEqBase", v"0.12.1", "SimpleTraits", v"0.1.1"], - ["DiffEqBase", v"0.13.0", "Compat", v"0.19.0"], - ["DiffEqBase", v"0.13.0", "Parameters", v"0.5.0"], - ["DiffEqBase", v"0.13.0", "Ranges", v"0.0.1"], - ["DiffEqBase", v"0.13.0", "RecipesBase", v"0.1.0"], - ["DiffEqBase", v"0.13.0", "RecursiveArrayTools", v"0.2.0"], - ["DiffEqBase", v"0.13.0", "SimpleTraits", v"0.1.1"], - ["DiffEqBase", v"0.14.0", "Compat", v"0.19.0"], - ["DiffEqBase", v"0.14.0", "Parameters", v"0.5.0"], - ["DiffEqBase", v"0.14.0", "Ranges", v"0.0.1"], - ["DiffEqBase", v"0.14.0", "RecipesBase", v"0.1.0"], - ["DiffEqBase", v"0.14.0", "RecursiveArrayTools", v"0.2.0"], - ["DiffEqBase", v"0.14.0", "SimpleTraits", v"0.1.1"], - ["DiffEqBase", v"0.15.0", "Compat", v"0.19.0"], - ["DiffEqBase", v"0.15.0", "Parameters", v"0.5.0"], - ["DiffEqBase", v"0.15.0", "Ranges", v"0.0.1"], - ["DiffEqBase", v"0.15.0", "RecipesBase", v"0.1.0"], - ["DiffEqBase", v"0.15.0", "RecursiveArrayTools", v"0.2.0"], - ["DiffEqBase", v"0.15.0", "SimpleTraits", v"0.1.1"], - ["DiffEqBiological", v"0.0.1", "DiffEqBase"], - ["DiffEqBiological", v"0.0.1", "DiffEqJump"], - ["DiffEqCallbacks", v"0.0.2", "DiffEqBase", v"0.6.0"], - ["DiffEqDevTools", v"0.0.1", "DiffEqBase", v"0.0.0", v"0.5.0"], - ["DiffEqDevTools", v"0.0.1", "FiniteElementDiffEq"], - ["DiffEqDevTools", v"0.0.1", "OrdinaryDiffEq"], - ["DiffEqDevTools", v"0.0.1", "StochasticDiffEq"], - ["DiffEqDevTools", v"0.0.1", "RecipesBase", v"0.1.0"], - ["DiffEqDevTools", v"0.1.0", "DiffEqBase", v"0.0.0", v"0.5.0"], - ["DiffEqDevTools", v"0.1.0", "FiniteElementDiffEq"], - ["DiffEqDevTools", v"0.1.0", "OrdinaryDiffEq"], - ["DiffEqDevTools", v"0.1.0", "RecursiveArrayTools"], - ["DiffEqDevTools", v"0.1.0", "StochasticDiffEq"], - ["DiffEqDevTools", v"0.1.0", "RecipesBase", v"0.1.0"], - ["DiffEqDevTools", v"0.1.1", "DiffEqBase", v"0.1.3", v"0.5.0"], - ["DiffEqDevTools", v"0.1.1", "FiniteElementDiffEq", v"0.0.5"], - ["DiffEqDevTools", v"0.1.1", "OrdinaryDiffEq", v"0.1.1"], - ["DiffEqDevTools", v"0.1.1", "RecipesBase", v"0.1.0"], - ["DiffEqDevTools", v"0.1.1", "RecursiveArrayTools", v"0.0.2"], - ["DiffEqDevTools", v"0.1.1", "StochasticDiffEq", v"0.0.5"], - ["DiffEqDevTools", v"0.2.0", "DiffEqBase", v"0.2.0", v"0.5.0"], - ["DiffEqDevTools", v"0.2.0", "FiniteElementDiffEq", v"0.0.5"], - ["DiffEqDevTools", v"0.2.0", "RecipesBase", v"0.1.0"], - ["DiffEqDevTools", v"0.2.0", "RecursiveArrayTools", v"0.0.2"], - ["DiffEqDevTools", v"0.3.0", "DiffEqBase", v"0.3.0", v"0.5.0"], - ["DiffEqDevTools", v"0.3.0", "RecipesBase", v"0.1.0"], - ["DiffEqDevTools", v"0.3.0", "RecursiveArrayTools", v"0.0.2"], - ["DiffEqDevTools", v"0.4.0", "DiffEqBase", v"0.4.0", v"0.5.0"], - ["DiffEqDevTools", v"0.4.0", "RecipesBase", v"0.1.0"], - ["DiffEqDevTools", v"0.4.0", "RecursiveArrayTools", v"0.1.2"], - ["DiffEqDevTools", v"0.5.0", "DiffEqBase", v"0.4.0", v"0.5.0"], - ["DiffEqDevTools", v"0.5.0", "DiffEqPDEBase"], - ["DiffEqDevTools", v"0.5.0", "RecipesBase", v"0.1.0"], - ["DiffEqDevTools", v"0.5.0", "RecursiveArrayTools", v"0.1.2"], - ["DiffEqDevTools", v"0.6.0", "DiffEqBase", v"0.5.0", v"0.15.0"], - ["DiffEqDevTools", v"0.6.0", "DiffEqPDEBase"], - ["DiffEqDevTools", v"0.6.0", "RecipesBase", v"0.1.0"], - ["DiffEqDevTools", v"0.6.0", "RecursiveArrayTools", v"0.1.2"], - ["DiffEqDevTools", v"0.7.0", "DiffEqBase", v"0.15.0"], - ["DiffEqDevTools", v"0.7.0", "DiffEqPDEBase"], - ["DiffEqDevTools", v"0.7.0", "RecipesBase", v"0.1.0"], - ["DiffEqDevTools", v"0.7.0", "RecursiveArrayTools", v"0.1.2"], - ["DiffEqFinancial", v"0.0.1", "DiffEqBase", v"0.0.0", v"0.15.0"], - ["DiffEqFinancial", v"0.0.1", "StochasticDiffEq"], - ["DiffEqFinancial", v"0.1.0", "DiffEqBase", v"0.15.0"], - ["DiffEqFinancial", v"0.1.0", "StochasticDiffEq"], - ["DiffEqJump", v"0.0.1", "DiffEqBase"], - ["DiffEqJump", v"0.2.0", "DiffEqBase"], - ["DiffEqJump", v"0.2.0", "RecursiveArrayTools"], - ["DiffEqJump", v"0.3.0", "DiffEqBase", v"0.13.0"], - ["DiffEqJump", v"0.3.0", "RecursiveArrayTools"], - ["DiffEqMonteCarlo", v"0.1.0", "DiffEqBase", v"0.6.0", v"0.14.0"], - ["DiffEqMonteCarlo", v"0.1.0", "RecipesBase", v"0.1.0"], - ["DiffEqMonteCarlo", v"0.2.0", "DiffEqBase", v"0.14.0"], - ["DiffEqPDEBase", v"0.0.1", "ChunkedArrays"], - ["DiffEqPDEBase", v"0.0.1", "DiffEqBase", v"0.0.0", v"0.15.0"], - ["DiffEqPDEBase", v"0.0.1", "RecipesBase"], - ["DiffEqPDEBase", v"0.0.1", "VectorizedRoutines"], - ["DiffEqPDEBase", v"0.0.3", "ChunkedArrays"], - ["DiffEqPDEBase", v"0.0.3", "DiffEqBase", v"0.4.1", v"0.15.0"], - ["DiffEqPDEBase", v"0.0.3", "RecipesBase"], - ["DiffEqPDEBase", v"0.0.3", "VectorizedRoutines"], - ["DiffEqPDEBase", v"0.1.0", "ChunkedArrays"], - ["DiffEqPDEBase", v"0.1.0", "Compat", v"0.17.0"], - ["DiffEqPDEBase", v"0.1.0", "DiffEqBase", v"0.4.1", v"0.15.0"], - ["DiffEqPDEBase", v"0.1.0", "RecipesBase"], - ["DiffEqPDEBase", v"0.1.0", "VectorizedRoutines"], - ["DiffEqPDEBase", v"0.2.0", "ChunkedArrays"], - ["DiffEqPDEBase", v"0.2.0", "Compat", v"0.17.0"], - ["DiffEqPDEBase", v"0.2.0", "DiffEqBase", v"0.15.0"], - ["DiffEqPDEBase", v"0.2.0", "RecipesBase"], - ["DiffEqPDEBase", v"0.2.0", "VectorizedRoutines"], - ["DiffEqParamEstim", v"0.0.1", "DiffEqBase", v"0.0.0", v"0.14.0"], - ["DiffEqParamEstim", v"0.0.1", "LossFunctions"], - ["DiffEqParamEstim", v"0.0.1", "LsqFit"], - ["DiffEqParamEstim", v"0.0.1", "OrdinaryDiffEq"], - ["DiffEqParamEstim", v"0.0.1", "RecursiveArrayTools"], - ["DiffEqParamEstim", v"0.0.2", "DiffEqBase", v"0.1.2", v"0.14.0"], - ["DiffEqParamEstim", v"0.0.2", "LossFunctions", v"0.0.2"], - ["DiffEqParamEstim", v"0.0.2", "LsqFit", v"0.0.2"], - ["DiffEqParamEstim", v"0.0.2", "OrdinaryDiffEq", v"0.1.1"], - ["DiffEqParamEstim", v"0.0.2", "RecursiveArrayTools", v"0.0.2"], - ["DiffEqParamEstim", v"0.0.4", "DiffEqBase", v"0.1.2", v"0.14.0"], - ["DiffEqParamEstim", v"0.0.4", "LossFunctions", v"0.0.2"], - ["DiffEqParamEstim", v"0.0.4", "LsqFit", v"0.0.2"], - ["DiffEqParamEstim", v"0.0.4", "RecursiveArrayTools", v"0.0.2"], - ["DiffEqParamEstim", v"0.1.0", "Calculus"], - ["DiffEqParamEstim", v"0.1.0", "DiffEqBase", v"0.1.2", v"0.14.0"], - ["DiffEqParamEstim", v"0.1.0", "ForwardDiff"], - ["DiffEqParamEstim", v"0.1.0", "LossFunctions", v"0.0.2"], - ["DiffEqParamEstim", v"0.1.0", "LsqFit", v"0.0.2"], - ["DiffEqParamEstim", v"0.1.0", "RecursiveArrayTools", v"0.0.2"], - ["DiffEqParamEstim", v"0.2.0", "Calculus"], - ["DiffEqParamEstim", v"0.2.0", "Optim"], - ["DiffEqParamEstim", v"0.2.0", "Compat", v"0.17.0"], - ["DiffEqParamEstim", v"0.2.0", "DiffEqBase", v"0.14.0"], - ["DiffEqParamEstim", v"0.2.0", "ForwardDiff"], - ["DiffEqParamEstim", v"0.2.0", "LossFunctions", v"0.0.2"], - ["DiffEqParamEstim", v"0.2.0", "LsqFit", v"0.0.2"], - ["DiffEqParamEstim", v"0.2.0", "RecursiveArrayTools", v"0.0.2"], - ["DiffEqProblemLibrary", v"0.0.1", "AlgebraicDiffEq"], - ["DiffEqProblemLibrary", v"0.0.1", "DiffEqBase", v"0.0.0", v"0.15.0"], - ["DiffEqProblemLibrary", v"0.0.1", "FiniteElementDiffEq"], - ["DiffEqProblemLibrary", v"0.0.1", "JLD", v"0.6.5"], - ["DiffEqProblemLibrary", v"0.0.1", "OrdinaryDiffEq"], - ["DiffEqProblemLibrary", v"0.0.1", "ParameterizedFunctions", v"0.2.0"], - ["DiffEqProblemLibrary", v"0.0.1", "StochasticDiffEq"], - ["DiffEqProblemLibrary", v"0.1.0", "AlgebraicDiffEq"], - ["DiffEqProblemLibrary", v"0.1.0", "DiffEqBase", v"0.0.0", v"0.15.0"], - ["DiffEqProblemLibrary", v"0.1.0", "FiniteElementDiffEq"], - ["DiffEqProblemLibrary", v"0.1.0", "JLD", v"0.6.5"], - ["DiffEqProblemLibrary", v"0.1.0", "ParameterizedFunctions", v"0.2.0"], - ["DiffEqProblemLibrary", v"0.1.0", "StochasticDiffEq"], - ["DiffEqProblemLibrary", v"0.2.0", "AlgebraicDiffEq", v"0.0.2"], - ["DiffEqProblemLibrary", v"0.2.0", "DiffEqBase", v"0.2.0", v"0.15.0"], - ["DiffEqProblemLibrary", v"0.2.0", "FiniteElementDiffEq", v"0.0.5"], - ["DiffEqProblemLibrary", v"0.2.0", "JLD", v"0.6.5"], - ["DiffEqProblemLibrary", v"0.2.0", "ParameterizedFunctions", v"0.2.0"], - ["DiffEqProblemLibrary", v"0.2.0", "StochasticDiffEq", v"0.1.0"], - ["DiffEqProblemLibrary", v"0.3.2", "AlgebraicDiffEq", v"0.0.2"], - ["DiffEqProblemLibrary", v"0.3.2", "DiffEqBase", v"0.2.0", v"0.15.0"], - ["DiffEqProblemLibrary", v"0.3.2", "FiniteElementDiffEq", v"0.0.5"], - ["DiffEqProblemLibrary", v"0.3.2", "JLD", v"0.6.5"], - ["DiffEqProblemLibrary", v"0.3.2", "ParameterizedFunctions", v"0.2.0"], - ["DiffEqProblemLibrary", v"0.4.0", "DiffEqBase", v"0.2.0", v"0.15.0"], - ["DiffEqProblemLibrary", v"0.4.0", "DiffEqPDEBase"], - ["DiffEqProblemLibrary", v"0.4.0", "FiniteElementDiffEq", v"0.0.5"], - ["DiffEqProblemLibrary", v"0.4.0", "JLD", v"0.6.5"], - ["DiffEqProblemLibrary", v"0.4.0", "ParameterizedFunctions", v"0.5.0"], - ["DiffEqProblemLibrary", v"0.5.0", "DiffEqBase", v"0.15.0"], - ["DiffEqProblemLibrary", v"0.5.0", "DiffEqPDEBase"], - ["DiffEqProblemLibrary", v"0.5.0", "JLD", v"0.6.5"], - ["DiffEqProblemLibrary", v"0.5.0", "ParameterizedFunctions", v"0.5.0"], - ["DiffEqSensitivity", v"0.0.1", "DiffEqBase", v"0.0.0", v"0.15.0"], - ["DiffEqSensitivity", v"0.0.2", "DiffEqBase", v"0.1.2", v"0.15.0"], - ["DiffEqSensitivity", v"0.0.4", "DiffEqBase", v"0.2.0", v"0.15.0"], - ["DiffEqSensitivity", v"0.1.0", "DiffEqBase", v"0.15.0"], - ["DifferentialEquations", v"0.4.0", "ChunkedArrays", v"0.0.2"], - ["DifferentialEquations", v"0.4.0", "Compat", v"0.8.8"], - ["DifferentialEquations", v"0.4.0", "DiffEqBase", v"0.0.0", v"0.15.0"], - ["DifferentialEquations", v"0.4.0", "ForwardDiff", v"0.2.4"], - ["DifferentialEquations", v"0.4.0", "GenericSVD", v"0.0.2"], - ["DifferentialEquations", v"0.4.0", "InplaceOps", v"0.0.5"], - ["DifferentialEquations", v"0.4.0", "IterativeSolvers", v"0.2.2"], - ["DifferentialEquations", v"0.4.0", "Parameters", v"0.3.1"], - ["DifferentialEquations", v"0.4.0", "OrdinaryDiffEq", v"0.0.0", v"1.2.0"], - ["DifferentialEquations", v"0.4.0", "Plots", v"0.9.2"], - ["DifferentialEquations", v"0.4.0", "SIUnits", v"0.0.6"], - ["DifferentialEquations", v"0.4.0", "StochasticDiffEq", v"0.0.0", v"1.0.0"], - ["DifferentialEquations", v"0.4.2", "ChunkedArrays", v"0.0.2"], - ["DifferentialEquations", v"0.4.2", "Compat", v"0.8.8"], - ["DifferentialEquations", v"0.4.2", "DiffEqBase", v"0.0.0", v"0.15.0"], - ["DifferentialEquations", v"0.4.2", "ForwardDiff", v"0.2.4"], - ["DifferentialEquations", v"0.4.2", "GenericSVD", v"0.0.2"], - ["DifferentialEquations", v"0.4.2", "InplaceOps", v"0.0.5"], - ["DifferentialEquations", v"0.4.2", "IterativeSolvers", v"0.2.2"], - ["DifferentialEquations", v"0.4.2", "Parameters", v"0.5.0"], - ["DifferentialEquations", v"0.4.2", "OrdinaryDiffEq", v"0.0.0", v"1.2.0"], - ["DifferentialEquations", v"0.4.2", "Plots", v"0.9.2"], - ["DifferentialEquations", v"0.4.2", "SIUnits", v"0.0.6"], - ["DifferentialEquations", v"0.4.2", "StochasticDiffEq", v"0.0.0", v"1.0.0"], - ["DifferentialEquations", v"0.5.0", "ChunkedArrays", v"0.0.2"], - ["DifferentialEquations", v"0.5.0", "Compat", v"0.8.8"], - ["DifferentialEquations", v"0.5.0", "DiffEqBase", v"0.0.0", v"0.15.0"], - ["DifferentialEquations", v"0.5.0", "ForwardDiff", v"0.2.4"], - ["DifferentialEquations", v"0.5.0", "GenericSVD", v"0.0.2"], - ["DifferentialEquations", v"0.5.0", "InplaceOps", v"0.0.5"], - ["DifferentialEquations", v"0.5.0", "IterativeSolvers", v"0.2.2"], - ["DifferentialEquations", v"0.5.0", "NLsolve", v"0.7.3"], - ["DifferentialEquations", v"0.5.0", "Parameters", v"0.5.0"], - ["DifferentialEquations", v"0.5.0", "OrdinaryDiffEq", v"0.0.0", v"1.2.0"], - ["DifferentialEquations", v"0.5.0", "Plots", v"0.9.2"], - ["DifferentialEquations", v"0.5.0", "Ranges", v"0.0.1"], - ["DifferentialEquations", v"0.5.0", "StochasticDiffEq", v"0.0.0", v"1.0.0"], - ["DifferentialEquations", v"0.5.0", "Sundials", v"0.3.0"], - ["DifferentialEquations", v"1.0.0", "AlgebraicDiffEq"], - ["DifferentialEquations", v"1.0.0", "DiffEqDevTools"], - ["DifferentialEquations", v"1.0.0", "DiffEqParamEstim"], - ["DifferentialEquations", v"1.0.0", "DiffEqSensitivity"], - ["DifferentialEquations", v"1.0.0", "FiniteElementDiffEq"], - ["DifferentialEquations", v"1.0.0", "Reexport"], - ["DifferentialEquations", v"1.0.0", "DiffEqBase", v"0.0.0", v"0.15.0"], - ["DifferentialEquations", v"1.0.0", "OrdinaryDiffEq", v"0.0.0", v"1.2.0"], - ["DifferentialEquations", v"1.0.0", "StochasticDiffEq", v"0.0.0", v"1.0.0"], - ["DifferentialEquations", v"1.0.0", "StokesDiffEq"], - ["DifferentialEquations", v"1.0.0", "Sundials"], - ["DifferentialEquations", v"1.1.0", "AlgebraicDiffEq", v"0.0.2"], - ["DifferentialEquations", v"1.1.0", "DiffEqBase", v"0.1.3", v"0.15.0"], - ["DifferentialEquations", v"1.1.0", "DiffEqDevTools", v"0.1.1"], - ["DifferentialEquations", v"1.1.0", "DiffEqParamEstim", v"0.0.2"], - ["DifferentialEquations", v"1.1.0", "DiffEqSensitivity", v"0.0.2"], - ["DifferentialEquations", v"1.1.0", "FiniteElementDiffEq", v"0.0.5"], - ["DifferentialEquations", v"1.1.0", "OrdinaryDiffEq", v"0.1.1", v"1.2.0"], - ["DifferentialEquations", v"1.1.0", "ParameterizedFunctions", v"0.3.2"], - ["DifferentialEquations", v"1.1.0", "Reexport", v"0.0.3"], - ["DifferentialEquations", v"1.1.0", "StochasticDiffEq", v"0.0.5", v"1.0.0"], - ["DifferentialEquations", v"1.1.0", "StokesDiffEq", v"0.0.2"], - ["DifferentialEquations", v"1.1.0", "Sundials", v"0.3.0"], - ["DifferentialEquations", v"1.4.0", "AlgebraicDiffEq", v"0.0.2"], - ["DifferentialEquations", v"1.4.0", "DiffEqBase", v"0.2.0", v"0.15.0"], - ["DifferentialEquations", v"1.4.0", "DiffEqDevTools", v"0.2.0"], - ["DifferentialEquations", v"1.4.0", "DiffEqParamEstim", v"0.0.2"], - ["DifferentialEquations", v"1.4.0", "DiffEqProblemLibrary", v"0.2.0"], - ["DifferentialEquations", v"1.4.0", "DiffEqSensitivity", v"0.0.2"], - ["DifferentialEquations", v"1.4.0", "FiniteElementDiffEq", v"0.0.5"], - ["DifferentialEquations", v"1.4.0", "OrdinaryDiffEq", v"0.2.0", v"1.2.0"], - ["DifferentialEquations", v"1.4.0", "ParameterizedFunctions", v"0.3.2"], - ["DifferentialEquations", v"1.4.0", "Reexport", v"0.0.3"], - ["DifferentialEquations", v"1.4.0", "StochasticDiffEq", v"0.1.0", v"1.0.0"], - ["DifferentialEquations", v"1.4.0", "StokesDiffEq", v"0.0.2"], - ["DifferentialEquations", v"1.4.0", "Sundials", v"0.4.1"], - ["DifferentialEquations", v"1.5.0", "DiffEqPDEBase"], - ["DifferentialEquations", v"1.5.0", "AlgebraicDiffEq", v"0.0.2"], - ["DifferentialEquations", v"1.5.0", "DiffEqBase", v"0.2.0", v"0.15.0"], - ["DifferentialEquations", v"1.5.0", "DiffEqDevTools", v"0.2.0"], - ["DifferentialEquations", v"1.5.0", "DiffEqParamEstim", v"0.0.2"], - ["DifferentialEquations", v"1.5.0", "DiffEqSensitivity", v"0.0.2"], - ["DifferentialEquations", v"1.5.0", "FiniteElementDiffEq", v"0.0.5"], - ["DifferentialEquations", v"1.5.0", "OrdinaryDiffEq", v"0.2.0", v"1.2.0"], - ["DifferentialEquations", v"1.5.0", "ParameterizedFunctions", v"0.3.2"], - ["DifferentialEquations", v"1.5.0", "Reexport", v"0.0.3"], - ["DifferentialEquations", v"1.5.0", "StochasticDiffEq", v"0.1.0", v"1.0.0"], - ["DifferentialEquations", v"1.5.0", "StokesDiffEq", v"0.0.2"], - ["DifferentialEquations", v"1.5.0", "Sundials", v"0.4.1"], - ["DifferentialEquations", v"1.6.0", "AlgebraicDiffEq", v"0.0.2"], - ["DifferentialEquations", v"1.6.0", "DelayDiffEq"], - ["DifferentialEquations", v"1.6.0", "DiffEqBase", v"0.2.0", v"0.15.0"], - ["DifferentialEquations", v"1.6.0", "DiffEqCallbacks"], - ["DifferentialEquations", v"1.6.0", "DiffEqMonteCarlo"], - ["DifferentialEquations", v"1.6.0", "DiffEqPDEBase"], - ["DifferentialEquations", v"1.6.0", "DiffEqDevTools", v"0.2.0"], - ["DifferentialEquations", v"1.6.0", "DiffEqParamEstim", v"0.0.2"], - ["DifferentialEquations", v"1.6.0", "DiffEqSensitivity", v"0.0.2"], - ["DifferentialEquations", v"1.6.0", "FiniteElementDiffEq", v"0.0.5"], - ["DifferentialEquations", v"1.6.0", "Reexport", v"0.0.3"], - ["DifferentialEquations", v"1.6.0", "OrdinaryDiffEq", v"0.2.0", v"1.2.0"], - ["DifferentialEquations", v"1.6.0", "ParameterizedFunctions", v"0.3.2"], - ["DifferentialEquations", v"1.6.0", "StochasticDiffEq", v"0.1.0", v"1.0.0"], - ["DifferentialEquations", v"1.6.0", "StokesDiffEq", v"0.0.2"], - ["DifferentialEquations", v"1.6.0", "Sundials", v"0.4.1"], - ["DifferentialEquations", v"1.7.0", "DiffEqCallbacks"], - ["DifferentialEquations", v"1.7.0", "DiffEqMonteCarlo"], - ["DifferentialEquations", v"1.7.0", "DiffEqPDEBase"], - ["DifferentialEquations", v"1.7.0", "AlgebraicDiffEq", v"0.0.2"], - ["DifferentialEquations", v"1.7.0", "DelayDiffEq", v"0.1.0"], - ["DifferentialEquations", v"1.7.0", "DiffEqDevTools", v"0.2.0"], - ["DifferentialEquations", v"1.7.0", "DiffEqParamEstim", v"0.0.2"], - ["DifferentialEquations", v"1.7.0", "DiffEqSensitivity", v"0.0.2"], - ["DifferentialEquations", v"1.7.0", "FiniteElementDiffEq", v"0.0.5"], - ["DifferentialEquations", v"1.7.0", "OrdinaryDiffEq", v"1.2.0"], - ["DifferentialEquations", v"1.7.0", "ParameterizedFunctions", v"0.3.2"], - ["DifferentialEquations", v"1.7.0", "Reexport", v"0.0.3"], - ["DifferentialEquations", v"1.7.0", "DiffEqBase", v"0.8.0", v"0.15.0"], - ["DifferentialEquations", v"1.7.0", "StochasticDiffEq", v"1.0.0"], - ["DifferentialEquations", v"1.7.0", "StokesDiffEq", v"0.0.2"], - ["DifferentialEquations", v"1.7.0", "Sundials", v"0.4.1"], - ["DifferentialEquations", v"1.9.0", "DiffEqBiological"], - ["DifferentialEquations", v"1.9.0", "DiffEqCallbacks"], - ["DifferentialEquations", v"1.9.0", "AlgebraicDiffEq", v"0.0.2"], - ["DifferentialEquations", v"1.9.0", "DelayDiffEq", v"0.1.0"], - ["DifferentialEquations", v"1.9.0", "DiffEqBase", v"0.8.0", v"0.15.0"], - ["DifferentialEquations", v"1.9.0", "DiffEqFinancial"], - ["DifferentialEquations", v"1.9.0", "DiffEqJump"], - ["DifferentialEquations", v"1.9.0", "DiffEqMonteCarlo"], - ["DifferentialEquations", v"1.9.0", "DiffEqPDEBase"], - ["DifferentialEquations", v"1.9.0", "DiffEqDevTools", v"0.2.0"], - ["DifferentialEquations", v"1.9.0", "DiffEqParamEstim", v"0.0.2"], - ["DifferentialEquations", v"1.9.0", "DiffEqSensitivity", v"0.0.2"], - ["DifferentialEquations", v"1.9.0", "FiniteElementDiffEq", v"0.0.5"], - ["DifferentialEquations", v"1.9.0", "MultiScaleArrays"], - ["DifferentialEquations", v"1.9.0", "OrdinaryDiffEq", v"1.2.0"], - ["DifferentialEquations", v"1.9.0", "PyDSTool"], - ["DifferentialEquations", v"1.9.0", "ParameterizedFunctions", v"0.3.2"], - ["DifferentialEquations", v"1.9.0", "Reexport", v"0.0.3"], - ["DifferentialEquations", v"1.9.0", "StochasticDiffEq", v"1.0.0"], - ["DifferentialEquations", v"1.9.0", "StokesDiffEq", v"0.0.2"], - ["DifferentialEquations", v"1.9.0", "Sundials", v"0.4.1"], - ["DifferentialEquations", v"1.9.1", "DiffEqBiological"], - ["DifferentialEquations", v"1.9.1", "DiffEqCallbacks"], - ["DifferentialEquations", v"1.9.1", "AlgebraicDiffEq", v"0.0.2"], - ["DifferentialEquations", v"1.9.1", "DelayDiffEq", v"0.1.0"], - ["DifferentialEquations", v"1.9.1", "DiffEqBase", v"0.8.0", v"0.15.0"], - ["DifferentialEquations", v"1.9.1", "DiffEqFinancial"], - ["DifferentialEquations", v"1.9.1", "DiffEqJump"], - ["DifferentialEquations", v"1.9.1", "DiffEqMonteCarlo"], - ["DifferentialEquations", v"1.9.1", "DiffEqPDEBase"], - ["DifferentialEquations", v"1.9.1", "DiffEqDevTools", v"0.2.0"], - ["DifferentialEquations", v"1.9.1", "DiffEqParamEstim", v"0.0.2"], - ["DifferentialEquations", v"1.9.1", "DiffEqSensitivity", v"0.0.2"], - ["DifferentialEquations", v"1.9.1", "FiniteElementDiffEq", v"0.0.5"], - ["DifferentialEquations", v"1.9.1", "MultiScaleArrays"], - ["DifferentialEquations", v"1.9.1", "OrdinaryDiffEq", v"1.2.0"], - ["DifferentialEquations", v"1.9.1", "ParameterizedFunctions", v"0.3.2"], - ["DifferentialEquations", v"1.9.1", "Reexport", v"0.0.3"], - ["DifferentialEquations", v"1.9.1", "StochasticDiffEq", v"1.0.0"], - ["DifferentialEquations", v"1.9.1", "StokesDiffEq", v"0.0.2"], - ["DifferentialEquations", v"1.9.1", "Sundials", v"0.4.1"], - ["DifferentialEquations", v"1.10.1", "DiffEqBase", v"0.15.0"], - ["DifferentialEquations", v"1.10.1", "DiffEqBiological"], - ["DifferentialEquations", v"1.10.1", "DiffEqCallbacks"], - ["DifferentialEquations", v"1.10.1", "AlgebraicDiffEq", v"0.0.2"], - ["DifferentialEquations", v"1.10.1", "DiffEqFinancial"], - ["DifferentialEquations", v"1.10.1", "DiffEqJump"], - ["DifferentialEquations", v"1.10.1", "DiffEqMonteCarlo"], - ["DifferentialEquations", v"1.10.1", "DiffEqPDEBase"], - ["DifferentialEquations", v"1.10.1", "MultiScaleArrays"], - ["DifferentialEquations", v"1.10.1", "DelayDiffEq", v"0.1.0"], - ["DifferentialEquations", v"1.10.1", "DiffEqDevTools", v"0.2.0"], - ["DifferentialEquations", v"1.10.1", "DiffEqParamEstim", v"0.0.2"], - ["DifferentialEquations", v"1.10.1", "DiffEqSensitivity", v"0.0.2"], - ["DifferentialEquations", v"1.10.1", "FiniteElementDiffEq", v"0.0.5"], - ["DifferentialEquations", v"1.10.1", "OrdinaryDiffEq", v"1.2.0"], - ["DifferentialEquations", v"1.10.1", "ParameterizedFunctions", v"0.3.2"], - ["DifferentialEquations", v"1.10.1", "Reexport", v"0.0.3"], - ["DifferentialEquations", v"1.10.1", "StochasticDiffEq", v"1.0.0"], - ["DifferentialEquations", v"1.10.1", "StokesDiffEq", v"0.0.2"], - ["DifferentialEquations", v"1.10.1", "Sundials", v"0.4.1"], - ["Distances", v"0.1.1", "ArrayViews", v"0.4.0-"], - ["Distances", v"0.2.0", "ArrayViews", v"0.4.8-"], - ["Distances", v"0.2.2", "Compat"], - ["Distances", v"0.2.2", "ArrayViews", v"0.4.8-"], - ["Distances", v"0.3.2", "Compat", v"0.8.4"], - ["Distances", v"0.4.0"], - ["Distances", v"0.4.1", "Compat", v"0.18.0"], - ["Distributions", v"0.6.4", "ArrayViews", v"0.4.8"], - ["Distributions", v"0.6.4", "Compat", v"0.2.4"], - ["Distributions", v"0.6.4", "PDMats", v"0.3.1", v"0.4.0"], - ["Distributions", v"0.6.4", "StatsBase", v"0.6.10"], - ["Distributions", v"0.6.4", "StatsFuns", v"0.0.0", v"0.3.0"], - ["Distributions", v"0.6.5", "ArrayViews", v"0.4.9"], - ["Distributions", v"0.6.5", "Compat", v"0.3.1"], - ["Distributions", v"0.6.5", "PDMats", v"0.3.1", v"0.4.0"], - ["Distributions", v"0.6.5", "StatsBase", v"0.6.10"], - ["Distributions", v"0.6.5", "StatsFuns", v"0.0.0", v"0.3.0"], - ["Distributions", v"0.6.7", "ArrayViews", v"0.4.10"], - ["Distributions", v"0.6.7", "Compat", v"0.3.2"], - ["Distributions", v"0.6.7", "PDMats", v"0.3.1", v"0.4.0"], - ["Distributions", v"0.6.7", "StatsBase", v"0.6.13"], - ["Distributions", v"0.6.7", "StatsFuns", v"0.0.0", v"0.3.0"], - ["Distributions", v"0.7.6", "ArrayViews", v"0.4.12"], - ["Distributions", v"0.7.6", "Compat", v"0.4.0"], - ["Distributions", v"0.7.6", "PDMats", v"0.3.2", v"0.4.0"], - ["Distributions", v"0.7.6", "StatsBase", v"0.6.14"], - ["Distributions", v"0.7.6", "StatsFuns", v"0.0.0", v"0.3.0"], - ["Distributions", v"0.8.9", "ArrayViews", v"0.4.12"], - ["Distributions", v"0.8.9", "Compat", v"0.4.0"], - ["Distributions", v"0.8.9", "PDMats", v"0.3.2", v"0.4.0"], - ["Distributions", v"0.8.9", "StatsBase", v"0.7.0"], - ["Distributions", v"0.8.9", "StatsFuns", v"0.1.1", v"0.3.0"], - ["Distributions", v"0.8.10", "ArrayViews", v"0.4.12"], - ["Distributions", v"0.8.10", "Compat", v"0.4.0"], - ["Distributions", v"0.8.10", "PDMats", v"0.4.0", v"0.5.0"], - ["Distributions", v"0.8.10", "StatsBase", v"0.7.0"], - ["Distributions", v"0.8.10", "StatsFuns", v"0.1.1", v"0.3.0"], - ["Distributions", v"0.9.0", "Compat", v"0.2.17"], - ["Distributions", v"0.9.0", "PDMats", v"0.4.1", v"0.5.0"], - ["Distributions", v"0.9.0", "StatsBase", v"0.7.0"], - ["Distributions", v"0.9.0", "StatsFuns", v"0.1.1", v"0.3.0"], - ["Distributions", v"0.10.2", "Calculus"], - ["Distributions", v"0.10.2", "Compat", v"0.8.4"], - ["Distributions", v"0.10.2", "PDMats", v"0.4.2", v"0.5.0"], - ["Distributions", v"0.10.2", "StatsBase", v"0.8.3"], - ["Distributions", v"0.10.2", "StatsFuns", v"0.3.0"], - ["Distributions", v"0.11.1", "Calculus"], - ["Distributions", v"0.11.1", "Compat", v"0.9.2"], - ["Distributions", v"0.11.1", "PDMats", v"0.5.0"], - ["Distributions", v"0.11.1", "StatsBase", v"0.8.3"], - ["Distributions", v"0.11.1", "StatsFuns", v"0.3.1"], - ["Distributions", v"0.12.0", "Calculus"], - ["Distributions", v"0.12.0", "Compat", v"0.14.0"], - ["Distributions", v"0.12.0", "PDMats", v"0.5.4"], - ["Distributions", v"0.12.0", "QuadGK", v"0.1.1"], - ["Distributions", v"0.12.0", "StatsBase", v"0.8.3"], - ["Distributions", v"0.12.0", "StatsFuns", v"0.3.1"], - ["Distributions", v"0.12.4", "Calculus"], - ["Distributions", v"0.12.4", "Compat", v"0.18.0"], - ["Distributions", v"0.12.4", "PDMats", v"0.5.4"], - ["Distributions", v"0.12.4", "QuadGK", v"0.1.1"], - ["Distributions", v"0.12.4", "SpecialFunctions", v"0.1.0"], - ["Distributions", v"0.12.4", "StatsBase", v"0.8.3"], - ["Distributions", v"0.12.4", "StatsFuns", v"0.3.1"], - ["Distributions", v"0.12.5", "Calculus"], - ["Distributions", v"0.12.5", "Compat", v"0.18.0"], - ["Distributions", v"0.12.5", "PDMats", v"0.6.0"], - ["Distributions", v"0.12.5", "QuadGK", v"0.1.1"], - ["Distributions", v"0.12.5", "SpecialFunctions", v"0.1.0"], - ["Distributions", v"0.12.5", "StatsBase", v"0.8.3"], - ["Distributions", v"0.12.5", "StatsFuns", v"0.3.1"], - ["Docile", v"0.1.0", "AnsiColor"], - ["Docile", v"0.1.0", "Markdown"], - ["Docile", v"0.3.1"], - ["Docile", v"0.3.2", "Compat"], - ["Docile", v"0.4.6", "Compat"], - ["Docile", v"0.4.13", "Compat", v"0.3.3"], - ["Docile", v"0.5.18", "Compat", v"0.3.5"], - ["Docile", v"0.5.23", "Compat", v"0.7.1"], - ["DualNumbers", v"0.1.0", "Calculus"], - ["DualNumbers", v"0.1.3", "Calculus"], - ["DualNumbers", v"0.1.3", "NaNMath"], - ["DualNumbers", v"0.1.5", "Calculus"], - ["DualNumbers", v"0.1.5", "Compat"], - ["DualNumbers", v"0.1.5", "NaNMath"], - ["DualNumbers", v"0.2.2", "Calculus"], - ["DualNumbers", v"0.2.2", "NaNMath"], - ["DualNumbers", v"0.3.0", "Calculus"], - ["DualNumbers", v"0.3.0", "NaNMath"], - ["DualNumbers", v"0.3.0", "Compat", v"0.9.1"], - ["ELF", v"0.0.0", "StrPack"], - ["ELF", v"0.1.0", "DWARF"], - ["ELF", v"0.1.0", "FileIO"], - ["ELF", v"0.1.0", "ObjFileBase"], - ["ELF", v"0.1.0", "StructIO"], - ["EllipsisNotation", v"0.0.1"], - ["EllipsisNotation", v"0.1.0"], - ["FFTViews", v"0.0.1", "CustomUnitRanges"], - ["FFTViews", v"0.0.2", "CustomUnitRanges"], - ["FFTViews", v"0.0.2", "Compat", v"0.17.0"], - ["FactCheck", v"0.0.0"], - ["FactCheck", v"0.0.2"], - ["FactCheck", v"0.2.2"], - ["FactCheck", v"0.4.2", "Compat"], - ["FactCheck", v"0.4.3", "Compat", v"0.7.18"], - ["FileIO", v"0.0.5", "Compat"], - ["FileIO", v"0.0.5", "Docile"], - ["FileIO", v"0.0.6", "Docile"], - ["FileIO", v"0.0.6", "Compat", v"0.7.15"], - ["FileIO", v"0.1.1", "Compat", v"0.7.19"], - ["FileIO", v"0.2.1", "Compat", v"0.7.19"], - ["FileIO", v"0.3.0", "Compat", v"0.9.5"], - ["FileIO", v"0.3.1", "Compat", v"0.17.0"], - ["FiniteElementDiffEq", v"0.0.3", "ChunkedArrays", v"0.1.0"], - ["FiniteElementDiffEq", v"0.0.3", "DiffEqBase", v"0.0.0", v"0.15.0"], - ["FiniteElementDiffEq", v"0.0.3", "ForwardDiff", v"0.2.4"], - ["FiniteElementDiffEq", v"0.0.3", "GenericSVD", v"0.0.2"], - ["FiniteElementDiffEq", v"0.0.3", "IterativeSolvers", v"0.2.2"], - ["FiniteElementDiffEq", v"0.0.3", "NLsolve", v"0.7.3"], - ["FiniteElementDiffEq", v"0.0.3", "Parameters", v"0.5.0"], - ["FiniteElementDiffEq", v"0.0.3", "Plots", v"0.9.2"], - ["FiniteElementDiffEq", v"0.0.3", "RecipesBase", v"0.1.0"], - ["FiniteElementDiffEq", v"0.0.3", "VectorizedRoutines", v"0.0.2"], - ["FiniteElementDiffEq", v"0.0.4", "ChunkedArrays", v"0.1.0"], - ["FiniteElementDiffEq", v"0.0.4", "DiffEqBase", v"0.0.0", v"0.15.0"], - ["FiniteElementDiffEq", v"0.0.4", "ForwardDiff", v"0.2.4"], - ["FiniteElementDiffEq", v"0.0.4", "GenericSVD", v"0.0.2"], - ["FiniteElementDiffEq", v"0.0.4", "IterativeSolvers", v"0.2.2"], - ["FiniteElementDiffEq", v"0.0.4", "NLsolve", v"0.7.3"], - ["FiniteElementDiffEq", v"0.0.4", "Parameters", v"0.5.0"], - ["FiniteElementDiffEq", v"0.0.4", "RecipesBase", v"0.1.0"], - ["FiniteElementDiffEq", v"0.0.4", "VectorizedRoutines", v"0.0.2"], - ["FiniteElementDiffEq", v"0.0.5", "ChunkedArrays", v"0.1.0"], - ["FiniteElementDiffEq", v"0.0.5", "DiffEqBase", v"0.1.1", v"0.15.0"], - ["FiniteElementDiffEq", v"0.0.5", "ForwardDiff", v"0.2.4"], - ["FiniteElementDiffEq", v"0.0.5", "GenericSVD", v"0.0.2"], - ["FiniteElementDiffEq", v"0.0.5", "IterativeSolvers", v"0.2.2"], - ["FiniteElementDiffEq", v"0.0.5", "Juno", v"0.2.4"], - ["FiniteElementDiffEq", v"0.0.5", "NLsolve", v"0.7.3"], - ["FiniteElementDiffEq", v"0.0.5", "Parameters", v"0.5.0"], - ["FiniteElementDiffEq", v"0.0.5", "RecipesBase", v"0.1.0"], - ["FiniteElementDiffEq", v"0.0.5", "VectorizedRoutines", v"0.0.2"], - ["FiniteElementDiffEq", v"0.2.0", "ChunkedArrays", v"0.1.0"], - ["FiniteElementDiffEq", v"0.2.0", "DiffEqBase", v"0.4.0", v"0.15.0"], - ["FiniteElementDiffEq", v"0.2.0", "ForwardDiff", v"0.2.4"], - ["FiniteElementDiffEq", v"0.2.0", "GenericSVD", v"0.0.2"], - ["FiniteElementDiffEq", v"0.2.0", "IterativeSolvers", v"0.2.2"], - ["FiniteElementDiffEq", v"0.2.0", "Juno", v"0.2.4"], - ["FiniteElementDiffEq", v"0.2.0", "NLsolve", v"0.7.3"], - ["FiniteElementDiffEq", v"0.2.0", "Parameters", v"0.5.0"], - ["FiniteElementDiffEq", v"0.2.0", "RecipesBase", v"0.1.0"], - ["FiniteElementDiffEq", v"0.2.0", "VectorizedRoutines", v"0.0.2"], - ["FiniteElementDiffEq", v"0.2.1", "ChunkedArrays", v"0.1.0"], - ["FiniteElementDiffEq", v"0.2.1", "DiffEqBase", v"0.4.0", v"0.15.0"], - ["FiniteElementDiffEq", v"0.2.1", "DiffEqPDEBase"], - ["FiniteElementDiffEq", v"0.2.1", "ForwardDiff", v"0.2.4"], - ["FiniteElementDiffEq", v"0.2.1", "GenericSVD", v"0.0.2"], - ["FiniteElementDiffEq", v"0.2.1", "IterativeSolvers", v"0.2.2"], - ["FiniteElementDiffEq", v"0.2.1", "Juno", v"0.2.4"], - ["FiniteElementDiffEq", v"0.2.1", "NLsolve", v"0.7.3"], - ["FiniteElementDiffEq", v"0.2.1", "Parameters", v"0.5.0"], - ["FiniteElementDiffEq", v"0.2.1", "VectorizedRoutines", v"0.0.2"], - ["FiniteElementDiffEq", v"0.3.0", "ChunkedArrays", v"0.1.0"], - ["FiniteElementDiffEq", v"0.3.0", "DiffEqBase", v"0.15.0"], - ["FiniteElementDiffEq", v"0.3.0", "DiffEqPDEBase"], - ["FiniteElementDiffEq", v"0.3.0", "ForwardDiff", v"0.2.4"], - ["FiniteElementDiffEq", v"0.3.0", "GenericSVD", v"0.0.2"], - ["FiniteElementDiffEq", v"0.3.0", "IterativeSolvers", v"0.2.2"], - ["FiniteElementDiffEq", v"0.3.0", "Juno", v"0.2.4"], - ["FiniteElementDiffEq", v"0.3.0", "NLsolve", v"0.7.3"], - ["FiniteElementDiffEq", v"0.3.0", "Parameters", v"0.5.0"], - ["FiniteElementDiffEq", v"0.3.0", "VectorizedRoutines", v"0.0.2"], - ["FixedPointNumbers", v"0.0.5"], - ["FixedPointNumbers", v"0.0.12", "Compat", v"0.2.2"], - ["FixedPointNumbers", v"0.1.2"], - ["FixedPointNumbers", v"0.1.4", "Compat", v"0.7.14"], - ["FixedPointNumbers", v"0.1.7", "Compat", v"0.9.1"], - ["FixedPointNumbers", v"0.2.1", "Compat", v"0.9.1"], - ["FixedPointNumbers", v"0.3.0", "Compat", v"0.9.1"], - ["FixedPointNumbers", v"0.3.2", "Compat", v"0.9.5"], - ["FixedPointNumbers", v"0.3.6", "Compat", v"0.17.0"], - ["FixedSizeArrays", v"0.1.0"], - ["FixedSizeArrays", v"0.1.1", "Compat"], - ["FixedSizeArrays", v"0.2.1", "Compat", v"0.7.15"], - ["FixedSizeArrays", v"0.2.2", "Compat", v"0.7.15"], - ["FixedSizeArrays", v"0.2.5", "Compat", v"0.8.7"], - ["ForwardDiff", v"0.2.5", "Calculus"], - ["ForwardDiff", v"0.2.5", "NaNMath"], - ["ForwardDiff", v"0.2.5", "Compat", v"0.8.6"], - ["ForwardDiff", v"0.3.4", "Calculus", v"0.2.0"], - ["ForwardDiff", v"0.3.4", "Compat", v"0.8.6"], - ["ForwardDiff", v"0.3.4", "DiffBase", v"0.0.3"], - ["ForwardDiff", v"0.3.4", "NaNMath", v"0.2.2"], - ["ForwardDiff", v"0.3.5", "Calculus", v"0.1.15"], - ["ForwardDiff", v"0.3.5", "Compat", v"0.8.6"], - ["ForwardDiff", v"0.3.5", "DiffBase", v"0.0.1"], - ["ForwardDiff", v"0.3.5", "NaNMath", v"0.2.1"], - ["ForwardDiff", v"0.4.2", "Calculus", v"0.2.0"], - ["ForwardDiff", v"0.4.2", "Compat", v"0.19.0"], - ["ForwardDiff", v"0.4.2", "DiffBase", v"0.0.3"], - ["ForwardDiff", v"0.4.2", "NaNMath", v"0.2.2"], - ["ForwardDiff", v"0.4.2", "SpecialFunctions", v"0.1.0"], - ["GZip", v"0.2.13"], - ["GZip", v"0.2.16", "Compat"], - ["GZip", v"0.2.18", "Compat", v"0.4.8"], - ["GZip", v"0.2.19", "Compat", v"0.7.9"], - ["GZip", v"0.2.20", "Compat", v"0.8.0"], - ["GZip", v"0.3.0", "Compat", v"0.9.5"], - ["Gallium", v"0.0.1", "ASTInterpreter"], - ["Gallium", v"0.0.1", "AbstractTrees"], - ["Gallium", v"0.0.1", "DWARF"], - ["Gallium", v"0.0.1", "ELF"], - ["Gallium", v"0.0.1", "MachO"], - ["Gallium", v"0.0.1", "TerminalUI"], - ["Gallium", v"0.0.2", "ASTInterpreter"], - ["Gallium", v"0.0.2", "AbstractTrees"], - ["Gallium", v"0.0.2", "DWARF"], - ["Gallium", v"0.0.2", "ELF"], - ["Gallium", v"0.0.2", "MachO"], - ["Gallium", v"0.0.2", "ObjFileBase"], - ["Gallium", v"0.0.2", "TerminalUI"], - ["Gallium", v"0.0.4", "ASTInterpreter"], - ["Gallium", v"0.0.4", "AbstractTrees"], - ["Gallium", v"0.0.4", "COFF"], - ["Gallium", v"0.0.4", "CRC"], - ["Gallium", v"0.0.4", "DWARF"], - ["Gallium", v"0.0.4", "ELF"], - ["Gallium", v"0.0.4", "MachO"], - ["Gallium", v"0.0.4", "ObjFileBase"], - ["Gallium", v"0.0.4", "TerminalUI"], - ["GenericSVD", v"0.0.2", "Compat", v"0.8.6"], - ["GnuTLS", v"0.0.1", "Nettle"], - ["GnuTLS", v"0.0.1", "BinDeps", v"0.2.1-"], - ["GnuTLS", v"0.0.4", "Compat"], - ["GnuTLS", v"0.0.4", "Nettle"], - ["GnuTLS", v"0.0.4", "BinDeps", v"0.2.1-"], - ["GnuTLS", v"0.0.5", "BinDeps"], - ["GnuTLS", v"0.0.5", "Compat"], - ["GnuTLS", v"0.0.5", "Nettle"], - ["Graphics", v"0.1.1"], - ["Graphics", v"0.1.3", "Colors"], - ["Graphics", v"0.1.4", "Colors"], - ["Graphics", v"0.1.4", "Compat", v"0.17.0"], - ["Graphics", v"0.2.0", "Colors"], - ["Graphics", v"0.2.0", "Compat", v"0.17.0"], - ["Graphics", v"0.2.0", "NaNMath", v"0.2.4"], - ["HDF5", v"0.2.1", "StrPack"], - ["HDF5", v"0.2.9"], - ["HDF5", v"0.4.6", "BinDeps"], - ["HDF5", v"0.5.2", "BinDeps"], - ["HDF5", v"0.5.2", "Blosc"], - ["HDF5", v"0.5.2", "Compat"], - ["HDF5", v"0.5.5", "BinDeps"], - ["HDF5", v"0.5.5", "Blosc"], - ["HDF5", v"0.5.5", "Compat", v"0.4.11"], - ["HDF5", v"0.6.0", "BinDeps"], - ["HDF5", v"0.6.0", "Blosc"], - ["HDF5", v"0.6.0", "Compat", v"0.7.1"], - ["HDF5", v"0.6.1", "BinDeps"], - ["HDF5", v"0.6.1", "Blosc"], - ["HDF5", v"0.6.1", "Compat", v"0.7.16"], - ["HDF5", v"0.7.3", "BinDeps"], - ["HDF5", v"0.7.3", "Blosc"], - ["HDF5", v"0.7.3", "Compat", v"0.8.0"], - ["HDF5", v"0.8.0", "BinDeps"], - ["HDF5", v"0.8.0", "Blosc"], - ["HDF5", v"0.8.0", "Compat", v"0.17.0"], - ["Hiccup", v"0.0.0", "Lazy"], - ["Hiccup", v"0.0.1", "Lazy"], - ["Hiccup", v"0.0.1", "MacroTools"], - ["Hiccup", v"0.0.2", "Compat"], - ["Hiccup", v"0.0.2", "Lazy"], - ["Hiccup", v"0.0.2", "MacroTools"], - ["Hiccup", v"0.0.3", "Lazy"], - ["Hiccup", v"0.0.3", "MacroTools"], - ["Hiccup", v"0.0.3", "Compat", v"0.8.2"], - ["Hiccup", v"0.1.1", "Compat", v"0.8.2"], - ["Hiccup", v"0.1.1", "MacroTools", v"0.3.4"], - ["HttpCommon", v"0.0.1"], - ["HttpCommon", v"0.0.2", "Calendar"], - ["HttpCommon", v"0.0.2", "FactCheck", v"0.0.1"], - ["HttpCommon", v"0.0.5", "Calendar"], - ["HttpCommon", v"0.0.5", "FactCheck", v"0.1.0-"], - ["HttpCommon", v"0.0.12", "Dates"], - ["HttpCommon", v"0.1.1", "Compat"], - ["HttpCommon", v"0.1.1", "Dates"], - ["HttpCommon", v"0.2.0", "Compat"], - ["HttpCommon", v"0.2.0", "Dates"], - ["HttpCommon", v"0.2.0", "URIParser"], - ["HttpCommon", v"0.2.4", "URIParser"], - ["HttpCommon", v"0.2.7", "URIParser"], - ["HttpCommon", v"0.2.7", "Compat", v"0.7.20"], - ["HttpParser", v"0.0.0", "HttpCommon"], - ["HttpParser", v"0.0.1", "BinDeps"], - ["HttpParser", v"0.0.1", "HttpCommon"], - ["HttpParser", v"0.0.2"], - ["HttpParser", v"0.0.3", "HttpCommon"], - ["HttpParser", v"0.0.3", "BinDeps", v"0.2.1-"], - ["HttpParser", v"0.0.4", "HttpCommon"], - ["HttpParser", v"0.0.4", "BinDeps", v"0.2.5-"], - ["HttpParser", v"0.0.11", "BinDeps", v"0.2.5-"], - ["HttpParser", v"0.0.11", "HttpCommon", v"0.0.3-"], - ["HttpParser", v"0.1.0", "BinDeps"], - ["HttpParser", v"0.1.0", "Compat"], - ["HttpParser", v"0.1.0", "HttpCommon"], - ["HttpParser", v"0.1.1", "BinDeps"], - ["HttpParser", v"0.1.1", "HttpCommon"], - ["HttpParser", v"0.2.0", "BinDeps"], - ["HttpParser", v"0.2.0", "HttpCommon"], - ["HttpParser", v"0.2.0", "Compat", v"0.7.20"], - ["HttpServer", v"0.0.1", "HttpCommon"], - ["HttpServer", v"0.0.1", "HttpParser"], - ["HttpServer", v"0.0.3", "GnuTLS"], - ["HttpServer", v"0.0.3", "HttpCommon"], - ["HttpServer", v"0.0.3", "HttpParser"], - ["HttpServer", v"0.0.7", "GnuTLS"], - ["HttpServer", v"0.0.7", "HttpCommon", v"0.0.3-"], - ["HttpServer", v"0.0.7", "HttpParser", v"0.0.5-"], - ["HttpServer", v"0.0.8", "GnuTLS"], - ["HttpServer", v"0.0.8", "HttpCommon"], - ["HttpServer", v"0.0.8", "HttpParser"], - ["HttpServer", v"0.0.11", "Docile"], - ["HttpServer", v"0.0.11", "GnuTLS"], - ["HttpServer", v"0.0.11", "HttpCommon"], - ["HttpServer", v"0.0.11", "HttpParser"], - ["HttpServer", v"0.1.2", "Compat"], - ["HttpServer", v"0.1.2", "Docile"], - ["HttpServer", v"0.1.2", "GnuTLS"], - ["HttpServer", v"0.1.2", "HttpCommon"], - ["HttpServer", v"0.1.2", "HttpParser"], - ["HttpServer", v"0.1.5", "HttpCommon"], - ["HttpServer", v"0.1.5", "HttpParser"], - ["HttpServer", v"0.1.5", "MbedTLS"], - ["HttpServer", v"0.1.7", "HttpCommon"], - ["HttpServer", v"0.1.7", "HttpParser"], - ["HttpServer", v"0.1.7", "MbedTLS"], - ["HttpServer", v"0.1.7", "Compat", v"0.7.16"], - ["HttpServer", v"0.2.0", "HttpCommon"], - ["HttpServer", v"0.2.0", "HttpParser"], - ["HttpServer", v"0.2.0", "MbedTLS"], - ["HttpServer", v"0.2.0", "Compat", v"0.17.0"], - ["ICU", v"0.2.1"], - ["ICU", v"0.4.4", "BinDeps"], - ["ImageAxes", v"0.0.2", "AxisArrays"], - ["ImageAxes", v"0.0.2", "Colors"], - ["ImageAxes", v"0.0.2", "ImageCore"], - ["ImageAxes", v"0.0.2", "Reexport"], - ["ImageAxes", v"0.0.2", "SimpleTraits"], - ["ImageAxes", v"0.1.1", "AxisArrays"], - ["ImageAxes", v"0.1.1", "Colors"], - ["ImageAxes", v"0.1.1", "FixedPointNumbers", v"0.3.0"], - ["ImageAxes", v"0.1.1", "ImageCore"], - ["ImageAxes", v"0.1.1", "Reexport"], - ["ImageAxes", v"0.1.1", "SimpleTraits"], - ["ImageAxes", v"0.2.1", "AxisArrays"], - ["ImageAxes", v"0.2.1", "Colors"], - ["ImageAxes", v"0.2.1", "FixedPointNumbers", v"0.3.0"], - ["ImageAxes", v"0.2.1", "MappedArrays"], - ["ImageAxes", v"0.2.1", "Reexport"], - ["ImageAxes", v"0.2.1", "SimpleTraits"], - ["ImageAxes", v"0.2.1", "ImageCore", v"0.2.0"], - ["ImageCore", v"0.0.3", "Colors"], - ["ImageCore", v"0.0.3", "Graphics"], - ["ImageCore", v"0.0.3", "FixedPointNumbers", v"0.0.0-", v"0.3.0"], - ["ImageCore", v"0.0.3", "MappedArrays"], - ["ImageCore", v"0.0.4", "Colors"], - ["ImageCore", v"0.0.4", "Graphics"], - ["ImageCore", v"0.0.4", "FixedPointNumbers", v"0.0.0-", v"0.3.0"], - ["ImageCore", v"0.0.4", "MappedArrays", v"0.0.3"], - ["ImageCore", v"0.0.5", "Colors"], - ["ImageCore", v"0.0.5", "Graphics"], - ["ImageCore", v"0.0.5", "FixedPointNumbers", v"0.0.0-", v"0.3.0"], - ["ImageCore", v"0.0.5", "MappedArrays", v"0.0.3"], - ["ImageCore", v"0.0.5", "OffsetArrays"], - ["ImageCore", v"0.0.5", "ShowItLikeYouBuildIt"], - ["ImageCore", v"0.1.1", "Colors"], - ["ImageCore", v"0.1.1", "Graphics"], - ["ImageCore", v"0.1.1", "FixedPointNumbers", v"0.3.0"], - ["ImageCore", v"0.1.1", "MappedArrays", v"0.0.3"], - ["ImageCore", v"0.1.1", "OffsetArrays"], - ["ImageCore", v"0.1.1", "ShowItLikeYouBuildIt"], - ["ImageCore", v"0.1.2", "ColorTypes"], - ["ImageCore", v"0.1.2", "Colors"], - ["ImageCore", v"0.1.2", "Graphics"], - ["ImageCore", v"0.1.2", "FixedPointNumbers", v"0.3.0"], - ["ImageCore", v"0.1.2", "MappedArrays", v"0.0.3"], - ["ImageCore", v"0.1.2", "OffsetArrays"], - ["ImageCore", v"0.1.2", "ShowItLikeYouBuildIt"], - ["ImageCore", v"0.1.5", "ColorTypes"], - ["ImageCore", v"0.1.5", "Colors"], - ["ImageCore", v"0.1.5", "Graphics"], - ["ImageCore", v"0.1.5", "Compat", v"0.19.0"], - ["ImageCore", v"0.1.5", "FixedPointNumbers", v"0.3.0"], - ["ImageCore", v"0.1.5", "MappedArrays", v"0.0.3"], - ["ImageCore", v"0.1.5", "OffsetArrays"], - ["ImageCore", v"0.1.5", "ShowItLikeYouBuildIt"], - ["ImageCore", v"0.2.0", "ColorTypes"], - ["ImageCore", v"0.2.0", "Colors"], - ["ImageCore", v"0.2.0", "Graphics"], - ["ImageCore", v"0.2.0", "Compat", v"0.19.0"], - ["ImageCore", v"0.2.0", "FixedPointNumbers", v"0.3.0"], - ["ImageCore", v"0.2.0", "MappedArrays", v"0.0.3"], - ["ImageCore", v"0.2.0", "OffsetArrays"], - ["ImageCore", v"0.2.0", "ShowItLikeYouBuildIt"], - ["ImageCore", v"0.3.0", "Colors"], - ["ImageCore", v"0.3.0", "Graphics"], - ["ImageCore", v"0.3.0", "ColorTypes", v"0.4.0"], - ["ImageCore", v"0.3.0", "Compat", v"0.19.0"], - ["ImageCore", v"0.3.0", "FixedPointNumbers", v"0.3.0"], - ["ImageCore", v"0.3.0", "MappedArrays", v"0.0.3"], - ["ImageCore", v"0.3.0", "OffsetArrays"], - ["ImageCore", v"0.3.0", "ShowItLikeYouBuildIt"], - ["ImageFiltering", v"0.0.2", "CatIndices"], - ["ImageFiltering", v"0.0.2", "ColorVectorSpace"], - ["ImageFiltering", v"0.0.2", "Colors"], - ["ImageFiltering", v"0.0.2", "ComputationalResources"], - ["ImageFiltering", v"0.0.2", "ImageCore"], - ["ImageFiltering", v"0.0.2", "DataStructures", v"0.4.6"], - ["ImageFiltering", v"0.0.2", "FFTViews"], - ["ImageFiltering", v"0.0.2", "MappedArrays"], - ["ImageFiltering", v"0.0.2", "OffsetArrays"], - ["ImageFiltering", v"0.0.2", "StaticArrays", v"0.0.5"], - ["ImageFiltering", v"0.0.2", "TiledIteration"], - ["ImageFiltering", v"0.0.2", "FixedPointNumbers", v"0.0.0-", v"0.3.0"], - ["ImageFiltering", v"0.1.2", "CatIndices"], - ["ImageFiltering", v"0.1.2", "ColorVectorSpace"], - ["ImageFiltering", v"0.1.2", "Colors"], - ["ImageFiltering", v"0.1.2", "ComputationalResources"], - ["ImageFiltering", v"0.1.2", "FFTViews"], - ["ImageFiltering", v"0.1.2", "ImageCore"], - ["ImageFiltering", v"0.1.2", "DataStructures", v"0.4.6"], - ["ImageFiltering", v"0.1.2", "MappedArrays"], - ["ImageFiltering", v"0.1.2", "OffsetArrays"], - ["ImageFiltering", v"0.1.2", "FixedPointNumbers", v"0.3.0"], - ["ImageFiltering", v"0.1.2", "StaticArrays", v"0.0.5"], - ["ImageFiltering", v"0.1.2", "TiledIteration"], - ["ImageFiltering", v"0.1.4", "CatIndices"], - ["ImageFiltering", v"0.1.4", "ColorVectorSpace"], - ["ImageFiltering", v"0.1.4", "Colors"], - ["ImageFiltering", v"0.1.4", "ComputationalResources"], - ["ImageFiltering", v"0.1.4", "Compat", v"0.18.0"], - ["ImageFiltering", v"0.1.4", "DataStructures", v"0.4.6"], - ["ImageFiltering", v"0.1.4", "FFTViews"], - ["ImageFiltering", v"0.1.4", "ImageCore"], - ["ImageFiltering", v"0.1.4", "MappedArrays"], - ["ImageFiltering", v"0.1.4", "OffsetArrays"], - ["ImageFiltering", v"0.1.4", "TiledIteration"], - ["ImageFiltering", v"0.1.4", "FixedPointNumbers", v"0.3.0"], - ["ImageFiltering", v"0.1.4", "StaticArrays", v"0.0.5"], - ["ImageMagick", v"0.0.1", "BinDeps"], - ["ImageMagick", v"0.0.1", "ColorTypes"], - ["ImageMagick", v"0.0.1", "Compat"], - ["ImageMagick", v"0.0.1", "FileIO"], - ["ImageMagick", v"0.0.1", "FixedPointNumbers", v"0.0.0-", v"0.3.0"], - ["ImageMagick", v"0.0.1", "Images", v"0.0.0-", v"0.6.0"], - ["ImageMagick", v"0.1.3", "BinDeps"], - ["ImageMagick", v"0.1.3", "ColorTypes", v"0.2.0"], - ["ImageMagick", v"0.1.3", "FileIO"], - ["ImageMagick", v"0.1.3", "FixedPointNumbers", v"0.1.0", v"0.3.0"], - ["ImageMagick", v"0.1.3", "Images", v"0.0.0-", v"0.6.0"], - ["ImageMagick", v"0.1.6", "BinDeps"], - ["ImageMagick", v"0.1.6", "ColorTypes", v"0.2.0"], - ["ImageMagick", v"0.1.6", "Compat", v"0.7.7"], - ["ImageMagick", v"0.1.6", "FileIO"], - ["ImageMagick", v"0.1.6", "FixedPointNumbers", v"0.1.0", v"0.3.0"], - ["ImageMagick", v"0.1.6", "Images", v"0.0.0-", v"0.6.0"], - ["ImageMagick", v"0.1.7", "BinDeps"], - ["ImageMagick", v"0.1.7", "ColorTypes", v"0.2.0"], - ["ImageMagick", v"0.1.7", "Compat", v"0.8.4"], - ["ImageMagick", v"0.1.7", "FileIO"], - ["ImageMagick", v"0.1.7", "FixedPointNumbers", v"0.1.0", v"0.3.0"], - ["ImageMagick", v"0.1.7", "Images", v"0.0.0-", v"0.6.0"], - ["ImageMagick", v"0.1.8", "BinDeps"], - ["ImageMagick", v"0.1.8", "ColorTypes", v"0.2.7"], - ["ImageMagick", v"0.1.8", "Compat", v"0.8.4"], - ["ImageMagick", v"0.1.8", "FileIO"], - ["ImageMagick", v"0.1.8", "FixedPointNumbers", v"0.1.8", v"0.3.0"], - ["ImageMagick", v"0.1.8", "Images", v"0.0.0-", v"0.6.0"], - ["ImageMagick", v"0.2.1", "BinDeps"], - ["ImageMagick", v"0.2.1", "ColorTypes", v"0.2.7"], - ["ImageMagick", v"0.2.1", "FileIO"], - ["ImageMagick", v"0.2.1", "FixedPointNumbers", v"0.3.0"], - ["ImageMagick", v"0.2.3", "BinDeps"], - ["ImageMagick", v"0.2.3", "ColorTypes", v"0.2.7"], - ["ImageMagick", v"0.2.3", "Compat", v"0.18.0"], - ["ImageMagick", v"0.2.3", "FileIO"], - ["ImageMagick", v"0.2.3", "FixedPointNumbers", v"0.3.0"], - ["ImageMagick", v"0.2.3", "ImageCore", v"0.1.0"], - ["ImageMagick", v"0.2.4", "BinDeps"], - ["ImageMagick", v"0.2.4", "ColorTypes", v"0.2.7"], - ["ImageMagick", v"0.2.4", "Compat", v"0.24.0"], - ["ImageMagick", v"0.2.4", "FileIO"], - ["ImageMagick", v"0.2.4", "FixedPointNumbers", v"0.3.0"], - ["ImageMagick", v"0.2.4", "Images", v"0.6.0"], - ["ImageMetadata", v"0.0.1", "Colors"], - ["ImageMetadata", v"0.0.1", "FixedPointNumbers", v"0.0.0-", v"0.3.0"], - ["ImageMetadata", v"0.0.1", "ImageAxes"], - ["ImageMetadata", v"0.0.1", "ColorVectorSpace", v"0.1.11"], - ["ImageMetadata", v"0.0.1", "ImageCore"], - ["ImageMetadata", v"0.0.1", "IndirectArrays"], - ["ImageMetadata", v"0.2.0", "Colors"], - ["ImageMetadata", v"0.2.0", "ImageAxes"], - ["ImageMetadata", v"0.2.0", "ColorVectorSpace", v"0.1.11"], - ["ImageMetadata", v"0.2.0", "FixedPointNumbers", v"0.3.0"], - ["ImageMetadata", v"0.2.0", "ImageCore"], - ["ImageMetadata", v"0.2.0", "IndirectArrays"], - ["ImageMetadata", v"0.2.3", "Colors"], - ["ImageMetadata", v"0.2.3", "ImageAxes"], - ["ImageMetadata", v"0.2.3", "ColorVectorSpace", v"0.1.11"], - ["ImageMetadata", v"0.2.3", "Compat", v"0.19.0"], - ["ImageMetadata", v"0.2.3", "FixedPointNumbers", v"0.3.0"], - ["ImageMetadata", v"0.2.3", "ImageCore"], - ["ImageMetadata", v"0.2.3", "IndirectArrays"], - ["ImageTransformations", v"0.0.1", "ColorVectorSpace", v"0.2.0"], - ["ImageTransformations", v"0.0.1", "Colors", v"0.7.0"], - ["ImageTransformations", v"0.0.1", "CoordinateTransformations", v"0.4.0"], - ["ImageTransformations", v"0.0.1", "ImageCore", v"0.1.2"], - ["ImageTransformations", v"0.0.1", "Interpolations", v"0.3.7"], - ["ImageTransformations", v"0.0.1", "OffsetArrays"], - ["ImageTransformations", v"0.0.1", "StaticArrays"], - ["ImageTransformations", v"0.1.0", "ColorVectorSpace", v"0.2.0"], - ["ImageTransformations", v"0.1.0", "Colors", v"0.7.0"], - ["ImageTransformations", v"0.1.0", "CoordinateTransformations", v"0.4.0"], - ["ImageTransformations", v"0.1.0", "FixedPointNumbers", v"0.3.0"], - ["ImageTransformations", v"0.1.0", "ImageCore", v"0.1.2"], - ["ImageTransformations", v"0.1.0", "Interpolations", v"0.3.7"], - ["ImageTransformations", v"0.1.0", "OffsetArrays"], - ["ImageTransformations", v"0.1.0", "StaticArrays"], - ["ImageTransformations", v"0.2.2", "AxisAlgorithms"], - ["ImageTransformations", v"0.2.2", "ColorVectorSpace", v"0.2.0"], - ["ImageTransformations", v"0.2.2", "Colors", v"0.7.0"], - ["ImageTransformations", v"0.2.2", "Compat", v"0.18.0"], - ["ImageTransformations", v"0.2.2", "CoordinateTransformations", v"0.4.0"], - ["ImageTransformations", v"0.2.2", "OffsetArrays"], - ["ImageTransformations", v"0.2.2", "StaticArrays"], - ["ImageTransformations", v"0.2.2", "FixedPointNumbers", v"0.3.0"], - ["ImageTransformations", v"0.2.2", "ImageCore", v"0.1.2"], - ["ImageTransformations", v"0.2.2", "Interpolations", v"0.4.0"], - ["Images", v"0.4.50", "BinDeps"], - ["Images", v"0.4.50", "ColorVectorSpace"], - ["Images", v"0.4.50", "Colors"], - ["Images", v"0.4.50", "SIUnits"], - ["Images", v"0.4.50", "Compat", v"0.4.0"], - ["Images", v"0.4.50", "FixedPointNumbers", v"0.0.0-", v"0.3.0"], - ["Images", v"0.4.50", "Graphics", v"0.1.0"], - ["Images", v"0.4.50", "Zlib"], - ["Images", v"0.5.4", "FileIO"], - ["Images", v"0.5.4", "SIUnits"], - ["Images", v"0.5.4", "ColorVectorSpace", v"0.1.0"], - ["Images", v"0.5.4", "Colors", v"0.6.0"], - ["Images", v"0.5.4", "Graphics", v"0.1.0"], - ["Images", v"0.5.4", "FixedPointNumbers", v"0.1.0", v"0.3.0"], - ["Images", v"0.5.4", "Zlib"], - ["Images", v"0.5.5", "ColorVectorSpace", v"0.1.0"], - ["Images", v"0.5.5", "Colors", v"0.6.0"], - ["Images", v"0.5.5", "Compat", v"0.7.15"], - ["Images", v"0.5.5", "FileIO"], - ["Images", v"0.5.5", "Graphics", v"0.1.0"], - ["Images", v"0.5.5", "FixedPointNumbers", v"0.1.0", v"0.3.0"], - ["Images", v"0.5.5", "SIUnits"], - ["Images", v"0.5.5", "Zlib"], - ["Images", v"0.5.9", "ColorVectorSpace", v"0.1.0"], - ["Images", v"0.5.9", "Colors", v"0.6.0"], - ["Images", v"0.5.9", "Compat", v"0.8.4"], - ["Images", v"0.5.9", "FileIO"], - ["Images", v"0.5.9", "Graphics", v"0.1.0"], - ["Images", v"0.5.9", "FixedPointNumbers", v"0.1.0", v"0.3.0"], - ["Images", v"0.5.9", "SIUnits"], - ["Images", v"0.5.9", "StatsBase"], - ["Images", v"0.5.9", "Zlib"], - ["Images", v"0.5.14", "ColorVectorSpace", v"0.1.0"], - ["Images", v"0.5.14", "Colors", v"0.6.0"], - ["Images", v"0.5.14", "Compat", v"0.9.1"], - ["Images", v"0.5.14", "FileIO"], - ["Images", v"0.5.14", "Graphics", v"0.1.0"], - ["Images", v"0.5.14", "FixedPointNumbers", v"0.1.0", v"0.3.0"], - ["Images", v"0.5.14", "SIUnits"], - ["Images", v"0.5.14", "StatsBase"], - ["Images", v"0.5.14", "Zlib"], - ["Images", v"0.6.0", "AxisArrays"], - ["Images", v"0.6.0", "FileIO"], - ["Images", v"0.6.0", "ImageAxes"], - ["Images", v"0.6.0", "ImageCore"], - ["Images", v"0.6.0", "ImageFiltering"], - ["Images", v"0.6.0", "ImageMetadata"], - ["Images", v"0.6.0", "IndirectArrays"], - ["Images", v"0.6.0", "MappedArrays"], - ["Images", v"0.6.0", "Reexport"], - ["Images", v"0.6.0", "SIUnits"], - ["Images", v"0.6.0", "StatsBase"], - ["Images", v"0.6.0", "Zlib"], - ["Images", v"0.6.0", "ColorVectorSpace", v"0.2.0"], - ["Images", v"0.6.0", "Colors", v"0.7.0"], - ["Images", v"0.6.0", "Compat", v"0.9.1"], - ["Images", v"0.6.0", "FixedPointNumbers", v"0.3.0"], - ["Images", v"0.6.0", "Graphics", v"0.1.0"], - ["Images", v"0.7.0", "AxisArrays"], - ["Images", v"0.7.0", "FileIO"], - ["Images", v"0.7.0", "ColorVectorSpace", v"0.2.0"], - ["Images", v"0.7.0", "Colors", v"0.7.0"], - ["Images", v"0.7.0", "Compat", v"0.9.1"], - ["Images", v"0.7.0", "Graphics", v"0.1.0"], - ["Images", v"0.7.0", "ImageAxes"], - ["Images", v"0.7.0", "ImageCore"], - ["Images", v"0.7.0", "ImageFiltering"], - ["Images", v"0.7.0", "ImageMetadata"], - ["Images", v"0.7.0", "IndirectArrays"], - ["Images", v"0.7.0", "MappedArrays"], - ["Images", v"0.7.0", "Reexport"], - ["Images", v"0.7.0", "SIUnits"], - ["Images", v"0.7.0", "StatsBase"], - ["Images", v"0.7.0", "FixedPointNumbers", v"0.3.0"], - ["Images", v"0.8.0", "AxisArrays"], - ["Images", v"0.8.0", "FileIO"], - ["Images", v"0.8.0", "ImageAxes"], - ["Images", v"0.8.0", "ImageCore"], - ["Images", v"0.8.0", "ColorVectorSpace", v"0.2.0"], - ["Images", v"0.8.0", "Colors", v"0.7.0"], - ["Images", v"0.8.0", "Compat", v"0.9.1"], - ["Images", v"0.8.0", "Graphics", v"0.1.0"], - ["Images", v"0.8.0", "ImageFiltering"], - ["Images", v"0.8.0", "ImageMetadata"], - ["Images", v"0.8.0", "ImageTransformations"], - ["Images", v"0.8.0", "IndirectArrays"], - ["Images", v"0.8.0", "MappedArrays"], - ["Images", v"0.8.0", "Reexport"], - ["Images", v"0.8.0", "SIUnits"], - ["Images", v"0.8.0", "StatsBase"], - ["Images", v"0.8.0", "FixedPointNumbers", v"0.3.0"], - ["Images", v"0.9.0", "AxisArrays"], - ["Images", v"0.9.0", "FileIO"], - ["Images", v"0.9.0", "Graphics", v"0.1.0"], - ["Images", v"0.9.0", "ImageAxes"], - ["Images", v"0.9.0", "ImageCore"], - ["Images", v"0.9.0", "ColorVectorSpace", v"0.2.0"], - ["Images", v"0.9.0", "Colors", v"0.7.0"], - ["Images", v"0.9.0", "Compat", v"0.18.0"], - ["Images", v"0.9.0", "ImageFiltering"], - ["Images", v"0.9.0", "ImageMetadata"], - ["Images", v"0.9.0", "ImageTransformations"], - ["Images", v"0.9.0", "IndirectArrays"], - ["Images", v"0.9.0", "MappedArrays"], - ["Images", v"0.9.0", "Reexport"], - ["Images", v"0.9.0", "SIUnits"], - ["Images", v"0.9.0", "StatsBase"], - ["Images", v"0.9.0", "FixedPointNumbers", v"0.3.0"], - ["Images", v"0.9.1", "AxisArrays"], - ["Images", v"0.9.1", "FileIO"], - ["Images", v"0.9.1", "ImageAxes"], - ["Images", v"0.9.1", "ImageCore"], - ["Images", v"0.9.1", "ColorVectorSpace", v"0.2.0"], - ["Images", v"0.9.1", "Colors", v"0.7.0"], - ["Images", v"0.9.1", "Compat", v"0.19.0"], - ["Images", v"0.9.1", "ImageFiltering"], - ["Images", v"0.9.1", "ImageMetadata"], - ["Images", v"0.9.1", "ImageTransformations"], - ["Images", v"0.9.1", "IndirectArrays"], - ["Images", v"0.9.1", "MappedArrays"], - ["Images", v"0.9.1", "Reexport"], - ["Images", v"0.9.1", "SIUnits"], - ["Images", v"0.9.1", "StatsBase"], - ["Images", v"0.9.1", "FixedPointNumbers", v"0.3.0"], - ["Images", v"0.9.1", "Graphics", v"0.1.0"], - ["IndirectArrays", v"0.1.0"], - ["IndirectArrays", v"0.1.1", "Compat", v"0.19.0"], - ["InplaceOps", v"0.1.0"], - ["Interpolations", v"0.0.1-beta", "Compat"], - ["Interpolations", v"0.0.1-beta", "WoodburyMatrices"], - ["Interpolations", v"0.1.0", "WoodburyMatrices"], - ["Interpolations", v"0.3.4", "AxisAlgorithms"], - ["Interpolations", v"0.3.4", "Ratios"], - ["Interpolations", v"0.3.4", "WoodburyMatrices", v"0.1.0"], - ["Interpolations", v"0.3.5", "AxisAlgorithms"], - ["Interpolations", v"0.3.5", "Ratios"], - ["Interpolations", v"0.3.5", "WoodburyMatrices", v"0.1.5"], - ["Interpolations", v"0.3.6", "AxisAlgorithms"], - ["Interpolations", v"0.3.6", "Ratios"], - ["Interpolations", v"0.3.6", "Compat", v"0.8.0"], - ["Interpolations", v"0.3.6", "WoodburyMatrices", v"0.1.5"], - ["Interpolations", v"0.3.7", "AxisAlgorithms"], - ["Interpolations", v"0.3.7", "DualNumbers"], - ["Interpolations", v"0.3.7", "Ratios"], - ["Interpolations", v"0.3.7", "Compat", v"0.8.0"], - ["Interpolations", v"0.3.7", "WoodburyMatrices", v"0.1.5"], - ["Interpolations", v"0.3.8", "AxisAlgorithms"], - ["Interpolations", v"0.3.8", "DualNumbers"], - ["Interpolations", v"0.3.8", "Ratios"], - ["Interpolations", v"0.3.8", "Compat", v"0.19.0"], - ["Interpolations", v"0.3.8", "WoodburyMatrices", v"0.1.5"], - ["Interpolations", v"0.4.0", "AxisAlgorithms"], - ["Interpolations", v"0.4.0", "DualNumbers"], - ["Interpolations", v"0.4.0", "Ratios"], - ["Interpolations", v"0.4.0", "Compat", v"0.19.0"], - ["Interpolations", v"0.4.0", "WoodburyMatrices", v"0.1.5"], - ["Interpolations", v"0.5.0", "AxisAlgorithms"], - ["Interpolations", v"0.5.0", "DualNumbers"], - ["Interpolations", v"0.5.0", "Ratios"], - ["Interpolations", v"0.5.0", "ShowItLikeYouBuildIt"], - ["Interpolations", v"0.5.0", "Compat", v"0.19.0"], - ["Interpolations", v"0.5.0", "WoodburyMatrices", v"0.1.5"], - ["IntervalSets", v"0.0.2"], - ["IntervalSets", v"0.0.5", "Compat", v"0.17.0"], - ["IterativeSolvers", v"0.0.1", "Compat"], - ["IterativeSolvers", v"0.0.1", "Docile"], - ["IterativeSolvers", v"0.2.1", "Compat"], - ["IterativeSolvers", v"0.2.2", "Compat"], - ["Iterators", v"0.1.10", "Compat"], - ["Iterators", v"0.3.0"], - ["JLD", v"0.6.4", "Compat", v"0.8.0"], - ["JLD", v"0.6.4", "FileIO"], - ["JLD", v"0.6.4", "HDF5"], - ["JLD", v"0.6.4", "LegacyStrings"], - ["JLD", v"0.6.10", "Compat", v"0.8.0"], - ["JLD", v"0.6.10", "FileIO"], - ["JLD", v"0.6.10", "HDF5"], - ["JLD", v"0.6.10", "LegacyStrings"], - ["JSON", v"0.3.9"], - ["JSON", v"0.4.4", "Compat"], - ["JSON", v"0.4.5", "Compat", v"0.4.12"], - ["JSON", v"0.5.0", "Compat", v"0.7.1"], - ["JSON", v"0.5.4", "Compat", v"0.7.16"], - ["JSON", v"0.6.0", "Compat", v"0.7.20"], - ["JSON", v"0.8.0", "Compat", v"0.8.4"], - ["JSON", v"0.8.2", "Compat", v"0.9.5"], - ["JSON", v"0.8.3", "Compat", v"0.17.0"], - ["JSON", v"0.9.0", "Compat", v"0.17.0"], - ["JuliaParser", v"0.5.3", "FactCheck"], - ["JuliaParser", v"0.6.4", "Compat"], - ["JuliaParser", v"0.6.4", "FactCheck"], - ["JuliaParser", v"0.7.0", "AbstractTrees"], - ["JuliaParser", v"0.7.0", "Compat"], - ["JuliaParser", v"0.7.1", "AbstractTrees"], - ["JuliaParser", v"0.7.1", "Compat"], - ["JuliaParser", v"0.7.4", "AbstractTrees"], - ["JuliaParser", v"0.7.4", "Compat"], - ["Juno", v"0.2.3", "Hiccup"], - ["Juno", v"0.2.3", "MacroTools"], - ["Juno", v"0.2.3", "Media"], - ["Juno", v"0.2.4", "Hiccup"], - ["Juno", v"0.2.4", "MacroTools"], - ["Juno", v"0.2.4", "Media"], - ["Juno", v"0.2.5", "Hiccup"], - ["Juno", v"0.2.5", "MacroTools"], - ["Juno", v"0.2.5", "Media"], - ["Juno", v"0.2.7", "Hiccup"], - ["Juno", v"0.2.7", "MacroTools"], - ["Juno", v"0.2.7", "Media"], - ["LNR", v"0.0.0"], - ["LNR", v"0.0.1", "Lazy"], - ["LNR", v"0.0.2", "Compat"], - ["LNR", v"0.0.2", "Lazy"], - ["Lazy", v"0.9.1"], - ["Lazy", v"0.10.0", "MacroTools"], - ["Lazy", v"0.10.1", "Compat"], - ["Lazy", v"0.10.1", "MacroTools"], - ["Lazy", v"0.11.2", "MacroTools"], - ["Lazy", v"0.11.2", "Compat", v"0.8.0"], - ["Lazy", v"0.11.6", "MacroTools"], - ["Lazy", v"0.11.6", "Compat", v"0.8.0"], - ["LearnBase", v"0.1.0", "StatsBase"], - ["LearnBase", v"0.1.1", "Distributions"], - ["LearnBase", v"0.1.1", "StatsBase"], - ["LearnBase", v"0.1.2", "Distributions"], - ["LearnBase", v"0.1.2", "StatsBase", v"0.8.0"], - ["LearnBase", v"0.1.3", "Distributions"], - ["LearnBase", v"0.1.3", "Compat", v"0.17.0"], - ["LearnBase", v"0.1.3", "StatsBase", v"0.8.0"], - ["LearnBase", v"0.1.5", "Distributions"], - ["LearnBase", v"0.1.5", "Compat", v"0.18.0"], - ["LearnBase", v"0.1.5", "StatsBase", v"0.8.0"], - ["LegacyStrings", v"0.1.0"], - ["LegacyStrings", v"0.2.0", "Compat", v"0.8.4"], - ["LegacyStrings", v"0.2.1", "Compat", v"0.18.0"], - ["LineSearches", v"0.0.2"], - ["LineSearches", v"0.1.1"], - ["LineSearches", v"0.1.5"], - ["LossFunctions", v"0.0.1", "LearnBase", v"0.0.1", v"0.2.0"], - ["LossFunctions", v"0.0.1", "RecipesBase"], - ["LossFunctions", v"0.0.1", "Reexport"], - ["LossFunctions", v"0.0.2", "LearnBase", v"0.0.1", v"0.2.0"], - ["LossFunctions", v"0.0.2", "RecipesBase"], - ["LossFunctions", v"0.0.2", "Reexport"], - ["LossFunctions", v"0.0.3", "LearnBase", v"0.1.2", v"0.2.0"], - ["LossFunctions", v"0.0.3", "RecipesBase"], - ["LossFunctions", v"0.0.3", "StatsBase", v"0.8.0"], - ["LossFunctions", v"0.1.0", "LearnBase", v"0.1.3", v"0.2.0"], - ["LossFunctions", v"0.1.0", "RecipesBase"], - ["LossFunctions", v"0.1.0", "StatsBase", v"0.8.0"], - ["LsqFit", v"0.0.1", "Calculus"], - ["LsqFit", v"0.0.1", "Distributions"], - ["LsqFit", v"0.0.1", "Optim", v"0.0.0", v"0.5.0"], - ["LsqFit", v"0.0.2", "Calculus"], - ["LsqFit", v"0.0.2", "Distributions"], - ["LsqFit", v"0.0.2", "Optim"], - ["LsqFit", v"0.1.0", "Calculus"], - ["LsqFit", v"0.1.0", "Distributions"], - ["LsqFit", v"0.1.0", "Optim", v"0.6.0"], - ["LsqFit", v"0.1.1", "Calculus"], - ["LsqFit", v"0.1.1", "Distributions"], - ["LsqFit", v"0.1.1", "Optim", v"0.7.0"], - ["LsqFit", v"0.2.0", "Calculus"], - ["LsqFit", v"0.2.0", "Distributions"], - ["LsqFit", v"0.2.0", "Compat", v"0.9.1"], - ["LsqFit", v"0.2.0", "Optim", v"0.7.5"], - ["MachO", v"0.0.4", "ObjFileBase"], - ["MachO", v"0.0.4", "StructIO"], - ["MacroTools", v"0.1.0"], - ["MacroTools", v"0.3.0"], - ["MacroTools", v"0.3.1", "Compat"], - ["MacroTools", v"0.3.3", "Compat"], - ["MacroTools", v"0.3.6", "Compat", v"0.7.9"], - ["MappedArrays", v"0.0.2"], - ["MappedArrays", v"0.0.5"], - ["MappedArrays", v"0.0.7", "Compat", v"0.19.0"], - ["Markdown", v"0.1.0"], - ["Markdown", v"0.3.0", "Lazy"], - ["MbedTLS", v"0.2.3", "BinDeps"], - ["MbedTLS", v"0.2.3", "Compat", v"0.7.9"], - ["MbedTLS", v"0.3.0", "BinDeps"], - ["MbedTLS", v"0.3.0", "Compat", v"0.8.0"], - ["MbedTLS", v"0.4.4", "BinDeps"], - ["MbedTLS", v"0.4.5", "BinDeps"], - ["MbedTLS", v"0.4.5", "Compat", v"0.9.5"], - ["Measures", v"0.0.2"], - ["Measures", v"0.0.3", "Compat", v"0.7.15"], - ["Measures", v"0.1.0", "Compat", v"0.18.0"], - ["Media", v"0.1.0", "Lazy"], - ["Media", v"0.1.0", "Requires"], - ["Media", v"0.2.2", "Lazy"], - ["Media", v"0.2.2", "MacroTools"], - ["Media", v"0.2.2", "Requires"], - ["Media", v"0.2.3", "MacroTools"], - ["Media", v"0.2.3", "Lazy", v"0.11.3"], - ["Media", v"0.2.7", "MacroTools"], - ["MultiScaleArrays", v"0.0.1", "Iterators"], - ["MultiScaleArrays", v"0.0.1", "RecursiveArrayTools", v"0.0.2"], - ["MultiScaleArrays", v"0.1.0", "DiffEqBase", v"0.11.0"], - ["MultiScaleArrays", v"0.1.0", "Iterators"], - ["MultiScaleArrays", v"0.1.0", "RecursiveArrayTools", v"0.0.2"], - ["Mustache", v"0.0.1", "DataFrames"], - ["Mustache", v"0.0.7", "Compat"], - ["Mustache", v"0.0.7", "Requires"], - ["Mustache", v"0.0.14", "Requires"], - ["Mustache", v"0.0.14", "Compat", v"0.4.0"], - ["Mustache", v"0.1.0"], - ["Mustache", v"0.1.4", "Compat", v"0.7.18"], - ["Mux", v"0.0.0", "Hiccup"], - ["Mux", v"0.0.0", "HttpServer"], - ["Mux", v"0.0.0", "Lazy"], - ["Mux", v"0.0.0", "URIParser"], - ["Mux", v"0.1.1", "Compat"], - ["Mux", v"0.1.1", "Hiccup"], - ["Mux", v"0.1.1", "HttpCommon"], - ["Mux", v"0.1.1", "HttpServer"], - ["Mux", v"0.1.1", "Lazy"], - ["Mux", v"0.1.1", "URIParser"], - ["Mux", v"0.1.1", "WebSockets"], - ["Mux", v"0.2.2", "Hiccup"], - ["Mux", v"0.2.2", "HttpCommon"], - ["Mux", v"0.2.2", "HttpServer"], - ["Mux", v"0.2.2", "Lazy"], - ["Mux", v"0.2.2", "URIParser"], - ["Mux", v"0.2.2", "WebSockets"], - ["Mux", v"0.2.3", "Hiccup"], - ["Mux", v"0.2.3", "HttpCommon"], - ["Mux", v"0.2.3", "Compat", v"0.7.9"], - ["Mux", v"0.2.3", "HttpServer"], - ["Mux", v"0.2.3", "Lazy"], - ["Mux", v"0.2.3", "URIParser"], - ["Mux", v"0.2.3", "WebSockets"], - ["NLSolversBase", v"2.1.1", "Compat", v"0.17.0"], - ["NLsolve", v"0.7.3", "Calculus"], - ["NLsolve", v"0.7.3", "Distances"], - ["NLsolve", v"0.7.3", "Optim"], - ["NLsolve", v"0.7.3", "Compat", v"0.8.0"], - ["NLsolve", v"0.7.3", "ForwardDiff", v"0.2.0"], - ["NLsolve", v"0.7.3", "LineSearches", v"0.0.1", v"1.0.0-"], - ["NLsolve", v"0.8.0", "Calculus"], - ["NLsolve", v"0.8.0", "Distances"], - ["NLsolve", v"0.8.0", "Optim"], - ["NLsolve", v"0.8.0", "Compat", v"0.8.4"], - ["NLsolve", v"0.8.0", "ForwardDiff", v"0.2.0"], - ["NLsolve", v"0.8.0", "LineSearches", v"0.0.1", v"1.0.0-"], - ["NLsolve", v"0.9.0", "Calculus"], - ["NLsolve", v"0.9.0", "DiffBase"], - ["NLsolve", v"0.9.0", "Distances"], - ["NLsolve", v"0.9.0", "Optim"], - ["NLsolve", v"0.9.0", "Compat", v"0.8.4"], - ["NLsolve", v"0.9.0", "ForwardDiff", v"0.3.0"], - ["NLsolve", v"0.9.0", "LineSearches", v"0.1.2", v"1.0.0-"], - ["NLsolve", v"0.9.1", "Calculus"], - ["NLsolve", v"0.9.1", "DiffBase"], - ["NLsolve", v"0.9.1", "Distances"], - ["NLsolve", v"0.9.1", "Optim"], - ["NLsolve", v"0.9.1", "Compat", v"0.8.4"], - ["NLsolve", v"0.9.1", "ForwardDiff", v"0.3.0"], - ["NLsolve", v"0.9.1", "LineSearches", v"0.1.2", v"1.0.0-"], - ["NaNMath", v"0.1.1", "Compat"], - ["NaNMath", v"0.2.0"], - ["NaNMath", v"0.2.1"], - ["NaNMath", v"0.2.3", "Compat", v"0.9.1"], - ["NaNMath", v"0.2.4", "Compat", v"0.9.1"], - ["Nettle", v"0.1.1"], - ["Nettle", v"0.1.7", "BinDeps"], - ["Nettle", v"0.1.10", "BinDeps"], - ["Nettle", v"0.1.10", "Compat"], - ["Nettle", v"0.2.3", "BinDeps"], - ["Nettle", v"0.2.3", "Compat"], - ["Nettle", v"0.3.0", "BinDeps"], - ["Nettle", v"0.3.0", "Compat", v"0.8.0"], - ["NumericExtensions", v"0.3.6"], - ["NumericExtensions", v"0.4.3", "ArrayViews", v"0.2.0-"], - ["NumericExtensions", v"0.5.6", "ArrayViews", v"0.2.0-"], - ["NumericExtensions", v"0.6.2", "ArrayViews", v"0.2.0-"], - ["NumericExtensions", v"0.6.2", "NumericFuns", v"0.2.1-"], - ["NumericFuns", v"0.2.0"], - ["NumericFuns", v"0.2.3"], - ["NumericFuns", v"0.2.4", "Compat"], - ["ObjFileBase", v"0.0.4"], - ["OffsetArrays", v"0.2.13"], - ["OffsetArrays", v"0.3.0", "Compat", v"0.19.0"], - ["Optim", v"0.4.6", "Calculus"], - ["Optim", v"0.4.6", "Compat"], - ["Optim", v"0.4.6", "DualNumbers"], - ["Optim", v"0.4.6", "LineSearches", v"0.0.1", v"1.0.0-"], - ["Optim", v"0.4.7", "Calculus"], - ["Optim", v"0.4.7", "DualNumbers", v"0.2.0"], - ["Optim", v"0.4.7", "PositiveFactorizations"], - ["Optim", v"0.4.7", "LineSearches", v"0.0.1", v"1.0.0-"], - ["Optim", v"0.5.0", "Calculus"], - ["Optim", v"0.5.0", "PositiveFactorizations"], - ["Optim", v"0.5.0", "Compat", v"0.7.16"], - ["Optim", v"0.5.0", "DualNumbers", v"0.2.0"], - ["Optim", v"0.5.0", "LineSearches", v"0.0.1", v"1.0.0-"], - ["Optim", v"0.6.1", "Calculus"], - ["Optim", v"0.6.1", "PositiveFactorizations"], - ["Optim", v"0.6.1", "Compat", v"0.8.4"], - ["Optim", v"0.6.1", "ForwardDiff", v"0.2.0", v"0.3.0"], - ["Optim", v"0.6.1", "LineSearches", v"0.0.1", v"1.0.0-"], - ["Optim", v"0.7.2", "Calculus"], - ["Optim", v"0.7.2", "PositiveFactorizations"], - ["Optim", v"0.7.2", "Compat", v"0.8.4"], - ["Optim", v"0.7.2", "ForwardDiff", v"0.3.0", v"0.4.0"], - ["Optim", v"0.7.2", "LineSearches", v"0.1.0", v"1.0.0-"], - ["Optim", v"0.7.4", "Calculus"], - ["Optim", v"0.7.4", "PositiveFactorizations"], - ["Optim", v"0.7.4", "Compat", v"0.8.4"], - ["Optim", v"0.7.4", "ForwardDiff", v"0.3.0", v"0.4.0"], - ["Optim", v"0.7.4", "LineSearches", v"0.1.2", v"1.0.0-"], - ["Optim", v"0.7.5", "Calculus"], - ["Optim", v"0.7.5", "PositiveFactorizations"], - ["Optim", v"0.7.5", "Compat", v"0.8.4"], - ["Optim", v"0.7.5", "ForwardDiff", v"0.3.0", v"0.4.0"], - ["Optim", v"0.7.5", "LineSearches", v"0.1.2", v"1.0.0-"], - ["Optim", v"0.7.7", "Calculus"], - ["Optim", v"0.7.7", "PositiveFactorizations"], - ["Optim", v"0.7.7", "Compat", v"0.18.0"], - ["Optim", v"0.7.7", "ForwardDiff", v"0.3.0", v"0.4.0"], - ["Optim", v"0.7.7", "LineSearches", v"0.1.2", v"1.0.0-"], - ["Optim", v"0.7.8", "Calculus"], - ["Optim", v"0.7.8", "PositiveFactorizations"], - ["Optim", v"0.7.8", "Compat", v"0.18.0"], - ["Optim", v"0.7.8", "ForwardDiff", v"0.3.0", v"0.5.0"], - ["Optim", v"0.7.8", "LineSearches", v"0.1.2", v"1.0.0-"], - ["Options", v"0.2.6"], - ["OrdinaryDiffEq", v"0.0.1", "Compat", v"0.8.8"], - ["OrdinaryDiffEq", v"0.0.1", "DiffEqBase", v"0.0.0", v"0.7.0"], - ["OrdinaryDiffEq", v"0.0.1", "ForwardDiff", v"0.2.4"], - ["OrdinaryDiffEq", v"0.0.1", "GenericSVD", v"0.0.2"], - ["OrdinaryDiffEq", v"0.0.1", "InplaceOps", v"0.0.5"], - ["OrdinaryDiffEq", v"0.0.1", "NLsolve", v"0.7.3"], - ["OrdinaryDiffEq", v"0.0.1", "Parameters", v"0.5.0"], - ["OrdinaryDiffEq", v"0.0.1", "Ranges", v"0.0.1"], - ["OrdinaryDiffEq", v"0.0.1", "RecipesBase", v"0.1.0"], - ["OrdinaryDiffEq", v"0.0.1", "Sundials", v"0.3.0"], - ["OrdinaryDiffEq", v"0.0.3", "Compat", v"0.8.8"], - ["OrdinaryDiffEq", v"0.0.3", "DiffEqBase", v"0.0.0", v"0.7.0"], - ["OrdinaryDiffEq", v"0.0.3", "ForwardDiff", v"0.2.4"], - ["OrdinaryDiffEq", v"0.0.3", "GenericSVD", v"0.0.2"], - ["OrdinaryDiffEq", v"0.0.3", "InplaceOps", v"0.0.5"], - ["OrdinaryDiffEq", v"0.0.3", "NLsolve", v"0.7.3"], - ["OrdinaryDiffEq", v"0.0.3", "ParameterizedFunctions", v"0.1.0"], - ["OrdinaryDiffEq", v"0.0.3", "Parameters", v"0.5.0"], - ["OrdinaryDiffEq", v"0.0.3", "Ranges", v"0.0.1"], - ["OrdinaryDiffEq", v"0.0.3", "RecipesBase", v"0.1.0"], - ["OrdinaryDiffEq", v"0.0.3", "Sundials", v"0.3.0"], - ["OrdinaryDiffEq", v"0.0.5", "RecursiveArrayTools"], - ["OrdinaryDiffEq", v"0.0.5", "Compat", v"0.8.8"], - ["OrdinaryDiffEq", v"0.0.5", "DiffEqBase", v"0.0.0", v"0.7.0"], - ["OrdinaryDiffEq", v"0.0.5", "ForwardDiff", v"0.2.4"], - ["OrdinaryDiffEq", v"0.0.5", "GenericSVD", v"0.0.2"], - ["OrdinaryDiffEq", v"0.0.5", "InplaceOps", v"0.0.5"], - ["OrdinaryDiffEq", v"0.0.5", "NLsolve", v"0.7.3"], - ["OrdinaryDiffEq", v"0.0.5", "Parameters", v"0.5.0"], - ["OrdinaryDiffEq", v"0.0.5", "Ranges", v"0.0.1"], - ["OrdinaryDiffEq", v"0.0.5", "RecipesBase", v"0.1.0"], - ["OrdinaryDiffEq", v"0.0.5", "Sundials", v"0.3.0"], - ["OrdinaryDiffEq", v"0.1.0", "Compat", v"0.8.8"], - ["OrdinaryDiffEq", v"0.1.0", "DiffEqBase", v"0.0.0", v"0.7.0"], - ["OrdinaryDiffEq", v"0.1.0", "Juno"], - ["OrdinaryDiffEq", v"0.1.0", "RecursiveArrayTools"], - ["OrdinaryDiffEq", v"0.1.0", "ForwardDiff", v"0.2.4"], - ["OrdinaryDiffEq", v"0.1.0", "GenericSVD", v"0.0.2"], - ["OrdinaryDiffEq", v"0.1.0", "InplaceOps", v"0.0.5"], - ["OrdinaryDiffEq", v"0.1.0", "NLsolve", v"0.7.3"], - ["OrdinaryDiffEq", v"0.1.0", "Parameters", v"0.5.0"], - ["OrdinaryDiffEq", v"0.1.0", "Ranges", v"0.0.1"], - ["OrdinaryDiffEq", v"0.1.0", "RecipesBase", v"0.1.0"], - ["OrdinaryDiffEq", v"0.1.1", "Compat", v"0.8.8"], - ["OrdinaryDiffEq", v"0.1.1", "DiffEqBase", v"0.1.2", v"0.7.0"], - ["OrdinaryDiffEq", v"0.1.1", "ForwardDiff", v"0.2.4"], - ["OrdinaryDiffEq", v"0.1.1", "GenericSVD", v"0.0.2"], - ["OrdinaryDiffEq", v"0.1.1", "InplaceOps", v"0.0.5"], - ["OrdinaryDiffEq", v"0.1.1", "Juno", v"0.2.5"], - ["OrdinaryDiffEq", v"0.1.1", "NLsolve", v"0.7.3"], - ["OrdinaryDiffEq", v"0.1.1", "Parameters", v"0.5.0"], - ["OrdinaryDiffEq", v"0.1.1", "Ranges", v"0.0.1"], - ["OrdinaryDiffEq", v"0.1.1", "RecipesBase", v"0.1.0"], - ["OrdinaryDiffEq", v"0.1.1", "RecursiveArrayTools", v"0.0.2"], - ["OrdinaryDiffEq", v"0.5.0", "Calculus", v"0.1.15"], - ["OrdinaryDiffEq", v"0.5.0", "Compat", v"0.8.8"], - ["OrdinaryDiffEq", v"0.5.0", "DiffEqBase", v"0.2.0", v"0.7.0"], - ["OrdinaryDiffEq", v"0.5.0", "ForwardDiff", v"0.2.4"], - ["OrdinaryDiffEq", v"0.5.0", "GenericSVD", v"0.0.2"], - ["OrdinaryDiffEq", v"0.5.0", "InplaceOps", v"0.0.5"], - ["OrdinaryDiffEq", v"0.5.0", "Juno", v"0.2.5"], - ["OrdinaryDiffEq", v"0.5.0", "NLsolve", v"0.7.3"], - ["OrdinaryDiffEq", v"0.5.0", "Parameters", v"0.5.0"], - ["OrdinaryDiffEq", v"0.5.0", "Ranges", v"0.0.1"], - ["OrdinaryDiffEq", v"0.5.0", "RecipesBase", v"0.1.0"], - ["OrdinaryDiffEq", v"0.5.0", "RecursiveArrayTools", v"0.0.2"], - ["OrdinaryDiffEq", v"0.6.0", "Calculus", v"0.1.15"], - ["OrdinaryDiffEq", v"0.6.0", "Compat", v"0.8.8"], - ["OrdinaryDiffEq", v"0.6.0", "DiffEqBase", v"0.4.0", v"0.7.0"], - ["OrdinaryDiffEq", v"0.6.0", "ForwardDiff", v"0.2.4"], - ["OrdinaryDiffEq", v"0.6.0", "GenericSVD", v"0.0.2"], - ["OrdinaryDiffEq", v"0.6.0", "InplaceOps", v"0.0.5"], - ["OrdinaryDiffEq", v"0.6.0", "Juno", v"0.2.5"], - ["OrdinaryDiffEq", v"0.6.0", "NLsolve", v"0.7.3"], - ["OrdinaryDiffEq", v"0.6.0", "Parameters", v"0.5.0"], - ["OrdinaryDiffEq", v"0.6.0", "Ranges", v"0.0.1"], - ["OrdinaryDiffEq", v"0.6.0", "RecipesBase", v"0.1.0"], - ["OrdinaryDiffEq", v"0.6.0", "RecursiveArrayTools", v"0.0.2"], - ["OrdinaryDiffEq", v"1.0.2", "Calculus", v"0.1.15"], - ["OrdinaryDiffEq", v"1.0.2", "Compat", v"0.8.8"], - ["OrdinaryDiffEq", v"1.0.2", "DataStructures", v"0.4.6"], - ["OrdinaryDiffEq", v"1.0.2", "DiffEqBase", v"0.6.0", v"0.8.0"], - ["OrdinaryDiffEq", v"1.0.2", "ForwardDiff", v"0.2.4"], - ["OrdinaryDiffEq", v"1.0.2", "GenericSVD", v"0.0.2"], - ["OrdinaryDiffEq", v"1.0.2", "InplaceOps", v"0.0.5"], - ["OrdinaryDiffEq", v"1.0.2", "Juno", v"0.2.5"], - ["OrdinaryDiffEq", v"1.0.2", "NLsolve", v"0.9.1"], - ["OrdinaryDiffEq", v"1.0.2", "Parameters", v"0.5.0"], - ["OrdinaryDiffEq", v"1.0.2", "RecursiveArrayTools", v"0.1.2"], - ["OrdinaryDiffEq", v"1.0.2", "Roots", v"0.2.1"], - ["OrdinaryDiffEq", v"1.1.0", "Calculus", v"0.1.15"], - ["OrdinaryDiffEq", v"1.1.0", "DiffEqBase", v"0.7.0", v"0.8.0"], - ["OrdinaryDiffEq", v"1.1.0", "Iterators"], - ["OrdinaryDiffEq", v"1.1.0", "Compat", v"0.8.8"], - ["OrdinaryDiffEq", v"1.1.0", "DataStructures", v"0.4.6"], - ["OrdinaryDiffEq", v"1.1.0", "ForwardDiff", v"0.2.4"], - ["OrdinaryDiffEq", v"1.1.0", "GenericSVD", v"0.0.2"], - ["OrdinaryDiffEq", v"1.1.0", "InplaceOps", v"0.0.5"], - ["OrdinaryDiffEq", v"1.1.0", "Juno", v"0.2.5"], - ["OrdinaryDiffEq", v"1.1.0", "NLsolve", v"0.9.1"], - ["OrdinaryDiffEq", v"1.1.0", "Parameters", v"0.5.0"], - ["OrdinaryDiffEq", v"1.1.0", "RecursiveArrayTools", v"0.1.2"], - ["OrdinaryDiffEq", v"1.1.0", "Roots", v"0.2.1"], - ["OrdinaryDiffEq", v"1.3.1", "Calculus", v"0.1.15"], - ["OrdinaryDiffEq", v"1.3.1", "Compat", v"0.8.8"], - ["OrdinaryDiffEq", v"1.3.1", "DataStructures", v"0.4.6"], - ["OrdinaryDiffEq", v"1.3.1", "DiffEqBase", v"0.8.0", v"0.15.0"], - ["OrdinaryDiffEq", v"1.3.1", "Iterators"], - ["OrdinaryDiffEq", v"1.3.1", "ForwardDiff", v"0.2.4"], - ["OrdinaryDiffEq", v"1.3.1", "GenericSVD", v"0.0.2"], - ["OrdinaryDiffEq", v"1.3.1", "InplaceOps", v"0.0.5"], - ["OrdinaryDiffEq", v"1.3.1", "Juno", v"0.2.5"], - ["OrdinaryDiffEq", v"1.3.1", "NLsolve", v"0.9.1"], - ["OrdinaryDiffEq", v"1.3.1", "Parameters", v"0.5.0"], - ["OrdinaryDiffEq", v"1.3.1", "RecursiveArrayTools", v"0.2.0"], - ["OrdinaryDiffEq", v"1.3.1", "Roots", v"0.2.1"], - ["OrdinaryDiffEq", v"1.4.1", "Calculus", v"0.1.15"], - ["OrdinaryDiffEq", v"1.4.1", "Iterators"], - ["OrdinaryDiffEq", v"1.4.1", "Compat", v"0.8.8"], - ["OrdinaryDiffEq", v"1.4.1", "DataStructures", v"0.4.6"], - ["OrdinaryDiffEq", v"1.4.1", "DiffEqBase", v"0.11.0", v"0.15.0"], - ["OrdinaryDiffEq", v"1.4.1", "ForwardDiff", v"0.2.4"], - ["OrdinaryDiffEq", v"1.4.1", "GenericSVD", v"0.0.2"], - ["OrdinaryDiffEq", v"1.4.1", "InplaceOps", v"0.0.5"], - ["OrdinaryDiffEq", v"1.4.1", "Juno", v"0.2.5"], - ["OrdinaryDiffEq", v"1.4.1", "NLsolve", v"0.9.1"], - ["OrdinaryDiffEq", v"1.4.1", "Parameters", v"0.5.0"], - ["OrdinaryDiffEq", v"1.4.1", "RecursiveArrayTools", v"0.2.0"], - ["OrdinaryDiffEq", v"1.4.1", "Roots", v"0.2.1"], - ["OrdinaryDiffEq", v"1.5.0", "Calculus", v"0.1.15"], - ["OrdinaryDiffEq", v"1.5.0", "Iterators"], - ["OrdinaryDiffEq", v"1.5.0", "Compat", v"0.17.0"], - ["OrdinaryDiffEq", v"1.5.0", "DataStructures", v"0.4.6"], - ["OrdinaryDiffEq", v"1.5.0", "DiffEqBase", v"0.11.0", v"0.15.0"], - ["OrdinaryDiffEq", v"1.5.0", "ForwardDiff", v"0.2.4"], - ["OrdinaryDiffEq", v"1.5.0", "GenericSVD", v"0.0.2"], - ["OrdinaryDiffEq", v"1.5.0", "InplaceOps", v"0.0.5"], - ["OrdinaryDiffEq", v"1.5.0", "Juno", v"0.2.5"], - ["OrdinaryDiffEq", v"1.5.0", "NLsolve", v"0.9.1"], - ["OrdinaryDiffEq", v"1.5.0", "Parameters", v"0.5.0"], - ["OrdinaryDiffEq", v"1.5.0", "RecursiveArrayTools", v"0.2.0"], - ["OrdinaryDiffEq", v"1.5.0", "Roots", v"0.2.1"], - ["OrdinaryDiffEq", v"1.7.0", "Calculus", v"0.1.15"], - ["OrdinaryDiffEq", v"1.7.0", "Iterators"], - ["OrdinaryDiffEq", v"1.7.0", "Compat", v"0.17.0"], - ["OrdinaryDiffEq", v"1.7.0", "DataStructures", v"0.4.6"], - ["OrdinaryDiffEq", v"1.7.0", "DiffEqBase", v"0.13.0", v"0.15.0"], - ["OrdinaryDiffEq", v"1.7.0", "ForwardDiff", v"0.2.4"], - ["OrdinaryDiffEq", v"1.7.0", "GenericSVD", v"0.0.2"], - ["OrdinaryDiffEq", v"1.7.0", "InplaceOps", v"0.0.5"], - ["OrdinaryDiffEq", v"1.7.0", "Juno", v"0.2.5"], - ["OrdinaryDiffEq", v"1.7.0", "NLsolve", v"0.9.1"], - ["OrdinaryDiffEq", v"1.7.0", "Parameters", v"0.5.0"], - ["OrdinaryDiffEq", v"1.7.0", "RecursiveArrayTools", v"0.2.0"], - ["OrdinaryDiffEq", v"1.7.0", "Roots", v"0.2.1"], - ["OrdinaryDiffEq", v"1.8.0", "Calculus", v"0.1.15"], - ["OrdinaryDiffEq", v"1.8.0", "DiffEqBase", v"0.15.0"], - ["OrdinaryDiffEq", v"1.8.0", "Iterators"], - ["OrdinaryDiffEq", v"1.8.0", "Compat", v"0.17.0"], - ["OrdinaryDiffEq", v"1.8.0", "DataStructures", v"0.4.6"], - ["OrdinaryDiffEq", v"1.8.0", "ForwardDiff", v"0.2.4"], - ["OrdinaryDiffEq", v"1.8.0", "GenericSVD", v"0.0.2"], - ["OrdinaryDiffEq", v"1.8.0", "InplaceOps", v"0.0.5"], - ["OrdinaryDiffEq", v"1.8.0", "Juno", v"0.2.5"], - ["OrdinaryDiffEq", v"1.8.0", "NLsolve", v"0.9.1"], - ["OrdinaryDiffEq", v"1.8.0", "Parameters", v"0.5.0"], - ["OrdinaryDiffEq", v"1.8.0", "RecursiveArrayTools", v"0.2.0"], - ["OrdinaryDiffEq", v"1.8.0", "Roots", v"0.2.1"], - ["PDMats", v"0.1.2", "NumericExtensions", v"0.5.0-"], - ["PDMats", v"0.2.5", "ArrayViews", v"0.4.0-"], - ["PDMats", v"0.3.0", "ArrayViews", v"0.4.8-"], - ["PDMats", v"0.3.1", "ArrayViews", v"0.4.8-"], - ["PDMats", v"0.3.6", "ArrayViews", v"0.4.8-"], - ["PDMats", v"0.4.0", "Compat", v"0.7.7"], - ["PDMats", v"0.4.1", "Compat", v"0.7.7"], - ["PDMats", v"0.4.2", "Compat", v"0.7.7"], - ["PDMats", v"0.5.3", "Compat", v"0.9.2"], - ["PDMats", v"0.5.4", "Compat", v"0.9.2"], - ["PDMats", v"0.5.5", "Compat", v"0.17.0"], - ["PDMats", v"0.5.6", "Compat", v"0.18.0"], - ["PDMats", v"0.6.0", "Compat", v"0.18.0"], - ["ParameterizedFunctions", v"0.0.1", "DataStructures", v"0.4.6"], - ["ParameterizedFunctions", v"0.0.1", "DiffEqBase", v"0.0.0", v"0.5.0"], - ["ParameterizedFunctions", v"0.0.1", "SymEngine", v"0.1.1"], - ["ParameterizedFunctions", v"0.1.1", "DataStructures", v"0.4.6"], - ["ParameterizedFunctions", v"0.1.1", "DiffEqBase", v"0.0.0", v"0.5.0"], - ["ParameterizedFunctions", v"0.1.1", "SymEngine", v"0.1.1"], - ["ParameterizedFunctions", v"0.2.2", "DataStructures", v"0.4.6"], - ["ParameterizedFunctions", v"0.2.2", "DiffEqBase", v"0.0.0", v"0.5.0"], - ["ParameterizedFunctions", v"0.2.2", "SymEngine", v"0.1.1"], - ["ParameterizedFunctions", v"0.3.1", "DataStructures", v"0.4.6"], - ["ParameterizedFunctions", v"0.3.1", "DiffEqBase", v"0.1.0", v"0.5.0"], - ["ParameterizedFunctions", v"0.3.1", "SymEngine", v"0.1.2"], - ["ParameterizedFunctions", v"0.3.2", "DataStructures", v"0.4.6"], - ["ParameterizedFunctions", v"0.3.2", "DiffEqBase", v"0.1.0", v"0.5.0"], - ["ParameterizedFunctions", v"0.3.2", "SymEngine", v"0.1.2"], - ["ParameterizedFunctions", v"0.3.3", "DataStructures", v"0.4.6"], - ["ParameterizedFunctions", v"0.3.3", "DiffEqBase", v"0.2.0", v"0.5.0"], - ["ParameterizedFunctions", v"0.3.3", "SymEngine", v"0.1.2"], - ["ParameterizedFunctions", v"0.4.2", "DataStructures", v"0.4.6"], - ["ParameterizedFunctions", v"0.4.2", "SimpleTraits", v"0.1.1"], - ["ParameterizedFunctions", v"0.4.2", "DiffEqBase", v"0.2.0", v"0.5.0"], - ["ParameterizedFunctions", v"0.4.2", "SymEngine", v"0.1.2"], - ["ParameterizedFunctions", v"0.5.1", "DataStructures", v"0.4.6"], - ["ParameterizedFunctions", v"0.5.1", "SimpleTraits", v"0.1.1"], - ["ParameterizedFunctions", v"0.5.1", "DiffEqBase", v"0.4.0", v"0.5.0"], - ["ParameterizedFunctions", v"0.5.1", "SymEngine", v"0.1.2"], - ["ParameterizedFunctions", v"1.2.0", "DataStructures", v"0.4.6"], - ["ParameterizedFunctions", v"1.2.0", "SimpleTraits", v"0.1.1"], - ["ParameterizedFunctions", v"1.2.0", "DiffEqBase", v"0.5.0", v"0.14.0"], - ["ParameterizedFunctions", v"1.2.0", "SymEngine", v"0.1.2"], - ["ParameterizedFunctions", v"1.3.0", "DataStructures", v"0.4.6"], - ["ParameterizedFunctions", v"1.3.0", "DiffEqBase", v"0.14.0"], - ["ParameterizedFunctions", v"1.3.0", "SimpleTraits", v"0.1.1"], - ["ParameterizedFunctions", v"1.3.0", "SymEngine", v"0.1.2"], - ["Parameters", v"0.5.0", "Compat", v"0.7.15"], - ["Parameters", v"0.5.0", "DataStructures", v"0.4.3"], - ["Parameters", v"0.6.0", "DataStructures", v"0.4.3"], - ["Parameters", v"0.7.1", "Compat", v"0.17.0"], - ["Parameters", v"0.7.1", "DataStructures", v"0.5.2"], - ["Parameters", v"0.7.2", "DataStructures", v"0.5.2"], - ["PlotThemes", v"0.1.1", "PlotUtils"], - ["PlotUtils", v"0.0.1"], - ["PlotUtils", v"0.3.0", "Colors"], - ["PlotUtils", v"0.3.0", "Reexport"], - ["Plots", v"0.1.0", "Colors"], - ["Plots", v"0.1.0", "FactCheck"], - ["Plots", v"0.1.0", "JSON", v"0.0.0", v"0.9.0"], - ["Plots", v"0.1.3", "Colors"], - ["Plots", v"0.1.3", "JSON", v"0.0.0", v"0.9.0"], - ["Plots", v"0.3.0", "Colors"], - ["Plots", v"0.3.0", "Reexport"], - ["Plots", v"0.3.0", "JSON", v"0.0.0", v"0.9.0"], - ["Plots", v"0.5.1", "Colors"], - ["Plots", v"0.5.1", "Compat"], - ["Plots", v"0.5.1", "Reexport"], - ["Plots", v"0.5.1", "JSON", v"0.0.0", v"0.9.0"], - ["Plots", v"0.5.2", "Colors"], - ["Plots", v"0.5.2", "Compat"], - ["Plots", v"0.5.2", "Reexport"], - ["Plots", v"0.5.2", "Requires"], - ["Plots", v"0.5.2", "JSON", v"0.0.0", v"0.9.0"], - ["Plots", v"0.6.1", "Colors"], - ["Plots", v"0.6.1", "Compat"], - ["Plots", v"0.6.1", "FixedSizeArrays"], - ["Plots", v"0.6.1", "Reexport"], - ["Plots", v"0.6.1", "Requires"], - ["Plots", v"0.6.1", "JSON", v"0.0.0", v"0.9.0"], - ["Plots", v"0.6.2", "Colors"], - ["Plots", v"0.6.2", "Compat"], - ["Plots", v"0.6.2", "FixedSizeArrays"], - ["Plots", v"0.6.2", "Reexport"], - ["Plots", v"0.6.2", "Requires"], - ["Plots", v"0.6.2", "JSON", v"0.0.0", v"0.9.0"], - ["Plots", v"0.6.2", "RecipesBase", v"0.0.1", v"0.0.2"], - ["Plots", v"0.7.5", "Colors"], - ["Plots", v"0.7.5", "Compat"], - ["Plots", v"0.7.5", "FixedSizeArrays"], - ["Plots", v"0.7.5", "Measures"], - ["Plots", v"0.7.5", "JSON", v"0.0.0", v"0.9.0"], - ["Plots", v"0.7.5", "RecipesBase"], - ["Plots", v"0.7.5", "Reexport"], - ["Plots", v"0.8.0", "Compat"], - ["Plots", v"0.8.0", "FixedSizeArrays"], - ["Plots", v"0.8.0", "Measures"], - ["Plots", v"0.8.0", "PlotUtils"], - ["Plots", v"0.8.0", "JSON", v"0.0.0", v"0.9.0"], - ["Plots", v"0.8.0", "RecipesBase"], - ["Plots", v"0.8.0", "Reexport"], - ["Plots", v"0.9.0", "Compat"], - ["Plots", v"0.9.0", "FixedSizeArrays"], - ["Plots", v"0.9.0", "Measures"], - ["Plots", v"0.9.0", "PlotUtils"], - ["Plots", v"0.9.0", "RecipesBase"], - ["Plots", v"0.9.0", "Reexport"], - ["Plots", v"0.9.0", "JSON", v"0.0.0", v"0.9.0"], - ["Plots", v"0.9.0", "Showoff"], - ["Plots", v"0.9.1", "Compat"], - ["Plots", v"0.9.1", "FixedSizeArrays"], - ["Plots", v"0.9.1", "Measures"], - ["Plots", v"0.9.1", "PlotUtils"], - ["Plots", v"0.9.1", "RecipesBase"], - ["Plots", v"0.9.1", "Reexport"], - ["Plots", v"0.9.1", "Showoff"], - ["Plots", v"0.9.3", "Compat"], - ["Plots", v"0.9.3", "FixedSizeArrays"], - ["Plots", v"0.9.3", "Measures"], - ["Plots", v"0.9.3", "PlotUtils"], - ["Plots", v"0.9.3", "RecipesBase"], - ["Plots", v"0.9.3", "Reexport"], - ["Plots", v"0.9.3", "Showoff"], - ["Plots", v"0.9.4", "FixedSizeArrays"], - ["Plots", v"0.9.4", "Measures"], - ["Plots", v"0.9.4", "PlotUtils"], - ["Plots", v"0.9.4", "RecipesBase"], - ["Plots", v"0.9.4", "Reexport"], - ["Plots", v"0.9.4", "Showoff"], - ["Plots", v"0.10.3", "FixedSizeArrays"], - ["Plots", v"0.10.3", "Measures"], - ["Plots", v"0.10.3", "PlotThemes"], - ["Plots", v"0.10.3", "PlotUtils"], - ["Plots", v"0.10.3", "RecipesBase"], - ["Plots", v"0.10.3", "Reexport"], - ["Plots", v"0.10.3", "Showoff"], - ["PolynomialFactors", v"0.0.1", "Combinatorics", v"0.2.1"], - ["PolynomialFactors", v"0.0.1", "Compat", v"0.7.15"], - ["PolynomialFactors", v"0.0.1", "Iterators", v"0.1.0"], - ["PolynomialFactors", v"0.0.1", "Primes", v"0.1.1"], - ["PolynomialFactors", v"0.0.2", "Combinatorics", v"0.2.1"], - ["PolynomialFactors", v"0.0.2", "Compat", v"0.7.15"], - ["PolynomialFactors", v"0.0.2", "Iterators", v"0.1.0"], - ["PolynomialFactors", v"0.0.2", "Polynomials", v"0.1.1"], - ["PolynomialFactors", v"0.0.2", "Primes", v"0.1.1"], - ["PolynomialFactors", v"0.0.4", "Combinatorics", v"0.2.1"], - ["PolynomialFactors", v"0.0.4", "Compat", v"0.7.15"], - ["PolynomialFactors", v"0.0.4", "Iterators", v"0.1.0"], - ["PolynomialFactors", v"0.0.4", "Polynomials", v"0.1.1"], - ["PolynomialFactors", v"0.0.4", "Primes", v"0.1.1"], - ["Polynomials", v"0.0.2"], - ["Polynomials", v"0.0.3"], - ["Polynomials", v"0.0.4", "Compat"], - ["Polynomials", v"0.0.5", "Compat"], - ["Polynomials", v"0.1.0", "Compat", v"0.7.15"], - ["Polynomials", v"0.1.1", "Compat", v"0.8.0"], - ["Polynomials", v"0.1.5", "Compat", v"0.9.4"], - ["PositiveFactorizations", v"0.0.1"], - ["PositiveFactorizations", v"0.0.3", "Compat", v"0.8.4"], - ["PositiveFactorizations", v"0.0.4", "Compat", v"0.12.0"], - ["PowerSeries", v"0.1.10"], - ["PowerSeries", v"0.1.14", "Compat", v"0.4.7"], - ["PowerSeries", v"0.2.0"], - ["Primes", v"0.1.0"], - ["Primes", v"0.1.1"], - ["Primes", v"0.1.3", "Compat", v"0.9.4"], - ["PyCall", v"0.4.10"], - ["PyCall", v"0.6.2", "Compat", v"0.2.0"], - ["PyCall", v"0.7.3", "Compat", v"0.2.0"], - ["PyCall", v"0.7.3", "Dates"], - ["PyCall", v"0.7.4", "Compat", v"0.3.1"], - ["PyCall", v"0.7.4", "Dates"], - ["PyCall", v"0.7.5", "Compat", v"0.3.4"], - ["PyCall", v"0.7.5", "Dates"], - ["PyCall", v"0.8.1", "Compat", v"0.4.0"], - ["PyCall", v"0.8.1", "Dates"], - ["PyCall", v"1.0.1", "Compat", v"0.4.6"], - ["PyCall", v"1.0.1", "Dates"], - ["PyCall", v"1.0.3", "Compat", v"0.7.1"], - ["PyCall", v"1.0.3", "Dates"], - ["PyCall", v"1.4.0", "Compat", v"0.7.1"], - ["PyCall", v"1.4.0", "Conda", v"0.1.6"], - ["PyCall", v"1.4.0", "Dates"], - ["PyCall", v"1.5.0", "Compat", v"0.7.15"], - ["PyCall", v"1.5.0", "Conda", v"0.1.6"], - ["PyCall", v"1.5.0", "MacroTools", v"0.2.0"], - ["PyCall", v"1.6.2", "Compat", v"0.7.15"], - ["PyCall", v"1.6.2", "Conda", v"0.2.0"], - ["PyCall", v"1.6.2", "MacroTools", v"0.2.0"], - ["PyCall", v"1.7.2", "Compat", v"0.8.0"], - ["PyCall", v"1.7.2", "Conda", v"0.2.0"], - ["PyCall", v"1.7.2", "MacroTools", v"0.2.0"], - ["PyCall", v"1.10.0", "Compat", v"0.9.5"], - ["PyCall", v"1.10.0", "Conda", v"0.2.0"], - ["PyCall", v"1.10.0", "MacroTools", v"0.2.0"], - ["PyCall", v"1.12.0", "Compat", v"0.18.0"], - ["PyCall", v"1.12.0", "Conda", v"0.2.0"], - ["PyCall", v"1.12.0", "MacroTools", v"0.2.0"], - ["PyDSTool", v"0.0.1", "DataStructures"], - ["PyDSTool", v"0.0.1", "PyCall"], - ["PyDSTool", v"0.0.2", "Conda"], - ["PyDSTool", v"0.0.2", "DataStructures"], - ["PyDSTool", v"0.0.2", "PyCall"], - ["PyDSTool", v"0.1.1", "Conda"], - ["PyDSTool", v"0.1.1", "DataStructures"], - ["PyDSTool", v"0.1.1", "DiffEqBase", v"0.11.0"], - ["PyDSTool", v"0.1.1", "PyCall"], - ["PyDSTool", v"0.1.1", "RecipesBase"], - ["PyDSTool", v"0.1.2", "DataStructures"], - ["PyDSTool", v"0.1.2", "PyCall"], - ["PyDSTool", v"0.1.2", "RecipesBase"], - ["PyDSTool", v"0.1.2", "Conda", v"0.2.0"], - ["PyDSTool", v"0.1.2", "DiffEqBase", v"0.11.0"], - ["QuadGK", v"0.1.0"], - ["QuadGK", v"0.1.2", "DataStructures", v"0.5.0"], - ["RangeArrays", v"0.1.1"], - ["RangeArrays", v"0.1.2", "Compat", v"0.19.0"], - ["Ranges", v"0.0.1"], - ["Ratios", v"0.0.3"], - ["Ratios", v"0.0.4", "Compat"], - ["Reactive", v"0.2.4", "FactCheck"], - ["Reactive", v"0.2.4", "Compat", v"0.4.0"], - ["Reactive", v"0.3.4", "Compat"], - ["Reactive", v"0.3.5", "Compat", v"0.9.2"], - ["Reactive", v"0.3.6"], - ["Reactive", v"0.3.7", "DataStructures"], - ["RecipesBase", v"0.1.0"], - ["RecursiveArrayTools", v"0.0.1"], - ["RecursiveArrayTools", v"0.1.1"], - ["RecursiveArrayTools", v"0.1.2"], - ["RecursiveArrayTools", v"0.2.0"], - ["Reexport", v"0.0.2"], - ["Reexport", v"0.0.3"], - ["Requires", v"0.2.3", "MacroTools"], - ["Requires", v"0.4.1"], - ["ResettableStacks", v"0.1.0"], - ["Rmath", v"0.1.0", "BinDeps"], - ["Rmath", v"0.1.2", "BinDeps"], - ["Rmath", v"0.1.2", "Compat", v"0.8.4"], - ["Rmath", v"0.1.6", "BinDeps"], - ["Rmath", v"0.1.6", "Compat", v"0.9.1"], - ["Roots", v"0.1.9", "Polynomials", v"0.0.3"], - ["Roots", v"0.1.9", "ForwardDiff", v"0.0.0", v"0.2.0"], - ["Roots", v"0.1.9", "PowerSeries", v"0.1.0"], - ["Roots", v"0.1.13", "Docile", v"0.4.0"], - ["Roots", v"0.1.13", "Polynomials", v"0.0.3"], - ["Roots", v"0.1.13", "ForwardDiff", v"0.0.0", v"0.2.0"], - ["Roots", v"0.1.13", "PowerSeries", v"0.1.11"], - ["Roots", v"0.1.18", "Compat", v"0.4.0"], - ["Roots", v"0.1.18", "Docile", v"0.4.0"], - ["Roots", v"0.1.18", "Polynomials", v"0.0.3"], - ["Roots", v"0.1.18", "ForwardDiff", v"0.0.0", v"0.2.0"], - ["Roots", v"0.1.18", "PowerSeries", v"0.1.11"], - ["Roots", v"0.1.22", "Compat", v"0.4.0"], - ["Roots", v"0.1.22", "Docile", v"0.4.0"], - ["Roots", v"0.1.22", "Polynomials", v"0.0.3"], - ["Roots", v"0.1.22", "ForwardDiff", v"0.0.0", v"0.2.0"], - ["Roots", v"0.1.26", "Compat", v"0.4.0"], - ["Roots", v"0.1.26", "Docile", v"0.4.0"], - ["Roots", v"0.1.26", "Polynomials", v"0.0.5"], - ["Roots", v"0.1.26", "ForwardDiff", v"0.0.0", v"0.2.0"], - ["Roots", v"0.2.0", "Primes"], - ["Roots", v"0.2.0", "Compat", v"0.4.0"], - ["Roots", v"0.2.0", "Docile", v"0.4.0"], - ["Roots", v"0.2.0", "ForwardDiff", v"0.2.0"], - ["Roots", v"0.2.0", "Polynomials", v"0.0.5"], - ["Roots", v"0.2.1", "Primes"], - ["Roots", v"0.2.1", "Compat", v"0.4.0"], - ["Roots", v"0.2.1", "ForwardDiff", v"0.2.0"], - ["Roots", v"0.2.1", "Polynomials", v"0.0.5"], - ["Roots", v"0.3.0", "Compat", v"0.8.0"], - ["Roots", v"0.3.0", "ForwardDiff", v"0.2.0"], - ["Roots", v"0.3.0", "PolynomialFactors", v"0.0.3"], - ["Roots", v"0.3.0", "Polynomials", v"0.0.5"], - ["Rotations", v"0.3.4", "StaticArrays", v"0.0.3", v"0.3.0-"], - ["Rotations", v"0.3.5", "StaticArrays", v"0.3.0", v"0.4.0-"], - ["Rotations", v"0.4.0", "StaticArrays", v"0.4.0", v"0.5.0-"], - ["SHA", v"0.0.2"], - ["SHA", v"0.0.3"], - ["SHA", v"0.2.0", "Compat", v"0.3.5"], - ["SHA", v"0.2.1", "Compat", v"0.7.9"], - ["SHA", v"0.3.1", "Compat", v"0.9.4"], - ["SHA", v"0.3.2", "Compat", v"0.17.0"], - ["SIUnits", v"0.0.5", "TexExtensions"], - ["SIUnits", v"0.0.6", "Compat"], - ["SIUnits", v"0.0.6", "TexExtensions"], - ["SIUnits", v"0.1.0", "TexExtensions"], - ["SIUnits", v"0.1.0", "Compat", v"0.8.0"], - ["ShowItLikeYouBuildIt", v"0.0.1"], - ["Showoff", v"0.0.1"], - ["Showoff", v"0.0.3", "Iterators"], - ["Showoff", v"0.0.7", "Compat"], - ["Showoff", v"0.0.7", "Iterators"], - ["Showoff", v"0.1.0", "Compat", v"0.9.5"], - ["Showoff", v"0.1.1", "Compat", v"0.18.0"], - ["SimpleTraits", v"0.1.0", "Compat"], - ["SimpleTraits", v"0.1.1"], - ["SimpleTraits", v"0.2.0", "MacroTools", v"0.3.2"], - ["SimpleTraits", v"0.4.0", "Compat", v"0.19.0"], - ["SimpleTraits", v"0.4.0", "MacroTools", v"0.3.2"], - ["SortingAlgorithms", v"0.0.3"], - ["SortingAlgorithms", v"0.0.6", "Compat"], - ["SortingAlgorithms", v"0.1.0", "Compat", v"0.8.4"], - ["SortingAlgorithms", v"0.1.1", "Compat", v"0.9.4"], - ["SortingAlgorithms", v"0.1.1", "DataStructures", v"0.5.3"], - ["SpecialFunctions", v"0.0.1", "Compat", v"0.9.1"], - ["SpecialFunctions", v"0.1.0", "Compat", v"0.9.1"], - ["SpecialFunctions", v"0.1.1", "Compat", v"0.18.0"], - ["StaticArrays", v"0.0.2"], - ["StaticArrays", v"0.0.4"], - ["StaticArrays", v"0.2.1"], - ["StaticArrays", v"0.3.0"], - ["StaticArrays", v"0.4.0"], - ["Stats", v"0.0.1", "StatsBase", v"0.3.0-"], - ["Stats", v"0.1.0", "StatsBase"], - ["StatsBase", v"0.2.4", "NumericExtensions"], - ["StatsBase", v"0.2.9"], - ["StatsBase", v"0.3.9"], - ["StatsBase", v"0.4.1"], - ["StatsBase", v"0.6.8", "ArrayViews", v"0.4.6-"], - ["StatsBase", v"0.6.9", "ArrayViews", v"0.4.8-"], - ["StatsBase", v"0.6.10", "ArrayViews", v"0.4.8-"], - ["StatsBase", v"0.6.12", "ArrayViews", v"0.4.8-"], - ["StatsBase", v"0.6.12", "Compat", v"0.2.11-"], - ["StatsBase", v"0.6.13", "ArrayViews", v"0.4.10"], - ["StatsBase", v"0.6.13", "Compat", v"0.3.2"], - ["StatsBase", v"0.6.16", "ArrayViews", v"0.4.12"], - ["StatsBase", v"0.6.16", "Compat", v"0.4.0"], - ["StatsBase", v"0.7.4", "ArrayViews", v"0.4.12"], - ["StatsBase", v"0.7.4", "Compat", v"0.4.0"], - ["StatsBase", v"0.7.4", "StatsFuns", v"0.1.0"], - ["StatsBase", v"0.8.1", "ArrayViews", v"0.4.12"], - ["StatsBase", v"0.8.1", "Compat", v"0.4.0"], - ["StatsBase", v"0.8.1", "StatsFuns", v"0.1.0"], - ["StatsBase", v"0.8.2", "ArrayViews", v"0.4.12"], - ["StatsBase", v"0.8.2", "Compat", v"0.4.0"], - ["StatsBase", v"0.8.2", "StatsFuns", v"0.1.0"], - ["StatsBase", v"0.8.3", "Compat", v"0.8.4"], - ["StatsBase", v"0.8.3", "StatsFuns", v"0.1.0"], - ["StatsBase", v"0.9.0", "Compat", v"0.8.4"], - ["StatsBase", v"0.9.0", "StatsFuns", v"0.3.0"], - ["StatsBase", v"0.10.0", "Compat", v"0.8.4"], - ["StatsBase", v"0.12.0", "Compat", v"0.8.4"], - ["StatsBase", v"0.13.0", "Compat", v"0.13.0"], - ["StatsBase", v"0.13.0", "DataStructures", v"0.5.0"], - ["StatsBase", v"0.13.1", "Compat", v"0.18.0"], - ["StatsBase", v"0.13.1", "DataStructures", v"0.5.0"], - ["StatsBase", v"0.13.1", "SpecialFunctions", v"0.1.0"], - ["StatsFuns", v"0.0.3", "Compat", v"0.4.0"], - ["StatsFuns", v"0.1.0", "Compat", v"0.4.0"], - ["StatsFuns", v"0.2.1", "Compat", v"0.4.0"], - ["StatsFuns", v"0.2.2", "Compat", v"0.7.18"], - ["StatsFuns", v"0.3.0", "Compat", v"0.8.4"], - ["StatsFuns", v"0.3.0", "Rmath", v"0.1.0"], - ["StatsFuns", v"0.4.0", "Compat", v"0.9.1"], - ["StatsFuns", v"0.4.0", "Rmath", v"0.1.0"], - ["StatsFuns", v"0.5.0", "SpecialFunctions"], - ["StatsFuns", v"0.5.0", "Compat", v"0.9.1"], - ["StatsFuns", v"0.5.0", "Rmath", v"0.1.0"], - ["StochasticDiffEq", v"0.0.3", "ChunkedArrays", v"0.1.0"], - ["StochasticDiffEq", v"0.0.3", "DiffEqBase", v"0.0.0", v"0.8.0"], - ["StochasticDiffEq", v"0.0.3", "ParameterizedFunctions", v"0.1.0"], - ["StochasticDiffEq", v"0.0.3", "Parameters", v"0.5.0"], - ["StochasticDiffEq", v"0.0.4", "RecursiveArrayTools"], - ["StochasticDiffEq", v"0.0.4", "ChunkedArrays", v"0.1.0"], - ["StochasticDiffEq", v"0.0.4", "DiffEqBase", v"0.0.0", v"0.8.0"], - ["StochasticDiffEq", v"0.0.4", "ParameterizedFunctions", v"0.1.0"], - ["StochasticDiffEq", v"0.0.4", "Parameters", v"0.5.0"], - ["StochasticDiffEq", v"0.0.5", "RecursiveArrayTools"], - ["StochasticDiffEq", v"0.0.5", "ChunkedArrays", v"0.1.0"], - ["StochasticDiffEq", v"0.0.5", "DiffEqBase", v"0.0.0", v"0.8.0"], - ["StochasticDiffEq", v"0.0.5", "Parameters", v"0.5.0"], - ["StochasticDiffEq", v"0.2.0", "ChunkedArrays", v"0.1.0"], - ["StochasticDiffEq", v"0.2.0", "DiffEqBase", v"0.2.0", v"0.8.0"], - ["StochasticDiffEq", v"0.2.0", "Parameters", v"0.5.0"], - ["StochasticDiffEq", v"0.2.0", "RecursiveArrayTools", v"0.0.2"], - ["StochasticDiffEq", v"0.3.0", "ChunkedArrays", v"0.1.0"], - ["StochasticDiffEq", v"0.3.0", "DataStructures"], - ["StochasticDiffEq", v"0.3.0", "DiffEqBase", v"0.2.0", v"0.8.0"], - ["StochasticDiffEq", v"0.3.0", "Juno"], - ["StochasticDiffEq", v"0.3.0", "Parameters", v"0.5.0"], - ["StochasticDiffEq", v"0.3.0", "RecursiveArrayTools", v"0.0.2"], - ["StochasticDiffEq", v"0.3.0", "ResettableStacks"], - ["StochasticDiffEq", v"0.5.0", "ChunkedArrays", v"0.1.0"], - ["StochasticDiffEq", v"0.5.0", "DataStructures", v"0.4.6"], - ["StochasticDiffEq", v"0.5.0", "DiffEqBase", v"0.4.0", v"0.8.0"], - ["StochasticDiffEq", v"0.5.0", "Juno", v"0.2.5"], - ["StochasticDiffEq", v"0.5.0", "Parameters", v"0.5.0"], - ["StochasticDiffEq", v"0.5.0", "RecursiveArrayTools", v"0.1.2"], - ["StochasticDiffEq", v"0.5.0", "ResettableStacks", v"0.0.1"], - ["StochasticDiffEq", v"1.0.2", "Iterators"], - ["StochasticDiffEq", v"1.0.2", "Roots"], - ["StochasticDiffEq", v"1.0.2", "DataStructures", v"0.4.6"], - ["StochasticDiffEq", v"1.0.2", "DiffEqBase", v"0.8.0", v"0.15.0"], - ["StochasticDiffEq", v"1.0.2", "Juno", v"0.2.5"], - ["StochasticDiffEq", v"1.0.2", "Parameters", v"0.5.0"], - ["StochasticDiffEq", v"1.0.2", "RecursiveArrayTools", v"0.2.0"], - ["StochasticDiffEq", v"1.0.2", "ResettableStacks", v"0.0.1"], - ["StochasticDiffEq", v"1.1.0", "Iterators"], - ["StochasticDiffEq", v"1.1.0", "Roots"], - ["StochasticDiffEq", v"1.1.0", "DataStructures", v"0.4.6"], - ["StochasticDiffEq", v"1.1.0", "DiffEqBase", v"0.11.0", v"0.15.0"], - ["StochasticDiffEq", v"1.1.0", "Juno", v"0.2.5"], - ["StochasticDiffEq", v"1.1.0", "Parameters", v"0.5.0"], - ["StochasticDiffEq", v"1.1.0", "RecursiveArrayTools", v"0.2.0"], - ["StochasticDiffEq", v"1.1.0", "ResettableStacks", v"0.0.1"], - ["StochasticDiffEq", v"1.2.1", "Compat", v"0.17.0"], - ["StochasticDiffEq", v"1.2.1", "Iterators"], - ["StochasticDiffEq", v"1.2.1", "Roots"], - ["StochasticDiffEq", v"1.2.1", "DataStructures", v"0.4.6"], - ["StochasticDiffEq", v"1.2.1", "DiffEqBase", v"0.11.0", v"0.15.0"], - ["StochasticDiffEq", v"1.2.1", "Juno", v"0.2.5"], - ["StochasticDiffEq", v"1.2.1", "Parameters", v"0.5.0"], - ["StochasticDiffEq", v"1.2.1", "RecursiveArrayTools", v"0.2.0"], - ["StochasticDiffEq", v"1.2.1", "ResettableStacks", v"0.0.1"], - ["StochasticDiffEq", v"1.3.0", "Compat", v"0.17.0"], - ["StochasticDiffEq", v"1.3.0", "Iterators"], - ["StochasticDiffEq", v"1.3.0", "Roots"], - ["StochasticDiffEq", v"1.3.0", "DataStructures", v"0.4.6"], - ["StochasticDiffEq", v"1.3.0", "DiffEqBase", v"0.13.0", v"0.15.0"], - ["StochasticDiffEq", v"1.3.0", "Juno", v"0.2.5"], - ["StochasticDiffEq", v"1.3.0", "Parameters", v"0.5.0"], - ["StochasticDiffEq", v"1.3.0", "RecursiveArrayTools", v"0.2.0"], - ["StochasticDiffEq", v"1.3.0", "ResettableStacks", v"0.0.1"], - ["StochasticDiffEq", v"1.4.0", "Compat", v"0.17.0"], - ["StochasticDiffEq", v"1.4.0", "DiffEqBase", v"0.15.0"], - ["StochasticDiffEq", v"1.4.0", "Iterators"], - ["StochasticDiffEq", v"1.4.0", "Roots"], - ["StochasticDiffEq", v"1.4.0", "DataStructures", v"0.4.6"], - ["StochasticDiffEq", v"1.4.0", "Juno", v"0.2.5"], - ["StochasticDiffEq", v"1.4.0", "Parameters", v"0.5.0"], - ["StochasticDiffEq", v"1.4.0", "RecursiveArrayTools", v"0.2.0"], - ["StochasticDiffEq", v"1.4.0", "ResettableStacks", v"0.0.1"], - ["StokesDiffEq", v"0.0.1", "DiffEqBase"], - ["StokesDiffEq", v"0.0.1", "Parameters", v"0.5.0"], - ["StokesDiffEq", v"0.0.1", "VectorizedRoutines", v"0.0.1"], - ["StokesDiffEq", v"0.0.2", "DiffEqBase"], - ["StokesDiffEq", v"0.0.2", "Parameters", v"0.5.0"], - ["StokesDiffEq", v"0.0.2", "VectorizedRoutines", v"0.0.1"], - ["StokesDiffEq", v"0.1.0", "DiffEqBase", v"0.4.0"], - ["StokesDiffEq", v"0.1.0", "Parameters", v"0.5.0"], - ["StokesDiffEq", v"0.1.0", "VectorizedRoutines", v"0.0.2"], - ["StrPack", v"0.0.1"], - ["StructIO", v"0.0.2"], - ["Sundials", v"0.0.0"], - ["Sundials", v"0.1.2", "BinDeps"], - ["Sundials", v"0.2.0", "BinDeps", v"0.3.0"], - ["Sundials", v"0.2.2", "Compat"], - ["Sundials", v"0.2.2", "BinDeps", v"0.3.0"], - ["Sundials", v"0.3.0", "BinDeps", v"0.4.3"], - ["Sundials", v"0.3.0", "Compat", v"0.9.0"], - ["Sundials", v"0.4.0", "BinDeps", v"0.4.3"], - ["Sundials", v"0.4.0", "Compat", v"0.9.0"], - ["Sundials", v"0.4.0", "DiffEqBase", v"0.0.0", v"0.2.0"], - ["Sundials", v"0.9.0", "BinDeps", v"0.4.3"], - ["Sundials", v"0.9.0", "Compat", v"0.9.0"], - ["Sundials", v"0.9.0", "DiffEqBase", v"0.2.0", v"0.15.0"], - ["Sundials", v"0.10.0", "BinDeps", v"0.4.3"], - ["Sundials", v"0.10.0", "Compat", v"0.9.0"], - ["Sundials", v"0.10.0", "DiffEqBase", v"0.15.0"], - ["SymEngine", v"0.1.0", "BinDeps"], - ["SymEngine", v"0.1.0", "Conda"], - ["SymEngine", v"0.1.0", "Compat", v"0.8.5"], - ["SymEngine", v"0.1.0", "RecipesBase", v"0.0.6"], - ["SymEngine", v"0.1.1", "BinDeps", v"0.4.0"], - ["SymEngine", v"0.1.1", "Compat", v"0.8.5"], - ["SymEngine", v"0.1.1", "Conda", v"0.3.0"], - ["SymEngine", v"0.1.1", "RecipesBase", v"0.0.6"], - ["SymEngine", v"0.1.2", "BinDeps", v"0.4.0"], - ["SymEngine", v"0.1.2", "Compat", v"0.8.5"], - ["SymEngine", v"0.1.2", "Conda", v"0.4.0"], - ["SymEngine", v"0.1.2", "RecipesBase", v"0.0.6"], - ["SymEngine", v"0.1.5", "BinDeps", v"0.4.0"], - ["SymEngine", v"0.1.5", "Compat", v"0.9.5"], - ["SymEngine", v"0.1.5", "Conda", v"0.4.0"], - ["SymEngine", v"0.1.5", "RecipesBase", v"0.0.6"], - ["TerminalUI", v"0.0.1", "Reactive"], - ["TerminalUI", v"0.0.1", "VT100"], - ["TerminalUI", v"0.0.2", "AbstractTrees"], - ["TerminalUI", v"0.0.2", "Colors"], - ["TerminalUI", v"0.0.2", "Compat"], - ["TerminalUI", v"0.0.2", "FixedPointNumbers"], - ["TerminalUI", v"0.0.2", "Reactive"], - ["TerminalUI", v"0.0.2", "VT100"], - ["TexExtensions", v"0.0.2"], - ["TexExtensions", v"0.0.3", "Compat"], - ["TextWrap", v"0.0.0", "Options"], - ["TextWrap", v"0.1.3"], - ["TextWrap", v"0.1.4"], - ["TextWrap", v"0.1.5", "Compat", v"0.7.3"], - ["TextWrap", v"0.1.6", "Compat", v"0.7.15"], - ["TextWrap", v"0.2.0", "Compat", v"0.9.5"], - ["TiledIteration", v"0.0.2", "OffsetArrays"], - ["URIParser", v"0.0.4", "Compat"], - ["URIParser", v"0.0.5", "Compat", v"0.3.5"], - ["URIParser", v"0.1.0", "HttpCommon"], - ["URIParser", v"0.1.0", "Compat", v"0.3.5"], - ["URIParser", v"0.1.3"], - ["URIParser", v"0.1.6", "Compat", v"0.8.0"], - ["URIParser", v"0.1.8", "Compat", v"0.9.5"], - ["VT100", v"0.0.1", "Colors"], - ["VT100", v"0.0.1", "Compat"], - ["VT100", v"0.0.1", "FixedPointNumbers"], - ["VT100", v"0.0.2", "Colors"], - ["VT100", v"0.0.2", "FixedPointNumbers"], - ["VT100", v"0.0.2", "Compat", v"0.7.15"], - ["VT100", v"0.1.0", "ColorTypes", v"0.3.4"], - ["VT100", v"0.1.0", "Compat", v"0.17.0"], - ["VT100", v"0.1.0", "FixedPointNumbers", v"0.3.0"], - ["VectorizedRoutines", v"0.0.1", "Distributions"], - ["VectorizedRoutines", v"0.0.1", "StatsFuns"], - ["VectorizedRoutines", v"0.0.2", "Distributions"], - ["WebSockets", v"0.0.0", "HttpCommon"], - ["WebSockets", v"0.0.0", "HttpServer"], - ["WebSockets", v"0.0.1"], - ["WebSockets", v"0.0.3", "Codecs"], - ["WebSockets", v"0.0.3", "HttpCommon"], - ["WebSockets", v"0.0.3", "HttpServer"], - ["WebSockets", v"0.0.5", "Codecs"], - ["WebSockets", v"0.0.5", "HttpCommon", v"0.0.3-"], - ["WebSockets", v"0.0.5", "HttpServer", v"0.0.4-"], - ["WebSockets", v"0.0.6", "Codecs"], - ["WebSockets", v"0.0.6", "Nettle"], - ["WebSockets", v"0.0.6", "HttpCommon", v"0.0.3-"], - ["WebSockets", v"0.0.6", "HttpServer", v"0.0.4-"], - ["WebSockets", v"0.1.0", "Codecs"], - ["WebSockets", v"0.1.0", "Compat"], - ["WebSockets", v"0.1.0", "Nettle"], - ["WebSockets", v"0.1.0", "HttpCommon", v"0.0.3"], - ["WebSockets", v"0.1.0", "HttpServer", v"0.0.4"], - ["WebSockets", v"0.1.2", "Codecs"], - ["WebSockets", v"0.1.2", "Compat"], - ["WebSockets", v"0.1.2", "HttpCommon", v"0.0.3"], - ["WebSockets", v"0.1.2", "HttpServer", v"0.0.4"], - ["WebSockets", v"0.1.2", "Nettle", v"0.2.0"], - ["WebSockets", v"0.2.1", "Codecs"], - ["WebSockets", v"0.2.1", "MbedTLS"], - ["WebSockets", v"0.2.1", "Compat", v"0.7.16"], - ["WebSockets", v"0.2.1", "HttpCommon", v"0.0.3"], - ["WebSockets", v"0.2.1", "HttpServer", v"0.0.4"], - ["WoodburyMatrices", v"0.0.2"], - ["WoodburyMatrices", v"0.1.3", "Docile"], - ["WoodburyMatrices", v"0.1.4", "Compat"], - ["WoodburyMatrices", v"0.1.4", "Docile"], - ["WoodburyMatrices", v"0.1.5", "Compat"], - ["WoodburyMatrices", v"0.1.5", "Docile"], - ["WoodburyMatrices", v"0.2.1", "Compat"], - ["WoodburyMatrices", v"0.2.2", "Compat", v"0.7.19"], - ["Zlib", v"0.1.9"], - ["Zlib", v"0.1.12", "Compat"], -] - -problematic_data = Any[ - ("CoordinateTransformations", v"0.2.0"), - ("Plots", v"0.6.2"), - ("Roots", v"0.1.9"), - ("Roots", v"0.1.13"), - ("Roots", v"0.1.18"), - ("Roots", v"0.1.22"), - ("Roots", v"0.1.26"), -] - -reqs_data = Any[ - ["Atom"], - ["DifferentialEquations"], - ["ImageMagick"], - ["Plots"], -] - -want_data = Dict( - "ASTInterpreter"=>v"0.0.4", - "AbstractTrees"=>v"0.0.4", - "AlgebraicDiffEq"=>v"0.1.0", - "ArgParse"=>v"0.4.0", - "Atom"=>v"0.5.10", - "AxisAlgorithms"=>v"0.1.6", - "AxisArrays"=>v"0.1.2", - "BinDeps"=>v"0.4.7", - "Blink"=>v"0.5.1", - "COFF"=>v"0.0.2", - "CRC"=>v"1.2.0", - "Calculus"=>v"0.2.2", - "CatIndices"=>v"0.0.2", - "ChunkedArrays"=>v"0.1.1", - "CodeTools"=>v"0.4.3", - "Codecs"=>v"0.3.0", - "ColorTypes"=>v"0.4.1", - "ColorVectorSpace"=>v"0.4.2", - "Colors"=>v"0.7.3", - "Combinatorics"=>v"0.4.0", - "Compat"=>v"0.24.0", - "ComputationalResources"=>v"0.0.2", - "Conda"=>v"0.5.3", - "CoordinateTransformations"=>v"0.4.1", - "CustomUnitRanges"=>v"0.0.4", - "DWARF"=>v"0.1.0", - "DataStructures"=>v"0.5.3", - "DelayDiffEq"=>v"0.3.0", - "DiffBase"=>v"0.1.0", - "DiffEqBase"=>v"0.15.0", - "DiffEqBiological"=>v"0.0.1", - "DiffEqCallbacks"=>v"0.0.2", - "DiffEqDevTools"=>v"0.7.0", - "DiffEqFinancial"=>v"0.1.0", - "DiffEqJump"=>v"0.3.0", - "DiffEqMonteCarlo"=>v"0.2.0", - "DiffEqPDEBase"=>v"0.2.0", - "DiffEqParamEstim"=>v"0.2.0", - "DiffEqSensitivity"=>v"0.1.0", - "DifferentialEquations"=>v"1.10.1", - "Distances"=>v"0.4.1", - "Distributions"=>v"0.12.5", - "DualNumbers"=>v"0.3.0", - "ELF"=>v"0.1.0", - "EllipsisNotation"=>v"0.1.0", - "FFTViews"=>v"0.0.2", - "FileIO"=>v"0.3.1", - "FiniteElementDiffEq"=>v"0.3.0", - "FixedPointNumbers"=>v"0.3.6", - "FixedSizeArrays"=>v"0.2.5", - "ForwardDiff"=>v"0.4.2", - "Gallium"=>v"0.0.4", - "GenericSVD"=>v"0.0.2", - "Graphics"=>v"0.2.0", - "Hiccup"=>v"0.1.1", - "HttpCommon"=>v"0.2.7", - "HttpParser"=>v"0.2.0", - "HttpServer"=>v"0.2.0", - "ImageAxes"=>v"0.2.1", - "ImageCore"=>v"0.3.0", - "ImageFiltering"=>v"0.1.4", - "ImageMagick"=>v"0.2.4", - "ImageMetadata"=>v"0.2.3", - "ImageTransformations"=>v"0.2.2", - "Images"=>v"0.9.1", - "IndirectArrays"=>v"0.1.1", - "InplaceOps"=>v"0.1.0", - "Interpolations"=>v"0.5.0", - "IntervalSets"=>v"0.0.5", - "IterativeSolvers"=>v"0.2.2", - "Iterators"=>v"0.3.0", - "JSON"=>v"0.9.0", - "JuliaParser"=>v"0.7.4", - "Juno"=>v"0.2.7", - "LNR"=>v"0.0.2", - "Lazy"=>v"0.11.6", - "LearnBase"=>v"0.1.5", - "LineSearches"=>v"0.1.5", - "LossFunctions"=>v"0.1.0", - "LsqFit"=>v"0.2.0", - "MachO"=>v"0.0.4", - "MacroTools"=>v"0.3.6", - "MappedArrays"=>v"0.0.7", - "MbedTLS"=>v"0.4.5", - "Measures"=>v"0.1.0", - "Media"=>v"0.2.7", - "MultiScaleArrays"=>v"0.1.0", - "Mustache"=>v"0.1.4", - "Mux"=>v"0.2.3", - "NLsolve"=>v"0.9.1", - "NaNMath"=>v"0.2.4", - "ObjFileBase"=>v"0.0.4", - "OffsetArrays"=>v"0.3.0", - "Optim"=>v"0.7.8", - "OrdinaryDiffEq"=>v"1.8.0", - "PDMats"=>v"0.6.0", - "ParameterizedFunctions"=>v"1.3.0", - "Parameters"=>v"0.7.2", - "PlotThemes"=>v"0.1.1", - "PlotUtils"=>v"0.3.0", - "Plots"=>v"0.10.3", - "PolynomialFactors"=>v"0.0.4", - "Polynomials"=>v"0.1.5", - "PositiveFactorizations"=>v"0.0.4", - "Primes"=>v"0.1.3", - "QuadGK"=>v"0.1.2", - "RangeArrays"=>v"0.1.2", - "Ranges"=>v"0.0.1", - "Ratios"=>v"0.0.4", - "Reactive"=>v"0.3.7", - "RecipesBase"=>v"0.1.0", - "RecursiveArrayTools"=>v"0.2.0", - "Reexport"=>v"0.0.3", - "ResettableStacks"=>v"0.1.0", - "Rmath"=>v"0.1.6", - "Roots"=>v"0.3.0", - "Rotations"=>v"0.4.0", - "SHA"=>v"0.3.2", - "SIUnits"=>v"0.1.0", - "ShowItLikeYouBuildIt"=>v"0.0.1", - "Showoff"=>v"0.1.1", - "SimpleTraits"=>v"0.4.0", - "SpecialFunctions"=>v"0.1.1", - "StaticArrays"=>v"0.4.0", - "StatsBase"=>v"0.13.1", - "StatsFuns"=>v"0.5.0", - "StochasticDiffEq"=>v"1.4.0", - "StokesDiffEq"=>v"0.1.0", - "StructIO"=>v"0.0.2", - "Sundials"=>v"0.10.0", - "SymEngine"=>v"0.1.5", - "TerminalUI"=>v"0.0.2", - "TexExtensions"=>v"0.0.3", - "TextWrap"=>v"0.2.0", - "TiledIteration"=>v"0.0.2", - "URIParser"=>v"0.1.8", - "VT100"=>v"0.1.0", - "VectorizedRoutines"=>v"0.0.2", - "WebSockets"=>v"0.2.1", - "WoodburyMatrices"=>v"0.2.2", -) diff --git a/julia-0.6.3/share/julia/test/rounding.jl b/julia-0.6.3/share/julia/test/rounding.jl deleted file mode 100644 index 32a19d1..0000000 --- a/julia-0.6.3/share/julia/test/rounding.jl +++ /dev/null @@ -1,139 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -# Small sanity tests to ensure changing the rounding of float functions work -using Base.Test - -## Float64 checks -# a + b returns a number exactly between prevfloat(1.) and 1., so its -# final result depends strongly on the utilized rounding direction. -a = prevfloat(0.5) -b = 0.5 -c = 0x1p-54 -d = prevfloat(1.) - -# Default rounding direction, RoundNearest -@test a + b === 1. -@test - a - b === -1. -@test a - b === -c -@test b - a === c - -# RoundToZero -setrounding(Float64,RoundToZero) do - @test a + b === d - @test - a - b === -d - @test a - b === -c - @test b - a === c -end - -# Sanity check to see if we have returned to RoundNearest -@test a + b === 1. -@test - a - b === -1. -@test a - b == -c -@test b - a == c - -# RoundUp -setrounding(Float64,RoundUp) do - @test a + b === 1. - @test - a - b === -d - @test a - b === -c - @test b - a === c -end - -# RoundDown -setrounding(Float64,RoundDown) do - @test a + b === d - @test - a - b === -1. - @test a - b === -c - @test b - a === c -end - -## Float32 checks - -a32 = prevfloat(0.5f0) -b32 = 0.5f0 -c32 = (1.f0 - prevfloat(1.f0))/2 -d32 = prevfloat(1.0f0) - -# Default rounding direction, RoundNearest -@test a32 + b32 === 1.0f0 -@test - a32 - b32 === -1.0f0 -@test a32 - b32 === -c32 -@test b32 - a32 === c32 - -# RoundToZero -setrounding(Float32,RoundToZero) do - @test a32 + b32 === d32 - @test - a32 - b32 === -d32 - @test a32 - b32 === -c32 - @test b32 - a32 === c32 -end - -# Sanity check to see if we have returned to RoundNearest -@test a32 + b32 === 1.0f0 -@test - a32 - b32 === -1.0f0 -@test a32 - b32 == -c32 -@test b32 - a32 == c32 - -# RoundUp -setrounding(Float32,RoundUp) do - @test a32 + b32 === 1.0f0 - @test - a32 - b32 === -d32 - @test a32 - b32 === -c32 - @test b32 - a32 === c32 -end - -# RoundDown -setrounding(Float32,RoundDown) do - @test a32 + b32 === d32 - @test - a32 - b32 === -1.0f0 - @test a32 - b32 === -c32 - @test b32 - a32 === c32 -end - -# convert with rounding -for v = [sqrt(2),-1/3,nextfloat(1.0),prevfloat(1.0),nextfloat(-1.0), - prevfloat(-1.0),nextfloat(0.0),prevfloat(0.0)] - pn = Float32(v,RoundNearest) - @test pn == convert(Float32,v) - pz = Float32(v,RoundToZero) - @test pz == setrounding(()->convert(Float32,v), Float64, RoundToZero) - pd = Float32(v,RoundDown) - @test pd == setrounding(()->convert(Float32,v), Float64, RoundDown) - pu = Float32(v,RoundUp) - @test pu == setrounding(()->convert(Float32,v), Float64, RoundUp) - - @test pn == pd || pn == pu - @test v > 0 ? pz == pd : pz == pu - @test pu - pd == eps(pz) -end - -for T in [Float32,Float64] - for v in [sqrt(big(2.0)),-big(1.0)/big(3.0),nextfloat(big(1.0)), - prevfloat(big(1.0)),nextfloat(big(0.0)),prevfloat(big(0.0)), - pi,e,eulergamma,catalan,golden, - typemax(Int64),typemax(UInt64),typemax(Int128),typemax(UInt128),0xa2f30f6001bb2ec6] - pn = T(v,RoundNearest) - @test pn == convert(T,BigFloat(v)) - pz = T(v,RoundToZero) - @test pz == setrounding(()->convert(T,BigFloat(v)), BigFloat, RoundToZero) - pd = T(v,RoundDown) - @test pd == setrounding(()->convert(T,BigFloat(v)), BigFloat, RoundDown) - pu = T(v,RoundUp) - @test pu == setrounding(()->convert(T,BigFloat(v)), BigFloat, RoundUp) - - @test pn == pd || pn == pu - @test v > 0 ? pz == pd : pz == pu - @test isinf(pu) || pu - pd == eps(pz) - end -end - -#fenv -@test Base.Rounding.from_fenv(Base.Rounding.to_fenv(RoundNearest)) == RoundNearest -@test Base.Rounding.from_fenv(Base.Rounding.to_fenv(RoundToZero)) == RoundToZero -@test Base.Rounding.from_fenv(Base.Rounding.to_fenv(RoundUp)) == RoundUp -@test Base.Rounding.from_fenv(Base.Rounding.to_fenv(RoundDown)) == RoundDown -@test_throws ArgumentError Base.Rounding.from_fenv(-99) - -badness = 1//0 -@test_throws DivideError round(Int64,badness,RoundNearestTiesAway) -@test_throws DivideError round(Int64,badness,RoundNearestTiesUp) diff --git a/julia-0.6.3/share/julia/test/runtests.jl b/julia-0.6.3/share/julia/test/runtests.jl deleted file mode 100644 index 262ca6a..0000000 --- a/julia-0.6.3/share/julia/test/runtests.jl +++ /dev/null @@ -1,188 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -using Base.Test -include("choosetests.jl") -include("testenv.jl") - -tests, net_on = choosetests(ARGS) -tests = unique(tests) - -const max_worker_rss = if haskey(ENV, "JULIA_TEST_MAXRSS_MB") - parse(Int, ENV["JULIA_TEST_MAXRSS_MB"]) * 2^20 -else - typemax(Csize_t) -end - -const node1_tests = String[] -function move_to_node1(t) - if t in tests - splice!(tests, findfirst(tests, t)) - push!(node1_tests, t) - end -end -# Base.compile only works from node 1, so compile test is handled specially -move_to_node1("compile") -# In a constrained memory environment, run the "distributed" test after all other tests -# since it starts a lot of workers and can easily exceed the maximum memory -max_worker_rss != typemax(Csize_t) && move_to_node1("distributed") - -cd(dirname(@__FILE__)) do - n = 1 - if net_on - n = min(Sys.CPU_CORES, length(tests)) - n > 1 && addprocs_with_testenv(n) - BLAS.set_num_threads(1) - end - - @everywhere include("testdefs.jl") - - #pretty print the information about gc and mem usage - name_align = maximum([length("Test (Worker)"); map(x -> length(x) + 3 + ndigits(nworkers()), tests)]) - elapsed_align = length("Time (s)") - gc_align = length("GC (s)") - percent_align = length("GC %") - alloc_align = length("Alloc (MB)") - rss_align = length("RSS (MB)") - print_with_color(:white, rpad("Test (Worker)",name_align," "), " | ") - print_with_color(:white, "Time (s) | GC (s) | GC % | Alloc (MB) | RSS (MB)\n") - results=[] - @sync begin - for p in workers() - @async begin - while length(tests) > 0 - test = shift!(tests) - local resp - wrkr = p - try - resp = remotecall_fetch(runtests, wrkr, test) - catch e - resp = [e] - end - push!(results, (test, resp)) - if (isa(resp[end], Integer) && (resp[end] > max_worker_rss)) || isa(resp, Exception) - if n > 1 - rmprocs(wrkr, waitfor=30) - p = addprocs_with_testenv(1)[1] - remotecall_fetch(include, p, "testdefs.jl") - else - # single process testing, bail if mem limit reached, or, on an exception. - isa(resp, Exception) ? rethrow(resp) : error("Halting tests. Memory limit reached : $resp > $max_worker_rss") - end - end - if !isa(resp[1], Exception) - print_with_color(:white, rpad(test*" ($wrkr)", name_align, " "), " | ") - time_str = @sprintf("%7.2f",resp[2]) - print_with_color(:white, rpad(time_str,elapsed_align," "), " | ") - gc_str = @sprintf("%5.2f",resp[5].total_time/10^9) - print_with_color(:white, rpad(gc_str,gc_align," "), " | ") - - # since there may be quite a few digits in the percentage, - # the left-padding here is less to make sure everything fits - percent_str = @sprintf("%4.1f",100*resp[5].total_time/(10^9*resp[2])) - print_with_color(:white, rpad(percent_str,percent_align," "), " | ") - alloc_str = @sprintf("%5.2f",resp[3]/2^20) - print_with_color(:white, rpad(alloc_str,alloc_align," "), " | ") - rss_str = @sprintf("%5.2f",resp[6]/2^20) - print_with_color(:white, rpad(rss_str,rss_align," "), "\n") - end - end - end - end - end - # Free up memory =) - n > 1 && rmprocs(workers(), waitfor=30) - for t in node1_tests - # As above, try to run each test - # which must run on node 1. If - # the test fails, catch the error, - # and either way, append the results - # to the overall aggregator - n > 1 && print("\tFrom worker 1:\t") - local resp - try - resp = eval(Expr(:call, () -> runtests(t))) # runtests is defined by the include above - catch e - resp = [e] - end - push!(results, (t, resp)) - end - #= -` Construct a testset on the master node which will hold results from all the - test files run on workers and on node1. The loop goes through the results, - inserting them as children of the overall testset if they are testsets, - handling errors otherwise. - - Since the workers don't return information about passing/broken tests, only - errors or failures, those Result types get passed `nothing` for their test - expressions (and expected/received result in the case of Broken). - - If a test failed, returning a `RemoteException`, the error is displayed and - the overall testset has a child testset inserted, with the (empty) Passes - and Brokens from the worker and the full information about all errors and - failures encountered running the tests. This information will be displayed - as a summary at the end of the test run. - - If a test failed, returning an `Exception` that is not a `RemoteException`, - it is likely the julia process running the test has encountered some kind - of internal error, such as a segfault. The entire testset is marked as - Errored, and execution continues until the summary at the end of the test - run, where the test file is printed out as the "failed expression". - =# - o_ts = Base.Test.DefaultTestSet("Overall") - Base.Test.push_testset(o_ts) - for res in results - if isa(res[2][1], Base.Test.DefaultTestSet) - Base.Test.push_testset(res[2][1]) - Base.Test.record(o_ts, res[2][1]) - Base.Test.pop_testset() - elseif isa(res[2][1], Tuple{Int,Int}) - fake = Base.Test.DefaultTestSet(res[1]) - for i in 1:res[2][1][1] - Base.Test.record(fake, Base.Test.Pass(:test, nothing, nothing, nothing)) - end - for i in 1:res[2][1][2] - Base.Test.record(fake, Base.Test.Broken(:test, nothing)) - end - Base.Test.push_testset(fake) - Base.Test.record(o_ts, fake) - Base.Test.pop_testset() - elseif isa(res[2][1], RemoteException) && isa(res[2][1].captured.ex, Base.Test.TestSetException) - println("Worker $(res[2][1].pid) failed running test $(res[1]):") - Base.showerror(STDOUT,res[2][1].captured) - fake = Base.Test.DefaultTestSet(res[1]) - for i in 1:res[2][1].captured.ex.pass - Base.Test.record(fake, Base.Test.Pass(:test, nothing, nothing, nothing)) - end - for i in 1:res[2][1].captured.ex.broken - Base.Test.record(fake, Base.Test.Broken(:test, nothing)) - end - for t in res[2][1].captured.ex.errors_and_fails - Base.Test.record(fake, t) - end - Base.Test.push_testset(fake) - Base.Test.record(o_ts, fake) - Base.Test.pop_testset() - elseif isa(res[2][1], Exception) - # If this test raised an exception that is not a remote testset exception, - # i.e. not a RemoteException capturing a TestSetException that means - # the test runner itself had some problem, so we may have hit a segfault, - # deserialization errors or something similar. Record this testset as Errored. - fake = Base.Test.DefaultTestSet(res[1]) - Base.Test.record(fake, Base.Test.Error(:test_error, res[1], res[2][1], [])) - Base.Test.push_testset(fake) - Base.Test.record(o_ts, fake) - Base.Test.pop_testset() - else - error(string("Unknown result type : ", typeof(res))) - end - end - println() - Base.Test.print_test_results(o_ts,1) - if !o_ts.anynonpass - println(" \033[32;1mSUCCESS\033[0m") - else - println(" \033[31;1mFAILURE\033[0m") - Base.Test.print_test_errors(o_ts) - throw(Test.FallbackTestSetException("Test run finished with errors")) - end -end diff --git a/julia-0.6.3/share/julia/test/serialize.jl b/julia-0.6.3/share/julia/test/serialize.jl deleted file mode 100644 index 5326eeb..0000000 --- a/julia-0.6.3/share/julia/test/serialize.jl +++ /dev/null @@ -1,493 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -using Base.Test - -# Check that serializer hasn't gone out-of-frame -@test Serializer.sertag(Symbol) == 1 -@test Serializer.sertag(()) == 55 -@test Serializer.sertag(false) == 63 - -function create_serialization_stream(f::Function) - s = IOBuffer() - f(s) - close(s) -end - -# Tags -create_serialization_stream() do s - Serializer.writetag(s, Serializer.sertag(Bool)) - @test take!(s)[end] == UInt8(Serializer.sertag(Bool)) -end - -create_serialization_stream() do s - Serializer.write_as_tag(s, Serializer.sertag(Bool)) - @test take!(s)[end] == UInt8(Serializer.sertag(Bool)) -end - -create_serialization_stream() do s - Serializer.write_as_tag(s, Serializer.sertag(Symbol)) - data = take!(s) - @test data[end-1] == 0x00 - @test data[end] == UInt8(Serializer.sertag(Symbol)) -end - -# Boolean & Empty & Nothing -create_serialization_stream() do s - serialize(s, true) - serialize(s, ()) - serialize(s, nothing) - seek(s, 0) - @test deserialize(s) === true - @test deserialize(s) === () - @test deserialize(s) === nothing -end - -# Ptr -create_serialization_stream() do s - serialize(s, C_NULL) - seekstart(s) - @test deserialize(s) === C_NULL -end - -# Integer -create_serialization_stream() do s - serialize(s, 0x1) - serialize(s, 32) - serialize(s, 33) - seek(s,0) - @test deserialize(s) === 0x01 - @test deserialize(s) === 32 - @test deserialize(s) === 33 -end - -# Tuple -create_serialization_stream() do s - tpl = (0x1,'a') - serialize(s, tpl) - - len = 257 - lt = ntuple(i->0x1, len) - serialize(s, lt) - - serialize(s, Tuple{}) - - seek(s, 0) - @test deserialize(s) === tpl - @test deserialize(s) === lt - @test deserialize(s) === Tuple{} -end - -# Dict -create_serialization_stream() do s - dct = Dict("A"=>1, "B"=>2) - serialize(s, dct) - seek(s, 0) - @test deserialize(s) == dct -end - -# Symbol -create_serialization_stream() do s - gensym(len) = Symbol(repeat("A", len)) - - smbl = gensym(1) - serialize(s, smbl) - - smbl2 = gensym(10) - serialize(s, smbl2) - - smbl3 = gensym(257) - serialize(s, smbl3) - - seek(s, 0) - @test deserialize(s) === smbl - @test deserialize(s) === smbl2 - @test deserialize(s) === smbl3 -end - -# Module -create_serialization_stream() do s # user-defined module - mod = b"SomeModule" - modstring = String(mod) - eval(parse("module $(modstring); end")) - modtype = eval(parse("$(modstring)")) - serialize(s, modtype) - seek(s, 0) - @test deserialize(s) === modtype -end - -# DataType -create_serialization_stream() do s # standard types - typ1 = UInt8 - serialize(s, typ1) - typ2 = Bool - serialize(s, typ2) - - seek(s, 0) - @test deserialize(s) == typ1 - @test deserialize(s) == typ2 -end - -create_serialization_stream() do s # user-defined type - usertype = "SerializeSomeType" - eval(parse("abstract type $(usertype) end")) - utype = eval(parse("$(usertype)")) - serialize(s, utype) - seek(s, 0) - @test deserialize(s) === utype -end - -create_serialization_stream() do s # user-defined type - usertype = "SerializeSomeType1" - eval(parse("mutable struct $(usertype); end")) - utype = eval(parse("$(usertype)")) - serialize(s, utype) - seek(s, 0) - @test deserialize(s) === utype -end - -create_serialization_stream() do s # user-defined type - usertype = "SerializeSomeType2" - eval(parse("abstract type $(usertype){T} end")) - utype = eval(parse("$(usertype)")) - serialize(s, utype) - seek(s, 0) - @test deserialize(s) == utype -end - -create_serialization_stream() do s # immutable struct with 1 field - usertype = "SerializeSomeType3" - eval(parse("struct $(usertype){T}; a::T; end")) - utype = eval(parse("$(usertype)")) - serialize(s, utype) - seek(s, 0) - @test deserialize(s) == utype -end - -create_serialization_stream() do s # immutable struct with 2 field - usertype = "SerializeSomeType4" - eval(parse("struct $(usertype){T}; a::T; b::T; end")) - utval = eval(parse("$(usertype)(1,2)")) - serialize(s, utval) - seek(s, 0) - @test deserialize(s) === utval -end - -create_serialization_stream() do s # immutable struct with 3 field - usertype = "SerializeSomeType5" - eval(parse("struct $(usertype){T}; a::T; b::T; c::T; end")) - utval = eval(parse("$(usertype)(1,2,3)")) - serialize(s, utval) - seek(s, 0) - @test deserialize(s) === utval -end - -create_serialization_stream() do s # immutable struct with 4 field - usertype = "SerializeSomeType6" - eval(parse("struct $(usertype){T}; a::T; b::T; c::T; d::T; end")) - utval = eval(parse("$(usertype)(1,2,3,4)")) - serialize(s, utval) - seek(s, 0) - @test deserialize(s) === utval -end - -# Expression -create_serialization_stream() do s - expr = parse("a = 1") - serialize(s, expr) - - expr2 = parse(repeat("a = 1;", 300)) - serialize(s, expr2) - - seek(s, 0) - @test deserialize(s) == expr - @test deserialize(s) == expr2 -end - -# Array -mutable struct TA1 - v::UInt8 -end -create_serialization_stream() do s # small 1d array - arr1 = fill(0x01, 10) # small 1d array - serialize(s, arr1) - arr2 = fill(0x01, 3, 3) # small 2d array - serialize(s, arr2) - arr3 = fill(0x0001, 50) # large 1d array - serialize(s, arr3) - arr4 = reshape([true, false, false, false, true, false, false, false, true], 3, 3) - serialize(s, arr4) # boolean array - - arr5 = Array{TA1}(3) - arr5[2] = TA1(0x01) - serialize(s, arr5) - - seek(s, 0) - @test deserialize(s) == arr1 - @test deserialize(s) == arr2 - @test deserialize(s) == arr3 - @test deserialize(s) == arr4 - - result = deserialize(s) - @test !isassigned(result,1) - @test !isassigned(result,3) - @test result[2].v == arr5[2].v -end - -# SubArray -create_serialization_stream() do s # slices - slc1 = view(ones(UInt8, 4), 2:3) - serialize(s, slc1) - slc2 = view(ones(UInt8, 4, 4) .+ [0x00, 0x01, 0x02, 0x03], 1, 2:4) - serialize(s, slc2) - - seek(s, 0) - @test deserialize(s) == slc1 - @test deserialize(s) == slc2 -end - -# Objects that have a SubArray as a type in a type-parameter list -module ArrayWrappers - -struct ArrayWrapper{T,N,A<:AbstractArray} <: AbstractArray{T,N} - data::A -end -ArrayWrapper{T,N}(data::AbstractArray{T,N}) = ArrayWrapper{T,N,typeof(data)}(data) -Base.size(A::ArrayWrapper) = size(A.data) -Base.size(A::ArrayWrapper, d) = size(A.data, d) -Base.getindex(A::ArrayWrapper, i::Real...) = getindex(A.data, i...) - -end - -let A = rand(3,4) - for B in (view(A, :, 2:4), view(A, 2, 1:3)) - C = ArrayWrappers.ArrayWrapper(B) - io = IOBuffer() - serialize(io, C) - seek(io, 0) - Cd = deserialize(io) - @test size(Cd) == size(C) - @test Cd == B - end -end - -# Function -serialize_test_function() = 1 -serialize_test_function2 = ()->1 -create_serialization_stream() do s # Base generic function - serialize(s, sin) - serialize(s, typeof) - serialize(s, serialize_test_function) - serialize(s, serialize_test_function2) - - seek(s, 0) - @test deserialize(s) === sin - @test deserialize(s) === typeof - @test deserialize(s)() === 1 - @test deserialize(s)() === 1 -end - -# Anonymous Functions -main_ex = quote - $create_serialization_stream() do s - local g() = :magic_token_anon_fun_test - serialize(s, g) - serialize(s, g) - - seekstart(s) - ds = SerializationState(s) - local g2 = deserialize(ds) - $Test.@test g2 !== g - $Test.@test g2() == :magic_token_anon_fun_test - $Test.@test g2() == :magic_token_anon_fun_test - $Test.@test deserialize(ds) === g2 - - # issue #21793 - y = x -> (() -> x) - seekstart(s) - serialize(s, y) - seekstart(s) - y2 = deserialize(s) - x2 = y2(2) - $Test.@test x2() == 2 - end -end -# This needs to be run on `Main` since the serializer treats it differently. -eval(Main, main_ex) - -# Task -create_serialization_stream() do s # user-defined type array - f = () -> begin task_local_storage(:v, 2); return 1+1 end - t = Task(f) - wait(schedule(t)) - serialize(s, t) - seek(s, 0) - r = deserialize(s) - @test r.storage[:v] == 2 - @test r.state == :done - @test r.exception === nothing -end - -struct MyErrorTypeTest <: Exception end -create_serialization_stream() do s # user-defined type array - t = Task(()->throw(MyErrorTypeTest())) - @test_throws MyErrorTypeTest wait(schedule(t)) - serialize(s, t) - seek(s, 0) - r = deserialize(s) - @test r.state == :failed - @test isa(t.exception, MyErrorTypeTest) -end - -# corner case: undefined inside immutable struct -create_serialization_stream() do s - serialize(s, Nullable{Any}()) - seekstart(s) - n = deserialize(s) - @test isa(n, Nullable) - @test !isdefined(n, :value) -end - -# cycles -module CycleFoo - echo(x)=x -end -create_serialization_stream() do s - echo(x) = x - afunc = (x)->x - A = Any[1,2,3,abs,abs,afunc,afunc,echo,echo,CycleFoo.echo,CycleFoo.echo,4,5] - A[3] = A - serialize(s, A) - seekstart(s) - b = deserialize(s) - @test b[3] === b - @test b[1] == 1 - @test b[4] === abs - @test b[5] === b[4] - @test b[5](-1) == 1 - - @test b[6] === b[7] - @test b[6]("Hello") == "Hello" - - @test b[8] === b[9] - @test b[8]("World") == "World" - - @test b[10] === b[11] - @test b[10]("foobar") == "foobar" - - @test b[end] == 5 - @test length(b) == length(A) - @test isa(b,Vector{Any}) -end - -# shared references -create_serialization_stream() do s - A = [1,2] - B = [A,A] - serialize(s, B) - seekstart(s) - C = deserialize(s) - @test C == B - @test C[1] === C[2] -end - -# Regex -create_serialization_stream() do s - r1 = r"a?b.*" - serialize(s, r1) - seekstart(s) - r2 = deserialize(s) - @test r1 == r2 -end - -# issue #13452 -module Test13452 -using Base.Test - -module Shell -export foo -foo(x) = error("Instances must implement foo") -end - -module Instance1 -using ..Shell -Shell.foo(x::Int) = "This is an Int" -end - -using .Shell, .Instance1 -io = IOBuffer() -serialize(io, foo) -str = String(take!(io)) -@test isempty(search(str, "Instance1")) -@test !isempty(search(str, "Shell")) - -end # module Test13452 - -# issue #15163 -mutable struct B15163{T} - x::Array{T} -end -let b = IOBuffer() - serialize(b,B15163([1])) - seekstart(b) - c = deserialize(b) - @test isa(c,B15163) && c.x == [1] -end -# related issue #20066 -let b = IOBuffer() - serialize(b, Dict{Vector, Vector}()) - seekstart(b) - c = deserialize(b) - @test isa(c, Dict{Vector, Vector}) -end - -# issue #15849 -let b = IOBuffer() - vt = Tuple[(1,)] - serialize(b, vt) - seekstart(b) - @test deserialize(b) == vt -end - -# issue #1770 -let a = ['T', 'e', 's', 't'] - f = IOBuffer() - serialize(f, a) - seek(f, 0) - @test deserialize(f) == a - f = IOBuffer() - serialize(f, a) - seek(f, 0) - @test deserialize(f) == a - - # issue #4414 - seek(f,0) - serialize(f, :β) - seek(f,0) - @test deserialize(f) === :β -end - -# issue #20324 -struct T20324{T} - x::T -end -let x = T20324[T20324(1) for i = 1:2] - b = IOBuffer() - serialize(b, x) - seekstart(b) - y = deserialize(b) - @test isa(y,Vector{T20324}) - @test y == x -end - -# issue #26979 -let io = IOBuffer() - function gen_f(a::T) where T - f = x -> T(x) - return f - end - f = gen_f(1f0) - serialize(io, f) - seekstart(io) - f2 = deserialize(io) - @test f2(1) === 1f0 -end diff --git a/julia-0.6.3/share/julia/test/sets.jl b/julia-0.6.3/share/julia/test/sets.jl deleted file mode 100644 index 4c3adaa..0000000 --- a/julia-0.6.3/share/julia/test/sets.jl +++ /dev/null @@ -1,278 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -# Set tests - -# Construction, collect -@test ===(typeof(Set([1,2,3])), Set{Int}) -@test ===(typeof(Set{Int}([3])), Set{Int}) -data_in = (1,"banana", ()) -s = Set(data_in) -data_out = collect(s) -@test ===(typeof(data_out), Array{Any,1}) -@test all(map(d->in(d,data_out), data_in)) -@test length(data_out) == length(data_in) -let f17741 = x -> x < 0 ? false : 1 - @test isa(Set(x for x = 1:3), Set{Int}) - @test isa(Set(sin(x) for x = 1:3), Set{Float64}) - @test isa(Set(f17741(x) for x = 1:3), Set{Int}) - @test isa(Set(f17741(x) for x = -1:1), Set{Integer}) -end - -# hash -s1 = Set(["bar", "foo"]) -s2 = Set(["foo", "bar"]) -s3 = Set(["baz"]) -@test hash(s1) == hash(s2) -@test hash(s1) != hash(s3) - -# isequal -@test isequal(Set(), Set()) -@test !isequal(Set(), Set([1])) -@test isequal(Set{Any}(Any[1,2]), Set{Int}([1,2])) -@test !isequal(Set{Any}(Any[1,2]), Set{Int}([1,2,3])) -# Comparison of unrelated types seems rather inconsistent -@test isequal(Set{Int}(), Set{AbstractString}()) -@test !isequal(Set{Int}(), Set{AbstractString}([""])) -@test !isequal(Set{AbstractString}(), Set{Int}([0])) -@test !isequal(Set{Int}([1]), Set{AbstractString}()) -@test isequal(Set{Any}([1,2,3]), Set{Int}([1,2,3])) -@test isequal(Set{Int}([1,2,3]), Set{Any}([1,2,3])) -@test !isequal(Set{Any}([1,2,3]), Set{Int}([1,2,3,4])) -@test !isequal(Set{Int}([1,2,3]), Set{Any}([1,2,3,4])) -@test !isequal(Set{Any}([1,2,3,4]), Set{Int}([1,2,3])) -@test !isequal(Set{Int}([1,2,3,4]), Set{Any}([1,2,3])) - -# eltype, similar -s1 = similar(Set([1,"hello"])) -@test isequal(s1, Set()) -@test ===(eltype(s1), Any) -s2 = similar(Set{Float32}([2.0f0,3.0f0,4.0f0])) -@test isequal(s2, Set()) -@test ===(eltype(s2), Float32) -s3 = similar(Set([1,"hello"]),Float32) -@test isequal(s3, Set()) -@test ===(eltype(s3), Float32) - -# show -@test sprint(show, Set()) == "Set{Any}()" -@test sprint(show, Set(['a'])) == "Set(['a'])" - -# isempty, length, in, push, pop, delete -# also test for no duplicates -s = Set(); push!(s,1); push!(s,2); push!(s,3) -@test !isempty(s) -@test in(1,s) -@test in(2,s) -@test length(s) == 3 -push!(s,1); push!(s,2); push!(s,3) -@test length(s) == 3 -@test pop!(s,1) == 1 -@test !in(1,s) -@test in(2,s) -@test length(s) == 2 -@test_throws KeyError pop!(s,1) -@test pop!(s,1,:foo) == :foo -@test length(delete!(s,2)) == 1 -@test !in(1,s) -@test !in(2,s) -@test pop!(s) == 3 -@test length(s) == 0 -@test isempty(s) - -# copy -data_in = (1,2,9,8,4) -s = Set(data_in) -c = copy(s) -@test isequal(s,c) -v = pop!(s) -@test !in(v,s) -@test in(v,c) -push!(s,100) -push!(c,200) -@test !in(100,c) -@test !in(200,s) - -# sizehint, empty -s = Set([1]) -@test isequal(sizehint!(s, 10), Set([1])) -@test isequal(empty!(s), Set()) - -# rehash! -let - # Use a pointer type to have defined behavior for uninitialized - # array element - s = Set(["a", "b", "c"]) - Base.rehash!(s) - k = s.dict.keys - Base.rehash!(s) - @test length(k) == length(s.dict.keys) - for i in 1:length(k) - if isassigned(k, i) - @test k[i] == s.dict.keys[i] - else - @test !isassigned(s.dict.keys, i) - end - end - s == Set(["a", "b", "c"]) -end - -# start, done, next -for data_in in ((7,8,4,5), - ("hello", 23, 2.7, (), [], (1,8))) - s = Set(data_in) - - s_new = Set() - for el in s - push!(s_new, el) - end - @test isequal(s, s_new) - - t = tuple(s...) - @test length(t) == length(s) - for e in t - @test in(e,s) - end -end - -# union -@test isequal(union(),Set()) -@test isequal(union(Set([1])),Set([1])) -s = ∪(Set([1,2]), Set([3,4])) -@test isequal(s, Set([1,2,3,4])) -s = union(Set([5,6,7,8]), Set([7,8,9])) -@test isequal(s, Set([5,6,7,8,9])) -s = Set([1,3,5,7]) -union!(s,(2,3,4,5)) -@test isequal(s,Set([1,2,3,4,5,7])) - -# intersect -@test isequal(intersect(Set([1])),Set([1])) -s = ∩(Set([1,2]), Set([3,4])) -@test isequal(s, Set()) -s = intersect(Set([5,6,7,8]), Set([7,8,9])) -@test isequal(s, Set([7,8])) -@test isequal(intersect(Set([2,3,1]), Set([4,2,3]), Set([5,4,3,2])), Set([2,3])) - -# setdiff -@test isequal(setdiff(Set([1,2,3]), Set()), Set([1,2,3])) -@test isequal(setdiff(Set([1,2,3]), Set([1])), Set([2,3])) -@test isequal(setdiff(Set([1,2,3]), Set([1,2])), Set([3])) -@test isequal(setdiff(Set([1,2,3]), Set([1,2,3])), Set()) -@test isequal(setdiff(Set([1,2,3]), Set([4])), Set([1,2,3])) -@test isequal(setdiff(Set([1,2,3]), Set([4,1])), Set([2,3])) -s = Set([1,3,5,7]) -setdiff!(s,(3,5)) -@test isequal(s,Set([1,7])) -s = Set([1,2,3,4]) -setdiff!(s, Set([2,4,5,6])) -@test isequal(s,Set([1,3])) - -# ordering -@test Set() < Set([1]) -@test Set([1]) < Set([1,2]) -@test !(Set([3]) < Set([1,2])) -@test !(Set([3]) > Set([1,2])) -@test Set([1,2,3]) > Set([1,2]) -@test !(Set([3]) <= Set([1,2])) -@test !(Set([3]) >= Set([1,2])) -@test Set([1]) <= Set([1,2]) -@test Set([1,2]) <= Set([1,2]) -@test Set([1,2]) >= Set([1,2]) -@test Set([1,2,3]) >= Set([1,2]) -@test !(Set([1,2,3]) >= Set([1,2,4])) -@test !(Set([1,2,3]) <= Set([1,2,4])) - -# issubset, symdiff -for (l,r) in ((Set([1,2]), Set([3,4])), - (Set([5,6,7,8]), Set([7,8,9])), - (Set([1,2]), Set([3,4])), - (Set([5,6,7,8]), Set([7,8,9])), - (Set([1,2,3]), Set()), - (Set([1,2,3]), Set([1])), - (Set([1,2,3]), Set([1,2])), - (Set([1,2,3]), Set([1,2,3])), - (Set([1,2,3]), Set([4])), - (Set([1,2,3]), Set([4,1]))) - @test issubset(intersect(l,r), l) - @test issubset(intersect(l,r), r) - @test issubset(l, union(l,r)) - @test issubset(r, union(l,r)) - @test isequal(union(intersect(l,r),symdiff(l,r)), union(l,r)) -end -using Base: ⊇, ⊉, ⊋ -@test ⊆(Set([1]), Set([1,2])) -@test ⊊(Set([1]), Set([1,2])) -@test !⊊(Set([1]), Set([1])) -@test ⊈(Set([1]), Set([2])) -@test ⊇(Set([1,2]), Set([1])) -@test ⊋(Set([1,2]), Set([1])) -@test !⊋(Set([1]), Set([1])) -@test ⊉(Set([1]), Set([2])) -@test symdiff(Set([1,2,3,4]), Set([2,4,5,6])) == Set([1,3,5,6]) - -# unique -u = unique([1,1,2]) -@test in(1,u) -@test in(2,u) -@test length(u) == 2 -@test unique(iseven, [5,1,8,9,3,4,10,7,2,6]) == [5,8] -@test unique(n->n % 3, [5,1,8,9,3,4,10,7,2,6]) == [5,1,9] -# issue 20105 -@test @inferred(unique(x for x in 1:1)) == [1] -@test unique(x for x in Any[1,1.0])::Vector{Real} == [1] - -# allunique -@test allunique([]) -@test allunique(Set()) -@test allunique([1,2,3]) -@test allunique([:a,:b,:c]) -@test allunique(Set([1,2,3])) -@test !allunique([1,1,2]) -@test !allunique([:a,:b,:c,:a]) -@test allunique(4:7) -@test allunique(1:1) -@test allunique(4.0:0.3:7.0) -@test allunique(4:-1:5) # empty range -@test allunique(7:-1:1) # negative step - -# filter -s = Set([1,2,3,4]) -@test isequal(filter(isodd,s), Set([1,3])) -filter!(isodd, s) -@test isequal(s, Set([1,3])) - -# first -@test_throws ArgumentError first(Set()) -@test first(Set(2)) == 2 - -# pop! -let s = Set(1:5) - @test 2 in s - @test pop!(s, 2) == 2 - @test !(2 in s) - @test_throws KeyError pop!(s, 2) - @test pop!(s, 2, ()) == () - @test 3 in s - @test pop!(s, 3, ()) == 3 - @test !(3 in s) -end - -@test pop!(Set(1:2), 2, nothing) == 2 - -@test length(Set(['x',120])) == 2 - -# convert -let - iset = Set([17, 4711]) - cfset = convert(Set{Float64}, iset) - @test typeof(cfset) == Set{Float64} - @test cfset == iset - fset = Set([17.0, 4711.0]) - ciset = convert(Set{Int}, fset) - @test typeof(ciset) == Set{Int} - @test ciset == fset - ssset = Set(split("foo bar")) - cssset = convert(Set{String}, ssset) - @test typeof(cssset) == Set{String} - @test cssset == Set(["foo", "bar"]) -end diff --git a/julia-0.6.3/share/julia/test/show.jl b/julia-0.6.3/share/julia/test/show.jl deleted file mode 100644 index db22195..0000000 --- a/julia-0.6.3/share/julia/test/show.jl +++ /dev/null @@ -1,683 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -# For curmod_* -include("testenv.jl") - -replstr(x) = sprint((io,x) -> show(IOContext(io, :limit => true), MIME("text/plain"), x), x) - -@test replstr(Array{Any}(2)) == "2-element Array{Any,1}:\n #undef\n #undef" -@test replstr(Array{Any}(2,2)) == "2×2 Array{Any,2}:\n #undef #undef\n #undef #undef" -@test replstr(Array{Any}(2,2,2)) == "2×2×2 Array{Any,3}:\n[:, :, 1] =\n #undef #undef\n #undef #undef\n\n[:, :, 2] =\n #undef #undef\n #undef #undef" -@test replstr([1f10]) == "1-element Array{Float32,1}:\n 1.0f10" - -struct T5589 - names::Vector{String} -end -@test replstr(T5589(Array{String,1}(100))) == "$(curmod_prefix)T5589(String[#undef, #undef, #undef, #undef, #undef, #undef, #undef, #undef, #undef, #undef … #undef, #undef, #undef, #undef, #undef, #undef, #undef, #undef, #undef, #undef])" - -@test replstr(parse("mutable struct X end")) == ":(mutable struct X # none, line 1:\n end)" -@test replstr(parse("struct X end")) == ":(struct X # none, line 1:\n end)" -s = "ccall(:f, Int, (Ptr{Void},), &x)" -@test replstr(parse(s)) == ":($s)" - -# recursive array printing -# issue #10353 -let - a = Any[] - push!(a,a) - show(IOBuffer(), a) - push!(a,a) - show(IOBuffer(), a) -end - -# expression printing - -macro test_repr(x) - quote - # Note: We can't just compare x1 and x2 because interpolated - # strings get converted to string Exprs by the first show(). - # This could produce a few false positives, but until string - # interpolation works we don't really have a choice. - let - local x1 = parse($x) - local x2 = eval(parse(repr(x1))) - local x3 = eval(parse(repr(x2))) - x3 == x1 ? nothing : error(string( - "repr test failed:", - "\noriginal: ", $x, - "\n\nparsed: ", x2, "\n", sprint(dump, x2), - "\n\nreparsed: ", x3, "\n", sprint(dump, x3) - )) - end - end -end - -# primitive types -@test_repr "x" -@test_repr "123" -@test_repr "\"123\"" -@test_repr ":()" -@test_repr ":(x, y)" - -# basic expressions -@test_repr "x + y" -@test_repr "2e" -@test_repr "!x" -@test_repr "f(1, 2, 3)" -@test_repr "x = ~y" -@test_repr ":(:x, :y)" -@test_repr ":(:(:(x)))" - -# order of operations -@test_repr "x + y * z" -@test_repr "x * y + z" -@test_repr "x * (y + z)" -@test_repr "!x^y" -@test_repr "!x^(y+z)" -@test_repr "!(x^y+z)" -@test_repr "x^-y" -@test_repr "x^-(y+z)" -@test_repr "x^-f(y+z)" -@test_repr "+(w-x)^-f(y+z)" -#@test_repr "w = (x = y) = z" # Doesn't pass, but it's an invalid assignment loc -@test_repr "a & b && c" -@test_repr "a & (b && c)" -@test_repr "(a => b) in c" -@test_repr "a => b in c" -@test_repr "*(a..., b)" -@test_repr "+(a, b, c...)" - -# precedence tie resolution -@test_repr "(a * b) * (c * d)" -@test_repr "(a / b) / (c / d / e)" -@test_repr "(a == b == c) != (c == d < e)" - -# control structures (shamelessly stolen from base/bitarray.jl) -@test_repr """mutable struct BitArray{N} <: AbstractArray{Bool, N} - chunks::Vector{UInt64} - len::Int - dims::NTuple{N,Int} - function BitArray(dims::Int...) - if length(dims) != N - error(\"number of dimensions must be \$N (got \$(length(dims)))\") - end - n = 1 - for d in dims - if d < 0 - error(\"dimension size must be nonnegative (got \$d)\") - end - n *= d - end - nc = num_bit_chunks(n) - chunks = Array{UInt64,1}(nc) - if nc > 0 - chunks[end] = UInt64(0) - end - b = new(chunks, n) - if N != 1 - b.dims = dims - end - return b - end -end""" - -@test_repr """function copy_chunks(dest::Vector{UInt64}, pos_d::Integer, src::Vector{UInt64}, pos_s::Integer, numbits::Integer) - if numbits == 0 - return - end - if dest === src && pos_d > pos_s - return copy_chunks_rtol(dest, pos_d, pos_s, numbits) - end - kd0, ld0 = get_chunks_id(pos_d) - kd1, ld1 = get_chunks_id(pos_d + numbits - 1) - ks0, ls0 = get_chunks_id(pos_s) - ks1, ls1 = get_chunks_id(pos_s + numbits - 1) - delta_kd = kd1 - kd0 - delta_ks = ks1 - ks0 - u = _msk64 - if delta_kd == 0 - msk_d0 = ~(u << ld0) | (u << ld1 << 1) - else - msk_d0 = ~(u << ld0) - msk_d1 = (u << ld1 << 1) - end - if delta_ks == 0 - msk_s0 = (u << ls0) & ~(u << ls1 << 1) - else - msk_s0 = (u << ls0) - end - chunk_s0 = glue_src_bitchunks(src, ks0, ks1, msk_s0, ls0) - dest[kd0] = (dest[kd0] & msk_d0) | ((chunk_s0 << ld0) & ~msk_d0) - if delta_kd == 0 - return - end - for i = 1 : kd1 - kd0 - 1 - chunk_s1 = glue_src_bitchunks(src, ks0 + i, ks1, msk_s0, ls0) - chunk_s = (chunk_s0 >>> (63 - ld0) >>> 1) | (chunk_s1 << ld0) - dest[kd0 + i] = chunk_s - chunk_s0 = chunk_s1 - end - if ks1 >= ks0 + delta_kd - chunk_s1 = glue_src_bitchunks(src, ks0 + delta_kd, ks1, msk_s0, ls0) - else - chunk_s1 = UInt64(0) - end - chunk_s = (chunk_s0 >>> (63 - ld0) >>> 1) | (chunk_s1 << ld0) - dest[kd1] = (dest[kd1] & msk_d1) | (chunk_s & ~msk_d1) - return -end""" - -# issue #7188 -@test sprint(show, :foo) == ":foo" -@test sprint(show, Symbol("foo bar")) == "Symbol(\"foo bar\")" -@test sprint(show, Symbol("foo \"bar")) == "Symbol(\"foo \\\"bar\")" -@test sprint(show, :+) == ":+" -@test sprint(show, :end) == ":end" - -# issue #12477 -@test sprint(show, Union{Int64, Int32, Int16, Int8, Float64}) == "Union{Float64, Int16, Int32, Int64, Int8}" - -# Function and array reference precedence -@test_repr "([2] + 3)[1]" -@test_repr "foo.bar[1]" -@test_repr "foo.bar()" -@test_repr "(foo + bar)()" - -# issue #7921 -@test replace(sprint(show, Expr(:function, :(==(a, b)), Expr(:block,:(return a == b)))), - r"\s+", " ") == ":(function ==(a, b) return a == b end)" - -# unicode operator printing -@test sprint(show, :(1 ⊕ (2 ⊗ 3))) == ":(1 ⊕ 2 ⊗ 3)" -@test sprint(show, :((1 ⊕ 2) ⊗ 3)) == ":((1 ⊕ 2) ⊗ 3)" - -# issue #8155 -@test_repr "foo(x,y; z=bar)" -@test_repr "foo(x,y,z=bar)" - -@test_repr "Int[i for i=1:10]" -@test_repr "Int[(i, j) for (i, j) in zip(1:10,1:0)]" - -@test_repr "[1 2 3; 4 5 6; 7 8 9]'" - -@test_repr "baremodule X -importall ..A.b -import ...B.c -import D -import B.C.D.E.F.g -end" -@test_repr "baremodule Y -export A, B, C -export D, E, F -end" - -# issue #19840 -@test_repr "Array{Int}(0)" -@test_repr "Array{Int}(0,0)" -@test_repr "Array{Int}(0,0,0)" -@test_repr "Array{Int}(0,1)" -@test_repr "Array{Int}(0,0,1)" - -# issue #8994 -@test_repr "get! => 2" -@test_repr "(<) : 2" -@test_repr "(<) :: T" -@test_repr "S{(<) <: T}" -@test_repr "+ + +" - -# issue #9474 -for s in ("(1::Int64 == 1::Int64)::Bool", "(1:2:3) + 4", "x = 1:2:3") - @test sprint(show, parse(s)) == ":("*s*")" -end - -# parametric type instantiation printing -struct TParametricPrint{a}; end -@test sprint(show, :(TParametricPrint{false}())) == ":(TParametricPrint{false}())" - -# issue #9797 -let q1 = parse(repr(:("$(a)b"))), - q2 = parse(repr(:("$ab"))) - @test isa(q1, Expr) - @test q1.args[1].head === :string - @test q1.args[1].args == [:a, "b"] - - @test isa(q2, Expr) - @test q2.args[1].head == :string - @test q2.args[1].args == [:ab,] -end - -x8d003 = 2 -let a = Expr(:quote,Expr(:$,:x8d003)) - @test eval(parse(repr(a))) == a - @test eval(eval(parse(repr(a)))) == 2 -end - -# issue #9865 -@test ismatch(r"^Set\(\[.+….+\]\)$", replstr(Set(1:100))) - -# issue #11413 -@test string(:(*{1, 2})) == "*{1, 2}" -@test string(:(*{1, x})) == "*{1, x}" -@test string(:(-{x})) == "-{x}" - -# issue #11393 -@test_repr "@m(x,y) + z" -@test_repr "(@m(x,y),z)" -@test_repr "[@m(x,y),z]" -@test_repr "A[@m(x,y),z]" -@test_repr "T{@m(x,y),z}" -@test_repr "@m x @n(y) z" -@test_repr "f(@m(x,y);z=@n(a))" -@test_repr "@m(x,y).z" -@test_repr "::@m(x,y)+z" -@test_repr "[@m(x) y z]" -@test_repr "[@m(x) y; z]" -@test_repr "let @m(x), y=z; end" - -@test repr(:(@m x y)) == ":(@m x y)" -@test string(:(@m x y)) == "@m x y" -@test string(:(@m x y;)) == "begin \n @m x y\nend" - -# issue #11436 -@test_repr "1 => 2 => 3" -@test_repr "1 => (2 => 3)" -@test_repr "(1 => 2) => 3" - -# pr 12008 -@test_repr "primitive type A B end" -@test_repr "primitive type B 100 end" -@test repr(:(primitive type A B end)) == ":(primitive type A B end)" -@test repr(:(primitive type B 100 end)) == ":(primitive type B 100 end)" - -# `where` syntax -@test_repr "A where T<:B" -@test_repr "A where T<:(Array{T} where T<:Real)" -@test_repr "Array{T} where T<:Array{S} where S<:Real" -@test_repr "x::Array{T} where T" -@test_repr "(a::b) where T" -@test_repr "a::b where T" -@test_repr "X where (T=1)" -@test_repr "X where T = 1" - -let oldout = STDOUT, olderr = STDERR - local rdout, wrout, rderr, wrerr, out, err, rd, wr - try - # pr 16917 - rdout, wrout = redirect_stdout() - @test wrout === STDOUT - out = @async readstring(rdout) - rderr, wrerr = redirect_stderr() - @test wrerr === STDERR - err = @async readstring(rderr) - @test dump(Int64) === nothing - if !is_windows() - close(wrout) - close(wrerr) - end - - for io in (Core.STDOUT, Core.STDERR) - Core.println(io, "TESTA") - println(io, "TESTB") - print(io, 'Α', 1) - Core.print(io, 'Β', 2) - Core.show(io, "A") - println(io) - end - Core.println("A") - Core.print("1", 2, 3.0) - Core.show("C") - Core.println() - redirect_stdout(oldout) - redirect_stderr(olderr) - close(wrout) - close(wrerr) - @test wait(out) == "Int64 <: Signed\nTESTA\nTESTB\nΑ1Β2\"A\"\nA\n123\"C\"\n" - @test wait(err) == "TESTA\nTESTB\nΑ1Β2\"A\"\n" - finally - redirect_stdout(oldout) - redirect_stderr(olderr) - end -end - -let filename = tempname() - ret = open(filename, "w") do f - redirect_stdout(f) do - println("hello") - [1,3] - end - end - @test ret == [1,3] - @test chomp(readstring(filename)) == "hello" - ret = open(filename, "w") do f - redirect_stderr(f) do - warn("hello") - [2] - end - end - @test ret == [2] - @test contains(readstring(filename), "WARNING: hello") - ret = open(filename) do f - redirect_stdin(f) do - readline() - end - end - @test contains(ret, "WARNING: hello") - rm(filename) -end - -# issue #12960 -mutable struct T12960 end -let - A = speye(3) - B = similar(A, T12960) - @test sprint(show, B) == "\n [1, 1] = #undef\n [2, 2] = #undef\n [3, 3] = #undef" - @test sprint(print, B) == "\n [1, 1] = #undef\n [2, 2] = #undef\n [3, 3] = #undef" - B[1,2] = T12960() - @test sprint(show, B) == "\n [1, 1] = #undef\n [1, 2] = $(curmod_prefix)T12960()\n [2, 2] = #undef\n [3, 3] = #undef" - @test sprint(print, B) == "\n [1, 1] = #undef\n [1, 2] = $(curmod_prefix)T12960()\n [2, 2] = #undef\n [3, 3] = #undef" -end - -# issue #13127 -function f13127() - buf = IOBuffer() - f() = 1 - show(buf, f) - String(take!(buf)) -end -@test f13127() == "$(curmod_prefix)f" - -let a = Pair(1.0,2.0) - @test sprint(show,a) == "1.0=>2.0" -end -let a = Pair(Pair(1,2),Pair(3,4)) - @test sprint(show,a) == "(1=>2)=>(3=>4)" -end - -#test methodshow.jl functions -@test Base.inbase(Base) -@test Base.inbase(LinAlg) -@test !Base.inbase(Core) - -let repr = sprint(show, "text/plain", methods(Base.inbase)) - @test contains(repr, "inbase(m::Module)") -end -let repr = sprint(show, "text/html", methods(Base.inbase)) - @test contains(repr, "inbase(m::<b>Module</b>)") -end - -f5971(x, y...; z=1, w...) = nothing -let repr = sprint(show, "text/plain", methods(f5971)) - @test contains(repr, "f5971(x, y...; z, w...)") -end -let repr = sprint(show, "text/html", methods(f5971)) - @test contains(repr, "f5971(x, y...; <i>z, w...</i>)") -end -f16580(x, y...; z=1, w=y+x, q...) = nothing -let repr = sprint(show, "text/html", methods(f16580)) - @test contains(repr, "f16580(x, y...; <i>z, w, q...</i>)") -end - -if isempty(Base.GIT_VERSION_INFO.commit) - @test contains(Base.url(first(methods(eigs))),"https://github.com/JuliaLang/julia/tree/v$VERSION/base/linalg/arnoldi.jl#L") -else - @test contains(Base.url(first(methods(eigs))),"https://github.com/JuliaLang/julia/tree/$(Base.GIT_VERSION_INFO.commit)/base/linalg/arnoldi.jl#L") -end - -# print_matrix should be able to handle small and large objects easily, test by -# calling show. This also indirectly tests print_matrix_row, which -# is used repeatedly by print_matrix. -# This fits on screen: -@test replstr(eye(10)) == "10×10 Array{Float64,2}:\n 1.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0\n 0.0 1.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0\n 0.0 0.0 1.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0\n 0.0 0.0 0.0 1.0 0.0 0.0 0.0 0.0 0.0 0.0\n 0.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 0.0 0.0\n 0.0 0.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 0.0\n 0.0 0.0 0.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0\n 0.0 0.0 0.0 0.0 0.0 0.0 0.0 1.0 0.0 0.0\n 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 1.0 0.0\n 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 1.0" -# an array too long vertically to fit on screen, and too long horizontally: -@test replstr(collect(1.:100.)) == "100-element Array{Float64,1}:\n 1.0\n 2.0\n 3.0\n 4.0\n 5.0\n 6.0\n 7.0\n 8.0\n 9.0\n 10.0\n ⋮ \n 92.0\n 93.0\n 94.0\n 95.0\n 96.0\n 97.0\n 98.0\n 99.0\n 100.0" -@test replstr(collect(1.:100.)') == "1×100 RowVector{Float64,Array{Float64,1}}:\n 1.0 2.0 3.0 4.0 5.0 6.0 7.0 … 95.0 96.0 97.0 98.0 99.0 100.0" -# too big in both directions to fit on screen: -@test replstr((1.:100.)*(1:100)') == "100×100 Array{Float64,2}:\n 1.0 2.0 3.0 4.0 5.0 6.0 … 97.0 98.0 99.0 100.0\n 2.0 4.0 6.0 8.0 10.0 12.0 194.0 196.0 198.0 200.0\n 3.0 6.0 9.0 12.0 15.0 18.0 291.0 294.0 297.0 300.0\n 4.0 8.0 12.0 16.0 20.0 24.0 388.0 392.0 396.0 400.0\n 5.0 10.0 15.0 20.0 25.0 30.0 485.0 490.0 495.0 500.0\n 6.0 12.0 18.0 24.0 30.0 36.0 … 582.0 588.0 594.0 600.0\n 7.0 14.0 21.0 28.0 35.0 42.0 679.0 686.0 693.0 700.0\n 8.0 16.0 24.0 32.0 40.0 48.0 776.0 784.0 792.0 800.0\n 9.0 18.0 27.0 36.0 45.0 54.0 873.0 882.0 891.0 900.0\n 10.0 20.0 30.0 40.0 50.0 60.0 970.0 980.0 990.0 1000.0\n ⋮ ⋮ ⋱ \n 92.0 184.0 276.0 368.0 460.0 552.0 8924.0 9016.0 9108.0 9200.0\n 93.0 186.0 279.0 372.0 465.0 558.0 9021.0 9114.0 9207.0 9300.0\n 94.0 188.0 282.0 376.0 470.0 564.0 9118.0 9212.0 9306.0 9400.0\n 95.0 190.0 285.0 380.0 475.0 570.0 9215.0 9310.0 9405.0 9500.0\n 96.0 192.0 288.0 384.0 480.0 576.0 … 9312.0 9408.0 9504.0 9600.0\n 97.0 194.0 291.0 388.0 485.0 582.0 9409.0 9506.0 9603.0 9700.0\n 98.0 196.0 294.0 392.0 490.0 588.0 9506.0 9604.0 9702.0 9800.0\n 99.0 198.0 297.0 396.0 495.0 594.0 9603.0 9702.0 9801.0 9900.0\n 100.0 200.0 300.0 400.0 500.0 600.0 9700.0 9800.0 9900.0 10000.0" - -# Issue 14121 -@test_repr "(A'x)'" - - -# issue #14481 -@test_repr "in(1,2,3)" -@test_repr "<(1,2,3)" -@test_repr "+(1,2,3)" -@test_repr "-(1,2,3)" -@test_repr "*(1,2,3)" - - -# issue #15309 -l1, l2, l2n = Expr(:line,42), Expr(:line,42,:myfile), LineNumberNode(42) -@test string(l2n) == " # line 42:" -@test string(l2) == " # myfile, line 42:" -@test string(l1) == string(l2n) -ex = Expr(:block, l1, :x, l2, :y, l2n, :z) -@test replace(string(ex)," ","") == replace(""" -begin # line 42: - x # myfile, line 42: - y # line 42: - z -end""", " ", "") -# Test the printing of whatever form of line number representation -# that is used in the arguments to a macro looks the same as for -# regular quoting -macro strquote(ex) - QuoteNode(string(ex)) -end -str_ex2a, str_ex2b = @strquote(begin x end), string(quote x end) -@test str_ex2a == str_ex2b - - -# test structured zero matrix printing for select structured types -A = reshape(1:16,4,4) -@test replstr(Diagonal(A)) == "4×4 Diagonal{$Int}:\n 1 ⋅ ⋅ ⋅\n ⋅ 6 ⋅ ⋅\n ⋅ ⋅ 11 ⋅\n ⋅ ⋅ ⋅ 16" -@test replstr(Bidiagonal(A,true)) == "4×4 Bidiagonal{$Int}:\n 1 5 ⋅ ⋅\n ⋅ 6 10 ⋅\n ⋅ ⋅ 11 15\n ⋅ ⋅ ⋅ 16" -@test replstr(Bidiagonal(A,false)) == "4×4 Bidiagonal{$Int}:\n 1 ⋅ ⋅ ⋅\n 2 6 ⋅ ⋅\n ⋅ 7 11 ⋅\n ⋅ ⋅ 12 16" -@test replstr(SymTridiagonal(A+A')) == "4×4 SymTridiagonal{$Int}:\n 2 7 ⋅ ⋅\n 7 12 17 ⋅\n ⋅ 17 22 27\n ⋅ ⋅ 27 32" -@test replstr(Tridiagonal(diag(A,-1),diag(A),diag(A,+1))) == "4×4 Tridiagonal{$Int}:\n 1 5 ⋅ ⋅\n 2 6 10 ⋅\n ⋅ 7 11 15\n ⋅ ⋅ 12 16" -@test replstr(UpperTriangular(copy(A))) == "4×4 UpperTriangular{$Int,Array{$Int,2}}:\n 1 5 9 13\n ⋅ 6 10 14\n ⋅ ⋅ 11 15\n ⋅ ⋅ ⋅ 16" -@test replstr(LowerTriangular(copy(A))) == "4×4 LowerTriangular{$Int,Array{$Int,2}}:\n 1 ⋅ ⋅ ⋅\n 2 6 ⋅ ⋅\n 3 7 11 ⋅\n 4 8 12 16" - -# Vararg methods in method tables -function test_mt(f, str) - mt = methods(f) - @test length(mt) == 1 - defs = first(mt) - io = IOBuffer() - show(io, defs) - strio = String(take!(io)) - strio = split(strio, " at")[1] - @test strio[1:length(str)] == str -end -show_f1(x...) = [x...] -show_f2(x::Vararg{Any}) = [x...] -show_f3(x::Vararg) = [x...] -show_f4(x::Vararg{Any,3}) = [x...] -show_f5{T, N}(A::AbstractArray{T,N}, indexes::Vararg{Int,N}) = [indexes...] -test_mt(show_f1, "show_f1(x...)") -test_mt(show_f2, "show_f2(x...)") -test_mt(show_f3, "show_f3(x...)") -test_mt(show_f4, "show_f4(x::Vararg{Any,3})") -test_mt(show_f5, "show_f5(A::AbstractArray{T,N}, indexes::Vararg{$Int,N})") - -# Issue #15525, printing of vcat -@test sprint(show, :([a;])) == ":([a;])" -@test sprint(show, :([a; b])) == ":([a; b])" -@test_repr "[a;]" -@test_repr "[a; b]" - -# Printing of :(function f end) -@test sprint(show, :(function f end)) == ":(function f end)" -@test_repr "function g end" - -# Issue #15765 printing of continue and break -@test sprint(show, :(continue)) == ":(continue)" -@test sprint(show, :(break)) == ":(break)" -@test_repr "continue" -@test_repr "break" - -let x = [], y = [] - push!(x, y) - push!(y, x) - @test replstr(x) == "1-element Array{Any,1}:\n Any[Any[Any[#= circular reference @-2 =#]]]" -end - -# PR 16221 -# Printing of upper and lower bound of a TypeVar -@test string(TypeVar(:V, Signed, Real)) == "Signed<:V<:Real" -# Printing of primary type in type parameter place should not show the type -# parameter names. -@test string(Array) == "Array" -@test string(Tuple{Array}) == "Tuple{Array}" - -# PR #16651 -@test !contains(repr(ones(10,10)), "\u2026") -@test contains(sprint((io, x) -> show(IOContext(io, :limit => true), x), ones(30, 30)), "\u2026") - -# showcompact() also sets :multiline=>false (#16817) -let io = IOBuffer() - x = [1, 2] - showcompact(io, x) - @test String(take!(io)) == "[1, 2]" - showcompact(IOContext(io, :compact => true), x) - @test String(take!(io)) == "[1, 2]" -end - -let io = IOBuffer() - ioc = IOContext(io, :limit => true) - @test sprint(show, ioc) == "IOContext($(sprint(show, ioc.io)))" -end - -# PR 17117 -# test show array -let s = IOBuffer(Array{UInt8}(0), true, true) - Base.showarray(s, [1, 2, 3], false, header = false) - @test String(resize!(s.data, s.size)) == " 1\n 2\n 3" -end - -let repr = sprint(dump, :(x = 1)) - @test repr == "Expr\n head: Symbol =\n args: Array{Any}((2,))\n 1: Symbol x\n 2: $Int 1\n typ: Any\n" -end -let repr = sprint(dump, Pair{String,Int64}) - @test repr == "Pair{String,Int64} <: Any\n first::String\n second::Int64\n" -end -let repr = sprint(dump, Tuple) - @test repr == "Tuple <: Any\n" -end -let repr = sprint(dump, Int64) - @test repr == "Int64 <: Signed\n" -end -# Make sure a `TypeVar` in a `Union` doesn't break subtype dump. -BreakDump17529{T} = Union{T, Void} -# make sure dependent parameters are represented correctly -VectorVI{I, VI<:AbstractVector{I}} = Vector{VI} -let repr = sprint(dump, Any) - @test length(repr) > 100000 - @test ismatch(r"^Any\n [^ \t\n]", repr) - @test endswith(repr, '\n') - @test contains(repr, " Base.Vector{T} = Array{T,1}\n") - @test contains(repr, ".VectorVI{I, VI<:AbstractArray{I,1}} = Array{VI,1}\n") - @test !contains(repr, "Core.Vector{T}") -end -let repr = sprint(dump, Integer) - @test contains(repr, "UInt128") - @test !contains(repr, "Any") -end -let repr = sprint(dump, Union{Integer, Float32}) - @test repr == "Union{Integer, Float32}\n" || repr == "Union{Float32, Integer}\n" -end -let repr = sprint(dump, Core.svec()) - @test repr == "empty SimpleVector\n" -end -let sv = Core.svec(:a, :b, :c) - # unsafe replacement of :c with #undef to test handling of incomplete SimpleVectors - unsafe_store!(convert(Ptr{Ptr{Void}}, Base.data_pointer_from_objref(sv)) + 3 * sizeof(Ptr), C_NULL) - repr = sprint(dump, sv) - @test repr == "SimpleVector\n 1: Symbol a\n 2: Symbol b\n 3: #undef\n" -end -let repr = sprint(dump, sin) - @test repr == "sin (function of type Base.#sin)\n" -end -let repr = sprint(dump, Base.Test) - @test repr == "Module Base.Test\n" -end -let a = Array{Any}(10000) - a[2] = "elemA" - a[4] = "elemB" - a[11] = "elemC" - repr = sprint(0, dump, a; env= (:limit => true)) - @test repr == "Array{Any}((10000,))\n 1: #undef\n 2: String \"elemA\"\n 3: #undef\n 4: String \"elemB\"\n 5: #undef\n ...\n 9996: #undef\n 9997: #undef\n 9998: #undef\n 9999: #undef\n 10000: #undef\n" -end - -# issue #17338 -@test repr(Core.svec(1, 2)) == "svec(1, 2)" - -# showing generator and comprehension expressions -@test repr(:(x for x in y for z in w)) == ":((x for x = y for z = w))" -@test repr(:(x for x in y if aa for z in w if bb)) == ":((x for x = y if aa for z = w if bb))" -@test repr(:([x for x = y])) == ":([x for x = y])" -@test repr(:([x for x = y if z])) == ":([x for x = y if z])" -@test repr(:(z for z = 1:5, y = 1:5)) == ":((z for z = 1:5, y = 1:5))" -@test_repr "(x for i in a, b in c)" -@test_repr "(x for a in b, c in d for e in f)" - -for op in (:(.=), :(.+=), :(.&=)) - @test repr(parse("x $op y")) == ":(x $op y)" -end - -# pretty-printing of compact broadcast expressions (#17289) -@test repr(:(f.(X, Y))) == ":(f.(X, Y))" -@test repr(:(f.(X))) == ":(f.(X))" -@test repr(:(f.())) == ":(f.())" - -# Test compact printing of homogeneous tuples -@test repr(NTuple{7,Int64}) == "NTuple{7,Int64}" -@test repr(Tuple{Float64, Float64, Float64, Float64}) == "NTuple{4,Float64}" -@test repr(Tuple{Float32, Float32, Float32}) == "Tuple{Float32,Float32,Float32}" - -# Test that REPL/mime display of invalid UTF-8 data doesn't throw an exception: -@test isa(stringmime("text/plain", String(UInt8[0x00:0xff;])), String) - -# don't use julia-specific `f` in Float32 printing (PR #18053) -@test sprint(print, 1f-7) == "1.0e-7" - -# test that the REPL TextDisplay works for displaying arbitrary textual MIME types -let d = TextDisplay(IOBuffer()) - display(d, "text/csv", [3 1 4]) - @test String(take!(d.io)) == "3,1,4\n" - @test_throws MethodError display(d, "text/foobar", [3 1 4]) - try - display(d, "text/foobar", [3 1 4]) - catch e - @test e.f == show - end -end - -struct TypeWith4Params{a,b,c,d} -end -@test endswith(string(TypeWith4Params{Int8,Int8,Int8,Int8}), "TypeWith4Params{Int8,Int8,Int8,Int8}") - -# issues #20332 and #20781 -struct T20332{T} -end - -(::T20332{T})(x) where T = 0 - -let m = which(T20332{Int}(), (Int,)), - mi = ccall(:jl_specializations_get_linfo, Ref{Core.MethodInstance}, (Any, Any, Any, UInt), - m, Tuple{T20332{T}, Int} where T, Core.svec(), typemax(UInt)) - # test that this doesn't throw an error - @test contains(repr(mi), "MethodInstance for") -end - -@test sprint(show, Main) == "Main" - -struct f_with_params{t} <: Function -end - -(::f_with_params)(x) = 2x - -let io = IOBuffer() - show(io, MIME"text/html"(), f_with_params.body.name.mt) - @test contains(String(take!(io)), "f_with_params") -end diff --git a/julia-0.6.3/share/julia/test/simdloop.jl b/julia-0.6.3/share/julia/test/simdloop.jl deleted file mode 100644 index 57be1d5..0000000 --- a/julia-0.6.3/share/julia/test/simdloop.jl +++ /dev/null @@ -1,139 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -function simd_loop_example_from_manual(x, y, z) - s = zero(eltype(z)) - n = min(length(x),length(y),length(z)) - @simd for i in 1:n - @inbounds begin - z[i] = x[i]-y[i] - s += z[i]*z[i] - end - end - s -end - -function simd_loop_with_multiple_reductions(x, y, z) - # Use non-zero initial value to make sure reduction values include it. - (s,t) = (one(eltype(x)),one(eltype(y))) - @simd for i in 1:length(z) - @inbounds begin - s += x[i] - t += 2*y[i] - s += z[i] # Two reductions go into s - end - end - (s,t) -end - -for T in [Int32,Int64,Float32,Float64] - # Try various lengths to make sure "remainder loop" works - for n in [0,1,2,3,4,255,256,257] - # Dataset chosen so that results will be exact with only 24 bits of mantissa - a = convert(Array{T},[2*j+1 for j in 1:n]) - b = convert(Array{T},[3*j+2 for j in 1:n]) - c = convert(Array{T},[5*j+3 for j in 1:n]) - s = simd_loop_example_from_manual(a,b,c) - - @test a==[2*j+1 for j in 1:n] - @test b==[3*j+2 for j in 1:n] - @test c==[-j-1 for j in 1:n] - @test s==sum(c.*c) - (s,t) = simd_loop_with_multiple_reductions(a,b,c) - @test s==sum(a)+sum(c)+1 - @test t==2*sum(b)+1 - end -end - -# Test that scope rules match regular for -let j=4 - # Use existing local variable. - @simd for j=1:0 end - @test j==4 - @simd for j=1:3 end - @test j==3 - - # Use global variable - global simd_glob = 4 - @simd for simd_glob=1:0 end - @test simd_glob==4 - @simd for simd_glob=1:3 end - @test simd_glob==3 - - # Index that is local to loop - @simd for simd_loop_local=1:0 end - simd_loop_local_present = true - try - simd_loop_local += 1 - catch - simd_loop_local_present = false - end - @test !simd_loop_local_present -end - -import Base.SimdLoop.SimdError - -# Test that @simd rejects inner loop body with invalid control flow statements -# issue #8613 -@test_throws SimdError eval(:(begin - @simd for x = 1:10 - x == 1 && break - end -end)) - -@test_throws SimdError eval(:(begin - @simd for x = 1:10 - x < 5 && continue - end -end)) - -@test_throws SimdError eval(:(begin - @simd for x = 1:10 - x == 1 || @goto exit_loop - end - @label exit_loop -end)) - -# @simd with cartesian iteration -function simd_cartesian_range!(indexes, crng) - @simd for I in crng - push!(indexes, I) - end - indexes -end - -crng = CartesianRange(CartesianIndex{4}(2,0,1,3), - CartesianIndex{4}(4,1,1,5)) -indexes = simd_cartesian_range!(Array{eltype(crng)}(0), crng) -@test indexes == vec(collect(crng)) - -crng = CartesianRange(CartesianIndex{2}(-1,1), - CartesianIndex{2}(1,3)) -indexes = simd_cartesian_range!(Array{eltype(crng)}(0), crng) -@test indexes == vec(collect(crng)) - -crng = CartesianRange(CartesianIndex{2}(-1,1), - CartesianIndex{2}(-1,3)) -indexes = simd_cartesian_range!(Array{eltype(crng)}(0), crng) -@test indexes == vec(collect(crng)) - -crng = CartesianRange(CartesianIndex{1}(2), - CartesianIndex{1}(4)) -indexes = simd_cartesian_range!(Array{eltype(crng)}(0), crng) -@test indexes == collect(crng) - -crng = CartesianRange(CartesianIndex{0}(), - CartesianIndex{0}()) -indexes = simd_cartesian_range!(Array{eltype(crng)}(0), crng) -@test indexes == vec(collect(crng)) - -# @simd with array as "range" -# issue #13869 -function simd_sum_over_array(a) - s = zero(eltype(a)) - @inbounds @simd for x in a - s += x - end - s -end -@test 2001000 == simd_sum_over_array(collect(1:2000)) -@test 2001000 == simd_sum_over_array(Float32[i+j*500 for i=1:500, j=0:3]) diff --git a/julia-0.6.3/share/julia/test/socket.jl b/julia-0.6.3/share/julia/test/socket.jl deleted file mode 100644 index 7e9a05b..0000000 --- a/julia-0.6.3/share/julia/test/socket.jl +++ /dev/null @@ -1,382 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -@test ip"127.0.0.1" == IPv4(127,0,0,1) -@test ip"192.0" == IPv4(192,0,0,0) - -# These used to work, but are now disallowed. Check that they error -@test_throws ArgumentError parse(IPv4, "192.0xFFF") # IPv4(192,0,15,255) -@test_throws ArgumentError parse(IPv4, "192.0xFFFF") # IPv4(192,0,255,255) -@test_throws ArgumentError parse(IPv4, "192.0xFFFFF") # IPv4(192,15,255,255) -@test_throws ArgumentError parse(IPv4, "192.0xFFFFFF") # IPv4(192,255,255,255) -@test_throws ArgumentError parse(IPv4, "022.0.0.1") # IPv4(18,0,0,1) - -@test UInt(IPv4(0x01020304)) == 0x01020304 -@test Int(IPv4("1.2.3.4")) == Int(0x01020304) == Int32(0x01020304) -@test Int128(IPv6("2001:1::2")) == 42540488241204005274814694018844196866 -@test_throws InexactError Int16(IPv4("1.2.3.4")) -@test_throws InexactError Int64(IPv6("2001:1::2")) - -let ipv = parse(IPAddr, "127.0.0.1") - @test isa(ipv, IPv4) - @test ipv == ip"127.0.0.1" -end - -@test_throws ArgumentError parse(IPv4, "192.0xFFFFFFF") -@test_throws ArgumentError IPv4(192,255,255,-1) -@test_throws ArgumentError IPv4(192,255,255,256) - -@test_throws ArgumentError parse(IPv4, "192.0xFFFFFFFFF") -@test_throws ArgumentError parse(IPv4, "192.") - -@test ip"::1" == IPv6(1) -@test ip"2605:2700:0:3::4713:93e3" == IPv6(parse(UInt128,"260527000000000300000000471393e3",16)) - -@test ip"2001:db8:0:0:0:0:2:1" == ip"2001:db8::2:1" == ip"2001:db8::0:2:1" - -@test ip"0:0:0:0:0:ffff:127.0.0.1" == IPv6(0xffff7f000001) - -let ipv = parse(IPAddr, "0:0:0:0:0:ffff:127.0.0.1") - @test isa(ipv, IPv6) - @test ipv == ip"0:0:0:0:0:ffff:127.0.0.1" -end - -@test_throws ArgumentError IPv6(1,1,1,1,1,1,1,-1) -@test_throws ArgumentError IPv6(1,1,1,1,1,1,1,typemax(UInt16)+1) - -# test InetAddr constructor -let inet = Base.InetAddr(IPv4(127,0,0,1), 1024) - @test inet.host == ip"127.0.0.1" - @test inet.port == 1024 -end -# test InetAddr invalid port -@test_throws InexactError Base.InetAddr(IPv4(127,0,0,1), -1) -@test_throws InexactError Base.InetAddr(IPv4(127,0,0,1), typemax(UInt16)+1) - -# isless and comparisons -@test ip"1.2.3.4" < ip"1.2.3.7" < ip"2.3.4.5" -@test ip"1.2.3.4" >= ip"1.2.3.4" >= ip"1.2.3.1" -@test isless(ip"1.2.3.4", ip"1.2.3.5") -@test_throws MethodError sort[ip"2.3.4.5", ip"1.2.3.4", ip"2001:1:2::1"] - -# RFC 5952 Compliance - -@test repr(ip"2001:db8:0:0:0:0:2:1") == "ip\"2001:db8::2:1\"" -@test repr(ip"2001:0db8::0001") == "ip\"2001:db8::1\"" -@test repr(ip"2001:db8::1:1:1:1:1") == "ip\"2001:db8:0:1:1:1:1:1\"" -@test repr(ip"2001:db8:0:0:1:0:0:1") == "ip\"2001:db8::1:0:0:1\"" -@test repr(ip"2001:0:0:1:0:0:0:1") == "ip\"2001:0:0:1::1\"" - -# test show() function for UDPSocket() -@test repr(UDPSocket()) == "UDPSocket(init)" - -defaultport = rand(2000:4000) -for testport in [0, defaultport] - port = Channel(1) - tsk = @async begin - p, s = listenany(testport) - put!(port, p) - sock = accept(s) - # test write call - write(sock,"Hello World\n") - - # test "locked" println to a socket - @sync begin - for i in 1:100 - @async println(sock, "a", 1) - end - end - close(s) - close(sock) - end - wait(port) - @test readstring(connect(fetch(port))) == "Hello World\n" * ("a1\n"^100) - wait(tsk) -end - -mktempdir() do tmpdir - socketname = is_windows() ? ("\\\\.\\pipe\\uv-test-" * randstring(6)) : joinpath(tmpdir, "socket") - c = Base.Condition() - tsk = @async begin - s = listen(socketname) - Base.notify(c) - sock = accept(s) - write(sock,"Hello World\n") - close(s) - close(sock) - end - wait(c) - @test readstring(connect(socketname)) == "Hello World\n" - wait(tsk) -end - -@test_throws Base.DNSError getaddrinfo(".invalid") -@test_throws ArgumentError getaddrinfo("localhost\0") # issue #10994 -@test_throws Base.UVError connect("localhost", 21452) - -# test invalid port -@test_throws ArgumentError connect(ip"127.0.0.1",-1) -@test_throws ArgumentError connect(ip"127.0.0.1", typemax(UInt16)+1) -@test_throws ArgumentError connect(ip"0:0:0:0:0:ffff:127.0.0.1", -1) -@test_throws ArgumentError connect(ip"0:0:0:0:0:ffff:127.0.0.1", typemax(UInt16)+1) - -p, server = listenany(defaultport) -r = Channel(1) -tsk = @async begin - put!(r, :start) - @test_throws Base.UVError accept(server) -end -@test fetch(r) === :start -close(server) -wait(tsk) - -port, server = listenany(defaultport) -@async connect("localhost",port) -s1 = accept(server) -@test_throws ErrorException accept(server,s1) -@test_throws Base.UVError listen(port) -port2, server2 = listenany(port) -@test port != port2 -close(server) -close(server2) - -@test_throws Base.DNSError connect(".invalid",80) - -begin - a = UDPSocket() - b = UDPSocket() - bind(a, ip"127.0.0.1", port) - bind(b, ip"127.0.0.1", port + 1) - - c = Condition() - tsk = @async begin - @test String(recv(a)) == "Hello World" - # Issue 6505 - tsk2 = @async begin - @test String(recv(a)) == "Hello World" - notify(c) - end - send(b, ip"127.0.0.1", port, "Hello World") - wait(tsk2) - end - send(b, ip"127.0.0.1", port, "Hello World") - wait(c) - wait(tsk) - - tsk = @async begin - @test begin - (addr,data) = recvfrom(a) - addr == ip"127.0.0.1" && String(data) == "Hello World" - end - end - send(b, ip"127.0.0.1", port, "Hello World") - wait(tsk) - - @test_throws MethodError bind(UDPSocket(),port) - - close(a) - close(b) -end -if !is_windows() || Sys.windows_version() >= Sys.WINDOWS_VISTA_VER - a = UDPSocket() - b = UDPSocket() - bind(a, ip"::1", UInt16(port)) - bind(b, ip"::1", UInt16(port+1)) - - tsk = @async begin - @test begin - (addr, data) = recvfrom(a) - addr == ip"::1" && String(data) == "Hello World" - end - end - send(b, ip"::1", port, "Hello World") - wait(tsk) -end - -begin - default_port = UInt16(11011) - default_addr = IPv4("127.0.0.1") - - sock = Base.TCPServer() - bind(sock,Base.InetAddr(default_addr,default_port)) - listen(sock) - - new_addr, new_port = getsockname(sock) - - @test default_addr == new_addr - @test default_port == new_port - close(sock) -end - -begin - default_port = UInt16(21011) - default_addr = IPv6("::1") - - sock = Base.TCPServer() - addr = Base.InetAddr(default_addr,default_port) - bind(sock,addr) - listen(sock) - - new_addr, new_port = getsockname(sock) - - @test default_addr == new_addr - @test default_port == new_port - close(sock) -end - -begin - default_port = UInt16(11011) - default_addr = getipaddr() - - sock = Base.TCPServer() - bind(sock,Base.InetAddr(default_addr,default_port)) - listen(sock) - - @async begin - sleep(1) - ssock = connect(default_addr, default_port) - end - - csock = accept(sock) - new_addr, new_port = getsockname(csock) - - @test default_addr == new_addr - @test new_port > 0 - close(csock) - close(sock) -end - -# Local-machine broadcast -let - # (Mac OS X's loopback interface doesn't support broadcasts) - bcastdst = is_apple() ? ip"255.255.255.255" : ip"127.255.255.255" - - function create_socket() - s = UDPSocket() - bind(s, ip"0.0.0.0", 2000, reuseaddr = true, enable_broadcast = true) - s - end - - function wait_with_timeout(recvs) - TIMEOUT_VAL = 3 # seconds - t0 = time() - recvs_check = copy(recvs) - while ((length(filter!(t->!istaskdone(t), recvs_check)) > 0) - && (time() - t0 < TIMEOUT_VAL)) - sleep(0.05) - end - length(recvs_check) > 0 && error("timeout") - map(wait, recvs) - end - - a, b, c = [create_socket() for i = 1:3] - try - # bsd family do not allow broadcasting to ip"255.255.255.255" - # or ip"127.255.255.255" - @static if !is_bsd() || is_apple() - send(c, bcastdst, 2000, "hello") - recvs = [@async @test String(recv(s)) == "hello" for s in (a, b)] - wait_with_timeout(recvs) - end - catch e - if isa(e, Base.UVError) && Base.uverrorname(e) == "EPERM" - warn("UDP broadcast test skipped (permission denied upon send, restrictive firewall?)") - else - rethrow() - end - end - [close(s) for s in [a, b, c]] -end - -let P = Pipe() - Base.link_pipe(P) - write(P, "hello") - @test nb_available(P) == 0 - @test !eof(P) - @test read(P, Char) === 'h' - @test !eof(P) - @test read(P, Char) === 'e' - @test isopen(P) - t = @async begin - # feed uv_read one more event so that it triggers the transition from active -> open - write(P, "w") - while P.out.status != Base.StatusOpen - yield() # wait for that transition - end - close(P.in) - end - # on unix, this proves that the kernel can buffer a single byte - # even with no registered active call to read - # on windows, the kernel fails to do even that - # causing the `write` call to freeze - # so we end up forced to do a slightly weaker test here - is_windows() || wait(t) - @test isopen(P) # without an active uv_reader, P shouldn't be closed yet - @test !eof(P) # should already know this, - @test isopen(P) # so it still shouldn't have an active uv_reader - @test readuntil(P, 'w') == "llow" - is_windows() && wait(t) - @test eof(P) - @test !isopen(P) # eof test should have closed this by now - close(P) # should be a no-op, just make sure - @test !isopen(P) - @test eof(P) -end - -# test the method matching connect!(::TCPSocket, ::Base.InetAddr{T<:Base.IPAddr}) -let - addr = Base.InetAddr(ip"127.0.0.1", 4444) - - function test_connect(addr::Base.InetAddr) - srv = listen(addr) - - @async try c = accept(srv); close(c) catch end - yield() - - t0 = TCPSocket() - t = t0 - @assert t === t0 - - try - t = connect(addr) - finally - close(srv) - end - - test = t !== t0 - close(t) - - return test - end - - @test test_connect(addr) -end - -# Issues #18818 and #24169 -mutable struct RLimit - cur::Int64 - max::Int64 -end -function with_ulimit(f::Function, stacksize::Int) - RLIMIT_STACK = 3 # from /usr/include/sys/resource.h - rlim = Ref(RLimit(0, 0)) - # Get the current maximum stack size in bytes - rc = ccall(:getrlimit, Cint, (Cint, Ref{RLimit}), RLIMIT_STACK, rlim) - @assert rc == 0 - current = rlim[].cur - try - rlim[].cur = stacksize * 1024 - ccall(:setrlimit, Cint, (Cint, Ref{RLimit}), RLIMIT_STACK, rlim) - f() - finally - rlim[].cur = current - ccall(:setrlimit, Cint, (Cint, Ref{RLimit}), RLIMIT_STACK, rlim) - end - nothing -end -@static if is_apple() - @testset "Issues #18818 and #24169" begin - with_ulimit(7001) do - @test getaddrinfo("localhost") isa IPAddr - end - end -end diff --git a/julia-0.6.3/share/julia/test/sorting.jl b/julia-0.6.3/share/julia/test/sorting.jl deleted file mode 100644 index 28d7020..0000000 --- a/julia-0.6.3/share/julia/test/sorting.jl +++ /dev/null @@ -1,361 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -using Base.Order: Forward - -@test sort([2,3,1]) == [1,2,3] -@test sort([2,3,1], rev=true) == [3,2,1] -@test sort(['z':-1:'a';]) == ['a':'z';] -@test sort(['a':'z';], rev=true) == ['z':-1:'a';] -@test sortperm([2,3,1]) == [3,1,2] -@test sortperm!([1,2,3], [2,3,1]) == [3,1,2] -let s = view([1,2,3,4], 1:3) - r = sortperm!(s, [2,3,1]) - @test r == [3,1,2] - @test r === s -end -@test_throws ArgumentError sortperm!(view([1,2,3,4], 1:4), [2,3,1]) -@test !issorted([2,3,1]) -@test issorted([1,2,3]) -@test reverse([2,3,1]) == [1,3,2] -@test select([3,6,30,1,9],3) == 6 -@test select([3,6,30,1,9],3:4) == [6,9] -@test selectperm([3,6,30,1,9], 3:4) == [2,5] -@test selectperm!(collect(1:5), [3,6,30,1,9], 3:4) == [2,5] -let a=[1:10;] - for r in Any[2:4, 1:2, 10:10, 4:2, 2:1, 4:-1:2, 2:-1:1, 10:-1:10, 4:1:3, 1:2:8, 10:-3:1] - @test select(a, r) == [r;] - @test selectperm(a, r) == [r;] - @test select(a, r, rev=true) == (11 .- [r;]) - @test selectperm(a, r, rev=true) == (11 .- [r;]) - end -end -@test sum(randperm(6)) == 21 - -numTypes = [ Int8, Int16, Int32, Int64, Int128, - UInt8, UInt16, UInt32, UInt64, UInt128, - Float16, Float32, Float64, BigInt, BigFloat] - -@test searchsorted([1:10;], 1, by=(x -> x >= 5)) == 1:4 -@test searchsorted([1:10;], 10, by=(x -> x >= 5)) == 5:10 -@test searchsorted([1:5; 1:5; 1:5], 1, 6, 10, Forward) == 6:6 -@test searchsorted(ones(15), 1, 6, 10, Forward) == 6:10 - -for R in numTypes, T in numTypes - @test searchsorted(R[1, 1, 2, 2, 3, 3], T(0)) == 1:0 - @test searchsorted(R[1, 1, 2, 2, 3, 3], T(1)) == 1:2 - @test searchsorted(R[1, 1, 2, 2, 3, 3], T(2)) == 3:4 - @test searchsorted(R[1, 1, 2, 2, 3, 3], T(4)) == 7:6 - @test searchsorted(R[1, 1, 2, 2, 3, 3], 2.5) == 5:4 - - @test searchsorted(1:3, T(0)) == 1:0 - @test searchsorted(1:3, T(1)) == 1:1 - @test searchsorted(1:3, T(2)) == 2:2 - @test searchsorted(1:3, T(4)) == 4:3 - - @test searchsorted(R[1:10;], T(1), by=(x -> x >= 5)) == 1:4 - @test searchsorted(R[1:10;], T(10), by=(x -> x >= 5)) == 5:10 - @test searchsorted(R[1:5; 1:5; 1:5], T(1), 6, 10, Forward) == 6:6 - @test searchsorted(ones(R, 15), T(1), 6, 10, Forward) == 6:10 -end - -for (rg,I) in [(49:57,47:59), (1:2:17,-1:19), (-3:0.5:2,-5:.5:4)] - rg_r = reverse(rg) - rgv, rgv_r = [rg;], [rg_r;] - for i = I - @test searchsorted(rg,i) == searchsorted(rgv,i) - @test searchsorted(rg_r,i,rev=true) == searchsorted(rgv_r,i,rev=true) - end -end - -rg = 0.0:0.01:1.0 -for i = 2:101 - @test searchsorted(rg, rg[i]) == i:i - @test searchsorted(rg, prevfloat(rg[i])) == i:i-1 - @test searchsorted(rg, nextfloat(rg[i])) == i+1:i -end - -rg_r = reverse(rg) -for i = 1:100 - @test searchsorted(rg_r, rg_r[i], rev=true) == i:i - @test searchsorted(rg_r, prevfloat(rg_r[i]), rev=true) == i+1:i - @test searchsorted(rg_r, nextfloat(rg_r[i]), rev=true) == i:i-1 -end - -@test searchsorted(1:10, 1, by=(x -> x >= 5)) == searchsorted([1:10;], 1, by=(x -> x >= 5)) -@test searchsorted(1:10, 10, by=(x -> x >= 5)) == searchsorted([1:10;], 10, by=(x -> x >= 5)) - -@test searchsorted([], 0) == 1:0 -@test searchsorted([1,2,3], 0) == 1:0 -@test searchsorted([1,2,3], 4) == 4:3 - -# issue 8866 -@test searchsortedfirst(500:1.0:600, -1.0e20) == 1 -@test searchsortedfirst(500:1.0:600, 1.0e20) == 102 -@test searchsortedlast(500:1.0:600, -1.0e20) == 0 -@test searchsortedlast(500:1.0:600, 1.0e20) == 101 - -# exercise the codepath in searchsorted* methods for ranges that check for zero step range -struct ConstantRange{T} <: Range{T} - val::T - len::Int -end - -Base.length(r::ConstantRange) = r.len -Base.getindex(r::ConstantRange, i::Int) = (1 <= i <= r.len || throw(BoundsError(r,i)); r.val) -Base.step(r::ConstantRange) = 0 - -r = ConstantRange(1, 5) - -@test searchsortedfirst(r, 1.0, Forward) == 1 -@test searchsortedfirst(r, 1, Forward) == 1 -@test searchsortedfirst(r, UInt(1), Forward) == 1 - -@test searchsortedlast(r, 1.0, Forward) == 5 -@test searchsortedlast(r, 1, Forward) == 5 -@test searchsortedlast(r, UInt(1), Forward) == 5 - -a = rand(1:10000, 1000) - -for alg in [InsertionSort, MergeSort] - b = sort(a, alg=alg) - @test issorted(b) - - ix = sortperm(a, alg=alg) - b = a[ix] - @test issorted(b) - @test a[ix] == b - - sortperm!(view(ix, 1:100), view(a, 1:100), alg=alg) - b = a[ix][1:100] - @test issorted(b) - - sortperm!(ix, a, alg=alg) - b = a[ix] - @test issorted(b) - @test a[ix] == b - - b = sort(a, alg=alg, rev=true) - @test issorted(b, rev=true) - ix = sortperm(a, alg=alg, rev=true) - b = a[ix] - @test issorted(b, rev=true) - @test a[ix] == b - - sortperm!(view(ix, 1:100), view(a, 1:100), alg=alg, rev=true) - b = a[ix][1:100] - @test issorted(b, rev=true) - - sortperm!(ix, a, alg=alg, rev=true) - b = a[ix] - @test issorted(b, rev=true) - @test a[ix] == b - - b = sort(a, alg=alg, by=x->1/x) - @test issorted(b, by=x->1/x) - ix = sortperm(a, alg=alg, by=x->1/x) - b = a[ix] - @test issorted(b, by=x->1/x) - @test a[ix] == b - - sortperm!(view(ix, 1:100), view(a, 1:100), by=x->1/x) - b = a[ix][1:100] - @test issorted(b, by=x->1/x) - - sortperm!(ix, a, alg=alg, by=x->1/x) - b = a[ix] - @test issorted(b, by=x->1/x) - @test a[ix] == b - - c = copy(a) - permute!(c, ix) - @test c == b - - ipermute!(c, ix) - @test c == a - - c = sort(a, alg=alg, lt=(>)) - @test b == c - - c = sort(a, alg=alg, by=x->1/x) - @test b == c -end - -# unstable algorithms -for alg in [QuickSort, PartialQuickSort(length(a))] - b = sort(a, alg=alg) - @test issorted(b) - b = sort(a, alg=alg, rev=true) - @test issorted(b, rev=true) - b = sort(a, alg=alg, by=x->1/x) - @test issorted(b, by=x->1/x) -end - -# test PartialQuickSort only does a partial sort -let alg = PartialQuickSort(div(length(a), 10)) - k = alg.k - b = sort(a, alg=alg) - c = sort(a, alg=alg, by=x->1/x) - d = sort(a, alg=alg, rev=true) - @test issorted(b[1:k]) - @test issorted(c[1:k], by=x->1/x) - @test issorted(d[1:k], rev=true) - @test !issorted(b) - @test !issorted(c, by=x->1/x) - @test !issorted(d, rev=true) -end - -@test select([3,6,30,1,9], 2, rev=true) == 9 -@test select([3,6,30,1,9], 2, by=x->1/x) == 9 -@test selectperm([3,6,30,1,9], 2, rev=true) == 5 -@test selectperm([3,6,30,1,9], 2, by=x->1/x) == 5 - -## more advanced sorting tests ## - -randnans(n) = reinterpret(Float64,[rand(UInt64)|0x7ff8000000000000 for i=1:n]) - -function randn_with_nans(n,p) - v = randn(n) - x = find(rand(n).<p) - v[x] = randnans(length(x)) - return v -end - -srand(0xdeadbeef) - -for n in [0:10; 100; 101; 1000; 1001] - r = -5:5 - v = rand(r,n) - h = [sum(v .== x) for x in r] - - for rev in [false,true] - # insertion sort (stable) as reference - pi = sortperm(v, alg=InsertionSort, rev=rev) - @test pi == sortperm(float(v), alg=InsertionSort, rev=rev) - @test isperm(pi) - si = v[pi] - @test [sum(si .== x) for x in r] == h - @test issorted(si, rev=rev) - @test all(issorted,[pi[si.==x] for x in r]) - c = copy(v) - permute!(c, pi) - @test c == si - ipermute!(c, pi) - @test c == v - - # stable algorithms - for alg in [MergeSort] - p = sortperm(v, alg=alg, rev=rev) - @test p == sortperm(float(v), alg=alg, rev=rev) - @test p == pi - s = copy(v) - permute!(s, p) - @test s == si - ipermute!(s, p) - @test s == v - end - - # unstable algorithms - for alg in [QuickSort, PartialQuickSort(n)] - p = sortperm(v, alg=alg, rev=rev) - @test p == sortperm(float(v), alg=alg, rev=rev) - @test isperm(p) - @test v[p] == si - s = copy(v) - permute!(s, p) - @test s == si - ipermute!(s, p) - @test s == v - end - end - - v = randn_with_nans(n,0.1) - # TODO: alg = PartialQuickSort(n) fails here - for alg in [InsertionSort, QuickSort, MergeSort], - rev in [false,true] - # test float sorting with NaNs - s = sort(v, alg=alg, rev=rev) - @test issorted(s, rev=rev) - @test reinterpret(UInt64,v[isnan.(v)]) == reinterpret(UInt64,s[isnan.(s)]) - - # test float permutation with NaNs - p = sortperm(v, alg=alg, rev=rev) - @test isperm(p) - vp = v[p] - @test isequal(vp,s) - @test reinterpret(UInt64,vp) == reinterpret(UInt64,s) - end -end - -inds = [ - 1,1,1,2,2,2,3,3,3,4,4,4,5,5,5,6,6,6,7,7,7,8,8,8,9,9,9,10, - 10,10,11,11,11,12,12,12,13,13,13,14,14,14,15,15,15,16,16, - 16,17,17,17,18,18,18,19,19,19,20,20,20,21,21,22,22,22,23, - 23,24,24,24,25,25,25,26,26,26,27,27,27,28,28,28,29,29,29, - 30,30,30,31,31,32,32,32,33,33,33,34,34,34,35,35,35,36,36, - 36,37,37,37,38,38,38,39,39,39,40,40,40,41,41,41,42,42,42, - 43,43,43,44,44,44,45,45,45,46,46,46,47,47,47,48,48,48,49, - 49,49,50,50,50,51,51,52,52,52,53,53,53,54,54,54,55,55,55, - 56,56,56,57,57,57,58,58,58,59,60,60,60,61,61,61,62,62,63, - 64,64,64,65,65,65,66,66,66,67,67,67,68,68,69,69,69,70,70, - 70,71,71,71,72,72,72,73,73,73,74,75,75,75,76,76,76,77,77, - 77,78,78,78,79,79,79,80,80,80,81,81,82,82,82,83,83,83,84, - 84,84,85,85,85,86,86,86,87,87,87,88,88,88,89,89,89,90,90, - 90,91,91,91,92,92,93,93,93,94,94,94,95,95,95,96,96,96,97, - 97,98,98,98,99,99,99,100,100,100,101,101,101,102,102,102, - 103,103,103,104,105,105,105,106,106,106,107,107,107,108, - 108,108,109,109,109,110,110,110,111,111,111,112,112,112, - 113,113,113,114,114,115,115,115,116,116,116,117,117,117, - 118,118,118,119,119,119,120,120,120,121,121,121,122,122, - 122,123,123,123,124,124,124,125,125,125,126,126,126,127, - 127,127,128,128,128,129,129,129,130,130,130,131,131,131, - 132,132,132,133,133,133,134,134,134,135,135,135,136,136, - 136,137,137,137,138,138,138,139,139,139,140,140,140,141, - 141,142,142,142,143,143,143,144,144,144,145,145,145,146, - 146,146,147,147,147,148,148,148,149,149,149,150,150,150, - 151,151,151,152,152,152,153,153,153,154,154,154,155,155, - 155,156,156,156,157,157,157,158,158,158,159,159,159,160, - 160,160,161,161,161,162,162,162,163,163,163,164,164,164, - 165,165,165,166,166,166,167,167,167,168,168,168,169,169, - 169,170,170,170,171,171,171,172,172,172,173,173,173,174, - 174,174,175,175,175,176,176,176,177,177,177,178,178,178, - 179,179,179,180,180,180,181,181,181,182,182,182,183,183, - 183,184,184,184,185,185,185,186,186,186,187,187,187,188, - 188,188,189,189,189,190,190,190,191,191,191,192,192,192, - 193,193,193,194,194,194,195,195,195,196,196,197,197,197, - 198,198,198,199,199,199,200,200,200 -] -sp = sortperm(inds) -@test all(issorted, [sp[inds.==x] for x in 1:200]) -for alg in [InsertionSort, MergeSort] - sp = sortperm(inds, alg=alg) - @test all(issorted, [sp[inds.==x] for x in 1:200]) -end - -# issue #6177 -@test sortperm([ 0.0, 1.0, 1.0], rev=true) == [2, 3, 1] -@test sortperm([-0.0, 1.0, 1.0], rev=true) == [2, 3, 1] -@test sortperm([-1.0, 1.0, 1.0], rev=true) == [2, 3, 1] - -# issue #8825 - stability of min/max -mutable struct Twain - a :: Int - b :: Int -end -Base.isless(x :: Twain, y :: Twain) = x.a < y.a -let x = Twain(2,3), y = Twain(2,4) - @test (min(x,y), max(x,y)) == (x,y) == minmax(x,y) -end - -# issue #12833 - type stability of sort -@test Base.return_types(sort, (Vector{Int},)) == [Vector{Int}] - -# PR #18791 -@test sort([typemax(Int),typemin(Int)]) == [typemin(Int),typemax(Int)] -@test sort([typemax(UInt),0]) == [0,typemax(UInt)] - -# issue #19005 -@test searchsortedfirst(0:256, 0x80) == 129 -@test searchsortedlast(0:256, 0x80) == 129 - -# https://discourse.julialang.org/t/sorting-big-int-with-v-0-6/1241 -@test sort([big(3), big(2)]) == [big(2), big(3)] diff --git a/julia-0.6.3/share/julia/test/sparse/cholmod.jl b/julia-0.6.3/share/julia/test/sparse/cholmod.jl deleted file mode 100644 index 233472d..0000000 --- a/julia-0.6.3/share/julia/test/sparse/cholmod.jl +++ /dev/null @@ -1,703 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -srand(123) - -using Base.SparseArrays.CHOLMOD - -# based on deps/SuiteSparse-4.0.2/CHOLMOD/Demo/ - -# chm_rdsp(joinpath(JULIA_HOME, "../../deps/SuiteSparse-4.0.2/CHOLMOD/Demo/Matrix/bcsstk01.tri")) -# because the file may not exist in binary distributions and when a system suitesparse library -# is used - -## Result from C program -## ---------------------------------- cholmod_demo: -## norm (A,inf) = 3.57095e+09 -## norm (A,1) = 3.57095e+09 -## CHOLMOD sparse: A: 48-by-48, nz 224, upper. OK -## CHOLMOD dense: B: 48-by-1, OK -## bnorm 1.97917 -## Analyze: flop 6009 lnz 489 -## Factorizing A -## CHOLMOD factor: L: 48-by-48 simplicial, LDL'. nzmax 489. nz 489 OK -## Ordering: AMD fl/lnz 12.3 lnz/anz 2.2 -## ints in L: 782, doubles in L: 489 -## factor flops 6009 nnz(L) 489 (w/no amalgamation) -## nnz(A*A'): 224 -## flops / nnz(L): 12.3 -## nnz(L) / nnz(A): 2.2 -## analyze cputime: 0.0000 -## factor cputime: 0.0000 mflop: 0.0 -## solve cputime: 0.0000 mflop: 0.0 -## overall cputime: 0.0000 mflop: 0.0 -## peak memory usage: 0 (MB) -## residual 2.5e-19 (|Ax-b|/(|A||x|+|b|)) -## residual 1.3e-19 (|Ax-b|/(|A||x|+|b|)) after iterative refinement -## rcond 9.5e-06 - -A = CHOLMOD.Sparse(48, 48, - CHOLMOD.SuiteSparse_long[0,1,2,3,6,9,12,15,18,20,25,30,34,36,39,43,47,52,58, - 62,67,71,77,84,90,93,95,98,103,106,110,115,119,123,130,136,142,146,150,155, - 161,167,174,182,189,197,207,215,224], # zero-based column pointers - CHOLMOD.SuiteSparse_long[0,1,2,1,2,3,0,2,4,0,1,5,0,4,6,1,3,7,2,8,1,3,7,8,9, - 0,4,6,8,10,5,6,7,11,6,12,7,11,13,8,10,13,14,9,13,14,15,8,10,12,14,16,7,11, - 12,13,16,17,0,12,16,18,1,5,13,15,19,2,4,14,20,3,13,15,19,20,21,2,4,12,16,18, - 20,22,1,5,17,18,19,23,0,5,24,1,25,2,3,26,2,3,25,26,27,4,24,28,0,5,24,29,6, - 11,24,28,30,7,25,27,31,8,9,26,32,8,9,25,27,31,32,33,10,24,28,30,32,34,6,11, - 29,30,31,35,12,17,30,36,13,31,35,37,14,15,32,34,38,14,15,33,37,38,39,16,32, - 34,36,38,40,12,17,31,35,36,37,41,12,16,17,18,23,36,40,42,13,14,15,19,37,39, - 43,13,14,15,20,21,38,43,44,13,14,15,20,21,37,39,43,44,45,12,16,17,22,36,40, - 42,46,12,16,17,18,23,41,42,46,47], - [2.83226851852e6,1.63544753086e6,1.72436728395e6,-2.0e6,-2.08333333333e6, - 1.00333333333e9,1.0e6,-2.77777777778e6,1.0675e9,2.08333333333e6, - 5.55555555555e6,1.53533333333e9,-3333.33333333,-1.0e6,2.83226851852e6, - -6666.66666667,2.0e6,1.63544753086e6,-1.68e6,1.72436728395e6,-2.0e6,4.0e8, - 2.0e6,-2.08333333333e6,1.00333333333e9,1.0e6,2.0e8,-1.0e6,-2.77777777778e6, - 1.0675e9,-2.0e6,2.08333333333e6,5.55555555555e6,1.53533333333e9,-2.8e6, - 2.8360994695e6,-30864.1975309,-5.55555555555e6,1.76741074446e6, - -15432.0987654,2.77777777778e6,517922.131816,3.89003806848e6, - -3.33333333333e6,4.29857058902e6,-2.6349902747e6,1.97572063531e9, - -2.77777777778e6,3.33333333333e8,-2.14928529451e6,2.77777777778e6, - 1.52734651547e9,5.55555555555e6,6.66666666667e8,2.35916180402e6, - -5.55555555555e6,-1.09779731332e8,1.56411143711e9,-2.8e6,-3333.33333333, - 1.0e6,2.83226851852e6,-30864.1975309,-5.55555555555e6,-6666.66666667, - -2.0e6,1.63544753086e6,-15432.0987654,2.77777777778e6,-1.68e6, - 1.72436728395e6,-3.33333333333e6,2.0e6,4.0e8,-2.0e6,-2.08333333333e6, - 1.00333333333e9,-2.77777777778e6,3.33333333333e8,-1.0e6,2.0e8,1.0e6, - 2.77777777778e6,1.0675e9,5.55555555555e6,6.66666666667e8,-2.0e6, - 2.08333333333e6,-5.55555555555e6,1.53533333333e9,-28935.1851852, - -2.08333333333e6,60879.6296296,-1.59791666667e6,3.37291666667e6, - -28935.1851852,2.08333333333e6,2.41171296296e6,-2.08333333333e6, - 1.0e8,-2.5e6,-416666.666667,1.5e9,-833333.333333,1.25e6,5.01833333333e8, - 2.08333333333e6,1.0e8,416666.666667,5.025e8,-28935.1851852, - -2.08333333333e6,-4166.66666667,-1.25e6,3.98587962963e6,-1.59791666667e6, - -8333.33333333,2.5e6,3.41149691358e6,-28935.1851852,2.08333333333e6, - -2.355e6,2.43100308642e6,-2.08333333333e6,1.0e8,-2.5e6,5.0e8,2.5e6, - -416666.666667,1.50416666667e9,-833333.333333,1.25e6,2.5e8,-1.25e6, - -3.47222222222e6,1.33516666667e9,2.08333333333e6,1.0e8,-2.5e6, - 416666.666667,6.94444444444e6,2.16916666667e9,-28935.1851852, - -2.08333333333e6,-3.925e6,3.98587962963e6,-1.59791666667e6, - -38580.2469136,-6.94444444444e6,3.41149691358e6,-28935.1851852, - 2.08333333333e6,-19290.1234568,3.47222222222e6,2.43100308642e6, - -2.08333333333e6,1.0e8,-4.16666666667e6,2.5e6,-416666.666667, - 1.50416666667e9,-833333.333333,-3.47222222222e6,4.16666666667e8, - -1.25e6,3.47222222222e6,1.33516666667e9,2.08333333333e6,1.0e8, - 6.94444444445e6,8.33333333333e8,416666.666667,-6.94444444445e6, - 2.16916666667e9,-3830.95098171,1.14928529451e6,-275828.470683, - -28935.1851852,-2.08333333333e6,-4166.66666667,1.25e6,64710.5806113, - -131963.213599,-517922.131816,-2.29857058902e6,-1.59791666667e6, - -8333.33333333,-2.5e6,3.50487988027e6,-517922.131816,-2.16567078453e6, - 551656.941366,-28935.1851852,2.08333333333e6,-2.355e6,517922.131816, - 4.57738374749e6,2.29857058902e6,-551656.941367,4.8619365099e8, - -2.08333333333e6,1.0e8,2.5e6,5.0e8,-4.79857058902e6,134990.2747, - 2.47238730198e9,-1.14928529451e6,2.29724661236e8,-5.57173510779e7, - -833333.333333,-1.25e6,2.5e8,2.39928529451e6,9.61679848804e8,275828.470683, - -5.57173510779e7,1.09411960038e7,2.08333333333e6,1.0e8,-2.5e6, - 140838.195984,-1.09779731332e8,5.31278103775e8], 1) -@test CHOLMOD.norm_sparse(A, 0) ≈ 3.570948074697437e9 -@test CHOLMOD.norm_sparse(A, 1) ≈ 3.570948074697437e9 -@test_throws ArgumentError CHOLMOD.norm_sparse(A, 2) -@test CHOLMOD.isvalid(A) - -B = A * ones(size(A,2)) -chma = ldltfact(A) # LDL' form -@test CHOLMOD.isvalid(chma) -@test unsafe_load(chma.p).is_ll == 0 # check that it is in fact an LDLt -x = chma\B -@test x ≈ ones(size(x)) -@test nnz(ldltfact(A, perm=1:size(A,1))) > nnz(chma) -@test size(chma) == size(A) -chmal = CHOLMOD.FactorComponent(chma, :L) -@test size(chmal) == size(A) -@test size(chmal, 1) == size(A, 1) - -chma = cholfact(A) # LL' form -@test CHOLMOD.isvalid(chma) -@test unsafe_load(chma.p).is_ll == 1 # check that it is in fact an LLt -x = chma\B -@test x ≈ ones(size(x)) -@test nnz(chma) == 489 -@test nnz(cholfact(A, perm=1:size(A,1))) > nnz(chma) -@test size(chma) == size(A) -chmal = CHOLMOD.FactorComponent(chma, :L) -@test size(chmal) == size(A) -@test size(chmal, 1) == size(A, 1) - -#lp_afiro example -afiro = CHOLMOD.Sparse(27, 51, - CHOLMOD.SuiteSparse_long[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19, - 23,25,27,29,33,37,41,45,47,49,51,53,55,57,59,63,65,67,69,71,75,79,83,87,89, - 91,93,95,97,99,101,102], - CHOLMOD.SuiteSparse_long[2,3,6,7,8,9,12,13,16,17,18,19,20,21,22,23,24,25,26, - 0,1,2,23,0,3,0,21,1,25,4,5,6,24,4,5,7,24,4,5,8,24,4,5,9,24,6,20,7,20,8,20,9, - 20,3,4,4,22,5,26,10,11,12,21,10,13,10,23,10,20,11,25,14,15,16,22,14,15,17, - 22,14,15,18,22,14,15,19,22,16,20,17,20,18,20,19,20,13,15,15,24,14,26,15], - [1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0, - 1.0,-1.0,-1.06,1.0,0.301,1.0,-1.0,1.0,-1.0,1.0,1.0,-1.0,-1.06,1.0,0.301, - -1.0,-1.06,1.0,0.313,-1.0,-0.96,1.0,0.313,-1.0,-0.86,1.0,0.326,-1.0,2.364, - -1.0,2.386,-1.0,2.408,-1.0,2.429,1.4,1.0,1.0,-1.0,1.0,1.0,-1.0,-0.43,1.0, - 0.109,1.0,-1.0,1.0,-1.0,1.0,-1.0,1.0,1.0,-0.43,1.0,1.0,0.109,-0.43,1.0,1.0, - 0.108,-0.39,1.0,1.0,0.108,-0.37,1.0,1.0,0.107,-1.0,2.191,-1.0,2.219,-1.0, - 2.249,-1.0,2.279,1.4,-1.0,1.0,-1.0,1.0,1.0,1.0], 0) -afiro2 = CHOLMOD.aat(afiro, CHOLMOD.SuiteSparse_long[0:50;], CHOLMOD.SuiteSparse_long(1)) -CHOLMOD.change_stype!(afiro2, -1) -chmaf = cholfact(afiro2) -y = afiro'*ones(size(afiro,1)) -sol = chmaf\(afiro*y) # least squares solution -@test CHOLMOD.isvalid(sol) -pred = afiro'*sol -@test norm(afiro * (convert(Matrix, y) - convert(Matrix, pred))) < 1e-8 - -let # Issue 9160 - A = sprand(10, 10, 0.1) - A = convert(SparseMatrixCSC{Float64,CHOLMOD.SuiteSparse_long}, A) - cmA = CHOLMOD.Sparse(A) - - B = sprand(10, 10, 0.1) - B = convert(SparseMatrixCSC{Float64,CHOLMOD.SuiteSparse_long}, B) - cmB = CHOLMOD.Sparse(B) - - # Ac_mul_B - @test sparse(cmA'*cmB) ≈ A'*B - - # A_mul_Bc - @test sparse(cmA*cmB') ≈ A*B' - - # A_mul_Ac - @test sparse(cmA*cmA') ≈ A*A' - - # Ac_mul_A - @test sparse(cmA'*cmA) ≈ A'*A - - # A_mul_Ac for symmetric A - A = 0.5*(A + A') - cmA = CHOLMOD.Sparse(A) - @test sparse(cmA*cmA') ≈ A*A' -end - -# Issue #9915 -@test speye(2)\speye(2) == eye(2) - -# test eltype -@test eltype(Dense(ones(3))) == Float64 -@test eltype(A) == Float64 -@test eltype(chma) == Float64 - -# test Sparse constructor Symmetric and Hermitian input (and issymmetric and ishermitian) -ACSC = sprandn(10, 10, 0.3) + I -@test issymmetric(Sparse(Symmetric(ACSC, :L))) -@test issymmetric(Sparse(Symmetric(ACSC, :U))) -@test ishermitian(Sparse(Hermitian(complex(ACSC), :L))) -@test ishermitian(Sparse(Hermitian(complex(ACSC), :U))) - -# test Sparse constructor for c_SparseVoid (and read_sparse) -mktempdir() do temp_dir - testfile = joinpath(temp_dir, "tmp.mtx") - - writedlm(testfile, ["%%MatrixMarket matrix coordinate real symmetric","3 3 4","1 1 1","2 2 1","3 2 0.5","3 3 1"]) - @test sparse(CHOLMOD.Sparse(testfile)) == [1 0 0;0 1 0.5;0 0.5 1] - rm(testfile) - - writedlm(testfile, ["%%MatrixMarket matrix coordinate complex Hermitian", - "3 3 4","1 1 1.0 0.0","2 2 1.0 0.0","3 2 0.5 0.5","3 3 1.0 0.0"]) - @test sparse(CHOLMOD.Sparse(testfile)) == [1 0 0;0 1 0.5-0.5im;0 0.5+0.5im 1] - rm(testfile) - - writedlm(testfile, ["%%MatrixMarket matrix coordinate real symmetric","%3 3 4","1 1 1","2 2 1","3 2 0.5","3 3 1"]) - @test_throws ArgumentError sparse(CHOLMOD.Sparse(testfile)) - rm(testfile) -end - -# test that Sparse(Ptr) constructor throws the right places -@test_throws ArgumentError CHOLMOD.Sparse(convert(Ptr{CHOLMOD.C_Sparse{Float64}}, C_NULL)) -@test_throws ArgumentError CHOLMOD.Sparse(convert(Ptr{CHOLMOD.C_SparseVoid}, C_NULL)) - -## The struct pointer must be constructed by the library constructor and then modified afterwards to checks that the method throws -### illegal dtype (for now but should be supported at some point) -p = ccall((:cholmod_l_allocate_sparse, :libcholmod), Ptr{CHOLMOD.C_SparseVoid}, - (Csize_t, Csize_t, Csize_t, Cint, Cint, Cint, Cint, Ptr{Void}), - 1, 1, 1, true, true, 0, CHOLMOD.REAL, CHOLMOD.common()) -puint = convert(Ptr{UInt32}, p) -unsafe_store!(puint, CHOLMOD.SINGLE, 3*div(sizeof(Csize_t), 4) + 5*div(sizeof(Ptr{Void}), 4) + 4) -@test_throws CHOLMOD.CHOLMODException CHOLMOD.Sparse(p) - -### illegal dtype -p = ccall((:cholmod_l_allocate_sparse, :libcholmod), Ptr{CHOLMOD.C_SparseVoid}, - (Csize_t, Csize_t, Csize_t, Cint, Cint, Cint, Cint, Ptr{Void}), - 1, 1, 1, true, true, 0, CHOLMOD.REAL, CHOLMOD.common()) -puint = convert(Ptr{UInt32}, p) -unsafe_store!(puint, 5, 3*div(sizeof(Csize_t), 4) + 5*div(sizeof(Ptr{Void}), 4) + 4) -@test_throws CHOLMOD.CHOLMODException CHOLMOD.Sparse(p) - -### illegal xtype -p = ccall((:cholmod_l_allocate_sparse, :libcholmod), Ptr{CHOLMOD.C_SparseVoid}, - (Csize_t, Csize_t, Csize_t, Cint, Cint, Cint, Cint, Ptr{Void}), - 1, 1, 1, true, true, 0, CHOLMOD.REAL, CHOLMOD.common()) -puint = convert(Ptr{UInt32}, p) -unsafe_store!(puint, 3, 3*div(sizeof(Csize_t), 4) + 5*div(sizeof(Ptr{Void}), 4) + 3) -@test_throws CHOLMOD.CHOLMODException CHOLMOD.Sparse(p) - -### illegal itype -p = ccall((:cholmod_l_allocate_sparse, :libcholmod), Ptr{CHOLMOD.C_SparseVoid}, - (Csize_t, Csize_t, Csize_t, Cint, Cint, Cint, Cint, Ptr{Void}), - 1, 1, 1, true, true, 0, CHOLMOD.REAL, CHOLMOD.common()) -puint = convert(Ptr{UInt32}, p) -unsafe_store!(puint, CHOLMOD.INTLONG, 3*div(sizeof(Csize_t), 4) + 5*div(sizeof(Ptr{Void}), 4) + 2) -@test_throws CHOLMOD.CHOLMODException CHOLMOD.Sparse(p) - -### illegal itype -p = ccall((:cholmod_l_allocate_sparse, :libcholmod), Ptr{CHOLMOD.C_SparseVoid}, - (Csize_t, Csize_t, Csize_t, Cint, Cint, Cint, Cint, Ptr{Void}), - 1, 1, 1, true, true, 0, CHOLMOD.REAL, CHOLMOD.common()) -puint = convert(Ptr{UInt32}, p) -unsafe_store!(puint, 5, 3*div(sizeof(Csize_t), 4) + 5*div(sizeof(Ptr{Void}), 4) + 2) -@test_throws CHOLMOD.CHOLMODException CHOLMOD.Sparse(p) - -# Test Dense wrappers (only Float64 supported a present) - -## High level interface -for elty in (Float64, Complex{Float64}) - if elty == Float64 - A = randn(5, 5) - b = randn(5) - else - A = complex.(randn(5, 5), randn(5, 5)) - b = complex.(randn(5), randn(5)) - end - ADense = CHOLMOD.Dense(A) - bDense = CHOLMOD.Dense(b) - - @test_throws BoundsError ADense[6, 1] - @test_throws BoundsError ADense[1, 6] - @test copy(ADense) == ADense - @test CHOLMOD.norm_dense(ADense, 1) ≈ norm(A, 1) - @test CHOLMOD.norm_dense(ADense, 0) ≈ norm(A, Inf) - @test_throws ArgumentError CHOLMOD.norm_dense(ADense, 2) - @test_throws ArgumentError CHOLMOD.norm_dense(ADense, 3) - - @test CHOLMOD.norm_dense(bDense, 2) ≈ norm(b) - @test CHOLMOD.check_dense(bDense) - - AA = CHOLMOD.eye(3) - unsafe_store!(convert(Ptr{Csize_t}, AA.p), 2, 1) # change size, but not stride, of Dense - @test convert(Matrix, AA) == eye(2, 3) -end - -## Low level interface -@test isa(CHOLMOD.zeros(3, 3, Float64), CHOLMOD.Dense{Float64}) -@test isa(CHOLMOD.zeros(3, 3), CHOLMOD.Dense{Float64}) -@test isa(CHOLMOD.zeros(3, 3, Float64), CHOLMOD.Dense{Float64}) -@test isa(CHOLMOD.ones(3, 3), CHOLMOD.Dense{Float64}) -@test isa(CHOLMOD.eye(3, 4, Float64), CHOLMOD.Dense{Float64}) -@test isa(CHOLMOD.eye(3, 4), CHOLMOD.Dense{Float64}) -@test isa(CHOLMOD.eye(3), CHOLMOD.Dense{Float64}) -@test isa(CHOLMOD.copy_dense(CHOLMOD.eye(3)), CHOLMOD.Dense{Float64}) - -# Test Sparse and Factor -## test free_sparse! -p = ccall((:cholmod_l_allocate_sparse, :libcholmod), Ptr{CHOLMOD.C_Sparse{Float64}}, - (Csize_t, Csize_t, Csize_t, Cint, Cint, Cint, Cint, Ptr{Void}), - 1, 1, 1, true, true, 0, CHOLMOD.REAL, CHOLMOD.common()) -@test CHOLMOD.free_sparse!(p) - -for elty in (Float64, Complex{Float64}) - A1 = sparse([1:5, 1;], [1:5, 2;], elty == Float64 ? randn(6) : complex.(randn(6), randn(6))) - A2 = sparse([1:5, 1;], [1:5, 2;], elty == Float64 ? randn(6) : complex.(randn(6), randn(6))) - A1pd = A1'A1 - A1Sparse = CHOLMOD.Sparse(A1) - A2Sparse = CHOLMOD.Sparse(A2) - A1pdSparse = CHOLMOD.Sparse( - A1pd.m, - A1pd.n, - Base.SparseArrays.decrement(A1pd.colptr), - Base.SparseArrays.decrement(A1pd.rowval), - A1pd.nzval) - - ## High level interface - @test isa(CHOLMOD.Sparse(3, 3, [0,1,3,4], [0,2,1,2], ones(4)), CHOLMOD.Sparse) # Sparse doesn't require columns to be sorted - @test_throws BoundsError A1Sparse[6, 1] - @test_throws BoundsError A1Sparse[1, 6] - @test sparse(A1Sparse) == A1 - for i=1:size(A1, 1) A1[i, i] = real(A1[i, i]) end #Construct Hermitian matrix properly - @test CHOLMOD.sparse(CHOLMOD.Sparse(Hermitian(A1, :L))) == Hermitian(A1, :L) - @test CHOLMOD.sparse(CHOLMOD.Sparse(Hermitian(A1, :U))) == Hermitian(A1, :U) - @test_throws ArgumentError convert(SparseMatrixCSC{elty,Int}, A1pdSparse) - if elty <: Real - @test_throws ArgumentError convert(Symmetric{Float64,SparseMatrixCSC{Float64,Int}}, A1Sparse) - else - @test_throws ArgumentError convert(Hermitian{Complex{Float64},SparseMatrixCSC{Complex{Float64},Int}}, A1Sparse) - end - @test copy(A1Sparse) == A1Sparse - @test size(A1Sparse, 3) == 1 - if elty <: Real # multiplication only defined for real matrices in CHOLMOD - @test A1Sparse*A2Sparse ≈ A1*A2 - @test_throws DimensionMismatch CHOLMOD.Sparse(A1[:,1:4])*A2Sparse - @test A1Sparse'A2Sparse ≈ A1'A2 - @test A1Sparse*A2Sparse' ≈ A1*A2' - - @test A1Sparse*A1Sparse ≈ A1*A1 - @test A1Sparse'A1Sparse ≈ A1'A1 - @test A1Sparse*A1Sparse' ≈ A1*A1' - - @test A1pdSparse*A1pdSparse ≈ A1pd*A1pd - @test A1pdSparse'A1pdSparse ≈ A1pd'A1pd - @test A1pdSparse*A1pdSparse' ≈ A1pd*A1pd' - - @test_throws DimensionMismatch A1Sparse*CHOLMOD.eye(4, 5, elty) - end - - # Factor - @test_throws ArgumentError cholfact(A1) - @test_throws Base.LinAlg.PosDefException cholfact(A1 + A1' - 2eigmax(Array(A1 + A1'))I) - @test_throws Base.LinAlg.PosDefException cholfact(A1 + A1', shift=-2eigmax(Array(A1 + A1'))) - @test_throws ArgumentError ldltfact(A1 + A1' - 2real(A1[1,1])I) - @test_throws ArgumentError ldltfact(A1 + A1', shift=-2real(A1[1,1])) - @test_throws ArgumentError cholfact(A1) - @test_throws ArgumentError cholfact(A1, shift=1.0) - @test_throws ArgumentError ldltfact(A1) - @test_throws ArgumentError ldltfact(A1, shift=1.0) - F = cholfact(A1pd) - tmp = IOBuffer() - show(tmp, F) - @test tmp.size > 0 - @test isa(CHOLMOD.Sparse(F), CHOLMOD.Sparse{elty}) - @test F\CHOLMOD.Sparse(sparse(ones(elty, 5))) ≈ A1pd\ones(5) - @test_throws DimensionMismatch F\CHOLMOD.Dense(ones(elty, 4)) - @test_throws DimensionMismatch F\CHOLMOD.Sparse(sparse(ones(elty, 4))) - @test F'\ones(elty, 5) ≈ Array(A1pd)'\ones(5) - @test F'\sparse(ones(elty, 5)) ≈ Array(A1pd)'\ones(5) - @test F.'\ones(elty, 5) ≈ conj(A1pd)'\ones(elty, 5) - @test logdet(F) ≈ logdet(Array(A1pd)) - @test det(F) == exp(logdet(F)) - let # to test supernodal, we must use a larger matrix - Ftmp = sprandn(100,100,0.1) - Ftmp = Ftmp'Ftmp + I - @test logdet(cholfact(Ftmp)) ≈ logdet(Array(Ftmp)) - end - @test logdet(ldltfact(A1pd)) ≈ logdet(Array(A1pd)) - @test isposdef(A1pd) - @test !isposdef(A1) - @test !isposdef(A1 + A1' |> t -> t - 2eigmax(Array(t))*I) - - if elty <: Real - @test CHOLMOD.issymmetric(Sparse(A1pd, 0)) - @test CHOLMOD.Sparse(cholfact(Symmetric(A1pd, :L))) == CHOLMOD.Sparse(cholfact(A1pd)) - F1 = CHOLMOD.Sparse(cholfact(Symmetric(A1pd, :L), shift=2)) - F2 = CHOLMOD.Sparse(cholfact(A1pd, shift=2)) - @test F1 == F2 - @test CHOLMOD.Sparse(ldltfact(Symmetric(A1pd, :L))) == CHOLMOD.Sparse(ldltfact(A1pd)) - F1 = CHOLMOD.Sparse(ldltfact(Symmetric(A1pd, :L), shift=2)) - F2 = CHOLMOD.Sparse(ldltfact(A1pd, shift=2)) - @test F1 == F2 - else - @test !CHOLMOD.issymmetric(Sparse(A1pd, 0)) - @test CHOLMOD.ishermitian(Sparse(A1pd, 0)) - @test CHOLMOD.Sparse(cholfact(Hermitian(A1pd, :L))) == CHOLMOD.Sparse(cholfact(A1pd)) - F1 = CHOLMOD.Sparse(cholfact(Hermitian(A1pd, :L), shift=2)) - F2 = CHOLMOD.Sparse(cholfact(A1pd, shift=2)) - @test F1 == F2 - @test CHOLMOD.Sparse(ldltfact(Hermitian(A1pd, :L))) == CHOLMOD.Sparse(ldltfact(A1pd)) - F1 = CHOLMOD.Sparse(ldltfact(Hermitian(A1pd, :L), shift=2)) - F2 = CHOLMOD.Sparse(ldltfact(A1pd, shift=2)) - @test F1 == F2 - end - - ### cholfact!/ldltfact! - F = cholfact(A1pd) - CHOLMOD.change_factor!(elty, false, false, true, true, F) - @test unsafe_load(F.p).is_ll == 0 - CHOLMOD.change_factor!(elty, true, false, true, true, F) - @test CHOLMOD.Sparse(cholfact!(copy(F), A1pd)) ≈ CHOLMOD.Sparse(F) # surprisingly, this can cause small ulp size changes so we cannot test exact equality - @test size(F, 2) == 5 - @test size(F, 3) == 1 - @test_throws ArgumentError size(F, 0) - - F = cholfact(A1pdSparse, shift=2) - @test isa(CHOLMOD.Sparse(F), CHOLMOD.Sparse{elty}) - @test CHOLMOD.Sparse(cholfact!(copy(F), A1pd, shift=2.0)) ≈ CHOLMOD.Sparse(F) # surprisingly, this can cause small ulp size changes so we cannot test exact equality - - F = ldltfact(A1pd) - @test isa(CHOLMOD.Sparse(F), CHOLMOD.Sparse{elty}) - @test CHOLMOD.Sparse(ldltfact!(copy(F), A1pd)) ≈ CHOLMOD.Sparse(F) # surprisingly, this can cause small ulp size changes so we cannot test exact equality - - F = ldltfact(A1pdSparse, shift=2) - @test isa(CHOLMOD.Sparse(F), CHOLMOD.Sparse{elty}) - @test CHOLMOD.Sparse(ldltfact!(copy(F), A1pd, shift=2.0)) ≈ CHOLMOD.Sparse(F) # surprisingly, this can cause small ulp size changes so we cannot test exact equality - - @test isa(CHOLMOD.factor_to_sparse!(F), CHOLMOD.Sparse) - @test_throws CHOLMOD.CHOLMODException CHOLMOD.factor_to_sparse!(F) - - ## Low level interface - @test CHOLMOD.nnz(A1Sparse) == nnz(A1) - @test CHOLMOD.speye(5, 5, elty) == eye(elty, 5, 5) - @test CHOLMOD.spzeros(5, 5, 5, elty) == zeros(elty, 5, 5) - if elty <: Real - @test CHOLMOD.copy(A1Sparse, 0, 1) == A1Sparse - @test CHOLMOD.horzcat(A1Sparse, A2Sparse, true) == [A1 A2] - @test CHOLMOD.vertcat(A1Sparse, A2Sparse, true) == [A1; A2] - svec = ones(elty, 1) - @test CHOLMOD.scale!(CHOLMOD.Dense(svec), CHOLMOD.SCALAR, A1Sparse) == A1Sparse - svec = ones(elty, 5) - @test_throws DimensionMismatch CHOLMOD.scale!(CHOLMOD.Dense(svec), CHOLMOD.SCALAR, A1Sparse) - @test CHOLMOD.scale!(CHOLMOD.Dense(svec), CHOLMOD.ROW, A1Sparse) == A1Sparse - @test_throws DimensionMismatch CHOLMOD.scale!(CHOLMOD.Dense([svec, 1;]), CHOLMOD.ROW, A1Sparse) - @test CHOLMOD.scale!(CHOLMOD.Dense(svec), CHOLMOD.COL, A1Sparse) == A1Sparse - @test_throws DimensionMismatch CHOLMOD.scale!(CHOLMOD.Dense([svec, 1;]), CHOLMOD.COL, A1Sparse) - @test CHOLMOD.scale!(CHOLMOD.Dense(svec), CHOLMOD.SYM, A1Sparse) == A1Sparse - @test_throws DimensionMismatch CHOLMOD.scale!(CHOLMOD.Dense([svec, 1;]), CHOLMOD.SYM, A1Sparse) - @test_throws DimensionMismatch CHOLMOD.scale!(CHOLMOD.Dense(svec), CHOLMOD.SYM, CHOLMOD.Sparse(A1[:,1:4])) - else - @test_throws MethodError CHOLMOD.copy(A1Sparse, 0, 1) == A1Sparse - @test_throws MethodError CHOLMOD.horzcat(A1Sparse, A2Sparse, true) == [A1 A2] - @test_throws MethodError CHOLMOD.vertcat(A1Sparse, A2Sparse, true) == [A1; A2] - end - - - if elty <: Real - @test CHOLMOD.ssmult(A1Sparse, A2Sparse, 0, true, true) ≈ A1*A2 - @test CHOLMOD.aat(A1Sparse, [0:size(A1,2)-1;], 1) ≈ A1*A1' - @test CHOLMOD.aat(A1Sparse, [0:1;], 1) ≈ A1[:,1:2]*A1[:,1:2]' - @test CHOLMOD.copy(A1Sparse, 0, 1) == A1Sparse - end - - @test CHOLMOD.Sparse(CHOLMOD.Dense(A1Sparse)) == A1Sparse -end - -Af = float([4 12 -16; 12 37 -43; -16 -43 98]) -As = sparse(Af) -Lf = float([2 0 0; 6 1 0; -8 5 3]) -LDf = float([4 0 0; 3 1 0; -4 5 9]) # D is stored along the diagonal -L_f = float([1 0 0; 3 1 0; -4 5 1]) # L by itself in LDLt of Af -D_f = float([4 0 0; 0 1 0; 0 0 9]) - -# cholfact, no permutation -Fs = cholfact(As, perm=[1:3;]) -@test Fs[:p] == [1:3;] -@test sparse(Fs[:L]) ≈ Lf -@test sparse(Fs) ≈ As -b = rand(3) -@test Fs\b ≈ Af\b -@test Fs[:UP]\(Fs[:PtL]\b) ≈ Af\b -@test Fs[:L]\b ≈ Lf\b -@test Fs[:U]\b ≈ Lf'\b -@test Fs[:L]'\b ≈ Lf'\b -@test Fs[:U]'\b ≈ Lf\b -@test Fs[:PtL]\b ≈ Lf\b -@test Fs[:UP]\b ≈ Lf'\b -@test Fs[:PtL]'\b ≈ Lf'\b -@test Fs[:UP]'\b ≈ Lf\b -@test_throws CHOLMOD.CHOLMODException Fs[:D] -@test_throws CHOLMOD.CHOLMODException Fs[:LD] -@test_throws CHOLMOD.CHOLMODException Fs[:DU] -@test_throws CHOLMOD.CHOLMODException Fs[:PLD] -@test_throws CHOLMOD.CHOLMODException Fs[:DUPt] - -# cholfact, with permutation -p = [2,3,1] -p_inv = [3,1,2] -Fs = cholfact(As, perm=p) -@test Fs[:p] == p -Afp = Af[p,p] -Lfp = cholfact(Afp)[:L] -@test sparse(Fs[:L]) ≈ Lfp -@test sparse(Fs) ≈ As -b = rand(3) -@test Fs\b ≈ Af\b -@test Fs[:UP]\(Fs[:PtL]\b) ≈ Af\b -@test Fs[:L]\b ≈ Lfp\b -@test Fs[:U]'\b ≈ Lfp\b -@test Fs[:U]\b ≈ Lfp'\b -@test Fs[:L]'\b ≈ Lfp'\b -@test Fs[:PtL]\b ≈ Lfp\b[p] -@test Fs[:UP]\b ≈ (Lfp'\b)[p_inv] -@test Fs[:PtL]'\b ≈ (Lfp'\b)[p_inv] -@test Fs[:UP]'\b ≈ Lfp\b[p] -@test_throws CHOLMOD.CHOLMODException Fs[:PL] -@test_throws CHOLMOD.CHOLMODException Fs[:UPt] -@test_throws CHOLMOD.CHOLMODException Fs[:D] -@test_throws CHOLMOD.CHOLMODException Fs[:LD] -@test_throws CHOLMOD.CHOLMODException Fs[:DU] -@test_throws CHOLMOD.CHOLMODException Fs[:PLD] -@test_throws CHOLMOD.CHOLMODException Fs[:DUPt] - -# ldltfact, no permutation -Fs = ldltfact(As, perm=[1:3;]) -@test Fs[:p] == [1:3;] -@test sparse(Fs[:LD]) ≈ LDf -@test sparse(Fs) ≈ As -b = rand(3) -@test Fs\b ≈ Af\b -@test Fs[:UP]\(Fs[:PtLD]\b) ≈ Af\b -@test Fs[:DUP]\(Fs[:PtL]\b) ≈ Af\b -@test Fs[:L]\b ≈ L_f\b -@test Fs[:U]\b ≈ L_f'\b -@test Fs[:L]'\b ≈ L_f'\b -@test Fs[:U]'\b ≈ L_f\b -@test Fs[:PtL]\b ≈ L_f\b -@test Fs[:UP]\b ≈ L_f'\b -@test Fs[:PtL]'\b ≈ L_f'\b -@test Fs[:UP]'\b ≈ L_f\b -@test Fs[:D]\b ≈ D_f\b -@test Fs[:D]'\b ≈ D_f\b -@test Fs[:LD]\b ≈ D_f\(L_f\b) -@test Fs[:DU]'\b ≈ D_f\(L_f\b) -@test Fs[:LD]'\b ≈ L_f'\(D_f\b) -@test Fs[:DU]\b ≈ L_f'\(D_f\b) -@test Fs[:PtLD]\b ≈ D_f\(L_f\b) -@test Fs[:DUP]'\b ≈ D_f\(L_f\b) -@test Fs[:PtLD]'\b ≈ L_f'\(D_f\b) -@test Fs[:DUP]\b ≈ L_f'\(D_f\b) - -# ldltfact, with permutation -Fs = ldltfact(As, perm=p) -@test Fs[:p] == p -@test sparse(Fs) ≈ As -b = rand(3) -Asp = As[p,p] -LDp = sparse(ldltfact(Asp, perm=[1,2,3])[:LD]) -# LDp = sparse(Fs[:LD]) -Lp, dp = Base.SparseArrays.CHOLMOD.getLd!(copy(LDp)) -Dp = spdiagm(dp) -@test Fs\b ≈ Af\b -@test Fs[:UP]\(Fs[:PtLD]\b) ≈ Af\b -@test Fs[:DUP]\(Fs[:PtL]\b) ≈ Af\b -@test Fs[:L]\b ≈ Lp\b -@test Fs[:U]\b ≈ Lp'\b -@test Fs[:L]'\b ≈ Lp'\b -@test Fs[:U]'\b ≈ Lp\b -@test Fs[:PtL]\b ≈ Lp\b[p] -@test Fs[:UP]\b ≈ (Lp'\b)[p_inv] -@test Fs[:PtL]'\b ≈ (Lp'\b)[p_inv] -@test Fs[:UP]'\b ≈ Lp\b[p] -@test Fs[:LD]\b ≈ Dp\(Lp\b) -@test Fs[:DU]'\b ≈ Dp\(Lp\b) -@test Fs[:LD]'\b ≈ Lp'\(Dp\b) -@test Fs[:DU]\b ≈ Lp'\(Dp\b) -@test Fs[:PtLD]\b ≈ Dp\(Lp\b[p]) -@test Fs[:DUP]'\b ≈ Dp\(Lp\b[p]) -@test Fs[:PtLD]'\b ≈ (Lp'\(Dp\b))[p_inv] -@test Fs[:DUP]\b ≈ (Lp'\(Dp\b))[p_inv] -@test_throws CHOLMOD.CHOLMODException Fs[:DUPt] -@test_throws CHOLMOD.CHOLMODException Fs[:PLD] - -# Issue 11745 - row and column pointers were not sorted in sparse(Factor) -let A = Float64[10 1 1 1; 1 10 0 0; 1 0 10 0; 1 0 0 10] - @test sparse(cholfact(sparse(A))) ≈ A -end -gc() - -# Issue 11747 - Wrong show method defined for FactorComponent -let v = cholfact(sparse(Float64[ 10 1 1 1; 1 10 0 0; 1 0 10 0; 1 0 0 10]))[:L] - for s in (sprint(show, MIME("text/plain"), v), sprint(show, v)) - @test contains(s, "method: simplicial") - @test !contains(s, "#undef") - end -end - -# Element promotion and type inference -@inferred cholfact(As)\ones(Int, size(As, 1)) -@inferred ldltfact(As)\ones(Int, size(As, 1)) - -# Issue 14076 -@test cholfact(sparse([1,2,3,4], [1,2,3,4], Float32[1,4,16,64]))\[1,4,16,64] == ones(4) - -# Issue 14134 -A = SparseArrays.CHOLMOD.Sparse(sprandn(10,5,0.1) + I |> t -> t't) -b = IOBuffer() -serialize(b, A) -seekstart(b) -Anew = deserialize(b) -@test_throws ArgumentError show(Anew) -@test_throws ArgumentError size(Anew) -@test_throws ArgumentError Anew[1] -@test_throws ArgumentError Anew[2,1] -F = cholfact(A) -serialize(b, F) -seekstart(b) -Fnew = deserialize(b) -@test_throws ArgumentError Fnew\ones(5) -@test_throws ArgumentError show(Fnew) -@test_throws ArgumentError size(Fnew) -@test_throws ArgumentError diag(Fnew) -@test_throws ArgumentError logdet(Fnew) - -# Issue with promotion during conversion to CHOLMOD.Dense -@test SparseArrays.CHOLMOD.Dense(ones(Float32, 5)) == ones(5, 1) -@test SparseArrays.CHOLMOD.Dense(ones(Int, 5)) == ones(5, 1) -@test SparseArrays.CHOLMOD.Dense(ones(Complex{Float32}, 5, 2)) == ones(5, 2) - -# Further issue with promotion #14894 -@test cholfact(speye(Float16, 5))\ones(5) == ones(5) -@test cholfact(Symmetric(speye(Float16, 5)))\ones(5) == ones(5) -@test cholfact(Hermitian(speye(Complex{Float16}, 5)))\ones(5) == ones(Complex{Float64}, 5) -@test_throws MethodError cholfact(speye(BigFloat, 5)) -@test_throws MethodError cholfact(Symmetric(speye(BigFloat, 5))) -@test_throws MethodError cholfact(Hermitian(speye(Complex{BigFloat}, 5))) - -# test \ for Factor and StridedVecOrMat -let x = rand(5) - A = cholfact(sparse(diagm(x.\1))) - @test A\view(ones(10),1:2:10) ≈ x - @test A\view(eye(5,5),:,:) ≈ diagm(x) -end - -# Real factorization and complex rhs -A = sprandn(5,5,0.4) |> t -> t't + I -B = complex.(randn(5,2), randn(5,2)) -@test cholfact(A)\B ≈ A\B - -# Make sure that ldltfact performs an LDLt (Issue #19032) -let m = 400, n = 500 - A = sprandn(m, n, .2) - M = [speye(n) A'; A -speye(m)] - b = M*ones(m + n) - F = ldltfact(M) - s = unsafe_load(get(F.p)) - @test s.is_super == 0 - @test F\b ≈ ones(m + n) -end - -# Test that \ and '\ and .'\ work for Symmetric and Hermitian. This is just -# a dispatch exercise so it doesn't matter that the complex matrix has -# zero imaginary parts -let Apre = sprandn(10, 10, 0.2) - I - for A in (Symmetric(Apre), Hermitian(Apre), - Symmetric(Apre + 10I), Hermitian(Apre + 10I), - Hermitian(complex(Apre)), Hermitian(complex(Apre) + 10I)) - x = ones(10) - b = A*x - @test x ≈ A\b - @test A.'\b ≈ A'\b - end -end - -# Check that Symmetric{SparseMatrixCSC} can be constructed from CHOLMOD.Sparse -let A = sprandn(10, 10, 0.1) - B = SparseArrays.CHOLMOD.Sparse(A) - C = B'B - # Change internal representation to symmetric (upper/lower) - o = fieldoffset(CHOLMOD.C_Sparse{eltype(C)}, find(fieldnames(CHOLMOD.C_Sparse{eltype(C)}) .== :stype)[1]) - for uplo in (1, -1) - unsafe_store!(Ptr{Int8}(C.p), uplo, Int(o) + 1) - @test convert(Symmetric{Float64,SparseMatrixCSC{Float64,Int}}, C) == Symmetric(A'A) - end -end - -@testset "Check inputs to Sparse. Related to #20024" for A in ( - SparseMatrixCSC(2, 2, [1, 2], CHOLMOD.SuiteSparse_long[], Float64[]), - SparseMatrixCSC(2, 2, [1, 2, 3], CHOLMOD.SuiteSparse_long[1], Float64[]), - SparseMatrixCSC(2, 2, [1, 2, 3], CHOLMOD.SuiteSparse_long[], Float64[1.0]), - SparseMatrixCSC(2, 2, [1, 2, 3], CHOLMOD.SuiteSparse_long[1], Float64[1.0])) - - @test_throws ArgumentError CHOLMOD.Sparse(size(A)..., A.colptr - 1, A.rowval - 1, A.nzval) - @test_throws ArgumentError CHOLMOD.Sparse(A) -end - -@testset "sparse right multiplication of Symmetric and Hermitian matrices #21431" begin - @test issparse(speye(2)*speye(2)*speye(2)) - for T in (Symmetric, Hermitian) - @test issparse(speye(2)*T(speye(2))*speye(2)) - @test issparse(speye(2)*(T(speye(2))*speye(2))) - @test issparse((speye(2)*T(speye(2)))*speye(2)) - end -end diff --git a/julia-0.6.3/share/julia/test/sparse/higherorderfns.jl b/julia-0.6.3/share/julia/test/sparse/higherorderfns.jl deleted file mode 100644 index 4b9e0a7..0000000 --- a/julia-0.6.3/share/julia/test/sparse/higherorderfns.jl +++ /dev/null @@ -1,543 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -# These tests cover the higher order functions specialized for sparse arrays defined in -# base/sparse/higherorderfns.jl, particularly map[!]/broadcast[!] for SparseVectors and -# SparseMatrixCSCs at present. - -@testset "map[!] implementation specialized for a single (input) sparse vector/matrix" begin - N, M = 10, 12 - for shapeA in ((N,), (N, M)) - A = sprand(shapeA..., 0.4); fA = Array(A) - # --> test map entry point - @test map(sin, A) == sparse(map(sin, fA)) - @test map(cos, A) == sparse(map(cos, fA)) - # --> test map! entry point - fX = copy(fA); X = sparse(fX) - map!(sin, X, A); X = sparse(fX) # warmup for @allocated - @test (@allocated map!(sin, X, A)) == 0 - @test map!(sin, X, A) == sparse(map!(sin, fX, fA)) - @test map!(cos, X, A) == sparse(map!(cos, fX, fA)) - @test_throws DimensionMismatch map!(sin, X, spzeros((shapeA .- 1)...)) - end -end - -@testset "map[!] implementation specialized for a pair of (input) sparse vectors/matrices" begin - N, M = 10, 12 - f(x, y) = x + y + 1 - for shapeA in ((N,), (N, M)) - A, Bo = sprand(shapeA..., 0.3), sprand(shapeA..., 0.3) - B = ndims(Bo) == 1 ? SparseVector{Float32, Int32}(Bo) : SparseMatrixCSC{Float32,Int32}(Bo) - # use different types to check internal type stability via allocation tests below - fA, fB = map(Array, (A, B)) - # --> test map entry point - @test map(+, A, B) == sparse(map(+, fA, fB)) - @test map(*, A, B) == sparse(map(*, fA, fB)) - @test map(f, A, B) == sparse(map(f, fA, fB)) - @test_throws DimensionMismatch map(+, A, spzeros((shapeA .- 1)...)) - # --> test map! entry point - fX = map(+, fA, fB); X = sparse(fX) - map!(+, X, A, B); X = sparse(fX) # warmup for @allocated - @test (@allocated map!(+, X, A, B)) == 0 - @test map!(+, X, A, B) == sparse(map!(+, fX, fA, fB)) - fX = map(*, fA, fB); X = sparse(fX) - map!(*, X, A, B); X = sparse(fX) # warmup for @allocated - @test (@allocated map!(*, X, A, B)) == 0 - @test map!(*, X, A, B) == sparse(map!(*, fX, fA, fB)) - @test map!(f, X, A, B) == sparse(map!(f, fX, fA, fB)) - @test_throws DimensionMismatch map!(f, X, A, spzeros((shapeA .- 1)...)) - end -end - -@testset "map[!] implementation capable of handling >2 (input) sparse vectors/matrices" begin - N, M = 10, 12 - f(x, y, z) = x + y + z + 1 - for shapeA in ((N,), (N, M)) - A, B, Co = sprand(shapeA..., 0.2), sprand(shapeA..., 0.2), sprand(shapeA..., 0.2) - C = ndims(Co) == 1 ? SparseVector{Float32,Int32}(Co) : SparseMatrixCSC{Float32,Int32}(Co) - # use different types to check internal type stability via allocation tests below - fA, fB, fC = map(Array, (A, B, C)) - # --> test map entry point - @test map(+, A, B, C) == sparse(map(+, fA, fB, fC)) - @test map(*, A, B, C) == sparse(map(*, fA, fB, fC)) - @test map(f, A, B, C) == sparse(map(f, fA, fB, fC)) - @test_throws DimensionMismatch map(+, A, B, spzeros(N, M - 1)) - # --> test map! entry point - fX = map(+, fA, fB, fC); X = sparse(fX) - map!(+, X, A, B, C); X = sparse(fX) # warmup for @allocated - @test (@allocated map!(+, X, A, B, C)) == 0 - @test map!(+, X, A, B, C) == sparse(map!(+, fX, fA, fB, fC)) - fX = map(*, fA, fB, fC); X = sparse(fX) - map!(*, X, A, B, C); X = sparse(fX) # warmup for @allocated - @test (@allocated map!(*, X, A, B, C)) == 0 - @test map!(*, X, A, B, C) == sparse(map!(*, fX, fA, fB, fC)) - @test map!(f, X, A, B, C) == sparse(map!(f, fX, fA, fB, fC)) - @test_throws DimensionMismatch map!(f, X, A, B, spzeros((shapeA .- 1)...)) - end -end - -@testset "broadcast! implementation specialized for solely an output sparse vector/matrix (no inputs)" begin - N, M, p = 10, 12, 0.4 - V, C = sprand(N, p), sprand(N, M, p) - fV, fC = Array(V), Array(C) - @test broadcast!(() -> 0, V) == sparse(broadcast!(() -> 0, fV)) - @test broadcast!(() -> 0, C) == sparse(broadcast!(() -> 0, fC)) - @test let z = 0, fz = 0; broadcast!(() -> z += 1, V) == broadcast!(() -> fz += 1, fV); end - @test let z = 0, fz = 0; broadcast!(() -> z += 1, C) == broadcast!(() -> fz += 1, fC); end -end - -@testset "broadcast implementation specialized for a single (input) sparse vector/matrix" begin - # broadcast for a single (input) sparse vector/matrix falls back to map, tested - # extensively above. here we simply lightly exercise the relevant broadcast entry - # point. - N, M, p = 10, 12, 0.4 - a, A = sprand(N, p), sprand(N, M, p) - fa, fA = Array(a), Array(A) - @test broadcast(sin, a) == sparse(broadcast(sin, fa)) - @test broadcast(sin, A) == sparse(broadcast(sin, fA)) -end - -@testset "broadcast! implementation specialized for a single (input) sparse vector/matrix" begin - N, M, p = 10, 12, 0.3 - f(x, y) = x + y + 1 - mats = (sprand(N, M, p), sprand(N, 1, p), sprand(1, M, p), sprand(1, 1, 1.0), spzeros(1, 1)) - vecs = (sprand(N, p), sprand(1, 1.0), spzeros(1)) - # --> test with matrix destination (Z/fZ) - fZ = Array(first(mats)) - for Xo in (mats..., vecs...) - X = ndims(Xo) == 1 ? SparseVector{Float32,Int32}(Xo) : SparseMatrixCSC{Float32,Int32}(Xo) - shapeX, fX = size(X), Array(X) - # --> test broadcast! entry point / zero-preserving op - broadcast!(sin, fZ, fX); Z = sparse(fZ) - broadcast!(sin, Z, X); Z = sparse(fZ) # warmup for @allocated - @test (@allocated broadcast!(sin, Z, X)) == 0 - @test broadcast!(sin, Z, X) == sparse(broadcast!(sin, fZ, fX)) - # --> test broadcast! entry point / not-zero-preserving op - broadcast!(cos, fZ, fX); Z = sparse(fZ) - broadcast!(cos, Z, X); Z = sparse(fZ) # warmup for @allocated - @test (@allocated broadcast!(cos, Z, X)) == 0 - @test broadcast!(cos, Z, X) == sparse(broadcast!(cos, fZ, fX)) - # --> test shape checks for broadcast! entry point - # TODO strengthen this test, avoiding dependence on checking whether - # broadcast_indices throws to determine whether sparse broadcast should throw - try - Base.Broadcast.check_broadcast_indices(indices(Z), spzeros((shapeX .- 1)...)) - catch - @test_throws DimensionMismatch broadcast!(sin, Z, spzeros((shapeX .- 1)...)) - end - end - # --> test with vector destination (V/fV) - fV = Array(first(vecs)) - for Xo in vecs # vector target - X = SparseVector{Float32,Int32}(Xo) - shapeX, fX = size(X), Array(X) - # --> test broadcast! entry point / zero-preserving op - broadcast!(sin, fV, fX); V = sparse(fV) - broadcast!(sin, V, X); V = sparse(fV) # warmup for @allocated - @test (@allocated broadcast!(sin, V, X)) == 0 - @test broadcast!(sin, V, X) == sparse(broadcast!(sin, fV, fX)) - # --> test broadcast! entry point / not-zero-preserving - broadcast!(cos, fV, fX); V = sparse(fV) - broadcast!(cos, V, X); V = sparse(fV) # warmup for @allocated - @test (@allocated broadcast!(cos, V, X)) == 0 - @test broadcast!(cos, V, X) == sparse(broadcast!(cos, fV, fX)) - # --> test shape checks for broadcast! entry point - # TODO strengthen this test, avoiding dependence on checking whether - # broadcast_indices throws to determine whether sparse broadcast should throw - try - Base.Broadcast.check_broadcast_indices(indices(V), spzeros((shapeX .- 1)...)) - catch - @test_throws DimensionMismatch broadcast!(sin, V, spzeros((shapeX .- 1)...)) - end - end - # Tests specific to #19895, i.e. for broadcast!(identity, C, A) specializations - Z = copy(first(mats)); fZ = Array(Z) - V = copy(first(vecs)); fV = Array(V) - for X in (mats..., vecs...) - @test broadcast!(identity, Z, X) == sparse(broadcast!(identity, fZ, Array(X))) - X isa SparseVector && @test broadcast!(identity, V, X) == sparse(broadcast!(identity, fV, Array(X))) - end -end - -@testset "broadcast[!] implementation specialized for pairs of (input) sparse vectors/matrices" begin - N, M, p = 10, 12, 0.3 - f(x, y) = x + y + 1 - mats = (sprand(N, M, p), sprand(N, 1, p), sprand(1, M, p), sprand(1, 1, 1.0), spzeros(1, 1)) - vecs = (sprand(N, p), sprand(1, 1.0), spzeros(1)) - tens = (mats..., vecs...) - fZ = Array(first(mats)) - for Xo in tens - X = ndims(Xo) == 1 ? SparseVector{Float32,Int32}(Xo) : SparseMatrixCSC{Float32,Int32}(Xo) - # use different types to check internal type stability via allocation tests below - shapeX, fX = size(X), Array(X) - for Y in tens - fY = Array(Y) - # --> test broadcast entry point - @test broadcast(+, X, Y) == sparse(broadcast(+, fX, fY)) - @test broadcast(*, X, Y) == sparse(broadcast(*, fX, fY)) - @test broadcast(f, X, Y) == sparse(broadcast(f, fX, fY)) - # TODO strengthen this test, avoiding dependence on checking whether - # broadcast_indices throws to determine whether sparse broadcast should throw - try - Base.Broadcast.broadcast_indices(spzeros((shapeX .- 1)...), Y) - catch - @test_throws DimensionMismatch broadcast(+, spzeros((shapeX .- 1)...), Y) - end - # --> test broadcast! entry point / +-like zero-preserving op - broadcast!(+, fZ, fX, fY); Z = sparse(fZ) - broadcast!(+, Z, X, Y); Z = sparse(fZ) # warmup for @allocated - @test (@allocated broadcast!(+, Z, X, Y)) == 0 - @test broadcast!(+, Z, X, Y) == sparse(broadcast!(+, fZ, fX, fY)) - # --> test broadcast! entry point / *-like zero-preserving op - broadcast!(*, fZ, fX, fY); Z = sparse(fZ) - broadcast!(*, Z, X, Y); Z = sparse(fZ) # warmup for @allocated - @test (@allocated broadcast!(*, Z, X, Y)) == 0 - @test broadcast!(*, Z, X, Y) == sparse(broadcast!(*, fZ, fX, fY)) - # --> test broadcast! entry point / not zero-preserving op - broadcast!(f, fZ, fX, fY); Z = sparse(fZ) - broadcast!(f, Z, X, Y); Z = sparse(fZ) # warmup for @allocated - @test (@allocated broadcast!(f, Z, X, Y)) == 0 - @test broadcast!(f, Z, X, Y) == sparse(broadcast!(f, fZ, fX, fY)) - # --> test shape checks for both broadcast and broadcast! entry points - # TODO strengthen this test, avoiding dependence on checking whether - # broadcast_indices throws to determine whether sparse broadcast should throw - try - Base.Broadcast.check_broadcast_indices(indices(Z), spzeros((shapeX .- 1)...), Y) - catch - @test_throws DimensionMismatch broadcast!(f, Z, spzeros((shapeX .- 1)...), Y) - end - end - end -end - -@testset "broadcast[!] implementation capable of handling >2 (input) sparse vectors/matrices" begin - N, M, p = 10, 12, 0.3 - f(x, y, z) = x + y + z + 1 - mats = (sprand(N, M, p), sprand(N, 1, p), sprand(1, M, p), sprand(1, 1, 1.0), spzeros(1, 1)) - vecs = (sprand(N, p), sprand(1, 1.0), spzeros(1)) - tens = (mats..., vecs...) - for Xo in tens - X = ndims(Xo) == 1 ? SparseVector{Float32,Int32}(Xo) : SparseMatrixCSC{Float32,Int32}(Xo) - # use different types to check internal type stability via allocation tests below - shapeX, fX = size(X), Array(X) - for Y in tens, Z in tens - fY, fZ = Array(Y), Array(Z) - # --> test broadcast entry point - @test broadcast(+, X, Y, Z) == sparse(broadcast(+, fX, fY, fZ)) - @test broadcast(*, X, Y, Z) == sparse(broadcast(*, fX, fY, fZ)) - @test broadcast(f, X, Y, Z) == sparse(broadcast(f, fX, fY, fZ)) - # TODO strengthen this test, avoiding dependence on checking whether - # broadcast_indices throws to determine whether sparse broadcast should throw - try - Base.Broadcast.broadcast_indices(spzeros((shapeX .- 1)...), Y, Z) - catch - @test_throws DimensionMismatch broadcast(+, spzeros((shapeX .- 1)...), Y, Z) - end - # --> test broadcast! entry point / +-like zero-preserving op - fQ = broadcast(+, fX, fY, fZ); Q = sparse(fQ) - broadcast!(+, Q, X, Y, Z); Q = sparse(fQ) # warmup for @allocated - @test (@allocated broadcast!(+, Q, X, Y, Z)) == 0 - @test broadcast!(+, Q, X, Y, Z) == sparse(broadcast!(+, fQ, fX, fY, fZ)) - # --> test broadcast! entry point / *-like zero-preserving op - fQ = broadcast(*, fX, fY, fZ); Q = sparse(fQ) - broadcast!(*, Q, X, Y, Z); Q = sparse(fQ) # warmup for @allocated - @test (@allocated broadcast!(*, Q, X, Y, Z)) == 0 - @test broadcast!(*, Q, X, Y, Z) == sparse(broadcast!(*, fQ, fX, fY, fZ)) - # --> test broadcast! entry point / not zero-preserving op - fQ = broadcast(f, fX, fY, fZ); Q = sparse(fQ) - broadcast!(f, Q, X, Y, Z); Q = sparse(fQ) # warmup for @allocated - @test_broken (@allocated broadcast!(f, Q, X, Y, Z)) == 0 - # the preceding test allocates 16 bytes in the entry point for broadcast!, but - # none of the earlier tests of the same code path allocate. no allocation shows - # up with --track-allocation=user. allocation shows up on the first line of the - # entry point for broadcast! with --track-allocation=all, but that first line - # almost certainly should not allocate. so not certain what's going on. - # additional info: occurs for broadcast!(f, Z, X) for Z and X of different - # shape, but not for Z and X of the same shape. - @test broadcast!(f, Q, X, Y, Z) == sparse(broadcast!(f, fQ, fX, fY, fZ)) - # --> test shape checks for both broadcast and broadcast! entry points - # TODO strengthen this test, avoiding dependence on checking whether - # broadcast_indices throws to determine whether sparse broadcast should throw - try - Base.Broadcast.check_broadcast_indices(indices(Q), spzeros((shapeX .- 1)...), Y, Z) - catch - @test_throws DimensionMismatch broadcast!(f, Q, spzeros((shapeX .- 1)...), Y, Z) - end - end - end -end - -@testset "sparse map/broadcast with result eltype not a concrete subtype of Number (#19561/#19589)" begin - N = 4 - A, fA = speye(N), eye(N) - B, fB = spzeros(1, N), zeros(1, N) - intorfloat_zeropres(xs...) = all(iszero, xs) ? zero(Float64) : Int(1) - stringorfloat_zeropres(xs...) = all(iszero, xs) ? zero(Float64) : "hello" - intorfloat_notzeropres(xs...) = all(iszero, xs) ? Int(1) : zero(Float64) - stringorfloat_notzeropres(xs...) = all(iszero, xs) ? "hello" : zero(Float64) - for fn in (intorfloat_zeropres, intorfloat_notzeropres, - stringorfloat_zeropres, stringorfloat_notzeropres) - @test map(fn, A) == sparse(map(fn, fA)) - @test broadcast(fn, A) == sparse(broadcast(fn, fA)) - @test broadcast(fn, A, B) == sparse(broadcast(fn, fA, fB)) - @test broadcast(fn, B, A) == sparse(broadcast(fn, fB, fA)) - end - for fn in (intorfloat_zeropres, stringorfloat_zeropres) - @test broadcast(fn, A, B, A) == sparse(broadcast(fn, fA, fB, fA)) - end -end - -@testset "broadcast[!] over combinations of scalars and sparse vectors/matrices" begin - N, M, p = 10, 12, 0.5 - elT = Float64 - s = Float32(2.0) - V = sprand(elT, N, p) - A = sprand(elT, N, M, p) - fV, fA = Array(V), Array(A) - # test combinations involving one to three scalars and one to five sparse vectors/matrices - spargseq, dargseq = Iterators.cycle((A, V)), Iterators.cycle((fA, fV)) - for nargs in 1:5 # number of tensor arguments - nargsl = cld(nargs, 2) # number in "left half" of tensor arguments - nargsr = fld(nargs, 2) # number in "right half" of tensor arguments - spargsl = tuple(Iterators.take(spargseq, nargsl)...) # "left half" of tensor args - spargsr = tuple(Iterators.take(spargseq, nargsr)...) # "right half" of tensor args - dargsl = tuple(Iterators.take(dargseq, nargsl)...) # "left half" of tensor args, densified - dargsr = tuple(Iterators.take(dargseq, nargsr)...) # "right half" of tensor args, densified - for (sparseargs, denseargs) in ( # argument combinations including scalars - # a few combinations involving one scalar - ((s, spargsl..., spargsr...), (s, dargsl..., dargsr...)), - ((spargsl..., s, spargsr...), (dargsl..., s, dargsr...)), - ((spargsl..., spargsr..., s), (dargsl..., dargsr..., s)), - # a few combinations involving two scalars - ((s, spargsl..., s, spargsr...), (s, dargsl..., s, dargsr...)), - ((s, spargsl..., spargsr..., s), (s, dargsl..., dargsr..., s)), - ((spargsl..., s, spargsr..., s), (dargsl..., s, dargsr..., s)), - ((s, s, spargsl..., spargsr...), (s, s, dargsl..., dargsr...)), - ((spargsl..., s, s, spargsr...), (dargsl..., s, s, dargsr...)), - ((spargsl..., spargsr..., s, s), (dargsl..., dargsr..., s, s)), - # a few combinations involving three scalars - ((s, spargsl..., s, spargsr..., s), (s, dargsl..., s, dargsr..., s)), - ((s, spargsl..., s, s, spargsr...), (s, dargsl..., s, s, dargsr...)), - ((spargsl..., s, s, spargsr..., s), (dargsl..., s, s, dargsr..., s)), - ((spargsl..., s, s, s, spargsr...), (dargsl..., s, s, s, dargsr...)), ) - # test broadcast entry point - @test broadcast(*, sparseargs...) == sparse(broadcast(*, denseargs...)) - @test isa(@inferred(broadcast(*, sparseargs...)), SparseMatrixCSC{elT}) - # test broadcast! entry point - fX = broadcast(*, sparseargs...); X = sparse(fX) - @test broadcast!(*, X, sparseargs...) == sparse(broadcast!(*, fX, denseargs...)) - @test isa(@inferred(broadcast!(*, X, sparseargs...)), SparseMatrixCSC{elT}) - X = sparse(fX) # reset / warmup for @allocated test - @test_broken (@allocated broadcast!(*, X, sparseargs...)) == 0 - # This test (and the analog below) fails for three reasons: - # (1) In all cases, generating the closures that capture the scalar arguments - # results in allocation, not sure why. - # (2) In some cases, though _broadcast_eltype (which wraps _return_type) - # consistently provides the correct result eltype when passed the closure - # that incorporates the scalar arguments to broadcast (and, with #19667, - # is inferable, so the overall return type from broadcast is inferred), - # in some cases inference seems unable to determine the return type of - # direct calls to that closure. This issue causes variables in both the - # broadcast[!] entry points (fofzeros = f(_zeros_eltypes(args...)...)) and - # the driver routines (Cx in _map_zeropres! and _broadcast_zeropres!) to have - # inferred type Any, resulting in allocation and lackluster performance. - # (3) The sparseargs... splat in the call above allocates a bit, but of course - # that issue is negligible and perhaps could be accounted for in the test. - end - end - # test combinations at the limit of inference (eight arguments net) - for (sparseargs, denseargs) in ( - ((s, s, s, A, s, s, s, s), (s, s, s, fA, s, s, s, s)), # seven scalars, one sparse matrix - ((s, s, V, s, s, A, s, s), (s, s, fV, s, s, fA, s, s)), # six scalars, two sparse vectors/matrices - ((s, s, V, s, A, s, V, s), (s, s, fV, s, fA, s, fV, s)), # five scalars, three sparse vectors/matrices - ((s, V, s, A, s, V, s, A), (s, fV, s, fA, s, fV, s, fA)), # four scalars, four sparse vectors/matrices - ((s, V, A, s, V, A, s, A), (s, fV, fA, s, fV, fA, s, fA)), # three scalars, five sparse vectors/matrices - ((V, A, V, s, A, V, A, s), (fV, fA, fV, s, fA, fV, fA, s)), # two scalars, six sparse vectors/matrices - ((V, A, V, A, s, V, A, V), (fV, fA, fV, fA, s, fV, fA, fV)) ) # one scalar, seven sparse vectors/matrices - # test broadcast entry point - @test broadcast(*, sparseargs...) == sparse(broadcast(*, denseargs...)) - @test isa(@inferred(broadcast(*, sparseargs...)), SparseMatrixCSC{elT}) - # test broadcast! entry point - fX = broadcast(*, sparseargs...); X = sparse(fX) - @test broadcast!(*, X, sparseargs...) == sparse(broadcast!(*, fX, denseargs...)) - @test isa(@inferred(broadcast!(*, X, sparseargs...)), SparseMatrixCSC{elT}) - X = sparse(fX) # reset / warmup for @allocated test - @test_broken (@allocated broadcast!(*, X, sparseargs...)) == 0 - # please see the note a few lines above re. this @test_broken - end -end - -@testset "broadcast[!] over combinations of scalars, sparse arrays, structured matrices, and dense vectors/matrices" begin - N, p = 10, 0.4 - s = rand() - V = sprand(N, p) - A = sprand(N, N, p) - Z = copy(A) - sparsearrays = (V, A) - fV, fA = map(Array, sparsearrays) - D = Diagonal(rand(N)) - B = Bidiagonal(rand(N), rand(N - 1), true) - T = Tridiagonal(rand(N - 1), rand(N), rand(N - 1)) - S = SymTridiagonal(rand(N), rand(N - 1)) - structuredarrays = (D, B, T, S) - fstructuredarrays = map(Array, structuredarrays) - for (X, fX) in zip(structuredarrays, fstructuredarrays) - @test (Q = broadcast(sin, X); Q isa SparseMatrixCSC && Q == sparse(broadcast(sin, fX))) - @test broadcast!(sin, Z, X) == sparse(broadcast(sin, fX)) - @test (Q = broadcast(cos, X); Q isa SparseMatrixCSC && Q == sparse(broadcast(cos, fX))) - @test broadcast!(cos, Z, X) == sparse(broadcast(cos, fX)) - @test (Q = broadcast(*, s, X); Q isa SparseMatrixCSC && Q == sparse(broadcast(*, s, fX))) - @test broadcast!(*, Z, s, X) == sparse(broadcast(*, s, fX)) - @test (Q = broadcast(+, V, A, X); Q isa SparseMatrixCSC && Q == sparse(broadcast(+, fV, fA, fX))) - @test broadcast!(+, Z, V, A, X) == sparse(broadcast(+, fV, fA, fX)) - @test (Q = broadcast(*, s, V, A, X); Q isa SparseMatrixCSC && Q == sparse(broadcast(*, s, fV, fA, fX))) - @test broadcast!(*, Z, s, V, A, X) == sparse(broadcast(*, s, fV, fA, fX)) - for (Y, fY) in zip(structuredarrays, fstructuredarrays) - @test (Q = broadcast(+, X, Y); Q isa SparseMatrixCSC && Q == sparse(broadcast(+, fX, fY))) - @test broadcast!(+, Z, X, Y) == sparse(broadcast(+, fX, fY)) - @test (Q = broadcast(*, X, Y); Q isa SparseMatrixCSC && Q == sparse(broadcast(*, fX, fY))) - @test broadcast!(*, Z, X, Y) == sparse(broadcast(*, fX, fY)) - end - end - C = Array(sprand(N, 0.4)) - M = Array(sprand(N, N, 0.4)) - densearrays = (C, M) - fD, fB = Array(D), Array(B) - for X in densearrays - @test broadcast(+, D, X)::SparseMatrixCSC == sparse(broadcast(+, fD, X)) - @test broadcast!(+, Z, D, X) == sparse(broadcast(+, fD, X)) - @test broadcast(*, s, B, X)::SparseMatrixCSC == sparse(broadcast(*, s, fB, X)) - @test broadcast!(*, Z, s, B, X) == sparse(broadcast(*, s, fB, X)) - @test broadcast(+, V, B, X)::SparseMatrixCSC == sparse(broadcast(+, fV, fB, X)) - @test broadcast!(+, Z, V, B, X) == sparse(broadcast(+, fV, fB, X)) - @test broadcast(+, V, A, X)::SparseMatrixCSC == sparse(broadcast(+, fV, fA, X)) - @test broadcast!(+, Z, V, A, X) == sparse(broadcast(+, fV, fA, X)) - @test broadcast(*, s, V, A, X)::SparseMatrixCSC == sparse(broadcast(*, s, fV, fA, X)) - @test broadcast!(*, Z, s, V, A, X) == sparse(broadcast(*, s, fV, fA, X)) - # Issue #20954 combinations of sparse arrays and RowVectors - @test broadcast(+, A, X')::SparseMatrixCSC == sparse(broadcast(+, fA, X')) - @test broadcast(*, V, X')::SparseMatrixCSC == sparse(broadcast(*, fV, X')) - end -end - -@testset "broadcast! where the destination is a structured matrix" begin - # Where broadcast!'s destination is a structured matrix, broadcast! should fall back - # to the generic AbstractArray broadcast! code (at least for now). - N, p = 5, 0.4 - A = sprand(N, N, p) - sA = A + transpose(A) - D = Diagonal(rand(N)) - B = Bidiagonal(rand(N), rand(N - 1), true) - T = Tridiagonal(rand(N - 1), rand(N), rand(N - 1)) - @test broadcast!(sin, copy(D), D) == Diagonal(sin.(D)) - @test broadcast!(sin, copy(B), B) == Bidiagonal(sin.(B), true) - @test broadcast!(sin, copy(T), T) == Tridiagonal(sin.(T)) - @test broadcast!(*, copy(D), D, A) == Diagonal(broadcast(*, D, A)) - @test broadcast!(*, copy(B), B, A) == Bidiagonal(broadcast(*, B, A), true) - @test broadcast!(*, copy(T), T, A) == Tridiagonal(broadcast(*, T, A)) - # SymTridiagonal (and similar symmetric matrix types) do not support setindex! - # off the diagonal, and so cannot serve as a destination for broadcast! -end - -@testset "map[!] over combinations of sparse and structured matrices" begin - N, p = 10, 0.4 - A = sprand(N, N, p) - Z, fA = copy(A), Array(A) - D = Diagonal(rand(N)) - B = Bidiagonal(rand(N), rand(N - 1), true) - T = Tridiagonal(rand(N - 1), rand(N), rand(N - 1)) - S = SymTridiagonal(rand(N), rand(N - 1)) - structuredarrays = (D, B, T, S) - fstructuredarrays = map(Array, structuredarrays) - for (X, fX) in zip(structuredarrays, fstructuredarrays) - @test (Q = map(sin, X); Q isa SparseMatrixCSC && Q == sparse(map(sin, fX))) - @test map!(sin, Z, X) == sparse(map(sin, fX)) - @test (Q = map(cos, X); Q isa SparseMatrixCSC && Q == sparse(map(cos, fX))) - @test map!(cos, Z, X) == sparse(map(cos, fX)) - @test (Q = map(+, A, X); Q isa SparseMatrixCSC && Q == sparse(map(+, fA, fX))) - @test map!(+, Z, A, X) == sparse(map(+, fA, fX)) - for (Y, fY) in zip(structuredarrays, fstructuredarrays) - @test (Q = map(+, X, Y); Q isa SparseMatrixCSC && Q == sparse(map(+, fX, fY))) - @test map!(+, Z, X, Y) == sparse(map(+, fX, fY)) - @test (Q = map(*, X, Y); Q isa SparseMatrixCSC && Q == sparse(map(*, fX, fY))) - @test map!(*, Z, X, Y) == sparse(map(*, fX, fY)) - @test (Q = map(+, X, A, Y); Q isa SparseMatrixCSC && Q == sparse(map(+, fX, fA, fY))) - @test map!(+, Z, X, A, Y) == sparse(map(+, fX, fA, fY)) - end - end -end - -# Older tests of sparse broadcast, now largely covered by the tests above -@testset "assorted tests of sparse broadcast over two input arguments" begin - N, p = 10, 0.3 - A, B, CF = sprand(N, N, p), sprand(N, N, p), rand(N, N) - AF, BF, C = Array(A), Array(B), sparse(CF) - - @test A .* B == AF .* BF - @test A[1,:] .* B == AF[1,:] .* BF - @test A[:,1] .* B == AF[:,1] .* BF - @test A .* B[1,:] == AF .* BF[1,:] - @test A .* B[:,1] == AF .* BF[:,1] - - @test A .* B == AF .* BF - @test A[1,:] .* BF == AF[1,:] .* BF - @test A[:,1] .* BF == AF[:,1] .* BF - @test A .* BF[1,:] == AF .* BF[1,:] - @test A .* BF[:,1] == AF .* BF[:,1] - - @test A .* B == AF .* BF - @test AF[1,:] .* B == AF[1,:] .* BF - @test AF[:,1] .* B == AF[:,1] .* BF - @test AF .* B[1,:] == AF .* BF[1,:] - @test AF .* B[:,1] == AF .* BF[:,1] - - @test A .* B == AF .* BF - @test A[1,:] .* B == AF[1,:] .* BF - @test A[:,1] .* B == AF[:,1] .* BF - @test A .* B[1,:] == AF .* BF[1,:] - @test A .* B[:,1] == AF .* BF[:,1] - - @test A .* 3 == AF .* 3 - @test 3 .* A == 3 .* AF - @test A[1,:] .* 3 == AF[1,:] .* 3 - @test A[:,1] .* 3 == AF[:,1] .* 3 - - @test A .- 3 == AF .- 3 - @test 3 .- A == 3 .- AF - @test A .- B == AF .- BF - @test A - AF == zeros(AF) - @test AF - A == zeros(AF) - @test A[1,:] .- B == AF[1,:] .- BF - @test A[:,1] .- B == AF[:,1] .- BF - @test A .- B[1,:] == AF .- BF[1,:] - @test A .- B[:,1] == AF .- BF[:,1] - - @test A .+ 3 == AF .+ 3 - @test 3 .+ A == 3 .+ AF - @test A .+ B == AF .+ BF - @test A + AF == AF + A - @test (A .< B) == (AF .< BF) - @test (A .!= B) == (AF .!= BF) - - @test A ./ 3 == AF ./ 3 - @test A .\ 3 == AF .\ 3 - @test 3 ./ A == 3 ./ AF - @test 3 .\ A == 3 .\ AF - @test A .\ C == AF .\ CF - @test A ./ C == AF ./ CF - @test A ./ CF[:,1] == AF ./ CF[:,1] - @test A .\ CF[:,1] == AF .\ CF[:,1] - @test BF ./ C == BF ./ CF - @test BF .\ C == BF .\ CF - - @test A .^ 3 == AF .^ 3 - @test 3 .^ A == 3 .^ AF - @test A .^ BF[:,1] == AF .^ BF[:,1] - @test BF[:,1] .^ A == BF[:,1] .^ AF - - @test spzeros(0,0) + spzeros(0,0) == zeros(0,0) - @test spzeros(0,0) * spzeros(0,0) == zeros(0,0) - @test spzeros(1,0) .+ spzeros(2,1) == zeros(2,0) - @test spzeros(1,0) .* spzeros(2,1) == zeros(2,0) - @test spzeros(1,2) .+ spzeros(0,1) == zeros(0,2) - @test spzeros(1,2) .* spzeros(0,1) == zeros(0,2) -end diff --git a/julia-0.6.3/share/julia/test/sparse/sparse.jl b/julia-0.6.3/share/julia/test/sparse/sparse.jl deleted file mode 100644 index b5e7b89..0000000 --- a/julia-0.6.3/share/julia/test/sparse/sparse.jl +++ /dev/null @@ -1,1773 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -@testset "issparse" begin - @test issparse(sparse(ones(5,5))) - @test !issparse(ones(5,5)) -end - -@testset "indtype" begin - @test Base.SparseArrays.indtype(sparse(ones(Int8,2),ones(Int8,2),rand(2))) == Int8 -end - -@testset "sparse matrix construction" begin - @test isequal(Array(sparse(complex.(ones(5,5), ones(5,5)))), complex.(ones(5,5), ones(5,5))) - @test_throws ArgumentError sparse([1,2,3], [1,2], [1,2,3], 3, 3) - @test_throws ArgumentError sparse([1,2,3], [1,2,3], [1,2], 3, 3) - @test_throws ArgumentError sparse([1,2,3], [1,2,3], [1,2,3], 0, 1) - @test_throws ArgumentError sparse([1,2,3], [1,2,3], [1,2,3], 1, 0) - @test_throws ArgumentError sparse([1,2,4], [1,2,3], [1,2,3], 3, 3) - @test_throws ArgumentError sparse([1,2,3], [1,2,4], [1,2,3], 3, 3) - @test isequal(sparse(Int[], Int[], Int[], 0, 0), SparseMatrixCSC(0, 0, Int[1], Int[], Int[])) - @test sparse(Any[1,2,3], Any[1,2,3], Any[1,1,1]) == sparse([1,2,3], [1,2,3], [1,1,1]) - @test sparse(Any[1,2,3], Any[1,2,3], Any[1,1,1], 5, 4) == sparse([1,2,3], [1,2,3], [1,1,1], 5, 4) -end - -se33 = speye(3) -do33 = ones(3) - -@testset "sparse binary operations" begin - @test isequal(se33 * se33, se33) - - @test all(Array(se33 + convert(SparseMatrixCSC{Float32,Int32}, se33)) == 2*eye(3)) - @test all(Array(se33 * convert(SparseMatrixCSC{Float32,Int32}, se33)) == eye(3)) - - @testset "shape checks for sparse elementwise binary operations equivalent to map" begin - sqrfloatmat, colfloatmat = sprand(4, 4, 0.5), sprand(4, 1, 0.5) - @test_throws DimensionMismatch (+)(sqrfloatmat, colfloatmat) - @test_throws DimensionMismatch (-)(sqrfloatmat, colfloatmat) - @test_throws DimensionMismatch map(min, sqrfloatmat, colfloatmat) - @test_throws DimensionMismatch map(max, sqrfloatmat, colfloatmat) - sqrboolmat, colboolmat = sprand(Bool, 4, 4, 0.5), sprand(Bool, 4, 1, 0.5) - @test_throws DimensionMismatch map(&, sqrboolmat, colboolmat) - @test_throws DimensionMismatch map(|, sqrboolmat, colboolmat) - @test_throws DimensionMismatch map(xor, sqrboolmat, colboolmat) - end -end - -@testset "concatenation tests" begin - @testset "horizontal concatenation" begin - @test all([se33 se33] == sparse([1, 2, 3, 1, 2, 3], [1, 2, 3, 4, 5, 6], ones(6))) - end - - @testset "vertical concatenation" begin - @test all([se33; se33] == sparse([1, 4, 2, 5, 3, 6], [1, 1, 2, 2, 3, 3], ones(6))) - se33_32bit = convert(SparseMatrixCSC{Float32,Int32}, se33) - @test all([se33; se33_32bit] == sparse([1, 4, 2, 5, 3, 6], [1, 1, 2, 2, 3, 3], ones(6))) - end - - se44 = speye(4) - sz42 = spzeros(4, 2) - sz41 = spzeros(4, 1) - sz34 = spzeros(3, 4) - se77 = speye(7) - @testset "h+v concatenation" begin - @test all([se44 sz42 sz41; sz34 se33] == se77) - end - - @testset "blkdiag concatenation" begin - @test all(blkdiag(se33, se33) == sparse([1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 5, 6], ones(6))) - end - - @testset "concatenation promotion" begin - sz41_f32 = spzeros(Float32, 4, 1) - se33_i32 = speye(Int32, 3, 3) - @test all([se44 sz42 sz41_f32; sz34 se33_i32] == se77) - end - - @testset "mixed sparse-dense concatenation" begin - sz33 = spzeros(3, 3) - de33 = eye(3) - @test all([se33 de33; sz33 se33] == Array([se33 se33; sz33 se33 ])) - end - - # check splicing + concatenation on random instances, with nested vcat and also side-checks sparse ref - @testset "splicing + concatenation on random instances" begin - for i = 1 : 10 - a = sprand(5, 4, 0.5) - @test all([a[1:2,1:2] a[1:2,3:4]; a[3:5,1] [a[3:4,2:4]; a[5:5,2:4]]] == a) - end - end -end - -a116 = copy(reshape(1:16, 4, 4)) -s116 = sparse(a116) - -@testset "sparse ref" begin - p = [4, 1, 2, 3, 2] - @test Array(s116[p,:]) == a116[p,:] - @test Array(s116[:,p]) == a116[:,p] - @test Array(s116[p,p]) == a116[p,p] -end - -@testset "sparse assignment" begin - p = [4, 1, 3] - a116[p, p] = -1 - s116[p, p] = -1 - @test a116 == s116 - - p = [2, 1, 4] - a116[p, p] = reshape(1:9, 3, 3) - s116[p, p] = reshape(1:9, 3, 3) - @test a116 == s116 -end - -@testset "squeeze" begin - for i = 1:5 - am = sprand(20, 1, 0.2) - av = squeeze(am, 2) - @test ndims(av) == 1 - @test all(av.==am) - am = sprand(1, 20, 0.2) - av = squeeze(am, 1) - @test ndims(av) == 1 - @test all(av.'.==am) - end -end - -@testset "matrix-vector multiplication (non-square)" begin - for i = 1:5 - a = sprand(10, 5, 0.5) - b = rand(5) - @test maximum(abs.(a*b - Array(a)*b)) < 100*eps() - end -end - -@testset "sparse matrix * BitArray" begin - A = sprand(5,5,0.2) - B = trues(5) - @test A*B ≈ Array(A)*B - B = trues(5,5) - @test A*B ≈ Array(A)*B - @test B*A ≈ B*Array(A) -end - -@testset "complex matrix-vector multiplication and left-division" begin - if Base.USE_GPL_LIBS - for i = 1:5 - a = speye(5) + 0.1*sprandn(5, 5, 0.2) - b = randn(5,3) + im*randn(5,3) - c = randn(5) + im*randn(5) - d = randn(5) + im*randn(5) - α = rand(Complex128) - β = rand(Complex128) - @test (maximum(abs.(a*b - Array(a)*b)) < 100*eps()) - @test (maximum(abs.(A_mul_B!(similar(b), a, b) - Array(a)*b)) < 100*eps()) # for compatibility with present matmul API. Should go away eventually. - @test (maximum(abs.(A_mul_B!(similar(c), a, c) - Array(a)*c)) < 100*eps()) # for compatibility with present matmul API. Should go away eventually. - @test (maximum(abs.(At_mul_B!(similar(b), a, b) - Array(a).'*b)) < 100*eps()) # for compatibility with present matmul API. Should go away eventually. - @test (maximum(abs.(At_mul_B!(similar(c), a, c) - Array(a).'*c)) < 100*eps()) # for compatibility with present matmul API. Should go away eventually. - @test (maximum(abs.(a'b - Array(a)'b)) < 100*eps()) - @test (maximum(abs.(a.'b - Array(a).'b)) < 100*eps()) - @test (maximum(abs.(a\b - Array(a)\b)) < 1000*eps()) - @test (maximum(abs.(a'\b - Array(a')\b)) < 1000*eps()) - @test (maximum(abs.(a.'\b - Array(a.')\b)) < 1000*eps()) - @test (maximum(abs.((a'*c + d) - (Array(a)'*c + d))) < 1000*eps()) - @test (maximum(abs.((α*a.'*c + β*d) - (α*Array(a).'*c + β*d))) < 1000*eps()) - @test (maximum(abs.((a.'*c + d) - (Array(a).'*c + d))) < 1000*eps()) - c = randn(6) + im*randn(6) - @test_throws DimensionMismatch α*a.'*c + β*c - @test_throws DimensionMismatch α*a.'*ones(5) + β*c - - a = speye(5) + 0.1*sprandn(5, 5, 0.2) + 0.1*im*sprandn(5, 5, 0.2) - b = randn(5,3) - @test (maximum(abs.(a*b - Array(a)*b)) < 100*eps()) - @test (maximum(abs.(a'b - Array(a)'b)) < 100*eps()) - @test (maximum(abs.(a.'b - Array(a).'b)) < 100*eps()) - @test (maximum(abs.(a\b - Array(a)\b)) < 1000*eps()) - @test (maximum(abs.(a'\b - Array(a')\b)) < 1000*eps()) - @test (maximum(abs.(a.'\b - Array(a.')\b)) < 1000*eps()) - - a = speye(5) + tril(0.1*sprandn(5, 5, 0.2)) - b = randn(5,3) + im*randn(5,3) - @test (maximum(abs.(a*b - Array(a)*b)) < 100*eps()) - @test (maximum(abs.(a'b - Array(a)'b)) < 100*eps()) - @test (maximum(abs.(a.'b - Array(a).'b)) < 100*eps()) - @test (maximum(abs.(a\b - Array(a)\b)) < 1000*eps()) - @test (maximum(abs.(a'\b - Array(a')\b)) < 1000*eps()) - @test (maximum(abs.(a.'\b - Array(a.')\b)) < 1000*eps()) - - a = speye(5) + tril(0.1*sprandn(5, 5, 0.2) + 0.1*im*sprandn(5, 5, 0.2)) - b = randn(5,3) - @test (maximum(abs.(a*b - Array(a)*b)) < 100*eps()) - @test (maximum(abs.(a'b - Array(a)'b)) < 100*eps()) - @test (maximum(abs.(a.'b - Array(a).'b)) < 100*eps()) - @test (maximum(abs.(a\b - Array(a)\b)) < 1000*eps()) - @test (maximum(abs.(a'\b - Array(a')\b)) < 1000*eps()) - @test (maximum(abs.(a.'\b - Array(a.')\b)) < 1000*eps()) - - a = speye(5) + triu(0.1*sprandn(5, 5, 0.2)) - b = randn(5,3) + im*randn(5,3) - @test (maximum(abs.(a*b - Array(a)*b)) < 100*eps()) - @test (maximum(abs.(a'b - Array(a)'b)) < 100*eps()) - @test (maximum(abs.(a.'b - Array(a).'b)) < 100*eps()) - @test (maximum(abs.(a\b - Array(a)\b)) < 1000*eps()) - @test (maximum(abs.(a'\b - Array(a')\b)) < 1000*eps()) - @test (maximum(abs.(a.'\b - Array(a.')\b)) < 1000*eps()) - - a = speye(5) + triu(0.1*sprandn(5, 5, 0.2) + 0.1*im*sprandn(5, 5, 0.2)) - b = randn(5,3) - @test (maximum(abs.(a*b - Array(a)*b)) < 100*eps()) - @test (maximum(abs.(a'b - Array(a)'b)) < 100*eps()) - @test (maximum(abs.(a.'b - Array(a).'b)) < 100*eps()) - @test (maximum(abs.(a\b - Array(a)\b)) < 1000*eps()) - @test (maximum(abs.(a'\b - Array(a')\b)) < 1000*eps()) - @test (maximum(abs.(a.'\b - Array(a.')\b)) < 1000*eps()) - - a = speye(5) + triu(0.1*sprandn(5, 5, 0.2)) - b = randn(5,3) + im*randn(5,3) - @test (maximum(abs.(a*b - Array(a)*b)) < 100*eps()) - @test (maximum(abs.(a'b - Array(a)'b)) < 100*eps()) - @test (maximum(abs.(a.'b - Array(a).'b)) < 100*eps()) - @test (maximum(abs.(a\b - Array(a)\b)) < 1000*eps()) - @test (maximum(abs.(a'\b - Array(a')\b)) < 1000*eps()) - @test (maximum(abs.(a.'\b - Array(a.')\b)) < 1000*eps()) - - a = spdiagm(randn(5)) + im*spdiagm(randn(5)) - b = randn(5,3) - @test (maximum(abs.(a*b - Array(a)*b)) < 100*eps()) - @test (maximum(abs.(a'b - Array(a)'b)) < 100*eps()) - @test (maximum(abs.(a.'b - Array(a).'b)) < 100*eps()) - @test (maximum(abs.(a\b - Array(a)\b)) < 1000*eps()) - @test (maximum(abs.(a'\b - Array(a')\b)) < 1000*eps()) - @test (maximum(abs.(a.'\b - Array(a.')\b)) < 1000*eps()) - - b = randn(5,3) + im*randn(5,3) - @test (maximum(abs.(a*b - Array(a)*b)) < 100*eps()) - @test (maximum(abs.(a'b - Array(a)'b)) < 100*eps()) - @test (maximum(abs.(a.'b - Array(a).'b)) < 100*eps()) - @test (maximum(abs.(a\b - Array(a)\b)) < 1000*eps()) - @test (maximum(abs.(a'\b - Array(a')\b)) < 1000*eps()) - @test (maximum(abs.(a.'\b - Array(a.')\b)) < 1000*eps()) - end - end -end - -@testset "matrix multiplication and kron" begin - for i = 1:5 - a = sprand(10, 5, 0.7) - b = sprand(5, 15, 0.3) - @test maximum(abs.(a*b - Array(a)*Array(b))) < 100*eps() - @test maximum(abs.(Base.SparseArrays.spmatmul(a,b,sortindices=:sortcols) - Array(a)*Array(b))) < 100*eps() - @test maximum(abs.(Base.SparseArrays.spmatmul(a,b,sortindices=:doubletranspose) - Array(a)*Array(b))) < 100*eps() - @test Array(kron(a,b)) == kron(Array(a), Array(b)) - @test Array(kron(Array(a),b)) == kron(Array(a), Array(b)) - @test Array(kron(a,Array(b))) == kron(Array(a), Array(b)) - c = sparse(rand(Float32,5,5)) - d = sparse(rand(Float64,5,5)) - @test Array(kron(c,d)) == kron(Array(c),Array(d)) - f = Diagonal(rand(5)) - @test Array(a*f) == Array(a)*f - @test Array(f*b) == f*Array(b) - end -end - -sA = sprandn(3, 7, 0.5) -sC = similar(sA) -dA = Array(sA) -b = randn(7) - -@testset "scale and scale!" begin - @test dA * Diagonal(b) == sA * Diagonal(b) - @test dA * Diagonal(b) == scale!(sC, sA, b) - @test dA * Diagonal(b) == scale!(copy(sA), b) - b = randn(3) - @test Diagonal(b) * dA == Diagonal(b) * sA - @test Diagonal(b) * dA == scale!(sC, b, sA) - @test Diagonal(b) * dA == scale!(b, copy(sA)) - - @test dA * 0.5 == sA * 0.5 - @test dA * 0.5 == scale!(sC, sA, 0.5) - @test dA * 0.5 == scale!(copy(sA), 0.5) - @test 0.5 * dA == 0.5 * sA - @test 0.5 * dA == scale!(sC, sA, 0.5) - @test 0.5 * dA == scale!(0.5, copy(sA)) - @test scale!(sC, 0.5, sA) == scale!(sC, sA, 0.5) -end - -@testset "copy!" begin - A = sprand(5, 5, 0.2) - B = sprand(5, 5, 0.2) - copy!(A, B) - @test A == B - @test pointer(A.nzval) != pointer(B.nzval) - @test pointer(A.rowval) != pointer(B.rowval) - @test pointer(A.colptr) != pointer(B.colptr) - # Test size(A) != size(B), but length(A) == length(B) - B = sprand(25, 1, 0.2) - copy!(A, B) - @test A[:] == B[:] - # Test various size(A) / size(B) combinations - for mA in [5, 10, 20], nA in [5, 10, 20], mB in [5, 10, 20], nB in [5, 10, 20] - A = sprand(mA,nA,0.4) - Aorig = copy(A) - B = sprand(mB,nB,0.4) - if mA*nA >= mB*nB - copy!(A,B) - @assert(A[1:length(B)] == B[:]) - @assert(A[length(B)+1:end] == Aorig[length(B)+1:end]) - else - @test_throws BoundsError copy!(A,B) - end - end - # Test eltype(A) != eltype(B), size(A) != size(B) - A = sprand(5, 5, 0.2) - Aorig = copy(A) - B = sparse(rand(Float32, 3, 3)) - copy!(A, B) - @test A[1:9] == B[:] - @test A[10:end] == Aorig[10:end] - # Test eltype(A) != eltype(B), size(A) == size(B) - A = sparse(rand(Float64, 3, 3)) - B = sparse(rand(Float32, 3, 3)) - copy!(A, B) - @test A == B -end - -@testset "conj" begin - cA = sprandn(5,5,0.2) + im*sprandn(5,5,0.2) - @test Array(conj.(cA)) == conj(Array(cA)) - @test Array(conj!(copy(cA))) == conj(Array(cA)) -end - -@testset "SparseMatrixCSC [c]transpose[!] and permute[!]" begin - smalldim = 5 - largedim = 10 - nzprob = 0.4 - (m, n) = (smalldim, smalldim) - A = sprand(m, n, nzprob) - X = similar(A) - C = transpose(A) - p = randperm(m) - q = randperm(n) - @testset "common error checking of [c]transpose! methods (ftranspose!)" begin - @test_throws DimensionMismatch transpose!(A[:, 1:(smalldim - 1)], A) - @test_throws DimensionMismatch transpose!(A[1:(smalldim - 1), 1], A) - @test_throws ArgumentError transpose!((B = similar(A); resize!(B.rowval, nnz(A) - 1); B), A) - @test_throws ArgumentError transpose!((B = similar(A); resize!(B.nzval, nnz(A) - 1); B), A) - end - @testset "common error checking of permute[!] methods / source-perm compat" begin - @test_throws DimensionMismatch permute(A, p[1:(end - 1)], q) - @test_throws DimensionMismatch permute(A, p, q[1:(end - 1)]) - end - @testset "common error checking of permute[!] methods / source-dest compat" begin - @test_throws DimensionMismatch permute!(A[1:(m - 1), :], A, p, q) - @test_throws DimensionMismatch permute!(A[:, 1:(m - 1)], A, p, q) - @test_throws ArgumentError permute!((Y = copy(X); resize!(Y.rowval, nnz(A) - 1); Y), A, p, q) - @test_throws ArgumentError permute!((Y = copy(X); resize!(Y.nzval, nnz(A) - 1); Y), A, p, q) - end - @testset "common error checking of permute[!] methods / source-workmat compat" begin - @test_throws DimensionMismatch permute!(X, A, p, q, C[1:(m - 1), :]) - @test_throws DimensionMismatch permute!(X, A, p, q, C[:, 1:(m - 1)]) - @test_throws ArgumentError permute!(X, A, p, q, (D = copy(C); resize!(D.rowval, nnz(A) - 1); D)) - @test_throws ArgumentError permute!(X, A, p, q, (D = copy(C); resize!(D.nzval, nnz(A) - 1); D)) - end - @testset "common error checking of permute[!] methods / source-workcolptr compat" begin - @test_throws DimensionMismatch permute!(A, p, q, C, Vector{eltype(A.rowval)}(length(A.colptr) - 1)) - end - @testset "common error checking of permute[!] methods / permutation validity" begin - @test_throws ArgumentError permute!(A, (r = copy(p); r[2] = r[1]; r), q) - @test_throws ArgumentError permute!(A, (r = copy(p); r[2] = m + 1; r), q) - @test_throws ArgumentError permute!(A, p, (r = copy(q); r[2] = r[1]; r)) - @test_throws ArgumentError permute!(A, p, (r = copy(q); r[2] = n + 1; r)) - end - @testset "overall functionality of [c]transpose[!] and permute[!]" begin - for (m, n) in ((smalldim, smalldim), (smalldim, largedim), (largedim, smalldim)) - A = sprand(m, n, nzprob) - At = transpose(A) - # transpose[!] - fullAt = transpose(Array(A)) - @test transpose(A) == fullAt - @test transpose!(similar(At), A) == fullAt - # ctranspose[!] - C = A + im*A/2 - fullCh = ctranspose(Array(C)) - @test ctranspose(C) == fullCh - @test ctranspose!(similar(sparse(fullCh)), C) == fullCh - # permute[!] - p = randperm(m) - q = randperm(n) - fullPAQ = Array(A)[p,q] - @test permute(A, p, q) == sparse(Array(A[p,q])) - @test permute!(similar(A), A, p, q) == fullPAQ - @test permute!(similar(A), A, p, q, similar(At)) == fullPAQ - @test permute!(copy(A), p, q) == fullPAQ - @test permute!(copy(A), p, q, similar(At)) == fullPAQ - @test permute!(copy(A), p, q, similar(At), similar(A.colptr)) == fullPAQ - end - end -end - -@testset "transpose of SubArrays" begin - A = view(sprandn(10, 10, 0.3), 1:4, 1:4) - @test transpose(Array(A)) == Array(transpose(A)) - @test ctranspose(Array(A)) == Array(ctranspose(A)) -end - -@testset "exp" begin - A = sprandn(5,5,0.2) - @test e.^A ≈ e.^Array(A) -end - -@testset "reductions" begin - pA = sparse(rand(3, 7)) - - for arr in (se33, sA, pA) - for f in (sum, prod, minimum, maximum, var) - farr = Array(arr) - @test f(arr) ≈ f(farr) - @test f(arr, 1) ≈ f(farr, 1) - @test f(arr, 2) ≈ f(farr, 2) - @test f(arr, (1, 2)) ≈ [f(farr)] - @test isequal(f(arr, 3), f(farr, 3)) - end - end - - for f in (sum, prod, minimum, maximum) - # Test with a map function that maps to non-zero - for arr in (se33, sA, pA) - @test f(x->x+1, arr) ≈ f(arr+1) - end - - # case where f(0) would throw - @test f(x->sqrt(x-1), pA+1) ≈ f(sqrt.(pA)) - # these actually throw due to #10533 - # @test f(x->sqrt(x-1), pA+1, 1) ≈ f(sqrt(pA), 1) - # @test f(x->sqrt(x-1), pA+1, 2) ≈ f(sqrt(pA), 2) - # @test f(x->sqrt(x-1), pA+1, 3) ≈ f(pA) - end - - @testset "empty cases" begin - @test sum(sparse(Int[])) === 0 - @test prod(sparse(Int[])) === 1 - @test_throws ArgumentError minimum(sparse(Int[])) - @test_throws ArgumentError maximum(sparse(Int[])) - @test var(sparse(Int[])) === NaN - - for f in (sum, prod, minimum, maximum, var) - @test isequal(f(spzeros(0, 1), 1), f(Array{Int}(0, 1), 1)) - @test isequal(f(spzeros(0, 1), 2), f(Array{Int}(0, 1), 2)) - @test isequal(f(spzeros(0, 1), (1, 2)), f(Array{Int}(0, 1), (1, 2))) - @test isequal(f(spzeros(0, 1), 3), f(Array{Int}(0, 1), 3)) - end - end -end - -@testset "construction of diagonal SparseMatrixCSCs" begin - @test Array(spdiagm((ones(2), ones(2)), (0, -1), 3, 3)) == - [1.0 0.0 0.0; 1.0 1.0 0.0; 0.0 1.0 0.0] - @test Array(spdiagm(ones(2), -1, 3, 3)) == diagm(ones(2), -1) -end - -@testset "issue #4986, reinterpret" begin - sfe22 = speye(Float64, 2) - mfe22 = eye(Float64, 2) - @test reinterpret(Int64, sfe22) == reinterpret(Int64, mfe22) -end - -@testset "issue #5190" begin - @test_throws ArgumentError sparsevec([3,5,7],[0.1,0.0,3.2],4) -end - -@testset "issue #5386" begin - K,J,V = findnz(SparseMatrixCSC(2,1,[1,3],[1,2],[1.0,0.0])) - @test length(K) == length(J) == length(V) == 1 -end - -@testset "issue described in https://groups.google.com/d/msg/julia-users/Yq4dh8NOWBQ/GU57L90FZ3EJ" begin - A = speye(Bool, 5) - @test find(A) == find(x -> x == true, A) == find(Array(A)) -end - -@testset "issue #5824" begin - @test sprand(4,5,0.5).^0 == sparse(ones(4,5)) -end - -@testset "issue #5985" begin - @test sprand(Bool, 4, 5, 0.0) == sparse(zeros(Bool, 4, 5)) - @test sprand(Bool, 4, 5, 1.00) == sparse(ones(Bool, 4, 5)) - sprb45nnzs = zeros(5) - for i=1:5 - sprb45 = sprand(Bool, 4, 5, 0.5) - @test length(sprb45) == 20 - sprb45nnzs[i] = sum(sprb45)[1] - end - @test 4 <= mean(sprb45nnzs) <= 16 -end - -@testset "issue #5853, sparse diff" begin - for i=1:2, a=Any[[1 2 3], reshape([1, 2, 3],(3,1)), eye(3)] - @test all(diff(sparse(a),i) == diff(a,i)) - end -end - -@testset "access to undefined error types that initially allocate elements as #undef" begin - @test all(sparse(1:2, 1:2, Number[1,2])^2 == sparse(1:2, 1:2, [1,4])) - sd1 = diff(sparse([1,1,1], [1,2,3], Number[1,2,3]), 1) -end - -@testset "issue #6036" begin - P = spzeros(Float64, 3, 3) - for i = 1:3 - P[i,i] = i - end - - @test minimum(P) === 0.0 - @test maximum(P) === 3.0 - @test minimum(-P) === -3.0 - @test maximum(-P) === 0.0 - - @test maximum(P, (1,)) == [1.0 2.0 3.0] - @test maximum(P, (2,)) == reshape([1.0,2.0,3.0],3,1) - @test maximum(P, (1,2)) == reshape([3.0],1,1) - - @test maximum(sparse(-ones(3,3))) == -1 - @test minimum(sparse(ones(3,3))) == 1 -end - -@testset "unary functions" begin - A = sprand(5, 15, 0.5) - C = A + im*A - Afull = Array(A) - Cfull = Array(C) - # Test representatives of [unary functions that map zeros to zeros and may map nonzeros to zeros] - @test sin.(Afull) == Array(sin.(A)) - @test tan.(Afull) == Array(tan.(A)) # should be redundant with sin test - @test ceil.(Afull) == Array(ceil.(A)) - @test floor.(Afull) == Array(floor.(A)) # should be redundant with ceil test - @test real.(Afull) == Array(real.(A)) == Array(real(A)) - @test imag.(Afull) == Array(imag.(A)) == Array(imag(A)) - @test conj.(Afull) == Array(conj.(A)) == Array(conj(A)) - @test real.(Cfull) == Array(real.(C)) == Array(real(C)) - @test imag.(Cfull) == Array(imag.(C)) == Array(imag(C)) - @test conj.(Cfull) == Array(conj.(C)) == Array(conj(C)) - # Test representatives of [unary functions that map zeros to zeros and nonzeros to nonzeros] - @test expm1.(Afull) == Array(expm1.(A)) - @test abs.(Afull) == Array(abs.(A)) - @test abs2.(Afull) == Array(abs2.(A)) - @test abs.(Cfull) == Array(abs.(C)) - @test abs2.(Cfull) == Array(abs2.(C)) - # Test representatives of [unary functions that map both zeros and nonzeros to nonzeros] - @test cos.(Afull) == Array(cos.(A)) - # Test representatives of remaining vectorized-nonbroadcast unary functions - @test ceil.(Int, Afull) == Array(ceil.(Int, A)) - @test floor.(Int, Afull) == Array(floor.(Int, A)) - # Tests of real, imag, abs, and abs2 for SparseMatrixCSC{Int,X}s previously elsewhere - for T in (Int, Float16, Float32, Float64, BigInt, BigFloat) - R = rand(T[1:100;], 2, 2) - I = rand(T[1:100;], 2, 2) - D = R + I*im - S = sparse(D) - spR = sparse(R) - - @test R == real.(S) == real(S) - @test I == imag.(S) == imag(S) - @test conj(full(S)) == conj.(S) == conj(S) - @test real.(spR) == R - @test nnz(imag.(spR)) == nnz(imag(spR)) == 0 - @test abs.(S) == abs.(D) - @test abs2.(S) == abs2.(D) - - # test aliasing of real and conj of real valued matrix - @test real(spR) === spR - @test conj(spR) === spR - end -end - -@testset "getindex" begin - ni = 23 - nj = 32 - a116 = reshape(1:(ni*nj), ni, nj) - s116 = sparse(a116) - - ad116 = diagm(diag(a116)) - sd116 = sparse(ad116) - - for (aa116, ss116) in [(a116, s116), (ad116, sd116)] - ij=11; i=3; j=2 - @test ss116[ij] == aa116[ij] - @test ss116[(i,j)] == aa116[i,j] - @test ss116[i,j] == aa116[i,j] - @test ss116[i-1,j] == aa116[i-1,j] - ss116[i,j] = 0 - @test ss116[i,j] == 0 - ss116 = sparse(aa116) - - @test ss116[:,:] == copy(ss116) - - # range indexing - @test Array(ss116[i,:]) == aa116[i,:] - @test Array(ss116[:,j]) == aa116[:,j] - @test Array(ss116[i,1:2:end]) == aa116[i,1:2:end] - @test Array(ss116[1:2:end,j]) == aa116[1:2:end,j] - @test Array(ss116[i,end:-2:1]) == aa116[i,end:-2:1] - @test Array(ss116[end:-2:1,j]) == aa116[end:-2:1,j] - # float-range indexing is not supported - - # sorted vector indexing - @test Array(ss116[i,[3:2:end-3;]]) == aa116[i,[3:2:end-3;]] - @test Array(ss116[[3:2:end-3;],j]) == aa116[[3:2:end-3;],j] - @test Array(ss116[i,[end-3:-2:1;]]) == aa116[i,[end-3:-2:1;]] - @test Array(ss116[[end-3:-2:1;],j]) == aa116[[end-3:-2:1;],j] - - # unsorted vector indexing with repetition - p = [4, 1, 2, 3, 2, 6] - @test Array(ss116[p,:]) == aa116[p,:] - @test Array(ss116[:,p]) == aa116[:,p] - @test Array(ss116[p,p]) == aa116[p,p] - - # bool indexing - li = bitrand(size(aa116,1)) - lj = bitrand(size(aa116,2)) - @test Array(ss116[li,j]) == aa116[li,j] - @test Array(ss116[li,:]) == aa116[li,:] - @test Array(ss116[i,lj]) == aa116[i,lj] - @test Array(ss116[:,lj]) == aa116[:,lj] - @test Array(ss116[li,lj]) == aa116[li,lj] - - # empty indices - for empty in (1:0, Int[]) - @test Array(ss116[empty,:]) == aa116[empty,:] - @test Array(ss116[:,empty]) == aa116[:,empty] - @test Array(ss116[empty,lj]) == aa116[empty,lj] - @test Array(ss116[li,empty]) == aa116[li,empty] - @test Array(ss116[empty,empty]) == aa116[empty,empty] - end - - # out of bounds indexing - @test_throws BoundsError ss116[0, 1] - @test_throws BoundsError ss116[end+1, 1] - @test_throws BoundsError ss116[1, 0] - @test_throws BoundsError ss116[1, end+1] - for j in (1, 1:size(s116,2), 1:1, Int[1], trues(size(s116, 2)), 1:0, Int[]) - @test_throws BoundsError ss116[0:1, j] - @test_throws BoundsError ss116[[0, 1], j] - @test_throws BoundsError ss116[end:end+1, j] - @test_throws BoundsError ss116[[end, end+1], j] - end - for i in (1, 1:size(s116,1), 1:1, Int[1], trues(size(s116, 1)), 1:0, Int[]) - @test_throws BoundsError ss116[i, 0:1] - @test_throws BoundsError ss116[i, [0, 1]] - @test_throws BoundsError ss116[i, end:end+1] - @test_throws BoundsError ss116[i, [end, end+1]] - end - end - - # workaround issue #7197: comment out let-block - #let S = SparseMatrixCSC(3, 3, UInt8[1,1,1,1], UInt8[], Int64[]) - S1290 = SparseMatrixCSC(3, 3, UInt8[1,1,1,1], UInt8[], Int64[]) - S1290[1,1] = 1 - S1290[5] = 2 - S1290[end] = 3 - @test S1290[end] == (S1290[1] + S1290[2,2]) - @test 6 == sum(diag(S1290)) - @test Array(S1290)[[3,1],1] == Array(S1290[[3,1],1]) - # end -end - -@testset "setindex" begin - a = spzeros(Int, 10, 10) - @test countnz(a) == 0 - a[1,:] = 1 - @test countnz(a) == 10 - @test a[1,:] == sparse(ones(Int,10)) - a[:,2] = 2 - @test countnz(a) == 19 - @test a[:,2] == 2*sparse(ones(Int,10)) - b = copy(a) - - # Zero-assignment behavior of setindex!(A, v, i, j) - a[1,3] = 0 - @test nnz(a) == 19 - @test countnz(a) == 18 - a[2,1] = 0 - @test nnz(a) == 19 - @test countnz(a) == 18 - - # Zero-assignment behavior of setindex!(A, v, I, J) - a[1,:] = 0 - @test nnz(a) == 19 - @test countnz(a) == 9 - a[2,:] = 0 - @test nnz(a) == 19 - @test countnz(a) == 8 - a[:,1] = 0 - @test nnz(a) == 19 - @test countnz(a) == 8 - a[:,2] = 0 - @test nnz(a) == 19 - @test countnz(a) == 0 - a = copy(b) - a[:,:] = 0 - @test nnz(a) == 19 - @test countnz(a) == 0 - - # Zero-assignment behavior of setindex!(A, B::SparseMatrixCSC, I, J) - a = copy(b) - a[1:2,:] = spzeros(2, 10) - @test nnz(a) == 19 - @test countnz(a) == 8 - a[1:2,1:3] = sparse([1 0 1; 0 0 1]) - @test nnz(a) == 20 - @test countnz(a) == 11 - a = copy(b) - a[1:2,:] = let c = sparse(ones(2,10)); fill!(c.nzval, 0); c; end - @test nnz(a) == 19 - @test countnz(a) == 8 - a[1:2,1:3] = let c = sparse(ones(2,3)); c[1,2] = c[2,1] = c[2,2] = 0; c; end - @test nnz(a) == 20 - @test countnz(a) == 11 - - a[1,:] = 1:10 - @test a[1,:] == sparse([1:10;]) - a[:,2] = 1:10 - @test a[:,2] == sparse([1:10;]) - - a[1,1:0] = [] - @test a[1,:] == sparse([1; 1; 3:10]) - a[1:0,2] = [] - @test a[:,2] == sparse([1:10;]) - a[1,1:0] = 0 - @test a[1,:] == sparse([1; 1; 3:10]) - a[1:0,2] = 0 - @test a[:,2] == sparse([1:10;]) - a[1,1:0] = 1 - @test a[1,:] == sparse([1; 1; 3:10]) - a[1:0,2] = 1 - @test a[:,2] == sparse([1:10;]) - - @test_throws BoundsError a[:,11] = spzeros(10,1) - @test_throws BoundsError a[11,:] = spzeros(1,10) - @test_throws BoundsError a[:,-1] = spzeros(10,1) - @test_throws BoundsError a[-1,:] = spzeros(1,10) - @test_throws BoundsError a[0:9] = spzeros(1,10) - @test_throws BoundsError a[:,11] = 0 - @test_throws BoundsError a[11,:] = 0 - @test_throws BoundsError a[:,-1] = 0 - @test_throws BoundsError a[-1,:] = 0 - @test_throws BoundsError a[0:9] = 0 - @test_throws BoundsError a[:,11] = 1 - @test_throws BoundsError a[11,:] = 1 - @test_throws BoundsError a[:,-1] = 1 - @test_throws BoundsError a[-1,:] = 1 - @test_throws BoundsError a[0:9] = 1 - - @test_throws DimensionMismatch a[1:2,1:2] = 1:3 - @test_throws DimensionMismatch a[1:2,1] = 1:3 - @test_throws DimensionMismatch a[1,1:2] = 1:3 - @test_throws DimensionMismatch a[1:2] = 1:3 - - A = spzeros(Int, 10, 20) - A[1:5,1:10] = 10 - A[1:5,1:10] = 10 - @test countnz(A) == 50 - @test A[1:5,1:10] == 10 * ones(Int, 5, 10) - A[6:10,11:20] = 0 - @test countnz(A) == 50 - A[6:10,11:20] = 20 - @test countnz(A) == 100 - @test A[6:10,11:20] == 20 * ones(Int, 5, 10) - A[4:8,8:16] = 15 - @test countnz(A) == 121 - @test A[4:8,8:16] == 15 * ones(Int, 5, 9) - - ASZ = 1000 - TSZ = 800 - A = sprand(ASZ, 2*ASZ, 0.0001) - B = copy(A) - nA = countnz(A) - x = A[1:TSZ, 1:(2*TSZ)] - nx = countnz(x) - A[1:TSZ, 1:(2*TSZ)] = 0 - nB = countnz(A) - @test nB == (nA - nx) - A[1:TSZ, 1:(2*TSZ)] = x - @test countnz(A) == nA - @test A == B - A[1:TSZ, 1:(2*TSZ)] = 10 - @test countnz(A) == nB + 2*TSZ*TSZ - A[1:TSZ, 1:(2*TSZ)] = x - @test countnz(A) == nA - @test A == B - - A = speye(Int, 5) - I=1:10 - X=reshape([trues(10); falses(15)],5,5) - @test A[I] == A[X] == [1,0,0,0,0,0,1,0,0,0] - A[I] = [1:10;] - @test A[I] == A[X] == collect(1:10) - A[I] = zeros(Int, 10) - @test nnz(A) == 13 - @test countnz(A) == 3 - @test A[I] == A[X] == zeros(Int, 10) - c = collect(11:20); c[1] = c[3] = 0 - A[I] = c - @test nnz(A) == 13 - @test countnz(A) == 11 - @test A[I] == A[X] == c - A = speye(Int, 5) - A[I] = c - @test nnz(A) == 12 - @test countnz(A) == 11 - @test A[I] == A[X] == c - - S = sprand(50, 30, 0.5, x -> round.(Int, rand(x) * 100)) - I = sprand(Bool, 50, 30, 0.2) - FS = Array(S) - FI = Array(I) - @test sparse(FS[FI]) == S[I] == S[FI] - @test sum(S[FI]) + sum(S[.!FI]) == sum(S) - @test countnz(I) == count(I) - - sumS1 = sum(S) - sumFI = sum(S[FI]) - nnzS1 = nnz(S) - S[FI] = 0 - sumS2 = sum(S) - cnzS2 = countnz(S) - @test sum(S[FI]) == 0 - @test nnz(S) == nnzS1 - @test (sum(S) + sumFI) == sumS1 - - S[FI] = 10 - nnzS3 = nnz(S) - @test sum(S) == sumS2 + 10*sum(FI) - S[FI] = 0 - @test sum(S) == sumS2 - @test nnz(S) == nnzS3 - @test countnz(S) == cnzS2 - - S[FI] = [1:sum(FI);] - @test sum(S) == sumS2 + sum(1:sum(FI)) - - S = sprand(50, 30, 0.5, x -> round.(Int, rand(x) * 100)) - N = length(S) >> 2 - I = randperm(N) .* 4 - J = randperm(N) - sumS1 = sum(S) - sumS2 = sum(S[I]) - S[I] = 0 - @test sum(S) == (sumS1 - sumS2) - S[I] = J - @test sum(S) == (sumS1 - sumS2 + sum(J)) -end - -@testset "dropstored!" begin - A = spzeros(Int, 10, 10) - # Introduce nonzeros in row and column two - A[1,:] = 1 - A[:,2] = 2 - @test nnz(A) == 19 - - # Test argument bounds checking for dropstored!(A, i, j) - @test_throws BoundsError Base.SparseArrays.dropstored!(A, 0, 1) - @test_throws BoundsError Base.SparseArrays.dropstored!(A, 1, 0) - @test_throws BoundsError Base.SparseArrays.dropstored!(A, 1, 11) - @test_throws BoundsError Base.SparseArrays.dropstored!(A, 11, 1) - - # Test argument bounds checking for dropstored!(A, I, J) - @test_throws BoundsError Base.SparseArrays.dropstored!(A, 0:1, 1:1) - @test_throws BoundsError Base.SparseArrays.dropstored!(A, 1:1, 0:1) - @test_throws BoundsError Base.SparseArrays.dropstored!(A, 10:11, 1:1) - @test_throws BoundsError Base.SparseArrays.dropstored!(A, 1:1, 10:11) - - # Test behavior of dropstored!(A, i, j) - # --> Test dropping a single stored entry - Base.SparseArrays.dropstored!(A, 1, 2) - @test nnz(A) == 18 - # --> Test dropping a single nonstored entry - Base.SparseArrays.dropstored!(A, 2, 1) - @test nnz(A) == 18 - - # Test behavior of dropstored!(A, I, J) and derivs. - # --> Test dropping a single row including stored and nonstored entries - Base.SparseArrays.dropstored!(A, 1, :) - @test nnz(A) == 9 - # --> Test dropping a single column including stored and nonstored entries - Base.SparseArrays.dropstored!(A, :, 2) - @test nnz(A) == 0 - # --> Introduce nonzeros in rows one and two and columns two and three - A[1:2,:] = 1 - A[:,2:3] = 2 - @test nnz(A) == 36 - # --> Test dropping multiple rows containing stored and nonstored entries - Base.SparseArrays.dropstored!(A, 1:3, :) - @test nnz(A) == 14 - # --> Test dropping multiple columns containing stored and nonstored entries - Base.SparseArrays.dropstored!(A, :, 2:4) - @test nnz(A) == 0 - # --> Introduce nonzeros in every other row - A[1:2:9, :] = 1 - @test nnz(A) == 50 - # --> Test dropping a block of the matrix towards the upper left - Base.SparseArrays.dropstored!(A, 2:5, 2:5) - @test nnz(A) == 42 -end - -@testset "issue #7507" begin - @test (i7507=sparsevec(Dict{Int64, Float64}(), 10))==spzeros(10) -end - -@testset "issue #7650" begin - S = spzeros(3, 3) - @test size(reshape(S, 9, 1)) == (9,1) -end - -@testset "sparsevec from matrices" begin - X = eye(5) - M = rand(5,4) - C = spzeros(3,3) - SX = sparse(X); SM = sparse(M) - VX = vec(X); VSX = vec(SX) - VM = vec(M); VSM1 = vec(SM); VSM2 = sparsevec(M) - VC = vec(C) - @test VX == VSX - @test VM == VSM1 - @test VM == VSM2 - @test size(VC) == (9,) - @test nnz(VC) == 0 - @test nnz(VSX) == 5 -end - -@testset "issue #7677" begin - A = sprand(5,5,0.5,(n)->rand(Float64,n)) - ACPY = copy(A) - B = reshape(A,25,1) - @test A == ACPY - C = reinterpret(Int64, A, (25, 1)) - @test A == ACPY - D = reinterpret(Int64, copy(B)) - @test C == D -end - -@testset "issue #8225" begin - @test_throws ArgumentError sparse([0],[-1],[1.0],2,2) -end - -@testset "issue #8363" begin - @test_throws ArgumentError sparsevec(Dict(-1=>1,1=>2)) -end - -@testset "issue #8976" begin - @test conj.(sparse([1im])) == sparse(conj([1im])) - @test conj!(sparse([1im])) == sparse(conj!([1im])) -end - -@testset "issue #9525" begin - @test_throws ArgumentError sparse([3], [5], 1.0, 3, 3) -end - -@testset "indmax, indmin, findmax, findmin" begin - S = sprand(100,80, 0.5) - A = Array(S) - @test indmax(S) == indmax(A) - @test indmin(S) == indmin(A) - @test findmin(S) == findmin(A) - @test findmax(S) == findmax(A) - for region in [(1,), (2,), (1,2)], m in [findmax, findmin] - @test m(S, region) == m(A, region) - end - - S = spzeros(10,8) - A = Array(S) - @test indmax(S) == indmax(A) == 1 - @test indmin(S) == indmin(A) == 1 - - A = Array{Int}(0,0) - S = sparse(A) - iA = try indmax(A) end - iS = try indmax(S) end - @test iA === iS === nothing - iA = try indmin(A) end - iS = try indmin(S) end - @test iA === iS === nothing -end - -@testset "findn" begin - b = findn( speye(4) ) - @test (length(b[1]) == 4) - @test (length(b[2]) == 4) -end - -@testset "rotations" begin - a = sparse( [1,1,2,3], [1,3,4,1], [1,2,3,4] ) - - @test rot180(a,2) == a - @test rot180(a,1) == sparse( [3,3,2,1], [4,2,1,4], [1,2,3,4] ) - @test rotr90(a,1) == sparse( [1,3,4,1], [3,3,2,1], [1,2,3,4] ) - @test rotl90(a,1) == sparse( [4,2,1,4], [1,1,2,3], [1,2,3,4] ) - @test rotl90(a,2) == rot180(a) - @test rotr90(a,2) == rot180(a) - @test rotl90(a,3) == rotr90(a) - @test rotr90(a,3) == rotl90(a) - - #ensure we have preserved the correct dimensions! - - a = speye(3,5) - @test size(rot180(a)) == (3,5) - @test size(rotr90(a)) == (5,3) - @test size(rotl90(a)) == (5,3) -end - -function test_getindex_algs{Tv,Ti}(A::SparseMatrixCSC{Tv,Ti}, I::AbstractVector, J::AbstractVector, alg::Int) - # Sorted vectors for indexing rows. - # Similar to getindex_general but without the transpose trick. - (m, n) = size(A) - !isempty(I) && ((I[1] < 1) || (I[end] > m)) && BoundsError() - if !isempty(J) - minj, maxj = extrema(J) - ((minj < 1) || (maxj > n)) && BoundsError() - end - - (alg == 0) ? Base.SparseArrays.getindex_I_sorted_bsearch_A(A, I, J) : - (alg == 1) ? Base.SparseArrays.getindex_I_sorted_bsearch_I(A, I, J) : - Base.SparseArrays.getindex_I_sorted_linear(A, I, J) -end - -@testset "test_getindex_algs" begin - M=2^14 - N=2^4 - Irand = randperm(M) - Jrand = randperm(N) - SA = [sprand(M, N, d) for d in [1., 0.1, 0.01, 0.001, 0.0001, 0.]] - IA = [sort(Irand[1:round(Int,n)]) for n in [M, M*0.1, M*0.01, M*0.001, M*0.0001, 0.]] - debug = false - - if debug - println("row sizes: $([round(Int,nnz(S)/S.n) for S in SA])") - println("I sizes: $([length(I) for I in IA])") - @printf(" S | I | binary S | binary I | linear | best\n") - end - - J = Jrand - for I in IA - for S in SA - res = Any[1,2,3] - times = Float64[0,0,0] - best = [typemax(Float64), 0] - for searchtype in [0, 1, 2] - gc() - tres = @timed test_getindex_algs(S, I, J, searchtype) - res[searchtype+1] = tres[1] - times[searchtype+1] = tres[2] - if best[1] > tres[2] - best[1] = tres[2] - best[2] = searchtype - end - end - - if debug - @printf(" %7d | %7d | %4.2e | %4.2e | %4.2e | %s\n", round(Int,nnz(S)/S.n), length(I), times[1], times[2], times[3], - (0 == best[2]) ? "binary S" : (1 == best[2]) ? "binary I" : "linear") - end - if res[1] != res[2] - println("1 and 2") - elseif res[2] != res[3] - println("2, 3") - end - @test res[1] == res[2] == res[3] - end - end - - M = 2^8 - N=2^3 - Irand = randperm(M) - Jrand = randperm(N) - I = sort([Irand; Irand; Irand]) - J = [Jrand; Jrand] - - SA = [sprand(M, N, d) for d in [1., 0.1, 0.01, 0.001, 0.0001, 0.]] - for S in SA - res = Any[1,2,3] - for searchtype in [0, 1, 2] - res[searchtype+1] = test_getindex_algs(S, I, J, searchtype) - end - - @test res[1] == res[2] == res[3] - end - - M = 2^14 - N=2^4 - I = randperm(M) - J = randperm(N) - Jsorted = sort(J) - - SA = [sprand(M, N, d) for d in [1., 0.1, 0.01, 0.001, 0.0001, 0.]] - IA = [I[1:round(Int,n)] for n in [M, M*0.1, M*0.01, M*0.001, M*0.0001, 0.]] - debug = false - if debug - @printf(" | | | times | memory |\n") - @printf(" S | I | J | sorted | unsorted | sorted | unsorted |\n") - end - for I in IA - Isorted = sort(I) - for S in SA - gc() - ru = @timed S[I, J] - gc() - rs = @timed S[Isorted, Jsorted] - if debug - @printf(" %7d | %7d | %7d | %4.2e | %4.2e | %4.2e | %4.2e |\n", round(Int,nnz(S)/S.n), length(I), length(J), rs[2], ru[2], rs[3], ru[3]) - end - end - end -end - -@testset "getindex bounds checking" begin - S = sprand(10, 10, 0.1) - @test_throws BoundsError S[[0,1,2], [1,2]] - @test_throws BoundsError S[[1,2], [0,1,2]] - @test_throws BoundsError S[[0,2,1], [1,2]] - @test_throws BoundsError S[[2,1], [0,1,2]] -end - -@testset "test that sparse / sparsevec constructors work for AbstractMatrix subtypes" begin - D = Diagonal(ones(10,10)) - sm = sparse(D) - sv = sparsevec(D) - - @test countnz(sm) == 10 - @test countnz(sv) == 10 - - @test countnz(sparse(Diagonal(Int[]))) == 0 - @test countnz(sparsevec(Diagonal(Int[]))) == 0 -end - -@testset "explicit zeros" begin - if Base.USE_GPL_LIBS - a = SparseMatrixCSC(2, 2, [1, 3, 5], [1, 2, 1, 2], [1.0, 0.0, 0.0, 1.0]) - @test lufact(a)\[2.0, 3.0] ≈ [2.0, 3.0] - @test cholfact(a)\[2.0, 3.0] ≈ [2.0, 3.0] - end -end - -@testset "issue #9917" begin - @test sparse([]') == reshape(sparse([]), 1, 0) - @test Array(sparse([])) == zeros(0) - @test_throws BoundsError sparse([])[1] - @test_throws BoundsError sparse([])[1] = 1 - x = speye(100) - @test_throws BoundsError x[-10:10] -end - -@testset "issue #10407" begin - @test maximum(spzeros(5, 5)) == 0.0 - @test minimum(spzeros(5, 5)) == 0.0 -end - -@testset "issue #10411" begin - for (m,n) in ((2,-2),(-2,2),(-2,-2)) - @test_throws ArgumentError spzeros(m,n) - @test_throws ArgumentError speye(m,n) - @test_throws ArgumentError sprand(m,n,0.2) - end -end - -@testset "issue #10837, sparse constructors from special matrices" begin - T = Tridiagonal(randn(4),randn(5),randn(4)) - S = sparse(T) - @test norm(Array(T) - Array(S)) == 0.0 - T = SymTridiagonal(randn(5),rand(4)) - S = sparse(T) - @test norm(Array(T) - Array(S)) == 0.0 - B = Bidiagonal(randn(5),randn(4),true) - S = sparse(B) - @test norm(Array(B) - Array(S)) == 0.0 - B = Bidiagonal(randn(5),randn(4),false) - S = sparse(B) - @test norm(Array(B) - Array(S)) == 0.0 -end - -@testset "spdiagm promotion" begin - @test spdiagm(([1,2],[3.5],[4+5im]), (0,1,-1), 2,2) == [1 3.5; 4+5im 2] -end - -@testset "error conditions for reinterpret, reshape, and squeeze" begin - A = sprand(Bool, 5,5,0.2) - @test_throws ArgumentError reinterpret(Complex128,A) - @test_throws ArgumentError reinterpret(Complex128,A,(5,5)) - @test_throws DimensionMismatch reinterpret(Int8,A,(20,)) - @test_throws DimensionMismatch reshape(A,(20,2)) - @test_throws ArgumentError squeeze(A,(1,1)) -end - -@testset "similar with type conversion" begin - A = speye(5) - @test size(similar(A,Complex128,Int)) == (5,5) - @test typeof(similar(A,Complex128,Int)) == SparseMatrixCSC{Complex128,Int} - @test size(similar(A,Complex128,Int8)) == (5,5) - @test typeof(similar(A,Complex128,Int8)) == SparseMatrixCSC{Complex128,Int8} - @test similar(A,Complex128,(6,6)) == spzeros(Complex128,6,6) - @test convert(Matrix,A) == Array(A) -end - -@testset "float" begin - A = sprand(Bool, 5,5,0.0) - @test eltype(float(A)) == Float64 # issue #11658 - A = sprand(Bool, 5,5,0.2) - @test float(A) == float(Array(A)) -end - -@testset "sparsevec" begin - A = sparse(ones(5,5)) - @test all(Array(sparsevec(A)) .== ones(25)) - @test all(Array(sparsevec([1:5;],1)) .== ones(5)) - @test_throws ArgumentError sparsevec([1:5;], [1:4;]) -end - -@testset "sparse" begin - A = sparse(ones(5,5)) - @test sparse(A) == A - @test sparse([1:5;],[1:5;],1) == speye(5) -end - -@testset "speye and one" begin - A = sparse(ones(5,5)) - @test speye(A) == speye(5) - @test eye(A) == speye(5) - @test one(A) == speye(5) - @test_throws DimensionMismatch one(sprand(5,6,0.2)) - @test eltype(speye(Real, 5, 5)) === Real -end - -@testset "istriu/istril" begin - A = sparse(triu(rand(5,5))) - @test istriu(A) - @test !istriu(sparse(ones(5,5))) - A = sparse(tril(rand(5,5))) - @test istril(A) - @test !istril(sparse(ones(5,5))) -end - -@testset "droptol" begin - srand(1234321) - A = triu(sprand(10,10,0.2)) - @test Base.droptol!(A,0.01).colptr == [1,1,1,2,2,3,4,6,6,7,9] - @test isequal(Base.droptol!(sparse([1], [1], [1]), 1), SparseMatrixCSC(1,1,Int[1,1],Int[],Int[])) -end - -@testset "dropzeros[!]" begin - smalldim = 5 - largedim = 10 - nzprob = 0.4 - targetnumposzeros = 5 - targetnumnegzeros = 5 - for (m, n) in ((largedim, largedim), (smalldim, largedim), (largedim, smalldim)) - A = sprand(m, n, nzprob) - struczerosA = find(x -> x == 0, A) - poszerosinds = unique(rand(struczerosA, targetnumposzeros)) - negzerosinds = unique(rand(struczerosA, targetnumnegzeros)) - Aposzeros = setindex!(copy(A), 2, poszerosinds) - Anegzeros = setindex!(copy(A), -2, negzerosinds) - Abothsigns = setindex!(copy(Aposzeros), -2, negzerosinds) - map!(x -> x == 2 ? 0.0 : x, Aposzeros.nzval, Aposzeros.nzval) - map!(x -> x == -2 ? -0.0 : x, Anegzeros.nzval, Anegzeros.nzval) - map!(x -> x == 2 ? 0.0 : x == -2 ? -0.0 : x, Abothsigns.nzval, Abothsigns.nzval) - for Awithzeros in (Aposzeros, Anegzeros, Abothsigns) - # Basic functionality / dropzeros! - @test dropzeros!(copy(Awithzeros)) == A - @test dropzeros!(copy(Awithzeros), false) == A - # Basic functionality / dropzeros - @test dropzeros(Awithzeros) == A - @test dropzeros(Awithzeros, false) == A - # Check trimming works as expected - @test length(dropzeros!(copy(Awithzeros)).nzval) == length(A.nzval) - @test length(dropzeros!(copy(Awithzeros)).rowval) == length(A.rowval) - @test length(dropzeros!(copy(Awithzeros), false).nzval) == length(Awithzeros.nzval) - @test length(dropzeros!(copy(Awithzeros), false).rowval) == length(Awithzeros.rowval) - end - end - # original lone dropzeros test - A = sparse([1 2 3; 4 5 6; 7 8 9]) - A.nzval[2] = A.nzval[6] = A.nzval[7] = 0 - @test dropzeros!(A).colptr == [1, 3, 5, 7] - # test for issue #5169, modified for new behavior following #15242/#14798 - @test nnz(sparse([1, 1], [1, 2], [0.0, -0.0])) == 2 - @test nnz(dropzeros!(sparse([1, 1], [1, 2], [0.0, -0.0]))) == 0 - # test for issue #5437, modified for new behavior following #15242/#14798 - @test nnz(sparse([1, 2, 3], [1, 2, 3], [0.0, 1.0, 2.0])) == 3 - @test nnz(dropzeros!(sparse([1, 2, 3],[1, 2, 3],[0.0, 1.0, 2.0]))) == 2 -end - -@testset "trace" begin - @test_throws DimensionMismatch trace(sparse(ones(5,6))) - @test trace(speye(5)) == 5 -end - -@testset "diagm on a matrix" begin - @test_throws DimensionMismatch diagm(sparse(ones(5,2))) - @test_throws DimensionMismatch diagm(sparse(ones(2,5))) - @test diagm(sparse(ones(1,5))) == speye(5) - @test diagm(sparse(ones(5,1))) == speye(5) -end - -@testset "expandptr" begin - A = speye(5) - @test Base.SparseArrays.expandptr(A.colptr) == collect(1:5) - A[1,2] = 1 - @test Base.SparseArrays.expandptr(A.colptr) == [1; 2; 2; 3; 4; 5] - @test_throws ArgumentError Base.SparseArrays.expandptr([2; 3]) -end - -@testset "triu/tril" begin - A = sprand(5,5,0.2) - AF = Array(A) - @test Array(triu(A,1)) == triu(AF,1) - @test Array(tril(A,1)) == tril(AF,1) - @test Array(triu!(copy(A), 2)) == triu(AF,2) - @test Array(tril!(copy(A), 2)) == tril(AF,2) - @test_throws BoundsError tril(A,6) - @test_throws BoundsError tril(A,-6) - @test_throws BoundsError triu(A,6) - @test_throws BoundsError triu(A,-6) - @test_throws ArgumentError tril!(sparse([1,2,3], [1,2,3], [1,2,3], 3, 4), 4) - @test_throws ArgumentError tril!(sparse([1,2,3], [1,2,3], [1,2,3], 3, 4), -3) - @test_throws ArgumentError triu!(sparse([1,2,3], [1,2,3], [1,2,3], 3, 4), 4) - @test_throws ArgumentError triu!(sparse([1,2,3], [1,2,3], [1,2,3], 3, 4), -3) - - # fkeep trim option - @test isequal(length(tril!(sparse([1,2,3], [1,2,3], [1,2,3], 3, 4), -1).rowval), 0) -end - -@testset "norm" begin - A = sparse(Int[],Int[],Float64[],0,0) - @test norm(A) == zero(eltype(A)) - A = sparse([1.0]) - @test norm(A) == 1.0 - @test_throws ArgumentError norm(sprand(5,5,0.2),3) - @test_throws ArgumentError norm(sprand(5,5,0.2),2) -end - -@testset "ishermitian/issymmetric" begin - # real matrices - A = speye(5,5) - @test ishermitian(A) == true - @test issymmetric(A) == true - A[1,3] = 1.0 - @test ishermitian(A) == false - @test issymmetric(A) == false - A[3,1] = 1.0 - @test ishermitian(A) == true - @test issymmetric(A) == true - - # complex matrices - A = speye(5,5) + im*speye(5,5) - @test ishermitian(A) == false - @test issymmetric(A) == true - A[1,4] = 1.0 + im - @test ishermitian(A) == false - @test issymmetric(A) == false - - A = speye(Complex128, 5,5) - A[3,2] = 1.0 + im - @test ishermitian(A) == false - @test issymmetric(A) == false - A[2,3] = 1.0 - im - @test ishermitian(A) == true - @test issymmetric(A) == false - - A = sparse(zeros(5,5)) - @test ishermitian(A) == true - @test issymmetric(A) == true - - # explicit zeros - A = speye(Complex128, 5,5) - A[3,1] = 2 - A.nzval[2] = 0.0 - @test ishermitian(A) == true - @test issymmetric(A) == true - - # 15504 - m = n = 5 - colptr = [1, 5, 9, 13, 13, 17] - rowval = [1, 2, 3, 5, 1, 2, 3, 5, 1, 2, 3, 5, 1, 2, 3, 5] - nzval = [0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 0.0, 1.0, 1.0, 1.0, 0.0, 1.0, 1.0, 1.0] - A = SparseMatrixCSC(m, n, colptr, rowval, nzval) - @test issymmetric(A) == true - A.nzval[end - 3] = 2.0 - @test issymmetric(A) == false - - # 16521 - @test issymmetric(sparse([0 0; 1 0])) == false - @test issymmetric(sparse([0 1; 0 0])) == false - @test issymmetric(sparse([0 0; 1 1])) == false - @test issymmetric(sparse([1 0; 1 0])) == false - @test issymmetric(sparse([0 1; 1 0])) == true - @test issymmetric(sparse([1 1; 1 0])) == true -end - -@testset "equality ==" begin - A1 = speye(10) - A2 = speye(10) - nonzeros(A1)[end]=0 - @test A1!=A2 - nonzeros(A1)[end]=1 - @test A1==A2 - A1[1:4,end] = 1 - @test A1!=A2 - nonzeros(A1)[end-4:end-1]=0 - @test A1==A2 - A2[1:4,end-1] = 1 - @test A1!=A2 - nonzeros(A2)[end-5:end-2]=0 - @test A1==A2 - A2[2:3,1] = 1 - @test A1!=A2 - nonzeros(A2)[2:3]=0 - @test A1==A2 - A1[2:5,1] = 1 - @test A1!=A2 - nonzeros(A1)[2:5]=0 - @test A1==A2 - @test sparse([1,1,0])!=sparse([0,1,1]) -end - -@testset "UniformScaling" begin - A = sprandn(10,10,0.5) - @test A + I == Array(A) + I - @test I + A == I + Array(A) - @test A - I == Array(A) - I - @test I - A == I - Array(A) -end - -@testset "issue #12177, error path if triplet vectors are not all the same length" begin - @test_throws ArgumentError sparse([1,2,3], [1,2], [1,2,3], 3, 3) - @test_throws ArgumentError sparse([1,2,3], [1,2,3], [1,2], 3, 3) -end - -@testset "issue #12118: sparse matrices are closed under +, -, min, max" begin - A12118 = sparse([1,2,3,4,5], [1,2,3,4,5], [1,2,3,4,5]) - B12118 = sparse([1,2,4,5], [1,2,3,5], [2,1,-1,-2]) - - @test A12118 + B12118 == sparse([1,2,3,4,4,5], [1,2,3,3,4,5], [3,3,3,-1,4,3]) - @test typeof(A12118 + B12118) == SparseMatrixCSC{Int,Int} - - @test A12118 - B12118 == sparse([1,2,3,4,4,5], [1,2,3,3,4,5], [-1,1,3,1,4,7]) - @test typeof(A12118 - B12118) == SparseMatrixCSC{Int,Int} - - @test max.(A12118, B12118) == sparse([1,2,3,4,5], [1,2,3,4,5], [2,2,3,4,5]) - @test typeof(max.(A12118, B12118)) == SparseMatrixCSC{Int,Int} - - @test min.(A12118, B12118) == sparse([1,2,4,5], [1,2,3,5], [1,1,-1,-2]) - @test typeof(min.(A12118, B12118)) == SparseMatrixCSC{Int,Int} -end - -@testset "sparse matrix norms" begin - Ac = sprandn(10,10,.1) + im* sprandn(10,10,.1) - Ar = sprandn(10,10,.1) - Ai = ceil.(Int,Ar*100) - @test norm(Ac,1) ≈ norm(Array(Ac),1) - @test norm(Ac,Inf) ≈ norm(Array(Ac),Inf) - @test vecnorm(Ac) ≈ vecnorm(Array(Ac)) - @test norm(Ar,1) ≈ norm(Array(Ar),1) - @test norm(Ar,Inf) ≈ norm(Array(Ar),Inf) - @test vecnorm(Ar) ≈ vecnorm(Array(Ar)) - @test norm(Ai,1) ≈ norm(Array(Ai),1) - @test norm(Ai,Inf) ≈ norm(Array(Ai),Inf) - @test vecnorm(Ai) ≈ vecnorm(Array(Ai)) - Ai = trunc.(Int, Ar*100) - @test norm(Ai,1) ≈ norm(Array(Ai),1) - @test norm(Ai,Inf) ≈ norm(Array(Ai),Inf) - @test vecnorm(Ai) ≈ vecnorm(Array(Ai)) - Ai = round.(Int, Ar*100) - @test norm(Ai,1) ≈ norm(Array(Ai),1) - @test norm(Ai,Inf) ≈ norm(Array(Ai),Inf) - @test vecnorm(Ai) ≈ vecnorm(Array(Ai)) -end - -@testset "sparse matrix cond" begin - A = sparse(reshape([1.0],1,1)) - Ac = sprandn(20,20,.5) + im* sprandn(20,20,.5) - Ar = sprandn(20,20,.5) - @test cond(A,1) == 1.0 - # For a discussion of the tolerance, see #14778 - if Base.USE_GPL_LIBS - @test 0.99 <= cond(Ar, 1) \ norm(Ar, 1) * norm(inv(Array(Ar)), 1) < 3 - @test 0.99 <= cond(Ac, 1) \ norm(Ac, 1) * norm(inv(Array(Ac)), 1) < 3 - @test 0.99 <= cond(Ar, Inf) \ norm(Ar, Inf) * norm(inv(Array(Ar)), Inf) < 3 - @test 0.99 <= cond(Ac, Inf) \ norm(Ac, Inf) * norm(inv(Array(Ac)), Inf) < 3 - end - @test_throws ArgumentError cond(A,2) - @test_throws ArgumentError cond(A,3) - Arect = spzeros(10, 6) - @test_throws DimensionMismatch cond(Arect, 1) - @test_throws ArgumentError cond(Arect,2) - @test_throws DimensionMismatch cond(Arect, Inf) -end - -@testset "sparse matrix normestinv" begin - Ac = sprandn(20,20,.5) + im* sprandn(20,20,.5) - Aci = ceil.(Int64, 100*sprand(20,20,.5)) + im*ceil.(Int64, sprand(20,20,.5)) - Ar = sprandn(20,20,.5) - Ari = ceil.(Int64, 100*Ar) - if Base.USE_GPL_LIBS - @test Base.SparseArrays.normestinv(Ac,3) ≈ norm(inv(Array(Ac)),1) atol=1e-4 - @test Base.SparseArrays.normestinv(Aci,3) ≈ norm(inv(Array(Aci)),1) atol=1e-4 - @test Base.SparseArrays.normestinv(Ar) ≈ norm(inv(Array(Ar)),1) atol=1e-4 - @test_throws ArgumentError Base.SparseArrays.normestinv(Ac,0) - @test_throws ArgumentError Base.SparseArrays.normestinv(Ac,21) - end - @test_throws DimensionMismatch Base.SparseArrays.normestinv(sprand(3,5,.9)) -end - -@testset "issue #13008" begin - @test_throws ArgumentError sparse(collect(1:100), collect(1:100), fill(5,100), 5, 5) - @test_throws ArgumentError sparse(Int[], collect(1:5), collect(1:5)) -end - -@testset "issue #13024" begin - A13024 = sparse([1,2,3,4,5], [1,2,3,4,5], fill(true,5)) - B13024 = sparse([1,2,4,5], [1,2,3,5], fill(true,4)) - - @test broadcast(&, A13024, B13024) == sparse([1,2,5], [1,2,5], fill(true,3)) - @test typeof(broadcast(&, A13024, B13024)) == SparseMatrixCSC{Bool,Int} - - @test broadcast(|, A13024, B13024) == sparse([1,2,3,4,4,5], [1,2,3,3,4,5], fill(true,6)) - @test typeof(broadcast(|, A13024, B13024)) == SparseMatrixCSC{Bool,Int} - - @test broadcast(⊻, A13024, B13024) == sparse([3,4,4], [3,3,4], fill(true,3), 5, 5) - @test typeof(broadcast(⊻, A13024, B13024)) == SparseMatrixCSC{Bool,Int} - - @test broadcast(max, A13024, B13024) == sparse([1,2,3,4,4,5], [1,2,3,3,4,5], fill(true,6)) - @test typeof(broadcast(max, A13024, B13024)) == SparseMatrixCSC{Bool,Int} - - @test broadcast(min, A13024, B13024) == sparse([1,2,5], [1,2,5], fill(true,3)) - @test typeof(broadcast(min, A13024, B13024)) == SparseMatrixCSC{Bool,Int} - - for op in (+, -) - @test op(A13024, B13024) == op(Array(A13024), Array(B13024)) - end - for op in (max, min, &, |, xor) - @test op.(A13024, B13024) == op.(Array(A13024), Array(B13024)) - end -end - -@testset "spones" begin - A = 2. * speye(5,5) - @test Array(spones(A)) == eye(Array(A)) -end - -@testset "factorization" begin - A = spdiagm(rand(5)) + sprandn(5,5,0.2) + im*sprandn(5,5,0.2) - A = A + A' - @test !Base.USE_GPL_LIBS || abs(det(factorize(Hermitian(A)))) ≈ abs(det(factorize(Array(A)))) - A = spdiagm(rand(5)) + sprandn(5,5,0.2) + im*sprandn(5,5,0.2) - A = A*A' - @test !Base.USE_GPL_LIBS || abs(det(factorize(Hermitian(A)))) ≈ abs(det(factorize(Array(A)))) - A = spdiagm(rand(5)) + sprandn(5,5,0.2) - A = A + A.' - @test !Base.USE_GPL_LIBS || abs(det(factorize(Symmetric(A)))) ≈ abs(det(factorize(Array(A)))) - A = spdiagm(rand(5)) + sprandn(5,5,0.2) - A = A*A.' - @test !Base.USE_GPL_LIBS || abs(det(factorize(Symmetric(A)))) ≈ abs(det(factorize(Array(A)))) - @test factorize(triu(A)) == triu(A) - @test isa(factorize(triu(A)), UpperTriangular{Float64, SparseMatrixCSC{Float64, Int}}) - @test factorize(tril(A)) == tril(A) - @test isa(factorize(tril(A)), LowerTriangular{Float64, SparseMatrixCSC{Float64, Int}}) - @test !Base.USE_GPL_LIBS || factorize(A[:,1:4])\ones(size(A,1)) ≈ Array(A[:,1:4])\ones(size(A,1)) - @test_throws ErrorException chol(A) - @test_throws ErrorException lu(A) - @test_throws ErrorException eig(A) - @test_throws ErrorException inv(A) -end - -@testset "issue #13792, use sparse triangular solvers for sparse triangular solves" begin - n = 100 - A = sprandn(n, n, 0.5) + sqrt(n)*I - x = LowerTriangular(A)*ones(n) - @test LowerTriangular(A)\x ≈ ones(n) - x = UpperTriangular(A)*ones(n) - @test UpperTriangular(A)\x ≈ ones(n) - A[2,2] = 0 - dropzeros!(A) - @test_throws LinAlg.SingularException LowerTriangular(A)\ones(n) - @test_throws LinAlg.SingularException UpperTriangular(A)\ones(n) -end - -@testset "issue described in https://groups.google.com/forum/#!topic/julia-dev/QT7qpIpgOaA" begin - @test sparse([1,1], [1,1], [true, true]) == sparse([1,1], [1,1], [true, true], 1, 1) == fill(true, 1, 1) - @test sparsevec([1,1], [true, true]) == sparsevec([1,1], [true, true], 1) == fill(true, 1) -end - -@testset "issparse for specialized matrix types" begin - m = sprand(10, 10, 0.1) - @test issparse(Symmetric(m)) - @test issparse(Hermitian(m)) - @test issparse(LowerTriangular(m)) - @test issparse(LinAlg.UnitLowerTriangular(m)) - @test issparse(UpperTriangular(m)) - @test issparse(LinAlg.UnitUpperTriangular(m)) - @test issparse(Symmetric(Array(m))) == false - @test issparse(Hermitian(Array(m))) == false - @test issparse(LowerTriangular(Array(m))) == false - @test issparse(LinAlg.UnitLowerTriangular(Array(m))) == false - @test issparse(UpperTriangular(Array(m))) == false - @test issparse(LinAlg.UnitUpperTriangular(Array(m))) == false -end - -@testset "test created type of sprand{T}(::Type{T}, m::Integer, n::Integer, density::AbstractFloat)" begin - m = sprand(Float32, 10, 10, 0.1) - @test eltype(m) == Float32 - m = sprand(Float64, 10, 10, 0.1) - @test eltype(m) == Float64 - m = sprand(Int32, 10, 10, 0.1) - @test eltype(m) == Int32 -end - -@testset "issue #16073" begin - @inferred sprand(1, 1, 1.0) - @inferred sprand(1, 1, 1.0, rand, Float64) - @inferred sprand(1, 1, 1.0, x -> round.(Int, rand(x) * 100)) -end - -# Test that concatenations of combinations of sparse matrices with sparse matrices or dense -# matrices/vectors yield sparse arrays -@testset "sparse and dense concatenations" begin - N = 4 - densevec = ones(N) - densemat = diagm(ones(N)) - spmat = spdiagm(ones(N)) - # Test that concatenations of pairs of sparse matrices yield sparse arrays - @test issparse(vcat(spmat, spmat)) - @test issparse(hcat(spmat, spmat)) - @test issparse(hvcat((2,), spmat, spmat)) - @test issparse(cat((1,2), spmat, spmat)) - # Test that concatenations of a sparse matrice with a dense matrix/vector yield sparse arrays - @test issparse(vcat(spmat, densemat)) - @test issparse(vcat(densemat, spmat)) - for densearg in (densevec, densemat) - @test issparse(hcat(spmat, densearg)) - @test issparse(hcat(densearg, spmat)) - @test issparse(hvcat((2,), spmat, densearg)) - @test issparse(hvcat((2,), densearg, spmat)) - @test issparse(cat((1,2), spmat, densearg)) - @test issparse(cat((1,2), densearg, spmat)) - end -end - -@testset "issue #14816" begin - m = 5 - intmat = fill(1, m, m) - ltintmat = LowerTriangular(rand(1:5, m, m)) - @test At_ldiv_B(ltintmat, sparse(intmat)) ≈ At_ldiv_B(ltintmat, intmat) -end - -# Test temporary fix for issue #16548 in PR #16979. Somewhat brittle. Expect to remove with `\` revisions. -@testset "issue #16548" begin - ms = methods(\, (SparseMatrixCSC, AbstractVecOrMat)).ms - @test all(m -> m.module == Base.SparseArrays, ms) -end - -@testset "row indexing a SparseMatrixCSC with non-Int integer type" begin - A = sparse(UInt32[1,2,3], UInt32[1,2,3], [1.0,2.0,3.0]) - @test A[1,1:3] == A[1,:] == [1,0,0] -end - -# Check that `broadcast` methods specialized for unary operations over `SparseMatrixCSC`s -# are called. (Issue #18705.) EDIT: #19239 unified broadcast over a single sparse matrix, -# eliminating the former operation classes. -@testset "issue #18705" begin - @test isa(sin.(spdiagm(1.0:5.0)), SparseMatrixCSC) -end - -@testset "issue #19225" begin - X = sparse([1 -1; -1 1]) - for T in (Symmetric, Hermitian) - Y = T(copy(X)) - _Y = similar(Y) - copy!(_Y, Y) - @test _Y == Y - - W = T(copy(X), :L) - copy!(W, Y) - @test W.data == Y.data - @test W.uplo != Y.uplo - - W[1,1] = 4 - @test W == T(sparse([4 -1; -1 1])) - @test_throws ArgumentError (W[1,2] = 2) - - @test Y + I == T(sparse([2 -1; -1 2])) - @test Y - I == T(sparse([0 -1; -1 0])) - @test Y * I == Y - - @test Y + 1 == T(sparse([2 0; 0 2])) - @test Y - 1 == T(sparse([0 -2; -2 0])) - @test Y * 2 == T(sparse([2 -2; -2 2])) - @test Y / 1 == Y - end -end - -@testset "issue #19304" begin - @inferred hcat(sparse(rand(2,1)), eye(2,2)) -end - -# Check that `broadcast` methods specialized for unary operations over -# `SparseMatrixCSC`s determine a reasonable return type. -@testset "issue #18974" begin - @test eltype(sin.(spdiagm(Int64(1):Int64(4)))) == Float64 -end - -# Check calling of unary minus method specialized for SparseMatrixCSCs -@testset "issue #19503" begin - @test which(-, (SparseMatrixCSC,)).module == Base.SparseArrays -end - -@testset "issue #14398" begin - @test transpose(view(speye(10), 1:5, 1:5)) ≈ eye(5,5) -end - -@testset "dropstored issue #20513" begin - x = sparse(rand(3,3)) - Base.SparseArrays.dropstored!(x, 1, 1) - @test x[1, 1] == 0.0 - @test x.colptr == [1, 3, 6, 9] - Base.SparseArrays.dropstored!(x, 2, 1) - @test x.colptr == [1, 2, 5, 8] - @test x[2, 1] == 0.0 - Base.SparseArrays.dropstored!(x, 2, 2) - @test x.colptr == [1, 2, 4, 7] - @test x[2, 2] == 0.0 - Base.SparseArrays.dropstored!(x, 2, 3) - @test x.colptr == [1, 2, 4, 6] - @test x[2, 3] == 0.0 -end - -@testset "setindex issue #20657" begin - A = spzeros(3, 3) - I = [1, 1, 1]; J = [1, 1, 1] - A[I, 1] = 1 - @test nnz(A) == 1 - A[1, J] = 1 - @test nnz(A) == 1 - A[I, J] = 1 - @test nnz(A) == 1 -end - -@testset "show" begin - io = IOBuffer() - show(io, MIME"text/plain"(), sparse(Int64[1], Int64[1], [1.0])) - @test String(take!(io)) == "1×1 SparseMatrixCSC{Float64,Int64} with 1 stored entry:\n [1, 1] = 1.0" - show(io, MIME"text/plain"(), spzeros(Float32, Int64, 2, 2)) - @test String(take!(io)) == "2×2 SparseMatrixCSC{Float32,Int64} with 0 stored entries" -end - -@testset "similar aliasing" begin - a = sparse(rand(3,3) .+ 0.1) - b = similar(a, Float32, Int32) - c = similar(b, Float32, Int32) - Base.SparseArrays.dropstored!(b, 1, 1) - @test length(c.rowval) == 9 - @test length(c.nzval) == 9 -end - -@testset "check buffers" for n in 1:3 - colptr = [1,2,3,4] - rowval = [1,2,3] - nzval1 = ones(0) - nzval2 = ones(3) - A = SparseMatrixCSC(n, n, colptr, rowval, nzval1) - @test nnz(A) == n - @test_throws BoundsError A[n,n] - A = SparseMatrixCSC(n, n, colptr, rowval, nzval2) - @test nnz(A) == n - @test A == eye(n) -end diff --git a/julia-0.6.3/share/julia/test/sparse/sparsevector.jl b/julia-0.6.3/share/julia/test/sparse/sparsevector.jl deleted file mode 100644 index 4ea50dc..0000000 --- a/julia-0.6.3/share/julia/test/sparse/sparsevector.jl +++ /dev/null @@ -1,1155 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -### Data - -spv_x1 = SparseVector(8, [2, 5, 6], [1.25, -0.75, 3.5]) - -@test isa(spv_x1, SparseVector{Float64,Int}) - -x1_full = zeros(length(spv_x1)) -x1_full[SparseArrays.nonzeroinds(spv_x1)] = nonzeros(spv_x1) - -### Basic Properties - -let x = spv_x1 - @test eltype(x) == Float64 - @test ndims(x) == 1 - @test length(x) == 8 - @test size(x) == (8,) - @test size(x,1) == 8 - @test size(x,2) == 1 - @test !isempty(x) - - @test countnz(x) == 3 - @test nnz(x) == 3 - @test SparseArrays.nonzeroinds(x) == [2, 5, 6] - @test nonzeros(x) == [1.25, -0.75, 3.5] -end - -@test count(SparseVector(8, [2, 5, 6], [true,false,true])) == 2 - -# full - -for (x, xf) in [(spv_x1, x1_full)] - @test isa(Array(x), Vector{Float64}) - @test Array(x) == xf -end - -### Show - -@test contains(string(spv_x1), "1.25") -@test contains(string(spv_x1), "-0.75") -@test contains(string(spv_x1), "3.5") - -### Other Constructors - -### Comparison helper to ensure exact equality with internal structure -function exact_equal(x::AbstractSparseVector, y::AbstractSparseVector) - eltype(x) == eltype(y) && - eltype(SparseArrays.nonzeroinds(x)) == eltype(SparseArrays.nonzeroinds(y)) && - length(x) == length(y) && - SparseArrays.nonzeroinds(x) == SparseArrays.nonzeroinds(y) && - nonzeros(x) == nonzeros(y) -end - -# construct empty sparse vector - -@test exact_equal(spzeros(Float64, 8), SparseVector(8, Int[], Float64[])) - -# from list of indices and values - -@test exact_equal( - sparsevec(Int[], Float64[], 8), - SparseVector(8, Int[], Float64[])) - -@test exact_equal( - sparsevec(Int[], Float64[]), - SparseVector(0, Int[], Float64[])) - -@test exact_equal( - sparsevec([3, 3], [5.0, -5.0], 8), - SparseVector(8, [3], [0.0])) - -@test exact_equal( - sparsevec([2, 3, 6], [12.0, 18.0, 25.0]), - SparseVector(6, [2, 3, 6], [12.0, 18.0, 25.0])) - -let x0 = SparseVector(8, [2, 3, 6], [12.0, 18.0, 25.0]) - @test exact_equal( - sparsevec([2, 3, 6], [12.0, 18.0, 25.0], 8), x0) - - @test exact_equal( - sparsevec([3, 6, 2], [18.0, 25.0, 12.0], 8), x0) - - @test exact_equal( - sparsevec([2, 3, 4, 4, 6], [12.0, 18.0, 5.0, -5.0, 25.0], 8), - SparseVector(8, [2, 3, 4, 6], [12.0, 18.0, 0.0, 25.0])) - - @test exact_equal( - sparsevec([1, 1, 1, 2, 3, 3, 6], [2.0, 3.0, -5.0, 12.0, 10.0, 8.0, 25.0], 8), - SparseVector(8, [1, 2, 3, 6], [0.0, 12.0, 18.0, 25.0])) - - @test exact_equal( - sparsevec([2, 3, 6, 7, 7], [12.0, 18.0, 25.0, 5.0, -5.0], 8), - SparseVector(8, [2, 3, 6, 7], [12.0, 18.0, 25.0, 0.0])) -end - -@test exact_equal( - sparsevec(Any[1, 3], [1, 1]), - sparsevec([1, 3], [1, 1])) - -@test exact_equal( - sparsevec(Any[1, 3], [1, 1], 5), - sparsevec([1, 3], [1, 1], 5)) - -# from dictionary - -function my_intmap(x) - a = Dict{Int,eltype(x)}() - for i in SparseArrays.nonzeroinds(x) - a[i] = x[i] - end - return a -end - -let x = spv_x1 - a = my_intmap(x) - xc = sparsevec(a, 8) - @test exact_equal(x, xc) - - xc = sparsevec(a) - @test exact_equal(xc, SparseVector(6, [2, 5, 6], [1.25, -0.75, 3.5])) - - d = Dict{Int, Float64}((1 => 0.0, 2 => 1.0, 3 => 2.0)) - @test exact_equal(sparsevec(d), SparseVector(3, [1, 2, 3], [0.0, 1.0, 2.0])) -end - -# spones - copies structure, but replaces nzvals with ones -let x = SparseVector(8, [2, 3, 6], [12.0, 18.0, 25.0]) - y = spones(x) - @test (x .!= 0) == (y .!= 0) - @test y == SparseVector(8, [2, 3, 6], [1.0, 1.0, 1.0]) -end - -# sprand & sprandn - -let xr = sprand(1000, 0.9) - @test isa(xr, SparseVector{Float64,Int}) - @test length(xr) == 1000 - @test all(nonzeros(xr) .>= 0.0) -end - -let xr = sprand(Float32, 1000, 0.9) - @test isa(xr, SparseVector{Float32,Int}) - @test length(xr) == 1000 - @test all(nonzeros(xr) .>= 0.0) -end - -let xr = sprandn(1000, 0.9) - @test isa(xr, SparseVector{Float64,Int}) - @test length(xr) == 1000 - if !isempty(nonzeros(xr)) - @test any(nonzeros(xr) .> 0.0) && any(nonzeros(xr) .< 0.0) - end -end - -let xr = sprand(Bool, 1000, 0.9) - @test isa(xr, SparseVector{Bool,Int}) - @test length(xr) == 1000 - @test all(nonzeros(xr)) -end - -let r1 = MersenneTwister(0), r2 = MersenneTwister(0) - @test sprand(r1, 100, .9) == sprand(r2, 100, .9) - @test sprandn(r1, 100, .9) == sprandn(r2, 100, .9) - @test sprand(r1, Bool, 100, .9) == sprand(r2, Bool, 100, .9) -end - -### Element access - -# getindex - -# single integer index -for (x, xf) in [(spv_x1, x1_full)] - for i = 1:length(x) - @test x[i] == xf[i] - end -end - -# generic array index -let x = sprand(100, 0.5) - I = rand(1:length(x), 20) - r = x[I] - @test isa(r, SparseVector{Float64,Int}) - @test all(nonzeros(r) .!= 0.0) - @test Array(r) == Array(x)[I] -end - -# boolean array index -let x = sprand(10, 10, 0.5) - I = rand(1:size(x, 2), 10) - bI = falses(size(x, 2)) - bI[I] = true - r = x[1,bI] - @test isa(r, SparseVector{Float64,Int}) - @test all(nonzeros(r) .!= 0.0) - @test Array(r) == Array(x)[1,bI] -end - -let x = sprand(10, 0.5) - I = rand(1:length(x), 5) - bI = falses(length(x)) - bI[I] = true - r = x[bI] - @test isa(r, SparseVector{Float64,Int}) - @test all(nonzeros(r) .!= 0.0) - @test Array(r) == Array(x)[bI] -end - -# setindex - -let xc = spzeros(Float64, 8) - xc[3] = 2.0 - @test exact_equal(xc, SparseVector(8, [3], [2.0])) -end - -let xc = copy(spv_x1) - xc[5] = 2.0 - @test exact_equal(xc, SparseVector(8, [2, 5, 6], [1.25, 2.0, 3.5])) -end - -let xc = copy(spv_x1) - xc[3] = 4.0 - @test exact_equal(xc, SparseVector(8, [2, 3, 5, 6], [1.25, 4.0, -0.75, 3.5])) - - xc[1] = 6.0 - @test exact_equal(xc, SparseVector(8, [1, 2, 3, 5, 6], [6.0, 1.25, 4.0, -0.75, 3.5])) - - xc[8] = -1.5 - @test exact_equal(xc, SparseVector(8, [1, 2, 3, 5, 6, 8], [6.0, 1.25, 4.0, -0.75, 3.5, -1.5])) -end - -let xc = copy(spv_x1) - xc[5] = 0.0 - @test exact_equal(xc, SparseVector(8, [2, 5, 6], [1.25, 0.0, 3.5])) - - xc[6] = 0.0 - @test exact_equal(xc, SparseVector(8, [2, 5, 6], [1.25, 0.0, 0.0])) - - xc[2] = 0.0 - @test exact_equal(xc, SparseVector(8, [2, 5, 6], [0.0, 0.0, 0.0])) - - xc[1] = 0.0 - @test exact_equal(xc, SparseVector(8, [2, 5, 6], [0.0, 0.0, 0.0])) -end - -## dropstored! tests -let x = SparseVector(10, [2, 7, 9], [2.0, 7.0, 9.0]) - # Test argument bounds checking for dropstored!(x, i) - @test_throws BoundsError Base.SparseArrays.dropstored!(x, 0) - @test_throws BoundsError Base.SparseArrays.dropstored!(x, 11) - # Test behavior of dropstored!(x, i) - # --> Test dropping a single stored entry - @test Base.SparseArrays.dropstored!(x, 2) == SparseVector(10, [7, 9], [7.0, 9.0]) - # --> Test dropping a single nonstored entry - @test Base.SparseArrays.dropstored!(x, 5) == SparseVector(10, [7, 9], [7.0, 9.0]) -end - -# find and findnz tests -@test find(spv_x1) == find(x1_full) -@test findnz(spv_x1) == (find(x1_full), filter(x->x!=0, x1_full)) -let xc = SparseVector(8, [2, 3, 5], [1.25, 0, -0.75]), fc = Array(xc) - @test find(xc) == find(fc) - @test findnz(xc) == ([2, 5], [1.25, -0.75]) -end - -### Array manipulation - -# copy - -let x = spv_x1 - xc = copy(x) - @test isa(xc, SparseVector{Float64,Int}) - @test x.nzind !== xc.nzval - @test x.nzval !== xc.nzval - @test exact_equal(x, xc) -end - -let a = SparseVector(8, [2, 5, 6], Int32[12, 35, 72]) - # vec - @test vec(a) == a - - # reinterpret - au = reinterpret(UInt32, a) - @test isa(au, SparseVector{UInt32,Int}) - @test exact_equal(au, SparseVector(8, [2, 5, 6], UInt32[12, 35, 72])) - - # float - af = float(a) - @test float(af) == af - @test isa(af, SparseVector{Float64,Int}) - @test exact_equal(af, SparseVector(8, [2, 5, 6], [12., 35., 72.])) - @test sparsevec(transpose(transpose(af))) == af - - # complex - acp = complex(af) - @test complex(acp) == acp - @test isa(acp, SparseVector{Complex128,Int}) - @test exact_equal(acp, SparseVector(8, [2, 5, 6], complex([12., 35., 72.]))) - @test sparsevec(ctranspose(ctranspose(acp))) == acp -end - -let x1 = SparseVector(8, [2, 5, 6], [12.2, 1.4, 5.0]) - x2 = SparseVector(8, [3, 4], [1.2, 3.4]) - copy!(x2, x1) - @test x2 == x1 - x2 = SparseVector(8, [2, 4, 8], [10.3, 7.4, 3.1]) - copy!(x2, x1) - @test x2 == x1 - x2 = SparseVector(8, [1, 3, 4, 7], [0.3, 1.2, 3.4, 0.1]) - copy!(x2, x1) - @test x2 == x1 - x2 = SparseVector(10, [3, 4], [1.2, 3.4]) - copy!(x2, x1) - @test x2[1:8] == x1 - @test x2[9:10] == spzeros(2) - x2 = SparseVector(10, [3, 4, 9], [1.2, 3.4, 17.8]) - copy!(x2, x1) - @test x2[1:8] == x1 - @test x2[9] == 17.8 - @test x2[10] == 0 - x2 = SparseVector(10, [3, 4, 5, 6, 9], [8.3, 7.2, 1.2, 3.4, 17.8]) - copy!(x2, x1) - @test x2[1:8] == x1 - @test x2[9] == 17.8 - @test x2[10] == 0 - x2 = SparseVector(6, [3, 4], [1.2, 3.4]) - @test_throws BoundsError copy!(x2, x1) -end - -let x1 = sparse([2, 1, 2], [1, 3, 3], [12.2, 1.4, 5.0], 2, 4) - x2 = SparseVector(8, [3, 4], [1.2, 3.4]) - copy!(x2, x1) - @test x2[:] == x1[:] - x2 = SparseVector(8, [2, 4, 8], [10.3, 7.4, 3.1]) - copy!(x2, x1) - @test x2[:] == x1[:] - x2 = SparseVector(8, [1, 3, 4, 7], [0.3, 1.2, 3.4, 0.1]) - copy!(x2, x1) - @test x2[:] == x1[:] - x2 = SparseVector(10, [3, 4], [1.2, 3.4]) - copy!(x2, x1) - @test x2[1:8] == x1[:] - @test x2[9:10] == spzeros(2) - x2 = SparseVector(10, [3, 4, 9], [1.2, 3.4, 17.8]) - copy!(x2, x1) - @test x2[1:8] == x1[:] - @test x2[9] == 17.8 - @test x2[10] == 0 - x2 = SparseVector(10, [3, 4, 5, 6, 9], [8.3, 7.2, 1.2, 3.4, 17.8]) - copy!(x2, x1) - @test x2[1:8] == x1[:] - @test x2[9] == 17.8 - @test x2[10] == 0 - x2 = SparseVector(6, [3, 4], [1.2, 3.4]) - @test_throws BoundsError copy!(x2, x1) -end - -let x1 = SparseVector(8, [2, 5, 6], [12.2, 1.4, 5.0]) - x2 = sparse([1, 2], [2, 2], [1.2, 3.4], 2, 4) - copy!(x2, x1) - @test x2[:] == x1[:] - x2 = sparse([2, 2, 2], [1, 3, 4], [10.3, 7.4, 3.1], 2, 4) - copy!(x2, x1) - @test x2[:] == x1[:] - x2 = sparse([1, 1, 2, 1], [1, 2, 2, 4], [0.3, 1.2, 3.4, 0.1], 2, 4) - copy!(x2, x1) - @test x2[:] == x1[:] - x2 = sparse([1, 2], [2, 2], [1.2, 3.4], 2, 5) - copy!(x2, x1) - @test x2[1:8] == x1 - @test x2[9:10] == spzeros(2) - x2 = sparse([1, 2, 1], [2, 2, 5], [1.2, 3.4, 17.8], 2, 5) - copy!(x2, x1) - @test x2[1:8] == x1 - @test x2[9] == 17.8 - @test x2[10] == 0 - x2 = sparse([1, 2, 1, 2, 1], [2, 2, 3, 3, 5], [8.3, 7.2, 1.2, 3.4, 17.8], 2, 5) - copy!(x2, x1) - @test x2[1:8] == x1 - @test x2[9] == 17.8 - @test x2[10] == 0 - x2 = sparse([1, 2], [2, 2], [1.2, 3.4], 2, 3) - @test_throws BoundsError copy!(x2, x1) -end - -### Type conversion - -let x = convert(SparseVector, sparse([2, 5, 6], [1, 1, 1], [1.25, -0.75, 3.5], 8, 1)) - @test isa(x, SparseVector{Float64,Int}) - @test exact_equal(x, spv_x1) -end - -let x = spv_x1, xf = x1_full - xc = convert(SparseVector, xf) - @test isa(xc, SparseVector{Float64,Int}) - @test exact_equal(xc, x) - - xc = convert(SparseVector{Float32,Int}, x) - xf32 = SparseVector(8, [2, 5, 6], [1.25f0, -0.75f0, 3.5f0]) - @test isa(xc, SparseVector{Float32,Int}) - @test exact_equal(xc, xf32) - - xc = convert(SparseVector{Float32}, x) - @test isa(xc, SparseVector{Float32,Int}) - @test exact_equal(xc, xf32) - - xm = convert(SparseMatrixCSC, x) - @test isa(xm, SparseMatrixCSC{Float64,Int}) - @test Array(xm) == reshape(xf, 8, 1) - - xm = convert(SparseMatrixCSC{Float32}, x) - @test isa(xm, SparseMatrixCSC{Float32,Int}) - @test Array(xm) == reshape(convert(Vector{Float32}, xf), 8, 1) -end - - -### Concatenation - -let m = 80, n = 100 - A = Array{SparseVector{Float64,Int}}(n) - tnnz = 0 - for i = 1:length(A) - A[i] = sprand(m, 0.3) - tnnz += nnz(A[i]) - end - - H = hcat(A...) - @test isa(H, SparseMatrixCSC{Float64,Int}) - @test size(H) == (m, n) - @test nnz(H) == tnnz - Hr = zeros(m, n) - for j = 1:n - Hr[:,j] = Array(A[j]) - end - @test Array(H) == Hr - - V = vcat(A...) - @test isa(V, SparseVector{Float64,Int}) - @test length(V) == m * n - Vr = vec(Hr) - @test Array(V) == Vr -end - -# Test that concatenations of combinations of sparse vectors with various other -# matrix/vector types yield sparse arrays -let N = 4 - spvec = spzeros(N) - spmat = spzeros(N, 1) - densevec = ones(N) - densemat = ones(N, 1) - diagmat = Diagonal(ones(4)) - # Test that concatenations of pairwise combinations of sparse vectors with dense - # vectors/matrices, sparse matrices, or special matrices yield sparse arrays - for othervecormat in (densevec, densemat, spmat) - @test issparse(vcat(spvec, othervecormat)) - @test issparse(vcat(othervecormat, spvec)) - end - for othervecormat in (densevec, densemat, spmat, diagmat) - @test issparse(hcat(spvec, othervecormat)) - @test issparse(hcat(othervecormat, spvec)) - @test issparse(hvcat((2,), spvec, othervecormat)) - @test issparse(hvcat((2,), othervecormat, spvec)) - @test issparse(cat((1,2), spvec, othervecormat)) - @test issparse(cat((1,2), othervecormat, spvec)) - end - # The preceding tests should cover multi-way combinations of those types, but for good - # measure test a few multi-way combinations involving those types - @test issparse(vcat(spvec, densevec, spmat, densemat)) - @test issparse(vcat(densevec, spvec, densemat, spmat)) - @test issparse(hcat(spvec, densemat, spmat, densevec, diagmat)) - @test issparse(hcat(densemat, spmat, spvec, densevec, diagmat)) - @test issparse(hvcat((5,), diagmat, densevec, spvec, densemat, spmat)) - @test issparse(hvcat((5,), spvec, densemat, diagmat, densevec, spmat)) - @test issparse(cat((1,2), densemat, diagmat, spmat, densevec, spvec)) - @test issparse(cat((1,2), spvec, diagmat, densevec, spmat, densemat)) -end -@testset "vertical concatenation of SparseVectors with different el- and ind-type (#22225)" begin - spv6464 = SparseVector(0, Int64[], Int64[]) - @test isa(vcat(spv6464, SparseVector(0, Int64[], Int32[])), SparseVector{Int64,Int64}) - @test isa(vcat(spv6464, SparseVector(0, Int32[], Int64[])), SparseVector{Int64,Int64}) - @test isa(vcat(spv6464, SparseVector(0, Int32[], Int32[])), SparseVector{Int64,Int64}) -end - -## sparsemat: combinations with sparse matrix - -let S = sprand(4, 8, 0.5) - Sf = Array(S) - @assert isa(Sf, Matrix{Float64}) - - # get a single column - for j = 1:size(S,2) - col = S[:, j] - @test isa(col, SparseVector{Float64,Int}) - @test length(col) == size(S,1) - @test Array(col) == Sf[:,j] - end - - # Get a reshaped vector - v = S[:] - @test isa(v, SparseVector{Float64,Int}) - @test length(v) == length(S) - @test Array(v) == Sf[:] - - # Get a linear subset - for i=0:length(S) - v = S[1:i] - @test isa(v, SparseVector{Float64,Int}) - @test length(v) == i - @test Array(v) == Sf[1:i] - end - for i=1:length(S)+1 - v = S[i:end] - @test isa(v, SparseVector{Float64,Int}) - @test length(v) == length(S) - i + 1 - @test Array(v) == Sf[i:end] - end - for i=0:div(length(S),2) - v = S[1+i:end-i] - @test isa(v, SparseVector{Float64,Int}) - @test length(v) == length(S) - 2i - @test Array(v) == Sf[1+i:end-i] - end -end - -let r = [1,10], S = sparse(r, r, r) - Sf = Array(S) - @assert isa(Sf, Matrix{Int}) - - inds = [1,1,1,1,1,1] - v = S[inds] - @test isa(v, SparseVector{Int,Int}) - @test length(v) == length(inds) - @test Array(v) == Sf[inds] - - inds = [2,2,2,2,2,2] - v = S[inds] - @test isa(v, SparseVector{Int,Int}) - @test length(v) == length(inds) - @test Array(v) == Sf[inds] - - # get a single column - for j = 1:size(S,2) - col = S[:, j] - @test isa(col, SparseVector{Int,Int}) - @test length(col) == size(S,1) - @test Array(col) == Sf[:,j] - end - - # Get a reshaped vector - v = S[:] - @test isa(v, SparseVector{Int,Int}) - @test length(v) == length(S) - @test Array(v) == Sf[:] - - # Get a linear subset - for i=0:length(S) - v = S[1:i] - @test isa(v, SparseVector{Int,Int}) - @test length(v) == i - @test Array(v) == Sf[1:i] - end - for i=1:length(S)+1 - v = S[i:end] - @test isa(v, SparseVector{Int,Int}) - @test length(v) == length(S) - i + 1 - @test Array(v) == Sf[i:end] - end - for i=0:div(length(S),2) - v = S[1+i:end-i] - @test isa(v, SparseVector{Int,Int}) - @test length(v) == length(S) - 2i - @test Array(v) == Sf[1+i:end-i] - end -end - -## math - -### Data - -rnd_x0 = sprand(50, 0.6) -rnd_x0f = Array(rnd_x0) - -rnd_x1 = sprand(50, 0.7) * 4.0 -rnd_x1f = Array(rnd_x1) - -spv_x1 = SparseVector(8, [2, 5, 6], [1.25, -0.75, 3.5]) -spv_x2 = SparseVector(8, [1, 2, 6, 7], [3.25, 4.0, -5.5, -6.0]) - -### Arithmetic operations - -let x = spv_x1, x2 = spv_x2 - # negate - @test exact_equal(-x, SparseVector(8, [2, 5, 6], [-1.25, 0.75, -3.5])) - - # abs and abs2 - @test exact_equal(abs.(x), SparseVector(8, [2, 5, 6], abs.([1.25, -0.75, 3.5]))) - @test exact_equal(abs2.(x), SparseVector(8, [2, 5, 6], abs2.([1.25, -0.75, 3.5]))) - - # plus and minus - xa = SparseVector(8, [1,2,5,6,7], [3.25,5.25,-0.75,-2.0,-6.0]) - - @test exact_equal(x + x, x * 2) - @test exact_equal(x + x2, xa) - @test exact_equal(x2 + x, xa) - - xb = SparseVector(8, [1,2,5,6,7], [-3.25,-2.75,-0.75,9.0,6.0]) - @test exact_equal(x - x, SparseVector(8, Int[], Float64[])) - @test exact_equal(x - x2, xb) - @test exact_equal(x2 - x, -xb) - - @test Array(x) + x2 == Array(xa) - @test Array(x) - x2 == Array(xb) - @test x + Array(x2) == Array(xa) - @test x - Array(x2) == Array(xb) - - # multiplies - xm = SparseVector(8, [2, 6], [5.0, -19.25]) - @test exact_equal(x .* x, abs2.(x)) - @test exact_equal(x .* x2, xm) - @test exact_equal(x2 .* x, xm) - - @test Array(x) .* x2 == Array(xm) - @test x .* Array(x2) == Array(xm) - - # max & min - @test exact_equal(max.(x, x), x) - @test exact_equal(min.(x, x), x) - @test exact_equal(max.(x, x2), - SparseVector(8, Int[1, 2, 6], Float64[3.25, 4.0, 3.5])) - @test exact_equal(min.(x, x2), - SparseVector(8, Int[2, 5, 6, 7], Float64[1.25, -0.75, -5.5, -6.0])) -end - -### Complex - -let x = spv_x1, x2 = spv_x2 - # complex - @test exact_equal(complex.(x, x), - SparseVector(8, [2,5,6], [1.25+1.25im, -0.75-0.75im, 3.5+3.5im])) - @test exact_equal(complex.(x, x2), - SparseVector(8, [1,2,5,6,7], [3.25im, 1.25+4.0im, -0.75+0.0im, 3.5-5.5im, -6.0im])) - @test exact_equal(complex.(x2, x), - SparseVector(8, [1,2,5,6,7], [3.25+0.0im, 4.0+1.25im, -0.75im, -5.5+3.5im, -6.0+0.0im])) - - # real, imag and conj - - @test real(x) === x - @test exact_equal(imag(x), spzeros(Float64, length(x))) - @test conj(x) === x - - xcp = complex.(x, x2) - @test exact_equal(real(xcp), x) - @test exact_equal(imag(xcp), x2) - @test exact_equal(conj(xcp), complex.(x, -x2)) -end - -### Zero-preserving math functions: sparse -> sparse - -function check_nz2z_z2z{T}(f::Function, x::SparseVector{T}, xf::Vector{T}) - R = typeof(f(zero(T))) - r = f(x) - isa(r, AbstractSparseVector) || error("$f(x) is not a sparse vector.") - eltype(r) == R || error("$f(x) results in eltype = $(eltype(r)), expect $R") - all(r.nzval .!= 0) || error("$f(x) contains zeros in nzval.") - Array(r) == f.(xf) || error("Incorrect results found in $f(x).") -end - -for f in [floor, ceil, trunc, round] - check_nz2z_z2z(f, rnd_x1, rnd_x1f) -end - -for f in [log1p, expm1, - sin, tan, sinpi, sind, tand, - asin, atan, asind, atand, - sinh, tanh, asinh, atanh] - check_nz2z_z2z(f, rnd_x0, rnd_x0f) -end - -### Non-zero-preserving math functions: sparse -> dense - -function check_z2nz{T}(f::Function, x::SparseVector{T}, xf::Vector{T}) - R = typeof(f(zero(T))) - r = f(x) - isa(r, Vector) || error("$f(x) is not a dense vector.") - eltype(r) == R || error("$f(x) results in eltype = $(eltype(r)), expect $R") - r == f.(xf) || error("Incorrect results found in $f(x).") -end - -for f in [exp, exp2, exp10, log, log2, log10, - cos, csc, cot, sec, cospi, - cosd, cscd, cotd, secd, - acos, acot, acosd, acotd, - cosh, csch, coth, sech, acsch, asech] - check_z2nz(f, rnd_x0, rnd_x0f) -end - - -### Reduction - -# sum, vecnorm - -let x = spv_x1 - @test sum(x) == 4.0 - @test sum(abs, x) == 5.5 - @test sum(abs2, x) == 14.375 - - @test vecnorm(x) == sqrt(14.375) - @test vecnorm(x, 1) == 5.5 - @test vecnorm(x, 2) == sqrt(14.375) - @test vecnorm(x, Inf) == 3.5 -end - -# maximum, minimum - -let x = spv_x1 - @test maximum(x) == 3.5 - @test minimum(x) == -0.75 - @test maximum(abs, x) == 3.5 - @test minimum(abs, x) == 0.0 -end - -let x = abs.(spv_x1) - @test maximum(x) == 3.5 - @test minimum(x) == 0.0 -end - -let x = -abs.(spv_x1) - @test maximum(x) == 0.0 - @test minimum(x) == -3.5 -end - -let x = SparseVector(3, [1, 2, 3], [-4.5, 2.5, 3.5]) - @test maximum(x) == 3.5 - @test minimum(x) == -4.5 - @test maximum(abs, x) == 4.5 - @test minimum(abs, x) == 2.5 -end - -let x = spzeros(Float64, 8) - @test maximum(x) == 0.0 - @test minimum(x) == 0.0 - @test maximum(abs, x) == 0.0 - @test minimum(abs, x) == 0.0 -end - - -### linalg - -### BLAS Level-1 - -let x = sprand(16, 0.5), x2 = sprand(16, 0.4) - xf = Array(x) - xf2 = Array(x2) - - # axpy! - for c in [1.0, -1.0, 2.0, -2.0] - y = Array(x) - @test Base.axpy!(c, x2, y) === y - @test y == Array(x2 * c + x) - end - - # scale - let α = 2.5, sx = SparseVector(x.n, x.nzind, x.nzval * α) - @test exact_equal(x * α, sx) - @test exact_equal(x * (α + 0.0*im), complex(sx)) - @test exact_equal(α * x, sx) - @test exact_equal((α + 0.0*im) * x, complex(sx)) - @test exact_equal(x * α, sx) - @test exact_equal(α * x, sx) - @test exact_equal(x .* α, sx) - @test exact_equal(α .* x, sx) - @test exact_equal(x / α, SparseVector(x.n, x.nzind, x.nzval / α)) - - xc = copy(x) - @test scale!(xc, α) === xc - @test exact_equal(xc, sx) - xc = copy(x) - @test scale!(α, xc) === xc - @test exact_equal(xc, sx) - xc = copy(x) - @test scale!(xc, complex(α, 0.0)) === xc - @test exact_equal(xc, sx) - xc = copy(x) - @test scale!(complex(α, 0.0), xc) === xc - @test exact_equal(xc, sx) - end - - # dot - let dv = dot(xf, xf2) - @test dot(x, x) == sum(abs2, x) - @test dot(x2, x2) == sum(abs2, x2) - @test dot(x, x2) ≈ dv - @test dot(x2, x) ≈ dv - @test dot(Array(x), x2) ≈ dv - @test dot(x, Array(x2)) ≈ dv - end -end - -let x = complex.(sprand(32, 0.6), sprand(32, 0.6)), - y = complex.(sprand(32, 0.6), sprand(32, 0.6)) - xf = Array(x)::Vector{Complex128} - yf = Array(y)::Vector{Complex128} - @test dot(x, x) ≈ dot(xf, xf) - @test dot(x, y) ≈ dot(xf, yf) -end - - -### BLAS Level-2: - -## dense A * sparse x -> dense y - -let A = randn(9, 16), x = sprand(16, 0.7) - xf = Array(x) - for α in [0.0, 1.0, 2.0], β in [0.0, 0.5, 1.0] - y = rand(9) - rr = α*A*xf + β*y - @test A_mul_B!(α, A, x, β, y) === y - @test y ≈ rr - end - y = A*x - @test isa(y, Vector{Float64}) - @test A*x ≈ A*xf -end - -let A = randn(16, 9), x = sprand(16, 0.7) - xf = Array(x) - for α in [0.0, 1.0, 2.0], β in [0.0, 0.5, 1.0] - y = rand(9) - rr = α*A'xf + β*y - @test At_mul_B!(α, A, x, β, y) === y - @test y ≈ rr - end - y = At_mul_B(A, x) - @test isa(y, Vector{Float64}) - @test y ≈ At_mul_B(A, xf) -end - -## sparse A * sparse x -> dense y - -let A = sprandn(9, 16, 0.5), x = sprand(16, 0.7) - Af = Array(A) - xf = Array(x) - for α in [0.0, 1.0, 2.0], β in [0.0, 0.5, 1.0] - y = rand(9) - rr = α*Af*xf + β*y - @test A_mul_B!(α, A, x, β, y) === y - @test y ≈ rr - end - y = SparseArrays.densemv(A, x) - @test isa(y, Vector{Float64}) - @test y ≈ Af*xf -end - -let A = sprandn(16, 9, 0.5), x = sprand(16, 0.7) - Af = Array(A) - xf = Array(x) - for α in [0.0, 1.0, 2.0], β in [0.0, 0.5, 1.0] - y = rand(9) - rr = α*Af'xf + β*y - @test At_mul_B!(α, A, x, β, y) === y - @test y ≈ rr - end - y = SparseArrays.densemv(A, x; trans='T') - @test isa(y, Vector{Float64}) - @test y ≈ At_mul_B(Af, xf) -end - -let A = complex.(sprandn(7, 8, 0.5), sprandn(7, 8, 0.5)), - x = complex.(sprandn(8, 0.6), sprandn(8, 0.6)), - x2 = complex.(sprandn(7, 0.75), sprandn(7, 0.75)) - Af = Array(A) - xf = Array(x) - x2f = Array(x2) - @test SparseArrays.densemv(A, x; trans='N') ≈ Af * xf - @test SparseArrays.densemv(A, x2; trans='T') ≈ Af.' * x2f - @test SparseArrays.densemv(A, x2; trans='C') ≈ Af'x2f - @test_throws ArgumentError SparseArrays.densemv(A, x; trans='D') -end - -## sparse A * sparse x -> sparse y - -let A = sprandn(9, 16, 0.5), x = sprand(16, 0.7), x2 = sprand(9, 0.7) - Af = Array(A) - xf = Array(x) - x2f = Array(x2) - - y = A*x - @test isa(y, SparseVector{Float64,Int}) - @test all(nonzeros(y) .!= 0.0) - @test Array(y) ≈ Af * xf - - y = At_mul_B(A, x2) - @test isa(y, SparseVector{Float64,Int}) - @test all(nonzeros(y) .!= 0.0) - @test Array(y) ≈ Af'x2f -end - -let A = complex.(sprandn(7, 8, 0.5), sprandn(7, 8, 0.5)), - x = complex.(sprandn(8, 0.6), sprandn(8, 0.6)), - x2 = complex.(sprandn(7, 0.75), sprandn(7, 0.75)) - Af = Array(A) - xf = Array(x) - x2f = Array(x2) - - y = A*x - @test isa(y, SparseVector{Complex128,Int}) - @test Array(y) ≈ Af * xf - - y = At_mul_B(A, x2) - @test isa(y, SparseVector{Complex128,Int}) - @test Array(y) ≈ Af.' * x2f - - y = Ac_mul_B(A, x2) - @test isa(y, SparseVector{Complex128,Int}) - @test Array(y) ≈ Af'x2f -end - -# left-division operations involving triangular matrices and sparse vectors (#14005) -let m = 10 - sparsefloatvecs = SparseVector[sprand(m, 0.4) for k in 1:3] - sparseintvecs = SparseVector[SparseVector(m, sprvec.nzind, round.(Int, sprvec.nzval*10)) for sprvec in sparsefloatvecs] - sparsecomplexvecs = SparseVector[SparseVector(m, sprvec.nzind, complex.(sprvec.nzval, sprvec.nzval)) for sprvec in sparsefloatvecs] - - sprmat = sprand(m, m, 0.2) - sparsefloatmat = speye(m) + sprmat/(2m) - sparsecomplexmat = speye(m) + SparseMatrixCSC(m, m, sprmat.colptr, sprmat.rowval, complex.(sprmat.nzval, sprmat.nzval)/(4m)) - sparseintmat = speye(Int, m)*10m + SparseMatrixCSC(m, m, sprmat.colptr, sprmat.rowval, round.(Int, sprmat.nzval*10)) - - denseintmat = eye(Int, m)*10m + rand(1:m, m, m) - densefloatmat = eye(m) + randn(m, m)/(2m) - densecomplexmat = eye(m) + complex.(randn(m, m), randn(m, m))/(4m) - - inttypes = (Int32, Int64, BigInt) - floattypes = (Float32, Float64, BigFloat) - complextypes = (Complex{Float32}, Complex{Float64}) - eltypes = (inttypes..., floattypes..., complextypes...) - - for eltypemat in eltypes - (densemat, sparsemat) = eltypemat in inttypes ? (denseintmat, sparseintmat) : - eltypemat in floattypes ? (densefloatmat, sparsefloatmat) : - eltypemat in complextypes && (densecomplexmat, sparsecomplexmat) - densemat = convert(Matrix{eltypemat}, densemat) - sparsemat = convert(SparseMatrixCSC{eltypemat}, sparsemat) - trimats = (LowerTriangular(densemat), UpperTriangular(densemat), - LowerTriangular(sparsemat), UpperTriangular(sparsemat) ) - unittrimats = (Base.LinAlg.UnitLowerTriangular(densemat), Base.LinAlg.UnitUpperTriangular(densemat), - Base.LinAlg.UnitLowerTriangular(sparsemat), Base.LinAlg.UnitUpperTriangular(sparsemat) ) - - for eltypevec in eltypes - spvecs = eltypevec in inttypes ? sparseintvecs : - eltypevec in floattypes ? sparsefloatvecs : - eltypevec in complextypes && sparsecomplexvecs - spvecs = SparseVector[SparseVector(m, spvec.nzind, convert(Vector{eltypevec}, spvec.nzval)) for spvec in spvecs] - - for spvec in spvecs - fspvec = convert(Array, spvec) - # test out-of-place left-division methods - for mat in (trimats..., unittrimats...), func in (\, At_ldiv_B, Ac_ldiv_B) - @test func(mat, spvec) ≈ func(mat, fspvec) - end - # test in-place left-division methods not involving quotients - if eltypevec == typeof(zero(eltypemat)*zero(eltypevec) + zero(eltypemat)*zero(eltypevec)) - for mat in unittrimats, func in (A_ldiv_B!, Base.LinAlg.At_ldiv_B!, Base.LinAlg.Ac_ldiv_B!) - @test func(mat, copy(spvec)) ≈ func(mat, copy(fspvec)) - end - end - # test in-place left-division methods involving quotients - if eltypevec == typeof((zero(eltypemat)*zero(eltypevec) + zero(eltypemat)*zero(eltypevec))/one(eltypemat)) - for mat in trimats, func in (A_ldiv_B!, Base.LinAlg.At_ldiv_B!, Base.LinAlg.Ac_ldiv_B!) - @test func(mat, copy(spvec)) ≈ func(mat, copy(fspvec)) - end - end - end - end - end -end -# The preceding tests miss the edge case where the sparse vector is empty (#16716) -let origmat = [-1.5 -0.7; 0.0 1.0] - transmat = transpose(origmat) - utmat = UpperTriangular(origmat) - ltmat = LowerTriangular(transmat) - uutmat = Base.LinAlg.UnitUpperTriangular(origmat) - ultmat = Base.LinAlg.UnitLowerTriangular(transmat) - - zerospvec = spzeros(Float64, 2) - zerodvec = zeros(Float64, 2) - - for mat in (utmat, ltmat, uutmat, ultmat) - for func in (\, At_ldiv_B, Ac_ldiv_B) - @test isequal((func)(mat, zerospvec), zerodvec) - end - for ipfunc in (A_ldiv_B!, Base.LinAlg.At_ldiv_B!, Base.LinAlg.Ac_ldiv_B!) - @test isequal((ipfunc)(mat, copy(zerospvec)), zerospvec) - end - end -end - -# fkeep! -let x = sparsevec(1:7, [3., 2., -1., 1., -2., -3., 3.], 7) - # droptol - xdrop = Base.droptol!(copy(x), 1.5) - @test exact_equal(xdrop, SparseVector(7, [1, 2, 5, 6, 7], [3., 2., -2., -3., 3.])) - Base.droptol!(xdrop, 2.5) - @test exact_equal(xdrop, SparseVector(7, [1, 6, 7], [3., -3., 3.])) - Base.droptol!(xdrop, 3.) - @test exact_equal(xdrop, SparseVector(7, Int[], Float64[])) - - xdrop = copy(x) - # This will keep index 1, 3, 4, 7 in xdrop - f_drop(i, x) = (abs(x) == 1.) || (i in [1, 7]) - Base.SparseArrays.fkeep!(xdrop, f_drop) - @test exact_equal(xdrop, SparseVector(7, [1, 3, 4, 7], [3., -1., 1., 3.])) -end - -# dropzeros[!] -let testdims = (10, 20, 30), nzprob = 0.4, targetnumposzeros = 5, targetnumnegzeros = 5 - for m in testdims - v = sprand(m, nzprob) - struczerosv = find(x -> x == 0, v) - poszerosinds = unique(rand(struczerosv, targetnumposzeros)) - negzerosinds = unique(rand(struczerosv, targetnumnegzeros)) - vposzeros = setindex!(copy(v), 2, poszerosinds) - vnegzeros = setindex!(copy(v), -2, negzerosinds) - vbothsigns = setindex!(copy(vposzeros), -2, negzerosinds) - map!(x -> x == 2 ? 0.0 : x, vposzeros.nzval, vposzeros.nzval) - map!(x -> x == -2 ? -0.0 : x, vnegzeros.nzval, vnegzeros.nzval) - map!(x -> x == 2 ? 0.0 : x == -2 ? -0.0 : x, vbothsigns.nzval, vbothsigns.nzval) - for vwithzeros in (vposzeros, vnegzeros, vbothsigns) - # Basic functionality / dropzeros! - @test dropzeros!(copy(vwithzeros)) == v - @test dropzeros!(copy(vwithzeros), false) == v - # Basic functionality / dropzeros - @test dropzeros(vwithzeros) == v - @test dropzeros(vwithzeros, false) == v - # Check trimming works as expected - @test length(dropzeros!(copy(vwithzeros)).nzval) == length(v.nzval) - @test length(dropzeros!(copy(vwithzeros)).nzind) == length(v.nzind) - @test length(dropzeros!(copy(vwithzeros), false).nzval) == length(vwithzeros.nzval) - @test length(dropzeros!(copy(vwithzeros), false).nzind) == length(vwithzeros.nzind) - end - end - # original dropzeros! test - xdrop = sparsevec(1:7, [3., 2., -1., 1., -2., -3., 3.], 7) - xdrop.nzval[[2, 4, 6]] = 0.0 - Base.SparseArrays.dropzeros!(xdrop) - @test exact_equal(xdrop, SparseVector(7, [1, 3, 5, 7], [3, -1., -2., 3.])) -end - -# It's tempting to share data between a SparseVector and a SparseMatrix, -# but if that's done, then modifications to one or the other will cause -# an inconsistent state: -sv = sparse(1:10) -sm = convert(SparseMatrixCSC, sv) -sv[1] = 0 -@test Array(sm)[2:end] == collect(2:10) - -# Ensure that sparsevec with all-zero values returns an array of zeros -@test sparsevec([1,2,3],[0,0,0]) == [0,0,0] - -# Compare stored zero semantics between SparseVector and SparseMatrixCSC -let S = SparseMatrixCSC(10,1,[1,6],[1,3,5,6,7],[0,1,2,0,3]), x = SparseVector(10,[1,3,5,6,7],[0,1,2,0,3]) - @test nnz(S) == nnz(x) == 5 - for I = (:, 1:10, collect(1:10)) - @test S[I,1] == S[I] == x[I] == x - @test nnz(S[I,1]) == nnz(S[I]) == nnz(x[I]) == nnz(x) - end - for I = (2:9, 1:2, 9:10, [3,6,1], [10,9,8], []) - @test S[I,1] == S[I] == x[I] - @test nnz(S[I,1]) == nnz(S[I]) == nnz(x[I]) - end - @test S[[1 3 5; 2 4 6]] == x[[1 3 5; 2 4 6]] - @test nnz(S[[1 3 5; 2 4 6]]) == nnz(x[[1 3 5; 2 4 6]]) -end - - -# Issue 14013 -s14013 = sparse([10.0 0.0 30.0; 0.0 1.0 0.0]) -a14013 = [10.0 0.0 30.0; 0.0 1.0 0.0] -@test s14013 == a14013 -@test vec(s14013) == s14013[:] == a14013[:] -@test Array(s14013)[1,:] == s14013[1,:] == a14013[1,:] == [10.0, 0.0, 30.0] -@test Array(s14013)[2,:] == s14013[2,:] == a14013[2,:] == [0.0, 1.0, 0.0] - -# Issue 14046 -s14046 = sprand(5, 1.0) -@test spzeros(5) + s14046 == s14046 -@test 2*s14046 == s14046 + s14046 - -# Issue 14589 -# test vectors with no zero elements -x = sparsevec(1:7, [3., 2., -1., 1., -2., -3., 3.], 7) -@test collect(sort(x)) == sort(collect(x)) -# test vectors with all zero elements -x = sparsevec(Int64[], Float64[], 7) -@test collect(sort(x)) == sort(collect(x)) -# test vector with sparsity approx 1/2 -x = sparsevec(1:7, [3., 2., -1., 1., -2., -3., 3.], 15) -@test collect(sort(x)) == sort(collect(x)) -# apply three distinct tranformations where zeros sort into start/middle/end -@test collect(sort(x, by=abs)) == sort(collect(x), by=abs) -@test collect(sort(x, by=sign)) == sort(collect(x), by=sign) -@test collect(sort(x, by=inv)) == sort(collect(x), by=inv) - -# fill! -for Tv in [Float32, Float64, Int64, Int32, Complex128] - for Ti in [Int16, Int32, Int64, BigInt] - sptypes = (SparseMatrixCSC{Tv, Ti}, SparseVector{Tv, Ti}) - sizes = [(3, 4), (3,)] - for (siz, Sp) in zip(sizes, sptypes) - arr = rand(Tv, siz...) - sparr = Sp(arr) - fillval = rand(Tv) - fill!(sparr, fillval) - @test Array(sparr) == fillval * ones(arr) - fill!(sparr, 0) - @test Array(sparr) == zeros(arr) - end - end -end - -# ref 13130 and 16661 -@test issparse([sprand(10,10,.1) sprand(10,.1)]) -@test issparse([sprand(10,1,.1); sprand(10,.1)]) - -@test issparse([sprand(10,10,.1) rand(10)]) -@test issparse([sprand(10,1,.1) rand(10)]) -@test issparse([sprand(10,2,.1) sprand(10,1,.1) rand(10)]) -@test issparse([sprand(10,1,.1); rand(10)]) - -@test issparse([sprand(10,.1) rand(10)]) -@test issparse([sprand(10,.1); rand(10)]) - - -mutable struct t20488 end - -@testset "similar" begin - x = sparsevec(rand(3) .+ 0.1) - @test length(similar(x, t20488).nzval) == 3 - @test typeof(similar(x, Float32, Int32)) == SparseVector{Float32, Int32} - @test typeof(similar(x, Float32)) == SparseVector{Float32, Int} -end - -@testset "show" begin - io = IOBuffer() - show(io, MIME"text/plain"(), sparsevec(Int64[1], [1.0])) - @test String(take!(io)) == "1-element SparseVector{Float64,Int64} with 1 stored entry:\n [1] = 1.0" - show(io, MIME"text/plain"(), spzeros(Float64, Int64, 2)) - @test String(take!(io)) == "2-element SparseVector{Float64,Int64} with 0 stored entries" - show(io, similar(sparsevec(rand(3) .+ 0.1), t20488)) - @test String(take!(io)) == " [1] = #undef\n [2] = #undef\n [3] = #undef" -end - -@testset "spzeros with index type" begin - @test typeof(spzeros(Float32, Int16, 3)) == SparseVector{Float32,Int16} -end diff --git a/julia-0.6.3/share/julia/test/sparse/spqr.jl b/julia-0.6.3/share/julia/test/sparse/spqr.jl deleted file mode 100644 index eaa659d..0000000 --- a/julia-0.6.3/share/julia/test/sparse/spqr.jl +++ /dev/null @@ -1,60 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -using Base.SparseArrays.SPQR -using Base.SparseArrays.CHOLMOD - -let -m, n = 100, 10 -nn = 100 - -for eltyA in (Float64, Complex{Float64}) - for eltyB in (Int, Float64, Complex{Float64}) - if eltyA <: Real - A = sparse([1:n; rand(1:m, nn - n)], [1:n; rand(1:n, nn - n)], randn(nn), m, n) - else - A = sparse([1:n; rand(1:m, nn - n)], [1:n; rand(1:n, nn - n)], complex.(randn(nn), randn(nn)), m, n) - end - if eltyB == Int - B = rand(1:10, m, 2) - elseif eltyB <: Real - B = randn(m, 2) - else - B = complex.(randn(m, 2), randn(m, 2)) - end - - @inferred A\B - @test A\B[:,1] ≈ Array(A)\B[:,1] - @test A\B ≈ Array(A)\B - @test_throws DimensionMismatch A\B[1:m-1,:] - @test A[1:9,:]*(A[1:9,:]\ones(eltyB, 9)) ≈ ones(9) # Underdetermined system - - if eltyA == eltyB # promotions not defined for unexported methods - @test qrfact(sparse(eye(eltyA, 5)))\ones(eltyA, 5) == ones(5) - @test_throws ArgumentError SPQR.factorize(SPQR.ORDERING_DEFAULT, SPQR.DEFAULT_TOL, CHOLMOD.Sparse(sparse(eye(eltyA, 5)))) - @test_throws ArgumentError SPQR.Factorization(1, 1, convert(Ptr{SPQR.C_Factorization{eltyA}}, C_NULL)) - F = qrfact(A) - @test size(F) == (m,n) - @test size(F, 1) == m - @test size(F, 2) == n - @test size(F, 3) == 1 - @test_throws ArgumentError size(F, 0) - - # low level wrappers - @test_throws DimensionMismatch SPQR.solve(SPQR.RX_EQUALS_B, F, CHOLMOD.Dense(B')) - @test_throws DimensionMismatch SPQR.solve(SPQR.RTX_EQUALS_B, F, CHOLMOD.Dense(B)) - @test_throws DimensionMismatch SPQR.qmult(SPQR.QX, F, CHOLMOD.Dense(B')) - @test_throws DimensionMismatch SPQR.qmult(SPQR.XQ, F, CHOLMOD.Dense(B)) - @test A\B ≈ SPQR.backslash(SPQR.ORDERING_DEFAULT, SPQR.DEFAULT_TOL, CHOLMOD.Sparse(A), CHOLMOD.Dense(B)) - @test_throws DimensionMismatch SPQR.backslash(SPQR.ORDERING_DEFAULT, SPQR.DEFAULT_TOL, CHOLMOD.Sparse(A), CHOLMOD.Dense(B[1:m-1,:])) - end - end -end - -# Issue 14134 -F = qrfact(sprandn(10,5,0.5)) -b = IOBuffer() -serialize(b, F) -seekstart(b) -@test_throws ArgumentError deserialize(b)\ones(10) - -end diff --git a/julia-0.6.3/share/julia/test/sparse/umfpack.jl b/julia-0.6.3/share/julia/test/sparse/umfpack.jl deleted file mode 100644 index 2427310..0000000 --- a/julia-0.6.3/share/julia/test/sparse/umfpack.jl +++ /dev/null @@ -1,163 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -se33 = speye(3) -do33 = ones(3) -@test isequal(se33 \ do33, do33) - -# based on deps/Suitesparse-4.0.2/UMFPACK/Demo/umfpack_di_demo.c - -using Base.SparseArrays.UMFPACK.increment! - -A0 = sparse(increment!([0,4,1,1,2,2,0,1,2,3,4,4]), - increment!([0,4,0,2,1,2,1,4,3,2,1,2]), - [2.,1.,3.,4.,-1.,-3.,3.,6.,2.,1.,4.,2.], 5, 5) - -for Tv in (Float64, Complex128) - for Ti in Base.uniontypes(Base.SparseArrays.UMFPACK.UMFITypes) - A = convert(SparseMatrixCSC{Tv,Ti}, A0) - lua = lufact(A) - @test nnz(lua) == 18 - @test_throws KeyError lua[:Z] - L,U,p,q,Rs = lua[:(:)] - @test (Diagonal(Rs) * A)[p,q] ≈ L * U - - det(lua) ≈ det(Array(A)) - - b = [8., 45., -3., 3., 19.] - x = lua\b - @test x ≈ float([1:5;]) - - @test norm(A*x-b,1) < eps(1e4) - z = complex.(b,zeros(b)) - x = Base.SparseArrays.A_ldiv_B!(lua, z) - @test x ≈ float([1:5;]) - @test z === x - y = similar(z) - A_ldiv_B!(y, lua, complex.(b,zeros(b))) - @test y ≈ x - - @test norm(A*x-b,1) < eps(1e4) - - b = [8., 20., 13., 6., 17.] - x = lua'\b - @test x ≈ float([1:5;]) - - @test norm(A'*x-b,1) < eps(1e4) - z = complex.(b,zeros(b)) - x = Base.SparseArrays.Ac_ldiv_B!(lua, z) - @test x ≈ float([1:5;]) - @test x === z - y = similar(x) - Base.SparseArrays.Ac_ldiv_B!(y, lua, complex.(b,zeros(b))) - @test y ≈ x - - @test norm(A'*x-b,1) < eps(1e4) - x = lua.'\b - @test x ≈ float([1:5;]) - - @test norm(A.'*x-b,1) < eps(1e4) - x = Base.SparseArrays.At_ldiv_B!(lua,complex.(b,zeros(b))) - @test x ≈ float([1:5;]) - y = similar(x) - Base.SparseArrays.At_ldiv_B!(y, lua,complex.(b,zeros(b))) - @test y ≈ x - - @test norm(A.'*x-b,1) < eps(1e4) - - # Element promotion and type inference - @inferred lua\ones(Int, size(A, 2)) - end -end - -Ac0 = complex.(A0,A0) -for Ti in Base.uniontypes(Base.SparseArrays.UMFPACK.UMFITypes) - Ac = convert(SparseMatrixCSC{Complex128,Ti}, Ac0) - x = complex.(ones(size(Ac, 1)), ones(size(Ac,1))) - lua = lufact(Ac) - L,U,p,q,Rs = lua[:(:)] - @test (Diagonal(Rs) * Ac)[p,q] ≈ L * U - b = Ac*x - @test Ac\b ≈ x - b = Ac'*x - @test Ac'\b ≈ x - b = Ac.'*x - @test Ac.'\b ≈ x -end - -for elty in (Float64, Complex128) - for (m, n) in ((10,5), (5, 10)) - A = sparse([1:min(m,n); rand(1:m, 10)], [1:min(m,n); rand(1:n, 10)], elty == Float64 ? randn(min(m, n) + 10) : complex.(randn(min(m, n) + 10), randn(min(m, n) + 10))) - F = lufact(A) - L, U, p, q, Rs = F[:(:)] - @test (Diagonal(Rs) * A)[p,q] ≈ L * U - end -end - -#4523 - complex sparse \ -x = speye(2) + im * speye(2) -@test (x*(lufact(x) \ ones(2))) ≈ ones(2) - -@test det(sparse([1,3,3,1], [1,1,3,3], [1,1,1,1])) == 0 - -# UMFPACK_ERROR_n_nonpositive -@test_throws ArgumentError lufact(sparse(Int[], Int[], Float64[], 5, 0)) - -#15099 -for (Tin, Tout) in ( - (Complex32, Complex128), - (Complex64, Complex128), - (Complex128, Complex128), - (Float16, Float64), - (Float32, Float64), - (Float64, Float64), - (Int, Float64), - ) - - F = lufact(sparse(ones(Tin, 1, 1))) - L = sparse(ones(Tout, 1, 1)) - @test F[:p] == F[:q] == [1] - @test F[:Rs] == [1.0] - @test F[:L] == F[:U] == L - @test F[:(:)] == (L, L, [1], [1], [1.0]) -end - -for T in (BigFloat, Complex{BigFloat}) - @test_throws ArgumentError lufact(sparse(ones(T, 1, 1))) -end - -#size(::UmfpackLU) -let - m = n = 1 - F = lufact(sparse(ones(m, n))) - @test size(F) == (m, n) - @test size(F, 1) == m - @test size(F, 2) == n - @test size(F, 3) == 1 - @test_throws ArgumentError size(F,-1) -end - -let - a = rand(5) - @test_throws ArgumentError Base.SparseArrays.UMFPACK.solve!(a, lufact(speye(5,5)), a, Base.SparseArrays.UMFPACK.UMFPACK_A) - aa = complex(a) - @test_throws ArgumentError Base.SparseArrays.UMFPACK.solve!(aa, lufact(complex(speye(5,5))), aa, Base.SparseArrays.UMFPACK.UMFPACK_A) -end - -#18246,18244-lufact sparse pivot -let A = speye(4) - A[1:2,1:2] = [-.01 -200; 200 .001] - F = lufact(A) - @test F[:p] == [3 ; 4 ; 2 ; 1] -end - -# Test that A[c|t]_ldiv_B!{T<:Complex}(X::StridedMatrix{T}, lu::UmfpackLU{Float64}, -# B::StridedMatrix{T}) works as expected. -let N = 10, p = 0.5 - A = N*speye(N) + sprand(N, N, p) - X = zeros(Complex{Float64}, N, N) - B = complex.(rand(N, N), rand(N, N)) - luA, lufA = lufact(A), lufact(Array(A)) - @test A_ldiv_B!(copy(X), luA, B) ≈ A_ldiv_B!(copy(X), lufA, B) - @test At_ldiv_B!(copy(X), luA, B) ≈ At_ldiv_B!(copy(X), lufA, B) - @test Ac_ldiv_B!(copy(X), luA, B) ≈ Ac_ldiv_B!(copy(X), lufA, B) -end diff --git a/julia-0.6.3/share/julia/test/spawn.jl b/julia-0.6.3/share/julia/test/spawn.jl deleted file mode 100644 index f6c514c..0000000 --- a/julia-0.6.3/share/julia/test/spawn.jl +++ /dev/null @@ -1,468 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -################################### -# Cross Platform tests for spawn. # -################################### - -valgrind_off = ccall(:jl_running_on_valgrind, Cint, ()) == 0 - -yescmd = `yes` -echocmd = `echo` -sortcmd = `sort` -printfcmd = `printf` -truecmd = `true` -falsecmd = `false` -catcmd = `cat` -shcmd = `sh` -sleepcmd = `sleep` -lscmd = `ls` -if is_windows() - try # use busybox-w32 on windows - success(`busybox`) - yescmd = `busybox yes` - echocmd = `busybox echo` - sortcmd = `busybox sort` - printfcmd = `busybox printf` - truecmd = `busybox true` - falsecmd = `busybox false` - catcmd = `busybox cat` - shcmd = `busybox sh` - sleepcmd = `busybox sleep` - lscmd = `busybox ls` - end -end - -#### Examples used in the manual #### - -@test readstring(`$echocmd hello \| sort`) == "hello | sort\n" -@test readstring(pipeline(`$echocmd hello`, sortcmd)) == "hello\n" -@test length(spawn(pipeline(`$echocmd hello`, sortcmd)).processes) == 2 - -out = readstring(`$echocmd hello` & `$echocmd world`) -@test search(out,"world") != 0:-1 -@test search(out,"hello") != 0:-1 -@test readstring(pipeline(`$echocmd hello` & `$echocmd world`, sortcmd)) == "hello\nworld\n" - -@test (run(`$printfcmd " \033[34m[stdio passthrough ok]\033[0m\n"`); true) - -# Test for SIGPIPE being treated as normal termination (throws an error if broken) -is_unix() && run(pipeline(yescmd, `head`, DevNull)) - -begin - a = Base.Condition() - @schedule begin - p = spawn(pipeline(yescmd,DevNull)) - Base.notify(a,p) - @test !success(p) - end - p = wait(a) - kill(p) -end - -if valgrind_off - # If --trace-children=yes is passed to valgrind, valgrind will - # exit here with an error code, and no UVError will be raised. - @test_throws Base.UVError run(`foo_is_not_a_valid_command`) -end - -if is_unix() - prefixer(prefix, sleep) = `sh -c "while IFS= read REPLY; do echo '$prefix ' \$REPLY; sleep $sleep; done"` - @test success(pipeline(`sh -c "for i in 1 2 3 4 5 6 7 8 9 10; do echo \$i; sleep 0.1; done"`, - prefixer("A", 0.2) & prefixer("B", 0.2))) - @test success(pipeline(`sh -c "for i in 1 2 3 4 5 6 7 8 9 10; do echo \$i; sleep 0.1; done"`, - prefixer("X", 0.3) & prefixer("Y", 0.3) & prefixer("Z", 0.3), - prefixer("A", 0.2) & prefixer("B", 0.2))) -end - -@test success(truecmd) -@test !success(falsecmd) -@test success(pipeline(truecmd, truecmd)) -@test_broken success(ignorestatus(falsecmd)) -@test_broken success(pipeline(ignorestatus(falsecmd), truecmd)) -@test !success(pipeline(ignorestatus(falsecmd), falsecmd)) -@test !success(ignorestatus(falsecmd) & falsecmd) -@test_broken success(ignorestatus(pipeline(falsecmd, falsecmd))) -@test_broken success(ignorestatus(falsecmd & falsecmd)) - -# STDIN Redirection -let file = tempname() - run(pipeline(`$echocmd hello world`, file)) - @test readstring(pipeline(file, catcmd)) == "hello world\n" - @test open(readstring, pipeline(file, catcmd), "r") == "hello world\n" - rm(file) -end - -# Stream Redirection -if !is_windows() # WINNT reports operation not supported on socket (ENOTSUP) for this test - local r = Channel(1) - local port, server, sock, client, t1, t2 - t1 = @async begin - port, server = listenany(2326) - put!(r, port) - client = accept(server) - @test readstring(pipeline(client, catcmd)) == "hello world\n" - close(server) - return true - end - t2 = @async begin - sock = connect(fetch(r)) - run(pipeline(`$echocmd hello world`, sock)) - close(sock) - return true - end - @test wait(t1) - @test wait(t2) -end - -@test readstring(setenv(`$shcmd -c "echo \$TEST"`,["TEST=Hello World"])) == "Hello World\n" -@test readstring(setenv(`$shcmd -c "echo \$TEST"`,Dict("TEST"=>"Hello World"))) == "Hello World\n" -@test readstring(setenv(`$shcmd -c "echo \$TEST"`,"TEST"=>"Hello World")) == "Hello World\n" -@test (withenv("TEST"=>"Hello World") do - readstring(`$shcmd -c "echo \$TEST"`); end) == "Hello World\n" -let pathA = readchomp(setenv(`$shcmd -c "pwd -P"`;dir="..")), - pathB = readchomp(setenv(`$shcmd -c "cd .. && pwd -P"`)) - if is_windows() - # on windows, sh returns posix-style paths that are not valid according to ispath - @test pathA == pathB - else - @test Base.samefile(pathA, pathB) - end -end - -let str = "", stdin, stdout, proc, str2, file - for i = 1:1000 - str = "$str\n $(randstring(10))" - end - - # Here we test that if we close a stream with pending writes, we don't lose the writes. - stdout, stdin, proc = readandwrite(`$catcmd -`) - write(stdin, str) - close(stdin) - str2 = readstring(stdout) - @test str2 == str - - # This test hangs if the end-of-run-walk-across-uv-streams calls shutdown on a stream that is shutting down. - file = tempname() - open(pipeline(`$catcmd -`, file), "w") do io - write(io, str) - end - rm(file) -end - -# issue #3373 -# fixing up Conditions after interruptions -let r, t - r = Channel(1) - t = @async begin - try - wait(r) - end - p = spawn(`$sleepcmd 1`); wait(p) - @test p.exitcode == 0 - return true - end - yield() - schedule(t, InterruptException(), error=true) - yield() - put!(r,11) - yield() - @test wait(t) -end - -# Test marking of IO -let r, t, sock - r = Channel(1) - t = @async begin - port, server = listenany(2327) - put!(r, port) - client = accept(server) - write(client, "Hello, world!\n") - write(client, "Goodbye, world...\n") - close(server) - return true - end - sock = connect(fetch(r)) - mark(sock) - @test ismarked(sock) - @test readline(sock) == "Hello, world!" - @test readline(sock) == "Goodbye, world..." - @test reset(sock) == 0 - @test !ismarked(sock) - mark(sock) - @test ismarked(sock) - @test readline(sock) == "Hello, world!" - unmark(sock) - @test !ismarked(sock) - @test_throws ArgumentError reset(sock) - @test !unmark(sock) - @test readline(sock) == "Goodbye, world..." - #@test eof(sock) ## doesn't work - close(sock) - @test wait(t) -end -# issue #4535 -exename = Base.julia_cmd() -if valgrind_off - # If --trace-children=yes is passed to valgrind, we will get a - # valgrind banner here, not "Hello World\n". - @test readstring(pipeline(`$exename --startup-file=no -e 'println(STDERR,"Hello World")'`, stderr=catcmd)) == "Hello World\n" - out = Pipe() - proc = spawn(pipeline(`$exename --startup-file=no -e 'println(STDERR,"Hello World")'`, stderr = out)) - close(out.in) - @test readstring(out) == "Hello World\n" - @test success(proc) -end - -# issue #6310 -@test readstring(pipeline(`$echocmd "2+2"`, `$exename --startup-file=no`)) == "4\n" - -# issue #5904 -@test run(pipeline(ignorestatus(falsecmd), truecmd)) === nothing - -@testset "redirect_*" begin - let OLD_STDOUT = STDOUT, - fname = tempname(), - f = open(fname,"w") - - redirect_stdout(f) - println("Hello World") - redirect_stdout(OLD_STDOUT) - close(f) - @test "Hello World\n" == readstring(fname) - @test OLD_STDOUT === STDOUT - rm(fname) - end -end - -# Test that redirecting an IOStream does not crash the process -let fname = tempname() - cmd = """ - # Overwrite libuv memory before freeing it, to make sure that a use after free - # triggers an assertion. - function thrash(handle::Ptr{Void}) - # Kill the memory, but write a nice low value in the libuv type field to - # trigger the right code path - ccall(:memset,Ptr{Void},(Ptr{Void},Cint,Csize_t),handle,0xee,3*sizeof(Ptr{Void})) - unsafe_store!(convert(Ptr{Cint},handle+2*sizeof(Ptr{Void})),15) - nothing - end - OLD_STDERR = STDERR - redirect_stderr(open("$(escape_string(fname))","w")) - # Usually this would be done by GC. Do it manually, to make the failure - # case more reliable. - oldhandle = OLD_STDERR.handle - OLD_STDERR.status = Base.StatusClosing - OLD_STDERR.handle = C_NULL - ccall(:uv_close,Void,(Ptr{Void},Ptr{Void}),oldhandle,cfunction(thrash,Void,(Ptr{Void},))) - sleep(1) - import Base.zzzInvalidIdentifier - """ - try - (in,p) = open(pipeline(`$exename --startup-file=no`, stderr=STDERR), "w") - write(in,cmd) - close(in) - wait(p) - catch - error("IOStream redirect failed. Child stderr was \n$(readstring(fname))\n") - finally - rm(fname) - end -end - -# issue #10994: libuv can't handle strings containing NUL -let bad = "bad\0name" - @test_throws ArgumentError run(`$bad`) - @test_throws ArgumentError run(`$echocmd $bad`) - @test_throws ArgumentError run(setenv(`$echocmd hello`, bad=>"good")) - @test_throws ArgumentError run(setenv(`$echocmd hello`, "good"=>bad)) -end - -# issue #12829 -let out = Pipe(), echo = `$exename --startup-file=no -e 'print(STDOUT, " 1\t", readstring(STDIN))'`, ready = Condition(), t, infd, outfd - @test_throws ArgumentError write(out, "not open error") - t = @async begin # spawn writer task - open(echo, "w", out) do in1 - open(echo, "w", out) do in2 - notify(ready) - write(in1, 'h') - write(in2, UInt8['w']) - println(in1, "ello") - write(in2, "orld\n") - end - end - infd = Base._fd(out.in) - outfd = Base._fd(out.out) - show(out, out) - notify(ready) - @test isreadable(out) - @test iswritable(out) - close(out.in) - @test !isopen(out.in) - is_windows() || @test !isopen(out.out) # it takes longer to propagate EOF through the Windows event system - @test_throws ArgumentError write(out, "now closed error") - @test isreadable(out) - @test !iswritable(out) - if is_windows() - # WINNT kernel does not provide a fast mechanism for async propagation - # of EOF for a blocking stream, so just wait for it to catch up. - # This shouldn't take much more than 32ms. - Base.wait_close(out) - end - @test !isopen(out) - end - wait(ready) # wait for writer task to be ready before using `out` - @test nb_available(out) == 0 - @test endswith(readuntil(out, '1'), '1') - @test Char(read(out, UInt8)) == '\t' - c = UInt8[0] - @test c == read!(out, c) - Base.wait_readnb(out, 1) - @test nb_available(out) > 0 - ln1 = readline(out) - ln2 = readline(out) - desc = readstring(out) - @test !isreadable(out) - @test !iswritable(out) - @test !isopen(out) - @test infd != Base._fd(out.in) == Base.INVALID_OS_HANDLE - @test outfd != Base._fd(out.out) == Base.INVALID_OS_HANDLE - @test nb_available(out) == 0 - @test c == UInt8['w'] - @test lstrip(ln2) == "1\thello" - @test ln1 == "orld" - @test isempty(read(out)) - @test eof(out) - @test desc == "Pipe($infd open => $outfd active, 0 bytes waiting)" - wait(t) -end - -# issue #8529 -let fname = tempname() - write(fname, "test\n") - code = """ - cmd = pipeline(`echo asdf`,`cat`) - if is_windows() - try - success(`busybox`) - cmd = pipeline(`busybox echo asdf`,`busybox cat`) - end - end - for line in eachline(STDIN) - run(cmd) - end - """ - @test success(pipeline(`$catcmd $fname`, `$exename --startup-file=no -e $code`)) - rm(fname) -end - -# Ensure that quoting works -@test Base.shell_split("foo bar baz") == ["foo", "bar", "baz"] -@test Base.shell_split("foo\\ bar baz") == ["foo bar", "baz"] -@test Base.shell_split("'foo bar' baz") == ["foo bar", "baz"] -@test Base.shell_split("\"foo bar\" baz") == ["foo bar", "baz"] - -# "Over quoted" -@test Base.shell_split("'foo\\ bar' baz") == ["foo\\ bar", "baz"] -@test Base.shell_split("\"foo\\ bar\" baz") == ["foo\\ bar", "baz"] - -# Ensure that shell_split handles quoted spaces -let cmd = ["/Volumes/External HD/program", "-a"] - @test Base.shell_split("/Volumes/External\\ HD/program -a") == cmd - @test Base.shell_split("'/Volumes/External HD/program' -a") == cmd - @test Base.shell_split("\"/Volumes/External HD/program\" -a") == cmd -end - -# Backticks should automatically quote where necessary -let cmd = ["foo bar", "baz"] - @test string(`$cmd`) == "`'foo bar' baz`" -end - -@test Base.shell_split("\"\\\\\"") == ["\\"] - -# issue #13616 -@test_throws ErrorException collect(eachline(pipeline(`$catcmd _doesnt_exist__111_`, stderr=DevNull))) - -# make sure windows_verbatim strips quotes -if is_windows() - readstring(`cmd.exe /c dir /b spawn.jl`) == readstring(Cmd(`cmd.exe /c dir /b "\"spawn.jl\""`, windows_verbatim=true)) -end - -# make sure Cmd is nestable -@test string(Cmd(Cmd(`ls`, detach=true))) == "`ls`" - -# equality tests for Cmd -@test Base.Cmd(``) == Base.Cmd(``) -@test Base.Cmd(`lsof -i :9090`) == Base.Cmd(`lsof -i :9090`) -@test Base.Cmd(`$echocmd test`) == Base.Cmd(`$echocmd test`) -@test Base.Cmd(``) != Base.Cmd(`$echocmd test`) -@test Base.Cmd(``, ignorestatus=true) != Base.Cmd(``, ignorestatus=false) -@test Base.Cmd(``, dir="TESTS") != Base.Cmd(``, dir="TEST") -@test Base.Set([``, ``]) == Base.Set([``]) -@test Set([``, echocmd]) != Set([``, ``]) -@test Set([echocmd, ``, ``, echocmd]) == Set([echocmd, ``]) - -# equality tests for AndCmds -@test Base.AndCmds(`$echocmd abc`, `$echocmd def`) == Base.AndCmds(`$echocmd abc`, `$echocmd def`) -@test Base.AndCmds(`$echocmd abc`, `$echocmd def`) != Base.AndCmds(`$echocmd abc`, `$echocmd xyz`) - -# test for correct error when an empty command is spawned (Issue 19094) -@test_throws ArgumentError run(Base.Cmd(``)) -@test_throws ArgumentError run(Base.AndCmds(``, ``)) -@test_throws ArgumentError run(Base.AndCmds(``, `$truecmd`)) -@test_throws ArgumentError run(Base.AndCmds(`$truecmd`, ``)) - -@test_throws ArgumentError spawn(Base.Cmd(``)) -@test_throws ArgumentError spawn(Base.AndCmds(``, ``)) -@test_throws ArgumentError spawn(Base.AndCmds(``, `$echocmd test`)) -@test_throws ArgumentError spawn(Base.AndCmds(`$echocmd test`, ``)) - -# tests for reducing over collection of Cmd -@test_throws ArgumentError reduce(&, Base.AbstractCmd[]) -@test_throws ArgumentError reduce(&, Base.Cmd[]) -@test reduce(&, [`$echocmd abc`, `$echocmd def`, `$echocmd hij`]) == `$echocmd abc` & `$echocmd def` & `$echocmd hij` - -# test for proper handling of FD exhaustion -if is_unix() - let ps = Pipe[] - ulimit_n = tryparse(Int, readchomp(`sh -c 'ulimit -n'`)) - try - for i = 1 : 100 * get(ulimit_n, 1000) - p = Pipe() - Base.link_pipe(p) - push!(ps, p) - end - if isnull(ulimit_n) - warn("`ulimit -n` is set to unlimited, fd exhaustion cannot be tested") - @test_broken false - else - @test false - end - catch ex - isa(ex, Base.UVError) || rethrow(ex) - @test ex.code == Base.UV_EMFILE - finally - for p in ps - close(p) - end - end - end -end - -# Test for PR 17803 -let p=Pipe() - Base.link_pipe(p; julia_only_read=true, julia_only_write=true) - ccall(:jl_static_show, Void, (Ptr{Void}, Any), p.in, Int128(-1)) - @async close(p.in) - @test readstring(p.out) == "Int128(0xffffffffffffffffffffffffffffffff)" -end - -# readlines(::Cmd), accidentally broken in #20203 -@test sort(readlines(`$lscmd -A`)) == sort(readdir()) - -# issue #19864 (PR #20497) -@test readchomp(pipeline(ignorestatus( - `$exename --startup-file=no -e ' - struct Error19864 <: Exception; end - Base.showerror(io::IO, e::Error19864) = print(io, "correct19864") - throw(Error19864())'`), - stderr=catcmd)) == "ERROR: correct19864" diff --git a/julia-0.6.3/share/julia/test/specificity.jl b/julia-0.6.3/share/julia/test/specificity.jl deleted file mode 100644 index 0273a93..0000000 --- a/julia-0.6.3/share/julia/test/specificity.jl +++ /dev/null @@ -1,196 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -function args_morespecific(a, b) - sp = (ccall(:jl_type_morespecific, Cint, (Any,Any), a, b) != 0) - if sp # make sure morespecific(a,b) implies !morespecific(b,a) - @test ccall(:jl_type_morespecific, Cint, (Any,Any), b, a) == 0 - end - return sp -end - -# issue #8652 -let - a = Tuple{Type{T1}, T1} where T1<:Integer - b2 = Tuple{Type{T2}, Integer} where T2<:Integer - @test args_morespecific(a, b2) - @test !args_morespecific(b2, a) - a = Tuple{Type{T1}, Ptr{T1}} where T1<:Integer - b2 = Tuple{Type{T2}, Ptr{Integer}} where T2<:Integer - @test args_morespecific(a, b2) - @test !args_morespecific(b2, a) -end - -# issue #11534 -let - t1 = Tuple{AbstractArray, Tuple{Vararg{RangeIndex}}} - t2 = Tuple{Array, T} where T<:Tuple{Vararg{RangeIndex}} - @test !args_morespecific(t1, t2) - @test args_morespecific(t2, t1) -end - -let - a = Tuple{Array{T,N}, Vararg{Int,N}} where T where N - b = Tuple{Array,Int} - @test args_morespecific(a, b) - @test !args_morespecific(b, a) - a = Tuple{Array, Vararg{Int,N}} where N - @test !args_morespecific(a, b) - @test args_morespecific(b, a) -end - -# another specificity issue -_z_z_z_(x, y) = 1 -_z_z_z_(::Int, ::Int, ::Vector) = 2 -_z_z_z_(::Int, c...) = 3 -@test _z_z_z_(1, 1, []) == 2 - -@test args_morespecific(Tuple{T,Vararg{T}} where T<:Number, Tuple{Number,Number,Vararg{Number}}) -@test !args_morespecific(Tuple{Number,Number,Vararg{Number}}, Tuple{T,Vararg{T}} where T<:Number) - -@test args_morespecific(Tuple{Array{T} where T<:Union{Float32,Float64,Complex64,Complex128}, Any}, - Tuple{Array{T} where T<:Real, Any}) - -@test args_morespecific(Tuple{1,T} where T, Tuple{Any}) -@test args_morespecific(Tuple{T} where T, Tuple{T,T} where T) -@test !args_morespecific(Type{T} where T<:Integer, Type{Any}) - -# issue #21016 -@test args_morespecific(Tuple{IO, Core.TypeofBottom}, Tuple{IO, Type{T}} where T<:Number) - -# issue #21382 -@test args_morespecific(Tuple{Type{Pair{A,B} where B}} where A, Tuple{DataType}) -@test args_morespecific(Tuple{Union{Int,String},Type{Pair{A,B} where B}} where A, Tuple{Integer,UnionAll}) - -# PR #21750 -let A = Tuple{Any, Tuple{Vararg{Integer,N} where N}}, - B = Tuple{Any, Tuple{Any}}, - C = Tuple{Any, Tuple{}} - @test args_morespecific(A, B) - @test args_morespecific(C, A) - @test args_morespecific(C, B) -end - -# with bound varargs -_bound_vararg_specificity_1{T,N}(::Type{Array{T,N}}, d::Vararg{Int, N}) = 0 -_bound_vararg_specificity_1{T}(::Type{Array{T,1}}, d::Int) = 1 -@test _bound_vararg_specificity_1(Array{Int,1}, 1) == 1 -@test _bound_vararg_specificity_1(Array{Int,2}, 1, 1) == 0 - -# issue #21710 -@test args_morespecific(Tuple{Array}, Tuple{AbstractVector}) -@test args_morespecific(Tuple{Matrix}, Tuple{AbstractVector}) - -# Method specificity -begin - local f, A - f{T}(dims::Tuple{}, A::AbstractArray{T,0}) = 1 - f{T,N}(dims::NTuple{N,Int}, A::AbstractArray{T,N}) = 2 - f{T,M,N}(dims::NTuple{M,Int}, A::AbstractArray{T,N}) = 3 - A = zeros(2,2) - @test f((1,2,3), A) == 3 - @test f((1,2), A) == 2 - @test f((), reshape([1])) == 1 - f{T,N}(dims::NTuple{N,Int}, A::AbstractArray{T,N}) = 4 - @test f((1,2), A) == 4 - @test f((1,2,3), A) == 3 -end - -# a method specificity issue -c99991{T}(::Type{T},x::T) = 0 -c99991{T}(::Type{UnitRange{T}},x::StepRangeLen{T}) = 1 -c99991{T}(::Type{UnitRange{T}},x::Range{T}) = 2 -@test c99991(UnitRange{Float64}, 1.0:2.0) == 1 -@test c99991(UnitRange{Int}, 1:2) == 2 - -# issue #17016, method specificity involving vararg tuples -T_17016{N} = Tuple{Any,Any,Vararg{Any,N}} -f17016(f, t::T_17016) = 0 -f17016(f, t1::Tuple) = 1 -@test f17016(0, (1,2,3)) == 0 - -@test !args_morespecific(Tuple{Type{Any}, Any}, Tuple{Type{T}, Any} where T<:VecElement) -@test !args_morespecific((Tuple{Type{T}, Any} where T<:VecElement), Tuple{Type{Any}, Any}) - -@test !args_morespecific(Tuple{Type{T}, Tuple{Any, Vararg{Any, N} where N}} where T<:Tuple{Any, Vararg{Any, N} where N}, - Tuple{Type{Any}, Any}) -@test !args_morespecific(Tuple{Type{T}, Tuple{Any, Vararg{Any, N} where N}} where T<:Tuple{Any, Vararg{Any, N} where N}, - Tuple{Type{Tuple}, Tuple}) -@test !args_morespecific(Tuple{Type{T}, T} where T<:Tuple{Any, Vararg{Any, N} where N}, - Tuple{Type{T}, Any} where T<:VecElement) - -@test args_morespecific(Tuple{Any, Tuple{}, Tuple{}}, Tuple{Any, Tuple{Any}}) -@test args_morespecific(Tuple{Any, Tuple{Any}, Tuple{Any}}, Tuple{Any, Tuple{Any, Any}}) -@test args_morespecific(Tuple{Any, Vararg{Tuple{}, N} where N}, Tuple{Any, Tuple{Any}}) - -@test args_morespecific(Tuple{T, T} where T<:AbstractFloat, Tuple{T, T, T} where T<:AbstractFloat) -@test args_morespecific(Tuple{T, Real, T} where T<:AbstractFloat, Tuple{T, T} where T<:Real) -@test args_morespecific(Tuple{Real, Real}, Tuple{T, T, T} where T <: Real) -@test !args_morespecific(Tuple{Real, Real, Real}, Tuple{T, T, T} where T <: Real) -@test !args_morespecific(Tuple{Real, Real, Vararg{Real}}, Tuple{T, T, T} where T <: Real) -@test args_morespecific(Tuple{Real, Real, Vararg{Int}}, Tuple{T, T, T} where T <: Real) - -@test args_morespecific(Tuple{Type{Base.Nullable{T}}} where T, Tuple{Type{T}, Any} where T) -@test !args_morespecific(Tuple{Type{Base.Nullable{T}}, T} where T, Tuple{Type{Base.Nullable{T}}} where T) - -@test args_morespecific(Tuple{Union{Base.StepRange{T, S} where S, Base.StepRangeLen{T, T, S} where S}, - Union{Base.StepRange{T, S} where S, Base.StepRangeLen{T, T, S} where S}} where T, - Tuple{T, T} where T<:Union{Base.StepRangeLen, Base.LinSpace}) - -@test args_morespecific(Tuple{Type{Tuple}, Any, Any}, - Tuple{Type{Tuple{Vararg{E, N} where N}}, Any, Any} where E) - -@test args_morespecific(Tuple{Type{Tuple{}}, Tuple{}}, - Tuple{Type{T}, T} where T<:Tuple{Any, Vararg{Any, N} where N}) - -@test args_morespecific(Tuple{Type{CartesianIndex{N}}} where N, - Tuple{Type{CartesianIndex{N}},Vararg{Int,N}} where N) - -# issue #22164 and #22002 -let A = Tuple{Type{D},D} where D<:Pair, - B = Tuple{Type{Any}, Any}, - C = Tuple{Type{Pair}, Pair} - @test args_morespecific(C, A) - @test !args_morespecific(A, B) - @test !args_morespecific(C, B) -end - -# issue #22338 -let A = Tuple{Ref, Tuple{T}} where T, - B = Tuple{Ref{T}, Tuple{Vararg{T}}} where T, - C = Tuple{Ref{T}, Tuple{T}} where T - @test args_morespecific(C, A) - @test args_morespecific(C, B) - @test !args_morespecific(A, B) - @test !args_morespecific(B, A) -end - -# issue #22339 -let A = Tuple{T, Array{T, 1}} where T, - B = Tuple{T} where T, - C = Tuple{T} where T<:AbstractFloat - @test args_morespecific(B, A) - @test args_morespecific(C, B) - @test args_morespecific(C, A) -end - -# issue #22908 -f22908(::Union) = 2 -f22908(::Type{Union{Int, Float32}}) = 1 -@test f22908(Union{Int, Float32}) == 1 - -let A = Tuple{Array{T,N}, Vararg{Int,N}} where {T,N}, - B = Tuple{Array, Int}, - C = Tuple{AbstractArray, Int, Array} - @test args_morespecific(A, B) - @test args_morespecific(B, C) - @test args_morespecific(A, C) -end - -# transitivity issue found in #26915 -let A = Tuple{Vector, AbstractVector}, - B = Tuple{AbstractVecOrMat{T}, AbstractVector{T}} where T, - C = Tuple{AbstractVecOrMat{T}, AbstractVecOrMat{T}} where T - @test args_morespecific(A, B) - @test args_morespecific(B, C) - @test args_morespecific(A, C) -end diff --git a/julia-0.6.3/share/julia/test/stacktraces.jl b/julia-0.6.3/share/julia/test/stacktraces.jl deleted file mode 100644 index ac18143..0000000 --- a/julia-0.6.3/share/julia/test/stacktraces.jl +++ /dev/null @@ -1,144 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -# Tests for /base/stacktraces.jl - -let - @noinline child() = stacktrace() - @noinline parent() = child() - @noinline grandparent() = parent() - line_numbers = @__LINE__ - [3, 2, 1] - stack = grandparent() - - # Basic tests. - @assert length(stack) >= 3 "Compiler has unexpectedly inlined functions" - - @test [:child, :parent, :grandparent] == [f.func for f in stack[1:3]] - for (line, frame) in zip(line_numbers, stack[1:3]) - @test [Symbol(@__FILE__), line] == [frame.file, frame.line] - end - @test [false, false, false] == [f.from_c for f in stack[1:3]] - - # Test remove_frames! - stack = StackTraces.remove_frames!(grandparent(), :parent) - @test stack[1] == StackFrame(:grandparent, @__FILE__, line_numbers[3]) - - stack = StackTraces.remove_frames!(grandparent(), [:child, :something_nonexistent]) - @test stack[1:2] == [ - StackFrame(:parent, @__FILE__, line_numbers[2]), - StackFrame(:grandparent, @__FILE__, line_numbers[3]) - ] - - b = PipeBuffer() - frame = stack[1] - serialize(b, frame) - frame2 = deserialize(b) - @test frame !== frame2 - @test frame == frame2 - @test !isnull(frame.linfo) - @test isnull(frame2.linfo) -end - -# Test from_c -let (default, with_c, without_c) = (stacktrace(), stacktrace(true), stacktrace(false)) - @test default == without_c - @test length(with_c) > length(without_c) - @test !isempty(filter(frame -> frame.from_c, with_c)) - @test isempty(filter(frame -> frame.from_c, without_c)) -end - -@test StackTraces.lookup(C_NULL) == [StackTraces.UNKNOWN] - -let ct = current_task() - # After a task switch, there should be nothing in catch_backtrace - yieldto(@task yieldto(ct)) - @test catch_backtrace() == StackFrame[] - - @noinline bad_function() = throw(UndefVarError(:nonexistent)) - @noinline function try_stacktrace() - try - bad_function() - catch - return stacktrace() - end - end - @noinline function try_catch() - try - bad_function() - catch - return catch_stacktrace() - end - end - line_numbers = @__LINE__ .- [15, 10, 5] - - # Test try...catch with stacktrace - @test try_stacktrace()[1] == StackFrame(:try_stacktrace, @__FILE__, line_numbers[2]) - - # Test try...catch with catch_stacktrace - @test try_catch()[1:2] == [ - StackFrame(:bad_function, @__FILE__, line_numbers[1]), - StackFrame(:try_catch, @__FILE__, line_numbers[3]) - ] -end - -module inlined_test -using Base.Test -@inline g(x) = (y = throw("a"); y) # the inliner does not insert the proper markers when inlining a single expression -@inline h(x) = (y = g(x); y) # this test could be extended to check for that if we switch to linear representation -f(x) = (y = h(x); y) -trace = (try; f(3); catch; catch_stacktrace(); end)[1:3] -can_inline = Bool(Base.JLOptions().can_inline) -for (frame, func, inlined) in zip(trace, [g,h,f], (can_inline, can_inline, false)) - @test frame.func === typeof(func).name.mt.name - #@test get(frame.linfo).def === which(func, (Any,)).func - #@test get(frame.linfo).specTypes === Tuple{typeof(func), Int} - # line - @test frame.file === Symbol(@__FILE__) - @test !frame.from_c - @test frame.inlined === inlined -end -end - -let src = expand(quote let x = 1 end end).args[1]::CodeInfo, - li = ccall(:jl_new_method_instance_uninit, Ref{Core.MethodInstance}, ()), - sf - - li.inferred = src - li.specTypes = Tuple{} - sf = StackFrame(:a, :b, 3, li, false, false, 0) - repr = string(sf) - @test repr == "Toplevel MethodInstance thunk at b:3" -end -let li = typeof(getfield).name.mt.cache.func::Core.MethodInstance, - sf = StackFrame(:a, :b, 3, li, false, false, 0), - repr = string(sf) - @test repr == "getfield(...) at b:3" -end - -let ctestptr = cglobal((:ctest, "libccalltest")), - ctest = StackTraces.lookup(ctestptr + 1) - - @test length(ctest) == 1 - @test ctest[1].func === :ctest - @test isnull(ctest[1].linfo) - @test ctest[1].from_c - @test ctest[1].pointer === UInt64(ctestptr) -end - -# issue #19655 -let st = stacktrace(empty!(backtrace())) - # not in a `catch`, so should return an empty StackTrace - @test isempty(st) - @test isa(st, StackTrace) -end - -module StackTracesTestMod - unfiltered_stacktrace() = stacktrace() - filtered_stacktrace() = StackTraces.remove_frames!(stacktrace(), StackTracesTestMod) -end - -# Test that `removes_frames!` can correctly remove frames from within the module -trace = StackTracesTestMod.unfiltered_stacktrace() -@test contains(string(trace), "unfiltered_stacktrace") - -trace = StackTracesTestMod.filtered_stacktrace() -@test !contains(string(trace), "filtered_stacktrace") diff --git a/julia-0.6.3/share/julia/test/staged.jl b/julia-0.6.3/share/julia/test/staged.jl deleted file mode 100644 index e81f4b4..0000000 --- a/julia-0.6.3/share/julia/test/staged.jl +++ /dev/null @@ -1,230 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -@generated function staged_t1(a,b) - if a == Int - return :(a+b) - else - return :(a*b) - end -end - -@test staged_t1(1,2) == 3 -@test staged_t1(1.0,0.5) == 0.5 -@test staged_t1(1,0.5) == 1.5 - -tinline(a,b) = staged_t1(a,b) - -@test !isa(tinline(1,2),Expr) -@test tinline(1,0.5) == 1.5 - -@generated function splat(a,b...) - :( ($a,$b,a,b) ) -end - -@test splat(1,2,3) == (Int,(Int,Int),1,(2,3)) - -stagediobuf = IOBuffer() -@generated function splat2(a...) - print(stagediobuf, a) - :(nothing) -end - -const intstr = @sprintf("%s", Int) -splat2(1) -@test String(take!(stagediobuf)) == "($intstr,)" -splat2(1, 3) -@test String(take!(stagediobuf)) == "($intstr, $intstr)" -splat2(5, 2) -@test String(take!(stagediobuf)) == "" -splat2(1:3, 5.2) -@test String(take!(stagediobuf)) == "(UnitRange{$intstr}, Float64)" -splat2(3, 5:2:7) -@test String(take!(stagediobuf)) == "($intstr, StepRange{$intstr,$intstr})" -splat2(1, 2, 3, 4) -@test String(take!(stagediobuf)) == "($intstr, $intstr, $intstr, $intstr)" -splat2(1, 2, 3) -@test String(take!(stagediobuf)) == "($intstr, $intstr, $intstr)" -splat2(1:5, 3, 3:3) -@test String(take!(stagediobuf)) == "(UnitRange{$intstr}, $intstr, UnitRange{$intstr})" -splat2(1:5, 3, 3:3) -@test String(take!(stagediobuf)) == "" -splat2(1:5, 3:3, 3) -@test String(take!(stagediobuf)) == "(UnitRange{$intstr}, UnitRange{$intstr}, $intstr)" -splat2(1:5, 3:3) -@test String(take!(stagediobuf)) == "(UnitRange{$intstr}, UnitRange{$intstr})" -splat2(3, 3:5) -@test String(take!(stagediobuf)) == "($intstr, UnitRange{$intstr})" - -# varargs specialization with parametric @generated functions (issue #8944) -@generated function splat3{T,N}(A::AbstractArray{T,N}, indx::RangeIndex...) - print(stagediobuf, indx) - :(nothing) -end -A = rand(5,5,3) -splat3(A, 1:2, 1:2, 1) -@test String(take!(stagediobuf)) == "(UnitRange{$intstr}, UnitRange{$intstr}, $intstr)" -splat3(A, 1:2, 1, 1:2) -@test String(take!(stagediobuf)) == "(UnitRange{$intstr}, $intstr, UnitRange{$intstr})" - -B = view(A, 1:3, 2, 1:3) -@generated function mygetindex(S::SubArray, indexes::Real...) - T, N, A, I = S.parameters - if N != length(indexes) - error("Wrong number of indexes supplied") - end - Ip = I.parameters - NP = length(Ip) - indexexprs = Array{Expr}(NP) - j = 1 - for i = 1:NP - if Ip[i] == Int - indexexprs[i] = :(S.indexes[$i]) - else - indexexprs[i] = :(S.indexes[$i][indexes[$j]]) - j += 1 - end - end - ex = :(S.parent[$(indexexprs...)]) - ex -end -@test mygetindex(B,2,2) == A[2,2,2] - -# issue #8497 -module MyTest8497 -internalfunction(x) = x+1 -@generated function h(x) - quote - internalfunction(x) - end -end -end -@test MyTest8497.h(3) == 4 - -# static parameters (issue #8505) -@generated function foo1{N,T}(a::Array{T,N}) - "N = $N, T = $T" -end -@generated function foo2{T,N}(a::Array{T,N}) - "N = $N, T = $T" -end -@test foo1(randn(3,3)) == "N = 2, T = Float64" -@test foo2(randn(3,3)) == "N = 2, T = Float64" - -# issue #9088 -@generated function f9088(x, a=5) - :(x+a) -end -@test f9088(7) == 12 - -# issue #10502 -@generated function f10502(x...) - :($x) -end -f10502() = () -@test f10502(1) == (Int,) -@test f10502(1,2) == (Int,Int) -@test f10502(1,2,3) == (Int,Int,Int) - -# One-line @generated functions -@generated oneliner(x,y) = :($x, x, $y, y) -@test oneliner(1, 2.) == (Int, 1, Float64, 2.) - -# issue #11982 -@generated function f11982(T) - string(T.parameters[1]) -end -@test f11982(Float32) == "Float32" -@test f11982(Int32) == "Int32" - -# @generated functions that throw (shouldn't segfault or throw) -module TestGeneratedThrow - using Base.Test - - @generated function bar(x) - error("I'm not happy with type $x") - end - - foo() = (bar(rand() > 0.5 ? 1 : 1.0); error("foo")) - function __init__() - code_typed(foo,(); optimize = false) - cfunction(foo,Void,()) - end -end - -# @generated functions including inner functions -@generated function _g_f_with_inner(x) - return :(y -> y) -end -@test_throws ErrorException _g_f_with_inner(1) - -@generated function _g_f_with_inner2(x) - return y -> y -end -@test _g_f_with_inner2(1)(2) == 2 - -# @generated functions errors -global gf_err_ref = Ref{Int}() - -gf_err_ref[] = 0 -let gf_err, tsk = @async nothing # create a Task for yield to try to run - @generated function gf_err() - gf_err_ref[] += 1 - yield() - gf_err_ref[] += 1000 - end - @test_throws ErrorException gf_err() - @test_throws ErrorException gf_err() - @test gf_err_ref[] == 4 -end - -gf_err_ref[] = 0 -let gf_err2 - @generated function gf_err2{f}(::f) - gf_err_ref[] += 1 - reflect = f.instance - gf_err_ref[] += 1 - reflect(+, (Int,Int)) - gf_err_ref[] += 1000 - return nothing - end - @test_throws ErrorException gf_err2(code_typed) - @test_throws ErrorException gf_err2(code_llvm) - @test_throws ErrorException gf_err2(code_native) - @test gf_err_ref[] == 12 - @test gf_err2(code_lowered) === nothing -end - -# issue #15043 -decorated = Set{DataType}() -let - @generated function decorate(t) - push!(decorated, t) - end - - foo() = return nothing - decorate(foo) - @test in(typeof(foo), decorated) - - bar() = return 1 - decorate(bar) - @test in(typeof(bar), decorated) -end - -# issue #19897 -@test code_lowered(staged_t1, (Int,Int)) isa Array # check no error thrown - -# issue #10178 -@generated function f10178(x::X) where X - :(x) -end -g10178(x) = f10178(x) -@test g10178(5) == 5 -@generated function f10178(x::X) where X - :(2x) -end -g10178(x) = f10178(x) -@test g10178(5) == 10 - -# issue #22135 -@generated f22135(x::T) where T = x -@test f22135(1) === Int diff --git a/julia-0.6.3/share/julia/test/statistics.jl b/julia-0.6.3/share/julia/test/statistics.jl deleted file mode 100644 index d6ecc27..0000000 --- a/julia-0.6.3/share/julia/test/statistics.jl +++ /dev/null @@ -1,411 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -using Base.Test - -# middle - -@test middle(3) === 3.0 -@test middle(2, 3) === 2.5 -let x = ((realmax(1.0)/4)*3) - @test middle(x, x) === x -end -@test middle(1:8) === 4.5 -@test middle([1:8;]) === 4.5 - -# ensure type-correctness -for T in [Bool,Int8,Int16,Int32,Int64,Int128,UInt8,UInt16,UInt32,UInt64,UInt128,Float16,Float32,Float64] - @test middle(one(T)) === middle(one(T), one(T)) -end - - -# median -@test median([1.]) === 1. -@test median([1.,3]) === 2. -@test median([1.,3,2]) === 2. - -@test median([1,3,2]) === 2.0 -@test median([1,3,2,4]) === 2.5 - -@test median([0.0,Inf]) == Inf -@test median([0.0,-Inf]) == -Inf -@test median([0.,Inf,-Inf]) == 0.0 -@test median([1.,-1.,Inf,-Inf]) == 0.0 -@test isnan(median([-Inf,Inf])) - -X = [2 3 1 -1; 7 4 5 -4] -@test all(median(X, 2) .== [1.5, 4.5]) -@test all(median(X, 1) .== [4.5 3.5 3.0 -2.5]) -@test X == [2 3 1 -1; 7 4 5 -4] # issue #17153 - -@test_throws ArgumentError median([]) -@test isnan(median([NaN])) -@test isnan(median([0.0,NaN])) -@test isnan(median([NaN,0.0])) -@test isequal(median([NaN 0.0; 1.2 4.5], 2), reshape([NaN; 2.85], 2, 1)) - -@test median!([1 2 3 4]) == 2.5 -@test median!([1 2; 3 4]) == 2.5 - - -@test invoke(median, Tuple{AbstractVector}, 1:10) == median(1:10) == 5.5 - -# mean -@test_throws ArgumentError mean(()) -@test mean((1,2,3)) === 2. -@test mean([0]) === 0. -@test mean([1.]) === 1. -@test mean([1.,3]) == 2. -@test mean([1,2,3]) == 2. -@test mean([0 1 2; 4 5 6], 1) == [2. 3. 4.] -@test mean([1 2 3; 4 5 6], 1) == [2.5 3.5 4.5] -@test mean(i->i+1, 0:2) === 2. -@test mean(isodd, [3]) === 1. -@test mean(x->3x, (1,1)) === 3. - -@test isnan(mean([NaN])) -@test isnan(mean([0.0,NaN])) -@test isnan(mean([NaN,0.0])) - -@test isnan(mean([0.,Inf,-Inf])) -@test isnan(mean([1.,-1.,Inf,-Inf])) -@test isnan(mean([-Inf,Inf])) -@test isequal(mean([NaN 0.0; 1.2 4.5], 2), reshape([NaN; 2.85], 2, 1)) - -# test var & std - -# edge case: empty vector -# iterable; this has to throw for type stability -@test_throws ArgumentError var(()) -@test_throws ArgumentError var((); corrected=false) -@test_throws ArgumentError var((); mean=2) -@test_throws ArgumentError var((); mean=2, corrected=false) -# reduction -@test isnan(var(Int[])) -@test isnan(var(Int[]; corrected=false)) -@test isnan(var(Int[]; mean=2)) -@test isnan(var(Int[]; mean=2, corrected=false)) -# reduction across dimensions -@test isequal(var(Int[], 1), [NaN]) -@test isequal(var(Int[], 1; corrected=false), [NaN]) -@test isequal(var(Int[], 1; mean=[2]), [NaN]) -@test isequal(var(Int[], 1; mean=[2], corrected=false), [NaN]) - -# edge case: one-element vector -# iterable -@test isnan(@inferred(var((1,)))) -@test var((1,); corrected=false) === 0.0 -@test var((1,); mean=2) === Inf -@test var((1,); mean=2, corrected=false) === 1.0 -# reduction -@test isnan(@inferred(var([1]))) -@test var([1]; corrected=false) === 0.0 -@test var([1]; mean=2) === Inf -@test var([1]; mean=2, corrected=false) === 1.0 -# reduction across dimensions -@test isequal(@inferred(var([1], 1)), [NaN]) -@test var([1], 1; corrected=false) ≈ [0.0] -@test var([1], 1; mean=[2]) ≈ [Inf] -@test var([1], 1; mean=[2], corrected=false) ≈ [1.0] - -@test var(1:8) == 6. -@test varm(1:8,1) == varm(collect(1:8),1) -@test isnan(varm(1:1,1)) -@test isnan(var(1:1)) -@test isnan(var(1:-1)) - -@test @inferred(var(1.0:8.0)) == 6. -@test varm(1.0:8.0,1.0) == varm(collect(1.0:8.0),1) -@test isnan(varm(1.0:1.0,1.0)) -@test isnan(var(1.0:1.0)) -@test isnan(var(1.0:-1.0)) - -@test @inferred(var(1.0f0:8.0f0)) === 6.f0 -@test varm(1.0f0:8.0f0,1.0f0) == varm(collect(1.0f0:8.0f0),1) -@test isnan(varm(1.0f0:1.0f0,1.0f0)) -@test isnan(var(1.0f0:1.0f0)) -@test isnan(var(1.0f0:-1.0f0)) - -@test varm([1,2,3], 2) ≈ 1. -@test var([1,2,3]) ≈ 1. -@test var([1,2,3]; corrected=false) ≈ 2.0/3 -@test var([1,2,3]; mean=0) ≈ 7. -@test var([1,2,3]; mean=0, corrected=false) ≈ 14.0/3 - -@test varm((1,2,3), 2) ≈ 1. -@test var((1,2,3)) ≈ 1. -@test var((1,2,3); corrected=false) ≈ 2.0/3 -@test var((1,2,3); mean=0) ≈ 7. -@test var((1,2,3); mean=0, corrected=false) ≈ 14.0/3 -@test_throws ArgumentError var((1,2,3); mean=()) - -@test var([1 2 3 4 5; 6 7 8 9 10], 2) ≈ [2.5 2.5]' -@test var([1 2 3 4 5; 6 7 8 9 10], 2; corrected=false) ≈ [2.0 2.0]' - -@test stdm([1,2,3], 2) ≈ 1. -@test std([1,2,3]) ≈ 1. -@test std([1,2,3]; corrected=false) ≈ sqrt(2.0/3) -@test std([1,2,3]; mean=0) ≈ sqrt(7.0) -@test std([1,2,3]; mean=0, corrected=false) ≈ sqrt(14.0/3) - -@test stdm((1,2,3), 2) ≈ 1. -@test std((1,2,3)) ≈ 1. -@test std((1,2,3); corrected=false) ≈ sqrt(2.0/3) -@test std((1,2,3); mean=0) ≈ sqrt(7.0) -@test std((1,2,3); mean=0, corrected=false) ≈ sqrt(14.0/3) - -@test std([1 2 3 4 5; 6 7 8 9 10], 2) ≈ sqrt.([2.5 2.5]') -@test std([1 2 3 4 5; 6 7 8 9 10], 2; corrected=false) ≈ sqrt.([2.0 2.0]') - -A = Complex128[exp(i*im) for i in 1:10^4] -@test varm(A,0.) ≈ sum(map(abs2,A))/(length(A)-1) -@test varm(A,mean(A)) ≈ var(A) - -# test covariance - -function safe_cov(x, y, zm::Bool, cr::Bool) - n = length(x) - if !zm - x = x .- mean(x) - y = y .- mean(y) - end - dot(vec(x), vec(y)) / (n - Int(cr)) -end - -X = [1. 2. 3. 4. 5.; 5. 4. 6. 2. 1.]' -Y = [6. 1. 5. 3. 2.; 2. 7. 8. 4. 3.]' - -for vd in [1, 2], zm in [true, false], cr in [true, false] - # println("vd = $vd: zm = $zm, cr = $cr") - if vd == 1 - k = size(X, 2) - Cxx = zeros(k, k) - Cxy = zeros(k, k) - for i = 1:k, j = 1:k - Cxx[i,j] = safe_cov(X[:,i], X[:,j], zm, cr) - Cxy[i,j] = safe_cov(X[:,i], Y[:,j], zm, cr) - end - x1 = vec(X[:,1]) - y1 = vec(Y[:,1]) - else - k = size(X, 1) - Cxx = zeros(k, k) - Cxy = zeros(k, k) - for i = 1:k, j = 1:k - Cxx[i,j] = safe_cov(X[i,:], X[j,:], zm, cr) - Cxy[i,j] = safe_cov(X[i,:], Y[j,:], zm, cr) - end - x1 = vec(X[1,:]) - y1 = vec(Y[1,:]) - end - - c = zm ? Base.covm(x1, 0, cr) : - cov(x1, cr) - @test isa(c, Float64) - @test c ≈ Cxx[1,1] - @inferred cov(x1, cr) - - @test cov(X) == Base.covm(X, mean(X, 1)) - C = zm ? Base.covm(X, 0, vd, cr) : - cov(X, vd, cr) - @test size(C) == (k, k) - @test C ≈ Cxx - @inferred cov(X, vd, cr) - - @test cov(x1, y1) == Base.covm(x1, mean(x1), y1, mean(y1)) - c = zm ? Base.covm(x1, 0, y1, 0, cr) : - cov(x1, y1, cr) - @test isa(c, Float64) - @test c ≈ Cxy[1,1] - @inferred cov(x1, y1, cr) - - if vd == 1 - @test cov(x1, Y) == Base.covm(x1, mean(x1), Y, mean(Y, 1)) - end - C = zm ? Base.covm(x1, 0, Y, 0, vd, cr) : - cov(x1, Y, vd, cr) - @test size(C) == (1, k) - @test vec(C) ≈ Cxy[1,:] - @inferred cov(x1, Y, vd, cr) - - if vd == 1 - @test cov(X, y1) == Base.covm(X, mean(X, 1), y1, mean(y1)) - end - C = zm ? Base.covm(X, 0, y1, 0, vd, cr) : - cov(X, y1, vd, cr) - @test size(C) == (k, 1) - @test vec(C) ≈ Cxy[:,1] - @inferred cov(X, y1, vd, cr) - - @test cov(X, Y) == Base.covm(X, mean(X, 1), Y, mean(Y, 1)) - C = zm ? Base.covm(X, 0, Y, 0, vd, cr) : - cov(X, Y, vd, cr) - @test size(C) == (k, k) - @test C ≈ Cxy - @inferred cov(X, Y, vd, cr) -end - -# test correlation - -function safe_cor(x, y, zm::Bool) - if !zm - x = x .- mean(x) - y = y .- mean(y) - end - x = vec(x) - y = vec(y) - dot(x, y) / (sqrt(dot(x, x)) * sqrt(dot(y, y))) -end - -for vd in [1, 2], zm in [true, false] - # println("vd = $vd: zm = $zm") - if vd == 1 - k = size(X, 2) - Cxx = zeros(k, k) - Cxy = zeros(k, k) - for i = 1:k, j = 1:k - Cxx[i,j] = safe_cor(X[:,i], X[:,j], zm) - Cxy[i,j] = safe_cor(X[:,i], Y[:,j], zm) - end - x1 = vec(X[:,1]) - y1 = vec(Y[:,1]) - else - k = size(X, 1) - Cxx = zeros(k, k) - Cxy = zeros(k, k) - for i = 1:k, j = 1:k - Cxx[i,j] = safe_cor(X[i,:], X[j,:], zm) - Cxy[i,j] = safe_cor(X[i,:], Y[j,:], zm) - end - x1 = vec(X[1,:]) - y1 = vec(Y[1,:]) - end - - c = zm ? Base.corm(x1, 0) : cor(x1) - @test isa(c, Float64) - @test c ≈ Cxx[1,1] - @inferred cor(x1) - - @test cor(X) == Base.corm(X, mean(X, 1)) - C = zm ? Base.corm(X, 0, vd) : cor(X, vd) - @test size(C) == (k, k) - @test C ≈ Cxx - @inferred cor(X, vd) - - @test cor(x1, y1) == Base.corm(x1, mean(x1), y1, mean(y1)) - c = zm ? Base.corm(x1, 0, y1, 0) : cor(x1, y1) - @test isa(c, Float64) - @test c ≈ Cxy[1,1] - @inferred cor(x1, y1) - - if vd == 1 - @test cor(x1, Y) == Base.corm(x1, mean(x1), Y, mean(Y, 1)) - end - C = zm ? Base.corm(x1, 0, Y, 0, vd) : cor(x1, Y, vd) - @test size(C) == (1, k) - @test vec(C) ≈ Cxy[1,:] - @inferred cor(x1, Y, vd) - - if vd == 1 - @test cor(X, y1) == Base.corm(X, mean(X, 1), y1, mean(y1)) - end - C = zm ? Base.corm(X, 0, y1, 0, vd) : cor(X, y1, vd) - @test size(C) == (k, 1) - @test vec(C) ≈ Cxy[:,1] - @inferred cor(X, y1, vd) - - @test cor(X, Y) == Base.corm(X, mean(X, 1), Y, mean(Y, 1)) - C = zm ? Base.corm(X, 0, Y, 0, vd) : cor(X, Y, vd) - @test size(C) == (k, k) - @test C ≈ Cxy - @inferred cor(X, Y, vd) -end - -@test cor(repmat(1:17, 1, 17))[2] <= 1.0 -@test cor(1:17, 1:17) <= 1.0 -@test cor(1:17, 18:34) <= 1.0 -let tmp = linspace(1, 85, 100) - tmp2 = collect(tmp) - @test cor(tmp, tmp) <= 1.0 - @test cor(tmp, tmp2) <= 1.0 -end - -@test quantile([1,2,3,4],0.5) == 2.5 -@test quantile([1,2,3,4],[0.5]) == [2.5] -@test quantile([1., 3],[.25,.5,.75])[2] == median([1., 3]) -@test quantile(100.0:-1.0:0.0, 0.0:0.1:1.0) == collect(0.0:10.0:100.0) -@test quantile(0.0:100.0, 0.0:0.1:1.0, sorted=true) == collect(0.0:10.0:100.0) -@test quantile(100f0:-1f0:0.0, 0.0:0.1:1.0) == collect(0f0:10f0:100f0) -@test quantile([Inf,Inf],0.5) == Inf -@test quantile([-Inf,1],0.5) == -Inf -@test quantile([0,1],1e-18) == 1e-18 - -# StatsBase issue 164 -y = [0.40003674665581906,0.4085630862624367,0.41662034698690303,0.41662034698690303,0.42189053966652057,0.42189053966652057,0.42553514344518345,0.43985732442991354] -@test issorted(quantile(y, linspace(0.01, 0.99, 17))) - -# variance of complex arrays (#13309) -let z = rand(Complex128, 10) - @test var(z) ≈ invoke(var, Tuple{Any}, z) ≈ cov(z) ≈ var(z,1)[1] ≈ sum(abs2, z - mean(z))/9 - @test isa(var(z), Float64) - @test isa(invoke(var, Tuple{Any}, z), Float64) - @test isa(cov(z), Float64) - @test isa(var(z,1), Vector{Float64}) - @test varm(z, 0.0) ≈ invoke(varm, Tuple{Any,Float64}, z, 0.0) ≈ sum(abs2, z)/9 - @test isa(varm(z, 0.0), Float64) - @test isa(invoke(varm, Tuple{Any,Float64}, z, 0.0), Float64) - @test cor(z) === 1.0 -end -let v = varm([1.0+2.0im], 0; corrected = false) - @test v ≈ 5 - @test isa(v, Float64) -end - -# cov and cor of complex arrays (issue #21093) -x = [2.7 - 3.3im, 0.9 + 5.4im, 0.1 + 0.2im, -1.7 - 5.8im, 1.1 + 1.9im] -y = [-1.7 - 1.6im, -0.2 + 6.5im, 0.8 - 10.0im, 9.1 - 3.4im, 2.7 - 5.5im] -@test cov(x, y) ≈ 4.8365 - 12.119im -@test cov(y, x) ≈ 4.8365 + 12.119im -@test cov(x, reshape(y, :, 1)) ≈ reshape([4.8365 - 12.119im], 1, 1) -@test cov(reshape(x, :, 1), y) ≈ reshape([4.8365 - 12.119im], 1, 1) -@test cov(reshape(x, :, 1), reshape(y, :, 1)) ≈ reshape([4.8365 - 12.119im], 1, 1) -@test cov([x y]) ≈ [21.779 4.8365-12.119im; - 4.8365+12.119im 54.548] -@test cor(x, y) ≈ 0.14032104449218274 - 0.35160772008699703im -@test cor(y, x) ≈ 0.14032104449218274 + 0.35160772008699703im -@test cor(x, reshape(y, :, 1)) ≈ reshape([0.14032104449218274 - 0.35160772008699703im], 1, 1) -@test cor(reshape(x, :, 1), y) ≈ reshape([0.14032104449218274 - 0.35160772008699703im], 1, 1) -@test cor(reshape(x, :, 1), reshape(y, :, 1)) ≈ reshape([0.14032104449218274 - 0.35160772008699703im], 1, 1) -@test cor([x y]) ≈ [1.0 0.14032104449218274-0.35160772008699703im - 0.14032104449218274+0.35160772008699703im 1.0] - -# Issue #17153 and PR #17154 -let a = rand(10,10) - b = deepcopy(a) - x = median(a, 1) - @test b == a - x = median(a, 2) - @test b == a - x = mean(a, 1) - @test b == a - x = mean(a, 2) - @test b == a - x = var(a, 1) - @test b == a - x = var(a, 2) - @test b == a - x = std(a, 1) - @test b == a - x = std(a, 2) - @test b == a -end - -# dimensional correctness -isdefined(Main, :TestHelpers) || @eval Main include("TestHelpers.jl") -using TestHelpers.Furlong -let r = Furlong(1):Furlong(1):Furlong(2), a = collect(r) - @test sum(r) == sum(a) == Furlong(3) - @test cumsum(r) == Furlong.([1,3]) - @test mean(r) == mean(a) == median(a) == median(r) == Furlong(1.5) - @test var(r) == var(a) == Furlong{2}(0.5) - @test std(r) == std(a) == Furlong{1}(sqrt(0.5)) -end diff --git a/julia-0.6.3/share/julia/test/strings/basic.jl b/julia-0.6.3/share/julia/test/strings/basic.jl deleted file mode 100644 index db32225..0000000 --- a/julia-0.6.3/share/julia/test/strings/basic.jl +++ /dev/null @@ -1,484 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -# constructors -@test String([0x61,0x62,0x63,0x21]) == "abc!" -@test String("abc!") == "abc!" - -@test isempty(string()) -@test eltype(GenericString) == Char -@test start("abc") == 1 -@test cmp("ab","abc") == -1 - -# {starts,ends}with -@test startswith("abcd", 'a') -@test startswith("abcd", "a") -@test startswith("abcd", "ab") -@test !startswith("ab", "abcd") -@test !startswith("abcd", "bc") -@test endswith("abcd", 'd') -@test endswith("abcd", "d") -@test endswith("abcd", "cd") -@test !endswith("abcd", "dc") -@test !endswith("cd", "abcd") -@test startswith("ab\0cd", "ab\0c") -@test !startswith("ab\0cd", "ab\0d") - -@test filter(x -> x ∈ ['f', 'o'], "foobar") == "foo" - -# string iteration, and issue #1454 -str = "é" -str_a = vcat(str...) -@test length(str_a)==1 -@test str_a[1] == str[1] - -str = "s\u2200" -@test str[1:end] == str - -# sizeof -@test sizeof("abc") == 3 -@test sizeof("\u2222") == 3 - -# issue #3597 -@test string(GenericString("Test")[1:1], "X") == "TX" - -for T = (UInt8,Int8,UInt16,Int16,UInt32,Int32,UInt64,Int64,UInt128,Int128,BigInt), - b = 2:62, _ = 1:10 - n = T != BigInt ? rand(T) : BigInt(rand(Int128)) - @test parse(T,base(b,n),b) == n -end - -# issue #6027 -let - # make symbol with invalid char - sym = Symbol(Char(0xdcdb)) - @test string(sym) == string(Char(0xdcdb)) - @test String(sym) == string(Char(0xdcdb)) - @test expand(sym) === sym - res = string(parse(string(Char(0xdcdb)," = 1"),1,raise=false)[1]) - @test res == """\$(Expr(:error, "invalid character \\\"\\udcdb\\\"\"))""" -end - -@test Symbol("asdf") === :asdf -@test Symbol(:abc,"def",'g',"hi",0) === :abcdefghi0 -@test :a < :b -@test startswith(string(gensym("asdf")),"##asdf#") -@test gensym("asdf") != gensym("asdf") -@test gensym() != gensym() -@test startswith(string(gensym()),"##") -@test_throws ArgumentError Symbol("ab\0") -@test_throws ArgumentError gensym("ab\0") - -# issue #6949 -let f =IOBuffer(), - x = split("1 2 3") - @test write(f, x) == 3 - @test String(take!(f)) == "123" - @test invoke(write, Tuple{IO, AbstractArray}, f, x) == 3 - @test String(take!(f)) == "123" -end - -# issue #7248 -@test_throws BoundsError ind2chr("hello", -1) -@test_throws BoundsError chr2ind("hello", -1) -@test_throws BoundsError ind2chr("hellø", -1) -@test_throws BoundsError chr2ind("hellø", -1) -@test_throws BoundsError ind2chr("hello", 10) -@test_throws BoundsError chr2ind("hello", 10) -@test_throws BoundsError ind2chr("hellø", 10) -@test_throws BoundsError chr2ind("hellø", 10) -@test_throws BoundsError checkbounds("hello", 0) -@test_throws BoundsError checkbounds("hello", 6) -@test_throws BoundsError checkbounds("hello", 0:3) -@test_throws BoundsError checkbounds("hello", 4:6) -@test_throws BoundsError checkbounds("hello", [0:3;]) -@test_throws BoundsError checkbounds("hello", [4:6;]) -@test checkbounds("hello", 2) -@test checkbounds("hello", 1:5) -@test checkbounds("hello", [1:5;]) - -# issue #15624 (indexing with out of bounds empty range) -@test ""[10:9] == "" -@test "hello"[10:9] == "" -@test "hellø"[10:9] == "" -@test SubString("hello", 1, 6)[10:9] == "" -@test SubString("hello", 1, 0)[10:9] == "" -@test SubString("hellø", 1, 6)[10:9] == "" -@test SubString("hellø", 1, 0)[10:9] == "" -@test SubString("", 1, 6)[10:9] == "" -@test SubString("", 1, 0)[10:9] == "" - - -#= -# issue #7764 -let - srep = repeat("Σβ",2) - s="Σβ" - ss=SubString(s,1,endof(s)) - - @test repeat(ss,2) == "ΣβΣβ" - - @test endof(srep) == 7 - - @test next(srep, 3) == ('β',5) - @test next(srep, 7) == ('β',9) - - @test srep[7] == 'β' - @test_throws BoundsError srep[8] -end -=# - -# This caused JuliaLang/JSON.jl#82 -@test first('\x00':'\x7f') === '\x00' -@test last('\x00':'\x7f') === '\x7f' - -# make sure substrings handle last code unit even if not start of codepoint -let s = "x\u0302" - @test s[1:3] == s -end - -# issue #9781 -# float(SubString) wasn't tolerant of trailing whitespace, which was different -# to "normal" strings. This also checks we aren't being too tolerant and allowing -# any arbitrary trailing characters. -@test parse(Float64,"1\n") == 1.0 -@test [parse(Float64,x) for x in split("0,1\n",",")][2] == 1.0 -@test_throws ArgumentError parse(Float64,split("0,1 X\n",",")[2]) -@test parse(Float32,"1\n") == 1.0 -@test [parse(Float32,x) for x in split("0,1\n",",")][2] == 1.0 -@test_throws ArgumentError parse(Float32,split("0,1 X\n",",")[2]) - -@test ucfirst("Hola")=="Hola" -@test ucfirst("hola")=="Hola" -@test ucfirst("")=="" -@test ucfirst("*")=="*" - -@test lcfirst("Hola")=="hola" -@test lcfirst("hola")=="hola" -@test lcfirst("")=="" -@test lcfirst("*")=="*" - -# test AbstractString functions at beginning of string.jl -struct tstStringType <: AbstractString - data::Array{UInt8,1} -end -tstr = tstStringType("12") -@test_throws ErrorException endof(tstr) -@test_throws ErrorException next(tstr, Bool(1)) - -gstr = GenericString("12") -@test typeof(string(gstr))==GenericString - -@test convert(Array{UInt8}, gstr) ==[49;50] -@test convert(Array{Char,1}, gstr) ==['1';'2'] -@test convert(Symbol, gstr)==Symbol("12") - -@test gstr[1] == '1' -@test gstr[1:1] == "1" -@test gstr[[1]] == "1" - -@test done(eachindex("foobar"),7) -@test eltype(Base.EachStringIndex) == Int -@test map(uppercase, "foó") == "FOÓ" -@test chr2ind("fóobar",3) == 4 - -@test Symbol(gstr)==Symbol("12") - -@test_throws ErrorException sizeof(gstr) - -@test length(GenericString(""))==0 - -@test nextind(1:1, 1) == 2 -@test nextind([1], 1) == 2 - -@test ind2chr(gstr,2)==2 - -# issue #10307 -@test typeof(map(Int16,AbstractString[])) == Vector{Int16} - -for T in [Int8, UInt8, Int16, UInt16, Int32, UInt32, Int64, UInt64, Int128, UInt128] - for i in [typemax(T), typemin(T)] - s = "$i" - @test get(tryparse(T, s)) == i - end -end - -for T in [Int8, Int16, Int32, Int64, Int128] - for i in [typemax(T), typemin(T)] - f = "$(i)0" - @test isnull(tryparse(T, f)) - end -end - -# issue #11142 -s = "abcdefghij" -sp = pointer(s) -@test unsafe_string(sp) == s -@test unsafe_string(sp,5) == "abcde" -@test typeof(unsafe_string(sp)) == String -s = "abcde\uff\u2000\U1f596" -sp = pointer(s) -@test unsafe_string(sp) == s -@test unsafe_string(sp,5) == "abcde" -@test typeof(unsafe_string(sp)) == String - -@test get(tryparse(BigInt, "1234567890")) == BigInt(1234567890) -@test isnull(tryparse(BigInt, "1234567890-")) - -@test get(tryparse(Float64, "64")) == 64.0 -@test isnull(tryparse(Float64, "64o")) -@test get(tryparse(Float32, "32")) == 32.0f0 -@test isnull(tryparse(Float32, "32o")) - -# issue #10994: handle embedded NUL chars for string parsing -for T in [BigInt, Int8, UInt8, Int16, UInt16, Int32, UInt32, Int64, UInt64, Int128, UInt128] - @test_throws ArgumentError parse(T, "1\0") -end -for T in [BigInt, Int8, UInt8, Int16, UInt16, Int32, UInt32, Int64, UInt64, Int128, UInt128, Float64, Float32] - @test isnull(tryparse(T, "1\0")) -end -let s = normalize_string("tést",:NFKC) - @test unsafe_string(Base.unsafe_convert(Cstring, Base.cconvert(Cstring, s))) == s - @test unsafe_string(convert(Cstring, Symbol(s))) == s -end -@test_throws ArgumentError Base.unsafe_convert(Cstring, Base.cconvert(Cstring, "ba\0d")) - -cstrdup(s) = @static is_windows() ? ccall(:_strdup, Cstring, (Cstring,), s) : ccall(:strdup, Cstring, (Cstring,), s) -let p = cstrdup("hello") - @test unsafe_string(p) == "hello" - Libc.free(p) -end - -# iteration -@test [c for c in "ḟøøƀäṙ"] == ['ḟ', 'ø', 'ø', 'ƀ', 'ä', 'ṙ'] -@test [i for i in eachindex("ḟøøƀäṙ")] == [1, 4, 6, 8, 10, 12] -@test [x for x in enumerate("ḟøøƀäṙ")] == [(1, 'ḟ'), (2, 'ø'), (3, 'ø'), (4, 'ƀ'), (5, 'ä'), (6, 'ṙ')] - -# test all edge conditions -for (val, pass) in ( - (0, true), (0xd7ff, true), - (0xd800, false), (0xdfff, false), - (0xe000, true), (0xffff, true), - (0x10000, true), (0x10ffff, true), - (0x110000, false) - ) - @test isvalid(Char, val) == pass -end -for (val, pass) in ( - (b"\x00", true), - (b"\x7f", true), - (b"\x80", false), - (b"\xbf", false), - (b"\xc0", false), - (b"\xff", false), - (b"\xc0\x80", false), - (b"\xc1\x80", false), - (b"\xc2\x80", true), - (b"\xc2\xc0", false), - (b"\xed\x9f\xbf", true), - (b"\xed\xa0\x80", false), - (b"\xed\xbf\xbf", false), - (b"\xee\x80\x80", true), - (b"\xef\xbf\xbf", true), - (b"\xf0\x90\x80\x80", true), - (b"\xf4\x8f\xbf\xbf", true), - (b"\xf4\x90\x80\x80", false), - (b"\xf5\x80\x80\x80", false), - (b"\ud800\udc00", false), - (b"\udbff\udfff", false), - (b"\ud800\u0100", false), - (b"\udc00\u0100", false), - (b"\udc00\ud800", false) - ) - @test isvalid(String, val) == pass == isvalid(String(val)) -end - -# Issue #11203 -@test isvalid(String, UInt8[]) == true == isvalid("") - -# Check UTF-8 characters -# Check ASCII range (true), -# then single continuation bytes and lead bytes with no following continuation bytes (false) -for (rng,flg) in ((0:0x7f, true), (0x80:0xff, false)) - for byt in rng - @test isvalid(String, UInt8[byt]) == flg - end -end -# Check overlong lead bytes for 2-character sequences (false) -for byt = 0xc0:0xc1 - @test isvalid(String, UInt8[byt,0x80]) == false -end -# Check valid lead-in to two-byte sequences (true) -for byt = 0xc2:0xdf - for (rng,flg) in ((0x00:0x7f, false), (0x80:0xbf, true), (0xc0:0xff, false)) - for cont in rng - @test isvalid(String, UInt8[byt, cont]) == flg - end - end -end -# Check three-byte sequences -for r1 in (0xe0:0xec, 0xee:0xef) - for byt = r1 - # Check for short sequence - @test isvalid(String, UInt8[byt]) == false - for (rng,flg) in ((0x00:0x7f, false), (0x80:0xbf, true), (0xc0:0xff, false)) - for cont in rng - @test isvalid(String, UInt8[byt, cont]) == false - @test isvalid(String, UInt8[byt, cont, 0x80]) == flg - end - end - end -end -# Check hangul characters (0xd000-0xd7ff) hangul -# Check for short sequence, or start of surrogate pair -for (rng,flg) in ((0x00:0x7f, false), (0x80:0x9f, true), (0xa0:0xff, false)) - for cont in rng - @test isvalid(String, UInt8[0xed, cont]) == false - @test isvalid(String, UInt8[0xed, cont, 0x80]) == flg - end -end -# Check valid four-byte sequences -for byt = 0xf0:0xf4 - if (byt == 0xf0) - r0 = ((0x00:0x8f, false), (0x90:0xbf, true), (0xc0:0xff, false)) - elseif byt == 0xf4 - r0 = ((0x00:0x7f, false), (0x80:0x8f, true), (0x90:0xff, false)) - else - r0 = ((0x00:0x7f, false), (0x80:0xbf, true), (0xc0:0xff, false)) - end - for (rng,flg) in r0 - for cont in rng - @test isvalid(String, UInt8[byt, cont]) == false - @test isvalid(String, UInt8[byt, cont, 0x80]) == false - @test isvalid(String, UInt8[byt, cont, 0x80, 0x80]) == flg - end - end -end -# Check five-byte sequences, should be invalid -for byt = 0xf8:0xfb - @test isvalid(String, UInt8[byt, 0x80, 0x80, 0x80, 0x80]) == false -end -# Check six-byte sequences, should be invalid -for byt = 0xfc:0xfd - @test isvalid(String, UInt8[byt, 0x80, 0x80, 0x80, 0x80, 0x80]) == false -end -# Check seven-byte sequences, should be invalid -@test isvalid(String, UInt8[0xfe, 0x80, 0x80, 0x80, 0x80, 0x80]) == false - -# 11482 - -# lower and upper -@test uppercase("aBc") == "ABC" -@test uppercase('A') == 'A' -@test uppercase('a') == 'A' -@test lowercase("AbC") == "abc" -@test lowercase('A') == 'a' -@test lowercase('a') == 'a' -@test uppercase('α') == '\u0391' -@test lowercase('Δ') == 'δ' -@test lowercase('\U118bf') == '\U118df' -@test uppercase('\U1044d') == '\U10425' -@test ucfirst("Abc") == "Abc" -@test ucfirst("abc") == "Abc" -@test lcfirst("ABC") == "aBC" -@test lcfirst("aBC") == "aBC" -@test ucfirst(GenericString("")) == "" -@test lcfirst(GenericString("")) == "" -@test ucfirst(GenericString("a")) == "A" -@test lcfirst(GenericString("A")) == "a" -@test lcfirst(GenericString("a")) == "a" -@test ucfirst(GenericString("A")) == "A" - -# titlecase -@test titlecase('lj') == 'Lj' -@test titlecase("ljubljana") == "Ljubljana" -@test titlecase("aBc ABC") == "ABc ABC" -@test titlecase("abcD EFG\n\thij") == "AbcD EFG\n\tHij" - -# issue # 11464: uppercase/lowercase of GenericString becomes a String -str = "abcdef\uff\uffff\u10ffffABCDEF" -@test typeof(uppercase("abcdef")) == String -@test typeof(uppercase(GenericString(str))) == String -@test typeof(lowercase("ABCDEF")) == String -@test typeof(lowercase(GenericString(str))) == String - -foomap(ch) = (ch > Char(65)) -foobar(ch) = Char(0xd800) -foobaz(ch) = reinterpret(Char, typemax(UInt32)) -@test_throws ArgumentError map(foomap, GenericString(str)) -@test map(foobar, GenericString(str)) == String(repeat(b"\ud800", outer=[17])) -@test map(foobaz, GenericString(str)) == String(repeat(b"\ufffd", outer=[17])) - -@test "a".*["b","c"] == ["ab","ac"] -@test ["b","c"].*"a" == ["ba","ca"] -@test ["a","b"].*["c" "d"] == ["ac" "ad"; "bc" "bd"] - -@test one(String) == "" -@test prod(["*" for i in 1:3]) == "***" -@test prod(["*" for i in 1:0]) == "" - -# Make sure NULL pointers are handled consistently by String -@test_throws ArgumentError unsafe_string(Ptr{UInt8}(0)) -@test_throws ArgumentError unsafe_string(Ptr{UInt8}(0), 10) - -# ascii works on ASCII strings and fails on non-ASCII strings -@test ascii("Hello, world") == "Hello, world" -@test typeof(ascii("Hello, world")) == String -@test ascii(GenericString("Hello, world")) == "Hello, world" -@test typeof(ascii(GenericString("Hello, world"))) == String -@test_throws ArgumentError ascii("Hello, ∀") -@test_throws ArgumentError ascii(GenericString("Hello, ∀")) - -# issue #17271: endof() doesn't throw an error even with invalid strings -@test endof(String(b"\x90")) == 0 -@test endof(String(b"\xce")) == 1 - -# issue #17624, missing getindex method for String -@test "abc"[:] == "abc" - -# issue #18280: next/nextind must return past String's underlying data -for s in ("Hello", "Σ", "こんにちは", "😊😁") - @test next(s, endof(s))[2] > sizeof(s) - @test nextind(s, endof(s)) > sizeof(s) -end - -# Test cmp with AbstractStrings that don't index the same as UTF-8, which would include -# (LegacyString.)UTF16String and (LegacyString.)UTF32String, among others. - -mutable struct CharStr <: AbstractString - chars::Vector{Char} - CharStr(x) = new(collect(x)) -end -Base.start(x::CharStr) = start(x.chars) -Base.next(x::CharStr, i::Int) = next(x.chars, i) -Base.done(x::CharStr, i::Int) = done(x.chars, i) -Base.endof(x::CharStr) = endof(x.chars) - -# Simple case, with just ANSI Latin 1 characters -@test "áB" != CharStr("áá") # returns false with bug -@test cmp("áB", CharStr("áá")) == -1 # returns 0 with bug - -# Case with Unicode characters -@test cmp("\U1f596\U1f596", CharStr("\U1f596")) == 1 # Gives BoundsError with bug -@test cmp(CharStr("\U1f596"), "\U1f596\U1f596") == -1 - -# repeat function -@test repeat("xx",3) == repeat("x",6) == "xxxxxx" -@test repeat("αα",3) == repeat("α",6) == "αααααα" - -# issue #12495: check that logical indexing attempt raises ArgumentError -@test_throws ArgumentError "abc"[[true, false, true]] -@test_throws ArgumentError "abc"[BitArray([true, false, true])] - -@testset "invalid code point" begin - s = String([0x61, 0xba, 0x41]) - @test !isvalid(s) - @test_throws UnicodeError s[2] - e = try - s[2] - catch e - e - end - b = IOBuffer() - show(b, e) - @test String(take!(b)) == "UnicodeError: invalid character index 2 (0xba is a continuation byte)" -end diff --git a/julia-0.6.3/share/julia/test/strings/io.jl b/julia-0.6.3/share/julia/test/strings/io.jl deleted file mode 100644 index 061c744..0000000 --- a/julia-0.6.3/share/julia/test/strings/io.jl +++ /dev/null @@ -1,276 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -# string escaping & unescaping -cx = Any[ - 0x00000000 '\0' "\\0" - 0x00000001 '\x01' "\\x01" - 0x00000006 '\x06' "\\x06" - 0x00000007 '\a' "\\a" - 0x00000008 '\b' "\\b" - 0x00000009 '\t' "\\t" - 0x0000000a '\n' "\\n" - 0x0000000b '\v' "\\v" - 0x0000000c '\f' "\\f" - 0x0000000d '\r' "\\r" - 0x0000000e '\x0e' "\\x0e" - 0x0000001a '\x1a' "\\x1a" - 0x0000001b '\e' "\\e" - 0x0000001c '\x1c' "\\x1c" - 0x0000001f '\x1f' "\\x1f" - 0x00000020 ' ' " " - 0x0000002f '/' "/" - 0x00000030 '0' "0" - 0x00000039 '9' "9" - 0x0000003a ':' ":" - 0x00000040 '@' "@" - 0x00000041 'A' "A" - 0x0000005a 'Z' "Z" - 0x0000005b '[' "[" - 0x00000060 '`' "`" - 0x00000061 'a' "a" - 0x0000007a 'z' "z" - 0x0000007b '{' "{" - 0x0000007e '~' "~" - 0x0000007f '\x7f' "\\x7f" - 0x000000bf '\ubf' "\\ubf" - 0x000000ff '\uff' "\\uff" - 0x00000100 '\u100' "\\u100" - 0x000001ff '\u1ff' "\\u1ff" - 0x00000fff '\ufff' "\\ufff" - 0x00001000 '\u1000' "\\u1000" - 0x00001fff '\u1fff' "\\u1fff" - 0x0000ffff '\uffff' "\\uffff" - 0x00010000 '\U10000' "\\U10000" - 0x0001ffff '\U1ffff' "\\U1ffff" - 0x0002ffff '\U2ffff' "\\U2ffff" - 0x00030000 '\U30000' "\\U30000" - 0x000dffff '\Udffff' "\\Udffff" - 0x000e0000 '\Ue0000' "\\Ue0000" - 0x000effff '\Ueffff' "\\Ueffff" - 0x000f0000 '\Uf0000' "\\Uf0000" - 0x000fffff '\Ufffff' "\\Ufffff" - 0x00100000 '\U100000' "\\U100000" - 0x0010ffff '\U10ffff' "\\U10ffff" -] - -for i = 1:size(cx,1) - cp, ch, st = cx[i,:] - @test cp == convert(UInt32, ch) - @test string(ch) == unescape_string(st) - if isascii(ch) || !isprint(ch) - @test st == escape_string(string(ch)) - end - for j = 1:size(cx,1) - str = string(ch, cx[j,2]) - @test str == unescape_string(escape_string(str)) - end - @test repr(ch) == "'$(isprint(ch) ? ch : st)'" -end - -for i = 0:0x7f, p = ["","\0","x","xxx","\x7f","\uFF","\uFFF", - "\uFFFF","\U10000","\U10FFF","\U10FFFF"] - c = Char(i) - cp = string(c,p) - op = string(Char(div(i,8)), oct(i%8), p) - hp = string(Char(div(i,16)), hex(i%16), p) - @test string(unescape_string(string("\\",oct(i,1),p))) == cp - @test string(unescape_string(string("\\",oct(i,2),p))) == cp - @test string(unescape_string(string("\\",oct(i,3),p))) == cp - @test string(unescape_string(string("\\",oct(i,4),p))) == op - @test string(unescape_string(string("\\x",hex(i,1),p))) == cp - @test string(unescape_string(string("\\x",hex(i,2),p))) == cp - @test string(unescape_string(string("\\x",hex(i,3),p))) == hp -end - -@test "\z" == unescape_string("\z") == "z" -@test "\X" == unescape_string("\X") == "X" -@test "\AbC" == unescape_string("\AbC") == "AbC" - -@test "\0" == unescape_string("\\0") -@test "\1" == unescape_string("\\1") -@test "\7" == unescape_string("\\7") -@test "\0x" == unescape_string("\\0x") -@test "\1x" == unescape_string("\\1x") -@test "\7x" == unescape_string("\\7x") -@test "\00" == unescape_string("\\00") -@test "\01" == unescape_string("\\01") -@test "\07" == unescape_string("\\07") -@test "\70" == unescape_string("\\70") -@test "\71" == unescape_string("\\71") -@test "\77" == unescape_string("\\77") -@test "\00x" == unescape_string("\\00x") -@test "\01x" == unescape_string("\\01x") -@test "\07x" == unescape_string("\\07x") -@test "\70x" == unescape_string("\\70x") -@test "\71x" == unescape_string("\\71x") -@test "\77x" == unescape_string("\\77x") -@test "\000" == unescape_string("\\000") -@test "\001" == unescape_string("\\001") -@test "\007" == unescape_string("\\007") -@test "\070" == unescape_string("\\070") -@test "\071" == unescape_string("\\071") -@test "\077" == unescape_string("\\077") -@test "\170" == unescape_string("\\170") -@test "\171" == unescape_string("\\171") -@test "\177" == unescape_string("\\177") -@test "\0001" == unescape_string("\\0001") -@test "\0011" == unescape_string("\\0011") -@test "\0071" == unescape_string("\\0071") -@test "\0701" == unescape_string("\\0701") -@test "\0711" == unescape_string("\\0711") -@test "\0771" == unescape_string("\\0771") -@test "\1701" == unescape_string("\\1701") -@test "\1711" == unescape_string("\\1711") -@test "\1771" == unescape_string("\\1771") - -@test "\x0" == unescape_string("\\x0") -@test "\x1" == unescape_string("\\x1") -@test "\xf" == unescape_string("\\xf") -@test "\xF" == unescape_string("\\xF") -@test "\x0x" == unescape_string("\\x0x") -@test "\x1x" == unescape_string("\\x1x") -@test "\xfx" == unescape_string("\\xfx") -@test "\xFx" == unescape_string("\\xFx") -@test "\x00" == unescape_string("\\x00") -@test "\x01" == unescape_string("\\x01") -@test "\x0f" == unescape_string("\\x0f") -@test "\x0F" == unescape_string("\\x0F") - -# Tests of join() -@test join([]) == "" -@test join(["a"],"?") == "a" -@test join("HELLO",'-') == "H-E-L-L-O" -@test join(1:5, ", ", " and ") == "1, 2, 3, 4 and 5" -@test join(["apples", "bananas", "pineapples"], ", ", " and ") == "apples, bananas and pineapples" - -# issue #9178 `join` calls `done()` twice on the iterables -mutable struct i9178 - nnext::Int64 - ndone::Int64 -end -Base.start(jt::i9178) = (jt.nnext=0 ; jt.ndone=0 ; 0) -Base.done(jt::i9178, n) = (jt.ndone += 1 ; n > 3) -Base.next(jt::i9178, n) = (jt.nnext += 1 ; ("$(jt.nnext),$(jt.ndone)", n+1)) -@test join(i9178(0,0), ";") == "1,1;2,2;3,3;4,4" - -# quotes + interpolation (issue #455) -@test "$("string")" == "string" -arr = ["a","b","c"] -@test "[$(join(arr, " - "))]" == "[a - b - c]" - -# join with empty input -myio = IOBuffer() -join(myio, "", "", 1) -@test isempty(take!(myio)) - -# unescape_chars -@test Base.unescape_chars("\\t","t") == "t" -@test_throws ArgumentError unescape_string(IOBuffer(), string('\\',"xZ")) -@test_throws ArgumentError unescape_string(IOBuffer(), string('\\',"777")) - -# 11659 -# The indentation code was not correctly counting tab stops -@test Base.indentation(" \t") == (8, true) -@test Base.indentation(" \tfoob") == (8, false) -@test Base.indentation(" \t \t") == (16, true) - -@test Base.unindent("\tfoo",0) == "\tfoo" -@test Base.unindent("\tfoo",4) == " foo" -@test Base.unindent(" \tfoo",4) == " foo" -@test Base.unindent("\t\n \tfoo",4) == " \n foo" -@test Base.unindent("\tfoo\tbar",4) == " foo bar" -@test Base.unindent("\n\tfoo",4) == "\n foo" -@test Base.unindent("\n \tfoo",4) == "\n foo" -@test Base.unindent("\n\t\n \tfoo",4) == "\n \n foo" -@test Base.unindent("\n\tfoo\tbar",4) == "\n foo bar" - -# Tests of raw_str macro -@test raw"$" == "\$" -@test raw"\n" == "\\n" -@test raw"\t" == "\\t" - -s1 = raw""" - lorem ipsum\n - $x = 1$ - """ - -s2 = """ - lorem ipsum\\n - \$x = 1\$ - """ - -@test s1 == s2 - -# issue #22021, string realloc bug with join -s22021 = String["\"\"\" - non_max_suppression(boxes, scores, max_output_size; iou_threshold=nothing) - -Greedily selects a subset of bounding boxes in descending order of score, - -pruning away boxes that have high intersection-over-union (IOU) overlap -with previously selected boxes. Bounding boxes are supplied as -[y1, x1, y2, x2], where (y1, x1) and (y2, x2) are the coordinates of any -diagonal pair of box corners and the coordinates can be provided as normalized -(i.e., lying in the interval [0, 1]) or absolute. Note that this algorithm -is agnostic to where the origin is in the coordinate system. Note that this -algorithm is invariant to orthogonal transformations and translations -of the coordinate system; thus translating or reflections of the coordinate -system result in the same boxes being selected by the algorithm. - -The output of this operation is a set of integers indexing into the input -collection of bounding boxes representing the selected boxes. The bounding -box coordinates corresponding to the selected indices can then be obtained -using the `tf.gather operation`. For example: - - selected_indices = tf.image.non_max_suppression( - boxes, scores, max_output_size, iou_threshold) - selected_boxes = tf.gather(boxes, selected_indices) -\"\"\"", - " tf.@op function non_max_suppression(v13566, v13567, v13568; name=nothing, iou_threshold=nothing) ", - " local desc ", - " tf.with_op_name((()->begin ", - " desc = tf.NodeDescription(\"NonMaxSuppression\") ", - " begin ", - " begin ", - " v13566 = convert(TensorFlow.Tensor{Float32}, v13566) ", - " begin ", - " end", - " end", - " begin ", - " v13567 = convert(TensorFlow.Tensor{Float32}, v13567) ", - " begin ", - " end", - " end", - " begin ", - " v13568 = convert(TensorFlow.Tensor{Int32}, v13568) ", - " begin ", - " end", - " end", - " end ", - " begin ", - " begin ", - " tf.add_input(desc, v13566)", - " end", - " begin ", - " tf.add_input(desc, v13567)", - " end", - " begin ", - " tf.add_input(desc, v13568)", - " end", - " end ", - " begin ", - " begin ", - " if iou_threshold !== nothing ", - " desc[\"iou_threshold\"] = Base.identity(iou_threshold)", - " end", - " end", - " end", - " end), name, \"NonMaxSuppression\") ", - " tf.Tensor(tf.Operation(desc))", - " end"] - -for i = 1:10 - buf = IOBuffer() - print(buf, join(s22021, "\n")) - @test isvalid(String, take!(buf)) -end diff --git a/julia-0.6.3/share/julia/test/strings/search.jl b/julia-0.6.3/share/julia/test/strings/search.jl deleted file mode 100644 index 98d4736..0000000 --- a/julia-0.6.3/share/julia/test/strings/search.jl +++ /dev/null @@ -1,377 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -# some test strings -astr = "Hello, world.\n" -u8str = "∀ ε > 0, ∃ δ > 0: |x-y| < δ ⇒ |f(x)-f(y)| < ε" - -# I think these should give error on 4 also, and "" is not treated -# consistently with SubString("",1,1), nor with Char[] -for ind in (0, 5) - @test_throws BoundsError search("foo", SubString("",1,1), ind) - @test_throws BoundsError rsearch("foo", SubString("",1,1), ind) - @test_throws BoundsError searchindex("foo", SubString("",1,1), ind) - @test_throws BoundsError rsearchindex("foo", SubString("",1,1), ind) -end - -# Note: the commented out tests will be enabled after fixes to make -# sure that search/rsearch/searchindex/rsearchindex are consistent -# no matter what type of AbstractString the second argument is -@test_throws BoundsError search("foo", Char[], 0) -@test_throws BoundsError search("foo", Char[], 5) -# @test_throws BoundsError rsearch("foo", Char[], 0) -@test_throws BoundsError rsearch("foo", Char[], 5) - -# @test_throws BoundsError searchindex("foo", Char[], 0) -# @test_throws BoundsError searchindex("foo", Char[], 5) -# @test_throws BoundsError rsearchindex("foo", Char[], 0) -# @test_throws BoundsError rsearchindex("foo", Char[], 5) - -# @test_throws ErrorException in("foobar","bar") -@test_throws BoundsError search(b"\x1\x2",0x1,0) -@test rsearchindex(b"foo",b"o",0) == 0 -@test rsearchindex(SubString("",1,1),SubString("",1,1)) == 1 - -@test search(b"foo",'o') == 2 -@test rsearch(b"foo",'o') == 3 -@test search(b"foó",'ó') == 3 -@test rsearch(b"foó",'ó') == 3 - -# ascii search -for str in [astr, GenericString(astr)] - @test_throws BoundsError search(str, 'z', 0) - @test_throws BoundsError search(str, '∀', 0) - @test search(str, 'x') == 0 - @test search(str, '\0') == 0 - @test search(str, '\u80') == 0 - @test search(str, '∀') == 0 - @test search(str, 'H') == 1 - @test search(str, 'l') == 3 - @test search(str, 'l', 4) == 4 - @test search(str, 'l', 5) == 11 - @test search(str, 'l', 12) == 0 - @test search(str, ',') == 6 - @test search(str, ',', 7) == 0 - @test search(str, '\n') == 14 - @test search(str, '\n', 15) == 0 - @test_throws BoundsError search(str, 'ε', nextind(str,endof(str))+1) - @test_throws BoundsError search(str, 'a', nextind(str,endof(str))+1) -end - -# ascii rsearch -for str in [astr] - @test rsearch(str, 'x') == 0 - @test rsearch(str, '\0') == 0 - @test rsearch(str, '\u80') == 0 - @test rsearch(str, '∀') == 0 - @test rsearch(str, 'H') == 1 - @test rsearch(str, 'H', 0) == 0 - @test rsearch(str, 'l') == 11 - @test rsearch(str, 'l', 5) == 4 - @test rsearch(str, 'l', 4) == 4 - @test rsearch(str, 'l', 3) == 3 - @test rsearch(str, 'l', 2) == 0 - @test rsearch(str, ',') == 6 - @test rsearch(str, ',', 5) == 0 - @test rsearch(str, '\n') == 14 -end - -# utf-8 search -for str in (u8str, GenericString(u8str)) - @test_throws BoundsError search(str, 'z', 0) - @test_throws BoundsError search(str, '∀', 0) - @test search(str, 'z') == 0 - @test search(str, '\0') == 0 - @test search(str, '\u80') == 0 - @test search(str, '∄') == 0 - @test search(str, '∀') == 1 - @test_throws UnicodeError search(str, '∀', 2) - @test search(str, '∀', 4) == 0 - @test search(str, '∃') == 13 - @test_throws UnicodeError search(str, '∃', 15) - @test search(str, '∃', 16) == 0 - @test search(str, 'x') == 26 - @test search(str, 'x', 27) == 43 - @test search(str, 'x', 44) == 0 - @test search(str, 'δ') == 17 - @test_throws UnicodeError search(str, 'δ', 18) - @test search(str, 'δ', nextind(str,17)) == 33 - @test search(str, 'δ', nextind(str,33)) == 0 - @test search(str, 'ε') == 5 - @test search(str, 'ε', nextind(str,5)) == 54 - @test search(str, 'ε', nextind(str,54)) == 0 - @test search(str, 'ε', nextind(str,endof(str))) == 0 - @test search(str, 'a', nextind(str,endof(str))) == 0 - @test_throws BoundsError search(str, 'ε', nextind(str,endof(str))+1) - @test_throws BoundsError search(str, 'a', nextind(str,endof(str))+1) -end - -# utf-8 rsearch -for str in [u8str] - @test rsearch(str, 'z') == 0 - @test rsearch(str, '\0') == 0 - @test rsearch(str, '\u80') == 0 - @test rsearch(str, '∄') == 0 - @test rsearch(str, '∀') == 1 - @test rsearch(str, '∀', 0) == 0 - @test rsearch(str, '∃') == 13 - @test rsearch(str, '∃', 14) == 13 - @test rsearch(str, '∃', 13) == 13 - @test rsearch(str, '∃', 12) == 0 - @test rsearch(str, 'x') == 43 - @test rsearch(str, 'x', 42) == 26 - @test rsearch(str, 'x', 25) == 0 - @test rsearch(str, 'δ') == 33 - @test rsearch(str, 'δ', 32) == 17 - @test rsearch(str, 'δ', 16) == 0 - @test rsearch(str, 'ε') == 54 - @test rsearch(str, 'ε', 53) == 5 - @test rsearch(str, 'ε', 4) == 0 -end - -# string search with a single-char string -@test search(astr, "x") == 0:-1 -@test search(astr, "H") == 1:1 -@test search(astr, "H", 2) == 0:-1 -@test search(astr, "l") == 3:3 -@test search(astr, "l", 4) == 4:4 -@test search(astr, "l", 5) == 11:11 -@test search(astr, "l", 12) == 0:-1 -@test search(astr, "\n") == 14:14 -@test search(astr, "\n", 15) == 0:-1 - -@test search(u8str, "z") == 0:-1 -@test search(u8str, "∄") == 0:-1 -@test search(u8str, "∀") == 1:1 -@test search(u8str, "∀", 4) == 0:-1 -@test search(u8str, "∃") == 13:13 -@test search(u8str, "∃", 16) == 0:-1 -@test search(u8str, "x") == 26:26 -@test search(u8str, "x", 27) == 43:43 -@test search(u8str, "x", 44) == 0:-1 -@test search(u8str, "ε") == 5:5 -@test search(u8str, "ε", 7) == 54:54 -@test search(u8str, "ε", 56) == 0:-1 - -# string rsearch with a single-char string -@test rsearch(astr, "x") == 0:-1 -@test rsearch(astr, "H") == 1:1 -@test rsearch(astr, "H", 2) == 1:1 -@test rsearch(astr, "H", 0) == 0:-1 -@test rsearch(astr, "l") == 11:11 -@test rsearch(astr, "l", 10) == 4:4 -@test rsearch(astr, "l", 4) == 4:4 -@test rsearch(astr, "l", 3) == 3:3 -@test rsearch(astr, "l", 2) == 0:-1 -@test rsearch(astr, "\n") == 14:14 -@test rsearch(astr, "\n", 13) == 0:-1 - -@test rsearch(u8str, "z") == 0:-1 -@test rsearch(u8str, "∄") == 0:-1 -@test rsearch(u8str, "∀") == 1:1 -@test rsearch(u8str, "∀", 0) == 0:-1 -#TODO: setting the limit in the middle of a wide char -# makes search fail but rsearch succeed. -# Should rsearch fail as well? -#@test rsearch(u8str, "∀", 2) == 0:-1 # gives 1:3 -@test rsearch(u8str, "∃") == 13:13 -@test rsearch(u8str, "∃", 12) == 0:-1 -@test rsearch(u8str, "x") == 43:43 -@test rsearch(u8str, "x", 42) == 26:26 -@test rsearch(u8str, "x", 25) == 0:-1 -@test rsearch(u8str, "ε") == 54:54 -@test rsearch(u8str, "ε", 53) == 5:5 -@test rsearch(u8str, "ε", 4) == 0:-1 - -# string search with a single-char regex -@test search(astr, r"x") == 0:-1 -@test search(astr, r"H") == 1:1 -@test search(astr, r"H", 2) == 0:-1 -@test search(astr, r"l") == 3:3 -@test search(astr, r"l", 4) == 4:4 -@test search(astr, r"l", 5) == 11:11 -@test search(astr, r"l", 12) == 0:-1 -@test search(astr, r"\n") == 14:14 -@test search(astr, r"\n", 15) == 0:-1 -@test search(u8str, r"z") == 0:-1 -@test search(u8str, r"∄") == 0:-1 -@test search(u8str, r"∀") == 1:1 -@test search(u8str, r"∀", 4) == 0:-1 -@test search(u8str, r"∀") == search(u8str, r"\u2200") -@test search(u8str, r"∀", 4) == search(u8str, r"\u2200", 4) -@test search(u8str, r"∃") == 13:13 -@test search(u8str, r"∃", 16) == 0:-1 -@test search(u8str, r"x") == 26:26 -@test search(u8str, r"x", 27) == 43:43 -@test search(u8str, r"x", 44) == 0:-1 -@test search(u8str, r"ε") == 5:5 -@test search(u8str, r"ε", 7) == 54:54 -@test search(u8str, r"ε", 56) == 0:-1 -for i = 1:endof(astr) - @test search(astr, r"."s, i) == i:i -end -for i = 1:endof(u8str) - if isvalid(u8str,i) - @test search(u8str, r"."s, i) == i:i - end -end - -# string search with a zero-char string -for i = 1:endof(astr) - @test search(astr, "", i) == i:i-1 -end -for i = 1:endof(u8str) - @test search(u8str, "", i) == i:i-1 -end -@test search("", "") == 1:0 - -# string rsearch with a zero-char string -for i = 1:endof(astr) - @test rsearch(astr, "", i) == i:i-1 -end -for i = 1:endof(u8str) - @test rsearch(u8str, "", i) == i:i-1 -end -@test rsearch("", "") == 1:0 - -# string search with a zero-char regex -for i = 1:endof(astr) - @test search(astr, r"", i) == i:i-1 -end -for i = 1:endof(u8str) - # TODO: should regex search fast-forward invalid indices? - if isvalid(u8str,i) - @test search(u8str, r""s, i) == i:i-1 - end -end - -# string search with a two-char string literal -@test search("foo,bar,baz", "xx") == 0:-1 -@test search("foo,bar,baz", "fo") == 1:2 -@test search("foo,bar,baz", "fo", 3) == 0:-1 -@test search("foo,bar,baz", "oo") == 2:3 -@test search("foo,bar,baz", "oo", 4) == 0:-1 -@test search("foo,bar,baz", "o,") == 3:4 -@test search("foo,bar,baz", "o,", 5) == 0:-1 -@test search("foo,bar,baz", ",b") == 4:5 -@test search("foo,bar,baz", ",b", 6) == 8:9 -@test search("foo,bar,baz", ",b", 10) == 0:-1 -@test search("foo,bar,baz", "az") == 10:11 -@test search("foo,bar,baz", "az", 12) == 0:-1 - -# issue #9365 -# string search with a two-char UTF-8 (2 byte) string literal -@test search("ééé", "éé") == 1:3 -@test search("ééé", "éé", 1) == 1:3 -# string search with a two-char UTF-8 (3 byte) string literal -@test search("€€€", "€€") == 1:4 -@test search("€€€", "€€", 1) == 1:4 -# string search with a two-char UTF-8 (4 byte) string literal -@test search("\U1f596\U1f596\U1f596", "\U1f596\U1f596") == 1:5 -@test search("\U1f596\U1f596\U1f596", "\U1f596\U1f596", 1) == 1:5 - -# string search with a two-char UTF-8 (2 byte) string literal -@test search("éé", "éé") == 1:3 -@test search("éé", "éé", 1) == 1:3 -# string search with a two-char UTF-8 (3 byte) string literal -@test search("€€", "€€") == 1:4 -@test search("€€", "€€", 1) == 1:4 -# string search with a two-char UTF-8 (4 byte) string literal -@test search("\U1f596\U1f596", "\U1f596\U1f596") == 1:5 -@test search("\U1f596\U1f596", "\U1f596\U1f596", 1) == 1:5 - -# string rsearch with a two-char UTF-8 (2 byte) string literal -@test rsearch("ééé", "éé") == 3:5 -@test rsearch("ééé", "éé", endof("ééé")) == 3:5 -# string rsearch with a two-char UTF-8 (3 byte) string literal -@test rsearch("€€€", "€€") == 4:7 -@test rsearch("€€€", "€€", endof("€€€")) == 4:7 -# string rsearch with a two-char UTF-8 (4 byte) string literal -@test rsearch("\U1f596\U1f596\U1f596", "\U1f596\U1f596") == 5:9 -@test rsearch("\U1f596\U1f596\U1f596", "\U1f596\U1f596", endof("\U1f596\U1f596\U1f596")) == 5:9 - -# string rsearch with a two-char UTF-8 (2 byte) string literal -@test rsearch("éé", "éé") == 1:3 # should really be 1:4! -@test rsearch("éé", "éé", endof("ééé")) == 1:3 -# string search with a two-char UTF-8 (3 byte) string literal -@test rsearch("€€", "€€") == 1:4 # should really be 1:6! -@test rsearch("€€", "€€", endof("€€€")) == 1:4 -# string search with a two-char UTF-8 (4 byte) string literal -@test rsearch("\U1f596\U1f596", "\U1f596\U1f596") == 1:5 # should really be 1:8! -@test rsearch("\U1f596\U1f596", "\U1f596\U1f596", endof("\U1f596\U1f596\U1f596")) == 1:5 - -# string rsearch with a two-char string literal -@test rsearch("foo,bar,baz", "xx") == 0:-1 -@test rsearch("foo,bar,baz", "fo") == 1:2 -@test rsearch("foo,bar,baz", "fo", 1) == 0:-1 -@test rsearch("foo,bar,baz", "oo") == 2:3 -@test rsearch("foo,bar,baz", "oo", 2) == 0:-1 -@test rsearch("foo,bar,baz", "o,") == 3:4 -@test rsearch("foo,bar,baz", "o,", 1) == 0:-1 -@test rsearch("foo,bar,baz", ",b") == 8:9 -@test rsearch("foo,bar,baz", ",b", 6) == 4:5 -@test rsearch("foo,bar,baz", ",b", 3) == 0:-1 -@test rsearch("foo,bar,baz", "az") == 10:11 -@test rsearch("foo,bar,baz", "az", 10) == 0:-1 - -# array rsearch -@test rsearch(UInt8[1,2,3],UInt8[2,3],3) == 2:3 -@test rsearch(UInt8[1,2,3],UInt8[2,3],1) == 0:-1 - -# string search with a two-char regex -@test search("foo,bar,baz", r"xx") == 0:-1 -@test search("foo,bar,baz", r"fo") == 1:2 -@test search("foo,bar,baz", r"fo", 3) == 0:-1 -@test search("foo,bar,baz", r"oo") == 2:3 -@test search("foo,bar,baz", r"oo", 4) == 0:-1 -@test search("foo,bar,baz", r"o,") == 3:4 -@test search("foo,bar,baz", r"o,", 5) == 0:-1 -@test search("foo,bar,baz", r",b") == 4:5 -@test search("foo,bar,baz", r",b", 6) == 8:9 -@test search("foo,bar,baz", r",b", 10) == 0:-1 -@test search("foo,bar,baz", r"az") == 10:11 -@test search("foo,bar,baz", r"az", 12) == 0:-1 - -@test searchindex("foo", 'o') == 2 -@test searchindex("foo", 'o', 3) == 3 - -# string searchindex with a two-char UTF-8 (2 byte) string literal -@test searchindex("ééé", "éé") == 1 -@test searchindex("ééé", "éé", 1) == 1 -# string searchindex with a two-char UTF-8 (3 byte) string literal -@test searchindex("€€€", "€€") == 1 -@test searchindex("€€€", "€€", 1) == 1 -# string searchindex with a two-char UTF-8 (4 byte) string literal -@test searchindex("\U1f596\U1f596\U1f596", "\U1f596\U1f596") == 1 -@test searchindex("\U1f596\U1f596\U1f596", "\U1f596\U1f596", 1) == 1 - -# string searchindex with a two-char UTF-8 (2 byte) string literal -@test searchindex("éé", "éé") == 1 -@test searchindex("éé", "éé", 1) == 1 -# string searchindex with a two-char UTF-8 (3 byte) string literal -@test searchindex("€€", "€€") == 1 -@test searchindex("€€", "€€", 1) == 1 -# string searchindex with a two-char UTF-8 (4 byte) string literal -@test searchindex("\U1f596\U1f596", "\U1f596\U1f596") == 1 -@test searchindex("\U1f596\U1f596", "\U1f596\U1f596", 1) == 1 - -# string rsearchindex with a two-char UTF-8 (2 byte) string literal -@test rsearchindex("ééé", "éé") == 3 -@test rsearchindex("ééé", "éé", endof("ééé")) == 3 -# string rsearchindex with a two-char UTF-8 (3 byte) string literal -@test rsearchindex("€€€", "€€") == 4 -@test rsearchindex("€€€", "€€", endof("€€€")) == 4 -# string rsearchindex with a two-char UTF-8 (4 byte) string literal -@test rsearchindex("\U1f596\U1f596\U1f596", "\U1f596\U1f596") == 5 -@test rsearchindex("\U1f596\U1f596\U1f596", "\U1f596\U1f596", endof("\U1f596\U1f596\U1f596")) == 5 - -# string rsearchindex with a two-char UTF-8 (2 byte) string literal -@test rsearchindex("éé", "éé") == 1 -@test rsearchindex("éé", "éé", endof("ééé")) == 1 -# string searchindex with a two-char UTF-8 (3 byte) string literal -@test rsearchindex("€€", "€€") == 1 -@test rsearchindex("€€", "€€", endof("€€€")) == 1 -# string searchindex with a two-char UTF-8 (4 byte) string literal -@test rsearchindex("\U1f596\U1f596", "\U1f596\U1f596") == 1 -@test rsearchindex("\U1f596\U1f596", "\U1f596\U1f596", endof("\U1f596\U1f596\U1f596")) == 1 - -@test_throws ErrorException "ab" ∈ "abc" diff --git a/julia-0.6.3/share/julia/test/strings/types.jl b/julia-0.6.3/share/julia/test/strings/types.jl deleted file mode 100644 index c4ff522..0000000 --- a/julia-0.6.3/share/julia/test/strings/types.jl +++ /dev/null @@ -1,212 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -## SubString, RevString and Cstring tests ## - -## SubString tests ## -u8str = "∀ ε > 0, ∃ δ > 0: |x-y| < δ ⇒ |f(x)-f(y)| < ε" -u8str2 = u8str^2 -len_u8str = length(u8str) -slen_u8str = length(u8str) -len_u8str2 = length(u8str2) -slen_u8str2 = length(u8str2) - -@test len_u8str2 == 2 * len_u8str -@test slen_u8str2 == 2 * slen_u8str - -u8str2plain = String(u8str2) - -for i1 = 1:length(u8str2) - if !isvalid(u8str2, i1); continue; end - for i2 = i1:length(u8str2) - if !isvalid(u8str2, i2); continue; end - @test length(u8str2[i1:i2]) == length(u8str2plain[i1:i2]) - @test length(u8str2[i1:i2]) == length(u8str2plain[i1:i2]) - @test u8str2[i1:i2] == u8str2plain[i1:i2] - end -end - -str="tempus fugit" #length(str)==12 -ss=SubString(str,1,length(str)) #match source string -@test length(ss)==length(str) - -ss=SubString(str,1,0) #empty SubString -@test length(ss)==0 - -ss=SubString(str,14,20) #start indexed beyond source string length -@test length(ss)==0 - -ss=SubString(str,10,16) #end indexed beyond source string length -@test length(ss)==3 - -str2="" -ss=SubString(str2,1,4) #empty source string -@test length(ss)==0 - -ss=SubString(str2,1,1) #empty source string, identical start and end index -@test length(ss)==0 - -@test SubString("foobar",big(1),big(3)) == "foo" - -str = "aa\u2200\u2222bb" -u = SubString(str, 3, 6) -@test length(u)==2 -b = IOBuffer() -write(b, u) -@test String(take!(b)) == "\u2200\u2222" - -@test_throws ArgumentError SubString(str, 4, 5) -@test_throws BoundsError next(u, 0) -@test_throws BoundsError next(u, 7) -@test_throws BoundsError getindex(u, 0) -@test_throws BoundsError getindex(u, 7) -@test_throws BoundsError getindex(u, 0:1) -@test_throws BoundsError getindex(u, 7:7) -@test reverseind(u, 1) == 4 -@test typeof(Base.cconvert(Ptr{Int8},u)) == SubString{String} -@test Base.cconvert(Ptr{Int8},u) == u - -str = "føøbar" -u = SubString(str, 4, 3) -@test length(u)==0 -b = IOBuffer() -write(b, u) -@test String(take!(b)) == "" - -str = "føøbar" -u = SubString(str, 10, 10) -@test length(u)==0 -b = IOBuffer() -write(b, u) -@test String(take!(b)) == "" - -# search and SubString (issue #5679) -str = "Hello, world!" -u = SubString(str, 1, 5) -@test rsearch(u, "World") == 0:-1 -@test rsearch(u, 'z') == 0 -@test rsearch(u, "ll") == 3:4 - -# sizeof -@test sizeof(SubString("abc\u2222def",4,4)) == 3 - -# issue #3710 -@test prevind(SubString("{var}",2,4),4) == 3 - -# issue #4183 -@test split(SubString("x", 2, 0), "y") == AbstractString[""] - -# issue #6772 -@test float(SubString("10",1,1)) === 1.0 -@test float(SubString("1 0",1,1)) === 1.0 -@test parse(Float32,SubString("10",1,1)) === 1.0f0 - -# issue #5870 -@test !ismatch(Regex("aa"), SubString("",1,0)) -@test ismatch(Regex(""), SubString("",1,0)) - -# isvalid(), chr2ind() and ind2chr() for SubString{DirectIndexString} -let s="lorem ipsum", - sdict=Dict(SubString(s,1,11)=>s, - SubString(s,1,6)=>"lorem ", - SubString(s,1,0)=>"", - SubString(s,2,4)=>"ore", - SubString(s,2,16)=>"orem ipsum", - SubString(s,12,14)=>"" - ) - for (ss,s) in sdict - for i in -1:12 - @test isvalid(ss,i)==isvalid(s,i) - end - end - for (ss,s) in sdict - for i in 1:length(ss) - @test ind2chr(ss,i)==ind2chr(s,i) - end - end - for (ss,s) in sdict - for i in 1:length(ss) - @test chr2ind(ss,i)==chr2ind(s,i) - end - end -end #let - -#for isvalid(SubString{String}) -let s = "Σx + βz - 2" - for i in -1:length(s)+2 - ss=SubString(s,1,i) - @test isvalid(ss,i)==isvalid(s,i) - end -end - -ss=SubString("hello",1,5) -@test_throws BoundsError ind2chr(ss, -1) -@test_throws BoundsError chr2ind(ss, -1) -@test_throws BoundsError chr2ind(ss, 10) -@test_throws BoundsError ind2chr(ss, 10) - -# length(SubString{String}) performance specialization -let s = "|η(α)-ϕ(κ)| < ε" - @test length(SubString(s,1,0))==length(s[1:0]) - @test length(SubString(s,4,4))==length(s[4:4]) - @test length(SubString(s,1,7))==length(s[1:7]) - @test length(SubString(s,4,11))==length(s[4:11]) -end - -## Reverse strings ## - -rs = RevString("foobar") -@test length(rs) == 6 -@test sizeof(rs) == 6 -@test isascii(rs) - -# issue #4586 -@test rsplit(RevString("ailuj"),'l') == ["ju","ia"] -@test parse(Float64,RevString("64")) === 46.0 - -# reverseind -for T in (String, GenericString) - for prefix in ("", "abcd", "\U0001d6a4\U0001d4c1", "\U0001d6a4\U0001d4c1c", " \U0001d6a4\U0001d4c1") - for suffix in ("", "abcde", "\U0001d4c1β\U0001d6a4", "\U0001d4c1β\U0001d6a4c", " \U0001d4c1β\U0001d6a4") - for c in ('X', 'δ', '\U0001d6a5') - s = convert(T, string(prefix, c, suffix)) - r = reverse(s) - ri = search(r, c) - @test r == RevString(s) - @test c == s[reverseind(s, ri)] == r[ri] - s = RevString(s) - r = reverse(s) - ri = search(r, c) - @test c == s[reverseind(s, ri)] == r[ri] - s = convert(T, string(prefix, prefix, c, suffix, suffix)) - pre = convert(T, prefix) - sb = SubString(s, nextind(pre, endof(pre)), endof(convert(T, string(prefix, prefix, c, suffix)))) - r = reverse(sb) - ri = search(r, c) - @test c == sb[reverseind(sb, ri)] == r[ri] - end - end - end -end - -## Cstring tests ## - -# issue #13974: comparison against pointers - -str = String("foobar") -ptr = pointer(str) -cstring = Cstring(ptr) -@test ptr == cstring -@test cstring == ptr - -# convenient NULL string creation from Ptr{Void} -nullstr = Cstring(C_NULL) - -# Comparisons against NULL strings -@test ptr != nullstr -@test nullstr != ptr - -# Short-hand comparison against C_NULL -@test nullstr == C_NULL -@test C_NULL == nullstr -@test cstring != C_NULL -@test C_NULL != cstring diff --git a/julia-0.6.3/share/julia/test/strings/util.jl b/julia-0.6.3/share/julia/test/strings/util.jl deleted file mode 100644 index 92298b7..0000000 --- a/julia-0.6.3/share/julia/test/strings/util.jl +++ /dev/null @@ -1,237 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -# padding (lpad and rpad) -@test lpad("foo", 3) == "foo" -@test rpad("foo", 3) == "foo" -@test lpad("foo", 5) == " foo" -@test rpad("foo", 5) == "foo " -@test lpad("foo", 5, " ") == " foo" -@test rpad("foo", 5, " ") == "foo " -@test lpad("foo", 6, " ") == " foo" -@test rpad("foo", 6, " ") == "foo " - -# string manipulation -@test strip("") == "" -@test strip(" ") == "" -@test strip(" ") == "" -@test strip(" ") == "" -@test strip("\t hi \n") == "hi" -@test strip("foobarfoo", ['f','o']) == "bar" -@test strip("foobarfoo", ('f','o')) == "bar" - -for s in ("", " ", " abc", "abc ", " abc "), f in (lstrip, rstrip, strip) - fs = f(s) - for T = (String, GenericString) - t = convert(T,s) - ft = f(t) - @test s == t - @test fs == ft - @test typeof(ft) == typeof(t[1:end]) - - b = convert(SubString{T}, t) - fb = f(b) - @test s == b - @test fs == fb - @test typeof(fb) == SubString{T} - end -end - -# split -@test isequal(split("foo,bar,baz", 'x'), ["foo,bar,baz"]) -@test isequal(split("foo,bar,baz", ','), ["foo","bar","baz"]) -@test isequal(split("foo,bar,baz", ","), ["foo","bar","baz"]) -@test isequal(split("foo,bar,baz", r","), ["foo","bar","baz"]) -@test isequal(split("foo,bar,baz", ','; limit=0), ["foo","bar","baz"]) -@test isequal(split("foo,bar,baz", ','; limit=1), ["foo,bar,baz"]) -@test isequal(split("foo,bar,baz", ','; limit=2), ["foo","bar,baz"]) -@test isequal(split("foo,bar,baz", ','; limit=3), ["foo","bar","baz"]) -@test isequal(split("foo,bar", "o,b"), ["fo","ar"]) - -@test isequal(split("", ','), [""]) -@test isequal(split(",", ','), ["",""]) -@test isequal(split(",,", ','), ["","",""]) -@test isequal(split("", ',' ; keep=false), []) -@test isequal(split(",", ',' ; keep=false), []) -@test isequal(split(",,", ','; keep=false), []) - -@test isequal(split("a b c"), ["a","b","c"]) -@test isequal(split("a b \t c\n"), ["a","b","c"]) - -@test isequal(rsplit("foo,bar,baz", 'x'), ["foo,bar,baz"]) -@test isequal(rsplit("foo,bar,baz", ','), ["foo","bar","baz"]) -@test isequal(rsplit("foo,bar,baz", ","), ["foo","bar","baz"]) -@test isequal(rsplit("foo,bar,baz", ','; limit=0), ["foo","bar","baz"]) -@test isequal(rsplit("foo,bar,baz", ','; limit=1), ["foo,bar,baz"]) -@test isequal(rsplit("foo,bar,baz", ','; limit=2), ["foo,bar","baz"]) -@test isequal(rsplit("foo,bar,baz", ','; limit=3), ["foo","bar","baz"]) -@test isequal(rsplit("foo,bar", "o,b"), ["fo","ar"]) - -@test isequal(rsplit("", ','), [""]) -@test isequal(rsplit(",", ','), ["",""]) -@test isequal(rsplit(",,", ','), ["","",""]) -@test isequal(rsplit(",,", ','; limit=2), [",",""]) -@test isequal(rsplit("", ',' ; keep=false), []) -@test isequal(rsplit(",", ',' ; keep=false), []) -@test isequal(rsplit(",,", ','; keep=false), []) - -#@test isequal(rsplit("a b c"), ["a","b","c"]) -#@test isequal(rsplit("a b \t c\n"), ["a","b","c"]) - -let str = "a.:.ba..:..cba.:.:.dcba.:." -@test isequal(split(str, ".:."), ["a","ba.",".cba",":.dcba",""]) -@test isequal(split(str, ".:."; keep=false), ["a","ba.",".cba",":.dcba"]) -@test isequal(split(str, ".:."), ["a","ba.",".cba",":.dcba",""]) -@test isequal(split(str, r"\.(:\.)+"), ["a","ba.",".cba","dcba",""]) -@test isequal(split(str, r"\.(:\.)+"; keep=false), ["a","ba.",".cba","dcba"]) -@test isequal(split(str, r"\.+:\.+"), ["a","ba","cba",":.dcba",""]) -@test isequal(split(str, r"\.+:\.+"; keep=false), ["a","ba","cba",":.dcba"]) - -@test isequal(rsplit(str, ".:."), ["a","ba.",".cba.:","dcba",""]) -@test isequal(rsplit(str, ".:."; keep=false), ["a","ba.",".cba.:","dcba"]) -@test isequal(rsplit(str, ".:."; limit=2), ["a.:.ba..:..cba.:.:.dcba", ""]) -@test isequal(rsplit(str, ".:."; limit=3), ["a.:.ba..:..cba.:", "dcba", ""]) -@test isequal(rsplit(str, ".:."; limit=4), ["a.:.ba.", ".cba.:", "dcba", ""]) -@test isequal(rsplit(str, ".:."; limit=5), ["a", "ba.", ".cba.:", "dcba", ""]) -@test isequal(rsplit(str, ".:."; limit=6), ["a", "ba.", ".cba.:", "dcba", ""]) -end - -# zero-width splits -@test isequal(rsplit("", ""), [""]) - -@test isequal(split("", ""), [""]) -@test isequal(split("", r""), [""]) -@test isequal(split("abc", ""), ["a","b","c"]) -@test isequal(split("abc", r""), ["a","b","c"]) -@test isequal(split("abcd", r"b?"), ["a","c","d"]) -@test isequal(split("abcd", r"b*"), ["a","c","d"]) -@test isequal(split("abcd", r"b+"), ["a","cd"]) -@test isequal(split("abcd", r"b?c?"), ["a","d"]) -@test isequal(split("abcd", r"[bc]?"), ["a","","d"]) -@test isequal(split("abcd", r"a*"), ["","b","c","d"]) -@test isequal(split("abcd", r"a+"), ["","bcd"]) -@test isequal(split("abcd", r"d*"), ["a","b","c",""]) -@test isequal(split("abcd", r"d+"), ["abc",""]) -@test isequal(split("abcd", r"[ad]?"), ["","b","c",""]) - -# replace -@test replace("\u2202", '*', '\0') == "\u2202" - -@test replace("foobar", 'o', '0') == "f00bar" -@test replace("foobar", 'o', '0', 1) == "f0obar" -@test replace("foobar", 'o', "") == "fbar" -@test replace("foobar", 'o', "", 1) == "fobar" -@test replace("foobar", 'f', 'F') == "Foobar" -@test replace("foobar", 'r', 'R') == "foobaR" - -@test replace("foofoofoo", "foo", "bar") == "barbarbar" -@test replace("foobarfoo", "foo", "baz") == "bazbarbaz" -@test replace("barfoofoo", "foo", "baz") == "barbazbaz" - -@test replace("", "", "") == "" -@test replace("", "", "x") == "x" -@test replace("", "x", "y") == "" - -@test replace("abcd", "", "^") == "^a^b^c^d^" -@test replace("abcd", "b", "^") == "a^cd" -@test replace("abcd", r"b?", "^") == "^a^c^d^" -@test replace("abcd", r"b+", "^") == "a^cd" -@test replace("abcd", r"b?c?", "^") == "^a^d^" -@test replace("abcd", r"[bc]?", "^") == "^a^^d^" - -@test replace("foobarfoo", r"(fo|ba)", "xx") == "xxoxxrxxo" -@test replace("foobarfoo", r"(foo|ba)", "bar") == "barbarrbar" - -@test replace("foobar", 'o', 'ø') == "føøbar" -@test replace("foobar", 'o', 'ø', 1) == "føobar" -@test replace("føøbar", 'ø', 'o') == "foobar" -@test replace("føøbar", 'ø', 'o', 1) == "foøbar" -@test replace("føøbar", 'ø', 'ö') == "fööbar" -@test replace("føøbar", 'ø', 'ö', 1) == "föøbar" -@test replace("føøbar", 'ø', "") == "fbar" -@test replace("føøbar", 'ø', "", 1) == "føbar" -@test replace("føøbar", 'f', 'F') == "Føøbar" -@test replace("ḟøøbar", 'ḟ', 'F') == "Føøbar" -@test replace("føøbar", 'f', 'Ḟ') == "Ḟøøbar" -@test replace("ḟøøbar", 'ḟ', 'Ḟ') == "Ḟøøbar" -@test replace("føøbar", 'r', 'R') == "føøbaR" -@test replace("føøbaṙ", 'ṙ', 'R') == "føøbaR" -@test replace("føøbar", 'r', 'Ṙ') == "føøbaṘ" -@test replace("føøbaṙ", 'ṙ', 'Ṙ') == "føøbaṘ" - -@test replace("ḟøøḟøøḟøø", "ḟøø", "bar") == "barbarbar" -@test replace("ḟøøbarḟøø", "ḟøø", "baz") == "bazbarbaz" -@test replace("barḟøøḟøø", "ḟøø", "baz") == "barbazbaz" - -@test replace("foofoofoo", "foo", "ƀäṙ") == "ƀäṙƀäṙƀäṙ" -@test replace("fooƀäṙfoo", "foo", "baz") == "bazƀäṙbaz" -@test replace("ƀäṙfoofoo", "foo", "baz") == "ƀäṙbazbaz" - -@test replace("foofoofoo", "foo", "bar") == "barbarbar" -@test replace("foobarfoo", "foo", "ƀäż") == "ƀäżbarƀäż" -@test replace("barfoofoo", "foo", "ƀäż") == "barƀäżƀäż" - -@test replace("ḟøøḟøøḟøø", "ḟøø", "ƀäṙ") == "ƀäṙƀäṙƀäṙ" -@test replace("ḟøøƀäṙḟøø", "ḟøø", "baz") == "bazƀäṙbaz" -@test replace("ƀäṙḟøøḟøø", "ḟøø", "baz") == "ƀäṙbazbaz" - -@test replace("ḟøøḟøøḟøø", "ḟøø", "bar") == "barbarbar" -@test replace("ḟøøbarḟøø", "ḟøø", "ƀäż") == "ƀäżbarƀäż" -@test replace("barḟøøḟøø", "ḟøø", "ƀäż") == "barƀäżƀäż" - -@test replace("ḟøøḟøøḟøø", "ḟøø", "ƀäṙ") == "ƀäṙƀäṙƀäṙ" -@test replace("ḟøøƀäṙḟøø", "ḟøø", "ƀäż") == "ƀäżƀäṙƀäż" -@test replace("ƀäṙḟøøḟøø", "ḟøø", "ƀäż") == "ƀäṙƀäżƀäż" - -@test replace("", "", "ẍ") == "ẍ" -@test replace("", "ẍ", "ÿ") == "" - -@test replace("äƀçđ", "", "π") == "πäπƀπçπđπ" -@test replace("äƀçđ", "ƀ", "π") == "äπçđ" -@test replace("äƀçđ", r"ƀ?", "π") == "πäπçπđπ" -@test replace("äƀçđ", r"ƀ+", "π") == "äπçđ" -@test replace("äƀçđ", r"ƀ?ç?", "π") == "πäπđπ" -@test replace("äƀçđ", r"[ƀç]?", "π") == "πäππđπ" - -@test replace("foobarfoo", r"(fo|ba)", "ẍẍ") == "ẍẍoẍẍrẍẍo" - -@test replace("ḟøøbarḟøø", r"(ḟø|ba)", "xx") == "xxøxxrxxø" -@test replace("ḟøøbarḟøø", r"(ḟøø|ba)", "bar") == "barbarrbar" - -@test replace("fooƀäṙfoo", r"(fo|ƀä)", "xx") == "xxoxxṙxxo" -@test replace("fooƀäṙfoo", r"(foo|ƀä)", "ƀäṙ") == "ƀäṙƀäṙṙƀäṙ" - -@test replace("ḟøøƀäṙḟøø", r"(ḟø|ƀä)", "xx") == "xxøxxṙxxø" -@test replace("ḟøøƀäṙḟøø", r"(ḟøø|ƀä)", "ƀäṙ") == "ƀäṙƀäṙṙƀäṙ" - -@test replace("foo", "oo", uppercase) == "fOO" - -# Issue 13332 -@test replace("abc", 'b', 2.1) == "a2.1c" - -# chomp/chop -@test chomp("foo\n") == "foo" -@test chop("fooε") == "foo" -@test isa(chomp("foo"), SubString) -@test isa(chop("foo"), SubString) - -# bytes2hex and hex2bytes -hex_str = "d7a8fbb307d7809469ca9abcb0082e4f8d5651e46d3cdb762d02d0bf37c9e592" -bin_val = hex2bytes(hex_str) - -@test div(length(hex_str), 2) == length(bin_val) -@test hex_str == bytes2hex(bin_val) - -bin_val = hex2bytes("07bf") -@test bin_val[1] == 7 -@test bin_val[2] == 191 -@test typeof(bin_val) == Array{UInt8, 1} -@test length(bin_val) == 2 - -# all valid hex chars -@test "0123456789abcdefabcdef" == bytes2hex(hex2bytes("0123456789abcdefABCDEF")) - -# odd size -@test_throws ArgumentError hex2bytes("0123456789abcdefABCDEF0") - -#non-hex characters -@test_throws ArgumentError hex2bytes("0123456789abcdefABCDEFGH") diff --git a/julia-0.6.3/share/julia/test/subarray.jl b/julia-0.6.3/share/julia/test/subarray.jl deleted file mode 100644 index 45d31b6..0000000 --- a/julia-0.6.3/share/julia/test/subarray.jl +++ /dev/null @@ -1,565 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -using Base.Test - -######## Utilities ########### - -# Generate an array similar to A[indx1, indx2, ...], but only call -# getindex with scalar-valued indexes. This will be safe even if -# `getindex` someday calls `view`. - -# The "nodrop" variant does not drop any dimensions (not even trailing ones) -function Agen_nodrop(A::AbstractArray, I...) - irep = replace_colon(A, I) - _Agen(A, ensure_iterable(irep)...) -end - -# This drops scalar dimensions -function Agen_slice(A::AbstractArray, I...) - irep = replace_colon(A, I) - B = _Agen(A, ensure_iterable(irep)...) - sd = Int[] - for i = 1:length(I) - if isa(I[i], Real) - push!(sd, i) - end - end - squeeze(B, sd) -end - -_Agen(A, i1) = [A[j1] for j1 in i1] -_Agen(A, i1, i2) = [A[j1,j2] for j1 in i1, j2 in i2] -_Agen(A, i1, i2, i3) = [A[j1,j2,j3] for j1 in i1, j2 in i2, j3 in i3] -_Agen(A, i1, i2, i3, i4) = [A[j1,j2,j3,j4] for j1 in i1, j2 in i2, j3 in i3, j4 in i4] - -function replace_colon(A::AbstractArray, I) - Iout = Array{Any}(length(I)) - for d = 1:length(I)-1 - Iout[d] = isa(I[d], Colon) ? (1:size(A,d)) : I[d] - end - d = length(I) - Iout[d] = isa(I[d], Colon) ? (1:prod(size(A)[d:end])) : I[d] - (Iout...,) -end - -ensure_iterable(::Tuple{}) = () -ensure_iterable(t::Tuple{Union{Number, CartesianIndex}, Vararg{Any}}) = ((t[1],), ensure_iterable(Base.tail(t))...) -ensure_iterable(t::Tuple{Any, Vararg{Any}}) = (t[1], ensure_iterable(Base.tail(t))...) - -index_ndims(t::Tuple) = tup2val(Base.index_ndims(t)) -tup2val{N}(::NTuple{N}) = Val{N} - -# To avoid getting confused by manipulations that are implemented for SubArrays, -# it's good to copy the contents to an Array. This version protects against -# `similar` ever changing its meaning. -function copy_to_array(A::AbstractArray) - Ac = Array{eltype(A)}(size(A)) - copy!(Ac, A) -end - -# Discover the highest dimension along which the values in A are -# separated by a single increment. If A was extracted via getindex -# from reshape(1:N, ...), this is equivalent to finding the highest -# dimension of the SubArray consistent with a single stride in the -# parent array. -function single_stride_dim(A::Array) - ld = 0 - while ld < ndims(A) - # Collapse all dimensions up to & including ld+1 into the first dimension - shp = [prod(size(A)[1:ld+1])] - for j = ld+2:ndims(A) - push!(shp, size(A,j)) - end - Ar = reshape(A, shp...) - # Compute the diff along dimension 1 - if size(Ar, 1) > 1 - indexes = map(d->1:size(Ar,d), [1:ndims(Ar);]) - indexesp = copy(indexes); indexesp[1] = 2:size(Ar,1) - indexesm = copy(indexes); indexesm[1] = 1:size(Ar,1)-1 - dA = Ar[indexesp...] - Ar[indexesm...] - ustride = unique(dA[:]) - if length(ustride) == 1 # is it a single stride? - ld += 1 - else - break - end - else - ld += 1 - end - end - ld -end -single_stride_dim(A::ANY) = single_stride_dim(copy_to_array(A)) - -# Testing equality of AbstractArrays, using several different methods to access values -function test_cartesian(A::ANY, B::ANY) - isgood = true - for (IA, IB) in zip(eachindex(A), eachindex(B)) - if A[IA] != B[IB] - @show IA IB A[IA] B[IB] - isgood = false - break - end - end - if !isgood - @show A - @show B - error("Mismatch") - end -end - -function test_linear(A::ANY, B::ANY) - length(A) == length(B) || error("length mismatch") - isgood = true - for (iA, iB) in zip(1:length(A), 1:length(B)) - if A[iA] != B[iB] - isgood = false - break - end - end - if !isgood - @show A - @show A.indexes - @show B - error("Mismatch") - end -end - -# "mixed" means 2 indexes even for N-dimensional arrays -test_mixed{T}(::AbstractArray{T,1}, ::Array) = nothing -test_mixed{T}(::AbstractArray{T,2}, ::Array) = nothing -test_mixed(A, B::Array) = _test_mixed(A, reshape(B, size(A))) -function _test_mixed(A::ANY, B::ANY) - m = size(A, 1) - n = size(A, 2) - isgood = true - for j = 1:n, i = 1:m - if A[i,j] != B[i,j] - isgood = false - break - end - end - if !isgood - @show A - @show B - error("Mismatch") - end - nothing -end - -function test_bounds(A::ANY) - @test_throws BoundsError A[0] - @test_throws BoundsError A[end+1] - @test_throws BoundsError A[1, 0] - @test_throws BoundsError A[1, end+1] - @test_throws BoundsError A[1, 1, 0] - @test_throws BoundsError A[1, 1, end+1] - @test_throws BoundsError A[0, 1] - @test_throws BoundsError A[end+1, 1] - @test_throws BoundsError A[0, 1, 1] - @test_throws BoundsError A[end+1, 1, 1] - @test_throws BoundsError A[1, 0, 1] - @test_throws BoundsError A[1, end+1, 1] -end - -function dim_break_linindex(I) - i = 1 - while i <= length(I) && !isa(I[i], Vector{Int}) - i += 1 - end - i - 1 -end - -function runsubarraytests(A::Array, I...) - # Direct test of linear indexing inference - C = Agen_nodrop(A, I...) - ld = min(single_stride_dim(C), dim_break_linindex(I)) - S = view(A, I...) - if Base.iscontiguous(S) - @test S.stride1 == 1 - end - test_linear(S, C) - test_cartesian(S, C) - test_mixed(S, C) -end - -function runsubarraytests(A::ANY, I...) - # When A was created with view, we have to check bounds, since some - # of the "residual" dimensions have size 1. It's possible that we - # need dedicated tests for view. - for d = 1:length(I)-1 - if !isa(I[d], Colon) && any(I[d] .> size(A,d)) - return nothing - end - end - if !isa(I[end], Colon) && any(I[end] .> prod(size(A)[length(I):end])) - return nothing - end - AA = copy_to_array(A) - # Direct test of linear indexing inference - C = Agen_nodrop(AA, I...) - Cld = ld = min(single_stride_dim(C), dim_break_linindex(I)) - Cdim = AIindex = 0 - while Cdim <= Cld && AIindex < length(A.indexes) - AIindex += 1 - if isa(A.indexes[AIindex], Real) - ld += 1 - else - Cdim += 1 - end - end - local S - try - S = view(A, I...) - catch err - @show typeof(A) - @show A.indexes - @show I - rethrow(err) - end - test_linear(S, C) - test_cartesian(S, C) - test_mixed(S, C) -end - -# indexN is a cartesian index, indexNN is a linear index for 2 dimensions, and indexNNN is a linear index for 3 dimensions -function runviews(SB::AbstractArray, indexN, indexNN, indexNNN) - @assert ndims(SB) > 2 - for i3 in indexN, i2 in indexN, i1 in indexN - ndims(SB) > 3 && i3 isa Colon && continue # TODO: Re-enable once Colon no longer spans partial trailing dimensions - runsubarraytests(SB, i1, i2, i3) - end - for i2 in indexN, i1 in indexN - i2 isa Colon && continue # TODO: Re-enable once Colon no longer spans partial trailing dimensions - runsubarraytests(SB, i1, i2) - end - for i1 in indexNNN - runsubarraytests(SB, i1) - end -end - -function runviews{T}(SB::AbstractArray{T,2}, indexN, indexNN, indexNNN) - for i2 in indexN, i1 in indexN - runsubarraytests(SB, i1, i2) - end - for i1 in indexNN - runsubarraytests(SB, i1) - end -end - -function runviews{T}(SB::AbstractArray{T,1}, indexN, indexNN, indexNNN) - for i1 in indexN - runsubarraytests(SB, i1) - end -end - -runviews{T}(SB::AbstractArray{T,0}, indexN, indexNN, indexNNN) = nothing - -######### Tests ######### - -testfull = Bool(parse(Int,(get(ENV, "JULIA_TESTFULL", "0")))) - -### Views from Arrays ### -index5 = (1, :, 2:5, [4,1,5], reshape([2]), view(1:5,[2 3 4 1])) # all work with at least size 5 -index25 = (3, :, 2:11, [19,9,7], reshape([10]), view(1:25,[19 15; 4 24])) -index125 = (113, :, 85:121, [99,14,103], reshape([72]), view(1:125,reshape([25,4,102,67], 1, 2, 2))) - -if testfull - let A = copy(reshape(1:5*7*11, 11, 7, 5)) - runviews(A, index5, index25, index125) - end -end - -### Views from views ### - -# "outer" indexes create snips that have at least size 5 along each dimension, -# with the exception of Int-slicing -oindex = (:, 6, 3:7, reshape([12]), [8,4,6,12,5,7], [3:7 1:5 2:6 4:8 5:9]) - -_ndims{T,N}(::AbstractArray{T,N}) = N -_ndims(x) = 1 - -if testfull - let B = copy(reshape(1:13^3, 13, 13, 13)) - for o3 in oindex, o2 in oindex, o1 in oindex - if (o3 isa Colon && (_ndims(o1) + _ndims(o2) != 2)) - continue # TODO: remove once Colon no longer spans partial trailing dimensions - end - viewB = view(B, o1, o2, o3) - runviews(viewB, index5, index25, index125) - end - end -end - -if !testfull - let B = copy(reshape(1:13^3, 13, 13, 13)) - for oind in ((:,:,:), - (:,:,6), - (:,6,:), - (6,:,:), - (:,3:7,:), - (3:7,:,:), - (3:7,6,:), - (3:7,6,0x6), - (6,UInt(3):UInt(7),3:7), - (13:-2:1,:,:), - ([8,4,6,12,5,7],:,3:7), - (6,CartesianIndex.(6,[8,4,6,12,5,7])), - (CartesianIndex(13,6),[8,4,6,12,5,7]), - (1,:,view(1:13,[9,12,4,13,1])), - (view(1:13,[9,12,4,13,1]),2:6,4), - ([1:5 2:6 3:7 4:8 5:9], :, 3)) - runsubarraytests(B, oind...) - viewB = view(B, oind...) - runviews(viewB, index5, index25, index125) - end - end -end - -# issue #11289 -x11289 = randn(5,5) -@test isempty(view(x11289, Int[], :)) -@test isempty(view(x11289, [2,5], Int[])) -@test isempty(view(x11289, Int[], 2)) - -####### "Classical" tests ####### - -# Tests where non-trailing dimensions are preserved -A = copy(reshape(1:120, 3, 5, 8)) -sA = view(A, 2:2, 1:5, :) -@test strides(sA) == (1, 3, 15) -@test parent(sA) == A -@test parentindexes(sA) == (2:2, 1:5, Base.Slice(1:8)) -@test Base.parentdims(sA) == [1:3;] -@test size(sA) == (1, 5, 8) -@test indices(sA) === (Base.OneTo(1), Base.OneTo(5), Base.OneTo(8)) -@test sA[1, 2, 1:8][:] == [5:15:120;] -sA[2:5:end] = -1 -@test all(sA[2:5:end] .== -1) -@test all(A[5:15:120] .== -1) -@test strides(sA) == (1,3,15) -@test stride(sA,3) == 15 -@test stride(sA,4) == 120 -test_bounds(sA) -sA = view(A, 1:3, 1:5, 5) -@test Base.parentdims(sA) == [1:2;] -sA[1:3,1:5] = -2 -@test all(A[:,:,5] .== -2) -sA[:] = -3 -@test all(A[:,:,5] .== -3) -@test strides(sA) == (1,3) -test_bounds(sA) -sA = view(A, 1:3, 3:3, 2:5) -@test Base.parentdims(sA) == [1:3;] -@test size(sA) == (3,1,4) -@test indices(sA) === (Base.OneTo(3), Base.OneTo(1), Base.OneTo(4)) -@test sA == A[1:3,3:3,2:5] -@test sA[:] == A[1:3,3,2:5][:] -test_bounds(sA) -sA = view(A, 1:2:3, 1:3:5, 1:2:8) -@test Base.parentdims(sA) == [1:3;] -@test strides(sA) == (2,9,30) -@test sA[:] == A[1:2:3, 1:3:5, 1:2:8][:] -# issue #8807 -@test view(view([1:5;], 1:5), 1:5) == [1:5;] -# Test with mixed types -@test sA[:, Int16[1,2], big(2)] == [31 40; 33 42] -test_bounds(sA) -sA = view(A, 1:1, 1:5, [1 3; 4 2]) -@test ndims(sA) == 4 -@test indices(sA) === (Base.OneTo(1), Base.OneTo(5), Base.OneTo(2), Base.OneTo(2)) -sA = view(A, 1:2, 3, [1 3; 4 2]) -@test ndims(sA) == 3 -@test indices(sA) === (Base.OneTo(2), Base.OneTo(2), Base.OneTo(2)) - -# logical indexing #4763 -A = view([1:10;], 5:8) -@test A[A.<7] == view(A, A.<7) == [5, 6] -@test Base.unsafe_getindex(A, A.<7) == [5, 6] -B = reshape(1:16, 4, 4) -sB = view(B, 2:3, 2:3) -@test sB[sB.>8] == view(sB, sB.>8) == [10, 11] -@test Base.unsafe_getindex(sB, sB.>8) == [10, 11] - -# Tests where dimensions are dropped -A = copy(reshape(1:120, 3, 5, 8)) -sA = view(A, 2, :, 1:8) -@test parent(sA) == A -@test parentindexes(sA) == (2, Base.Slice(1:5), 1:8) -@test Base.parentdims(sA) == [2:3;] -@test size(sA) == (5, 8) -@test indices(sA) === (Base.OneTo(5), Base.OneTo(8)) -@test strides(sA) == (3,15) -@test sA[2, 1:8][:] == [5:15:120;] -@test sA[:,1] == [2:3:14;] -@test sA[2:5:end] == [5:15:110;] -sA[2:5:end] = -1 -@test all(sA[2:5:end] .== -1) -@test all(A[5:15:120] .== -1) -test_bounds(sA) -sA = view(A, 1:3, 1:5, 5) -@test Base.parentdims(sA) == [1:2;] -@test size(sA) == (3,5) -@test indices(sA) === (Base.OneTo(3),Base.OneTo(5)) -@test strides(sA) == (1,3) -test_bounds(sA) -sA = view(A, 1:2:3, 3, 1:2:8) -@test Base.parentdims(sA) == [1,3] -@test size(sA) == (2,4) -@test indices(sA) === (Base.OneTo(2), Base.OneTo(4)) -@test strides(sA) == (2,30) -@test sA[:] == A[sA.indexes...][:] -test_bounds(sA) - -a = [5:8;] -@test parent(a) == a -@test parentindexes(a) == (1:4,) - -# issue #6218 - logical indexing -A = rand(2, 2, 3) -msk = ones(Bool, 2, 2) -msk[2,1] = false -sA = view(A, :, :, 1) -sA[msk] = 1.0 -@test sA[msk] == ones(countnz(msk)) - -# bounds checking upon construction; see #4044, #10296 -@test_throws BoundsError view(1:10, 8:11) -A = reshape(1:20, 5, 4) -sA = view(A, 1:2, 1:3) -@test_throws BoundsError view(sA, 1:3, 1:3) -@test_throws BoundsError view(sA, 1:2, 1:4) -view(sA, 1:2, 1:2) -@test_throws BoundsError view(A, 17:23) -view(A, 17:20) - -# Linear indexing by one multidimensional array: -A = reshape(1:120, 3, 5, 8) -sA = view(A, :, :, :) -@test sA[[72 17; 107 117]] == [72 17; 107 117] -@test sA[[99 38 119 14 76 81]] == [99 38 119 14 76 81] -@test sA[[ones(Int, 2, 2, 2); 2ones(Int, 2, 2, 2)]] == [ones(Int, 2, 2, 2); 2ones(Int, 2, 2, 2)] -sA = view(A, 1:2, 2:3, 3:4) -@test sA[(1:8)'] == [34 35 37 38 49 50 52 53] -@test sA[[1 2 4 4; 6 1 1 4]] == [34 35 38 38; 50 34 34 38] - -# issue #11871 -let a = ones(Float64, (2,2)), - b = view(a, 1:2, 1:2) - b[2] = 2 - @test b[2] === 2.0 -end - -# issue #15138 -let a = [1,2,3], - b = view(a, UInt(1):UInt(2)) - @test b == view(a, UInt(1):UInt(2)) == view(view(a, :), UInt(1):UInt(2)) == [1,2] -end - -let A = reshape(1:4, 2, 2) - B = view(A, :, :) - @test parent(B) === A - @test parent(view(B, 0x1, :)) === parent(view(B, 0x1, :)) === A -end - -# issue #15168 -let A = rand(10), sA = view(copy(A), :) - @test sA[Int16(1)] === sA[Int32(1)] === sA[Int64(1)] === A[1] - permute!(sA, collect(Int16, 1:10)) - @test A == sA -end - -# the following segfaults with LLVM 3.8 on Windows, ref #15417 -@test collect(view(view(reshape(1:13^3, 13, 13, 13), 3:7, 6:6, :), 1:2:5, :, 1:2:5)) == - cat(3,[68,70,72],[406,408,410],[744,746,748]) - -# tests @view (and replace_ref_end!) -X = reshape(1:24,2,3,4) -Y = 4:-1:1 - -@test isa(@view(X[1:3]), SubArray) - -@test X[1:end] == @.(@view X[1:end]) # test compatibility of @. and @view -@test X[1:end-3] == @view X[1:end-3] -@test X[1:end,2,2] == @view X[1:end,2,2] -# @test X[1,1:end-2] == @view X[1,1:end-2] # TODO: Re-enable after partial linear indexing deprecation -@test X[1,2,1:end-2] == @view X[1,2,1:end-2] -@test X[1,2,Y[2:end]] == @view X[1,2,Y[2:end]] -@test X[1:end,2,Y[2:end]] == @view X[1:end,2,Y[2:end]] - -u = (1,2:3) -@test X[u...,2:end] == @view X[u...,2:end] -@test X[(1,)...,(2,)...,2:end] == @view X[(1,)...,(2,)...,2:end] - -# test macro hygiene -let size=(x,y)-> error("should not happen"), Base=nothing - @test X[1:end,2,2] == @view X[1:end,2,2] -end - -# test that side effects occur only once -let foo = [X] - @test X[2:end-1] == @view (push!(foo,X)[1])[2:end-1] - @test foo == [X, X] -end - -# test @views macro -@views let f!(x) = x[1:end-1] .+= x[2:end].^2 - x = [1,2,3,4] - f!(x) - @test x == [5,11,19,4] - @test x[1:3] isa SubArray - @test x[2] === 11 - @test Dict((1:3) => 4)[1:3] === 4 - x[1:2] = 0 - @test x == [0,0,19,4] - x[1:2] .= 5:6 - @test x == [5,6,19,4] - f!(x[3:end]) - @test x == [5,6,35,4] - x[Y[2:3]] .= 7:8 - @test x == [5,8,7,4] - @. x[(3,)..., ()...] += 3 # @. should convert to .+=, test compatibility with @views - @test x == [5,8,10,4] - i = Int[] - # test that lhs expressions in update operations are evaluated only once: - x[push!(i,4)[1]] += 5 - @test x == [5,8,10,9] && i == [4] - x[push!(i,3)[end]] += 2 - @test x == [5,8,12,9] && i == [4,3] - @. x[3:end] = 0 # make sure @. works with end expressions in @views - @test x == [5,8,0,0] -end -@views @test isa(X[1:3], SubArray) -@test X[1:end] == @views X[1:end] -@test X[1:end-3] == @views X[1:end-3] -@test X[1:end,2,2] == @views X[1:end,2,2] -# @test X[1,1:end-2] == @views X[1,1:end-2] # TODO: Re-enable after partial linear indexing deprecation -@test X[1,2,1:end-2] == @views X[1,2,1:end-2] -@test X[1,2,Y[2:end]] == @views X[1,2,Y[2:end]] -@test X[1:end,2,Y[2:end]] == @views X[1:end,2,Y[2:end]] -@test X[u...,2:end] == @views X[u...,2:end] -@test X[(1,)...,(2,)...,2:end] == @views X[(1,)...,(2,)...,2:end] -# test macro hygiene -let size=(x,y)-> error("should not happen"), Base=nothing - @test X[1:end,2,2] == @views X[1:end,2,2] -end - -# issue #18034 -# ensure that it is possible to create an isbits, IndexLinear view of an immutable Array -let - struct ImmutableTestArray{T, N} <: Base.DenseArray{T, N} - end - Base.size(::Union{ImmutableTestArray, Type{ImmutableTestArray}}) = (0, 0) - Base.IndexStyle(::Union{ImmutableTestArray, Type{ImmutableTestArray}}) = Base.IndexLinear() - a = ImmutableTestArray{Float64, 2}() - @test Base.IndexStyle(view(a, :, :)) == Base.IndexLinear() - @test isbits(view(a, :, :)) -end - -# Issue #17351 -let - x = rand(10) - u = rand(10, 3) - su = view(u, :, 1) - @test size(@inferred(xcorr(x, su))) == (19,) -end diff --git a/julia-0.6.3/share/julia/test/subtype.jl b/julia-0.6.3/share/julia/test/subtype.jl deleted file mode 100644 index 2756241..0000000 --- a/julia-0.6.3/share/julia/test/subtype.jl +++ /dev/null @@ -1,1181 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -using Base.Bottom -using Base.Test - -macro UnionAll(var, expr) - Expr(:where, esc(expr), esc(var)) -end - -const issub = issubtype -issub_strict(x::ANY,y::ANY) = issub(x,y) && !issub(y,x) -isequal_type(x::ANY,y::ANY) = issub(x,y) && issub(y,x) -notequal_type(x::ANY,y::ANY) = !isequal_type(x, y) - -_type_intersect(x::ANY, y::ANY) = ccall(:jl_intersect_types, Any, (Any, Any), x, y) - -intersection_env(x::ANY, y::ANY) = ccall(:jl_env_from_type_intersection, Any, (Any,Any), x, y) - -# level 1: no varags, union, UnionAll -function test_1() - @test issub_strict(Int, Integer) - @test issub_strict(Array{Int,1}, AbstractArray{Int,1}) - - @test isequal_type(Int, Int) - @test isequal_type(Integer, Integer) - @test isequal_type(Array{Int,1}, Array{Int,1}) - @test isequal_type(AbstractArray{Int,1}, AbstractArray{Int,1}) - - @test issub_strict(Tuple{Int,Int}, Tuple{Integer,Integer}) - @test issub_strict(Tuple{Array{Int,1}}, Tuple{AbstractArray{Int,1}}) - - @test isequal_type(Tuple{Integer,Integer}, Tuple{Integer,Integer}) - - @test !issub(Tuple{Int,Int}, Tuple{Int}) - @test !issub(Tuple{Int}, Tuple{Integer,Integer}) - - @test !issub(Array{Int,1}, Array{Integer,1}) -end - -# level 2: varargs -function test_2() - @test issub_strict(Tuple{Int,Int}, Tuple{Vararg{Int}}) - @test issub_strict(Tuple{Int,Int}, Tuple{Int,Vararg{Int}}) - @test issub_strict(Tuple{Int,Int}, Tuple{Int,Vararg{Integer}}) - @test issub_strict(Tuple{Int,Int}, Tuple{Int,Int,Vararg{Integer}}) - @test issub_strict(Tuple{Int,Vararg{Int}}, Tuple{Vararg{Int}}) - @test issub_strict(Tuple{Int,Int,Int}, Tuple{Vararg{Int}}) - @test issub_strict(Tuple{Int,Int,Int}, Tuple{Integer,Vararg{Int}}) - @test issub_strict(Tuple{Int}, Tuple{Any}) - @test issub_strict(Tuple{}, Tuple{Vararg{Any}}) - - @test isequal_type(Tuple{Int}, Tuple{Int}) - @test isequal_type(Tuple{Vararg{Integer}}, Tuple{Vararg{Integer}}) - - @test !issub(Tuple{}, Tuple{Int, Vararg{Int}}) - @test !issub(Tuple{Int}, Tuple{Int, Int, Vararg{Int}}) - - @test !issub(Tuple{Int, Tuple{Real, Integer}}, Tuple{Vararg{Int}}) - - @test isequal_type(Tuple{Int,Int}, Tuple{Vararg{Int,2}}) - - @test Tuple{Int,Vararg{Int,2}} == Tuple{Int,Int,Int} - @test Tuple{Int,Vararg{Int,2}} === Tuple{Int,Int,Int} - @test Tuple{Any, Any} === Tuple{Vararg{Any,2}} - @test Tuple{Int,Vararg{Int,2}} == Tuple{Int,Int,Vararg{Int,1}} - @test Tuple{Int,Vararg{Int,2}} == Tuple{Int,Int,Int,Vararg{Int,0}} - @test !(Tuple{Int,Vararg{Int,2}} <: Tuple{Int,Int,Int,Vararg{Int,1}}) - @test Tuple{Int,Vararg{Int}} == Tuple{Int,Vararg{Int}} - @test (@UnionAll N Tuple{Int,Vararg{Int,N}}) == (@UnionAll N Tuple{Int,Vararg{Int,N}}) - - @test issub_strict(Tuple{Tuple{Int,Int},Tuple{Int,Int}}, Tuple{NTuple{N,Int},NTuple{N,Int}} where N) - @test !issub(Tuple{Tuple{Int,Int},Tuple{Int,}}, Tuple{NTuple{N,Int},NTuple{N,Int}} where N) - @test NTuple{0} === Tuple{} - - @test issub_strict(Tuple{Int,Int}, Tuple{Int,Int,Vararg{Int,N}} where N) - @test issub_strict(Tuple{Int,Int}, Tuple{E,E,Vararg{E,N}} where E where N) - - @test issub(Type{Tuple{VecElement{Bool}}}, (Type{Tuple{Vararg{VecElement{T},N}}} where T where N)) - - @test isequal_type(Type{Tuple{Vararg{Int,N}} where N}, Type{Tuple{Vararg{Int,N} where N}}) - @test Type{Tuple{Vararg{Int,N}} where N} !== Type{Tuple{Vararg{Int,N} where N}} -end - -function test_diagonal() - @test !issub(Tuple{Integer,Integer}, @UnionAll T Tuple{T,T}) - @test issub(Tuple{Integer,Int}, (@UnionAll T @UnionAll S<:T Tuple{T,S})) - @test issub(Tuple{Integer,Int}, (@UnionAll T @UnionAll T<:S<:T Tuple{T,S})) - @test !issub(Tuple{Integer,Int,Int}, (@UnionAll T @UnionAll T<:S<:T Tuple{T,S,S})) - - @test issub_strict((@UnionAll R Tuple{R,R}), - (@UnionAll T @UnionAll S Tuple{T,S})) - @test issub_strict((@UnionAll R Tuple{R,R}), - (@UnionAll T @UnionAll S<:T Tuple{T,S})) - @test issub_strict((@UnionAll R Tuple{R,R}), - (@UnionAll T @UnionAll T<:S<:T Tuple{T,S})) - @test issub_strict((@UnionAll R Tuple{R,R}), - (@UnionAll T @UnionAll S>:T Tuple{T,S})) - - @test !issub(Tuple{Real,Real}, @UnionAll T<:Real Tuple{T,T}) - - @test issub((@UnionAll S<:Int (@UnionAll R<:AbstractString Tuple{S,R,Vector{Any}})), - (@UnionAll T Tuple{T, T, Array{T,1}})) - - @test issub_strict(Tuple{String, Real, Ref{Number}}, - (@UnionAll T Tuple{Union{T,String}, T, Ref{T}})) - - @test issub_strict(Tuple{String, Real}, - (@UnionAll T Tuple{Union{T,String}, T})) - - @test !issub( Tuple{Real, Real}, - (@UnionAll T Tuple{Union{T,String}, T})) - - @test issub_strict(Tuple{Int, Int}, - (@UnionAll T Tuple{Union{T,String}, T})) - - # don't consider a diagonal variable concrete if it already has an abstract lower bound - @test isequal_type(Tuple{Vararg{A}} where A>:Integer, - Tuple{Vararg{A}} where A>:Integer) -end - -# level 3: UnionAll -function test_3() - @test issub_strict(Array{Int,1}, @UnionAll T Vector{T}) - @test issub_strict((@UnionAll T Pair{T,T}), Pair) - @test issub(Pair{Int,Int8}, Pair) - @test issub(Pair{Int,Int8}, (@UnionAll S Pair{Int,S})) - - @test !issub((@UnionAll T<:Real T), (@UnionAll T<:Integer T)) - - @test isequal_type((@UnionAll T Tuple{T,T}), (@UnionAll R Tuple{R,R})) - - @test !issub((@UnionAll T<:Integer @UnionAll S<:Number Tuple{T,S}), - (@UnionAll T<:Integer @UnionAll S<:Number Tuple{S,T})) - - @test issub_strict((@UnionAll T Tuple{Array{T},Array{T}}), - Tuple{Array, Array}) - - AUA = Array{(@UnionAll T Array{T,1}), 1} - UAA = (@UnionAll T Array{Array{T,1}, 1}) - - @test !issub(AUA, UAA) - @test !issub(UAA, AUA) - @test !isequal_type(AUA, UAA) - - @test issub_strict((@UnionAll T Int), (@UnionAll T<:Integer Integer)) - - @test isequal_type((@UnionAll T @UnionAll S Tuple{T, Tuple{S}}), - (@UnionAll T Tuple{T, @UnionAll S Tuple{S}})) - - @test !issub((@UnionAll T Pair{T,T}), Pair{Int,Int8}) - @test !issub((@UnionAll T Pair{T,T}), Pair{Int,Int}) - - @test isequal_type((@UnionAll T Tuple{T}), Tuple{Any}) - @test isequal_type((@UnionAll T<:Real Tuple{T}), Tuple{Real}) - - @test issub(Tuple{Array{Integer,1}, Int}, - @UnionAll T<:Integer @UnionAll S<:T Tuple{Array{T,1},S}) - - @test !issub(Tuple{Array{Integer,1}, Real}, - @UnionAll T<:Integer Tuple{Array{T,1},T}) - - @test !issub(Tuple{Int,String,Vector{Integer}}, - @UnionAll T Tuple{T, T, Array{T,1}}) - @test !issub(Tuple{String,Int,Vector{Integer}}, - @UnionAll T Tuple{T, T, Array{T,1}}) - @test !issub(Tuple{Int,String,Vector{Tuple{Integer}}}, - @UnionAll T Tuple{T,T,Array{Tuple{T},1}}) - - @test issub(Tuple{Int,String,Vector{Any}}, - @UnionAll T Tuple{T, T, Array{T,1}}) - - @test isequal_type(Array{Int,1}, Array{(@UnionAll T<:Int T), 1}) - @test isequal_type(Array{Tuple{Any},1}, Array{(@UnionAll T Tuple{T}), 1}) - - @test isequal_type(Array{Tuple{Int,Int},1}, - Array{(@UnionAll T<:Int Tuple{T,T}), 1}) - @test !issub(Array{Tuple{Int,Integer},1}, - Array{(@UnionAll T<:Integer Tuple{T,T}), 1}) - - @test !issub(Pair{Int,Int8}, (@UnionAll T Pair{T,T})) - - @test !issub(Tuple{Array{Int,1}, Integer}, - @UnionAll T<:Integer Tuple{Array{T,1},T}) - - @test !issub(Tuple{Integer, Array{Int,1}}, - @UnionAll T<:Integer Tuple{T, Array{T,1}}) - - @test !issub(Pair{Array{Int,1},Integer}, @UnionAll T Pair{Array{T,1},T}) - @test issub(Pair{Array{Int,1},Int}, @UnionAll T Pair{Array{T,1},T}) - - @test issub(Tuple{Integer,Int}, @UnionAll T<:Integer @UnionAll S<:T Tuple{T,S}) - @test !issub(Tuple{Integer,Int}, @UnionAll T<:Int @UnionAll S<:T Tuple{T,S}) - @test !issub(Tuple{Integer,Int}, @UnionAll T<:String @UnionAll S<:T Tuple{T,S}) - - @test issub(Tuple{Float32,Array{Float32,1}}, - @UnionAll T<:Real @UnionAll S<:AbstractArray{T,1} Tuple{T,S}) - - @test !issub(Tuple{Float32,Array{Float64,1}}, - @UnionAll T<:Real @UnionAll S<:AbstractArray{T,1} Tuple{T,S}) - - @test issub(Tuple{Float32,Array{Real,1}}, - @UnionAll T<:Real @UnionAll S<:AbstractArray{T,1} Tuple{T,S}) - - @test !issub(Tuple{Number,Array{Real,1}}, - @UnionAll T<:Real @UnionAll S<:AbstractArray{T,1} Tuple{T,S}) - - @test issub((@UnionAll Int<:T<:Integer T), @UnionAll T<:Real T) - @test issub((@UnionAll Int<:T<:Integer Array{T,1}), - (@UnionAll T<:Real Array{T,1})) - - @test issub((@UnionAll Int<:T<:Integer T), (@UnionAll Integer<:T<:Real T)) - @test !issub((@UnionAll Int<:T<:Integer Array{T,1}), (@UnionAll Integer<:T<:Real Array{T,1})) - - X = (@UnionAll T<:Real @UnionAll S<:AbstractArray{T,1} Tuple{T,S}) - Y = (@UnionAll A<:Real @UnionAll B<:AbstractArray{A,1} Tuple{A,B}) - @test isequal_type(X,Y) - Z = (@UnionAll A<:Real @UnionAll B<:AbstractArray{A,1} Tuple{Real,B}) - @test issub_strict(X,Z) - - @test issub_strict((@UnionAll T @UnionAll S<:T Pair{T,S}), - (@UnionAll T @UnionAll S Pair{T,S})) - @test issub_strict((@UnionAll T @UnionAll S>:T Pair{T,S}), - (@UnionAll T @UnionAll S Pair{T,S})) - - # these would be correct if the diagonal rule applied to type vars occurring - # only once in covariant position. - #@test issub_strict((@UnionAll T Tuple{Ref{T}, T}), - # (@UnionAll T @UnionAll S<:T Tuple{Ref{T},S})) - #@test issub_strict((@UnionAll T Tuple{Ref{T}, T}), - # (@UnionAll T @UnionAll S<:T @UnionAll R<:S Tuple{Ref{T},R})) - - @test isequal_type((@UnionAll T Tuple{Ref{T}, T}), - (@UnionAll T @UnionAll T<:S<:T Tuple{Ref{T},S})) - @test issub_strict((@UnionAll T Tuple{Ref{T}, T}), - (@UnionAll T @UnionAll S>:T Tuple{Ref{T}, S})) - - A = @UnionAll T Tuple{T,Ptr{T}} - B = @UnionAll T Tuple{Ptr{T},T} - - C = @UnionAll T>:Ptr @UnionAll S>:Ptr Tuple{Ptr{T},Ptr{S}} - D = @UnionAll T>:Ptr @UnionAll S>:Ptr{T} Tuple{Ptr{T},Ptr{S}} - E = @UnionAll T>:Ptr @UnionAll S>:Ptr{T} Tuple{Ptr{S},Ptr{T}} - - @test !issub(A, B) - @test !issub(B, A) - @test issub_strict(C, A) - @test issub_strict(C, B) - @test issub_strict(C, D) - @test issub_strict(Union{D,E}, A) - @test issub_strict(Union{D,E}, B) - @test issub_strict((@UnionAll T>:Ptr @UnionAll Ptr<:S<:Ptr Tuple{Ptr{T},Ptr{S}}), - (@UnionAll T>:Ptr @UnionAll S>:Ptr{T} Tuple{Ptr{T},Ptr{S}})) - @test !issub((@UnionAll T>:Ptr @UnionAll S>:Ptr Tuple{Ptr{T},Ptr{S}}), - (@UnionAll T>:Ptr @UnionAll Ptr{T}<:S<:Ptr Tuple{Ptr{T},Ptr{S}})) - - @test !issub((@UnionAll T>:Integer @UnionAll S>:Ptr Tuple{Ptr{T},Ptr{S}}), B) - - @test issub((@UnionAll T>:Ptr @UnionAll S>:Integer Tuple{Ptr{T},Ptr{S}}), B) -end - -# level 4: Union -function test_4() - @test isequal_type(Union{Bottom,Bottom}, Bottom) - - @test issub_strict(Int, Union{Int,String}) - @test issub_strict(Union{Int,Int8}, Integer) - - @test isequal_type(Union{Int,Int8}, Union{Int,Int8}) - - @test isequal_type(Union{Int,Integer}, Integer) - - @test isequal_type(Tuple{Union{Int,Int8},Int16}, Union{Tuple{Int,Int16},Tuple{Int8,Int16}}) - - @test issub_strict(Tuple{Int,Int8,Int}, Tuple{Vararg{Union{Int,Int8}}}) - @test issub_strict(Tuple{Int,Int8,Int}, Tuple{Vararg{Union{Int,Int8,Int16}}}) - - # nested unions - @test !issub(Union{Int,Ref{Union{Int,Int8}}}, Union{Int,Ref{Union{Int8,Int16}}}) - - A = Int64; B = Int8 - C = Int16; D = Int32 - @test issub(Union{Union{A,Union{A,Union{B,C}}}, Union{D,Bottom}}, - Union{Union{A,B},Union{C,Union{B,D}}}) - @test !issub(Union{Union{A,Union{A,Union{B,C}}}, Union{D,Bottom}}, - Union{Union{A,B},Union{C,Union{B,A}}}) - - @test isequal_type(Union{Union{A,B,C}, Union{D}}, Union{A,B,C,D}) - @test isequal_type(Union{Union{A,B,C}, Union{D}}, Union{A,Union{B,C},D}) - @test isequal_type(Union{Union{Union{Union{A}},B,C}, Union{D}}, - Union{A,Union{B,C},D}) - - @test issub_strict(Union{Union{A,C}, Union{D}}, Union{A,B,C,D}) - - @test !issub(Union{Union{A,B,C}, Union{D}}, Union{A,C,D}) - - # obviously these unions can be simplified, but when they aren't there's trouble - X = Union{Union{A,B,C},Union{A,B,C},Union{A,B,C},Union{A,B,C}, - Union{A,B,C},Union{A,B,C},Union{A,B,C},Union{A,B,C}} - Y = Union{Union{D,B,C},Union{D,B,C},Union{D,B,C},Union{D,B,C}, - Union{D,B,C},Union{D,B,C},Union{D,B,C},Union{A,B,C}} - @test issub_strict(X,Y) -end - -# level 5: union and UnionAll -function test_5() - u = Union{Int8,Int} - - @test issub(Tuple{String,Array{Int,1}}, - (@UnionAll T Union{Tuple{T,Array{T,1}}, Tuple{T,Array{Int,1}}})) - - @test issub(Tuple{Union{Vector{Int},Vector{Int8}}}, - @UnionAll T Tuple{Array{T,1}}) - - @test !issub(Tuple{Union{Vector{Int},Vector{Int8}},Vector{Int}}, - @UnionAll T Tuple{Array{T,1}, Array{T,1}}) - - @test !issub(Tuple{Union{Vector{Int},Vector{Int8}},Vector{Int8}}, - @UnionAll T Tuple{Array{T,1}, Array{T,1}}) - - @test !issub(Vector{Int}, @UnionAll T>:u Array{T,1}) - @test issub(Vector{Integer}, @UnionAll T>:u Array{T,1}) - @test issub(Vector{Union{Int,Int8}}, @UnionAll T>:u Array{T,1}) - - @test issub((@UnionAll Int<:T<:u Array{T,1}), (@UnionAll Int<:T<:u Array{T,1})) - - # with varargs - @test !issub(Array{Tuple{Array{Int},Array{Vector{Int16}},Array{Vector{Int}},Array{Int}}}, - @UnionAll T<:(@UnionAll S Tuple{Vararg{Union{Array{S}, Array{Array{S,1}}}}}) Array{T}) - - @test issub(Array{Tuple{Array{Int},Array{Vector{Int}},Array{Vector{Int}},Array{Int}}}, - @UnionAll T<:(@UnionAll S Tuple{Vararg{Union{Array{S}, Array{Array{S,1}}}}}) Array{T}) - - @test !issub(Tuple{Array{Int},Array{Vector{Int16}},Array{Vector{Int}},Array{Int}}, - @UnionAll S Tuple{Vararg{Union{Array{S},Array{Array{S,1}}}}}) - - @test issub(Tuple{Array{Int},Array{Vector{Int}},Array{Vector{Int}},Array{Int}}, - @UnionAll S Tuple{Vararg{Union{Array{S},Array{Array{S,1}}}}}) - - B = @UnionAll S<:u Tuple{S, Tuple{Any,Any,Any}, Ref{S}} - # these tests require renaming in issub_unionall - @test issub((@UnionAll T<:B Tuple{Int8, T, Ref{Int8}}), B) - @test !issub((@UnionAll T<:B Tuple{Int8, T, Ref{T}}), B) - - # the `convert(Type{T},T)` pattern, where T is a Union - # required changing priority of unions and vars - @test issub(Tuple{Array{u,1},Int}, @UnionAll T Tuple{Array{T,1}, T}) - @test issub(Tuple{Array{u,1},Int}, @UnionAll T @UnionAll S<:T Tuple{Array{T,1}, S}) - - @test !issub(Ref{Union{Ref{Int},Ref{Int8}}}, @UnionAll T Ref{Ref{T}}) - @test issub(Tuple{Union{Ref{Int},Ref{Int8}}}, @UnionAll T Tuple{Ref{T}}) - @test !issub(Ref{Union{Ref{Int},Ref{Int8}}}, Union{Ref{Ref{Int}}, Ref{Ref{Int8}}}) - - @test isequal_type(Ref{Tuple{Union{Int,Int8},Int16}}, Ref{Union{Tuple{Int,Int16},Tuple{Int8,Int16}}}) - @test isequal_type(Ref{T} where T<:Tuple{Union{Int,Int8},Int16}, - Ref{T} where T<:Union{Tuple{Int,Int16},Tuple{Int8,Int16}}) - - @test isequal_type(Ref{Tuple{Union{Int,Int8},Int16,T}} where T, - Ref{Union{Tuple{Int,Int16,S},Tuple{Int8,Int16,S}}} where S) -end - -# tricky type variable lower bounds -function test_6() - @test issub((@UnionAll S<:Int (@UnionAll R<:String Tuple{S,R,Vector{Any}})), - (@UnionAll T Tuple{T, T, Array{T,1}})) - - @test !issub((@UnionAll S<:Int (@UnionAll R<:String Tuple{S,R,Vector{Integer}})), - (@UnionAll T Tuple{T, T, Array{T,1}})) - - t = @UnionAll T Tuple{T,T,Ref{T}} - @test isequal_type(t, @UnionAll S Tuple{S,S,Ref{S}}) - - @test !issub((@UnionAll T Tuple{T,String,Ref{T}}), (@UnionAll T Tuple{T,T,Ref{T}})) - - @test !issub((@UnionAll T Tuple{T,Ref{T},String}), (@UnionAll T Tuple{T,Ref{T},T})) - - i = Int; ai = Integer - @test isequal_type((@UnionAll i<:T<:i Ref{T}), Ref{i}) - @test isequal_type((@UnionAll ai<:T<:ai Ref{T}), Ref{ai}) - - # Pair{T,S} <: Pair{T,T} can be true with certain bounds - @test issub_strict((@UnionAll i<:T<:i @UnionAll i<:S<:i Pair{T,S}), - @UnionAll T Pair{T,T}) - - @test issub_strict(Tuple{i, Ref{i}}, - (@UnionAll T @UnionAll S<:T Tuple{S,Ref{T}})) - - @test !issub(Tuple{Real, Ref{i}}, - (@UnionAll T @UnionAll S<:T Tuple{S,Ref{T}})) - - # S >: T - @test issub_strict(Tuple{Real, Ref{i}}, - (@UnionAll T @UnionAll S>:T Tuple{S,Ref{T}})) - - @test !issub(Tuple{Ref{i}, Ref{ai}}, - (@UnionAll T @UnionAll S>:T Tuple{Ref{S},Ref{T}})) - - @test issub_strict(Tuple{Ref{Real}, Ref{ai}}, - (@UnionAll T @UnionAll S>:T Tuple{Ref{S},Ref{T}})) - - @test issub_strict(Tuple{Real, Ref{Tuple{i}}}, - (@UnionAll T @UnionAll S>:T Tuple{S,Ref{Tuple{T}}})) - - @test !issub(Tuple{Ref{Tuple{i}}, Ref{Tuple{ai}}}, - (@UnionAll T @UnionAll S>:T Tuple{Ref{Tuple{S}},Ref{Tuple{T}}})) - - @test issub_strict(Tuple{Ref{Tuple{Real}}, Ref{Tuple{ai}}}, - (@UnionAll T @UnionAll S>:T Tuple{Ref{Tuple{S}},Ref{Tuple{T}}})) - - # (@UnionAll x<:T<:x Q{T}) == Q{x} - @test isequal_type(Ref{Ref{i}}, Ref{@UnionAll i<:T<:i Ref{T}}) - @test isequal_type(Ref{Ref{i}}, @UnionAll i<:T<:i Ref{Ref{T}}) - @test isequal_type((@UnionAll i<:T<:i Ref{Ref{T}}), Ref{@UnionAll i<:T<:i Ref{T}}) - @test !issub((@UnionAll i<:T<:i Ref{Ref{T}}), Ref{@UnionAll T<:i Ref{T}}) - - u = Union{Int8,Int64} - A = Ref{Bottom} - B = @UnionAll S<:u Ref{S} - @test issub(Ref{B}, @UnionAll A<:T<:B Ref{T}) - - C = @UnionAll S<:u S - @test issub(Ref{C}, @UnionAll u<:T<:u Ref{T}) - - BB = @UnionAll S<:Bottom S - @test issub(Ref{B}, @UnionAll BB<:U<:B Ref{U}) -end - -# uncategorized -function test_7() - @test isequal_type(Ref{Union{Int16, T}} where T, Ref{Union{Int16, S}} where S) - @test isequal_type(Pair{Union{Int16, T}, T} where T, Pair{Union{Int16, S}, S} where S) -end - -function test_Type() - @test issub_strict(DataType, Type) - @test issub_strict(Union, Type) - @test issub_strict(UnionAll, Type) - @test issub_strict(typeof(Bottom), Type) - @test !issub(TypeVar, Type) - @test !issub(Type, TypeVar) - @test !issub(DataType, @UnionAll T<:Number Type{T}) - @test issub_strict(Type{Int}, DataType) - @test !issub((@UnionAll T<:Integer Type{T}), DataType) - @test isequal_type(Type{AbstractArray}, Type{AbstractArray}) - @test !issub(Type{Int}, Type{Integer}) - @test issub((@UnionAll T<:Integer Type{T}), (@UnionAll T<:Number Type{T})) - @test isa(Int, @UnionAll T<:Number Type{T}) - @test !isa(DataType, @UnionAll T<:Number Type{T}) - - @test !(DataType <: (@UnionAll T<:Type Type{T})) - @test isa(DataType, (@UnionAll T<:Type Type{T})) - - @test isa(Tuple{},Type{Tuple{}}) - @test !(Tuple{Int,} <: (@UnionAll T<:Tuple Type{T})) - @test isa(Tuple{Int}, (@UnionAll T<:Tuple Type{T})) - - # this matches with T==DataType, since DataType is concrete - @test issub(Tuple{Type{Int},Type{Int8}}, Tuple{T,T} where T) - @test !issub(Tuple{Type{Int},Type{Union{}}}, Tuple{T,T} where T) - - # issue #20476 - @test issub(Tuple{Type{Union{Type{UInt32}, Type{UInt64}}}, Type{UInt32}}, Tuple{Type{T},T} where T) - - @test isequal_type(Core.TypeofBottom, Type{Union{}}) - @test issub(Core.TypeofBottom, Type{T} where T<:Real) -end - -# old subtyping tests from test/core.jl -function test_old() - @test Int8 <: Integer - @test Int32 <: Integer - @test Tuple{Int8,Int8} <: Tuple{Integer,Integer} - @test !(AbstractArray{Float64,2} <: AbstractArray{Number,2}) - @test !(AbstractArray{Float64,1} <: AbstractArray{Float64,2}) - @test Tuple{Integer,Vararg{Integer}} <: Tuple{Integer,Vararg{Real}} - @test Tuple{Integer,Float64,Vararg{Integer}} <: Tuple{Integer,Vararg{Number}} - @test Tuple{Integer,Float64} <: Tuple{Integer,Vararg{Number}} - @test Tuple{Int32,} <: Tuple{Vararg{Number}} - @test Tuple{} <: Tuple{Vararg{Number}} - @test !(Tuple{Vararg{Int32}} <: Tuple{Int32,}) - @test !(Tuple{Vararg{Int32}} <: Tuple{Number,Integer}) - @test !(Tuple{Vararg{Integer}} <: Tuple{Integer,Integer,Vararg{Integer}}) - @test !(Array{Int8,1} <: Array{Any,1}) - @test !(Array{Any,1} <: Array{Int8,1}) - @test Array{Int8,1} <: Array{Int8,1} - @test !(Type{Bottom} <: Type{Int32}) - @test !(Vector{Float64} <: Vector{Union{Float64,Float32}}) - - @test !isa(Array,Type{Any}) - @test Type{Complex} <: UnionAll - @test isa(Complex,Type{Complex}) - @test !(Type{Ptr{Bottom}} <: Type{Ptr}) - @test !(Type{Rational{Int}} <: Type{Rational}) - @test Tuple{} <: Tuple{Vararg} - @test Tuple{Int,Int} <: Tuple{Vararg} - @test Tuple{} <: @UnionAll N NTuple{N} - @test !(Type{Tuple{}} <: Type{Tuple{Vararg}}) - @test Type{Tuple{}} <: (@UnionAll N Type{NTuple{N}}) - - @test !(Type{Array{Integer}} <: Type{AbstractArray{Integer}}) - @test !(Type{Array{Integer}} <: Type{@UnionAll T<:Integer Array{T}}) - - # issue #6561 - # TODO: note that NTuple now means "tuples of all the same type" - #@test issubtype(Array{Tuple}, Array{NTuple}) - @test issub_strict(NTuple, Tuple) - @test issub_strict(NTuple, Tuple{Vararg}) - @test isequal_type(Tuple, Tuple{Vararg}) - #@test issubtype(Array{Tuple{Vararg{Any}}}, Array{NTuple}) - #@test issubtype(Array{Tuple{Vararg}}, Array{NTuple}) - @test !issubtype(Type{Tuple{Void}}, Tuple{Type{Void}}) -end - -const menagerie = - Any[Bottom, Any, Int, Int8, Integer, Real, - Array{Int,1}, AbstractArray{Int,1}, - Tuple{Int,Vararg{Integer}}, Tuple{Integer,Vararg{Int}}, Tuple{}, - Union{Int,Int8}, - (@UnionAll T Array{T,1}), - (@UnionAll T Pair{T,T}), - (@UnionAll T @UnionAll S Pair{T,S}), - Pair{Int,Int8}, - (@UnionAll S Pair{Int,S}), - (@UnionAll T Tuple{T,T}), - (@UnionAll T<:Integer Tuple{T,T}), - (@UnionAll T @UnionAll S Tuple{T,S}), - (@UnionAll T<:Integer @UnionAll S<:Number Tuple{T,S}), - (@UnionAll T<:Integer @UnionAll S<:Number Tuple{S,T}), - Array{(@UnionAll T Array{T,1}),1}, - (@UnionAll T Array{Array{T,1},1}), - Array{(@UnionAll T<:Int T), 1}, - (@UnionAll T<:Real @UnionAll S<:AbstractArray{T,1} Tuple{T,S}), - Union{Int,Ref{Union{Int,Int8}}}, - (@UnionAll T Union{Tuple{T,Array{T,1}}, Tuple{T,Array{Int,1}}}), - ] - -let new = Any[] - # add variants of each type - for T in menagerie - push!(new, Ref{T}) - push!(new, Tuple{T}) - push!(new, Tuple{T,T}) - push!(new, Tuple{Vararg{T}}) - push!(new, @UnionAll S<:T S) - push!(new, @UnionAll S<:T Ref{S}) - end - append!(menagerie, new) -end - -function test_properties() - x→y = !x || y - ¬T = @UnionAll X>:T Ref{X} - - for T in menagerie - # top and bottom identities - @test issub(Bottom, T) - @test issub(T, Any) - @test issub(T, Bottom) → isequal_type(T, Bottom) - @test issub(Any, T) → isequal_type(T, Any) - - # unionall identity - @test isequal_type(T, @UnionAll S<:T S) - @test isequal_type(Ref{T}, @UnionAll T<:U<:T Ref{U}) - - # equality under renaming - if isa(T, UnionAll) - lb, ub = T.var.lb, T.var.ub - @test isequal_type(T, (@UnionAll lb<:Y<:ub T{Y})) - end - - # inequality under wrapping - @test !isequal_type(T, Ref{T}) - - for S in menagerie - issubTS = issub(T, S) - # transitivity - if issubTS - for R in menagerie - if issub(S, R) - @test issub(T, R) # issub(T,S) ∧ issub(S,R) → issub(T,R) - @test issub(Ref{S}, @UnionAll T<:U<:R Ref{U}) - end - end - end - - # union subsumption - @test isequal_type(T, Union{T,S}) → issub(S, T) - - # invariance - @test isequal_type(T, S) == isequal_type(Ref{T}, Ref{S}) - - # covariance - @test issubTS == issub(Tuple{T}, Tuple{S}) - @test issubTS == issub(Tuple{Vararg{T}}, Tuple{Vararg{S}}) - @test issubTS == issub(Tuple{T}, Tuple{Vararg{S}}) - - # pseudo-contravariance - @test issubTS == issub(¬S, ¬T) - end - end -end - -macro testintersect(a, b, result) - if isa(result, Expr) && result.head === :call && length(result.args) == 2 && result.args[1] === :! - result = result.args[2] - cmp = :(!=) - else - cmp = :(==) - end - cmp = esc(cmp) - a = esc(a) - b = esc(b) - result = esc(result) - Base.remove_linenums!(quote - # test real intersect - @test $cmp(_type_intersect($a, $b), $result) - @test $cmp(_type_intersect($b, $a), $result) - # test simplified intersect - if !($result === Union{}) - @test typeintersect($a, $b) != Union{} - @test typeintersect($b, $a) != Union{} - end - end) -end - -abstract type IT4805_2{N, T} end -abstract type AbstractThing{T,N} end -mutable struct ConcreteThing{T<:AbstractFloat,N} <: AbstractThing{T,N} -end -mutable struct A11136 end -mutable struct B11136 end -abstract type Foo11367 end - -abstract type AbstractTriangular{T,S<:AbstractMatrix} <: AbstractMatrix{T} end -struct UpperTriangular{T,S<:AbstractMatrix} <: AbstractTriangular{T,S} end -struct UnitUpperTriangular{T,S<:AbstractMatrix} <: AbstractTriangular{T,S} end - -struct SIQ20671{T<:Number,m,kg,s,A,K,mol,cd,rad,sr} <: Number - val::T -end - -function test_intersection() - @testintersect(Vector{Float64}, Vector{Union{Float64,Float32}}, Bottom) - - @testintersect(Array{Bottom}, (@UnionAll T AbstractArray{T}), !Bottom) - - @testintersect(Tuple{Type{Ptr{UInt8}}, Ptr{Bottom}}, - (@UnionAll T Tuple{Type{Ptr{T}},Ptr{T}}), Bottom) - - @testintersect(Tuple{Range{Int},Tuple{Int,Int}}, (@UnionAll T Tuple{AbstractArray{T},Dims}), - Tuple{Range{Int},Tuple{Int,Int}}) - - @testintersect((@UnionAll Integer<:T<:Number Array{T}), (@UnionAll T<:Number Array{T}), - (@UnionAll Integer<:T<:Number Array{T})) - - @testintersect((@UnionAll Integer<:T<:Number Array{T}), (@UnionAll T<:Real Array{T}), - (@UnionAll Integer<:T<:Real Array{T})) - - @testintersect((@UnionAll Integer<:T<:Number Array{T}), (@UnionAll T<:String Array{T}), - Bottom) - - @testintersect((@UnionAll Integer<:T<:Number Array{T}), (@UnionAll String<:T<:AbstractString Array{T}), - Bottom) - - @testintersect((@UnionAll T<:Number Array{T}), (@UnionAll T<:String Array{T}), - Array{Bottom}) - - @testintersect((@UnionAll T Tuple{T, AbstractArray{T}}), Tuple{Number, Array{Int,1}}, - Tuple{Int, Array{Int,1}}) - - @testintersect((@UnionAll T Tuple{T, AbstractArray{T}}), Tuple{Int, Array{Number,1}}, - Tuple{Int, Array{Number,1}}) - - @testintersect((@UnionAll S Tuple{S,Vector{S}}), (@UnionAll T<:Real Tuple{T,AbstractVector{T}}), - (@UnionAll S<:Real Tuple{S,Vector{S}})) - - # typevar corresponding to a type it will end up being neither greater than nor - # less than - @testintersect((@UnionAll T Tuple{T, Ref{T}}), Tuple{Array{Int}, Ref{AbstractVector}}, - Tuple{Array{Int,1}, Ref{AbstractVector}}) - - @testintersect((@UnionAll T Tuple{T, AbstractArray{T}}), Tuple{Any, Array{Number,1}}, - Tuple{Number, Array{Number,1}}) - @testintersect((@UnionAll T Tuple{Array{T}, Array{T}}), Tuple{Array, Array{Any}}, !Bottom) - - @testintersect((@UnionAll T Tuple{T,T}), Tuple{Real, Real}, (@UnionAll T<:Real Tuple{T,T})) - @testintersect((@UnionAll T Tuple{T}), Tuple{Real}, Tuple{Real}) - @testintersect((@UnionAll T Tuple{T,T}), Tuple{Union{Float64,Int64},Int64}, Tuple{Int64,Int64}) - @testintersect((@UnionAll T Tuple{T,T}), Tuple{Int64,Union{Float64,Int64}}, Tuple{Int64,Int64}) - @testintersect((@UnionAll Z Tuple{Z,Z}), (@UnionAll T<:Integer @UnionAll S<:Number Tuple{T,S}), - @UnionAll Z<:Integer Tuple{Z,Z}) - @testintersect((@UnionAll Z Pair{Z,Z}), (@UnionAll T<:Integer @UnionAll S<:Number Pair{T,S}), - @UnionAll Z<:Integer Pair{Z,Z}) - - @testintersect((@UnionAll T<:Vector Type{T}), (@UnionAll N Type{@UnionAll S<:Number Array{S,N}}), - Type{@UnionAll S<:Number Array{S,1}}) - - @testintersect((@UnionAll T Tuple{Type{Array{T,1}},Array{T,1}}), - Tuple{Type{AbstractVector},Vector{Int}}, Bottom) - - @testintersect(Tuple{Type{Vector{Complex128}}, AbstractVector}, - (@UnionAll T @UnionAll S @UnionAll N Tuple{Type{Array{T,N}}, Array{S,N}}), - Tuple{Type{Vector{Complex128}},Vector}) - - @testintersect(Tuple{Type{Vector{Complex128}}, AbstractArray}, - (@UnionAll T @UnionAll S @UnionAll N Tuple{Type{Array{T,N}}, Array{S,N}}), - Tuple{Type{Vector{Complex128}},Vector}) - - @testintersect(Type{Array}, Type{AbstractArray}, Bottom) - - @testintersect(Type{Tuple{Bool,Vararg{Int}}}, Type{@UnionAll T Tuple{Vararg{T}}}, Bottom) - @testintersect(Type{Tuple{Bool,Vararg{Int}}}, Type{@UnionAll T Tuple{T,Vararg{T}}}, Bottom) - @testintersect((@UnionAll T Tuple{Vararg{T}}), Tuple{Float64,Int}, Bottom) - - @testintersect((@UnionAll T Tuple{Rational{T},T}), Tuple{Rational{Integer},Int}, Tuple{Rational{Integer},Int}) - - @testintersect((@UnionAll T Pair{T,Ptr{T}}), (@UnionAll S Pair{Ptr{S},S}), Bottom) - @testintersect((@UnionAll T Tuple{T,Ptr{T}}), (@UnionAll S Tuple{Ptr{S},S}), - Union{(@UnionAll T>:Ptr @UnionAll S>:Ptr{T} Tuple{Ptr{T},Ptr{S}}), - (@UnionAll T>:Ptr @UnionAll S>:Ptr{T} Tuple{Ptr{S},Ptr{T}})}) - - @testintersect((@UnionAll N Tuple{NTuple{N,Integer},NTuple{N,Integer}}), - Tuple{Tuple{Integer,Integer}, Tuple{Vararg{Integer}}}, - Tuple{Tuple{Integer,Integer}, Tuple{Integer,Integer}}) - @testintersect((@UnionAll N Tuple{NTuple{N,Integer},NTuple{N,Integer}}), - Tuple{Tuple{Vararg{Integer}}, Tuple{Integer,Integer}}, - Tuple{Tuple{Integer,Integer}, Tuple{Integer,Integer}}) - - #@test isequal_type(typeintersect((@UnionAll N Tuple{NTuple{N,Any},Array{Int,N}}), - # Tuple{Tuple{Int,Vararg{Int}},Array}), - # Tuple{Tuple{Int,Vararg{Int}},Array{Int,N}}) - - @testintersect((@UnionAll N Tuple{NTuple{N,Any},Array{Int,N}}), - Tuple{Tuple{Int,Vararg{Int}},Array{Int,2}}, - Tuple{Tuple{Int,Int}, Array{Int,2}}) - @testintersect(Type{Any},Type{Complex}, Bottom) - @testintersect(Type{Any},(@UnionAll T<:Real Type{T}), Bottom) - - @testintersect(Type{Function},Union,Bottom) - @testintersect(Type{Int32}, DataType, Type{Int32}) - - @testintersect(DataType, Type, !Bottom) - @testintersect(Union, Type, !Bottom) - @testintersect(DataType, Type{Int}, !Bottom) - @testintersect(DataType, (@UnionAll T<:Int Type{T}), !Bottom) - @testintersect(DataType, (@UnionAll T<:Integer Type{T}), !Bottom) - @testintersect(Tuple{Vararg{Int}}, Tuple{Vararg{Bool}}, Tuple{}) - @testintersect(Type{Tuple{Vararg{Int}}}, Type{Tuple{Vararg{Bool}}}, Bottom) - @testintersect(Tuple{Bool,Vararg{Int}}, Tuple{Vararg{Bool}}, Tuple{Bool}) - - let M = @UnionAll T<:Union{Float32,Float64} Matrix{T} - @testintersect(AbstractArray, M, M) - end - - @testintersect((@UnionAll N Tuple{Array{Int,N},Vararg{Int,N}}), Tuple{Vector{Int},Real,Real,Real}, Bottom) - - @testintersect((@UnionAll N Tuple{Array{Int,N},Vararg{Int,N}}), Tuple{Array{Int,0}}, Tuple{Array{Int,0}}) - @testintersect((@UnionAll N Tuple{Array{Int,N},Vararg{Int,N}}), Tuple{Array{Int,2}}, Bottom) - - @testintersect(Tuple{Int,Vararg{Int}}, Tuple{Int,Int,Int,Vararg{Float64}}, Tuple{Int,Int,Int}) - @testintersect(Tuple{Int,Vararg{Int}}, Tuple{Int,Vararg{Float64}}, Tuple{Int}) - @testintersect((@UnionAll N Tuple{Array{Int,N},Vararg{Int,N}}), - Tuple{Matrix{Int},Int,Int,Vararg{Float64}}, - Tuple{Matrix{Int},Int,Int}) - @testintersect((@UnionAll N Tuple{Array{Int,N},Vararg{Int,N}}), - Tuple{Matrix{Int},Int,Vararg{Float64}}, Bottom) - - @testintersect(Tuple{Array{Any,1}, Tuple{Int64, Int64, Vararg{Int64, N} where N}}, - Tuple{Array{T,N}, Tuple{Vararg{Int64,N}}} where N where T, - Bottom) - - @testintersect((@UnionAll T<:Union{Float64,Array{Float64,1}} T), Real, Float64) - - # issue #4805 - @testintersect((@UnionAll T<:Int Type{IT4805_2{1,T}}), - (@UnionAll S<:(@UnionAll N IT4805_2{N,Int}) Type{S}), - !Bottom) - - # issue #8851 - @testintersect((@UnionAll T AbstractThing{T,2}), - ConcreteThing, - (@UnionAll T<:AbstractFloat ConcreteThing{T,2})) - - # issue #11136 and #11367 - @testintersect((@UnionAll T Tuple{T, T}), (@UnionAll TB<:B11136 Tuple{A11136, TB}), Bottom) - @testintersect((@UnionAll T Tuple{T, T}), (@UnionAll T2<:Foo11367 Tuple{Type{BigInt}, T2}), Bottom) - - # PR #12058 - @testintersect((@UnionAll N NTuple{N,Int}), (@UnionAll N NTuple{N,Float64}), Tuple{}) - - @testintersect((@UnionAll T Tuple{Type{T},T}), Tuple{Type{Type{Float64}},Type{Int}}, Bottom) - - @testintersect((@UnionAll T T), Type{Int8}, Type{Int8}) - # issue #14482 - @testintersect((@UnionAll T Tuple{T}), Tuple{Type{Int8}}, Tuple{Type{Int8}}) - - @testintersect((@UnionAll T Tuple{Union{Int,T}, Union{Vector{T},Vector{String}}}), - Tuple{Integer, Vector{Int8}}, - Tuple{Union{Int,Int8}, Vector{Int8}}) - @testintersect((@UnionAll T Tuple{Union{Int,T}, Union{Vector{T},Vector{String}}}), - Tuple{Int8, Vector{String}}, - Tuple{Int8, Vector{String}}) - @testintersect((@UnionAll T Tuple{Union{Int,T}, Union{Vector{T},Vector{String}}}), - Tuple{Int, Vector{Int8}}, - Tuple{Int, Vector{Int8}}) - @testintersect(( Tuple{Union{Int,String}, Union{Ref{Int}, Ref{String}}}), - (@UnionAll T Tuple{T, Union{Ref{T}, Ref{String}}}), - Union{Tuple{Int, Union{Ref{Int},Ref{String}}}, - Tuple{String, Ref{String}}}) - - @testintersect((@UnionAll Z<:(@UnionAll T @UnionAll S Tuple{T,S}) Ref{Z}), - (@UnionAll X<:(@UnionAll T Tuple{T,T}) Ref{X}), - (@UnionAll X<:(@UnionAll T Tuple{T,T}) Ref{X})) - @testintersect(Ref{@UnionAll T @UnionAll S Tuple{T,S}}, - Ref{@UnionAll T Tuple{T,T}}, Bottom) - - @testintersect(Tuple{T,T} where T<:Union{UpperTriangular, UnitUpperTriangular}, - Tuple{AbstractArray{T,N}, AbstractArray{T,N}} where N where T, - Union{Tuple{T,T} where T<:UpperTriangular, - Tuple{T,T} where T<:UnitUpperTriangular}) - - @testintersect(DataType, Type, DataType) - @testintersect(DataType, Type{T} where T<:Integer, Type{T} where T<:Integer) - @testintersect(Union{DataType,Int}, Type, DataType) - @testintersect(Union{DataType,Int}, Type{T} where T, DataType) - # test typeintersect wrapper as well as _type_intersect - @test typeintersect(Union{DataType,Int}, Type) === DataType - @test typeintersect(Union{DataType,Int}, Type{T} where T) === DataType - - # since TypeofBottom is a singleton we can deduce its intersection with Type{...} - @testintersect(Core.TypeofBottom, (Type{T} where T<:Tuple), Type{Union{}}) - - @testintersect((Type{Tuple{Vararg{T}}} where T), Type{Tuple}, Bottom) - @testintersect(Tuple{Type{S}, Tuple{Any, Vararg{Any}}} where S<:Tuple{Any, Vararg{Any}}, - Tuple{Type{T}, T} where T, - Tuple{Type{S},S} where S<:Tuple{Any,Vararg{Any,N} where N}) - - # part of issue #20450 - @testintersect(Tuple{Array{Ref{T}, 1}, Array{Pair{M, V}, 1}} where V where T where M, - Tuple{Array{Ref{T}, 1}, Array{Pair{M, T}, 1}, SS} where T where M where SS, - Union{}) - - @testintersect(Tuple{Array{Ref{T}, 1}, Array{Pair{M, V}, 1}, Int} where V where T where M, - Tuple{Array{Ref{T}, 1}, Array{Pair{M, T}, 1}, Any} where T where M, - Tuple{Array{Ref{T}, 1}, Array{Pair{M, T}, 1}, Int} where T where M) - - @testintersect(Tuple{Int, Ref{Pair{K,V}}} where V where K, - Tuple{Any, Ref{Pair{T,T}} where T }, - Tuple{Int, Ref{Pair{T,T}} where T }) - - @test_broken isequal_type(_type_intersect(Tuple{T,T} where T, - Union{Tuple{S,Array{Int64,1}},Tuple{S,Array{S,1}}} where S), - Union{Tuple{Vector{Int64},Vector{Int64}}, - Tuple{Vector{T},Vector{T}} where T>:Vector}) - - # part of issue #20344 - @testintersect(Tuple{Type{Tuple{Vararg{T, N} where N}}, Tuple} where T, - Tuple{Type{Tuple{Vararg{T, N}}} where N where T, Any}, - Bottom) - @testintersect(Type{NTuple{N,UnitRange}} where N, - Type{Tuple{Vararg{UnitRange}}}, - Bottom) - - @testintersect(Type{NTuple{Z,UnitRange}} where Z, - Type{NTuple{Z,String}} where Z, - Type{Tuple{}}) - - # first union component sets N==0, but for the second N is unknown - _, E = intersection_env(Tuple{Tuple{Vararg{Int}}, Any}, - Tuple{Union{Base.DimsInteger{N},Base.Indices{N}}, Int} where N) - @test length(E)==1 && isa(E[1],TypeVar) - - @testintersect(Tuple{Dict{Int,Int}, Ref{Pair{K,V}}} where V where K, - Tuple{Associative{Int,Int}, Ref{Pair{T,T}} where T}, - Tuple{Dict{Int,Int}, Ref{Pair{K,K}}} where K) - - # issue #20643 - @testintersect(Tuple{Ref{Pair{p2,T2}}, Pair{p1,Pair}} where T2 where p2 where p1, - Tuple{Ref{Pair{p3,T3}}, Pair{p3}} where T3 where p3, - Tuple{Ref{Pair{p1,T2}}, Pair{p1,Pair}} where T2 where p1) - - # issue #20998 - _, E = intersection_env(Tuple{Int,Any,Any}, Tuple{T,T,S} where {T,S}) - @test length(E) == 2 && E[1] == Int && isa(E[2], TypeVar) - _, E = intersection_env(Tuple{Dict{Int,Type}, Type, Any}, - Tuple{Dict{K,V}, Any, Int} where {K,V}) - @test E[2] == Type - - # issue #20611 - I, E = intersection_env(Tuple{Ref{Integer},Int,Any}, Tuple{Ref{Z},Z,Z} where Z) - @test isequal_type(I, Tuple{Ref{Integer},Int,Integer}) - @test E[1] == Integer - - # issue #21118 - A = Tuple{Ref, Vararg{Any}} - B = Tuple{Vararg{Union{Z,Ref,Void}}} where Z<:Union{Ref,Void} - @test B <: _type_intersect(A, B) - # TODO: this would be a better version of that test: - #let T = _type_intersect(A, B) - # @test T <: A - # @test T <: B - # @test Tuple{Ref, Vararg{Union{Ref,Void}}} <: T - #end - @testintersect(Tuple{Int,Any,Vararg{A}} where A>:Integer, - Tuple{Any,Int,Vararg{A}} where A>:Integer, - Tuple{Int,Int,Vararg{A}} where A>:Integer) - - # issue #21132 - @testintersect(Pair{L,Tuple{L,Pair{L,HL}}} where {L,HL}, - Pair{R,Tuple{Pair{R,HR},R}} where {R,HR}, - Bottom) # X == Pair{X,...} is not satisfiable - - # issue #20671 --- this just took too long - @testintersect(Tuple{Type{SIQ20671{T, mT, kgT, sT, AT, KT, molT, cdT, radT, srT}}, - SIQ20671{S, mS, kgS, sS, AS, KS, molS, cdS, radS, srS}} where {T, mT, kgT, sT, AT, KT, molT, cdT, radT, srT, - S, mS, kgS, sS, AS, KS, molS, cdS, radS, srS}, - Tuple{Type{T}, T} where T, - Tuple{Type{SIQ20671{T,mS,kgS,sS,AS,KS,molS,cdS,radS,srS}}, - SIQ20671{T,mS,kgS,sS,AS,KS,molS,cdS,radS,srS}} where {T,mS,kgS,sS,AS,KS,molS,cdS,radS,srS}) - - # issue #21243 - @testintersect(Tuple{Ref{Ref{T}} where T, Ref}, - Tuple{Ref{T}, Ref{T}} where T, - Tuple{Ref{Ref{T}}, Ref{Ref{T}}} where T) -end - -function test_intersection_properties() - for T in menagerie - for S in menagerie - I = _type_intersect(T,S) - I2 = _type_intersect(S,T) - @test isequal_type(I, I2) - @test issub(I, T) && issub(I, S) - if issub(T, S) - @test isequal_type(I, T) - end - end - end -end - -test_1() -test_2() -test_diagonal() -test_3() -test_4() -test_5() -test_6() -test_7() -test_Type() -test_old() -test_intersection() -test_properties() -test_intersection_properties() - - -# issue #20121 -@test NTuple{170,Matrix{Int}} <: (Tuple{Vararg{Union{Array{T,1},Array{T,2},Array{T,3}}}} where T) - -# Issue #12580 -abstract type AbstractMyType12580{T} end -struct MyType12580{T}<:AbstractMyType12580{T} end -tpara{A<:AbstractMyType12580}(::Type{A}) = tpara(supertype(A)) -tpara{I}(::Type{AbstractMyType12580{I}}) = I -@test tpara(MyType12580{true}) - -# Issue #18348 -f18348{T<:Any}(::Type{T}, x) = 1 -f18348{T<:Any}(::Type{T}, x::T) = 2 -@test length(methods(f18348, Tuple{Type{Any},Any})) == 1 - -# Issue #13165 -@test Symmetric{Float64,Matrix{Float64}} <: LinAlg.RealHermSymComplexHerm -@test Hermitian{Float64,Matrix{Float64}} <: LinAlg.RealHermSymComplexHerm -@test Hermitian{Complex{Float64},Matrix{Complex{Float64}}} <: LinAlg.RealHermSymComplexHerm - -# Issue #12721 -f12721{T<:Type{Int}}(::T) = true -@test_throws MethodError f12721(Float64) - -# implicit "covariant" type parameters: -mutable struct TwoParams{S,T}; x::S; y::T; end -@test TwoParams{<:Real,<:Number} == (TwoParams{S,T} where S<:Real where T<:Number) == - (TwoParams{S,<:Number} where S<:Real) == (TwoParams{<:Real,T} where T<:Number) -@test TwoParams(3,0im) isa TwoParams{<:Real,<:Number} -@test TwoParams(3,"foo") isa TwoParams{<:Real} -@test !(TwoParams(3im,0im) isa TwoParams{<:Real,<:Number}) -@test !(TwoParams(3,"foo") isa TwoParams{<:Real,<:Number}) -ftwoparams(::TwoParams) = 1 -ftwoparams(::TwoParams{<:Real}) = 2 -ftwoparams(::TwoParams{<:Real,<:Real}) = 3 -@test ftwoparams(TwoParams('x',3)) == 1 -@test ftwoparams(TwoParams(3,'x')) == 2 -@test ftwoparams(TwoParams(3,4)) == 3 -@test !([TwoParams(3,4)] isa Vector{TwoParams{<:Real,<:Real}}) -@test TwoParams{<:Real,<:Real}[TwoParams(3,4)] isa Vector{TwoParams{<:Real,<:Real}} -@test [TwoParams(3,4)] isa Vector{<:TwoParams{<:Real,<:Real}} -@test [TwoParams(3,4)] isa (Vector{TwoParams{T,T}} where T<:Real) - -# implicit "contravariant" type parameters: -@test TwoParams{>:Int,<:Number} == (TwoParams{S,T} where S>:Int where T<:Number) == - (TwoParams{S,<:Number} where S>:Int) == (TwoParams{>:Int,T} where T<:Number) -@test TwoParams(3,0im) isa TwoParams{>:Int,<:Number} -@test TwoParams{Real,Complex}(3,0im) isa TwoParams{>:Int,<:Number} -@test !(TwoParams(3.0,0im) isa TwoParams{>:Int,<:Number}) -@test !(TwoParams(3,'x') isa TwoParams{>:Int,<:Number}) - -# supertype operator -@test !(Int >: Integer) -@test Integer >: Int - -# tolerate non-types in Tuples -@test typeintersect(Tuple{0}, Tuple{T} where T) === Tuple{0} - -# TypeVars deduced as non-type constants (#20869) -@testintersect(Tuple{Val{0}, Val{Val{N}}} where N, Tuple{Val{N}, Val{Val{N}}} where N, Tuple{Val{0},Val{Val{0}}}) -@testintersect(Tuple{Val{N}, Val{Val{0}}} where N, Tuple{Val{N}, Val{Val{N}}} where N, Tuple{Val{0},Val{Val{0}}}) - -@testintersect(Tuple{Val{Val{0}}, Val{N}} where N, Tuple{Val{Val{N}}, Val{N}} where N, Tuple{Val{Val{0}},Val{0}}) -@testintersect(Tuple{Val{Val{N}}, Val{0}} where N, Tuple{Val{Val{N}}, Val{N}} where N, Tuple{Val{Val{0}},Val{0}}) - -# a bunch of cases found by fuzzing -let a = Tuple{Float64,T7} where T7, - b = Tuple{S5,Tuple{S5}} where S5 - @test_broken typeintersect(a, b) <: b -end -let a = Tuple{T1,T1} where T1, - b = Tuple{Val{S2},S6} where S2 where S6 - @test_broken typeintersect(a, b) == typeintersect(b, a) -end -let a = Val{Tuple{T1,T1}} where T1, - b = Val{Tuple{Val{S2},S6}} where S2 where S6 - @testintersect(a, b, Val{Tuple{Val{T},Val{T}}} where T) -end -let a = Tuple{Float64,T3,T4} where T4 where T3, - b = Tuple{S2,Tuple{S3},S3} where S2 where S3 - @test_broken typeintersect(a, b) == typeintersect(b, a) -end -let a = Tuple{T1,Tuple{T1}} where T1, - b = Tuple{Float64,S3} where S3 - @test_broken typeintersect(a, b) <: a -end -let a = Tuple{5,T4,T5} where T4 where T5, - b = Tuple{S2,S3,Tuple{S3}} where S2 where S3 - @test_broken typeintersect(a, b) == typeintersect(b, a) -end -let a = Tuple{T2,Tuple{T4,T2}} where T4 where T2, - b = Tuple{Float64,Tuple{Tuple{S3},S3}} where S3 - @test_broken typeintersect(a, b) <: b -end -let a = Tuple{Tuple{T2,4},T6} where T2 where T6, - b = Tuple{Tuple{S2,S3},Tuple{S2}} where S2 where S3 - @test_broken typeintersect(a, b) == typeintersect(b, a) -end -let a = Tuple{T3,Int64,Tuple{T3}} where T3, - b = Tuple{S3,S3,S4} where S4 where S3 - @test_broken typeintersect(a, b) <: a -end -let a = Tuple{T1,Val{T2},T2} where T2 where T1, - b = Tuple{Float64,S1,S2} where S2 where S1 - @test_broken typeintersect(a, b) == typeintersect(b, a) -end -let a = Tuple{T1,Val{T2},T2} where T2 where T1, - b = Tuple{Float64,S1,S2} where S2 where S1 - @test_broken typeintersect(a, b) <: a -end -let a = Tuple{Float64,T1} where T1, - b = Tuple{S1,Tuple{S1}} where S1 - @test_broken typeintersect(a, b) <: b -end -let a = Tuple{Val{T1},T2,T2} where T2 where T1, - b = Tuple{Val{Tuple{S2}},S3,Float64} where S2 where S3 - @testintersect(a, b, Tuple{Val{Tuple{S2}},Float64,Float64} where S2) -end -let a = Tuple{T1,T2,T2} where T1 where T2, - b = Tuple{Val{S2},S2,Float64} where S2, - x = Tuple{Val{Float64},Float64,Float64} - @test_broken x <: typeintersect(a, b) -end -let a = Val{Tuple{T1,Val{T2},Val{Int64},Tuple{Tuple{T3,5,Float64},T4,T2,T5}}} where T1 where T5 where T4 where T3 where T2, - b = Val{Tuple{Tuple{S1,5,Float64},Val{S2},S3,Tuple{Tuple{Val{Float64},5,Float64},2,Float64,S4}}} where S2 where S3 where S1 where S4 - @test_skip typeintersect(b, a) -end - -# issue #20992 -abstract type A20992{T,D,d} end -abstract type B20992{SV,T,D,d} <: A20992{T,D,d} end -struct C20992{S,n,T,D,d} <: B20992{NTuple{n,S},T,D,d} -end -@testintersect(Tuple{A20992{R, D, d} where d where D, Int} where R, - Tuple{C20992{S, n, T, D, d} where d where D where T where n where S, Any}, - Tuple{C20992, Int}) - -# Issue #19414 -let ex = try struct A19414 <: Base.AbstractSet end catch e; e end - @test isa(ex, ErrorException) && ex.msg == "invalid subtyping in definition of A19414" -end - -# issue #20103, OP and comments -struct TT20103{X,Y} end -f20103{X,Y}(::Type{TT20103{X,Y}},x::X,y::Y) = 1 -f20103{X}(::Type{TT20103{X,X}},x::X) = 100 -@test_broken typeintersect(Type{NTuple{N,E}} where E where N, Type{NTuple{N,E} where N} where E) == Union{} # use @testintersect once fixed -let ints = (Int, Int32, UInt, UInt32) - const Ints = Union{ints...} - vecs = [] - for i = 2:4, t in ints - push!(vecs, NTuple{i, t}) - end - const Vecs = Union{vecs...} - T = Type{Tuple{V, I}} where V <: Vecs where I <: Ints - @testintersect(T, T, T) - test{V <: Vecs, I <: Ints}(a::Type{Tuple{V, I}}) = I - test{V <: Vecs, I <: Ints}(a::Type{Tuple{V, I}}) = I -end - -# issue #21191 -let T1 = Val{Val{Val{Union{Int8,Int16,Int32,Int64,UInt8,UInt16}}}}, - T2 = Val{Val{Val{Union{Int8,Int16,Int32,Int64,UInt8, S}}}} where S - @test T1 <: T2 -end - -# issue #21613 -abstract type A21613{S <: Tuple} end -struct B21613{S <: Tuple, L} <: A21613{S} - data::NTuple{L,Float64} -end -@testintersect(Tuple{Type{B21613{Tuple{L},L}} where L, Any}, - Tuple{Type{SA}, Tuple} where SA<:(A21613{S} where S<:Tuple), - Tuple{Type{B21613{Tuple{L},L}} where L, Tuple}) - -# issue #22239 -@testintersect(Val{Pair{T,T}} where T, - Val{Pair{Int,T}} where T, - Val{Pair{Int,Int}}) - -# issue #23024 -@testintersect(Tuple{DataType, Any}, - Tuple{Type{T}, Int} where T, - Tuple{DataType, Int}) - -# issue #23430 -@test [0 0.; 0 0.; 0 0.; 0 0.; 0 0.; 0 0.; 0 0.; 0 0.; 0 0.; 0 0.; 0 0.; 0 0.; - 0 0.; 0 0.; 0 0.; 0 0.; 0 0.; 0 0.; 0 0.; 0 0.; 0 0.; 0 0.; 0 0.; 0 0.; - 0 0.; 0 0.; 0 0.; 0 0.; 0 0.; 0 0.; 0 0.; 0 0.; 0 0.; 0 0.; 0 0.; 0 0.; - 0 0.; 0 0.; 0 0.; 0 0.; 0 0.; 0 0.; 0 0.; 0 0.; 0 0.; 0 0.; 0 0.; 0 0.; - 0 0.; 0 0.; 0 0.; 0 0.; 0 0.; 0 0.; 0 0.; 0 0.; 0 0.; 0 0.; 0 0.; 0 0.; - 0 0.; 0 0.; 0 0.; 0 0.] isa Matrix{Float64} -@test !(Tuple{Int64,Float64,Int64,Float64,Int64,Float64,Int64,Float64,Int64,Float64,Int64,Float64, - Int64,Float64,Int64,Float64,Int64,Float64,Int64,Float64,Int64,Float64,Int64,Float64, - Int64,Float64,Int64,Float64,Int64,Float64,Int64,Float64,Int64,Float64,Int64,Float64, - Int64,Float64,Int64,Float64,Int64,Float64,Int64,Float64,Int64,Float64,Int64,Float64, - Int64,Float64,Int64,Float64,Int64,Float64,Int64,Float64,Int64,Float64,Int64,Float64, - Int64,Float64,Int64,Float64,Int64,Float64,Int64,Float64,Int64,Float64,Int64,Float64, - Int64,Float64,Int64,Float64,Int64,Float64,Int64,Float64,Int64,Float64,Int64,Float64, - Int64,Float64,Int64,Float64,Int64,Float64,Int64,Float64,Int64,Float64,Int64,Float64, - Int64,Float64,Int64,Float64,Int64,Float64,Int64,Float64,Int64,Float64,Int64,Float64, - Int64,Float64,Int64,Float64,Int64,Float64,Int64,Float64,Int64,Float64,Int64,Float64, - Int64,Float64,Int64,Float64,Int64,Float64,Int64,Float64} <: (Tuple{Vararg{T}} where T<:Number)) - -# PR #24399 -let (t, e) = intersection_env(Tuple{Union{Int,Int8}}, Tuple{T} where T) - @test e[1] isa TypeVar -end - -# issue #24305 -f24305(x) = [g24305(x) g24305(x) g24305(x) g24305(x); g24305(x) g24305(x) 0 0]; -@test_throws UndefVarError f24305(1) - -f1_24305(x,y,z) = x*y-z^2-1 -f2_24305(x,y,z) = x*y*z+y^2-x^2-2 -f3_24305(x,y,z) = exp(x)+z-exp(y)-3 -Fun_24305(x) = [ f1_24305(x[1],x[2],x[3]); f2_24305(x[1],x[2],x[3]); f3_24305(x[1],x[2],x[3]) ] -Jac_24305(x) = [ x[2] x[1] -2*x[3] ; x[2]*x[3]-2x[1] x[1]*x[3]+2x[2] x[1]*x[2] ; exp(x[1]) -exp(x[2]) 1 ] - -x_24305 = ones(3) - -for it = 1:5 - h = - \(Jac_24305(x_24305), Fun_24305(x_24305)) - global x_24305 = x_24305 + h -end - -@test round.(x_24305, 2) == [1.78, 1.42, 1.24] diff --git a/julia-0.6.3/share/julia/test/sysinfo.jl b/julia-0.6.3/share/julia/test/sysinfo.jl deleted file mode 100644 index a34adf5..0000000 --- a/julia-0.6.3/share/julia/test/sysinfo.jl +++ /dev/null @@ -1,8 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -# We can't guarantee that these are correct, but we can at least check -# that they run -@test length(Base.Sys.cpu_info()) > 0 -sprint(Base.Sys.cpu_summary) -@test Base.Sys.uptime() > 0 -Base.Sys.loadavg() diff --git a/julia-0.6.3/share/julia/test/test.jl b/julia-0.6.3/share/julia/test/test.jl deleted file mode 100644 index 6b63c30..0000000 --- a/julia-0.6.3/share/julia/test/test.jl +++ /dev/null @@ -1,513 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -# Test @test -@test true -@test 1 == 1 -@test 1 != 2 -@test strip("\t hi \n") == "hi" -@test strip("\t this should fail \n") != "hi" - -# @test should only evaluate the arguments once -let g = Int[], f = (x) -> (push!(g, x); x) - @test f(1) == 1 - @test g == [1] -end - -# Test @test_broken with fail -@test_broken false -@test_broken 1 == 2 -@test_broken 1 != 1 -@test_broken strip("\t hi \n") != "hi" -@test_broken strip("\t this should fail \n") == "hi" -# Test @test_broken with errors -@test_broken error() -@test_broken absolute_nonsense - -#Test @test_skip -@test_skip error() -@test_skip true -@test_skip false -@test_skip gobbeldygook - -# Test @test_warn -@test 1234 === @test_nowarn(1234) -@test 5678 === @test_warn("WARNING: foo", begin warn("foo"); 5678; end) -let a - # Broken - # @test_throws UndefVarError a - # Replace with the previous line when #20016 is fixed - @test_throws UndefRefError a - @test_nowarn a = 1 - @test a === 1 -end - -a = Array{Float64,5}(2, 2, 2, 2, 2) -a[1,1,1,1,1] = 10 -@test a[1,1,1,1,1] == 10 -@test a[1,1,1,1,1] != 2 - -@test rand() != rand() - -# Pass - exception -@test contains(sprint(show, @test_throws ErrorException error()), - "Thrown: ErrorException") - -# Test printing of Fail results -mutable struct NoThrowTestSet <: Base.Test.AbstractTestSet - results::Vector - NoThrowTestSet(desc) = new([]) -end -Base.Test.record(ts::NoThrowTestSet, t::Base.Test.Result) = (push!(ts.results, t); t) -Base.Test.finish(ts::NoThrowTestSet) = ts.results -fails = @testset NoThrowTestSet begin - # Fail - wrong exception - @test_throws OverflowError error() - # Fail - no exception - @test_throws OverflowError 1 + 1 - # Fail - comparison - @test 1+1 == 2+2 - # Fail - approximate comparison - @test 1/1 ≈ 2/1 - # Fail - chained comparison - @test 1+0 == 2+0 == 3+0 - # Fail - comparison call - @test ==(1 - 2, 2 - 1) - # Error - unexpected pass - @test_broken true -end -for i in 1:length(fails) - 1 - @test isa(fails[i], Base.Test.Fail) -end - -str = sprint(show, fails[1]) -@test contains(str, "Expression: error()") -@test contains(str, "Thrown: ErrorException") - -str = sprint(show, fails[2]) -@test contains(str, "Expression: 1 + 1") -@test contains(str, "No exception thrown") - -str = sprint(show, fails[3]) -@test contains(str, "Expression: 1 + 1 == 2 + 2") -@test contains(str, "Evaluated: 2 == 4") - -str = sprint(show, fails[4]) -@test contains(str, "Expression: 1 / 1 ≈ 2 / 1") -@test contains(str, "Evaluated: 1.0 ≈ 2.0") - -str = sprint(show, fails[5]) -@test contains(str, "Expression: 1 + 0 == 2 + 0 == 3 + 0") -@test contains(str, "Evaluated: 1 == 2 == 3") - -str = sprint(show, fails[6]) -@test contains(str, "Expression: 1 - 2 == 2 - 1") -@test contains(str, "Evaluated: -1 == 1") - -str = sprint(show, fails[7]) -@test contains(str, "Unexpected Pass") -@test contains(str, "Expression: true") - -# Test printing of a TestSetException -tse_str = sprint(show, Test.TestSetException(1,2,3,4,Vector{Union{Base.Test.Error, Base.Test.Fail}}())) -@test contains(tse_str, "1 passed") -@test contains(tse_str, "2 failed") -@test contains(tse_str, "3 errored") -@test contains(tse_str, "4 broken") - -@test Test.finish(Test.FallbackTestSet()) !== nothing - -OLD_STDOUT = STDOUT -OLD_STDERR = STDERR -catch_out = IOStream("") -catch_err = IOStream("") -rde, wre = redirect_stderr() -rdo, wro = redirect_stdout() - -# test that FallbackTestSet will throw immediately -cmd = `$(Base.julia_cmd()) --startup-file=no --depwarn=error test_exec.jl` -@test !success(pipeline(cmd)) - -@testset "no errors" begin - @test true - @test 1 == 1 -end - -# Test entirely empty test set -@testset "outer" begin - @testset "inner" begin - end -end - -@testset "testset types" begin - ts = @testset "@testset should return the testset" begin - @test true - end - @test typeof(ts) == Base.Test.DefaultTestSet - @test ts.n_passed == 1 - tss = @testset "@testset/for should return an array of testsets: $i" for i in 1:3 - @test true - end - @test length(tss) == 3 - @test typeof(tss[1]) == Base.Test.DefaultTestSet - @test tss[1].n_passed == 1 -end -@testset "accounting" begin - local ts - try - ts = @testset "outer" begin - @testset "inner1" begin - @test true - @test false - @test 1 == 1 - @test 2 == :foo - @test 3 == 3 - @testset "d" begin - @test 4 == 4 - end - @testset begin - @test :blank != :notblank - end - end - @testset "inner1" begin - @test 1 == 1 - @test 2 == 2 - @test 3 == :bar - @test 4 == 4 - @test_throws ErrorException 1+1 - @test_throws ErrorException error() - @test_throws RemoteException error() - @testset "errrrr" begin - @test "not bool" - @test error() - end - - error("exceptions in testsets should be caught") - @test 1 == 1 # this test will not be run - end - - @testset "loop with desc" begin - @testset "loop1 $T" for T in (Float32, Float64) - @test 1 == T(1) - end - end - @testset "loops without desc" begin - @testset for T in (Float32, Float64) - @test 1 == T(1) - end - @testset for T in (Float32, Float64), S in (Int32,Int64) - @test S(1) == T(1) - end - end - srand(123) - @testset "some loops fail" begin - @testset for i in 1:5 - @test i <= rand(1:10) - end - # should add 3 errors and 3 passing tests - @testset for i in 1:6 - iseven(i) || error("error outside of test") - @test true # only gets run if the above passed - end - end - end - # These lines shouldn't be called - error("No exception was thrown!") - catch ex - redirect_stdout(OLD_STDOUT) - redirect_stderr(OLD_STDERR) - ex - end - @testset "ts results" begin - @test isa(ts, Test.DefaultTestSet) - passes, fails, errors, broken, c_passes, c_fails, c_errors, c_broken = Base.Test.get_test_counts(ts) - total_pass = passes + c_passes - total_fail = fails + c_fails - total_error = errors + c_errors - total_broken = broken + c_broken - @test total_pass == 24 - @test total_fail == 6 - @test total_error == 6 - @test total_broken == 0 - end - ts.anynonpass = false - deleteat!(Base.Test.get_testset().results,1) -end - -@test .1+.1+.1 ≈ .3 -@test .1+.1+.1 ≉ .4 - -ts = @testset "@testset should return the testset" begin - @test true -end -@test typeof(ts) == Base.Test.DefaultTestSet -@test ts.n_passed == 1 - -tss = @testset "@testset/for should return an array of testsets: $i" for i in 1:3 - @test true -end -@test length(tss) == 3 -@test typeof(tss[1]) == Base.Test.DefaultTestSet -@test tss[1].n_passed == 1 - -# Issue #17908 (return) -testset_depth17908 = Test.get_testset_depth() -@testset for i in 1:3 - i > 1 && return - @test i == 1 -end -# The return aborts the control flow so the expression above doesn't return a -# value. The only thing we can test is whether the testset is properly popped. -# Do not use `@test` since the issue this is testing will swallow the error. -@assert testset_depth17908 == Test.get_testset_depth() - -# Issue #17462 and Issue #17908 (break, continue) -testset_depth17462 = Test.get_testset_depth() -counter_17462_pre = 0 -counter_17462_post = 0 -tss17462 = @testset for x in [1,2,3,4] - counter_17462_pre += 1 - if x == 1 - @test counter_17462_pre == x - continue - @test false - elseif x == 3 - @test counter_17462_pre == x - break - @test false - elseif x == 4 - @test false - else - @test counter_17462_pre == x - @test x == 2 - @test counter_17462_post == 0 - end - counter_17462_post += 1 -end -# Do not use `@test` since the issue this is testing will swallow the error. -# Same for the `@assert` in the for loop below -@assert testset_depth17462 == Test.get_testset_depth() -@assert length(tss17462) == 3 -for ts17462 in tss17462 - @assert isa(ts17462, Base.Test.DefaultTestSet) -end -@test counter_17462_pre == 3 -@test counter_17462_post == 1 - -# Issue #21008 -ts = try - @testset "@test_broken and @test_skip should not give an exception" begin - @test_broken false - @test_skip true - @test_skip false - end -catch - nothing # Shouldn't get here -end -@test ts isa Base.Test.DefaultTestSet - -# now we're done running tests with DefaultTestSet so we can go back to STDOUT -redirect_stdout(OLD_STDOUT) -redirect_stderr(OLD_STDERR) - -# import the methods needed for defining our own testset type -import Base.Test: record, finish -using Base.Test: get_testset_depth, get_testset -using Base.Test: AbstractTestSet, Result, Pass, Fail, Error -struct CustomTestSet <: Base.Test.AbstractTestSet - description::AbstractString - foo::Int - results::Vector - # constructor takes a description string and options keyword arguments - CustomTestSet(desc; foo=1) = new(desc, foo, []) -end - -record(ts::CustomTestSet, child::AbstractTestSet) = push!(ts.results, child) -record(ts::CustomTestSet, res::Result) = push!(ts.results, res) -function finish(ts::CustomTestSet) - # just record if we're not the top-level parent - if get_testset_depth() > 0 - record(get_testset(), ts) - end - ts -end - -ts = @testset CustomTestSet "Testing custom testsets" begin - # this testset should inherit the parent testset type - @testset "custom testset inner 1" begin - @test true - @test false - @test error("this error will be reported as an error") - @test_throws ErrorException nothing - @test_throws ErrorException error("this error is a success") - end - # this testset has its own testset type - @testset CustomTestSet foo=4 "custom testset inner 2" begin - # this testset should inherit the type, but not the argument. If a particular - # testset type wants inheritance behavior they should implement it themselves - # using get_testset() in the constructor - @testset "custom testset inner 2 inner 1" begin - @test true - end - # make sure the RHS can use computed values, also tests options without - # specifying the testset type - @testset foo=(1+2) "custom testset inner 2 inner 2" begin - @test true - end - end -end - -@test typeof(ts) == CustomTestSet -@test ts.foo == 1 -@test ts.description == "Testing custom testsets" -@test typeof(ts.results[1]) == CustomTestSet -@test ts.results[1].description == "custom testset inner 1" -@test ts.results[1].foo == 1 -@test typeof(ts.results[1].results[1]) == Pass -@test typeof(ts.results[1].results[2]) == Fail -@test typeof(ts.results[1].results[3]) == Error -@test typeof(ts.results[1].results[4]) == Fail -@test typeof(ts.results[1].results[5]) == Pass - -@test typeof(ts.results[2]) == CustomTestSet -@test ts.results[2].description == "custom testset inner 2" -@test ts.results[2].foo == 4 -@test typeof(ts.results[2].results[1]) == CustomTestSet -@test ts.results[2].results[1].foo == 1 -@test typeof(ts.results[2].results[1].results[1]) == Pass -@test typeof(ts.results[2].results[2]) == CustomTestSet -@test ts.results[2].results[2].foo == 3 - -# test custom testset types on testset/for -tss = @testset CustomTestSet foo=3 "custom testset $i" for i in 1:6 - @testset "inner testset $i-$j" for j in 1:3 - @test iseven(i + j) - end - # make sure a testset within a testset/for works - @testset "inner testset $i" begin - @test iseven(i) - end -end - - -for i in 1:6 - @test typeof(tss[i]) == CustomTestSet - @test tss[i].foo == 3 - for j in 1:3 - @test typeof(tss[i].results[j]) == CustomTestSet - @test tss[i].results[j].foo == 1 - @test typeof(tss[i].results[j].results[1]) == (iseven(i+j) ? Pass : Fail) - end - @test typeof(tss[i].results[4]) == CustomTestSet - @test typeof(tss[i].results[4].results[1]) == (iseven(i) ? Pass : Fail) -end - -# test @inferred -function uninferrable_function(i) - q = [1, "1"] - return q[i] -end - -@test_throws ErrorException @inferred(uninferrable_function(1)) -@test @inferred(identity(1)) == 1 - -# Ensure @inferred only evaluates the arguments once -inferred_test_global = 0 -function inferred_test_function() - global inferred_test_global - inferred_test_global += 1 - true -end -@test @inferred inferred_test_function() -@test inferred_test_global == 1 - -# Test that @inferred works with A[i] expressions -@test @inferred((1:3)[2]) == 2 -struct SillyArray <: AbstractArray{Float64,1} end -Base.getindex(a::SillyArray, i) = rand() > 0.5 ? 0 : false -test_result = @test_throws ErrorException @inferred(SillyArray()[2]) -@test contains(test_result.value.msg, "Bool") - -# Issue #14928 -# Make sure abstract error type works. -@test_throws Exception error("") - -# Issue #17105 -# @inferred with kwargs -function inferrable_kwtest(x; y=1) - 2x -end -function uninferrable_kwtest(x; y=1) - 2x+y -end -@test @inferred(inferrable_kwtest(1)) == 2 -@test @inferred(inferrable_kwtest(1; y=1)) == 2 -@test @inferred(uninferrable_kwtest(1)) == 3 -@test_throws ErrorException @inferred(uninferrable_kwtest(1; y=2)) == 2 - -@test_throws ErrorException @testset "$(error())" for i in 1:10 -end -@test_throws ErrorException @testset "$(error())" begin -end - -io = IOBuffer() -@test (print(io, Base.Test.Error(:test_error, "woot", 5, backtrace())); 1) == 1 -str = String(take!(io)) -# NOTE: This test depends on the code generated by @testset getting compiled, -# to get good backtraces. If it fails, check the implementation of `testset_beginend`. -@test contains(str, "test.jl") -@test !contains(str, "boot.jl") - -let io = IOBuffer() - exc = Test.TestSetException(1,2,3,4,Vector{Union{Base.Test.Error, Base.Test.Fail}}()) - Base.showerror(io, exc, backtrace()) - @test !contains(String(take!(io)), "backtrace()") -end - -# 19750 -let io = IOBuffer() - exc = Test.TestSetException(1,2,3,4,Vector{Union{Base.Test.Error, Base.Test.Fail}}()) - Base.showerror(io, exc, backtrace()) - @test !contains(String(take!(io)), "backtrace()") - - exc = Test.FallbackTestSetException("msg") - Base.showerror(io, exc, backtrace()) - str = String(take!(io)) - @test contains(str, "msg") - @test !contains(str, "backtrace()") -end - -msg = readstring(pipeline(ignorestatus(`$(Base.julia_cmd()) --startup-file=no --color=no -e ' -using Base.Test - -foo(x) = length(x)^2 - -@testset "Foo Tests" begin - @testset "Animals" begin - @testset "Felines" begin - @test foo("cat") == 9 - end - @testset "Canines" begin - @test foo("dog") == 11 - end - end - @testset "Arrays" begin - @test foo(zeros(2)) == 4 - @test foo(ones(4)) == 15 - end -end'`), stderr=DevNull)) - -@test contains(msg, -""" -Test Summary: | Pass Fail Total -Foo Tests | 2 2 4 - Animals | 1 1 2 - Felines | 1 1 - Canines | 1 1 - Arrays | 1 1 2 -""") - -# 20489 -msg = split(readstring(pipeline(ignorestatus(`$(Base.julia_cmd()) --startup-file=no --color=no -e ' -Test.print_test_results(Test.DefaultTestSet(""))'`), stderr=DevNull)), "\n")[1] - -@test msg == rstrip(msg) diff --git a/julia-0.6.3/share/julia/test/test_exec.jl b/julia-0.6.3/share/julia/test/test_exec.jl deleted file mode 100644 index 529f9f6..0000000 --- a/julia-0.6.3/share/julia/test/test_exec.jl +++ /dev/null @@ -1,5 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -using Base.Test -# Check that the fallback test set throws immediately -@test 1 == 2 diff --git a/julia-0.6.3/share/julia/test/test_sourcepath.jl b/julia-0.6.3/share/julia/test/test_sourcepath.jl deleted file mode 100644 index 60985b8..0000000 --- a/julia-0.6.3/share/julia/test/test_sourcepath.jl +++ /dev/null @@ -1,17 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -# source path in tasks -path = Base.source_path()::String # this variable is leaked to the source script -@test endswith(path, joinpath("test","test_sourcepath.jl")) -@test let ct = current_task() - yieldto(@task yieldto(ct, Base.source_path())) -end == path -@test let ct = current_task() - yieldto(@task schedule(ct, Base.source_path())) -end == path -@test let ct = current_task(), t = @task Base.source_path() - schedule(ct) - yieldto(t) - wait(t) -end == path -@test isabspath(@__FILE__) diff --git a/julia-0.6.3/share/julia/test/testdefs.jl b/julia-0.6.3/share/julia/test/testdefs.jl deleted file mode 100644 index bc214da..0000000 --- a/julia-0.6.3/share/julia/test/testdefs.jl +++ /dev/null @@ -1,42 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -function runtests(name, isolate=true) - old_print_setting = Base.Test.TESTSET_PRINT_ENABLE[] - Base.Test.TESTSET_PRINT_ENABLE[] = false - try - if isolate - # Simple enough to type and random enough so that no one will hard - # code it in the test - mod_name = Symbol("Test", rand(1:100), "Main_", replace(name, '/', '_')) - m = @eval(Main, module $mod_name end) - else - m = Main - end - @eval(m, using Base.Test) - ex = quote - @timed @testset $"$name" begin - include($"$name.jl") - end - end - res_and_time_data = eval(m, ex) - rss = Sys.maxrss() - #res_and_time_data[1] is the testset - passes,fails,error,broken,c_passes,c_fails,c_errors,c_broken = Base.Test.get_test_counts(res_and_time_data[1]) - if res_and_time_data[1].anynonpass == false - res_and_time_data = ( - (passes+c_passes,broken+c_broken), - res_and_time_data[2], - res_and_time_data[3], - res_and_time_data[4], - res_and_time_data[5]) - end - vcat(collect(res_and_time_data), rss) - finally - Base.Test.TESTSET_PRINT_ENABLE[] = old_print_setting - end -end - -# looking in . messes things up badly -filter!(x->x!=".", LOAD_PATH) - -nothing # File is loaded via a remotecall to "include". Ensure it returns "nothing". diff --git a/julia-0.6.3/share/julia/test/testenv.jl b/julia-0.6.3/share/julia/test/testenv.jl deleted file mode 100644 index 871999c..0000000 --- a/julia-0.6.3/share/julia/test/testenv.jl +++ /dev/null @@ -1,35 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -# This includes a few helper variables and functions that provide information about the -# test environment (command line flags, current module, etc). -# This file can be included multiple times in the same module if necessary, -# which can happen with unisolated test runs. - -if !isdefined(:testenv_defined) - const testenv_defined = true - if haskey(ENV, "JULIA_TEST_EXEFLAGS") - const test_exeflags = `$(Base.shell_split(ENV["JULIA_TEST_EXEFLAGS"]))` - else - inline_flag = Base.JLOptions().can_inline == 1 ? `` : `--inline=no` - cov_flag = `` - if Base.JLOptions().code_coverage == 1 - cov_flag = `--code-coverage=user` - elseif Base.JLOptions().code_coverage == 2 - cov_flag = `--code-coverage=all` - end - const test_exeflags = `$cov_flag $inline_flag --check-bounds=yes --startup-file=no --depwarn=error` - end - - if haskey(ENV, "JULIA_TEST_EXENAME") - const test_exename = `$(Base.shell_split(ENV["JULIA_TEST_EXENAME"]))` - else - const test_exename = `$(joinpath(JULIA_HOME, Base.julia_exename()))` - end - - addprocs_with_testenv(X; kwargs...) = addprocs(X; exename=test_exename, exeflags=test_exeflags, kwargs...) - - const curmod = current_module() - const curmod_name = fullname(curmod) - const curmod_str = curmod === Main ? "Main" : join(curmod_name, ".") - const curmod_prefix = "$(["$m." for m in curmod_name]...)" -end diff --git a/julia-0.6.3/share/julia/test/threads.jl b/julia-0.6.3/share/julia/test/threads.jl deleted file mode 100644 index 878db35..0000000 --- a/julia-0.6.3/share/julia/test/threads.jl +++ /dev/null @@ -1,451 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -using Base.Test -using Base.Threads - -# threading constructs - -# parallel loop with parallel atomic addition -function threaded_loop(a, r, x) - @threads for i in r - a[i] = 1 + atomic_add!(x, 1) - end -end - -function test_threaded_loop_and_atomic_add() - x = Atomic() - a = zeros(Int,10000) - threaded_loop(a,1:10000,x) - found = zeros(Bool,10000) - was_inorder = true - for i=1:length(a) - was_inorder &= a[i]==i - found[a[i]] = true - end - @test x[] == 10000 - # Next test checks that all loop iterations ran, - # and were unique (via pigeon-hole principle). - @test findfirst(found,false) == 0 - if was_inorder - println(STDERR, "Warning: threaded loop executed in order") - end -end - -test_threaded_loop_and_atomic_add() - -# Helper for test_threaded_atomic_minmax that verifies sequential consistency. -function check_minmax_consistency{T}(old::Array{T,1}, m::T, start::T, o::Base.Ordering) - for v in old - if v != start - # Check that atomic op that installed v reported consistent old value. - @test Base.lt(o, old[v-m+1], v) - end - end -end - -function test_threaded_atomic_minmax{T}(m::T,n::T) - mid = m + (n-m)>>1 - x = Atomic{T}(mid) - y = Atomic{T}(mid) - oldx = Array{T}(n-m+1) - oldy = Array{T}(n-m+1) - @threads for i = m:n - oldx[i-m+1] = atomic_min!(x, T(i)) - oldy[i-m+1] = atomic_max!(y, T(i)) - end - @test x[] == m - @test y[] == n - check_minmax_consistency(oldy,m,mid,Base.Forward) - check_minmax_consistency(oldx,m,mid,Base.Reverse) -end - -# The ranges below verify that the correct signed/unsigned comparison is used. -test_threaded_atomic_minmax(Int16(-5000),Int16(5000)) -test_threaded_atomic_minmax(UInt16(27000),UInt16(37000)) - -function threaded_add_locked{LockT}(::Type{LockT}, x, n) - critical = LockT() - @threads for i = 1:n - @test lock(critical) === nothing - @test islocked(critical) - x = x + 1 - @test unlock(critical) === nothing - end - @test !islocked(critical) - nentered = 0 - nfailed = Atomic() - @threads for i = 1:n - if trylock(critical) - @test islocked(critical) - nentered += 1 - @test unlock(critical) === nothing - else - atomic_add!(nfailed, 1) - end - end - @test 0 < nentered <= n - @test nentered + nfailed[] == n - @test !islocked(critical) - return x -end - -@test threaded_add_locked(SpinLock, 0, 10000) == 10000 -@test threaded_add_locked(RecursiveSpinLock, 0, 10000) == 10000 -@test threaded_add_locked(Mutex, 0, 10000) == 10000 - -# Check if the recursive lock can be locked and unlocked correctly. -let critical = RecursiveSpinLock() - @test !islocked(critical) - @test_throws AssertionError unlock(critical) - @test lock(critical) === nothing - @test islocked(critical) - @test lock(critical) === nothing - @test trylock(critical) == true - @test islocked(critical) - @test unlock(critical) === nothing - @test islocked(critical) - @test unlock(critical) === nothing - @test islocked(critical) - @test unlock(critical) === nothing - @test !islocked(critical) - @test_throws AssertionError unlock(critical) - @test trylock(critical) == true - @test islocked(critical) - @test unlock(critical) === nothing - @test !islocked(critical) - @test_throws AssertionError unlock(critical) - @test !islocked(critical) -end - -# Make sure doing a GC while holding a lock doesn't cause dead lock -# PR 14190. (This is only meaningful for threading) -function threaded_gc_locked{LockT}(::Type{LockT}) - critical = LockT() - @threads for i = 1:20 - @test lock(critical) === nothing - @test islocked(critical) - gc(false) - @test unlock(critical) === nothing - end - @test !islocked(critical) -end - -threaded_gc_locked(SpinLock) -threaded_gc_locked(Threads.RecursiveSpinLock) -threaded_gc_locked(Mutex) - -# Issue 14726 -# Make sure that eval'ing in a different module doesn't mess up other threads -orig_curmodule14726 = current_module() -main_var14726 = 1 -module M14726 -module_var14726 = 1 -end - -@threads for i in 1:100 - for j in 1:100 - @eval M14726 module_var14726 = $j - end -end -@test isdefined(:orig_curmodule14726) -@test isdefined(:main_var14726) -@test current_module() == orig_curmodule14726 - -@threads for i in 1:100 - # Make sure current module is not null. - # The @test might not be particularly meaningful currently since the - # thread infrastructures swallows the error. (Same below) - @test current_module() == orig_curmodule14726 -end - -module M14726_2 -using Base.Test -using Base.Threads -@threads for i in 1:100 - # Make sure current module is the same as the one on the thread that - # pushes the work onto the threads. - # The @test might not be particularly meaningful currently since the - # thread infrastructures swallows the error. (See also above) - @test current_module() == M14726_2 -end -end - -# Ensure only LLVM-supported types can be atomic -@test_throws TypeError Atomic{Bool} -@test_throws TypeError Atomic{BigInt} -@test_throws TypeError Atomic{Complex128} - -# Test atomic memory ordering with load/store -mutable struct CommBuf - var1::Atomic{Int} - var2::Atomic{Int} - correct_write::Bool - correct_read::Bool - CommBuf() = new(Atomic{Int}(0), Atomic{Int}(0), false, false) -end -function test_atomic_write(commbuf::CommBuf, n::Int) - for i in 1:n - # The atomic stores guarantee that var1 >= var2 - commbuf.var1[] = i - commbuf.var2[] = i - end - commbuf.correct_write = true -end -function test_atomic_read(commbuf::CommBuf, n::Int) - correct = true - while true - # load var2 before var1 - var2 = commbuf.var2[] - var1 = commbuf.var1[] - correct &= var1 >= var2 - var1 == n && break - # Temporary solution before we have gc transition support in codegen. - ccall(:jl_gc_safepoint, Void, ()) - end - commbuf.correct_read = correct -end -function test_atomic() - commbuf = CommBuf() - count = 1_000_000 - @threads for i in 1:2 - if i==1 - test_atomic_write(commbuf, count) - else - test_atomic_read(commbuf, count) - end - end - @test commbuf.correct_write == true - @test commbuf.correct_read == true -end -test_atomic() - -# Test ordering with fences using Peterson's algorithm -# Example adapted from <https://en.wikipedia.org/wiki/Peterson%27s_algorithm> -mutable struct Peterson - # State for Peterson's algorithm - flag::Vector{Atomic{Int}} - turn::Atomic{Int} - # Collision detection - critical::Vector{Atomic{Int}} - correct::Vector{Bool} - Peterson() = - new([Atomic{Int}(0), Atomic{Int}(0)], - Atomic{Int}(0), - [Atomic{Int}(0), Atomic{Int}(0)], - [false, false]) -end -function test_fence(p::Peterson, id::Int, n::Int) - @assert id == mod1(id,2) - correct = true - otherid = mod1(id+1,2) - for i in 1:n - p.flag[id][] = 1 - p.turn[] = otherid - atomic_fence() - while p.flag[otherid][] != 0 && p.turn[] == otherid - # busy wait - # Temporary solution before we have gc transition support in codegen. - ccall(:jl_gc_safepoint, Void, ()) - end - # critical section - p.critical[id][] = 1 - correct &= p.critical[otherid][] == 0 - p.critical[id][] = 0 - # end of critical section - p.flag[id][] = 0 - end - p.correct[id] = correct -end -function test_fence() - commbuf = Peterson() - count = 1_000_000 - @threads for i in 1:2 - test_fence(commbuf, i, count) - end - @test commbuf.correct[1] == true - @test commbuf.correct[2] == true -end -test_fence() - -# Test load / store with various types -let atomic_types = [Int8, Int16, Int32, Int64, Int128, - UInt8, UInt16, UInt32, UInt64, UInt128, - Float16, Float32, Float64] - # Temporarily omit 128-bit types on 32bit x86 - # 128-bit atomics do not exist on AArch32. - # And we don't support them yet on power, because they are lowered - # to `__sync_lock_test_and_set_16`. - if Sys.ARCH === :i686 || startswith(string(Sys.ARCH), "arm") || - Sys.ARCH === :powerpc64le || Sys.ARCH === :ppc64le - filter!(T -> sizeof(T)<=8, atomic_types) - end - for T in atomic_types - var = Atomic{T}() - var[] = 42 - @test var[] === T(42) - old = atomic_xchg!(var, T(13)) - @test old === T(42) - @test var[] === T(13) - old = atomic_cas!(var, T(13), T(14)) # this will succeed - @test old === T(13) - @test var[] === T(14) - old = atomic_cas!(var, T(13), T(15)) # this will fail - @test old === T(14) - @test var[] === T(14) - end -end - -# Test atomic_cas! and atomic_xchg! -function test_atomic_cas!{T}(var::Atomic{T}, range::StepRange{Int,Int}) - for i in range - while true - old = atomic_cas!(var, T(i-1), T(i)) - old == T(i-1) && break - # Temporary solution before we have gc transition support in codegen. - ccall(:jl_gc_safepoint, Void, ()) - end - end -end -for T in (Int32, Int64, Float32, Float64) - var = Atomic{T}() - nloops = 1000 - di = nthreads() - @threads for i in 1:di - test_atomic_cas!(var, i:di:nloops) - end - @test var[] === T(nloops) -end - -function test_atomic_xchg!{T}(var::Atomic{T}, i::Int, accum::Atomic{Int}) - old = atomic_xchg!(var, T(i)) - atomic_add!(accum, Int(old)) -end -for T in (Int32, Int64, Float32, Float64) - accum = Atomic{Int}() - var = Atomic{T}() - nloops = 1000 - @threads for i in 1:nloops - test_atomic_xchg!(var, i, accum) - end - @test accum[] + Int(var[]) === sum(0:nloops) -end - -function test_atomic_float{T}(varadd::Atomic{T}, varmax::Atomic{T}, varmin::Atomic{T}, i::Int) - atomic_add!(varadd, T(i)) - atomic_max!(varmax, T(i)) - atomic_min!(varmin, T(i)) -end -for T in (Int32, Int64, Float32, Float64) - varadd = Atomic{T}() - varmax = Atomic{T}() - varmin = Atomic{T}() - nloops = 1000 - @threads for i in 1:nloops - test_atomic_float(varadd, varmax, varmin, i) - end - @test varadd[] === T(sum(1:nloops)) - @test varmax[] === T(maximum(1:nloops)) - @test varmin[] === T(0) -end -for period in (0.06, Dates.Millisecond(60)) - let async = Base.AsyncCondition(), t - c = Condition() - task = schedule(Task(function() - notify(c) - wait(c) - t = Timer(period) - wait(t) - ccall(:uv_async_send, Void, (Ptr{Void},), async) - ccall(:uv_async_send, Void, (Ptr{Void},), async) - wait(c) - sleep(period) - ccall(:uv_async_send, Void, (Ptr{Void},), async) - ccall(:uv_async_send, Void, (Ptr{Void},), async) - end)) - wait(c) - notify(c) - delay1 = @elapsed wait(async) - notify(c) - delay2 = @elapsed wait(async) - @test istaskdone(task) - @test delay1 > 0.05 - @test delay2 > 0.05 - @test isopen(async) - @test !isopen(t) - close(t) - close(async) - @test_throws EOFError wait(async) - @test !isopen(async) - @test_throws EOFError wait(t) - @test_throws EOFError wait(async) - end -end - -complex_cfunction = function(a) - s = zero(eltype(a)) - @inbounds @simd for i in a - s += muladd(a[i], a[i], -2) - end - return s -end -function test_thread_cfunction() - @threads for i in 1:1000 - # Make sure this is not inferrable - # and a runtime call to `jl_function_ptr` will be created - ccall(:jl_function_ptr, Ptr{Void}, (Any, Any, Any), - complex_cfunction, Float64, Tuple{Ref{Vector{Float64}}}) - end -end -test_thread_cfunction() - -# Compare the two ways of checking if threading is enabled. -# `jl_tls_states` should only be defined on non-threading build. -if ccall(:jl_threading_enabled, Cint, ()) == 0 - @test nthreads() == 1 - cglobal(:jl_tls_states) != C_NULL -else - @test_throws ErrorException cglobal(:jl_tls_states) -end - -function test_thread_range() - a = zeros(Int, nthreads()) - @threads for i in 1:threadid() - a[i] = 1 - end - for i in 1:threadid() - @test a[i] == 1 - end - for i in (threadid() + 1):nthreads() - @test a[i] == 0 - end -end -test_thread_range() - -# Thread safety of `jl_load_and_lookup`. -function test_load_and_lookup_18020(n) - @threads for i in 1:n - try - ccall(:jl_load_and_lookup, - Ptr{Void}, (Cstring, Cstring, Ref{Ptr{Void}}), - "$i", :f, C_NULL) - end - end -end -test_load_and_lookup_18020(10000) - -# Nested threaded loops -# This may not be efficient/fully supported but should work without crashing..... -function test_nested_loops() - a = zeros(Int, 100, 100) - @threads for i in 1:100 - @threads for j in 1:100 - a[j, i] = i + j - end - end - for i in 1:100 - for j in 1:100 - @test a[j, i] == i + j - end - end -end -test_nested_loops() diff --git a/julia-0.6.3/share/julia/test/topology.jl b/julia-0.6.3/share/julia/test/topology.jl deleted file mode 100644 index c3c92c5..0000000 --- a/julia-0.6.3/share/julia/test/topology.jl +++ /dev/null @@ -1,89 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -pids = addprocs_with_testenv(4; topology="master_slave") -p1 = pids[1] -p2 = pids[2] - -@test_throws RemoteException remotecall_fetch(()->remotecall_fetch(myid, p2), p1) - -function test_worker_counts() - # check if the nprocs/nworkers/workers are the same on the remaining workers - np=nprocs() - nw=nworkers() - ws=sort(workers()) - - for p in workers() - @test (true, true, true) == remotecall_fetch(p, np, nw, ws) do x,y,z - (x==nprocs(), y==nworkers(), z==sort(workers())) - end - end -end - -function remove_workers_and_test() - while nworkers() > 0 - rmprocs(workers()[1]; waitfor=2.0) - test_worker_counts() - if nworkers() == nprocs() - break - end - end -end - -remove_workers_and_test() - -# connect even pids to other even pids, odd to odd. -mutable struct TopoTestManager <: ClusterManager - np::Integer -end - -function Base.launch(manager::TopoTestManager, params::Dict, launched::Array, c::Condition) - dir = params[:dir] - exename = params[:exename] - exeflags = params[:exeflags] - - for i in 1:manager.np - io, pobj = open(pipeline(detach( - setenv(`$exename $exeflags --bind-to $(Base.Distributed.LPROC.bind_addr) --worker $(Base.cluster_cookie())`, dir=dir)); stderr=STDERR), "r") - wconfig = WorkerConfig() - wconfig.process = pobj - wconfig.io = io - wconfig.ident = i - wconfig.connect_idents = collect(i+2:2:manager.np) - push!(launched, wconfig) - end - - notify(c) -end - -const map_pid_ident=Dict() -function Base.manage(manager::TopoTestManager, id::Integer, config::WorkerConfig, op::Symbol) - if op == :register - map_pid_ident[id] = get(config.ident) - elseif op == :interrupt - kill(get(config.process), 2) - end -end - -addprocs_with_testenv(TopoTestManager(8); topology="custom") - -while true - if any(x->get(map_pid_ident, x, 0)==0, workers()) - yield() - else - break - end -end - -for p1 in workers() - for p2 in workers() - i1 = map_pid_ident[p1] - i2 = map_pid_ident[p2] - if (iseven(i1) && iseven(i2)) || (isodd(i1) && isodd(i2)) - @test p2 == remotecall_fetch(p->remotecall_fetch(myid, p), p1, p2) - else - @test_throws RemoteException remotecall_fetch(p->remotecall_fetch(myid, p), p1, p2) - end - end -end - -remove_workers_and_test() diff --git a/julia-0.6.3/share/julia/test/triplequote.jl b/julia-0.6.3/share/julia/test/triplequote.jl deleted file mode 100644 index 35bc1fa..0000000 --- a/julia-0.6.3/share/julia/test/triplequote.jl +++ /dev/null @@ -1,68 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -# triple-quote delimited strings -@test """abc""" == "abc" -@test """ab"c""" == "ab\"c" -@test """ab""c""" == "ab\"\"c" -@test """ab"\"c""" == "ab\"\"c" -@test """abc\"""" == "abc\"" -n = 3 -@test """$n\n""" == "$n\n" -@test """$(n)""" == "3" -@test """$(2n)""" == "6" -@test """$(n+4)""" == "7" -@test """$("string")""" == "string" -a = [3,1,2] -@test """$(a[2])""" == "1" -@test """$(a[3]+7)""" == "9" -@test """$(floor(Int,4.5))""" == "4" -nl = " -" -@test """ - a - b - - c - """ == "a$(nl)b$(nl)$(nl)c$(nl)" -@test """ - """ == "" -@test """x - a - """ == "x$(nl) a$(nl)" -@test """ - $n - """ == " $n$(nl)" -@test """ - a - b - c""" == " a$(nl)b$(nl) c" -# tabs + spaces -@test """ - a - b - """ == " a$(nl) b$(nl)" -@test """ - a - """ == "a$(nl) " -s = " p" -@test """ - $s""" == "$s" -@test """ - $s - """ == " $s$(nl)" -@test """\t""" == "\t" -@test """ - \t""" == "" -@test """ - foo - \tbar""" == "foo$(nl)\tbar" -@test """ - foo - \tbar - """ == "foo$(nl)\tbar$(nl)" -@test """ - foo - bar\t""" == "foo$(nl)bar\t" -@test """ - $("\n ") - """ == "\n $(nl)" diff --git a/julia-0.6.3/share/julia/test/tuple.jl b/julia-0.6.3/share/julia/test/tuple.jl deleted file mode 100644 index bbf224c..0000000 --- a/julia-0.6.3/share/julia/test/tuple.jl +++ /dev/null @@ -1,264 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -@test convert(Tuple, (1,2)) == (1,2) -@testset "indexing" begin - @test length(()) == 0 - @test length((1,)) === 1 - @test length((1,2)) === 2 - - @test_throws ArgumentError Base.front(()) - @test_throws ArgumentError first(()) - - @test endof(()) === 0 - @test endof((1,)) === 1 - @test endof((1,2)) === 2 - - @test size((), 1) === 0 - @test size((1,), 1) === 1 - @test size((1,2), 1) === 2 -end -# @test_throws ArgumentError size((), 2) -# @test_throws ArgumentError size((1,), 2) -# @test_throws ArgumentError size((1,2), 2) - -@test getindex((1,), 1) === 1 -@test getindex((1,2), 2) === 2 -@test_throws BoundsError getindex((), 1) -@test_throws BoundsError getindex((1,2), 0) -@test_throws BoundsError getindex((1,2), -1) - -@test getindex((1,), 1.0) === 1 -@test getindex((1,2), 2.0) === 2 -@test_throws BoundsError getindex((), 1.0) -@test_throws BoundsError getindex((1,2), 0.0) -@test_throws BoundsError getindex((1,2), -1.0) - -@test getindex((5,6,7,8), [1,2,3]) === (5,6,7) -@test_throws BoundsError getindex((1,2), [3,4]) - -@test getindex((5,6,7,8), [true, false, false, true]) === (5,8) -@test_throws BoundsError getindex((5,6,7,8), [true, false, false, true, true]) - -@test getindex((5,6,7,8), []) === () - -## filling to specified length -@test @inferred(Base.fill_to_length((1,2,3), -1, Val{5})) == (1,2,3,-1,-1) -@test_throws ArgumentError Base.fill_to_length((1,2,3), -1, Val{2}) - -## iterating ## -@test start((1,2,3)) === 1 - -@test done((), 1) -@test !done((1,2,3), 3) -@test done((1,2,3), 4) - -@test next((5,6,7), 1) === (5, 2) -@test next((5,6,7), 3) === (7, 4) -@test_throws BoundsError next((5,6,7), 0) -@test_throws BoundsError next((), 1) - -@test collect(eachindex((2,5,"foo"))) == collect(1:3) -@test collect(eachindex((2,5,"foo"), (1,2,5,7))) == collect(1:4) - - -## eltype ## -@test eltype((1,2,3)) === Int -@test eltype((1.0,2.0,3.0)) <: AbstractFloat -@test eltype((true, false)) === Bool -@test eltype((1, 2.0, false)) === typejoin(Int, Float64, Bool) -@test eltype(()) === Union{} -@test eltype(Tuple{Int, Float64, Vararg{Bool}}) === typejoin(Int, Float64, Bool) -@test eltype(Tuple{Int, T, Vararg{Bool}} where T <: AbstractFloat) === - typejoin(Int, AbstractFloat, Bool) -@test eltype(Tuple{Int, Bool, Vararg{T}} where T <: AbstractFloat) === - typejoin(Int, AbstractFloat, Bool) -@test eltype(Union{Tuple{Int, Float64}, Tuple{Vararg{Bool}}}) === typejoin(Int, Float64, Bool) - -begin - local foo - ## mapping ## - foo() = 2 - foo(x) = 2x - foo(x, y) = x + y - foo(x, y, z) = x + y + z - longtuple = ntuple(identity, 20) - - # 1 argument - @test map(foo, ()) === () - @test map(foo, (1,)) === (2,) - @test map(foo, (1,2)) === (2,4) - @test map(foo, (1,2,3,4)) === (2,4,6,8) - @test map(foo, longtuple) === ntuple(i->2i,20) - - # 2 arguments - @test map(foo, (), ()) === () - @test map(foo, (1,), (1,)) === (2,) - @test map(foo, (1,2), (1,2)) === (2,4) - @test map(foo, (1,2,3,4), (1,2,3,4)) === (2,4,6,8) - @test map(foo, longtuple, longtuple) === ntuple(i->2i,20) - @test_throws BoundsError map(foo, (), (1,)) - @test_throws BoundsError map(foo, (1,), ()) - - # n arguments - @test map(foo, (), (), ()) === () - @test map(foo, (1,), (1,), (1,)) === (3,) - @test map(foo, (1,2), (1,2), (1,2)) === (3,6) - @test map(foo, (1,2,3,4), (1,2,3,4), (1,2,3,4)) === (3,6,9,12) - @test map(foo, longtuple, longtuple, longtuple) === ntuple(i->3i,20) - @test_throws BoundsError map(foo, (), (1,), (1,)) - @test_throws BoundsError map(foo, (1,), (1,), ()) -end - -## comparison ## -@test isequal((), ()) -@test isequal((1,2,3), (1,2,3)) -@test !isequal((1,2,3), (1,2,4)) -@test !isequal((1,2,3), (1,2)) - -@test ==((), ()) -@test ==((1,2,3), (1,2,3)) -@test !==((1,2,3), (1,2,4)) -@test !==((1,2,3), (1,2)) - -@test isless((1,2), (1,3)) -@test isless((1,), (1,2)) -@test !isless((1,2), (1,2)) -@test !isless((2,1), (1,2)) - - -## functions ## -@test isempty(()) -@test !isempty((1,)) - -@test reverse(()) === () -@test reverse((1,2,3)) === (3,2,1) - - -## specialized reduction ## -@test sum((1,2,3)) === 6 - -@test prod(()) === 1 -@test prod((1,2,3)) === 6 - -@test all(()) === true -@test all((false,)) === false -@test all((true,)) === true -@test all((true, true)) === true -@test all((true, false)) === false -@test all((false, false)) === false - -@test any(()) === false -@test any((true,)) === true -@test any((false,)) === false -@test any((true, true)) === true -@test any((true, false)) === true -@test any((false, false)) === false -@test any((false,false,false)) === false -@test any((true,false,false)) === true -@test any((false,true,false)) === true -@test any((false,false,true)) === true -@test any((true,true,false)) === true -@test any((true,false,true)) === true -@test any((true,true,false)) === true -@test any((true,true,true)) === true - -@test @inferred(ntuple(abs2, Val{0})) == () -@test @inferred(ntuple(abs2, Val{2})) == (1, 4) -@test @inferred(ntuple(abs2, Val{3})) == (1, 4, 9) -@test @inferred(ntuple(abs2, Val{4})) == (1, 4, 9, 16) -@test @inferred(ntuple(abs2, Val{5})) == (1, 4, 9, 16, 25) -@test @inferred(ntuple(abs2, Val{6})) == (1, 4, 9, 16, 25, 36) -# issue #21697 -@test_throws ArgumentError ntuple(abs2, Val{-1}) - -# issue #12854 -@test_throws TypeError ntuple(identity, Val{1:2}) - -for n = 0:20 - t = ntuple(identity, n) - @test length(t) == n - for i = 1:n - @test t[i] == i - end -end - -# issue #19719 -@test_throws BoundsError (1,2,3)[falses(4)] -@test_throws BoundsError (1,2,3)[[false,false,true,true]] -@test_throws BoundsError (1,2,3)[trues(2)] -@test_throws BoundsError (1,2,3)[falses(2)] -@test_throws BoundsError ()[[false]] -@test_throws BoundsError ()[[true]] - -struct BitPerm_19352 - p::NTuple{8,UInt8} - function BitPerm(p::NTuple{8,UInt8}) - sort(collect(p)) != collect(0:7) && error("$p is not a permutation of 0:7") - new(p) - end - BitPerm_19352(b0,b1,b2,b3,b4,b5,b6,b7) = BitPerm((UInt8(b0),UInt8(b1),UInt8(b2),UInt8(b3), - UInt8(b4),UInt8(b5),UInt8(b6),UInt8(b7))) -end - -@testset "side effect in tuple constructor #19352" begin - @test BitPerm_19352(0,2,4,6,1,3,5,7).p[2] == 0x02 -end - -# issue #15703 -let - struct A_15703{N} - keys::NTuple{N, Int} - end - - struct B_15703 - x::A_15703 - end - - function bug_15703(xs...) - [x for x in xs] - end - - function test_15703() - s = (1,) - a = A_15703(s) - ss = B_15703(a).x.keys - @test ss === s - bug_15703(ss...) - end - - test_15703() -end - -# PR #15516 -@test Tuple{Char,Char}("za") === ('z','a') -@test_throws ArgumentError Tuple{Char,Char}("z") - -@test NTuple{20,Int}(Iterators.countfrom(2)) === (2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21) -@test NTuple{20,Float64}(Iterators.countfrom(2)) === (2.,3.,4.,5.,6.,7.,8.,9.,10.,11.,12.,13.,14.,15.,16.,17.,18.,19.,20.,21.) -@test_throws ArgumentError NTuple{20,Int}([1,2]) - -@test Tuple{Vararg{Float32}}(Float64[1,2,3]) === (1.0f0, 2.0f0, 3.0f0) -@test Tuple{Int,Vararg{Float32}}(Float64[1,2,3]) === (1, 2.0f0, 3.0f0) -@test Tuple{Int,Vararg{Any}}(Float64[1,2,3]) === (1, 2.0, 3.0) -@test Tuple(ones(5)) === (1.0,1.0,1.0,1.0,1.0) -@test_throws MethodError convert(Tuple, ones(5)) - -@testset "Multidimensional indexing (issue #20453)" begin - @test_throws MethodError (1,)[] - @test_throws MethodError (1,1,1)[1,1] -end - -@testset "ambiguity between tuple constructors #20990" begin - Tuple16Int = Tuple{Int,Int,Int,Int,Int,Int,Int,Int,Int,Int,Int,Int,Int,Int,Int,Int} - tuple16int = (1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1) - @test Tuple16Int(tuple16int) isa Tuple16Int -end - -# PR #21446 -for n = 0:15 - @test ntuple(identity, Val{n}) == ntuple(identity, n) -end - -# https://github.com/JuliaLang/julia/issues/21026#issuecomment-317113307 -const VecTuple21026{T} = Tuple{VecElement{T}} -@test convert(VecTuple21026, (1,)) === (VecElement(1),) diff --git a/julia-0.6.3/share/julia/test/unicode/UnicodeError.jl b/julia-0.6.3/share/julia/test/unicode/UnicodeError.jl deleted file mode 100644 index a5665df..0000000 --- a/julia-0.6.3/share/julia/test/unicode/UnicodeError.jl +++ /dev/null @@ -1,9 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -@testset "invalid utf8" begin - let io = IOBuffer() - show(io, UnicodeError(Base.UTF_ERR_SHORT, 1, 10)) - check = "UnicodeError: invalid UTF-8 sequence starting at index 1 (0xa missing one or more continuation bytes)" - @test String(take!(io)) == check - end -end diff --git a/julia-0.6.3/share/julia/test/unicode/utf8.jl b/julia-0.6.3/share/julia/test/unicode/utf8.jl deleted file mode 100644 index 093c899..0000000 --- a/julia-0.6.3/share/julia/test/unicode/utf8.jl +++ /dev/null @@ -1,47 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -@testset "cesu8 input" begin - let ch = 0x10000 - for hi = 0xd800:0xdbff - for lo = 0xdc00:0xdfff - @test convert(String, Vector{UInt8}(String(Char[hi, lo]))) == string(Char(ch)) - ch += 1 - end - end - end -end - -@testset "string indexing" begin - let str = String(b"this is a test\xed\x80") - @test next(str, 15) == ('\ufffd', 16) - @test_throws BoundsError getindex(str, 0:3) - @test_throws BoundsError getindex(str, 17:18) - @test_throws BoundsError getindex(str, 2:17) - @test_throws UnicodeError getindex(str, 16:17) - @test string(Char(0x110000)) == "\ufffd" - end -end - -@testset "string reverse" begin - @test reverse("") == "" - @test reverse("a") == "a" - @test reverse("abc") == "cba" - @test reverse("xyz\uff\u800\uffff\U10ffff") == "\U10ffff\uffff\u800\uffzyx" - for str in [ - b"xyz\xc1", - b"xyz\xd0", - b"xyz\xe0", - b"xyz\xed\x80", - b"xyz\xf0", - b"xyz\xf0\x80", - b"xyz\xf0\x80\x80" - ] - @test_throws UnicodeError reverse(String(str)) - end -end - -@testset "string convert" begin - @test convert(String, b"this is a test\xed\x80\x80") == "this is a test\ud000" - ## Specifically check UTF-8 string whose lead byte is same as a surrogate - @test convert(String, b"\xed\x9f\xbf") == "\ud7ff" -end diff --git a/julia-0.6.3/share/julia/test/unicode/utf8proc.jl b/julia-0.6.3/share/julia/test/unicode/utf8proc.jl deleted file mode 100644 index 2ecee1d..0000000 --- a/julia-0.6.3/share/julia/test/unicode/utf8proc.jl +++ /dev/null @@ -1,323 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -@testset "string normalization" begin - # normalize_string (Unicode normalization etc.): - @test normalize_string("\u006e\u0303", :NFC) == "\u00f1" - @test "\u006e\u0303" == normalize_string("\u00f1", :NFD) - @test normalize_string("\ufb00", :NFC) != "ff" - @test normalize_string("\ufb00", :NFKC) == "ff" - @test normalize_string("\u006e\u0303\ufb00", :NFKC) == "\u00f1"*"ff" - @test normalize_string("\u00f1\ufb00", :NFKD) == "\u006e\u0303"*"ff" - @test normalize_string("\u006e\u0303", compose=true) == "\u00f1" - @test "\u006e\u0303" == normalize_string("\u00f1", decompose=true) - @test normalize_string("\u006e\u0303\u00b5",compat=true) == "\u00f1\u03bc" - @test normalize_string("Σσς",casefold=true) == "σσσ" - @test normalize_string("∕⁄", lump=true) == "//" - @test normalize_string("\ua\n\r\r\ua", newline2lf=true) == "\ua\ua\ua\ua" - @test normalize_string("\ua\n\r\r\ua", newline2ls=true) == "\u2028\u2028\u2028\u2028" - @test normalize_string("\ua\n\r\r\ua", newline2ps=true) == "\u2029\u2029\u2029\u2029" - @test normalize_string("\u00f1", stripmark=true) == "n" - @test isempty(normalize_string("\u00ad", stripignore=true)) - @test normalize_string("\t\r", stripcc=true) == " " - @test normalize_string("\t\r", stripcc=true, newline2ls=true) == " \u2028" - @test normalize_string("\u0072\u0307\u0323", :NFC) == "\u1E5B\u0307" #26917 -end - -@testset "unicode sa#15" begin - #Tests from Unicode SA#15, "Unicode normalization forms" - #http://www.unicode.org/reports/tr15/ - - @testset "canonical equivalence" begin - let ==(a::Array{Char},b::Array{Char}) = normalize_string(string(a...), :NFC)==normalize_string(string(b...), :NFC) - ==(a,b) = Base.:(==)(a,b) - @test ['C', '̧'] == ['Ç'] - @test ['q', '̇', '̣'] == ['q', '̣', '̇'] - @test ['가'] == ['ᄀ', 'ᅡ'] - @test ['Ω'] == ['Ω'] - end - end - - @testset "compatibility equivalence" begin - let ==(a::Array{Char},b::Array{Char}) = normalize_string(string(a...), :NFKC)==normalize_string(string(b...), :NFKC) - ==(a,b) = Base.:(==)(a,b) - @test ['ℌ'] == ['ℍ'] == ['H'] - @test ['ﻨ'] == ['ﻧ'] == ['ﻦ'] == ['ﻥ'] - @test ['①'] == ['1'] - @test ['カ'] == ['カ'] - @test ['︷'] == ['{'] - @test ['⁹'] == ['₉'] - @test ['㌀'] == ['ア', 'パ', 'ー', 'ト'] - @test ['¼'] == ['1', '⁄', '4'] - @test ['dž'] == ['d', 'ž'] - end - end - - @testset "singletons" begin - @test normalize_string("\U212b", :NFD) == "A\U030a" - @test normalize_string("\U212b", :NFC) == "\U00c5" - @test normalize_string("\U2126", :NFC) == normalize_string("\U2126", :NFD) == "\U03a9" - end - - @testset "canonical composites" begin - @test normalize_string("\U00c5", :NFC) == "\U00c5" - @test normalize_string("\U00c5", :NFD) == "A\U030a" - @test normalize_string("\U00f4", :NFC) == "\U00f4" - @test normalize_string("\U00f4", :NFD) == "o\U0302" - end - - @testset "multiple combining marks" begin - @test normalize_string("\U1e69", :NFD) == "s\U0323\U0307" - @test normalize_string("\U1e69", :NFC) == "\U1e69" - @test normalize_string("\U1e0b\U0323", :NFD) == "d\U0323\U0307" - @test normalize_string("\U1e0b\U0323", :NFC) == "\U1e0d\U0307" - @test normalize_string("q\U0307\U0323", :NFC) == "q\U0323\U0307" - @test normalize_string("q\U0307\U0323", :NFD) == "q\U0323\U0307" - end - - @testset "compatibility composites" begin - @test normalize_string("\Ufb01", :NFD) == normalize_string("\Ufb01", :NFC) == "\Ufb01" - @test normalize_string("\Ufb01", :NFKD) == normalize_string("\Ufb01", :NFKC) == "fi" - @test normalize_string("2\U2075", :NFD) == normalize_string("2\U2075", :NFC) == "2\U2075" - @test normalize_string("2\U2075", :NFKD) == normalize_string("2\U2075", :NFKC) == "25" - @test normalize_string("\U1e9b\U0323", :NFD) == "\U017f\U0323\U0307" - @test normalize_string("\U1e9b\U0323", :NFC) == "\U1e9b\U0323" - @test normalize_string("\U1e9b\U0323", :NFKD) == "s\U0323\U0307" - @test normalize_string("\U1e9b\U0323", :NFKC) == "\U1e69" - end -end - -@testset "#5939 uft8proc character predicates" begin - alower=['a', 'd', 'j', 'y', 'z'] - ulower=['α', 'β', 'γ', 'δ', 'ф', 'я'] - for c in vcat(alower,ulower) - @test islower(c) == true - @test isupper(c) == false - @test isdigit(c) == false - @test isnumber(c) == false - end - - aupper=['A', 'D', 'J', 'Y', 'Z'] - uupper= ['Δ', 'Γ', 'Π', 'Ψ', 'Dž', 'Ж', 'Д'] - - for c in vcat(aupper,uupper) - @test islower(c) == false - @test isupper(c) == true - @test isdigit(c) == false - @test isnumber(c) == false - end - - nocase=['א','ﺵ'] - alphas=vcat(alower,ulower,aupper,uupper,nocase) - - for c in alphas - @test isalpha(c) == true - @test isnumber(c) == false - end - - anumber=['0', '1', '5', '9'] - unumber=['٣', '٥', '٨', '¹', 'ⅳ' ] - - for c in anumber - @test isdigit(c) == true - @test isnumber(c) == true - end - for c in unumber - @test isdigit(c) == false - @test isnumber(c) == true - end - - alnums=vcat(alphas,anumber,unumber) - for c in alnums - @test isalnum(c) == true - @test ispunct(c) == false - end - - asymbol = ['(',')', '~', '$' ] - usymbol = ['∪', '∩', '⊂', '⊃', '√', '€', '¥', '↰', '△', '§'] - - apunct =['.',',',';',':','&'] - upunct =['‡', '؟', '჻' ] - - for c in vcat(apunct,upunct) - @test ispunct(c) == true - @test isalnum(c) == false - end - - for c in vcat(alnums,asymbol,usymbol,apunct,upunct) - @test isprint(c) == true - @test isgraph(c) == true - @test isspace(c) == false - @test iscntrl(c) == false - end - - NBSP = Char(0x0000A0) - ENSPACE = Char(0x002002) - EMSPACE = Char(0x002003) - THINSPACE = Char(0x002009) - ZWSPACE = Char(0x002060) - - uspace = [ENSPACE, EMSPACE, THINSPACE] - aspace = [' '] - acntrl_space = ['\t', '\n', '\v', '\f', '\r'] - for c in vcat(aspace,uspace) - @test isspace(c) == true - @test isprint(c) == true - @test isgraph(c) == false - end - - for c in vcat(acntrl_space) - @test isspace(c) == true - @test isprint(c) == false - @test isgraph(c) == false - end - - @test isspace(ZWSPACE) == false # zero-width space - - acontrol = [ Char(0x001c), Char(0x001d), Char(0x001e), Char(0x001f)] - latincontrol = [ Char(0x0080), Char(0x0085) ] - ucontrol = [ Char(0x200E), Char(0x202E) ] - - for c in vcat(acontrol, acntrl_space, latincontrol) - @test iscntrl(c) == true - @test isalnum(c) == false - @test isprint(c) == false - @test isgraph(c) == false - end - - for c in ucontrol #non-latin1 controls - if c!=Char(0x0085) - @test iscntrl(c) == false - @test isspace(c) == false - @test isalnum(c) == false - @test isprint(c) == false - @test isgraph(c) == false - end - end - - @test all(isspace," \t \n \r ") - @test !all(isgraph," \t \n \r ") - @test !all(isprint," \t \n \r ") - @test !all(isalpha," \t \n \r ") - @test !all(isnumber," \t \n \r ") - @test !all(ispunct," \t \n \r ") - - @test !all(isspace,"ΣβΣβ") - @test all(isalpha,"ΣβΣβ") - @test all(isgraph,"ΣβΣβ") - @test all(isprint,"ΣβΣβ") - @test !all(isupper,"ΣβΣβ") - @test !all(islower,"ΣβΣβ") - @test !all(isnumber,"ΣβΣβ") - @test !all(iscntrl,"ΣβΣβ") - @test !all(ispunct,"ΣβΣβ") - - @test all(isnumber,"23435") - @test all(isdigit,"23435") - @test all(isalnum,"23435") - @test !all(isalpha,"23435") - @test all(iscntrl,string(Char(0x0080))) - @test all(ispunct, "‡؟჻") - - @test isxdigit('0') - @test isxdigit('a') - @test !isxdigit('x') - @test !isxdigit('g') -end - -@testset "utf8proc" begin - # check utf8proc handling of CN category constants - let c_ll = 'β', c_cn = '\u038B' - @test Base.UTF8proc.category_code(c_ll) == Base.UTF8proc.UTF8PROC_CATEGORY_LL - # check codepoint with category code CN - @test Base.UTF8proc.category_code(c_cn) == Base.UTF8proc.UTF8PROC_CATEGORY_CN - end -end - -@testset "graphemes" begin - let grphtest = (("b\u0300lahβlahb\u0302láh", ["b\u0300","l","a","h", - "β","l","a","h", - "b\u0302","l","á","h"]), - ("", String[]), - ("x\u0302", ["x\u0302"]), - ("\U1d4c1\u0302", ["\U1d4c1\u0302"]), - ("\U1d4c1\u0302\U1d4c1\u0300", ["\U1d4c1\u0302", - "\U1d4c1\u0300"]), - ("x",["x"]), - ("abc",["a","b","c"])) - for T in (String,GenericString) - for nf in (:NFC, :NFD) - for (s, g) in grphtest - s_ = T(normalize_string(s, nf)) - g_ = map(s -> normalize_string(s, nf), g) - # #9261 - if length(s_) > 0 - @test typeof(first(graphemes(s_))) == SubString{typeof(s_)} - end - grph = collect(graphemes(s_)) - @test eltype(grph) == SubString{typeof(s_)} - @test grph == g_ - @test length(graphemes(s_)) == length(grph) - end - S = [T(normalize_string(s)) for (s,g) in grphtest] - G = map(graphemes, S) - @test map(graphemes, sort!(S)) == sort!(G) - end - end - end -end - -@testset "#3721, #6939 up-to-date character widths" begin - @test charwidth('\U1f355') == 2 - @test strwidth("\U1f355") == 2 - @test strwidth(GenericString("\U1f355")) == 2 - @test strwidth("\U1f355\u0302") == 2 - @test strwidth(GenericString("\U1f355\u0302")) == 2 -end - -@testset "#10958 handling of embedded NUL chars" begin - @test length("\0w") == length("\0α") == 2 - @test strwidth("\0w") == strwidth("\0α") == 1 - @test normalize_string("\0W", casefold=true) == "\0w" -end - -@testset "ut8proc_map with GenericString" begin - @test normalize_string(GenericString("\u006e\u0303"), :NFC) == "\u00f1" -end - -@testset "normalize_string keywords" begin - @test_throws ArgumentError normalize_string("\u006e\u0303", compose=false, compat=true) - @test_throws ArgumentError normalize_string("\u006e\u0303", compose=false, stripmark=true) -end - -@testset "fastplus" begin - @test lowercase('A') == 'a' - @test uppercase('a') == 'A' - - @test is_assigned_char('A') -end - -@testset "isspace" begin - @test isspace(' ') - @test isspace('\t') - @test isspace('\r') - @test isspace('\u85') - @test isspace('\ua0') - @test !isspace('\ufffd') - @test !isspace('\U10ffff') -end - -@testset "grapheme iterators" begin - let str = ascii("This is a test") - g = graphemes(str) - h = hash(str) - @test hash(g) == h - @test convert(GenericString, g) == str - @test repr(g) == "length-14 GraphemeIterator{String} for \"$str\"" - end -end - -@testset "#22693: substring graphemes" begin - g = graphemes(SubString("123α56789", 1, 6)) - @test eltype(g) == SubString{String} - @test collect(g) == ["1","2","3","α","5"] -end diff --git a/julia-0.6.3/share/julia/test/util/segfault.jl b/julia-0.6.3/share/julia/test/util/segfault.jl deleted file mode 100644 index fef3908..0000000 --- a/julia-0.6.3/share/julia/test/util/segfault.jl +++ /dev/null @@ -1,3 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -unsafe_load(convert(Ptr{UInt8},C_NULL)) diff --git a/julia-0.6.3/share/julia/test/util/throw_error_exception.jl b/julia-0.6.3/share/julia/test/util/throw_error_exception.jl deleted file mode 100644 index d0acea8..0000000 --- a/julia-0.6.3/share/julia/test/util/throw_error_exception.jl +++ /dev/null @@ -1,3 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -error("This purposefully dies") diff --git a/julia-0.6.3/share/julia/test/vecelement.jl b/julia-0.6.3/share/julia/test/vecelement.jl deleted file mode 100644 index e9a5e42..0000000 --- a/julia-0.6.3/share/julia/test/vecelement.jl +++ /dev/null @@ -1,121 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -make_value{T<:Integer}(::Type{T}, i::Integer) = 3*i%T -make_value{T<:AbstractFloat}(::Type{T},i::Integer) = T(3*i) - -Vec{N,T} = NTuple{N,Base.VecElement{T}} - -# Crash report for #15244 motivated this test. -@generated function thrice_iota{N,T}(::Type{Vec{N,T}}) - :(tuple($([:(Base.VecElement(make_value($T,$i))) for i in 1:N]...))) -end - -function call_iota(n::Integer,t::DataType) - x = thrice_iota(Vec{n,t}) - @test x[1].value === make_value(t,1) - @test x[n].value === make_value(t,n) -end - -# Try various tuple lengths and element types -for i=1:20 - for t in [Bool, Int8, Int16, Int32, Int64, Float32, Float64] - call_iota(i,t) - end -end - -# Try various large tuple lengths and element types #20961 -for i in (34, 36, 48, 64, 72, 80, 96) - for t in [Bool, Int8, Int16, Int32, Int64, Float32, Float64] - call_iota(i,t) - end -end - -# Another crash report for #15244 motivated this test. -struct Bunch{N,T} - elts::NTuple{N,Base.VecElement{T}} -end - -unpeel(x) = x.elts[1].value - -@test unpeel(Bunch{2,Float64}((Base.VecElement(5.0), - Base.VecElement(4.0)))) === 5.0 - -rewrap(x) = VecElement(x.elts[1].value+0) -b = Bunch((VecElement(1.0), VecElement(2.0))) - -@test rewrap(b)===VecElement(1.0) - -struct Herd{N,T} - elts::NTuple{N,Base.VecElement{T}} - Herd{N,T}(elts::NTuple{N,T}) where {N,T} = new(ntuple(i->Base.VecElement{T}(elts[i]), N)) -end - -function check{N,T}(x::Herd{N,T}) - for i=1:N - @test x.elts[i].value === N*N+i-1 - end -end - -check(Herd{1,Int}((1,))) -check(Herd{2,Int}((4,5))) -check(Herd{4,Int}((16,17,18,19))) - -struct Gr{N, T} - u::T - v::Bunch{N,T} - w::T -end - -a = Vector{Gr{2,Float64}}(2) -a[2] = Gr(1.0, Bunch((VecElement(2.0), VecElement(3.0))), 4.0) -a[1] = Gr(5.0, Bunch((VecElement(6.0), VecElement(7.0))), 8.0) -@test a[2] == Gr(1.0, Bunch((VecElement(2.0), VecElement(3.0))), 4.0) - -@test isa(VecElement((1,2)), VecElement{Tuple{Int,Int}}) - -# The following test mimic SIMD.jl -const _llvmtypes = Dict{DataType, String}( - Float64 => "double", - Float32 => "float", - Int32 => "i32", - Int64 => "i64" -) - -@generated function vecadd(x::Vec{N, T}, y::Vec{N, T}) where {N, T} - llvmT = _llvmtypes[T] - func = T <: AbstractFloat ? "fadd" : "add" - exp = """ - %3 = $(func) <$(N) x $(llvmT)> %0, %1 - ret <$(N) x $(llvmT)> %3 - """ - return quote - Base.@_inline_meta - Base.llvmcall($exp, Vec{$N, $T}, Tuple{Vec{$N, $T}, Vec{$N, $T}}, x, y) - end -end - -function f20961(x::Vector{Vec{N, T}}, y::Vector{Vec{N, T}}) where{N, T} - @inbounds begin - a = x[1] - b = y[1] - return vecadd(a, b) - end -end - -# Test various SIMD Vectors with known good sizes -for T in (Float64, Float32, Int64, Int32) - for N in 1:36 - # For some vectortypes Julia emits llvm arrays instead of vectors - if N % 7 == 0 || N % 11 == 0 || N % 13 == 0 || N % 15 == 0 || - N % 19 == 0 || N % 23 == 0 || N % 25 == 0 || N % 27 == 0 || - N % 29 == 0 || N % 31 == 0 - continue - end - a = ntuple(i->VecElement(T(i)), N) - result = ntuple(i-> VecElement(T(i+i)), N) - b = vecadd(a, a) - @test b == result - b = f20961([a], [a]) - @test b == result - end -end diff --git a/julia-0.6.3/share/julia/test/version.jl b/julia-0.6.3/share/julia/test/version.jl deleted file mode 100644 index 5620d66..0000000 --- a/julia-0.6.3/share/julia/test/version.jl +++ /dev/null @@ -1,278 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -# parsing tests -@test v"2" == VersionNumber(2) -@test v"3.2" == VersionNumber(3, 2) -@test v"4.3.2" == VersionNumber(4, 3, 2) - -@test v"2-" == VersionNumber(2, 0, 0, ("",), ()) -@test v"3.2-" == VersionNumber(3, 2, 0, ("",), ()) -@test v"4.3.2-" == VersionNumber(4, 3, 2, ("",), ()) - -@test v"2-1" == VersionNumber(2, 0, 0, (1,), ()) -@test v"3.2-1" == VersionNumber(3, 2, 0, (1,), ()) -@test v"4.3.2-1" == VersionNumber(4, 3, 2, (1,), ()) - -@test v"2-a" == VersionNumber(2, 0, 0, ("a",), ()) == v"2a" -@test v"3.2-a" == VersionNumber(3, 2, 0, ("a",), ()) == v"3.2a" -@test v"4.3.2-a" == VersionNumber(4, 3, 2, ("a",), ()) == v"4.3.2a" - -@test v"2-a1" == VersionNumber(2, 0, 0, ("a1",), ()) == v"2a1" -@test v"3.2-a1" == VersionNumber(3, 2, 0, ("a1",), ()) == v"3.2a1" -@test v"4.3.2-a1" == VersionNumber(4, 3, 2, ("a1",), ()) == v"4.3.2a1" - -@test v"2-1a" == VersionNumber(2, 0, 0, ("1a",), ()) -@test v"3.2-1a" == VersionNumber(3, 2, 0, ("1a",), ()) -@test v"4.3.2-1a" == VersionNumber(4, 3, 2, ("1a",), ()) - -@test v"2-a.1" == VersionNumber(2, 0, 0, ("a", 1), ()) == v"2a.1" -@test v"3.2-a.1" == VersionNumber(3, 2, 0, ("a", 1), ()) == v"3.2a.1" -@test v"4.3.2-a.1" == VersionNumber(4, 3, 2, ("a", 1), ()) == v"4.3.2a.1" - -@test v"2-1.a" == VersionNumber(2, 0, 0, (1, "a"), ()) -@test v"3.2-1.a" == VersionNumber(3, 2, 0, (1, "a"), ()) -@test v"4.3.2-1.a" == VersionNumber(4, 3, 2, (1, "a"), ()) - -@test v"2+" == VersionNumber(2, 0, 0, (), ("",)) -@test v"3.2+" == VersionNumber(3, 2, 0, (), ("",)) -@test v"4.3.2+" == VersionNumber(4, 3, 2, (), ("",)) - -@test v"2+1" == VersionNumber(2, 0, 0, (), (1,)) -@test v"3.2+1" == VersionNumber(3, 2, 0, (), (1,)) -@test v"4.3.2+1" == VersionNumber(4, 3, 2, (), (1,)) - -@test v"2+a" == VersionNumber(2, 0, 0, (), ("a",)) -@test v"3.2+a" == VersionNumber(3, 2, 0, (), ("a",)) -@test v"4.3.2+a" == VersionNumber(4, 3, 2, (), ("a",)) - -@test v"2+a1" == VersionNumber(2, 0, 0, (), ("a1",)) -@test v"3.2+a1" == VersionNumber(3, 2, 0, (), ("a1",)) -@test v"4.3.2+a1" == VersionNumber(4, 3, 2, (), ("a1",)) - -@test v"2+1a" == VersionNumber(2, 0, 0, (), ("1a",)) -@test v"3.2+1a" == VersionNumber(3, 2, 0, (), ("1a",)) -@test v"4.3.2+1a" == VersionNumber(4, 3, 2, (), ("1a",)) - -@test v"2+a.1" == VersionNumber(2, 0, 0, (), ("a", 1)) -@test v"3.2+a.1" == VersionNumber(3, 2, 0, (), ("a", 1)) -@test v"4.3.2+a.1" == VersionNumber(4, 3, 2, (), ("a", 1)) - -@test v"2+1.a" == VersionNumber(2, 0, 0, (), (1, "a")) -@test v"3.2+1.a" == VersionNumber(3, 2, 0, (), (1, "a")) -@test v"4.3.2+1.a" == VersionNumber(4, 3, 2, (), (1, "a")) - -# ArgumentErrors in constructor -@test_throws ArgumentError VersionNumber(4, 3, 2, ("nonalphanumeric!",), ()) -@test_throws ArgumentError VersionNumber(4, 3, 2, ("nonalphanumeric!", 1), ()) -@test_throws ArgumentError VersionNumber(4, 3, 2, (1, "nonalphanumeric!"), ()) - -@test_throws ArgumentError VersionNumber(4, 3, 2, ("", 1), ()) -@test_throws ArgumentError VersionNumber(4, 3, 2, (1, ""), ()) -@test_throws ArgumentError VersionNumber(4, 3, 2, ("",), ("",)) -@test_throws ArgumentError VersionNumber(4, 3, 2, ("",), ("nonempty", 1)) - -@test_throws ArgumentError VersionNumber(4, 3, 2, (), ("nonalphanumeric!",)) -@test_throws ArgumentError VersionNumber(4, 3, 2, (), ("nonalphanumeric!", 1)) -@test_throws ArgumentError VersionNumber(4, 3, 2, (), (1, "nonalphanumeric!")) - -@test_throws ArgumentError VersionNumber(4, 3, 2, (), ("", 1)) - -# show -io = IOBuffer() -show(io,v"4.3.2+1.a") -@test length(String(take!(io))) == 12 - -# conversion from Int -@test convert(VersionNumber, 2) == v"2.0.0" - -# conversion from Tuple -@test convert(VersionNumber, (2,)) == v"2.0.0" -@test convert(VersionNumber, (3, 2)) == v"3.2.0" - -# conversion from AbstractString -@test convert(VersionNumber, "4.3.2+1.a") == v"4.3.2+1.a" - -# typemin and typemax -@test typemin(VersionNumber) == v"0-" -@test typemax(VersionNumber) == - VersionNumber(typemax(Int), typemax(Int), typemax(Int), (), ("",)) - -# issupbuild -import Base.issupbuild -@test issupbuild(v"4.3.2+") -@test ~issupbuild(v"4.3.2") -@test ~issupbuild(v"4.3.2-") -@test ~issupbuild(v"4.3.2-a") -@test ~issupbuild(v"4.3.2-a1") -@test ~issupbuild(v"4.3.2-1") -@test ~issupbuild(v"4.3.2-a.1") -@test ~issupbuild(v"4.3.2-1a") -@test ~issupbuild(v"4.3.2+a") -@test ~issupbuild(v"4.3.2+a1") -@test ~issupbuild(v"4.3.2+1") -@test ~issupbuild(v"4.3.2+a.1") -@test ~issupbuild(v"4.3.2+1a") - -# basic comparison -VersionNumber(2, 3, 1) == VersionNumber(Int8(2), UInt32(3), Int32(1)) == v"2.3.1" -@test v"2.3.0" < v"2.3.1" < v"2.4.8" < v"3.7.2" -@test v"0.6.0-" < v"0.6.0-dev" < v"0.6.0-dev.123" < v"0.6.0-dev.unknown" < v"0.6.0-pre" < v"0.6.0" - -#lowerbound and upperbound -import Base: lowerbound, upperbound -@test lowerbound(v"4.3.2") == v"4.3.2-" -@test lowerbound(v"4.3.2-") == v"4.3.2-" -@test lowerbound(v"4.3.2+") == v"4.3.2-" -@test upperbound(v"4.3.2") == v"4.3.2+" -@test upperbound(v"4.3.2-") == v"4.3.2+" -@test upperbound(v"4.3.2+") == v"4.3.2+" - -# advanced comparison & manipulation -import Base: thispatch, thisminor, thismajor, - nextpatch, nextminor, nextmajor, check_new_version -@test v"1.2.3" == thispatch(v"1.2.3-") -@test v"1.2.3" == thispatch(v"1.2.3-pre") -@test v"1.2.3" == thispatch(v"1.2.3") -@test v"1.2.3" == thispatch(v"1.2.3+post") -@test v"1.2.3" == thispatch(v"1.2.3+") - -@test v"1.2" == thisminor(v"1.2.3-") -@test v"1.2" == thisminor(v"1.2.3-pre") -@test v"1.2" == thisminor(v"1.2.3") -@test v"1.2" == thisminor(v"1.2.3+post") -@test v"1.2" == thisminor(v"1.2.3+") - -@test v"1" == thismajor(v"1.2.3-") -@test v"1" == thismajor(v"1.2.3-pre") -@test v"1" == thismajor(v"1.2.3") -@test v"1" == thismajor(v"1.2.3+post") -@test v"1" == thismajor(v"1.2.3+") - -@test v"1.2.3" == nextpatch(v"1.2.3-") -@test v"1.2.3" == nextpatch(v"1.2.3-pre") -@test v"1.2.4" == nextpatch(v"1.2.3") -@test v"1.2.4" == nextpatch(v"1.2.3+post") -@test v"1.2.4" == nextpatch(v"1.2.3+") - -@test v"1.2" == nextminor(v"1.2-") -@test v"1.2" == nextminor(v"1.2-pre") -@test v"1.3" == nextminor(v"1.2") -@test v"1.3" == nextminor(v"1.2+post") -@test v"1.3" == nextminor(v"1.2+") - -@test v"1.3" == nextminor(v"1.2.3-") -@test v"1.3" == nextminor(v"1.2.3-pre") -@test v"1.3" == nextminor(v"1.2.3") -@test v"1.3" == nextminor(v"1.2.3+post") -@test v"1.3" == nextminor(v"1.2.3+") - -@test v"1" == nextmajor(v"1-") -@test v"1" == nextmajor(v"1-pre") -@test v"2" == nextmajor(v"1") -@test v"2" == nextmajor(v"1+post") -@test v"2" == nextmajor(v"1+") - -@test v"2" == nextmajor(v"1.2-") -@test v"2" == nextmajor(v"1.2-pre") -@test v"2" == nextmajor(v"1.2") -@test v"2" == nextmajor(v"1.2+post") -@test v"2" == nextmajor(v"1.2+") - -@test v"2" == nextmajor(v"1.2.3-") -@test v"2" == nextmajor(v"1.2.3-pre") -@test v"2" == nextmajor(v"1.2.3") -@test v"2" == nextmajor(v"1.2.3+post") -@test v"2" == nextmajor(v"1.2.3+") - -for major=0:3, minor=0:3, patch=0:3 - a = VersionNumber(major,minor,patch,("",),()) - b = VersionNumber(major,minor,patch,("pre",),()) - c = VersionNumber(major,minor,patch,(),()) - d = VersionNumber(major,minor,patch,(),("post",)) - e = VersionNumber(major,minor,patch,(),("",)) - @test a < b < c < d < e - for x in [a,b,c,d,e] - @test thispatch(x) == VersionNumber(major,minor,patch) - @test thisminor(x) == VersionNumber(major,minor,0) - @test thismajor(x) == VersionNumber(major,0,0) - @test x < nextpatch(x) <= nextminor(x) <= nextmajor(x) - @test x < thispatch(x) ? nextpatch(x) == thispatch(x) : thispatch(x) < nextpatch(x) - @test x < thisminor(x) ? nextminor(x) == thisminor(x) : thisminor(x) < nextminor(x) - @test x < thismajor(x) ? nextmajor(x) == thismajor(x) : thismajor(x) < nextmajor(x) - end -end - -# check_new_version -import Base.check_new_version -@test check_new_version([v"1", v"2"], v"3") === nothing -@test_throws AssertionError check_new_version([v"2", v"1"], v"3") -@test_throws ErrorException check_new_version([v"1", v"2"], v"2") -@test check_new_version(VersionNumber[], v"0") === nothing -@test check_new_version(VersionNumber[], v"0.0.1") === nothing -@test_throws ErrorException check_new_version(VersionNumber[], v"0.0.2") -@test check_new_version(VersionNumber[], v"0.1") === nothing -@test_throws ErrorException check_new_version(VersionNumber[], v"0.2") -@test check_new_version(VersionNumber[], v"1") === nothing -@test_throws ErrorException check_new_version(VersionNumber[], v"2") -@test_throws ErrorException check_new_version(VersionNumber[v"1", v"2", v"3"], v"2") -@test_throws ErrorException check_new_version([v"1", v"2"], v"4") -@test_throws ErrorException check_new_version([v"1", v"2"], v"2-rc") -@test check_new_version([v"1", v"2"], v"2.0.1") === nothing -@test check_new_version([v"1", v"2"], v"2.1") === nothing -@test check_new_version([v"1", v"2"], v"3") === nothing - -# banner -import Base.banner -io = IOBuffer() -@test banner(io) === nothing -@test length(String(take!(io))) > 50 - -# julia_version.h version test -@test VERSION.major == ccall(:jl_ver_major, Cint, ()) -@test VERSION.minor == ccall(:jl_ver_minor, Cint, ()) -@test VERSION.patch == ccall(:jl_ver_patch, Cint, ()) - -# test construction with non-Int and non-String components -@test_throws MethodError VersionNumber() -@test VersionNumber(true) == v"1" -@test VersionNumber(true, 0x2) == v"1.2" -@test VersionNumber(true, 0x2, Int128(3)) == v"1.2.3" -@test VersionNumber(true, 0x2, Int128(3)) == v"1.2.3" -@test VersionNumber(true, 0x2, Int128(3), (GenericString("rc"), 0x1)) == v"1.2.3-rc.1" -@test VersionNumber(true, 0x2, Int128(3), (GenericString("rc"), 0x1)) == v"1.2.3-rc.1" -@test VersionNumber(true, 0x2, Int128(3), (), (GenericString("sp"), 0x2)) == v"1.2.3+sp.2" - -# VersionSet tests - -import Base.Pkg.Types: VersionInterval, VersionSet - -function chkint(a::VersionSet) - ints = a.intervals - for k = 1:length(ints) - ints[k].lower < ints[k].upper || return false - k < length(ints) && (ints[k].upper < ints[k+1].lower || return false) - end - return true -end - -const empty_versionset = VersionSet(VersionInterval[]) -@test isempty(empty_versionset) - -# VersionSet intersections and unions -@test empty_versionset ∩ empty_versionset == empty_versionset -@test empty_versionset ∪ empty_versionset == empty_versionset -for t = 1:1_000 - a = VersionSet(sort!(map(v->VersionNumber(v...), [(rand(0:8),rand(0:3)) for i = 1:rand(0:10)]))...) - b = VersionSet(sort!(map(v->VersionNumber(v...), [(rand(0:8),rand(0:3)) for i = 1:rand(0:10)]))...) - @assert chkint(a) - @assert chkint(b) - u = a ∪ b - @test chkint(u) - i = a ∩ b - @test chkint(i) - for vM = 0:9, vm = 0:5 - v = VersionNumber(vM, vm) - @test (v ∈ a || v ∈ b) ? (v ∈ u) : (v ∉ u) - @test (v ∈ a && v ∈ b) ? (v ∈ i) : (v ∉ i) - end -end diff --git a/julia-0.6.3/share/julia/test/workspace.jl b/julia-0.6.3/share/julia/test/workspace.jl deleted file mode 100644 index 44a315c..0000000 --- a/julia-0.6.3/share/julia/test/workspace.jl +++ /dev/null @@ -1,60 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -using Base.Test - -script = """ -# Issue #11948 -f(x) = x+1 -workspace() -@assert !isdefined(:f) -LastMain.f(2) - -# PR #12990 -io = IOBuffer() -show(io, Pair) -@assert String(take!(io)) == "Pair" -@assert !Base.inbase(LastMain) -""" -exename = Base.julia_cmd() -run(`$exename --startup-file=no -e $script`) - -# issue #17764 -script2 = """ -mutable struct Foo end -workspace() -mutable struct Foo end -@assert Tuple{Type{LastMain.Foo}} !== Tuple{Type{Main.Foo}} -""" -run(`$exename --startup-file=no -e $script2`) - -# Issue #22101 -mktempdir() do dir - withenv("JULIA_DEBUG_LOADING" => nothing) do - # We need to ensure that the module does a nontrivial amount of work during precompilation - write(joinpath(dir, "Test22101.jl"), """ - __precompile__() - module Test22101 - export f22101 - f22101() = collect(1:10) - f22101() - end - """) - write(joinpath(dir, "testdriver.jl"), """ - insert!(LOAD_PATH, 1, $(repr(dir))) - insert!(Base.LOAD_CACHE_PATH, 1, $(repr(dir))) - try - using Test22101 - f22101() - workspace() - using Test22101 - finally - splice!(LOAD_PATH, 1) - splice!(Base.LOAD_CACHE_PATH, 1) - end - exit(isdefined(Main, :f22101) ? 0 : 1) - """) - # Ensure that STDIO doesn't get swallowed (helps with debugging) - cmd = `$(Base.julia_cmd()) --startup-file=no --precompiled=yes --compilecache=yes $(joinpath(dir, "testdriver.jl"))` - @test success(pipeline(cmd, stdout=STDOUT, stderr=STDERR)) - end -end diff --git a/julia-0.6.3/share/julia/test/worlds.jl b/julia-0.6.3/share/julia/test/worlds.jl deleted file mode 100644 index 13bb285..0000000 --- a/julia-0.6.3/share/julia/test/worlds.jl +++ /dev/null @@ -1,169 +0,0 @@ -# This file is a part of Julia. License is MIT: https://julialang.org/license - -# tests for accurate updating of method tables - -tls_world_age() = ccall(:jl_get_tls_world_age, UInt, ()) -world_counter() = ccall(:jl_get_world_counter, UInt, ()) -@test typemax(UInt) > world_counter() == tls_world_age() > 0 - -# test simple method replacement -begin - g265a() = f265a(0) - f265a(x::Any) = 1 - @test g265a() == 1 - @test Base.return_types(g265a, ()) == Any[Int] - @test Core.Inference.return_type(g265a, ()) == Int - - f265a(x::Any) = 2.0 - @test g265a() == 2.0 - - @test Base.return_types(g265a, ()) == Any[Float64] - @test Core.Inference.return_type(g265a, ()) == Float64 -end - -# test signature widening -begin - f265b(x::Int) = 1 - let ty = Any[1, 2.0e0] - global g265b(i::Int) = f265b(ty[i]) - end - @test g265b(1) == 1 - @test Base.return_types(g265b, (Int,)) == Any[Int] - @test Core.Inference.return_type(g265b, (Int,)) == Int - - f265b(x::Any) = 2.0 - @test g265b(1) == 1 - @test g265b(2) == 2.0 - @test Base.return_types(g265b, (Int,)) == Any[Union{Int, Float64}] - @test Core.Inference.return_type(g265b, (Int,)) == Union{Int, Float64} -end - -# test signature narrowing -begin - g265c() = f265c(0) - f265c(x::Any) = 1 - @test g265c() == 1 - @test Base.return_types(g265c, ()) == Any[Int] - @test Core.Inference.return_type(g265c, ()) == Int - - f265c(x::Int) = 2.0 - @test g265c() == 2.0 - - @test Base.return_types(g265c, ()) == Any[Float64] - @test Core.Inference.return_type(g265c, ()) == Float64 -end - -# test constructor narrowing -mutable struct A265{T} - field1::T -end -A265_() = A265(1) -@test (A265_()::A265{Int}).field1 === 1 -A265(fld::Int) = A265(Float64(fld)) -@test (A265_()::A265{Float64}).field1 === 1.0e0 - -# test constructor widening -mutable struct B265{T} - field1::T - # dummy arg is present to prevent (::Type{T}){T}(arg) from matching the test calls - B265{T}(field1::Any, dummy::Void) where T = new(field1) # prevent generation of outer ctor -end - # define some constructors -B265(x::Int, dummy::Void) = B265{Int}(x, dummy) -let ty = Any[1, 2.0e0, 3.0f0] - global B265_(i::Int) = B265(ty[i], nothing) -end - # test for correct answers -@test (B265_(1)::B265{Int}).field1 === 1 -@test_throws MethodError B265_(2) -@test_throws MethodError B265_(3) -@test Base.return_types(B265_, (Int,)) == Any[B265{Int}] -@test Core.Inference.return_type(B265_, (Int,)) == B265{Int} - - # add new constructors -B265(x::Float64, dummy::Void) = B265{Float64}(x, dummy) -B265(x::Any, dummy::Void) = B265{UInt8}(x, dummy) - - # make sure answers are updated -@test (B265_(1)::B265{Int}).field1 === 1 -@test (B265_(2)::B265{Float64}).field1 === 2.0e0 -@test (B265_(3)::B265{UInt8}).field1 === 0x03 - -@test Base.return_types(B265_, (Int,)) == Any[Union{B265{Float64}, B265{Int}, B265{UInt8}}] -@test Core.Inference.return_type(B265_, (Int,)) == Union{B265{Float64}, B265{Int}, B265{UInt8}} - - -# test oldworld call / inference -function wfunc(c1,c2) - while true - (f, args) = take!(c1) - put!(c2, f(args...)) - end -end -function put_n_take!(v...) - put!(chnls[1], v) - take!(chnls[2]) -end - -g265() = [f265(x) for x in 1:3.] -wc265 = world_counter() -f265(::Any) = 1.0 -@test wc265 + 1 == world_counter() -chnls, tasks = Base.channeled_tasks(2, wfunc) -t265 = tasks[1] - -wc265 = world_counter() -@test put_n_take!(world_counter, ()) == wc265 -@test put_n_take!(tls_world_age, ()) == wc265 -f265(::Int) = 1 -@test put_n_take!(world_counter, ()) == wc265 + 1 == world_counter() == tls_world_age() -@test put_n_take!(tls_world_age, ()) == wc265 - -@test g265() == Int[1, 1, 1] -@test Core.Inference.return_type(f265, (Any,)) == Union{Float64, Int} -@test Core.Inference.return_type(f265, (Int,)) == Int -@test Core.Inference.return_type(f265, (Float64,)) == Float64 - -@test put_n_take!(g265, ()) == Float64[1.0, 1.0, 1.0] -@test put_n_take!(Core.Inference.return_type, (f265, (Any,))) == Float64 -@test put_n_take!(Core.Inference.return_type, (f265, (Int,))) == Float64 -@test put_n_take!(Core.Inference.return_type, (f265, (Float64,))) == Float64 -@test put_n_take!(Core.Inference.return_type, (f265, (Float64,))) == Float64 - -# test that reflection ignores worlds -@test Base.return_types(f265, (Any,)) == Any[Int, Float64] -@test put_n_take!(Base.return_types, (f265, (Any,))) == Any[Int, Float64] - -# test for method errors -h265() = true -loc_h265 = "$(Base.source_path()):$(@__LINE__ - 1)" -@test h265() -@test_throws MethodError put_n_take!(h265, ()) -@test_throws MethodError wait(t265) -@test istaskdone(t265) -let ex = t265.exception - @test ex.f == h265 - @test ex.args == () - @test ex.world == wc265 - str = sprint(showerror, ex) - wc = world_counter() - cmps = """ - MethodError: no method matching h265() - The applicable method may be too new: running in world age $wc265, while current world is $wc.""" - @test startswith(str, cmps) - cmps = "\n h265() at $loc_h265 (method too new to be called from this world context.)" - @test contains(str, cmps) -end - -# test for generated function correctness -# and min/max world computation validity of cache_method -f_gen265(x) = 1 -@generated g_gen265(x) = f_gen265(x) -@generated h_gen265(x) = :(f_gen265(x)) -f_gen265(x::Int) = 2 -f_gen265(x::Type{Int}) = 3 -@generated g_gen265b(x) = f_gen265(x) -@test h_gen265(0) == 2 -@test g_gen265(0) == 1 -@test f_gen265(Int) == 3 -@test g_gen265b(0) == 3 diff --git a/julia-0.6.3/share/man/man1/julia.1 b/julia-0.6.3/share/man/man1/julia.1 deleted file mode 100644 index cc77d36..0000000 --- a/julia-0.6.3/share/man/man1/julia.1 +++ /dev/null @@ -1,203 +0,0 @@ -.\" To get a preview of the man page as it will actually be displayed, run -.\" -.\" > nroff -man julia.1 | less -.\" -.\" at the terminal. -.\" -.\" Suggestions and improvements very much appreciated! -.\" Nothing is too large or too small. -.\" This man page was largely taken from pre-existing sources of documentation. -.\" This is documented by comments in the man page's source. -.\" -.\" # TODOs: -.\" 1. Simple, hopefully portable way to get the man page on everyone's manpath. -.\" (The whole point was to be able to simply `man julia`!) -.\" -.\" Possible sections to add to man page: -.\" - licensing -.\" - internet resources and/or documentation -.\" - environment -.\" - see also -.\" - diagnostics -.\" - notes - -.TH JULIA 1 2013-12-10 Julia "Julia Programmers' Reference Guide" - -.\" from the front page of https://julialang.org/ -.SH NAME -julia - high-level, high-performance dynamic programming language for technical computing - -.SH SYNOPSIS -julia [option] [program] [args..] - -.\" Taken almost verbatim from the front page of https://julialang.org/ -.SH DESCRIPTION -Julia is a high-level, high-performance dynamic programming language -for technical computing, with syntax that is familiar to users -of other technical computing environments. -It provides a sophisticated compiler, distributed parallel execution, -numerical accuracy, and an extensive mathematical function library. -The library, largely written in Julia itself, also integrates mature, -best-of-breed C and Fortran libraries for linear algebra, -random number generation, signal processing, and string processing. -In addition, the Julia developer community is contributing a number of -external packages through Julia's built-in package manager at a rapid pace. -Julia programs are organized around multiple dispatch; -by defining functions and overloading them for different combinations -of argument types, which can also be user-defined. -For a more in-depth discussion of the rationale and advantages of Julia -over other systems, please see the online manual: -https://docs.julialang.org/en/latest/manual/ - -If a Julia source file is given as a \fIprogram\fP (optionally followed by - arguments in \fIargs\fP) Julia will execute the program and exit. - -.\" This section was taken nearly verbatim from the output of `julia --help` -.SH "COMMAND-LINE OPTIONS" - -.TP --v, --version -Display version information - -.TP --h, --help -Print help message - -.TP --J, --sysimage <file> -Start up with the given system image file - -.TP ---precompiled={yes|no} -Use precompiled code from system image if available - -.TP --H, --home <dir> -Set location of julia executable - -.TP ---startup-file={yes|no} -Load ~/.juliarc.jl - -.TP ---handle-signals={yes|no} -Enable or disable Julia's default signal handlers - -.TP --e, --eval <expr> -Evaluate <expr> - -.TP --E, --print <expr> -Evaluate and show <expr> - -.TP --L, --load <file> -Load <file> immediately on all processors - -.TP --p, --procs <n> -Run n local processes - -.TP ---machinefile <file> -Run processes on hosts listed in <file> - -.TP --i -Interactive mode; REPL runs and isinteractive() is true - -.TP --q, --quiet -Quiet startup without banner - -.TP ---color={yes|no} -Enable or disable color text - -.TP ---history-file={yes|no} -Load or save history - -.TP ---compile={yes|no|all} -Enable or disable compiler, or request exhaustive compilation - -.TP --C, --cpu-target=<target> -Limit usage of cpu features up to <target> - -.TP --O, --optimize -Run time-intensive code optimizations - -.TP --O <n>, --optimize=<n> -Set the optimization level to <n> - -.TP --g -Enable generation of full debug info - -.TP --g <n> -Set the level of debug info generation to <n> - -.TP ---inline={yes|no} -Control whether inlining is permitted (overrides functions declared as @inline) - -.TP ---check-bounds={yes|no} -Emit bounds checks always or never (ignoring declarations) - -.TP ---math-mode={ieee|user} -Always use IEEE semantics for math (ignoring declarations), -or adhere to declarations in source code - -.TP ---depwarn={yes|no|error} -Enable or disable syntax and method deprecation warnings ('error' turns warnings into errors) - -.TP ---output-o <name> -Generate an object file (including system image data) - -.TP ---output-ji <name> -Generate a system image data file (.ji) - -.TP ---output-bc <name> -Generate LLVM bitcode (.bc) - -.TP ---output-incremental={yes|no} -Generate an incremental output file (rather than complete) - -.TP ---code-coverage={none|user|all}, --code-coverage -Count executions of source lines (omitting setting is equivalent to 'user') - -.TP ---track-allocation={none|user|all}, --track-allocation -Count bytes allocated by each source line - -.SH FILES -.I ~/.juliarc.jl -.RS -Per user startup file. -.RE - -.I /etc/julia/juliarc.jl -.RS -System-wide startup file. -.RE - -.SH BUGS -Please report any bugs using the GitHub issue tracker: -https://github.com/julialang/julia/issues?state=open - -.SH AUTHORS -Contributors: https://github.com/JuliaLang/julia/graphs/contributors